@air-jam/sdk 0.1.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.
Files changed (56) hide show
  1. package/README.md +87 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/chunk-XSXI3RIS.js +72 -0
  4. package/dist/chunk-XSXI3RIS.js.map +1 -0
  5. package/dist/index.cjs +3514 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +1529 -0
  8. package/dist/index.d.ts +1529 -0
  9. package/dist/index.js +3366 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/protocol.cjs +85 -0
  12. package/dist/protocol.cjs.map +1 -0
  13. package/dist/protocol.d.cts +242 -0
  14. package/dist/protocol.d.ts +242 -0
  15. package/dist/protocol.js +3 -0
  16. package/dist/protocol.js.map +1 -0
  17. package/package.json +81 -0
  18. package/src/AirJamClient.ts +775 -0
  19. package/src/audio/audio-manager.ts +395 -0
  20. package/src/audio/hooks.tsx +140 -0
  21. package/src/audio/index.ts +3 -0
  22. package/src/audio/volume-store.ts +77 -0
  23. package/src/components/air-jam-overlay.tsx +456 -0
  24. package/src/components/controller-shell.tsx +329 -0
  25. package/src/components/qr-scanner-dialog.tsx +373 -0
  26. package/src/components/ui/alert.tsx +66 -0
  27. package/src/components/ui/avatar.tsx +46 -0
  28. package/src/components/ui/badge.tsx +47 -0
  29. package/src/components/ui/button.tsx +61 -0
  30. package/src/components/ui/card.tsx +92 -0
  31. package/src/components/ui/slider.tsx +61 -0
  32. package/src/components/ui/tabs.tsx +64 -0
  33. package/src/components/volume-controls.tsx +93 -0
  34. package/src/constants.ts +45 -0
  35. package/src/context/air-jam-context.tsx +478 -0
  36. package/src/context/index.ts +2 -0
  37. package/src/context/socket-manager.ts +98 -0
  38. package/src/events.ts +151 -0
  39. package/src/hooks/use-air-jam-controller.ts +608 -0
  40. package/src/hooks/use-air-jam-host.ts +624 -0
  41. package/src/hooks/use-air-jam-shell.ts +343 -0
  42. package/src/hooks/use-fullscreen.ts +108 -0
  43. package/src/hooks/use-get-input.ts +97 -0
  44. package/src/hooks/use-send-signal.ts +164 -0
  45. package/src/index.ts +33 -0
  46. package/src/internal/input-manager.ts +362 -0
  47. package/src/protocol.ts +331 -0
  48. package/src/state/connection-store.ts +84 -0
  49. package/src/styles.css +128 -0
  50. package/src/types/browser.ts +42 -0
  51. package/src/utils/cn.ts +4 -0
  52. package/src/utils/ids.ts +31 -0
  53. package/src/utils/index.ts +1 -0
  54. package/src/utils/mode.ts +13 -0
  55. package/src/utils/network-ip.ts +145 -0
  56. package/src/utils/url-builder.ts +170 -0
