@bun-native/protocol 0.33.0 → 0.33.2

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/elements.ts CHANGED
@@ -1,57 +1,25 @@
1
1
  import { ProtocolError } from './framing.ts'
2
- import { integer, keys, number, object, string } from './values.ts'
2
+ import { choice, integer, keys, number, object, string } from './values.ts'
3
+ import {
4
+ ACCESSIBLE_ROLES,
5
+ ELEMENT_KEYS,
6
+ LIVE_POLITENESS,
7
+ MAX_ACCESSIBLE_SET_SIZE,
8
+ OVERLAY_ANCHORS,
9
+ OVERLAY_NAVIGATIONS,
10
+ OVERLAY_SURFACES,
11
+ STYLE_FIELDS,
12
+ type AccessibleRole,
13
+ type Live,
14
+ type Style,
15
+ } from './wire-schema.ts'
3
16
 
4
- export interface Style {
5
- direction?: 'row' | 'column'
6
- gap?: number
7
- padding?: number
8
- width?: number | 'fill'
9
- height?: number | 'fill'
10
- min_width?: number
11
- max_width?: number
12
- min_height?: number
13
- max_height?: number
14
- flex_grow?: number
15
- flex_shrink?: number
16
- align_items?: 'start' | 'center' | 'end' | 'stretch'
17
- justify_content?: 'start' | 'center' | 'end' | 'space_between' | 'space_around' | 'space_evenly'
18
- overflow?: 'visible' | 'hidden' | 'scroll_x' | 'scroll_y' | 'scroll'
19
- /** Requires `scroll_y` or `scroll`. `end` keeps a viewport already at its end pinned there. */
20
- scroll_anchor?: 'start' | 'end'
21
- background?: number
22
- color?: number
23
- font_size?: number
24
- /** `style_decoration_v1`: one uniform border width, 0–64 logical pixels. */
25
- border_width?: number
26
- /** `style_decoration_v1`: unsigned 24-bit RGB. */
27
- border_color?: number
28
- /** `style_decoration_v1`: one radius for every corner, 0–4,096 logical pixels. */
29
- corner_radius?: number
30
- /** `style_decoration_v1`: 0–1, multiplying descendants too. */
31
- opacity?: number
32
- /** `style_decoration_v1`: inherited 100–900 in steps of 100. */
33
- font_weight?: 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
34
- }
17
+ export type { Style }
35
18
 
36
19
  type LeafStyle = Omit<Style, 'overflow' | 'scroll_anchor'> & { overflow?: 'visible' | 'hidden' }
37
20
  /** A split's `direction` selects its axis; gap, alignment and scrolling do not apply. */
38
21
  export type SplitStyle = Omit<LeafStyle, 'gap' | 'align_items' | 'justify_content'>
39
22
 
40
- /** Main-axis thickness of the host-drawn split divider, in logical pixels. */
41
- export const SPLIT_DIVIDER = 6
42
-
43
- /** Style fields that require `style_decoration_v1`. */
44
- export const DECORATION_FIELDS = Object.freeze([
45
- 'border_width',
46
- 'border_color',
47
- 'corner_radius',
48
- 'opacity',
49
- 'font_weight',
50
- ] as const)
51
-
52
- /** Overlays nested inside overlays, the outermost counting as one. */
53
- export const MAX_OVERLAY_DEPTH = 8
54
-
55
23
  /** Requires the `overlay_keyboard_v1` capability; defaults are omitted when normalized. */
