Files
xo-cash-utils/scripts/generate-schema.js

55 lines
1.9 KiB
JavaScript

#!/usr/bin/env node
import { execSync } from 'child_process';
import { readFileSync, writeFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = join(__dirname, '..');
// exec helper
function exec(command, options = {}) {
const defaultOptions = {
stdio: 'inherit',
cwd: rootDir,
shell: true,
...options,
};
return execSync(command, defaultOptions);
}
try {
const schemaPath = join(rootDir, 'src/parser/xo-template.schema.json');
const validatorPath = join(rootDir, 'src/parser/ajv/validate-xo-template.js');
const tsconfigPath = join(rootDir, 'tsconfig.json');
const templatePath = join(rootDir, 'node_modules/@xo-cash/types/build/template.d.ts');
// Generate schema JSON (write to file directly instead of shell redirection)
const schemaContent = execSync(
`ts-json-schema-generator --no-ref-encode --tsconfig "${tsconfigPath}" --path "${templatePath}" --type "XOTemplate"`,
{ encoding: 'utf8', cwd: rootDir },
);
writeFileSync(schemaPath, schemaContent, 'utf8');
// Compile validator with AJV
exec(`ajv compile -s "${schemaPath}" --allowUnionTypes --all-errors -o "${validatorPath}"`);
// Transform the generated validator code
let code = readFileSync(validatorPath, 'utf8');
code = code
.replace(/"use strict";module\.exports = [^;]+;module\.exports\.default = [^;]+;/, 'export default validate20;')
.replace(/;const /g, ';\nconst ')
.replace(/;function /g, ';\nfunction ')
.replace(/\}function /g, '}\nfunction ');
writeFileSync(validatorPath, code, 'utf8');
console.log('Schema generation complete!');
} catch (error) {
console.error('Error generating schema:', error.message);
process.exit(1);
}