@gamepadly/sdk 0.0.0-stage → 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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -2
  3. package/SECURITY.md +19 -0
  4. package/dist/bridge/index.d.ts +50 -0
  5. package/dist/bridge/index.d.ts.map +1 -0
  6. package/dist/bridge/index.js +422 -0
  7. package/dist/bridge/index.js.map +7 -0
  8. package/dist/bridge/profiles.d.ts +51 -0
  9. package/dist/bridge/profiles.d.ts.map +1 -0
  10. package/dist/browser.d.ts +15 -0
  11. package/dist/browser.d.ts.map +1 -0
  12. package/dist/browser.js +4234 -0
  13. package/dist/browser.js.map +7 -0
  14. package/dist/browser.min.js +1 -0
  15. package/dist/chunks/chunk-GMU2WEFE.js +1850 -0
  16. package/dist/chunks/chunk-GMU2WEFE.js.map +7 -0
  17. package/dist/haptics/presets.d.ts +35 -0
  18. package/dist/haptics/presets.d.ts.map +1 -0
  19. package/dist/haptics/router.d.ts +102 -0
  20. package/dist/haptics/router.d.ts.map +1 -0
  21. package/dist/hid/index.d.ts +323 -0
  22. package/dist/hid/index.d.ts.map +1 -0
  23. package/dist/hub.d.ts +112 -0
  24. package/dist/hub.d.ts.map +1 -0
  25. package/dist/index.d.ts +15 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +819 -0
  28. package/dist/index.js.map +7 -0
  29. package/dist/input/actions.d.ts +64 -0
  30. package/dist/input/actions.d.ts.map +1 -0
  31. package/dist/link/engine.d.ts +213 -0
  32. package/dist/link/engine.d.ts.map +1 -0
  33. package/dist/link/index.d.ts +8 -0
  34. package/dist/link/index.d.ts.map +1 -0
  35. package/dist/link/index.js +966 -0
  36. package/dist/link/index.js.map +7 -0
  37. package/dist/loop/index.d.ts +69 -0
  38. package/dist/loop/index.d.ts.map +1 -0
  39. package/dist/loop/index.js +214 -0
  40. package/dist/loop/index.js.map +7 -0
  41. package/package.json +79 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gamepadly (https://gamepadly.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,138 @@
1
- # Temporary Holding Version
1
+ # `@gamepadly/sdk`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Headless, framework-agnostic Web controller & tactile haptics SDK powering [gamepadly.com](https://gamepadly.com).
4
+
5
+ Build controller-first browser games or adapt existing open-source HTML5/Canvas/WebGL games to **PS5 DualSense / Edge**, **Xbox Series**, **Nintendo Switch Pro**, and standard gamepads without rewriting hardware protocols, trigger encoders, or fallback logic.
6
+
7
+ ## Why `@gamepadly/sdk`?
8
+
9
+ * **Zero runtime dependencies & tree-shakable subpaths** — works with Vite, Webpack, Next.js, Three.js, Phaser, PixiJS, React, Vue, Electron, or plain `<script type="module">` HTML.
10
+ * **Capability-Driven across brands (L0 → L1 → L2)**:
11
+ * **L0 (Zero prompts)**: Gamepad API with 0% hidden deadzone + native **Xbox Series Impulse Triggers** (`trigger-rumble`).
12
+ * **L1 (One-click WebHID, USB & Bluetooth)**: **DualSense / Edge** 10-zone Adaptive Triggers, 6-axis Gyro/Accel, dual-finger Touchpad, RGB Lightbar & read-only firmware info; **Nintendo Switch Pro** dual-band LRA **HD Rumble**, 6-axis Gyro/Accel & read-only SPI calibration.
13
+ * **L2 (Optional `@gamepadly/sdk/link`)**: 3-layer audio & **4-channel 48 kHz voice-coil haptics + controller speaker** via browser `setSinkId()` or the standalone MIT companion [`gamepadly-link`](https://github.com/gamepadly/gamepadly-link).
14
+ * **Multi-controller P1–P4** — independent slot polling, per-player triggers/haptics, and `onCapabilitiesChange` hotplug notifications.
15
+ * **Semantic Action Map** — fuse gamepad sticks/buttons/triggers with keyboard & mouse fallbacks, complete with `justPressed`, `justReleased`, and `heldMs`.
16
+ * **Declarative Key/Mouse Bridge (`@gamepadly/sdk/bridge`)** — turn existing keyboard/mouse open-source H5 games into controller + haptics experiences in minutes.
17
+ * **Hardware-safe by default** — Switch Pro amplitudes clamped `<= 0.85` with neutral silence packets, automatic `pagehide`/`beforeunload`/`dispose()` emergency reset, read-only device access, and Chrome Local Network Access (LNA) compliance.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install @gamepadly/sdk
23
+ # or
24
+ pnpm add @gamepadly/sdk
25
+ ```
26
+
27
+ Or use directly in plain HTML with zero bundler:
28
+
29
+ ```html
30
+ <script type="module">
31
+ import { createGamepadly, createKeyMouseBridge } from 'https://esm.sh/@gamepadly/sdk/browser';
32
+ </script>
33
+ ```
34
+
35
+ ## Subpath Modules
36
+
37
+ | Import | Purpose |
38
+ | :--- | :--- |
39
+ | `@gamepadly/sdk` | Core `createGamepadly()` hub, P1–P4 players, `ActionTracker`, cross-brand tactile presets & haptics router, low-level `ControllerManager` & protocol encoders |
40
+ | `@gamepadly/sdk/link` | Optional `ThreeLayerAudioEngine` / `createLinkAudio()` for PC synth audio, browser `setSinkId` 4ch routing, and `Gamepadly Link` `protocol/v1` |
41
+ | `@gamepadly/sdk/bridge` | Optional `createKeyMouseBridge()` + built-in profiles (`platformer`, `arcade-4way`, `racing`, `twin-stick`) for adapting keyboard/mouse H5 games |
42
+ | `@gamepadly/sdk/loop` | Optional `createCanvasStage()`, `createGameLoop({ fixedStep })`, and `createDisposables()` |
43
+ | `@gamepadly/sdk/browser` | All-in-one single-file browser ESM bundle for zero-bundler HTML usage |
44
+
45
+ ## Quick Start: Controller-First Game
46
+
47
+ ```ts
48
+ import { createGamepadly } from '@gamepadly/sdk';
49
+ import { createGameLoop } from '@gamepadly/sdk/loop';
50
+
51
+ const hub = createGamepadly();
52
+ const p1 = hub.player(0);
53
+
54
+ // Bind WebHID upgrade to a user click (required by browsers)
55
+ connectBtn.addEventListener('click', () => hub.connectWebHID());
56
+
57
+ // Fuse controller + keyboard + mouse into semantic actions
58
+ const actions = p1.createActions({
59
+ actions: {
60
+ fire: ['r2', 'Space', 'MouseLeft'],
61
+ jump: ['cross', 'KeyW', 'ArrowUp'],
62
+ },
63
+ axes: {
64
+ moveX: { stick: 'lx', negativeKeys: ['KeyA', 'ArrowLeft'], positiveKeys: ['KeyD', 'ArrowRight'] },
65
+ },
66
+ });
67
+
68
+ // Automatically re-apply trigger resistance if the user upgrades to DualSense WebHID mid-game
69
+ const syncTriggers = () => p1.triggers.applyPreset('weapon', 'right');
70
+ syncTriggers();
71
+ hub.onCapabilitiesChange(syncTriggers);
72
+
73
+ const loop = createGameLoop({
74
+ fixedStep: 1 / 60,
75
+ onUpdate(dt, now) {
76
+ actions.update(p1.input.getState(), now);
77
+
78
+ const moveX = actions.axis('moveX');
79
+ if (actions.justPressed('fire')) {
80
+ // Routes to 4ch VCM -> Switch Pro HD Rumble -> Xbox Impulse Triggers -> Dual Rumble
81
+ p1.haptics.playPreset('recoil', { pan: moveX });
82
+ }
83
+ },
84
+ });
85
+ loop.start();
86
+
87
+ // Cleanly stops all rumble/triggers/audio/listeners
88
+ // loop.dispose(); hub.dispose();
89
+ ```
90
+
91
+ ## Quick Start: Adapt an Open-Source H5 Game (`@gamepadly/sdk/bridge`)
92
+
93
+ ```ts
94
+ import { createGamepadly } from '@gamepadly/sdk';
95
+ import { createKeyMouseBridge } from '@gamepadly/sdk/bridge';
96
+
97
+ const hub = createGamepadly();
98
+ const bridge = createKeyMouseBridge({
99
+ player: hub,
100
+ profile: 'platformer', // or 'arcade-4way' | 'racing' | 'twin-stick' | custom BridgeProfile
101
+ });
102
+ bridge.start();
103
+
104
+ // Later, upgrade key game moments with real source-level haptics:
105
+ bridge.triggerHaptic('heavy_impact', { pan: -0.6 });
106
+ ```
107
+
108
+ See [`examples/bridge-arcade-demo.html`](./examples/bridge-arcade-demo.html) for a complete standalone demo.
109
+
110
+ ## Optional: 4-Channel Audio Haptics via Gamepadly Link (`@gamepadly/sdk/link`)
111
+
112
+ ```ts
113
+ import { createGamepadly } from '@gamepadly/sdk';
114
+ import { createLinkAudio } from '@gamepadly/sdk/link';
115
+
116
+ const audio = createLinkAudio(); // custom { httpBase, wsBase } supported
117
+ const hub = createGamepadly({ audio });
118
+
119
+ // Must be triggered from a user click (Chrome LNA loopback compliance)
120
+ connectLinkBtn.addEventListener('click', async () => {
121
+ await audio.initPcOutput();
122
+ await audio.bindDualSenseViaCompanion();
123
+ hub.syncCapabilities();
124
+ });
125
+ ```
126
+
127
+ ## Development
128
+
129
+ ```bash
130
+ pnpm install
131
+ pnpm typecheck
132
+ pnpm test
133
+ pnpm build
134
+ ```
135
+
136
+ ## License
137
+
138
+ [MIT](./LICENSE) — Copyright (c) 2026 Gamepadly
package/SECURITY.md ADDED
@@ -0,0 +1,19 @@
1
+ # Security Policy
2
+
3
+ ## Hardware & Browser Safety Guarantees
4
+
5
+ `@gamepadly/sdk` adheres strictly to read-only, user-consented browser APIs:
6
+
7
+ 1. **Read-Only Hardware Access**: Never writes firmware, NVRAM, or permanent calibration tables to connected controllers.
8
+ 2. **Hardware Actuator Protection**:
9
+ - Switch Pro HD Rumble amplitudes are clamped to `<= 0.85` and always terminate with a neutral silence packet (`00 01 40 40`).
10
+ - DualSense adaptive triggers, lightbar, legacy rumble, Switch Pro HD Rumble, and Gamepad API actuators are forcibly reset on `dispose()`, `pagehide`, and `beforeunload`.
11
+ - DualSense built-in speaker audio is emitted mono-safe across Ch0 + Ch1.
12
+ 3. **Chrome Local Network Access (LNA) Compliance**:
13
+ - Never probes `127.0.0.1` automatically on page load.
14
+ - All `Gamepadly Link` requests require explicit user gesture invocation and send `targetAddressSpace: 'loopback'`.
15
+ 4. **No Trademark Assets & Zero GPL Dependencies**: Pure TypeScript, MIT licensed, zero third-party runtime dependencies.
16
+
17
+ ## Reporting a Vulnerability
18
+
19
+ Please report security issues privately via GitHub Security Advisories on `gamepadly/gamepadly-sdk` or email `security@gamepadly.com`.
@@ -0,0 +1,50 @@
1
+ import { type TactilePresetId } from '../haptics/presets.js';
2
+ import type { HapticPulseSpec } from '../haptics/router.js';
3
+ import type { GamepadlyHub, PlayerHandle } from '../hub.js';
4
+ import { BUILTIN_BRIDGE_PROFILES, type BridgeProfile, type BridgeSourceInput, type BuiltinBridgeProfileId, type KeyMappingRule, type VirtualPointerConfig } from './profiles.js';
5
+ export { BUILTIN_BRIDGE_PROFILES, type BridgeProfile, type BridgeSourceInput, type BuiltinBridgeProfileId, type KeyMappingRule, type VirtualPointerConfig, };
6
+ export interface VirtualCursorState {
7
+ x: number;
8
+ y: number;
9
+ down: boolean;
10
+ secondaryDown: boolean;
11
+ visible: boolean;
12
+ }
13
+ export interface KeyMouseBridgeOptions {
14
+ /** Gamepadly hub or a specific PlayerHandle to read input & emit haptics from. */
15
+ player: PlayerHandle | GamepadlyHub;
16
+ /** Built-in profile name or custom `BridgeProfile`. */
17
+ profile: BuiltinBridgeProfileId | BridgeProfile;
18
+ /** Target receiving synthetic `KeyboardEvent`s (defaults to `window`). */
19
+ keyTarget?: EventTarget;
20
+ /** Element receiving synthetic `PointerEvent`/`MouseEvent`s for virtual cursor (defaults to `document.body`). */
21
+ pointerTarget?: HTMLElement | null;
22
+ /** Optional callback fired every tick when virtual pointer state updates (for rendering a custom cursor). */
23
+ onCursorUpdate?: (cursor: VirtualCursorState) => void;
24
+ /** Automatically drive polling via `requestAnimationFrame` on `start()`. Default true. */
25
+ autoRaf?: boolean;
26
+ }
27
+ export interface KeyMouseBridge {
28
+ /** Starts polling controller input and dispatching bridged events (+ applies profile trigger presets). */
29
+ start(): void;
30
+ /** Stops polling and cleanly releases all currently held synthetic keys & pointer buttons. */
31
+ stop(): void;
32
+ /** Manually advance one tick (useful when integrating into an existing loop or unit tests). */
33
+ tick(dtSec?: number, nowMs?: number): void;
34
+ /** Hot-swaps the active profile at runtime, releasing stale keys and updating triggers. */
35
+ setProfile(profile: BuiltinBridgeProfileId | BridgeProfile): void;
36
+ /** Returns the current virtual cursor coordinates and button state. */
37
+ getCursor(): VirtualCursorState;
38
+ /**
39
+ * Source-level haptic upgrade hook: call this from inside an adapted game on hit, explosion,
40
+ * score, or collision to fire cross-brand haptics across DualSense / Switch Pro / Xbox / standard pads.
41
+ */
42
+ triggerHaptic(presetOrSpec: TactilePresetId | HapticPulseSpec, opts?: {
43
+ pan?: number;
44
+ intensity?: number;
45
+ }): void;
46
+ /** Stops the bridge, releases synthetic inputs, and resets triggers. */
47
+ dispose(): void;
48
+ }
49
+ export declare function createKeyMouseBridge(options: KeyMouseBridgeOptions): KeyMouseBridge;
50
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bridge/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAAmB,KAAK,eAAe,EAAwB,MAAM,uBAAuB,CAAC;AACpG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EACL,uBAAuB,EACvB,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,sBAAsB,EAC3B,KAAK,cAAc,EACnB,KAAK,oBAAoB,EAC1B,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,uBAAuB,EACvB,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,sBAAsB,EAC3B,KAAK,cAAc,EACnB,KAAK,oBAAoB,GAC1B,CAAC;AAEF,MAAM,WAAW,kBAAkB;IACjC,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,IAAI,EAAE,OAAO,CAAC;IACd,aAAa,EAAE,OAAO,CAAC;IACvB,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,qBAAqB;IACpC,kFAAkF;IAClF,MAAM,EAAE,YAAY,GAAG,YAAY,CAAC;IACpC,uDAAuD;IACvD,OAAO,EAAE,sBAAsB,GAAG,aAAa,CAAC;IAChD,0EAA0E;IAC1E,SAAS,CAAC,EAAE,WAAW,CAAC;IACxB,iHAAiH;IACjH,aAAa,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC;IACnC,6GAA6G;IAC7G,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,kBAAkB,KAAK,IAAI,CAAC;IACtD,0FAA0F;IAC1F,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,cAAc;IAC7B,0GAA0G;IAC1G,KAAK,IAAI,IAAI,CAAC;IACd,8FAA8F;IAC9F,IAAI,IAAI,IAAI,CAAC;IACb,+FAA+F;IAC/F,IAAI,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3C,2FAA2F;IAC3F,UAAU,CAAC,OAAO,EAAE,sBAAsB,GAAG,aAAa,GAAG,IAAI,CAAC;IAClE,uEAAuE;IACvE,SAAS,IAAI,kBAAkB,CAAC;IAChC;;;OAGG;IACH,aAAa,CAAC,YAAY,EAAE,eAAe,GAAG,eAAe,EAAE,IAAI,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAClH,wEAAwE;IACxE,OAAO,IAAI,IAAI,CAAC;CACjB;AAqJD,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,cAAc,CA+QnF"}
@@ -0,0 +1,422 @@
1
+ import {
2
+ TRIGGER_PRESETS,
3
+ applyDeadzone
4
+ } from "../chunks/chunk-GMU2WEFE.js";
5
+
6
+ // src/bridge/profiles.ts
7
+ var BUILTIN_BRIDGE_PROFILES = {
8
+ platformer: {
9
+ name: "Platformer (WASD / Arrows + Space Jump)",
10
+ keys: {
11
+ left: "ArrowLeft",
12
+ right: "ArrowRight",
13
+ up: "ArrowUp",
14
+ down: "ArrowDown",
15
+ "lx-": "ArrowLeft",
16
+ "lx+": "ArrowRight",
17
+ "ly-": "ArrowUp",
18
+ "ly+": "ArrowDown",
19
+ cross: { code: "Space", hapticOnPress: "click" },
20
+ square: { code: "KeyZ", hapticOnPress: "recoil", hapticPan: 0.4 },
21
+ circle: { code: "KeyX", hapticOnPress: "click" },
22
+ r2: { code: "ShiftLeft", hapticOnPress: "boost", hapticPan: 0.6 },
23
+ options: "Escape"
24
+ },
25
+ triggers: {
26
+ right: "soft_wall"
27
+ }
28
+ },
29
+ "arcade-4way": {
30
+ name: "Arcade 4-Way (Grid / Puzzle / Snake / Tetris)",
31
+ keys: {
32
+ left: { code: "ArrowLeft", repeatMs: 120, hapticOnPress: "ratchet", hapticPan: -0.5 },
33
+ right: { code: "ArrowRight", repeatMs: 120, hapticOnPress: "ratchet", hapticPan: 0.5 },
34
+ up: { code: "ArrowUp", repeatMs: 120, hapticOnPress: "ratchet" },
35
+ down: { code: "ArrowDown", repeatMs: 90, hapticOnPress: "ratchet" },
36
+ "lx-": { code: "ArrowLeft", repeatMs: 140, hapticOnPress: "ratchet", hapticPan: -0.5 },
37
+ "lx+": { code: "ArrowRight", repeatMs: 140, hapticOnPress: "ratchet", hapticPan: 0.5 },
38
+ "ly-": { code: "ArrowUp", repeatMs: 140, hapticOnPress: "ratchet" },
39
+ "ly+": { code: "ArrowDown", repeatMs: 100, hapticOnPress: "ratchet" },
40
+ cross: { code: "Space", hapticOnPress: "click" },
41
+ circle: "Escape",
42
+ options: "Enter"
43
+ }
44
+ },
45
+ racing: {
46
+ name: "Racing (Steer + R2 Gas / L2 ABS Brake)",
47
+ keys: {
48
+ left: "ArrowLeft",
49
+ right: "ArrowRight",
50
+ "lx-": { code: "ArrowLeft", threshold: 0.25 },
51
+ "lx+": { code: "ArrowRight", threshold: 0.25 },
52
+ r2: { code: "ArrowUp", threshold: 0.2 },
53
+ l2: { code: "ArrowDown", threshold: 0.2 },
54
+ cross: { code: "Space", hapticOnPress: "boost" },
55
+ square: { code: "ShiftLeft", hapticOnPress: "ratchet" },
56
+ options: "Escape"
57
+ },
58
+ triggers: {
59
+ left: "abs",
60
+ right: "bow"
61
+ }
62
+ },
63
+ "twin-stick": {
64
+ name: "Twin-Stick Shooter (Left Stick Move + Right Stick Aim + R2 Fire)",
65
+ keys: {
66
+ "lx-": "KeyA",
67
+ "lx+": "KeyD",
68
+ "ly-": "KeyW",
69
+ "ly+": "KeyS",
70
+ left: "KeyA",
71
+ right: "KeyD",
72
+ up: "KeyW",
73
+ down: "KeyS",
74
+ cross: { code: "Space", hapticOnPress: "click" },
75
+ square: { code: "KeyR", hapticOnPress: "ratchet" },
76
+ options: "Escape"
77
+ },
78
+ pointer: {
79
+ stick: "right",
80
+ speedPxPerSec: 720,
81
+ deadzone: 0.14,
82
+ clickButton: "r2",
83
+ secondaryClickButton: "l2",
84
+ hapticOnClick: "recoil"
85
+ },
86
+ triggers: {
87
+ left: "precision_damp",
88
+ right: "weapon"
89
+ }
90
+ }
91
+ };
92
+
93
+ // src/bridge/index.ts
94
+ var KEY_CODE_TABLE = {
95
+ Space: { key: " ", keyCode: 32 },
96
+ Enter: { key: "Enter", keyCode: 13 },
97
+ Escape: { key: "Escape", keyCode: 27 },
98
+ Tab: { key: "Tab", keyCode: 9 },
99
+ Backspace: { key: "Backspace", keyCode: 8 },
100
+ ArrowLeft: { key: "ArrowLeft", keyCode: 37 },
101
+ ArrowUp: { key: "ArrowUp", keyCode: 38 },
102
+ ArrowRight: { key: "ArrowRight", keyCode: 39 },
103
+ ArrowDown: { key: "ArrowDown", keyCode: 40 },
104
+ ShiftLeft: { key: "Shift", keyCode: 16 },
105
+ ShiftRight: { key: "Shift", keyCode: 16 },
106
+ ControlLeft: { key: "Control", keyCode: 17 },
107
+ AltLeft: { key: "Alt", keyCode: 18 }
108
+ };
109
+ function inferKeyMeta(rule) {
110
+ const known = KEY_CODE_TABLE[rule.code];
111
+ if (known) {
112
+ return {
113
+ code: rule.code,
114
+ key: rule.key ?? known.key,
115
+ keyCode: rule.keyCode ?? known.keyCode
116
+ };
117
+ }
118
+ if (/^Key[A-Z]$/.test(rule.code)) {
119
+ const ch = rule.code.slice(3);
120
+ return {
121
+ code: rule.code,
122
+ key: rule.key ?? ch.toLowerCase(),
123
+ keyCode: rule.keyCode ?? ch.charCodeAt(0)
124
+ };
125
+ }
126
+ if (/^Digit[0-9]$/.test(rule.code)) {
127
+ const ch = rule.code.slice(5);
128
+ return {
129
+ code: rule.code,
130
+ key: rule.key ?? ch,
131
+ keyCode: rule.keyCode ?? ch.charCodeAt(0)
132
+ };
133
+ }
134
+ return {
135
+ code: rule.code,
136
+ key: rule.key ?? rule.code,
137
+ keyCode: rule.keyCode ?? 0
138
+ };
139
+ }
140
+ function normalizeRules(entry) {
141
+ const arr = Array.isArray(entry) ? entry : [entry];
142
+ return arr.map((item) => typeof item === "string" ? { code: item } : item);
143
+ }
144
+ function readSourceValue(source, input) {
145
+ if (source === "l2") return input.l2;
146
+ if (source === "r2") return input.r2;
147
+ if (source === "lx+") return Math.max(0, input.lx);
148
+ if (source === "lx-") return Math.max(0, -input.lx);
149
+ if (source === "ly+") return Math.max(0, input.ly);
150
+ if (source === "ly-") return Math.max(0, -input.ly);
151
+ if (source === "rx+") return Math.max(0, input.rx);
152
+ if (source === "rx-") return Math.max(0, -input.rx);
153
+ if (source === "ry+") return Math.max(0, input.ry);
154
+ if (source === "ry-") return Math.max(0, -input.ry);
155
+ return input.buttons[source] ? 1 : 0;
156
+ }
157
+ function resolveTriggerSpec(val) {
158
+ if (!val) return void 0;
159
+ return typeof val === "string" ? TRIGGER_PRESETS[val] : val;
160
+ }
161
+ function isHub(p) {
162
+ return "active" in p && "getSlots" in p;
163
+ }
164
+ function dispatchSyntheticKey(target, type, meta, repeat = false) {
165
+ if (typeof KeyboardEvent !== "undefined") {
166
+ const evt = new KeyboardEvent(type, {
167
+ key: meta.key,
168
+ code: meta.code,
169
+ bubbles: true,
170
+ cancelable: true,
171
+ repeat
172
+ });
173
+ try {
174
+ Object.defineProperty(evt, "keyCode", { value: meta.keyCode });
175
+ Object.defineProperty(evt, "which", { value: meta.keyCode });
176
+ } catch {
177
+ }
178
+ target.dispatchEvent(evt);
179
+ return;
180
+ }
181
+ if (typeof Event !== "undefined") {
182
+ const evt = new Event(type, { bubbles: true, cancelable: true });
183
+ evt.key = meta.key;
184
+ evt.code = meta.code;
185
+ evt.keyCode = meta.keyCode;
186
+ evt.which = meta.keyCode;
187
+ evt.repeat = repeat;
188
+ target.dispatchEvent(evt);
189
+ }
190
+ }
191
+ function dispatchSyntheticPointer(target, type, clientX, clientY, button, buttons) {
192
+ const init = {
193
+ bubbles: true,
194
+ cancelable: true,
195
+ clientX,
196
+ clientY,
197
+ button,
198
+ buttons,
199
+ pointerId: 1,
200
+ pointerType: "mouse",
201
+ isPrimary: true
202
+ };
203
+ if (typeof PointerEvent !== "undefined") {
204
+ target.dispatchEvent(new PointerEvent(type, init));
205
+ }
206
+ const mouseType = type.replace("pointer", "mouse");
207
+ if (typeof MouseEvent !== "undefined") {
208
+ target.dispatchEvent(new MouseEvent(mouseType, init));
209
+ }
210
+ }
211
+ function createKeyMouseBridge(options) {
212
+ const hub = isHub(options.player) ? options.player : null;
213
+ const player = hub ? hub.active : options.player;
214
+ const keyTarget = options.keyTarget ?? (typeof window !== "undefined" ? window : void 0);
215
+ const pointerTarget = options.pointerTarget !== void 0 ? options.pointerTarget : typeof document !== "undefined" ? document.body : null;
216
+ let profile = typeof options.profile === "string" ? BUILTIN_BRIDGE_PROFILES[options.profile] : options.profile;
217
+ let running = false;
218
+ let rafId = 0;
219
+ let lastFrameAt = 0;
220
+ const heldKeys = /* @__PURE__ */ new Map();
221
+ const prevRulePressed = /* @__PURE__ */ new Map();
222
+ const cursor = {
223
+ x: 0,
224
+ y: 0,
225
+ down: false,
226
+ secondaryDown: false,
227
+ visible: false
228
+ };
229
+ let cursorInitialized = false;
230
+ const fireHaptic = (presetOrSpec, opts) => {
231
+ if (typeof presetOrSpec === "string") {
232
+ player.haptics.playPreset(presetOrSpec, opts);
233
+ } else {
234
+ player.haptics.pulse({
235
+ ...presetOrSpec,
236
+ pan: opts?.pan ?? presetOrSpec.pan,
237
+ intensity: (opts?.intensity ?? 1) * presetOrSpec.intensity
238
+ });
239
+ }
240
+ };
241
+ const applyProfileTriggers = () => {
242
+ const left = resolveTriggerSpec(profile.triggers?.left);
243
+ const right = resolveTriggerSpec(profile.triggers?.right);
244
+ if (left && right) player.triggers.setBoth(left, right);
245
+ else if (left) player.triggers.setLeft(left);
246
+ else if (right) player.triggers.setRight(right);
247
+ else player.triggers.reset();
248
+ };
249
+ const unsubCaps = hub ? hub.onCapabilitiesChange(() => {
250
+ if (running) applyProfileTriggers();
251
+ }) : null;
252
+ const releaseAllHeld = () => {
253
+ if (keyTarget) {
254
+ for (const { meta } of heldKeys.values()) {
255
+ dispatchSyntheticKey(keyTarget, "keyup", meta, false);
256
+ }
257
+ }
258
+ heldKeys.clear();
259
+ prevRulePressed.clear();
260
+ if (pointerTarget && (cursor.down || cursor.secondaryDown)) {
261
+ const rect = pointerTarget.getBoundingClientRect?.() ?? { left: 0, top: 0 };
262
+ if (cursor.down) {
263
+ dispatchSyntheticPointer(pointerTarget, "pointerup", rect.left + cursor.x, rect.top + cursor.y, 0, 0);
264
+ }
265
+ if (cursor.secondaryDown) {
266
+ dispatchSyntheticPointer(pointerTarget, "pointerup", rect.left + cursor.x, rect.top + cursor.y, 2, 0);
267
+ }
268
+ }
269
+ cursor.down = false;
270
+ cursor.secondaryDown = false;
271
+ };
272
+ const tick = (dtSec, nowMs = typeof performance !== "undefined" ? performance.now() : Date.now()) => {
273
+ const dt = dtSec !== void 0 ? Math.max(0, Math.min(0.1, dtSec)) : lastFrameAt > 0 ? Math.max(0, Math.min(0.1, (nowMs - lastFrameAt) / 1e3)) : 1 / 60;
274
+ lastFrameAt = nowMs;
275
+ const input = player.input.getState();
276
+ if (!input.connected || input.source === "keyboard_mouse") {
277
+ if (heldKeys.size > 0 || cursor.down || cursor.secondaryDown) {
278
+ releaseAllHeld();
279
+ }
280
+ return;
281
+ }
282
+ const activeCodes = /* @__PURE__ */ new Map();
283
+ for (const [sourceKey, rawEntry] of Object.entries(profile.keys)) {
284
+ if (!rawEntry) continue;
285
+ const source = sourceKey;
286
+ const val = readSourceValue(source, input);
287
+ const rules = normalizeRules(rawEntry);
288
+ for (let i = 0; i < rules.length; i++) {
289
+ const rule = rules[i];
290
+ const threshold = rule.threshold ?? 0.45;
291
+ const pressed = val >= threshold;
292
+ const ruleKey = `${source}:${rule.code}:${i}`;
293
+ const wasPressed = prevRulePressed.get(ruleKey) ?? false;
294
+ prevRulePressed.set(ruleKey, pressed);
295
+ if (pressed) {
296
+ const meta = inferKeyMeta(rule);
297
+ if (!activeCodes.has(meta.code)) {
298
+ activeCodes.set(meta.code, {
299
+ meta,
300
+ repeatMs: rule.repeatMs,
301
+ repeatDelayMs: rule.repeatDelayMs ?? 220
302
+ });
303
+ }
304
+ if (!wasPressed && rule.hapticOnPress) {
305
+ fireHaptic(rule.hapticOnPress, { pan: rule.hapticPan });
306
+ }
307
+ }
308
+ }
309
+ }
310
+ if (keyTarget) {
311
+ for (const [code, held] of heldKeys.entries()) {
312
+ if (!activeCodes.has(code)) {
313
+ dispatchSyntheticKey(keyTarget, "keyup", held.meta, false);
314
+ heldKeys.delete(code);
315
+ }
316
+ }
317
+ for (const [code, info] of activeCodes.entries()) {
318
+ const existing = heldKeys.get(code);
319
+ if (!existing) {
320
+ dispatchSyntheticKey(keyTarget, "keydown", info.meta, false);
321
+ heldKeys.set(code, {
322
+ meta: info.meta,
323
+ nextRepeatAt: info.repeatMs ? nowMs + info.repeatDelayMs : Number.POSITIVE_INFINITY
324
+ });
325
+ } else if (info.repeatMs && nowMs >= existing.nextRepeatAt) {
326
+ dispatchSyntheticKey(keyTarget, "keydown", info.meta, true);
327
+ existing.nextRepeatAt = nowMs + info.repeatMs;
328
+ }
329
+ }
330
+ }
331
+ if (profile.pointer && pointerTarget) {
332
+ const cfg = profile.pointer;
333
+ const rect = pointerTarget.getBoundingClientRect?.() ?? { left: 0, top: 0, width: 800, height: 600 };
334
+ const w = Math.max(1, rect.width);
335
+ const h = Math.max(1, rect.height);
336
+ if (!cursorInitialized) {
337
+ cursor.x = w / 2;
338
+ cursor.y = h / 2;
339
+ cursorInitialized = true;
340
+ }
341
+ const dz = cfg.deadzone ?? 0.14;
342
+ const sx = applyDeadzone(cfg.stick === "left" ? input.lx : input.rx, dz);
343
+ const sy = applyDeadzone(cfg.stick === "left" ? input.ly : input.ry, dz);
344
+ const speed = cfg.speedPxPerSec ?? 680;
345
+ const moved = sx !== 0 || sy !== 0;
346
+ if (moved) {
347
+ cursor.x = Math.max(0, Math.min(w, cursor.x + sx * speed * dt));
348
+ cursor.y = Math.max(0, Math.min(h, cursor.y + sy * speed * dt));
349
+ cursor.visible = true;
350
+ }
351
+ const clickSrc = cfg.clickButton ?? "r2";
352
+ const secSrc = cfg.secondaryClickButton ?? "l2";
353
+ const nextDown = readSourceValue(clickSrc, input) >= 0.45;
354
+ const nextSecDown = readSourceValue(secSrc, input) >= 0.45;
355
+ const buttonsMask = (nextDown ? 1 : 0) | (nextSecDown ? 2 : 0);
356
+ const cx = rect.left + cursor.x;
357
+ const cy = rect.top + cursor.y;
358
+ if (moved) {
359
+ dispatchSyntheticPointer(pointerTarget, "pointermove", cx, cy, -1, buttonsMask);
360
+ }
361
+ if (nextDown !== cursor.down) {
362
+ cursor.down = nextDown;
363
+ cursor.visible = true;
364
+ dispatchSyntheticPointer(pointerTarget, nextDown ? "pointerdown" : "pointerup", cx, cy, 0, buttonsMask);
365
+ if (nextDown && cfg.hapticOnClick) {
366
+ fireHaptic(cfg.hapticOnClick);
367
+ }
368
+ }
369
+ if (nextSecDown !== cursor.secondaryDown) {
370
+ cursor.secondaryDown = nextSecDown;
371
+ cursor.visible = true;
372
+ dispatchSyntheticPointer(pointerTarget, nextSecDown ? "pointerdown" : "pointerup", cx, cy, 2, buttonsMask);
373
+ }
374
+ options.onCursorUpdate?.({ ...cursor });
375
+ }
376
+ };
377
+ const loop = (now) => {
378
+ if (!running) return;
379
+ tick(void 0, now);
380
+ rafId = requestAnimationFrame(loop);
381
+ };
382
+ return {
383
+ start() {
384
+ if (running) return;
385
+ running = true;
386
+ lastFrameAt = 0;
387
+ applyProfileTriggers();
388
+ if (options.autoRaf !== false && typeof requestAnimationFrame !== "undefined") {
389
+ rafId = requestAnimationFrame(loop);
390
+ }
391
+ },
392
+ stop() {
393
+ if (!running) return;
394
+ running = false;
395
+ if (rafId && typeof cancelAnimationFrame !== "undefined") {
396
+ cancelAnimationFrame(rafId);
397
+ }
398
+ rafId = 0;
399
+ releaseAllHeld();
400
+ },
401
+ tick,
402
+ setProfile(next) {
403
+ releaseAllHeld();
404
+ profile = typeof next === "string" ? BUILTIN_BRIDGE_PROFILES[next] : next;
405
+ if (running) applyProfileTriggers();
406
+ },
407
+ getCursor() {
408
+ return { ...cursor };
409
+ },
410
+ triggerHaptic: fireHaptic,
411
+ dispose() {
412
+ this.stop();
413
+ unsubCaps?.();
414
+ player.triggers.reset();
415
+ }
416
+ };
417
+ }
418
+ export {
419
+ BUILTIN_BRIDGE_PROFILES,
420
+ createKeyMouseBridge
421
+ };
422
+ //# sourceMappingURL=index.js.map