@hyve-sdk/js 1.5.1 → 2.1.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.
@@ -0,0 +1,453 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { ReactNode } from 'react';
3
+
4
+ /**
5
+ * Telemetry configuration options
6
+ */
7
+ interface TelemetryConfig {
8
+ /**
9
+ * Environment: true for dev, false for prod.
10
+ * AUTO-DETECTED from parent page URL by default - only set for local testing.
11
+ * Use this ONLY for testing, NOT in production code.
12
+ */
13
+ isDev?: boolean;
14
+ /** Base API URL for all API calls (telemetry and external). Can be set via env. If not provided, defaults based on isDev */
15
+ apiBaseUrl?: string;
16
+ }
17
+ /**
18
+ * User inventory item
19
+ */
20
+ interface InventoryItem {
21
+ id: string;
22
+ user_id: string;
23
+ item_type: string;
24
+ item_id: string;
25
+ quantity: number;
26
+ metadata?: Record<string, any>;
27
+ created_at: string;
28
+ updated_at: string;
29
+ }
30
+ /**
31
+ * User inventory response
32
+ */
33
+ interface Inventory {
34
+ items: InventoryItem[];
35
+ total_count: number;
36
+ }
37
+ /**
38
+ * Persistent Game Data Types
39
+ */
40
+ /** Generic value type for game data storage - can be any JSON-serializable value */
41
+ type GameDataValue = string | number | boolean | null | GameDataValue[] | {
42
+ [key: string]: GameDataValue;
43
+ };
44
+ /** Single game data item with metadata */
45
+ interface GameDataItem {
46
+ key: string;
47
+ value: GameDataValue;
48
+ created_at: string;
49
+ updated_at: string;
50
+ }
51
+ /** Response from save operations */
52
+ interface SaveGameDataResponse {
53
+ success: boolean;
54
+ message: string;
55
+ }
56
+ /** Batch item for saving multiple entries */
57
+ interface GameDataBatchItem {
58
+ key: string;
59
+ value: GameDataValue;
60
+ }
61
+
62
+ /**
63
+ * Ads Service for Hyve SDK
64
+ *
65
+ * Wraps Google H5 Games Ads with auto-initialization and Playgama fallback.
66
+ * Ads are ON by default — just call showAd() and it works.
67
+ *
68
+ * Optional setup in HTML for Google H5 Games Ads:
69
+ * <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
70
+ * <script>
71
+ * window.adBreak = window.adBreak || function(o) { (window.adsbygoogle = window.adsbygoogle || []).push(o); };
72
+ * window.adConfig = window.adConfig || function(o) { (window.adsbygoogle = window.adsbygoogle || []).push(o); };
73
+ * </script>
74
+ *
75
+ * @packageDocumentation
76
+ */
77
+ type AdType = 'rewarded' | 'interstitial' | 'preroll';
78
+ interface AdResult {
79
+ success: boolean;
80
+ type: AdType;
81
+ error?: Error;
82
+ requestedAt: number;
83
+ completedAt: number;
84
+ }
85
+ interface AdConfig {
86
+ sound?: 'on' | 'off';
87
+ debug?: boolean;
88
+ onBeforeAd?: (type: AdType) => void;
89
+ onAfterAd?: (type: AdType) => void;
90
+ onRewardEarned?: () => void;
91
+ }
92
+ interface GoogleAdBreakConfig {
93
+ type: 'reward' | 'next' | 'start';
94
+ name: string;
95
+ beforeAd?: () => void;
96
+ afterAd?: () => void;
97
+ beforeReward?: (showAdFn: () => void) => void;
98
+ adViewed?: () => void;
99
+ adDismissed?: () => void;
100
+ adBreakDone?: (info?: any) => void;
101
+ }
102
+ interface GoogleAdConfigOptions {
103
+ sound?: 'on' | 'off';
104
+ preloadAdBreaks?: 'on' | 'off';
105
+ onReady?: () => void;
106
+ }
107
+ declare global {
108
+ interface Window {
109
+ adBreak?: (config: GoogleAdBreakConfig) => void;
110
+ adConfig?: (config: GoogleAdConfigOptions) => void;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Product information from the native app or server
116
+ */
117
+ interface BillingProduct {
118
+ productId: string;
119
+ title: string;
120
+ description: string;
121
+ price: number;
122
+ localizedPrice: string;
123
+ currency: string;
124
+ }
125
+ /**
126
+ * Purchase result
127
+ */
128
+ interface PurchaseResult {
129
+ success: boolean;
130
+ productId: string;
131
+ transactionId?: string;
132
+ transactionDate?: string;
133
+ error?: {
134
+ code: string;
135
+ message: string;
136
+ };
137
+ }
138
+ /**
139
+ * Billing configuration
140
+ */
141
+ interface BillingConfig {
142
+ /**
143
+ * Stripe publishable key (required for web)
144
+ */
145
+ stripePublishableKey?: string;
146
+ /**
147
+ * Game ID for native purchases
148
+ */
149
+ gameId?: number;
150
+ /**
151
+ * User ID for purchases
152
+ */
153
+ userId?: string;
154
+ /**
155
+ * Checkout URL for API calls
156
+ */
157
+ checkoutUrl?: string;
158
+ }
159
+ /**
160
+ * Platform types
161
+ */
162
+ declare enum BillingPlatform {
163
+ WEB = "web",
164
+ NATIVE = "native",
165
+ UNKNOWN = "unknown"
166
+ }
167
+
168
+ /**
169
+ * HyveClient configuration options
170
+ */
171
+ interface HyveClientConfig extends TelemetryConfig {
172
+ /** Optional ads configuration (sound, debug, lifecycle callbacks) */
173
+ ads?: AdConfig;
174
+ /** Billing configuration (disabled by default) */
175
+ billing?: BillingConfig;
176
+ /** Storage mode for persistent game data - 'cloud' (default) or 'local' */
177
+ storageMode?: 'cloud' | 'local';
178
+ }
179
+ /**
180
+ * HyveClient provides telemetry and authentication functionality for Hyve games
181
+ */
182
+ declare class HyveClient {
183
+ private telemetryConfig;
184
+ private apiBaseUrl;
185
+ private sessionId;
186
+ private userId;
187
+ private jwtToken;
188
+ private gameId;
189
+ private adsService;
190
+ private playgamaService;
191
+ private playgamaInitPromise;
192
+ private crazyGamesService;
193
+ private crazyGamesInitPromise;
194
+ private billingService;
195
+ private storageMode;
196
+ private cloudStorageAdapter;
197
+ private localStorageAdapter;
198
+ /**
199
+ * Creates a new HyveClient instance
200
+ * @param config Optional configuration including telemetry and ads
201
+ */
202
+ constructor(config?: HyveClientConfig);
203
+ /**
204
+ * Parses JWT and game ID from the current window URL and stores them on the client.
205
+ * Called automatically during construction.
206
+ */
207
+ private _parseUrlAuth;
208
+ /**
209
+ * Sends a user-level telemetry event using JWT authentication
210
+ * Requires JWT token, authenticated user, and game ID from URL parameters
211
+ * @param eventLocation Location where the event occurred
212
+ * @param eventCategory Main category of the event
213
+ * @param eventAction Primary action taken
214
+ * @param eventSubCategory Optional sub-category
215
+ * @param eventSubAction Optional sub-action
216
+ * @param eventDetails Optional event details (object or JSON string)
217
+ * @param platformId Optional platform identifier
218
+ * @returns Promise resolving to boolean indicating success
219
+ */
220
+ sendTelemetry(eventLocation: string, eventCategory: string, eventAction: string, eventSubCategory?: string | null, eventSubAction?: string | null, eventDetails?: Record<string, any> | string | null, platformId?: string | null): Promise<boolean>;
221
+ /**
222
+ * Makes an authenticated API call using the JWT token
223
+ * @param endpoint API endpoint path (will be appended to base URL)
224
+ * @param options Fetch options (method, body, etc.)
225
+ * @returns Promise resolving to the API response
226
+ */
227
+ callApi<T = any>(endpoint: string, options?: RequestInit): Promise<T>;
228
+ /**
229
+ * Gets the user's inventory
230
+ * @returns Promise resolving to the user's inventory
231
+ */
232
+ getInventory(): Promise<Inventory>;
233
+ /**
234
+ * Gets a specific inventory item by ID
235
+ * @param itemId The inventory item ID
236
+ * @returns Promise resolving to the inventory item details
237
+ */
238
+ getInventoryItem(itemId: string): Promise<InventoryItem>;
239
+ /**
240
+ * Updates the telemetry configuration
241
+ * @param config New telemetry configuration
242
+ */
243
+ updateTelemetryConfig(config: TelemetryConfig): void;
244
+ /**
245
+ * Gets the current user ID
246
+ * @returns Current user ID or null if not authenticated
247
+ */
248
+ getUserId(): string | null;
249
+ /**
250
+ * Gets the current session ID
251
+ * @returns Current session ID
252
+ */
253
+ getSessionId(): string;
254
+ /**
255
+ * Gets the current JWT token
256
+ * @returns Current JWT token or null if not available
257
+ */
258
+ getJwtToken(): string | null;
259
+ /**
260
+ * Gets the current game ID
261
+ * @returns Current game ID or null if not available
262
+ */
263
+ getGameId(): string | null;
264
+ /**
265
+ * Gets the API base URL
266
+ * @returns API base URL
267
+ */
268
+ getApiBaseUrl(): string;
269
+ /**
270
+ * Checks if user is authenticated
271
+ * @returns Boolean indicating authentication status
272
+ */
273
+ isUserAuthenticated(): boolean;
274
+ /**
275
+ * Checks if JWT token is available
276
+ * @returns Boolean indicating if JWT token is present
277
+ */
278
+ hasJwtToken(): boolean;
279
+ /**
280
+ * Logs out the current user
281
+ */
282
+ logout(): void;
283
+ /**
284
+ * Resets the client state
285
+ */
286
+ reset(): void;
287
+ /**
288
+ * Get the storage adapter based on mode
289
+ * @param mode Storage mode override (cloud or local)
290
+ */
291
+ private getStorageAdapter;
292
+ /**
293
+ * Returns the current game ID or throws if not available.
294
+ */
295
+ private requireGameId;
296
+ /**
297
+ * Save persistent game data
298
+ * @param key Data key
299
+ * @param value Data value (any JSON-serializable value)
300
+ * @param storage Storage mode override ('cloud' or 'local')
301
+ * @returns Promise resolving to save response
302
+ */
303
+ saveGameData(key: string, value: GameDataValue, storage?: 'cloud' | 'local'): Promise<SaveGameDataResponse>;
304
+ /**
305
+ * Batch save persistent game data
306
+ * @param items Array of key-value pairs to save
307
+ * @param storage Storage mode override ('cloud' or 'local')
308
+ * @returns Promise resolving to save response
309
+ */
310
+ batchSaveGameData(items: GameDataBatchItem[], storage?: 'cloud' | 'local'): Promise<SaveGameDataResponse>;
311
+ /**
312
+ * Get persistent game data
313
+ * @param key Data key
314
+ * @param storage Storage mode override ('cloud' or 'local')
315
+ * @returns Promise resolving to game data item or null if not found
316
+ */
317
+ getGameData(key: string, storage?: 'cloud' | 'local'): Promise<GameDataItem | null>;
318
+ /**
319
+ * Get multiple persistent game data entries
320
+ * @param keys Array of data keys
321
+ * @param storage Storage mode override ('cloud' or 'local')
322
+ * @returns Promise resolving to array of game data items
323
+ */
324
+ getMultipleGameData(keys: string[], storage?: 'cloud' | 'local'): Promise<GameDataItem[]>;
325
+ /**
326
+ * Delete persistent game data
327
+ * @param key Data key
328
+ * @param storage Storage mode override ('cloud' or 'local')
329
+ * @returns Promise resolving to boolean indicating if data was deleted
330
+ */
331
+ deleteGameData(key: string, storage?: 'cloud' | 'local'): Promise<boolean>;
332
+ /**
333
+ * Delete multiple persistent game data entries
334
+ * @param keys Array of data keys
335
+ * @param storage Storage mode override ('cloud' or 'local')
336
+ * @returns Promise resolving to number of entries deleted
337
+ */
338
+ deleteMultipleGameData(keys: string[], storage?: 'cloud' | 'local'): Promise<number>;
339
+ /**
340
+ * Configure storage mode
341
+ * @param mode Storage mode ('cloud' or 'local')
342
+ */
343
+ configureStorage(mode: 'cloud' | 'local'): void;
344
+ /**
345
+ * Get current storage mode
346
+ * @returns Current storage mode
347
+ */
348
+ getStorageMode(): 'cloud' | 'local';
349
+ /**
350
+ * Configure ads service
351
+ * @param config Ads configuration
352
+ */
353
+ configureAds(config: AdConfig): void;
354
+ /**
355
+ * Show an ad
356
+ * @param type Type of ad to show ('rewarded', 'interstitial', or 'preroll')
357
+ * @returns Promise resolving to ad result
358
+ */
359
+ showAd(type: AdType): Promise<AdResult>;
360
+ /**
361
+ * Notifies CrazyGames that gameplay has started.
362
+ * No-op on other platforms.
363
+ */
364
+ gameplayStart(): Promise<void>;
365
+ /**
366
+ * Notifies CrazyGames that gameplay has stopped.
367
+ * No-op on other platforms.
368
+ */
369
+ gameplayStop(): Promise<void>;
370
+ /**
371
+ * Triggers a celebration effect on the CrazyGames website for significant achievements.
372
+ * No-op on other platforms.
373
+ */
374
+ happytime(): Promise<void>;
375
+ /**
376
+ * Check if ads are ready to show
377
+ * @returns Boolean indicating if ads have initialized successfully
378
+ */
379
+ areAdsReady(): boolean;
380
+ /**
381
+ * Get the billing platform
382
+ * @returns Current billing platform
383
+ */
384
+ getBillingPlatform(): BillingPlatform;
385
+ /**
386
+ * Check if billing is available
387
+ * @returns Boolean indicating if billing is available
388
+ */
389
+ isBillingAvailable(): boolean;
390
+ /**
391
+ * Get available billing products
392
+ * @returns Promise resolving to array of products
393
+ */
394
+ getBillingProducts(): Promise<BillingProduct[]>;
395
+ /**
396
+ * Purchase a product
397
+ * @param productId Product ID to purchase
398
+ * @param options Optional purchase options (e.g., elementId for web)
399
+ * @returns Promise resolving to purchase result
400
+ */
401
+ purchaseProduct(productId: string, options?: {
402
+ elementId?: string;
403
+ }): Promise<PurchaseResult>;
404
+ /**
405
+ * Set callback for successful purchases
406
+ * @param callback Function to call on purchase completion
407
+ */
408
+ onPurchaseComplete(callback: (result: PurchaseResult) => void): void;
409
+ /**
410
+ * Set callback for failed purchases
411
+ * @param callback Function to call on purchase error
412
+ */
413
+ onPurchaseError(callback: (result: PurchaseResult) => void): void;
414
+ /**
415
+ * Unmount Stripe checkout element
416
+ */
417
+ unmountBillingCheckout(): void;
418
+ }
419
+
420
+ interface HyveSdkProviderProps {
421
+ /** Pre-created HyveClient instance, or omit to have the provider create one from config */
422
+ client?: HyveClient;
423
+ /** Config to create a HyveClient instance — ignored when client prop is provided */
424
+ config?: HyveClientConfig;
425
+ children: ReactNode;
426
+ }
427
+ /**
428
+ * Provides a HyveClient instance to all descendant components.
429
+ *
430
+ * @example
431
+ * // Option A: pass a pre-created client
432
+ * const client = new HyveClient({ isDev: true });
433
+ * <HyveSdkProvider client={client}><App /></HyveSdkProvider>
434
+ *
435
+ * @example
436
+ * // Option B: let the provider create the client from config
437
+ * <HyveSdkProvider config={{ isDev: true }}><App /></HyveSdkProvider>
438
+ */
439
+ declare function HyveSdkProvider({ client, config, children, }: HyveSdkProviderProps): react_jsx_runtime.JSX.Element;
440
+ /**
441
+ * Returns the HyveClient instance from the nearest HyveSdkProvider.
442
+ * Throws if used outside of a provider.
443
+ *
444
+ * @example
445
+ * function MyComponent() {
446
+ * const sdk = useHyveSdk();
447
+ * const handleClick = () => sdk.sendTelemetry("game", "ui", "button_click");
448
+ * return <button onClick={handleClick}>Play</button>;
449
+ * }
450
+ */
451
+ declare function useHyveSdk(): HyveClient;
452
+
453
+ export { HyveSdkProvider, useHyveSdk };