feat(Yaml Prettifier): add a JSON Schema Validator

Allow pasting JSON Schema or fetching from schemastore.org

Fix #540
This commit is contained in:
ShareVB committed 2025-08-24 14:50:17 +02:00
1 parent 5f8aea2d09
commit 2ee02742e7
5 files changed
+159 -3

No files matched your search

+2
View File
@@ -92,6 +92,8 @@
"@zxing/library": "^0.21.3",
"a11y-color-contrast": "^0.2.0",
"aircodes": "^1.3.16",
"ajv": "^8.17.1",
"ajv-errors": "^3.0.0",
"ansi-styles": "^6.2.1",
"ansible-vault": "^1.3.0",
"apache-md5": "^1.1.8",
+6
View File
@@ -164,6 +164,12 @@ dependencies:
aircodes:
specifier: ^1.3.16
version: 1.3.16
ajv:
specifier: ^8.17.1
version: 8.17.1
ajv-errors:
specifier: ^3.0.0
version: 3.0.0(ajv@8.17.1)
ansi-styles:
specifier: ^6.2.1
version: 6.2.1
+1 -1
View File
@@ -6,7 +6,7 @@ export const tool = defineTool({
name: t('tools.yaml-prettify.title'),
path: '/yaml-prettify',
description: t('tools.yaml-prettify.description'),
keywords: ['yaml', 'viewer', 'prettify', 'format', 'lint'],
keywords: ['yaml', 'viewer', 'prettify', 'format', 'lint', 'validator', 'schema'],
component: () => import('./yaml-viewer.vue'),
icon: AlignJustified,
createdAt: new Date('2024-01-31'),
@@ -0,0 +1,105 @@
import { type Schema } from 'jsonschema';
import { isRef, onBeforeMount, ref, watch } from 'vue';
import { type MaybeRef, get } from '@vueuse/core';
import YAML from 'yaml';
import Ajv from 'ajv';
import AjvErrors from 'ajv-errors';
import { yamlParse } from 'composeverter';
export interface SchemaStore {
name: string
description: string
url: string
fileMatch: string[]
versions?: string[]
}
interface NodeWithRange {
range?: number[]
}
export function useYamlSchemaValidation({ yaml, schemaUrl, schemaData }: { yaml: MaybeRef<string>; schemaUrl: MaybeRef<string>; schemaData: MaybeRef<string> }) {
const schemas = ref<SchemaStore[]>([]);
const schema = ref<Schema | null>(null);
const errors = ref<string[]>([]);
onBeforeMount(async () => {
const catalog = await fetch('https://www.schemastore.org/api/json/catalog.json');
const catalogJson: { $schemaUrl: string; schemas: SchemaStore[]; version: number } = await catalog.json();
schemas.value = catalogJson.schemas;
});
watch([schemaUrl, schemaData].filter(isRef), async () => {
if (get(schemaUrl) === 'custom') {
try {
schema.value = JSON.parse(get(schemaData)) as Schema;
}
catch (e: any) {
errors.value = [`Schema parsing error:${e.toString()}`];
}
return;
}
if (get(schemaUrl)) {
try {
const response = await fetch(get(schemaUrl));
const schemaJson = await response.json();
schema.value = schemaJson;
}
catch (e: any) {
errors.value = [`Schema fetching error:${e.toString()}`];
}
}
}, { immediate: true });
watch([yaml, schema].filter(isRef), () => {
const schemaValue = get(schema);
const yamlValue = get(yaml);
if (!schemaValue) {
errors.value = [];
return;
}
if (!yamlValue) {
errors.value = [];
return;
}
const parsedYaml = yamlParse(yamlValue);
const ajv = new Ajv({ allErrors: true, strict: false });
AjvErrors(ajv);
const validate = ajv.compile(schemaValue);
const valid = validate(parsedYaml);
if (valid || validate.errors === null) {
errors.value = [];
}
else {
const yamlDoc = YAML.parseDocument(yamlValue, { prettyErrors: true });
errors.value = validate.errors!.map((err) => {
let { instancePath } = err;
if (err.keyword === 'additionalProperties') {
instancePath += `/${err.params.additionalProperty}`;
}
const parsedPath = instancePath.split('/').slice(1);
let node = yamlDoc.getIn(parsedPath, true);
if (node === null) {
node = yamlDoc.getIn(parsedPath.slice(0, -1), true);
}
const nodeWithRange = node as NodeWithRange;
const pos = nodeWithRange?.range ? nodeWithRange.range[0] + 1 : 0;
const line = (yamlValue.substring(0, pos).match(/\n/g) || []).length + 1;
let message;
if (err.keyword === 'additionalProperties') {
message = `Line ${line}(${instancePath}): '${err.params.additionalProperty}' is unknown for '${instancePath}'`;
}
else if (err.keyword === 'format') {
message = `Line ${line}(${instancePath}): must have a valid syntax for '${err.params.format}'`;
}
else if (err.keyword === 'oneOf') {
message = `Line ${line}(${instancePath}): must be either a Short Syntax (string(s)) or a Long Syntax (object(s))`;
}
else { message = `Line ${line}(${instancePath}): ${err.message} (${err.keyword}: ${JSON.stringify(err.params)})`; }
return message;
});
}
}, { immediate: true });
return { schemas, errors };
}
+45 -2
View File
@@ -1,12 +1,16 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { formatYaml } from './yaml-models';
import { useYamlSchemaValidation } from './useYamlSchemaValidation';
import TextareaCopyable from '@/components/TextareaCopyable.vue';
import { useITStorage } from '@/composable/queryParams';
import { useITStorage, useQueryParamOrStorage } from '@/composable/queryParams';
const { t } = useI18n();
const jsonSchemaInputElement = ref<HTMLElement>();
const rawYaml = useITStorage('yaml-prettify:raw-yaml', '');
const schemaData = useITStorage('yaml-prettify:schema-data', '');
const indentSize = useITStorage('yaml-prettify:indent-size', 2);
const sortKeys = useITStorage('yaml-prettify:sort-keys', false);
@@ -26,6 +30,9 @@ const MONACO_EDITOR_OPTIONS = {
formatOnType: true,
formatOnPaste: true,
};
const schemaUrl = useQueryParamOrStorage({ name: 'schema', storageName: 'yaml-prettify:schema', defaultValue: '' });
const { schemas, errors: validationErrors } = useYamlSchemaValidation({ yaml: rawYaml, schemaUrl, schemaData });
</script>
<template>
@@ -41,6 +48,31 @@ const MONACO_EDITOR_OPTIONS = {
</div>
</div>
<n-form-item label="JSON schema:" label-placement="left" label-width="130px" label-align="right">
<n-select
v-model:value="schemaUrl"
:options="[
{ label: 'No validation', value: '' },
{ label: 'Custom', value: 'custom' },
...schemas.map(s => ({ label: `${s.name} / ${s.description}`, value: s.url })),
]"
filterable mb-4
/>
</n-form-item>
<c-input-text
v-if="schemaUrl === 'custom'"
ref="jsonSchemaInputElement"
v-model:value="schemaData"
placeholder="Paste your JSON Schema here..."
rows="20"
multiline
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"
monospace
/>
<c-label :label="t('tools.yaml-viewer.texts.label-your-raw-yaml')">
<div relative w-full>
<c-monaco-editor
@@ -53,7 +85,7 @@ const MONACO_EDITOR_OPTIONS = {
</div>
</c-label>
<div v-if="errors.length > 0">
<div v-if="errors.length > 0" mb-2 mt-2>
<n-alert :title="t('tools.yaml-viewer.texts.title-the-following-errors-occured')" type="error" mt-5>
<ul>
<li v-for="(message, index) of errors" :key="index">
@@ -63,6 +95,17 @@ const MONACO_EDITOR_OPTIONS = {
</n-alert>
</div>
<div v-if="validationErrors.length > 0" mb-2 mt-2>
<n-alert title="Schema Validation Errors" type="error">
<ul
v-for="error in validationErrors"
:key="error"
>
<li>{{ error }}</li>
</ul>
</n-alert>
</div>
<n-divider />
<n-form-item :label="t('tools.yaml-viewer.texts.label-prettified-version-of-your-yaml')">