c64-ready 2.4.0 → 3.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 (90) hide show
  1. package/README.md +32 -0
  2. package/bin/admin.mjs +7 -1
  3. package/bin/headless.mjs +1 -1
  4. package/dist/assets/BeachHead-CuSwFD4k.js +1 -0
  5. package/dist/assets/ChuckieEgg-CPqBnAOF.js +1 -0
  6. package/dist/assets/ForbiddenForest-DsQ9jsc8.js +1 -0
  7. package/dist/assets/Galaga-Cutc3p9s.js +1 -0
  8. package/dist/assets/Gribbly-DdZ_hHFt.js +1 -0
  9. package/dist/assets/Hercules-vZYKm7GG.js +1 -0
  10. package/dist/assets/LegendOfWilf-CxSMOjsj.js +1 -0
  11. package/dist/assets/MariosCementFactory-z0IZ0q30.js +1 -0
  12. package/dist/assets/MoleAttack-buC6ChYy.js +1 -0
  13. package/dist/assets/MunchyWorm-D2Zv7i0Q.js +1 -0
  14. package/dist/assets/ParkPatrol-CVj7hyoB.js +1 -0
  15. package/dist/assets/PottyPigeon-0SYpIUBa.js +1 -0
  16. package/dist/assets/RainbowIslands-BjfmJB8z.js +1 -0
  17. package/dist/assets/Stix-BU-qUCeC.js +1 -0
  18. package/dist/assets/Tilt-C5KtKisF.js +1 -0
  19. package/dist/assets/UpNDown-CATRO7Mz.js +1 -0
  20. package/dist/assets/Uridium-DanS2KoH.js +1 -0
  21. package/dist/assets/VegetablesDeluxe-C41ViimS.js +1 -0
  22. package/dist/assets/index-B8DSjPqI.js +243 -0
  23. package/dist/assets/src-DX0rJQsE.js +1 -0
  24. package/dist/assets/src-_trgwTvp.js +2 -0
  25. package/dist/assets/string-utils-CMVABfx0.js +1 -0
  26. package/dist/index.html +1 -1
  27. package/dist-ts/emulator/c64-keys.d.ts +69 -0
  28. package/dist-ts/emulator/c64-keys.d.ts.map +1 -0
  29. package/dist-ts/emulator/c64-keys.js +69 -0
  30. package/dist-ts/emulator/c64-keys.js.map +1 -0
  31. package/dist-ts/emulator/gamepad-mapping.d.ts +64 -0
  32. package/dist-ts/emulator/gamepad-mapping.d.ts.map +1 -0
  33. package/dist-ts/emulator/gamepad-mapping.js +154 -0
  34. package/dist-ts/emulator/gamepad-mapping.js.map +1 -0
  35. package/dist-ts/emulator/input.d.ts +24 -75
  36. package/dist-ts/emulator/input.d.ts.map +1 -1
  37. package/dist-ts/emulator/input.js +93 -214
  38. package/dist-ts/emulator/input.js.map +1 -1
  39. package/dist-ts/player/c64-player.d.ts +25 -0
  40. package/dist-ts/player/c64-player.d.ts.map +1 -1
  41. package/dist-ts/player/c64-player.js +77 -1
  42. package/dist-ts/player/c64-player.js.map +1 -1
  43. package/dist-ts/player/cheevos-dev.d.ts +65 -0
  44. package/dist-ts/player/cheevos-dev.d.ts.map +1 -0
  45. package/dist-ts/player/cheevos-dev.js +237 -0
  46. package/dist-ts/player/cheevos-dev.js.map +1 -0
  47. package/dist-ts/player/cheevos-tracker-panel.d.ts +21 -0
  48. package/dist-ts/player/cheevos-tracker-panel.d.ts.map +1 -0
  49. package/dist-ts/player/cheevos-tracker-panel.js +242 -0
  50. package/dist-ts/player/cheevos-tracker-panel.js.map +1 -0
  51. package/dist-ts/player/index.d.ts +3 -0
  52. package/dist-ts/player/index.d.ts.map +1 -1
  53. package/dist-ts/player/index.js +2 -0
  54. package/dist-ts/player/index.js.map +1 -1
  55. package/dist-ts/player/input-handler.d.ts +12 -1
  56. package/dist-ts/player/input-handler.d.ts.map +1 -1
  57. package/dist-ts/player/input-handler.js +46 -1
  58. package/dist-ts/player/input-handler.js.map +1 -1
  59. package/dist-ts/player/local-rom-store.d.ts +23 -0
  60. package/dist-ts/player/local-rom-store.d.ts.map +1 -0
  61. package/dist-ts/player/local-rom-store.js +87 -0
  62. package/dist-ts/player/local-rom-store.js.map +1 -0
  63. package/dist-ts/player/startup-params.d.ts +7 -0
  64. package/dist-ts/player/startup-params.d.ts.map +1 -0
  65. package/dist-ts/player/startup-params.js +47 -0
  66. package/dist-ts/player/startup-params.js.map +1 -0
  67. package/dist-ts/player/ui-controller.d.ts +22 -0
  68. package/dist-ts/player/ui-controller.d.ts.map +1 -1
  69. package/dist-ts/player/ui-controller.js +666 -1
  70. package/dist-ts/player/ui-controller.js.map +1 -1
  71. package/package.json +2 -1
  72. package/src/emulator/c64-keys.ts +68 -0
  73. package/src/emulator/gamepad-mapping.ts +212 -0
  74. package/src/emulator/input.ts +106 -209
  75. package/src/headless/headless-cli.mjs +10 -4
  76. package/src/headless/input-server.mjs +92 -17
  77. package/src/headless/webrtc-server.mjs +344 -22
  78. package/src/main.ts +177 -12
  79. package/src/player/c64-player.ts +96 -1
  80. package/src/player/cheevos-dev.ts +340 -0
  81. package/src/player/cheevos-tracker-panel.ts +309 -0
  82. package/src/player/index.ts +19 -0
  83. package/src/player/input-handler.ts +63 -1
  84. package/src/player/local-rom-store.ts +126 -0
  85. package/src/player/startup-params.ts +40 -0
  86. package/src/player/ui-controller.ts +741 -0
  87. package/src/types/c64-cheevos.d.ts +6 -0
  88. package/dist/assets/index-Dxuihfdi.js +0 -177
  89. /package/dist/assets/{marked.esm--kBm026b.js → marked.esm-fTuuvbcB.js} +0 -0
  90. /package/dist/assets/{purify.es-BcoGFDcJ.js → purify.es-CRM-GE0Y.js} +0 -0
