@air-jam/sdk 0.1.0 → 0.1.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.js CHANGED
@@ -1,5 +1,5 @@
1
- import { roomCodeSchema, controllerInputSchema, controllerSystemSchema, controllerStateSchema, controllerJoinSchema, hostRegistrationSchema } from './chunk-XSXI3RIS.js';
2
- export { AIRJAM_PROXY_PREFIX, ErrorCode, controllerInputSchema, controllerJoinSchema, controllerLeaveSchema, controllerStateSchema, controllerSystemSchema, hostJoinAsChildSchema, hostRegisterSystemSchema, hostRegistrationSchema, roomCodeSchema, systemLaunchGameSchema } from './chunk-XSXI3RIS.js';
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';
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';
@@ -7,12 +7,13 @@ import { useShallow } from 'zustand/react/shallow';
7
7
  import { io } from 'socket.io-client';
8
8
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
9
9
  import { Howler, Howl } from 'howler';
10
- import { Volume2, Music, Headphones, Pause, Play, QrCode, MonitorSmartphone, Settings, RefreshCw, Minimize, Maximize } from 'lucide-react';
11
- import QRCode from 'qrcode';
10
+ import { X, Check, Copy, Bug, Volume2, Music, Headphones, Pause, Play, QrCode, MonitorSmartphone, Settings, ExternalLink, RefreshCw, Minimize, Maximize } from 'lucide-react';
11
+ import { Slot } from '@radix-ui/react-slot';
12
12
  import { cva } from 'class-variance-authority';
13
13
  import { clsx } from 'clsx';
14
14
  import { twMerge } from 'tailwind-merge';
15
- import { Slot } from '@radix-ui/react-slot';
15
+ import * as DialogPrimitive from '@radix-ui/react-dialog';
16
+ import QRCode from 'qrcode';
16
17
  import * as TabsPrimitive from '@radix-ui/react-tabs';
17
18
  import * as SliderPrimitive from '@radix-ui/react-slider';
18
19
  import { Html5Qrcode } from 'html5-qrcode';
@@ -782,116 +783,6 @@ var useAudioManager = (manifest) => {
782
783
  return managerRef.current;
783
784
  };
784
785
  var cn = (...inputs) => twMerge(clsx(inputs));
785
- var alertVariants = cva(
786
- "relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
787
- {
788
- variants: {
789
- variant: {
790
- default: "bg-card text-card-foreground",
791
- destructive: "text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"
792
- }
793
- },
794
- defaultVariants: {
795
- variant: "default"
796
- }
797
- }
798
- );
799
- function Alert({
800
- className,
801
- variant,
802
- ...props
803
- }) {
804
- return /* @__PURE__ */ jsx(
805
- "div",
806
- {
807
- "data-slot": "alert",
808
- role: "alert",
809
- className: cn(alertVariants({ variant }), className),
810
- ...props
811
- }
812
- );
813
- }
814
- function AlertDescription({
815
- className,
816
- ...props
817
- }) {
818
- return /* @__PURE__ */ jsx(
819
- "div",
820
- {
821
- "data-slot": "alert-description",
822
- className: cn(
823
- "text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
824
- className
825
- ),
826
- ...props
827
- }
828
- );
829
- }
830
- var Avatar = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
831
- "div",
832
- {
833
- ref,
834
- className: cn(
835
- "relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
836
- className
837
- ),
838
- ...props
839
- }
840
- ));
841
- Avatar.displayName = "Avatar";
842
- var AvatarImage = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
843
- "img",
844
- {
845
- ref,
846
- className: cn("aspect-square h-full w-full", className),
847
- ...props
848
- }
849
- ));
850
- AvatarImage.displayName = "AvatarImage";
851
- var AvatarFallback = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
852
- "div",
853
- {
854
- ref,
855
- className: cn(
856
- "bg-muted flex h-full w-full items-center justify-center rounded-full",
857
- className
858
- ),
859
- ...props
860
- }
861
- ));
862
- AvatarFallback.displayName = "AvatarFallback";
863
- var badgeVariants = cva(
864
- "inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
865
- {
866
- variants: {
867
- variant: {
868
- default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
869
- secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
870
- destructive: "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
871
- outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"
872
- }
873
- },
874
- defaultVariants: {
875
- variant: "default"
876
- }
877
- }
878
- );
879
- function Badge({
880
- className,
881
- variant,
882
- asChild = false,
883
- ...props
884
- }) {
885
- const Comp = asChild ? Slot : "span";
886
- return /* @__PURE__ */ jsx(
887
- Comp,
888
- {
889
- "data-slot": "badge",
890
- className: cn(badgeVariants({ variant }), className),
891
- ...props
892
- }
893
- );
894
- }
895
786
  var buttonVariants = cva(
896
787
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
897
788
  {
@@ -901,7 +792,7 @@ var buttonVariants = cva(
901
792
  destructive: "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
902
793
  outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
903
794
  secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
904
- ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
795
+ ghost: "text-foreground hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
905
796
  link: "text-primary underline-offset-4 hover:underline"
906
797
  },
907
798
  size: {
@@ -936,309 +827,1167 @@ function Button({
936
827
  }
937
828
  );
938
829
  }
939
- function Card({ className, ...props }) {
940
- return /* @__PURE__ */ jsx(
941
- "div",
942
- {
943
- "data-slot": "card",
944
- className: cn(
945
- "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
946
- className
947
- ),
948
- ...props
949
- }
950
- );
951
- }
952
- function CardHeader({ className, ...props }) {
953
- return /* @__PURE__ */ jsx(
954
- "div",
830
+ var Dialog = DialogPrimitive.Root;
831
+ var DialogPortal = DialogPrimitive.Portal;
832
+ var DialogOverlay = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
833
+ DialogPrimitive.Overlay,
834
+ {
835
+ ref,
836
+ className: cn(
837
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-99999 bg-black/80",
838
+ className
839
+ ),
840
+ ...props
841
+ }
842
+ ));
843
+ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
844
+ var DialogContent = React.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ jsx(DialogPortal, { children: /* @__PURE__ */ jsxs("div", { className: "dark", children: [
845
+ /* @__PURE__ */ jsx(DialogOverlay, {}),
846
+ /* @__PURE__ */ jsxs(
847
+ DialogPrimitive.Content,
955
848
  {
956
- "data-slot": "card-header",
849
+ ref,
957
850
  className: cn(
958
- "@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
851
+ "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] fixed top-[50%] left-[50%] z-99999 w-full translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border border-white p-6 shadow-lg duration-200",
959
852
  className
960
853
  ),
961
- ...props
962
- }
963
- );
964
- }
965
- function CardTitle({ className, ...props }) {
966
- return /* @__PURE__ */ jsx(
967
- "div",
968
- {
969
- "data-slot": "card-title",
970
- className: cn("leading-none font-semibold", className),
971
- ...props
972
- }
973
- );
974
- }
975
- function CardDescription({ className, ...props }) {
976
- return /* @__PURE__ */ jsx(
977
- "div",
978
- {
979
- "data-slot": "card-description",
980
- className: cn("text-muted-foreground text-sm", className),
981
- ...props
982
- }
983
- );
984
- }
985
- function CardContent({ className, ...props }) {
986
- return /* @__PURE__ */ jsx(
987
- "div",
988
- {
989
- "data-slot": "card-content",
990
- className: cn("px-6", className),
991
- ...props
854
+ ...props,
855
+ children: [
856
+ children,
857
+ /* @__PURE__ */ jsxs(DialogPrimitive.Close, { className: "text-foreground ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:pointer-events-none", children: [
858
+ /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }),
859
+ /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Close" })
860
+ ] })
861
+ ]
992
862
  }
993
- );
994
- }
995
- function Tabs({
863
+ )
864
+ ] }) }));
865
+ DialogContent.displayName = DialogPrimitive.Content.displayName;
866
+ var DialogHeader = ({
996
867
  className,
997
868
  ...props
998
- }) {
999
- return /* @__PURE__ */ jsx(
1000
- TabsPrimitive.Root,
1001
- {
1002
- "data-slot": "tabs",
1003
- className: cn("flex flex-col gap-2", className),
1004
- ...props
869
+ }) => /* @__PURE__ */ jsx(
870
+ "div",
871
+ {
872
+ className: cn(
873
+ "flex flex-col space-y-1.5 text-center sm:text-left",
874
+ className
875
+ ),
876
+ ...props
877
+ }
878
+ );
879
+ DialogHeader.displayName = "DialogHeader";
880
+ var DialogTitle = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
881
+ DialogPrimitive.Title,
882
+ {
883
+ ref,
884
+ className: cn(
885
+ "text-lg leading-none font-semibold tracking-tight",
886
+ className
887
+ ),
888
+ ...props
889
+ }
890
+ ));
891
+ DialogTitle.displayName = DialogPrimitive.Title.displayName;
892
+ var DialogDescription = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
893
+ DialogPrimitive.Description,
894
+ {
895
+ ref,
896
+ className: cn("text-muted-foreground text-sm", className),
897
+ ...props
898
+ }
899
+ ));
900
+ DialogDescription.displayName = DialogPrimitive.Description.displayName;
901
+ var DebugStateDialog = ({
902
+ isOpen,
903
+ onClose,
904
+ getState,
905
+ title = "Debug State",
906
+ updateInterval = 100
907
+ }) => {
908
+ const [state, setState] = useState(() => getState());
909
+ const [copied, setCopied] = useState(false);
910
+ useEffect(() => {
911
+ if (!isOpen) return;
912
+ const interval = setInterval(() => {
913
+ setState(getState());
914
+ }, updateInterval);
915
+ const timeoutId = setTimeout(() => {
916
+ setState(getState());
917
+ }, 0);
918
+ return () => {
919
+ clearInterval(interval);
920
+ clearTimeout(timeoutId);
921
+ };
922
+ }, [isOpen, getState, updateInterval]);
923
+ const jsonString = JSON.stringify(state, null, 2);
924
+ const handleCopy = async () => {
925
+ try {
926
+ await navigator.clipboard.writeText(jsonString);
927
+ setCopied(true);
928
+ setTimeout(() => setCopied(false), 2e3);
929
+ } catch (error) {
930
+ console.error("Failed to copy:", error);
1005
931
  }
1006
- );
1007
- }
1008
- function TabsList({
1009
- className,
1010
- ...props
1011
- }) {
1012
- return /* @__PURE__ */ jsx(
1013
- TabsPrimitive.List,
1014
- {
1015
- "data-slot": "tabs-list",
1016
- className: cn(
1017
- "bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
1018
- className
932
+ };
933
+ return /* @__PURE__ */ jsx(Dialog, { open: isOpen, onOpenChange: onClose, children: /* @__PURE__ */ jsxs(DialogContent, { className: "dark max-h-[90vh] max-w-2xl flex-col", children: [
934
+ /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { className: "text-foreground", children: title }) }),
935
+ /* @__PURE__ */ jsxs("div", { className: "relative flex-1 overflow-auto pt-4", children: [
936
+ /* @__PURE__ */ jsx(
937
+ Button,
938
+ {
939
+ variant: "ghost",
940
+ size: "icon-sm",
941
+ onClick: handleCopy,
942
+ className: "text-muted-foreground hover:text-foreground absolute top-6 right-2 z-10",
943
+ "aria-label": "Copy state",
944
+ children: copied ? /* @__PURE__ */ jsx(Check, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4" })
945
+ }
1019
946
  ),
1020
- ...props
947
+ /* @__PURE__ */ jsx("pre", { className: "bg-muted text-muted-foreground overflow-auto rounded-lg border p-4 font-mono text-xs", children: jsonString })
948
+ ] })
949
+ ] }) });
950
+ };
951
+ var AirJamDebug = ({
952
+ state,
953
+ title = "Debug State",
954
+ updateInterval = 100,
955
+ className
956
+ }) => {
957
+ const [isOpen, setIsOpen] = useState(false);
958
+ const [currentState, setCurrentState] = useState(state);
959
+ useEffect(() => {
960
+ if (!isOpen) return;
961
+ const interval = setInterval(() => {
962
+ setCurrentState(state);
963
+ }, updateInterval);
964
+ setCurrentState(state);
965
+ return () => clearInterval(interval);
966
+ }, [isOpen, state, updateInterval]);
967
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
968
+ /* @__PURE__ */ jsx(
969
+ Button,
970
+ {
971
+ type: "button",
972
+ variant: "ghost",
973
+ size: "icon",
974
+ onClick: () => setIsOpen(true),
975
+ "aria-label": "Debug state",
976
+ title,
977
+ className: `text-white hover:bg-white/20 hover:text-white ${className || ""}`,
978
+ children: /* @__PURE__ */ jsx(Bug, { className: "h-4 w-4" })
979
+ }
980
+ ),
981
+ /* @__PURE__ */ jsx(
982
+ DebugStateDialog,
983
+ {
984
+ isOpen,
985
+ onClose: () => setIsOpen(false),
986
+ getState: () => currentState,
987
+ title,
988
+ updateInterval
989
+ }
990
+ )
991
+ ] });
992
+ };
993
+
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);
1021
1003
  }
1022
- );
1023
- }
1024
- function TabsTrigger({
1025
- className,
1026
- ...props
1027
- }) {
1028
- return /* @__PURE__ */ jsx(
1029
- TabsPrimitive.Trigger,
1030
- {
1031
- "data-slot": "tabs-trigger",
1032
- className: cn(
1033
- "data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
1034
- className
1035
- ),
1036
- ...props
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
+ // src/utils/mode.ts
1018
+ var detectRunMode = () => {
1019
+ if (typeof window === "undefined") {
1020
+ return "standalone";
1021
+ }
1022
+ try {
1023
+ return window.self !== window.top ? "platform" : "standalone";
1024
+ } catch {
1025
+ return "platform";
1026
+ }
1027
+ };
1028
+
1029
+ // src/utils/network-ip.ts
1030
+ var isVirtualNetwork = (ip) => {
1031
+ if (ip.startsWith("192.168.64.") || ip.startsWith("192.168.65.")) {
1032
+ return true;
1033
+ }
1034
+ if (ip.startsWith("172.17.")) {
1035
+ return true;
1036
+ }
1037
+ if (ip.startsWith("172.18.") || ip.startsWith("172.19.")) {
1038
+ return true;
1039
+ }
1040
+ if (ip.startsWith("169.254.")) {
1041
+ return true;
1042
+ }
1043
+ return false;
1044
+ };
1045
+ var scoreIp = (ip) => {
1046
+ if (ip.startsWith("192.168.")) {
1047
+ const parts = ip.split(".");
1048
+ const thirdOctet = parseInt(parts[2] || "0", 10);
1049
+ if (thirdOctet < 64) {
1050
+ return 100 - thirdOctet;
1037
1051
  }
1038
- );
1039
- }
1040
- function TabsContent({
1041
- className,
1042
- ...props
1043
- }) {
1044
- return /* @__PURE__ */ jsx(
1045
- TabsPrimitive.Content,
1046
- {
1047
- "data-slot": "tabs-content",
1048
- className: cn("flex-1 outline-none", className),
1049
- ...props
1052
+ return 10;
1053
+ }
1054
+ if (ip.startsWith("10.")) {
1055
+ return 50;
1056
+ }
1057
+ if (/^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip)) {
1058
+ return 30;
1059
+ }
1060
+ return 0;
1061
+ };
1062
+ var getLocalNetworkIp = () => {
1063
+ return new Promise((resolve) => {
1064
+ if (typeof window === "undefined" || typeof RTCPeerConnection === "undefined") {
1065
+ resolve(null);
1066
+ return;
1050
1067
  }
1051
- );
1052
- }
1053
- function Slider({
1054
- className,
1055
- defaultValue,
1056
- value,
1057
- min = 0,
1058
- max = 100,
1059
- ...props
1060
- }) {
1061
- const _values = React.useMemo(
1062
- () => Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min, max],
1063
- [value, defaultValue, min, max]
1064
- );
1065
- return /* @__PURE__ */ jsxs(
1066
- SliderPrimitive.Root,
1067
- {
1068
- "data-slot": "slider",
1069
- defaultValue,
1070
- value,
1071
- min,
1072
- max,
1073
- className: cn(
1074
- "relative flex w-full cursor-pointer touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
1075
- className
1076
- ),
1077
- ...props,
1078
- children: [
1079
- /* @__PURE__ */ jsx(
1080
- SliderPrimitive.Track,
1081
- {
1082
- "data-slot": "slider-track",
1083
- className: cn(
1084
- "bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
1085
- ),
1086
- children: /* @__PURE__ */ jsx(
1087
- SliderPrimitive.Range,
1088
- {
1089
- "data-slot": "slider-range",
1090
- className: cn(
1091
- "bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
1092
- )
1093
- }
1094
- )
1068
+ const pc = new RTCPeerConnection({
1069
+ iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
1070
+ });
1071
+ const candidates = [];
1072
+ let candidateGatheringComplete = false;
1073
+ const resolveOnce = (ip) => {
1074
+ pc.close();
1075
+ resolve(ip);
1076
+ };
1077
+ const timeout = setTimeout(() => {
1078
+ if (candidateGatheringComplete) {
1079
+ pickBestCandidate();
1080
+ } else {
1081
+ setTimeout(() => {
1082
+ pickBestCandidate();
1083
+ }, 500);
1084
+ }
1085
+ }, 3e3);
1086
+ const pickBestCandidate = () => {
1087
+ if (candidates.length === 0) {
1088
+ resolveOnce(null);
1089
+ return;
1090
+ }
1091
+ candidates.sort((a, b) => b.score - a.score);
1092
+ const best = candidates[0];
1093
+ clearTimeout(timeout);
1094
+ resolveOnce(best.ip);
1095
+ };
1096
+ pc.onicecandidate = (event) => {
1097
+ if (event.candidate) {
1098
+ const candidate = event.candidate.candidate;
1099
+ const match = candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3})/);
1100
+ if (match) {
1101
+ const ip = match[1];
1102
+ if (ip === "127.0.0.1") {
1103
+ return;
1104
+ }
1105
+ const isPrivate = ip.startsWith("192.168.") || ip.startsWith("10.") || /^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip);
1106
+ if (isPrivate && !isVirtualNetwork(ip)) {
1107
+ const score = scoreIp(ip);
1108
+ candidates.push({ ip, score });
1095
1109
  }
1096
- ),
1097
- Array.from({ length: _values.length }, (_, index) => /* @__PURE__ */ jsx(
1098
- SliderPrimitive.Thumb,
1099
- {
1100
- "data-slot": "slider-thumb",
1101
- className: "border-primary ring-ring/50 block size-4 shrink-0 cursor-pointer rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
1102
- },
1103
- index
1104
- ))
1105
- ]
1106
- }
1107
- );
1108
- }
1109
- function VolumeControls({ className, compact }) {
1110
- const {
1111
- masterVolume,
1112
- musicVolume,
1113
- sfxVolume,
1114
- setMasterVolume,
1115
- setMusicVolume,
1116
- setSfxVolume
1117
- } = useVolumeStore();
1118
- return /* @__PURE__ */ jsxs("div", { className: cn("flex flex-col gap-3", compact && "gap-1", className), children: [
1119
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
1120
- /* @__PURE__ */ jsx(Volume2, { className: "text-muted-foreground h-4 w-4" }),
1121
- /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Volume" })
1122
- ] }),
1123
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1124
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1125
- /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "Master" }),
1126
- /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1127
- Math.round(masterVolume * 100),
1128
- "%"
1129
- ] })
1130
- ] }),
1131
- /* @__PURE__ */ jsx(
1132
- Slider,
1133
- {
1134
- value: [masterVolume * 100],
1135
- onValueChange: (values) => setMasterVolume(values[0] / 100),
1136
- min: 0,
1137
- max: 100,
1138
- step: 1,
1139
- className: "w-full",
1140
- "aria-label": "Master volume"
1141
- }
1142
- )
1143
- ] }),
1144
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1145
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1146
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
1147
- /* @__PURE__ */ jsx(Music, { className: "text-muted-foreground h-3 w-3" }),
1148
- /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "Music" })
1149
- ] }),
1150
- /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1151
- Math.round(musicVolume * 100),
1152
- "%"
1153
- ] })
1154
- ] }),
1155
- /* @__PURE__ */ jsx(
1156
- Slider,
1157
- {
1158
- value: [musicVolume * 100],
1159
- onValueChange: (values) => setMusicVolume(values[0] / 100),
1160
- min: 0,
1161
- max: 100,
1162
- step: 1,
1163
- className: "w-full",
1164
- "aria-label": "Music volume"
1165
1110
  }
1166
- )
1167
- ] }),
1168
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1169
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1170
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
1171
- /* @__PURE__ */ jsx(Headphones, { className: "text-muted-foreground h-3 w-3" }),
1172
- /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "SFX" })
1173
- ] }),
1174
- /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1175
- Math.round(sfxVolume * 100),
1176
- "%"
1177
- ] })
1178
- ] }),
1179
- /* @__PURE__ */ jsx(
1180
- Slider,
1181
- {
1182
- value: [sfxVolume * 100],
1183
- onValueChange: (values) => setSfxVolume(values[0] / 100),
1184
- min: 0,
1185
- max: 100,
1186
- step: 1,
1187
- className: "w-full",
1188
- "aria-label": "SFX volume"
1189
- }
1190
- )
1191
- ] })
1192
- ] });
1193
- }
1194
- var statusCopy = {
1195
- idle: "Idle",
1196
- connecting: "Waiting for server\u2026",
1197
- connected: "Ready for controllers",
1198
- disconnected: "Disconnected",
1199
- reconnecting: "Reconnecting\u2026"
1111
+ } else {
1112
+ candidateGatheringComplete = true;
1113
+ setTimeout(() => {
1114
+ pickBestCandidate();
1115
+ }, 200);
1116
+ }
1117
+ };
1118
+ pc.createDataChannel("");
1119
+ pc.createOffer().then((offer) => pc.setLocalDescription(offer)).catch(() => {
1120
+ clearTimeout(timeout);
1121
+ resolveOnce(null);
1122
+ });
1123
+ });
1200
1124
  };
