react-voice-action-router 1.0.0 → 1.0.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nouman Ejaz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # react-voice-action-router 🎙️
2
+
3
+ > **Don't build a chatbot. Build a hands-free interface.**
4
+
5
+ [![npm version](https://img.shields.io/npm/v/react-voice-action-router.svg?style=flat-square)](https://www.npmjs.com/package/react-voice-action-router)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)
7
+
8
+ A headless, latency-first voice intent router for React applications. It bridges natural language speech to your existing React functions using an **LLM-Agnostic Adapter Pattern**.
9
+
10
+ * **Headless & Zero UI:** We provide the logic hooks; you build the interface (or keep it invisible).
11
+ * **Context-Aware:** The AI only knows about commands on the *current* screen, reducing costs and hallucinations.
12
+ * **Universal Adapter:** Works with OpenAI, Anthropic, local Llama models (Ollama), or your own secure backend.
13
+ * **Latency-First:** Supports instant execution for exact phrases, falling back to AI for fuzzy intents.
14
+
15
+ ---
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install react-voice-action-router
21
+ # Note: React 16.8+ is required for Hooks support.
@@ -0,0 +1 @@
1
+ export { c as createOpenAIAdapter } from '../index-DyZ8YKh9.mjs';
@@ -0,0 +1 @@
1
+ export { c as createOpenAIAdapter } from '../index-DyZ8YKh9.js';
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+
3
+ // src/core/prompt.ts
4
+ var createSystemPrompt = (commands) => {
5
+ const commandList = commands.map(
6
+ (cmd) => `- ID: "${cmd.id}" | Description: "${cmd.description}"`
7
+ ).join("\n");
8
+ return `
9
+ You are a precise Voice Command Router.
10
+ Your goal is to map the user's spoken input to the correct Command ID from the list below.
11
+
12
+ RULES:
13
+ 1. Analyze the user's input and find the intent.
14
+ 2. Match it to the command with the most relevant "Description".
15
+ 3. Use fuzzy matching (e.g., "Dark mode" matches "Toggle Theme").
16
+ 4. If NO command matches the intent, return null.
17
+ 5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.
18
+
19
+ AVAILABLE COMMANDS:
20
+ ${commandList}
21
+
22
+ RESPONSE FORMAT:
23
+ { "commandId": "string_id_or_null" }
24
+ `;
25
+ };
26
+
27
+ // src/adapters/openai.ts
28
+ var createOpenAIAdapter = (config) => {
29
+ return async (transcript, commands) => {
30
+ const systemPrompt = createSystemPrompt(commands);
31
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
32
+ method: "POST",
33
+ headers: {
34
+ "Content-Type": "application/json",
35
+ "Authorization": `Bearer ${config.apiKey}`
36
+ },
37
+ body: JSON.stringify({
38
+ model: config.model || "gpt-4o-mini",
39
+ messages: [
40
+ { role: "system", content: systemPrompt },
41
+ { role: "user", content: transcript }
42
+ ],
43
+ temperature: 0,
44
+ // Deterministic results
45
+ response_format: { type: "json_object" }
46
+ // Force JSON mode
47
+ })
48
+ });
49
+ if (!response.ok) {
50
+ throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);
51
+ }
52
+ const data = await response.json();
53
+ try {
54
+ const parsed = JSON.parse(data.choices[0].message.content);
55
+ return { commandId: parsed.commandId };
56
+ } catch (e) {
57
+ console.error("Failed to parse LLM response", e);
58
+ return { commandId: null };
59
+ }
60
+ };
61
+ };
62
+
63
+ exports.createOpenAIAdapter = createOpenAIAdapter;
64
+ //# sourceMappingURL=index.js.map
65
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/prompt.ts","../../src/adapters/openai.ts"],"names":[],"mappings":";;;AAMO,IAAM,kBAAA,GAAqB,CAAC,QAAA,KAA6C;AAE5E,EAAA,MAAM,cAAc,QAAA,CAAS,GAAA;AAAA,IAAI,SAC7B,CAAA,OAAA,EAAU,GAAA,CAAI,EAAE,CAAA,kBAAA,EAAqB,IAAI,WAAW,CAAA,CAAA;AAAA,GACxD,CAAE,KAAK,IAAI,CAAA;AAEX,EAAA,OAAO;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA,EAYT,WAAW;;AAAA;AAAA;AAAA,CAAA;AAKb,CAAA;;;AChBO,IAAM,mBAAA,GAAsB,CAAC,MAAA,KAAqC;AACrE,EAAA,OAAO,OAAO,YAAY,QAAA,KAAa;AAGnC,IAAA,MAAM,YAAA,GAAe,mBAAmB,QAAQ,CAAA;AAGhD,IAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,4CAAA,EAA8C;AAAA,MACvE,MAAA,EAAQ,MAAA;AAAA,MACR,OAAA,EAAS;AAAA,QACL,cAAA,EAAgB,kBAAA;AAAA,QAChB,eAAA,EAAiB,CAAA,OAAA,EAAU,MAAA,CAAO,MAAM,CAAA;AAAA,OAC5C;AAAA,MACA,IAAA,EAAM,KAAK,SAAA,CAAU;AAAA,QACjB,KAAA,EAAO,OAAO,KAAA,IAAS,aAAA;AAAA,QACvB,QAAA,EAAU;AAAA,UACN,EAAE,IAAA,EAAM,QAAA,EAAU,OAAA,EAAS,YAAA,EAAa;AAAA,UACxC,EAAE,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,UAAA;AAAW,SACxC;AAAA,QACA,WAAA,EAAa,CAAA;AAAA;AAAA,QACb,eAAA,EAAiB,EAAE,IAAA,EAAM,aAAA;AAAc;AAAA,OAC1C;AAAA,KACJ,CAAA;AAED,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AACd,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,uBAAA,EAA0B,QAAA,CAAS,UAAU,CAAA,CAAE,CAAA;AAAA,IACnE;AAEA,IAAA,MAAM,IAAA,GAAO,MAAM,QAAA,CAAS,IAAA,EAAK;AAGjC,IAAA,IAAI;AACA,MAAA,MAAM,MAAA,GAAS,KAAK,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAC,CAAA,CAAE,QAAQ,OAAO,CAAA;AACzD,MAAA,OAAO,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU;AAAA,IACzC,SAAS,CAAA,EAAG;AACR,MAAA,OAAA,CAAQ,KAAA,CAAM,gCAAgC,CAAC,CAAA;AAC/C,MAAA,OAAO,EAAE,WAAW,IAAA,EAAK;AAAA,IAC7B;AAAA,EACJ,CAAA;AACJ","file":"index.js","sourcesContent":["import { VoiceCommand } from '../types';\n\n/**\n * Generates the System Prompt for the LLM.\n * This ensures consistent behavior across different AI providers.\n */\nexport const createSystemPrompt = (commands: Omit<VoiceCommand, 'action'>[]) => {\n // Format the list of commands for the AI to read\n const commandList = commands.map(cmd =>\n `- ID: \"${cmd.id}\" | Description: \"${cmd.description}\"`\n ).join('\\n');\n\n return `\nYou are a precise Voice Command Router.\nYour goal is to map the user's spoken input to the correct Command ID from the list below.\n\nRULES:\n1. Analyze the user's input and find the intent.\n2. Match it to the command with the most relevant \"Description\".\n3. Use fuzzy matching (e.g., \"Dark mode\" matches \"Toggle Theme\").\n4. If NO command matches the intent, return null.\n5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.\n\nAVAILABLE COMMANDS:\n${commandList}\n\nRESPONSE FORMAT:\n{ \"commandId\": \"string_id_or_null\" }\n`;\n};\n\n/**\n * Standardizes how the user's voice transcript is presented to the AI.\n */\nexport const createUserPrompt = (transcript: string) => {\n return `User Input: \"${transcript}\"`;\n};","import { LLMAdapter } from '../types';\nimport { createSystemPrompt } from '../core/prompt';\n\ninterface OpenAIConfig {\n apiKey: string;\n /** @default \"gpt-4o-mini\" */\n model?: string;\n}\n\n/**\n * A Factory that creates an Adapter for OpenAI.\n * Users call this: createOpenAIAdapter({ apiKey: '...' })\n */\nexport const createOpenAIAdapter = (config: OpenAIConfig): LLMAdapter => {\n return async (transcript, commands) => {\n\n // 1. Generate the optimized system instructions\n const systemPrompt = createSystemPrompt(commands);\n\n // 2. Call the API\n const response = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`\n },\n body: JSON.stringify({\n model: config.model || \"gpt-4o-mini\",\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: transcript }\n ],\n temperature: 0, // Deterministic results\n response_format: { type: \"json_object\" } // Force JSON mode\n })\n });\n\n if (!response.ok) {\n throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // 3. Parse the result\n try {\n const parsed = JSON.parse(data.choices[0].message.content);\n return { commandId: parsed.commandId };\n } catch (e) {\n console.error(\"Failed to parse LLM response\", e);\n return { commandId: null };\n }\n };\n};"]}
@@ -0,0 +1,63 @@
1
+ // src/core/prompt.ts
2
+ var createSystemPrompt = (commands) => {
3
+ const commandList = commands.map(
4
+ (cmd) => `- ID: "${cmd.id}" | Description: "${cmd.description}"`
5
+ ).join("\n");
6
+ return `
7
+ You are a precise Voice Command Router.
8
+ Your goal is to map the user's spoken input to the correct Command ID from the list below.
9
+
10
+ RULES:
11
+ 1. Analyze the user's input and find the intent.
12
+ 2. Match it to the command with the most relevant "Description".
13
+ 3. Use fuzzy matching (e.g., "Dark mode" matches "Toggle Theme").
14
+ 4. If NO command matches the intent, return null.
15
+ 5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.
16
+
17
+ AVAILABLE COMMANDS:
18
+ ${commandList}
19
+
20
+ RESPONSE FORMAT:
21
+ { "commandId": "string_id_or_null" }
22
+ `;
23
+ };
24
+
25
+ // src/adapters/openai.ts
26
+ var createOpenAIAdapter = (config) => {
27
+ return async (transcript, commands) => {
28
+ const systemPrompt = createSystemPrompt(commands);
29
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
30
+ method: "POST",
31
+ headers: {
32
+ "Content-Type": "application/json",
33
+ "Authorization": `Bearer ${config.apiKey}`
34
+ },
35
+ body: JSON.stringify({
36
+ model: config.model || "gpt-4o-mini",
37
+ messages: [
38
+ { role: "system", content: systemPrompt },
39
+ { role: "user", content: transcript }
40
+ ],
41
+ temperature: 0,
42
+ // Deterministic results
43
+ response_format: { type: "json_object" }
44
+ // Force JSON mode
45
+ })
46
+ });
47
+ if (!response.ok) {
48
+ throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);
49
+ }
50
+ const data = await response.json();
51
+ try {
52
+ const parsed = JSON.parse(data.choices[0].message.content);
53
+ return { commandId: parsed.commandId };
54
+ } catch (e) {
55
+ console.error("Failed to parse LLM response", e);
56
+ return { commandId: null };
57
+ }
58
+ };
59
+ };
60
+
61
+ export { createOpenAIAdapter };
62
+ //# sourceMappingURL=index.mjs.map
63
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/prompt.ts","../../src/adapters/openai.ts"],"names":[],"mappings":";AAMO,IAAM,kBAAA,GAAqB,CAAC,QAAA,K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O,MAAM,QAAA,CAAS,IAAA,EAAK;AAGjC,IAAA,IAAI;AACA,MAAA,MAAM,MAAA,GAAS,KAAK,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAC,CAAA,CAAE,QAAQ,OAAO,CAAA;AACzD,MAAA,OAAO,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU;AAAA,IACzC,SAAS,CAAA,EAAG;AACR,MAAA,OAAA,CAAQ,KAAA,CAAM,gCAAgC,CAAC,CAAA;AAC/C,MAAA,OAAO,EAAE,WAAW,IAAA,EAAK;AAAA,IAC7B;AAAA,EACJ,CAAA;AACJ","file":"index.mjs","sourcesContent":["import { VoiceCommand } from '../types';\n\n/**\n * Generates the System Prompt for the LLM.\n * This ensures consistent behavior across different AI providers.\n */\nexport const createSystemPrompt = (commands: Omit<VoiceCommand, 'action'>[]) => {\n // Format the list of commands for the AI to read\n const commandList = commands.map(cmd =>\n `- ID: \"${cmd.id}\" | Description: \"${cmd.description}\"`\n ).join('\\n');\n\n return `\nYou are a precise Voice Command Router.\nYour goal is to map the user's spoken input to the correct Command ID from the list below.\n\nRULES:\n1. Analyze the user's input and find the intent.\n2. Match it to the command with the most relevant \"Description\".\n3. Use fuzzy matching (e.g., \"Dark mode\" matches \"Toggle Theme\").\n4. If NO command matches the intent, return null.\n5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.\n\nAVAILABLE COMMANDS:\n${commandList}\n\nRESPONSE FORMAT:\n{ \"commandId\": \"string_id_or_null\" }\n`;\n};\n\n/**\n * Standardizes how the user's voice transcript is presented to the AI.\n */\nexport const createUserPrompt = (transcript: string) => {\n return `User Input: \"${transcript}\"`;\n};","import { LLMAdapter } from '../types';\nimport { createSystemPrompt } from '../core/prompt';\n\ninterface OpenAIConfig {\n apiKey: string;\n /** @default \"gpt-4o-mini\" */\n model?: string;\n}\n\n/**\n * A Factory that creates an Adapter for OpenAI.\n * Users call this: createOpenAIAdapter({ apiKey: '...' })\n */\nexport const createOpenAIAdapter = (config: OpenAIConfig): LLMAdapter => {\n return async (transcript, commands) => {\n\n // 1. Generate the optimized system instructions\n const systemPrompt = createSystemPrompt(commands);\n\n // 2. Call the API\n const response = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`\n },\n body: JSON.stringify({\n model: config.model || \"gpt-4o-mini\",\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: transcript }\n ],\n temperature: 0, // Deterministic results\n response_format: { type: \"json_object\" } // Force JSON mode\n })\n });\n\n if (!response.ok) {\n throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // 3. Parse the result\n try {\n const parsed = JSON.parse(data.choices[0].message.content);\n return { commandId: parsed.commandId };\n } catch (e) {\n console.error(\"Failed to parse LLM response\", e);\n return { commandId: null };\n }\n };\n};"]}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * A voice command that can be registered by a component.
3
+ */
4
+ interface VoiceCommand {
5
+ /** Unique identifier for the command (e.g., 'nav_home') */
6
+ id: string;
7
+ /** Natural language description for the LLM (e.g., 'Navigate to the home dashboard') */
8
+ description: string;
9
+ /** Optional: Exact phrase for 0-latency matching (e.g., 'Go Home') */
10
+ phrase?: string;
11
+ /** The function to execute when matched */
12
+ action: () => void;
13
+ }
14
+ /**
15
+ * The internal state of the voice engine.
16
+ */
17
+ interface VoiceControlState {
18
+ isListening: boolean;
19
+ isProcessing: boolean;
20
+ lastTranscript: string | null;
21
+ /** Exposed primarily for debugging/visualization */
22
+ activeCommands: VoiceCommand[];
23
+ }
24
+ /**
25
+ * The Adapter Protocol ("The Universal Plug").
26
+ * Any AI provider (OpenAI, Anthropic, Local) must match this signature.
27
+ */
28
+ type LLMAdapter = (transcript: string, commands: Omit<VoiceCommand, 'action'>[]) => Promise<{
29
+ commandId: string | null;
30
+ }>;
31
+ interface VoiceProviderProps {
32
+ children: React.ReactNode;
33
+ /** The AI Adapter function */
34
+ adapter: LLMAdapter;
35
+ /** Optional: Trigger word (e.g., "Jarvis") - not implemented in MVP */
36
+ wakeWord?: string;
37
+ /** Optional: Callback for debugging state changes */
38
+ onStateChange?: (state: VoiceControlState) => void;
39
+ }
40
+
41
+ interface OpenAIConfig {
42
+ apiKey: string;
43
+ /** @default "gpt-4o-mini" */
44
+ model?: string;
45
+ }
46
+ /**
47
+ * A Factory that creates an Adapter for OpenAI.
48
+ * Users call this: createOpenAIAdapter({ apiKey: '...' })
49
+ */
50
+ declare const createOpenAIAdapter: (config: OpenAIConfig) => LLMAdapter;
51
+
52
+ export { type LLMAdapter as L, type VoiceProviderProps as V, type VoiceControlState as a, type VoiceCommand as b, createOpenAIAdapter as c };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * A voice command that can be registered by a component.
3
+ */
4
+ interface VoiceCommand {
5
+ /** Unique identifier for the command (e.g., 'nav_home') */
6
+ id: string;
7
+ /** Natural language description for the LLM (e.g., 'Navigate to the home dashboard') */
8
+ description: string;
9
+ /** Optional: Exact phrase for 0-latency matching (e.g., 'Go Home') */
10
+ phrase?: string;
11
+ /** The function to execute when matched */
12
+ action: () => void;
13
+ }
14
+ /**
15
+ * The internal state of the voice engine.
16
+ */
17
+ interface VoiceControlState {
18
+ isListening: boolean;
19
+ isProcessing: boolean;
20
+ lastTranscript: string | null;
21
+ /** Exposed primarily for debugging/visualization */
22
+ activeCommands: VoiceCommand[];
23
+ }
24
+ /**
25
+ * The Adapter Protocol ("The Universal Plug").
26
+ * Any AI provider (OpenAI, Anthropic, Local) must match this signature.
27
+ */
28
+ type LLMAdapter = (transcript: string, commands: Omit<VoiceCommand, 'action'>[]) => Promise<{
29
+ commandId: string | null;
30
+ }>;
31
+ interface VoiceProviderProps {
32
+ children: React.ReactNode;
33
+ /** The AI Adapter function */
34
+ adapter: LLMAdapter;
35
+ /** Optional: Trigger word (e.g., "Jarvis") - not implemented in MVP */
36
+ wakeWord?: string;
37
+ /** Optional: Callback for debugging state changes */
38
+ onStateChange?: (state: VoiceControlState) => void;
39
+ }
40
+
41
+ interface OpenAIConfig {
42
+ apiKey: string;
43
+ /** @default "gpt-4o-mini" */
44
+ model?: string;
45
+ }
46
+ /**
47
+ * A Factory that creates an Adapter for OpenAI.
48
+ * Users call this: createOpenAIAdapter({ apiKey: '...' })
49
+ */
50
+ declare const createOpenAIAdapter: (config: OpenAIConfig) => LLMAdapter;
51
+
52
+ export { type LLMAdapter as L, type VoiceProviderProps as V, type VoiceControlState as a, type VoiceCommand as b, createOpenAIAdapter as c };
@@ -0,0 +1,25 @@
1
+ import React from 'react';
2
+ import { V as VoiceProviderProps, a as VoiceControlState, b as VoiceCommand } from './index-DyZ8YKh9.mjs';
3
+ export { L as LLMAdapter, c as createOpenAIAdapter } from './index-DyZ8YKh9.mjs';
4
+
5
+ interface VoiceContextValue extends VoiceControlState {
6
+ register: (cmd: VoiceCommand) => void;
7
+ unregister: (id: string) => void;
8
+ processTranscript: (text: string) => Promise<void>;
9
+ }
10
+ declare const VoiceControlProvider: React.FC<VoiceProviderProps>;
11
+ declare const useVoiceContext: () => VoiceContextValue;
12
+
13
+ /**
14
+ * The Developer Hook
15
+ * Wraps the lifecycle logic so the developer doesn't have to.
16
+ * * Usage:
17
+ * useVoiceCommand({
18
+ * id: 'nav_home',
19
+ * description: 'Go to home',
20
+ * action: () => navigate('/')
21
+ * });
22
+ */
23
+ declare const useVoiceCommand: (command: VoiceCommand) => void;
24
+
25
+ export { VoiceCommand, VoiceControlProvider, VoiceControlState, useVoiceCommand, useVoiceContext };
@@ -0,0 +1,25 @@
1
+ import React from 'react';
2
+ import { V as VoiceProviderProps, a as VoiceControlState, b as VoiceCommand } from './index-DyZ8YKh9.js';
3
+ export { L as LLMAdapter, c as createOpenAIAdapter } from './index-DyZ8YKh9.js';
4
+
5
+ interface VoiceContextValue extends VoiceControlState {
6
+ register: (cmd: VoiceCommand) => void;
7
+ unregister: (id: string) => void;
8
+ processTranscript: (text: string) => Promise<void>;
9
+ }
10
+ declare const VoiceControlProvider: React.FC<VoiceProviderProps>;
11
+ declare const useVoiceContext: () => VoiceContextValue;
12
+
13
+ /**
14
+ * The Developer Hook
15
+ * Wraps the lifecycle logic so the developer doesn't have to.
16
+ * * Usage:
17
+ * useVoiceCommand({
18
+ * id: 'nav_home',
19
+ * description: 'Go to home',
20
+ * action: () => navigate('/')
21
+ * });
22
+ */
23
+ declare const useVoiceCommand: (command: VoiceCommand) => void;
24
+
25
+ export { VoiceCommand, VoiceControlProvider, VoiceControlState, useVoiceCommand, useVoiceContext };
package/dist/index.js ADDED
@@ -0,0 +1,147 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+ var jsxRuntime = require('react/jsx-runtime');
5
+
6
+ // src/components/VoiceContext.tsx
7
+ var VoiceContext = react.createContext(null);
8
+ var VoiceControlProvider = ({
9
+ children,
10
+ adapter
11
+ }) => {
12
+ const commandsRef = react.useRef(/* @__PURE__ */ new Map());
13
+ const [state, setState] = react.useState({
14
+ isListening: false,
15
+ isProcessing: false,
16
+ lastTranscript: null,
17
+ activeCommands: []
18
+ });
19
+ const register = react.useCallback((cmd) => {
20
+ commandsRef.current.set(cmd.id, cmd);
21
+ setState((prev) => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));
22
+ }, []);
23
+ const unregister = react.useCallback((id) => {
24
+ commandsRef.current.delete(id);
25
+ setState((prev) => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));
26
+ }, []);
27
+ const processTranscript = react.useCallback(async (transcript) => {
28
+ const cleanText = transcript.trim().toLowerCase();
29
+ setState((prev) => ({ ...prev, isProcessing: true, lastTranscript: cleanText }));
30
+ const allCommands = Array.from(commandsRef.current.values());
31
+ const exactMatch = allCommands.find((c) => {
32
+ var _a;
33
+ return ((_a = c.phrase) == null ? void 0 : _a.toLowerCase()) === cleanText;
34
+ });
35
+ if (exactMatch) {
36
+ console.log(`\u26A1 Instant Match: "${cleanText}" -> ${exactMatch.id}`);
37
+ exactMatch.action();
38
+ setState((prev) => ({ ...prev, isProcessing: false }));
39
+ return;
40
+ }
41
+ try {
42
+ console.log(`\u{1F916} AI Routing: "${cleanText}"...`);
43
+ const commandListForAI = allCommands.map(({ id, description, phrase }) => ({
44
+ id,
45
+ description,
46
+ phrase
47
+ }));
48
+ const result = await adapter(cleanText, commandListForAI);
49
+ if (result.commandId) {
50
+ const cmd = commandsRef.current.get(result.commandId);
51
+ if (cmd) {
52
+ console.log(`\u2705 Matched: ${cmd.id}`);
53
+ cmd.action();
54
+ } else {
55
+ console.warn(`\u26A0\uFE0F Adapter returned unknown ID: ${result.commandId}`);
56
+ }
57
+ }
58
+ } catch (error) {
59
+ console.error("Adapter Error:", error);
60
+ } finally {
61
+ setState((prev) => ({ ...prev, isProcessing: false }));
62
+ }
63
+ }, [adapter]);
64
+ return /* @__PURE__ */ jsxRuntime.jsx(VoiceContext.Provider, { value: { ...state, register, unregister, processTranscript }, children });
65
+ };
66
+ var useVoiceContext = () => {
67
+ const ctx = react.useContext(VoiceContext);
68
+ if (!ctx) throw new Error("useVoiceContext must be used within a VoiceControlProvider");
69
+ return ctx;
70
+ };
71
+ var useVoiceCommand = (command) => {
72
+ const { register, unregister } = useVoiceContext();
73
+ const idRef = react.useRef(command.id);
74
+ react.useEffect(() => {
75
+ register(command);
76
+ return () => {
77
+ unregister(idRef.current);
78
+ };
79
+ }, [register, unregister, command]);
80
+ };
81
+
82
+ // src/core/prompt.ts
83
+ var createSystemPrompt = (commands) => {
84
+ const commandList = commands.map(
85
+ (cmd) => `- ID: "${cmd.id}" | Description: "${cmd.description}"`
86
+ ).join("\n");
87
+ return `
88
+ You are a precise Voice Command Router.
89
+ Your goal is to map the user's spoken input to the correct Command ID from the list below.
90
+
91
+ RULES:
92
+ 1. Analyze the user's input and find the intent.
93
+ 2. Match it to the command with the most relevant "Description".
94
+ 3. Use fuzzy matching (e.g., "Dark mode" matches "Toggle Theme").
95
+ 4. If NO command matches the intent, return null.
96
+ 5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.
97
+
98
+ AVAILABLE COMMANDS:
99
+ ${commandList}
100
+
101
+ RESPONSE FORMAT:
102
+ { "commandId": "string_id_or_null" }
103
+ `;
104
+ };
105
+
106
+ // src/adapters/openai.ts
107
+ var createOpenAIAdapter = (config) => {
108
+ return async (transcript, commands) => {
109
+ const systemPrompt = createSystemPrompt(commands);
110
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
111
+ method: "POST",
112
+ headers: {
113
+ "Content-Type": "application/json",
114
+ "Authorization": `Bearer ${config.apiKey}`
115
+ },
116
+ body: JSON.stringify({
117
+ model: config.model || "gpt-4o-mini",
118
+ messages: [
119
+ { role: "system", content: systemPrompt },
120
+ { role: "user", content: transcript }
121
+ ],
122
+ temperature: 0,
123
+ // Deterministic results
124
+ response_format: { type: "json_object" }
125
+ // Force JSON mode
126
+ })
127
+ });
128
+ if (!response.ok) {
129
+ throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);
130
+ }
131
+ const data = await response.json();
132
+ try {
133
+ const parsed = JSON.parse(data.choices[0].message.content);
134
+ return { commandId: parsed.commandId };
135
+ } catch (e) {
136
+ console.error("Failed to parse LLM response", e);
137
+ return { commandId: null };
138
+ }
139
+ };
140
+ };
141
+
142
+ exports.VoiceControlProvider = VoiceControlProvider;
143
+ exports.createOpenAIAdapter = createOpenAIAdapter;
144
+ exports.useVoiceCommand = useVoiceCommand;
145
+ exports.useVoiceContext = useVoiceContext;
146
+ //# sourceMappingURL=index.js.map
147
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/VoiceContext.tsx","../src/hooks/useVoiceCommand.ts","../src/core/prompt.ts","../src/adapters/openai.ts"],"names":["createContext","useRef","useState","useCallback","jsx","useContext","useEffect"],"mappings":";;;;;;AASA,IAAM,YAAA,GAAeA,oBAAwC,IAAI,CAAA;AAE1D,IAAM,uBAAqD,CAAC;AAAA,EACjE,QAAA;AAAA,EACA;AACF,CAAA,K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,MAAA,GAAS,KAAK,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAC,CAAA,CAAE,QAAQ,OAAO,CAAA;AACzD,MAAA,OAAO,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU;AAAA,IACzC,SAAS,CAAA,EAAG;AACR,MAAA,OAAA,CAAQ,KAAA,CAAM,gCAAgC,CAAC,CAAA;AAC/C,MAAA,OAAO,EAAE,WAAW,IAAA,EAAK;AAAA,IAC7B;AAAA,EACJ,CAAA;AACJ","file":"index.js","sourcesContent":["import React, { createContext, useContext, useState, useCallback, useRef } from 'react';\nimport { VoiceCommand, VoiceControlState, VoiceProviderProps } from '../types';\n\ninterface VoiceContextValue extends VoiceControlState {\n register: (cmd: VoiceCommand) => void;\n unregister: (id: string) => void;\n processTranscript: (text: string) => Promise<void>;\n}\n\nconst VoiceContext = createContext<VoiceContextValue | null>(null);\n\nexport const VoiceControlProvider: React.FC<VoiceProviderProps> = ({ \n children, \n adapter \n}) => {\n // THE REGISTRY: A Map ensures O(1) lookups and prevents duplicate IDs\n const commandsRef = useRef<Map<string, VoiceCommand>>(new Map());\n \n // UI STATE\n const [state, setState] = useState<VoiceControlState>({\n isListening: false,\n isProcessing: false,\n lastTranscript: null,\n activeCommands: [],\n });\n\n // 1. REGISTRATION LOGIC\n const register = useCallback((cmd: VoiceCommand) => {\n commandsRef.current.set(cmd.id, cmd);\n // Update generic state for debugging UI\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\n }, []);\n\n const unregister = useCallback((id: string) => {\n commandsRef.current.delete(id);\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\n }, []);\n\n // 2. THE ROUTER LOGIC\n const processTranscript = useCallback(async (transcript: string) => {\n const cleanText = transcript.trim().toLowerCase();\n setState(prev => ({ ...prev, isProcessing: true, lastTranscript: cleanText }));\n\n const allCommands = Array.from(commandsRef.current.values());\n\n // PHASE 1: EXACT MATCH (0ms Latency)\n const exactMatch = allCommands.find(c => c.phrase?.toLowerCase() === cleanText);\n \n if (exactMatch) {\n console.log(`⚡ Instant Match: \"${cleanText}\" -> ${exactMatch.id}`);\n exactMatch.action();\n setState(prev => ({ ...prev, isProcessing: false }));\n return;\n }\n\n // PHASE 2: FUZZY MATCH (AI Adapter)\n try {\n console.log(`🤖 AI Routing: \"${cleanText}\"...`);\n \n // We strip the 'action' function before sending to the AI\n const commandListForAI = allCommands.map(({ id, description, phrase }) => ({ \n id, \n description, \n phrase \n }));\n\n const result = await adapter(cleanText, commandListForAI);\n\n if (result.commandId) {\n const cmd = commandsRef.current.get(result.commandId);\n if (cmd) {\n console.log(`✅ Matched: ${cmd.id}`);\n cmd.action();\n } else {\n console.warn(`⚠️ Adapter returned unknown ID: ${result.commandId}`);\n }\n }\n } catch (error) {\n console.error(\"Adapter Error:\", error);\n } finally {\n setState(prev => ({ ...prev, isProcessing: false }));\n }\n }, [adapter]);\n\n return (\n <VoiceContext.Provider value={{ ...state, register, unregister, processTranscript }}>\n {children}\n </VoiceContext.Provider>\n );\n};\n\nexport const useVoiceContext = () => {\n const ctx = useContext(VoiceContext);\n if (!ctx) throw new Error(\"useVoiceContext must be used within a VoiceControlProvider\");\n return ctx;\n};","import { useEffect, useRef } from 'react';\nimport { useVoiceContext } from '../components/VoiceContext';\nimport { VoiceCommand } from '../types';\n\n/**\n * The Developer Hook\n * Wraps the lifecycle logic so the developer doesn't have to.\n * * Usage:\n * useVoiceCommand({\n * id: 'nav_home',\n * description: 'Go to home',\n * action: () => navigate('/')\n * });\n */\nexport const useVoiceCommand = (command: VoiceCommand) => {\n const { register, unregister } = useVoiceContext();\n\n // Use a ref to keep the ID stable across renders\n const idRef = useRef(command.id);\n\n useEffect(() => {\n // 1. Mount: Register the tool\n register(command);\n\n // 2. Unmount: Remove the tool\n return () => {\n unregister(idRef.current);\n };\n }, [register, unregister, command]); // Re-register if command definition changes\n};","import { VoiceCommand } from '../types';\n\n/**\n * Generates the System Prompt for the LLM.\n * This ensures consistent behavior across different AI providers.\n */\nexport const createSystemPrompt = (commands: Omit<VoiceCommand, 'action'>[]) => {\n // Format the list of commands for the AI to read\n const commandList = commands.map(cmd =>\n `- ID: \"${cmd.id}\" | Description: \"${cmd.description}\"`\n ).join('\\n');\n\n return `\nYou are a precise Voice Command Router.\nYour goal is to map the user's spoken input to the correct Command ID from the list below.\n\nRULES:\n1. Analyze the user's input and find the intent.\n2. Match it to the command with the most relevant \"Description\".\n3. Use fuzzy matching (e.g., \"Dark mode\" matches \"Toggle Theme\").\n4. If NO command matches the intent, return null.\n5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.\n\nAVAILABLE COMMANDS:\n${commandList}\n\nRESPONSE FORMAT:\n{ \"commandId\": \"string_id_or_null\" }\n`;\n};\n\n/**\n * Standardizes how the user's voice transcript is presented to the AI.\n */\nexport const createUserPrompt = (transcript: string) => {\n return `User Input: \"${transcript}\"`;\n};","import { LLMAdapter } from '../types';\nimport { createSystemPrompt } from '../core/prompt';\n\ninterface OpenAIConfig {\n apiKey: string;\n /** @default \"gpt-4o-mini\" */\n model?: string;\n}\n\n/**\n * A Factory that creates an Adapter for OpenAI.\n * Users call this: createOpenAIAdapter({ apiKey: '...' })\n */\nexport const createOpenAIAdapter = (config: OpenAIConfig): LLMAdapter => {\n return async (transcript, commands) => {\n\n // 1. Generate the optimized system instructions\n const systemPrompt = createSystemPrompt(commands);\n\n // 2. Call the API\n const response = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`\n },\n body: JSON.stringify({\n model: config.model || \"gpt-4o-mini\",\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: transcript }\n ],\n temperature: 0, // Deterministic results\n response_format: { type: \"json_object\" } // Force JSON mode\n })\n });\n\n if (!response.ok) {\n throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // 3. Parse the result\n try {\n const parsed = JSON.parse(data.choices[0].message.content);\n return { commandId: parsed.commandId };\n } catch (e) {\n console.error(\"Failed to parse LLM response\", e);\n return { commandId: null };\n }\n };\n};"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,142 @@
1
+ import { createContext, useRef, useState, useCallback, useContext, useEffect } from 'react';
2
+ import { jsx } from 'react/jsx-runtime';
3
+
4
+ // src/components/VoiceContext.tsx
5
+ var VoiceContext = createContext(null);
6
+ var VoiceControlProvider = ({
7
+ children,
8
+ adapter
9
+ }) => {
10
+ const commandsRef = useRef(/* @__PURE__ */ new Map());
11
+ const [state, setState] = useState({
12
+ isListening: false,
13
+ isProcessing: false,
14
+ lastTranscript: null,
15
+ activeCommands: []
16
+ });
17
+ const register = useCallback((cmd) => {
18
+ commandsRef.current.set(cmd.id, cmd);
19
+ setState((prev) => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));
20
+ }, []);
21
+ const unregister = useCallback((id) => {
22
+ commandsRef.current.delete(id);
23
+ setState((prev) => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));
24
+ }, []);
25
+ const processTranscript = useCallback(async (transcript) => {
26
+ const cleanText = transcript.trim().toLowerCase();
27
+ setState((prev) => ({ ...prev, isProcessing: true, lastTranscript: cleanText }));
28
+ const allCommands = Array.from(commandsRef.current.values());
29
+ const exactMatch = allCommands.find((c) => {
30
+ var _a;
31
+ return ((_a = c.phrase) == null ? void 0 : _a.toLowerCase()) === cleanText;
32
+ });
33
+ if (exactMatch) {
34
+ console.log(`\u26A1 Instant Match: "${cleanText}" -> ${exactMatch.id}`);
35
+ exactMatch.action();
36
+ setState((prev) => ({ ...prev, isProcessing: false }));
37
+ return;
38
+ }
39
+ try {
40
+ console.log(`\u{1F916} AI Routing: "${cleanText}"...`);
41
+ const commandListForAI = allCommands.map(({ id, description, phrase }) => ({
42
+ id,
43
+ description,
44
+ phrase
45
+ }));
46
+ const result = await adapter(cleanText, commandListForAI);
47
+ if (result.commandId) {
48
+ const cmd = commandsRef.current.get(result.commandId);
49
+ if (cmd) {
50
+ console.log(`\u2705 Matched: ${cmd.id}`);
51
+ cmd.action();
52
+ } else {
53
+ console.warn(`\u26A0\uFE0F Adapter returned unknown ID: ${result.commandId}`);
54
+ }
55
+ }
56
+ } catch (error) {
57
+ console.error("Adapter Error:", error);
58
+ } finally {
59
+ setState((prev) => ({ ...prev, isProcessing: false }));
60
+ }
61
+ }, [adapter]);
62
+ return /* @__PURE__ */ jsx(VoiceContext.Provider, { value: { ...state, register, unregister, processTranscript }, children });
63
+ };
64
+ var useVoiceContext = () => {
65
+ const ctx = useContext(VoiceContext);
66
+ if (!ctx) throw new Error("useVoiceContext must be used within a VoiceControlProvider");
67
+ return ctx;
68
+ };
69
+ var useVoiceCommand = (command) => {
70
+ const { register, unregister } = useVoiceContext();
71
+ const idRef = useRef(command.id);
72
+ useEffect(() => {
73
+ register(command);
74
+ return () => {
75
+ unregister(idRef.current);
76
+ };
77
+ }, [register, unregister, command]);
78
+ };
79
+
80
+ // src/core/prompt.ts
81
+ var createSystemPrompt = (commands) => {
82
+ const commandList = commands.map(
83
+ (cmd) => `- ID: "${cmd.id}" | Description: "${cmd.description}"`
84
+ ).join("\n");
85
+ return `
86
+ You are a precise Voice Command Router.
87
+ Your goal is to map the user's spoken input to the correct Command ID from the list below.
88
+
89
+ RULES:
90
+ 1. Analyze the user's input and find the intent.
91
+ 2. Match it to the command with the most relevant "Description".
92
+ 3. Use fuzzy matching (e.g., "Dark mode" matches "Toggle Theme").
93
+ 4. If NO command matches the intent, return null.
94
+ 5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.
95
+
96
+ AVAILABLE COMMANDS:
97
+ ${commandList}
98
+
99
+ RESPONSE FORMAT:
100
+ { "commandId": "string_id_or_null" }
101
+ `;
102
+ };
103
+
104
+ // src/adapters/openai.ts
105
+ var createOpenAIAdapter = (config) => {
106
+ return async (transcript, commands) => {
107
+ const systemPrompt = createSystemPrompt(commands);
108
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
109
+ method: "POST",
110
+ headers: {
111
+ "Content-Type": "application/json",
112
+ "Authorization": `Bearer ${config.apiKey}`
113
+ },
114
+ body: JSON.stringify({
115
+ model: config.model || "gpt-4o-mini",
116
+ messages: [
117
+ { role: "system", content: systemPrompt },
118
+ { role: "user", content: transcript }
119
+ ],
120
+ temperature: 0,
121
+ // Deterministic results
122
+ response_format: { type: "json_object" }
123
+ // Force JSON mode
124
+ })
125
+ });
126
+ if (!response.ok) {
127
+ throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);
128
+ }
129
+ const data = await response.json();
130
+ try {
131
+ const parsed = JSON.parse(data.choices[0].message.content);
132
+ return { commandId: parsed.commandId };
133
+ } catch (e) {
134
+ console.error("Failed to parse LLM response", e);
135
+ return { commandId: null };
136
+ }
137
+ };
138
+ };
139
+
140
+ export { VoiceControlProvider, createOpenAIAdapter, useVoiceCommand, useVoiceContext };
141
+ //# sourceMappingURL=index.mjs.map
142
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/VoiceContext.tsx","../src/hooks/useVoiceCommand.ts","../src/core/prompt.ts","../src/adapters/openai.ts"],"names":["useRef"],"mappings":";;;;AASA,IAAM,YAAA,GAAe,cAAwC,IAAI,CAAA;AAE1D,IAAM,uBAAqD,CAAC;AAAA,EACjE,QAAA;AAAA,EACA;AACF,CAAA,KAAM;AAEJ,EAAA,MAAM,WAAA,GAAc,MAAA,iBAAkC,IAAI,GAAA,EAAK,CAAA;AAG/D,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAI,QAAA,CAA4B;AAAA,IACpD,WAAA,EAAa,KAAA;AAAA,IACb,YAAA,EAAc,KAAA;AAAA,IACd,cAAA,EAAgB,IAAA;AAAA,IAChB,gBAAgB;AAAC,GAClB,CAAA;AAGD,EAAA,MAAM,QAAA,GAAW,WAAA,CAAY,CAAC,GAAA,KAAsB;AAClD,IAAA,WAAA,CAAY,OAAA,CAA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ommand, VoiceControlState, VoiceProviderProps } from '../types';\n\ninterface VoiceContextValue extends VoiceControlState {\n register: (cmd: VoiceCommand) => void;\n unregister: (id: string) => void;\n processTranscript: (text: string) => Promise<void>;\n}\n\nconst VoiceContext = createContext<VoiceContextValue | null>(null);\n\nexport const VoiceControlProvider: React.FC<VoiceProviderProps> = ({ \n children, \n adapter \n}) => {\n // THE REGISTRY: A Map ensures O(1) lookups and prevents duplicate IDs\n const commandsRef = useRef<Map<string, VoiceCommand>>(new Map());\n \n // UI STATE\n const [state, setState] = useState<VoiceControlState>({\n isListening: false,\n isProcessing: false,\n lastTranscript: null,\n activeCommands: [],\n });\n\n // 1. REGISTRATION LOGIC\n const register = useCallback((cmd: VoiceCommand) => {\n commandsRef.current.set(cmd.id, cmd);\n // Update generic state for debugging UI\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\n }, []);\n\n const unregister = useCallback((id: string) => {\n commandsRef.current.delete(id);\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\n }, []);\n\n // 2. THE ROUTER LOGIC\n const processTranscript = useCallback(async (transcript: string) => {\n const cleanText = transcript.trim().toLowerCase();\n setState(prev => ({ ...prev, isProcessing: true, lastTranscript: cleanText }));\n\n const allCommands = Array.from(commandsRef.current.values());\n\n // PHASE 1: EXACT MATCH (0ms Latency)\n const exactMatch = allCommands.find(c => c.phrase?.toLowerCase() === cleanText);\n \n if (exactMatch) {\n console.log(`⚡ Instant Match: \"${cleanText}\" -> ${exactMatch.id}`);\n exactMatch.action();\n setState(prev => ({ ...prev, isProcessing: false }));\n return;\n }\n\n // PHASE 2: FUZZY MATCH (AI Adapter)\n try {\n console.log(`🤖 AI Routing: \"${cleanText}\"...`);\n \n // We strip the 'action' function before sending to the AI\n const commandListForAI = allCommands.map(({ id, description, phrase }) => ({ \n id, \n description, \n phrase \n }));\n\n const result = await adapter(cleanText, commandListForAI);\n\n if (result.commandId) {\n const cmd = commandsRef.current.get(result.commandId);\n if (cmd) {\n console.log(`✅ Matched: ${cmd.id}`);\n cmd.action();\n } else {\n console.warn(`⚠️ Adapter returned unknown ID: ${result.commandId}`);\n }\n }\n } catch (error) {\n console.error(\"Adapter Error:\", error);\n } finally {\n setState(prev => ({ ...prev, isProcessing: false }));\n }\n }, [adapter]);\n\n return (\n <VoiceContext.Provider value={{ ...state, register, unregister, processTranscript }}>\n {children}\n </VoiceContext.Provider>\n );\n};\n\nexport const useVoiceContext = () => {\n const ctx = useContext(VoiceContext);\n if (!ctx) throw new Error(\"useVoiceContext must be used within a VoiceControlProvider\");\n return ctx;\n};","import { useEffect, useRef } from 'react';\nimport { useVoiceContext } from '../components/VoiceContext';\nimport { VoiceCommand } from '../types';\n\n/**\n * The Developer Hook\n * Wraps the lifecycle logic so the developer doesn't have to.\n * * Usage:\n * useVoiceCommand({\n * id: 'nav_home',\n * description: 'Go to home',\n * action: () => navigate('/')\n * });\n */\nexport const useVoiceCommand = (command: VoiceCommand) => {\n const { register, unregister } = useVoiceContext();\n\n // Use a ref to keep the ID stable across renders\n const idRef = useRef(command.id);\n\n useEffect(() => {\n // 1. Mount: Register the tool\n register(command);\n\n // 2. Unmount: Remove the tool\n return () => {\n unregister(idRef.current);\n };\n }, [register, unregister, command]); // Re-register if command definition changes\n};","import { VoiceCommand } from '../types';\n\n/**\n * Generates the System Prompt for the LLM.\n * This ensures consistent behavior across different AI providers.\n */\nexport const createSystemPrompt = (commands: Omit<VoiceCommand, 'action'>[]) => {\n // Format the list of commands for the AI to read\n const commandList = commands.map(cmd =>\n `- ID: \"${cmd.id}\" | Description: \"${cmd.description}\"`\n ).join('\\n');\n\n return `\nYou are a precise Voice Command Router.\nYour goal is to map the user's spoken input to the correct Command ID from the list below.\n\nRULES:\n1. Analyze the user's input and find the intent.\n2. Match it to the command with the most relevant \"Description\".\n3. Use fuzzy matching (e.g., \"Dark mode\" matches \"Toggle Theme\").\n4. If NO command matches the intent, return null.\n5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.\n\nAVAILABLE COMMANDS:\n${commandList}\n\nRESPONSE FORMAT:\n{ \"commandId\": \"string_id_or_null\" }\n`;\n};\n\n/**\n * Standardizes how the user's voice transcript is presented to the AI.\n */\nexport const createUserPrompt = (transcript: string) => {\n return `User Input: \"${transcript}\"`;\n};","import { LLMAdapter } from '../types';\nimport { createSystemPrompt } from '../core/prompt';\n\ninterface OpenAIConfig {\n apiKey: string;\n /** @default \"gpt-4o-mini\" */\n model?: string;\n}\n\n/**\n * A Factory that creates an Adapter for OpenAI.\n * Users call this: createOpenAIAdapter({ apiKey: '...' })\n */\nexport const createOpenAIAdapter = (config: OpenAIConfig): LLMAdapter => {\n return async (transcript, commands) => {\n\n // 1. Generate the optimized system instructions\n const systemPrompt = createSystemPrompt(commands);\n\n // 2. Call the API\n const response = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`\n },\n body: JSON.stringify({\n model: config.model || \"gpt-4o-mini\",\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: transcript }\n ],\n temperature: 0, // Deterministic results\n response_format: { type: \"json_object\" } // Force JSON mode\n })\n });\n\n if (!response.ok) {\n throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // 3. Parse the result\n try {\n const parsed = JSON.parse(data.choices[0].message.content);\n return { commandId: parsed.commandId };\n } catch (e) {\n console.error(\"Failed to parse LLM response\", e);\n return { commandId: null };\n }\n };\n};"]}
package/package.json CHANGED
@@ -1,11 +1,33 @@
1
1
  {
2
2
  "name": "react-voice-action-router",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "A headless voice action router for React",
5
- "main": "index.js",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "require": "./dist/index.js",
12
+ "import": "./dist/index.mjs"
13
+ },
14
+ "./adapters": {
15
+ "types": "./dist/adapters/index.d.ts",
16
+ "require": "./dist/adapters/index.js",
17
+ "import": "./dist/adapters/index.mjs"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
6
25
  "license": "MIT",
7
26
  "scripts": {
8
- "test": "echo \"Error: no test specified\" && exit 1"
27
+ "build": "tsup",
28
+ "dev": "tsup --watch",
29
+ "typecheck": "tsc --noEmit",
30
+ "prepublishOnly": "npm run build"
9
31
  },
10
32
  "repository": {
11
33
  "type": "git",
@@ -17,5 +39,11 @@
17
39
  "bugs": {
18
40
  "url": "https://github.com/Nouman64-cat/react-voice-action-router/issues"
19
41
  },
20
- "homepage": "https://github.com/Nouman64-cat/react-voice-action-router#readme"
42
+ "homepage": "https://github.com/Nouman64-cat/react-voice-action-router#readme",
43
+ "devDependencies": {
44
+ "@types/react": "^19.2.7",
45
+ "@types/react-dom": "^19.2.3",
46
+ "tsup": "^8.5.1",
47
+ "typescript": "^5.9.3"
48
+ }
21
49
  }
package/index.js DELETED
@@ -1,3 +0,0 @@
1
- // index.js
2
- console.log("react-voice-action-router: Coming soon!");
3
- module.exports = {};