@tinkerlandai/longplay-sdk 0.10.6 → 0.10.7

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 CHANGED
@@ -1,9 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.7 — 2026-11-01
4
+
5
+ - Require the clicked node itself to remain the unique active IAM target; hidden or detached controls cannot borrow a replacement's anchor.
6
+ - Release entry waits when an accepted Run credential is revoked before its first read or a close after navigation; preserve original requests on transient failures.
7
+ - Bound immutable release descriptor headers and body with one deadline, cancel late responses, and support AbortController without optional AbortSignal helpers.
8
+
3
9
  ## 0.10.6
4
10
 
5
11
  Only Longplay public factories, errors, types and browser globals are supported. Migrate old Indiana imports to their Longplay names. Internal implementations, protocol and saved identities are unchanged; previously published artifacts remain immutable.
6
12
 
13
+
7
14
  ## 0.10.5 — 2026-11-01
8
15
 
9
16
  - Make IAM Funnel entries recover from configuration timeouts, delayed scene changes, hidden retained pages and earlier refused entries; recheck the selected scene before mounting a Run.
package/README.md CHANGED
@@ -6,13 +6,13 @@
6
6
 
7
7
  # @tinkerlandai/longplay-sdk
8
8
 
9
- This source checkout is SDK 0.10.6, protocol 0.10. These examples use `https://api.longplayai.com` with a Sandbox App and credentials issued by the production deployment. Sandbox still contains production data; do not reuse credentials from the separate test deployment. Confirm runtime readiness in [environment state](../../docs/development-status.md) before running them.
9
+ This source checkout is SDK 0.10.7, protocol 0.10. These examples use `https://api.longplayai.com` with a Sandbox App and credentials issued by the production deployment. Sandbox still contains production data; do not reuse credentials from the separate test deployment. Confirm runtime readiness in [environment state](../../docs/development-status.md) before running them.
10
10
 
11
11
  [简体中文](./README.zh-CN.md)
12
12
 
13
13
  The Longplay business SDK groups its capabilities as **Identity, Commerce, experimentation engine, Analytics, Delivery (Offering, Paywall, Page, Popup and Banner), and Funnel**, over shared protocol, transport, configuration, rendering and recovery foundations. These responsibilities follow the existing L0–L4 architecture; language packages and entry points implement different subsets. The browser/native client and merchant-server entries share contracts and core behavior while retaining separate credentials and allowed operations. Indianapolis is the backend runtime they call; it is not the merchant's server SDK.
14
14
 
15
- **IAM source scanning, generation, validation and upload belong to the independent build package `@tinkerlandai/longplay-iam`.** This business SDK retains only the runtime release binding used by GB visual changes. See [SDK boundaries](../../docs/sdk-architecture.md) and the [IAM package](../iam/README.md).
15
+ **IAM source scanning, generation, validation and upload belong to the independent build package `@tinkerlandai/longplay-iam`.** This business SDK consumes the runtime release binding for IAM Funnel entries and GB visual changes. See [SDK boundaries](../../docs/sdk-architecture.md) and the [IAM package](../iam/README.md).
16
16
 
17
17
  ```sh
18
18
  npm install --save-exact @tinkerlandai/longplay-sdk@latest
@@ -20,7 +20,7 @@ npm install --save-exact @tinkerlandai/longplay-sdk@latest
20
20
 
21
21
  The first install resolves latest and saves an exact package.json version. Commit the lockfile and use npm ci for later builds. Use the original package identity and exact version from the [release records](../../docs/sdk-releases.md) for historical installations and rollback. New Longplay package names require their own publication; source changes do not publish artifacts.
22
22
 
23
- IAM Funnel entry reliability fixes require SDK 0.10.6 or later. Select this release explicitly with `npm install --save-exact @tinkerlandai/longplay-sdk@0.10.5`; current mutable tags are recorded in the [release records](../../docs/sdk-releases.md).
23
+ IAM Funnel entries and their initial reliability fixes require SDK 0.10.5 or later. Select this release explicitly with `npm install --save-exact @tinkerlandai/longplay-sdk@0.10.5`; current mutable tags are recorded in the [release records](../../docs/sdk-releases.md).
24
24
 
25
25
  This SDK requires HTTP protocol 0.10. The runtime must serve the same current protocol; publishing a package does not deploy the server. Publication and accepted environment scope are recorded in the [release ledger](../../docs/sdk-releases.md) and [development status](../../docs/development-status.md).
26
26
 
@@ -396,11 +396,11 @@ entries.destroy();
396
396
 
397
397
  The host observes original button behavior, matches unique render/element guards and attempts automatic entries once per pathname visit. GOP selects the Funnel, checks entry publication, suppresses an existing Customer/Funnel Run and enforces the automatic-entry cooldown. The host retains unknown requests in memory; page reload recovery is not included. When a Run is stopped from Console or expires, the host removes its UI and reports `run_ended`, whether the Run reads `closed` or its next command is refused with `FORBIDDEN`; a later trigger can then start again. An IAM binding supplies no Customer credential or business permission.
398
398
 
399
- The entry scope is the route template plus render, covering every matching dynamic URL instance. Query/hash changes do not create a new visit. Supported anchor and inline-display changes recheck delayed scenes; hidden retained pages do not block the single active button. Multiple active targets remain refused. Configuration fetch/body reads default to a five-second deadline (`timeoutMs` overrides it), recover on the next 15-second poll, and discard late responses. Inspect `onStatus` for `identity_required`, `configuration_unavailable`, `incompatible` and `start_failed`. Definitively refused entries allow the next matching entry in delivered order; pending unknown starts wait for `retry()`. Other entries are preserved while a Run is mounted and reconsidered when it ends. Original button navigation continues, so full-page navigation can prevent presentation.
399
+ The entry scope is the route template plus render, covering every matching dynamic URL instance. Query/hash changes do not create a new visit. Supported anchor and inline-display changes recheck delayed scenes; hidden retained pages do not block the single active button. The clicked control itself must still be the unique active target; a replacement with the same selector cannot authorize an obsolete click. Multiple active targets remain refused. Configuration fetch/body reads default to a five-second deadline (`timeoutMs` overrides it), recover on the next 15-second poll, and discard late responses. Inspect `onStatus` for `identity_required`, `configuration_unavailable`, `incompatible` and `start_failed`. Definitively refused entries and accepted Runs whose first read is refused with a revoked credential allow the next matching entry in delivered order; transient read failures and pending unknown starts retain the original request for `retry()`. Other entries are preserved while a Run is mounted and reconsidered when it ends. Original button navigation continues, so full-page navigation can prevent presentation.
400
400
 
401
401
  An opted-in Split (`applyPageExperiment: true`) uses its accepted experiment variation for the merchant page. The entry host automatically shares `appManifestRelease` with `showFunnelRun`; manual hosts pass that option explicitly. `createFunnelPageExperiments({client, appManifestRelease})` is available for hosts without the standard UI. The consumer never rebuckets, reports use against the accepted receipt, and reverts on stop, completion or destruction. A separately installed visual consumer yields ownership of that experiment during the Run. This Web source feature requires matching GOP contracts and the IAM/Funnel database migration; installation alone does not promote runtime support.
402
402
 
403
- All eligible changesets are delivered within the visual payload's existing 100-item/2 MiB budget, with one assignment per accepted Split receipt and up to 100 assignments. More than 20 distinct assignments require the matching GOP response contract and SDK before the SQL is activated. Used-receipt requests keep their existing 20-ID limit. After a source upgrade, check **Version applicability** in the App page map: invalid published Funnel entries link to the affected Funnel for reselection and publication. Missing current versions, read failures and incomplete inventories remain explicit. Follow the [two-layer integration guide](https://longplayai.com/docs/iam?lang=en#funnel-entries) for build binding and host lifecycle.
403
+ All eligible changesets are delivered within the visual payload's existing 100-item/2 MiB budget, with one assignment per accepted Split receipt and up to 100 assignments. More than 20 distinct assignments require the matching GOP response contract and SDK before the SQL is activated. Used-receipt requests keep their existing 20-ID limit. After a source upgrade, check **Version applicability** in the App page map: invalid published Funnel entries link to the affected Funnel for reselection and publication. Missing current versions, read failures and incomplete inventories remain explicit. The immutable release descriptor has a separate two-second deadline covering fetch headers and body, including fetch wrappers that ignore abort. It requires ordinary AbortController support. Follow the [two-layer integration guide](https://longplayai.com/docs/iam?lang=en#funnel-entries) for build binding and host lifecycle.
404
404
 
405
405
  ## Funnel-scoped resource requests
406
406
 
package/README.zh-CN.md CHANGED
@@ -6,13 +6,13 @@
6
6
 
7
7
  [English](./README.md)
8
8
 
9
- 当前源码为 SDK 0.10.6、协议 0.10。本页示例使用 `https://api.longplayai.com` 以及生产部署内签发的 Sandbox App/凭据。Sandbox 仍属于生产数据,不能复用独立测试部署的凭据。运行前核对[环境状态](../../docs/development-status.md),确认服务已就绪。
9
+ 当前源码为 SDK 0.10.7、协议 0.10。本页示例使用 `https://api.longplayai.com` 以及生产部署内签发的 Sandbox App/凭据。Sandbox 仍属于生产数据,不能复用独立测试部署的凭据。运行前核对[环境状态](../../docs/development-status.md),确认服务已就绪。
10
10
 
11
11
  # @tinkerlandai/longplay-sdk
12
12
 
13
13
  业务 SDK 按职责分为 **身份、商业、实验引擎、Analytics、内容交付(Offering、Paywall、Page、Popup、Banner)和 Funnel 六组能力**,共用协议、传输、配置、渲染与恢复等基础设施。分类沿用系统的 L0–L4 归属,各语言包和入口支持的子集不同。客户端与商户服务端共用契约和核心行为,凭据及可执行操作分开。Indianapolis 是它们调用的 SDK 运行服务,不是商户安装的服务端 SDK。
14
14
 
15
- **IAM 的源码扫描、生成、校验和上传属于独立构建包 `@tinkerlandai/longplay-iam`。** 普通业务 SDK 只保留 GB visual 应用页面变更所需的运行时 release 绑定。完整定义见 [SDK 边界](../../docs/sdk-architecture.md) 与 [IAM 构建包](../iam/README.md)。
15
+ **IAM 的源码扫描、生成、校验和上传属于独立构建包 `@tinkerlandai/longplay-iam`。** 普通业务 SDK 消费 IAM Funnel 入口和 GB visual 页面变更所需的运行时 release 绑定。完整定义见 [SDK 边界](../../docs/sdk-architecture.md) 与 [IAM 构建包](../iam/README.md)。
16
16
 
