@autogames/sdk 1.1.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.
Files changed (72) hide show
  1. package/README.md +732 -0
  2. package/dist/PhArrowCircleDown-Db_5u1DC.js +73 -0
  3. package/dist/PhArrowClockwise-D5uNEUen.js +73 -0
  4. package/dist/PhArrowDown-CKkl0Ow8.js +73 -0
  5. package/dist/PhArrowLeft-5Y_-c8ih.js +73 -0
  6. package/dist/PhArrowRight-BAENQRa7.js +73 -0
  7. package/dist/PhArrowSquareOut-DlfAcw2e.js +73 -0
  8. package/dist/PhArrowUp-8KZkS1Bo.js +73 -0
  9. package/dist/PhArrowUpRight-DU3GSwzb.js +73 -0
  10. package/dist/PhArrowsClockwise-CShJ-Teu.js +73 -0
  11. package/dist/PhArrowsDownUp-BL_LzwqW.js +73 -0
  12. package/dist/PhArrowsLeftRight-B8vh7AsL.js +73 -0
  13. package/dist/PhBank-CP_QveNf.js +73 -0
  14. package/dist/PhBrowser-CCSpUQte.js +73 -0
  15. package/dist/PhCaretDown-C4u7yn0j.js +73 -0
  16. package/dist/PhCaretLeft-BSbx9BBc.js +73 -0
  17. package/dist/PhCaretRight-B1CumbxI.js +73 -0
  18. package/dist/PhCaretUp-CqiATiNS.js +73 -0
  19. package/dist/PhCheck-DNkwyplN.js +73 -0
  20. package/dist/PhCircleHalf-D4fgYYPo.js +73 -0
  21. package/dist/PhClock-DkIJeKoF.js +73 -0
  22. package/dist/PhCompass-CwVX0Z1y.js +73 -0
  23. package/dist/PhCopy-C0BiDhpw.js +73 -0
  24. package/dist/PhCreditCard-Bv5P9lrI.js +73 -0
  25. package/dist/PhCurrencyDollar-BCl4tAtz.js +73 -0
  26. package/dist/PhDesktop-DREPgw1q.js +73 -0
  27. package/dist/PhDeviceMobile-CM6lQlUa.js +73 -0
  28. package/dist/PhDotsThree-dmgI5Eht.js +73 -0
  29. package/dist/PhEnvelope-D7EatbfP.js +73 -0
  30. package/dist/PhFunnelSimple-Bs-Zsz_A.js +73 -0
  31. package/dist/PhGlobe-Azwq0DDw.js +73 -0
  32. package/dist/PhIdentificationCard-BZpHUHrg.js +73 -0
  33. package/dist/PhImage-CuSFzxM3.js +73 -0
  34. package/dist/PhInfo-B4SBturW.js +73 -0
  35. package/dist/PhLightbulb-79sWB45x.js +73 -0
  36. package/dist/PhMagnifyingGlass-CojwRGSu.js +73 -0
  37. package/dist/PhPaperPlaneRight-C3krm3eP.js +73 -0
  38. package/dist/PhPlus-DDYz48cV.js +73 -0
  39. package/dist/PhPower-CZWV02MF.js +73 -0
  40. package/dist/PhPuzzlePiece-fazdHBSU.js +73 -0
  41. package/dist/PhQrCode-BbBdb_ct.js +73 -0
  42. package/dist/PhQuestion-B6cc25Dw.js +73 -0
  43. package/dist/PhQuestionMark-TmZ4Sxa8.js +73 -0
  44. package/dist/PhSealCheck-CdKeNk5K.js +73 -0
  45. package/dist/PhSignOut-BBNQiKWI.js +73 -0
  46. package/dist/PhSpinner-BwqRA0He.js +73 -0
  47. package/dist/PhTrash-CXtQYiKu.js +73 -0
  48. package/dist/PhUser-DVV5XCqw.js +73 -0
  49. package/dist/PhVault-B73IPDB0.js +73 -0
  50. package/dist/PhWarning-BEhs8fc4.js +73 -0
  51. package/dist/PhWarningCircle-BA0Qvc1c.js +73 -0
  52. package/dist/PhX-CifUIiFs.js +73 -0
  53. package/dist/autogames-sdk.esm.js +5 -0
  54. package/dist/autogames-sdk.js +5247 -0
  55. package/dist/basic-R2aK52rX.js +4875 -0
  56. package/dist/bridge-mount-Bhf05oeO.js +89817 -0
  57. package/dist/ccip-Bg_nydEz.js +145 -0
  58. package/dist/ccip-CjgrAp_t.js +147 -0
  59. package/dist/core-CnCeDQAm.js +17712 -0
  60. package/dist/features-BrlR4_0m.js +268 -0
  61. package/dist/index-C9RsDt_J.js +8044 -0
  62. package/dist/index-Chq42DrS.js +2010 -0
  63. package/dist/index-HQNbtrlg.js +341 -0
  64. package/dist/index-zA8BVXWW.js +264 -0
  65. package/dist/main-oRLGGL0R.js +2284 -0
  66. package/dist/main.d.ts +342 -0
  67. package/dist/parseSignature-DFDCc7FD.js +131 -0
  68. package/dist/property-DkPmFHg2.js +587 -0
  69. package/dist/secp256k1-UpZfvHa8.js +1347 -0
  70. package/dist/stats-confirm.html +4949 -0
  71. package/dist/w3m-modal-ClvdQLsb.js +2822 -0
  72. package/package.json +48 -0
