@bun-native/core 0.33.0 → 0.33.1

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.
@@ -1,233 +0,0 @@
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
- }