@gamepropel/sdk-crazygames 0.0.0-stage → 1.0.0
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/README.md +131 -2
- package/SERVER_HANDOFF.md +29 -0
- package/VALIDATION.md +39 -0
- package/dist/commonjs/index.js +5 -0
- package/dist/commonjs/index.js.map +1 -0
- package/dist/commonjs/package.json +1 -0
- package/dist/index.js +2224 -0
- package/dist/index.js.map +1 -0
- package/dist/types/crazygames/src/ads.d.ts +26 -0
- package/dist/types/crazygames/src/host.d.ts +37 -0
- package/dist/types/crazygames/src/index.d.ts +68 -0
- package/dist/types/crazygames/src/storage.d.ts +10 -0
- package/dist/types/crazygames/src/transport.d.ts +8 -0
- package/dist/types/rest-api/src/browser-storage.d.ts +42 -0
- package/dist/types/rest-api/src/core-client.d.ts +250 -0
- package/dist/types/rest-api/src/dda.d.ts +22 -0
- package/dist/types/rest-api/src/event-queue-store.d.ts +20 -0
- package/dist/types/rest-api/src/http-url.d.ts +8 -0
- package/dist/types/rest-api/src/sha256.d.ts +1 -0
- package/dist/types/rest-api/src/types.d.ts +244 -0
- package/dist/types/rest-api/src/utf8.d.ts +2 -0
- package/package.json +34 -4
package/README.md
CHANGED
|
@@ -1,3 +1,132 @@
|
|
|
1
|
-
#
|
|
1
|
+
# GamePropel CrazyGames SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Independent HTML5 v3 adapter, package `@gamepropel/sdk-crazygames`, entry
|
|
4
|
+
`GamePropelCrazyGamesClient`.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
npm install @gamepropel/sdk-crazygames
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Initialize
|
|
11
|
+
|
|
12
|
+
Load the official portal SDK before your game code:
|
|
13
|
+
|
|
14
|
+
```html
|
|
15
|
+
<script src="https://sdk.crazygames.com/crazygames-sdk-v3.js"></script>
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { GamePropelCrazyGamesClient } from "@gamepropel/sdk-crazygames";
|
|
20
|
+
|
|
21
|
+
const gamePropel = await GamePropelCrazyGamesClient.init({
|
|
22
|
+
baseUrl: yourGamePropelBaseUrl,
|
|
23
|
+
gameKey: yourExistingClientGameKey,
|
|
24
|
+
appVersion: "1.0.0",
|
|
25
|
+
});
|
|
26
|
+
await gamePropel.waitForReady(5000);
|
|
27
|
+
gamePropel.tracker.trackLevelStart({ levelId: "1" });
|
|
28
|
+
const difficulty = gamePropel.executor("difficulty").number("difficulty", 1);
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`init()` waits for the official SDK initialization (10 seconds by default).
|
|
32
|
+
An unavailable/disabled portal SDK rejects explicitly. `waitForReady()` then
|
|
33
|
+
waits for GamePropel identity, queue recovery and configuration. Parameter
|
|
34
|
+
experiments and JSON configuration files work; this first version does not
|
|
35
|
+
download/execute remote scripts or include QuickJS/WASM or multiplayer.
|
|
36
|
+
The wire platform is always `crazygames`; the server must accept this platform
|
|
37
|
+
before production use. See [server handoff](./SERVER_HANDOFF.md).
|
|
38
|
+
|
|
39
|
+
The caller remains responsible for CrazyGames' `gameplayStart/Stop`, loading,
|
|
40
|
+
mute settings and any account/progress integration. SDK initialization cannot
|
|
41
|
+
infer whether the player has entered gameplay, opened a menu or paused a level.
|
|
42
|
+
|
|
43
|
+
## Video ads
|
|
44
|
+
|
|
45
|
+
CrazyGames has one shared video slot and does not require a TapTap-style ad unit
|
|
46
|
+
ID. Register separate GamePropel placements with the correct static ad type.
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
const revive = gamePropel.createAdSpace({ adType: "rewarded" });
|
|
50
|
+
pauseGameAndMute(); // Also block gameplay while the ad request is pending.
|
|
51
|
+
try {
|
|
52
|
+
await revive.show(yourRegisteredRewardPlacementId, {
|
|
53
|
+
onStarted() { pauseGameAndMute(); },
|
|
54
|
+
onFinished() { grantRevive(); resumeGameAndAudio(); },
|
|
55
|
+
onError(error) { resumeGameAndAudio(); console.log(error.code); },
|
|
56
|
+
});
|
|
57
|
+
} catch (error) {
|
|
58
|
+
// Handles unavailable ads, native rejections, busy slots and timeouts.
|
|
59
|
+
resumeGameAndAudio(); // Also handles validation or a busy video slot.
|
|
60
|
+
// Ensure the game can continue without a rewarded ad.
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const betweenLevels = gamePropel.createAdSpace({ adType: "midgame" });
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`show()` resolves on native `adFinished` and rejects on `adError`, native Promise
|
|
67
|
+
rejection, cancellation or timeout (default 180 seconds). It never retries ads.
|
|
68
|
+
Mute/pause the game while requesting as required by CrazyGames, and restore it
|
|
69
|
+
on failure as well as completion. Business callbacks cannot prevent telemetry.
|
|
70
|
+
|
|
71
|
+
* Native `adStarted` records one `ad_view` and immediately flushes it. Repeated
|
|
72
|
+
callbacks are ignored. An error before start does not create an impression.
|
|
73
|
+
* There is no documented per-impression revenue or ad track ID. Events use
|
|
74
|
+
`network=crazygames`, `revenue=0`, `revenueStatus=unavailable`, and
|
|
75
|
+
`hostAdType=rewarded|midgame`. Zero is a compatibility placeholder, not settled
|
|
76
|
+
income. No caller-supplied `trackId` is forwarded.
|
|
77
|
+
* Both ad types and all GamePropel instances share a host lock, avoiding callback
|
|
78
|
+
replacement by overlapping requests. Only ads requested through these handles
|
|
79
|
+
are captured automatically; arbitrary direct portal calls are not intercepted.
|
|
80
|
+
* Local portal test ads force `isDebug=true`. They must not count as production
|
|
81
|
+
impressions/revenue. Basic Launch does not enable production ads.
|
|
82
|
+
|
|
83
|
+
## Sessions, time and persistence
|
|
84
|
+
|
|
85
|
+
* Ordinary batches flush every 5 seconds, up to 20 events / 48 KiB per request;
|
|
86
|
+
queue limit defaults to 500. `ad_view` and `session_end` have urgent delivery.
|
|
87
|
+
* `visibilitychange(hidden)` and `pagehide` enqueue a durable `session_end`
|
|
88
|
+
snapshot and attempt `fetch(..., {keepalive:true})`. Repeated hide callbacks
|
|
89
|
+
within the same hidden period are deduplicated. `blur` is not treated as exit.
|
|
90
|
+
* Returning keeps the existing session. Only initialization or explicit
|
|
91
|
+
`tracker.newSession()` creates a new session; `newSession()` closes the old
|
|
92
|
+
unfinished session first. Multiple end snapshots report cumulative time;
|
|
93
|
+
aggregate by the maximum per session/context, not the sum.
|
|
94
|
+
* `getForegroundTimeMs()` is a pure memory read of a one-second sampled clock.
|
|
95
|
+
Each sample contributes at most one second. Background and suspended gaps
|
|
96
|
+
are excluded, including gaps during ads; no exact full ad duration is claimed.
|
|
97
|
+
* Queue chunks commit before their directory. Offline tails, IDs, timestamps
|
|
98
|
+
and original contexts recover on the next start. A process kill before a
|
|
99
|
+
browser storage transaction commits can still lose that final uncommitted
|
|
100
|
+
tail. Neither callbacks nor last-moment HTTP completion are guaranteed.
|
|
101
|
+
* Default storage uses a separate IndexedDB database `gamepropel-crazygames`,
|
|
102
|
+
store `telemetry`. It does not use `CrazyGames.SDK.data` or localStorage
|
|
103
|
+
fallback. It rejects failed persistent operations rather than acknowledging
|
|
104
|
+
an in-memory queue as durable. If IndexedDB is disabled, provide a durable
|
|
105
|
+
device-local `storage` adapter; initialization otherwise fails observably.
|
|
106
|
+
Portal cloud-save/APS behavior must still be verified in Preview; the SDK
|
|
107
|
+
does not claim that a dedicated database alone guarantees APS exclusion.
|
|
108
|
+
|
|
109
|
+
Optional options include `crazyGames` (host injection), `fetchImpl`, `storage`,
|
|
110
|
+
`browserStorage.indexedDB`, `autoLifecycle`, `autoSessionLifecycle`,
|
|
111
|
+
`requestTimeoutMs` and `hostInitTimeoutMs`. Device OS/version, browser, locale,
|
|
112
|
+
device type and application type come from the portal's `user.systemInfo`.
|
|
113
|
+
No login prompt is shown and no unverified portal user ID is auto-linked.
|
|
114
|
+
|
|
115
|
+
## Validation
|
|
116
|
+
|
|
117
|
+
```sh
|
|
118
|
+
npm run check:crazygames
|
|
119
|
+
npm run check:crazygames:pack
|
|
120
|
+
npm run check:crazygames:probe
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
The probe serves a local test endpoint and loads the official v3 SDK. It creates
|
|
124
|
+
no production game and sends no events to GamePropel's live services. Use the
|
|
125
|
+
developer portal's Preview to validate real ads, desktop/mobile lifecycle,
|
|
126
|
+
iframe storage and cloud-save behavior before shipping. Browser integration
|
|
127
|
+
tests run locally, outside CI.
|
|
128
|
+
|
|
129
|
+
Official references: [initialization](https://docs.crazygames.com/sdk/intro/),
|
|
130
|
+
[video ads](https://docs.crazygames.com/sdk/video-ads/),
|
|
131
|
+
[device info](https://docs.crazygames.com/sdk/user/#system-info),
|
|
132
|
+
[data](https://docs.crazygames.com/sdk/data/).
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# GamePropel CrazyGames 服务端对接
|
|
2
|
+
|
|
3
|
+
客户端包:`@gamepropel/sdk-crazygames@1.0.0`,入口 `GamePropelCrazyGamesClient`。
|
|
4
|
+
客户端与服务端分别发布;服务端由负责该部分的 agent 接续上线。
|
|
5
|
+
|
|
6
|
+
1. 配置、归因、诊断等使用 Platform 的接口及游戏平台/Key 校验允许 `crazygames`。
|
|
7
|
+
SDK 不会伪装成 `web`(历史 TapTap H5)或 `wechat`。现有域名、路由前缀、
|
|
8
|
+
`X-GameAlgo-Key`、事件格式、Key 格式均沿用。事件通过 Context 关联平台。
|
|
9
|
+
2. 参数实验和 JSON 配置支持;`device.runtime=crazygames`、
|
|
10
|
+
`device.remoteScripts=false`。首版不分配远端脚本为唯一生效策略。
|
|
11
|
+
3. `device` 可包含官方 systemInfo 的 OS、OS 版本、设备类型、浏览器/版本、
|
|
12
|
+
locale、countryCode、applicationType,以及 crazyGamesEnvironment。
|
|
13
|
+
操作系统与投放平台是两个维度;环境 `local` 的数据强制标为 debug。
|
|
14
|
+
4. 注册 GamePropel 广告位,静态 adType 对应宿主的 rewarded/midgame。
|
|
15
|
+
曝光在 adStarted 时产生,携带 adPlacementId、network=crazygames、
|
|
16
|
+
hostAdType、hostEnvironment、revenueStatus=unavailable、revenue=0。
|
|
17
|
+
公开 SDK 没有单次广告收益金额或 trackId;不要把 0 解释为已知实际收入,
|
|
18
|
+
不要要求 trackId 才接收曝光,也不要由缺失收益推算实际 eCPM。
|
|
19
|
+
5. session_end 为累计前台时长快照;同 Context/session 可多次上报。
|
|
20
|
+
时长取最大值,不能求和。回到游戏不会自动创建新 session。
|
|
21
|
+
6. CLI 下载配置、平台枚举及接入示例增加独立包,保留现有平台与统计历史。
|
|
22
|
+
|
|
23
|
+
验证范围:本地协议、队列/生命周期单元测试及安装包检查;官方 v3 的 localhost
|
|
24
|
+
探针用于验证宿主初始化和模拟广告。生产域名 CORS、实际广告、移动 App/iframe
|
|
25
|
+
生命周期和 APS 云存档对设备标识/待发队列的影响,需要在 CrazyGames Preview 联调。
|
|
26
|
+
客户端默认单独 IndexedDB,不主动写 SDK Data Module 或 localStorage;这不是
|
|
27
|
+
已经确认平台不会同步该数据库的保证。
|
|
28
|
+
|
|
29
|
+
本机具体结果见 [验证记录](./VALIDATION.md)。
|
package/VALIDATION.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# CrazyGames 客户端验证记录
|
|
2
|
+
|
|
3
|
+
2026-11-12,本机 Node 24 / Chrome,客户端 `1.0.0` 的发布前验证;npm 可用版本以 registry 为准。
|
|
4
|
+
|
|
5
|
+
## 自动检查
|
|
6
|
+
|
|
7
|
+
* CrazyGames:11 项通过,覆盖官方宿主初始化的等待/超时、平台字段固定、
|
|
8
|
+
设备信息、参数/JSON 配置、广告开始去重、失败/取消/并发互斥、生命周期、
|
|
9
|
+
1 秒计时、5 秒发送、离线恢复、部分接受不重试及持久化/网络异常。
|
|
10
|
+
* 共享核心:71 项通过。
|
|
11
|
+
* TapTap H5:134 项通过,Web 兼容入口、打包及生产 bundle 检查通过。
|
|
12
|
+
* 微信:8 项通过,安装包检查通过。
|
|
13
|
+
* CrazyGames 安装包:ESM、CommonJS、TypeScript、独立安装及本机真实 HTTP
|
|
14
|
+
校验通过。不包含 QuickJS/WASM、Node 运行时或 TapTap 广告/TapDB 实现。
|
|
15
|
+
|
|
16
|
+
## 官方 SDK 本地浏览器探针
|
|
17
|
+
|
|
18
|
+
加载自 `https://sdk.crazygames.com/crazygames-sdk-v3.js`,使用其真实
|
|
19
|
+
`environment=local` 模式。GamePropel 配置和事件发送到本机协议模拟服务,
|
|
20
|
+
未创建线上游戏、未发送生产数据,事件均为 debug。
|
|
21
|
+
|
|
22
|
+
实际操作验证:
|
|
23
|
+
|
|
24
|
+
1. 宿主初始化成功,参数读取成功。
|
|
25
|
+
2. 激励广告收到 adStarted、adFinished,仅产生一次 ad_view。
|
|
26
|
+
3. 插屏广告收到 adStarted、adFinished,仅产生一次 ad_view。
|
|
27
|
+
4. 页面隐藏/恢复时 session 不变;重新加载时创建新 session,用户身份不变。
|
|
28
|
+
5. 服务端模拟 503 后产生关卡事件,重新加载页面;恢复上报后,原关卡事件
|
|
29
|
+
和 session_end 从真实 IndexedDB 队列恢复,事件保留旧 session。
|
|
30
|
+
|
|
31
|
+
本地广告是 CrazyGames 官方模拟覆盖层,无法证明生产广告展示/填充或收益。
|
|
32
|
+
|
|
33
|
+
## 仍需平台 Preview 联调
|
|
34
|
+
|
|
35
|
+
* 服务端接受 `platform=crazygames` 和生产域名 CORS。
|
|
36
|
+
* 实际 rewarded/midgame 回调、广告拦截、无填充及 Basic Launch 禁用行为。
|
|
37
|
+
* 移动端浏览器/平台 App、锁屏、广告中退后台、iframe 生命周期。
|
|
38
|
+
* APS/云存档是否会同步独立遥测数据库;目前仅确认本 SDK 不主动使用
|
|
39
|
+
CrazyGames Data Module 或 localStorage。不能据此声称已保证跨设备隔离。
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e){if(typeof TextEncoder<`u`)return new TextEncoder().encode(e);let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>=55296&&r<=56319){let t=e.charCodeAt(n+1);t>=56320&&t<=57343?(r=65536+(r-55296<<10)+t-56320,n++):r=65533}else r>=56320&&r<=57343&&(r=65533);r<128?t.push(r):r<2048?t.push(192|r>>6,128|r&63):r<65536?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return new Uint8Array(t)}function t(t){let i=e(t),a=i.length*8,o=Math.ceil((i.length+9)/64)*64,s=new Uint8Array(o);s.set(i),s[i.length]=128;let c=new DataView(s.buffer);c.setUint32(o-8,Math.floor(a/4294967296)),c.setUint32(o-4,a>>>0);let l=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),u=new Uint32Array(64);for(let e=0;e<o;e+=64){for(let t=0;t<16;t+=1)u[t]=c.getUint32(e+t*4);for(let e=16;e<64;e+=1){let t=u[e-15],r=u[e-2],i=n(t,7)^n(t,18)^t>>>3,a=n(r,17)^n(r,19)^r>>>10;u[e]=u[e-16]+i+u[e-7]+a>>>0}let[t,i,a,o,s,d,f,p]=l;for(let e=0;e<64;e+=1){let c=n(s,6)^n(s,11)^n(s,25),l=s&d^~s&f,m=p+c+l+r[e]+u[e]>>>0,h=(n(t,2)^n(t,13)^n(t,22))+(t&i^t&a^i&a)>>>0;p=f,f=d,d=s,s=o+m>>>0,o=a,a=i,i=t,t=m+h>>>0}l[0]=l[0]+t>>>0,l[1]=l[1]+i>>>0,l[2]=l[2]+a>>>0,l[3]=l[3]+o>>>0,l[4]=l[4]+s>>>0,l[5]=l[5]+d>>>0,l[6]=l[6]+f>>>0,l[7]=l[7]+p>>>0}return[...l].map(e=>e.toString(16).padStart(8,`0`)).join(``)}function n(e,t){return e>>>t|e<<32-t}var r=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function i(e){if(typeof URL<`u`){let t=new URL(e);if(!/^https?:$/.test(t.protocol)||t.username||t.password)throw Error(`Invalid GameAlgo HTTP URL`);return{origin:t.origin,pathname:t.pathname,href:t.href}}let t=/^(https?):\/\/([^\s/?#@]+)(\/[^?#\s]*)?(?:\?[^#\s]*)?(?:#[^\s]*)?$/i.exec(e);if(!t)throw Error(`Invalid GameAlgo HTTP URL`);let n=t[1].toLowerCase(),r=`${n}://${t[2].toLowerCase().replace(n===`https`?/:443$/:/:80$/,``)}`,i=o(t[3]||`/`);return{origin:r,pathname:i,href:r+i}}function a(e,t){if(typeof URL<`u`)return new URL(e,t.href).href;if(/^https?:\/\//i.test(e))return i(e).href;if(/^[a-z][a-z0-9+.-]*:/i.test(e)||e.startsWith(`//`))throw Error(`Invalid GameAlgo HTTP URL`);let n=e.startsWith(`/`)?e:t.pathname.replace(/[^/]*$/,``)+e;return t.origin+o(n)}function o(e){let t=[];for(let n of e.split(`/`))n===`..`?t.pop():n!==`.`&&t.push(n);return t.join(`/`)||`/`}function s(e){"@babel/helpers - typeof";return s=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},s(e)}function c(e,t){if(s(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(s(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){var t=c(e,`string`);return s(t)==`symbol`?t:t+``}function u(e,t,n){return(t=l(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var d=10,f=class{constructor(e,t,n,r={},i){var a;u(this,`executor`,void 0),u(this,`storage`,void 0),u(this,`storageKey`,void 0),u(this,`recentWindowSize`,void 0),u(this,`logger`,void 0),u(this,`statePromise`,void 0),u(this,`writeTail`,Promise.resolve()),this.executor=e,this.storage=t,this.storageKey=(a=r.storageKey)==null?n:a,this.recentWindowSize=v(r.recentWindowSize),this.logger=i,this.statePromise=this.loadState()}async recordBehavior(e,t=1){let n=_(e);if(!Number.isFinite(t)||t<=0)throw Error(`DDA behavior amount must be greater than 0`);await this.mutate(e=>{var r,i;e.current[n]=((r=e.current[n])==null?0:r)+t,e.lifetime[n]=((i=e.lifetime[n])==null?0:i)+t})}async completeStep(e){await this.mutate(t=>{t.recentSteps.push({...x(e)?{stepId:x(e)}:{},behaviors:{...t.current}}),t.recentSteps.length>this.recentWindowSize&&t.recentSteps.splice(0,t.recentSteps.length-this.recentWindowSize),t.current={},t.completedSteps+=1})}async reset(e=`all`){await this.mutate(t=>{if(e===`all`)Object.assign(t,p());else if(e===`current`)t.current={};else if(e===`recent`)t.recentSteps=[];else throw Error(`Unsupported DDA reset scope: ${e}`)})}async snapshot(e={}){await this.writeTail;let t=await this.statePromise,n=g(t.recentSteps);return{context:e,behavior:{current:{...t.current},recent:n,lifetime:{...t.lifetime},recentSteps:t.recentSteps.map(e=>({...e.stepId?{stepId:e.stepId}:{},behaviors:{...e.behaviors}})),completedSteps:t.completedSteps,windowSize:this.recentWindowSize}}}async decide(e={}){try{let t=await this.executor.execute(await this.snapshot(e));if(!t)return b(`executor_not_ready`);let n=y(t.payload);return n?{adjustment:n,payload:t.payload,diagnostics:t.diagnostics,assignment:t.assignment,isFallback:!1}:b(`invalid_adjustment`,t)}catch(e){var t;return(t=this.logger)==null||t.call(this,`[GameAlgoSDK] DDA decision failed: ${e instanceof Error?e.message:String(e)}`),b(`execution_failed`)}}async loadState(){try{var e;let t=await((e=this.storage)==null?void 0:e.getItem(this.storageKey));if(!t)return p();let n=m(JSON.parse(t));return n.recentSteps.length>this.recentWindowSize&&n.recentSteps.splice(0,n.recentSteps.length-this.recentWindowSize),n}catch(e){var t;return(t=this.logger)==null||t.call(this,`[GameAlgoSDK] DDA state load failed; using empty state: ${e instanceof Error?e.message:String(e)}`),p()}}async mutate(e){let t=this.writeTail.then(async()=>{var t;let n=await this.statePromise;e(n),await((t=this.storage)==null?void 0:t.setItem(this.storageKey,JSON.stringify(n)))});return this.writeTail=t.catch(()=>void 0),t}};function p(){return{schemaVersion:1,current:{},lifetime:{},recentSteps:[],completedSteps:0}}function m(e){if(!e||typeof e!=`object`||Array.isArray(e))return p();let t=e,n=Array.isArray(t.recentSteps)?t.recentSteps.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e;return[{...x(t.stepId)?{stepId:x(t.stepId)}:{},behaviors:h(t.behaviors)}]}):[];return{schemaVersion:1,current:h(t.current),lifetime:h(t.lifetime),recentSteps:n,completedSteps:typeof t.completedSteps==`number`&&Number.isFinite(t.completedSteps)&&t.completedSteps>=0?Math.floor(t.completedSteps):0}}function h(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))n&&typeof r==`number`&&Number.isFinite(r)&&r>0&&(t[n]=r);return t}function g(e){let t={};for(let r of e){var n;for(let[e,i]of Object.entries(r.behaviors))t[e]=((n=t[e])==null?0:n)+i}return t}function _(e){let t=x(e);if(!t)throw Error(`DDA behavior type is required`);if(t.length>128)throw Error(`DDA behavior type must be at most 128 characters`);return t}function v(e){if(e===void 0)return d;if(!Number.isInteger(e)||e<1||e>100)throw Error(`DDA recentWindowSize must be an integer between 1 and 100`);return e}function y(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.adjustment;return t===`increase`||t===`keep`||t===`decrease`?t:void 0}function b(e,t){return{adjustment:`keep`,payload:{adjustment:`keep`},diagnostics:{fallback:!0,reason:e},...t?{assignment:t.assignment}:{},isFallback:!0}}function x(e){return typeof e==`string`&&e.trim()?e.trim():void 0}var S=`gamealgo-event-chunks-v2`,C=class{constructor(e,n){u(this,`prefix`,void 0),u(this,`chunks`,[]),u(this,`locations`,new Map),u(this,`contexts`,new Map),u(this,`dirty`,new Set),u(this,`revision`,0),u(this,`sequence`,0),u(this,`reloadAfterFailure`,!1),u(this,`storage`,void 0),u(this,`key`,void 0);let r=e;this.storage=r.setItemDurably?{getItem:t=>{var n;return((n=r.getItemDurably)==null?e.getItem:n).call(e,t)},setItem:(t,n)=>r.setItemDurably.call(e,t,n),removeItem:t=>{var n,i;return(n=(i=r.removeItemDurably)==null?e.removeItem:i)==null?void 0:n.call(e,t)}}:e,this.key=n,this.prefix=`gamealgo:queue-chunk:${t(n)}`}reset(){this.chunks=[],this.locations.clear(),this.contexts.clear(),this.dirty.clear(),this.revision=0,this.sequence=0,this.reloadAfterFailure=!1}async load(e){var t,n;let r=e==null?await this.storage.getItem(this.key):e;if(!r)return[];let i;try{i=JSON.parse(r)}catch{}if((i==null?void 0:i.format)!==S){let e=r.split(`
|
|
2
|
+
`).filter(Boolean).map(e=>JSON.parse(e)).filter(e=>e.eventId&&e.userId&&e.sessionId&&e.eventType);for(let t of e)this.upsert(t);return e}this.revision=(t=i.revision)==null?0:t;let a=[];for(let e of(n=i.chunks)==null?[]:n){let t=this.chunks.length,n={ref:e,bank:Number(e.key.slice(-1))};this.chunks.push(n);try{var o;let r=JSON.parse((o=await this.storage.getItem(e.key))==null?`null`:o);if((r==null?void 0:r.revision)!==e.revision||!Array.isArray(r.rows))continue;let i=new Map,s=r.rows.map(e=>{let t=JSON.parse(e.event);if(!t.eventId||!t.sessionId)throw Error(`invalid stored event`);return{row:e,event:t,id:t.eventId}});for(let{row:e,event:n,id:r}of s)i.set(r,e),a.push({sequence:e.sequence,event:n}),this.locations.set(r,t),this.contexts.set(r,n.contextId),this.sequence=Math.max(this.sequence,e.sequence);n.rows=i}catch{}}return a.sort((e,t)=>e.sequence-t.sequence).map(e=>e.event)}upsert(e){var t,n;let r=e.eventId,i=this.locations.get(r);if(i!==void 0&&this.contexts.get(r)===e.contextId)return;let a=i;a===void 0&&(a=this.chunks.findIndex(e=>e.rows!==void 0&&e.rows.size<100),a<0&&(a=this.chunks.length,this.chunks.push({rows:new Map,bank:1})));let o=this.chunks[a].rows;o.set(r,{sequence:(t=(n=o.get(r))==null?void 0:n.sequence)==null?++this.sequence:t,event:JSON.stringify(e)}),this.locations.set(r,a),this.contexts.set(r,e.contextId),this.dirty.add(a)}async save(e){try{return this.reloadAfterFailure&&(this.reset(),await this.load()),await this.saveCurrent(e)}catch(e){throw this.reloadAfterFailure=!0,e}}async saveCurrent(e){let t=new Set(e.map(e=>e.eventId));for(let[e,n]of this.locations)t.has(e)||(this.chunks[n].rows.delete(e),this.locations.delete(e),this.contexts.delete(e),this.dirty.add(n));for(let t of e)this.upsert(t);if(this.chunks.length===0)return!1;if(this.locations.size===0&&this.chunks.every(e=>e.rows!==void 0)){this.storage.removeItem?await this.storage.removeItem(this.key):await this.storage.setItem(this.key,``);for(let e=0;e<this.chunks.length;e++)for(let t of[0,1]){var n,r;await((n=(r=this.storage).removeItem)==null?void 0:n.call(r,`${this.prefix}:${e}:${t}`))}return this.chunks=[],this.dirty.clear(),!1}if(this.dirty.size===0)return!0;let i=++this.revision,a=this.chunks.map(e=>e.ref);for(let e of this.dirty){let t=this.chunks[e],n=`${this.prefix}:${e}:${1-t.bank}`;await this.storage.setItem(n,JSON.stringify({revision:i,rows:[...t.rows.values()]})),a[e]={key:n,revision:i}}await this.storage.setItem(this.key,JSON.stringify({format:S,revision:i,chunks:a}));for(let e of this.dirty)this.chunks[e].ref=a[e],this.chunks[e].bank=Number(a[e].key.slice(-1));return this.dirty.clear(),!0}},w=new Set([`session_end`,`level_start`,`level_end`,`ad_view`,`purchase`,`milestone`]),T=class extends Error{constructor(e,t,n){super(t),u(this,`status`,void 0),u(this,`code`,void 0),this.status=e,this.code=n}},E=class{constructor(e){var n,r,a,o,s,c,l,d,f,p,m,h,g,_;if(u(this,`baseUrl`,void 0),u(this,`gameKey`,void 0),u(this,`sdkVersion`,void 0),u(this,`appVersion`,void 0),u(this,`accountUserId`,void 0),u(this,`accountUserCreatedAt`,void 0),u(this,`experimentIntegrationVersion`,void 0),u(this,`platform`,void 0),u(this,`timezone`,void 0),u(this,`isDebug`,void 0),u(this,`fetchImpl`,void 0),u(this,`now`,void 0),u(this,`storage`,void 0),u(this,`scriptRuntime`,void 0),u(this,`logger`,void 0),u(this,`snapshotCacheKey`,void 0),u(this,`legacySnapshotCacheKey`,void 0),u(this,`attributionAckCacheKey`,void 0),u(this,`userIdKey`,void 0),u(this,`userCreatedAtKey`,void 0),u(this,`userCreatedLocalAtKey`,void 0),u(this,`cachedConfig`,null),u(this,`snapshot`,{configFiles:new Map,updatedAt:0}),u(this,`currentIdentity`,null),u(this,`readyPromise`,null),u(this,`didLogUserId`,!1),u(this,`didMigrateLegacyIdentity`,!1),u(this,`ddaControllers`,new Map),u(this,`config`,void 0),u(this,`tracker`,void 0),!e.baseUrl)throw Error(`baseUrl is required`);if(!e.gameKey)throw Error(`gameKey is required`);if(this.baseUrl=i(e.baseUrl),this.gameKey=e.gameKey,this.sdkVersion=(n=e.sdkVersion)==null?`1.0.0`:n,this.appVersion=e.appVersion,this.accountUserId=P(e.accountUserId),this.accountUserCreatedAt=P(e.accountUserCreatedAt),this.experimentIntegrationVersion=F(e.experimentIntegrationVersion),this.platform=e.platform===`rest`||(r=e.platform)==null?`maker`:r,this.timezone=(a=P(e.timezone))==null?L():a,this.isDebug=(o=e.isDebug)!=null&&o,this.fetchImpl=(s=e.fetchImpl)==null?(c=globalThis.fetch)==null?void 0:c.bind(globalThis):s,!this.fetchImpl)throw Error(`An HTTP transport is required`);this.now=(l=e.now)==null?Date.now:l,this.storage=e.storage,this.scriptRuntime=(d=e.scriptRuntime)==null?{execute(){throw Error(`Remote scripts are unavailable in this host`)}}:d,this.logger=ie(e.logger);let v=N(this.baseUrl),y=t(this.gameKey),b=(f=P(e.userId))==null?`anonymous`:f;this.legacySnapshotCacheKey=`gamealgo:v1:snapshot:${v}:${this.gameKey.slice(0,16)}`,this.snapshotCacheKey=(p=e.cacheKey)==null?`gamealgo:v1:snapshot:${v}:${y}:${b}`:p,this.attributionAckCacheKey=`gamealgo:v1:attribution:${v}:${y}:${b}`,this.userIdKey=`gamealgo:v1:identity:${v}:${y}:user-id`,this.userCreatedAtKey=`gamealgo:v1:identity:${v}:${y}:created-at`,this.userCreatedLocalAtKey=`gamealgo:v1:identity:${v}:${y}:created-local-at`,this.config=new ee(()=>this.snapshot),this.tracker=new D({uploadEvents:e=>this.uploadEvents(e),reportDiagnostic:e=>this.reportSdkDiagnostic(e),platform:this.platform,sdkVersion:this.sdkVersion,appVersion:this.appVersion,timezone:this.timezone,isDebug:this.isDebug,flushIntervalMs:(m=e.eventFlushIntervalMs)==null?3e4:m,maxBatchSize:(h=e.eventMaxBatchSize)==null?100:h,maxBatchBytes:e.eventMaxBatchBytes,queueLimit:(g=e.eventQueueLimit)==null?1e3:g,persistOnEnqueue:(_=e.eventPersistOnEnqueue)!=null&&_,now:this.now,storage:this.storage,persistenceKey:`gamealgo:v1:event-queue:${v}:${y}:${b}`,onAdIdentityState:(e,t)=>{try{this.log(`ad_view identity ${e}: count=${t}`)}catch{}}}),e.autoStart!==!1&&(this.readyPromise=this.initialize(e),this.readyPromise.catch(()=>void 0))}async waitForReady(e=5e3){if(!this.readyPromise)return this.snapshot.config!==void 0;let t;try{return await Promise.race([this.readyPromise,new Promise((n,r)=>{t=setTimeout(()=>r(Error(`GameAlgo ready timeout`)),e)})]),!0}catch{return!1}finally{t&&clearTimeout(t)}}executor(e){return new O(e,()=>this.snapshot,this.scriptRuntime,this.logger)}dda(e,n={}){var r,i;let a=P(e);if(!a)throw Error(`DDA strategy key is required`);let o=this.ddaControllers.get(a);if(o)return o;let s=(r=(i=this.currentIdentity)==null?void 0:i.userId)==null?`anonymous`:r,c=`gamealgo:v1:dda:${N(this.baseUrl)}:${t(this.gameKey)}:${s}:${a}`,l=new f(this.executor(a),this.storage,c,n,this.logger);return this.ddaControllers.set(a,l),l}async userIdentity(e){var t,n,r,i;await this.migrateLegacyIdentity();let a=P(e);if(a){var o,s,c,l,u,d,f;if(((o=this.currentIdentity)==null?void 0:o.userId)===a)return this.currentIdentity;let e=P(await((s=this.storage)==null?void 0:s.getItem(this.userIdKey))),t=P(await((c=this.storage)==null?void 0:c.getItem(this.userCreatedAtKey))),n=P(await((l=this.storage)==null?void 0:l.getItem(this.userCreatedLocalAtKey))),r=e===a&&t?t:new Date(this.now()).toISOString();return this.currentIdentity={userId:a,userCreatedAt:r,userCreatedLocalAt:e===a&&n?n:k(Date.parse(r))},await((u=this.storage)==null?void 0:u.setItem(this.userIdKey,this.currentIdentity.userId)),await((d=this.storage)==null?void 0:d.setItem(this.userCreatedAtKey,this.currentIdentity.userCreatedAt)),await((f=this.storage)==null?void 0:f.setItem(this.userCreatedLocalAtKey,this.currentIdentity.userCreatedLocalAt)),this.currentIdentity}if(this.currentIdentity)return this.currentIdentity;let p=P(await((t=this.storage)==null?void 0:t.getItem(this.userIdKey)));if(p){var m,h,g,_,v,y;let e=(m=P(await((h=this.storage)==null?void 0:h.getItem(this.userCreatedAtKey))))==null?new Date(this.now()).toISOString():m,t=(g=P(await((_=this.storage)==null?void 0:_.getItem(this.userCreatedLocalAtKey))))==null?k(Date.parse(e)):g;return this.currentIdentity={userId:p,userCreatedAt:e,userCreatedLocalAt:t},await((v=this.storage)==null?void 0:v.setItem(this.userCreatedAtKey,e)),await((y=this.storage)==null?void 0:y.setItem(this.userCreatedLocalAtKey,t)),this.currentIdentity}return this.currentIdentity={userId:M(),userCreatedAt:new Date(this.now()).toISOString(),userCreatedLocalAt:k(this.now())},await((n=this.storage)==null?void 0:n.setItem(this.userIdKey,this.currentIdentity.userId)),await((r=this.storage)==null?void 0:r.setItem(this.userCreatedAtKey,this.currentIdentity.userCreatedAt)),await((i=this.storage)==null?void 0:i.setItem(this.userCreatedLocalAtKey,this.currentIdentity.userCreatedLocalAt)),this.currentIdentity}async configureAdjustServerCallbackParams(e,t){if(typeof e!=`function`)throw Error(`callback parameter setter is required`);let n=await this.userIdentity(t);await e(`gamealgo_user_id`,n.userId),await e(`gamealgo_user_created_at`,n.userCreatedAt)}defaultDeviceContext(){return ae()}onConfigReady(e,t){}async fetchConfig(e={}){var t,n,r,i,a,o,s,c,l,u,d,f;let p=await this.userIdentity(e.userId),m=(t=P(e.userCreatedAt))==null?p.userCreatedAt:t,h=(n=P(e.userCreatedLocalAt))==null?P(e.userCreatedAt)?k(Date.parse(m)):p.userCreatedLocalAt:n,g=k(this.now()),_=(r=P(e.accountUserId))==null?this.accountUserId:r,v=(i=P(e.accountUserCreatedAt))==null?this.accountUserCreatedAt:i;this.logUserId(p.userId),this.tracker.identify(p.userId,e.sessionId,m,_);let y=(a=e.platform)==null?this.platform:a,b=(o=e.sdkVersion)==null?this.sdkVersion:o,x=(s=e.appVersion)==null?this.appVersion:s,S=F((c=e.experimentIntegrationVersion)==null?this.experimentIntegrationVersion:c),C=(l=P(e.sessionId))==null?this.tracker.currentSessionId():l,w=(u=e.isDebug)==null?this.isDebug:u,T={...this.defaultDeviceContext(),...(d=e.device)==null?{}:d,...e.deviceId?{deviceId:e.deviceId}:{}},E=JSON.stringify({userId:p.userId,userCreatedAt:m,userCreatedLocalAt:h,accountUserId:_,accountUserCreatedAt:v,sessionId:C,platform:y,sdkVersion:b,appVersion:x,experimentIntegrationVersion:S,deviceId:e.deviceId,timezone:(f=e.timezone)==null?this.timezone:f,device:T,isDebug:w});if(!e.forceRefresh&&this.cachedConfig&&this.cachedConfig.cacheKey===E&&this.cachedConfig.expiresAt>this.now())return this.log(`config cache hit: ${this.cachedConfig.value.configVersion}`),this.cachedConfig.value;this.log(`fetching config: userId=${p.userId}, platform=${y}`);try{var D;let t=await this.requestJson(this.url(`/v1/config`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({userId:p.userId,userCreatedAt:m,userCreatedLocalAt:h,accountUserId:_,accountUserCreatedAt:v,createdLocalAt:g,sessionId:C,platform:y,sdkVersion:b,appVersion:x,experimentIntegrationVersion:S,timezone:(D=e.timezone)==null?this.timezone:D,device:T,isDebug:w})});if(this.tracker.bindSessionContext(C,t.contextId),J(this.platform)&&P(t.contextId))try{this.log(`context ready`)}catch{}return C===this.tracker.currentSessionId()?(this.cachedConfig={value:t,cacheKey:E,expiresAt:this.now()+Math.max(Number(t.ttlSeconds)||0,0)*1e3},this.tracker.setEventQuota(t.eventQuota),this.tracker.setAssignments(t.experiments),this.snapshot={...this.snapshot,config:t,updatedAt:this.now(),userId:p.userId},this.onConfigReady(t,{userId:p.userId,sessionId:C,isDebug:w}),await this.persistSnapshot(),this.log(`config fetched: version=${t.configVersion}, experiments=${t.experiments.length}, configFiles=${t.configFiles.length}, ttl=${t.ttlSeconds}s`),this.logAssignments(t.experiments,`config ready`),t):t}catch(e){var O;if(((O=this.cachedConfig)==null?void 0:O.cacheKey)===E)return this.log(`config fetch failed, using cached config: ${I(e)}`),this.cachedConfig.value;throw this.log(`config fetch failed: ${I(e)}`),e}}async fetchConfigFile(e){var t,n;let r=ne(e),i=await this.request(this.url(`/v1/config-files/${encodeURIComponent(r)}`),{method:`GET`}),a={name:r,content:await i.text(),contentType:(t=i.headers.get(`content-type`))==null?`application/octet-stream`:t,etag:(n=i.headers.get(`etag`))==null?void 0:n},o=new Map(this.snapshot.configFiles);return o.set(r,a),this.snapshot={...this.snapshot,configFiles:o,updatedAt:this.now()},await this.persistSnapshot(),this.log(`config file loaded: ${a.name} (${a.contentType})`),a}async fetchScriptFile(e){var t,n,r,i,o;let s=P(e.versionId);if(!s)throw Error(`script versionId is required: ${e.name}`);if(!P(e.url))throw Error(`script url is required: ${e.name}@${s}`);if(!/^sha256:[a-f0-9]{64}$/i.test(e.hash))throw Error(`script hash is invalid: ${e.name}@${s}`);let c=a(e.url,this.baseUrl),l=await this.request(c,{method:`GET`}),u=await l.text();await V(u,e.hash),await((t=(n=this.scriptRuntime).prepare)==null?void 0:t.call(n,u));let d={name:j(e),content:u,contentType:(r=(i=l.headers.get(`content-type`))==null?e.contentType:i)==null?`application/octet-stream`:r,etag:(o=l.headers.get(`etag`))==null?void 0:o},f=new Map(this.snapshot.configFiles);return f.set(d.name,d),this.snapshot={...this.snapshot,configFiles:f,updatedAt:this.now()},await this.persistSnapshot(),this.log(`script loaded: ${e.name}${e.versionId?` (${e.versionId})`:``}`),d}async uploadEvents(e){if(!Array.isArray(e)||e.length===0)throw Error(`events must be a non-empty array`);if(e.length>100)throw Error(`Maximum 100 events per batch`);let t=e.map(e=>{var t,n,r,i;return{...e,eventId:(t=e.eventId)==null?M():t,isDebug:!!e.isDebug,timestamp:(n=e.timestamp)==null?new Date(this.now()).toISOString():n,createdLocalAt:(r=e.createdLocalAt)==null?k(e.timestamp?Date.parse(e.timestamp):this.now()):r,payload:z((i=e.payload)==null?{}:i)}}),n=await this.requestJson(this.url(`/v1/events/batch`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({events:t})});if(t.some(e=>e.eventType===`ad_view`)){let e=n.stored;try{var r,i;this.log(`ad_view upload ack: accepted=${n.accepted} stored=${typeof e==`number`?e:`unknown`} rejected=${(r=(i=n.rejected)==null?void 0:i.length)==null?0:r}`)}catch{}}return n}async reportSdkDiagnostic(e){await this.requestJson(this.url(`/v1/diagnostics/sdk`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)})}async setAttribution(e){var t,n,r,i,a,o,s;let c=P(e.provider);if(!c)throw Error(`provider is required`);let l=await this.userIdentity(e.userId),u=(t=e.platform)==null?this.platform:t,d=ce(e.attribution),f=le(c,P(e.status),d),p=P(e.attributedAt),m=(n=P(e.attributionHash))==null?await H(q({platform:u,provider:c,status:f,attribution:d,attributedAt:p==null?``:p})):n,h=`${this.attributionAckCacheKey}:${c}`;if(m&&await((r=this.storage)==null?void 0:r.getItem(h))===m)return this.log(`attribution already synced: provider=${c}`),{ok:!0,accepted:0,attributionHash:m};let g=await this.requestJson(this.url(`/v1/attribution`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({userId:l.userId,userCreatedAt:(i=P(e.userCreatedAt))==null?l.userCreatedAt:i,sessionId:(a=P(e.sessionId))==null?this.tracker.currentSessionId():a,contextId:(o=P(e.contextId))==null?(s=this.snapshot.config)==null?void 0:s.contextId:o,platform:u,provider:c,status:f,attribution:d,attributedAt:p,attributionHash:m})});if(g.attributionHash){var _;await((_=this.storage)==null?void 0:_.setItem(h,g.attributionHash))}return this.log(`attribution synced: provider=${c}, accepted=${g.accepted}`),g}async setAdjustAdid(e,t){return this.setContextIdentifier(`adjust_adid`,e,t)}async setFirebaseAppInstanceId(e,t){return this.setContextIdentifier(`firebase_app_instance_id`,e,t)}async setGoogleAdvertisingId(e,t){return this.setContextIdentifier(`gaid`,e,t)}async setIdfa(e,t){return this.setContextIdentifier(`idfa`,e,t)}async setIdfv(e,t){return this.setContextIdentifier(`idfv`,e,t)}async setContextIdentifier(e,t,n){var r,i;!this.snapshot.config&&this.readyPromise&&await this.readyPromise;let a=P((r=this.snapshot.config)==null?void 0:r.contextId);if(!a)throw Error(`config context is not ready`);let o=await this.userIdentity(),s=re(e,t),c=await H(JSON.stringify({identifierType:e,identifierValue:s})),l=await this.requestJson(this.url(`/v1/context-identifiers`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({userId:o.userId,sessionId:this.tracker.currentSessionId(),contextId:a,platform:this.platform,identifierType:e,identifierValue:s,observedAt:(i=P(n))==null?new Date(this.now()).toISOString():i,identifierHash:c})});return this.log(`context identifier synced: type=${e}, accepted=${l.accepted}`),l}clearConfigCache(){this.cachedConfig=null}snapshotValue(){return{config:this.snapshot.config,configFiles:new Map(this.snapshot.configFiles),updatedAt:this.snapshot.updatedAt}}async initialize(e){let t=`identity`;try{var n,r;let i=this.now();if(J(this.platform))try{this.log(`identity restore started`)}catch{}let a=await this.userIdentity(e.userId),o=(n=P(e.userCreatedAt))==null?a.userCreatedAt:n;if(this.logUserId(a.userId),this.tracker.identify(a.userId,e.sessionId,o,(r=P(e.accountUserId))==null?this.accountUserId:r),J(this.platform))try{this.log(`identity ready: elapsedMs=${Math.max(0,this.now()-i)}`)}catch{}this.tracker.markSessionStarted(),t=`event-queue-restore`,await this.tracker.waitForRestore(),t=`snapshot-restore`,await this.loadPersistedSnapshot();try{t=`config`,await this.refresh({...e,userId:a.userId,userCreatedAt:o,forceRefresh:!0})}catch(e){if(!this.snapshot.config)throw this.log(`config fetch failed: ${I(e)}`),e;this.log(`config fetch failed, using cached snapshot: ${I(e)}`)}}catch(e){if(J(this.platform))try{this.log(`initialization failed: stage=${t} errorType=${e instanceof Error?e.name:typeof e}`)}catch{}throw e}}async refresh(e){var t;let n=await this.fetchConfig(e),r=(t=e.preloadConfigFiles)==null||t;if(!r){this.log(`config file preload skipped`);return}let i=Array.isArray(r)?r:n.configFiles.map(e=>e.name),a=Array.isArray(r)?[]:[...new Map(n.experiments.flatMap(e=>e.script?[[j(e.script),e.script]]:[])).values()],o=[...new Set([...i,...a.map(e=>e.versionId?`${e.name}@${e.versionId}`:e.name)])];o.length===0?this.log(`no config files to preload`):this.log(`preloading config files: ${o.sort().join(`, `)}`),await Promise.all([...[...new Set(i)].map(e=>this.fetchConfigFile(e)),...a.map(e=>this.fetchScriptFile(e))]);for(let e of n.experiments){let t=e.script;t&&this.snapshot.configFiles.has(j(t))&&this.log(`script ready: ${e.key} -> ${t.name}${t.versionId?` (${t.versionId})`:``}`)}o.length>0&&this.log(`all config files loaded`),this.tracker.setAssignments(n.experiments),this.logAssignments(n.experiments,`experiment`)}async loadPersistedSnapshot(){if(!this.storage)return;let e=await this.storage.getItem(this.snapshotCacheKey);if(!e&&this.legacySnapshotCacheKey!==this.snapshotCacheKey&&(e=await this.storage.getItem(this.legacySnapshotCacheKey),e)){var t,n;await this.storage.setItem(this.snapshotCacheKey,e),await((t=(n=this.storage).removeItem)==null?void 0:t.call(n,this.legacySnapshotCacheKey))}if(e)try{var r;let t=JSON.parse(e);this.snapshot={config:t.config,configFiles:new Map(((r=t.configFiles)==null?[]:r).map(e=>[e.name,e])),updatedAt:Number(t.updatedAt||0),userId:t.userId},this.log(`cached snapshot loaded`)}catch{var i,a;await((i=(a=this.storage).removeItem)==null?void 0:i.call(a,this.snapshotCacheKey))}}async persistSnapshot(){this.storage&&await this.storage.setItem(this.snapshotCacheKey,JSON.stringify({config:this.snapshot.config,configFiles:[...this.snapshot.configFiles.values()],updatedAt:this.snapshot.updatedAt,userId:this.snapshot.userId}))}async migrateLegacyIdentity(){var e,t,n,r,i,a;if(this.didMigrateLegacyIdentity||!this.storage||(this.didMigrateLegacyIdentity=!0,P(await this.storage.getItem(this.userIdKey))))return;let o=P(await this.storage.getItem(`gamealgo_user_id`));if(!o)return;let s=P(await this.storage.getItem(`gamealgo_user_created_at`)),c=P(await this.storage.getItem(`gamealgo_user_created_local_at`));await this.storage.setItem(this.userIdKey,o),s&&await this.storage.setItem(this.userCreatedAtKey,s),c&&await this.storage.setItem(this.userCreatedLocalAtKey,c),await((e=(t=this.storage).removeItem)==null?void 0:e.call(t,`gamealgo_user_id`)),await((n=(r=this.storage).removeItem)==null?void 0:n.call(r,`gamealgo_user_created_at`)),await((i=(a=this.storage).removeItem)==null?void 0:i.call(a,`gamealgo_user_created_local_at`))}url(e){return`${N(this.baseUrl)}/${e.replace(/^\/+/,``)}`}async requestJson(e,t){return(await this.request(e,t)).json()}async request(e,t){let n=await this.fetchImpl(e,{...t,headers:{...t.headers,"X-GameAlgo-Key":this.gameKey}});if(!n.ok)throw await te(n);return n}logUserId(e){this.didLogUserId||(this.didLogUserId=!0,this.log(`userId: ${e}`))}logAssignments(e,t){for(let n of e)this.log(`${t}: ${n.key} -> ${n.variant}`)}log(e){var t;(t=this.logger)==null||t.call(this,`[GameAlgoSDK] ${e}`)}},D=class{constructor(e){var t,n;if(u(this,`uploadEvents`,void 0),u(this,`reportDiagnostic`,void 0),u(this,`platform`,void 0),u(this,`sdkVersion`,void 0),u(this,`appVersion`,void 0),u(this,`maxBatchSize`,void 0),u(this,`maxBatchBytes`,void 0),u(this,`queueLimit`,void 0),u(this,`persistOnEnqueue`,void 0),u(this,`flushIntervalMs`,void 0),u(this,`now`,void 0),u(this,`storage`,void 0),u(this,`persistenceKey`,void 0),u(this,`milestonePersistenceKey`,void 0),u(this,`milestoneRestorePromise`,void 0),u(this,`restorePromise`,void 0),u(this,`userId`,void 0),u(this,`sessionId`,M()),u(this,`contextId`,void 0),u(this,`timezone`,void 0),u(this,`userCreatedAt`,void 0),u(this,`accountUserId`,void 0),u(this,`isDebug`,void 0),u(this,`currentExperiments`,{}),u(this,`queue`,[]),u(this,`retryBatch`,[]),u(this,`inflightBatch`,[]),u(this,`urgentEventIds`,new Set),u(this,`urgentFlushes`,new Map),u(this,`pendingIdentityAds`,[]),u(this,`timersStopped`,!1),u(this,`onAdIdentityState`,void 0),u(this,`restored`,!1),u(this,`flushTimer`,void 0),u(this,`activeFlush`,void 0),u(this,`sessionStartMs`,void 0),u(this,`sessionDurationTimer`,void 0),u(this,`sampledForegroundTimeMs`,0),u(this,`sessionForegroundStartMs`,0),u(this,`sessionDurationSampleAt`,0),u(this,`sessionDurationVisible`,void 0),u(this,`sessionDurationWasVisible`,!0),u(this,`sessionHasEnd`,!1),u(this,`consecutiveFailures`,0),u(this,`hasPersistedQueue`,!1),u(this,`queueRestorePending`,!1),u(this,`incrementalQueue`,void 0),u(this,`queuePersistActive`,void 0),u(this,`queuePersistRevision`,0),u(this,`customCounts`,new Map),u(this,`ordinaryCounts`,new Map),u(this,`eventQuota`,void 0),u(this,`diagnosticKeys`,new Set),u(this,`diagnosticCount`,0),u(this,`reachedMilestoneKeys`,new Set),u(this,`pendingMilestoneKeys`,new Set),u(this,`milestonePersistPromise`,Promise.resolve()),u(this,`queuePersistPromise`,Promise.resolve()),this.uploadEvents=e.uploadEvents,this.reportDiagnostic=e.reportDiagnostic,this.platform=e.platform,this.sdkVersion=e.sdkVersion,this.appVersion=e.appVersion,this.timezone=(t=P(e.timezone))==null?L():t,this.isDebug=e.isDebug,this.flushIntervalMs=e.flushIntervalMs,this.maxBatchSize=Math.max(1,Math.min(e.maxBatchSize,100)),this.maxBatchBytes=Number.isFinite(e.maxBatchBytes)&&Number(e.maxBatchBytes)>0?Math.floor(Number(e.maxBatchBytes)):void 0,this.queueLimit=Math.max(e.queueLimit,this.maxBatchSize),this.persistOnEnqueue=(n=e.persistOnEnqueue)!=null&&n,this.now=e.now,this.onAdIdentityState=e.onAdIdentityState,this.sessionStartMs=this.now(),this.sessionDurationSampleAt=this.sessionStartMs,J(this.platform)){var r,i;this.sessionDurationTimer=setInterval(()=>this.sampleSessionDuration(),1e3),(r=(i=this.sessionDurationTimer).unref)==null||r.call(i)}this.storage=e.storage,this.persistenceKey=P(e.persistenceKey),this.persistOnEnqueue&&this.storage&&this.persistenceKey&&(this.incrementalQueue=new C(this.storage,this.persistenceKey)),this.milestonePersistenceKey=this.persistenceKey?`${this.persistenceKey}:milestones`:void 0,this.milestoneRestorePromise=this.restorePersistedMilestones(),this.restorePromise=Promise.all([this.restorePersistedQueue(),this.milestoneRestorePromise]).then(()=>{this.restored=!0})}identify(e,t,n,r){if(P(e)&&(this.userId=e),P(t)&&t!==this.sessionId&&(this.sessionId=t,this.sessionHasEnd=!1,this.sessionStartMs=this.now(),this.resetSessionDuration(this.sessionStartMs)),P(n)&&(this.userCreatedAt=n),P(r)&&(this.accountUserId=r),P(this.userId)){let e=this.pendingIdentityAds.splice(0);if(e.length)try{var i;(i=this.onAdIdentityState)==null||i.call(this,`released`,e.length)}catch{}for(let t of e)this.track(`ad_view`,t.payload,t.options)}}newSession(e=M()){var t;if(e=(t=P(e))==null?M():t,e===this.sessionId)return;let n=this.sessionId,r=this.now(),i=P(this.userId);if(i&&!this.sessionHasEnd){var a;this.enqueue({eventId:M(),contextId:(a=this.contextId)==null?``:a,userId:i,sessionId:n,eventType:`session_end`,isDebug:this.isDebug,timestamp:new Date(r).toISOString(),createdLocalAt:k(r),accountUserId:this.accountUserId,payload:{reason:`new_session`,sessionDurationMs:this.sessionDuration(r)}})}this.sessionId=e,this.sessionHasEnd=!1,this.ordinaryCounts.delete(`pending:${n}`),this.diagnosticKeys.clear(),this.diagnosticCount=0,this.pendingMilestoneKeys.clear(),this.contextId=void 0,this.eventQuota=void 0,this.sessionStartMs=r,this.resetSessionDuration(r),this.hasPersistedQueue=!0,this.persistPendingQueue().catch(()=>void 0),J(this.platform)&&this.flushUrgent().catch(()=>void 0),this.flush().catch(()=>void 0)}currentSessionId(){return this.sessionId}async waitForRestore(){await this.restorePromise}setContextId(e){this.bindSessionContext(this.sessionId,e)}bindSessionContext(e,t){let n=P(t);if(e===this.sessionId&&(this.contextId=n),!n)return;this.mergeCustomCountBucket(`pending:${e}`,`context:${n}`),this.mergeOrdinaryCountBucket(`pending:${e}`,`context:${n}`);let r=t=>!P(t.contextId)&&t.sessionId===e?{...t,contextId:n}:t;this.retryBatch=this.retryBatch.map(r),this.queue=this.queue.map(r),this.rememberBoundMilestones(n),this.hasPersistedQueue&&this.persistPendingQueue().catch(()=>void 0),J(this.platform)&&this.flushUrgent().catch(()=>void 0),[...this.retryBatch,...this.queue].some(t=>t.sessionId===e&&t.eventType===`session_end`)&&this.flush().catch(()=>void 0)}setDebug(e){this.isDebug=e}setTimezone(e){var t;this.timezone=(t=P(e))==null?L():t}setAssignments(e){this.currentExperiments={};for(let t of e)this.currentExperiments[t.key]=t.variant}setEventQuota(e){let t=Math.floor(Number(e==null?void 0:e.ordinaryEventLimit));this.eventQuota=(e==null?void 0:e.mode)===`enforce`&&Number.isSafeInteger(t)&&t>=0?{...e,ordinaryEventLimit:t,exemptEventTypes:Array.isArray(e.exemptEventTypes)?e.exemptEventTypes.filter(e=>typeof e==`string`&&e.length>0):[]}:void 0}markSessionStarted(){this.sessionStartMs=this.now(),this.resetSessionDuration(this.sessionStartMs)}getForegroundTimeMs(){return Math.round(this.sampledForegroundTimeMs)}setSessionDurationVisibility(e){this.sessionDurationVisible=e,this.sessionDurationWasVisible=e()}observeSessionDurationVisibility(){J(this.platform)&&this.sampleSessionDuration()}resetSessionDuration(e){J(this.platform)&&this.sampleSessionDuration(e),this.sessionForegroundStartMs=this.getForegroundTimeMs()}sampleSessionDuration(e=this.now()){var t,n;if(!Number.isFinite(e))return;let r=(t=(n=this.sessionDurationVisible)==null?void 0:n.call(this))==null||t;this.sessionDurationWasVisible&&(this.sampledForegroundTimeMs+=Math.min(1e3,Math.max(0,e-this.sessionDurationSampleAt))),this.sessionDurationWasVisible=r,this.sessionDurationSampleAt=e}sessionDuration(e){var t;return J(this.platform)?(this.sampleSessionDuration(e),this.getForegroundTimeMs()-this.sessionForegroundStartMs):Math.max(0,e-((t=this.sessionStartMs)==null?e:t))}track(e,t={},n={}){var r,i,a,o,s,c;let l=P((r=n.userId)==null?this.userId:r);if(!l){var u,d,f,p;if(!J(this.platform)||e!==`ad_view`||n.userId!==void 0)return!1;let r=(u=n.timestamp)==null?new Date(this.now()).toISOString():u;this.pendingIdentityAds.push({payload:z(t),options:{...n,sessionId:(d=P(n.sessionId))==null?this.sessionId:d,isDebug:(f=n.isDebug)==null?this.isDebug:f,timestamp:r,createdLocalAt:(p=n.createdLocalAt)==null?k(Date.parse(r)):p}}),this.pendingIdentityAds.length>this.queueLimit&&this.pendingIdentityAds.shift();try{var m;(m=this.onAdIdentityState)==null||m.call(this,`buffered`,this.pendingIdentityAds.length)}catch{}return!0}let h=(i=P(n.sessionId))==null?this.sessionId:i,g=P((a=n.contextId)==null?h===this.sessionId?this.contextId:void 0:a),_=n.timestamp?Date.parse(n.timestamp):this.now(),v=(o=n.isDebug)==null?this.isDebug:o,y=z(t),b=e===`milestone`?this.prepareMilestone(l,g,v,y,_):void 0;return b!=null&&b.duplicate||!this.consumeOrdinaryEventQuota(e,g,h,!1)||!this.consumeCustomEventQuota(e,g,h)?!1:(this.consumeOrdinaryEventQuota(e,g,h,!0),this.enqueue({eventId:M(),contextId:g==null?``:g,userId:l,sessionId:h,eventType:e,isDebug:v,timestamp:(s=n.timestamp)==null?new Date(this.now()).toISOString():s,createdLocalAt:(c=n.createdLocalAt)==null?k(n.timestamp?Date.parse(n.timestamp):this.now()):c,accountUserId:this.accountUserId,payload:y}),b!=null&&b.key&&this.rememberMilestone(b.key,b.durable),J(this.platform)&&e===`ad_view`?this.flushUrgent().then(()=>this.flush()).catch(()=>void 0):J(this.platform)&&e===`session_end`&&this.flushUrgent().catch(()=>void 0),!0)}prepareMilestone(e,t,n,r,i){let a=this.userCreatedAt?Date.parse(this.userCreatedAt):NaN;delete r.elapsedSinceRegistrationMs,Number.isFinite(i)&&Number.isFinite(a)&&(r.elapsedSinceRegistrationMs=Math.max(0,Math.floor(i-a)));let o=P(typeof r.milestoneType==`string`?r.milestoneType:void 0),s=P(typeof r.milestonePoint==`string`?r.milestonePoint:void 0);if(!o||!s)return{duplicate:!1,durable:!1};let c=JSON.stringify([n?`debug`:`live`,e,o,s]),l=!!t;return{duplicate:(l?this.reachedMilestoneKeys:this.pendingMilestoneKeys).has(c),key:c,durable:l}}rememberMilestone(e,t){if(!t){this.pendingMilestoneKeys.add(e);return}this.reachedMilestoneKeys.has(e)||(this.reachedMilestoneKeys.add(e),this.persistReachedMilestones())}rememberBoundMilestones(e){let t=!1;for(let i of[...this.retryBatch,...this.queue]){var n,r;if(i.contextId!==e||i.eventType!==`milestone`)continue;let a=P(typeof((n=i.payload)==null?void 0:n.milestoneType)==`string`?i.payload.milestoneType:void 0),o=P(typeof((r=i.payload)==null?void 0:r.milestonePoint)==`string`?i.payload.milestonePoint:void 0);if(!a||!o)continue;let s=JSON.stringify([i.isDebug?`debug`:`live`,i.userId,a,o]);this.reachedMilestoneKeys.has(s)||(this.reachedMilestoneKeys.add(s),t=!0)}t&&this.persistReachedMilestones()}consumeCustomEventQuota(e,t,n){var r,i;if(w.has(e))return!0;let a=t?`context:${t}`:`pending:${n}`,o=(r=this.customCounts.get(a))==null?{total:0,byType:new Map}:r,s=(i=o.byType.get(e))==null?0:i,c,l=0;if(!o.byType.has(e)&&o.byType.size>=100?(c=`distinct_event_types`,l=100):s>=1e3?(c=`context_event_type`,l=1e3):o.total>=5e3&&(c=`context_total`,l=5e3),c){let r=c===`context_total`?o.total+1:c===`distinct_event_types`?o.byType.size+1:s+1;return this.reportQuotaDiagnostic(e,n,t,c,l,r),!1}return o.total+=1,o.byType.set(e,s+1),this.customCounts.set(a,o),!0}mergeCustomCountBucket(e,t){var n,r;let i=this.customCounts.get(e);if(!i)return;let a=(n=this.customCounts.get(t))==null?{total:0,byType:new Map}:n;a.total+=i.total;for(let[e,t]of i.byType)a.byType.set(e,((r=a.byType.get(e))==null?0:r)+t);this.customCounts.set(t,a),this.customCounts.delete(e)}consumeOrdinaryEventQuota(e,t,n,r){var i;let a=this.eventQuota;if(e===`purchase`||e===`ad_view`||a!=null&&a.exemptEventTypes.includes(e))return!0;let o=t?`context:${t}`:`pending:${n}`,s=(i=this.ordinaryCounts.get(o))==null?0:i;return a&&s>=a.ordinaryEventLimit?(this.reportContextQuotaDiagnostic(e,n,t,a,s+1),!1):(r&&this.ordinaryCounts.set(o,s+1),!0)}mergeOrdinaryCountBucket(e,t){var n;let r=this.ordinaryCounts.get(e);r!==void 0&&(this.ordinaryCounts.set(t,((n=this.ordinaryCounts.get(t))==null?0:n)+r),this.ordinaryCounts.delete(e))}reportContextQuotaDiagnostic(e,t,n,r,i){let a=`${n==null?`pending:${t}`:n}\u0000context_event_quota`;if(!this.reportDiagnostic||this.diagnosticKeys.has(a)||this.diagnosticCount>=10)return;this.diagnosticKeys.add(a),this.diagnosticCount+=1;let o=new Date(this.now()).toISOString(),s=e.replace(/[;\r\n]/g,`_`).slice(0,96);this.reportDiagnostic({diagnosticId:M(),userId:this.userId,sessionId:t,contextId:n,platform:this.platform,sdkVersion:this.sdkVersion,appVersion:this.appVersion,stage:`event_guard`,status:`degraded`,reasonCode:`context_event_quota_exceeded`,reasonDetail:`eventType=${s};scope=context_total;limit=${r.ordinaryEventLimit};observed=${i};policyVersion=${r.policyVersion};quotaDate=${r.quotaDate};dropped=1`,createdAt:o,createdLocalAt:k(this.now()),isDebug:this.isDebug}).catch(()=>void 0)}reportQuotaDiagnostic(e,t,n,r,i,a){let o=`${t}\u0000${e}\u0000${r}`;if(!this.reportDiagnostic||this.diagnosticKeys.has(o)||this.diagnosticCount>=10)return;this.diagnosticKeys.add(o),this.diagnosticCount+=1;let s=new Date(this.now()).toISOString(),c=e.replace(/[;\r\n]/g,`_`).slice(0,96);this.reportDiagnostic({diagnosticId:M(),userId:this.userId,sessionId:t,contextId:n,platform:this.platform,sdkVersion:this.sdkVersion,appVersion:this.appVersion,stage:`event_guard`,status:`degraded`,reasonCode:`custom_event_quota_exceeded`,reasonDetail:`eventType=${c};scope=${r};limit=${i};observed=${a};dropped=1`,createdAt:s,createdLocalAt:k(this.now()),isDebug:this.isDebug}).catch(()=>void 0)}trackEvent(e,t={},n={}){return this.track(e.startsWith(`_`)?e:`_${e}`,t,n)}trackSessionEnd(e={}){let t=R(e);return this.sessionStartMs!==void 0&&(t.sessionDurationMs=this.sessionDuration(this.now())),this.track(`session_end`,t)}trackSessionEndSnapshot(e={}){var t;let n=P(this.userId);if(!n)return!1;let r=this.now(),i=R(e);return i.sessionDurationMs=this.sessionDuration(r),this.hasPersistedQueue=!0,this.enqueue({eventId:M(),contextId:(t=this.contextId)==null?``:t,userId:n,sessionId:this.sessionId,eventType:`session_end`,isDebug:this.isDebug,timestamp:new Date(r).toISOString(),createdLocalAt:k(r),accountUserId:this.accountUserId,payload:z(i)},!0),this.persistOnEnqueue||this.persistPendingQueue().catch(()=>void 0),J(this.platform)&&this.flushUrgent().catch(()=>void 0),!0}trackLevelStart(e={}){return this.track(`level_start`,e)}trackLevelEnd(e={}){return this.track(`level_end`,e)}trackMilestone(e,t,n={}){let r=R(n);return r.milestoneType=e,r.milestonePoint=t,this.track(`milestone`,r)}trackAdPlacement(e,t,n,r={}){if(typeof e!=`string`||e.length!==36||!/^gap_[a-f0-9]{32}$/.test(e)||!Number.isFinite(t))return!1;let i=typeof n==`string`?n:void 0,a=R(typeof n==`string`||n==null?r:n);return delete a.placement,delete a.adType,delete a.currency,a.adPlacementId=e,a.revenue=t,i&&(a.network=i),this.track(`ad_view`,a)}trackPurchase(e,t,n,r={}){let i=R(r);return e&&(i.productId=e),t!==void 0&&(i.revenue=t),n&&(i.currency=n),this.track(`purchase`,i)}flush(){if(this.activeFlush)return this.activeFlush;let e=this.drain();return this.activeFlush=e,e.finally(()=>{this.activeFlush===e&&(this.activeFlush=void 0)}).catch(()=>void 0),e}async drain(){await this.restorePromise,await this.milestonePersistPromise,await this.queuePersistPromise,this.queueRestorePending&&await this.persistPendingQueue().catch(()=>void 0);let e=[];for(;this.retryBatch.length>0||this.queue.length>0;){let t=[...this.retryBatch,...this.queue],n=t.filter(e=>!this.urgentEventIds.has(e.eventId)&&P(e.contextId)),r=new Set(n.map(e=>e.eventId)),i=t.filter(e=>!r.has(e.eventId));if(n.length===0)return e;let a=B(n,this.maxBatchSize,this.maxBatchBytes);this.retryBatch=[],this.queue=[...i,...n.slice(a.length)],this.inflightBatch=a;try{e.push(await this.uploadEvents(a)),this.inflightBatch=[],this.consecutiveFailures=0,this.hasPersistedQueue&&await this.persistPendingQueue().catch(()=>void 0)}catch(e){if(this.inflightBatch=[],this.retryBatch=[...a,...this.retryBatch],this.consecutiveFailures+=1,this.hasPersistedQueue||this.consecutiveFailures>=3){this.hasPersistedQueue=!0;try{await this.persistPendingQueue()}catch{}}throw e}}return await this.queuePersistPromise,this.hasPersistedQueue&&this.retryBatch.length===0&&this.queue.length===0&&await this.clearPersistedQueue().catch(()=>void 0),e}async flushUrgent(){let e=[`session_end`,`ad_view`].map(e=>{let t=this.urgentFlushes.get(e);if(t)return t;if(!this.urgentCandidates(e).length)return Promise.resolve([]);let n=this.drainUrgent(e);return this.urgentFlushes.set(e,n),n});return(await Promise.all(e)).flat()}urgentCandidates(e){return[...this.retryBatch,...this.queue].filter(t=>t.eventType===e&&!this.urgentEventIds.has(t.eventId)&&(P(t.contextId)||t.sessionId===this.sessionId&&P(this.contextId)))}async drainUrgent(e){let t=[];try{for(this.restored||await this.restorePromise;;){let n=this.urgentCandidates(e);if(n.length===0)return t;let r=B(n,this.maxBatchSize,this.maxBatchBytes),i=new Set(r.map(e=>e.eventId));for(let e of i)this.urgentEventIds.add(e);let a=r.map(e=>P(e.contextId)?e:{...e,contextId:this.contextId});try{t.push(await this.uploadEvents(a)),this.retryBatch=this.retryBatch.filter(e=>!i.has(e.eventId)),this.queue=this.queue.filter(e=>!i.has(e.eventId)),this.hasPersistedQueue&&this.persistPendingQueue().catch(()=>void 0)}catch(e){let t=new Set([...this.retryBatch,...this.queue,...this.inflightBatch].map(e=>e.eventId));throw this.retryBatch=[...a.filter(e=>!t.has(e.eventId)),...this.retryBatch],this.hasPersistedQueue&&this.persistPendingQueue().catch(()=>void 0),e}finally{for(let e of i)this.urgentEventIds.delete(e)}}}finally{this.urgentFlushes.delete(e)}}close(){this.timersStopped=!0,this.sessionDurationTimer&&(clearInterval(this.sessionDurationTimer),this.sessionDurationTimer=void 0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0)}enqueue(e,t=!1){this.queue.push(e),!t&&e.eventType===`session_end`&&e.sessionId===this.sessionId&&(this.sessionHasEnd=!0),this.queue.length>this.queueLimit&&this.queue.splice(0,this.queue.length-this.queueLimit),this.persistOnEnqueue&&(this.hasPersistedQueue=!0,this.persistPendingQueue().catch(()=>void 0)),this.startTimer(),this.queue.length>=this.maxBatchSize&&this.flush().catch(()=>void 0)}startTimer(){var e,t;this.timersStopped||this.flushTimer||this.flushIntervalMs<=0||(this.flushTimer=setInterval(()=>{this.flush().catch(()=>void 0)},this.flushIntervalMs),(e=(t=this.flushTimer).unref)==null||e.call(t))}async restorePersistedQueue(){if(!this.storage||!this.persistenceKey)return;let e=this.storage,t;try{var n;t=await((n=e.getItemDurably)==null?e.getItem:n).call(e,this.persistenceKey)}catch{this.queueRestorePending=!0,this.hasPersistedQueue=!0;return}if(this.queueRestorePending=!1,t){if(this.incrementalQueue){let e;try{e=await this.incrementalQueue.load(t)}catch{var r,i;this.incrementalQueue.reset(),await((r=(i=this.storage).removeItem)==null?void 0:r.call(i,this.persistenceKey));return}let n=new Set([...this.retryBatch,...this.inflightBatch,...this.queue].map(e=>e.eventId));this.retryBatch=[...e.filter(e=>!n.has(e.eventId)),...this.retryBatch],this.hasPersistedQueue=e.length>0;return}try{if(t.includes(`"format":"gamealgo-event-chunks-v2"`)){this.incrementalQueue=new C(this.storage,this.persistenceKey);let e=await this.incrementalQueue.load(t),n=new Set([...this.retryBatch,...this.inflightBatch,...this.queue].map(e=>e.eventId));this.retryBatch=[...e.filter(e=>!n.has(e.eventId)),...this.retryBatch],this.hasPersistedQueue=e.length>0;return}let e=t.split(`
|
|
3
|
+
`).map(e=>e.trim()).filter(Boolean).map(e=>JSON.parse(e)).filter(e=>P(e.eventId)&&P(e.userId)&&P(e.sessionId)&&P(e.eventType)),n=new Set([...this.retryBatch,...this.inflightBatch,...this.queue].map(e=>e.eventId));this.retryBatch=[...e.filter(e=>!n.has(e.eventId)),...this.retryBatch],this.hasPersistedQueue=e.length>0}catch{var a,o;await((a=(o=this.storage).removeItem)==null?void 0:a.call(o,this.persistenceKey))}}}async restorePersistedMilestones(){if(!this.storage||!this.milestonePersistenceKey)return;let e=await this.storage.getItem(this.milestonePersistenceKey);if(e)try{let t=JSON.parse(e);if(!Array.isArray(t))throw Error(`invalid milestone cache`);for(let e of t)typeof e==`string`&&e&&this.reachedMilestoneKeys.add(e)}catch{var t,n;await((t=(n=this.storage).removeItem)==null?void 0:t.call(n,this.milestonePersistenceKey))}}persistReachedMilestones(){if(!this.storage||!this.milestonePersistenceKey)return Promise.resolve();let e=async()=>{await this.milestoneRestorePromise,await this.storage.setItem(this.milestonePersistenceKey,JSON.stringify([...this.reachedMilestoneKeys].sort()))};return this.milestonePersistPromise=this.milestonePersistPromise.then(e,e),this.milestonePersistPromise}persistPendingQueue(){if(!this.storage||!this.persistenceKey)return Promise.resolve();if(this.queuePersistRevision++,this.queuePersistActive)return this.queuePersistActive;let e=async()=>{try{if(await this.restorePromise,this.queueRestorePending&&(await this.restorePersistedQueue(),this.queueRestorePending))throw Error(`Event queue storage is unavailable`);let n;do{n=this.queuePersistRevision;let r=[...this.retryBatch,...this.inflightBatch,...this.queue];if(this.incrementalQueue)this.hasPersistedQueue=await this.incrementalQueue.save(r);else if(r.length===0){var e,t;await((e=(t=this.storage).removeItem)==null?void 0:e.call(t,this.persistenceKey)),this.hasPersistedQueue=!1}else await this.storage.setItem(this.persistenceKey,r.map(e=>JSON.stringify(e)).join(`
|
|
4
|
+
`)),this.hasPersistedQueue=!0}while(n!==this.queuePersistRevision)}finally{this.queuePersistActive=void 0}},t=this.queuePersistPromise.then(e,e);return this.queuePersistActive=t,this.queuePersistPromise=t.catch(()=>void 0),t}async clearPersistedQueue(){if(!this.storage||!this.persistenceKey){this.hasPersistedQueue=!1;return}await this.persistPendingQueue()}},O=class{constructor(e,t,n,r){u(this,`key`,void 0),u(this,`snapshotProvider`,void 0),u(this,`scriptRuntime`,void 0),u(this,`logger`,void 0),this.key=e,this.snapshotProvider=t,this.scriptRuntime=n,this.logger=r}get isReady(){return this.assignment()!==void 0}assignment(){var e;return(e=this.snapshotProvider().config)==null?void 0:e.experiments.find(e=>e.key===this.key)}variant(e=`control`){var t,n;return(t=(n=this.assignment())==null?void 0:n.variant)==null?e:t}config(e){var t,n;return(t=(n=this.assignment())==null?void 0:n.config)==null?e:t}value(e,t){var n,r;let i=(n=this.assignment())==null?void 0:n.config;return i===void 0||(r=de(i,e))==null?t:r}string(e,t=``){let n=this.value(e,t);return typeof n==`string`?n:t}number(e,t=0){let n=this.value(e,t);return typeof n==`number`?n:t}bool(e,t=!1){let n=this.value(e,t);return typeof n==`boolean`?n:t}async execute(e){var t;let n=this.snapshotProvider(),r=this.assignment();if(!n.config||!r){this.log(`execute skipped: ${this.key} is not ready`);return}if(!r.script)return{payload:r.config,diagnostics:{mode:`config-only`},assignment:r};let i=n.configFiles.get(j(r.script));if(!i){this.log(`execute skipped: script not loaded: ${r.key} -> ${r.script.name}${r.script.versionId?` (${r.script.versionId})`:``}`);return}try{await V(i.content,r.script.hash)}catch(e){throw this.log(`execute skipped: script hash mismatch: ${r.key} -> ${r.script.name}`),e}let a={state:e,config:r.config,meta:{gameId:n.config.gameId,userId:(t=n.userId)==null?``:t,environment:n.config.environment,strategy:r.key,experimentId:r.experimentId,variant:r.variant}},o=U(await this.scriptRuntime.execute(i.content,a));if(!o||typeof o!=`object`||Array.isArray(o)){this.log(`execute failed for ${r.key}: result must be an object`);return}let s=o.payload,c=o.diagnostics;if(s===void 0){this.log(`execute failed for ${r.key}: result must contain payload`);return}return{payload:s,diagnostics:c==null?{}:c,assignment:r}}log(e){var t;(t=this.logger)==null||t.call(this,`[GameAlgoSDK] ${e}`)}},ee=class{constructor(e){u(this,`snapshotProvider`,void 0),this.snapshotProvider=e}file(e){return this.snapshotProvider().configFiles.get(e)}jsonFile(e,t){let n=this.file(e);if(!n)return t;try{return JSON.parse(n.content)}catch{return t}}value(e,t,n){var r;let i=this.defaultJsonSource(n);return i===void 0||(r=de(i,e))==null?t:r}string(e,t=``,n){let r=this.value(e,t,n);return typeof r==`string`?r:t}number(e,t=0,n){let r=this.value(e,t,n);return typeof r==`number`?r:t}bool(e,t=!1,n){let r=this.value(e,t,n);return typeof r==`boolean`?r:t}defaultJsonSource(e){if(e)return this.jsonFile(e,ue);let t=[...this.snapshotProvider().configFiles.values()].filter(e=>e.contentType.includes(`application/json`)||e.name.endsWith(`.json`));if(t.length===1)try{return JSON.parse(t[0].content)}catch{return}}};function k(e){let t=new Date(Number.isFinite(e)?e:Date.now()),n=-t.getTimezoneOffset(),r=n>=0?`+`:`-`,i=Math.abs(n),a=`${r}${A(Math.floor(i/60))}:${A(i%60)}`;return`${t.getFullYear()}-${A(t.getMonth()+1)}-${A(t.getDate())}T${A(t.getHours())}:${A(t.getMinutes())}:${A(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,`0`)}${a}`}function A(e){return String(e).padStart(2,`0`)}function j(e){let t=P(e.versionId);if(!t)throw Error(`script versionId is required: ${e.name}`);return`script:${t}`}async function te(e){let t=`GameAlgo API returned ${e.status}`;try{var n,r;let i=await e.json();return new T(e.status,(n=(r=i.message)==null?i.error:r)==null?t:n,i.error)}catch{return new T(e.status,t)}}function ne(e){let t=e.trim();if(!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(t)||t.includes(`..`))throw Error(`Invalid config file name`);return t}function M(){var e,t,n;return(e=(t=globalThis.crypto)==null||(n=t.randomUUID)==null?void 0:n.call(t))==null?`${Date.now()}-${Math.random().toString(16).slice(2)}`:e}function N(e){return`${e.origin}${e.pathname.replace(/\/+$/,``)}`}function P(e){return(e==null?void 0:e.trim())||void 0}function re(e,t){let n=P(t);return!n||(e===`gaid`||e===`idfa`)&&/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(n)?null:n}function F(e){let t=e==null?0:e;if(!Number.isSafeInteger(t)||t<0)throw Error(`experimentIntegrationVersion must be a non-negative integer`);return t}function ie(e){if(e!==!1)return e==null?(e=>console.log(e)):e}function I(e){return e instanceof Error?e.message:String(e)}function L(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`}catch{return`UTC`}}function ae(){var e;let t={},n=globalThis.navigator,r=globalThis.process;return r!=null&&(e=r.versions)!=null&&e.node?(t.runtime=`node`,t.nodeVersion=r.versions.node):n&&(t.runtime=`browser`),r!=null&&r.platform&&(t.os=r.platform),r!=null&&r.arch&&(t.arch=r.arch),n!=null&&n.language&&(t.locale=n.language),n!=null&&n.platform&&(t.browserPlatform=n.platform),n!=null&&n.userAgent&&(t.userAgent=n.userAgent),t}function R(e){return e&&typeof e==`object`&&!Array.isArray(e)?{...e}:{}}function z(e){let t={},n=R(e);for(let[e,r]of Object.entries(n)){if(!e)continue;let n=se(r);n!==void 0&&(t[e]=n)}return t}function B(e,t,n){let r=e.slice(0,t);if(!n||r.length<=1)return r;let i=[];for(let e of r){let t=[...i,e];if(i.length>0&&oe(JSON.stringify({events:t}))>n)break;i.push(e)}return i}function oe(t){return e(t).byteLength}function se(e){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(e!==void 0)return JSON.stringify(e)}async function V(e,t){if(!/^sha256:[a-f0-9]{64}$/i.test(t))throw Error(`Script hash must use sha256:<64 lowercase hex characters>`);let n=await H(e);if(!n)throw Error(`SHA-256 is unavailable in this runtime`);if(n.toLowerCase()!==t.toLowerCase())throw Error(`Script hash mismatch: expected=${t} actual=${n}`)}async function H(n){var r;if(!((r=globalThis.crypto)!=null&&r.subtle))return`sha256:${t(n)}`;let i=await globalThis.crypto.subtle.digest(`SHA-256`,e(n));return`sha256:${[...new Uint8Array(i)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}function U(e){return JSON.parse(JSON.stringify(e))}function ce(e){let t=U(e);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`attribution must be an object`);return t}function le(e,t,n){let r=G(t);if(r===`organic`)return`organic`;if(K(r))return`unknown`;if(e.toLowerCase()===`adjust`){let e=W(n,`network`),t=W(n,`tracker_name`)||W(n,`trackerName`),r=W(n,`tracker_token`)||W(n,`trackerToken`);if([e,t,r].some(K))return`unknown`;if([e,t,r].some(e=>e===`organic`))return`organic`}return t==null?`attributed`:t}function W(e,t){let n=e[t];return typeof n==`string`?G(n):``}function G(e){return(e==null?``:e).trim().toLowerCase().replace(/[_-]+/g,` `).replace(/\s+/g,` `)}function K(e){return e===`unknown`||e===`unattr`||e===`unattributed`||e===`no user consent`}function q(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>q(e)).join(`,`)}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${q(e[t])}`).join(`,`)}}`}var ue=void 0;function de(e,t){if(!t)return e;let n=e;for(let e of t.split(`.`)){if(Array.isArray(n)){let t=Number(e);n=Number.isInteger(t)?n[t]:void 0}else if(n&&typeof n==`object`)n=n[e];else return;if(n===void 0)return}return n}function J(e){return e===`web`||e===`wechat`||e===`crazygames`}var Y=new WeakSet,fe=class{constructor(e,t,n,r=18e4){if(u(this,`closed`,!1),u(this,`cancel`,void 0),u(this,`host`,void 0),u(this,`report`,void 0),u(this,`logger`,void 0),u(this,`timeoutMs`,void 0),this.host=e,this.report=t,this.logger=n,this.timeoutMs=r,!Number.isFinite(r)||r<=0)throw Error(`adTimeoutMs must be positive`)}createAdSpace({adType:e}){if(this.closed)throw Error(`GamePropel client is closed`);if(e!==`rewarded`&&e!==`midgame`)throw Error(`Invalid CrazyGames ad type`);return Object.freeze({show:(t,n={},r={})=>this.show(e,t,n,r)})}async show(e,t,n,r){if(this.closed)throw Error(`GamePropel client is closed`);if(!/^gap_[a-f0-9]{32}$/.test(t))throw Error(`Invalid GamePropel adPlacementId`);if(!n||typeof n!=`object`||Array.isArray(n)||[n.onStarted,n.onFinished,n.onError].some(e=>e!==void 0&&typeof e!=`function`))throw Error(`Invalid CrazyGames ad callbacks`);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Ad payload must be an object`);let i=this.host.ad;if(Y.has(i))throw Error(`A CrazyGames video ad is already pending`);let a=JSON.parse(JSON.stringify(r));return delete a.trackId,a.hostAdType=e,a.revenueStatus=`unavailable`,a.hostEnvironment=this.host.environment,Y.add(i),new Promise((r,o)=>{var s;let c=!1,l=!1,u=()=>{try{var e;(e=this.logger)==null||e.call(this,`[GamePropelSDK] ad callback failed`)}catch{}},d=e=>{try{Promise.resolve(e==null?void 0:e()).catch(u)}catch{u()}},f=()=>{c=!0,clearTimeout(m),Y.delete(i),this.cancel=void 0},p=e=>{c||(f(),d(n.onError?()=>n.onError(e):void 0),o(Object.assign(Error(e.message),{code:e.code})))},m=setTimeout(()=>p({code:`timeout`,message:`CrazyGames ad callbacks timed out`}),this.timeoutMs);(s=m.unref)==null||s.call(m),this.cancel=()=>{c||(f(),o(Error(`GamePropel client is closed`)))};try{let o=i.requestAd(e,{adStarted:()=>{if(!(c||l)){l=!0;try{this.report(t,a)}catch{u()}d(n.onStarted)}},adFinished:()=>{c||(f(),d(n.onFinished),r())},adError:e=>p(X(e))});Promise.resolve(o).catch(e=>p(X(e)))}catch(e){p(X(e))}})}close(){var e;this.closed=!0,(e=this.cancel)==null||e.call(this)}};function X(e){let t=e;return{code:typeof(t==null?void 0:t.code)==`string`?t.code:`other`,message:typeof(t==null?void 0:t.message)==`string`?t.message:`CrazyGames ad failed`}}function pe(e){var t;let n=e==null?(t=globalThis.CrazyGames)==null?void 0:t.SDK:e;if(!n||typeof n.init!=`function`)throw Error(`Load https://sdk.crazygames.com/crazygames-sdk-v3.js before initializing GamePropel`);return n}var me=class{constructor(e={}){var t,n,r,i;u(this,`databaseName`,void 0),u(this,`storeName`,void 0),u(this,`indexedDB`,void 0),u(this,`localStorage`,void 0),u(this,`memory`,new Map),u(this,`databasePromise`,void 0),u(this,`logger`,void 0),u(this,`operationSequence`,0),this.databaseName=(t=e.databaseName)==null?`gamealgo-sdk`:t,this.storeName=(n=e.storeName)==null?`kv`:n,this.indexedDB=e.indexedDB===null?void 0:(r=e.indexedDB)==null?ve():r,this.localStorage=e.localStorage===null?void 0:(i=e.localStorage)==null?he():i,this.logger=typeof e.logger==`function`?e.logger:void 0;try{var a;(a=this.logger)==null||a.call(this,`[GameAlgoSDK] storage capabilities indexedDB=${!!this.indexedDB} localStorage=${!!this.localStorage}`)}catch{}}async getItem(e){return this.observe(`read ${Z(e)}`,()=>this.readItem(e,!1))}async getItemDurably(e){return this.observe(`read-durable ${Z(e)}`,()=>this.readItem(e,!0))}async readItem(e,t){let n;try{var r,i,a;let n=(r=this.localStorage)==null?void 0:r.getItem(`gamealgo:fallback:${e}`);if(n===`deleted`)return;if(n===`value`)return(i=(a=this.localStorage)==null?void 0:a.getItem(e))==null?t?void 0:this.memory.get(e):i}catch(e){if(t)throw e;n=e}if(this.indexedDB)try{let t=await this.readIndexedDB(e);if(typeof t==`string`)return t}catch(e){if(t)throw e;n=e}try{var o;let t=(o=this.localStorage)==null?void 0:o.getItem(e);if(t!=null)return t}catch(e){n=e}if(t&&n)throw n;return t?void 0:this.memory.get(e)}async setItem(e,t){return this.observe(`write ${Z(e)}`,()=>this.writeItem(e,t,!1))}async setItemDurably(e,t){return this.observe(`write-durable ${Z(e)}`,()=>this.writeItem(e,t,!0))}async writeItem(e,t,n){var r;if(n&&((r=this.localStorage)==null||r.getItem(`gamealgo:fallback:${e}`)),this.memory.set(e,t),this.indexedDB)try{await this.writeIndexedDB(e,t);try{var i,a;(i=this.localStorage)==null||i.removeItem(`gamealgo:fallback:${e}`),(a=this.localStorage)==null||a.removeItem(e)}catch(e){if(n)throw e}return}catch{}try{var o,s;if(!this.localStorage)throw Error(`Persistent browser storage is unavailable`);(o=this.localStorage)==null||o.setItem(e,t),(s=this.localStorage)==null||s.setItem(`gamealgo:fallback:${e}`,`value`)}catch(e){if(n)throw e}}async removeItem(e){return this.observe(`delete ${Z(e)}`,()=>this.deleteItem(e,!1))}async removeItemDurably(e){return this.observe(`delete-durable ${Z(e)}`,()=>this.deleteItem(e,!0))}async deleteItem(e,t){this.memory.delete(e);let n=!1;if(this.indexedDB)try{await this.deleteIndexedDB(e),n=!0}catch{}try{var r,i,a;if(!this.localStorage){if(n)return;throw Error(`Persistent browser storage is unavailable`)}(r=this.localStorage)==null||r.removeItem(e),n?(i=this.localStorage)==null||i.removeItem(`gamealgo:fallback:${e}`):(a=this.localStorage)==null||a.setItem(`gamealgo:fallback:${e}`,`deleted`)}catch(e){if(t)throw e}}database(){return this.indexedDB?(this.databasePromise||(this.databasePromise=this.observe(`indexeddb.open`,()=>new Promise((e,t)=>{let n=this.indexedDB.open(this.databaseName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)},n.onsuccess=()=>e(n.result),n.onerror=()=>{var e;return t((e=n.error)==null?Error(`Unable to open IndexedDB`):e)},n.onblocked=()=>t(Error(`IndexedDB upgrade is blocked`))}))),this.databasePromise):Promise.reject(Error(`IndexedDB is unavailable`))}async readIndexedDB(e){let t=await this.database();return this.observe(`indexeddb.read ${Z(e)}`,()=>ge(t.transaction(this.storeName,`readonly`).objectStore(this.storeName).get(e)))}async writeIndexedDB(e,t){let n=await this.database();await this.observe(`indexeddb.write ${Z(e)}`,async()=>{let r=n.transaction(this.storeName,`readwrite`);r.objectStore(this.storeName).put(t,e),await _e(r)})}async deleteIndexedDB(e){let t=await this.database();await this.observe(`indexeddb.delete ${Z(e)}`,async()=>{let n=t.transaction(this.storeName,`readwrite`);n.objectStore(this.storeName).delete(e),await _e(n)})}async observe(e,t){var n;if(!this.logger)return t();let r=++this.operationSequence,i=Date.now(),a=t=>{try{var n;(n=this.logger)==null||n.call(this,`[GameAlgoSDK] storage op=${r} ${e} ${t} elapsedMs=${Math.max(0,Date.now()-i)}`)}catch{}};a(`started`);let o=setTimeout(()=>a(`pending`),3e3);(n=o.unref)==null||n.call(o);try{let e=await t();return a(`complete resultType=${typeof e}`),e}catch(e){throw a(`failed errorType=${e instanceof Error?e.name:typeof e}`),e}finally{clearTimeout(o)}}};function Z(e){return e.startsWith(`gamealgo:v1:identity:`)?e.endsWith(`:user-id`)?`identity.userId`:e.endsWith(`:created-at`)?`identity.createdAt`:e.endsWith(`:created-local-at`)?`identity.createdLocalAt`:`identity`:e.startsWith(`gamealgo_user_`)?`identity.legacy`:e.startsWith(`gamealgo:v1:event-queue:`)?`event-queue`:e.startsWith(`gamealgo:v1:snapshot:`)?`snapshot`:`cache`}function he(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function ge(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>{var t;return n((t=e.error)==null?Error(`IndexedDB request failed`):t)}})}function _e(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>{var t;return n((t=e.error)==null?Error(`IndexedDB transaction failed`):t)},e.onabort=()=>{var t;return n((t=e.error)==null?Error(`IndexedDB transaction was aborted`):t)}})}function ve(){try{return globalThis.indexedDB}catch{return}}var ye=class{constructor(e={}){u(this,`storage`,void 0),this.storage=new me({...e,databaseName:`gamepropel-crazygames`,storeName:`telemetry`,localStorage:null})}getItem(e){return this.storage.getItemDurably(e)}setItem(e,t){return this.storage.setItemDurably(e,t)}removeItem(e){return this.storage.removeItemDurably(e)}},be=class{constructor(t,n=1e4){if(u(this,`pending`,new Set),u(this,`closed`,!1),u(this,`fetch`,void 0),!Number.isFinite(n)||n<=0)throw Error(`requestTimeoutMs must be positive`);this.fetch=async(r,i={})=>{var a;if(this.closed)throw Error(`GamePropel client is closed`);let o=new AbortController,s=/\/v1\/events\/batch(?:\?|$)/.test(r)&&e((a=i.body)==null?``:a).length<=61440,c,l,u=new Promise((e,t)=>{c=()=>{o.abort(),t(Error(`GamePropel client is closed`))},l=setTimeout(()=>{o.abort(),t(Error(`GamePropel request timed out`))},n)});this.pending.add(c);try{let e=(async()=>{let e=await t(r,{...i,keepalive:s,signal:o.signal}),n=await e.text();return{ok:e.ok,status:e.status,headers:e.headers,text:async()=>n,json:async()=>JSON.parse(n)}})();return await Promise.race([e,u])}finally{l&&clearTimeout(l),this.pending.delete(c)}}}close(){this.closed=!0;for(let e of this.pending)e();this.pending.clear()}},Q=`1.0.0`,xe=Object.freeze({config:!0,parameterExperiments:!0,remoteScripts:!1,multiplayer:!1,rewardedAds:!0,midgameAds:!0,impressionRevenue:!1}),Se=class e extends E{static async init(t){var n;let r=pe(t.crazyGames);if(t.adTimeoutMs!==void 0&&(!Number.isFinite(t.adTimeoutMs)||t.adTimeoutMs<=0))throw Error(`adTimeoutMs must be positive`);let i=(n=t.hostInitTimeoutMs)==null?1e4:n;if(!Number.isFinite(i)||i<=0)throw Error(`hostInitTimeoutMs must be positive`);let a;try{await Promise.race([r.init(),new Promise((e,t)=>{a=setTimeout(()=>t(Error(`CrazyGames initialization timed out`)),i)})])}finally{a&&clearTimeout(a)}if(r.environment!==`crazygames`&&r.environment!==`local`)throw Error(`CrazyGames SDK is disabled on this domain`);return new e(t,r)}constructor(e,t){var n,r,i,a,o,s,c,l,d;let f=(n=e.fetchImpl)==null?(r=globalThis.fetch)==null?void 0:r.bind(globalThis):n;if(!f)throw Error(`Browser fetch is required`);let p=new be(f,e.requestTimeoutMs);super({...e,platform:`crazygames`,sdkVersion:Q,storage:(i=e.storage)==null?new ye(e.browserStorage):i,fetchImpl:p.fetch,scriptRuntime:{execute(){throw Error(`CrazyGames SDK 1.x supports parameter experiments; remote scripts are unavailable`)}},isDebug:t.environment===`local`||e.isDebug,eventFlushIntervalMs:(a=e.eventFlushIntervalMs)==null?5e3:a,eventMaxBatchSize:Math.min((o=e.eventMaxBatchSize)==null?20:o,20),eventMaxBatchBytes:Math.min((s=e.eventMaxBatchBytes)==null?49152:s,49152),eventQueueLimit:(c=e.eventQueueLimit)==null?500:c,eventPersistOnEnqueue:!0,logger:(l=e.logger)!=null&&l,device:$(e.device)}),u(this,`host`,void 0),u(this,`transport`,void 0),u(this,`ads`,void 0),u(this,`win`,typeof window>`u`?void 0:window),u(this,`doc`,typeof document>`u`?void 0:document),u(this,`releases`,[]),u(this,`autoSessionLifecycle`,void 0),u(this,`preload`,void 0),u(this,`deviceOverrides`,void 0),u(this,`closed`,!1),u(this,`endedSessionId`,void 0),u(this,`onVisibility`,()=>{var e,t;((e=this.doc)==null?void 0:e.visibilityState)===`hidden`?this.endSession(`visibility_hidden`):((t=this.doc)==null?void 0:t.visibilityState)===`visible`&&this.resume()}),u(this,`onPageHide`,()=>this.endSession(`pagehide`)),u(this,`onPageShow`,()=>{var e;((e=this.doc)==null?void 0:e.visibilityState)!==`hidden`&&this.resume()}),u(this,`onOnline`,()=>this.flushInBackground()),this.host=t,this.deviceOverrides=$(e.device),this.transport=p,this.autoSessionLifecycle=e.autoSessionLifecycle!==!1,this.preload=(d=e.preloadConfigFiles)==null||d,this.tracker.setSessionDurationVisibility(()=>{var e;return((e=this.doc)==null?void 0:e.visibilityState)!==`hidden`}),this.ads=new fe(t,(e,t)=>{this.tracker.trackAdPlacement(e,0,`crazygames`,t)},typeof e.logger==`function`?e.logger:void 0,e.adTimeoutMs),e.autoLifecycle!==!1&&(this.listen(this.doc,`visibilitychange`,this.onVisibility),this.listen(this.win,`pagehide`,this.onPageHide),this.listen(this.win,`pageshow`,this.onPageShow),this.listen(this.win,`online`,this.onOnline))}createAdSpace(e){return this.ads.createAdSpace(e)}getForegroundTimeMs(){return this.tracker.getForegroundTimeMs()}async flush(){await this.tracker.flushUrgent(),await this.tracker.flush()}fetchConfig(e={}){return this.closed?Promise.reject(Error(`GamePropel client is closed`)):super.fetchConfig({...e,platform:`crazygames`,sdkVersion:Q,isDebug:this.host.environment===`local`||e.isDebug,device:$(e.device)})}async refresh(e={}){var t;let n=await this.fetchConfig(e);if(this.closed)return;let r=(t=e.preloadConfigFiles)==null?this.preload:t;if(r===!1)return;let i=n.configFiles.filter(e=>{var t;return e.name.endsWith(`.json`)||((t=e.contentType)==null?void 0:t.includes(`application/json`))}).filter(e=>!Array.isArray(r)||r.includes(e.name)).map(e=>e.name);await Promise.all([...new Set(i)].map(e=>this.fetchConfigFile(e)))}defaultDeviceContext(){let e={...this.deviceOverrides,runtime:`crazygames`,remoteScripts:!1,crazyGamesEnvironment:this.host.environment};try{var t,n,r,i,a,o;let s=(t=this.host.user)==null?void 0:t.systemInfo,c={locale:s==null?void 0:s.locale,countryCode:s==null?void 0:s.countryCode,deviceType:s==null||(n=s.device)==null?void 0:n.type,osVersion:s==null||(r=s.os)==null?void 0:r.version,browser:s==null||(i=s.browser)==null?void 0:i.name,browserVersion:s==null||(a=s.browser)==null?void 0:a.version,applicationType:s==null?void 0:s.applicationType};for(let[t,n]of Object.entries(c))typeof n==`string`&&n.trim()&&(e[t]=n.trim().slice(0,128));let l=s==null||(o=s.os)==null||(o=o.name)==null?void 0:o.toLowerCase(),u=l&&{ios:`ios`,android:`android`,windows:`windows`,"mac os":`macos`,macos:`macos`,linux:`linux`,"chromium os":`chromeos`,"chrome os":`chromeos`}[l];u&&(e.os=u)}catch{}return e}onConfigReady(){var e;((e=this.doc)==null?void 0:e.visibilityState)===`hidden`&&this.endSession(`visibility_hidden`)}close(){if(!this.closed){this.closed=!0;for(let e of this.releases.splice(0))e();this.ads.close(),this.tracker.close(),this.transport.close()}}listen(e,t,n){e==null||e.addEventListener(t,n),this.releases.push(()=>e==null?void 0:e.removeEventListener(t,n))}endSession(e){if(this.closed)return;this.tracker.observeSessionDurationVisibility();let t=this.tracker.currentSessionId();this.autoSessionLifecycle&&this.endedSessionId!==t&&this.tracker.trackSessionEndSnapshot({reason:e})&&(this.endedSessionId=t),this.flushInBackground()}resume(){if(this.closed)return;this.tracker.observeSessionDurationVisibility();let e=this.endedSessionId!==void 0;this.endedSessionId=void 0,this.flushInBackground(),e&&this.refresh({forceRefresh:!0}).catch(()=>void 0)}flushInBackground(){this.closed||(this.tracker.flushUrgent().catch(()=>void 0),this.tracker.flush().catch(()=>void 0))}};function $(e){let t={...e};for(let e of[`runtime`,`remoteScripts`,`runtimeMiniappId`,`runtimeProjectId`,`runtimeAppId`,`runtimeIdentitySource`,`wechatAppId`,`crazyGamesEnvironment`,`os`,`osVersion`,`locale`,`countryCode`,`deviceType`,`browser`,`browserVersion`,`applicationType`])delete t[e];return t}function Ce(e){return Se.init(e)}exports.GAMEPROPEL_CRAZYGAMES_CAPABILITIES=xe,exports.GAMEPROPEL_CRAZYGAMES_SDK_VERSION=Q,exports.GamePropelCrazyGamesClient=Se,exports.GamePropelCrazyGamesStorage=ye,exports.initGamePropelCrazyGames=Ce;
|
|
5
|
+
//# sourceMappingURL=index.js.map
|