UNPKG

@autorest/cadl

Version:
59 lines 1.87 kB
import { readFile, realpath, stat } from "fs/promises"; import { dirname, resolve } from "path"; import { pathToFileURL } from "url"; import { resolveModule } from "./module-resolver.js"; export function createCadlHost(logger, writeFile, host) { return { ...host, writeFile, logSink: { log: (x) => logger.debug(`${x.code ? `${x.code}: ` : ""}${x.message}`), }, }; } export async function compileCadl(logger, entrypoint) { const output = {}; const writeFile = async (path, content) => { output[path] = content; }; const baseDir = resolve(dirname(entrypoint)); try { const { compile, NodeHost } = await importCadl(baseDir); const program = await compile(createCadlHost(logger, writeFile, NodeHost), entrypoint, { emitters: { "@azure-tools/cadl-autorest": {} }, }); if (program.diagnostics.length > 0) { return { diagnostics: program.diagnostics }; } return { compiledFiles: output }; } catch (e) { if (typeof e === "object" && e !== null && "diagnostics" in e) { return { diagnostics: e.diagnostics }; } throw e; } } export async function importCadl(baseDir) { try { const host = { realpath, readFile: async (path) => await readFile(path, "utf-8"), stat, }; const resolved = await resolveModule(host, "@cadl-lang/compiler", { baseDir, }); return import(pathToFileURL(resolved).toString()); } catch (err) { if (err.code === "MODULE_NOT_FOUND") { // Resolution from cwd failed: use current package. return import("@cadl-lang/compiler"); } else { throw err; } } } //# sourceMappingURL=cadl-compiler.js.map