esbuild-wasm-bundler/introspect.ts
2024-08-13 10:25:16 -04:00

68 lines
2.1 KiB
TypeScript

import { parse as JSONC } from "jsr:@std/jsonc";
type JsonLike = { [key: string]: string | string[] | JsonLike; };
/** A `file://` URL version of Deno.cwd() (contains trailing slash) */
export const Root = new URL(`file://${Deno.cwd().replaceAll("\\", "/")}/`).toString();
export default async function HuntConfig(directory = Root) {
let path = "";
let json: JsonLike | undefined;
console.log("Searching in directory", directory);
const loadJSON = async (inPath: string): Promise<JsonLike | undefined> => {
try {
const pathUrl = new URL(inPath, directory);
console.log("Looking at", pathUrl.href);
let text: string;
if (inPath.endsWith(".jsonc")) {
text = await Deno.readTextFile(pathUrl);
json = JSONC(text) as JsonLike;
} else {
text = await Deno.readTextFile(pathUrl);
json = JSON.parse(text) as JsonLike;
}
return json;
} catch (e) {
console.error(`Error loading JSON from ${inPath}:`, e.message);
return undefined;
}
};
try {
json = await loadJSON("./deno.json");
} catch (_e) {
try {
json = await loadJSON("./deno.jsonc");
} catch (_e) {
try {
json = await loadJSON("./.vscode/settings.json");
path = json?.["deno.config"] as string || "";
json = undefined;
if (path) {
json = await loadJSON(path);
}
} catch (_e) {
console.warn("Cannot find a config using the VSCode plugin");
}
}
}
if (!json) {
json = {};
}
path = json.importMap as string || "";
if (!json.imports && path) {
json.imports = await loadJSON(path) as JsonLike;
}
// Ensure the return type always includes imports and compilerOptions
return {
imports: json.imports || {},
compilerOptions: json.compilerOptions || {}
} as { imports: JsonLike, compilerOptions: JsonLike };
}