1201
- var getPlayerAvatarUrl = (playerId) => {
1202
- return `https://api.dicebear.com/9.x/adventurer-neutral/svg?seed=${encodeURIComponent(
1203
- playerId
1204
- )}`;
1125
+
1126
+ // src/utils/url-builder.ts
1127
+ var UrlBuilder = class {
1128
+ cachedLocalIp = null;
1129
+ ipDetectionPromise = null;
1130
+ /**
1131
+ * Get the local network IP address with caching.
1132
+ * First call triggers detection, subsequent calls return cached value.
1133
+ */
1134
+ async getLocalIp() {
1135
+ if (this.cachedLocalIp !== null) {
1136
+ return this.cachedLocalIp;
1137
+ }
1138
+ if (this.ipDetectionPromise !== null) {
1139
+ return this.ipDetectionPromise;
1140
+ }
1141
+ this.ipDetectionPromise = getLocalNetworkIp().then((ip) => {
1142
+ this.cachedLocalIp = ip;
1143
+ this.ipDetectionPromise = null;
1144
+ return ip;
1145
+ });
1146
+ return this.ipDetectionPromise;
1147
+ }
1148
+ /**
1149
+ * Clear the cached IP address.
1150
+ * Useful for testing or when network changes are detected.
1151
+ */
1152
+ clearCache() {
1153
+ this.cachedLocalIp = null;
1154
+ this.ipDetectionPromise = null;
1155
+ }
1156
+ /**
1157
+ * Normalize a URL for mobile access.
1158
+ * Replaces localhost with the local network IP.
1159
+ */
1160
+ async normalizeForMobile(url) {
1161
+ if (typeof window === "undefined") return url;
1162
+ try {
1163
+ const urlObj = new URL(url);
1164
+ if (urlObj.hostname === "localhost" || urlObj.hostname === "127.0.0.1") {
1165
+ const localIp = await this.getLocalIp();
1166
+ if (localIp) {
1167
+ urlObj.hostname = localIp;
1168
+ return urlObj.toString();
1169
+ }
1170
+ urlObj.hostname = window.location.hostname;
1171
+ return urlObj.toString();
1172
+ }
1173
+ return url;
1174
+ } catch {
1175
+ return url;
1176
+ }
1177
+ }
1178
+ /**
1179
+ * Build a controller URL with room code.
1180
+ * Automatically uses local IP when running on localhost.
1181
+ */
1182
+ async buildControllerUrl(roomId, options) {
1183
+ const path = options?.path || DEFAULT_CONTROLLER_PATH;
1184
+ if (options?.host) {
1185
+ const url2 = new URL(path, this.normalizeOrigin(options.host));
1186
+ url2.searchParams.set("room", roomId);
1187
+ return url2.toString();
1188
+ }
1189
+ let base;
1190
+ if (typeof window === "undefined") {
1191
+ base = `http://localhost:${DEFAULT_SERVER_PORT}`;
1192
+ } else {
1193
+ const currentUrl = new URL(window.location.href);
1194
+ if (!this.isLocalhost(currentUrl.hostname)) {
1195
+ base = currentUrl.origin;
1196
+ } else {
1197
+ const localIp = await this.getLocalIp();
1198
+ if (localIp) {
1199
+ const port = currentUrl.port;
1200
+ base = port ? `http://${localIp}:${port}` : `http://${localIp}`;
1201
+ } else {
1202
+ base = currentUrl.origin;
1203
+ }
1204
+ }
1205
+ }
1206
+ const url = new URL(path, base);
1207
+ url.searchParams.set("room", roomId);
1208
+ return url.toString();
1209
+ }
1210
+ /**
1211
+ * Resolve the server URL.
1212
+ * Uses explicit URL if provided, otherwise infers from window location.
1213
+ */
1214
+ resolveServerUrl(explicit) {
1215
+ if (explicit) {
1216
+ return this.normalizeOrigin(explicit);
1217
+ }
1218
+ if (typeof window !== "undefined") {
1219
+ const url = new URL(window.location.href);
1220
+ url.port = String(DEFAULT_SERVER_PORT);
1221
+ return url.origin;
1222
+ }
1223
+ return `http://localhost:${DEFAULT_SERVER_PORT}`;
1224
+ }
1225
+ /**
1226
+ * Check if a hostname is localhost.
1227
+ */
1228
+ isLocalhost(hostname) {
1229
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
1230
+ }
1231
+ /**
1232
+ * Normalize an origin string to ensure it has a protocol.
1233
+ */
1234
+ normalizeOrigin(origin) {
1235
+ if (!origin.includes("://")) {
1236
+ return `http://${origin}`;
1237
+ }
1238
+ return origin;
1239
+ }
1205
1240
  };
1206
- var AirJamOverlay = ({
1207
- roomId,
1208
- joinUrl,
1209
- connectionStatus,
1210
- players,
1211
- lastError,
1212
- gameState,
1213
- onTogglePlayPause,
1214
- isChildMode = false
1215
- }) => {
1216
- const [qrUrl, setQrUrl] = useState(null);
1217
- const [qrError, setQrError] = useState(null);
1241
+ var urlBuilder = new UrlBuilder();
1242
+
1243
+ // src/hooks/use-air-jam-host.ts
1244
+ var useAirJamHost = (options = {}) => {
1245
+ const { config, store, getSocket, disconnectSocket, inputManager } = useAirJamContext();
1246
+ const arcadeParams = useMemo(() => {
1247
+ if (typeof window === "undefined") return null;
1248
+ const params = new URLSearchParams(window.location.search);
1249
+ const room = params.get("aj_room");
1250
+ const token = params.get("aj_token");
1251
+ if (room && token) {
1252
+ return { room, token };
1253
+ }
1254
+ return null;
1255
+ }, []);
1256
+ const isChildMode = !!arcadeParams;
1257
+ const shouldConnect = true;
1258
+ const [fallbackRoomId] = useState(() => generateRoomCode());
1259
+ const parsedRoomId = useMemo(() => {
1260
+ if (arcadeParams) {
1261
+ return roomCodeSchema.parse(arcadeParams.room.toUpperCase());
1262
+ }
1263
+ if (typeof window !== "undefined") {
1264
+ const params = new URLSearchParams(window.location.search);
1265
+ const paramRoom = params.get("room");
1266
+ if (paramRoom) {
1267
+ const result = roomCodeSchema.safeParse(paramRoom.toUpperCase());
1268
+ if (result.success) return result.data;
1269
+ }
1270
+ }
1271
+ if (options.roomId) {
1272
+ return roomCodeSchema.parse(options.roomId.toUpperCase());
1273
+ }
1274
+ return fallbackRoomId;
1275
+ }, [options.roomId, fallbackRoomId, arcadeParams]);
1218
1276
  useEffect(() => {
1219
- if (isChildMode) return;
1220
- let mounted = true;
1221
- QRCode.toDataURL(joinUrl, {
1222
- margin: 1,
1223
- color: {
1224
- dark: "#0f172a",
1225
- light: "#ffffff"
1226
- },
1227
- width: 320
1228
- }).then((value) => {
1229
- if (mounted) {
1230
- setQrUrl(value);
1231
- setQrError(null);
1277
+ if (inputManager) {
1278
+ inputManager.setRoomId(parsedRoomId);
1279
+ }
1280
+ }, [inputManager, parsedRoomId]);
1281
+ const [joinUrl, setJoinUrl] = useState("");
1282
+ const onPlayerJoinRef = useRef(options.onPlayerJoin);
1283
+ const onPlayerLeaveRef = useRef(options.onPlayerLeave);
1284
+ const onChildCloseRef = useRef(options.onChildClose);
1285
+ useEffect(() => {
1286
+ onPlayerJoinRef.current = options.onPlayerJoin;
1287
+ onPlayerLeaveRef.current = options.onPlayerLeave;
1288
+ onChildCloseRef.current = options.onChildClose;
1289
+ }, [options.onPlayerJoin, options.onPlayerLeave, options.onChildClose]);
1290
+ const connectionState = useStore(
1291
+ store,
1292
+ useShallow((state) => ({
1293
+ connectionStatus: state.connectionStatus,
1294
+ lastError: state.lastError,
1295
+ players: state.players,
1296
+ gameState: state.gameState,
1297
+ mode: state.mode
1298
+ }))
1299
+ );
1300
+ const socket = useMemo(
1301
+ () => getSocket("host") ,
1302
+ [shouldConnect, getSocket]
1303
+ );
1304
+ const [lastToggle, setLastToggle] = useState(0);
1305
+ const toggleGameState = useCallback(() => {
1306
+ const now = Date.now();
1307
+ if (now - lastToggle < TOGGLE_DEBOUNCE_MS) {
1308
+ return;
1309
+ }
1310
+ setLastToggle(now);
1311
+ if (!socket || !socket.connected) {
1312
+ return;
1313
+ }
1314
+ const payload = controllerSystemSchema.safeParse({
1315
+ roomId: parsedRoomId,
1316
+ command: "toggle_pause"
1317
+ });
1318
+ if (payload.success) {
1319
+ socket.emit("host:system", payload.data);
1320
+ }
1321
+ }, [socket, parsedRoomId, lastToggle]);
1322
+ const sendState = useCallback(
1323
+ (state) => {
1324
+ if (!socket || !socket.connected) {
1325
+ return false;
1232
1326
  }
1233
- }).catch((err) => {
1234
- if (mounted) {
1235
- setQrError(err.message);
1327
+ const payload = controllerStateSchema.safeParse({
1328
+ roomId: parsedRoomId,
1329
+ state
1330
+ });
1331
+ if (!payload.success) {
1332
+ return false;
1333
+ }
1334
+ socket.emit("host:state", payload.data);
1335
+ return true;
1336
+ },
1337
+ [socket, parsedRoomId]
1338
+ );
1339
+ const sendSignal = useCallback(
1340
+ (type, payload, targetId) => {
1341
+ if (!socket || !socket.connected) {
1342
+ return;
1343
+ }
1344
+ const signal = {
1345
+ targetId,
1346
+ type,
1347
+ payload
1348
+ };
1349
+ socket.emit("host:signal", signal);
1350
+ },
1351
+ [socket]
1352
+ );
1353
+ const reconnect = useCallback(() => {
1354
+ disconnectSocket("host");
1355
+ if (socket) {
1356
+ socket.connect();
1357
+ }
1358
+ }, [socket, disconnectSocket]);
1359
+ useEffect(() => {
1360
+ (async () => {
1361
+ const url = await urlBuilder.buildControllerUrl(parsedRoomId, {
1362
+ path: config.controllerPath,
1363
+ host: config.publicHost
1364
+ });
1365
+ setJoinUrl(url);
1366
+ })();
1367
+ }, [parsedRoomId, config.controllerPath, config.publicHost]);
1368
+ const setRegisteredRoomId = useStore(store, (s) => s.setRegisteredRoomId);
1369
+ useEffect(() => {
1370
+ const storeState = store.getState();
1371
+ storeState.setMode(detectRunMode());
1372
+ storeState.setRole("host");
1373
+ storeState.setRoomId(parsedRoomId);
1374
+ storeState.setStatus("connecting");
1375
+ storeState.setError(void 0);
1376
+ if (!socket) {
1377
+ storeState.setStatus("idle");
1378
+ return;
1379
+ }
1380
+ const registerHost = async () => {
1381
+ const storeState2 = store.getState();
1382
+ const currentRegisteredRoomId2 = store.getState().registeredRoomId;
1383
+ if (currentRegisteredRoomId2 === parsedRoomId && socket.connected) {
1384
+ return;
1385
+ }
1386
+ if (arcadeParams) {
1387
+ const childRoomId = roomCodeSchema.parse(
1388
+ arcadeParams.room.toUpperCase()
1389
+ );
1390
+ const payload = {
1391
+ roomId: childRoomId,
1392
+ joinToken: arcadeParams.token
1393
+ };
1394
+ socket.emit("host:joinAsChild", payload, (ack) => {
1395
+ if (!ack.ok) {
1396
+ storeState2.setError(ack.message ?? "Failed to join as child");
1397
+ storeState2.setStatus("disconnected");
1398
+ setRegisteredRoomId(null);
1399
+ return;
1400
+ }
1401
+ storeState2.setStatus("connected");
1402
+ storeState2.setRoomId(childRoomId);
1403
+ setRegisteredRoomId(childRoomId);
1404
+ });
1405
+ } 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);
1422
+ } else {
1423
+ setRegisteredRoomId(parsedRoomId);
1424
+ }
1425
+ });
1426
+ }
1427
+ };
1428
+ const handleConnect = () => {
1429
+ store.getState().setStatus("connected");
1430
+ registerHost();
1431
+ };
1432
+ const handleDisconnect = () => {
1433
+ store.getState().setStatus("disconnected");
1434
+ };
1435
+ const handleJoin = (payload) => {
1436
+ if (payload.player) {
1437
+ store.getState().upsertPlayer(payload.player);
1438
+ setTimeout(() => {
1439
+ onPlayerJoinRef.current?.(payload.player);
1440
+ }, 0);
1441
+ }
1442
+ };
1443
+ const handleLeave = (payload) => {
1444
+ store.getState().removePlayer(payload.controllerId);
1445
+ onPlayerLeaveRef.current?.(payload.controllerId);
1446
+ };
1447
+ const handleInput = (payload) => {
1448
+ if (inputManager) {
1449
+ inputManager.handleInput(payload);
1450
+ }
1451
+ };
1452
+ const handleChildClose = () => {
1453
+ onChildCloseRef.current?.();
1454
+ };
1455
+ const handleState = (payload) => {
1456
+ if (payload.roomId !== parsedRoomId) return;
1457
+ const storeState2 = store.getState();
1458
+ if (payload.state.gameState) {
1459
+ storeState2.setGameState(payload.state.gameState);
1460
+ }
1461
+ if (payload.state.message !== void 0) {
1462
+ storeState2.setStateMessage(payload.state.message);
1463
+ }
1464
+ };
1465
+ const handleError = (payload) => {
1466
+ store.getState().setError(payload.message);
1467
+ };
1468
+ socket.on("connect", handleConnect);
1469
+ socket.on("disconnect", handleDisconnect);
1470
+ socket.on("server:controllerJoined", handleJoin);
1471
+ socket.on("server:controllerLeft", handleLeave);
1472
+ socket.on("server:input", handleInput);
1473
+ socket.on("server:error", handleError);
1474
+ socket.on("server:closeChild", handleChildClose);
1475
+ socket.on("server:state", handleState);
1476
+ socket.connect();
1477
+ const currentRegisteredRoomId = store.getState().registeredRoomId;
1478
+ if (socket.connected && currentRegisteredRoomId !== parsedRoomId) {
1479
+ registerHost();
1480
+ }
1481
+ if (currentRegisteredRoomId && currentRegisteredRoomId !== parsedRoomId) {
1482
+ setRegisteredRoomId(null);
1483
+ }
1484
+ return () => {
1485
+ socket.off("connect", handleConnect);
1486
+ socket.off("disconnect", handleDisconnect);
1487
+ socket.off("server:controllerJoined", handleJoin);
1488
+ socket.off("server:controllerLeft", handleLeave);
1489
+ socket.off("server:input", handleInput);
1490
+ socket.off("server:error", handleError);
1491
+ socket.off("server:closeChild", handleChildClose);
1492
+ socket.off("server:state", handleState);
1493
+ };
1494
+ }, [
1495
+ config.maxPlayers,
1496
+ config.apiKey,
1497
+ options.maxPlayers,
1498
+ options.apiKey,
1499
+ parsedRoomId,
1500
+ arcadeParams,
1501
+ shouldConnect,
1502
+ socket,
1503
+ store,
1504
+ inputManager,
1505
+ setRegisteredRoomId
1506
+ ]);
1507
+ const returnSocket = socket ?? getSocket("host");
1508
+ const getInput = useCallback(
1509
+ (controllerId) => {
1510
+ if (!inputManager) {
1511
+ return void 0;
1512
+ }
1513
+ return inputManager.getInput(controllerId);
1514
+ },
1515
+ [inputManager]
1516
+ );
1517
+ return {
1518
+ roomId: parsedRoomId,
1519
+ joinUrl,
1520
+ connectionStatus: connectionState.connectionStatus,
1521
+ players: connectionState.players,
1522
+ lastError: connectionState.lastError,
1523
+ mode: connectionState.mode,
1524
+ gameState: connectionState.gameState,
1525
+ toggleGameState,
1526
+ sendState,
1527
+ sendSignal,
1528
+ reconnect,
1529
+ socket: returnSocket,
1530
+ isChildMode,
1531
+ getInput
1532
+ };
1533
+ };
1534
+ var getPlayerAvatarUrl = (playerId) => {
1535
+ return `https://api.dicebear.com/9.x/adventurer-neutral/svg?seed=${encodeURIComponent(
1536
+ playerId
1537
+ )}`;
1538
+ };
1539
+ var hexToRgba = (hex, opacity) => {
1540
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
1541
+ if (!result) return `rgba(0, 0, 0, ${opacity})`;
1542
+ const r = parseInt(result[1], 16);
1543
+ const g = parseInt(result[2], 16);
1544
+ const b = parseInt(result[3], 16);
1545
+ return `rgba(${r}, ${g}, ${b}, ${opacity})`;
1546
+ };
1547
+ var PlayerAvatar = ({
1548
+ player,
1549
+ size = "md",
1550
+ className = ""
1551
+ }) => {
1552
+ const sizeClasses = {
1553
+ sm: "h-8 w-8 border-2",
1554
+ md: "h-12 w-12 border-4",
1555
+ lg: "h-16 w-16 border-4"
1556
+ };
1557
+ const shadowStyles = {
1558
+ sm: player.color ? `inset 0 0 4px rgba(0, 0, 0, 0.2), 0 0 8px ${hexToRgba(player.color, 0.4)}` : "inset 0 0 4px rgba(0, 0, 0, 0.2)",
1559
+ md: player.color ? `inset 0 0 10px rgba(0, 0, 0, 0.4), 0 0 20px ${hexToRgba(player.color, 0.6)}, 0 0 10px ${hexToRgba(player.color, 0.8)}` : "inset 0 0 10px rgba(0, 0, 0, 0.4), 0 0 20px hsl(var(--border) / 0.5)",
1560
+ lg: player.color ? `inset 0 0 12px rgba(0, 0, 0, 0.4), 0 0 24px ${hexToRgba(player.color, 0.6)}, 0 0 12px ${hexToRgba(player.color, 0.8)}` : "inset 0 0 12px rgba(0, 0, 0, 0.4), 0 0 24px hsl(var(--border) / 0.5)"
1561
+ };
1562
+ return /* @__PURE__ */ jsx(
1563
+ "img",
1564
+ {
1565
+ src: getPlayerAvatarUrl(player.id),
1566
+ alt: player.label,
1567
+ className: `bg-secondary/30 shrink-0 rounded-full shadow-lg ${sizeClasses[size]} ${className}`,
1568
+ style: {
1569
+ borderColor: player.color || "hsl(var(--border))",
1570
+ boxShadow: shadowStyles[size]
1571
+ }
1572
+ }
1573
+ );
1574
+ };
1575
+ var alertVariants = cva(
1576
+ "relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
1577
+ {
1578
+ variants: {
1579
+ variant: {
1580
+ default: "bg-card text-card-foreground",
1581
+ destructive: "text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"
1582
+ }
1583
+ },
1584
+ defaultVariants: {
1585
+ variant: "default"
1586
+ }
1587
+ }
1588
+ );
1589
+ function Alert({
1590
+ className,
1591
+ variant,
1592
+ ...props
1593
+ }) {
1594
+ return /* @__PURE__ */ jsx(
1595
+ "div",
1596
+ {
1597
+ "data-slot": "alert",
1598
+ role: "alert",
1599
+ className: cn(alertVariants({ variant }), className),
1600
+ ...props
1601
+ }
1602
+ );
1603
+ }
1604
+ function AlertDescription({
1605
+ className,
1606
+ ...props
1607
+ }) {
1608
+ return /* @__PURE__ */ jsx(
1609
+ "div",
1610
+ {
1611
+ "data-slot": "alert-description",
1612
+ className: cn(
1613
+ "text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
1614
+ className
1615
+ ),
1616
+ ...props
1617
+ }
1618
+ );
1619
+ }
1620
+ var badgeVariants = cva(
1621
+ "inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
1622
+ {
1623
+ variants: {
1624
+ variant: {
1625
+ default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
1626
+ secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
1627
+ destructive: "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
1628
+ outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"
1629
+ }
1630
+ },
1631
+ defaultVariants: {
1632
+ variant: "default"
1633
+ }
1634
+ }
1635
+ );
1636
+ function Badge({
1637
+ className,
1638
+ variant,
1639
+ asChild = false,
1640
+ ...props
1641
+ }) {
1642
+ const Comp = asChild ? Slot : "span";
1643
+ return /* @__PURE__ */ jsx(
1644
+ Comp,
1645
+ {
1646
+ "data-slot": "badge",
1647
+ className: cn(badgeVariants({ variant }), className),
1648
+ ...props
1649
+ }
1650
+ );
1651
+ }
1652
+ function Card({ className, ...props }) {
1653
+ return /* @__PURE__ */ jsx(
1654
+ "div",
1655
+ {
1656
+ "data-slot": "card",
1657
+ className: cn(
1658
+ "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
1659
+ className
1660
+ ),
1661
+ ...props
1662
+ }
1663
+ );
1664
+ }
1665
+ function CardTitle({ className, ...props }) {
1666
+ return /* @__PURE__ */ jsx(
1667
+ "div",
1668
+ {
1669
+ "data-slot": "card-title",
1670
+ className: cn("leading-none font-semibold", className),
1671
+ ...props
1672
+ }
1673
+ );
1674
+ }
1675
+ function CardDescription({ className, ...props }) {
1676
+ return /* @__PURE__ */ jsx(
1677
+ "div",
1678
+ {
1679
+ "data-slot": "card-description",
1680
+ className: cn("text-muted-foreground text-sm", className),
1681
+ ...props
1682
+ }
1683
+ );
1684
+ }
1685
+ function CardContent({ className, ...props }) {
1686
+ return /* @__PURE__ */ jsx(
1687
+ "div",
1688
+ {
1689
+ "data-slot": "card-content",
1690
+ className: cn("px-6", className),
1691
+ ...props
1692
+ }
1693
+ );
1694
+ }
1695
+ function Tabs({
1696
+ className,
1697
+ ...props
1698
+ }) {
1699
+ return /* @__PURE__ */ jsx(
1700
+ TabsPrimitive.Root,
1701
+ {
1702
+ "data-slot": "tabs",
1703
+ className: cn("flex flex-col gap-2", className),
1704
+ ...props
1705
+ }
1706
+ );
1707
+ }
1708
+ function TabsList({
1709
+ className,
1710
+ ...props
1711
+ }) {
1712
+ return /* @__PURE__ */ jsx(
1713
+ TabsPrimitive.List,
1714
+ {
1715
+ "data-slot": "tabs-list",
1716
+ className: cn(
1717
+ "bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
1718
+ className
1719
+ ),
1720
+ ...props
1721
+ }
1722
+ );
1723
+ }
1724
+ function TabsTrigger({
1725
+ className,
1726
+ ...props
1727
+ }) {
1728
+ return /* @__PURE__ */ jsx(
1729
+ TabsPrimitive.Trigger,
1730
+ {
1731
+ "data-slot": "tabs-trigger",
1732
+ className: cn(
1733
+ "data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
1734
+ className
1735
+ ),
1736
+ ...props
1737
+ }
1738
+ );
1739
+ }
1740
+ function TabsContent({
1741
+ className,
1742
+ ...props
1743
+ }) {
1744
+ return /* @__PURE__ */ jsx(
1745
+ TabsPrimitive.Content,
1746
+ {
1747
+ "data-slot": "tabs-content",
1748
+ className: cn("flex-1 outline-none", className),
1749
+ ...props
1750
+ }
1751
+ );
1752
+ }
1753
+ function Slider({
1754
+ className,
1755
+ defaultValue,
1756
+ value,
1757
+ min = 0,
1758
+ max = 100,
1759
+ ...props
1760
+ }) {
1761
+ const _values = React.useMemo(
1762
+ () => Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min, max],
1763
+ [value, defaultValue, min, max]
1764
+ );
1765
+ return /* @__PURE__ */ jsxs(
1766
+ SliderPrimitive.Root,
1767
+ {
1768
+ "data-slot": "slider",
1769
+ defaultValue,
1770
+ value,
1771
+ min,
1772
+ max,
1773
+ className: cn(
1774
+ "relative flex w-full cursor-pointer touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
1775
+ className
1776
+ ),
1777
+ ...props,
1778
+ children: [
1779
+ /* @__PURE__ */ jsx(
1780
+ SliderPrimitive.Track,
1781
+ {
1782
+ "data-slot": "slider-track",
1783
+ className: cn(
1784
+ "bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
1785
+ ),
1786
+ children: /* @__PURE__ */ jsx(
1787
+ SliderPrimitive.Range,
1788
+ {
1789
+ "data-slot": "slider-range",
1790
+ className: cn(
1791
+ "bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
1792
+ )
1793
+ }
1794
+ )
1795
+ }
1796
+ ),
1797
+ Array.from({ length: _values.length }, (_, index) => /* @__PURE__ */ jsx(
1798
+ SliderPrimitive.Thumb,
1799
+ {
1800
+ "data-slot": "slider-thumb",
1801
+ className: "border-primary ring-ring/50 block size-4 shrink-0 cursor-pointer rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
1802
+ },
1803
+ index
1804
+ ))
1805
+ ]
1806
+ }
1807
+ );
1808
+ }
1809
+ function VolumeControls({ className, compact }) {
1810
+ const {
1811
+ masterVolume,
1812
+ musicVolume,
1813
+ sfxVolume,
1814
+ setMasterVolume,
1815
+ setMusicVolume,
1816
+ setSfxVolume
1817
+ } = useVolumeStore();
1818
+ return /* @__PURE__ */ jsxs("div", { className: cn("flex flex-col gap-3", compact && "gap-1", className), children: [
1819
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
1820
+ /* @__PURE__ */ jsx(Volume2, { className: "text-muted-foreground h-4 w-4" }),
1821
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Volume" })
1822
+ ] }),
1823
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1824
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1825
+ /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "Master" }),
1826
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1827
+ Math.round(masterVolume * 100),
1828
+ "%"
1829
+ ] })
1830
+ ] }),
1831
+ /* @__PURE__ */ jsx(
1832
+ Slider,
1833
+ {
1834
+ value: [masterVolume * 100],
1835
+ onValueChange: (values) => setMasterVolume(values[0] / 100),
1836
+ min: 0,
1837
+ max: 100,
1838
+ step: 1,
1839
+ className: "w-full",
1840
+ "aria-label": "Master volume"
1841
+ }
1842
+ )
1843
+ ] }),
1844
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1845
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1846
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
1847
+ /* @__PURE__ */ jsx(Music, { className: "text-muted-foreground h-3 w-3" }),
1848
+ /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "Music" })
1849
+ ] }),
1850
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1851
+ Math.round(musicVolume * 100),
1852
+ "%"
1853
+ ] })
1854
+ ] }),
1855
+ /* @__PURE__ */ jsx(
1856
+ Slider,
1857
+ {
1858
+ value: [musicVolume * 100],
1859
+ onValueChange: (values) => setMusicVolume(values[0] / 100),
1860
+ min: 0,
1861
+ max: 100,
1862
+ step: 1,
1863
+ className: "w-full",
1864
+ "aria-label": "Music volume"
1865
+ }
1866
+ )
1867
+ ] }),
1868
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1869
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1870
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
1871
+ /* @__PURE__ */ jsx(Headphones, { className: "text-muted-foreground h-3 w-3" }),
1872
+ /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "SFX" })
1873
+ ] }),
1874
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1875
+ Math.round(sfxVolume * 100),
1876
+ "%"
1877
+ ] })
1878
+ ] }),
1879
+ /* @__PURE__ */ jsx(
1880
+ Slider,
1881
+ {
1882
+ value: [sfxVolume * 100],
1883
+ onValueChange: (values) => setSfxVolume(values[0] / 100),
1884
+ min: 0,
1885
+ max: 100,
1886
+ step: 1,
1887
+ className: "w-full",
1888
+ "aria-label": "SFX volume"
1889
+ }
1890
+ )
1891
+ ] })
1892
+ ] });
1893
+ }
1894
+ var statusCopy = {
1895
+ idle: "Idle",
1896
+ connecting: "Waiting for server\u2026",
1897
+ connected: "Ready for controllers",
1898
+ disconnected: "Disconnected",
1899
+ reconnecting: "Reconnecting\u2026"
1900
+ };
1901
+ var AirJamOverlay = () => {
1902
+ const host = useAirJamHost();
1903
+ const {
1904
+ roomId,
1905
+ joinUrl,
1906
+ connectionStatus,
1907
+ players,
1908
+ lastError,
1909
+ gameState,
1910
+ toggleGameState,
1911
+ isChildMode
1912
+ } = host;
1913
+ const [qrUrl, setQrUrl] = useState(null);
1914
+ const [qrError, setQrError] = useState(null);
1915
+ const [copied, setCopied] = useState(false);
1916
+ const [copiedPlayerId, setCopiedPlayerId] = useState(null);
1917
+ useEffect(() => {
1918
+ if (isChildMode) return;
1919
+ let mounted = true;
1920
+ QRCode.toDataURL(joinUrl, {
1921
+ margin: 1,
1922
+ color: {
1923
+ dark: "#0f172a",
1924
+ light: "#ffffff"
1925
+ },
1926
+ width: 320
1927
+ }).then((value) => {
1928
+ if (mounted) {
1929
+ setQrUrl(value);
1930
+ setQrError(null);
1931
+ }
1932
+ }).catch((err) => {
1933
+ if (mounted) {
1934
+ setQrError(err.message);
1236
1935
  }
1237
1936
  });
1238
1937
  return () => {
1239
1938
  mounted = false;
1240
1939
  };
1241
1940
  }, [joinUrl, isChildMode]);
1941
+ const handleCopyUrl = async () => {
1942
+ if (!joinUrl) return;
1943
+ try {
1944
+ await navigator.clipboard.writeText(joinUrl);
1945
+ setCopied(true);
1946
+ setTimeout(() => setCopied(false), 2e3);
1947
+ } catch {
1948
+ const textArea = document.createElement("textarea");
1949
+ textArea.value = joinUrl;
1950
+ textArea.style.position = "fixed";
1951
+ textArea.style.opacity = "0";
1952
+ document.body.appendChild(textArea);
1953
+ textArea.select();
1954
+ try {
1955
+ document.execCommand("copy");
1956
+ setCopied(true);
1957
+ setTimeout(() => setCopied(false), 2e3);
1958
+ } catch {
1959
+ }
1960
+ document.body.removeChild(textArea);
1961
+ }
1962
+ };
1963
+ const handleOpenInNewTab = () => {
1964
+ if (joinUrl) {
1965
+ window.open(joinUrl, "_blank", "noopener,noreferrer");
1966
+ }
1967
+ };
1968
+ const handleCopyPlayerId = async (playerId) => {
1969
+ try {
1970
+ await navigator.clipboard.writeText(playerId);
1971
+ console.log(`Copied player ID: ${playerId}`);
1972
+ setCopiedPlayerId(playerId);
1973
+ setTimeout(() => setCopiedPlayerId(null), 1e3);
1974
+ } catch {
1975
+ const textArea = document.createElement("textarea");
1976
+ textArea.value = playerId;
1977
+ textArea.style.position = "fixed";
1978
+ textArea.style.opacity = "0";
1979
+ document.body.appendChild(textArea);
1980
+ textArea.select();
1981
+ try {
1982
+ document.execCommand("copy");
1983
+ console.log(`Copied player ID: ${playerId}`);
1984
+ setCopiedPlayerId(playerId);
1985
+ setTimeout(() => setCopiedPlayerId(null), 1e3);
1986
+ } catch {
1987
+ }
1988
+ document.body.removeChild(textArea);
1989
+ }
1990
+ };
1242
1991
  const connectionVariant = useMemo(() => {
1243
1992
  switch (connectionStatus) {
1244
1993
  case "connected":
@@ -1251,7 +2000,7 @@ var AirJamOverlay = ({
1251
2000
  }
1252
2001
  }, [connectionStatus]);
1253
2002
  if (isChildMode) return null;
1254
- return /* @__PURE__ */ jsxs(Fragment, { children: [
2003
+ return /* @__PURE__ */ jsxs("div", { className: "dark", children: [
1255
2004
  !isChildMode && /* @__PURE__ */ jsx("div", { className: "pointer-events-none absolute inset-x-0 top-0 z-99999", children: /* @__PURE__ */ jsx("div", { className: "mx-auto w-full", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-4 py-2", children: [
1256
2005
  /* @__PURE__ */ jsx("div", { className: "flex items-center gap-3", children: /* @__PURE__ */ jsxs("div", { children: [
1257
2006
  /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs tracking-[0.18em] uppercase", children: "Room" }),
@@ -1259,35 +2008,19 @@ var AirJamOverlay = ({
1259
2008
  ] }) }),
1260
2009
  /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
1261
2010
  players.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-center -space-x-2", children: [
1262
- players.slice(0, 4).map((player) => /* @__PURE__ */ jsx(
1263
- Avatar,
1264
- {
1265
- className: "h-8 w-8 border-2",
1266
- style: {
1267
- borderColor: player.color || "hsl(var(--border))"
1268
- },
1269
- children: /* @__PURE__ */ jsx(
1270
- AvatarImage,
1271
- {
1272
- src: getPlayerAvatarUrl(player.id),
1273
- alt: player.label
1274
- }
1275
- )
1276
- },
1277
- player.id
1278
- )),
2011
+ players.slice(0, 4).map((player) => /* @__PURE__ */ jsx(PlayerAvatar, { player, size: "sm" }, player.id)),
1279
2012
  players.length > 4 && /* @__PURE__ */ jsxs("div", { className: "border-background bg-muted flex h-8 w-8 items-center justify-center rounded-full border-2 text-xs font-medium", children: [
1280
2013
  "+",
1281
2014
  players.length - 4
1282
2015
  ] })
1283
2016
  ] }),
1284
- onTogglePlayPause && /* @__PURE__ */ jsx(
2017
+ /* @__PURE__ */ jsx(
1285
2018
  Button,
1286
2019
  {
1287
2020
  type: "button",
1288
2021
  variant: "ghost",
1289
2022
  size: "icon",
1290
- onClick: onTogglePlayPause,
2023
+ onClick: toggleGameState,
1291
2024
  "aria-label": gameState === "playing" ? "Pause" : "Play",
1292
2025
  className: "h-8 w-8",
1293
2026
  children: gameState === "playing" ? /* @__PURE__ */ jsx(Pause, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Play, { className: "h-4 w-4" })
@@ -1295,7 +2028,7 @@ var AirJamOverlay = ({
1295
2028
  )
1296
2029
  ] })
1297
2030
  ] }) }) }),
1298
- gameState === "paused" && /* @__PURE__ */ jsx("div", { className: "pointer-events-none fixed inset-0 z-99998 flex items-center justify-center p-4", children: /* @__PURE__ */ jsx("div", { className: "pointer-events-auto w-full max-w-2xl", children: /* @__PURE__ */ jsx(Card, { className: "bg-card/20 flex h-[80vh] flex-col overflow-hidden border py-0 shadow-lg backdrop-blur-sm", children: /* @__PURE__ */ jsxs(
2031
+ gameState === "paused" && /* @__PURE__ */ jsx("div", { className: "pointer-events-none fixed inset-0 z-99998 flex items-center justify-center p-4", children: /* @__PURE__ */ jsx("div", { className: "pointer-events-auto w-full max-w-2xl", children: /* @__PURE__ */ jsx(Card, { className: "bg-card/20 flex max-h-[85vh] flex-col overflow-hidden border py-0 shadow-lg backdrop-blur-sm", children: /* @__PURE__ */ jsxs(
1299
2032
  Tabs,
1300
2033
  {
1301
2034
  defaultValue: isChildMode ? "settings" : "room-code",
@@ -1341,66 +2074,108 @@ var AirJamOverlay = ({
1341
2074
  {
1342
2075
  value: "room-code",
1343
2076
  className: "mt-0 min-h-0 flex-1 overflow-y-auto",
1344
- children: /* @__PURE__ */ jsxs("div", { className: "space-y-6 pb-6", children: [
1345
- /* @__PURE__ */ jsxs(CardHeader, { className: "pt-6 text-center", children: [
1346
- /* @__PURE__ */ jsx(CardTitle, { className: "text-4xl font-bold tracking-wider", children: roomId }),
1347
- /* @__PURE__ */ jsx(
1348
- Badge,
1349
- {
1350
- variant: connectionVariant,
1351
- className: "mx-auto mt-3",
1352
- children: statusCopy[connectionStatus]
1353
- }
1354
- )
1355
- ] }),
1356
- /* @__PURE__ */ jsx(CardContent, { className: "space-y-6", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center space-y-4", children: [
1357
- /* @__PURE__ */ jsx(CardDescription, { className: "text-xs tracking-[0.18em] uppercase", children: "Join URL" }),
1358
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-center font-mono text-xs break-all", children: joinUrl }),
1359
- /* @__PURE__ */ jsx("div", { className: "border-border bg-card w-48 overflow-hidden rounded-lg border-2 shadow-md", children: qrUrl ? /* @__PURE__ */ jsx(
2077
+ children: /* @__PURE__ */ jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-6 md:grid-cols-[auto_1fr]", children: [
2078
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-start gap-4", children: [
2079
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
2080
+ /* @__PURE__ */ jsx(CardTitle, { className: "text-3xl font-bold tracking-wider", children: roomId }),
2081
+ /* @__PURE__ */ jsx(
2082
+ Badge,
2083
+ {
2084
+ variant: connectionVariant,
2085
+ className: "w-fit",
2086
+ children: statusCopy[connectionStatus]
2087
+ }
2088
+ )
2089
+ ] }),
2090
+ /* @__PURE__ */ jsx("div", { className: "border-border bg-card w-48 shrink-0 overflow-hidden rounded-lg border-2 shadow-md", children: qrUrl ? /* @__PURE__ */ jsx(
1360
2091
  "img",
1361
2092
  {
1362
2093
  src: qrUrl,
1363
2094
  alt: `Join room ${roomId}`,
1364
2095
  className: "w-full rounded bg-white"
1365
2096
  }
1366
- ) : /* @__PURE__ */ jsx("div", { className: "text-muted-foreground flex h-48 items-center justify-center text-sm", children: qrError ? `QR failed: ${qrError}` : "Generating QR code\u2026" }) }),
1367
- /* @__PURE__ */ jsx("div", { className: "w-full", children: players.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-muted-foreground py-4 text-center text-sm", children: "Waiting for controllers to join\u2026" }) : /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
1368
- /* @__PURE__ */ jsxs("p", { className: "text-foreground text-center text-sm font-medium", children: [
2097
+ ) : /* @__PURE__ */ jsx("div", { className: "text-muted-foreground flex h-48 items-center justify-center text-sm", children: qrError ? `QR failed: ${qrError}` : "Generating QR code\u2026" }) })
2098
+ ] }),
2099
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-6", children: [
2100
+ /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
2101
+ /* @__PURE__ */ jsx(CardDescription, { className: "text-xs tracking-[0.18em] uppercase", children: "Join URL" }),
2102
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
2103
+ /* @__PURE__ */ jsx(
2104
+ "input",
2105
+ {
2106
+ type: "text",
2107
+ readOnly: true,
2108
+ value: joinUrl,
2109
+ className: "bg-background border-input text-foreground focus:ring-ring flex h-10 w-full rounded-md border px-3 py-2 font-mono text-xs focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
2110
+ }
2111
+ ),
2112
+ /* @__PURE__ */ jsx(
2113
+ Button,
2114
+ {
2115
+ type: "button",
2116
+ variant: "outline",
2117
+ size: "icon",
2118
+ onClick: handleCopyUrl,
2119
+ className: "h-10 shrink-0",
2120
+ "aria-label": "Copy join URL",
2121
+ children: copied ? /* @__PURE__ */ jsx(Check, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4" })
2122
+ }
2123
+ ),
2124
+ /* @__PURE__ */ jsx(
2125
+ Button,
2126
+ {
2127
+ type: "button",
2128
+ variant: "outline",
2129
+ size: "icon",
2130
+ onClick: handleOpenInNewTab,
2131
+ className: "h-10 shrink-0",
2132
+ "aria-label": "Open join URL in new tab",
2133
+ children: /* @__PURE__ */ jsx(ExternalLink, { className: "h-4 w-4" })
2134
+ }
2135
+ )
2136
+ ] })
2137
+ ] }),
2138
+ /* @__PURE__ */ jsx("div", { className: "space-y-3", children: players.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-white", children: "Waiting for controllers to join\u2026" }) : /* @__PURE__ */ jsxs(Fragment, { children: [
2139
+ /* @__PURE__ */ jsxs("p", { className: "text-foreground text-sm font-medium", children: [
1369
2140
  "Connected Players (",
1370
2141
  players.length,
1371
2142
  ")"
1372
2143
  ] }),
1373
- /* @__PURE__ */ jsx("ul", { className: "flex flex-wrap items-center justify-center gap-4", children: players.map((player) => /* @__PURE__ */ jsxs(
2144
+ /* @__PURE__ */ jsx("ul", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3", children: players.map((player) => /* @__PURE__ */ jsx(
1374
2145
  "li",
1375
2146
  {
1376
- className: "flex flex-col items-center gap-2",
1377
- children: [
2147
+ className: "flex min-w-0 flex-col items-start gap-2",
2148
+ children: /* @__PURE__ */ jsxs("div", { className: "flex w-full min-w-0 items-center gap-2", children: [
1378
2149
  /* @__PURE__ */ jsx(
1379
- "img",
2150
+ PlayerAvatar,
1380
2151
  {
1381
- src: getPlayerAvatarUrl(player.id),
1382
- alt: player.label,
1383
- className: "bg-secondary/30 h-16 w-16 rounded-full border-4 shadow-md",
1384
- style: {
1385
- borderColor: player.color || "hsl(var(--border))"
1386
- }
2152
+ player,
2153
+ size: "md"
1387
2154
  }
1388
2155
  ),
1389
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-0.5", children: [
1390
- /* @__PURE__ */ jsx("span", { className: "text-card-foreground max-w-[100px] truncate text-center text-sm font-medium", children: player.label }),
1391
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground font-mono text-xs", children: player.id.slice(0, 8) })
2156
+ /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden", children: [
2157
+ /* @__PURE__ */ jsx("span", { className: "text-card-foreground truncate text-sm font-medium", children: player.label }),
2158
+ /* @__PURE__ */ jsx(
2159
+ "div",
2160
+ {
2161
+ onClick: () => handleCopyPlayerId(player.id),
2162
+ className: "text-muted-foreground m-0 inline min-w-0 cursor-pointer truncate border-0 font-mono text-xs transition-colors hover:text-white",
2163
+ title: "Click to copy player ID",
2164
+ children: copiedPlayerId === player.id ? "Copied!" : player.id.slice(0, 8)
2165
+ }
2166
+ )
1392
2167
  ] })
1393
- ]
2168
+ ] })
1394
2169
  },
1395
2170
  player.id
1396
2171
  )) })
1397
2172
  ] }) }),
1398
2173
  lastError && /* @__PURE__ */ jsx(Alert, { variant: "destructive", className: "w-full", children: /* @__PURE__ */ jsx(AlertDescription, { children: lastError }) }),
1399
- onTogglePlayPause && /* @__PURE__ */ jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxs(
2174
+ /* @__PURE__ */ jsx("div", { className: "mt-auto flex justify-end", children: /* @__PURE__ */ jsxs(
1400
2175
  Button,
1401
2176
  {
1402
2177
  type: "button",
1403
- onClick: onTogglePlayPause,
2178
+ onClick: toggleGameState,
1404
2179
  size: "lg",
1405
2180
  children: [
1406
2181
  /* @__PURE__ */ jsx(Play, { className: "mr-2 h-5 w-5" }),
@@ -1408,8 +2183,8 @@ var AirJamOverlay = ({
1408
2183
  ]
1409
2184
  }
1410
2185
  ) })
1411
- ] }) })
1412
- ] })
2186
+ ] })
2187
+ ] }) })
1413
2188
  }
1414
2189
  ),
1415
2190
  isChildMode && /* @__PURE__ */ jsx(
@@ -1417,54 +2192,42 @@ var AirJamOverlay = ({
1417
2192
  {
1418
2193
  value: "info",
1419
2194
  className: "mt-0 min-h-0 flex-1 overflow-y-auto",
1420
- children: /* @__PURE__ */ jsxs("div", { className: "space-y-6 pb-6", children: [
1421
- /* @__PURE__ */ jsxs(CardHeader, { className: "pt-6 text-center", children: [
2195
+ children: /* @__PURE__ */ jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
2196
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
1422
2197
  /* @__PURE__ */ jsx(CardTitle, { className: "text-2xl font-bold tracking-wider", children: "Connected to Platform" }),
1423
- /* @__PURE__ */ jsx(CardDescription, { className: "mt-2", children: "This game is running inside the Air Jam Platform." })
1424
- ] }),
1425
- /* @__PURE__ */ jsx(CardContent, { className: "space-y-6", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center space-y-4", children: [
1426
- /* @__PURE__ */ jsx("div", { className: "w-full", children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
1427
- /* @__PURE__ */ jsxs("p", { className: "text-foreground text-center text-sm font-medium", children: [
1428
- "Connected Players (",
1429
- players.length,
1430
- ")"
1431
- ] }),
1432
- /* @__PURE__ */ jsx("ul", { className: "flex flex-wrap items-center justify-center gap-4", children: players.map((player) => /* @__PURE__ */ jsxs(
1433
- "li",
1434
- {
1435
- className: "flex flex-col items-center gap-2",
1436
- children: [
1437
- /* @__PURE__ */ jsx(
1438
- "img",
1439
- {
1440
- src: getPlayerAvatarUrl(player.id),
1441
- alt: player.label,
1442
- className: "bg-secondary/30 h-16 w-16 rounded-full border-4 shadow-md",
1443
- style: {
1444
- borderColor: player.color || "hsl(var(--border))"
1445
- }
1446
- }
1447
- ),
1448
- /* @__PURE__ */ jsx("div", { className: "flex flex-col items-center gap-0.5", children: /* @__PURE__ */ jsx("span", { className: "text-card-foreground max-w-[100px] truncate text-center text-sm font-medium", children: player.label }) })
1449
- ]
1450
- },
1451
- player.id
1452
- )) })
1453
- ] }) }),
1454
- onTogglePlayPause && /* @__PURE__ */ jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxs(
1455
- Button,
1456
- {
1457
- type: "button",
1458
- onClick: onTogglePlayPause,
1459
- size: "lg",
1460
- children: [
1461
- /* @__PURE__ */ jsx(Play, { className: "mr-2 h-5 w-5" }),
1462
- "Resume Game"
1463
- ]
1464
- }
1465
- ) })
1466
- ] }) })
1467
- ] })
2198
+ /* @__PURE__ */ jsx(CardDescription, { children: "This game is running inside the Air Jam Platform." })
2199
+ ] }),
2200
+ /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
2201
+ /* @__PURE__ */ jsxs("p", { className: "text-foreground text-sm font-medium", children: [
2202
+ "Connected Players (",
2203
+ players.length,
2204
+ ")"
2205
+ ] }),
2206
+ /* @__PURE__ */ jsx("ul", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3", children: players.map((player) => /* @__PURE__ */ jsx(
2207
+ "li",
2208
+ {
2209
+ className: "flex min-w-0 flex-col items-start gap-2",
2210
+ children: /* @__PURE__ */ jsxs("div", { className: "flex w-full min-w-0 items-center gap-2", children: [
2211
+ /* @__PURE__ */ jsx(PlayerAvatar, { player, size: "md" }),
2212
+ /* @__PURE__ */ jsx("div", { className: "flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden", children: /* @__PURE__ */ jsx("span", { className: "text-card-foreground truncate text-sm font-medium", children: player.label }) })
2213
+ ] })
2214
+ },
2215
+ player.id
2216
+ )) })
2217
+ ] }),
2218
+ /* @__PURE__ */ jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxs(
2219
+ Button,
2220
+ {
2221
+ type: "button",
2222
+ onClick: toggleGameState,
2223
+ size: "lg",
2224
+ children: [
2225
+ /* @__PURE__ */ jsx(Play, { className: "mr-2 h-5 w-5" }),
2226
+ "Resume Game"
2227
+ ]
2228
+ }
2229
+ ) })
2230
+ ] }) })
1468
2231
  }
