Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : client/src/lib/research/files.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/** The workspace as a tree, what each file is, and a small CSV reader for the table preview. */46import type { RestFile } from "./types";4748export interface TreeNode {49 name: string;50 path: string;51 type: "dir" | "file";52 bytes: number;53 modifiedAt: number | null;54 children: TreeNode[];55 /** number of files below (directories) */56 fileCount: number;57}5859/** Builds the tree from the flat recursive listing. Directories first, then names (numeric-aware). */60export function buildTree(files: RestFile[]): TreeNode[] {61 const root: TreeNode = { name: "", path: "", type: "dir", bytes: 0, modifiedAt: null, children: [], fileCount: 0 };62 const dirs = new Map<string, TreeNode>([["", root]]);63 const dir = (path: string): TreeNode => {64 const known = dirs.get(path);65 if (known) return known;66 const i = path.lastIndexOf("/");67 const node: TreeNode = { name: path.slice(i + 1), path, type: "dir", bytes: 0, modifiedAt: null, children: [], fileCount: 0 };68 dirs.set(path, node);69 dir(i < 0 ? "" : path.slice(0, i)).children.push(node);70 return node;71 };72 for (const f of files) {73 if (!f.path) continue;74 if (f.type === "dir") { dir(f.path).modifiedAt = f.modifiedAt ?? null; continue; }75 const i = f.path.lastIndexOf("/");76 dir(i < 0 ? "" : f.path.slice(0, i)).children.push({ name: f.path.slice(i + 1), path: f.path, type: "file", bytes: f.bytes, modifiedAt: f.modifiedAt ?? null, children: [], fileCount: 1 });77 }78 const finish = (n: TreeNode): void => {79 if (n.type === "file") return;80 n.children.forEach(finish);81 n.children.sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name, "fr", { numeric: true }) : a.type === "dir" ? -1 : 1));82 n.bytes = n.children.reduce((s, c) => s + c.bytes, 0);83 n.fileCount = n.children.reduce((s, c) => s + c.fileCount, 0);84 };85 finish(root);86 return root.children;87}8889export type FileKind = "code" | "table" | "text" | "json" | "image" | "pdf" | "data" | "log" | "other";9091export function fileKind(path: string): FileKind {92 const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase();93 const ext = name.includes(".") ? name.slice(name.lastIndexOf(".")) : "";94 if ([".py", ".r", ".sql", ".ipynb", ".toml", ".yaml", ".yml", ".tex"].includes(ext)) return "code";95 if ([".csv", ".tsv"].includes(ext)) return "table";96 if ([".json", ".jsonl"].includes(ext)) return "json";97 if (ext === ".log") return "log";98 if ([".txt", ".md"].includes(ext)) return "text";99 if ([".png", ".svg", ".jpg", ".jpeg", ".gif", ".webp"].includes(ext)) return "image";100 if (ext === ".pdf") return "pdf";101 if ([".parquet", ".xlsx", ".xls", ".feather"].includes(ext)) return "data";102 return "other";103}104105/** Files the text route returns as JSON (`{ text, totalLines, truncated }`); the others are raw bytes. */106export function isTextual(path: string): boolean {107 return ["code", "table", "json", "log", "text"].includes(fileKind(path)) || path.endsWith("environment.lock.txt");108}109110/** Files the dataset inspector can profile. */111export function isDataset(path: string): boolean {112 return /\.(csv|tsv|txt|json|jsonl|parquet|xlsx|xls|feather)$/i.test(path) && (path.startsWith("data/") || /\.(csv|tsv|parquet|xlsx|xls|feather)$/i.test(path));113}114115export function fileUrl(workspaceId: string, path: string, download = false): string {116 return `/api/v2/research/sessions/${encodeURIComponent(workspaceId)}/file?path=${encodeURIComponent(path)}${download ? "&download=1" : ""}`;117}118119/** RFC 4180-style parser (quotes, doubled quotes, newlines inside quotes); the delimiter is `,` `;` or tab, guessed from the first line. */120export function parseDelimited(text: string, maxRows = 200): { header: string[]; rows: string[][]; delimiter: string; truncated: boolean } {121 const firstLine = text.slice(0, text.indexOf("\n") < 0 ? text.length : text.indexOf("\n"));122 const count = (d: string) => firstLine.split(d).length - 1;123 const delimiter = count("\t") > count(",") && count("\t") >= count(";") ? "\t" : count(";") > count(",") ? ";" : ",";124 const out: string[][] = [];125 let row: string[] = [], cell = "", quoted = false, truncated = false;126 for (let i = 0; i < text.length; i++) {127 const ch = text[i];128 if (quoted) {129 if (ch === '"') { if (text[i + 1] === '"') { cell += '"'; i++; } else quoted = false; } else cell += ch;130 } else if (ch === '"' && cell === "") quoted = true;131 else if (ch === delimiter) { row.push(cell); cell = ""; }132 else if (ch === "\n" || ch === "\r") {133 if (ch === "\r" && text[i + 1] === "\n") i++;134 row.push(cell); cell = "";135 if (row.length > 1 || row[0] !== "") out.push(row);136 row = [];137 if (out.length > maxRows) { truncated = true; break; }138 } else cell += ch;139 }140 if (!truncated && (cell !== "" || row.length > 0)) { row.push(cell); out.push(row); }141 const [header = [], ...rows] = out;142 return { header, rows: rows.slice(0, maxRows), delimiter, truncated: truncated || rows.length > maxRows };143}144