@kokimoki/app 1.17.0 → 2.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.
@@ -51,23 +51,6 @@ declare class KokimokiStore<T extends object> {
51
51
  onLeave(client: KokimokiClient): Promise<void>;
52
52
  }
53
53
 
54
- declare class KokimokiAwareness<DataT> extends KokimokiStore<{
55
- [connectionId: string]: {
56
- clientId: string;
57
- data: DataT;
58
- };
59
- }> {
60
- private _data;
61
- private _kmClients;
62
- constructor(roomName: string, _data: DataT, mode?: RoomSubscriptionMode);
63
- onJoin(client: KokimokiClient<any>): Promise<void>;
64
- onLeave(client: KokimokiClient<any>): Promise<void>;
65
- getClients(): {
66
- [clientId: string]: Snapshot<DataT>;
67
- };
68
- setData(data: DataT): Promise<void>;
69
- }
70
-
71
54
  declare class KokimokiLocalStore<T extends object> extends KokimokiStore<T> {
72
55
  private readonly localRoomName;
73
56
  private _stateKey?;
@@ -79,11 +62,644 @@ declare class KokimokiLocalStore<T extends object> extends KokimokiStore<T> {
79
62
  };
80
63
  }
81
64
 
65
+ /**
66
+ * Kokimoki AI Integration Service
67
+ *
68
+ * Provides built-in AI capabilities for game applications without requiring API keys or setup.
69
+ * Includes text generation, structured JSON output, and image modification.
70
+ *
71
+ * **Key Features:**
72
+ * - Multiple AI models (GPT-4, GPT-5, Gemini variants)
73
+ * - Text generation with configurable creativity (temperature)
74
+ * - Structured JSON output for game data
75
+ * - AI-powered image modifications
76
+ * - No API keys or configuration required
77
+ *
78
+ * **Common Use Cases:**
79
+ * - Generate dynamic game content (quests, dialogues, stories)
80
+ * - Create AI opponents or NPCs with personalities
81
+ * - Generate quiz questions or trivia
82
+ * - Create game assets (character stats, item descriptions)
83
+ * - Transform user-uploaded images
84
+ * - Generate procedural content
85
+ *
86
+ * Access via `kmClient.ai`
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * // Generate story text
91
+ * const story = await kmClient.ai.chat({
92
+ * systemPrompt: 'You are a fantasy story writer',
93
+ * userPrompt: 'Write a short quest description',
94
+ * temperature: 0.8
95
+ * });
96
+ *
97
+ * // Generate structured game data
98
+ * interface Enemy {
99
+ * name: string;
100
+ * health: number;
101
+ * attack: number;
102
+ * }
103
+ * const enemy = await kmClient.ai.generateJson<Enemy>({
104
+ * userPrompt: 'Create a level 5 goblin warrior'
105
+ * });
106
+ *
107
+ * // Transform image
108
+ * const modified = await kmClient.ai.modifyImage(
109
+ * imageUrl,
110
+ * 'Make it look like pixel art'
111
+ * );
112
+ * ```
113
+ */
114
+ declare class KokimokiAi {
115
+ private readonly client;
116
+ constructor(client: KokimokiClient);
117
+ /**
118
+ * Generate a chat response from the AI model.
119
+ *
120
+ * Sends a chat request to the AI service and returns the generated response.
121
+ * Supports multiple AI models including GPT and Gemini variants with configurable
122
+ * parameters for fine-tuning the response behavior.
123
+ *
124
+ * @param req The chat request parameters.
125
+ * @param req.model Optional. The AI model to use. Defaults to server-side default if not specified.
126
+ * Available models:
127
+ * - `gpt-4o`: OpenAI GPT-4 Optimized
128
+ * - `gpt-4o-mini`: Smaller, faster GPT-4 variant
129
+ * - `gpt-5`: OpenAI GPT-5 (latest)
130
+ * - `gpt-5-mini`: Smaller GPT-5 variant
131
+ * - `gpt-5-nano`: Smallest GPT-5 variant for lightweight tasks
132
+ * - `gemini-2.5-flash-lite`: Google Gemini lite variant
133
+ * - `gemini-2.5-flash`: Google Gemini fast variant
134
+ * @param req.systemPrompt Optional. The system message that sets the behavior and context for the AI.
135
+ * This helps define the AI's role, personality, and constraints.
136
+ * @param req.userPrompt The user's message or question to send to the AI.
137
+ * @param req.temperature Optional. Controls randomness in the response (0.0 to 1.0).
138
+ * Lower values make output more focused and deterministic,
139
+ * higher values make it more creative and varied.
140
+ * @param req.maxTokens Optional. The maximum number of tokens to generate in the response.
141
+ * Controls the length of the AI's output.
142
+ *
143
+ * @returns A promise that resolves to an object containing the AI-generated response.
144
+ * @returns {string} content The text content of the AI's response.
145
+ *
146
+ * @throws An error object if the API request fails.
147
+ *
148
+ * @example
149
+ * ```typescript
150
+ * const response = await client.ai.chat({
151
+ * model: "gpt-4o",
152
+ * systemPrompt: "You are a helpful coding assistant.",
153
+ * userPrompt: "Explain what TypeScript is in one sentence.",
154
+ * temperature: 0.7,
155
+ * maxTokens: 100
156
+ * });
157
+ * console.log(response.content);
158
+ * ```
159
+ */
160
+ chat(req: {
161
+ model?: "gpt-4o" | "gpt-4o-mini" | "gpt-5" | "gpt-5-mini" | "gpt-5-nano" | "gemini-2.5-flash-lite" | "gemini-2.5-flash";
162
+ systemPrompt?: string;
163
+ userPrompt: string;
164
+ temperature?: number;
165
+ maxTokens?: number;
166
+ responseMimeType?: string;
167
+ }): Promise<{
168
+ content: string;
169
+ }>;
170
+ /**
171
+ * Generate structured JSON output from the AI model.
172
+ *
173
+ * Sends a chat request to the AI service with the expectation of receiving
174
+ * a JSON-formatted response. This is useful for scenarios where the output
175
+ * needs to be parsed or processed programmatically.
176
+ *
177
+ * @param req The chat request parameters.
178
+ * @param req.model Optional. The AI model to use. Defaults to server-side default if not specified.
179
+ * Available models:
180
+ * - `gpt-4o`: OpenAI GPT-4 Optimized
181
+ * - `gpt-4o-mini`: Smaller, faster GPT-4 variant
182
+ * - `gpt-5`: OpenAI GPT-5 (latest)
183
+ * - `gpt-5-mini`: Smaller GPT-5 variant
184
+ * - `gpt-5-nano`: Smallest GPT-5 variant for lightweight tasks
185
+ * - `gemini-2.5-flash-lite`: Google Gemini lite variant
186
+ * - `gemini-2.5-flash`: Google Gemini fast variant
187
+ * @param req.systemPrompt Optional. The system message that sets the behavior and context for the AI.
188
+ * This helps define the AI's role, personality, and constraints.
189
+ * @param req.userPrompt The user's message or question to send to the AI.
190
+ * @param req.temperature Optional. Controls randomness in the response (0.0 to 1.0).
191
+ * Lower values make output more focused and deterministic,
192
+ * higher values make it more creative and varied.
193
+ * @param req.maxTokens Optional. The maximum number of tokens to generate in the response.
194
+ * Controls the length of the AI's output.
195
+ *
196
+ * @returns A promise that resolves to the parsed JSON object generated by the AI.
197
+ *
198
+ * @throws An error object if the API request fails or if the response is not valid JSON.
199
+ */
200
+ generateJson<T extends object>(req: {
201
+ model?: "gpt-4o" | "gpt-4o-mini" | "gpt-5" | "gpt-5-mini" | "gpt-5-nano" | "gemini-2.5-flash-lite" | "gemini-2.5-flash";
202
+ systemPrompt?: string;
203
+ userPrompt: string;
204
+ temperature?: number;
205
+ maxTokens?: number;
206
+ }): Promise<T>;
207
+ /**
208
+ * Modify an image using the AI service.
209
+ * @param baseImageUrl The URL of the base image to modify.
210
+ * @param prompt The modification prompt to apply to the image.
211
+ * @param tags Optional. Tags to associate with the image.
212
+ * @returns A promise that resolves to the modified image upload information.
213
+ */
214
+ modifyImage(baseImageUrl: string, prompt: string, tags?: string[]): Promise<Upload>;
215
+ }
216
+
217
+ /**
218
+ * Kokimoki Leaderboard Service
219
+ *
220
+ * Provides efficient player ranking and score tracking with database indexes and optimized queries.
221
+ * Ideal for games with large numbers of players and competitive scoring.
222
+ *
223
+ * **Key Features:**
224
+ * - Efficient ranking with database indexes
225
+ * - Support for ascending (lowest-is-best) and descending (highest-is-best) sorting
226
+ * - Pagination for large leaderboards
227
+ * - Public and private metadata for entries
228
+ * - Insert (preserve all attempts) or upsert (keep latest only) modes
229
+ *
230
+ * **When to use Leaderboard API vs Global Store:**
231
+ *
232
+ * Use the **Leaderboard API** when:
233
+ * - You have a large number of entries (hundreds to thousands of players)
234
+ * - You need efficient ranking and sorting with database indexes
235
+ * - You want pagination and optimized queries for top scores
236
+ * - Memory and network efficiency are important
237
+ *
238
+ * Use a **Global Store** when:
239
+ * - You have a small number of players (typically under 100)
240
+ * - You need real-time updates and live leaderboard changes
241
+ * - You want to combine player scores with other game state
242
+ * - The leaderboard is temporary (session-based or reset frequently)
243
+ *
244
+ * Access via `kmClient.leaderboard`
245
+ *
246
+ * @example
247
+ * ```typescript
248
+ * // Submit a high score
249
+ * const { rank } = await kmClient.leaderboard.upsertEntry(
250
+ * 'high-scores',
251
+ * 'desc',
252
+ * 1500,
253
+ * { playerName: 'Alice' },
254
+ * {}
255
+ * );
256
+ *
257
+ * // Get top 10
258
+ * const { items } = await kmClient.leaderboard.listEntries('high-scores', 'desc', 0, 10);
259
+ *
260
+ * // Get player's best
261
+ * const best = await kmClient.leaderboard.getBestEntry('high-scores', 'desc');
262
+ * ```
263
+ */
264
+ declare class KokimokiLeaderboard {
265
+ private readonly client;
266
+ constructor(client: KokimokiClient);
267
+ /**
268
+ * Add a new entry to a leaderboard.
269
+ *
270
+ * Creates a new entry each time it's called, preserving all attempts. Use this when you want
271
+ * to track every score submission (e.g., all game attempts).
272
+ *
273
+ * @param leaderboardName The name of the leaderboard to add the entry to
274
+ * @param sortDir Sort direction: "asc" for lowest-is-best (e.g., completion time),
275
+ * "desc" for highest-is-best (e.g., points)
276
+ * @param score The numeric score value
277
+ * @param metadata Public metadata visible to all players (e.g., player name, level)
278
+ * @param privateMetadata Private metadata only accessible via API calls (e.g., session ID)
279
+ * @returns A promise resolving to an object with the entry's rank
280
+ *
281
+ * @example
282
+ * ```typescript
283
+ * const { rank } = await kmClient.leaderboard.insertEntry(
284
+ * 'high-scores',
285
+ * 'desc',
286
+ * 1500,
287
+ * { playerName: 'Alice', level: 10 },
288
+ * { sessionId: 'abc123' }
289
+ * );
290
+ * console.log(`New rank: ${rank}`);
291
+ * ```
292
+ */
293
+ insertEntry<MetadataT, PrivateMetadataT>(leaderboardName: string, sortDir: "asc" | "desc", score: number, metadata: MetadataT, privateMetadata: PrivateMetadataT): Promise<{
294
+ rank: number;
295
+ }>;
296
+ /**
297
+ * Add or update the latest entry for the current client in a leaderboard.
298
+ *
299
+ * Replaces the previous entry if one exists for this client. Use this when you only want
300
+ * to keep the latest or best score per player (e.g., daily high score).
301
+ *
302
+ * @param leaderboardName The name of the leaderboard to upsert the entry in
303
+ * @param sortDir Sort direction: "asc" for lowest-is-best (e.g., completion time),
304
+ * "desc" for highest-is-best (e.g., points)
305
+ * @param score The numeric score value
306
+ * @param metadata Public metadata visible to all players (e.g., player name, completion time)
307
+ * @param privateMetadata Private metadata only accessible via API calls (e.g., device ID)
308
+ * @returns A promise resolving to an object with the entry's updated rank
309
+ *
310
+ * @example
311
+ * ```typescript
312
+ * const { rank } = await kmClient.leaderboard.upsertEntry(
313
+ * 'daily-scores',
314
+ * 'desc',
315
+ * 2000,
316
+ * { playerName: 'Bob', completionTime: 120 },
317
+ * { deviceId: 'xyz789' }
318
+ * );
319
+ * console.log(`Updated rank: ${rank}`);
320
+ * ```
321
+ */
322
+ upsertEntry<MetadataT, PrivateMetadataT>(leaderboardName: string, sortDir: "asc" | "desc", score: number, metadata: MetadataT, privateMetadata: PrivateMetadataT): Promise<{
323
+ rank: number;
324
+ }>;
325
+ /**
326
+ * List entries in a leaderboard with pagination.
327
+ *
328
+ * Retrieves a sorted list of leaderboard entries. Use skip and limit parameters for
329
+ * pagination (e.g., showing top 10, or implementing "load more" functionality).
330
+ *
331
+ * @param leaderboardName The name of the leaderboard to query
332
+ * @param sortDir Sort direction: "asc" for lowest-is-best (e.g., completion time),
333
+ * "desc" for highest-is-best (e.g., points)
334
+ * @param skip Number of entries to skip for pagination (default: 0)
335
+ * @param limit Maximum number of entries to return (default: 100)
336
+ * @returns A promise resolving to a paginated list of entries with rank, score, and metadata
337
+ *
338
+ * @example
339
+ * ```typescript
340
+ * // Get top 10 scores
341
+ * const { items, total } = await kmClient.leaderboard.listEntries(
342
+ * 'weekly-scores',
343
+ * 'desc',
344
+ * 0,
345
+ * 10
346
+ * );
347
+ *
348
+ * items.forEach(entry => {
349
+ * console.log(`Rank ${entry.rank}: ${entry.metadata.playerName} - ${entry.score}`);
350
+ * });
351
+ * ```
352
+ */
353
+ listEntries<MetadataT>(leaderboardName: string, sortDir: "asc" | "desc", skip?: number, limit?: number): Promise<Paginated<{
354
+ rank: number;
355
+ score: number;
356
+ metadata: MetadataT;
357
+ }>>;
358
+ /**
359
+ * Get the best entry for a specific client in a leaderboard.
360
+ *
361
+ * Retrieves the highest-ranked entry for a client based on the sort direction.
362
+ * Defaults to the current client if no clientId is provided.
363
+ *
364
+ * @param leaderboardName The name of the leaderboard to query
365
+ * @param sortDir Sort direction: "asc" for lowest-is-best (e.g., completion time),
366
+ * "desc" for highest-is-best (e.g., points)
367
+ * @param clientId The client ID to get the best entry for (optional, defaults to current client)
368
+ * @returns A promise resolving to the best entry with rank, score, and metadata
369
+ *
370
+ * @example
371
+ * ```typescript
372
+ * // Get current client's best entry
373
+ * const myBest = await kmClient.leaderboard.getBestEntry('all-time-high', 'desc');
374
+ * console.log(`My best: Rank ${myBest.rank}, Score ${myBest.score}`);
375
+ *
376
+ * // Get another player's best entry
377
+ * const otherBest = await kmClient.leaderboard.getBestEntry(
378
+ * 'all-time-high',
379
+ * 'desc',
380
+ * 'other-client-id'
381
+ * );
382
+ * ```
383
+ */
384
+ getBestEntry<MetadataT>(leaderboardName: string, sortDir: "asc" | "desc", clientId?: string): Promise<{
385
+ rank: number;
386
+ score: number;
387
+ metadata: MetadataT;
388
+ }>;
389
+ }
390
+
391
+ /**
392
+ * Kokimoki Storage Service
393
+ *
394
+ * Provides file upload and management capabilities for game applications. Ideal for media files
395
+ * (images, videos, audio) and other data not suitable for real-time stores (JSON, text files).
396
+ *
397
+ * **Key Features:**
398
+ * - Upload files to cloud storage with CDN delivery
399
+ * - Tag-based organization and filtering
400
+ * - Query uploads by client, MIME type, or tags
401
+ * - Pagination support for large collections
402
+ * - Public CDN URLs for direct access
403
+ *
404
+ * **Common Use Cases:**
405
+ * - Player avatars and profile images
406
+ * - Game screenshots and replays
407
+ * - User-generated content
408
+ * - Asset uploads (levels, maps, custom skins)
409
+ * - JSON configuration files
410
+ *
411
+ * Access via `kmClient.storage`
412
+ *
413
+ * @example
414
+ * ```typescript
415
+ * // Upload an image
416
+ * const upload = await kmClient.storage.upload('avatar.jpg', imageBlob, ['profile']);
417
+ *
418
+ * // Query user's uploads
419
+ * const myUploads = await kmClient.storage.listUploads({
420
+ * clientId: kmClient.id
421
+ * });
422
+ *
423
+ * // Use in store
424
+ * await kmClient.transact([store], (state) => {
425
+ * state.playerAvatar = upload.url;
426
+ * });
427
+ * ```
428
+ */
429
+ declare class KokimokiStorage {
430
+ private readonly client;
431
+ constructor(client: KokimokiClient);
432
+ private createUpload;
433
+ private uploadChunks;
434
+ private completeUpload;
435
+ /**
436
+ * Upload a file to cloud storage.
437
+ *
438
+ * Uploads a file (Blob) to Kokimoki storage and returns an Upload object with a public CDN URL.
439
+ * Files are automatically chunked for efficient upload. The returned URL can be used directly
440
+ * in your application (e.g., in img tags or store state).
441
+ *
442
+ * @param name The filename for the upload
443
+ * @param blob The Blob object containing the file data
444
+ * @param tags Optional array of tags for organizing and filtering uploads (default: [])
445
+ * @returns A promise resolving to the Upload object with CDN URL and metadata
446
+ *
447
+ * @example
448
+ * ```typescript
449
+ * // Upload image with tags
450
+ * const upload = await kmClient.storage.upload(
451
+ * 'avatar.jpg',
452
+ * imageBlob,
453
+ * ['profile', 'avatar']
454
+ * );
455
+ *
456
+ * // Use the CDN URL
457
+ * console.log(upload.url); // https://cdn.kokimoki.com/...
458
+ *
459
+ * // Store in game state
460
+ * await kmClient.transact([store], (state) => {
461
+ * state.players[kmClient.id].avatar = upload.url;
462
+ * });
463
+ * ```
464
+ */
465
+ upload(name: string, blob: Blob, tags?: string[]): Promise<Upload>;
466
+ /**
467
+ * Update metadata for an existing upload.
468
+ *
469
+ * Allows you to replace the tags associated with an upload. Useful for reorganizing
470
+ * or recategorizing uploaded files.
471
+ *
472
+ * @param id The upload ID to update
473
+ * @param update Object containing the new tags array
474
+ * @returns A promise resolving to the updated Upload object
475
+ *
476
+ * @example
477
+ * ```typescript
478
+ * // Update tags
479
+ * const updated = await kmClient.storage.updateUpload(upload.id, {
480
+ * tags: ['archived', 'old-profile']
481
+ * });
482
+ * ```
483
+ */
484
+ updateUpload(id: string, update: {
485
+ tags?: string[];
486
+ }): Promise<Upload>;
487
+ /**
488
+ * Query uploaded files with filtering and pagination.
489
+ *
490
+ * Retrieves a list of uploads matching the specified criteria. Supports filtering by
491
+ * client (uploader), MIME types, and tags. Use pagination for large collections.
492
+ *
493
+ * @param filter Optional filter criteria
494
+ * @param filter.clientId Filter by uploader's client ID
495
+ * @param filter.mimeTypes Filter by MIME types (e.g., ['image/jpeg', 'image/png'])
496
+ * @param filter.tags Filter by tags (all specified tags must match)
497
+ * @param skip Number of results to skip for pagination (default: 0)
498
+ * @param limit Maximum number of results to return (default: 100)
499
+ * @returns A promise resolving to paginated Upload results with total count
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * // Get current user's images
504
+ * const myImages = await kmClient.storage.listUploads({
505
+ * clientId: kmClient.id,
506
+ * mimeTypes: ['image/jpeg', 'image/png']
507
+ * });
508
+ *
509
+ * // Get all profile avatars
510
+ * const avatars = await kmClient.storage.listUploads({
511
+ * tags: ['profile', 'avatar']
512
+ * });
513
+ *
514
+ * // Pagination
515
+ * const page2 = await kmClient.storage.listUploads({}, 10, 10);
516
+ * ```
517
+ */
518
+ listUploads(filter?: {
519
+ clientId?: string;
520
+ mimeTypes?: string[];
521
+ tags?: string[];
522
+ }, skip?: number, limit?: number): Promise<Paginated<Upload>>;
523
+ /**
524
+ * Permanently delete an uploaded file.
525
+ *
526
+ * Removes the file from cloud storage and the CDN. The URL will no longer be accessible.
527
+ * This operation cannot be undone.
528
+ *
529
+ * @param id The upload ID to delete
530
+ * @returns A promise resolving to deletion confirmation
531
+ *
532
+ * @example
533
+ * ```typescript
534
+ * // Delete an upload
535
+ * const result = await kmClient.storage.deleteUpload(upload.id);
536
+ * console.log(`Deleted: ${result.deletedCount} file(s)`);
537
+ * ```
538
+ */
539
+ deleteUpload(id: string): Promise<{
540
+ acknowledged: boolean;
541
+ deletedCount: number;
542
+ }>;
543
+ }
544
+
82
545
  type Mutable<T> = {
83
546
  -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K];