1469
2232
  ),
1470
2233
  /* @__PURE__ */ jsx(
@@ -1555,263 +2318,37 @@ var useFullscreen = () => {
1555
2318
  }, []);
1556
2319
  const enterFullscreen = useCallback(async (element) => {
1557
2320
  try {
1558
- const elem = element || document.documentElement;
1559
- if (elem.requestFullscreen) {
1560
- await elem.requestFullscreen();
1561
- } else if (elem.webkitRequestFullscreen) {
1562
- await elem.webkitRequestFullscreen();
1563
- } else if (elem.mozRequestFullScreen) {
1564
- await elem.mozRequestFullScreen();
1565
- } else if (elem.msRequestFullscreen) {
1566
- await elem.msRequestFullscreen();
1567
- }
1568
- } catch (error) {
1569
- console.error("Error entering fullscreen:", error);
1570
- }
1571
- }, []);
1572
- const toggleFullscreen = useCallback(
1573
- async (element) => {
1574
- if (isFullscreen) {
1575
- await exitFullscreen();
1576
- } else {
1577
- await enterFullscreen(element);
1578
- }
1579
- },
1580
- [isFullscreen, exitFullscreen, enterFullscreen]
1581
- );
1582
- return {
1583
- isFullscreen,
1584
- enterFullscreen,
1585
- exitFullscreen,
1586
- toggleFullscreen
1587
- };
1588
- };
1589
-
1590
- // src/utils/mode.ts
1591
- var detectRunMode = () => {
1592
- if (typeof window === "undefined") {
1593
- return "standalone";
1594
- }
1595
- try {
1596
- return window.self !== window.top ? "platform" : "standalone";
1597
- } catch {
1598
- return "platform";
1599
- }
1600
- };
1601
-
1602
- // src/utils/network-ip.ts
1603
- var isVirtualNetwork = (ip) => {
1604
- if (ip.startsWith("192.168.64.") || ip.startsWith("192.168.65.")) {
1605
- return true;
1606
- }
1607
- if (ip.startsWith("172.17.")) {
1608
- return true;
1609
- }
1610
- if (ip.startsWith("172.18.") || ip.startsWith("172.19.")) {
1611
- return true;
1612
- }
1613
- if (ip.startsWith("169.254.")) {
1614
- return true;
1615
- }
1616
- return false;
1617
- };
1618
- var scoreIp = (ip) => {
1619
- if (ip.startsWith("192.168.")) {
1620
- const parts = ip.split(".");
1621
- const thirdOctet = parseInt(parts[2] || "0", 10);
1622
- if (thirdOctet < 64) {
1623
- return 100 - thirdOctet;
1624
- }
1625
- return 10;
1626
- }
1627
- if (ip.startsWith("10.")) {
1628
- return 50;
1629
- }
1630
- if (/^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip)) {
1631
- return 30;
1632
- }
1633
- return 0;
1634
- };
1635
- var getLocalNetworkIp = () => {
1636
- return new Promise((resolve) => {
1637
- if (typeof window === "undefined" || typeof RTCPeerConnection === "undefined") {
1638
- resolve(null);
1639
- return;
1640
- }
1641
- const pc = new RTCPeerConnection({
1642
- iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
1643
- });
1644
- const candidates = [];
1645
- let candidateGatheringComplete = false;
1646
- const resolveOnce = (ip) => {
1647
- pc.close();
1648
- resolve(ip);
1649
- };
1650
- const timeout = setTimeout(() => {
1651
- if (candidateGatheringComplete) {
1652
- pickBestCandidate();
1653
- } else {
1654
- setTimeout(() => {
1655
- pickBestCandidate();
1656
- }, 500);
1657
- }
1658
- }, 3e3);
1659
- const pickBestCandidate = () => {
1660
- if (candidates.length === 0) {
1661
- resolveOnce(null);
1662
- return;
1663
- }
1664
- candidates.sort((a, b) => b.score - a.score);
1665
- const best = candidates[0];
1666
- clearTimeout(timeout);
1667
- resolveOnce(best.ip);
1668
- };
1669
- pc.onicecandidate = (event) => {
1670
- if (event.candidate) {
1671
- const candidate = event.candidate.candidate;
1672
- const match = candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3})/);
1673
- if (match) {
1674
- const ip = match[1];
1675
- if (ip === "127.0.0.1") {
1676
- return;
1677
- }
1678
- const isPrivate = ip.startsWith("192.168.") || ip.startsWith("10.") || /^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip);
1679
- if (isPrivate && !isVirtualNetwork(ip)) {
1680
- const score = scoreIp(ip);
1681
- candidates.push({ ip, score });
1682
- }
1683
- }
1684
- } else {
1685
- candidateGatheringComplete = true;
1686
- setTimeout(() => {
1687
- pickBestCandidate();
1688
- }, 200);
1689
- }
1690
- };
1691
- pc.createDataChannel("");
1692
- pc.createOffer().then((offer) => pc.setLocalDescription(offer)).catch(() => {
1693
- clearTimeout(timeout);
1694
- resolveOnce(null);
1695
- });
1696
- });
1697
- };
1698
-
1699
- // src/utils/url-builder.ts
1700
- var UrlBuilder = class {
1701
- cachedLocalIp = null;
1702
- ipDetectionPromise = null;
1703
- /**
1704
- * Get the local network IP address with caching.
1705
- * First call triggers detection, subsequent calls return cached value.
1706
- */
1707
- async getLocalIp() {
1708
- if (this.cachedLocalIp !== null) {
1709
- return this.cachedLocalIp;
1710
- }
1711
- if (this.ipDetectionPromise !== null) {
1712
- return this.ipDetectionPromise;
1713
- }
1714
- this.ipDetectionPromise = getLocalNetworkIp().then((ip) => {
1715
- this.cachedLocalIp = ip;
1716
- this.ipDetectionPromise = null;
1717
- return ip;
1718
- });
1719
- return this.ipDetectionPromise;
1720
- }
1721
- /**
1722
- * Clear the cached IP address.
1723
- * Useful for testing or when network changes are detected.
1724
- */
1725
- clearCache() {
1726
- this.cachedLocalIp = null;
1727
- this.ipDetectionPromise = null;
1728
- }
1729
- /**
1730
- * Normalize a URL for mobile access.
1731
- * Replaces localhost with the local network IP.
1732
- */
1733
- async normalizeForMobile(url) {
1734
- if (typeof window === "undefined") return url;
1735
- try {
1736
- const urlObj = new URL(url);
1737
- if (urlObj.hostname === "localhost" || urlObj.hostname === "127.0.0.1") {
1738
- const localIp = await this.getLocalIp();
1739
- if (localIp) {
1740
- urlObj.hostname = localIp;
1741
- return urlObj.toString();
1742
- }
1743
- urlObj.hostname = window.location.hostname;
1744
- return urlObj.toString();
1745
- }
1746
- return url;
1747
- } catch {
1748
- return url;
1749
- }
1750
- }
1751
- /**
1752
- * Build a controller URL with room code.
1753
- * Automatically uses local IP when running on localhost.
1754
- */
1755
- async buildControllerUrl(roomId, options) {
1756
- const path = options?.path || DEFAULT_CONTROLLER_PATH;
1757
- if (options?.host) {
1758
- const url2 = new URL(path, this.normalizeOrigin(options.host));
1759
- url2.searchParams.set("room", roomId);
1760
- return url2.toString();
1761
- }
1762
- let base;
1763
- if (typeof window === "undefined") {
1764
- base = `http://localhost:${DEFAULT_SERVER_PORT}`;
1765
- } else {
1766
- const currentUrl = new URL(window.location.href);
1767
- if (!this.isLocalhost(currentUrl.hostname)) {
1768
- base = currentUrl.origin;
1769
- } else {
1770
- const localIp = await this.getLocalIp();
1771
- if (localIp) {
1772
- const port = currentUrl.port;
1773
- base = port ? `http://${localIp}:${port}` : `http://${localIp}`;
1774
- } else {
1775
- base = currentUrl.origin;
1776
- }
1777
- }
1778
- }
1779
- const url = new URL(path, base);
1780
- url.searchParams.set("room", roomId);
1781
- return url.toString();
1782
- }
1783
- /**
1784
- * Resolve the server URL.
1785
- * Uses explicit URL if provided, otherwise infers from window location.
1786
- */
1787
- resolveServerUrl(explicit) {
1788
- if (explicit) {
1789
- return this.normalizeOrigin(explicit);
1790
- }
1791
- if (typeof window !== "undefined") {
1792
- const url = new URL(window.location.href);
1793
- url.port = String(DEFAULT_SERVER_PORT);
1794
- return url.origin;
1795
- }
1796
- return `http://localhost:${DEFAULT_SERVER_PORT}`;
1797
- }
1798
- /**
1799
- * Check if a hostname is localhost.
1800
- */
1801
- isLocalhost(hostname) {
1802
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
1803
- }
1804
- /**
1805
- * Normalize an origin string to ensure it has a protocol.
1806
- */
1807
- normalizeOrigin(origin) {
1808
- if (!origin.includes("://")) {
1809
- return `http://${origin}`;
2321
+ const elem = element || document.documentElement;
2322
+ if (elem.requestFullscreen) {
2323
+ await elem.requestFullscreen();
2324
+ } else if (elem.webkitRequestFullscreen) {
2325
+ await elem.webkitRequestFullscreen();
2326
+ } else if (elem.mozRequestFullScreen) {
2327
+ await elem.mozRequestFullScreen();
2328
+ } else if (elem.msRequestFullscreen) {
2329
+ await elem.msRequestFullscreen();
2330
+ }
2331
+ } catch (error) {
2332
+ console.error("Error entering fullscreen:", error);
1810
2333
  }
1811
- return origin;
1812
- }
2334
+ }, []);
2335
+ const toggleFullscreen = useCallback(
2336
+ async (element) => {
2337
+ if (isFullscreen) {
2338
+ await exitFullscreen();
2339
+ } else {
2340
+ await enterFullscreen(element);
2341
+ }
2342
+ },
2343
+ [isFullscreen, exitFullscreen, enterFullscreen]
2344
+ );
2345
+ return {
2346
+ isFullscreen,
2347
+ enterFullscreen,
2348
+ exitFullscreen,
2349
+ toggleFullscreen
2350
+ };
1813
2351
  };
