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