@tinkerlandai/longplay-sdk 0.10.67 → 0.10.69
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/dist/chunk-2BSDXKQS.js +1 -0
- package/dist/chunk-5MOJUGMA.js +1 -0
- package/dist/{chunk-AY3SB6ZI.js → chunk-5U7LC2NL.js} +1 -1
- package/dist/{chunk-YTURNXJA.js → chunk-BGCCW5QX.js} +2 -2
- package/dist/{chunk-N3S35ZVH.js → chunk-F5ABUGHD.js} +1 -1
- package/dist/{chunk-VE2NUFUU.js → chunk-G3YIPDT6.js} +1 -1
- package/dist/{chunk-TDM3ZUZS.js → chunk-GBUGEL6M.js} +1 -1
- package/dist/chunk-JAH62B6J.js +1 -0
- package/dist/{chunk-SFTMGGY4.js → chunk-MT4OQFDI.js} +1 -1
- package/dist/{chunk-3454S2FL.js → chunk-ST7XO45I.js} +1 -1
- package/dist/{chunk-DFSBT7N6.js → chunk-TYJWRPJY.js} +1 -1
- package/dist/{chunk-BLH6AF6U.js → chunk-UFTKCFNI.js} +1 -1
- package/dist/{chunk-XAJEVHTU.js → chunk-UIR5CBCC.js} +1 -1
- package/dist/{content-AG3EPSZT.js → content-66BI72XB.js} +1 -1
- package/dist/{funnel-host-purchase-63Y6YLAW.js → funnel-host-purchase-YPAWZLXP.js} +1 -1
- package/dist/{funnel-host-recovery-paywall-IE5C2X7L.js → funnel-host-recovery-paywall-KHBGMNS5.js} +1 -1
- package/dist/{funnel-paywall-prerender-ZFSTTVBW.js → funnel-paywall-prerender-PNJXR4VC.js} +1 -1
- package/dist/{funnel-runtime-host-VDWINOKR.js → funnel-runtime-host-RWU52BJ7.js} +1 -1
- 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-MAJJ2AKD.js → paywall-BSY67NQL.js} +1 -1
- package/dist/{paywall-content-64XRKMNN.js → paywall-content-RAB5S6KB.js} +1 -1
- package/dist/{paywall-session-JFAJ3A7C.js → paywall-session-CRIGHMOQ.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-4XHSDZ4N.js +0 -1
- package/dist/chunk-P2OZG34H.js +0 -1
- package/dist/chunk-RDMNLOWQ.js +0 -1
- /package/dist/{chunk-YTURNXJA.js.LEGAL.txt → chunk-BGCCW5QX.js.LEGAL.txt} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.69
|
|
4
|
+
|
|
5
|
+
- A purchase client whose device kept only a Start that never reached Longplay (no Run, purchase or command) no longer reports `blocked` with `RESULT_UNKNOWN` on every `refresh()`. The lookup forgets that Start and returns `idle` with `start`, so a host that treats `blocked` as an unfinished purchase stops asking the Customer to check an earlier purchase that does not exist. Explicit `retry()` before a refresh still resumes the retained Start with its original input
|
|
6
|
+
|
|
7
|
+
## 0.10.68
|
|
8
|
+
|
|
9
|
+
- A Paywall mounted in another frame's document (such as a preview inside an iframe) starts again: since 0.10.66 its page-visibility listener passed this frame's AbortSignal to that document, which a frame may refuse. The listener is now removed when the Paywall ends
|
|
10
|
+
|
|
3
11
|
## 0.10.67
|
|
4
12
|
|
|
5
13
|
- An entry whose last click started a Run that ended without presenting anything (for example a Funnel that finds this Customer ineligible and sends them to the merchant's own flow) is remembered on the device: the next pre-render of that entry paints nothing first and the click waits for its Run, instead of showing a Paywall that the Run then replaces. That record has no age limit and gives way to the Paywall the next Run presents, which becomes the kept copy again
|
package/README.md
CHANGED
|
@@ -335,7 +335,7 @@ When the merchant's targeting is off, omit `start` and set `allowNewPurchase: fa
|
|
|
335
335
|
|
|
336
336
|
`merchant` permits merchant-provider quotes; `record_only` permits Stripe quotes executed by the merchant; `indiana` permits platform execution; `native` permits Apple/Google execution. The original and current policies are intersected. The Controller checks the original quote before confirmation, including Host automatic confirmation and log retry; a policy refusal sends no commercial command. Checkout URLs and external business destinations remain merchant policy. The existing Host owns Run observation and loading/ready/dismissal; one recovery observer handles Operation-only or post-termination work. `onDismiss` releases presentation ownership before merchant code runs, so immediate reopening does not wait on a merchant lock.
|
|
337
337
|
|
|
338
|
-
The matching Customer-session recovery protocol ([Indianapolis API reference](https://github.com/tinkerlandai/Indianapolis/blob/dev/docs/sdk-api-reference.md), FRC-001/002) uses the current original Customer's access token, including a new login session, without issuing another Run Token. For an unknown Start, `refresh()` only performs `recover_start` with `intent: "lookup"
|
|
338
|
+
The matching Customer-session recovery protocol ([Indianapolis API reference](https://github.com/tinkerlandai/Indianapolis/blob/dev/docs/sdk-api-reference.md), FRC-001/002) uses the current original Customer's access token, including a new login session, without issuing another Run Token. For an unknown Start, `refresh()` only performs `recover_start` with `intent: "lookup"`. A missing result for a Start that holds no Run, purchase or command forgets that Start: nothing of it can be recovered or charged, so the state returns to `idle` and the next `start()` begins with its own Start (a consumer still awaiting the forgotten Start's reply finds it superseded). A missing result for anything else remains blocked. Initial `start()` and explicit `retry()` use `intent: "start"` with the retained original ID and full input: Longplay accepts a Start it never saw and drives it to its first position in the same request, so the first screen arrives without a separate resume. An API that predates `start` refuses it with 400, and the SDK repeats the request with `intent: "resume"`. Known Runs use `recover_run`; exact retained commands use `settle_command`, and the same Controller continues through `run_command`. Operation-only recovery retains original references and unresolved commands, and reads `recover_purchase` for the existing SQL reselection decision. A false decision is preserved even when the Operation reports failure or cancellation; commercial completion does not mark recovery complete while an original command remains unsettled. A missing receipt never authorizes replacement. Managed recovery requires matching Indianapolis runtime and SQL functions. Offline simulated results do not establish deployment, native RLS, concurrent SQL locking or Sandbox acceptance.
|
|
339
339
|
|
|
340
340
|
#### Pre-render the first Paywall
|
|
341
341
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as n,r as t}from"./chunk-UIR5CBCC.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as He}from"./chunk-NEW77IDA.js";import{a as $}from"./chunk-YDPF2ZZW.js";import{D as K,F as Qe,c as Te,e as z,j as xe,u as Le,v as Me,x as Ge,z as ze}from"./chunk-UIR5CBCC.js";import{a as Ne,b as je,c as Ue}from"./chunk-T5SCW4IA.js";import{a as se}from"./chunk-LBYMDTGD.js";import{i as ue}from"./chunk-CQ5EQNQA.js";import{K as G}from"./chunk-3NV6NBQB.js";import{A as ae,B as ie,C as J,E as Fe}from"./chunk-WVTKVQLZ.js";import{x as ye}from"./chunk-QTXHF27F.js";import{b as Ve}from"./chunk-MT4OQFDI.js";import{a as l}from"./chunk-ZRU7WONE.js";import{h as oe}from"./chunk-TFPLIX5E.js";import{a as De}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-S7NHVERO.js";import{a as ge}from"./chunk-DSPLGTQI.js";var R=G.options,st=r.discriminatedUnion("operation",[R[1].omit({customerToken:!0}),R[2].omit({customerToken:!0}),R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0}),R[8].omit({customerToken:!0}),xe.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),yt=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:R[0].shape.requestId,funnelId:R[0].shape.funnelId,locale:R[0].shape.locale,parameters:R[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",[R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[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:st})]),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()},Be=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"})}),Ye=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"})}),Je=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"})}),Ke=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:R[0].shape.locale,parameters:R[0].shape.parameters}),purchase:Pe})]);var ut=G.options[0].refine(i=>!i.customer&&!i.customerData),ct=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),$e=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:ut,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Te.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ct).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:Le.nullable()})});function We(i){return Ge({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function Xe(i){let d=new URL(i.baseUrl??De).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){i.assertCurrent();try{let E=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(E.revision)||E.revision<0)throw f();let c=E.entry===null?null:$e.parse(E.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(k=>k.operationId===c.operationCommand?.operationId))throw f();return{revision:E.revision,entry:c}}catch(E){throw E instanceof l?E:f()}}async function W(E){for(let c=0;c<8;c++){let k=await S(),q=E(structuredClone(k.entry));if(JSON.stringify(q)===JSON.stringify(k.entry))return q;q&&$e.parse(q),i.assertCurrent();let j;try{j=await i.storage.write(k.revision,q)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=k.revision)throw f();return q}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:W,baseUrl:d}}var lt=5*6e4,dt=2e3;function pt(i,d){let f=i.purchases.find(S=>S.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 Qt(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:S,sessionId:W}=f,E=!1,c=null,k,q,j=null,F=!1,U,X,Z,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=Ve(d),te=He(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(E||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Xe({...d,customerId:S,assertCurrent:P,storage:d.storage??We({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),Ze,Re=()=>Ze??=import("./funnel-paywall-copies-A76T5V7B.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:S})),et={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},tt=d.session.subscribeIdentity(Se);function Se(){E||(E=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),tt(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function v(e){P();let t=JSON.stringify(e)!==JSON.stringify(b);b=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(E)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==q)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function Ce(e){return!e.run&&!O(e).length&&!e.journal.entry&&!e.operationCommand}function O(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=O(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=O(e).map(I=>{let C=g.get(I.operationId);return I.terminal&&!C?{type:I.terminal,operationId:I.operationId}:se({quote:C?.quote??null,operation:C??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!==S)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 nt(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=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)&&O(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),v(A(t,"run"))}function rt(){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=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!==S)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||!Fe(a))?{operationCommand:void 0}:{},purchases:O(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 ot(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 at(){let e=$(Ke,await Y({operation:"find_purchase"}));if(e.customerId!==S||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:S,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<lt))return t.job;let n={at:Date.now(),job:at().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=$(Je,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 Ee(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Ye,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=O(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"?Me(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!==S||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 Ee(e)),!O(e).length&&x(e))return v(A(e,"operation"));if(!O(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=O(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 v(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(q=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 ot(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:B(h)});throw h}let a=$(Be,u);if(a.customerId!==S||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"){if(!t&&Ce(e)){let h=e.start.requestId;if(!await w.update(C=>C&&C.start.requestId===h&&Ce(C)?null:C))return v({mode:"idle",status:"idle",actions:["start"],purchases:[]})}return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}})}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 Ee(e);let p=a.view;if(p.locale!==e.start.locale||!ze(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=Qe({...d,customerRun:{runId:a.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:rt(),onAcceptedResponse:nt},{scope:a.scope,run:p})}try{let s=o&&k?.controller===c?performance.now()-k.at:1/0;(s>=dt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(k=void 0,await c.get(),k={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),v(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!E&&!n?.(s)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.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 be();({entry:n}=await w.read())}return n?(q&&n.start.requestId!==q&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&q===n.start.requestId?fe(n,b.error):re(n,!1,!0,t)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function be(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Oe(){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 v(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),v(A(h,"run"))}let n=t.operationCommand?.operationId??b.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),v(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function it(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function _e(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?it(g.get(t)):null}async function qe(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(b)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return S},retained:qe,get paywallCopies(){return et},async findPurchase(){let e=await qe();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Ne(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([je(Q.request,"resolvePaywall"),import("./paywall-content-RAB5S6KB.js"),import("./check-response-754GDUOJ.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 Ue(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 _e()!==null},recoverUpgradePaywall(){let e=_e();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=O(n),s=o.filter(_=>!_.terminal),u=o.filter(_=>_.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(_=>e&&e.runId===n.run?.id&&_.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(_){if(!(_ instanceof l&&_.status===400&&_.code==="INVALID_REQUEST"))throw _;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(_=>d.executionPolicy.allowed.includes(_))},h);let I=ve.get(a.operationId),C=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof C!="object"||!C||!("provider"in C)||typeof C.provider!="string"||!("currency"in C)||typeof C.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:C.provider,currency:C.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let Ae=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:Ae,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return Ae},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let _=await L(n,!1,new Set([a.operationId]));return we||v(A(_,"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 be();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:S,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 q!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,b.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:Oe,retry:()=>F?Oe():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):v({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),v(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(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return v(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(pt(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(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 v(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{We as a,pt as b,Qt as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as fe,b as pe}from"./chunk-2ZMIM4MO.js";import{d as De,e as B}from"./chunk-CQ5EQNQA.js";import{a as Ve}from"./chunk-ZRU7WONE.js";import{a as C}from"./chunk-DSPLGTQI.js";var Te=5*6e4,je=15e3,Oe=new WeakMap;function Be(c){return Oe.get(c)}var A=c=>Array.isArray(c)?c.map(A):c&&typeof c=="object"?Object.fromEntries(Object.keys(c).sort().map(a=>[a,A(c[a])])):c,N=(c,a)=>JSON.stringify(A(c))===JSON.stringify(A(a)),X=c=>JSON.stringify(A([c.funnelId,c.locale??null,c.parameters??{}])),Je=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","prepareSubscriptionChange","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Xe(c,a){let we=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),m,x="",R=a.start instanceof Promise?void 0:we(a.start),$=e=>e?.parameters?.commerce,M=Promise.resolve(a.start).then(e=>e?we(e):void 0),z=a.maxAgeMs??Te,ye=new AbortController,w=AbortSignal.any([ye.signal,a.client.identitySignal,...a.signal?[a.signal]:[]]),Q=()=>d("released","aborted"),r="preparing",me,q,Y=()=>{},L=0,P=null,b=null,v=null,y=null,g,D,Z,ge=new Map,h=null,T=new Set,k=new Map,ee,he=new Promise(e=>ee=e),j,be=new Promise(e=>j=e),ne,He=new Promise(e=>ne=e);function J(e,n){r!==e&&(r=e,me=n,C(a.onState,e))}function Fe(){w.removeEventListener("abort",Q),U(),b?.destroy(),b=null,P?.remove(),P=null,v=null}function d(e,n){["adopted","unavailable","released","closed"].includes(r)||(J(e,n),Fe(),ee(!1),j(!1),ne(null))}function O(e){r!=="shown"&&d("unavailable",e)}let p,ae=!1,E=a.client.paywallCopies,te,Pe=new Promise(e=>te=e),re=!1;function ve(e){Pe.then(n=>{n&&E&&E.write(n,e).catch(()=>{})})}function Ie(e){Pe.then(async n=>{if(!n||!E)return;let t=await E.read(n);ae||t&&"presented"in t||await E.write(n,e)}).catch(()=>{})}let oe=e=>`error:${e?.code??e?.name??"unknown"}`,le=c.ownerDocument.defaultView,H=!0,Se=null,_=!1,Ne=e=>e.storageArea===le?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),Ce=e=>{Ne(e)&&G()},xe=a.client.subscribe(()=>G());function U(){H&&(H=!1,le?.removeEventListener("storage",Ce),xe(),Y())}let ie=()=>H&&(r==="ready"||r==="preparing");function se(e){(r==="ready"||r==="preparing")&&d("unavailable",e)}function G(){if(r==="ready"&&Date.now()-L>=z)return U();_=!0,Se??=(async()=>{for(;_&&m&&ie();){_=!1;try{await a.client.retained()==="pending"&&se("purchase_pending")}catch(e){w.aborted?d("released","aborted"):se(oe(e))}}})().finally(()=>{Se=null,_&&m&&ie()&&G()})}le?.addEventListener("storage",Ce),w.addEventListener("abort",Q,{once:!0});let Ae=a.client.findPurchase();Ae.catch(()=>{});let W;function K(e){let n=W?.paywallVersionId??a.paywallVersionId??p?.resolution.id??y?.id,t=JSON.stringify(A([n??null,e])),l=ge.get(t);return l||(l=a.client.readPaywall({paywallVersionId:n,...n?{}:{paywallId:W?.paywallId??a.paywallId},...e}),ge.set(t,l)),l}function V(e,n){let t=Object.values(e.capabilities.plans),l=Object.values(e.document.buttons).some(i=>i.type==="checkout");return l&&t.length===0?!1:n.intent==="subscription_change"&&l?t.some(i=>i.available):t.every(i=>i.available)}function ce(e,n){if(y&&!B(e,y))return d("unavailable","paywall_changed"),!1;y=e,Z=n;for(let t of k.keys())C(t,structuredClone(e));return!0}function Re(e,n){if(!(!y||!["preparing","ready","shown"].includes(r))){if(!B(e,y))return O("paywall_changed");if(!V(e,n.commerce))return O("plan_unavailable");ce(e,n)}}async function F(){let e=await He;if(!e)throw new Ve("PURCHASE_PENDING","The purchase did not start; open it again");return e}let Me={get view(){return h?h.view:y},get signal(){return h?.signal??a.client.identitySignal},get quote(){return h?.quote??null},get operation(){return h?.operation??null},webViewUrl:"bundled",get canReselect(){return h?.canReselect},get recovery(){return h?.recovery},get pendingCancellation(){return h?.pendingCancellation},subscribe(e){return k.set(e,h?.subscribe?.(e)??(()=>{})),()=>{k.get(e)?.(),k.delete(e)}},refresh:async()=>h?h.refresh():structuredClone(y),preview:async e=>(await F()).preview(e),confirm:async()=>(await F()).confirm(),cancel:async()=>(await F()).cancel(),read:async()=>(await F()).read(),destroy(){h?.destroy()}},u={options:{},handoff:{}},ke={loading:"host",focusAtReveal:!0,signal:a.client.identitySignal,start:async()=>Me,canInteract:()=>u.options.canInteract?u.options.canInteract():!["unavailable","released","closed"].includes(r),async beforeAction(){let e=r!=="adopted",n=y?.capabilities,t=await F();if(e&&!N(t.view?.capabilities,n))throw new De;await u.options.beforeAction?.()}};for(let e of Je)Object.defineProperty(ke,e,{enumerable:!0,get:()=>u.options[e]});function de(){r!=="preparing"||!v||!b||!p&&(!m||!N(Z?.commerce,$(m))||Z?.locale!==m.locale)||(J("ready"),ee(!0))}let Ee={present(e){if(u.handoff.present)return u.handoff.present(e);r==="preparing"&&(v=e,L=Date.now(),de())},async dismiss(){if(u.handoff.dismiss)return u.handoff.dismiss();d("closed");for(let e of[...T])C(e)},async closeAction(e){if(u.handoff.closeAction)return u.handoff.closeAction(e);u.options.onAction?await u.options.onAction(e):await Ee.dismiss()},quoteError(e){u.handoff.quoteError?u.handoff.quoteError(e):C(u.options.onError,e)}};async function qe(){if(a.paywallVersionId||a.paywallId)return{paywallVersionId:a.paywallVersionId,paywallId:a.paywallId};let e=a.configuration;if(!e)return d("unavailable","paywall_missing"),null;let n=await Promise.resolve(a.start).catch(()=>null);if(!n||r!=="preparing")return null;let t=()=>fe(e,{funnelId:n.funnelId,customerId:a.client.customerId,parameters:n.parameters??{}});if(q=await t(),r!=="preparing")return null;let l=q;if(l.type!=="paywall")return d("unavailable",pe(l)??"route"),null;let i=!1;return Y=e.subscribe(()=>{i||!ie()||(i=!0,t().then(s=>{!(s.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(s.reason))&&(s.type!=="paywall"||s.paywallVersionId!==l.paywallVersionId)&&se("route_changed")}).finally(()=>i=!1))}),H||Y(),{paywallVersionId:l.paywallVersionId}}(async()=>{try{let[{showPaywall:e},n]=await Promise.all([import("./paywall-MAJJ2AKD.js"),qe()]),t=a.commerce??$(R),l=a.locale??R?.locale,i=n&&t&&l?JSON.stringify(A([n.paywallVersionId??null,n.paywallId??null,{commerce:t,locale:l}])):null;if(te(i),w.throwIfAborted(),r!=="preparing"||!n)return;if(!t)return d("unavailable","commerce_missing");if(!l)return d("unavailable","locale_missing");W=n;let s={commerce:t,locale:l},f=i?await E?.read(i).catch(()=>null):null;if(re=!!f&&"presented"in f&&(!R||f.funnelId===R.funnelId),w.throwIfAborted(),r!=="preparing"||re)return;f&&!("presented"in f)&&(!R||f.funnelId===R.funnelId)&&V(f.resolution,f.context.commerce)&&(p=f),j(!!p);let o;if(p){let ue=p.context;s=ue,o=structuredClone(p.resolution),K(ue).then(Le=>Re(Le,ue),()=>{})}else o=await K(s);if(w.throwIfAborted(),r!=="preparing"||(!V(o,s.commerce)&&a.start instanceof Promise&&!g&&await M,!p&&g&&!N(s,g)&&(s=g,o=await K(s)),w.throwIfAborted(),r!=="preparing"))return;if(!V(o,s.commerce))return d("unavailable","plan_unavailable");if(!ce(o,s))return;P=c.ownerDocument.createElement("div"),c.append(P);let S=setTimeout(()=>r==="preparing"&&d("unavailable","timeout"),je);he.then(()=>clearTimeout(S));let I=await e(P,ke,Ee);if(!I.host||w.aborted||r!=="preparing"){I.host?.destroy(),d(w.aborted?"released":"unavailable","error");return}b=I.host,de()}catch(e){d(w.aborted?"released":"unavailable",oe(e))}finally{te(null),j(!1)}})(),M.then(async e=>{let n=s=>{Ie(null),O(s)};if(!e)return n("gated");let t=e,l=$(t),i=a.commerce??l;if(!N(l&&{...l,intent:void 0},i&&{...i,intent:void 0})||a.locale!==void 0&&t.locale!==a.locale)return n("start_mismatch");if(!l)return n("commerce_missing");g={commerce:l,locale:t.locale},D=t,p&&["preparing","ready","shown"].includes(r)&&(m=t,x=X(t));try{let s=await Ae,f=s==="pending"?"purchase_pending":s==="found"?"original_purchase":s==="blocked"?"purchase_blocked":void 0;if(f)return n(f);if(!["preparing","ready","shown"].includes(r))return;if(a.configuration&&(a.paywallId||a.paywallVersionId)){let o=await fe(a.configuration,{funnelId:t.funnelId,customerId:a.client.customerId,parameters:t.parameters??{}});w.throwIfAborted();let S=o.type==="unknown"||o.type==="unavailable"&&o.reason!=="funnel_stopped";if(o.type==="paywall"?p?o.paywallId!==p.resolution.paywallId:a.paywallVersionId?o.paywallVersionId!==a.paywallVersionId:o.paywallId!==a.paywallId:!S)return n(pe(o)??"route_changed")}if(H&&(_=!1,await a.client.retained()==="pending"))return n("purchase_pending");if(await be,re){m=t,x=X(t);return}if(W||a.paywallId||a.paywallVersionId||y){let o=await K(g);if(w.throwIfAborted(),Ie(V(o,g.commerce)?{savedAt:Date.now(),funnelId:t.funnelId,context:g,resolution:o}:null),p)Re(o,g);else{if(r!=="preparing")return;if(y){if(!V(o,g.commerce))return d("unavailable","plan_unavailable");if(!ce(o,g))return}}}}catch(s){return w.aborted?d("released","aborted"):O(oe(s))}["preparing","ready","shown"].includes(r)&&(m=t,x=X(t),de(),_&&G())},()=>O("gated"));let _e={get state(){return r},get reason(){return me},ready:he,local:be,get start(){return m},get prediction(){return q?structuredClone(q):void 0},matches:e=>m?X(e)===x:!!p&&e.funnelId===p.funnelId&&e.locale===p.context.locale,open(){if(r==="preparing")return"pending";if(r!=="ready"||!v)return!1;if(Date.now()-L>=z)return d("unavailable","expired"),!1;let e=v;return v=null,U(),J("shown"),e(),"shown"},destroy(){ye.abort()}};return Oe.set(_e,{onClose(e){return r==="closed"?(C(e),()=>{}):(T.add(e),()=>{T.delete(e)})},claim(){U()},remember(e){ae=!0;let n=structuredClone(e);M.then(()=>{!D||!g||ve({savedAt:Date.now(),funnelId:D.funnelId,context:g,resolution:n})},()=>{})},withhold(){ae=!0,M.then(()=>{D&&ve({savedAt:Date.now(),funnelId:D.funnelId,presented:"nothing"})},()=>{})},async adopt(e,n){let t=e.paywall?.resolution,l=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(r!=="shown"||!b||!y||!t||!l||e.source.id!==m?.funnelId||e.locale!==m?.locale||!N(e.parameters??{},m?.parameters??{})||!["running","waiting"].includes(e.status)||!B(t,y))return null;let i;try{i=await n.start()}catch{return null}if(r!=="shown"||!b)return i.destroy(),null;h=i,u.options=n.options,u.handoff=n.handoff;for(let[o]of k)k.set(o,i.subscribe?.(o)??(()=>{})),i.view&&C(o,structuredClone(i.view));w.removeEventListener("abort",Q),J("adopted"),ne(i),T.clear();let s=b,f=P;return b=null,P=null,v=null,new Proxy(s,{get(o,S){return S==="destroy"?()=>{o.destroy(),f?.remove()}:S==="retainPurchaseDialog"?()=>{let I=o.retainPurchaseDialog();if(I)return{dialog:I.dialog,release(){I.release(),f?.remove()}}}:Reflect.get(o,S,o)}})},retainPurchaseDialog(){if(r!=="shown")return;let e=b?.retainPurchaseDialog();if(!e)return;let n=P;return b=null,P=null,d("released"),{dialog:e.dialog,release(){e.release(),n?.remove()}}},get modal(){return y?.document.presentation.type!=="inline"},get revealable(){return r==="ready"&&!!v&&Date.now()-L<z},release(){d("released")}}),_e}export{Te as a,Be as b,Xe as c};
|
|
1
|
+
import{a as fe,b as pe}from"./chunk-2ZMIM4MO.js";import{d as De,e as B}from"./chunk-CQ5EQNQA.js";import{a as Ve}from"./chunk-ZRU7WONE.js";import{a as C}from"./chunk-DSPLGTQI.js";var Te=5*6e4,je=15e3,Oe=new WeakMap;function Be(c){return Oe.get(c)}var A=c=>Array.isArray(c)?c.map(A):c&&typeof c=="object"?Object.fromEntries(Object.keys(c).sort().map(a=>[a,A(c[a])])):c,N=(c,a)=>JSON.stringify(A(c))===JSON.stringify(A(a)),X=c=>JSON.stringify(A([c.funnelId,c.locale??null,c.parameters??{}])),Je=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","prepareSubscriptionChange","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Xe(c,a){let we=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),m,x="",R=a.start instanceof Promise?void 0:we(a.start),$=e=>e?.parameters?.commerce,M=Promise.resolve(a.start).then(e=>e?we(e):void 0),z=a.maxAgeMs??Te,ye=new AbortController,w=AbortSignal.any([ye.signal,a.client.identitySignal,...a.signal?[a.signal]:[]]),Q=()=>d("released","aborted"),r="preparing",me,q,Y=()=>{},L=0,P=null,b=null,v=null,y=null,g,D,Z,ge=new Map,h=null,T=new Set,k=new Map,ee,he=new Promise(e=>ee=e),j,be=new Promise(e=>j=e),ne,He=new Promise(e=>ne=e);function J(e,n){r!==e&&(r=e,me=n,C(a.onState,e))}function Fe(){w.removeEventListener("abort",Q),U(),b?.destroy(),b=null,P?.remove(),P=null,v=null}function d(e,n){["adopted","unavailable","released","closed"].includes(r)||(J(e,n),Fe(),ee(!1),j(!1),ne(null))}function O(e){r!=="shown"&&d("unavailable",e)}let p,ae=!1,E=a.client.paywallCopies,te,Pe=new Promise(e=>te=e),re=!1;function ve(e){Pe.then(n=>{n&&E&&E.write(n,e).catch(()=>{})})}function Ie(e){Pe.then(async n=>{if(!n||!E)return;let t=await E.read(n);ae||t&&"presented"in t||await E.write(n,e)}).catch(()=>{})}let oe=e=>`error:${e?.code??e?.name??"unknown"}`,le=c.ownerDocument.defaultView,H=!0,Se=null,_=!1,Ne=e=>e.storageArea===le?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),Ce=e=>{Ne(e)&&G()},xe=a.client.subscribe(()=>G());function U(){H&&(H=!1,le?.removeEventListener("storage",Ce),xe(),Y())}let ie=()=>H&&(r==="ready"||r==="preparing");function se(e){(r==="ready"||r==="preparing")&&d("unavailable",e)}function G(){if(r==="ready"&&Date.now()-L>=z)return U();_=!0,Se??=(async()=>{for(;_&&m&&ie();){_=!1;try{await a.client.retained()==="pending"&&se("purchase_pending")}catch(e){w.aborted?d("released","aborted"):se(oe(e))}}})().finally(()=>{Se=null,_&&m&&ie()&&G()})}le?.addEventListener("storage",Ce),w.addEventListener("abort",Q,{once:!0});let Ae=a.client.findPurchase();Ae.catch(()=>{});let W;function K(e){let n=W?.paywallVersionId??a.paywallVersionId??p?.resolution.id??y?.id,t=JSON.stringify(A([n??null,e])),l=ge.get(t);return l||(l=a.client.readPaywall({paywallVersionId:n,...n?{}:{paywallId:W?.paywallId??a.paywallId},...e}),ge.set(t,l)),l}function V(e,n){let t=Object.values(e.capabilities.plans),l=Object.values(e.document.buttons).some(i=>i.type==="checkout");return l&&t.length===0?!1:n.intent==="subscription_change"&&l?t.some(i=>i.available):t.every(i=>i.available)}function ce(e,n){if(y&&!B(e,y))return d("unavailable","paywall_changed"),!1;y=e,Z=n;for(let t of k.keys())C(t,structuredClone(e));return!0}function Re(e,n){if(!(!y||!["preparing","ready","shown"].includes(r))){if(!B(e,y))return O("paywall_changed");if(!V(e,n.commerce))return O("plan_unavailable");ce(e,n)}}async function F(){let e=await He;if(!e)throw new Ve("PURCHASE_PENDING","The purchase did not start; open it again");return e}let Me={get view(){return h?h.view:y},get signal(){return h?.signal??a.client.identitySignal},get quote(){return h?.quote??null},get operation(){return h?.operation??null},webViewUrl:"bundled",get canReselect(){return h?.canReselect},get recovery(){return h?.recovery},get pendingCancellation(){return h?.pendingCancellation},subscribe(e){return k.set(e,h?.subscribe?.(e)??(()=>{})),()=>{k.get(e)?.(),k.delete(e)}},refresh:async()=>h?h.refresh():structuredClone(y),preview:async e=>(await F()).preview(e),confirm:async()=>(await F()).confirm(),cancel:async()=>(await F()).cancel(),read:async()=>(await F()).read(),destroy(){h?.destroy()}},u={options:{},handoff:{}},ke={loading:"host",focusAtReveal:!0,signal:a.client.identitySignal,start:async()=>Me,canInteract:()=>u.options.canInteract?u.options.canInteract():!["unavailable","released","closed"].includes(r),async beforeAction(){let e=r!=="adopted",n=y?.capabilities,t=await F();if(e&&!N(t.view?.capabilities,n))throw new De;await u.options.beforeAction?.()}};for(let e of Je)Object.defineProperty(ke,e,{enumerable:!0,get:()=>u.options[e]});function de(){r!=="preparing"||!v||!b||!p&&(!m||!N(Z?.commerce,$(m))||Z?.locale!==m.locale)||(J("ready"),ee(!0))}let Ee={present(e){if(u.handoff.present)return u.handoff.present(e);r==="preparing"&&(v=e,L=Date.now(),de())},async dismiss(){if(u.handoff.dismiss)return u.handoff.dismiss();d("closed");for(let e of[...T])C(e)},async closeAction(e){if(u.handoff.closeAction)return u.handoff.closeAction(e);u.options.onAction?await u.options.onAction(e):await Ee.dismiss()},quoteError(e){u.handoff.quoteError?u.handoff.quoteError(e):C(u.options.onError,e)}};async function qe(){if(a.paywallVersionId||a.paywallId)return{paywallVersionId:a.paywallVersionId,paywallId:a.paywallId};let e=a.configuration;if(!e)return d("unavailable","paywall_missing"),null;let n=await Promise.resolve(a.start).catch(()=>null);if(!n||r!=="preparing")return null;let t=()=>fe(e,{funnelId:n.funnelId,customerId:a.client.customerId,parameters:n.parameters??{}});if(q=await t(),r!=="preparing")return null;let l=q;if(l.type!=="paywall")return d("unavailable",pe(l)??"route"),null;let i=!1;return Y=e.subscribe(()=>{i||!ie()||(i=!0,t().then(s=>{!(s.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(s.reason))&&(s.type!=="paywall"||s.paywallVersionId!==l.paywallVersionId)&&se("route_changed")}).finally(()=>i=!1))}),H||Y(),{paywallVersionId:l.paywallVersionId}}(async()=>{try{let[{showPaywall:e},n]=await Promise.all([import("./paywall-BSY67NQL.js"),qe()]),t=a.commerce??$(R),l=a.locale??R?.locale,i=n&&t&&l?JSON.stringify(A([n.paywallVersionId??null,n.paywallId??null,{commerce:t,locale:l}])):null;if(te(i),w.throwIfAborted(),r!=="preparing"||!n)return;if(!t)return d("unavailable","commerce_missing");if(!l)return d("unavailable","locale_missing");W=n;let s={commerce:t,locale:l},f=i?await E?.read(i).catch(()=>null):null;if(re=!!f&&"presented"in f&&(!R||f.funnelId===R.funnelId),w.throwIfAborted(),r!=="preparing"||re)return;f&&!("presented"in f)&&(!R||f.funnelId===R.funnelId)&&V(f.resolution,f.context.commerce)&&(p=f),j(!!p);let o;if(p){let ue=p.context;s=ue,o=structuredClone(p.resolution),K(ue).then(Le=>Re(Le,ue),()=>{})}else o=await K(s);if(w.throwIfAborted(),r!=="preparing"||(!V(o,s.commerce)&&a.start instanceof Promise&&!g&&await M,!p&&g&&!N(s,g)&&(s=g,o=await K(s)),w.throwIfAborted(),r!=="preparing"))return;if(!V(o,s.commerce))return d("unavailable","plan_unavailable");if(!ce(o,s))return;P=c.ownerDocument.createElement("div"),c.append(P);let S=setTimeout(()=>r==="preparing"&&d("unavailable","timeout"),je);he.then(()=>clearTimeout(S));let I=await e(P,ke,Ee);if(!I.host||w.aborted||r!=="preparing"){I.host?.destroy(),d(w.aborted?"released":"unavailable","error");return}b=I.host,de()}catch(e){d(w.aborted?"released":"unavailable",oe(e))}finally{te(null),j(!1)}})(),M.then(async e=>{let n=s=>{Ie(null),O(s)};if(!e)return n("gated");let t=e,l=$(t),i=a.commerce??l;if(!N(l&&{...l,intent:void 0},i&&{...i,intent:void 0})||a.locale!==void 0&&t.locale!==a.locale)return n("start_mismatch");if(!l)return n("commerce_missing");g={commerce:l,locale:t.locale},D=t,p&&["preparing","ready","shown"].includes(r)&&(m=t,x=X(t));try{let s=await Ae,f=s==="pending"?"purchase_pending":s==="found"?"original_purchase":s==="blocked"?"purchase_blocked":void 0;if(f)return n(f);if(!["preparing","ready","shown"].includes(r))return;if(a.configuration&&(a.paywallId||a.paywallVersionId)){let o=await fe(a.configuration,{funnelId:t.funnelId,customerId:a.client.customerId,parameters:t.parameters??{}});w.throwIfAborted();let S=o.type==="unknown"||o.type==="unavailable"&&o.reason!=="funnel_stopped";if(o.type==="paywall"?p?o.paywallId!==p.resolution.paywallId:a.paywallVersionId?o.paywallVersionId!==a.paywallVersionId:o.paywallId!==a.paywallId:!S)return n(pe(o)??"route_changed")}if(H&&(_=!1,await a.client.retained()==="pending"))return n("purchase_pending");if(await be,re){m=t,x=X(t);return}if(W||a.paywallId||a.paywallVersionId||y){let o=await K(g);if(w.throwIfAborted(),Ie(V(o,g.commerce)?{savedAt:Date.now(),funnelId:t.funnelId,context:g,resolution:o}:null),p)Re(o,g);else{if(r!=="preparing")return;if(y){if(!V(o,g.commerce))return d("unavailable","plan_unavailable");if(!ce(o,g))return}}}}catch(s){return w.aborted?d("released","aborted"):O(oe(s))}["preparing","ready","shown"].includes(r)&&(m=t,x=X(t),de(),_&&G())},()=>O("gated"));let _e={get state(){return r},get reason(){return me},ready:he,local:be,get start(){return m},get prediction(){return q?structuredClone(q):void 0},matches:e=>m?X(e)===x:!!p&&e.funnelId===p.funnelId&&e.locale===p.context.locale,open(){if(r==="preparing")return"pending";if(r!=="ready"||!v)return!1;if(Date.now()-L>=z)return d("unavailable","expired"),!1;let e=v;return v=null,U(),J("shown"),e(),"shown"},destroy(){ye.abort()}};return Oe.set(_e,{onClose(e){return r==="closed"?(C(e),()=>{}):(T.add(e),()=>{T.delete(e)})},claim(){U()},remember(e){ae=!0;let n=structuredClone(e);M.then(()=>{!D||!g||ve({savedAt:Date.now(),funnelId:D.funnelId,context:g,resolution:n})},()=>{})},withhold(){ae=!0,M.then(()=>{D&&ve({savedAt:Date.now(),funnelId:D.funnelId,presented:"nothing"})},()=>{})},async adopt(e,n){let t=e.paywall?.resolution,l=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(r!=="shown"||!b||!y||!t||!l||e.source.id!==m?.funnelId||e.locale!==m?.locale||!N(e.parameters??{},m?.parameters??{})||!["running","waiting"].includes(e.status)||!B(t,y))return null;let i;try{i=await n.start()}catch{return null}if(r!=="shown"||!b)return i.destroy(),null;h=i,u.options=n.options,u.handoff=n.handoff;for(let[o]of k)k.set(o,i.subscribe?.(o)??(()=>{})),i.view&&C(o,structuredClone(i.view));w.removeEventListener("abort",Q),J("adopted"),ne(i),T.clear();let s=b,f=P;return b=null,P=null,v=null,new Proxy(s,{get(o,S){return S==="destroy"?()=>{o.destroy(),f?.remove()}:S==="retainPurchaseDialog"?()=>{let I=o.retainPurchaseDialog();if(I)return{dialog:I.dialog,release(){I.release(),f?.remove()}}}:Reflect.get(o,S,o)}})},retainPurchaseDialog(){if(r!=="shown")return;let e=b?.retainPurchaseDialog();if(!e)return;let n=P;return b=null,P=null,d("released"),{dialog:e.dialog,release(){e.release(),n?.remove()}}},get modal(){return y?.document.presentation.type!=="inline"},get revealable(){return r==="ready"&&!!v&&Date.now()-L<z},release(){d("released")}}),_e}export{Te as a,Be as b,Xe as c};
|
|
@@ -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-G3YIPDT6.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-BGCCW5QX.js.LEGAL.txt */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as Gn}from"./chunk-AY3SB6ZI.js";import{a as gn}from"./chunk-VMYLTNDS.js";import{a as _n,b as $n,c as wn,d as yn,e as $e,f as Mn,h as xn,i as zn,j as Bn,k as Jn}from"./chunk-6GY2YT3U.js";import{a as Qn}from"./chunk-45PGU2HW.js";import{a as qn}from"./chunk-W32FI2A2.js";import{c as Hn,e as Ln,f as Nn,i as Un,j as He,k as tn,l as Vn,m as rn}from"./chunk-57ZXT7AS.js";import{b as Sn}from"./chunk-EQ64JD4L.js";import{a as mn,d as On}from"./chunk-LBYMDTGD.js";import{C as Dn}from"./chunk-EJSTRCBQ.js";import{a as te}from"./chunk-ZRU7WONE.js";import{a as Ce}from"./chunk-DSPLGTQI.js";function Wn(i){let b=new Set,N=new Set,n=null;async function p(a,f){let L=!1;for(;!i.stopped&&i.key===a&&i.client.pendingCommand?.requestId===f;){if(!i.client.settle)throw new te("COMMAND_PENDING","The original display acknowledgement is still pending");await i.client.settle(f),L=!0,i.client.pendingCommand?.requestId===f&&await new Promise(S=>setTimeout(S,1500))}i.stopped||i.key!==a||(L&&await i.client.get(),!(i.stopped||i.key!==a)&&b.add(a))}function E(a,f){n=f;let L=()=>{n===f&&(n=null),N.delete(a)};return f.then(L,S=>{L(),i.busy||i.fail(S)}),f}function X(a){if(i.reviewing||b.has(a)||N.has(a)||i.stopped)return;N.add(a);let f=async()=>{if(i.reviewing||i.stopped||i.key!==a||b.has(a)){N.delete(a);return}if(i.busy||i.client.pendingCommand){setTimeout(()=>{f()},250);return}let L=(async()=>{if(i.staleRead){if(await i.staleRead,i.stopped||i.key!==a)return;if(i.client.pendingCommand){setTimeout(()=>{f()},250);return}}let S=i.client.view,de=i.expected(),_=de.requestId;try{await i.client.submit({operation:"shown",...de})}catch(o){if(!(o instanceof te)||o.code!=="CONFLICT"||o.status!==409||i.client.pendingCommand)throw o;await i.client.get();let u=i.client.view;if(i.stopped||i.reviewing||i.key!==a||!u||!S||u.id!==S.id||u.source.versionId!==S.source.versionId||u.nodeId!==de.nodeId||u.visit!==de.visit||u.revision<=de.revision||u.stopped||!u.screen&&(!u.paywall||u.paywall.receiptId!==S.paywall?.receiptId)||!["running","waiting"].includes(u.status)||i.client.pendingCommand)throw o;let P=i.expected();_=P.requestId,await i.client.submit({operation:"shown",...P})}await p(a,_)})();E(a,L)};f()}function g(){if(n)return n;let a=i.client.pendingCommand;if(a?.operation!=="shown")return null;let f=i.key;return N.add(f),E(f,(async()=>{await i.client.retry(),await p(f,a.requestId)})())}return{report:X,settled:g,get inFlight(){return n}}}function jn(i){let b={},N=new Map;async function n(p){let E=i.client.view,X=E?.screen,g=X?.customerData.nodes[p.nodeId];if(i.stopped||i.busy||!E||!X||!g)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let o=i.document,u=o?Dn(o,p.nodeId):null,P=u?.type==="customer_data"?u.data.outputs?.[p.action]:void 0;P&&X.outputs.includes(P)?await i.perform(()=>i.client.submit({operation:"submit",...i.expected(),input:{type:"screen",output:P,answers:i.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await i.onIntent?.(p,E);return}let f=p.action.startsWith("sources_")?g.resources.find(o=>o.key===p.value):null;if(p.action.startsWith("sources_")&&!f)throw new te("INVALID_REQUEST","Choose a current resource");let L=`${E.visit}:${p.nodeId}:${f?.key??""}`,S=N.get(L)??[null],_=b[p.nodeId]??{page:1,after:null,filter:"all",...f?{resourceKey:f.key}:{}};if(p.action==="filter"){let o=p.value;if(!o||!(g.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(o))throw new te("INVALID_REQUEST","Unknown data filter");_={page:1,after:null,filter:o},S.splice(0,S.length,null)}else if(p.action==="next"||p.action==="sources_next"){let o=f?.sources.at(-1),u=f?o?{kind:"ledger",cursor:{at:o.detail[0],id:o.id,type:"source"}}:null:X.dataCursors[p.nodeId];if(!u||!f&&!g.hasNext)return;S[_.page]=u,_={..._,page:_.page+1,after:u}}else if(p.action==="previous"||p.action==="sources_previous"){if(_.page<=1)return;_={..._,page:_.page-1,after:S[_.page-2]??null}}N.set(L,S),b={...b,[p.nodeId]:_},await i.perform(()=>i.client.get({nodeId:E.nodeId,visit:E.visit,revision:E.revision,components:b}))}return{get queries(){return b},intent:n,reset(){b={},N.clear()}}}function Xn(i){let{doc:b,holder:N,reviewHolder:n,mountScreenPreview:p}=i,E=!1,X,g=0,a=null,f="",L,S=new Map,de=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function _(u){if(i.stopped||!i.client.review||E&&u===X&&L?.active)return;let P=!E||u!==X;E||(f=de(i.client.view),S.set(f,structuredClone(i.answers))),E=!0,X=u,N.hidden=!0,i.suspend(!0),n.hidden=!1;let c=++g;P&&(L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),L=tn(n,i.loadingOptions,"funnel",()=>{o()}));let k=P?L:void 0;try{if(k?.start(!1,i.client.view?.locale),c!==g||i.stopped)return;let U=i.client.review(u),j=await(k?.wait(U,He)??U);if(i.stopped||c!==g||!E)return;if(!j.review)throw new te("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,k||n.replaceChildren();let M=b.createElement("div"),ye=k?rn(M,n):()=>{};n.append(M);let O=j.run.locale.startsWith("zh"),q=i.chrome;M.style.cssText=q.history;let A=b.createElement("p");A.textContent=O?"只读回看":"Read-only history",A.style.cssText=q.historyTitle,M.append(A);let Y=b.createElement("p");Y.style.cssText=q.historyNote,Y.textContent=j.review.pages.length?O?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":O?"还没有可回看的页面。":"There are no earlier pages yet.",M.append(Y);let D=j.review.page?.receiptId,Ie=b.createElement("div");Ie.style.cssText=q.historyPages;for(let[F,x]of j.review.pages.entries()){let R=b.createElement("button");R.type="button",R.textContent=O?`第 ${F+1} 页`:`Page ${F+1}`;let J=D!==void 0&&x.receiptId===D;R.style.cssText=J?q.primary:q.secondary,J&&R.setAttribute("aria-current","page"),$e(R,()=>i.chrome.focus),R.onclick=()=>{_(x.receiptId)},Ie.append(R)}if(Ie.childElementCount&&M.append(Ie),j.review.page){let F=j.review.page,x=b.createElement("div");x.inert=!0,x.style.cssText=q.historyPage,M.append(x),a=p(x,{mode:"live",rendererUrl:i.client.webViewUrl,title:F.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{c===g&&!i.stopped&&k?.present(ye)},onError:J=>{if(c!==g||i.stopped)return;let Ae=new Error(J);k?.finish("error",Ae),a?.destroy(),a=null,M.remove(),i.fail(Ae)},onEscape:()=>{o()}});let R=a;if(R.update(F.document,j.run.locale,{serverInput:{bindings:F.inputs,answers:F.answers,values:F.values}}),await R.ready,i.stopped||c!==g||!E)return}let Le=O?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},ae=b.createElement("div");ae.style.cssText=q.historyRecords;for(let F of[...j.review.coupons.map((x,R)=>`${O?"优惠券":"Coupon"} ${R+1}: ${Le[x.status]}`),...j.review.purchases.map((x,R)=>`${O?"购买":"Purchase"} ${R+1}: ${Jn(x.status,O)}`)]){let x=b.createElement("p");x.textContent=F,x.style.margin="0",ae.append(x)}ae.childElementCount&&M.append(ae),j.review.page||k?.present(ye),i.client.view&&await i.enqueue(i.client.view)}catch(U){if(c!==g||i.stopped)return;k?.finish("error",U),a?.destroy(),a=null,n.replaceChildren(),i.fail(U)}}async function o(){if(!E||i.stopped||!i.client.review)return;let u=++g;L?.finish("dismissed");try{if(await i.client.review(),i.stopped||u!==g)return;E=!1,g++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,N.hidden=!1;let P=i.client.view;de(P)!==f?(S.set(f,structuredClone(i.answers)),i.resetScreen()):(S.delete(f),i.suspend(!1)),P&&await i.enqueue(P)}catch(P){if(u!==g||i.stopped)return;a?.destroy(),a=null,n.replaceChildren(),i.fail(P)}}return{get active(){return E},get receipt(){return X},open:_,exit:o,get drafts(){return new Map([...S].map(([u,P])=>[u,structuredClone(P)]))},stop(){E=!1,g++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,N.hidden=!1}}}var vn=5e3;async function tt(i,b,N){let n=b,p=n.prepared&&Gn(n.prepared),E=()=>{},X;function g(){n.prepared&&n.prepared.state!=="adopted"&&p?.release()}let a=()=>n.prepared?.state==="shown"&&!!p?.modal,f=n.client.identitySignal,L;try{L=await Promise.all([import("./screen-renderer-H3FBGJZB.js"),import("./paywall-MAJJ2AKD.js")]),n.signal?.throwIfAborted(),f?.throwIfAborted()}catch(e){throw g(),e}let[{mountScreenPreview:S},{showPaywall:de}]=L,_=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Qn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;_?.start();let o=i.ownerDocument,u=Un(o),P=!1,c=o.createElement("section"),k=o.createElement("div"),U=o.createElement("div"),j=o.createElement("div"),M=o.createElement("button");j.hidden=!0,M.type="button";let ye=o.createElement("p"),O=o.createElement("p"),q=o.createElement("button"),A=o.createElement("button"),Y=o.createElement("button"),D=o.createElement("dialog"),Ie,Le=!1;c.dataset.indianaFunnel="",c.dataset.longplayCloseOwner="sdk",c.setAttribute("aria-busy","false"),ye.setAttribute("role","status"),O.setAttribute("role","alert"),O.hidden=!0,q.type=A.type=Y.type="button",U.append(q,M,ye,O,Y,A),c.append(k,j,U),i.append(c);let ae=$n,F=wn(ae),x="",R=(o.documentElement.lang||"").startsWith("zh"),J,Ae="",Me;for(let e of[q,M,Y,A])$e(e,()=>F.focus);function hn(){let e=R?"关闭":"Close";A.parentElement===D?(A.textContent="×",A.setAttribute("aria-label",e),Nn(A,ae)):(A.textContent=e,A.removeAttribute("aria-label"),A.style.cssText=F.link+";margin-inline-start:auto")}function xe(e){let t=e?.screen?.content.document.theme??ae,r=JSON.stringify([t.primary,t.background,t.text,t.radius,t.font,A.parentElement===D]);if(r===x)return;x=r,ae=t;let v=A.parentElement===D;F=wn(ae,v),c.style.cssText=F.root+";min-width:0"+(v?";display:flex;flex-direction:column;min-height:100%":""),U.style.cssText=F.bar+(v?";margin-top:auto":""),U.hidden&&(U.style.display="none"),q.style.cssText=M.style.cssText=F.secondary,Y.style.cssText=F.primary,ye.style.cssText=F.status,O.style.cssText=F.alert,hn(),yn(q)}function be(){U.hidden=q.hidden&&M.hidden&&Y.hidden&&O.hidden&&!ye.textContent&&(A.hidden||A.parentElement!==U),U.style.display=U.hidden?"none":"flex",J?.responsive&&Me!==void 0&&J.setContentHeight(Me+U.getBoundingClientRect().height)}xe();let ue=null,h=null,ie=null,ge="",ne="",Pe=!1,ze="",on="",Be="",s=!1,Z=0,Je=!1,In="",sn=null,an=Promise.resolve(),Cn=!n.client.view,Ne,ln=!1,T=N,Ge=n.hostPaywallTarget,Fe,_e,Qe="",We,re=!1,Re=null,pe=!1,je=()=>n.client.pendingCommand?.operation==="close",oe=null,V=null,dn=qn({document:o,run:async()=>{(!h?.observing||n.client.pendingCommand)&&await cn()},delay:()=>{if(!se.pending&&!(s||!ie||!["running","waiting"].includes(ie.status)&&!n.client.pendingCommand)&&!(h?.observing&&!n.client.pendingCommand))return ie.pendingRequest||n.client.pendingCommand?1500:vn},hiddenDelay:()=>!s&&!se.pending&&n.client.pendingCommand?15e3:void 0}),z=null;function un(){return V&&n.client.hasDurableJournal===!0&&z?.acknowledged===!0&&z.operationId===V.operationId&&n.client.view?.id===z.runId&&n.client.view?.status==="closed"&&n.client.view.revision===z.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?V:null}function bn(e){let t=e.run.paywall;if(z&&e.settlement?.requestId===z.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===z.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===z.revision+1&&e.run.nodeId===z.nodeId&&e.run.visit===z.visit&&t?.receiptId===z.receiptId&&t.selectionGeneration===z.selectionGeneration&&(t.quote?.operationId??null)===z.operationId&&(t.operation?.operationId??t.quote?.operationId??null)===z.operationId){let r=z.operationId===null&&t.selectionGeneration===0&&!t.quote&&!t.operation&&!t.purchaseRequestId,v=mn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect});(r||t.canReselect===!0&&v.type==="native")&&(z.acknowledged=!0)}}let Ee=null,Ue=new Set,fe={},Te=!1,K=(e,t=null)=>{s||(e instanceof te&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&dn.destroy(),Ee=t,Te=!1,O.textContent=Mn(e,R),O.hidden=!1,Y.hidden=n.client.pendingCommand===null,be(),Ce(n.onError,e))},se=Sn({client:n.client,document:o,conceal(){s||(me(),T?.finish("dismissed"),c.hidden=!0,P||(P=!0,u()))},async receive(e){s||await le(n.client.view??e.run)},failed(e){if(!s){if(!se.pending){pe=!1;let t=n.client.view;t&&le(t).then(()=>K(e),K);return}Ke(),c.parentElement!==i&&i.append(c),c.hidden=!1,q.hidden=M.hidden=A.hidden=!0,ye.textContent="",xe(),K(e,n.client.pendingCommand?.requestId??null)}}}),Pn=()=>{s||(Ee=null,O.textContent=zn(R),O.hidden=!1,Y.hidden=!0,be())};function ke(){let e=n.client.view;if(!e)throw new te("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let w=Xn({client:n.client,doc:o,holder:k,reviewHolder:j,mountScreenPreview:S,loadingOptions:n,get chrome(){return F},get stopped(){return s},get answers(){return fe},suspend(e){h?.setSuspended(e)},resetScreen(){ge="",ne="",ze=""},enqueue:le,fail:K}),Ve=Wn({client:n.client,expected:ke,fail:K,get stopped(){return s},get reviewing(){return w.active},get key(){return ge},get busy(){return Z},get staleRead(){return sn}}),Xe=jn({client:n.client,expected:ke,perform:Se,onIntent:n.onCustomerDataIntent,get stopped(){return s},get busy(){return Z},get document(){return ue?.document},get answers(){return fe}}),Ye=e=>`${e.id}:${e.nodeId}:${e.visit}`,De=e=>e&&(e.screen||e.paywall)?Ye(e):"";function ve(){let e=n.client.view;q.disabled=!w.active&&(Z>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!De(e)||ne!==De(e)),q.hidden=!w.active&&!e?.canBack,yn(q);let t=!!h&&!w.active;A.hidden=t&&!T?.active||Le&&!w.active,M.hidden=!n.client.review||!w.active&&!e?.canBack;let r=e?.locale.startsWith("zh");ye.textContent=t?"":Z>0||e?.pendingRequest?r?"正在处理":"Processing":e?.instruction?.type==="wait"?r?"等待中":"Waiting":"",be()}async function Rn(e){if(!e)return;let t=n.client.view;await e;let r=n.client.view;if(!t||!r||r.id!==t.id||r.nodeId!==t.nodeId||r.visit!==t.visit||r.stopped||!["running","waiting"].includes(r.status))throw new te("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Se(e,t=!1,r){if(!((Z||pe||oe||V)&&!t||s||w.active&&!t)){Z++,c.setAttribute("aria-busy","true"),O.hidden=!0,Ee=null,Te=!1,ve();try{if(t||await Rn(Ve.inFlight),s)return;let v=await e();s||await le(n.client.view??v.run)}catch(v){r?.(v)&&n.client.pendingCommand===null?Pn():se.pending||K(v,n.client.pendingCommand?.requestId??null)}finally{Z=Math.max(0,Z-1),c.setAttribute("aria-busy",String(Z>0)),s||(Y.hidden=n.client.pendingCommand===null,ve())}}}function Oe(){dn.schedule()}async function cn(){if(!(s||Je||Z)&&!se.pending){if(w.active){await w.open(w.receipt);return}Je=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let t=n.client.view,r=Xe.queries,v=await n.client.get(t?.screen&&Object.keys(r).length?{nodeId:t.nodeId,visit:t.visit,revision:t.revision,components:r}:void 0);Te&&!s&&(Te=!1,O.hidden=!0,be()),!s&&r===Xe.queries&&await le(n.client.view??v.run)}catch(e){K(e),Te=!s}finally{Je=!1}}}function Ze(e,t,r){if(T?.active){let ee=T;return ee.setDismissHandler(()=>En(ee)),ee}let v=tn(i,n,"funnel",()=>En(v),_n);return T=v,v.start(e,t,r),v}function En(e){s||re||(re=!0,e.finish("dismissed"),me(),c.hidden=!0,n.client.view?he().finally(G):G())}function pn(){clearTimeout(We?.timeout),We=void 0}function me(e){Le=!1,pn(),Fe?.abort(),Fe=void 0,ue?.destroy(),ue=null,h?.destroy(),h=null,Ne=void 0,_e?.(),_e=void 0,D.open&&D.close();for(let t of Array.from(k.children))(!e||!t.contains(e))&&t.remove();k.style.cssText="",Me=void 0,ge="",ne="",Pe=!1,ze="",Be=""}function kn(){let e=o.defaultView;J?.responsive&&e&&ue?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ke(){J?.destroy(),J=void 0,Ae=""}function en(e){let t=e.screen?.presentation;if(!t||t.type==="inline"){D.open&&D.close(),Ke(),A.parentElement!==U&&U.append(A),c.parentElement!==i&&i.append(c);for(let ee of["flex","display","flex-direction","justify-content"])k.style.removeProperty(ee);xe(e),be();return}c.parentElement!==D&&(D.append(A,c),i.append(D)),k.style.flex="1 0 auto",k.style.display="flex",k.style.flexDirection="column",k.style.justifyContent="center",xe(e);let r=e.screen.content.document,v=JSON.stringify([t,x]);if(v!==Ae){Ke(),Ae=v;let ee={sm:420,md:640,lg:900},we="size"in t&&!t.backdrop?",0 0 0 100vmax #16142566":"";D.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${ae.background};color:${ae.text};`+(t.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ee[t.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${we};`+(t.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),J=Hn(D,{presentation:t,theme:r.theme,pages:r.pages},kn),J.latch()}be(),D.setAttribute("aria-label",(Ie?.screen===e.screen?.content.document.name?Ie?.label:void 0)??ue?.document?.name??e.screen?.content.document.name??"Funnel")}async function Yn(e){if(s||re)return;if(se.observe(),se.pending){ie=e;return}if(pe&&(je()||["running","waiting"].includes(e.status))||(ie=e,Ee&&n.client.pendingCommand?.requestId!==Ee&&(O.hidden=!0,Ee=null),R=e.locale.startsWith("zh"),M.textContent=R?"回看":"History",q.textContent=w.active?R?"返回当前":"Return to current":R?"返回":"Back",hn(),Y.textContent=R?"重试":"Retry",Y.hidden=n.client.pendingCommand===null,ve(),In!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(In=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ce(n.onState,structuredClone(e))),s||re))return;if((!e.pendingRequest||pe&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){G();return}if(e.stopped&&a()){G();return}if(e.stopped||n.client.configurationReady===!1){w.stop(),g(),me(),T?.finish("skipped"),c.hidden=!0,Oe();return}if(c.hidden=!1,w.active){Oe();return}if(e.status==="completed"&&h?.subscriptionUpgradeActive){Oe();return}let t=De(e),r=n.client.view;if(r&&r.revision>e.revision&&De(r)!==t)return;let v=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);t!==ge&&(ge&&T?.finish("dismissed"),me(),ge=t,fe={...e.answers},Xe.reset());let ee=Ye(e);if(Qe===ee){c.hidden=!0;return}if(v&&!t){c.hidden=!0;let I=n.prepared?.state==="shown"?null:Ze(!0,e.locale);!s&&!re&&We?.key!==ee&&(pn(),We={key:ee,timeout:setTimeout(()=>{let l=n.client.view;if(s||!I?.active&&n.prepared?.state!=="shown"||!l||Ye(l)!==ee)return;Qe=ee;let H=new Error("Funnel screen preparation timed out");I?.finish("error",H),g(),me(),K(H)},He)}),Oe();return}pn();let $=I=>{let l=n.client.view;return!s&&!re&&!Re&&!I.aborted&&n.client.configurationReady!==!1&&!!l&&!l.stopped&&!["closed","ineligible","failed"].includes(l.status)&&(De(l)===t||l.status==="completed"&&h?.subscriptionUpgradeActive===!0)},we=(I,l)=>{$(l)&&(Qe=t,T?.finish("error",I),me(),c.hidden=!0,K(I))};if(t||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&g(),en(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&T?.finish("skipped")),e.screen){ln=!0,Ge=void 0,g();let I=e.screen.content;if(!ue){let W=e.screen.presentation.type!=="inline",C=Ze(W,e.locale);if(s||re)return;let B=(Fe=new AbortController).signal;en(e),_e=W?Vn(D):rn(c,i),ue=S(k,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...I.document.actions.filter(y=>y.type==="event"&&y.close).map(y=>y.id)])),onAuthoredClose(y){$(B)&&(Le=y,ve())},rendererUrl:n.client.webViewUrl,title:I.document.name,...W?{hostPresentation:()=>J?.type??e.screen.presentation.type}:{},onResize:y=>{Me=y,J?.responsive&&J.setContentHeight(y+U.getBoundingClientRect().height)},onAction(y,d={},ce={}){if(w.active||!$(B)||ne!==t)return;fe={...fe,...ce};let fn=e.screen?.inputs??[],Tn=Object.fromEntries(fn.filter(({variable:qe})=>Object.hasOwn(fe,qe)).map(({variable:qe})=>[qe,fe[qe]]));if(Bn(fn,Tn).length){Pn();return}Se(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:y,answers:Tn,selection:d}}),!1,qe=>xn(qe,fn))},onAnswers:y=>{w.active||!$(B)||ne!==t||(fe={...fe,...y})},onCustomerDataIntent:y=>{w.active||!$(B)||ne!==t||Xe.intent(y).catch(K)},onEscape:()=>{!$(B)||ne!==t||w.active||oe||V||he()},onError:y=>{let d=new Error(y);ne===t?K(d):we(d,B)},onRendered:y=>{if(!(!$(B)||ne===t))try{C.present(d=>{_e?.(),_e=void 0,y&&(Ie={screen:I.document.name,label:y},D.setAttribute("aria-label",y)),W&&(D.showModal(),P=!1,J?.responsive&&D.focus({preventScroll:!0}),!d&&n.loading!=="host"&&Ln(D,J?.type??e.screen.presentation.type,J?.responsive)),ne=t,Pe=W,ve()}),$(B)&&Ve.report(t)}catch(d){we(d,B)}}}),kn()}let l={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:fe,values:e.screen.values}},H=JSON.stringify([I,e.locale,l.parameters,e.screen.inputs,e.screen.values]);if(H!==ze)ue.update(I.document,e.locale,l),ze=H,on=JSON.stringify(l.capabilities),Be=JSON.stringify(l.customerData);else{let W=JSON.stringify(l.capabilities);W!==on&&(ue.updateCapabilities(l.capabilities),on=W),JSON.stringify(l.customerData)!==Be&&(ue.updateCustomerData(l.customerData),Be=JSON.stringify(l.customerData))}let Q=ue;if(Q)try{await(T?.wait(Q.ready)??Q.ready)}catch(W){Fe&&we(W,Fe.signal)}}else if(e.paywall&&!h){ln=!0;let I=e.paywall.resolution,l="document"in I?I.document:null,H=p,Q=n.mountPaywallControls,W=null,C=(Fe=new AbortController).signal,B={loading:"host",signal:C,...Q&&{mountControls:d=>Q(d,e)},canInteract:()=>$(C)&&!w.active&&!oe&&!V,beforeAction:async()=>{Z++;try{await Rn(Ve.settled()),O.hidden=!0,Ee=null,Te=!1,be()}finally{Z=Math.max(0,Z-1)}},start:async()=>{let d=await gn(n.client),ce=X;return X=void 0,d.view&&ce?.(d.view),d},onObservationChange:Oe,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,beforeCheckoutReplacement:n.beforeCheckoutReplacement,purchaseConfirmation:n.purchaseConfirmation,confirmOnHostedCheckout:n.confirmOnHostedCheckout,resolveOfferId:n.resolveOfferId,prepareSubscriptionChange:n.prepareSubscriptionChange,resolveSubscriptionChange:n.resolveSubscriptionChange,claimCoupon:n.claimCoupon,onEvent:n.onEvent,onOpenUrl:d=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:d,openIn:"same_window"}):o.defaultView?.location.assign(d),onAction:async d=>{if(w.active)return;let ce=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:d,answers:{}}});await le(n.client.view??ce.run)},onError:d=>{ne===t?K(d):we(d,C)}},y={quoteError:d=>Ce(n.onError,d),present(d){$(C)&&(W?.present(ce=>{d(ce),ne=t,Pe=y.retainedDialog?.dialog.open??!!k.querySelector("dialog[open]"),Pe&&(P=!1),ve()}),$(C)&&Ve.report(t))},async closeAction(d){s||w.active||await se.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:d,answers:{}}})},async dismiss(){if(s||C.aborted||w.active||oe||V||!pe&&!$(C))return;pe=!0;let d=n.client.view;if(d?.status==="completed"&&h?.subscriptionUpgradeActive){Ue.add(`complete:${d.id}`),Ce(n.onComplete,structuredClone(d)),G();return}if((n.resumeCheckout||n.terminateCheckout)&&nt()){ie=n.client.view,G();return}await he()}};if(H&&Q)g();else if(H){let d=await H.adopt(e,{options:B,handoff:y,start:()=>gn(n.client)});d&&$(C)&&!s?(en(e),h=d,Ne={runId:e.id,receiptId:e.paywall.receiptId},T?.active&&T.present(()=>{}),ne=t,Pe=H.modal,Pe&&(P=!1),ve(),Ve.report(t),w.active&&h.setSuspended(!0)):(d?.destroy(),g(),X=ce=>p?.remember(ce))}if(s||re)return;if(!h){if(W=Ze(!0,e.locale,l),s||re)return;(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.loading==="host"&&Ge?.ownerDocument===o&&(y.hostPaywallTarget=Ge),Ge=void 0,en(e);let d=await de(k,B,y).catch(ce=>(we(ce,C),null));!$(C)&&!(pe&&!s&&!C.aborted)?d?.host?.destroy():d&&(h=d.host,h&&(Ne={runId:e.id,receiptId:e.paywall.receiptId}),h?.setSuspended(w.active))}}if(s||re)return;ve();let m=e.instruction;if(m&&(m.type==="open_url"||m.type==="event")&&!Ue.has(m.receiptId)){let I=o.createElement("button");I.type="button",I.style.cssText=F.primary,$e(I,()=>F.focus),k.style.cssText=F.stage,I.textContent=m.type==="open_url"?`${R?"前往":"Continue to"} ${new URL(m.url).host}`:R?"继续":"Continue",I.onclick=()=>{let l=ke(),H=m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="new_window"?Zn(m.url):null;Se(async()=>{let Q="success";if(m.type==="open_url")if(n.onOpenUrl)try{Q=await n.onOpenUrl({receiptId:m.receiptId,url:m.url,openIn:m.openIn})===!1?"failed":"opened"}catch(C){Ce(n.onError,C),Q="failed"}else Q=m.openIn==="new_window"&&!H?"failed":"opened";if(m.type==="event"){if(!n.onEvent)throw new te("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(m.event)}if(s||n.client.view?.nodeId!==l.nodeId||n.client.view.visit!==l.visit)throw new te("PRECONDITION_FAILED","The client action visit changed");let W=await n.client.submit({operation:"submit",...l,input:{type:"client_action",receiptId:m.receiptId,outcome:Q}});return Ue.add(m.receiptId),m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="same_window"&&o.defaultView?.location.assign(m.url),W})},T?.active?T.present(()=>k.replaceChildren(I)):k.replaceChildren(I)}!e.pendingRequest&&e.status==="completed"&&!Ue.has(`complete:${e.id}`)&&(Ue.add(`complete:${e.id}`),Ce(n.onComplete,structuredClone(e))),Oe()}function Zn(e){let t=o.defaultView?.open(e,"_blank")??null;return t&&(t.opener=null),t}function le(e){return ve(),an=an.catch(()=>{}).then(async()=>{try{await Yn(e)}catch(t){throw T?.active&&(Qe=Ye(e),T.finish("error",t),me(),c.hidden=!0),t}}),an}let Kn=n.client.subscribe(e=>{if(!Cn){if(e.stopped&&(Pe||a())&&!pe){ie=e,G();return}!pe&&(e.stopped||n.client.configurationReady===!1||ge&&ne!==ge&&(De(e)!==ge||["closed","ineligible","failed"].includes(e.status)))&&(me(),T?.finish("dismissed"),c.hidden=!0),le(e).catch(K)}}),et=n.client.subscribeError?.(e=>{se.pending||K(e)});function nt(){let e=n.client.view,t=e?.paywall;return!!t?.operation&&!!e&&["running","waiting"].includes(e.status)&&On(mn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect}))}function he(e){if(Re)return Re;if(s||!e&&(oe||V))return Promise.resolve();let t=!e&&je();return!t&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ie=n.client.view,G(),Promise.resolve()):(Re=Se(async()=>{let r=t?await n.client.retry():await(e?n.client.submit.bind(n.client):se.submit)({operation:"close",...e??ke()});return e&&bn(r),r},!0).then(()=>{let r=n.client.view;r?.status==="closed"&&!je()&&(ie=r,G())}).finally(()=>{Re=null}),Re)}function G(){An()}function An(e){_?.destroy(),!s&&(s=!0,se.destroy(),E(),!ln&&(ie?.status==="ineligible"||ie?.status==="completed")&&p?.withhold(),g(),n.signal?.removeEventListener("abort",G),f?.removeEventListener("abort",G),T?.finish("dismissed"),dn.destroy(),Kn(),et?.(),me(e),Ke(),w.stop(),D.remove(),!e||!c.contains(e)?c.remove():(U.remove(),j.remove()),!e&&!P&&u(),Ce(n.onDismiss,ie?structuredClone(ie):null))}q.onclick=()=>{if(!q.disabled){if(w.active){w.exit();return}Se(()=>n.client.submit({operation:"back",...ke()}))}},M.onclick=()=>{w.open()},A.onclick=()=>{T?.active?T.dismiss():oe||he()},Y.onclick=()=>{se.pending?se.retry().catch(()=>{}):je()?he():Se(()=>n.client.retry())},D.addEventListener("cancel",e=>{e.preventDefault(),T?.active?T.dismiss():oe||he()}),n.signal?.addEventListener("abort",G,{once:!0}),f?.addEventListener("abort",G,{once:!0});let nn=!1;p&&(E=p.onClose(()=>{s||re||(re=!0,T?.finish("dismissed"),me(),c.hidden=!0,n.client.view?he().finally(G):nn=!0)}));let Fn={destroy:G,refresh:cn,get recoveryPaywall(){if(h&&Ne)return{...Ne,view:h.currentResolution}},setPurchaseRecovery(e,t){return h?.setPurchaseRecovery(e,t),h!==null},retainPurchaseDialog(){let e=h?.retainPurchaseDialog();if(e)return h=null,An(e.dialog),{dialog:e.dialog,release(){e.release(),c.remove(),P||u()}}},get recovery(){let e=un();if(e)return e;if(!s&&!Z&&!pe&&!oe&&h){let t=h.recovery;if(t.type!=="native")return t}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(oe)return oe;let e=un();if(e)return Promise.resolve(e);let t=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,r=()=>({type:"recover",operationId:t,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let m=h?.recovery;return Promise.resolve(m&&m.type!=="native"&&m.type!=="cancel"?m:r())}let v=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(m=>m.operation==="close");if(s&&!(v||V&&n.client.view?.status==="closed")||Z||Je||Re||w.active||!h&&!V&&!v)return Promise.resolve(r());let ee=h,$=(async()=>{try{if(!V&&v){let l=await n.client.retry();return await le(n.client.view??l.run),r()}if(!V){let l=await ee.prepareFallback();if(l.type!=="native")return l;if(n.client.hasDurableJournal!==!0)return r();V=l}let m=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(m.length){let l=m.find(Q=>Q.operation==="close");if(!l||!z||l.requestId!==z.requestId)return r();let H=await n.client.retry();bn(H),await le(n.client.view??H.run)}else{let l=n.client.view,H=l?.paywall;if(!l||!H||H.selectionGeneration===void 0||(H.quote?.operationId??null)!==V.operationId||V.operationId!==null&&H.canReselect!==!0)return r();let Q=H.selectionGeneration,W=await n.client.get();await le(n.client.view??W.run);let C=n.client.view,B=C?.paywall;if(!C||!B||!["running","waiting"].includes(C.status)||C.stopped||C.id!==l.id||C.nodeId!==l.nodeId||C.visit!==l.visit||B.receiptId!==H.receiptId||B.selectionGeneration!==Q||(B.quote?.operationId??null)!==V.operationId||V.operationId!==null&&B.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return r();let y=ke();z={runId:C.id,operationId:V.operationId,revision:y.revision,requestId:y.requestId,nodeId:C.nodeId,visit:C.visit,receiptId:B.receiptId,selectionGeneration:Q,acknowledged:!1},await he(y)}let I=un();return I?(G(),I):r()}catch(m){return K(m),r()}})();oe=$;let we=()=>{oe===$&&(oe=null)};return $.then(we,we),$},review:w.open,exitReview:w.exit,get unappliedDrafts(){return w.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??vn)>=vn||e.instruction?.type==="evaluate_segment")&&(sn=cn().finally(()=>{sn=null})),await le(e);else{if(c.hidden=!0,s)throw new DOMException("Presentation cancelled","AbortError");let t=nn||n.prepared?.state==="shown"?null:Ze(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(s||re&&!nn)throw new DOMException("Presentation cancelled","AbortError");let r=n.client.get(),v=await(t?t.wait(r,He):it(r,He));if(Cn=!1,nn)return s||await he().finally(G),Fn;await le(n.client.view??v.run)}}catch(e){throw T?.finish("error",e),G(),e}return Fn}function it(i,b){let N;return Promise.race([i,new Promise((n,p)=>{N=setTimeout(()=>p(new Error("Presentation data timed out")),b)})]).finally(()=>clearTimeout(N))}function qt(i,b,N){return tt(i,b,N)}export{tt as a,qt as b};
|
|
1
|
+
import{b as Gn}from"./chunk-5U7LC2NL.js";import{a as gn}from"./chunk-VMYLTNDS.js";import{a as _n,b as $n,c as wn,d as yn,e as $e,f as Mn,h as xn,i as zn,j as Bn,k as Jn}from"./chunk-6GY2YT3U.js";import{a as Qn}from"./chunk-45PGU2HW.js";import{a as qn}from"./chunk-W32FI2A2.js";import{c as Hn,e as Ln,f as Nn,i as Un,j as He,k as tn,l as Vn,m as rn}from"./chunk-57ZXT7AS.js";import{b as Sn}from"./chunk-EQ64JD4L.js";import{a as mn,d as On}from"./chunk-LBYMDTGD.js";import{C as Dn}from"./chunk-EJSTRCBQ.js";import{a as te}from"./chunk-ZRU7WONE.js";import{a as Ce}from"./chunk-DSPLGTQI.js";function Wn(i){let b=new Set,N=new Set,n=null;async function p(a,f){let L=!1;for(;!i.stopped&&i.key===a&&i.client.pendingCommand?.requestId===f;){if(!i.client.settle)throw new te("COMMAND_PENDING","The original display acknowledgement is still pending");await i.client.settle(f),L=!0,i.client.pendingCommand?.requestId===f&&await new Promise(S=>setTimeout(S,1500))}i.stopped||i.key!==a||(L&&await i.client.get(),!(i.stopped||i.key!==a)&&b.add(a))}function E(a,f){n=f;let L=()=>{n===f&&(n=null),N.delete(a)};return f.then(L,S=>{L(),i.busy||i.fail(S)}),f}function X(a){if(i.reviewing||b.has(a)||N.has(a)||i.stopped)return;N.add(a);let f=async()=>{if(i.reviewing||i.stopped||i.key!==a||b.has(a)){N.delete(a);return}if(i.busy||i.client.pendingCommand){setTimeout(()=>{f()},250);return}let L=(async()=>{if(i.staleRead){if(await i.staleRead,i.stopped||i.key!==a)return;if(i.client.pendingCommand){setTimeout(()=>{f()},250);return}}let S=i.client.view,de=i.expected(),_=de.requestId;try{await i.client.submit({operation:"shown",...de})}catch(o){if(!(o instanceof te)||o.code!=="CONFLICT"||o.status!==409||i.client.pendingCommand)throw o;await i.client.get();let u=i.client.view;if(i.stopped||i.reviewing||i.key!==a||!u||!S||u.id!==S.id||u.source.versionId!==S.source.versionId||u.nodeId!==de.nodeId||u.visit!==de.visit||u.revision<=de.revision||u.stopped||!u.screen&&(!u.paywall||u.paywall.receiptId!==S.paywall?.receiptId)||!["running","waiting"].includes(u.status)||i.client.pendingCommand)throw o;let P=i.expected();_=P.requestId,await i.client.submit({operation:"shown",...P})}await p(a,_)})();E(a,L)};f()}function g(){if(n)return n;let a=i.client.pendingCommand;if(a?.operation!=="shown")return null;let f=i.key;return N.add(f),E(f,(async()=>{await i.client.retry(),await p(f,a.requestId)})())}return{report:X,settled:g,get inFlight(){return n}}}function jn(i){let b={},N=new Map;async function n(p){let E=i.client.view,X=E?.screen,g=X?.customerData.nodes[p.nodeId];if(i.stopped||i.busy||!E||!X||!g)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let o=i.document,u=o?Dn(o,p.nodeId):null,P=u?.type==="customer_data"?u.data.outputs?.[p.action]:void 0;P&&X.outputs.includes(P)?await i.perform(()=>i.client.submit({operation:"submit",...i.expected(),input:{type:"screen",output:P,answers:i.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await i.onIntent?.(p,E);return}let f=p.action.startsWith("sources_")?g.resources.find(o=>o.key===p.value):null;if(p.action.startsWith("sources_")&&!f)throw new te("INVALID_REQUEST","Choose a current resource");let L=`${E.visit}:${p.nodeId}:${f?.key??""}`,S=N.get(L)??[null],_=b[p.nodeId]??{page:1,after:null,filter:"all",...f?{resourceKey:f.key}:{}};if(p.action==="filter"){let o=p.value;if(!o||!(g.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(o))throw new te("INVALID_REQUEST","Unknown data filter");_={page:1,after:null,filter:o},S.splice(0,S.length,null)}else if(p.action==="next"||p.action==="sources_next"){let o=f?.sources.at(-1),u=f?o?{kind:"ledger",cursor:{at:o.detail[0],id:o.id,type:"source"}}:null:X.dataCursors[p.nodeId];if(!u||!f&&!g.hasNext)return;S[_.page]=u,_={..._,page:_.page+1,after:u}}else if(p.action==="previous"||p.action==="sources_previous"){if(_.page<=1)return;_={..._,page:_.page-1,after:S[_.page-2]??null}}N.set(L,S),b={...b,[p.nodeId]:_},await i.perform(()=>i.client.get({nodeId:E.nodeId,visit:E.visit,revision:E.revision,components:b}))}return{get queries(){return b},intent:n,reset(){b={},N.clear()}}}function Xn(i){let{doc:b,holder:N,reviewHolder:n,mountScreenPreview:p}=i,E=!1,X,g=0,a=null,f="",L,S=new Map,de=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function _(u){if(i.stopped||!i.client.review||E&&u===X&&L?.active)return;let P=!E||u!==X;E||(f=de(i.client.view),S.set(f,structuredClone(i.answers))),E=!0,X=u,N.hidden=!0,i.suspend(!0),n.hidden=!1;let c=++g;P&&(L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),L=tn(n,i.loadingOptions,"funnel",()=>{o()}));let k=P?L:void 0;try{if(k?.start(!1,i.client.view?.locale),c!==g||i.stopped)return;let U=i.client.review(u),j=await(k?.wait(U,He)??U);if(i.stopped||c!==g||!E)return;if(!j.review)throw new te("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,k||n.replaceChildren();let M=b.createElement("div"),ye=k?rn(M,n):()=>{};n.append(M);let O=j.run.locale.startsWith("zh"),q=i.chrome;M.style.cssText=q.history;let A=b.createElement("p");A.textContent=O?"只读回看":"Read-only history",A.style.cssText=q.historyTitle,M.append(A);let Y=b.createElement("p");Y.style.cssText=q.historyNote,Y.textContent=j.review.pages.length?O?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":O?"还没有可回看的页面。":"There are no earlier pages yet.",M.append(Y);let D=j.review.page?.receiptId,Ie=b.createElement("div");Ie.style.cssText=q.historyPages;for(let[F,x]of j.review.pages.entries()){let R=b.createElement("button");R.type="button",R.textContent=O?`第 ${F+1} 页`:`Page ${F+1}`;let J=D!==void 0&&x.receiptId===D;R.style.cssText=J?q.primary:q.secondary,J&&R.setAttribute("aria-current","page"),$e(R,()=>i.chrome.focus),R.onclick=()=>{_(x.receiptId)},Ie.append(R)}if(Ie.childElementCount&&M.append(Ie),j.review.page){let F=j.review.page,x=b.createElement("div");x.inert=!0,x.style.cssText=q.historyPage,M.append(x),a=p(x,{mode:"live",rendererUrl:i.client.webViewUrl,title:F.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{c===g&&!i.stopped&&k?.present(ye)},onError:J=>{if(c!==g||i.stopped)return;let Ae=new Error(J);k?.finish("error",Ae),a?.destroy(),a=null,M.remove(),i.fail(Ae)},onEscape:()=>{o()}});let R=a;if(R.update(F.document,j.run.locale,{serverInput:{bindings:F.inputs,answers:F.answers,values:F.values}}),await R.ready,i.stopped||c!==g||!E)return}let Le=O?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},ae=b.createElement("div");ae.style.cssText=q.historyRecords;for(let F of[...j.review.coupons.map((x,R)=>`${O?"优惠券":"Coupon"} ${R+1}: ${Le[x.status]}`),...j.review.purchases.map((x,R)=>`${O?"购买":"Purchase"} ${R+1}: ${Jn(x.status,O)}`)]){let x=b.createElement("p");x.textContent=F,x.style.margin="0",ae.append(x)}ae.childElementCount&&M.append(ae),j.review.page||k?.present(ye),i.client.view&&await i.enqueue(i.client.view)}catch(U){if(c!==g||i.stopped)return;k?.finish("error",U),a?.destroy(),a=null,n.replaceChildren(),i.fail(U)}}async function o(){if(!E||i.stopped||!i.client.review)return;let u=++g;L?.finish("dismissed");try{if(await i.client.review(),i.stopped||u!==g)return;E=!1,g++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,N.hidden=!1;let P=i.client.view;de(P)!==f?(S.set(f,structuredClone(i.answers)),i.resetScreen()):(S.delete(f),i.suspend(!1)),P&&await i.enqueue(P)}catch(P){if(u!==g||i.stopped)return;a?.destroy(),a=null,n.replaceChildren(),i.fail(P)}}return{get active(){return E},get receipt(){return X},open:_,exit:o,get drafts(){return new Map([...S].map(([u,P])=>[u,structuredClone(P)]))},stop(){E=!1,g++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,N.hidden=!1}}}var vn=5e3;async function tt(i,b,N){let n=b,p=n.prepared&&Gn(n.prepared),E=()=>{},X;function g(){n.prepared&&n.prepared.state!=="adopted"&&p?.release()}let a=()=>n.prepared?.state==="shown"&&!!p?.modal,f=n.client.identitySignal,L;try{L=await Promise.all([import("./screen-renderer-H3FBGJZB.js"),import("./paywall-BSY67NQL.js")]),n.signal?.throwIfAborted(),f?.throwIfAborted()}catch(e){throw g(),e}let[{mountScreenPreview:S},{showPaywall:de}]=L,_=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Qn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;_?.start();let o=i.ownerDocument,u=Un(o),P=!1,c=o.createElement("section"),k=o.createElement("div"),U=o.createElement("div"),j=o.createElement("div"),M=o.createElement("button");j.hidden=!0,M.type="button";let ye=o.createElement("p"),O=o.createElement("p"),q=o.createElement("button"),A=o.createElement("button"),Y=o.createElement("button"),D=o.createElement("dialog"),Ie,Le=!1;c.dataset.indianaFunnel="",c.dataset.longplayCloseOwner="sdk",c.setAttribute("aria-busy","false"),ye.setAttribute("role","status"),O.setAttribute("role","alert"),O.hidden=!0,q.type=A.type=Y.type="button",U.append(q,M,ye,O,Y,A),c.append(k,j,U),i.append(c);let ae=$n,F=wn(ae),x="",R=(o.documentElement.lang||"").startsWith("zh"),J,Ae="",Me;for(let e of[q,M,Y,A])$e(e,()=>F.focus);function hn(){let e=R?"关闭":"Close";A.parentElement===D?(A.textContent="×",A.setAttribute("aria-label",e),Nn(A,ae)):(A.textContent=e,A.removeAttribute("aria-label"),A.style.cssText=F.link+";margin-inline-start:auto")}function xe(e){let t=e?.screen?.content.document.theme??ae,r=JSON.stringify([t.primary,t.background,t.text,t.radius,t.font,A.parentElement===D]);if(r===x)return;x=r,ae=t;let v=A.parentElement===D;F=wn(ae,v),c.style.cssText=F.root+";min-width:0"+(v?";display:flex;flex-direction:column;min-height:100%":""),U.style.cssText=F.bar+(v?";margin-top:auto":""),U.hidden&&(U.style.display="none"),q.style.cssText=M.style.cssText=F.secondary,Y.style.cssText=F.primary,ye.style.cssText=F.status,O.style.cssText=F.alert,hn(),yn(q)}function be(){U.hidden=q.hidden&&M.hidden&&Y.hidden&&O.hidden&&!ye.textContent&&(A.hidden||A.parentElement!==U),U.style.display=U.hidden?"none":"flex",J?.responsive&&Me!==void 0&&J.setContentHeight(Me+U.getBoundingClientRect().height)}xe();let ue=null,h=null,ie=null,ge="",ne="",Pe=!1,ze="",on="",Be="",s=!1,Z=0,Je=!1,In="",sn=null,an=Promise.resolve(),Cn=!n.client.view,Ne,ln=!1,T=N,Ge=n.hostPaywallTarget,Fe,_e,Qe="",We,re=!1,Re=null,pe=!1,je=()=>n.client.pendingCommand?.operation==="close",oe=null,V=null,dn=qn({document:o,run:async()=>{(!h?.observing||n.client.pendingCommand)&&await cn()},delay:()=>{if(!se.pending&&!(s||!ie||!["running","waiting"].includes(ie.status)&&!n.client.pendingCommand)&&!(h?.observing&&!n.client.pendingCommand))return ie.pendingRequest||n.client.pendingCommand?1500:vn},hiddenDelay:()=>!s&&!se.pending&&n.client.pendingCommand?15e3:void 0}),z=null;function un(){return V&&n.client.hasDurableJournal===!0&&z?.acknowledged===!0&&z.operationId===V.operationId&&n.client.view?.id===z.runId&&n.client.view?.status==="closed"&&n.client.view.revision===z.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?V:null}function bn(e){let t=e.run.paywall;if(z&&e.settlement?.requestId===z.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===z.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===z.revision+1&&e.run.nodeId===z.nodeId&&e.run.visit===z.visit&&t?.receiptId===z.receiptId&&t.selectionGeneration===z.selectionGeneration&&(t.quote?.operationId??null)===z.operationId&&(t.operation?.operationId??t.quote?.operationId??null)===z.operationId){let r=z.operationId===null&&t.selectionGeneration===0&&!t.quote&&!t.operation&&!t.purchaseRequestId,v=mn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect});(r||t.canReselect===!0&&v.type==="native")&&(z.acknowledged=!0)}}let Ee=null,Ue=new Set,fe={},Te=!1,K=(e,t=null)=>{s||(e instanceof te&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&dn.destroy(),Ee=t,Te=!1,O.textContent=Mn(e,R),O.hidden=!1,Y.hidden=n.client.pendingCommand===null,be(),Ce(n.onError,e))},se=Sn({client:n.client,document:o,conceal(){s||(me(),T?.finish("dismissed"),c.hidden=!0,P||(P=!0,u()))},async receive(e){s||await le(n.client.view??e.run)},failed(e){if(!s){if(!se.pending){pe=!1;let t=n.client.view;t&&le(t).then(()=>K(e),K);return}Ke(),c.parentElement!==i&&i.append(c),c.hidden=!1,q.hidden=M.hidden=A.hidden=!0,ye.textContent="",xe(),K(e,n.client.pendingCommand?.requestId??null)}}}),Pn=()=>{s||(Ee=null,O.textContent=zn(R),O.hidden=!1,Y.hidden=!0,be())};function ke(){let e=n.client.view;if(!e)throw new te("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let w=Xn({client:n.client,doc:o,holder:k,reviewHolder:j,mountScreenPreview:S,loadingOptions:n,get chrome(){return F},get stopped(){return s},get answers(){return fe},suspend(e){h?.setSuspended(e)},resetScreen(){ge="",ne="",ze=""},enqueue:le,fail:K}),Ve=Wn({client:n.client,expected:ke,fail:K,get stopped(){return s},get reviewing(){return w.active},get key(){return ge},get busy(){return Z},get staleRead(){return sn}}),Xe=jn({client:n.client,expected:ke,perform:Se,onIntent:n.onCustomerDataIntent,get stopped(){return s},get busy(){return Z},get document(){return ue?.document},get answers(){return fe}}),Ye=e=>`${e.id}:${e.nodeId}:${e.visit}`,De=e=>e&&(e.screen||e.paywall)?Ye(e):"";function ve(){let e=n.client.view;q.disabled=!w.active&&(Z>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!De(e)||ne!==De(e)),q.hidden=!w.active&&!e?.canBack,yn(q);let t=!!h&&!w.active;A.hidden=t&&!T?.active||Le&&!w.active,M.hidden=!n.client.review||!w.active&&!e?.canBack;let r=e?.locale.startsWith("zh");ye.textContent=t?"":Z>0||e?.pendingRequest?r?"正在处理":"Processing":e?.instruction?.type==="wait"?r?"等待中":"Waiting":"",be()}async function Rn(e){if(!e)return;let t=n.client.view;await e;let r=n.client.view;if(!t||!r||r.id!==t.id||r.nodeId!==t.nodeId||r.visit!==t.visit||r.stopped||!["running","waiting"].includes(r.status))throw new te("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Se(e,t=!1,r){if(!((Z||pe||oe||V)&&!t||s||w.active&&!t)){Z++,c.setAttribute("aria-busy","true"),O.hidden=!0,Ee=null,Te=!1,ve();try{if(t||await Rn(Ve.inFlight),s)return;let v=await e();s||await le(n.client.view??v.run)}catch(v){r?.(v)&&n.client.pendingCommand===null?Pn():se.pending||K(v,n.client.pendingCommand?.requestId??null)}finally{Z=Math.max(0,Z-1),c.setAttribute("aria-busy",String(Z>0)),s||(Y.hidden=n.client.pendingCommand===null,ve())}}}function Oe(){dn.schedule()}async function cn(){if(!(s||Je||Z)&&!se.pending){if(w.active){await w.open(w.receipt);return}Je=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let t=n.client.view,r=Xe.queries,v=await n.client.get(t?.screen&&Object.keys(r).length?{nodeId:t.nodeId,visit:t.visit,revision:t.revision,components:r}:void 0);Te&&!s&&(Te=!1,O.hidden=!0,be()),!s&&r===Xe.queries&&await le(n.client.view??v.run)}catch(e){K(e),Te=!s}finally{Je=!1}}}function Ze(e,t,r){if(T?.active){let ee=T;return ee.setDismissHandler(()=>En(ee)),ee}let v=tn(i,n,"funnel",()=>En(v),_n);return T=v,v.start(e,t,r),v}function En(e){s||re||(re=!0,e.finish("dismissed"),me(),c.hidden=!0,n.client.view?he().finally(G):G())}function pn(){clearTimeout(We?.timeout),We=void 0}function me(e){Le=!1,pn(),Fe?.abort(),Fe=void 0,ue?.destroy(),ue=null,h?.destroy(),h=null,Ne=void 0,_e?.(),_e=void 0,D.open&&D.close();for(let t of Array.from(k.children))(!e||!t.contains(e))&&t.remove();k.style.cssText="",Me=void 0,ge="",ne="",Pe=!1,ze="",Be=""}function kn(){let e=o.defaultView;J?.responsive&&e&&ue?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ke(){J?.destroy(),J=void 0,Ae=""}function en(e){let t=e.screen?.presentation;if(!t||t.type==="inline"){D.open&&D.close(),Ke(),A.parentElement!==U&&U.append(A),c.parentElement!==i&&i.append(c);for(let ee of["flex","display","flex-direction","justify-content"])k.style.removeProperty(ee);xe(e),be();return}c.parentElement!==D&&(D.append(A,c),i.append(D)),k.style.flex="1 0 auto",k.style.display="flex",k.style.flexDirection="column",k.style.justifyContent="center",xe(e);let r=e.screen.content.document,v=JSON.stringify([t,x]);if(v!==Ae){Ke(),Ae=v;let ee={sm:420,md:640,lg:900},we="size"in t&&!t.backdrop?",0 0 0 100vmax #16142566":"";D.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${ae.background};color:${ae.text};`+(t.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ee[t.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${we};`+(t.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),J=Hn(D,{presentation:t,theme:r.theme,pages:r.pages},kn),J.latch()}be(),D.setAttribute("aria-label",(Ie?.screen===e.screen?.content.document.name?Ie?.label:void 0)??ue?.document?.name??e.screen?.content.document.name??"Funnel")}async function Yn(e){if(s||re)return;if(se.observe(),se.pending){ie=e;return}if(pe&&(je()||["running","waiting"].includes(e.status))||(ie=e,Ee&&n.client.pendingCommand?.requestId!==Ee&&(O.hidden=!0,Ee=null),R=e.locale.startsWith("zh"),M.textContent=R?"回看":"History",q.textContent=w.active?R?"返回当前":"Return to current":R?"返回":"Back",hn(),Y.textContent=R?"重试":"Retry",Y.hidden=n.client.pendingCommand===null,ve(),In!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(In=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ce(n.onState,structuredClone(e))),s||re))return;if((!e.pendingRequest||pe&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){G();return}if(e.stopped&&a()){G();return}if(e.stopped||n.client.configurationReady===!1){w.stop(),g(),me(),T?.finish("skipped"),c.hidden=!0,Oe();return}if(c.hidden=!1,w.active){Oe();return}if(e.status==="completed"&&h?.subscriptionUpgradeActive){Oe();return}let t=De(e),r=n.client.view;if(r&&r.revision>e.revision&&De(r)!==t)return;let v=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);t!==ge&&(ge&&T?.finish("dismissed"),me(),ge=t,fe={...e.answers},Xe.reset());let ee=Ye(e);if(Qe===ee){c.hidden=!0;return}if(v&&!t){c.hidden=!0;let I=n.prepared?.state==="shown"?null:Ze(!0,e.locale);!s&&!re&&We?.key!==ee&&(pn(),We={key:ee,timeout:setTimeout(()=>{let l=n.client.view;if(s||!I?.active&&n.prepared?.state!=="shown"||!l||Ye(l)!==ee)return;Qe=ee;let H=new Error("Funnel screen preparation timed out");I?.finish("error",H),g(),me(),K(H)},He)}),Oe();return}pn();let $=I=>{let l=n.client.view;return!s&&!re&&!Re&&!I.aborted&&n.client.configurationReady!==!1&&!!l&&!l.stopped&&!["closed","ineligible","failed"].includes(l.status)&&(De(l)===t||l.status==="completed"&&h?.subscriptionUpgradeActive===!0)},we=(I,l)=>{$(l)&&(Qe=t,T?.finish("error",I),me(),c.hidden=!0,K(I))};if(t||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&g(),en(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&T?.finish("skipped")),e.screen){ln=!0,Ge=void 0,g();let I=e.screen.content;if(!ue){let W=e.screen.presentation.type!=="inline",C=Ze(W,e.locale);if(s||re)return;let B=(Fe=new AbortController).signal;en(e),_e=W?Vn(D):rn(c,i),ue=S(k,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...I.document.actions.filter(y=>y.type==="event"&&y.close).map(y=>y.id)])),onAuthoredClose(y){$(B)&&(Le=y,ve())},rendererUrl:n.client.webViewUrl,title:I.document.name,...W?{hostPresentation:()=>J?.type??e.screen.presentation.type}:{},onResize:y=>{Me=y,J?.responsive&&J.setContentHeight(y+U.getBoundingClientRect().height)},onAction(y,d={},ce={}){if(w.active||!$(B)||ne!==t)return;fe={...fe,...ce};let fn=e.screen?.inputs??[],Tn=Object.fromEntries(fn.filter(({variable:qe})=>Object.hasOwn(fe,qe)).map(({variable:qe})=>[qe,fe[qe]]));if(Bn(fn,Tn).length){Pn();return}Se(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:y,answers:Tn,selection:d}}),!1,qe=>xn(qe,fn))},onAnswers:y=>{w.active||!$(B)||ne!==t||(fe={...fe,...y})},onCustomerDataIntent:y=>{w.active||!$(B)||ne!==t||Xe.intent(y).catch(K)},onEscape:()=>{!$(B)||ne!==t||w.active||oe||V||he()},onError:y=>{let d=new Error(y);ne===t?K(d):we(d,B)},onRendered:y=>{if(!(!$(B)||ne===t))try{C.present(d=>{_e?.(),_e=void 0,y&&(Ie={screen:I.document.name,label:y},D.setAttribute("aria-label",y)),W&&(D.showModal(),P=!1,J?.responsive&&D.focus({preventScroll:!0}),!d&&n.loading!=="host"&&Ln(D,J?.type??e.screen.presentation.type,J?.responsive)),ne=t,Pe=W,ve()}),$(B)&&Ve.report(t)}catch(d){we(d,B)}}}),kn()}let l={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:fe,values:e.screen.values}},H=JSON.stringify([I,e.locale,l.parameters,e.screen.inputs,e.screen.values]);if(H!==ze)ue.update(I.document,e.locale,l),ze=H,on=JSON.stringify(l.capabilities),Be=JSON.stringify(l.customerData);else{let W=JSON.stringify(l.capabilities);W!==on&&(ue.updateCapabilities(l.capabilities),on=W),JSON.stringify(l.customerData)!==Be&&(ue.updateCustomerData(l.customerData),Be=JSON.stringify(l.customerData))}let Q=ue;if(Q)try{await(T?.wait(Q.ready)??Q.ready)}catch(W){Fe&&we(W,Fe.signal)}}else if(e.paywall&&!h){ln=!0;let I=e.paywall.resolution,l="document"in I?I.document:null,H=p,Q=n.mountPaywallControls,W=null,C=(Fe=new AbortController).signal,B={loading:"host",signal:C,...Q&&{mountControls:d=>Q(d,e)},canInteract:()=>$(C)&&!w.active&&!oe&&!V,beforeAction:async()=>{Z++;try{await Rn(Ve.settled()),O.hidden=!0,Ee=null,Te=!1,be()}finally{Z=Math.max(0,Z-1)}},start:async()=>{let d=await gn(n.client),ce=X;return X=void 0,d.view&&ce?.(d.view),d},onObservationChange:Oe,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,beforeCheckoutReplacement:n.beforeCheckoutReplacement,purchaseConfirmation:n.purchaseConfirmation,confirmOnHostedCheckout:n.confirmOnHostedCheckout,resolveOfferId:n.resolveOfferId,prepareSubscriptionChange:n.prepareSubscriptionChange,resolveSubscriptionChange:n.resolveSubscriptionChange,claimCoupon:n.claimCoupon,onEvent:n.onEvent,onOpenUrl:d=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:d,openIn:"same_window"}):o.defaultView?.location.assign(d),onAction:async d=>{if(w.active)return;let ce=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:d,answers:{}}});await le(n.client.view??ce.run)},onError:d=>{ne===t?K(d):we(d,C)}},y={quoteError:d=>Ce(n.onError,d),present(d){$(C)&&(W?.present(ce=>{d(ce),ne=t,Pe=y.retainedDialog?.dialog.open??!!k.querySelector("dialog[open]"),Pe&&(P=!1),ve()}),$(C)&&Ve.report(t))},async closeAction(d){s||w.active||await se.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:d,answers:{}}})},async dismiss(){if(s||C.aborted||w.active||oe||V||!pe&&!$(C))return;pe=!0;let d=n.client.view;if(d?.status==="completed"&&h?.subscriptionUpgradeActive){Ue.add(`complete:${d.id}`),Ce(n.onComplete,structuredClone(d)),G();return}if((n.resumeCheckout||n.terminateCheckout)&&nt()){ie=n.client.view,G();return}await he()}};if(H&&Q)g();else if(H){let d=await H.adopt(e,{options:B,handoff:y,start:()=>gn(n.client)});d&&$(C)&&!s?(en(e),h=d,Ne={runId:e.id,receiptId:e.paywall.receiptId},T?.active&&T.present(()=>{}),ne=t,Pe=H.modal,Pe&&(P=!1),ve(),Ve.report(t),w.active&&h.setSuspended(!0)):(d?.destroy(),g(),X=ce=>p?.remember(ce))}if(s||re)return;if(!h){if(W=Ze(!0,e.locale,l),s||re)return;(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.loading==="host"&&Ge?.ownerDocument===o&&(y.hostPaywallTarget=Ge),Ge=void 0,en(e);let d=await de(k,B,y).catch(ce=>(we(ce,C),null));!$(C)&&!(pe&&!s&&!C.aborted)?d?.host?.destroy():d&&(h=d.host,h&&(Ne={runId:e.id,receiptId:e.paywall.receiptId}),h?.setSuspended(w.active))}}if(s||re)return;ve();let m=e.instruction;if(m&&(m.type==="open_url"||m.type==="event")&&!Ue.has(m.receiptId)){let I=o.createElement("button");I.type="button",I.style.cssText=F.primary,$e(I,()=>F.focus),k.style.cssText=F.stage,I.textContent=m.type==="open_url"?`${R?"前往":"Continue to"} ${new URL(m.url).host}`:R?"继续":"Continue",I.onclick=()=>{let l=ke(),H=m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="new_window"?Zn(m.url):null;Se(async()=>{let Q="success";if(m.type==="open_url")if(n.onOpenUrl)try{Q=await n.onOpenUrl({receiptId:m.receiptId,url:m.url,openIn:m.openIn})===!1?"failed":"opened"}catch(C){Ce(n.onError,C),Q="failed"}else Q=m.openIn==="new_window"&&!H?"failed":"opened";if(m.type==="event"){if(!n.onEvent)throw new te("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(m.event)}if(s||n.client.view?.nodeId!==l.nodeId||n.client.view.visit!==l.visit)throw new te("PRECONDITION_FAILED","The client action visit changed");let W=await n.client.submit({operation:"submit",...l,input:{type:"client_action",receiptId:m.receiptId,outcome:Q}});return Ue.add(m.receiptId),m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="same_window"&&o.defaultView?.location.assign(m.url),W})},T?.active?T.present(()=>k.replaceChildren(I)):k.replaceChildren(I)}!e.pendingRequest&&e.status==="completed"&&!Ue.has(`complete:${e.id}`)&&(Ue.add(`complete:${e.id}`),Ce(n.onComplete,structuredClone(e))),Oe()}function Zn(e){let t=o.defaultView?.open(e,"_blank")??null;return t&&(t.opener=null),t}function le(e){return ve(),an=an.catch(()=>{}).then(async()=>{try{await Yn(e)}catch(t){throw T?.active&&(Qe=Ye(e),T.finish("error",t),me(),c.hidden=!0),t}}),an}let Kn=n.client.subscribe(e=>{if(!Cn){if(e.stopped&&(Pe||a())&&!pe){ie=e,G();return}!pe&&(e.stopped||n.client.configurationReady===!1||ge&&ne!==ge&&(De(e)!==ge||["closed","ineligible","failed"].includes(e.status)))&&(me(),T?.finish("dismissed"),c.hidden=!0),le(e).catch(K)}}),et=n.client.subscribeError?.(e=>{se.pending||K(e)});function nt(){let e=n.client.view,t=e?.paywall;return!!t?.operation&&!!e&&["running","waiting"].includes(e.status)&&On(mn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect}))}function he(e){if(Re)return Re;if(s||!e&&(oe||V))return Promise.resolve();let t=!e&&je();return!t&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ie=n.client.view,G(),Promise.resolve()):(Re=Se(async()=>{let r=t?await n.client.retry():await(e?n.client.submit.bind(n.client):se.submit)({operation:"close",...e??ke()});return e&&bn(r),r},!0).then(()=>{let r=n.client.view;r?.status==="closed"&&!je()&&(ie=r,G())}).finally(()=>{Re=null}),Re)}function G(){An()}function An(e){_?.destroy(),!s&&(s=!0,se.destroy(),E(),!ln&&(ie?.status==="ineligible"||ie?.status==="completed")&&p?.withhold(),g(),n.signal?.removeEventListener("abort",G),f?.removeEventListener("abort",G),T?.finish("dismissed"),dn.destroy(),Kn(),et?.(),me(e),Ke(),w.stop(),D.remove(),!e||!c.contains(e)?c.remove():(U.remove(),j.remove()),!e&&!P&&u(),Ce(n.onDismiss,ie?structuredClone(ie):null))}q.onclick=()=>{if(!q.disabled){if(w.active){w.exit();return}Se(()=>n.client.submit({operation:"back",...ke()}))}},M.onclick=()=>{w.open()},A.onclick=()=>{T?.active?T.dismiss():oe||he()},Y.onclick=()=>{se.pending?se.retry().catch(()=>{}):je()?he():Se(()=>n.client.retry())},D.addEventListener("cancel",e=>{e.preventDefault(),T?.active?T.dismiss():oe||he()}),n.signal?.addEventListener("abort",G,{once:!0}),f?.addEventListener("abort",G,{once:!0});let nn=!1;p&&(E=p.onClose(()=>{s||re||(re=!0,T?.finish("dismissed"),me(),c.hidden=!0,n.client.view?he().finally(G):nn=!0)}));let Fn={destroy:G,refresh:cn,get recoveryPaywall(){if(h&&Ne)return{...Ne,view:h.currentResolution}},setPurchaseRecovery(e,t){return h?.setPurchaseRecovery(e,t),h!==null},retainPurchaseDialog(){let e=h?.retainPurchaseDialog();if(e)return h=null,An(e.dialog),{dialog:e.dialog,release(){e.release(),c.remove(),P||u()}}},get recovery(){let e=un();if(e)return e;if(!s&&!Z&&!pe&&!oe&&h){let t=h.recovery;if(t.type!=="native")return t}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(oe)return oe;let e=un();if(e)return Promise.resolve(e);let t=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,r=()=>({type:"recover",operationId:t,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let m=h?.recovery;return Promise.resolve(m&&m.type!=="native"&&m.type!=="cancel"?m:r())}let v=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(m=>m.operation==="close");if(s&&!(v||V&&n.client.view?.status==="closed")||Z||Je||Re||w.active||!h&&!V&&!v)return Promise.resolve(r());let ee=h,$=(async()=>{try{if(!V&&v){let l=await n.client.retry();return await le(n.client.view??l.run),r()}if(!V){let l=await ee.prepareFallback();if(l.type!=="native")return l;if(n.client.hasDurableJournal!==!0)return r();V=l}let m=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(m.length){let l=m.find(Q=>Q.operation==="close");if(!l||!z||l.requestId!==z.requestId)return r();let H=await n.client.retry();bn(H),await le(n.client.view??H.run)}else{let l=n.client.view,H=l?.paywall;if(!l||!H||H.selectionGeneration===void 0||(H.quote?.operationId??null)!==V.operationId||V.operationId!==null&&H.canReselect!==!0)return r();let Q=H.selectionGeneration,W=await n.client.get();await le(n.client.view??W.run);let C=n.client.view,B=C?.paywall;if(!C||!B||!["running","waiting"].includes(C.status)||C.stopped||C.id!==l.id||C.nodeId!==l.nodeId||C.visit!==l.visit||B.receiptId!==H.receiptId||B.selectionGeneration!==Q||(B.quote?.operationId??null)!==V.operationId||V.operationId!==null&&B.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return r();let y=ke();z={runId:C.id,operationId:V.operationId,revision:y.revision,requestId:y.requestId,nodeId:C.nodeId,visit:C.visit,receiptId:B.receiptId,selectionGeneration:Q,acknowledged:!1},await he(y)}let I=un();return I?(G(),I):r()}catch(m){return K(m),r()}})();oe=$;let we=()=>{oe===$&&(oe=null)};return $.then(we,we),$},review:w.open,exitReview:w.exit,get unappliedDrafts(){return w.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??vn)>=vn||e.instruction?.type==="evaluate_segment")&&(sn=cn().finally(()=>{sn=null})),await le(e);else{if(c.hidden=!0,s)throw new DOMException("Presentation cancelled","AbortError");let t=nn||n.prepared?.state==="shown"?null:Ze(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(s||re&&!nn)throw new DOMException("Presentation cancelled","AbortError");let r=n.client.get(),v=await(t?t.wait(r,He):it(r,He));if(Cn=!1,nn)return s||await he().finally(G),Fn;await le(n.client.view??v.run)}}catch(e){throw T?.finish("error",e),G(),e}return Fn}function it(i,b){let N;return Promise.race([i,new Promise((n,p)=>{N=setTimeout(()=>p(new Error("Presentation data timed out")),b)})]).finally(()=>clearTimeout(N))}function qt(i,b,N){return tt(i,b,N)}export{tt as a,qt as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.
|
|
1
|
+
var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.69",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md","native-funnel-host.NOTICES.txt"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};export{s as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-XAJEVHTU.js";import{a as tt}from"./chunk-3454S2FL.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-ECUGL7AO.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-3NV6NBQB.js";import{a as fe,b as Ze}from"./chunk-SFTMGGY4.js";import{a as le}from"./chunk-KJTHMRSH.js";import{e as de}from"./chunk-LUVTP4VU.js";import{a as D}from"./chunk-ZRU7WONE.js";import{h as ie}from"./chunk-TFPLIX5E.js";import{b as et}from"./chunk-3VUPVXAV.js";import{a as Qe}from"./chunk-5MRSFLQA.js";import{b as e}from"./chunk-S7NHVERO.js";import{c as Fe,f as Pe}from"./chunk-VPT5MFDG.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-WEYKNM2C.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-WEYKNM2C.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
|
|
1
|
+
import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-UIR5CBCC.js";import{a as tt}from"./chunk-ST7XO45I.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-ECUGL7AO.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-3NV6NBQB.js";import{a as fe,b as Ze}from"./chunk-MT4OQFDI.js";import{a as le}from"./chunk-KJTHMRSH.js";import{e as de}from"./chunk-LUVTP4VU.js";import{a as D}from"./chunk-ZRU7WONE.js";import{h as ie}from"./chunk-TFPLIX5E.js";import{b as et}from"./chunk-3VUPVXAV.js";import{a as Qe}from"./chunk-5MRSFLQA.js";import{b as e}from"./chunk-S7NHVERO.js";import{c as Fe,f as Pe}from"./chunk-VPT5MFDG.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-WEYKNM2C.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-WEYKNM2C.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
|