1814
- var urlBuilder = new UrlBuilder();
1815
2352
  var extractRoomCode = (text) => {
1816
2353
  try {
1817
2354
  const url = new URL(text);
@@ -2083,935 +2620,563 @@ var QRScannerDialog = ({
2083
2620
  type: "button",
2084
2621
  variant: "outline",
2085
2622
  onClick: onClose,
2086
- className: "flex-1 py-6",
2087
- children: "Cancel"
2088
- }
2089
- ),
2090
- /* @__PURE__ */ jsx(
2091
- Button,
2092
- {
2093
- type: "button",
2094
- onClick: handleSubmit,
2095
- disabled: !isValid,
2096
- className: "flex-1 py-6",
2097
- children: "Connect"
2098
- }
2099
- )
2100
- ] })
2101
- ] });
2102
- };
2103
- var getPlayerAvatarUrl2 = (playerId) => {
2104
- return `https://api.dicebear.com/9.x/adventurer-neutral/svg?seed=${encodeURIComponent(
2105
- playerId
2106
- )}`;
2107
- };
2108
- var describeStatus = (status) => {
2109
- switch (status) {
2110
- case "connected":
2111
- return "Connected to host";
2112
- case "connecting":
2113
- return "Connecting\u2026";
2114
- case "reconnecting":
2115
- return "Trying to reconnect\u2026";
2116
- case "disconnected":
2117
- return "Disconnected";
2118
- case "idle":
2119
- default:
2120
- return "Idle";
2121
- }
2122
- };
2123
- var orientationMatches = (required) => {
2124
- if (required === "any") return true;
2125
- if (typeof window === "undefined" || !window.matchMedia) return true;
2126
- const matcher = window.matchMedia(`(orientation: ${required})`);
2127
- return matcher.matches;
2128
- };
2129
- var ControllerShell = ({
2130
- roomId,
2131
- connectionStatus,
2132
- requiredOrientation = "landscape",
2133
- children,
2134
- gameState = "paused",
2135
- onTogglePlayPause,
2136
- onReconnect,
2137
- onRefresh,
2138
- customActions
2139
- }) => {
2140
- const isChildMode = useMemo(() => detectRunMode() === "platform", []);
2141
- const [isOrientationOk, setOrientationOk] = useState(
2142
- () => orientationMatches(requiredOrientation)
2143
- );
2144
- const [isScannerOpen, setIsScannerOpen] = useState(false);
2145
- const { isFullscreen, toggleFullscreen } = useFullscreen();
2146
- const { store } = useAirJamContext();
2147
- const { controllerId, players } = useStore(
2148
- store,
2149
- useShallow(
2150
- (state) => ({
2151
- controllerId: state.controllerId,
2152
- players: state.players
2153
- })
2154
- )
2155
- );
2156
- const currentPlayer = useMemo(() => {
2157
- if (!controllerId) return null;
2158
- const found = players.find((p) => p.id === controllerId);
2159
- if (!found && connectionStatus === "connected" && players.length > 0) ;
2160
- return found || null;
2161
- }, [controllerId, players, connectionStatus]);
2162
- useEffect(() => {
2163
- if (requiredOrientation === "any") {
2164
- return;
2165
- }
2166
- const media = window.matchMedia(`(orientation: ${requiredOrientation})`);
2167
- const handleChange = () => setOrientationOk(media.matches);
2168
- handleChange();
2169
- media.addEventListener("change", handleChange);
2170
- return () => media.removeEventListener("change", handleChange);
2171
- }, [requiredOrientation]);
2172
- const orientationOk = requiredOrientation === "any" ? true : isOrientationOk;
2173
- const statusDotColor = useMemo(() => {
2174
- switch (connectionStatus) {
2175
- case "connected":
2176
- return "bg-green-500";
2177
- case "connecting":
2178
- case "reconnecting":
2179
- return "bg-yellow-500";
2180
- case "disconnected":
2181
- default:
2182
- return "bg-red-500";
2183
- }
2184
- }, [connectionStatus]);
2185
- if (isChildMode) {
2186
- return /* @__PURE__ */ jsx("div", { className: "text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden bg-transparent select-none", children: /* @__PURE__ */ jsxs("main", { className: "relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4", children: [
2187
- !orientationOk && /* @__PURE__ */ jsxs("div", { className: "bg-background/95 absolute inset-0 z-50 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm", children: [
2188
- /* @__PURE__ */ jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2189
- /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2190
- "This game is best experienced in ",
2191
- requiredOrientation,
2192
- " ",
2193
- "orientation."
2194
- ] })
2195
- ] }),
2196
- /* @__PURE__ */ jsx(
2197
- "div",
2198
- {
2199
- className: cn(
2200
- "h-full w-full select-none",
2201
- !orientationOk && "pointer-events-none opacity-30"
2202
- ),
2203
- children
2204
- }
2205
- )
2206
- ] }) });
2207
- }
2208
- return /* @__PURE__ */ jsxs("div", { className: "bg-background text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden select-none", children: [
2209
- /* @__PURE__ */ jsxs("header", { className: "pointer-events-none sticky top-0 z-50 flex items-center justify-between border-b px-6 py-2", children: [
2210
- /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2211
- typeof window !== "undefined" && (currentPlayer || controllerId) && /* @__PURE__ */ jsxs("div", { className: "relative", title: describeStatus(connectionStatus), children: [
2212
- /* @__PURE__ */ jsx(
2213
- Avatar,
2214
- {
2215
- className: "h-8 w-8 border-2",
2216
- style: {
2217
- borderColor: currentPlayer?.color || "hsl(var(--border))"
2218
- },
2219
- children: /* @__PURE__ */ jsx(
2220
- AvatarImage,
2221
- {
2222
- src: getPlayerAvatarUrl2(
2223
- currentPlayer?.id || controllerId || ""
2224
- ),
2225
- alt: currentPlayer?.label || "Player"
2226
- }
2227
- )
2228
- }
2229
- ),
2230
- /* @__PURE__ */ jsx(
2231
- "span",
2232
- {
2233
- className: "absolute right-0 bottom-0 h-3 w-3 rounded-full bg-black",
2234
- "aria-hidden": "true"
2235
- }
2236
- ),
2237
- /* @__PURE__ */ jsx(
2238
- "span",
2239
- {
2240
- className: cn(
2241
- "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
2242
- statusDotColor,
2243
- connectionStatus === "connected" && "animate-pulse"
2244
- ),
2245
- "aria-label": describeStatus(connectionStatus)
2246
- }
2247
- )
2248
- ] }),
2249
- /* @__PURE__ */ jsxs("div", { children: [
2250
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs tracking-[0.24em] uppercase", children: "Room" }),
2251
- /* @__PURE__ */ jsx("p", { className: "text-foreground text-lg font-semibold", children: typeof window !== "undefined" ? roomId ?? "N/A" : "N/A" })
2252
- ] })
2253
- ] }),
2254
- /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2255
- customActions,
2256
- onRefresh && roomId && /* @__PURE__ */ jsx(
2257
- Button,
2258
- {
2259
- type: "button",
2260
- variant: "outline",
2261
- size: "icon",
2262
- onClick: onRefresh,
2263
- disabled: connectionStatus === "connecting" || connectionStatus === "reconnecting",
2264
- "aria-label": "Reconnect",
2265
- title: "Reconnect to room",
2266
- children: /* @__PURE__ */ jsx(
2267
- RefreshCw,
2268
- {
2269
- className: cn(
2270
- "h-5 w-5",
2271
- (connectionStatus === "connecting" || connectionStatus === "reconnecting") && "animate-spin"
2272
- )
2273
- }
2274
- )
2275
- }
2276
- ),
2277
- onReconnect && /* @__PURE__ */ jsx(
2278
- Button,
2279
- {
2280
- type: "button",
2281
- variant: "outline",
2282
- size: "icon",
2283
- onClick: () => setIsScannerOpen(true),
2284
- "aria-label": "Scan QR code to reconnect",
2285
- title: "Scan QR code to reconnect",
2286
- children: /* @__PURE__ */ jsx(QrCode, { className: "h-5 w-5" })
2287
- }
2288
- ),
2289
- onTogglePlayPause && /* @__PURE__ */ jsx(
2290
- Button,
2291
- {
2292
- type: "button",
2293
- variant: "outline",
2294
- size: "icon",
2295
- onClick: onTogglePlayPause,
2296
- "aria-label": gameState === "playing" ? "Pause" : "Play",
2297
- title: gameState === "playing" ? "Pause" : "Play",
2298
- children: gameState === "playing" ? /* @__PURE__ */ jsx(Pause, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Play, { className: "h-5 w-5" })
2299
- }
2300
- ),
2301
- /* @__PURE__ */ jsx(
2302
- Button,
2303
- {
2304
- type: "button",
2305
- variant: "outline",
2306
- size: "icon",
2307
- onClick: () => toggleFullscreen(),
2308
- "aria-label": isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2309
- title: isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2310
- children: isFullscreen ? /* @__PURE__ */ jsx(Minimize, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Maximize, { className: "h-5 w-5" })
2311
- }
2312
- )
2313
- ] })
2314
- ] }),
2315
- /* @__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 }) }) }),
2316
- /* @__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: [
2317
- !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: [
2318
- /* @__PURE__ */ jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2319
- /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2320
- "This game is best experienced in ",
2321
- requiredOrientation,
2322
- " ",
2323
- "orientation."
2324
- ] })
2325
- ] }),
2623
+ className: "flex-1 py-6",
2624
+ children: "Cancel"
2625
+ }
2626
+ ),
2326
2627
  /* @__PURE__ */ jsx(
2327
- "div",
2628
+ Button,
2328
2629
  {
2329
- className: cn(
2330
- "h-full w-full select-none",
2331
- !orientationOk && "pointer-events-none opacity-30"
2332
- ),
2333
- children
2630
+ type: "button",
2631
+ onClick: handleSubmit,
2632
+ disabled: !isValid,
2633
+ className: "flex-1 py-6",
2634
+ children: "Connect"
2334
2635
  }
2335
2636
  )
