@hyve-sdk/js 2.13.0 → 2.14.0-canary.1

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/dist/react.d.ts CHANGED
@@ -256,6 +256,25 @@ interface HyveClientConfig extends TelemetryConfig {
256
256
  billing?: BillingConfig;
257
257
  /** Storage mode for persistent game data - 'cloud' (default) or 'local' */
258
258
  storageMode?: 'cloud' | 'local';
259
+ /**
260
+ * Partner API key for externally-hosted games (e.g. CrazyGames) that cannot
261
+ * carry a hyve JWT. When set, telemetry is sent to the partner analytics
262
+ * endpoint with an `x-api-key` header instead of the JWT path. The key is
263
+ * scoped to the `analytics` domain and bound to a game_id server-side.
264
+ * NOTE: this key ships in client-side game code and is therefore public.
265
+ */
266
+ partnerApiKey?: string;
267
+ /**
268
+ * Optional base URL for partner analytics requests. Defaults to apiBaseUrl
269
+ * when omitted.
270
+ */
271
+ partnerApiBaseUrl?: string;
272
+ /**
273
+ * Game ID for externally-hosted builds (e.g. CrazyGames) whose URL carries
274
+ * no `game-id` parameter or hyve JWT. Used for storage key namespacing and
275
+ * telemetry. A `game-id` URL parameter still takes precedence when present.
276
+ */
277
+ gameId?: string;
259
278
  }
260
279
  /**
261
280
  * HyveClient provides telemetry and authentication functionality for Hyve games
@@ -276,6 +295,11 @@ declare class HyveClient {
276
295
  private storageMode;
277
296
  private cloudStorageAdapter;
278
297
  private localStorageAdapter;
298
+ private crazyGamesStorageAdapter;
299
+ private partnerApiKey;
300
+ private partnerApiBaseUrl;
301
+ /** Raw (unprefixed) CrazyGames __dangerousUserId, seeded at init and on login. */
302
+ private crazyGamesUserId;
279
303
  /**
280
304
  * Creates a new HyveClient instance
281
305
  * @param config Optional configuration including telemetry and ads
@@ -299,6 +323,28 @@ declare class HyveClient {
299
323
  * @returns Promise resolving to boolean indicating success
300
324
  */
301
325
  sendTelemetry(eventLocation: string, eventCategory: string, eventAction: string, eventSubCategory?: string | null, eventSubAction?: string | null, eventDetails?: Record<string, any> | string | null, platformId?: string | null): Promise<boolean>;
326
+ /**
327
+ * Validates and enriches user-provided event details with device info,
328
+ * attribution data, and session context — matching the enrichment
329
+ * platform-v2 applies in sendAnalyticsEvent. Shared by the JWT and partner
330
+ * telemetry paths.
331
+ * @returns Enriched details object, or null if eventDetails is not valid JSON.
332
+ */
333
+ private enrichEventDetails;
334
+ /**
335
+ * Sends a telemetry event via the partner analytics endpoint using a partner
336
+ * API key (x-api-key) instead of a hyve JWT. Used by externally-hosted games
337
+ * such as CrazyGames. game_id is derived from the API key server-side and is
338
+ * therefore not sent. hyve_user_id carries the `cg:`-prefixed CrazyGames id,
339
+ * or a guest sentinel when the player is not logged in.
340
+ */
341
+ private sendPartnerTelemetry;
342
+ /**
343
+ * Seeds the CrazyGames user id used for telemetry attribution and registers
344
+ * an auth listener so the id updates if a guest logs in mid-session.
345
+ * The id is client-asserted (spoofable) and used only as an attribution label.
346
+ */
347
+ private seedCrazyGamesUser;
302
348
  /**
303
349
  * Required lifecycle telemetry — Session start.
304
350
  * See https://docs.hyve.gg/docs/telemetry#required-lifecycle-events
@@ -419,7 +465,15 @@ declare class HyveClient {
419
465
  */
420
466
  reset(): void;
