hs2-mock 0.3.1 → 0.5.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/README.md CHANGED
@@ -28,57 +28,55 @@ Reading a member the mock lacks throws `hs2-mock: hs.x.y is not mocked`. Tests c
28
28
  | `hs.appinfo` | `pid` |
29
29
  | `hs.application` | `frontmost`, `fromPID`, `launchOrFocus`, `matchingBundleID`, `on`, `off` |
30
30
  | `hs.audiodevice` | `allInputDevices`, `allOutputDevices`, `defaultInputDevice`, `defaultOutputDevice`, `on`, `off` |
31
+ | `hs.bluetooth` | `isScanning`, `on`, `off`, `scan`, `stopScan` |
32
+ | `hs.chooser` | `create` (`setChoices`, `show`, `hide`, `onSelect`, `onHide`) |
31
33
  | `hs.ax` | `applicationElement`, `windowElement` |
32
34
  | `hs.distributednotifications` | `on`, `off` |
35
+ | `hs.eventtap` | `keyStroke`, `leftClick` |
33
36
  | `hs.fs` (in memory) | `exists`, `homeDirectory`, `mkdir`, `read`, `urlFromPath`, `write` |
34
37
  | `hs.hotkey` | `bind`, `create` |
35
- | `hs.menubar` | `create` (`title`, `setIcon`, `setMenu`, `destroy`) |
38
+ | `hs.http` | `openWebSocket` |
39
+ | `hs.menubar` | `create` (`title`, `setIcon`, `setTooltip`, `setClickCallback`, `setMenu`, `destroy`) |
40
+ | `hs.mouse` | `absolutePosition`, `setAbsolutePosition` |
36
41
  | `hs.notify` | `show`, `create` (`send`) |
37
- | `hs.permissions` | `checkAccessibility`, `checkLocation`, `requestLocation`, `requestNotifications` |
38
- | `hs.power` | `on`, `off` |
42
+ | `hs.permissions` | `checkAccessibility`, `checkBluetooth`, `requestBluetooth`, `checkLocation`, `requestLocation`, `requestNotifications` |
43
+ | `hs.power` | `lockScreen`, `on`, `off` |
39
44
  | `hs.screen` | `main` |
40
45
  | `hs.task` | `create`, `runAsync` |
41
46
  | `hs.timer` | `absoluteTime`, `doAfter`, `doEvery`, `secondsSinceEpoch` |
42
47
  | `hs.ui` | `alert`, `dialog`, `webview`, `window` |
43
48
  | `hs.urlevent` | `openURL` |
49
+ | `hs.userdefaults` | `get`, `set`, `clear` |
44
50
  | `hs.wifi` | `currentNetwork`, `on`, `off` |
