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.

17.9 KB
Raw Blame
// Web platform utilities JavaScriptCore does not include: URL, URLSearchParams, TextEncoder/Decoder,
// atob/btoa, crypto, AbortController, structuredClone.
import { Event, EventTarget, DOMExceptionImpl } from "./events.ts";

// ---------------------------------------------------------------- URLSearchParams
const enc = (s: string) => encodeURIComponent(s).replace(/%20/g, "+").replace(/[!'()~]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
const dec = (s: string) => { try { return decodeURIComponent(s.replace(/\+/g, " ")); } catch { return s; } };

export class URLSearchParams {
  /** @internal */ _list: [string, string][] = [];
  /** @internal */ _url: URL | null = null;
  constructor(init?: string | Record<string, string> | [string, string][] | URLSearchParams) {
    if (init == null) return;
    if (typeof init === "string") this._parse(init);
    else if (init instanceof URLSearchParams) this._list = init._list.map(([k, v]) => [k, v]);
    else if (Array.isArray(init) || typeof (init as any)[Symbol.iterator] === "function") for (const [k, v] of init as any) this._list.push([String(k), String(v)]);
    else for (const k of Object.keys(init)) this._list.push([k, String((init as any)[k])]);
  }
  /** @internal */ _parse(s: string) {
    this._list = [];
    for (const part of s.replace(/^\?/, "").split("&")) {
      if (!part) continue;
      const i = part.indexOf("=");
      this._list.push(i < 0 ? [dec(part), ""] : [dec(part.slice(0, i)), dec(part.slice(i + 1))]);
    }
  }
  /** @internal */ _update() { if (this._url) { const s = this.toString(); this._url._search = s ? "?" + s : ""; } }
  get size() { return this._list.length; }
  append(k: string, v: string) { this._list.push([String(k), String(v)]); this._update(); }
  delete(k: string, v?: string) { this._list = this._list.filter(([a, b]) => a !== k || (v !== undefined && b !== v)); this._update(); }
  get(k: string) { return this._list.find(([a]) => a === k)?.[1] ?? null; }
  getAll(k: string) { return this._list.filter(([a]) => a === k).map(([, b]) => b); }
  has(k: string, v?: string) { return this._list.some(([a, b]) => a === k && (v === undefined || b === v)); }
  set(k: string, v: string) {
    const i = this._list.findIndex(([a]) => a === k);
    if (i < 0) this._list.push([String(k), String(v)]);
    else { this._list[i][1] = String(v); this._list = this._list.filter(([a], j) => a !== k || j === i); }
    this._update();
  }
  sort() { this._list.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); this._update(); }
  forEach(cb: (v: string, k: string, p: URLSearchParams) => void, thisArg?: any) { for (const [k, v] of this._list) cb.call(thisArg, v, k, this); }
  keys() { return this._list.map(([k]) => k)[Symbol.iterator](); }
  values() { return this._list.map(([, v]) => v)[Symbol.iterator](); }
  entries() { return this._list.map(([k, v]) => [k, v] as [string, string])[Symbol.iterator](); }
  [Symbol.iterator]() { return this.entries(); }
  toString() { return this._list.map(([k, v]) => enc(k) + "=" + enc(v)).join("&"); }
}

// ---------------------------------------------------------------- URL
const SPECIAL: Record<string, string> = { "http:": "80", "https:": "443", "ws:": "80", "wss:": "443", "ftp:": "21", "file:": "" };

function normalizePath(path: string, special: boolean) {
  const out: string[] = [];
  const parts = path.split("/");
  for (let i = 0; i < parts.length; i++) {
    const p = parts[i];
    if (p === "." || p.toLowerCase() === "%2e") { if (i === parts.length - 1) out.push(""); continue; }
    if (p === ".." || /^(\.|%2e){2}$/i.test(p)) { if (out.length > 1) out.pop(); if (i === parts.length - 1) out.push(""); continue; }
    out.push(p);
  }
  let s = out.join("/");
  if (special && !s.startsWith("/")) s = "/" + s;
  return s.replace(/[\s"<>`{}]/g, (c) => encodeURIComponent(c));
}

export class URL {
  /** @internal */ _protocol = ""; /** @internal */ _username = ""; /** @internal */ _password = "";
  /** @internal */ _hostname = ""; /** @internal */ _port = ""; /** @internal */ _pathname = "";
  /** @internal */ _search = ""; /** @internal */ _hash = ""; /** @internal */ _opaque = false;
  /** @internal */ _params: URLSearchParams | null = null;

  constructor(input: string | URL, base?: string | URL) {
    const s = String(input).trim().replace(/[\t\n\r]/g, "");
    const m = /^([a-zA-Z][a-zA-Z0-9+.-]*):(.*)$/.exec(s);
    if (m) this._parseAbsolute(m[1].toLowerCase() + ":", m[2]);
    else {
      if (base === undefined) throw new TypeError(`Invalid URL: ${s}`);
      const b = base instanceof URL ? base : new URL(base);
      this._resolve(s, b);
    }
  }
  static canParse(u: string, b?: string) { try { new URL(u, b); return true; } catch { return false; } }
  static parse(u: string, b?: string) { try { return new URL(u, b); } catch { return null; } }

  /** @internal */ _parseAbsolute(protocol: string, rest: string) {
    this._protocol = protocol;
    const special = protocol in SPECIAL;
    if (special) rest = rest.replace(/\\/g, "/");
    if (rest.startsWith("//") || (special && protocol !== "file:")) {
      rest = rest.replace(/^\/*/, "");
      const end = rest.search(/[/?#]/);
      const auth = end < 0 ? rest : rest.slice(0, end);
      this._setAuthority(auth);
      this._splitPath(end < 0 ? "" : rest.slice(end), special);
    } else if (protocol === "file:") {
      this._splitPath(rest, true);
    } else {
      this._opaque = !rest.startsWith("/");
      this._splitPath(rest, false);
    }
  }
  /** @internal */ _setAuthority(auth: string) {
    const at = auth.lastIndexOf("@");
    if (at >= 0) {
      const cred = auth.slice(0, at);
      auth = auth.slice(at + 1);
      const c = cred.indexOf(":");
      this._username = c < 0 ? cred : cred.slice(0, c);
      this._password = c < 0 ? "" : cred.slice(c + 1);
    }
    const pm = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(auth);
    if (!pm) throw new TypeError("Invalid URL host");
    this._hostname = pm[1].toLowerCase();
    const port = pm[2] ?? "";
    this._port = port && SPECIAL[this._protocol] === port ? "" : port;
    if (!this._hostname && this._protocol in SPECIAL && this._protocol !== "file:") throw new TypeError("Invalid URL: empty host");
  }
  /** @internal */ _splitPath(rest: string, special: boolean) {
    const h = rest.indexOf("#");
    if (h >= 0) { this._hash = rest.slice(h) === "#" ? "" : rest.slice(h); rest = rest.slice(0, h); }
    const q = rest.indexOf("?");
    if (q >= 0) { this._search = rest.slice(q) === "?" ? "" : rest.slice(q); rest = rest.slice(0, q); }
    this._pathname = this._opaque ? rest : normalizePath(rest, special);
  }
  /** @internal */ _resolve(s: string, b: URL) {
    Object.assign(this, { _protocol: b._protocol, _username: b._username, _password: b._password, _hostname: b._hostname, _port: b._port });
    const special = b._protocol in SPECIAL;
    if (special) s = s.replace(/\\/g, "/");
    if (s.startsWith("//")) { this._parseAbsolute(b._protocol, s); return; }
    if (s.startsWith("#")) { this._pathname = b._pathname; this._search = b._search; this._hash = s === "#" ? "" : s; return; }
    if (s.startsWith("?")) { this._pathname = b._pathname; this._splitPath(s, special); return; }
    if (s === "") { this._pathname = b._pathname; this._search = b._search; return; }
    if (s.startsWith("/")) { this._splitPath(s, special); return; }
    const dir = b._pathname.slice(0, b._pathname.lastIndexOf("/") + 1);
    this._splitPath(dir + s, special);
  }

  get protocol() { return this._protocol; }
  set protocol(v: string) { const p = String(v).replace(/:?$/, ":").toLowerCase(); if (/^[a-z][a-z0-9+.-]*:$/.test(p)) { this._protocol = p; if (SPECIAL[p] === this._port) this._port = ""; } }
  get username() { return this._username; } set username(v: string) { this._username = String(v); }
  get password() { return this._password; } set password(v: string) { this._password = String(v); }
  get hostname() { return this._hostname; } set hostname(v: string) { this._hostname = String(v).toLowerCase(); }
  get port() { return this._port; } set port(v: string) { const p = String(v); this._port = p === SPECIAL[this._protocol] ? "" : p.replace(/\D.*$/, ""); }
  get host() { return this._hostname + (this._port ? ":" + this._port : ""); }
  set host(v: string) { this._setAuthority(String(v)); }
  get origin() { return this._protocol in SPECIAL && this._protocol !== "file:" ? `${this._protocol}//${this.host}` : "null"; }
  get pathname() { return this._pathname; }
  set pathname(v: string) { if (!this._opaque) this._pathname = normalizePath(String(v), this._protocol in SPECIAL); }
  get search() { return this._search; }
  set search(v: string) { const s = String(v); this._search = s === "" || s === "?" ? "" : s.startsWith("?") ? s : "?" + s; this._params?._parse(this._search); }
  get searchParams() { if (!this._params) { this._params = new URLSearchParams(this._search); this._params._url = this; } return this._params; }
  get hash() { return this._hash; }
  set hash(v: string) { const s = String(v); this._hash = s === "" || s === "#" ? "" : s.startsWith("#") ? s : "#" + s; }
  get href() {
    const auth = this._username ? this._username + (this._password ? ":" + this._password : "") + "@" : "";
    const slashes = this._opaque ? "" : this._protocol in SPECIAL || this._hostname ? "//" : "";
    return this._protocol + slashes + auth + this.host + this._pathname + this._search + this._hash;
  }
  set href(v: string) { const u = new URL(v); Object.assign(this, u); this._params = null; }
  toString() { return this.href; }
  toJSON() { return this.href; }
  static createObjectURL(_b: unknown): string { throw new DOMExceptionImpl("createObjectURL is not supported", "NotSupportedError"); }
  static revokeObjectURL(_u: string) {}
}

// ---------------------------------------------------------------- text encoding
// Native UTF-8 codecs (crates/net) when present; the JS fallbacks below keep the runtime self-contained.
const nativeNet = (globalThis as any).__native?.net as { utf8Decode?(b: ArrayBuffer | ArrayBufferView): string; utf8Encode?(s: string): Uint8Array } | undefined;

export class TextEncoder {
  readonly encoding = "utf-8";
  encode(s = ""): Uint8Array {
    if (nativeNet?.utf8Encode) return nativeNet.utf8Encode(String(s));
    const str = String(s);
    const out = new Uint8Array(str.length * 3);
    let n = 0;
    for (let i = 0; i < str.length; i++) {
      let c = str.charCodeAt(i);
      if (c >= 0xd800 && c < 0xdc00 && i + 1 < str.length) {
        const d = str.charCodeAt(i + 1);
        if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; }
        else c = 0xfffd;
      } else if (c >= 0xd800 && c < 0xe000) c = 0xfffd;
      if (c < 0x80) out[n++] = c;
      else if (c < 0x800) { out[n++] = 0xc0 | (c >> 6); out[n++] = 0x80 | (c & 63); }
      else if (c < 0x10000) { out[n++] = 0xe0 | (c >> 12); out[n++] = 0x80 | ((c >> 6) & 63); out[n++] = 0x80 | (c & 63); }
      else { out[n++] = 0xf0 | (c >> 18); out[n++] = 0x80 | ((c >> 12) & 63); out[n++] = 0x80 | ((c >> 6) & 63); out[n++] = 0x80 | (c & 63); }
    }
    return out.slice(0, n);
  }
  encodeInto(s: string, dest: Uint8Array) { const b = this.encode(s); const n = Math.min(b.length, dest.length); dest.set(b.subarray(0, n)); return { read: s.length, written: n }; }
}

export class TextDecoder {
  readonly encoding: string; readonly fatal: boolean; readonly ignoreBOM: boolean;
  constructor(label = "utf-8", opts: { fatal?: boolean; ignoreBOM?: boolean } = {}) {
    this.encoding = label.toLowerCase().replace("utf8", "utf-8"); this.fatal = !!opts.fatal; this.ignoreBOM = !!opts.ignoreBOM;
  }
  decode(input?: ArrayBuffer | ArrayBufferView): string {
    if (!input) return "";
    const b = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
    if ((this.encoding === "utf-8" || this.encoding === "unicode-1-1-utf-8") && !this.fatal && nativeNet?.utf8Decode) {
      const skip = !this.ignoreBOM && b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf ? 3 : 0;
      return nativeNet.utf8Decode(skip ? b.subarray(skip) : b);
    }
    if (this.encoding === "utf-16le") { let s = ""; for (let i = 0; i + 1 < b.length; i += 2) s += String.fromCharCode(b[i] | (b[i + 1] << 8)); return s; }
    if (this.encoding === "latin1" || this.encoding === "iso-8859-1" || this.encoding === "ascii") { let s = ""; for (const x of b) s += String.fromCharCode(x); return s; }
    const parts: string[] = [];
    let chunk: number[] = [];
    let i = !this.ignoreBOM && b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf ? 3 : 0;
    while (i < b.length) {
      const c = b[i];
      let cp = 0xfffd, len = 1;
      if (c < 0x80) { cp = c; }
      else if (c >= 0xc2 && c < 0xe0 && (b[i + 1] & 0xc0) === 0x80) { cp = ((c & 31) << 6) | (b[i + 1] & 63); len = 2; }
      else if (c >= 0xe0 && c < 0xf0 && (b[i + 1] & 0xc0) === 0x80 && (b[i + 2] & 0xc0) === 0x80) { cp = ((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63); len = 3; }
      else if (c >= 0xf0 && c < 0xf5 && (b[i + 1] & 0xc0) === 0x80 && (b[i + 2] & 0xc0) === 0x80 && (b[i + 3] & 0xc0) === 0x80) {
        cp = ((c & 7) << 18) | ((b[i + 1] & 63) << 12) | ((b[i + 2] & 63) << 6) | (b[i + 3] & 63); len = 4;
      } else if (this.fatal) throw new TypeError("The encoded data was not valid utf-8");
      i += len;
      if (cp > 0xffff) { cp -= 0x10000; chunk.push(0xd800 + (cp >> 10), 0xdc00 + (cp & 1023)); } else chunk.push(cp);
      if (chunk.length > 8192) { parts.push(String.fromCharCode(...chunk)); chunk = []; }
    }
    parts.push(String.fromCharCode(...chunk));
    return parts.join("");
  }
}

// ---------------------------------------------------------------- base64
const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const B64R = new Int16Array(128).fill(-1);
for (let i = 0; i < 64; i++) B64R[B64.charCodeAt(i)] = i;

export function btoa(input: string): string {
  const s = String(input);
  let out = "";
  for (let i = 0; i < s.length; i += 3) {
    const a = s.charCodeAt(i), b = s.charCodeAt(i + 1), c = s.charCodeAt(i + 2);
    if (a > 255 || b > 255 || c > 255) throw new DOMExceptionImpl("The string to be encoded contains characters outside of the Latin1 range.", "InvalidCharacterError");
    const n = (a << 16) | ((b || 0) << 8) | (c || 0);
    out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (i + 1 < s.length ? B64[(n >> 6) & 63] : "=") + (i + 2 < s.length ? B64[n & 63] : "=");
  }
  return out;
}

export function atob(input: string): string {
  const s = String(input).replace(/[\t\n\f\r ]/g, "").replace(/={1,2}$/, "");
  if (s.length % 4 === 1 || /[^A-Za-z0-9+/]/.test(s)) throw new DOMExceptionImpl("The string to be decoded is not correctly encoded.", "InvalidCharacterError");
  let out = "";
  let buf = 0, bits = 0;
  for (let i = 0; i < s.length; i++) {
    buf = (buf << 6) | B64R[s.charCodeAt(i)];
    bits += 6;
    if (bits >= 8) { bits -= 8; out += String.fromCharCode((buf >> bits) & 255); }
  }
  return out;
}

/** bytes → base64 (fast path used by canvas.toDataURL etc.) */
export function bytesToBase64(b: Uint8Array): string {
  let s = "";
  for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000));
  return btoa(s);
}
export function base64ToBytes(s: string): Uint8Array {
  const bin = atob(s);
  const out = new Uint8Array(bin.length);
  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
  return out;
}

// ---------------------------------------------------------------- crypto
const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
export const crypto = {
  getRandomValues<T extends ArrayBufferView | null>(a: T): T {
    if (!a) return a;
    if ((a as any).byteLength > 65536) throw new DOMExceptionImpl("quota exceeded", "QuotaExceededError");
    __native.sys.randomBytes(a as any);
    return a;
  },
  randomUUID(): string {
    const b = crypto.getRandomValues(new Uint8Array(16));
    b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80;
    const h = hex(b);
    return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
  },
  subtle: undefined as any,
};

// ---------------------------------------------------------------- AbortController
export class AbortSignal extends EventTarget {
  aborted = false;
  reason: any = undefined;
  onabort: ((e: Event) => void) | null = null;
  static abort(reason?: any) { const c = new AbortController(); c.abort(reason); return c.signal; }
  static timeout(ms: number) { const c = new AbortController(); (globalThis as any).setTimeout(() => c.abort(new DOMExceptionImpl("signal timed out", "TimeoutError")), ms); return c.signal; }
  throwIfAborted() { if (this.aborted) throw this.reason; }
}
export class AbortController {
  readonly signal = new AbortSignal();
  abort(reason?: any) {
    const s = this.signal;
    if (s.aborted) return;
    s.aborted = true;
    s.reason = reason ?? new DOMExceptionImpl("This operation was aborted", "AbortError");
    const e = new Event("abort");
    s.onabort?.(e);
    s.dispatchEvent(e);
  }
}

// ---------------------------------------------------------------- structuredClone
export function structuredClone<T>(v: T, seen = new Map<any, any>()): T {
  if (typeof v !== "object" || v === null) return v;
  if (seen.has(v)) return seen.get(v);
  if (v instanceof Date) return new Date(v.getTime()) as any;
  if (v instanceof RegExp) return new RegExp(v.source, v.flags) as any;
  if (ArrayBuffer.isView(v)) return (v as any).slice() as any;
  if (v instanceof ArrayBuffer) return v.slice(0) as any;
  if (v instanceof Map) { const m = new Map(); seen.set(v, m); for (const [k, x] of v) m.set(structuredClone(k, seen), structuredClone(x, seen)); return m as any; }
  if (v instanceof Set) { const s = new Set(); seen.set(v, s); for (const x of v) s.add(structuredClone(x, seen)); return s as any; }
  if (Array.isArray(v)) { const a: any[] = []; seen.set(v, a); for (const x of v) a.push(structuredClone(x, seen)); return a as any; }
  const o: any = {};
  seen.set(v, o);
  for (const k of Object.keys(v)) o[k] = structuredClone((v as any)[k], seen);
  return o;
}