@@ -8,6 +8,20 @@ import {
8
8
  type JoystickInput,
9
9
  } from './constants';
10
10
  import type { JoystickPort } from './constants';
11
+ import { C64_KEY } from './c64-keys';
12
+ import {
13
+ GAMEPAD_BUTTONS,
14
+ GAMEPAD_DIRECTIONS,
15
+ outputId,
16
+ readGamepadState,
17
+ resolveGamepadMapping,
18
+ resolveOutputs,
19
+ restrictDirections,
20
+ type GamepadMapping,
21
+ type GamepadOutput,
22
+ type GamepadState,
23
+ type ResolvedGamepadMapping,
24
+ } from './gamepad-mapping';
11
25
 
12
26
  export const KEY_TO_JOYSTICK = {
13
27
  ArrowUp: JOYSTICK_DIRECTION.UP,
@@ -64,74 +78,7 @@ const DEFAULT_MIXED_EXTRA_JOYSTICK_KEYS: KeyboardJoystickMap = {
64
78
  // typed characters to the C64 keyboard matrix.
65
79
  // ---------------------------------------------------------------------------
66
80
 
67
- /** C64 keyboard matrix indices */
68
- export const C64_KEY = {
69
- ARROW_LEFT: 0,
70
- ONE: 1,
71
- TWO: 2,
72
- THREE: 3,
73
- FOUR: 4,
74
- FIVE: 5,
75
- SIX: 6,
76
- SEVEN: 7,
77
- EIGHT: 8,
78
- NINE: 9,
79
- ZERO: 10,
80
- PLUS: 11,
81
- MINUS: 12,
82
- POUND: 13,
83
- CLEAR_HOME: 14,
84
- INS_DEL: 15,
85
- CTRL: 16,
86
- Q: 17,
87
- W: 18,
88
- E: 19,
89
- R: 20,
90
- T: 21,
91
- Y: 22,
92
- U: 23,
93
- I: 24,
94
- O: 25,
95
- P: 26,
96
- AT: 27,
97
- STAR: 28,
98
- ARROW_UP: 29,
99
- RUN_STOP: 30,
100
- A: 31,
101
- S: 32,
102
- D: 33,
103
- F: 34,
104
- G: 35,
105
- H: 36,
106
- J: 37,
107
- K: 38,
108
- L: 39,
109
- COLON: 40,
110
- SEMICOLON: 41,
111
- EQUALS: 42,
112
- RETURN: 43,
113
- COMMODORE: 44,
114
- SHIFT_LEFT: 45,
115
- Z: 46,
116
- X: 47,
117
- C: 48,
118
- V: 49,
119
- B: 50,
120
- N: 51,
121
- M: 52,
122
- COMMA: 53,
123
- PERIOD: 54,
124
- SLASH: 55,
125
- SHIFT_RIGHT: 56,
126
- CURSOR_UP_DOWN: 57,
127
- CURSOR_LEFT_RIGHT: 58,
128
- SPACE: 59,
129
- F1: 60,
130
- F3: 61,
131
- F5: 62,
132
- F7: 63,
133
- RESTORE: 64,
134
- } as const;
81
+ export { C64_KEY } from './c64-keys';
135
82
 
136
83
  type C64KeyAction = { key: number; action: 'press' | 'release' };
137
84
 
@@ -506,27 +453,14 @@ export class EmulatorInput {
506
453
  private inputMode: InputMode = 'mixed';
507
454
  private updateFrame: number = -1;
508
455
  private gamepadIndex: number = -1;
509
- private gamepadPresses: Array<boolean> = [];
510
- /**
511
- * Ultimate 8bitdo axes:
512
- * [LeftX, LeftX, LeftUp, LeftDown, L2, RightX, RightX, RightUp, RightDown, R2, DpadX, DpadX, DpadY, DpadY]
513
- **/
514
- private gamepadAxes: Array<boolean> = [
515
- false,
516
- false,
517
- false,
518
- false,
519
- false,
520
- false,
521
- false,
522
- false,
523
- false,
524
- false,
525
- false,
526
- false,
527
- false,
528
- false,
529
- ];
456
+ private gamepadMapping: ResolvedGamepadMapping = resolveGamepadMapping();
457
+ // Controls held on the physical gamepad (plus Start) and on a virtual one, e.g. on-screen touch controls
458
+ private physicalGamepadState: GamepadState & { start?: boolean } = {};
459
+ private virtualGamepadState: GamepadState = {};
460
+ // Directions after the stick mode was applied, so 4-way can keep the one already held
461
+ private heldGamepadDirections: GamepadState = {};
462
+ // Emulator inputs currently held because of the gamepads, by outputId()
463
+ private heldGamepadOutputs = new Map<string, GamepadOutput>();
530
464
  private keyboardJoystickMap: KeyboardJoystickMap = { ...KEY_TO_JOYSTICK };
531
465
  private mixedJoystickMap: KeyboardJoystickMap = { ...MIXED_JOYSTICK_KEYS };
532
466
  private potFire2Pressed = false;
@@ -588,116 +522,53 @@ export class EmulatorInput {
588
522
  }
589
523
  const gp = gamepads[this.gamepadIndex];
590
524
  if (!gp) {
525
+ this.physicalGamepadState = {};
526
+ this.applyGamepadState();
591
527
  this.cancelUpdate();
592
528
  return;
593
529
  }
594
- if (gp.buttons) {
595
- for (let b = 0; b < gp.buttons.length; b++) {
596
- if (gp.buttons[b].pressed) {
597
- this.gamepadPresses[b] = true;
598
- console.log('Buttons Pressed', b, gp.buttons[b]);
599
- switch (b) {
600
- case 0:
601
- this.emulator.joystickPush(this.joystickPort, JOYSTICK_FIRE_1);
602
- break;
603
- case 1:
604
- this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
605
- break;
606
- case 2:
607
- this.emulator.keyDown(C64_KEY.SPACE);
608
- break;
609
- case 3:
610
- //this.pushJoystickInput(JOYSTICK_FIRE_3);
611
- break;
612
- case 7:
613
- case 9:
614
- this.emulator.keyDown(C64_KEY.RUN_STOP);
615
- break;
616
- case 14:
617
- this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
618
- break;
619
- case 15:
620
- this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
621
- break;
622
- case 12:
623
- this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
624
- break;
625
- case 13:
626
- this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
627
- break;
628
- }
629
- // this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
630
- } else if (!gp.buttons[b].pressed && this.gamepadPresses[b] === true) {
631
- this.gamepadPresses[b] = false;
632
- switch (b) {
633
- case 0:
634
- this.emulator.joystickRelease(this.joystickPort, JOYSTICK_FIRE_1);
635
- break;
636
- case 1:
637
- this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
638
- break;
639
- case 2:
640
- this.emulator.keyUp(C64_KEY.SPACE);
641
- //this.releaseJoystickInput(JOYSTICK_FIRE_2);
642
- break;
643
- case 3:
644
- //this.releaseJoystickInput(JOYSTICK_FIRE_3);
645
- break;
646
- case 7:
647
- case 9:
648
- this.emulator.keyUp(C64_KEY.RUN_STOP);
649
- break;
650
- case 14:
651
- this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
652
- break;
653
- case 15:
654
- this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
655
- break;
656
- case 12:
657
- this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
658
- break;
659
- case 13:
660
- this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
661
- break;
662
- }
663
- // this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
664
- }
665
- }
666
- }
530
+ this.physicalGamepadState = readGamepadState(gp);
531
+ this.applyGamepadState();
667
532
 
668
- if (gp.axes[0] <= -0.5 || gp.axes[6] <= -0.5) {
669
- this.gamepadAxes[0] = true;
670
- this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
671
- } else if (this.gamepadAxes[0] === true) {
672
- this.gamepadAxes[0] = false;
673
- this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
674
- }
533
+ this.updateFrame = requestAnimationFrame(this.step.bind(this));
534
+ }
675
535
 
676
- if (gp.axes[0] >= 0.5 || gp.axes[6] >= 0.5) {
677
- this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
678
- this.gamepadAxes[1] = true;
679
- } else if (this.gamepadAxes[1] === true) {
680
- this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
681
- this.gamepadAxes[1] = false;
536
+ /** Holds exactly the emulator inputs that the physical and virtual gamepads map to right now */
537
+ private applyGamepadState(): void {
538
+ const physical = this.physicalGamepadState;
539
+ const virtual = this.virtualGamepadState;
540
+ const combined: GamepadState = {};
541
+ for (const control of [...GAMEPAD_DIRECTIONS, ...GAMEPAD_BUTTONS]) {
542
+ combined[control] = !!physical[control] || !!virtual[control];
682
543
  }
683
544
 
684
- if (gp.axes[1] <= -0.5 || gp.axes[7] <= -0.5) {
685
- this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
686
- this.gamepadAxes[2] = true;
687
- } else if (this.gamepadAxes[2] === true) {
688
- this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
689
- this.gamepadAxes[2] = false;
690
- }
545
+ const directions = restrictDirections(
546
+ combined,
547
+ this.gamepadMapping.stick,
548
+ this.heldGamepadDirections,
549
+ );
550
+ this.heldGamepadDirections = directions;
551
+ const outputs = resolveOutputs({ ...combined, ...directions }, this.gamepadMapping);
552
+ // Start is always RUN/STOP
553
+ if (physical.start) outputs.set(outputId({ key: C64_KEY.RUN_STOP }), { key: C64_KEY.RUN_STOP });
691
554
 
692
- if (gp.axes[1] >= 0.5 || gp.axes[7] >= 0.5) {
693
- this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
694
- this.gamepadAxes[3] = true;
695
- } else if (this.gamepadAxes[3] === true) {
696
- this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
697
- this.gamepadAxes[3] = false;
555
+ for (const [id, output] of this.heldGamepadOutputs) {
556
+ if (!outputs.has(id)) this.releaseGamepadOutput(output);
698
557
  }
558
+ for (const [id, output] of outputs) {
559
+ if (!this.heldGamepadOutputs.has(id)) this.pushGamepadOutput(output);
560
+ }
561
+ this.heldGamepadOutputs = outputs;
562
+ }
699
563
 
700
- this.updateFrame = requestAnimationFrame(this.step.bind(this));
564
+ private pushGamepadOutput(output: GamepadOutput): void {
565
+ if ('joystick' in output) this.emulator.joystickPush(this.joystickPort, output.joystick);
566
+ else this.emulator.keyDown(output.key);
567
+ }
568
+
569
+ private releaseGamepadOutput(output: GamepadOutput): void {
570
+ if ('joystick' in output) this.emulator.joystickRelease(this.joystickPort, output.joystick);
571
+ else this.emulator.keyUp(output.key);
701
572
  }
702
573
 
703
574
  private cancelUpdate(): void {
@@ -706,27 +577,13 @@ export class EmulatorInput {
706
577
  this.gamepadIndex = -1;
707
578
  }
708
579
 
580
+ /** Lets go of everything the gamepads hold, physical and virtual */
709
581
  private releaseAllGamepadButtons(): void {
710
- if (!this.gamepadPresses.some(Boolean)) return;
711
-
712
- const buttonToInput: Partial<Record<number, JoystickInput>> = {
713
- 0: JOYSTICK_FIRE_1,
714
- 2: JOYSTICK_FIRE_2,
715
- 3: JOYSTICK_FIRE_3,
716
- 12: JOYSTICK_DIRECTION.UP,
717
- 13: JOYSTICK_DIRECTION.DOWN,
718
- 14: JOYSTICK_DIRECTION.LEFT,
719
- 15: JOYSTICK_DIRECTION.RIGHT,
720
- };
721
-
722
- for (const [button, input] of Object.entries(buttonToInput)) {
723
- if (!input) continue;
724
- if (this.gamepadPresses[Number(button)] === true) {
725
- this.releaseJoystickInput(input);
726
- }
727
- }
728
-
729
- this.gamepadPresses = [];
582
+ this.physicalGamepadState = {};
583
+ this.virtualGamepadState = {};
584
+ this.heldGamepadDirections = {};
585
+ for (const output of this.heldGamepadOutputs.values()) this.releaseGamepadOutput(output);
586
+ this.heldGamepadOutputs = new Map();
730
587
  }
731
588
 
732
589
  private findConnectedGamepadIndex(excludeIndex?: number): number {
@@ -789,6 +646,8 @@ export class EmulatorInput {
789
646
  }
790
647
 
791
648
  private handleKeyDown(event: KeyboardEvent): void {
649
+ if (isEditableEventTarget(event.target)) return;
650
+
792
651
  if (this.inputMode === 'keyboard') {
793
652
  // Pure keyboard mode — all keys go to C64 matrix, no joystick
794
653
  const acts = domKeyToC64Actions(event.key, event.shiftKey, 'keydown');
@@ -836,6 +695,8 @@ export class EmulatorInput {
836
695
  }
837
696
 
838
697
  private handleKeyUp(event: KeyboardEvent): void {
698
+ if (isEditableEventTarget(event.target)) return;
699
+
839
700
  if (this.inputMode === 'keyboard') {
840
701
  const acts = domKeyToC64Actions(event.key, event.shiftKey, 'keyup');
841
702
  if (acts.length > 0) {
@@ -986,4 +847,40 @@ export class EmulatorInput {
986
847
  getActiveGamepadIndex(): number {
987
848
  return this.gamepadIndex;
988
849
  }
850
+
851
+ /**
852
+ * Changes what the gamepad controls do: the stick mode, and the joystick input or C64 key for
853
+ * each direction and button. Unlisted controls keep their defaults; null/undefined restores all
854
+ * defaults. Applies to both the physical and the virtual gamepad.
855
+ */
856
+ setGamepadMapping(mapping?: GamepadMapping | null): void {
857
+ this.gamepadMapping = resolveGamepadMapping(mapping);
858
+ this.heldGamepadDirections = {};
859
+ this.applyGamepadState();
860
+ }
861
+
862
+ getGamepadMapping(): ResolvedGamepadMapping {
863
+ return this.gamepadMapping;
864
+ }
865
+
866
+ /**
867
+ * Sets the controls held on a virtual gamepad, e.g. on-screen touch controls. They go through
868
+ * the same mapping as the physical gamepad, combined with it.
869
+ */
870
+ setVirtualGamepadState(state: GamepadState): void {
871
+ this.virtualGamepadState = { ...state };
872
+ this.applyGamepadState();
873
+ }
874
+ }
875
+
876
+ function isEditableEventTarget(target: EventTarget | null): boolean {
877
+ if (!(target instanceof Element)) return false;
878
+ if (target instanceof HTMLInputElement) {
879
+ return target.type !== 'button' && target.type !== 'checkbox' && target.type !== 'radio';
880
+ }
881
+ return (
882
+ target instanceof HTMLTextAreaElement ||
883
+ target instanceof HTMLSelectElement ||
884
+ (target instanceof HTMLElement && target.isContentEditable)
885
+ );
989
886
  }
@@ -3,6 +3,7 @@ import { readFileSync, mkdirSync, createWriteStream, readdirSync, statSync, unli
3
3
  import path from 'path';
4
4
  import { fileURLToPath } from 'url';
5
5
  import { execSync } from 'child_process';
6
+ import { timingSafeEqual } from 'crypto';
6
7
  import FFmpegRunner from './ffmpeg-runner.mjs';
7
8
  import { domKeyToC64Actions } from './c64-key-map.mjs';
8
9
 
@@ -382,6 +383,12 @@ export async function runHeadless(options = {}) {
382
383
  }
383
384
  if (!Number.isFinite(hostTimeoutMs) || hostTimeoutMs <= 0) hostTimeoutMs = undefined;
384
385
  const adminTokenSafe = String(adminToken ?? '').trim();
386
+ const validateAdminToken = (token) => {
387
+ if (!adminTokenSafe) return false;
388
+ const expected = Buffer.from(adminTokenSafe);
389
+ const received = Buffer.from(String(token ?? ''));
390
+ return received.length === expected.length && timingSafeEqual(received, expected);
391
+ };
385
392
 
386
393
  const webrtcMinBitrateKbpsSafe =
387
394
  Number.isFinite(webrtcMinBitrateKbps) && webrtcMinBitrateKbps > 0
@@ -765,10 +772,9 @@ export async function runHeadless(options = {}) {
765
772
  logEvents,
766
773
  hostTimeoutMs,
767
774
  validateKickToken,
768
- validateAdminToken: (token) => {
769
- if (!adminTokenSafe) return false;
770
- return token === adminTokenSafe;
771
- },
775
+ hostAuthRequired: true,
776
+ validateHostToken: validateAdminToken,
777
+ validateAdminToken,
772
778
  initialCartFilename: gamePath ? path.basename(gamePath) : null,
773
779
  serverVersion: _serverVersion,
774
780
  serverGitHash: _serverGitHash,
@@ -22,6 +22,8 @@ import { randomBytes } from 'crypto';
22
22
  * @param {number} [opts.hostTimeoutMs=300000]
23
23
  * @param {Function} [opts.validateKickToken]
24
24
  * @param {Function} [opts.validateAdminToken]
25
+ * @param {boolean} [opts.hostAuthRequired=false]
26
+ * @param {Function} [opts.validateHostToken]
25
27
  * @param {number} [opts.hostReconnectGraceMs=8000]
26
28
  * @param {number} [opts.p2ReconnectGraceMs=5000]
27
29
  * @param {Function} [opts.getRuntimeStats]
@@ -47,6 +49,8 @@ export function createInputServer(opts = {}) {
47
49
  const HOST_TIMEOUT = opts.hostTimeoutMs ?? 10 * 60 * 1000;
48
50
  const validateKickToken = opts.validateKickToken ?? (() => null);
49
51
  const validateAdminToken = opts.validateAdminToken ?? (() => false);
52
+ const hostAuthRequired = opts.hostAuthRequired ?? false;
53
+ const validateHostToken = opts.validateHostToken ?? (() => false);
50
54
  const serverVersion = opts.serverVersion ?? null;
51
55
  const serverGitHash = opts.serverGitHash ?? null;
52
56
  const getRuntimeStats = opts.getRuntimeStats ?? (() => null);
@@ -177,6 +181,8 @@ export function createInputServer(opts = {}) {
177
181
  let attractPlaylist = null;
178
182
  let attractCursor = null;
179
183
  let attractGeneration = 0;
184
+ let attractAutoStartEnabled = true;
185
+ let attractSelectedPlaylistOnce = false;
180
186
 
181
187
  function clearAttractTimer() {
182
188
  if (attractTimer) clearTimeout(attractTimer);
@@ -294,6 +300,7 @@ export function createInputServer(opts = {}) {
294
300
  csdbUrl: item.url ?? null,
295
301
  rating: item.rating ?? null,
296
302
  playlistPath: attractPlaylist._playlistPath ?? null,
303
+ playlistIndex: attractPlaylist._playlistIndex ?? null,
297
304
  itemIndex,
298
305
  fileIndex,
299
306
  filename,
@@ -311,6 +318,7 @@ export function createInputServer(opts = {}) {
311
318
  attractStatus = { active: false, reason, updatedAt: Date.now() };
312
319
  attractPlaylist = null;
313
320
  attractCursor = null;
321
+ attractSelectedPlaylistOnce = false;
314
322
  if (broadcast && wasActive) broadcastAttractMode();
315
323
  return wasActive;
316
324
  }
@@ -619,7 +627,7 @@ export function createInputServer(opts = {}) {
619
627
  if (typeof attractTimer.unref === 'function') attractTimer.unref();
620
628
  }
621
629
 
622
- async function loadAttractEntry(itemIndex, fileIndex, { mountOnly = false, rebootBeforeLoad = false } = {}) {
630
+ async function loadAttractEntry(itemIndex, fileIndex, { mountOnly = false, rebootBeforeLoad = false, afterStatus = null } = {}) {
623
631
  const generation = attractGeneration;
624
632
  const item = getAttractItem(itemIndex);
625
633
  const file = getAttractFile(item, fileIndex);
@@ -659,6 +667,7 @@ export function createInputServer(opts = {}) {
659
667
  if (generation !== attractGeneration) return;
660
668
  setAttractStatus({ item, file, itemIndex, fileIndex, filename });
661
669
  broadcastAttractMode();
670
+ if (typeof afterStatus === 'function') afterStatus();
662
671
  await runLoadFileCommand({
663
672
  filename,
664
673
  fileType,
@@ -670,20 +679,32 @@ export function createInputServer(opts = {}) {
670
679
  scheduleAttractAdvance();
671
680
  }
672
681
 
673
- async function startAttractMode(demoIndex = 0) {
682
+ async function startAttractMode(
683
+ demoIndex = 0,
684
+ playlistIndex = undefined,
685
+ { afterStatus = null, resumeAutoStart = false } = {},
686
+ ) {
674
687
  if (!attractEnabled) throw new Error('Attract Mode is not configured');
675
688
  attractGeneration += 1;
689
+ const generation = attractGeneration;
676
690
  clearAttractTimer();
691
+ if (resumeAutoStart) attractAutoStartEnabled = true;
677
692
  const manifest = await fetchAttractJson(resolveAttractUrl(attractManifest));
693
+ if (generation !== attractGeneration) return;
678
694
  logEv('attract-manifest-loaded', { count: Array.isArray(manifest) ? manifest.length : '-' });
679
695
  if (!Array.isArray(manifest) || manifest.length === 0) {
680
696
  throw new Error('No Attract Mode playlists configured');
681
697
  }
682
- const playlistEntry = chooseRandom(manifest);
698
+ if (playlistIndex != null && (!Number.isInteger(playlistIndex) || playlistIndex < 0 || playlistIndex >= manifest.length)) {
699
+ throw new Error(`Playlist index ${playlistIndex} is out of bounds (manifest has ${manifest.length} playlists)`);
700
+ }
701
+ const resolvedPlaylistIndex = playlistIndex ?? manifest.indexOf(chooseRandom(manifest));
702
+ const playlistEntry = manifest[resolvedPlaylistIndex];
683
703
  const playlistPath = typeof playlistEntry === 'string' ? playlistEntry : playlistEntry?.filename;
684
704
  if (!playlistPath) throw new Error('Invalid Attract Mode playlist entry');
685
- logEv('attract-playlist-selected', { playlistPath });
705
+ logEv('attract-playlist-selected', { playlistPath, playlistIndex: resolvedPlaylistIndex });
686
706
  const playlist = await fetchAttractJson(resolveAttractUrl(playlistPath));
707
+ if (generation !== attractGeneration) return;
687
708
  if (!playlist?.name) throw new Error('Attract Mode playlist is missing a name');
688
709
  if (!Array.isArray(playlist.items) || playlist.items.length === 0) {
689
710
  throw new Error('Attract Mode playlist has no demos');
@@ -691,15 +712,17 @@ export function createInputServer(opts = {}) {
691
712
  if (demoIndex < 0 || demoIndex >= playlist.items.length) {
692
713
  throw new Error(`Demo index ${demoIndex} is out of bounds (playlist has ${playlist.items.length} demos)`);
693
714
  }
694
- attractPlaylist = { ...playlist, _playlistPath: playlistPath };
695
- await loadAttractEntry(demoIndex, 0, { rebootBeforeLoad: true });
715
+ attractSelectedPlaylistOnce = playlistIndex != null;
716
+ attractPlaylist = { ...playlist, _playlistPath: playlistPath, _playlistIndex: resolvedPlaylistIndex };
717
+ await loadAttractEntry(demoIndex, 0, { rebootBeforeLoad: true, afterStatus });
696
718
  }
697
719
 
698
720
  function startAttractModeIfRoomEmpty(reason = 'empty-room') {
699
- if (!attractEnabled || attractStatus.active || hostClient || p2Client) {
721
+ if (!attractEnabled || !attractAutoStartEnabled || attractStatus.active || hostClient || p2Client) {
700
722
  logEv('attract-empty-room-start-skipped', {
701
723
  reason,
702
724
  attractEnabled,
725
+ autoStartEnabled: attractAutoStartEnabled,
703
726
  active: !!attractStatus.active,
704
727
  hasHost: !!hostClient,
705
728
  hasP2: !!p2Client,
@@ -716,10 +739,11 @@ export function createInputServer(opts = {}) {
716
739
 
717
740
  function scheduleAttractModeIfRoomEmpty(reason = 'empty-room') {
718
741
  clearEmptyRoomAttractTimer();
719
- if (!attractEnabled || attractStatus.active || hostClient || p2Client) {
742
+ if (!attractEnabled || !attractAutoStartEnabled || attractStatus.active || hostClient || p2Client) {
720
743
  logEv('attract-empty-room-schedule-skipped', {
721
744
  reason,
722
745
  attractEnabled,
746
+ autoStartEnabled: attractAutoStartEnabled,
723
747
  active: !!attractStatus.active,
724
748
  hasHost: !!hostClient,
725
749
  hasP2: !!p2Client,
@@ -746,6 +770,11 @@ export function createInputServer(opts = {}) {
746
770
  }
747
771
  const nextItemIndex = (attractCursor.itemIndex + 1) % attractPlaylist.items.length;
748
772
  if (generation !== attractGeneration) return;
773
+ if (nextItemIndex === 0 && attractSelectedPlaylistOnce) {
774
+ attractSelectedPlaylistOnce = false;
775
+ await startAttractMode(0);
776
+ return;
777
+ }
749
778
  await loadAttractEntry(nextItemIndex, 0, { rebootBeforeLoad: true });
750
779
  }
751
780
 
@@ -996,6 +1025,7 @@ export function createInputServer(opts = {}) {
996
1025
  ? {
997
1026
  connected: hostClient.readyState === hostClient.OPEN,
998
1027
  username: hostUsername,
1028
+ joystickPort: hostPort(),
999
1029
  addr: hostMeta?.addr ?? null,
1000
1030
  webrtcPeers: hostWebrtcPeers,
1001
1031
  }
@@ -1004,6 +1034,7 @@ export function createInputServer(opts = {}) {
1004
1034
  ? {
1005
1035
  connected: p2Client.readyState === p2Client.OPEN,
1006
1036
  username: p2Username,
1037
+ joystickPort: p2Port(),
1007
1038
  addr: p2Meta?.addr ?? null,
1008
1039
  webrtcPeers: p2WebrtcPeers,
1009
1040
  }
@@ -1020,6 +1051,10 @@ export function createInputServer(opts = {}) {
1020
1051
  webrtc: webrtcSnapshot,
1021
1052
  runtime: getRuntimeStats?.() ?? null,
1022
1053
  attractMode: attractStatusPayload(),
1054
+ gameState: {
1055
+ cartFilename: currentCartFilename,
1056
+ filename: currentCartFilename,
1057
+ },
1023
1058
  sampledAt: Date.now(),
1024
1059
  };
1025
1060
  }
@@ -1072,6 +1107,14 @@ export function createInputServer(opts = {}) {
1072
1107
 
1073
1108
  // ── Host claim ────────────────────────────────────────────────────────
1074
1109
  if (msg.type === 'host') {
1110
+ if (hostAuthRequired && !validateHostToken(msg.token ?? '')) {
1111
+ ws.send(JSON.stringify({ type: 'host-auth-failed', reason: 'invalid-token' }));
1112
+ logEv('host-claim-rejected', {
1113
+ reason: 'invalid-token',
1114
+ username: msg.username ?? 'player',
1115
+ });
1116
+ return;
1117
+ }
1075
1118
  if (hostClient && hostClient.readyState === hostClient.OPEN) {
1076
1119
  // force:true lets a new connection take over from a stale/ghost host
1077
1120
  // (e.g. page reload, WebRTC reconnect, or lost tab). Without this
@@ -1519,10 +1562,28 @@ export function createInputServer(opts = {}) {
1519
1562
  }
1520
1563
  setWsIdentity(ws, 'admin', null);
1521
1564
  const action = String(msg.action ?? '').toLowerCase();
1522
- const demoIndex = msg.demoIndex != null ? Number(msg.demoIndex) : undefined;
1523
- if (action === 'on') {
1524
- startAttractMode(demoIndex)
1525
- .then(() => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ type: 'admin-attract-mode-ok', action, attractMode: attractStatusPayload() })))
1565
+ const rawDemoIndex = msg.demoIndex != null ? Number(msg.demoIndex) : undefined;
1566
+ const rawIndex = msg.index != null ? Number(msg.index) : undefined;
1567
+ const demoIndex = action === 'playlist' ? 0 : rawDemoIndex;
1568
+ const playlistIndex = msg.playlistIndex != null
1569
+ ? Number(msg.playlistIndex)
1570
+ : action === 'playlist'
1571
+ ? rawDemoIndex ?? rawIndex
1572
+ : undefined;
1573
+ let sentAttractAdminOk = false;
1574
+ const sendAttractAdminOk = () => {
1575
+ if (sentAttractAdminOk) return;
1576
+ sentAttractAdminOk = true;
1577
+ if (ws.readyState === ws.OPEN) {
1578
+ ws.send(JSON.stringify({ type: 'admin-attract-mode-ok', action, attractMode: attractStatusPayload() }));
1579
+ }
1580
+ };
1581
+ if (action === 'on' || action === 'playlist') {
1582
+ startAttractMode(demoIndex, playlistIndex, {
1583
+ afterStatus: sendAttractAdminOk,
1584
+ resumeAutoStart: true,
1585
+ })
1586
+ .then(sendAttractAdminOk)
1526
1587
  .catch((e) => {
1527
1588
  stopAttractMode({ reason: 'error' });
1528
1589
  if (ws.readyState === ws.OPEN) {
@@ -1532,8 +1593,13 @@ export function createInputServer(opts = {}) {
1532
1593
  return;
1533
1594
  }
1534
1595
  if (action === 'off') {
1596
+ attractAutoStartEnabled = false;
1535
1597
  stopAttractMode({ reason: 'admin' });
1536
- ws.send(JSON.stringify({ type: 'admin-attract-mode-ok', action, attractMode: attractStatusPayload() }));
1598
+ sendAttractAdminOk();
1599
+ return;
1600
+ }
1601
+ if (ws.readyState === ws.OPEN) {
1602
+ ws.send(JSON.stringify({ type: 'admin-error', command: 'attract-mode', reason: 'invalid-action' }));
1537
1603
  }
1538
1604
  return;
1539
1605
  }
@@ -1614,10 +1680,17 @@ export function createInputServer(opts = {}) {
1614
1680
  return;
1615
1681
  }
1616
1682
  const action = String(msg.action ?? '').toLowerCase();
1617
- const demoIndex = msg.demoIndex != null ? Number(msg.demoIndex) : undefined;
1618
- logEv('cmd-attract-mode', { action, host: hostUsername ?? '-', demoIndex: demoIndex ?? '-' });
1619
- if (action === 'on') {
1620
- startAttractMode(demoIndex)
1683
+ const rawDemoIndex = msg.demoIndex != null ? Number(msg.demoIndex) : undefined;
1684
+ const rawIndex = msg.index != null ? Number(msg.index) : undefined;
1685
+ const demoIndex = action === 'playlist' ? 0 : rawDemoIndex;
1686
+ const playlistIndex = msg.playlistIndex != null
1687
+ ? Number(msg.playlistIndex)
1688
+ : action === 'playlist'
1689
+ ? rawDemoIndex ?? rawIndex
1690
+ : undefined;
1691
+ logEv('cmd-attract-mode', { action, host: hostUsername ?? '-', demoIndex: demoIndex ?? '-', playlistIndex: playlistIndex ?? '-' });
1692
+ if (action === 'on' || action === 'playlist') {
1693
+ startAttractMode(demoIndex, playlistIndex, { resumeAutoStart: true })
1621
1694
  .then(() => {
1622
1695
  if (ws.readyState === ws.OPEN) {
1623
1696
  ws.send(JSON.stringify({ type: 'attract-mode-ok', action, attractMode: attractStatusPayload() }));
@@ -1634,6 +1707,7 @@ export function createInputServer(opts = {}) {
1634
1707
  return;
1635
1708
  }
1636
1709
  if (action === 'off') {
1710
+ attractAutoStartEnabled = false;
1637
1711
  stopAttractMode({ reason: 'manual' });
1638
1712
  if (ws.readyState === ws.OPEN) {
1639
1713
  ws.send(JSON.stringify({ type: 'attract-mode-ok', action, attractMode: attractStatusPayload() }));
@@ -1824,6 +1898,7 @@ export function createInputServer(opts = {}) {
1824
1898
  type: 'hello',
1825
1899
  protocol: 'c64-input',
1826
1900
  version: 1,
1901
+ hostAuthRequired,
1827
1902
  serverTime, // Unix ms for client clock sync
1828
1903
  // During grace period: treat slot as free so the original host can reclaim it.
1829
1904
  // hostPendingRejoin tells P2 (and spectators) to hold off.