45
- | `HSImage`, `HSSize` globals | `fromName`, `fromSymbol` |
46
-
47
- ## Controls (`ctl`)
48
-
49
- | Control | Does |
50
- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
51
- | `advance(seconds)` | Moves the clock, firing timers and settling promises between them |
52
- | `flush()` | Settles pending promises |
53
- | `addApp({ bundleID, name, allWindows, focusedWindow, mainWindow })` | Adds a running app and returns it |
54
- | `activate(bundleID)` | Brings an app to the front and emits `didActivate`; `null` for one without a bundle ID |
55
- | `killed`, `launched`, `activations`, `raised` | Apps killed, launched and activated, and windows raised |
56
- | `frontmostRequests` | Times Hammerspoon asked to be frontmost |
57
- | `element({ role, children, attributes })` | An accessibility element |
58
- | `window(element)` | A window whose element it is |
59
- | `url(text)` | A URL attribute value, as `hs.ax` returns it |
60
- | `hotkeys` | Created hotkeys that have not been destroyed |
61
- | `tasks` | Started tasks: `launchPath`, `args`, `environment`, `running`, `terminated`, `inputClosed`, `finish({ stdout, exitCode, reason, error })` |
62
- | `respondToTasks(handler)` | Answers each task as it starts with what `finish()` takes, or `undefined` to leave it running |
63
- | `menubarItems` | Menu bar items: `item`, `icon`, `menu`, `destroyed` |
64
- | `notifications` | `title`, `body`; `click()` for `show()` ones, `options` for `create()` ones |
65
- | `dialogs` | `message`, `informativeText`, `buttons`, `open`, `press(label)` |
66
- | `windows` | `rect`, `title`, `view.html`, `view.post(name, body)`, `shown`, `userClose()` |
67
- | `alerts`, `openedURLs` | What was shown and opened |
68
- | `files`, `dirs`, `home`, `writeFails` | The in-memory file system |
69
- | `power(event)`, `notify(name)` | Emits an `hs.power` event or a distributed notification |
70
- | `ssid`, `wifi(event)` | The current Wi-Fi network, and its events |
71
- | `addAudioDevice({ name, uid, input })` | Adds an audio device (emits `dev+`) and returns it |
72
- | `removeAudioDevice(device)` | Removes it (emits `dev-`) |
73
- | `setDefaultAudioDevice(direction, device)` | Sets the default and emits `dOut` or `dIn` |
74
- | `updateAudioDevice(device, changes)` | Sets `volume` or `muted` and emits the device event |
75
- | `audioListeners()` | Number of audio listeners registered |
76
- | `images` | Add the names `HSImage.fromName` can load |
77
- | `accessibility`, `location`, `notificationPermission` | Whether each permission is granted |
78
- | `locationRequests` | How often location permission was requested |
79
-
80
- ## Types
81
-
82
- Add `node_modules/hs2-mock/types/*.d.ts` to your `tsconfig.json`, with `"types": []`. The version they come
83
- from is in `types/VERSION`; refresh with `mise run vendor <tag>`. `hammerspoon.d.ts` is MIT-licensed,
84
- copyright the Hammerspoon contributors.
51
+ | `HSImage`, `HSSize` globals | `fromAppBundle`, `fromName`, `fromSymbol` |
52
+
53
+ ## Controls
54
+
55
+ `ctl` drives the mock and records what the spoon did: the clock (`ctl.advance()`), apps, windows and the
56
+ accessibility tree, the menu bar, alerts, choosers and dialogs, hotkeys, keystrokes and clicks, tasks,
57
+ websockets, Bluetooth, files, settings and permissions.
58
+
59
+ [`index.d.ts`](index.d.ts) documents every control. Editors show it as you type `ctl.`, with no setup.
60
+
61
+ ## What belongs here, and what stays in a spoon's tests
62
+
63
+ Generic fakes belong here: ones that record calls or hold simple state, with no opinion about a particular
64
+ spoon. They follow what Hammerspoon 2 does, including the awkward parts, and a test fails if the mock has a
65
+ member the real API lacks.
66
+
67
+ A spoon's tests keep their own fake, with a comment saying why, when it is:
68
+
69
+ - **a test assertion** rather than a mock, such as counting how often an accessibility tree is walked;
70
+ - **deliberately unrealistic**, such as a call that throws, to test error handling;
71
+ - **particular to one spoon**, such as the Dock or Teams window trees built on `ctl.element()`.
72
+
73
+ ## Types for spoons
74
+
75
+ To type-check a spoon against Hammerspoon 2, add `node_modules/hs2-mock/types/*.d.ts` to its `tsconfig.json`,
76
+ with `"types": []`. The version those come from is in `types/VERSION`; refresh with `mise run vendor <tag>`.
77
+ `hammerspoon.d.ts` is MIT-licensed, copyright the Hammerspoon contributors.
78
+
79
+ ## Development
80
+
81
+ `mise run test` type-checks the declarations and runs the tests. A new member goes in the table above, and a
82
+ new control in `index.d.ts`; tests fail otherwise.
package/index.d.ts ADDED
@@ -0,0 +1,309 @@
1
+ // Types of the mock and its test controls. The `hs` it mocks is typed by
2
+ // types/hammerspoon.d.ts.
3
+
4
+ // Hammerspoon objects and the mock's stand-ins for them. Left open, so tests can
5
+ // replace anything, and so these types need no other declarations.
6
+ // biome-ignore lint/suspicious/noExplicitAny: see above
7
+ type Mocked = any;
8
+
9
+ export interface AppOptions {
10
+ bundleID: string | null;
11
+ /** Defaults to the bundle ID. */
12
+ name?: string;
13
+ allWindows?: Mocked[];
14
+ focusedWindow?: Mocked;
15
+ mainWindow?: Mocked;
16
+ /** The app's accessibility tree, from `ctl.element()`. */
17
+ axElement?: Mocked;
18
+ }
19
+
20
+ export interface ElementOptions {
21
+ role: string;
22
+ title?: string | null;
23
+ elementDescription?: string | null;
24
+ position?: { x: number; y: number } | null;
25
+ size?: { w: number; h: number } | null;
26
+ children?: Mocked[];
27
+ /** What `attributeValue()` returns, by attribute name. */
28
+ attributes?: Record<string, unknown>;
29
+ }
30
+
31
+ export interface AudioDeviceOptions {
32
+ name: string;
33
+ /** Defaults to the name. */
34
+ uid?: string;
35
+ input?: boolean;
36
+ /** Defaults to the opposite of `input`. */
37
+ output?: boolean;
38
+ volume?: number;
39
+ muted?: boolean;
40
+ isInUse?: boolean;
41
+ }
42
+
43
+ export interface TaskResult {
44
+ /** One chunk, or several, passed to the output callback in turn. */
45
+ stdout?: string | string[];
46
+ exitCode?: number;
47
+ reason?: string;
48
+ error?: string;
49
+ }
50
+
51
+ export interface Task {
52
+ launchPath: string;
53
+ args: string[];
54
+ environment: Record<string, string> | null;
55
+ inputClosed: boolean;
56
+ terminated: boolean;
57
+ readonly running: boolean;
58
+ /** The HSTask, when made with `hs.task.create()`. */
59
+ task?: Mocked;
60
+ /** Ends the task, calling its output and termination callbacks. */
61
+ finish(result?: TaskResult): void;
62
+ }
63
+
64
+ export interface Hotkey {
65
+ mods: string[];
66
+ key: string;
67
+ onPressed: () => void;
68
+ isEnabled(): boolean;
69
+ enable(): boolean;
70
+ disable(): void;
71
+ destroy(): void;
72
+ }
73
+
74
+ export interface MenubarItem {
75
+ /** The HSMenuBarItem, for its `title`. */
76
+ item: Mocked;
77
+ icon: Mocked;
78
+ tooltip: string | null;
79
+ /** What `setMenu()` was given: an array, or a function returning one. */
80
+ menu: Mocked;
81
+ destroyed: boolean;
82
+ /** Calls the click callback; throws if none is set. */
83
+ click(button?: string): void;
84
+ }
85
+
86
+ export interface Notification {
87
+ title: string;
88
+ body: string;
89
+ /** Clicks a notification made with `show()`. */
90
+ click?(): void;
91
+ /** What a notification made with `create()` was given. */
92
+ options?: Mocked;
93
+ }
94
+
95
+ export interface Dialog {
96
+ message: string;
97
+ informativeText: string | null;
98
+ buttons: string[];
99
+ style: string;
100
+ open: boolean;
101
+ /** Presses a button of an open dialog. */
102
+ press(label: string): void;
103
+ }
104
+
105
+ export interface Window {
106
+ rect: Mocked;
107
+ title: string;
108
+ /** The web view's HTML, and `post()` to send what its page would. */
109
+ view: { html: string | null; post(name: string, body: unknown): void } | null;
110
+ shown: boolean;
111
+ shows: number;
112
+ destroyed: boolean;
113
+ /** Closes the window as the user would. */
114
+ userClose(): void;
115
+ }
116
+
117
+ export interface Alert {
118
+ message: string;
119
+ duration: number;
120
+ closed: boolean;
121
+ }
122
+
123
+ export interface Chooser {
124
+ /** The HSChooser. */
125
+ chooser: Mocked;
126
+ choices: Mocked[];
127
+ readonly visible: boolean;
128
+ /** Selects the choice with this text: the chooser hides, then `onSelect`. */
129
+ choose(text: string): void;
130
+ /** Dismisses it as Escape does: `onSelect(null)`. */
131
+ dismiss(): void;
132
+ }
133
+
134
+ export interface Scan {
135
+ seconds: number;
136
+ allowDuplicates: boolean;
137
+ done: boolean;
138
+ }
139
+
140
+ export interface Advertisement {
141
+ identifier: string;
142
+ name?: string | null;
143
+ /** Defaults to the name. */
144
+ localName?: string | null;
145
+ /** 127 means no reading, which keeps the last one. */
146
+ rssi: number;
147
+ }
148
+
149
+ export interface Keystroke {
150
+ mods: string[];
151
+ key: string | number;
152
+ app: Mocked;
153
+ }
154
+
155
+ export interface WebSocket {
156
+ url: string;
157
+ /** Messages sent while open. */
158
+ sent: string[];
159
+ destroyed: boolean;
160
+ readonly readyState: number;
161
+ /** The connection succeeds. */
162
+ open(): void;
163
+ /** The server sends a message. */
164
+ message(text: string): void;
165
+ /** The server closes an open connection. */
166
+ remoteClose(code?: number, reason?: string): void;
167
+ /** The connection fails, as when it is refused. */
168
+ error(text: string): void;
169
+ }
170
+
171
+ export interface Controls {
172
+ /** Moves the clock, firing timers and settling promises between them. */
173
+ advance(seconds: number): Promise<void>;
174
+ /** Settles pending promises. */
175
+ flush(): Promise<void>;
176
+
177
+ /** Adds a running app, without an event, and returns it. */
178
+ addApp(options: AppOptions): Mocked;
179
+ /** Adds an app and emits `didLaunch`. */
180
+ launch(options: AppOptions): Mocked;
181
+ /** Ends a running app and emits `didTerminate`. */
182
+ quit(bundleID: string): void;
183
+ /** Brings an app to the front, adding it if needed, and emits `didActivate`. */
184
+ activate(bundleID: string | null): void;
185
+ /** Each time an app was activated. */
186
+ activations: { bundleID: string | null; allWindows: boolean }[];
187
+ /** Bundle IDs of the apps killed. */
188
+ killed: (string | null)[];
189
+ /** Bundle IDs passed to `hs.application.launchOrFocus()`. */
190
+ launched: string[];
191
+ /** Times Hammerspoon asked to be frontmost. */
192
+ readonly frontmostRequests: number;
193
+
194
+ /** An accessibility element. */
195
+ element(options: ElementOptions): Mocked;
196
+ /** A window whose accessibility element this is. */
197
+ window(
198
+ element: Mocked,
199
+ options?: { id?: number; isStandard?: boolean },
200
+ ): Mocked;
201
+ /** A URL attribute value, as `hs.ax` returns it. */
202
+ url(text: string): Mocked;
203
+ /** Windows raised. */
204
+ raised: Mocked[];
205
+
206
+ /** Adds an audio device, emitting `dev+`, and returns it. */
207
+ addAudioDevice(options: AudioDeviceOptions): Mocked;
208
+ /** Removes a device, emitting `dev-`. */
209
+ removeAudioDevice(device: Mocked): void;
210
+ /** Sets the default device and emits `dOut` or `dIn`. */
211
+ setDefaultAudioDevice(direction: "output" | "input", device: Mocked): void;
212
+ /** Changes a device, emitting its event for `volume` or `muted`. */
213
+ updateAudioDevice(device: Mocked, changes: Record<string, unknown>): void;
214
+ /** Number of audio listeners registered. */
215
+ audioListeners(): number;
216
+
217
+ /** BLE scans started. */
218
+ scans: Scan[];
219
+ /** An advertisement. Returns false when no scan was there to hear it. */
220
+ discover(advertisement: Advertisement): boolean;
221
+ /** Turns Bluetooth on or off; off fails the running scan and later ones. */
222
+ setBluetooth(on: boolean): void;
223
+
224
+ /** Choosers created. */
225
+ choosers: Chooser[];
226
+ /** Dialogs created. */
227
+ dialogs: Dialog[];
228
+ /** Windows created with `hs.ui.window()`. */
229
+ windows: Window[];
230
+ /** Messages of the alerts shown. */
231
+ alerts: string[];
232
+ /** The alerts shown, with their duration and whether they were closed. */
233
+ shownAlerts: Alert[];
234
+ /** Menu bar items created, destroyed ones included. */
235
+ menubarItems: MenubarItem[];
236
+ /** Notifications shown. */
237
+ notifications: Notification[];
238
+ /** Add the names `HSImage.fromName()` can load. */
239
+ images: Set<string>;
240
+ /** Add the apps `HSImage.fromAppBundle()` cannot load. */
241
+ missingIcons: Set<string>;
242
+
243
+ /** Created hotkeys that have not been destroyed. */
244
+ hotkeys: Hotkey[];
245
+ /** Keystrokes `hs.eventtap` sent. */
246
+ keystrokes: Keystroke[];
247
+ /** Clicks `hs.eventtap` made. */
248
+ clicks: { x: number; y: number }[];
249
+ /** Where the mouse is. */
250
+ mouse: { x: number; y: number };
251
+ /** Runs as each keystroke is sent. */
252
+ respondToKeystrokes(handler: (keystroke: Keystroke) => void): void;
253
+ /** Runs as each click is made. */
254
+ respondToClicks(handler: (point: { x: number; y: number }) => void): void;
255
+
256
+ /** Tasks started. Nothing runs until the test ends one. */
257
+ tasks: Task[];
258
+ /** Answers each task as it starts; return `undefined` to leave it running. */
259
+ respondToTasks(handler: (task: Task) => TaskResult | undefined): void;
260
+ /** Websockets opened. */
261
+ websockets: WebSocket[];
262
+ /** URLs passed to `hs.urlevent.openURL()`. */
263
+ openedURLs: string[];
264
+
265
+ /** The in-memory file system: contents by path. */
266
+ files: Map<string, string>;
267
+ /** Directories made. */
268
+ dirs: string[];
269
+ /** What `hs.fs.homeDirectory()` returns. */
270
+ home: string;
271
+ /** Makes `hs.fs.write()` fail. */
272
+ writeFails: boolean;
273
+ /** What `hs.userdefaults` holds. */
274
+ defaults: Map<string, unknown>;
275
+
276
+ /** Emits an `hs.power` event. */
277
+ power(event: string): void;
278
+ /** Times the screen was locked. */
279
+ readonly locks: number;
280
+ /** Emits a distributed notification. */
281
+ notify(name: string, object?: unknown, userInfo?: object): void;
282
+ /** The current Wi-Fi network. */
283
+ ssid: string | null;
284
+ /** Emits an `hs.wifi` event. */
285
+ wifi(event: string): void;
286
+
287
+ /** Whether Accessibility is granted. */
288
+ accessibility: boolean;
289
+ /** Whether Bluetooth access is granted. */
290
+ bluetoothPermission: boolean;
291
+ /** Whether Location is granted. */
292
+ location: boolean;
293
+ /** How often Location permission was requested. */
294
+ locationRequests: number;
295
+ /** Whether notifications are allowed. */
296
+ notificationPermission: boolean;
297
+ }
298
+
299
+ /**
300
+ * A fresh strict mock of the Hammerspoon 2 `hs` global, and the test controls.
301
+ * Also sets the HSImage and HSSize globals.
302
+ */
303
+ export function createHs(): { hs: Mocked; ctl: Controls };
304
+
305
+ /**
306
+ * Loads a spoon the way `hs.spoons.load()` does, installing `hs` as the global.
307
+ * @param dir the spoon's directory
308
+ */
309
+ export function loadSpoon(dir: string, hs: Mocked): Mocked;
package/index.js CHANGED
@@ -1,12 +1,16 @@
1
1
  const { createApplication } = require("./lib/application.js");
