@kokimoki/app 3.1.3 → 3.1.4

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 (61) hide show
  1. package/README.md +1 -2
  2. package/dist/core/kokimoki-client.d.ts +4 -4
  3. package/dist/core/kokimoki-client.js +4 -4
  4. package/dist/kokimoki.min.d.ts +3 -321
  5. package/dist/kokimoki.min.js +763 -2014
  6. package/dist/kokimoki.min.js.map +1 -1
  7. package/dist/utils/valtio.d.ts +2 -5
  8. package/dist/utils/valtio.js +4 -2
  9. package/dist/version.d.ts +1 -1
  10. package/dist/version.js +1 -1
  11. package/docs/kokimoki-ai.instructions.md +4 -2
  12. package/docs/kokimoki-dynamic-stores.instructions.md +3 -3
  13. package/docs/kokimoki-i18n.instructions.md +1 -1
  14. package/docs/kokimoki-sdk.instructions.md +46 -7
  15. package/package.json +8 -2
  16. package/dist/fields.d.ts +0 -110
  17. package/dist/fields.js +0 -158
  18. package/dist/kokimoki-ai.d.ts +0 -153
  19. package/dist/kokimoki-ai.js +0 -164
  20. package/dist/kokimoki-awareness.d.ts +0 -21
  21. package/dist/kokimoki-awareness.js +0 -48
  22. package/dist/kokimoki-client-refactored.d.ts +0 -80
  23. package/dist/kokimoki-client-refactored.js +0 -400
  24. package/dist/kokimoki-client.d.ts +0 -362
  25. package/dist/kokimoki-client.js +0 -823
  26. package/dist/kokimoki-leaderboard.d.ts +0 -175
  27. package/dist/kokimoki-leaderboard.js +0 -203
  28. package/dist/kokimoki-local-store.d.ts +0 -11
  29. package/dist/kokimoki-local-store.js +0 -40
  30. package/dist/kokimoki-queue.d.ts +0 -0
  31. package/dist/kokimoki-queue.js +0 -38
  32. package/dist/kokimoki-req-res.d.ts +0 -0
  33. package/dist/kokimoki-req-res.js +0 -198
  34. package/dist/kokimoki-schema.d.ts +0 -113
  35. package/dist/kokimoki-schema.js +0 -162
  36. package/dist/kokimoki-storage.d.ts +0 -156
  37. package/dist/kokimoki-storage.js +0 -208
  38. package/dist/kokimoki-store.d.ts +0 -23
  39. package/dist/kokimoki-store.js +0 -117
  40. package/dist/kokimoki-transaction.d.ts +0 -18
  41. package/dist/kokimoki-transaction.js +0 -143
  42. package/dist/message-queue.d.ts +0 -8
  43. package/dist/message-queue.js +0 -19
  44. package/dist/room-subscription-mode.d.ts +0 -5
  45. package/dist/room-subscription-mode.js +0 -6
  46. package/dist/room-subscription.d.ts +0 -15
  47. package/dist/room-subscription.js +0 -52
  48. package/dist/synced-schema.d.ts +0 -74
  49. package/dist/synced-schema.js +0 -83
  50. package/dist/synced-store.d.ts +0 -10
  51. package/dist/synced-store.js +0 -9
  52. package/dist/synced-types.d.ts +0 -47
  53. package/dist/synced-types.js +0 -67
  54. package/dist/ws-message-reader.d.ts +0 -11
  55. package/dist/ws-message-reader.js +0 -36
  56. package/dist/ws-message-type copy.d.ts +0 -6
  57. package/dist/ws-message-type copy.js +0 -7
  58. package/dist/ws-message-type.d.ts +0 -11
  59. package/dist/ws-message-type.js +0 -12
  60. package/dist/ws-message-writer.d.ts +0 -9
  61. package/dist/ws-message-writer.js +0 -45
