@makefully/engagefully 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@makefully/engagefully",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Device-agnostic input: keyboard/gamepad/pointer → Button/Joystick, plus ActionMap logical bindings.",
5
5
  "main": "./lib/engagefully.js",
6
6
  "module": "./src/index.js",
@@ -23,7 +23,8 @@
23
23
  "build": "webpack --env prod",
24
24
  "build:release": "webpack --env prod",
25
25
  "build:debug": "webpack --env dev",
26
- "test": "node -e \"console.log('no unit tests yet')\"",
26
+ "test": "vitest run",
27
+ "test:watch": "vitest",
27
28
  "prepublishOnly": "npm run build:release"
28
29
  },
29
30
  "publishConfig": {
@@ -61,6 +62,8 @@
61
62
  "@babel/preset-env": "^7.4.3",
62
63
  "babel-loader": "^8.0.2",
63
64
  "file-loader": "^6.2.0",
65
+ "happy-dom": "^21.0.4",
66
+ "vitest": "^5.1.2",
64
67
  "webpack": "^5.68.0",
65
68
  "webpack-cli": "^4.9.2",
66
69
  "webpack-dev-server": "^4.7.3"
@@ -31,7 +31,7 @@ class PixiDevice extends EventEmitter {
31
31
  y: event.y
32
32
  });
33
33
  });