421
467
  /**
422
- * Get the storage adapter based on mode
468
+ * Get the storage adapter based on mode.
469
+ *
470
+ * Selection order:
471
+ * 1. An explicit `mode` override ('cloud' | 'local') always wins.
472
+ * 2. On the CrazyGames platform, the CrazyGames data store is auto-selected
473
+ * (D3 — public storageMode type is preserved; this is chosen internally).
474
+ * 3. Otherwise the configured storageMode is used.
475
+ *
476
+ * Awaits CrazyGames SDK initialization so the data store is ready before use.
423
477
  * @param mode Storage mode override (cloud or local)
424
478
  */
425
479
  private getStorageAdapter;
package/dist/react.js CHANGED
@@ -1199,6 +1199,7 @@ var PlaygamaService = class {
1199
1199
  var CRAZYGAMES_SDK_CDN = "https://sdk.crazygames.com/crazygames-sdk-v2.js";
1200
1200
  var CrazyGamesService = class {
1201
1201
  initialized = false;
1202
+ environment = null;
1202
1203
  /**
1203
1204
  * Detects if the game is running on the CrazyGames platform.
1204
1205
  * Games on CrazyGames run inside an iframe, so we check document.referrer
@@ -1240,6 +1241,7 @@ var CrazyGamesService = class {
1240
1241
  logger.warn("[CrazyGamesService] Unexpected environment:", env);
1241
1242
  return false;
1242
1243
  }
1244
+ this.environment = env;
1243
1245
  this.initialized = true;
1244
1246
  return true;
1245
1247
  } catch (error) {
@@ -1350,6 +1352,88 @@ var CrazyGamesService = class {
1350
1352
  if (!this.initialized) return;
1351
1353
  window.CrazyGames?.SDK.game.happytime();
1352
1354
  }
1355
+ /**
1356
+ * Returns the resolved CrazyGames environment ('crazygames' | 'local' |
1357
+ * 'disabled'), or null if the SDK has not initialized yet. Used to
1358
+ * auto-select the CrazyGames storage adapter.
1359
+ */
1360
+ getEnvironment() {
1361
+ return this.environment;
1362
+ }
1363
+ /**
1364
+ * Whether the CrazyGames account system is present (sync). When false,
1365
+ * there is no logged-in user concept and telemetry falls back to guests.
1366
+ */
1367
+ isUserAccountAvailable() {
1368
+ if (!this.initialized) return false;
1369
+ return window.CrazyGames?.SDK.user.isUserAccountAvailable ?? false;
1370
+ }
1371
+ /**
1372
+ * Fetches the current CrazyGames user, or null if the player is not logged
1373
+ * in (guest). The returned `__dangerousUserId` is client-asserted and used
1374
+ * only as a telemetry attribution label.
1375
+ */
1376
+ async getUser() {
1377
+ const sdk = window.CrazyGames?.SDK;
1378
+ if (!this.initialized || !sdk || !this.isUserAccountAvailable()) {
1379
+ return null;
1380
+ }
1381
+ try {
1382
+ return await sdk.user.getUser() ?? null;
1383
+ } catch (error) {
1384
+ logger.warn("[CrazyGamesService] getUser failed:", error);
1385
+ return null;
1386
+ }
1387
+ }
1388
+ /**
1389
+ * Registers a listener that fires when a guest logs in mid-session.
1390
+ * No-op if the SDK or account system is unavailable.
1391
+ */
1392
+ addAuthListener(callback) {
1393
+ const sdk = window.CrazyGames?.SDK;
1394
+ if (!this.initialized || !sdk || !this.isUserAccountAvailable()) return;
1395
+ try {
1396
+ sdk.user.addAuthListener(callback);
1397
+ } catch (error) {
1398
+ logger.warn("[CrazyGamesService] addAuthListener failed:", error);
1399
+ }
1400
+ }
1401
+ /** Removes a previously registered auth listener. */
1402
+ removeAuthListener(callback) {
1403
+ const sdk = window.CrazyGames?.SDK;
1404
+ if (!this.initialized || !sdk) return;
1405
+ try {
1406
+ sdk.user.removeAuthListener(callback);
1407
+ } catch (error) {
1408
+ logger.warn("[CrazyGamesService] removeAuthListener failed:", error);
1409
+ }
1410
+ }
1411
+ /**
1412
+ * Reads a value from the CrazyGames data store. Returns null when the SDK
1413
+ * is unavailable or the key is absent.
1414
+ */
1415
+ async dataGetItem(key) {
1416
+ const sdk = window.CrazyGames?.SDK;
1417
+ if (!this.initialized || !sdk) return null;
1418
+ const value = await sdk.data.getItem(key);
1419
+ return value ?? null;
1420
+ }
1421
+ /** Writes a value to the CrazyGames data store. */
1422
+ async dataSetItem(key, value) {
1423
+ const sdk = window.CrazyGames?.SDK;
1424
+ if (!this.initialized || !sdk) {
1425
+ throw new Error("CrazyGames SDK not initialized");
1426
+ }
1427
+ await sdk.data.setItem(key, value);
1428
+ }
1429
+ /** Removes a value from the CrazyGames data store. */
1430
+ async dataRemoveItem(key) {
1431
+ const sdk = window.CrazyGames?.SDK;
1432
+ if (!this.initialized || !sdk) {
1433
+ throw new Error("CrazyGames SDK not initialized");
1434
+ }
1435
+ await sdk.data.removeItem(key);
1436
+ }
1353
1437
  loadScript() {
1354
1438
  return new Promise((resolve, reject) => {
1355
1439
  if (window.CrazyGames?.SDK) {
@@ -2011,6 +2095,162 @@ var LocalStorageAdapter = class {
2011
2095
  return count;
2012
2096
  }
2013
2097
  };
2098
+ function isGameDataObject(value) {
2099
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2100
+ }
2101
+ function toNumber(value) {
2102
+ return typeof value === "number" ? value : 0;
2103
+ }
2104
+ function applyOperation(operation, current, operand) {
2105
+ switch (operation) {
2106
+ case "set":
2107
+ return operand;
2108
+ case "add":
2109
+ return toNumber(current) + toNumber(operand);
2110
+ case "subtract":
2111
+ return toNumber(current) - toNumber(operand);
2112
+ case "multiply":
2113
+ return toNumber(current) * toNumber(operand);
2114
+ case "divide": {
2115
+ const divisor = toNumber(operand);
2116
+ if (divisor === 0) throw new Error("Cannot divide by zero");
2117
+ return toNumber(current) / divisor;
2118
+ }
2119
+ case "modulo": {
2120
+ const divisor = toNumber(operand);
2121
+ if (divisor === 0) throw new Error("Cannot modulo by zero");
2122
+ return toNumber(current) % divisor;
2123
+ }
2124
+ // For min/max, a missing current has nothing to compare against — adopt the operand.
2125
+ case "min":
2126
+ return typeof current === "number" ? Math.min(current, toNumber(operand)) : operand;
2127
+ case "max":
2128
+ return typeof current === "number" ? Math.max(current, toNumber(operand)) : operand;
2129
+ case "append": {
2130
+ const base = Array.isArray(current) ? [...current] : current === void 0 || current === null ? [] : [current];
2131
+ if (Array.isArray(operand)) {
2132
+ base.push(...operand);
2133
+ } else {
2134
+ base.push(operand);
2135
+ }
2136
+ return base;
2137
+ }
2138
+ default:
2139
+ return operand;
2140
+ }
2141
+ }
2142
+ function getAtPath(value, path) {
2143
+ let current = value;
2144
+ for (const segment of path.split(".")) {
2145
+ if (!isGameDataObject(current)) return void 0;
2146
+ current = current[segment];
2147
+ }
2148
+ return current;
2149
+ }
2150
+ function setAtPath(value, path, newValue) {
2151
+ const segments = path.split(".");
2152
+ const root = isGameDataObject(value) ? { ...value } : {};
2153
+ let cursor = root;
2154
+ for (let i = 0; i < segments.length - 1; i++) {
2155
+ const segment = segments[i];
2156
+ const existing = cursor[segment];
2157
+ const next = isGameDataObject(existing) ? { ...existing } : {};
2158
+ cursor[segment] = next;
2159
+ cursor = next;
2160
+ }
2161
+ cursor[segments[segments.length - 1]] = newValue;
2162
+ return root;
2163
+ }
2164
+ var CrazyGamesStorageAdapter = class {
2165
+ constructor(service) {
2166
+ this.service = service;
2167
+ }
2168
+ getStorageKey(gameId, key) {
2169
+ return `${gameId}:${key}`;
2170
+ }
2171
+ async saveGameData(gameId, key, value, operation, path) {
2172
+ const storageKey = this.getStorageKey(gameId, key);
2173
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2174
+ const existingRaw = await this.service.dataGetItem(storageKey);
2175
+ const existing = existingRaw ? JSON.parse(existingRaw) : null;
2176
+ const createdAt = existing?.created_at ?? now;
2177
+ const useOperation = operation !== void 0;
2178
+ let storedValue;
2179
+ let opResult;
2180
+ if (path) {
2181
+ const current = getAtPath(existing?.value, path);
2182
+ const next = useOperation ? applyOperation(operation, current, value) : value;
2183
+ storedValue = setAtPath(existing?.value, path, next);
2184
+ opResult = next;
2185
+ } else {
2186
+ const current = existing?.value;
2187
+ const next = useOperation ? applyOperation(operation, current, value) : value;
2188
+ storedValue = next;
2189
+ opResult = next;
2190
+ }
2191
+ const item = {
2192
+ key,
2193
+ value: storedValue,
2194
+ created_at: createdAt,
2195
+ updated_at: now
2196
+ };
2197
+ await this.service.dataSetItem(storageKey, JSON.stringify(item));
2198
+ const response = { success: true, message: "Data saved successfully" };
2199
+ if (useOperation && operation !== "set") {
2200
+ response.result = opResult;
2201
+ }
2202
+ return response;
2203
+ }
2204
+ async batchSaveGameData(gameId, items) {
2205
+ const results = [];
2206
+ let usedOperation = false;
2207
+ for (const item of items) {
2208
+ if (item.operation !== void 0) usedOperation = true;
2209
+ try {
2210
+ const saved = await this.saveGameData(gameId, item.key, item.value, item.operation, item.path);
2211
+ results.push({ key: item.key, success: true, ...saved.result !== void 0 && { result: saved.result } });
2212
+ } catch (error) {
2213
+ results.push({
2214
+ key: item.key,
2215
+ success: false,
2216
+ error: error instanceof Error ? error.message : "Unknown error"
2217
+ });
2218
+ }
2219
+ }
2220
+ const allSucceeded = results.every((r) => r.success);
2221
+ return {
2222
+ success: allSucceeded,
2223
+ message: `${results.filter((r) => r.success).length}/${items.length} items saved`,
2224
+ ...usedOperation && { results }
2225
+ };
2226
+ }
2227
+ async getGameData(gameId, key) {
2228
+ const raw = await this.service.dataGetItem(this.getStorageKey(gameId, key));
2229
+ return raw ? JSON.parse(raw) : null;
2230
+ }
2231
+ async getMultipleGameData(gameId, keys) {
2232
+ const items = [];
2233
+ for (const key of keys) {
2234
+ const item = await this.getGameData(gameId, key);
2235
+ if (item) items.push(item);
2236
+ }
2237
+ return items;
2238
+ }
2239
+ async deleteGameData(gameId, key) {
2240
+ const storageKey = this.getStorageKey(gameId, key);
2241
+ const existing = await this.service.dataGetItem(storageKey);
2242
+ if (existing === null) return false;
2243
+ await this.service.dataRemoveItem(storageKey);
2244
+ return true;
2245
+ }
2246
+ async deleteMultipleGameData(gameId, keys) {
2247
+ let count = 0;
2248
+ for (const key of keys) {
2249
+ if (await this.deleteGameData(gameId, key)) count++;
2250
+ }
2251
+ return count;
2252
+ }
2253
+ };
2014
2254
 
2015
2255
  // src/core/client.ts
2016
2256
  function determineEnvironmentFromParentUrl() {
@@ -2057,6 +2297,11 @@ var HyveClient = class {
2057
2297
  storageMode;
2058
2298
  cloudStorageAdapter;
2059
2299
  localStorageAdapter;
2300
+ crazyGamesStorageAdapter = null;
2301
+ partnerApiKey = null;
2302
+ partnerApiBaseUrl = null;
2303
+ /** Raw (unprefixed) CrazyGames __dangerousUserId, seeded at init and on login. */
2304
+ crazyGamesUserId = null;
2060
2305
  /**
2061
2306
  * Creates a new HyveClient instance
2062
2307
  * @param config Optional configuration including telemetry and ads
@@ -2084,10 +2329,17 @@ var HyveClient = class {
2084
2329
  return success;
2085
2330
  });
2086
2331
  }
2332
+ this.partnerApiKey = config?.partnerApiKey ?? null;
2333
+ this.partnerApiBaseUrl = config?.partnerApiBaseUrl ?? null;
2334
+ this.gameId = config?.gameId ?? null;
2087
2335
  if (typeof window !== "undefined" && CrazyGamesService.isCrazyGamesDomain()) {
2088
2336
  this.crazyGamesService = new CrazyGamesService();
2089
- this.crazyGamesInitPromise = this.crazyGamesService.initialize().then((success) => {
2337
+ this.crazyGamesStorageAdapter = new CrazyGamesStorageAdapter(this.crazyGamesService);
2338
+ this.crazyGamesInitPromise = this.crazyGamesService.initialize().then(async (success) => {
2090
2339
  logger.info("CrazyGames SDK initialized:", success);
2340
+ if (success) {
2341
+ await this.seedCrazyGamesUser();
2342
+ }
2091
2343
  return success;
2092
2344
  });
2093
2345
  }
@@ -2124,6 +2376,7 @@ var HyveClient = class {
2124
2376
  !!config?.billing && Object.keys(config.billing).length > 0
2125
2377
  );
2126
2378
  logger.info("Storage mode:", this.storageMode);
2379
+ logger.info("Game ID:", this.gameId ?? "not set");
2127
2380
  logger.info("Authenticated:", this.jwtToken !== null);
2128
2381
  logger.debug("Config:", {
2129
2382
  isDev: this.telemetryConfig.isDev,
@@ -2183,6 +2436,16 @@ var HyveClient = class {
2183
2436
  * @returns Promise resolving to boolean indicating success
2184
2437
  */
2185
2438
  async sendTelemetry(eventLocation, eventCategory, eventAction, eventSubCategory, eventSubAction, eventDetails, platformId) {
2439
+ if (this.partnerApiKey) {
2440
+ return this.sendPartnerTelemetry(
2441
+ eventLocation,
2442
+ eventCategory,
2443
+ eventAction,
2444
+ eventSubCategory,
2445
+ eventSubAction,
2446
+ eventDetails
2447
+ );
2448
+ }
2186
2449
  if (!this.jwtToken) {
2187
2450
  logger.error("JWT token required. Ensure hyve-access and game-id are present in the URL.");
2188
2451
  return false;
@@ -2192,42 +2455,11 @@ var HyveClient = class {
2192
2455
  return false;
2193
2456
  }
2194
2457
  try {
2195
- if (eventDetails) {
2196
- try {
2197
- if (typeof eventDetails === "string") {
2198
- JSON.parse(eventDetails);
2199
- } else if (typeof eventDetails === "object") {
2200
- JSON.stringify(eventDetails);
2201
- }
2202
- } catch (validationError) {
2203
- logger.error("Invalid JSON in eventDetails:", validationError);
2204
- logger.error("eventDetails value:", eventDetails);
2205
- return false;
2206
- }
2207
- }
2208
- let parsedEventDetails = {};
2209
- if (eventDetails) {
2210
- if (typeof eventDetails === "string") {
2211
- try {
2212
- parsedEventDetails = JSON.parse(eventDetails);
2213
- } catch {
2214
- }
2215
- } else {
2216
- parsedEventDetails = eventDetails;
2217
- }
2458
+ const enrichedEventDetails = this.enrichEventDetails(eventDetails);
2459
+ if (enrichedEventDetails === null) {
2460
+ return false;
2218
2461
  }
2219
2462
  const attribution = getAttributionData();
2220
- const enrichedEventDetails = {
2221
- // Device info
2222
- ...getEssentialDeviceInfo(),
2223
- // Attribution data
2224
- ...attribution,
2225
- // Timestamp and session context
2226
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2227
- session_id: this.sessionId,
2228
- // Event-specific details can override any of the above
2229
- ...parsedEventDetails
2230
- };
2231
2463
  const telemetryEvent = {
2232
2464
  game_id: this.gameId,
2233
2465
  session_id: this.sessionId,
@@ -2266,6 +2498,122 @@ var HyveClient = class {
2266
2498
  return false;
2267
2499
  }
2268
2500
  }
2501
+ /**
2502
+ * Validates and enriches user-provided event details with device info,
2503
+ * attribution data, and session context — matching the enrichment
2504
+ * platform-v2 applies in sendAnalyticsEvent. Shared by the JWT and partner
2505
+ * telemetry paths.
2506
+ * @returns Enriched details object, or null if eventDetails is not valid JSON.
2507
+ */
2508
+ enrichEventDetails(eventDetails) {
2509
+ let parsedEventDetails = {};
2510
+ if (eventDetails) {
2511
+ try {
2512
+ if (typeof eventDetails === "string") {
2513
+ parsedEventDetails = JSON.parse(eventDetails);
2514
+ } else if (typeof eventDetails === "object") {
2515
+ JSON.stringify(eventDetails);
2516
+ parsedEventDetails = eventDetails;
2517
+ }
2518
+ } catch (validationError) {
2519
+ logger.error("Invalid JSON in eventDetails:", validationError);
2520
+ logger.error("eventDetails value:", eventDetails);
2521
+ return null;
2522
+ }
2523
+ }
2524
+ const attribution = getAttributionData();
2525
+ return {
2526
+ // Device info
2527
+ ...getEssentialDeviceInfo(),
2528
+ // Attribution data
2529
+ ...attribution,
2530
+ // Timestamp and session context
2531
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2532
+ session_id: this.sessionId,
2533
+ // Event-specific details can override any of the above
2534
+ ...parsedEventDetails
2535
+ };
2536
+ }
2537
+ /**
2538
+ * Sends a telemetry event via the partner analytics endpoint using a partner
2539
+ * API key (x-api-key) instead of a hyve JWT. Used by externally-hosted games
2540
+ * such as CrazyGames. game_id is derived from the API key server-side and is
2541
+ * therefore not sent. hyve_user_id carries the `cg:`-prefixed CrazyGames id,
2542
+ * or a guest sentinel when the player is not logged in.
2543
+ */
2544
+ async sendPartnerTelemetry(eventLocation, eventCategory, eventAction, eventSubCategory, eventSubAction, eventDetails) {
2545
+ if (!this.partnerApiKey) {
2546
+ logger.error("Partner API key required for partner telemetry path.");
2547
+ return false;
2548
+ }
2549
+ if (this.crazyGamesService && this.crazyGamesInitPromise) {
2550
+ await this.crazyGamesInitPromise;
2551
+ }
2552
+ try {
2553
+ const enrichedEventDetails = this.enrichEventDetails(eventDetails);
2554
+ if (enrichedEventDetails === null) {
2555
+ return false;
2556
+ }
2557
+ const hyveUserId = this.crazyGamesUserId ? `cg:${this.crazyGamesUserId}` : "cg:guest";
2558
+ const partnerEvent = {
2559
+ session_id: this.sessionId,
2560
+ hyve_user_id: hyveUserId,
2561
+ event_location: eventLocation,
2562
+ event_category: eventCategory,
2563
+ event_sub_category: eventSubCategory || null,
2564
+ event_action: eventAction,
2565
+ event_sub_action: eventSubAction || null,
2566
+ event_details: enrichedEventDetails
2567
+ };
2568
+ logger.debug("Sending partner telemetry event:", partnerEvent);
2569
+ const base = this.partnerApiBaseUrl || this.apiBaseUrl;
2570
+ const telemetryUrl = `${base}/api/v1/partners/analytics/events`;
2571
+ const response = await fetch(telemetryUrl, {
2572
+ method: "POST",
2573
+ headers: {
2574
+ "Content-Type": "application/json",
2575
+ "x-api-key": this.partnerApiKey
2576
+ },
2577
+ body: JSON.stringify(partnerEvent)
2578
+ });
2579
+ if (response.ok) {
2580
+ logger.info("Partner telemetry event sent successfully:", response.status);
2581
+ return true;
2582
+ } else {
2583
+ const errorText = await response.text();
2584
+ logger.error(
2585
+ "Failed to send partner telemetry event:",
2586
+ response.status,
2587
+ errorText
2588
+ );
2589
+ return false;
2590
+ }
2591
+ } catch (error) {
2592
+ logger.error("Error sending partner telemetry event:", error);
2593
+ return false;
2594
+ }
2595
+ }
2596
+ /**
2597
+ * Seeds the CrazyGames user id used for telemetry attribution and registers
2598
+ * an auth listener so the id updates if a guest logs in mid-session.
2599
+ * The id is client-asserted (spoofable) and used only as an attribution label.
2600
+ */
2601
+ async seedCrazyGamesUser() {
2602
+ if (!this.crazyGamesService) return;
2603
+ if (!this.crazyGamesService.isUserAccountAvailable()) {
2604
+ logger.info("CrazyGames account system unavailable \u2014 telemetry attributed by session only");
2605
+ return;
2606
+ }
2607
+ const user = await this.crazyGamesService.getUser();
2608
+ this.crazyGamesUserId = user?.__dangerousUserId ?? null;
2609
+ if (this.crazyGamesUserId) {
2610
+ logger.info("CrazyGames user id seeded for telemetry attribution");
2611
+ }
2612
+ this.crazyGamesService.addAuthListener((updatedUser) => {
2613
+ this.crazyGamesUserId = updatedUser?.__dangerousUserId ?? null;
2614
+ logger.info("CrazyGames auth state changed; telemetry user id updated");
2615
+ });
2616
+ }
2269
2617
  /**
2270
2618
  * Required lifecycle telemetry — Session start.
2271
2619
  * See https://docs.hyve.gg/docs/telemetry#required-lifecycle-events
@@ -2486,12 +2834,28 @@ var HyveClient = class {
2486
2834
  logger.info("Client reset with new sessionId:", this.sessionId);
2487
2835
  }
2488
2836
  /**
2489
- * Get the storage adapter based on mode
2837
+ * Get the storage adapter based on mode.
2838
+ *
2839
+ * Selection order:
2840
+ * 1. An explicit `mode` override ('cloud' | 'local') always wins.
2841
+ * 2. On the CrazyGames platform, the CrazyGames data store is auto-selected
2842
+ * (D3 — public storageMode type is preserved; this is chosen internally).
2843
+ * 3. Otherwise the configured storageMode is used.
2844
+ *
2845
+ * Awaits CrazyGames SDK initialization so the data store is ready before use.
2490
2846
  * @param mode Storage mode override (cloud or local)
2491
2847
  */
2492
- getStorageAdapter(mode) {
2493
- const storageMode = mode || this.storageMode;
2494
- return storageMode === "local" ? this.localStorageAdapter : this.cloudStorageAdapter;
2848
+ async getStorageAdapter(mode) {
2849
+ if (mode) {
2850
+ return mode === "local" ? this.localStorageAdapter : this.cloudStorageAdapter;
2851
+ }
2852
+ if (this.crazyGamesService && this.crazyGamesStorageAdapter) {
2853
+ if (this.crazyGamesInitPromise) await this.crazyGamesInitPromise;
2854
+ if (this.crazyGamesService.getEnvironment() === "crazygames") {
2855
+ return this.crazyGamesStorageAdapter;
2856
+ }
2857
+ }
2858
+ return this.storageMode === "local" ? this.localStorageAdapter : this.cloudStorageAdapter;
2495
2859
  }
2496
2860
  /**
2497
2861
  * Returns the current game ID or throws if not available.
@@ -2515,7 +2879,7 @@ var HyveClient = class {
2515
2879
  const gameId = this.requireGameId();
2516
2880
  const storageMode = storage || this.storageMode;
2517
2881
  logger.debug(`Saving game data to ${storageMode}: ${gameId}/${key}`);
2518
- const adapter = this.getStorageAdapter(storage);
2882
+ const adapter = await this.getStorageAdapter(storage);
2519
2883
  const response = await adapter.saveGameData(gameId, key, value, operation, path);
2520
2884
  logger.info(`Game data saved successfully to ${storageMode}: ${gameId}/${key}`);
2521
2885
  return response;
@@ -2530,7 +2894,7 @@ var HyveClient = class {
2530
2894
  const gameId = this.requireGameId();
2531
2895
  const storageMode = storage || this.storageMode;
2532
2896
  logger.debug(`Batch saving ${items.length} game data entries to ${storageMode} for game: ${gameId}`);
2533
- const adapter = this.getStorageAdapter(storage);
2897
+ const adapter = await this.getStorageAdapter(storage);
2534
2898
  const response = await adapter.batchSaveGameData(gameId, items);
2535
2899
  logger.info(`Batch saved ${items.length} game data entries successfully to ${storageMode}`);
2536
2900
  return response;
@@ -2545,7 +2909,7 @@ var HyveClient = class {
2545
2909
  const gameId = this.requireGameId();
2546
2910
  const storageMode = storage || this.storageMode;
2547
2911
  logger.debug(`Getting game data from ${storageMode}: ${gameId}/${key}`);
2548
- const adapter = this.getStorageAdapter(storage);
2912
+ const adapter = await this.getStorageAdapter(storage);
2549
2913
  const data = await adapter.getGameData(gameId, key);
2550
2914
  if (data) {
2551
2915
  logger.info(`Game data retrieved successfully from ${storageMode}: ${gameId}/${key}`);
@@ -2564,7 +2928,7 @@ var HyveClient = class {
2564
2928
  const gameId = this.requireGameId();
2565
2929
  const storageMode = storage || this.storageMode;
2566
2930
  logger.debug(`Getting ${keys.length} game data entries from ${storageMode} for game: ${gameId}`);
2567
- const adapter = this.getStorageAdapter(storage);
2931
+ const adapter = await this.getStorageAdapter(storage);
2568
2932
  const data = await adapter.getMultipleGameData(gameId, keys);
2569
2933
  logger.info(`Retrieved ${data.length} game data entries from ${storageMode}`);
2570
2934
  return data;
@@ -2579,7 +2943,7 @@ var HyveClient = class {
2579
2943
  const gameId = this.requireGameId();
2580
2944
  const storageMode = storage || this.storageMode;
2581
2945
  logger.debug(`Deleting game data from ${storageMode}: ${gameId}/${key}`);
2582
- const adapter = this.getStorageAdapter(storage);
2946
+ const adapter = await this.getStorageAdapter(storage);
2583
2947
  const deleted = await adapter.deleteGameData(gameId, key);
2584
2948
  if (deleted) {
2585
2949
  logger.info(`Game data deleted successfully from ${storageMode}: ${gameId}/${key}`);
@@ -2598,7 +2962,7 @@ var HyveClient = class {
2598
2962
  const gameId = this.requireGameId();
2599
2963
  const storageMode = storage || this.storageMode;
2600
2964
  logger.debug(`Deleting ${keys.length} game data entries from ${storageMode} for game: ${gameId}`);
2601
- const adapter = this.getStorageAdapter(storage);
2965
+ const adapter = await this.getStorageAdapter(storage);
2602
2966
  const deletedCount = await adapter.deleteMultipleGameData(gameId, keys);
2603
2967
  logger.info(`Deleted ${deletedCount} game data entries from ${storageMode}`);
2604
2968
  return deletedCount;