fromWire

tcmts.cli.codec.fromWire · #b6ijtxgb · term · runs anywhere

import type { Tagged } from "#codebase/tcmts/cli/codec";

export function fromWire(v: unknown): unknown {
  if (v === null || typeof v !== "object") return v;
  if (Array.isArray(v)) return v.map(fromWire);
  const o = v as Record<string, unknown>;
  const keys = Object.keys(o);
  if (keys.length === 1) {
    const t = v as Tagged;
    if ("$u" in t) return undefined;
    if ("$d" in t) return new Date(t.$d);
    if ("$b" in t) return BigInt(t.$b);
    if ("$n" in t) return t.$n === "-0" ? -0 : Number(t.$n);
    if ("$m" in t) return new Map((t.$m as [unknown, unknown][]).map(([k, x]) => [fromWire(k), fromWire(x)]));
    if ("$s" in t) return new Set(t.$s.map(fromWire));
    if ("$o" in t) return Object.fromEntries(Object.entries(t.$o).map(([k, x]) => [k, fromWire(x)]));
  }
  return Object.fromEntries(keys.map((k) => [k, fromWire(o[k])]));
}

uses

used by