@@ -1,823 +0,0 @@
1
- import EventEmitter from "events";
2
- import { KOKIMOKI_APP_VERSION } from "./version";
3
- import * as Y from "yjs";
4
- import { KokimokiTransaction } from "./kokimoki-transaction";
5
- import { KokimokiStore } from "./kokimoki-store";
6
- import { WsMessageType } from "./ws-message-type";
7
- import { WsMessageWriter } from "./ws-message-writer";
8
- import { WsMessageReader } from "./ws-message-reader";
9
- import { RoomSubscription } from "./room-subscription";
10
- import { KokimokiLocalStore } from "./kokimoki-local-store";
11
- import { KokimokiAi } from "./kokimoki-ai";
12
- import { KokimokiLeaderboard } from "./kokimoki-leaderboard";
13
- /**
14
- * Kokimoki Client - Real-time Collaborative Game Development SDK
15
- *
16
- * The main entry point for building multiplayer games and collaborative applications.
17
- * Provides real-time state synchronization, AI integration, cloud storage, leaderboards,
18
- * and more - all without complex backend setup.
19
- *
20
- * **Core Capabilities:**
21
- * - **Real-time Stores**: Synchronized state with automatic conflict resolution (powered by Valtio + Y.js)
22
- * - **Atomic Transactions**: Update multiple stores consistently with automatic batching
23
- * - **AI Integration**: Built-in text generation, structured JSON output, and image modification
24
- * - **Cloud Storage**: File uploads with CDN delivery and tag-based organization
25
- * - **Leaderboards**: Efficient player ranking with database indexes and pagination
26
- * - **Presence Tracking**: Real-time connection status for all players
27
- * - **Time Sync**: Server-synchronized timestamps across all clients
28
- * - **Webhooks**: Send data to external services for backend processing
29
- *
30
- * **Quick Start:**
31
- * ```typescript
32
- * import { KokimokiClient } from '@kokimoki/app';
33
- *
34
- * // Initialize the client
35
- * const kmClient = new KokimokiClient(
36
- * 'your-host.kokimoki.com',
37
- * 'your-app-id',
38
- * 'optional-access-code'
39
- * );
40
- *
41
- * // Connect to the server
42
- * await kmClient.connect();
43
- *
44
- * // Create a synchronized store
45
- * interface GameState {
46
- * players: Record<string, { name: string; score: number }>;
47
- * round: number;
48
- * }
49
- *
50
- * const gameStore = kmClient.store<GameState>('game', {
51
- * players: {},
52
- * round: 1
53
- * });
54
- *
55
- * // Update state atomically
56
- * await kmClient.transact([gameStore], ([game]) => {
57
- * game.players[kmClient.id] = { name: 'Player 1', score: 0 };
58
- * game.round = 2;
59
- * });
60
- *
61
- * // Use in React components with Valtio
62
- * import { useSnapshot } from 'valtio';
63
- *
64
- * function GameComponent() {
65
- * const game = useSnapshot(gameStore.proxy);
66
- * return <div>Round: {game.round}</div>;
67
- * }
68
- * ```
69
- *
70
- * **Key Features:**
71
- *
72
- * **1. Real-time State Management**
73
- * - Create global stores shared across all players: `kmClient.store()`
74
- * - Create local stores for client-side data: `kmClient.localStore()`
75
- * - Automatic synchronization and conflict resolution
76
- * - Use `useSnapshot()` from Valtio for reactive React components
77
- *
78
- * **2. Atomic Transactions**
79
- * ```typescript
80
- * // Update multiple stores atomically
81
- * await kmClient.transact([playerStore, gameStore], ([player, game]) => {
82
- * player.score += 10;
83
- * game.lastUpdate = kmClient.serverTimestamp();
84
- * });
85
- * ```
86
- *
87
- * **3. AI Integration (No API keys required)**
88
- * ```typescript
89
- * // Generate text
90
- * const story = await kmClient.ai.chat({
91
- * model: 'gpt-4o',
92
- * userPrompt: 'Write a quest description',
93
- * temperature: 0.8
94
- * });
95
- *
96
- * // Generate structured data
97
- * interface Quest { title: string; reward: number; }
98
- * const quest = await kmClient.ai.generateJson<Quest>({
99
- * userPrompt: 'Create a level 5 quest'
100
- * });
101
- *
102
- * // Modify images
103
- * const modified = await kmClient.ai.modifyImage(url, 'Make it pixel art');
104
- * ```
105
- *
106
- * **4. Cloud Storage**
107
- * ```typescript
108
- * // Upload files with tags
109
- * const upload = await kmClient.storage.upload('avatar.jpg', blob, ['profile']);
110
- *
111
- * // Query uploads
112
- * const images = await kmClient.storage.listUploads({
113
- * clientId: kmClient.id,
114
- * mimeTypes: ['image/jpeg', 'image/png']
115
- * });
116
- * ```
117
- *
118
- * **5. Leaderboards**
119
- * ```typescript
120
- * // Submit score (replaces previous entry)
121
- * await kmClient.leaderboard.upsertEntry(
122
- * 'high-scores',
123
- * 'desc',
124
- * 1500,
125
- * { playerName: 'Alice' },
126
- * {}
127
- * );
128
- *
129
- * // Get top 10
130
- * const top10 = await kmClient.leaderboard.listEntries('high-scores', 'desc', 0, 10);
131
- * ```
132
- *
133
- * **6. Presence Tracking**
134
- * ```typescript
135
- * // Track online players
136
- * const onlineClientIds = useSnapshot(gameStore.connections).clientIds;
137
- * const isPlayerOnline = onlineClientIds.has(playerId);
138
- * ```
139
- *
140
- * **Best Practices:**
141
- * - Always use `kmClient.serverTimestamp()` for time-sensitive operations
142
- * - Prefer Records over Arrays: `Record<string, T>` with timestamp keys
143
- * - Use `kmClient.transact()` for all state updates to ensure atomicity
144
- * - Tag uploads for easy filtering and organization
145
- * - Use local stores for client-side settings and preferences
146
- * - Leverage TypeScript generics for type-safe stores
147
- *
148
- * **Events:**
149
- * - `connected`: Fired when client connects/reconnects to server
150
- * - `disconnected`: Fired when connection is lost
151
- *
152
- * @template ClientContextT The type of client context data (custom user data from your backend)
153
- *
154
- * @example
155
- * ```typescript
156
- * // Listen for connection events
157
- * kmClient.on('connected', () => {
158
- * console.log('Connected to Kokimoki!');
159
- * });
160
- *
161
- * kmClient.on('disconnected', () => {
162
- * console.log('Connection lost, will auto-reconnect...');
163
- * });
164
- * ```
165
- */
166
- export class KokimokiClient extends EventEmitter {
167
- host;
168
- appId;
169
- code;
170
- _wsUrl;
171
- _apiUrl;
172
- _id;
173
- _connectionId;
174
- _token;
175
- _apiHeaders;
176
- _serverTimeOffset = 0;
177
- _clientContext;
178
- _ws;
179
- _subscriptionsByName = new Map();
180
- _subscriptionsByHash = new Map();
181
- _subscribeReqPromises = new Map();
182
- _unsubscribeReqPromises = new Map();
183
- _transactionPromises = new Map();
184
- _connected = false;
185
- _connectPromise;
186
- _messageId = 0;
187
- _autoReconnect = true;
188
- _reconnectTimeout = 0;
189
- _pingInterval;
190
- _clientTokenKey = "KM_TOKEN";
191
- _editorContext;
192
- _ai;
193
- _storage;
194
- _leaderboard;
195
- constructor(host, appId, code = "") {
196
- super();
197
- this.host = host;
198
- this.appId = appId;
199
- this.code = code;
200
- // Set up the URLs
201
- const secure = this.host.indexOf(":") === -1;
202
- this._wsUrl = `ws${secure ? "s" : ""}://${this.host}`;
203
- this._apiUrl = `http${secure ? "s" : ""}://${this.host}`;
204
- // Initialize modules
205
- this._ai = new KokimokiAi(this);
206
- this._leaderboard = new KokimokiLeaderboard(this);
207
- // Set up ping interval
208
- const pingMsg = new WsMessageWriter();
209
- pingMsg.writeInt32(WsMessageType.Ping);
210
- const pingBuffer = pingMsg.getBuffer();
211
- this._pingInterval = setInterval(() => {
212
- if (this.connected) {
213
- this.ws.send(pingBuffer);
214
- }
215
- }, 5000);
216
- // Listen for devtools messages
217
- if (window.parent && window.self !== window.parent) {
218
- window.addEventListener("message", (e) => {
219
- console.log(`[KM TOOLS] ${e.data}`);
220
- this._editorContext = e.data;
221
- if (e.data === "km:clearStorage") {
222
- localStorage.removeItem(this._clientTokenKey);
223
- window.location.reload();
224
- }
225
- else if (e.data === "km:reload") {
226
- window.location.reload();
227
- }
228
- });
229
- }
230
- }
231
- get id() {
232
- if (!this._id) {
233
- throw new Error("Client not connected");
234
- }
235
- return this._id;
236
- }
237
- get connectionId() {
238
- if (!this._connectionId) {
239
- throw new Error("Client not connected");
240
- }
241
- return this._connectionId;
242
- }
243
- get token() {
244
- if (!this._token) {
245
- throw new Error("Client not connected");
246
- }
247
- return this._token;
248
- }
249
- get apiUrl() {
250
- if (!this._apiUrl) {
251
- throw new Error("Client not connected");
252
- }
253
- return this._apiUrl;
254
- }
255
- get apiHeaders() {
256
- if (!this._apiHeaders) {
257
- throw new Error("Client not connected");
258
- }
259
- return this._apiHeaders;
260
- }
261
- get clientContext() {
262
- if (this._clientContext === undefined) {
263
- throw new Error("Client not connected");
264
- }
265
- return this._clientContext;
266
- }
267
- /**
268
- * Indicates whether the client is currently connected to the server.
269
- */
270
- get connected() {
271
- return this._connected;
272
- }
273
- get ws() {
274
- if (!this._ws) {
275
- throw new Error("Not connected");
276
- }
277
- return this._ws;
278
- }
279
- /**
280
- * Indicates whether the client is running in editor/development mode.
281
- */
282
- get isEditor() {
283
- return !!this._editorContext;
284
- }
285
- /**
286
- * Establishes a connection to the Kokimoki server.
287
- *
288
- * Handles authentication, WebSocket setup, and automatic reconnection.
289
- * If already connecting, returns the existing connection promise.
290
- *
291
- * @returns A promise that resolves when the connection is established.
292
- * @throws Error if the connection fails.
293
- */
294
- async connect() {
295
- if (this._connectPromise) {
296
- return await this._connectPromise;
297
- }
298
- // Detect devtools
299
- if (window.parent && window.self !== window.parent) {
300
- await new Promise((resolve) => {
301
- /* // Wait up to 500ms for parent to respond
302
- const timeout = setTimeout(() => {
303
- window.removeEventListener("message", onMessage);
304
- resolve();
305
- }, 500); */
306
- // Listen for parent response
307
- const onMessage = (e) => {
308
- // clearTimeout(timeout);
309
- window.removeEventListener("message", onMessage);
310
- if (e.data.clientKey) {
311
- this._clientTokenKey = `KM_TOKEN/${e.data.clientKey}`;
312
- }
313
- resolve();
314
- };
315
- window.addEventListener("message", onMessage);
316
- window.parent.postMessage({ appId: this.appId }, "*");
317
- });
318
- }
319
- // Set up the WebSocket connection
320
- this._ws = new WebSocket(`${this._wsUrl}/apps/${this.appId}?clientVersion=${KOKIMOKI_APP_VERSION}`);
321
- this._ws.binaryType = "arraybuffer";
322
- // Close previous connection in hot-reload scenarios
323
- if (window) {
324
- if (!window.__KOKIMOKI_WS__) {
325
- window.__KOKIMOKI_WS__ = {};
326
- }
327
- if (this.appId in window.__KOKIMOKI_WS__) {
328
- console.log(`[Kokimoki] Closing previous connection for ${this.appId}`);
329
- window.__KOKIMOKI_WS__[this.appId].close();
330
- }
331
- window.__KOKIMOKI_WS__[this.appId] = this;
332
- }
333
- // Wait for connection
334
- this._connectPromise = new Promise((onInit) => {
335
- // Fetch the auth token
336
- let clientToken = localStorage.getItem(this._clientTokenKey);
337
- // Send the app token on first connect
338
- this.ws.onopen = () => {
339
- this.ws.send(JSON.stringify({ type: "auth", code: this.code, token: clientToken }));
340
- };
341
- this.ws.onclose = () => {
342
- this._connected = false;
343
- this._connectPromise = undefined;
344
- this._ws.onmessage = null;
345
- this._ws = undefined;
346
- if (window && window.__KOKIMOKI_WS__) {
347
- delete window.__KOKIMOKI_WS__[this.appId];
348
- }
349
- // Clean up
350
- this._subscribeReqPromises.clear();
351
- this._transactionPromises.clear();
352
- // Attempt to reconnect
353
- if (!this._autoReconnect) {
354
- return;
355
- }
356
- console.log(`[Kokimoki] Connection lost, attempting to reconnect in ${this._reconnectTimeout} seconds...`);
357
- setTimeout(async () => await this.connect(), this._reconnectTimeout * 1000);
358
- this._reconnectTimeout = Math.min(3, this._reconnectTimeout + 1);
359
- // Emit disconnected event
360
- this.emit("disconnected");
361
- };
362
- this.ws.onmessage = (e) => {
363
- // console.log(`Received WS message: ${e.data}`);
364
- // Handle JSON messages
365
- if (typeof e.data === "string") {
366
- const message = JSON.parse(e.data);
367
- switch (message.type) {
368
- case "init":
369
- this.handleInitMessage(message);
370
- onInit();
371
- break;
372
- }
373
- return;
374
- }
375
- // Handle binary messages
376
- this.handleBinaryMessage(e.data);
377
- };
378
- });
379
- await this._connectPromise;
380
- this._connected = true;
381
- // Connection established
382
- console.log(`[Kokimoki] Client id: ${this.id}`);
383
- console.log(`[Kokimoki] Client context:`, this.clientContext);
384
- // Restore subscriptions if reconnected
385
- const roomNames = Array.from(this._subscriptionsByName.keys()).map((name) => `"${name}"`);
386
- if (roomNames.length) {
387
- console.log(`[Kokimoki] Restoring subscriptions: ${roomNames}`);
388
- }
389
- for (const subscription of this._subscriptionsByName.values()) {
390
- try {
391
- await this.join(subscription.store);
392
- }
393
- catch (err) {
394
- console.error(`[Kokimoki] Failed to restore subscription for "${subscription.roomName}":`, err);
395
- }
396
- }
397
- // Emit connected event
398
- this._reconnectTimeout = 0;
399
- this.emit("connected");
400
- }
401
- handleInitMessage(message) {
402
- localStorage.setItem(this._clientTokenKey, message.clientToken);
403
- this._id = message.clientId;
404
- this._connectionId = message.id;
405
- this._token = message.appToken;
406
- this._clientContext = message.clientContext;
407
- // Set up the auth headers
408
- this._apiHeaders = new Headers({
409
- Authorization: `Bearer ${this.token}`,
410
- "Content-Type": "application/json",
411
- });
412
- }
413
- handleBinaryMessage(data) {
414
- const reader = new WsMessageReader(data);
415
- const type = reader.readInt32();
416
- switch (type) {
417
- case WsMessageType.SubscribeRes:
418
- this.handleSubscribeResMessage(reader);
419
- break;
420
- case WsMessageType.UnsubscribeRes:
421
- this.handleUnsubscribeResMessage(reader);
422
- break;
423
- case WsMessageType.RoomUpdate:
424
- this.handleRoomUpdateMessage(reader);
425
- break;
426
- case WsMessageType.Error:
427
- this.handleErrorMessage(reader);
428
- break;
429
- case WsMessageType.Pong: {
430
- const s = reader.readInt32();
431
- const ms = reader.readInt32();
432
- this._serverTimeOffset = Date.now() - s * 1000 - ms;
433
- break;
434
- }
435
- }
436
- }
437
- handleErrorMessage(msg) {
438
- const reqId = msg.readInt32();
439
- const error = msg.readString();
440
- const subscribeReqPromise = this._subscribeReqPromises.get(reqId);
441
- const transactionPromise = this._transactionPromises.get(reqId);
442
- if (subscribeReqPromise) {
443
- this._subscribeReqPromises.delete(reqId);
444
- subscribeReqPromise.reject(error);
445
- }
446
- else if (transactionPromise) {
447
- this._transactionPromises.delete(reqId);
448
- transactionPromise.reject(error);
449
- }
450
- else {
451
- console.warn(`Received error for unknown request ${reqId}: ${error}`);
452
- }
453
- }
454
- handleSubscribeResMessage(msg) {
455
- const reqId = msg.readInt32();
456
- const roomHash = msg.readUint32();
457
- const promise = this._subscribeReqPromises.get(reqId);
458
- if (promise) {
459
- this._subscribeReqPromises.delete(reqId);
460
- // In Write mode, no initial state is sent
461
- if (!msg.end) {
462
- promise.resolve(roomHash, msg.readUint8Array());
463
- }
464
- else {
465
- promise.resolve(roomHash);
466
- }
467
- }
468
- }
469
- handleUnsubscribeResMessage(msg) {
470
- const reqId = msg.readInt32();
471
- const promise = this._unsubscribeReqPromises.get(reqId);
472
- if (promise) {
473
- this._unsubscribeReqPromises.delete(reqId);
474
- promise.resolve();
475
- }
476
- }
477
- handleRoomUpdateMessage(msg) {
478
- const appliedId = msg.readInt32();
479
- const roomHash = msg.readUint32();
480
- // Apply update if not in Write mode
481
- if (!msg.end) {
482
- const subscription = this._subscriptionsByHash.get(roomHash);
483
- if (subscription) {
484
- Y.applyUpdate(subscription.store.doc, msg.readUint8Array(), this);
485
- }
486
- else {
487
- console.warn(`Received update for unknown room ${roomHash}`);
488
- }
489
- }
490
- // Check transaction resolves
491
- for (const [transactionId, { resolve },] of this._transactionPromises.entries()) {
492
- if (appliedId >= transactionId) {
493
- this._transactionPromises.delete(transactionId);
494
- resolve();
495
- }
496
- }
497
- }
498
- /**
499
- * Gets the current server timestamp, accounting for client-server time offset.
500
- *
501
- * @returns The current server timestamp in milliseconds.
502
- */
503
- serverTimestamp() {
504
- return Date.now() - this._serverTimeOffset;
505
- }
506
- /**
507
- * Sends a Y.js update to a specific room.
508
- *
509
- * @param room - The name of the room to update.
510
- * @param update - The Y.js update as a Uint8Array.
511
- * @returns A promise that resolves with the server response.
512
- */
513
- async patchRoomState(room, update) {
514
- const res = await fetch(`${this._apiUrl}/rooms/${room}`, {
515
- method: "PATCH",
516
- headers: this.apiHeaders,
517
- body: update,
518
- });
519
- return await res.json();
520
- }
521
- async sendSubscribeReq(roomName, mode) {
522
- // Set up sync resolver
523
- const reqId = ++this._messageId;
524
- return await new Promise((resolve, reject) => {
525
- this._subscribeReqPromises.set(reqId, {
526
- resolve: (roomHash, initialUpdate) => {
527
- resolve({ roomHash, initialUpdate });
528
- },
529
- reject,
530
- });
531
- // Send subscription request
532
- const msg = new WsMessageWriter();
533
- msg.writeInt32(WsMessageType.SubscribeReq);
534
- msg.writeInt32(reqId);
535
- msg.writeString(roomName);
536
- msg.writeChar(mode);
537
- this.ws.send(msg.getBuffer());
538
- });
539
- }
540
- async sendUnsubscribeReq(roomHash) {
541
- const reqId = ++this._messageId;
542
- return await new Promise((resolve, reject) => {
543
- this._unsubscribeReqPromises.set(reqId, {
544
- resolve,
545
- reject,
546
- });
547
- // Send unsubscribe request
548
- const msg = new WsMessageWriter();
549
- msg.writeInt32(WsMessageType.UnsubscribeReq);
550
- msg.writeInt32(reqId);
551
- msg.writeUint32(roomHash);
552
- this.ws.send(msg.getBuffer());
553
- });
554
- }
555
- /**
556
- * Joins a store by subscribing to its corresponding room.
557
- *
558
- * If already joined, this method does nothing. For local stores, initializes
559
- * the store locally. For remote stores, sends a subscription request to the server.
560
- *
561
- * @param store - The KokimokiStore to join.
562
- * @template T - The type of the store's state object.
563
- */
564
- async join(store) {
565
- let subscription = this._subscriptionsByName.get(store.roomName);
566
- if (!subscription) {
567
- subscription = new RoomSubscription(this, store);
568
- this._subscriptionsByName.set(store.roomName, subscription);
569
- }
570
- // Send subscription request if connected to server
571
- if (!subscription.joined) {
572
- let res;
573
- if (store instanceof KokimokiLocalStore) {
574
- res = store.getInitialUpdate(this.appId, this.id);
575
- }
576
- else {
577
- res = await this.sendSubscribeReq(store.roomName, store.mode);
578
- }
579
- this._subscriptionsByHash.set(res.roomHash, subscription);
580
- await subscription.applyInitialResponse(res.roomHash, res.initialUpdate);
581
- // Trigger onJoin event
582
- await store.onJoin(this);
583
- }
584
- }
585
- /**
586
- * Leaves a store by unsubscribing from its corresponding room.
587
- *
588
- * Triggers the store's `onBeforeLeave` and `onLeave` lifecycle hooks.
589
- *
590
- * @param store - The KokimokiStore to leave.
591
- * @template T - The type of the store's state object.
592
- */
593
- async leave(store) {
594
- const subscription = this._subscriptionsByName.get(store.roomName);
595
- if (subscription) {
596
- await store.onBeforeLeave(this);
597
- await this.sendUnsubscribeReq(subscription.roomHash);
598
- this._subscriptionsByName.delete(store.roomName);
599
- this._subscriptionsByHash.delete(subscription.roomHash);
600
- subscription.close();
601
- // Trigger onLeave event
602
- store.onLeave(this);
603
- }
604
- }
605
- /**
606
- * Executes a transaction across one or more stores.
607
- *
608
- * Provides proxies to the stores that track changes. All changes are batched
609
- * and sent to the server atomically. The transaction ensures consistency across
610
- * multiple stores.
611
- *
612
- * @param stores - Array of stores to include in the transaction.
613
- * @param handler - Function that receives store proxies and performs modifications.
614
- * @returns A promise that resolves with the return value of the handler.
615
- * @template TStores - Tuple type of the stores array.
616
- * @template ReturnT - The return type of the handler function.
617
- *
618
- * @example
619
- * ```ts
620
- * await client.transact([playerStore, gameStore], ([player, game]) => {
621
- * player.score += 10;
622
- * game.lastUpdate = Date.now();
623
- * });
624
- * ```
625
- */
626
- async transact(stores, handler) {
627
- // if (!this._connected) {
628
- // throw new Error("Client not connected");
629
- // }
630
- const transaction = new KokimokiTransaction(stores);
631
- // @ts-ignore
632
- const returnValue = await handler(transaction.getProxies());
633
- const { updates, consumedMessages } = await transaction.getUpdates();
634
- if (!updates.length) {
635
- return returnValue;
636
- }
637
- // Construct buffers
638
- const remoteUpdateWriter = new WsMessageWriter();
639
- const localUpdateWriter = new WsMessageWriter();
640
- // Write message type
641
- remoteUpdateWriter.writeInt32(WsMessageType.Transaction);
642
- // Update and write transaction ID
643
- const transactionId = ++this._messageId;
644
- remoteUpdateWriter.writeInt32(transactionId);
645
- localUpdateWriter.writeInt32(transactionId);
646
- // Write room hashes where messages were consumed (remote only)
647
- remoteUpdateWriter.writeInt32(consumedMessages.size);
648
- for (const roomName of consumedMessages) {
649
- const subscription = this._subscriptionsByName.get(roomName);
650
- if (!subscription) {
651
- throw new Error(`Cannot consume message in "${roomName}" because it hasn't been joined`);
652
- }
653
- remoteUpdateWriter.writeUint32(subscription.roomHash);
654
- }
655
- // Write updates
656
- let localUpdates = 0, remoteUpdates = 0;
657
- for (const { roomName, update } of updates) {
658
- const subscription = this._subscriptionsByName.get(roomName);
659
- if (!subscription) {
660
- throw new Error(`Cannot send update to "${roomName}" because it hasn't been joined`);
661
- }
662
- if (subscription.store instanceof KokimokiLocalStore) {
663
- localUpdates++;
664
- localUpdateWriter.writeUint32(subscription.roomHash);
665
- localUpdateWriter.writeUint8Array(update);
666
- }
667
- else {
668
- remoteUpdates++;
669
- remoteUpdateWriter.writeUint32(subscription.roomHash);
670
- remoteUpdateWriter.writeUint8Array(update);
671
- }
672
- }
673
- // Wait for server to apply transaction
674
- if (remoteUpdates) {
675
- const remoteBuffer = remoteUpdateWriter.getBuffer();
676
- await new Promise((resolve, reject) => {
677
- this._transactionPromises.set(transactionId, { resolve, reject });
678
- // Send update to server
679
- try {
680
- this.ws.send(remoteBuffer);
681
- }
682
- catch (e) {
683
- // Not connected
684
- console.log("Failed to send update to server:", e);
685
- // Delete transaction promise
686
- this._transactionPromises.delete(transactionId);
687
- // TODO: merge updates or something
688
- reject(e);
689
- }
690
- });
691
- }
692
- // Apply local updates
693
- if (localUpdates) {
694
- const localBuffer = localUpdateWriter.getBuffer();
695
- const reader = new WsMessageReader(localBuffer);
696
- this.handleRoomUpdateMessage(reader);
697
- }
698
- return returnValue;
699
- }
700
- /**
701
- * Closes the client connection and cleans up resources.
702
- *
703
- * Disables automatic reconnection, closes the WebSocket, and clears all intervals.
704
- */
705
- async close() {
706
- this._autoReconnect = false;
707
- if (this._ws) {
708
- this._ws.close();
709
- }
710
- if (this._pingInterval) {
711
- clearInterval(this._pingInterval);
712
- }
713
- }
714
- /**
715
- * Gets the internal room hash identifier for a store.
716
- *
717
- * @param store - The store to get the room hash for.
718
- * @returns The room hash as a number.
719
- * @throws Error if the store hasn't been joined.
720
- * @template T - The type of the store's state object.
721
- */
722
- getRoomHash(store) {
723
- const subscription = this._subscriptionsByName.get(store.roomName);
724
- if (!subscription) {
725
- throw new Error(`Store "${store.roomName}" not joined`);
726
- }
727
- return subscription.roomHash;
728
- }
729
- /**
730
- * Creates a new remote store synchronized with the server.
731
- *
732
- * @param name - The name of the room/store.
733
- * @param defaultState - The initial state of the store.
734
- * @param autoJoin - Whether to automatically join the store (default: true).
735
- * @returns A new KokimokiStore instance.
736
- * @template T - The type of the store's state object.
737
- *
738
- * @example
739
- * ```ts
740
- * const gameStore = client.store('game', { players: [], score: 0 });
741
- * ```
742
- */
743
- store(name, defaultState, autoJoin = true) {
744
- const store = new KokimokiStore(name, defaultState);
745
- if (autoJoin) {
746
- this.join(store)
747
- .then(() => { })
748
- .catch(() => { });
749
- }
750
- return store;
751
- }
752
- /**
753
- * Creates a new local store that persists only in the client's browser.
754
- *
755
- * Local stores are automatically joined and are not synchronized with the server.
756
- * Data is stored locally per client and app.
757
- *
758
- * @param name - The name of the local store.
759
- * @param defaultState - The initial state of the store.
760
- * @returns A new KokimokiLocalStore instance.
761
- * @template T - The type of the store's state object.
762
- *
763
- * @example
764
- * ```ts
765
- * const settingsStore = client.localStore('settings', { volume: 0.5, theme: 'dark' });
766
- * ```
767
- */
768
- localStore(name, defaultState) {
769
- const store = new KokimokiLocalStore(name, defaultState);
770
- this.join(store)
771
- .then(() => { })
772
- .catch(() => { });
773
- return store;
774
- }
775
- /**
776
- * Sends app data to the server via webhook for external processing.
777
- *
778
- * @param event - The name of the webhook event.
779
- * @param data - The data to send with the webhook.
780
- * @returns A promise that resolves with the job ID.
781
- * @template T - The type of the data being sent.
782
- *
783
- * @example
784
- * ```ts
785
- * await client.sendWebhook('game-ended', { winner: 'player1', score: 100 });
786
- * ```
787
- */
788
- async sendWebhook(event, data) {
789
- const res = await fetch(`${this._apiUrl}/webhooks`, {
790
- method: "POST",
791
- headers: this.apiHeaders,
792
- body: JSON.stringify({ event, data }),
793
- });
794
- return await res.json();
795
- }
796
- /**
797
- * Access AI capabilities including text generation, structured JSON output, and image modification.
798
- */
799
- get ai() {
800
- if (!this._ai) {
801
- throw new Error("AI client not initialized");
802
- }
803
- return this._ai;
804
- }
805
- /**
806
- * Access file upload and management for media files, images, and user-generated content.
807
- */
808
- get storage() {
809
- if (!this._storage) {
810
- throw new Error("Storage client not initialized");
811
- }
812
- return this._storage;
813
- }
814
- /**
815
- * Access player ranking and score tracking with efficient queries and pagination.
816
- */
817
- get leaderboard() {
818
- if (!this._leaderboard) {
819
- throw new Error("Leaderboard client not initialized");
820
- }
821
- return this._leaderboard;
822
- }
823
- }