@tinkerlandai/longplay-sdk 0.10.63 → 0.10.64

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 (36) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +1 -1
  4. package/dist/{chunk-JCZ2E6QB.js → chunk-5ZD3BY5R.js} +1 -1
  5. package/dist/{chunk-5II75UJQ.js → chunk-7HJQJG6Z.js} +1 -1
  6. package/dist/{chunk-LJFHEKYZ.js → chunk-7N765ZES.js} +1 -1
  7. package/dist/chunk-D4CK3DCQ.js +1 -0
  8. package/dist/{chunk-K7ROZKFG.js → chunk-FDWFBCXV.js} +1 -1
  9. package/dist/chunk-GKNN4T3B.js +1 -0
  10. package/dist/{chunk-7G7QSSC2.js → chunk-KOJI7IH6.js} +2 -2
  11. package/dist/{chunk-U5L5MKL7.js → chunk-LFEFSEK3.js} +1 -1
  12. package/dist/{chunk-2TYSHLVI.js → chunk-NA6IYWSB.js} +1 -1
  13. package/dist/chunk-R7CH2XLH.js +1 -0
  14. package/dist/{chunk-US23EYSC.js → chunk-YVTXJWTS.js} +1 -1
  15. package/dist/{chunk-OVZPLYWF.js → chunk-ZYSMQMC5.js} +1 -1
  16. package/dist/{content-DVKUHVVI.js → content-N4FPQMWG.js} +1 -1
  17. package/dist/{funnel-host-purchase-ERJYGR3N.js → funnel-host-purchase-YWSXBNT6.js} +1 -1
  18. package/dist/{funnel-host-recovery-paywall-KX4MF5VM.js → funnel-host-recovery-paywall-OJROCEFE.js} +1 -1
  19. package/dist/{funnel-paywall-prerender-ARUTTHRQ.js → funnel-paywall-prerender-EMEIQRIH.js} +1 -1
  20. package/dist/{funnel-runtime-host-HH7PJ34L.js → funnel-runtime-host-JUGVP64Q.js} +1 -1
  21. package/dist/index.d.ts +4 -2
  22. package/dist/index.js +1 -1
  23. package/dist/native-shell.js +1 -1
  24. package/dist/openrouter.js +1 -1
  25. package/dist/page.js +1 -1
  26. package/dist/{paywall-6B3F557D.js → paywall-KJ44JWLV.js} +1 -1
  27. package/dist/{paywall-content-5YMPVL4L.js → paywall-content-Y5L3WMDS.js} +1 -1
  28. package/dist/{paywall-session-EYD73DJ2.js → paywall-session-I6XT22TL.js} +1 -1
  29. package/dist/react-native.js +1 -1
  30. package/dist/server.js +1 -1
  31. package/dist/visual.js +1 -1
  32. package/package.json +1 -1
  33. package/dist/chunk-4GSVJBO7.js +0 -1
  34. package/dist/chunk-GYIAMOZY.js +0 -1
  35. package/dist/chunk-H37TGSCQ.js +0 -1
  36. /package/dist/{chunk-7G7QSSC2.js.LEGAL.txt → chunk-KOJI7IH6.js.LEGAL.txt} +0 -0
