esbuild-wasm-bundler/introspect.ts

68 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-08-13 10:25:16 -04:00
import { parse as JSONC } from "jsr:@std/jsonc";
2024-06-07 16:54:12 -04:00
2024-06-12 14:48:53 -04:00
type JsonLike = { [key: string]: string | string[] | JsonLike; };
2024-06-10 16:23:31 -04:00
2024-08-13 10:25:16 -04:00
/** 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);
2024-06-07 16:54:12 -04:00
json = JSONC(text) as JsonLike;
2024-08-13 10:25:16 -04:00
} else {
text = await Deno.readTextFile(pathUrl);
json = JSON.parse(text) as JsonLike;
2024-06-07 16:54:12 -04:00
}
2024-08-13 10:25:16 -04:00
return json;
} catch (e) {
console.error(`Error loading JSON from ${inPath}:`, e.message);
return undefined;
2024-06-07 16:54:12 -04:00
}
2024-08-13 10:25:16 -04:00
};
2024-06-07 16:54:12 -04:00
2024-08-13 10:25:16 -04:00
try {
2024-06-14 17:07:50 -04:00
json = await loadJSON("./deno.json");
2024-08-13 10:25:16 -04:00
} catch (_e) {
try {
2024-06-14 17:07:50 -04:00
json = await loadJSON("./deno.jsonc");
2024-08-13 10:25:16 -04:00
} catch (_e) {
try {
json = await loadJSON("./.vscode/settings.json");
path = json?.["deno.config"] as string || "";
2024-06-07 16:54:12 -04:00
json = undefined;
2024-08-13 10:25:16 -04:00
if (path) {
json = await loadJSON(path);
2024-06-07 16:54:12 -04:00
}
2024-08-13 10:25:16 -04:00
} catch (_e) {
console.warn("Cannot find a config using the VSCode plugin");
2024-06-07 16:54:12 -04:00
}
}
}
2024-08-13 10:25:16 -04:00
if (!json) {
2024-06-07 16:54:12 -04:00
json = {};
}
2024-08-13 10:25:16 -04:00
path = json.importMap as string || "";
if (!json.imports && path) {
2024-06-12 14:48:53 -04:00
json.imports = await loadJSON(path) as JsonLike;
2024-08-13 10:25:16 -04:00
}
2024-06-07 16:54:12 -04:00
2024-08-13 10:25:16 -04:00
// Ensure the return type always includes imports and compilerOptions
return {
imports: json.imports || {},
compilerOptions: json.compilerOptions || {}
} as { imports: JsonLike, compilerOptions: JsonLike };
2024-06-07 16:54:12 -04:00
}