@livx.cc/native-kit 0.24.0 → 0.25.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@livx.cc/native-kit",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "Isomorphic native-capabilities kit for PWAs — same API in browser and in an appwrap native shell. Zero dependencies.",
5
5
  "license": "MIT",
6
6
  "author": "Elya Livshitz",
@@ -1,6 +1,6 @@
1
1
  import { AppwrapAdapter } from './appwrap-adapter';
2
2
  import { WebAdapter } from './web-adapter';
3
- import { Capability, Handshake, InvokeOptions, KIT_PROTOCOL, KitError, NativeKitAdapter, Unsubscribe } from './types';
3
+ import { Capability, Handshake, InvokeOptions, KIT_PROTOCOL, KitError, NativeKitAdapter, Platform, Unsubscribe } from './types';
4
4
  import { AppModule } from '../modules/app';
5
5
  import { BillingModule } from '../modules/billing/billing';
6
6
  import { BiometricsModule } from '../modules/biometrics';
@@ -26,6 +26,7 @@ import { ReviewsModule } from '../modules/reviews';
26
26
  import { ScannerModule } from '../modules/scanner';
27
27
  import { ScreenModule } from '../modules/screen';
28
28
  import { ShareModule } from '../modules/share';
29
+ import { SpeechModule } from '../modules/speech';
29
30
  import { StorageModule } from '../modules/storage';
30
31
  import { ToastModule } from '../modules/toast';
31
32
  import { UiModule } from '../modules/ui';
