Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

56.0 KB
Raw Blame
// Network, clipboard and audio globals on top of `__native.net` (crates/net):
//   fetch / Request / Response / Headers / Blob / File / FormData, WebSocket, AudioContext.
//
// Native work happens on worker threads; results come back through one handler installed with
// `setHandler(fn)`: `fn(kind, id, ...)`. Bodies and binary messages arrive as ArrayBuffers and are
// decoded natively (`utf8Decode`), so no byte-by-byte JavaScript runs on network data.
import { Event, EventTarget, MessageEvent, CloseEvent, DOMExceptionImpl as DOMException, defineHandlers } from "./core/events.ts";
import { URL, URLSearchParams, AbortSignal, base64ToBytes } from "./core/web.ts";
import { location, navigator } from "./core/window.ts";

interface NativeNet {
  setHandler(fn: (kind: number, id: number, ...args: any[]) => void, userAgent: string): void;
  fetch(id: number, method: string, url: string, headers: string[], body: string | Uint8Array | null, redirect: number): void;
  fetchAbort(id: number): void;
  wsOpen(id: number, url: string, protocols: string[], origin: string, acceptLanguage: string): void;
  wsSend(id: number, data: string | ArrayBuffer | Uint8Array): void;
  wsClose(id: number, code: number, reason: string): void;
  wsBuffered(id: number): number;
  utf8Decode(b: ArrayBuffer | ArrayBufferView): string;
  utf8Encode(s: string): Uint8Array;
  clipboardWrite(s: string): boolean;
  clipboardRead(): string;
  audioRate(): number;
  audioCreate(): number;
  audioTime(ctx: number): number;
  audioSuspend(ctx: number): void;
  audioResume(ctx: number): void;
  audioClose(ctx: number): void;
  audioNode(ctx: number, kind: number): number;
  audioConnect(from: number, to: number, param: number): void;
  audioDisconnect(from: number, to: number, param: number): void;
  audioParam(node: number, index: number, intrinsic: number, events: Float64Array): void;
  audioParamValue(events: Float64Array, intrinsic: number, t: number): number;
  audioWave(node: number, wave: number): void;
  audioStart(node: number, when: number): void;
  audioStop(node: number, when: number): void;
  audioWantEnded(node: number): void;
  audioRelease(node: number): void;
}

const native = __native.net as NativeNet;
const g = globalThis as any;

const FETCH_HEAD = 1, FETCH_BODY = 2, FETCH_ERROR = 3;
const WS_OPEN = 10, WS_TEXT = 11, WS_BINARY = 12, WS_CLOSE = 13;
const AUDIO_ENDED = 20;

const decodeUtf8 = (b: ArrayBuffer | ArrayBufferView) => native.utf8Decode(b);
const encodeUtf8 = (s: string) => native.utf8Encode(s);
const swallow = () => {};
/** Network errors go to the log the way Chromium's console shows them, without calling the page's
 *  (possibly hooked) console.error. */
const netLog = (msg: string) => __native.sys.log("error", msg);

// ---------------------------------------------------------------- byte helpers

function isBufferSource(v: any): v is ArrayBuffer | ArrayBufferView {
  return v instanceof ArrayBuffer || ArrayBuffer.isView(v) || Object.prototype.toString.call(v) === "[object SharedArrayBuffer]";
}

/** A copy of a buffer source's bytes (the page may mutate its buffer afterwards). */
function copyBytes(v: ArrayBuffer | ArrayBufferView): Uint8Array {
  if (ArrayBuffer.isView(v)) return new Uint8Array(v.buffer, v.byteOffset, v.byteLength).slice();
  return new Uint8Array(v as ArrayBuffer).slice();
}

function concat(parts: Uint8Array[]): Uint8Array {
  if (parts.length === 1) return parts[0];
  let n = 0;
  for (const p of parts) n += p.length;
  const out = new Uint8Array(n);
  let o = 0;
  for (const p of parts) { out.set(p, o); o += p.length; }
  return out;
}

/** An ArrayBuffer holding exactly these bytes (no copy when the view covers its buffer). */
function exactBuffer(b: Uint8Array): ArrayBuffer {
  return b.byteOffset === 0 && b.byteLength === b.buffer.byteLength ? (b.buffer as ArrayBuffer) : (b.slice().buffer as ArrayBuffer);
}

function utf8Length(s: string) {
  let n = 0;
  for (let i = 0; i < s.length; i++) {
    const c = s.charCodeAt(i);
    if (c < 0x80) n += 1;
    else if (c < 0x800) n += 2;
    else if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length && (s.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { n += 4; i++; }
    else n += 3;
  }
  return n;
}

// ---------------------------------------------------------------- Blob / File

const BYTES = Symbol("bytes");

export class Blob {
  /** @internal */ [BYTES]: Uint8Array;
  readonly type: string;
  constructor(parts: any[] = [], options: { type?: string; endings?: string } = {}) {
    if (parts == null || typeof parts !== "object" || typeof (parts as any)[Symbol.iterator] !== "function") {
      throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");
    }
    const chunks: Uint8Array[] = [];
    for (const p of parts) {
      if (p instanceof Blob) chunks.push(p[BYTES]);
      else if (isBufferSource(p)) chunks.push(copyBytes(p));
      else {
        let s = String(p);
        if (options.endings === "native") s = s.replace(/\r\n|\r/g, "\n");
        chunks.push(encodeUtf8(s));
      }
    }
    this[BYTES] = chunks.length ? concat(chunks) : new Uint8Array(0);
    const t = options.type === undefined ? "" : String(options.type);
    this.type = /^[\x20-\x7e]*$/.test(t) ? t.toLowerCase() : "";
  }
  get size() { return this[BYTES].length; }
  slice(start = 0, end = this.size, type = "") {
    const n = this.size;
    const s = start < 0 ? Math.max(n + start, 0) : Math.min(start, n);
    const e = end < 0 ? Math.max(n + end, 0) : Math.min(end, n);
    const b = new Blob([], { type });
    b[BYTES] = this[BYTES].slice(s, Math.max(s, e));
    return b;
  }
  text() { return Promise.resolve(decodeUtf8(this[BYTES])); }
  arrayBuffer() { return Promise.resolve(this[BYTES].slice().buffer as ArrayBuffer); }
  bytes() { return Promise.resolve(this[BYTES].slice()); }
  stream() { return new ByteStream(Promise.resolve(this[BYTES])); }
  get [Symbol.toStringTag]() { return "Blob"; }
}

export class File extends Blob {
  readonly name: string;
  readonly lastModified: number;
  readonly webkitRelativePath = "";
  constructor(parts: any[], name: string, options: { type?: string; lastModified?: number } = {}) {
    super(parts, options);
    if (arguments.length < 2) throw new TypeError("Failed to construct 'File': 2 arguments required, but only " + arguments.length + " present.");
    this.name = String(name);
    this.lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified);
  }
  get [Symbol.toStringTag]() { return "File"; }
}

// ---------------------------------------------------------------- ReadableStream (minimal)

/** `Response.body` / `Blob.stream()`: one chunk holding the whole body. Enough for readers and
 *  `for await`; JavaScriptCore has no streams of its own here. */
