@namzu/computer-use 4.4.0 → 4.6.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.
Files changed (139) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/SubprocessComputerUseHost.d.ts +8 -1
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +15 -4
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/a11y/a11y.d.ts +15 -7
  7. package/dist/a11y/a11y.d.ts.map +1 -1
  8. package/dist/a11y/a11y.js +12 -5
  9. package/dist/a11y/a11y.js.map +1 -1
  10. package/dist/a11y/index.d.ts +7 -1
  11. package/dist/a11y/index.d.ts.map +1 -1
  12. package/dist/a11y/index.js +4 -1
  13. package/dist/a11y/index.js.map +1 -1
  14. package/dist/a11y/macos-helper.d.ts +80 -0
  15. package/dist/a11y/macos-helper.d.ts.map +1 -0
  16. package/dist/a11y/macos-helper.js +436 -0
  17. package/dist/a11y/macos-helper.js.map +1 -0
  18. package/dist/a11y/macos-signing.d.ts +56 -0
  19. package/dist/a11y/macos-signing.d.ts.map +1 -0
  20. package/dist/a11y/macos-signing.js +228 -0
  21. package/dist/a11y/macos-signing.js.map +1 -0
  22. package/dist/a11y/macos.d.ts +173 -0
  23. package/dist/a11y/macos.d.ts.map +1 -0
  24. package/dist/a11y/macos.js +271 -0
  25. package/dist/a11y/macos.js.map +1 -0
  26. package/dist/a11y/windows.d.ts +14 -2
  27. package/dist/a11y/windows.d.ts.map +1 -1
  28. package/dist/a11y/windows.js +31 -6
  29. package/dist/a11y/windows.js.map +1 -1
  30. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  31. package/dist/adapters/cua-driver/adapter.js +48 -10
  32. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  33. package/dist/adapters/cua-driver/ui-tree.d.ts +1 -0
  34. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  35. package/dist/adapters/cua-driver/ui-tree.js +2 -0
  36. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  37. package/dist/adapters/darwin-ax.d.ts +94 -0
  38. package/dist/adapters/darwin-ax.d.ts.map +1 -0
  39. package/dist/adapters/darwin-ax.js +754 -0
  40. package/dist/adapters/darwin-ax.js.map +1 -0
  41. package/dist/adapters/darwin.d.ts +43 -2
  42. package/dist/adapters/darwin.d.ts.map +1 -1
  43. package/dist/adapters/darwin.js +145 -7
  44. package/dist/adapters/darwin.js.map +1 -1
  45. package/dist/adapters/png.d.ts +6 -0
  46. package/dist/adapters/png.d.ts.map +1 -0
  47. package/dist/adapters/png.js +7 -0
  48. package/dist/adapters/png.js.map +1 -0
  49. package/dist/adapters/win32-native.d.ts +53 -0
  50. package/dist/adapters/win32-native.d.ts.map +1 -0
  51. package/dist/adapters/win32-native.js +279 -0
  52. package/dist/adapters/win32-native.js.map +1 -0
  53. package/dist/adapters/win32.d.ts +19 -1
  54. package/dist/adapters/win32.d.ts.map +1 -1
  55. package/dist/adapters/win32.js +35 -8
  56. package/dist/adapters/win32.js.map +1 -1
  57. package/dist/foreground/ladder.d.ts.map +1 -1
  58. package/dist/foreground/ladder.js +5 -1
  59. package/dist/foreground/ladder.js.map +1 -1
  60. package/dist/foreground/types.d.ts +6 -0
  61. package/dist/foreground/types.d.ts.map +1 -1
  62. package/dist/foreground/types.js.map +1 -1
  63. package/dist/foreground/windows.d.ts +2 -0
  64. package/dist/foreground/windows.d.ts.map +1 -1
  65. package/dist/foreground/windows.js +24 -11
  66. package/dist/foreground/windows.js.map +1 -1
  67. package/dist/index.d.ts +9 -0
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +7 -0
  70. package/dist/index.js.map +1 -1
  71. package/dist/native/a11y.d.ts +61 -0
  72. package/dist/native/a11y.d.ts.map +1 -0
  73. package/dist/native/a11y.js +197 -0
  74. package/dist/native/a11y.js.map +1 -0
  75. package/dist/native/env.d.ts +19 -0
  76. package/dist/native/env.d.ts.map +1 -0
  77. package/dist/native/env.js +29 -0
  78. package/dist/native/env.js.map +1 -0
  79. package/dist/native/foreground-monitor.d.ts +51 -0
  80. package/dist/native/foreground-monitor.d.ts.map +1 -0
  81. package/dist/native/foreground-monitor.js +120 -0
  82. package/dist/native/foreground-monitor.js.map +1 -0
  83. package/dist/native/presence.d.ts +24 -0
  84. package/dist/native/presence.d.ts.map +1 -0
  85. package/dist/native/presence.js +47 -0
  86. package/dist/native/presence.js.map +1 -0
  87. package/dist/native/process.d.ts +73 -0
  88. package/dist/native/process.d.ts.map +1 -0
  89. package/dist/native/process.js +302 -0
  90. package/dist/native/process.js.map +1 -0
  91. package/dist/native/protocol.d.ts +476 -0
  92. package/dist/native/protocol.d.ts.map +1 -0
  93. package/dist/native/protocol.js +601 -0
  94. package/dist/native/protocol.js.map +1 -0
  95. package/dist/native/shared.d.ts +16 -0
  96. package/dist/native/shared.d.ts.map +1 -0
  97. package/dist/native/shared.js +62 -0
  98. package/dist/native/shared.js.map +1 -0
  99. package/dist/native/watch.d.ts +35 -0
  100. package/dist/native/watch.d.ts.map +1 -0
  101. package/dist/native/watch.js +45 -0
  102. package/dist/native/watch.js.map +1 -0
  103. package/dist/presence/presence.d.ts +3 -2
  104. package/dist/presence/presence.d.ts.map +1 -1
  105. package/dist/presence/presence.js.map +1 -1
  106. package/dist/presence/windows.d.ts +2 -0
  107. package/dist/presence/windows.d.ts.map +1 -1
  108. package/dist/presence/windows.js +15 -0
  109. package/dist/presence/windows.js.map +1 -1
  110. package/helper-macos/main.swift +1756 -0
  111. package/package.json +3 -2
  112. package/src/SubprocessComputerUseHost.ts +26 -2
  113. package/src/a11y/a11y.ts +25 -11
  114. package/src/a11y/index.ts +28 -1
  115. package/src/a11y/macos-helper.ts +538 -0
  116. package/src/a11y/macos-signing.ts +280 -0
  117. package/src/a11y/macos.ts +496 -0
  118. package/src/a11y/windows.ts +31 -4
  119. package/src/adapters/cua-driver/adapter.ts +55 -15
  120. package/src/adapters/cua-driver/ui-tree.ts +2 -0
  121. package/src/adapters/darwin-ax.ts +920 -0
  122. package/src/adapters/darwin.ts +184 -4
  123. package/src/adapters/png.ts +5 -0
  124. package/src/adapters/win32-native.ts +329 -0
  125. package/src/adapters/win32.ts +53 -5
  126. package/src/foreground/ladder.ts +5 -1
  127. package/src/foreground/types.ts +6 -0
  128. package/src/foreground/windows.ts +25 -11
  129. package/src/index.ts +14 -0
  130. package/src/native/a11y.ts +267 -0
  131. package/src/native/env.ts +33 -0
  132. package/src/native/foreground-monitor.ts +165 -0
  133. package/src/native/presence.ts +58 -0
  134. package/src/native/process.ts +347 -0
  135. package/src/native/protocol.ts +1103 -0
  136. package/src/native/shared.ts +75 -0
  137. package/src/native/watch.ts +78 -0
  138. package/src/presence/presence.ts +3 -2
  139. package/src/presence/windows.ts +15 -0
