@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.
package/src/tree.ts ADDED
@@ -0,0 +1,672 @@
1
+ import {
2
+ DECORATION_FIELDS,
3
+ MAX_OVERLAY_DEPTH,
4
+ MAX_SCROLL_OFFSET,
5
+ parseElement,
6
+ type Capability,
7
+ type Element,
8
+ type Limits,
9
+ type Operation,
10
+ type Style,
11
+ } from '@bun-native/protocol'
12
+ import {
13
+ NativeStateError,
14
+ UnsupportedFeatureError,
15
+ type ContainerKind,
16
+ type ElementKind,
17
+ type NativeBatch,
18
+ type NativeNode,
19
+ type ScrollOffset,
20
+ } from './types.ts'
21
+
22
+ const identities = new WeakMap<NativeNode, number>()
23
+ const encoder = new TextEncoder()
24
+ // Normalized elements are replaced, never mutated, so their size is stable.
25
+ const textSizes = new WeakMap<Element, readonly number[]>()
26
+ const elementKinds: readonly string[] = ['box', 'text', 'button', 'input', 'split', 'overlay']
27
+ const isContainer = (element: Element) =>
28
+ element.kind === 'box' || element.kind === 'split' || element.kind === 'overlay'
29
+ /** Splits and overlays carry placement rules that the incremental check leaves to the full walk. */
30
+ const layered = (element: Element) => element.kind === 'split' || element.kind === 'overlay'
31
+
32
+ function normalize(element: Element): Element {
33
+ if (
34
+ element !== null &&
35
+ typeof element === 'object' &&
36
+ typeof element.kind === 'string' &&
37
+ !elementKinds.includes(element.kind)
38
+ )
39
+ throw new UnsupportedFeatureError('element:' + element.kind)
40
+ return parseElement(element)
41
+ }
42
+
43
+ /** Optional element features fail locally instead of reaching a host that lacks them. */
44
+ function supported(element: Element, capabilities: readonly Capability[]): Element {
45
+ if (element.kind === 'split' && !capabilities.includes('split_v1'))
46
+ throw new UnsupportedFeatureError('element:split')
47
+ if (element.kind === 'overlay' && !capabilities.includes('overlays_v1'))
48
+ throw new UnsupportedFeatureError('element:overlay')
49
+ const style: Style = element.style ?? {}
50
+ if (
51
+ !capabilities.includes('style_decoration_v1') &&
52
+ DECORATION_FIELDS.some((field) => style[field] !== undefined)
53
+ )
54
+ throw new UnsupportedFeatureError('style:decoration')
55
+ if (
56
+ (element.kind === 'box' || element.kind === 'overlay') &&
57
+ element.style?.scroll_anchor !== undefined &&
58
+ !capabilities.includes('scroll_anchor_v1')
59
+ )
60
+ throw new UnsupportedFeatureError('style:scroll_anchor')
61
+ if (
62
+ element.kind === 'overlay' &&
63
+ (element.autofocus !== undefined || element.navigation !== undefined) &&
64
+ !capabilities.includes('overlay_keyboard_v1')
65
+ )
66
+ throw new UnsupportedFeatureError(
67
+ element.autofocus === undefined ? 'overlay:navigation' : 'overlay:autofocus'
68
+ )
69
+ if (
70
+ element.kind === 'overlay' &&
71
+ element.surface === 'window' &&
72
+ !capabilities.includes('popup_windows_v1')
73
+ )
74
+ throw new UnsupportedFeatureError('overlay:surface_window')
75
+ if (
76
+ element.kind === 'input' &&
77
+ (element.disabled === true || element.read_only === true) &&
78
+ !capabilities.includes('input_states_v1')
79
+ )
80
+ throw new UnsupportedFeatureError('input:' + (element.disabled ? 'disabled' : 'read_only'))
81
+ if (
82
+ (element.kind === 'split' || element.kind === 'overlay') &&
83
+ element.accessible_label !== undefined &&
84
+ !capabilities.includes('accessibility_v1')
85
+ )
86
+ throw new UnsupportedFeatureError(element.kind + ':accessible_label')
87
+ if (
88
+ ((element.kind === 'box' && element.accessible_role !== undefined) ||
89
+ (element.kind === 'text' && element.accessible_live !== undefined)) &&
90
+ !capabilities.includes('accessibility_lists_v1')
91
+ )
92
+ throw new UnsupportedFeatureError(
93
+ element.kind === 'box' ? 'box:accessible_role' : 'text:accessible_live'
94
+ )
95
+ return element
96
+ }
97
+
98
+ function requireCapability(
99
+ capabilities: readonly Capability[],
100
+ capability: Capability,
101
+ feature: string
102
+ ) {
103
+ if (!capabilities.includes(capability)) throw new UnsupportedFeatureError(feature)
104
+ }
105
+
106
+ /** A focus or scroll request checked against the final candidate tree. */
107
+ type Request = {
108
+ type: 'focus' | 'scroll_to' | 'scroll_into_view'
109
+ id: number
110
+ x?: number
111
+ y?: number
112
+ }
113
+
114
+ export interface NodeState {
115
+ id: number
116
+ handle: NativeNode
117
+ element: Element
118
+ parent: number | undefined
119
+ children: number[]
120
+ inputRevision: number
121
+ }
122
+
123
+ export function makeNode<E extends Element>(
124
+ id: number,
125
+ element: E
126
+ ): NodeState & { handle: NativeNode<E['kind']> } {
127
+ const handle = Object.freeze({ kind: element.kind }) as NativeNode<E['kind']>
128
+ identities.set(handle, id)
129
+ return {
130
+ id,
131
+ handle,
132
+ element: normalize(element),
133
+ parent: undefined,
134
+ children: [],
135
+ inputRevision: 0,
136
+ }
137
+ }
138
+
139
+ /**
140
+ * One logical transaction may exceed a native batch (see commit-plan.ts), but
141
+ * it stays bounded: a full-window mount needs a create and an insert per node.
142
+ */
143
+ function logicalOperationLimit(limits: Readonly<Limits>): number {
144
+ return 2 * limits.max_nodes_per_window + limits.max_operations
145
+ }
146
+
147
+ export function own(nodes: ReadonlyMap<number, NodeState>, handle: NativeNode): NodeState {
148
+ const id = identities.get(handle)
149
+ const node = id === undefined ? undefined : nodes.get(id)
150
+ if (!node || node.handle !== handle)
151
+ throw new NativeStateError(
152
+ 'invalid_handle',
153
+ 'Node is forged, disposed or belongs to another window'
154
+ )
155
+ return node
156
+ }
157
+
158
+ function textSizesOf(element: Element): readonly number[] {
159
+ let sizes = textSizes.get(element)
160
+ if (!sizes) {
161
+ const texts =
162
+ element.kind === 'input'
163
+ ? [element.value, element.placeholder ?? '']
164
+ : 'text' in element
165
+ ? [element.text]
166
+ : 'accessible_label' in element && element.accessible_label !== undefined
167
+ ? [element.accessible_label]
168
+ : []
169
+ sizes = texts.map((text) => encoder.encode(text).byteLength)
170
+ textSizes.set(element, sizes)
171
+ }
172
+ return sizes
173
+ }
174
+
175
+ function textBytesOf(element: Element | undefined): number {
176
+ let bytes = 0
177
+ if (element) for (const size of textSizesOf(element)) bytes += size
178
+ return bytes
179
+ }
180
+
181
+ /**
182
+ * Text totals of a committed graph, kept current by commits and native edits
183
+ * so a batch checks the window budget without walking the window.
184
+ */
185
+ export class CommittedText {
186
+ bytes = 0
187
+ /** Committed nodes above the per-text limit; only a native edit leaves one. */
188
+ readonly oversized = new Set<number>()
189
+
190
+ constructor(
191
+ private readonly maxTextBytes: number,
192
+ nodes: Iterable<NodeState> = []
193
+ ) {
194
+ for (const node of nodes) this.replace(node.id, undefined, node.element)
195
+ }
196
+
197
+ /** Account node `id` holding `next` (absent once removed) instead of `previous`. */
198
+ replace(id: number, previous: Element | undefined, next: Element | undefined): void {
199
+ this.bytes += textBytesOf(next) - textBytesOf(previous)
200
+ if (next && textSizesOf(next).some((size) => size > this.maxTextBytes)) this.oversized.add(id)
201
+ else this.oversized.delete(id)
202
+ }
203
+ }
204
+
205
+ /**
206
+ * The candidate graph: this transaction's own node copies and removals over
207
+ * the committed map, which it never writes, so opening a batch costs nothing
208
+ * per window node.
209
+ */
210
+ class Overlay implements ReadonlyMap<number, NodeState> {
211
+ /** Nodes this transaction created or wrote; each is its own copy. */
212
+ readonly writes = new Map<number, NodeState>()
213
+ /** Committed nodes this transaction removed. */
214
+ readonly deletes = new Set<number>()
215
+ size: number
216
+
217
+ constructor(readonly base: ReadonlyMap<number, NodeState>) {
218
+ this.size = base.size
219
+ }
220
+
221
+ get(id: number): NodeState | undefined {
222
+ return this.writes.get(id) ?? (this.deletes.has(id) ? undefined : this.base.get(id))
223
+ }
224
+
225
+ has(id: number): boolean {
226
+ return this.get(id) !== undefined
227
+ }
228
+
229
+ /** Node IDs are never reused, so a removed node is never written again. */
230
+ write(node: NodeState): void {
231
+ if (!this.has(node.id)) this.size += 1
232
+ this.writes.set(node.id, node)
233
+ }
234
+
235
+ delete(id: number): void {
236
+ if (!this.has(id)) return
237
+ this.size -= 1
238
+ this.writes.delete(id)
239
+ if (this.base.has(id)) this.deletes.add(id)
240
+ }
241
+
242
+ /** Committed order, then created nodes in creation order, as a full copy had. */
243
+ *entries(): MapIterator<[number, NodeState]> {
244
+ for (const id of this.base.keys()) {
245
+ const node = this.get(id)
246
+ if (node) yield [id, node]
247
+ }
248
+ for (const entry of this.writes) if (!this.base.has(entry[0])) yield entry
249
+ }
250
+
251
+ *keys(): MapIterator<number> {
252
+ for (const [id] of this.entries()) yield id
253
+ }
254
+
255
+ *values(): MapIterator<NodeState> {
256
+ for (const [, node] of this.entries()) yield node
257
+ }
258
+
259
+ [Symbol.iterator](): MapIterator<[number, NodeState]> {
260
+ return this.entries()
261
+ }
262
+
263
+ forEach(
264
+ callback: (node: NodeState, id: number, map: ReadonlyMap<number, NodeState>) => void
265
+ ): void {
266
+ for (const [id, node] of this.entries()) callback(node, id, this)
267
+ }
268
+ }
269
+
270
+ /**
271
+ * A bounded candidate graph; native preflight remains authoritative. Nodes are
272
+ * shared with the committed graph until this transaction first writes one.
273
+ */
274
+ export class Transaction implements NativeBatch {
275
+ readonly nodes: Overlay
276
+ readonly operations: Operation[] = []
277
+ private readonly requests: Request[] = []
278
+ /** Created and moved nodes: the only places a batch can break ownership or depth. */
279
+ private readonly attached: number[] = []
280
+ private active = true
281
+
282
+ /** `text` describes `current`, and both stay unchanged until `commit`. */
283
+ constructor(
284
+ current: ReadonlyMap<number, NodeState>,
285
+ private readonly rootId: number,
286
+ private readonly allocateId: () => number,
287
+ private readonly limits: Readonly<Limits>,
288
+ private readonly capabilities: readonly Capability[],
289
+ private readonly text: CommittedText
290
+ ) {
291
+ this.nodes = new Overlay(current)
292
+ }
293
+
294
+ /** The candidate's own copy of a node, made on its first write. */
295
+ private writable(node: NodeState): NodeState {
296
+ const written = this.nodes.writes.get(node.id)
297
+ if (written) return written
298
+ const copy = { ...node, children: [...node.children] }
299
+ this.nodes.write(copy)
300
+ return copy
301
+ }
302
+
303
+ private check(): void {
304
+ if (!this.active)
305
+ throw new NativeStateError('invalid_state', 'Batch callback has already returned')
306
+ if (this.operations.length >= logicalOperationLimit(this.limits))
307
+ throw new NativeStateError('limit_exceeded', 'Batch operation limit exceeded')
308
+ }
309
+
310
+ finish(): void {
311
+ this.active = false
312
+ }
313
+
314
+ create<E extends Element>(element: E): NativeNode<E['kind']> {
315
+ this.check()
316
+ if (this.nodes.size >= this.limits.max_nodes_per_window)
317
+ throw new NativeStateError('limit_exceeded', 'Window node limit exceeded')
318
+ const normalized = supported(normalize(element), this.capabilities)
319
+ const node = makeNode(this.allocateId(), normalized)
320
+ this.nodes.write(node)
321
+ this.attached.push(node.id)
322
+ this.operations.push({ type: 'create', node_id: node.id, element: node.element })
323
+ return node.handle as NativeNode<E['kind']>
324
+ }
325
+
326
+ set(
327
+ node: NativeNode<'input'>,
328
+ element: Extract<Element, { kind: 'input' }>,
329
+ expectedInputRevision: number
330
+ ): void
331
+ set<K extends Exclude<ElementKind, 'input'>>(
332
+ node: NativeNode<K>,
333
+ element: Extract<Element, { kind: NoInfer<K> }>
334
+ ): void
335
+ set(handle: NativeNode, value: Element, expectedInputRevision?: number): void {
336
+ this.check()
337
+ const node = this.writable(own(this.nodes, handle))
338
+ const element = supported(normalize(value), this.capabilities)
339
+ if (element.kind !== node.element.kind)
340
+ throw new NativeStateError(
341
+ 'invalid_state',
342
+ 'Element kind cannot change; create a replacement node'
343
+ )
344
+ if (element.kind === 'input') {
345
+ if (
346
+ !Number.isSafeInteger(expectedInputRevision) ||
347
+ expectedInputRevision !== node.inputRevision
348
+ )
349
+ throw new NativeStateError(
350
+ 'stale_revision',
351
+ 'Input update requires its current observed revision'
352
+ )
353
+ if (node.inputRevision === Number.MAX_SAFE_INTEGER)
354
+ throw new NativeStateError('limit_exceeded', 'Input revision exhausted')
355
+ this.operations.push({
356
+ type: 'set',
357
+ node_id: node.id,
358
+ element,
359
+ expected_input_revision: node.inputRevision,
360
+ })
361
+ node.inputRevision += 1
362
+ } else {
363
+ if (expectedInputRevision !== undefined)
364
+ throw new NativeStateError('invalid_state', 'Only an input accepts an edit revision')
365
+ this.operations.push({ type: 'set', node_id: node.id, element })
366
+ }
367
+ node.element = element
368
+ // An overlay's surface decides what its subtree may hold.
369
+ if (element.kind === 'overlay') this.attached.push(node.id)
370
+ }
371
+
372
+ insert(parentHandle: NativeNode<ContainerKind>, childHandle: NativeNode, index: number): void {
373
+ this.check()
374
+ let parent = own(this.nodes, parentHandle)
375
+ let child = own(this.nodes, childHandle)
376
+ if (!isContainer(parent.element) || child.id === this.rootId)
377
+ throw new NativeStateError(
378
+ 'invalid_state',
379
+ 'Only boxes, splits and overlays accept children and the root cannot move'
380
+ )
381
+ let ancestor: NodeState | undefined = parent
382
+ while (ancestor) {
383
+ if (ancestor.id === child.id)
384
+ throw new NativeStateError('invalid_state', 'Native tree cannot contain a cycle')
385
+ ancestor = ancestor.parent === undefined ? undefined : this.nodes.get(ancestor.parent)
386
+ }
387
+ const length = parent.children.length - (child.parent === parent.id ? 1 : 0)
388
+ if (!Number.isSafeInteger(index) || index < 0 || index > length)
389
+ throw new NativeStateError('invalid_state', 'Child insertion index is out of range')
390
+ child = this.writable(child)
391
+ if (child.parent !== undefined) {
392
+ const previous = this.writable(this.nodes.get(child.parent)!)
393
+ previous.children.splice(previous.children.indexOf(child.id), 1)
394
+ }
395
+ parent = this.writable(parent)
396
+ parent.children.splice(index, 0, child.id)
397
+ child.parent = parent.id
398
+ this.attached.push(child.id)
399
+ this.operations.push({ type: 'insert', parent_id: parent.id, child_id: child.id, index })
400
+ }
401
+
402
+ append(parentHandle: NativeNode<ContainerKind>, childHandle: NativeNode): void {
403
+ const parent = own(this.nodes, parentHandle)
404
+ const child = own(this.nodes, childHandle)
405
+ this.insert(
406
+ parentHandle,
407
+ childHandle,
408
+ parent.children.length - (child.parent === parent.id ? 1 : 0)
409
+ )
410
+ }
411
+
412
+ remove(handle: NativeNode): void {
413
+ this.check()
414
+ const node = own(this.nodes, handle)
415
+ if (node.id === this.rootId)
416
+ throw new NativeStateError('invalid_state', 'Close the window to dispose its root')
417
+ if (node.parent !== undefined) {
418
+ const parent = this.writable(this.nodes.get(node.parent)!)
419
+ parent.children.splice(parent.children.indexOf(node.id), 1)
420
+ }
421
+ const pending = [node.id]
422
+ for (const id of pending) {
423
+ const child = this.nodes.get(id)!
424
+ pending.push(...child.children)
425
+ this.nodes.delete(id)
426
+ }
427
+ this.operations.push({ type: 'delete', node_id: node.id })
428
+ }
429
+
430
+ focus(handle: NativeNode<'button' | 'input'>): void {
431
+ this.check()
432
+ requireCapability(this.capabilities, 'focus_v1', 'operation:focus')
433
+ const node = own(this.nodes, handle)
434
+ this.requests.push({ type: 'focus', id: node.id })
435
+ this.operations.push({ type: 'focus', node_id: node.id })
436
+ }
437
+
438
+ scrollTo(handle: NativeNode<ContainerKind>, offset: ScrollOffset): void {
439
+ this.check()
440
+ requireCapability(this.capabilities, 'scroll_control_v1', 'operation:scroll_to')
441
+ const node = own(this.nodes, handle)
442
+ if (offset === null || typeof offset !== 'object')
443
+ throw new TypeError('A scroll offset must be an object')
444
+ const axes: { x?: number; y?: number } = {}
445
+ for (const axis of ['x', 'y'] as const) {
446
+ const value = offset[axis]
447
+ if (value === undefined) continue
448
+ if (
449
+ typeof value !== 'number' ||
450
+ !Number.isFinite(value) ||
451
+ value < 0 ||
452
+ value > MAX_SCROLL_OFFSET
453
+ )
454
+ throw new RangeError('Scroll offsets must be finite and between 0 and ' + MAX_SCROLL_OFFSET)
455
+ axes[axis] = value
456
+ }
457
+ if (axes.x === undefined && axes.y === undefined)
458
+ throw new TypeError('A scroll offset requires x or y')
459
+ this.requests.push({ type: 'scroll_to', id: node.id, ...axes })
460
+ this.operations.push({ type: 'scroll_to', node_id: node.id, ...axes })
461
+ }
462
+
463
+ scrollIntoView(handle: NativeNode): void {
464
+ this.check()
465
+ requireCapability(this.capabilities, 'scroll_control_v1', 'operation:scroll_into_view')
466
+ const node = own(this.nodes, handle)
467
+ this.requests.push({ type: 'scroll_into_view', id: node.id })
468
+ this.operations.push({ type: 'scroll_into_view', node_id: node.id })
469
+ }
470
+
471
+ /** The modal overlay highest in paint order: deepest, then later in tree order. */
472
+ private activeModal(): number | undefined {
473
+ let active: { depth: number; id: number } | undefined
474
+ const pending = [{ id: this.rootId, outer: 0 }]
475
+ while (pending.length) {
476
+ const { id, outer } = pending.pop()!
477
+ const node = this.nodes.get(id)!
478
+ let depth = outer
479
+ if (node.element.kind === 'overlay') {
480
+ depth += 1
481
+ if (node.element.modal && (!active || depth >= active.depth)) active = { depth, id }
482
+ }
483
+ for (let index = node.children.length - 1; index >= 0; index -= 1)
484
+ pending.push({ id: node.children[index]!, outer: depth })
485
+ }
486
+ return active?.id
487
+ }
488
+
489
+ private validateRequests(): void {
490
+ for (const request of this.requests) {
491
+ const node = this.nodes.get(request.id)
492
+ if (!node)
493
+ throw new NativeStateError('invalid_handle', 'Request target is removed by this batch')
494
+ const element = node.element
495
+ if (request.type === 'focus') {
496
+ if ((element.kind !== 'input' && element.kind !== 'button') || element.disabled === true)
497
+ throw new NativeStateError(
498
+ 'invalid_state',
499
+ 'Only an enabled button or an enabled input can take focus'
500
+ )
501
+ const modal = this.activeModal()
502
+ let ancestor: NodeState | undefined = node
503
+ while (modal !== undefined && ancestor && ancestor.id !== modal)
504
+ ancestor = ancestor.parent === undefined ? undefined : this.nodes.get(ancestor.parent)
505
+ if (modal !== undefined && !ancestor)
506
+ throw new NativeStateError(
507
+ 'invalid_state',
508
+ 'Focus target is outside the active modal overlay'
509
+ )
510
+ } else if (request.type === 'scroll_to') {
511
+ const overflow = isContainer(element) ? element.style?.overflow : undefined
512
+ const horizontal = overflow === 'scroll_x' || overflow === 'scroll'
513
+ const vertical = overflow === 'scroll_y' || overflow === 'scroll'
514
+ if ((request.x !== undefined && !horizontal) || (request.y !== undefined && !vertical))
515
+ throw new NativeStateError(
516
+ 'invalid_state',
517
+ 'scrollTo requires a container scrolling on each given axis'
518
+ )
519
+ }
520
+ }
521
+ }
522
+
523
+ /**
524
+ * Give created nodes the identities in `identity` (old to new) before a
525
+ * staged commit (see commit-plan.ts). Their handles were never committed,
526
+ * and only this transaction's own copies can name a created node.
527
+ */
528
+ renumber(identity: ReadonlyMap<number, number>): void {
529
+ const { writes } = this.nodes
530
+ const map = (id: number) => identity.get(id) ?? id
531
+ const written = [...writes.values()]
532
+ for (const id of identity.keys()) writes.delete(id)
533
+ for (const node of written) {
534
+ const next = map(node.id)
535
+ if (next !== node.id) {
536
+ identities.set(node.handle, next)
537
+ node.id = next
538
+ }
539
+ if (node.parent !== undefined) node.parent = map(node.parent)
540
+ node.children = node.children.map(map)
541
+ writes.set(next, node)
542
+ }
543
+ }
544
+
545
+ /** The candidate's window text bytes, from the committed total and this batch's writes. */
546
+ private textBytes(): number {
547
+ const { base, writes, deletes } = this.nodes
548
+ let bytes = this.text.bytes
549
+ for (const [id, node] of writes)
550
+ bytes += textBytesOf(node.element) - textBytesOf(base.get(id)?.element)
551
+ for (const id of deletes) bytes -= textBytesOf(base.get(id)?.element)
552
+ return bytes
553
+ }
554
+
555
+ /**
556
+ * The committed graph was valid, and create, insert and remove keep parent
557
+ * and child links consistent and reject cycles. A batch can then break depth
558
+ * or attachment only at or below a node it created or moved, and a text
559
+ * limit only through a node it wrote. When none of those can fail, the batch
560
+ * is valid without walking the window; otherwise the whole-graph walk runs
561
+ * to report the first failure in its own order.
562
+ */
563
+ validate(): void {
564
+ const { limits, nodes } = this
565
+ if (this.text.oversized.size || this.textBytes() > limits.max_text_bytes_per_window)
566
+ return this.walk()
567
+ for (const node of nodes.writes.values())
568
+ for (const size of textSizesOf(node.element))
569
+ if (size > limits.max_text_bytes) return this.walk()
570
+ const seen = new Set<number>()
571
+ // Flat (id, depth) pairs.
572
+ const pending: number[] = []
573
+ for (const id of this.attached) {
574
+ let top = nodes.get(id)
575
+ if (!top || seen.has(id)) continue
576
+ let depth = 0
577
+ if (layered(top.element)) return this.walk()
578
+ while (top.parent !== undefined) {
579
+ top = nodes.get(top.parent)!
580
+ if (layered(top.element)) return this.walk()
581
+ depth += 1
582
+ }
583
+ if (top.id !== this.rootId) return this.walk()
584
+ pending.push(id, depth)
585
+ while (pending.length) {
586
+ const level = pending.pop()!
587
+ const next = pending.pop()!
588
+ if (level > limits.max_depth) return this.walk()
589
+ if (seen.has(next)) continue
590
+ seen.add(next)
591
+ const state = nodes.get(next)!
592
+ if (layered(state.element)) return this.walk()
593
+ for (const child of state.children) pending.push(child, level + 1)
594
+ }
595
+ }
596
+ this.validateRequests()
597
+ }
598
+
599
+ private walk(): void {
600
+ let seen = 0
601
+ let bytes = 0
602
+ // `popup` marks content beneath a popup window surface: keyboard focus
603
+ // stays on the parent window, so it holds no editor or further layer.
604
+ const pending = [{ id: this.rootId, depth: 0, overlays: 0, popup: false }]
605
+ for (const { id, depth, overlays: outer, popup: inPopup } of pending) {
606
+ if (depth > this.limits.max_depth)
607
+ throw new NativeStateError('limit_exceeded', 'Native tree depth limit exceeded')
608
+ const node = this.nodes.get(id)!
609
+ seen += 1
610
+ const element = node.element
611
+ if (element.kind === 'split' && node.children.length > 2)
612
+ throw new NativeStateError('limit_exceeded', 'A split owns at most two panes')
613
+ const overlays = outer + (element.kind === 'overlay' ? 1 : 0)
614
+ if (overlays > MAX_OVERLAY_DEPTH)
615
+ throw new NativeStateError('limit_exceeded', 'Overlay nesting limit exceeded')
616
+ if (inPopup && (element.kind === 'input' || element.kind === 'overlay'))
617
+ throw new NativeStateError(
618
+ 'invalid_state',
619
+ 'Popup window content cannot contain inputs or overlays'
620
+ )
621
+ const popup = inPopup || (element.kind === 'overlay' && element.surface === 'window')
622
+ for (const size of textSizesOf(element)) {
623
+ if (size > this.limits.max_text_bytes)
624
+ throw new NativeStateError('limit_exceeded', 'Native text limit exceeded')
625
+ bytes += size
626
+ }
627
+ if (bytes > this.limits.max_text_bytes_per_window)
628
+ throw new NativeStateError('limit_exceeded', 'Window text memory limit exceeded')
629
+ pending.push(
630
+ ...node.children.map((child) => ({ id: child, depth: depth + 1, overlays, popup }))
631
+ )
632
+ }
633
+ if (seen !== this.nodes.size)
634
+ throw new NativeStateError(
635
+ 'invalid_state',
636
+ 'Every created node must be attached before commit'
637
+ )
638
+ this.validateRequests()
639
+ }
640
+
641
+ /**
642
+ * Apply this validated, acknowledged batch to the committed graph and text
643
+ * totals it was opened over, in time proportional to the batch.
644
+ */
645
+ commit(nodes: Map<number, NodeState>, text: CommittedText): void {
646
+ if (nodes !== this.nodes.base || text !== this.text)
647
+ throw new NativeStateError(
648
+ 'invalid_state',
649
+ 'Batch commits only to the graph it was opened on'
650
+ )
651
+ for (const id of this.nodes.deletes) {
652
+ text.replace(id, nodes.get(id)?.element, undefined)
653
+ nodes.delete(id)
654
+ }
655
+ for (const [id, candidate] of this.nodes.writes) {
656
+ const current = nodes.get(id)
657
+ // Native input can arrive while an unrelated batch is in flight. Preserve
658
+ // every newer edit instead of replacing it with a cloned candidate value.
659
+ if (
660
+ current &&
661
+ current.inputRevision > candidate.inputRevision &&
662
+ current.element.kind === 'input' &&
663
+ candidate.element.kind === 'input'
664
+ ) {
665
+ candidate.inputRevision = current.inputRevision
666
+ candidate.element = { ...candidate.element, value: current.element.value }
667
+ }
668
+ text.replace(id, current?.element, candidate.element)
669
+ nodes.set(id, candidate)
670
+ }
671
+ }
672
+ }