package/README.md ADDED
@@ -0,0 +1,732 @@
1
+ # AutoGames SDK
2
+
3
+ A TypeScript SDK for web-based games with Privy authentication and AutoGames backend integration. This SDK provides a simple interface for Unity web games to interact with Privy's authentication system and the AutoGames platform without directly dealing with React.
4
+
5
+ ## Quick Start (Development)
6
+
7
+ ```bash
8
+ # Clone and install
9
+ git clone <repo-url>
10
+ cd autogames-sdk
11
+ pnpm install
12
+
13
+ # Build the SDK
14
+ pnpm build
15
+
16
+ # Run the example app
17
+ pnpm dev
18
+ ```
19
+
20
+ Open `http://localhost:3000` to test the SDK in the example app!
21
+
22
+ ## Features
23
+
24
+ - 🔐 **Privy Authentication** - Seamless social login and wallet authentication
25
+ - 🎮 **Unity-Friendly** - Simple JavaScript API accessible from Unity WebGL
26
+ - 📦 **Single Bundle** - Distributed as a single JS file with bundled Privy App ID
27
+ - 🔧 **Build-Time Configuration** - Configure Privy App ID and API base URL via environment variables
28
+ - 🔄 **Auto Token Refresh** - Automatic JWT token refresh with Web Locks API coordination across tabs
29
+ - 💼 **TypeScript Support** - Full type definitions using Privy's native types
30
+ - 🎨 **Flexible Configuration** - Customize UI, login methods, wallets, and more
31
+ - 🔒 **Type-Safe** - Uses Privy's `PrivyClientConfig` types directly for perfect compatibility
32
+ - 🌐 **Backend Integration** - Seamless integration with AutoGames backend API
33
+
34
+ This SDK is designed specifically for the AutoGames ecosystem:
35
+
36
+ - **Agent-Based Authentication** - Each game requires an `agentId` for proper backend integration
37
+ - **Consistent Experience** - Unified authentication flow across all games
38
+ - **Easy Customization** - Match the UI to your game's branding with simple config options
39
+ - **Full Privy Power** - Access to all Privy features (embedded wallets, MFA, social logins, etc.)
40
+ - **Backend Token Exchange** - Automatic token exchange from Privy tokens to AutoGames JWT tokens
41
+
42
+ ## Installation
43
+
44
+ ### Via CDN (Recommended for Unity)
45
+
46
+ Add the SDK to your `index.html`:
47
+
48
+ ```html
49
+ <script src="https://unpkg.com/autogames-sdk@latest/dist/autogames-sdk.js"></script>
50
+ <script>
51
+ // SDK is available as window.AutoGamesSDK
52
+ // Initialize with your agentId (required)
53
+ window.AutoGamesSDK.init({
54
+ agentId: 1 // Your game's agent ID from AutoGames platform
55
+ });
56
+ </script>
57
+ ```
58
+
59
+ ### Via npm
60
+
61
+ ```bash
62
+ npm install autogames-sdk
63
+ # or
64
+ pnpm add autogames-sdk
65
+ # or
66
+ yarn add autogames-sdk
67
+ ```
68
+
69
+ ```javascript
70
+ import { AutoGamesSDK } from 'autogames-sdk';
71
+ // Optional: Import Privy types for advanced configuration
72
+ import type { PrivyClientConfig } from 'autogames-sdk';
73
+
74
+ // Initialize with agentId (required)
75
+ await AutoGamesSDK.init({
76
+ agentId: 1 // Your game's agent ID from AutoGames platform
77
+ });
78
+
79
+ // Or with custom appearance
80
+ await AutoGamesSDK.init({
81
+ agentId: 1,
82
+ appearance: {
83
+ theme: 'dark',
84
+ accentColor: '#FF6B6B'
85
+ }
86
+ });
87
+ ```
88
+
89
+ ## Quick Start
90
+
91
+ ### 1. Initialize the SDK
92
+
93
+ **Required: Agent ID**
94
+
95
+ The SDK requires an `agentId` parameter, which identifies your game in the AutoGames platform. This is used for backend token exchange and user management.
96
+
97
+ ```javascript
98
+ // Initialize with agentId (required)
99
+ await window.AutoGamesSDK.init({
100
+ agentId: 1, // Your game's agent ID from AutoGames platform
101
+ });
102
+ ```
103
+
104
+ **With customization:**
105
+
106
+ ```javascript
107
+ // Customize appearance to match your game's branding
108
+ await window.AutoGamesSDK.init({
109
+ agentId: 1, // Required: Your game's agent ID
110
+ appearance: {
111
+ theme: 'dark',
112
+ accentColor: '#FF6B6B',
113
+ logo: 'https://yourgame.com/logo.png'
114
+ },
115
+ onAuthStateChange: (user) => {
116
+ console.log('Auth state changed:', user);
117
+ }
118
+ });
119
+ ```
120
+
121
+ ### 2. Trigger Login
122
+
123
+ ```javascript
124
+ try {
125
+ await window.AutoGamesSDK.login();
126
+ // Note: With OAuth providers (e.g., Google), the page may reload during authentication.
127
+ // Use the onAuthStateChange callback in init() or poll isAuthenticated() to detect completion.
128
+ } catch (error) {
129
+ console.error('Login failed:', error);
130
+ }
131
+ ```
132
+
133
+ ### 3. Get User Profile
134
+
135
+ **Get cached profile (synchronous):**
136
+
137
+ ```javascript
138
+ const profile = window.AutoGamesSDK.getProfile();
139
+ if (profile) {
140
+ console.log('User:', profile.Email, profile.ID);
141
+ console.log('Balance:', profile.BalanceUSD);
142
+ console.log('Ethereum Address:', profile.EthereumAddress);
143
+ }
144
+ ```
145
+
146
+ **Fetch fresh profile from backend (asynchronous):**
147
+
148
+ ```javascript
149
+ const profile = await window.AutoGamesSDK.fetchProfile();
150
+ if (profile) {
151
+ console.log('Fresh user data:', profile);
152
+ }
153
+ ```
154
+
155
+ ### 4. Logout
156
+
157
+ ```javascript
158
+ await window.AutoGamesSDK.logout();
159
+ // This will logout from both Privy and AutoGames backend
160
+ ```
161
+
162
+ ## API Reference
163
+
164
+ ### `init(config: SDKConfig): Promise<void>`
165
+
166
+ Initialize the SDK with required configuration. The SDK requires an `agentId` to identify your game in the AutoGames platform.
167
+
168
+ **Parameters:**
169
+ - `config`: SDK configuration object
170
+ - `agentId` (required): Your game's agent ID from the AutoGames platform. Used for backend token exchange and user management.
171
+ - `privyAppId` (optional): Custom Privy App ID. Defaults to bundled AutoGames app ID.
172
+ - `appearance` (optional): Customize the Privy UI appearance (uses Privy's native `PrivyClientConfig['appearance']`)
173
+ - `theme`: `'light'`, `'dark'`, or custom hex color (default: `'light'`)
174
+ - `accentColor`: Hex color code (default: `'#676FFF'`)
175
+ - `logo`: URL to your game's logo or React element
176
+ - `landingHeader`: Header text for the login modal
177
+ - `loginMessage`: Subtitle text for the login modal
178
+ - `showWalletLoginFirst`: Show wallet options first (default: `false`)
179
+ - `walletChainType`: `'ethereum-only'`, `'solana-only'`, or `'ethereum-and-solana'`
180
+ - `walletList`: Array of wallet providers to show
181
+ - `loginMethods` (optional): Array of enabled login methods (uses Privy's native `PrivyClientConfig['loginMethods']`)
182
+ - Available methods: `'email'`, `'sms'`, `'wallet'`, `'google'`, `'twitter'`, `'discord'`, `'github'`, `'linkedin'`, `'spotify'`, `'instagram'`, `'tiktok'`, `'apple'`, `'farcaster'`, `'telegram'`, `'passkey'`
183
+ - `loginMethodsAndOrder` (optional): Advanced login methods configuration with custom ordering (uses Privy's native `PrivyClientConfig['loginMethodsAndOrder']`)
184
+ - `config` (optional): Any additional Privy configuration options (embedded wallets, MFA, external wallets, etc.)
185
+ - `onAuthStateChange` (optional): Callback fired when authentication state changes
186
+
187
+ > **Note:** The SDK uses Privy's native types directly, so you get full type safety and access to all Privy configuration options. See [Privy's documentation](https://docs.privy.io/reference/react-auth/modules#privyclientconfig) for complete configuration details.
188
+
189
+ **Examples:**
190
+
191
+ Basic initialization:
192
+ ```javascript
193
+ // Required: agentId identifies your game in AutoGames platform
194
+ await AutoGamesSDK.init({
195
+ agentId: 1
196
+ });
197
+ ```
198
+
199
+ Custom branding:
200
+ ```javascript
201
+ await AutoGamesSDK.init({
202
+ agentId: 1, // Required
203
+ appearance: {
204
+ theme: 'dark',
205
+ accentColor: '#FF6B6B',
206
+ logo: 'https://yourgame.com/logo.png'
207
+ },
208
+ onAuthStateChange: (user) => {
209
+ if (user) {
210
+ console.log('User logged in:', user.Email);
211
+ } else {
212
+ console.log('User logged out');
213
+ }
214
+ }
215
+ });
216
+ ```
217
+
218
+ Customize login methods:
219
+ ```javascript
220
+ await AutoGamesSDK.init({
221
+ agentId: 1,
222
+ loginMethods: ['email', 'wallet', 'google'] // Only these methods will be available
223
+ });
224
+ ```
225
+
226
+ Wallet-first experience:
227
+ ```javascript
228
+ await AutoGamesSDK.init({
229
+ agentId: 1,
230
+ appearance: {
231
+ showWalletLoginFirst: true,
232
+ walletChainType: 'ethereum-only',
233
+ landingHeader: 'Connect Your Wallet',
234
+ loginMessage: 'Sign in with your crypto wallet'
235
+ }
236
+ });
237
+ ```
238
+
239
+ Advanced configuration with embedded wallets:
240
+ ```javascript
241
+ await AutoGamesSDK.init({
242
+ agentId: 1,
243
+ appearance: {
244
+ theme: 'dark',
245
+ accentColor: '#FF6B6B'
246
+ },
247
+ config: {
248
+ // Enable embedded wallet creation on login
249
+ embeddedWallets: {
250
+ createOnLogin: 'users-without-wallets',
251
+ showWalletUIs: true
252
+ },
253
+ // Enable MFA
254
+ mfa: {
255
+ noPromptOnMfaRequired: false
256
+ }
257
+ }
258
+ });
259
+ ```
260
+
261
+ ### `login(): Promise<void>`
262
+
263
+ Trigger the Privy login flow. The SDK handles token exchange with the AutoGames backend automatically.
264
+
265
+ **Returns:** `Promise<void>`
266
+
267
+ **Note:** With OAuth providers (e.g., Google), the page may reload during authentication. Use the `onAuthStateChange` callback in `init()` or poll `isAuthenticated()`/`getProfile()` to detect when login completes.
268
+
269
+ **Example:**
270
+ ```javascript
271
+ try {
272
+ await AutoGamesSDK.login();
273
+ // Login flow initiated. Use onAuthStateChange callback to detect completion.
274
+ } catch (error) {
275
+ console.error('Login failed:', error);
276
+ }
277
+ ```
278
+
279
+ ### `logout(): Promise<void>`
280
+
281
+ Log out the current user.
282
+
283
+ **Example:**
284
+ ```javascript
285
+ await AutoGamesSDK.logout();
286
+ ```
287
+
288
+ ### `getProfile(): User | null`
289
+
290
+ Get the current user's profile synchronously (cached from last fetch).
291
+
292
+ **Returns:** `User | null`
293
+
294
+ **Example:**
295
+ ```javascript
296
+ const profile = AutoGamesSDK.getProfile();
297
+ if (profile) {
298
+ console.log('User ID:', profile.ID);
299
+ console.log('Email:', profile.Email);
300
+ console.log('Balance:', profile.BalanceUSD);
301
+ }
302
+ ```
303
+
304
+ ### `fetchProfile(): Promise<User | null>`
305
+
306
+ Fetch a fresh user profile from the AutoGames backend and update the cache.
307
+
308
+ **Returns:** `Promise<User | null>`
309
+
310
+ **Example:**
311
+ ```javascript
312
+ const profile = await AutoGamesSDK.fetchProfile();
313
+ if (profile) {
314
+ console.log('Fresh user data:', profile);
315
+ }
316
+ ```
317
+
318
+ ### `isAuthenticated(): boolean`
319
+
320
+ Check if a user is currently authenticated.
321
+
322
+ **Returns:** `boolean`
323
+
324
+ ### `isReady(): boolean`
325
+
326
+ Check if the SDK is ready to use.
327
+
328
+ **Returns:** `boolean`
329
+
330
+ ### `getAuthState(): AuthState`
331
+
332
+ Get the complete authentication state.
333
+
334
+ **Returns:** `AuthState`
335
+
336
+ ```typescript
337
+ interface AuthState {
338
+ isAuthenticated: boolean;
339
+ isReady: boolean;
340
+ user: User | null;
341
+ }
342
+ ```
343
+
344
+ ### `destroy(): void`
345
+
346
+ Clean up SDK subscriptions and reset state. Useful for testing or when unmounting the SDK.
347
+
348
+ **Example:**
349
+ ```javascript
350
+ AutoGamesSDK.destroy();
351
+ ```
352
+
353
+ ## Types
354
+
355
+ ### User
356
+
357
+ The user profile returned by the SDK includes information from the AutoGames backend:
358
+
359
+ ```typescript
360
+ interface User {
361
+ // Base entity fields
362
+ ID: number;
363
+ CreatedAt: string;
364
+ UpdatedAt: string;
365
+
366
+ // User profile fields
367
+ BalanceUSD: number;
368
+ Email: string;
369
+ GeoInfo: string;
370
+ ImageThumbnailURL: string;
371
+ ImageURL: string;
372
+ IsEmailVerified: boolean;
373
+ Name: string;
374
+ PrivyUserID: string;
375
+ WalletPublicKey: string;
376
+ EthereumAddress: string;
377
+ SolanaAddress: string;
378
+ SolanaBalanceLamports: number;
379
+ }
380
+ ```
381
+
382
+ ### SDKConfig
383
+
384
+ ```typescript
385
+ import type { PrivyClientConfig } from '@privy-io/react-auth';
386
+ import type { User } from 'autogames-sdk';
387
+
388
+ interface SDKConfig {
389
+ /**
390
+ * Required: Agent ID. Game ID in the AutoGames platform.
391
+ * Used for backend token exchange and user management.
392
+ */
393
+ agentId: number;
394
+
395
+ /**
396
+ * Optional: Privy App ID. If not provided, uses the bundled default.
397
+ * Only needed if you want to use a different Privy app for isolated user base.
398
+ */
399
+ privyAppId?: string;
400
+
401
+ /**
402
+ * Optional: Customize the appearance of Privy UI elements.
403
+ * Uses Privy's native appearance configuration.
404
+ */
405
+ appearance?: PrivyClientConfig['appearance'];
406
+
407
+ /**
408
+ * Optional: Configure which login methods are available.
409
+ * Uses Privy's native login methods configuration.
410
+ */
411
+ loginMethods?: PrivyClientConfig['loginMethods'];
412
+
413
+ /**
414
+ * Optional: Advanced login methods configuration with ordering.
415
+ */
416
+ loginMethodsAndOrder?: PrivyClientConfig['loginMethodsAndOrder'];
417
+
418
+ /**
419
+ * Optional: Additional Privy client configuration options.
420
+ * Supports embedded wallets, MFA, external wallets, etc.
421
+ */
422
+ config?: Omit<PrivyClientConfig, 'appearance' | 'loginMethods' | 'loginMethodsAndOrder'>;
423
+
424
+ /**
425
+ * Optional: Callback fired when authentication state changes
426
+ */
427
+ onAuthStateChange?: (user: User | null) => void;
428
+ }
429
+ ```
430
+
431
+ > **Type Safety:** The SDK uses Privy's native `PrivyClientConfig` types directly, giving you full IntelliSense support and type checking for all Privy configuration options. See [Privy's documentation](https://docs.privy.io/reference/react-auth/modules#privyclientconfig) for complete details.
432
+
433
+ ## Unity Integration
434
+
435
+ ### C# Example
436
+
437
+ ```csharp
438
+ using UnityEngine;
439
+ using System.Runtime.InteropServices;
440
+
441
+ public class AutoGamesAuth : MonoBehaviour
442
+ {
443
+ [DllImport("__Internal")]
444
+ private static extern void InitSDK(int agentId);
445
+
446
+ [DllImport("__Internal")]
447
+ private static extern void Login();
448
+
449
+ [DllImport("__Internal")]
450
+ private static extern void Logout();
451
+
452
+ [DllImport("__Internal")]
453
+ private static extern string GetUserProfile();
454
+
455
+ [DllImport("__Internal")]
456
+ private static extern bool IsAuthenticated();
457
+
458
+ public int agentId = 1; // Set your agent ID in Unity Inspector
459
+
460
+ void Start()
461
+ {
462
+ #if UNITY_WEBGL && !UNITY_EDITOR
463
+ InitSDK(agentId); // Initialize with your agent ID
464
+ #endif
465
+ }
466
+
467
+ public void OnLoginButtonClick()
468
+ {
469
+ #if UNITY_WEBGL && !UNITY_EDITOR
470
+ Login();
471
+ #endif
472
+ }
473
+
474
+ public void OnLogoutButtonClick()
475
+ {
476
+ #if UNITY_WEBGL && !UNITY_EDITOR
477
+ Logout();
478
+ #endif
479
+ }
480
+
481
+ public void OnCheckAuthButtonClick()
482
+ {
483
+ #if UNITY_WEBGL && !UNITY_EDITOR
484
+ bool isAuth = IsAuthenticated();
485
+ Debug.Log($"Is Authenticated: {isAuth}");
486
+ #endif
487
+ }
488
+ }
489
+ ```
490
+
491
+ ### JavaScript Plugin (Assets/Plugins/WebGL/AutoGames.jslib)
492
+
493
+ ```javascript
494
+ mergeInto(LibraryManager.library, {
495
+ InitSDK: function(agentId) {
496
+ window.AutoGamesSDK.init({
497
+ agentId: agentId,
498
+ onAuthStateChange: function(user) {
499
+ if (user) {
500
+ SendMessage('AutoGamesAuth', 'OnAuthStateChanged', JSON.stringify(user));
501
+ } else {
502
+ SendMessage('AutoGamesAuth', 'OnAuthStateChanged', '');
503
+ }
504
+ }
505
+ });
506
+ },
507
+
508
+ Login: function() {
509
+ window.AutoGamesSDK.login()
510
+ .then(function() {
511
+ SendMessage('AutoGamesAuth', 'OnLoginInitiated', '');
512
+ })
513
+ .catch(function(error) {
514
+ SendMessage('AutoGamesAuth', 'OnLoginError', error.message);
515
+ });
516
+ },
517
+
518
+ Logout: function() {
519
+ window.AutoGamesSDK.logout()
520
+ .then(function() {
521
+ SendMessage('AutoGamesAuth', 'OnLogoutSuccess', '');
522
+ })
523
+ .catch(function(error) {
524
+ SendMessage('AutoGamesAuth', 'OnLogoutError', error.message);
525
+ });
526
+ },
527
+
528
+ GetUserProfile: function() {
529
+ var profile = window.AutoGamesSDK.getProfile();
530
+ if (profile) {
531
+ var json = JSON.stringify(profile);
532
+ var buffer = _malloc(lengthBytesUTF8(json) + 1);
533
+ stringToUTF8(json, buffer, lengthBytesUTF8(json) + 1);
534
+ return buffer;
535
+ }
536
+ return null;
537
+ },
538
+
539
+ IsAuthenticated: function() {
540
+ return window.AutoGamesSDK.isAuthenticated() ? 1 : 0;
541
+ }
542
+ });
543
+ ```
544
+
545
+ ## Architecture
546
+
547
+ The SDK uses a **domain-driven design** architecture with a bridge pattern to connect Privy's React SDK with vanilla JavaScript:
548
+
549
+ ### Domain Structure
550
+
551
+ ```
552
+ packages/sdk/src/
553
+ ├── domains/
554
+ │ ├── auth/ # Authentication domain
555
+ │ │ ├── api/ # Backend API calls
556
+ │ │ │ ├── exchange-privy-token.ts # Exchange Privy token for JWT
557
+ │ │ │ └── logout.ts # Backend logout
558
+ │ │ └── stores/
559
+ │ │ └── auth-store.ts # Zustand auth state store
560
+ │ └── user/ # User domain
561
+ │ ├── api/
562
+ │ │ └── get-user.ts # Fetch user from backend
563
+ │ └── types/
564
+ │ └── index.ts # User type definitions
565
+ ├── shared/
566
+ │ ├── components/
567
+ │ │ └── privy-bridge.tsx # React bridge component
568
+ │ ├── lib/
569
+ │ │ └── axios.ts # Axios instance with token refresh
570
+ │ └── types/
571
+ │ └── index.ts # Shared type definitions
572
+ ├── bridge-mount.tsx # Bridge mounting logic
573
+ ├── sdk.ts # Main SDK class
574
+ └── main.tsx # Entry point and exports
575
+ ```
576
+
577
+ ### How It Works
578
+
579
+ 1. **Bridge Pattern**: A hidden React component (`PrivyBridge`) mounts in the background to use Privy's React hooks
580
+ 2. **State Management**: Zustand store (`authStore`) manages authentication state and syncs with Privy
581
+ 3. **Token Exchange**: On login, Privy token is exchanged for AutoGames JWT token via backend API
582
+ 4. **Token Refresh**: Axios interceptor automatically refreshes JWT tokens using httpOnly cookies
583
+ 5. **Web Locks API**: Token refresh is coordinated across browser tabs using Web Locks API
584
+ 6. **Public API**: The SDK class (`AutoGamesSDK`) exposes a simple, promise-based API
585
+
586
+ ### Backend Integration
587
+
588
+ The SDK integrates with the AutoGames backend:
589
+
590
+ - **Token Exchange**: `/sso/exchange-privy-token` - Exchanges Privy token for JWT token
591
+ - **Token Refresh**: `/sso/refresh-token` - Refreshes JWT token using httpOnly cookie
592
+ - **Logout**: `/sso/logout` - Logs out from backend
593
+ - **User API**: `/users/:id` - Fetches user profile
594
+
595
+ All API calls include:
596
+ - `Authorization: Bearer <access_token>` header
597
+ - `X-Auth-Type: jwt` header
598
+ - Automatic token refresh on 401 errors
599
+
600
+ ## Repository Structure
601
+
602
+ This is a **pnpm workspace monorepo** containing:
603
+
604
+ ```
605
+ autogames-sdk/
606
+ ├── packages/
607
+ │ ├── sdk/ # Main SDK package (autogames-sdk)
608
+ │ │ ├── src/
609
+ │ │ │ ├── domains/ # Domain-driven architecture
610
+ │ │ │ ├── shared/ # Shared components and utilities
611
+ │ │ │ ├── bridge-mount.tsx
612
+ │ │ │ ├── sdk.ts # Main SDK class
613
+ │ │ │ └── main.tsx # Entry point
614
+ │ │ ├── dist/ # Built SDK bundles
615
+ │ │ └── package.json
616
+ │ └── example/ # Example React app for testing
617
+ │ ├── src/
618
+ │ │ ├── demos/ # Demo components
619
+ │ │ └── App.tsx
620
+ │ └── package.json
621
+ ├── pnpm-workspace.yaml
622
+ ├── package.json # Root workspace config
623
+ └── README.md
624
+ ```
625
+
626
+ ## Development
627
+
628
+ ### Setup
629
+
630
+ ```bash
631
+ # Install dependencies for all packages
632
+ pnpm install
633
+
634
+ # Build the SDK
635
+ pnpm build
636
+
637
+ # Or build all packages
638
+ pnpm build:all
639
+ ```
640
+
641
+ ### Running the Example App
642
+
643
+ The example app is a React application that demonstrates SDK integration:
644
+
645
+ ```bash
646
+ # Start the example app (automatically uses local SDK)
647
+ pnpm dev
648
+
649
+ # Or run from the example package directory
650
+ cd packages/example
651
+ pnpm dev
652
+ ```
653
+
654
+ The example app will be available at `http://localhost:3000` and includes:
655
+ - **Login & Methods Tab**: Test authentication flow and SDK methods
656
+ - **SDK State Tab**: Real-time view of authentication state
657
+ - **Configuration Tab**: Test different SDK configurations
658
+
659
+ ### Building the SDK
660
+
661
+ ```bash
662
+ # Build SDK package
663
+ pnpm --filter autogames-sdk build
664
+
665
+ # Or from the SDK directory
666
+ cd packages/sdk
667
+ pnpm build
668
+ ```
669
+
670
+ The Privy App ID and API base URL can be configured at build time via environment variables:
671
+
672
+ ```bash
673
+ # Using environment variables
674
+ VITE_PRIVY_APP_ID=your-app-id VITE_API_BASE_URL=https://api.autogames.com pnpm build
675
+
676
+ # Or create a .env file in packages/sdk/
677
+ cd packages/sdk
678
+ cat > .env << EOF
679
+ VITE_PRIVY_APP_ID=cmh3ikmhm00o6gz0d46f40swl
680
+ VITE_API_BASE_URL=https://api.autogames.com
681
+ EOF
682
+ pnpm build
683
+ ```
684
+
685
+ **Example `.env` file:**
686
+ ```env
687
+ # Privy App ID for AutoGames SDK
688
+ # This will be bundled into the SDK at build time
689
+ VITE_PRIVY_APP_ID=cmh3ikmhm00o6gz0d46f40swl
690
+
691
+ # AutoGames API base URL
692
+ # Used for token exchange, user fetching, and other backend operations
693
+ VITE_API_BASE_URL=https://api.autogames.com
694
+ ```
695
+
696
+ ### Development Workflow
697
+
698
+ 1. **Make changes to SDK** (`packages/sdk/src/`)
699
+ 2. **Rebuild SDK**: `pnpm --filter autogames-sdk build`
700
+ 3. **Test in example app**: The example app uses `workspace:*` so it automatically uses your local build
701
+ 4. **Run example app**: `pnpm dev` to see changes
702
+
703
+ ### Workspace Commands
704
+
705
+ ```bash
706
+ # Run command in specific package
707
+ pnpm --filter autogames-sdk <command>
708
+ pnpm --filter example <command>
709
+
710
+ # Run command in all packages
711
+ pnpm -r <command>
712
+
713
+ # Check code quality
714
+ pnpm check
715
+ ```
716
+
717
+ ## Authentication Flow
718
+
719
+ 1. **Initialization**: SDK mounts a hidden React bridge component that initializes Privy
720
+ 2. **Login**: User authenticates with Privy (social login, wallet, etc.)
721
+ 3. **Token Exchange**: SDK automatically exchanges Privy token for AutoGames JWT token
722
+ 4. **State Sync**: User profile is fetched and stored in Zustand store
723
+ 5. **Token Refresh**: Axios interceptor automatically refreshes expired tokens
724
+ 6. **Logout**: Clears both Privy and AutoGames backend sessions
725
+
726
+ ### Token Management
727
+
728
+ - **Access Token**: JWT token stored in memory (Zustand store)
729
+ - **Refresh Token**: Stored in httpOnly cookie (secure, not accessible to JavaScript)
730
+ - **Automatic Refresh**: Tokens are refreshed automatically before expiration
731
+ - **Cross-Tab Coordination**: Web Locks API ensures only one tab refreshes tokens at a time
732
+