@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,233 @@
1
+ import type { Element, Limits, Operation } from '@bun-native/protocol'
2
+ import type { NodeState, Transaction } from './tree.ts'
3
+ import { NativeStateError } from './types.ts'
4
+
5
+ /**
6
+ * A logical transaction larger than one native batch.
7
+ *
8
+ * The native host validates and paints each batch atomically, rejects a batch
9
+ * above `max_operations`, and rejects any batch that leaves a node detached.
10
+ * Splitting the application's operation sequence would therefore expose (and
11
+ * be unable to roll back) its intermediate states. Instead, new nodes are
12
+ * first built under a zero-size, clipped staging box appended to the window
13
+ * root. Those staging batches touch only nodes the application has not yet
14
+ * committed, so they change nothing it or the user can see. One final batch
15
+ * then applies every change to committed nodes at once: sets, moves of new
16
+ * subtrees and retained nodes into place, deletions, and the staging box's
17
+ * removal. A failure before or in that batch removes the staging box, which
18
+ * restores the committed tree exactly. The wire protocol is unchanged.
19
+ *
20
+ * New nodes receive fresh identities in pre-order so that each parent exists
21
+ * before its children while native identities keep increasing. The
22
+ * transaction renumbers its own copies and their handles, none of which was
23
+ * committed, and later commits copy-on-write as a single batch does.
24
+ */
25
+ export interface StagedCommit {
26
+ readonly staging: readonly (readonly Operation[])[]
27
+ readonly visible: readonly Operation[]
28
+ readonly discard: Operation
29
+ }
30
+
31
+ const STAGING: Element = {
32
+ kind: 'box',
33
+ style: { width: 0, height: 0, max_width: 0, max_height: 0, flex_shrink: 0, overflow: 'hidden' },
34
+ }
35
+ // The command envelope (id, type, window and revision) and the array brackets.
36
+ const FRAME_OVERHEAD = 256
37
+
38
+ function bytes(operation: Operation): number {
39
+ return Buffer.byteLength(JSON.stringify(operation)) + 1
40
+ }
41
+
42
+ /** Split units that must stay together into frames within both native limits. */
43
+ function frames(units: readonly Operation[][], limits: Readonly<Limits>): Operation[][] {
44
+ const budget = limits.max_frame_bytes - FRAME_OVERHEAD
45
+ const result: Operation[][] = []
46
+ let current: Operation[] = []
47
+ let size = 0
48
+ for (const unit of units) {
49
+ const unitSize = unit.reduce((total, operation) => total + bytes(operation), 0)
50
+ if (
51
+ current.length &&
52
+ (current.length + unit.length > limits.max_operations || size + unitSize > budget)
53
+ ) {
54
+ result.push(current)
55
+ current = []
56
+ size = 0
57
+ }
58
+ current.push(...unit)
59
+ size += unitSize
60
+ }
61
+ if (current.length) result.push(current)
62
+ return result
63
+ }
64
+
65
+ /** The longest subsequence of `target` already in `current` order. */
66
+ function stableChildren(current: readonly number[], target: readonly number[]): Set<number> {
67
+ const positions = new Map(current.map((id, index) => [id, index]))
68
+ const tails: { id: number; position: number }[] = []
69
+ const preceding = new Map<number, number | undefined>()
70
+ for (const id of target) {
71
+ const position = positions.get(id)
72
+ if (position === undefined) continue
73
+ let start = 0
74
+ let end = tails.length
75
+ while (start < end) {
76
+ const middle = (start + end) >>> 1
77
+ if (tails[middle]!.position < position) start = middle + 1
78
+ else end = middle
79
+ }
80
+ preceding.set(id, tails[start - 1]?.id)
81
+ tails[start] = { id, position }
82
+ }
83
+ const stable = new Set<number>()
84
+ for (let id = tails.at(-1)?.id; id !== undefined; id = preceding.get(id)) stable.add(id)
85
+ return stable
86
+ }
87
+
88
+ export function planStagedCommit(
89
+ committed: ReadonlyMap<number, NodeState>,
90
+ transaction: Transaction,
91
+ rootId: number,
92
+ allocate: () => number,
93
+ limits: Readonly<Limits>
94
+ ): StagedCommit {
95
+ const { nodes, operations } = transaction
96
+ const preorder: number[] = []
97
+ for (const pending = [rootId]; pending.length;) {
98
+ const id = pending.pop()!
99
+ preorder.push(id)
100
+ pending.push(...[...nodes.get(id)!.children].reverse())
101
+ }
102
+ const staging = allocate()
103
+ const identity = new Map<number, number>()
104
+ for (const id of preorder) if (!committed.has(id)) identity.set(id, allocate())
105
+ transaction.renumber(identity)
106
+ const order = preorder.map((id) => identity.get(id) ?? id)
107
+ const fresh = new Set(identity.values())
108
+
109
+ const units: Operation[][] = [
110
+ [
111
+ { type: 'create', node_id: staging, element: STAGING },
112
+ {
113
+ type: 'insert',
114
+ parent_id: rootId,
115
+ child_id: staging,
116
+ index: committed.get(rootId)!.children.length,
117
+ },
118
+ ],
119
+ ]
120
+ // The simulated native children after staging, for placing nodes below.
121
+ const children = new Map<number, number[]>()
122
+ const parents = new Map<number, number>()
123
+ for (const [id, node] of committed) {
124
+ children.set(id, [...node.children])
125
+ if (node.parent !== undefined) parents.set(id, node.parent)
126
+ }
127
+ children.get(rootId)!.push(staging)
128
+ children.set(staging, [])
129
+ parents.set(staging, rootId)
130
+ for (const next of order) {
131
+ if (!fresh.has(next)) continue
132
+ const node = nodes.get(next)!
133
+ // Pre-order: a new parent is already staged; otherwise wait in the box.
134
+ const parent = fresh.has(node.parent!) ? node.parent! : staging
135
+ const siblings = children.get(parent)!
136
+ units.push([
137
+ { type: 'create', node_id: next, element: node.element },
138
+ { type: 'insert', parent_id: parent, child_id: next, index: siblings.length },
139
+ ])
140
+ siblings.push(next)
141
+ children.set(next, [])
142
+ parents.set(next, parent)
143
+ // A new input's edit revision counts its sets in this transaction.
144
+ if (node.element.kind === 'input')
145
+ for (let revision = 0; revision < node.inputRevision; revision += 1)
146
+ units.push([
147
+ {
148
+ type: 'set',
149
+ node_id: next,
150
+ element: node.element,
151
+ expected_input_revision: revision,
152
+ },
153
+ ])
154
+ }
155
+
156
+ const visible: Operation[] = operations.filter(
157
+ (operation) =>
158
+ operation.type === 'set' && committed.has(operation.node_id) && nodes.has(operation.node_id)
159
+ )
160
+ for (const next of order) {
161
+ const target = nodes.get(next)!.children
162
+ const current = children.get(next)!
163
+ // Keep a longest already ordered run and move only the other children,
164
+ // last first, each before its placed successor. Nodes that are not in the
165
+ // target stay behind until they move to a later parent or are deleted.
166
+ const stable = stableChildren(current, target)
167
+ let anchor: number | undefined
168
+ for (let index = target.length - 1; index >= 0; index -= 1) {
169
+ const child = target[index]!
170
+ if (!stable.has(child)) {
171
+ const previous = children.get(parents.get(child)!)!
172
+ previous.splice(previous.indexOf(child), 1)
173
+ const before = anchor === undefined ? current.length : current.indexOf(anchor)
174
+ current.splice(before, 0, child)
175
+ parents.set(child, next)
176
+ visible.push({ type: 'insert', parent_id: next, child_id: child, index: before })
177
+ }
178
+ anchor = child
179
+ }
180
+ }
181
+ for (const [id, node] of committed)
182
+ if (!nodes.has(id) && node.parent !== undefined && nodes.has(node.parent))
183
+ visible.push({ type: 'delete', node_id: id })
184
+ visible.push({ type: 'delete', node_id: staging })
185
+ // Focus and scroll requests are applied natively after the tree changes, so
186
+ // they ride the final batch, addressed by the renumbered identities.
187
+ for (const operation of operations)
188
+ if (
189
+ operation.type === 'focus' ||
190
+ operation.type === 'scroll_to' ||
191
+ operation.type === 'scroll_into_view'
192
+ )
193
+ visible.push({ ...operation, node_id: identity.get(operation.node_id) ?? operation.node_id })
194
+ if (visible.length > limits.max_operations)
195
+ throw new NativeStateError(
196
+ 'limit_exceeded',
197
+ 'Batch operation limit exceeded by changes to committed nodes'
198
+ )
199
+ return {
200
+ staging: frames(units, limits),
201
+ visible,
202
+ discard: { type: 'delete', node_id: staging },
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Send a staged commit. `acknowledge` runs in each reply's own continuation,
208
+ * so a native event after that batch never sees an older revision.
209
+ */
210
+ export async function sendStagedCommit<Reply>(
211
+ plan: StagedCommit,
212
+ send: (operations: readonly Operation[]) => Promise<Reply>,
213
+ acknowledge: (reply: Reply, final: boolean) => void
214
+ ): Promise<void> {
215
+ let staged = false
216
+ try {
217
+ for (const operations of plan.staging) {
218
+ acknowledge(await send(operations), false)
219
+ staged = true
220
+ }
221
+ acknowledge(await send(plan.visible), true)
222
+ } catch (error) {
223
+ // Removing the box (and every new node still in it) restores the
224
+ // committed tree; the original rejection is the transaction's result.
225
+ if (staged)
226
+ try {
227
+ acknowledge(await send([plan.discard]), false)
228
+ } catch {
229
+ // A closed window or failed host already ended this tree's lifetime.
230
+ }
231
+ throw error
232
+ }
233
+ }
@@ -0,0 +1,76 @@
1
+ import { parseContextMenuItems, ProtocolError, type AppMenuEntry } from '@bun-native/protocol'
2
+ import { menuEntriesRequest, type MenuEntryOptions } from './app-menu.ts'
3
+
4
+ /** Where an OS context menu opens, in logical pixels of the window's content. */
5
+ export interface ContextMenuPosition {
6
+ readonly x: number
7
+ readonly y: number
8
+ }
9
+
10
+ const MAX_COORDINATE = 1_048_576
11
+
12
+ /** Copies consumer items into the closed wire shape and validates it with the shared parser. */
13
+ export function contextMenuRequest(
14
+ items: readonly MenuEntryOptions[],
15
+ position: ContextMenuPosition
16
+ ): { items: AppMenuEntry[]; x: number; y: number } {
17
+ if (!position || typeof position !== 'object')
18
+ throw new TypeError('Context menu position must be an object')
19
+ const { x, y } = position
20
+ for (const value of [x, y])
21
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > MAX_COORDINATE)
22
+ throw new TypeError('Context menu position must be finite, nonnegative logical pixels')
23
+ try {
24
+ return { items: parseContextMenuItems(menuEntriesRequest(items)), x, y }
25
+ } catch (error) {
26
+ if (error instanceof ProtocolError) throw new TypeError(error.message)
27
+ throw error
28
+ }
29
+ }
30
+
31
+ /** Internal registry entry for one live native context menu. */
32
+ export class ContextMenuRequest {
33
+ readonly result: Promise<string | null>
34
+ private resolve!: (result: string | null) => void
35
+ private reject!: (error: Error) => void
36
+ private settled = false
37
+
38
+ constructor(
39
+ readonly id: number,
40
+ readonly windowId: number,
41
+ private readonly ids: ReadonlySet<string>
42
+ ) {
43
+ this.result = new Promise((resolve, reject) => {
44
+ this.resolve = resolve
45
+ this.reject = reject
46
+ })
47
+ // The caller may not await before revocation rejects it.
48
+ void this.result.catch(() => {})
49
+ }
50
+
51
+ get live(): boolean {
52
+ return !this.settled
53
+ }
54
+
55
+ complete(itemId: string | undefined): void {
56
+ if (this.settled) return
57
+ if (itemId !== undefined && !this.ids.has(itemId))
58
+ throw new ProtocolError('Native context menu chose an item it was not given')
59
+ this.settled = true
60
+ this.resolve(itemId ?? null)
61
+ }
62
+
63
+ fail(error: Error): void {
64
+ if (this.settled) return
65
+ this.settled = true
66
+ this.reject(error)
67
+ }
68
+ }
69
+
70
+ /** Every item id of a validated menu, at any depth. */
71
+ export function itemIds(items: readonly AppMenuEntry[], into = new Set<string>()): Set<string> {
72
+ for (const item of items)
73
+ if (item.kind === 'item') into.add(item.id)
74
+ else if (item.kind === 'submenu') itemIds(item.items, into)
75
+ return into
76
+ }
package/src/dialogs.ts ADDED
@@ -0,0 +1,153 @@
1
+ import {
2
+ ProtocolError,
3
+ parseFileDialogOptions,
4
+ type FileDialogMode,
5
+ type FileDialogOptions,
6
+ type FileDialogResult,
7
+ } from '@bun-native/protocol'
8
+ import { NativeServiceError } from './services.ts'
9
+
10
+ export interface FileDialogFilter {
11
+ /** Shown to the user, e.g. `Text`. At most 128 UTF-8 bytes. */
12
+ readonly name: string
13
+ /** Shell-style globs such as `*.txt`; 1-16 of at most 64 bytes each. */
14
+ readonly patterns: readonly string[]
15
+ }
16
+
17
+ interface CommonDialogOptions {
18
+ /** One nonempty line of at most 256 UTF-8 bytes. */
19
+ readonly title: string
20
+ /** The accept button's label; the platform default when absent. */
21
+ readonly acceptLabel?: string
22
+ /** An absolute starting folder. A hint the platform may ignore. */
23
+ readonly folder?: string
24
+ /** At most 16 filters. */
25
+ readonly filters?: readonly FileDialogFilter[]
26
+ }
27
+
28
+ export interface OpenDialogOptions extends CommonDialogOptions {
29
+ /** `file` (default) picks one file, `files` one or more, `directory` one folder. */
30
+ readonly select?: 'file' | 'files' | 'directory'
31
+ }
32
+
33
+ export interface SaveDialogOptions extends CommonDialogOptions {
34
+ /** The suggested file name: one path component of at most 255 bytes. */
35
+ readonly name?: string
36
+ }
37
+
38
+ /**
39
+ * Absolute paths the user chose. They are data, not authority: a path does not
40
+ * grant filesystem access through Bun Native, and converting it into a scoped
41
+ * filesystem grant is a separate, explicit operation.
42
+ */
43
+ export type OpenDialogResult =
44
+ | Readonly<{ kind: 'selected'; paths: readonly string[] }>
45
+ | Readonly<{ kind: 'cancelled' }>
46
+ export type SaveDialogResult =
47
+ | Readonly<{ kind: 'selected'; path: string }>
48
+ | Readonly<{ kind: 'cancelled' }>
49
+
50
+ const OPEN_KEYS = ['title', 'acceptLabel', 'folder', 'filters', 'select']
51
+ const SAVE_KEYS = ['title', 'acceptLabel', 'folder', 'filters', 'name']
52
+ const SELECT_MODES = {
53
+ file: 'open_file',
54
+ files: 'open_files',
55
+ directory: 'open_directory',
56
+ } as const
57
+
58
+ function wireOptions(
59
+ options: unknown,
60
+ allowed: readonly string[],
61
+ mode: (data: Record<string, unknown>) => FileDialogMode
62
+ ): FileDialogOptions {
63
+ if (!options || typeof options !== 'object' || Array.isArray(options))
64
+ throw new TypeError('File dialog options must be an object')
65
+ const data = options as Record<string, unknown>
66
+ if (Object.keys(data).some((key) => !allowed.includes(key)))
67
+ throw new TypeError('Unknown file dialog option')
68
+ const filters = data['filters']
69
+ if (filters !== undefined && !Array.isArray(filters))
70
+ throw new TypeError('File dialog filters must be an array')
71
+ const wire: Record<string, unknown> = { mode: mode(data), title: data['title'] }
72
+ if (data['acceptLabel'] !== undefined) wire['accept_label'] = data['acceptLabel']
73
+ if (data['folder'] !== undefined) wire['folder'] = data['folder']
74
+ if (data['name'] !== undefined) wire['name'] = data['name']
75
+ if (filters?.length)
76
+ wire['filters'] = filters.map((filter: unknown) => {
77
+ if (!filter || typeof filter !== 'object' || Array.isArray(filter))
78
+ throw new TypeError('A file dialog filter must be an object')
79
+ const { name, patterns } = filter as Record<string, unknown>
80
+ if (Object.keys(filter).some((key) => key !== 'name' && key !== 'patterns'))
81
+ throw new TypeError('Unknown file dialog filter option')
82
+ return { name, patterns: Array.isArray(patterns) ? [...patterns] : patterns }
83
+ })
84
+ try {
85
+ // One shared validator for both language implementations' bounds.
86
+ return parseFileDialogOptions(wire)
87
+ } catch (error) {
88
+ if (error instanceof ProtocolError) throw new TypeError(error.message)
89
+ throw error
90
+ }
91
+ }
92
+
93
+ export function openDialogRequest(options: OpenDialogOptions): FileDialogOptions {
94
+ return wireOptions(options, OPEN_KEYS, (data) => {
95
+ const select = data['select'] === undefined ? 'file' : data['select']
96
+ if (select !== 'file' && select !== 'files' && select !== 'directory')
97
+ throw new TypeError('File dialog select must be file, files or directory')
98
+ return SELECT_MODES[select]
99
+ })
100
+ }
101
+
102
+ export function saveDialogRequest(options: SaveDialogOptions): FileDialogOptions {
103
+ return wireOptions(options, SAVE_KEYS, () => 'save_file')
104
+ }
105
+
106
+ /** Internal registry entry for one live native dialog. */
107
+ export class FileDialogRequest {
108
+ readonly result: Promise<FileDialogResult>
109
+ private resolve!: (result: FileDialogResult) => void
110
+ private reject!: (error: Error) => void
111
+ private settled = false
112
+
113
+ constructor(
114
+ readonly id: number,
115
+ readonly windowId: number,
116
+ readonly mode: FileDialogMode
117
+ ) {
118
+ this.result = new Promise((resolve, reject) => {
119
+ this.resolve = resolve
120
+ this.reject = reject
121
+ })
122
+ // The caller may not await before revocation rejects it.
123
+ void this.result.catch(() => {})
124
+ }
125
+
126
+ get live(): boolean {
127
+ return !this.settled
128
+ }
129
+
130
+ complete(result: FileDialogResult): void {
131
+ if (this.settled) return
132
+ if (result.kind === 'selected' && this.mode !== 'open_files' && result.paths.length !== 1)
133
+ throw new ProtocolError('A single-selection file dialog returned several paths')
134
+ this.settled = true
135
+ if (result.kind === 'failed')
136
+ this.reject(
137
+ new NativeServiceError(
138
+ 'file_dialogs',
139
+ result.code,
140
+ result.code === 'payload_too_large'
141
+ ? 'The selection does not fit one native message'
142
+ : 'The native file dialog failed'
143
+ )
144
+ )
145
+ else this.resolve(result)
146
+ }
147
+
148
+ fail(error: Error): void {
149
+ if (this.settled) return
150
+ this.settled = true
151
+ this.reject(error)
152
+ }
153
+ }
package/src/display.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { DisplayChangeEvent } from './services.ts'
2
+
3
+ /** Internal owner of one `onDisplayChange` listener. Consumers only receive its remover. */
4
+ export class DisplaySubscription {
5
+ readonly controller = new AbortController()
6
+ private listener: ((event: DisplayChangeEvent) => void | Promise<void>) | undefined
7
+
8
+ constructor(listener: (event: DisplayChangeEvent) => void | Promise<void>) {
9
+ this.listener = listener
10
+ }
11
+
12
+ get live(): boolean {
13
+ return this.listener !== undefined
14
+ }
15
+
16
+ /** Idempotent: no later change is delivered and an active listener's signal aborts. */
17
+ revoke(): void {
18
+ this.listener = undefined
19
+ this.controller.abort()
20
+ }
21
+
22
+ get current(): ((event: DisplayChangeEvent) => void | Promise<void>) | undefined {
23
+ return this.listener
24
+ }
25
+ }
package/src/drops.ts ADDED
@@ -0,0 +1,95 @@
1
+ import type { DropRejection } from '@bun-native/protocol'
2
+ import type { Listener, NativeNode } from './types.ts'
3
+
4
+ /**
5
+ * One item of a drop. `name` is untrusted display text: the final path
6
+ * component, lossily decoded and bounded. It is not unique and not a path.
7
+ */
8
+ export interface NativeDroppedItem {
9
+ readonly name: string
10
+ /**
11
+ * Map this item to a path relative to a launch filesystem root the
12
+ * application already holds. The host matches the path it retained for
13
+ * the drop; nothing here grants new authority. Rejects with `path_denied`
14
+ * when the item is not beneath that root, and `cancelled` once a newer drop
15
+ * replaced this one or the target, its node or its window is gone.
16
+ */
17
+ resolve(root: string): Promise<Readonly<{ root: string; path: string }>>
18
+ }
19
+
20
+ interface TargetEvent {
21
+ readonly sequence: number
22
+ readonly target: NativeDropTarget
23
+ /** Aborted when the target closes, its node is removed, its window closes or the app stops. */
24
+ readonly signal: AbortSignal
25
+ }
26
+
27
+ export type DropTargetEvent =
28
+ | (TargetEvent & { readonly type: 'drag_entered' })
29
+ /** The drag moved off the target or ended without a drop on it. */
30
+ | (TargetEvent & { readonly type: 'drag_left' })
31
+ | (TargetEvent & { readonly type: 'drop'; readonly items: readonly NativeDroppedItem[] })
32
+ | (TargetEvent & { readonly type: 'drop_rejected'; readonly reason: DropRejection })
33
+
34
+ export interface NativeDropTarget {
35
+ readonly node: NativeNode
36
+ /** False once closed or revoked; no later event is delivered. */
37
+ readonly active: boolean
38
+ /** Idempotent. Delivery stops immediately; resolves after native removal. */
39
+ close(): Promise<void>
40
+ }
41
+
42
+ /** Internal registry entry. Consumers only receive its frozen handle. */
43
+ export class DropTargetRegistration {
44
+ readonly handle: NativeDropTarget
45
+ readonly controller = new AbortController()
46
+ listener: Listener<DropTargetEvent> | undefined
47
+ /** The host retains paths only for the target's latest accepted drop. */
48
+ latestDrop: number | undefined
49
+ private released = false
50
+ private releasing: Promise<void> | undefined
51
+
52
+ constructor(
53
+ readonly id: number,
54
+ readonly windowId: number,
55
+ readonly nodeId: number,
56
+ node: NativeNode,
57
+ listener: Listener<DropTargetEvent>,
58
+ release: (registration: DropTargetRegistration) => Promise<void>
59
+ ) {
60
+ this.listener = listener
61
+ this.handle = publicHandle(this, node, release)
62
+ }
63
+
64
+ release(release: (registration: DropTargetRegistration) => Promise<void>): Promise<void> {
65
+ this.releasing ??= this.released ? Promise.resolve() : release(this)
66
+ return this.releasing
67
+ }
68
+
69
+ get live(): boolean {
70
+ return !this.released
71
+ }
72
+
73
+ /** Synchronous local revocation; native removal happens separately. */
74
+ revoke(): void {
75
+ if (this.released) return
76
+ this.released = true
77
+ this.listener = undefined
78
+ this.latestDrop = undefined
79
+ this.controller.abort()
80
+ }
81
+ }
82
+
83
+ function publicHandle(
84
+ registration: DropTargetRegistration,
85
+ node: NativeNode,
86
+ release: (registration: DropTargetRegistration) => Promise<void>
87
+ ): NativeDropTarget {
88
+ return Object.freeze({
89
+ node,
90
+ get active() {
91
+ return registration.live
92
+ },
93
+ close: () => registration.release(release),
94
+ })
95
+ }