2336
- ] }) }),
2337
- onReconnect && /* @__PURE__ */ jsx(
2338
- QRScannerDialog,
2339
- {
2340
- isOpen: isScannerOpen,
2341
- onClose: () => setIsScannerOpen(false),
2342
- onScan: (roomCode) => {
2343
- onReconnect(roomCode);
2344
- setIsScannerOpen(false);
2345
- },
2346
- currentRoomId: roomId
2347
- }
2348
- )
2637
+ ] })
2349
2638
  ] });
2350
2639
  };
2351
-
2352
- // src/events.ts
2353
- var HostEvents = {
2354
- /**
2355
- * Register as a master host (standalone mode)
2356
- */
2357
- REGISTER: "host:register",
2358
- /**
2359
- * Register as the system/arcade master host
2360
- */
2361
- REGISTER_SYSTEM: "host:registerSystem",
2362
- /**
2363
- * Join as a child host (game launched from arcade)
2364
- */
2365
- JOIN_AS_CHILD: "host:joinAsChild"
2366
- };
2367
- var ControllerEvents = {
2368
- /**
2369
- * Controller joins a room
2370
- */
2371
- JOIN: "controller:join",
2372
- /**
2373
- * Controller sends input
2374
- */
2375
- INPUT: "controller:input",
2376
- /**
2377
- * Controller leaves a room
2378
- */
2379
- LEAVE: "controller:leave",
2380
- /**
2381
- * Controller sends game state update
2382
- */
2383
- STATE: "controller:state",
2384
- /**
2385
- * Controller sends system command
2386
- */
2387
- SYSTEM: "controller:system"
2388
- };
2389
- var SystemEvents = {
2390
- /**
2391
- * Arcade launches a game
2392
- */
2393
- LAUNCH_GAME: "system:launchGame",
2394
- /**
2395
- * Arcade closes a game
2396
- */
2397
- CLOSE_GAME: "system:closeGame"
2398
- };
2399
- var ServerEvents = {
2400
- /**
2401
- * Welcome message with room/controller info
2402
- */
2403
- WELCOME: "server:welcome",
2404
- /**
2405
- * Room is ready
2406
- */
2407
- ROOM_READY: "server:roomReady",
2408
- /**
2409
- * Controller joined notification
2410
- */
2411
- CONTROLLER_JOINED: "server:controllerJoined",
2412
- /**
2413
- * Controller left notification
2414
- */
2415
- CONTROLLER_LEFT: "server:controllerLeft",
2416
- /**
2417
- * Host left notification
2418
- */
2419
- HOST_LEFT: "server:hostLeft",
2420
- /**
2421
- * Server error
2422
- */
2423
- ERROR: "server:error",
2424
- /**
2425
- * Play sound on client
2426
- */
2427
- PLAY_SOUND: "server:playSound"
2428
- };
2429
- var ClientEvents = {
2430
- /**
2431
- * Load a game UI in the controller iframe
2432
- */
2433
- LOAD_UI: "client:loadUi",
2434
- /**
2435
- * Unload the game UI from the controller iframe
2436
- */
2437
- UNLOAD_UI: "client:unloadUi",
2438
- /**
2439
- * Update game state display
2440
- */
2441
- STATE: "client:state"
2442
- };
2443
- var ChildEvents = {
2444
- /**
2445
- * Server requests child to close
2446
- */
2447
- CLOSE: "child:close"
2448
- };
2449
- var Events = {
2450
- Host: HostEvents,
2451
- Controller: ControllerEvents,
2452
- System: SystemEvents,
2453
- Server: ServerEvents,
2454
- Client: ClientEvents,
2455
- Child: ChildEvents
2456
- };
2457
-
2458
- // src/utils/ids.ts
2459
- var alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
2460
- var generateRoomCode = () => {
2461
- const array = new Uint32Array(4);
2462
- if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
2463
- crypto.getRandomValues(array);
2464
- } else {
2465
- for (let i = 0; i < array.length; i += 1) {
2466
- array[i] = Math.floor(Math.random() * alphabet.length);
2467
- }
2468
- }
2469
- const code = Array.from(
2470
- array,
2471
- (value) => alphabet[value % alphabet.length]
2472
- ).join("");
2473
- return roomCodeSchema.parse(code);
2474
- };
2475
- var generateControllerId = () => {
2476
- const stamp = Math.floor(Date.now() % 1e5).toString().padStart(5, "0");
2477
- const random = alphabet[Math.floor(Math.random() * alphabet.length)];
2478
- return `C${random}${stamp}`;
2479
- };
2480
-
2481
- // src/hooks/use-air-jam-controller.ts
2482
- var getRoomFromLocation = () => {
2483
- if (typeof window === "undefined") {
2484
- return null;
2640
+ var describeStatus = (status) => {
2641
+ switch (status) {
2642
+ case "connected":
2643
+ return "Connected to host";
2644
+ case "connecting":
2645
+ return "Connecting\u2026";
2646
+ case "reconnecting":
2647
+ return "Trying to reconnect\u2026";
2648
+ case "disconnected":
2649
+ return "Disconnected";
2650
+ case "idle":
2651
+ default:
2652
+ return "Idle";
2485
2653
  }
2486
- const params = new URLSearchParams(window.location.search);
2487
- const code = params.get("room");
2488
- return code ? code.toUpperCase() : null;
2489
- };
2490
- var useAirJamController = (options = {}) => {
2491
- const { store, getSocket, disconnectSocket } = useAirJamContext();
2492
- const nicknameRef = useRef(options.nickname ?? "");
2493
- const subControllerParams = useMemo(() => {
2494
- if (typeof window === "undefined") return null;
2495
- const params = new URLSearchParams(window.location.search);
2496
- const room = params.get("aj_room");
2497
- const controllerId2 = params.get("aj_controller_id");
2498
- if (room && controllerId2) {
2499
- return { room, controllerId: controllerId2 };
2500
- }
2501
- return null;
2502
- }, []);
2503
- const parsedRoomId = useMemo(() => {
2504
- const code = subControllerParams?.room ?? options.roomId ?? getRoomFromLocation();
2505
- if (!code) return null;
2506
- try {
2507
- return roomCodeSchema.parse(code.toUpperCase());
2508
- } catch {
2509
- return null;
2510
- }
2511
- }, [options.roomId, subControllerParams]);
2512
- const controllerId = useMemo(() => {
2513
- if (subControllerParams?.controllerId) {
2514
- return subControllerParams.controllerId;
2515
- }
2516
- if (options.controllerId) {
2517
- return options.controllerId;
2518
- }
2519
- if (typeof window !== "undefined") {
2520
- const params = new URLSearchParams(window.location.search);
2521
- const urlControllerId = params.get("controllerId");
2522
- if (urlControllerId) return urlControllerId;
2523
- }
2524
- return generateControllerId();
2525
- }, [options.controllerId, subControllerParams]);
2526
- const onStateRef = useRef(
2527
- options.onState
2528
- );
2529
- useEffect(() => {
2530
- onStateRef.current = options.onState;
2531
- }, [options.onState]);
2532
- const connectionState = useStore(
2533
- store,
2534
- useShallow((state) => ({
2535
- connectionStatus: state.connectionStatus,
2536
- lastError: state.lastError,
2537
- controllerId: state.controllerId,
2538
- players: state.players,
2539
- gameState: state.gameState,
2540
- stateMessage: state.stateMessage
2541
- }))
2542
- );
2543
- const [reconnectKey, setReconnectKey] = useState(0);
2544
- const reconnect = useCallback(() => {
2545
- if (!parsedRoomId) return;
2546
- disconnectSocket("controller");
2547
- setReconnectKey((prev) => prev + 1);
2548
- }, [parsedRoomId, disconnectSocket]);
2549
- const isChildMode = useMemo(() => {
2550
- if (typeof window === "undefined") return false;
2551
- const params = new URLSearchParams(window.location.search);
2552
- return params.get("airjam_mode") === "child";
2553
- }, []);
2554
- const shouldConnect = useMemo(() => {
2555
- if (options.forceConnect) return true;
2556
- if (subControllerParams) return true;
2557
- if (typeof window !== "undefined") {
2558
- const params = new URLSearchParams(window.location.search);
2559
- return params.get("airjam_force_connect") === "true";
2560
- }
2561
- return false;
2562
- }, [options.forceConnect, subControllerParams]);
2563
- const canConnect = useMemo(
2564
- () => !isChildMode || shouldConnect,
2565
- [isChildMode, shouldConnect]
2654
+ };
2655
+ var orientationMatches = (required) => {
2656
+ if (required === "any") return true;
2657
+ if (typeof window === "undefined" || !window.matchMedia) return true;
2658
+ const matcher = window.matchMedia(`(orientation: ${required})`);
2659
+ return matcher.matches;
2660
+ };
2661
+ var ControllerShell = ({
2662
+ roomId,
2663
+ connectionStatus,
2664
+ requiredOrientation = "landscape",
2665
+ children,
2666
+ gameState = "paused",
2667
+ onTogglePlayPause,
2668
+ onReconnect,
2669
+ onRefresh,
2670
+ customActions
2671
+ }) => {
2672
+ const isChildMode = useMemo(() => detectRunMode() === "platform", []);
2673
+ const [isOrientationOk, setOrientationOk] = useState(
2674
+ () => orientationMatches(requiredOrientation)
2566
2675
  );
2567
- const socket = useMemo(
2568
- () => canConnect && parsedRoomId ? getSocket("controller") : null,
2569
- [canConnect, parsedRoomId, getSocket]
2676
+ const [isScannerOpen, setIsScannerOpen] = useState(false);
2677
+ const { isFullscreen, toggleFullscreen } = useFullscreen();
2678
+ const { store } = useAirJamContext();
2679
+ const { controllerId, players } = useStore(
2680
+ store,
2681
+ useShallow(
2682
+ (state) => ({
2683
+ controllerId: state.controllerId,
2684
+ players: state.players
2685
+ })
2686
+ )
2570
2687
  );
2688
+ const currentPlayer = useMemo(() => {
2689
+ if (!controllerId) return null;
2690
+ const found = players.find((p) => p.id === controllerId);
2691
+ if (!found && connectionStatus === "connected" && players.length > 0) ;
2692
+ return found || null;
2693
+ }, [controllerId, players, connectionStatus]);
2571
2694
  useEffect(() => {
2572
- if (!socket) return;
2573
- const handleSignal = (signal) => {
2574
- if (signal.type !== "HAPTIC") return;
2575
- if (typeof navigator === "undefined" || !navigator.vibrate) return;
2576
- const payload = signal.payload;
2577
- switch (payload.pattern) {
2578
- case "light":
2579
- navigator.vibrate(10);
2580
- break;
2581
- case "medium":
2582
- navigator.vibrate(30);
2583
- break;
2584
- case "heavy":
2585
- navigator.vibrate([50, 20, 50]);
2586
- break;
2587
- case "success":
2588
- navigator.vibrate([10, 30, 10]);
2589
- break;
2590
- case "failure":
2591
- navigator.vibrate([50, 50, 50, 50]);
2592
- break;
2593
- case "custom":
2594
- if (Array.isArray(payload.sequence)) {
2595
- navigator.vibrate(payload.sequence);
2596
- } else if (typeof payload.sequence === "number") {
2597
- navigator.vibrate(payload.sequence);
2598
- }
2599
- break;
2600
- }
2601
- };
2602
- socket.on("server:signal", handleSignal);
2603
- return () => {
2604
- socket.off("server:signal", handleSignal);
2605
- };
2606
- }, [socket]);
2607
- useEffect(() => {
2608
- const storeState = store.getState();
2609
- storeState.setMode(detectRunMode());
2610
- storeState.setRole("controller");
2611
- storeState.setRoomId(parsedRoomId);
2612
- storeState.setStatus(parsedRoomId ? "connecting" : "idle");
2613
- storeState.setError(void 0);
2614
- if (!canConnect) {
2615
- storeState.setStatus("connected");
2616
- const handleMessage = (event) => {
2617
- if (event.source !== window.parent) return;
2618
- const data = event.data;
2619
- if (data?.type === "AIRJAM_STATE") {
2620
- const payload = data.payload;
2621
- if (payload.gameState) storeState.setGameState(payload.gameState);
2622
- if (payload.message !== void 0)
2623
- storeState.setStateMessage(payload.message);
2624
- onStateRef.current?.(payload);
2625
- }
2626
- };
2627
- window.addEventListener("message", handleMessage);
2628
- window.parent.postMessage({ type: "AIRJAM_READY" }, "*");
2629
- return () => {
2630
- window.removeEventListener("message", handleMessage);
2631
- storeState.setStatus("disconnected");
2632
- };
2633
- }
2634
- if (!parsedRoomId || !socket || !controllerId) {
2635
- storeState.setStatus("idle");
2695
+ if (requiredOrientation === "any") {
2636
2696
  return;
2637
2697
  }
2638
- storeState.setControllerId(controllerId);
2639
- const handleConnect = () => {
2640
- store.getState().setStatus("connected");
2641
- if (subControllerParams) {
2642
- return;
2643
- }
2644
- const payload = controllerJoinSchema.parse({
2645
- roomId: parsedRoomId,
2646
- controllerId,
2647
- nickname: nicknameRef.current || void 0
2648
- });
2649
- socket.emit("controller:join", payload, (ack) => {
2650
- const storeState2 = store.getState();
2651
- if (!ack.ok) {
2652
- storeState2.setError(ack.message ?? "Unable to join room");
2653
- storeState2.setStatus("disconnected");
2654
- return;
2655
- }
2656
- if (ack.controllerId) {
2657
- storeState2.setControllerId(ack.controllerId);
2698
+ const media = window.matchMedia(`(orientation: ${requiredOrientation})`);
2699
+ const handleChange = () => setOrientationOk(media.matches);
2700
+ handleChange();
2701
+ media.addEventListener("change", handleChange);
2702
+ return () => media.removeEventListener("change", handleChange);
2703
+ }, [requiredOrientation]);
2704
+ const orientationOk = requiredOrientation === "any" ? true : isOrientationOk;
2705
+ const statusDotColor = useMemo(() => {
2706
+ switch (connectionStatus) {
2707
+ case "connected":
2708
+ return "bg-green-500";
2709
+ case "connecting":
2710
+ case "reconnecting":
2711
+ return "bg-yellow-500";
2712
+ case "disconnected":
2713
+ default:
2714
+ return "bg-red-500";
2715
+ }
2716
+ }, [connectionStatus]);
2717
+ if (isChildMode) {
2718
+ return /* @__PURE__ */ jsx("div", { className: "dark", children: /* @__PURE__ */ jsx("div", { className: "text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden bg-transparent select-none", children: /* @__PURE__ */ jsxs("main", { className: "relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4", children: [
2719
+ !orientationOk && /* @__PURE__ */ jsxs("div", { className: "bg-background/95 absolute inset-0 z-50 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm", children: [
2720
+ /* @__PURE__ */ jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2721
+ /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2722
+ "This game is best experienced in ",
2723
+ requiredOrientation,
2724
+ " ",
2725
+ "orientation."
2726
+ ] })
2727
+ ] }),
2728
+ /* @__PURE__ */ jsx(
2729
+ "div",
2730
+ {
2731
+ className: cn(
2732
+ "h-full w-full select-none",
2733
+ !orientationOk && "pointer-events-none opacity-30"
2734
+ ),
2735
+ children
2658
2736
  }
2659
- storeState2.setStatus("connected");
2660
- });
2661
- };
2662
- const handleDisconnect = () => {
2663
- store.getState().setStatus("disconnected");
2664
- };
2665
- const handleWelcome = (payload) => {
2666
- const storeState2 = store.getState();
2667
- const storeRoomId = storeState2.roomId;
2668
- if (storeRoomId && payload.roomId.toUpperCase() !== storeRoomId.toUpperCase()) {
2669
- return;
2670
- }
2671
- if (!storeRoomId && payload.roomId) {
2672
- storeState2.setRoomId(payload.roomId);
2673
- }
2674
- if (!payload.player) {
2675
- storeState2.setError(
2676
- "Welcome message received but no player profile included."
2677
- );
2678
- return;
2679
- }
2680
- storeState2.upsertPlayer(payload.player);
2681
- };
2682
- const handleState = (payload) => {
2683
- if (payload.roomId !== parsedRoomId) return;
2684
- const storeState2 = store.getState();
2685
- if (payload.state.gameState) {
2686
- storeState2.setGameState(payload.state.gameState);
2687
- }
2688
- if (payload.state.message !== void 0) {
2689
- storeState2.setStateMessage(payload.state.message);
2690
- }
2691
- onStateRef.current?.(payload.state);
2692
- };
2693
- const handleHostLeft = (payload) => {
2694
- const storeState2 = store.getState();
2695
- storeState2.setError(payload.reason);
2696
- storeState2.setStatus("disconnected");
2697
- storeState2.resetGameState();
2698
- setTimeout(() => {
2699
- disconnectSocket("controller");
2700
- setReconnectKey((prev) => prev + 1);
2701
- }, 1e3);
2702
- };
2703
- const handleError = (payload) => {
2704
- store.getState().setError(payload.message);
2705
- };
2706
- socket.on("connect", handleConnect);
2707
- socket.on("disconnect", handleDisconnect);
2708
- socket.on("server:welcome", handleWelcome);
2709
- socket.on("server:state", handleState);
2710
- socket.on("server:hostLeft", handleHostLeft);
2711
- socket.on("server:error", handleError);
2712
- socket.connect();
2713
- return () => {
2714
- socket.off("connect", handleConnect);
2715
- socket.off("disconnect", handleDisconnect);
2716
- socket.off("server:welcome", handleWelcome);
2717
- socket.off("server:state", handleState);
2718
- socket.off("server:hostLeft", handleHostLeft);
2719
- socket.off("server:error", handleError);
2720
- };
2721
- }, [
2722
- parsedRoomId,
2723
- reconnectKey,
2724
- canConnect,
2725
- socket,
2726
- controllerId,
2727
- subControllerParams,
2728
- store,
2729
- disconnectSocket
2730
- ]);
2731
- const setNickname = useCallback((value) => {
2732
- nicknameRef.current = value;
2733
- }, []);
2734
- const sendInput = useCallback(
2735
- (input) => {
2736
- const storeState = store.getState();
2737
- if (!canConnect) {
2738
- if (typeof window !== "undefined") {
2739
- window.parent.postMessage(
2737
+ )
2738
+ ] }) }) });
2739
+ }
2740
+ 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
+ /* @__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
+ /* @__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",
2740
2763
  {
2741
- type: "AIRJAM_INPUT",
2742
- payload: input
2743
- },
2744
- "*"
2745
- );
2764
+ className: cn(
2765
+ "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
2766
+ statusDotColor,
2767
+ connectionStatus === "connected" && "animate-pulse"
2768
+ ),
2769
+ "aria-label": describeStatus(connectionStatus)
2770
+ }
2771
+ )
2772
+ ] }),
2773
+ /* @__PURE__ */ jsxs("div", { children: [
2774
+ /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs tracking-[0.24em] uppercase", children: "Room" }),
2775
+ /* @__PURE__ */ jsx("p", { className: "text-foreground text-lg font-semibold", children: typeof window !== "undefined" ? roomId ?? "N/A" : "N/A" })
2776
+ ] })
2777
+ ] }),
2778
+ /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2779
+ customActions,
2780
+ onRefresh && roomId && /* @__PURE__ */ jsx(
2781
+ Button,
2782
+ {
2783
+ type: "button",
2784
+ variant: "outline",
2785
+ size: "icon",
2786
+ onClick: onRefresh,
2787
+ disabled: connectionStatus === "connecting" || connectionStatus === "reconnecting",
2788
+ "aria-label": "Reconnect",
2789
+ title: "Reconnect to room",
2790
+ children: /* @__PURE__ */ jsx(
2791
+ RefreshCw,
2792
+ {
2793
+ className: cn(
2794
+ "h-5 w-5",
2795
+ (connectionStatus === "connecting" || connectionStatus === "reconnecting") && "animate-spin"
2796
+ )
2797
+ }
2798
+ )
2799
+ }
2800
+ ),
2801
+ onReconnect && /* @__PURE__ */ jsx(
2802
+ Button,
2803
+ {
2804
+ type: "button",
2805
+ variant: "outline",
2806
+ size: "icon",
2807
+ onClick: () => setIsScannerOpen(true),
2808
+ "aria-label": "Scan QR code to reconnect",
2809
+ title: "Scan QR code to reconnect",
2810
+ children: /* @__PURE__ */ jsx(QrCode, { className: "h-5 w-5" })
2811
+ }
2812
+ ),
2813
+ onTogglePlayPause && /* @__PURE__ */ jsx(
2814
+ Button,
2815
+ {
2816
+ type: "button",
2817
+ variant: "outline",
2818
+ size: "icon",
2819
+ onClick: onTogglePlayPause,
2820
+ "aria-label": gameState === "playing" ? "Pause" : "Play",
2821
+ title: gameState === "playing" ? "Pause" : "Play",
2822
+ children: gameState === "playing" ? /* @__PURE__ */ jsx(Pause, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Play, { className: "h-5 w-5" })
2823
+ }
2824
+ ),
2825
+ /* @__PURE__ */ jsx(
2826
+ Button,
2827
+ {
2828
+ type: "button",
2829
+ variant: "outline",
2830
+ size: "icon",
2831
+ onClick: () => toggleFullscreen(),
2832
+ "aria-label": isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2833
+ title: isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2834
+ children: isFullscreen ? /* @__PURE__ */ jsx(Minimize, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Maximize, { className: "h-5 w-5" })
2835
+ }
2836
+ )
2837
+ ] })
2838
+ ] }),
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
+ /* @__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: [
2842
+ /* @__PURE__ */ jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2843
+ /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2844
+ "This game is best experienced in ",
2845
+ requiredOrientation,
2846
+ " ",
2847
+ "orientation."
2848
+ ] })
2849
+ ] }),
2850
+ /* @__PURE__ */ jsx(
2851
+ "div",
2852
+ {
2853
+ className: cn(
2854
+ "h-full w-full select-none",
2855
+ !orientationOk && "pointer-events-none opacity-30"
2856
+ ),
2857
+ children
2746
2858
  }
2747
- return true;
2748
- }
2749
- if (!parsedRoomId || !storeState.controllerId || !socket) {
2750
- storeState.setError("Not connected to a room");
2751
- return false;
2752
- }
2753
- if (!socket.connected) {
2754
- return false;
2755
- }
2756
- if (typeof input !== "object" || input === null || Array.isArray(input)) {
2757
- storeState.setError("Input must be an object");
2758
- return false;
2759
- }
2760
- const payload = controllerInputSchema.safeParse({
2761
- roomId: parsedRoomId,
2762
- controllerId: storeState.controllerId,
2763
- input
2764
- });
2765
- if (!payload.success) {
2766
- storeState.setError(payload.error.message);
2767
- return false;
2768
- }
2769
- socket.emit("controller:input", payload.data);
2770
- return true;
2771
- },
2772
- [parsedRoomId, canConnect, socket, store]
2773
- );
2774
- const sendSystemCommand = useCallback(
2775
- (command) => {
2776
- const storeState = store.getState();
2777
- if (!canConnect) return;
2778
- if (!parsedRoomId || !storeState.controllerId || !socket) return;
2779
- if (!socket.connected) return;
2780
- const payload = controllerSystemSchema.safeParse({
2781
- roomId: parsedRoomId,
2782
- command
2783
- });
2784
- if (payload.success) {
2785
- socket.emit("controller:system", payload.data);
2859
+ )
2860
+ ] }) }),
2861
+ onReconnect && /* @__PURE__ */ jsx(
2862
+ QRScannerDialog,
2863
+ {
2864
+ isOpen: isScannerOpen,
2865
+ onClose: () => setIsScannerOpen(false),
2866
+ onScan: (roomCode) => {
2867
+ onReconnect(roomCode);
2868
+ setIsScannerOpen(false);
2869
+ },
2870
+ currentRoomId: roomId
2786
2871
  }
2787
- },
2788
- [parsedRoomId, canConnect, socket, store]
2789
- );
2790
- return {
2791
- roomId: parsedRoomId,
2792
- controllerId: connectionState.controllerId,
2793
- connectionStatus: connectionState.connectionStatus,
2794
- lastError: connectionState.lastError,
2795
- gameState: connectionState.gameState,
2796
- stateMessage: connectionState.stateMessage,
2797
- sendInput,
2798
- sendSystemCommand,
2799
- setNickname,
2800
- reconnect,
2801
- players: connectionState.players,
2802
- socket
2803
- };
2872
+ )
2873
+ ] }) });
2874
+ };
2875
+
2876
+ // src/events.ts
2877
+ var HostEvents = {
2878
+ /**
2879
+ * Register as a master host (standalone mode)
2880
+ */
2881
+ REGISTER: "host:register",
2882
+ /**
2883
+ * Register as the system/arcade master host
2884
+ */
2885
+ REGISTER_SYSTEM: "host:registerSystem",
2886
+ /**
2887
+ * Join as a child host (game launched from arcade)
2888
+ */
2889
+ JOIN_AS_CHILD: "host:joinAsChild"
2890
+ };
2891
+ var ControllerEvents = {
2892
+ /**
2893
+ * Controller joins a room
2894
+ */
2895
+ JOIN: "controller:join",
2896
+ /**
2897
+ * Controller sends input
2898
+ */
2899
+ INPUT: "controller:input",
2900
+ /**
2901
+ * Controller leaves a room
2902
+ */
2903
+ LEAVE: "controller:leave",
2904
+ /**
2905
+ * Controller sends game state update
2906
+ */
2907
+ STATE: "controller:state",
2908
+ /**
2909
+ * Controller sends system command
2910
+ */
2911
+ SYSTEM: "controller:system"
2912
+ };
2913
+ var SystemEvents = {
2914
+ /**
2915
+ * Arcade launches a game
2916
+ */
2917
+ LAUNCH_GAME: "system:launchGame",
2918
+ /**
2919
+ * Arcade closes a game
2920
+ */
2921
+ CLOSE_GAME: "system:closeGame"
2922
+ };
2923
+ var ServerEvents = {
2924
+ /**
2925
+ * Welcome message with room/controller info
2926
+ */
2927
+ WELCOME: "server:welcome",
2928
+ /**
2929
+ * Room is ready
2930
+ */
2931
+ ROOM_READY: "server:roomReady",
2932
+ /**
2933
+ * Controller joined notification
2934
+ */
2935
+ CONTROLLER_JOINED: "server:controllerJoined",
2936
+ /**
2937
+ * Controller left notification
2938
+ */
2939
+ CONTROLLER_LEFT: "server:controllerLeft",
2940
+ /**
2941
+ * Host left notification
2942
+ */
2943
+ HOST_LEFT: "server:hostLeft",
2944
+ /**
2945
+ * Server error
2946
+ */
2947
+ ERROR: "server:error",
2948
+ /**
2949
+ * Play sound on client
2950
+ */
2951
+ PLAY_SOUND: "server:playSound"
2952
+ };
2953
+ var ClientEvents = {
2954
+ /**
2955
+ * Load a game UI in the controller iframe
2956
+ */
2957
+ LOAD_UI: "client:loadUi",
2958
+ /**
2959
+ * Unload the game UI from the controller iframe
2960
+ */
2961
+ UNLOAD_UI: "client:unloadUi",
2962
+ /**
2963
+ * Update game state display
2964
+ */
2965
+ STATE: "client:state"
2804
2966
  };
