chore: move schema and doc related code into the docs sub-package

This commit is contained in:
Matthew Little
2020-05-15 20:45:27 +02:00
parent 7c4bdc9cec
commit ab49121e22
23 changed files with 18555 additions and 7721 deletions

View File

@@ -0,0 +1,59 @@
import * as fs from 'fs';
import * as path from 'path';
import * as glob from 'glob';
import * as deref from '@apidevtools/json-schema-ref-parser';
import * as mergeSchemas from 'json-schema-merge-allof';
import { compile } from 'json-schema-to-typescript';
import { JSONSchema4 } from 'json-schema';
const root = path.resolve(path.join(__dirname, '..'));
const typeFilePath = path.join(root, 'index.d.ts');
const schemaFilesPath = path.join(root, '**/*.schema.json');
const clearFile = async () => {
fs.writeFileSync(typeFilePath, '', 'utf8');
};
async function run() {
const files = await new Promise<string[]>((resolve, reject) => {
glob(schemaFilesPath, async (err, files) => {
if (err) {
reject(err);
} else {
resolve(files);
}
});
});
if (files.length === 0) {
throw new Error(`Did not find any files in ${schemaFilesPath}`);
}
clearFile();
for (const file of files) {
const derefedSchema = await deref.dereference(file);
const schema = mergeSchemas(derefedSchema, {
ignoreAdditionalProperties: true,
});
if (!schema.title) continue;
if (schema.type === 'object') {
schema.additionalProperties = false;
}
const outputType = await compile(schema as JSONSchema4, schema.title, {
bannerComment: '',
strictIndexSignatures: true,
declareExternallyReferenced: false,
});
fs.appendFileSync(typeFilePath, outputType);
fs.appendFileSync(typeFilePath, '\n');
}
}
run().then(() => {
process.exit(0);
}).catch(error => {
console.error('generate-types error');
console.error(error);
process.exit(1);
});

View File

@@ -0,0 +1,47 @@
import * as fs from 'fs';
import * as chalk from 'chalk';
import * as glob from 'glob';
import * as Ajv from 'ajv';
const dataEncoding = 'utf8';
const ajv = new Ajv();
glob('.tmp/**/*.example.json', (err, files) => {
if (err) throw err;
let exitCode = 0;
files.forEach(file => {
let schema;
let exampleJson;
//
// Schemas are precompiled to avoid inconsistent schema fragment resolution
const schemaFileName = file.replace('example', 'schema').replace('docs', 'dist');
//
// JSON likely invalid if error
try {
schema = JSON.parse(fs.readFileSync(schemaFileName, dataEncoding));
exampleJson = JSON.parse(fs.readFileSync(file, dataEncoding));
} catch (err) {
throw new Error(`${chalk.red(file)} ${err}`);
}
const valid = ajv.validate(schema, exampleJson);
if (!valid) {
exitCode = 1;
console.warn(`[${file}] ${chalk.red('INVALID')}\n`);
console.warn('Error at', chalk.yellow(file));
console.warn(ajv.errorsText());
console.warn('\n');
return;
}
console.log(`[${file}] ${chalk.green('VALID')}`);
});
process.exit(exitCode);
});