Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Text · 51 lines · 1.8 KiB · at 503e839

import { Ok, Err, type Result } from "@tsus/runtime";export type PathError =  | { kind: "invalid_cwd" }  | { kind: "escapes_root"; input: string }  | { kind: "not_absolute"; path: string };const walk = (start: string[], path: string, input: string): Result<string[], PathError> => {  const out = [...start];  for (const seg of path.split("/")) {    if (seg === "" || seg === ".") {      continue;    }    if (seg === "..") {      if (out.length === 0) {        return Err({ kind: "escapes_root", input });      }      out.pop();    } else {      out.push(seg);    }  }  return Ok(out);};const join = (segs: string[]): string => "/" + segs.join("/");export const resolvePath = (cwd: string, input: string): Result<string, PathError> =>  !cwd.startsWith("/")    ? Err({ kind: "invalid_cwd" })    : (input.startsWith("/") ? Ok([]) : walk([], cwd, input)).andThen((base: string[]) =>        walk(base, input, input).map(join),      );const absolute = (path: string): Result<string[], PathError> =>  path.startsWith("/") ? walk([], path, path) : Err({ kind: "not_absolute", path });const relative = (a: string[], b: string[]): string => {  let k = 0;  while (k < a.length && k < b.length && a[k] === b[k]) {    k++;  }  const parts = [...a.slice(k).map(() => ".."), ...b.slice(k)];  return parts.length === 0 ? "." : parts.join("/");};const checkAbsolute = (from: string, to: string): Result<true, PathError> =>  !from.startsWith("/") ? Err({ kind: "not_absolute", path: from }) : !to.startsWith("/") ? Err({ kind: "not_absolute", path: to }) : Ok(true);export const relativeTo = (from: string, to: string): Result<string, PathError> =>  checkAbsolute(from, to).andThen(() => absolute(from).andThen((a) => absolute(to).map((b) => relative(a, b))));