1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
|
---|
4 | var validate_1 = require("./compile/validate");
|
---|
5 | Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
|
---|
6 | var codegen_1 = require("./compile/codegen");
|
---|
7 | Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
|
---|
8 | Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
|
---|
9 | Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
|
---|
10 | Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
|
---|
11 | Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
|
---|
12 | Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
|
---|
13 | const validation_error_1 = require("./runtime/validation_error");
|
---|
14 | const ref_error_1 = require("./compile/ref_error");
|
---|
15 | const rules_1 = require("./compile/rules");
|
---|
16 | const compile_1 = require("./compile");
|
---|
17 | const codegen_2 = require("./compile/codegen");
|
---|
18 | const resolve_1 = require("./compile/resolve");
|
---|
19 | const dataType_1 = require("./compile/validate/dataType");
|
---|
20 | const util_1 = require("./compile/util");
|
---|
21 | const $dataRefSchema = require("./refs/data.json");
|
---|
22 | const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
|
---|
23 | const EXT_SCOPE_NAMES = new Set([
|
---|
24 | "validate",
|
---|
25 | "serialize",
|
---|
26 | "parse",
|
---|
27 | "wrapper",
|
---|
28 | "root",
|
---|
29 | "schema",
|
---|
30 | "keyword",
|
---|
31 | "pattern",
|
---|
32 | "formats",
|
---|
33 | "validate$data",
|
---|
34 | "func",
|
---|
35 | "obj",
|
---|
36 | "Error",
|
---|
37 | ]);
|
---|
38 | const removedOptions = {
|
---|
39 | errorDataPath: "",
|
---|
40 | format: "`validateFormats: false` can be used instead.",
|
---|
41 | nullable: '"nullable" keyword is supported by default.',
|
---|
42 | jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
|
---|
43 | extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
|
---|
44 | missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
|
---|
45 | processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
|
---|
46 | sourceCode: "Use option `code: {source: true}`",
|
---|
47 | strictDefaults: "It is default now, see option `strict`.",
|
---|
48 | strictKeywords: "It is default now, see option `strict`.",
|
---|
49 | uniqueItems: '"uniqueItems" keyword is always validated.',
|
---|
50 | unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
|
---|
51 | cache: "Map is used as cache, schema object as key.",
|
---|
52 | serialize: "Map is used as cache, schema object as key.",
|
---|
53 | ajvErrors: "It is default now.",
|
---|
54 | };
|
---|
55 | const deprecatedOptions = {
|
---|
56 | ignoreKeywordsWithRef: "",
|
---|
57 | jsPropertySyntax: "",
|
---|
58 | unicode: '"minLength"/"maxLength" account for unicode characters by default.',
|
---|
59 | };
|
---|
60 | const MAX_EXPRESSION = 200;
|
---|
61 | // eslint-disable-next-line complexity
|
---|
62 | function requiredOptions(o) {
|
---|
63 | var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
|
---|
64 | const s = o.strict;
|
---|
65 | const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
|
---|
66 | const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
|
---|
67 | return {
|
---|
68 | strictSchema: (_c = (_b = o.strictSchema) !== null && _b !== void 0 ? _b : s) !== null && _c !== void 0 ? _c : true,
|
---|
69 | strictNumbers: (_e = (_d = o.strictNumbers) !== null && _d !== void 0 ? _d : s) !== null && _e !== void 0 ? _e : true,
|
---|
70 | strictTypes: (_g = (_f = o.strictTypes) !== null && _f !== void 0 ? _f : s) !== null && _g !== void 0 ? _g : "log",
|
---|
71 | strictTuples: (_j = (_h = o.strictTuples) !== null && _h !== void 0 ? _h : s) !== null && _j !== void 0 ? _j : "log",
|
---|
72 | strictRequired: (_l = (_k = o.strictRequired) !== null && _k !== void 0 ? _k : s) !== null && _l !== void 0 ? _l : false,
|
---|
73 | code: o.code ? { ...o.code, optimize } : { optimize },
|
---|
74 | loopRequired: (_m = o.loopRequired) !== null && _m !== void 0 ? _m : MAX_EXPRESSION,
|
---|
75 | loopEnum: (_o = o.loopEnum) !== null && _o !== void 0 ? _o : MAX_EXPRESSION,
|
---|
76 | meta: (_p = o.meta) !== null && _p !== void 0 ? _p : true,
|
---|
77 | messages: (_q = o.messages) !== null && _q !== void 0 ? _q : true,
|
---|
78 | inlineRefs: (_r = o.inlineRefs) !== null && _r !== void 0 ? _r : true,
|
---|
79 | schemaId: (_s = o.schemaId) !== null && _s !== void 0 ? _s : "$id",
|
---|
80 | addUsedSchema: (_t = o.addUsedSchema) !== null && _t !== void 0 ? _t : true,
|
---|
81 | validateSchema: (_u = o.validateSchema) !== null && _u !== void 0 ? _u : true,
|
---|
82 | validateFormats: (_v = o.validateFormats) !== null && _v !== void 0 ? _v : true,
|
---|
83 | unicodeRegExp: (_w = o.unicodeRegExp) !== null && _w !== void 0 ? _w : true,
|
---|
84 | int32range: (_x = o.int32range) !== null && _x !== void 0 ? _x : true,
|
---|
85 | };
|
---|
86 | }
|
---|
87 | class Ajv {
|
---|
88 | constructor(opts = {}) {
|
---|
89 | this.schemas = {};
|
---|
90 | this.refs = {};
|
---|
91 | this.formats = {};
|
---|
92 | this._compilations = new Set();
|
---|
93 | this._loading = {};
|
---|
94 | this._cache = new Map();
|
---|
95 | opts = this.opts = { ...opts, ...requiredOptions(opts) };
|
---|
96 | const { es5, lines } = this.opts.code;
|
---|
97 | this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
|
---|
98 | this.logger = getLogger(opts.logger);
|
---|
99 | const formatOpt = opts.validateFormats;
|
---|
100 | opts.validateFormats = false;
|
---|
101 | this.RULES = rules_1.getRules();
|
---|
102 | checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
|
---|
103 | checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
|
---|
104 | this._metaOpts = getMetaSchemaOptions.call(this);
|
---|
105 | if (opts.formats)
|
---|
106 | addInitialFormats.call(this);
|
---|
107 | this._addVocabularies();
|
---|
108 | this._addDefaultMetaSchema();
|
---|
109 | if (opts.keywords)
|
---|
110 | addInitialKeywords.call(this, opts.keywords);
|
---|
111 | if (typeof opts.meta == "object")
|
---|
112 | this.addMetaSchema(opts.meta);
|
---|
113 | addInitialSchemas.call(this);
|
---|
114 | opts.validateFormats = formatOpt;
|
---|
115 | }
|
---|
116 | _addVocabularies() {
|
---|
117 | this.addKeyword("$async");
|
---|
118 | }
|
---|
119 | _addDefaultMetaSchema() {
|
---|
120 | const { $data, meta, schemaId } = this.opts;
|
---|
121 | let _dataRefSchema = $dataRefSchema;
|
---|
122 | if (schemaId === "id") {
|
---|
123 | _dataRefSchema = { ...$dataRefSchema };
|
---|
124 | _dataRefSchema.id = _dataRefSchema.$id;
|
---|
125 | delete _dataRefSchema.$id;
|
---|
126 | }
|
---|
127 | if (meta && $data)
|
---|
128 | this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
|
---|
129 | }
|
---|
130 | defaultMeta() {
|
---|
131 | const { meta, schemaId } = this.opts;
|
---|
132 | return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
|
---|
133 | }
|
---|
134 | validate(schemaKeyRef, // key, ref or schema object
|
---|
135 | data // to be validated
|
---|
136 | ) {
|
---|
137 | let v;
|
---|
138 | if (typeof schemaKeyRef == "string") {
|
---|
139 | v = this.getSchema(schemaKeyRef);
|
---|
140 | if (!v)
|
---|
141 | throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
|
---|
142 | }
|
---|
143 | else {
|
---|
144 | v = this.compile(schemaKeyRef);
|
---|
145 | }
|
---|
146 | const valid = v(data);
|
---|
147 | if (!("$async" in v))
|
---|
148 | this.errors = v.errors;
|
---|
149 | return valid;
|
---|
150 | }
|
---|
151 | compile(schema, _meta) {
|
---|
152 | const sch = this._addSchema(schema, _meta);
|
---|
153 | return (sch.validate || this._compileSchemaEnv(sch));
|
---|
154 | }
|
---|
155 | compileAsync(schema, meta) {
|
---|
156 | if (typeof this.opts.loadSchema != "function") {
|
---|
157 | throw new Error("options.loadSchema should be a function");
|
---|
158 | }
|
---|
159 | const { loadSchema } = this.opts;
|
---|
160 | return runCompileAsync.call(this, schema, meta);
|
---|
161 | async function runCompileAsync(_schema, _meta) {
|
---|
162 | await loadMetaSchema.call(this, _schema.$schema);
|
---|
163 | const sch = this._addSchema(_schema, _meta);
|
---|
164 | return sch.validate || _compileAsync.call(this, sch);
|
---|
165 | }
|
---|
166 | async function loadMetaSchema($ref) {
|
---|
167 | if ($ref && !this.getSchema($ref)) {
|
---|
168 | await runCompileAsync.call(this, { $ref }, true);
|
---|
169 | }
|
---|
170 | }
|
---|
171 | async function _compileAsync(sch) {
|
---|
172 | try {
|
---|
173 | return this._compileSchemaEnv(sch);
|
---|
174 | }
|
---|
175 | catch (e) {
|
---|
176 | if (!(e instanceof ref_error_1.default))
|
---|
177 | throw e;
|
---|
178 | checkLoaded.call(this, e);
|
---|
179 | await loadMissingSchema.call(this, e.missingSchema);
|
---|
180 | return _compileAsync.call(this, sch);
|
---|
181 | }
|
---|
182 | }
|
---|
183 | function checkLoaded({ missingSchema: ref, missingRef }) {
|
---|
184 | if (this.refs[ref]) {
|
---|
185 | throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
|
---|
186 | }
|
---|
187 | }
|
---|
188 | async function loadMissingSchema(ref) {
|
---|
189 | const _schema = await _loadSchema.call(this, ref);
|
---|
190 | if (!this.refs[ref])
|
---|
191 | await loadMetaSchema.call(this, _schema.$schema);
|
---|
192 | if (!this.refs[ref])
|
---|
193 | this.addSchema(_schema, ref, meta);
|
---|
194 | }
|
---|
195 | async function _loadSchema(ref) {
|
---|
196 | const p = this._loading[ref];
|
---|
197 | if (p)
|
---|
198 | return p;
|
---|
199 | try {
|
---|
200 | return await (this._loading[ref] = loadSchema(ref));
|
---|
201 | }
|
---|
202 | finally {
|
---|
203 | delete this._loading[ref];
|
---|
204 | }
|
---|
205 | }
|
---|
206 | }
|
---|
207 | // Adds schema to the instance
|
---|
208 | addSchema(schema, // If array is passed, `key` will be ignored
|
---|
209 | key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
|
---|
210 | _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
|
---|
211 | _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
|
---|
212 | ) {
|
---|
213 | if (Array.isArray(schema)) {
|
---|
214 | for (const sch of schema)
|
---|
215 | this.addSchema(sch, undefined, _meta, _validateSchema);
|
---|
216 | return this;
|
---|
217 | }
|
---|
218 | let id;
|
---|
219 | if (typeof schema === "object") {
|
---|
220 | const { schemaId } = this.opts;
|
---|
221 | id = schema[schemaId];
|
---|
222 | if (id !== undefined && typeof id != "string") {
|
---|
223 | throw new Error(`schema ${schemaId} must be string`);
|
---|
224 | }
|
---|
225 | }
|
---|
226 | key = resolve_1.normalizeId(key || id);
|
---|
227 | this._checkUnique(key);
|
---|
228 | this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
|
---|
229 | return this;
|
---|
230 | }
|
---|
231 | // Add schema that will be used to validate other schemas
|
---|
232 | // options in META_IGNORE_OPTIONS are alway set to false
|
---|
233 | addMetaSchema(schema, key, // schema key
|
---|
234 | _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
|
---|
235 | ) {
|
---|
236 | this.addSchema(schema, key, true, _validateSchema);
|
---|
237 | return this;
|
---|
238 | }
|
---|
239 | // Validate schema against its meta-schema
|
---|
240 | validateSchema(schema, throwOrLogError) {
|
---|
241 | if (typeof schema == "boolean")
|
---|
242 | return true;
|
---|
243 | let $schema;
|
---|
244 | $schema = schema.$schema;
|
---|
245 | if ($schema !== undefined && typeof $schema != "string") {
|
---|
246 | throw new Error("$schema must be a string");
|
---|
247 | }
|
---|
248 | $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
|
---|
249 | if (!$schema) {
|
---|
250 | this.logger.warn("meta-schema not available");
|
---|
251 | this.errors = null;
|
---|
252 | return true;
|
---|
253 | }
|
---|
254 | const valid = this.validate($schema, schema);
|
---|
255 | if (!valid && throwOrLogError) {
|
---|
256 | const message = "schema is invalid: " + this.errorsText();
|
---|
257 | if (this.opts.validateSchema === "log")
|
---|
258 | this.logger.error(message);
|
---|
259 | else
|
---|
260 | throw new Error(message);
|
---|
261 | }
|
---|
262 | return valid;
|
---|
263 | }
|
---|
264 | // Get compiled schema by `key` or `ref`.
|
---|
265 | // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
|
---|
266 | getSchema(keyRef) {
|
---|
267 | let sch;
|
---|
268 | while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
|
---|
269 | keyRef = sch;
|
---|
270 | if (sch === undefined) {
|
---|
271 | const { schemaId } = this.opts;
|
---|
272 | const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
|
---|
273 | sch = compile_1.resolveSchema.call(this, root, keyRef);
|
---|
274 | if (!sch)
|
---|
275 | return;
|
---|
276 | this.refs[keyRef] = sch;
|
---|
277 | }
|
---|
278 | return (sch.validate || this._compileSchemaEnv(sch));
|
---|
279 | }
|
---|
280 | // Remove cached schema(s).
|
---|
281 | // If no parameter is passed all schemas but meta-schemas are removed.
|
---|
282 | // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
|
---|
283 | // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
|
---|
284 | removeSchema(schemaKeyRef) {
|
---|
285 | if (schemaKeyRef instanceof RegExp) {
|
---|
286 | this._removeAllSchemas(this.schemas, schemaKeyRef);
|
---|
287 | this._removeAllSchemas(this.refs, schemaKeyRef);
|
---|
288 | return this;
|
---|
289 | }
|
---|
290 | switch (typeof schemaKeyRef) {
|
---|
291 | case "undefined":
|
---|
292 | this._removeAllSchemas(this.schemas);
|
---|
293 | this._removeAllSchemas(this.refs);
|
---|
294 | this._cache.clear();
|
---|
295 | return this;
|
---|
296 | case "string": {
|
---|
297 | const sch = getSchEnv.call(this, schemaKeyRef);
|
---|
298 | if (typeof sch == "object")
|
---|
299 | this._cache.delete(sch.schema);
|
---|
300 | delete this.schemas[schemaKeyRef];
|
---|
301 | delete this.refs[schemaKeyRef];
|
---|
302 | return this;
|
---|
303 | }
|
---|
304 | case "object": {
|
---|
305 | const cacheKey = schemaKeyRef;
|
---|
306 | this._cache.delete(cacheKey);
|
---|
307 | let id = schemaKeyRef[this.opts.schemaId];
|
---|
308 | if (id) {
|
---|
309 | id = resolve_1.normalizeId(id);
|
---|
310 | delete this.schemas[id];
|
---|
311 | delete this.refs[id];
|
---|
312 | }
|
---|
313 | return this;
|
---|
314 | }
|
---|
315 | default:
|
---|
316 | throw new Error("ajv.removeSchema: invalid parameter");
|
---|
317 | }
|
---|
318 | }
|
---|
319 | // add "vocabulary" - a collection of keywords
|
---|
320 | addVocabulary(definitions) {
|
---|
321 | for (const def of definitions)
|
---|
322 | this.addKeyword(def);
|
---|
323 | return this;
|
---|
324 | }
|
---|
325 | addKeyword(kwdOrDef, def // deprecated
|
---|
326 | ) {
|
---|
327 | let keyword;
|
---|
328 | if (typeof kwdOrDef == "string") {
|
---|
329 | keyword = kwdOrDef;
|
---|
330 | if (typeof def == "object") {
|
---|
331 | this.logger.warn("these parameters are deprecated, see docs for addKeyword");
|
---|
332 | def.keyword = keyword;
|
---|
333 | }
|
---|
334 | }
|
---|
335 | else if (typeof kwdOrDef == "object" && def === undefined) {
|
---|
336 | def = kwdOrDef;
|
---|
337 | keyword = def.keyword;
|
---|
338 | if (Array.isArray(keyword) && !keyword.length) {
|
---|
339 | throw new Error("addKeywords: keyword must be string or non-empty array");
|
---|
340 | }
|
---|
341 | }
|
---|
342 | else {
|
---|
343 | throw new Error("invalid addKeywords parameters");
|
---|
344 | }
|
---|
345 | checkKeyword.call(this, keyword, def);
|
---|
346 | if (!def) {
|
---|
347 | util_1.eachItem(keyword, (kwd) => addRule.call(this, kwd));
|
---|
348 | return this;
|
---|
349 | }
|
---|
350 | keywordMetaschema.call(this, def);
|
---|
351 | const definition = {
|
---|
352 | ...def,
|
---|
353 | type: dataType_1.getJSONTypes(def.type),
|
---|
354 | schemaType: dataType_1.getJSONTypes(def.schemaType),
|
---|
355 | };
|
---|
356 | util_1.eachItem(keyword, definition.type.length === 0
|
---|
357 | ? (k) => addRule.call(this, k, definition)
|
---|
358 | : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
|
---|
359 | return this;
|
---|
360 | }
|
---|
361 | getKeyword(keyword) {
|
---|
362 | const rule = this.RULES.all[keyword];
|
---|
363 | return typeof rule == "object" ? rule.definition : !!rule;
|
---|
364 | }
|
---|
365 | // Remove keyword
|
---|
366 | removeKeyword(keyword) {
|
---|
367 | // TODO return type should be Ajv
|
---|
368 | const { RULES } = this;
|
---|
369 | delete RULES.keywords[keyword];
|
---|
370 | delete RULES.all[keyword];
|
---|
371 | for (const group of RULES.rules) {
|
---|
372 | const i = group.rules.findIndex((rule) => rule.keyword === keyword);
|
---|
373 | if (i >= 0)
|
---|
374 | group.rules.splice(i, 1);
|
---|
375 | }
|
---|
376 | return this;
|
---|
377 | }
|
---|
378 | // Add format
|
---|
379 | addFormat(name, format) {
|
---|
380 | if (typeof format == "string")
|
---|
381 | format = new RegExp(format);
|
---|
382 | this.formats[name] = format;
|
---|
383 | return this;
|
---|
384 | }
|
---|
385 | errorsText(errors = this.errors, // optional array of validation errors
|
---|
386 | { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
|
---|
387 | ) {
|
---|
388 | if (!errors || errors.length === 0)
|
---|
389 | return "No errors";
|
---|
390 | return errors
|
---|
391 | .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
|
---|
392 | .reduce((text, msg) => text + separator + msg);
|
---|
393 | }
|
---|
394 | $dataMetaSchema(metaSchema, keywordsJsonPointers) {
|
---|
395 | const rules = this.RULES.all;
|
---|
396 | metaSchema = JSON.parse(JSON.stringify(metaSchema));
|
---|
397 | for (const jsonPointer of keywordsJsonPointers) {
|
---|
398 | const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
|
---|
399 | let keywords = metaSchema;
|
---|
400 | for (const seg of segments)
|
---|
401 | keywords = keywords[seg];
|
---|
402 | for (const key in rules) {
|
---|
403 | const rule = rules[key];
|
---|
404 | if (typeof rule != "object")
|
---|
405 | continue;
|
---|
406 | const { $data } = rule.definition;
|
---|
407 | const schema = keywords[key];
|
---|
408 | if ($data && schema)
|
---|
409 | keywords[key] = schemaOrData(schema);
|
---|
410 | }
|
---|
411 | }
|
---|
412 | return metaSchema;
|
---|
413 | }
|
---|
414 | _removeAllSchemas(schemas, regex) {
|
---|
415 | for (const keyRef in schemas) {
|
---|
416 | const sch = schemas[keyRef];
|
---|
417 | if (!regex || regex.test(keyRef)) {
|
---|
418 | if (typeof sch == "string") {
|
---|
419 | delete schemas[keyRef];
|
---|
420 | }
|
---|
421 | else if (sch && !sch.meta) {
|
---|
422 | this._cache.delete(sch.schema);
|
---|
423 | delete schemas[keyRef];
|
---|
424 | }
|
---|
425 | }
|
---|
426 | }
|
---|
427 | }
|
---|
428 | _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
|
---|
429 | let id;
|
---|
430 | const { schemaId } = this.opts;
|
---|
431 | if (typeof schema == "object") {
|
---|
432 | id = schema[schemaId];
|
---|
433 | }
|
---|
434 | else {
|
---|
435 | if (this.opts.jtd)
|
---|
436 | throw new Error("schema must be object");
|
---|
437 | else if (typeof schema != "boolean")
|
---|
438 | throw new Error("schema must be object or boolean");
|
---|
439 | }
|
---|
440 | let sch = this._cache.get(schema);
|
---|
441 | if (sch !== undefined)
|
---|
442 | return sch;
|
---|
443 | const localRefs = resolve_1.getSchemaRefs.call(this, schema);
|
---|
444 | baseId = resolve_1.normalizeId(id || baseId);
|
---|
445 | sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
|
---|
446 | this._cache.set(sch.schema, sch);
|
---|
447 | if (addSchema && !baseId.startsWith("#")) {
|
---|
448 | // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
|
---|
449 | if (baseId)
|
---|
450 | this._checkUnique(baseId);
|
---|
451 | this.refs[baseId] = sch;
|
---|
452 | }
|
---|
453 | if (validateSchema)
|
---|
454 | this.validateSchema(schema, true);
|
---|
455 | return sch;
|
---|
456 | }
|
---|
457 | _checkUnique(id) {
|
---|
458 | if (this.schemas[id] || this.refs[id]) {
|
---|
459 | throw new Error(`schema with key or id "${id}" already exists`);
|
---|
460 | }
|
---|
461 | }
|
---|
462 | _compileSchemaEnv(sch) {
|
---|
463 | if (sch.meta)
|
---|
464 | this._compileMetaSchema(sch);
|
---|
465 | else
|
---|
466 | compile_1.compileSchema.call(this, sch);
|
---|
467 | /* istanbul ignore if */
|
---|
468 | if (!sch.validate)
|
---|
469 | throw new Error("ajv implementation error");
|
---|
470 | return sch.validate;
|
---|
471 | }
|
---|
472 | _compileMetaSchema(sch) {
|
---|
473 | const currentOpts = this.opts;
|
---|
474 | this.opts = this._metaOpts;
|
---|
475 | try {
|
---|
476 | compile_1.compileSchema.call(this, sch);
|
---|
477 | }
|
---|
478 | finally {
|
---|
479 | this.opts = currentOpts;
|
---|
480 | }
|
---|
481 | }
|
---|
482 | }
|
---|
483 | exports.default = Ajv;
|
---|
484 | Ajv.ValidationError = validation_error_1.default;
|
---|
485 | Ajv.MissingRefError = ref_error_1.default;
|
---|
486 | function checkOptions(checkOpts, options, msg, log = "error") {
|
---|
487 | for (const key in checkOpts) {
|
---|
488 | const opt = key;
|
---|
489 | if (opt in options)
|
---|
490 | this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
|
---|
491 | }
|
---|
492 | }
|
---|
493 | function getSchEnv(keyRef) {
|
---|
494 | keyRef = resolve_1.normalizeId(keyRef); // TODO tests fail without this line
|
---|
495 | return this.schemas[keyRef] || this.refs[keyRef];
|
---|
496 | }
|
---|
497 | function addInitialSchemas() {
|
---|
498 | const optsSchemas = this.opts.schemas;
|
---|
499 | if (!optsSchemas)
|
---|
500 | return;
|
---|
501 | if (Array.isArray(optsSchemas))
|
---|
502 | this.addSchema(optsSchemas);
|
---|
503 | else
|
---|
504 | for (const key in optsSchemas)
|
---|
505 | this.addSchema(optsSchemas[key], key);
|
---|
506 | }
|
---|
507 | function addInitialFormats() {
|
---|
508 | for (const name in this.opts.formats) {
|
---|
509 | const format = this.opts.formats[name];
|
---|
510 | if (format)
|
---|
511 | this.addFormat(name, format);
|
---|
512 | }
|
---|
513 | }
|
---|
514 | function addInitialKeywords(defs) {
|
---|
515 | if (Array.isArray(defs)) {
|
---|
516 | this.addVocabulary(defs);
|
---|
517 | return;
|
---|
518 | }
|
---|
519 | this.logger.warn("keywords option as map is deprecated, pass array");
|
---|
520 | for (const keyword in defs) {
|
---|
521 | const def = defs[keyword];
|
---|
522 | if (!def.keyword)
|
---|
523 | def.keyword = keyword;
|
---|
524 | this.addKeyword(def);
|
---|
525 | }
|
---|
526 | }
|
---|
527 | function getMetaSchemaOptions() {
|
---|
528 | const metaOpts = { ...this.opts };
|
---|
529 | for (const opt of META_IGNORE_OPTIONS)
|
---|
530 | delete metaOpts[opt];
|
---|
531 | return metaOpts;
|
---|
532 | }
|
---|
533 | const noLogs = { log() { }, warn() { }, error() { } };
|
---|
534 | function getLogger(logger) {
|
---|
535 | if (logger === false)
|
---|
536 | return noLogs;
|
---|
537 | if (logger === undefined)
|
---|
538 | return console;
|
---|
539 | if (logger.log && logger.warn && logger.error)
|
---|
540 | return logger;
|
---|
541 | throw new Error("logger must implement log, warn and error methods");
|
---|
542 | }
|
---|
543 | const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
|
---|
544 | function checkKeyword(keyword, def) {
|
---|
545 | const { RULES } = this;
|
---|
546 | util_1.eachItem(keyword, (kwd) => {
|
---|
547 | if (RULES.keywords[kwd])
|
---|
548 | throw new Error(`Keyword ${kwd} is already defined`);
|
---|
549 | if (!KEYWORD_NAME.test(kwd))
|
---|
550 | throw new Error(`Keyword ${kwd} has invalid name`);
|
---|
551 | });
|
---|
552 | if (!def)
|
---|
553 | return;
|
---|
554 | if (def.$data && !("code" in def || "validate" in def)) {
|
---|
555 | throw new Error('$data keyword must have "code" or "validate" function');
|
---|
556 | }
|
---|
557 | }
|
---|
558 | function addRule(keyword, definition, dataType) {
|
---|
559 | var _a;
|
---|
560 | const post = definition === null || definition === void 0 ? void 0 : definition.post;
|
---|
561 | if (dataType && post)
|
---|
562 | throw new Error('keyword with "post" flag cannot have "type"');
|
---|
563 | const { RULES } = this;
|
---|
564 | let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
|
---|
565 | if (!ruleGroup) {
|
---|
566 | ruleGroup = { type: dataType, rules: [] };
|
---|
567 | RULES.rules.push(ruleGroup);
|
---|
568 | }
|
---|
569 | RULES.keywords[keyword] = true;
|
---|
570 | if (!definition)
|
---|
571 | return;
|
---|
572 | const rule = {
|
---|
573 | keyword,
|
---|
574 | definition: {
|
---|
575 | ...definition,
|
---|
576 | type: dataType_1.getJSONTypes(definition.type),
|
---|
577 | schemaType: dataType_1.getJSONTypes(definition.schemaType),
|
---|
578 | },
|
---|
579 | };
|
---|
580 | if (definition.before)
|
---|
581 | addBeforeRule.call(this, ruleGroup, rule, definition.before);
|
---|
582 | else
|
---|
583 | ruleGroup.rules.push(rule);
|
---|
584 | RULES.all[keyword] = rule;
|
---|
585 | (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
|
---|
586 | }
|
---|
587 | function addBeforeRule(ruleGroup, rule, before) {
|
---|
588 | const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
|
---|
589 | if (i >= 0) {
|
---|
590 | ruleGroup.rules.splice(i, 0, rule);
|
---|
591 | }
|
---|
592 | else {
|
---|
593 | ruleGroup.rules.push(rule);
|
---|
594 | this.logger.warn(`rule ${before} is not defined`);
|
---|
595 | }
|
---|
596 | }
|
---|
597 | function keywordMetaschema(def) {
|
---|
598 | let { metaSchema } = def;
|
---|
599 | if (metaSchema === undefined)
|
---|
600 | return;
|
---|
601 | if (def.$data && this.opts.$data)
|
---|
602 | metaSchema = schemaOrData(metaSchema);
|
---|
603 | def.validateSchema = this.compile(metaSchema, true);
|
---|
604 | }
|
---|
605 | const $dataRef = {
|
---|
606 | $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
---|
607 | };
|
---|
608 | function schemaOrData(schema) {
|
---|
609 | return { anyOf: [schema, $dataRef] };
|
---|
610 | }
|
---|
611 | //# sourceMappingURL=core.js.map |
---|