2
2
  const { createAudiodevice } = require("./lib/audiodevice.js");
3
3
  const { createAx } = require("./lib/ax.js");
4
+ const { createBluetooth } = require("./lib/bluetooth.js");
5
+ const { createChooser } = require("./lib/chooser.js");
4
6
  const { createDialog } = require("./lib/dialog.js");
5
7
  const {
6
8
  createDistributedNotifications,
7
9
  } = require("./lib/distributednotifications.js");
10
+ const { createEventtap } = require("./lib/eventtap.js");
8
11
  const { createFs } = require("./lib/fs.js");
9
12
  const { createHotkey } = require("./lib/hotkey.js");
13
+ const { createHttp } = require("./lib/http.js");
10
14
  const { createImage } = require("./lib/image.js");
11
15
  const { loadSpoon } = require("./lib/load.js");
12
16
  const { createMenubar } = require("./lib/menubar.js");
@@ -17,6 +21,7 @@ const { strict } = require("./lib/strict.js");
17
21
  const { createTask } = require("./lib/task.js");
18
22
  const { createTimer } = require("./lib/timer.js");
19
23
  const { createUi } = require("./lib/ui.js");
24
+ const { createUserdefaults } = require("./lib/userdefaults.js");
20
25
  const { createWifi } = require("./lib/wifi.js");
