@bun-native/core 0.0.0-bootstrap.0 → 0.33.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.
@@ -0,0 +1,218 @@
1
+ import {
2
+ MAX_PROCESS_ARGS,
3
+ MAX_PROCESS_ENV,
4
+ parseProcessLaunch,
5
+ PROCESS_SIGNALS,
6
+ type ProcessExit,
7
+ type ProcessLaunch,
8
+ type ProcessSignal,
9
+ type ProcessStream,
10
+ type TerminalSize,
11
+ } from '@bun-native/protocol'
12
+ import type { NativeFileGrant } from './files.ts'
13
+ import type { Listener } from './types.ts'
14
+
15
+ export interface ProcessOptions {
16
+ /** Explicit argument vector after the executable; never parsed by a shell. */
17
+ readonly args?: readonly string[]
18
+ /** The complete environment. Nothing is inherited from the native host. */
19
+ readonly env?: Readonly<Record<string, string>>
20
+ /** A directory inside a live grant owned by the same window. */
21
+ readonly cwd?: Readonly<{ grant: NativeFileGrant; path?: string }>
22
+ /** One pseudo-terminal for all three standard streams instead of pipes. */
23
+ readonly terminal?: Readonly<TerminalSize>
24
+ }
25
+
26
+ export type NativeProcessExit = Readonly<ProcessExit>
27
+
28
+ export type ProcessEvent =
29
+ | Readonly<{
30
+ type: 'process_output'
31
+ sequence: number
32
+ process: NativeProcess
33
+ /** `terminal` for a pseudo-terminal process; otherwise `stdout` or `stderr`. */
34
+ stream: ProcessStream
35
+ /** At most 16384 bytes. The next chunk is not delivered until this callback settles. */
36
+ bytes: Uint8Array
37
+ signal: AbortSignal
38
+ }>
39
+ | Readonly<{
40
+ type: 'process_exited'
41
+ sequence: number
42
+ process: NativeProcess
43
+ /** The direct child's status. Its process group was stopped and all output delivered. */
44
+ exit: NativeProcessExit
45
+ signal: AbortSignal
46
+ }>
47
+
48
+ /**
49
+ * One child process started from a launch-policy executable. It belongs to
50
+ * its window: closing the window or the application stops its process group.
51
+ */
52
+ export interface NativeProcess {
53
+ readonly executable: string
54
+ readonly terminal: boolean
55
+ /** False once released or revoked. An exited process stays active until released. */
56
+ readonly active: boolean
57
+ /** Undefined until the exit event has been delivered. */
58
+ readonly exit: NativeProcessExit | undefined
59
+ /** Writes at most 16384 bytes to standard input or the terminal. */
60
+ write(bytes: Uint8Array): Promise<void>
61
+ /** Closes standard input; on a terminal, sends end-of-file. */
62
+ closeInput(): Promise<void>
63
+ resize(size: TerminalSize): Promise<void>
64
+ /** Signals the whole process group. */
65
+ signal(signal: ProcessSignal): Promise<void>
66
+ /** Idempotent. Stops delivery, kills the process group and reaps it. */
67
+ release(): Promise<void>
68
+ }
69
+
70
+ export type ProcessCall =
71
+ | { type: 'write_process'; data: string }
72
+ | { type: 'close_process_input' }
73
+ | { type: 'resize_process'; size: TerminalSize }
74
+ | { type: 'signal_process'; signal: ProcessSignal }
75
+
76
+ const OPTION_KEYS = ['args', 'env', 'cwd', 'terminal']
77
+
78
+ /** Validates everything but the grant, which the window resolves. */
79
+ export function processRequest(
80
+ executable: unknown,
81
+ options: ProcessOptions
82
+ ): { launch: Omit<ProcessLaunch, 'cwd'>; cwd?: { grant: NativeFileGrant; path: string } } {
83
+ if (!options || typeof options !== 'object' || Array.isArray(options))
84
+ throw new TypeError('Process options must be an object')
85
+ if (Object.keys(options).some((key) => !OPTION_KEYS.includes(key)))
86
+ throw new TypeError('Unknown process option')
87
+ const { args = [], env = {}, cwd, terminal } = options
88
+ if (!Array.isArray(args) || args.length > MAX_PROCESS_ARGS)
89
+ throw new TypeError('Process args must be an array of at most ' + MAX_PROCESS_ARGS + ' strings')
90
+ if (!env || typeof env !== 'object' || Array.isArray(env))
91
+ throw new TypeError('Process env must be an object of strings')
92
+ if (Object.keys(env).length > MAX_PROCESS_ENV)
93
+ throw new TypeError('At most ' + MAX_PROCESS_ENV + ' environment variables may be set')
94
+ let directory: { grant: NativeFileGrant; path: string } | undefined
95
+ if (cwd !== undefined) {
96
+ if (
97
+ !cwd ||
98
+ typeof cwd !== 'object' ||
99
+ Object.keys(cwd).some((key) => key !== 'grant' && key !== 'path')
100
+ )
101
+ throw new TypeError('Process cwd must be { grant, path? }')
102
+ directory = { grant: cwd.grant, path: cwd.path ?? '' }
103
+ }
104
+ try {
105
+ const launch = parseProcessLaunch({
106
+ executable,
107
+ args: [...args],
108
+ env: { ...env },
109
+ ...(directory ? { cwd: { grant_id: 1, path: directory.path } } : {}),
110
+ ...(terminal === undefined ? {} : { terminal: { ...terminal } }),
111
+ })
112
+ delete launch.cwd
113
+ return directory ? { launch, cwd: directory } : { launch }
114
+ } catch (error) {
115
+ throw new TypeError((error as Error).message)
116
+ }
117
+ }
118
+
119
+ function processCall(name: string, value: unknown): ProcessCall {
120
+ switch (name) {
121
+ case 'write':
122
+ if (!(value instanceof Uint8Array)) throw new TypeError('Process input must be a Uint8Array')
123
+ if (value.byteLength === 0 || value.byteLength > 16_384)
124
+ throw new TypeError('Process input must be 1 to 16384 bytes; write in chunks')
125
+ return { type: 'write_process', data: value.toBase64() }
126
+ case 'resize': {
127
+ const size = value as TerminalSize
128
+ if (
129
+ !size ||
130
+ typeof size !== 'object' ||
131
+ Object.keys(size).some((key) => key !== 'columns' && key !== 'rows') ||
132
+ ![size.columns, size.rows].every(
133
+ (item) => Number.isInteger(item) && item >= 1 && item <= 1_000
134
+ )
135
+ )
136
+ throw new TypeError('Terminal size must be { columns, rows } between 1 and 1000')
137
+ return { type: 'resize_process', size: { columns: size.columns, rows: size.rows } }
138
+ }
139
+ case 'signal':
140
+ if (!PROCESS_SIGNALS.includes(value as ProcessSignal))
141
+ throw new TypeError('Process signal must be one of ' + PROCESS_SIGNALS.join(', '))
142
+ return { type: 'signal_process', signal: value as ProcessSignal }
143
+ default:
144
+ return { type: 'close_process_input' }
145
+ }
146
+ }
147
+
148
+ /** Internal registry entry. Consumers only receive its frozen handle. */
149
+ export class ProcessRegistration {
150
+ readonly handle: NativeProcess
151
+ readonly controller = new AbortController()
152
+ listener: Listener<ProcessEvent> | undefined
153
+ exit: NativeProcessExit | undefined
154
+ /** The highest output chunk received from the host. */
155
+ chunk = 0
156
+ private revoked = false
157
+ private exited = false
158
+ private releasing: Promise<void> | undefined
159
+
160
+ constructor(
161
+ readonly id: number,
162
+ readonly windowId: number,
163
+ executable: string,
164
+ terminal: boolean,
165
+ listener: Listener<ProcessEvent>,
166
+ call: (registration: ProcessRegistration, request: ProcessCall) => Promise<void>,
167
+ release: (registration: ProcessRegistration) => Promise<void>
168
+ ) {
169
+ this.listener = listener
170
+ const run = (name: string, value?: unknown) => {
171
+ try {
172
+ return call(this, processCall(name, value))
173
+ } catch (error) {
174
+ return Promise.reject(error)
175
+ }
176
+ }
177
+ const live = () => this.live
178
+ const exit = () => this.exit
179
+ this.handle = Object.freeze({
180
+ executable,
181
+ terminal,
182
+ get active() {
183
+ return live()
184
+ },
185
+ get exit() {
186
+ return exit()
187
+ },
188
+ write: (bytes: Uint8Array) => run('write', bytes),
189
+ closeInput: () => run('close'),
190
+ resize: (size: TerminalSize) => run('resize', size),
191
+ signal: (signal: ProcessSignal) => run('signal', signal),
192
+ release: () => {
193
+ this.releasing ??= this.revoked ? Promise.resolve() : release(this)
194
+ return this.releasing
195
+ },
196
+ })
197
+ }
198
+
199
+ get live(): boolean {
200
+ return !this.revoked
201
+ }
202
+
203
+ /** True after the host reported the exit; no further output follows. */
204
+ get ended(): boolean {
205
+ return this.exited
206
+ }
207
+
208
+ end(): void {
209
+ this.exited = true
210
+ }
211
+
212
+ /** Synchronous local revocation; the native group is stopped separately. */
213
+ revoke(): void {
214
+ this.revoked = true
215
+ this.listener = undefined
216
+ this.controller.abort()
217
+ }
218
+ }
@@ -0,0 +1,428 @@
1
+ import {
2
+ ProtocolError,
3
+ type Capability,
4
+ type ClipboardText,
5
+ type DisplaySnapshot,
6
+ type ServicePolicy,
7
+ } from '@bun-native/protocol'
8
+
9
+ export type NativeClipboardText = Readonly<ClipboardText>
10
+ type ServiceName =
11
+ | 'window_display'
12
+ | 'clipboard_read'
13
+ | 'clipboard_write'
14
+ | 'global_shortcuts'
15
+ | 'notifications'
16
+ | 'filesystem_grants'
17
+ | 'processes'
18
+ | 'file_dialogs'
19
+ | 'message_dialogs'
20
+ | 'context_menus'
21
+ | 'drag_drop'
22
+ | 'app_menu'
23
+
24
+ export type ServicePermissions = NonNullable<
25
+ import('@bun-native/runtime').HostOptions['permissions']
26
+ >
27
+
28
+ export interface ServiceRequestOptions {
29
+ /** Cancels queued dispatch or delivery of an already-dispatched, bounded native read. */
30
+ readonly signal?: AbortSignal
31
+ }
32
+
33
+ export interface NativeDisplaySnapshot {
34
+ /** GPUI-reported logical display bounds; coordinate origins depend on the backend. */
35
+ readonly bounds: Readonly<{ x: number; y: number; width: number; height: number }>
36
+ readonly scaleFactor: number
37
+ /**
38
+ * The display's work area (excluding the menu bar, Dock or taskbar), in the
39
+ * same logical coordinates as `bounds`. Only when `windowDisplay.details`
40
+ * is available (macOS and Windows).
41
+ */
42
+ readonly visibleBounds?: Readonly<{ x: number; y: number; width: number; height: number }>
43
+ /**
44
+ * The platform's display identifier when `windowDisplay.identity` is
45
+ * available and the platform reports one. macOS: the CoreGraphics display
46
+ * UUID. Windows: derived from the GDI device name (for example
47
+ * `\\.\DISPLAY1`), so it names an adapter output rather than a physical
48
+ * monitor. Linux Wayland: derived from the compositor's output name (for
49
+ * example `DP-1`, `wl_output` version 4), so it names a connector.
50
+ */
51
+ readonly displayId?: string
52
+ }
53
+
54
+ export interface DisplayChangeEvent {
55
+ readonly type: 'display_change'
56
+ readonly sequence: number
57
+ /** The window's display after the change. */
58
+ readonly snapshot: NativeDisplaySnapshot
59
+ /** Aborted when the listener is removed, its window closes or the app stops. */
60
+ readonly signal: AbortSignal
61
+ }
62
+
63
+ export interface ServiceCapabilities {
64
+ readonly windowDisplay: Readonly<{
65
+ availability: 'available'
66
+ permission: 'allow' | 'deny'
67
+ scope: 'owned_window'
68
+ /** Snapshots include `visibleBounds`, the display's work area. */
69
+ details: 'available' | 'unavailable'
70
+ /** Snapshots include `displayId` when the platform names the display. */
71
+ identity: 'available' | 'unavailable'
72
+ /** `onDisplayChange` reports display moves and OS display reconfiguration. */
73
+ changes: 'available' | 'unavailable'
74
+ }>
75
+ readonly clipboardText:
76
+ | Readonly<{
77
+ availability: 'available'
78
+ read: 'allow' | 'deny'
79
+ write: 'allow' | 'deny'
80
+ scope: 'owned_window'
81
+ /** X11 selections on Linux; the general pasteboard's plain text on macOS. */
82
+ backend: 'x11' | 'appkit'
83
+ }>
84
+ | Readonly<{ availability: 'unavailable'; reason: 'unsupported_platform' }>
85
+ readonly globalShortcuts:
86
+ | Readonly<{
87
+ availability: 'available'
88
+ permission: 'allow' | 'deny'
89
+ scope: 'owned_window'
90
+ /** X11 passive key grabs on Linux; exclusive Carbon hot keys on macOS. */
91
+ backend: 'x11' | 'carbon'
92
+ }>
93
+ | Readonly<{ availability: 'unavailable'; reason: 'unsupported_platform' }>
94
+ /**
95
+ * The application menu bar: a native NSMenu bar on macOS. GPUI's Linux and
96
+ * Windows backends only store menus, so they report it unavailable. OS
97
+ * context menus are a separate service (`contextMenus`).
98
+ */
99
+ readonly appMenu:
100
+ | Readonly<{
101
+ availability: 'available'
102
+ permission: 'allow' | 'deny'
103
+ scope: 'application'
104
+ backend: 'appkit'
105
+ }>
106
+ | Readonly<{ availability: 'unavailable'; reason: 'unsupported_platform' }>
107
+ /**
108
+ * `window.showContextMenu`: an OS context menu at a point of the window, an
109
+ * `NSMenu` on macOS and a Win32 popup menu on Windows. It needs no grant.
110
+ */
111
+ readonly contextMenus:
112
+ | Readonly<{
113
+ availability: 'available'
114
+ scope: 'owned_window'
115
+ backend: 'appkit' | 'win32'
116
+ }>
117
+ | Readonly<{ availability: 'unavailable'; reason: 'unsupported_platform' }>
118
+ /** OS file open/save/folder dialogs. Selected paths are data, not filesystem grants. */
119
+ readonly fileDialogs:
120
+ | Readonly<{
121
+ availability: 'available'
122
+ permission: 'allow' | 'deny'
123
+ scope: 'owned_window'
124
+ /** The desktop portal's file chooser on Linux; open and save panel sheets on macOS. */
125
+ backend: 'xdg_desktop_portal' | 'appkit'
126
+ }>
127
+ | Readonly<{ availability: 'unavailable'; reason: 'unsupported_platform' }>
128
+ /**
129
+ * `showMessageDialog`/`showConfirmDialog`: an in-window modal overlay drawn
130
+ * by core on every platform and needing no launch grant, or, when the host
131
+ * advertises `task_dialogs_v1` and `permissions.taskDialogs` is `allow`, an
132
+ * OS dialog owned by the window: a task dialog on Windows, an `NSAlert`
133
+ * sheet on macOS.
134
+ */
135
+ readonly messageDialogs:
136
+ | Readonly<{
137
+ availability: 'available'
138
+ scope: 'owned_window'
139
+ backend: 'modal_overlay' | 'task_dialog' | 'alert_sheet'
140
+ }>
141
+ | Readonly<{ availability: 'unavailable'; reason: 'unsupported_host' }>
142
+ readonly notifications:
143
+ | Readonly<{
144
+ availability: 'available'
145
+ permission: 'allow' | 'deny'
146
+ scope: 'owned_window'
147
+ /**
148
+ * The freedesktop.org notification service on Linux;
149
+ * `UNUserNotificationCenter` on macOS, offered only when the host runs
150
+ * from an application bundle.
151
+ */
152
+ backend: 'freedesktop' | 'user_notifications'
153
+ }>
154
+ | Readonly<{ availability: 'unavailable'; reason: 'unsupported_platform' }>
155
+ readonly dragDrop:
156
+ | Readonly<{
157
+ availability: 'available'
158
+ permission: 'allow' | 'deny'
159
+ scope: 'owned_target'
160
+ /** Local files only, delivered as untrusted display names. */
161
+ payload: 'files'
162
+ /** GPUI's X11 XDND target, AppKit dragging destination or OLE drop target. */
163
+ backend: DropBackend
164
+ }>
165
+ | Readonly<{ availability: 'unavailable'; reason: 'unsupported_platform' }>
166
+ readonly filesystemGrants:
167
+ | Readonly<{
168
+ availability: 'available'
169
+ /** Launch roots by ID; each caps the access a grant may request. */
170
+ roots: Readonly<Record<string, Readonly<{ access: 'read' | 'read_write' }>>>
171
+ scope: 'owned_window'
172
+ /**
173
+ * Linux resolves with `openat2`; macOS walks one name at a time with
174
+ * `openat(O_NOFOLLOW)`; Windows walks one name at a time with
175
+ * handle-relative `NtCreateFile` that never follows a reparse point.
176
+ */
177
+ backend: FilesystemBackend
178
+ }>
179
+ | Readonly<{ availability: 'unavailable'; reason: 'unsupported_platform' }>
180
+ readonly ptyProcess:
181
+ | Readonly<{
182
+ availability: 'available'
183
+ /** Launch-policy executables by ID; nothing else can be started. */
184
+ executables: Readonly<
185
+ Record<
186
+ string,
187
+ Readonly<{
188
+ executable: string
189
+ /** Limits every child of this entry runs under, when the launch policy set any. */
190
+ limits?: Readonly<{ cpuSeconds?: number; memoryBytes?: number; openFiles?: number }>
191
+ }>
192
+ >
193
+ >
194
+ scope: 'owned_window'
195
+ /** POSIX process groups and PTYs, or Windows job objects and ConPTY. */
196
+ backend: ProcessBackend
197
+ }>
198
+ | Readonly<{ availability: 'unavailable'; reason: 'unsupported_platform' }>
199
+ }
200
+
201
+ type DropBackend = 'x11' | 'appkit' | 'ole'
202
+ type FilesystemBackend = 'openat2' | 'openat_walk' | 'ntcreatefile_walk'
203
+ type ProcessBackend = 'posix' | 'windows_job'
204
+
205
+ /** The confinement the host on this platform enforces for filesystem grants. */
206
+ function filesystemBackend(): FilesystemBackend {
207
+ if (process.platform === 'darwin') return 'openat_walk'
208
+ return process.platform === 'win32' ? 'ntcreatefile_walk' : 'openat2'
209
+ }
210
+
211
+ /** The host runs beside the core, so its platform names the OS dialog backend. */
212
+ function osDialogBackend(): 'task_dialog' | 'alert_sheet' {
213
+ return process.platform === 'darwin' ? 'alert_sheet' : 'task_dialog'
214
+ }
215
+
216
+ /** The host runs beside the core, so its platform names the drop backend. */
217
+ function dropBackend(): DropBackend {
218
+ if (process.platform === 'darwin') return 'appkit'
219
+ if (process.platform === 'win32') return 'ole'
220
+ return 'x11'
221
+ }
222
+
223
+ export class NativeServiceError extends Error {
224
+ override readonly name = 'NativeServiceError'
225
+ constructor(
226
+ readonly service: ServiceName,
227
+ readonly code:
228
+ | 'permission_denied'
229
+ | 'service_unavailable'
230
+ | 'cancelled'
231
+ | 'native_failure'
232
+ | 'operation_timed_out'
233
+ | 'payload_too_large'
234
+ | 'limit_exceeded'
235
+ | 'conflict'
236
+ | 'not_found'
237
+ | 'already_exists'
238
+ | 'path_denied'
239
+ | 'wrong_kind'
240
+ | 'not_empty'
241
+ | 'access_denied'
242
+ | 'invalid_state',
243
+ message: string
244
+ ) {
245
+ super(message)
246
+ }
247
+ }
248
+
249
+ export function serviceCapabilities(
250
+ policy: Readonly<ServicePolicy>,
251
+ capabilities: readonly Capability[]
252
+ ): Readonly<ServiceCapabilities> {
253
+ return Object.freeze({
254
+ windowDisplay: Object.freeze({
255
+ availability: 'available',
256
+ permission: policy.window_display ? 'allow' : 'deny',
257
+ scope: 'owned_window',
258
+ details: capabilities.includes('display_details_v1') ? 'available' : 'unavailable',
259
+ identity: capabilities.includes('display_identity_v1') ? 'available' : 'unavailable',
260
+ changes: capabilities.includes('display_changes_v1') ? 'available' : 'unavailable',
261
+ }),
262
+ clipboardText: capabilities.includes('clipboard_text_v1')
263
+ ? Object.freeze({
264
+ availability: 'available',
265
+ read: policy.clipboard_read ? 'allow' : 'deny',
266
+ write: policy.clipboard_write ? 'allow' : 'deny',
267
+ scope: 'owned_window',
268
+ backend: process.platform === 'darwin' ? 'appkit' : 'x11',
269
+ })
270
+ : Object.freeze({ availability: 'unavailable', reason: 'unsupported_platform' }),
271
+ globalShortcuts: capabilities.includes('global_shortcuts_v1')
272
+ ? Object.freeze({
273
+ availability: 'available',
274
+ permission: policy.global_shortcuts ? 'allow' : 'deny',
275
+ scope: 'owned_window',
276
+ backend: process.platform === 'darwin' ? 'carbon' : 'x11',
277
+ })
278
+ : Object.freeze({ availability: 'unavailable', reason: 'unsupported_platform' }),
279
+ contextMenus: capabilities.includes('context_menus_v1')
280
+ ? Object.freeze({
281
+ availability: 'available',
282
+ scope: 'owned_window',
283
+ // The host runs beside the core, so its platform names the backend.
284
+ backend: process.platform === 'darwin' ? 'appkit' : 'win32',
285
+ })
286
+ : Object.freeze({ availability: 'unavailable', reason: 'unsupported_platform' }),
287
+ appMenu: capabilities.includes('app_menu_v1')
288
+ ? Object.freeze({
289
+ availability: 'available',
290
+ permission: policy.app_menu ? 'allow' : 'deny',
291
+ scope: 'application',
292
+ backend: 'appkit',
293
+ })
294
+ : Object.freeze({ availability: 'unavailable', reason: 'unsupported_platform' }),
295
+ fileDialogs: capabilities.includes('file_dialogs_v1')
296
+ ? Object.freeze({
297
+ availability: 'available',
298
+ permission: policy.file_dialogs ? 'allow' : 'deny',
299
+ scope: 'owned_window',
300
+ backend: process.platform === 'darwin' ? 'appkit' : 'xdg_desktop_portal',
301
+ })
302
+ : Object.freeze({ availability: 'unavailable', reason: 'unsupported_platform' }),
303
+ // The modal overlay and a focus request are the only native features used.
304
+ messageDialogs:
305
+ capabilities.includes('overlays_v1') && capabilities.includes('focus_v1')
306
+ ? Object.freeze({
307
+ availability: 'available',
308
+ scope: 'owned_window',
309
+ // The OS backend needs both the host capability and the grant.
310
+ backend:
311
+ capabilities.includes('task_dialogs_v1') && policy.task_dialogs
312
+ ? osDialogBackend()
313
+ : 'modal_overlay',
314
+ })
315
+ : Object.freeze({ availability: 'unavailable', reason: 'unsupported_host' }),
316
+ notifications: capabilities.includes('notifications_v1')
317
+ ? Object.freeze({
318
+ availability: 'available',
319
+ permission: policy.notifications ? 'allow' : 'deny',
320
+ scope: 'owned_window',
321
+ backend: process.platform === 'darwin' ? 'user_notifications' : 'freedesktop',
322
+ })
323
+ : Object.freeze({ availability: 'unavailable', reason: 'unsupported_platform' }),
324
+ dragDrop: capabilities.includes('drag_drop_files_v1')
325
+ ? Object.freeze({
326
+ availability: 'available',
327
+ permission: policy.drag_drop ? 'allow' : 'deny',
328
+ scope: 'owned_target',
329
+ payload: 'files',
330
+ backend: dropBackend(),
331
+ })
332
+ : Object.freeze({ availability: 'unavailable', reason: 'unsupported_platform' }),
333
+ filesystemGrants: capabilities.includes('filesystem_grants_v1')
334
+ ? Object.freeze({
335
+ availability: 'available',
336
+ roots: Object.freeze(
337
+ Object.fromEntries(
338
+ policy.filesystem_roots.map((root) => [
339
+ root.id,
340
+ Object.freeze({ access: root.access }),
341
+ ])
342
+ )
343
+ ),
344
+ scope: 'owned_window',
345
+ backend: filesystemBackend(),
346
+ })
347
+ : Object.freeze({ availability: 'unavailable', reason: 'unsupported_platform' }),
348
+ ptyProcess: capabilities.includes('processes_v1')
349
+ ? Object.freeze({
350
+ availability: 'available',
351
+ executables: Object.freeze(
352
+ Object.fromEntries(
353
+ policy.processes.map((entry) => [
354
+ entry.id,
355
+ Object.freeze({
356
+ executable: entry.executable,
357
+ ...(entry.limits && {
358
+ limits: Object.freeze({
359
+ ...(entry.limits.cpu_seconds !== undefined && {
360
+ cpuSeconds: entry.limits.cpu_seconds,
361
+ }),
362
+ ...(entry.limits.memory_bytes !== undefined && {
363
+ memoryBytes: entry.limits.memory_bytes,
364
+ }),
365
+ ...(entry.limits.open_files !== undefined && {
366
+ openFiles: entry.limits.open_files,
367
+ }),
368
+ }),
369
+ }),
370
+ }),
371
+ ])
372
+ )
373
+ ),
374
+ scope: 'owned_window',
375
+ backend: process.platform === 'win32' ? 'windows_job' : 'posix',
376
+ })
377
+ : Object.freeze({ availability: 'unavailable', reason: 'unsupported_platform' }),
378
+ })
379
+ }
380
+
381
+ /**
382
+ * A frozen public snapshot; a work area and an identity are accepted only from
383
+ * a host that advertised them. A host with `display_details_v1` always sends
384
+ * the work area; an identity is optional even when advertised.
385
+ */
386
+ export function publicDisplaySnapshot(
387
+ snapshot: DisplaySnapshot,
388
+ capabilities: readonly Capability[]
389
+ ): NativeDisplaySnapshot {
390
+ const details = capabilities.includes('display_details_v1')
391
+ const identity = capabilities.includes('display_identity_v1')
392
+ if (
393
+ (details ? !snapshot.visible_bounds : snapshot.visible_bounds) ||
394
+ (!identity && snapshot.display_uuid)
395
+ )
396
+ throw new ProtocolError('Native display details do not match the negotiated capabilities')
397
+ return Object.freeze({
398
+ bounds: Object.freeze({ ...snapshot.bounds }),
399
+ scaleFactor: snapshot.scale_factor,
400
+ ...(snapshot.visible_bounds
401
+ ? { visibleBounds: Object.freeze({ ...snapshot.visible_bounds }) }
402
+ : {}),
403
+ ...(snapshot.display_uuid ? { displayId: snapshot.display_uuid } : {}),
404
+ })
405
+ }
406
+
407
+ export function serviceSignal(options: ServiceRequestOptions): AbortSignal | undefined {
408
+ if (!options || typeof options !== 'object' || Array.isArray(options))
409
+ throw new TypeError('Native service options must be an object')
410
+ if (Object.keys(options).some((key) => key !== 'signal'))
411
+ throw new TypeError('Unknown native service option')
412
+ const signal = Object.hasOwn(options, 'signal') ? options.signal : undefined
413
+ if (signal !== undefined && !(signal instanceof AbortSignal))
414
+ throw new TypeError('Native service signal must be an AbortSignal')
415
+ return signal
416
+ }
417
+
418
+ export function checkServiceCancellation(
419
+ signal: AbortSignal | undefined,
420
+ service: ServiceName
421
+ ): void {
422
+ if (signal?.aborted)
423
+ throw new NativeServiceError(
424
+ service,
425
+ 'cancelled',
426
+ 'Native service read was cancelled; no result is delivered'
427
+ )
428
+ }