UNPKG

@tsed/cli-core

Version:
58 lines (57 loc) 1.8 kB
import { __decorate, __metadata } from "tslib"; import { extname } from "node:path"; import { inject, Injectable } from "@tsed/di"; import { default as Ajv } from "ajv"; import { CliFs } from "./CliFs.js"; import { CliYaml } from "./CliYaml.js"; let CliLoadFile = class CliLoadFile { // @ts-ignore #ajv; constructor() { this.cliYaml = inject(CliYaml); this.cliFs = inject(CliFs); const options = { verbose: false, coerceTypes: true, strict: false }; // @ts-ignore this.#ajv = new Ajv(options); } /** * Load a configuration file from yaml, json */ async loadFile(path, schema) { let config; const ext = extname(path); if ([".yml", ".yaml"].includes(ext)) { config = await this.cliYaml.read(path); } else if ([".json"].includes(ext)) { config = await JSON.parse(await this.cliFs.readFile(path, "utf8")); } else if (!config) { throw new Error("Unsupported format file"); } if (schema) { const validate = this.#ajv.compile(schema); const isValid = validate(config); if (!isValid) { const [error] = validate.errors; throw new Error([ `${error.instancePath.replace(/\//gi, ".")} `, error.message, error.params?.allowedValues && `. Allowed values: ${error.params?.allowedValues}` ] .filter(Boolean) .join("")); } } return config; } }; CliLoadFile = __decorate([ Injectable(), __metadata("design:paramtypes", []) ], CliLoadFile); export { CliLoadFile };