@tinkerlandai/longplay-sdk 0.10.61 → 0.10.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/dist/{chunk-4VCPJSRS.js → chunk-2TYSHLVI.js} +1 -1
- package/dist/chunk-4GSVJBO7.js +1 -0
- package/dist/{chunk-LH67TSR2.js → chunk-5II75UJQ.js} +1 -1
- package/dist/chunk-6AHZAXQE.js +1 -0
- package/dist/{chunk-SQRNYT2W.js → chunk-7G7QSSC2.js} +2 -2
- package/dist/{chunk-X7V7AAWG.js → chunk-GYIAMOZY.js} +1 -1
- package/dist/{chunk-KCLHX3Y5.js → chunk-H37TGSCQ.js} +1 -1
- package/dist/{chunk-FEBXEBDK.js → chunk-JCZ2E6QB.js} +1 -1
- package/dist/{chunk-HNNJ2RVS.js → chunk-K7ROZKFG.js} +1 -1
- package/dist/{chunk-24EPEF3N.js → chunk-LJFHEKYZ.js} +1 -1
- package/dist/{chunk-WBBP25Q2.js → chunk-OVZPLYWF.js} +1 -1
- package/dist/{chunk-DCZUPVAI.js → chunk-U5L5MKL7.js} +1 -1
- package/dist/{chunk-X6VBLJHA.js → chunk-US23EYSC.js} +1 -1
- package/dist/{content-CXXLVFDH.js → content-DVKUHVVI.js} +1 -1
- package/dist/{funnel-host-purchase-RFDAZBS6.js → funnel-host-purchase-ERJYGR3N.js} +1 -1
- package/dist/{funnel-host-recovery-paywall-HQI6ZBRL.js → funnel-host-recovery-paywall-KX4MF5VM.js} +1 -1
- package/dist/{funnel-paywall-prerender-RMSOP32P.js → funnel-paywall-prerender-ARUTTHRQ.js} +1 -1
- package/dist/{funnel-runtime-host-FI4TYAXG.js → funnel-runtime-host-HH7PJ34L.js} +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-VMEEMKO4.js → paywall-6B3F557D.js} +1 -1
- package/dist/{paywall-content-JGK22QA7.js → paywall-content-5YMPVL4L.js} +1 -1
- package/dist/{paywall-session-UTQVXDY4.js → paywall-session-EYD73DJ2.js} +1 -1
- package/dist/react-native.js +1 -1
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-IHA7BSU3.js +0 -1
- package/dist/chunk-XZLGDFZ4.js +0 -1
- /package/dist/{chunk-SQRNYT2W.js.LEGAL.txt → chunk-7G7QSSC2.js.LEGAL.txt} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.63
|
|
4
|
+
|
|
5
|
+
- When a plan change could not be charged to the saved payment method, the Paywall now says the payment didn’t go through, the plan is unchanged, and the Customer should check the payment method before choosing again.
|
|
6
|
+
|
|
7
|
+
## 0.10.62
|
|
8
|
+
|
|
9
|
+
- A named pre-render Paywall whose Funnel publishes no route stays ready and keeps its kept copy; 0.10.61 withdrew it and forgot the copy. Only a route that sends the Start elsewhere, or a paused Funnel, withdraws it
|
|
10
|
+
|
|
3
11
|
## 0.10.61
|
|
4
12
|
|
|
5
13
|
- `prerenderFunnelPurchase` with a named Paywall and `configuration` checks the Paywall against the Funnel's route for the final Start: a Start routed to another Paywall, a screen or an end makes the copy unavailable and forgets the kept copy. The preview then follows the same rule as the click
|
package/README.md
CHANGED
|
@@ -360,7 +360,7 @@ button.onclick = () => {
|
|
|
360
360
|
|
|
361
361
|
- `paywallVersionId` (one exact Version) or `paywallId` (its current published Version) names the Paywall the Funnel presents first. The copy is read with `purchase.readPaywall()` as a standalone Paywall would be, for the Start's `parameters.commerce` and `locale`.
|
|
362
362
|
- Or pass `configuration` (the page's `createConfigurationSync`) and name no Paywall: the SDK predicts this Customer's first screen from the Funnel's published route (see below) once the Start is final, and renders that Paywall. `prepared.prediction` holds the prediction. A first screen that is not a Paywall leaves the copy `unavailable` with reason `first_screen_popup`, `first_screen_page`, `first_screen_external_page`, `route_end_<outcome>` (for example `route_end_ineligible`) or `route_unknown_<reason>`; a route that is not published reads `route_unavailable`. Until a click takes it, a ready copy becomes `unavailable` (`route_changed`) when a configuration refresh routes the Start to another first screen.
|
|
363
|
-
- Name a Paywall and pass `configuration` too, and the SDK checks the named Paywall against the same route once the Start is final: a Start the route sends to another Paywall, a screen or an end makes the copy `unavailable` with the same reasons (`route_changed` for another Paywall) and forgets the kept copy, so that Customer is never shown it first. A step only the server decides, or a configuration read that failed for now, leaves the decision to the click's Run. The preview and the click then follow one rule: the Funnel's route for the click's Start.
|
|
363
|
+
- Name a Paywall and pass `configuration` too, and the SDK checks the named Paywall against the same route once the Start is final: a Start the route sends to another Paywall, a screen or an end makes the copy `unavailable` with the same reasons (`route_changed` for another Paywall) and forgets the kept copy, so that Customer is never shown it first. A step only the server decides, a route the Funnel does not publish, or a configuration read that failed for now, leaves the decision to the click's Run; a paused Funnel withdraws it. The preview and the click then follow one rule: the Funnel's route for the click's Start.
|
|
364
364
|
- `start` can be a promise while the merchant's own checks run: rendering starts at once and the copy becomes ready only with the Start. Pass provisional `commerce` and `locale` then. If admission changes only `commerce.intent`, the SDK rereads the same Paywall's server availability for the final intent before revealing it; an unavailable provisional purchase screen cannot decide upgrade eligibility. A provider, currency or locale change, `null` or a rejection leaves it `unavailable`.
|
|
365
365
|
- The SDK keeps on the device the Paywall a pre-render last read for this Customer, Paywall, commerce and locale (up to 24 hours; nothing commercial). The next pre-render of that entry paints it without any request and is ready once painted, before your checks, Longplay's original-purchase lookup or a fresh read answer, so the click needs no request to show the complete Paywall. Until the Start is final a click matches it by Funnel and locale; the Run's takeover still compares the final Start exactly. The checks and the fresh read still run: until a click takes the copy they withdraw it as usual; a revealed copy is left to the click, whose own checks and Run replace it (for example with an original purchase's recovery). A fresh read updates changed plans in place; one that names another Paywall withdraws an unclaimed copy. A refused Start or an original purchase forgets the kept copy. `prepared.local` resolves true when the copy renders from that kept Paywall: show no loading state then, and show one at once when it resolves false or `ready` resolves false.
|
|
366
366
|
- For `commerce.intent: "subscription_change"`, a purchase screen can be prepared when at least one plan is available; the current membership and other unavailable choices keep their server availability. With no available upgrade choice the copy remains unavailable. Ordinary purchase screens still require every plan to be available, and commercial actions always wait for the Run's own session.
|
package/README.zh-CN.md
CHANGED
|
@@ -241,7 +241,7 @@ SDK 在首次派发前保存原 Start 请求 ID 和完整输入;同一未决
|
|
|
241
241
|
- 公开入口的 `prerenderFunnelPurchase` 返回 Promise,需在点击前 await 得到 `PreparedFunnelPurchase`。`paywallVersionId` 指定一个确切版本,`paywallId` 指定其当前发布版本;内容通过 `purchase.readPaywall()` 按 Start 的 `parameters.commerce` 和 `locale` 读取。
|
|
242
242
|
- 商户自己的校验尚未完成时,`start` 可以传 Promise:渲染立即开始,拿到 Start 后才变为 ready。此时传入初始 `commerce` 和 `locale`;若最终只改变 commerce.intent,SDK 会按最终意图正常重新读取同一 Paywall 可用性,读取完成前不展示,不能用新购灰态判定升级资格。provider、currency 或 locale 改变、Start 为 `null` 或被拒绝时,仍为 `unavailable`。
|
|
243
243
|
- SDK 会在设备上保存预渲染最近一次为该 Customer、该 Paywall、币种渠道和语言读到的 Paywall(最长 24 小时,不含任何交易数据)。下次预渲染同一入口时不发请求直接画出它,画好即 ready,不等你的校验、Longplay 原订单查询和最新读取返回,点击时无需任何请求即可显示完整 Paywall。Start 确定前点击按 Funnel 和语言匹配,Run 接管时仍严格比较最终 Start。校验和最新读取照常进行:点击前照常撤回副本;已显示的副本交给这次点击,由它自己的校验和 Run 替换(例如原订单的恢复)。最新读取只改变套餐时原地更新;指向另一个 Paywall 时,未被认领的副本撤回。Start 被拒绝或发现原订单时会删除保存的副本。`prepared.local` 为 true 表示这次从本机保存的 Paywall 画出:此时不要显示加载状态;为 false 或 `ready` 为 false 时立即显示加载状态。
|
|
244
|
-
- 指定 Paywall 的同时传入 `configuration`,SDK 会在 Start 确定后用同一份 Funnel 路由核对它:路由把这个 Start 送到别的 Paywall、页面或结束时,副本变为不可用(另一个 Paywall 为 `route_changed`),并删除保存的副本,这位 Customer
|
|
244
|
+
- 指定 Paywall 的同时传入 `configuration`,SDK 会在 Start 确定后用同一份 Funnel 路由核对它:路由把这个 Start 送到别的 Paywall、页面或结束时,副本变为不可用(另一个 Paywall 为 `route_changed`),并删除保存的副本,这位 Customer 不会先看到它。只有服务端能决定的步骤、Funnel 未公开路由或暂时读不到配置时,交给点击时的 Run 决定;Funnel 已暂停时撤回。这样预渲染和点击走同一条规则:点击 Start 对应的 Funnel 路由。
|
|
245
245
|
- `state` 依次为 `preparing`、`ready`、`unavailable`(原因见 `reason`)、`shown`、`adopted`、`released`、`closed`;`ready` 在可显示时解析为 `true`,永远不能显示时为 `false`;`onState` 报告每次变化。
|
|
246
246
|
- 必须在点击处理函数里同步调用 `open()`(任何 await 之前):`"shown"` 表示本帧已显示;`"pending"` 表示仍在渲染,照样传给 `showFunnelPurchase`,只有在 Run 展示任何内容之前准备好才会显示,点击不会等它;`false` 表示按普通方式打开。传给 `showFunnelPurchase` 的 Start 必须与预渲染时相同(请求 ID 可以不同),`matches(start)` 可用于判断。
|
|
247
247
|
- 把 `prepared` 传给 `showFunnelPurchase`(或 `showFunnelRun`)即交给 SDK 管理。SDK 用不上时(该 client 已有展示、Start 不同或缺失、没有 Run、仅恢复 Operation 或受阻、失败、Run 先展示指令或其他内容)会释放它,已显示的副本不会留在屏幕上。已显示的展示在没有 Run 的情况下结束时,商户收到 `onDismiss(null)`,失败时收到 `onError`;接管前 Funnel 被暂停时,已显示的对话框与 Run 自己展示的一样被永久关闭。传出后不要再复用,需要时重新预渲染。
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as Ve}from"./chunk-77O2O552.js";import{a as $}from"./chunk-PJHTN5NJ.js";import{D as K,F as ze,c as Ue,e as z,j as Te,u as He,v as Le,x as Me,z as Ge}from"./chunk-X6VBLJHA.js";import{a as Fe,b as Ne,c as je}from"./chunk-VNYUL3PV.js";import{a as se}from"./chunk-NDNHTG5B.js";import{i as ue}from"./chunk-5LNX7MHO.js";import{K as G}from"./chunk-EKUDMQXT.js";import{A as ae,B as ie,C as J,E as Ae}from"./chunk-EB7MIZ4T.js";import{x as ye}from"./chunk-S5RM3VO6.js";import{b as De}from"./chunk-FEBXEBDK.js";import{a as l}from"./chunk-TK3WOD2O.js";import{h as oe}from"./chunk-RIEWU4MN.js";import{a as xe}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-PZTWDJHN.js";import{a as ge}from"./chunk-DSPLGTQI.js";var v=G.options,it=r.discriminatedUnion("operation",[v[1].omit({customerToken:!0}),v[2].omit({customerToken:!0}),v[3].omit({customerToken:!0}),v[4].omit({customerToken:!0}),v[5].omit({customerToken:!0}),v[6].omit({customerToken:!0}),v[7].omit({customerToken:!0}),v[8].omit({customerToken:!0}),Te.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),It=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:v[0].shape.requestId,funnelId:v[0].shape.funnelId,locale:v[0].shape.locale,parameters:v[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[v[3].omit({customerToken:!0}),v[4].omit({customerToken:!0}),v[5].omit({customerToken:!0}),v[6].omit({customerToken:!0}),v[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:it})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Qe=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Be=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ye=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Je=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:v[0].shape.locale,parameters:v[0].shape.parameters}),purchase:Pe})]);var st=G.options[0].refine(i=>!i.customer&&!i.customerData),ut=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),Ke=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:st,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Ue.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ut).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:He.nullable()})});function $e(i){return Me({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function We(i){let d=new URL(i.baseUrl??xe).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function R(){i.assertCurrent();try{let C=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(C.revision)||C.revision<0)throw f();let c=C.entry===null?null:Ke.parse(C.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(q=>q.operationId===c.operationCommand?.operationId))throw f();return{revision:C.revision,entry:c}}catch(C){throw C instanceof l?C:f()}}async function W(C){for(let c=0;c<8;c++){let q=await R(),O=C(structuredClone(q.entry));if(JSON.stringify(O)===JSON.stringify(q.entry))return O;O&&Ke.parse(O),i.assertCurrent();let j;try{j=await i.storage.write(q.revision,O)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=q.revision)throw f();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:R,update:W,baseUrl:d}}var ct=5*6e4,lt=2e3;function dt(i,d){let f=i.purchases.find(R=>R.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function zt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:R,sessionId:W}=f,C=!1,c=null,q,O,j=null,F=!1,U,X,Z,E={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=De(d),te=Ve(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(C||d.session.snapshot()?.customerId!==R)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=We({...d,customerId:R,assertCurrent:P,storage:d.storage??$e({baseUrl:d.baseUrl,scope:d.scope,customerId:R})}),Xe,Re=()=>Xe??=import("./funnel-paywall-copies-U3JIYQJ5.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:R})),Ze={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},et=d.session.subscribeIdentity(Se);function Se(){C||(C=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),et(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function S(e){P();let t=JSON.stringify(e)!==JSON.stringify(E);E=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(C)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==O)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function _(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=_(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&T.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=_(e).map(I=>{let k=g.get(I.operationId);return I.terminal&&!k?{type:I.terminal,operationId:I.operationId}:se({quote:k?.quote??null,operation:k??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==R)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function tt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=_(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&_(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),S(A(t,"run"))}function nt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=_(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==R)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Ae(a))?{operationCommand:void 0}:{},purchases:_(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function rt(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function ot(){let e=$(Je,await Y({operation:"find_purchase"}));if(e.customerId!==R||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:R,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<ct))return t.job;let n={at:Date.now(),job:ot().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Ye,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ce(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Be,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=_(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Le(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==R||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ce(e)),!_(e).length&&x(e))return S(A(e,"operation"));if(!_(e).length)return S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=_(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return S(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(O=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await rt(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return S({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:E.purchases,error:B(h)});throw h}let a=$(Qe,u);if(a.customerId!==R||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown")return S({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:E.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ce(e);let p=a.view;if(p.locale!==e.start.locale||!Ge(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=ze({...d,customerRun:{runId:a.target.runId,customerId:R,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:nt(),onAcceptedResponse:tt},{scope:a.scope,run:p})}try{let s=o&&q?.controller===c?performance.now()-q.at:1/0;(s>=lt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(q=void 0,await c.get(),q={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),S(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!C&&!n?.(s)&&S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:E.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return Ee();({entry:n}=await w.read())}return n?(O&&n.start.requestId!==O&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&O===n.start.requestId?fe(n,E.error):re(n,!1,!0,t)):S({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function Ee(){return S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function be(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return S(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),S(A(h,"run"))}let n=t.operationCommand?.operationId??E.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),S(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function at(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function Oe(){if(E.mode!=="operation"||E.status==="blocked")return null;let e=E.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?at(g.get(t)):null}async function _e(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(E)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return R},retained:_e,get paywallCopies(){return Ze},async findPurchase(){let e=await _e();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Fe(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([Ne(Q.request,"resolvePaywall"),import("./paywall-content-JGK22QA7.js"),import("./check-response-K56UEZ6E.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await je(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return Oe()!==null},recoverUpgradePaywall(){let e=Oe();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(E.mode!=="operation"||E.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=_(n),s=o.filter(b=>!b.terminal),u=o.filter(b=>b.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(b=>e&&e.runId===n.run?.id&&b.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(b){if(!(b instanceof l&&b.status===400&&b.code==="INVALID_REQUEST"))throw b;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(b=>d.executionPolicy.allowed.includes(b))},h);let I=ve.get(a.operationId),k=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof k!="object"||!k||!("provider"in k)||typeof k.provider!="string"||!("currency"in k)||typeof k.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:k.provider,currency:k.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let qe=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:qe,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return qe},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let b=await L(n,!1,new Set([a.operationId]));return we||S(A(b,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return Ee();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:R,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return O!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,E.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:be,retry:()=>F?be():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):S({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),S(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!_(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return S(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(dt(n,t))},async terminateCheckout(e){let t=await M();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await w.read();y(o);let s=_(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return S(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{$e as a,dt as b,zt as c};
|
|
1
|
+
import{b as Ve}from"./chunk-77O2O552.js";import{a as $}from"./chunk-PJHTN5NJ.js";import{D as K,F as ze,c as Ue,e as z,j as Te,u as He,v as Le,x as Me,z as Ge}from"./chunk-US23EYSC.js";import{a as Fe,b as Ne,c as je}from"./chunk-VNYUL3PV.js";import{a as se}from"./chunk-NDNHTG5B.js";import{i as ue}from"./chunk-5LNX7MHO.js";import{K as G}from"./chunk-EKUDMQXT.js";import{A as ae,B as ie,C as J,E as Ae}from"./chunk-EB7MIZ4T.js";import{x as ye}from"./chunk-S5RM3VO6.js";import{b as De}from"./chunk-JCZ2E6QB.js";import{a as l}from"./chunk-TK3WOD2O.js";import{h as oe}from"./chunk-RIEWU4MN.js";import{a as xe}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-PZTWDJHN.js";import{a as ge}from"./chunk-DSPLGTQI.js";var v=G.options,it=r.discriminatedUnion("operation",[v[1].omit({customerToken:!0}),v[2].omit({customerToken:!0}),v[3].omit({customerToken:!0}),v[4].omit({customerToken:!0}),v[5].omit({customerToken:!0}),v[6].omit({customerToken:!0}),v[7].omit({customerToken:!0}),v[8].omit({customerToken:!0}),Te.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),It=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:v[0].shape.requestId,funnelId:v[0].shape.funnelId,locale:v[0].shape.locale,parameters:v[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[v[3].omit({customerToken:!0}),v[4].omit({customerToken:!0}),v[5].omit({customerToken:!0}),v[6].omit({customerToken:!0}),v[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:it})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Qe=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Be=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ye=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Je=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:v[0].shape.locale,parameters:v[0].shape.parameters}),purchase:Pe})]);var st=G.options[0].refine(i=>!i.customer&&!i.customerData),ut=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),Ke=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:st,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Ue.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ut).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:He.nullable()})});function $e(i){return Me({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function We(i){let d=new URL(i.baseUrl??xe).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function R(){i.assertCurrent();try{let C=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(C.revision)||C.revision<0)throw f();let c=C.entry===null?null:Ke.parse(C.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(q=>q.operationId===c.operationCommand?.operationId))throw f();return{revision:C.revision,entry:c}}catch(C){throw C instanceof l?C:f()}}async function W(C){for(let c=0;c<8;c++){let q=await R(),O=C(structuredClone(q.entry));if(JSON.stringify(O)===JSON.stringify(q.entry))return O;O&&Ke.parse(O),i.assertCurrent();let j;try{j=await i.storage.write(q.revision,O)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=q.revision)throw f();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:R,update:W,baseUrl:d}}var ct=5*6e4,lt=2e3;function dt(i,d){let f=i.purchases.find(R=>R.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function zt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:R,sessionId:W}=f,C=!1,c=null,q,O,j=null,F=!1,U,X,Z,E={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=De(d),te=Ve(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(C||d.session.snapshot()?.customerId!==R)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=We({...d,customerId:R,assertCurrent:P,storage:d.storage??$e({baseUrl:d.baseUrl,scope:d.scope,customerId:R})}),Xe,Re=()=>Xe??=import("./funnel-paywall-copies-U3JIYQJ5.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:R})),Ze={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},et=d.session.subscribeIdentity(Se);function Se(){C||(C=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),et(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function S(e){P();let t=JSON.stringify(e)!==JSON.stringify(E);E=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(C)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==O)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function _(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=_(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&T.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=_(e).map(I=>{let k=g.get(I.operationId);return I.terminal&&!k?{type:I.terminal,operationId:I.operationId}:se({quote:k?.quote??null,operation:k??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==R)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function tt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=_(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&_(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),S(A(t,"run"))}function nt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=_(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==R)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Ae(a))?{operationCommand:void 0}:{},purchases:_(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function rt(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function ot(){let e=$(Je,await Y({operation:"find_purchase"}));if(e.customerId!==R||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:R,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<ct))return t.job;let n={at:Date.now(),job:ot().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Ye,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ce(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Be,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=_(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Le(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==R||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ce(e)),!_(e).length&&x(e))return S(A(e,"operation"));if(!_(e).length)return S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=_(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return S(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(O=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await rt(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return S({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:E.purchases,error:B(h)});throw h}let a=$(Qe,u);if(a.customerId!==R||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown")return S({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:E.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ce(e);let p=a.view;if(p.locale!==e.start.locale||!Ge(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=ze({...d,customerRun:{runId:a.target.runId,customerId:R,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:nt(),onAcceptedResponse:tt},{scope:a.scope,run:p})}try{let s=o&&q?.controller===c?performance.now()-q.at:1/0;(s>=lt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(q=void 0,await c.get(),q={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),S(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!C&&!n?.(s)&&S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:E.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return Ee();({entry:n}=await w.read())}return n?(O&&n.start.requestId!==O&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&O===n.start.requestId?fe(n,E.error):re(n,!1,!0,t)):S({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function Ee(){return S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function be(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return S(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),S(A(h,"run"))}let n=t.operationCommand?.operationId??E.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),S(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function at(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function Oe(){if(E.mode!=="operation"||E.status==="blocked")return null;let e=E.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?at(g.get(t)):null}async function _e(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(E)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return R},retained:_e,get paywallCopies(){return Ze},async findPurchase(){let e=await _e();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Fe(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([Ne(Q.request,"resolvePaywall"),import("./paywall-content-5YMPVL4L.js"),import("./check-response-K56UEZ6E.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await je(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return Oe()!==null},recoverUpgradePaywall(){let e=Oe();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(E.mode!=="operation"||E.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=_(n),s=o.filter(b=>!b.terminal),u=o.filter(b=>b.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(b=>e&&e.runId===n.run?.id&&b.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(b){if(!(b instanceof l&&b.status===400&&b.code==="INVALID_REQUEST"))throw b;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(b=>d.executionPolicy.allowed.includes(b))},h);let I=ve.get(a.operationId),k=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof k!="object"||!k||!("provider"in k)||typeof k.provider!="string"||!("currency"in k)||typeof k.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:k.provider,currency:k.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let qe=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:qe,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return qe},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let b=await L(n,!1,new Set([a.operationId]));return we||S(A(b,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return Ee();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:R,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return O!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,E.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:be,retry:()=>F?be():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):S({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),S(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!_(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return S(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(dt(n,t))},async terminateCheckout(e){let t=await M();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await w.read();y(o);let s=_(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return S(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{$e as a,dt as b,zt as c};
|
|
@@ -0,0 +1 @@
|
|
|
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 +1 @@
|
|
|
1
|
-
import{e as p}from"./chunk-NAFHQVSX.js";import{c as g}from"./chunk-VNYUL3PV.js";import{a as $}from"./chunk-NDNHTG5B.js";import{e as Y,f as X,g as Z,h as ee,i as re}from"./chunk-5LNX7MHO.js";import{b as B}from"./chunk-C3HZCZVJ.js";import{b as F}from"./chunk-
|
|
1
|
+
import{e as p}from"./chunk-NAFHQVSX.js";import{c as g}from"./chunk-VNYUL3PV.js";import{a as $}from"./chunk-NDNHTG5B.js";import{e as Y,f as X,g as Z,h as ee,i as re}from"./chunk-5LNX7MHO.js";import{b as B}from"./chunk-C3HZCZVJ.js";import{b as F}from"./chunk-LJFHEKYZ.js";import{b as j}from"./chunk-4OODZM64.js";import{A as x,B as R,E as K,z as J}from"./chunk-EB7MIZ4T.js";import{x as G}from"./chunk-S5RM3VO6.js";import{b as W}from"./chunk-JCZ2E6QB.js";import{a as M}from"./chunk-HUYKZH3H.js";import{t as H}from"./chunk-VXDVMAS6.js";import{a}from"./chunk-TK3WOD2O.js";import{a as z}from"./chunk-DSPLGTQI.js";function ae(I){let t=[...new Set(I.map(({path:s})=>{let c=s.map(String).join(".");return c.startsWith("selector")?"paywallId or paywallVersionId":c||"input"}))],O=t.includes("locale")?` Pass locale, the Customer's language such as "en" or "zh-CN".`:"";return new a("INVALID_REQUEST",`createPaywallSession input is invalid: ${t.join(", ")}.${O}`)}async function Ie(I,t){if(!M.test(t.customerToken))throw new a("INVALID_TOKEN","A verified Customer credential is required");if(I.session&&I.session.peek()!==t.customerToken)throw new a("SCOPE_MISMATCH","Paywall credential does not match the shared session");let O=p.resolvePaywall.request.safeParse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}});if(!O.success)throw ae(O.error.issues);let s=O.data,c=W(I);I.session||c.identify(t.customerToken);let n=null,v=!1,U=new AbortController,u=null,d=null,b=null,P=null,T=null,y=null,m=null,A=0,q=null,k="",D=0,C=new Map,E=new Set;function S(){if(v)throw new a("IDENTITY_CHANGED","Paywall is closed")}function L(){let e=JSON.stringify([A,m!==null]);if(!q||e!==k){k=e;let r=te(++D);q=r;let i=()=>{q===r&&(q=null)};r.then(i,i)}return q.then(r=>structuredClone(r))}async function te(e){S();let r=p.resolvePaywall,i=await g(c.request,r,{...s,selector:n?{type:"version",versionId:n.id}:s.selector});B(s,i.paywall.check,i.scope);let l=await F(I,i.paywall);if(S(),t.paywallVersionId?l.id!==t.paywallVersionId:l.paywallId!==t.paywallId)throw new a("INVALID_RESPONSE","The requested Paywall changed");if(n&&(!Y(l,n)||l.paywallId!==n.paywallId))throw new a("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(e!==D)return structuredClone(n??l);n=l;for(let h of E)z(h,structuredClone(n));return structuredClone(n)}async function Q(e){if(S(),P&&e!=="read")throw new a("COMMAND_PENDING","Wait for the original quote");if(!u)throw new a("INVALID_REQUEST","A quoted purchase is required");let r=u;if(e!=="read"){if(m){if(y===e)return m;throw new a("COMMAND_PENDING","Wait for the original purchase command")}if(y&&y!==e)throw new a("COMMAND_PENDING","Read the original purchase before changing an uncertain command");y=e,A++,D++}let i=y,l=A,h=e==="read"&&m===null,f=JSON.stringify([r.operationId,l,m!==null]);if(e==="read"&&C.has(f))return C.get(f).then(o=>structuredClone(o));let w=(async()=>{let o={operationId:r.operationId,...e==="read"?{}:{intent:e},...e==="confirm"&&r.merchantTerms?{merchantConfirmation:G(r.merchantTerms)}:{}},V=R(r)?e==="read"?await g(c.request,p.readSubscriptionUpdate,o):await g(c.request,p.update,o):e==="read"?await g(c.request,p.readSubscriptionOperation,o):await g(c.request,p.attach,o),N=x.parse(V.operation);return N.quote&&ee(r,N.quote),X(N,{operationId:r.operationId,currency:s.commerce.currency,membershipId:R(r)?r.membershipId:null,...R(r)?{featureQuantities:r.featureQuantities??{}}:{}},"The purchase operation changed"),S(),u?.operationId!==r.operationId?structuredClone(N):(d=re(d,N),(e!=="read"||h&&m===null)&&A===l&&y===i&&(y=null),structuredClone(d))})();if(e!=="read"){m=w;let o=()=>{m===w&&(m=null)};w.then(o,o)}else{C.set(f,w);let o=()=>{C.get(f)===w&&C.delete(f)};w.then(o,o)}return w.then(o=>structuredClone(o))}let _={signal:U.signal,get view(){return n?structuredClone(n):null},get quote(){return u?structuredClone(u):null},get operation(){return d?structuredClone(d):null},get webViewUrl(){return"bundled"},get locale(){return s.locale},get recovery(){return $({quote:u,operation:d,requestId:T,pending:P!==null||y!==null,destroyed:v})},get pendingCancellation(){return!v&&y==="cancel"},refresh:L,subscribe(e){return v?()=>{}:(E.add(e),()=>E.delete(e))},async preview(e){if(S(),!n)throw new a("INVALID_REQUEST","Load the Paywall first");let r=n.document.buttons[e.actionId];if(r?.type!=="checkout")throw new a("INVALID_REQUEST","Choose an authored purchase action");let i=j(r.product,e.selection,n.capabilities);if(!i)throw new a("PRODUCT_UNAVAILABLE","Choose an available Product");let l=H(n.document.screen,i,e.selection,n.capabilities);if(s.commerce.intent==="subscription_change"&&!e.subscriptionChange)throw new a("INVALID_REQUEST","Choose the existing membership for this subscription change");if(e.subscriptionChange&&e.nativeOffer)throw new a("INVALID_REQUEST","A web membership change cannot include a store offer");let h=e.subscriptionChange?p.previewUpdate.request.parse({requestId:e.requestId,...e.subscriptionChange,change:{type:"plan",productVersionId:i,...Object.keys(l).length?{featureQuantities:l}:{}},...e.offerId?{offerId:e.offerId}:{}}):p.previewAttach.request.parse({funnelId:s.funnelId,funnelVersionId:s.funnelVersionId,requestId:e.requestId,plans:[{productVersionId:i,...Object.keys(l).length?{featureQuantities:l}:{}}],provider:s.commerce.provider,currency:s.commerce.currency,...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{}}),f=JSON.stringify(h);if(b&&b!==f&&(P||y||!d||K(d)))throw new a("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(b===f){if(P)return P;if(u)return structuredClone(u)}b!==f&&(u=null,d=null),b=f,T=h.requestId;let w=(async()=>{let o="membershipId"in h?await g(c.request,p.previewUpdate,h):await g(c.request,p.previewAttach,h),V=J.parse(o.quote);return S(),Z(V,{productVersionId:i,featureQuantities:l,currency:s.commerce.currency,provider:s.commerce.provider,subscriptionChange:e.subscriptionChange},"The purchase quote changed its selected Product or presentment"),u=V,d=null,structuredClone(u)})();P=w;try{return await w}finally{P===w&&(P=null)}},confirm:()=>Q("confirm"),cancel:()=>Q("cancel"),read:()=>Q("read"),destroy(){v||(v=!0,U.abort(),E.clear(),C.clear(),ne?.(),c.dispose(),n=null,u=null,d=null,b=null,T=null)}},ne=I.session?.subscribeIdentity(_.destroy);try{return await L(),_}catch(e){throw _.destroy(),e}}export{Ie as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as mn,c as bn,d as Tt,f as Ot,g as Cn,k as vn}from"./chunk-QXDLOPZK.js";import{a as un,b as ze}from"./chunk-W32FI2A2.js";import{d as dn,e as fn,f as pn,g as hn,i as St,j as it,k as yn,l as wn,m as gn}from"./chunk-IM5OXTEH.js";import{a as on,c as xt,d as sn,e as ln}from"./chunk-NDNHTG5B.js";import{a as rt,b as ae,d as Rt,f as At,j as cn}from"./chunk-5LNX7MHO.js";import{b as Ie}from"./chunk-4OODZM64.js";import{B as N,C as nt,D as Ge,E as De,y as an}from"./chunk-EB7MIZ4T.js";import{r as _e,t as Ue}from"./chunk-VXDVMAS6.js";import{i as rn}from"./chunk-ZRGL2CAP.js";import{c as ge,j as We}from"./chunk-KTWKDR5L.js";import{c as Et}from"./chunk-XCFAKO23.js";import{a as k}from"./chunk-TK3WOD2O.js";import{a as G}from"./chunk-DSPLGTQI.js";async function Pn($,a,E){if(!Ge(a))throw new k("INVALID_RESPONSE","A verified completed purchase is required");let T=$?We.parse($):null;if(await E.onComplete?.(a),!T||!E.check)return;let j=We.parse(await E.check());if(j.internal_feature_id!==T.internal_feature_id||j.quantity!==T.quantity||T.observation!==void 0&&(j.observation===void 0||j.observation.requirementDigest!==T.observation.requirementDigest||j.observation.authority!==T.observation.authority||Et(j.observation.subject)!==Et(T.observation.subject)))throw new k("INVALID_RESPONSE","The access requirement changed");j.allowed&&await E.onAccessGranted?.(j)}function kn($){return Object.entries($.document.buttons).filter(([,a])=>a.type==="checkout"&&a.product.type==="fixed"&&!Ie(a.product,{},$.capabilities)).map(([a])=>a)}function In($,a){let E=N(a)?void 0:a.lines[0];if(!N(a)&&(a.lines.length!==1||!E))return;let T=N(a)?a.productVersionId:E.productVersionId,{screen:j,buttons:oe}=$.document,U=new Map(N(a)?Object.entries(a.featureQuantities??{}):(E?.prepaid??[]).map(b=>[b.internal_feature_id,b.quantity]));function se(b,c){if(b.hidden)return!1;if(b.type==="plan_picker"&&$.capabilities.pickers[b.id]?.options.includes(T))return c[b.id]=T,!0;if(b.type==="quantity_picker"){let te=U.get(b.internalFeatureId);return te!==void 0&&(!b.bind?.plan||b.bind.plan===T)&&(c[b.id]=te),!1}if(b.type==="button"&&b.action){let te=oe[b.action];return te?.type==="checkout"&&te.product.type==="fixed"&&te.product.productVersionId===T}if(b.type!=="stack")return!1;let ee=b.interaction,i=b.bind?.plan===T;for(let[te,p]of b.children.entries()){let ne={},D=se(p,ne);if(ee?.type==="toggle"||ee?.type==="tabs"){if(!D)continue;return c[b.id]=ee.type==="toggle"?te===0:p.id,Object.assign(c,ne),!0}Object.assign(c,ne),D&&(i=!0,ee?.type==="select"&&ee.purpose==="product"&&ee.pickerId&&p.type==="stack"&&p.bind?.plan===T&&(c[b.id]=p.id,c[ee.pickerId]=T))}return i}for(let b of j.pages){let c={__page:b.id};if(se(b.root,c))return c}}async function dr($,a,E){let T=a.focusAtReveal?()=>{}:St($.ownerDocument),j=()=>{U.finish("dismissed"),T()},oe=()=>j(),U=yn($,a,"paywall",()=>{j(),G(a.onDismiss)},mn);a.signal?.throwIfAborted(),a.signal?.addEventListener("abort",oe,{once:!0});let se=null,b,c,ee;try{if(U.start(!0,a.loadingDocument?.screen.strings.defaultLocale,a.loadingDocument??null),U.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(se=a.check?We.parse(await U.wait(a.check(),it)):null,se?.allowed)return U.finish("skipped"),a.signal?.removeEventListener("abort",oe),T(),await a.onAccessGranted?.(se),{check:se,host:null};let[e,t]=await Promise.allSettled([U.wait(import("./screen-renderer-3YO6EUWD.js")),U.wait(a.start().then(r=>(U.cancelled&&r.destroy(),r)),it)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;ee=e.value,b=t.value,a.signal?.throwIfAborted(),b.signal?.throwIfAborted(),b.signal?.addEventListener("abort",oe,{once:!0});let n=b.view??await U.wait(b.refresh(),it);if(!n)throw new k("INVALID_RESPONSE","Paywall presentation is missing");b.signal?.throwIfAborted(),c=n}catch(e){throw U.finish("error",e),E?.retainedDialog?.release(),a.signal?.removeEventListener("abort",oe),b?.signal?.removeEventListener("abort",oe),b?.destroy(),T(),e}let i=b,{mountScreenPreview:te}=ee,p=$.ownerDocument,ne=new AbortController,D=p.createElement("section"),pe=p.createElement("div"),F=p.createElement("div"),at=a.mountControls,X=at?p.createElement("div"):void 0,d=p.createElement("p"),h=p.createElement("button"),le=p.createElement("button"),O=p.createElement("button");(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&E?.hostPaywallTarget&&!E.retainedDialog&&c.document.presentation.type==="modal"&&(E.retainedDialog=hn(E.hostPaywallTarget));let ce=E?.retainedDialog,R=ce?.dialog??p.createElement("dialog"),Le=ce&&c.document.presentation.type==="inline"?{type:"modal",size:"md"}:c.document.presentation,re=Le.type==="inline"?F:p.createElement("div"),ot=i.locale||c.document.screen.strings.defaultLocale,o=ot.toLowerCase().startsWith("zh"),En=o?"正在处理…":"Processing…",xn=o?"正在准备报价…":"Preparing your price…",L=bn(c.document.screen.theme);D.dataset.indianaPaywall="",D.setAttribute("aria-label",c.document.name),D.style.cssText=L.root,F.style.cssText=L.controls,d.style.cssText=L.message,d.setAttribute("role","status"),O.style.cssText=L.link,O.textContent=o?"关闭":"Close",h.style.cssText=L.secondary,h.textContent=o?"重试":"Retry",h.hidden=!0,le.type="button",le.style.cssText=L.primary,le.textContent=o?"继续付款":"Continue payment",le.hidden=!0,re.append(d,le,h),F.append(O),X&&(X.style.cssText="flex:1 0 100%;min-width:0",X.hidden=!0,F.prepend(X)),re!==F&&(re.dataset.indianaPaywallStatus="",re.style.cssText="display:none;padding:0",D.append(re)),D.append(pe,F);let st=()=>{let e=s=>!s.hidden&&(s!==d||!!d.textContent);if(re!==F&&(re.style.cssText=!ie&&[...re.children].some(e)?`${L.controls};padding:12px 64px 12px 20px;flex-shrink:0`:"display:none;padding:0"),X){let s=!X.childElementCount&&!X.textContent?.trim();X.hidden!==s&&(X.hidden=s)}let t=me??F,n=![...t.children].some(e),r=[...t.children].some(s=>s!==O&&e(s));t.style.cssText=n?L.controls.replace(/padding:[^;]+/,"padding:0"):r?`${L.controls};${L.pinned}`:L.controls,ct()},Nt=typeof MutationObserver>"u"?void 0:new MutationObserver(st);Nt?.observe(D,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let Rn=Object.entries(c.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),H,Dt,Me=!1,_t=JSON.stringify(c.capabilities),q;function be(e){let t=kn(e);if(q||he&&!fe||Q&&(C||!Re()||ye))return $e(e).map(({actionId:r})=>r);if(mt()||!C&&Re())return t;let n=C?Ht(e):Qt(e);return[...new Set([...t,...$e(e).map(({actionId:r})=>r).filter(r=>!n.includes(r))])]}function Ve(e){if(g)return;let t=c.id!==e.id;c=e;let n=JSON.stringify(e.capabilities);if(t||n!==_t){let r=!P&&!i.quote&&!i.operation?rt(e,z,Mt):z;t||JSON.stringify(r)!==JSON.stringify(z)?(z=r,H?.update(e.document.screen,ot,{capabilities:ae(e),unavailableActions:be(e),serverInput:{bindings:[],answers:{}},selection:z})):H?.updateCapabilities(ae(e),be(e)),_t=n}Sn(e),ve()}let _,lt=0;function Ut(){return(me??F).getBoundingClientRect().height+(re===F?0:re.getBoundingClientRect().height)}function ct(){let e=p.defaultView;if(!_?.responsive||!e)return;let t=me??F,n=e.innerHeight-(_.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",lt=Math.max(1,n-Ut()),H?.resizeViewport?.(lt,e.innerWidth)}let g=!1,he=!1,P=null,ut,Ye=!1,Lt=!1,Ce=!1,dt,ft=!1,ie,me;function An(){return he||g||ie||ft?{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null}:xt(i)}let I=()=>!g&&!Ye&&!ie&&a.canInteract?.()!==!1,Y,Ee=!1,xe=!1,u=null,ue=null,Ke="",de=()=>a.checkoutNavigation==="after_confirmation"&&!!(a.terminateCheckout||a.resumeCheckout),z={},Mt=new Set,fe,C;function pt(e){return!!e&&N(e)&&e.timing==="immediate"&&e.execution.provider==="merchant"}let ht=o?"正在确认付款…":"Confirming payment…",Q=null,ye,Je,Vt=!1,Re=()=>a.allowNewPurchase!==!1||Vt;function $e(e){return Object.entries(e.document.buttons).flatMap(([t,n])=>n.type==="checkout"?[{actionId:t,policy:n}]:[])}function $t(e){let t=C?.quote;return t?$e(e).filter(({actionId:n,policy:r})=>Ae(t,e,n,r.product,z)).map(({actionId:n})=>n):[]}function Ht(e){return C?.phase==="payment"?$t(e):[]}function mt(){return(C?C.phase==="payment":!Re())&&(Re()||!!a.prepareUpgradeReplacement)&&de()&&!!a.terminateCheckout&&!!i.quote&&i.canReselect===!1&&!!i.operation&&x(i.operation).type==="checkout"}function Qt(e){let t=i.quote;return!de()||Q||!t||!i.operation||x(i.operation).type!=="checkout"?[]:$e(e).filter(({actionId:n,policy:r})=>Ae(t,e,n,r.product,z)).map(({actionId:n})=>n)}function ve(){let e=q?[]:C?Ht(c):Qt(c),t=a.allowNewPurchase===!1&&!!i.operation&&x(i.operation).type==="checkout";if(le.hidden=!!q||(C?C.phase!=="payment":!t)||e.length>0,!de()&&!C||!H?.updateCheckoutControls)return;let n=!q&&C?.phase==="checking"?fe:void 0;H.updateCheckoutControls({actions:$e(c).map(({actionId:r})=>r),resume:n?[n]:e,resumeLabel:n?ht:o?"继续付款":C?"Continue payment":"Continue checkout",busy:fe})}function Bt(){ue?.remove(),ue=null}async function Xe(){if(Q)return;if(a.resumeCheckout&&i.operation){let t=i.operation.operationId;try{await a.resumeCheckout(t)}catch(n){if(!(n instanceof k&&n.code==="PURCHASE_PENDING"))throw n;let r=await i.read();if(!I())return;if(r.operationId!==t||x(r).type==="checkout")throw n;await M(r,!1)}return}let e=await i.read();if(x(e).type!=="checkout")return M(e,!1);I()&&(He.delete(e.operationId),await Qe(e))}function yt(){ye?.destroy(),ye=void 0,Je=void 0}function jt(){let e=Q;if(!e||ye)return;let t=o?"仍在核对原订单,暂时无法更换套餐。":"We’re still checking the original purchase before changing plans.",n=Date.now()+6e5,r=un({document:p,delay:()=>Date.now()<n?5e3:void 0,async run(){if(!I())return;let s=await i.read();if(ye!==r||!I())return;if(s.operationId!==e.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");let f=x(s);f.type==="native"?(yt(),d.textContent=o?"原订单已关闭。你可以继续更换套餐。":"The original checkout is closed. You can continue changing plans.",h.textContent=o?"继续更换套餐":"Continue changing plans",u=()=>Ze(),h.hidden=!1):(f.type==="complete"||f.type==="fulfillment"||f.type==="recording")&&(yt(),Q=null,h.hidden=!0,await M(s,!1))}});ye=r,Je=async()=>{try{await r.refresh()}finally{ye===r&&(d.textContent=t,h.hidden=!1)}},u=Je,h.textContent=o?"查询结果":"Check result",h.hidden=!1,d.textContent=t,r.schedule()}async function Ze(e=!1){let t=Q;if(!t)return;u=()=>Ze(),C&&(h.textContent=o?"查询状态":"Check status"),h.hidden=!0;let n=Date.now()+2e4;for(;I();){let r=await i.read();if(r.operationId!==t.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");if(!I())break;let s=x(r);if(s.type==="native"){if(!Re()&&a.prepareUpgradeReplacement){let f=await a.prepareUpgradeReplacement(t.operationId,t.intent);if(!I())return;Vt=!0,Ve(f)}Q=null,C&&Se(C.quote),Bt(),P=t.selection,Y=t.coupon,Ee=!1,xe=!1,await Fe();return}if(s.type==="complete"||s.type==="fulfillment"||s.type==="recording"){Q=null,C?await Pe(C.quote,r):await M(r,!1);return}if(e&&s.type==="checkout"){e=!1;try{await a.terminateCheckout(t.operationId)}catch(f){G(a.onError,f)}}if(Date.now()>=n){C&&s.type==="checkout"&&(Q=null,await Pe(C.quote,r));break}await ze(1e3,p,ne.signal)}!Q||g||(C?(d.textContent=o?"仍在核对原升级单,暂时无法更换套餐。":"We’re still checking the original upgrade before changing plans.",h.hidden=!1):jt())}async function Ft(e,t,n,r){if(u=()=>Ft(e,t,n,r),await a.beforeCheckoutReplacement?.(structuredClone(r)),!I())return;let s=i.operation;if(s?.operationId!==e||x(s).type!=="checkout"){u=null,s&&await M(s,!1);return}Q={operationId:e,selection:t,coupon:n,intent:r},C&&(d.textContent=o?"正在切换套餐…":"Changing plan…",h.hidden=!0);let f=!1;try{await a.terminateCheckout(e)}catch(l){if(l instanceof k&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(l.code)){Q=null,C&&(u=bt,h.textContent=o?"查询状态":"Check status",h.hidden=!1),d.textContent=o?"请继续原订单,或等待它过期后再更换方案。":"Continue your original checkout, or wait for it to expire before changing plans.",G(a.onError,l);return}f=l instanceof k&&(l.status??0)>=500,G(a.onError,l)}I()&&await Ze(f)}function wt(e,t,n,r,s){let f=ae(e).checkoutCoupons?.[t],l=f?f.products[n]:a.claimCoupon&&s?rn(e.capabilities,s,r):void 0;return l?.couponId&&l.planVersionId===n?{id:l.couponId,offerId:l.offerId}:void 0}function Sn(e){he||P||i.quote||i.operation||Ke&&d.textContent===Ke||(d.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":o?"当前账号暂无可购买的方案。":"No plans are currently available for this account.")}let He=new Map,et=!1;function Ae(e,t,n,r,s,f){let l=N(e),y=!l&&e.lines.length===1?e.lines[0]:void 0,m=Ie(r,s,t.capabilities);if(!m||m!==(l?e.productVersionId:y?.productVersionId))return!1;let A=wt(t,n,m,s,f),K;try{K=Ue(t.document.screen,m,s,t.capabilities)}catch{return!1}if(l){let J=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return Object.keys(K).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(K).every(([Ne,It])=>e.featureQuantities?.[Ne]===It)&&(!A||J?.couponId===A.id&&(!A.offerId||J.grantId===A.offerId))}if((A||ae(t).checkoutCoupons?.[n])&&(A?.id??null)!==(e.discount?.couponId??null))return!1;let Z=Object.fromEntries((y?.prepaid??[]).map(J=>[J.internal_feature_id,J.quantity]));return[...new Set([...Object.keys(K),...Object.keys(Z)])].every(J=>(K[J]??0)===(Z[J]??0))}let x=e=>on({quote:i.quote,operation:e,requestId:null,pending:!1,destroyed:g,canReselect:i.canReselect});async function Qe(e){let t=e.merchantExecution,n=x(e),r=n.type==="checkout"?n.checkoutUrl:e.checkoutUrl;if(!(!I()||!r||nt(e)&&n.type!=="checkout"||a.checkoutNavigation==="after_confirmation"&&n.type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||He.get(e.operationId)===r)){He.set(e.operationId,r);try{a.onCheckoutUrl?await a.onCheckoutUrl(r):p.defaultView?.location.assign(r)}catch(s){throw He.delete(e.operationId),s}}}let we=(e,t=!1)=>{if(e instanceof Rt)u=null,d.textContent=e.customerMessage(o);else if(Cn(e))u=null,d.textContent=t?o?"当前无法在此购买,付款尚未开始。请联系商户。":"Purchases aren’t available here right now. Payment hasn’t started. Contact the merchant for help.":Ot(e,o);else if(t){let n=e instanceof k?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(u=null,d.textContent=o?"暂时无法为此套餐报价,付款尚未开始。":"Pricing for this plan is unavailable. Payment hasn’t started."):i.canReselect===!0&&!P?d.textContent=o?"未能取得报价,付款尚未开始。请重新选择套餐。":"We couldn’t prepare your price. Payment hasn’t started. Choose a plan again.":n==="COMMAND_PENDING"?d.textContent=o?"仍在准备报价,请重试以查看结果。":"Your price is still being prepared. Retry to check the result.":d.textContent=o?"未能取得报价,付款尚未开始。请重试。":"We couldn’t prepare your price. Payment hasn’t started. Try again."}else d.textContent=e instanceof k&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?Ot(e,o):e instanceof k?e.message:o?"操作未完成,请重试。":"This action couldn’t be completed. Try again.";h.hidden=u===null,Ke=d.textContent,t&&fe===void 0&&!_?.responsive&&d.scrollIntoView?.({block:"nearest"}),G(t&&E?.quoteError?E.quoteError:a.onError,e)},Be=new WeakMap;function je(e){he=e,h.disabled=e,le.disabled=e,H?.updateCapabilities?.(ae(c),be(c));for(let t of ue?.querySelectorAll("button")??[])e?(Be.has(t)||Be.set(t,t.disabled),t.disabled=!0):Be.has(t)&&(t.disabled=Be.get(t),Be.delete(t)),Tt(t)}function qt(){q&&(d.textContent=q.message,h.textContent=o?"重试":"Retry",h.disabled=!1,h.hidden=!q.retry,le.disabled=!0)}function gt(){d.textContent=o?"暂时无法操作,请稍后重试。":"This action is unavailable right now. Try again in a moment."}async function Tn(e){if(a.beforeAction)try{await a.beforeAction()}catch(t){throw t instanceof Rt?(P=null,Ee=!1,xe=!1,u=null):u=e,t}}async function B(e,t){if(he||g||q)return;if(!I()){gt();return}let n=e===Fe,r=n?xn:En,s=de()&&t!==void 0;fe=s?t:void 0,je(!0),ve(),h.hidden=!0,d.textContent=s?"":r;try{if(e!==Jt&&e!==bt&&e!==Ct&&e!==Je&&(e!==Xe||!a.resumeCheckout)&&await Tn(e),g||q)return;if(!I()){u=e,h.hidden=!1,gt();return}await e()}catch(f){g||we(f,n)}finally{fe=void 0,je(!1),ve(),q?qt():d.textContent===r&&(d.textContent="")}}async function Wt(e){await Pn(se,e,a)}function Se(e,t){C=t?{quote:e,phase:t}:void 0,t==="checking"?(fe??=P?.actionId??$t(c)[0],d.textContent=ht,u=bt,h.textContent=o?"查询状态":"Check status",h.hidden=!0):fe=void 0,H?.updateCapabilities(ae(c),be(c)),ve()}function Gt(e){return e instanceof k&&(e.code==="COMMAND_PENDING"||e.reason==="RESULT_UNKNOWN"||e.code==="NETWORK_ERROR"||e.code==="TIMEOUT"||e.status===429||(e.status??0)>=500)}function zt(e,t){At(e,{...t,featureQuantities:t.featureQuantities??{}},"Purchase operation changed")}async function bt(){C&&await Pe(C.quote)}async function Pe(e,t){Se(e,"checking"),Ke="";let n=1e3;Me=!0,G(a.onObservationChange,!0);try{for(let r=t;I();r=void 0){if(!r){try{r=await i.read()}catch(s){if(!Gt(s))throw s}if(!I())return}if(r){zt(r,e);let s=x(r);if(s.type==="checkout"){Se(e,"payment"),d.textContent=o?"请先完成原订单的付款。":"Finish paying for this upgrade.",h.hidden=!1;return}if(s.type==="complete"){Se(e,"complete"),u=null;let f=c.capabilities.plans[e.productVersionId]?.name,l=e.merchantTerms?.subscriptionTerms?.items,y=l?.length===1?l[0].interval:void 0,m=y==="year"?o?"年付":"annual billing":y==="month"?o?"月付":"monthly billing":null;d.textContent=f?o?`已升级到 ${f}${m?" "+m:""}。`:`Upgraded to ${f}${m?" ("+m+")":""}.`:o?"已成功升级。":"Plan upgraded.",await Wt(r);return}if(s.type==="native"&&!De(r)){Se(e),P=null,u=null,d.textContent=o?"付款没有成功,套餐未变更。请检查付款方式后重新选择套餐。":"Your payment didn’t go through, so your plan is unchanged. Check your payment method, then choose a plan again.",h.textContent=o?"重试":"Retry";return}if(r.problem&&!["RESULT_UNKNOWN","STATE_CHANGED"].includes(r.problem.reason??""))throw new k(r.problem.code,o?"暂时无法完成升级。":"The upgrade needs attention.",void 0,void 0,r.problem)}await ze(n,p,ne.signal),n=Math.min(n*1.5,15e3)}}finally{Me=!1,G(a.onObservationChange,!1)}}async function Ct(){let e=C?.quote;if(!e)return;let t=await i.read();if(zt(t,e),x(t).type!=="checkout")return Pe(e,t);if(a.resumeCheckout){await a.resumeCheckout(t.operationId);return}He.delete(t.operationId),await Qe(t)}function Yt(e){return xt(i).type==="recording"||x(e).type==="recording"}function Kt(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],r=t?t.totalMinor:N(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),s=t?n.length===1&&n[0]?.amountMinor===r&&n[0]:!N(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],f=r===null?ge(t.subtotalMinor-t.discountMinor,e.currency)+(o?" + 待确认税费":" + tax confirmed at checkout"):ge(r,e.currency)+(s?_e(s.interval,o?"zh-CN":"en",s.intervalCount??1):""),l=N(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(y=>y.productName).join(", ");return{label:l?`${l} · ${f}`:f,recurring:s}}async function M(e,t=a.checkoutNavigation!=="after_confirmation"){if(g)return;if(!I()){u=async()=>M(await i.read()),h.hidden=!1;return}let n=e.quote??i.quote;if(pt(n)&&(e.confirmedAt||e.merchantExecution))return Pe(n,e);if(d.textContent=vn(e.status,o),Yt(e)){let m=e.merchantExecution?.recordingStatus==="failed";d.textContent=m?o?"付款和商户处理已完成,但交易记录失败。请联系商户修复,勿重复购买。":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"付款和商户处理已完成,正在确认交易记录。请勿重复购买。":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",h.textContent=o?"查询记录":"Check recording",u=async()=>M(await i.read()),h.hidden=!1;return}if(e.problem&&x(e).type!=="native"){let m=e.problem;u=Te,h.textContent=o?"检查并恢复原操作":"Check and recover original purchase",we(new k(m.code,m.reason==="RESULT_UNKNOWN"?o?"付款结果尚未确定,请恢复原操作,暂勿重复购买。":"The payment result is unknown. Recover the original purchase before buying again.":m.phase==="fulfillment"?o?"付款已记录,商户权益处理需要核对。":"Payment was recorded. Access fulfillment needs attention.":m.code==="CAPABILITY_UNAVAILABLE"?o?"商户尚不支持本次购买所需的完整能力,请处理后恢复原操作。":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":m.code==="NOT_CONFIGURED"?o?"付款服务连接需要处理,请联系商户后恢复原操作。":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"原购买操作需要处理,请查询或恢复此操作。":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,m));return}if((e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"||e.merchantExecution?.type==="subscription_change"&&e.merchantExecution.status==="applied")&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(d.textContent=o?"付款已记录,正在等待商户完成处理。":"Payment was recorded. Waiting for merchant fulfillment."),Ge(e)&&x(e).type==="complete"){u=null,await Wt(e);return}if(!De(e)&&x(e).type!=="fulfillment"){if(i.canReselect===!1){d.textContent=o?"正在核对原购买结果":"Checking the original purchase result",h.textContent=o?"查询结果":"Check result",u=async()=>M(await i.read()),h.hidden=!1;return}e.status==="cancelled"?d.textContent=o?"这笔购买已取消,可以重新选择方案。":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(d.textContent=o?"这笔购买未能完成,可以重新选择方案。":"This purchase didn’t go through. Choose a plan to try again."),h.textContent=o?"重试":"Retry",u=null,P=null;return}if(!t&&x(e).type==="checkout"){if(Q){jt();return}if(de()){d.textContent="",et=!1,u=null,h.hidden=!0,H?.updateCapabilities?.(ae(c),be(c)),ve();return}let m=i.quote,A=m?.operationId===e.operationId?Kt(m).label:"";d.textContent=et?A?o?`${A} 尚未付款。再次选择该方案即可继续付款。`:`${A} is still unpaid. Choose it again to continue paying.`:o?"之前的购买尚未付款。再次选择该方案即可继续付款。":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",et=!1,u=null;return}await Qe(e);let r=Date.now(),s=r+6e5,f=2e3,l=x(e).type!=="checkout",y=()=>l&&Date.now()-r<15e3;Me=!0,G(a.onObservationChange,!0);try{for(;!g&&Date.now()<s;){if(await ze(y()?700:f,p,ne.signal),g)return;if(!I()){u=async()=>M(await i.read()),h.hidden=!1;return}let m=await i.read();if(x(m).type==="checkout"&&(l=!1),!t&&x(m).type==="checkout"){await M(m,!1);return}if(!m.problem&&De(m)&&await Qe(m),!De(m)||m.problem||Yt(m)){await M(m);return}y()||(f=Math.min(f*1.5,3e4))}}finally{Me=!1,G(a.onObservationChange,!1)}u=async()=>M(await i.read()),h.hidden=!1}async function vt(e=!1){let t=await i.read();if(g)return;if(!I()){u=()=>vt(e),h.hidden=!1;return}let n=i.quote;if(n&&At(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&(nt(t)?["prepared","quoted"].includes(t.status):t.status==="pending")&&(nt(t)||t.quoteFinalized===!1)&&!t.confirmedAt&&!t.checkoutUrl&&!("nativePurchase"in t&&t.nativePurchase)&&!t.merchantExecution&&!t.problem&&!i.pendingCancellation){if(a.purchaseConfirmation!=="paywall"){e?await Te():u=null;return}setTimeout(Xt,0,n);return}await M(t,e||void 0)}async function Jt(){await vt()}async function On(e){d.textContent=ht;let t=Date.now()+12e3;for(;!g&&Date.now()<t&&(await ze(1500,p,ne.signal),!(g||!I()));){let n;try{n=await i.read()}catch{break}if(n.problem?.reason!=="RESULT_UNKNOWN")return n}return e}async function Te(){if(i.quote&&!(Date.parse(i.quote.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");Bt();let e=i.quote;if(pt(e)){Se(e,"checking");let n;try{n=await i.confirm()}catch(r){if(!Gt(r))throw r;return Pe(e)}return Pe(e,n)}u=Te;let t=await i.confirm();if(!I()){u=Te,h.hidden=!1;return}if(t.problem?.reason==="RESULT_UNKNOWN"&&(t=await On(t)),t.problem){await M(t);return}if(De(t)){if(x(t).type==="checkout")await Qe(t);else if(t.execution&&t.execution.provider!=="merchant"||"nativePurchase"in t&&t.nativePurchase){if(!a.onPurchase)throw new k("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await a.onPurchase({operation:t,signal:ne.signal})}}u=async()=>M(await i.read()),await M(t,!0)}function Xt(e){if(g)return;ue?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());d.textContent=t?o?"此报价已过期。请先取消,再重新选择。":"This quote has expired. Cancel it, then choose again.":"";let n=p.createElement("div"),r=p.createElement("button"),s=p.createElement("button"),f=p.createElement("div"),l=p.createElement("p"),y=e.merchantTerms,m=o?"zh-CN":"en",A=y?.subscriptionTerms?.items??[],K=y?y.subscriptionTerms?.trial?.days:N(e)?void 0:e.lines.find(w=>w.trial)?.trial?.days,Z=N(e)?y?y.totalMinor:e.totalMinor:K===void 0?null:y?y.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(w=>w.trial)?0:null,Oe=(w,v)=>o?`${v} 天试用结束后 ${w}`:`Then ${w} after the ${v}-day trial`,{label:J,recurring:Ne}=Kt(e),It=N(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(w=>w.productName).join(", "),tn=Z===null?"":`${o?"今天应付":"Due today"} ${ge(Z,e.currency)}`;l.textContent=tn?[It,tn].filter(Boolean).join(" · "):J,r.textContent=N(e)?o?"确认变更":"Confirm change":o?"确认购买":"Confirm purchase",r.disabled=t,s.textContent=o?"取消":"Cancel",n.style.cssText=L.panel,l.style.cssText=L.summary,f.style.cssText=L.actions,r.style.cssText=L.primary,s.style.cssText=L.secondary,Tt(r),r.onclick=()=>{B(Te)};let nn=async()=>{let w=await i.cancel();g||(n.remove(),ue=null,await M(w))};s.onclick=()=>{u=nn,B(nn)};let W=p.createElement("div");if(W.style.cssText=L.terms,N(e)){for(let[v,S]of Object.entries(e.featureQuantities??{})){let V=i.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(Nn=>Nn.internalFeatureId===v),tt=p.createElement("p");tt.textContent=`${V?.name??v} · ${S} ${o?"份":"packs"}${V?` × ${V.terms.units}`:""}`,W.append(tt)}for(let[v,S]of[[o?"原订阅抵扣":"Unused subscription credit",e.creditMinor],[o?"新套餐费用":"New plan charge",e.debitMinor],[o?"优惠减免":"Offer savings",y?.discountMinor??e.discountMinor],[o?"税费":"Tax",y?y.taxMinor:e.taxMinor]]){let V=p.createElement("p");V.textContent=`${v}: ${S===null?o?"结账时确认":"Confirmed at checkout":ge(S,e.currency)}`,W.append(V)}let w=p.createElement("p");w.textContent=`${o?"生效时间":"Effective"}: ${e.effectiveAt}`,W.append(w)}if(y){for(let v of A){if(Z===null&&v===Ne)continue;let S=p.createElement("p"),V=ge(v.amountMinor,e.currency)+_e(v.interval,m,v.intervalCount);S.textContent=Z!==null&&K!==void 0?Oe(V,K):V,v.amountAfterOfferMinor!==void 0&&(S.textContent+=` · ${o?"优惠结束后":"After the offer"} ${ge(v.amountAfterOfferMinor,e.currency)}${_e(v.interval,m,v.intervalCount)}`),W.append(S)}let w=y.subscriptionTerms?.trial;if(w){let v=p.createElement("p");v.textContent=o?`试用 ${w.days} 天;${w.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${w.days}; ${w.cardRequired?"a payment method is required":"no payment method is required"}`,W.append(v)}for(let v of[...y.expectedEffects.map(S=>S.description),...y.requiredConsents.map(S=>S.summary)]){let S=p.createElement("p");S.textContent=v,W.append(S)}}else if(!N(e)){for(let w of e.lines){if(Z!==null||w!==Ne){let v=p.createElement("p"),S=`${ge(w.catalogAmountMinor,e.currency)}${_e(w.interval,m,w.intervalCount??1)}`;v.textContent=Z!==null&&w.trial?(e.lines.length>1?`${w.productName} · `:"")+Oe(S,w.trial.days):`${w.productName} · ${S}`,W.append(v)}for(let v of w.prepaid??[]){let S=p.createElement("p"),V=i.view?.capabilities.plans[w.productVersionId]?.prepaid?.find(tt=>tt.internalFeatureId===v.internal_feature_id);S.textContent=`${V?.name??v.internal_feature_id} · ${v.quantity} ${o?"份":"packs"} × ${v.terms.units}`,V&&(S.textContent+=_e(V.reset==="week"||V.reset==="month"||V.reset==="year"?V.reset:"one_time",m,V.resetCount)),W.append(S)}if(w.trial){let v=p.createElement("p");v.textContent=o?`试用 ${w.trial.days} 天;${w.trial.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${w.trial.days}; ${w.trial.cardRequired?"a payment method is required":"no payment method is required"}`,W.append(v)}}if(!e.charge){let w=p.createElement("p");w.textContent=o?"目录价格;最终金额以结账时税费和试用规则为准。":"Catalog price; the final charge depends on checkout taxes and trial terms.",W.append(w)}}for(let w of W.children)w.style.margin="0";f.append(r,s),n.append(l,...W.childElementCount?[W]:[],f),F.prepend(n),_?.responsive||n.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),ue=n,he&&je(!0),u=null}async function Fe(){if(!P)return;if(u=Fe,!Ee){let n=i.view,r=n?.document.buttons[P.actionId],s=n&&r?.type==="checkout"?Ie(r.product,P.selection,n.capabilities):null;if(!n||!s)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!xe){let l=await a.resolveSubscriptionChange?.({actionId:P.actionId,productVersionId:s,featureQuantities:Ue(n.document.screen,s,P.selection,n.capabilities)});if(g)return;l!==void 0&&(P.subscriptionChange=an.parse(l)),xe=!0}let f=Y?.offerId;if(Y&&!f){if(!a.claimCoupon)throw new k("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:l}=await a.claimCoupon(Y.id,P.requestId);if(g)return;if(!l||l.couponId!==Y.id||l.status!=="issued"||!(Date.parse(l.expiresAt)>Date.now()))throw P=null,Y=void 0,u=async()=>{Ve(await i.refresh()),u=null},new k("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");f=l.id}if(!Y&&!n.document.screen.actions.some(l=>l.id===P?.actionId&&typeof l.properties.couponBinding=="string")&&(f=await a.resolveOfferId?.({actionId:P.actionId,productVersionId:s,featureQuantities:Ue(n.document.screen,s,P.selection,n.capabilities)})),g)return;f!==void 0&&(P.offerId=f),Ee=!0}if(!I()){h.hidden=!1;return}let e;try{e=await i.preview(P)}catch(n){throw i.canReselect===!0&&(P=null,Ee=!1,xe=!1,Y=void 0,u=null),n}if(Y&&(N(e)?(()=>{let n=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return n?.couponId!==Y.id||n.grantId!==P.offerId})():e.discount?.couponId!==Y.id||e.discount.offerId!==P.offerId))throw new k("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(g)return;let t=e.merchantTerms;if(a.purchaseConfirmation!=="paywall"||a.confirmOnHostedCheckout&&I()&&!N(e)&&e.provider==="merchant"&&e.billingSubscriptionId===null&&t?.request.action==="purchase"&&t.request.mode==="subscription"&&t.subscriptionTerms?.trial===null&&t.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){if(!I()){h.hidden=!1;return}if(!(Date.parse(e.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");let n=fe?"":o?"正在打开收银台…":"Opening checkout…";d.textContent=n;try{await Te()}catch(r){g||we(r)}finally{d.textContent===n&&(d.textContent="")}return}Xt(e)}function ke(e="destroy",t=!1){if(g)return;g=!0;let n=ut;ut=void 0,G(n),a.signal?.removeEventListener("abort",oe),i.signal?.removeEventListener("abort",oe),U.finish("dismissed"),Dt?.(),yt(),ne.abort(),Nt?.disconnect(),H?.destroy(),i.destroy(),R.removeEventListener("cancel",en),O.remove(),D.remove(),t||Zt(),e==="dismiss"&&G(a.onDismiss)}function Zt(){if(_?.destroy(),ce){ce.release();return}R.open&&R.close(),R.remove(),T()}j=ke;async function qe(){if(!Ce||g||Ye||ie==="closing"||!ie&&!I())return;if(!E){ke("dismiss");return}let e=p.createElement("p");e.setAttribute("role","status"),e.textContent=o?"正在关闭…":"Closing…",me||(me=p.createElement("div"),me.style.cssText=F.style.cssText,F.replaceWith(me),pe.inert=!0),O.hidden=!1,me.replaceChildren(e,O),ie="closing",O.setAttribute("aria-disabled","true"),O.focus({preventScroll:!0});try{await E.dismiss()}catch(t){g||G(a.onError,t)}g||(ie="retry",e.textContent=o?"未能确认关闭,请重试。":"Could not confirm closure. Try again.",O.textContent=o?"重试关闭":"Retry closing",O.removeAttribute("aria-label"),O.removeAttribute("aria-disabled"))}O.onclick=()=>{qe()};function en(e){e.preventDefault(),qe()}R.addEventListener("cancel",en),le.onclick=()=>{B(C?Ct:Xe)},h.onclick=()=>{if(q){q.retry?.();return}u&&B(u)};function Pt(e){U.finish("error",e),ke()}function kt(){if(!(!Lt||Ce||g||Ye||_&&!I()))try{let e=t=>{a.focusAtReveal&&(T=St(p)),H?.setHidden?.(!1),dt?.(),_&&(R.open||R.showModal(),_.responsive&&R.focus({preventScroll:!0}),!t&&a.loading!=="host"&&fn(R,_.type,_.responsive)),t&&a.loading!=="host"&&typeof pe.animate=="function"&&!p.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&pe.animate([{opacity:.55},{opacity:1}],{duration:160,easing:"ease-out"}),Ce=!0};E?E.present(t=>U.present(n=>e(t??n))):U.present(e)}catch(e){Pt(e),we(e)}}try{if(Le.type==="inline"?(st(),dt=gn(D,$),$.append(D)):(R.setAttribute("aria-label",c.document.name),O.textContent="×",O.setAttribute("aria-label",o?"关闭":"Close"),pn(O,c.document.screen.theme),O.hidden=cn(c.document),(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&ce?.content?ce.content.append(O,D):R.replaceChildren(O,D),ce||$.append(R),_=dn(R,{...c.document.screen,presentation:Le},ct),_.latch(),_.responsive&&(D.style.display="flex",D.style.flexDirection="column",D.style.maxHeight="100%",pe.style.overflow="clip",pe.style.minHeight="0"),ce||(dt=wn(R))),at&&X){let n=at(X);if(typeof n=="function"&&(g?G(n):ut=n),g)throw new DOMException("Presentation cancelled","AbortError");st()}H=te(pe,{mode:"live",rendererUrl:"bundled",title:c.document.name,closeActions:Rn,onAuthoredClose(n){ie||g||(O.hidden=n)},hostPresentation:()=>_?.type??Le.type,reportContentHeight:_?.responsive,onResize:n=>{if(!_?.responsive)return;let r=Math.min(n,lt);pe.style.height=`${r}px`,_.setContentHeight(r+Ut())},onSelection(n){for(let[r,s]of Object.entries(n))typeof s=="number"&&typeof z[r]=="number"&&z[r]!==s&&Mt.add(r);z=n,ve()},onAction(n,r={},s,f){if(!Ce||g||ie)return;let l=i.view,y=l?.document.buttons[n];if(!y)return;if(q){y.type==="close"&&qe();return}if(y.type==="close"&&E&&a.resumeCheckout&&i.operation&&sn(x(i.operation))){qe();return}if(he)return;if(!I()){gt();return}if(y.type==="close"){B(async()=>{E?.closeAction?await E.closeAction(n):await a.onAction?.(n),ke(a.onAction?"action":"dismiss")});return}if(y.type==="action"){u=async()=>{if(y.action.type==="event"){if(!a.onEvent)throw new k("EVENT_HANDLER_REQUIRED","Provide the event handler");await a.onEvent(y.action.event)}else a.onOpenUrl?await a.onOpenUrl(y.action.url):p.defaultView?.location.assign(y.action.url);await a.onAction?.(n),u=null},B(u);return}if(de()&&Q){!ye&&Q.selection.actionId===n&&B(()=>Ze(!0),n);return}if(C){if(C.phase==="payment"&&l&&Ae(C.quote,l,n,y.product,r,f)){B(Ct,n);return}if(!mt())return}if(!Re()&&!mt()){de()&&l&&i.quote&&i.operation&&x(i.operation).type==="checkout"&&Ae(i.quote,l,n,y.product,r,f)?B(Xe,n):d.textContent=o?"当前只能继续原订单。":"Only your original checkout is available.";return}if(ue&&i.canReselect===!1){d.textContent=o?"请先确认或取消当前购买。":"Confirm or cancel the current purchase first.",_?.responsive||ue.scrollIntoView?.({block:"nearest"}),ue.querySelector("button")?.focus({preventScroll:!0});return}if(de()&&a.terminateCheckout&&l&&i.quote&&i.operation&&i.canReselect===!1&&x(i.operation).type==="checkout"){if(Ae(i.quote,l,n,y.product,r,f)){B(Xe,n);return}let A=Ie(y.product,r,l.capabilities),K;try{if(!A)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");K=Ue(l.document.screen,A,r,l.capabilities)}catch(Ne){we(Ne);return}let Z=i.operation.operationId,Oe={actionId:n,requestId:crypto.randomUUID(),selection:structuredClone(r)},J=wt(l,n,A,r,f);B(()=>Ft(Z,Oe,J,{actionId:n,productVersionId:A,selection:Oe.selection,featureQuantities:K}),n);return}if((i.quote||P)&&i.canReselect===!1){let A=!!l&&!!i.quote&&Ae(i.quote,l,n,y.product,r,f);et=!!i.quote&&!A,u=i.quote?()=>vt(A):Fe,B(u);return}let m=l&&Ie(y.product,r,l.capabilities);if(!l||!m){we(new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(a.onPurchaseIntent){u=null,B(async()=>{let A={actionId:n,productVersionId:m,selection:structuredClone(r),featureQuantities:Ue(l.document.screen,m,r,l.capabilities)};ft=!0,await a.onPurchaseIntent(A)});return}if(P&&P.actionId!==n){we(new k("COMMAND_PENDING","Finish the current purchase"));return}P||(Y=wt(l,n,m,r,f),P={requestId:crypto.randomUUID(),actionId:n,selection:structuredClone(r)},Ee=!1,xe=!1),B(Fe,n)},onEscape:()=>{qe()},onError:n=>{let r=new Error(n);!Ce&&!g&&Pt(r),we(r)},onRendered:n=>{n&&R.setAttribute("aria-label",n),Lt=!0,kt()}}),H.setHidden?.(!0),ct();let e=de()&&!!i.quote&&!!i.operation&&x(i.operation).type==="checkout";z=i.quote?In(c,i.quote)??rt(c,{}):rt(c,{}),H.update(c.document.screen,ot,{capabilities:ae(c),unavailableActions:be(c),serverInput:{bindings:[],answers:{}},...Object.keys(z).length?{selection:z}:{}}),Dt=i.subscribe?.(Ve),Ve(i.view??c),await U.wait(H.ready);let t=i.operation;(!e||pt(i.quote))&&(i.quote||t&&(t.confirmedAt||t.checkoutUrl||Ge(t)))&&(u=Jt,B(u))}catch(e){throw Pt(e),e}return{check:se,host:{get currentResolution(){return c},setPurchaseRecovery(e,t){q={message:e,retry:t},H?.updateCapabilities?.(ae(c),be(c)),ve(),qt()},get subscriptionUpgradeActive(){return C!==void 0},get observing(){return Me},get recovery(){return An()},async prepareFallback(){if(he||g||ie||ft)return{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null};je(!0);try{let e=await ln(i);return e.type==="native"&&ke(),e}finally{je(!1)}},setSuspended(e){Ye=e,D.hidden=e,e&&R.open?R.close():!e&&!Ce?kt():!e&&!g&&Ce&&Le.type!=="inline"&&!R.open&&R.showModal()},destroy:ke,retainPurchaseDialog(){if(!(g||!R.open||!R.isConnected))return ke("destroy",!0),{dialog:R,content:ce?.content,release:Zt}},refresh:async()=>{if(!I()){if(i.view)return i.view;throw new k("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await i.refresh();return Ve(e),kt(),e}}}}export{dr as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as $,b as N,c as J,d as q}from"./chunk-MB2U2GWJ.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-
|
|
2
|
-
/*! For license information please see chunk-
|
|
1
|
+
import{a as $,b as N,c as J,d as q}from"./chunk-MB2U2GWJ.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-K7ROZKFG.js";import{a as _}from"./chunk-DSPLGTQI.js";import{b as C,c as O,e as j}from"./chunk-VPT5MFDG.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
|
|
2
|
+
/*! For license information please see chunk-7G7QSSC2.js.LEGAL.txt */
|
|
@@ -1 +1 @@
|
|
|
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-VMEEMKO4.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"&&!["funnel_stopped","route_unavailable"].includes(o.reason);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
|
+
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};
|