@senad-d/micme 0.3.3 → 0.3.5

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": "@senad-d/micme",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "type": "module",
5
5
  "description": "Local voice dictation for Pi coding prompts. Press Alt+M, speak, review, send.",
6
6
  "license": "MIT",
@@ -59,13 +59,15 @@
59
59
  "check": "node --check scripts/doctor.mjs && node --check scripts/check-format.mjs && node --check scripts/check-package-contents.mjs && node --check scripts/publish-npm.mjs",
60
60
  "test": "node --test test/*.test.mjs",
61
61
  "typecheck": "tsc --noEmit",
62
- "lint": "npm run typecheck && npm run check",
62
+ "lint": "npm run lint:eslint && npm run typecheck && npm run check",
63
63
  "format:check": "node scripts/check-format.mjs",
64
64
  "pack:dry-run": "npm pack --dry-run --json",
65
65
  "check:pack": "node scripts/check-package-contents.mjs",
66
66
  "validate": "npm run lint && npm run format:check && npm run test && npm run check:pack",
67
67
  "publish:npm": "node scripts/publish-npm.mjs",
68
- "prepublishOnly": "npm run validate"
68
+ "prepublishOnly": "npm run validate",
69
+ "test:coverage": "node --test --experimental-test-coverage --test-coverage-include=src/**/*.ts --test-reporter=spec --test-reporter=lcov --test-reporter-destination=stdout --test-reporter-destination=lcov.info test/*.test.mjs",
70
+ "lint:eslint": "eslint eslint.config.mjs \"scripts/**/*.mjs\" \"test/**/*.mjs\" \"src/**/*.ts\""
69
71
  },