17
17
  ```sh
18
18
  npm install --save-exact @tinkerlandai/longplay-sdk@latest
@@ -20,9 +20,9 @@ npm install --save-exact @tinkerlandai/longplay-sdk@latest
20
20
 
21
21
  首次安装解析最新稳定版,--save-exact 将结果固定在 package.json。提交锁文件,后续构建使用 npm ci;历史安装或回滚请沿用[发布记录](../../docs/sdk-releases.md)中的原包名和精确版本。Longplay 新包名需要单独发布,源码修改不代表已经发布。
22
22
 
23
- IAM Funnel 入口的可靠触发修复需要 SDK 0.10.6 或更新版本。可执行 `npm install --save-exact @tinkerlandai/longplay-sdk@0.10.5` 固定安装此版本;可变标签的实际指向见[发布记录](../../docs/sdk-releases.md)。
23
+ IAM Funnel 入口及首批可靠性修复需要 SDK 0.10.5 或更新版本。可执行 `npm install --save-exact @tinkerlandai/longplay-sdk@0.10.5` 固定安装此版本;可变标签的实际指向见[发布记录](../../docs/sdk-releases.md)。
24
24
 
25
- SDK 0.10.6 要求 HTTP 协议 0.10。服务端须使用同一当前协议,不提供旧协议兼容;发布包不会部署服务端。实际发布、标签与环境验收范围见 [SDK 发布总账](../../docs/sdk-releases.md) 和 [开发状态](../../docs/development-status.md)。
25
+ SDK 0.10.7 要求 HTTP 协议 0.10。服务端须使用同一当前协议,不提供旧协议兼容;发布包不会部署服务端。实际发布、标签与环境验收范围见 [SDK 发布总账](../../docs/sdk-releases.md) 和 [开发状态](../../docs/development-status.md)。
26
26
 
27
27
  数据/会话层负责公开 JSON、完整性校验和鉴权操作;展示宿主将会话接口接入打包的屏幕渲染器,渲染器消费已提供的数据并返回动作意图。客户端按需加载展示;`/server` 入口使用商户后端的受限 Server Key,不加载屏幕展示。SDK 本地检查不替代运行时授权或付款核实。后台 Preview 为同一个展示宿主提供模拟会话和数据。
28
28
 
@@ -303,9 +303,9 @@ npm 发布不部署 Web 服务、不应用数据库迁移,也不发布 Swift
303
303
 
304
304
  ## Web IAM 入口与 Funnel 页面实验
305
305
 
306
- `createIamFunnelEntries({scope, environmentId, baseUrl, appManifestRelease, session: longplay.session, container})` 安装一次后,通过 `start()` 启动监听,即可在 IAM 页面地图配置现有 Funnel Entry 节点的「进入屏幕」和「按钮/链接点击」入口。配置保存到 Funnel 草稿,随 Funnel 一起发布、暂停。`appManifestRelease` 必须来自当前构建的 IAM release descriptor。原页面点击处理继续执行;仅唯一、可验证的页面和元素能够触发。自动入口每次 pathname 访问尝试一次,查询参数、hash 和重新渲染不制造新访问。
306
+ `createIamFunnelEntries({scope, environmentId, baseUrl, appManifestRelease, session: longplay.session, container})` 安装一次后,通过 `start()` 启动监听,即可在 IAM 页面地图配置现有 Funnel Entry 节点的「进入屏幕」和「按钮/链接点击」入口。配置保存到 Funnel 草稿,随 Funnel 一起发布、暂停。`appManifestRelease` 必须来自当前构建的 IAM release descriptor。描述文件的请求头和正文读取共用两秒超时,fetch 忽略取消时也会释放等待。原页面点击处理继续执行;点击的原节点本身必须仍是唯一活动目标,具有相同选择器的替代节点不能证明旧点击有效。自动入口每次 pathname 访问尝试一次,查询参数、hash 和重新渲染不制造新访问。
307
307
 
308
- 服务端选择 Funnel,验证发布状态,并按原 Customer/Funnel 检查进行中的 Run 和自动入口冷却时间。未知响应通过 `retry()` 复用内存中的原请求;入口宿主不提供刷新页面后的恢复。Run 被 Console 终止或过期后,无论读取到 `closed` 状态还是后续命令被 `FORBIDDEN` 拒绝,入口宿主都会移除界面并上报 `run_ended`,之后的入口可以重新启动。卸载时调用 `destroy()`。IAM 不提供 Customer 凭据或业务权限。
308
+ 服务端选择 Funnel,验证发布状态,并按原 Customer/Funnel 检查进行中的 Run 和自动入口冷却时间。未知响应或 Run 首次读取的暂时失败通过 `retry()` 复用内存中的原请求;入口宿主不提供刷新页面后的恢复。已接受 Run 在首次读取或离开页面后的关闭请求中被撤销凭据拒绝时,会释放入口等待。Run 被 Console 终止或过期后,无论读取到 `closed` 状态还是后续命令被 `FORBIDDEN` 拒绝,入口宿主都会移除界面并上报 `run_ended`,之后的入口可以重新启动。卸载时调用 `destroy()`。IAM 不提供 Customer 凭据或业务权限。
309
309
 
310
310
  Split 开启 `applyPageExperiment` 后,页面直接使用该 Run 已接受的实验变体,不重新分桶。标准入口宿主自动向 `showFunnelRun` 传入 release;手动宿主传入 `appManifestRelease`,或使用 `createFunnelPageExperiments({client, appManifestRelease})`。停止、完成和销毁会清理效果,实际应用沿用原 receipt 的 GB used 上报。同一实验的独立 visual consumer 在 Funnel 持有分组期间让出控制。这些 Web 源码能力需要配套 GOP 合同和数据库迁移,安装 SDK 不等于运行时已发布。
311
311
 
@@ -1 +1 @@
1
- var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.6",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var i="https://api.longplayai.com";export{s as a,i as b};
1
+ var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.7",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var i="https://api.longplayai.com";export{s as a,i as b};
@@ -1 +1 @@
1
- import{a as u,b as Y,l as W,o as $}from"./chunk-HV4THS52.js";import{N as Q,Qa as K,a as J,b as H,c as z,d as U,e as B,f as G,j,na as i,pa as L}from"./chunk-WCVK4OMS.js";import{qa as a}from"./chunk-ACF2FBUB.js";import{a as M}from"./chunk-G56XGVMS.js";var x=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new a("INVALID_STATE","Installation sequence exhausted");return t+1},me=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function V(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new a("INVALID_STATE","Installation journal is invalid");return e({...n})})}function X(t,e,n){let r=null,d=0,p=0,c=0,m=Promise.resolve();if(t&&(!n||M.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new a("SCOPE_MISMATCH","Push installation belongs to another scope");let A=()=>{if(!t)throw new a("NOT_CONFIGURED","Configure this client's native Push host first");return t},h=o=>{if(o!==d)throw new a("IDENTITY_CHANGED","Identity changed during Push operation")};async function T(o){let s=A();if(!s.sha256&&!globalThis.crypto?.subtle)throw new a("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let l=s.sha256?await s.sha256(Uint8Array.from(o,f=>f.charCodeAt(0))):await me(o);if(!/^[a-f0-9]{64}$/.test(l))throw new a("INVALID_STATE","Push credential digest is invalid");return l}function C(o){let s=B.parse(o);if(s.installationId.toLowerCase()!==A().installationId.toLowerCase())throw new a("INVALID_RESPONSE","Push response belongs to another installation");return s}async function R(o,s){let l=A(),f={installationId:l.installationId,publicKey:l.publicKey,issuedAt:new Date().toISOString(),...s},g=await l.sign(G(o,l.scope,f));return{...f,signature:g}}let k=(o,s,l)=>e.requestWithCredential?e.requestWithCredential(o,s,l):e.request(o,s);async function S(){let o=A(),s=d,l=r?await(e.session?.access()??r):null,f=V(o,y=>y),g;if(f.detachSeq!==null){let y=f.detachSeq,b=J.parse(await R("detach",{sequence:y,platform:o.platform}));try{let w=await e.request("push/installations/detach",{...o.scope,...b},"POST",{installationDetach:!0});if(!w||typeof w!="object"||!("installation"in w))throw new a("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=C(w.installation);if(_.bound||_.identitySeq!==y)throw new a("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(w){if(w instanceof a&&w.status===404)g=w;else if(!(w instanceof a)||w.status!==412)throw w}g||V(o,w=>({...w,detachSeq:w.detachSeq===y?null:w.detachSeq}))}if(h(s),!l){if(g)throw g;return null}let E=i.bindPushInstallation,N=E.request.parse(await R("bind",{sequence:c,platform:o.platform,credentialDigest:await T(l)}));h(s);let D=E.response.parse(await k(E.path,N,l));h(s);let v=C(D.installation);if(!v.bound||v.identitySeq!==c)throw new a("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return g&&f.detachSeq!==null&&c>f.detachSeq&&V(o,y=>({...y,detachSeq:y.detachSeq===f.detachSeq?null:y.detachSeq})),v}async function P(){A();let o=d,s=r?await(e.session?.access()??r):null;if(!s)throw new a("NOT_IDENTIFIED","Identify before reading this installation");let l=i.readPushInstallation,f=l.request.parse(await R("read",{credentialDigest:await T(s)}));h(o);let g=l.response.parse(await k(l.path,f,s));return h(o),C(g.installation)}function O(o=S){let s=m.catch(()=>{}).then(o);return m=s,s.catch(l=>{try{t?.onError?.(l instanceof Error?l:new Error("Push synchronization failed"))}catch{}}),s}async function q(o,s,l){let f=A(),g=s.identity,E=s.observation,N=r?await(e.session?.access()??r):null;if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");if(!N)throw new a("NOT_IDENTIFIED","Identify before recovering a Push address");if(!o.connectionId||!o.kind||!o.token||!["granted","provisional"].includes(o.permission))throw new a("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await O(async()=>{if(h(g),await S(),h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let D=V(f,_=>l?_:{..._,addressSeq:x(_.addressSeq)}),y=await R(l?"recovery_confirm":"recovery_request",{...o,sequence:D.addressSeq,credentialDigest:await T(N),...l?{challenge:l}:{}}),b=l?z.parse(y):H.parse(y);if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let w=await k(`push/installations/recovery/${l?"confirm":"request"}`,b,N);if(h(g),E!==p||V(f,_=>_).addressSeq!==D.addressSeq)throw new a("INVALID_STATE","Push observation changed during recovery");if(l){let _=i.updatePushAddress.response.parse(w),F=C(_.installation);if(!F.bound||F.identitySeq!==c||F.addressSeq!==D.addressSeq||F.connectionId!==o.connectionId||F.addressStatus!=="active")throw new a("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return F}if(!w||typeof w!="object"||!("recovery"in w))throw new a("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return U.parse(w.recovery)})}return{recoveryObserver(){A();let o={identity:d,observation:++p};return{async request(s){return U.parse(await q(s,o))},async confirm(s,l){return B.parse(await q(l,o,s))}}},identify(o){if(!t)return;c=V(t,l=>({...l,identitySeq:x(l.identitySeq)})).identitySeq,r=o,d++,p++},reset(){if(t)try{V(t,o=>{let s=x(o.identitySeq);return{...o,identitySeq:s,detachSeq:s}})}finally{r=null,d++,p++}},start(){t&&O()},async sync(){return await O()},read:P,async recover(){let o=A(),s=d,l=c;return p++,await O(async()=>{h(s);let f=await P();return h(s),c=V(o,E=>{if(E.identitySeq!==l)throw new a("IDENTITY_CHANGED","A newer installation intent exists");return{...E,identitySeq:x(Math.max(E.identitySeq,f.identitySeq)),addressSeq:Math.max(E.addressSeq,f.addressSeq)}}).identitySeq,await S()})},tokenObserver(){A();let o=++p,s=d;return async l=>{if(o!==p||s!==d)return null;let f=A(),g=r?await(e.session?.access()??r):null;if(!g)throw new a("NOT_IDENTIFIED","Identify before registering a Push token");if(await O(),h(s),o!==p)return null;let E=V(f,y=>({...y,addressSeq:x(y.addressSeq)})),N=i.updatePushAddress,D=N.request.parse(await R("address",{...l,sequence:E.addressSeq,credentialDigest:await T(g)}));if(h(s),o!==p)return null;let v=N.response.parse(await k(N.path,D,g));return h(s),C(v.installation)}}}}function Z(t,e){return{messaging:{async preference(n){let r=i.readMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse(n))).preference}},push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){let n=i.readMessagingPreference;return n.response.parse(await t(n.path,{channel:"push"})).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}function ee(t,e,n={}){let r=!!t.session.peek(),d=new Set,p=c=>{for(let m of d)try{m(c)}catch{}};return t.session.subscribeIdentity(()=>{r=!!t.session.peek(),p(r),n.afterChange?.()},()=>{r=!1,e()}),{isIdentified:()=>r,methods:{subscribeIdentity(c){return d.add(c),()=>{d.delete(c)}},identify(c){let m=typeof c=="string"?c:c.accessToken;if(!j.test(m))throw new a("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(m),t.identify(c)},reset(){try{n.beforeReset?.()}finally{t.reset()}}}}}function I(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new a("INVALID_REQUEST","Customer requests use the verified session identity")}function te(t){return{async checkEntitlement(e){I(e);let n=i.checkEntitlement;return u(t,n,e)},async readHoldings(e={}){let n=i.readHoldings;return u(t,{...n,request:n.request.omit({customerId:!0})},e)}}}function ne(t){return{async readLedger(e){let n=i.readLedger;return u(t,n,{query:e})},async readCreditStatement(e){I(e);let n=i.readCreditStatement;return u(t,n,e)},async quoteBalance(e){I(e);let n=i.quoteBalance;return u(t,n,{command:e})}}}function re(t){return{async setupPayment(e){I(e);let n=i.setupPayment;return u(t,n,e)},async readPaymentSetup(e){I(e);let n=i.readPaymentSetup;return u(t,n,e)},async readBillingInvoice(e){I(e);let n=i.readBillingInvoice;return u(t,n,e)},async readBillingControls(e={}){I(e);let n=i.readBillingControls;return u(t,n,e)},async prepareBillingAuthorization(e){I(e);let n=i.prepareBillingAuthorization;return u(t,n,e)},async confirmBillingAuthorization(e){I(e);let n=i.confirmBillingAuthorization;return u(t,n,e)},async setBillingCoupons(e){I(e);let n=i.setBillingCoupons;return u(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){I(e);let n=i.revokeBillingAuthorization;return u(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){I(e);let n=i.listBillingInvoices;return u(t,n,e)},async confirmBillingAdjustment(e){I(e);let n=i.confirmBillingAdjustment;return u(t,n,e)}}}function ie(t){return{async previewUpdate(e){I(e);let n=i.previewUpdate;return u(t,n,e)},async update(e){I(e);let n=i.update;return u(t,n,e)},async readSubscriptionUpdate(e){I(e);let n=i.readSubscriptionUpdate;return u(t,n,e)},async restoreNativePurchase(e){I(e);let n=i.restoreNativePurchase;return u(t,n,e)},async previewAttach(e){I(e);let n=i.previewAttach;return u(t,n,e)},async attach(e){I(e);let n=i.attach;return u(t,n,e)},async readSubscriptionOperation(e){I(e);let n=i.readSubscriptionOperation;return u(t,n,e)}}}function oe(t){return{async redeemReward(e){return I(e),(await u(t,i.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return I(e),(await u(t,i.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return I(e),(await u(t,i.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await u(t,i.listOffers,{},{response:"Invalid offers response"})).offers}}}function se(t){return{...te(t),...ne(t),...re(t),...ie(t),...oe(t)}}function ae(t){return{async resolveContent(e){I(e);let n=i.resolveContent;return u(t,n,e)},async resolvePaywall(e){I(e);let n=i.resolvePaywall;return u(t,n,e)},async resolveOffering(e){I(e);let n=i.resolveOffering;return u(t,n,e)}}}var ce=t=>new TextEncoder().encode(JSON.stringify(t)).length,ue=16384;function de(t,e){let n=0,r,d=S=>{r={config:structuredClone(S),until:Date.now()+3e4}},p=[],c=null,m;function A(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}function h(){m||!p.length||(m=setTimeout(()=>{m=void 0,C().catch(()=>{}).finally(h)},5e3),typeof m=="object"&&"unref"in m&&m.unref())}function T(S,P={},O={}){if(A(),r&&Date.now()<r.until&&!Q(r.config,S))return;k();let q=i.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:S,properties:P,...O}]}).events[0];if(ce({events:[q]})>ue)throw new a("INVALID_REQUEST","Event exceeds the delivery size limit");if(p.length>=500)throw new a("EVENT_QUEUE_FULL","Flush pending events before tracking more");p.push(structuredClone(q)),h()}async function C(S=!1){if(A(),c)return c;let P=n,O=(async()=>{let q={inserted:0,duplicates:0,rejected:0,skipped:0},o=p.length;for(;o&&P===n;){let s=[];for(let g of p.slice(0,Math.min(o,100))){if(s.length&&ce({events:[...s,g]})>ue)break;s.push(g)}let l=i.trackEvents,f=await u(t,l,{events:s},void 0,{keepalive:S});if(P!==n)throw new a("IDENTITY_CHANGED","Event identity changed during delivery");if(f.inserted+f.duplicates+f.rejected+f.skipped!==s.length)throw new a("INVALID_RESPONSE","Incomplete event acknowledgement");d(f.analyticsConfig),p.splice(0,s.length),o-=s.length,q.inserted+=f.inserted,q.duplicates+=f.duplicates,q.rejected+=f.rejected,q.skipped+=f.skipped}return q})();c=O;try{return await O}finally{c===O&&(c=null)}}let R;function k(){if(R||typeof document>"u")return;let S=()=>{document.visibilityState==="hidden"&&e()&&p.length&&C(!0).catch(()=>{})};document.addEventListener("visibilitychange",S),R=()=>document.removeEventListener("visibilitychange",S)}return{rememberConfiguration:d,track(S,P,O={}){return k(),T(S,P,O)},flush:C,reset(){n++,r=void 0,clearTimeout(m),m=void 0,p=[],c=null},detachVisibility(){R?.(),R=void 0}}}function pe(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function ye(t){let e=pe(t),{merchandiseId:n,merchandise:r,...d}=t;return{...d,...e?{merchandise:e}:{}}}function le(t,e,n,r,d){if(d&&r&&(d.scope.projectId!==r.projectId||d.scope.environment!==r.environment))throw new a("SCOPE_MISMATCH","Configuration belongs to another App/environment");let p=0,c=new Set;function m(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}async function A(h={}){d||m();let T=p,C=!1,R=async()=>{if(C||T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let v=i.getFeatures,y=d?{scope:{projectId:d.scope.projectId,environment:d.scope.environment},payload:await d.features()}:await u(t,v,{});if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");if(r&&(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment))throw new a("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(y.payload.analyticsConfig),y},k=await R(),S=!0,P,O=v=>{try{h.onError?.(v)}catch{}},q=(v,y,b)=>{try{let w=pe(b);n.track(v,y,w?{merchandise:w}:{})}catch(w){O(w)}},o=Y({assertUsable:d?.assertFeatures,scope:k.scope,attributes:h.attributes,onError:h.onError,load:async()=>S?(S=!1,k.payload):(await R()).payload,evaluateRemote:async v=>{if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let y=i.evaluateFeatures,b=await u(t,y,{...v,attributes:ye(v.attributes)});if(b.scope.projectId!==k.scope.projectId||b.scope.environment!==k.scope.environment)throw new a("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:b.generation,evaluatedAt:b.evaluatedAt,expiresAt:b.expiresAt,features:b.features,...b.merchandiseContext?{merchandiseContext:b.merchandiseContext}:{}}},onExperimentViewed:(v,y,b)=>q("Experiment Viewed",{experimentId:v.key,variationId:y.key},b),onFeatureUsage:(v,y,b)=>q("Feature Evaluated",{feature:v,value:y.value,source:y.source,ruleId:y.ruleId,...y.experimentResult?{variationId:y.experimentResult.key}:{}},b)}),s=o.refresh;function l(){clearTimeout(P),!d&&(C||T!==p||!o.expiresAt||(P=setTimeout(()=>{f().catch(O)},Math.min(2147483647,Math.max(1e3,Date.parse(o.expiresAt)-Date.now()))),typeof P=="object"&&"unref"in P&&P.unref()))}async function f(){try{return await s()}finally{l()}}let g=()=>{C||f().catch(O)},E=o.subscribe(l),N=d?.subscribe(()=>{!C&&d.fresh&&f().catch(O)});function D(){C||(C=!0,clearTimeout(P),typeof window<"u"&&window.removeEventListener("focus",g),E(),N?.(),o.reset(),c.delete(D))}c.add(D);try{await o.init(),(h.attributes?.merchandise||h.attributes?.merchandiseId)&&await o.refreshRemote()}catch(v){throw D(),v}return l(),!d&&typeof window<"u"&&window.addEventListener("focus",g),Object.assign(o,{refresh:f,destroy:D})}return{features:A,reset(h){p++,h();for(let T of c)T()}}}import{z as Ie}from"zod";function fe(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=Ie.object({funnelId:L.shape.id,funnelVersionId:L.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new a("INVALID_REQUEST","A valid Funnel source is required");let d=Object.freeze(r.data);function p(c){if("customerId"in c)throw new a("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in c&&c.funnelId!==void 0&&c.funnelId!==d.funnelId||"funnelVersionId"in c&&c.funnelVersionId!==void 0&&c.funnelVersionId!==d.funnelVersionId)throw new a("SCOPE_MISMATCH","The original Funnel source cannot change");return{...c,...d}}return{async claimCoupon(c,m=crypto.randomUUID()){let A=i.grantOffer,h=await u(t,A,p({couponId:c,requestId:m}));return{offer:h.offer,reason:h.reason}},async resolveOffering(c){let m=i.resolveOffering;return u(t,m,p(c))},async resolvePaywall(c){let m=i.resolvePaywall;return u(t,m,p(c))},async previewAttach(c){let m=i.previewAttach;return u(t,m,p(c))}}}function Pt(t){return he(t)}function he(t){let e=K(t),n=e.request,r=X(t.push,e,t.scope??t.configuration?.scope),d=ee(e,()=>{c.reset(p.reset),p.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),p=de(n,d.isIdentified),c=le(n,d.isIdentified,p,t.scope,t.configuration);return{session:e.session,...Z(n,r),...se(n),...ae(n),forFunnel(m){return fe(n,m)},async features(m={}){return c.features(m)},track(m,A,h={}){return p.track(m,A,h)},flush(){return p.flush()},...d.methods}}function Nt(t){if(!j.test(t.customerToken))throw new a("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new a("INVALID_REQUEST","An explicit App and environment scope is required");let e=$({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),d=W({...t,runToken:r.runToken});d.identify(t.customerToken);let p=r.run.instruction?.type==="evaluate_segment"?await d.get():r;return{...r,...p,controller:d}}}}export{Pt as a,he as b,Nt as c};
1
+ import{a as u,b as Y,l as W,o as $}from"./chunk-Y3AGPHWF.js";import{N as Q,Qa as K,a as J,b as H,c as z,d as U,e as B,f as G,j,na as i,pa as L}from"./chunk-IAOOTBJV.js";import{qa as a}from"./chunk-ACF2FBUB.js";import{a as M}from"./chunk-G56XGVMS.js";var x=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new a("INVALID_STATE","Installation sequence exhausted");return t+1},me=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function V(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new a("INVALID_STATE","Installation journal is invalid");return e({...n})})}function X(t,e,n){let r=null,d=0,p=0,c=0,m=Promise.resolve();if(t&&(!n||M.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new a("SCOPE_MISMATCH","Push installation belongs to another scope");let A=()=>{if(!t)throw new a("NOT_CONFIGURED","Configure this client's native Push host first");return t},h=o=>{if(o!==d)throw new a("IDENTITY_CHANGED","Identity changed during Push operation")};async function T(o){let s=A();if(!s.sha256&&!globalThis.crypto?.subtle)throw new a("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let l=s.sha256?await s.sha256(Uint8Array.from(o,f=>f.charCodeAt(0))):await me(o);if(!/^[a-f0-9]{64}$/.test(l))throw new a("INVALID_STATE","Push credential digest is invalid");return l}function C(o){let s=B.parse(o);if(s.installationId.toLowerCase()!==A().installationId.toLowerCase())throw new a("INVALID_RESPONSE","Push response belongs to another installation");return s}async function R(o,s){let l=A(),f={installationId:l.installationId,publicKey:l.publicKey,issuedAt:new Date().toISOString(),...s},g=await l.sign(G(o,l.scope,f));return{...f,signature:g}}let k=(o,s,l)=>e.requestWithCredential?e.requestWithCredential(o,s,l):e.request(o,s);async function S(){let o=A(),s=d,l=r?await(e.session?.access()??r):null,f=V(o,y=>y),g;if(f.detachSeq!==null){let y=f.detachSeq,b=J.parse(await R("detach",{sequence:y,platform:o.platform}));try{let w=await e.request("push/installations/detach",{...o.scope,...b},"POST",{installationDetach:!0});if(!w||typeof w!="object"||!("installation"in w))throw new a("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=C(w.installation);if(_.bound||_.identitySeq!==y)throw new a("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(w){if(w instanceof a&&w.status===404)g=w;else if(!(w instanceof a)||w.status!==412)throw w}g||V(o,w=>({...w,detachSeq:w.detachSeq===y?null:w.detachSeq}))}if(h(s),!l){if(g)throw g;return null}let E=i.bindPushInstallation,N=E.request.parse(await R("bind",{sequence:c,platform:o.platform,credentialDigest:await T(l)}));h(s);let D=E.response.parse(await k(E.path,N,l));h(s);let v=C(D.installation);if(!v.bound||v.identitySeq!==c)throw new a("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return g&&f.detachSeq!==null&&c>f.detachSeq&&V(o,y=>({...y,detachSeq:y.detachSeq===f.detachSeq?null:y.detachSeq})),v}async function P(){A();let o=d,s=r?await(e.session?.access()??r):null;if(!s)throw new a("NOT_IDENTIFIED","Identify before reading this installation");let l=i.readPushInstallation,f=l.request.parse(await R("read",{credentialDigest:await T(s)}));h(o);let g=l.response.parse(await k(l.path,f,s));return h(o),C(g.installation)}function O(o=S){let s=m.catch(()=>{}).then(o);return m=s,s.catch(l=>{try{t?.onError?.(l instanceof Error?l:new Error("Push synchronization failed"))}catch{}}),s}async function q(o,s,l){let f=A(),g=s.identity,E=s.observation,N=r?await(e.session?.access()??r):null;if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");if(!N)throw new a("NOT_IDENTIFIED","Identify before recovering a Push address");if(!o.connectionId||!o.kind||!o.token||!["granted","provisional"].includes(o.permission))throw new a("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await O(async()=>{if(h(g),await S(),h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let D=V(f,_=>l?_:{..._,addressSeq:x(_.addressSeq)}),y=await R(l?"recovery_confirm":"recovery_request",{...o,sequence:D.addressSeq,credentialDigest:await T(N),...l?{challenge:l}:{}}),b=l?z.parse(y):H.parse(y);if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let w=await k(`push/installations/recovery/${l?"confirm":"request"}`,b,N);if(h(g),E!==p||V(f,_=>_).addressSeq!==D.addressSeq)throw new a("INVALID_STATE","Push observation changed during recovery");if(l){let _=i.updatePushAddress.response.parse(w),F=C(_.installation);if(!F.bound||F.identitySeq!==c||F.addressSeq!==D.addressSeq||F.connectionId!==o.connectionId||F.addressStatus!=="active")throw new a("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return F}if(!w||typeof w!="object"||!("recovery"in w))throw new a("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return U.parse(w.recovery)})}return{recoveryObserver(){A();let o={identity:d,observation:++p};return{async request(s){return U.parse(await q(s,o))},async confirm(s,l){return B.parse(await q(l,o,s))}}},identify(o){if(!t)return;c=V(t,l=>({...l,identitySeq:x(l.identitySeq)})).identitySeq,r=o,d++,p++},reset(){if(t)try{V(t,o=>{let s=x(o.identitySeq);return{...o,identitySeq:s,detachSeq:s}})}finally{r=null,d++,p++}},start(){t&&O()},async sync(){return await O()},read:P,async recover(){let o=A(),s=d,l=c;return p++,await O(async()=>{h(s);let f=await P();return h(s),c=V(o,E=>{if(E.identitySeq!==l)throw new a("IDENTITY_CHANGED","A newer installation intent exists");return{...E,identitySeq:x(Math.max(E.identitySeq,f.identitySeq)),addressSeq:Math.max(E.addressSeq,f.addressSeq)}}).identitySeq,await S()})},tokenObserver(){A();let o=++p,s=d;return async l=>{if(o!==p||s!==d)return null;let f=A(),g=r?await(e.session?.access()??r):null;if(!g)throw new a("NOT_IDENTIFIED","Identify before registering a Push token");if(await O(),h(s),o!==p)return null;let E=V(f,y=>({...y,addressSeq:x(y.addressSeq)})),N=i.updatePushAddress,D=N.request.parse(await R("address",{...l,sequence:E.addressSeq,credentialDigest:await T(g)}));if(h(s),o!==p)return null;let v=N.response.parse(await k(N.path,D,g));return h(s),C(v.installation)}}}}function Z(t,e){return{messaging:{async preference(n){let r=i.readMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse(n))).preference}},push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){let n=i.readMessagingPreference;return n.response.parse(await t(n.path,{channel:"push"})).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}function ee(t,e,n={}){let r=!!t.session.peek(),d=new Set,p=c=>{for(let m of d)try{m(c)}catch{}};return t.session.subscribeIdentity(()=>{r=!!t.session.peek(),p(r),n.afterChange?.()},()=>{r=!1,e()}),{isIdentified:()=>r,methods:{subscribeIdentity(c){return d.add(c),()=>{d.delete(c)}},identify(c){let m=typeof c=="string"?c:c.accessToken;if(!j.test(m))throw new a("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(m),t.identify(c)},reset(){try{n.beforeReset?.()}finally{t.reset()}}}}}function I(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new a("INVALID_REQUEST","Customer requests use the verified session identity")}function te(t){return{async checkEntitlement(e){I(e);let n=i.checkEntitlement;return u(t,n,e)},async readHoldings(e={}){let n=i.readHoldings;return u(t,{...n,request:n.request.omit({customerId:!0})},e)}}}function ne(t){return{async readLedger(e){let n=i.readLedger;return u(t,n,{query:e})},async readCreditStatement(e){I(e);let n=i.readCreditStatement;return u(t,n,e)},async quoteBalance(e){I(e);let n=i.quoteBalance;return u(t,n,{command:e})}}}function re(t){return{async setupPayment(e){I(e);let n=i.setupPayment;return u(t,n,e)},async readPaymentSetup(e){I(e);let n=i.readPaymentSetup;return u(t,n,e)},async readBillingInvoice(e){I(e);let n=i.readBillingInvoice;return u(t,n,e)},async readBillingControls(e={}){I(e);let n=i.readBillingControls;return u(t,n,e)},async prepareBillingAuthorization(e){I(e);let n=i.prepareBillingAuthorization;return u(t,n,e)},async confirmBillingAuthorization(e){I(e);let n=i.confirmBillingAuthorization;return u(t,n,e)},async setBillingCoupons(e){I(e);let n=i.setBillingCoupons;return u(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){I(e);let n=i.revokeBillingAuthorization;return u(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){I(e);let n=i.listBillingInvoices;return u(t,n,e)},async confirmBillingAdjustment(e){I(e);let n=i.confirmBillingAdjustment;return u(t,n,e)}}}function ie(t){return{async previewUpdate(e){I(e);let n=i.previewUpdate;return u(t,n,e)},async update(e){I(e);let n=i.update;return u(t,n,e)},async readSubscriptionUpdate(e){I(e);let n=i.readSubscriptionUpdate;return u(t,n,e)},async restoreNativePurchase(e){I(e);let n=i.restoreNativePurchase;return u(t,n,e)},async previewAttach(e){I(e);let n=i.previewAttach;return u(t,n,e)},async attach(e){I(e);let n=i.attach;return u(t,n,e)},async readSubscriptionOperation(e){I(e);let n=i.readSubscriptionOperation;return u(t,n,e)}}}function oe(t){return{async redeemReward(e){return I(e),(await u(t,i.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return I(e),(await u(t,i.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return I(e),(await u(t,i.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await u(t,i.listOffers,{},{response:"Invalid offers response"})).offers}}}function se(t){return{...te(t),...ne(t),...re(t),...ie(t),...oe(t)}}function ae(t){return{async resolveContent(e){I(e);let n=i.resolveContent;return u(t,n,e)},async resolvePaywall(e){I(e);let n=i.resolvePaywall;return u(t,n,e)},async resolveOffering(e){I(e);let n=i.resolveOffering;return u(t,n,e)}}}var ce=t=>new TextEncoder().encode(JSON.stringify(t)).length,ue=16384;function de(t,e){let n=0,r,d=S=>{r={config:structuredClone(S),until:Date.now()+3e4}},p=[],c=null,m;function A(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}function h(){m||!p.length||(m=setTimeout(()=>{m=void 0,C().catch(()=>{}).finally(h)},5e3),typeof m=="object"&&"unref"in m&&m.unref())}function T(S,P={},O={}){if(A(),r&&Date.now()<r.until&&!Q(r.config,S))return;k();let q=i.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:S,properties:P,...O}]}).events[0];if(ce({events:[q]})>ue)throw new a("INVALID_REQUEST","Event exceeds the delivery size limit");if(p.length>=500)throw new a("EVENT_QUEUE_FULL","Flush pending events before tracking more");p.push(structuredClone(q)),h()}async function C(S=!1){if(A(),c)return c;let P=n,O=(async()=>{let q={inserted:0,duplicates:0,rejected:0,skipped:0},o=p.length;for(;o&&P===n;){let s=[];for(let g of p.slice(0,Math.min(o,100))){if(s.length&&ce({events:[...s,g]})>ue)break;s.push(g)}let l=i.trackEvents,f=await u(t,l,{events:s},void 0,{keepalive:S});if(P!==n)throw new a("IDENTITY_CHANGED","Event identity changed during delivery");if(f.inserted+f.duplicates+f.rejected+f.skipped!==s.length)throw new a("INVALID_RESPONSE","Incomplete event acknowledgement");d(f.analyticsConfig),p.splice(0,s.length),o-=s.length,q.inserted+=f.inserted,q.duplicates+=f.duplicates,q.rejected+=f.rejected,q.skipped+=f.skipped}return q})();c=O;try{return await O}finally{c===O&&(c=null)}}let R;function k(){if(R||typeof document>"u")return;let S=()=>{document.visibilityState==="hidden"&&e()&&p.length&&C(!0).catch(()=>{})};document.addEventListener("visibilitychange",S),R=()=>document.removeEventListener("visibilitychange",S)}return{rememberConfiguration:d,track(S,P,O={}){return k(),T(S,P,O)},flush:C,reset(){n++,r=void 0,clearTimeout(m),m=void 0,p=[],c=null},detachVisibility(){R?.(),R=void 0}}}function pe(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function ye(t){let e=pe(t),{merchandiseId:n,merchandise:r,...d}=t;return{...d,...e?{merchandise:e}:{}}}function le(t,e,n,r,d){if(d&&r&&(d.scope.projectId!==r.projectId||d.scope.environment!==r.environment))throw new a("SCOPE_MISMATCH","Configuration belongs to another App/environment");let p=0,c=new Set;function m(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}async function A(h={}){d||m();let T=p,C=!1,R=async()=>{if(C||T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let v=i.getFeatures,y=d?{scope:{projectId:d.scope.projectId,environment:d.scope.environment},payload:await d.features()}:await u(t,v,{});if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");if(r&&(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment))throw new a("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(y.payload.analyticsConfig),y},k=await R(),S=!0,P,O=v=>{try{h.onError?.(v)}catch{}},q=(v,y,b)=>{try{let w=pe(b);n.track(v,y,w?{merchandise:w}:{})}catch(w){O(w)}},o=Y({assertUsable:d?.assertFeatures,scope:k.scope,attributes:h.attributes,onError:h.onError,load:async()=>S?(S=!1,k.payload):(await R()).payload,evaluateRemote:async v=>{if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let y=i.evaluateFeatures,b=await u(t,y,{...v,attributes:ye(v.attributes)});if(b.scope.projectId!==k.scope.projectId||b.scope.environment!==k.scope.environment)throw new a("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:b.generation,evaluatedAt:b.evaluatedAt,expiresAt:b.expiresAt,features:b.features,...b.merchandiseContext?{merchandiseContext:b.merchandiseContext}:{}}},onExperimentViewed:(v,y,b)=>q("Experiment Viewed",{experimentId:v.key,variationId:y.key},b),onFeatureUsage:(v,y,b)=>q("Feature Evaluated",{feature:v,value:y.value,source:y.source,ruleId:y.ruleId,...y.experimentResult?{variationId:y.experimentResult.key}:{}},b)}),s=o.refresh;function l(){clearTimeout(P),!d&&(C||T!==p||!o.expiresAt||(P=setTimeout(()=>{f().catch(O)},Math.min(2147483647,Math.max(1e3,Date.parse(o.expiresAt)-Date.now()))),typeof P=="object"&&"unref"in P&&P.unref()))}async function f(){try{return await s()}finally{l()}}let g=()=>{C||f().catch(O)},E=o.subscribe(l),N=d?.subscribe(()=>{!C&&d.fresh&&f().catch(O)});function D(){C||(C=!0,clearTimeout(P),typeof window<"u"&&window.removeEventListener("focus",g),E(),N?.(),o.reset(),c.delete(D))}c.add(D);try{await o.init(),(h.attributes?.merchandise||h.attributes?.merchandiseId)&&await o.refreshRemote()}catch(v){throw D(),v}return l(),!d&&typeof window<"u"&&window.addEventListener("focus",g),Object.assign(o,{refresh:f,destroy:D})}return{features:A,reset(h){p++,h();for(let T of c)T()}}}import{z as Ie}from"zod";function fe(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=Ie.object({funnelId:L.shape.id,funnelVersionId:L.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new a("INVALID_REQUEST","A valid Funnel source is required");let d=Object.freeze(r.data);function p(c){if("customerId"in c)throw new a("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in c&&c.funnelId!==void 0&&c.funnelId!==d.funnelId||"funnelVersionId"in c&&c.funnelVersionId!==void 0&&c.funnelVersionId!==d.funnelVersionId)throw new a("SCOPE_MISMATCH","The original Funnel source cannot change");return{...c,...d}}return{async claimCoupon(c,m=crypto.randomUUID()){let A=i.grantOffer,h=await u(t,A,p({couponId:c,requestId:m}));return{offer:h.offer,reason:h.reason}},async resolveOffering(c){let m=i.resolveOffering;return u(t,m,p(c))},async resolvePaywall(c){let m=i.resolvePaywall;return u(t,m,p(c))},async previewAttach(c){let m=i.previewAttach;return u(t,m,p(c))}}}function Pt(t){return he(t)}function he(t){let e=K(t),n=e.request,r=X(t.push,e,t.scope??t.configuration?.scope),d=ee(e,()=>{c.reset(p.reset),p.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),p=de(n,d.isIdentified),c=le(n,d.isIdentified,p,t.scope,t.configuration);return{session:e.session,...Z(n,r),...se(n),...ae(n),forFunnel(m){return fe(n,m)},async features(m={}){return c.features(m)},track(m,A,h={}){return p.track(m,A,h)},flush(){return p.flush()},...d.methods}}function Nt(t){if(!j.test(t.customerToken))throw new a("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new a("INVALID_REQUEST","An explicit App and environment scope is required");let e=$({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),d=W({...t,runToken:r.runToken});d.identify(t.customerToken);let p=r.run.instruction?.type==="evaluate_segment"?await d.get():r;return{...r,...p,controller:d}}}}export{Pt as a,he as b,Nt as c};
@@ -0,0 +1 @@
1
+ import{d as t}from"./chunk-Y3AGPHWF.js";import{Ga as n}from"./chunk-IAOOTBJV.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
@@ -1,2 +1,2 @@
1
- import{a as re,b as ne,c as oe}from"./chunk-CLXORAOK.js";var be=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,Y={revert:function(){}},H=new Map,Q=new Set;function we(t){return t==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[t]}}function J(t){var e=H.get(t);return e||(e={element:t,attributes:{}},H.set(t,e)),e}function j(t,e,r,n,a){var p=r(t),u={isDirty:!1,originalValue:p,virtualValue:p,mutations:[],el:t,_positionTimeout:null,observer:new MutationObserver(function(){if(!Pe&&!(e==="position"&&u._positionTimeout)){e==="position"&&(u._positionTimeout=setTimeout(function(){u._positionTimeout=null},1e3));var l=r(t);e==="position"&&l.parentNode===u.virtualValue.parentNode&&l.insertBeforeNode===u.virtualValue.insertBeforeNode||l!==u.virtualValue&&(u.originalValue=l,a(u))}}),mutationRunner:a,setValue:n,getCurrentValue:r};return e==="position"&&t.parentNode?u.observer.observe(t.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):u.observer.observe(t,we(e)),u}function G(t,e){var r=e.getCurrentValue(e.el);e.virtualValue=t,t&&typeof t!="string"?(!r||t.parentNode!==r.parentNode||t.insertBeforeNode!==r.insertBeforeNode)&&(e.isDirty=!0,ie()):t!==r&&(e.isDirty=!0,ie())}function ye(t){var e=t.originalValue;t.mutations.forEach(function(r){return e=r.mutate(e)}),G(Ce(e),t)}function Ee(t){var e=new Set(t.originalValue.split(/\s+/).filter(Boolean));t.mutations.forEach(function(r){return r.mutate(e)}),G(Array.from(e).filter(Boolean).join(" "),t)}function Me(t){var e=t.originalValue;t.mutations.forEach(function(r){return e=r.mutate(e)}),G(e,t)}function Se(t){var e=t.parentSelector,r=t.insertBeforeSelector,n=document.querySelector(e);if(!n)return null;var a=r?document.querySelector(r):null;return r&&!a?null:{parentNode:n,insertBeforeNode:a}}function Ve(t){var e=t.originalValue;t.mutations.forEach(function(r){var n=r.mutate(),a=Se(n);e=a||e}),G(e,t)}var Ae=function(e){return e.innerHTML},ke=function(e,r){return e.innerHTML=r};function ae(t){var e=J(t);return e.html||(e.html=j(t,"html",Ae,ke,ye)),e.html}var Ne=function(e){return{parentNode:e.parentElement,insertBeforeNode:e.nextElementSibling}},Te=function(e,r){r.insertBeforeNode&&!r.parentNode.contains(r.insertBeforeNode)||r.parentNode.insertBefore(e,r.insertBeforeNode)};function ue(t){var e=J(t);return e.position||(e.position=j(t,"position",Ne,Te,Ve)),e.position}var xe=function(e,r){return r?e.className=r:e.removeAttribute("class")},Re=function(e){return e.className};function le(t){var e=J(t);return e.classes||(e.classes=j(t,"class",Re,xe,Ee)),e.classes}var qe=function(e){return function(r){var n;return(n=r.getAttribute(e))!=null?n:null}},Le=function(e){return function(r,n){return n!==null?r.setAttribute(e,n):r.removeAttribute(e)}};function ce(t,e){var r=J(t);return r.attributes[e]||(r.attributes[e]=j(t,e,qe(e),Le(e),Me)),r.attributes[e]}function Ie(t,e){var r=H.get(t);if(r)if(e==="html"){var n,a;(n=r.html)==null||(a=n.observer)==null||a.disconnect(),delete r.html}else if(e==="class"){var p,u;(p=r.classes)==null||(u=p.observer)==null||u.disconnect(),delete r.classes}else if(e==="position"){var l,E;(l=r.position)==null||(E=l.observer)==null||E.disconnect(),delete r.position}else{var g,b,f;(g=r.attributes)==null||(b=g[e])==null||(f=b.observer)==null||f.disconnect(),delete r.attributes[e]}}var D;function Ce(t){return D||(D=document.createElement("div")),D.innerHTML=t,D.innerHTML}function z(t,e,r){if(r.isDirty){r.isDirty=!1;var n=r.virtualValue;r.mutations.length||Ie(t,e),r.setValue(t,n)}}function Oe(t,e){t.html&&z(e,"html",t.html),t.classes&&z(e,"class",t.classes),t.position&&z(e,"position",t.position),Object.keys(t.attributes).forEach(function(r){z(e,r,t.attributes[r])})}function ie(){H.forEach(Oe)}function Be(t,e){var r=null;t.kind==="html"?r=ae(e):t.kind==="class"?r=le(e):t.kind==="attribute"?r=ce(e,t.attribute):t.kind==="position"&&(r=ue(e)),r&&(r.mutations.push(t),r.mutationRunner(r))}function De(t,e){var r=null;if(t.kind==="html"?r=ae(e):t.kind==="class"?r=le(e):t.kind==="attribute"?r=ce(e,t.attribute):t.kind==="position"&&(r=ue(e)),!!r){var n=r.mutations.indexOf(t);n!==-1&&r.mutations.splice(n,1),r.mutationRunner(r)}}function fe(t){if(!(t.kind==="position"&&t.elements.size===1)){var e=new Set(t.elements),r=document.querySelectorAll(t.selector);r.forEach(function(n){e.has(n)||(t.elements.add(n),Be(t,n))})}}function ze(t){t.elements.forEach(function(e){return De(t,e)}),t.elements.clear(),Q.delete(t)}function se(){Q.forEach(fe)}var Pe=!1;var Z;function He(){typeof document>"u"||(Z||(Z=new MutationObserver(function(){se()})),se(),Z.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}He();function U(t){return typeof document>"u"?Y:(Q.add(t),fe(t),{revert:function(){ze(t)}})}function K(t,e){return U({kind:"html",elements:new Set,mutate:e,selector:t})}function de(t,e){return U({kind:"position",elements:new Set,mutate:e,selector:t})}function C(t,e){return U({kind:"class",elements:new Set,mutate:e,selector:t})}function P(t,e,r){return be.test(e)?e==="class"||e==="className"?C(t,function(n){var a=r(Array.from(n).join(" "));n.clear(),a&&a.split(/\s+/g).filter(Boolean).forEach(function(p){return n.add(p)})}):U({kind:"attribute",attribute:e,elements:new Set,mutate:r,selector:t}):Y}function Je(t){var e=t.selector,r=t.action,n=t.value,a=t.attribute,p=t.parentSelector,u=t.insertBeforeSelector;if(a==="html"){if(r==="append")return K(e,function(l){return l+(n??"")});if(r==="set")return K(e,function(){return n??""})}else if(a==="class"){if(r==="append")return C(e,function(l){n&&l.add(n)});if(r==="remove")return C(e,function(l){n&&l.delete(n)});if(r==="set")return C(e,function(l){l.clear(),n&&l.add(n)})}else if(a==="position"){if(r==="set"&&p)return de(e,function(){return{insertBeforeSelector:u,parentSelector:p}})}else{if(r==="append")return P(e,a,function(l){return l!==null?l+(n??""):n??""});if(r==="set")return P(e,a,function(){return n??""});if(r==="remove")return P(e,a,function(){return null})}return Y}var je={html:K,classes:C,attribute:P,position:de,declarative:Je},X=je;import Ue from"dompurify";var T=class extends Error{constructor(){super("IAM page check exceeded its work budget")}},_=new WeakMap,$=new WeakSet;function ee(t){$.add(t)}function Ge(t){let e=new Set,r=new Set,n,a=0,p=!1,u=0,l,E=()=>{e.size||a||(n?.disconnect(),l!==void 0&&cancelAnimationFrame(l),t.removeEventListener("visibilitychange",f),_.delete(t))};function g(h){if(t.hidden)return;let M=performance.now(),w=new Map,v=new Map,V=()=>{if(performance.now()-M>8)throw new T},x=o=>{V();let i=w.get(o);return i||(i=t.querySelectorAll(o),w.set(o,i)),V(),i},R=re({querySelectorAll:x},V),W=o=>{let i=o.filter(m=>!w.has(m));if(!i.length)return;let s=new Map;for(let m of i){let d=/^([a-z][a-z0-9-]*)\[(id|data-testid|data-test|data-qa|data-indiana-id)="((?:[^"\\\x00-\x1f\x7f]|\\["\\])*)"\]$/.exec(m);if(!d)throw Error("Invalid IAM render selector");let[,y,k,A]=d,I=A.replace(/\\(["\\])/g,"$1"),O=s.get(y);O||s.set(y,O=new Map);let B=O.get(k);B||O.set(k,B=new Map);let F=B.get(I);F||B.set(I,F=[]),w.set(m,F)}V();let c=t.querySelectorAll(i.join(","));if(V(),c.length>8192)throw Error("IAM render selection budget exceeded");for(let m of c){let d=s.get(m.localName.toLowerCase());if(d)for(let[y,k]of d){let A=m.getAttribute(y);A!==null&&k.get(A)?.push(m)}V()}},S={query:x,checkpoint:V,matches(o,i){let s=v.get(i);if(!s){try{let c=!1;s={match:oe(o,t,location.pathname,V,m=>(c||(W(o.selectors),c=!0),R(m)))}}catch(c){s={error:c}}v.set(i,s)}if("error"in s)throw s.error;return s.match}},N=[],q=[],L=[];for(let o of h)if(e.has(o))try{N.push({job:o,commit:o.prepare(S)})}catch(i){if(i instanceof T)throw i;q.push({job:o,error:i})}V();for(let{job:o,error:i}of q)e.has(o)&&o.fail(i);for(let{job:o,commit:i}of N)if(e.has(o))try{V(),i(s=>L.push(s))}catch(s){if(s instanceof T)throw s;o.fail(s)}for(let o of L)o()}function b(h){if(!(l!==void 0||t.hidden))try{g(h),u=0}catch(M){if(!(M instanceof T))throw M;for(let w of[...e])w.suspend();if(u++>=2){for(let w of[...e])w.fail(M);return}l=requestAnimationFrame(()=>{l=void 0,b([...e])})}}function f(){p||!e.size||t.hidden||(p=!0,queueMicrotask(()=>{p=!1,b([...e])}))}return{begin(){a++},end(){--a===0&&(r.clear(),b([...e])),E()},add(h){return n||(n=new MutationObserver(M=>{let w=v=>$.has(v)||!!(v.parentNode&&$.has(v.parentNode));M.some(v=>!w(v.target)&&!(v.type==="childList"&&[...v.addedNodes,...v.removedNodes].length>0&&[...v.addedNodes,...v.removedNodes].every(w)))&&f()}),n.observe(t.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["style","hidden","data-indiana-id","data-indiana-release","data-testid","id","name"]}),t.addEventListener("visibilitychange",f)),e.add(h),a?r.add(h):b([h]),()=>{e.delete(h),r.delete(h),E()}}}}function pe(){let t=_.get(document);return t||(t=Ge(document),_.set(document,t)),t}function me(t){return pe().add(t)}function Ye(t){let e=pe();e.begin();try{t()}finally{e.end()}}var te,he;function ve(t){return(!te||he!==window)&&(te=Ue(window),he=window),te.sanitize(t,{USE_PROFILES:{html:!0},FORBID_TAGS:["form","input","textarea","select","button","style"]})}function ge(t){let e={...t};if(!["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e.attribute)&&!/^(aria|data)-[a-z0-9_-]+$/.test(e.attribute))throw new Error("Unsupported visual attribute");document.querySelector(e.selector);for(let r of document.querySelectorAll(e.selector))if(["SCRIPT","IFRAME","OBJECT","EMBED","HTML","HEAD"].includes(r.tagName)||r.tagName==="BODY"&&e.attribute==="html")throw new Error("Protected visual target");if(e.attribute==="html"&&(e.value=ve(e.value??"")),["href","src"].includes(e.attribute)&&e.action!=="remove"){let r=new URL(e.value??"",location.href);if(!["https:","http:","mailto:","tel:"].includes(r.protocol)||e.attribute==="src"&&!["https:","http:"].includes(r.protocol))throw new Error("Unsafe visual URL")}return e.parentSelector&&document.querySelector(e.parentSelector),e.insertBeforeSelector&&document.querySelector(e.insertBeforeSelector),e}function tt(t,e={}){if(t.renderGuard&&!e.requireUniqueTargets)throw new Error("IAM render guard requires the source release fence");if(e.requireUniqueTargets)return We(t,e);let r=t.domMutations.map(ge),n=[],a=!1,p=!1,u,l=()=>{if(!a){a=!0,u?.disconnect();for(let g of n.reverse())g()}},E=()=>{a||p||(!r.length||t.css||e.allowJs&&t.js||r.some(g=>document.querySelector(g.selector)))&&(p=!0,e.onApplied?.())};try{if(t.css){let f=document.createElement("style");e.nonce&&(f.nonce=e.nonce),f.textContent=t.css,document.head.append(f),n.push(()=>f.remove())}for(let f of r){let h=X.declarative(f);n.push(()=>h.revert())}if(e.allowJs&&t.js){let f=document.createElement("script");e.nonce&&(f.nonce=e.nonce),f.textContent=t.js,document.head.append(f),n.push(()=>f.remove())}let g=performance.now(),b=new WeakMap;u=new MutationObserver(f=>{if(!a){performance.now()-g>1e3&&(g=performance.now(),b=new WeakMap);for(let h of f){let M=(b.get(h.target)??0)+1;if(b.set(h.target,M),M>40){l(),e.onError?.(new Error("Visual changes conflict with repeated page rendering"));return}}E()}}),u.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),E()}catch(g){throw l(),g}return{revert:l,inspect(){return{status:"unavailable",total:0,applied:0}},get applied(){return p}}}function We(t,e){let r=e?.boundVariations??[t],n=new Set,a=new Set,p=[],u=new Map,l=r.flatMap(o=>o.renderGuard?[ne(o.renderGuard)]:[]),E=l[0];if(l.some(o=>JSON.stringify(o)!==JSON.stringify(E)))throw new Error("IAM variations use different render states");if(t.js||r.some(o=>o.js))throw Error("IAM scripts cannot execute");if(r.length>20||r.reduce((o,i)=>o+i.css.length,0)>262144)throw Error("IAM target budget");let g=(o,i)=>{for(let c of o.domMutations){if(c.action!=="set"||c.attribute!=="html")throw Error("Unsupported IAM mutation");n.add(c.selector),a.add(c.selector)}if(!o.css)return;let s=document.createElement("style");ee(s),s.media="not all",e?.nonce&&(s.nonce=e.nonce),s.textContent=o.css;try{if(document.head.append(s),!s.sheet)throw Error("IAM CSS is blocked");for(let c of s.sheet.cssRules){if(!("selectorText"in c)||typeof c.selectorText!="string")throw Error("Unsupported IAM style rule");n.add(c.selectorText),i&&p.push({selector:c.selectorText,css:c.cssText})}}finally{s.remove()}};for(let o of r)g(o,!1);if(g(t,!0),n.size>200)throw Error("IAM target budget");let b=t.domMutations.map(ge),f=!1,h=!1,M=!1,w=!1,v="",V=0,x=(o,i)=>{let s=`${o}:${i}`;if(s!==v&&(v=s,!(!e?.onTargetStatus||V>=32))){V++;try{e.onTargetStatus({status:o,total:n.size,matched:i})}catch{}}},R={},W=E?JSON.stringify(E):"",S,N="",q=()=>{if(!f){f=!0,R.unsubscribe?.();for(let o of u.values())o.revert();u.clear(),S?.remove(),S=void 0,h=!1}},L=()=>{for(let o of u.values())o.revert();u.clear(),S?.remove(),S=void 0,N="",h=!1};return R.unsubscribe=me({suspend:L,fail(o){q(),e?.onError?.(o)},prepare(o){if(E&&!o.matches(E,W))return s=>{f||(L(),w=!1,s(()=>{f||x("inactive",null)}))};let i=new Map;for(let s of n){let c=o.query(s);if(c.length>1)throw Error("IAM target is ambiguous in this rendered state");if(c.length){if(a.has(s)&&c[0].children.length)throw Error("IAM text target is no longer a leaf");i.set(s,c[0])}o.checkpoint()}return s=>{if(f)return;for(let[d,y]of u)i.get(d)!==y.element&&(y.revert(),u.delete(d));for(let d of new Set(b.map(y=>y.selector))){let y=i.get(d);if(!y||u.has(d))continue;let k=b.filter(A=>A.selector===d).map(A=>X.declarative(A));u.set(d,{element:y,revert:()=>k.forEach(A=>A.revert())})}let c=p.filter(d=>i.has(d.selector)).map(d=>d.css).join(`
1
+ import{a as re,b as ne,c as oe}from"./chunk-J6KIN4RH.js";var be=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,Y={revert:function(){}},H=new Map,Q=new Set;function we(t){return t==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[t]}}function J(t){var e=H.get(t);return e||(e={element:t,attributes:{}},H.set(t,e)),e}function j(t,e,r,n,a){var p=r(t),u={isDirty:!1,originalValue:p,virtualValue:p,mutations:[],el:t,_positionTimeout:null,observer:new MutationObserver(function(){if(!Pe&&!(e==="position"&&u._positionTimeout)){e==="position"&&(u._positionTimeout=setTimeout(function(){u._positionTimeout=null},1e3));var l=r(t);e==="position"&&l.parentNode===u.virtualValue.parentNode&&l.insertBeforeNode===u.virtualValue.insertBeforeNode||l!==u.virtualValue&&(u.originalValue=l,a(u))}}),mutationRunner:a,setValue:n,getCurrentValue:r};return e==="position"&&t.parentNode?u.observer.observe(t.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):u.observer.observe(t,we(e)),u}function G(t,e){var r=e.getCurrentValue(e.el);e.virtualValue=t,t&&typeof t!="string"?(!r||t.parentNode!==r.parentNode||t.insertBeforeNode!==r.insertBeforeNode)&&(e.isDirty=!0,ie()):t!==r&&(e.isDirty=!0,ie())}function ye(t){var e=t.originalValue;t.mutations.forEach(function(r){return e=r.mutate(e)}),G(Ce(e),t)}function Ee(t){var e=new Set(t.originalValue.split(/\s+/).filter(Boolean));t.mutations.forEach(function(r){return r.mutate(e)}),G(Array.from(e).filter(Boolean).join(" "),t)}function Me(t){var e=t.originalValue;t.mutations.forEach(function(r){return e=r.mutate(e)}),G(e,t)}function Se(t){var e=t.parentSelector,r=t.insertBeforeSelector,n=document.querySelector(e);if(!n)return null;var a=r?document.querySelector(r):null;return r&&!a?null:{parentNode:n,insertBeforeNode:a}}function Ve(t){var e=t.originalValue;t.mutations.forEach(function(r){var n=r.mutate(),a=Se(n);e=a||e}),G(e,t)}var Ae=function(e){return e.innerHTML},ke=function(e,r){return e.innerHTML=r};function ae(t){var e=J(t);return e.html||(e.html=j(t,"html",Ae,ke,ye)),e.html}var Ne=function(e){return{parentNode:e.parentElement,insertBeforeNode:e.nextElementSibling}},Te=function(e,r){r.insertBeforeNode&&!r.parentNode.contains(r.insertBeforeNode)||r.parentNode.insertBefore(e,r.insertBeforeNode)};function ue(t){var e=J(t);return e.position||(e.position=j(t,"position",Ne,Te,Ve)),e.position}var xe=function(e,r){return r?e.className=r:e.removeAttribute("class")},Re=function(e){return e.className};function le(t){var e=J(t);return e.classes||(e.classes=j(t,"class",Re,xe,Ee)),e.classes}var qe=function(e){return function(r){var n;return(n=r.getAttribute(e))!=null?n:null}},Le=function(e){return function(r,n){return n!==null?r.setAttribute(e,n):r.removeAttribute(e)}};function ce(t,e){var r=J(t);return r.attributes[e]||(r.attributes[e]=j(t,e,qe(e),Le(e),Me)),r.attributes[e]}function Ie(t,e){var r=H.get(t);if(r)if(e==="html"){var n,a;(n=r.html)==null||(a=n.observer)==null||a.disconnect(),delete r.html}else if(e==="class"){var p,u;(p=r.classes)==null||(u=p.observer)==null||u.disconnect(),delete r.classes}else if(e==="position"){var l,E;(l=r.position)==null||(E=l.observer)==null||E.disconnect(),delete r.position}else{var g,b,f;(g=r.attributes)==null||(b=g[e])==null||(f=b.observer)==null||f.disconnect(),delete r.attributes[e]}}var D;function Ce(t){return D||(D=document.createElement("div")),D.innerHTML=t,D.innerHTML}function z(t,e,r){if(r.isDirty){r.isDirty=!1;var n=r.virtualValue;r.mutations.length||Ie(t,e),r.setValue(t,n)}}function Oe(t,e){t.html&&z(e,"html",t.html),t.classes&&z(e,"class",t.classes),t.position&&z(e,"position",t.position),Object.keys(t.attributes).forEach(function(r){z(e,r,t.attributes[r])})}function ie(){H.forEach(Oe)}function Be(t,e){var r=null;t.kind==="html"?r=ae(e):t.kind==="class"?r=le(e):t.kind==="attribute"?r=ce(e,t.attribute):t.kind==="position"&&(r=ue(e)),r&&(r.mutations.push(t),r.mutationRunner(r))}function De(t,e){var r=null;if(t.kind==="html"?r=ae(e):t.kind==="class"?r=le(e):t.kind==="attribute"?r=ce(e,t.attribute):t.kind==="position"&&(r=ue(e)),!!r){var n=r.mutations.indexOf(t);n!==-1&&r.mutations.splice(n,1),r.mutationRunner(r)}}function fe(t){if(!(t.kind==="position"&&t.elements.size===1)){var e=new Set(t.elements),r=document.querySelectorAll(t.selector);r.forEach(function(n){e.has(n)||(t.elements.add(n),Be(t,n))})}}function ze(t){t.elements.forEach(function(e){return De(t,e)}),t.elements.clear(),Q.delete(t)}function se(){Q.forEach(fe)}var Pe=!1;var Z;function He(){typeof document>"u"||(Z||(Z=new MutationObserver(function(){se()})),se(),Z.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}He();function U(t){return typeof document>"u"?Y:(Q.add(t),fe(t),{revert:function(){ze(t)}})}function K(t,e){return U({kind:"html",elements:new Set,mutate:e,selector:t})}function de(t,e){return U({kind:"position",elements:new Set,mutate:e,selector:t})}function C(t,e){return U({kind:"class",elements:new Set,mutate:e,selector:t})}function P(t,e,r){return be.test(e)?e==="class"||e==="className"?C(t,function(n){var a=r(Array.from(n).join(" "));n.clear(),a&&a.split(/\s+/g).filter(Boolean).forEach(function(p){return n.add(p)})}):U({kind:"attribute",attribute:e,elements:new Set,mutate:r,selector:t}):Y}function Je(t){var e=t.selector,r=t.action,n=t.value,a=t.attribute,p=t.parentSelector,u=t.insertBeforeSelector;if(a==="html"){if(r==="append")return K(e,function(l){return l+(n??"")});if(r==="set")return K(e,function(){return n??""})}else if(a==="class"){if(r==="append")return C(e,function(l){n&&l.add(n)});if(r==="remove")return C(e,function(l){n&&l.delete(n)});if(r==="set")return C(e,function(l){l.clear(),n&&l.add(n)})}else if(a==="position"){if(r==="set"&&p)return de(e,function(){return{insertBeforeSelector:u,parentSelector:p}})}else{if(r==="append")return P(e,a,function(l){return l!==null?l+(n??""):n??""});if(r==="set")return P(e,a,function(){return n??""});if(r==="remove")return P(e,a,function(){return null})}return Y}var je={html:K,classes:C,attribute:P,position:de,declarative:Je},X=je;import Ue from"dompurify";var T=class extends Error{constructor(){super("IAM page check exceeded its work budget")}},_=new WeakMap,$=new WeakSet;function ee(t){$.add(t)}function Ge(t){let e=new Set,r=new Set,n,a=0,p=!1,u=0,l,E=()=>{e.size||a||(n?.disconnect(),l!==void 0&&cancelAnimationFrame(l),t.removeEventListener("visibilitychange",f),_.delete(t))};function g(h){if(t.hidden)return;let M=performance.now(),w=new Map,v=new Map,V=()=>{if(performance.now()-M>8)throw new T},x=o=>{V();let i=w.get(o);return i||(i=t.querySelectorAll(o),w.set(o,i)),V(),i},R=re({querySelectorAll:x},V),W=o=>{let i=o.filter(m=>!w.has(m));if(!i.length)return;let s=new Map;for(let m of i){let d=/^([a-z][a-z0-9-]*)\[(id|data-testid|data-test|data-qa|data-indiana-id)="((?:[^"\\\x00-\x1f\x7f]|\\["\\])*)"\]$/.exec(m);if(!d)throw Error("Invalid IAM render selector");let[,y,k,A]=d,I=A.replace(/\\(["\\])/g,"$1"),O=s.get(y);O||s.set(y,O=new Map);let B=O.get(k);B||O.set(k,B=new Map);let F=B.get(I);F||B.set(I,F=[]),w.set(m,F)}V();let c=t.querySelectorAll(i.join(","));if(V(),c.length>8192)throw Error("IAM render selection budget exceeded");for(let m of c){let d=s.get(m.localName.toLowerCase());if(d)for(let[y,k]of d){let A=m.getAttribute(y);A!==null&&k.get(A)?.push(m)}V()}},S={query:x,checkpoint:V,matches(o,i){let s=v.get(i);if(!s){try{let c=!1;s={match:oe(o,t,location.pathname,V,m=>(c||(W(o.selectors),c=!0),R(m)))}}catch(c){s={error:c}}v.set(i,s)}if("error"in s)throw s.error;return s.match}},N=[],q=[],L=[];for(let o of h)if(e.has(o))try{N.push({job:o,commit:o.prepare(S)})}catch(i){if(i instanceof T)throw i;q.push({job:o,error:i})}V();for(let{job:o,error:i}of q)e.has(o)&&o.fail(i);for(let{job:o,commit:i}of N)if(e.has(o))try{V(),i(s=>L.push(s))}catch(s){if(s instanceof T)throw s;o.fail(s)}for(let o of L)o()}function b(h){if(!(l!==void 0||t.hidden))try{g(h),u=0}catch(M){if(!(M instanceof T))throw M;for(let w of[...e])w.suspend();if(u++>=2){for(let w of[...e])w.fail(M);return}l=requestAnimationFrame(()=>{l=void 0,b([...e])})}}function f(){p||!e.size||t.hidden||(p=!0,queueMicrotask(()=>{p=!1,b([...e])}))}return{begin(){a++},end(){--a===0&&(r.clear(),b([...e])),E()},add(h){return n||(n=new MutationObserver(M=>{let w=v=>$.has(v)||!!(v.parentNode&&$.has(v.parentNode));M.some(v=>!w(v.target)&&!(v.type==="childList"&&[...v.addedNodes,...v.removedNodes].length>0&&[...v.addedNodes,...v.removedNodes].every(w)))&&f()}),n.observe(t.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["style","hidden","data-indiana-id","data-indiana-release","data-testid","id","name"]}),t.addEventListener("visibilitychange",f)),e.add(h),a?r.add(h):b([h]),()=>{e.delete(h),r.delete(h),E()}}}}function pe(){let t=_.get(document);return t||(t=Ge(document),_.set(document,t)),t}function me(t){return pe().add(t)}function Ye(t){let e=pe();e.begin();try{t()}finally{e.end()}}var te,he;function ve(t){return(!te||he!==window)&&(te=Ue(window),he=window),te.sanitize(t,{USE_PROFILES:{html:!0},FORBID_TAGS:["form","input","textarea","select","button","style"]})}function ge(t){let e={...t};if(!["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e.attribute)&&!/^(aria|data)-[a-z0-9_-]+$/.test(e.attribute))throw new Error("Unsupported visual attribute");document.querySelector(e.selector);for(let r of document.querySelectorAll(e.selector))if(["SCRIPT","IFRAME","OBJECT","EMBED","HTML","HEAD"].includes(r.tagName)||r.tagName==="BODY"&&e.attribute==="html")throw new Error("Protected visual target");if(e.attribute==="html"&&(e.value=ve(e.value??"")),["href","src"].includes(e.attribute)&&e.action!=="remove"){let r=new URL(e.value??"",location.href);if(!["https:","http:","mailto:","tel:"].includes(r.protocol)||e.attribute==="src"&&!["https:","http:"].includes(r.protocol))throw new Error("Unsafe visual URL")}return e.parentSelector&&document.querySelector(e.parentSelector),e.insertBeforeSelector&&document.querySelector(e.insertBeforeSelector),e}function tt(t,e={}){if(t.renderGuard&&!e.requireUniqueTargets)throw new Error("IAM render guard requires the source release fence");if(e.requireUniqueTargets)return We(t,e);let r=t.domMutations.map(ge),n=[],a=!1,p=!1,u,l=()=>{if(!a){a=!0,u?.disconnect();for(let g of n.reverse())g()}},E=()=>{a||p||(!r.length||t.css||e.allowJs&&t.js||r.some(g=>document.querySelector(g.selector)))&&(p=!0,e.onApplied?.())};try{if(t.css){let f=document.createElement("style");e.nonce&&(f.nonce=e.nonce),f.textContent=t.css,document.head.append(f),n.push(()=>f.remove())}for(let f of r){let h=X.declarative(f);n.push(()=>h.revert())}if(e.allowJs&&t.js){let f=document.createElement("script");e.nonce&&(f.nonce=e.nonce),f.textContent=t.js,document.head.append(f),n.push(()=>f.remove())}let g=performance.now(),b=new WeakMap;u=new MutationObserver(f=>{if(!a){performance.now()-g>1e3&&(g=performance.now(),b=new WeakMap);for(let h of f){let M=(b.get(h.target)??0)+1;if(b.set(h.target,M),M>40){l(),e.onError?.(new Error("Visual changes conflict with repeated page rendering"));return}}E()}}),u.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),E()}catch(g){throw l(),g}return{revert:l,inspect(){return{status:"unavailable",total:0,applied:0}},get applied(){return p}}}function We(t,e){let r=e?.boundVariations??[t],n=new Set,a=new Set,p=[],u=new Map,l=r.flatMap(o=>o.renderGuard?[ne(o.renderGuard)]:[]),E=l[0];if(l.some(o=>JSON.stringify(o)!==JSON.stringify(E)))throw new Error("IAM variations use different render states");if(t.js||r.some(o=>o.js))throw Error("IAM scripts cannot execute");if(r.length>20||r.reduce((o,i)=>o+i.css.length,0)>262144)throw Error("IAM target budget");let g=(o,i)=>{for(let c of o.domMutations){if(c.action!=="set"||c.attribute!=="html")throw Error("Unsupported IAM mutation");n.add(c.selector),a.add(c.selector)}if(!o.css)return;let s=document.createElement("style");ee(s),s.media="not all",e?.nonce&&(s.nonce=e.nonce),s.textContent=o.css;try{if(document.head.append(s),!s.sheet)throw Error("IAM CSS is blocked");for(let c of s.sheet.cssRules){if(!("selectorText"in c)||typeof c.selectorText!="string")throw Error("Unsupported IAM style rule");n.add(c.selectorText),i&&p.push({selector:c.selectorText,css:c.cssText})}}finally{s.remove()}};for(let o of r)g(o,!1);if(g(t,!0),n.size>200)throw Error("IAM target budget");let b=t.domMutations.map(ge),f=!1,h=!1,M=!1,w=!1,v="",V=0,x=(o,i)=>{let s=`${o}:${i}`;if(s!==v&&(v=s,!(!e?.onTargetStatus||V>=32))){V++;try{e.onTargetStatus({status:o,total:n.size,matched:i})}catch{}}},R={},W=E?JSON.stringify(E):"",S,N="",q=()=>{if(!f){f=!0,R.unsubscribe?.();for(let o of u.values())o.revert();u.clear(),S?.remove(),S=void 0,h=!1}},L=()=>{for(let o of u.values())o.revert();u.clear(),S?.remove(),S=void 0,N="",h=!1};return R.unsubscribe=me({suspend:L,fail(o){q(),e?.onError?.(o)},prepare(o){if(E&&!o.matches(E,W))return s=>{f||(L(),w=!1,s(()=>{f||x("inactive",null)}))};let i=new Map;for(let s of n){let c=o.query(s);if(c.length>1)throw Error("IAM target is ambiguous in this rendered state");if(c.length){if(a.has(s)&&c[0].children.length)throw Error("IAM text target is no longer a leaf");i.set(s,c[0])}o.checkpoint()}return s=>{if(f)return;for(let[d,y]of u)i.get(d)!==y.element&&(y.revert(),u.delete(d));for(let d of new Set(b.map(y=>y.selector))){let y=i.get(d);if(!y||u.has(d))continue;let k=b.filter(A=>A.selector===d).map(A=>X.declarative(A));u.set(d,{element:y,revert:()=>k.forEach(A=>A.revert())})}let c=p.filter(d=>i.has(d.selector)).map(d=>d.css).join(`
2
2
  `);c!==N&&(N=c,c?(S||(S=document.createElement("style"),ee(S),e?.nonce&&(S.nonce=e.nonce),document.head.append(S)),S.textContent=c):(S?.remove(),S=void 0)),h=n.size===0||i.size>0;let m=i.size===n.size?"matched":i.size>0?"partial":w?"missing":"waiting";i.size&&(w=!0),s(()=>{f||x(m,i.size)}),h&&!M&&s(()=>{!f&&h&&!M&&(M=!0,e?.onApplied?.())})}}}),f&&R.unsubscribe(),{revert:q,inspect(){let o=b.length+p.reduce((m,d)=>m+(d.css.includes("font-size:")?1:0)+(d.css.includes("color:")?1:0),0);if(f)return{status:"error",total:o,applied:0};if(v.startsWith("inactive:"))return{status:"inactive",total:o,applied:0};if(!o)return{status:"no_changes",total:o,applied:0};let i=0,s=0;for(let m of b){let d=document.querySelectorAll(m.selector);d.length===1&&(s++,d[0].innerHTML===ve(m.value??"")&&i++)}let c=document.createElement("span");for(let m of p){let d=document.querySelectorAll(m.selector),y=d.length===1?d[0]:void 0,k=m.css.slice(m.css.indexOf("{")+1,m.css.lastIndexOf("}"));c.style.cssText=k;for(let A of["font-size","color"]){let I=c.style.getPropertyValue(A);I&&y?.isConnected&&(s++,getComputedStyle(y).getPropertyValue(A)===I&&i++)}}return{status:i===o?"applied":s?i?"partial":"mismatch":"waiting",total:o,applied:i}},get applied(){return h}}}export{Ye as a,ge as b,tt as c};
@@ -1 +1 @@
1
- import{ia as E,ja as M,ka as j,la as O,ma as T}from"./chunk-WCVK4OMS.js";import{k as w,qa as u}from"./chunk-ACF2FBUB.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
1
+ import{ia as E,ja as M,ka as j,la as O,ma as T}from"./chunk-IAOOTBJV.js";import{k as w,qa as u}from"./chunk-ACF2FBUB.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
@@ -1,4 +1,4 @@
1
- import{$ as gn,A as qi,B as fn,C as as,D as ss,E as cs,F as us,G as ls,H as Pr,I as An,J as ps,K as ds,L as Hn,M as ms,N as hn,O as fs,Q as As,R as hs,S as gs,T as bs,X as Zn,Z as Pt,_ as it,a as Ln,aa as zi,b as La,ba as Tt,c as $a,d as Ga,e as Ka,ea as Ni,f as Ha,g as se,h as Ti,ha as kr,i as Za,ia as Zt,j as ft,ja as xt,k as we,ka as Fi,l as Mi,m as _t,n as Qa,na as Os,o as Or,p as Ja,q as Wa,qa as ue,r as mn,s as es,t as Gn,u as ts,v as ns,w as rs,x as Kn,y as is,z as os}from"./chunk-ACF2FBUB.js";import{a as ve,b as ys,c as xs,d as Ss,e as Mt,f as vs,g as Cr,h as Is,i as ws}from"./chunk-G56XGVMS.js";import{a as js,b as _s}from"./chunk-AWZFL4HE.js";import{a as me,b as rt,c as Ht,d as Dt,e as _r}from"./chunk-7DXL3LHT.js";import{c as wr,d as jr,e as Xa,f as Bi,g as Ya,h as $n}from"./chunk-XSVQHPQT.js";import{z as y}from"zod";import{z as A}from"zod";var He=A.string().min(1).max(200),et=A.iso.datetime({offset:!0}),De=A.number().int().nonnegative().max(1e8),Rr=A.string().regex(/^[A-Z]{3}$/),ud=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],Ps=A.enum(ud),Cs=A.strictObject({priceId:A.uuid(),productVersionId:A.uuid(),productId:He,quantity:A.number().int().min(1).max(1e6),unitAmountMinor:De,totalMinor:De,interval:A.enum(["week","month","year","one_off"]),intervalCount:A.number().int().min(1).max(52),kind:A.enum(["fixed","prepaid","seat"]),tiers:A.strictObject({mode:A.enum(["graduated","volume"]),tiers:A.array(A.strictObject({upTo:A.number().int().positive().nullable(),unitAmountMinor:De,flatAmountMinor:De.optional()})).min(2).max(12)}).nullable()}),ld=A.strictObject({grantId:A.uuid(),couponId:A.uuid(),amountMinor:De,terms:A.discriminatedUnion("type",[A.strictObject({type:A.literal("percent"),percentOff:A.number().gt(0).max(100)}),A.strictObject({type:A.literal("amount"),amountOffMinor:De,currency:Rr})]),duration:A.discriminatedUnion("type",[A.strictObject({type:A.literal("once")}),A.strictObject({type:A.literal("forever")}),A.strictObject({type:A.literal("repeating"),months:A.number().int().min(1).max(36)})])}),$i={provider:A.literal("merchant"),executor:A.literal("merchant"),operationId:A.uuid(),customerId:A.uuid(),configurationRevision:A.number().int().nonnegative(),connectionRevision:A.number().int().nonnegative(),currency:Rr,expiresAt:et},Er=A.strictObject({...$i,type:A.literal("purchase"),mode:A.enum(["payment","subscription"]),lineItems:A.array(Cs).min(1).max(100),catalogAmountMinor:De,discount:ld.nullable(),trialPeriodDays:A.number().int().min(1).max(730).nullable(),automaticTax:A.boolean()}).refine(e=>e.lineItems.reduce((t,n)=>t+n.totalMinor,0)===e.catalogAmountMinor&&(!e.discount||e.discount.amountMinor<=e.catalogAmountMinor)&&new Set(e.lineItems.map(t=>t.priceId)).size===e.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),Dr=A.strictObject({...$i,type:A.literal("subscription_change"),subscriptionId:A.uuid(),merchantSubscriptionId:He,membershipId:A.uuid(),subscriptionAction:A.enum(["update","cancel","schedule","release"]),supersedesOperationId:A.uuid().nullable(),change:A.discriminatedUnion("type",[A.strictObject({type:A.literal("cancel")}),A.strictObject({type:A.literal("uncancel")}),A.strictObject({type:A.literal("plan"),productVersionId:A.uuid()}),A.strictObject({type:A.literal("seats"),licenseKey:He,quantity:A.number().int().nonnegative().max(1e6)}),A.strictObject({type:A.literal("quantity"),internal_feature_id:A.uuid(),quantity:A.number().int().nonnegative().max(1e6)}),A.strictObject({type:A.literal("billing_cycle"),billingCycleAnchor:A.union([A.literal("now"),A.number().int().positive()])})]),timing:A.enum(["immediate","renewal"]),effectiveAt:et,creditMinor:De,debitMinor:De,totalMinor:De,discountMinor:De,taxMinor:De,proration:A.enum(["none","create_prorations","always_invoice"]),lineItems:A.array(Cs.extend({quantity:A.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:A.array(A.uuid()).max(100)}),Tr=A.strictObject({...$i,type:A.literal("refund"),invoiceId:A.uuid(),merchantInvoiceId:He,amountMinor:De.refine(e=>e>0),mode:A.enum(["full","partial"]),entitlementAction:A.enum(["retain","revoke"]),cancelSubscriptions:A.array(He).max(100)}),ks=A.discriminatedUnion("type",[Er,Dr,Tr]);function Zh(e){let t=new Set;if(e.type==="purchase")t.add(e.mode==="subscription"?"purchase.subscription":"purchase.one_time"),e.lineItems.some(n=>n.kind==="prepaid")&&t.add("purchase.prepaid"),e.lineItems.some(n=>n.kind==="seat")&&t.add("purchase.seats"),e.lineItems.some(n=>n.tiers!==null)&&t.add("purchase.tiered"),e.trialPeriodDays!==null&&t.add("purchase.trial"),e.automaticTax&&t.add("tax.automatic"),e.discount&&t.add(`discount.${e.discount.terms.type}.${e.discount.duration.type}`);else if(e.type==="refund")t.add(`refund.${e.mode}`),e.entitlementAction==="revoke"&&t.add("refund.revoke");else{let n=e.change.type;n==="cancel"?t.add(`subscription.cancel.${e.timing}`):n==="uncancel"?t.add("subscription.resume"):n==="plan"?t.add(`subscription.plan.${e.timing}`):t.add(`subscription.${n}`),e.proration!=="none"&&t.add("subscription.proration")}return[...t].sort()}function Qh(e){return e.type==="purchase"?e.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:e.type==="subscription_change"?["subscription.change.completed","subscription.observed",...e.change.type==="cancel"||e.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...e.entitlementAction==="revoke"&&e.cancelSubscriptions.length?["subscription.observed"]:[]]}var Qn=A.strictObject({phase:A.enum(["execution","payment","fulfillment","recording"]),code:Ln,reason:$a.optional(),recovery:La,retryable:A.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ui={operationId:A.uuid(),customerId:A.uuid(),merchantExecutionId:He,fulfillmentStatus:A.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:A.enum(["not_ready","pending","accepted","failed"]),updatedAt:et,problem:Qn.nullable(),pollAfterMs:A.number().int().min(1e3).max(6e4).nullable()},Qt=A.discriminatedUnion("type",[A.strictObject({...Ui,type:A.literal("purchase"),merchantOrderId:He.nullable(),paymentStatus:A.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:A.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:et.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),A.strictObject({...Ui,type:A.literal("subscription_change"),status:A.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:He,scheduledFor:et.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),A.strictObject({...Ui,type:A.literal("refund"),status:A.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:He.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),Rs=A.discriminatedUnion("lookup",[A.strictObject({lookup:A.literal("found"),operationId:A.uuid(),customerId:A.uuid(),execution:Qt,readAt:et}),A.strictObject({lookup:A.literal("not_received"),operationId:A.uuid(),customerId:A.uuid(),execution:A.null(),readAt:et})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),Vi=A.strictObject({merchantSubscriptionId:He,revision:A.number().int().positive(),status:A.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:et,periodEndsAt:et,cancelAtPeriodEnd:A.boolean(),hasDiscounts:A.boolean(),items:A.array(A.strictObject({merchantItemId:He,priceId:A.uuid(),quantity:A.number().int().positive().max(1e6)})).min(1).max(100)}).refine(e=>Date.parse(e.periodEndsAt)>Date.parse(e.periodStartsAt)&&new Set(e.items.map(t=>t.priceId)).size===e.items.length,"Subscription periods and Price identities must be unambiguous"),Li=A.strictObject({merchantInvoiceId:He,currency:Rr,subtotalMinor:De,discountMinor:De,taxMinor:De,totalMinor:De,paidMinor:De,periodStartsAt:et.nullable(),periodEndsAt:et.nullable(),lines:A.array(A.strictObject({merchantLineId:He,priceId:A.uuid(),quantity:A.number().int().nonnegative().max(1e6),subtotalMinor:A.number().int().min(-1e8).max(1e8),discountMinor:De,taxMinor:De,totalMinor:A.number().int().min(-1e8).max(2e8),periodStartsAt:et.nullable(),periodEndsAt:et.nullable()}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&(e.subtotalMinor<0?e.discountMinor===0&&e.taxMinor===0:e.discountMinor<=e.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&e.discountMinor<=e.subtotalMinor&&e.paidMinor===e.totalMinor&&new Set(e.lines.map(t=>t.merchantLineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.subtotalMinor,0)===e.subtotalMinor&&e.lines.reduce((t,n)=>t+n.discountMinor,0)===e.discountMinor&&e.lines.reduce((t,n)=>t+n.taxMinor,0)===e.taxMinor&&e.lines.reduce((t,n)=>t+n.totalMinor,0)===e.totalMinor,"A paid Invoice retains the complete financial amounts"),bn={provider:A.literal("merchant"),eventId:A.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:A.uuid(),occurredAt:et},Es=A.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),Ds=A.discriminatedUnion("type",[A.strictObject({...bn,type:A.literal("purchase.completed"),operationId:A.uuid(),merchantOrderId:He,paymentStatus:A.enum(["paid","trialing","no_payment_required"]),invoice:Li.nullable(),subscription:Vi.nullable()}).refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),A.strictObject({...bn,type:A.literal("purchase.closed"),operationId:A.uuid(),status:A.enum(["failed","expired","canceled"])}),A.strictObject({...bn,type:A.literal("subscription.observed"),operationId:A.uuid().nullable(),subscription:Vi}),A.strictObject({...bn,type:A.literal("subscription.change.completed"),operationId:A.uuid(),status:A.enum(["scheduled","applied"]),scheduledFor:et.nullable(),subscription:Vi,invoice:Li.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),A.strictObject({...bn,type:A.literal("invoice.paid"),merchantSubscriptionId:He,invoice:Li}),A.strictObject({...bn,type:A.literal("refund.updated"),operationId:A.uuid(),merchantRefundId:He,status:A.enum(["pending","succeeded","failed"]),amountMinor:De.refine(e=>e>0),currency:Rr})]);import{z as Jt}from"zod";var Bt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,qt=Jt.object({customerId:Jt.uuid(),sessionId:Jt.uuid(),accessToken:Jt.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Jt.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Jt.iso.datetime(),refreshExpiresAt:Jt.iso.datetime()});var yn=3,Ms="/integrations/indiana",ng="X-Indiana-Merchant-Bridge-Version",pd=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],dd=y.enum(pd),rg={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},Bs=y.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),qs=y.string().regex(/^[A-Za-z0-9_-]{1,64}$/),md=y.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),Ki=y.strictObject({keyId:qs,signingSecret:md}),fd=y.string().max(300).superRefine((e,t)=>{try{let n=new URL(e);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.port&&n.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(n.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(n.hostname))throw new Error("invalid origin")}catch{t.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(e=>new URL(e).origin),zs=y.array(dd).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),Ns=y.strictObject({bridgeVersion:y.literal(yn),projectId:y.uuid(),environmentId:y.uuid(),environment:y.enum(["sandbox","live"]),capabilities:zs,catalog:y.enum(["endpoint","static","none"]),billingEvents:y.array(Es).max(6),profiles:y.array(Ps).max(32).refine(e=>new Set(e).size===e.length,"Profiles must be unique")}).superRefine((e,t)=>{let n=r=>e.capabilities.includes(r);n("catalog")!==(e.catalog!=="none")&&t.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(n("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&t.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),Fs=y.strictObject({origin:fd,requiredCapabilities:zs}),Ad=y.strictObject({revision:y.number().int().nonnegative(),checkedAt:y.iso.datetime(),outcome:y.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:y.strictObject({ping:y.enum(["passed","failed","not_checked"]),authentication:y.enum(["passed","failed","not_checked"]),catalog:y.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:Ns.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),ig=y.strictObject({projectId:y.uuid(),environmentId:y.uuid(),environment:y.enum(["sandbox","live"]),execution:y.enum(["indiana","record_only"]),accountId:y.string().nullable(),revision:y.number().int().nonnegative(),authentication:y.strictObject({keyId:qs}).nullable(),secretStoreConfigured:y.boolean().optional(),connection:Fs.nullable(),check:Ad.nullable()});var Ts=y.strictObject({projectId:y.uuid(),environmentId:y.uuid()}),og=y.discriminatedUnion("action",[Ts.extend({action:y.literal("save"),revision:y.number().int().nonnegative(),connection:Fs,authentication:Ki.optional()}),Ts.extend({action:y.literal("check"),revision:y.number().int().nonnegative()})]),Br=y.strictObject({projectId:y.uuid(),environmentId:y.uuid(),environment:y.enum(["sandbox","live"])});function ag(e){return y.strictObject({bridgeVersion:y.literal(yn),requestId:y.uuid(),command:Bs,scope:Br,data:e})}var hd=y.strictObject({nativeUserId:y.string().min(1).max(128),session:qt.strict()}),gd=y.strictObject({nativeUserId:y.string().min(1).max(128),presentation:y.strictObject({customerId:y.uuid(),decisionId:y.uuid(),offeringVersionId:y.uuid(),paywallVersionId:y.uuid(),variant:y.string().min(1).max(128)}).nullable()}),bd=y.strictObject({decisionId:y.uuid(),eventId:y.uuid()}),Mr=y.strictObject({operationId:y.uuid(),customerId:y.uuid()}),qr=y.strictObject({scope:Br,operationId:y.uuid(),customerId:y.uuid(),confirmedAt:y.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:y.boolean(),instruction:ks}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),Gi=Qt,Ct=y.string().min(1).max(120),yd=y.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),xd=y.strictObject({revision:Ct,updatedAt:y.iso.datetime(),provider:y.literal("merchant"),items:y.array(y.strictObject({merchantProductId:Ct,productVersionId:y.uuid(),name:y.string().min(1).max(255),kind:y.enum(["subscription","credit_pack"]),merchantPriceId:Ct,currency:y.string().regex(/^[a-z]{3}$/),amountMinor:y.number().int().nonnegative().max(1e8),interval:y.enum(["one_time","month","year"]),intervalCount:y.literal(1),includedCredits:y.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:y.enum(["none","month"]),creditPolicyId:Ct,available:y.boolean()}).superRefine((e,t)=>{(e.kind==="credit_pack"&&(e.interval!=="one_time"||e.creditReset!=="none")||e.kind==="subscription"&&e.interval==="one_time"||e.available&&e.amountMinor===0)&&t.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Sd=y.strictObject({customerId:y.uuid(),revision:y.string().min(1).max(128),observedAt:y.iso.datetime(),subscriptions:y.array(y.strictObject({merchantSubscriptionId:Ct,merchantProductId:Ct,productVersionId:y.uuid().nullable(),status:y.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:y.iso.datetime().nullable(),currentPeriodEndsAt:y.iso.datetime().nullable(),cancelAtPeriodEnd:y.boolean(),scheduledChange:y.strictObject({effectiveAt:y.iso.datetime(),merchantProductId:Ct}).nullable()})).max(100),purchaseHistory:y.strictObject({complete:y.boolean(),hasPaidPurchase:y.boolean(),lastPaidAt:y.iso.datetime().nullable()}),balances:y.array(y.strictObject({bucketId:Ct,key:Ct,available:yd,expiresAt:y.iso.datetime().nullable(),nextResetAt:y.iso.datetime().nullable()})).max(100)}),sg=y.strictObject({bridgeVersion:y.literal(yn),requestId:y.uuid(),command:y.string().min(1).max(64),scope:Br,error:y.strictObject({code:y.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:y.string().min(1).max(500),retryable:y.boolean(),recovery:y.string().min(1).max(80)})}),Jn=y.strictObject({}),vd={"bridge.ping":y.strictObject({challenge:y.uuid()}),"bridge.describe":Jn,"session.create":Jn,"catalog.read":Jn,"customer.commerce.read":Jn,"presentation.resolve":Jn,"presentation.report":bd,"purchase.execute":Mr,"operation.read":Mr,"subscription.change":Mr,"refund.execute":Mr},cg={"bridge.ping":y.strictObject({challenge:y.uuid()}),"bridge.describe":Ns,"session.create":hd,"catalog.read":xd,"customer.commerce.read":Sd,"presentation.resolve":gd,"presentation.report":y.strictObject({queued:y.literal(!0)}),"purchase.execute":Gi,"operation.read":Rs,"subscription.change":Gi,"refund.execute":Gi},ug=y.strictObject({bridgeVersion:y.literal(yn),requestId:y.uuid(),scope:Br,command:Bs,data:y.unknown()}).superRefine((e,t)=>{vd[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});var Us="X-Indiana-Bridge-Signature",Vs="X-Indiana-Bridge-Key-Id";function Id(e){return new TextEncoder().encode(e)}function Ls(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}function $s(e,t,n){return Id(`indiana-merchant-bridge:${yn}
1
+ import{$ as gn,A as qi,B as fn,C as as,D as ss,E as cs,F as us,G as ls,H as Pr,I as An,J as ps,K as ds,L as Hn,M as ms,N as hn,O as fs,Q as As,R as hs,S as gs,T as bs,X as Zn,Z as Pt,_ as it,a as Ln,aa as zi,b as La,ba as Tt,c as $a,d as Ga,e as Ka,ea as Ni,f as Ha,g as se,h as Ti,ha as kr,i as Za,ia as Zt,j as ft,ja as xt,k as we,ka as Fi,l as Mi,m as _t,n as Qa,na as Os,o as Or,p as Ja,q as Wa,qa as ue,r as mn,s as es,t as Gn,u as ts,v as ns,w as rs,x as Kn,y as is,z as os}from"./chunk-ACF2FBUB.js";import{a as ve,b as ys,c as xs,d as Ss,e as Mt,f as vs,g as Cr,h as Is,i as ws}from"./chunk-G56XGVMS.js";import{a as js,b as _s}from"./chunk-22Z7JR4B.js";import{a as me,b as rt,c as Ht,d as Dt,e as _r}from"./chunk-7DXL3LHT.js";import{c as wr,d as jr,e as Xa,f as Bi,g as Ya,h as $n}from"./chunk-XSVQHPQT.js";import{z as y}from"zod";import{z as A}from"zod";var He=A.string().min(1).max(200),et=A.iso.datetime({offset:!0}),De=A.number().int().nonnegative().max(1e8),Rr=A.string().regex(/^[A-Z]{3}$/),ud=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],Ps=A.enum(ud),Cs=A.strictObject({priceId:A.uuid(),productVersionId:A.uuid(),productId:He,quantity:A.number().int().min(1).max(1e6),unitAmountMinor:De,totalMinor:De,interval:A.enum(["week","month","year","one_off"]),intervalCount:A.number().int().min(1).max(52),kind:A.enum(["fixed","prepaid","seat"]),tiers:A.strictObject({mode:A.enum(["graduated","volume"]),tiers:A.array(A.strictObject({upTo:A.number().int().positive().nullable(),unitAmountMinor:De,flatAmountMinor:De.optional()})).min(2).max(12)}).nullable()}),ld=A.strictObject({grantId:A.uuid(),couponId:A.uuid(),amountMinor:De,terms:A.discriminatedUnion("type",[A.strictObject({type:A.literal("percent"),percentOff:A.number().gt(0).max(100)}),A.strictObject({type:A.literal("amount"),amountOffMinor:De,currency:Rr})]),duration:A.discriminatedUnion("type",[A.strictObject({type:A.literal("once")}),A.strictObject({type:A.literal("forever")}),A.strictObject({type:A.literal("repeating"),months:A.number().int().min(1).max(36)})])}),$i={provider:A.literal("merchant"),executor:A.literal("merchant"),operationId:A.uuid(),customerId:A.uuid(),configurationRevision:A.number().int().nonnegative(),connectionRevision:A.number().int().nonnegative(),currency:Rr,expiresAt:et},Er=A.strictObject({...$i,type:A.literal("purchase"),mode:A.enum(["payment","subscription"]),lineItems:A.array(Cs).min(1).max(100),catalogAmountMinor:De,discount:ld.nullable(),trialPeriodDays:A.number().int().min(1).max(730).nullable(),automaticTax:A.boolean()}).refine(e=>e.lineItems.reduce((t,n)=>t+n.totalMinor,0)===e.catalogAmountMinor&&(!e.discount||e.discount.amountMinor<=e.catalogAmountMinor)&&new Set(e.lineItems.map(t=>t.priceId)).size===e.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),Dr=A.strictObject({...$i,type:A.literal("subscription_change"),subscriptionId:A.uuid(),merchantSubscriptionId:He,membershipId:A.uuid(),subscriptionAction:A.enum(["update","cancel","schedule","release"]),supersedesOperationId:A.uuid().nullable(),change:A.discriminatedUnion("type",[A.strictObject({type:A.literal("cancel")}),A.strictObject({type:A.literal("uncancel")}),A.strictObject({type:A.literal("plan"),productVersionId:A.uuid()}),A.strictObject({type:A.literal("seats"),licenseKey:He,quantity:A.number().int().nonnegative().max(1e6)}),A.strictObject({type:A.literal("quantity"),internal_feature_id:A.uuid(),quantity:A.number().int().nonnegative().max(1e6)}),A.strictObject({type:A.literal("billing_cycle"),billingCycleAnchor:A.union([A.literal("now"),A.number().int().positive()])})]),timing:A.enum(["immediate","renewal"]),effectiveAt:et,creditMinor:De,debitMinor:De,totalMinor:De,discountMinor:De,taxMinor:De,proration:A.enum(["none","create_prorations","always_invoice"]),lineItems:A.array(Cs.extend({quantity:A.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:A.array(A.uuid()).max(100)}),Tr=A.strictObject({...$i,type:A.literal("refund"),invoiceId:A.uuid(),merchantInvoiceId:He,amountMinor:De.refine(e=>e>0),mode:A.enum(["full","partial"]),entitlementAction:A.enum(["retain","revoke"]),cancelSubscriptions:A.array(He).max(100)}),ks=A.discriminatedUnion("type",[Er,Dr,Tr]);function Zh(e){let t=new Set;if(e.type==="purchase")t.add(e.mode==="subscription"?"purchase.subscription":"purchase.one_time"),e.lineItems.some(n=>n.kind==="prepaid")&&t.add("purchase.prepaid"),e.lineItems.some(n=>n.kind==="seat")&&t.add("purchase.seats"),e.lineItems.some(n=>n.tiers!==null)&&t.add("purchase.tiered"),e.trialPeriodDays!==null&&t.add("purchase.trial"),e.automaticTax&&t.add("tax.automatic"),e.discount&&t.add(`discount.${e.discount.terms.type}.${e.discount.duration.type}`);else if(e.type==="refund")t.add(`refund.${e.mode}`),e.entitlementAction==="revoke"&&t.add("refund.revoke");else{let n=e.change.type;n==="cancel"?t.add(`subscription.cancel.${e.timing}`):n==="uncancel"?t.add("subscription.resume"):n==="plan"?t.add(`subscription.plan.${e.timing}`):t.add(`subscription.${n}`),e.proration!=="none"&&t.add("subscription.proration")}return[...t].sort()}function Qh(e){return e.type==="purchase"?e.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:e.type==="subscription_change"?["subscription.change.completed","subscription.observed",...e.change.type==="cancel"||e.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...e.entitlementAction==="revoke"&&e.cancelSubscriptions.length?["subscription.observed"]:[]]}var Qn=A.strictObject({phase:A.enum(["execution","payment","fulfillment","recording"]),code:Ln,reason:$a.optional(),recovery:La,retryable:A.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ui={operationId:A.uuid(),customerId:A.uuid(),merchantExecutionId:He,fulfillmentStatus:A.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:A.enum(["not_ready","pending","accepted","failed"]),updatedAt:et,problem:Qn.nullable(),pollAfterMs:A.number().int().min(1e3).max(6e4).nullable()},Qt=A.discriminatedUnion("type",[A.strictObject({...Ui,type:A.literal("purchase"),merchantOrderId:He.nullable(),paymentStatus:A.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:A.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:et.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),A.strictObject({...Ui,type:A.literal("subscription_change"),status:A.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:He,scheduledFor:et.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),A.strictObject({...Ui,type:A.literal("refund"),status:A.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:He.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),Rs=A.discriminatedUnion("lookup",[A.strictObject({lookup:A.literal("found"),operationId:A.uuid(),customerId:A.uuid(),execution:Qt,readAt:et}),A.strictObject({lookup:A.literal("not_received"),operationId:A.uuid(),customerId:A.uuid(),execution:A.null(),readAt:et})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),Vi=A.strictObject({merchantSubscriptionId:He,revision:A.number().int().positive(),status:A.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:et,periodEndsAt:et,cancelAtPeriodEnd:A.boolean(),hasDiscounts:A.boolean(),items:A.array(A.strictObject({merchantItemId:He,priceId:A.uuid(),quantity:A.number().int().positive().max(1e6)})).min(1).max(100)}).refine(e=>Date.parse(e.periodEndsAt)>Date.parse(e.periodStartsAt)&&new Set(e.items.map(t=>t.priceId)).size===e.items.length,"Subscription periods and Price identities must be unambiguous"),Li=A.strictObject({merchantInvoiceId:He,currency:Rr,subtotalMinor:De,discountMinor:De,taxMinor:De,totalMinor:De,paidMinor:De,periodStartsAt:et.nullable(),periodEndsAt:et.nullable(),lines:A.array(A.strictObject({merchantLineId:He,priceId:A.uuid(),quantity:A.number().int().nonnegative().max(1e6),subtotalMinor:A.number().int().min(-1e8).max(1e8),discountMinor:De,taxMinor:De,totalMinor:A.number().int().min(-1e8).max(2e8),periodStartsAt:et.nullable(),periodEndsAt:et.nullable()}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&(e.subtotalMinor<0?e.discountMinor===0&&e.taxMinor===0:e.discountMinor<=e.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&e.discountMinor<=e.subtotalMinor&&e.paidMinor===e.totalMinor&&new Set(e.lines.map(t=>t.merchantLineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.subtotalMinor,0)===e.subtotalMinor&&e.lines.reduce((t,n)=>t+n.discountMinor,0)===e.discountMinor&&e.lines.reduce((t,n)=>t+n.taxMinor,0)===e.taxMinor&&e.lines.reduce((t,n)=>t+n.totalMinor,0)===e.totalMinor,"A paid Invoice retains the complete financial amounts"),bn={provider:A.literal("merchant"),eventId:A.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:A.uuid(),occurredAt:et},Es=A.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),Ds=A.discriminatedUnion("type",[A.strictObject({...bn,type:A.literal("purchase.completed"),operationId:A.uuid(),merchantOrderId:He,paymentStatus:A.enum(["paid","trialing","no_payment_required"]),invoice:Li.nullable(),subscription:Vi.nullable()}).refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),A.strictObject({...bn,type:A.literal("purchase.closed"),operationId:A.uuid(),status:A.enum(["failed","expired","canceled"])}),A.strictObject({...bn,type:A.literal("subscription.observed"),operationId:A.uuid().nullable(),subscription:Vi}),A.strictObject({...bn,type:A.literal("subscription.change.completed"),operationId:A.uuid(),status:A.enum(["scheduled","applied"]),scheduledFor:et.nullable(),subscription:Vi,invoice:Li.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),A.strictObject({...bn,type:A.literal("invoice.paid"),merchantSubscriptionId:He,invoice:Li}),A.strictObject({...bn,type:A.literal("refund.updated"),operationId:A.uuid(),merchantRefundId:He,status:A.enum(["pending","succeeded","failed"]),amountMinor:De.refine(e=>e>0),currency:Rr})]);import{z as Jt}from"zod";var Bt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,qt=Jt.object({customerId:Jt.uuid(),sessionId:Jt.uuid(),accessToken:Jt.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Jt.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Jt.iso.datetime(),refreshExpiresAt:Jt.iso.datetime()});var yn=3,Ms="/integrations/indiana",ng="X-Indiana-Merchant-Bridge-Version",pd=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],dd=y.enum(pd),rg={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},Bs=y.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),qs=y.string().regex(/^[A-Za-z0-9_-]{1,64}$/),md=y.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),Ki=y.strictObject({keyId:qs,signingSecret:md}),fd=y.string().max(300).superRefine((e,t)=>{try{let n=new URL(e);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.port&&n.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(n.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(n.hostname))throw new Error("invalid origin")}catch{t.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(e=>new URL(e).origin),zs=y.array(dd).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),Ns=y.strictObject({bridgeVersion:y.literal(yn),projectId:y.uuid(),environmentId:y.uuid(),environment:y.enum(["sandbox","live"]),capabilities:zs,catalog:y.enum(["endpoint","static","none"]),billingEvents:y.array(Es).max(6),profiles:y.array(Ps).max(32).refine(e=>new Set(e).size===e.length,"Profiles must be unique")}).superRefine((e,t)=>{let n=r=>e.capabilities.includes(r);n("catalog")!==(e.catalog!=="none")&&t.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(n("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&t.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),Fs=y.strictObject({origin:fd,requiredCapabilities:zs}),Ad=y.strictObject({revision:y.number().int().nonnegative(),checkedAt:y.iso.datetime(),outcome:y.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:y.strictObject({ping:y.enum(["passed","failed","not_checked"]),authentication:y.enum(["passed","failed","not_checked"]),catalog:y.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:Ns.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),ig=y.strictObject({projectId:y.uuid(),environmentId:y.uuid(),environment:y.enum(["sandbox","live"]),execution:y.enum(["indiana","record_only"]),accountId:y.string().nullable(),revision:y.number().int().nonnegative(),authentication:y.strictObject({keyId:qs}).nullable(),secretStoreConfigured:y.boolean().optional(),connection:Fs.nullable(),check:Ad.nullable()});var Ts=y.strictObject({projectId:y.uuid(),environmentId:y.uuid()}),og=y.discriminatedUnion("action",[Ts.extend({action:y.literal("save"),revision:y.number().int().nonnegative(),connection:Fs,authentication:Ki.optional()}),Ts.extend({action:y.literal("check"),revision:y.number().int().nonnegative()})]),Br=y.strictObject({projectId:y.uuid(),environmentId:y.uuid(),environment:y.enum(["sandbox","live"])});function ag(e){return y.strictObject({bridgeVersion:y.literal(yn),requestId:y.uuid(),command:Bs,scope:Br,data:e})}var hd=y.strictObject({nativeUserId:y.string().min(1).max(128),session:qt.strict()}),gd=y.strictObject({nativeUserId:y.string().min(1).max(128),presentation:y.strictObject({customerId:y.uuid(),decisionId:y.uuid(),offeringVersionId:y.uuid(),paywallVersionId:y.uuid(),variant:y.string().min(1).max(128)}).nullable()}),bd=y.strictObject({decisionId:y.uuid(),eventId:y.uuid()}),Mr=y.strictObject({operationId:y.uuid(),customerId:y.uuid()}),qr=y.strictObject({scope:Br,operationId:y.uuid(),customerId:y.uuid(),confirmedAt:y.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:y.boolean(),instruction:ks}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),Gi=Qt,Ct=y.string().min(1).max(120),yd=y.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),xd=y.strictObject({revision:Ct,updatedAt:y.iso.datetime(),provider:y.literal("merchant"),items:y.array(y.strictObject({merchantProductId:Ct,productVersionId:y.uuid(),name:y.string().min(1).max(255),kind:y.enum(["subscription","credit_pack"]),merchantPriceId:Ct,currency:y.string().regex(/^[a-z]{3}$/),amountMinor:y.number().int().nonnegative().max(1e8),interval:y.enum(["one_time","month","year"]),intervalCount:y.literal(1),includedCredits:y.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:y.enum(["none","month"]),creditPolicyId:Ct,available:y.boolean()}).superRefine((e,t)=>{(e.kind==="credit_pack"&&(e.interval!=="one_time"||e.creditReset!=="none")||e.kind==="subscription"&&e.interval==="one_time"||e.available&&e.amountMinor===0)&&t.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Sd=y.strictObject({customerId:y.uuid(),revision:y.string().min(1).max(128),observedAt:y.iso.datetime(),subscriptions:y.array(y.strictObject({merchantSubscriptionId:Ct,merchantProductId:Ct,productVersionId:y.uuid().nullable(),status:y.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:y.iso.datetime().nullable(),currentPeriodEndsAt:y.iso.datetime().nullable(),cancelAtPeriodEnd:y.boolean(),scheduledChange:y.strictObject({effectiveAt:y.iso.datetime(),merchantProductId:Ct}).nullable()})).max(100),purchaseHistory:y.strictObject({complete:y.boolean(),hasPaidPurchase:y.boolean(),lastPaidAt:y.iso.datetime().nullable()}),balances:y.array(y.strictObject({bucketId:Ct,key:Ct,available:yd,expiresAt:y.iso.datetime().nullable(),nextResetAt:y.iso.datetime().nullable()})).max(100)}),sg=y.strictObject({bridgeVersion:y.literal(yn),requestId:y.uuid(),command:y.string().min(1).max(64),scope:Br,error:y.strictObject({code:y.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:y.string().min(1).max(500),retryable:y.boolean(),recovery:y.string().min(1).max(80)})}),Jn=y.strictObject({}),vd={"bridge.ping":y.strictObject({challenge:y.uuid()}),"bridge.describe":Jn,"session.create":Jn,"catalog.read":Jn,"customer.commerce.read":Jn,"presentation.resolve":Jn,"presentation.report":bd,"purchase.execute":Mr,"operation.read":Mr,"subscription.change":Mr,"refund.execute":Mr},cg={"bridge.ping":y.strictObject({challenge:y.uuid()}),"bridge.describe":Ns,"session.create":hd,"catalog.read":xd,"customer.commerce.read":Sd,"presentation.resolve":gd,"presentation.report":y.strictObject({queued:y.literal(!0)}),"purchase.execute":Gi,"operation.read":Rs,"subscription.change":Gi,"refund.execute":Gi},ug=y.strictObject({bridgeVersion:y.literal(yn),requestId:y.uuid(),scope:Br,command:Bs,data:y.unknown()}).superRefine((e,t)=>{vd[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});var Us="X-Indiana-Bridge-Signature",Vs="X-Indiana-Bridge-Key-Id";function Id(e){return new TextEncoder().encode(e)}function Ls(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}function $s(e,t,n){return Id(`indiana-merchant-bridge:${yn}
2
2
  ${t}
3
3
  POST
4
4
  ${Ms}
@@ -0,0 +1 @@
1
+ function f(e,o=()=>{}){let a=new WeakMap,n=0,s=t=>{let d=a.get(t);if(d!==void 0)return d;let i=[],r=t,c=!0;for(;r;){let l=a.get(r);if(l!==void 0){c=l;break}if(++n>8192||i.length>=256)throw Error("IAM render ancestry budget exceeded");if(i.push(r),o(),r.hasAttribute("hidden")||/(?:^|;)\s*display\s*:\s*none\s*(?:!\s*important\s*)?(?:;|$)/i.test(r.getAttribute("style")??"")){c=!1;break}r=r.parentElement}for(let l of i)a.set(l,c);return c};return(t,d)=>{let i=0,r=!1,c=e.querySelectorAll(t);for(let l=0;l<c.length;l++){let m=c[l];if(!m)throw Error("IAM render selection changed");s(m)&&(i++,m===d&&(r=!0)),o()}return d&&!r?0:i}}var p=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function y(e){if(!p(e)||Object.keys(e).some(t=>!["schemaVersion","renderKey","routeTemplate","selectors","present","absent"].includes(t))||e.schemaVersion!==1||typeof e.renderKey!="string"||!e.renderKey||e.renderKey.length>256||typeof e.routeTemplate!="string"||!e.routeTemplate.startsWith("/")||e.routeTemplate.length>2048||!Array.isArray(e.selectors)||e.selectors.length>512||e.selectors.some(t=>typeof t!="string"||t.length>512||!/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/.test(t))||!Array.isArray(e.present)||!Array.isArray(e.absent))throw new Error("Invalid IAM render guard");if(e.present.length===0)throw Error("IAM render needs positive source evidence");let o=e.selectors,a=e.present,n=e.absent,s=[...a,...n];if(new Set(o).size!==o.length||s.length!==o.length||new Set(s).size!==s.length||s.some(t=>typeof t!="number"||!Number.isInteger(t)||t<0||t>=o.length))throw new Error("Invalid IAM render signature");return{schemaVersion:1,renderKey:e.renderKey,routeTemplate:e.routeTemplate,selectors:e.selectors,present:e.present,absent:e.absent}}function u(e,o){let a=e.split("/").filter(Boolean),n="";for(let s of a)/^\[\[\.\.\.[^\[\]]+\]\]$/.test(s)?n+="(?:/[^/]+)*":/^\[\.\.\.[^\[\]]+\]$/.test(s)?n+="(?:/[^/]+)+":/^\[[^\[\]]+\]$/.test(s)?n+="/[^/]+":n+="/"+s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+(n?n+"/?":"/")+"$").test(o)&&!/[\[\]]/.test(o)}function b(e,o,a,n,s=f(o,n)){if(!u(e.routeTemplate,a))return!1;let t=new Set(e.present),d=!0;for(let i=0;i<e.selectors.length;i++){let r=s(e.selectors[i]);if(t.has(i)&&r>1)throw new Error("IAM render anchor is ambiguous");(t.has(i)?r!==1:r!==0)&&(d=!1),n()}return d}export{f as a,y as b,b as c};
@@ -1,4 +1,4 @@
1
- import{a as j,b as N,c as $,d as Y}from"./chunk-FXVZRIJ3.js";import{a as D}from"./chunk-DSPLGTQI.js";import{a as O}from"./chunk-AWZFL4HE.js";import{b as U,e as _,g as C}from"./chunk-XSVQHPQT.js";var te=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function re(e,t){let n=e,r=o=>Number.isInteger(o)&&o>=0;return!!n&&typeof n=="object"&&r(n.inserted)&&r(n.duplicates)&&r(n.skipped)&&Array.isArray(n.rejected)&&n.inserted+n.duplicates+n.skipped+n.rejected.length===t}function V(e){let t=[],n,r=(a,i)=>e.log?.(`${e.label} ${a}`,i);function o(a){n===void 0&&t.length&&(n=setTimeout(()=>{u()},a))}async function s(a){let i;try{i=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:a}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(p){return r("not sent",{error:p}),!1}if(i.status===408||i.status===429||i.status>=500)return r("not sent",{status:i.status}),!1;if(!i.ok)return r("rejected",{status:i.status,events:a.length}),!0;let f;try{f=await i.json()}catch{f=void 0}return re(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:i.status}),!1)}function u(){clearTimeout(n),n=void 0;let a=[];for(;t.length&&a.length<20&&(!a.length||te([...a,t[0]].map(i=>i.event))<=65536);)a.push(t.shift());return a.length?s(a.map(i=>i.event)).then(i=>{if(i)return o(1e3);let f=a.filter(p=>++p.attempts<5);f.length<a.length&&r("dropped after retries",{events:a.length-f.length}),t.unshift(...f),o(5e3)}):Promise.resolve()}return{push(a){t.push({event:a,attempts:0}),t.length>=20?u():o(1e3)},flush:u}}async function q(e,t,n,r={}){let o=r.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(o);let u=e.body.getReader(),a=[],i=0,f=!1,p=()=>{},g=new Promise((v,h)=>{p=()=>h(Error(o)),n.addEventListener("abort",p,{once:!0}),n.aborted&&p()});try{for(;;){let m=await Promise.race([u.read(),g]);if(m.done){f=!0;break}if(i+=m.value.byteLength,i>t)throw Error(o);a.push(m.value)}let v=new Uint8Array(i),h=0;for(let m of a)v.set(m,h),h+=m.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(v))}finally{n.removeEventListener("abort",p),f||u.cancel().catch(()=>{}),u.releaseLock()}}async function B(e,t){let n=e?.body;if(!n)return;let r=n.getReader(),o=0,s=!1,u,a=new Promise((p,g)=>{u=setTimeout(()=>g(Error("Exposure response timeout")),2e3)}),i=()=>{},f=new Promise((p,g)=>{i=()=>g(t?.reason),t?.addEventListener("abort",i,{once:!0}),t?.aborted&&i()});try{for(;;){let p=await Promise.race([r.read(),a,f]);if(p.done){s=!0;return}if(o+=p.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(u),t?.removeEventListener("abort",i),s||r.cancel().catch(()=>{}),r.releaseLock()}}var fe=2*1024*1024,J=256*1024;async function G(e,t,n,r){let o=()=>{},s=new Promise((u,a)=>{o=()=>a(r.reason),r.addEventListener("abort",o,{once:!0}),r.aborted&&o()});try{let u=e(t,{...n,signal:r});return u.then(a=>{r.aborted&&a.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{r.removeEventListener("abort",o)}}async function pe(e,t,n,r=!1){if(new TextEncoder().encode(n).byteLength>65536)throw Error("Exposure request budget");let o=new URL(t);o.searchParams.set("sdkVersion",O.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let a=await G(e,o.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:n,credentials:"omit",keepalive:r,redirect:"error"},s.signal);await B(a,s.signal)}finally{clearTimeout(u)}}function M(e){let t,n=!1;return{async read(r,o){if(n)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,a=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let i=await G(e,r,{cache:"no-cache",credentials:"omit",redirect:"error"},u),f=await q(i,o,u);return u.throwIfAborted(),f}finally{clearTimeout(a),t===s&&(t=void 0)}},destroy(){n=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}/*!
1
+ import{a as j,b as N,c as $,d as Y}from"./chunk-ZKSKBL4N.js";import{a as D}from"./chunk-DSPLGTQI.js";import{a as O}from"./chunk-22Z7JR4B.js";import{b as U,e as _,g as C}from"./chunk-XSVQHPQT.js";var te=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function re(e,t){let n=e,r=o=>Number.isInteger(o)&&o>=0;return!!n&&typeof n=="object"&&r(n.inserted)&&r(n.duplicates)&&r(n.skipped)&&Array.isArray(n.rejected)&&n.inserted+n.duplicates+n.skipped+n.rejected.length===t}function V(e){let t=[],n,r=(a,i)=>e.log?.(`${e.label} ${a}`,i);function o(a){n===void 0&&t.length&&(n=setTimeout(()=>{u()},a))}async function s(a){let i;try{i=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:a}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(p){return r("not sent",{error:p}),!1}if(i.status===408||i.status===429||i.status>=500)return r("not sent",{status:i.status}),!1;if(!i.ok)return r("rejected",{status:i.status,events:a.length}),!0;let f;try{f=await i.json()}catch{f=void 0}return re(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:i.status}),!1)}function u(){clearTimeout(n),n=void 0;let a=[];for(;t.length&&a.length<20&&(!a.length||te([...a,t[0]].map(i=>i.event))<=65536);)a.push(t.shift());return a.length?s(a.map(i=>i.event)).then(i=>{if(i)return o(1e3);let f=a.filter(p=>++p.attempts<5);f.length<a.length&&r("dropped after retries",{events:a.length-f.length}),t.unshift(...f),o(5e3)}):Promise.resolve()}return{push(a){t.push({event:a,attempts:0}),t.length>=20?u():o(1e3)},flush:u}}async function q(e,t,n,r={}){let o=r.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(o);let u=e.body.getReader(),a=[],i=0,f=!1,p=()=>{},g=new Promise((v,h)=>{p=()=>h(Error(o)),n.addEventListener("abort",p,{once:!0}),n.aborted&&p()});try{for(;;){let m=await Promise.race([u.read(),g]);if(m.done){f=!0;break}if(i+=m.value.byteLength,i>t)throw Error(o);a.push(m.value)}let v=new Uint8Array(i),h=0;for(let m of a)v.set(m,h),h+=m.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(v))}finally{n.removeEventListener("abort",p),f||u.cancel().catch(()=>{}),u.releaseLock()}}async function B(e,t){let n=e?.body;if(!n)return;let r=n.getReader(),o=0,s=!1,u,a=new Promise((p,g)=>{u=setTimeout(()=>g(Error("Exposure response timeout")),2e3)}),i=()=>{},f=new Promise((p,g)=>{i=()=>g(t?.reason),t?.addEventListener("abort",i,{once:!0}),t?.aborted&&i()});try{for(;;){let p=await Promise.race([r.read(),a,f]);if(p.done){s=!0;return}if(o+=p.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(u),t?.removeEventListener("abort",i),s||r.cancel().catch(()=>{}),r.releaseLock()}}var fe=2*1024*1024,J=256*1024;async function G(e,t,n,r){let o=()=>{},s=new Promise((u,a)=>{o=()=>a(r.reason),r.addEventListener("abort",o,{once:!0}),r.aborted&&o()});try{let u=e(t,{...n,signal:r});return u.then(a=>{r.aborted&&a.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{r.removeEventListener("abort",o)}}async function pe(e,t,n,r=!1){if(new TextEncoder().encode(n).byteLength>65536)throw Error("Exposure request budget");let o=new URL(t);o.searchParams.set("sdkVersion",O.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let a=await G(e,o.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:n,credentials:"omit",keepalive:r,redirect:"error"},s.signal);await B(a,s.signal)}finally{clearTimeout(u)}}function M(e){let t,n=!1;return{async read(r,o){if(n)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,a=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let i=await G(e,r,{cache:"no-cache",credentials:"omit",redirect:"error"},u),f=await q(i,o,u);return u.throwIfAborted(),f}finally{clearTimeout(a),t===s&&(t=void 0)}},destroy(){n=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}/*!
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 ne(e,t){let n,r;try{n=new URL(e),r=new URL(t)}catch{return t}return n.searchParams.forEach((o,s)=>{r.searchParams.has(s)||r.searchParams.set(s,o)}),r.toString()}function oe(e,t){let n=navigator.userAgent,r=new URLSearchParams(t.search),o={};for(let s of["source","medium","campaign","term","content"]){let u=r.get(`utm_${s}`);u!==null&&(o[`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(n)?"edge":/Chrome/.test(n)?"chrome":/Firefox/.test(n)?"firefox":/Safari/.test(n)?"safari":"unknown",deviceType:/Mobi/.test(n)?"mobile":"desktop",...o}}function ie(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(r=>!!r&&!["namespace","status","url","groups"].some(o=>Object.hasOwn(r,o))&&(r.hashVersion===void 0||r.hashVersion===2)&&typeof r.key=="string"&&Array.isArray(r.variations)&&r.variations.length>=2&&r.variations.every(o=>!!o&&typeof o.urlRedirect=="string")&&(r.urlPatterns===void 0||Array.isArray(r.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function be(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=$(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),r=M(async(c,d)=>{let l=await n(c,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),o=e.log?(c,d)=>D(e.log,c,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=j(e.deviceIdCookie??"indiana_did"),a=N(),i=null,f={...e.attributes??{}},p="",g=!1,v=!1,h=0,m=0,w=new Map,T=V({endpoint:`${s}/events`,fetch:n,log:o,label:"Exposure"}),P=T.flush,E={trackedExperiments:new Set,log:o,onExperimentViewed:(c,d)=>{e.trackExposures===!1||i?.trackExposures===!1||T.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...a?{sessionId:a}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:c.key,variationKey:d.key})}},H=()=>{E.url=location.href,E.attributes={...oe(u,location),...f}};function Q(c){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return c.variations.some(l=>{if(!l.urlRedirect)return!1;let y=new URL(l.urlRedirect);return y.protocol!==d.protocol||y.host!==d.host})}catch{return!0}}function K(c,d){let l=e.configuration?.snapshot?.generation,y=m,z=location.href;p=c;let W=e.navigate??(x=>location.replace(x)),Z=e.navigateDelay??(e.navigate?0:100),ee=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(x=>setTimeout(x,ee))]),new Promise(x=>setTimeout(x,Z))]).then(()=>{!g&&y===m&&location.href===z&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&W(c)})}function b(){if(!(!i||g||e.configuration&&!e.configuration.fresh)){H();for(let c of i.experiments){if(Q(c)){o?.("Auto experiment blocked",{id:c.key});continue}let d;try{d=C(c,E)}catch(l){o?.("Skipping page experiment",{id:c.key,error:String(l)});continue}if(w.set(c.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=c.persistQueryString?ne(location.href,d.value.urlRedirect):d.value.urlRedirect;U(l,c.urlPatterns??[])?o?.("Skipping redirect because original URL matches redirect URL",{id:c.key}):l!==p&&K(l,P())}break}}}}let R="",F=()=>{location.href!==R&&(m++,R=location.href,p="",b())},A,S;function X(){A??=Y(F),addEventListener("pagehide",L)}let L=()=>{P()};async function k(){if(g)return!1;let c=++h,d;try{d=e.configuration?await e.configuration.pageExperiments():await r.read(s,J)}catch(y){if(g||c!==h)return!1;throw y}if(g||c!==h)return!1;let l=ie(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return i?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),i=l,E.savedGroups=_(l.savedGroups),!0}function I(){g||(S??=e.configuration?.subscribe(()=>{!g&&e.configuration?.fresh&&k().then(c=>{c&&b()}).catch(c=>o?.("Page configuration unavailable",{error:String(c)}))}),X(),R=location.href)}return{async start(){v||g||(v=!0,await k()&&(I(),b()))},async refresh(){await k()&&(m++,v&&I(),p="",b())},setAttributes(c){m++,p="",f={...c},b()},getResults(){return new Map(w)},get generation(){return i?.generation??null},destroy(){g||(g=!0,h++,r.destroy(),S?.(),A?.(),removeEventListener("pagehide",L),i=null,w.clear(),P())}}}export{fe as a,pe as b,M as c,ne as d,oe as e,ie as f,be as g};
@@ -0,0 +1 @@
1
+ async function j(e,n,o){let t=new URL(e,n.baseURI),g=n.defaultView?.location.origin,d=/^(?:\/[^/?#]+)*\/\.well-known\/indiana\/releases\/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\.json$/.exec(t.pathname)?.[1];if(!d||t.origin!==g||t.search||t.hash||t.username||t.password)throw Error("Invalid IAM release URL");if(o.aborted)throw Error("IAM release cancelled");let s=new AbortController,w=()=>s.abort();o.addEventListener("abort",w,{once:!0});let i=setTimeout(w,2e3),m=[],r=0,f=()=>{},u=new Promise((c,v)=>{f=()=>v(Error("IAM release timeout")),s.signal.addEventListener("abort",f,{once:!0})}),p=!1,l;try{let c=await Promise.race([fetch(t,{credentials:"omit",redirect:"error",cache:"force-cache",signal:s.signal}).then(b=>{if(s.signal.aborted)throw b.body?.cancel().catch(()=>{}),Error("IAM release timeout");return b}),u]),v=c.headers.get("content-length");if(!c.ok||!/^application\/json(?:;|$)/i.test(c.headers.get("content-type")??"")||v!==null&&(!/^\d+$/.test(v)||Number(v)>512))throw c.body?.cancel().catch(()=>{}),Error("IAM release is unavailable");if(l=c.body?.getReader(),!l)throw Error("IAM release is unavailable");for(;;){let b=await Promise.race([l.read(),u]);if(b.done){p=!0;break}if(r+=b.value.length,r>512)throw Error("IAM release budget");m.push(b.value)}}finally{clearTimeout(i),o.removeEventListener("abort",w),s.signal.removeEventListener("abort",f),p||l?.cancel().catch(()=>{}),l?.releaseLock()}let A=new Uint8Array(r),I=0;for(let c of m)A.set(c,I),I+=c.length;let y=new TextDecoder("utf-8",{fatal:!0}).decode(A),a=JSON.parse(y);if(y.trim()!==JSON.stringify(a))throw Error("Noncanonical IAM release descriptor");if(!a||typeof a!="object"||Array.isArray(a)||Object.keys(a).sort().join(",")!=="format,manifestDigest,releaseId,schemaVersion"||Reflect.get(a,"format")!=="indiana-app-manifest-release"||Reflect.get(a,"schemaVersion")!==2||Reflect.get(a,"releaseId")!==d||!/^[a-f0-9]{64}$/.test(String(Reflect.get(a,"manifestDigest"))))throw Error("Invalid IAM release descriptor");return Reflect.get(a,"manifestDigest")}var M=new WeakMap;function D(e,n=document){if(!/^[a-f0-9]{64}$/.test(e))throw new Error("Invalid IAM manifest digest");let o="data-indiana-release",t=n.documentElement,g=()=>new Set((t.getAttribute(o)??"").split(/\s+/).filter(Boolean)),d=M.get(n);if(!d){let r=new Map,f=new MutationObserver(()=>{let u=g(),p=!1;for(let[l,A]of r)A.count&&!u.has(l)&&(u.add(l),p=!0);p&&t.setAttribute(o,[...u].join(" "))});f.observe(t,{attributes:!0,attributeFilter:[o]}),d={releases:r,observer:f},M.set(n,d)}let{releases:s,observer:w}=d,i=s.get(e);if(!i){let r=g();i={count:0,owned:!r.has(e)},s.set(e,i),r.add(e),t.setAttribute(o,[...r].join(" "))}i.count++;let m=!1;return{attributes:{indianaAppManifestRelease:e},destroy(){if(!m&&(m=!0,i.count--,!i.count&&(s.delete(e),s.size||(w.disconnect(),M.delete(n)),i.owned))){let r=g();r.delete(e),r.size?t.setAttribute(o,[...r].join(" ")):t.removeAttribute(o)}}}}var h=new Map,E=new Set,R=()=>{for(let e of[...E])e()},O=e=>h.has(e);function S(e){return E.add(e),()=>{E.delete(e)}}function k(e,n){if(h.has(e)&&h.get(e)!==n)throw new Error("A different Funnel owns this page experiment");return h.set(e,n),R(),()=>{h.get(e)===n&&(h.delete(e),R())}}export{j as a,D as b,O as c,S as d,k as e};