@tinkerlandai/longplay-sdk 0.10.53 → 0.10.54

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 (48) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/chunk-66TY4EFN.js +1 -0
  3. package/dist/chunk-AEQUKR4O.js +1 -0
  4. package/dist/chunk-C4NXQMSO.js +1 -0
  5. package/dist/chunk-JCI5PGY3.js +1 -0
  6. package/dist/{chunk-JCOSQTFG.js → chunk-LBDLWHBY.js} +1 -1
  7. package/dist/{chunk-VSARBT7T.js → chunk-LFMAFY3P.js} +1 -1
  8. package/dist/chunk-MRL7XUBV.js +1 -0
  9. package/dist/{chunk-WTPS62L7.js → chunk-MZRDAMFQ.js} +1 -1
  10. package/dist/chunk-OJDO7546.js +1 -0
  11. package/dist/{chunk-RYZBE5FQ.js → chunk-PB34FLPJ.js} +1 -1
  12. package/dist/{chunk-PCSCRMPD.js → chunk-PPXVRQAG.js} +1 -1
  13. package/dist/{chunk-PSAAZJZA.js → chunk-R2L227PQ.js} +1 -1
  14. package/dist/{chunk-3CKAOP4L.js → chunk-S2MSRPR2.js} +1 -1
  15. package/dist/{chunk-QRBZYLE4.js → chunk-SK5JZ7HA.js} +2 -2
  16. package/dist/{chunk-DX33T5JM.js → chunk-TS26DZNO.js} +1 -1
  17. package/dist/chunk-ZEU56NVY.js +1 -0
  18. package/dist/{chunk-UYKPVE5Y.js → chunk-ZQY7OYHM.js} +1 -1
  19. package/dist/{content-NZHXCUXY.js → content-A4SPKH7N.js} +1 -1
  20. package/dist/funnel-host-purchase-V2TIWGCQ.js +1 -0
  21. package/dist/funnel-host-recovery-paywall-DWKTPDLY.js +1 -0
  22. package/dist/{funnel-local-client-bKBuUwkG.d.ts → funnel-local-client-Fxsyl7rh.d.ts} +75 -75
  23. package/dist/{funnel-paywall-prerender-I5IMXZ3D.js → funnel-paywall-prerender-DD7LQXDJ.js} +1 -1
  24. package/dist/{funnel-process-client-ABZkQ8sZ.d.ts → funnel-process-client-D9saqPse.d.ts} +1 -1
  25. package/dist/funnel-runtime-host-JG3OAYZ6.js +1 -0
  26. package/dist/index.d.ts +88 -82
  27. package/dist/index.js +1 -1
  28. package/dist/native-shell.js +1 -1
  29. package/dist/openrouter.js +1 -1
  30. package/dist/page.js +1 -1
  31. package/dist/{paywall-4YXZP2TO.js → paywall-NM4HMYMK.js} +1 -1
  32. package/dist/{paywall-content-IDET7P7K.js → paywall-content-T2FGNRBR.js} +1 -1
  33. package/dist/{paywall-session-6R4UYJJF.js → paywall-session-BAUWSWWR.js} +1 -1
  34. package/dist/react-native.d.ts +4 -4
  35. package/dist/react-native.js +1 -1
  36. package/dist/server.d.ts +2 -2
  37. package/dist/server.js +1 -1
  38. package/dist/visual.js +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-3JF2REGQ.js +0 -1
  41. package/dist/chunk-45XVSI2M.js +0 -1
  42. package/dist/chunk-DXQJ2JQZ.js +0 -1
  43. package/dist/chunk-SM44S6BK.js +0 -1
  44. package/dist/chunk-Y2B7RDRB.js +0 -1
  45. package/dist/funnel-host-purchase-CVJC5MYJ.js +0 -1
  46. package/dist/funnel-host-recovery-paywall-Q56M2FYK.js +0 -1
  47. package/dist/funnel-runtime-host-OVSFAGO5.js +0 -1
  48. /package/dist/{chunk-QRBZYLE4.js.LEGAL.txt → chunk-SK5JZ7HA.js.LEGAL.txt} +0 -0
