hs2-mock 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hugo Haas
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 CHANGED
@@ -1,3 +1,56 @@
1
- # Temporary Holding Version
1
+ # hs2-mock
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A strict mock of the [Hammerspoon 2](https://github.com/Hammerspoon/Hammerspoon2) `hs` global, for testing
4
+ Spoons with `node:test`. It also ships the matching `hammerspoon.d.ts` for type checking.
5
+
6
+ ```sh
7
+ npm install --save-dev hs2-mock
8
+ ```
9
+
10
+ ```js
11
+ const { createHs, loadSpoon } = require("hs2-mock");
12
+
13
+ const { hs, ctl } = createHs();
14
+ const spoon = loadSpoon(`${__dirname}/..`, hs);
15
+
16
+ ctl.addApp({ bundleID: "com.apple.Preview" });
17
+ spoon.monitor([{ bundleID: "com.apple.Preview", idleTime: 60 }]).start();
18
+ await ctl.advance(600);
19
+ assert.deepEqual(ctl.killed, ["com.apple.Preview"]);
20
+ ```
21
+
22
+ Reading a member the mock lacks throws `hs2-mock: hs.x.y is not mocked`. Tests can add or replace anything.
23
+
24
+ ## Mocked
25
+
26
+ | Module | Members |
27
+ | ---------------- | -------------------------------------------- |
28
+ | `hs.application` | `frontmost`, `matchingBundleID`, `on`, `off` |
29
+ | `hs.ax` | `applicationElement`, `windowElement` |
30
+ | `hs.hotkey` | `bind`, `create` |
31
+ | `hs.permissions` | `checkAccessibility` |
32
+ | `hs.timer` | `doAfter`, `doEvery`, `secondsSinceEpoch` |
33
+ | `hs.ui` | `alert` (`show`) |
34
+ | `hs.urlevent` | `openURL` |
35
+
36
+ ## Controls (`ctl`)
37
+
38
+ | Control | Does |
39
+ | ----------------------------------------- | -------------------------------------------------------------------------------------- |
40
+ | `advance(seconds)` | Moves the clock, firing timers and settling promises between them |
41
+ | `flush()` | Settles pending promises |
42
+ | `addApp({ bundleID, name, allWindows })` | Adds a running app and returns it |
43
+ | `activate(bundleID)` | Brings an app to the front and emits `didActivate`; `null` for one without a bundle ID |
44
+ | `hotkeys` | Created hotkeys that have not been destroyed |
45
+ | `element({ role, children, attributes })` | An accessibility element |
46
+ | `window(element)` | A window whose element it is, for `addApp`'s `focusedWindow` or `mainWindow` |
47
+ | `url(text)` | A URL attribute value, as `hs.ax` returns it |
48
+ | `alerts`, `openedURLs` | What was shown and opened |
49
+ | `killed` | Bundle IDs of killed apps |
50
+ | `accessibility` | Whether Accessibility permission is granted |
51
+
52
+ ## Types
53
+
54
+ Add `node_modules/hs2-mock/types/*.d.ts` to your `tsconfig.json`, with `"types": []`. The version they come
55
+ from is in `types/VERSION`; refresh with `mise run vendor <tag>`. `hammerspoon.d.ts` is MIT-licensed,
56
+ copyright the Hammerspoon contributors.
package/index.js ADDED
@@ -0,0 +1,40 @@
1
+ const { createApplication } = require("./lib/application.js");
2
+ const { createAx } = require("./lib/ax.js");
3
+ const { createHotkey } = require("./lib/hotkey.js");
4
+ const { loadSpoon } = require("./lib/load.js");
5
+ const { strict } = require("./lib/strict.js");
6
+ const { createTimer } = require("./lib/timer.js");
7
+ const { createUi } = require("./lib/ui.js");
8
+
9
+ /**
10
+ * A fresh strict mock of the Hammerspoon 2 `hs` global, and the test controls.
11
+ */
12
+ function createHs() {
13
+ const timer = createTimer();
14
+ const application = createApplication();
15
+ const hotkey = createHotkey();
16
+ const ax = createAx();
17
+ const ui = createUi();
18
+ const ctl = {
19
+ ...timer.ctl,
20
+ ...application.ctl,
21
+ ...hotkey.ctl,
22
+ ...ax.ctl,
23
+ ...ui.ctl,
24
+ accessibility: true,
25
+ };
26
+ const modules = {
27
+ application: application.module,
28
+ ax: ax.module,
29
+ hotkey: hotkey.module,
30
+ permissions: { checkAccessibility: () => ctl.accessibility },
31
+ timer: timer.module,
32
+ ui: ui.ui,
33
+ urlevent: ui.urlevent,
34
+ };
35
+ for (const [name, module] of Object.entries(modules))
36
+ modules[name] = strict(`hs.${name}`, module);
37
+ return { hs: strict("hs", modules), ctl };
38
+ }
39
+
40
+ module.exports = { createHs, loadSpoon };
@@ -0,0 +1,55 @@
1
+ const { element } = require("./ax.js");
2
+ const { createEmitter } = require("./emitter.js");
3
+ const { strict } = require("./strict.js");
4
+
5
+ function createApplication() {
6
+ const apps = new Map();
7
+ const killed = [];
8
+ const events = createEmitter();
9
+ let frontmost = null;
10
+
11
+ const module = {
12
+ matchingBundleID: (bundleID) => apps.get(bundleID) ?? null,
13
+ frontmost: () => frontmost,
14
+ on: events.on,
15
+ off: events.off,
16
+ };
17
+
18
+ function addApp({
19
+ bundleID,
20
+ name = bundleID,
21
+ allWindows = [],
22
+ focusedWindow = null,
23
+ mainWindow = null,
24
+ }) {
25
+ const axElement = element({ role: "AXApplication" });
26
+ const app = strict("HSApplication", {
27
+ bundleID,
28
+ name,
29
+ allWindows,
30
+ focusedWindow,
31
+ mainWindow,
32
+ axElement: () => axElement,
33
+ get isActive() {
34
+ return frontmost === app;
35
+ },
36
+ kill() {
37
+ killed.push(bundleID);
38
+ apps.delete(bundleID);
39
+ return true;
40
+ },
41
+ });
42
+ apps.set(bundleID, app);
43
+ return app;
44
+ }
45
+
46
+ function activate(bundleID) {
47
+ frontmost =
48
+ apps.get(bundleID) ?? addApp({ bundleID, name: bundleID ?? "unbundled" });
49
+ events.emit("didActivate", frontmost);
50
+ }
51
+
52
+ return { module, ctl: { addApp, activate, killed } };
53
+ }
54
+
55
+ module.exports = { createApplication };
package/lib/ax.js ADDED
@@ -0,0 +1,34 @@
1
+ const { inspect } = require("node:util");
2
+ const { strict } = require("./strict.js");
3
+
4
+ function element({ role, children = [], attributes = {} }) {
5
+ const values = { ...attributes };
6
+ return strict("HSAXElement", {
7
+ role,
8
+ children: () => children,
9
+ attributeValue: (name) => values[name] ?? null,
10
+ setAttributeValue(name, value) {
11
+ values[name] = value;
12
+ return true;
13
+ },
14
+ });
15
+ }
16
+
17
+ const window = (axElement) =>
18
+ strict("HSWindow", { axElement: () => axElement });
19
+
20
+ /** hs.ax returns URL attributes as an NSURL that only util.inspect() reads. */
21
+ const url = (text) => ({
22
+ toString: () => "[object NSURL]",
23
+ [inspect.custom]: () => text,
24
+ });
25
+
26
+ function createAx() {
27
+ const module = {
28
+ applicationElement: (app) => app.axElement(),
29
+ windowElement: (w) => w.axElement(),
30
+ };
31
+ return { module, ctl: { element, window, url } };
32
+ }
33
+
34
+ module.exports = { createAx, element };
package/lib/dts.js ADDED
@@ -0,0 +1,37 @@
1
+ // Reads member names from the vendored, generated hammerspoon.d.ts. A line
2
+ // parser is enough for its regular layout, and TypeScript 7 has no compiler API.
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+
6
+ const OPEN = /^declare (?:namespace|class|interface) ([\w.]+)/;
7
+ const MEMBER = {
8
+ namespace: /^ {4}(?:function|const|let|var) (\w+)/,
9
+ type: /^ {4}(?:static )?(?:readonly )?(\w+)\??[(:<]/,
10
+ };
11
+
12
+ /** @returns {Map<string, Set<string>>} member names by namespace or class */
13
+ function declarations(
14
+ file = path.join(__dirname, "..", "types", "hammerspoon.d.ts"),
15
+ ) {
16
+ const found = new Map();
17
+ let members;
18
+ let pattern;
19
+ for (const line of fs.readFileSync(file, "utf8").split("\n")) {
20
+ const open = OPEN.exec(line);
21
+ if (open) {
22
+ members = found.get(open[1]) ?? new Set();
23
+ found.set(open[1], members);
24
+ pattern = line.startsWith("declare namespace")
25
+ ? MEMBER.namespace
26
+ : MEMBER.type;
27
+ } else if (line.startsWith("}")) {
28
+ members = undefined;
29
+ } else if (members) {
30
+ const member = pattern.exec(line);
31
+ if (member) members.add(member[1]);
32
+ }
33
+ }
34
+ return found;
35
+ }
36
+
37
+ module.exports = { declarations };
package/lib/emitter.js ADDED
@@ -0,0 +1,19 @@
1
+ function createEmitter() {
2
+ const listeners = new Map();
3
+ return {
4
+ on(event, listener) {
5
+ listeners.set(event, [...(listeners.get(event) ?? []), listener]);
6
+ },
7
+ off(event, listener) {
8
+ listeners.set(
9
+ event,
10
+ (listeners.get(event) ?? []).filter((l) => l !== listener),
11
+ );
12
+ },
13
+ emit(event, ...args) {
14
+ for (const listener of listeners.get(event) ?? []) listener(...args);
15
+ },
16
+ };
17
+ }
18
+
19
+ module.exports = { createEmitter };
package/lib/hotkey.js ADDED
@@ -0,0 +1,41 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ function createHotkey() {
4
+ const hotkeys = [];
5
+
6
+ const module = {
7
+ create(mods, key, onPressed) {
8
+ let enabled = false;
9
+ const hotkey = strict("HSHotkey", {
10
+ mods,
11
+ key,
12
+ onPressed,
13
+ enable() {
14
+ enabled = true;
15
+ return true;
16
+ },
17
+ disable() {
18
+ enabled = false;
19
+ },
20
+ isEnabled: () => enabled,
21
+ destroy() {
22
+ enabled = false;
23
+ const index = hotkeys.indexOf(hotkey);
24
+ if (index >= 0) hotkeys.splice(index, 1);
25
+ },
26
+ });
27
+ hotkeys.push(hotkey);
28
+ return hotkey;
29
+ },
30
+ };
31
+
32
+ module.bind = (mods, key, onPressed) => {
33
+ const hotkey = module.create(mods, key, onPressed);
34
+ hotkey.enable();
35
+ return hotkey;
36
+ };
37
+
38
+ return { module, ctl: { hotkeys } };
39
+ }
40
+
41
+ module.exports = { createHotkey };
package/lib/load.js ADDED
@@ -0,0 +1,58 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+
4
+ /** Stands in for the bindHotkeys() that hs.spoons.load() makes from `bindings`. */
5
+ function installBindHotkeys(spoon, name) {
6
+ const bound = new Map();
7
+ const release = (action) => {
8
+ bound.get(action)?.destroy();
9
+ bound.delete(action);
10
+ };
11
+ spoon.bindHotkeys = (mapping) => {
12
+ for (const [action, spec] of Object.entries(mapping)) {
13
+ if (!Object.hasOwn(spoon.bindings, action)) {
14
+ throw new Error(`${name}.bindHotkeys(): no action '${action}'`);
15
+ }
16
+ release(action);
17
+ if (!spec) continue;
18
+ const [mods, key] = Array.isArray(spec) ? spec : [spec.mods, spec.key];
19
+ const binding = spoon.bindings[action];
20
+ const pressed = typeof binding === "function" ? binding : binding.pressed;
21
+ bound.set(
22
+ action,
23
+ globalThis.hs.hotkey.bind(mods, key, pressed, null, null),
24
+ );
25
+ }
26
+ return spoon;
27
+ };
28
+ spoon.unbindHotkeys = (actions = [...bound.keys()]) => {
29
+ for (const action of actions) release(action);
30
+ return spoon;
31
+ };
32
+ }
33
+
34
+ /**
35
+ * Loads a spoon the way hs.spoons.load() does: its modules run afresh, spoon.json
36
+ * metadata is set on the export, bindHotkeys() is made from `bindings`, then
37
+ * init() is called.
38
+ * @param {string} dir the spoon's directory
39
+ * @param {object} hs the mock to install as the `hs` global
40
+ */
41
+ function loadSpoon(dir, hs) {
42
+ const root = fs.realpathSync(dir);
43
+ for (const file of Object.keys(require.cache)) {
44
+ if (file.startsWith(root + path.sep)) delete require.cache[file];
45
+ }
46
+ Object.assign(globalThis, { hs });
47
+ const manifest = JSON.parse(
48
+ fs.readFileSync(path.join(root, "spoon.json"), "utf8"),
49
+ );
50
+ const spoon = require(path.join(root, "init.js"));
51
+ const { name, author, version, description } = manifest;
52
+ Object.assign(spoon, { name, author, version, description });
53
+ if (spoon.bindings) installBindHotkeys(spoon, name);
54
+ spoon.init?.();
55
+ return spoon;
56
+ }
57
+
58
+ module.exports = { loadSpoon };
package/lib/strict.js ADDED
@@ -0,0 +1,15 @@
1
+ // Keys that Node and promise resolution probe on any object.
2
+ const PROBED = new Set(["then", "toJSON", "inspect", "constructor"]);
3
+
4
+ /** Makes reading a member the mock lacks an error instead of undefined. */
5
+ function strict(name, object) {
6
+ return new Proxy(object, {
7
+ get(target, key, receiver) {
8
+ if (typeof key === "symbol" || key in target || PROBED.has(key))
9
+ return Reflect.get(target, key, receiver);
10
+ throw new Error(`hs2-mock: ${name}.${key} is not mocked`);
11
+ },
12
+ });
13
+ }
14
+
15
+ module.exports = { strict };
package/lib/timer.js ADDED
@@ -0,0 +1,58 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ const EPOCH = 1_800_000_000;
4
+ const flush = () => new Promise((resolve) => setImmediate(resolve));
5
+
6
+ function createTimer() {
7
+ let now = EPOCH;
8
+ const active = new Set();
9
+
10
+ function schedule(interval, callback, repeats) {
11
+ const state = { due: now + interval };
12
+ const timer = {
13
+ interval,
14
+ repeats,
15
+ start() {
16
+ state.due = now + interval;
17
+ active.add(state);
18
+ return timer;
19
+ },
20
+ stop() {
21
+ active.delete(state);
22
+ return timer;
23
+ },
24
+ running: () => active.has(state),
25
+ };
26
+ state.fire = () => {
27
+ if (repeats) state.due += interval;
28
+ else active.delete(state);
29
+ callback();
30
+ };
31
+ return strict("HSTimer", timer).start();
32
+ }
33
+
34
+ const module = {
35
+ secondsSinceEpoch: () => now,
36
+ doAfter: (seconds, callback) => schedule(seconds, callback, false),
37
+ doEvery: (interval, callback) => schedule(interval, callback, true),
38
+ };
39
+
40
+ async function advance(seconds) {
41
+ const end = now + seconds;
42
+ await flush();
43
+ for (;;) {
44
+ const next = [...active]
45
+ .filter((t) => t.due <= end)
46
+ .sort((a, b) => a.due - b.due)[0];
47
+ if (!next) break;
48
+ now = next.due;
49
+ next.fire();
50
+ await flush();
51
+ }
52
+ now = end;
53
+ }
54
+
55
+ return { module, ctl: { advance, flush } };
56
+ }
57
+
58
+ module.exports = { createTimer };
package/lib/ui.js ADDED
@@ -0,0 +1,26 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ function createUi() {
4
+ const alerts = [];
5
+ const openedURLs = [];
6
+ const ui = {
7
+ alert(message) {
8
+ const alert = strict("HSUIAlert", {
9
+ show() {
10
+ alerts.push(message);
11
+ return alert;
12
+ },
13
+ });
14
+ return alert;
15
+ },
16
+ };
17
+ const urlevent = {
18
+ openURL(url) {
19
+ openedURLs.push(url);
20
+ return true;
21
+ },
22
+ };
23
+ return { ui, urlevent, ctl: { alerts, openedURLs } };
24
+ }
25
+
26
+ module.exports = { createUi };
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "hs2-mock",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Strict mock of the Hammerspoon 2 hs global for testing Spoons under node:test",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/hugoh/hs2-mock.git"
9
+ },
10
+ "main": "index.js",
11
+ "files": [
12
+ "index.js",
13
+ "lib",
14
+ "types"
15
+ ],
16
+ "scripts": {
17
+ "test": "node --test"
18
+ },
19
+ "engines": {
20
+ "node": ">=22"
21
+ }
22
+ }
package/types/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.0.0-beta.4
@@ -0,0 +1,8 @@
1
+ declare const module: { exports: any };
2
+ declare function require(id: string): any;
3
+ declare const __dirname: string;
4
+
5
+ // The part of Hammerspoon 2's built-in `util` module that spoons use.
6
+ declare module "util" {
7
+ export function inspect(value: unknown): string;
8
+ }