84
547
  };
85
548
  type StoreValue<S> = S extends KokimokiStore<infer U> ? Mutable<U> : never;
86
549
  declare const KokimokiClient_base: new () => TypedEmitter<KokimokiClientEvents>;
550
+ /**
551
+ * Kokimoki Client - Real-time Collaborative Game Development SDK
552
+ *
553
+ * The main entry point for building multiplayer games and collaborative applications.
554
+ * Provides real-time state synchronization, AI integration, cloud storage, leaderboards,
555
+ * and more - all without complex backend setup.
556
+ *
557
+ * **Core Capabilities:**
558
+ * - **Real-time Stores**: Synchronized state with automatic conflict resolution (powered by Valtio + Y.js)
559
+ * - **Atomic Transactions**: Update multiple stores consistently with automatic batching
560
+ * - **AI Integration**: Built-in text generation, structured JSON output, and image modification
561
+ * - **Cloud Storage**: File uploads with CDN delivery and tag-based organization
562
+ * - **Leaderboards**: Efficient player ranking with database indexes and pagination
563
+ * - **Presence Tracking**: Real-time connection status for all players
564
+ * - **Time Sync**: Server-synchronized timestamps across all clients
565
+ * - **Webhooks**: Send data to external services for backend processing
566
+ *
567
+ * **Quick Start:**
568
+ * ```typescript
569
+ * import { KokimokiClient } from '@kokimoki/app';
570
+ *
571
+ * // Initialize the client
572
+ * const kmClient = new KokimokiClient(
573
+ * 'your-host.kokimoki.com',
574
+ * 'your-app-id',
575
+ * 'optional-access-code'
576
+ * );
577
+ *
578
+ * // Connect to the server
579
+ * await kmClient.connect();
580
+ *
581
+ * // Create a synchronized store
582
+ * interface GameState {
583
+ * players: Record<string, { name: string; score: number }>;
584
+ * round: number;
585
+ * }
586
+ *
587
+ * const gameStore = kmClient.store<GameState>('game', {
588
+ * players: {},
589
+ * round: 1
590
+ * });
591
+ *
592
+ * // Update state atomically
593
+ * await kmClient.transact([gameStore], ([game]) => {
594
+ * game.players[kmClient.id] = { name: 'Player 1', score: 0 };
595
+ * game.round = 2;
596
+ * });
597
+ *
598
+ * // Use in React components with Valtio
599
+ * import { useSnapshot } from 'valtio';
600
+ *
601
+ * function GameComponent() {
602
+ * const game = useSnapshot(gameStore.proxy);
603
+ * return <div>Round: {game.round}</div>;
604
+ * }
605
+ * ```
606
+ *
607
+ * **Key Features:**
608
+ *
609
+ * **1. Real-time State Management**
610
+ * - Create global stores shared across all players: `kmClient.store()`
611
+ * - Create local stores for client-side data: `kmClient.localStore()`
612
+ * - Automatic synchronization and conflict resolution
613
+ * - Use `useSnapshot()` from Valtio for reactive React components
614
+ *
615
+ * **2. Atomic Transactions**
616
+ * ```typescript
617
+ * // Update multiple stores atomically
618
+ * await kmClient.transact([playerStore, gameStore], ([player, game]) => {
619
+ * player.score += 10;
620
+ * game.lastUpdate = kmClient.serverTimestamp();
621
+ * });
622
+ * ```
623
+ *
624
+ * **3. AI Integration (No API keys required)**
625
+ * ```typescript
626
+ * // Generate text
627
+ * const story = await kmClient.ai.chat({
628
+ * model: 'gpt-4o',
629
+ * userPrompt: 'Write a quest description',
630
+ * temperature: 0.8
631
+ * });
632
+ *
633
+ * // Generate structured data
634
+ * interface Quest { title: string; reward: number; }
635
+ * const quest = await kmClient.ai.generateJson<Quest>({
636
+ * userPrompt: 'Create a level 5 quest'
637
+ * });
638
+ *
639
+ * // Modify images
640
+ * const modified = await kmClient.ai.modifyImage(url, 'Make it pixel art');
641
+ * ```
642
+ *
643
+ * **4. Cloud Storage**
644
+ * ```typescript
645
+ * // Upload files with tags
646
+ * const upload = await kmClient.storage.upload('avatar.jpg', blob, ['profile']);
647
+ *
648
+ * // Query uploads
649
+ * const images = await kmClient.storage.listUploads({
650
+ * clientId: kmClient.id,
651
+ * mimeTypes: ['image/jpeg', 'image/png']
652
+ * });
653
+ * ```
654
+ *
655
+ * **5. Leaderboards**
656
+ * ```typescript
657
+ * // Submit score (replaces previous entry)
658
+ * await kmClient.leaderboard.upsertEntry(
659
+ * 'high-scores',
660
+ * 'desc',
661
+ * 1500,
662
+ * { playerName: 'Alice' },
663
+ * {}
664
+ * );
665
+ *
666
+ * // Get top 10
667
+ * const top10 = await kmClient.leaderboard.listEntries('high-scores', 'desc', 0, 10);
668
+ * ```
669
+ *
670
+ * **6. Presence Tracking**
671
+ * ```typescript
672
+ * // Track online players
673
+ * const onlineClientIds = useSnapshot(gameStore.connections).clientIds;
674
+ * const isPlayerOnline = onlineClientIds.has(playerId);
675
+ * ```
676
+ *
677
+ * **Best Practices:**
678
+ * - Always use `kmClient.serverTimestamp()` for time-sensitive operations
679
+ * - Prefer Records over Arrays: `Record<string, T>` with timestamp keys
680
+ * - Use `kmClient.transact()` for all state updates to ensure atomicity
681
+ * - Tag uploads for easy filtering and organization
682
+ * - Use local stores for client-side settings and preferences
683
+ * - Leverage TypeScript generics for type-safe stores
684
+ *
685
+ * **Events:**
686
+ * - `connected`: Fired when client connects/reconnects to server
687
+ * - `disconnected`: Fired when connection is lost
688
+ *
689
+ * @template ClientContextT The type of client context data (custom user data from your backend)
690
+ *
691
+ * @example
692
+ * ```typescript
693
+ * // Listen for connection events
694
+ * kmClient.on('connected', () => {
695
+ * console.log('Connected to Kokimoki!');
696
+ * });
697
+ *
698
+ * kmClient.on('disconnected', () => {
699
+ * console.log('Connection lost, will auto-reconnect...');
700
+ * });
701
+ * ```
702
+ */
87
703
  declare class KokimokiClient<ClientContextT = any> extends KokimokiClient_base {
88
704
  readonly host: string;
89
705
  readonly appId: string;
@@ -110,6 +726,9 @@ declare class KokimokiClient<ClientContextT = any> extends KokimokiClient_base {
110
726
  private _pingInterval;
111
727
  private _clientTokenKey;
112
728
  private _editorContext;
729
+ private _ai?;
730
+ private _storage?;
731
+ private _leaderboard?;
113
732
  constructor(host: string, appId: string, code?: string);
114
733
  get id(): string;
115
734
  get connectionId(): string;
@@ -117,9 +736,24 @@ declare class KokimokiClient<ClientContextT = any> extends KokimokiClient_base {
117
736
  get apiUrl(): string;
118
737
  get apiHeaders(): Headers;
119
738
  get clientContext(): ClientContextT & ({} | null);
739
+ /**
740
+ * Indicates whether the client is currently connected to the server.
741
+ */
120
742
  get connected(): boolean;
121
743
  get ws(): WebSocket;
744
+ /**
745
+ * Indicates whether the client is running in editor/development mode.
746
+ */
122
747
  get isEditor(): boolean;
748
+ /**
749
+ * Establishes a connection to the Kokimoki server.
750
+ *
751
+ * Handles authentication, WebSocket setup, and automatic reconnection.
752
+ * If already connecting, returns the existing connection promise.
753
+ *
754
+ * @returns A promise that resolves when the connection is established.
755
+ * @throws Error if the connection fails.
756
+ */
123
757
  connect(): Promise<void>;
124
758
  private handleInitMessage;
125
759
  private handleBinaryMessage;
@@ -127,105 +761,140 @@ declare class KokimokiClient<ClientContextT = any> extends KokimokiClient_base {
127
761
  private handleSubscribeResMessage;
128
762
  private handleUnsubscribeResMessage;
129
763
  private handleRoomUpdateMessage;
764
+ /**
765
+ * Gets the current server timestamp, accounting for client-server time offset.
766
+ *
767
+ * @returns The current server timestamp in milliseconds.
768
+ */
130
769
  serverTimestamp(): number;
770
+ /**
771
+ * Sends a Y.js update to a specific room.
772
+ *
773
+ * @param room - The name of the room to update.
774
+ * @param update - The Y.js update as a Uint8Array.
775
+ * @returns A promise that resolves with the server response.
776
+ */
131
777
  patchRoomState(room: string, update: Uint8Array): Promise<any>;
132
- private createUpload;
133
- private uploadChunks;
134
- private completeUpload;
135
- upload(name: string, blob: Blob, tags?: string[]): Promise<Upload>;
136
- updateUpload(id: string, update: {
137
- tags?: string[];
138
- }): Promise<Upload>;
139
- listUploads(filter?: {
140
- clientId?: string;
141
- mimeTypes?: string[];
142
- tags?: string[];
143
- }, skip?: number, limit?: number): Promise<Paginated<Upload>>;
144
- deleteUpload(id: string): Promise<{
145
- acknowledged: boolean;
146
- deletedCount: number;
147
- }>;
148
- exposeScriptingContext(context: any): Promise<void>;
149
778
  private sendSubscribeReq;
150
779
  private sendUnsubscribeReq;
780
+ /**
781
+ * Joins a store by subscribing to its corresponding room.
782
+ *
783
+ * If already joined, this method does nothing. For local stores, initializes
784
+ * the store locally. For remote stores, sends a subscription request to the server.
785
+ *
786
+ * @param store - The KokimokiStore to join.
787
+ * @template T - The type of the store's state object.
788
+ */
151
789
  join<T extends object>(store: KokimokiStore<T>): Promise<void>;
790
+ /**
791
+ * Leaves a store by unsubscribing from its corresponding room.
792
+ *
793
+ * Triggers the store's `onBeforeLeave` and `onLeave` lifecycle hooks.
794
+ *
795
+ * @param store - The KokimokiStore to leave.
796
+ * @template T - The type of the store's state object.
797
+ */
152
798
  leave<T extends object>(store: KokimokiStore<T>): Promise<void>;
799
+ /**
800
+ * Executes a transaction across one or more stores.
801
+ *
802
+ * Provides proxies to the stores that track changes. All changes are batched
803
+ * and sent to the server atomically. The transaction ensures consistency across
804
+ * multiple stores.
805
+ *
806
+ * @param stores - Array of stores to include in the transaction.
807
+ * @param handler - Function that receives store proxies and performs modifications.
808
+ * @returns A promise that resolves with the return value of the handler.
809
+ * @template TStores - Tuple type of the stores array.
810
+ * @template ReturnT - The return type of the handler function.
811
+ *
812
+ * @example
813
+ * ```ts
814
+ * await client.transact([playerStore, gameStore], ([player, game]) => {
815
+ * player.score += 10;
816
+ * game.lastUpdate = Date.now();
817
+ * });
818
+ * ```
819
+ */
153
820
  transact<TStores extends readonly KokimokiStore<any>[], ReturnT = void>(stores: [...TStores], handler: (proxies: {
154
821
  [K in keyof TStores]: StoreValue<TStores[K]>;
155
822
  }) => ReturnT | Promise<ReturnT>): Promise<ReturnT>;
156
- close(): Promise<void>;
157
- getRoomHash<T extends object>(store: KokimokiStore<T>): number;
158
- /** Initializers */
159
- store<T extends object>(name: string, defaultState: T, autoJoin?: boolean): KokimokiStore<T>;
160
- localStore<T extends object>(name: string, defaultState: T): KokimokiLocalStore<T>;
161
- awareness<T>(name: string, initialData: T, autoJoin?: boolean): KokimokiAwareness<T>;
162
823
  /**
163
- * Add a new entry to a leaderboard
164
- * @param leaderboardName
165
- * @param score
166
- * @param metadata
167
- * @returns
824
+ * Closes the client connection and cleans up resources.
825
+ *
826
+ * Disables automatic reconnection, closes the WebSocket, and clears all intervals.
168
827
  */
169
- insertLeaderboardEntry<MetadataT, PrivateMetadataT>(leaderboardName: string, sortDir: "asc" | "desc", score: number, metadata: MetadataT, privateMetadata: PrivateMetadataT): Promise<{
170
- rank: number;
171
- }>;
828
+ close(): Promise<void>;
172
829
  /**
173
- * Add or update latest entry to a leaderboard
174
- * @param leaderboardName
175
- * @param score
176
- * @param metadata
177
- * @param privateMetadata Can only be read using the leaderboard API
178
- * @returns
830
+ * Gets the internal room hash identifier for a store.
831
+ *
832
+ * @param store - The store to get the room hash for.
833
+ * @returns The room hash as a number.
834
+ * @throws Error if the store hasn't been joined.
835
+ * @template T - The type of the store's state object.
179
836
  */
180
- upsertLeaderboardEntry<MetadataT, PrivateMetadataT>(leaderboardName: string, sortDir: "asc" | "desc", score: number, metadata: MetadataT, privateMetadata: PrivateMetadataT): Promise<{
181
- rank: number;
182
- }>;
837
+ getRoomHash<T extends object>(store: KokimokiStore<T>): number;
183
838
  /**
184
- * List entries in a leaderboard
185
- * @param leaderboardName
186
- * @param skip
187
- * @param limit
188
- * @returns
839
+ * Creates a new remote store synchronized with the server.
840
+ *
841
+ * @param name - The name of the room/store.
842
+ * @param defaultState - The initial state of the store.
843
+ * @param autoJoin - Whether to automatically join the store (default: true).
844
+ * @returns A new KokimokiStore instance.
845
+ * @template T - The type of the store's state object.
846
+ *
847
+ * @example
848
+ * ```ts
849
+ * const gameStore = client.store('game', { players: [], score: 0 });
850
+ * ```
189
851
  */
190
- listLeaderboardEntries<MetadataT>(leaderboardName: string, sortDir: "asc" | "desc", skip?: number, limit?: number): Promise<Paginated<{
191
- rank: number;
192
- score: number;
193
- metadata: MetadataT;
194
- }>>;
852
+ store<T extends object>(name: string, defaultState: T, autoJoin?: boolean): KokimokiStore<T>;
195
853
  /**
196
- * Get best entry in leaderboard for a client, defaults to current client
197
- * @param leaderboardName
198
- * @param sortDir
199
- * @param clientId
854
+ * Creates a new local store that persists only in the client's browser.
855
+ *
856
+ * Local stores are automatically joined and are not synchronized with the server.
857
+ * Data is stored locally per client and app.
858
+ *
859
+ * @param name - The name of the local store.
860
+ * @param defaultState - The initial state of the store.
861
+ * @returns A new KokimokiLocalStore instance.
862
+ * @template T - The type of the store's state object.
863
+ *
864
+ * @example
865
+ * ```ts
866
+ * const settingsStore = client.localStore('settings', { volume: 0.5, theme: 'dark' });
867
+ * ```
200
868
  */
201
- getBestLeaderboardEntry<MetadataT>(leaderboardName: string, sortDir: "asc" | "desc", clientId?: string): Promise<{
202
- rank: number;
203
- score: number;
204
- metadata: MetadataT;
205
- }>;
869
+ localStore<T extends object>(name: string, defaultState: T): KokimokiLocalStore<T>;
206
870
  /**
207
- * Send app data via webhook
871
+ * Sends app data to the server via webhook for external processing.
872
+ *
873
+ * @param event - The name of the webhook event.
874
+ * @param data - The data to send with the webhook.
875
+ * @returns A promise that resolves with the job ID.
876
+ * @template T - The type of the data being sent.
877
+ *
878
+ * @example
879
+ * ```ts
880
+ * await client.sendWebhook('game-ended', { winner: 'player1', score: 100 });
881
+ * ```
208
882
  */
209
883
  sendWebhook<T>(event: string, data: T): Promise<{
210
884
  jobId: string;
211
885
  }>;
212
886
  /**
213
- * Generic AI chat endpoint: send a system prompt (and optional user prompt) to get a response.
887
+ * Access AI capabilities including text generation, structured JSON output, and image modification.
214
888
  */
215
- chat(systemPrompt: string, userPrompt?: string, temperature?: number, maxTokens?: number): Promise<{
216
- content: string;
217
- }>;
889
+ get ai(): KokimokiAi;
218
890
  /**
219
- * Use AI to apply prompt to an image
891
+ * Access file upload and management for media files, images, and user-generated content.
220
892
  */
221
- transformImage(baseImageUrl: string, prompt: string, tags?: string[]): Promise<Upload>;
893
+ get storage(): KokimokiStorage;
222
894
  /**
223
- * Load app config - optionally translated to any language
895
+ * Access player ranking and score tracking with efficient queries and pagination.
224
896
  */
225
- getConfig<T>(language?: string): Promise<{
226
- status: "processing" | "failed" | "completed";
227
- config: T;
228
- }>;
897
+ get leaderboard(): KokimokiLeaderboard;
229
898
  }
230
899
 
231
900
  declare class RoomSubscription {
@@ -242,4 +911,4 @@ declare class RoomSubscription {
242
911
  close(): void;
243
912
  }
244
913
 
245
- export { KokimokiAwareness, KokimokiClient, type KokimokiClientEvents, KokimokiStore, type Paginated, RoomSubscription, RoomSubscriptionMode, type Upload };
914
+ export { KokimokiClient, type KokimokiClientEvents, KokimokiStore, type Paginated, RoomSubscription, RoomSubscriptionMode, type Upload };