@air-jam/sdk 0.1.1 → 0.1.2

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.js CHANGED
@@ -1,5 +1,5 @@
1
- import { roomCodeSchema, controllerSystemSchema, controllerStateSchema, controllerInputSchema, controllerJoinSchema, hostRegistrationSchema } from './chunk-7M5D3Y3L.js';
2
- export { AIRJAM_PROXY_PREFIX, ErrorCode, controllerInputSchema, controllerJoinSchema, controllerLeaveSchema, controllerStateSchema, controllerSystemSchema, hostJoinAsChildSchema, hostRegisterSystemSchema, hostRegistrationSchema, roomCodeSchema, systemLaunchGameSchema } from './chunk-7M5D3Y3L.js';
1
+ import { roomCodeSchema, controllerSystemSchema, controllerStateSchema, controllerInputSchema, controllerJoinSchema, hostReconnectSchema, hostCreateRoomSchema } from './chunk-B5DURUWT.js';
2
+ export { AIRJAM_PROXY_PREFIX, ErrorCode, controllerInputSchema, controllerJoinSchema, controllerLeaveSchema, controllerStateSchema, controllerSystemSchema, hostCreateRoomSchema, hostJoinAsChildSchema, hostReconnectSchema, hostRegisterSystemSchema, hostRegistrationSchema, roomCodeSchema, systemLaunchGameSchema } from './chunk-B5DURUWT.js';
3
3
  import * as React from 'react';
4
4
  import { createContext, useMemo, useEffect, useCallback, useContext, useRef, useState } from 'react';
5
5
  import { create, useStore } from 'zustand';
@@ -20,7 +20,7 @@ import { Html5Qrcode } from 'html5-qrcode';
20
20
 
21
21
  // src/constants.ts
22
22
  var DEFAULT_SERVER_PORT = 4e3;
23
- var DEFAULT_CONTROLLER_PATH = "/joypad";
23
+ var CONTROLLER_PATH = "/controller";
24
24
  var INPUT_DEBOUNCE_MS = 200;
25
25
  var TOGGLE_DEBOUNCE_MS = 300;
