Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

JavaScript · 185 lines · 6.1 KiB · at 74947de

// Language-neutral helpers for the hidden tests.//// Each task's test.mjs runs against compiled JS from either a .ts or a .tsus// solution. The two languages express absence and failure differently:////   absence:  .ts -> undefined (or null)      .tsus -> None / Some(v)//   failure:  .ts -> throws { kind, ... }      .tsus -> Err({ kind, ... }) / Ok(v)//// Tests never look at those representations directly. They build inputs with// h.some/h.none/h.ok/h.err and read outputs with h.opt/h.res, which normalize// both languages to one canonical shape:////   h.opt(v)      -> { some: true, value } | { some: false }//   h.res(fn)     -> { ok: true, value } | { ok: false, error } | { crash: "..." }//// A crash is any exception that is not a typed task error (in .ts) or any// exception at all (in .tsus). Crashes always fail the assertion they reach,// which is the point: an unexpected TypeError is a bug, not an error value.import { Some, None, Ok, Err } from "@tsus/runtime";export const lang = process.env.TSUS_EVAL_LANG === "tsus" ? "tsus" : "ts";export const solutionPath = process.env.TSUS_EVAL_SOLUTION;export const load = async () => {  if (!solutionPath) {    throw new Error("TSUS_EVAL_SOLUTION is not set");  }  return import(solutionPath);};const isTypedError = (e) => e !== null && typeof e === "object" && typeof e.kind === "string";const describeCrash = (e) => {  if (e instanceof Error) {    return `${e.name}: ${e.message}`;  }  try {    return `non-error thrown: ${JSON.stringify(e)}`;  } catch {    return `non-error thrown: ${String(e)}`;  }};const toPlainError = (e) => {  // Typed errors in .ts are usually Error subclasses with a kind field. Keep  // only own enumerable data fields so deepEqual compares just the contract.  // Error bookkeeping (`stack`, `message`, and a `name` set to the class name  // by the common `this.name = "FooError"` idiom) is dropped; a contract field  // called `name` with any other value is kept. Keys holding `undefined` are  // dropped too: with ES2022 class fields, an optional field the constructor  // never set is an own property whose value is undefined, and the .tsus error  // object simply would not have that key.  const out = {};  for (const key of Object.keys(e)) {    if (key === "stack" || key === "message" || e[key] === undefined) {      continue;    }    if (key === "name" && e instanceof Error && typeof e.name === "string" && /Error$/.test(e.name)) {      continue;    }    out[key] = e[key];  }  return out;};const normalizeOption = (v) => {  if (lang === "ts") {    return v === undefined || v === null ? { some: false } : { some: true, value: v };  }  if (v !== null && typeof v === "object" && v.tag === "Some") {    return { some: true, value: v.value };  }  if (v !== null && typeof v === "object" && v.tag === "None") {    return { some: false };  }  return { invalid: `expected Option, got ${describeValue(v)}` };};const describeValue = (v) => {  try {    return JSON.stringify(v) ?? String(v);  } catch {    return String(v);  }};const normalizeResultValue = (v) => {  if (lang === "ts") {    return { ok: true, value: v };  }  if (v !== null && typeof v === "object" && v.tag === "Ok") {    return { ok: true, value: v.value };  }  if (v !== null && typeof v === "object" && v.tag === "Err") {    return isTypedError(v.error)      ? { ok: false, error: toPlainError(v.error) }      : { ok: false, untypedError: describeValue(v.error) };  }  return { invalid: `expected Result, got ${describeValue(v)}` };};const normalizeThrown = (e) => {  if (lang === "ts" && isTypedError(e)) {    return { ok: false, error: toPlainError(e) };  }  return { crash: describeCrash(e) };};export const h = {  lang,  // --- building inputs ---  some: (v) => (lang === "tsus" ? Some(v) : v),  none: () => (lang === "tsus" ? None : undefined),  // An optional input value: pass `absent` to mean "not provided".  maybe: (v, absent = undefined) => (v === absent ? h.none() : h.some(v)),  // A dependency that can fail. In .ts it returns or throws; in .tsus it  // returns Ok/Err. `error` must be a { kind } object.  okValue: (v) => (lang === "tsus" ? Ok(v) : v),  failWith: (error) => {    if (lang === "tsus") {      return Err(error);    }    throw Object.assign(new Error(error.message ?? error.kind), error);  },  // Async dependency outcomes.  resolveOk: (v) => Promise.resolve(lang === "tsus" ? Ok(v) : v),  resolveErr: (error) =>    lang === "tsus"      ? Promise.resolve(Err(error))      : Promise.reject(Object.assign(new Error(error.message ?? error.kind), error)),  // --- reading outputs ---  opt: normalizeOption,  // Read an optional field off a returned record.  field: (obj, key) => normalizeOption(obj?.[key]),  // Canonicalize a returned record: every key in optKeys becomes  // { some, value } / { some: false }, so `{ a: 1 }` (.ts, b omitted) and  // `{ a: 1, b: None }` (.tsus) compare equal. Other keys pass through.  shape: (obj, optKeys) => {    if (obj === null || typeof obj !== "object") {      return { notARecord: describeValue(obj) };    }    const out = {};    for (const [key, value] of Object.entries(obj)) {      if (!optKeys.includes(key)) {        out[key] = value;      }    }    for (const key of optKeys) {      out[key] = normalizeOption(obj[key]);    }    return out;  },  res: (fn) => {    try {      return normalizeResultValue(fn());    } catch (e) {      return normalizeThrown(e);    }  },  resAsync: async (fn) => {    try {      return normalizeResultValue(await fn());    } catch (e) {      return normalizeThrown(e);    }  },  // Call a function that should neither fail nor crash; returns its value.  call: (fn) => {    try {      return fn();    } catch (e) {      return { crash: describeCrash(e) };    }  },  // Unwrap an ok result for further inspection, or return a marker that will  // fail any deepEqual it reaches.  okOf: (r) => (r.ok === true ? r.value : { notOk: r }),};export const ok = (value) => ({ ok: true, value });export const err = (error) => ({ ok: false, error });export const some = (value) => ({ some: true, value });export const none = { some: false };