@@ -1 +1 @@
1
- import"./chunk-IN32NWRI.js";import"./chunk-ANJPFGFN.js";import"./chunk-DX33T5JM.js";import"./chunk-L64BS65O.js";import{a as i}from"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-JCOSQTFG.js";import{b as A}from"./chunk-5YBTU4KS.js";import"./chunk-WOT6VMZA.js";var c=A.number().int().min(0).max(1e9);function R(e,o){let a=c.parse(e.promptTokens),p=c.parse(e.completionTokens),s=c.parse(e.promptTokensDetails?.cachedTokens??0),t=c.parse(e.promptTokensDetails?.cacheWriteTokens??0),r=c.parse(e.promptTokensDetails?.audioTokens??0),l=c.parse(e.completionTokensDetails?.audioTokens??0),n=c.parse(e.completionTokensDetails?.reasoningTokens??0);if(c.parse(e.totalTokens)!==a+p||s+t+r>a||n+l>p||(e.promptTokensDetails?.videoTokens??0)>0)throw new i("AI_USAGE_UNAVAILABLE","Token pools must conserve usage; video needs an explicit token mapper");return{input:a-s-t-r,output:p-l-(o==="separate"?n:0),cache_read:s,cache_write:t,input_audio:r,output_audio:l,reasoning:o==="separate"?n:0}}function I(e){if(!Number.isFinite(e)||e<0)throw new i("AI_USAGE_UNAVAILABLE","Provider cost must be a nonnegative USD amount");let o=String(e),a=o.includes("e")?e.toFixed(18).replace(/0+$/,"").replace(/\.$/,""):o;if(!/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/.test(a)||Number(a)!==e)throw new i("AI_USAGE_UNAVAILABLE","Provider cost exceeds the supported precision");return a}async function f(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning)||!e.modelId||!e.generationId)throw new i("INVALID_REQUEST","Actual model, generation ID and reasoning pricing are required");let o={context:e.context,generationId:e.generationId,modelId:`openrouter/${e.modelId}`,usage:e.usage,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let a=e.mapTokens?e.mapTokens(e.usage):R(e.usage,e.reasoning),p=e.usage.cost==null?void 0:I(e.usage.cost),s=e.quote??await e.pricing.quoteTokens({modelId:o.modelId,tokens:a});if(s.pricing.modelId!==o.modelId||Object.keys(a).some(l=>a[l]!==s.tokens[l]))throw new i("INVALID_REQUEST","Saved quote must match the provider model and token pools");await e.persist({...o,tokens:a,quote:s,phase:"quoted"});let t=await e.pricing.trackTokens(e.client,{...e.context,quote:s,providerCostUsd:p,generationId:e.generationId});if(!t.receipt.accepted)throw new i("AI_BALANCE_REJECTED","OpenRouter usage was saved but the balance request was rejected");let r={...o,tokens:a,quote:s,receipt:t,phase:"settled"};return await e.persist(r),r}function T(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning))throw new i("INVALID_REQUEST","Reasoning pricing is required");let o=e.openRouter.chat;async function a(t){if(!t.usage||!t.modelId||!t.generationId)throw new i("AI_USAGE_UNAVAILABLE","OpenRouter did not return final usage and the actual model");await f({...e,context:t.context,generationId:t.generationId,modelId:t.modelId.slice(11),usage:t.usage})}let p=async(t,r)=>{let n={context:await e.context(),generationId:null,modelId:null,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"},d;try{d=await o.send(t,r)}catch(g){throw await e.persist(n),g}if(!(d instanceof ReadableStream)){if(n={...n,generationId:d.id,modelId:d.model?`openrouter/${d.model}`:null,usage:d.usage??null},!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter omitted final accounting");return await a(n),d}let w=d.getReader(),m=!1;return new ReadableStream({async pull(g){try{let{value:u,done:k}=await w.read();if(k){if(m=!0,!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter stream ended without final accounting");await a(n),g.close();return}if(u.error)throw new i("AI_PROVIDER_ERROR",u.error.message);u.usage&&(n={...n,generationId:u.id,modelId:u.model?`openrouter/${u.model}`:null,usage:u.usage}),g.enqueue(u)}catch(u){m||(m=!0,await e.persist(n)),await w.cancel(u),g.error(u)}},async cancel(g){m||(m=!0,await e.persist(n)),await w.cancel(g)}})},s=new Proxy(o,{get(t,r){return r==="send"?p:Reflect.get(t,r,t)}});return new Proxy(e.openRouter,{get(t,r){return r==="chat"?s:Reflect.get(t,r,t)}})}export{T as createOpenRouterUsageClient,f as trackOpenRouterUsage};
1
+ import"./chunk-IN32NWRI.js";import"./chunk-ANJPFGFN.js";import"./chunk-TS26DZNO.js";import"./chunk-L64BS65O.js";import{a as i}from"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-LBDLWHBY.js";import{b as A}from"./chunk-5YBTU4KS.js";import"./chunk-WOT6VMZA.js";var c=A.number().int().min(0).max(1e9);function R(e,o){let a=c.parse(e.promptTokens),p=c.parse(e.completionTokens),s=c.parse(e.promptTokensDetails?.cachedTokens??0),t=c.parse(e.promptTokensDetails?.cacheWriteTokens??0),r=c.parse(e.promptTokensDetails?.audioTokens??0),l=c.parse(e.completionTokensDetails?.audioTokens??0),n=c.parse(e.completionTokensDetails?.reasoningTokens??0);if(c.parse(e.totalTokens)!==a+p||s+t+r>a||n+l>p||(e.promptTokensDetails?.videoTokens??0)>0)throw new i("AI_USAGE_UNAVAILABLE","Token pools must conserve usage; video needs an explicit token mapper");return{input:a-s-t-r,output:p-l-(o==="separate"?n:0),cache_read:s,cache_write:t,input_audio:r,output_audio:l,reasoning:o==="separate"?n:0}}function I(e){if(!Number.isFinite(e)||e<0)throw new i("AI_USAGE_UNAVAILABLE","Provider cost must be a nonnegative USD amount");let o=String(e),a=o.includes("e")?e.toFixed(18).replace(/0+$/,"").replace(/\.$/,""):o;if(!/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/.test(a)||Number(a)!==e)throw new i("AI_USAGE_UNAVAILABLE","Provider cost exceeds the supported precision");return a}async function f(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning)||!e.modelId||!e.generationId)throw new i("INVALID_REQUEST","Actual model, generation ID and reasoning pricing are required");let o={context:e.context,generationId:e.generationId,modelId:`openrouter/${e.modelId}`,usage:e.usage,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let a=e.mapTokens?e.mapTokens(e.usage):R(e.usage,e.reasoning),p=e.usage.cost==null?void 0:I(e.usage.cost),s=e.quote??await e.pricing.quoteTokens({modelId:o.modelId,tokens:a});if(s.pricing.modelId!==o.modelId||Object.keys(a).some(l=>a[l]!==s.tokens[l]))throw new i("INVALID_REQUEST","Saved quote must match the provider model and token pools");await e.persist({...o,tokens:a,quote:s,phase:"quoted"});let t=await e.pricing.trackTokens(e.client,{...e.context,quote:s,providerCostUsd:p,generationId:e.generationId});if(!t.receipt.accepted)throw new i("AI_BALANCE_REJECTED","OpenRouter usage was saved but the balance request was rejected");let r={...o,tokens:a,quote:s,receipt:t,phase:"settled"};return await e.persist(r),r}function T(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning))throw new i("INVALID_REQUEST","Reasoning pricing is required");let o=e.openRouter.chat;async function a(t){if(!t.usage||!t.modelId||!t.generationId)throw new i("AI_USAGE_UNAVAILABLE","OpenRouter did not return final usage and the actual model");await f({...e,context:t.context,generationId:t.generationId,modelId:t.modelId.slice(11),usage:t.usage})}let p=async(t,r)=>{let n={context:await e.context(),generationId:null,modelId:null,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"},d;try{d=await o.send(t,r)}catch(g){throw await e.persist(n),g}if(!(d instanceof ReadableStream)){if(n={...n,generationId:d.id,modelId:d.model?`openrouter/${d.model}`:null,usage:d.usage??null},!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter omitted final accounting");return await a(n),d}let w=d.getReader(),m=!1;return new ReadableStream({async pull(g){try{let{value:u,done:k}=await w.read();if(k){if(m=!0,!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter stream ended without final accounting");await a(n),g.close();return}if(u.error)throw new i("AI_PROVIDER_ERROR",u.error.message);u.usage&&(n={...n,generationId:u.id,modelId:u.model?`openrouter/${u.model}`:null,usage:u.usage}),g.enqueue(u)}catch(u){m||(m=!0,await e.persist(n)),await w.cancel(u),g.error(u)}},async cancel(g){m||(m=!0,await e.persist(n)),await w.cancel(g)}})},s=new Proxy(o,{get(t,r){return r==="send"?p:Reflect.get(t,r,t)}});return new Proxy(e.openRouter,{get(t,r){return r==="chat"?s:Reflect.get(t,r,t)}})}export{T as createOpenRouterUsageClient,f as trackOpenRouterUsage};
package/dist/page.js CHANGED
@@ -1 +1 @@
1
- import{d as o,e as r,f as e,g as f}from"./chunk-QRBZYLE4.js";import"./chunk-PSAAZJZA.js";import"./chunk-3VUPVXAV.js";import"./chunk-JCOSQTFG.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
1
+ import{d as o,e as r,f as e,g as f}from"./chunk-SK5JZ7HA.js";import"./chunk-R2L227PQ.js";import"./chunk-3VUPVXAV.js";import"./chunk-LBDLWHBY.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
@@ -1 +1 @@
1
- import{a}from"./chunk-45XVSI2M.js";import"./chunk-DXLBEXC6.js";import"./chunk-W32FI2A2.js";import"./chunk-QAGK2SLZ.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-DX33T5JM.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-JCOSQTFG.js";import"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";export{a as showPaywall};
1
+ import{a}from"./chunk-OJDO7546.js";import"./chunk-DXLBEXC6.js";import"./chunk-W32FI2A2.js";import"./chunk-QAGK2SLZ.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-TS26DZNO.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-LBDLWHBY.js";import"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";export{a as showPaywall};
@@ -1 +1 @@
1
- import{b as a}from"./chunk-VSARBT7T.js";import"./chunk-6HKQILBV.js";import"./chunk-EACC667P.js";import"./chunk-BX2MSRA4.js";import"./chunk-J4RM5GQP.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-DX33T5JM.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-3VUPVXAV.js";import"./chunk-JCOSQTFG.js";import"./chunk-5YBTU4KS.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";export{a as readPaywallContent};
1
+ import{b as a}from"./chunk-LFMAFY3P.js";import"./chunk-6HKQILBV.js";import"./chunk-EACC667P.js";import"./chunk-BX2MSRA4.js";import"./chunk-J4RM5GQP.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-TS26DZNO.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-3VUPVXAV.js";import"./chunk-LBDLWHBY.js";import"./chunk-5YBTU4KS.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";export{a as readPaywallContent};
@@ -1 +1 @@
1
- import{a}from"./chunk-UYKPVE5Y.js";import"./chunk-JXWZS4UM.js";import"./chunk-YMRWDMIL.js";import"./chunk-CAE4KIZN.js";import"./chunk-CJUODAOF.js";import"./chunk-XHZH3E4G.js";import"./chunk-VSARBT7T.js";import"./chunk-6HKQILBV.js";import"./chunk-EACC667P.js";import"./chunk-BX2MSRA4.js";import"./chunk-J4RM5GQP.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-ANJPFGFN.js";import"./chunk-DX33T5JM.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-3VUPVXAV.js";import"./chunk-JCOSQTFG.js";import"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
1
+ import{a}from"./chunk-ZQY7OYHM.js";import"./chunk-JXWZS4UM.js";import"./chunk-YMRWDMIL.js";import"./chunk-CAE4KIZN.js";import"./chunk-CJUODAOF.js";import"./chunk-XHZH3E4G.js";import"./chunk-LFMAFY3P.js";import"./chunk-6HKQILBV.js";import"./chunk-EACC667P.js";import"./chunk-BX2MSRA4.js";import"./chunk-J4RM5GQP.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-ANJPFGFN.js";import"./chunk-TS26DZNO.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-3VUPVXAV.js";import"./chunk-LBDLWHBY.js";import"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
@@ -1,7 +1,7 @@
1
- import { f as createCustomerClient, d as createFunnelClient } from './funnel-process-client-ABZkQ8sZ.js';
2
- export { F as FunnelProcessAdapter, a as FunnelProcessOptions, c as createFunnelProcess } from './funnel-process-client-ABZkQ8sZ.js';
3
- import { I as IndianaOptions, S as SessionCredentials, N as Scope, B as createFunnelRunController, x as PaywallStartInput, l as createPaywallSession } from './funnel-local-client-bKBuUwkG.js';
4
- export { F as FunnelCommandStorage, d as FunnelRunController, u as LocalFunnelClientOptions, v as LongplayError, w as PaywallPurchaseInput, f as PaywallSession, y as PushHost, z as PushJournal, A as createFeatureClient, D as createLocalFunnelClient } from './funnel-local-client-bKBuUwkG.js';
1
+ import { f as createCustomerClient, d as createFunnelClient } from './funnel-process-client-D9saqPse.js';
2
+ export { F as FunnelProcessAdapter, a as FunnelProcessOptions, c as createFunnelProcess } from './funnel-process-client-D9saqPse.js';
3
+ import { I as IndianaOptions, S as SessionCredentials, N as Scope, B as createFunnelRunController, x as PaywallStartInput, l as createPaywallSession } from './funnel-local-client-Fxsyl7rh.js';
4
+ export { F as FunnelCommandStorage, h as FunnelRunController, u as LocalFunnelClientOptions, v as LongplayError, w as PaywallPurchaseInput, P as PaywallSession, y as PushHost, z as PushJournal, A as createFeatureClient, D as createLocalFunnelClient } from './funnel-local-client-Fxsyl7rh.js';
5
5
  import { z } from 'zod';
6
6
  import { J as JsonValue } from './growth-rules-B4YYy64R.js';
7
7
  export { a as ConfigurationStorage, b as ConfigurationSyncOptions, c as createConfigurationSync } from './configuration-sync-DeWWW5za.js';
@@ -1 +1 @@
1
- import{b as S,c as E,d as T}from"./chunk-PCSCRMPD.js";import"./chunk-PVMGYRGE.js";import{a as A}from"./chunk-UYKPVE5Y.js";import{e as P}from"./chunk-JXWZS4UM.js";import"./chunk-YMRWDMIL.js";import{h as b,i as x,k as L}from"./chunk-RYZBE5FQ.js";import{E as C}from"./chunk-WTPS62L7.js";import"./chunk-73UFNVEP.js";import"./chunk-CAE4KIZN.js";import"./chunk-CJUODAOF.js";import"./chunk-XHZH3E4G.js";import"./chunk-VSARBT7T.js";import"./chunk-6HKQILBV.js";import"./chunk-EACC667P.js";import"./chunk-BX2MSRA4.js";import"./chunk-LOBZ45T3.js";import"./chunk-J4RM5GQP.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-ANJPFGFN.js";import"./chunk-DX33T5JM.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import{a as r}from"./chunk-WE55LJEN.js";import{h as R}from"./chunk-OZK47BUU.js";import"./chunk-3VUPVXAV.js";import"./chunk-JCOSQTFG.js";import"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";function k(t,d){let n,a=0,m=-1,l,i=!1,y=()=>{if(i)throw new r("CLOSED","Native host was destroyed");if(!t.nativeModule)throw new r("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return t.nativeModule},o=()=>new r("IDENTITY_CHANGED","Customer identity changed during the native operation"),h=d.subscribeIdentity(()=>{a++,m=-1;let e=a;n&&t.nativeModule&&n.then(c=>t.nativeModule.reset(c,e)).catch(()=>{})}),I=t.nativeEvents?.(e=>{!n||!t.nativeModule||typeof e?.requestId!="string"||(async()=>{let c=await n;if(e.instanceId!==c)return;if(e.kind==="credential"){let w=a,f=null;try{if(!i&&e.revision===w){let N=await d.access();!i&&a===w&&(f=N)}}finally{await t.nativeModule.provideCredential(c,e.requestId,f)}return}let s=!1,u=a;try{if(i||e.revision!==u||!t.onNativeAction)throw o();await t.onNativeAction(e.action),s=!i&&a===u}finally{await t.nativeModule.acknowledge(c,e.requestId,s)}})().catch(()=>{})});async function p(e,c={}){let s=y();if(d.snapshot()&&!t.nativeEvents)throw new r("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let u=a,w=await d.access();if(i||a!==u)throw o();if(!n){let v=s.create(JSON.stringify({baseUrl:t.baseUrl??"https://api.longplayai.com",scope:t.scope,timeout:(t.timeoutMs??15e3)/1e3,credentialEvents:!!t.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let f=await n;if(i||a!==u)throw o();if(m!==u){if(!l||l.epoch!==u){let O=(async()=>{if(await s.identify(f,JSON.stringify({revision:u,credentials:w})),i||a!==u)throw await s.reset(f,u),o();m=u})();l={epoch:u,task:O}}let v=l;try{await v.task}finally{l===v&&(l=void 0)}}let N=await s.invoke(f,e,JSON.stringify(c));if(i||a!==u)throw o();try{return JSON.parse(N)}catch{throw new r("INVALID_RESPONSE","Native host returned invalid JSON")}}async function g(e,c){let s=await p(e,c);if(!s||typeof s!="object"||Array.isArray(s)||s.status!=="complete"&&s.status!=="dismissed")throw new r("INVALID_RESPONSE","Native presentation returned an invalid result");return s}return{showFunnel(e){return g("showFunnel",{runToken:e})},showPaywall(e){return g("showPaywall",e)},showContent(e){return g("showContent",e)},purchaseSubscription(e,c){return p("purchaseSubscription",{operationId:e,accepted:c})},switchSubscription(e,c){return p("switchSubscription",{operationId:e,accepted:c})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(e){return p("manageSubscriptions",e?{productId:e}:{})},async dismiss(){a++,m=-1,n&&await y().reset(await n,a)},async destroy(){i||(i=!0,a++,h(),I?.(),n&&t.nativeModule&&await t.nativeModule.destroy(await n))}}}var M=P.trackUsage.request.shape.command,U=P.trackUsage.response;function F(t){let d=R.parse(t.scope),n=S({...t,scope:d}),a={...t,scope:d,session:n.session},m=k(t,n.session),l=0,i=!1;n.subscribeIdentity(()=>{l++});let y=()=>{if(i)throw new r("CLOSED","SDK client was destroyed");let o=n.session.peek();if(!o)throw new r("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:m,async destroy(){i||(i=!0,l++,n.destroy(),await m.destroy())},funnel(){return E({...a,customerToken:y()})},resumeFunnel(o){return y(),C({...a,runToken:o})},paywall(o){return A(a,{...o,customerToken:y()})},async trackUsage(o){if(y(),!t.usageReporter)throw new r("INVALID_REQUEST","Configure your authenticated backend usageReporter");let h=M.parse(o),I=l,p;try{p=await t.usageReporter(h)}catch(e){throw I!==l?new r("IDENTITY_CHANGED","Customer identity changed during usage reporting"):e}if(I!==l)throw new r("IDENTITY_CHANGED","Customer identity changed during usage reporting");let g=U.parse(p);if(g.scope.projectId!==d.projectId||g.scope.environment!==d.environment)throw new r("INVALID_RESPONSE","Usage response scope differs");return g}}}export{r as LongplayError,x as createConfigurationSync,b as createFeatureClient,T as createFunnelProcess,L as createLocalFunnelClient,F as createLongplayReactNative};
1
+ import{b as S,c as E,d as T}from"./chunk-PPXVRQAG.js";import"./chunk-PVMGYRGE.js";import{a as A}from"./chunk-ZQY7OYHM.js";import{e as P}from"./chunk-JXWZS4UM.js";import"./chunk-YMRWDMIL.js";import{h as b,i as x,k as L}from"./chunk-PB34FLPJ.js";import{E as C}from"./chunk-MZRDAMFQ.js";import"./chunk-73UFNVEP.js";import"./chunk-CAE4KIZN.js";import"./chunk-CJUODAOF.js";import"./chunk-XHZH3E4G.js";import"./chunk-LFMAFY3P.js";import"./chunk-6HKQILBV.js";import"./chunk-EACC667P.js";import"./chunk-BX2MSRA4.js";import"./chunk-LOBZ45T3.js";import"./chunk-J4RM5GQP.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-ANJPFGFN.js";import"./chunk-TS26DZNO.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import{a as r}from"./chunk-WE55LJEN.js";import{h as R}from"./chunk-OZK47BUU.js";import"./chunk-3VUPVXAV.js";import"./chunk-LBDLWHBY.js";import"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";function k(t,d){let n,a=0,m=-1,l,i=!1,y=()=>{if(i)throw new r("CLOSED","Native host was destroyed");if(!t.nativeModule)throw new r("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return t.nativeModule},o=()=>new r("IDENTITY_CHANGED","Customer identity changed during the native operation"),h=d.subscribeIdentity(()=>{a++,m=-1;let e=a;n&&t.nativeModule&&n.then(c=>t.nativeModule.reset(c,e)).catch(()=>{})}),I=t.nativeEvents?.(e=>{!n||!t.nativeModule||typeof e?.requestId!="string"||(async()=>{let c=await n;if(e.instanceId!==c)return;if(e.kind==="credential"){let w=a,f=null;try{if(!i&&e.revision===w){let N=await d.access();!i&&a===w&&(f=N)}}finally{await t.nativeModule.provideCredential(c,e.requestId,f)}return}let s=!1,u=a;try{if(i||e.revision!==u||!t.onNativeAction)throw o();await t.onNativeAction(e.action),s=!i&&a===u}finally{await t.nativeModule.acknowledge(c,e.requestId,s)}})().catch(()=>{})});async function p(e,c={}){let s=y();if(d.snapshot()&&!t.nativeEvents)throw new r("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let u=a,w=await d.access();if(i||a!==u)throw o();if(!n){let v=s.create(JSON.stringify({baseUrl:t.baseUrl??"https://api.longplayai.com",scope:t.scope,timeout:(t.timeoutMs??15e3)/1e3,credentialEvents:!!t.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let f=await n;if(i||a!==u)throw o();if(m!==u){if(!l||l.epoch!==u){let O=(async()=>{if(await s.identify(f,JSON.stringify({revision:u,credentials:w})),i||a!==u)throw await s.reset(f,u),o();m=u})();l={epoch:u,task:O}}let v=l;try{await v.task}finally{l===v&&(l=void 0)}}let N=await s.invoke(f,e,JSON.stringify(c));if(i||a!==u)throw o();try{return JSON.parse(N)}catch{throw new r("INVALID_RESPONSE","Native host returned invalid JSON")}}async function g(e,c){let s=await p(e,c);if(!s||typeof s!="object"||Array.isArray(s)||s.status!=="complete"&&s.status!=="dismissed")throw new r("INVALID_RESPONSE","Native presentation returned an invalid result");return s}return{showFunnel(e){return g("showFunnel",{runToken:e})},showPaywall(e){return g("showPaywall",e)},showContent(e){return g("showContent",e)},purchaseSubscription(e,c){return p("purchaseSubscription",{operationId:e,accepted:c})},switchSubscription(e,c){return p("switchSubscription",{operationId:e,accepted:c})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(e){return p("manageSubscriptions",e?{productId:e}:{})},async dismiss(){a++,m=-1,n&&await y().reset(await n,a)},async destroy(){i||(i=!0,a++,h(),I?.(),n&&t.nativeModule&&await t.nativeModule.destroy(await n))}}}var M=P.trackUsage.request.shape.command,U=P.trackUsage.response;function F(t){let d=R.parse(t.scope),n=S({...t,scope:d}),a={...t,scope:d,session:n.session},m=k(t,n.session),l=0,i=!1;n.subscribeIdentity(()=>{l++});let y=()=>{if(i)throw new r("CLOSED","SDK client was destroyed");let o=n.session.peek();if(!o)throw new r("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:m,async destroy(){i||(i=!0,l++,n.destroy(),await m.destroy())},funnel(){return E({...a,customerToken:y()})},resumeFunnel(o){return y(),C({...a,runToken:o})},paywall(o){return A(a,{...o,customerToken:y()})},async trackUsage(o){if(y(),!t.usageReporter)throw new r("INVALID_REQUEST","Configure your authenticated backend usageReporter");let h=M.parse(o),I=l,p;try{p=await t.usageReporter(h)}catch(e){throw I!==l?new r("IDENTITY_CHANGED","Customer identity changed during usage reporting"):e}if(I!==l)throw new r("IDENTITY_CHANGED","Customer identity changed during usage reporting");let g=U.parse(p);if(g.scope.projectId!==d.projectId||g.scope.environment!==d.environment)throw new r("INVALID_RESPONSE","Usage response scope differs");return g}}}export{r as LongplayError,x as createConfigurationSync,b as createFeatureClient,T as createFunnelProcess,L as createLocalFunnelClient,F as createLongplayReactNative};
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { F as FoundationApi, I as InvoiceModeParams } from './api-1Tplv-7M.js';
2
- import { X as IndianaServerOptions, v as IndianaError, Y as FunnelProcessSuppression, Z as FunnelProcessCommand, T as FunnelProcessResponse, C as CustomerSession, Q as FunnelProcessOpenInput, V as FunnelProcessMutation, x as PaywallStartInput, f as PaywallSession, n as FeatureClientOptions, R as RemoteFeatureResult } from './funnel-local-client-bKBuUwkG.js';
3
- export { m as FeatureClient, a as FunnelStartInput, L as LocalFunnelClient, u as LocalFunnelClientOptions, A as createFeatureClient, _ as createFunnelStartClient, D as createLocalFunnelClient } from './funnel-local-client-bKBuUwkG.js';
2
+ import { X as IndianaServerOptions, v as IndianaError, Y as FunnelProcessSuppression, Z as FunnelProcessCommand, T as FunnelProcessResponse, C as CustomerSession, Q as FunnelProcessOpenInput, V as FunnelProcessMutation, x as PaywallStartInput, P as PaywallSession, n as FeatureClientOptions, R as RemoteFeatureResult } from './funnel-local-client-Fxsyl7rh.js';
3
+ export { m as FeatureClient, d as FunnelStartInput, L as LocalFunnelClient, u as LocalFunnelClientOptions, A as createFeatureClient, _ as createFunnelStartClient, D as createLocalFunnelClient } from './funnel-local-client-Fxsyl7rh.js';
4
4
  import * as zod from 'zod';
5
5
  import { z } from 'zod';
6
6
  import { S as StackNode } from './screen-D2bUmJ4M.js';
package/dist/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as pn}from"./chunk-3JF2REGQ.js";import{a as I}from"./chunk-36VNAOG6.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-IN32NWRI.js";import{a as xt}from"./chunk-UYKPVE5Y.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-JXWZS4UM.js";import"./chunk-YMRWDMIL.js";import{a as Te,b as ae,c as yt,d as It,e as wt,f as xe,g as vt,h as Me,i as dn,j as ln,k as mn}from"./chunk-RYZBE5FQ.js";import{B as V,C as N,d as ft,e as ht,k as gt,l as z,m as St,p as Ct,q as Rt,r as bt,s as At,t as Ot,y as pe,z as Tt}from"./chunk-WTPS62L7.js";import"./chunk-73UFNVEP.js";import{c as h}from"./chunk-CAE4KIZN.js";import"./chunk-CJUODAOF.js";import{a as Et,b as _e}from"./chunk-XHZH3E4G.js";import"./chunk-VSARBT7T.js";import"./chunk-6HKQILBV.js";import{e as at}from"./chunk-EACC667P.js";import{B as pt,C as de,D as Z,E as lt,J as mt,a as et,e as q,j as Re,k as st,l as ct,q as ut,r as dt,s as be,t as Ae}from"./chunk-BX2MSRA4.js";import{b as Oe}from"./chunk-LOBZ45T3.js";import{e as ve,i as Ze,l as it}from"./chunk-J4RM5GQP.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import{A as W,B as oe,C as tt,D as Se,E as ie,G as se,H as Ce,M as j,O as ce,P as nt,R as Ee,S as rt,T as ot,f as Ge,g as je,j as we,r as ze,s as Ke,u as an,v as sn,y as cn,z as X}from"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-ANJPFGFN.js";import"./chunk-DX33T5JM.js";import{a as Ne,b as Le}from"./chunk-L64BS65O.js";import{o as ue}from"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-RJT764B2.js";import{c as Ie}from"./chunk-BKBWGPNR.js";import{e as Xe,h as We}from"./chunk-NNJVMJUG.js";import{a as c}from"./chunk-WE55LJEN.js";import{h as Y}from"./chunk-OZK47BUU.js";import"./chunk-3VUPVXAV.js";import"./chunk-JCOSQTFG.js";import{b as u}from"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";var _t=4,Mt=[...tt,"requirement_checks","native_offers","preparations","benefit_claims","authorizations","business_results","checkout_termination"],In=u.enum(Mt),ee=(e,n)=>u.array(e).max(n).refine(t=>new Set(t).size===t.length,"Declarations must be unique"),ke=u.strictObject({...se.shape,bridgeVersion:u.literal(_t),capabilities:ee(In,Mt.length),checkKinds:ee(u.enum(["access","metered","credit"]),3),preparationActions:ee(u.enum(["purchase","subscription_change","refund"]),3),authorizationKinds:ee(u.enum(["auto_topup"]),1),nextActionTypes:ee(u.enum(["redirect","authenticate"]),2),resultEvents:ee(u.enum(["benefit.claimed","authorization.updated"]),2)}).superRefine((e,n)=>{e.capabilities.includes("catalog")!==(e.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(e.capabilities.includes("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare unique supported billing events"});let t=r=>e.capabilities.includes(r),o=(r,a)=>n.addIssue({code:"custom",path:[r],message:a});t("requirement_checks")!==e.checkKinds.length>0&&o("checkKinds","Declare the supported Check kinds"),t("preparations")!==e.preparationActions.length>0&&o("preparationActions","Declare the supported preparation actions"),t("authorizations")!==e.authorizationKinds.length>0&&o("authorizationKinds","Declare the supported authorization kinds"),t("business_results")!==e.resultEvents.length>0&&o("resultEvents","Declare the supported non-financial results");for(let[r,a,s]of[["purchases","purchase","purchase.completed"],["subscription_changes","subscription_change","subscription.change.completed"],["refunds","refund","refund.updated"]])t(r)&&(!t("operation_status")||!t("billing_records")||!t("preparations")||!e.preparationActions.includes(a)||!e.billingEvents.includes(s))&&o("capabilities",`${r} requires preparation, original lookup and its billing result`);t("purchases")&&!e.billingEvents.includes("purchase.closed")&&o("billingEvents","Purchase execution requires its terminal closure result"),t("checkout_termination")&&(!t("operation_status")||!t("billing_records")||!e.billingEvents.includes("purchase.closed"))&&o("capabilities","Checkout termination requires original lookup and purchase.closed"),t("subscription_changes")&&!e.billingEvents.includes("subscription.change.closed")&&o("billingEvents","Subscription change execution requires its terminal closure result");for(let[r,a]of[["benefit_claims","benefit.claimed"],["authorizations","authorization.updated"]])t(r)&&(!t("operation_status")||!t("business_results")||!e.resultEvents.includes(a))&&o("capabilities",`${r} requires original lookup and its non-financial result`)}),K={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":u.strictObject({}),"requirement.check":$e,"operation.prepare":ze,"benefit.claim":Ue,"operation.read":qe,"purchase.terminate":j},wn={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":ke,"requirement.check":Qe,"operation.prepare":Ke,"benefit.claim":Ve,"operation.read":He,"purchase.terminate":j.extend({outcome:u.enum(["requested","already_paid"])})},Gn=u.enum(["bridge.ping","bridge.describe","requirement.check","operation.prepare","benefit.claim","operation.read","purchase.terminate"]);function $(e,n){return u.strictObject({bridgeVersion:u.literal(_t),requestId:u.uuid(),scope:Ce,command:u.literal(e),data:n})}var kt=u.discriminatedUnion("command",[$("bridge.ping",K["bridge.ping"]),$("bridge.describe",K["bridge.describe"]),$("requirement.check",K["requirement.check"]),$("operation.prepare",K["operation.prepare"]),$("benefit.claim",K["benefit.claim"]),$("operation.read",K["operation.read"]),$("purchase.terminate",K["purchase.terminate"])]),Be=u.strictObject({code:u.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:u.string().min(1).max(500),retryable:u.boolean(),recovery:u.string().min(1).max(80),effect:u.enum(["none","unknown"])}).refine(e=>e.effect!=="unknown"||!e.retryable&&e.recovery==="recover_operation","Unknown effects require original-operation recovery");function Bt(e){let n={bridgeVersion:u.literal(4),requestId:u.uuid(),scope:Ce,command:u.literal(e)};return u.union([u.strictObject({...n,data:wn[e]}),u.strictObject({...n,error:Be})])}var Pt="X-Indiana-Bridge-Signature",Q="X-Indiana-Bridge-Key-Id";function vn(e){return new TextEncoder().encode(e)}function Dt(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),n=>n.charCodeAt(0))}function Ft(e,n,t,o){return vn(`indiana-merchant-bridge:${o}
1
+ import{a as pn}from"./chunk-MRL7XUBV.js";import{a as I}from"./chunk-36VNAOG6.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-IN32NWRI.js";import{a as xt}from"./chunk-ZQY7OYHM.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-JXWZS4UM.js";import"./chunk-YMRWDMIL.js";import{a as Te,b as ae,c as yt,d as It,e as wt,f as xe,g as vt,h as Me,i as dn,j as ln,k as mn}from"./chunk-PB34FLPJ.js";import{B as V,C as N,d as ft,e as ht,k as gt,l as z,m as St,p as Ct,q as Rt,r as bt,s as At,t as Ot,y as pe,z as Tt}from"./chunk-MZRDAMFQ.js";import"./chunk-73UFNVEP.js";import{c as h}from"./chunk-CAE4KIZN.js";import"./chunk-CJUODAOF.js";import{a as Et,b as _e}from"./chunk-XHZH3E4G.js";import"./chunk-LFMAFY3P.js";import"./chunk-6HKQILBV.js";import{e as at}from"./chunk-EACC667P.js";import{B as pt,C as de,D as Z,E as lt,J as mt,a as et,e as q,j as Re,k as st,l as ct,q as ut,r as dt,s as be,t as Ae}from"./chunk-BX2MSRA4.js";import{b as Oe}from"./chunk-LOBZ45T3.js";import{e as ve,i as Ze,l as it}from"./chunk-J4RM5GQP.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import{A as W,B as oe,C as tt,D as Se,E as ie,G as se,H as Ce,M as j,O as ce,P as nt,R as Ee,S as rt,T as ot,f as Ge,g as je,j as we,r as ze,s as Ke,u as an,v as sn,y as cn,z as X}from"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-ANJPFGFN.js";import"./chunk-TS26DZNO.js";import{a as Ne,b as Le}from"./chunk-L64BS65O.js";import{o as ue}from"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-RJT764B2.js";import{c as Ie}from"./chunk-BKBWGPNR.js";import{e as Xe,h as We}from"./chunk-NNJVMJUG.js";import{a as c}from"./chunk-WE55LJEN.js";import{h as Y}from"./chunk-OZK47BUU.js";import"./chunk-3VUPVXAV.js";import"./chunk-LBDLWHBY.js";import{b as u}from"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";var _t=4,Mt=[...tt,"requirement_checks","native_offers","preparations","benefit_claims","authorizations","business_results","checkout_termination"],In=u.enum(Mt),ee=(e,n)=>u.array(e).max(n).refine(t=>new Set(t).size===t.length,"Declarations must be unique"),ke=u.strictObject({...se.shape,bridgeVersion:u.literal(_t),capabilities:ee(In,Mt.length),checkKinds:ee(u.enum(["access","metered","credit"]),3),preparationActions:ee(u.enum(["purchase","subscription_change","refund"]),3),authorizationKinds:ee(u.enum(["auto_topup"]),1),nextActionTypes:ee(u.enum(["redirect","authenticate"]),2),resultEvents:ee(u.enum(["benefit.claimed","authorization.updated"]),2)}).superRefine((e,n)=>{e.capabilities.includes("catalog")!==(e.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(e.capabilities.includes("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare unique supported billing events"});let t=r=>e.capabilities.includes(r),o=(r,a)=>n.addIssue({code:"custom",path:[r],message:a});t("requirement_checks")!==e.checkKinds.length>0&&o("checkKinds","Declare the supported Check kinds"),t("preparations")!==e.preparationActions.length>0&&o("preparationActions","Declare the supported preparation actions"),t("authorizations")!==e.authorizationKinds.length>0&&o("authorizationKinds","Declare the supported authorization kinds"),t("business_results")!==e.resultEvents.length>0&&o("resultEvents","Declare the supported non-financial results");for(let[r,a,s]of[["purchases","purchase","purchase.completed"],["subscription_changes","subscription_change","subscription.change.completed"],["refunds","refund","refund.updated"]])t(r)&&(!t("operation_status")||!t("billing_records")||!t("preparations")||!e.preparationActions.includes(a)||!e.billingEvents.includes(s))&&o("capabilities",`${r} requires preparation, original lookup and its billing result`);t("purchases")&&!e.billingEvents.includes("purchase.closed")&&o("billingEvents","Purchase execution requires its terminal closure result"),t("checkout_termination")&&(!t("operation_status")||!t("billing_records")||!e.billingEvents.includes("purchase.closed"))&&o("capabilities","Checkout termination requires original lookup and purchase.closed"),t("subscription_changes")&&!e.billingEvents.includes("subscription.change.closed")&&o("billingEvents","Subscription change execution requires its terminal closure result");for(let[r,a]of[["benefit_claims","benefit.claimed"],["authorizations","authorization.updated"]])t(r)&&(!t("operation_status")||!t("business_results")||!e.resultEvents.includes(a))&&o("capabilities",`${r} requires original lookup and its non-financial result`)}),K={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":u.strictObject({}),"requirement.check":$e,"operation.prepare":ze,"benefit.claim":Ue,"operation.read":qe,"purchase.terminate":j},wn={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":ke,"requirement.check":Qe,"operation.prepare":Ke,"benefit.claim":Ve,"operation.read":He,"purchase.terminate":j.extend({outcome:u.enum(["requested","already_paid"])})},Gn=u.enum(["bridge.ping","bridge.describe","requirement.check","operation.prepare","benefit.claim","operation.read","purchase.terminate"]);function $(e,n){return u.strictObject({bridgeVersion:u.literal(_t),requestId:u.uuid(),scope:Ce,command:u.literal(e),data:n})}var kt=u.discriminatedUnion("command",[$("bridge.ping",K["bridge.ping"]),$("bridge.describe",K["bridge.describe"]),$("requirement.check",K["requirement.check"]),$("operation.prepare",K["operation.prepare"]),$("benefit.claim",K["benefit.claim"]),$("operation.read",K["operation.read"]),$("purchase.terminate",K["purchase.terminate"])]),Be=u.strictObject({code:u.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:u.string().min(1).max(500),retryable:u.boolean(),recovery:u.string().min(1).max(80),effect:u.enum(["none","unknown"])}).refine(e=>e.effect!=="unknown"||!e.retryable&&e.recovery==="recover_operation","Unknown effects require original-operation recovery");function Bt(e){let n={bridgeVersion:u.literal(4),requestId:u.uuid(),scope:Ce,command:u.literal(e)};return u.union([u.strictObject({...n,data:wn[e]}),u.strictObject({...n,error:Be})])}var Pt="X-Indiana-Bridge-Signature",Q="X-Indiana-Bridge-Key-Id";function vn(e){return new TextEncoder().encode(e)}function Dt(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),n=>n.charCodeAt(0))}function Ft(e,n,t,o){return vn(`indiana-merchant-bridge:${o}
2
2
  ${n}
3
3
  POST
4
4
  ${W}
package/dist/visual.js CHANGED
@@ -1 +1 @@
1
- import{a as pe,c as fe}from"./chunk-VJIONC4S.js";import{b as le}from"./chunk-J6KIN4RH.js";import{a as Ve,b as ce,c as de,d as ue}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-QRBZYLE4.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-PSAAZJZA.js";import"./chunk-3VUPVXAV.js";import"./chunk-JCOSQTFG.js";import{b as o}from"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:le(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=se(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=re(e.deviceIdCookie??"indiana_did"),T=ae(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(de(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=oe(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=ue(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=ce(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
1
+ import{a as pe,c as fe}from"./chunk-VJIONC4S.js";import{b as le}from"./chunk-J6KIN4RH.js";import{a as Ve,b as ce,c as de,d as ue}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-SK5JZ7HA.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-R2L227PQ.js";import"./chunk-3VUPVXAV.js";import"./chunk-LBDLWHBY.js";import{b as o}from"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:le(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=se(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=re(e.deviceIdCookie??"indiana_did"),T=ae(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(de(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=oe(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=ue(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=ce(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinkerlandai/longplay-sdk",
3
- "version": "0.10.53",
3
+ "version": "0.10.54",
4
4
  "description": "Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- import{o as n,r as t}from"./chunk-WTPS62L7.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
@@ -1 +0,0 @@
1
- import{a as cn,c as un,d as kt,f as Et,g as dn,k as fn}from"./chunk-DXLBEXC6.js";import{b as Xe}from"./chunk-W32FI2A2.js";import{d as nn,e as rn,f as an,h as Pt,i as Ze,j as on,k as sn,l as ln}from"./chunk-QAGK2SLZ.js";import{a as Xt,c as bt,d as Zt,e as en}from"./chunk-ADTZEBQF.js";import{a as Je,b as ne,d as Ct,f as vt,j as tn}from"./chunk-OV46DXRX.js";import{b as Ce}from"./chunk-M4P6TGBU.js";import{B as N,C as Ke,D as Be,E as Re,y as Jt}from"./chunk-GGZG56GR.js";import{r as Se,t as Oe}from"./chunk-QGKROSRD.js";import{i as Kt}from"./chunk-RRZZUIFM.js";import{c as he,j as He}from"./chunk-RJT764B2.js";import{c as gt}from"./chunk-BKBWGPNR.js";import{a as P}from"./chunk-WE55LJEN.js";import{a as q}from"./chunk-DSPLGTQI.js";async function pn($,i,k){if(!Be(i))throw new P("INVALID_RESPONSE","A verified completed purchase is required");let A=$?He.parse($):null;if(await k.onComplete?.(i),!A||!k.check)return;let B=He.parse(await k.check());if(B.internal_feature_id!==A.internal_feature_id||B.quantity!==A.quantity||A.observation!==void 0&&(B.observation===void 0||B.observation.requirementDigest!==A.observation.requirementDigest||B.observation.authority!==A.observation.authority||gt(B.observation.subject)!==gt(A.observation.subject)))throw new P("INVALID_RESPONSE","The access requirement changed");B.allowed&&await k.onAccessGranted?.(B)}function mn($){return Object.entries($.document.buttons).filter(([,i])=>i.type==="checkout"&&i.product.type==="fixed"&&!Ce(i.product,{},$.capabilities)).map(([i])=>i)}function hn($,i){let k=N(i)?void 0:i.lines[0];if(!N(i)&&(i.lines.length!==1||!k))return;let A=N(i)?i.productVersionId:k.productVersionId,{screen:B,buttons:re}=$.document,D=new Map(N(i)?Object.entries(i.featureQuantities??{}):(k?.prepaid??[]).map(w=>[w.internal_feature_id,w.quantity]));function ie(w,c){if(w.hidden)return!1;if(w.type==="plan_picker"&&$.capabilities.pickers[w.id]?.options.includes(A))return c[w.id]=A,!0;if(w.type==="quantity_picker"){let Z=D.get(w.internalFeatureId);return Z!==void 0&&(!w.bind?.plan||w.bind.plan===A)&&(c[w.id]=Z),!1}if(w.type==="button"&&w.action){let Z=re[w.action];return Z?.type==="checkout"&&Z.product.type==="fixed"&&Z.product.productVersionId===A}if(w.type!=="stack")return!1;let X=w.interaction,a=w.bind?.plan===A;for(let[Z,p]of w.children.entries()){let ae={},_=ie(p,ae);if(X?.type==="toggle"||X?.type==="tabs"){if(!_)continue;return c[w.id]=X.type==="toggle"?Z===0:p.id,Object.assign(c,ae),!0}Object.assign(c,ae),_&&(a=!0,X?.type==="select"&&X.purpose==="product"&&X.pickerId&&p.type==="stack"&&p.bind?.plan===A&&(c[w.id]=p.id,c[X.pickerId]=A))}return a}for(let w of B.pages){let c={__page:w.id};if(ie(w.root,c))return c}}async function tr($,i,k){let A=i.focusAtReveal?()=>{}:Pt($.ownerDocument),B=()=>{D.finish("dismissed"),A()},re=()=>B(),D=on($,i,"paywall",()=>{B(),q(i.onDismiss)},cn);i.signal?.throwIfAborted(),i.signal?.addEventListener("abort",re,{once:!0});let ie=null,w,c,X;try{if(D.start(!0,i.loadingDocument?.screen.strings.defaultLocale,i.loadingDocument??null),D.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(ie=i.check?He.parse(await D.wait(i.check(),Ze)):null,ie?.allowed)return D.finish("skipped"),i.signal?.removeEventListener("abort",re),A(),await i.onAccessGranted?.(ie),{check:ie,host:null};let[e,t]=await Promise.allSettled([D.wait(import("./screen-renderer-CMFJVI36.js")),D.wait(i.start().then(r=>(D.cancelled&&r.destroy(),r)),Ze)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;X=e.value,w=t.value,i.signal?.throwIfAborted(),w.signal?.throwIfAborted(),w.signal?.addEventListener("abort",re,{once:!0});let n=w.view??await D.wait(w.refresh(),Ze);if(!n)throw new P("INVALID_RESPONSE","Paywall presentation is missing");w.signal?.throwIfAborted(),c=n}catch(e){throw D.finish("error",e),k?.retainedDialog?.release(),i.signal?.removeEventListener("abort",re),w?.signal?.removeEventListener("abort",re),w?.destroy(),A(),e}let a=w,{mountScreenPreview:Z}=X,p=$.ownerDocument,ae=new AbortController,_=p.createElement("section"),ue=p.createElement("div"),ee=p.createElement("div"),et=i.mountControls,K=et?p.createElement("div"):void 0,d=p.createElement("p"),g=p.createElement("button"),oe=p.createElement("button"),O=p.createElement("button"),ve=k?.retainedDialog,E=ve?.dialog??p.createElement("dialog"),tt=a.locale||c.document.screen.strings.defaultLocale,o=tt.toLowerCase().startsWith("zh"),yn=o?"正在处理…":"Processing…",wn=o?"正在准备报价…":"Preparing your price…",M=un(c.document.screen.theme);_.dataset.indianaPaywall="",_.setAttribute("aria-label",c.document.name),_.style.cssText=M.root,ee.style.cssText=M.controls,d.style.cssText=M.message,d.setAttribute("role","status"),O.style.cssText=M.link,O.textContent=o?"关闭":"Close",g.style.cssText=M.secondary,g.textContent=o?"重试":"Retry",g.hidden=!0,oe.type="button",oe.style.cssText=M.primary,oe.textContent=o?"继续付款":"Continue payment",oe.hidden=!0,ee.append(d,oe,g,O),K&&(K.style.cssText="flex:1 0 100%;min-width:0",K.hidden=!0,ee.prepend(K)),_.append(ue,ee);let nt=()=>{if(K){let r=!K.childElementCount&&!K.textContent?.trim();K.hidden!==r&&(K.hidden=r)}let e=fe??ee,t=[...e.children].every(r=>r===d?!d.textContent:r.hidden),n=[...e.children].some(r=>r===O?!1:r===d?!!d.textContent:!r.hidden);e.style.cssText=t?M.controls.replace(/padding:[^;]+/,"padding:0"):n?`${M.controls};${M.pinned}`:M.controls,it()},It=typeof MutationObserver>"u"?void 0:new MutationObserver(nt);It?.observe(_,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let je=ve&&c.document.presentation.type==="inline"?{type:"modal",size:"md"}:c.document.presentation,gn=Object.entries(c.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),V,xt,Te=!1,At=JSON.stringify(c.capabilities),j;function ye(e){let t=mn(e);if(j||de&&!ce)return Ne(e).map(({actionId:r})=>r);if(!T&&i.allowNewPurchase!==!1)return t;let n=T?Nt(e):Dt(e);return[...new Set([...t,...Ne(e).map(({actionId:r})=>r).filter(r=>!n.includes(r))])]}function Fe(e){if(b)return;c=e;let t=JSON.stringify(e.capabilities);if(t!==At){let n=!v&&!a.quote&&!a.operation?Je(e,G,St):G;JSON.stringify(n)!==JSON.stringify(G)?(G=n,V?.update(e.document.screen,tt,{capabilities:ne(e),unavailableActions:ye(e),serverInput:{bindings:[],answers:{}},selection:G})):V?.updateCapabilities(ne(e),ye(e)),At=t}Cn(e),ge()}let L,rt=0;function it(){let e=p.defaultView;if(!L?.responsive||!e)return;let t=fe??ee,n=e.innerHeight-(L.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",rt=Math.max(1,n-t.getBoundingClientRect().height),V?.resizeViewport?.(rt,e.innerWidth)}let b=!1,de=!1,v=null,at,qe=!1,Rt=!1,we=!1,ot,st=!1,se,fe;function bn(){return de||b||se||st?{type:"recover",operationId:a.operation?.operationId??a.quote?.operationId??null,requestId:null}:bt(a)}let R=()=>!b&&!qe&&!se&&i.canInteract?.()!==!1,W,Pe=!1,ke=!1,u=null,le=null,Ge="",pe=()=>i.checkoutNavigation==="after_confirmation"&&!!(i.terminateCheckout||i.resumeCheckout),G={},St=new Set,ce,T;function lt(e){return!!e&&N(e)&&e.timing==="immediate"&&e.execution.provider==="merchant"}let Ot=o?"正在确认付款…":"Confirming payment…",te=null;function Ne(e){return Object.entries(e.document.buttons).flatMap(([t,n])=>n.type==="checkout"?[{actionId:t,policy:n}]:[])}function Tt(e){let t=T?.quote;return t?Ne(e).filter(({actionId:n,policy:r})=>Ee(t,e,n,r.product,G)).map(({actionId:n})=>n):[]}function Nt(e){return T?.phase==="payment"?Tt(e):[]}function Dt(e){let t=a.quote;return!pe()||te||!t||!a.operation||S(a.operation).type!=="checkout"?[]:Ne(e).filter(({actionId:n,policy:r})=>Ee(t,e,n,r.product,G)).map(({actionId:n})=>n)}function ge(){let e=j?[]:T?Nt(c):Dt(c),t=i.allowNewPurchase===!1&&!!a.operation&&S(a.operation).type==="checkout";if(oe.hidden=!!j||(T?T.phase!=="payment":!t)||e.length>0,!pe()&&!T||!V?.updateCheckoutControls)return;let n=!j&&T?.phase==="checking"?ce:void 0;V.updateCheckoutControls({actions:Ne(c).map(({actionId:r})=>r),resume:n?[n]:e,resumeLabel:n?Ot:o?"继续付款":T?"Continue payment":"Continue checkout",busy:ce})}function Lt(){le?.remove(),le=null}async function We(){if(te)return;if(i.resumeCheckout&&a.operation){await i.resumeCheckout(a.operation.operationId);return}let e=await a.read();if(S(e).type!=="checkout")return H(e,!1);R()&&(De.delete(e.operationId),await Le(e))}function _t(){d.textContent=o?"暂时无法打开付款页面。请重试。":"Couldn’t open checkout. Try again.",g.hidden=!0}async function Ut(e=!1){let t=te;if(!t)return;g.hidden=!0;let n=Date.now()+2e4;for(;R();){let r=await a.read();if(r.operationId!==t.operationId)throw new P("PURCHASE_PENDING","The original Checkout changed");if(!R())break;let l=S(r);if(l.type==="native"){te=null,Lt(),v=t.selection,W=t.coupon,Pe=!1,ke=!1,await Ve();return}if(l.type==="complete"||l.type==="fulfillment"||l.type==="recording"){te=null,await H(r,!1);return}if(e&&l.type==="checkout"){e=!1;try{await i.terminateCheckout(t.operationId)}catch(y){q(i.onError,y)}}if(Date.now()>=n)break;await Xe(1e3,p,ae.signal)}b||_t()}async function Mt(e,t,n,r){if(u=()=>Mt(e,t,n,r),await i.beforeCheckoutReplacement?.(structuredClone(r)),!R())return;let l=a.operation;if(l?.operationId!==e||S(l).type!=="checkout"){u=null,l&&await H(l,!1);return}te={operationId:e,selection:t,coupon:n};let y=!1;try{await i.terminateCheckout(e)}catch(s){if(s instanceof P&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(s.code)){te=null,d.textContent=o?"请继续原订单,或等待它过期后再更换方案。":"Continue your original checkout, or wait for it to expire before changing plans.",q(i.onError,s);return}y=s instanceof P&&(s.status??0)>=500,q(i.onError,s)}R()&&await Ut(y)}function ct(e,t,n,r,l){let y=ne(e).checkoutCoupons?.[t],s=y?y.products[n]:i.claimCoupon&&l?Kt(e.capabilities,l,r):void 0;return s?.couponId&&s.planVersionId===n?{id:s.couponId,offerId:s.offerId}:void 0}function Cn(e){de||v||a.quote||a.operation||Ge&&d.textContent===Ge||(d.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":o?"当前账号暂无可购买的方案。":"No plans are currently available for this account.")}let De=new Map,ze=!1;function Ee(e,t,n,r,l,y){let s=N(e),m=!s&&e.lines.length===1?e.lines[0]:void 0,f=Ce(r,l,t.capabilities);if(!f||f!==(s?e.productVersionId:m?.productVersionId))return!1;let I=ct(t,n,f,l,y),z;try{z=Oe(t.document.screen,f,l,t.capabilities)}catch{return!1}if(s){let Y=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return Object.keys(z).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(z).every(([Ae,wt])=>e.featureQuantities?.[Ae]===wt)&&(!I||Y?.couponId===I.id&&(!I.offerId||Y.grantId===I.offerId))}if((I||ne(t).checkoutCoupons?.[n])&&(I?.id??null)!==(e.discount?.couponId??null))return!1;let J=Object.fromEntries((m?.prepaid??[]).map(Y=>[Y.internal_feature_id,Y.quantity]));return[...new Set([...Object.keys(z),...Object.keys(J)])].every(Y=>(z[Y]??0)===(J[Y]??0))}let S=e=>Xt({quote:a.quote,operation:e,requestId:null,pending:!1,destroyed:b,canReselect:a.canReselect});async function Le(e){let t=e.merchantExecution,n=S(e),r=n.type==="checkout"?n.checkoutUrl:e.checkoutUrl;if(!(!R()||!r||Ke(e)&&n.type!=="checkout"||i.checkoutNavigation==="after_confirmation"&&n.type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||De.get(e.operationId)===r)){De.set(e.operationId,r);try{i.onCheckoutUrl?await i.onCheckoutUrl(r):p.defaultView?.location.assign(r)}catch(l){throw De.delete(e.operationId),l}}}let me=(e,t=!1)=>{if(e instanceof Ct)u=null,d.textContent=e.customerMessage(o);else if(dn(e))u=null,d.textContent=t?o?"当前无法在此购买,付款尚未开始。请联系商户。":"Purchases aren’t available here right now. Payment hasn’t started. Contact the merchant for help.":Et(e,o);else if(t){let n=e instanceof P?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(u=null,d.textContent=o?"暂时无法为此套餐报价,付款尚未开始。":"Pricing for this plan is unavailable. Payment hasn’t started."):a.canReselect===!0&&!v?d.textContent=o?"未能取得报价,付款尚未开始。请重新选择套餐。":"We couldn’t prepare your price. Payment hasn’t started. Choose a plan again.":n==="COMMAND_PENDING"?d.textContent=o?"仍在准备报价,请重试以查看结果。":"Your price is still being prepared. Retry to check the result.":d.textContent=o?"未能取得报价,付款尚未开始。请重试。":"We couldn’t prepare your price. Payment hasn’t started. Try again."}else d.textContent=e instanceof P&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?Et(e,o):e instanceof P?e.message:o?"操作未完成,请重试。":"This action couldn’t be completed. Try again.";g.hidden=u===null,Ge=d.textContent,t&&ce===void 0&&!L?.responsive&&d.scrollIntoView?.({block:"nearest"}),q(t&&k?.quoteError?k.quoteError:i.onError,e)},_e=new WeakMap;function Ue(e){de=e,g.disabled=e,oe.disabled=e,V?.updateCapabilities?.(ne(c),ye(c));for(let t of le?.querySelectorAll("button")??[])e?(_e.has(t)||_e.set(t,t.disabled),t.disabled=!0):_e.has(t)&&(t.disabled=_e.get(t),_e.delete(t)),kt(t)}function $t(){j&&(d.textContent=j.message,g.textContent=o?"重试":"Retry",g.disabled=!1,g.hidden=!j.retry,oe.disabled=!0)}function ut(){d.textContent=o?"暂时无法操作,请稍后重试。":"This action is unavailable right now. Try again in a moment."}async function vn(e){if(i.beforeAction)try{await i.beforeAction()}catch(t){throw t instanceof Ct?(v=null,Pe=!1,ke=!1,u=null):u=e,t}}async function Q(e,t){if(de||b||j)return;if(!R()){ut();return}let n=e===Ve,r=n?wn:yn,l=pe()&&t!==void 0;ce=l?t:void 0,Ue(!0),ge(),g.hidden=!0,d.textContent=l?"":r;try{if(e!==mt&&e!==dt&&e!==ft&&e!==dt&&(e!==We||!i.resumeCheckout)&&await vn(e),b||j)return;if(!R()){u=e,g.hidden=!1,ut();return}await e()}catch(y){b||me(y,n)}finally{ce=void 0,Ue(!1),ge(),j?$t():d.textContent===r&&(d.textContent="")}}async function Vt(e){await pn(ie,e,i)}function Me(e,t){T=t?{quote:e,phase:t}:void 0,t==="checking"?(ce??=v?.actionId??Tt(c)[0],d.textContent=Ot,u=dt,g.textContent=o?"查询状态":"Check status",g.hidden=!0):ce=void 0,V?.updateCapabilities(ne(c),ye(c)),ge()}function Qt(e){return e instanceof P&&(e.code==="COMMAND_PENDING"||e.reason==="RESULT_UNKNOWN"||e.code==="NETWORK_ERROR"||e.code==="TIMEOUT"||e.status===429||(e.status??0)>=500)}function Ht(e,t){vt(e,{...t,featureQuantities:t.featureQuantities??{}},"Purchase operation changed")}async function dt(){T&&await $e(T.quote)}async function $e(e,t){Me(e,"checking"),Ge="";let n=1e3;Te=!0,q(i.onObservationChange,!0);try{for(let r=t;R();r=void 0){if(!r){try{r=await a.read()}catch(l){if(!Qt(l))throw l}if(!R())return}if(r){Ht(r,e);let l=S(r);if(l.type==="checkout"){Me(e,"payment"),d.textContent=o?"请先完成原订单的付款。":"Finish paying for this upgrade.",g.hidden=!1;return}if(l.type==="complete"){Me(e,"complete"),u=null;let y=c.capabilities.plans[e.productVersionId]?.name,s=e.merchantTerms?.subscriptionTerms?.items,m=s?.length===1?s[0].interval:void 0,f=m==="year"?o?"年付":"annual billing":m==="month"?o?"月付":"monthly billing":null;d.textContent=y?o?`已升级到 ${y}${f?" "+f:""}。`:`Upgraded to ${y}${f?" ("+f+")":""}.`:o?"已成功升级。":"Plan upgraded.",await Vt(r);return}if(l.type==="native"&&!Re(r)){Me(e),v=null,u=null,d.textContent=o?"付款未完成,请重新选择套餐。":"Payment failed. Choose a plan to start again.",g.textContent=o?"重试":"Retry";return}if(r.problem&&!["RESULT_UNKNOWN","STATE_CHANGED"].includes(r.problem.reason??""))throw new P(r.problem.code,o?"暂时无法完成升级。":"The upgrade needs attention.",void 0,void 0,r.problem)}await Xe(n,p,ae.signal),n=Math.min(n*1.5,15e3)}}finally{Te=!1,q(i.onObservationChange,!1)}}async function ft(){let e=T?.quote;if(!e)return;let t=await a.read();if(Ht(t,e),S(t).type!=="checkout")return $e(e,t);if(i.resumeCheckout){await i.resumeCheckout(t.operationId);return}De.delete(t.operationId),await Le(t)}function Bt(e){return bt(a).type==="recording"||S(e).type==="recording"}function jt(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],r=t?t.totalMinor:N(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),l=t?n.length===1&&n[0]?.amountMinor===r&&n[0]:!N(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],y=r===null?he(t.subtotalMinor-t.discountMinor,e.currency)+(o?" + 待确认税费":" + tax confirmed at checkout"):he(r,e.currency)+(l?Se(l.interval,o?"zh-CN":"en",l.intervalCount??1):""),s=N(e)?a.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(m=>m.productName).join(", ");return{label:s?`${s} · ${y}`:y,recurring:l}}async function H(e,t=i.checkoutNavigation!=="after_confirmation"){if(b)return;if(!R()){u=async()=>H(await a.read()),g.hidden=!1;return}let n=e.quote??a.quote;if(lt(n)&&(e.confirmedAt||e.merchantExecution))return $e(n,e);if(d.textContent=fn(e.status,o),Bt(e)){let f=e.merchantExecution?.recordingStatus==="failed";d.textContent=f?o?"付款和商户处理已完成,但交易记录失败。请联系商户修复,勿重复购买。":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"付款和商户处理已完成,正在确认交易记录。请勿重复购买。":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",g.textContent=o?"查询记录":"Check recording",u=async()=>H(await a.read()),g.hidden=!1;return}if(e.problem&&S(e).type!=="native"){let f=e.problem;u=Ie,g.textContent=o?"检查并恢复原操作":"Check and recover original purchase",me(new P(f.code,f.reason==="RESULT_UNKNOWN"?o?"付款结果尚未确定,请恢复原操作,暂勿重复购买。":"The payment result is unknown. Recover the original purchase before buying again.":f.phase==="fulfillment"?o?"付款已记录,商户权益处理需要核对。":"Payment was recorded. Access fulfillment needs attention.":f.code==="CAPABILITY_UNAVAILABLE"?o?"商户尚不支持本次购买所需的完整能力,请处理后恢复原操作。":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":f.code==="NOT_CONFIGURED"?o?"付款服务连接需要处理,请联系商户后恢复原操作。":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"原购买操作需要处理,请查询或恢复此操作。":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,f));return}if((e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"||e.merchantExecution?.type==="subscription_change"&&e.merchantExecution.status==="applied")&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(d.textContent=o?"付款已记录,正在等待商户完成处理。":"Payment was recorded. Waiting for merchant fulfillment."),Be(e)&&S(e).type==="complete"){u=null,await Vt(e);return}if(!Re(e)&&S(e).type!=="fulfillment"){if(a.canReselect===!1){d.textContent=o?"正在核对原购买结果":"Checking the original purchase result",g.textContent=o?"查询结果":"Check result",u=async()=>H(await a.read()),g.hidden=!1;return}e.status==="cancelled"?d.textContent=o?"这笔购买已取消,可以重新选择方案。":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(d.textContent=o?"这笔购买未能完成,可以重新选择方案。":"This purchase didn’t go through. Choose a plan to try again."),g.textContent=o?"重试":"Retry",u=null,v=null;return}if(!t&&S(e).type==="checkout"){if(te){_t();return}if(pe()){d.textContent="",ze=!1,i.allowNewPurchase===!1?Ft():u=null,V?.updateCapabilities?.(ne(c),ye(c)),ge();return}let f=a.quote,I=f?.operationId===e.operationId?jt(f).label:"";d.textContent=ze?I?o?`${I} 尚未付款。再次选择该方案即可继续付款。`:`${I} is still unpaid. Choose it again to continue paying.`:o?"之前的购买尚未付款。再次选择该方案即可继续付款。":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",ze=!1,u=null;return}await Le(e);let r=Date.now(),l=r+6e5,y=2e3,s=S(e).type!=="checkout",m=()=>s&&Date.now()-r<15e3;Te=!0,q(i.onObservationChange,!0);try{for(;!b&&Date.now()<l;){if(await Xe(m()?700:y,p,ae.signal),b)return;if(!R()){u=async()=>H(await a.read()),g.hidden=!1;return}let f=await a.read();if(S(f).type==="checkout"&&(s=!1),!t&&S(f).type==="checkout"){await H(f,!1);return}if(!f.problem&&Re(f)&&await Le(f),!Re(f)||f.problem||Bt(f)){await H(f);return}m()||(y=Math.min(y*1.5,3e4))}}finally{Te=!1,q(i.onObservationChange,!1)}u=async()=>H(await a.read()),g.hidden=!1}async function pt(e=!1){let t=await a.read();if(b)return;if(!R()){u=()=>pt(e),g.hidden=!1;return}let n=a.quote;if(n&&vt(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&(Ke(t)?["prepared","quoted"].includes(t.status):t.status==="pending")&&(Ke(t)||t.quoteFinalized===!1)&&!t.confirmedAt&&!t.checkoutUrl&&!("nativePurchase"in t&&t.nativePurchase)&&!t.merchantExecution&&!t.problem&&!a.pendingCancellation){if(i.purchaseConfirmation!=="paywall"){e?await Ie():u=null;return}setTimeout(qt,0,n);return}await H(t,e||void 0)}function Ft(){u=mt,g.textContent=o?"查询状态":"Check status",g.hidden=!1}async function mt(){await pt()}async function Ie(){if(a.quote&&!(Date.parse(a.quote.expiresAt)>Date.now()))throw new P("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");Lt();let e=a.quote;if(lt(e)){Me(e,"checking");let n;try{n=await a.confirm()}catch(r){if(!Qt(r))throw r;return $e(e)}return $e(e,n)}u=Ie;let t=await a.confirm();if(!R()){u=Ie,g.hidden=!1;return}if(t.problem){await H(t);return}if(Re(t)){if(S(t).type==="checkout")await Le(t);else if(t.execution&&t.execution.provider!=="merchant"||"nativePurchase"in t&&t.nativePurchase){if(!i.onPurchase)throw new P("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await i.onPurchase({operation:t,signal:ae.signal})}}u=async()=>H(await a.read()),await H(t,!0)}function qt(e){if(b)return;le?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());d.textContent=t?o?"此报价已过期。请先取消,再重新选择。":"This quote has expired. Cancel it, then choose again.":"";let n=p.createElement("div"),r=p.createElement("button"),l=p.createElement("button"),y=p.createElement("div"),s=p.createElement("p"),m=e.merchantTerms,f=o?"zh-CN":"en",I=m?.subscriptionTerms?.items??[],z=m?m.subscriptionTerms?.trial?.days:N(e)?void 0:e.lines.find(h=>h.trial)?.trial?.days,J=N(e)?m?m.totalMinor:e.totalMinor:z===void 0?null:m?m.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(h=>h.trial)?0:null,xe=(h,C)=>o?`${C} 天试用结束后 ${h}`:`Then ${h} after the ${C}-day trial`,{label:Y,recurring:Ae}=jt(e),wt=N(e)?a.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(h=>h.productName).join(", "),zt=J===null?"":`${o?"今天应付":"Due today"} ${he(J,e.currency)}`;s.textContent=zt?[wt,zt].filter(Boolean).join(" · "):Y,r.textContent=N(e)?o?"确认变更":"Confirm change":o?"确认购买":"Confirm purchase",r.disabled=t,l.textContent=o?"取消":"Cancel",n.style.cssText=M.panel,s.style.cssText=M.summary,y.style.cssText=M.actions,r.style.cssText=M.primary,l.style.cssText=M.secondary,kt(r),r.onclick=()=>{Q(Ie)};let Yt=async()=>{let h=await a.cancel();b||(n.remove(),le=null,await H(h))};l.onclick=()=>{u=Yt,Q(Yt)};let F=p.createElement("div");if(F.style.cssText=M.terms,N(e)){for(let[C,x]of Object.entries(e.featureQuantities??{})){let U=a.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(Pn=>Pn.internalFeatureId===C),Ye=p.createElement("p");Ye.textContent=`${U?.name??C} · ${x} ${o?"份":"packs"}${U?` × ${U.terms.units}`:""}`,F.append(Ye)}for(let[C,x]of[[o?"原订阅抵扣":"Unused subscription credit",e.creditMinor],[o?"新套餐费用":"New plan charge",e.debitMinor],[o?"优惠减免":"Offer savings",m?.discountMinor??e.discountMinor],[o?"税费":"Tax",m?m.taxMinor:e.taxMinor]]){let U=p.createElement("p");U.textContent=`${C}: ${x===null?o?"结账时确认":"Confirmed at checkout":he(x,e.currency)}`,F.append(U)}let h=p.createElement("p");h.textContent=`${o?"生效时间":"Effective"}: ${e.effectiveAt}`,F.append(h)}if(m){for(let C of I){if(J===null&&C===Ae)continue;let x=p.createElement("p"),U=he(C.amountMinor,e.currency)+Se(C.interval,f,C.intervalCount);x.textContent=J!==null&&z!==void 0?xe(U,z):U,C.amountAfterOfferMinor!==void 0&&(x.textContent+=` · ${o?"优惠结束后":"After the offer"} ${he(C.amountAfterOfferMinor,e.currency)}${Se(C.interval,f,C.intervalCount)}`),F.append(x)}let h=m.subscriptionTerms?.trial;if(h){let C=p.createElement("p");C.textContent=o?`试用 ${h.days} 天;${h.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${h.days}; ${h.cardRequired?"a payment method is required":"no payment method is required"}`,F.append(C)}for(let C of[...m.expectedEffects.map(x=>x.description),...m.requiredConsents.map(x=>x.summary)]){let x=p.createElement("p");x.textContent=C,F.append(x)}}else if(!N(e)){for(let h of e.lines){if(J!==null||h!==Ae){let C=p.createElement("p"),x=`${he(h.catalogAmountMinor,e.currency)}${Se(h.interval,f,h.intervalCount??1)}`;C.textContent=J!==null&&h.trial?(e.lines.length>1?`${h.productName} · `:"")+xe(x,h.trial.days):`${h.productName} · ${x}`,F.append(C)}for(let C of h.prepaid??[]){let x=p.createElement("p"),U=a.view?.capabilities.plans[h.productVersionId]?.prepaid?.find(Ye=>Ye.internalFeatureId===C.internal_feature_id);x.textContent=`${U?.name??C.internal_feature_id} · ${C.quantity} ${o?"份":"packs"} × ${C.terms.units}`,U&&(x.textContent+=Se(U.reset==="week"||U.reset==="month"||U.reset==="year"?U.reset:"one_time",f,U.resetCount)),F.append(x)}if(h.trial){let C=p.createElement("p");C.textContent=o?`试用 ${h.trial.days} 天;${h.trial.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${h.trial.days}; ${h.trial.cardRequired?"a payment method is required":"no payment method is required"}`,F.append(C)}}if(!e.charge){let h=p.createElement("p");h.textContent=o?"目录价格;最终金额以结账时税费和试用规则为准。":"Catalog price; the final charge depends on checkout taxes and trial terms.",F.append(h)}}for(let h of F.children)h.style.margin="0";y.append(r,l),n.append(s,...F.childElementCount?[F]:[],y),ee.prepend(n),L?.responsive||n.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),le=n,de&&Ue(!0),u=null}async function Ve(){if(!v)return;if(u=Ve,!Pe){let n=a.view,r=n?.document.buttons[v.actionId],l=n&&r?.type==="checkout"?Ce(r.product,v.selection,n.capabilities):null;if(!n||!l)throw new P("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!ke){let s=await i.resolveSubscriptionChange?.({actionId:v.actionId,productVersionId:l,featureQuantities:Oe(n.document.screen,l,v.selection,n.capabilities)});if(b)return;s!==void 0&&(v.subscriptionChange=Jt.parse(s)),ke=!0}let y=W?.offerId;if(W&&!y){if(!i.claimCoupon)throw new P("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:s}=await i.claimCoupon(W.id,v.requestId);if(b)return;if(!s||s.couponId!==W.id||s.status!=="issued"||!(Date.parse(s.expiresAt)>Date.now()))throw v=null,W=void 0,u=async()=>{Fe(await a.refresh()),u=null},new P("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");y=s.id}if(!W&&!n.document.screen.actions.some(s=>s.id===v?.actionId&&typeof s.properties.couponBinding=="string")&&(y=await i.resolveOfferId?.({actionId:v.actionId,productVersionId:l,featureQuantities:Oe(n.document.screen,l,v.selection,n.capabilities)})),b)return;y!==void 0&&(v.offerId=y),Pe=!0}if(!R()){g.hidden=!1;return}let e;try{e=await a.preview(v)}catch(n){throw a.canReselect===!0&&(v=null,Pe=!1,ke=!1,W=void 0,u=null),n}if(W&&(N(e)?(()=>{let n=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return n?.couponId!==W.id||n.grantId!==v.offerId})():e.discount?.couponId!==W.id||e.discount.offerId!==v.offerId))throw new P("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(b)return;let t=e.merchantTerms;if(i.purchaseConfirmation!=="paywall"||i.confirmOnHostedCheckout&&R()&&!N(e)&&e.provider==="merchant"&&e.billingSubscriptionId===null&&t?.request.action==="purchase"&&t.request.mode==="subscription"&&t.subscriptionTerms?.trial===null&&t.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){if(!R()){g.hidden=!1;return}if(!(Date.parse(e.expiresAt)>Date.now()))throw new P("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");let n=ce?"":o?"正在打开收银台…":"Opening checkout…";d.textContent=n;try{await Ie()}catch(r){b||me(r)}finally{d.textContent===n&&(d.textContent="")}return}qt(e)}function be(e="destroy",t=!1){if(b)return;b=!0;let n=at;at=void 0,q(n),i.signal?.removeEventListener("abort",re),a.signal?.removeEventListener("abort",re),D.finish("dismissed"),xt?.(),ae.abort(),It?.disconnect(),V?.destroy(),a.destroy(),E.removeEventListener("cancel",Wt),O.remove(),_.remove(),t||Gt(),e==="dismiss"&&q(i.onDismiss)}function Gt(){if(L?.destroy(),ve){ve.release();return}E.open&&E.close(),E.remove(),A()}B=be;async function Qe(){if(!we||b||qe||se==="closing"||!se&&!R())return;if(!k){be("dismiss");return}let e=p.createElement("p");e.setAttribute("role","status"),e.textContent=o?"正在关闭…":"Closing…",fe||(fe=p.createElement("div"),fe.style.cssText=ee.style.cssText,ee.replaceWith(fe),ue.inert=!0),O.hidden=!1,fe.replaceChildren(e,O),se="closing",O.setAttribute("aria-disabled","true"),O.focus({preventScroll:!0});try{await k.dismiss()}catch(t){b||q(i.onError,t)}b||(se="retry",e.textContent=o?"未能确认关闭,请重试。":"Could not confirm closure. Try again.",O.textContent=o?"重试关闭":"Retry closing",O.removeAttribute("aria-label"),O.removeAttribute("aria-disabled"))}O.onclick=()=>{Qe()};function Wt(e){e.preventDefault(),Qe()}E.addEventListener("cancel",Wt),oe.onclick=()=>{Q(T?ft:We)},g.onclick=()=>{if(j){j.retry?.();return}u&&Q(u)};function ht(e){D.finish("error",e),be()}function yt(){if(!(!Rt||we||b||qe||L&&!R()))try{let e=t=>{i.focusAtReveal&&(A=Pt(p)),V?.setHidden?.(!1),ot?.(),L&&(E.open||E.showModal(),L.responsive&&E.focus({preventScroll:!0}),!t&&i.loading!=="host"&&rn(E,L.type,L.responsive)),t&&i.loading!=="host"&&typeof ue.animate=="function"&&!p.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&ue.animate([{opacity:.55},{opacity:1}],{duration:160,easing:"ease-out"}),we=!0};k?k.present(t=>D.present(n=>e(t??n))):D.present(e)}catch(e){ht(e),me(e)}}try{if(je.type==="inline"?(nt(),ot=ln(_,$),$.append(_)):(E.setAttribute("aria-label",c.document.name),O.textContent="×",O.setAttribute("aria-label",o?"关闭":"Close"),an(O,c.document.screen.theme),O.hidden=tn(c.document),(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&k?.retainedContent?k.retainedContent.append(O,_):E.replaceChildren(O,_),ve||$.append(E),L=nn(E,{...c.document.screen,presentation:je},it),L.latch(),L.responsive&&(_.style.display="flex",_.style.flexDirection="column",_.style.maxHeight="100%",ue.style.overflow="clip",ue.style.minHeight="0"),ve||(ot=sn(E))),et&&K){let n=et(K);if(typeof n=="function"&&(b?q(n):at=n),b)throw new DOMException("Presentation cancelled","AbortError");nt()}V=Z(ue,{mode:"live",loadingLayout:()=>D.getLoadingLayout?.()??k?.loadingLayout?.(),rendererUrl:"bundled",title:c.document.name,closeActions:gn,onAuthoredClose(n){se||b||(O.hidden=n)},hostPresentation:()=>L?.type??je.type,reportContentHeight:L?.responsive,onResize:n=>{if(!L?.responsive)return;let r=Math.min(n,rt);ue.style.height=`${r}px`,L.setContentHeight(r+(fe??ee).getBoundingClientRect().height)},onSelection(n){for(let[r,l]of Object.entries(n))typeof l=="number"&&typeof G[r]=="number"&&G[r]!==l&&St.add(r);G=n,ge()},onAction(n,r={},l,y){if(!we||b||se)return;let s=a.view,m=s?.document.buttons[n];if(!m)return;if(j){m.type==="close"&&Qe();return}if(m.type==="close"&&k&&i.resumeCheckout&&a.operation&&Zt(S(a.operation))){Qe();return}if(de)return;if(!R()){ut();return}if(m.type==="close"){Q(async()=>{k?.closeAction?await k.closeAction(n):await i.onAction?.(n),be(i.onAction?"action":"dismiss")});return}if(m.type==="action"){u=async()=>{if(m.action.type==="event"){if(!i.onEvent)throw new P("EVENT_HANDLER_REQUIRED","Provide the event handler");await i.onEvent(m.action.event)}else i.onOpenUrl?await i.onOpenUrl(m.action.url):p.defaultView?.location.assign(m.action.url);await i.onAction?.(n),u=null},Q(u);return}if(T){T.phase==="payment"&&s&&Ee(T.quote,s,n,m.product,r,y)&&Q(ft,n);return}if(i.allowNewPurchase===!1){pe()&&s&&a.quote&&a.operation&&S(a.operation).type==="checkout"&&Ee(a.quote,s,n,m.product,r,y)?Q(We,n):d.textContent=o?"当前只能继续原订单。":"Only your original checkout is available.";return}if(le&&a.canReselect===!1){d.textContent=o?"请先确认或取消当前购买。":"Confirm or cancel the current purchase first.",L?.responsive||le.scrollIntoView?.({block:"nearest"}),le.querySelector("button")?.focus({preventScroll:!0});return}if(pe()&&te){te.selection.actionId===n&&Q(()=>Ut(!0),n);return}if(pe()&&i.terminateCheckout&&s&&a.quote&&a.operation&&a.canReselect===!1&&S(a.operation).type==="checkout"){if(Ee(a.quote,s,n,m.product,r,y)){Q(We,n);return}let I=Ce(m.product,r,s.capabilities),z;try{if(!I)throw new P("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");z=Oe(s.document.screen,I,r,s.capabilities)}catch(Ae){me(Ae);return}let J=a.operation.operationId,xe={actionId:n,requestId:crypto.randomUUID(),selection:structuredClone(r)},Y=ct(s,n,I,r,y);Q(()=>Mt(J,xe,Y,{actionId:n,productVersionId:I,selection:xe.selection,featureQuantities:z}),n);return}if((a.quote||v)&&a.canReselect===!1){let I=!!s&&!!a.quote&&Ee(a.quote,s,n,m.product,r,y);ze=!!a.quote&&!I,u=a.quote?()=>pt(I):Ve,Q(u);return}let f=s&&Ce(m.product,r,s.capabilities);if(!s||!f){me(new P("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(i.onPurchaseIntent){u=null,Q(async()=>{let I={actionId:n,productVersionId:f,selection:structuredClone(r),featureQuantities:Oe(s.document.screen,f,r,s.capabilities)};st=!0,await i.onPurchaseIntent(I)});return}if(v&&v.actionId!==n){me(new P("COMMAND_PENDING","Finish the current purchase"));return}v||(W=ct(s,n,f,r,y),v={requestId:crypto.randomUUID(),actionId:n,selection:structuredClone(r)},Pe=!1,ke=!1),Q(Ve,n)},onEscape:()=>{Qe()},onError:n=>{let r=new Error(n);!we&&!b&&ht(r),me(r)},onRendered:n=>{n&&E.setAttribute("aria-label",n),Rt=!0,yt()}}),V.setHidden?.(!0),it();let e=pe()&&!!a.quote&&!!a.operation&&S(a.operation).type==="checkout";G=a.quote?hn(c,a.quote)??Je(c,{}):Je(c,{}),V.update(c.document.screen,tt,{capabilities:ne(c),unavailableActions:ye(c),serverInput:{bindings:[],answers:{}},...Object.keys(G).length?{selection:G}:{}}),xt=a.subscribe?.(Fe),Fe(a.view??c),await D.wait(V.ready);let t=a.operation;(!e||lt(a.quote))&&(a.quote||t&&(t.confirmedAt||t.checkoutUrl||Be(t)))?(u=mt,Q(u)):e&&i.allowNewPurchase===!1&&Ft()}catch(e){throw ht(e),e}return{check:ie,host:{get currentResolution(){return c},setPurchaseRecovery(e,t){j={message:e,retry:t},V?.updateCapabilities?.(ne(c),ye(c)),ge(),$t()},get subscriptionUpgradeActive(){return T!==void 0},get observing(){return Te},get recovery(){return bn()},async prepareFallback(){if(de||b||se||st)return{type:"recover",operationId:a.operation?.operationId??a.quote?.operationId??null,requestId:null};Ue(!0);try{let e=await en(a);return e.type==="native"&&be(),e}finally{Ue(!1)}},setSuspended(e){qe=e,_.hidden=e,e&&E.open?E.close():!e&&!we?yt():!e&&!b&&we&&je.type!=="inline"&&!E.open&&E.showModal()},destroy:be,retainPurchaseDialog(){if(!(b||!E.open||!E.isConnected))return be("destroy",!0),{dialog:E,release:Gt}},refresh:async()=>{if(!R()){if(a.view)return a.view;throw new P("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await a.refresh();return Fe(e),yt(),e}}}}export{tr as a};
@@ -1 +0,0 @@
1
- import{b as nt}from"./chunk-3CKAOP4L.js";import{a as Bn,b as Wn,c as wn,d as yn,e as Ge,f as Yn,h as Xn,i as Zn,j as Kn,k as et}from"./chunk-DXLBEXC6.js";import{b as Nn,c as tt}from"./chunk-Y2B7RDRB.js";import{a as xn}from"./chunk-W32FI2A2.js";import{c as Gn,e as Qn,f as zn,h as Jn,i as He,j as rn,k as jn,l as on}from"./chunk-QAGK2SLZ.js";import{b as On}from"./chunk-73UFNVEP.js";import{K as tn}from"./chunk-BX2MSRA4.js";import{a as xe,d as _n}from"./chunk-ADTZEBQF.js";import{c as Ln,e as Hn,f as Vn,g as Un,h as Mn,i as $n}from"./chunk-OV46DXRX.js";import{b as Sn}from"./chunk-M4P6TGBU.js";import{B as mn}from"./chunk-GGZG56GR.js";import{x as Tn}from"./chunk-NL7AXMUA.js";import{t as Fn}from"./chunk-QGKROSRD.js";import{C as An}from"./chunk-RRZZUIFM.js";import{a as w}from"./chunk-WE55LJEN.js";import{a as Pe}from"./chunk-DSPLGTQI.js";async function hn(t){let{session:b,load:R}=ct(t);try{return await R(),b}catch(n){throw b.destroy(),n}}function ct(t){let b=t.view;if(!b?.paywall)throw new w("INVALID_REQUEST","The current node is not a Paywall");let R=b.paywall.receiptId,n=b.nodeId,g=b.visit,S=b.paywall.resolution,o=b.paywall,_="document"in S?{document:S.document,offering:S.offering,capabilities:S.capabilities}:null;function c(){let i=o.resolution;return"document"in i?i:_&&{...i,document:_.document,offering:_.offering,capabilities:Ln(i.capabilities,_.capabilities)}}function C(i){if(!Hn(i,S))throw new w("INVALID_RESPONSE","The pinned Paywall binding changed")}let E=!1,G=new Set,re=null;function y(){let i=c();if(i&&!E)for(let a of G)Pe(a,structuredClone(i))}async function N(){I();let i=c();if(i)return structuredClone(i);if(!re){let a=(async()=>{if("document"in o.resolution||!t.resolvePaywall)throw new w("INVALID_RESPONSE","Public Paywall reader is unavailable");let D=await Nn(t,o.resolution);return I(),C(D),_={document:D.document,offering:D.offering,capabilities:D.capabilities},y(),c()})();re=a;let s=()=>{re===a&&(re=null)};a.then(s,s)}return re.then(a=>structuredClone(a))}let u=new AbortController,q=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===n&&i.visit===g&&i.input.type==="paywall_quote")?.requestId??b.paywall.purchaseRequestId,T=0,ne=null,U=new Set,M=null,z=new Map;function Q(i){if(i.purchase&&i.purchase.receiptId!==R)throw new w("INVALID_RESPONSE","Purchase receipt changed");let a=i.run.paywall;return i.purchase??(a?.receiptId===R?a:null)}function I(){if(E)throw new w("IDENTITY_CHANGED","Paywall presentation has closed")}function K(i,a,s){if(I(),a!==T||s!==void 0&&o.quote?.operationId!==s)return!1;let D=o.selectionGeneration??0,m=i.run.paywall;if(m?.receiptId===R){if((m.selectionGeneration??0)<(o.selectionGeneration??0))return!1;C(m.resolution)}let f=Q(i),F=m?.receiptId===R&&(m.selectionGeneration??0)>D,l=F?f?.quote??null:f?.quote??o.quote,Y=f?.operation??(l?.operationId===o.quote?.operationId?o.operation:null);return o.quote&&l&&Mn(o.quote,l),l&&Y&&Vn(Y,{operationId:l.operationId,membershipId:mn(l)?l.membershipId:null,...mn(l)?{featureQuantities:l.featureQuantities??{}}:{}},"Purchase operation changed"),(F||l?.operationId!==o.quote?.operationId)&&(T++,m?.receiptId===R&&(q=m.purchaseRequestId)),m?.canReselect===!0&&m.purchaseRequestId===M&&!(t.pendingCommands??[t.pendingCommand]).some(X=>X?.requestId===M)&&(M=null),o={...o,...m?.receiptId===R?m:{},...s!==void 0&&!F&&f?.canReselect!==void 0?{canReselect:f.canReselect}:{},quote:l,operation:$n(o.operation,Y,!0)},y(),!0}function O(i,a,s){return new Promise((D,m)=>{let f=!1,F=()=>{clearTimeout(j),u.signal.removeEventListener("abort",X)},l=ge=>{f||(f=!0,F(),D(ge))},Y=ge=>{f||(f=!0,F(),m(ge))},X=()=>Y(new w("IDENTITY_CHANGED","Paywall presentation has closed")),j=setTimeout(()=>Y(new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s)),Math.max(0,a-Date.now()));u.signal.addEventListener("abort",X,{once:!0}),u.signal.aborted&&X(),i.then(l,Y)})}function qe(i){return new Promise(a=>{let s=()=>{clearTimeout(D),u.signal.removeEventListener("abort",s),a()},D=setTimeout(s,i);u.signal.addEventListener("abort",s,{once:!0}),u.signal.aborted&&s()})}function he(i,a){I();let s=z.get(i)??t.pendingCommands?.find(f=>f.requestId===i)??t.pendingCommand;if(s?.operation==="submit"&&s.requestId===i&&s.nodeId===n&&s.visit===g){a.type==="paywall_quote"&&s.input.type==="paywall_quote"&&s.input.predecessor&&!a.predecessor&&(a={...a,predecessor:s.input.predecessor});let f=tn.parse(s),F=tn.parse({...s,input:a});if(f.operation!=="submit"||F.operation!=="submit"||JSON.stringify(f.input)!==JSON.stringify(F.input))throw new w("CONFLICT","A purchase request cannot change its input");return z.set(i,f),f}let D=t.view;if(!D||D.nodeId!==n||D.visit!==g||D.paywall?.receiptId!==R)throw new w("PRECONDITION_FAILED","The Paywall visit has changed");let m=tn.parse({operation:"submit",requestId:i,nodeId:n,visit:g,revision:D.revision,input:structuredClone(a)});if(m.operation!=="submit")throw new w("INVALID_REQUEST","A purchase submission is required");return z.set(i,m),m}async function we(i,a){I();let{requestId:s,input:D}=i,m=Date.now()+3e4;U.add(s);try{let f=await O(t.submit(i),m,s);for(;f.run.pendingRequest?.requestId===s&&Date.now()<m&&!E&&(await qe(Math.min(1e3,m-Date.now())),!(E||Date.now()>=m));)f=await O(t.resume(s),m,s);if(E)throw new w("IDENTITY_CHANGED","Paywall presentation has closed");if(f.run.pendingRequest?.requestId===s)throw new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s);if(!K(f,a,D.type==="paywall_confirm"||D.type==="paywall_cancel"?D.operationId:void 0))throw new w("PRECONDITION_FAILED","The purchase selection has changed");M===s&&(M=null)}catch(f){if(M=s,D.type==="paywall_quote"&&t.settle&&!E&&f instanceof w&&f.status!==void 0&&![401,425].includes(f.status)&&!f.retryable&&f.recovery!=="recover_operation")try{if((await O(t.settle(s),m,s)).settlement?.state==="settled"){let l=await O(t.get(),m,s);K(l,a)&&l.run.paywall?.purchaseRequestId===s&&o.canReselect===!0&&z.delete(s)}}catch{}throw f instanceof w&&f.code==="COMMAND_PENDING"&&f.status===void 0&&z.delete(s),f}finally{U.delete(s)}}async function W(i){if(!o.quote)throw new w("INVALID_REQUEST","A quoted purchase is required");let a=i==="confirm"?"paywall_confirm":"paywall_cancel",s=[...z.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(m=>m.operation==="submit"&&m.input.type===a&&"operationId"in m.input&&m.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 we(he(D,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId,...i==="confirm"&&o.quote.merchantTerms?{merchantConfirmation:Tn(o.quote.merchantTerms)}:{}}),T),!o.operation)throw new w("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let le={get view(){return structuredClone(c())},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??b.locale},get canReselect(){return o.canReselect===!0&&M===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=xe({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??M??q,pending:U.size>0||i.length>0||M!==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===g&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return E?()=>{}:(G.add(i),()=>G.delete(i))},async refresh(){I();let i=T,a=await t.get();if(K(a,i),a.run.paywall?.receiptId!==R)throw new w("PRECONDITION_FAILED","Paywall presentation has changed");return N()},preview(i){let a=c();if(!a)return Promise.reject(new w("PRECONDITION_FAILED","Load the Paywall presentation first"));if(q&&q!==i.requestId&&(ne||o.canReselect!==!0))return Promise.reject(new w("COMMAND_PENDING","Retry the original purchase before starting another"));let s=a.document.buttons[i.actionId],D=s?.type==="checkout"?Sn(s.product,i.selection,a.capabilities):null;if(!D)return Promise.reject(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let m=Fn(a.document.screen,D,i.selection,a.capabilities),f=q!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0,F=t.view?.parameters.commerce;if(F&&typeof F=="object"&&!Array.isArray(F)&&F.intent==="subscription_change"&&!i.subscriptionChange)return Promise.reject(new w("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(i.subscriptionChange&&i.nativeOffer)return Promise.reject(new w("INVALID_REQUEST","A web membership change cannot include a store offer"));if(f&&o.canReselect!==!0)return Promise.reject(new w("COMMAND_PENDING","Original purchase requires authoritative termination"));let l;try{l=he(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:D,...Object.keys(m).length?{featureQuantities:m}:{},...f?{predecessor:f}:{},...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&&ne)return ne;q!==i.requestId&&T++;let Y=T;q=i.requestId;let X=(async()=>{if(await we(l,Y),!o.quote)throw new w("INVALID_RESPONSE","The accepted quote is missing");return Un(o.quote,{productVersionId:D,featureQuantities:m,subscriptionChange:i.subscriptionChange},"The selected purchase changed"),structuredClone(o.quote)})();return ne=X,X.then(()=>{ne===X&&(ne=null)},j=>{ne===X&&(ne=null),q===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&j instanceof w&&j.status!==void 0&&j.status<500&&![401,425].includes(j.status)&&(q=null)}),X},confirm:()=>W("confirm"),cancel:()=>W("cancel"),async read(){if(I(),!o.quote)throw new w("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,a=T,s=t.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.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});I();let m=Q(D);if(m?.quote&&m.quote.operationId!==i||m?.operation&&m.operation.operationId!==i)throw new w("INVALID_RESPONSE","Purchase operation changed");let f=K(D,a,i),F=f?o.operation:m?.operation;if(!F)throw new w("INVALID_RESPONSE","The current purchase result is missing");return f&&U.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(M=null),structuredClone(F)},destroy(){E=!0,L(),G.clear(),u.abort(),z.clear()}},L=t.subscribe(i=>{E||i.nodeId!==n||i.visit!==g||i.paywall?.receiptId!==R||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(C(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},y())});return{session:le,load:N}}function it(t){let b=new Set,R=new Set,n=null;async function g(c,C){let E=!1;for(;!t.stopped&&t.key===c&&t.client.pendingCommand?.requestId===C;){if(!t.client.settle)throw new w("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(C),E=!0,t.client.pendingCommand?.requestId===C&&await new Promise(G=>setTimeout(G,1500))}t.stopped||t.key!==c||(E&&await t.client.get(),!(t.stopped||t.key!==c)&&b.add(c))}function S(c,C){n=C;let E=()=>{n===C&&(n=null),R.delete(c)};return C.then(E,G=>{E(),t.busy||t.fail(G)}),C}function o(c){if(t.reviewing||b.has(c)||R.has(c)||t.stopped)return;R.add(c);let C=async()=>{if(t.reviewing||t.stopped||t.key!==c||b.has(c)){R.delete(c);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{C()},250);return}let E=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==c)return;if(t.client.pendingCommand){setTimeout(()=>{C()},250);return}}let G=t.client.view,re=t.expected(),y=re.requestId;try{await t.client.submit({operation:"shown",...re})}catch(N){if(!(N instanceof w)||N.code!=="CONFLICT"||N.status!==409||t.client.pendingCommand)throw N;await t.client.get();let u=t.client.view;if(t.stopped||t.reviewing||t.key!==c||!u||!G||u.id!==G.id||u.source.versionId!==G.source.versionId||u.nodeId!==re.nodeId||u.visit!==re.visit||u.revision<=re.revision||u.stopped||!u.screen&&(!u.paywall||u.paywall.receiptId!==G.paywall?.receiptId)||!["running","waiting"].includes(u.status)||t.client.pendingCommand)throw N;let d=t.expected();y=d.requestId,await t.client.submit({operation:"shown",...d})}await g(c,y)})();S(c,E)};C()}function _(){if(n)return n;let c=t.client.pendingCommand;if(c?.operation!=="shown")return null;let C=t.key;return R.add(C),S(C,(async()=>{await t.client.retry(),await g(C,c.requestId)})())}return{report:o,settled:_,get inFlight(){return n}}}function rt(t){let b={},R=new Map;async function n(g){let S=t.client.view,o=S?.screen,_=o?.customerData.nodes[g.nodeId];if(t.stopped||t.busy||!S||!o||!_)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(g.action)){let N=t.document,u=N?An(N,g.nodeId):null,d=u?.type==="customer_data"?u.data.outputs?.[g.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:g.value?{[g.nodeId]:g.value}:{}}})):await t.onIntent?.(g,S);return}let C=g.action.startsWith("sources_")?_.resources.find(N=>N.key===g.value):null;if(g.action.startsWith("sources_")&&!C)throw new w("INVALID_REQUEST","Choose a current resource");let E=`${S.visit}:${g.nodeId}:${C?.key??""}`,G=R.get(E)??[null],y=b[g.nodeId]??{page:1,after:null,filter:"all",...C?{resourceKey:C.key}:{}};if(g.action==="filter"){let N=g.value;if(!N||!(_.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(N))throw new w("INVALID_REQUEST","Unknown data filter");y={page:1,after:null,filter:N},G.splice(0,G.length,null)}else if(g.action==="next"||g.action==="sources_next"){let N=C?.sources.at(-1),u=C?N?{kind:"ledger",cursor:{at:N.detail[0],id:N.id,type:"source"}}:null:o.dataCursors[g.nodeId];if(!u||!C&&!_.hasNext)return;G[y.page]=u,y={...y,page:y.page+1,after:u}}else if(g.action==="previous"||g.action==="sources_previous"){if(y.page<=1)return;y={...y,page:y.page-1,after:G[y.page-2]??null}}R.set(E,G),b={...b,[g.nodeId]:y},await t.perform(()=>t.client.get({nodeId:S.nodeId,visit:S.visit,revision:S.revision,components:b}))}return{get queries(){return b},intent:n,reset(){b={},R.clear()}}}function ot(t){let{doc:b,holder:R,reviewHolder:n,mountScreenPreview:g}=t,S=!1,o,_=0,c=null,C="",E,G=new Map,re=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function y(u){if(t.stopped||!t.client.review||S&&u===o&&E?.active)return;let d=!S||u!==o;S||(C=re(t.client.view),G.set(C,structuredClone(t.answers))),S=!0,o=u,R.hidden=!0,t.suspend(!0),n.hidden=!1;let q=++_;d&&(E?.finish("dismissed"),c?.destroy(),c=null,n.replaceChildren(),E=rn(n,t.loadingOptions,"funnel",()=>{N()}));let T=d?E:void 0;try{if(T?.start(!1,t.client.view?.locale),q!==_||t.stopped)return;let ne=t.client.review(u),U=await(T?.wait(ne,He)??ne);if(t.stopped||q!==_||!S)return;if(!U.review)throw new w("INVALID_RESPONSE","Historical projection is missing");c?.destroy(),c=null,T||n.replaceChildren();let M=b.createElement("div"),z=T?on(M,n):()=>{};n.append(M);let Q=U.run.locale.startsWith("zh"),I=t.chrome;M.style.cssText=I.history;let K=b.createElement("p");K.textContent=Q?"只读回看":"Read-only history",K.style.cssText=I.historyTitle,M.append(K);let O=b.createElement("p");O.style.cssText=I.historyNote,O.textContent=U.review.pages.length?Q?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":Q?"还没有可回看的页面。":"There are no earlier pages yet.",M.append(O);let qe=U.review.page?.receiptId,he=b.createElement("div");he.style.cssText=I.historyPages;for(let[le,L]of U.review.pages.entries()){let i=b.createElement("button");i.type="button",i.textContent=Q?`第 ${le+1} 页`:`Page ${le+1}`;let a=qe!==void 0&&L.receiptId===qe;i.style.cssText=a?I.primary:I.secondary,a&&i.setAttribute("aria-current","page"),Ge(i,()=>t.chrome.focus),i.onclick=()=>{y(L.receiptId)},he.append(i)}if(he.childElementCount&&M.append(he),U.review.page){let le=U.review.page,L=b.createElement("div");L.inert=!0,L.style.cssText=I.historyPage,M.append(L),c=g(L,{mode:"live",rendererUrl:t.client.webViewUrl,title:le.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{q===_&&!t.stopped&&T?.present(z)},onError:a=>{if(q!==_||t.stopped)return;let s=new Error(a);T?.finish("error",s),c?.destroy(),c=null,M.remove(),t.fail(s)},onEscape:()=>{N()}});let i=c;if(i.update(le.document,U.run.locale,{serverInput:{bindings:le.inputs,answers:le.answers,values:le.values}}),await i.ready,t.stopped||q!==_||!S)return}let we=Q?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},W=b.createElement("div");W.style.cssText=I.historyRecords;for(let le of[...U.review.coupons.map((L,i)=>`${Q?"优惠券":"Coupon"} ${i+1}: ${we[L.status]}`),...U.review.purchases.map((L,i)=>`${Q?"购买":"Purchase"} ${i+1}: ${et(L.status,Q)}`)]){let L=b.createElement("p");L.textContent=le,L.style.margin="0",W.append(L)}W.childElementCount&&M.append(W),U.review.page||T?.present(z),t.client.view&&await t.enqueue(t.client.view)}catch(ne){if(q!==_||t.stopped)return;T?.finish("error",ne),c?.destroy(),c=null,n.replaceChildren(),t.fail(ne)}}async function N(){if(!S||t.stopped||!t.client.review)return;let u=++_;E?.finish("dismissed");try{if(await t.client.review(),t.stopped||u!==_)return;S=!1,_++,E?.finish("dismissed"),c?.destroy(),c=null,n.replaceChildren(),n.hidden=!0,R.hidden=!1;let d=t.client.view;re(d)!==C?(G.set(C,structuredClone(t.answers)),t.resetScreen()):(G.delete(C),t.suspend(!1)),d&&await t.enqueue(d)}catch(d){if(u!==_||t.stopped)return;c?.destroy(),c=null,n.replaceChildren(),t.fail(d)}}return{get active(){return S},get receipt(){return o},open:y,exit:N,get drafts(){return new Map([...G].map(([u,d])=>[u,structuredClone(d)]))},stop(){S=!1,_++,E?.finish("dismissed"),c?.destroy(),c=null,n.replaceChildren(),n.hidden=!0,R.hidden=!1}}}var gn=5e3;async function pt(t,b,R){let n=b,g=n.prepared&&nt(n.prepared),S=()=>{};function o(){n.prepared&&n.prepared.state!=="adopted"&&g?.release()}let _=()=>n.prepared?.state==="shown"&&!!g?.modal,c=n.client.identitySignal,C;try{C=await Promise.all([import("./screen-renderer-CMFJVI36.js"),import("./paywall-4YXZP2TO.js")]),n.signal?.throwIfAborted(),c?.throwIfAborted()}catch(e){throw o(),e}let[{mountScreenPreview:E},{showPaywall:G}]=C,re=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?tt({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;re?.start();let y=t.ownerDocument,N=Jn(y),u=!1,d=y.createElement("section"),q=y.createElement("div"),T=y.createElement("div"),ne=y.createElement("div"),U=y.createElement("button");ne.hidden=!0,U.type="button";let M=y.createElement("p"),z=y.createElement("p"),Q=y.createElement("button"),I=y.createElement("button"),K=y.createElement("button"),O=y.createElement("dialog"),qe,he=!1;d.dataset.indianaFunnel="",d.dataset.longplayCloseOwner="sdk",d.setAttribute("aria-busy","false"),M.setAttribute("role","status"),z.setAttribute("role","alert"),z.hidden=!0,Q.type=I.type=K.type="button",T.append(Q,U,M,z,K,I),d.append(q,ne,T),t.append(d);let we=Wn,W=wn(we),le="",L=(y.documentElement.lang||"").startsWith("zh"),i,a="",s;for(let e of[Q,U,K,I])Ge(e,()=>W.focus);function D(){let e=L?"关闭":"Close";I.parentElement===O?(I.textContent="×",I.setAttribute("aria-label",e),zn(I,we)):(I.textContent=e,I.removeAttribute("aria-label"),I.style.cssText=W.link+";margin-inline-start:auto")}function m(e){let r=e?.screen?.content.document.theme??we,p=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,I.parentElement===O]);if(p===le)return;le=p,we=r;let H=I.parentElement===O;W=wn(we,H),d.style.cssText=W.root+";min-width:0"+(H?";display:flex;flex-direction:column;min-height:100%":""),T.style.cssText=W.bar+(H?";margin-top:auto":""),T.hidden&&(T.style.display="none"),Q.style.cssText=U.style.cssText=W.secondary,K.style.cssText=W.primary,M.style.cssText=W.status,z.style.cssText=W.alert,D(),yn(Q)}function f(){T.hidden=Q.hidden&&U.hidden&&K.hidden&&z.hidden&&!M.textContent&&(I.hidden||I.parentElement!==T),T.style.display=T.hidden?"none":"flex",i?.responsive&&s!==void 0&&i.setContentHeight(s+T.getBoundingClientRect().height)}m();let F=null,l=null,Y=null,X="",j="",ge=!1,Qe="",sn="",ze="",h=!1,ue=0,Je=!1,vn="",an=null,ln=Promise.resolve(),In=!n.client.view,Ve,J=R,Se,Ue,je="",Be,pe=!1,De=null,ve=!1,We=()=>n.client.pendingCommand?.operation==="close",fe=null,ee=null,un=xn({document:y,run:async()=>{(!l?.observing||n.client.pendingCommand)&&await cn()},delay:()=>{if(!me.pending&&!(h||!Y||!["running","waiting"].includes(Y.status)&&!n.client.pendingCommand)&&!(l?.observing&&!n.client.pendingCommand))return Y.pendingRequest||n.client.pendingCommand?1500:gn},hiddenDelay:()=>!h&&!me.pending&&n.client.pendingCommand?15e3:void 0}),te=null;function dn(){return ee&&n.client.hasDurableJournal===!0&&te?.acknowledged===!0&&te.operationId===ee.operationId&&n.client.view?.id===te.runId&&n.client.view?.status==="closed"&&n.client.view.revision===te.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?ee:null}function bn(e){let r=e.run.paywall;if(te&&e.settlement?.requestId===te.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===te.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===te.revision+1&&e.run.nodeId===te.nodeId&&e.run.visit===te.visit&&r?.receiptId===te.receiptId&&r.selectionGeneration===te.selectionGeneration&&(r.quote?.operationId??null)===te.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===te.operationId){let p=te.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,H=xe({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(p||r.canReselect===!0&&H.type==="native")&&(te.acknowledged=!0)}}let ke=null,Me=new Set,Ie={},Fe=!1,de=(e,r=null)=>{h||(e instanceof w&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&un.destroy(),ke=r,Fe=!1,z.textContent=Yn(e,L),z.hidden=!1,K.hidden=n.client.pendingCommand===null,f(),Pe(n.onError,e))},me=On({client:n.client,document:y,conceal(){h||(be(),J?.finish("dismissed"),d.hidden=!0,u||(u=!0,N()))},async receive(e){h||await ye(n.client.view??e.run)},failed(e){if(!h){if(!me.pending){ve=!1;let r=n.client.view;r&&ye(r).then(()=>de(e),de);return}Ke(),d.parentElement!==t&&t.append(d),d.hidden=!1,Q.hidden=U.hidden=I.hidden=!0,M.textContent="",m(),de(e,n.client.pendingCommand?.requestId??null)}}}),Cn=()=>{h||(ke=null,z.textContent=Zn(L),z.hidden=!1,K.hidden=!0,f())};function Te(){let e=n.client.view;if(!e)throw new w("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let A=ot({client:n.client,doc:y,holder:q,reviewHolder:ne,mountScreenPreview:E,loadingOptions:n,get chrome(){return W},get stopped(){return h},get answers(){return Ie},suspend(e){l?.setSuspended(e)},resetScreen(){X="",j="",Qe=""},enqueue:ye,fail:de}),$e=it({client:n.client,expected:Te,fail:de,get stopped(){return h},get reviewing(){return A.active},get key(){return X},get busy(){return ue},get staleRead(){return an}}),Ye=rt({client:n.client,expected:Te,perform:Oe,onIntent:n.onCustomerDataIntent,get stopped(){return h},get busy(){return ue},get document(){return F?.document},get answers(){return Ie}}),Xe=e=>`${e.id}:${e.nodeId}:${e.visit}`,Ne=e=>e&&(e.screen||e.paywall)?Xe(e):"";function Re(){let e=n.client.view;Q.disabled=!A.active&&(ue>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!Ne(e)||j!==Ne(e)),Q.hidden=!A.active&&!e?.canBack,yn(Q);let r=!!l&&!A.active;I.hidden=r&&!J?.active||he&&!A.active,U.hidden=!n.client.review||!A.active&&!e?.canBack;let p=e?.locale.startsWith("zh");M.textContent=r?"":ue>0||e?.pendingRequest?p?"正在处理":"Processing":e?.instruction?.type==="wait"?p?"等待中":"Waiting":"",f()}async function Pn(e){if(!e)return;let r=n.client.view;await e;let p=n.client.view;if(!r||!p||p.id!==r.id||p.nodeId!==r.nodeId||p.visit!==r.visit||p.stopped||!["running","waiting"].includes(p.status))throw new w("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Oe(e,r=!1,p){if(!((ue||ve||fe||ee)&&!r||h||A.active&&!r)){ue++,d.setAttribute("aria-busy","true"),z.hidden=!0,ke=null,Fe=!1,Re();try{if(r||await Pn($e.inFlight),h)return;let H=await e();h||await ye(n.client.view??H.run)}catch(H){p?.(H)&&n.client.pendingCommand===null?Cn():me.pending||de(H,n.client.pendingCommand?.requestId??null)}finally{ue=Math.max(0,ue-1),d.setAttribute("aria-busy",String(ue>0)),h||(K.hidden=n.client.pendingCommand===null,Re())}}}function _e(){un.schedule()}async function cn(){if(!(h||Je||ue)&&!me.pending){if(A.active){await A.open(A.receipt);return}Je=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let r=n.client.view,p=Ye.queries,H=await n.client.get(r?.screen&&Object.keys(p).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:p}:void 0);Fe&&!h&&(Fe=!1,z.hidden=!0,f()),!h&&p===Ye.queries&&await ye(n.client.view??H.run)}catch(e){de(e),Fe=!h}finally{Je=!1}}}function Ze(e,r,p){if(J?.active){let ce=J;return ce.setDismissHandler(()=>Rn(ce)),ce}let H=rn(t,n,"funnel",()=>Rn(H),Bn);return J=H,H.start(e,r,p),H}function Rn(e){h||pe||(pe=!0,e.finish("dismissed"),be(),d.hidden=!0,n.client.view?Ee().finally(oe):oe())}function pn(){clearTimeout(Be?.timeout),Be=void 0}function be(e){he=!1,pn(),Se?.abort(),Se=void 0,F?.destroy(),F=null,l?.destroy(),l=null,Ve=void 0,Ue?.(),Ue=void 0,O.open&&O.close();for(let r of Array.from(q.children))(!e||!r.contains(e))&&r.remove();q.style.cssText="",s=void 0,X="",j="",ge=!1,Qe="",ze=""}function En(){let e=y.defaultView;i?.responsive&&e&&F?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ke(){i?.destroy(),i=void 0,a=""}function en(e){let r=e.screen?.presentation;if(!r||r.type==="inline"){O.open&&O.close(),Ke(),I.parentElement!==T&&T.append(I),d.parentElement!==t&&t.append(d);for(let ce of["flex","display","flex-direction","justify-content"])q.style.removeProperty(ce);m(e),f();return}d.parentElement!==O&&(O.append(I,d),t.append(O)),q.style.flex="1 0 auto",q.style.display="flex",q.style.flexDirection="column",q.style.justifyContent="center",m(e);let p=e.screen.content.document,H=JSON.stringify([r,le]);if(H!==a){Ke(),a=H;let ce={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:${we.background};color:${we.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ce[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=Gn(O,{presentation:r,theme:p.theme,pages:p.pages},En),i.latch()}f(),O.setAttribute("aria-label",(qe?.screen===e.screen?.content.document.name?qe?.label:void 0)??F?.document?.name??e.screen?.content.document.name??"Funnel")}async function st(e){if(h||pe)return;if(me.observe(),me.pending){Y=e;return}if(ve&&(We()||["running","waiting"].includes(e.status))||(Y=e,ke&&n.client.pendingCommand?.requestId!==ke&&(z.hidden=!0,ke=null),L=e.locale.startsWith("zh"),U.textContent=L?"回看":"History",Q.textContent=A.active?L?"返回当前":"Return to current":L?"返回":"Back",D(),K.textContent=L?"重试":"Retry",K.hidden=n.client.pendingCommand===null,Re(),vn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(vn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Pe(n.onState,structuredClone(e))),h||pe))return;if((!e.pendingRequest||ve&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){oe();return}if(e.stopped&&_()){oe();return}if(e.stopped||n.client.configurationReady===!1){A.stop(),o(),be(),J?.finish("skipped"),d.hidden=!0,_e();return}if(d.hidden=!1,A.active){_e();return}if(e.status==="completed"&&l?.subscriptionUpgradeActive){_e();return}let r=Ne(e),p=n.client.view;if(p&&p.revision>e.revision&&Ne(p)!==r)return;let H=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);r!==X&&(X&&J?.finish("dismissed"),be(),X=r,Ie={...e.answers},Ye.reset());let ce=Xe(e);if(je===ce){d.hidden=!0;return}if(H&&!r){d.hidden=!0;let $=n.prepared?.state==="shown"?null:Ze(!0,e.locale);!h&&!pe&&Be?.key!==ce&&(pn(),Be={key:ce,timeout:setTimeout(()=>{let v=n.client.view;if(h||!$?.active&&n.prepared?.state!=="shown"||!v||Xe(v)!==ce)return;je=ce;let B=new Error("Funnel screen preparation timed out");$?.finish("error",B),o(),be(),de(B)},He)}),_e();return}pn();let Z=$=>{let v=n.client.view;return!h&&!pe&&!De&&!$.aborted&&n.client.configurationReady!==!1&&!!v&&!v.stopped&&!["closed","ineligible","failed"].includes(v.status)&&(Ne(v)===r||v.status==="completed"&&l?.subscriptionUpgradeActive===!0)},Ce=($,v)=>{Z(v)&&(je=r,J?.finish("error",$),be(),d.hidden=!0,de($))};if(r||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&o(),en(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&J?.finish("skipped")),e.screen){o();let $=e.screen.content;if(!F){let se=e.screen.presentation.type!=="inline",x=Ze(se,e.locale);if(h||pe)return;let ie=(Se=new AbortController).signal;en(e),Ue=se?jn(O):on(d,t),F=E(q,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...$.document.actions.filter(V=>V.type==="event"&&V.close).map(V=>V.id)])),onAuthoredClose(V){Z(ie)&&(he=V,Re())},rendererUrl:n.client.webViewUrl,title:$.document.name,...se?{hostPresentation:()=>i?.type??e.screen.presentation.type}:{},onResize:V=>{s=V,i?.responsive&&i.setContentHeight(V+T.getBoundingClientRect().height)},onAction(V,P={},Ae={}){if(A.active||!Z(ie)||j!==r)return;Ie={...Ie,...Ae};let fn=e.screen?.inputs??[],kn=Object.fromEntries(fn.filter(({variable:Le})=>Object.hasOwn(Ie,Le)).map(({variable:Le})=>[Le,Ie[Le]]));if(Kn(fn,kn).length){Cn();return}Oe(()=>n.client.submit({operation:"submit",...Te(),input:{type:"screen",output:V,answers:kn,selection:P}}),!1,Le=>Xn(Le,fn))},onAnswers:V=>{A.active||!Z(ie)||j!==r||(Ie={...Ie,...V})},onCustomerDataIntent:V=>{A.active||!Z(ie)||j!==r||Ye.intent(V).catch(de)},onEscape:()=>{!Z(ie)||j!==r||A.active||fe||ee||Ee()},onError:V=>{let P=new Error(V);j===r?de(P):Ce(P,ie)},onRendered:V=>{if(!(!Z(ie)||j===r))try{x.present(P=>{Ue?.(),Ue=void 0,V&&(qe={screen:$.document.name,label:V},O.setAttribute("aria-label",V)),se&&(O.showModal(),u=!1,i?.responsive&&O.focus({preventScroll:!0}),!P&&n.loading!=="host"&&Qn(O,i?.type??e.screen.presentation.type,i?.responsive)),j=r,ge=se,Re()}),Z(ie)&&$e.report(r)}catch(P){Ce(P,ie)}}}),En()}let v={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:Ie,values:e.screen.values}},B=JSON.stringify([$,e.locale,v.parameters,e.screen.inputs,e.screen.values]);if(B!==Qe)F.update($.document,e.locale,v),Qe=B,sn=JSON.stringify(v.capabilities),ze=JSON.stringify(v.customerData);else{let se=JSON.stringify(v.capabilities);se!==sn&&(F.updateCapabilities(v.capabilities),sn=se),JSON.stringify(v.customerData)!==ze&&(F.updateCustomerData(v.customerData),ze=JSON.stringify(v.customerData))}let ae=F;if(ae)try{await(J?.wait(ae.ready)??ae.ready)}catch(se){Se&&Ce(se,Se.signal)}}else if(e.paywall&&!l){let $=e.paywall.resolution,v="document"in $?$.document:null,B=g,ae=n.mountPaywallControls,se=null,x=(Se=new AbortController).signal,ie={loading:"host",signal:x,...ae&&{mountControls:P=>ae(P,e)},canInteract:()=>Z(x)&&!A.active&&!fe&&!ee,beforeAction:async()=>{ue++;try{await Pn($e.settled()),z.hidden=!0,ke=null,Fe=!1,f()}finally{ue=Math.max(0,ue-1)}},start:()=>hn(n.client),onObservationChange:_e,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,beforeCheckoutReplacement:n.beforeCheckoutReplacement,purchaseConfirmation:n.purchaseConfirmation,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"}):y.defaultView?.location.assign(P),onAction:async P=>{if(A.active)return;let Ae=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 ye(n.client.view??Ae.run)},onError:P=>{j===r?de(P):Ce(P,x)}},V={quoteError:P=>Pe(n.onError,P),loadingLayout:()=>Z(x)?se?.getLoadingLayout?.():void 0,present(P){Z(x)&&(se?.present(Ae=>{P(Ae),j=r,ge=!!q.querySelector("dialog[open]"),ge&&(u=!1),Re()}),Z(x)&&$e.report(r))},async closeAction(P){h||A.active||await me.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(h||x.aborted||A.active||fe||ee||!ve&&!Z(x))return;ve=!0;let P=n.client.view;if(P?.status==="completed"&&l?.subscriptionUpgradeActive){Me.add(`complete:${P.id}`),Pe(n.onComplete,structuredClone(P)),oe();return}if((n.resumeCheckout||n.terminateCheckout)&&dt()){Y=n.client.view,oe();return}await Ee()}};if(B&&ae)o();else if(B){let P=await B.adopt(e,{options:ie,handoff:V,start:()=>hn(n.client)});P&&Z(x)&&!h?(en(e),l=P,Ve={runId:e.id,receiptId:e.paywall.receiptId},J?.active&&J.present(()=>{}),j=r,ge=B.modal,ge&&(u=!1),Re(),$e.report(r),A.active&&l.setSuspended(!0)):(P?.destroy(),o())}if(h||pe)return;if(!l){if(se=Ze(!0,e.locale,v),h||pe)return;en(e);let P=await G(q,ie,V).catch(Ae=>(Ce(Ae,x),null));!Z(x)&&!(ve&&!h&&!x.aborted)?P?.host?.destroy():P&&(l=P.host,l&&(Ve={runId:e.id,receiptId:e.paywall.receiptId}),l?.setSuspended(A.active))}}if(h||pe)return;Re();let k=e.instruction;if(k&&(k.type==="open_url"||k.type==="event")&&!Me.has(k.receiptId)){let $=y.createElement("button");$.type="button",$.style.cssText=W.primary,Ge($,()=>W.focus),q.style.cssText=W.stage,$.textContent=k.type==="open_url"?`${L?"前往":"Continue to"} ${new URL(k.url).host}`:L?"继续":"Continue",$.onclick=()=>{let v=Te(),B=k.type==="open_url"&&!n.onOpenUrl&&k.openIn==="new_window"?at(k.url):null;Oe(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(x){Pe(n.onError,x),ae="failed"}else ae=k.openIn==="new_window"&&!B?"failed":"opened";if(k.type==="event"){if(!n.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(k.event)}if(h||n.client.view?.nodeId!==v.nodeId||n.client.view.visit!==v.visit)throw new w("PRECONDITION_FAILED","The client action visit changed");let se=await n.client.submit({operation:"submit",...v,input:{type:"client_action",receiptId:k.receiptId,outcome:ae}});return Me.add(k.receiptId),k.type==="open_url"&&!n.onOpenUrl&&k.openIn==="same_window"&&y.defaultView?.location.assign(k.url),se})},J?.active?J.present(()=>q.replaceChildren($)):q.replaceChildren($)}!e.pendingRequest&&e.status==="completed"&&!Me.has(`complete:${e.id}`)&&(Me.add(`complete:${e.id}`),Pe(n.onComplete,structuredClone(e))),_e()}function at(e){let r=y.defaultView?.open(e,"_blank")??null;return r&&(r.opener=null),r}function ye(e){return Re(),ln=ln.catch(()=>{}).then(async()=>{try{await st(e)}catch(r){throw J?.active&&(je=Xe(e),J.finish("error",r),be(),d.hidden=!0),r}}),ln}let lt=n.client.subscribe(e=>{if(!In){if(e.stopped&&(ge||_())&&!ve){Y=e,oe();return}!ve&&(e.stopped||n.client.configurationReady===!1||X&&j!==X&&(Ne(e)!==X||["closed","ineligible","failed"].includes(e.status)))&&(be(),J?.finish("dismissed"),d.hidden=!0),ye(e).catch(de)}}),ut=n.client.subscribeError?.(e=>{me.pending||de(e)});function dt(){let e=n.client.view,r=e?.paywall;return!!r?.operation&&!!e&&["running","waiting"].includes(e.status)&&_n(xe({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function Ee(e){if(De)return De;if(h||!e&&(fe||ee))return Promise.resolve();let r=!e&&We();return!r&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(Y=n.client.view,oe(),Promise.resolve()):(De=Oe(async()=>{let p=r?await n.client.retry():await(e?n.client.submit.bind(n.client):me.submit)({operation:"close",...e??Te()});return e&&bn(p),p},!0).then(()=>{let p=n.client.view;p?.status==="closed"&&!We()&&(Y=p,oe())}).finally(()=>{De=null}),De)}function oe(){qn()}function qn(e){re?.destroy(),!h&&(h=!0,me.destroy(),S(),o(),n.signal?.removeEventListener("abort",oe),c?.removeEventListener("abort",oe),J?.finish("dismissed"),un.destroy(),lt(),ut?.(),be(e),Ke(),A.stop(),O.remove(),!e||!d.contains(e)?d.remove():(T.remove(),ne.remove()),!e&&!u&&N(),Pe(n.onDismiss,Y?structuredClone(Y):null))}Q.onclick=()=>{if(!Q.disabled){if(A.active){A.exit();return}Oe(()=>n.client.submit({operation:"back",...Te()}))}},U.onclick=()=>{A.open()},I.onclick=()=>{J?.active?J.dismiss():fe||Ee()},K.onclick=()=>{me.pending?me.retry().catch(()=>{}):We()?Ee():Oe(()=>n.client.retry())},O.addEventListener("cancel",e=>{e.preventDefault(),J?.active?J.dismiss():fe||Ee()}),n.signal?.addEventListener("abort",oe,{once:!0}),c?.addEventListener("abort",oe,{once:!0});let nn=!1;g&&(S=g.onClose(()=>{h||pe||(pe=!0,J?.finish("dismissed"),be(),d.hidden=!0,n.client.view?Ee().finally(oe):nn=!0)}));let Dn={destroy:oe,refresh:cn,get recoveryPaywall(){if(l&&Ve)return{...Ve,view:l.currentResolution}},setPurchaseRecovery(e,r){return l?.setPurchaseRecovery(e,r),l!==null},retainPurchaseDialog(){let e=l?.retainPurchaseDialog();if(e)return l=null,qn(e.dialog),{dialog:e.dialog,release(){e.release(),d.remove(),u||N()}}},get recovery(){let e=dn();if(e)return e;if(!h&&!ue&&!ve&&!fe&&l){let r=l.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??ee?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(fe)return fe;let e=dn();if(e)return Promise.resolve(e);let r=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??ee?.operationId??null,p=()=>({type:"recover",operationId:r,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let k=l?.recovery;return Promise.resolve(k&&k.type!=="native"&&k.type!=="cancel"?k:p())}let H=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(k=>k.operation==="close");if(h&&!(H||ee&&n.client.view?.status==="closed")||ue||Je||De||A.active||!l&&!ee&&!H)return Promise.resolve(p());let ce=l,Z=(async()=>{try{if(!ee&&H){let v=await n.client.retry();return await ye(n.client.view??v.run),p()}if(!ee){let v=await ce.prepareFallback();if(v.type!=="native")return v;if(n.client.hasDurableJournal!==!0)return p();ee=v}let k=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(k.length){let v=k.find(ae=>ae.operation==="close");if(!v||!te||v.requestId!==te.requestId)return p();let B=await n.client.retry();bn(B),await ye(n.client.view??B.run)}else{let v=n.client.view,B=v?.paywall;if(!v||!B||B.selectionGeneration===void 0||(B.quote?.operationId??null)!==ee.operationId||ee.operationId!==null&&B.canReselect!==!0)return p();let ae=B.selectionGeneration,se=await n.client.get();await ye(n.client.view??se.run);let x=n.client.view,ie=x?.paywall;if(!x||!ie||!["running","waiting"].includes(x.status)||x.stopped||x.id!==v.id||x.nodeId!==v.nodeId||x.visit!==v.visit||ie.receiptId!==B.receiptId||ie.selectionGeneration!==ae||(ie.quote?.operationId??null)!==ee.operationId||ee.operationId!==null&&ie.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return p();let V=Te();te={runId:x.id,operationId:ee.operationId,revision:V.revision,requestId:V.requestId,nodeId:x.nodeId,visit:x.visit,receiptId:ie.receiptId,selectionGeneration:ae,acknowledged:!1},await Ee(V)}let $=dn();return $?(oe(),$):p()}catch(k){return de(k),p()}})();fe=Z;let Ce=()=>{fe===Z&&(fe=null)};return Z.then(Ce,Ce),Z},review:A.open,exitReview:A.exit,get unappliedDrafts(){return A.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??gn)>=gn||e.instruction?.type==="evaluate_segment")&&(an=cn().finally(()=>{an=null})),await ye(e);else{if(d.hidden=!0,h)throw new DOMException("Presentation cancelled","AbortError");let r=nn||n.prepared?.state==="shown"?null:Ze(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(h||pe&&!nn)throw new DOMException("Presentation cancelled","AbortError");let p=n.client.get(),H=await(r?r.wait(p,He):ft(p,He));if(In=!1,nn)return h||await Ee().finally(oe),Dn;await ye(n.client.view??H.run)}}catch(e){throw J?.finish("error",e),oe(),e}return Dn}function ft(t,b){let R;return Promise.race([t,new Promise((n,g)=>{R=setTimeout(()=>g(new Error("Presentation data timed out")),b)})]).finally(()=>clearTimeout(R))}function ei(t,b,R){return pt(t,b,R)}export{pt as a,ei as b};
@@ -1 +0,0 @@
1
- import{b as xe}from"./chunk-PVMGYRGE.js";import{a as J}from"./chunk-36VNAOG6.js";import{D as Y,F as Ge,c as Ne,e as G,j as je,u as De,v as Ve,x as He,z as Le}from"./chunk-WTPS62L7.js";import{a as qe,b as Ae,c as Fe}from"./chunk-CAE4KIZN.js";import{K as L}from"./chunk-BX2MSRA4.js";import{a as ie}from"./chunk-ADTZEBQF.js";import{i as se}from"./chunk-OV46DXRX.js";import{A as re,B as oe,C as ae,E as ke}from"./chunk-GGZG56GR.js";import{x as we}from"./chunk-NL7AXMUA.js";import{b as Ue}from"./chunk-DX33T5JM.js";import{a as l}from"./chunk-WE55LJEN.js";import{h as ne}from"./chunk-OZK47BUU.js";import{b as Te}from"./chunk-JCOSQTFG.js";import{b as r}from"./chunk-5YBTU4KS.js";import{a as ye}from"./chunk-DSPLGTQI.js";var g=L.options,nt=r.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}),je.omit({customerToken:!0})]),ge=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),pt=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:ge,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:ge}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.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),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:nt})]),ue=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:G.shape.run.shape.status}),U={scope:ne,customerId:r.uuid()},Me=r.discriminatedUnion("outcome",[r.strictObject({...U,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...U,outcome:r.literal("resolved"),target:ue,view:G.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,p)=>{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))&&p.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),ze=r.strictObject({...U,target:ue,view:G.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:G.shape.purchase.unwrap().nullable()}).superRefine((a,p)=>{let f=a.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||a.purchase&&(a.purchase.receiptId!==f.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==f.operationId||a.purchase.quote&&a.purchase.quote.operationId!==f.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))&&p.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Qe=r.strictObject({...U,target:ue,purchase:G.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((a,p)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&p.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Be=r.discriminatedUnion("outcome",[r.strictObject({...U,outcome:r.literal("none")}),r.strictObject({...U,outcome:r.literal("blocked")}),r.strictObject({...U,outcome:r.literal("found"),target:ue,start:r.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:ge})]);var rt=L.options[0].refine(a=>!a.customer&&!a.customerData),ot=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),Ye=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:ne,customerId:r.uuid(),sessionId:r.uuid(),start:rt,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Ne.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ot).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:De.nullable()})});function Je(a){return He({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Ke(a){let p=new URL(a.baseUrl??Te).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){a.assertCurrent();try{let C=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(C.revision)||C.revision<0)throw f();let u=C.entry===null?null:Ye.parse(C.entry);if(u&&(u.baseUrl!==p||u.customerId!==a.customerId||u.scope.projectId!==a.scope.projectId||u.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(u?.journal.entry&&(u.journal.entry.scope.projectId!==u.scope.projectId||u.journal.entry.scope.environment!==u.scope.environment||u.journal.entry.funnelId!==u.start.funnelId||u.journal.entry.runId!==u.run?.id||u.journal.entry.versionId!==u.run?.versionId)||u?.operationCommand&&!u.purchases.some(_=>_.operationId===u.operationCommand?.operationId))throw f();return{revision:C.revision,entry:u}}catch(C){throw C instanceof l?C:f()}}async function K(C){for(let u=0;u<8;u++){let _=await S(),F=C(structuredClone(_.entry));if(JSON.stringify(F)===JSON.stringify(_.entry))return F;F&&Ye.parse(F),a.assertCurrent();let R;try{R=await a.storage.write(_.revision,F)}catch{throw f()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=_.revision)throw f();return F}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:K,baseUrl:p}}var at=5*6e4;function it(a,p){let f=a.purchases.find(S=>S.type==="checkout");if(!a.actions.includes("continue_checkout")||f?.type!=="checkout"||p!==void 0&&f.operationId!==p)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Vt(a){let p={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},f=p.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:K}=f,C=!1,u=null,_,F=null,R=!1,j,$,W,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},P=new Map,Pe=new Map,x=new Map,ce=new AbortController,X=new Set,M=Ue(p),Z=xe(M.request);function z(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(C||p.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let h=Ke({...p,customerId:S,assertCurrent:y,storage:p.storage??Je({baseUrl:p.baseUrl,scope:p.scope,customerId:S})}),$e=p.session.subscribeIdentity(ve);function ve(){C||(C=!0,clearTimeout(W),ce.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),$e(),u?.reset(),u=null,F=null,M.dispose(),X.clear(),P.clear(),x.clear())}function v(e){y();let t=JSON.stringify(e)!==JSON.stringify(b);b=e,clearTimeout(W),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(W=setTimeout(()=>{H().catch(()=>{})},5e3)),t&&ye(p.onRecovery,structuredClone(e));for(let n of t?X:[]){if(C)break;ye(n,structuredClone(e))}return structuredClone(e)}function w(e){if(y(),!e||e.start.requestId!==_)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function k(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function T(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&k(e).every(t=>t.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=k(e).map(I=>{let q=P.get(I.operationId);return I.terminal&&!q?{type:I.terminal,operationId:I.operationId}:ie({quote:q?.quote??null,operation:q??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:x.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),i=s[0],c=s.length===1&&i?.operationId?P.get(i.operationId):void 0;if(c&&(i?.type==="checkout"||i?.type==="cancel"))try{Y({allowed:e.allowed.filter(I=>p.executionPolicy.allowed.includes(I))},c.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:z(I)}}let m;if(t==="operation"&&!n&&i?.type==="cancel"&&c?.quote&&!c.problem&&!c.confirmedAt)try{Y({allowed:e.allowed.filter(I=>p.executionPolicy.allowed.includes(I))},c.quote),Date.parse(c.quote.expiresAt)>Date.now()&&(m={operationId:c.operationId,quote:c.quote})}catch{}let d=o.length>0&&s.length===0,E=T(e)||t==="operation"&&d&&!n&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":n||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:E,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...T(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function Q(e){let t=ie({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&x.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function le(e){if(!e.operation)return;let t=re.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=se(P.get(t.operationId)??null,t);P.set(t.operationId,n),n===t&&x.set(t.operationId,e.canReselect===!0)}async function We(e){y();for(let n of[e.purchase,e.run.paywall])n&&le(n);let t=await h.update(n=>{if(w(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=k(n);for(let s of[e.purchase,e.run.paywall]){let i=s?.operation?.operationId??s?.quote?.operationId;if(!s||!i)continue;let c=o.find(d=>d.operationId===i);if(c&&c.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=Q(P.get(i));c?c.terminal??=m:o.push({receiptId:s.receiptId,operationId:i,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});w(t),t.run&&!["running","waiting"].includes(t.run.status)&&k(t).some(n=>!n.terminal)&&(t=await D(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),w(t),v(A(t,"run"))}function Xe(){return{async read(){let{entry:e}=await h.read();return w(e),structuredClone(e.journal)},async write(e,t){let n=null;return await h.update(o=>{if(w(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 n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function D(e,t=!1,n=new Set){w(e);let o=k(e);for(let i of o){if(i.terminal)continue;let c=n.has(i.operationId)?P.get(i.operationId):void 0;if(c??=await V(e,i),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(c.merchantExecution&&c.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&ie({quote:c.quote??null,operation:c,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=ae(c)?await Z.update({operationId:i.operationId,intent:"cancel"}):await Z.attach({operationId:i.operationId,intent:"cancel"});if(c=re.parse(m.operation),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");c=await V(e,i)}P.set(i.operationId,se(P.get(i.operationId)??null,c))}let s=await h.update(i=>{w(i);let c=i.operationCommand&&P.get(i.operationCommand.operationId);return{...i,...c&&(c.confirmedAt||c.merchantExecution||!ke(c))?{operationCommand:void 0}:{},purchases:k(i).map(m=>({...m,terminal:m.terminal??Q(P.get(m.operationId))}))}});return w(s),s}async function B(e){y();let t=await M.request("funnels",e);return y(),t}async function Ze(e){try{return await B(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return B({...e,intent:"resume"})}}async function et(){let e=J(Be,await B({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==p.scope.projectId||e.scope.environment!==p.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await h.update(o=>o&&!T(o)?o:{schemaVersion:1,baseUrl:h.baseUrl,scope:p.scope,customerId:S,sessionId:K,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...p.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ee;function de(e){let t=ee;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<at))return t.job;let n={at:Date.now(),job:et().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ee===n&&(ee=void 0),o})};return ee=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=J(Qe,await B({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(pe(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return le(s.purchase),o&&s.paywallVersionId&&Pe.set(t.operationId,s.paywallVersionId),P.get(t.operationId)}async function Se(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=J(ze,await B({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(pe(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&le(n.purchase);let o=await h.update(s=>{w(s);let i=k(s),{receiptId:c,operationId:m}=n.settlement;if(c&&m){let E=i.find(I=>I.operationId===m);if(E&&E.receiptId!==c)throw new l("INVALID_RESPONSE","Original Receipt changed");E||i.push({receiptId:c,operationId:m,terminal:Q(P.get(m))})}let d=n.settlement.state==="settled"?Ve(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:i,journal:d===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:d}}});w(o),e=o}return e}function pe(e,t){if(t.customerId!==S||t.scope.projectId!==p.scope.projectId||t.scope.environment!==p.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 me(e,t){if(w(e),e.run&&(e=await Se(e)),!k(e).length&&T(e))return v(A(e,"operation"));if(!k(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:z(t)});R=!0;let n=await D(e);return v(A(n,"operation"))}async function te(e,t=!1,n=!0){if(_=e.start.requestId,F=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!u){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}},s;try{s=await Ze(o)}catch(d){if(!e.run&&d instanceof l&&(d.status===void 0||d.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:z(d)});throw d}let i=J(Me,s);if(i.customerId!==S||i.scope.projectId!==p.scope.projectId||i.scope.environment!==p.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});pe(e,i);let c=await h.update(d=>(w(d),{...d,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??d.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(w(c),e=c,i.access.type==="operation_only")return me(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Se(e);let m=i.view;if(m.locale!==e.start.locale||!Le(m.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");u=Ge({...p,customerRun:{runId:i.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(d=>p.executionPolicy.allowed.includes(d))},funnelCommandStorage:Xe(),onAcceptedResponse:We},{scope:i.scope,run:m})}try{await u.get(),u.view?.pendingRequest?.requestId===e.start.requestId&&!u.pendingCommands?.length&&await u.resume(u.view.pendingRequest.requestId);for(let s of u.pendingCommands??[])s.operation!=="close"&&await u.settle?.(s.requestId);u.pendingCommands?.length&&await u.retry(),y();let o=(await h.read()).entry;return w(o),v(A(o,"run"))}catch(o){if(y(),n&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){u.reset(),u=null;let s=(await h.read()).entry;return w(s),te(s,!1,!1)}throw o}}function N(e,t="read",n){if(y(),j)return t==="read"||t===$?j:j.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(W);let o=e().catch(s=>{throw!C&&!n?.(s)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.purchases,error:z(s)}),s});return j=o,$=t,o.then(()=>{j===o&&(j=void 0,$=void 0)},()=>{j===o&&(j=void 0,$=void 0)}),o}function H(){return N(async()=>{let{entry:e}=await h.read();if(!e||T(e)){if(await de(!1)==="blocked")return Ce();({entry:e}=await h.read())}return e?(_&&e.start.requestId!==_&&(u?.reset(),u=null,P.clear(),x.clear(),R=!1),R&&_===e.start.requestId?me(e,b.error):te(e)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function Ce(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:z(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Ee(){let e=await H();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await h.read()).entry;if(w(t),!R){if(!u?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let d=u.view.paywall.operation;if(d?.confirmedAt||d?.merchantExecution||d&&!(ae(d)?["prepared","quoted"].includes(d.status):d.status==="pending"))return v(A(t,"run"));if(u.pendingCommands?.length)await u.retry();else{let I=u.view;await u.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:we(I.paywall.quote.merchantTerms)}:{}}})}let E=(await h.read()).entry;return w(E),v(A(E,"run"))}let n=t.operationCommand?.operationId??b.confirmation?.operationId,o=n&&P.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");Y({allowed:t.allowed.filter(d=>p.executionPolicy.allowed.includes(d))},o.quote),await h.update(d=>{if(w(d),d.journal.entry?.command||d.journal.entry?.closeCommand||d.operationCommand&&d.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...d,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:we(o.quote.merchantTerms)}:{}},i=ae(o)?await Z.update(s):await Z.attach(s),c=re.parse(i.operation);if(y(),i.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");P.set(n,se(o,c));let m=(await h.read()).entry;return w(m),v(A(await D(m,!1,new Set([n])),"operation"))},"confirm")}function tt(e){let t=e?.quote;return t&&oe(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function Re(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?tt(P.get(t)):null}async function be(){y();let{entry:e}=await h.read();return e?T(e)?"finished":"pending":"none"}return{get controller(){return u},get recovery(){return structuredClone(b)},get attempt(){return y(),structuredClone(F)},get identitySignal(){return ce.signal},get customerId(){return S},retained:be,async findPurchase(){let e=await be();if(e==="pending")return e;let t=await de(!0);return y(),t==="none"?e:t},async readPaywall(e){y();let t=qe(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([Ae(M.request,"resolvePaywall"),import("./paywall-content-IDET7P7K.js"),import("./check-response-MJHH5FWT.js")]);y();let i=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),c=await Fe(M.request,n,i);s(i,c.paywall.check,c.scope);let m=await o(p,c.paywall);if(y(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return Re()!==null},recoverUpgradePaywall(){let e=Re();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await h.read();if(!n?.run)return null;w(n);let o=k(n),s=o.filter(O=>!O.terminal),i=o.filter(O=>O.terminal==="complete"),c=s.length===1?s[0]:s.length?void 0:i.find(O=>e&&e.runId===n.run?.id&&O.receiptId===e.receiptId)??(i.length===1?i[0]:void 0);if(!c||t&&c.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===c.receiptId?e.view:void 0,d;try{d=await V(n,c,"recover_purchase",!0)}catch(O){if(!(O instanceof l&&O.status===400&&O.code==="INVALID_REQUEST"))throw O;if(!m)return null;d=await V(n,c)}let E=d.quote;if(!E||oe(E)&&(E.timing!=="immediate"||E.execution.provider!=="merchant")||!(d.confirmedAt||d.merchantExecution||d.checkoutUrl||Q(d)==="complete"))return null;Q(d)!=="complete"&&Y({allowed:n.allowed.filter(O=>p.executionPolicy.allowed.includes(O))},E);let I=Pe.get(c.operationId),q=n.start.parameters?.commerce,Oe=n.start.locale??"en",fe=m;if(I){if(typeof q!="object"||!q||!("provider"in q)||typeof q.provider!="string"||!("currency"in q)||typeof q.currency!="string")return null;fe=await this.readPaywall({paywallVersionId:I,locale:Oe,commerce:{provider:q.provider,currency:q.currency,...oe(E)?{intent:"subscription_change"}:{}}})}if(!fe)return null;y();let _e=fe,he=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:ce.signal,view:_e,quote:E,locale:Oe,get operation(){return d},canReselect:!1,async refresh(){return _e},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(he)throw new DOMException("Purchase view closed","AbortError");d=await V(n,c);let O=await D(n,!1,new Set([c.operationId]));return he||v(A(O,"operation")),structuredClone(d)},destroy(){he=!0}}},start(e){let t=L.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 N(async()=>{let n=(await h.read()).entry;if((!n||T(n))&&await de(!0)==="blocked")return Ce();let o=await h.update(s=>{if(s&&!T(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:h.baseUrl,scope:p.scope,customerId:S,sessionId:K,start:t,allowed:[...p.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return _!==o.start.requestId&&(u?.reset(),u=null,P.clear(),x.clear(),R=!1),R?me(o,b.error):te(o,!0)},`start:${t.funnelId}`)},refresh:H,confirm:Ee,retry:()=>R?Ee():N(async()=>{let{entry:e}=await h.read();return e?te(e,!0):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return u?.view?N(async()=>{if(!u?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(u.pendingCommands?.find(n=>n.operation==="close"))await u.retry();else if(["running","waiting"].includes(u.view.status)){let n=u.view;await u.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await h.read()).entry;return w(t),v(A(t,"run"))},"close"):H()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await h.read();if(w(o),!o.run||!k(o).some(i=>i.operationId===t&&!i.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await D(o);return v(A(s,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await H();y(),await e(it(n,t))},async terminateCheckout(e){let t=await H();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 N(async()=>{let{entry:o}=await h.read();w(o);let s=k(o).find(c=>c.operationId===e&&!c.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let i=await D(o,!1,new Set([e]));return v(A(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return X.add(e),()=>{X.delete(e)}},destroy:ve}}export{Je as a,it as b,Vt as c};
@@ -1 +0,0 @@
1
- import{a as A}from"./chunk-W32FI2A2.js";import{b as D,e as L}from"./chunk-SLUA7ABW.js";import{d as T}from"./chunk-PSAAZJZA.js";import{a as R}from"./chunk-DSPLGTQI.js";import{b as O}from"./chunk-HMJTABQ5.js";var m=new WeakMap;function B(e){let o=e.view,n=o?.paywall?.resolution;if(!o||!["running","waiting"].includes(o.status)||o.stopped||!n||"document"in n||!e.resolvePaywall||e.identitySignal?.aborted)return;let a=JSON.stringify(n);if(m.get(e)?.key===a)return;let i=JSON.parse(a),c=e.identitySignal,u=Promise.resolve().then(async()=>{c?.throwIfAborted();let v=await e.resolvePaywall(i);return c?.throwIfAborted(),v}),f={key:a,content:u};return m.set(e,f),u.catch(()=>{}),()=>{m.get(e)===f&&m.delete(e)}}function Q(e,o){let n=m.get(e);return m.delete(e),n?.key===JSON.stringify(o)?n.content:e.resolvePaywall(o)}function re(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let o=e.client.pageExperiments.bind(e.client),n=!1,a=!1,i=0,c=!1,u=!1,f="",v=()=>{let t=e.client.view;return JSON.stringify([t?.id,t?.source.versionId,t?.visit,t?.revision,t?.status,t?.stopped])},s=new Map,x=new Set,q={},d=new Map,U=D(e.appManifestRelease),C=()=>{for(let t of s.values())t.effect.revert();s.clear()},g=()=>{C();for(let t of d.values())t();d.clear()};function E(t){if(n||x.has(t))return;x.add(t);let h=i;o(e.appManifestRelease,[t]).catch(k=>{x.delete(t),!n&&h===i&&R(e.onError,k)})}async function w(){if(n)return;f=v();let t=e.client.view;if(!t||t.stopped||!["running","waiting"].includes(t.status)){i++,g();return}if(document.visibilityState==="hidden")return;if(c){u=!0;return}c=!0;let h=++i,k=`${t.id}:${t.visit}:${t.revision}`,W=location.href;try{let[P,{applyVisualVariation:j}]=await Promise.all([o(e.appManifestRelease),import("./visual-dom-MH3JDJHJ.js")]),p=e.client.view;if(n||h!==i||!p||p.stopped||!["running","waiting"].includes(p.status)||`${p.id}:${p.visit}:${p.revision}`!==k||location.href!==W)return;let $=new Set,I=new Set;for(let r of P.assignments){let l=`${P.payload.environmentId}:${r.experimentKey}`;if(I.add(l),d.has(l)||d.set(l,L(l,q)),!!r.inExperiment)for(let y of P.payload.experiments){if(y.key!==r.experimentKey||!O(location.href,y.urlPatterns??[]))continue;let z=y.meta?.findIndex(F=>F.key===r.variationKey)??-1,S=y.variations[z];if(!S?.renderGuard)continue;let b=r.receiptId+":"+y.changeId,J=JSON.stringify([r.variationKey,S]);$.add(b);let N=s.get(b);if(N?.signature===J){N.effect.applied&&E(r.receiptId);continue}s.get(b)?.effect.revert(),s.delete(b);let K=j(S,{requireUniqueTargets:!0,boundVariations:y.variations,allowJs:!1,onApplied:()=>E(r.receiptId),onError:F=>R(e.onError,F)});s.set(b,{signature:J,effect:K}),K.applied&&E(r.receiptId)}}for(let[r,l]of s)$.has(r)||(l.effect.revert(),s.delete(r));for(let[r,l]of d)I.has(r)||(l(),d.delete(r))}catch(P){h===i&&g(),!n&&h===i&&R(e.onError,P)}finally{c=!1,u&&!n&&(u=!1,w())}}let G=e.client.subscribe(()=>{if(v()===f)return;f=v(),i++;let t=e.client.view;(!t||t.stopped||!["running","waiting"].includes(t.status))&&g(),a&&w()}),H=T(()=>{i++,g(),a&&w()}),V=()=>{i++,C()};document.addEventListener("visibilitychange",V);let M=A({document,run:async()=>{a&&await w()},delay:()=>a&&!n?15e3:void 0});return{async start(){a||n||(a=!0,await M.refresh())},refresh:w,destroy(){n=!0,i++,M.destroy(),document.removeEventListener("visibilitychange",V),G(),H(),g(),U.destroy()}}}export{B as a,Q as b,re as c};
@@ -1 +0,0 @@
1
- import{b as ne}from"./chunk-DXQJ2JQZ.js";import{b as j}from"./chunk-3CKAOP4L.js";import"./chunk-JJIP6BZL.js";import"./chunk-R4BYUK7S.js";import{a as re}from"./chunk-45XVSI2M.js";import{a as z}from"./chunk-DXLBEXC6.js";import{b as te}from"./chunk-SM44S6BK.js";import"./chunk-Y2B7RDRB.js";import"./chunk-W32FI2A2.js";import{i as O,j as V}from"./chunk-QAGK2SLZ.js";import"./chunk-PVMGYRGE.js";import"./chunk-36VNAOG6.js";import"./chunk-WTPS62L7.js";import"./chunk-73UFNVEP.js";import"./chunk-CAE4KIZN.js";import"./chunk-VSARBT7T.js";import"./chunk-6HKQILBV.js";import"./chunk-EACC667P.js";import"./chunk-BX2MSRA4.js";import"./chunk-LOBZ45T3.js";import"./chunk-J4RM5GQP.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-DX33T5JM.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import{a as C}from"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-SLUA7ABW.js";import"./chunk-PSAAZJZA.js";import"./chunk-3VUPVXAV.js";import"./chunk-JCOSQTFG.js";import"./chunk-5YBTU4KS.js";import{a as h}from"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";var k=new WeakMap,_=new WeakMap,B=new WeakSet;function he(D,e){let m=e.prepared,J=()=>{m&&!B.has(m)&&j(m)?.release()},K=k.get(e.client);if(K)return J(),K;let Q=n=>({...n,requestId:n.requestId??crypto.randomUUID()}),R=e.allowNewPurchase!==!1&&e.start instanceof Promise?e.start:void 0,w=e.allowNewPurchase===!1||!e.start||e.start instanceof Promise?void 0:Q(e.start);w&&m?.state==="ready"&&m.matches(w)&&m.open();let f=m&&(w&&(m.state==="preparing"||["shown","closed"].includes(m.state)&&m.matches(w))||R&&["preparing","ready"].includes(m.state))?m:void 0;f?B.add(f):J();let y=f&&j(f);y?.claim();let S=Promise.resolve().then(async()=>{let n=!1,c,p=!1,U,g=0,E,q,X=!1,F=()=>{},Y=()=>{},H,L=!1,M=!1,I,Z=!1,a=e.signal?AbortSignal.any([e.signal,e.client.identitySignal]):e.client.identitySignal,v=()=>{k.get(e.client)===S&&k.delete(e.client),a.removeEventListener("abort",A),F(),Y(),f&&B.delete(f),y?.release()};function $(){if(I)return I;let t=new Promise(o=>I=o);return _.set(e.client,t),t.then(()=>{_.get(e.client)===t&&_.delete(e.client)}),k.get(e.client)===S&&k.delete(e.client),I}let l=V(D,e,"funnel",()=>b(),z);function A(){b()}function b(t=!1){if(!n){if(n=!0,l.finish("dismissed"),c){c.destroy();return}if(t&&H){let o=$();Z=!0,H.then(async i=>{i.mode==="run"&&i.status!=="blocked"&&e.client.controller&&e.client.attempt?.requestId===w?.requestId&&await e.client.close()}).catch(()=>{}).finally(()=>{o(),h(e.onDismiss,null)}),v();return}v(),h(e.onDismiss,null)}}let N={destroy:()=>b(),refresh:()=>E??(p?G():c?.refresh())??Promise.resolve(),get recovery(){return c?.recovery??{type:"recover",operationId:null,requestId:null}},prepareFallback:()=>c?.prepareFallback()??Promise.resolve({type:"recover",operationId:null,requestId:null}),review:(...t)=>c?.review(...t)??Promise.resolve(),exitReview:(...t)=>c?.exitReview(...t)??Promise.resolve(),get unappliedDrafts(){return c?.unappliedDrafts??new Map}};a.addEventListener("abort",A,{once:!0}),y&&(Y=y.onClose(()=>{L?n||$():b(!0)}));try{a.throwIfAborted();let t=e.client.controller?.view?.paywall?.resolution,o=t&&"document"in t?t.document:e.loadingDocument;l.start(!0,w?.locale??e.client.attempt?.locale??o?.screen.strings.defaultLocale,o??null);let i=R?l.wait(R.then(r=>r?Q(r):null,()=>null),O):Promise.resolve(w??null);i.catch(()=>{}),f?.state==="shown"?(M=!0,l.present(()=>{})):f&&["preparing","ready"].includes(f.state)&&Promise.all([f.ready,i.catch(()=>null)]).then(([r,s])=>{if(r){if(n||!l.active||!s||!f.matches(s)||!y?.revealable)return y?.release();l.present(()=>{f.open()==="shown"?M=!0:y.release()})}});let d=_.get(e.client);if(d&&await l.wait(d),n)return null;if(a.throwIfAborted(),R){let r=await i;if(n)return null;if(a.throwIfAborted(),!r)return l.finish("skipped"),v(),null;w=r}H=w?e.client.start(w):e.client.refresh();let u=await l.wait(H,O);return n?null:(a.throwIfAborted(),await ee(u,l))}catch(t){if(Z||I?.(),n)return null;throw l.finish("error",t),v(),h(e.onError,t),t}function x(t=!1){g++;let o=c;c=void 0,F(),F=()=>{};let i=t?o?.retainPurchaseDialog?.():void 0;return o?.destroy(),a.addEventListener("abort",A,{once:!0}),i}function T(t){p=!0;let o=e.client.attempt?.locale??w?.locale,i=o?.startsWith("zh"),d=t?i?"正在查询原订单…":"Checking your purchase…":i?"暂时无法确认原订单,请重试。":"Could not check your original purchase. Try again.",u=t?void 0:()=>{G()};c?.setPurchaseRecovery?.(d,u)||(c&&x(),l.active||(l=V(D,e,"funnel",()=>b(),z),l.start(!0,o,e.loadingDocument??null)),l.setPurchaseRecovery(d,u))}function G(){if(E)return E;if(n||a.aborted)return Promise.resolve();U??=c?.recoveryPaywall,a.addEventListener("abort",A,{once:!0}),T(!0);let t=Promise.resolve().then(async()=>{try{let i=await l.wait(e.client.refresh(),O);!n&&!a.aborted&&await ee(i,l)}catch(i){!n&&!a.aborted&&(h(e.onError,i),T(!1))}});E=t;let o=()=>{E===t&&(E=void 0)};return t.then(o,o),t}async function ee(t,o){let i=e.client.controller;if(t.mode==="run"&&t.status!=="blocked"&&i)return p&&c&&x(),p=!1,U=void 0,ae(i,o?.active?o:void 0);if(t.mode==="operation"&&t.purchases.length){T(!0);let d=await l.wait(e.client.recoverPurchasePaywall(U).then(u=>((n||a.aborted)&&u?.destroy(),u)),O).catch(u=>(!n&&!a.aborted&&h(e.onError,u),null));if(n||a.aborted)return null;if(d){if(n||a.aborted)return d.destroy(),null;let u=x(!0)??y?.retainPurchaseDialog?.()??l.retainPurchaseDialog();y?.release();let r=await re(D,{signal:a,loading:"host",start:async()=>d,checkoutNavigation:"after_confirmation",allowNewPurchase:!1,resumeCheckout:P=>e.client.continueCheckout(W,P),onError:e.onError,onDismiss:()=>{n||b()}},{retainedDialog:u,present(P){l.active?l.present(P):P(!!u)},async dismiss(){b()}});if(!r.host||n||a.aborted)return r.host?.destroy(),u?.release(),v(),null;let s=r.host;return p=!1,c={destroy(){s.destroy(),v(),h(e.onDismiss,null)},refresh:async()=>{await s.refresh()},get recovery(){return s.recovery},prepareFallback:()=>s.prepareFallback(),review:async()=>{},exitReview:async()=>{},unappliedDrafts:new Map},N}}return t.purchases.length||p?(T(!1),N):(l.finish("skipped"),v(),(M||L)&&(n=!0,h(e.onDismiss,null)),null)}function W(t){if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");return e.onCheckoutUrl?e.onCheckoutUrl(t):D.ownerDocument.defaultView?.location.assign(t)}async function ae(t,o){a.removeEventListener("abort",A),L=!0;function i(){!n&&!a.aborted&&!p&&!X&&q&&e.client.recovery.status==="complete"&&(X=!0,h(e.onComplete,structuredClone(q)))}F(),F=e.client.subscribe(i);let d=++g,u=await ne(D,{...e,prepared:f,client:t,signal:a,checkoutNavigation:"after_confirmation",resumeCheckout:r=>e.client.continueCheckout(W,r),terminateCheckout:e.allowNewPurchase===!1?void 0:r=>e.client.terminateCheckout(r),async onCheckoutUrl(r){if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");let s=e.client.recovery;if((!s.actions.includes("continue_checkout")||!s.purchases.some(P=>P.type==="checkout"&&P.checkoutUrl===r))&&(s=await e.client.refresh(),a.throwIfAborted(),n))throw new DOMException("Presentation dismissed","AbortError");if(te(s)!==r)throw new C("PURCHASE_PENDING","Checkout differs from the original recovery proof");return W(r)},async resolveOfferId(r){if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");let s=e.client.attempt;if(!s)throw new C("PURCHASE_PENDING","Read the original Start before selecting an offer");let P=await e.resolveOfferId?.(r,s);if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");if(e.client.attempt?.requestId!==s.requestId)throw new C("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting an offer");return P},async resolveSubscriptionChange(r){a.throwIfAborted();let s=e.client.attempt;if(n||!s)throw new C("PURCHASE_PENDING","Read the original Start before selecting a membership");let P=await e.resolveSubscriptionChange?.(r);if(a.throwIfAborted(),n||e.client.attempt?.requestId!==s.requestId)throw new C("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting a membership");return P},onPresentationState(r){d===g&&h(e.onPresentationState,r)},onComplete(r){d===g&&(q=r,i())},onError(r){d===g&&(h(e.onError,r),r instanceof C&&(r.status===401||r.status===409&&r.reason==="STATE_CHANGED"&&r.recovery==="recover_operation")&&!a.aborted&&G().catch(s=>h(e.onError,s)))},onDismiss(r){d===g&&(n=!0,v(),I?.(),h(e.onDismiss,r))}},o);return d!==g||n||a.aborted?(u.destroy(),n||a.aborted?null:N):(c=u,N)}});return k.set(e.client,S),S}export{he as showFunnelPurchase};
@@ -1 +0,0 @@
1
- import{a as d}from"./chunk-45XVSI2M.js";import"./chunk-DXLBEXC6.js";import"./chunk-W32FI2A2.js";import"./chunk-QAGK2SLZ.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-DX33T5JM.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-JCOSQTFG.js";import"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";async function w(i,n){let r=i.closest("dialog");if(!r?.open)return null;let o=AbortSignal.any([n.signal,n.client.identitySignal]);o.throwIfAborted();let a=await n.client.recoverPurchasePaywall();if(!a)return null;let s=a.view;if(!s||s.document.presentation.type!=="modal"||o.aborted)return a.destroy(),null;let m=["style","tabindex","aria-label","data-presentation","data-indiana-backdrop"].map(e=>[e,r.getAttribute(e)]),f=()=>{for(let[e,t]of m)t===null?r.removeAttribute(e):r.setAttribute(e,t)},l,y=new Promise(e=>{l=e}),c=!1,u=()=>l(!1);o.addEventListener("abort",u,{once:!0});try{let{host:e}=await d(i,{signal:o,start:async()=>a,loading:"host",checkoutNavigation:"after_confirmation",allowNewPurchase:!1,resumeCheckout:t=>n.client.continueCheckout(n.onCheckoutUrl,t),onComplete:n.onComplete,onError(t){c?n.onError?.(t):l(!1)}},{retainedDialog:{dialog:r,release:f},retainedContent:i,present(t){t(!0),c=!0,l(!0)},async dismiss(){n.onDismiss()}});return!e||!await y||o.aborted?(e?.destroy(),null):{document:s.document,destroy:()=>e.destroy()}}finally{o.removeEventListener("abort",u)}}export{w as mountFunnelRecoveryPaywall};
@@ -1 +0,0 @@
1
- import{a,b}from"./chunk-DXQJ2JQZ.js";import"./chunk-3CKAOP4L.js";import"./chunk-JJIP6BZL.js";import"./chunk-R4BYUK7S.js";import"./chunk-DXLBEXC6.js";import"./chunk-Y2B7RDRB.js";import"./chunk-W32FI2A2.js";import"./chunk-QAGK2SLZ.js";import"./chunk-73UFNVEP.js";import"./chunk-BX2MSRA4.js";import"./chunk-LOBZ45T3.js";import"./chunk-J4RM5GQP.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-DX33T5JM.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-SLUA7ABW.js";import"./chunk-PSAAZJZA.js";import"./chunk-JCOSQTFG.js";import"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";export{a as showFunnelRun,b as showObservedFunnelRun};