@tinkerlandai/longplay-sdk 0.10.39 → 0.10.40
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 +6 -0
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/dist/check-response-DRQCUWDW.js +1 -0
- package/dist/{chunk-CBZ5GW4J.js → chunk-2DPNSTCN.js} +1 -1
- package/dist/{chunk-CE5MAAIR.js → chunk-33ZVZOSC.js} +1 -1
- package/dist/{chunk-N774V4SQ.js → chunk-4TEZZZYK.js} +1 -1
- package/dist/{chunk-DPIQ3SV7.js → chunk-57GPGWSK.js} +1 -1
- package/dist/{chunk-O2D3A4CS.js → chunk-5DZJCFNQ.js} +1 -1
- package/dist/{chunk-PFPMK4IO.js → chunk-67AY54E2.js} +1 -1
- package/dist/{chunk-MTIOLSVM.js → chunk-6PG3AS3G.js} +1 -1
- package/dist/{chunk-GGYBZWWY.js → chunk-7QDT6DO7.js} +1 -1
- package/dist/{chunk-LZBJHWVH.js → chunk-ASDJTOGM.js} +1 -1
- package/dist/{chunk-GDD26ZDV.js → chunk-AZFWG352.js} +1 -1
- package/dist/{chunk-GNAMACMK.js → chunk-BYP4KVB3.js} +1 -1
- package/dist/{chunk-YJS6NNIO.js → chunk-C2KT5ZFU.js} +1 -1
- package/dist/{chunk-LJBTEB2Q.js → chunk-C3GYAKIU.js} +1 -1
- package/dist/{chunk-525K7BPJ.js → chunk-CZ4TQCUV.js} +1 -1
- package/dist/{chunk-CEMHQQAJ.js → chunk-EREQZWGI.js} +1 -1
- package/dist/{chunk-TA4W6SXG.js → chunk-ESAHTG3Y.js} +1 -1
- package/dist/{chunk-IGANLTKS.js → chunk-FCDWCQYC.js} +1 -1
- package/dist/{chunk-CKVAV2W5.js → chunk-GC6JBIRQ.js} +1 -1
- package/dist/chunk-IJKAQNK6.js +1 -0
- package/dist/{chunk-IYHXEKAD.js → chunk-IOJVF52Q.js} +1 -1
- package/dist/{chunk-3JD3U45R.js → chunk-LSPHUA7V.js} +1 -1
- package/dist/{chunk-YURGISSB.js → chunk-OOD2VDDP.js} +1 -1
- package/dist/{chunk-U7XD4ZR5.js → chunk-ORMQJAQE.js} +1 -1
- package/dist/{chunk-W3G4YIM5.js → chunk-P23JOPR5.js} +1 -1
- package/dist/{chunk-KIPUBMU3.js → chunk-P6C3PNMQ.js} +1 -1
- package/dist/chunk-PJS7M6X3.js +1 -0
- package/dist/{chunk-ZORZA4WG.js → chunk-POCDWUD3.js} +1 -1
- package/dist/{chunk-HFD4CLCJ.js → chunk-PZOQV6MU.js} +1 -1
- package/dist/{chunk-TLRRBUGP.js → chunk-QZTTKH2H.js} +1 -1
- package/dist/{chunk-HX36OZPQ.js → chunk-RFNIGJOL.js} +1 -1
- package/dist/{chunk-3S25TLC3.js → chunk-RULQQ7WI.js} +1 -1
- package/dist/{chunk-JBVZ6A6V.js → chunk-RV6UAUK2.js} +1 -1
- package/dist/chunk-U7GH4VME.js +1 -0
- package/dist/{chunk-UKVWANDE.js → chunk-VC2HPREX.js} +1 -1
- package/dist/{chunk-VYI6QRJW.js → chunk-VOKEZHAH.js} +1 -1
- package/dist/{chunk-TPXRO63H.js → chunk-WLGLQJ6M.js} +1 -1
- package/dist/{chunk-ONMIBSOC.js → chunk-X6ONZGRY.js} +1 -1
- package/dist/{chunk-BIT6YWM7.js → chunk-XDOKFAE6.js} +1 -1
- package/dist/{chunk-2Y5SGDC6.js → chunk-Y6HL2IY2.js} +1 -1
- package/dist/{chunk-JAZHNQKO.js → chunk-YLPQLD2A.js} +1 -1
- package/dist/{chunk-QCMFCK7Z.js → chunk-YY445FBU.js} +1 -1
- package/dist/{content-HSMBQFM3.js → content-QUEVNSXD.js} +1 -1
- package/dist/{funnel-host-purchase-4KOOLMXV.js → funnel-host-purchase-LMVMJNUO.js} +1 -1
- package/dist/funnel-paywall-prerender-LGUSHEP3.js +1 -0
- package/dist/funnel-runtime-host-H5FM67UC.js +1 -0
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-LZSQYE3O.js +1 -0
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-O7TCDGV4.js +1 -0
- package/dist/page.js +1 -1
- package/dist/{paywall-ZGG6DXO3.js → paywall-UANWOKKC.js} +1 -1
- package/dist/paywall-content-CHPX2P77.js +1 -0
- package/dist/paywall-session-3BNUC5ZE.js +1 -0
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-FFVZ64MR.js +1 -0
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +9 -10
- package/dist/check-response-MNFEOKKE.js +0 -1
- package/dist/chunk-73ISTR7P.js +0 -1
- package/dist/chunk-NSAEHRIT.js +0 -1
- package/dist/chunk-QXOUDODX.js +0 -1
- package/dist/funnel-paywall-prerender-NX6ZQ7EU.js +0 -1
- package/dist/funnel-runtime-host-6XYYLVCI.js +0 -1
- package/dist/merchant-bridge-contracts-ACGAMHU6.js +0 -1
- package/dist/operation-contracts-H27WHXQC.js +0 -1
- package/dist/paywall-content-ZQBE2EZP.js +0 -1
- package/dist/paywall-session-DBTBLLWI.js +0 -1
- package/dist/screen-renderer-5SJCTMJH.js +0 -1
- /package/dist/{chunk-NOOIJXRN.js → chunk-RGEBK6UF.js} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.40
|
|
4
|
+
|
|
5
|
+
- A purchase Funnel opens its first screen in one request. The purchase client asks Longplay to accept the Start and drive it to its first position in the same `recover_start` request (`intent: "start"`), instead of a recovery followed by a separate resume. A Run that ends in its first segment is reported as complete from that reply.
|
|
6
|
+
- Against an API without the `start` intent, the request is refused with 400 before anything is accepted, and the client repeats it with `intent: "resume"`, as 0.10.39 did.
|
|
7
|
+
- Wire protocol remains `0.10`.
|
|
8
|
+
|
|
3
9
|
## 0.10.39
|
|
4
10
|
|
|
5
11
|
- After a purchase is confirmed, the Paywall reads it every 700 ms, for up to 15 seconds, until the merchant's Checkout arrives. It used to wait 2 seconds, then 3, so a ready Checkout could sit for seconds before the Customer was sent to it. Once a Checkout exists the wait backs off as before.
|
package/README.md
CHANGED
|
@@ -262,7 +262,7 @@ When the merchant's targeting is off, omit `start` and set `allowNewPurchase: fa
|
|
|
262
262
|
|
|
263
263
|
`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.
|
|
264
264
|
|
|
265
|
-
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 remains blocked. Initial `start()` and explicit `retry()` use `intent: "
|
|
265
|
+
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 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.
|
|
266
266
|
|
|
267
267
|
#### Pre-render the first Paywall
|
|
268
268
|
|
package/README.zh-CN.md
CHANGED
|
@@ -224,7 +224,7 @@ SDK 在首次派发前保存原 Start 请求 ID 和完整输入;同一未决
|
|
|
224
224
|
|
|
225
225
|
`merchant` 允许 merchant Provider,`record_only` 允许商户执行的 Stripe 报价,`indiana` 允许平台执行,`native` 允许 Apple/Google。首次确认、Host 自动流程和原日志重试共用 Controller 派发边界检查;恢复时取原策略与当前策略的交集。展示继续使用现有 loading/ready/dismissed/error 生命周期,`onDismiss` 前已释放展示入口,未知 Close 和未决购买保留原单保护。Operation 购买完成不替代未知 Run/Close 的服务端结算。
|
|
226
226
|
|
|
227
|
-
配套的 [Customer Session 恢复协议](../../docs/funnel-storage-design.md#customer-session-recovery-protocol)使用当前原 Customer 的 Access Token;新登录会话可恢复同一原 Run,不补发 Run Token。`refresh()` 对未知 Start 只执行 `recover_start/lookup`,查不到仍受阻;首次 `start()` 和显式 `retry()` 才以原 ID、原完整输入执行 `resume
|
|
227
|
+
配套的 [Customer Session 恢复协议](../../docs/funnel-storage-design.md#customer-session-recovery-protocol)使用当前原 Customer 的 Access Token;新登录会话可恢复同一原 Run,不补发 Run Token。`refresh()` 对未知 Start 只执行 `recover_start/lookup`,查不到仍受阻;首次 `start()` 和显式 `retry()` 才以原 ID、原完整输入执行 `recover_start/start`:Longplay 受理未见过的 Start,并在同一请求里推进到第一个位置,首屏不再需要单独的 `resume`。不支持 `start` 的旧 API 以 400 拒绝,SDK 随即改用 `resume` 重发同一请求。已知 Run 使用 `recover_run`,原日志经 `settle_command` 结算后,由同一 Controller 通过 `run_command` 继续。仅可恢复 Operation 时,通过 `recover_purchase` 读取原 Receipt/Operation 及服务端重选裁决,保留原引用和未决命令;失败/取消状态不能覆盖 `canReselect: false`,命令未结算时也不提前报告完成;没有服务端负证明便不能开启替代购买。托管恢复需要配套的 Indianapolis 运行时和 SQL 函数;离线模拟不代表真实 Sandbox、原生 RLS 或事务锁并发验收。
|
|
228
228
|
|
|
229
229
|
#### 预渲染首个 Paywall
|
|
230
230
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b}from"./chunk-7QDT6DO7.js";import"./chunk-Y6HL2IY2.js";import"./chunk-LSPHUA7V.js";import"./chunk-OOD2VDDP.js";import"./chunk-WLGLQJ6M.js";import"./chunk-RULQQ7WI.js";import"./chunk-RGEBK6UF.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as $,b as N,c as J,d as q}from"./chunk-
|
|
1
|
+
import{a as $,b as N,c as J,d as q}from"./chunk-C2KT5ZFU.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-RV6UAUK2.js";import{b as C,c as O,e as j}from"./chunk-O4KXODTJ.js";import{a as _}from"./chunk-DSPLGTQI.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}}/*!
|
|
2
2
|
Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
|
|
3
3
|
plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
|
|
4
4
|
*/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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{k as c}from"./chunk-
|
|
1
|
+
import{k as c}from"./chunk-XDOKFAE6.js";import{b as r}from"./chunk-RGEBK6UF.js";var s=r.strictObject({items:r.array(r.strictObject({productVersionId:r.string().min(1).max(200),label:r.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:r.string().min(1).max(200).nullable(),grouping:c.optional()});function p(e,t,n){let i=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof i!="string"||!Object.values(n.plans).some(o=>o.versionId===i&&o.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(i)||!n.pickers[e.pickerId]?.options.includes(i))?null:i}export{s as a,p as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as ue,g as se}from"./chunk-HX36OZPQ.js";import{b as on}from"./chunk-ONMIBSOC.js";import{d as tn,e as pe}from"./chunk-CEMHQQAJ.js";import{c as Be,d as Ke,e as J,l as nn}from"./chunk-W3G4YIM5.js";import{$ as de,A as $e,E as Ye,S as Ze,X as We,Y as Xe,Z as $,_ as en,a as j,aa as U,b as qe,c as Me,d as je,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,y as Je}from"./chunk-IYHXEKAD.js";import{b as an}from"./chunk-3NCMYTNG.js";import{b as ne}from"./chunk-HFD4CLCJ.js";import{a as W}from"./chunk-IGANLTKS.js";import{$ as Qe,I as L,J as De,K as Le,Z as He,_ as le,aa as ce,g as Oe,m as Ae,q as Te,z as ae}from"./chunk-BIT6YWM7.js";import{b as D}from"./chunk-YURGISSB.js";import{a as f}from"./chunk-TPXRO63H.js";import{b as rn}from"./chunk-JBVZ6A6V.js";import{b as n}from"./chunk-NOOIJXRN.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-O4KXODTJ.js";import{a as Pe,b as Ne}from"./chunk-CILM5XMH.js";function un(e){return Cn({...e,namespace:"commands",identity:[e.runToken]})}function Cn(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??rn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var sn=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Pn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Nn=n.discriminatedUnion("type",[Ye,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:q.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:We,openIn:Xe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),On={id:q,presentation:Te,outputs:n.array(q).max(250),inputs:ce,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(q,He.nullable())},An=n.strictObject({...On,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:sn,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Pn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:Qe,variables:n.record(n.string(),L),output:L.nullable(),screen:An.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([tn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Nn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),Tn=n.strictObject({scope:D,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),ln=Tn.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var cn="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function dn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var _n=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),kn=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(_n).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=kn.omit({variation:!0,description:!0,iam:!0}),Vn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),pn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(Vn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),jt=n.strictObject({iam:Q,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Dn=n.strictObject({release:Q,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Gt=n.strictObject({scope:D.extend({environmentId:n.uuid()}),release:Q,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Je.optional(),target:Dn})).max(4e3)}),Ut=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Q,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Bt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Kt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Ln=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),mn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Ln.extend({receiptId:n.uuid()})).max(100),payload:pn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(j,j),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),fn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:gn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...fn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...fn,evaluationMode:n.literal("remote")})]),qn=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ze.nullable()}))})});function Mn(e){return gn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Mn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:nn(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function er(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return qn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,jn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var Gn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),L),Un=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:en,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),ar=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:Gn,context:Ie,steps:n.array(Un).min(1).max(he)}).refine(e=>X(e)<=jn,"Segment exceeds its byte budget");var Bn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Y(e){return Array.isArray(e)?e.some(Y):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Y(u):!Bn.test(t))}function yn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Y(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Y(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Y(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Kn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Kn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let I=e.conditions[a.id];if(!I)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:I.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=h.value,o=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function hr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),zn(p,c,d))}function zn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function wr(e,t,u,r=re){return vn(Re(e,r),t,u)}function vn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(L.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(L.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function In(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>yn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),vn(I,O,{attributes:$e({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let R=s.type==="end"?s.output:s.value;if(m=R?.type==="feature"?b(s.id):{...m,port:"value",value:R?.type==="literal"?R.value:R?.type==="variable"?Ue({source:"variable",key:R.key,...R.path?{path:R.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},R&&(m.value===void 0||!je(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:o,result:m}];if(X({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let R=s.type==="coupons"?s.couponIds.map(V=>({type:"reward",id:V})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(R===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=G(s,{value:R});Ge(t.variables,s,_),Object.assign(c,_)}for(let R of m.sticky)d[`${R.next.attributeName}||${R.next.attributeValue}`]=structuredClone(R.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let T=p.get(o);return{steps:a,...!y&&T&&(!we(T)||h(T))?{boundary:{nodeId:o,visit:g}}:{}}}function hn(e,t){let u=ln.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Cr(e){return xe(e,Se)}var Jn=3,$n=2e3;function Hn(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Qn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Jn||!Hn(u))throw u;await new Promise(r=>setTimeout(r,t*$n))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Yn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Qn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Yn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Zn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Zn(e,t,u){return In(e,t,u,Se)}var wn=U.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),bn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function xn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:bn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let I=await e.write(g.revision,y);if(I!==null){if(!Number.isSafeInteger(I)||I<=g.revision)throw A();t=I;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=bn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,I)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[h,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(I!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((I,h)=>{if(!I&&h!==t||I&&r(I)!==r({...a,schemaVersion:1}))throw A();if(I?.purchase&&I.purchase.generation>o.generation)return Z(I,y);if(I?.purchase&&I.purchase.generation===o.generation&&I.purchase.operationId!==o.operationId)throw A();return g?!I?.purchase||I.purchase.operationId!==o.operationId?Z(I,y):Z(I.command?{...I,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...I,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function jr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function Rn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,I=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,b="Run identity changed during the request"){if(h!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!ie(h.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of I)try{m(structuredClone(r))}catch{}}},identify(h){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(h))throw new f("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return I.add(h),()=>I.delete(h)},reset(){o||(o=!0,a(),g=void 0,r=null,I.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function $r(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Hr(e){let t=ne(e);return t.identify(e.apiKey),t}function Sn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Wn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Fn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function I(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:M(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let R=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Wn(C),V=!1;if(R&&_&&m===t.generation&&i===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});V=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw m===t.generation&&(i===s||p===s)&&_&&(!R||!(C instanceof f)||C.status===void 0||V)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),C}}function h(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return T(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(M(p))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(M(i))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=I(s);d[m]=x;let C=()=>{d[m]===x&&(d[m]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,C){let R=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=R&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==R&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?R:void 0,V=i?.requestId===_?i:p?.requestId===_?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,v=l??m.purchase,P=v?.operation,E=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,S=P?.operationId??v?.quote?.operationId??E?.operationId,F=v?.receiptId??E?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!o||w>=o.generation)){let N={receiptId:F,operationId:S,generation:w},k=an(P,v?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},N,k,_),t.assertCurrent(x),(!o||N.generation>=o.generation)&&(C===void 0||C>=t.readSequence)&&(k?o?.operationId===N.operationId&&(o=void 0):o=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(V):!1},stop(){c=!0},submit:h,settle:T,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Xn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=Rn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?un(e):void 0),a=d&&xn(d),o=Fn({journal:a,state:i,call:T,processIdentity:e.process}),g=0,y=new Map;function I(){g++,y.clear(),t=void 0}async function h(l){let v=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!v&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(v?.operation==="submit"&&v.input.type==="paywall_confirm"){let N=i.view?.paywall;Sn(u,N?.quote?.operationId===v.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=i.generation;i.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),S=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=i.signal,k,K=()=>{},En=new Promise((et,Ce)=>{K=()=>Ce(N.reason),N.addEventListener("abort",K,{once:!0}),k=setTimeout(()=>Ce(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(P),e.session.access())),En])}finally{clearTimeout(k),N.removeEventListener("abort",K)}}i.assertCurrent(P);let F={...l,...S?{customerToken:S}:{}},w=l.operation==="page_experiments"?ye.parse(F):U.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!S?{[cn]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){I(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function T(l,v){let P=t;t=void 0;let E=i.generation,S=()=>i.assertCurrent(E);a&&await o.ready,S();let F=i.view,w=hn(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(S(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let k=await o.observe(l,w,E,v);return(!i.view||w.run.revision>=i.view.revision)&&(v===void 0||v>=i.readSequence)&&(await e.onAcceptedResponse?.(w),S()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,F,v,k)),w}function O(l){let v=i.generation;I();let P=l(),E=()=>{i.generation===v&&I()};return P.then(E,E),P}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function C(l){let v=x.get(l);if(v)return v;let P=_(l);return x.set(l,P),P}let R=!1;async function _(l){let v=await l;if(v.run.instruction?.type!=="evaluate_segment")return v;if(m)return m;R=!0;let P=i.generation,E=(async()=>{for(let S=0;S<32&&v.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return v;let F=v.run;if(v.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Fe(e.configuration,F,{predict:!1});if(P!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return v;if(i.view&&(i.view.revision!==F.revision||i.view.visit!==F.visit||i.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Fe(e.configuration,F).then(({prediction:K})=>{k&&P===i.generation&&!o.closeRequested&&i.view?.id===F.id&&!i.view.stopped&&i.view.nodeId===F.nodeId&&i.view.visit===F.visit&&i.view.revision===F.revision&&(c=K)}).catch(()=>{});try{v=await s({operation:"commit_segment",requestId:dn(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...N})}finally{k=!1,c=null}}}return v})();m=E;try{return await E}finally{m===E&&(m=null)}}let V={get configuration(){return R?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(M(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(M(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return on(e,l)},async pageExperiments(l,v=[]){let P=i.generation;i.assertCurrent(P);let E=i.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let S=mn.parse(await h(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:v})));if(i.assertCurrent(P),S.runId!==E||S.scope.projectId!==i.scope?.projectId||S.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,v){let P=i.generation;l=l&&structuredClone(l),v=v&&{...v},a&&await o.ready,i.assertCurrent(P),v??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let E=JSON.stringify([i.generation,g,l??null,v??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=i.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...v?{purchase:v}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?V.settle(l):o.pending?.requestId===l?C(s(o.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(s(l))},async retry(){if(o.closeFlight)return o.closeFlight;if(o.closing)return s(o.closing);if(o.closeRequested&&o.pending)return V.settle(o.pending.requestId);if(o.inFlight)return C(o.inFlight);if(!o.pending)throw new f("INVALID_REQUEST","No command is pending");let l=o.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let v=i.generation;if(await V.settle(l.requestId),i.assertCurrent(v),!o.pending)return V.get();if(o.pending!==l||o.closeRequested)throw new f("COMMAND_PENDING","The original quote is being recovered")}return C(s(l))},identify(l){let v=i.customerToken?void 0:t;I(),i.identify(l),t=v,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return V}function vo(e,t){return Xn({...e,runToken:"",initialResponse:t})}export{dn as a,sn as b,Nn as c,me as d,Tn as e,ln as f,Dn as g,Gt as h,Ut as i,Bt as j,ye as k,mn as l,te as m,qn as n,er as o,hr as p,wr as q,hn as r,Se as s,Cr as t,Zn as u,bn as v,Z as w,un as x,Cn as y,jr as z,ie as A,Ee as B,$r as C,Hr as D,Sn as E,Xn as F,vo as G};
|
|
1
|
+
import{f as ue,g as se}from"./chunk-RFNIGJOL.js";import{b as on}from"./chunk-X6ONZGRY.js";import{d as tn,e as pe}from"./chunk-EREQZWGI.js";import{c as Be,d as Ke,e as J,l as nn}from"./chunk-P23JOPR5.js";import{$ as de,A as $e,E as Ye,S as Ze,X as We,Y as Xe,Z as $,_ as en,a as j,aa as U,b as qe,c as Me,d as je,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,y as Je}from"./chunk-IOJVF52Q.js";import{b as an}from"./chunk-3NCMYTNG.js";import{b as ne}from"./chunk-PZOQV6MU.js";import{a as W}from"./chunk-FCDWCQYC.js";import{$ as Qe,I as L,J as De,K as Le,Z as He,_ as le,aa as ce,g as Oe,m as Ae,q as Te,z as ae}from"./chunk-XDOKFAE6.js";import{b as D}from"./chunk-OOD2VDDP.js";import{a as f}from"./chunk-WLGLQJ6M.js";import{b as rn}from"./chunk-RV6UAUK2.js";import{b as n}from"./chunk-RGEBK6UF.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-O4KXODTJ.js";import{a as Pe,b as Ne}from"./chunk-CILM5XMH.js";function un(e){return Cn({...e,namespace:"commands",identity:[e.runToken]})}function Cn(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??rn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var sn=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Pn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Nn=n.discriminatedUnion("type",[Ye,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:q.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:We,openIn:Xe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),On={id:q,presentation:Te,outputs:n.array(q).max(250),inputs:ce,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(q,He.nullable())},An=n.strictObject({...On,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:sn,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Pn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:Qe,variables:n.record(n.string(),L),output:L.nullable(),screen:An.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([tn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Nn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),Tn=n.strictObject({scope:D,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),ln=Tn.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var cn="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function dn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var _n=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),kn=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(_n).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=kn.omit({variation:!0,description:!0,iam:!0}),Vn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),pn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(Vn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),jt=n.strictObject({iam:Q,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Dn=n.strictObject({release:Q,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Gt=n.strictObject({scope:D.extend({environmentId:n.uuid()}),release:Q,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Je.optional(),target:Dn})).max(4e3)}),Ut=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Q,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Bt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Kt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Ln=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),mn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Ln.extend({receiptId:n.uuid()})).max(100),payload:pn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(j,j),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),fn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:gn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...fn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...fn,evaluationMode:n.literal("remote")})]),qn=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ze.nullable()}))})});function Mn(e){return gn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Mn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:nn(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function er(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return qn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,jn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var Gn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),L),Un=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:en,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),ar=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:Gn,context:Ie,steps:n.array(Un).min(1).max(he)}).refine(e=>X(e)<=jn,"Segment exceeds its byte budget");var Bn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Y(e){return Array.isArray(e)?e.some(Y):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Y(u):!Bn.test(t))}function yn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Y(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Y(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Y(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Kn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Kn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let I=e.conditions[a.id];if(!I)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:I.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=h.value,o=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function hr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),zn(p,c,d))}function zn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function wr(e,t,u,r=re){return vn(Re(e,r),t,u)}function vn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(L.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(L.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function In(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>yn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),vn(I,O,{attributes:$e({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let R=s.type==="end"?s.output:s.value;if(m=R?.type==="feature"?b(s.id):{...m,port:"value",value:R?.type==="literal"?R.value:R?.type==="variable"?Ue({source:"variable",key:R.key,...R.path?{path:R.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},R&&(m.value===void 0||!je(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:o,result:m}];if(X({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let R=s.type==="coupons"?s.couponIds.map(V=>({type:"reward",id:V})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(R===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=G(s,{value:R});Ge(t.variables,s,_),Object.assign(c,_)}for(let R of m.sticky)d[`${R.next.attributeName}||${R.next.attributeValue}`]=structuredClone(R.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let T=p.get(o);return{steps:a,...!y&&T&&(!we(T)||h(T))?{boundary:{nodeId:o,visit:g}}:{}}}function hn(e,t){let u=ln.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Cr(e){return xe(e,Se)}var Jn=3,$n=2e3;function Hn(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Qn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Jn||!Hn(u))throw u;await new Promise(r=>setTimeout(r,t*$n))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Yn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Qn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Yn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Zn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Zn(e,t,u){return In(e,t,u,Se)}var wn=U.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),bn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function xn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:bn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let I=await e.write(g.revision,y);if(I!==null){if(!Number.isSafeInteger(I)||I<=g.revision)throw A();t=I;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=bn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,I)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[h,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(I!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((I,h)=>{if(!I&&h!==t||I&&r(I)!==r({...a,schemaVersion:1}))throw A();if(I?.purchase&&I.purchase.generation>o.generation)return Z(I,y);if(I?.purchase&&I.purchase.generation===o.generation&&I.purchase.operationId!==o.operationId)throw A();return g?!I?.purchase||I.purchase.operationId!==o.operationId?Z(I,y):Z(I.command?{...I,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...I,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function jr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function Rn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,I=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,b="Run identity changed during the request"){if(h!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!ie(h.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of I)try{m(structuredClone(r))}catch{}}},identify(h){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(h))throw new f("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return I.add(h),()=>I.delete(h)},reset(){o||(o=!0,a(),g=void 0,r=null,I.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function $r(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Hr(e){let t=ne(e);return t.identify(e.apiKey),t}function Sn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Wn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Fn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function I(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:M(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let R=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Wn(C),V=!1;if(R&&_&&m===t.generation&&i===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});V=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw m===t.generation&&(i===s||p===s)&&_&&(!R||!(C instanceof f)||C.status===void 0||V)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),C}}function h(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return T(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(M(p))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(M(i))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=I(s);d[m]=x;let C=()=>{d[m]===x&&(d[m]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,C){let R=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=R&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==R&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?R:void 0,V=i?.requestId===_?i:p?.requestId===_?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,v=l??m.purchase,P=v?.operation,E=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,S=P?.operationId??v?.quote?.operationId??E?.operationId,F=v?.receiptId??E?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!o||w>=o.generation)){let N={receiptId:F,operationId:S,generation:w},k=an(P,v?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},N,k,_),t.assertCurrent(x),(!o||N.generation>=o.generation)&&(C===void 0||C>=t.readSequence)&&(k?o?.operationId===N.operationId&&(o=void 0):o=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(V):!1},stop(){c=!0},submit:h,settle:T,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Xn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=Rn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?un(e):void 0),a=d&&xn(d),o=Fn({journal:a,state:i,call:T,processIdentity:e.process}),g=0,y=new Map;function I(){g++,y.clear(),t=void 0}async function h(l){let v=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!v&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(v?.operation==="submit"&&v.input.type==="paywall_confirm"){let N=i.view?.paywall;Sn(u,N?.quote?.operationId===v.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=i.generation;i.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),S=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=i.signal,k,K=()=>{},En=new Promise((et,Ce)=>{K=()=>Ce(N.reason),N.addEventListener("abort",K,{once:!0}),k=setTimeout(()=>Ce(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(P),e.session.access())),En])}finally{clearTimeout(k),N.removeEventListener("abort",K)}}i.assertCurrent(P);let F={...l,...S?{customerToken:S}:{}},w=l.operation==="page_experiments"?ye.parse(F):U.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!S?{[cn]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){I(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function T(l,v){let P=t;t=void 0;let E=i.generation,S=()=>i.assertCurrent(E);a&&await o.ready,S();let F=i.view,w=hn(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(S(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let k=await o.observe(l,w,E,v);return(!i.view||w.run.revision>=i.view.revision)&&(v===void 0||v>=i.readSequence)&&(await e.onAcceptedResponse?.(w),S()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,F,v,k)),w}function O(l){let v=i.generation;I();let P=l(),E=()=>{i.generation===v&&I()};return P.then(E,E),P}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function C(l){let v=x.get(l);if(v)return v;let P=_(l);return x.set(l,P),P}let R=!1;async function _(l){let v=await l;if(v.run.instruction?.type!=="evaluate_segment")return v;if(m)return m;R=!0;let P=i.generation,E=(async()=>{for(let S=0;S<32&&v.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return v;let F=v.run;if(v.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Fe(e.configuration,F,{predict:!1});if(P!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return v;if(i.view&&(i.view.revision!==F.revision||i.view.visit!==F.visit||i.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Fe(e.configuration,F).then(({prediction:K})=>{k&&P===i.generation&&!o.closeRequested&&i.view?.id===F.id&&!i.view.stopped&&i.view.nodeId===F.nodeId&&i.view.visit===F.visit&&i.view.revision===F.revision&&(c=K)}).catch(()=>{});try{v=await s({operation:"commit_segment",requestId:dn(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...N})}finally{k=!1,c=null}}}return v})();m=E;try{return await E}finally{m===E&&(m=null)}}let V={get configuration(){return R?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(M(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(M(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return on(e,l)},async pageExperiments(l,v=[]){let P=i.generation;i.assertCurrent(P);let E=i.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let S=mn.parse(await h(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:v})));if(i.assertCurrent(P),S.runId!==E||S.scope.projectId!==i.scope?.projectId||S.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,v){let P=i.generation;l=l&&structuredClone(l),v=v&&{...v},a&&await o.ready,i.assertCurrent(P),v??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let E=JSON.stringify([i.generation,g,l??null,v??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=i.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...v?{purchase:v}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?V.settle(l):o.pending?.requestId===l?C(s(o.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(s(l))},async retry(){if(o.closeFlight)return o.closeFlight;if(o.closing)return s(o.closing);if(o.closeRequested&&o.pending)return V.settle(o.pending.requestId);if(o.inFlight)return C(o.inFlight);if(!o.pending)throw new f("INVALID_REQUEST","No command is pending");let l=o.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let v=i.generation;if(await V.settle(l.requestId),i.assertCurrent(v),!o.pending)return V.get();if(o.pending!==l||o.closeRequested)throw new f("COMMAND_PENDING","The original quote is being recovered")}return C(s(l))},identify(l){let v=i.customerToken?void 0:t;I(),i.identify(l),t=v,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return V}function vo(e,t){return Xn({...e,runToken:"",initialResponse:t})}export{dn as a,sn as b,Nn as c,me as d,Tn as e,ln as f,Dn as g,Gt as h,Ut as i,Bt as j,ye as k,mn as l,te as m,qn as n,er as o,hr as p,wr as q,hn as r,Se as s,Cr as t,Zn as u,bn as v,Z as w,un as x,Cn as y,jr as z,ie as A,Ee as B,$r as C,Hr as D,Sn as E,Xn as F,vo as G};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as o}from"./chunk-
|
|
1
|
+
import{b as o}from"./chunk-RGEBK6UF.js";var s=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],n=o.string().regex(/.+\/.+/),e=o.number().min(-100),t=o.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),p=o.strictObject({input:t,output:t,cache_read:t.optional(),cache_write:t.optional(),reasoning:t.optional(),input_audio:t.optional(),output_audio:t.optional()}),i=(r,a)=>o.record(r,a).refine(c=>Object.keys(c).length<=100,"At most 100 AI overrides"),d=o.strictObject({defaultMarkup:e,providerMarkups:i(o.string().min(1),e),modelMarkups:i(n,e),customModels:i(n,p.partial())});export{s as a,n as b,e as c,p as d,d as e};
|