import assert from 'node:assert/strict' import test from 'node:test' import { loadTestModule } from './load-test-module.mjs' const { createKeymapRequests, keymapPresetUpdate } = await loadTestModule(`export * from './lib/vmKeymap'`) const off = { preset: 'off', bindings: {} } const custom = { preset: 'custom', bindings: { lwin: 'lcmd' } } test('switching to custom preserves the previous preset bindings', () => { const preset = { ...custom, preset: 'win_to_cmd' } assert.equal(keymapPresetUpdate(preset, 'win_to_cmd'), undefined) assert.deepEqual(keymapPresetUpdate(preset, 'custom'), custom) assert.deepEqual(keymapPresetUpdate(off, 'custom'), { preset: 'custom', bindings: {} }) }) test('a pending write for one VM does not block or overwrite another VM', async () => { const saved = Promise.withResolvers() const writes = [] let active = 'a' let state = {} const requests = createKeymapRequests({ async GetVMKeymap(name) { assert.equal(name, 'b') return off }, SetVMKeymap(name, request) { writes.push([name, request]) return saved.promise }, }, () => active, (patch) => Object.assign(state, patch)) const write = requests.write('a', custom) await requests.write('a', off) assert.deepEqual(writes, [['a', custom]]) assert.equal(state.busy, true) active = 'b' state = requests.initial('b') await requests.watch('b').refresh() saved.resolve(custom) await write assert.deepEqual(state, { keymap: off, busy: false, error: '' }) assert.equal(requests.initial('a').busy, false) }) test('a failed keymap read recovers on the next refresh', async () => { let fail = true const state = {} const requests = createKeymapRequests({ async GetVMKeymap() { if (fail) throw new Error('temporary') return off }, }, () => 'vm', (patch) => Object.assign(state, patch)) const watch = requests.watch('vm') await watch.refresh() assert.equal(state.error, 'temporary') fail = false await watch.refresh() assert.deepEqual(state, { keymap: off, error: '' }) }) test('a read started before a write cannot restore the old keymap', async () => { const previousRead = Promise.withResolvers() const state = {} const requests = createKeymapRequests({ GetVMKeymap: () => previousRead.promise, SetVMKeymap: async () => custom, }, () => 'vm', (patch) => Object.assign(state, patch)) const read = requests.watch('vm').refresh() await requests.write('vm', custom) previousRead.resolve(off) await read assert.deepEqual(state, { keymap: custom, busy: false, error: '' }) })