@@ -1 +1 @@
1
- import"./chunk-7STWC4L4.js";import"./chunk-2RFI2DEV.js";import"./chunk-JCZ2E6QB.js";import"./chunk-HUYKZH3H.js";import{a as i}from"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-K7ROZKFG.js";import"./chunk-5MRSFLQA.js";import{b as A}from"./chunk-PZTWDJHN.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-7STWC4L4.js";import"./chunk-2RFI2DEV.js";import"./chunk-5ZD3BY5R.js";import"./chunk-HUYKZH3H.js";import{a as i}from"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-FDWFBCXV.js";import"./chunk-5MRSFLQA.js";import{b as A}from"./chunk-PZTWDJHN.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-7G7QSSC2.js";import"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-K7ROZKFG.js";import"./chunk-5MRSFLQA.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-KOJI7IH6.js";import"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-FDWFBCXV.js";import"./chunk-5MRSFLQA.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-6AHZAXQE.js";import"./chunk-QXDLOPZK.js";import"./chunk-W32FI2A2.js";import"./chunk-IM5OXTEH.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-VILB5M4X.js";import"./chunk-JCZ2E6QB.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-K7ROZKFG.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as showPaywall};
1
+ import{a}from"./chunk-6AHZAXQE.js";import"./chunk-QXDLOPZK.js";import"./chunk-W32FI2A2.js";import"./chunk-IM5OXTEH.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-VILB5M4X.js";import"./chunk-5ZD3BY5R.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-FDWFBCXV.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as showPaywall};
@@ -1 +1 @@
1
- import{b as a}from"./chunk-LJFHEKYZ.js";import"./chunk-BJW4AXFL.js";import"./chunk-32AEJKJW.js";import"./chunk-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-JCZ2E6QB.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-K7ROZKFG.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as readPaywallContent};
1
+ import{b as a}from"./chunk-7N765ZES.js";import"./chunk-BJW4AXFL.js";import"./chunk-32AEJKJW.js";import"./chunk-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-5ZD3BY5R.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-FDWFBCXV.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as readPaywallContent};
@@ -1 +1 @@
1
- import{a}from"./chunk-5II75UJQ.js";import"./chunk-NAFHQVSX.js";import"./chunk-EE6QNOCL.js";import"./chunk-VNYUL3PV.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4SI4SQ3C.js";import"./chunk-C3HZCZVJ.js";import"./chunk-LJFHEKYZ.js";import"./chunk-BJW4AXFL.js";import"./chunk-32AEJKJW.js";import"./chunk-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-2RFI2DEV.js";import"./chunk-JCZ2E6QB.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-K7ROZKFG.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
1
+ import{a}from"./chunk-7HJQJG6Z.js";import"./chunk-NAFHQVSX.js";import"./chunk-EE6QNOCL.js";import"./chunk-VNYUL3PV.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4SI4SQ3C.js";import"./chunk-C3HZCZVJ.js";import"./chunk-7N765ZES.js";import"./chunk-BJW4AXFL.js";import"./chunk-32AEJKJW.js";import"./chunk-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-2RFI2DEV.js";import"./chunk-5ZD3BY5R.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-FDWFBCXV.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
@@ -1 +1 @@
1
- import{b as S,c as E,d as T}from"./chunk-OVZPLYWF.js";import"./chunk-77O2O552.js";import{a as A}from"./chunk-5II75UJQ.js";import{e as P}from"./chunk-NAFHQVSX.js";import"./chunk-EE6QNOCL.js";import{h as b,i as x,k as L}from"./chunk-U5L5MKL7.js";import{E as C}from"./chunk-US23EYSC.js";import"./chunk-ZCJEXNJD.js";import"./chunk-VNYUL3PV.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4SI4SQ3C.js";import"./chunk-C3HZCZVJ.js";import"./chunk-LJFHEKYZ.js";import"./chunk-BJW4AXFL.js";import"./chunk-32AEJKJW.js";import"./chunk-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-JEDRJAJ5.js";import"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-2RFI2DEV.js";import"./chunk-JCZ2E6QB.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import{a as r}from"./chunk-TK3WOD2O.js";import{h as R}from"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-K7ROZKFG.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-ZYSMQMC5.js";import"./chunk-77O2O552.js";import{a as A}from"./chunk-7HJQJG6Z.js";import{e as P}from"./chunk-NAFHQVSX.js";import"./chunk-EE6QNOCL.js";import{h as b,i as x,k as L}from"./chunk-LFEFSEK3.js";import{E as C}from"./chunk-YVTXJWTS.js";import"./chunk-ZCJEXNJD.js";import"./chunk-VNYUL3PV.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4SI4SQ3C.js";import"./chunk-C3HZCZVJ.js";import"./chunk-7N765ZES.js";import"./chunk-BJW4AXFL.js";import"./chunk-32AEJKJW.js";import"./chunk-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-JEDRJAJ5.js";import"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-2RFI2DEV.js";import"./chunk-5ZD3BY5R.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import{a as r}from"./chunk-TK3WOD2O.js";import{h as R}from"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-FDWFBCXV.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as pn}from"./chunk-4GSVJBO7.js";import{a as I}from"./chunk-PJHTN5NJ.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-7STWC4L4.js";import{a as xt}from"./chunk-5II75UJQ.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-NAFHQVSX.js";import"./chunk-EE6QNOCL.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-U5L5MKL7.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-US23EYSC.js";import"./chunk-ZCJEXNJD.js";import{c as h}from"./chunk-VNYUL3PV.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4SI4SQ3C.js";import{a as Et,b as _e}from"./chunk-C3HZCZVJ.js";import"./chunk-LJFHEKYZ.js";import"./chunk-BJW4AXFL.js";import{e as at}from"./chunk-32AEJKJW.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-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.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-S5RM3VO6.js";import{b as Oe}from"./chunk-JEDRJAJ5.js";import{e as ve,i as Ze,l as it}from"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-2RFI2DEV.js";import"./chunk-JCZ2E6QB.js";import{a as Ne,b as Le}from"./chunk-HUYKZH3H.js";import{o as ue}from"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-KTWKDR5L.js";import{c as Ie}from"./chunk-XCFAKO23.js";import{e as Xe,h as We}from"./chunk-FQMZY5VP.js";import{a as c}from"./chunk-TK3WOD2O.js";import{h as Y}from"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-K7ROZKFG.js";import"./chunk-5MRSFLQA.js";import{b as u}from"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-D4CK3DCQ.js";import{a as I}from"./chunk-PJHTN5NJ.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-7STWC4L4.js";import{a as xt}from"./chunk-7HJQJG6Z.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-NAFHQVSX.js";import"./chunk-EE6QNOCL.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-LFEFSEK3.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-YVTXJWTS.js";import"./chunk-ZCJEXNJD.js";import{c as h}from"./chunk-VNYUL3PV.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4SI4SQ3C.js";import{a as Et,b as _e}from"./chunk-C3HZCZVJ.js";import"./chunk-7N765ZES.js";import"./chunk-BJW4AXFL.js";import{e as at}from"./chunk-32AEJKJW.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-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.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-S5RM3VO6.js";import{b as Oe}from"./chunk-JEDRJAJ5.js";import{e as ve,i as Ze,l as it}from"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-2RFI2DEV.js";import"./chunk-5ZD3BY5R.js";import{a as Ne,b as Le}from"./chunk-HUYKZH3H.js";import{o as ue}from"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-KTWKDR5L.js";import{c as Ie}from"./chunk-XCFAKO23.js";import{e as Xe,h as We}from"./chunk-FQMZY5VP.js";import{a as c}from"./chunk-TK3WOD2O.js";import{h as Y}from"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-FDWFBCXV.js";import"./chunk-5MRSFLQA.js";import{b as u}from"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-OJM6ORHE.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-7G7QSSC2.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-K7ROZKFG.js";import"./chunk-5MRSFLQA.js";import{b as o}from"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-OJM6ORHE.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-KOJI7IH6.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-FDWFBCXV.js";import"./chunk-5MRSFLQA.js";import{b as o}from"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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.63",
3
+ "version": "0.10.64",
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-US23EYSC.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
@@ -1 +0,0 @@
1
- import{a as ie,b as se}from"./chunk-JBSJ3JU2.js";import{d as Ae,e as U}from"./chunk-5LNX7MHO.js";import{a as Ce}from"./chunk-TK3WOD2O.js";import{a as C}from"./chunk-DSPLGTQI.js";var xe=5*6e4,Me=15e3,Re=new WeakMap;function Ue(c){return Re.get(c)}var A=c=>Array.isArray(c)?c.map(A):c&&typeof c=="object"?Object.fromEntries(Object.keys(c).sort().map(n=>[n,A(c[n])])):c,O=(c,n)=>JSON.stringify(A(c))===JSON.stringify(A(n)),ce=c=>JSON.stringify(A([c.funnelId,c.locale??null,c.parameters??{}])),qe=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Ge(c,n){let de=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),g,G="",H=n.start instanceof Promise?void 0:de(n.start),W=e=>e?.parameters?.commerce,ue=Promise.resolve(n.start).then(e=>e?de(e):void 0),K=n.maxAgeMs??xe,fe=new AbortController,f=AbortSignal.any([fe.signal,n.client.identitySignal,...n.signal?[n.signal]:[]]),B=()=>d("released","aborted"),r="preparing",pe,F,X=()=>{},N=0,P=null,b=null,v=null,p=null,h,$,ye=new Map,w=null,x=new Set,R=new Map,z,we=new Promise(e=>z=e),M,ke=new Promise(e=>M=e),Q,Ee=new Promise(e=>Q=e);function q(e,a){r!==e&&(r=e,pe=a,C(n.onState,e))}function _e(){f.removeEventListener("abort",B),L(),b?.destroy(),b=null,P?.remove(),P=null,v=null}function d(e,a){["adopted","unavailable","released","closed"].includes(r)||(q(e,a),_e(),z(!1),M(!1),Q(null))}function _(e){r!=="shown"&&d("unavailable",e)}let m,Y=n.client.paywallCopies,Z,Ve=new Promise(e=>Z=e);function me(e){Ve.then(a=>{a&&Y&&Y.write(a,e).catch(()=>{})})}let ee=e=>`error:${e?.code??e?.name??"unknown"}`,ne=c.ownerDocument.defaultView,V=!0,ge=null,k=!1,De=e=>e.storageArea===ne?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),he=e=>{De(e)&&T()},Oe=n.client.subscribe(()=>T());function L(){V&&(V=!1,ne?.removeEventListener("storage",he),Oe(),X())}let ae=()=>V&&(r==="ready"||r==="preparing");function re(e){(r==="ready"||r==="preparing")&&d("unavailable",e)}function T(){if(r==="ready"&&Date.now()-N>=K)return L();k=!0,ge??=(async()=>{for(;k&&g&&ae();){k=!1;try{await n.client.retained()==="pending"&&re("purchase_pending")}catch(e){f.aborted?d("released","aborted"):re(ee(e))}}})().finally(()=>{ge=null,k&&g&&ae()&&T()})}ne?.addEventListener("storage",he),f.addEventListener("abort",B,{once:!0});let be=n.client.findPurchase();be.catch(()=>{});let j;function J(e){let a=JSON.stringify(A(e)),t=ye.get(a);if(!t){let i=j?.paywallVersionId??n.paywallVersionId??(m?void 0:p?.id);t=n.client.readPaywall({paywallVersionId:i,...i?{}:{paywallId:j?.paywallId??n.paywallId},...e}),ye.set(a,t)}return t}function E(e,a){let t=Object.values(e.capabilities.plans),i=Object.values(e.document.buttons).some(l=>l.type==="checkout");return i&&t.length===0?!1:a.intent==="subscription_change"&&i?t.some(l=>l.available):t.every(l=>l.available)}function te(e,a){if(p&&!U(e,p))return d("unavailable","paywall_changed"),!1;p=e,$=a;for(let t of R.keys())C(t,structuredClone(e));return!0}function Pe(e,a){if(!(!p||!["preparing","ready","shown"].includes(r))){if(!U(e,p))return _("paywall_changed");if(!E(e,a.commerce))return _("plan_unavailable");te(e,a)}}async function D(){let e=await Ee;if(!e)throw new Ce("PURCHASE_PENDING","The purchase did not start; open it again");return e}let He={get view(){return w?w.view:p},get signal(){return w?.signal??n.client.identitySignal},get quote(){return w?.quote??null},get operation(){return w?.operation??null},webViewUrl:"bundled",get canReselect(){return w?.canReselect},get recovery(){return w?.recovery},get pendingCancellation(){return w?.pendingCancellation},subscribe(e){return R.set(e,w?.subscribe?.(e)??(()=>{})),()=>{R.get(e)?.(),R.delete(e)}},refresh:async()=>w?w.refresh():structuredClone(p),preview:async e=>(await D()).preview(e),confirm:async()=>(await D()).confirm(),cancel:async()=>(await D()).cancel(),read:async()=>(await D()).read(),destroy(){w?.destroy()}},u={options:{},handoff:{}},ve={loading:"host",focusAtReveal:!0,signal:n.client.identitySignal,start:async()=>He,canInteract:()=>u.options.canInteract?u.options.canInteract():!["unavailable","released","closed"].includes(r),async beforeAction(){let e=r!=="adopted",a=p?.capabilities,t=await D();if(e&&!O(t.view?.capabilities,a))throw new Ae;await u.options.beforeAction?.()}};for(let e of qe)Object.defineProperty(ve,e,{enumerable:!0,get:()=>u.options[e]});function oe(){r!=="preparing"||!v||!b||!m&&(!g||!O($?.commerce,W(g))||$?.locale!==g.locale)||(q("ready"),z(!0))}let Ie={present(e){if(u.handoff.present)return u.handoff.present(e);r==="preparing"&&(v=e,N=Date.now(),oe())},async dismiss(){if(u.handoff.dismiss)return u.handoff.dismiss();d("closed");for(let e of[...x])C(e)},async closeAction(e){if(u.handoff.closeAction)return u.handoff.closeAction(e);u.options.onAction?await u.options.onAction(e):await Ie.dismiss()},quoteError(e){u.handoff.quoteError?u.handoff.quoteError(e):C(u.options.onError,e)}};async function Fe(){if(n.paywallVersionId||n.paywallId)return{paywallVersionId:n.paywallVersionId,paywallId:n.paywallId};let e=n.configuration;if(!e)return d("unavailable","paywall_missing"),null;let a=await Promise.resolve(n.start).catch(()=>null);if(!a||r!=="preparing")return null;let t=()=>ie(e,{funnelId:a.funnelId,customerId:n.client.customerId,parameters:a.parameters??{}});if(F=await t(),r!=="preparing")return null;let i=F;if(i.type!=="paywall")return d("unavailable",se(i)??"route"),null;let l=!1;return X=e.subscribe(()=>{l||!ae()||(l=!0,t().then(s=>{!(s.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(s.reason))&&(s.type!=="paywall"||s.paywallVersionId!==i.paywallVersionId)&&re("route_changed")}).finally(()=>l=!1))}),V||X(),{paywallVersionId:i.paywallVersionId}}(async()=>{try{let[{showPaywall:e},a]=await Promise.all([import("./paywall-6B3F557D.js"),Fe()]),t=n.commerce??W(H),i=n.locale??H?.locale,l=a&&t&&i?JSON.stringify(A([a.paywallVersionId??null,a.paywallId??null,{commerce:t,locale:i}])):null;if(Z(l),f.throwIfAborted(),r!=="preparing"||!a)return;if(!t)return d("unavailable","commerce_missing");if(!i)return d("unavailable","locale_missing");j=a;let s={commerce:t,locale:i},y=l?await Y?.read(l).catch(()=>null):null;if(f.throwIfAborted(),r!=="preparing")return;y&&(!H||y.funnelId===H.funnelId)&&(a.paywallVersionId?y.resolution.id===a.paywallVersionId:y.resolution.paywallId===a.paywallId)&&E(y.resolution,y.context.commerce)&&(m=y),M(!!m);let o;if(m){let le=m.context;s=le,o=structuredClone(m.resolution),J(le).then(Ne=>Pe(Ne,le),()=>{})}else o=await J(s);if(f.throwIfAborted(),r!=="preparing"||(!E(o,s.commerce)&&n.start instanceof Promise&&!h&&await ue,!m&&h&&!O(s,h)&&(s=h,o=await J(s)),f.throwIfAborted(),r!=="preparing"))return;if(!E(o,s.commerce))return d("unavailable","plan_unavailable");if(!te(o,s))return;P=c.ownerDocument.createElement("div"),c.append(P);let S=setTimeout(()=>r==="preparing"&&d("unavailable","timeout"),Me);we.then(()=>clearTimeout(S));let I=await e(P,ve,Ie);if(!I.host||f.aborted||r!=="preparing"){I.host?.destroy(),d(f.aborted?"released":"unavailable","error");return}b=I.host,oe()}catch(e){d(f.aborted?"released":"unavailable",ee(e))}finally{Z(null),M(!1)}})(),ue.then(async e=>{let a=s=>{me(null),_(s)};if(!e)return a("gated");let t=e,i=W(t),l=n.commerce??i;if(!O(i&&{...i,intent:void 0},l&&{...l,intent:void 0})||n.locale!==void 0&&t.locale!==n.locale)return a("start_mismatch");if(!i)return a("commerce_missing");h={commerce:i,locale:t.locale},m&&["preparing","ready","shown"].includes(r)&&(g=t,G=ce(t));try{let s=await be,y=s==="pending"?"purchase_pending":s==="found"?"original_purchase":s==="blocked"?"purchase_blocked":void 0;if(y)return a(y);if(!["preparing","ready","shown"].includes(r))return;if(n.configuration&&(n.paywallId||n.paywallVersionId)){let o=await ie(n.configuration,{funnelId:t.funnelId,customerId:n.client.customerId,parameters:t.parameters??{}});f.throwIfAborted();let S=o.type==="unknown"||o.type==="unavailable"&&o.reason!=="funnel_stopped";if(o.type==="paywall"?n.paywallVersionId?o.paywallVersionId!==n.paywallVersionId:o.paywallId!==n.paywallId:!S)return a(se(o)??"route_changed")}if(V&&(k=!1,await n.client.retained()==="pending"))return a("purchase_pending");if(j||n.paywallId||n.paywallVersionId||p){let o=await J(h);if(f.throwIfAborted(),me(E(o,h.commerce)?{savedAt:Date.now(),funnelId:t.funnelId,context:h,resolution:o}:null),m)Pe(o,h);else{if(r!=="preparing")return;if(p){if(!E(o,h.commerce))return d("unavailable","plan_unavailable");if(!te(o,h))return}}}}catch(s){return f.aborted?d("released","aborted"):_(ee(s))}["preparing","ready","shown"].includes(r)&&(g=t,G=ce(t),oe(),k&&T())},()=>_("gated"));let Se={get state(){return r},get reason(){return pe},ready:we,local:ke,get start(){return g},get prediction(){return F?structuredClone(F):void 0},matches:e=>g?ce(e)===G:!!m&&e.funnelId===m.funnelId&&e.locale===m.context.locale,open(){if(r==="preparing")return"pending";if(r!=="ready"||!v)return!1;if(Date.now()-N>=K)return d("unavailable","expired"),!1;let e=v;return v=null,L(),q("shown"),e(),"shown"},destroy(){fe.abort()}};return Re.set(Se,{onClose(e){return r==="closed"?(C(e),()=>{}):(x.add(e),()=>{x.delete(e)})},claim(){L()},async adopt(e,a){let t=e.paywall?.resolution,i=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(r!=="shown"||!b||!p||!t||!i||e.source.id!==g?.funnelId||e.locale!==g?.locale||!O(e.parameters??{},g?.parameters??{})||!["running","waiting"].includes(e.status)||!U(t,p))return null;let l;try{l=await a.start()}catch{return null}if(r!=="shown"||!b)return l.destroy(),null;w=l,u.options=a.options,u.handoff=a.handoff;for(let[o]of R)R.set(o,l.subscribe?.(o)??(()=>{})),l.view&&C(o,structuredClone(l.view));f.removeEventListener("abort",B),q("adopted"),Q(l),x.clear();let s=b,y=P;return b=null,P=null,v=null,new Proxy(s,{get(o,S){return S==="destroy"?()=>{o.destroy(),y?.remove()}:S==="retainPurchaseDialog"?()=>{let I=o.retainPurchaseDialog();if(I)return{dialog:I.dialog,release(){I.release(),y?.remove()}}}:Reflect.get(o,S,o)}})},retainPurchaseDialog(){if(r!=="shown")return;let e=b?.retainPurchaseDialog();if(!e)return;let a=P;return b=null,P=null,d("released"),{dialog:e.dialog,release(){e.release(),a?.remove()}}},get modal(){return p?.document.presentation.type!=="inline"},get revealable(){return r==="ready"&&!!v&&Date.now()-N<K},release(){d("released")}}),Se}export{xe as a,Ue as b,Ge as c};
@@ -1 +0,0 @@
1
- import{b as Bn}from"./chunk-GYIAMOZY.js";import{a as wn}from"./chunk-R4CYPCBI.js";import{a as Ln,b as Un,c as fn,d as mn,e as $e,f as Vn,h as $n,i as Mn,j as xn,k as zn}from"./chunk-QXDLOPZK.js";import{a as Jn}from"./chunk-45PGU2HW.js";import{a as Sn}from"./chunk-W32FI2A2.js";import{c as On,e as qn,f as Hn,i as Nn,j as Le,k as nn,l as _n,m as tn}from"./chunk-IM5OXTEH.js";import{b as An}from"./chunk-ZCJEXNJD.js";import{a as pn,d as Dn}from"./chunk-NDNHTG5B.js";import{C as Tn}from"./chunk-ZRGL2CAP.js";import{a as ne}from"./chunk-TK3WOD2O.js";import{a as Ie}from"./chunk-DSPLGTQI.js";function Gn(i){let E=new Set,_=new Set,n=null;async function p(a,f){let H=!1;for(;!i.stopped&&i.key===a&&i.client.pendingCommand?.requestId===f;){if(!i.client.settle)throw new ne("COMMAND_PENDING","The original display acknowledgement is still pending");await i.client.settle(f),H=!0,i.client.pendingCommand?.requestId===f&&await new Promise(L=>setTimeout(L,1500))}i.stopped||i.key!==a||(H&&await i.client.get(),!(i.stopped||i.key!==a)&&E.add(a))}function k(a,f){n=f;let H=()=>{n===f&&(n=null),_.delete(a)};return f.then(H,L=>{H(),i.busy||i.fail(L)}),f}function U(a){if(i.reviewing||E.has(a)||_.has(a)||i.stopped)return;_.add(a);let f=async()=>{if(i.reviewing||i.stopped||i.key!==a||E.has(a)){_.delete(a);return}if(i.busy||i.client.pendingCommand){setTimeout(()=>{f()},250);return}let H=(async()=>{if(i.staleRead){if(await i.staleRead,i.stopped||i.key!==a)return;if(i.client.pendingCommand){setTimeout(()=>{f()},250);return}}let L=i.client.view,oe=i.expected(),u=oe.requestId;try{await i.client.submit({operation:"shown",...oe})}catch(b){if(!(b instanceof ne)||b.code!=="CONFLICT"||b.status!==409||i.client.pendingCommand)throw b;await i.client.get();let s=i.client.view;if(i.stopped||i.reviewing||i.key!==a||!s||!L||s.id!==L.id||s.source.versionId!==L.source.versionId||s.nodeId!==oe.nodeId||s.visit!==oe.visit||s.revision<=oe.revision||s.stopped||!s.screen&&(!s.paywall||s.paywall.receiptId!==L.paywall?.receiptId)||!["running","waiting"].includes(s.status)||i.client.pendingCommand)throw b;let r=i.expected();u=r.requestId,await i.client.submit({operation:"shown",...r})}await p(a,u)})();k(a,H)};f()}function D(){if(n)return n;let a=i.client.pendingCommand;if(a?.operation!=="shown")return null;let f=i.key;return _.add(f),k(f,(async()=>{await i.client.retry(),await p(f,a.requestId)})())}return{report:U,settled:D,get inFlight(){return n}}}function Qn(i){let E={},_=new Map;async function n(p){let k=i.client.view,U=k?.screen,D=U?.customerData.nodes[p.nodeId];if(i.stopped||i.busy||!k||!U||!D)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let b=i.document,s=b?Tn(b,p.nodeId):null,r=s?.type==="customer_data"?s.data.outputs?.[p.action]:void 0;r&&U.outputs.includes(r)?await i.perform(()=>i.client.submit({operation:"submit",...i.expected(),input:{type:"screen",output:r,answers:i.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await i.onIntent?.(p,k);return}let f=p.action.startsWith("sources_")?D.resources.find(b=>b.key===p.value):null;if(p.action.startsWith("sources_")&&!f)throw new ne("INVALID_REQUEST","Choose a current resource");let H=`${k.visit}:${p.nodeId}:${f?.key??""}`,L=_.get(H)??[null],u=E[p.nodeId]??{page:1,after:null,filter:"all",...f?{resourceKey:f.key}:{}};if(p.action==="filter"){let b=p.value;if(!b||!(D.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(b))throw new ne("INVALID_REQUEST","Unknown data filter");u={page:1,after:null,filter:b},L.splice(0,L.length,null)}else if(p.action==="next"||p.action==="sources_next"){let b=f?.sources.at(-1),s=f?b?{kind:"ledger",cursor:{at:b.detail[0],id:b.id,type:"source"}}:null:U.dataCursors[p.nodeId];if(!s||!f&&!D.hasNext)return;L[u.page]=s,u={...u,page:u.page+1,after:s}}else if(p.action==="previous"||p.action==="sources_previous"){if(u.page<=1)return;u={...u,page:u.page-1,after:L[u.page-2]??null}}_.set(H,L),E={...E,[p.nodeId]:u},await i.perform(()=>i.client.get({nodeId:k.nodeId,visit:k.visit,revision:k.revision,components:E}))}return{get queries(){return E},intent:n,reset(){E={},_.clear()}}}function Wn(i){let{doc:E,holder:_,reviewHolder:n,mountScreenPreview:p}=i,k=!1,U,D=0,a=null,f="",H,L=new Map,oe=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function u(s){if(i.stopped||!i.client.review||k&&s===U&&H?.active)return;let r=!k||s!==U;k||(f=oe(i.client.view),L.set(f,structuredClone(i.answers))),k=!0,U=s,_.hidden=!0,i.suspend(!0),n.hidden=!1;let S=++D;r&&(H?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),H=nn(n,i.loadingOptions,"funnel",()=>{b()}));let A=r?H:void 0;try{if(A?.start(!1,i.client.view?.locale),S!==D||i.stopped)return;let de=i.client.review(s),N=await(A?.wait(de,Le)??de);if(i.stopped||S!==D||!k)return;if(!N.review)throw new ne("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,A||n.replaceChildren();let Q=E.createElement("div"),W=A?tn(Q,n):()=>{};n.append(Q);let O=N.run.locale.startsWith("zh"),g=i.chrome;Q.style.cssText=g.history;let j=E.createElement("p");j.textContent=O?"只读回看":"Read-only history",j.style.cssText=g.historyTitle,Q.append(j);let F=E.createElement("p");F.style.cssText=g.historyNote,F.textContent=N.review.pages.length?O?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":O?"还没有可回看的页面。":"There are no earlier pages yet.",Q.append(F);let Te=N.review.page?.receiptId,ve=E.createElement("div");ve.style.cssText=g.historyPages;for(let[K,P]of N.review.pages.entries()){let v=E.createElement("button");v.type="button",v.textContent=O?`第 ${K+1} 页`:`Page ${K+1}`;let he=Te!==void 0&&P.receiptId===Te;v.style.cssText=he?g.primary:g.secondary,he&&v.setAttribute("aria-current","page"),$e(v,()=>i.chrome.focus),v.onclick=()=>{u(P.receiptId)},ve.append(v)}if(ve.childElementCount&&Q.append(ve),N.review.page){let K=N.review.page,P=E.createElement("div");P.inert=!0,P.style.cssText=g.historyPage,Q.append(P),a=p(P,{mode:"live",rendererUrl:i.client.webViewUrl,title:K.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{S===D&&!i.stopped&&A?.present(W)},onError:he=>{if(S!==D||i.stopped)return;let Ce=new Error(he);A?.finish("error",Ce),a?.destroy(),a=null,Q.remove(),i.fail(Ce)},onEscape:()=>{b()}});let v=a;if(v.update(K.document,N.run.locale,{serverInput:{bindings:K.inputs,answers:K.answers,values:K.values}}),await v.ready,i.stopped||S!==D||!k)return}let me=O?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},z=E.createElement("div");z.style.cssText=g.historyRecords;for(let K of[...N.review.coupons.map((P,v)=>`${O?"优惠券":"Coupon"} ${v+1}: ${me[P.status]}`),...N.review.purchases.map((P,v)=>`${O?"购买":"Purchase"} ${v+1}: ${zn(P.status,O)}`)]){let P=E.createElement("p");P.textContent=K,P.style.margin="0",z.append(P)}z.childElementCount&&Q.append(z),N.review.page||A?.present(W),i.client.view&&await i.enqueue(i.client.view)}catch(de){if(S!==D||i.stopped)return;A?.finish("error",de),a?.destroy(),a=null,n.replaceChildren(),i.fail(de)}}async function b(){if(!k||i.stopped||!i.client.review)return;let s=++D;H?.finish("dismissed");try{if(await i.client.review(),i.stopped||s!==D)return;k=!1,D++,H?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,_.hidden=!1;let r=i.client.view;oe(r)!==f?(L.set(f,structuredClone(i.answers)),i.resetScreen()):(L.delete(f),i.suspend(!1)),r&&await i.enqueue(r)}catch(r){if(s!==D||i.stopped)return;a?.destroy(),a=null,n.replaceChildren(),i.fail(r)}}return{get active(){return k},get receipt(){return U},open:u,exit:b,get drafts(){return new Map([...L].map(([s,r])=>[s,structuredClone(r)]))},stop(){k=!1,D++,H?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,_.hidden=!1}}}var yn=5e3;async function et(i,E,_){let n=E,p=n.prepared&&Bn(n.prepared),k=()=>{};function U(){n.prepared&&n.prepared.state!=="adopted"&&p?.release()}let D=()=>n.prepared?.state==="shown"&&!!p?.modal,a=n.client.identitySignal,f;try{f=await Promise.all([import("./screen-renderer-3YO6EUWD.js"),import("./paywall-6B3F557D.js")]),n.signal?.throwIfAborted(),a?.throwIfAborted()}catch(e){throw U(),e}let[{mountScreenPreview:H},{showPaywall:L}]=f,oe=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Jn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;oe?.start();let u=i.ownerDocument,b=Nn(u),s=!1,r=u.createElement("section"),S=u.createElement("div"),A=u.createElement("div"),de=u.createElement("div"),N=u.createElement("button");de.hidden=!0,N.type="button";let Q=u.createElement("p"),W=u.createElement("p"),O=u.createElement("button"),g=u.createElement("button"),j=u.createElement("button"),F=u.createElement("dialog"),Te,ve=!1;r.dataset.indianaFunnel="",r.dataset.longplayCloseOwner="sdk",r.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),W.setAttribute("role","alert"),W.hidden=!0,O.type=g.type=j.type="button",A.append(O,N,Q,W,j,g),r.append(S,de,A),i.append(r);let me=Un,z=fn(me),K="",P=(u.documentElement.lang||"").startsWith("zh"),v,he="",Ce;for(let e of[O,N,j,g])$e(e,()=>z.focus);function gn(){let e=P?"关闭":"Close";g.parentElement===F?(g.textContent="×",g.setAttribute("aria-label",e),Hn(g,me)):(g.textContent=e,g.removeAttribute("aria-label"),g.style.cssText=z.link+";margin-inline-start:auto")}function Me(e){let t=e?.screen?.content.document.theme??me,o=JSON.stringify([t.primary,t.background,t.text,t.radius,t.font,g.parentElement===F]);if(o===K)return;K=o,me=t;let h=g.parentElement===F;z=fn(me,h),r.style.cssText=z.root+";min-width:0"+(h?";display:flex;flex-direction:column;min-height:100%":""),A.style.cssText=z.bar+(h?";margin-top:auto":""),A.hidden&&(A.style.display="none"),O.style.cssText=N.style.cssText=z.secondary,j.style.cssText=z.primary,Q.style.cssText=z.status,W.style.cssText=z.alert,gn(),mn(O)}function be(){A.hidden=O.hidden&&N.hidden&&j.hidden&&W.hidden&&!Q.textContent&&(g.hidden||g.parentElement!==A),A.style.display=A.hidden?"none":"flex",v?.responsive&&Ce!==void 0&&v.setContentHeight(Ce+A.getBoundingClientRect().height)}Me();let ae=null,I=null,le=null,we="",ee="",Pe=!1,xe="",rn="",ze="",l=!1,X=0,Be=!1,vn="",on=null,sn=Promise.resolve(),hn=!n.client.view,Ne,T=_,Je=n.hostPaywallTarget,Ae,_e,Ge="",Qe,te=!1,Re=null,ue=!1,We=()=>n.client.pendingCommand?.operation==="close",ie=null,V=null,an=Sn({document:u,run:async()=>{(!I?.observing||n.client.pendingCommand)&&await dn()},delay:()=>{if(!re.pending&&!(l||!le||!["running","waiting"].includes(le.status)&&!n.client.pendingCommand)&&!(I?.observing&&!n.client.pendingCommand))return le.pendingRequest||n.client.pendingCommand?1500:yn},hiddenDelay:()=>!l&&!re.pending&&n.client.pendingCommand?15e3:void 0}),M=null;function ln(){return V&&n.client.hasDurableJournal===!0&&M?.acknowledged===!0&&M.operationId===V.operationId&&n.client.view?.id===M.runId&&n.client.view?.status==="closed"&&n.client.view.revision===M.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?V:null}function In(e){let t=e.run.paywall;if(M&&e.settlement?.requestId===M.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===M.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===M.revision+1&&e.run.nodeId===M.nodeId&&e.run.visit===M.visit&&t?.receiptId===M.receiptId&&t.selectionGeneration===M.selectionGeneration&&(t.quote?.operationId??null)===M.operationId&&(t.operation?.operationId??t.quote?.operationId??null)===M.operationId){let o=M.operationId===null&&t.selectionGeneration===0&&!t.quote&&!t.operation&&!t.purchaseRequestId,h=pn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect});(o||t.canReselect===!0&&h.type==="native")&&(M.acknowledged=!0)}}let Ee=null,Ue=new Set,ce={},De=!1,Y=(e,t=null)=>{l||(e instanceof ne&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&an.destroy(),Ee=t,De=!1,W.textContent=Vn(e,P),W.hidden=!1,j.hidden=n.client.pendingCommand===null,be(),Ie(n.onError,e))},re=An({client:n.client,document:u,conceal(){l||(pe(),T?.finish("dismissed"),r.hidden=!0,s||(s=!0,b()))},async receive(e){l||await se(n.client.view??e.run)},failed(e){if(!l){if(!re.pending){ue=!1;let t=n.client.view;t&&se(t).then(()=>Y(e),Y);return}Ze(),r.parentElement!==i&&i.append(r),r.hidden=!1,O.hidden=N.hidden=g.hidden=!0,Q.textContent="",Me(),Y(e,n.client.pendingCommand?.requestId??null)}}}),Cn=()=>{l||(Ee=null,W.textContent=Mn(P),W.hidden=!1,j.hidden=!0,be())};function ke(){let e=n.client.view;if(!e)throw new ne("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let w=Wn({client:n.client,doc:u,holder:S,reviewHolder:de,mountScreenPreview:H,loadingOptions:n,get chrome(){return z},get stopped(){return l},get answers(){return ce},suspend(e){I?.setSuspended(e)},resetScreen(){we="",ee="",xe=""},enqueue:se,fail:Y}),Ve=Gn({client:n.client,expected:ke,fail:Y,get stopped(){return l},get reviewing(){return w.active},get key(){return we},get busy(){return X},get staleRead(){return on}}),je=Qn({client:n.client,expected:ke,perform:Oe,onIntent:n.onCustomerDataIntent,get stopped(){return l},get busy(){return X},get document(){return ae?.document},get answers(){return ce}}),Xe=e=>`${e.id}:${e.nodeId}:${e.visit}`,Se=e=>e&&(e.screen||e.paywall)?Xe(e):"";function ye(){let e=n.client.view;O.disabled=!w.active&&(X>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!Se(e)||ee!==Se(e)),O.hidden=!w.active&&!e?.canBack,mn(O);let t=!!I&&!w.active;g.hidden=t&&!T?.active||ve&&!w.active,N.hidden=!n.client.review||!w.active&&!e?.canBack;let o=e?.locale.startsWith("zh");Q.textContent=t?"":X>0||e?.pendingRequest?o?"正在处理":"Processing":e?.instruction?.type==="wait"?o?"等待中":"Waiting":"",be()}async function bn(e){if(!e)return;let t=n.client.view;await e;let o=n.client.view;if(!t||!o||o.id!==t.id||o.nodeId!==t.nodeId||o.visit!==t.visit||o.stopped||!["running","waiting"].includes(o.status))throw new ne("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Oe(e,t=!1,o){if(!((X||ue||ie||V)&&!t||l||w.active&&!t)){X++,r.setAttribute("aria-busy","true"),W.hidden=!0,Ee=null,De=!1,ye();try{if(t||await bn(Ve.inFlight),l)return;let h=await e();l||await se(n.client.view??h.run)}catch(h){o?.(h)&&n.client.pendingCommand===null?Cn():re.pending||Y(h,n.client.pendingCommand?.requestId??null)}finally{X=Math.max(0,X-1),r.setAttribute("aria-busy",String(X>0)),l||(j.hidden=n.client.pendingCommand===null,ye())}}}function qe(){an.schedule()}async function dn(){if(!(l||Be||X)&&!re.pending){if(w.active){await w.open(w.receipt);return}Be=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let t=n.client.view,o=je.queries,h=await n.client.get(t?.screen&&Object.keys(o).length?{nodeId:t.nodeId,visit:t.visit,revision:t.revision,components:o}:void 0);De&&!l&&(De=!1,W.hidden=!0,be()),!l&&o===je.queries&&await se(n.client.view??h.run)}catch(e){Y(e),De=!l}finally{Be=!1}}}function Ye(e,t,o){if(T?.active){let Z=T;return Z.setDismissHandler(()=>Pn(Z)),Z}let h=nn(i,n,"funnel",()=>Pn(h),Ln);return T=h,h.start(e,t,o),h}function Pn(e){l||te||(te=!0,e.finish("dismissed"),pe(),r.hidden=!0,n.client.view?ge().finally(B):B())}function un(){clearTimeout(Qe?.timeout),Qe=void 0}function pe(e){ve=!1,un(),Ae?.abort(),Ae=void 0,ae?.destroy(),ae=null,I?.destroy(),I=null,Ne=void 0,_e?.(),_e=void 0,F.open&&F.close();for(let t of Array.from(S.children))(!e||!t.contains(e))&&t.remove();S.style.cssText="",Ce=void 0,we="",ee="",Pe=!1,xe="",ze=""}function Rn(){let e=u.defaultView;v?.responsive&&e&&ae?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ze(){v?.destroy(),v=void 0,he=""}function Ke(e){let t=e.screen?.presentation;if(!t||t.type==="inline"){F.open&&F.close(),Ze(),g.parentElement!==A&&A.append(g),r.parentElement!==i&&i.append(r);for(let Z of["flex","display","flex-direction","justify-content"])S.style.removeProperty(Z);Me(e),be();return}r.parentElement!==F&&(F.append(g,r),i.append(F)),S.style.flex="1 0 auto",S.style.display="flex",S.style.flexDirection="column",S.style.justifyContent="center",Me(e);let o=e.screen.content.document,h=JSON.stringify([t,K]);if(h!==he){Ze(),he=h;let Z={sm:420,md:640,lg:900},fe="size"in t&&!t.backdrop?",0 0 0 100vmax #16142566":"";F.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${me.background};color:${me.text};`+(t.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${Z[t.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${fe};`+(t.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),v=On(F,{presentation:t,theme:o.theme,pages:o.pages},Rn),v.latch()}be(),F.setAttribute("aria-label",(Te?.screen===e.screen?.content.document.name?Te?.label:void 0)??ae?.document?.name??e.screen?.content.document.name??"Funnel")}async function jn(e){if(l||te)return;if(re.observe(),re.pending){le=e;return}if(ue&&(We()||["running","waiting"].includes(e.status))||(le=e,Ee&&n.client.pendingCommand?.requestId!==Ee&&(W.hidden=!0,Ee=null),P=e.locale.startsWith("zh"),N.textContent=P?"回看":"History",O.textContent=w.active?P?"返回当前":"Return to current":P?"返回":"Back",gn(),j.textContent=P?"重试":"Retry",j.hidden=n.client.pendingCommand===null,ye(),vn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(vn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ie(n.onState,structuredClone(e))),l||te))return;if((!e.pendingRequest||ue&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){B();return}if(e.stopped&&D()){B();return}if(e.stopped||n.client.configurationReady===!1){w.stop(),U(),pe(),T?.finish("skipped"),r.hidden=!0,qe();return}if(r.hidden=!1,w.active){qe();return}if(e.status==="completed"&&I?.subscriptionUpgradeActive){qe();return}let t=Se(e),o=n.client.view;if(o&&o.revision>e.revision&&Se(o)!==t)return;let h=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);t!==we&&(we&&T?.finish("dismissed"),pe(),we=t,ce={...e.answers},je.reset());let Z=Xe(e);if(Ge===Z){r.hidden=!0;return}if(h&&!t){r.hidden=!0;let C=n.prepared?.state==="shown"?null:Ye(!0,e.locale);!l&&!te&&Qe?.key!==Z&&(un(),Qe={key:Z,timeout:setTimeout(()=>{let d=n.client.view;if(l||!C?.active&&n.prepared?.state!=="shown"||!d||Xe(d)!==Z)return;Ge=Z;let q=new Error("Funnel screen preparation timed out");C?.finish("error",q),U(),pe(),Y(q)},Le)}),qe();return}un();let $=C=>{let d=n.client.view;return!l&&!te&&!Re&&!C.aborted&&n.client.configurationReady!==!1&&!!d&&!d.stopped&&!["closed","ineligible","failed"].includes(d.status)&&(Se(d)===t||d.status==="completed"&&I?.subscriptionUpgradeActive===!0)},fe=(C,d)=>{$(d)&&(Ge=t,T?.finish("error",C),pe(),r.hidden=!0,Y(C))};if(t||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&U(),Ke(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&T?.finish("skipped")),e.screen){Je=void 0,U();let C=e.screen.content;if(!ae){let G=e.screen.presentation.type!=="inline",R=Ye(G,e.locale);if(l||te)return;let x=(Ae=new AbortController).signal;Ke(e),_e=G?_n(F):tn(r,i),ae=H(S,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...C.document.actions.filter(y=>y.type==="event"&&y.close).map(y=>y.id)])),onAuthoredClose(y){$(x)&&(ve=y,ye())},rendererUrl:n.client.webViewUrl,title:C.document.name,...G?{hostPresentation:()=>v?.type??e.screen.presentation.type}:{},onResize:y=>{Ce=y,v?.responsive&&v.setContentHeight(y+A.getBoundingClientRect().height)},onAction(y,c={},Fe={}){if(w.active||!$(x)||ee!==t)return;ce={...ce,...Fe};let cn=e.screen?.inputs??[],Fn=Object.fromEntries(cn.filter(({variable:He})=>Object.hasOwn(ce,He)).map(({variable:He})=>[He,ce[He]]));if(xn(cn,Fn).length){Cn();return}Oe(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:y,answers:Fn,selection:c}}),!1,He=>$n(He,cn))},onAnswers:y=>{w.active||!$(x)||ee!==t||(ce={...ce,...y})},onCustomerDataIntent:y=>{w.active||!$(x)||ee!==t||je.intent(y).catch(Y)},onEscape:()=>{!$(x)||ee!==t||w.active||ie||V||ge()},onError:y=>{let c=new Error(y);ee===t?Y(c):fe(c,x)},onRendered:y=>{if(!(!$(x)||ee===t))try{R.present(c=>{_e?.(),_e=void 0,y&&(Te={screen:C.document.name,label:y},F.setAttribute("aria-label",y)),G&&(F.showModal(),s=!1,v?.responsive&&F.focus({preventScroll:!0}),!c&&n.loading!=="host"&&qn(F,v?.type??e.screen.presentation.type,v?.responsive)),ee=t,Pe=G,ye()}),$(x)&&Ve.report(t)}catch(c){fe(c,x)}}}),Rn()}let d={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:ce,values:e.screen.values}},q=JSON.stringify([C,e.locale,d.parameters,e.screen.inputs,e.screen.values]);if(q!==xe)ae.update(C.document,e.locale,d),xe=q,rn=JSON.stringify(d.capabilities),ze=JSON.stringify(d.customerData);else{let G=JSON.stringify(d.capabilities);G!==rn&&(ae.updateCapabilities(d.capabilities),rn=G),JSON.stringify(d.customerData)!==ze&&(ae.updateCustomerData(d.customerData),ze=JSON.stringify(d.customerData))}let J=ae;if(J)try{await(T?.wait(J.ready)??J.ready)}catch(G){Ae&&fe(G,Ae.signal)}}else if(e.paywall&&!I){let C=e.paywall.resolution,d="document"in C?C.document:null,q=p,J=n.mountPaywallControls,G=null,R=(Ae=new AbortController).signal,x={loading:"host",signal:R,...J&&{mountControls:c=>J(c,e)},canInteract:()=>$(R)&&!w.active&&!ie&&!V,beforeAction:async()=>{X++;try{await bn(Ve.settled()),W.hidden=!0,Ee=null,De=!1,be()}finally{X=Math.max(0,X-1)}},start:()=>wn(n.client),onObservationChange:qe,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:c=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:c,openIn:"same_window"}):u.defaultView?.location.assign(c),onAction:async c=>{if(w.active)return;let Fe=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:c,answers:{}}});await se(n.client.view??Fe.run)},onError:c=>{ee===t?Y(c):fe(c,R)}},y={quoteError:c=>Ie(n.onError,c),present(c){$(R)&&(G?.present(Fe=>{c(Fe),ee=t,Pe=y.retainedDialog?.dialog.open??!!S.querySelector("dialog[open]"),Pe&&(s=!1),ye()}),$(R)&&Ve.report(t))},async closeAction(c){l||w.active||await re.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:c,answers:{}}})},async dismiss(){if(l||R.aborted||w.active||ie||V||!ue&&!$(R))return;ue=!0;let c=n.client.view;if(c?.status==="completed"&&I?.subscriptionUpgradeActive){Ue.add(`complete:${c.id}`),Ie(n.onComplete,structuredClone(c)),B();return}if((n.resumeCheckout||n.terminateCheckout)&&Kn()){le=n.client.view,B();return}await ge()}};if(q&&J)U();else if(q){let c=await q.adopt(e,{options:x,handoff:y,start:()=>wn(n.client)});c&&$(R)&&!l?(Ke(e),I=c,Ne={runId:e.id,receiptId:e.paywall.receiptId},T?.active&&T.present(()=>{}),ee=t,Pe=q.modal,Pe&&(s=!1),ye(),Ve.report(t),w.active&&I.setSuspended(!0)):(c?.destroy(),U())}if(l||te)return;if(!I){if(G=Ye(!0,e.locale,d),l||te)return;(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.loading==="host"&&Je?.ownerDocument===u&&(y.hostPaywallTarget=Je),Je=void 0,Ke(e);let c=await L(S,x,y).catch(Fe=>(fe(Fe,R),null));!$(R)&&!(ue&&!l&&!R.aborted)?c?.host?.destroy():c&&(I=c.host,I&&(Ne={runId:e.id,receiptId:e.paywall.receiptId}),I?.setSuspended(w.active))}}if(l||te)return;ye();let m=e.instruction;if(m&&(m.type==="open_url"||m.type==="event")&&!Ue.has(m.receiptId)){let C=u.createElement("button");C.type="button",C.style.cssText=z.primary,$e(C,()=>z.focus),S.style.cssText=z.stage,C.textContent=m.type==="open_url"?`${P?"前往":"Continue to"} ${new URL(m.url).host}`:P?"继续":"Continue",C.onclick=()=>{let d=ke(),q=m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="new_window"?Xn(m.url):null;Oe(async()=>{let J="success";if(m.type==="open_url")if(n.onOpenUrl)try{J=await n.onOpenUrl({receiptId:m.receiptId,url:m.url,openIn:m.openIn})===!1?"failed":"opened"}catch(R){Ie(n.onError,R),J="failed"}else J=m.openIn==="new_window"&&!q?"failed":"opened";if(m.type==="event"){if(!n.onEvent)throw new ne("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(m.event)}if(l||n.client.view?.nodeId!==d.nodeId||n.client.view.visit!==d.visit)throw new ne("PRECONDITION_FAILED","The client action visit changed");let G=await n.client.submit({operation:"submit",...d,input:{type:"client_action",receiptId:m.receiptId,outcome:J}});return Ue.add(m.receiptId),m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="same_window"&&u.defaultView?.location.assign(m.url),G})},T?.active?T.present(()=>S.replaceChildren(C)):S.replaceChildren(C)}!e.pendingRequest&&e.status==="completed"&&!Ue.has(`complete:${e.id}`)&&(Ue.add(`complete:${e.id}`),Ie(n.onComplete,structuredClone(e))),qe()}function Xn(e){let t=u.defaultView?.open(e,"_blank")??null;return t&&(t.opener=null),t}function se(e){return ye(),sn=sn.catch(()=>{}).then(async()=>{try{await jn(e)}catch(t){throw T?.active&&(Ge=Xe(e),T.finish("error",t),pe(),r.hidden=!0),t}}),sn}let Yn=n.client.subscribe(e=>{if(!hn){if(e.stopped&&(Pe||D())&&!ue){le=e,B();return}!ue&&(e.stopped||n.client.configurationReady===!1||we&&ee!==we&&(Se(e)!==we||["closed","ineligible","failed"].includes(e.status)))&&(pe(),T?.finish("dismissed"),r.hidden=!0),se(e).catch(Y)}}),Zn=n.client.subscribeError?.(e=>{re.pending||Y(e)});function Kn(){let e=n.client.view,t=e?.paywall;return!!t?.operation&&!!e&&["running","waiting"].includes(e.status)&&Dn(pn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect}))}function ge(e){if(Re)return Re;if(l||!e&&(ie||V))return Promise.resolve();let t=!e&&We();return!t&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(le=n.client.view,B(),Promise.resolve()):(Re=Oe(async()=>{let o=t?await n.client.retry():await(e?n.client.submit.bind(n.client):re.submit)({operation:"close",...e??ke()});return e&&In(o),o},!0).then(()=>{let o=n.client.view;o?.status==="closed"&&!We()&&(le=o,B())}).finally(()=>{Re=null}),Re)}function B(){En()}function En(e){oe?.destroy(),!l&&(l=!0,re.destroy(),k(),U(),n.signal?.removeEventListener("abort",B),a?.removeEventListener("abort",B),T?.finish("dismissed"),an.destroy(),Yn(),Zn?.(),pe(e),Ze(),w.stop(),F.remove(),!e||!r.contains(e)?r.remove():(A.remove(),de.remove()),!e&&!s&&b(),Ie(n.onDismiss,le?structuredClone(le):null))}O.onclick=()=>{if(!O.disabled){if(w.active){w.exit();return}Oe(()=>n.client.submit({operation:"back",...ke()}))}},N.onclick=()=>{w.open()},g.onclick=()=>{T?.active?T.dismiss():ie||ge()},j.onclick=()=>{re.pending?re.retry().catch(()=>{}):We()?ge():Oe(()=>n.client.retry())},F.addEventListener("cancel",e=>{e.preventDefault(),T?.active?T.dismiss():ie||ge()}),n.signal?.addEventListener("abort",B,{once:!0}),a?.addEventListener("abort",B,{once:!0});let en=!1;p&&(k=p.onClose(()=>{l||te||(te=!0,T?.finish("dismissed"),pe(),r.hidden=!0,n.client.view?ge().finally(B):en=!0)}));let kn={destroy:B,refresh:dn,get recoveryPaywall(){if(I&&Ne)return{...Ne,view:I.currentResolution}},setPurchaseRecovery(e,t){return I?.setPurchaseRecovery(e,t),I!==null},retainPurchaseDialog(){let e=I?.retainPurchaseDialog();if(e)return I=null,En(e.dialog),{dialog:e.dialog,release(){e.release(),r.remove(),s||b()}}},get recovery(){let e=ln();if(e)return e;if(!l&&!X&&!ue&&!ie&&I){let t=I.recovery;if(t.type!=="native")return t}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(ie)return ie;let e=ln();if(e)return Promise.resolve(e);let t=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,o=()=>({type:"recover",operationId:t,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let m=I?.recovery;return Promise.resolve(m&&m.type!=="native"&&m.type!=="cancel"?m:o())}let h=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(m=>m.operation==="close");if(l&&!(h||V&&n.client.view?.status==="closed")||X||Be||Re||w.active||!I&&!V&&!h)return Promise.resolve(o());let Z=I,$=(async()=>{try{if(!V&&h){let d=await n.client.retry();return await se(n.client.view??d.run),o()}if(!V){let d=await Z.prepareFallback();if(d.type!=="native")return d;if(n.client.hasDurableJournal!==!0)return o();V=d}let m=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(m.length){let d=m.find(J=>J.operation==="close");if(!d||!M||d.requestId!==M.requestId)return o();let q=await n.client.retry();In(q),await se(n.client.view??q.run)}else{let d=n.client.view,q=d?.paywall;if(!d||!q||q.selectionGeneration===void 0||(q.quote?.operationId??null)!==V.operationId||V.operationId!==null&&q.canReselect!==!0)return o();let J=q.selectionGeneration,G=await n.client.get();await se(n.client.view??G.run);let R=n.client.view,x=R?.paywall;if(!R||!x||!["running","waiting"].includes(R.status)||R.stopped||R.id!==d.id||R.nodeId!==d.nodeId||R.visit!==d.visit||x.receiptId!==q.receiptId||x.selectionGeneration!==J||(x.quote?.operationId??null)!==V.operationId||V.operationId!==null&&x.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return o();let y=ke();M={runId:R.id,operationId:V.operationId,revision:y.revision,requestId:y.requestId,nodeId:R.nodeId,visit:R.visit,receiptId:x.receiptId,selectionGeneration:J,acknowledged:!1},await ge(y)}let C=ln();return C?(B(),C):o()}catch(m){return Y(m),o()}})();ie=$;let fe=()=>{ie===$&&(ie=null)};return $.then(fe,fe),$},review:w.open,exitReview:w.exit,get unappliedDrafts(){return w.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??yn)>=yn||e.instruction?.type==="evaluate_segment")&&(on=dn().finally(()=>{on=null})),await se(e);else{if(r.hidden=!0,l)throw new DOMException("Presentation cancelled","AbortError");let t=en||n.prepared?.state==="shown"?null:Ye(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(l||te&&!en)throw new DOMException("Presentation cancelled","AbortError");let o=n.client.get(),h=await(t?t.wait(o,Le):nt(o,Le));if(hn=!1,en)return l||await ge().finally(B),kn;await se(n.client.view??h.run)}}catch(e){throw T?.finish("error",e),B(),e}return kn}function nt(i,E){let _;return Promise.race([i,new Promise((n,p)=>{_=setTimeout(()=>p(new Error("Presentation data timed out")),E)})]).finally(()=>clearTimeout(_))}function St(i,E,_){return et(i,E,_)}export{et as a,St as b};