70
72
  "pi": {
71
73
  "extensions": [
@@ -80,7 +82,11 @@
80
82
  "devDependencies": {
81
83
  "@earendil-works/pi-coding-agent": "file:./dev-shims/pi-coding-agent",
82
84
  "@earendil-works/pi-tui": "*",
83
- "@types/node": "^25.9.3",
84
- "typescript": "^6.0.3"
85
+ "@eslint/js": "^10.0.1",
86
+ "@types/node": "^26.0.0",
87
+ "eslint": "^10.6.0",
88
+ "globals": "^17.7.0",
89
+ "typescript": "^6.0.3",
90
+ "typescript-eslint": "^8.62.1"
85
91
  }
86
92
  }
@@ -7,6 +7,7 @@ const roots = ["src", "test", "scripts"];
7
7
  const rootFiles = [
8
8
  ".github/workflows/ci.yml",
9
9
  ".gitignore",
10
+ "eslint.config.mjs",
10
11
  "CHANGELOG.md",
11
12
  "CONTRIBUTING.md",
12
13
  "README.md",
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
3
  import { execFileSync, spawnSync } from "node:child_process";
4
4
  import { createInterface } from "node:readline/promises";
5
5
  import { stdin as input, stdout as output } from "node:process";
@@ -9,11 +9,66 @@ const rootUrl = new URL("../", import.meta.url);
9
9
  const root = fileURLToPath(rootUrl);
10
10
  const packageJsonUrl = new URL("package.json", rootUrl);
11
11
  const pkg = JSON.parse(readFileSync(packageJsonUrl, "utf8"));
12
- const semverPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
12
+
13
+ const SAFE_PATH = "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/homebrew/bin";
14
+ const SAFE_ENV = { ...process.env, PATH: SAFE_PATH };
15
+ const COMMAND_PATHS = {
16
+ git: ["/usr/bin/git", "/usr/local/bin/git", "/opt/homebrew/bin/git"],
17
+ npm: ["/usr/bin/npm", "/usr/local/bin/npm", "/opt/homebrew/bin/npm"],
18
+ };
19
+ const PACKAGE_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/;
20
+ const SEMVER_IDENTIFIER_RE = "(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)";
21
+ const SEMVER_RE = new RegExp(
22
+ `^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-(${SEMVER_IDENTIFIER_RE}(?:\\.${SEMVER_IDENTIFIER_RE})*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$`,
23
+ );
24
+ const GIT_REF_FORBIDDEN_RE = /[\x00-\x20\x7f~^:?*[\\]/;
25
+ const CONTROL_OR_WHITESPACE_RE = /[\x00-\x20\x7f]/;
26
+
27
+ function fail(message) {
28
+ console.error(`\n${message}`);
29
+ process.exit(1);
30
+ }
31
+
32
+ function firstExistingPath(paths) {
33
+ return paths.find((path) => existsSync(path));
34
+ }
35
+
36
+ function commandPath(command) {
37
+ const candidates = COMMAND_PATHS[command];
38
+ if (!candidates) fail(`Unsupported command: ${command}`);
39
+
40
+ const resolved = firstExistingPath(candidates);
41
+ if (!resolved) fail(`Required command ${command} was not found in trusted locations.`);
42
+ return resolved;
43
+ }
44
+
45
+ function commandDisplayName(command) {
46
+ if (!COMMAND_PATHS[command]) fail(`Unsupported command: ${command}`);
47
+ return command;
48
+ }
49
+
50
+ function assertSafeCommandArgs(args) {
51
+ for (const arg of args) {
52
+ if (typeof arg !== "string" || arg.includes("\0")) {
53
+ fail("Refusing to execute a command with an invalid argument.");
54
+ }
55
+ }
56
+ }
57
+
58
+ function spawnKnownCommand(command, args, options = {}) {
59
+ assertSafeCommandArgs(args);
60
+ return spawnSync(commandPath(command), args, {
61
+ cwd: root,
62
+ env: SAFE_ENV,
63
+ ...options,
64
+ });
65
+ }
13
66
 
14
67
  function capture(command, args, options = {}) {
15
- return execFileSync(command, args, {
68
+ assertSafeCommandArgs(args);
69
+ return execFileSync(commandPath(command), args, {
16
70
  cwd: root,
71
+ env: SAFE_ENV,
17
72
  encoding: "utf8",
18
73
  stdio: ["ignore", "pipe", "pipe"],
19
74
  ...options,
@@ -21,30 +76,68 @@ function capture(command, args, options = {}) {
21
76
  }
22
77
 
23
78
  function run(command, args) {
24
- console.log(`\n$ ${command} ${args.join(" ")}`);
25
- const result = spawnSync(command, args, {
26
- cwd: root,
27
- stdio: "inherit",
28
- });
79
+ console.log(`\n$ ${commandDisplayName(command)} ${args.join(" ")}`);
80
+ const result = spawnKnownCommand(command, args, { stdio: "inherit" });
29
81
 
30
82
  if (result.status !== 0) {
31
83
  process.exit(result.status ?? 1);
32
84
  }
33
85
  }
34
86
 
35
- function fail(message) {
36
- console.error(`\n${message}`);
37
- process.exit(1);
38
- }
39
-
40
87
  function commandSucceeds(command, args) {
41
- const result = spawnSync(command, args, {
42
- cwd: root,
43
- stdio: "ignore",
44
- });
88
+ const result = spawnKnownCommand(command, args, { stdio: "ignore" });
45
89
  return result.status === 0;
46
90
  }
47
91
 
92
+ function assertNonEmptySafeValue(label, value) {
93
+ if (typeof value !== "string" || value.length === 0) fail(`${label} must not be empty.`);
94
+ if (value.startsWith("-")) fail(`${label} must not start with a dash.`);
95
+ if (CONTROL_OR_WHITESPACE_RE.test(value)) fail(`${label} must not contain whitespace or control characters.`);
96
+ }
97
+
98
+ function assertPackageName(value) {
99
+ assertNonEmptySafeValue("Package name", value);
100
+ if (!PACKAGE_NAME_RE.test(value)) fail(`Package name ${value} is not safe for publishing.`);
101
+ }
102
+
103
+ function assertVersion(value) {
104
+ assertNonEmptySafeValue("Version", value);
105
+ if (!SEMVER_RE.test(value)) {
106
+ fail("Enter a valid semver version, for example 0.1.1 or 1.0.0-beta.1.");
107
+ }
108
+ }
109
+
110
+ function assertSafeGitRefSegment(label, value) {
111
+ assertNonEmptySafeValue(label, value);
112
+ if (GIT_REF_FORBIDDEN_RE.test(value)) fail(`${label} contains characters that are not safe in git refs.`);
113
+ if (value.includes("..") || value.includes("@{") || value.includes("//")) fail(`${label} is not a safe git ref.`);
114
+ if (value.endsWith(".") || value.endsWith("/") || value.endsWith(".lock")) fail(`${label} is not a safe git ref.`);
115
+ if (value.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) {
116
+ fail(`${label} is not a safe git ref.`);
117
+ }
118
+ }
119
+
120
+ function gitTagForVersion(version) {
121
+ assertVersion(version);
122
+ const tag = `v${version}`;
123
+ assertSafeGitRefSegment("Git tag", tag);
124
+ return tag;
125
+ }
126
+
127
+ function npmPackageSpec(packageName, version) {
128
+ assertPackageName(packageName);
129
+ assertVersion(version);
130
+ const spec = `${packageName}@${version}`;
131
+ assertNonEmptySafeValue("npm package spec", spec);
132
+ return spec;
133
+ }
134
+
135
+ function validateCurrentBranch(branch) {
136
+ assertSafeGitRefSegment("Current branch", branch);
137
+ if (branch === "HEAD" || branch.startsWith("HEAD:")) fail("Git is in detached HEAD.");
138
+ return branch;
139
+ }
140
+
48
141
  function ensureCleanGitTree() {
49
142
  const status = capture("git", ["status", "--porcelain"]);
50
143
  if (status) {
@@ -53,8 +146,7 @@ function ensureCleanGitTree() {
53
146
  }
54
147
 
55
148
  function ensureNpmLogin() {
56
- const result = spawnSync("npm", ["whoami"], {
57
- cwd: root,
149
+ const result = spawnKnownCommand("npm", ["whoami"], {
58
150
  encoding: "utf8",
59
151
  stdio: ["ignore", "pipe", "pipe"],
60
152
  });
@@ -63,86 +155,99 @@ function ensureNpmLogin() {
63
155
  fail("npm login is required before publishing. Run `npm login`, then retry.");
64
156
  }
65
157
 
66
- console.log(`npm user: ${result.stdout.trim()}`);
158
+ const npmUser = String(result.stdout).trim();
159
+ assertNonEmptySafeValue("npm username", npmUser);
160
+ console.log(`npm user: ${npmUser}`);
67
161
  }
68
162
 
69
- async function main() {
70
- console.log(`Publishing ${pkg.name}`);
71
- console.log(`Current version: ${pkg.version}`);
72
-
73
- ensureCleanGitTree();
74
- ensureNpmLogin();
75
-
76
- const rl = createInterface({ input, output });
77
- const version = (await rl.question("Version to publish (for example 0.1.1): ")).trim();
78
-
79
- if (!semverPattern.test(version)) {
80
- rl.close();
81
- fail("Enter a valid semver version, for example 0.1.1 or 1.0.0-beta.1.");
82
- }
83
-
84
- if (version === pkg.version) {
85
- rl.close();
86
- fail(`package.json is already at version ${version}. Choose a new version.`);
87
- }
163
+ function packageIsScoped(packageName) {
164
+ assertPackageName(packageName);
165
+ return packageName.startsWith("@");
166
+ }
88
167
 
89
- const gitTag = `v${version}`;
90
- if (commandSucceeds("git", ["rev-parse", "--verify", `refs/tags/${gitTag}`])) {
91
- rl.close();
92
- fail(`Git tag ${gitTag} already exists.`);
93
- }
168
+ function publishArgsForPackage(packageName) {
169
+ const publishArgs = ["publish"];
170
+ if (packageIsScoped(packageName)) publishArgs.push("--access", "public");
171
+ return publishArgs;
172
+ }
94
173
 
95
- const publishedVersion = spawnSync("npm", ["view", `${pkg.name}@${version}`, "version"], {
96
- cwd: root,
174
+ function packageVersionExists(packageName, version) {
175
+ const spec = npmPackageSpec(packageName, version);
176
+ const publishedVersion = spawnKnownCommand("npm", ["view", spec, "version"], {
97
177
  encoding: "utf8",
98
178
  stdio: ["ignore", "pipe", "ignore"],
99
179
  });
180
+ return publishedVersion.status === 0 && String(publishedVersion.stdout).trim().length > 0;
181
+ }
100
182
 
101
- if (publishedVersion.status === 0 && publishedVersion.stdout.trim()) {
183
+ async function askQuestion(question) {
184
+ const rl = createInterface({ input, output });
185
+ try {
186
+ return (await rl.question(question)).trim();
187
+ } finally {
102
188
  rl.close();
103
- fail(`${pkg.name}@${version} already exists on npm.`);
104
189
  }
190
+ }
105
191
 
106
- const publishArgs = ["publish"];
107
- if (pkg.name.startsWith("@")) {
108
- publishArgs.push("--access", "public");
109
- }
192
+ async function readVersionFromUser() {
193
+ const version = await askQuestion("Version to publish (for example 0.1.1): ");
194
+ assertVersion(version);
195
+ return version;
196
+ }
110
197
 
198
+ async function confirmPublishPlan(version, gitTag, publishArgs) {
111
199
  console.log("\nThis will:");
112
- console.log(`- run npm validation`);
200
+ console.log("- run npm validation");
113
201
  console.log(`- run npm version ${version} to update package.json/package-lock.json`);
114
202
  console.log(`- create a release commit and git tag ${gitTag}`);
115
203
  console.log(`- run npm ${publishArgs.join(" ")}`);
116
204
 
117
- const confirm = (await rl.question("Continue? [y/N] ")).trim().toLowerCase();
118
- if (confirm !== "y" && confirm !== "yes") {
119
- rl.close();
120
- fail("Publish cancelled.");
121
- }
205
+ const confirm = (await askQuestion("Continue? [y/N] ")).toLowerCase();
206
+ if (confirm !== "y" && confirm !== "yes") fail("Publish cancelled.");
207
+ }
122
208
 
123
- rl.close();
209
+ async function pushReleaseRefs(gitTag) {
210
+ const push = (await askQuestion(`Push current branch and ${gitTag} to origin? [y/N] `)).toLowerCase();
211
+ if (push !== "y" && push !== "yes") return;
124
212
 
125
- run("npm", ["run", "validate"]);
126
- run("npm", ["version", version, "-m", "chore(release): v%s"]);
127
- run("npm", publishArgs);
213
+ const branch = validateCurrentBranch(capture("git", ["branch", "--show-current"]));
214
+ run("git", ["push", "origin", `refs/heads/${branch}:refs/heads/${branch}`]);
215
+ run("git", ["push", "origin", `refs/tags/${gitTag}:refs/tags/${gitTag}`]);
216
+ }
128
217
 
129
- const pushRl = createInterface({ input, output });
130
- const push = (await pushRl.question(`Push current branch and ${gitTag} to origin? [y/N] `)).trim().toLowerCase();
131
- pushRl.close();
218
+ async function main() {
219
+ assertPackageName(pkg.name);
220
+ assertVersion(pkg.version);
132
221
 
133
- if (push === "y" || push === "yes") {
134
- const branch = capture("git", ["branch", "--show-current"]);
135
- if (!branch) {
136
- fail(`Release was published, but git is in detached HEAD. Push ${gitTag} manually.`);
137
- }
222
+ console.log(`Publishing ${pkg.name}`);
223
+ console.log(`Current version: ${pkg.version}`);
138
224
 
139
- run("git", ["push", "origin", branch]);
140
- run("git", ["push", "origin", gitTag]);
225
+ ensureCleanGitTree();
226
+ ensureNpmLogin();
227
+
228
+ const version = await readVersionFromUser();
229
+ if (version === pkg.version) fail(`package.json is already at version ${version}. Choose a new version.`);
230
+
231
+ const gitTag = gitTagForVersion(version);
232
+ if (commandSucceeds("git", ["rev-parse", "--verify", "--quiet", `refs/tags/${gitTag}`])) {
233
+ fail(`Git tag ${gitTag} already exists.`);
141
234
  }
142
235
 
236
+ if (packageVersionExists(pkg.name, version)) fail(`${pkg.name}@${version} already exists on npm.`);
237
+
238
+ const publishArgs = publishArgsForPackage(pkg.name);
239
+ await confirmPublishPlan(version, gitTag, publishArgs);
240
+
241
+ run("npm", ["run", "validate"]);
242
+ run("npm", ["version", version, "-m", "chore(release): v%s"]);
243
+ run("npm", publishArgs);
244
+ await pushReleaseRefs(gitTag);
245
+
143
246
  console.log(`\nPublished ${pkg.name}@${version}.`);
144
247
  }
145
248
 
146
- main().catch((error) => {
249
+ try {
250
+ await main();
251
+ } catch (error) {
147
252
  fail(error instanceof Error ? error.message : String(error));
148
- });
253
+ }
package/src/audio.ts CHANGED
@@ -60,6 +60,11 @@ const DEVICE_PANEL_DEFAULT_WIDTH = 92;
60
60
  const DEVICE_PANEL_MAX_WIDTH = 100;
61
61
  const DEVICE_PANEL_MIN_WIDTH = 36;
62
62
  const RECORD_TIMING_SYNC_FILTER = "aresample=async=1:first_pts=0";
63
+ const AVFOUNDATION_DEVICE_PREFIX_PATTERN = /^\[(\d+)]\s+/;
64
+ const DIRECT_SHOW_FULL_DEVICE_NAME_PATTERN = /^"(.+)"$/;
65
+ const DIRECT_SHOW_DEVICE_NAME_PATTERN = /"([^"]+)"/;
66
+ const FFMPEG_WARNING_WORDS = new Set(["warning", "error", "failed", "cannot", "unable"]);
67
+ const PULSE_SOURCE_LINE_PATTERN = /^([^\s[]+)(?:\s+\[(.+)\])?$/;
63
68
 
64
69
  let deviceMessageRendererRegistered = false;
65
70
 
@@ -225,10 +230,10 @@ export function parseAvfoundationDevices(output: string): ParsedDeviceInventory
225
230
  }
226
231
  if (!section) continue;
227
232
 
228
- const match = line.match(/\[(\d+)\]\s+(.+)$/);
233
+ const match = AVFOUNDATION_DEVICE_PREFIX_PATTERN.exec(line);
229
234
  if (!match) continue;
230
235
  const id = sanitizeDeviceField(match[1] ?? "");
231
- const name = sanitizeDeviceField(match[2] ?? "");
236
+ const name = sanitizeDeviceField(line.slice(match[0].length));
232
237
  if (!name) continue;
233
238
  inventory[section].push({ id, name });
234
239
  }
@@ -250,7 +255,7 @@ function parsePulseAudioDevices(output: string): ParsedDeviceInventory {
250
255
  if (!inSources || !line || /^(Cannot|Error|Failed|Unknown)\b/i.test(line)) continue;
251
256
 
252
257
  const sourceLine = line.replace(/^\*\s*/, "");
253
- const match = sourceLine.match(/^([^\s\[]+)(?:\s+\[(.+)\])?$/);
258
+ const match = PULSE_SOURCE_LINE_PATTERN.exec(sourceLine);
254
259
  if (!match) continue;
255
260
  const id = sanitizeDeviceField(match[1] ?? "");
256
261
  if (!id || id.includes(":")) continue;
@@ -262,7 +267,7 @@ function parsePulseAudioDevices(output: string): ParsedDeviceInventory {
262
267
  return inventory;
263
268
  }
264
269
 
265
- function parseDirectShowDevices(output: string): ParsedDeviceInventory {
270
+ export function parseDirectShowDevices(output: string): ParsedDeviceInventory {
266
271
  const inventory: ParsedDeviceInventory = { audio: [], video: [], sawDeviceSection: false };
267
272
  let section: DeviceKind | undefined;
268
273
 
@@ -280,7 +285,7 @@ function parseDirectShowDevices(output: string): ParsedDeviceInventory {
280
285
  }
281
286
  if (!section || /Alternative name/i.test(line)) continue;
282
287
 
283
- const match = line.match(/^"(.+)"$/) ?? line.match(/"([^"]+)"/);
288
+ const match = DIRECT_SHOW_FULL_DEVICE_NAME_PATTERN.exec(line) ?? DIRECT_SHOW_DEVICE_NAME_PATTERN.exec(line);
284
289
  const name = sanitizeDeviceField(match?.[1] ?? "");
285
290
  if (!name) continue;
286
291
  inventory[section].push({ name });
@@ -315,7 +320,10 @@ function hasAvfoundationIoWarning(output: string) {
315
320
  }
316
321
 
317
322
  function hasFfmpegWarningAfterScan(output: string) {
318
- return /\b(?:warning|error|failed|cannot|unable)\b/i.test(output);
323
+ return output
324
+ .toLowerCase()
325
+ .split(/\W+/)
326
+ .some((word) => FFMPEG_WARNING_WORDS.has(word));
319
327
  }
320
328
 
321
329
  function getNoParseableDeviceMessage(backend: Exclude<DeviceBackend, "unsupported">) {
@@ -353,7 +361,9 @@ class DevicePanelMessageComponent implements Component {
353
361
  return renderDevicePanel(this.options, Math.min(width, DEVICE_PANEL_MAX_WIDTH)).split("\n");
354
362
  }
355
363
 
356
- invalidate(): void {}
364
+ invalidate(): void {
365
+ // Device panel messages render immutable options directly, so there is no cached state to invalidate.
366
+ }
357
367
  }
358
368
 
359
369
  function readDevicePanelOptions(value: unknown): DevicePanelOptions {
@@ -445,7 +455,27 @@ function shouldUsePlainDevicePanel() {
445
455
  }
446
456
 
447
457
  function formatSourceLabel(sourceLabel: string, style: DevicePanelStyle) {
448
- return style.plain ? sourceLabel.replace(/\s*·\s*/g, " - ") : sourceLabel;
458
+ return style.plain ? replaceMiddleDotSeparators(sourceLabel) : sourceLabel;
459
+ }
460
+
461
+ function replaceMiddleDotSeparators(text: string) {
462
+ let formatted = "";
463
+ let index = 0;
464
+
465
+ while (index < text.length) {
466
+ const middleDotIndex = text.indexOf("·", index);
467
+ if (middleDotIndex === -1) return `${formatted}${text.slice(index)}`;
468
+
469
+ formatted = `${formatted}${text.slice(index, middleDotIndex).trimEnd()} - `;
470
+ index = middleDotIndex + 1;
471
+ while (index < text.length && isLabelWhitespace(text[index] ?? "")) index++;
472
+ }
473
+
474
+ return formatted;
475
+ }
476
+
477
+ function isLabelWhitespace(character: string) {
478
+ return character.trim() === "";
449
479
  }
450
480
 
451
481
  function buildDevicePanelHeader(width: number, sourceLabel: string, style: DevicePanelStyle) {
@@ -456,7 +486,7 @@ function buildDevicePanelHeader(width: number, sourceLabel: string, style: Devic
456
486
  const availableTextWidth = Math.max(1, width - overhead - 1);
457
487
  const sourceBudget = Math.max(4, Math.min(visibleWidth(sourceLabel), Math.floor(availableTextWidth * 0.45)));
458
488
  let source = ellipsize(formatSourceLabel(sourceLabel, style), sourceBudget, style);
459
- let titleText = ellipsize(title, Math.max(4, availableTextWidth - visibleWidth(source)), style);
489
+ const titleText = ellipsize(title, Math.max(4, availableTextWidth - visibleWidth(source)), style);
460
490
  if (visibleWidth(titleText) + visibleWidth(source) > availableTextWidth) {
461
491
  source = ellipsize(source, Math.max(1, availableTextWidth - visibleWidth(titleText)), style);
462
492
  }
@@ -473,7 +503,8 @@ function buildDevicePanelFooter(width: number, style: DevicePanelStyle) {
473
503
  }
474
504
 
475
505
  function buildDeviceRow(kind: DeviceKind, devices: ListedDevice[], style: DevicePanelStyle, width: number) {
476
- const prefix = style.plain ? ` ${kind.padEnd(5)} ${devices.length}` : ` ${kind === "audio" ? style.audioLabel : style.videoLabel} ${devices.length}`;
506
+ const deviceLabel = kind === "audio" ? style.audioLabel : style.videoLabel;
507
+ const prefix = style.plain ? ` ${kind.padEnd(5)} ${devices.length}` : ` ${deviceLabel} ${devices.length}`;
477
508
  if (devices.length === 0) return fitLine(`${prefix}${style.separator}no ${kind} devices found`, width, style);
478
509
 
479
510
  const displayNames = compactDeviceNames(devices);
@@ -657,7 +688,8 @@ export async function validateRecordedAudio(audioPath: string): Promise<AudioDia
657
688
  }
658
689
 
659
690
  export function parseVolumeDb(output: string, label: "mean_volume" | "max_volume") {
660
- const match = output.match(new RegExp(`${label}:\\s*(-?(?:\\d+(?:\\.\\d+)?|inf))\\s*dB`, "i"));
691
+ const pattern = new RegExp(String.raw`${label}:\s*(-?(?:\d+(?:\.\d+)?|inf))\s*dB`, "i");
692
+ const match = pattern.exec(output);
661
693
  if (!match) return undefined;
662
694
  return match[1]?.toLowerCase() === "-inf" ? Number.NEGATIVE_INFINITY : Number(match[1]);
663
695
  }
@@ -685,7 +717,7 @@ export function buildRecorderCommand(audioPath: string, tempDir = dirname(audioP
685
717
  const args = buildFfmpegRecorderArgs("avfoundation", input, audioPath, recordSampleRate, {
686
718
  meter: recordMeter,
687
719
  inputOptions: ["-drop_late_frames", getAvfoundationDropLateFrames() ? "true" : "false"],
688
- audioFilters: recordSync ? timingFilters : avfoundationInputSampleRate ? [`asetrate=${avfoundationInputSampleRate}`] : [],
720
+ audioFilters: getAvfoundationAudioFilters(recordSync, avfoundationInputSampleRate),
689
721
  });
690
722
  return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n" };
691
723
  }
@@ -711,6 +743,12 @@ type FfmpegRecorderOptions = {
711
743
  audioFilters?: string[];
712
744
  };
713
745
 
746
+ function getAvfoundationAudioFilters(recordSync: boolean, avfoundationInputSampleRate: number | undefined) {
747
+ if (recordSync) return [RECORD_TIMING_SYNC_FILTER];
748
+ if (avfoundationInputSampleRate) return [`asetrate=${avfoundationInputSampleRate}`];
749
+ return [];
750
+ }
751
+
714
752
  export function buildFfmpegRecorderArgs(inputFormat: string, input: string, audioPath: string, recordSampleRate: string | undefined, options: FfmpegRecorderOptions = {}) {
715
753
  const inputArgs = [
716
754
  "-hide_banner",
package/src/backends.ts CHANGED
@@ -5,8 +5,10 @@ import { env, expandConfigPath, getTranscribeBackend, getTranslateToEnglishLangu
5
5
  import { getPythonWhisperModelName, isEnglishOnlyWhisperModelName, isTranslationUnsupportedWhisperModelName, resolveWhisperCppModel } from "./models.ts";
6
6
  import { findExecutable, isExecutableFile } from "./processes.ts";
7
7
 
8
+ export type RequestedTranscribeBackend = TranscribeBackend | (string & Record<never, never>);
9
+
8
10
  export type ResolveTranscriptionPlanOptions = {
9
- requestedBackend?: TranscribeBackend | string;
11
+ requestedBackend?: RequestedTranscribeBackend;
10
12
  transcriptionMode?: TranscriptionMode;
11
13
  customCommand?: string | null;
12
14
  whisperCppBinary?: string | null;
@@ -220,7 +222,7 @@ function nonePlan(requestedBackend: TranscribeBackend, reason: string, warnings:
220
222
  };
221
223
  }
222
224
 
223
- function parseRequestedBackend(value: TranscribeBackend | string | undefined, warnings: string[]) {
225
+ function parseRequestedBackend(value: RequestedTranscribeBackend | undefined, warnings: string[]) {
224
226
  const raw = value ?? env("MICME_TRANSCRIBE_BACKEND")?.trim();
225
227
  if (!raw) return getTranscribeBackend();
226
228
  if (isTranscribeBackend(raw)) return raw;
@@ -233,7 +235,7 @@ function getOptionValue<K extends keyof ResolveTranscriptionPlanOptions>(
233
235
  key: K,
234
236
  fallback: () => Extract<ResolveTranscriptionPlanOptions[K], string | null | undefined>,
235
237
  ) {
236
- if (Object.prototype.hasOwnProperty.call(options, key)) {
238
+ if (Object.hasOwn(options, key)) {
237
239
  const value = options[key];
238
240
  return typeof value === "string" && value.trim() ? value.trim() : undefined;
239
241
  }
@@ -253,7 +255,7 @@ function getExecutableOption(
253
255
  warnings.push(error);
254
256
  return undefined;
255
257
  }
256
- if (Object.prototype.hasOwnProperty.call(options, key)) {
258
+ if (Object.hasOwn(options, key)) {
257
259
  const value = options[key];
258
260
  return typeof value === "string" && value.trim() ? value.trim() : undefined;
259
261
  }
package/src/config.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { existsSync, readFileSync } from "node:fs";
2
3
  import { mkdir, rename, rm, writeFile } from "node:fs/promises";
3
4
  import { createRequire } from "node:module";
@@ -6,7 +7,6 @@ import { dirname, join, resolve } from "node:path";
6
7
  import type { MicmeConfigState, TranscribeBackend, TranscriptionMode } from "./types.ts";
7
8
  import {
8
9
  DEFAULT_MACOS_PRINTABLE_SHORTCUT,
9
- DEFAULT_RECORD_SAMPLE_RATE,
10
10
  DEFAULT_SHORTCUT,
11
11
  DEFAULT_STREAM_KEEP_MS,
12
12
  DEFAULT_STREAM_LENGTH_MS,
@@ -94,7 +94,7 @@ export async function writeMicmeConfigValues(values: Record<string, string | und
94
94
  }
95
95
 
96
96
  await mkdir(configDir, { recursive: true });
97
- const tempPath = join(configDir, `.micme.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);
97
+ const tempPath = join(configDir, `.micme.${process.pid}.${Date.now()}.${randomUUID()}.tmp`);
98
98
  try {
99
99
  await writeFile(tempPath, `${JSON.stringify(next, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
100
100
  await rename(tempPath, configPath);
@@ -143,7 +143,7 @@ export function expandConfigPath(value: string) {
143
143
 
144
144
  export function expandEnvReferences(value: string, configValues: Record<string, string>) {
145
145
  const withHome = value.startsWith("~/") && process.env.HOME ? `${process.env.HOME}${value.slice(1)}` : value;
146
- return withHome.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (_match, braced: string | undefined, bare: string | undefined) => {
146
+ return withHome.replace(/\$\{([A-Za-z_]\w*)\}|\$([A-Za-z_]\w*)/g, (_match, braced: string | undefined, bare: string | undefined) => {
147
147
  const key = braced ?? bare ?? "";
148
148
  return process.env[key] ?? configValues[key] ?? "";
149
149
  });
@@ -190,13 +190,32 @@ export function isTranscribeBackend(value: string | undefined): value is Transcr
190
190
  return value === "auto" || value === "whisper.cpp" || value === "python" || value === "custom";
191
191
  }
192
192
 
193
+ const NAMED_TERMINAL_KEYS = new Set([
194
+ "escape",
195
+ "esc",
196
+ "enter",
197
+ "return",
198
+ "tab",
199
+ "space",
200
+ "backspace",
201
+ "delete",
202
+ "insert",
203
+ "clear",
204
+ "home",
205
+ "end",
206
+ "pageup",
207
+ "pagedown",
208
+ "up",
209
+ "down",
210
+ "left",
211
+ "right",
212
+ ]);
213
+ const FUNCTION_TERMINAL_KEY_PATTERN = /^f\d{1,2}$/i;
214
+ const MODIFIED_TERMINAL_KEY_PATTERN = /^(?:(?:ctrl|control|alt|option|meta|cmd|command|shift|super)\+)+.+$/i;
215
+
193
216
  export function getPrintableShortcuts() {
194
217
  const shortcut = env("MICME_SHORTCUT");
195
- if (shortcut !== undefined) {
196
- if (shortcut && !isTerminalShortcut(shortcut)) return splitShortcutValues(shortcut);
197
- const legacyConfigured = env("MICME_PRINTABLE_SHORTCUTS");
198
- return legacyConfigured !== undefined ? splitShortcutValues(legacyConfigured) : [];
199
- }
218
+ if (shortcut !== undefined) return getPrintableShortcutsForUnifiedShortcut(shortcut);
200
219
 
201
220
  const legacyConfigured = env("MICME_PRINTABLE_SHORTCUTS");
202
221
  if (legacyConfigured !== undefined) return splitShortcutValues(legacyConfigured);
@@ -209,7 +228,29 @@ export function matchesPrintableMicmeShortcut(data: string) {
209
228
 
210
229
  export function isTerminalShortcut(value: string) {
211
230
  const normalized = value.trim();
212
- return /^[\x20-\x7E]$/.test(normalized) || /^(?:escape|esc|enter|return|tab|space|backspace|delete|insert|clear|home|end|pageUp|pageDown|up|down|left|right|f\d{1,2}|(?:(?:ctrl|control|alt|option|meta|cmd|command|shift|super)\+)+.+)$/i.test(normalized);
231
+ return isPrintableAsciiCharacter(normalized) || isNamedTerminalKey(normalized) || FUNCTION_TERMINAL_KEY_PATTERN.test(normalized) || MODIFIED_TERMINAL_KEY_PATTERN.test(normalized);
232
+ }
233
+
234
+ function getPrintableShortcutsForUnifiedShortcut(shortcut: string) {
235
+ if (shortcut && isTerminalShortcut(shortcut)) return getConfiguredLegacyPrintableShortcuts();
236
+ if (shortcut) return splitShortcutValues(shortcut);
237
+ return getConfiguredLegacyPrintableShortcuts();
238
+ }
239
+
240
+ function getConfiguredLegacyPrintableShortcuts() {
241
+ const legacyConfigured = env("MICME_PRINTABLE_SHORTCUTS");
242
+ return legacyConfigured === undefined ? [] : splitShortcutValues(legacyConfigured);
243
+ }
244
+
245
+ function isPrintableAsciiCharacter(value: string) {
246
+ const characters = Array.from(value);
247
+ if (characters.length !== 1) return false;
248
+ const codePoint = characters[0]?.codePointAt(0);
249
+ return codePoint !== undefined && codePoint >= 0x20 && codePoint <= 0x7E;
250
+ }
251
+
252
+ function isNamedTerminalKey(value: string) {
253
+ return NAMED_TERMINAL_KEYS.has(value.toLowerCase());
213
254
  }
214
255
 
215
256
  function firstShortcutValue(value: string | undefined) {
@@ -346,7 +387,7 @@ function readMicmeJsonObjectForWrite(configPath: string): JsonObject {
346
387
  return parsed;
347
388
  } catch (error) {
348
389
  const message = error instanceof Error ? error.message : String(error);
349
- throw new Error(`Cannot save Micme config: ${configPath} is invalid JSON (${message}). Fix or remove it first.`);
390
+ throw new Error(`Cannot save Micme config: ${configPath} is invalid JSON (${message}). Fix or remove it first.`, { cause: error });
350
391
  }
351
392
  }
352
393