@@ -0,0 +1,1103 @@
1
+ /**
2
+ * The `namzu-native/1` line codec: how this package talks to the native Windows
3
+ * helper (`crates/namzu-native`), one JSON object per line over stdio.
4
+ *
5
+ * Only the codec lives here: a request is written with {@link encodeRequest},
6
+ * a reply is read with {@link decodeReply}, which refuses a line that is not
7
+ * the shape the op promises. The Rust side (`crates/namzu-native-core`) reads and
8
+ * writes the same lines; `conformance/namzu-native/` is the list both are held to.
9
+ */
10
+
11
+ import type {
12
+ A11yAction,
13
+ A11yChangeKind,
14
+ A11yDisplay,
15
+ A11yFingerprint,
16
+ A11yNode,
17
+ A11yRect,
18
+ A11yWindow,
19
+ } from '../a11y/interface.js'
20
+
21
+ export const NATIVE_PROTOCOL = 'namzu-native/1'
22
+
23
+ /**
24
+ * What `NATIVE_PROTOCOL` was called while the helper was `namzu-win`. The
25
+ * lines are identical. A helper built before the rename answers `hello` with
26
+ * `protocol_mismatch` to the new name, and the client then says the old one.
27
+ *
28
+ * Deprecated: the next major release of `@namzu/computer-use` drops it.
29
+ */
30
+ export const LEGACY_NATIVE_PROTOCOL = 'namzu-win/1'
31
+
32
+ /** The largest id or revision either side writes: a JavaScript number holds it exactly. */
33
+ export const MAX_SAFE_ID = Number.MAX_SAFE_INTEGER
34
+
35
+ export type NativeOp =
36
+ | 'hello'
37
+ | 'windows'
38
+ | 'displays'
39
+ | 'snapshot'
40
+ | 'identity'
41
+ | 'resolve'
42
+ | 'seq'
43
+ | 'wait_change'
44
+ | 'act'
45
+ | 'input'
46
+ | 'capture'
47
+ | 'foreground.get'
48
+ | 'foreground.set'
49
+ | 'lease.begin'
50
+ | 'lease.end'
51
+ | 'monitor.start'
52
+ | 'monitor.stop'
53
+ | 'monitor.poll'
54
+ | 'watch.start'
55
+ | 'watch.stop'
56
+ | 'watch.poll'
57
+ | 'presence.act'
58
+ | 'presence.hide'
59
+ | 'cancel'
60
+ | 'quit'
61
+
62
+ // --- requests ---------------------------------------------------------------
63
+
64
+ export type NativeRequest =
65
+ | { readonly op: 'hello'; readonly protocol: string; readonly cliVersion: string }
66
+ | { readonly op: 'windows'; readonly includeOwned?: boolean }
67
+ | { readonly op: 'displays' }
68
+ | {
69
+ readonly op: 'snapshot'
70
+ readonly windowId: string
71
+ readonly maxNodes?: number
72
+ readonly maxDepth?: number
73
+ readonly skeleton?: boolean
74
+ readonly allowChromium?: boolean
75
+ readonly timeoutMs?: number
76
+ }
77
+ | {
78
+ readonly op: 'identity'
79
+ readonly windowId: string
80
+ readonly index: number
81
+ readonly revision?: number
82
+ }
83
+ | { readonly op: 'resolve'; readonly windowId: string; readonly fingerprint: A11yFingerprint }
84
+ | { readonly op: 'seq'; readonly windowId?: string }
85
+ | {
86
+ readonly op: 'wait_change'
87
+ readonly windowId: string
88
+ readonly since?: number
89
+ readonly quietMs?: number
90
+ readonly timeoutMs?: number
91
+ readonly kinds?: readonly A11yChangeKind[]
92
+ }
93
+ | NativeActRequest
94
+ | NativeInputRequest
95
+ | NativeCaptureRequest
96
+ | { readonly op: 'foreground.get'; readonly windowId?: string; readonly processId?: number }
97
+ | { readonly op: 'foreground.set'; readonly windowId: string }
98
+ | NativeLeaseBeginRequest
99
+ | {
100
+ readonly op: 'lease.end'
101
+ readonly restore: boolean
102
+ readonly keepCursor?: boolean
103
+ readonly release?: boolean
104
+ }
105
+ | NativeMonitorStartRequest
106
+ | { readonly op: 'monitor.stop' }
107
+ | { readonly op: 'monitor.poll'; readonly since?: number }
108
+ | NativeWatchStartRequest
109
+ | { readonly op: 'watch.stop' }
110
+ | { readonly op: 'watch.poll' }
111
+ | NativePresenceActRequest
112
+ | { readonly op: 'presence.hide' }
113
+ | { readonly op: 'cancel'; readonly target: number }
114
+ | { readonly op: 'quit' }
115
+
116
+ /** What `act` does to a control, through the pattern it offers. */
117
+ export type NativeActKind =
118
+ | 'invoke'
119
+ | 'setValue'
120
+ | 'toggle'
121
+ | 'expand'
122
+ | 'collapse'
123
+ | 'select'
124
+ | 'scrollIntoView'
125
+ | 'scroll'
126
+ | 'focus'
127
+
128
+ /** One of `ref` and `fingerprint` names the control. */
129
+ export interface NativeActRequest {
130
+ readonly op: 'act'
131
+ readonly windowId: string
132
+ readonly ref?: string
133
+ readonly fingerprint?: A11yFingerprint
134
+ readonly action: NativeActKind
135
+ /** For `setValue`. */
136
+ readonly text?: string
137
+ /** For `scroll`: steps right and down are positive. */
138
+ readonly dx?: number
139
+ readonly dy?: number
140
+ readonly timeoutMs?: number
141
+ }
142
+
143
+ export type NativeMouseButton = 'left' | 'right' | 'middle'
144
+ export type NativeScrollDirection = 'up' | 'down' | 'left' | 'right'
145
+
146
+ /** Points are virtual-desktop physical pixels. */
147
+ export type NativeInputRequest = { readonly op: 'input' } & (
148
+ | {
149
+ readonly kind: 'click'
150
+ readonly x: number
151
+ readonly y: number
152
+ readonly button?: NativeMouseButton
153
+ readonly count?: 1 | 2 | 3
154
+ }
155
+ | { readonly kind: 'move'; readonly x: number; readonly y: number }
156
+ | {
157
+ readonly kind: 'drag'
158
+ readonly x: number
159
+ readonly y: number
160
+ readonly toX: number
161
+ readonly toY: number
162
+ readonly button?: NativeMouseButton
163
+ }
164
+ | {
165
+ readonly kind: 'scroll'
166
+ readonly x: number
167
+ readonly y: number
168
+ readonly direction: NativeScrollDirection
169
+ readonly amount?: number
170
+ }
171
+ | { readonly kind: 'type'; readonly text: string }
172
+ | { readonly kind: 'key'; readonly keys: string }
173
+ )
174
+
175
+ export type NativeCaptureTarget =
176
+ | { readonly kind: 'window'; readonly windowId: string }
177
+ | { readonly kind: 'display'; readonly id?: string }
178
+ | {
179
+ readonly kind: 'region'
180
+ readonly x: number
181
+ readonly y: number
182
+ readonly width: number
183
+ readonly height: number
184
+ }
185
+
186
+ export interface NativeCaptureRequest {
187
+ readonly op: 'capture'
188
+ readonly target: NativeCaptureTarget
189
+ /** A directory the caller made; the picture is written into it. */
190
+ readonly into?: string
191
+ /** Return a small picture in the reply instead. */
192
+ readonly inline?: boolean
193
+ readonly cursor?: boolean
194
+ readonly timeoutMs?: number
195
+ }
196
+
197
+ export type NativeMonitorHook = 'foreground' | 'input'
198
+
199
+ /** What to watch; default both. */
200
+ export interface NativeMonitorStartRequest {
201
+ readonly op: 'monitor.start'
202
+ readonly hooks?: readonly NativeMonitorHook[]
203
+ }
204
+
205
+ /** What a watch reports. Nothing here is about keys or the mouse: there is no such kind. */
206
+ export type NativeWatchKind = 'invoke' | 'focus' | 'selection' | 'menu' | 'window' | 'value' | 'app'
207
+
208
+ export const NATIVE_WATCH_KINDS: readonly NativeWatchKind[] = [
209
+ 'invoke',
210
+ 'focus',
211
+ 'selection',
212
+ 'menu',
213
+ 'window',
214
+ 'value',
215
+ 'app',
216
+ ]
217
+
218
+ /** What to watch and how much to keep. Every field is optional; the helper clamps each. */
219
+ export interface NativeWatchStartRequest {
220
+ readonly op: 'watch.start'
221
+ /** Default every kind. */
222
+ readonly kinds?: readonly NativeWatchKind[]
223
+ /** Repeated value changes of one control within this many ms are one event (default 250, at most 5000; 0 keeps all). */
224
+ readonly coalesceMs?: number
225
+ /** Events kept between polls (default and most 2000). */
226
+ readonly maxQueue?: number
227
+ /** Characters of a value kept (default and most 200). */
228
+ readonly maxValue?: number
229
+ /** Characters of a control name kept (default and most 80). */
230
+ readonly maxName?: number
231
+ }
232
+
233
+ export type NativePresenceKind = 'click' | 'type' | 'move'
234
+
235
+ export interface NativePresenceActRequest {
236
+ readonly op: 'presence.act'
237
+ readonly windowId: string
238
+ readonly kind: NativePresenceKind
239
+ /** Where the action lands, in virtual-desktop pixels; absent for typing. */
240
+ readonly at?: { readonly x: number; readonly y: number }
241
+ }
242
+
243
+ export interface NativeLeaseBeginRequest {
244
+ readonly op: 'lease.begin'
245
+ readonly windowId?: string
246
+ readonly raise?: boolean
247
+ readonly idleMs?: number
248
+ readonly ttlMs?: number
249
+ readonly leasePath?: string
250
+ readonly token?: string
251
+ }
252
+
253
+ /** One request as a line, without the trailing newline. */
254
+ export function encodeRequest(id: number, request: NativeRequest): string {
255
+ assertId(id)
256
+ return JSON.stringify({ id, ...request })
257
+ }
258
+
259
+ // --- replies ----------------------------------------------------------------
260
+
261
+ export interface NativeHello {
262
+ readonly version: string
263
+ readonly buildHash: string
264
+ readonly arch: string
265
+ readonly osBuild: string
266
+ readonly signer?: string
267
+ readonly caps: readonly string[]
268
+ readonly dpiAwareness: string
269
+ }
270
+
271
+ /** A control as the helper lists it: the accessibility node plus the ref `act` takes. */
272
+ export interface NativeNode extends A11yNode {
273
+ readonly ref: string
274
+ }
275
+
276
+ export interface NativeSnapshot {
277
+ readonly windowId: string
278
+ readonly revision: number
279
+ readonly nodes: readonly NativeNode[]
280
+ readonly total: number
281
+ readonly truncated: boolean
282
+ readonly skeleton: boolean
283
+ readonly readMs: number
284
+ }
285
+
286
+ export type NativeResolution =
287
+ | {
288
+ readonly found: true
289
+ readonly index: number
290
+ readonly via: 'runtimeId' | 'automationId' | 'name'
291
+ readonly revision: number
292
+ }
293
+ | {
294
+ readonly found: false
295
+ readonly code: 'not_found' | 'ambiguous'
296
+ readonly candidates?: number
297
+ }
298
+
299
+ export type NativeWaitResult =
300
+ | {
301
+ readonly changed: true
302
+ readonly settled: boolean
303
+ readonly firstEventMs: number
304
+ readonly settledMs: number
305
+ readonly events: number
306
+ readonly newWindows: readonly string[]
307
+ }
308
+ | { readonly changed: false; readonly timedOut: true; readonly settledMs: number }
309
+
310
+ export interface NativeActState {
311
+ readonly value?: string
312
+ readonly toggle?: 'on' | 'off' | 'mixed'
313
+ readonly expand?: 'expanded' | 'collapsed' | 'partial' | 'leaf'
314
+ readonly selected?: boolean
315
+ readonly focused?: boolean
316
+ }
317
+
318
+ export interface NativeActReply {
319
+ /** The pattern call went through. */
320
+ readonly done: boolean
321
+ readonly via: 'pattern'
322
+ /** Whether the read-back shows the effect; absent when there is nothing to read. */
323
+ readonly verified?: boolean
324
+ readonly after?: NativeActState
325
+ /** The control's place in the read that found it, and that read's revision. */
326
+ readonly index: number
327
+ readonly revision: number
328
+ }
329
+
330
+ export interface NativeInputReply {
331
+ readonly delivered: number
332
+ readonly via: 'sendinput'
333
+ readonly cursor?: { readonly x: number; readonly y: number }
334
+ }
335
+
336
+ export interface NativeCaptureReply {
337
+ readonly path?: string
338
+ readonly dataBase64?: string
339
+ readonly bytes: number
340
+ readonly width: number
341
+ readonly height: number
342
+ readonly scale: number
343
+ readonly via: 'wgc' | 'printwindow' | 'bitblt'
344
+ readonly sha256: string
345
+ readonly bounds: A11yRect
346
+ readonly display?: string
347
+ }
348
+
349
+ export interface NativeForegroundWindow {
350
+ readonly windowId: string
351
+ readonly processId: number
352
+ readonly exe: string
353
+ readonly elevated: boolean
354
+ /** The integrity level as a RID (0x2000 medium, 0x3000 high); -1 when unreadable. */
355
+ readonly integrity: number
356
+ }
357
+
358
+ export interface NativeForegroundState {
359
+ readonly foreground: NativeForegroundWindow | null
360
+ readonly cursor: { readonly x: number; readonly y: number }
361
+ readonly desktop: string
362
+ readonly selfElevated: boolean
363
+ readonly selfIntegrity: number
364
+ readonly inputTick: number
365
+ readonly userIdleMs: number
366
+ readonly target?: {
367
+ readonly exe: string
368
+ readonly elevated: boolean
369
+ readonly integrity: number
370
+ }
371
+ }
372
+
373
+ export type NativeRaiseHow = 'already' | 'plain' | 'unlock' | 'attach' | 'switch' | 'refused'
374
+
375
+ export interface NativeForegroundSetReply {
376
+ readonly raised: boolean
377
+ readonly changed: boolean
378
+ readonly how: NativeRaiseHow
379
+ readonly blockedBy?: 'windows' | 'elevated'
380
+ }
381
+
382
+ export interface NativeLeaseBeginReply extends NativeForegroundState {
383
+ readonly refused: boolean
384
+ readonly raised?: boolean
385
+ readonly raiseHow?: NativeRaiseHow
386
+ }
387
+
388
+ export interface NativeLeaseEndReply {
389
+ readonly restoredForeground: boolean
390
+ readonly restoredCursor: boolean
391
+ readonly restoreNote?: string
392
+ readonly inputMoved: boolean
393
+ readonly frontElevated: boolean
394
+ readonly released: boolean
395
+ /** A person's input events between begin and end; absent when the monitor was not running throughout. */
396
+ readonly inputsDuring?: number
397
+ }
398
+
399
+ export interface NativeMonitorStartReply {
400
+ /** Raw Input is registered: a person's use of keyboard and mouse is seen. */
401
+ readonly input: boolean
402
+ /** Foreground changes are hooked. */
403
+ readonly foreground: boolean
404
+ }
405
+
406
+ /**
407
+ * One thing that happened. Input carries the device class and a time only,
408
+ * never a key, a character or a position.
409
+ */
410
+ export interface NativeMonitorEvent {
411
+ readonly seq: number
412
+ readonly kind: 'input' | 'foreground'
413
+ /** ms since the monitor started. */
414
+ readonly tMs: number
415
+ readonly device?: 'keyboard' | 'mouse'
416
+ /** The system synthesised the input (SendInput, from this helper or another program). */
417
+ readonly injected?: boolean
418
+ /** For a foreground change: the window that came to the front. */
419
+ readonly windowId?: string
420
+ }
421
+
422
+ export interface NativeMonitorPollReply {
423
+ readonly events: readonly NativeMonitorEvent[]
424
+ readonly seq: number
425
+ /** Events a person's devices produced since the monitor started. */
426
+ readonly inputs: number
427
+ readonly injectedInputs: number
428
+ readonly foregroundChanges: number
429
+ /** ms since a person's last input, when there was one. */
430
+ readonly lastInputAgoMs?: number
431
+ /** `since` was older than the oldest event kept. */
432
+ readonly dropped: boolean
433
+ }
434
+
435
+ export interface NativeWatchStartReply {
436
+ /** UI Automation subscriptions are in place; false: the controls of programs are not watched. */
437
+ readonly controls: boolean
438
+ /** Foreground changes are hooked. */
439
+ readonly foreground: boolean
440
+ /** The kinds being watched. */
441
+ readonly kinds: readonly NativeWatchKind[]
442
+ }
443
+
444
+ /**
445
+ * One thing a person did to a control, or a window that opened or closed.
446
+ * There is no key, no character typed and no mouse button or position in it;
447
+ * `value` is an ordinary edit control's text and is never present for a
448
+ * password field, which says `secure: true` instead.
449
+ */
450
+ export interface NativeWatchEvent {
451
+ readonly kind: NativeWatchKind
452
+ /** Monotonic ms since the watch started. */
453
+ readonly tMs: number
454
+ readonly role?: string
455
+ readonly name?: string
456
+ readonly value?: string
457
+ readonly secure?: boolean
458
+ /** For a menu or a window: which end. */
459
+ readonly phase?: 'open' | 'close'
460
+ /** The title of the window the control is in. */
461
+ readonly window?: string
462
+ /** The program's file name. */
463
+ readonly process?: string
464
+ readonly windowId?: string
465
+ }
466
+
467
+ export interface NativeWatchPollReply {
468
+ /** Events since the last poll, oldest first. */
469
+ readonly events: readonly NativeWatchEvent[]
470
+ /** Events not kept since the last poll because the queue was full. */
471
+ readonly dropped: number
472
+ }
473
+
474
+ export interface NativePresenceActReply {
475
+ readonly cursorWindow: number
476
+ readonly frameWindow: number
477
+ }
478
+
479
+ export interface NativeReplyBodies {
480
+ readonly hello: NativeHello
481
+ readonly windows: { readonly windows: readonly A11yWindow[] }
482
+ readonly displays: { readonly displays: readonly A11yDisplay[] }
483
+ readonly snapshot: NativeSnapshot
484
+ readonly identity: { readonly fingerprint: A11yFingerprint }
485
+ readonly resolve: NativeResolution
486
+ readonly seq: { readonly seq: number }
487
+ readonly wait_change: NativeWaitResult
488
+ readonly act: NativeActReply
489
+ readonly input: NativeInputReply
490
+ readonly capture: NativeCaptureReply
491
+ readonly 'foreground.get': NativeForegroundState
492
+ readonly 'foreground.set': NativeForegroundSetReply
493
+ readonly 'lease.begin': NativeLeaseBeginReply
494
+ readonly 'lease.end': NativeLeaseEndReply
495
+ readonly 'monitor.start': NativeMonitorStartReply
496
+ readonly 'monitor.stop': Record<string, never>
497
+ readonly 'monitor.poll': NativeMonitorPollReply
498
+ readonly 'watch.start': NativeWatchStartReply
499
+ readonly 'watch.stop': Record<string, never>
500
+ readonly 'watch.poll': NativeWatchPollReply
501
+ readonly 'presence.act': NativePresenceActReply
502
+ readonly 'presence.hide': Record<string, never>
503
+ readonly cancel: Record<string, never>
504
+ readonly quit: Record<string, never>
505
+ }
506
+
507
+ export type NativeReply<K extends NativeOp> =
508
+ | { readonly id: number; readonly ok: true; readonly body: NativeReplyBodies[K] }
509
+ | { readonly id: number; readonly ok: false; readonly code: string; readonly message: string }
510
+
511
+ /** A line the helper should not have sent: not JSON, or not the shape the op promises. */
512
+ export class NativeProtocolError extends Error {
513
+ constructor(message: string) {
514
+ super(message)
515
+ this.name = 'NativeProtocolError'
516
+ }
517
+ }
518
+
519
+ type Obj = Record<string, unknown>
520
+
521
+ function bad(path: string, want: string): never {
522
+ throw new NativeProtocolError(`${path} must be ${want}`)
523
+ }
524
+
525
+ function assertId(id: number): void {
526
+ if (!Number.isSafeInteger(id) || id < 0) {
527
+ throw new NativeProtocolError(
528
+ 'id must be a non-negative integer a JavaScript number holds exactly',
529
+ )
530
+ }
531
+ }
532
+
533
+ function obj(v: unknown, path: string): Obj {
534
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) bad(path, 'an object')
535
+ return v as Obj
536
+ }
537
+
538
+ function str(o: Obj, key: string, path: string): string {
539
+ const v = o[key]
540
+ if (typeof v !== 'string') bad(`${path}.${key}`, 'a string')
541
+ return v
542
+ }
543
+
544
+ function optStr(o: Obj, key: string, path: string): string | undefined {
545
+ return o[key] === undefined ? undefined : str(o, key, path)
546
+ }
547
+
548
+ function int(o: Obj, key: string, path: string, min = 0): number {
549
+ const v = o[key]
550
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < min) {
551
+ bad(`${path}.${key}`, `an integer of at least ${min}`)
552
+ }
553
+ return v
554
+ }
555
+
556
+ function optInt(o: Obj, key: string, path: string): number | undefined {
557
+ return o[key] === undefined ? undefined : int(o, key, path)
558
+ }
559
+
560
+ function num(o: Obj, key: string, path: string): number {
561
+ const v = o[key]
562
+ if (typeof v !== 'number' || !Number.isFinite(v)) bad(`${path}.${key}`, 'a number')
563
+ return v
564
+ }
565
+
566
+ function bool(o: Obj, key: string, path: string): boolean {
567
+ const v = o[key]
568
+ if (typeof v !== 'boolean') bad(`${path}.${key}`, 'a boolean')
569
+ return v
570
+ }
571
+
572
+ function optBool(o: Obj, key: string, path: string): boolean | undefined {
573
+ return o[key] === undefined ? undefined : bool(o, key, path)
574
+ }
575
+
576
+ function arr(o: Obj, key: string, path: string): readonly unknown[] {
577
+ const v = o[key]
578
+ if (!Array.isArray(v)) bad(`${path}.${key}`, 'a list')
579
+ return v
580
+ }
581
+
582
+ function oneOf<T extends string>(v: unknown, allowed: readonly T[], path: string): T {
583
+ if (typeof v !== 'string' || !(allowed as readonly string[]).includes(v)) {
584
+ bad(path, `one of ${allowed.join(', ')}`)
585
+ }
586
+ return v as T
587
+ }
588
+
589
+ function rect(o: Obj, key: string, path: string): A11yRect {
590
+ const r = obj(o[key], `${path}.${key}`)
591
+ const p = `${path}.${key}`
592
+ return {
593
+ x: int(r, 'x', p, Number.MIN_SAFE_INTEGER),
594
+ y: int(r, 'y', p, Number.MIN_SAFE_INTEGER),
595
+ width: int(r, 'width', p, Number.MIN_SAFE_INTEGER),
596
+ height: int(r, 'height', p, Number.MIN_SAFE_INTEGER),
597
+ }
598
+ }
599
+
600
+ const ACTIONS: readonly A11yAction[] = [
601
+ 'invoke',
602
+ 'value',
603
+ 'toggle',
604
+ 'expandCollapse',
605
+ 'selectionItem',
606
+ 'scroll',
607
+ ]
608
+
609
+ function node(v: unknown, path: string): NativeNode {
610
+ const o = obj(v, path)
611
+ const out: { -readonly [K in keyof NativeNode]: NativeNode[K] } = {
612
+ index: int(o, 'index', path),
613
+ ref: str(o, 'ref', path),
614
+ parent: int(o, 'parent', path, -1),
615
+ depth: int(o, 'depth', path),
616
+ role: str(o, 'role', path),
617
+ bounds: rect(o, 'bounds', path),
618
+ enabled: bool(o, 'enabled', path),
619
+ offscreen: bool(o, 'offscreen', path),
620
+ focused: bool(o, 'focused', path),
621
+ actions: arr(o, 'actions', path).map((a, i) => oneOf(a, ACTIONS, `${path}.actions[${i}]`)),
622
+ }
623
+ const name = optStr(o, 'name', path)
624
+ if (name !== undefined) out.name = name
625
+ const automationId = optStr(o, 'automationId', path)
626
+ if (automationId !== undefined) out.automationId = automationId
627
+ const className = optStr(o, 'className', path)
628
+ if (className !== undefined) out.className = className
629
+ const value = optStr(o, 'value', path)
630
+ if (value !== undefined) out.value = value
631
+ if (o.toggle !== undefined)
632
+ out.toggle = oneOf<'on' | 'off' | 'mixed'>(o.toggle, ['on', 'off', 'mixed'], `${path}.toggle`)
633
+ if (o.expand !== undefined) {
634
+ out.expand = oneOf<'expanded' | 'collapsed' | 'partial' | 'leaf'>(
635
+ o.expand,
636
+ ['expanded', 'collapsed', 'partial', 'leaf'],
637
+ `${path}.expand`,
638
+ )
639
+ }
640
+ const selected = optBool(o, 'selected', path)
641
+ if (selected !== undefined) out.selected = selected
642
+ const childCount = optInt(o, 'childCount', path)
643
+ if (childCount !== undefined) out.childCount = childCount
644
+ return out
645
+ }
646
+
647
+ function window(v: unknown, path: string): A11yWindow {
648
+ const o = obj(v, path)
649
+ return {
650
+ windowId: str(o, 'windowId', path),
651
+ processId: int(o, 'processId', path),
652
+ processName: str(o, 'processName', path),
653
+ title: str(o, 'title', path),
654
+ bounds: rect(o, 'bounds', path),
655
+ minimized: bool(o, 'minimized', path),
656
+ focused: bool(o, 'focused', path),
657
+ z: int(o, 'z', path),
658
+ }
659
+ }
660
+
661
+ function display(v: unknown, path: string): A11yDisplay {
662
+ const o = obj(v, path)
663
+ return {
664
+ id: str(o, 'id', path),
665
+ bounds: rect(o, 'bounds', path),
666
+ workArea: rect(o, 'workArea', path),
667
+ scale: num(o, 'scale', path),
668
+ primary: bool(o, 'primary', path),
669
+ }
670
+ }
671
+
672
+ function hello(o: Obj): NativeHello {
673
+ const out: { -readonly [K in keyof NativeHello]: NativeHello[K] } = {
674
+ version: str(o, 'version', 'hello'),
675
+ buildHash: str(o, 'buildHash', 'hello'),
676
+ arch: str(o, 'arch', 'hello'),
677
+ osBuild: str(o, 'osBuild', 'hello'),
678
+ caps: arr(o, 'caps', 'hello').map((c, i) => {
679
+ if (typeof c !== 'string') bad(`hello.caps[${i}]`, 'a string')
680
+ return c
681
+ }),
682
+ dpiAwareness: str(o, 'dpiAwareness', 'hello'),
683
+ }
684
+ const signer = optStr(o, 'signer', 'hello')
685
+ if (signer !== undefined) out.signer = signer
686
+ return out
687
+ }
688
+
689
+ function snapshot(o: Obj): NativeSnapshot {
690
+ return {
691
+ windowId: str(o, 'windowId', 'snapshot'),
692
+ revision: int(o, 'revision', 'snapshot'),
693
+ nodes: arr(o, 'nodes', 'snapshot').map((n, i) => node(n, `snapshot.nodes[${i}]`)),
694
+ total: int(o, 'total', 'snapshot'),
695
+ truncated: bool(o, 'truncated', 'snapshot'),
696
+ skeleton: bool(o, 'skeleton', 'snapshot'),
697
+ readMs: num(o, 'readMs', 'snapshot'),
698
+ }
699
+ }
700
+
701
+ function fingerprint(v: unknown, path: string): A11yFingerprint {
702
+ const o = obj(v, path)
703
+ return {
704
+ runtimeId: str(o, 'runtimeId', path),
705
+ automationId: str(o, 'automationId', path),
706
+ role: str(o, 'role', path),
707
+ nameHash: str(o, 'nameHash', path),
708
+ parentPath: str(o, 'parentPath', path),
709
+ ordinal: int(o, 'ordinal', path),
710
+ processStart: int(o, 'processStart', path),
711
+ }
712
+ }
713
+
714
+ function resolution(o: Obj): NativeResolution {
715
+ if (bool(o, 'found', 'resolve')) {
716
+ return {
717
+ found: true,
718
+ index: int(o, 'index', 'resolve'),
719
+ via: oneOf(o.via, ['runtimeId', 'automationId', 'name'], 'resolve.via'),
720
+ revision: int(o, 'revision', 'resolve'),
721
+ }
722
+ }
723
+ const code = oneOf(o.code, ['not_found', 'ambiguous'], 'resolve.code')
724
+ const candidates = optInt(o, 'candidates', 'resolve')
725
+ return candidates === undefined ? { found: false, code } : { found: false, code, candidates }
726
+ }
727
+
728
+ function waitResult(o: Obj): NativeWaitResult {
729
+ if (bool(o, 'changed', 'wait_change')) {
730
+ return {
731
+ changed: true,
732
+ settled: bool(o, 'settled', 'wait_change'),
733
+ firstEventMs: int(o, 'firstEventMs', 'wait_change', Number.MIN_SAFE_INTEGER),
734
+ settledMs: int(o, 'settledMs', 'wait_change'),
735
+ events: int(o, 'events', 'wait_change'),
736
+ newWindows: arr(o, 'newWindows', 'wait_change').map((w, i) => {
737
+ if (typeof w !== 'string') bad(`wait_change.newWindows[${i}]`, 'a string')
738
+ return w
739
+ }),
740
+ }
741
+ }
742
+ if (o.timedOut !== true) bad('wait_change.timedOut', 'true when nothing changed')
743
+ return { changed: false, timedOut: true, settledMs: int(o, 'settledMs', 'wait_change') }
744
+ }
745
+
746
+ function point(v: unknown, path: string): { x: number; y: number } {
747
+ const o = obj(v, path)
748
+ return {
749
+ x: int(o, 'x', path, Number.MIN_SAFE_INTEGER),
750
+ y: int(o, 'y', path, Number.MIN_SAFE_INTEGER),
751
+ }
752
+ }
753
+
754
+ const RAISE_HOW: readonly NativeRaiseHow[] = [
755
+ 'already',
756
+ 'plain',
757
+ 'unlock',
758
+ 'attach',
759
+ 'switch',
760
+ 'refused',
761
+ ]
762
+
763
+ function actState(v: unknown, path: string): NativeActState {
764
+ const o = obj(v, path)
765
+ const out: { -readonly [K in keyof NativeActState]: NativeActState[K] } = {}
766
+ const value = optStr(o, 'value', path)
767
+ if (value !== undefined) out.value = value
768
+ if (o.toggle !== undefined)
769
+ out.toggle = oneOf<'on' | 'off' | 'mixed'>(o.toggle, ['on', 'off', 'mixed'], `${path}.toggle`)
770
+ if (o.expand !== undefined) {
771
+ out.expand = oneOf<'expanded' | 'collapsed' | 'partial' | 'leaf'>(
772
+ o.expand,
773
+ ['expanded', 'collapsed', 'partial', 'leaf'],
774
+ `${path}.expand`,
775
+ )
776
+ }
777
+ const selected = optBool(o, 'selected', path)
778
+ if (selected !== undefined) out.selected = selected
779
+ const focused = optBool(o, 'focused', path)
780
+ if (focused !== undefined) out.focused = focused
781
+ return out
782
+ }
783
+
784
+ function actReply(o: Obj): NativeActReply {
785
+ const out: { -readonly [K in keyof NativeActReply]: NativeActReply[K] } = {
786
+ done: bool(o, 'done', 'act'),
787
+ via: oneOf<'pattern'>(o.via, ['pattern'], 'act.via'),
788
+ index: int(o, 'index', 'act'),
789
+ revision: int(o, 'revision', 'act'),
790
+ }
791
+ const verified = optBool(o, 'verified', 'act')
792
+ if (verified !== undefined) out.verified = verified
793
+ if (o.after !== undefined) out.after = actState(o.after, 'act.after')
794
+ return out
795
+ }
796
+
797
+ function inputReply(o: Obj): NativeInputReply {
798
+ const out: { -readonly [K in keyof NativeInputReply]: NativeInputReply[K] } = {
799
+ delivered: int(o, 'delivered', 'input'),
800
+ via: oneOf<'sendinput'>(o.via, ['sendinput'], 'input.via'),
801
+ }
802
+ if (o.cursor !== undefined) out.cursor = point(o.cursor, 'input.cursor')
803
+ return out
804
+ }
805
+
806
+ function captureReply(o: Obj): NativeCaptureReply {
807
+ const out: { -readonly [K in keyof NativeCaptureReply]: NativeCaptureReply[K] } = {
808
+ bytes: int(o, 'bytes', 'capture'),
809
+ width: int(o, 'width', 'capture'),
810
+ height: int(o, 'height', 'capture'),
811
+ scale: num(o, 'scale', 'capture'),
812
+ via: oneOf<'wgc' | 'printwindow' | 'bitblt'>(
813
+ o.via,
814
+ ['wgc', 'printwindow', 'bitblt'],
815
+ 'capture.via',
816
+ ),
817
+ sha256: str(o, 'sha256', 'capture'),
818
+ bounds: rect(o, 'bounds', 'capture'),
819
+ }
820
+ const path = optStr(o, 'path', 'capture')
821
+ if (path !== undefined) out.path = path
822
+ const data = optStr(o, 'dataBase64', 'capture')
823
+ if (data !== undefined) out.dataBase64 = data
824
+ const display = optStr(o, 'display', 'capture')
825
+ if (display !== undefined) out.display = display
826
+ return out
827
+ }
828
+
829
+ function foregroundState(o: Obj, path: string): NativeForegroundState {
830
+ let foreground: NativeForegroundWindow | null = null
831
+ if (o.foreground === undefined) bad(`${path}.foreground`, 'a window or null')
832
+ if (o.foreground !== null) {
833
+ const f = obj(o.foreground, `${path}.foreground`)
834
+ const p = `${path}.foreground`
835
+ foreground = {
836
+ windowId: str(f, 'windowId', p),
837
+ processId: int(f, 'processId', p),
838
+ exe: str(f, 'exe', p),
839
+ elevated: bool(f, 'elevated', p),
840
+ integrity: int(f, 'integrity', p, -1),
841
+ }
842
+ }
843
+ const out: { -readonly [K in keyof NativeForegroundState]: NativeForegroundState[K] } = {
844
+ foreground,
845
+ cursor: point(o.cursor, `${path}.cursor`),
846
+ desktop: str(o, 'desktop', path),
847
+ selfElevated: bool(o, 'selfElevated', path),
848
+ selfIntegrity: int(o, 'selfIntegrity', path, -1),
849
+ inputTick: int(o, 'inputTick', path),
850
+ userIdleMs: int(o, 'userIdleMs', path),
851
+ }
852
+ if (o.target !== undefined) {
853
+ const t = obj(o.target, `${path}.target`)
854
+ out.target = {
855
+ exe: str(t, 'exe', `${path}.target`),
856
+ elevated: bool(t, 'elevated', `${path}.target`),
857
+ integrity: int(t, 'integrity', `${path}.target`, -1),
858
+ }
859
+ }
860
+ return out
861
+ }
862
+
863
+ function foregroundSet(o: Obj): NativeForegroundSetReply {
864
+ const out: { -readonly [K in keyof NativeForegroundSetReply]: NativeForegroundSetReply[K] } = {
865
+ raised: bool(o, 'raised', 'foreground.set'),
866
+ changed: bool(o, 'changed', 'foreground.set'),
867
+ how: oneOf(o.how, RAISE_HOW, 'foreground.set.how'),
868
+ }
869
+ if (o.blockedBy !== undefined)
870
+ out.blockedBy = oneOf<'windows' | 'elevated'>(
871
+ o.blockedBy,
872
+ ['windows', 'elevated'],
873
+ 'foreground.set.blockedBy',
874
+ )
875
+ return out
876
+ }
877
+
878
+ function leaseBegin(o: Obj): NativeLeaseBeginReply {
879
+ const out: { -readonly [K in keyof NativeLeaseBeginReply]: NativeLeaseBeginReply[K] } = {
880
+ ...foregroundState(o, 'lease.begin'),
881
+ refused: bool(o, 'refused', 'lease.begin'),
882
+ }
883
+ const raised = optBool(o, 'raised', 'lease.begin')
884
+ if (raised !== undefined) out.raised = raised
885
+ if (o.raiseHow !== undefined) out.raiseHow = oneOf(o.raiseHow, RAISE_HOW, 'lease.begin.raiseHow')
886
+ return out
887
+ }
888
+
889
+ function leaseEnd(o: Obj): NativeLeaseEndReply {
890
+ const out: { -readonly [K in keyof NativeLeaseEndReply]: NativeLeaseEndReply[K] } = {
891
+ restoredForeground: bool(o, 'restoredForeground', 'lease.end'),
892
+ restoredCursor: bool(o, 'restoredCursor', 'lease.end'),
893
+ inputMoved: bool(o, 'inputMoved', 'lease.end'),
894
+ frontElevated: bool(o, 'frontElevated', 'lease.end'),
895
+ released: bool(o, 'released', 'lease.end'),
896
+ }
897
+ const note = optStr(o, 'restoreNote', 'lease.end')
898
+ if (note !== undefined) out.restoreNote = note
899
+ const during = optInt(o, 'inputsDuring', 'lease.end')
900
+ if (during !== undefined) out.inputsDuring = during
901
+ return out
902
+ }
903
+
904
+ function monitorEvent(v: unknown, path: string): NativeMonitorEvent {
905
+ const o = obj(v, path)
906
+ const out: { -readonly [K in keyof NativeMonitorEvent]: NativeMonitorEvent[K] } = {
907
+ seq: int(o, 'seq', path),
908
+ kind: oneOf<'input' | 'foreground'>(o.kind, ['input', 'foreground'], `${path}.kind`),
909
+ tMs: int(o, 'tMs', path),
910
+ }
911
+ if (o.device !== undefined)
912
+ out.device = oneOf<'keyboard' | 'mouse'>(o.device, ['keyboard', 'mouse'], `${path}.device`)
913
+ const injected = optBool(o, 'injected', path)
914
+ if (injected !== undefined) out.injected = injected
915
+ const windowId = optStr(o, 'windowId', path)
916
+ if (windowId !== undefined) out.windowId = windowId
917
+ return out
918
+ }
919
+
920
+ function monitorPoll(o: Obj): NativeMonitorPollReply {
921
+ const out: { -readonly [K in keyof NativeMonitorPollReply]: NativeMonitorPollReply[K] } = {
922
+ events: arr(o, 'events', 'monitor.poll').map((e, i) =>
923
+ monitorEvent(e, `monitor.poll.events[${i}]`),
924
+ ),
925
+ seq: int(o, 'seq', 'monitor.poll'),
926
+ inputs: int(o, 'inputs', 'monitor.poll'),
927
+ injectedInputs: int(o, 'injectedInputs', 'monitor.poll'),
928
+ foregroundChanges: int(o, 'foregroundChanges', 'monitor.poll'),
929
+ dropped: bool(o, 'dropped', 'monitor.poll'),
930
+ }
931
+ const ago = optInt(o, 'lastInputAgoMs', 'monitor.poll')
932
+ if (ago !== undefined) out.lastInputAgoMs = ago
933
+ return out
934
+ }
935
+
936
+ function watchKind(v: unknown, path: string): NativeWatchKind {
937
+ return oneOf(v, NATIVE_WATCH_KINDS, path)
938
+ }
939
+
940
+ function watchEvent(v: unknown, path: string): NativeWatchEvent {
941
+ const o = obj(v, path)
942
+ const out: { -readonly [K in keyof NativeWatchEvent]: NativeWatchEvent[K] } = {
943
+ kind: watchKind(o.kind, `${path}.kind`),
944
+ tMs: int(o, 'tMs', path),
945
+ }
946
+ for (const key of ['role', 'name', 'value', 'window', 'process', 'windowId'] as const) {
947
+ const text = optStr(o, key, path)
948
+ if (text !== undefined) out[key] = text
949
+ }
950
+ const secure = optBool(o, 'secure', path)
951
+ if (secure !== undefined) out.secure = secure
952
+ if (o.phase !== undefined) out.phase = oneOf(o.phase, ['open', 'close'] as const, `${path}.phase`)
953
+ const cap = (key: 'name' | 'value' | 'window' | 'process', max: number) => {
954
+ const t = out[key]
955
+ if (t !== undefined && [...t].length > max) bad(`${path}.${key}`, `at most ${max} characters`)
956
+ }
957
+ cap('name', 80)
958
+ cap('value', 200)
959
+ cap('window', 120)
960
+ cap('process', 80)
961
+ if (out.value !== undefined && out.kind !== 'value')
962
+ bad(`${path}.value`, 'present only on value events')
963
+ if (out.phase !== undefined && out.kind !== 'menu' && out.kind !== 'window')
964
+ bad(`${path}.phase`, 'present only on menu and window events')
965
+ // A password field never carries its text, whatever a helper sent.
966
+ if (out.secure === true && out.value !== undefined)
967
+ bad(`${path}.value`, 'absent for a secure field')
968
+ return out
969
+ }
970
+
971
+ function body(op: NativeOp, o: Obj): NativeReplyBodies[NativeOp] {
972
+ switch (op) {
973
+ case 'hello':
974
+ return hello(o)
975
+ case 'windows':
976
+ return { windows: arr(o, 'windows', 'windows').map((w, i) => window(w, `windows[${i}]`)) }
977
+ case 'displays':
978
+ return {
979
+ displays: arr(o, 'displays', 'displays').map((d, i) => display(d, `displays[${i}]`)),
980
+ }
981
+ case 'snapshot':
982
+ return snapshot(o)
983
+ case 'identity':
984
+ return { fingerprint: fingerprint(o.fingerprint, 'identity.fingerprint') }
985
+ case 'resolve':
986
+ return resolution(o)
987
+ case 'seq':
988
+ return { seq: int(o, 'seq', 'seq') }
989
+ case 'wait_change':
990
+ return waitResult(o)
991
+ case 'act':
992
+ return actReply(o)
993
+ case 'input':
994
+ return inputReply(o)
995
+ case 'capture':
996
+ return captureReply(o)
997
+ case 'foreground.get':
998
+ return foregroundState(o, 'foreground.get')
999
+ case 'foreground.set':
1000
+ return foregroundSet(o)
1001
+ case 'lease.begin':
1002
+ return leaseBegin(o)
1003
+ case 'lease.end':
1004
+ return leaseEnd(o)
1005
+ case 'monitor.start':
1006
+ return {
1007
+ input: bool(o, 'input', 'monitor.start'),
1008
+ foreground: bool(o, 'foreground', 'monitor.start'),
1009
+ }
1010
+ case 'monitor.poll':
1011
+ return monitorPoll(o)
1012
+ case 'watch.start': {
1013
+ const kinds = arr(o, 'kinds', 'watch.start').map((k, i) =>
1014
+ watchKind(k, `watch.start.kinds[${i}]`),
1015
+ )
1016
+ if (kinds.length === 0) bad('watch.start.kinds', 'not empty')
1017
+ return {
1018
+ controls: bool(o, 'controls', 'watch.start'),
1019
+ foreground: bool(o, 'foreground', 'watch.start'),
1020
+ kinds,
1021
+ }
1022
+ }
1023
+ case 'watch.poll': {
1024
+ const events = arr(o, 'events', 'watch.poll')
1025
+ if (events.length > 2000) bad('watch.poll.events', 'at most 2000 events')
1026
+ return {
1027
+ events: events.map((e, i) => watchEvent(e, `watch.poll.events[${i}]`)),
1028
+ dropped: int(o, 'dropped', 'watch.poll'),
1029
+ }
1030
+ }
1031
+ case 'presence.act':
1032
+ return {
1033
+ cursorWindow: int(o, 'cursorWindow', 'presence.act'),
1034
+ frameWindow: int(o, 'frameWindow', 'presence.act'),
1035
+ }
1036
+ case 'monitor.stop':
1037
+ case 'watch.stop':
1038
+ case 'presence.hide':
1039
+ case 'cancel':
1040
+ case 'quit':
1041
+ return {}
1042
+ }
1043
+ }
1044
+
1045
+ /**
1046
+ * Reads the reply to a request of kind `op`. Throws {@link NativeProtocolError}
1047
+ * for a line that is not a reply; a reply that says the request failed is a
1048
+ * value (`ok: false`), not a throw.
1049
+ */
1050
+ export function decodeReply<K extends NativeOp>(op: K, line: string): NativeReply<K> {
1051
+ let parsed: unknown
1052
+ try {
1053
+ parsed = JSON.parse(line)
1054
+ } catch {
1055
+ throw new NativeProtocolError('a reply is one JSON object per line')
1056
+ }
1057
+ const o = obj(parsed, 'reply')
1058
+ const id = int(o, 'id', 'reply')
1059
+ if (typeof o.ok !== 'boolean') bad('reply.ok', 'a boolean')
1060
+ if (!o.ok) {
1061
+ return { id, ok: false, code: str(o, 'code', 'reply'), message: str(o, 'message', 'reply') }
1062
+ }
1063
+ return { id, ok: true, body: body(op, o) as NativeReplyBodies[K] }
1064
+ }
1065
+
1066
+ // --- refs -------------------------------------------------------------------
1067
+
1068
+ /** A ref names control `index` of read `revision`: `r<revision>.<index>`. */
1069
+ export function formatRef(revision: number, index: number): string {
1070
+ return `r${revision}.${index}`
1071
+ }
1072
+
1073
+ const MAX_INDEX = 0xffff_ffff
1074
+
1075
+ function plainNumber(s: string, max: number): number | undefined {
1076
+ if (!/^(0|[1-9][0-9]*)$/.test(s)) return undefined
1077
+ const n = Number(s)
1078
+ return Number.isSafeInteger(n) && n <= max ? n : undefined
1079
+ }
1080
+
1081
+ /** The pair a ref names, or `undefined` for a string that is not exactly one. */
1082
+ export function parseRef(ref: string): { revision: number; index: number } | undefined {
1083
+ const m = /^r([0-9]+)\.([0-9]+)$/.exec(ref)
1084
+ if (!m) return undefined
1085
+ const revision = plainNumber(m[1] ?? '', MAX_SAFE_ID)
1086
+ const index = plainNumber(m[2] ?? '', MAX_INDEX)
1087
+ return revision === undefined || index === undefined ? undefined : { revision, index }
1088
+ }
1089
+
1090
+ // --- fingerprints -----------------------------------------------------------
1091
+
1092
+ /**
1093
+ * FNV-1a 32 over the UTF-16 code units of `s`, eight lowercase hex digits:
1094
+ * the `nameHash` of a fingerprint, the same as the PowerShell helper wrote.
1095
+ */
1096
+ export function nameHash(s: string): string {
1097
+ let h = 2166136261
1098
+ for (let i = 0; i < s.length; i++) {
1099
+ h ^= s.charCodeAt(i)
1100
+ h = Math.imul(h, 16777619) >>> 0
1101
+ }
1102
+ return h.toString(16).padStart(8, '0')
1103
+ }