|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +const fs = require("fs"); |
| 4 | +const yaml = require("yaml"); |
| 5 | +const JsonSchema = require("@hyperjump/json-schema"); |
| 6 | +const dialect = require("../schemas/v3.1/dialect/base.schema.json"); |
| 7 | +const vocabulary = require("../schemas/v3.1/meta/base.schema.json"); |
| 8 | + |
| 9 | + |
| 10 | +if (process.argv.length < 3) { |
| 11 | + console.log("Usage: validate [--schema=schema] [--version=2021-03-02] [--format=BASIC] path-to-file.yaml"); |
| 12 | + console.log("\t--schema: (Default: schema) The name of the yaml schema file to use"); |
| 13 | + console.log("\t--version: (Default: 2021-03-02) The version of the yaml schema file to use"); |
| 14 | + console.log("\t--format: (Default: BASIC) The JSON Schema output format to use. Options: FLAG, BASIC, DETAILED, VERBOSE"); |
| 15 | + process.exit(1); |
| 16 | +} |
| 17 | + |
| 18 | +const args = process.argv.reduce((acc, arg) => { |
| 19 | + if (!arg.startsWith("--")) return acc; |
| 20 | + |
| 21 | + const [argName, argValue] = arg.substring(2).split("=", 2); |
| 22 | + return { ...acc, [argName]: argValue }; |
| 23 | +}, {}); |
| 24 | + |
| 25 | +(async function () { |
| 26 | + try { |
| 27 | + // Config |
| 28 | + JsonSchema.setMetaOutputFormat(outputFormat); |
| 29 | + //JsonSchema.setShouldMetaValidate(false); |
| 30 | + |
| 31 | + const schemaType = args.schema || "schema"; |
| 32 | + const schemaVersion = args.version || "2021-03-02"; |
| 33 | + const ouputFormat = args.format || JsonSchema.BASIC; |
| 34 | + |
| 35 | + // Load schemas |
| 36 | + JsonSchema.add(dialect); |
| 37 | + JsonSchema.add(vocabulary); |
| 38 | + fs.readdirSync(`${__dirname}/../schemas/v3.1`, { withFileTypes: true }) |
| 39 | + .filter((entry) => entry.isFile() && /\.yaml$/.test(entry.name)) |
| 40 | + .map((entry) => fs.readFileSync(`${__dirname}/../schemas/v3.1/${entry.name}`, "utf8")) |
| 41 | + .map((schemaYaml) => yaml.parse(schemaYaml)) |
| 42 | + .forEach((schema) => JsonSchema.add(schema)); |
| 43 | + |
| 44 | + // Compile / meta-validate |
| 45 | + const schema = await JsonSchema.get(`https://spec.openapis.org/oas/3.1/${schemaType}/${schemaVersion}`); |
| 46 | + const validateSchema = await JsonSchema.validate(schema); |
| 47 | + |
| 48 | + // Validate instance |
| 49 | + const instanceYaml = fs.readFileSync(`${process.cwd()}/${process.argv[process.argv.length - 1]}`, "utf8"); |
| 50 | + const instance = yaml.parse(instanceYaml); |
| 51 | + const results = validateSchema(instance, outputFormat); |
| 52 | + console.log(JSON.stringify(results, null, " ")); |
| 53 | + } catch (error) { |
| 54 | + console.log("************* Error ***************"); |
| 55 | + console.log(error); |
| 56 | + console.log(JSON.stringify(error.output, null, " ")); |
| 57 | + } |
| 58 | +}()); |
0 commit comments