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