@watchtower-sdk/core 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -256,6 +256,285 @@ var Room = class {
256
256
  return this.ws?.readyState === WebSocket.OPEN;
257
257
  }
258
258
  };
259
+ var Sync = class {
260
+ constructor(state, config, options) {
261
+ this._roomId = null;
262
+ this.ws = null;
263
+ this.syncInterval = null;
264
+ this.lastSentState = "";
265
+ this.interpolationTargets = /* @__PURE__ */ new Map();
266
+ this.listeners = /* @__PURE__ */ new Map();
267
+ this.state = state;
268
+ this.myId = config.playerId;
269
+ this.config = config;
270
+ this.options = {
271
+ tickRate: options?.tickRate ?? 20,
272
+ interpolate: options?.interpolate ?? true
273
+ };
274
+ }
275
+ /** Current room ID (null if not in a room) */
276
+ get roomId() {
277
+ return this._roomId;
278
+ }
279
+ /** Whether currently connected to a room */
280
+ get connected() {
281
+ return this.ws?.readyState === WebSocket.OPEN;
282
+ }
283
+ /**
284
+ * Join a room - your state will sync with everyone in this room
285
+ *
286
+ * @param roomId - Room identifier (any string)
287
+ * @param options - Join options
288
+ */
289
+ async join(roomId, options) {
290
+ if (this._roomId) {
291
+ await this.leave();
292
+ }
293
+ this._roomId = roomId;
294
+ await this.connectWebSocket(roomId, options);
295
+ this.startSyncLoop();
296
+ }
297
+ /**
298
+ * Leave the current room
299
+ */
300
+ async leave() {
301
+ this.stopSyncLoop();
302
+ if (this.ws) {
303
+ this.ws.close();
304
+ this.ws = null;
305
+ }
306
+ this.clearRemotePlayers();
307
+ this._roomId = null;
308
+ }
309
+ /**
310
+ * Create a new room and join it
311
+ *
312
+ * @param options - Room creation options
313
+ * @returns The room code/ID
314
+ */
315
+ async create(options) {
316
+ const code = this.generateRoomCode();
317
+ await this.join(code, { ...options, create: true });
318
+ return code;
319
+ }
320
+ /**
321
+ * List public rooms
322
+ */
323
+ async listRooms() {
324
+ const response = await fetch(`${this.config.apiUrl}/v1/sync/rooms?gameId=${this.config.gameId}`, {
325
+ headers: this.getHeaders()
326
+ });
327
+ if (!response.ok) {
328
+ const data2 = await response.json();
329
+ throw new Error(data2.error || "Failed to list rooms");
330
+ }
331
+ const data = await response.json();
332
+ return data.rooms || [];
333
+ }
334
+ /**
335
+ * Subscribe to sync events
336
+ */
337
+ on(event, callback) {
338
+ if (!this.listeners.has(event)) {
339
+ this.listeners.set(event, /* @__PURE__ */ new Set());
340
+ }
341
+ this.listeners.get(event).add(callback);
342
+ }
343
+ /**
344
+ * Unsubscribe from sync events
345
+ */
346
+ off(event, callback) {
347
+ this.listeners.get(event)?.delete(callback);
348
+ }
349
+ emit(event, ...args) {
350
+ this.listeners.get(event)?.forEach((cb) => {
351
+ try {
352
+ cb(...args);
353
+ } catch (e) {
354
+ console.error(`Error in sync ${event} handler:`, e);
355
+ }
356
+ });
357
+ }
358
+ async connectWebSocket(roomId, options) {
359
+ return new Promise((resolve, reject) => {
360
+ const wsUrl = this.config.apiUrl.replace("https://", "wss://").replace("http://", "ws://");
361
+ const params = new URLSearchParams({
362
+ playerId: this.config.playerId,
363
+ gameId: this.config.gameId,
364
+ ...this.config.apiKey ? { apiKey: this.config.apiKey } : {},
365
+ ...options?.create ? { create: "true" } : {},
366
+ ...options?.maxPlayers ? { maxPlayers: String(options.maxPlayers) } : {},
367
+ ...options?.public ? { public: "true" } : {},
368
+ ...options?.metadata ? { metadata: JSON.stringify(options.metadata) } : {}
369
+ });
370
+ const url = `${wsUrl}/v1/sync/${roomId}/ws?${params}`;
371
+ this.ws = new WebSocket(url);
372
+ const timeout = setTimeout(() => {
373
+ reject(new Error("Connection timeout"));
374
+ this.ws?.close();
375
+ }, 1e4);
376
+ this.ws.onopen = () => {
377
+ clearTimeout(timeout);
378
+ this.emit("connected");
379
+ resolve();
380
+ };
381
+ this.ws.onerror = () => {
382
+ clearTimeout(timeout);
383
+ const error = new Error("WebSocket connection failed");
384
+ this.emit("error", error);
385
+ reject(error);
386
+ };
387
+ this.ws.onclose = () => {
388
+ this.stopSyncLoop();
389
+ this.emit("disconnected");
390
+ };
391
+ this.ws.onmessage = (event) => {
392
+ try {
393
+ const data = JSON.parse(event.data);
394
+ this.handleMessage(data);
395
+ } catch (e) {
396
+ console.error("Failed to parse sync message:", e);
397
+ }
398
+ };
399
+ });
400
+ }
401
+ handleMessage(data) {
402
+ switch (data.type) {
403
+ case "full_state":
404
+ this.applyFullState(data.state);
405
+ break;
406
+ case "state":
407
+ this.applyPlayerState(data.playerId, data.data);
408
+ break;
409
+ case "join":
410
+ this.emit("join", data.playerId);
411
+ break;
412
+ case "leave":
413
+ this.removePlayer(data.playerId);
414
+ this.emit("leave", data.playerId);
415
+ break;
416
+ }
417
+ }
418
+ applyFullState(fullState) {
419
+ for (const [playerId, playerState] of Object.entries(fullState)) {
420
+ if (playerId !== this.myId) {
421
+ this.applyPlayerState(playerId, playerState);
422
+ }
423
+ }
424
+ }
425
+ applyPlayerState(playerId, playerState) {
426
+ const playersKey = this.findPlayersKey();
427
+ if (!playersKey) return;
428
+ const players = this.state[playersKey];
429
+ if (this.options.interpolate && players[playerId]) {
430
+ this.interpolationTargets.set(playerId, {
431
+ target: { ...playerState },
432
+ current: { ...players[playerId] }
433
+ });
434
+ }
435
+ players[playerId] = playerState;
436
+ }
437
+ removePlayer(playerId) {
438
+ const playersKey = this.findPlayersKey();
439
+ if (!playersKey) return;
440
+ const players = this.state[playersKey];
441
+ delete players[playerId];
442
+ this.interpolationTargets.delete(playerId);
443
+ }
444
+ clearRemotePlayers() {
445
+ const playersKey = this.findPlayersKey();
446
+ if (!playersKey) return;
447
+ const players = this.state[playersKey];
448
+ for (const playerId of Object.keys(players)) {
449
+ if (playerId !== this.myId) {
450
+ delete players[playerId];
451
+ }
452
+ }
453
+ this.interpolationTargets.clear();
454
+ }
455
+ findPlayersKey() {
456
+ const candidates = ["players", "entities", "gnomes", "users", "clients"];
457
+ for (const key of candidates) {
458
+ if (key in this.state && typeof this.state[key] === "object") {
459
+ return key;
460
+ }
461
+ }
462
+ for (const key of Object.keys(this.state)) {
463
+ if (typeof this.state[key] === "object" && this.state[key] !== null) {
464
+ return key;
465
+ }
466
+ }
467
+ return null;
468
+ }
469
+ startSyncLoop() {
470
+ if (this.syncInterval) return;
471
+ const intervalMs = 1e3 / this.options.tickRate;
472
+ this.syncInterval = setInterval(() => {
473
+ this.syncMyState();
474
+ if (this.options.interpolate) {
475
+ this.updateInterpolation();
476
+ }
477
+ }, intervalMs);
478
+ }
479
+ stopSyncLoop() {
480
+ if (this.syncInterval) {
481
+ clearInterval(this.syncInterval);
482
+ this.syncInterval = null;
483
+ }
484
+ }
485
+ syncMyState() {
486
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
487
+ const playersKey = this.findPlayersKey();
488
+ if (!playersKey) return;
489
+ const players = this.state[playersKey];
490
+ const myState = players[this.myId];
491
+ if (!myState) return;
492
+ const stateJson = JSON.stringify(myState);
493
+ if (stateJson === this.lastSentState) return;
494
+ this.lastSentState = stateJson;
495
+ this.ws.send(JSON.stringify({
496
+ type: "state",
497
+ data: myState
498
+ }));
499
+ }
500
+ updateInterpolation() {
501
+ const playersKey = this.findPlayersKey();
502
+ if (!playersKey) return;
503
+ const players = this.state[playersKey];
504
+ const lerpFactor = 0.2;
505
+ for (const [playerId, interp] of this.interpolationTargets) {
506
+ const player = players[playerId];
507
+ if (!player) continue;
508
+ for (const [key, targetValue] of Object.entries(interp.target)) {
509
+ if (typeof targetValue === "number" && typeof interp.current[key] === "number") {
510
+ const current = interp.current[key];
511
+ const newValue = current + (targetValue - current) * lerpFactor;
512
+ interp.current[key] = newValue;
513
+ player[key] = newValue;
514
+ }
515
+ }
516
+ }
517
+ }
518
+ generateRoomCode() {
519
+ const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
520
+ let code = "";
521
+ for (let i = 0; i < 6; i++) {
522
+ code += chars[Math.floor(Math.random() * chars.length)];
523
+ }
524
+ return code;
525
+ }
526
+ getHeaders() {
527
+ const headers = {
528
+ "Content-Type": "application/json",
529
+ "X-Player-ID": this.config.playerId,
530
+ "X-Game-ID": this.config.gameId
531
+ };
532
+ if (this.config.apiKey) {
533
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
534
+ }
535
+ return headers;
536
+ }
537
+ };
259
538
  var Watchtower = class {
260
539
  constructor(config) {
261
540
  Object.defineProperty(this, "config", {
@@ -432,10 +711,44 @@ var Watchtower = class {
432
711
  get stats() {
433
712
  return this.getStats();
434
713
  }
714
+ // ============ SYNC API ============
715
+ /**
716
+ * Create a synchronized state object
717
+ *
718
+ * Point this at your game state and it becomes multiplayer.
719
+ * No events, no callbacks - just read and write your state.
720
+ *
721
+ * @param state - Your game state object (e.g., { players: {} })
722
+ * @param options - Sync options (tickRate, interpolation)
723
+ * @returns A Sync instance
724
+ *
725
+ * @example
726
+ * ```ts
727
+ * const state = { players: {} }
728
+ * const sync = wt.sync(state)
729
+ *
730
+ * await sync.join('my-room')
731
+ *
732
+ * // Add yourself
733
+ * state.players[sync.myId] = { x: 0, y: 0 }
734
+ *
735
+ * // Move (automatically syncs to others)
736
+ * state.players[sync.myId].x = 100
737
+ *
738
+ * // Others appear automatically in state.players!
739
+ * for (const [id, player] of Object.entries(state.players)) {
740
+ * draw(player.x, player.y)
741
+ * }
742
+ * ```
743
+ */
744
+ sync(state, options) {
745
+ return new Sync(state, this.config, options);
746
+ }
435
747
  };
436
748
  var index_default = Watchtower;
437
749
  export {
438
750
  Room,
751
+ Sync,
439
752
  Watchtower,
440
753
  index_default as default
441
754
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@watchtower-sdk/core",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Simple game backend SDK - saves, multiplayer rooms, and more",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",