import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime";import { fromNullable } from "@tsus/runtime/boundary";export type PathError = { kind: "invalid_path"; path: string };type Step = { isIndex: boolean; key: string; index: number };const isDigit = (c: string): boolean => c.length === 1 && c >= "0" && c <= "9";const isKeyChar = (c: string): boolean => c.length === 1 && c !== "." && c !== "[" && c !== "]";const scan = (path: string, from: number, ok: (c: string) => boolean): number => { let i = from; while (i < path.length && ok(path.charAt(i))) { i += 1; } return i;};const parsePath = (path: string): Option<Step[]> => { if (path.length === 0) { return None; } const steps: Step[] = []; let i = 0; while (i < path.length) { const c = path.charAt(i); if (c === "[") { const end = scan(path, i + 1, isDigit); if (end === i + 1 || path.charAt(end) !== "]") { return None; } steps.push({ isIndex: true, key: "", index: Number(path.slice(i + 1, end)) }); i = end + 1; } else if (c === "." && steps.length > 0) { const end = scan(path, i + 1, isKeyChar); if (end === i + 1) { return None; } steps.push({ isIndex: false, key: path.slice(i + 1, end), index: 0 }); i = end; } else if (steps.length === 0) { const end = scan(path, i, isKeyChar); if (end === i) { return None; } steps.push({ isIndex: false, key: path.slice(i, end), index: 0 }); i = end; } else { return None; } } return Some(steps);};const isPlainObject = (v: unknown): boolean => typeof v === "object" && fromNullable(v).isSome() && !Array.isArray(v);const applyStep = (cur: unknown, step: Step): Option<unknown> => step.isIndex ? Array.isArray(cur) && step.index < cur.length ? fromNullable(cur[step.index]) : None : isPlainObject(cur) && Object.hasOwn(cur as object, step.key) ? fromNullable((cur as Record<string, unknown>)[step.key]) : None;const walk = (obj: unknown, steps: Step[]): Option<unknown> => steps.reduce((acc: Option<unknown>, step: Step) => acc.andThen((cur) => applyStep(cur, step)), fromNullable(obj));export const getPath = (obj: unknown, path: string): Result<Option<unknown>, PathError> => match (parsePath(path)) { Some(steps) => Ok(walk(obj, steps)), None => Err({ kind: "invalid_path", path }), };