class ByteStream {
  /** @internal */ _bytes: Promise<Uint8Array>;
  /** @internal */ _locked = false;
  /** @internal */ _done = false;
  constructor(bytes: Promise<Uint8Array>) { this._bytes = bytes; }
  get locked() { return this._locked; }
  getReader() {
    if (this._locked) throw new TypeError("ReadableStreamDefaultReader constructor can only accept readable streams that are not yet locked to a reader");
    this._locked = true;
    const self = this;
    return {
      read(): Promise<{ value: Uint8Array | undefined; done: boolean }> {
        if (self._done) return Promise.resolve({ value: undefined, done: true });
        self._done = true;
        return self._bytes.then((b) => (b.length ? { value: b, done: false } : { value: undefined, done: true }));
      },
      releaseLock() { self._locked = false; },
      cancel() { self._done = true; return Promise.resolve(); },
      get closed() { return self._bytes.then(() => undefined); },
    };
  }
  cancel() { this._done = true; return Promise.resolve(); }
  async *[Symbol.asyncIterator]() {
    const r = this.getReader();
    for (;;) { const { value, done } = await r.read(); if (done) return; yield value; }
  }
}

// ---------------------------------------------------------------- FormData

type FormValue = string | File;

const BOUNDARY_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

export class FormData {
  /** @internal */ _entries: [string, FormValue][] = [];
  constructor(form?: any) {
    if (form == null) return;
    // <form> element: its named, enabled, successful controls.
    const controls: any[] = form.elements ? Array.from(form.elements) : form.querySelectorAll ? Array.from(form.querySelectorAll("input,select,textarea,button")) : [];
    for (const el of controls) {
      const name = el.name ?? el.getAttribute?.("name");
      if (!name || el.disabled) continue;
      const tag = String(el.tagName ?? "").toLowerCase();
      const type = String(el.type ?? "").toLowerCase();
      if (tag === "button" || ["submit", "button", "reset", "image", "file"].includes(type)) continue;
      if ((type === "checkbox" || type === "radio") && !el.checked) continue;
      if (tag === "select") {
        for (const o of Array.from(el.options ?? []) as any[]) if (o.selected) this.append(name, o.value);
        continue;
      }
      this.append(name, type === "checkbox" || type === "radio" ? (el.value || "on") : String(el.value ?? ""));
    }
  }
  /** @internal */ _value(value: any, filename?: string): FormValue {
    if (value instanceof Blob) {
      if (value instanceof File && filename === undefined) return value;
      return new File([value], filename !== undefined ? String(filename) : value instanceof File ? value.name : "blob", { type: value.type });
    }
    return String(value);
  }
  append(name: string, value: any, filename?: string) { this._entries.push([String(name), this._value(value, filename)]); }
  set(name: string, value: any, filename?: string) {
    const n = String(name), v = this._value(value, filename);
    const i = this._entries.findIndex(([k]) => k === n);
    if (i < 0) this._entries.push([n, v]);
    else { this._entries[i] = [n, v]; this._entries = this._entries.filter(([k], j) => k !== n || j === i); }
  }
  get(name: string) { return this._entries.find(([k]) => k === String(name))?.[1] ?? null; }
  getAll(name: string) { return this._entries.filter(([k]) => k === String(name)).map(([, v]) => v); }
  has(name: string) { return this._entries.some(([k]) => k === String(name)); }
  delete(name: string) { this._entries = this._entries.filter(([k]) => k !== String(name)); }
  forEach(cb: (v: FormValue, k: string, f: FormData) => void, thisArg?: any) { for (const [k, v] of this._entries.slice()) cb.call(thisArg, v, k, this); }
  keys() { return this._entries.map(([k]) => k)[Symbol.iterator](); }
  values() { return this._entries.map(([, v]) => v)[Symbol.iterator](); }
  entries() { return this._entries.map(([k, v]) => [k, v] as [string, FormValue])[Symbol.iterator](); }
  [Symbol.iterator]() { return this.entries(); }
  get [Symbol.toStringTag]() { return "FormData"; }

  /** @internal multipart/form-data, laid out like Chromium (`----WebKitFormBoundary…`). */
  _encode(): { bytes: Uint8Array; type: string } {
    const rnd = crypto.getRandomValues(new Uint8Array(16));
    const boundary = "----WebKitFormBoundary" + Array.from(rnd, (b) => BOUNDARY_CHARS[b % 62]).join("");
    const esc = (s: string) => s.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
    const parts: Uint8Array[] = [];
    for (const [name, v] of this._entries) {
      let head = `--${boundary}\r\nContent-Disposition: form-data; name="${esc(name.replace(/\r\n|\r|\n/g, "\r\n"))}"`;
      if (typeof v === "string") {
        parts.push(encodeUtf8(head + "\r\n\r\n" + v.replace(/\r\n|\r|\n/g, "\r\n") + "\r\n"));
      } else {
        head += `; filename="${esc(v.name)}"\r\nContent-Type: ${v.type || "application/octet-stream"}\r\n\r\n`;
        parts.push(encodeUtf8(head), v[BYTES], encodeUtf8("\r\n"));
      }
    }
    parts.push(encodeUtf8(`--${boundary}--\r\n`));
    return { bytes: concat(parts), type: `multipart/form-data; boundary=${boundary}` };
  }
}

function parseFormData(bytes: Uint8Array, contentType: string): FormData {
  const fd = new FormData();
  const mime = contentType.split(";")[0].trim().toLowerCase();
  if (mime === "application/x-www-form-urlencoded") {
    for (const [k, v] of new URLSearchParams(decodeUtf8(bytes))) fd.append(k, v);
    return fd;
  }
  if (mime === "multipart/form-data") {
    const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
    if (!m) throw new TypeError("Failed to fetch");
    const boundary = "--" + (m[1] ?? m[2]).trim();
    // Latin-1 view of the body keeps byte offsets equal to string offsets.
    let text = "";
    for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
    let pos = text.indexOf(boundary);
    while (pos >= 0) {
      const start = pos + boundary.length;
      if (text.startsWith("--", start)) break;
      const headEnd = text.indexOf("\r\n\r\n", start);
      const next = text.indexOf("\r\n" + boundary, headEnd);
      if (headEnd < 0 || next < 0) break;
      const head = decodeUtf8(bytes.subarray(start, headEnd));
      const body = bytes.subarray(headEnd + 4, next);
      const name = /name="([^"]*)"/i.exec(head)?.[1] ?? "";
      const filename = /filename="([^"]*)"/i.exec(head)?.[1];
      const type = /content-type:\s*([^\r\n]+)/i.exec(head)?.[1]?.trim() ?? "";
      if (filename !== undefined) fd.append(name, new File([body], filename, { type }));
      else fd.append(name, decodeUtf8(body));
      pos = next + 2;
    }
    return fd;
  }
  throw new TypeError("Failed to execute 'formData' on 'Response': Could not parse content as FormData.");
}

// ---------------------------------------------------------------- Headers

const FORBIDDEN_REQUEST = new Set([
  "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection",
  "content-length", "cookie", "cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin", "referer", "set-cookie",
  "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via",
]);
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;

type Guard = "none" | "request" | "response" | "immutable";