34
- target.on(options?.up ?? 'pointerup', (event) => {
34
+ target.on('pointerup', (event) => {
35
35
  this.pressed = 0;
36
36
  this.emit('updated', {
37
37
  control: 'Pointer',
@@ -0,0 +1,606 @@
1
+ import EventEmitter from 'events';
2
+
3
+ /** Delay before restarting after a natural session end (Chrome teardown race). */
4
+ const RESTART_DELAY_MS = 250;
5
+ /** Max wait for onend after an intentional stop before forcing cleanup. */
6
+ const STOP_WAIT_MS = 500;
7
+ /** Backoff between recoverable start/error retries. */
8
+ const RETRY_DELAYS_MS = [250, 500, 1000, 2000];
9
+ /** If onstart never arrives, treat the session as dead and retry. */
10
+ const START_WATCHDOG_MS = 3000;
11
+ const DEFAULT_COOLDOWN_MS = 800;
12
+ const DEFAULT_TRANSCRIPT_CONTROL = 'SpeechTranscript';
13
+
14
+ function getSpeechRecognitionCtor () {
15
+ if (typeof window === 'undefined') {
16
+ return null;
17
+ }
18
+
19
+ return window.SpeechRecognition || window.webkitSpeechRecognition || null;
20
+ }
21
+
22
+ function normalizeUtterance (text) {
23
+ return String(text ?? '')
24
+ .replace(/\s+/g, ' ')
25
+ .trim()
26
+ .toLowerCase();
27
+ }
28
+
29
+ function normalizeMappings (mappings = []) {
30
+ if (!Array.isArray(mappings)) {
31
+ return [];
32
+ }
33
+
34
+ return mappings
35
+ .filter((m) => m && typeof m.control === 'string' && m.type && Array.isArray(m.phrases))
36
+ .map((m) => ({
37
+ control: m.control,
38
+ type: m.type,
39
+ phrases: m.phrases
40
+ .map(normalizeUtterance)
41
+ .filter(Boolean),
42
+ value: m.value,
43
+ x: m.x,
44
+ y: m.y,
45
+ releaseMs: typeof m.releaseMs === 'number' ? m.releaseMs : null
46
+ }))
47
+ .filter((m) => m.phrases.length > 0);
48
+ }
49
+
50
+ /**
51
+ * Web Speech Recognition → Engagefully device.
52
+ * Transcripts emit as Data; phrase mappings emit Button / Amount / Joystick / Dial.
53
+ *
54
+ * Does not auto-start. Call setActive(true) / start() after a user gesture.
55
+ * Mic UI stays app-owned.
56
+ */
57
+ class SpeechDevice extends EventEmitter {
58
+ static supported () {
59
+ return getSpeechRecognitionCtor() != null;
60
+ }
61
+
62
+ constructor (options = {}) {
63
+ super();
64
+
65
+ if (typeof options === 'string') {
66
+ options = { device: options };
67
+ }
68
+
69
+ this.device = options.device || 'Speech';
70
+ this.transcriptControl = options.transcriptControl || DEFAULT_TRANSCRIPT_CONTROL;
71
+ this.lang = options.lang || 'en-US';
72
+ this.interimResults = Boolean(options.interimResults);
73
+ this.cooldownMs = typeof options.cooldownMs === 'number'
74
+ ? options.cooldownMs
75
+ : DEFAULT_COOLDOWN_MS;
76
+
77
+ this._Ctor = getSpeechRecognitionCtor();
78
+ this._mappings = normalizeMappings(options.mappings);
79
+ this._cooldownUntil = new Map();
80
+ this._releaseTimers = new Map();
81
+
82
+ this._recognition = null;
83
+ this._active = false;
84
+ this._listening = false;
85
+ this._starting = false;
86
+ this._recovering = false;
87
+ this._intentionalStop = false;
88
+ this._failCount = 0;
89
+ this._destroyed = false;
90
+
91
+ this._restartTimer = null;
92
+ this._stopWaitTimer = null;
93
+ this._startWatchTimer = null;
94
+
95
+ this._warmResult = null;
96
+ this._warmPromise = null;
97
+
98
+ this._onBlur = () => {
99
+ this.setActive(false);
100
+ };
101
+
102
+ if (typeof window !== 'undefined') {
103
+ window.addEventListener('blur', this._onBlur);
104
+ }
105
+ }
106
+
107
+ setMappings (mappings) {
108
+ this._mappings = normalizeMappings(mappings);
109
+ }
110
+
111
+ setActive (next) {
112
+ const active = Boolean(next);
113
+
114
+ if (this._active === active) {
115
+ return;
116
+ }
117
+
118
+ this._active = active;
119
+
120
+ if (!active) {
121
+ this._failCount = 0;
122
+ this._stopRecognition();
123
+ return;
124
+ }
125
+
126
+ if (this._shouldListen()) {
127
+ this._scheduleStart(0);
128
+ }
129
+ }
130
+
131
+ start () {
132
+ this.setActive(true);
133
+ }
134
+
135
+ stop () {
136
+ this.setActive(false);
137
+ }
138
+
139
+ destroy () {
140
+ this._destroyed = true;
141
+
142
+ if (typeof window !== 'undefined') {
143
+ window.removeEventListener('blur', this._onBlur);
144
+ }
145
+
146
+ this._clearRestartTimer();
147
+ this._clearStopWaitTimer();
148
+ this._clearStartWatchTimer();
149
+ this._clearAllReleaseTimers();
150
+ this.setActive(false);
151
+ this.removeAllListeners();
152
+ }
153
+
154
+ _shouldListen () {
155
+ return this._active && !this._destroyed && this._Ctor != null;
156
+ }
157
+
158
+ _clearRestartTimer () {
159
+ if (this._restartTimer == null) {
160
+ return;
161
+ }
162
+ clearTimeout(this._restartTimer);
163
+ this._restartTimer = null;
164
+ }
165
+
166
+ _clearStopWaitTimer () {
167
+ if (this._stopWaitTimer == null) {
168
+ return;
169
+ }
170
+ clearTimeout(this._stopWaitTimer);
171
+ this._stopWaitTimer = null;
172
+ }
173
+
174
+ _clearStartWatchTimer () {
175
+ if (this._startWatchTimer == null) {
176
+ return;
177
+ }
178
+ clearTimeout(this._startWatchTimer);
179
+ this._startWatchTimer = null;
180
+ }
181
+
182
+ _clearAllReleaseTimers () {
183
+ for (const timer of this._releaseTimers.values()) {
184
+ clearTimeout(timer);
185
+ }
186
+ this._releaseTimers.clear();
187
+ }
188
+
189
+ _clearReleaseTimer (control) {
190
+ const timer = this._releaseTimers.get(control);
191
+ if (timer != null) {
192
+ clearTimeout(timer);
193
+ this._releaseTimers.delete(control);
194
+ }
195
+ }
196
+
197
+ _detach (rec) {
198
+ rec.onstart = null;
199
+ rec.onresult = null;
200
+ rec.onerror = null;
201
+ rec.onend = null;
202
+ }
203
+
204
+ _scheduleStart (delayMs) {
205
+ this._clearRestartTimer();
206
+ if (!this._shouldListen()) {
207
+ return;
208
+ }
209
+ this._restartTimer = setTimeout(() => {
210
+ this._restartTimer = null;
211
+ void this._startRecognition();
212
+ }, delayMs);
213
+ }
214
+
215
+ _noteRecoverableFailure () {
216
+ this._failCount += 1;
217
+ this._starting = false;
218
+ this._listening = false;
219
+
220
+ if (!this._shouldListen()) {
221
+ this._recovering = false;
222
+ return;
223
+ }
224
+
225
+ if (this._failCount > RETRY_DELAYS_MS.length) {
226
+ this._recovering = false;
227
+ this.setActive(false);
228
+ return;
229
+ }
230
+
231
+ this._recovering = true;
232
+ const delay = RETRY_DELAYS_MS[this._failCount - 1] ?? RETRY_DELAYS_MS[RETRY_DELAYS_MS.length - 1];
233
+ this._scheduleStart(delay);
234
+ }
235
+
236
+ _warmCapture (force = false) {
237
+ if (force) {
238
+ this._warmResult = null;
239
+ }
240
+ if (this._warmResult != null) {
241
+ return Promise.resolve(this._warmResult);
242
+ }
243
+ if (this._warmPromise) {
244
+ return this._warmPromise;
245
+ }
246
+
247
+ const media = typeof navigator !== 'undefined' ? navigator.mediaDevices : null;
248
+ if (!media?.getUserMedia) {
249
+ this._warmResult = true;
250
+ return Promise.resolve(true);
251
+ }
252
+
253
+ const attempt = media
254
+ .getUserMedia({ audio: true })
255
+ .then((stream) => {
256
+ for (const track of stream.getTracks()) {
257
+ track.stop();
258
+ }
259
+ this._warmResult = true;
260
+ return true;
261
+ })
262
+ .catch(() => {
263
+ this._warmResult = false;
264
+ return false;
265
+ });
266
+
267
+ const timed = Promise.race([
268
+ attempt,
269
+ new Promise((resolve) => {
270
+ setTimeout(() => resolve(this._warmResult ?? false), 1500);
271
+ })
272
+ ]);
273
+
274
+ this._warmPromise = timed.finally(() => {
275
+ this._warmPromise = null;
276
+ });
277
+
278
+ return this._warmPromise;
279
+ }
280
+
281
+ _stopRecognition () {
282
+ this._clearRestartTimer();
283
+ this._clearStartWatchTimer();
284
+ this._starting = false;
285
+ this._recovering = false;
286
+
287
+ const rec = this._recognition;
288
+ if (!rec) {
289
+ this._intentionalStop = false;
290
+ this._clearStopWaitTimer();
291
+ this._listening = false;
292
+ return;
293
+ }
294
+
295
+ this._intentionalStop = true;
296
+ try {
297
+ rec.stop();
298
+ } catch (_) {
299
+ try {
300
+ rec.abort();
301
+ } catch (_) {
302
+ /* ignore */
303
+ }
304
+ }
305
+
306
+ this._clearStopWaitTimer();
307
+ this._stopWaitTimer = setTimeout(() => {
308
+ this._stopWaitTimer = null;
309
+ if (this._recognition === rec) {
310
+ this._recognition = null;
311
+ this._detach(rec);
312
+ }
313
+ this._intentionalStop = false;
314
+ this._listening = false;
315
+ if (this._shouldListen()) {
316
+ this._scheduleStart(RESTART_DELAY_MS);
317
+ }
318
+ }, STOP_WAIT_MS);
319
+ }
320
+
321
+ async _startRecognition () {
322
+ if (!this._shouldListen() || this._listening || this._starting || this._recognition) {
323
+ return;
324
+ }
325
+
326
+ this._clearRestartTimer();
327
+ this._starting = true;
328
+
329
+ if (this._warmResult == null || this._failCount > 0) {
330
+ await this._warmCapture(this._failCount > 0);
331
+ if (!this._shouldListen() || this._listening || this._recognition) {
332
+ this._starting = false;
333
+ return;
334
+ }
335
+ }
336
+
337
+ const rec = new this._Ctor();
338
+ this._recognition = rec;
339
+ rec.continuous = true;
340
+ rec.interimResults = true;
341
+ rec.lang = this.lang;
342
+
343
+ rec.onstart = () => {
344
+ if (this._recognition !== rec) {
345
+ return;
346
+ }
347
+ this._clearStartWatchTimer();
348
+ this._starting = false;
349
+ this._failCount = 0;
350
+ this._recovering = false;
351
+ this._listening = true;
352
+ };
353
+
354
+ rec.onresult = (ev) => {
355
+ if (this._recognition !== rec) {
356
+ return;
357
+ }
358
+ this._handleResult(ev);
359
+ };
360
+
361
+ rec.onerror = (ev) => {
362
+ if (this._recognition !== rec) {
363
+ return;
364
+ }
365
+ const err = ev.error || '';
366
+
367
+ if (err === 'aborted' || err === 'no-speech') {
368
+ return;
369
+ }
370
+
371
+ this._clearStartWatchTimer();
372
+ this._recognition = null;
373
+ this._detach(rec);
374
+ this._starting = false;
375
+ this._listening = false;
376
+
377
+ if (err === 'not-allowed' || err === 'service-not-allowed') {
378
+ this._intentionalStop = false;
379
+ this._clearStopWaitTimer();
380
+ this._recovering = false;
381
+ this.setActive(false);
382
+ return;
383
+ }
384
+
385
+ if (this._intentionalStop) {
386
+ return;
387
+ }
388
+
389
+ if (err === 'audio-capture') {
390
+ this._warmResult = null;
391
+ }
392
+
393
+ this._noteRecoverableFailure();
394
+ };
395
+
396
+ rec.onend = () => {
397
+ this._clearStartWatchTimer();
398
+ if (this._recognition === rec) {
399
+ this._recognition = null;
400
+ this._detach(rec);
401
+ }
402
+ this._starting = false;
403
+ this._listening = false;
404
+ this._intentionalStop = false;
405
+ this._clearStopWaitTimer();
406
+
407
+ if (this._shouldListen()) {
408
+ this._scheduleStart(RESTART_DELAY_MS);
409
+ }
410
+ };
411
+
412
+ try {
413
+ rec.start();
414
+ this._clearStartWatchTimer();
415
+ this._startWatchTimer = setTimeout(() => {
416
+ this._startWatchTimer = null;
417
+ if (this._recognition !== rec || this._listening) {
418
+ return;
419
+ }
420
+ try {
421
+ rec.abort();
422
+ } catch (_) {
423
+ /* ignore */
424
+ }
425
+ if (this._recognition !== rec) {
426
+ return;
427
+ }
428
+ this._recognition = null;
429
+ this._detach(rec);
430
+ this._noteRecoverableFailure();
431
+ }, START_WATCHDOG_MS);
432
+ } catch (_) {
433
+ this._clearStartWatchTimer();
434
+ this._recognition = null;
435
+ this._detach(rec);
436
+ this._noteRecoverableFailure();
437
+ }
438
+ }
439
+
440
+ _handleResult (ev) {
441
+ const now = Date.now();
442
+
443
+ for (let i = ev.resultIndex; i < ev.results.length; i++) {
444
+ const result = ev.results[i];
445
+ if (!result) {
446
+ continue;
447
+ }
448
+
449
+ const alt = result[0];
450
+ const raw = alt?.transcript ?? '';
451
+ const text = String(raw).replace(/\s+/g, ' ').trim();
452
+ if (!text) {
453
+ continue;
454
+ }
455
+
456
+ const isFinal = Boolean(result.isFinal);
457
+ const confidence = typeof alt?.confidence === 'number' ? alt.confidence : undefined;
458
+
459
+ if (!isFinal) {
460
+ if (this.interimResults) {
461
+ this.emit('updated', {
462
+ control: this.transcriptControl,
463
+ device: this.device,
464
+ type: 'Data',
465
+ value: {
466
+ text,
467
+ isFinal: false,
468
+ confidence,
469
+ matchedControls: []
470
+ },
471
+ event: ev
472
+ });
473
+ }
474
+ continue;
475
+ }
476
+
477
+ const normalized = normalizeUtterance(text);
478
+ const hits = [];
479
+ const matchedControls = [];
480
+ const seenControls = new Set();
481
+
482
+ for (const mapping of this._mappings) {
483
+ if (!mapping.phrases.includes(normalized)) {
484
+ continue;
485
+ }
486
+
487
+ const until = this._cooldownUntil.get(mapping.control) || 0;
488
+ if (now < until) {
489
+ continue;
490
+ }
491
+
492
+ hits.push(mapping);
493
+ if (!seenControls.has(mapping.control)) {
494
+ seenControls.add(mapping.control);
495
+ matchedControls.push(mapping.control);
496
+ }
497
+ }
498
+
499
+ this.emit('updated', {
500
+ control: this.transcriptControl,
501
+ device: this.device,
502
+ type: 'Data',
503
+ value: {
504
+ text,
505
+ isFinal: true,
506
+ confidence,
507
+ matchedControls
508
+ },
509
+ event: ev
510
+ });
511
+
512
+ for (const mapping of hits) {
513
+ this._cooldownUntil.set(mapping.control, now + this.cooldownMs);
514
+ this._emitMapping(mapping, ev);
515
+ }
516
+ }
517
+ }
518
+
519
+ _emitMapping (mapping, nativeEvent) {
520
+ this._clearReleaseTimer(mapping.control);
521
+
522
+ const type = mapping.type;
523
+
524
+ if (type === 'Button') {
525
+ this.emit('updated', {
526
+ control: mapping.control,
527
+ device: this.device,
528
+ type: 'Button',
529
+ value: 1,
530
+ event: nativeEvent
531
+ });
532
+ queueMicrotask(() => {
533
+ if (this._destroyed) {
534
+ return;
535
+ }
536
+ this.emit('updated', {
537
+ control: mapping.control,
538
+ device: this.device,
539
+ type: 'Button',
540
+ value: 0,
541
+ event: nativeEvent
542
+ });
543
+ });
544
+ return;
545
+ }
546
+
547
+ if (type === 'Joystick') {
548
+ const x = typeof mapping.x === 'number' ? mapping.x : 0;
549
+ const y = typeof mapping.y === 'number' ? mapping.y : 0;
550
+ this.emit('updated', {
551
+ control: mapping.control,
552
+ device: this.device,
553
+ type: 'Joystick',
554
+ x,
555
+ y,
556
+ event: nativeEvent
557
+ });
558
+
559
+ if (mapping.releaseMs != null) {
560
+ this._releaseTimers.set(mapping.control, setTimeout(() => {
561
+ this._releaseTimers.delete(mapping.control);
562
+ if (this._destroyed) {
563
+ return;
564
+ }
565
+ this.emit('updated', {
566
+ control: mapping.control,
567
+ device: this.device,
568
+ type: 'Joystick',
569
+ x: 0,
570
+ y: 0,
571
+ event: nativeEvent
572
+ });
573
+ }, mapping.releaseMs));
574
+ }
575
+ return;
576
+ }
577
+
578
+ // Amount, Dial, or any value-bearing type
579
+ const value = mapping.value;
580
+ this.emit('updated', {
581
+ control: mapping.control,
582
+ device: this.device,
583
+ type,
584
+ value,
585
+ event: nativeEvent
586
+ });
587
+
588
+ if (mapping.releaseMs != null && (type === 'Amount' || type === 'Dial')) {
589
+ this._releaseTimers.set(mapping.control, setTimeout(() => {
590
+ this._releaseTimers.delete(mapping.control);
591
+ if (this._destroyed) {
592
+ return;
593
+ }
594
+ this.emit('updated', {
595
+ control: mapping.control,
596
+ device: this.device,
597
+ type,
598
+ value: 0,
599
+ event: nativeEvent
600
+ });
601
+ }, mapping.releaseMs));
602
+ }
603
+ }
604
+ }
605
+
606
+ export default SpeechDevice;
@@ -9,6 +9,7 @@ import KeyboardDevice from './KeyboardDevice';
9
9
  import PageDevice from './PageDevice';
10
10
  import PixiDevice from './PixiDevice';
11
11
  import PointerDevice from './PointerDevice';
12
+ import SpeechDevice from './SpeechDevice';
12
13
 
13
14
  export default {
14
15
  BLEDevice,
@@ -17,6 +18,7 @@ export default {
17
18
  KeyboardDevice,
18
19
  PageDevice,
19
20
  PixiDevice,
20
- PointerDevice
21
+ PointerDevice,
22
+ SpeechDevice
21
23
  };
22
24