21
26
  const { createWindow } = require("./lib/window.js");
22
27
 
@@ -49,11 +54,17 @@ function createHs() {
49
54
  const ui = createUi();
50
55
  const wifi = createWifi(() => ctl.ssid);
51
56
  const window = createWindow();
57
+ const bluetooth = createBluetooth(timer.module);
58
+ const chooser = createChooser();
59
+ const eventtap = createEventtap();
60
+ const http = createHttp();
61
+ const userdefaults = createUserdefaults();
52
62
  Object.assign(globalThis, image.globals);
53
63
 
54
64
  const ctl = merge(
55
65
  {
56
66
  accessibility: true,
67
+ bluetoothPermission: true,
57
68
  location: true,
58
69
  locationRequests: 0,
59
70
  notificationPermission: true,
@@ -77,17 +88,29 @@ function createHs() {
77
88
  ),
78
89
  );
79
90
 
91
+ merge(
92
+ ctl,
93
+ ...[bluetooth, chooser, eventtap, http, userdefaults].map((m) => m.ctl),
94
+ );
95
+
80
96
  const modules = {
81
97
  appinfo: application.appinfo,
82
98
  application: application.module,
83
99
  audiodevice: audiodevice.module,
84
100
  ax: ax.module,
101
+ bluetooth: bluetooth.module,
102
+ chooser: chooser.module,
85
103
  distributednotifications: distributed.module,
104
+ eventtap: eventtap.eventtap,
86
105
  fs: fs.module,
87
106
  hotkey: hotkey.module,
107
+ http: http.module,
88
108
  menubar: menubar.module,
109
+ mouse: eventtap.mouse,
89
110
  notify: notify.module,
90
111
  permissions: {
112
+ checkBluetooth: () => ctl.bluetoothPermission,
113
+ requestBluetooth: async () => ctl.bluetoothPermission,
91
114
  checkAccessibility: () => ctl.accessibility,
92
115
  checkLocation: () => ctl.location,
93
116
  requestLocation: async () => {
@@ -102,6 +125,7 @@ function createHs() {
102
125
  timer: timer.module,
103
126
  ui: { ...ui.ui, ...dialog.module, ...window.module },
104
127
  urlevent: ui.urlevent,
128
+ userdefaults: userdefaults.module,
105
129
  wifi: wifi.module,
106
130
  };
107
131
  for (const [name, module] of Object.entries(modules)) {
@@ -37,8 +37,8 @@ function createApplication() {
37
37
  allWindows = [],
38
38
  focusedWindow = null,
39
39
  mainWindow = null,
40
+ axElement = element({ role: "AXApplication" }),
40
41
  }) {
41
- const axElement = element({ role: "AXApplication" });
42
42
  const app = strict("HSApplication", {
43
43
  bundleID,
44
44
  name,
@@ -63,6 +63,20 @@ function createApplication() {
63
63
  return app;
64
64
  }
65
65
 
66
+ function launch(options) {
67
+ const app = addApp(options);
68
+ events.emit("didLaunch", app);
69
+ return app;
70
+ }
71
+
72
+ function quit(bundleID) {
73
+ const app = apps.get(bundleID);
74
+ if (!app) throw new Error(`hs2-mock: ${bundleID} is not running`);
75
+ apps.delete(bundleID);
76
+ if (frontmost === app) frontmost = null;
77
+ events.emit("didTerminate", app);
78
+ }
79
+
66
80
  function activate(bundleID) {
67
81
  frontmost =
68
82
  apps.get(bundleID) ?? addApp({ bundleID, name: bundleID ?? "unbundled" });
@@ -71,6 +85,8 @@ function createApplication() {
71
85
 
72
86
  const ctl = {
73
87
  addApp,
88
+ launch,
89
+ quit,
74
90
  activate,
75
91
  activations,
76
92
  killed,
@@ -49,6 +49,7 @@ function createAudiodevice() {
49
49
  output = !input,
50
50
  volume = 0.5,
51
51
  muted = false,
52
+ isInUse = false,
52
53
  }) {
53
54
  const events = createListeners("HSAudioDevice", DEVICE_EVENTS);
54
55
  const device = strict("HSAudioDevice", {
@@ -59,6 +60,7 @@ function createAudiodevice() {
59
60
  isOutput: output,
60
61
  volume,
61
62
  muted,
63
+ isInUse,
62
64
  setDefaultOutputDevice() {
63
65
  defaults.output = device;
64
66
  return true;
package/lib/ax.js CHANGED
@@ -1,10 +1,22 @@
1
1
  const { inspect } = require("node:util");
2
2
  const { strict } = require("./strict.js");
3
3
 
4
- function element({ role, children = [], attributes = {} }) {
4
+ function element({
5
+ role,
6
+ title = null,
7
+ elementDescription = null,
8
+ position = null,
9
+ size = null,
10
+ children = [],
11
+ attributes = {},
12
+ }) {
5
13
  const values = { ...attributes };
6
14
  return strict("HSAXElement", {
7
15
  role,
16
+ title,
17
+ elementDescription,
18
+ position,
19
+ size,
8
20
  children: () => children,
9
21
  attributeValue: (name) => values[name] ?? null,
10
22
  setAttributeValue(name, value) {
@@ -22,8 +34,11 @@ const url = (text) => ({
22
34
 
23
35
  function createAx() {
24
36
  const raised = [];
25
- const window = (axElement) => {
37
+ let nextID = 1;
38
+ const window = (axElement, { id = nextID++, isStandard = true } = {}) => {
26
39
  const self = strict("HSWindow", {
40
+ id,
41
+ isStandard,
27
42
  axElement: () => axElement,
28
43
  raise() {
29
44
  raised.push(self);
@@ -0,0 +1,94 @@
1
+ const { createEmitter } = require("./emitter.js");
2
+ const { strict } = require("./strict.js");
3
+
4
+ const OFF = "hs.bluetooth.scan(): Bluetooth is turned off";
5
+
6
+ /** hs.bluetooth BLE scanning. A scan always ends: after `seconds`, 10 by default. */
7
+ function createBluetooth(timer) {
8
+ const events = createEmitter();
9
+ const peripherals = new Map();
10
+ const scans = [];
11
+ let powered = true;
12
+ let active = null;
13
+
14
+ function end(error) {
15
+ const scan = active;
16
+ if (!scan) return;
17
+ active = null;
18
+ scan.timer.stop();
19
+ scan.record.done = true;
20
+ if (error) scan.reject(new Error(error));
21
+ else scan.resolve([...scan.found.values()]);
22
+ }
23
+
24
+ const module = {
25
+ scan({ seconds = 10, allowDuplicates = false } = {}) {
26
+ if (active)
27
+ return Promise.reject(
28
+ new Error("hs.bluetooth.scan(): a scan is already running"),
29
+ );
30
+ if (!powered) return Promise.reject(new Error(OFF));
31
+ const record = { seconds, allowDuplicates, done: false };
32
+ scans.push(record);
33
+ return new Promise((resolve, reject) => {
34
+ active = { record, resolve, reject, found: new Map() };
35
+ active.timer = timer.doAfter(seconds, () => end());
36
+ });
37
+ },
38
+ stopScan: () => end(),
39
+ get isScanning() {
40
+ return active !== null;
41
+ },
42
+ on: events.on,
43
+ off: events.off,
44
+ };
45
+
46
+ function peripheral(identifier) {
47
+ let entry = peripherals.get(identifier);
48
+ if (!entry) {
49
+ const state = { name: null, rssi: null, advertisement: null };
50
+ entry = {
51
+ state,
52
+ object: strict("HSBluetoothPeripheral", {
53
+ identifier,
54
+ get name() {
55
+ return state.name;
56
+ },
57
+ get rssi() {
58
+ return state.rssi;
59
+ },
60
+ get advertisement() {
61
+ return state.advertisement;
62
+ },
63
+ }),
64
+ };
65
+ peripherals.set(identifier, entry);
66
+ }
67
+ return entry;
68
+ }
69
+
70
+ /** An advertisement. Returns false when no scan was there to hear it. */
71
+ function discover({ identifier, name = null, localName = name, rssi }) {
72
+ if (!active) return false;
73
+ const { state, object } = peripheral(identifier);
74
+ state.name = name;
75
+ // 127 means CoreBluetooth has no reading: HS2 keeps the last one.
76
+ if (rssi !== 127) state.rssi = rssi;
77
+ state.advertisement = { localName };
78
+ const repeat = active.found.has(identifier);
79
+ active.found.set(identifier, object);
80
+ if (!repeat || active.record.allowDuplicates)
81
+ events.emit("discovered", object);
82
+ return true;
83
+ }
84
+
85
+ function setBluetooth(on) {
86
+ powered = on;
87
+ if (!on) end(OFF);
88
+ events.emit("powerChanged", on);
89
+ }
90
+
91
+ return { module, ctl: { scans, discover, setBluetooth } };
92
+ }
93
+
94
+ module.exports = { createBluetooth };
package/lib/chooser.js ADDED
@@ -0,0 +1,58 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ /** hs.chooser, without rendering. As in HS2, it hides before onSelect is called. */
4
+ function createChooser() {
5
+ const choosers = [];
6
+
7
+ function create() {
8
+ let visible = false;
9
+ const record = {
10
+ choices: [],
11
+ get visible() {
12
+ return visible;
13
+ },
14
+ choose(text) {
15
+ const item = record.choices.find((choice) => choice.text === text);
16
+ if (!item) throw new Error(`hs2-mock: no choice '${text}'`);
17
+ select(item);
18
+ },
19
+ dismiss: () => select(null),
20
+ };
21
+ function hide() {
22
+ if (!visible) return chooser;
23
+ visible = false;
24
+ chooser.onHide?.();
25
+ return chooser;
26
+ }
27
+ function select(item) {
28
+ if (!visible) throw new Error("hs2-mock: the chooser is not showing");
29
+ hide();
30
+ chooser.onSelect?.(item);
31
+ }
32
+ const chooser = strict("HSChooser", {
33
+ placeholder: "Search...",
34
+ searchSubText: false,
35
+ onSelect: null,
36
+ onHide: null,
37
+ get isVisible() {
38
+ return visible;
39
+ },
40
+ setChoices(choices) {
41
+ record.choices = choices;
42
+ return chooser;
43
+ },
44
+ show() {
45
+ visible = true;
46
+ return chooser;
47
+ },
48
+ hide,
49
+ });
50
+ record.chooser = chooser;
51
+ choosers.push(record);
52
+ return chooser;
53
+ }
54
+
55
+ return { module: { create }, ctl: { choosers } };
56
+ }
57
+
58
+ module.exports = { createChooser };
@@ -0,0 +1,44 @@
1
+ function createEventtap() {
2
+ const keystrokes = [];
3
+ const clicks = [];
4
+ let mouse = { x: 0, y: 0 };
5
+ let onKeystroke;
6
+ let onClick;
7
+
8
+ const eventtap = {
9
+ keyStroke(mods, key, app = null) {
10
+ const keystroke = { mods, key, app };
11
+ keystrokes.push(keystroke);
12
+ onKeystroke?.(keystroke);
13
+ },
14
+ leftClick(x, y) {
15
+ clicks.push({ x, y });
16
+ onClick?.({ x, y });
17
+ },
18
+ };
19
+ const mouseModule = {
20
+ absolutePosition: () => ({ ...mouse }),
21
+ setAbsolutePosition(x, y) {
22
+ mouse = { x, y };
23
+ },
24
+ };
25
+ const ctl = {
26
+ keystrokes,
27
+ clicks,
28
+ get mouse() {
29
+ return { ...mouse };
30
+ },
31
+ set mouse(position) {
32
+ mouse = { ...position };
33
+ },
34
+ respondToKeystrokes(handler) {
35
+ onKeystroke = handler;
36
+ },
37
+ respondToClicks(handler) {
38
+ onClick = handler;
39
+ },
40
+ };
41
+ return { eventtap, mouse: mouseModule, ctl };
42
+ }
43
+
44
+ module.exports = { createEventtap };
package/lib/http.js ADDED
@@ -0,0 +1,75 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ const CONNECTING = 0;
4
+ const OPEN = 1;
5
+ const CLOSED = 3;
6
+
7
+ /** hs.http websockets, as HS2 1.0.0-beta.4 calls their callbacks back. */
8
+ function createHttp() {
9
+ const websockets = [];
10
+
11
+ function openWebSocket(url) {
12
+ const callbacks = {};
13
+ let readyState = CONNECTING;
14
+ const record = {
15
+ url,
16
+ sent: [],
17
+ destroyed: false,
18
+ get readyState() {
19
+ return readyState;
20
+ },
21
+ open() {
22
+ if (readyState !== CONNECTING) return;
23
+ readyState = OPEN;
24
+ callbacks.open?.();
25
+ },
26
+ message(text) {
27
+ if (readyState === OPEN) callbacks.message?.(text);
28
+ },
29
+ remoteClose(code = 1001, reason = "") {
30
+ if (readyState !== OPEN) return;
31
+ readyState = CLOSED;
32
+ callbacks.close?.(code, reason);
33
+ },
34
+ error(text) {
35
+ if (readyState === CLOSED) return;
36
+ readyState = CLOSED;
37
+ callbacks.error?.(text);
38
+ },
39
+ };
40
+ const set = (name) => (callback) => {
41
+ callbacks[name] = callback;
42
+ return socket;
43
+ };
44
+ const socket = strict("HSWebSocket", {
45
+ get readyState() {
46
+ return readyState;
47
+ },
48
+ setOpenCallback: set("open"),
49
+ setMessageCallback: set("message"),
50
+ setCloseCallback: set("close"),
51
+ setErrorCallback: set("error"),
52
+ send(message) {
53
+ if (readyState === OPEN) record.sent.push(message);
54
+ return socket;
55
+ },
56
+ close() {
57
+ if (readyState === CLOSED) return;
58
+ const wasOpen = readyState === OPEN;
59
+ readyState = CLOSED;
60
+ if (wasOpen) callbacks.close?.(1000, "Normal closure");
61
+ },
62
+ destroy() {
63
+ readyState = CLOSED;
64
+ record.destroyed = true;
65
+ for (const name of Object.keys(callbacks)) delete callbacks[name];
66
+ },
67
+ });
68
+ websockets.push(record);
69
+ return socket;
70
+ }
71
+
72
+ return { module: { openWebSocket }, ctl: { websockets } };
73
+ }
74
+
75
+ module.exports = { createHttp };
package/lib/image.js CHANGED
@@ -1,8 +1,12 @@
1
1
  const { strict } = require("./strict.js");
2
2
 
3
- /** The HSImage and HSSize globals. fromName() only loads names in `images`. */
3
+ /**
4
+ * The HSImage and HSSize globals. fromName() only loads names in `images`;
5
+ * fromAppBundle() loads any app not in `missingIcons`.
6
+ */
4
7
  function createImage() {
5
8
  const images = new Set();
9
+ const missingIcons = new Set();
6
10
  class HSSize {
7
11
  constructor(w, h) {
8
12
  this.w = w;
@@ -14,8 +18,10 @@ function createImage() {
14
18
  const HSImage = strict("HSImage", {
15
19
  fromName: (name) => (images.has(name) ? image(name) : null),
16
20
  fromSymbol: image,
21
+ fromAppBundle: (bundleID) =>
22
+ missingIcons.has(bundleID) ? null : image(bundleID),
17
23
  });
18
- return { globals: { HSImage, HSSize }, ctl: { images } };
24
+ return { globals: { HSImage, HSSize }, ctl: { images, missingIcons } };
19
25
  }
20
26
 
21
27
  module.exports = { createImage };
package/lib/menubar.js CHANGED
@@ -4,7 +4,17 @@ function createMenubar() {
4
4
  const menubarItems = [];
5
5
  const module = {
6
6
  create() {
7
- const record = { icon: null, menu: null, destroyed: false };
7
+ let onClick = null;
8
+ const record = {
9
+ icon: null,
10
+ menu: null,
11
+ tooltip: null,
12
+ destroyed: false,
13
+ click(button = "left") {
14
+ if (!onClick) throw new Error("hs2-mock: no click callback is set");
15
+ onClick(button, []);
16
+ },
17
+ };
8
18
  let title = null;
9
19
  record.item = strict("HSMenuBarItem", {
10
20
  get title() {
@@ -17,6 +27,12 @@ function createMenubar() {
17
27
  setIcon(icon) {
18
28
  record.icon = icon;
19
29
  },
30
+ setTooltip(tooltip) {
31
+ record.tooltip = tooltip;
32
+ },
33
+ setClickCallback(callback) {
34
+ onClick = callback;
35
+ },
20
36
  setMenu(menu) {
21
37
  record.menu = menu;
22
38
  },
package/lib/power.js CHANGED
@@ -23,11 +23,21 @@ function createPower() {
23
23
  throw new Error(`hs2-mock: unknown hs.power event '${event}'`);
24
24
  return event;
25
25
  };
26
+ let locks = 0;
26
27
  const module = {
28
+ lockScreen() {
29
+ locks++;
30
+ },
27
31
  on: (event, listener) => events.on(known(event), listener),
28
32
  off: events.off,
29
33
  };
30
- return { module, ctl: { power: (event) => events.emit(known(event)) } };
34
+ const ctl = {
35
+ power: (event) => events.emit(known(event)),
36
+ get locks() {
37
+ return locks;
38
+ },
39
+ };
40
+ return { module, ctl };
31
41
  }
32
42
 
33
43
  module.exports = { createPower };
package/lib/ui.js CHANGED
@@ -2,14 +2,24 @@ const { strict } = require("./strict.js");
2
2
 
3
3
  function createUi() {
4
4
  const alerts = [];
5
+ const shownAlerts = [];
5
6
  const openedURLs = [];
6
7
  const ui = {
7
8
  alert(message) {
9
+ const record = { message, duration: 5, closed: false };
8
10
  const alert = strict("HSUIAlert", {
11
+ duration(seconds) {
12
+ record.duration = seconds;
13
+ return alert;
14
+ },
9
15
  show() {
10
16
  alerts.push(message);
17
+ shownAlerts.push(record);
11
18
  return alert;
12
19
  },
20
+ close() {
21
+ record.closed = true;
22
+ },
13
23
  });
14
24
  return alert;
15
25
  },
@@ -20,7 +30,7 @@ function createUi() {
20
30
  return true;
21
31
  },
22
32
  };
23
- return { ui, urlevent, ctl: { alerts, openedURLs } };
33
+ return { ui, urlevent, ctl: { alerts, shownAlerts, openedURLs } };
24
34
  }
25
35
 
26
36
  module.exports = { createUi };
@@ -0,0 +1,14 @@
1
+ function createUserdefaults() {
2
+ const defaults = new Map();
3
+ const module = {
4
+ get: (key) =>
5
+ defaults.has(key) ? structuredClone(defaults.get(key)) : null,
6
+ set(key, value) {
7
+ defaults.set(key, structuredClone(value));
8
+ },
9
+ clear: (key) => defaults.delete(key),
10
+ };
11
+ return { module, ctl: { defaults } };
12
+ }
13
+
14
+ module.exports = { createUserdefaults };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hs2-mock",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "Strict mock of the Hammerspoon 2 hs global for testing Spoons under node:test",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -8,8 +8,10 @@
8
8
  "url": "git+https://github.com/hugoh/hs2-mock.git"
9
9
  },
10
10
  "main": "index.js",
11
+ "types": "index.d.ts",
11
12
  "files": [
12
13
  "index.js",
14
+ "index.d.ts",
13
15
  "lib",
14
16
  "types"
15
17
  ],
@@ -27,5 +29,8 @@
27
29
  "mock",
28
30
  "testing",
29
31
  "node-test"
30
- ]
32
+ ],
33
+ "devDependencies": {
34
+ "typescript": "7.0.2"
35
+ }
31
36
  }