56
24
  export interface OverlayKeyboard {
57
25
  /** Focus the layer's first enabled control when it opens. */
@@ -103,9 +71,6 @@ export interface AccessibleLabel {
103
71
  accessible_label?: string
104
72
  }
105
73
 
106
- /** The largest `accessible_set_size` and `accessible_position`. */
107
- export const MAX_ACCESSIBLE_SET_SIZE = 2_147_483_647
108
-
109
74
  /**
110
75
  * Requires `accessibility_lists_v1`. A box without `accessible_role` is layout
111
76
  * only and has no accessible node. A list's `accessible_set_size` counts every
@@ -113,7 +78,7 @@ export const MAX_ACCESSIBLE_SET_SIZE = 2_147_483_647
113
78
  * in that full set, so assistive technology knows a windowed list's extent.
114
79
  */
115
80
  export interface BoxAccessibility {
116
- accessible_role?: 'list' | 'list_item'
81
+ accessible_role?: AccessibleRole
117
82
  /** Only with a role: the list's or item's accessible name. */
118
83
  accessible_label?: string
119
84
  /** Only on a `list`. */
@@ -133,7 +98,7 @@ export type Element =
133
98
  * Requires `accessibility_lists_v1`: announce the text when the node
134
99
  * appears and whenever it changes.
135
100
  */
136
- accessible_live?: 'polite' | 'assertive'
101
+ accessible_live?: Live
137
102
  style?: LeafStyle
138
103
  }
139
104
  | { kind: 'button'; text: string; disabled?: boolean; style?: LeafStyle }
@@ -155,99 +120,55 @@ export type Element =
155
120
  | ({ kind: 'split'; ratio?: number; min_size?: number; style?: SplitStyle } & AccessibleLabel)
156
121
  | OverlayElement
157
122
 
158
- function choice<T extends string>(value: unknown, name: string, values: readonly T[]): T {
159
- for (const candidate of values) if (candidate === value) return candidate
160
- throw new ProtocolError(name + ' must be one of ' + values.join(', '))
161
- }
162
-
163
123
  function requireLeafStyle(style: Style): asserts style is LeafStyle {
164
124
  if (style.overflow !== undefined && style.overflow !== 'visible' && style.overflow !== 'hidden')
165
125
  throw new ProtocolError('Scrolling is supported only on box and overlay elements')
166
126
  }
167
127
 
128
+ /**
129
+ * One pass over the members present, each checked by its generated field
130
+ * description. Inherited properties are ignored, as `keys` ignores them.
131
+ */
168
132
  function parseStyle(value: unknown): Style {
169
133
  const data = object(value)
170
- keys(data, [
171
- 'direction',
172
- 'gap',
173
- 'padding',
174
- 'width',
175
- 'height',
176
- 'min_width',
177
- 'max_width',
178
- 'min_height',
179
- 'max_height',
180
- 'flex_grow',
181
- 'flex_shrink',
182
- 'align_items',
183
- 'justify_content',
184
- 'overflow',
185
- 'scroll_anchor',
186
- 'background',
187
- 'color',
188
- 'font_size',
189
- ...DECORATION_FIELDS,
190
- ])
191
- const style: Style = {}
192
- for (const key of ['gap', 'padding'] as const)
193
- if (key in data) style[key] = number(data[key], key, 0, 4_096)
194
- for (const key of ['width', 'height'] as const)
195
- if (key in data) style[key] = data[key] === 'fill' ? 'fill' : number(data[key], key, 0, 16_384)
196
- for (const key of ['min_width', 'max_width', 'min_height', 'max_height'] as const)
197
- if (key in data) style[key] = number(data[key], key, 0, 16_384)
134
+ const style: Record<string, unknown> = {}
135
+ for (const key of Object.keys(data)) {
136
+ const field = STYLE_FIELDS.get(key)
137
+ if (field === undefined) throw new ProtocolError('Unknown message property: ' + key)
138
+ const member = data[key]
139
+ switch (field.type) {
140
+ case 'number':
141
+ style[key] = number(member, key, field.min, field.max)
142
+ break
143
+ case 'dimension':
144
+ style[key] = member === 'fill' ? 'fill' : number(member, key, field.min, field.max)
145
+ break
146
+ case 'color':
147
+ style[key] = integer(member, key, 0, 0xff_ffff)
148
+ break
149
+ case 'enum':
150
+ style[key] = choice(member, key, field.values)
151
+ break
152
+ case 'weight':
153
+ style[key] = integer(member, key, field.min, field.max)
154
+ if ((style[key] as number) % field.step !== 0)
155
+ throw new ProtocolError(key + ' must be a multiple of ' + field.step)
156
+ }
157
+ }
158
+ const parsed = style as Style
198
159
  for (const [minimum, maximum] of [
199
- [style.min_width, style.max_width],
200
- [style.min_height, style.max_height],
160
+ [parsed.min_width, parsed.max_width],
161
+ [parsed.min_height, parsed.max_height],
201
162
  ])
202
163
  if (minimum !== undefined && maximum !== undefined && minimum > maximum)
203
164
  throw new ProtocolError('Minimum size must not exceed maximum size')
204
- for (const key of ['background', 'color', 'border_color'] as const)
205
- if (key in data) style[key] = integer(data[key], key, 0, 0xff_ffff)
206
- if ('direction' in data)
207
- style.direction = choice(data['direction'], 'direction', ['row', 'column'])
208
- for (const key of ['flex_grow', 'flex_shrink'] as const)
209
- if (key in data) style[key] = number(data[key], key, 0, 1_000)
210
- if ('align_items' in data)
211
- style.align_items = choice(data['align_items'], 'align_items', [
212
- 'start',
213
- 'center',
214
- 'end',
215
- 'stretch',
216
- ])
217
- if ('justify_content' in data)
218
- style.justify_content = choice(data['justify_content'], 'justify_content', [
219
- 'start',
220
- 'center',
221
- 'end',
222
- 'space_between',
223
- 'space_around',
224
- 'space_evenly',
225
- ])
226
- if ('overflow' in data)
227
- style.overflow = choice(data['overflow'], 'overflow', [
228
- 'visible',
229
- 'hidden',
230
- 'scroll_x',
231
- 'scroll_y',
232
- 'scroll',
233
- ])
234
- if ('scroll_anchor' in data) {
235
- style.scroll_anchor = choice(data['scroll_anchor'], 'scroll_anchor', ['start', 'end'])
236
- if (style.overflow !== 'scroll_y' && style.overflow !== 'scroll')
237
- throw new ProtocolError('scroll_anchor requires vertical scrolling overflow')
238
- }
239
- if ('font_size' in data) style.font_size = number(data['font_size'], 'font_size', 1, 512)
240
- if ('border_width' in data)
241
- style.border_width = number(data['border_width'], 'border_width', 0, 64)
242
- if ('corner_radius' in data)
243
- style.corner_radius = number(data['corner_radius'], 'corner_radius', 0, 4_096)
244
- if ('opacity' in data) style.opacity = number(data['opacity'], 'opacity', 0, 1)
245
- if ('font_weight' in data) {
246
- const weight = integer(data['font_weight'], 'font_weight', 100, 900)
247
- if (weight % 100 !== 0) throw new ProtocolError('font_weight must be a multiple of 100')
248
- style.font_weight = weight as NonNullable<Style['font_weight']>
249
- }
250
- return style
165
+ if (
166
+ parsed.scroll_anchor !== undefined &&
167
+ parsed.overflow !== 'scroll_y' &&
168
+ parsed.overflow !== 'scroll'
169
+ )
170
+ throw new ProtocolError('scroll_anchor requires vertical scrolling overflow')
171
+ return parsed
251
172
  }
252
173
 
253
174
  function accessibleLabel(element: Record<string, unknown>): AccessibleLabel {
@@ -268,7 +189,7 @@ function boxAccessibility(element: Record<string, unknown>): BoxAccessibility {
268
189
  if (name in element) throw new ProtocolError(name + ' requires accessible_role')
269
190
  return {}
270
191
  }
271
- const role = choice(element['accessible_role'], 'accessible_role', ['list', 'list_item'])
192
+ const role = choice(element['accessible_role'], 'accessible_role', ACCESSIBLE_ROLES)
272
193
  if (role === 'list') {
273
194
  for (const name of ['accessible_position', 'accessible_selected'])
274
195
  if (name in element) throw new ProtocolError(name + ' is only accepted on a list_item')
@@ -310,40 +231,53 @@ function boxAccessibility(element: Record<string, unknown>): BoxAccessibility {
310
231
  }
311
232
  }
312
233
 
313
- /** Normalize and validate the entire property set, including JavaScript consumers. */
234
+ /**
235
+ * Elements this module produced. Each is frozen with its style, so it is still
236
+ * exactly the normalized value that passed validation.
237
+ */
238
+ const parsed = new WeakSet<Element>()
239
+
240
+ /**
241
+ * Normalize and validate the entire property set, including JavaScript consumers.
242
+ *
243
+ * The result is frozen and returned unchanged when parsed again, so core's
244
+ * normalized elements cross the runtime boundary in O(1). Any other value,
245
+ * including an unfrozen copy of a parsed element, is validated in full.
246
+ */
314
247
  export function parseElement(value: unknown): Element {
248
+ if (parsed.has(value as Element)) return value as Element
249
+ const element = validElement(value)
250
+ Object.freeze(element.style)
251
+ parsed.add(Object.freeze(element))
252
+ return element
253
+ }
254
+
255
+ function validElement(value: unknown): Element {
315
256
  const element = object(value)
316
257
  const style = 'style' in element ? parseStyle(element['style']) : {}
317
258
  switch (element['kind']) {
318
259
  case 'box':
319
- keys(element, [
320
- 'kind',
321
- 'accessible_role',
322
- 'accessible_label',
323
- 'accessible_set_size',
324
- 'accessible_position',
325
- 'accessible_selected',
326
- 'style',
327
- ])
260
+ keys(element, ELEMENT_KEYS.box)
328
261
  return { kind: 'box', ...boxAccessibility(element), style }
329
262
  case 'text':
330
- keys(element, ['kind', 'text', 'accessible_live', 'style'])
263
+ keys(element, ELEMENT_KEYS.text)
331
264
  requireLeafStyle(style)
332
265
  return {
333
266
  kind: 'text',
334
267
  text: string(element['text'], 'text'),
335
268
  ...('accessible_live' in element
336
269
  ? {
337
- accessible_live: choice(element['accessible_live'], 'accessible_live', [
338
- 'polite',
339
- 'assertive',
340
- ]),
270
+ accessible_live: choice(
271
+ element['accessible_live'],
272
+ 'accessible_live',
273
+ LIVE_POLITENESS
274
+ ),
341
275
  }
342
276
  : {}),
343
277
  style,
344
278
  }
345
279
  case 'button': {
346
- keys(element, ['kind', 'text', 'disabled', 'style'])
280
+ keys(element, ELEMENT_KEYS.button)
347
281
  requireLeafStyle(style)
348
282
  if ('disabled' in element && typeof element['disabled'] !== 'boolean')
349
283
  throw new ProtocolError('disabled must be a boolean')
@@ -355,7 +289,7 @@ export function parseElement(value: unknown): Element {
355
289
  }
356
290
  }
357
291
  case 'input': {
358
- keys(element, ['kind', 'value', 'placeholder', 'disabled', 'read_only', 'style'])
292
+ keys(element, ELEMENT_KEYS.input)
359
293
  requireLeafStyle(style)
360
294
  for (const name of ['disabled', 'read_only'])
361
295
  if (name in element && typeof element[name] !== 'boolean')
@@ -371,7 +305,7 @@ export function parseElement(value: unknown): Element {
371
305
  }
372
306
  }
373
307
  case 'split': {
374
- keys(element, ['kind', 'ratio', 'min_size', 'accessible_label', 'style'])
308
+ keys(element, ELEMENT_KEYS.split)
375
309
  requireLeafStyle(style)
376
310
  if (
377
311
  style.gap !== undefined ||
@@ -388,19 +322,10 @@ export function parseElement(value: unknown): Element {
388
322
  }
389
323
  }
390
324
  case 'overlay': {
391
- keys(element, [
392
- 'kind',
393
- 'anchor',
394
- 'modal',
395
- 'surface',
396
- 'autofocus',
397
- 'navigation',
398
- 'accessible_label',
399
- 'style',
400
- ])
325
+ keys(element, ELEMENT_KEYS.overlay)
401
326
  const label = accessibleLabel(element)
402
327
  const anchor =
403
- 'anchor' in element ? choice(element['anchor'], 'anchor', ['window', 'parent']) : 'window'
328
+ 'anchor' in element ? choice(element['anchor'], 'anchor', OVERLAY_ANCHORS) : 'window'
404
329
  for (const flag of ['modal', 'autofocus'])
405
330
  if (flag in element && typeof element[flag] !== 'boolean')
406
331
  throw new ProtocolError(flag + ' must be a boolean')
@@ -408,12 +333,12 @@ export function parseElement(value: unknown): Element {
408
333
  const keyboard: OverlayKeyboard = {
409
334
  ...(element['autofocus'] === true ? { autofocus: true } : {}),
410
335
  ...('navigation' in element &&
411
- choice(element['navigation'], 'navigation', ['tab', 'menu']) === 'menu'
336
+ choice(element['navigation'], 'navigation', OVERLAY_NAVIGATIONS) === 'menu'
412
337
  ? { navigation: 'menu' as const }
413
338
  : {}),
414
339
  }
415
340
  const surface =
416
- 'surface' in element ? choice(element['surface'], 'surface', ['layer', 'window']) : 'layer'
341
+ 'surface' in element ? choice(element['surface'], 'surface', OVERLAY_SURFACES) : 'layer'
417
342
  if (surface === 'window') {
418
343
  if (anchor !== 'parent')
419
344
  throw new ProtocolError('A popup window overlay must be anchored to its parent')
package/src/files.ts CHANGED
@@ -1,14 +1,17 @@
1
1
  import { ProtocolError } from './framing.ts'
2
2
  import { integer, keys, object, string } from './values.ts'
3
+ import {
4
+ MAX_DIRECTORY_ENTRIES,
5
+ MAX_FILESYSTEM_ROOTS,
6
+ MAX_FILE_CHUNK_BYTES,
7
+ MAX_FILE_NAME_BYTES,
8
+ MAX_FILE_PATH_BYTES,
9
+ MAX_FILE_PATH_COMPONENTS,
10
+ MAX_ROOT_ID_BYTES,
11
+ MAX_ROOT_PATH_BYTES,
12
+ PAYLOAD_KEYS,
13
+ } from './wire-schema.ts'
3
14
 
4
- export const MAX_FILESYSTEM_ROOTS = 8
5
- export const MAX_FILE_GRANTS = 32
6
- const MAX_FILE_PATH_BYTES = 1_024
7
- const MAX_FILE_PATH_COMPONENTS = 32
8
- const MAX_FILE_NAME_BYTES = 255
9
- const MAX_ROOT_PATH_BYTES = 4_096
10
- export const MAX_FILE_CHUNK_BYTES = 16_384
11
- export const MAX_DIRECTORY_ENTRIES = 64
12
15
  const MAX_FILE_CHUNK_BASE64 = Math.ceil(MAX_FILE_CHUNK_BYTES / 3) * 4
13
16
  const FILESYSTEM_ROOT_ARGUMENT = '--bun-native-filesystem-root='
14
17
  const encoder = new TextEncoder()
@@ -45,10 +48,12 @@ export type FileResult =
45
48
  | { kind: 'written'; bytes: number }
46
49
  | { kind: 'done' }
47
50
 
51
+ const ROOT_ID = new RegExp(`^[a-z][a-z0-9_-]{0,${MAX_ROOT_ID_BYTES - 1}}$`)
52
+
48
53
  export function parseRootId(value: unknown): string {
49
- if (typeof value !== 'string' || !/^[a-z][a-z0-9_-]{0,31}$/.test(value))
54
+ if (typeof value !== 'string' || !ROOT_ID.test(value))
50
55
  throw new ProtocolError(
51
- 'Filesystem root ID must be 1-32 lowercase ASCII letters, digits, "-" or "_", starting with a letter'
56
+ `Filesystem root ID must be 1-${MAX_ROOT_ID_BYTES} lowercase ASCII letters, digits, "-" or "_", starting with a letter`
52
57
  )
53
58
  return value
54
59
  }
@@ -89,7 +94,7 @@ export function parseFileAccess(value: unknown): FileAccess {
89
94
 
90
95
  function root(value: unknown): FilesystemRoot {
91
96
  const data = object(value)
92
- keys(data, ['id', 'path', 'access'])
97
+ keys(data, PAYLOAD_KEYS.filesystem_root)
93
98
  return {
94
99
  id: parseRootId(data['id']),
95
100
  path: parseRootPath(data['path']),
@@ -167,15 +172,15 @@ export function parseFileOperation(value: unknown, path: string): FileOperation
167
172
  case 'stat':
168
173
  case 'create_directory':
169
174
  case 'remove':
170
- keys(data, ['kind'])
175
+ keys(data, PAYLOAD_KEYS.file_operation.stat)
171
176
  return { kind: data['kind'] }
172
177
  case 'list':
173
- keys(data, ['kind', 'after'])
178
+ keys(data, PAYLOAD_KEYS.file_operation.list)
174
179
  return 'after' in data
175
180
  ? { kind: 'list', after: parseFileName(data['after']) }
176
181
  : { kind: 'list' }
177
182
  case 'read':
178
- keys(data, ['kind', 'offset', 'length'])
183
+ keys(data, PAYLOAD_KEYS.file_operation.read)
179
184
  return {
180
185
  kind: 'read',
181
186
  offset: integer(
@@ -187,7 +192,7 @@ export function parseFileOperation(value: unknown, path: string): FileOperation
187
192
  length: integer(data['length'], 'file read length', 1, MAX_FILE_CHUNK_BYTES),
188
193
  }
189
194
  case 'write': {
190
- keys(data, ['kind', 'mode', 'data'])
195
+ keys(data, PAYLOAD_KEYS.file_operation.write)
191
196
  const mode = WRITE_MODES.find((item) => item === data['mode'])
192
197
  if (!mode) throw new ProtocolError('Unknown file write mode')
193
198
  return { kind: 'write', mode, data: parseChunk(data['data']) }
@@ -215,7 +220,7 @@ export function parseFileResult(value: unknown): FileResult {
215
220
  const data = object(value)
216
221
  switch (data['kind']) {
217
222
  case 'stat':
218
- keys(data, ['kind', 'file_kind', 'size', 'modified_ms'])
223
+ keys(data, PAYLOAD_KEYS.file_result.stat)
219
224
  return {
220
225
  kind: 'stat',
221
226
  file_kind: fileKind(data['file_kind']),
@@ -227,13 +232,13 @@ export function parseFileResult(value: unknown): FileResult {
227
232
  ),
228
233
  }
229
234
  case 'list': {
230
- keys(data, ['kind', 'entries', 'complete', 'omitted'])
235
+ keys(data, PAYLOAD_KEYS.file_result.list)
231
236
  const entries = data['entries']
232
237
  if (!Array.isArray(entries) || entries.length > MAX_DIRECTORY_ENTRIES)
233
238
  throw new ProtocolError('Directory page exceeds ' + MAX_DIRECTORY_ENTRIES + ' entries')
234
239
  const parsed = entries.map((entry) => {
235
240
  const item = object(entry)
236
- keys(item, ['name', 'kind'])
241
+ keys(item, PAYLOAD_KEYS.directory_entry)
237
242
  return { name: parseFileName(item['name']), kind: fileKind(item['kind']) }
238
243
  })
239
244
  for (let index = 1; index < parsed.length; index++)
@@ -249,18 +254,18 @@ export function parseFileResult(value: unknown): FileResult {
249
254
  }
250
255
  }
251
256
  case 'read':
252
- keys(data, ['kind', 'data', 'end_of_file'])
257
+ keys(data, PAYLOAD_KEYS.file_result.read)
253
258
  if (typeof data['end_of_file'] !== 'boolean')
254
259
  throw new ProtocolError('File end-of-file flag must be a boolean')
255
260
  return { kind: 'read', data: parseChunk(data['data']), end_of_file: data['end_of_file'] }
256
261
  case 'written':
257
- keys(data, ['kind', 'bytes'])
262
+ keys(data, PAYLOAD_KEYS.file_result.written)
258
263
  return {
259
264
  kind: 'written',
260
265
  bytes: integer(data['bytes'], 'written bytes', 0, MAX_FILE_CHUNK_BYTES),
261
266
  }
262
267
  case 'done':
263
- keys(data, ['kind'])
268
+ keys(data, PAYLOAD_KEYS.file_result.done)
264
269
  return { kind: 'done' }
265
270
  default:
266
271
  throw new ProtocolError('Unknown file result')
package/src/framing.ts CHANGED
@@ -1,5 +1,7 @@
1
- /** Maximum UTF-8 JSON payload bytes, excluding the newline delimiter. */
2
- export const MAX_FRAME_BYTES = 65_536
1
+ import { MAX_FRAME_BYTES } from './wire-schema.ts'
2
+
3
+ /** Decoder capacity kept between frames; a larger frame borrows memory while it is read. */
4
+ const RETAINED_FRAME_BYTES = 65_536
3
5
 
4
6
  export class ProtocolError extends Error {
5
7
  override readonly name = 'ProtocolError'
@@ -24,17 +26,35 @@ export function encodeFrame(value: unknown): Uint8Array {
24
26
  }
25
27
 
26
28
  /**
27
- * Incremental, bounded JSON-lines decoder for a native process pipe.
29
+ * Incremental, bounded JSON-lines decoder for a native process pipe. `limit`
30
+ * is the largest frame payload it accepts: the runtime reads events with
31
+ * `MAX_EVENT_FRAME_BYTES`; a peer reading commands keeps the default.
28
32
  * A protocol error poisons the decoder; the caller must terminate that session.
29
33
  * Successful finish closes the decoder and is idempotent.
30
34
  */
31
35
  export class FrameDecoder {
32
- private readonly buffer = new Uint8Array(MAX_FRAME_BYTES)
36
+ private buffer = new Uint8Array(0)
33
37
  // Preserve a leading BOM so JSON.parse rejects it, matching Rust serde_json.
34
38
  private readonly utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
35
39
  private length = 0
36
40
  private state: 'open' | 'finished' | 'failed' = 'open'
37
41
 
42
+ constructor(private readonly limit: number = MAX_FRAME_BYTES) {}
43
+
44
+ /** Append a partial frame, growing the buffer geometrically up to the limit. */
45
+ private append(bytes: Uint8Array): void {
46
+ const length = this.length + bytes.length
47
+ if (length > this.buffer.length) {
48
+ const grown = new Uint8Array(
49
+ Math.min(this.limit, Math.max(length, 2 * this.buffer.length, 4_096))
50
+ )
51
+ grown.set(this.buffer.subarray(0, this.length))
52
+ this.buffer = grown
53
+ }
54
+ this.buffer.set(bytes, this.length)
55
+ this.length = length
56
+ }
57
+
38
58
  push(chunk: Uint8Array): unknown[] {
39
59
  if (this.state !== 'open')
40
60
  throw new ProtocolError(
@@ -49,8 +69,7 @@ export class FrameDecoder {
49
69
  const newline = chunk.indexOf(10, start)
50
70
  const end = newline === -1 ? chunk.length : newline
51
71
  const size = end - start
52
- if (this.length + size > MAX_FRAME_BYTES)
53
- throw new ProtocolError('Frame exceeds byte limit')
72
+ if (this.length + size > this.limit) throw new ProtocolError('Frame exceeds byte limit')
54
73
  if (newline !== -1 && this.length === 0) {
55
74
  // A frame wholly inside this chunk decodes in place, without a copy.
56
75
  if (size === 0) throw new ProtocolError('Empty frame')
@@ -58,12 +77,12 @@ export class FrameDecoder {
58
77
  start = newline + 1
59
78
  continue
60
79
  }
61
- this.buffer.set(chunk.subarray(start, end), this.length)
62
- this.length += size
80
+ this.append(chunk.subarray(start, end))
63
81
  if (newline === -1) break
64
82
  const json = this.utf8.decode(this.buffer.subarray(0, this.length))
65
- frames.push(JSON.parse(json) as unknown)
66
83
  this.length = 0
84
+ if (this.buffer.length > RETAINED_FRAME_BYTES) this.buffer = new Uint8Array(0)
85
+ frames.push(JSON.parse(json) as unknown)
67
86
  start = newline + 1
68
87
  }
69
88
  } catch (error) {