@gamepadly/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +4140 -0
  13. package/dist/browser.js.map +7 -0
  14. package/dist/browser.min.js +1 -0
  15. package/dist/chunks/chunk-BEBDNL5B.js +1850 -0
  16. package/dist/chunks/chunk-BEBDNL5B.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 +747 -0
  28. package/dist/index.js.map +7 -0
  29. package/dist/input/actions.d.ts +59 -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 +944 -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
@@ -0,0 +1,4140 @@
1
+ // src/hid/index.ts
2
+ var SONY_VENDOR_ID = 1356;
3
+ var DUALSENSE_PIDS = [3302, 3570];
4
+ var NINTENDO_VENDOR_ID = 1406;
5
+ var SWITCH_PRO_PIDS = [8201];
6
+ var SWITCH_NEUTRAL_RUMBLE = new Uint8Array([0, 1, 64, 64]);
7
+ function encodeSwitchAmpStep(rawAmp) {
8
+ if (!Number.isFinite(rawAmp) || rawAmp <= 0.01) return 0;
9
+ const amp = Math.min(0.85, Math.max(0, rawAmp));
10
+ if (amp >= 0.23) {
11
+ return Math.min(100, Math.round(Math.log2(amp * 8.7) * 32));
12
+ }
13
+ if (amp >= 0.12) {
14
+ return Math.round(Math.log2(amp * 17) * 16);
15
+ }
16
+ return Math.max(1, Math.round(amp / 0.12 * 16));
17
+ }
18
+ function encodeSwitchHdRumbleSide(side) {
19
+ if (!side || side.highAmp <= 0.01 && side.lowAmp <= 0.01) {
20
+ return SWITCH_NEUTRAL_RUMBLE.slice();
21
+ }
22
+ const hfHz = Math.max(81.75, Math.min(1252.6, Number.isFinite(side.highFreqHz) ? side.highFreqHz : 320));
23
+ const lfHz = Math.max(40.88, Math.min(626.3, Number.isFinite(side.lowFreqHz) ? side.lowFreqHz : 160));
24
+ const encodedHf = Math.round(Math.log2(hfHz / 10) * 32);
25
+ const encodedLf = Math.round(Math.log2(lfHz / 10) * 32);
26
+ const hf = Math.max(0, Math.min(508, (encodedHf - 96) * 4));
27
+ const lf = Math.max(1, Math.min(127, encodedLf - 64));
28
+ const hfStep = encodeSwitchAmpStep(side.highAmp);
29
+ const lfStep = encodeSwitchAmpStep(side.lowAmp);
30
+ const hfAmpByte = Math.min(200, hfStep * 2);
31
+ const lfAmpParity = (lfStep & 1) !== 0 ? 128 : 0;
32
+ const lfAmpLo = Math.min(114, (lfStep >> 1) + 64);
33
+ return new Uint8Array([
34
+ hf & 255,
35
+ hfAmpByte + (hf >> 8 & 1) & 255,
36
+ (lf | lfAmpParity) & 255,
37
+ lfAmpLo & 255
38
+ ]);
39
+ }
40
+ function applyDeadzone(value, threshold = 0.06) {
41
+ const abs = Math.abs(value);
42
+ if (abs <= threshold) return 0;
43
+ const scaled = (abs - threshold) / (1 - threshold);
44
+ return Math.sign(value) * Math.max(0, Math.min(1, scaled));
45
+ }
46
+ function parseGamepadVendorId(lower) {
47
+ return (lower.match(/vendor:\s*([0-9a-f]{4})/) ?? lower.match(/^([0-9a-f]{1,4})-[0-9a-f]{1,4}-/))?.[1]?.padStart(4, "0");
48
+ }
49
+ function detectGamepadBrand(lower) {
50
+ const vendor = parseGamepadVendorId(lower);
51
+ if (vendor === "054c") return "sony";
52
+ if (vendor === "045e") return "xbox";
53
+ if (vendor === "057e") return "nintendo";
54
+ if (vendor) return void 0;
55
+ if (/xbox|xinput|microsoft/.test(lower)) return "xbox";
56
+ if (/dualsense|dualshock|wireless controller/.test(lower)) return "sony";
57
+ if (/nintendo|pro controller|joy-con|switch/.test(lower)) return "nintendo";
58
+ return void 0;
59
+ }
60
+ function identifyGamepadFromId(rawId) {
61
+ const lower = (rawId || "").toLowerCase();
62
+ const brand = detectGamepadBrand(lower);
63
+ if (brand === "sony") {
64
+ if (/0df2|edge/.test(lower)) {
65
+ return { brand: "sony", model: "dualsense_edge", displayName: "DualSense Edge", rawId, vendorId: 1356, productId: 3570 };
66
+ }
67
+ if (/0ce6|dualsense/.test(lower)) {
68
+ return { brand: "sony", model: "dualsense", displayName: "PlayStation DualSense", rawId, vendorId: 1356, productId: 3302 };
69
+ }
70
+ if (/05c4|09cc|dualshock/.test(lower)) {
71
+ return { brand: "sony", model: "dualshock4", displayName: "DualShock 4", rawId, vendorId: 1356 };
72
+ }
73
+ return { brand: "sony", model: "dualsense", displayName: "PlayStation Controller", rawId, vendorId: 1356 };
74
+ }
75
+ if (brand === "xbox") {
76
+ if (/0b12|0b13|0b20|0b21|0b22|series/.test(lower)) {
77
+ return { brand: "xbox", model: "xbox_series", displayName: "Xbox Wireless Controller", rawId, vendorId: 1118 };
78
+ }
79
+ if (/028e|360/.test(lower)) {
80
+ return { brand: "xbox", model: "xbox_360", displayName: "Xbox 360 Controller", rawId, vendorId: 1118 };
81
+ }
82
+ return { brand: "xbox", model: "xbox_series", displayName: "Xbox Controller", rawId, vendorId: 1118 };
83
+ }
84
+ if (brand === "nintendo") {
85
+ if (/2069|pro 2|switch 2/.test(lower)) {
86
+ return { brand: "nintendo", model: "switch2_pro", displayName: "Nintendo Switch 2 Pro Controller", rawId, vendorId: 1406, productId: 8297 };
87
+ }
88
+ if (/joy-con|2006|2007/.test(lower)) {
89
+ return { brand: "nintendo", model: "joycon", displayName: "Nintendo Joy-Con", rawId, vendorId: 1406 };
90
+ }
91
+ return { brand: "nintendo", model: "switch_pro", displayName: "Nintendo Switch Pro Controller", rawId, vendorId: 1406, productId: 8201 };
92
+ }
93
+ if (rawId) {
94
+ return { brand: "generic", model: "generic", displayName: rawId.split("(")[0].trim() || rawId, rawId };
95
+ }
96
+ return { brand: "none", model: "none", displayName: "No Controller Detected", rawId: "" };
97
+ }
98
+ var CRC32_TABLE = (() => {
99
+ const table = new Uint32Array(256);
100
+ for (let i = 0; i < 256; i++) {
101
+ let c = i;
102
+ for (let k = 0; k < 8; k++) {
103
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
104
+ }
105
+ table[i] = c >>> 0;
106
+ }
107
+ return table;
108
+ })();
109
+ function crc32WithSeed(seedByte, reportId, bytes) {
110
+ let crc = 4294967295;
111
+ crc = CRC32_TABLE[(crc ^ seedByte) & 255] ^ crc >>> 8;
112
+ crc = CRC32_TABLE[(crc ^ reportId) & 255] ^ crc >>> 8;
113
+ for (let i = 0; i < bytes.length; i++) {
114
+ crc = CRC32_TABLE[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
115
+ }
116
+ return (crc ^ 4294967295) >>> 0;
117
+ }
118
+ function encodeTriggerEffect(spec) {
119
+ const out = new Uint8Array(11);
120
+ if (spec.type === "off") {
121
+ out[0] = 5;
122
+ return out;
123
+ }
124
+ if (spec.type === "feedback" || spec.type === "slope") {
125
+ out[0] = 33;
126
+ const forces = new Array(10).fill(0);
127
+ if (spec.type === "feedback") {
128
+ const s2 = Math.max(0, Math.min(9, Math.round(spec.startZone)));
129
+ const f = Math.max(1, Math.min(8, Math.round(spec.strength)));
130
+ for (let i = s2; i < 10; i++) forces[i] = f;
131
+ } else {
132
+ const s2 = Math.max(0, Math.min(8, Math.round(spec.startZone)));
133
+ const e = Math.max(s2 + 1, Math.min(9, Math.round(spec.endZone)));
134
+ for (let i = s2; i <= e; i++) {
135
+ const t = (i - s2) / (e - s2);
136
+ forces[i] = Math.max(
137
+ 1,
138
+ Math.min(8, Math.round(spec.startStrength + t * (spec.endStrength - spec.startStrength)))
139
+ );
140
+ }
141
+ }
142
+ let activeZones2 = 0;
143
+ let forceZones = 0;
144
+ for (let i = 0; i < 10; i++) {
145
+ const f = forces[i];
146
+ if (f > 0) {
147
+ activeZones2 |= 1 << i;
148
+ forceZones |= (f - 1 & 7) << 3 * i;
149
+ }
150
+ }
151
+ out[1] = activeZones2 & 255;
152
+ out[2] = activeZones2 >> 8 & 255;
153
+ out[3] = forceZones & 255;
154
+ out[4] = forceZones >> 8 & 255;
155
+ out[5] = forceZones >> 16 & 255;
156
+ out[6] = forceZones >> 24 & 255;
157
+ return out;
158
+ }
159
+ if (spec.type === "weapon") {
160
+ const s2 = Math.max(2, Math.min(7, Math.round(spec.startZone)));
161
+ const e = Math.max(s2 + 1, Math.min(8, Math.round(spec.endZone)));
162
+ const f = Math.max(1, Math.min(8, Math.round(spec.strength)));
163
+ const startEnd = 1 << s2 | 1 << e;
164
+ out[0] = 37;
165
+ out[1] = startEnd & 255;
166
+ out[2] = startEnd >> 8 & 255;
167
+ out[3] = f - 1 & 7;
168
+ return out;
169
+ }
170
+ const s = Math.max(0, Math.min(9, Math.round(spec.startZone)));
171
+ const a = Math.max(1, Math.min(8, Math.round(spec.amplitude)));
172
+ const freq = Math.max(1, Math.min(255, Math.round(spec.frequencyHz)));
173
+ let activeZones = 0;
174
+ let ampZones = 0;
175
+ for (let i = s; i < 10; i++) {
176
+ activeZones |= 1 << i;
177
+ ampZones |= (a - 1 & 7) << 3 * i;
178
+ }
179
+ out[0] = 38;
180
+ out[1] = activeZones & 255;
181
+ out[2] = activeZones >> 8 & 255;
182
+ out[3] = ampZones & 255;
183
+ out[4] = ampZones >> 8 & 255;
184
+ out[5] = ampZones >> 16 & 255;
185
+ out[6] = ampZones >> 24 & 255;
186
+ out[9] = freq;
187
+ return out;
188
+ }
189
+ function createEmptyInput() {
190
+ return {
191
+ connected: false,
192
+ source: "none",
193
+ deviceName: "",
194
+ isDualSense: false,
195
+ identity: {
196
+ brand: "none",
197
+ model: "none",
198
+ displayName: "No Controller Detected",
199
+ rawId: "",
200
+ transport: "disconnected",
201
+ source: "none"
202
+ },
203
+ lx: 0,
204
+ ly: 0,
205
+ rx: 0,
206
+ ry: 0,
207
+ l2: 0,
208
+ r2: 0,
209
+ buttons: {
210
+ cross: false,
211
+ circle: false,
212
+ square: false,
213
+ triangle: false,
214
+ l1: false,
215
+ r1: false,
216
+ l2Btn: false,
217
+ r2Btn: false,
218
+ l3: false,
219
+ r3: false,
220
+ up: false,
221
+ down: false,
222
+ left: false,
223
+ right: false,
224
+ create: false,
225
+ options: false,
226
+ ps: false,
227
+ touchpadClick: false
228
+ },
229
+ touch: { active: false, x: 0.5, y: 0.5 },
230
+ touch2: { active: false, x: 0.5, y: 0.5 },
231
+ gyro: { x: 0, y: 0, z: 0 },
232
+ accel: { x: 0, y: 0, z: 0 },
233
+ battery: { percent: 0, charging: false, full: false, known: false },
234
+ observedReportHz: null
235
+ };
236
+ }
237
+ function createDefaultSwitchCal() {
238
+ const def = () => ({ center: 2048, minDelta: 1500, maxDelta: 1500 });
239
+ return { lx: def(), ly: def(), rx: def(), ry: def() };
240
+ }
241
+ var PS5_PLAYER_LED_PATTERNS = [4, 10, 21, 27];
242
+ var SWITCH_PLAYER_LED_PATTERNS = [1, 3, 7, 15];
243
+ function sleepMs(ms) {
244
+ return new Promise((resolve) => setTimeout(resolve, ms));
245
+ }
246
+ function createDefaultOutState(playerIndex = 0) {
247
+ return {
248
+ speakerVolume: 100,
249
+ headphoneVolume: 100,
250
+ audioRoute: "speaker",
251
+ speakerPreamp: 7,
252
+ lightbar: [23, 23, 23],
253
+ playerLeds: PS5_PLAYER_LED_PATTERNS[playerIndex % PS5_PLAYER_LED_PATTERNS.length],
254
+ leftTrigger: encodeTriggerEffect({ type: "off" }),
255
+ rightTrigger: encodeTriggerEffect({ type: "off" }),
256
+ legacyRumbleActive: false,
257
+ legacyLeft: 0,
258
+ legacyRight: 0
259
+ };
260
+ }
261
+ var DualSenseControllerManager = class _DualSenseControllerManager {
262
+ hidSessions = /* @__PURE__ */ new Map();
263
+ nextHidSeq = 1;
264
+ activeSlotId = null;
265
+ hidDisconnectAttached = false;
266
+ hidConnectAttached = false;
267
+ listeners = /* @__PURE__ */ new Set();
268
+ // Per-gamepad input snapshots & activity tracking (supports P1-P4 simultaneous polling)
269
+ gamepadInputs = /* @__PURE__ */ new Map();
270
+ gamepadLastActivity = /* @__PURE__ */ new Map();
271
+ gamepadPrevBtnMask = /* @__PURE__ */ new Map();
272
+ // Fallback buffer for single-slot Gamepad API & Keyboard/Mouse snapshots
273
+ fallbackInput = createEmptyInput();
274
+ keysDown = /* @__PURE__ */ new Set();
275
+ kbmAttached = false;
276
+ boundConnect = (e) => {
277
+ void this.handleConnect(e);
278
+ };
279
+ boundDisconnect = (e) => this.handleDisconnect(e);
280
+ boundKeyDown = (e) => {
281
+ this.keysDown.add(e.code);
282
+ };
283
+ boundKeyUp = (e) => {
284
+ this.keysDown.delete(e.code);
285
+ };
286
+ boundWindowBlur = () => {
287
+ this.keysDown.clear();
288
+ };
289
+ /** Active slot's WebHID device (null if active slot is a Gamepad API controller or disconnected). */
290
+ get device() {
291
+ return this.getActiveHidSession()?.device ?? null;
292
+ }
293
+ /** Active slot's WebHID transport (or 'disconnected' when active slot is not WebHID). */
294
+ get transport() {
295
+ return this.getActiveHidSession()?.transport ?? "disconnected";
296
+ }
297
+ /** Active slot's read-only DualSense firmware metadata, if available. */
298
+ get firmwareInfo() {
299
+ return this.getActiveHidSession()?.firmwareInfo;
300
+ }
301
+ /** Count of currently open WebHID sessions (multi-DualSense support). */
302
+ get hidDeviceCount() {
303
+ return this.hidSessions.size;
304
+ }
305
+ static isWebHIDSupported() {
306
+ return typeof navigator !== "undefined" && "hid" in navigator;
307
+ }
308
+ static isGamepadSupported() {
309
+ return typeof navigator !== "undefined" && typeof navigator.getGamepads === "function";
310
+ }
311
+ isSupportedHidDevice(device) {
312
+ return device.vendorId === SONY_VENDOR_ID && DUALSENSE_PIDS.includes(device.productId) || device.vendorId === NINTENDO_VENDOR_ID && SWITCH_PRO_PIDS.includes(device.productId);
313
+ }
314
+ /**
315
+ * Listens for previously authorized DualSense / Switch Pro devices re-connecting over USB or Bluetooth
316
+ * while the page is open, automatically re-attaching WebHID with zero browser prompts.
317
+ */
318
+ attachHidHotplug() {
319
+ if (this.hidConnectAttached || !_DualSenseControllerManager.isWebHIDSupported()) return;
320
+ navigator.hid.addEventListener("connect", this.boundConnect);
321
+ this.hidConnectAttached = true;
322
+ }
323
+ detachHidHotplug() {
324
+ if (!this.hidConnectAttached || !_DualSenseControllerManager.isWebHIDSupported()) return;
325
+ navigator.hid.removeEventListener("connect", this.boundConnect);
326
+ this.hidConnectAttached = false;
327
+ }
328
+ async handleConnect(e) {
329
+ if (!this.isSupportedHidDevice(e.device)) return;
330
+ try {
331
+ await this.attachDevice(e.device);
332
+ } catch {
333
+ }
334
+ }
335
+ attachKeyboardFallback() {
336
+ if (this.kbmAttached || typeof window === "undefined") return;
337
+ window.addEventListener("keydown", this.boundKeyDown);
338
+ window.addEventListener("keyup", this.boundKeyUp);
339
+ window.addEventListener("blur", this.boundWindowBlur);
340
+ this.kbmAttached = true;
341
+ }
342
+ detachKeyboardFallback() {
343
+ if (!this.kbmAttached || typeof window === "undefined") return;
344
+ window.removeEventListener("keydown", this.boundKeyDown);
345
+ window.removeEventListener("keyup", this.boundKeyUp);
346
+ window.removeEventListener("blur", this.boundWindowBlur);
347
+ this.keysDown.clear();
348
+ this.kbmAttached = false;
349
+ }
350
+ onStatusChange(fn) {
351
+ this.listeners.add(fn);
352
+ return () => this.listeners.delete(fn);
353
+ }
354
+ emit(evt) {
355
+ for (const fn of this.listeners) {
356
+ try {
357
+ fn(evt);
358
+ } catch (err) {
359
+ console.error("[core-hid] listener error:", err);
360
+ }
361
+ }
362
+ }
363
+ getAllRawGamepads() {
364
+ if (!_DualSenseControllerManager.isGamepadSupported()) return [];
365
+ const pads = navigator.getGamepads();
366
+ const out = [];
367
+ for (const p of pads) {
368
+ if (p && p.connected) out.push(p);
369
+ }
370
+ return out;
371
+ }
372
+ pollGamepadActivity(pad) {
373
+ let mask = 0;
374
+ const len = Math.min(20, pad.buttons.length);
375
+ for (let i = 0; i < len; i++) {
376
+ if (pad.buttons[i]?.pressed) mask |= 1 << i;
377
+ }
378
+ const prev = this.gamepadPrevBtnMask.get(pad.index) ?? 0;
379
+ this.gamepadPrevBtnMask.set(pad.index, mask);
380
+ if ((mask & ~prev) !== 0) {
381
+ const now = performance.now();
382
+ this.gamepadLastActivity.set(pad.index, now);
383
+ return now;
384
+ }
385
+ return this.gamepadLastActivity.get(pad.index) ?? 0;
386
+ }
387
+ /**
388
+ * Returns all connected controllers across WebHID and Gamepad API, automatically
389
+ * deduplicating DualSense and Switch Pro controllers that appear in both APIs simultaneously.
390
+ */
391
+ getConnectedControllers() {
392
+ const slots = [];
393
+ let edgeHidCount = 0;
394
+ let stdHidCount = 0;
395
+ let switchProHidCount = 0;
396
+ for (const session of this.hidSessions.values()) {
397
+ if (!session.device.opened) continue;
398
+ if (session.input.identity.model === "dualsense_edge") edgeHidCount++;
399
+ else if (session.input.identity.model === "switch_pro") switchProHidCount++;
400
+ else stdHidCount++;
401
+ slots.push({
402
+ id: session.id,
403
+ playerNumber: slots.length + 1,
404
+ source: "webhid",
405
+ identity: { ...session.input.identity },
406
+ battery: { ...session.input.battery },
407
+ observedReportHz: session.input.observedReportHz,
408
+ lastActivityAt: session.lastActivityAt
409
+ });
410
+ }
411
+ const rawPads = this.getAllRawGamepads();
412
+ const activePadIndices = /* @__PURE__ */ new Set();
413
+ for (const pad of rawPads) {
414
+ activePadIndices.add(pad.index);
415
+ const baseId = identifyGamepadFromId(pad.id || "");
416
+ if (baseId.model === "dualsense_edge" && edgeHidCount > 0) {
417
+ edgeHidCount--;
418
+ continue;
419
+ }
420
+ if (baseId.model === "dualsense" && stdHidCount > 0) {
421
+ stdHidCount--;
422
+ continue;
423
+ }
424
+ if (baseId.model === "switch_pro" && switchProHidCount > 0) {
425
+ switchProHidCount--;
426
+ continue;
427
+ }
428
+ const lastActivityAt = this.pollGamepadActivity(pad);
429
+ slots.push({
430
+ id: `gp-${pad.index}`,
431
+ playerNumber: slots.length + 1,
432
+ source: "gamepad",
433
+ identity: {
434
+ ...baseId,
435
+ transport: "unknown",
436
+ source: "gamepad"
437
+ },
438
+ battery: { percent: 0, charging: false, full: false, known: false },
439
+ observedReportHz: null,
440
+ lastActivityAt
441
+ });
442
+ }
443
+ for (const idx of this.gamepadPrevBtnMask.keys()) {
444
+ if (!activePadIndices.has(idx)) {
445
+ this.gamepadPrevBtnMask.delete(idx);
446
+ this.gamepadLastActivity.delete(idx);
447
+ }
448
+ }
449
+ if (slots.length === 0) {
450
+ this.activeSlotId = null;
451
+ } else if (!this.activeSlotId || !slots.some((s) => s.id === this.activeSlotId)) {
452
+ this.activeSlotId = slots[0].id;
453
+ }
454
+ return slots;
455
+ }
456
+ getActiveSlotId() {
457
+ this.getConnectedControllers();
458
+ return this.activeSlotId;
459
+ }
460
+ setActiveSlot(slotId) {
461
+ const slots = this.getConnectedControllers();
462
+ if (!slots.some((s) => s.id === slotId)) return false;
463
+ if (this.activeSlotId !== slotId) {
464
+ this.activeSlotId = slotId;
465
+ this.emit({ type: "slots_changed", slotId });
466
+ }
467
+ return true;
468
+ }
469
+ getHidSessionForSlot(slotId) {
470
+ if (slotId !== void 0) {
471
+ const session2 = this.hidSessions.get(slotId);
472
+ return session2 && session2.device.opened ? session2 : null;
473
+ }
474
+ const slots = this.getConnectedControllers();
475
+ const targetId = this.activeSlotId ?? slots[0]?.id ?? null;
476
+ if (!targetId) return null;
477
+ const session = this.hidSessions.get(targetId);
478
+ return session && session.device.opened ? session : null;
479
+ }
480
+ getActiveHidSession() {
481
+ return this.getHidSessionForSlot();
482
+ }
483
+ getGamepadForSlot(slotId) {
484
+ if (!_DualSenseControllerManager.isGamepadSupported()) return null;
485
+ if (slotId !== void 0) {
486
+ if (!slotId.startsWith("gp-")) return null;
487
+ const idx = Number(slotId.slice(3));
488
+ const pad = navigator.getGamepads()[idx];
489
+ return pad && pad.connected ? pad : null;
490
+ }
491
+ const slots = this.getConnectedControllers();
492
+ const targetId = this.activeSlotId ?? slots[0]?.id ?? null;
493
+ if (targetId && targetId.startsWith("gp-")) {
494
+ const idx = Number(targetId.slice(3));
495
+ const pad = navigator.getGamepads()[idx];
496
+ if (pad && pad.connected) return pad;
497
+ }
498
+ if (targetId && targetId.startsWith("hid-")) {
499
+ return null;
500
+ }
501
+ for (const p of navigator.getGamepads()) {
502
+ if (p && p.connected) return p;
503
+ }
504
+ return null;
505
+ }
506
+ getActiveGamepad() {
507
+ return this.getGamepadForSlot();
508
+ }
509
+ getGamepadActuatorEffects(slotId) {
510
+ const pad = this.getGamepadForSlot(slotId);
511
+ const act = pad?.vibrationActuator;
512
+ if (!act) return [];
513
+ if (Array.isArray(act.effects) && act.effects.length > 0) return act.effects;
514
+ if (typeof act.playEffect === "function") return ["dual-rumble"];
515
+ return [];
516
+ }
517
+ hasTriggerRumbleSupport(slotId) {
518
+ return this.getGamepadActuatorEffects(slotId).includes("trigger-rumble");
519
+ }
520
+ hasDualRumbleSupport(slotId) {
521
+ const effects = this.getGamepadActuatorEffects(slotId);
522
+ return effects.includes("dual-rumble") || Boolean(this.getGamepadForSlot(slotId)?.vibrationActuator?.playEffect);
523
+ }
524
+ /**
525
+ * Opens the browser WebHID device picker to connect (or append) a DualSense / DualSense Edge
526
+ * or Nintendo Switch Pro controller. Existing connected controllers remain active and untouched.
527
+ */
528
+ async connect() {
529
+ if (!_DualSenseControllerManager.isWebHIDSupported()) {
530
+ throw new Error("WebHID requires a Chromium browser (Chrome or Edge on desktop).");
531
+ }
532
+ const devices = await navigator.hid.requestDevice({
533
+ filters: [
534
+ ...DUALSENSE_PIDS.map((productId) => ({ vendorId: SONY_VENDOR_ID, productId })),
535
+ ...SWITCH_PRO_PIDS.map((productId) => ({ vendorId: NINTENDO_VENDOR_ID, productId }))
536
+ ]
537
+ });
538
+ if (!devices.length) return false;
539
+ let attachedId = null;
540
+ for (const dev of devices) {
541
+ attachedId = await this.attachDevice(dev);
542
+ }
543
+ if (attachedId) {
544
+ this.activeSlotId = attachedId;
545
+ this.emit({ type: "slots_changed", slotId: attachedId });
546
+ }
547
+ return Boolean(attachedId);
548
+ }
549
+ /**
550
+ * Silently re-attaches all previously authorized DualSense & Switch Pro WebHID devices (zero browser prompts).
551
+ */
552
+ async reconnectAuthorized() {
553
+ if (!_DualSenseControllerManager.isWebHIDSupported()) return false;
554
+ const devices = await navigator.hid.getDevices();
555
+ const matches = devices.filter((d) => this.isSupportedHidDevice(d));
556
+ if (!matches.length) return false;
557
+ let attachedAny = false;
558
+ for (const dev of matches) {
559
+ try {
560
+ await this.attachDevice(dev);
561
+ attachedAny = true;
562
+ } catch {
563
+ }
564
+ }
565
+ return attachedAny;
566
+ }
567
+ async readFirmwareInfoSafe(device) {
568
+ try {
569
+ const view = await device.receiveFeatureReport(32);
570
+ if (view.byteLength < 44) return void 0;
571
+ const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
572
+ const offset = bytes[0] === 32 ? 1 : 0;
573
+ const decodeAscii = (start, len) => {
574
+ let s = "";
575
+ for (let i = start; i < start + len && i < bytes.length; i++) {
576
+ const ch = bytes[i];
577
+ if (ch >= 32 && ch <= 126) s += String.fromCharCode(ch);
578
+ }
579
+ return s.trim();
580
+ };
581
+ const buildDate = decodeAscii(offset + 0, 11);
582
+ const buildTime = decodeAscii(offset + 11, 8);
583
+ const dv = new DataView(view.buffer, view.byteOffset + offset);
584
+ const hwInfo = dv.byteLength >= 28 ? dv.getUint32(24, true) : 0;
585
+ const fwVersion = dv.byteLength >= 32 ? dv.getUint32(28, true) : 0;
586
+ if (!buildDate && !hwInfo) return void 0;
587
+ return {
588
+ buildDate: buildDate || "Unknown",
589
+ buildTime: buildTime || "",
590
+ hwInfoHex: `0x${hwInfo.toString(16).padStart(8, "0")}`,
591
+ fwVersionHex: `0x${fwVersion.toString(16).padStart(8, "0")}`
592
+ };
593
+ } catch {
594
+ return void 0;
595
+ }
596
+ }
597
+ async attachDevice(device) {
598
+ for (const existing of this.hidSessions.values()) {
599
+ if (existing.device === device && existing.device.opened) {
600
+ return existing.id;
601
+ }
602
+ }
603
+ if (!device.opened) await device.open();
604
+ const isSwitchPro = device.vendorId === NINTENDO_VENDOR_ID && SWITCH_PRO_PIDS.includes(device.productId);
605
+ if (isSwitchPro) {
606
+ return this.attachSwitchProDevice(device);
607
+ }
608
+ let hasUsb02 = false;
609
+ let hasBt31 = false;
610
+ let usbPayloadLength = 47;
611
+ let btPayloadLength = 77;
612
+ for (const col of device.collections || []) {
613
+ for (const rep of col.outputReports || []) {
614
+ const byteLen = Math.ceil(
615
+ (rep.items || []).reduce((acc, it) => acc + (it.reportSize || 0) * (it.reportCount || 0), 0) / 8
616
+ );
617
+ if (rep.reportId === 2) {
618
+ hasUsb02 = true;
619
+ if (byteLen >= 47) usbPayloadLength = byteLen;
620
+ }
621
+ if (rep.reportId === 49) {
622
+ hasBt31 = true;
623
+ if (byteLen >= 77) btPayloadLength = byteLen;
624
+ }
625
+ }
626
+ }
627
+ const transport = hasUsb02 ? "usb" : hasBt31 ? "bluetooth" : "usb";
628
+ const isEdge = device.productId === 3570;
629
+ const firmwareInfo = await this.readFirmwareInfoSafe(device);
630
+ const slotId = `hid-${this.nextHidSeq++}`;
631
+ const displayName = isEdge ? "DualSense Edge" : "PlayStation DualSense";
632
+ const input = createEmptyInput();
633
+ input.connected = true;
634
+ input.source = "webhid";
635
+ input.isDualSense = true;
636
+ input.deviceName = device.productName || displayName;
637
+ input.identity = {
638
+ brand: "sony",
639
+ model: isEdge ? "dualsense_edge" : "dualsense",
640
+ displayName,
641
+ rawId: device.productName || displayName,
642
+ vendorId: device.vendorId,
643
+ productId: device.productId,
644
+ transport,
645
+ source: "webhid",
646
+ firmwareInfo
647
+ };
648
+ const session = {
649
+ id: slotId,
650
+ kind: "dualsense",
651
+ device,
652
+ transport,
653
+ firmwareInfo,
654
+ usbPayloadLength,
655
+ btPayloadLength,
656
+ btSeq: 0,
657
+ switchSubcmdLength: 48,
658
+ switchRumbleLength: 9,
659
+ switchUsb80Length: 1,
660
+ switchPacketNum: 0,
661
+ switchCal: createDefaultSwitchCal(),
662
+ switchRumbleTimer: null,
663
+ switchSeqTimers: [],
664
+ reportTimes: [],
665
+ input,
666
+ outState: createDefaultOutState(this.hidSessions.size),
667
+ legacyTimer: null,
668
+ lastActivityAt: performance.now(),
669
+ prevBtnMask: 0,
670
+ boundInputReport: (e) => this.handleInputReport(session, e)
671
+ };
672
+ this.hidSessions.set(slotId, session);
673
+ if (!this.activeSlotId) {
674
+ this.activeSlotId = slotId;
675
+ }
676
+ this.getConnectedControllers();
677
+ device.addEventListener("inputreport", session.boundInputReport);
678
+ if (!this.hidDisconnectAttached && typeof navigator !== "undefined" && navigator.hid) {
679
+ navigator.hid.addEventListener("disconnect", this.boundDisconnect);
680
+ this.hidDisconnectAttached = true;
681
+ }
682
+ await this.flushSessionOutput(session, { includeAudioConfig: true, includeTriggers: true, includeLeds: true });
683
+ this.emit({
684
+ type: "connected",
685
+ slotId,
686
+ deviceName: input.deviceName,
687
+ productId: device.productId,
688
+ transport,
689
+ firmwareInfo
690
+ });
691
+ return slotId;
692
+ }
693
+ async attachSwitchProDevice(device) {
694
+ let hasUsb80 = false;
695
+ let switchSubcmdLength = 48;
696
+ let switchRumbleLength = 9;
697
+ let switchUsb80Length = 1;
698
+ for (const col of device.collections || []) {
699
+ for (const rep of col.outputReports || []) {
700
+ const byteLen = Math.ceil(
701
+ (rep.items || []).reduce((acc, it) => acc + (it.reportSize || 0) * (it.reportCount || 0), 0) / 8
702
+ );
703
+ if (rep.reportId === 128) {
704
+ hasUsb80 = true;
705
+ if (byteLen >= 1) switchUsb80Length = byteLen;
706
+ }
707
+ if (rep.reportId === 1 && byteLen >= 10) {
708
+ switchSubcmdLength = byteLen;
709
+ }
710
+ if (rep.reportId === 16 && byteLen >= 9) {
711
+ switchRumbleLength = byteLen;
712
+ }
713
+ }
714
+ }
715
+ const transport = hasUsb80 ? "usb" : "bluetooth";
716
+ const slotId = `hid-${this.nextHidSeq++}`;
717
+ const displayName = "Nintendo Switch Pro Controller";
718
+ const input = createEmptyInput();
719
+ input.connected = true;
720
+ input.source = "webhid";
721
+ input.isDualSense = false;
722
+ input.deviceName = device.productName || displayName;
723
+ input.identity = {
724
+ brand: "nintendo",
725
+ model: "switch_pro",
726
+ displayName,
727
+ rawId: device.productName || displayName,
728
+ vendorId: device.vendorId,
729
+ productId: device.productId,
730
+ transport,
731
+ source: "webhid"
732
+ };
733
+ const playerIndex = this.hidSessions.size;
734
+ const session = {
735
+ id: slotId,
736
+ kind: "switch_pro",
737
+ device,
738
+ transport,
739
+ firmwareInfo: void 0,
740
+ usbPayloadLength: 47,
741
+ btPayloadLength: 77,
742
+ btSeq: 0,
743
+ switchSubcmdLength,
744
+ switchRumbleLength,
745
+ switchUsb80Length,
746
+ switchPacketNum: 0,
747
+ switchCal: createDefaultSwitchCal(),
748
+ switchRumbleTimer: null,
749
+ switchSeqTimers: [],
750
+ reportTimes: [],
751
+ input,
752
+ outState: createDefaultOutState(playerIndex),
753
+ legacyTimer: null,
754
+ lastActivityAt: performance.now(),
755
+ prevBtnMask: 0,
756
+ boundInputReport: (e) => this.handleSwitchProInputReport(session, e)
757
+ };
758
+ this.hidSessions.set(slotId, session);
759
+ if (!this.activeSlotId) {
760
+ this.activeSlotId = slotId;
761
+ }
762
+ this.getConnectedControllers();
763
+ device.addEventListener("inputreport", session.boundInputReport);
764
+ if (!this.hidDisconnectAttached && typeof navigator !== "undefined" && navigator.hid) {
765
+ navigator.hid.addEventListener("disconnect", this.boundDisconnect);
766
+ this.hidDisconnectAttached = true;
767
+ }
768
+ await this.initSwitchProSession(session, playerIndex);
769
+ this.emit({
770
+ type: "connected",
771
+ slotId,
772
+ deviceName: input.deviceName,
773
+ productId: device.productId,
774
+ transport
775
+ });
776
+ return slotId;
777
+ }
778
+ async sendSwitchUsbCmd(session, cmd) {
779
+ if (!session.device.opened) return;
780
+ const payload = new Uint8Array(Math.max(1, session.switchUsb80Length));
781
+ payload[0] = cmd & 255;
782
+ await session.device.sendReport(128, payload);
783
+ }
784
+ async sendSwitchSubcommand(session, subcmd, args = []) {
785
+ if (!session.device.opened) return;
786
+ const len = Math.max(10 + args.length, session.switchSubcmdLength);
787
+ const payload = new Uint8Array(len);
788
+ payload[0] = session.switchPacketNum & 15;
789
+ session.switchPacketNum = session.switchPacketNum + 1 & 15;
790
+ payload.set(SWITCH_NEUTRAL_RUMBLE, 1);
791
+ payload.set(SWITCH_NEUTRAL_RUMBLE, 5);
792
+ payload[9] = subcmd & 255;
793
+ for (let i = 0; i < args.length; i++) {
794
+ payload[10 + i] = args[i] & 255;
795
+ }
796
+ await session.device.sendReport(1, payload);
797
+ }
798
+ async sendSwitchRumbleBytes(session, left4, right4) {
799
+ if (!session.device.opened) return false;
800
+ const len = Math.max(9, session.switchRumbleLength);
801
+ const payload = new Uint8Array(len);
802
+ payload[0] = session.switchPacketNum & 15;
803
+ session.switchPacketNum = session.switchPacketNum + 1 & 15;
804
+ payload.set(left4.subarray(0, 4), 1);
805
+ payload.set(right4.subarray(0, 4), 5);
806
+ await session.device.sendReport(16, payload);
807
+ return true;
808
+ }
809
+ clearSwitchRumbleTimers(session) {
810
+ if (session.switchRumbleTimer) {
811
+ clearTimeout(session.switchRumbleTimer);
812
+ session.switchRumbleTimer = null;
813
+ }
814
+ for (const t of session.switchSeqTimers) {
815
+ clearTimeout(t);
816
+ }
817
+ session.switchSeqTimers = [];
818
+ }
819
+ async initSwitchProSession(session, playerIndex) {
820
+ try {
821
+ if (session.transport === "usb") {
822
+ await this.sendSwitchUsbCmd(session, 2).catch(() => {
823
+ });
824
+ await sleepMs(25);
825
+ await this.sendSwitchUsbCmd(session, 4).catch(() => {
826
+ });
827
+ await sleepMs(25);
828
+ }
829
+ await this.sendSwitchSubcommand(session, 3, [48]);
830
+ await sleepMs(20);
831
+ await this.sendSwitchSubcommand(session, 64, [1]);
832
+ await sleepMs(20);
833
+ await this.sendSwitchSubcommand(session, 72, [1]);
834
+ await sleepMs(20);
835
+ await this.sendSwitchSubcommand(session, 48, [
836
+ SWITCH_PLAYER_LED_PATTERNS[playerIndex % SWITCH_PLAYER_LED_PATTERNS.length]
837
+ ]);
838
+ await sleepMs(20);
839
+ await this.sendSwitchSubcommand(session, 16, [61, 96, 0, 0, 18]).catch(() => {
840
+ });
841
+ } catch {
842
+ }
843
+ }
844
+ parseSwitchStickCalibration(session, data) {
845
+ if (data.byteLength < 37) return;
846
+ if (data.getUint8(13) !== 16) return;
847
+ const addr = data.getUint32(14, true);
848
+ if (addr !== 24637) return;
849
+ const u12Pair = (o) => {
850
+ const b0 = data.getUint8(o);
851
+ const b1 = data.getUint8(o + 1);
852
+ const b2 = data.getUint8(o + 2);
853
+ return [b0 | (b1 & 15) << 8, b1 >> 4 & 15 | b2 << 4];
854
+ };
855
+ const [lxMax, lyMax] = u12Pair(19);
856
+ const [lxCtr, lyCtr] = u12Pair(22);
857
+ const [lxMin, lyMin] = u12Pair(25);
858
+ const [rxCtr, ryCtr] = u12Pair(28);
859
+ const [rxMin, ryMin] = u12Pair(31);
860
+ const [rxMax, ryMax] = u12Pair(34);
861
+ const validAxis = (center, minD, maxD) => center >= 900 && center <= 3200 && minD >= 400 && minD <= 2400 && maxD >= 400 && maxD <= 2400;
862
+ if (validAxis(lxCtr, lxMin, lxMax) && validAxis(lyCtr, lyMin, lyMax)) {
863
+ session.switchCal.lx = { center: lxCtr, minDelta: lxMin, maxDelta: lxMax };
864
+ session.switchCal.ly = { center: lyCtr, minDelta: lyMin, maxDelta: lyMax };
865
+ }
866
+ if (validAxis(rxCtr, rxMin, rxMax) && validAxis(ryCtr, ryMin, ryMax)) {
867
+ session.switchCal.rx = { center: rxCtr, minDelta: rxMin, maxDelta: rxMax };
868
+ session.switchCal.ry = { center: ryCtr, minDelta: ryMin, maxDelta: ryMax };
869
+ }
870
+ }
871
+ handleSwitchProInputReport(session, event) {
872
+ const { reportId, data } = event;
873
+ if (reportId === 33) {
874
+ this.parseSwitchStickCalibration(session, data);
875
+ }
876
+ if (reportId !== 48 && reportId !== 33 || data.byteLength < 11) {
877
+ return;
878
+ }
879
+ const input = session.input;
880
+ const now = performance.now();
881
+ if (reportId === 48) {
882
+ session.reportTimes.push(now);
883
+ if (session.reportTimes.length > 33) session.reportTimes.shift();
884
+ if (session.reportTimes.length >= 6) {
885
+ const spanMs = session.reportTimes[session.reportTimes.length - 1] - session.reportTimes[0];
886
+ if (spanMs > 10) {
887
+ input.observedReportHz = Math.round((session.reportTimes.length - 1) * 1e3 / spanMs);
888
+ }
889
+ }
890
+ }
891
+ const battByte = data.getUint8(1);
892
+ const bars = Math.min(4, battByte >> 5 & 7);
893
+ input.battery.percent = bars * 25;
894
+ input.battery.charging = Boolean(battByte & 16);
895
+ input.battery.full = bars >= 4;
896
+ input.battery.known = true;
897
+ const bRight = data.getUint8(2);
898
+ const bShared = data.getUint8(3);
899
+ const bLeft = data.getUint8(4);
900
+ input.buttons.square = Boolean(bRight & 1);
901
+ input.buttons.triangle = Boolean(bRight & 2);
902
+ input.buttons.cross = Boolean(bRight & 4);
903
+ input.buttons.circle = Boolean(bRight & 8);
904
+ input.buttons.r1 = Boolean(bRight & 64);
905
+ input.buttons.r2Btn = Boolean(bRight & 128);
906
+ input.buttons.create = Boolean(bShared & 1);
907
+ input.buttons.options = Boolean(bShared & 2);
908
+ input.buttons.r3 = Boolean(bShared & 4);
909
+ input.buttons.l3 = Boolean(bShared & 8);
910
+ input.buttons.ps = Boolean(bShared & 16);
911
+ input.buttons.touchpadClick = Boolean(bShared & 32);
912
+ input.buttons.down = Boolean(bLeft & 1);
913
+ input.buttons.up = Boolean(bLeft & 2);
914
+ input.buttons.right = Boolean(bLeft & 4);
915
+ input.buttons.left = Boolean(bLeft & 8);
916
+ input.buttons.l1 = Boolean(bLeft & 64);
917
+ input.buttons.l2Btn = Boolean(bLeft & 128);
918
+ input.l2 = input.buttons.l2Btn ? 1 : 0;
919
+ input.r2 = input.buttons.r2Btn ? 1 : 0;
920
+ const btnMask = bRight & 207 | (bShared & 63) << 8 | (bLeft & 207) << 16;
921
+ if ((btnMask & ~session.prevBtnMask) !== 0) {
922
+ session.lastActivityAt = now;
923
+ }
924
+ session.prevBtnMask = btnMask;
925
+ const normAxis = (raw, cal) => {
926
+ const diff = raw - cal.center;
927
+ const denom = diff >= 0 ? cal.maxDelta : cal.minDelta;
928
+ const v = denom > 0 ? diff / denom : 0;
929
+ return Math.max(-1, Math.min(1, v));
930
+ };
931
+ const lxRaw = data.getUint8(5) | (data.getUint8(6) & 15) << 8;
932
+ const lyRaw = data.getUint8(6) >> 4 & 15 | data.getUint8(7) << 4;
933
+ const rxRaw = data.getUint8(8) | (data.getUint8(9) & 15) << 8;
934
+ const ryRaw = data.getUint8(9) >> 4 & 15 | data.getUint8(10) << 4;
935
+ input.lx = normAxis(lxRaw, session.switchCal.lx);
936
+ input.ly = -normAxis(lyRaw, session.switchCal.ly);
937
+ input.rx = normAxis(rxRaw, session.switchCal.rx);
938
+ input.ry = -normAxis(ryRaw, session.switchCal.ry);
939
+ if (reportId === 48 && data.byteLength >= 48) {
940
+ let sumAx = 0;
941
+ let sumAy = 0;
942
+ let sumAz = 0;
943
+ let sumGx = 0;
944
+ let sumGy = 0;
945
+ let sumGz = 0;
946
+ for (let s = 0; s < 3; s++) {
947
+ const base = 12 + s * 12;
948
+ sumAx += data.getInt16(base + 0, true);
949
+ sumAy += data.getInt16(base + 2, true);
950
+ sumAz += data.getInt16(base + 4, true);
951
+ sumGx += data.getInt16(base + 6, true);
952
+ sumGy += data.getInt16(base + 8, true);
953
+ sumGz += data.getInt16(base + 10, true);
954
+ }
955
+ const avgAx = sumAx / 3;
956
+ const avgAy = sumAy / 3;
957
+ const avgAz = sumAz / 3;
958
+ const avgGx = sumGx / 3;
959
+ const avgGy = sumGy / 3;
960
+ const avgGz = sumGz / 3;
961
+ const clamp1 = (v) => Math.max(-1, Math.min(1, v));
962
+ input.accel.x = clamp1(avgAy / 4096);
963
+ input.accel.y = clamp1(avgAz / 4096);
964
+ input.accel.z = clamp1(-avgAx / 4096);
965
+ input.gyro.x = clamp1(avgGy / 8192);
966
+ input.gyro.y = clamp1(avgGz / 8192);
967
+ input.gyro.z = clamp1(avgGx / 8192);
968
+ }
969
+ }
970
+ /**
971
+ * Disconnects a specific WebHID controller slot, or the active WebHID slot when `slotId` is omitted.
972
+ */
973
+ async disconnect(slotId) {
974
+ const targetId = slotId ?? this.activeSlotId ?? Array.from(this.hidSessions.keys())[0];
975
+ if (!targetId) return;
976
+ const session = this.hidSessions.get(targetId);
977
+ if (!session) return;
978
+ if (session.legacyTimer) {
979
+ clearTimeout(session.legacyTimer);
980
+ session.legacyTimer = null;
981
+ }
982
+ this.clearSwitchRumbleTimers(session);
983
+ try {
984
+ if (session.kind === "switch_pro") {
985
+ await this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE);
986
+ } else {
987
+ session.outState.leftTrigger = encodeTriggerEffect({ type: "off" });
988
+ session.outState.rightTrigger = encodeTriggerEffect({ type: "off" });
989
+ session.outState.legacyRumbleActive = false;
990
+ session.outState.legacyLeft = 0;
991
+ session.outState.legacyRight = 0;
992
+ await this.flushSessionOutput(session, { includeTriggers: true });
993
+ }
994
+ } catch {
995
+ }
996
+ session.device.removeEventListener("inputreport", session.boundInputReport);
997
+ try {
998
+ if (session.device.opened) await session.device.close();
999
+ } catch {
1000
+ }
1001
+ this.hidSessions.delete(targetId);
1002
+ if (this.hidSessions.size === 0 && this.hidDisconnectAttached && typeof navigator !== "undefined" && navigator.hid) {
1003
+ navigator.hid.removeEventListener("disconnect", this.boundDisconnect);
1004
+ this.hidDisconnectAttached = false;
1005
+ }
1006
+ if (this.activeSlotId === targetId) {
1007
+ const remaining = this.getConnectedControllers();
1008
+ this.activeSlotId = remaining[0]?.id ?? null;
1009
+ }
1010
+ this.emit({ type: "disconnected", slotId: targetId });
1011
+ }
1012
+ async disconnectAll() {
1013
+ const ids = Array.from(this.hidSessions.keys());
1014
+ for (const id of ids) {
1015
+ await this.disconnect(id);
1016
+ }
1017
+ }
1018
+ handleDisconnect(e) {
1019
+ for (const [slotId, session] of this.hidSessions.entries()) {
1020
+ if (session.device === e.device) {
1021
+ if (session.legacyTimer) {
1022
+ clearTimeout(session.legacyTimer);
1023
+ session.legacyTimer = null;
1024
+ }
1025
+ this.clearSwitchRumbleTimers(session);
1026
+ session.device.removeEventListener("inputreport", session.boundInputReport);
1027
+ this.hidSessions.delete(slotId);
1028
+ if (this.activeSlotId === slotId) {
1029
+ const remaining = this.getConnectedControllers();
1030
+ this.activeSlotId = remaining[0]?.id ?? null;
1031
+ }
1032
+ this.emit({ type: "disconnected", slotId });
1033
+ }
1034
+ }
1035
+ if (this.hidSessions.size === 0 && this.hidDisconnectAttached && typeof navigator !== "undefined" && navigator.hid) {
1036
+ navigator.hid.removeEventListener("disconnect", this.boundDisconnect);
1037
+ this.hidDisconnectAttached = false;
1038
+ }
1039
+ }
1040
+ handleInputReport(session, event) {
1041
+ const { reportId, data } = event;
1042
+ let offset = 0;
1043
+ if (reportId === 49 && data.byteLength >= 40) {
1044
+ offset = 1;
1045
+ } else if (reportId !== 1 || data.byteLength < 10) {
1046
+ return;
1047
+ }
1048
+ const input = session.input;
1049
+ const now = performance.now();
1050
+ session.reportTimes.push(now);
1051
+ if (session.reportTimes.length > 33) session.reportTimes.shift();
1052
+ if (session.reportTimes.length >= 6) {
1053
+ const spanMs = session.reportTimes[session.reportTimes.length - 1] - session.reportTimes[0];
1054
+ if (spanMs > 10) {
1055
+ input.observedReportHz = Math.round((session.reportTimes.length - 1) * 1e3 / spanMs);
1056
+ }
1057
+ }
1058
+ const normRaw = (v) => {
1059
+ const n = v >= 128 ? (v - 128) / 127 : (v - 128) / 128;
1060
+ return Math.max(-1, Math.min(1, n));
1061
+ };
1062
+ input.lx = normRaw(data.getUint8(offset + 0));
1063
+ input.ly = normRaw(data.getUint8(offset + 1));
1064
+ input.rx = normRaw(data.getUint8(offset + 2));
1065
+ input.ry = normRaw(data.getUint8(offset + 3));
1066
+ input.l2 = data.getUint8(offset + 4) / 255;
1067
+ input.r2 = data.getUint8(offset + 5) / 255;
1068
+ const btn0 = data.getUint8(offset + 7);
1069
+ const btn1 = data.getUint8(offset + 8);
1070
+ const btn2 = data.getUint8(offset + 9);
1071
+ const dpad = btn0 & 15;
1072
+ input.buttons.up = dpad === 0 || dpad === 1 || dpad === 7;
1073
+ input.buttons.right = dpad === 1 || dpad === 2 || dpad === 3;
1074
+ input.buttons.down = dpad === 3 || dpad === 4 || dpad === 5;
1075
+ input.buttons.left = dpad === 5 || dpad === 6 || dpad === 7;
1076
+ input.buttons.square = Boolean(btn0 & 16);
1077
+ input.buttons.cross = Boolean(btn0 & 32);
1078
+ input.buttons.circle = Boolean(btn0 & 64);
1079
+ input.buttons.triangle = Boolean(btn0 & 128);
1080
+ input.buttons.l1 = Boolean(btn1 & 1);
1081
+ input.buttons.r1 = Boolean(btn1 & 2);
1082
+ input.buttons.l2Btn = Boolean(btn1 & 4);
1083
+ input.buttons.r2Btn = Boolean(btn1 & 8);
1084
+ input.buttons.create = Boolean(btn1 & 16);
1085
+ input.buttons.options = Boolean(btn1 & 32);
1086
+ input.buttons.l3 = Boolean(btn1 & 64);
1087
+ input.buttons.r3 = Boolean(btn1 & 128);
1088
+ input.buttons.ps = Boolean(btn2 & 1);
1089
+ input.buttons.touchpadClick = Boolean(btn2 & 2);
1090
+ const btnMask = btn0 & 240 | (dpad < 8 ? 1 : 0) | btn1 << 8 | (btn2 & 3) << 16;
1091
+ if ((btnMask & ~session.prevBtnMask) !== 0) {
1092
+ session.lastActivityAt = now;
1093
+ }
1094
+ session.prevBtnMask = btnMask;
1095
+ if (data.byteLength > offset + 26) {
1096
+ input.gyro.x = Math.max(-1, Math.min(1, data.getInt16(offset + 15, true) / 16384));
1097
+ input.gyro.y = Math.max(-1, Math.min(1, data.getInt16(offset + 17, true) / 16384));
1098
+ input.gyro.z = Math.max(-1, Math.min(1, data.getInt16(offset + 19, true) / 16384));
1099
+ input.accel.x = Math.max(-1, Math.min(1, data.getInt16(offset + 21, true) / 8192));
1100
+ input.accel.y = Math.max(-1, Math.min(1, data.getInt16(offset + 23, true) / 8192));
1101
+ input.accel.z = Math.max(-1, Math.min(1, data.getInt16(offset + 25, true) / 8192));
1102
+ }
1103
+ const parseFinger = (base, target) => {
1104
+ if (data.byteLength <= base + 3) return;
1105
+ const contact = data.getUint8(base);
1106
+ const touching = (contact & 128) === 0;
1107
+ target.active = touching;
1108
+ if (touching) {
1109
+ const b0 = data.getUint8(base + 1);
1110
+ const b1 = data.getUint8(base + 2);
1111
+ const b2 = data.getUint8(base + 3);
1112
+ const tx = b0 | (b1 & 15) << 8;
1113
+ const ty = (b1 & 240) >> 4 | b2 << 4;
1114
+ target.x = Math.max(0, Math.min(1, tx / 1919));
1115
+ target.y = Math.max(0, Math.min(1, ty / 1079));
1116
+ }
1117
+ };
1118
+ parseFinger(offset + 32, input.touch);
1119
+ parseFinger(offset + 36, input.touch2);
1120
+ if (data.byteLength > offset + 52) {
1121
+ const battByte = data.getUint8(offset + 52);
1122
+ const level = battByte & 15;
1123
+ const state = battByte >> 4 & 15;
1124
+ input.battery.percent = Math.min(100, Math.round((level + 0.5) / 10 * 100));
1125
+ input.battery.charging = state === 1;
1126
+ input.battery.full = state === 2;
1127
+ input.battery.known = true;
1128
+ }
1129
+ }
1130
+ populateGamepadInput(pad, out) {
1131
+ const clamp = (v) => Math.max(-1, Math.min(1, Number.isFinite(v) ? v : 0));
1132
+ const baseId = identifyGamepadFromId(pad.id || "");
1133
+ out.connected = true;
1134
+ out.source = "gamepad";
1135
+ out.deviceName = baseId.displayName;
1136
+ out.isDualSense = baseId.model === "dualsense" || baseId.model === "dualsense_edge";
1137
+ out.identity = {
1138
+ ...baseId,
1139
+ transport: "unknown",
1140
+ source: "gamepad"
1141
+ };
1142
+ out.lx = clamp(pad.axes[0] ?? 0);
1143
+ out.ly = clamp(pad.axes[1] ?? 0);
1144
+ out.rx = clamp(pad.axes[2] ?? 0);
1145
+ out.ry = clamp(pad.axes[3] ?? 0);
1146
+ out.l2 = Math.max(0, Math.min(1, pad.buttons[6]?.value ?? 0));
1147
+ out.r2 = Math.max(0, Math.min(1, pad.buttons[7]?.value ?? 0));
1148
+ out.buttons.cross = Boolean(pad.buttons[0]?.pressed);
1149
+ out.buttons.circle = Boolean(pad.buttons[1]?.pressed);
1150
+ out.buttons.square = Boolean(pad.buttons[2]?.pressed);
1151
+ out.buttons.triangle = Boolean(pad.buttons[3]?.pressed);
1152
+ out.buttons.l1 = Boolean(pad.buttons[4]?.pressed);
1153
+ out.buttons.r1 = Boolean(pad.buttons[5]?.pressed);
1154
+ out.buttons.l2Btn = Boolean(pad.buttons[6]?.pressed);
1155
+ out.buttons.r2Btn = Boolean(pad.buttons[7]?.pressed);
1156
+ out.buttons.create = Boolean(pad.buttons[8]?.pressed);
1157
+ out.buttons.options = Boolean(pad.buttons[9]?.pressed);
1158
+ out.buttons.l3 = Boolean(pad.buttons[10]?.pressed);
1159
+ out.buttons.r3 = Boolean(pad.buttons[11]?.pressed);
1160
+ out.buttons.up = Boolean(pad.buttons[12]?.pressed);
1161
+ out.buttons.down = Boolean(pad.buttons[13]?.pressed);
1162
+ out.buttons.left = Boolean(pad.buttons[14]?.pressed);
1163
+ out.buttons.right = Boolean(pad.buttons[15]?.pressed);
1164
+ out.buttons.ps = Boolean(pad.buttons[16]?.pressed);
1165
+ out.buttons.touchpadClick = Boolean(pad.buttons[17]?.pressed);
1166
+ out.touch.active = false;
1167
+ out.touch2.active = false;
1168
+ out.battery.known = false;
1169
+ out.observedReportHz = null;
1170
+ return out;
1171
+ }
1172
+ /**
1173
+ * Returns a live input snapshot for a specific controller slot (e.g. `hid-1` or `gp-0`).
1174
+ * Returns a disconnected empty snapshot when that slot is not currently connected.
1175
+ */
1176
+ getInputStateForSlot(slotId) {
1177
+ const hidSession = this.getHidSessionForSlot(slotId);
1178
+ if (hidSession) return hidSession.input;
1179
+ const pad = this.getGamepadForSlot(slotId);
1180
+ if (pad) {
1181
+ let buf = this.gamepadInputs.get(pad.index);
1182
+ if (!buf) {
1183
+ buf = createEmptyInput();
1184
+ this.gamepadInputs.set(pad.index, buf);
1185
+ }
1186
+ return this.populateGamepadInput(pad, buf);
1187
+ }
1188
+ return createEmptyInput();
1189
+ }
1190
+ getInputState(slotId) {
1191
+ if (slotId !== void 0) {
1192
+ return this.getInputStateForSlot(slotId);
1193
+ }
1194
+ const activeHid = this.getActiveHidSession();
1195
+ if (activeHid) {
1196
+ return activeHid.input;
1197
+ }
1198
+ const pad = this.getActiveGamepad();
1199
+ if (pad) {
1200
+ return this.populateGamepadInput(pad, this.fallbackInput);
1201
+ }
1202
+ const k = this.keysDown;
1203
+ const lx = (k.has("KeyD") || k.has("ArrowRight") ? 1 : 0) - (k.has("KeyA") || k.has("ArrowLeft") ? 1 : 0);
1204
+ const ly = (k.has("KeyS") || k.has("ArrowDown") ? 1 : 0) - (k.has("KeyW") || k.has("ArrowUp") ? 1 : 0);
1205
+ const out = this.fallbackInput;
1206
+ out.connected = false;
1207
+ out.source = "keyboard_mouse";
1208
+ out.deviceName = "Keyboard & Mouse";
1209
+ out.isDualSense = false;
1210
+ out.identity = {
1211
+ brand: "none",
1212
+ model: "none",
1213
+ displayName: "Keyboard & Mouse",
1214
+ rawId: "",
1215
+ transport: "disconnected",
1216
+ source: "keyboard_mouse"
1217
+ };
1218
+ out.lx = lx;
1219
+ out.ly = ly;
1220
+ out.rx = 0;
1221
+ out.ry = 0;
1222
+ out.l2 = k.has("ShiftLeft") || k.has("KeyQ") ? 1 : 0;
1223
+ out.r2 = k.has("Space") || k.has("KeyE") ? 1 : 0;
1224
+ out.buttons.cross = k.has("Space") || k.has("Enter");
1225
+ out.buttons.circle = k.has("KeyC") || k.has("Escape");
1226
+ out.buttons.square = k.has("KeyR");
1227
+ out.buttons.triangle = k.has("KeyF");
1228
+ out.buttons.l1 = k.has("KeyQ");
1229
+ out.buttons.r1 = k.has("KeyE");
1230
+ out.buttons.l2Btn = out.l2 > 0.5;
1231
+ out.buttons.r2Btn = out.r2 > 0.5;
1232
+ out.buttons.l3 = false;
1233
+ out.buttons.r3 = false;
1234
+ out.buttons.up = k.has("ArrowUp") || k.has("KeyW");
1235
+ out.buttons.down = k.has("ArrowDown") || k.has("KeyS");
1236
+ out.buttons.left = k.has("ArrowLeft") || k.has("KeyA");
1237
+ out.buttons.right = k.has("ArrowRight") || k.has("KeyD");
1238
+ out.buttons.create = false;
1239
+ out.buttons.options = false;
1240
+ out.buttons.ps = false;
1241
+ out.buttons.touchpadClick = false;
1242
+ out.touch.active = false;
1243
+ out.touch2.active = false;
1244
+ out.battery.known = false;
1245
+ out.observedReportHz = null;
1246
+ return out;
1247
+ }
1248
+ /**
1249
+ * Computes a real-time capability matrix for the active controller slot (or a specific `slotId`).
1250
+ */
1251
+ getCapabilityMatrixForSlot(slotId, opts = {}) {
1252
+ const state = this.getInputState(slotId);
1253
+ const id = state.identity;
1254
+ const activeHid = this.getHidSessionForSlot(slotId);
1255
+ const isDsHid = activeHid?.kind === "dualsense";
1256
+ const isSwitchProHid = activeHid?.kind === "switch_pro";
1257
+ const isHid = Boolean(activeHid);
1258
+ const activeTransport = activeHid?.transport ?? "unknown";
1259
+ const hasWebHid = _DualSenseControllerManager.isWebHIDSupported();
1260
+ const isDS = id.model === "dualsense" || id.model === "dualsense_edge";
1261
+ const isXbox = id.brand === "xbox";
1262
+ const isSwitchPro = id.model === "switch_pro";
1263
+ const isNintendo = id.brand === "nintendo";
1264
+ const connected = state.connected;
1265
+ const hasTrigRumble = this.hasTriggerRumbleSupport(slotId);
1266
+ const hasDualRumble = this.hasDualRumbleSupport(slotId);
1267
+ if (!connected) {
1268
+ const disc = { inherent: false, availability: "disconnected" };
1269
+ return {
1270
+ standard_input: disc,
1271
+ analog_triggers: disc,
1272
+ dual_motor_rumble: disc,
1273
+ impulse_triggers: disc,
1274
+ hd_rumble: disc,
1275
+ adaptive_triggers: disc,
1276
+ audio_haptics: disc,
1277
+ controller_speaker: disc,
1278
+ gyro: disc,
1279
+ accelerometer: disc,
1280
+ touchpad: disc,
1281
+ lightbar: disc,
1282
+ battery: disc
1283
+ };
1284
+ }
1285
+ return {
1286
+ standard_input: { inherent: true, availability: "ready" },
1287
+ analog_triggers: {
1288
+ inherent: !isNintendo,
1289
+ availability: isNintendo ? "unsupported" : "ready",
1290
+ reason: isNintendo ? "Nintendo Pro/Joy-Con triggers are digital buttons" : void 0
1291
+ },
1292
+ dual_motor_rumble: {
1293
+ inherent: true,
1294
+ availability: isHid ? "ready" : hasDualRumble ? "ready" : "unsupported",
1295
+ reason: !isHid && !hasDualRumble ? "Browser Gamepad rumble actuator not exposed" : void 0
1296
+ },
1297
+ impulse_triggers: {
1298
+ inherent: isXbox,
1299
+ availability: isXbox ? hasTrigRumble ? "ready" : "unsupported" : "unsupported",
1300
+ reason: isXbox && !hasTrigRumble ? "Requires Chrome/Edge 126+ with USB or Xbox Wireless Adapter (Windows Bluetooth often blocks trigger motors)" : void 0
1301
+ },
1302
+ hd_rumble: {
1303
+ inherent: isNintendo,
1304
+ availability: !isNintendo ? "unsupported" : isSwitchProHid ? "ready" : isSwitchPro ? hasWebHid ? "permission_required" : "unsupported" : "bridge_required",
1305
+ reason: isSwitchPro && !isSwitchProHid ? hasWebHid ? "Connect Switch Pro via WebHID to unlock dual-band HD Rumble and 6-axis gyro" : "WebHID requires desktop Chrome or Edge" : void 0
1306
+ },
1307
+ adaptive_triggers: {
1308
+ inherent: isDS,
1309
+ availability: !isDS ? "unsupported" : isDsHid ? "ready" : hasWebHid ? "permission_required" : "unsupported",
1310
+ reason: isDS && !isDsHid ? hasWebHid ? "Click Unlock DualSense WebHID (works over USB & Bluetooth)" : "WebHID requires desktop Chrome or Edge" : void 0
1311
+ },
1312
+ audio_haptics: {
1313
+ inherent: isDS,
1314
+ availability: !isDS ? "unsupported" : opts.has4ChAudio ? "ready" : activeTransport === "bluetooth" ? "configuration_required" : "bridge_required",
1315
+ reason: isDS && !opts.has4ChAudio ? activeTransport === "bluetooth" ? "4-channel audio haptics require a wired USB-C connection on Windows" : "Optional Gamepadly Link or USB 4ch audio routing required" : void 0
1316
+ },
1317
+ controller_speaker: {
1318
+ inherent: isDS,
1319
+ availability: !isDS ? "unsupported" : opts.hasControllerSpeaker ? "ready" : activeTransport === "bluetooth" ? "configuration_required" : "bridge_required",
1320
+ reason: isDS && !opts.hasControllerSpeaker ? "Requires wired USB-C DualSense audio output" : void 0
1321
+ },
1322
+ gyro: {
1323
+ inherent: isDS || isNintendo,
1324
+ availability: isDS ? isDsHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : isSwitchPro ? isSwitchProHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : isNintendo ? "bridge_required" : "unsupported"
1325
+ },
1326
+ accelerometer: {
1327
+ inherent: isDS || isNintendo,
1328
+ availability: isDS ? isDsHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : isSwitchPro ? isSwitchProHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : isNintendo ? "bridge_required" : "unsupported"
1329
+ },
1330
+ touchpad: {
1331
+ inherent: isDS || id.model === "dualshock4",
1332
+ availability: isDS ? isDsHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : "unsupported"
1333
+ },
1334
+ lightbar: {
1335
+ inherent: isDS || id.model === "dualshock4",
1336
+ availability: isDS ? isDsHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : "unsupported"
1337
+ },
1338
+ battery: {
1339
+ inherent: true,
1340
+ availability: isDS && isDsHid || isSwitchPro && isSwitchProHid ? "ready" : "unknown"
1341
+ }
1342
+ };
1343
+ }
1344
+ getCapabilityMatrix(opts = {}) {
1345
+ return this.getCapabilityMatrixForSlot(void 0, opts);
1346
+ }
1347
+ /**
1348
+ * Drives Nintendo Switch Pro dual-band HD Rumble (LRA) over WebHID Report 0x10.
1349
+ * Automatically returns both motors to neutral off after `durationMs`.
1350
+ */
1351
+ async playSwitchHdRumble(spec, slotId) {
1352
+ const session = this.getHidSessionForSlot(slotId);
1353
+ if (!session || session.kind !== "switch_pro" || !session.device.opened) return false;
1354
+ this.clearSwitchRumbleTimers(session);
1355
+ const left4 = encodeSwitchHdRumbleSide(spec.left);
1356
+ const right4 = encodeSwitchHdRumbleSide(spec.right);
1357
+ const dur = Math.max(30, Math.min(2500, Math.round(spec.durationMs ?? 220)));
1358
+ try {
1359
+ await this.sendSwitchRumbleBytes(session, left4, right4);
1360
+ } catch {
1361
+ return false;
1362
+ }
1363
+ session.switchRumbleTimer = setTimeout(() => {
1364
+ session.switchRumbleTimer = null;
1365
+ void this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE).catch(() => {
1366
+ });
1367
+ }, dur);
1368
+ return true;
1369
+ }
1370
+ /**
1371
+ * Plays a timed sequence of Switch Pro HD Rumble steps (e.g., ice-cube sweep or L/R stereo pulse).
1372
+ */
1373
+ async playSwitchHdRumbleSequence(steps, slotId) {
1374
+ const session = this.getHidSessionForSlot(slotId);
1375
+ if (!session || session.kind !== "switch_pro" || !session.device.opened || steps.length === 0) {
1376
+ return false;
1377
+ }
1378
+ this.clearSwitchRumbleTimers(session);
1379
+ let maxEndMs = 0;
1380
+ for (const step of steps) {
1381
+ const startAt = Math.max(0, Math.round(step.delayMs));
1382
+ const dur = Math.max(30, Math.min(1200, Math.round(step.durationMs ?? 80)));
1383
+ if (startAt + dur > maxEndMs) maxEndMs = startAt + dur;
1384
+ const left4 = encodeSwitchHdRumbleSide(step.left);
1385
+ const right4 = encodeSwitchHdRumbleSide(step.right);
1386
+ if (startAt === 0) {
1387
+ await this.sendSwitchRumbleBytes(session, left4, right4).catch(() => {
1388
+ });
1389
+ } else {
1390
+ const t = setTimeout(() => {
1391
+ void this.sendSwitchRumbleBytes(session, left4, right4).catch(() => {
1392
+ });
1393
+ }, startAt);
1394
+ session.switchSeqTimers.push(t);
1395
+ }
1396
+ }
1397
+ session.switchRumbleTimer = setTimeout(() => {
1398
+ session.switchRumbleTimer = null;
1399
+ session.switchSeqTimers = [];
1400
+ void this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE).catch(() => {
1401
+ });
1402
+ }, maxEndMs + 15);
1403
+ return true;
1404
+ }
1405
+ stopSwitchHdRumble(slotId) {
1406
+ if (slotId !== void 0) {
1407
+ const session = this.getHidSessionForSlot(slotId);
1408
+ if (session && session.kind === "switch_pro" && session.device.opened) {
1409
+ this.clearSwitchRumbleTimers(session);
1410
+ void this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE).catch(() => {
1411
+ });
1412
+ }
1413
+ return;
1414
+ }
1415
+ for (const session of this.hidSessions.values()) {
1416
+ if (session.kind !== "switch_pro" || !session.device.opened) continue;
1417
+ this.clearSwitchRumbleTimers(session);
1418
+ void this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE).catch(() => {
1419
+ });
1420
+ }
1421
+ }
1422
+ /**
1423
+ * Native Xbox Series Impulse Triggers (Chrome/Edge 126+, zero WebHID / zero install).
1424
+ * Automatically maps to HD Rumble when the targeted slot is a WebHID Switch Pro.
1425
+ */
1426
+ async playTriggerRumble(leftTrigger, rightTrigger, durationMs, weakMagnitude = 0, strongMagnitude = 0, slotId) {
1427
+ const activeHid = this.getHidSessionForSlot(slotId);
1428
+ if (activeHid?.kind === "switch_pro") {
1429
+ const lAmp = Math.max(leftTrigger, strongMagnitude);
1430
+ const rAmp = Math.max(rightTrigger, weakMagnitude);
1431
+ return this.playSwitchHdRumble(
1432
+ {
1433
+ left: lAmp > 0.02 ? { highFreqHz: 260, highAmp: lAmp * 0.65, lowFreqHz: 145, lowAmp: lAmp * 0.7 } : void 0,
1434
+ right: rAmp > 0.02 ? { highFreqHz: 340, highAmp: rAmp * 0.7, lowFreqHz: 170, lowAmp: rAmp * 0.55 } : void 0,
1435
+ durationMs
1436
+ },
1437
+ slotId
1438
+ );
1439
+ }
1440
+ const pad = this.getGamepadForSlot(slotId);
1441
+ const act = pad?.vibrationActuator;
1442
+ if (!act?.playEffect) return false;
1443
+ const dur = Math.max(20, Math.min(2500, Math.round(durationMs)));
1444
+ const lt = Math.max(0, Math.min(1, leftTrigger));
1445
+ const rt = Math.max(0, Math.min(1, rightTrigger));
1446
+ const weak = Math.max(0, Math.min(1, weakMagnitude));
1447
+ const strong = Math.max(0, Math.min(1, strongMagnitude));
1448
+ if (this.hasTriggerRumbleSupport(slotId)) {
1449
+ try {
1450
+ await act.playEffect("trigger-rumble", {
1451
+ startDelay: 0,
1452
+ duration: dur,
1453
+ leftTrigger: lt,
1454
+ rightTrigger: rt,
1455
+ weakMagnitude: weak,
1456
+ strongMagnitude: strong
1457
+ });
1458
+ return true;
1459
+ } catch {
1460
+ }
1461
+ }
1462
+ const fallbackWeak = Math.max(weak, rt * 0.65);
1463
+ const fallbackStrong = Math.max(strong, lt * 0.65);
1464
+ if (fallbackWeak > 0 || fallbackStrong > 0) {
1465
+ return this.playDualRumble(fallbackWeak, fallbackStrong, dur, slotId);
1466
+ }
1467
+ return false;
1468
+ }
1469
+ /**
1470
+ * Standard Gamepad API dual-rumble for Xbox / Switch / Generic controllers.
1471
+ * Automatically uses true HD Rumble when the targeted slot is a WebHID Switch Pro.
1472
+ */
1473
+ async playDualRumble(weakMagnitude, strongMagnitude, durationMs, slotId) {
1474
+ const activeHid = this.getHidSessionForSlot(slotId);
1475
+ if (activeHid?.kind === "switch_pro") {
1476
+ const side = {
1477
+ highFreqHz: 320,
1478
+ highAmp: Math.max(0, Math.min(0.85, weakMagnitude * 0.8)),
1479
+ lowFreqHz: 150,
1480
+ lowAmp: Math.max(0, Math.min(0.85, strongMagnitude * 0.8))
1481
+ };
1482
+ return this.playSwitchHdRumble({ left: side, right: side, durationMs }, slotId);
1483
+ }
1484
+ const pad = this.getGamepadForSlot(slotId);
1485
+ const act = pad?.vibrationActuator;
1486
+ if (!act?.playEffect) return false;
1487
+ try {
1488
+ await act.playEffect("dual-rumble", {
1489
+ startDelay: 0,
1490
+ duration: Math.max(20, Math.min(2500, Math.round(durationMs))),
1491
+ strongMagnitude: Math.max(0, Math.min(1, strongMagnitude)),
1492
+ weakMagnitude: Math.max(0, Math.min(1, weakMagnitude))
1493
+ });
1494
+ return true;
1495
+ } catch {
1496
+ return false;
1497
+ }
1498
+ }
1499
+ stopGamepadRumble(slotId) {
1500
+ this.stopSwitchHdRumble(slotId);
1501
+ if (!_DualSenseControllerManager.isGamepadSupported()) return;
1502
+ if (slotId !== void 0) {
1503
+ const pad = this.getGamepadForSlot(slotId);
1504
+ if (pad?.vibrationActuator?.reset) {
1505
+ void pad.vibrationActuator.reset().catch(() => {
1506
+ });
1507
+ }
1508
+ return;
1509
+ }
1510
+ for (const pad of this.getAllRawGamepads()) {
1511
+ const act = pad.vibrationActuator;
1512
+ if (act?.reset) {
1513
+ void act.reset().catch(() => {
1514
+ });
1515
+ }
1516
+ }
1517
+ }
1518
+ /**
1519
+ * Backwards-compatible helper used when 4ch VCM audio is not active.
1520
+ */
1521
+ triggerGamepadRumbleFallback(weakMagnitude, strongMagnitude, durationMs, slotId) {
1522
+ const activeHid = this.getHidSessionForSlot(slotId);
1523
+ if (activeHid?.kind === "switch_pro") {
1524
+ void this.playDualRumble(weakMagnitude, strongMagnitude, durationMs, slotId);
1525
+ return;
1526
+ }
1527
+ if (activeHid?.kind === "dualsense") {
1528
+ void this.pulseLegacyRumble(
1529
+ Math.round(Math.max(0, Math.min(1, strongMagnitude)) * 220),
1530
+ Math.round(Math.max(0, Math.min(1, weakMagnitude)) * 220),
1531
+ Math.max(25, Math.min(350, durationMs)),
1532
+ slotId
1533
+ );
1534
+ return;
1535
+ }
1536
+ void this.playDualRumble(weakMagnitude, strongMagnitude, durationMs, slotId);
1537
+ }
1538
+ buildCommonPayload(outState, { includeAudioConfig = false, includeTriggers = false, includeLeds = false } = {}) {
1539
+ const common = new Uint8Array(47);
1540
+ let flag0 = 0;
1541
+ let flag1 = 0;
1542
+ if (outState.legacyRumbleActive) {
1543
+ flag0 |= 1 | 2;
1544
+ common[2] = Math.max(0, Math.min(255, Math.round(outState.legacyRight)));
1545
+ common[3] = Math.max(0, Math.min(255, Math.round(outState.legacyLeft)));
1546
+ }
1547
+ if (includeTriggers) {
1548
+ flag0 |= 4 | 8;
1549
+ common.set(outState.rightTrigger.subarray(0, 11), 10);
1550
+ common.set(outState.leftTrigger.subarray(0, 11), 21);
1551
+ }
1552
+ if (includeAudioConfig) {
1553
+ flag0 |= 16 | 32 | 128;
1554
+ flag1 |= 2 | 128;
1555
+ common[4] = Math.max(0, Math.min(127, outState.headphoneVolume));
1556
+ common[5] = Math.max(0, Math.min(255, outState.speakerVolume));
1557
+ common[6] = 0;
1558
+ common[7] = outState.audioRoute === "speaker" ? 48 : outState.audioRoute === "both" ? 32 : 0;
1559
+ common[9] = 0;
1560
+ common[37] = outState.speakerPreamp & 7;
1561
+ }
1562
+ if (includeLeds) {
1563
+ flag1 |= 4 | 16;
1564
+ common[38] = 2;
1565
+ common[41] = 2;
1566
+ common[42] = 0;
1567
+ common[43] = outState.playerLeds & 31;
1568
+ common[44] = outState.lightbar[0] & 255;
1569
+ common[45] = outState.lightbar[1] & 255;
1570
+ common[46] = outState.lightbar[2] & 255;
1571
+ }
1572
+ common[0] = flag0;
1573
+ common[1] = flag1;
1574
+ return common;
1575
+ }
1576
+ async flushSessionOutput(session, opts = {}) {
1577
+ if (session.kind !== "dualsense" || !session.device.opened) return false;
1578
+ const common = this.buildCommonPayload(session.outState, opts);
1579
+ if (session.transport === "bluetooth") {
1580
+ const payload2 = new Uint8Array(session.btPayloadLength);
1581
+ payload2[0] = (session.btSeq & 15) << 4;
1582
+ session.btSeq = session.btSeq + 1 & 15;
1583
+ payload2[1] = 16;
1584
+ payload2.set(common, 2);
1585
+ const crcOffset = payload2.length - 4;
1586
+ const crc = crc32WithSeed(162, 49, payload2.subarray(0, crcOffset));
1587
+ new DataView(payload2.buffer).setUint32(crcOffset, crc, true);
1588
+ await session.device.sendReport(49, payload2);
1589
+ return true;
1590
+ }
1591
+ const payload = new Uint8Array(session.usbPayloadLength);
1592
+ payload.set(common, 0);
1593
+ await session.device.sendReport(2, payload);
1594
+ return true;
1595
+ }
1596
+ async flushOutput(opts = {}) {
1597
+ const session = this.getActiveHidSession();
1598
+ if (!session || session.kind !== "dualsense") return false;
1599
+ return this.flushSessionOutput(session, opts);
1600
+ }
1601
+ async setAudioConfig(cfg) {
1602
+ const session = this.getActiveHidSession();
1603
+ if (!session || session.kind !== "dualsense") return false;
1604
+ if (cfg.speakerVolume !== void 0) session.outState.speakerVolume = cfg.speakerVolume;
1605
+ if (cfg.headphoneVolume !== void 0) session.outState.headphoneVolume = cfg.headphoneVolume;
1606
+ if (cfg.audioRoute !== void 0) session.outState.audioRoute = cfg.audioRoute;
1607
+ if (cfg.speakerPreamp !== void 0) session.outState.speakerPreamp = cfg.speakerPreamp;
1608
+ return this.flushSessionOutput(session, { includeAudioConfig: true });
1609
+ }
1610
+ async setTriggers(left, right, slotId) {
1611
+ const session = this.getHidSessionForSlot(slotId);
1612
+ if (!session || session.kind !== "dualsense") return false;
1613
+ const prevLeft = session.outState.leftTrigger;
1614
+ const prevRight = session.outState.rightTrigger;
1615
+ const nextLeft = left ? encodeTriggerEffect(left) : void 0;
1616
+ const nextRight = right ? encodeTriggerEffect(right) : void 0;
1617
+ if (nextLeft) session.outState.leftTrigger = nextLeft;
1618
+ if (nextRight) session.outState.rightTrigger = nextRight;
1619
+ try {
1620
+ const ok = await this.flushSessionOutput(session, { includeTriggers: true });
1621
+ if (!ok) {
1622
+ if (nextLeft && session.outState.leftTrigger === nextLeft) session.outState.leftTrigger = prevLeft;
1623
+ if (nextRight && session.outState.rightTrigger === nextRight) session.outState.rightTrigger = prevRight;
1624
+ }
1625
+ return ok;
1626
+ } catch (err) {
1627
+ if (nextLeft && session.outState.leftTrigger === nextLeft) session.outState.leftTrigger = prevLeft;
1628
+ if (nextRight && session.outState.rightTrigger === nextRight) session.outState.rightTrigger = prevRight;
1629
+ throw err;
1630
+ }
1631
+ }
1632
+ async resetTriggers(slotId) {
1633
+ this.stopGamepadRumble(slotId);
1634
+ if (slotId !== void 0) {
1635
+ const session = this.getHidSessionForSlot(slotId);
1636
+ if (!session || !session.device.opened || session.kind !== "dualsense") return false;
1637
+ session.outState.leftTrigger = encodeTriggerEffect({ type: "off" });
1638
+ session.outState.rightTrigger = encodeTriggerEffect({ type: "off" });
1639
+ return this.flushSessionOutput(session, { includeTriggers: true }).catch(() => false);
1640
+ }
1641
+ let resetAny = false;
1642
+ for (const session of this.hidSessions.values()) {
1643
+ if (!session.device.opened || session.kind !== "dualsense") continue;
1644
+ session.outState.leftTrigger = encodeTriggerEffect({ type: "off" });
1645
+ session.outState.rightTrigger = encodeTriggerEffect({ type: "off" });
1646
+ const ok = await this.flushSessionOutput(session, { includeTriggers: true }).catch(() => false);
1647
+ if (ok) resetAny = true;
1648
+ }
1649
+ return resetAny;
1650
+ }
1651
+ /**
1652
+ * Fire-and-forget safety reset across ALL connected WebHID and Gamepad controllers
1653
+ * used inside `pagehide` / `beforeunload` so no controller ever stays stuck with stiff triggers or rumble.
1654
+ */
1655
+ emergencyReset() {
1656
+ this.stopGamepadRumble();
1657
+ for (const session of this.hidSessions.values()) {
1658
+ if (!session.device.opened) continue;
1659
+ if (session.kind === "switch_pro") {
1660
+ this.clearSwitchRumbleTimers(session);
1661
+ void this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE).catch(() => {
1662
+ });
1663
+ continue;
1664
+ }
1665
+ session.outState.leftTrigger = encodeTriggerEffect({ type: "off" });
1666
+ session.outState.rightTrigger = encodeTriggerEffect({ type: "off" });
1667
+ session.outState.legacyRumbleActive = false;
1668
+ session.outState.legacyLeft = 0;
1669
+ session.outState.legacyRight = 0;
1670
+ session.outState.lightbar = [23, 23, 23];
1671
+ void this.flushSessionOutput(session, { includeTriggers: true, includeLeds: true }).catch(() => {
1672
+ });
1673
+ }
1674
+ }
1675
+ async setLightbar(r, g, b, slotId) {
1676
+ const session = this.getHidSessionForSlot(slotId);
1677
+ if (!session || session.kind !== "dualsense") return false;
1678
+ session.outState.lightbar = [r & 255, g & 255, b & 255];
1679
+ return this.flushSessionOutput(session, { includeLeds: true });
1680
+ }
1681
+ async pulseLegacyRumble(left = 200, right = 200, durationMs = 250, slotId) {
1682
+ const session = this.getHidSessionForSlot(slotId);
1683
+ if (!session || session.kind !== "dualsense" || !session.device.opened) return false;
1684
+ if (session.legacyTimer) {
1685
+ clearTimeout(session.legacyTimer);
1686
+ session.legacyTimer = null;
1687
+ }
1688
+ session.outState.legacyRumbleActive = true;
1689
+ session.outState.legacyLeft = left;
1690
+ session.outState.legacyRight = right;
1691
+ await this.flushSessionOutput(session, {});
1692
+ return new Promise((resolve) => {
1693
+ session.legacyTimer = setTimeout(async () => {
1694
+ session.legacyTimer = null;
1695
+ try {
1696
+ session.outState.legacyLeft = 0;
1697
+ session.outState.legacyRight = 0;
1698
+ await this.flushSessionOutput(session, {});
1699
+ session.outState.legacyRumbleActive = false;
1700
+ await this.flushSessionOutput(session, { includeAudioConfig: true });
1701
+ } catch {
1702
+ }
1703
+ resolve(true);
1704
+ }, durationMs);
1705
+ });
1706
+ }
1707
+ };
1708
+
1709
+ // src/haptics/presets.ts
1710
+ var TRIGGER_PRESETS = {
1711
+ off: { type: "off" },
1712
+ weapon: { type: "weapon", startZone: 2, endZone: 5, strength: 7 },
1713
+ heavy_weapon: { type: "weapon", startZone: 3, endZone: 6, strength: 8 },
1714
+ bow: { type: "slope", startZone: 1, endZone: 8, startStrength: 1, endStrength: 7 },
1715
+ abs: { type: "vibration", startZone: 2, amplitude: 6, frequencyHz: 22 },
1716
+ soft_wall: { type: "feedback", startZone: 4, strength: 4 },
1717
+ rapid_pulse: { type: "vibration", startZone: 1, amplitude: 7, frequencyHz: 14 },
1718
+ precision_damp: { type: "feedback", startZone: 2, strength: 3 }
1719
+ };
1720
+ var TACTILE_PRESETS = {
1721
+ click: {
1722
+ freqHz: 210,
1723
+ endFreqHz: 140,
1724
+ durationMs: 26,
1725
+ intensity: 0.45,
1726
+ wave: "triangle",
1727
+ triggerEmphasis: 0.65,
1728
+ switchHd: { highFreqHz: 340, lowFreqHz: 165, highWeight: 0.75, lowWeight: 0.25 }
1729
+ },
1730
+ ratchet: {
1731
+ freqHz: 180,
1732
+ endFreqHz: 110,
1733
+ durationMs: 22,
1734
+ intensity: 0.5,
1735
+ wave: "triangle",
1736
+ triggerEmphasis: 0.75,
1737
+ switchHd: { highFreqHz: 320, lowFreqHz: 155, highWeight: 0.8, lowWeight: 0.2 }
1738
+ },
1739
+ wall_hit: {
1740
+ freqHz: 135,
1741
+ endFreqHz: 58,
1742
+ durationMs: 65,
1743
+ intensity: 0.78,
1744
+ wave: "triangle",
1745
+ triggerEmphasis: 0.5,
1746
+ switchHd: { highFreqHz: 290, lowFreqHz: 130, highWeight: 0.55, lowWeight: 0.75 }
1747
+ },
1748
+ marble_click: {
1749
+ freqHz: 290,
1750
+ endFreqHz: 210,
1751
+ durationMs: 32,
1752
+ intensity: 0.62,
1753
+ wave: "sine",
1754
+ triggerEmphasis: 0.85,
1755
+ switchHd: { highFreqHz: 380, lowFreqHz: 190, highWeight: 0.85, lowWeight: 0.18 }
1756
+ },
1757
+ recoil: {
1758
+ freqHz: 115,
1759
+ endFreqHz: 46,
1760
+ durationMs: 75,
1761
+ intensity: 0.88,
1762
+ wave: "triangle",
1763
+ triggerEmphasis: 1,
1764
+ switchHd: { highFreqHz: 310, lowFreqHz: 120, highWeight: 0.65, lowWeight: 0.85 }
1765
+ },
1766
+ heavy_impact: {
1767
+ freqHz: 75,
1768
+ endFreqHz: 34,
1769
+ durationMs: 140,
1770
+ intensity: 0.95,
1771
+ wave: "sine",
1772
+ triggerEmphasis: 0.7,
1773
+ switchHd: { highFreqHz: 220, lowFreqHz: 95, highWeight: 0.45, lowWeight: 0.95 }
1774
+ },
1775
+ lock_unlock: {
1776
+ freqHz: 95,
1777
+ endFreqHz: 220,
1778
+ durationMs: 120,
1779
+ intensity: 0.72,
1780
+ wave: "triangle",
1781
+ triggerEmphasis: 0.6,
1782
+ switchHd: { highFreqHz: 350, lowFreqHz: 150, highWeight: 0.7, lowWeight: 0.55 }
1783
+ },
1784
+ splash: {
1785
+ freqHz: 90,
1786
+ endFreqHz: 48,
1787
+ durationMs: 110,
1788
+ intensity: 0.6,
1789
+ wave: "sine",
1790
+ triggerEmphasis: 0.35,
1791
+ switchHd: { highFreqHz: 250, lowFreqHz: 120, highWeight: 0.5, lowWeight: 0.6 }
1792
+ },
1793
+ boost: {
1794
+ freqHz: 65,
1795
+ endFreqHz: 165,
1796
+ durationMs: 160,
1797
+ intensity: 0.75,
1798
+ wave: "sawtooth",
1799
+ triggerEmphasis: 0.85,
1800
+ switchHd: { highFreqHz: 300, lowFreqHz: 135, highWeight: 0.6, lowWeight: 0.75 }
1801
+ },
1802
+ error_buzz: {
1803
+ freqHz: 145,
1804
+ endFreqHz: 115,
1805
+ durationMs: 95,
1806
+ intensity: 0.65,
1807
+ wave: "square",
1808
+ triggerEmphasis: 0.45,
1809
+ switchHd: { highFreqHz: 260, lowFreqHz: 125, highWeight: 0.55, lowWeight: 0.65 }
1810
+ }
1811
+ };
1812
+ function buildSwitchHdFromPulse(opts) {
1813
+ const pan = Math.max(-1, Math.min(1, opts.pan ?? 0));
1814
+ const intensity = Math.max(0, Math.min(1, opts.intensity));
1815
+ const leftGain = Math.min(1, 1 - Math.max(0, pan));
1816
+ const rightGain = Math.min(1, 1 + Math.min(0, pan));
1817
+ const highFreqHz = opts.highFreqHz ?? Math.max(160, Math.min(620, opts.freqHz * 1.9));
1818
+ const lowFreqHz = opts.lowFreqHz ?? Math.max(60, Math.min(240, opts.freqHz));
1819
+ const highBias = opts.highWeight ?? (opts.freqHz >= 140 ? 0.78 : 0.42);
1820
+ const lowBias = opts.lowWeight ?? (opts.freqHz < 140 ? 0.82 : 0.38);
1821
+ const mkSide = (gain) => {
1822
+ const scaled = intensity * gain;
1823
+ if (scaled < 0.02) return void 0;
1824
+ return {
1825
+ highFreqHz,
1826
+ highAmp: Math.min(0.85, scaled * highBias * 0.85),
1827
+ lowFreqHz,
1828
+ lowAmp: Math.min(0.85, scaled * lowBias * 0.85)
1829
+ };
1830
+ };
1831
+ return {
1832
+ left: mkSide(leftGain),
1833
+ right: mkSide(rightGain),
1834
+ durationMs: Math.max(30, Math.min(2500, Math.round(opts.durationMs)))
1835
+ };
1836
+ }
1837
+
1838
+ // src/haptics/router.ts
1839
+ function canUse4Ch(ctx) {
1840
+ if (ctx.allow4ChAudio === false) return false;
1841
+ return Boolean(ctx.audio && ctx.audio.dsMode !== "none" && ctx.audio.dsMaxChannelCount >= 4);
1842
+ }
1843
+ function routeHapticPulse(ctx, spec) {
1844
+ if (canUse4Ch(ctx)) {
1845
+ ctx.audio.playHapticPulse(spec);
1846
+ return;
1847
+ }
1848
+ const matrix = ctx.hid.getCapabilityMatrixForSlot(ctx.slotId);
1849
+ const intensity = Math.max(0, Math.min(1, spec.intensity));
1850
+ const durationMs = Math.max(25, Math.min(2500, Math.round(spec.durationMs)));
1851
+ const pan = Math.max(-1, Math.min(1, spec.pan ?? 0));
1852
+ if (matrix.hd_rumble?.availability === "ready") {
1853
+ const hdSpec = buildSwitchHdFromPulse({
1854
+ pan,
1855
+ freqHz: spec.freqHz,
1856
+ intensity,
1857
+ durationMs
1858
+ });
1859
+ void ctx.hid.playSwitchHdRumble(hdSpec, ctx.slotId);
1860
+ return;
1861
+ }
1862
+ if (matrix.impulse_triggers?.availability === "ready") {
1863
+ const leftGain = Math.min(1, 1 - Math.max(0, pan));
1864
+ const rightGain = Math.min(1, 1 + Math.min(0, pan));
1865
+ const crispBias = spec.freqHz >= 120 ? 0.85 : 0.45;
1866
+ const gripBias = spec.freqHz < 120 ? 0.78 : 0.35;
1867
+ void ctx.hid.playTriggerRumble(
1868
+ intensity * leftGain * crispBias,
1869
+ intensity * rightGain * crispBias,
1870
+ durationMs,
1871
+ intensity * (spec.freqHz >= 120 ? 0.65 : 0.35),
1872
+ intensity * gripBias,
1873
+ ctx.slotId
1874
+ );
1875
+ return;
1876
+ }
1877
+ const strong = spec.freqHz < 120 ? intensity * 0.8 : intensity * 0.3;
1878
+ const weak = spec.freqHz >= 120 ? intensity * 0.85 : intensity * 0.4;
1879
+ ctx.hid.triggerGamepadRumbleFallback(weak, strong, durationMs, ctx.slotId);
1880
+ }
1881
+ function routeHapticSweep(ctx, spec) {
1882
+ if (canUse4Ch(ctx)) {
1883
+ ctx.audio.playHapticSweep(spec);
1884
+ return;
1885
+ }
1886
+ const matrix = ctx.hid.getCapabilityMatrixForSlot(ctx.slotId);
1887
+ const intensity = Math.max(0, Math.min(1, spec.intensity));
1888
+ const durationMs = Math.max(40, Math.min(2500, Math.round(spec.durationMs)));
1889
+ if (matrix.hd_rumble?.availability === "ready") {
1890
+ const stepsCount = Math.max(2, Math.min(6, Math.round(durationMs / 55)));
1891
+ const stepDur = Math.max(30, Math.round(durationMs / stepsCount));
1892
+ const steps = [];
1893
+ for (let i = 0; i < stepsCount; i++) {
1894
+ const t = stepsCount === 1 ? 0 : i / (stepsCount - 1);
1895
+ const pan = spec.fromPan + (spec.toPan - spec.fromPan) * t;
1896
+ const freqHz = spec.fromHz + (spec.toHz - spec.fromHz) * t;
1897
+ steps.push({
1898
+ ...buildSwitchHdFromPulse({ pan, freqHz, intensity, durationMs: stepDur }),
1899
+ delayMs: i * stepDur
1900
+ });
1901
+ }
1902
+ void ctx.hid.playSwitchHdRumbleSequence(steps, ctx.slotId);
1903
+ return;
1904
+ }
1905
+ if (matrix.impulse_triggers?.availability === "ready") {
1906
+ const midPan = (spec.fromPan + spec.toPan) * 0.5;
1907
+ const leftGain = Math.min(1, 1 - Math.max(0, midPan));
1908
+ const rightGain = Math.min(1, 1 + Math.min(0, midPan));
1909
+ void ctx.hid.playTriggerRumble(
1910
+ intensity * leftGain * 0.7,
1911
+ intensity * rightGain * 0.7,
1912
+ durationMs,
1913
+ intensity * 0.5,
1914
+ intensity * 0.6,
1915
+ ctx.slotId
1916
+ );
1917
+ return;
1918
+ }
1919
+ ctx.hid.triggerGamepadRumbleFallback(intensity * 0.55, intensity * 0.65, durationMs, ctx.slotId);
1920
+ }
1921
+ function routeTactilePreset(ctx, presetId, opts = {}) {
1922
+ const preset = TACTILE_PRESETS[presetId];
1923
+ if (!preset) return;
1924
+ const pan = Math.max(-1, Math.min(1, opts.pan ?? 0));
1925
+ const intensity = Math.max(0, Math.min(1, (opts.intensity ?? 1) * preset.intensity));
1926
+ if (canUse4Ch(ctx)) {
1927
+ ctx.audio.playHapticPulse({
1928
+ pan,
1929
+ freqHz: preset.freqHz,
1930
+ endFreqHz: preset.endFreqHz,
1931
+ durationMs: preset.durationMs,
1932
+ intensity,
1933
+ wave: preset.wave
1934
+ });
1935
+ return;
1936
+ }
1937
+ const matrix = ctx.hid.getCapabilityMatrixForSlot(ctx.slotId);
1938
+ if (matrix.hd_rumble?.availability === "ready" && preset.switchHd) {
1939
+ const hdSpec = buildSwitchHdFromPulse({
1940
+ pan,
1941
+ freqHz: preset.freqHz,
1942
+ intensity,
1943
+ durationMs: preset.durationMs,
1944
+ highFreqHz: preset.switchHd.highFreqHz,
1945
+ lowFreqHz: preset.switchHd.lowFreqHz,
1946
+ highWeight: preset.switchHd.highWeight,
1947
+ lowWeight: preset.switchHd.lowWeight
1948
+ });
1949
+ void ctx.hid.playSwitchHdRumble(hdSpec, ctx.slotId);
1950
+ return;
1951
+ }
1952
+ if (matrix.impulse_triggers?.availability === "ready" && preset.triggerEmphasis) {
1953
+ const leftGain = Math.min(1, 1 - Math.max(0, pan));
1954
+ const rightGain = Math.min(1, 1 + Math.min(0, pan));
1955
+ const trig = intensity * preset.triggerEmphasis;
1956
+ void ctx.hid.playTriggerRumble(
1957
+ trig * leftGain,
1958
+ trig * rightGain,
1959
+ Math.max(30, preset.durationMs),
1960
+ intensity * 0.45,
1961
+ intensity * 0.55,
1962
+ ctx.slotId
1963
+ );
1964
+ return;
1965
+ }
1966
+ routeHapticPulse(ctx, {
1967
+ pan,
1968
+ freqHz: preset.freqHz,
1969
+ endFreqHz: preset.endFreqHz,
1970
+ durationMs: preset.durationMs,
1971
+ intensity,
1972
+ wave: preset.wave
1973
+ });
1974
+ }
1975
+
1976
+ // src/input/actions.ts
1977
+ var BUTTON_NAMES = /* @__PURE__ */ new Set([
1978
+ "cross",
1979
+ "circle",
1980
+ "square",
1981
+ "triangle",
1982
+ "l1",
1983
+ "r1",
1984
+ "l2Btn",
1985
+ "r2Btn",
1986
+ "l3",
1987
+ "r3",
1988
+ "up",
1989
+ "down",
1990
+ "left",
1991
+ "right",
1992
+ "create",
1993
+ "options",
1994
+ "ps",
1995
+ "touchpadClick"
1996
+ ]);
1997
+ function evalBindingValue(binding, input, keysDown, mouseDown, threshold) {
1998
+ if (binding === "l2") return input.l2;
1999
+ if (binding === "r2") return input.r2;
2000
+ if (binding === "lx+") return Math.max(0, input.lx);
2001
+ if (binding === "lx-") return Math.max(0, -input.lx);
2002
+ if (binding === "ly+") return Math.max(0, input.ly);
2003
+ if (binding === "ly-") return Math.max(0, -input.ly);
2004
+ if (binding === "rx+") return Math.max(0, input.rx);
2005
+ if (binding === "rx-") return Math.max(0, -input.rx);
2006
+ if (binding === "ry+") return Math.max(0, input.ry);
2007
+ if (binding === "ry-") return Math.max(0, -input.ry);
2008
+ if (BUTTON_NAMES.has(binding)) {
2009
+ return input.buttons[binding] ? 1 : 0;
2010
+ }
2011
+ if (binding === "MouseLeft" || binding === "MouseRight" || binding === "MouseMiddle") {
2012
+ return mouseDown.has(binding) ? 1 : 0;
2013
+ }
2014
+ if (keysDown.has(binding)) {
2015
+ return Math.max(1, threshold);
2016
+ }
2017
+ return 0;
2018
+ }
2019
+ function createActionTracker(spec) {
2020
+ const threshold = spec.analogThreshold ?? 0.45;
2021
+ const actionsDef = spec.actions ?? {};
2022
+ const axesDef = spec.axes ?? {};
2023
+ const keysDown = /* @__PURE__ */ new Set();
2024
+ const mouseDown = /* @__PURE__ */ new Set();
2025
+ const states = /* @__PURE__ */ new Map();
2026
+ const pressedAt = /* @__PURE__ */ new Map();
2027
+ const axisValues = /* @__PURE__ */ new Map();
2028
+ for (const name of Object.keys(actionsDef)) {
2029
+ states.set(name, { pressed: false, justPressed: false, justReleased: false, heldMs: 0, value: 0 });
2030
+ }
2031
+ for (const name of Object.keys(axesDef)) {
2032
+ axisValues.set(name, 0);
2033
+ }
2034
+ const mapMouseButton = (button) => {
2035
+ if (button === 0) return "MouseLeft";
2036
+ if (button === 1) return "MouseMiddle";
2037
+ if (button === 2) return "MouseRight";
2038
+ return null;
2039
+ };
2040
+ const onKeyDown = (e) => {
2041
+ const ke = e;
2042
+ if (ke.code) keysDown.add(ke.code);
2043
+ };
2044
+ const onKeyUp = (e) => {
2045
+ const ke = e;
2046
+ if (ke.code) keysDown.delete(ke.code);
2047
+ };
2048
+ const onPointerDown = (e) => {
2049
+ const pe = e;
2050
+ const mapped = mapMouseButton(pe.button);
2051
+ if (mapped) mouseDown.add(mapped);
2052
+ };
2053
+ const onPointerUp = (e) => {
2054
+ const pe = e;
2055
+ const mapped = mapMouseButton(pe.button);
2056
+ if (mapped) mouseDown.delete(mapped);
2057
+ };
2058
+ const onBlur = () => {
2059
+ keysDown.clear();
2060
+ mouseDown.clear();
2061
+ };
2062
+ const shouldAttach = spec.attachWindowListeners !== false && typeof window !== "undefined";
2063
+ const mouseTarget = spec.mouseTarget ?? (typeof window !== "undefined" ? window : void 0);
2064
+ if (shouldAttach) {
2065
+ window.addEventListener("keydown", onKeyDown);
2066
+ window.addEventListener("keyup", onKeyUp);
2067
+ window.addEventListener("blur", onBlur);
2068
+ mouseTarget?.addEventListener("pointerdown", onPointerDown);
2069
+ window.addEventListener("pointerup", onPointerUp);
2070
+ }
2071
+ const EMPTY_STATE = {
2072
+ pressed: false,
2073
+ justPressed: false,
2074
+ justReleased: false,
2075
+ heldMs: 0,
2076
+ value: 0
2077
+ };
2078
+ return {
2079
+ update(input, nowMs = typeof performance !== "undefined" ? performance.now() : Date.now()) {
2080
+ for (const [name, bindings] of Object.entries(actionsDef)) {
2081
+ let maxVal = 0;
2082
+ for (const b of bindings) {
2083
+ const v = evalBindingValue(b, input, keysDown, mouseDown, threshold);
2084
+ if (v > maxVal) maxVal = v;
2085
+ }
2086
+ const pressed = maxVal >= threshold;
2087
+ const prev = states.get(name);
2088
+ const justPressed = pressed && !prev.pressed;
2089
+ const justReleased = !pressed && prev.pressed;
2090
+ if (justPressed) {
2091
+ pressedAt.set(name, nowMs);
2092
+ } else if (!pressed) {
2093
+ pressedAt.delete(name);
2094
+ }
2095
+ const startAt = pressedAt.get(name);
2096
+ prev.pressed = pressed;
2097
+ prev.justPressed = justPressed;
2098
+ prev.justReleased = justReleased;
2099
+ prev.heldMs = pressed && startAt !== void 0 ? Math.max(0, nowMs - startAt) : 0;
2100
+ prev.value = Math.max(0, Math.min(1, maxVal));
2101
+ }
2102
+ for (const [name, def] of Object.entries(axesDef)) {
2103
+ let value = 0;
2104
+ if (def.stick) {
2105
+ const raw = input[def.stick];
2106
+ const dz = def.deadzone ?? 0.08;
2107
+ value = applyDeadzone(raw, dz);
2108
+ }
2109
+ let digital = 0;
2110
+ if (def.negativeButtons?.some((b) => input.buttons[b])) digital -= 1;
2111
+ if (def.positiveButtons?.some((b) => input.buttons[b])) digital += 1;
2112
+ if (def.negativeKeys?.some((k) => keysDown.has(k))) digital -= 1;
2113
+ if (def.positiveKeys?.some((k) => keysDown.has(k))) digital += 1;
2114
+ const combined = Math.abs(digital) > Math.abs(value) ? digital : value;
2115
+ const clamped = Math.max(-1, Math.min(1, combined));
2116
+ axisValues.set(name, def.invert ? -clamped : clamped);
2117
+ }
2118
+ },
2119
+ action(name) {
2120
+ return states.get(name) ?? EMPTY_STATE;
2121
+ },
2122
+ isPressed(name) {
2123
+ return states.get(name)?.pressed ?? false;
2124
+ },
2125
+ justPressed(name) {
2126
+ return states.get(name)?.justPressed ?? false;
2127
+ },
2128
+ justReleased(name) {
2129
+ return states.get(name)?.justReleased ?? false;
2130
+ },
2131
+ axis(name) {
2132
+ return axisValues.get(name) ?? 0;
2133
+ },
2134
+ setKeyDown(code, down) {
2135
+ if (down) keysDown.add(code);
2136
+ else keysDown.delete(code);
2137
+ },
2138
+ setMouseButton(button, down) {
2139
+ if (down) mouseDown.add(button);
2140
+ else mouseDown.delete(button);
2141
+ },
2142
+ dispose() {
2143
+ if (shouldAttach) {
2144
+ window.removeEventListener("keydown", onKeyDown);
2145
+ window.removeEventListener("keyup", onKeyUp);
2146
+ window.removeEventListener("blur", onBlur);
2147
+ mouseTarget?.removeEventListener("pointerdown", onPointerDown);
2148
+ window.removeEventListener("pointerup", onPointerUp);
2149
+ }
2150
+ keysDown.clear();
2151
+ mouseDown.clear();
2152
+ pressedAt.clear();
2153
+ }
2154
+ };
2155
+ }
2156
+
2157
+ // src/hub.ts
2158
+ var NOOP_CONTINUOUS = {
2159
+ update() {
2160
+ },
2161
+ stop() {
2162
+ }
2163
+ };
2164
+ function computeCapabilities(hid, audio, slotId, allow4ChAudio) {
2165
+ const has4Ch = allow4ChAudio && Boolean(audio && audio.dsMode !== "none" && audio.dsMaxChannelCount >= 4);
2166
+ const hasSpk = allow4ChAudio && Boolean(audio && audio.dsMode !== "none");
2167
+ const input = hid.getInputState(slotId);
2168
+ const matrix = hid.getCapabilityMatrixForSlot(slotId, {
2169
+ has4ChAudio: has4Ch,
2170
+ hasControllerSpeaker: hasSpk
2171
+ });
2172
+ const has = (cap) => matrix[cap]?.availability === "ready";
2173
+ let tier = "keyboard_mouse";
2174
+ if (has("adaptive_triggers") && has4Ch) tier = "dualsense_full_4ch";
2175
+ else if (has("adaptive_triggers")) tier = "dualsense_hid_only";
2176
+ else if (has("hd_rumble")) tier = "switch_pro_hid";
2177
+ else if (has("impulse_triggers")) tier = "xbox_impulse";
2178
+ else if (input.source === "gamepad") tier = "standard_gamepad";
2179
+ return {
2180
+ slotId: slotId ?? hid.getActiveSlotId(),
2181
+ tier,
2182
+ identity: input.identity,
2183
+ matrix,
2184
+ has,
2185
+ hasAdaptiveTriggers: has("adaptive_triggers"),
2186
+ hasImpulseTriggers: has("impulse_triggers"),
2187
+ hasHdRumble: has("hd_rumble"),
2188
+ hasDualRumble: has("dual_motor_rumble"),
2189
+ has4ChHaptics: has4Ch,
2190
+ hasControllerSpeaker: hasSpk,
2191
+ hasGyro: has("gyro"),
2192
+ hasTouchpad: has("touchpad")
2193
+ };
2194
+ }
2195
+ function buildCapabilitySignature(slots, active) {
2196
+ const slotSig = slots.map((s) => `${s.id}:${s.source}:${s.identity.model}:${s.identity.transport}`).join(",");
2197
+ return [
2198
+ slotSig,
2199
+ active.slotId ?? "",
2200
+ active.tier,
2201
+ active.hasAdaptiveTriggers ? 1 : 0,
2202
+ active.hasImpulseTriggers ? 1 : 0,
2203
+ active.hasHdRumble ? 1 : 0,
2204
+ active.has4ChHaptics ? 1 : 0,
2205
+ active.hasControllerSpeaker ? 1 : 0,
2206
+ active.hasGyro ? 1 : 0
2207
+ ].join("|");
2208
+ }
2209
+ function createGamepadly(options = {}) {
2210
+ const ownsHid = !options.hid;
2211
+ const hid = options.hid ?? new DualSenseControllerManager();
2212
+ let audio = options.audio ?? null;
2213
+ let disposed = false;
2214
+ const continuousHandles = /* @__PURE__ */ new Set();
2215
+ const timers = /* @__PURE__ */ new Set();
2216
+ const trackers = /* @__PURE__ */ new Set();
2217
+ const capListeners = /* @__PURE__ */ new Set();
2218
+ if (options.autoHotplug !== false) {
2219
+ hid.attachHidHotplug();
2220
+ }
2221
+ if (options.attachKeyboardFallback && ownsHid) {
2222
+ hid.attachKeyboardFallback();
2223
+ }
2224
+ let lastCapSig = "";
2225
+ const syncCapabilities = () => {
2226
+ if (disposed) return;
2227
+ const slots = hid.getConnectedControllers();
2228
+ const active = computeCapabilities(hid, audio, void 0, true);
2229
+ const nextSig = buildCapabilitySignature(slots, active);
2230
+ if (nextSig === lastCapSig) return;
2231
+ lastCapSig = nextSig;
2232
+ for (const fn of capListeners) {
2233
+ try {
2234
+ fn({ slots, active });
2235
+ } catch {
2236
+ }
2237
+ }
2238
+ };
2239
+ lastCapSig = buildCapabilitySignature(
2240
+ hid.getConnectedControllers(),
2241
+ computeCapabilities(hid, audio, void 0, true)
2242
+ );
2243
+ const unsubHidStatus = hid.onStatusChange(() => {
2244
+ syncCapabilities();
2245
+ });
2246
+ const onGamepadEvent = () => syncCapabilities();
2247
+ const onPageHide = () => hid.emergencyReset();
2248
+ if (typeof window !== "undefined") {
2249
+ if (options.autoHotplug !== false) {
2250
+ window.addEventListener("gamepadconnected", onGamepadEvent);
2251
+ window.addEventListener("gamepaddisconnected", onGamepadEvent);
2252
+ }
2253
+ if (options.autoEmergencyReset !== false) {
2254
+ window.addEventListener("pagehide", onPageHide);
2255
+ window.addEventListener("beforeunload", onPageHide);
2256
+ }
2257
+ }
2258
+ let pollInterval = null;
2259
+ const pollMs = options.capabilityPollMs ?? 250;
2260
+ if (pollMs > 0 && typeof setInterval !== "undefined") {
2261
+ pollInterval = setInterval(syncCapabilities, pollMs);
2262
+ }
2263
+ const createPlayerHandle = (target) => {
2264
+ let lastLightbarColor = [23, 23, 23];
2265
+ let lastLightbarSentAt = 0;
2266
+ const resolveTarget = () => {
2267
+ if (target === "active") {
2268
+ return { slotId: void 0, connected: true, isPrimary: true };
2269
+ }
2270
+ if (typeof target === "number") {
2271
+ const slots = hid.getConnectedControllers();
2272
+ const slot = slots[target];
2273
+ if (!slot) return { slotId: `__unassigned_${target}`, connected: false, isPrimary: target === 0 };
2274
+ const activeId2 = hid.getActiveSlotId();
2275
+ return { slotId: slot.id, connected: true, isPrimary: slot.id === activeId2 || target === 0 };
2276
+ }
2277
+ const activeId = hid.getActiveSlotId();
2278
+ return { slotId: target, connected: true, isPrimary: target === activeId };
2279
+ };
2280
+ const getRouteCtx = () => {
2281
+ const r = resolveTarget();
2282
+ return {
2283
+ hid,
2284
+ audio,
2285
+ slotId: r.slotId,
2286
+ allow4ChAudio: r.isPrimary
2287
+ };
2288
+ };
2289
+ return {
2290
+ getSlotId() {
2291
+ const r = resolveTarget();
2292
+ if (r.slotId === void 0) return hid.getActiveSlotId();
2293
+ return r.connected ? r.slotId : null;
2294
+ },
2295
+ getCapabilities() {
2296
+ const r = resolveTarget();
2297
+ return computeCapabilities(hid, audio, r.slotId, r.isPrimary);
2298
+ },
2299
+ input: {
2300
+ getState: () => {
2301
+ const r = resolveTarget();
2302
+ return hid.getInputState(r.slotId);
2303
+ },
2304
+ applyDeadzone
2305
+ },
2306
+ triggers: {
2307
+ reset: () => {
2308
+ if (disposed) return;
2309
+ const r = resolveTarget();
2310
+ hid.resetTriggers(r.slotId).catch(() => {
2311
+ });
2312
+ },
2313
+ setLeft: (effect) => {
2314
+ if (disposed) return;
2315
+ const r = resolveTarget();
2316
+ hid.setTriggers(effect, void 0, r.slotId).catch(() => {
2317
+ });
2318
+ },
2319
+ setRight: (effect) => {
2320
+ if (disposed) return;
2321
+ const r = resolveTarget();
2322
+ hid.setTriggers(void 0, effect, r.slotId).catch(() => {
2323
+ });
2324
+ },
2325
+ setBoth: (left, right) => {
2326
+ if (disposed) return;
2327
+ const r = resolveTarget();
2328
+ hid.setTriggers(left, right, r.slotId).catch(() => {
2329
+ });
2330
+ },
2331
+ applyPreset: (presetId, side = "both") => {
2332
+ if (disposed) return;
2333
+ const effect = TRIGGER_PRESETS[presetId];
2334
+ if (!effect) return;
2335
+ const r = resolveTarget();
2336
+ if (side === "left") hid.setTriggers(effect, void 0, r.slotId).catch(() => {
2337
+ });
2338
+ else if (side === "right") hid.setTriggers(void 0, effect, r.slotId).catch(() => {
2339
+ });
2340
+ else hid.setTriggers(effect, effect, r.slotId).catch(() => {
2341
+ });
2342
+ },
2343
+ pulseImpulse: (spec) => {
2344
+ if (disposed) return;
2345
+ const r = resolveTarget();
2346
+ void hid.playTriggerRumble(
2347
+ spec.left ?? 0,
2348
+ spec.right ?? 0,
2349
+ spec.durationMs ?? 80,
2350
+ spec.weakGrip ?? 0,
2351
+ spec.strongGrip ?? 0,
2352
+ r.slotId
2353
+ );
2354
+ }
2355
+ },
2356
+ haptics: {
2357
+ pulse: (spec) => {
2358
+ if (disposed) return;
2359
+ routeHapticPulse(getRouteCtx(), spec);
2360
+ },
2361
+ sweep: (spec) => {
2362
+ if (disposed) return;
2363
+ routeHapticSweep(getRouteCtx(), spec);
2364
+ },
2365
+ rumble: (opts) => {
2366
+ if (disposed) return;
2367
+ const r = resolveTarget();
2368
+ hid.triggerGamepadRumbleFallback(opts.weak, opts.strong, opts.durationMs, r.slotId);
2369
+ },
2370
+ hdRumble: (spec) => {
2371
+ if (disposed) return;
2372
+ const r = resolveTarget();
2373
+ void hid.playSwitchHdRumble(spec, r.slotId);
2374
+ },
2375
+ hdSequence: (steps) => {
2376
+ if (disposed) return;
2377
+ const r = resolveTarget();
2378
+ void hid.playSwitchHdRumbleSequence(steps, r.slotId);
2379
+ },
2380
+ playPreset: (presetId, opts) => {
2381
+ if (disposed) return;
2382
+ routeTactilePreset(getRouteCtx(), presetId, opts);
2383
+ },
2384
+ createContinuous: (preset) => {
2385
+ if (disposed || !audio) return NOOP_CONTINUOUS;
2386
+ const handle = audio.createContinuous(preset);
2387
+ continuousHandles.add(handle);
2388
+ return {
2389
+ update: (p) => {
2390
+ if (!disposed) handle.update(p);
2391
+ },
2392
+ stop: () => {
2393
+ continuousHandles.delete(handle);
2394
+ handle.stop();
2395
+ }
2396
+ };
2397
+ },
2398
+ playComboPreset: (presetId, pan = 0) => {
2399
+ if (disposed) return;
2400
+ const r = resolveTarget();
2401
+ audio?.playComboPreset(presetId, pan);
2402
+ if (!audio || !r.isPrimary || audio.dsMode === "none" || audio.dsMaxChannelCount < 4) {
2403
+ const strong = presetId === "shotgun" || presetId === "thunder" ? 0.85 : 0.4;
2404
+ const dur = presetId === "ratchet_tick" ? 30 : 120;
2405
+ routeHapticPulse(getRouteCtx(), {
2406
+ pan,
2407
+ freqHz: presetId === "ratchet_tick" ? 190 : 95,
2408
+ durationMs: dur,
2409
+ intensity: strong
2410
+ });
2411
+ }
2412
+ },
2413
+ stop: () => {
2414
+ const r = resolveTarget();
2415
+ hid.stopGamepadRumble(r.slotId);
2416
+ }
2417
+ },
2418
+ audio: {
2419
+ playPcTone: (spec) => {
2420
+ if (!disposed) audio?.playPcTone(spec);
2421
+ },
2422
+ playPcNoise: (noiseOpts) => {
2423
+ if (!disposed) audio?.playPcNoiseBurst(noiseOpts);
2424
+ },
2425
+ playControllerSpeakerTone: (spec) => {
2426
+ if (!disposed) audio?.playControllerSpeakerTone(spec);
2427
+ }
2428
+ },
2429
+ lightbar: {
2430
+ setColor: (rCol, gCol, bCol) => {
2431
+ if (disposed) return;
2432
+ const now = typeof performance !== "undefined" ? performance.now() : Date.now();
2433
+ if (lastLightbarColor[0] === rCol && lastLightbarColor[1] === gCol && lastLightbarColor[2] === bCol) {
2434
+ return;
2435
+ }
2436
+ if (now - lastLightbarSentAt < 45) return;
2437
+ lastLightbarSentAt = now;
2438
+ lastLightbarColor = [rCol, gCol, bCol];
2439
+ const r = resolveTarget();
2440
+ hid.setLightbar(rCol, gCol, bCol, r.slotId).catch(() => {
2441
+ });
2442
+ },
2443
+ flash: (rCol, gCol, bCol, durationMs = 240) => {
2444
+ if (disposed) return;
2445
+ const prev = [...lastLightbarColor];
2446
+ const r = resolveTarget();
2447
+ hid.setLightbar(rCol, gCol, bCol, r.slotId).catch(() => {
2448
+ });
2449
+ const t = setTimeout(() => {
2450
+ timers.delete(t);
2451
+ if (!disposed) {
2452
+ hid.setLightbar(prev[0], prev[1], prev[2], r.slotId).catch(() => {
2453
+ });
2454
+ }
2455
+ }, durationMs);
2456
+ timers.add(t);
2457
+ }
2458
+ },
2459
+ createActions(spec) {
2460
+ const tracker = createActionTracker(spec);
2461
+ trackers.add(tracker);
2462
+ return {
2463
+ ...tracker,
2464
+ dispose() {
2465
+ trackers.delete(tracker);
2466
+ tracker.dispose();
2467
+ }
2468
+ };
2469
+ }
2470
+ };
2471
+ };
2472
+ const activePlayer = createPlayerHandle("active");
2473
+ return {
2474
+ hid,
2475
+ async connectWebHID() {
2476
+ const ok = await hid.connect();
2477
+ syncCapabilities();
2478
+ return ok;
2479
+ },
2480
+ async reconnectAuthorized() {
2481
+ const ok = await hid.reconnectAuthorized();
2482
+ syncCapabilities();
2483
+ return ok;
2484
+ },
2485
+ attachAudio(nextAudio) {
2486
+ audio = nextAudio;
2487
+ syncCapabilities();
2488
+ },
2489
+ getSlots() {
2490
+ return hid.getConnectedControllers();
2491
+ },
2492
+ get active() {
2493
+ return activePlayer;
2494
+ },
2495
+ player(target) {
2496
+ if (target === void 0 || target === "active") return activePlayer;
2497
+ return createPlayerHandle(target);
2498
+ },
2499
+ onCapabilitiesChange(listener) {
2500
+ capListeners.add(listener);
2501
+ return () => {
2502
+ capListeners.delete(listener);
2503
+ };
2504
+ },
2505
+ syncCapabilities,
2506
+ dispose() {
2507
+ if (disposed) return;
2508
+ disposed = true;
2509
+ if (pollInterval !== null) {
2510
+ clearInterval(pollInterval);
2511
+ pollInterval = null;
2512
+ }
2513
+ unsubHidStatus();
2514
+ capListeners.clear();
2515
+ if (typeof window !== "undefined") {
2516
+ if (options.autoHotplug !== false) {
2517
+ window.removeEventListener("gamepadconnected", onGamepadEvent);
2518
+ window.removeEventListener("gamepaddisconnected", onGamepadEvent);
2519
+ }
2520
+ if (options.autoEmergencyReset !== false) {
2521
+ window.removeEventListener("pagehide", onPageHide);
2522
+ window.removeEventListener("beforeunload", onPageHide);
2523
+ }
2524
+ }
2525
+ for (const t of timers) clearTimeout(t);
2526
+ timers.clear();
2527
+ for (const tr of trackers) {
2528
+ try {
2529
+ tr.dispose();
2530
+ } catch {
2531
+ }
2532
+ }
2533
+ trackers.clear();
2534
+ for (const h of continuousHandles) {
2535
+ try {
2536
+ h.stop();
2537
+ } catch {
2538
+ }
2539
+ }
2540
+ continuousHandles.clear();
2541
+ hid.stopGamepadRumble();
2542
+ hid.resetTriggers().catch(() => {
2543
+ });
2544
+ hid.setLightbar(23, 23, 23).catch(() => {
2545
+ });
2546
+ if (ownsHid) {
2547
+ if (options.autoHotplug !== false) hid.detachHidHotplug();
2548
+ if (options.attachKeyboardFallback) hid.detachKeyboardFallback();
2549
+ }
2550
+ }
2551
+ };
2552
+ }
2553
+
2554
+ // src/link/engine.ts
2555
+ var COMPANION_HTTP_BASE = "http://127.0.0.1:5178";
2556
+ var COMPANION_WS_BASE = "ws://127.0.0.1:5178";
2557
+ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
2558
+ httpBase;
2559
+ wsBase;
2560
+ // Layer 1: PC Main Speakers / Headset
2561
+ pcCtx = null;
2562
+ pcSinkId = "";
2563
+ pcSinkLabel = "PC Default Speakers";
2564
+ pcMasterGain = null;
2565
+ pcAnalysers = [];
2566
+ pcNoiseBuffer = null;
2567
+ // Layer 2 & 3: DualSense 4-Channel Endpoint
2568
+ dsMode = "none";
2569
+ dsCtx = null;
2570
+ dsSinkId = "";
2571
+ dsSinkLabel = "";
2572
+ dsMaxChannelCount = 2;
2573
+ dsActiveChannelCount = 2;
2574
+ dsWs = null;
2575
+ dsWorklet = null;
2576
+ dsMerger = null;
2577
+ dsChGains = [];
2578
+ // [0: SpkL, 1: SpkR, 2: VcmL, 3: VcmR]
2579
+ dsAnalysers = [];
2580
+ dsNoiseBuffer = null;
2581
+ // Master Gains
2582
+ pcGainValue = 0.8;
2583
+ dsSpeakerGainValue = 0.95;
2584
+ dsHapticGainValue = 0.95;
2585
+ audioMuted = false;
2586
+ constructor(options = {}) {
2587
+ this.httpBase = (options.httpBase || COMPANION_HTTP_BASE).replace(/\/+$/, "");
2588
+ this.wsBase = (options.wsBase || COMPANION_WS_BASE).replace(/\/+$/, "");
2589
+ }
2590
+ /**
2591
+ * Mutes or unmutes audible outputs (PC speakers & controller speaker) while keeping tactile VCM haptics active.
2592
+ */
2593
+ setAudioMuted(muted) {
2594
+ this.audioMuted = muted;
2595
+ if (this.pcMasterGain && this.pcCtx) {
2596
+ this.pcMasterGain.gain.setTargetAtTime(muted ? 0 : this.pcGainValue, this.pcCtx.currentTime, 0.015);
2597
+ }
2598
+ if (this.dsChGains.length >= 2 && this.dsCtx) {
2599
+ const spk = muted ? 0 : this.dsSpeakerGainValue;
2600
+ this.dsChGains[0].gain.setTargetAtTime(spk, this.dsCtx.currentTime, 0.015);
2601
+ this.dsChGains[1].gain.setTargetAtTime(spk, this.dsCtx.currentTime, 0.015);
2602
+ }
2603
+ }
2604
+ // Track active continuous handles for clean disposal
2605
+ activeContinuous = /* @__PURE__ */ new Set();
2606
+ // Companion WebSocket lifecycle & auto-reconnect
2607
+ companionToken = "";
2608
+ intentionalWsClose = false;
2609
+ reconnectAttempts = 0;
2610
+ reconnectTimer = null;
2611
+ streamStateListeners = /* @__PURE__ */ new Set();
2612
+ onCompanionStreamState(fn) {
2613
+ this.streamStateListeners.add(fn);
2614
+ return () => this.streamStateListeners.delete(fn);
2615
+ }
2616
+ emitStreamState(state, message) {
2617
+ for (const fn of this.streamStateListeners) {
2618
+ try {
2619
+ fn(state, message);
2620
+ } catch {
2621
+ }
2622
+ }
2623
+ }
2624
+ static isLoopbackOrigin() {
2625
+ if (typeof window === "undefined") return true;
2626
+ const h = window.location.hostname;
2627
+ return h === "localhost" || h === "127.0.0.1" || h === "[::1]";
2628
+ }
2629
+ /**
2630
+ * Checks Chrome 142+/147+ Local Network Access (`loopback-network`) permission state.
2631
+ * Prevents unsolicited browser permission popups on initial page load for public HTTPS visitors!
2632
+ */
2633
+ static async getLoopbackPermissionState() {
2634
+ if (_ThreeLayerAudioEngine.isLoopbackOrigin()) return "local_exempt";
2635
+ if (typeof navigator === "undefined" || !navigator.permissions?.query) return "unknown";
2636
+ for (const permName of ["loopback-network", "local-network-access"]) {
2637
+ try {
2638
+ const res = await navigator.permissions.query({ name: permName });
2639
+ if (res.state === "granted" || res.state === "prompt" || res.state === "denied") {
2640
+ return res.state;
2641
+ }
2642
+ } catch {
2643
+ }
2644
+ }
2645
+ return "unknown";
2646
+ }
2647
+ /**
2648
+ * Fetch wrapper targeting 127.0.0.1 with Chrome LNA `targetAddressSpace: 'loopback'`.
2649
+ */
2650
+ async loopbackFetch(url, init = {}) {
2651
+ const lnaInit = { ...init, targetAddressSpace: "loopback" };
2652
+ try {
2653
+ return await fetch(url, lnaInit);
2654
+ } catch (err) {
2655
+ if (err instanceof TypeError && !String(err.message).toLowerCase().includes("fetch")) {
2656
+ return fetch(url, init);
2657
+ }
2658
+ throw err;
2659
+ }
2660
+ }
2661
+ static checkBrowserCapabilities() {
2662
+ if (typeof window === "undefined") {
2663
+ return {
2664
+ hasWebAudio: false,
2665
+ hasSetSinkId: false,
2666
+ hasAudioWorklet: false,
2667
+ isSecureContext: true
2668
+ };
2669
+ }
2670
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
2671
+ return {
2672
+ hasWebAudio: Boolean(AudioCtx),
2673
+ hasSetSinkId: Boolean(AudioCtx && "setSinkId" in AudioCtx.prototype),
2674
+ hasAudioWorklet: Boolean(AudioCtx && "audioWorklet" in AudioCtx.prototype),
2675
+ isSecureContext: Boolean(window.isSecureContext)
2676
+ };
2677
+ }
2678
+ async probeCompanion(timeoutMs = 700) {
2679
+ const ctrl = new AbortController();
2680
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
2681
+ try {
2682
+ const res = await this.loopbackFetch(`${this.httpBase}/api/health`, {
2683
+ cache: "no-store",
2684
+ signal: ctrl.signal
2685
+ });
2686
+ if (!res.ok) return { online: false };
2687
+ const data = await res.json();
2688
+ return {
2689
+ online: Boolean(data.ok),
2690
+ version: data.version,
2691
+ protocolVersion: typeof data.protocolVersion === "number" ? data.protocolVersion : 1,
2692
+ platform: data.platform
2693
+ };
2694
+ } catch {
2695
+ return { online: false };
2696
+ } finally {
2697
+ clearTimeout(timer);
2698
+ }
2699
+ }
2700
+ /**
2701
+ * Acquires a short-lived cryptographic session token from Gamepadly Link v2+ (`POST /api/session`).
2702
+ * Uses a custom header (`X-Gamepadly-Client: web`) so browsers enforce CORS preflight.
2703
+ */
2704
+ async acquireCompanionSession() {
2705
+ const res = await this.loopbackFetch(`${this.httpBase}/api/session`, {
2706
+ method: "POST",
2707
+ headers: { "X-Gamepadly-Client": "web" },
2708
+ cache: "no-store"
2709
+ });
2710
+ if (res.status === 404) {
2711
+ this.companionToken = "";
2712
+ return "";
2713
+ }
2714
+ if (!res.ok) {
2715
+ throw new Error(`Gamepadly Link rejected session request (HTTP ${res.status}).`);
2716
+ }
2717
+ const data = await res.json();
2718
+ this.companionToken = typeof data.token === "string" ? data.token : "";
2719
+ return this.companionToken;
2720
+ }
2721
+ async listCompanionDevices() {
2722
+ const res = await this.loopbackFetch(`${this.httpBase}/api/devices`, { cache: "no-store" });
2723
+ if (!res.ok) throw new Error("Gamepadly Link companion did not respond.");
2724
+ const data = await res.json();
2725
+ return Array.isArray(data.devices) ? data.devices : [];
2726
+ }
2727
+ async openWindowsSoundPanelViaCompanion() {
2728
+ try {
2729
+ const token = this.companionToken || await this.acquireCompanionSession();
2730
+ const headers = {};
2731
+ if (token) headers["X-Gamepadly-Token"] = token;
2732
+ const res = await this.loopbackFetch(`${this.httpBase}/api/open-sound-panel`, {
2733
+ method: "POST",
2734
+ headers
2735
+ });
2736
+ return res.ok;
2737
+ } catch {
2738
+ return false;
2739
+ }
2740
+ }
2741
+ async unlockBrowserDeviceLabels() {
2742
+ if (!navigator.mediaDevices?.getUserMedia) return false;
2743
+ try {
2744
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
2745
+ for (const t of stream.getTracks()) t.stop();
2746
+ return true;
2747
+ } catch {
2748
+ return false;
2749
+ }
2750
+ }
2751
+ async listBrowserOutputDevices() {
2752
+ if (!navigator.mediaDevices?.enumerateDevices) return [];
2753
+ const all = await navigator.mediaDevices.enumerateDevices();
2754
+ return all.filter((d) => d.kind === "audiooutput").map((d) => ({
2755
+ deviceId: d.deviceId,
2756
+ label: d.label || (d.deviceId === "default" ? "System Default" : `Audio Output (${d.deviceId.slice(0, 8)})`),
2757
+ isLikelyDualSense: /wireless controller|dualsense|ps5|dsx/i.test(d.label || "")
2758
+ }));
2759
+ }
2760
+ // =========================================================================
2761
+ // OUTPUT A: PC MAIN SPEAKERS / HEADPHONES
2762
+ // =========================================================================
2763
+ async initPcOutput(sinkId = "", sinkLabel = "PC Default Speakers") {
2764
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
2765
+ if (!this.pcCtx) {
2766
+ this.pcCtx = new AudioCtx({ latencyHint: "interactive" });
2767
+ }
2768
+ const ctxWithSink = this.pcCtx;
2769
+ if (sinkId && typeof ctxWithSink.setSinkId === "function") {
2770
+ await ctxWithSink.setSinkId(sinkId);
2771
+ }
2772
+ if (this.pcCtx.state === "suspended") {
2773
+ await this.pcCtx.resume();
2774
+ }
2775
+ if (!this.pcMasterGain) {
2776
+ this.buildPcGraph();
2777
+ }
2778
+ this.pcSinkId = sinkId;
2779
+ this.pcSinkLabel = sinkLabel;
2780
+ return { sinkId: this.pcSinkId, sinkLabel: this.pcSinkLabel, sampleRate: this.pcCtx.sampleRate };
2781
+ }
2782
+ buildPcGraph() {
2783
+ const ctx = this.pcCtx;
2784
+ this.pcMasterGain = ctx.createGain();
2785
+ this.pcMasterGain.gain.value = this.audioMuted ? 0 : this.pcGainValue;
2786
+ const comp = ctx.createDynamicsCompressor();
2787
+ comp.threshold.value = -4;
2788
+ comp.knee.value = 8;
2789
+ comp.ratio.value = 6;
2790
+ const splitter = ctx.createChannelSplitter(2);
2791
+ const anL = ctx.createAnalyser();
2792
+ const anR = ctx.createAnalyser();
2793
+ anL.fftSize = 256;
2794
+ anR.fftSize = 256;
2795
+ anL.smoothingTimeConstant = 0.55;
2796
+ anR.smoothingTimeConstant = 0.55;
2797
+ this.pcMasterGain.connect(comp);
2798
+ comp.connect(ctx.destination);
2799
+ comp.connect(splitter);
2800
+ splitter.connect(anL, 0);
2801
+ splitter.connect(anR, 1);
2802
+ this.pcAnalysers = [anL, anR];
2803
+ this.pcNoiseBuffer = this.createNoiseBuffer(ctx);
2804
+ }
2805
+ // =========================================================================
2806
+ // OUTPUT B: DUALSENSE 4CH (MODE 1: GAMEPADLY LINK COMPANION WASAPI)
2807
+ // =========================================================================
2808
+ async openCompanionWebSocket(deviceId) {
2809
+ const token = await this.acquireCompanionSession();
2810
+ const params = new URLSearchParams();
2811
+ if (token) params.set("token", token);
2812
+ if (deviceId) params.set("device", deviceId);
2813
+ const qs = params.toString();
2814
+ const wsUrl = `${this.wsBase}/ws/haptics${qs ? `?${qs}` : ""}`;
2815
+ return new Promise((resolve, reject) => {
2816
+ const ws = new WebSocket(wsUrl);
2817
+ ws.binaryType = "arraybuffer";
2818
+ const timer = setTimeout(() => {
2819
+ ws.close();
2820
+ reject(new Error("Gamepadly Link WASAPI handshake timeout."));
2821
+ }, 5e3);
2822
+ ws.onmessage = (evt) => {
2823
+ if (typeof evt.data !== "string") return;
2824
+ try {
2825
+ const msg = JSON.parse(evt.data);
2826
+ if (msg.type === "ready") {
2827
+ clearTimeout(timer);
2828
+ resolve({ ws, ready: msg });
2829
+ } else if (msg.type === "error") {
2830
+ clearTimeout(timer);
2831
+ ws.close();
2832
+ reject(new Error(msg.message || "WASAPI renderer failed to initialize."));
2833
+ }
2834
+ } catch {
2835
+ }
2836
+ };
2837
+ ws.onerror = () => {
2838
+ clearTimeout(timer);
2839
+ reject(new Error("Failed to connect to Gamepadly Link WebSocket (check LNA loopback permission)."));
2840
+ };
2841
+ });
2842
+ }
2843
+ attachWsReconnectHandler(ws, deviceId) {
2844
+ ws.onclose = () => {
2845
+ if (this.dsWs !== ws) return;
2846
+ this.dsWs = null;
2847
+ if (this.intentionalWsClose || this.dsMode !== "companion") {
2848
+ this.emitStreamState("idle");
2849
+ return;
2850
+ }
2851
+ if (this.reconnectAttempts >= 3) {
2852
+ this.emitStreamState("disconnected", "Gamepadly Link connection lost. Click Connect to retry.");
2853
+ return;
2854
+ }
2855
+ const delayMs = 800 * Math.pow(2, this.reconnectAttempts);
2856
+ this.reconnectAttempts++;
2857
+ this.emitStreamState("reconnecting", `Reconnecting to Gamepadly Link (${this.reconnectAttempts}/3)...`);
2858
+ this.reconnectTimer = window.setTimeout(async () => {
2859
+ this.reconnectTimer = null;
2860
+ if (this.intentionalWsClose || this.dsMode !== "companion") return;
2861
+ try {
2862
+ const { ws: newWs } = await this.openCompanionWebSocket(deviceId);
2863
+ this.dsWs = newWs;
2864
+ this.reconnectAttempts = 0;
2865
+ this.attachWsReconnectHandler(newWs, deviceId);
2866
+ this.emitStreamState("connected", "Gamepadly Link reconnected.");
2867
+ } catch {
2868
+ if (this.reconnectAttempts < 3) {
2869
+ this.attachWsReconnectHandler(ws, deviceId);
2870
+ ws.onclose?.(new CloseEvent("close"));
2871
+ } else {
2872
+ this.emitStreamState("disconnected", "Gamepadly Link offline.");
2873
+ }
2874
+ }
2875
+ }, delayMs);
2876
+ };
2877
+ }
2878
+ async connectDualSenseCompanion(deviceId = "", deviceLabel = "DualSense WASAPI") {
2879
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
2880
+ await this.teardownDsOutput();
2881
+ this.intentionalWsClose = false;
2882
+ this.reconnectAttempts = 0;
2883
+ const { ws, ready } = await this.openCompanionWebSocket(deviceId);
2884
+ this.dsWs = ws;
2885
+ this.attachWsReconnectHandler(ws, ready.id || deviceId);
2886
+ this.emitStreamState("connected");
2887
+ const sr = ready.sampleRate || 48e3;
2888
+ this.dsCtx = new AudioCtx({ sampleRate: sr, latencyHint: "interactive" });
2889
+ if (this.dsCtx.state === "suspended") {
2890
+ await this.dsCtx.resume();
2891
+ }
2892
+ await this.dsCtx.audioWorklet.addModule("/haptic-worklet.js");
2893
+ this.dsMode = "companion";
2894
+ this.dsSinkId = ready.id || deviceId;
2895
+ this.dsSinkLabel = ready.name || deviceLabel;
2896
+ this.dsMaxChannelCount = ready.channels || 4;
2897
+ this.dsActiveChannelCount = Math.min(4, this.dsMaxChannelCount);
2898
+ this.buildDsGraph(false);
2899
+ this.dsWorklet = new AudioWorkletNode(this.dsCtx, "gamepadly-wasapi-capture", {
2900
+ numberOfInputs: 1,
2901
+ numberOfOutputs: 1,
2902
+ outputChannelCount: [1],
2903
+ channelCount: 4,
2904
+ channelCountMode: "explicit",
2905
+ channelInterpretation: "discrete"
2906
+ });
2907
+ const muteSink = this.dsCtx.createGain();
2908
+ muteSink.gain.value = 0;
2909
+ this.dsMerger.connect(this.dsWorklet);
2910
+ this.dsWorklet.connect(muteSink);
2911
+ muteSink.connect(this.dsCtx.destination);
2912
+ this.dsWorklet.port.onmessage = (evt) => {
2913
+ if (this.dsWs && this.dsWs.readyState === WebSocket.OPEN) {
2914
+ this.dsWs.send(evt.data);
2915
+ }
2916
+ };
2917
+ return {
2918
+ mode: "companion",
2919
+ sinkId: this.dsSinkId,
2920
+ sinkLabel: this.dsSinkLabel,
2921
+ sampleRate: this.dsCtx.sampleRate,
2922
+ maxChannelCount: this.dsMaxChannelCount,
2923
+ activeChannelCount: this.dsActiveChannelCount,
2924
+ isQuadraphonicReady: this.dsMaxChannelCount >= 4,
2925
+ state: this.dsCtx.state
2926
+ };
2927
+ }
2928
+ // =========================================================================
2929
+ // OUTPUT B: DUALSENSE 4CH (MODE 2: ZERO-INSTALL BROWSER setSinkId)
2930
+ // =========================================================================
2931
+ async connectDualSenseBrowserSink(sinkId, sinkLabel) {
2932
+ if (!sinkId) {
2933
+ throw new Error("DualSense audio output device ID is empty.");
2934
+ }
2935
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
2936
+ await this.teardownDsOutput();
2937
+ try {
2938
+ this.dsCtx = new AudioCtx({
2939
+ latencyHint: "interactive",
2940
+ sinkId
2941
+ });
2942
+ } catch {
2943
+ this.dsCtx = new AudioCtx({ latencyHint: "interactive" });
2944
+ }
2945
+ const ctxWithSink = this.dsCtx;
2946
+ if (typeof ctxWithSink.setSinkId === "function" && ctxWithSink.sinkId !== sinkId) {
2947
+ await ctxWithSink.setSinkId(sinkId);
2948
+ }
2949
+ if (this.dsCtx.state === "suspended") {
2950
+ await this.dsCtx.resume();
2951
+ }
2952
+ const dest = this.dsCtx.destination;
2953
+ this.dsMaxChannelCount = dest.maxChannelCount;
2954
+ const target = this.dsMaxChannelCount >= 4 ? 4 : Math.min(2, this.dsMaxChannelCount);
2955
+ dest.channelCountMode = "explicit";
2956
+ dest.channelInterpretation = "discrete";
2957
+ dest.channelCount = target;
2958
+ this.dsActiveChannelCount = dest.channelCount;
2959
+ this.dsMode = "setsinkid";
2960
+ this.dsSinkId = sinkId;
2961
+ this.dsSinkLabel = sinkLabel;
2962
+ this.buildDsGraph(true);
2963
+ return {
2964
+ mode: "setsinkid",
2965
+ sinkId: this.dsSinkId,
2966
+ sinkLabel: this.dsSinkLabel,
2967
+ sampleRate: this.dsCtx.sampleRate,
2968
+ maxChannelCount: this.dsMaxChannelCount,
2969
+ activeChannelCount: this.dsActiveChannelCount,
2970
+ isQuadraphonicReady: this.dsMaxChannelCount >= 4,
2971
+ state: this.dsCtx.state
2972
+ };
2973
+ }
2974
+ buildDsGraph(connectDirectlyToDest) {
2975
+ const ctx = this.dsCtx;
2976
+ this.dsMerger = ctx.createChannelMerger(4);
2977
+ this.dsChGains = [];
2978
+ this.dsAnalysers = [];
2979
+ for (let ch = 0; ch < 4; ch++) {
2980
+ const gain = ctx.createGain();
2981
+ gain.gain.value = ch < 2 ? this.dsSpeakerGainValue : this.dsHapticGainValue;
2982
+ let chainHead = gain;
2983
+ if (ch >= 2) {
2984
+ const dcBlocker = ctx.createBiquadFilter();
2985
+ dcBlocker.type = "highpass";
2986
+ dcBlocker.frequency.value = 20;
2987
+ dcBlocker.Q.value = 0.707;
2988
+ gain.connect(dcBlocker);
2989
+ chainHead = dcBlocker;
2990
+ }
2991
+ const comp = ctx.createDynamicsCompressor();
2992
+ comp.threshold.value = -3;
2993
+ comp.knee.value = 6;
2994
+ comp.ratio.value = 12;
2995
+ comp.attack.value = 15e-4;
2996
+ comp.release.value = 0.05;
2997
+ const analyser = ctx.createAnalyser();
2998
+ analyser.fftSize = 256;
2999
+ analyser.smoothingTimeConstant = 0.5;
3000
+ chainHead.connect(comp);
3001
+ comp.connect(analyser);
3002
+ analyser.connect(this.dsMerger, 0, ch);
3003
+ this.dsChGains.push(gain);
3004
+ this.dsAnalysers.push(analyser);
3005
+ }
3006
+ if (connectDirectlyToDest) {
3007
+ this.dsMerger.connect(ctx.destination);
3008
+ }
3009
+ this.dsNoiseBuffer = this.createNoiseBuffer(ctx);
3010
+ }
3011
+ async teardownDsOutput() {
3012
+ this.intentionalWsClose = true;
3013
+ if (this.reconnectTimer !== null) {
3014
+ window.clearTimeout(this.reconnectTimer);
3015
+ this.reconnectTimer = null;
3016
+ }
3017
+ this.stopAllContinuous();
3018
+ if (this.dsWorklet) {
3019
+ try {
3020
+ this.dsWorklet.port.onmessage = null;
3021
+ this.dsWorklet.disconnect();
3022
+ } catch {
3023
+ }
3024
+ this.dsWorklet = null;
3025
+ }
3026
+ if (this.dsWs) {
3027
+ try {
3028
+ this.dsWs.close();
3029
+ } catch {
3030
+ }
3031
+ this.dsWs = null;
3032
+ }
3033
+ if (this.dsCtx) {
3034
+ try {
3035
+ await this.dsCtx.close();
3036
+ } catch {
3037
+ }
3038
+ this.dsCtx = null;
3039
+ }
3040
+ this.dsMerger = null;
3041
+ this.dsChGains = [];
3042
+ this.dsAnalysers = [];
3043
+ this.dsNoiseBuffer = null;
3044
+ this.dsMode = "none";
3045
+ }
3046
+ createNoiseBuffer(ctx) {
3047
+ const len = ctx.sampleRate * 2;
3048
+ const buf = ctx.createBuffer(1, len, ctx.sampleRate);
3049
+ const ch = buf.getChannelData(0);
3050
+ for (let i = 0; i < len; i++) ch[i] = Math.random() * 2 - 1;
3051
+ return buf;
3052
+ }
3053
+ async resumeAll() {
3054
+ if (!this.pcCtx) {
3055
+ await this.initPcOutput("", this.pcSinkLabel);
3056
+ }
3057
+ if (this.pcCtx && this.pcCtx.state === "suspended") await this.pcCtx.resume();
3058
+ if (this.dsCtx && this.dsCtx.state === "suspended") await this.dsCtx.resume();
3059
+ }
3060
+ setGains(gains) {
3061
+ if (gains.pc !== void 0) {
3062
+ this.pcGainValue = Math.max(0, Math.min(1.4, gains.pc));
3063
+ if (this.pcMasterGain && this.pcCtx) {
3064
+ this.pcMasterGain.gain.setTargetAtTime(this.pcGainValue, this.pcCtx.currentTime, 0.02);
3065
+ }
3066
+ }
3067
+ if (gains.dsSpeaker !== void 0) {
3068
+ this.dsSpeakerGainValue = Math.max(0, Math.min(1.3, gains.dsSpeaker));
3069
+ if (this.dsChGains.length >= 2 && this.dsCtx) {
3070
+ this.dsChGains[0].gain.setTargetAtTime(this.dsSpeakerGainValue, this.dsCtx.currentTime, 0.02);
3071
+ this.dsChGains[1].gain.setTargetAtTime(this.dsSpeakerGainValue, this.dsCtx.currentTime, 0.02);
3072
+ }
3073
+ }
3074
+ if (gains.dsHaptic !== void 0) {
3075
+ this.dsHapticGainValue = Math.max(0, Math.min(1.4, gains.dsHaptic));
3076
+ if (this.dsChGains.length >= 4 && this.dsCtx) {
3077
+ this.dsChGains[2].gain.setTargetAtTime(this.dsHapticGainValue, this.dsCtx.currentTime, 0.02);
3078
+ this.dsChGains[3].gain.setTargetAtTime(this.dsHapticGainValue, this.dsCtx.currentTime, 0.02);
3079
+ }
3080
+ }
3081
+ }
3082
+ getWaveforms() {
3083
+ const read = (an) => {
3084
+ if (!an) return null;
3085
+ const arr = new Float32Array(an.fftSize);
3086
+ an.getFloatTimeDomainData(arr);
3087
+ return arr;
3088
+ };
3089
+ return {
3090
+ pcL: read(this.pcAnalysers[0]),
3091
+ pcR: read(this.pcAnalysers[1]),
3092
+ dsCh0: read(this.dsAnalysers[0]),
3093
+ dsCh1: read(this.dsAnalysers[1]),
3094
+ dsCh2: read(this.dsAnalysers[2]),
3095
+ dsCh3: read(this.dsAnalysers[3])
3096
+ };
3097
+ }
3098
+ getHapticEnergy() {
3099
+ if (this.dsAnalysers.length < 4) return { left: 0, right: 0 };
3100
+ const rms = (an) => {
3101
+ const buf = new Float32Array(an.fftSize);
3102
+ an.getFloatTimeDomainData(buf);
3103
+ let s = 0;
3104
+ for (let i = 0; i < buf.length; i++) s += buf[i] * buf[i];
3105
+ return Math.min(1, Math.sqrt(s / buf.length) * 3.5);
3106
+ };
3107
+ return { left: rms(this.dsAnalysers[2]), right: rms(this.dsAnalysers[3]) };
3108
+ }
3109
+ stopAllContinuous() {
3110
+ for (const h of Array.from(this.activeContinuous)) {
3111
+ try {
3112
+ h.stop();
3113
+ } catch {
3114
+ }
3115
+ }
3116
+ this.activeContinuous.clear();
3117
+ }
3118
+ // =========================================================================
3119
+ // LOW-LEVEL ROUTING HELPERS
3120
+ // =========================================================================
3121
+ routePc(node, pan = 0, gain = 1) {
3122
+ if (!this.pcCtx || !this.pcMasterGain) return;
3123
+ const g = this.pcCtx.createGain();
3124
+ g.gain.value = gain;
3125
+ const panner = this.pcCtx.createStereoPanner();
3126
+ panner.pan.value = Math.max(-1, Math.min(1, pan));
3127
+ node.connect(g);
3128
+ g.connect(panner);
3129
+ panner.connect(this.pcMasterGain);
3130
+ }
3131
+ routeDsSpeakerMonoSafe(node, gain = 0.9) {
3132
+ if (!this.dsCtx || this.dsChGains.length < 2) return;
3133
+ const g = this.dsCtx.createGain();
3134
+ g.gain.value = gain;
3135
+ node.connect(g);
3136
+ g.connect(this.dsChGains[0]);
3137
+ g.connect(this.dsChGains[1]);
3138
+ }
3139
+ routeDsVcm(node, pan = 0, gain = 1) {
3140
+ if (!this.dsCtx || this.dsChGains.length < 4) return;
3141
+ const p = Math.max(-1, Math.min(1, pan));
3142
+ const gL = this.dsCtx.createGain();
3143
+ const gR = this.dsCtx.createGain();
3144
+ gL.gain.value = Math.cos((p + 1) * Math.PI / 4) * gain;
3145
+ gR.gain.value = Math.sin((p + 1) * Math.PI / 4) * gain;
3146
+ node.connect(gL);
3147
+ node.connect(gR);
3148
+ gL.connect(this.dsChGains[2]);
3149
+ gR.connect(this.dsChGains[3]);
3150
+ }
3151
+ // =========================================================================
3152
+ // SEMANTIC 3-LAYER SYNTHESIS PRIMITIVES (USED BY @gamepadly/game-sdk)
3153
+ // =========================================================================
3154
+ playPcTone(spec) {
3155
+ if (!this.pcCtx) return;
3156
+ const ctx = this.pcCtx;
3157
+ const start = ctx.currentTime + (spec.delayMs || 0) / 1e3;
3158
+ const dur = Math.max(0.015, spec.durationMs / 1e3);
3159
+ const osc = ctx.createOscillator();
3160
+ osc.type = spec.wave || "sine";
3161
+ osc.frequency.setValueAtTime(Math.max(20, spec.freqHz), start);
3162
+ if (spec.endFreqHz && spec.endFreqHz > 0) {
3163
+ osc.frequency.exponentialRampToValueAtTime(Math.max(20, spec.endFreqHz), start + dur);
3164
+ }
3165
+ const env = ctx.createGain();
3166
+ const amp = Math.max(1e-3, Math.min(1, spec.intensity ?? 0.45));
3167
+ env.gain.setValueAtTime(1e-4, start);
3168
+ env.gain.linearRampToValueAtTime(amp, start + Math.min(0.012, dur * 0.2));
3169
+ env.gain.exponentialRampToValueAtTime(1e-4, start + dur);
3170
+ osc.connect(env);
3171
+ this.routePc(env, spec.pan ?? 0, 1);
3172
+ osc.start(start);
3173
+ osc.stop(start + dur + 0.02);
3174
+ }
3175
+ playPcNoiseBurst(opts) {
3176
+ if (!this.pcCtx || !this.pcNoiseBuffer) return;
3177
+ const ctx = this.pcCtx;
3178
+ const start = ctx.currentTime + (opts.delayMs || 0) / 1e3;
3179
+ const dur = Math.max(0.02, opts.durationMs / 1e3);
3180
+ const src = ctx.createBufferSource();
3181
+ src.buffer = this.pcNoiseBuffer;
3182
+ const flt = ctx.createBiquadFilter();
3183
+ flt.type = opts.filterType || "bandpass";
3184
+ flt.Q.value = opts.q ?? 2;
3185
+ flt.frequency.setValueAtTime(opts.freqHz, start);
3186
+ if (opts.endFreqHz) {
3187
+ flt.frequency.exponentialRampToValueAtTime(Math.max(30, opts.endFreqHz), start + dur);
3188
+ }
3189
+ const env = ctx.createGain();
3190
+ const amp = Math.max(1e-3, Math.min(1, opts.intensity ?? 0.5));
3191
+ env.gain.setValueAtTime(1e-4, start);
3192
+ env.gain.linearRampToValueAtTime(amp, start + Math.min(0.015, dur * 0.15));
3193
+ env.gain.exponentialRampToValueAtTime(1e-4, start + dur);
3194
+ src.connect(flt);
3195
+ flt.connect(env);
3196
+ this.routePc(env, opts.pan ?? 0, 1);
3197
+ src.start(start);
3198
+ src.stop(start + dur + 0.03);
3199
+ }
3200
+ playControllerSpeakerTone(spec) {
3201
+ if (!this.dsCtx || this.dsChGains.length < 2) {
3202
+ this.playPcTone({ ...spec, intensity: (spec.intensity ?? 0.5) * 0.45 });
3203
+ return;
3204
+ }
3205
+ const ctx = this.dsCtx;
3206
+ const start = ctx.currentTime + (spec.delayMs || 0) / 1e3;
3207
+ const dur = Math.max(0.015, spec.durationMs / 1e3);
3208
+ const osc = ctx.createOscillator();
3209
+ osc.type = spec.wave || "triangle";
3210
+ osc.frequency.setValueAtTime(Math.max(60, spec.freqHz), start);
3211
+ if (spec.endFreqHz && spec.endFreqHz > 0) {
3212
+ osc.frequency.exponentialRampToValueAtTime(Math.max(60, spec.endFreqHz), start + dur);
3213
+ }
3214
+ const env = ctx.createGain();
3215
+ const amp = Math.max(1e-3, Math.min(1, spec.intensity ?? 0.75));
3216
+ env.gain.setValueAtTime(1e-4, start);
3217
+ env.gain.linearRampToValueAtTime(amp, start + Math.min(6e-3, dur * 0.18));
3218
+ env.gain.exponentialRampToValueAtTime(1e-4, start + dur);
3219
+ osc.connect(env);
3220
+ this.routeDsSpeakerMonoSafe(env, 0.95);
3221
+ osc.start(start);
3222
+ osc.stop(start + dur + 0.02);
3223
+ }
3224
+ playHapticPulse(spec) {
3225
+ if (!this.dsCtx || this.dsChGains.length < 4) return;
3226
+ const ctx = this.dsCtx;
3227
+ const start = ctx.currentTime + (spec.delayMs || 0) / 1e3;
3228
+ const dur = Math.max(0.012, spec.durationMs / 1e3);
3229
+ const osc = ctx.createOscillator();
3230
+ osc.type = spec.wave || "sine";
3231
+ osc.frequency.setValueAtTime(Math.max(22, spec.freqHz), start);
3232
+ if (spec.endFreqHz && spec.endFreqHz > 0) {
3233
+ osc.frequency.exponentialRampToValueAtTime(Math.max(22, spec.endFreqHz), start + dur);
3234
+ }
3235
+ const env = ctx.createGain();
3236
+ const amp = Math.max(1e-3, Math.min(1, spec.intensity));
3237
+ env.gain.setValueAtTime(1e-4, start);
3238
+ env.gain.linearRampToValueAtTime(amp, start + Math.min(4e-3, dur * 0.2));
3239
+ env.gain.exponentialRampToValueAtTime(1e-4, start + dur);
3240
+ osc.connect(env);
3241
+ this.routeDsVcm(env, spec.pan ?? 0, 1);
3242
+ osc.start(start);
3243
+ osc.stop(start + dur + 0.02);
3244
+ }
3245
+ playHapticSweep(spec) {
3246
+ if (!this.dsCtx || this.dsChGains.length < 4) return;
3247
+ const ctx = this.dsCtx;
3248
+ const now = ctx.currentTime;
3249
+ const dur = Math.max(0.04, spec.durationMs / 1e3);
3250
+ const osc = ctx.createOscillator();
3251
+ osc.type = spec.wave || "sine";
3252
+ osc.frequency.setValueAtTime(Math.max(25, spec.fromHz), now);
3253
+ osc.frequency.exponentialRampToValueAtTime(Math.max(25, spec.toHz), now + dur);
3254
+ const p0 = Math.max(-1, Math.min(1, spec.fromPan));
3255
+ const p1 = Math.max(-1, Math.min(1, spec.toPan));
3256
+ const gL = ctx.createGain();
3257
+ const gR = ctx.createGain();
3258
+ gL.gain.setValueAtTime(Math.cos((p0 + 1) * Math.PI / 4) * spec.intensity, now);
3259
+ gL.gain.linearRampToValueAtTime(Math.cos((p1 + 1) * Math.PI / 4) * spec.intensity, now + dur);
3260
+ gR.gain.setValueAtTime(Math.sin((p0 + 1) * Math.PI / 4) * spec.intensity, now);
3261
+ gR.gain.linearRampToValueAtTime(Math.sin((p1 + 1) * Math.PI / 4) * spec.intensity, now + dur);
3262
+ osc.connect(gL);
3263
+ osc.connect(gR);
3264
+ gL.connect(this.dsChGains[2]);
3265
+ gR.connect(this.dsChGains[3]);
3266
+ osc.start(now);
3267
+ osc.stop(now + dur + 0.02);
3268
+ }
3269
+ createContinuous(preset) {
3270
+ let stopped = false;
3271
+ let dsNodes = null;
3272
+ if (this.dsCtx && this.dsChGains.length >= 4) {
3273
+ const ctx = this.dsCtx;
3274
+ const osc = ctx.createOscillator();
3275
+ const filter = ctx.createBiquadFilter();
3276
+ const master = ctx.createGain();
3277
+ const gL = ctx.createGain();
3278
+ const gR = ctx.createGain();
3279
+ const spkGain = ctx.createGain();
3280
+ master.gain.value = 1e-4;
3281
+ gL.gain.value = 0.7;
3282
+ gR.gain.value = 0.7;
3283
+ spkGain.gain.value = 1e-4;
3284
+ const baseCfg = {
3285
+ ice: { wave: "triangle", f: 240, filtF: 310, spk: 0.25 },
3286
+ metal: { wave: "sine", f: 150, filtF: 180, spk: 0.35 },
3287
+ gravel: { wave: "sawtooth", f: 82, filtF: 150, spk: 0.2 },
3288
+ grass: { wave: "sine", f: 65, filtF: 110, spk: 0.1 },
3289
+ water: { wave: "sine", f: 48, filtF: 85, spk: 0.18 },
3290
+ engine: { wave: "sawtooth", f: 42, filtF: 160, spk: 0.05 },
3291
+ tension: { wave: "sawtooth", f: 78, filtF: 210, spk: 0.4 }
3292
+ };
3293
+ const c = baseCfg[preset];
3294
+ osc.type = c.wave;
3295
+ osc.frequency.value = c.f;
3296
+ filter.type = "lowpass";
3297
+ filter.frequency.value = c.filtF;
3298
+ let noise;
3299
+ if (this.dsNoiseBuffer && (preset === "water" || preset === "gravel" || preset === "ice")) {
3300
+ noise = ctx.createBufferSource();
3301
+ noise.buffer = this.dsNoiseBuffer;
3302
+ noise.loop = true;
3303
+ const nGain = ctx.createGain();
3304
+ nGain.gain.value = 0.45;
3305
+ noise.connect(nGain);
3306
+ nGain.connect(filter);
3307
+ noise.start();
3308
+ }
3309
+ osc.connect(filter);
3310
+ filter.connect(master);
3311
+ master.connect(gL);
3312
+ master.connect(gR);
3313
+ gL.connect(this.dsChGains[2]);
3314
+ gR.connect(this.dsChGains[3]);
3315
+ master.connect(spkGain);
3316
+ spkGain.connect(this.dsChGains[0]);
3317
+ spkGain.connect(this.dsChGains[1]);
3318
+ spkGain.gain.value = c.spk;
3319
+ osc.start();
3320
+ dsNodes = { osc, noise, filter, master, gL, gR, spkGain };
3321
+ }
3322
+ let pcNodes = null;
3323
+ if (this.pcCtx && this.pcMasterGain && (preset === "engine" || preset === "tension" || preset === "water")) {
3324
+ const ctx = this.pcCtx;
3325
+ const osc = ctx.createOscillator();
3326
+ osc.type = preset === "water" ? "sine" : "triangle";
3327
+ osc.frequency.value = preset === "engine" ? 75 : preset === "tension" ? 210 : 120;
3328
+ const gain = ctx.createGain();
3329
+ gain.gain.value = 1e-4;
3330
+ const panner = ctx.createStereoPanner();
3331
+ osc.connect(gain);
3332
+ gain.connect(panner);
3333
+ panner.connect(this.pcMasterGain);
3334
+ osc.start();
3335
+ pcNodes = { osc, gain, panner };
3336
+ }
3337
+ const handle = {
3338
+ update: ({ intensity = 0, speed = 0.5, pan = 0, freqScale = 1 } = {}) => {
3339
+ if (stopped) return;
3340
+ const amp = Math.max(1e-4, Math.min(1, intensity));
3341
+ const p = Math.max(-1, Math.min(1, pan));
3342
+ if (dsNodes && this.dsCtx) {
3343
+ const now = this.dsCtx.currentTime;
3344
+ dsNodes.master.gain.setTargetAtTime(amp * 0.85, now, 0.025);
3345
+ dsNodes.gL.gain.setTargetAtTime(Math.cos((p + 1) * Math.PI / 4), now, 0.025);
3346
+ dsNodes.gR.gain.setTargetAtTime(Math.sin((p + 1) * Math.PI / 4), now, 0.025);
3347
+ const baseF = preset === "tension" ? 68 + speed * 150 : preset === "engine" ? 35 + speed * 95 : 85 + speed * 140;
3348
+ dsNodes.osc.frequency.setTargetAtTime(Math.max(25, baseF * freqScale), now, 0.03);
3349
+ }
3350
+ if (pcNodes && this.pcCtx) {
3351
+ const now = this.pcCtx.currentTime;
3352
+ pcNodes.gain.gain.setTargetAtTime(amp * 0.22, now, 0.03);
3353
+ pcNodes.panner.pan.setTargetAtTime(p * 0.7, now, 0.03);
3354
+ const pcF = preset === "tension" ? 180 + speed * 260 : 70 + speed * 160;
3355
+ pcNodes.osc.frequency.setTargetAtTime(Math.max(30, pcF * freqScale), now, 0.03);
3356
+ }
3357
+ },
3358
+ stop: () => {
3359
+ if (stopped) return;
3360
+ stopped = true;
3361
+ this.activeContinuous.delete(handle);
3362
+ try {
3363
+ if (dsNodes) {
3364
+ dsNodes.osc.stop();
3365
+ dsNodes.noise?.stop();
3366
+ dsNodes.master.disconnect();
3367
+ dsNodes.spkGain.disconnect();
3368
+ }
3369
+ if (pcNodes) {
3370
+ pcNodes.osc.stop();
3371
+ pcNodes.gain.disconnect();
3372
+ }
3373
+ } catch {
3374
+ }
3375
+ }
3376
+ };
3377
+ this.activeContinuous.add(handle);
3378
+ return handle;
3379
+ }
3380
+ playComboPreset(id, pan = 0) {
3381
+ switch (id) {
3382
+ case "ratchet_tick":
3383
+ this.playHapticPulse({ pan, freqHz: 215, endFreqHz: 115, durationMs: 18, intensity: 0.52, wave: "triangle" });
3384
+ this.playControllerSpeakerTone({ freqHz: 2100, endFreqHz: 1150, durationMs: 16, intensity: 0.45, wave: "triangle" });
3385
+ break;
3386
+ case "lock_sweet_spot":
3387
+ this.playHapticPulse({ pan: -0.45, freqHz: 145, endFreqHz: 68, durationMs: 65, intensity: 0.95, wave: "sine" });
3388
+ this.playHapticPulse({ pan: 0.45, freqHz: 285, endFreqHz: 170, durationMs: 48, intensity: 0.75, wave: "triangle", delayMs: 14 });
3389
+ this.playControllerSpeakerTone({ freqHz: 1480, endFreqHz: 860, durationMs: 75, intensity: 0.85, wave: "sine" });
3390
+ this.playPcTone({ freqHz: 440, endFreqHz: 330, durationMs: 110, intensity: 0.28, pan, wave: "sine" });
3391
+ break;
3392
+ case "lock_unlock":
3393
+ this.playHapticSweep({ fromPan: -0.95, toPan: 0.95, fromHz: 65, toHz: 185, durationMs: 260, intensity: 0.95 });
3394
+ this.playControllerSpeakerTone({ freqHz: 980, endFreqHz: 1560, durationMs: 120, intensity: 0.85, wave: "triangle" });
3395
+ this.playControllerSpeakerTone({ freqHz: 1560, endFreqHz: 2093, durationMs: 180, intensity: 0.8, delayMs: 120, wave: "sine" });
3396
+ this.playPcNoiseBurst({ durationMs: 520, filterType: "lowpass", freqHz: 280, endFreqHz: 65, intensity: 0.85 });
3397
+ this.playPcTone({ freqHz: 523.25, endFreqHz: 783.99, durationMs: 360, intensity: 0.38, delayMs: 90, wave: "triangle" });
3398
+ break;
3399
+ case "fish_bite":
3400
+ this.playHapticPulse({ pan, freqHz: 95, endFreqHz: 42, durationMs: 110, intensity: 0.95, wave: "sine" });
3401
+ this.playHapticPulse({ pan: -pan * 0.5, freqHz: 165, endFreqHz: 75, durationMs: 75, intensity: 0.8, delayMs: 85 });
3402
+ this.playControllerSpeakerTone({ freqHz: 1250, endFreqHz: 780, durationMs: 95, intensity: 0.85, wave: "sawtooth" });
3403
+ this.playPcNoiseBurst({ durationMs: 240, filterType: "bandpass", freqHz: 1400, endFreqHz: 500, intensity: 0.6, pan });
3404
+ break;
3405
+ case "fish_splash":
3406
+ this.playHapticSweep({ fromPan: pan, toPan: -pan, fromHz: 140, toHz: 52, durationMs: 220, intensity: 0.85 });
3407
+ this.playPcNoiseBurst({ durationMs: 420, filterType: "bandpass", freqHz: 1800, endFreqHz: 420, intensity: 0.72, pan });
3408
+ this.playControllerSpeakerTone({ freqHz: 1600, endFreqHz: 620, durationMs: 110, intensity: 0.55, wave: "triangle" });
3409
+ break;
3410
+ case "pistol":
3411
+ this.playHapticPulse({ pan: 0.2, freqHz: 145, endFreqHz: 42, durationMs: 80, intensity: 1 });
3412
+ this.playHapticPulse({ pan: 0.6, freqHz: 260, endFreqHz: 135, durationMs: 36, intensity: 0.68, delayMs: 55, wave: "triangle" });
3413
+ this.playControllerSpeakerTone({ freqHz: 1850, endFreqHz: 620, durationMs: 48, intensity: 0.85, delayMs: 50, wave: "triangle" });
3414
+ this.playPcNoiseBurst({ durationMs: 190, filterType: "lowpass", freqHz: 3200, endFreqHz: 240, intensity: 0.75 });
3415
+ break;
3416
+ case "shotgun":
3417
+ this.playHapticPulse({ pan: 0, freqHz: 115, endFreqHz: 28, durationMs: 210, intensity: 1 });
3418
+ this.playHapticPulse({ pan: -0.85, freqHz: 210, endFreqHz: 105, durationMs: 50, intensity: 0.85, delayMs: 260, wave: "sawtooth" });
3419
+ this.playHapticPulse({ pan: 0.85, freqHz: 265, endFreqHz: 130, durationMs: 50, intensity: 0.85, delayMs: 390, wave: "sawtooth" });
3420
+ this.playControllerSpeakerTone({ freqHz: 1100, endFreqHz: 520, durationMs: 55, intensity: 0.85, delayMs: 260, wave: "sawtooth" });
3421
+ this.playControllerSpeakerTone({ freqHz: 1450, endFreqHz: 740, durationMs: 55, intensity: 0.85, delayMs: 390, wave: "sawtooth" });
3422
+ this.playPcNoiseBurst({ durationMs: 420, filterType: "lowpass", freqHz: 2800, endFreqHz: 110, intensity: 0.95 });
3423
+ break;
3424
+ case "bow_release":
3425
+ this.playHapticPulse({ pan: -0.35, freqHz: 240, endFreqHz: 72, durationMs: 150, intensity: 0.95, wave: "triangle" });
3426
+ this.playControllerSpeakerTone({ freqHz: 920, endFreqHz: 360, durationMs: 120, intensity: 0.85, wave: "triangle" });
3427
+ this.playPcNoiseBurst({ durationMs: 210, filterType: "bandpass", freqHz: 2200, endFreqHz: 600, intensity: 0.55 });
3428
+ break;
3429
+ case "thunder":
3430
+ this.playPcNoiseBurst({ durationMs: 1650, filterType: "lowpass", freqHz: 520, endFreqHz: 68, intensity: 0.95, pan });
3431
+ this.playHapticPulse({ pan, freqHz: 82, endFreqHz: 28, durationMs: 950, intensity: 1, wave: "sawtooth" });
3432
+ break;
3433
+ }
3434
+ }
3435
+ // =========================================================================
3436
+ // CALIBRATION & HARDWARE SELF-TESTS
3437
+ // =========================================================================
3438
+ async testPcSpeakersLoud() {
3439
+ await this.resumeAll();
3440
+ this.playPcTone({ freqHz: 523.25, durationMs: 240, intensity: 0.55, pan: -0.85, wave: "sine" });
3441
+ this.playPcTone({ freqHz: 659.25, durationMs: 260, intensity: 0.55, pan: 0.85, delayMs: 260, wave: "sine" });
3442
+ }
3443
+ async testDualSenseSpeakerLoud() {
3444
+ await this.resumeAll();
3445
+ if (!this.dsCtx || this.dsChGains.length < 2) {
3446
+ throw new Error("DualSense 4-channel audio is not connected yet.");
3447
+ }
3448
+ const notes = [880, 1174.66, 1318.51];
3449
+ notes.forEach((f, idx) => {
3450
+ this.playControllerSpeakerTone({ freqHz: f, durationMs: 200, intensity: 0.95, delayMs: idx * 210, wave: "triangle" });
3451
+ });
3452
+ }
3453
+ async testDualSenseVcmLoud() {
3454
+ await this.resumeAll();
3455
+ if (!this.dsCtx || this.dsChGains.length < 4) {
3456
+ throw new Error("DualSense 4-channel audio is not connected yet.");
3457
+ }
3458
+ this.playHapticPulse({ pan: -0.95, freqHz: 55, endFreqHz: 180, durationMs: 520, intensity: 0.95 });
3459
+ this.playHapticPulse({ pan: 0.95, freqHz: 180, endFreqHz: 55, durationMs: 520, intensity: 0.95, delayMs: 560 });
3460
+ }
3461
+ async runThreeLayerCalibration(onStep) {
3462
+ await this.resumeAll();
3463
+ onStep(1);
3464
+ this.playPcTone({ freqHz: 523.25, durationMs: 320, intensity: 0.5, pan: -0.9 });
3465
+ this.playPcTone({ freqHz: 659.25, durationMs: 320, intensity: 0.5, pan: 0.9, delayMs: 340 });
3466
+ setTimeout(() => {
3467
+ onStep(2);
3468
+ this.playControllerSpeakerTone({ freqHz: 880, endFreqHz: 1174.66, durationMs: 480, intensity: 0.95, wave: "triangle" });
3469
+ }, 760);
3470
+ setTimeout(() => {
3471
+ onStep(3);
3472
+ this.playHapticPulse({ pan: -1, freqHz: 45, endFreqHz: 210, durationMs: 650, intensity: 0.95 });
3473
+ }, 1350);
3474
+ setTimeout(() => {
3475
+ onStep(4);
3476
+ this.playHapticPulse({ pan: 1, freqHz: 210, endFreqHz: 45, durationMs: 650, intensity: 0.95 });
3477
+ }, 2100);
3478
+ setTimeout(() => {
3479
+ onStep(5);
3480
+ this.playHapticSweep({ fromPan: -1, toPan: 1, fromHz: 110, toHz: 145, durationMs: 850, intensity: 0.95 });
3481
+ this.playPcTone({ freqHz: 392, endFreqHz: 523.25, durationMs: 820, intensity: 0.35, wave: "triangle" });
3482
+ }, 2850);
3483
+ setTimeout(() => onStep(6), 3800);
3484
+ }
3485
+ };
3486
+
3487
+ // src/link/index.ts
3488
+ function createLinkAudio(options) {
3489
+ return new ThreeLayerAudioEngine(options);
3490
+ }
3491
+
3492
+ // src/bridge/profiles.ts
3493
+ var BUILTIN_BRIDGE_PROFILES = {
3494
+ platformer: {
3495
+ name: "Platformer (WASD / Arrows + Space Jump)",
3496
+ keys: {
3497
+ left: "ArrowLeft",
3498
+ right: "ArrowRight",
3499
+ up: "ArrowUp",
3500
+ down: "ArrowDown",
3501
+ "lx-": "ArrowLeft",
3502
+ "lx+": "ArrowRight",
3503
+ "ly-": "ArrowUp",
3504
+ "ly+": "ArrowDown",
3505
+ cross: { code: "Space", hapticOnPress: "click" },
3506
+ square: { code: "KeyZ", hapticOnPress: "recoil", hapticPan: 0.4 },
3507
+ circle: { code: "KeyX", hapticOnPress: "click" },
3508
+ r2: { code: "ShiftLeft", hapticOnPress: "boost", hapticPan: 0.6 },
3509
+ options: "Escape"
3510
+ },
3511
+ triggers: {
3512
+ right: "soft_wall"
3513
+ }
3514
+ },
3515
+ "arcade-4way": {
3516
+ name: "Arcade 4-Way (Grid / Puzzle / Snake / Tetris)",
3517
+ keys: {
3518
+ left: { code: "ArrowLeft", repeatMs: 120, hapticOnPress: "ratchet", hapticPan: -0.5 },
3519
+ right: { code: "ArrowRight", repeatMs: 120, hapticOnPress: "ratchet", hapticPan: 0.5 },
3520
+ up: { code: "ArrowUp", repeatMs: 120, hapticOnPress: "ratchet" },
3521
+ down: { code: "ArrowDown", repeatMs: 90, hapticOnPress: "ratchet" },
3522
+ "lx-": { code: "ArrowLeft", repeatMs: 140, hapticOnPress: "ratchet", hapticPan: -0.5 },
3523
+ "lx+": { code: "ArrowRight", repeatMs: 140, hapticOnPress: "ratchet", hapticPan: 0.5 },
3524
+ "ly-": { code: "ArrowUp", repeatMs: 140, hapticOnPress: "ratchet" },
3525
+ "ly+": { code: "ArrowDown", repeatMs: 100, hapticOnPress: "ratchet" },
3526
+ cross: { code: "Space", hapticOnPress: "click" },
3527
+ circle: "Escape",
3528
+ options: "Enter"
3529
+ }
3530
+ },
3531
+ racing: {
3532
+ name: "Racing (Steer + R2 Gas / L2 ABS Brake)",
3533
+ keys: {
3534
+ left: "ArrowLeft",
3535
+ right: "ArrowRight",
3536
+ "lx-": { code: "ArrowLeft", threshold: 0.25 },
3537
+ "lx+": { code: "ArrowRight", threshold: 0.25 },
3538
+ r2: { code: "ArrowUp", threshold: 0.2 },
3539
+ l2: { code: "ArrowDown", threshold: 0.2 },
3540
+ cross: { code: "Space", hapticOnPress: "boost" },
3541
+ square: { code: "ShiftLeft", hapticOnPress: "ratchet" },
3542
+ options: "Escape"
3543
+ },
3544
+ triggers: {
3545
+ left: "abs",
3546
+ right: "bow"
3547
+ }
3548
+ },
3549
+ "twin-stick": {
3550
+ name: "Twin-Stick Shooter (Left Stick Move + Right Stick Aim + R2 Fire)",
3551
+ keys: {
3552
+ "lx-": "KeyA",
3553
+ "lx+": "KeyD",
3554
+ "ly-": "KeyW",
3555
+ "ly+": "KeyS",
3556
+ left: "KeyA",
3557
+ right: "KeyD",
3558
+ up: "KeyW",
3559
+ down: "KeyS",
3560
+ cross: { code: "Space", hapticOnPress: "click" },
3561
+ square: { code: "KeyR", hapticOnPress: "ratchet" },
3562
+ options: "Escape"
3563
+ },
3564
+ pointer: {
3565
+ stick: "right",
3566
+ speedPxPerSec: 720,
3567
+ deadzone: 0.14,
3568
+ clickButton: "r2",
3569
+ secondaryClickButton: "l2",
3570
+ hapticOnClick: "recoil"
3571
+ },
3572
+ triggers: {
3573
+ left: "precision_damp",
3574
+ right: "weapon"
3575
+ }
3576
+ }
3577
+ };
3578
+
3579
+ // src/bridge/index.ts
3580
+ var KEY_CODE_TABLE = {
3581
+ Space: { key: " ", keyCode: 32 },
3582
+ Enter: { key: "Enter", keyCode: 13 },
3583
+ Escape: { key: "Escape", keyCode: 27 },
3584
+ Tab: { key: "Tab", keyCode: 9 },
3585
+ Backspace: { key: "Backspace", keyCode: 8 },
3586
+ ArrowLeft: { key: "ArrowLeft", keyCode: 37 },
3587
+ ArrowUp: { key: "ArrowUp", keyCode: 38 },
3588
+ ArrowRight: { key: "ArrowRight", keyCode: 39 },
3589
+ ArrowDown: { key: "ArrowDown", keyCode: 40 },
3590
+ ShiftLeft: { key: "Shift", keyCode: 16 },
3591
+ ShiftRight: { key: "Shift", keyCode: 16 },
3592
+ ControlLeft: { key: "Control", keyCode: 17 },
3593
+ AltLeft: { key: "Alt", keyCode: 18 }
3594
+ };
3595
+ function inferKeyMeta(rule) {
3596
+ const known = KEY_CODE_TABLE[rule.code];
3597
+ if (known) {
3598
+ return {
3599
+ code: rule.code,
3600
+ key: rule.key ?? known.key,
3601
+ keyCode: rule.keyCode ?? known.keyCode
3602
+ };
3603
+ }
3604
+ if (/^Key[A-Z]$/.test(rule.code)) {
3605
+ const ch = rule.code.slice(3);
3606
+ return {
3607
+ code: rule.code,
3608
+ key: rule.key ?? ch.toLowerCase(),
3609
+ keyCode: rule.keyCode ?? ch.charCodeAt(0)
3610
+ };
3611
+ }
3612
+ if (/^Digit[0-9]$/.test(rule.code)) {
3613
+ const ch = rule.code.slice(5);
3614
+ return {
3615
+ code: rule.code,
3616
+ key: rule.key ?? ch,
3617
+ keyCode: rule.keyCode ?? ch.charCodeAt(0)
3618
+ };
3619
+ }
3620
+ return {
3621
+ code: rule.code,
3622
+ key: rule.key ?? rule.code,
3623
+ keyCode: rule.keyCode ?? 0
3624
+ };
3625
+ }
3626
+ function normalizeRules(entry) {
3627
+ const arr = Array.isArray(entry) ? entry : [entry];
3628
+ return arr.map((item) => typeof item === "string" ? { code: item } : item);
3629
+ }
3630
+ function readSourceValue(source, input) {
3631
+ if (source === "l2") return input.l2;
3632
+ if (source === "r2") return input.r2;
3633
+ if (source === "lx+") return Math.max(0, input.lx);
3634
+ if (source === "lx-") return Math.max(0, -input.lx);
3635
+ if (source === "ly+") return Math.max(0, input.ly);
3636
+ if (source === "ly-") return Math.max(0, -input.ly);
3637
+ if (source === "rx+") return Math.max(0, input.rx);
3638
+ if (source === "rx-") return Math.max(0, -input.rx);
3639
+ if (source === "ry+") return Math.max(0, input.ry);
3640
+ if (source === "ry-") return Math.max(0, -input.ry);
3641
+ return input.buttons[source] ? 1 : 0;
3642
+ }
3643
+ function resolveTriggerSpec(val) {
3644
+ if (!val) return void 0;
3645
+ return typeof val === "string" ? TRIGGER_PRESETS[val] : val;
3646
+ }
3647
+ function isHub(p) {
3648
+ return "active" in p && "getSlots" in p;
3649
+ }
3650
+ function dispatchSyntheticKey(target, type, meta, repeat = false) {
3651
+ if (typeof KeyboardEvent !== "undefined") {
3652
+ const evt = new KeyboardEvent(type, {
3653
+ key: meta.key,
3654
+ code: meta.code,
3655
+ bubbles: true,
3656
+ cancelable: true,
3657
+ repeat
3658
+ });
3659
+ try {
3660
+ Object.defineProperty(evt, "keyCode", { value: meta.keyCode });
3661
+ Object.defineProperty(evt, "which", { value: meta.keyCode });
3662
+ } catch {
3663
+ }
3664
+ target.dispatchEvent(evt);
3665
+ return;
3666
+ }
3667
+ if (typeof Event !== "undefined") {
3668
+ const evt = new Event(type, { bubbles: true, cancelable: true });
3669
+ evt.key = meta.key;
3670
+ evt.code = meta.code;
3671
+ evt.keyCode = meta.keyCode;
3672
+ evt.which = meta.keyCode;
3673
+ evt.repeat = repeat;
3674
+ target.dispatchEvent(evt);
3675
+ }
3676
+ }
3677
+ function dispatchSyntheticPointer(target, type, clientX, clientY, button, buttons) {
3678
+ const init = {
3679
+ bubbles: true,
3680
+ cancelable: true,
3681
+ clientX,
3682
+ clientY,
3683
+ button,
3684
+ buttons,
3685
+ pointerId: 1,
3686
+ pointerType: "mouse",
3687
+ isPrimary: true
3688
+ };
3689
+ if (typeof PointerEvent !== "undefined") {
3690
+ target.dispatchEvent(new PointerEvent(type, init));
3691
+ }
3692
+ const mouseType = type.replace("pointer", "mouse");
3693
+ if (typeof MouseEvent !== "undefined") {
3694
+ target.dispatchEvent(new MouseEvent(mouseType, init));
3695
+ }
3696
+ }
3697
+ function createKeyMouseBridge(options) {
3698
+ const hub = isHub(options.player) ? options.player : null;
3699
+ const player = hub ? hub.active : options.player;
3700
+ const keyTarget = options.keyTarget ?? (typeof window !== "undefined" ? window : void 0);
3701
+ const pointerTarget = options.pointerTarget !== void 0 ? options.pointerTarget : typeof document !== "undefined" ? document.body : null;
3702
+ let profile = typeof options.profile === "string" ? BUILTIN_BRIDGE_PROFILES[options.profile] : options.profile;
3703
+ let running = false;
3704
+ let rafId = 0;
3705
+ let lastFrameAt = 0;
3706
+ const heldKeys = /* @__PURE__ */ new Map();
3707
+ const prevRulePressed = /* @__PURE__ */ new Map();
3708
+ const cursor = {
3709
+ x: 0,
3710
+ y: 0,
3711
+ down: false,
3712
+ secondaryDown: false,
3713
+ visible: false
3714
+ };
3715
+ let cursorInitialized = false;
3716
+ const fireHaptic = (presetOrSpec, opts) => {
3717
+ if (typeof presetOrSpec === "string") {
3718
+ player.haptics.playPreset(presetOrSpec, opts);
3719
+ } else {
3720
+ player.haptics.pulse({
3721
+ ...presetOrSpec,
3722
+ pan: opts?.pan ?? presetOrSpec.pan,
3723
+ intensity: (opts?.intensity ?? 1) * presetOrSpec.intensity
3724
+ });
3725
+ }
3726
+ };
3727
+ const applyProfileTriggers = () => {
3728
+ const left = resolveTriggerSpec(profile.triggers?.left);
3729
+ const right = resolveTriggerSpec(profile.triggers?.right);
3730
+ if (left && right) player.triggers.setBoth(left, right);
3731
+ else if (left) player.triggers.setLeft(left);
3732
+ else if (right) player.triggers.setRight(right);
3733
+ else player.triggers.reset();
3734
+ };
3735
+ const unsubCaps = hub ? hub.onCapabilitiesChange(() => {
3736
+ if (running) applyProfileTriggers();
3737
+ }) : null;
3738
+ const releaseAllHeld = () => {
3739
+ if (keyTarget) {
3740
+ for (const { meta } of heldKeys.values()) {
3741
+ dispatchSyntheticKey(keyTarget, "keyup", meta, false);
3742
+ }
3743
+ }
3744
+ heldKeys.clear();
3745
+ prevRulePressed.clear();
3746
+ if (pointerTarget && (cursor.down || cursor.secondaryDown)) {
3747
+ const rect = pointerTarget.getBoundingClientRect?.() ?? { left: 0, top: 0 };
3748
+ if (cursor.down) {
3749
+ dispatchSyntheticPointer(pointerTarget, "pointerup", rect.left + cursor.x, rect.top + cursor.y, 0, 0);
3750
+ }
3751
+ if (cursor.secondaryDown) {
3752
+ dispatchSyntheticPointer(pointerTarget, "pointerup", rect.left + cursor.x, rect.top + cursor.y, 2, 0);
3753
+ }
3754
+ }
3755
+ cursor.down = false;
3756
+ cursor.secondaryDown = false;
3757
+ };
3758
+ const tick = (dtSec, nowMs = typeof performance !== "undefined" ? performance.now() : Date.now()) => {
3759
+ 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;
3760
+ lastFrameAt = nowMs;
3761
+ const input = player.input.getState();
3762
+ if (!input.connected || input.source === "keyboard_mouse") {
3763
+ if (heldKeys.size > 0 || cursor.down || cursor.secondaryDown) {
3764
+ releaseAllHeld();
3765
+ }
3766
+ return;
3767
+ }
3768
+ const activeCodes = /* @__PURE__ */ new Map();
3769
+ for (const [sourceKey, rawEntry] of Object.entries(profile.keys)) {
3770
+ if (!rawEntry) continue;
3771
+ const source = sourceKey;
3772
+ const val = readSourceValue(source, input);
3773
+ const rules = normalizeRules(rawEntry);
3774
+ for (let i = 0; i < rules.length; i++) {
3775
+ const rule = rules[i];
3776
+ const threshold = rule.threshold ?? 0.45;
3777
+ const pressed = val >= threshold;
3778
+ const ruleKey = `${source}:${rule.code}:${i}`;
3779
+ const wasPressed = prevRulePressed.get(ruleKey) ?? false;
3780
+ prevRulePressed.set(ruleKey, pressed);
3781
+ if (pressed) {
3782
+ const meta = inferKeyMeta(rule);
3783
+ if (!activeCodes.has(meta.code)) {
3784
+ activeCodes.set(meta.code, {
3785
+ meta,
3786
+ repeatMs: rule.repeatMs,
3787
+ repeatDelayMs: rule.repeatDelayMs ?? 220
3788
+ });
3789
+ }
3790
+ if (!wasPressed && rule.hapticOnPress) {
3791
+ fireHaptic(rule.hapticOnPress, { pan: rule.hapticPan });
3792
+ }
3793
+ }
3794
+ }
3795
+ }
3796
+ if (keyTarget) {
3797
+ for (const [code, held] of heldKeys.entries()) {
3798
+ if (!activeCodes.has(code)) {
3799
+ dispatchSyntheticKey(keyTarget, "keyup", held.meta, false);
3800
+ heldKeys.delete(code);
3801
+ }
3802
+ }
3803
+ for (const [code, info] of activeCodes.entries()) {
3804
+ const existing = heldKeys.get(code);
3805
+ if (!existing) {
3806
+ dispatchSyntheticKey(keyTarget, "keydown", info.meta, false);
3807
+ heldKeys.set(code, {
3808
+ meta: info.meta,
3809
+ nextRepeatAt: info.repeatMs ? nowMs + info.repeatDelayMs : Number.POSITIVE_INFINITY
3810
+ });
3811
+ } else if (info.repeatMs && nowMs >= existing.nextRepeatAt) {
3812
+ dispatchSyntheticKey(keyTarget, "keydown", info.meta, true);
3813
+ existing.nextRepeatAt = nowMs + info.repeatMs;
3814
+ }
3815
+ }
3816
+ }
3817
+ if (profile.pointer && pointerTarget) {
3818
+ const cfg = profile.pointer;
3819
+ const rect = pointerTarget.getBoundingClientRect?.() ?? { left: 0, top: 0, width: 800, height: 600 };
3820
+ const w = Math.max(1, rect.width);
3821
+ const h = Math.max(1, rect.height);
3822
+ if (!cursorInitialized) {
3823
+ cursor.x = w / 2;
3824
+ cursor.y = h / 2;
3825
+ cursorInitialized = true;
3826
+ }
3827
+ const dz = cfg.deadzone ?? 0.14;
3828
+ const sx = applyDeadzone(cfg.stick === "left" ? input.lx : input.rx, dz);
3829
+ const sy = applyDeadzone(cfg.stick === "left" ? input.ly : input.ry, dz);
3830
+ const speed = cfg.speedPxPerSec ?? 680;
3831
+ const moved = sx !== 0 || sy !== 0;
3832
+ if (moved) {
3833
+ cursor.x = Math.max(0, Math.min(w, cursor.x + sx * speed * dt));
3834
+ cursor.y = Math.max(0, Math.min(h, cursor.y + sy * speed * dt));
3835
+ cursor.visible = true;
3836
+ }
3837
+ const clickSrc = cfg.clickButton ?? "r2";
3838
+ const secSrc = cfg.secondaryClickButton ?? "l2";
3839
+ const nextDown = readSourceValue(clickSrc, input) >= 0.45;
3840
+ const nextSecDown = readSourceValue(secSrc, input) >= 0.45;
3841
+ const buttonsMask = (nextDown ? 1 : 0) | (nextSecDown ? 2 : 0);
3842
+ const cx = rect.left + cursor.x;
3843
+ const cy = rect.top + cursor.y;
3844
+ if (moved) {
3845
+ dispatchSyntheticPointer(pointerTarget, "pointermove", cx, cy, -1, buttonsMask);
3846
+ }
3847
+ if (nextDown !== cursor.down) {
3848
+ cursor.down = nextDown;
3849
+ cursor.visible = true;
3850
+ dispatchSyntheticPointer(pointerTarget, nextDown ? "pointerdown" : "pointerup", cx, cy, 0, buttonsMask);
3851
+ if (nextDown && cfg.hapticOnClick) {
3852
+ fireHaptic(cfg.hapticOnClick);
3853
+ }
3854
+ }
3855
+ if (nextSecDown !== cursor.secondaryDown) {
3856
+ cursor.secondaryDown = nextSecDown;
3857
+ cursor.visible = true;
3858
+ dispatchSyntheticPointer(pointerTarget, nextSecDown ? "pointerdown" : "pointerup", cx, cy, 2, buttonsMask);
3859
+ }
3860
+ options.onCursorUpdate?.({ ...cursor });
3861
+ }
3862
+ };
3863
+ const loop = (now) => {
3864
+ if (!running) return;
3865
+ tick(void 0, now);
3866
+ rafId = requestAnimationFrame(loop);
3867
+ };
3868
+ return {
3869
+ start() {
3870
+ if (running) return;
3871
+ running = true;
3872
+ lastFrameAt = 0;
3873
+ applyProfileTriggers();
3874
+ if (options.autoRaf !== false && typeof requestAnimationFrame !== "undefined") {
3875
+ rafId = requestAnimationFrame(loop);
3876
+ }
3877
+ },
3878
+ stop() {
3879
+ if (!running) return;
3880
+ running = false;
3881
+ if (rafId && typeof cancelAnimationFrame !== "undefined") {
3882
+ cancelAnimationFrame(rafId);
3883
+ }
3884
+ rafId = 0;
3885
+ releaseAllHeld();
3886
+ },
3887
+ tick,
3888
+ setProfile(next) {
3889
+ releaseAllHeld();
3890
+ profile = typeof next === "string" ? BUILTIN_BRIDGE_PROFILES[next] : next;
3891
+ if (running) applyProfileTriggers();
3892
+ },
3893
+ getCursor() {
3894
+ return { ...cursor };
3895
+ },
3896
+ triggerHaptic: fireHaptic,
3897
+ dispose() {
3898
+ this.stop();
3899
+ unsubCaps?.();
3900
+ player.triggers.reset();
3901
+ }
3902
+ };
3903
+ }
3904
+
3905
+ // src/loop/index.ts
3906
+ function createDisposables() {
3907
+ const cleanups = /* @__PURE__ */ new Set();
3908
+ let disposed = false;
3909
+ const add = (fn) => {
3910
+ if (disposed) {
3911
+ try {
3912
+ fn();
3913
+ } catch {
3914
+ }
3915
+ return () => {
3916
+ };
3917
+ }
3918
+ cleanups.add(fn);
3919
+ return () => {
3920
+ if (cleanups.delete(fn)) {
3921
+ try {
3922
+ fn();
3923
+ } catch {
3924
+ }
3925
+ }
3926
+ };
3927
+ };
3928
+ return {
3929
+ add,
3930
+ on(target, type, listener, options) {
3931
+ target.addEventListener(type, listener, options);
3932
+ return add(() => target.removeEventListener(type, listener, options));
3933
+ },
3934
+ timeout(fn, ms) {
3935
+ const id = setTimeout(() => {
3936
+ cleanups.delete(cancel);
3937
+ if (!disposed) fn();
3938
+ }, ms);
3939
+ const cancel = () => clearTimeout(id);
3940
+ cleanups.add(cancel);
3941
+ return id;
3942
+ },
3943
+ interval(fn, ms) {
3944
+ const id = setInterval(() => {
3945
+ if (!disposed) fn();
3946
+ }, ms);
3947
+ cleanups.add(() => clearInterval(id));
3948
+ return id;
3949
+ },
3950
+ dispose() {
3951
+ if (disposed) return;
3952
+ disposed = true;
3953
+ const list = Array.from(cleanups).reverse();
3954
+ cleanups.clear();
3955
+ for (const fn of list) {
3956
+ try {
3957
+ fn();
3958
+ } catch {
3959
+ }
3960
+ }
3961
+ }
3962
+ };
3963
+ }
3964
+ function createCanvasStage(container, options = {}) {
3965
+ const maxDpr = options.maxDpr ?? 2;
3966
+ const minWidth = options.minWidth ?? 320;
3967
+ const minHeight = options.minHeight ?? 240;
3968
+ const canvas = document.createElement("canvas");
3969
+ canvas.style.width = "100%";
3970
+ canvas.style.height = "100%";
3971
+ canvas.style.display = "block";
3972
+ canvas.style.touchAction = "none";
3973
+ if (options.cursor) canvas.style.cursor = options.cursor;
3974
+ container.innerHTML = "";
3975
+ container.appendChild(canvas);
3976
+ const ctx = canvas.getContext("2d");
3977
+ let width = minWidth;
3978
+ let height = minHeight;
3979
+ let dpr = 1;
3980
+ const resize = () => {
3981
+ const rect = container.getBoundingClientRect();
3982
+ const rawDpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
3983
+ dpr = Math.max(1, Math.min(maxDpr, rawDpr));
3984
+ width = Math.max(minWidth, Math.floor(rect.width || minWidth));
3985
+ height = Math.max(minHeight, Math.floor(rect.height || minHeight));
3986
+ canvas.width = Math.floor(width * dpr);
3987
+ canvas.height = Math.floor(height * dpr);
3988
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
3989
+ options.onResize?.(width, height, dpr);
3990
+ };
3991
+ resize();
3992
+ let ro = null;
3993
+ if (typeof ResizeObserver !== "undefined") {
3994
+ ro = new ResizeObserver(() => resize());
3995
+ ro.observe(container);
3996
+ }
3997
+ const onWinResize = () => resize();
3998
+ if (typeof window !== "undefined") {
3999
+ window.addEventListener("resize", onWinResize);
4000
+ }
4001
+ return {
4002
+ canvas,
4003
+ ctx,
4004
+ get width() {
4005
+ return width;
4006
+ },
4007
+ get height() {
4008
+ return height;
4009
+ },
4010
+ get dpr() {
4011
+ return dpr;
4012
+ },
4013
+ resize,
4014
+ dispose() {
4015
+ ro?.disconnect();
4016
+ ro = null;
4017
+ if (typeof window !== "undefined") {
4018
+ window.removeEventListener("resize", onWinResize);
4019
+ }
4020
+ if (canvas.parentElement === container) {
4021
+ container.removeChild(canvas);
4022
+ }
4023
+ }
4024
+ };
4025
+ }
4026
+ function createGameLoop(options) {
4027
+ const maxDelta = options.maxDelta ?? 0.05;
4028
+ const fixedStep = options.fixedStep;
4029
+ const autoPause = options.autoPauseOnHidden !== false;
4030
+ let running = false;
4031
+ let paused = false;
4032
+ let rafId = 0;
4033
+ let lastNow = 0;
4034
+ let accumulator = 0;
4035
+ const step = (nowMs) => {
4036
+ if (paused) {
4037
+ lastNow = nowMs;
4038
+ return;
4039
+ }
4040
+ if (lastNow === 0) {
4041
+ lastNow = nowMs;
4042
+ }
4043
+ const rawDt = Math.max(0, (nowMs - lastNow) / 1e3);
4044
+ lastNow = nowMs;
4045
+ const dt = Math.min(maxDelta, rawDt);
4046
+ if (fixedStep && fixedStep > 0) {
4047
+ accumulator += dt;
4048
+ let safetySteps = 0;
4049
+ while (accumulator >= fixedStep && safetySteps < 8) {
4050
+ options.onUpdate(fixedStep, nowMs);
4051
+ accumulator -= fixedStep;
4052
+ safetySteps++;
4053
+ }
4054
+ options.onRender?.(accumulator / fixedStep, nowMs);
4055
+ } else {
4056
+ options.onUpdate(dt, nowMs);
4057
+ options.onRender?.(1, nowMs);
4058
+ }
4059
+ };
4060
+ const frame = (nowMs) => {
4061
+ if (!running) return;
4062
+ step(nowMs);
4063
+ rafId = requestAnimationFrame(frame);
4064
+ };
4065
+ const onVisibilityChange = () => {
4066
+ if (!autoPause || typeof document === "undefined") return;
4067
+ if (document.hidden) {
4068
+ lastNow = 0;
4069
+ accumulator = 0;
4070
+ }
4071
+ };
4072
+ if (autoPause && typeof document !== "undefined") {
4073
+ document.addEventListener("visibilitychange", onVisibilityChange);
4074
+ }
4075
+ return {
4076
+ start() {
4077
+ if (running) return;
4078
+ running = true;
4079
+ lastNow = 0;
4080
+ accumulator = 0;
4081
+ if (typeof requestAnimationFrame !== "undefined") {
4082
+ rafId = requestAnimationFrame(frame);
4083
+ }
4084
+ },
4085
+ stop() {
4086
+ if (!running) return;
4087
+ running = false;
4088
+ if (rafId && typeof cancelAnimationFrame !== "undefined") {
4089
+ cancelAnimationFrame(rafId);
4090
+ }
4091
+ rafId = 0;
4092
+ },
4093
+ pause() {
4094
+ paused = true;
4095
+ lastNow = 0;
4096
+ },
4097
+ resume() {
4098
+ paused = false;
4099
+ lastNow = 0;
4100
+ },
4101
+ isPaused() {
4102
+ return paused;
4103
+ },
4104
+ step,
4105
+ dispose() {
4106
+ this.stop();
4107
+ if (autoPause && typeof document !== "undefined") {
4108
+ document.removeEventListener("visibilitychange", onVisibilityChange);
4109
+ }
4110
+ }
4111
+ };
4112
+ }
4113
+ export {
4114
+ BUILTIN_BRIDGE_PROFILES,
4115
+ COMPANION_HTTP_BASE,
4116
+ COMPANION_WS_BASE,
4117
+ DualSenseControllerManager as ControllerManager,
4118
+ DualSenseControllerManager,
4119
+ TACTILE_PRESETS,
4120
+ TRIGGER_PRESETS,
4121
+ ThreeLayerAudioEngine,
4122
+ applyDeadzone,
4123
+ buildSwitchHdFromPulse,
4124
+ crc32WithSeed,
4125
+ createActionTracker,
4126
+ createCanvasStage,
4127
+ createDisposables,
4128
+ createEmptyInput,
4129
+ createGameLoop,
4130
+ createGamepadly,
4131
+ createKeyMouseBridge,
4132
+ createLinkAudio,
4133
+ encodeSwitchHdRumbleSide,
4134
+ encodeTriggerEffect,
4135
+ identifyGamepadFromId,
4136
+ routeHapticPulse,
4137
+ routeHapticSweep,
4138
+ routeTactilePreset
4139
+ };
4140
+ //# sourceMappingURL=browser.js.map