@@ -0,0 +1,478 @@
1
+ /* eslint-disable react-refresh/only-export-components */
2
+ /**
3
+ * @module AirJamContext
4
+ * @description Core context and provider for the AirJam SDK.
5
+ *
6
+ * The AirJamProvider is the root component that must wrap your application
7
+ * to enable AirJam functionality. It manages:
8
+ * - WebSocket connections to the AirJam server
9
+ * - Global state via Zustand store
10
+ * - Input validation and latching configuration
11
+ * - Environment variable resolution for server URLs and API keys
12
+ *
13
+ * @example Basic Setup
14
+ * ```tsx
15
+ * import { AirJamProvider } from "@air-jam/sdk";
16
+ *
17
+ * const App = () => (
18
+ * <AirJamProvider>
19
+ * <YourGame />
20
+ * </AirJamProvider>
21
+ * );
22
+ * ```
23
+ *
24
+ * @example With Input Configuration
25
+ * ```tsx
26
+ * import { AirJamProvider } from "@air-jam/sdk";
27
+ * import { z } from "zod";
28
+ *
29
+ * const inputSchema = z.object({
30
+ * vector: z.object({ x: z.number(), y: z.number() }),
31
+ * action: z.boolean(),
32
+ * });
33
+ *
34
+ * const App = () => (
35
+ * <AirJamProvider
36
+ * input={{
37
+ * schema: inputSchema,
38
+ * latch: { booleanFields: ["action"], vectorFields: ["vector"] },
39
+ * }}
40
+ * >
41
+ * <YourGame />
42
+ * </AirJamProvider>
43
+ * );
44
+ * ```
45
+ */
46
+ import {
47
+ createContext,
48
+ useCallback,
49
+ useContext,
50
+ useEffect,
51
+ useMemo,
52
+ type ReactNode,
53
+ } from "react";
54
+ import type { z } from "zod";
55
+ import { useStore } from "zustand";
56
+ import { useShallow } from "zustand/react/shallow";
57
+ import { DEFAULT_CONTROLLER_PATH, DEFAULT_MAX_PLAYERS } from "../constants";
58
+ import { InputManager, type InputConfig } from "../internal/input-manager";
59
+ import type { ConnectionRole } from "../protocol";
60
+ import { createAirJamStore, type AirJamStore } from "../state/connection-store";
61
+ import { SocketManager, type AirJamSocket } from "./socket-manager";
62
+
63
+ // ============================================================================
64
+ // Configuration Types
65
+ // ============================================================================
66
+
67
+ /**
68
+ * Resolved configuration for the AirJam SDK.
69
+ * Created from AirJamProviderProps with environment variable fallbacks applied.
70
+ */
71
+ export interface AirJamConfig {
72
+ /** WebSocket server URL. Falls back to env vars or window location */
73
+ serverUrl?: string;
74
+ /** API key for production authentication */
75
+ apiKey?: string;
76
+ /** Path for controller page (default: /joypad) */
77
+ controllerPath: string;
78
+ /** Maximum players allowed in a room */
79
+ maxPlayers: number;
80
+ /** Public host for controller URLs (optional) */
81
+ publicHost?: string;
82
+ }
83
+
84
+ /**
85
+ * Props for the AirJamProvider component.
86
+ *
87
+ * @template TSchema - Zod schema type for input validation (inferred from input.schema)
88
+ *
89
+ * @example Minimal configuration (uses environment variables)
90
+ * ```tsx
91
+ * <AirJamProvider>
92
+ * <App />
93
+ * </AirJamProvider>
94
+ * ```
95
+ *
96
+ * @example Full configuration
97
+ * ```tsx
98
+ * <AirJamProvider
99
+ * serverUrl="wss://your-server.com"
100
+ * apiKey="your-api-key"
101
+ * controllerPath="/controller"
102
+ * maxPlayers={4}
103
+ * input={{
104
+ * schema: myInputSchema,
105
+ * latch: { booleanFields: ["fire"], vectorFields: ["move"] },
106
+ * }}
107
+ * >
108
+ * <App />
109
+ * </AirJamProvider>
110
+ * ```
111
+ */
112
+ export interface AirJamProviderProps<
113
+ TSchema extends z.ZodSchema = z.ZodSchema,
114
+ > {
115
+ /** React children to render within the provider */
116
+ children: ReactNode;
117
+ /**
118
+ * WebSocket server URL for AirJam connections.
119
+ * Falls back to VITE_AIR_JAM_SERVER_URL or NEXT_PUBLIC_AIR_JAM_SERVER_URL environment variables.
120
+ */
121
+ serverUrl?: string;
122
+ /**
123
+ * API key for production authentication.
124
+ * Falls back to VITE_AIR_JAM_API_KEY or NEXT_PUBLIC_AIR_JAM_API_KEY environment variables.
125
+ */
126
+ apiKey?: string;
127
+ /**
128
+ * URL path for the controller page on your app.
129
+ * Controllers will be directed to this path with ?room=XXXX query parameter.
130
+ * @default "/joypad"
131
+ */
132
+ controllerPath?: string;
133
+ /**
134
+ * Maximum number of players allowed in a room.
135
+ * @default 8
136
+ */
137
+ maxPlayers?: number;
138
+ /**
139
+ * Public hostname for controller URLs.
140
+ * Useful when your app is behind a proxy or has a different public URL.
141
+ */
142
+ publicHost?: string;
143
+ /**
144
+ * Input handling configuration including Zod schema validation and latching.
145
+ * When provided, enables typed input with automatic validation and latch support.
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * input={{
150
+ * schema: z.object({
151
+ * vector: z.object({ x: z.number(), y: z.number() }),
152
+ * action: z.boolean(),
153
+ * ability: z.boolean(),
154
+ * }),
155
+ * latch: {
156
+ * booleanFields: ["action", "ability"], // Latch button presses
157
+ * vectorFields: ["vector"], // Latch stick flicks
158
+ * },
159
+ * }}
160
+ * ```
161
+ */
162
+ input?: InputConfig<TSchema>;
163
+ }
164
+
165
+ // ============================================================================
166
+ // Context Value
167
+ // ============================================================================
168
+
169
+ export interface AirJamContextValue {
170
+ /** Resolved configuration with env fallbacks */
171
+ config: AirJamConfig;
172
+ /** Context-bound Zustand store */
173
+ store: ReturnType<typeof createAirJamStore>;
174
+ /** Socket manager for this provider instance */
175
+ socketManager: SocketManager;
176
+ /** Get socket for a specific role */
177
+ getSocket: (role: ConnectionRole) => AirJamSocket;
178
+ /** Disconnect socket for a specific role */
179
+ disconnectSocket: (role: ConnectionRole) => void;
180
+ /** InputManager instance (created from input config if provided) */
181
+ inputManager: InputManager | null;
182
+ }
183
+
184
+ const AirJamContext = createContext<AirJamContextValue | null>(null);
185
+
186
+ // ============================================================================
187
+ // Environment Variable Resolution
188
+ // ============================================================================
189
+
190
+ // Type-safe access to import.meta.env (Vite)
191
+ interface ImportMetaEnv {
192
+ VITE_AIR_JAM_SERVER_URL?: string;
193
+ VITE_AIR_JAM_API_KEY?: string;
194
+ }
195
+
196
+ const getViteEnv = (): ImportMetaEnv | undefined => {
197
+ try {
198
+ // Access import.meta.env dynamically to avoid TS errors
199
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
200
+ const meta = import.meta as any;
201
+ if (meta && typeof meta.env === "object") {
202
+ return meta.env as ImportMetaEnv;
203
+ }
204
+ } catch {
205
+ // import.meta not available
206
+ }
207
+ return undefined;
208
+ };
209
+
210
+ /**
211
+ * Attempts to read server URL from various environment variable formats
212
+ */
213
+ const getEnvServerUrl = (): string | undefined => {
214
+ // Vite
215
+ const viteEnv = getViteEnv();
216
+ if (viteEnv?.VITE_AIR_JAM_SERVER_URL) {
217
+ return viteEnv.VITE_AIR_JAM_SERVER_URL;
218
+ }
219
+
220
+ // Next.js / Node
221
+ if (typeof process !== "undefined" && process.env) {
222
+ const nextUrl = process.env.NEXT_PUBLIC_AIR_JAM_SERVER_URL;
223
+ if (nextUrl) return nextUrl;
224
+ }
225
+
226
+ return undefined;
227
+ };
228
+
229
+ /**
230
+ * Attempts to read API key from various environment variable formats
231
+ */
232
+ const getEnvApiKey = (): string | undefined => {
233
+ // Vite
234
+ const viteEnv = getViteEnv();
235
+ if (viteEnv?.VITE_AIR_JAM_API_KEY) {
236
+ return viteEnv.VITE_AIR_JAM_API_KEY;
237
+ }
238
+
239
+ // Next.js / Node
240
+ if (typeof process !== "undefined" && process.env) {
241
+ const nextKey = process.env.NEXT_PUBLIC_AIR_JAM_API_KEY;
242
+ if (nextKey) return nextKey;
243
+ }
244
+
245
+ return undefined;
246
+ };
247
+
248
+ // ============================================================================
249
+ // Provider Component
250
+ // ============================================================================
251
+
252
+ /**
253
+ * Root provider component for the AirJam SDK.
254
+ *
255
+ * Wrap your application (or game component tree) with this provider to enable
256
+ * AirJam functionality. The provider manages WebSocket connections, global state,
257
+ * and input processing.
258
+ *
259
+ * **Key responsibilities:**
260
+ * - Creates and manages WebSocket connections to the AirJam server
261
+ * - Provides a Zustand store for connection state (players, game state, etc.)
262
+ * - Creates an InputManager for typed input validation and latching
263
+ * - Resolves configuration from props and environment variables
264
+ *
265
+ * @template TSchema - Zod schema for input validation (inferred from props)
266
+ *
267
+ * @example Basic usage
268
+ * ```tsx
269
+ * import { AirJamProvider } from "@air-jam/sdk";
270
+ *
271
+ * export const App = () => (
272
+ * <AirJamProvider>
273
+ * <Routes>
274
+ * <Route path="/" element={<HostView />} />
275
+ * <Route path="/joypad" element={<ControllerView />} />
276
+ * </Routes>
277
+ * </AirJamProvider>
278
+ * );
279
+ * ```
280
+ *
281
+ * @example With typed input and latching
282
+ * ```tsx
283
+ * import { AirJamProvider } from "@air-jam/sdk";
284
+ * import { z } from "zod";
285
+ *
286
+ * const gameInputSchema = z.object({
287
+ * vector: z.object({ x: z.number(), y: z.number() }),
288
+ * action: z.boolean(),
289
+ * ability: z.boolean(),
290
+ * timestamp: z.number(),
291
+ * });
292
+ *
293
+ * export const App = () => (
294
+ * <AirJamProvider
295
+ * input={{
296
+ * schema: gameInputSchema,
297
+ * latch: {
298
+ * booleanFields: ["action", "ability"],
299
+ * vectorFields: ["vector"],
300
+ * },
301
+ * }}
302
+ * >
303
+ * <GameRoutes />
304
+ * </AirJamProvider>
305
+ * );
306
+ * ```
307
+ */
308
+ export const AirJamProvider = <TSchema extends z.ZodSchema = z.ZodSchema>({
309
+ children,
310
+ serverUrl,
311
+ apiKey,
312
+ controllerPath = DEFAULT_CONTROLLER_PATH,
313
+ maxPlayers = DEFAULT_MAX_PLAYERS,
314
+ publicHost,
315
+ input,
316
+ }: AirJamProviderProps<TSchema>) => {
317
+ // Resolve config with env fallbacks
318
+ const config = useMemo<AirJamConfig>(
319
+ () => ({
320
+ serverUrl: serverUrl ?? getEnvServerUrl(),
321
+ apiKey: apiKey ?? getEnvApiKey(),
322
+ controllerPath,
323
+ maxPlayers,
324
+ publicHost,
325
+ }),
326
+ [serverUrl, apiKey, controllerPath, maxPlayers, publicHost],
327
+ );
328
+
329
+ // Create InputManager from input config if provided
330
+ const inputManager = useMemo(() => {
331
+ if (!input) {
332
+ return null;
333
+ }
334
+ return new InputManager<TSchema>(input);
335
+ }, [input]);
336
+
337
+ // Create context-bound store (once per provider)
338
+ const store = useMemo(() => createAirJamStore(), []);
339
+
340
+ // Create socket manager (once per provider)
341
+ const socketManager = useMemo(
342
+ () => new SocketManager(config.serverUrl),
343
+ // Only recreate if serverUrl changes - intentionally omitting config
344
+
345
+ [config.serverUrl],
346
+ );
347
+
348
+ // Cleanup on unmount
349
+ useEffect(() => {
350
+ return () => {
351
+ socketManager.disconnectAll();
352
+ };
353
+ }, [socketManager]);
354
+
355
+ // Stable function references - don't recreate when config changes
356
+ const getSocket = useCallback(
357
+ (role: ConnectionRole) => socketManager.getSocket(role),
358
+ [socketManager],
359
+ );
360
+
361
+ const disconnectSocket = useCallback(
362
+ (role: ConnectionRole) => socketManager.disconnect(role),
363
+ [socketManager],
364
+ );
365
+
366
+ const contextValue = useMemo<AirJamContextValue>(
367
+ () => ({
368
+ config,
369
+ store,
370
+ socketManager,
371
+ getSocket,
372
+ disconnectSocket,
373
+ inputManager,
374
+ }),
375
+ [config, store, socketManager, getSocket, disconnectSocket, inputManager],
376
+ );
377
+
378
+ return (
379
+ <AirJamContext.Provider value={contextValue}>
380
+ {children}
381
+ </AirJamContext.Provider>
382
+ );
383
+ };
384
+
385
+ // ============================================================================
386
+ // Context Hooks
387
+ // ============================================================================
388
+
389
+ /**
390
+ * Access the raw AirJam context value.
391
+ *
392
+ * This is a low-level hook that provides direct access to the context.
393
+ * Most applications should use the higher-level hooks instead:
394
+ * - `useAirJamHost()` - For host/game functionality
395
+ * - `useAirJamController()` - For controller functionality
396
+ * - `useGetInput()` - For input access without re-renders
397
+ * - `useSendSignal()` - For sending signals without re-renders
398
+ *
399
+ * @throws Error if used outside of an AirJamProvider
400
+ *
401
+ * @example
402
+ * ```tsx
403
+ * const { config, store, inputManager } = useAirJamContext();
404
+ * ```
405
+ */
406
+ export const useAirJamContext = (): AirJamContextValue => {
407
+ const context = useContext(AirJamContext);
408
+ if (!context) {
409
+ throw new Error(
410
+ "useAirJamContext must be used within an AirJamProvider. " +
411
+ "Wrap your app or component tree with <AirJamProvider>.",
412
+ );
413
+ }
414
+ return context;
415
+ };
416
+
417
+ /**
418
+ * Access the resolved AirJam configuration.
419
+ *
420
+ * Returns the configuration with all environment variable fallbacks resolved.
421
+ *
422
+ * @example
423
+ * ```tsx
424
+ * const config = useAirJamConfig();
425
+ * console.log(config.serverUrl, config.maxPlayers);
426
+ * ```
427
+ */
428
+ export const useAirJamConfig = (): AirJamConfig => {
429
+ return useAirJamContext().config;
430
+ };
431
+
432
+ /**
433
+ * Access AirJam store state with a selector.
434
+ *
435
+ * Uses Zustand's useShallow for optimal re-render behavior.
436
+ * Only re-renders when the selected values actually change.
437
+ *
438
+ * @param selector - Function to select state from the store
439
+ * @returns The selected state value
440
+ *
441
+ * @example
442
+ * ```tsx
443
+ * const { players, gameState } = useAirJamState((state) => ({
444
+ * players: state.players,
445
+ * gameState: state.gameState,
446
+ * }));
447
+ * ```
448
+ */
449
+ export const useAirJamState = <T,>(selector: (state: AirJamStore) => T): T => {
450
+ const { store } = useAirJamContext();
451
+ return useStore(store, useShallow(selector));
452
+ };
453
+
454
+ /**
455
+ * Get a socket instance for the specified role.
456
+ *
457
+ * Returns the same socket instance across renders (stable reference).
458
+ * The socket is managed by the SocketManager and shared across hooks.
459
+ *
460
+ * @param role - Either "host" or "controller"
461
+ * @returns The Socket.IO socket instance
462
+ *
463
+ * @example
464
+ * ```tsx
465
+ * const socket = useAirJamSocket("host");
466
+ * socket.emit("custom:event", { data: "value" });
467
+ * ```
468
+ */
469
+ export const useAirJamSocket = (role: ConnectionRole): AirJamSocket => {
470
+ const { getSocket } = useAirJamContext();
471
+ return useMemo(() => getSocket(role), [getSocket, role]);
472
+ };
473
+
474
+ // ============================================================================
475
+ // Exports
476
+ // ============================================================================
477
+
478
+ export { AirJamContext };
@@ -0,0 +1,2 @@
1
+ export * from "./air-jam-context";
2
+ export * from "./socket-manager";
@@ -0,0 +1,98 @@
1
+ import { io, type Socket } from "socket.io-client";
2
+ import { DEFAULT_SERVER_PORT } from "../constants";
3
+ import type {
4
+ ClientToServerEvents,
5
+ ConnectionRole,
6
+ ServerToClientEvents,
7
+ } from "../protocol";
8
+
9
+ export type AirJamSocket = Socket<ServerToClientEvents, ClientToServerEvents>;
10
+
11
+ /**
12
+ * Manages socket connections per role within a provider instance.
13
+ * Unlike the global singleton, each SocketManager is scoped to its provider.
14
+ */
15
+ export class SocketManager {
16
+ private sockets: Partial<Record<ConnectionRole, AirJamSocket>> = {};
17
+ private serverUrl: string;
18
+
19
+ constructor(serverUrl?: string) {
20
+ this.serverUrl = this.resolveServerUrl(serverUrl);
21
+ }
22
+
23
+ /**
24
+ * Get or create a socket for the specified role.
25
+ * Sockets are lazily created and cached per role.
26
+ */
27
+ getSocket(role: ConnectionRole): AirJamSocket {
28
+ const existing = this.sockets[role];
29
+ if (existing) {
30
+ return existing;
31
+ }
32
+
33
+ const socket = io(this.serverUrl, {
34
+ autoConnect: false,
35
+ transports: ["websocket"],
36
+ query: { role },
37
+ }) as AirJamSocket;
38
+
39
+ this.sockets[role] = socket;
40
+ return socket;
41
+ }
42
+
43
+ /**
44
+ * Disconnect a socket by role.
45
+ * NOTE: We intentionally do NOT delete the socket from cache.
46
+ * This ensures all hooks using getSocket() get the same instance,
47
+ * even during React Strict Mode remounts. The socket can be reconnected
48
+ * by calling socket.connect() again.
49
+ */
50
+ disconnect(role: ConnectionRole): void {
51
+ const socket = this.sockets[role];
52
+ if (socket) {
53
+ socket.disconnect();
54
+ // DO NOT delete from cache - keep the same socket instance
55
+ // so all components can reconnect to it
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Disconnect all sockets managed by this instance
61
+ */
62
+ disconnectAll(): void {
63
+ for (const role of Object.keys(this.sockets) as ConnectionRole[]) {
64
+ this.disconnect(role);
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Get the resolved server URL
70
+ */
71
+ getServerUrl(): string {
72
+ return this.serverUrl;
73
+ }
74
+
75
+ /**
76
+ * Resolve server URL with fallbacks
77
+ */
78
+ private resolveServerUrl(explicit?: string): string {
79
+ if (explicit) {
80
+ return this.normalizeOrigin(explicit);
81
+ }
82
+
83
+ if (typeof window !== "undefined") {
84
+ const url = new URL(window.location.href);
85
+ url.port = String(DEFAULT_SERVER_PORT);
86
+ return url.origin;
87
+ }
88
+
89
+ return `http://localhost:${DEFAULT_SERVER_PORT}`;
90
+ }
91
+
92
+ private normalizeOrigin(origin: string): string {
93
+ if (!origin.includes("://")) {
94
+ return `http://${origin}`;
95
+ }
96
+ return origin;
97
+ }
98
+ }