26
26
  var SOCKET_CONFIG = {
@@ -34,26 +34,21 @@ var SOCKET_CONFIG = {
34
34
  PING_TIMEOUT: 5e3
35
35
  };
36
36
  var DEFAULT_MAX_PLAYERS = 8;
37
-
38
- // src/internal/input-manager.ts
39
37
  var InputManager = class {
40
38
  inputBuffer = /* @__PURE__ */ new Map();
41
39
  latchState = /* @__PURE__ */ new Map();
42
40
  config;
43
- roomId;
44
- constructor(config = {}, roomId) {
41
+ constructor(config = {}) {
45
42
  this.config = config;
46
- this.roomId = roomId;
47
43
  }
48
44
  /**
49
45
  * Handles incoming input events from the socket.
50
46
  * Should be called when 'server:input' event is received.
51
47
  */
52
48
  handleInput(payload) {
53
- if (this.roomId && payload.roomId !== this.roomId) {
54
- return;
55
- }
56
49
  this.inputBuffer.set(payload.controllerId, payload.input);
50
+ const input = payload?.input;
51
+ input && (input.action === true || typeof input.vector === "object" && input.vector !== null && (Math.abs(input.vector.x ?? 0) > 0.01 || Math.abs(input.vector.y ?? 0) > 0.01));
57
52
  }
58
53
  /**
59
54
  * Gets input for a specific controller.
@@ -92,12 +87,6 @@ var InputManager = class {
92
87
  this.inputBuffer.delete(controllerId);
93
88
  this.latchState.delete(controllerId);
94
89
  }
95
- /**
96
- * Updates the room ID filter.
97
- */
98
- setRoomId(roomId) {
99
- this.roomId = roomId;
100
- }
101
90
  /**
102
91
  * Internal method to apply latching logic.
103
92
  */
@@ -321,7 +310,6 @@ var AirJamProvider = ({
321
310
  children,
322
311
  serverUrl,
323
312
  apiKey,
324
- controllerPath = DEFAULT_CONTROLLER_PATH,
325
313
  maxPlayers = DEFAULT_MAX_PLAYERS,
326
314
  publicHost,
327
315
  input
@@ -330,11 +318,10 @@ var AirJamProvider = ({
330
318
  () => ({
331
319
  serverUrl: serverUrl ?? getEnvServerUrl(),
332
320
  apiKey: apiKey ?? getEnvApiKey(),
333
- controllerPath,
334
321
  maxPlayers,
335
322
  publicHost
336
323
  }),
337
- [serverUrl, apiKey, controllerPath, maxPlayers, publicHost]
324
+ [serverUrl, apiKey, maxPlayers, publicHost]
338
325
  );
339
326
  const inputManager = useMemo(() => {
340
327
  if (!input) {
@@ -451,6 +438,22 @@ var useVolumeStore = create((set, get) => ({
451
438
  return masterVolume * categoryVolume;
452
439
  }
453
440
  }));
441
+ var setupParentSettingsListener = () => {
442
+ if (typeof window === "undefined") return;
443
+ const isInIframe = window.parent !== window;
444
+ if (!isInIframe) return;
445
+ const handleMessage = (event) => {
446
+ if (event.source !== window.parent) return;
447
+ if (event.data?.type !== "AIRJAM_SETTINGS_SYNC") return;
448
+ const { masterVolume, musicVolume, sfxVolume } = event.data.payload;
449
+ const store = useVolumeStore.getState();
450
+ if (typeof masterVolume === "number") store.setMasterVolume(masterVolume);
451
+ if (typeof musicVolume === "number") store.setMusicVolume(musicVolume);
452
+ if (typeof sfxVolume === "number") store.setSfxVolume(sfxVolume);
453
+ };
454
+ window.addEventListener("message", handleMessage);
455
+ };
456
+ setupParentSettingsListener();
454
457
 
455
458
  // src/audio/audio-manager.ts
456
459
  function detectSoundCategory(config) {
@@ -519,7 +522,12 @@ var AudioManager = class {
519
522
  if (roomId) this.roomId = roomId;
520
523
  }
521
524
  /**
522
- * Initialize audio context (must be called on user interaction)
525
+ * Resume audio context if suspended. This is automatically called by play(),
526
+ * so you typically don't need to call this manually.
527
+ *
528
+ * Note: Due to browser autoplay policies, audio context starts suspended
529
+ * and can only be resumed in response to a user gesture. The useAudio hook
530
+ * handles this automatically, and play() also calls init() internally.
523
531
  */
524
532
  init() {
525
533
  if (Howler.ctx && Howler.ctx.state === "suspended") {
@@ -563,6 +571,7 @@ var AudioManager = class {
563
571
  sprite,
564
572
  pitch
565
573
  } = options || {};
574
+ this.init();
566
575
  if (remote) {
567
576
  this.playRemote(id, target, volume, loop);
568
577
  return null;
@@ -620,6 +629,7 @@ var AudioManager = class {
620
629
  * Play a sound at a specific 3D position
621
630
  */
622
631
  playSpatial(id, pos, sprite) {
632
+ this.init();
623
633
  const soundId = this.playLocal(id, void 0, void 0, sprite);
624
634
  if (soundId !== null) {
625
635
  const sound = this.sounds.get(id);
@@ -991,29 +1001,6 @@ var AirJamDebug = ({
991
1001
  ] });
992
1002
  };
993
1003
 
994
- // src/utils/ids.ts
995
- var alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
996
- var generateRoomCode = () => {
997
- const array = new Uint32Array(4);
998
- if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
999
- crypto.getRandomValues(array);
1000
- } else {
1001
- for (let i = 0; i < array.length; i += 1) {
1002
- array[i] = Math.floor(Math.random() * alphabet.length);
1003
- }
1004
- }
1005
- const code = Array.from(
1006
- array,
1007
- (value) => alphabet[value % alphabet.length]
1008
- ).join("");
1009
- return roomCodeSchema.parse(code);
1010
- };
1011
- var generateControllerId = () => {
1012
- const stamp = Math.floor(Date.now() % 1e5).toString().padStart(5, "0");
1013
- const random = alphabet[Math.floor(Math.random() * alphabet.length)];
1014
- return `C${random}${stamp}`;
1015
- };
1016
-
1017
1004
  // src/utils/mode.ts
1018
1005
  var detectRunMode = () => {
1019
1006
  if (typeof window === "undefined") {
@@ -1177,10 +1164,11 @@ var UrlBuilder = class {
1177
1164
  }
1178
1165
  /**
1179
1166
  * Build a controller URL with room code.
1167
+ * Controller is always at {baseUrl}/controller (standardized convention).
1180
1168
  * Automatically uses local IP when running on localhost.
1181
1169
  */
1182
1170
  async buildControllerUrl(roomId, options) {
1183
- const path = options?.path || DEFAULT_CONTROLLER_PATH;
1171
+ const path = CONTROLLER_PATH;
1184
1172
  if (options?.host) {
1185
1173
  const url2 = new URL(path, this.normalizeOrigin(options.host));
1186
1174
  url2.searchParams.set("room", roomId);
@@ -1255,11 +1243,14 @@ var useAirJamHost = (options = {}) => {
1255
1243
  }, []);
1256
1244
  const isChildMode = !!arcadeParams;
1257
1245
  const shouldConnect = true;
1258
- const [fallbackRoomId] = useState(() => generateRoomCode());
1246
+ const storeRoomId = useStore(store, (s) => s.roomId);
1259
1247
  const parsedRoomId = useMemo(() => {
1260
1248
  if (arcadeParams) {
1261
1249
  return roomCodeSchema.parse(arcadeParams.room.toUpperCase());
1262
1250
  }
1251
+ if (storeRoomId) {
1252
+ return roomCodeSchema.parse(storeRoomId.toUpperCase());
1253
+ }
1263
1254
  if (typeof window !== "undefined") {
1264
1255
  const params = new URLSearchParams(window.location.search);
1265
1256
  const paramRoom = params.get("room");
@@ -1271,13 +1262,8 @@ var useAirJamHost = (options = {}) => {
1271
1262
  if (options.roomId) {
1272
1263
  return roomCodeSchema.parse(options.roomId.toUpperCase());
1273
1264
  }
1274
- return fallbackRoomId;
1275
- }, [options.roomId, fallbackRoomId, arcadeParams]);
1276
- useEffect(() => {
1277
- if (inputManager) {
1278
- inputManager.setRoomId(parsedRoomId);
1279
- }
1280
- }, [inputManager, parsedRoomId]);
1265
+ return null;
1266
+ }, [options.roomId, storeRoomId, arcadeParams]);
1281
1267
  const [joinUrl, setJoinUrl] = useState("");
1282
1268
  const onPlayerJoinRef = useRef(options.onPlayerJoin);
1283
1269
  const onPlayerLeaveRef = useRef(options.onPlayerLeave);
@@ -1294,7 +1280,8 @@ var useAirJamHost = (options = {}) => {
1294
1280
  lastError: state.lastError,
1295
1281
  players: state.players,
1296
1282
  gameState: state.gameState,
1297
- mode: state.mode
1283
+ mode: state.mode,
1284
+ roomId: state.roomId
1298
1285
  }))
1299
1286
  );
1300
1287
  const socket = useMemo(
@@ -1311,6 +1298,7 @@ var useAirJamHost = (options = {}) => {
1311
1298
  if (!socket || !socket.connected) {
1312
1299
  return;
1313
1300
  }
1301
+ if (!parsedRoomId) return;
1314
1302
  const payload = controllerSystemSchema.safeParse({
1315
1303
  roomId: parsedRoomId,
1316
1304
  command: "toggle_pause"
@@ -1321,7 +1309,7 @@ var useAirJamHost = (options = {}) => {
1321
1309
  }, [socket, parsedRoomId, lastToggle]);
1322
1310
  const sendState = useCallback(
1323
1311
  (state) => {
1324
- if (!socket || !socket.connected) {
1312
+ if (!socket || !socket.connected || !parsedRoomId) {
1325
1313
  return false;
1326
1314
  }
1327
1315
  const payload = controllerStateSchema.safeParse({
@@ -1357,20 +1345,22 @@ var useAirJamHost = (options = {}) => {
1357
1345
  }
1358
1346
  }, [socket, disconnectSocket]);
1359
1347
  useEffect(() => {
1348
+ if (!parsedRoomId) return;
1360
1349
  (async () => {
1361
1350
  const url = await urlBuilder.buildControllerUrl(parsedRoomId, {
1362
- path: config.controllerPath,
1363
1351
  host: config.publicHost
1364
1352
  });
1365
1353
  setJoinUrl(url);
1366
1354
  })();
1367
- }, [parsedRoomId, config.controllerPath, config.publicHost]);
1355
+ }, [parsedRoomId, config.publicHost, options.roomId]);
1368
1356
  const setRegisteredRoomId = useStore(store, (s) => s.setRegisteredRoomId);
1369
1357
  useEffect(() => {
1370
1358
  const storeState = store.getState();
1371
1359
  storeState.setMode(detectRunMode());
1372
1360
  storeState.setRole("host");
1373
- storeState.setRoomId(parsedRoomId);
1361
+ if (parsedRoomId) {
1362
+ storeState.setRoomId(parsedRoomId);
1363
+ }
1374
1364
  storeState.setStatus("connecting");
1375
1365
  storeState.setError(void 0);
1376
1366
  if (!socket) {
@@ -1380,7 +1370,7 @@ var useAirJamHost = (options = {}) => {
1380
1370
  const registerHost = async () => {
1381
1371
  const storeState2 = store.getState();
1382
1372
  const currentRegisteredRoomId2 = store.getState().registeredRoomId;
1383
- if (currentRegisteredRoomId2 === parsedRoomId && socket.connected) {
1373
+ if (currentRegisteredRoomId2 && socket.connected) {
1384
1374
  return;
1385
1375
  }
1386
1376
  if (arcadeParams) {
@@ -1403,26 +1393,56 @@ var useAirJamHost = (options = {}) => {
1403
1393
  setRegisteredRoomId(childRoomId);
1404
1394
  });
1405
1395
  } else {
1406
- const payload = hostRegistrationSchema.parse({
1407
- roomId: parsedRoomId,
1408
- maxPlayers: options.maxPlayers ?? config.maxPlayers,
1409
- apiKey: options.apiKey ?? config.apiKey
1410
- });
1411
- socket.emit("host:register", payload, (ack) => {
1412
- if (!ack.ok) {
1413
- storeState2.setError(ack.message ?? "Failed to register host");
1414
- storeState2.setStatus("disconnected");
1415
- setRegisteredRoomId(null);
1416
- return;
1417
- }
1418
- storeState2.setStatus("connected");
1419
- if (ack.roomId) {
1420
- storeState2.setRoomId(ack.roomId);
1421
- setRegisteredRoomId(ack.roomId);
1396
+ const createNewRoom = () => {
1397
+ const payload = hostCreateRoomSchema.parse({
1398
+ maxPlayers: options.maxPlayers ?? config.maxPlayers,
1399
+ apiKey: options.apiKey ?? config.apiKey
1400
+ });
1401
+ socket.emit("host:createRoom", payload, (ack) => {
1402
+ if (!ack.ok) {
1403
+ storeState2.setError(ack.message ?? "Failed to create room");
1404
+ storeState2.setStatus("disconnected");
1405
+ setRegisteredRoomId(null);
1406
+ return;
1407
+ }
1408
+ if (ack.roomId) {
1409
+ storeState2.setStatus("connected");
1410
+ storeState2.setRoomId(ack.roomId);
1411
+ setRegisteredRoomId(ack.roomId);
1412
+ if (typeof window !== "undefined") {
1413
+ sessionStorage.setItem("airjam_room_id", ack.roomId);
1414
+ }
1415
+ } else {
1416
+ storeState2.setError("Server did not return room ID");
1417
+ storeState2.setStatus("disconnected");
1418
+ }
1419
+ });
1420
+ };
1421
+ if (typeof window !== "undefined") {
1422
+ const savedRoomId = sessionStorage.getItem("airjam_room_id");
1423
+ if (savedRoomId) {
1424
+ const reconnectPayload = hostReconnectSchema.parse({
1425
+ roomId: savedRoomId,
1426
+ apiKey: options.apiKey ?? config.apiKey
1427
+ });
1428
+ socket.emit("host:reconnect", reconnectPayload, (ack) => {
1429
+ if (ack.ok && ack.roomId) {
1430
+ storeState2.setStatus("connected");
1431
+ storeState2.setRoomId(ack.roomId);
1432
+ setRegisteredRoomId(ack.roomId);
1433
+ } else {
1434
+ if (typeof window !== "undefined") {
1435
+ sessionStorage.removeItem("airjam_room_id");
1436
+ }
1437
+ createNewRoom();
1438
+ }
1439
+ });
1422
1440
  } else {
1423
- setRegisteredRoomId(parsedRoomId);
1441
+ createNewRoom();
1424
1442
  }
1425
- });
1443
+ } else {
1444
+ createNewRoom();
1445
+ }
1426
1446
  }
1427
1447
  };
1428
1448
  const handleConnect = () => {
@@ -1453,7 +1473,7 @@ var useAirJamHost = (options = {}) => {
1453
1473
  onChildCloseRef.current?.();
1454
1474
  };
1455
1475
  const handleState = (payload) => {
1456
- if (payload.roomId !== parsedRoomId) return;
1476
+ if (!parsedRoomId || payload.roomId !== parsedRoomId) return;
1457
1477
  const storeState2 = store.getState();
1458
1478
  if (payload.state.gameState) {
1459
1479
  storeState2.setGameState(payload.state.gameState);
@@ -1475,12 +1495,9 @@ var useAirJamHost = (options = {}) => {
1475
1495
  socket.on("server:state", handleState);
1476
1496
  socket.connect();
1477
1497
  const currentRegisteredRoomId = store.getState().registeredRoomId;
1478
- if (socket.connected && currentRegisteredRoomId !== parsedRoomId) {
1498
+ if (socket.connected && !currentRegisteredRoomId) {
1479
1499
  registerHost();
1480
1500
  }
1481
- if (currentRegisteredRoomId && currentRegisteredRoomId !== parsedRoomId) {
1482
- setRegisteredRoomId(null);
1483
- }
1484
1501
  return () => {
1485
1502
  socket.off("connect", handleConnect);
1486
1503
  socket.off("disconnect", handleDisconnect);
@@ -1496,8 +1513,9 @@ var useAirJamHost = (options = {}) => {
1496
1513
  config.apiKey,
1497
1514
  options.maxPlayers,
1498
1515
  options.apiKey,
1499
- parsedRoomId,
1500
1516
  arcadeParams,
1517
+ parsedRoomId,
1518
+ // Include parsedRoomId since it's used in handleState callback
1501
1519
  shouldConnect,
1502
1520
  socket,
1503
1521
  store,
@@ -1515,7 +1533,8 @@ var useAirJamHost = (options = {}) => {
1515
1533
  [inputManager]
1516
1534
  );
1517
1535
  return {
1518
- roomId: parsedRoomId,
1536
+ roomId: parsedRoomId ?? "",
1537
+ // Return empty string as fallback if not yet available
1519
1538
  joinUrl,
1520
1539
  connectionStatus: connectionState.connectionStatus,
1521
1540
  players: connectionState.players,
@@ -2179,7 +2198,7 @@ var AirJamOverlay = () => {
2179
2198
  size: "lg",
2180
2199
  children: [
2181
2200
  /* @__PURE__ */ jsx(Play, { className: "mr-2 h-5 w-5" }),
2182
- "Start Game"
2201
+ "Play"
2183
2202
  ]
2184
2203
  }
2185
2204
  ) })
@@ -2653,7 +2672,7 @@ var describeStatus = (status) => {
2653
2672
  }
2654
2673
  };
2655
2674
  var orientationMatches = (required) => {
2656
- if (required === "any") return true;
2675
+ if (!required) return true;
2657
2676
  if (typeof window === "undefined" || !window.matchMedia) return true;
2658
2677
  const matcher = window.matchMedia(`(orientation: ${required})`);
2659
2678
  return matcher.matches;
@@ -2661,7 +2680,7 @@ var orientationMatches = (required) => {
2661
2680
  var ControllerShell = ({
2662
2681
  roomId,
2663
2682
  connectionStatus,
2664
- requiredOrientation = "landscape",
2683
+ forceOrientation,
2665
2684
  children,
2666
2685
  gameState = "paused",
2667
2686
  onTogglePlayPause,
@@ -2671,7 +2690,7 @@ var ControllerShell = ({
2671
2690
  }) => {
2672
2691
  const isChildMode = useMemo(() => detectRunMode() === "platform", []);
2673
2692
  const [isOrientationOk, setOrientationOk] = useState(
2674
- () => orientationMatches(requiredOrientation)
2693
+ () => orientationMatches(forceOrientation)
2675
2694
  );
2676
2695
  const [isScannerOpen, setIsScannerOpen] = useState(false);
2677
2696
  const { isFullscreen, toggleFullscreen } = useFullscreen();
@@ -2692,16 +2711,17 @@ var ControllerShell = ({
2692
2711
  return found || null;
2693
2712
  }, [controllerId, players, connectionStatus]);
2694
2713
  useEffect(() => {
2695
- if (requiredOrientation === "any") {
2714
+ if (!forceOrientation) {
2715
+ setOrientationOk(true);
2696
2716
  return;
2697
2717
  }
2698
- const media = window.matchMedia(`(orientation: ${requiredOrientation})`);
2718
+ const media = window.matchMedia(`(orientation: ${forceOrientation})`);
2699
2719
  const handleChange = () => setOrientationOk(media.matches);
2700
2720
  handleChange();
2701
2721
  media.addEventListener("change", handleChange);
2702
2722
  return () => media.removeEventListener("change", handleChange);
2703
- }, [requiredOrientation]);
2704
- const orientationOk = requiredOrientation === "any" ? true : isOrientationOk;
2723
+ }, [forceOrientation]);
2724
+ const orientationOk = !forceOrientation ? true : isOrientationOk;
2705
2725
  const statusDotColor = useMemo(() => {
2706
2726
  switch (connectionStatus) {
2707
2727
  case "connected":
@@ -2720,7 +2740,7 @@ var ControllerShell = ({
2720
2740
  /* @__PURE__ */ jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2721
2741
  /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2722
2742
  "This game is best experienced in ",
2723
- requiredOrientation,
2743
+ forceOrientation,
2724
2744
  " ",
2725
2745
  "orientation."
2726
2746
  ] })
@@ -2740,36 +2760,43 @@ var ControllerShell = ({
2740
2760
  return /* @__PURE__ */ jsx("div", { className: "dark", children: /* @__PURE__ */ jsxs("div", { className: "bg-background text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden select-none", children: [
2741
2761
  /* @__PURE__ */ jsxs("header", { className: "pointer-events-none sticky top-0 z-50 flex items-center justify-between border-b px-6 py-2", children: [
2742
2762
  /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2743
- typeof window !== "undefined" && (currentPlayer || controllerId) && /* @__PURE__ */ jsxs("div", { className: "relative", title: describeStatus(connectionStatus), children: [
2744
- currentPlayer ? /* @__PURE__ */ jsx(PlayerAvatar, { player: currentPlayer, size: "sm" }) : controllerId ? /* @__PURE__ */ jsx(
2745
- PlayerAvatar,
2746
- {
2747
- player: {
2748
- id: controllerId,
2749
- label: "Player"
2750
- },
2751
- size: "sm"
2752
- }
2753
- ) : null,
2754
- /* @__PURE__ */ jsx(
2755
- "span",
2756
- {
2757
- className: "absolute right-0 bottom-0 h-3 w-3 rounded-full bg-black",
2758
- "aria-hidden": "true"
2759
- }
2760
- ),
2761
- /* @__PURE__ */ jsx(
2762
- "span",
2763
- {
2764
- className: cn(
2765
- "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
2766
- statusDotColor,
2767
- connectionStatus === "connected" && "animate-pulse"
2763
+ typeof window !== "undefined" && (currentPlayer || controllerId) && /* @__PURE__ */ jsxs(
2764
+ "div",
2765
+ {
2766
+ className: "relative",
2767
+ title: describeStatus(connectionStatus),
2768
+ children: [
2769
+ currentPlayer ? /* @__PURE__ */ jsx(PlayerAvatar, { player: currentPlayer, size: "sm" }) : controllerId ? /* @__PURE__ */ jsx(
2770
+ PlayerAvatar,
2771
+ {
2772
+ player: {
2773
+ id: controllerId,
2774
+ label: "Player"
2775
+ },
2776
+ size: "sm"
2777
+ }
2778
+ ) : null,
2779
+ /* @__PURE__ */ jsx(
2780
+ "span",
2781
+ {
2782
+ className: "absolute right-0 bottom-0 h-3 w-3 rounded-full bg-black",
2783
+ "aria-hidden": "true"
2784
+ }
2768
2785
  ),
2769
- "aria-label": describeStatus(connectionStatus)
2770
- }
2771
- )
2772
- ] }),
2786
+ /* @__PURE__ */ jsx(
2787
+ "span",
2788
+ {
2789
+ className: cn(
2790
+ "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
2791
+ statusDotColor,
2792
+ connectionStatus === "connected" && "animate-pulse"
2793
+ ),
2794
+ "aria-label": describeStatus(connectionStatus)
2795
+ }
2796
+ )
2797
+ ]
2798
+ }
2799
+ ),
2773
2800
  /* @__PURE__ */ jsxs("div", { children: [
2774
2801
  /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs tracking-[0.24em] uppercase", children: "Room" }),
2775
2802
  /* @__PURE__ */ jsx("p", { className: "text-foreground text-lg font-semibold", children: typeof window !== "undefined" ? roomId ?? "N/A" : "N/A" })
@@ -2836,13 +2863,12 @@ var ControllerShell = ({
2836
2863
  )
2837
2864
  ] })
2838
2865
  ] }),
2839
- /* @__PURE__ */ jsx("div", { className: "pointer-events-none fixed right-4 bottom-4 z-50", children: /* @__PURE__ */ jsx("div", { className: "pointer-events-auto", children: /* @__PURE__ */ jsx(VolumeControls, { compact: true }) }) }),
2840
2866
  /* @__PURE__ */ jsx("main", { className: "relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4", children: /* @__PURE__ */ jsxs("div", { className: "bg-card/95 absolute inset-0 z-10 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm", children: [
2841
- !orientationOk && /* @__PURE__ */ jsxs("div", { className: "bg-background/95 absolute inset-0 z-10 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm", children: [
2867
+ !orientationOk && forceOrientation && /* @__PURE__ */ jsxs("div", { className: "bg-background/95 absolute inset-0 z-10 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm", children: [
2842
2868
  /* @__PURE__ */ jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2843
2869
  /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2844
2870
  "This game is best experienced in ",
2845
- requiredOrientation,
2871
+ forceOrientation,
2846
2872
  " ",
2847
2873
  "orientation."
2848
2874
  ] })
@@ -2978,6 +3004,31 @@ var Events = {
2978
3004
  Client: ClientEvents,
2979
3005
  Child: ChildEvents
2980
3006
  };
3007
+
3008
+ // src/utils/ids.ts
3009
+ var alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
3010
+ var generateRoomCode = () => {
3011
+ const array = new Uint32Array(4);
3012
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
3013
+ crypto.getRandomValues(array);
3014
+ } else {
3015
+ for (let i = 0; i < array.length; i += 1) {
3016
+ array[i] = Math.floor(Math.random() * alphabet.length);
3017
+ }
3018
+ }
3019
+ const code = Array.from(
3020
+ array,
3021
+ (value) => alphabet[value % alphabet.length]
3022
+ ).join("");
3023
+ return roomCodeSchema.parse(code);
3024
+ };
3025
+ var generateControllerId = () => {
3026
+ const stamp = Math.floor(Date.now() % 1e5).toString().padStart(5, "0");
3027
+ const random = alphabet[Math.floor(Math.random() * alphabet.length)];
3028
+ return `C${random}${stamp}`;
3029
+ };
3030
+
3031
+ // src/hooks/use-air-jam-controller.ts
2981
3032
  var getRoomFromLocation = () => {
2982
3033
  if (typeof window === "undefined") {
2983
3034
  return null;
@@ -3486,6 +3537,7 @@ var useAirJamShell = (options = {}) => {
3486
3537
  const sendInput = useCallback(
3487
3538
  (input) => {
3488
3539
  const storeState = store.getState();
3540
+ input.action === true || typeof input.vector === "object" && input.vector !== null && (Math.abs(input.vector.x ?? 0) > 0.01 || Math.abs(input.vector.y ?? 0) > 0.01);
3489
3541
  if (!parsedRoomId || !storeState.controllerId || !socket) {
3490
3542
  storeState.setError("Not connected to a room");
3491
3543
  return false;
@@ -3582,6 +3634,7 @@ function createAirJamStore2(initializer) {
3582
3634
  }
3583
3635
  };
3584
3636
  });
3637
+ const gameUiUnloadedRef = { current: false };
3585
3638
  const useSyncedStore = (selector = (s) => s) => {
3586
3639
  const slice = store(selector);
3587
3640
  const { getSocket } = useAirJamContext();
@@ -3589,6 +3642,10 @@ function createAirJamStore2(initializer) {
3589
3642
  const roomId = useAirJamState((state) => state.roomId);
3590
3643
  const controllerId = useAirJamState((state) => state.controllerId);
3591
3644
  const socket = role === "host" ? getSocket("host") : getSocket("controller");
3645
+ const socketRef = useRef(socket);
3646
+ useEffect(() => {
3647
+ socketRef.current = socket;
3648
+ }, [socket]);
3592
3649
  useEffect(() => {
3593
3650
  if (!socket || !roomId || !role) {
3594
3651
  return;
@@ -3612,6 +3669,7 @@ function createAirJamStore2(initializer) {
3612
3669
  };
3613
3670
  }
3614
3671
  if (role === "controller") {
3672
+ gameUiUnloadedRef.current = false;
3615
3673
  const handleSync = (payload) => {
3616
3674
  const { data } = payload;
3617
3675
  const currentState = store.getState();
@@ -3623,9 +3681,27 @@ function createAirJamStore2(initializer) {
3623
3681
  }
3624
3682
  };
3625
3683
  socket.on("airjam:state_sync", handleSync);
3626
- return () => socket.off("airjam:state_sync", handleSync);
3684
+ const handleUnloadUi = () => {
3685
+ gameUiUnloadedRef.current = true;
3686
+ socket.off("airjam:state_sync", handleSync);
3687
+ };
3688
+ const handleLoadUi = () => {
3689
+ gameUiUnloadedRef.current = false;
3690
+ };
3691
+ socket.on("client:loadUi", handleLoadUi);
3692
+ const handleDisconnect = () => {
3693
+ gameUiUnloadedRef.current = true;
3694
+ };
3695
+ socket.on("disconnect", handleDisconnect);
3696
+ socket.on("client:unloadUi", handleUnloadUi);
3697
+ return () => {
3698
+ socket.off("airjam:state_sync", handleSync);
3699
+ socket.off("client:loadUi", handleLoadUi);
3700
+ socket.off("client:unloadUi", handleUnloadUi);
3701
+ socket.off("disconnect", handleDisconnect);
3702
+ };
3627
3703
  }
3628
- }, [socket, role, roomId]);
3704
+ }, [socket, role, roomId, socket?.id]);
3629
3705
  if (role === "controller" && socket && roomId) {
3630
3706
  let originalActions = null;
3631
3707
  if (typeof slice === "object" && slice !== null && "actions" in slice) {
@@ -3646,13 +3722,26 @@ function createAirJamStore2(initializer) {
3646
3722
  const proxyActions = {};
3647
3723
  Object.keys(originalActions).forEach((key) => {
3648
3724
  proxyActions[key] = (...args) => {
3725
+ if (gameUiUnloadedRef.current) {
3726
+ console.warn(
3727
+ `[AirJamStore] Action "${key}" blocked: Game UI unloaded.`
3728
+ );
3729
+ return;
3730
+ }
3731
+ const activeSocket = socketRef.current;
3732
+ if (!activeSocket || !activeSocket.connected) {
3733
+ console.warn(
3734
+ `[AirJamStore] Action "${key}" blocked: Socket disconnected.`
3735
+ );
3736
+ return;
3737
+ }
3649
3738
  if (!controllerId) {
3650
3739
  console.warn(
3651
3740
  "[AirJamStore] Cannot send action RPC: controllerId not set"
3652
3741
  );
3653
3742
  return;
3654
3743
  }
3655
- socket.emit("controller:action_rpc", {
3744
+ activeSocket.emit("controller:action_rpc", {
3656
3745
  roomId,
3657
3746
  actionName: key,
3658
3747
  args,
@@ -3672,6 +3761,6 @@ function createAirJamStore2(initializer) {
3672
3761
  return useSyncedStore;
3673
3762
  }
3674
3763
 
3675
- export { AirJamContext, AirJamDebug, AirJamOverlay, AirJamProvider, AudioManager, AudioProvider, Button, ChildEvents, ClientEvents, ControllerEvents, ControllerShell, DEFAULT_CONTROLLER_PATH, DEFAULT_MAX_PLAYERS, DEFAULT_SERVER_PORT, DebugStateDialog, Events, HostEvents, INPUT_DEBOUNCE_MS, PlayerAvatar, SOCKET_CONFIG, ServerEvents, Slider, SocketManager, SystemEvents, TOGGLE_DEBOUNCE_MS, UrlBuilder, VolumeControls, buttonVariants, createAirJamStore2 as createAirJamStore, createAudioManager, detectSoundCategory, generateControllerId, generateRoomCode, getLocalNetworkIp, urlBuilder, useAirJamConfig, useAirJamContext, useAirJamController, useAirJamHost, useAirJamShell, useAirJamSocket, useAirJamState, useAudio, useAudioLegacy, useAudioManager, useGetInput, useSendSignal, useVolumeStore };
3764
+ export { AirJamContext, AirJamDebug, AirJamOverlay, AirJamProvider, AudioManager, AudioProvider, Button, CONTROLLER_PATH, ChildEvents, ClientEvents, ControllerEvents, ControllerShell, DEFAULT_MAX_PLAYERS, DEFAULT_SERVER_PORT, DebugStateDialog, Events, HostEvents, INPUT_DEBOUNCE_MS, PlayerAvatar, SOCKET_CONFIG, ServerEvents, Slider, SocketManager, SystemEvents, TOGGLE_DEBOUNCE_MS, UrlBuilder, VolumeControls, buttonVariants, createAirJamStore2 as createAirJamStore, createAudioManager, detectSoundCategory, generateControllerId, generateRoomCode, getLocalNetworkIp, urlBuilder, useAirJamConfig, useAirJamContext, useAirJamController, useAirJamHost, useAirJamShell, useAirJamSocket, useAirJamState, useAudio, useAudioLegacy, useAudioManager, useGetInput, useSendSignal, useVolumeStore };
3676
3765
  //# sourceMappingURL=index.js.map
3677
3766
  //# sourceMappingURL=index.js.map