// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // Web Serial (navigator.serial: Chromium-based desktop browsers, in a // secure context) as a SerialBackend (js/core/serial.ts) for the guest's // /dev/ttyACM ports. // // const port = await navigator.serial.requestPort(); // in a click handler // vm.serial.attach(webSerialBackend(port)); // // The SerialPort stays on the thread that got it (it cannot be posted), so // the kernel's worker in worker mode reaches it through SerialHost on this // thread. Web Serial's own rules, which the host keeps: open() rejects on // an open port, so a config change is a close and an open; close() needs // the reader and the writer released (close() here cancels the one and // closes or aborts the other first); after a non-fatal read error // (BreakError, FramingError, ParityError, BufferOverrunError, // BufferOverflowError) `readable` is a new stream, which the next read() // takes; NetworkError or a null `readable` means the device is gone, as // does the port's "disconnect" event; getSignals() and setSignals() reject // on a closed port. Web Serial opens 7 or 8 data bits only: a guest's 5 // or 6 opens with 8 (logged once). import type { SerialBackend, SerialBackendInfo, SerialConfig, SerialInputSignals, SerialOutputSignals } from "../core/serial.ts"; /** The parts of Web Serial's SerialPort this uses (TypeScript's DOM library has no Web Serial). */ export interface WebSerialPort extends EventTarget { readonly readable: ReadableStream | null; readonly writable: WritableStream | null; readonly connected?: boolean; open(options: { baudRate: number; dataBits?: number; stopBits?: number; parity?: string; bufferSize?: number; flowControl?: string }): Promise; close(): Promise; getInfo(): { usbVendorId?: number; usbProductId?: number; bluetoothServiceClassId?: number | string }; setSignals(signals: { dataTerminalReady?: boolean; requestToSend?: boolean; break?: boolean }): Promise; getSignals(): Promise; forget?(): Promise; } /** navigator.serial. */ export interface WebSerial extends EventTarget { requestPort(options?: { filters?: Array<{ usbVendorId?: number; usbProductId?: number }> }): Promise; getPorts(): Promise; } /** navigator.serial where there is one. */ export function webSerial(): WebSerial | undefined { const nav = (globalThis as { navigator?: { serial?: WebSerial } }).navigator; return nav?.serial ?? undefined; } /** * Why Web Serial cannot be used here, or undefined: no navigator.serial * (browsers other than Chromium-based desktop ones), not a secure context * (https or localhost), or a permissions policy that blocks `serial`. */ export function webSerialBlocker(): string | undefined { const g = globalThis as { isSecureContext?: boolean; document?: { featurePolicy?: { allowsFeature(f: string): boolean }; permissionsPolicy?: { allowsFeature(f: string): boolean } } }; if (g.isSecureContext === false) return "Web Serial needs a secure context (https, or http://localhost)"; if (!webSerial()) return "this browser has no Web Serial (Chrome, Edge and other Chromium-based desktop browsers have it)"; const policy = g.document?.permissionsPolicy ?? g.document?.featurePolicy; try { if (policy && !policy.allowsFeature("serial")) return "the page's permissions policy does not allow serial"; } catch {} return undefined; } /** "USB 303a:1001" from getInfo(), or a Bluetooth service, or "serial port". */ export function serialPortLabel(info: { usbVendorId?: number; usbProductId?: number; bluetoothServiceClassId?: number | string }): string { const hex = (n: number) => n.toString(16).padStart(4, "0"); if (info.usbVendorId !== undefined) return `USB ${hex(info.usbVendorId)}:${info.usbProductId !== undefined ? hex(info.usbProductId) : "????"}`; if (info.bluetoothServiceClassId !== undefined) return "Bluetooth serial port"; return "serial port"; } const named = (name: string, message: string) => Object.assign(new Error(message), { name }); export interface WebSerialBackendOptions { /** Web Serial's read and write buffer (default 16384 bytes; Web Serial's own is 255). */ bufferSize?: number; log?: (msg: string) => void; } /** A Web Serial SerialPort as a SerialBackend: attach it with vm.serial.attach(). */ export class WebSerialBackend implements SerialBackend { readonly port: WebSerialPort; readonly info: SerialBackendInfo; #bufferSize: number; #log: (msg: string) => void; #open = false; #closing = false; #reader: ReadableStreamDefaultReader | null = null; #writer: WritableStreamDefaultWriter | null = null; #writing = 0; #warned = false; constructor(port: WebSerialPort, opts: WebSerialBackendOptions = {}) { this.port = port; const i = port.getInfo(); this.info = { usbVendorId: i.usbVendorId, usbProductId: i.usbProductId, label: serialPortLabel(i) }; this.#bufferSize = opts.bufferSize ?? 16384; this.#log = opts.log ?? ((m) => console.warn(m)); } async open(c: SerialConfig): Promise { let dataBits = c.dataBits; if (dataBits !== 7 && dataBits !== 8) { if (!this.#warned) this.#log(`[serial] ${this.info.label}: Web Serial opens 7 or 8 data bits only; ${dataBits} opens as 8`); this.#warned = true; dataBits = 8; } this.#closing = false; await this.port.open({ baudRate: c.baudRate, dataBits, stopBits: c.stopBits, parity: c.parity, flowControl: c.flowControl, bufferSize: this.#bufferSize }); this.#open = true; } async read(): Promise { for (;;) { if (!this.#open || this.#closing) return null; if (!this.#reader) { const r = this.port.readable; if (!r) throw named("NetworkError", "the port has no readable stream (the device is gone)"); this.#reader = r.getReader(); } const reader = this.#reader; try { const { value, done } = await reader.read(); if (done) { this.#release(reader); continue; // closing (null above), or a stream that ended: take the next one } if (value?.length) return value; } catch (e) { // After a non-fatal error `readable` is a new stream; the next read() takes it. this.#release(reader); if (!this.#open || this.#closing) return null; throw e; } } } #release(reader: ReadableStreamDefaultReader): void { try { reader.releaseLock(); } catch {} if (this.#reader === reader) this.#reader = null; } async write(data: Uint8Array): Promise { if (!this.#open) throw named("InvalidStateError", "the port is not open"); if (!this.#writer) { const w = this.port.writable; if (!w) throw named("NetworkError", "the port has no writable stream (the device is gone)"); this.#writer = w.getWriter(); } const writer = this.#writer; this.#writing++; try { await writer.write(data); } catch (e) { try { writer.releaseLock(); } catch {} if (this.#writer === writer) this.#writer = null; throw e; } finally { this.#writing--; } } setSignals(s: SerialOutputSignals): Promise { return this.port.setSignals({ dataTerminalReady: s.dataTerminalReady, requestToSend: s.requestToSend, break: s.break }); } async getSignals(): Promise { const s = await this.port.getSignals(); return { clearToSend: !!s.clearToSend, dataSetReady: !!s.dataSetReady, dataCarrierDetect: !!s.dataCarrierDetect, ringIndicator: !!s.ringIndicator }; } async close(): Promise { this.#closing = true; const reader = this.#reader; if (reader) { await reader.cancel().catch(() => {}); this.#release(reader); } const writer = this.#writer; this.#writer = null; if (writer) { // Written out first (close() flushes), unless a write is stuck (flow control) or the flush takes over 1 s. const flushed = this.#writing ? Promise.reject(new Error("a write is pending")) : writer.close(); const ok = await Promise.race([flushed.then(() => true, () => false), new Promise((r) => setTimeout(() => r(false), 1000))]); if (!ok) await writer.abort().catch(() => {}); try { writer.releaseLock(); } catch {} } if (this.#open || this.port.readable || this.port.writable) { try { await this.port.close(); } catch (e) { // Not open (a failed open) is fine; anything else is the caller's to log. if ((e as Error)?.name !== "InvalidStateError") throw e; } } this.#open = false; } listen(lost: () => void): () => void { const on = () => lost(); this.port.addEventListener("disconnect", on); return () => this.port.removeEventListener("disconnect", on); } } /** A Web Serial SerialPort as a SerialBackend (see WebSerialBackend). */ export function webSerialBackend(port: WebSerialPort, opts?: WebSerialBackendOptions): WebSerialBackend { return new WebSerialBackend(port, opts); }