@@ -93,6 +94,7 @@ export class NativeKit {
93
94
  public readonly media = new MediaModule(this);
94
95
  public readonly contacts = new ContactsModule(this);
95
96
  public readonly scanner = new ScannerModule(this);
97
+ public readonly speech = new SpeechModule(this);
96
98
  public readonly calendar = new CalendarModule(this);
97
99
  public readonly app = new AppModule(this);
98
100
  public readonly browser = new BrowserModule(this);
@@ -40,6 +40,8 @@ export class WebAdapter implements NativeKitAdapter {
40
40
  private motionHandler: ((e: DeviceMotionEvent) => void) | null = null;
41
41
  /** Tear-down for an in-progress scanner.scan loop (stops the camera, removes the overlay). */
42
42
  private scanCancel: (() => void) | null = null;
43
+ /** Stop an in-progress speech.listen session (resolves it with the best transcript so far). */
44
+ private listenStop: (() => void) | null = null;
43
45
 
44
46
  detect(): boolean {
45
47
  return typeof window !== 'undefined';
@@ -79,6 +81,13 @@ export class WebAdapter implements NativeKitAdapter {
79
81
  media: (navigator as any).mediaDevices?.getUserMedia ? 'web' : 'none',
80
82
  // BarcodeDetector (Chrome/Android) decodes; needs a getUserMedia stream to feed it. Both → 'web'.
81
83
  scanner: typeof (window as any).BarcodeDetector !== 'undefined' && (navigator as any).mediaDevices?.getUserMedia ? 'web' : 'none',
84
+ // TTS: SpeechSynthesis API (broad support). STT: SpeechRecognition (Chrome/webkit only).
85
+ speech: typeof (window as any).speechSynthesis !== 'undefined' ? 'web' : 'none',
86
+ speechRecognition:
87
+ typeof (window as any).SpeechRecognition !== 'undefined' ||
88
+ typeof (window as any).webkitSpeechRecognition !== 'undefined'
89
+ ? 'web'
90
+ : 'none',
82
91
  app: 'web', // openUrl via window.open; openSettings unsupported
83
92
  browser: 'web', // new tab/window
84
93
  billing: 'none', // no IAP in a plain browser — wire a web checkout yourself
@@ -331,6 +340,19 @@ export class WebAdapter implements NativeKitAdapter {
331
340
  this.scanCancel?.();
332
341
  return undefined as T;
333
342
 
343
+ case 'speech.speak':
344
+ return this.speak(String(p.text ?? ''), p) as Promise<T>;
345
+ case 'speech.stop':
346
+ (window as any).speechSynthesis?.cancel?.();
347
+ return undefined as T;
348
+ case 'speech.voices':
349
+ return this.listVoices() as Promise<T>;
350
+ case 'speech.listen':
351
+ return this.listen(p) as Promise<T>;
352
+ case 'speech.stopListening':
353
+ this.listenStop?.();
354
+ return undefined as T;
355
+
334
356
  case 'photos.pick':
335
357
  return this.pickImageFile(false, !!p.dataUrl, p.maxSize) as Promise<T>;
336
358
  case 'camera.capture':
@@ -547,6 +569,88 @@ export class WebAdapter implements NativeKitAdapter {
547
569
  });
548
570
  }
549
571
 
572
+ // ── speech (Web Speech API) ─────────────────────────────────────────
573
+
574
+ /** Speak via SpeechSynthesis; resolve when the utterance ends (or rejects on synth error). */
575
+ private speak(text: string, opts: Record<string, any>): Promise<void> {
576
+ const synth = (window as any).speechSynthesis;
577
+ if (!synth) throw new KitError('UNSUPPORTED', 'SpeechSynthesis unavailable');
578
+ return new Promise((resolve, reject) => {
579
+ const u = new (window as any).SpeechSynthesisUtterance(text);
580
+ if (opts.lang) u.lang = opts.lang;
581
+ if (opts.rate != null) u.rate = opts.rate;
582
+ if (opts.pitch != null) u.pitch = opts.pitch;
583
+ if (opts.voice) {
584
+ const v = synth.getVoices().find((vc: any) => vc.voiceURI === opts.voice || vc.name === opts.voice);
585
+ if (v) u.voice = v;
586
+ }
587
+ u.onend = () => resolve();
588
+ u.onerror = (e: any) => reject(new KitError('NATIVE_ERROR', e?.error ?? 'speech synthesis failed'));
589
+ synth.speak(u);
590
+ });
591
+ }
592
+
593
+ /** List synthesizer voices, awaiting the async `voiceschanged` event when the list is empty. */
594
+ private listVoices(): Promise<Array<{ id: string; name: string; lang: string }>> {
595
+ const synth = (window as any).speechSynthesis;
596
+ if (!synth) throw new KitError('UNSUPPORTED', 'SpeechSynthesis unavailable');
597
+ const map = (vs: any[]) => vs.map((v) => ({ id: v.voiceURI ?? v.name, name: v.name, lang: v.lang }));
598
+ const ready = synth.getVoices();
599
+ if (ready.length) return Promise.resolve(map(ready));
600
+ // Chrome populates voices asynchronously — wait once for voiceschanged, with a short fallback.
601
+ return new Promise((resolve) => {
602
+ let settled = false;
603
+ const done = () => {
604
+ if (settled) return;
605
+ settled = true;
606
+ resolve(map(synth.getVoices()));
607
+ };
608
+ synth.addEventListener?.('voiceschanged', done, { once: true });
609
+ setTimeout(done, 1000);
610
+ });
611
+ }
612
+
613
+ /** Capture the mic via SpeechRecognition; resolve the FINAL transcript, stream partials. */
614
+ private listen(opts: Record<string, any>): Promise<string> {
615
+ const Rec = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
616
+ if (!Rec) throw new KitError('UNSUPPORTED', 'SpeechRecognition unavailable (Chrome only)');
617
+ return new Promise((resolve, reject) => {
618
+ const rec = new Rec();
619
+ if (opts.lang) rec.lang = opts.lang;
620
+ rec.interimResults = !!opts.partial;
621
+ rec.continuous = false;
622
+ let best = '';
623
+ let settled = false;
624
+ const finish = () => {
625
+ if (settled) return;
626
+ settled = true;
627
+ if (this.listenStop === stop) this.listenStop = null;
628
+ resolve(best);
629
+ };
630
+ const stop = () => { try { rec.stop(); } catch { /* already stopped */ } };
631
+ this.listenStop = stop;
632
+ rec.onresult = (e: any) => {
633
+ let interim = '';
634
+ let finalText = '';
635
+ for (let i = 0; i < e.results.length; i++) {
636
+ const t = e.results[i][0]?.transcript ?? '';
637
+ if (e.results[i].isFinal) finalText += t;
638
+ else interim += t;
639
+ }
640
+ best = (finalText || interim).trim();
641
+ if (opts.partial && interim) this.emit('speech.partial', { transcript: interim.trim() });
642
+ };
643
+ rec.onerror = (e: any) => {
644
+ if (settled) return;
645
+ settled = true;
646
+ if (this.listenStop === stop) this.listenStop = null;
647
+ reject(new KitError(e?.error === 'not-allowed' ? 'DENIED' : 'NATIVE_ERROR', e?.error ?? 'recognition failed'));
648
+ };
649
+ rec.onend = finish; // fires after stop() or natural end → resolve with best-so-far
650
+ rec.start();
651
+ });
652
+ }
653
+
550
654
  private pickImageFile(
551
655
  capture: boolean,
552
656
  wantDataUrl = false,
package/src/index.ts CHANGED
@@ -37,6 +37,7 @@ export type { UpdateStatus, UpdatesOptions } from './modules/updates';
37
37
  export type { PickedContact } from './modules/contacts';
38
38
  export type { ScanFormat, ScanOptions, ScanResult, ScanCancelled } from './modules/scanner';
39
39
  export { isScanResult } from './modules/scanner';
40
+ export type { SpeechVoice, SpeakOptions, ListenOptions, SpeechPartial } from './modules/speech';
40
41
  export type { CalendarEventOptions } from './modules/calendar';
41
42
  export type { BrowserOptions } from './modules/browser';
42
43
  export type { OAuthAuthorizeParams, OAuthResult } from './modules/oauth';
@@ -0,0 +1,99 @@
1
+ import type { NativeKit } from '../core/NativeKit';
2
+ import type { Unsubscribe } from '../core/types';
3
+
4
+ /** An installed synthesizer voice, as offered by {@link SpeechModule.voices}. */
5
+ export interface SpeechVoice {
6
+ /** Platform voice identifier — pass back as {@link SpeakOptions.voice} to select it. */
7
+ id: string;
8
+ /** Human-readable name (e.g. 'Samantha'). */
9
+ name: string;
10
+ /** BCP-47 language tag the voice speaks (e.g. 'en-US'). */
11
+ lang: string;
12
+ }
13
+
14
+ export interface SpeakOptions {
15
+ /** BCP-47 language for the utterance (e.g. 'en-US'). Defaults to the system/voice language. */
16
+ lang?: string;
17
+ /** Speaking rate. ~0.5 slow … 1 normal … 2 fast (platforms clamp to their own range). */
18
+ rate?: number;
19
+ /** Voice pitch. ~0.5 low … 1 normal … 2 high. */
20
+ pitch?: number;
21
+ /** A {@link SpeechVoice.id} from {@link SpeechModule.voices} to speak with. */
22
+ voice?: string;
23
+ }
24
+
25
+ export interface ListenOptions {
26
+ /** BCP-47 language to recognize (e.g. 'en-US'). Defaults to the device locale. */
27
+ lang?: string;
28
+ /** Stream interim results via {@link SpeechModule.onPartial} while listening. Default false. */
29
+ partial?: boolean;
30
+ }
31
+
32
+ /** Payload of {@link SpeechModule.onPartial}: the best-so-far interim transcript. */
33
+ export interface SpeechPartial {
34
+ /** Interim transcript text (not final — may change as recognition continues). */
35
+ transcript: string;
36
+ }
37
+
38
+ /**
39
+ * Voice I/O — text-to-speech (TTS) and speech-to-text (STT) — ONE API across platforms.
40
+ *
41
+ * TTS is permission-free: {@link speak} reads text aloud and resolves when the utterance finishes;
42
+ * {@link stop} cancels current/queued speech; {@link voices} lists installed synthesizer voices.
43
+ *
44
+ * STT carries microphone + speech-recognition permissions (the opt-in `speech` module stamps them).
45
+ * {@link listen} starts capture and resolves the FINAL transcript string; pass `{ partial: true }` to
46
+ * also stream interim results via {@link onPartial}. {@link stopListening} ends capture early and
47
+ * resolves the pending {@link listen} with the best transcript so far.
48
+ *
49
+ * Two HONEST capability flags — synthesis availability ≠ recognition availability:
50
+ * - {@link capability} (TTS): native iOS `AVSpeechSynthesizer` / Android `TextToSpeech`; web `'web'`
51
+ * when `speechSynthesis` exists, else `'none'`.
52
+ * - {@link recognitionCapability} (STT): native iOS `SFSpeechRecognizer` / Android `SpeechRecognizer`;
53
+ * web `'web'` when `SpeechRecognition`/`webkitSpeechRecognition` exists (Chrome) else `'none'` —
54
+ * then {@link listen} throws `KitError('UNSUPPORTED')`. Branch on the flag, not try/catch.
55
+ */
56
+ export class SpeechModule {
57
+ constructor(private kit: NativeKit) {}
58
+
59
+ /** TTS availability: 'native' on a shell · 'web' where speechSynthesis exists · else 'none'. */
60
+ get capability() {
61
+ return this.kit.capability('speech');
62
+ }
63
+
64
+ /** STT availability: 'native' on a shell · 'web' where SpeechRecognition exists · else 'none'. */
65
+ get recognitionCapability() {
66
+ return this.kit.capability('speechRecognition');
67
+ }
68
+
69
+ /** Speak `text` aloud; resolves when the utterance finishes (or is stopped). */
70
+ speak(text: string, opts: SpeakOptions = {}): Promise<void> {
71
+ return this.kit.invoke('speech.speak', { text, ...opts });
72
+ }
73
+
74
+ /** Cancel the current/queued utterance immediately. */
75
+ stop(): Promise<void> {
76
+ return this.kit.invoke('speech.stop');
77
+ }
78
+
79
+ /** List installed synthesizer voices. */
80
+ voices(): Promise<SpeechVoice[]> {
81
+ return this.kit.invoke('speech.voices');
82
+ }
83
+
84
+ /** Start capturing the mic; resolves the FINAL transcript. With `{ partial:true }`, interim
85
+ * results stream via {@link onPartial}. Throws `KitError('UNSUPPORTED')` where STT is absent. */
86
+ listen(opts: ListenOptions = {}): Promise<string> {
87
+ return this.kit.invoke('speech.listen', opts);
88
+ }
89
+
90
+ /** Stop capture early; the pending {@link listen} resolves with the best transcript so far. */
91
+ stopListening(): Promise<void> {
92
+ return this.kit.invoke('speech.stopListening');
93
+ }
94
+
95
+ /** Interim transcripts while listening (only when {@link listen} was called with `partial:true`). */
96
+ onPartial(cb: (p: SpeechPartial) => void): Unsubscribe {
97
+ return this.kit.on('speech.partial', (p) => cb(p as SpeechPartial));
98
+ }
99
+ }