Repository navigation
Expand file tree
/
Copy pathvalidate-json.js
More file actions
executable file
·449 lines (387 loc) · 12.5 KB
/
Copy pathvalidate-json.js
File metadata and controls
executable file
·449 lines (387 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#!/usr/bin/env node
/**
* Comprehensive JSON linting & validation tool for LightSpeedWP.
*
* Features:
* - Pretty-print JSON with Prettier
* - Validate syntax with JSONLint (optional)
* - Validate against JSON Schema using Ajv
* - Produce minimal diffs and actionable reports
* - Support glob patterns and multiple files
*
* Usage:
* node validate-json.js [options]
*
* Options:
* --glob <pattern> Glob pattern for JSON files
* --schema <path> Path to JSON schema file
* --spec <draft> JSON Schema spec (draft7|draft2019|draft2020|jtd)
* --format-only Only format files, skip validation
* --validate-only Only validate, skip formatting
* --read-only Don't modify files, show diffs only
* --strict Use JSONLint for strict syntax checking
* --report-dir <path> Directory for reports (default: ./reports)
* --errors <format> Error format: text|json (default: text)
*
* @module scripts/validation/validate-json
* @see ../../instructions/linting.instructions.md
* @version 1.0.0
* @license GPL-3.0-or-later
*/
const fs = require('fs');
const path = require('path');
const { globSync } = require('glob');
const Ajv = require('ajv');
const addFormats = require('ajv-formats');
const prettier = require('prettier');
// Configuration
const config = {
glob: '**/*.json',
schema: null,
spec: 'draft2020',
formatOnly: false,
validateOnly: false,
readOnly: false,
strict: false,
reportDir: './reports',
errorsFormat: 'text',
verbose: false,
};
// Parse command-line arguments
function parseArgs() {
const args = process.argv.slice(2);
for (let i = 0; i < args.length; i++) {
const arg = args[i];
switch (arg) {
case '--glob':
config.glob = args[++i];
break;
case '--schema':
config.schema = args[++i];
break;
case '--spec':
config.spec = args[++i];
break;
case '--format-only':
config.formatOnly = true;
break;
case '--validate-only':
config.validateOnly = true;
break;
case '--read-only':
config.readOnly = true;
break;
case '--strict':
config.strict = true;
break;
case '--report-dir':
config.reportDir = args[++i];
break;
case '--errors':
config.errorsFormat = args[++i];
break;
case '--verbose':
config.verbose = true;
break;
case '--help':
case '-h':
printHelp();
process.exit(0);
break;
default:
console.error(`Unknown option: ${arg}`);
process.exit(1);
}
}
}
// Print help text
function printHelp() {
console.log(`
JSON Linting & Validation Tool
Usage:
node validate-json.js [options]
Options:
--glob <pattern> Glob pattern for JSON files (default: "**/*.json")
--schema <path> Path to JSON schema file
--spec <draft> JSON Schema spec: draft7|draft2019|draft2020|jtd (default: draft2020)
--format-only Only format files, skip validation
--validate-only Only validate, skip formatting
--read-only Don't modify files, show diffs only
--strict Use JSONLint for strict syntax checking
--report-dir <path> Directory for reports (default: ./reports)
--errors <format> Error format: text|json (default: text)
--verbose Show verbose output
--help, -h Show this help message
Examples:
# Format all JSON files
node validate-json.js --glob "**/*.json" --format-only
# Validate against schema
node validate-json.js --glob "data/**/*.json" --schema "schema/my-doc.schema.json"
# Read-only validation (don't modify files)
node validate-json.js --glob "**/*.json" --schema "schema/my-doc.schema.json" --read-only
# Strict syntax check with JSONLint
node validate-json.js --glob "config/**/*.json" --strict
`);
}
// Logging utilities
const log = {
info: (msg) => console.log(`\x1b[36mℹ\x1b[0m ${msg}`),
success: (msg) => console.log(`\x1b[32m✓\x1b[0m ${msg}`),
warn: (msg) => console.warn(`\x1b[33m⚠\x1b[0m ${msg}`),
error: (msg) => console.error(`\x1b[31m✗\x1b[0m ${msg}`),
debug: (msg) => config.verbose && console.log(`\x1b[90m→\x1b[0m ${msg}`),
};
// Ensure report directory exists
function ensureReportDir() {
if (!fs.existsSync(config.reportDir)) {
fs.mkdirSync(config.reportDir, { recursive: true });
log.debug(`Created report directory: ${config.reportDir}`);
}
}
// Find JSON files matching glob pattern
function findJsonFiles() {
log.debug(`Searching for files matching: ${config.glob}`);
const files = globSync(config.glob, {
ignore: ['**/node_modules/**', '**/package-lock.json', '**/reports/**', '**/.git/**'],
});
log.info(`Found ${files.length} JSON file(s)`);
return files;
}
// Format JSON files with Prettier
async function formatFiles(files) {
if (config.validateOnly) {
log.debug('Skipping formatting (validate-only mode)');
return { formatted: 0, skipped: files.length };
}
log.info('Formatting JSON files with Prettier...');
let formatted = 0;
let needsFormatting = 0;
const prettierOptions = {
parser: 'json',
tabWidth: 2,
useTabs: false,
};
try {
for (const file of files) {
const content = fs.readFileSync(file, 'utf8');
const formattedContent = await prettier.format(content, prettierOptions);
if (content !== formattedContent) {
needsFormatting++;
if (!config.readOnly) {
fs.writeFileSync(file, formattedContent, 'utf8');
formatted++;
log.debug(`Formatted: ${file}`);
} else {
log.debug(`Needs formatting: ${file}`);
}
}
}
if (config.readOnly && needsFormatting > 0) {
log.warn(`${needsFormatting} file(s) need formatting (read-only mode)`);
return { formatted: 0, skipped: files.length };
}
log.success(`Formatted ${formatted} file(s)`);
return { formatted, skipped: files.length - formatted };
} catch (error) {
log.error(`Prettier failed: ${error.message}`);
throw error;
}
}
// Validate syntax with JSONLint
function validateSyntax(files) {
if (!config.strict) {
log.debug('Skipping strict syntax check (use --strict to enable)');
return { valid: files.length, invalid: 0 };
}
log.info('Validating JSON syntax with JSONLint...');
let invalid = 0;
const errors = [];
for (const file of files) {
try {
const content = fs.readFileSync(file, 'utf8');
JSON.parse(content);
log.debug(`✓ ${file}`);
} catch (error) {
invalid++;
const errorMsg = `${file} → Syntax error: ${error.message}`;
errors.push(errorMsg);
log.error(errorMsg);
}
}
if (invalid > 0) {
const reportFile = path.join(config.reportDir, 'jsonlint.log');
ensureReportDir();
fs.writeFileSync(reportFile, errors.join('\n'));
log.info(`Syntax errors written to: ${reportFile}`);
}
return { valid: files.length - invalid, invalid };
}
// Validate against JSON Schema with Ajv
async function validateSchema(files) {
if (!config.schema) {
log.debug('No schema provided, skipping schema validation');
return { valid: files.length, invalid: 0, errors: [] };
}
if (config.formatOnly) {
log.debug('Skipping schema validation (format-only mode)');
return { valid: files.length, invalid: 0, errors: [] };
}
log.info(`Validating against schema: ${config.schema}`);
let schema;
try {
const schemaContent = fs.readFileSync(config.schema, 'utf8');
schema = JSON.parse(schemaContent);
} catch (error) {
log.error(`Failed to load schema: ${error.message}`);
throw error;
}
const ajvOptions = {
allErrors: true,
verbose: true,
strict: false,
};
if (config.spec === 'jtd') {
ajvOptions.jtd = true;
}
const ajv = new Ajv(ajvOptions);
addFormats(ajv);
let validate;
try {
validate = ajv.compile(schema);
} catch (error) {
log.error(`Invalid schema: ${error.message}`);
throw error;
}
let invalid = 0;
const allErrors = [];
for (const file of files) {
try {
const content = fs.readFileSync(file, 'utf8');
const data = JSON.parse(content);
const valid = validate(data);
if (!valid) {
invalid++;
const fileErrors = validate.errors.map((err) => {
const jsonPath = err.instancePath || '$';
return {
file,
path: jsonPath,
keyword: err.keyword,
message: err.message,
params: JSON.stringify(err.params),
};
});
allErrors.push(...fileErrors);
log.error(`FAIL ${file}`);
fileErrors.forEach((err) => {
log.error(` → ${err.path}: ${err.message} (${err.keyword})`);
});
} else {
log.debug(`✓ ${file}`);
}
} catch (error) {
invalid++;
allErrors.push({
file,
path: '$',
keyword: 'parse',
message: error.message,
params: '{}',
});
log.error(`FAIL ${file} → Parse error: ${error.message}`);
}
}
if (invalid > 0) {
ensureReportDir();
if (config.errorsFormat === 'json') {
const reportFile = path.join(config.reportDir, 'ajv-errors.json');
fs.writeFileSync(reportFile, JSON.stringify(allErrors, null, 2));
log.info(`Validation errors written to: ${reportFile}`);
} else {
const reportFile = path.join(config.reportDir, 'ajv-errors.txt');
const errorText = allErrors
.map((err) => `${err.file} → ${err.path}: ${err.message} (${err.keyword})`)
.join('\n');
fs.writeFileSync(reportFile, errorText);
log.info(`Validation errors written to: ${reportFile}`);
}
}
return { valid: files.length - invalid, invalid, errors: allErrors };
}
// Generate summary report
function generateSummary(stats) {
console.log('\n' + '='.repeat(60));
console.log('JSON Validation Summary');
console.log('='.repeat(60));
console.log(`Total files: ${stats.total}`);
console.log(`Formatted: ${stats.formatted}`);
console.log(`Syntax valid: ${stats.syntaxValid}`);
console.log(`Schema valid: ${stats.schemaValid}`);
console.log(`Invalid: ${stats.invalid}`);
console.log(`Schema spec: ${config.schema ? config.spec : 'N/A'}`);
console.log('='.repeat(60));
if (stats.invalid > 0) {
console.log(`\n\x1b[31mValidation failed with ${stats.invalid} error(s)\x1b[0m`);
console.log(`See reports in: ${config.reportDir}/\n`);
return 1;
}
console.log('\n\x1b[32m✓ All validations passed!\x1b[0m\n');
return 0;
}
// Print commands for reference
function printCommands(files) {
console.log('\n' + '─'.repeat(60));
console.log('Runnable Commands');
console.log('─'.repeat(60));
if (!config.validateOnly) {
const formatCmd = config.readOnly
? `npx prettier --check "${config.glob}"`
: `npx prettier --write "${config.glob}"`;
console.log(`\n# Format JSON files:`);
console.log(formatCmd);
}
if (config.schema && !config.formatOnly) {
const specFlag = config.spec !== 'draft2020' ? ` --spec=${config.spec}` : '';
const errorsFlag = config.errorsFormat === 'json' ? ' --errors=json' : ' --errors=text';
console.log(`\n# Validate against schema:`);
console.log(`npx ajv validate -s ${config.schema} -d "${config.glob}"${specFlag}${errorsFlag}`);
}
if (config.strict) {
console.log(`\n# Strict syntax check:`);
console.log(`npx jsonlint -cq ${files.slice(0, 3).join(' ')}${files.length > 3 ? ' ...' : ''}`);
}
console.log('─'.repeat(60) + '\n');
}
// Main execution
async function main() {
parseArgs();
log.info('JSON Linting & Validation Tool v1.0.0');
log.info('─'.repeat(60));
try {
const files = findJsonFiles();
if (files.length === 0) {
log.warn('No JSON files found matching pattern');
return 0;
}
printCommands(files);
const formatResults = await formatFiles(files);
const syntaxResults = validateSyntax(files);
const schemaResults = await validateSchema(files);
const stats = {
total: files.length,
formatted: formatResults.formatted,
syntaxValid: syntaxResults.valid,
schemaValid: schemaResults.valid,
invalid: syntaxResults.invalid + schemaResults.invalid,
};
const exitCode = generateSummary(stats);
process.exit(exitCode);
} catch (error) {
log.error(`Fatal error: ${error.message}`);
if (config.verbose) {
console.error(error);
}
process.exit(1);
}
}
main();