@tinkerlandai/longplay-sdk 0.10.19 → 0.10.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +6 -2
  3. package/README.zh-CN.md +4 -2
  4. package/dist/{ai-usage-DPGx5otD.d.ts → ai-usage-wsrO7M2I.d.ts} +1 -1
  5. package/dist/{api-G8EA_ueL.d.ts → api-BDUQ1udV.d.ts} +54 -5
  6. package/dist/{chunk-A7U4Z6EH.js → chunk-327BKZ6Q.js} +1 -1
  7. package/dist/chunk-5QS6C4AI.js +6 -0
  8. package/dist/chunk-6WFCEV3R.js +1 -0
  9. package/dist/{chunk-CCRBXW4M.js → chunk-BO5DJEMS.js} +1 -1
  10. package/dist/{chunk-YNMSSQQY.js → chunk-CRIFRDSD.js} +1 -1
  11. package/dist/{chunk-W2Z3UVW3.js → chunk-E6GGMHIY.js} +1 -1
  12. package/dist/{chunk-XXBN76NP.js → chunk-LE4UIZGR.js} +1 -1
  13. package/dist/chunk-P3EOONST.js +1 -0
  14. package/dist/chunk-S4LVODTE.js +1 -0
  15. package/dist/{chunk-LNSFRQ6G.js → chunk-SHEGSRUV.js} +1 -1
  16. package/dist/{content-E2OWWKDG.js → content-42ORME22.js} +1 -1
  17. package/dist/{funnel-local-client-DjvVzCfH.d.ts → funnel-local-client-DInl0SJb.d.ts} +5 -3
  18. package/dist/{funnel-process-client-bO9Wfumi.d.ts → funnel-process-client-DRztj2Cb.d.ts} +4 -2
  19. package/dist/funnel-runtime-host-FG4BOC3T.js +1 -0
  20. package/dist/index.d.ts +5 -5
  21. package/dist/index.js +1 -1
  22. package/dist/native-shell.js +1 -1
  23. package/dist/openrouter.d.ts +2 -2
  24. package/dist/openrouter.js +1 -1
  25. package/dist/page.js +1 -1
  26. package/dist/{paywall-OUIB7SVI.js → paywall-GVZTDHXI.js} +1 -1
  27. package/dist/react-native.d.ts +5 -5
  28. package/dist/react-native.js +1 -1
  29. package/dist/server.d.ts +4 -4
  30. package/dist/server.js +1 -1
  31. package/dist/visual.js +1 -1
  32. package/package.json +1 -1
  33. package/dist/chunk-2JBNOE2D.js +0 -1
  34. package/dist/chunk-5OD42XQS.js +0 -1
  35. package/dist/chunk-DVKZLOS7.js +0 -1
  36. package/dist/chunk-GSFNAB3W.js +0 -6
  37. package/dist/funnel-runtime-host-FOM4Z7ZK.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.20 — 2026-11-06
4
+
5
+ - **Breaking:** tracked events now declare their type. `track()` is unchanged, but direct `trackEvents` callers in JavaScript, Python and Go must send `kind`: `custom`, `experiment_exposure` or `feature_usage`. Exposure and Feature usage reports also name the Feature `generation` that produced them. Once the runtime serves this contract, earlier SDKs cannot record events. Wire protocol stays `0.10`, and only this route changes.
6
+ - One refused event no longer refuses its batch. `flush()` and `trackEvents` return `rejections`, one `{ eventUuid, reason }` for each refused event, and a refused event is not resent.
7
+ - Event queues no longer wait on an answer that cannot change. A batch the server refuses is dropped at once. During an outage a batch is retried with growing delays and given up after five attempts.
8
+ - iOS and Android send at most 16 KiB per request and hold 500 queued events, and a failed background delivery no longer fails `track`. A full queue raises `eventQueueFull` on iOS and `event_queue_full` on Android.
9
+ - Keep verified Customer attributes out of Remote evaluation. `id`, `externalUserId`, `createdAt`, `ageDays` and `subscription` passed for Local bucketing no longer break Remote Features for a Customer.
10
+
3
11
  ## 0.10.19 — 2026-11-06