function normalizeValue(v: any, method: string) {
  const s = String(v).replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
  if (/[\0\r\n]/.test(s) || /[^\x00-\xff]/.test(s)) throw new TypeError(`Failed to execute '${method}' on 'Headers': Invalid value`);
  return s;
}
function checkName(n: any, method: string) {
  const s = String(n);
  if (!TOKEN.test(s)) throw new TypeError(`Failed to execute '${method}' on 'Headers': Invalid name`);
  return s.toLowerCase();
}

export class Headers {
  /** @internal */ _list: [string, string][] = [];
  /** @internal */ _guard: Guard = "none";
  constructor(init?: any) {
    if (init == null) return;
    if (init instanceof Headers) { this._list = init._list.map(([k, v]) => [k, v]); return; }
    if (typeof init !== "object") throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(record<ByteString, ByteString> or sequence<sequence<ByteString>>)'.");
    if (typeof init[Symbol.iterator] === "function") {
      for (const pair of init) {
        const p = Array.from(pair as any);
        if (p.length !== 2) throw new TypeError("Failed to construct 'Headers': Invalid value");
        this.append(p[0] as string, p[1] as string);
      }
    } else {
      for (const k of Object.keys(init)) this.append(k, init[k]);
    }
  }
  /** @internal */ _allowed(name: string) {
    if (this._guard === "immutable") throw new TypeError("Failed to execute on 'Headers': Headers are immutable");
    if (this._guard === "request" && (FORBIDDEN_REQUEST.has(name) || name.startsWith("proxy-") || name.startsWith("sec-"))) return false;
    if (this._guard === "response" && (name === "set-cookie" || name === "set-cookie2")) return false;
    return true;
  }
  append(name: string, value: string) {
    const n = checkName(name, "append"), v = normalizeValue(value, "append");
    if (this._allowed(n)) this._list.push([n, v]);
  }
  set(name: string, value: string) {
    const n = checkName(name, "set"), v = normalizeValue(value, "set");
    if (!this._allowed(n)) return;
    const i = this._list.findIndex(([k]) => k === n);
    if (i < 0) this._list.push([n, v]);
    else { this._list[i] = [n, v]; this._list = this._list.filter(([k], j) => k !== n || j === i); }
  }
  delete(name: string) {
    const n = checkName(name, "delete");
    if (this._allowed(n)) this._list = this._list.filter(([k]) => k !== n);
  }
  get(name: string) {
    const n = checkName(name, "get");
    const vs = this._list.filter(([k]) => k === n).map(([, v]) => v);
    return vs.length ? vs.join(", ") : null;
  }
  getSetCookie(): string[] { return []; }
  has(name: string) { const n = checkName(name, "has"); return this._list.some(([k]) => k === n); }
  /** @internal sorted, combined (the iteration order of the Fetch standard) */
  _sorted(): [string, string][] {
    const names = [...new Set(this._list.map(([k]) => k))].sort();
    return names.map((n) => [n, this._list.filter(([k]) => k === n).map(([, v]) => v).join(", ")]);
  }
  forEach(cb: (v: string, k: string, h: Headers) => void, thisArg?: any) { for (const [k, v] of this._sorted()) cb.call(thisArg, v, k, this); }
  keys() { return this._sorted().map(([k]) => k)[Symbol.iterator](); }
  values() { return this._sorted().map(([, v]) => v)[Symbol.iterator](); }
  entries() { return this._sorted()[Symbol.iterator](); }
  [Symbol.iterator]() { return this.entries(); }
  get [Symbol.toStringTag]() { return "Headers"; }
}

function guarded(init: any, guard: Guard) {
  const h = new Headers();
  h._guard = guard === "immutable" ? "none" : guard;
  if (init != null) {
    const src = init instanceof Headers ? init._list : new Headers(init)._list;
    for (const [k, v] of src) if (h._allowed(k)) h._list.push([k, v]);
  }
  h._guard = guard;
  return h;
}

// ---------------------------------------------------------------- Body

type BodySource = string | Uint8Array | null;

interface Extracted { src: BodySource; type: string | null }

function extractBody(body: any): Extracted {
  if (body == null) return { src: null, type: null };
  if (typeof body === "string") return { src: body, type: "text/plain;charset=UTF-8" };
  if (body instanceof URLSearchParams) return { src: body.toString(), type: "application/x-www-form-urlencoded;charset=UTF-8" };
  if (body instanceof Blob) return { src: body[BYTES], type: body.type || null };
  if (body instanceof FormData) { const e = body._encode(); return { src: e.bytes, type: e.type }; }
  if (isBufferSource(body)) return { src: copyBytes(body), type: null };
  if (body instanceof ByteStream) throw new TypeError("Streaming request bodies are not supported");
  return { src: String(body), type: "text/plain;charset=UTF-8" };
}

const NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);

abstract class Body {
  /** @internal */ _src: BodySource = null;
  /** @internal body still arriving from the network */ _pending: Promise<Uint8Array> | null = null;
  /** @internal */ _used = false;
  /** @internal */ _hasBody = false;
  /** @internal */ _stream: ByteStream | null = null;
  abstract readonly headers: Headers;
  /** @internal */ abstract _kind(): string;

  get bodyUsed() { return this._used; }
  get body(): any {
    if (!this._hasBody) return null;
    return (this._stream ??= new ByteStream(this._peek().then((b) => (typeof b === "string" ? encodeUtf8(b) : b))));
  }
  /** @internal the body without consuming it */
  _peek(): Promise<string | Uint8Array> {
    if (this._pending) return this._pending;
    return Promise.resolve(this._src ?? new Uint8Array(0));
  }
  /** @internal */ _consume(method: string): Promise<string | Uint8Array> {
    if (this._used || this._stream?.locked) {
      return Promise.reject(new TypeError(`Failed to execute '${method}' on '${this._kind()}': body stream already read`));
    }
    if (this._hasBody) this._used = true;
    return this._peek();
  }
  arrayBuffer(): Promise<ArrayBuffer> {
    return this._consume("arrayBuffer").then((b) => (typeof b === "string" ? exactBuffer(encodeUtf8(b)) : exactBuffer(b)));
  }
  bytes(): Promise<Uint8Array> {
    return this._consume("bytes").then((b) => (typeof b === "string" ? encodeUtf8(b) : b));
  }
  text(): Promise<string> {
    return this._consume("text").then((b) => (typeof b === "string" ? b : decodeUtf8(b)));
  }
  json(): Promise<any> {
    return this.text().then((t) => JSON.parse(t));
  }
  blob(): Promise<Blob> {
    const type = this.headers.get("content-type") ?? "";
    return this._consume("blob").then((b) => {
      const blob = new Blob([], { type });
      blob[BYTES] = typeof b === "string" ? encodeUtf8(b) : b;
      return blob;
    });
  }
  formData(): Promise<FormData> {
    const type = this.headers.get("content-type") ?? "";
    return this._consume("formData").then((b) => parseFormData(typeof b === "string" ? encodeUtf8(b) : b, type));
  }
}

// ---------------------------------------------------------------- Request

const NORMALIZED_METHODS = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"];

function parseUrl(input: string, what: string) {
  let u: URL;
  try { u = new URL(input, location.href); } catch { throw new TypeError(`Failed to ${what}: Failed to parse URL from ${input}`); }
  if (u.username || u.password) throw new TypeError(`Failed to ${what}: Request cannot be constructed from a URL that includes credentials: ${input}`);
  return u;
}

