@air-jam/sdk 0.1.4 → 0.9.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/LICENSE +21 -0
- package/README.md +627 -57
- package/dist/agent-tooling-BSMGBix9.d.cts +123 -0
- package/dist/agent-tooling-BSMGBix9.d.ts +123 -0
- package/dist/agent-tooling.cjs +83 -0
- package/dist/agent-tooling.cjs.map +1 -0
- package/dist/agent-tooling.d.cts +2 -0
- package/dist/agent-tooling.d.ts +2 -0
- package/dist/agent-tooling.js +17 -0
- package/dist/agent-tooling.js.map +1 -0
- package/dist/arcade/bridge/controller.cjs +749 -0
- package/dist/arcade/bridge/controller.cjs.map +1 -0
- package/dist/arcade/bridge/controller.d.cts +85 -0
- package/dist/arcade/bridge/controller.d.ts +85 -0
- package/dist/arcade/bridge/controller.js +33 -0
- package/dist/arcade/bridge/controller.js.map +1 -0
- package/dist/arcade/bridge/host.cjs +421 -0
- package/dist/arcade/bridge/host.cjs.map +1 -0
- package/dist/arcade/bridge/host.d.cts +73 -0
- package/dist/arcade/bridge/host.d.ts +73 -0
- package/dist/arcade/bridge/host.js +25 -0
- package/dist/arcade/bridge/host.js.map +1 -0
- package/dist/arcade/bridge/iframe.cjs +453 -0
- package/dist/arcade/bridge/iframe.cjs.map +1 -0
- package/dist/arcade/bridge/iframe.d.cts +80 -0
- package/dist/arcade/bridge/iframe.d.ts +80 -0
- package/dist/arcade/bridge/iframe.js +28 -0
- package/dist/arcade/bridge/iframe.js.map +1 -0
- package/dist/arcade/bridge.cjs +1067 -0
- package/dist/arcade/bridge.cjs.map +1 -0
- package/dist/arcade/bridge.d.cts +11 -0
- package/dist/arcade/bridge.d.ts +11 -0
- package/dist/arcade/bridge.js +76 -0
- package/dist/arcade/bridge.js.map +1 -0
- package/dist/arcade/host.cjs +481 -0
- package/dist/arcade/host.cjs.map +1 -0
- package/dist/arcade/host.d.cts +19 -0
- package/dist/arcade/host.d.ts +19 -0
- package/dist/arcade/host.js +14 -0
- package/dist/arcade/host.js.map +1 -0
- package/dist/arcade/surface.cjs +113 -0
- package/dist/arcade/surface.cjs.map +1 -0
- package/dist/arcade/surface.d.cts +14 -0
- package/dist/arcade/surface.d.ts +14 -0
- package/dist/arcade/surface.js +27 -0
- package/dist/arcade/surface.js.map +1 -0
- package/dist/arcade/url.cjs +544 -0
- package/dist/arcade/url.cjs.map +1 -0
- package/dist/arcade/url.d.cts +68 -0
- package/dist/arcade/url.d.ts +68 -0
- package/dist/arcade/url.js +29 -0
- package/dist/arcade/url.js.map +1 -0
- package/dist/arcade-runtime-url-BW-MUAOY.d.cts +28 -0
- package/dist/arcade-runtime-url-l8qj01Pg.d.ts +28 -0
- package/dist/arcade-surface-identity-CQxDpn_w.d.cts +16 -0
- package/dist/arcade-surface-identity-CQxDpn_w.d.ts +16 -0
- package/dist/arcade.cjs +1737 -0
- package/dist/arcade.cjs.map +1 -0
- package/dist/arcade.d.cts +18 -0
- package/dist/arcade.d.ts +18 -0
- package/dist/arcade.js +123 -0
- package/dist/arcade.js.map +1 -0
- package/dist/capabilities.cjs +39 -0
- package/dist/capabilities.cjs.map +1 -0
- package/dist/capabilities.d.cts +31 -0
- package/dist/capabilities.d.ts +31 -0
- package/dist/capabilities.js +12 -0
- package/dist/capabilities.js.map +1 -0
- package/dist/chunk-32NYL7XI.js +539 -0
- package/dist/chunk-32NYL7XI.js.map +1 -0
- package/dist/chunk-3USU7GY2.js +54 -0
- package/dist/chunk-3USU7GY2.js.map +1 -0
- package/dist/chunk-7UXSWCZZ.js +32 -0
- package/dist/chunk-7UXSWCZZ.js.map +1 -0
- package/dist/chunk-BE6Z4SIT.js +65 -0
- package/dist/chunk-BE6Z4SIT.js.map +1 -0
- package/dist/chunk-CABEUV65.js +184 -0
- package/dist/chunk-CABEUV65.js.map +1 -0
- package/dist/chunk-CEJ5RFSG.js +288 -0
- package/dist/chunk-CEJ5RFSG.js.map +1 -0
- package/dist/chunk-EDRQIOCV.js +25 -0
- package/dist/chunk-EDRQIOCV.js.map +1 -0
- package/dist/chunk-EVZJA6RN.js +140 -0
- package/dist/chunk-EVZJA6RN.js.map +1 -0
- package/dist/chunk-FAT2KJ3K.js +238 -0
- package/dist/chunk-FAT2KJ3K.js.map +1 -0
- package/dist/chunk-IKKDONQL.js +1 -0
- package/dist/chunk-IKKDONQL.js.map +1 -0
- package/dist/chunk-JEHV5C2X.js +249 -0
- package/dist/chunk-JEHV5C2X.js.map +1 -0
- package/dist/chunk-JO2HR5PV.js +43 -0
- package/dist/chunk-JO2HR5PV.js.map +1 -0
- package/dist/chunk-JTF47B56.js +1 -0
- package/dist/chunk-JTF47B56.js.map +1 -0
- package/dist/chunk-KXAFI5OP.js +193 -0
- package/dist/chunk-KXAFI5OP.js.map +1 -0
- package/dist/chunk-LIXPF4P6.js +22 -0
- package/dist/chunk-LIXPF4P6.js.map +1 -0
- package/dist/chunk-MPDMJIX5.js +1 -0
- package/dist/chunk-MPDMJIX5.js.map +1 -0
- package/dist/chunk-NCL6WJCL.js +91 -0
- package/dist/chunk-NCL6WJCL.js.map +1 -0
- package/dist/chunk-NUJBMV3O.js +1435 -0
- package/dist/chunk-NUJBMV3O.js.map +1 -0
- package/dist/chunk-TGRTEWYV.js +195 -0
- package/dist/chunk-TGRTEWYV.js.map +1 -0
- package/dist/chunk-UWJOIVON.js +369 -0
- package/dist/chunk-UWJOIVON.js.map +1 -0
- package/dist/chunk-VKBMZHMQ.js +216 -0
- package/dist/chunk-VKBMZHMQ.js.map +1 -0
- package/dist/chunk-W2VK36RO.js +11 -0
- package/dist/chunk-W2VK36RO.js.map +1 -0
- package/dist/chunk-W3YA5BWR.js +126 -0
- package/dist/chunk-W3YA5BWR.js.map +1 -0
- package/dist/chunk-X24K52DG.js +12 -0
- package/dist/chunk-X24K52DG.js.map +1 -0
- package/dist/chunk-YXHH3MQT.js +230 -0
- package/dist/chunk-YXHH3MQT.js.map +1 -0
- package/dist/chunk-ZLPL2R3R.js +183 -0
- package/dist/chunk-ZLPL2R3R.js.map +1 -0
- package/dist/chunk-ZTQ5SP4H.js +9 -0
- package/dist/chunk-ZTQ5SP4H.js.map +1 -0
- package/dist/controller-Bod8YYr1.d.cts +172 -0
- package/dist/controller-DxVchfiA.d.ts +172 -0
- package/dist/dev-log-events-CVAM29hx.d.cts +123 -0
- package/dist/dev-log-events-CVAM29hx.d.ts +123 -0
- package/dist/handshake-CC_LrK5g.d.cts +31 -0
- package/dist/handshake-CC_LrK5g.d.ts +31 -0
- package/dist/host-8hmq_Sgc.d.cts +109 -0
- package/dist/host-Cw-N6e-5.d.ts +109 -0
- package/dist/index.cjs +8730 -3426
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +676 -1070
- package/dist/index.d.ts +676 -1070
- package/dist/index.js +4892 -3196
- package/dist/index.js.map +1 -1
- package/dist/metadata.cjs +114 -0
- package/dist/metadata.cjs.map +1 -0
- package/dist/metadata.d.cts +95 -0
- package/dist/metadata.d.ts +95 -0
- package/dist/metadata.js +83 -0
- package/dist/metadata.js.map +1 -0
- package/dist/notices-CnGaaS8B.d.ts +38 -0
- package/dist/notices-NyDM5Mtz.d.cts +38 -0
- package/dist/platform-machine.cjs +425 -0
- package/dist/platform-machine.cjs.map +1 -0
- package/dist/platform-machine.d.cts +1183 -0
- package/dist/platform-machine.d.ts +1183 -0
- package/dist/platform-machine.js +309 -0
- package/dist/platform-machine.js.map +1 -0
- package/dist/platform-settings-cuor3i11.d.cts +48 -0
- package/dist/platform-settings-cuor3i11.d.ts +48 -0
- package/dist/prefabs.cjs +36 -0
- package/dist/prefabs.cjs.map +1 -0
- package/dist/prefabs.d.cts +49 -0
- package/dist/prefabs.d.ts +49 -0
- package/dist/prefabs.js +8 -0
- package/dist/prefabs.js.map +1 -0
- package/dist/preview.cjs +2620 -0
- package/dist/preview.cjs.map +1 -0
- package/dist/preview.d.cts +155 -0
- package/dist/preview.d.ts +155 -0
- package/dist/preview.js +1671 -0
- package/dist/preview.js.map +1 -0
- package/dist/protocol.cjs +621 -54
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +76 -240
- package/dist/protocol.d.ts +76 -240
- package/dist/protocol.js +100 -2
- package/dist/protocol.js.map +1 -1
- package/dist/realtime-client-Cu8yVJFw.d.cts +15 -0
- package/dist/realtime-client-Cu8yVJFw.d.ts +15 -0
- package/dist/release.cjs +143 -0
- package/dist/release.cjs.map +1 -0
- package/dist/release.d.cts +64 -0
- package/dist/release.d.ts +64 -0
- package/dist/release.js +43 -0
- package/dist/release.js.map +1 -0
- package/dist/runtime-topology.cjs +405 -0
- package/dist/runtime-topology.cjs.map +1 -0
- package/dist/runtime-topology.d.cts +59 -0
- package/dist/runtime-topology.d.ts +59 -0
- package/dist/runtime-topology.js +31 -0
- package/dist/runtime-topology.js.map +1 -0
- package/dist/standard-match-phase-BucA5dYo.d.ts +44 -0
- package/dist/standard-match-phase-U2ra8J-0.d.cts +44 -0
- package/dist/sync-B6QsNrXz.d.cts +125 -0
- package/dist/sync-B6QsNrXz.d.ts +125 -0
- package/dist/ui.cjs +3061 -0
- package/dist/ui.cjs.map +1 -0
- package/dist/ui.d.cts +320 -0
- package/dist/ui.d.ts +320 -0
- package/dist/ui.js +1719 -0
- package/dist/ui.js.map +1 -0
- package/dist/url-policy-C89zxgw9.d.cts +9 -0
- package/dist/url-policy-C89zxgw9.d.ts +9 -0
- package/package.json +155 -10
- package/src/agent/agent-action.ts +304 -0
- package/src/agent/agent-contract.ts +180 -0
- package/src/agent-tooling.ts +20 -0
- package/src/arcade/bridge/controller.ts +15 -0
- package/src/arcade/bridge/host.ts +12 -0
- package/src/arcade/bridge/iframe.ts +61 -0
- package/src/arcade/bridge.ts +3 -0
- package/src/arcade/host.ts +1 -0
- package/src/arcade/surface.ts +4 -0
- package/src/arcade/url.ts +60 -0
- package/src/arcade.ts +4 -0
- package/src/audio/audio-manager.ts +162 -171
- package/src/audio/hooks.tsx +218 -97
- package/src/audio/index.ts +1 -1
- package/src/audio/music.tsx +139 -0
- package/src/capabilities/manifest.ts +71 -0
- package/src/capabilities.ts +12 -0
- package/src/components/connection-status-pill.tsx +55 -0
- package/src/components/controller-player-name-field.tsx +119 -0
- package/src/components/controller-primary-action.tsx +58 -0
- package/src/components/host-mute-button.tsx +49 -0
- package/src/components/join-qr-overlay.tsx +133 -0
- package/src/components/join-url-action-buttons.tsx +95 -0
- package/src/components/join-url-controls.tsx +58 -0
- package/src/components/join-url-field.tsx +52 -0
- package/src/components/lifecycle-action-group.tsx +129 -0
- package/src/components/player-avatar-strip.tsx +65 -0
- package/src/components/player-avatar.tsx +42 -13
- package/src/components/room-qr-code.tsx +125 -0
- package/src/components/runtime-shell-header.tsx +37 -0
- package/src/components/shell-classes.ts +19 -0
- package/src/components/surface-orientation-layout.ts +60 -0
- package/src/components/surface-viewport-layout.ts +268 -0
- package/src/components/surface-viewport.tsx +314 -0
- package/src/components/ui/button.tsx +4 -6
- package/src/components/ui/slider.tsx +1 -1
- package/src/components/volume-controls.tsx +65 -6
- package/src/context/air-jam-context.tsx +209 -161
- package/src/context/index.ts +2 -2
- package/src/context/session-providers.tsx +77 -0
- package/src/context/session-scope.ts +64 -0
- package/src/context/socket-manager.ts +6 -24
- package/src/contracts/v2/bridge.ts +261 -0
- package/src/contracts/v2/handshake.ts +40 -0
- package/src/contracts/v2/index.ts +2 -0
- package/src/dev/browser-log-sink.ts +912 -0
- package/src/diagnostics.ts +128 -0
- package/src/events.ts +7 -34
- package/src/hooks/internal/use-controller-runtime-api.ts +875 -0
- package/src/hooks/internal/use-host-runtime-api.ts +1051 -0
- package/src/hooks/internal/use-runtime-control-contract.ts +15 -0
- package/src/hooks/internal/use-runtime-inspection-contract.ts +16 -0
- package/src/hooks/internal/use-runtime-observability-contract.ts +24 -0
- package/src/hooks/use-air-jam-controller.ts +155 -475
- package/src/hooks/use-air-jam-host.ts +156 -485
- package/src/hooks/use-connection-status.ts +8 -0
- package/src/hooks/use-controller-lifecycle-intents.ts +27 -0
- package/src/hooks/use-controller-lifecycle-permissions.ts +36 -0
- package/src/hooks/use-controller-shell-status.ts +40 -0
- package/src/hooks/use-controller-tick.ts +65 -0
- package/src/hooks/use-controller-toasts.ts +116 -0
- package/src/hooks/use-get-input.ts +8 -5
- package/src/hooks/use-host-arcade-restore.ts +30 -0
- package/src/hooks/use-host-join-controls.ts +152 -0
- package/src/hooks/use-host-tick.ts +171 -0
- package/src/hooks/use-input-writer.ts +83 -0
- package/src/hooks/use-lifecycle-action-group-model.ts +98 -0
- package/src/hooks/use-players.ts +12 -0
- package/src/hooks/use-room.ts +22 -0
- package/src/hooks/use-send-signal.ts +6 -2
- package/src/index.ts +205 -31
- package/src/internal/input-manager.ts +195 -215
- package/src/lifecycle/index.ts +9 -0
- package/src/lifecycle/standard-match-phase.ts +32 -0
- package/src/metadata/manifest.ts +152 -0
- package/src/metadata.ts +12 -0
- package/src/platform-machine.ts +475 -0
- package/src/prefabs/types.ts +82 -0
- package/src/prefabs.ts +12 -0
- package/src/preview/host-workspace.tsx +59 -0
- package/src/preview/identity.ts +66 -0
- package/src/preview/layout.ts +223 -0
- package/src/preview/manager.ts +577 -0
- package/src/preview/messages.ts +26 -0
- package/src/preview/ownership.ts +81 -0
- package/src/preview/url.ts +117 -0
- package/src/preview/window.tsx +490 -0
- package/src/preview/workspace.tsx +678 -0
- package/src/preview.ts +42 -0
- package/src/protocol/arcade-platform-actions.ts +29 -0
- package/src/protocol/controller.ts +187 -0
- package/src/protocol/core.ts +23 -0
- package/src/protocol/dev-log-events.ts +222 -0
- package/src/protocol/errors.ts +21 -0
- package/src/protocol/host-grant.ts +185 -0
- package/src/protocol/host.ts +138 -0
- package/src/protocol/notices.ts +43 -0
- package/src/protocol/signals.ts +38 -0
- package/src/protocol/socket-events.ts +154 -0
- package/src/protocol/sync.ts +121 -0
- package/src/protocol/url-policy.ts +63 -0
- package/src/protocol.ts +12 -386
- package/src/qrcode.d.ts +16 -0
- package/src/release.ts +99 -0
- package/src/runtime/air-jam-config.ts +287 -0
- package/src/runtime/air-jam-error-boundary.tsx +672 -0
- package/src/runtime/arcade-bridge-request-surface.ts +15 -0
- package/src/runtime/arcade-runtime-url.ts +95 -0
- package/src/runtime/arcade-surface-identity.ts +16 -0
- package/src/runtime/contracts/control.ts +68 -0
- package/src/runtime/contracts/inspection.ts +165 -0
- package/src/runtime/contracts/observability.ts +94 -0
- package/src/runtime/controller-bridge.ts +451 -0
- package/src/runtime/controller-identity.ts +132 -0
- package/src/runtime/controller-presentation.ts +24 -0
- package/src/runtime/controller-realtime-client.ts +591 -0
- package/src/runtime/create-air-jam-app.tsx +260 -0
- package/src/runtime/dev-runtime-events.ts +36 -0
- package/src/runtime/embedded-runtime-adapters.ts +68 -0
- package/src/runtime/host-bridge.ts +388 -0
- package/src/runtime/host-realtime-client.ts +550 -0
- package/src/runtime/iframe-bridge.ts +135 -0
- package/src/runtime/realtime-client.ts +20 -0
- package/src/runtime/router-basename.ts +25 -0
- package/src/runtime/runtime-owner-contexts.tsx +4 -0
- package/src/runtime/runtime-session-params.ts +169 -0
- package/src/runtime/sdk-version.ts +6 -0
- package/src/runtime/session-runtimes.tsx +188 -0
- package/src/runtime/validate-arcade-bridge-attach.ts +14 -0
- package/src/runtime-control.ts +10 -0
- package/src/runtime-inspection.ts +14 -0
- package/src/runtime-observability.ts +9 -0
- package/src/runtime-topology.ts +569 -0
- package/src/settings/platform-settings-bridge.ts +336 -0
- package/src/settings/platform-settings-runtime.tsx +387 -0
- package/src/settings/platform-settings.ts +288 -0
- package/src/state/connection-store.ts +80 -12
- package/src/store/air-jam-store-domain-constants.ts +4 -0
- package/src/store/create-air-jam-store.ts +1094 -227
- package/src/styles.css +4 -38
- package/src/ui.ts +29 -0
- package/src/utils/is-rpc-serializable.ts +56 -0
- package/src/utils/player-avatar-url.ts +48 -0
- package/src/utils/url-builder.ts +7 -0
- package/dist/.tsbuildinfo +0 -1
- package/dist/chunk-B5DURUWT.js +0 -80
- package/dist/chunk-B5DURUWT.js.map +0 -1
- package/src/AirJamClient.ts +0 -224
- package/src/audio/volume-store.ts +0 -124
- package/src/components/controller-shell.tsx +0 -346
- package/src/components/host-shell.tsx +0 -520
- package/src/components/qr-scanner-dialog.tsx +0 -373
- package/src/components/ui/alert.tsx +0 -66
- package/src/components/ui/avatar.tsx +0 -46
- package/src/components/ui/badge.tsx +0 -47
- package/src/components/ui/card.tsx +0 -92
- package/src/components/ui/dialog.tsx +0 -122
- package/src/components/ui/tabs.tsx +0 -64
- package/src/hooks/use-air-jam-shell.ts +0 -379
- package/src/hooks/use-fullscreen.ts +0 -108
|
@@ -1,274 +1,1141 @@
|
|
|
1
|
-
import { useEffect, useRef } from "react";
|
|
1
|
+
import { useEffect, useMemo, useRef, type MutableRefObject } from "react";
|
|
2
2
|
import { create, type StateCreator } from "zustand";
|
|
3
|
+
import type { StoreApi } from "zustand/vanilla";
|
|
3
4
|
import { useAirJamContext, useAirJamState } from "../context/air-jam-context";
|
|
5
|
+
import { emitAirJamDiagnostic } from "../diagnostics";
|
|
4
6
|
import type {
|
|
7
|
+
AirJamActionActorRole,
|
|
8
|
+
AirJamActionInvocationResult,
|
|
9
|
+
AirJamActionPayload,
|
|
5
10
|
AirJamActionRpcPayload,
|
|
6
11
|
AirJamStateSyncPayload,
|
|
7
12
|
} from "../protocol";
|
|
13
|
+
import { resolveImplicitReplicatedStoreDomainFromWindow } from "../runtime/arcade-runtime-url";
|
|
14
|
+
import { getControllerRealtimeClient } from "../runtime/controller-realtime-client";
|
|
15
|
+
import { getHostRealtimeClient } from "../runtime/host-realtime-client";
|
|
16
|
+
import type { AirJamRealtimeClient } from "../runtime/realtime-client";
|
|
17
|
+
import { isRpcSerializable } from "../utils/is-rpc-serializable";
|
|
18
|
+
import {
|
|
19
|
+
AIR_JAM_ARCADE_SURFACE_STORE_DOMAIN,
|
|
20
|
+
AIR_JAM_DEFAULT_STORE_DOMAIN,
|
|
21
|
+
} from "./air-jam-store-domain-constants";
|
|
22
|
+
|
|
23
|
+
const INTERNAL_ACTION_PREFIX = "_";
|
|
24
|
+
const UNRESOLVED_ACTOR_ID = "unknown";
|
|
25
|
+
|
|
26
|
+
export interface CreateAirJamStoreOptions {
|
|
27
|
+
storeDomain?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const isEventLikePayload = (payload: unknown): boolean => {
|
|
31
|
+
if (payload === null || typeof payload !== "object") {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const candidate = payload as Record<string, unknown>;
|
|
36
|
+
return (
|
|
37
|
+
typeof candidate.preventDefault === "function" ||
|
|
38
|
+
typeof candidate.stopPropagation === "function" ||
|
|
39
|
+
typeof candidate.persist === "function" ||
|
|
40
|
+
("nativeEvent" in candidate &&
|
|
41
|
+
("target" in candidate || "currentTarget" in candidate))
|
|
42
|
+
);
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const isPlainActionPayload = (
|
|
46
|
+
payload: unknown,
|
|
47
|
+
): payload is AirJamActionPayload => {
|
|
48
|
+
if (
|
|
49
|
+
payload === null ||
|
|
50
|
+
typeof payload !== "object" ||
|
|
51
|
+
Array.isArray(payload)
|
|
52
|
+
) {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const prototype = Object.getPrototypeOf(payload);
|
|
57
|
+
return prototype === Object.prototype || prototype === null;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export interface AirJamActionContext {
|
|
61
|
+
actorId: string;
|
|
62
|
+
role: AirJamActionActorRole;
|
|
63
|
+
connectedPlayerIds: string[];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface AirJamActionRejection {
|
|
67
|
+
readonly __airJamActionRejection: true;
|
|
68
|
+
reason: string;
|
|
69
|
+
message: string;
|
|
70
|
+
details?: AirJamActionPayload;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface AirJamActionAcceptance<TResult = unknown> {
|
|
74
|
+
readonly __airJamActionAcceptance: true;
|
|
75
|
+
result?: TResult;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
type AirJamActionHandler = (
|
|
79
|
+
ctx: AirJamActionContext,
|
|
80
|
+
// Internal existential handler shape for heterogenous action maps.
|
|
81
|
+
// Store authors still get precise payload types through inference at the public API.
|
|
82
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
83
|
+
payload: any,
|
|
84
|
+
) => unknown;
|
|
85
|
+
type AirJamActionMap = Record<string, AirJamActionHandler>;
|
|
86
|
+
type AirJamActionName<TActions extends AirJamActionMap> = Extract<
|
|
87
|
+
keyof TActions,
|
|
88
|
+
string
|
|
89
|
+
>;
|
|
90
|
+
|
|
91
|
+
type IsValidActionPayloadType<TPayload> = [TPayload] extends [undefined]
|
|
92
|
+
? true
|
|
93
|
+
: TPayload extends readonly unknown[]
|
|
94
|
+
? false
|
|
95
|
+
: TPayload extends object
|
|
96
|
+
? true
|
|
97
|
+
: false;
|
|
98
|
+
|
|
99
|
+
type InvalidActionPayloadKeys<TActions extends AirJamActionMap> = {
|
|
100
|
+
[K in keyof TActions]: TActions[K] extends (
|
|
101
|
+
ctx: AirJamActionContext,
|
|
102
|
+
payload: infer TPayload,
|
|
103
|
+
) => unknown
|
|
104
|
+
? IsValidActionPayloadType<TPayload> extends true
|
|
105
|
+
? never
|
|
106
|
+
: K
|
|
107
|
+
: K;
|
|
108
|
+
}[keyof TActions];
|
|
109
|
+
|
|
110
|
+
type InvalidActionPayloadKeyNames<TActions extends AirJamActionMap> = Extract<
|
|
111
|
+
InvalidActionPayloadKeys<TActions>,
|
|
112
|
+
string
|
|
113
|
+
>;
|
|
114
|
+
|
|
115
|
+
type AirJamInvalidActionPayloadDiagnostic<TActions extends AirJamActionMap> = {
|
|
116
|
+
readonly __airJamInvalidActionPayloads__: InvalidActionPayloadKeyNames<TActions>;
|
|
117
|
+
readonly __airJamActionPayloadRule__: "Networked store action payloads must be omitted or one plain object payload. Unions like T | undefined, arrays, and primitives are not valid payload roots.";
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
type AirJamNetworkedState<TActions extends AirJamActionMap = AirJamActionMap> =
|
|
121
|
+
{
|
|
122
|
+
actions: TActions;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
type AirJamActionDispatchMap<TActions extends AirJamActionMap> = {
|
|
126
|
+
[K in keyof TActions]: TActions[K] extends (
|
|
127
|
+
ctx: AirJamActionContext,
|
|
128
|
+
payload: infer TPayload,
|
|
129
|
+
) => infer TResult
|
|
130
|
+
? [TPayload] extends [undefined]
|
|
131
|
+
? () => Promise<
|
|
132
|
+
AirJamActionInvocationResult<InferAirJamActionResult<TResult>>
|
|
133
|
+
>
|
|
134
|
+
: TPayload extends readonly unknown[]
|
|
135
|
+
? never
|
|
136
|
+
: TPayload extends object
|
|
137
|
+
? (
|
|
138
|
+
payload: TPayload,
|
|
139
|
+
) => Promise<
|
|
140
|
+
AirJamActionInvocationResult<InferAirJamActionResult<TResult>>
|
|
141
|
+
>
|
|
142
|
+
: never
|
|
143
|
+
: never;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
type InferAirJamActionResult<TResult> =
|
|
147
|
+
TResult extends AirJamActionAcceptance<infer TAccepted>
|
|
148
|
+
? TAccepted
|
|
149
|
+
: TResult extends AirJamActionRejection
|
|
150
|
+
? never
|
|
151
|
+
: TResult;
|
|
152
|
+
|
|
153
|
+
interface StoreRuntimeSnapshot {
|
|
154
|
+
socket: AirJamRealtimeClient | null;
|
|
155
|
+
role: AirJamActionActorRole | null;
|
|
156
|
+
roomId: string | null;
|
|
157
|
+
resolvedStoreDomain: string;
|
|
158
|
+
connectionStatus: string | null;
|
|
159
|
+
canBroadcastHostState: boolean;
|
|
160
|
+
connectedPlayerIds: string[];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
interface StoreRuntimeBinding {
|
|
164
|
+
refCount: number;
|
|
165
|
+
flushHostStateSync?: () => void;
|
|
166
|
+
lastHostFlushKey?: string;
|
|
167
|
+
cleanup: () => void;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export type AirJamHostActionEvent<
|
|
171
|
+
TActions extends AirJamActionMap = AirJamActionMap,
|
|
172
|
+
TActionName extends AirJamActionName<TActions> = AirJamActionName<TActions>,
|
|
173
|
+
> =
|
|
174
|
+
TActionName extends AirJamActionName<TActions>
|
|
175
|
+
? TActions[TActionName] extends (
|
|
176
|
+
ctx: AirJamActionContext,
|
|
177
|
+
payload: infer TPayload,
|
|
178
|
+
) => infer TResult
|
|
179
|
+
? {
|
|
180
|
+
actionName: TActionName;
|
|
181
|
+
payload: TPayload;
|
|
182
|
+
context: AirJamActionContext;
|
|
183
|
+
acknowledgement: AirJamActionInvocationResult<
|
|
184
|
+
InferAirJamActionResult<TResult>
|
|
185
|
+
>;
|
|
186
|
+
invocationKind: "local" | "rpc";
|
|
187
|
+
roomId: string | null;
|
|
188
|
+
storeDomain: string;
|
|
189
|
+
}
|
|
190
|
+
: never
|
|
191
|
+
: never;
|
|
192
|
+
|
|
193
|
+
export interface AirJamHostActionSubscriptionOptions<
|
|
194
|
+
TActions extends AirJamActionMap = AirJamActionMap,
|
|
195
|
+
> {
|
|
196
|
+
actionNames?: readonly AirJamActionName<TActions>[];
|
|
197
|
+
includeRejected?: boolean;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export type AirJamHostActionListener<
|
|
201
|
+
TActions extends AirJamActionMap = AirJamActionMap,
|
|
202
|
+
> = (event: AirJamHostActionEvent<TActions>) => void;
|
|
203
|
+
|
|
204
|
+
interface HostActionListenerRegistration<TActions extends AirJamActionMap> {
|
|
205
|
+
actionNames: ReadonlySet<string> | null;
|
|
206
|
+
includeRejected: boolean;
|
|
207
|
+
listener: AirJamHostActionListener<TActions>;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export type AirJamSyncedStoreHook<T extends AirJamNetworkedState> = {
|
|
211
|
+
<U>(selector?: (state: T) => U): U;
|
|
212
|
+
useActions: () => AirJamActionDispatchMap<T["actions"]>;
|
|
213
|
+
asPlayer: (controllerId: string) => AirJamActionDispatchMap<T["actions"]>;
|
|
214
|
+
getState: () => T;
|
|
215
|
+
subscribe: StoreApi<T>["subscribe"];
|
|
216
|
+
subscribeHostActions: (
|
|
217
|
+
listener: AirJamHostActionListener<T["actions"]>,
|
|
218
|
+
options?: AirJamHostActionSubscriptionOptions<T["actions"]>,
|
|
219
|
+
) => () => void;
|
|
220
|
+
useHostActionListener: (
|
|
221
|
+
listener: AirJamHostActionListener<T["actions"]>,
|
|
222
|
+
options?: AirJamHostActionSubscriptionOptions<T["actions"]>,
|
|
223
|
+
) => void;
|
|
224
|
+
useLiveStateRef: () => MutableRefObject<T>;
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
export const isInternalActionName = (actionName: string): boolean =>
|
|
228
|
+
actionName.startsWith(INTERNAL_ACTION_PREFIX);
|
|
229
|
+
|
|
230
|
+
export const acceptAirJamAction = <TResult = unknown>(
|
|
231
|
+
result?: TResult,
|
|
232
|
+
): AirJamActionAcceptance<TResult> => ({
|
|
233
|
+
__airJamActionAcceptance: true,
|
|
234
|
+
...(result !== undefined ? { result } : {}),
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
export const rejectAirJamAction = (
|
|
238
|
+
reason: string,
|
|
239
|
+
message: string,
|
|
240
|
+
details?: AirJamActionPayload,
|
|
241
|
+
): AirJamActionRejection => ({
|
|
242
|
+
__airJamActionRejection: true,
|
|
243
|
+
reason,
|
|
244
|
+
message,
|
|
245
|
+
...(details ? { details } : {}),
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
const isAirJamActionAcceptance = (
|
|
249
|
+
value: unknown,
|
|
250
|
+
): value is AirJamActionAcceptance<unknown> =>
|
|
251
|
+
typeof value === "object" &&
|
|
252
|
+
value !== null &&
|
|
253
|
+
(value as { __airJamActionAcceptance?: boolean }).__airJamActionAcceptance ===
|
|
254
|
+
true;
|
|
255
|
+
|
|
256
|
+
const isAirJamActionRejection = (
|
|
257
|
+
value: unknown,
|
|
258
|
+
): value is AirJamActionRejection =>
|
|
259
|
+
typeof value === "object" &&
|
|
260
|
+
value !== null &&
|
|
261
|
+
(value as { __airJamActionRejection?: boolean }).__airJamActionRejection ===
|
|
262
|
+
true;
|
|
263
|
+
|
|
264
|
+
const createClientRejectedActionResult = (
|
|
265
|
+
reason: string,
|
|
266
|
+
message: string,
|
|
267
|
+
details?: AirJamActionPayload,
|
|
268
|
+
): AirJamActionInvocationResult => ({
|
|
269
|
+
ok: false,
|
|
270
|
+
status: "rejected",
|
|
271
|
+
source: "client",
|
|
272
|
+
reason,
|
|
273
|
+
message,
|
|
274
|
+
...(details ? { details } : {}),
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
const createServerRejectedActionResult = (
|
|
278
|
+
reason: string,
|
|
279
|
+
message: string,
|
|
280
|
+
details?: AirJamActionPayload,
|
|
281
|
+
): AirJamActionInvocationResult => ({
|
|
282
|
+
ok: false,
|
|
283
|
+
status: "rejected",
|
|
284
|
+
source: "server",
|
|
285
|
+
reason,
|
|
286
|
+
message,
|
|
287
|
+
...(details ? { details } : {}),
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
const normalizeAirJamActionInvocationResult = (
|
|
291
|
+
value: unknown,
|
|
292
|
+
source: "client" | "host",
|
|
293
|
+
): AirJamActionInvocationResult => {
|
|
294
|
+
if (isAirJamActionRejection(value)) {
|
|
295
|
+
return {
|
|
296
|
+
ok: false,
|
|
297
|
+
status: "rejected",
|
|
298
|
+
source,
|
|
299
|
+
reason: value.reason,
|
|
300
|
+
message: value.message,
|
|
301
|
+
...(value.details ? { details: value.details } : {}),
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (isAirJamActionAcceptance(value)) {
|
|
306
|
+
return {
|
|
307
|
+
ok: true,
|
|
308
|
+
status: "accepted",
|
|
309
|
+
source,
|
|
310
|
+
...(value.result !== undefined ? { result: value.result } : {}),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
return {
|
|
315
|
+
ok: true,
|
|
316
|
+
status: "accepted",
|
|
317
|
+
source,
|
|
318
|
+
...(value !== undefined ? { result: value } : {}),
|
|
319
|
+
};
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const stripActionsFromState = <T extends AirJamNetworkedState>(
|
|
323
|
+
data: Partial<T>,
|
|
324
|
+
): Partial<T> => {
|
|
325
|
+
const { actions: _ignored, ...stateData } = data as Partial<T> & {
|
|
326
|
+
actions?: unknown;
|
|
327
|
+
};
|
|
328
|
+
return stateData as Partial<T>;
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
const toActionContext = (
|
|
332
|
+
payload: AirJamActionRpcPayload,
|
|
333
|
+
connectedPlayerIds: string[],
|
|
334
|
+
): AirJamActionContext => ({
|
|
335
|
+
actorId: payload.actor.id || UNRESOLVED_ACTOR_ID,
|
|
336
|
+
role: payload.actor.role,
|
|
337
|
+
connectedPlayerIds,
|
|
338
|
+
});
|
|
8
339
|
|
|
9
340
|
/**
|
|
10
|
-
* Creates a networked Zustand store that
|
|
11
|
-
*
|
|
12
|
-
* The store pattern works as follows:
|
|
13
|
-
* - Host: Stores state locally and broadcasts changes to all controllers
|
|
14
|
-
* - Controller: Sends action RPCs to host, receives state updates from host
|
|
341
|
+
* Creates a networked Zustand store that syncs state from host to controllers.
|
|
15
342
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
* phase: "lobby" | "playing" | "gameover";
|
|
20
|
-
* scores: { team1: number; team2: number };
|
|
21
|
-
* actions: {
|
|
22
|
-
* setPhase: (phase: "lobby" | "playing") => void;
|
|
23
|
-
* scorePoint: (team: "team1" | "team2") => void;
|
|
24
|
-
* };
|
|
25
|
-
* }
|
|
343
|
+
* Host is the source of truth:
|
|
344
|
+
* - Host broadcasts state updates to all controllers.
|
|
345
|
+
* - Controllers invoke actions through RPC to host.
|
|
26
346
|
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* actions: {
|
|
31
|
-
* setPhase: (phase) => set({ phase }),
|
|
32
|
-
* scorePoint: (team) => set((state) => ({
|
|
33
|
-
* scores: { ...state.scores, [team]: state.scores[team] + 1 }
|
|
34
|
-
* })),
|
|
35
|
-
* },
|
|
36
|
-
* }));
|
|
37
|
-
* ```
|
|
347
|
+
* `storeDomain` isolates sync and action RPC so multiple replicated stores can coexist in one room
|
|
348
|
+
* (e.g. arcade shell vs running game). When omitted, resolves from the runtime URL: explicit
|
|
349
|
+
* `aj_store_domain`, else embedded Arcade identity (`aj_arcade_*`), else the default domain.
|
|
38
350
|
*/
|
|
39
|
-
export function createAirJamStore<
|
|
40
|
-
T extends
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
351
|
+
export function createAirJamStore<T extends AirJamNetworkedState>(
|
|
352
|
+
initializer: InvalidActionPayloadKeys<T["actions"]> extends never
|
|
353
|
+
? StateCreator<T>
|
|
354
|
+
: StateCreator<T> & AirJamInvalidActionPayloadDiagnostic<T["actions"]>,
|
|
355
|
+
options?: CreateAirJamStoreOptions,
|
|
356
|
+
): AirJamSyncedStoreHook<T> {
|
|
357
|
+
const store = create<T>((set, get, api) => initializer(set, get, api));
|
|
358
|
+
const runtimeSnapshotRef: { current: StoreRuntimeSnapshot } = {
|
|
359
|
+
current: {
|
|
360
|
+
socket: null,
|
|
361
|
+
role: null,
|
|
362
|
+
roomId: null,
|
|
363
|
+
resolvedStoreDomain: AIR_JAM_DEFAULT_STORE_DOMAIN,
|
|
364
|
+
connectionStatus: null,
|
|
365
|
+
canBroadcastHostState: false,
|
|
366
|
+
connectedPlayerIds: [],
|
|
367
|
+
},
|
|
368
|
+
};
|
|
369
|
+
const runtimeBindings = new Map<string, StoreRuntimeBinding>();
|
|
370
|
+
const hostActionListeners = new Set<
|
|
371
|
+
HostActionListenerRegistration<T["actions"]>
|
|
372
|
+
>();
|
|
373
|
+
|
|
374
|
+
const createDispatchedActions = (
|
|
375
|
+
mode:
|
|
376
|
+
| {
|
|
377
|
+
kind: "default";
|
|
378
|
+
}
|
|
379
|
+
| {
|
|
380
|
+
kind: "player";
|
|
381
|
+
controllerId: string;
|
|
55
382
|
},
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
383
|
+
): AirJamActionDispatchMap<T["actions"]> => {
|
|
384
|
+
const sourceActions = store.getState().actions;
|
|
385
|
+
const actionDispatch = {} as AirJamActionDispatchMap<T["actions"]>;
|
|
386
|
+
|
|
387
|
+
for (const actionName of Object.keys(sourceActions)) {
|
|
388
|
+
if (isInternalActionName(actionName)) {
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
59
391
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
392
|
+
const sourceAction = sourceActions[actionName];
|
|
393
|
+
|
|
394
|
+
(
|
|
395
|
+
actionDispatch as unknown as Record<
|
|
396
|
+
string,
|
|
397
|
+
(payload: unknown) => Promise<AirJamActionInvocationResult>
|
|
398
|
+
>
|
|
399
|
+
)[actionName] = async (
|
|
400
|
+
payload: unknown,
|
|
401
|
+
): Promise<AirJamActionInvocationResult> => {
|
|
402
|
+
const normalizedPayload = isEventLikePayload(payload)
|
|
403
|
+
? undefined
|
|
404
|
+
: payload;
|
|
405
|
+
|
|
406
|
+
if (normalizedPayload !== payload) {
|
|
407
|
+
emitAirJamDiagnostic({
|
|
408
|
+
code: "AJ_STORE_ACTION_EVENT_PAYLOAD_DROPPED",
|
|
409
|
+
severity: "warn",
|
|
410
|
+
message: `[AirJamStore] Action "${actionName}" received an event-like payload. Dropping payload and continuing.`,
|
|
411
|
+
details: { actionName },
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const runtime = runtimeSnapshotRef.current;
|
|
416
|
+
|
|
417
|
+
if (mode.kind === "player" && runtime.role !== "host") {
|
|
418
|
+
emitAirJamDiagnostic({
|
|
419
|
+
code: "AJ_STORE_PLAYER_ACTIONS_HOST_ONLY",
|
|
420
|
+
severity: "warn",
|
|
421
|
+
message: `[AirJamStore] Player impersonation for action "${actionName}" is host-only.`,
|
|
422
|
+
details: {
|
|
423
|
+
actionName,
|
|
424
|
+
role: runtime.role,
|
|
425
|
+
controllerId: mode.controllerId,
|
|
426
|
+
},
|
|
427
|
+
});
|
|
428
|
+
return createClientRejectedActionResult(
|
|
429
|
+
"player_actions_host_only",
|
|
430
|
+
`Store action "${actionName}" cannot impersonate a player outside the host runtime.`,
|
|
431
|
+
{
|
|
432
|
+
actionName,
|
|
433
|
+
...(runtime.role ? { role: runtime.role } : {}),
|
|
434
|
+
controllerId: mode.controllerId,
|
|
435
|
+
},
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
if (mode.kind === "player") {
|
|
440
|
+
const normalizedControllerId = mode.controllerId.trim();
|
|
441
|
+
if (normalizedControllerId.length === 0) {
|
|
442
|
+
emitAirJamDiagnostic({
|
|
443
|
+
code: "AJ_STORE_PLAYER_ACTIONS_INVALID_ACTOR_ID",
|
|
444
|
+
severity: "warn",
|
|
445
|
+
message: `[AirJamStore] Player impersonation for action "${actionName}" requires a non-empty controller id.`,
|
|
446
|
+
details: {
|
|
447
|
+
actionName,
|
|
448
|
+
},
|
|
449
|
+
});
|
|
450
|
+
return createClientRejectedActionResult(
|
|
451
|
+
"player_actor_id_invalid",
|
|
452
|
+
`Store action "${actionName}" requires a non-empty controller id for player impersonation.`,
|
|
453
|
+
{
|
|
454
|
+
actionName,
|
|
455
|
+
},
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
if (!runtime.connectedPlayerIds.includes(normalizedControllerId)) {
|
|
460
|
+
emitAirJamDiagnostic({
|
|
461
|
+
code: "AJ_STORE_PLAYER_ACTIONS_PLAYER_NOT_CONNECTED",
|
|
462
|
+
severity: "warn",
|
|
463
|
+
message: `[AirJamStore] Player impersonation for action "${actionName}" requires a currently connected controller.`,
|
|
464
|
+
details: {
|
|
465
|
+
actionName,
|
|
466
|
+
controllerId: normalizedControllerId,
|
|
467
|
+
connectedPlayerIds: runtime.connectedPlayerIds,
|
|
468
|
+
},
|
|
469
|
+
});
|
|
470
|
+
return createClientRejectedActionResult(
|
|
471
|
+
"player_not_connected",
|
|
472
|
+
`Store action "${actionName}" cannot impersonate controller "${normalizedControllerId}" because it is not currently connected.`,
|
|
473
|
+
{
|
|
474
|
+
actionName,
|
|
475
|
+
controllerId: normalizedControllerId,
|
|
476
|
+
},
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
if (runtime.role === "host") {
|
|
482
|
+
try {
|
|
483
|
+
const context =
|
|
484
|
+
mode.kind === "player"
|
|
485
|
+
? ({
|
|
486
|
+
actorId: mode.controllerId.trim(),
|
|
487
|
+
role: "controller",
|
|
488
|
+
connectedPlayerIds: runtime.connectedPlayerIds,
|
|
489
|
+
} satisfies AirJamActionContext)
|
|
490
|
+
: ({
|
|
491
|
+
actorId: "host",
|
|
492
|
+
role: "host",
|
|
493
|
+
connectedPlayerIds: runtime.connectedPlayerIds,
|
|
494
|
+
} satisfies AirJamActionContext);
|
|
495
|
+
const result = sourceAction(context, normalizedPayload);
|
|
496
|
+
const acknowledgement = normalizeAirJamActionInvocationResult(
|
|
497
|
+
result,
|
|
498
|
+
"host",
|
|
499
|
+
);
|
|
500
|
+
const typedActionName = actionName as AirJamActionName<
|
|
501
|
+
T["actions"]
|
|
502
|
+
>;
|
|
503
|
+
notifyHostActionListeners({
|
|
504
|
+
actionName: typedActionName,
|
|
505
|
+
payload: normalizedPayload,
|
|
506
|
+
context,
|
|
507
|
+
acknowledgement,
|
|
508
|
+
invocationKind: "local",
|
|
509
|
+
roomId: runtime.roomId,
|
|
510
|
+
storeDomain: runtime.resolvedStoreDomain,
|
|
511
|
+
} as AirJamHostActionEvent<T["actions"], typeof typedActionName>);
|
|
512
|
+
return acknowledgement;
|
|
513
|
+
} catch (error) {
|
|
514
|
+
const acknowledgement = {
|
|
515
|
+
ok: false,
|
|
516
|
+
status: "rejected",
|
|
517
|
+
source: "host",
|
|
518
|
+
reason: "handler_error",
|
|
519
|
+
message: error instanceof Error ? error.message : String(error),
|
|
520
|
+
} satisfies AirJamActionInvocationResult;
|
|
521
|
+
const typedActionName = actionName as AirJamActionName<
|
|
522
|
+
T["actions"]
|
|
523
|
+
>;
|
|
524
|
+
notifyHostActionListeners({
|
|
525
|
+
actionName: typedActionName,
|
|
526
|
+
payload: normalizedPayload,
|
|
527
|
+
context: {
|
|
528
|
+
actorId:
|
|
529
|
+
mode.kind === "player" ? mode.controllerId.trim() : "host",
|
|
530
|
+
role: mode.kind === "player" ? "controller" : "host",
|
|
531
|
+
connectedPlayerIds: runtime.connectedPlayerIds,
|
|
532
|
+
},
|
|
533
|
+
acknowledgement,
|
|
534
|
+
invocationKind: "local",
|
|
535
|
+
roomId: runtime.roomId,
|
|
536
|
+
storeDomain: runtime.resolvedStoreDomain,
|
|
537
|
+
} as AirJamHostActionEvent<T["actions"], typeof typedActionName>);
|
|
538
|
+
return acknowledgement;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
if (runtime.role !== "controller" || !runtime.roomId) {
|
|
543
|
+
emitAirJamDiagnostic({
|
|
544
|
+
code: "AJ_STORE_ACTION_SESSION_NOT_READY",
|
|
545
|
+
severity: "warn",
|
|
546
|
+
message: `[AirJamStore] Action "${actionName}" blocked: session role not ready.`,
|
|
547
|
+
details: {
|
|
548
|
+
actionName,
|
|
549
|
+
role: runtime.role,
|
|
550
|
+
roomId: runtime.roomId,
|
|
551
|
+
},
|
|
552
|
+
});
|
|
553
|
+
return createClientRejectedActionResult(
|
|
554
|
+
"session_not_ready",
|
|
555
|
+
`Store action "${actionName}" cannot run because the controller session is not ready.`,
|
|
556
|
+
{
|
|
557
|
+
actionName,
|
|
558
|
+
...(runtime.role ? { role: runtime.role } : {}),
|
|
559
|
+
...(runtime.roomId ? { roomId: runtime.roomId } : {}),
|
|
560
|
+
},
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
const activeSocket = runtime.socket;
|
|
565
|
+
if (!activeSocket || !activeSocket.connected) {
|
|
566
|
+
emitAirJamDiagnostic({
|
|
567
|
+
code: "AJ_STORE_ACTION_SOCKET_DISCONNECTED",
|
|
568
|
+
severity: "warn",
|
|
569
|
+
message: `[AirJamStore] Action "${actionName}" blocked: Socket disconnected.`,
|
|
570
|
+
details: { actionName },
|
|
571
|
+
});
|
|
572
|
+
return createClientRejectedActionResult(
|
|
573
|
+
"socket_disconnected",
|
|
574
|
+
`Store action "${actionName}" cannot run because the controller socket is disconnected.`,
|
|
575
|
+
{
|
|
576
|
+
actionName,
|
|
577
|
+
},
|
|
578
|
+
);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (!isRpcSerializable(normalizedPayload)) {
|
|
582
|
+
emitAirJamDiagnostic({
|
|
583
|
+
code: "AJ_STORE_ACTION_PAYLOAD_NOT_SERIALIZABLE",
|
|
584
|
+
severity: "warn",
|
|
585
|
+
message: `[AirJamStore] Action "${actionName}" blocked: payload must be RPC-serializable.`,
|
|
586
|
+
details: { actionName },
|
|
587
|
+
});
|
|
588
|
+
return createClientRejectedActionResult(
|
|
589
|
+
"payload_not_serializable",
|
|
590
|
+
`Store action "${actionName}" requires an RPC-serializable payload.`,
|
|
591
|
+
{
|
|
592
|
+
actionName,
|
|
593
|
+
},
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
if (
|
|
598
|
+
normalizedPayload !== undefined &&
|
|
599
|
+
!isPlainActionPayload(normalizedPayload)
|
|
600
|
+
) {
|
|
601
|
+
emitAirJamDiagnostic({
|
|
602
|
+
code: "AJ_STORE_ACTION_PAYLOAD_INVALID_SHAPE",
|
|
603
|
+
severity: "warn",
|
|
604
|
+
message: `[AirJamStore] Action "${actionName}" blocked: payload must be omitted or a plain object.`,
|
|
605
|
+
details: { actionName },
|
|
606
|
+
});
|
|
607
|
+
return createClientRejectedActionResult(
|
|
608
|
+
"payload_invalid_shape",
|
|
609
|
+
`Store action "${actionName}" requires an omitted payload or a plain object payload.`,
|
|
610
|
+
{
|
|
611
|
+
actionName,
|
|
612
|
+
},
|
|
613
|
+
);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
return await activeSocket.emitWithAck<AirJamActionInvocationResult>(
|
|
617
|
+
"controller:action_rpc",
|
|
618
|
+
{
|
|
619
|
+
roomId: runtime.roomId,
|
|
620
|
+
actionName,
|
|
621
|
+
payload: normalizedPayload,
|
|
622
|
+
storeDomain: runtime.resolvedStoreDomain,
|
|
623
|
+
},
|
|
624
|
+
);
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
return actionDispatch;
|
|
629
|
+
};
|
|
630
|
+
|
|
631
|
+
const notifyHostActionListeners = <
|
|
632
|
+
TActionName extends AirJamActionName<T["actions"]>,
|
|
633
|
+
>(
|
|
634
|
+
event: AirJamHostActionEvent<T["actions"], TActionName>,
|
|
635
|
+
): void => {
|
|
636
|
+
for (const registration of hostActionListeners) {
|
|
637
|
+
if (
|
|
638
|
+
registration.actionNames &&
|
|
639
|
+
!registration.actionNames.has(event.actionName)
|
|
640
|
+
) {
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
if (
|
|
645
|
+
!registration.includeRejected &&
|
|
646
|
+
event.acknowledgement.status === "rejected"
|
|
647
|
+
) {
|
|
648
|
+
continue;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
try {
|
|
652
|
+
registration.listener(event);
|
|
653
|
+
} catch (error) {
|
|
654
|
+
console.error(
|
|
655
|
+
`[AirJamStore] Host action listener for "${event.actionName}" threw.`,
|
|
656
|
+
error,
|
|
657
|
+
);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
};
|
|
661
|
+
|
|
662
|
+
const createRuntimeBinding = ({
|
|
663
|
+
socket,
|
|
664
|
+
role,
|
|
665
|
+
roomId,
|
|
666
|
+
resolvedStoreDomain,
|
|
667
|
+
}: {
|
|
668
|
+
socket: AirJamRealtimeClient;
|
|
669
|
+
role: AirJamActionActorRole;
|
|
670
|
+
roomId: string;
|
|
671
|
+
resolvedStoreDomain: string;
|
|
672
|
+
}): StoreRuntimeBinding => {
|
|
673
|
+
if (role === "host") {
|
|
674
|
+
let syncedStateData = stripActionsFromState(store.getState());
|
|
675
|
+
let syncedStateSignature = JSON.stringify(syncedStateData);
|
|
676
|
+
let syncRevision = 0;
|
|
677
|
+
|
|
678
|
+
const emitHostStateSync = (requestId?: string): void => {
|
|
679
|
+
const runtime = runtimeSnapshotRef.current;
|
|
680
|
+
if (
|
|
681
|
+
runtime.role !== "host" ||
|
|
682
|
+
runtime.roomId !== roomId ||
|
|
683
|
+
runtime.resolvedStoreDomain !== resolvedStoreDomain ||
|
|
684
|
+
!runtime.canBroadcastHostState ||
|
|
685
|
+
!runtime.socket
|
|
686
|
+
) {
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
runtime.socket.emit("host:state_sync", {
|
|
691
|
+
roomId,
|
|
692
|
+
data: syncedStateData,
|
|
693
|
+
storeDomain: resolvedStoreDomain,
|
|
694
|
+
revision: syncRevision,
|
|
695
|
+
...(requestId ? { requestId } : {}),
|
|
696
|
+
});
|
|
697
|
+
};
|
|
698
|
+
|
|
699
|
+
const flushHostStateSync = (requestId?: string): void => {
|
|
700
|
+
emitHostStateSync(requestId);
|
|
701
|
+
};
|
|
702
|
+
|
|
703
|
+
const handleControllerJoined = (): void => {
|
|
704
|
+
flushHostStateSync();
|
|
705
|
+
};
|
|
706
|
+
|
|
707
|
+
const unsubscribe = store.subscribe((newState) => {
|
|
708
|
+
const runtime = runtimeSnapshotRef.current;
|
|
709
|
+
if (
|
|
710
|
+
runtime.role !== "host" ||
|
|
711
|
+
runtime.roomId !== roomId ||
|
|
712
|
+
runtime.resolvedStoreDomain !== resolvedStoreDomain ||
|
|
713
|
+
!runtime.canBroadcastHostState ||
|
|
714
|
+
!runtime.socket
|
|
715
|
+
) {
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
const stateData = stripActionsFromState(newState);
|
|
720
|
+
const nextSignature = JSON.stringify(stateData);
|
|
721
|
+
if (nextSignature === syncedStateSignature) {
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
syncedStateData = stateData;
|
|
726
|
+
syncedStateSignature = nextSignature;
|
|
727
|
+
syncRevision += 1;
|
|
728
|
+
emitHostStateSync();
|
|
729
|
+
});
|
|
730
|
+
|
|
731
|
+
const handleAction = (
|
|
732
|
+
payload: AirJamActionRpcPayload,
|
|
733
|
+
callback?: (ack: AirJamActionInvocationResult) => void,
|
|
734
|
+
) => {
|
|
735
|
+
if (payload.storeDomain !== resolvedStoreDomain) {
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const { actionName } = payload;
|
|
739
|
+
if (isInternalActionName(actionName)) {
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
const runtime = runtimeSnapshotRef.current;
|
|
744
|
+
const actionFn = store.getState().actions[actionName];
|
|
745
|
+
if (typeof actionFn !== "function") {
|
|
746
|
+
callback?.(
|
|
747
|
+
createServerRejectedActionResult(
|
|
748
|
+
"action_not_found",
|
|
749
|
+
`Store action "${actionName}" is not registered on the host.`,
|
|
750
|
+
{
|
|
751
|
+
actionName,
|
|
752
|
+
storeDomain: resolvedStoreDomain,
|
|
753
|
+
},
|
|
754
|
+
),
|
|
755
|
+
);
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
try {
|
|
760
|
+
const context = toActionContext(payload, runtime.connectedPlayerIds);
|
|
761
|
+
const result = actionFn(context, payload.payload);
|
|
762
|
+
const acknowledgement = normalizeAirJamActionInvocationResult(
|
|
763
|
+
result,
|
|
764
|
+
"host",
|
|
765
|
+
);
|
|
766
|
+
const actionName = payload.actionName as AirJamActionName<
|
|
767
|
+
T["actions"]
|
|
768
|
+
>;
|
|
769
|
+
notifyHostActionListeners({
|
|
770
|
+
actionName,
|
|
771
|
+
payload: payload.payload,
|
|
772
|
+
context,
|
|
773
|
+
acknowledgement,
|
|
774
|
+
invocationKind: "rpc",
|
|
775
|
+
roomId,
|
|
776
|
+
storeDomain: resolvedStoreDomain,
|
|
777
|
+
} as AirJamHostActionEvent<T["actions"], typeof actionName>);
|
|
778
|
+
callback?.(acknowledgement);
|
|
779
|
+
} catch (error) {
|
|
780
|
+
const acknowledgement = {
|
|
781
|
+
ok: false,
|
|
782
|
+
status: "rejected",
|
|
783
|
+
source: "host",
|
|
784
|
+
reason: "handler_error",
|
|
785
|
+
message: error instanceof Error ? error.message : String(error),
|
|
786
|
+
} satisfies AirJamActionInvocationResult;
|
|
787
|
+
const actionName = payload.actionName as AirJamActionName<
|
|
788
|
+
T["actions"]
|
|
789
|
+
>;
|
|
790
|
+
notifyHostActionListeners({
|
|
791
|
+
actionName,
|
|
792
|
+
payload: payload.payload,
|
|
793
|
+
context: toActionContext(payload, runtime.connectedPlayerIds),
|
|
794
|
+
acknowledgement,
|
|
795
|
+
invocationKind: "rpc",
|
|
796
|
+
roomId,
|
|
797
|
+
storeDomain: resolvedStoreDomain,
|
|
798
|
+
} as AirJamHostActionEvent<T["actions"], typeof actionName>);
|
|
799
|
+
callback?.(acknowledgement);
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
|
|
803
|
+
const handleStateSyncRequest = (payload: {
|
|
804
|
+
roomId: string;
|
|
805
|
+
storeDomain: string;
|
|
806
|
+
requestId?: string;
|
|
807
|
+
}): void => {
|
|
808
|
+
if (payload.roomId !== roomId) {
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
if (payload.storeDomain !== resolvedStoreDomain) {
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
flushHostStateSync(payload.requestId);
|
|
815
|
+
};
|
|
816
|
+
|
|
817
|
+
const handleSync = (payload: AirJamStateSyncPayload) => {
|
|
818
|
+
if (payload.roomId !== roomId) {
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
if (payload.storeDomain !== resolvedStoreDomain) {
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
if (payload.revision < syncRevision) {
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
const nextStateData = stripActionsFromState(payload.data as Partial<T>);
|
|
829
|
+
const nextSignature = JSON.stringify(nextStateData);
|
|
830
|
+
const currentSignature = JSON.stringify(
|
|
831
|
+
stripActionsFromState(store.getState()),
|
|
832
|
+
);
|
|
833
|
+
syncRevision = payload.revision;
|
|
834
|
+
syncedStateData = nextStateData;
|
|
835
|
+
syncedStateSignature = nextSignature;
|
|
836
|
+
|
|
837
|
+
if (nextSignature === currentSignature) {
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
store.setState(nextStateData);
|
|
842
|
+
};
|
|
843
|
+
|
|
844
|
+
socket.on("server:controllerJoined", handleControllerJoined);
|
|
845
|
+
socket.on("airjam:state_sync", handleSync);
|
|
846
|
+
socket.on("airjam:state_sync_request", handleStateSyncRequest);
|
|
847
|
+
socket.on("airjam:action_rpc", handleAction);
|
|
848
|
+
|
|
849
|
+
return {
|
|
850
|
+
refCount: 0,
|
|
851
|
+
flushHostStateSync,
|
|
852
|
+
cleanup: () => {
|
|
853
|
+
unsubscribe();
|
|
854
|
+
socket.off("server:controllerJoined", handleControllerJoined);
|
|
855
|
+
socket.off("airjam:state_sync", handleSync);
|
|
856
|
+
socket.off("airjam:state_sync_request", handleStateSyncRequest);
|
|
857
|
+
socket.off("airjam:action_rpc", handleAction);
|
|
858
|
+
},
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
let latestSyncRevision = -1;
|
|
863
|
+
|
|
864
|
+
const handleSync = (payload: AirJamStateSyncPayload) => {
|
|
865
|
+
if (payload.storeDomain !== resolvedStoreDomain) {
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
if (payload.revision < latestSyncRevision) {
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
latestSyncRevision = payload.revision;
|
|
872
|
+
const stateData = stripActionsFromState(payload.data as Partial<T>);
|
|
873
|
+
store.setState(stateData);
|
|
874
|
+
};
|
|
875
|
+
|
|
876
|
+
socket.on("airjam:state_sync", handleSync);
|
|
877
|
+
|
|
878
|
+
if (runtimeSnapshotRef.current.connectionStatus === "connected") {
|
|
879
|
+
socket.emit("controller:state_sync_request", {
|
|
880
|
+
roomId,
|
|
881
|
+
storeDomain: resolvedStoreDomain,
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
return {
|
|
886
|
+
refCount: 0,
|
|
887
|
+
cleanup: () => {
|
|
888
|
+
socket.off("airjam:state_sync", handleSync);
|
|
889
|
+
},
|
|
890
|
+
};
|
|
891
|
+
};
|
|
63
892
|
|
|
64
893
|
const useSyncedStore = <U>(
|
|
65
|
-
selector: (state: T) => U = (
|
|
894
|
+
selector: (state: T) => U = (state) => state as unknown as U,
|
|
66
895
|
): U => {
|
|
67
|
-
// Standard Zustand selector behavior
|
|
68
896
|
const slice = store(selector);
|
|
69
897
|
|
|
898
|
+
const explicitDomain = options?.storeDomain;
|
|
899
|
+
let resolvedStoreDomain: string;
|
|
900
|
+
if (
|
|
901
|
+
typeof explicitDomain === "string" &&
|
|
902
|
+
explicitDomain.trim().length > 0
|
|
903
|
+
) {
|
|
904
|
+
const trimmed = explicitDomain.trim();
|
|
905
|
+
resolvedStoreDomain =
|
|
906
|
+
trimmed.length > 128 ? trimmed.slice(0, 128) : trimmed;
|
|
907
|
+
} else {
|
|
908
|
+
resolvedStoreDomain = resolveImplicitReplicatedStoreDomainFromWindow();
|
|
909
|
+
}
|
|
910
|
+
|
|
70
911
|
const { getSocket } = useAirJamContext();
|
|
71
912
|
const role = useAirJamState((state) => state.role);
|
|
72
913
|
const roomId = useAirJamState((state) => state.roomId);
|
|
73
|
-
const
|
|
74
|
-
const
|
|
75
|
-
|
|
914
|
+
const registeredRoomId = useAirJamState((state) => state.registeredRoomId);
|
|
915
|
+
const connectionStatus = useAirJamState((state) => state.connectionStatus);
|
|
916
|
+
const players = useAirJamState((state) => state.players);
|
|
917
|
+
const hostArcadeRestore = useAirJamState(
|
|
918
|
+
(state) => state.hostArcadeRestore,
|
|
919
|
+
);
|
|
920
|
+
const blockArcadeShellHostBroadcast =
|
|
921
|
+
resolvedStoreDomain === AIR_JAM_ARCADE_SURFACE_STORE_DOMAIN &&
|
|
922
|
+
hostArcadeRestore.phase !== "idle";
|
|
923
|
+
const canBroadcastHostState =
|
|
924
|
+
role === "host" &&
|
|
925
|
+
!!roomId &&
|
|
926
|
+
registeredRoomId === roomId &&
|
|
927
|
+
!blockArcadeShellHostBroadcast;
|
|
928
|
+
const connectedPlayerIds = useMemo(
|
|
929
|
+
() => Array.from(new Set(players.map((player) => player.id))).sort(),
|
|
930
|
+
[players],
|
|
931
|
+
);
|
|
932
|
+
const playerRosterKey = useMemo(
|
|
933
|
+
() =>
|
|
934
|
+
players
|
|
935
|
+
.map((player) => player.id)
|
|
936
|
+
.sort()
|
|
937
|
+
.join(","),
|
|
938
|
+
[players],
|
|
939
|
+
);
|
|
940
|
+
const socket: AirJamRealtimeClient =
|
|
941
|
+
role === "host"
|
|
942
|
+
? getHostRealtimeClient((runtimeRole) => getSocket(runtimeRole))
|
|
943
|
+
: getControllerRealtimeClient((runtimeRole) => getSocket(runtimeRole));
|
|
76
944
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
945
|
+
runtimeSnapshotRef.current = {
|
|
946
|
+
socket,
|
|
947
|
+
role,
|
|
948
|
+
roomId,
|
|
949
|
+
resolvedStoreDomain,
|
|
950
|
+
connectionStatus,
|
|
951
|
+
canBroadcastHostState,
|
|
952
|
+
connectedPlayerIds,
|
|
953
|
+
};
|
|
954
|
+
|
|
955
|
+
const runtimeBindingKey =
|
|
956
|
+
socket && roomId && role
|
|
957
|
+
? [
|
|
958
|
+
role,
|
|
959
|
+
roomId,
|
|
960
|
+
resolvedStoreDomain,
|
|
961
|
+
socket.id ?? "socket",
|
|
962
|
+
role === "controller" ? connectionStatus : "host",
|
|
963
|
+
].join(":")
|
|
964
|
+
: null;
|
|
82
965
|
|
|
83
|
-
// --- NETWORKING LOGIC ---
|
|
84
966
|
useEffect(() => {
|
|
85
|
-
if (!socket || !roomId || !role) {
|
|
967
|
+
if (!runtimeBindingKey || !socket || !roomId || !role) {
|
|
86
968
|
return;
|
|
87
969
|
}
|
|
88
970
|
|
|
89
|
-
|
|
90
|
-
if (
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
socket.emit("host:state_sync", { roomId, data: stateData });
|
|
971
|
+
let binding = runtimeBindings.get(runtimeBindingKey);
|
|
972
|
+
if (!binding) {
|
|
973
|
+
binding = createRuntimeBinding({
|
|
974
|
+
socket,
|
|
975
|
+
role,
|
|
976
|
+
roomId,
|
|
977
|
+
resolvedStoreDomain,
|
|
97
978
|
});
|
|
979
|
+
runtimeBindings.set(runtimeBindingKey, binding);
|
|
980
|
+
}
|
|
98
981
|
|
|
99
|
-
|
|
100
|
-
const handleAction = (payload: AirJamActionRpcPayload) => {
|
|
101
|
-
const { actionName, args, controllerId } = payload;
|
|
102
|
-
// Execute the action on the Host (Source of Truth)
|
|
103
|
-
// We can optionally pass controllerId as the last arg if the action expects it
|
|
104
|
-
const actionFn = store.getState().actions[actionName];
|
|
105
|
-
if (actionFn) {
|
|
106
|
-
// Spread args and optionally append controllerId
|
|
107
|
-
actionFn(...args, controllerId);
|
|
108
|
-
}
|
|
109
|
-
};
|
|
982
|
+
binding.refCount += 1;
|
|
110
983
|
|
|
111
|
-
|
|
984
|
+
return () => {
|
|
985
|
+
const currentBinding = runtimeBindings.get(runtimeBindingKey);
|
|
986
|
+
if (!currentBinding) {
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
112
989
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
}
|
|
990
|
+
currentBinding.refCount -= 1;
|
|
991
|
+
if (currentBinding.refCount > 0) {
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
currentBinding.cleanup();
|
|
996
|
+
runtimeBindings.delete(runtimeBindingKey);
|
|
997
|
+
};
|
|
998
|
+
}, [
|
|
999
|
+
runtimeBindingKey,
|
|
1000
|
+
socket,
|
|
1001
|
+
role,
|
|
1002
|
+
roomId,
|
|
1003
|
+
socket?.id,
|
|
1004
|
+
resolvedStoreDomain,
|
|
1005
|
+
]);
|
|
1006
|
+
|
|
1007
|
+
useEffect(() => {
|
|
1008
|
+
if (
|
|
1009
|
+
!runtimeBindingKey ||
|
|
1010
|
+
role !== "host" ||
|
|
1011
|
+
!canBroadcastHostState ||
|
|
1012
|
+
!roomId
|
|
1013
|
+
) {
|
|
1014
|
+
return;
|
|
117
1015
|
}
|
|
118
1016
|
|
|
119
|
-
|
|
120
|
-
if (
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
const handleSync = (payload: AirJamStateSyncPayload) => {
|
|
125
|
-
const { data } = payload;
|
|
126
|
-
// Merge incoming state, but KEEP the local actions
|
|
127
|
-
// Use the internal _syncState action to update state (triggers Zustand subscriptions)
|
|
128
|
-
const currentState = store.getState();
|
|
129
|
-
const actions = currentState.actions as T["actions"] & {
|
|
130
|
-
_syncState?: (partial: Partial<T>) => void;
|
|
131
|
-
};
|
|
132
|
-
|
|
133
|
-
// Update store using internal action - this triggers Zustand subscriptions properly
|
|
134
|
-
if (actions._syncState) {
|
|
135
|
-
actions._syncState(data as Partial<T>);
|
|
136
|
-
} else {
|
|
137
|
-
// Fallback to setState if _syncState not available
|
|
138
|
-
store.setState(data as Partial<T>);
|
|
139
|
-
}
|
|
140
|
-
};
|
|
1017
|
+
const binding = runtimeBindings.get(runtimeBindingKey);
|
|
1018
|
+
if (!binding?.flushHostStateSync) {
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
141
1021
|
|
|
142
|
-
|
|
1022
|
+
const flushKey = [
|
|
1023
|
+
roomId,
|
|
1024
|
+
registeredRoomId,
|
|
1025
|
+
socket?.id ?? "socket",
|
|
1026
|
+
resolvedStoreDomain,
|
|
1027
|
+
playerRosterKey,
|
|
1028
|
+
canBroadcastHostState ? "broadcast" : "blocked",
|
|
1029
|
+
].join(":");
|
|
143
1030
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
const handleUnloadUi = () => {
|
|
147
|
-
gameUiUnloadedRef.current = true; // Disable proxy actions
|
|
148
|
-
socket.off("airjam:state_sync", handleSync);
|
|
149
|
-
};
|
|
150
|
-
|
|
151
|
-
// Also listen for client:loadUi to re-enable proxy actions when new game loads
|
|
152
|
-
const handleLoadUi = () => {
|
|
153
|
-
gameUiUnloadedRef.current = false; // Re-enable proxy actions when game loads
|
|
154
|
-
};
|
|
155
|
-
socket.on("client:loadUi", handleLoadUi);
|
|
156
|
-
|
|
157
|
-
// Also listen for socket disconnect as a fallback to disable proxy actions
|
|
158
|
-
const handleDisconnect = () => {
|
|
159
|
-
gameUiUnloadedRef.current = true; // Disable proxy actions on disconnect
|
|
160
|
-
};
|
|
161
|
-
socket.on("disconnect", handleDisconnect);
|
|
162
|
-
|
|
163
|
-
// Register client:unloadUi listener
|
|
164
|
-
// Socket.IO listeners work even if registered before connection, but we include socket.id
|
|
165
|
-
// in dependencies to ensure the effect re-runs when socket connects (socket.id changes from undefined to a string)
|
|
166
|
-
socket.on("client:unloadUi", handleUnloadUi);
|
|
167
|
-
|
|
168
|
-
return () => {
|
|
169
|
-
socket.off("airjam:state_sync", handleSync);
|
|
170
|
-
socket.off("client:loadUi", handleLoadUi);
|
|
171
|
-
socket.off("client:unloadUi", handleUnloadUi);
|
|
172
|
-
socket.off("disconnect", handleDisconnect);
|
|
173
|
-
};
|
|
1031
|
+
if (binding.lastHostFlushKey === flushKey) {
|
|
1032
|
+
return;
|
|
174
1033
|
}
|
|
175
|
-
}, [socket, role, roomId, socket?.id]);
|
|
176
1034
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
1035
|
+
binding.lastHostFlushKey = flushKey;
|
|
1036
|
+
binding.flushHostStateSync();
|
|
1037
|
+
}, [
|
|
1038
|
+
role,
|
|
1039
|
+
roomId,
|
|
1040
|
+
registeredRoomId,
|
|
1041
|
+
socket?.id,
|
|
1042
|
+
playerRosterKey,
|
|
1043
|
+
resolvedStoreDomain,
|
|
1044
|
+
canBroadcastHostState,
|
|
1045
|
+
runtimeBindingKey,
|
|
1046
|
+
]);
|
|
184
1047
|
|
|
185
|
-
|
|
1048
|
+
const dispatchedActions = useMemo<AirJamActionDispatchMap<T["actions"]>>(
|
|
1049
|
+
() => createDispatchedActions({ kind: "default" }),
|
|
1050
|
+
[],
|
|
1051
|
+
);
|
|
186
1052
|
|
|
187
|
-
|
|
188
|
-
if (typeof slice === "object" && slice !== null && "actions" in slice) {
|
|
189
|
-
originalActions = (slice as { actions: T["actions"] }).actions;
|
|
190
|
-
}
|
|
191
|
-
// Case 2: Slice IS the actions object (selector returned state.actions)
|
|
192
|
-
else if (typeof slice === "object" && slice !== null) {
|
|
193
|
-
// Check if this looks like an actions object (has function properties matching store actions)
|
|
194
|
-
const fullState = store.getState();
|
|
195
|
-
if (fullState.actions) {
|
|
196
|
-
const sliceKeys = Object.keys(slice);
|
|
197
|
-
const actionKeys = Object.keys(fullState.actions);
|
|
198
|
-
// If slice keys match action keys and are all functions, it's the actions object
|
|
199
|
-
if (
|
|
200
|
-
sliceKeys.length > 0 &&
|
|
201
|
-
sliceKeys.every(
|
|
202
|
-
(key) =>
|
|
203
|
-
typeof (slice as Record<string, unknown>)[key] === "function" &&
|
|
204
|
-
actionKeys.includes(key),
|
|
205
|
-
)
|
|
206
|
-
) {
|
|
207
|
-
originalActions = slice as T["actions"];
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
}
|
|
1053
|
+
const stateActions = store.getState().actions;
|
|
211
1054
|
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
Object.keys(originalActions).forEach((key) => {
|
|
217
|
-
// Type assertion needed because we're creating proxies dynamically
|
|
218
|
-
// We cast to the same type as T["actions"] to maintain type compatibility
|
|
219
|
-
(proxyActions as Record<string, (...args: unknown[]) => void>)[key] =
|
|
220
|
-
(...args: unknown[]) => {
|
|
221
|
-
// --- EXECUTION TIME GUARDS (THE FIX) ---
|
|
222
|
-
// Check guards at EXECUTION time, not creation time
|
|
223
|
-
// This ensures old closures are still safe even if they're called after game exit
|
|
224
|
-
|
|
225
|
-
// 1. Check if UI is unloaded right now (at execution time)
|
|
226
|
-
if (gameUiUnloadedRef.current) {
|
|
227
|
-
console.warn(
|
|
228
|
-
`[AirJamStore] Action "${key}" blocked: Game UI unloaded.`,
|
|
229
|
-
);
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// 2. Check if we have a valid socket right now (at execution time)
|
|
234
|
-
const activeSocket = socketRef.current;
|
|
235
|
-
if (!activeSocket || !activeSocket.connected) {
|
|
236
|
-
console.warn(
|
|
237
|
-
`[AirJamStore] Action "${key}" blocked: Socket disconnected.`,
|
|
238
|
-
);
|
|
239
|
-
return;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// 3. Check controllerId
|
|
243
|
-
if (!controllerId) {
|
|
244
|
-
console.warn(
|
|
245
|
-
"[AirJamStore] Cannot send action RPC: controllerId not set",
|
|
246
|
-
);
|
|
247
|
-
return;
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
// 4. Send RPC to Host (include controllerId to handle reconnections)
|
|
251
|
-
activeSocket.emit("controller:action_rpc", {
|
|
252
|
-
roomId,
|
|
253
|
-
actionName: key,
|
|
254
|
-
args,
|
|
255
|
-
controllerId,
|
|
256
|
-
});
|
|
257
|
-
};
|
|
258
|
-
});
|
|
1055
|
+
if (slice === stateActions) {
|
|
1056
|
+
return dispatchedActions as U;
|
|
1057
|
+
}
|
|
259
1058
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
1059
|
+
if (
|
|
1060
|
+
typeof slice === "object" &&
|
|
1061
|
+
slice !== null &&
|
|
1062
|
+
"actions" in slice &&
|
|
1063
|
+
(slice as { actions: unknown }).actions === stateActions
|
|
1064
|
+
) {
|
|
1065
|
+
return {
|
|
1066
|
+
...(slice as Record<string, unknown>),
|
|
1067
|
+
actions: dispatchedActions,
|
|
1068
|
+
} as U;
|
|
268
1069
|
}
|
|
269
1070
|
|
|
270
1071
|
return slice;
|
|
271
1072
|
};
|
|
272
1073
|
|
|
273
|
-
|
|
1074
|
+
const syncedStore = useSyncedStore as AirJamSyncedStoreHook<T>;
|
|
1075
|
+
const useActions = (): AirJamActionDispatchMap<T["actions"]> =>
|
|
1076
|
+
useSyncedStore((state) => state.actions) as AirJamActionDispatchMap<
|
|
1077
|
+
T["actions"]
|
|
1078
|
+
>;
|
|
1079
|
+
const asPlayer = (
|
|
1080
|
+
controllerId: string,
|
|
1081
|
+
): AirJamActionDispatchMap<T["actions"]> =>
|
|
1082
|
+
createDispatchedActions({
|
|
1083
|
+
kind: "player",
|
|
1084
|
+
controllerId,
|
|
1085
|
+
});
|
|
1086
|
+
const subscribeHostActions = (
|
|
1087
|
+
listener: AirJamHostActionListener<T["actions"]>,
|
|
1088
|
+
options?: AirJamHostActionSubscriptionOptions<T["actions"]>,
|
|
1089
|
+
): (() => void) => {
|
|
1090
|
+
const actionNames =
|
|
1091
|
+
options?.actionNames && options.actionNames.length > 0
|
|
1092
|
+
? new Set<string>(options.actionNames)
|
|
1093
|
+
: null;
|
|
1094
|
+
const registration: HostActionListenerRegistration<T["actions"]> = {
|
|
1095
|
+
actionNames,
|
|
1096
|
+
includeRejected: options?.includeRejected ?? false,
|
|
1097
|
+
listener,
|
|
1098
|
+
};
|
|
1099
|
+
hostActionListeners.add(registration);
|
|
1100
|
+
return () => {
|
|
1101
|
+
hostActionListeners.delete(registration);
|
|
1102
|
+
};
|
|
1103
|
+
};
|
|
1104
|
+
const useHostActionListener = (
|
|
1105
|
+
listener: AirJamHostActionListener<T["actions"]>,
|
|
1106
|
+
options?: AirJamHostActionSubscriptionOptions<T["actions"]>,
|
|
1107
|
+
): void => {
|
|
1108
|
+
const listenerRef = useRef(listener);
|
|
1109
|
+
useEffect(() => {
|
|
1110
|
+
listenerRef.current = listener;
|
|
1111
|
+
}, [listener]);
|
|
1112
|
+
|
|
1113
|
+
const includeRejected = options?.includeRejected ?? false;
|
|
1114
|
+
const actionNamesKey = options?.actionNames?.join("\u0000") ?? "";
|
|
1115
|
+
|
|
1116
|
+
useEffect(() => {
|
|
1117
|
+
return subscribeHostActions((event) => {
|
|
1118
|
+
listenerRef.current(event);
|
|
1119
|
+
}, options);
|
|
1120
|
+
}, [actionNamesKey, includeRejected, options]);
|
|
1121
|
+
};
|
|
1122
|
+
const useLiveStateRef = (): MutableRefObject<T> => {
|
|
1123
|
+
const latestState = useSyncedStore((state) => state);
|
|
1124
|
+
const stateRef = useRef<T>(latestState);
|
|
1125
|
+
|
|
1126
|
+
useEffect(() => {
|
|
1127
|
+
stateRef.current = latestState;
|
|
1128
|
+
}, [latestState]);
|
|
1129
|
+
|
|
1130
|
+
return stateRef;
|
|
1131
|
+
};
|
|
1132
|
+
syncedStore.useActions = useActions;
|
|
1133
|
+
syncedStore.asPlayer = asPlayer;
|
|
1134
|
+
syncedStore.getState = store.getState;
|
|
1135
|
+
syncedStore.subscribe = store.subscribe;
|
|
1136
|
+
syncedStore.subscribeHostActions = subscribeHostActions;
|
|
1137
|
+
syncedStore.useHostActionListener = useHostActionListener;
|
|
1138
|
+
syncedStore.useLiveStateRef = useLiveStateRef;
|
|
1139
|
+
|
|
1140
|
+
return syncedStore;
|
|
274
1141
|
}
|