4
12
 
5
13
  - Restore explicit confirmation for the original unconfirmed Paywall quote after interruption or reload, retaining request identity and the existing recovery path for confirmed purchases.
package/README.md CHANGED
@@ -215,7 +215,7 @@ Web IAM hosts opt in with `createIamFunnelProcessEntries`. React Native exports
215
215
 
216
216
  Funnel, standalone Features and page experiments evaluate independently. Matching App/environment, experiment definition, attributes, hash identity and Sticky state produce matching results; different refresh times or inputs may produce different variations. A Remote Funnel still evaluates on Longplay when its referenced code Experiment allows Local definition delivery. Accepted Funnel decisions retain their original results. There is no cross-feature result synchronization.
217
217
 
218
- For Customer-based evaluation, `id` means the Longplay Customer UUID (`customer.id`); `externalUserId` means the merchant account ID (`customer.externalUserId`). Choose the experiment's `hashAttribute` explicitly when creating it and preserve that meaning in every consumer. Do not put the merchant account ID into `attributes.id`. Supply local attributes from your trusted backend's Customer data; `identify(customerToken)` authenticates requests but does not populate local bucketing attributes. These attributes are evaluation data, not authorization.
218
+ For Customer-based evaluation, `id` means the Longplay Customer UUID (`customer.id`); `externalUserId` means the merchant account ID (`customer.externalUserId`). Choose the experiment's `hashAttribute` explicitly when creating it and preserve that meaning in every consumer. Do not put the merchant account ID into `attributes.id`. Supply local attributes from your trusted backend's Customer data; `identify(customerToken)` authenticates requests but does not populate local bucketing attributes. These attributes are evaluation data, not authorization. Local rules read them. Remote rules read the verified Customer, so the SDK leaves `id`, `externalUserId`, `createdAt`, `ageDays` and `subscription` out of Remote requests.
219
219
 