2805
- var useAirJamHost = (options = {}) => {
2806
- const { config, store, getSocket, disconnectSocket, inputManager } = useAirJamContext();
2807
- const arcadeParams = useMemo(() => {
2967
+ var ChildEvents = {
2968
+ /**
2969
+ * Server requests child to close
2970
+ */
2971
+ CLOSE: "child:close"
2972
+ };
2973
+ var Events = {
2974
+ Host: HostEvents,
2975
+ Controller: ControllerEvents,
2976
+ System: SystemEvents,
2977
+ Server: ServerEvents,
2978
+ Client: ClientEvents,
2979
+ Child: ChildEvents
2980
+ };
2981
+ var getRoomFromLocation = () => {
2982
+ if (typeof window === "undefined") {
2983
+ return null;
2984
+ }
2985
+ const params = new URLSearchParams(window.location.search);
2986
+ const code = params.get("room");
2987
+ return code ? code.toUpperCase() : null;
2988
+ };
2989
+ var useAirJamController = (options = {}) => {
2990
+ const { store, getSocket, disconnectSocket } = useAirJamContext();
2991
+ const nicknameRef = useRef(options.nickname ?? "");
2992
+ const subControllerParams = useMemo(() => {
2808
2993
  if (typeof window === "undefined") return null;
2809
2994
  const params = new URLSearchParams(window.location.search);
2810
2995
  const room = params.get("aj_room");
2811
- const token = params.get("aj_token");
2812
- if (room && token) {
2813
- return { room, token };
2996
+ const controllerId2 = params.get("aj_controller_id");
2997
+ if (room && controllerId2) {
2998
+ return { room, controllerId: controllerId2 };
2814
2999
  }
2815
3000
  return null;
2816
3001
  }, []);
2817
- const isChildMode = !!arcadeParams;
2818
- const shouldConnect = true;
2819
- const [fallbackRoomId] = useState(() => generateRoomCode());
2820
3002
  const parsedRoomId = useMemo(() => {
2821
- if (arcadeParams) {
2822
- return roomCodeSchema.parse(arcadeParams.room.toUpperCase());
3003
+ const code = subControllerParams?.room ?? options.roomId ?? getRoomFromLocation();
3004
+ if (!code) return null;
3005
+ try {
3006
+ return roomCodeSchema.parse(code.toUpperCase());
3007
+ } catch {
3008
+ return null;
2823
3009
  }
2824
- if (typeof window !== "undefined") {
2825
- const params = new URLSearchParams(window.location.search);
2826
- const paramRoom = params.get("room");
2827
- if (paramRoom) {
2828
- const result = roomCodeSchema.safeParse(paramRoom.toUpperCase());
2829
- if (result.success) return result.data;
2830
- }
3010
+ }, [options.roomId, subControllerParams]);
3011
+ const controllerId = useMemo(() => {
3012
+ if (subControllerParams?.controllerId) {
3013
+ return subControllerParams.controllerId;
2831
3014
  }
2832
- if (options.roomId) {
2833
- return roomCodeSchema.parse(options.roomId.toUpperCase());
3015
+ if (options.controllerId) {
3016
+ return options.controllerId;
2834
3017
  }
2835
- return fallbackRoomId;
2836
- }, [options.roomId, fallbackRoomId, arcadeParams]);
2837
- useEffect(() => {
2838
- if (inputManager) {
2839
- inputManager.setRoomId(parsedRoomId);
3018
+ if (typeof window !== "undefined") {
3019
+ const params = new URLSearchParams(window.location.search);
3020
+ const urlControllerId = params.get("controllerId");
3021
+ if (urlControllerId) return urlControllerId;
2840
3022
  }
2841
- }, [inputManager, parsedRoomId]);
2842
- const [joinUrl, setJoinUrl] = useState("");
2843
- const onPlayerJoinRef = useRef(options.onPlayerJoin);
2844
- const onPlayerLeaveRef = useRef(options.onPlayerLeave);
2845
- const onChildCloseRef = useRef(options.onChildClose);
3023
+ return generateControllerId();
3024
+ }, [options.controllerId, subControllerParams]);
3025
+ const onStateRef = useRef(
3026
+ options.onState
3027
+ );
2846
3028
  useEffect(() => {
2847
- onPlayerJoinRef.current = options.onPlayerJoin;
2848
- onPlayerLeaveRef.current = options.onPlayerLeave;
2849
- onChildCloseRef.current = options.onChildClose;
2850
- }, [options.onPlayerJoin, options.onPlayerLeave, options.onChildClose]);
3029
+ onStateRef.current = options.onState;
3030
+ }, [options.onState]);
2851
3031
  const connectionState = useStore(
2852
3032
  store,
2853
3033
  useShallow((state) => ({
2854
3034
  connectionStatus: state.connectionStatus,
2855
3035
  lastError: state.lastError,
3036
+ controllerId: state.controllerId,
2856
3037
  players: state.players,
2857
3038
  gameState: state.gameState,
2858
- mode: state.mode
3039
+ stateMessage: state.stateMessage
2859
3040
  }))
2860
3041
  );
2861
- const socket = useMemo(
2862
- () => getSocket("host") ,
2863
- [shouldConnect, getSocket]
2864
- );
2865
- const [lastToggle, setLastToggle] = useState(0);
2866
- const toggleGameState = useCallback(() => {
2867
- const now = Date.now();
2868
- if (now - lastToggle < TOGGLE_DEBOUNCE_MS) {
2869
- return;
2870
- }
2871
- setLastToggle(now);
2872
- if (!socket || !socket.connected) {
2873
- return;
2874
- }
2875
- const payload = controllerSystemSchema.safeParse({
2876
- roomId: parsedRoomId,
2877
- command: "toggle_pause"
2878
- });
2879
- if (payload.success) {
2880
- socket.emit("host:system", payload.data);
3042
+ const [reconnectKey, setReconnectKey] = useState(0);
3043
+ const reconnect = useCallback(() => {
3044
+ if (!parsedRoomId) return;
3045
+ disconnectSocket("controller");
3046
+ setReconnectKey((prev) => prev + 1);
3047
+ }, [parsedRoomId, disconnectSocket]);
3048
+ const isChildMode = useMemo(() => {
3049
+ if (typeof window === "undefined") return false;
3050
+ const params = new URLSearchParams(window.location.search);
3051
+ return params.get("airjam_mode") === "child";
3052
+ }, []);
3053
+ const shouldConnect = useMemo(() => {
3054
+ if (options.forceConnect) return true;
3055
+ if (subControllerParams) return true;
3056
+ if (typeof window !== "undefined") {
3057
+ const params = new URLSearchParams(window.location.search);
3058
+ return params.get("airjam_force_connect") === "true";
2881
3059
  }
2882
- }, [socket, parsedRoomId, lastToggle]);
2883
- const sendState = useCallback(
2884
- (state) => {
2885
- if (!socket || !socket.connected) {
2886
- return false;
2887
- }
2888
- const payload = controllerStateSchema.safeParse({
2889
- roomId: parsedRoomId,
2890
- state
2891
- });
2892
- if (!payload.success) {
2893
- return false;
2894
- }
2895
- socket.emit("host:state", payload.data);
2896
- return true;
2897
- },
2898
- [socket, parsedRoomId]
3060
+ return false;
3061
+ }, [options.forceConnect, subControllerParams]);
3062
+ const canConnect = useMemo(
3063
+ () => !isChildMode || shouldConnect,
3064
+ [isChildMode, shouldConnect]
2899
3065
  );
2900
- const sendSignal = useCallback(
2901
- (type, payload, targetId) => {
2902
- if (!socket || !socket.connected) {
2903
- return;
2904
- }
2905
- const signal = {
2906
- targetId,
2907
- type,
2908
- payload
2909
- };
2910
- socket.emit("host:signal", signal);
2911
- },
2912
- [socket]
3066
+ const socket = useMemo(
3067
+ () => canConnect && parsedRoomId ? getSocket("controller") : null,
3068
+ [canConnect, parsedRoomId, getSocket]
2913
3069
  );
2914
- const reconnect = useCallback(() => {
2915
- disconnectSocket("host");
2916
- if (socket) {
2917
- socket.connect();
2918
- }
2919
- }, [socket, disconnectSocket]);
2920
- useEffect(() => {
2921
- (async () => {
2922
- const url = await urlBuilder.buildControllerUrl(parsedRoomId, {
2923
- path: config.controllerPath,
2924
- host: config.publicHost
2925
- });
2926
- setJoinUrl(url);
2927
- })();
2928
- }, [parsedRoomId, config.controllerPath, config.publicHost]);
2929
- const setRegisteredRoomId = useStore(store, (s) => s.setRegisteredRoomId);
2930
3070
  useEffect(() => {
2931
- const storeState = store.getState();
2932
- storeState.setMode(detectRunMode());
2933
- storeState.setRole("host");
2934
- storeState.setRoomId(parsedRoomId);
2935
- storeState.setStatus("connecting");
2936
- storeState.setError(void 0);
2937
- if (!socket) {
2938
- storeState.setStatus("idle");
2939
- return;
2940
- }
2941
- const registerHost = async () => {
2942
- const storeState2 = store.getState();
2943
- const currentRegisteredRoomId2 = store.getState().registeredRoomId;
2944
- if (currentRegisteredRoomId2 === parsedRoomId && socket.connected) {
2945
- return;
2946
- }
2947
- if (arcadeParams) {
2948
- const childRoomId = roomCodeSchema.parse(
2949
- arcadeParams.room.toUpperCase()
2950
- );
2951
- const payload = {
2952
- roomId: childRoomId,
2953
- joinToken: arcadeParams.token
2954
- };
2955
- socket.emit("host:joinAsChild", payload, (ack) => {
2956
- if (!ack.ok) {
2957
- storeState2.setError(ack.message ?? "Failed to join as child");
2958
- storeState2.setStatus("disconnected");
2959
- setRegisteredRoomId(null);
2960
- return;
2961
- }
2962
- storeState2.setStatus("connected");
2963
- storeState2.setRoomId(childRoomId);
2964
- setRegisteredRoomId(childRoomId);
2965
- });
2966
- } else {
2967
- const payload = hostRegistrationSchema.parse({
2968
- roomId: parsedRoomId,
2969
- maxPlayers: options.maxPlayers ?? config.maxPlayers,
2970
- apiKey: options.apiKey ?? config.apiKey
2971
- });
2972
- socket.emit("host:register", payload, (ack) => {
2973
- if (!ack.ok) {
2974
- storeState2.setError(ack.message ?? "Failed to register host");
2975
- storeState2.setStatus("disconnected");
2976
- setRegisteredRoomId(null);
2977
- return;
2978
- }
2979
- storeState2.setStatus("connected");
2980
- if (ack.roomId) {
2981
- storeState2.setRoomId(ack.roomId);
2982
- setRegisteredRoomId(ack.roomId);
2983
- } else {
2984
- setRegisteredRoomId(parsedRoomId);
3071
+ if (!socket) return;
3072
+ const handleSignal = (signal) => {
3073
+ if (signal.type !== "HAPTIC") return;
3074
+ if (typeof navigator === "undefined" || !navigator.vibrate) return;
3075
+ const payload = signal.payload;
3076
+ switch (payload.pattern) {
3077
+ case "light":
3078
+ navigator.vibrate(10);
3079
+ break;
3080
+ case "medium":
3081
+ navigator.vibrate(30);
3082
+ break;
3083
+ case "heavy":
3084
+ navigator.vibrate([50, 20, 50]);
3085
+ break;
3086
+ case "success":
3087
+ navigator.vibrate([10, 30, 10]);
3088
+ break;
3089
+ case "failure":
3090
+ navigator.vibrate([50, 50, 50, 50]);
3091
+ break;
3092
+ case "custom":
3093
+ if (Array.isArray(payload.sequence)) {
3094
+ navigator.vibrate(payload.sequence);
3095
+ } else if (typeof payload.sequence === "number") {
3096
+ navigator.vibrate(payload.sequence);
2985
3097
  }
2986
- });
3098
+ break;
2987
3099
  }
2988
3100
  };
3101
+ socket.on("server:signal", handleSignal);
3102
+ return () => {
3103
+ socket.off("server:signal", handleSignal);
3104
+ };
3105
+ }, [socket]);
3106
+ useEffect(() => {
3107
+ const storeState = store.getState();
3108
+ storeState.setMode(detectRunMode());
3109
+ storeState.setRole("controller");
3110
+ storeState.setRoomId(parsedRoomId);
3111
+ storeState.setStatus(parsedRoomId ? "connecting" : "idle");
3112
+ storeState.setError(void 0);
3113
+ if (!canConnect) {
3114
+ storeState.setStatus("connected");
3115
+ const handleMessage = (event) => {
3116
+ if (event.source !== window.parent) return;
3117
+ const data = event.data;
3118
+ if (data?.type === "AIRJAM_STATE") {
3119
+ const payload = data.payload;
3120
+ if (payload.gameState) storeState.setGameState(payload.gameState);
3121
+ if (payload.message !== void 0)
3122
+ storeState.setStateMessage(payload.message);
3123
+ onStateRef.current?.(payload);
3124
+ }
3125
+ };
3126
+ window.addEventListener("message", handleMessage);
3127
+ window.parent.postMessage({ type: "AIRJAM_READY" }, "*");
3128
+ return () => {
3129
+ window.removeEventListener("message", handleMessage);
3130
+ storeState.setStatus("disconnected");
3131
+ };
3132
+ }
3133
+ if (!parsedRoomId || !socket || !controllerId) {
3134
+ storeState.setStatus("idle");
3135
+ return;
3136
+ }
3137
+ storeState.setControllerId(controllerId);
2989
3138
  const handleConnect = () => {
2990
3139
  store.getState().setStatus("connected");
2991
- registerHost();
3140
+ if (subControllerParams) {
3141
+ return;
3142
+ }
3143
+ const payload = controllerJoinSchema.parse({
3144
+ roomId: parsedRoomId,
3145
+ controllerId,
3146
+ nickname: nicknameRef.current || void 0
3147
+ });
3148
+ socket.emit("controller:join", payload, (ack) => {
3149
+ const storeState2 = store.getState();
3150
+ if (!ack.ok) {
3151
+ storeState2.setError(ack.message ?? "Unable to join room");
3152
+ storeState2.setStatus("disconnected");
3153
+ return;
3154
+ }
3155
+ if (ack.controllerId) {
3156
+ storeState2.setControllerId(ack.controllerId);
3157
+ }
3158
+ storeState2.setStatus("connected");
3159
+ });
2992
3160
  };
2993
3161
  const handleDisconnect = () => {
2994
3162
  store.getState().setStatus("disconnected");
2995
3163
  };
2996
- const handleJoin = (payload) => {
2997
- if (payload.player) {
2998
- store.getState().upsertPlayer(payload.player);
2999
- setTimeout(() => {
3000
- onPlayerJoinRef.current?.(payload.player);
3001
- }, 0);
3164
+ const handleWelcome = (payload) => {
3165
+ const storeState2 = store.getState();
3166
+ const storeRoomId = storeState2.roomId;
3167
+ if (storeRoomId && payload.roomId.toUpperCase() !== storeRoomId.toUpperCase()) {
3168
+ return;
3002
3169
  }
3003
- };
3004
- const handleLeave = (payload) => {
3005
- store.getState().removePlayer(payload.controllerId);
3006
- onPlayerLeaveRef.current?.(payload.controllerId);
3007
- };
3008
- const handleInput = (payload) => {
3009
- if (inputManager) {
3010
- inputManager.handleInput(payload);
3170
+ if (!storeRoomId && payload.roomId) {
3171
+ storeState2.setRoomId(payload.roomId);
3011
3172
  }
3012
- };
3013
- const handleChildClose = () => {
3014
- onChildCloseRef.current?.();
3173
+ if (!payload.player) {
3174
+ storeState2.setError(
3175
+ "Welcome message received but no player profile included."
3176
+ );
3177
+ return;
3178
+ }
3179
+ storeState2.upsertPlayer(payload.player);
3015
3180
  };
3016
3181
  const handleState = (payload) => {
3017
3182
  if (payload.roomId !== parsedRoomId) return;
@@ -3022,74 +3187,118 @@ var useAirJamHost = (options = {}) => {
3022
3187
  if (payload.state.message !== void 0) {
3023
3188
  storeState2.setStateMessage(payload.state.message);
3024
3189
  }
3190
+ onStateRef.current?.(payload.state);
3191
+ };
3192
+ const handleHostLeft = (payload) => {
3193
+ const storeState2 = store.getState();
3194
+ storeState2.setError(payload.reason);
3195
+ storeState2.setStatus("disconnected");
3196
+ storeState2.resetGameState();
3197
+ setTimeout(() => {
3198
+ disconnectSocket("controller");
3199
+ setReconnectKey((prev) => prev + 1);
3200
+ }, 1e3);
3025
3201
  };
3026
3202
  const handleError = (payload) => {
3027
3203
  store.getState().setError(payload.message);
3028
3204
  };
3029
3205
  socket.on("connect", handleConnect);
3030
3206
  socket.on("disconnect", handleDisconnect);
3031
- socket.on("server:controllerJoined", handleJoin);
3032
- socket.on("server:controllerLeft", handleLeave);
3033
- socket.on("server:input", handleInput);
3034
- socket.on("server:error", handleError);
3035
- socket.on("server:closeChild", handleChildClose);
3207
+ socket.on("server:welcome", handleWelcome);
3036
3208
  socket.on("server:state", handleState);
3209
+ socket.on("server:hostLeft", handleHostLeft);
3210
+ socket.on("server:error", handleError);
3037
3211
  socket.connect();
3038
- const currentRegisteredRoomId = store.getState().registeredRoomId;
3039
- if (socket.connected && currentRegisteredRoomId !== parsedRoomId) {
3040
- registerHost();
3041
- }
3042
- if (currentRegisteredRoomId && currentRegisteredRoomId !== parsedRoomId) {
3043
- setRegisteredRoomId(null);
3044
- }
3045
3212
  return () => {
3046
3213
  socket.off("connect", handleConnect);
3047
3214
  socket.off("disconnect", handleDisconnect);
3048
- socket.off("server:controllerJoined", handleJoin);
3049
- socket.off("server:controllerLeft", handleLeave);
3050
- socket.off("server:input", handleInput);
3051
- socket.off("server:error", handleError);
3052
- socket.off("server:closeChild", handleChildClose);
3215
+ socket.off("server:welcome", handleWelcome);
3053
3216
  socket.off("server:state", handleState);
3217
+ socket.off("server:hostLeft", handleHostLeft);
3218
+ socket.off("server:error", handleError);
3054
3219
  };
3055
3220
  }, [
3056
- config.maxPlayers,
3057
- config.apiKey,
3058
- options.maxPlayers,
3059
- options.apiKey,
3060
3221
  parsedRoomId,
3061
- arcadeParams,
3062
- shouldConnect,
3222
+ reconnectKey,
3223
+ canConnect,
3063
3224
  socket,
3225
+ controllerId,
3226
+ subControllerParams,
3064
3227
  store,
3065
- inputManager,
3066
- setRegisteredRoomId
3228
+ disconnectSocket
3067
3229
  ]);
3068
- const returnSocket = socket ?? getSocket("host");
3069
- const getInput = useCallback(
3070
- (controllerId) => {
3071
- if (!inputManager) {
3072
- return void 0;
3230
+ const setNickname = useCallback((value) => {
3231
+ nicknameRef.current = value;
3232
+ }, []);
3233
+ const sendInput = useCallback(
3234
+ (input) => {
3235
+ const storeState = store.getState();
3236
+ if (!canConnect) {
3237
+ if (typeof window !== "undefined") {
3238
+ window.parent.postMessage(
3239
+ {
3240
+ type: "AIRJAM_INPUT",
3241
+ payload: input
3242
+ },
3243
+ "*"
3244
+ );
3245
+ }
3246
+ return true;
3073
3247
  }
3074
- return inputManager.getInput(controllerId);
3248
+ if (!parsedRoomId || !storeState.controllerId || !socket) {
3249
+ storeState.setError("Not connected to a room");
3250
+ return false;
3251
+ }
3252
+ if (!socket.connected) {
3253
+ return false;
3254
+ }
3255
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
3256
+ storeState.setError("Input must be an object");
3257
+ return false;
3258
+ }
3259
+ const payload = controllerInputSchema.safeParse({
3260
+ roomId: parsedRoomId,
3261
+ controllerId: storeState.controllerId,
3262
+ input
3263
+ });
3264
+ if (!payload.success) {
3265
+ storeState.setError(payload.error.message);
3266
+ return false;
3267
+ }
3268
+ socket.emit("controller:input", payload.data);
3269
+ return true;
3075
3270
  },
3076
- [inputManager]
3271
+ [parsedRoomId, canConnect, socket, store]
3272
+ );
3273
+ const sendSystemCommand = useCallback(
3274
+ (command) => {
3275
+ const storeState = store.getState();
3276
+ if (!canConnect) return;
3277
+ if (!parsedRoomId || !storeState.controllerId || !socket) return;
3278
+ if (!socket.connected) return;
3279
+ const payload = controllerSystemSchema.safeParse({
3280
+ roomId: parsedRoomId,
3281
+ command
3282
+ });
3283
+ if (payload.success) {
3284
+ socket.emit("controller:system", payload.data);
3285
+ }
3286
+ },
3287
+ [parsedRoomId, canConnect, socket, store]
3077
3288
  );
3078
3289
  return {
3079
3290
  roomId: parsedRoomId,
3080
- joinUrl,
3291
+ controllerId: connectionState.controllerId,
3081
3292
  connectionStatus: connectionState.connectionStatus,
3082
- players: connectionState.players,
3083
3293
  lastError: connectionState.lastError,
3084
- mode: connectionState.mode,
3085
3294
  gameState: connectionState.gameState,
3086
- toggleGameState,
3087
- sendState,
3088
- sendSignal,
3295
+ stateMessage: connectionState.stateMessage,
3296
+ sendInput,
3297
+ sendSystemCommand,
3298
+ setNickname,
3089
3299
  reconnect,
3090
- socket: returnSocket,
3091
- isChildMode,
3092
- getInput
3300
+ players: connectionState.players,
3301
+ socket
3093
3302
  };
3094
3303
  };
3095
3304
  var getRoomFromLocation2 = () => {
@@ -3360,7 +3569,109 @@ var useSendSignal = () => {
3360
3569
  );
3361
3570
  return sendSignal;
3362
3571
  };
3572
+ function createAirJamStore2(initializer) {
3573
+ const store = create((set, get, api) => {
3574
+ const baseState = initializer(set, get, api);
3575
+ return {
3576
+ ...baseState,
3577
+ actions: {
3578
+ ...baseState.actions,
3579
+ _syncState: (partial) => {
3580
+ set(partial);
3581
+ }
3582
+ }
3583
+ };
3584
+ });
3585
+ const useSyncedStore = (selector = (s) => s) => {
3586
+ const slice = store(selector);
3587
+ const { getSocket } = useAirJamContext();
3588
+ const role = useAirJamState((state) => state.role);
3589
+ const roomId = useAirJamState((state) => state.roomId);
3590
+ const controllerId = useAirJamState((state) => state.controllerId);
3591
+ const socket = role === "host" ? getSocket("host") : getSocket("controller");
3592
+ useEffect(() => {
3593
+ if (!socket || !roomId || !role) {
3594
+ return;
3595
+ }
3596
+ if (role === "host") {
3597
+ const unsubscribe = store.subscribe((newState) => {
3598
+ const { actions, ...stateData } = newState;
3599
+ socket.emit("host:state_sync", { roomId, data: stateData });
3600
+ });
3601
+ const handleAction = (payload) => {
3602
+ const { actionName, args, controllerId: controllerId2 } = payload;
3603
+ const actionFn = store.getState().actions[actionName];
3604
+ if (actionFn) {
3605
+ actionFn(...args, controllerId2);
3606
+ }
3607
+ };
3608
+ socket.on("airjam:action_rpc", handleAction);
3609
+ return () => {
3610
+ unsubscribe();
3611
+ socket.off("airjam:action_rpc", handleAction);
3612
+ };
3613
+ }
3614
+ if (role === "controller") {
3615
+ const handleSync = (payload) => {
3616
+ const { data } = payload;
3617
+ const currentState = store.getState();
3618
+ const actions = currentState.actions;
3619
+ if (actions._syncState) {
3620
+ actions._syncState(data);
3621
+ } else {
3622
+ store.setState(data);
3623
+ }
3624
+ };
3625
+ socket.on("airjam:state_sync", handleSync);
3626
+ return () => socket.off("airjam:state_sync", handleSync);
3627
+ }
3628
+ }, [socket, role, roomId]);
3629
+ if (role === "controller" && socket && roomId) {
3630
+ let originalActions = null;
3631
+ if (typeof slice === "object" && slice !== null && "actions" in slice) {
3632
+ originalActions = slice.actions;
3633
+ } else if (typeof slice === "object" && slice !== null) {
3634
+ const fullState = store.getState();
3635
+ if (fullState.actions) {
3636
+ const sliceKeys = Object.keys(slice);
3637
+ const actionKeys = Object.keys(fullState.actions);
3638
+ if (sliceKeys.length > 0 && sliceKeys.every(
3639
+ (key) => typeof slice[key] === "function" && actionKeys.includes(key)
3640
+ )) {
3641
+ originalActions = slice;
3642
+ }
3643
+ }
3644
+ }
3645
+ if (originalActions) {
3646
+ const proxyActions = {};
3647
+ Object.keys(originalActions).forEach((key) => {
3648
+ proxyActions[key] = (...args) => {
3649
+ if (!controllerId) {
3650
+ console.warn(
3651
+ "[AirJamStore] Cannot send action RPC: controllerId not set"
3652
+ );
3653
+ return;
3654
+ }
3655
+ socket.emit("controller:action_rpc", {
3656
+ roomId,
3657
+ actionName: key,
3658
+ args,
3659
+ controllerId
3660
+ });
3661
+ };
3662
+ });
3663
+ if (typeof slice === "object" && slice !== null && "actions" in slice) {
3664
+ return { ...slice, actions: proxyActions };
3665
+ } else {
3666
+ return proxyActions;
3667
+ }
3668
+ }
3669
+ }
3670
+ return slice;
3671
+ };
3672
+ return useSyncedStore;
3673
+ }
3363
3674
 
3364
- export { AirJamContext, AirJamOverlay, AirJamProvider, AudioManager, AudioProvider, Button, ChildEvents, ClientEvents, ControllerEvents, ControllerShell, DEFAULT_CONTROLLER_PATH, DEFAULT_MAX_PLAYERS, DEFAULT_SERVER_PORT, Events, HostEvents, INPUT_DEBOUNCE_MS, SOCKET_CONFIG, ServerEvents, Slider, SocketManager, SystemEvents, TOGGLE_DEBOUNCE_MS, UrlBuilder, VolumeControls, buttonVariants, createAudioManager, detectSoundCategory, generateControllerId, generateRoomCode, getLocalNetworkIp, urlBuilder, useAirJamConfig, useAirJamContext, useAirJamController, useAirJamHost, useAirJamShell, useAirJamSocket, useAirJamState, useAudio, useAudioLegacy, useAudioManager, useGetInput, useSendSignal, useVolumeStore };
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 };
3365
3676
  //# sourceMappingURL=index.js.map
3366
3677
  //# sourceMappingURL=index.js.map