native-modifiers.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { createRequire } from "node:module";
  2. import * as path from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. const cjsRequire = createRequire(import.meta.url);
  5. export type ModifierKey = "shift" | "command" | "control" | "option";
  6. type NativeModifiersHelper = {
  7. isModifierPressed: (name: ModifierKey) => boolean;
  8. };
  9. let nativeModifiersHelper: NativeModifiersHelper | null | undefined;
  10. function isNativeModifiersHelper(value: unknown): value is NativeModifiersHelper {
  11. if (typeof value !== "object" || value === null) return false;
  12. const candidate = (value as { isModifierPressed?: unknown }).isModifierPressed;
  13. return typeof candidate === "function";
  14. }
  15. function loadNativeModifiersHelper(): NativeModifiersHelper | undefined {
  16. if (nativeModifiersHelper !== undefined) return nativeModifiersHelper ?? undefined;
  17. nativeModifiersHelper = null;
  18. if (process.platform !== "darwin") return undefined;
  19. const arch = process.arch;
  20. if (arch !== "x64" && arch !== "arm64") return undefined;
  21. const moduleDir = path.dirname(fileURLToPath(import.meta.url));
  22. const nativePath = path.join("native", "darwin", "prebuilds", `darwin-${arch}`, "darwin-modifiers.node");
  23. const candidates = [
  24. path.join(moduleDir, "..", nativePath),
  25. path.join(moduleDir, nativePath),
  26. path.join(path.dirname(process.execPath), nativePath),
  27. ];
  28. for (const modulePath of candidates) {
  29. try {
  30. const helper = cjsRequire(modulePath) as unknown;
  31. if (isNativeModifiersHelper(helper)) {
  32. nativeModifiersHelper = helper;
  33. return helper;
  34. }
  35. } catch {
  36. // Try the next possible packaging location.
  37. }
  38. }
  39. return undefined;
  40. }
  41. export function isNativeModifierPressed(key: ModifierKey): boolean {
  42. const helper = loadNativeModifiersHelper();
  43. if (!helper) return false;
  44. try {
  45. return helper.isModifierPressed(key) === true;
  46. } catch {
  47. return false;
  48. }
  49. }