220
220
  `setAttributes()` replaces the complete object, so retain the bucketing fields on every update. Anonymous page/visual experiments instead default `id` and `deviceId` to the shared first-party device cookie; they do not automatically match an account-based experiment. An open visual client rereads its payload every 60 seconds while visible, so a stopped experiment or disabled delivery reverts without a page reload. Sticky capabilities differ by adapter: managed Local Run instructions receive server state, while pure local tools require their existing host persistence adapter for durable Sticky. No new shared state is introduced. See the [architecture boundary](../../docs/growthbook-sdk-delivery.md#cross-consumer-evaluation-and-bucketing-identity).
221
221
 
@@ -271,9 +271,13 @@ unsubscribe();
271
271
  flags.destroy();
272
272
  ```
273
273
 
274
+ `flush()` resolves with `inserted`, `duplicates`, `skipped` and `rejected` counts, plus `rejections`: one `{ eventUuid, reason }` for each event the server refused. A refused event is final and does not affect the rest of its batch. The queue holds 500 events; if the service stays unavailable, a batch is given up after five attempts so later events are not held back.
275
+
274
276
  The selected environment's integration settings control behavior events, experiment exposures and Feature usage independently. New environments enable behavior events, experiment exposures and Feature usage collection. `flush()` includes a `skipped` count for intentionally disabled collection. The database rechecks every batch, including direct SDK/server and Funnel ingestion. Running experiment/Bandit dependencies prevent incompatible collection changes. These controls do not delete history or affect commercial usage accounting.
275
277
 
276
- Flags default to local evaluation; Owner/Admin can switch each flag to server evaluation. Server-evaluated flags deliver only keys and results, using the caller's fallback until the first result arrives. Attribute changes immediately discard old results. List hashes are not a secrecy boundary. Local Funnels cannot depend on server-evaluated flags; mode switches also check active historical Runs. `identify` / `reset` release the previous identity's Feature instances and event queue.
278
+ Flags default to local evaluation; Owner/Admin can switch each flag to server evaluation. Server-evaluated flags deliver only keys and results, using the caller's fallback until the first result arrives. A failed evaluation keeps the fallback and reports to the `onError` option of `features()`. Attribute changes immediately discard old results. List hashes are not a secrecy boundary. Local Funnels cannot depend on server-evaluated flags; mode switches also check active historical Runs. `identify` / `reset` release the previous identity's Feature instances and event queue.
279
+
280
+ A direct `evaluateFeatures` call for a Customer sends request context only: a Customer session or a Server Key with `customerId` gets `INVALID_REQUEST` naming any of those five fields it sends. A Server Key without `customerId` evaluates its attributes as sent.
277
281
 
278
282
  Merchandise targeting resolves a trusted item in the selected App/environment. Register its attributes and maintain the
279
283
  item in Console, then pass a reference rather than item metadata. The SDK resolves the initial SKU before returning;
package/README.zh-CN.md CHANGED
@@ -187,7 +187,7 @@ Local/Remote 求值策略由每个 Funnel 决定。`createFunnelDecisionClient
187
187
 
188
188
  Funnel、独立 Feature 和页面实验各自求值、各自使用结果。App/环境、实验定义、属性、分桶身份及 Sticky 状态相同时结果应一致;刷新时间或输入不同时允许不同组。Remote Funnel 引用允许 Local 定义投递的代码 Experiment 时,仍由 Longplay 计算。已接受的 Funnel 决定保留原结果,不做跨功能结果同步。
189
189
 
190
- Customer 求值中的 `id` 是 Longplay Customer UUID(`customer.id`),`externalUserId` 是商户账号 ID(`customer.externalUserId`)。创建实验时明确选择 `hashAttribute`,每个消费方保持相同语义;不要把商户账号 ID 填进 `attributes.id`。本地属性来自可信后端给当前用户的 Customer 数据;`identify(customerToken)` 负责请求认证,不会自动补齐本地分桶属性。属性仅用于求值,不构成授权。
190
+ Customer 求值中的 `id` 是 Longplay Customer UUID(`customer.id`),`externalUserId` 是商户账号 ID(`customer.externalUserId`)。创建实验时明确选择 `hashAttribute`,每个消费方保持相同语义;不要把商户账号 ID 填进 `attributes.id`。本地属性来自可信后端给当前用户的 Customer 数据;`identify(customerToken)` 负责请求认证,不会自动补齐本地分桶属性。属性仅用于求值,不构成授权。本地规则读取这些属性;远程规则读取已验证的 Customer,因此 SDK 不会把 `id`、`externalUserId`、`createdAt`、`ageDays` 和 `subscription` 放进远程请求。
191
191
 
192
192
  `setAttributes()` 替换整个对象,每次更新都保留分桶字段。匿名页面/视觉实验默认的 `id` 和 `deviceId` 来自共用的第一方设备 cookie,不自动与账号实验同组。已打开的页面在可见时每 60 秒重新读取视觉配置,实验停止或关闭投放后无需刷新页面即可撤销修改。各适配器的 Sticky 能力有区别:共用 Run 的 Local 指令读取服务端状态,纯本地工具的持久 Sticky 使用已有宿主适配器,不新增共享状态。完整要求见[架构边界](../../docs/growthbook-sdk-delivery.md#cross-consumer-evaluation-and-bucketing-identity)。
193
193
 
@@ -243,7 +243,9 @@ unsubscribe();
243
243
  flags.destroy();
244
244
  ```
245
245
 
246
- 每个 flag 默认本地计算,Owner/Admin 可切换为服务器计算。服务器 flag 只下发键与结果,首次结果到达前使用调用方默认值;属性变化立即丢弃旧结果。名单哈希不等于保密,敏感规则应使用服务器计算。本地 Funnel 不得依赖服务器 flag,切换时也会校验仍在运行的历史版本。`identify` / `reset` 会释放旧身份的功能实例和事件队列。
246
+ 每个 flag 默认本地计算,Owner/Admin 可切换为服务器计算。服务器 flag 只下发键与结果,首次结果到达前使用调用方默认值;求值失败时保留默认值,并通过 `features()` 的 `onError` 选项报告;属性变化立即丢弃旧结果。名单哈希不等于保密,敏感规则应使用服务器计算。本地 Funnel 不得依赖服务器 flag,切换时也会校验仍在运行的历史版本。`identify` / `reset` 会释放旧身份的功能实例和事件队列。
247
+
248
+ 为 Customer 直接调用 `evaluateFeatures` 时只传请求上下文:Customer 会话或带 `customerId` 的 Server Key 传入上述五个字段时,返回写明字段名的 `INVALID_REQUEST`。不带 `customerId` 的 Server Key 按传入的属性求值。
247
249
 
248
250
  商品定向使用当前 App/环境的可信商品主档。在 Console 登记属性并维护商品后,传入 `merchandise: { id: "sku-outdoor" }` 引用;SDK 在返回 Feature 客户端之前解析商品。切换商品后,先调用 `setAttributes({ ...bucketingIdentity, merchandise: { id: "sku-indoor" } })`,再等待 `refreshRemote()` 后读取决策。商品实验使用服务端解析的 `merchandiseId`(内部 UUID),不能回退到人的分桶标识。请求中的商品属性不能覆盖主档。
249
251
 
@@ -1,5 +1,5 @@
1
1
  import { LanguageModelV4Usage, LanguageModelV4Middleware } from '@ai-sdk/provider';
2
- import { F as FoundationApi, A as ApiInput } from './api-G8EA_ueL.js';
2
+ import { F as FoundationApi, A as ApiInput } from './api-BDUQ1udV.js';
3
3
  import { z } from 'zod';
4
4
 
5
5
  declare const tokenCounts: z.ZodObject<{
@@ -1663,19 +1663,59 @@ declare const apiOperations: {
1663
1663
  readonly audience: "mixed";
1664
1664
  readonly request: z$1.ZodObject<{
1665
1665
  customerId: z$1.ZodOptional<z$1.ZodUUID>;
1666
- events: z$1.ZodArray<z$1.ZodObject<{
1666
+ events: z$1.ZodArray<z$1.ZodDiscriminatedUnion<[z$1.ZodObject<{
1667
+ kind: z$1.ZodLiteral<"custom">;
1668
+ name: z$1.ZodString;
1669
+ properties: z$1.ZodDefault<z$1.ZodRecord<z$1.ZodString, z$1.ZodJSONSchema>>;
1667
1670
  eventUuid: z$1.ZodUUID;
1668
1671
  timestamp: z$1.ZodISODateTime;
1669
- name: z$1.ZodString;
1670
1672
  merchandise: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
1671
1673
  id: z$1.ZodString;
1672
1674
  }, z$1.core.$strict>, z$1.ZodObject<{
1673
1675
  internalId: z$1.ZodUUID;
1674
1676
  }, z$1.core.$strict>]>>;
1675
- properties: z$1.ZodDefault<z$1.ZodRecord<z$1.ZodString, z$1.ZodJSONSchema>>;
1676
1677
  deviceId: z$1.ZodOptional<z$1.ZodString>;
1677
1678
  sessionId: z$1.ZodOptional<z$1.ZodString>;
1678
- }, z$1.core.$strict>>;
1679
+ }, z$1.core.$strict>, z$1.ZodObject<{
1680
+ kind: z$1.ZodLiteral<"experiment_exposure">;
1681
+ experimentId: z$1.ZodString;
1682
+ variationId: z$1.ZodString;
1683
+ generation: z$1.ZodString;
1684
+ eventUuid: z$1.ZodUUID;
1685
+ timestamp: z$1.ZodISODateTime;
1686
+ merchandise: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
1687
+ id: z$1.ZodString;
1688
+ }, z$1.core.$strict>, z$1.ZodObject<{
1689
+ internalId: z$1.ZodUUID;
1690
+ }, z$1.core.$strict>]>>;
1691
+ deviceId: z$1.ZodOptional<z$1.ZodString>;
1692
+ sessionId: z$1.ZodOptional<z$1.ZodString>;
1693
+ }, z$1.core.$strict>, z$1.ZodObject<{
1694
+ kind: z$1.ZodLiteral<"feature_usage">;
1695
+ feature: z$1.ZodString;
1696
+ value: z$1.ZodJSONSchema;
1697
+ source: z$1.ZodEnum<{
1698
+ override: "override";
1699
+ unknownFeature: "unknownFeature";
1700
+ defaultValue: "defaultValue";
1701
+ force: "force";
1702
+ experiment: "experiment";
1703
+ prerequisite: "prerequisite";
1704
+ cyclicPrerequisite: "cyclicPrerequisite";
1705
+ }>;
1706
+ ruleId: z$1.ZodString;
1707
+ variationId: z$1.ZodOptional<z$1.ZodString>;
1708
+ generation: z$1.ZodString;
1709
+ eventUuid: z$1.ZodUUID;
1710
+ timestamp: z$1.ZodISODateTime;
1711
+ merchandise: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
1712
+ id: z$1.ZodString;
1713
+ }, z$1.core.$strict>, z$1.ZodObject<{
1714
+ internalId: z$1.ZodUUID;
1715
+ }, z$1.core.$strict>]>>;
1716
+ deviceId: z$1.ZodOptional<z$1.ZodString>;
1717
+ sessionId: z$1.ZodOptional<z$1.ZodString>;
1718
+ }, z$1.core.$strict>], "kind">>;
1679
1719
  }, z$1.core.$strict>;
1680
1720
  readonly response: z$1.ZodObject<{
1681
1721
  requestId: z$1.ZodUUID;
@@ -1690,6 +1730,15 @@ declare const apiOperations: {
1690
1730
  duplicates: z$1.ZodNumber;
1691
1731
  rejected: z$1.ZodNumber;
1692
1732
  skipped: z$1.ZodNumber;
1733
+ rejections: z$1.ZodArray<z$1.ZodObject<{
1734
+ eventUuid: z$1.ZodUUID;
1735
+ reason: z$1.ZodEnum<{
1736
+ invalid_event: "invalid_event";
1737
+ invalid_merchandise: "invalid_merchandise";
1738
+ not_delivered: "not_delivered";
1739
+ reserved_name: "reserved_name";
1740
+ }>;
1741
+ }, z$1.core.$strict>>;
1693
1742
  analyticsConfig: z$1.ZodObject<{
1694
1743
  eventsEnabled: z$1.ZodBoolean;
1695
1744
  experimentViewsEnabled: z$1.ZodBoolean;
@@ -20438,4 +20487,4 @@ interface FoundationApi {
20438
20487
  readModelBenefit(input: ApiInput<"readModelBenefit">): Promise<ApiOutput<"readModelBenefit">>;
20439
20488
  }
20440
20489
 
20441
- export type { ApiInput as A, FoundationApi as F, InvoiceModeParams as I, OfferingItem as O, InvoiceModeParamsInput as a };
20490
+ export type { ApiInput as A, FoundationApi as F, InvoiceModeParams as I, OfferingItem as O, ApiOutput as a, InvoiceModeParamsInput as b };
@@ -1,4 +1,4 @@
1
- import{a as $,b as N,c as J,d as q}from"./chunk-LNSFRQ6G.js";import{a as _}from"./chunk-DSPLGTQI.js";import{a as P}from"./chunk-CCRBXW4M.js";import{jb as D}from"./chunk-GSFNAB3W.js";import{I as C,J as O,L as j}from"./chunk-4SWGHICJ.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
1
+ import{a as $,b as N,c as J,d as q}from"./chunk-SHEGSRUV.js";import{a as _}from"./chunk-DSPLGTQI.js";import{a as P}from"./chunk-BO5DJEMS.js";import{kb as D}from"./chunk-5QS6C4AI.js";import{I as C,J as O,L as j}from"./chunk-4SWGHICJ.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
2
2
  Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
3
  plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
4
  */function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};