export class Request extends Body {
  readonly method: string;
  readonly url: string;
  readonly headers: Headers;
  readonly signal: AbortSignal;
  readonly redirect: RequestRedirect;
  readonly mode: RequestMode;
  readonly credentials: RequestCredentials;
  readonly cache: RequestCache;
  readonly referrer: string;
  readonly referrerPolicy: ReferrerPolicy;
  readonly integrity: string;
  readonly keepalive: boolean;
  readonly destination = "";
  readonly duplex = "half";
  constructor(input: any, init: any = {}) {
    super();
    const from = input instanceof Request ? input : null;
    if (init == null) init = {};
    const url = from ? from.url : parseUrl(String(input), "construct 'Request'").href.replace(/#.*$/, "");
    this.url = url;
    let method = init.method !== undefined ? String(init.method) : from ? from.method : "GET";
    if (!TOKEN.test(method)) throw new TypeError(`Failed to construct 'Request': '${method}' is not a valid HTTP method.`);
    const upper = method.toUpperCase();
    if (upper === "CONNECT" || upper === "TRACE" || upper === "TRACK") throw new TypeError(`Failed to construct 'Request': '${method}' HTTP method is unsupported.`);
    if (NORMALIZED_METHODS.includes(upper)) method = upper;
    this.method = method;
    this.mode = init.mode ?? from?.mode ?? "cors";
    if (this.mode === "navigate") throw new TypeError("Failed to construct 'Request': Cannot construct a Request with a RequestInit whose mode member is set as 'navigate'.");
    this.credentials = init.credentials ?? from?.credentials ?? "same-origin";
    this.cache = init.cache ?? from?.cache ?? "default";
    this.redirect = init.redirect ?? from?.redirect ?? "follow";
    if (!["follow", "error", "manual"].includes(this.redirect)) throw new TypeError(`Failed to construct 'Request': The provided value '${this.redirect}' is not a valid enum value of type RequestRedirect.`);
    this.referrer = init.referrer !== undefined ? (init.referrer === "" ? "" : "about:client") : from?.referrer ?? "about:client";
    this.referrerPolicy = init.referrerPolicy ?? from?.referrerPolicy ?? "";
    this.integrity = init.integrity ?? from?.integrity ?? "";
    this.keepalive = !!(init.keepalive ?? from?.keepalive);
    this.signal = init.signal !== undefined ? (init.signal ?? new AbortSignal()) : from?.signal ?? new AbortSignal();
    this.headers = guarded(init.headers !== undefined ? init.headers : from?.headers, "request");

    const hasInitBody = init.body !== undefined && init.body !== null;
    if ((hasInitBody || (from?._hasBody && init.body === undefined)) && (method === "GET" || method === "HEAD")) {
      throw new TypeError("Failed to construct 'Request': Request with GET/HEAD method cannot have body.");
    }
    if (hasInitBody) {
      const e = extractBody(init.body);
      this._src = e.src;
      this._hasBody = true;
      if (e.type && !this.headers.has("content-type")) this.headers._list.push(["content-type", e.type]);
    } else if (from?._hasBody && init.body === undefined) {
      if (from.bodyUsed) throw new TypeError("Failed to construct 'Request': Cannot construct a Request with a Request object that has already been used.");
      this._src = from._src;
      this._pending = from._pending;
      this._hasBody = true;
      from._used = true; // the body moves to the new request
    }
  }
  /** @internal */ _kind() { return "Request"; }
  clone(): Request {
    if (this.bodyUsed) throw new TypeError("Failed to execute 'clone' on 'Request': Request body is already used");
    const r = new Request(this, {});
    // `new Request(this)` moved the body; a clone shares it instead.
    this._used = false;
    return r;
  }
  get [Symbol.toStringTag]() { return "Request"; }
}

// ---------------------------------------------------------------- Response

const STATUS_TEXT_OK = /^[\t\x20-\x7e\x80-\xff]*$/;

export class Response extends Body {
  readonly headers: Headers;
  /** @internal */ _status: number;
  /** @internal */ _statusText: string;
  /** @internal */ _type: ResponseType = "default";
  /** @internal */ _url = "";
  /** @internal */ _redirected = false;
  constructor(body: any = null, init: any = {}) {
    super();
    if (init == null) init = {};
    const status = init.status === undefined ? 200 : Number(init.status);
    if (!(status >= 200 && status <= 599) || !Number.isInteger(status)) {
      throw new RangeError(`Failed to construct 'Response': The status provided (${init.status}) is outside the range [200, 599].`);
    }
    const statusText = init.statusText === undefined ? "" : String(init.statusText);
    if (!STATUS_TEXT_OK.test(statusText)) throw new TypeError("Failed to construct 'Response': Invalid statusText");
    this._status = status;
    this._statusText = statusText;
    this.headers = guarded(init.headers, "response");
    if (body != null) {
      if (NULL_BODY_STATUS.has(status)) throw new TypeError("Failed to construct 'Response': Response with null body status cannot have body");
      const e = extractBody(body);
      this._src = e.src;
      this._hasBody = true;
      if (e.type && !this.headers.has("content-type")) this.headers._list.push(["content-type", e.type]);
    }
  }
  /** @internal */ _kind() { return "Response"; }
  get type() { return this._type; }
  get url() { return this._url; }
  get redirected() { return this._redirected; }
  get status() { return this._status; }
  get ok() { return this._status >= 200 && this._status <= 299; }
  get statusText() { return this._statusText; }
  clone(): Response {
    if (this.bodyUsed || this._stream?.locked) throw new TypeError("Failed to execute 'clone' on 'Response': Response body is already used");
    const r = Object.create(Response.prototype) as Response;
    Object.assign(r, { _src: this._src, _pending: this._pending, _used: false, _hasBody: this._hasBody, _stream: null });
    (r as any).headers = guarded(this.headers, this.headers._guard);
    Object.assign(r, { _status: this._status, _statusText: this._statusText, _type: this._type, _url: this._url, _redirected: this._redirected });
    return r;
  }
  static error(): Response {
    const r = new Response(null, { status: 200 });
    Object.assign(r, { _status: 0, _type: "error" });
    r.headers._guard = "immutable";
    return r;
  }
  static redirect(url: string | URL, status = 302): Response {
    const u = parseUrl(String(url), "execute 'redirect' on 'Response'");
    if (![301, 302, 303, 307, 308].includes(status)) throw new RangeError("Failed to execute 'redirect' on 'Response': Invalid status code");
    const r = new Response(null, { status, headers: { location: u.href } });
    r.headers._guard = "immutable";
    return r;
  }
  static json(data: any, init: any = {}): Response {
    const text = JSON.stringify(data);
    if (text === undefined) throw new TypeError("Failed to execute 'json' on 'Response': The data is not JSON serializable");
    const headers = guarded(init?.headers, "response");
    if (!headers.has("content-type")) headers.set("content-type", "application/json");
    return new Response(text, { ...init, headers });
  }
  get [Symbol.toStringTag]() { return "Response"; }
}

// ---------------------------------------------------------------- fetch

interface PendingFetch {
  method: string;
  resolve: (r: Response) => void;
  reject: (e: any) => void;
  url: URL;
  response: Response | null;
  bodyResolve: ((b: Uint8Array) => void) | null;
  bodyReject: ((e: any) => void) | null;
  cleanup: () => void;
}

const fetches = new Map<number, PendingFetch>();
let nextFetchId = 1;

function acceptLanguage() {
  const langs: string[] = (navigator.languages as string[]) ?? [navigator.language];
  return langs.map((l, i) => (i === 0 ? l : `${l};q=${Math.max(0.1, 1 - i * 0.1).toFixed(1)}`)).join(",");
}

/** Referer under the default policy (strict-origin-when-cross-origin). */
function referer(req: Request, target: URL): string | null {
  if (req.referrer === "") return null;
  const page = new URL(location.href);
  if (page.protocol === "https:" && target.protocol === "http:") return null;
  if (page.origin === target.origin) return page.href.replace(/#.*$/, "");
  return page.origin + "/";
}

function dataUrlResponse(u: URL): Response {
  const href = u.href;
  const comma = href.indexOf(",");
  if (comma < 0) throw new TypeError("Failed to fetch");
  const meta = href.slice(5, comma);
  const data = href.slice(comma + 1);
  const isB64 = /;\s*base64\s*$/i.test(meta);
  const type = (isB64 ? meta.replace(/;\s*base64\s*$/i, "") : meta).trim() || "text/plain;charset=US-ASCII";
  let bytes: Uint8Array;
  if (isB64) bytes = base64ToBytes(decodeURIComponent(data).replace(/\s/g, ""));
  else {
    const raw = unescape(data);
    bytes = new Uint8Array(raw.length);
    for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i) & 0xff;
  }
  const r = new Response(bytes, { status: 200, headers: { "content-type": type } });
  Object.assign(r, { _statusText: "OK", _type: "basic", _url: href });
  r.headers._guard = "immutable";
  return r;
}

export function fetch(input: any, init?: any): Promise<Response> {
  return new Promise<Response>((resolve, reject) => {
    let req: Request;
    try { req = new Request(input, init); } catch (e) { reject(e); return; }
    const signal = req.signal;
    if (signal.aborted) { reject(signal.reason); return; }
    const url = new URL(req.url);
    if (url.protocol === "data:") {
      try { resolve(dataUrlResponse(url)); } catch (e) { reject(e); }
      return;
    }
    if (url.protocol !== "http:" && url.protocol !== "https:") {
      netLog(`Fetch API cannot load ${url.href}. URL scheme "${url.protocol.slice(0, -1)}" is not supported.`);
      reject(new TypeError("Failed to fetch"));
      return;
    }
    if (input instanceof Request && input._hasBody) input._used = true;
    if (req._pending) { reject(new TypeError("Streaming request bodies are not supported")); return; }

    const headers: string[] = [];
    for (const [k, v] of req.headers._list) headers.push(k, v);
    const has = (n: string) => req.headers._list.some(([k]) => k === n);
    const pageOrigin = location.origin;
    const crossOrigin = url.origin !== pageOrigin;
    if (!has("accept")) headers.push("accept", "*/*");
    if (!has("accept-language")) headers.push("accept-language", acceptLanguage());
    if (crossOrigin || (req.method !== "GET" && req.method !== "HEAD")) headers.push("origin", pageOrigin);
    const ref = referer(req, url);
    if (ref) headers.push("referer", ref);
    headers.push("user-agent", navigator.userAgent);
    if (req.cache === "no-store" || req.cache === "reload" || req.cache === "no-cache") headers.push("cache-control", "no-cache", "pragma", "no-cache");

    const id = nextFetchId++;
    const onAbort = () => {
      const p = fetches.get(id);
      if (!p) return;
      fetches.delete(id);
      native.fetchAbort(id);
      if (!p.response) p.reject(signal.reason);
      else p.bodyReject?.(signal.reason);
    };
    signal.addEventListener("abort", onAbort);
    fetches.set(id, {
      method: req.method, resolve, reject, url, response: null, bodyResolve: null, bodyReject: null,
      cleanup: () => signal.removeEventListener("abort", onAbort),
    });
    const redirect = req.redirect === "error" ? 1 : req.redirect === "manual" ? 2 : 0;
    try {
      native.fetch(id, req.method, url.href.replace(/#.*$/, ""), headers, req._src, redirect);
    } catch (e) {
      fetches.delete(id);
      reject(new TypeError("Failed to fetch"));
    }
  });
}

function onFetchHead(id: number, status: number, statusText: string, headerList: string[], url: string, redirected: boolean, opaque: boolean) {
  const p = fetches.get(id);
  if (!p) return;
  const r = Object.create(Response.prototype) as Response;
  const headers = new Headers();
  for (let i = 0; i + 1 < headerList.length; i += 2) headers._list.push([headerList[i], headerList[i + 1]]);
  headers._guard = "immutable";
  const finalUrl = new URL(url);
  Object.assign(r, {
    _src: null, _pending: null, _used: false, _hasBody: false, _stream: null,
    _status: status, _statusText: statusText, _url: url, _redirected: redirected,
    _type: opaque ? "opaqueredirect" : finalUrl.origin === location.origin ? "basic" : "cors",
  });
  (r as any).headers = headers;
  if (!opaque && !NULL_BODY_STATUS.has(status) && p.method !== "HEAD") {
    r._hasBody = true;
    r._pending = new Promise<Uint8Array>((res, rej) => { p.bodyResolve = res; p.bodyReject = rej; });
    r._pending.catch(swallow); // nobody may read the body; that is not an unhandled rejection
  }
  p.response = r;
  p.resolve(r);
}

function onFetchBody(id: number, buf: ArrayBuffer) {
  const p = fetches.get(id);
  if (!p) return;
  fetches.delete(id);
  p.cleanup();
  const bytes = new Uint8Array(buf);
  if (p.response?._pending) {
    p.response._pending = null;
    p.response._src = bytes;
    p.bodyResolve?.(bytes);
  }
}

function onFetchError(id: number, message: string) {
  const p = fetches.get(id);
  if (!p) return;
  fetches.delete(id);
  p.cleanup();
  if (!p.response) {
    netLog(`${p.method} ${p.url.href} ${message}`);
    p.reject(new TypeError("Failed to fetch"));
  } else {
    p.bodyReject?.(new TypeError("network error"));
  }
}

// ---------------------------------------------------------------- WebSocket

const sockets = new Map<number, WebSocket>();
let nextSocketId = 1;

export class WebSocket extends EventTarget {
  static readonly CONNECTING = 0; static readonly OPEN = 1; static readonly CLOSING = 2; static readonly CLOSED = 3;
  declare readonly CONNECTING: 0; declare readonly OPEN: 1; declare readonly CLOSING: 2; declare readonly CLOSED: 3;
  /** @internal */ _id: number;
  /** @internal */ _url: string;
  /** @internal */ _origin: string;
  /** @internal */ _state = 0;
  /** @internal */ _protocol = "";
  /** @internal */ _extensions = "";
  /** @internal */ _binaryType: BinaryType = "blob";
  /** @internal bytes sent while CLOSING/CLOSED: counted, never sent */ _unsent = 0;
  /** @internal close() before the connection opened */ _failed = false;
  constructor(url: string | URL, protocols?: string | string[]) {
    super();
    if (arguments.length < 1) throw new TypeError("Failed to construct 'WebSocket': 1 argument required, but only 0 present.");
    let u: URL;
    try { u = new URL(String(url), location.href); } catch { throw new DOMException(`Failed to construct 'WebSocket': The URL '${url}' is invalid.`, "SyntaxError"); }
    if (u.protocol === "http:") u.protocol = "ws:";
    else if (u.protocol === "https:") u.protocol = "wss:";
    if (u.protocol !== "ws:" && u.protocol !== "wss:") {
      throw new DOMException(`Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${u.protocol.slice(0, -1)}' is not allowed.`, "SyntaxError");
    }
    if (u.hash) throw new DOMException(`Failed to construct 'WebSocket': The URL contains a fragment identifier ('${u.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`, "SyntaxError");
    const list = protocols === undefined ? [] : typeof protocols === "string" ? [protocols] : Array.from(protocols, String);
    const seen = new Set<string>();
    for (const p of list) {
      if (!TOKEN.test(p)) throw new DOMException(`Failed to construct 'WebSocket': The subprotocol '${p}' is invalid.`, "SyntaxError");
      if (seen.has(p)) throw new DOMException(`Failed to construct 'WebSocket': The subprotocol '${p}' is duplicated.`, "SyntaxError");
      seen.add(p);
    }
    this._url = u.href;
    this._origin = u.origin;
    this._id = nextSocketId++;
    sockets.set(this._id, this);
    native.wsOpen(this._id, u.href, list, location.origin, acceptLanguage());
  }
  get url() { return this._url; }
  get readyState() { return this._state; }
  get protocol() { return this._protocol; }
  get extensions() { return this._extensions; }
  get bufferedAmount() { return (this._state === 1 || this._state === 2 ? native.wsBuffered(this._id) : 0) + this._unsent; }
  get binaryType() { return this._binaryType; }
  set binaryType(v: BinaryType) { if (v === "blob" || v === "arraybuffer") this._binaryType = v; }

  send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {
    if (arguments.length < 1) throw new TypeError("Failed to execute 'send' on 'WebSocket': 1 argument required, but only 0 present.");
    if (this._state === 0) throw new DOMException("Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.", "InvalidStateError");
    let payload: string | ArrayBuffer | Uint8Array;
    let size: number;
    if (data instanceof Blob) { payload = data[BYTES]; size = payload.length; }
    else if (data instanceof ArrayBuffer) { payload = data; size = data.byteLength; }
    else if (ArrayBuffer.isView(data)) { payload = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); size = data.byteLength; }
    else { payload = String(data); size = -1; }
    if (this._state !== 1) {
      // Spec: after close() the data is not sent but still counts towards bufferedAmount.
      this._unsent += size < 0 ? utf8Length(payload as string) : size;
      return;
    }
    native.wsSend(this._id, payload);
  }

  close(code?: number, reason?: string) {
    let c = -1;
    if (code !== undefined) {
      c = Math.min(65535, Math.max(0, Math.round(Number(code) || 0)));
      if (c !== 1000 && (c < 3000 || c > 4999)) {
        throw new DOMException(`Failed to execute 'close' on 'WebSocket': The close code must be either 1000, or between 3000 and 4999. ${c} is neither.`, "InvalidAccessError");
      }
    }
    let r = "";
    if (reason !== undefined) {
      r = String(reason);
      if (utf8Length(r) > 123) throw new DOMException("Failed to execute 'close' on 'WebSocket': The close reason must not be greater than 123 UTF-8 bytes.", "SyntaxError");
      if (c < 0) c = 1000;
    }
    if (this._state === 2 || this._state === 3) return;
    if (this._state === 0) {
      // Fails the connection: error + close(1006) follow once the native side gives up.
      this._failed = true;
      this._state = 2;
      native.wsClose(this._id, -1, "");
      return;
    }
    this._state = 2;
    native.wsClose(this._id, c, r);
  }
  get [Symbol.toStringTag]() { return "WebSocket"; }
}
for (const [k, v] of [["CONNECTING", 0], ["OPEN", 1], ["CLOSING", 2], ["CLOSED", 3]] as const) {
  Object.defineProperty(WebSocket.prototype, k, { value: v, enumerable: true });
}
defineHandlers(WebSocket.prototype, ["open", "message", "error", "close"]);

function onSocketEvent(kind: number, id: number, a: any, b: any, c: any, d: any) {
  const ws = sockets.get(id);
  if (!ws) return;
  switch (kind) {
    case WS_OPEN:
      if (ws._failed) return;
      ws._state = 1;
      ws._protocol = a;
      ws._extensions = b;
      ws.dispatchEvent(new Event("open"));
      break;
    case WS_TEXT:
      if (ws._state !== 1) return;
      ws.dispatchEvent(new MessageEvent("message", { data: a, origin: ws._origin }));
      break;
    case WS_BINARY: {
      if (ws._state !== 1) return;
      let data: any = a;
      if (ws._binaryType === "blob") { data = new Blob([]); data[BYTES] = new Uint8Array(a); }
      ws.dispatchEvent(new MessageEvent("message", { data, origin: ws._origin }));
      break;
    }
    case WS_CLOSE: {
      sockets.delete(id);
      let [code, reason, clean, error] = [a as number, b as string, c as boolean, d as boolean];
      if (ws._failed) { code = 1006; reason = ""; clean = false; error = true; }
      ws._state = 3;
      if (error) ws.dispatchEvent(new Event("error"));
      ws.dispatchEvent(new CloseEvent("close", { code, reason, wasClean: clean }));
      break;
    }
  }
}

// ---------------------------------------------------------------- Web Audio

const nodeRegistry = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((id) => native.audioRelease(id)) : null;

const EV_SET = 0, EV_LINEAR = 1, EV_EXP = 2, EV_TARGET = 3;
interface ParamEvent { type: number; time: number; value: number; tau: number; t0: number }

function finite(v: any, method: string, what = "value") {
  const n = Number(v);
  if (!Number.isFinite(n)) throw new TypeError(`Failed to execute '${method}' on 'AudioParam': The provided ${what} is non-finite.`);
  return n;
}
function timeArg(t: any, method: string) {
  const n = finite(t, method, "double value");
  if (n < 0) throw new RangeError(`Failed to execute '${method}' on 'AudioParam': The time provided (${n}) is less than 0.`);
  return n;
}

export class AudioParam {
  readonly defaultValue: number;
  readonly minValue: number;
  readonly maxValue: number;
  automationRate: "a-rate" | "k-rate" = "a-rate";
  /** @internal */ _node: AudioNode;
  /** @internal */ _index: number;
  /** @internal */ _intrinsic: number;
  /** @internal */ _events: ParamEvent[] = [];
  constructor(node: AudioNode, index: number, defaultValue: number, min: number, max: number) {
    this._node = node; this._index = index;
    this.defaultValue = defaultValue; this.minValue = min; this.maxValue = max;
    this._intrinsic = defaultValue;
  }
  /** @internal */ _flat() {
    const f = new Float64Array(this._events.length * 5);
    this._events.forEach((e, i) => f.set([e.type, e.time, e.value, e.tau, e.t0], i * 5));
    return f;
  }
  /** @internal */ _sync() { native.audioParam(this._node._id, this._index, this._intrinsic, this._flat()); }
  /** @internal */ _now() { return this._node.context.currentTime; }
  /** @internal */ _insert(e: ParamEvent) {
    const evs = this._events;
    // Same time and type replaces; otherwise it goes after events at the same time.
    const same = evs.findIndex((x) => x.time === e.time && x.type === e.type);
    if (same >= 0) evs[same] = e;
    else {
      let i = evs.length;
      while (i > 0 && evs[i - 1].time > e.time) i--;
      evs.splice(i, 0, e);
    }
    this._prune();
    this._sync();
    return this;
  }
  /** @internal Old events stop mattering once a later one has taken over (keeps the list short
   *  for pages that set `.value` every frame). */
  _prune() {
    if (this._events.length < 64) return;
    const now = this._now() - 0.5;
    let i = -1;
    for (let j = 0; j < this._events.length && this._events[j].time <= now; j++) i = j;
    if (i <= 0 || this._events[i].type === EV_TARGET) return;
    const v = native.audioParamValue(this._flat(), this._intrinsic, this._events[i].time);
    this._events.splice(0, i + 1, { type: EV_SET, time: this._events[i].time, value: v, tau: 0, t0: 0 });
  }
  get value() {
    if (!this._events.length) return this._intrinsic;
    return Math.fround(native.audioParamValue(this._flat(), this._intrinsic, this._now()));
  }
  set value(v: number) {
    const n = finite(v, "value");
    this._intrinsic = n;
    // Setting value is setValueAtTime(value, currentTime) (Web Audio §1.6.2).
    if (this._events.length) this._insert({ type: EV_SET, time: this._now(), value: n, tau: 0, t0: 0 });
    else this._sync();
  }
  setValueAtTime(value: number, time: number) {
    return this._insert({ type: EV_SET, time: timeArg(time, "setValueAtTime"), value: finite(value, "setValueAtTime"), tau: 0, t0: 0 });
  }
  linearRampToValueAtTime(value: number, time: number) {
    return this._insert({ type: EV_LINEAR, time: timeArg(time, "linearRampToValueAtTime"), value: finite(value, "linearRampToValueAtTime"), tau: 0, t0: this._now() });
  }
  exponentialRampToValueAtTime(value: number, time: number) {
    const v = finite(value, "exponentialRampToValueAtTime");
    if (v === 0) throw new RangeError(`Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (${-1.40130e-45}, ${1.40130e-45}).`);
    return this._insert({ type: EV_EXP, time: timeArg(time, "exponentialRampToValueAtTime"), value: v, tau: 0, t0: this._now() });
  }
  setTargetAtTime(target: number, startTime: number, timeConstant: number) {
    const tau = finite(timeConstant, "setTargetAtTime");
    if (tau < 0) throw new RangeError(`Failed to execute 'setTargetAtTime' on 'AudioParam': Time constant (${tau}) is negative.`);
    return this._insert({ type: EV_TARGET, time: timeArg(startTime, "setTargetAtTime"), value: finite(target, "setTargetAtTime"), tau, t0: 0 });
  }
  setValueCurveAtTime(values: ArrayLike<number>, startTime: number, duration: number) {
    const t = timeArg(startTime, "setValueCurveAtTime");
    const d = finite(duration, "setValueCurveAtTime");
    if (d <= 0) throw new RangeError("Failed to execute 'setValueCurveAtTime' on 'AudioParam': The duration must be positive.");
    if (values.length < 2) throw new DOMException("Failed to execute 'setValueCurveAtTime' on 'AudioParam': The curve must have at least 2 values.", "InvalidStateError");
    // A curve is linear interpolation between its points: a set followed by linear ramps.
    const n = values.length;
    this._insert({ type: EV_SET, time: t, value: Number(values[0]), tau: 0, t0: 0 });
    for (let i = 1; i < n; i++) this._insert({ type: EV_LINEAR, time: t + (d * i) / (n - 1), value: Number(values[i]), tau: 0, t0: t });
    return this;
  }
  cancelScheduledValues(cancelTime: number) {
    const t = timeArg(cancelTime, "cancelScheduledValues");
    this._events = this._events.filter((e) => e.time < t);
    this._sync();
    return this;
  }
  cancelAndHoldAtTime(cancelTime: number) {
    const t = timeArg(cancelTime, "cancelAndHoldAtTime");
    const v = native.audioParamValue(this._flat(), this._intrinsic, t);
    const next = this._events.find((e) => e.time >= t);
    this._events = this._events.filter((e) => e.time < t);
    const ramp = next && (next.type === EV_LINEAR || next.type === EV_EXP) ? next.type : EV_SET;
    this._events.push({ type: ramp, time: t, value: v, tau: 0, t0: next?.t0 ?? 0 });
    this._sync();
    return this;
  }
}

export class AudioNode extends EventTarget {
  readonly context: AudioContext;
  readonly numberOfInputs: number;
  readonly numberOfOutputs: number;
  channelCount = 2;
  channelCountMode: ChannelCountMode = "max";
  channelInterpretation: ChannelInterpretation = "speakers";
  /** @internal */ _id: number;
  constructor(context: AudioContext, id: number, inputs: number, outputs: number) {
    super();
    if (!(context instanceof AudioContext)) throw new TypeError("Failed to construct 'AudioNode': parameter 1 is not of type 'BaseAudioContext'.");
    this.context = context; this._id = id; this.numberOfInputs = inputs; this.numberOfOutputs = outputs;
  }
  connect(destination: AudioNode | AudioParam, output = 0, input = 0): any {
    if (destination instanceof AudioParam) {
      if (destination._node.context !== this.context) throw new DOMException("Failed to execute 'connect' on 'AudioNode': cannot connect to an AudioParam belonging to a different audio context.", "InvalidAccessError");
      native.audioConnect(this._id, destination._node._id, destination._index);
      return undefined;
    }
    if (!(destination instanceof AudioNode)) throw new TypeError("Failed to execute 'connect' on 'AudioNode': Overload resolution failed.");
    if (destination.context !== this.context) throw new DOMException("Failed to execute 'connect' on 'AudioNode': cannot connect to an AudioNode belonging to a different audio context.", "InvalidAccessError");
    if (output >= this.numberOfOutputs || input >= destination.numberOfInputs) throw new DOMException("Failed to execute 'connect' on 'AudioNode': output or input index out of range.", "IndexSizeError");
    native.audioConnect(this._id, destination._id, -1);
    return destination;
  }
  disconnect(destination?: AudioNode | AudioParam | number) {
    if (destination instanceof AudioParam) native.audioDisconnect(this._id, destination._node._id, destination._index);
    else if (destination instanceof AudioNode) native.audioDisconnect(this._id, destination._id, -1);
    else native.audioDisconnect(this._id, 0, -1);
  }
}

export class AudioDestinationNode extends AudioNode {
  readonly maxChannelCount = 2;
}

export class GainNode extends AudioNode {
  readonly gain: AudioParam;
  constructor(context: AudioContext, options: { gain?: number } = {}) {
    super(context, native.audioNode(context._id, 1), 1, 1);
    this.gain = new AudioParam(this, 0, 1, -3.4028234663852886e38, 3.4028234663852886e38);
    if (options.gain !== undefined) this.gain.value = options.gain;
    nodeRegistry?.register(this, this._id);
  }
}

const WAVES = ["sine", "square", "sawtooth", "triangle"];

export class PeriodicWave {
  constructor(_context: AudioContext, _options?: any) {}
}

/** Started sources with `ended` listeners stay reachable until they end (as in Chromium), so the
 *  event fires even when the page dropped its reference. */
const playing = new Map<number, AudioScheduledSourceNode>();

export class AudioScheduledSourceNode extends AudioNode {
  /** @internal */ _started = false;
  /** @internal */ _wantEnded = false;
  start(when = 0) {
    const t = Number(when);
    if (!Number.isFinite(t)) throw new TypeError("Failed to execute 'start' on 'AudioScheduledSourceNode': The provided double value is non-finite.");
    if (t < 0) throw new RangeError(`Failed to execute 'start' on 'AudioScheduledSourceNode': The start time provided (${t}) is less than the minimum bound (0).`);
    if (this._started) throw new DOMException("Failed to execute 'start' on 'AudioScheduledSourceNode': cannot call start more than once.", "InvalidStateError");
    this._started = true;
    if (this._wantEnded) playing.set(this._id, this);
    native.audioStart(this._id, t);
  }
  stop(when = 0) {
    const t = Number(when);
    if (!Number.isFinite(t)) throw new TypeError("Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.");
    if (t < 0) throw new RangeError(`Failed to execute 'stop' on 'AudioScheduledSourceNode': The stop time provided (${t}) is less than the minimum bound (0).`);
    if (!this._started) throw new DOMException("Failed to execute 'stop' on 'AudioScheduledSourceNode': cannot call stop without calling start first.", "InvalidStateError");
    native.audioStop(this._id, t);
  }
  override addEventListener(type: string, fn: any, options?: any) {
    if (type === "ended" && !this._wantEnded) {
      this._wantEnded = true;
      native.audioWantEnded(this._id);
      if (this._started) playing.set(this._id, this);
    }
    super.addEventListener(type, fn, options);
  }
}
defineHandlers(AudioScheduledSourceNode.prototype, ["ended"]);

export class OscillatorNode extends AudioScheduledSourceNode {
  readonly frequency: AudioParam;
  readonly detune: AudioParam;
  /** @internal */ _type: OscillatorType = "sine";
  constructor(context: AudioContext, options: { type?: OscillatorType; frequency?: number; detune?: number } = {}) {
    super(context, native.audioNode(context._id, 2), 0, 1);
    const nyquist = context.sampleRate / 2;
    this.frequency = new AudioParam(this, 0, 440, -nyquist, nyquist);
    this.detune = new AudioParam(this, 1, 0, -153600, 153600);
    if (options.type !== undefined) this.type = options.type;
    if (options.frequency !== undefined) this.frequency.value = options.frequency;
    if (options.detune !== undefined) this.detune.value = options.detune;
    nodeRegistry?.register(this, this._id);
  }
  get type() { return this._type; }
  set type(t: OscillatorType) {
    if (t === "custom") throw new DOMException("Failed to set the 'type' property on 'OscillatorNode': 'type' cannot be set directly to 'custom'.  Use setPeriodicWave() to create a custom Oscillator type.", "InvalidStateError");
    const i = WAVES.indexOf(t);
    if (i < 0) return; // invalid enum values are ignored
    this._type = t;
    native.audioWave(this._id, i);
  }
  setPeriodicWave(_wave: PeriodicWave) {
    // Custom waveforms are not synthesised; they play as a sine.
    this._type = "custom";
    native.audioWave(this._id, 0);
  }
}

type AudioState = "suspended" | "running" | "closed";

export class AudioContext extends EventTarget {
  readonly sampleRate: number;
  readonly destination: AudioDestinationNode;
  readonly baseLatency: number;
  readonly outputLatency: number;
  readonly listener = {};
  readonly audioWorklet = undefined;
  /** @internal */ _id: number;
  /** @internal */ _state: AudioState = "running";
  /** @internal */ _closedAt = 0;
  constructor(_options: { latencyHint?: any; sampleRate?: number } = {}) {
    super();
    this._id = native.audioCreate();
    this.sampleRate = native.audioRate();
    this.baseLatency = 256 / this.sampleRate;
    this.outputLatency = 512 / this.sampleRate;
    this.destination = new AudioDestinationNode(this, this._id, 1, 0);
    // Pages that let go of a context without close() still release it.
    contextRegistry?.register(this, this._id);
  }
  get currentTime() { return this._state === "closed" ? this._closedAt : native.audioTime(this._id); }
  get state() { return this._state; }
  /** @internal */ _setState(s: AudioState) {
    if (this._state === s) return;
    this._state = s;
    setTimeout(() => this.dispatchEvent(new Event("statechange")), 0);
  }
  createOscillator() { return new OscillatorNode(this); }
  createGain() { return new GainNode(this); }
  createPeriodicWave(real: ArrayLike<number>, imag: ArrayLike<number>, _constraints?: any) {
    if (real.length !== imag.length || real.length < 2) throw new DOMException("Failed to execute 'createPeriodicWave' on 'BaseAudioContext': length mismatch.", "IndexSizeError");
    return new PeriodicWave(this);
  }
  getOutputTimestamp() { return { contextTime: this.currentTime, performanceTime: performance.now() }; }
  resume(): Promise<void> {
    if (this._state === "closed") return Promise.reject(new DOMException("Cannot resume a closed AudioContext.", "InvalidStateError"));
    native.audioResume(this._id);
    this._setState("running");
    return Promise.resolve();
  }
  suspend(): Promise<void> {
    if (this._state === "closed") return Promise.reject(new DOMException("Cannot suspend a closed AudioContext.", "InvalidStateError"));
    native.audioSuspend(this._id);
    this._setState("suspended");
    return Promise.resolve();
  }
  close(): Promise<void> {
    if (this._state === "closed") return Promise.reject(new DOMException("Cannot close a closed AudioContext.", "InvalidStateError"));
    this._closedAt = this.currentTime;
    native.audioClose(this._id);
    this._setState("closed");
    return Promise.resolve();
  }
}
defineHandlers(AudioContext.prototype, ["statechange"]);
const contextRegistry = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((id) => native.audioClose(id)) : null;

function onAudioEnded(id: number) {
  const node = playing.get(id);
  playing.delete(id);
  node?.dispatchEvent(new Event("ended"));
}

// ---------------------------------------------------------------- install

export function installNet() {
  native.setHandler((kind, id, a, b, c, d, e, f) => {
    switch (kind) {
      case FETCH_HEAD: onFetchHead(id, a, b, c, d, e, f); break;
      case FETCH_BODY: onFetchBody(id, a); break;
      case FETCH_ERROR: onFetchError(id, a); break;
      case AUDIO_ENDED: onAudioEnded(id); break;
      default: onSocketEvent(kind, id, a, b, c, d);
    }
  }, navigator.userAgent);
  Object.assign(g, {
    fetch, Request, Response, Headers, Blob, File, FormData, WebSocket,
    AudioContext, webkitAudioContext: AudioContext, BaseAudioContext: AudioContext, AudioNode, AudioParam, GainNode, OscillatorNode,
    AudioScheduledSourceNode, AudioDestinationNode, PeriodicWave,
  });
}