Initial commit: ERP system with advance verification fixes
This commit is contained in:
+17
@@ -0,0 +1,17 @@
|
||||
export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, } from "./types";
|
||||
export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core";
|
||||
export { SchemaCxt, SchemaObjCxt } from "./compile";
|
||||
import KeywordCxt from "./compile/context";
|
||||
export { KeywordCxt };
|
||||
export { DefinedError } from "./vocabularies/errors";
|
||||
export { JSONType } from "./compile/rules";
|
||||
export { JSONSchemaType } from "./types/json-schema";
|
||||
export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen";
|
||||
import type { AnySchemaObject } from "./types";
|
||||
import AjvCore, { Options } from "./core";
|
||||
export default class Ajv2019 extends AjvCore {
|
||||
constructor(opts?: Options);
|
||||
_addVocabularies(): void;
|
||||
_addDefaultMetaSchema(): void;
|
||||
defaultMeta(): string | AnySchemaObject | undefined;
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
|
||||
const context_1 = require("./compile/context");
|
||||
exports.KeywordCxt = context_1.default;
|
||||
var codegen_1 = require("./compile/codegen");
|
||||
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
|
||||
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
|
||||
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
|
||||
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
|
||||
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
|
||||
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
|
||||
const core_1 = require("./core");
|
||||
const draft7_1 = require("./vocabularies/draft7");
|
||||
const dynamic_1 = require("./vocabularies/dynamic");
|
||||
const next_1 = require("./vocabularies/next");
|
||||
const unevaluated_1 = require("./vocabularies/unevaluated");
|
||||
const json_schema_2019_09_1 = require("./refs/json-schema-2019-09");
|
||||
const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema";
|
||||
class Ajv2019 extends core_1.default {
|
||||
constructor(opts = {}) {
|
||||
super({
|
||||
...opts,
|
||||
dynamicRef: true,
|
||||
next: true,
|
||||
unevaluated: true,
|
||||
});
|
||||
}
|
||||
_addVocabularies() {
|
||||
super._addVocabularies();
|
||||
this.addVocabulary(dynamic_1.default);
|
||||
draft7_1.default.forEach((v) => this.addVocabulary(v));
|
||||
this.addVocabulary(next_1.default);
|
||||
this.addVocabulary(unevaluated_1.default);
|
||||
}
|
||||
_addDefaultMetaSchema() {
|
||||
super._addDefaultMetaSchema();
|
||||
const { $data, meta } = this.opts;
|
||||
if (!meta)
|
||||
return;
|
||||
json_schema_2019_09_1.default.call(this, $data);
|
||||
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
|
||||
}
|
||||
defaultMeta() {
|
||||
return (this.opts.defaultMeta =
|
||||
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
|
||||
}
|
||||
}
|
||||
exports.default = Ajv2019;
|
||||
//# sourceMappingURL=2019.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"2019.js","sourceRoot":"","sources":["../lib/2019.ts"],"names":[],"mappings":";;;AAuBA,+CAA0C;AAClC,qBADD,iBAAU,CACC;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG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A9BD,0BA8BC"}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, SchemaValidateFunction, ErrorObject, ErrorNoParams, } from "./types";
|
||||
export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core";
|
||||
export { SchemaCxt, SchemaObjCxt } from "./compile";
|
||||
import KeywordCxt from "./compile/context";
|
||||
export { KeywordCxt };
|
||||
export { DefinedError } from "./vocabularies/errors";
|
||||
export { JSONType } from "./compile/rules";
|
||||
export { JSONSchemaType } from "./types/json-schema";
|
||||
export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen";
|
||||
import type { AnySchemaObject } from "./types";
|
||||
import AjvCore from "./core";
|
||||
export default class Ajv extends AjvCore {
|
||||
_addVocabularies(): void;
|
||||
_addDefaultMetaSchema(): void;
|
||||
defaultMeta(): string | AnySchemaObject | undefined;
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
|
||||
const context_1 = require("./compile/context");
|
||||
exports.KeywordCxt = context_1.default;
|
||||
var codegen_1 = require("./compile/codegen");
|
||||
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
|
||||
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
|
||||
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
|
||||
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
|
||||
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
|
||||
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
|
||||
const core_1 = require("./core");
|
||||
const draft7_1 = require("./vocabularies/draft7");
|
||||
const draft7MetaSchema = require("./refs/json-schema-draft-07.json");
|
||||
const META_SUPPORT_DATA = ["/properties"];
|
||||
const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
|
||||
class Ajv extends core_1.default {
|
||||
_addVocabularies() {
|
||||
super._addVocabularies();
|
||||
draft7_1.default.forEach((v) => this.addVocabulary(v));
|
||||
}
|
||||
_addDefaultMetaSchema() {
|
||||
super._addDefaultMetaSchema();
|
||||
if (!this.opts.meta)
|
||||
return;
|
||||
const metaSchema = this.opts.$data
|
||||
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
|
||||
: draft7MetaSchema;
|
||||
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
|
||||
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
|
||||
}
|
||||
defaultMeta() {
|
||||
return (this.opts.defaultMeta =
|
||||
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
|
||||
}
|
||||
}
|
||||
exports.default = Ajv;
|
||||
//# sourceMappingURL=ajv.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ajv.js","sourceRoot":"","sources":["../lib/ajv.ts"],"names":[],"mappings":";;;AAwBA,+CAA0C;AAClC,qBADD,iBAAU,CACC;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AAGnD,iCAA4B;AAC5B,kDAAsD;AACtD,qEAAoE;AAEpE,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,MAAM,cAAc,GAAG,wCAAwC,CAAA;AAE/D,MAAqB,GAAI,SAAQ,cAAO;IACtC,gBAAgB;QACd,KAAK,CAAC,gBAAgB,EAAE,CAAA;QACxB,gBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;IAC1D,CAAC;IAED,qBAAqB;QACnB,KAAK,CAAC,qBAAqB,EAAE,CAAA;QAC7B,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,OAAM;QAC3B,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK;YAChC,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,gBAAgB,EAAE,iBAAiB,CAAC;YAC3D,CAAC,CAAC,gBAAgB,CAAA;QACpB,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,cAAc,EAAE,KAAK,CAAC,CAAA;QACrD,IAAI,CAAC,IAAI,CAAC,+BAA+B,CAAC,GAAG,cAAc,CAAA;IAC7D,CAAC;IAED,WAAW;QACT,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW;YAC3B,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAA;IACzF,CAAC;CACF;AApBD,sBAoBC"}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
export declare abstract class _CodeOrName {
|
||||
abstract readonly str: string;
|
||||
abstract readonly names: UsedNames;
|
||||
abstract toString(): string;
|
||||
abstract emptyStr(): boolean;
|
||||
}
|
||||
export declare const IDENTIFIER: RegExp;
|
||||
export declare class Name extends _CodeOrName {
|
||||
readonly str: string;
|
||||
constructor(s: string);
|
||||
toString(): string;
|
||||
emptyStr(): boolean;
|
||||
get names(): UsedNames;
|
||||
}
|
||||
export declare class _Code extends _CodeOrName {
|
||||
readonly _items: readonly CodeItem[];
|
||||
private _str?;
|
||||
private _names?;
|
||||
constructor(code: string | readonly CodeItem[]);
|
||||
toString(): string;
|
||||
emptyStr(): boolean;
|
||||
get str(): string;
|
||||
get names(): UsedNames;
|
||||
}
|
||||
export declare type CodeItem = Name | string | number | boolean | null;
|
||||
export declare type UsedNames = Record<string, number | undefined>;
|
||||
export declare type Code = _Code | Name;
|
||||
export declare type SafeExpr = Code | number | boolean | null;
|
||||
export declare const nil: _Code;
|
||||
declare type CodeArg = SafeExpr | string | undefined;
|
||||
export declare function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code;
|
||||
export declare function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code;
|
||||
export declare function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void;
|
||||
export declare function strConcat(c1: Code, c2: Code): Code;
|
||||
export declare function stringify(x: unknown): Code;
|
||||
export declare function safeStringify(x: unknown): string;
|
||||
export declare function getProperty(key: Code | string | number): Code;
|
||||
export {};
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
|
||||
class _CodeOrName {
|
||||
}
|
||||
exports._CodeOrName = _CodeOrName;
|
||||
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
|
||||
class Name extends _CodeOrName {
|
||||
constructor(s) {
|
||||
super();
|
||||
if (!exports.IDENTIFIER.test(s))
|
||||
throw new Error("CodeGen: name must be a valid identifier");
|
||||
this.str = s;
|
||||
}
|
||||
toString() {
|
||||
return this.str;
|
||||
}
|
||||
emptyStr() {
|
||||
return false;
|
||||
}
|
||||
get names() {
|
||||
return { [this.str]: 1 };
|
||||
}
|
||||
}
|
||||
exports.Name = Name;
|
||||
class _Code extends _CodeOrName {
|
||||
constructor(code) {
|
||||
super();
|
||||
this._items = typeof code === "string" ? [code] : code;
|
||||
}
|
||||
toString() {
|
||||
return this.str;
|
||||
}
|
||||
emptyStr() {
|
||||
if (this._items.length > 1)
|
||||
return false;
|
||||
const item = this._items[0];
|
||||
return item === "" || item === '""';
|
||||
}
|
||||
get str() {
|
||||
var _a;
|
||||
return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
|
||||
}
|
||||
get names() {
|
||||
var _a;
|
||||
return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
|
||||
if (c instanceof Name)
|
||||
names[c.str] = (names[c.str] || 0) + 1;
|
||||
return names;
|
||||
}, {})));
|
||||
}
|
||||
}
|
||||
exports._Code = _Code;
|
||||
exports.nil = new _Code("");
|
||||
function _(strs, ...args) {
|
||||
const code = [strs[0]];
|
||||
let i = 0;
|
||||
while (i < args.length) {
|
||||
addCodeArg(code, args[i]);
|
||||
code.push(strs[++i]);
|
||||
}
|
||||
return new _Code(code);
|
||||
}
|
||||
exports._ = _;
|
||||
const plus = new _Code("+");
|
||||
function str(strs, ...args) {
|
||||
const expr = [safeStringify(strs[0])];
|
||||
let i = 0;
|
||||
while (i < args.length) {
|
||||
expr.push(plus);
|
||||
addCodeArg(expr, args[i]);
|
||||
expr.push(plus, safeStringify(strs[++i]));
|
||||
}
|
||||
optimize(expr);
|
||||
return new _Code(expr);
|
||||
}
|
||||
exports.str = str;
|
||||
function addCodeArg(code, arg) {
|
||||
if (arg instanceof _Code)
|
||||
code.push(...arg._items);
|
||||
else if (arg instanceof Name)
|
||||
code.push(arg);
|
||||
else
|
||||
code.push(interpolate(arg));
|
||||
}
|
||||
exports.addCodeArg = addCodeArg;
|
||||
function optimize(expr) {
|
||||
let i = 1;
|
||||
while (i < expr.length - 1) {
|
||||
if (expr[i] === plus) {
|
||||
const res = mergeExprItems(expr[i - 1], expr[i + 1]);
|
||||
if (res !== undefined) {
|
||||
expr.splice(i - 1, 3, res);
|
||||
continue;
|
||||
}
|
||||
expr[i++] = "+";
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
function mergeExprItems(a, b) {
|
||||
if (b === '""')
|
||||
return a;
|
||||
if (a === '""')
|
||||
return b;
|
||||
if (typeof a == "string") {
|
||||
if (b instanceof Name || a[a.length - 1] !== '"')
|
||||
return;
|
||||
if (typeof b != "string")
|
||||
return `${a.slice(0, -1)}${b}"`;
|
||||
if (b[0] === '"')
|
||||
return a.slice(0, -1) + b.slice(1);
|
||||
return;
|
||||
}
|
||||
if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
|
||||
return `"${a}${b.slice(1)}`;
|
||||
return;
|
||||
}
|
||||
function strConcat(c1, c2) {
|
||||
return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
|
||||
}
|
||||
exports.strConcat = strConcat;
|
||||
// TODO do not allow arrays here
|
||||
function interpolate(x) {
|
||||
return typeof x == "number" || typeof x == "boolean" || x === null
|
||||
? x
|
||||
: safeStringify(Array.isArray(x) ? x.join(",") : x);
|
||||
}
|
||||
function stringify(x) {
|
||||
return new _Code(safeStringify(x));
|
||||
}
|
||||
exports.stringify = stringify;
|
||||
function safeStringify(x) {
|
||||
return JSON.stringify(x)
|
||||
.replace(/\u2028/g, "\\u2028")
|
||||
.replace(/\u2029/g, "\\u2029");
|
||||
}
|
||||
exports.safeStringify = safeStringify;
|
||||
function getProperty(key) {
|
||||
return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
|
||||
}
|
||||
exports.getProperty = getProperty;
|
||||
//# sourceMappingURL=code.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"code.js","sourceRoot":"","sources":["../../../lib/compile/codegen/code.ts"],"names":[],"mappings":";;;AAAA,MAAsB,WAAW;CAKhC;AALD,kCAKC;AAEY,QAAA,UAAU,GAAG,uBAAuB,CAAA;AAEjD,MAAa,IAAK,SAAQ,WAAW;IAEnC,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;AACvD,CAAC;AAED,SAAgB,SAAS,CAAC,CAAU;IAClC,OAAO,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;AACpC,CAAC;AAFD,8BAEC;AAED,SAAgB,aAAa,CAAC,CAAU;IACtC,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7B,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;AAClC,CAAC;AAJD,sCAIC;AAED,SAAgB,WAAW,CAAC,GAA2B;IACrD,OAAO,OAAO,GAAG,IAAI,QAAQ,IAAI,kBAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA,IAAI,GAAG,GAAG,CAAA;AAC5F,CAAC;AAFD,kCAEC"}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import type { ScopeValueSets, NameValue, ValueScope, ValueScopeName } from "./scope";
|
||||
import { _Code, Code, Name } from "./code";
|
||||
import { Scope } from "./scope";
|
||||
export { _, str, strConcat, nil, getProperty, stringify, Name, Code } from "./code";
|
||||
export { Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds } from "./scope";
|
||||
export declare type SafeExpr = Code | number | boolean | null;
|
||||
export declare type Block = Code | (() => void);
|
||||
export declare const operators: {
|
||||
GT: _Code;
|
||||
GTE: _Code;
|
||||
LT: _Code;
|
||||
LTE: _Code;
|
||||
EQ: _Code;
|
||||
NEQ: _Code;
|
||||
NOT: _Code;
|
||||
OR: _Code;
|
||||
AND: _Code;
|
||||
ADD: _Code;
|
||||
};
|
||||
export interface CodeGenOptions {
|
||||
es5?: boolean;
|
||||
lines?: boolean;
|
||||
ownProperties?: boolean;
|
||||
}
|
||||
export declare class CodeGen {
|
||||
readonly _scope: Scope;
|
||||
readonly _extScope: ValueScope;
|
||||
readonly _values: ScopeValueSets;
|
||||
private readonly _nodes;
|
||||
private readonly _blockStarts;
|
||||
private readonly _constants;
|
||||
private readonly opts;
|
||||
constructor(extScope: ValueScope, opts?: CodeGenOptions);
|
||||
toString(): string;
|
||||
name(prefix: string): Name;
|
||||
scopeName(prefix: string): ValueScopeName;
|
||||
scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name;
|
||||
getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined;
|
||||
scopeRefs(scopeName: Name): Code;
|
||||
scopeCode(): Code;
|
||||
private _def;
|
||||
const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name;
|
||||
let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name;
|
||||
var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name;
|
||||
assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen;
|
||||
add(lhs: Code, rhs: SafeExpr): CodeGen;
|
||||
code(c: Block | SafeExpr): CodeGen;
|
||||
object(...keyValues: [Name | string, SafeExpr | string][]): _Code;
|
||||
if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen;
|
||||
elseIf(condition: Code | boolean): CodeGen;
|
||||
else(): CodeGen;
|
||||
endIf(): CodeGen;
|
||||
private _for;
|
||||
for(iteration: Code, forBody?: Block): CodeGen;
|
||||
forRange(nameOrPrefix: Name | string, from: SafeExpr, to: SafeExpr, forBody: (index: Name) => void, varKind?: Code): CodeGen;
|
||||
forOf(nameOrPrefix: Name | string, iterable: Code, forBody: (item: Name) => void, varKind?: Code): CodeGen;
|
||||
forIn(nameOrPrefix: Name | string, obj: Code, forBody: (item: Name) => void, varKind?: Code): CodeGen;
|
||||
endFor(): CodeGen;
|
||||
label(label: Name): CodeGen;
|
||||
break(label?: Code): CodeGen;
|
||||
return(value: Block | SafeExpr): CodeGen;
|
||||
try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen;
|
||||
throw(error: Code): CodeGen;
|
||||
block(body?: Block, nodeCount?: number): CodeGen;
|
||||
endBlock(nodeCount?: number): CodeGen;
|
||||
func(name: Name, args?: Code, async?: boolean, funcBody?: Block): CodeGen;
|
||||
endFunc(): CodeGen;
|
||||
optimize(n?: number): void;
|
||||
private _leafNode;
|
||||
private _blockNode;
|
||||
private _endBlockNode;
|
||||
private _elseNode;
|
||||
private get _root();
|
||||
private get _currNode();
|
||||
private set _currNode(value);
|
||||
}
|
||||
export declare function not<T extends Code | SafeExpr>(x: T): T;
|
||||
export declare function and(...args: Code[]): Code;
|
||||
export declare function or(...args: Code[]): Code;
|
||||
+696
@@ -0,0 +1,696 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
|
||||
const code_1 = require("./code");
|
||||
const scope_1 = require("./scope");
|
||||
var code_2 = require("./code");
|
||||
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return code_2._; } });
|
||||
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return code_2.str; } });
|
||||
Object.defineProperty(exports, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } });
|
||||
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return code_2.nil; } });
|
||||
Object.defineProperty(exports, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } });
|
||||
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return code_2.stringify; } });
|
||||
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return code_2.Name; } });
|
||||
var scope_2 = require("./scope");
|
||||
Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
|
||||
Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
|
||||
Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
|
||||
Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
|
||||
exports.operators = {
|
||||
GT: new code_1._Code(">"),
|
||||
GTE: new code_1._Code(">="),
|
||||
LT: new code_1._Code("<"),
|
||||
LTE: new code_1._Code("<="),
|
||||
EQ: new code_1._Code("==="),
|
||||
NEQ: new code_1._Code("!=="),
|
||||
NOT: new code_1._Code("!"),
|
||||
OR: new code_1._Code("||"),
|
||||
AND: new code_1._Code("&&"),
|
||||
ADD: new code_1._Code("+"),
|
||||
};
|
||||
class Node {
|
||||
optimizeNodes() {
|
||||
return this;
|
||||
}
|
||||
optimizeNames(_names, _constants) {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class Def extends Node {
|
||||
constructor(varKind, name, rhs) {
|
||||
super();
|
||||
this.varKind = varKind;
|
||||
this.name = name;
|
||||
this.rhs = rhs;
|
||||
}
|
||||
render({ es5, _n }) {
|
||||
const varKind = es5 ? scope_1.varKinds.var : this.varKind;
|
||||
const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
|
||||
return `${varKind} ${this.name}${rhs};` + _n;
|
||||
}
|
||||
optimizeNames(names, constants) {
|
||||
if (!names[this.name.str])
|
||||
return;
|
||||
if (this.rhs)
|
||||
this.rhs = optimizeExpr(this.rhs, names, constants);
|
||||
return this;
|
||||
}
|
||||
get names() {
|
||||
return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
|
||||
}
|
||||
}
|
||||
class Assign extends Node {
|
||||
constructor(lhs, rhs, sideEffects) {
|
||||
super();
|
||||
this.lhs = lhs;
|
||||
this.rhs = rhs;
|
||||
this.sideEffects = sideEffects;
|
||||
}
|
||||
render({ _n }) {
|
||||
return `${this.lhs} = ${this.rhs};` + _n;
|
||||
}
|
||||
optimizeNames(names, constants) {
|
||||
if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
|
||||
return;
|
||||
this.rhs = optimizeExpr(this.rhs, names, constants);
|
||||
return this;
|
||||
}
|
||||
get names() {
|
||||
const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
|
||||
return addExprNames(names, this.rhs);
|
||||
}
|
||||
}
|
||||
class AssignOp extends Assign {
|
||||
constructor(lhs, op, rhs, sideEffects) {
|
||||
super(lhs, rhs, sideEffects);
|
||||
this.op = op;
|
||||
}
|
||||
render({ _n }) {
|
||||
return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
|
||||
}
|
||||
}
|
||||
class Label extends Node {
|
||||
constructor(label) {
|
||||
super();
|
||||
this.label = label;
|
||||
this.names = {};
|
||||
}
|
||||
render({ _n }) {
|
||||
return `${this.label}:` + _n;
|
||||
}
|
||||
}
|
||||
class Break extends Node {
|
||||
constructor(label) {
|
||||
super();
|
||||
this.label = label;
|
||||
this.names = {};
|
||||
}
|
||||
render({ _n }) {
|
||||
const label = this.label ? ` ${this.label}` : "";
|
||||
return `break${label};` + _n;
|
||||
}
|
||||
}
|
||||
class Throw extends Node {
|
||||
constructor(error) {
|
||||
super();
|
||||
this.error = error;
|
||||
}
|
||||
render({ _n }) {
|
||||
return `throw ${this.error};` + _n;
|
||||
}
|
||||
get names() {
|
||||
return this.error.names;
|
||||
}
|
||||
}
|
||||
class AnyCode extends Node {
|
||||
constructor(code) {
|
||||
super();
|
||||
this.code = code;
|
||||
}
|
||||
render({ _n }) {
|
||||
return `${this.code};` + _n;
|
||||
}
|
||||
optimizeNodes() {
|
||||
return `${this.code}` ? this : undefined;
|
||||
}
|
||||
optimizeNames(names, constants) {
|
||||
this.code = optimizeExpr(this.code, names, constants);
|
||||
return this;
|
||||
}
|
||||
get names() {
|
||||
return this.code instanceof code_1._CodeOrName ? this.code.names : {};
|
||||
}
|
||||
}
|
||||
class ParentNode extends Node {
|
||||
constructor(nodes = []) {
|
||||
super();
|
||||
this.nodes = nodes;
|
||||
}
|
||||
render(opts) {
|
||||
return this.nodes.reduce((code, n) => code + n.render(opts), "");
|
||||
}
|
||||
optimizeNodes() {
|
||||
const { nodes } = this;
|
||||
let i = nodes.length;
|
||||
while (i--) {
|
||||
const n = nodes[i].optimizeNodes();
|
||||
if (Array.isArray(n))
|
||||
nodes.splice(i, 1, ...n);
|
||||
else if (n)
|
||||
nodes[i] = n;
|
||||
else
|
||||
nodes.splice(i, 1);
|
||||
}
|
||||
return nodes.length > 0 ? this : undefined;
|
||||
}
|
||||
optimizeNames(names, constants) {
|
||||
const { nodes } = this;
|
||||
let i = nodes.length;
|
||||
while (i--) {
|
||||
// iterating backwards improves 1-pass optimization
|
||||
const n = nodes[i];
|
||||
if (n.optimizeNames(names, constants))
|
||||
continue;
|
||||
subtractNames(names, n.names);
|
||||
nodes.splice(i, 1);
|
||||
}
|
||||
return nodes.length > 0 ? this : undefined;
|
||||
}
|
||||
get names() {
|
||||
return this.nodes.reduce((names, n) => addNames(names, n.names), {});
|
||||
}
|
||||
}
|
||||
class BlockNode extends ParentNode {
|
||||
render(opts) {
|
||||
return "{" + opts._n + super.render(opts) + "}" + opts._n;
|
||||
}
|
||||
}
|
||||
class Root extends ParentNode {
|
||||
}
|
||||
class Else extends BlockNode {
|
||||
}
|
||||
Else.kind = "else";
|
||||
class If extends BlockNode {
|
||||
constructor(condition, nodes) {
|
||||
super(nodes);
|
||||
this.condition = condition;
|
||||
}
|
||||
render(opts) {
|
||||
let code = `if(${this.condition})` + super.render(opts);
|
||||
if (this.else)
|
||||
code += "else " + this.else.render(opts);
|
||||
return code;
|
||||
}
|
||||
optimizeNodes() {
|
||||
super.optimizeNodes();
|
||||
const cond = this.condition;
|
||||
if (cond === true)
|
||||
return this.nodes; // else is ignored here
|
||||
let e = this.else;
|
||||
if (e) {
|
||||
const ns = e.optimizeNodes();
|
||||
e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
|
||||
}
|
||||
if (e) {
|
||||
if (cond === false)
|
||||
return e instanceof If ? e : e.nodes;
|
||||
if (this.nodes.length)
|
||||
return this;
|
||||
return new If(not(cond), e instanceof If ? [e] : e.nodes);
|
||||
}
|
||||
if (cond === false || !this.nodes.length)
|
||||
return undefined;
|
||||
return this;
|
||||
}
|
||||
optimizeNames(names, constants) {
|
||||
var _a;
|
||||
this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
|
||||
if (!(super.optimizeNames(names, constants) || this.else))
|
||||
return;
|
||||
this.condition = optimizeExpr(this.condition, names, constants);
|
||||
return this;
|
||||
}
|
||||
get names() {
|
||||
const names = super.names;
|
||||
addExprNames(names, this.condition);
|
||||
if (this.else)
|
||||
addNames(names, this.else.names);
|
||||
return names;
|
||||
}
|
||||
}
|
||||
If.kind = "if";
|
||||
class For extends BlockNode {
|
||||
}
|
||||
For.kind = "for";
|
||||
class ForLoop extends For {
|
||||
constructor(iteration) {
|
||||
super();
|
||||
this.iteration = iteration;
|
||||
}
|
||||
render(opts) {
|
||||
return `for(${this.iteration})` + super.render(opts);
|
||||
}
|
||||
optimizeNames(names, constants) {
|
||||
if (!super.optimizeNames(names, constants))
|
||||
return;
|
||||
this.iteration = optimizeExpr(this.iteration, names, constants);
|
||||
return this;
|
||||
}
|
||||
get names() {
|
||||
return addNames(super.names, this.iteration.names);
|
||||
}
|
||||
}
|
||||
class ForRange extends For {
|
||||
constructor(varKind, name, from, to) {
|
||||
super();
|
||||
this.varKind = varKind;
|
||||
this.name = name;
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
}
|
||||
render(opts) {
|
||||
const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
|
||||
const { name, from, to } = this;
|
||||
return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
|
||||
}
|
||||
get names() {
|
||||
const names = addExprNames(super.names, this.from);
|
||||
return addExprNames(names, this.to);
|
||||
}
|
||||
}
|
||||
class ForIter extends For {
|
||||
constructor(loop, varKind, name, iterable) {
|
||||
super();
|
||||
this.loop = loop;
|
||||
this.varKind = varKind;
|
||||
this.name = name;
|
||||
this.iterable = iterable;
|
||||
}
|
||||
render(opts) {
|
||||
return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
|
||||
}
|
||||
optimizeNames(names, constants) {
|
||||
if (!super.optimizeNames(names, constants))
|
||||
return;
|
||||
this.iterable = optimizeExpr(this.iterable, names, constants);
|
||||
return this;
|
||||
}
|
||||
get names() {
|
||||
return addNames(super.names, this.iterable.names);
|
||||
}
|
||||
}
|
||||
class Func extends BlockNode {
|
||||
constructor(name, args, async) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.args = args;
|
||||
this.async = async;
|
||||
}
|
||||
render(opts) {
|
||||
const _async = this.async ? "async " : "";
|
||||
return `${_async}function ${this.name}(${this.args})` + super.render(opts);
|
||||
}
|
||||
}
|
||||
Func.kind = "func";
|
||||
class Return extends ParentNode {
|
||||
render(opts) {
|
||||
return "return " + super.render(opts);
|
||||
}
|
||||
}
|
||||
Return.kind = "return";
|
||||
class Try extends BlockNode {
|
||||
render(opts) {
|
||||
let code = "try" + super.render(opts);
|
||||
if (this.catch)
|
||||
code += this.catch.render(opts);
|
||||
if (this.finally)
|
||||
code += this.finally.render(opts);
|
||||
return code;
|
||||
}
|
||||
optimizeNodes() {
|
||||
var _a, _b;
|
||||
super.optimizeNodes();
|
||||
(_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
|
||||
(_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
|
||||
return this;
|
||||
}
|
||||
optimizeNames(names, constants) {
|
||||
var _a, _b;
|
||||
super.optimizeNames(names, constants);
|
||||
(_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
|
||||
(_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
|
||||
return this;
|
||||
}
|
||||
get names() {
|
||||
const names = super.names;
|
||||
if (this.catch)
|
||||
addNames(names, this.catch.names);
|
||||
if (this.finally)
|
||||
addNames(names, this.finally.names);
|
||||
return names;
|
||||
}
|
||||
}
|
||||
class Catch extends BlockNode {
|
||||
constructor(error) {
|
||||
super();
|
||||
this.error = error;
|
||||
}
|
||||
render(opts) {
|
||||
return `catch(${this.error})` + super.render(opts);
|
||||
}
|
||||
}
|
||||
Catch.kind = "catch";
|
||||
class Finally extends BlockNode {
|
||||
render(opts) {
|
||||
return "finally" + super.render(opts);
|
||||
}
|
||||
}
|
||||
Finally.kind = "finally";
|
||||
class CodeGen {
|
||||
constructor(extScope, opts = {}) {
|
||||
this._values = {};
|
||||
this._blockStarts = [];
|
||||
this._constants = {};
|
||||
this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
|
||||
this._extScope = extScope;
|
||||
this._scope = new scope_1.Scope({ parent: extScope });
|
||||
this._nodes = [new Root()];
|
||||
}
|
||||
toString() {
|
||||
return this._root.render(this.opts);
|
||||
}
|
||||
// returns unique name in the internal scope
|
||||
name(prefix) {
|
||||
return this._scope.name(prefix);
|
||||
}
|
||||
// reserves unique name in the external scope
|
||||
scopeName(prefix) {
|
||||
return this._extScope.name(prefix);
|
||||
}
|
||||
// reserves unique name in the external scope and assigns value to it
|
||||
scopeValue(prefixOrName, value) {
|
||||
const name = this._extScope.value(prefixOrName, value);
|
||||
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
|
||||
vs.add(name);
|
||||
return name;
|
||||
}
|
||||
getScopeValue(prefix, keyOrRef) {
|
||||
return this._extScope.getValue(prefix, keyOrRef);
|
||||
}
|
||||
// return code that assigns values in the external scope to the names that are used internally
|
||||
// (same names that were returned by gen.scopeName or gen.scopeValue)
|
||||
scopeRefs(scopeName) {
|
||||
return this._extScope.scopeRefs(scopeName, this._values);
|
||||
}
|
||||
scopeCode() {
|
||||
return this._extScope.scopeCode(this._values);
|
||||
}
|
||||
_def(varKind, nameOrPrefix, rhs, constant) {
|
||||
const name = this._scope.toName(nameOrPrefix);
|
||||
if (rhs !== undefined && constant)
|
||||
this._constants[name.str] = rhs;
|
||||
this._leafNode(new Def(varKind, name, rhs));
|
||||
return name;
|
||||
}
|
||||
// `const` declaration (`var` in es5 mode)
|
||||
const(nameOrPrefix, rhs, _constant) {
|
||||
return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
|
||||
}
|
||||
// `let` declaration with optional assignment (`var` in es5 mode)
|
||||
let(nameOrPrefix, rhs, _constant) {
|
||||
return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
|
||||
}
|
||||
// `var` declaration with optional assignment
|
||||
var(nameOrPrefix, rhs, _constant) {
|
||||
return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
|
||||
}
|
||||
// assignment code
|
||||
assign(lhs, rhs, sideEffects) {
|
||||
return this._leafNode(new Assign(lhs, rhs, sideEffects));
|
||||
}
|
||||
// `+=` code
|
||||
add(lhs, rhs) {
|
||||
return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
|
||||
}
|
||||
// appends passed SafeExpr to code or executes Block
|
||||
code(c) {
|
||||
if (typeof c == "function")
|
||||
c();
|
||||
else if (c !== code_1.nil)
|
||||
this._leafNode(new AnyCode(c));
|
||||
return this;
|
||||
}
|
||||
// returns code for object literal for the passed argument list of key-value pairs
|
||||
object(...keyValues) {
|
||||
const code = ["{"];
|
||||
for (const [key, value] of keyValues) {
|
||||
if (code.length > 1)
|
||||
code.push(",");
|
||||
code.push(key);
|
||||
if (key !== value || this.opts.es5) {
|
||||
code.push(":");
|
||||
code_1.addCodeArg(code, value);
|
||||
}
|
||||
}
|
||||
code.push("}");
|
||||
return new code_1._Code(code);
|
||||
}
|
||||
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
|
||||
if(condition, thenBody, elseBody) {
|
||||
this._blockNode(new If(condition));
|
||||
if (thenBody && elseBody) {
|
||||
this.code(thenBody).else().code(elseBody).endIf();
|
||||
}
|
||||
else if (thenBody) {
|
||||
this.code(thenBody).endIf();
|
||||
}
|
||||
else if (elseBody) {
|
||||
throw new Error('CodeGen: "else" body without "then" body');
|
||||
}
|
||||
return this;
|
||||
}
|
||||
// `else if` clause - invalid without `if` or after `else` clauses
|
||||
elseIf(condition) {
|
||||
return this._elseNode(new If(condition));
|
||||
}
|
||||
// `else` clause - only valid after `if` or `else if` clauses
|
||||
else() {
|
||||
return this._elseNode(new Else());
|
||||
}
|
||||
// end `if` statement (needed if gen.if was used only with condition)
|
||||
endIf() {
|
||||
return this._endBlockNode(If, Else);
|
||||
}
|
||||
_for(node, forBody) {
|
||||
this._blockNode(node);
|
||||
if (forBody)
|
||||
this.code(forBody).endFor();
|
||||
return this;
|
||||
}
|
||||
// a generic `for` clause (or statement if `forBody` is passed)
|
||||
for(iteration, forBody) {
|
||||
return this._for(new ForLoop(iteration), forBody);
|
||||
}
|
||||
// `for` statement for a range of values
|
||||
forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
|
||||
const name = this._scope.toName(nameOrPrefix);
|
||||
return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
|
||||
}
|
||||
// `for-of` statement (in es5 mode replace with a normal for loop)
|
||||
forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
|
||||
const name = this._scope.toName(nameOrPrefix);
|
||||
if (this.opts.es5) {
|
||||
const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
|
||||
return this.forRange("_i", 0, code_1._ `${arr}.length`, (i) => {
|
||||
this.var(name, code_1._ `${arr}[${i}]`);
|
||||
forBody(name);
|
||||
});
|
||||
}
|
||||
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
|
||||
}
|
||||
// `for-in` statement.
|
||||
// With option `ownProperties` replaced with a `for-of` loop for object keys
|
||||
forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
|
||||
if (this.opts.ownProperties) {
|
||||
return this.forOf(nameOrPrefix, code_1._ `Object.keys(${obj})`, forBody);
|
||||
}
|
||||
const name = this._scope.toName(nameOrPrefix);
|
||||
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
|
||||
}
|
||||
// end `for` loop
|
||||
endFor() {
|
||||
return this._endBlockNode(For);
|
||||
}
|
||||
// `label` statement
|
||||
label(label) {
|
||||
return this._leafNode(new Label(label));
|
||||
}
|
||||
// `break` statement
|
||||
break(label) {
|
||||
return this._leafNode(new Break(label));
|
||||
}
|
||||
// `return` statement
|
||||
return(value) {
|
||||
const node = new Return();
|
||||
this._blockNode(node);
|
||||
this.code(value);
|
||||
if (node.nodes.length !== 1)
|
||||
throw new Error('CodeGen: "return" should have one node');
|
||||
return this._endBlockNode(Return);
|
||||
}
|
||||
// `try` statement
|
||||
try(tryBody, catchCode, finallyCode) {
|
||||
if (!catchCode && !finallyCode)
|
||||
throw new Error('CodeGen: "try" without "catch" and "finally"');
|
||||
const node = new Try();
|
||||
this._blockNode(node);
|
||||
this.code(tryBody);
|
||||
if (catchCode) {
|
||||
const error = this.name("e");
|
||||
this._currNode = node.catch = new Catch(error);
|
||||
catchCode(error);
|
||||
}
|
||||
if (finallyCode) {
|
||||
this._currNode = node.finally = new Finally();
|
||||
this.code(finallyCode);
|
||||
}
|
||||
return this._endBlockNode(Catch, Finally);
|
||||
}
|
||||
// `throw` statement
|
||||
throw(error) {
|
||||
return this._leafNode(new Throw(error));
|
||||
}
|
||||
// start self-balancing block
|
||||
block(body, nodeCount) {
|
||||
this._blockStarts.push(this._nodes.length);
|
||||
if (body)
|
||||
this.code(body).endBlock(nodeCount);
|
||||
return this;
|
||||
}
|
||||
// end the current self-balancing block
|
||||
endBlock(nodeCount) {
|
||||
const len = this._blockStarts.pop();
|
||||
if (len === undefined)
|
||||
throw new Error("CodeGen: not in self-balancing block");
|
||||
const toClose = this._nodes.length - len;
|
||||
if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
|
||||
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
|
||||
}
|
||||
this._nodes.length = len;
|
||||
return this;
|
||||
}
|
||||
// `function` heading (or definition if funcBody is passed)
|
||||
func(name, args = code_1.nil, async, funcBody) {
|
||||
this._blockNode(new Func(name, args, async));
|
||||
if (funcBody)
|
||||
this.code(funcBody).endFunc();
|
||||
return this;
|
||||
}
|
||||
// end function definition
|
||||
endFunc() {
|
||||
return this._endBlockNode(Func);
|
||||
}
|
||||
optimize(n = 1) {
|
||||
while (n-- > 0) {
|
||||
this._root.optimizeNodes();
|
||||
this._root.optimizeNames(this._root.names, this._constants);
|
||||
}
|
||||
}
|
||||
_leafNode(node) {
|
||||
this._currNode.nodes.push(node);
|
||||
return this;
|
||||
}
|
||||
_blockNode(node) {
|
||||
this._currNode.nodes.push(node);
|
||||
this._nodes.push(node);
|
||||
}
|
||||
_endBlockNode(N1, N2) {
|
||||
const n = this._currNode;
|
||||
if (n instanceof N1 || (N2 && n instanceof N2)) {
|
||||
this._nodes.pop();
|
||||
return this;
|
||||
}
|
||||
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
|
||||
}
|
||||
_elseNode(node) {
|
||||
const n = this._currNode;
|
||||
if (!(n instanceof If)) {
|
||||
throw new Error('CodeGen: "else" without "if"');
|
||||
}
|
||||
this._currNode = n.else = node;
|
||||
return this;
|
||||
}
|
||||
get _root() {
|
||||
return this._nodes[0];
|
||||
}
|
||||
get _currNode() {
|
||||
const ns = this._nodes;
|
||||
return ns[ns.length - 1];
|
||||
}
|
||||
set _currNode(node) {
|
||||
const ns = this._nodes;
|
||||
ns[ns.length - 1] = node;
|
||||
}
|
||||
}
|
||||
exports.CodeGen = CodeGen;
|
||||
function addNames(names, from) {
|
||||
for (const n in from)
|
||||
names[n] = (names[n] || 0) + (from[n] || 0);
|
||||
return names;
|
||||
}
|
||||
function addExprNames(names, from) {
|
||||
return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
|
||||
}
|
||||
function optimizeExpr(expr, names, constants) {
|
||||
if (expr instanceof code_1.Name)
|
||||
return replaceName(expr);
|
||||
if (!canOptimize(expr))
|
||||
return expr;
|
||||
return new code_1._Code(expr._items.reduce((items, c) => {
|
||||
if (c instanceof code_1.Name)
|
||||
c = replaceName(c);
|
||||
if (c instanceof code_1._Code)
|
||||
items.push(...c._items);
|
||||
else
|
||||
items.push(c);
|
||||
return items;
|
||||
}, []));
|
||||
function replaceName(n) {
|
||||
const c = constants[n.str];
|
||||
if (c === undefined || names[n.str] !== 1)
|
||||
return n;
|
||||
delete names[n.str];
|
||||
return c;
|
||||
}
|
||||
function canOptimize(e) {
|
||||
return (e instanceof code_1._Code &&
|
||||
e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
|
||||
}
|
||||
}
|
||||
function subtractNames(names, from) {
|
||||
for (const n in from)
|
||||
names[n] = (names[n] || 0) - (from[n] || 0);
|
||||
}
|
||||
function not(x) {
|
||||
return typeof x == "boolean" || typeof x == "number" || x === null ? !x : code_1._ `!${par(x)}`;
|
||||
}
|
||||
exports.not = not;
|
||||
const andCode = mappend(exports.operators.AND);
|
||||
// boolean AND (&&) expression with the passed arguments
|
||||
function and(...args) {
|
||||
return args.reduce(andCode);
|
||||
}
|
||||
exports.and = and;
|
||||
const orCode = mappend(exports.operators.OR);
|
||||
// boolean OR (||) expression with the passed arguments
|
||||
function or(...args) {
|
||||
return args.reduce(orCode);
|
||||
}
|
||||
exports.or = or;
|
||||
function mappend(op) {
|
||||
return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : code_1._ `${par(x)} ${op} ${par(y)}`);
|
||||
}
|
||||
function par(x) {
|
||||
return x instanceof code_1.Name ? x : code_1._ `(${x})`;
|
||||
}
|
||||
//# sourceMappingURL=index.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+79
@@ -0,0 +1,79 @@
|
||||
import { Code, Name } from "./code";
|
||||
interface NameGroup {
|
||||
prefix: string;
|
||||
index: number;
|
||||
}
|
||||
export interface NameValue {
|
||||
ref: ValueReference;
|
||||
key?: unknown;
|
||||
code?: Code;
|
||||
}
|
||||
export declare type ValueReference = unknown;
|
||||
interface ScopeOptions {
|
||||
prefixes?: Set<string>;
|
||||
parent?: Scope;
|
||||
}
|
||||
interface ValueScopeOptions extends ScopeOptions {
|
||||
scope: ScopeStore;
|
||||
es5?: boolean;
|
||||
lines?: boolean;
|
||||
}
|
||||
export declare type ScopeStore = Record<string, ValueReference[] | undefined>;
|
||||
declare type ScopeValues = {
|
||||
[Prefix in string]?: Map<unknown, ValueScopeName>;
|
||||
};
|
||||
export declare type ScopeValueSets = {
|
||||
[Prefix in string]?: Set<ValueScopeName>;
|
||||
};
|
||||
export declare enum UsedValueState {
|
||||
Started = 0,
|
||||
Completed = 1
|
||||
}
|
||||
export declare type UsedScopeValues = {
|
||||
[Prefix in string]?: Map<ValueScopeName, UsedValueState | undefined>;
|
||||
};
|
||||
export declare const varKinds: {
|
||||
const: Name;
|
||||
let: Name;
|
||||
var: Name;
|
||||
};
|
||||
export declare class Scope {
|
||||
protected readonly _names: {
|
||||
[Prefix in string]?: NameGroup;
|
||||
};
|
||||
protected readonly _prefixes?: Set<string>;
|
||||
protected readonly _parent?: Scope;
|
||||
constructor({ prefixes, parent }?: ScopeOptions);
|
||||
toName(nameOrPrefix: Name | string): Name;
|
||||
name(prefix: string): Name;
|
||||
protected _newName(prefix: string): string;
|
||||
private _nameGroup;
|
||||
}
|
||||
interface ScopePath {
|
||||
property: string;
|
||||
itemIndex: number;
|
||||
}
|
||||
export declare class ValueScopeName extends Name {
|
||||
readonly prefix: string;
|
||||
value?: NameValue;
|
||||
scopePath?: Code;
|
||||
constructor(prefix: string, nameStr: string);
|
||||
setValue(value: NameValue, { property, itemIndex }: ScopePath): void;
|
||||
}
|
||||
interface VSOptions extends ValueScopeOptions {
|
||||
_n: Code;
|
||||
}
|
||||
export declare class ValueScope extends Scope {
|
||||
protected readonly _values: ScopeValues;
|
||||
protected readonly _scope: ScopeStore;
|
||||
readonly opts: VSOptions;
|
||||
constructor(opts: ValueScopeOptions);
|
||||
get(): ScopeStore;
|
||||
name(prefix: string): ValueScopeName;
|
||||
value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName;
|
||||
getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined;
|
||||
scopeRefs(scopeName: Name, values?: ScopeValues | ScopeValueSets): Code;
|
||||
scopeCode(values?: ScopeValues | ScopeValueSets, usedValues?: UsedScopeValues, getCode?: (n: ValueScopeName) => Code | undefined): Code;
|
||||
private _reduceValues;
|
||||
}
|
||||
export {};
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
|
||||
const code_1 = require("./code");
|
||||
class ValueError extends Error {
|
||||
constructor(name) {
|
||||
super(`CodeGen: "code" for ${name} not defined`);
|
||||
this.value = name.value;
|
||||
}
|
||||
}
|
||||
var UsedValueState;
|
||||
(function (UsedValueState) {
|
||||
UsedValueState[UsedValueState["Started"] = 0] = "Started";
|
||||
UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
|
||||
})(UsedValueState = exports.UsedValueState || (exports.UsedValueState = {}));
|
||||
exports.varKinds = {
|
||||
const: new code_1.Name("const"),
|
||||
let: new code_1.Name("let"),
|
||||
var: new code_1.Name("var"),
|
||||
};
|
||||
class Scope {
|
||||
constructor({ prefixes, parent } = {}) {
|
||||
this._names = {};
|
||||
this._prefixes = prefixes;
|
||||
this._parent = parent;
|
||||
}
|
||||
toName(nameOrPrefix) {
|
||||
return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
|
||||
}
|
||||
name(prefix) {
|
||||
return new code_1.Name(this._newName(prefix));
|
||||
}
|
||||
_newName(prefix) {
|
||||
const ng = this._names[prefix] || this._nameGroup(prefix);
|
||||
return `${prefix}${ng.index++}`;
|
||||
}
|
||||
_nameGroup(prefix) {
|
||||
var _a, _b;
|
||||
if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
|
||||
throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
|
||||
}
|
||||
return (this._names[prefix] = { prefix, index: 0 });
|
||||
}
|
||||
}
|
||||
exports.Scope = Scope;
|
||||
class ValueScopeName extends code_1.Name {
|
||||
constructor(prefix, nameStr) {
|
||||
super(nameStr);
|
||||
this.prefix = prefix;
|
||||
}
|
||||
setValue(value, { property, itemIndex }) {
|
||||
this.value = value;
|
||||
this.scopePath = code_1._ `.${new code_1.Name(property)}[${itemIndex}]`;
|
||||
}
|
||||
}
|
||||
exports.ValueScopeName = ValueScopeName;
|
||||
const line = code_1._ `\n`;
|
||||
class ValueScope extends Scope {
|
||||
constructor(opts) {
|
||||
super(opts);
|
||||
this._values = {};
|
||||
this._scope = opts.scope;
|
||||
this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
|
||||
}
|
||||
get() {
|
||||
return this._scope;
|
||||
}
|
||||
name(prefix) {
|
||||
return new ValueScopeName(prefix, this._newName(prefix));
|
||||
}
|
||||
value(nameOrPrefix, value) {
|
||||
var _a;
|
||||
if (value.ref === undefined)
|
||||
throw new Error("CodeGen: ref must be passed in value");
|
||||
const name = this.toName(nameOrPrefix);
|
||||
const { prefix } = name;
|
||||
const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
|
||||
let vs = this._values[prefix];
|
||||
if (vs) {
|
||||
const _name = vs.get(valueKey);
|
||||
if (_name)
|
||||
return _name;
|
||||
}
|
||||
else {
|
||||
vs = this._values[prefix] = new Map();
|
||||
}
|
||||
vs.set(valueKey, name);
|
||||
const s = this._scope[prefix] || (this._scope[prefix] = []);
|
||||
const itemIndex = s.length;
|
||||
s[itemIndex] = value.ref;
|
||||
name.setValue(value, { property: prefix, itemIndex });
|
||||
return name;
|
||||
}
|
||||
getValue(prefix, keyOrRef) {
|
||||
const vs = this._values[prefix];
|
||||
if (!vs)
|
||||
return;
|
||||
return vs.get(keyOrRef);
|
||||
}
|
||||
scopeRefs(scopeName, values = this._values) {
|
||||
return this._reduceValues(values, (name) => {
|
||||
if (name.scopePath === undefined)
|
||||
throw new Error(`CodeGen: name "${name}" has no value`);
|
||||
return code_1._ `${scopeName}${name.scopePath}`;
|
||||
});
|
||||
}
|
||||
scopeCode(values = this._values, usedValues, getCode) {
|
||||
return this._reduceValues(values, (name) => {
|
||||
if (name.value === undefined)
|
||||
throw new Error(`CodeGen: name "${name}" has no value`);
|
||||
return name.value.code;
|
||||
}, usedValues, getCode);
|
||||
}
|
||||
_reduceValues(values, valueCode, usedValues = {}, getCode) {
|
||||
let code = code_1.nil;
|
||||
for (const prefix in values) {
|
||||
const vs = values[prefix];
|
||||
if (!vs)
|
||||
continue;
|
||||
const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
|
||||
vs.forEach((name) => {
|
||||
if (nameSet.has(name))
|
||||
return;
|
||||
nameSet.set(name, UsedValueState.Started);
|
||||
let c = valueCode(name);
|
||||
if (c) {
|
||||
const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
|
||||
code = code_1._ `${code}${def} ${name} = ${c};${this.opts._n}`;
|
||||
}
|
||||
else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
|
||||
code = code_1._ `${code}${c}${this.opts._n}`;
|
||||
}
|
||||
else {
|
||||
throw new ValueError(name);
|
||||
}
|
||||
nameSet.set(name, UsedValueState.Completed);
|
||||
});
|
||||
}
|
||||
return code;
|
||||
}
|
||||
}
|
||||
exports.ValueScope = ValueScope;
|
||||
//# sourceMappingURL=scope.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+38
@@ -0,0 +1,38 @@
|
||||
import type { AddedKeywordDefinition, KeywordErrorCxt, KeywordCxtParams, AnySchemaObject } from "../types";
|
||||
import { SchemaCxt, SchemaObjCxt } from "./index";
|
||||
import { JSONType } from "./rules";
|
||||
import { CodeGen, Code, Name } from "./codegen";
|
||||
import { SubschemaArgs } from "./subschema";
|
||||
export default class KeywordCxt implements KeywordErrorCxt {
|
||||
readonly gen: CodeGen;
|
||||
readonly allErrors?: boolean;
|
||||
readonly keyword: string;
|
||||
readonly data: Name;
|
||||
readonly $data?: string | false;
|
||||
schema: any;
|
||||
readonly schemaValue: Code | number | boolean;
|
||||
readonly schemaCode: Code | number | boolean;
|
||||
readonly schemaType: JSONType[];
|
||||
readonly parentSchema: AnySchemaObject;
|
||||
readonly errsCount?: Name;
|
||||
params: KeywordCxtParams;
|
||||
readonly it: SchemaObjCxt;
|
||||
readonly def: AddedKeywordDefinition;
|
||||
constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string);
|
||||
result(condition: Code, successAction?: () => void, failAction?: () => void): void;
|
||||
pass(condition: Code, failAction?: () => void): void;
|
||||
fail(condition?: Code): void;
|
||||
fail$data(condition: Code): void;
|
||||
error(append?: true): void;
|
||||
$dataError(): void;
|
||||
reset(): void;
|
||||
ok(cond: Code | boolean): void;
|
||||
setParams(obj: KeywordCxtParams, assign?: true): void;
|
||||
block$data(valid: Name, codeBlock: () => void, $dataValid?: Code): void;
|
||||
check$data(valid?: Name, $dataValid?: Code): void;
|
||||
invalid$data(): Code;
|
||||
subschema(appl: SubschemaArgs, valid: Name): SchemaCxt;
|
||||
mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void;
|
||||
mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void;
|
||||
}
|
||||
export declare function getData($data: string, { dataLevel, dataNames, dataPathArr }: SchemaCxt): Code | number;
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getData = void 0;
|
||||
const dataType_1 = require("./validate/dataType");
|
||||
const util_1 = require("./util");
|
||||
const errors_1 = require("./errors");
|
||||
const codegen_1 = require("./codegen");
|
||||
const names_1 = require("./names");
|
||||
const subschema_1 = require("./subschema");
|
||||
class KeywordCxt {
|
||||
constructor(it, def, keyword) {
|
||||
validateKeywordUsage(it, def, keyword);
|
||||
this.gen = it.gen;
|
||||
this.allErrors = it.allErrors;
|
||||
this.keyword = keyword;
|
||||
this.data = it.data;
|
||||
this.schema = it.schema[keyword];
|
||||
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
|
||||
this.schemaValue = util_1.schemaRefOrVal(it, this.schema, keyword, this.$data);
|
||||
this.schemaType = def.schemaType;
|
||||
this.parentSchema = it.schema;
|
||||
this.params = {};
|
||||
this.it = it;
|
||||
this.def = def;
|
||||
if (this.$data) {
|
||||
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
|
||||
}
|
||||
else {
|
||||
this.schemaCode = this.schemaValue;
|
||||
if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
|
||||
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
|
||||
}
|
||||
}
|
||||
if ("code" in def ? def.trackErrors : def.errors !== false) {
|
||||
this.errsCount = it.gen.const("_errs", names_1.default.errors);
|
||||
}
|
||||
}
|
||||
result(condition, successAction, failAction) {
|
||||
this.gen.if(codegen_1.not(condition));
|
||||
if (failAction)
|
||||
failAction();
|
||||
else
|
||||
this.error();
|
||||
if (successAction) {
|
||||
this.gen.else();
|
||||
successAction();
|
||||
if (this.allErrors)
|
||||
this.gen.endIf();
|
||||
}
|
||||
else {
|
||||
if (this.allErrors)
|
||||
this.gen.endIf();
|
||||
else
|
||||
this.gen.else();
|
||||
}
|
||||
}
|
||||
pass(condition, failAction) {
|
||||
this.result(condition, undefined, failAction);
|
||||
}
|
||||
fail(condition) {
|
||||
if (condition === undefined) {
|
||||
this.error();
|
||||
if (!this.allErrors)
|
||||
this.gen.if(false); // this branch will be removed by gen.optimize
|
||||
return;
|
||||
}
|
||||
this.gen.if(condition);
|
||||
this.error();
|
||||
if (this.allErrors)
|
||||
this.gen.endIf();
|
||||
else
|
||||
this.gen.else();
|
||||
}
|
||||
fail$data(condition) {
|
||||
if (!this.$data)
|
||||
return this.fail(condition);
|
||||
const { schemaCode } = this;
|
||||
this.fail(codegen_1._ `${schemaCode} !== undefined && (${codegen_1.or(this.invalid$data(), condition)})`);
|
||||
}
|
||||
error(append) {
|
||||
;
|
||||
(append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error);
|
||||
}
|
||||
$dataError() {
|
||||
errors_1.reportError(this, this.def.$dataError || errors_1.keyword$DataError);
|
||||
}
|
||||
reset() {
|
||||
if (this.errsCount === undefined)
|
||||
throw new Error('add "trackErrors" to keyword definition');
|
||||
errors_1.resetErrorsCount(this.gen, this.errsCount);
|
||||
}
|
||||
ok(cond) {
|
||||
if (!this.allErrors)
|
||||
this.gen.if(cond);
|
||||
}
|
||||
setParams(obj, assign) {
|
||||
if (assign)
|
||||
Object.assign(this.params, obj);
|
||||
else
|
||||
this.params = obj;
|
||||
}
|
||||
block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
|
||||
this.gen.block(() => {
|
||||
this.check$data(valid, $dataValid);
|
||||
codeBlock();
|
||||
});
|
||||
}
|
||||
check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
|
||||
if (!this.$data)
|
||||
return;
|
||||
const { gen, schemaCode, schemaType, def } = this;
|
||||
gen.if(codegen_1.or(codegen_1._ `${schemaCode} === undefined`, $dataValid));
|
||||
if (valid !== codegen_1.nil)
|
||||
gen.assign(valid, true);
|
||||
if (schemaType.length || def.validateSchema) {
|
||||
gen.elseIf(this.invalid$data());
|
||||
this.$dataError();
|
||||
if (valid !== codegen_1.nil)
|
||||
gen.assign(valid, false);
|
||||
}
|
||||
gen.else();
|
||||
}
|
||||
invalid$data() {
|
||||
const { gen, schemaCode, schemaType, def, it } = this;
|
||||
return codegen_1.or(wrong$DataType(), invalid$DataSchema());
|
||||
function wrong$DataType() {
|
||||
if (schemaType.length) {
|
||||
/* istanbul ignore if */
|
||||
if (!(schemaCode instanceof codegen_1.Name))
|
||||
throw new Error("ajv implementation error");
|
||||
const st = Array.isArray(schemaType) ? schemaType : [schemaType];
|
||||
return codegen_1._ `${dataType_1.checkDataTypes(st, schemaCode, it.opts.strict, dataType_1.DataType.Wrong)}`;
|
||||
}
|
||||
return codegen_1.nil;
|
||||
}
|
||||
function invalid$DataSchema() {
|
||||
if (def.validateSchema) {
|
||||
const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone
|
||||
return codegen_1._ `!${validateSchemaRef}(${schemaCode})`;
|
||||
}
|
||||
return codegen_1.nil;
|
||||
}
|
||||
}
|
||||
subschema(appl, valid) {
|
||||
return subschema_1.applySubschema(this.it, appl, valid);
|
||||
}
|
||||
mergeEvaluated(schemaCxt, toName) {
|
||||
const { it, gen } = this;
|
||||
if (!it.opts.unevaluated)
|
||||
return;
|
||||
if (it.props !== true && schemaCxt.props !== undefined) {
|
||||
it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
|
||||
}
|
||||
if (it.items !== true && schemaCxt.items !== undefined) {
|
||||
it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
|
||||
}
|
||||
}
|
||||
mergeValidEvaluated(schemaCxt, valid) {
|
||||
const { it, gen } = this;
|
||||
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
|
||||
gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.default = KeywordCxt;
|
||||
function validSchemaType(schema, schemaType, allowUndefined = false) {
|
||||
// TODO add tests
|
||||
return (!schemaType.length ||
|
||||
schemaType.some((st) => st === "array"
|
||||
? Array.isArray(schema)
|
||||
: st === "object"
|
||||
? schema && typeof schema == "object" && !Array.isArray(schema)
|
||||
: typeof schema == st || (allowUndefined && typeof schema == "undefined")));
|
||||
}
|
||||
function validateKeywordUsage({ schema, opts, self }, def, keyword) {
|
||||
/* istanbul ignore if */
|
||||
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
|
||||
throw new Error("ajv implementation error");
|
||||
}
|
||||
const deps = def.dependencies;
|
||||
if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
|
||||
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
|
||||
}
|
||||
if (def.validateSchema) {
|
||||
const valid = def.validateSchema(schema[keyword]);
|
||||
if (!valid) {
|
||||
const msg = "keyword value is invalid: " + self.errorsText(def.validateSchema.errors);
|
||||
if (opts.validateSchema === "log")
|
||||
self.logger.error(msg);
|
||||
else
|
||||
throw new Error(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
|
||||
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
|
||||
function getData($data, { dataLevel, dataNames, dataPathArr }) {
|
||||
let jsonPointer;
|
||||
let data;
|
||||
if ($data === "")
|
||||
return names_1.default.rootData;
|
||||
if ($data[0] === "/") {
|
||||
if (!JSON_POINTER.test($data))
|
||||
throw new Error(`Invalid JSON-pointer: ${$data}`);
|
||||
jsonPointer = $data;
|
||||
data = names_1.default.rootData;
|
||||
}
|
||||
else {
|
||||
const matches = RELATIVE_JSON_POINTER.exec($data);
|
||||
if (!matches)
|
||||
throw new Error(`Invalid JSON-pointer: ${$data}`);
|
||||
const up = +matches[1];
|
||||
jsonPointer = matches[2];
|
||||
if (jsonPointer === "#") {
|
||||
if (up >= dataLevel)
|
||||
throw new Error(errorMsg("property/index", up));
|
||||
return dataPathArr[dataLevel - up];
|
||||
}
|
||||
if (up > dataLevel)
|
||||
throw new Error(errorMsg("data", up));
|
||||
data = dataNames[dataLevel - up];
|
||||
if (!jsonPointer)
|
||||
return data;
|
||||
}
|
||||
let expr = data;
|
||||
const segments = jsonPointer.split("/");
|
||||
for (const segment of segments) {
|
||||
if (segment) {
|
||||
data = codegen_1._ `${data}${codegen_1.getProperty(util_1.unescapeJsonPointer(segment))}`;
|
||||
expr = codegen_1._ `${expr} && ${data}`;
|
||||
}
|
||||
}
|
||||
return expr;
|
||||
function errorMsg(pointerType, up) {
|
||||
return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
|
||||
}
|
||||
}
|
||||
exports.getData = getData;
|
||||
//# sourceMappingURL=context.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+2
@@ -0,0 +1,2 @@
|
||||
declare const _exports: (a: any, b: any) => boolean;
|
||||
export = _exports;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
// do NOT remove this file - it would break pre-compiled schemas
|
||||
// https://github.com/ajv-validator/ajv/issues/889
|
||||
module.exports = require("fast-deep-equal");
|
||||
//# sourceMappingURL=equal.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"equal.js","sourceRoot":"","sources":["../../lib/compile/equal.js"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,kDAAkD;AAClD,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAA"}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import type { ErrorObject } from "../types";
|
||||
export declare class ValidationError extends Error {
|
||||
readonly errors: Partial<ErrorObject>[];
|
||||
readonly ajv: true;
|
||||
readonly validation: true;
|
||||
constructor(errors: Partial<ErrorObject>[]);
|
||||
}
|
||||
export declare class MissingRefError extends Error {
|
||||
readonly missingRef: string;
|
||||
readonly missingSchema: string;
|
||||
constructor(baseId: string, ref: string, msg?: string);
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.MissingRefError = exports.ValidationError = void 0;
|
||||
const resolve_1 = require("./resolve");
|
||||
class ValidationError extends Error {
|
||||
constructor(errors) {
|
||||
super("validation failed");
|
||||
this.errors = errors;
|
||||
this.ajv = this.validation = true;
|
||||
}
|
||||
}
|
||||
exports.ValidationError = ValidationError;
|
||||
class MissingRefError extends Error {
|
||||
constructor(baseId, ref, msg) {
|
||||
super(msg || `can't resolve reference ${ref} from id ${baseId}`);
|
||||
this.missingRef = resolve_1.resolveUrl(baseId, ref);
|
||||
this.missingSchema = resolve_1.normalizeId(resolve_1.getFullPath(this.missingRef));
|
||||
}
|
||||
}
|
||||
exports.MissingRefError = MissingRefError;
|
||||
module.exports = {
|
||||
ValidationError,
|
||||
MissingRefError,
|
||||
};
|
||||
//# sourceMappingURL=error_classes.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"error_classes.js","sourceRoot":"","sources":["../../lib/compile/error_classes.ts"],"names":[],"mappings":";;;AACA,uCAA8D;AAE9D,MAAa,eAAgB,SAAQ,KAAK;IAKxC,YAAY,MAA8B;QACxC,KAAK,CAAC,mBAAmB,CAAC,CAAA;QAC1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;IACnC,CAAC;CACF;AAVD,0CAUC;AAED,MAAa,eAAgB,SAAQ,KAAK;IAIxC,YAAY,MAAc,EAAE,GAAW,EAAE,GAAY;QACnD,KAAK,CAAC,GAAG,IAAI,2BAA2B,GAAG,YAAY,MAAM,EAAE,CAAC,CAAA;QAChE,IAAI,CAAC,UAAU,GAAG,oBAAU,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QACzC,IAAI,CAAC,aAAa,GAAG,qBAAW,CAAC,qBAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAA;IAChE,CAAC;CACF;AATD,0CASC;AAED,MAAM,CAAC,OAAO,GAAG;IACf,eAAe;IACf,eAAe;CAChB,CAAA"}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import type { KeywordErrorCxt, KeywordErrorDefinition } from "../types";
|
||||
import { CodeGen, Name } from "./codegen";
|
||||
export declare const keywordError: KeywordErrorDefinition;
|
||||
export declare const keyword$DataError: KeywordErrorDefinition;
|
||||
export declare function reportError(cxt: KeywordErrorCxt, error?: KeywordErrorDefinition, overrideAllErrors?: boolean): void;
|
||||
export declare function reportExtraError(cxt: KeywordErrorCxt, error?: KeywordErrorDefinition): void;
|
||||
export declare function resetErrorsCount(gen: CodeGen, errsCount: Name): void;
|
||||
export declare function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }: KeywordErrorCxt): void;
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
|
||||
const codegen_1 = require("./codegen");
|
||||
const names_1 = require("./names");
|
||||
exports.keywordError = {
|
||||
message: ({ keyword }) => codegen_1.str `should pass "${keyword}" keyword validation`,
|
||||
};
|
||||
exports.keyword$DataError = {
|
||||
message: ({ keyword, schemaType }) => schemaType
|
||||
? codegen_1.str `"${keyword}" keyword must be ${schemaType} ($data)`
|
||||
: codegen_1.str `"${keyword}" keyword is invalid ($data)`,
|
||||
};
|
||||
function reportError(cxt, error = exports.keywordError, overrideAllErrors) {
|
||||
const { it } = cxt;
|
||||
const { gen, compositeRule, allErrors } = it;
|
||||
const errObj = errorObjectCode(cxt, error);
|
||||
if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
|
||||
addError(gen, errObj);
|
||||
}
|
||||
else {
|
||||
returnErrors(it, codegen_1._ `[${errObj}]`);
|
||||
}
|
||||
}
|
||||
exports.reportError = reportError;
|
||||
function reportExtraError(cxt, error = exports.keywordError) {
|
||||
const { it } = cxt;
|
||||
const { gen, compositeRule, allErrors } = it;
|
||||
const errObj = errorObjectCode(cxt, error);
|
||||
addError(gen, errObj);
|
||||
if (!(compositeRule || allErrors)) {
|
||||
returnErrors(it, names_1.default.vErrors);
|
||||
}
|
||||
}
|
||||
exports.reportExtraError = reportExtraError;
|
||||
function resetErrorsCount(gen, errsCount) {
|
||||
gen.assign(names_1.default.errors, errsCount);
|
||||
gen.if(codegen_1._ `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign(codegen_1._ `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
|
||||
}
|
||||
exports.resetErrorsCount = resetErrorsCount;
|
||||
function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
|
||||
/* istanbul ignore if */
|
||||
if (errsCount === undefined)
|
||||
throw new Error("ajv implementation error");
|
||||
const err = gen.name("err");
|
||||
gen.forRange("i", errsCount, names_1.default.errors, (i) => {
|
||||
gen.const(err, codegen_1._ `${names_1.default.vErrors}[${i}]`);
|
||||
gen.if(codegen_1._ `${err}.dataPath === undefined`, () => gen.assign(codegen_1._ `${err}.dataPath`, codegen_1.strConcat(names_1.default.dataPath, it.errorPath)));
|
||||
gen.assign(codegen_1._ `${err}.schemaPath`, codegen_1.str `${it.errSchemaPath}/${keyword}`);
|
||||
if (it.opts.verbose) {
|
||||
gen.assign(codegen_1._ `${err}.schema`, schemaValue);
|
||||
gen.assign(codegen_1._ `${err}.data`, data);
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.extendErrors = extendErrors;
|
||||
function addError(gen, errObj) {
|
||||
const err = gen.const("err", errObj);
|
||||
gen.if(codegen_1._ `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, codegen_1._ `[${err}]`), codegen_1._ `${names_1.default.vErrors}.push(${err})`);
|
||||
gen.code(codegen_1._ `${names_1.default.errors}++`);
|
||||
}
|
||||
function returnErrors(it, errs) {
|
||||
const { gen, validateName, schemaEnv } = it;
|
||||
if (schemaEnv.$async) {
|
||||
gen.throw(codegen_1._ `new ${it.ValidationError}(${errs})`);
|
||||
}
|
||||
else {
|
||||
gen.assign(codegen_1._ `${validateName}.errors`, errs);
|
||||
gen.return(false);
|
||||
}
|
||||
}
|
||||
const E = {
|
||||
keyword: new codegen_1.Name("keyword"),
|
||||
schemaPath: new codegen_1.Name("schemaPath"),
|
||||
params: new codegen_1.Name("params"),
|
||||
propertyName: new codegen_1.Name("propertyName"),
|
||||
message: new codegen_1.Name("message"),
|
||||
schema: new codegen_1.Name("schema"),
|
||||
parentSchema: new codegen_1.Name("parentSchema"),
|
||||
// JTD error properties
|
||||
instancePath: new codegen_1.Name("instancePath"),
|
||||
};
|
||||
function errorObjectCode(cxt, error) {
|
||||
const { createErrors, opts } = cxt.it;
|
||||
if (createErrors === false)
|
||||
return codegen_1._ `{}`;
|
||||
return (opts.jtd && !opts.ajvErrors ? jtdErrorObject : ajvErrorObject)(cxt, error);
|
||||
}
|
||||
function jtdErrorObject(cxt, { message }) {
|
||||
const { gen, keyword, it } = cxt;
|
||||
const { errorPath, errSchemaPath, opts } = it;
|
||||
const keyValues = [
|
||||
[E.instancePath, codegen_1.strConcat(names_1.default.dataPath, errorPath)],
|
||||
[E.schemaPath, codegen_1.str `${errSchemaPath}/${keyword}`],
|
||||
];
|
||||
if (opts.messages) {
|
||||
keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
|
||||
}
|
||||
return gen.object(...keyValues);
|
||||
}
|
||||
function ajvErrorObject(cxt, error) {
|
||||
const { gen, keyword, data, schemaValue, it } = cxt;
|
||||
const { topSchemaRef, schemaPath, errorPath, errSchemaPath, propertyName, opts } = it;
|
||||
const { params, message } = error;
|
||||
const keyValues = [
|
||||
[E.keyword, keyword],
|
||||
[names_1.default.dataPath, codegen_1.strConcat(names_1.default.dataPath, errorPath)],
|
||||
[E.schemaPath, codegen_1.str `${errSchemaPath}/${keyword}`],
|
||||
[E.params, typeof params == "function" ? params(cxt) : params || codegen_1._ `{}`],
|
||||
];
|
||||
if (propertyName)
|
||||
keyValues.push([E.propertyName, propertyName]);
|
||||
if (opts.messages) {
|
||||
keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
|
||||
}
|
||||
if (opts.verbose) {
|
||||
keyValues.push([E.schema, schemaValue], [E.parentSchema, codegen_1._ `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
|
||||
}
|
||||
return gen.object(...keyValues);
|
||||
}
|
||||
//# sourceMappingURL=errors.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+76
@@ -0,0 +1,76 @@
|
||||
import type { AnySchema, AnySchemaObject, AnyValidateFunction, EvaluatedProperties, EvaluatedItems } from "../types";
|
||||
import type Ajv from "../core";
|
||||
import type { InstanceOptions } from "../core";
|
||||
import { CodeGen, Name, Code, ValueScopeName } from "./codegen";
|
||||
import { LocalRefs } from "./resolve";
|
||||
import { JSONType } from "./rules";
|
||||
export declare type SchemaRefs = {
|
||||
[Ref in string]?: SchemaEnv | AnySchema;
|
||||
};
|
||||
export interface SchemaCxt {
|
||||
readonly gen: CodeGen;
|
||||
readonly allErrors?: boolean;
|
||||
readonly data: Name;
|
||||
readonly parentData: Name;
|
||||
readonly parentDataProperty: Code | number;
|
||||
readonly dataNames: Name[];
|
||||
readonly dataPathArr: (Code | number)[];
|
||||
readonly dataLevel: number;
|
||||
dataTypes: JSONType[];
|
||||
definedProperties: Set<string>;
|
||||
readonly topSchemaRef: Code;
|
||||
readonly validateName: Name;
|
||||
evaluated?: Name;
|
||||
readonly ValidationError?: Name;
|
||||
readonly schema: AnySchema;
|
||||
readonly schemaEnv: SchemaEnv;
|
||||
readonly rootId: string;
|
||||
baseId: string;
|
||||
readonly schemaPath: Code;
|
||||
readonly errSchemaPath: string;
|
||||
readonly errorPath: Code;
|
||||
readonly propertyName?: Name;
|
||||
readonly compositeRule?: boolean;
|
||||
props?: EvaluatedProperties | Name;
|
||||
items?: EvaluatedItems | Name;
|
||||
jtdDiscriminator?: string;
|
||||
jtdMetadata?: boolean;
|
||||
readonly createErrors?: boolean;
|
||||
readonly opts: InstanceOptions;
|
||||
readonly self: Ajv;
|
||||
}
|
||||
export interface SchemaObjCxt extends SchemaCxt {
|
||||
readonly schema: AnySchemaObject;
|
||||
}
|
||||
interface SchemaEnvArgs {
|
||||
readonly schema: AnySchema;
|
||||
readonly root?: SchemaEnv;
|
||||
readonly baseId?: string;
|
||||
readonly localRefs?: LocalRefs;
|
||||
readonly meta?: boolean;
|
||||
}
|
||||
export declare class SchemaEnv implements SchemaEnvArgs {
|
||||
readonly schema: AnySchema;
|
||||
readonly root: SchemaEnv;
|
||||
baseId: string;
|
||||
localRefs?: LocalRefs;
|
||||
readonly meta?: boolean;
|
||||
readonly $async?: boolean;
|
||||
readonly refs: SchemaRefs;
|
||||
readonly dynamicAnchors: {
|
||||
[Ref in string]?: true;
|
||||
};
|
||||
validate?: AnyValidateFunction;
|
||||
validateName?: ValueScopeName;
|
||||
serialize?: (data: unknown) => string;
|
||||
serializeName?: ValueScopeName;
|
||||
parse?: (data: string) => unknown;
|
||||
parseName?: ValueScopeName;
|
||||
constructor(env: SchemaEnvArgs);
|
||||
}
|
||||
export declare function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv;
|
||||
export declare function resolveRef(this: Ajv, root: SchemaEnv, baseId: string, ref: string): AnySchema | SchemaEnv | undefined;
|
||||
export declare function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void;
|
||||
export declare function resolveSchema(this: Ajv, root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
|
||||
ref: string): SchemaEnv | undefined;
|
||||
export {};
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
|
||||
const codegen_1 = require("./codegen");
|
||||
const error_classes_1 = require("./error_classes");
|
||||
const names_1 = require("./names");
|
||||
const resolve_1 = require("./resolve");
|
||||
const util_1 = require("./util");
|
||||
const validate_1 = require("./validate");
|
||||
const URI = require("uri-js");
|
||||
class SchemaEnv {
|
||||
constructor(env) {
|
||||
var _a;
|
||||
this.refs = {};
|
||||
this.dynamicAnchors = {};
|
||||
let schema;
|
||||
if (typeof env.schema == "object")
|
||||
schema = env.schema;
|
||||
this.schema = env.schema;
|
||||
this.root = env.root || this;
|
||||
this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : resolve_1.normalizeId(schema === null || schema === void 0 ? void 0 : schema.$id);
|
||||
this.localRefs = env.localRefs;
|
||||
this.meta = env.meta;
|
||||
this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
|
||||
this.refs = {};
|
||||
}
|
||||
}
|
||||
exports.SchemaEnv = SchemaEnv;
|
||||
// let codeSize = 0
|
||||
// let nodeCount = 0
|
||||
// Compiles schema in SchemaEnv
|
||||
function compileSchema(sch) {
|
||||
// TODO refactor - remove compilations
|
||||
const _sch = getCompilingSchema.call(this, sch);
|
||||
if (_sch)
|
||||
return _sch;
|
||||
const rootId = resolve_1.getFullPath(sch.root.baseId); // TODO if getFullPath removed 1 tests fails
|
||||
const { es5, lines } = this.opts.code;
|
||||
const { ownProperties } = this.opts;
|
||||
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
|
||||
let _ValidationError;
|
||||
if (sch.$async) {
|
||||
_ValidationError = gen.scopeValue("Error", {
|
||||
ref: error_classes_1.ValidationError,
|
||||
code: codegen_1._ `require("ajv/dist/compile/error_classes").ValidationError`,
|
||||
});
|
||||
}
|
||||
const validateName = gen.scopeName("validate");
|
||||
sch.validateName = validateName;
|
||||
const schemaCxt = {
|
||||
gen,
|
||||
allErrors: this.opts.allErrors,
|
||||
data: names_1.default.data,
|
||||
parentData: names_1.default.parentData,
|
||||
parentDataProperty: names_1.default.parentDataProperty,
|
||||
dataNames: [names_1.default.data],
|
||||
dataPathArr: [codegen_1.nil],
|
||||
dataLevel: 0,
|
||||
dataTypes: [],
|
||||
definedProperties: new Set(),
|
||||
topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
|
||||
? { ref: sch.schema, code: codegen_1.stringify(sch.schema) }
|
||||
: { ref: sch.schema }),
|
||||
validateName,
|
||||
ValidationError: _ValidationError,
|
||||
schema: sch.schema,
|
||||
schemaEnv: sch,
|
||||
rootId,
|
||||
baseId: sch.baseId || rootId,
|
||||
schemaPath: codegen_1.nil,
|
||||
errSchemaPath: this.opts.jtd ? "" : "#",
|
||||
errorPath: codegen_1._ `""`,
|
||||
opts: this.opts,
|
||||
self: this,
|
||||
};
|
||||
let sourceCode;
|
||||
try {
|
||||
this._compilations.add(sch);
|
||||
validate_1.validateFunctionCode(schemaCxt);
|
||||
gen.optimize(this.opts.code.optimize);
|
||||
// gen.optimize(1)
|
||||
const validateCode = gen.toString();
|
||||
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
|
||||
// console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
|
||||
if (this.opts.code.process)
|
||||
sourceCode = this.opts.code.process(sourceCode, sch);
|
||||
// console.log("\n\n\n *** \n", sourceCode)
|
||||
const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
|
||||
const validate = makeValidate(this, this.scope.get());
|
||||
this.scope.value(validateName, { ref: validate });
|
||||
validate.errors = null;
|
||||
validate.schema = sch.schema;
|
||||
validate.schemaEnv = sch;
|
||||
if (sch.$async)
|
||||
validate.$async = true;
|
||||
if (this.opts.code.source === true) {
|
||||
validate.source = { validateName, validateCode, scopeValues: gen._values };
|
||||
}
|
||||
if (this.opts.unevaluated) {
|
||||
const { props, items } = schemaCxt;
|
||||
validate.evaluated = {
|
||||
props: props instanceof codegen_1.Name ? undefined : props,
|
||||
items: items instanceof codegen_1.Name ? undefined : items,
|
||||
dynamicProps: props instanceof codegen_1.Name,
|
||||
dynamicItems: items instanceof codegen_1.Name,
|
||||
};
|
||||
if (validate.source)
|
||||
validate.source.evaluated = codegen_1.stringify(validate.evaluated);
|
||||
}
|
||||
sch.validate = validate;
|
||||
return sch;
|
||||
}
|
||||
catch (e) {
|
||||
delete sch.validate;
|
||||
delete sch.validateName;
|
||||
if (sourceCode)
|
||||
this.logger.error("Error compiling schema, function code:", sourceCode);
|
||||
// console.log("\n\n\n *** \n", sourceCode, this.opts)
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
this._compilations.delete(sch);
|
||||
}
|
||||
}
|
||||
exports.compileSchema = compileSchema;
|
||||
function resolveRef(root, baseId, ref) {
|
||||
var _a;
|
||||
ref = resolve_1.resolveUrl(baseId, ref);
|
||||
const schOrFunc = root.refs[ref];
|
||||
if (schOrFunc)
|
||||
return schOrFunc;
|
||||
let _sch = resolve.call(this, root, ref);
|
||||
if (_sch === undefined) {
|
||||
const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv
|
||||
if (schema)
|
||||
_sch = new SchemaEnv({ schema, root, baseId });
|
||||
}
|
||||
if (_sch === undefined)
|
||||
return;
|
||||
return (root.refs[ref] = inlineOrCompile.call(this, _sch));
|
||||
}
|
||||
exports.resolveRef = resolveRef;
|
||||
function inlineOrCompile(sch) {
|
||||
if (resolve_1.inlineRef(sch.schema, this.opts.inlineRefs))
|
||||
return sch.schema;
|
||||
return sch.validate ? sch : compileSchema.call(this, sch);
|
||||
}
|
||||
// Index of schema compilation in the currently compiled list
|
||||
function getCompilingSchema(schEnv) {
|
||||
for (const sch of this._compilations) {
|
||||
if (sameSchemaEnv(sch, schEnv))
|
||||
return sch;
|
||||
}
|
||||
}
|
||||
exports.getCompilingSchema = getCompilingSchema;
|
||||
function sameSchemaEnv(s1, s2) {
|
||||
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
|
||||
}
|
||||
// resolve and compile the references ($ref)
|
||||
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
|
||||
function resolve(root, // information about the root schema for the current schema
|
||||
ref // reference to resolve
|
||||
) {
|
||||
let sch;
|
||||
while (typeof (sch = this.refs[ref]) == "string")
|
||||
ref = sch;
|
||||
return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
|
||||
}
|
||||
// Resolve schema, its root and baseId
|
||||
function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
|
||||
ref // reference to resolve
|
||||
) {
|
||||
const p = URI.parse(ref);
|
||||
const refPath = resolve_1._getFullPath(p);
|
||||
let baseId = resolve_1.getFullPath(root.baseId);
|
||||
// TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
|
||||
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
|
||||
return getJsonPointer.call(this, p, root);
|
||||
}
|
||||
const id = resolve_1.normalizeId(refPath);
|
||||
const schOrRef = this.refs[id] || this.schemas[id];
|
||||
if (typeof schOrRef == "string") {
|
||||
const sch = resolveSchema.call(this, root, schOrRef);
|
||||
if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
|
||||
return;
|
||||
return getJsonPointer.call(this, p, sch);
|
||||
}
|
||||
if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
|
||||
return;
|
||||
if (!schOrRef.validate)
|
||||
compileSchema.call(this, schOrRef);
|
||||
if (id === resolve_1.normalizeId(ref)) {
|
||||
const { schema } = schOrRef;
|
||||
if (schema.$id)
|
||||
baseId = resolve_1.resolveUrl(baseId, schema.$id);
|
||||
return new SchemaEnv({ schema, root, baseId });
|
||||
}
|
||||
return getJsonPointer.call(this, p, schOrRef);
|
||||
}
|
||||
exports.resolveSchema = resolveSchema;
|
||||
const PREVENT_SCOPE_CHANGE = new Set([
|
||||
"properties",
|
||||
"patternProperties",
|
||||
"enum",
|
||||
"dependencies",
|
||||
"definitions",
|
||||
]);
|
||||
function getJsonPointer(parsedRef, { baseId, schema, root }) {
|
||||
var _a;
|
||||
if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
|
||||
return;
|
||||
for (const part of parsedRef.fragment.slice(1).split("/")) {
|
||||
if (typeof schema == "boolean")
|
||||
return;
|
||||
schema = schema[util_1.unescapeFragment(part)];
|
||||
if (schema === undefined)
|
||||
return;
|
||||
// TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
|
||||
if (!PREVENT_SCOPE_CHANGE.has(part) && typeof schema == "object" && schema.$id) {
|
||||
baseId = resolve_1.resolveUrl(baseId, schema.$id);
|
||||
}
|
||||
}
|
||||
let env;
|
||||
if (typeof schema != "boolean" && schema.$ref && !util_1.schemaHasRulesButRef(schema, this.RULES)) {
|
||||
const $ref = resolve_1.resolveUrl(baseId, schema.$ref);
|
||||
env = resolveSchema.call(this, root, $ref);
|
||||
}
|
||||
// even though resolution failed we need to return SchemaEnv to throw exception
|
||||
// so that compileAsync loads missing schema.
|
||||
env = env || new SchemaEnv({ schema, root, baseId });
|
||||
if (env.schema !== env.root.schema)
|
||||
return env;
|
||||
return undefined;
|
||||
}
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+4
@@ -0,0 +1,4 @@
|
||||
import type Ajv from "../../core";
|
||||
import { SchemaObjectMap } from "./types";
|
||||
import { SchemaEnv } from "..";
|
||||
export default function compileParser(this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap): SchemaEnv;
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const types_1 = require("./types");
|
||||
const __1 = require("..");
|
||||
const codegen_1 = require("../codegen");
|
||||
const error_classes_1 = require("../error_classes");
|
||||
const names_1 = require("../names");
|
||||
const code_1 = require("../../vocabularies/code");
|
||||
const ref_1 = require("../../vocabularies/jtd/ref");
|
||||
const type_1 = require("../../vocabularies/jtd/type");
|
||||
const parseJson_1 = require("../../runtime/parseJson");
|
||||
const util_1 = require("../util");
|
||||
const timestamp_1 = require("../timestamp");
|
||||
const genParse = {
|
||||
elements: parseElements,
|
||||
values: parseValues,
|
||||
discriminator: parseDiscriminator,
|
||||
properties: parseProperties,
|
||||
optionalProperties: parseProperties,
|
||||
enum: parseEnum,
|
||||
type: parseType,
|
||||
ref: parseRef,
|
||||
};
|
||||
function compileParser(sch, definitions) {
|
||||
const _sch = __1.getCompilingSchema.call(this, sch);
|
||||
if (_sch)
|
||||
return _sch;
|
||||
const { es5, lines } = this.opts.code;
|
||||
const { ownProperties } = this.opts;
|
||||
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
|
||||
const parseName = gen.scopeName("parse");
|
||||
const cxt = {
|
||||
self: this,
|
||||
gen,
|
||||
schema: sch.schema,
|
||||
schemaEnv: sch,
|
||||
definitions,
|
||||
data: names_1.default.data,
|
||||
parseName,
|
||||
char: gen.name("c"),
|
||||
};
|
||||
let sourceCode;
|
||||
try {
|
||||
this._compilations.add(sch);
|
||||
sch.parseName = parseName;
|
||||
parserFunction(cxt);
|
||||
gen.optimize(this.opts.code.optimize);
|
||||
const parseFuncCode = gen.toString();
|
||||
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`;
|
||||
const makeParse = new Function(`${names_1.default.scope}`, sourceCode);
|
||||
const parse = makeParse(this.scope.get());
|
||||
this.scope.value(parseName, { ref: parse });
|
||||
sch.parse = parse;
|
||||
}
|
||||
catch (e) {
|
||||
if (sourceCode)
|
||||
this.logger.error("Error compiling parser, function code:", sourceCode);
|
||||
delete sch.parse;
|
||||
delete sch.parseName;
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
this._compilations.delete(sch);
|
||||
}
|
||||
return sch;
|
||||
}
|
||||
exports.default = compileParser;
|
||||
const undef = codegen_1._ `undefined`;
|
||||
function parserFunction(cxt) {
|
||||
const { gen, parseName, char } = cxt;
|
||||
gen.func(parseName, codegen_1._ `${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => {
|
||||
gen.let(names_1.default.data);
|
||||
gen.let(char);
|
||||
gen.assign(codegen_1._ `${parseName}.message`, undef);
|
||||
gen.assign(codegen_1._ `${parseName}.position`, undef);
|
||||
gen.assign(names_1.default.jsonPos, codegen_1._ `${names_1.default.jsonPos} || 0`);
|
||||
gen.const(names_1.default.jsonLen, codegen_1._ `${names_1.default.json}.length`);
|
||||
parseCode(cxt);
|
||||
skipWhitespace(cxt);
|
||||
gen.if(names_1.default.jsonPart, () => {
|
||||
gen.assign(codegen_1._ `${parseName}.position`, names_1.default.jsonPos);
|
||||
gen.return(names_1.default.data);
|
||||
});
|
||||
gen.if(codegen_1._ `${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data));
|
||||
jsonSyntaxError(cxt);
|
||||
});
|
||||
}
|
||||
function parseCode(cxt) {
|
||||
let form;
|
||||
for (const key of types_1.jtdForms) {
|
||||
if (key in cxt.schema) {
|
||||
form = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (form)
|
||||
parseNullable(cxt, genParse[form]);
|
||||
else
|
||||
parseEmpty(cxt);
|
||||
}
|
||||
const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError));
|
||||
function parseNullable(cxt, parseForm) {
|
||||
const { gen, schema, data } = cxt;
|
||||
if (!schema.nullable)
|
||||
return parseForm(cxt);
|
||||
tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null));
|
||||
}
|
||||
function parseElements(cxt) {
|
||||
const { gen, schema, data } = cxt;
|
||||
parseToken(cxt, "[");
|
||||
const ix = gen.let("i", 0);
|
||||
gen.assign(data, codegen_1._ `[]`);
|
||||
parseItems(cxt, "]", () => {
|
||||
const el = gen.let("el");
|
||||
parseCode({ ...cxt, schema: schema.elements, data: el });
|
||||
gen.assign(codegen_1._ `${data}[${ix}++]`, el);
|
||||
});
|
||||
}
|
||||
function parseValues(cxt) {
|
||||
const { gen, schema, data } = cxt;
|
||||
parseToken(cxt, "{");
|
||||
gen.assign(data, codegen_1._ `{}`);
|
||||
parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values));
|
||||
}
|
||||
function parseItems(cxt, endToken, block) {
|
||||
tryParseItems(cxt, endToken, block);
|
||||
parseToken(cxt, endToken);
|
||||
}
|
||||
function tryParseItems(cxt, endToken, block) {
|
||||
const { gen } = cxt;
|
||||
gen.for(codegen_1._ `;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => {
|
||||
block();
|
||||
tryParseToken(cxt, ",", () => gen.break(), hasItem);
|
||||
});
|
||||
function hasItem() {
|
||||
tryParseToken(cxt, endToken, () => { }, jsonSyntaxError);
|
||||
}
|
||||
}
|
||||
function parseKeyValue(cxt, schema) {
|
||||
const { gen } = cxt;
|
||||
const key = gen.let("key");
|
||||
parseString({ ...cxt, data: key });
|
||||
parseToken(cxt, ":");
|
||||
parsePropertyValue(cxt, key, schema);
|
||||
}
|
||||
function parseDiscriminator(cxt) {
|
||||
const { gen, data, schema } = cxt;
|
||||
const { discriminator, mapping } = schema;
|
||||
parseToken(cxt, "{");
|
||||
gen.assign(data, codegen_1._ `{}`);
|
||||
const startPos = gen.const("pos", names_1.default.jsonPos);
|
||||
const value = gen.let("value");
|
||||
const tag = gen.let("tag");
|
||||
tryParseItems(cxt, "}", () => {
|
||||
const key = gen.let("key");
|
||||
parseString({ ...cxt, data: key });
|
||||
parseToken(cxt, ":");
|
||||
gen.if(codegen_1._ `${key} === ${discriminator}`, () => {
|
||||
parseString({ ...cxt, data: tag });
|
||||
gen.assign(codegen_1._ `${data}[${key}]`, tag);
|
||||
gen.break();
|
||||
}, () => parseEmpty({ ...cxt, data: value }) // can be discarded/skipped
|
||||
);
|
||||
});
|
||||
gen.assign(names_1.default.jsonPos, startPos);
|
||||
gen.if(codegen_1._ `${tag} === undefined`);
|
||||
parsingError(cxt, codegen_1.str `discriminator tag not found`);
|
||||
for (const tagValue in mapping) {
|
||||
gen.elseIf(codegen_1._ `${tag} === ${tagValue}`);
|
||||
parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator);
|
||||
}
|
||||
gen.else();
|
||||
parsingError(cxt, codegen_1.str `discriminator value not in schema`);
|
||||
gen.endIf();
|
||||
}
|
||||
function parseProperties(cxt) {
|
||||
const { gen, data } = cxt;
|
||||
parseToken(cxt, "{");
|
||||
gen.assign(data, codegen_1._ `{}`);
|
||||
parseSchemaProperties(cxt);
|
||||
}
|
||||
function parseSchemaProperties(cxt, discriminator) {
|
||||
const { gen, schema, data } = cxt;
|
||||
const { properties, optionalProperties, additionalProperties } = schema;
|
||||
parseItems(cxt, "}", () => {
|
||||
const key = gen.let("key");
|
||||
parseString({ ...cxt, data: key });
|
||||
parseToken(cxt, ":");
|
||||
gen.if(false);
|
||||
parseDefinedProperty(cxt, key, properties);
|
||||
parseDefinedProperty(cxt, key, optionalProperties);
|
||||
if (discriminator) {
|
||||
gen.elseIf(codegen_1._ `${key} === ${discriminator}`);
|
||||
const tag = gen.let("tag");
|
||||
parseString({ ...cxt, data: tag }); // can be discarded, it is already assigned
|
||||
}
|
||||
gen.else();
|
||||
if (additionalProperties) {
|
||||
parseEmpty({ ...cxt, data: codegen_1._ `${data}[${key}]` });
|
||||
}
|
||||
else {
|
||||
parsingError(cxt, codegen_1.str `property ${key} not allowed`);
|
||||
}
|
||||
gen.endIf();
|
||||
});
|
||||
if (properties) {
|
||||
const hasProp = code_1.hasPropFunc(gen);
|
||||
const allProps = codegen_1.and(...Object.keys(properties).map((p) => codegen_1._ `${hasProp}.call(${data}, ${p})`));
|
||||
gen.if(codegen_1.not(allProps), () => parsingError(cxt, codegen_1.str `missing required properties`));
|
||||
}
|
||||
}
|
||||
function parseDefinedProperty(cxt, key, schemas = {}) {
|
||||
const { gen } = cxt;
|
||||
for (const prop in schemas) {
|
||||
gen.elseIf(codegen_1._ `${key} === ${prop}`);
|
||||
parsePropertyValue(cxt, key, schemas[prop]);
|
||||
}
|
||||
}
|
||||
function parsePropertyValue(cxt, key, schema) {
|
||||
parseCode({ ...cxt, schema, data: codegen_1._ `${cxt.data}[${key}]` });
|
||||
}
|
||||
function parseType(cxt) {
|
||||
const { gen, schema, data } = cxt;
|
||||
switch (schema.type) {
|
||||
case "boolean":
|
||||
parseBoolean(cxt);
|
||||
break;
|
||||
case "string":
|
||||
parseString(cxt);
|
||||
break;
|
||||
case "timestamp": {
|
||||
// TODO parse timestamp?
|
||||
parseString(cxt);
|
||||
const vts = util_1.func(gen, timestamp_1.default);
|
||||
gen.if(codegen_1._ `!${vts}(${data})`, () => parsingError(cxt, codegen_1.str `invalid timestamp`));
|
||||
break;
|
||||
}
|
||||
case "float32":
|
||||
case "float64":
|
||||
parseNumber(cxt);
|
||||
break;
|
||||
default: {
|
||||
const [min, max, maxDigits] = type_1.intRange[schema.type];
|
||||
parseNumber(cxt, maxDigits);
|
||||
gen.if(codegen_1._ `${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, codegen_1.str `integer out of range`));
|
||||
}
|
||||
}
|
||||
}
|
||||
function parseString(cxt) {
|
||||
parseToken(cxt, '"');
|
||||
parseWith(cxt, parseJson_1.parseJsonString);
|
||||
}
|
||||
function parseEnum(cxt) {
|
||||
const { gen, data, schema } = cxt;
|
||||
const enumSch = schema.enum;
|
||||
parseToken(cxt, '"');
|
||||
// TODO loopEnum
|
||||
gen.if(false);
|
||||
for (const value of enumSch) {
|
||||
const valueStr = JSON.stringify(value).slice(1); // remove starting quote
|
||||
gen.elseIf(codegen_1._ `${jsonSlice(valueStr.length)} === ${valueStr}`);
|
||||
gen.assign(data, codegen_1.str `${value}`);
|
||||
gen.add(names_1.default.jsonPos, valueStr.length);
|
||||
}
|
||||
gen.else();
|
||||
jsonSyntaxError(cxt);
|
||||
gen.endIf();
|
||||
}
|
||||
function parseNumber(cxt, maxDigits) {
|
||||
const { gen } = cxt;
|
||||
skipWhitespace(cxt);
|
||||
gen.if(codegen_1._ `"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits));
|
||||
}
|
||||
function parseBooleanToken(bool, fail) {
|
||||
return (cxt) => {
|
||||
const { gen, data } = cxt;
|
||||
tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool));
|
||||
};
|
||||
}
|
||||
function parseRef(cxt) {
|
||||
const { gen, self, definitions, schema, schemaEnv } = cxt;
|
||||
const { ref } = schema;
|
||||
const refSchema = definitions[ref];
|
||||
if (!refSchema)
|
||||
throw new error_classes_1.MissingRefError("", ref, `No definition ${ref}`);
|
||||
if (!ref_1.hasRef(refSchema))
|
||||
return parseCode({ ...cxt, schema: refSchema });
|
||||
const { root } = schemaEnv;
|
||||
const sch = compileParser.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
|
||||
partialParse(cxt, getParser(gen, sch), true);
|
||||
}
|
||||
function getParser(gen, sch) {
|
||||
return sch.parse
|
||||
? gen.scopeValue("parse", { ref: sch.parse })
|
||||
: codegen_1._ `${gen.scopeValue("wrapper", { ref: sch })}.parse`;
|
||||
}
|
||||
function parseEmpty(cxt) {
|
||||
parseWith(cxt, parseJson_1.parseJson);
|
||||
}
|
||||
function parseWith(cxt, parseFunc, args) {
|
||||
const f = cxt.gen.scopeValue("func", {
|
||||
ref: parseFunc,
|
||||
code: parseFunc.code,
|
||||
});
|
||||
partialParse(cxt, f, args);
|
||||
}
|
||||
function partialParse(cxt, parseFunc, args) {
|
||||
const { gen, data } = cxt;
|
||||
gen.assign(data, codegen_1._ `${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? codegen_1._ `, ${args}` : codegen_1.nil})`);
|
||||
gen.assign(names_1.default.jsonPos, codegen_1._ `${parseFunc}.position`);
|
||||
gen.if(codegen_1._ `${data} === undefined`, () => parsingError(cxt, codegen_1._ `${parseFunc}.message`));
|
||||
}
|
||||
function parseToken(cxt, tok) {
|
||||
tryParseToken(cxt, tok, jsonSyntaxError);
|
||||
}
|
||||
function tryParseToken(cxt, tok, fail, success) {
|
||||
const { gen } = cxt;
|
||||
const n = tok.length;
|
||||
skipWhitespace(cxt);
|
||||
gen.if(codegen_1._ `${jsonSlice(n)} === ${tok}`, () => {
|
||||
gen.add(names_1.default.jsonPos, n);
|
||||
success === null || success === void 0 ? void 0 : success(cxt);
|
||||
}, () => fail(cxt));
|
||||
}
|
||||
function skipWhitespace({ gen, char: c }) {
|
||||
gen.code(codegen_1._ `while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`);
|
||||
}
|
||||
function jsonSlice(len) {
|
||||
return len === 1
|
||||
? codegen_1._ `${names_1.default.json}[${names_1.default.jsonPos}]`
|
||||
: codegen_1._ `${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`;
|
||||
}
|
||||
function jsonSyntaxError(cxt) {
|
||||
parsingError(cxt, codegen_1._ `"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`);
|
||||
}
|
||||
function parsingError({ gen, parseName }, msg) {
|
||||
gen.assign(codegen_1._ `${parseName}.message`, msg);
|
||||
gen.assign(codegen_1._ `${parseName}.position`, names_1.default.jsonPos);
|
||||
gen.return(undef);
|
||||
}
|
||||
//# sourceMappingURL=parse.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+4
@@ -0,0 +1,4 @@
|
||||
import type Ajv from "../../core";
|
||||
import { SchemaObjectMap } from "./types";
|
||||
import { SchemaEnv } from "..";
|
||||
export default function compileSerializer(this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap): SchemaEnv;
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const types_1 = require("./types");
|
||||
const __1 = require("..");
|
||||
const codegen_1 = require("../codegen");
|
||||
const error_classes_1 = require("../error_classes");
|
||||
const names_1 = require("../names");
|
||||
const code_1 = require("../../vocabularies/code");
|
||||
const ref_1 = require("../../vocabularies/jtd/ref");
|
||||
const quote_1 = require("../../runtime/quote");
|
||||
const genSerialize = {
|
||||
elements: serializeElements,
|
||||
values: serializeValues,
|
||||
discriminator: serializeDiscriminator,
|
||||
properties: serializeProperties,
|
||||
optionalProperties: serializeProperties,
|
||||
enum: serializeString,
|
||||
type: serializeType,
|
||||
ref: serializeRef,
|
||||
};
|
||||
function compileSerializer(sch, definitions) {
|
||||
const _sch = __1.getCompilingSchema.call(this, sch);
|
||||
if (_sch)
|
||||
return _sch;
|
||||
const { es5, lines } = this.opts.code;
|
||||
const { ownProperties } = this.opts;
|
||||
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
|
||||
const serializeName = gen.scopeName("serialize");
|
||||
const cxt = {
|
||||
self: this,
|
||||
gen,
|
||||
schema: sch.schema,
|
||||
schemaEnv: sch,
|
||||
definitions,
|
||||
data: names_1.default.data,
|
||||
};
|
||||
let sourceCode;
|
||||
try {
|
||||
this._compilations.add(sch);
|
||||
sch.serializeName = serializeName;
|
||||
gen.func(serializeName, names_1.default.data, false, () => {
|
||||
gen.let(names_1.default.json, codegen_1.str ``);
|
||||
serializeCode(cxt);
|
||||
gen.return(names_1.default.json);
|
||||
});
|
||||
gen.optimize(this.opts.code.optimize);
|
||||
const serializeFuncCode = gen.toString();
|
||||
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`;
|
||||
const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode);
|
||||
const serialize = makeSerialize(this.scope.get());
|
||||
this.scope.value(serializeName, { ref: serialize });
|
||||
sch.serialize = serialize;
|
||||
}
|
||||
catch (e) {
|
||||
if (sourceCode)
|
||||
this.logger.error("Error compiling serializer, function code:", sourceCode);
|
||||
delete sch.serialize;
|
||||
delete sch.serializeName;
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
this._compilations.delete(sch);
|
||||
}
|
||||
return sch;
|
||||
}
|
||||
exports.default = compileSerializer;
|
||||
function serializeCode(cxt) {
|
||||
let form;
|
||||
for (const key of types_1.jtdForms) {
|
||||
if (key in cxt.schema) {
|
||||
form = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty);
|
||||
}
|
||||
function serializeNullable(cxt, serializeForm) {
|
||||
const { gen, schema, data } = cxt;
|
||||
if (!schema.nullable)
|
||||
return serializeForm(cxt);
|
||||
gen.if(codegen_1._ `${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, codegen_1._ `"null"`), () => serializeForm(cxt));
|
||||
}
|
||||
function serializeElements(cxt) {
|
||||
const { gen, schema, data } = cxt;
|
||||
gen.add(names_1.default.json, codegen_1.str `[`);
|
||||
const first = gen.let("first", true);
|
||||
gen.forOf("el", data, (el) => {
|
||||
addComma(cxt, first);
|
||||
serializeCode({ ...cxt, schema: schema.elements, data: el });
|
||||
});
|
||||
gen.add(names_1.default.json, codegen_1.str `]`);
|
||||
}
|
||||
function serializeValues(cxt) {
|
||||
const { gen, schema, data } = cxt;
|
||||
gen.add(names_1.default.json, codegen_1.str `{`);
|
||||
const first = gen.let("first", true);
|
||||
gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first));
|
||||
gen.add(names_1.default.json, codegen_1.str `}`);
|
||||
}
|
||||
function serializeKeyValue(cxt, key, schema, first) {
|
||||
const { gen, data } = cxt;
|
||||
addComma(cxt, first);
|
||||
serializeString({ ...cxt, data: key });
|
||||
gen.add(names_1.default.json, codegen_1.str `:`);
|
||||
const value = gen.const("value", codegen_1._ `${data}${codegen_1.getProperty(key)}`);
|
||||
serializeCode({ ...cxt, schema, data: value });
|
||||
}
|
||||
function serializeDiscriminator(cxt) {
|
||||
const { gen, schema, data } = cxt;
|
||||
const { discriminator } = schema;
|
||||
gen.add(names_1.default.json, codegen_1.str `{${JSON.stringify(discriminator)}:`);
|
||||
const tag = gen.const("tag", codegen_1._ `${data}${codegen_1.getProperty(discriminator)}`);
|
||||
serializeString({ ...cxt, data: tag });
|
||||
gen.if(false);
|
||||
for (const tagValue in schema.mapping) {
|
||||
gen.elseIf(codegen_1._ `${tag} === ${tagValue}`);
|
||||
const sch = schema.mapping[tagValue];
|
||||
serializeSchemaProperties({ ...cxt, schema: sch }, discriminator);
|
||||
}
|
||||
gen.endIf();
|
||||
gen.add(names_1.default.json, codegen_1.str `}`);
|
||||
}
|
||||
function serializeProperties(cxt) {
|
||||
const { gen } = cxt;
|
||||
gen.add(names_1.default.json, codegen_1.str `{`);
|
||||
serializeSchemaProperties(cxt);
|
||||
gen.add(names_1.default.json, codegen_1.str `}`);
|
||||
}
|
||||
function serializeSchemaProperties(cxt, discriminator) {
|
||||
const { gen, schema, data } = cxt;
|
||||
const { properties, optionalProperties } = schema;
|
||||
const props = keys(properties);
|
||||
const optProps = keys(optionalProperties);
|
||||
const allProps = allProperties(props.concat(optProps));
|
||||
let first = !discriminator;
|
||||
for (const key of props) {
|
||||
serializeProperty(key, properties[key], keyValue(key));
|
||||
}
|
||||
for (const key of optProps) {
|
||||
const value = keyValue(key);
|
||||
gen.if(codegen_1.and(codegen_1._ `${value} !== undefined`, code_1.isOwnProperty(gen, data, key)), () => serializeProperty(key, optionalProperties[key], value));
|
||||
}
|
||||
if (schema.additionalProperties) {
|
||||
gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, gen.let("first", first))));
|
||||
}
|
||||
function keys(ps) {
|
||||
return ps ? Object.keys(ps) : [];
|
||||
}
|
||||
function allProperties(ps) {
|
||||
if (discriminator)
|
||||
ps.push(discriminator);
|
||||
if (new Set(ps).size !== ps.length) {
|
||||
throw new Error("JTD: properties/optionalProperties/disciminator overlap");
|
||||
}
|
||||
return ps;
|
||||
}
|
||||
function keyValue(key) {
|
||||
return gen.const("value", codegen_1._ `${data}${codegen_1.getProperty(key)}`);
|
||||
}
|
||||
function serializeProperty(key, propSchema, value) {
|
||||
if (first)
|
||||
first = false;
|
||||
else
|
||||
gen.add(names_1.default.json, codegen_1.str `,`);
|
||||
gen.add(names_1.default.json, codegen_1.str `${JSON.stringify(key)}:`);
|
||||
serializeCode({ ...cxt, schema: propSchema, data: value });
|
||||
}
|
||||
function isAdditional(key, ps) {
|
||||
return ps.length ? codegen_1.and(...ps.map((p) => codegen_1._ `${key} !== ${p}`)) : true;
|
||||
}
|
||||
}
|
||||
function serializeType(cxt) {
|
||||
const { gen, schema, data } = cxt;
|
||||
switch (schema.type) {
|
||||
case "boolean":
|
||||
gen.add(names_1.default.json, codegen_1._ `${data} ? "true" : "false"`);
|
||||
break;
|
||||
case "string":
|
||||
serializeString(cxt);
|
||||
break;
|
||||
case "timestamp":
|
||||
gen.if(codegen_1._ `${data} instanceof Date`, () => gen.add(names_1.default.json, codegen_1._ `${data}.toISOString()`), () => serializeString(cxt));
|
||||
break;
|
||||
default:
|
||||
serializeNumber(cxt);
|
||||
}
|
||||
}
|
||||
function serializeString({ gen, data }) {
|
||||
gen.add(names_1.default.json, codegen_1._ `${quoteFunc(gen)}(${data})`);
|
||||
}
|
||||
function serializeNumber({ gen, data }) {
|
||||
gen.add(names_1.default.json, codegen_1._ `"" + ${data}`);
|
||||
}
|
||||
function serializeRef(cxt) {
|
||||
const { gen, self, data, definitions, schema, schemaEnv } = cxt;
|
||||
const { ref } = schema;
|
||||
const refSchema = definitions[ref];
|
||||
if (!refSchema)
|
||||
throw new error_classes_1.MissingRefError("", ref, `No definition ${ref}`);
|
||||
if (!ref_1.hasRef(refSchema))
|
||||
return serializeCode({ ...cxt, schema: refSchema });
|
||||
const { root } = schemaEnv;
|
||||
const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
|
||||
gen.add(names_1.default.json, codegen_1._ `${getSerialize(gen, sch)}(${data})`);
|
||||
}
|
||||
function getSerialize(gen, sch) {
|
||||
return sch.serialize
|
||||
? gen.scopeValue("serialize", { ref: sch.serialize })
|
||||
: codegen_1._ `${gen.scopeValue("wrapper", { ref: sch })}.serialize`;
|
||||
}
|
||||
function serializeEmpty({ gen, data }) {
|
||||
gen.add(names_1.default.json, codegen_1._ `JSON.stringify(${data})`);
|
||||
}
|
||||
function addComma({ gen }, first) {
|
||||
gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, codegen_1.str `,`));
|
||||
}
|
||||
function quoteFunc(gen) {
|
||||
return gen.scopeValue("func", {
|
||||
ref: quote_1.default,
|
||||
code: codegen_1._ `require("ajv/dist/runtime/quote").default`,
|
||||
});
|
||||
}
|
||||
//# sourceMappingURL=serialize.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+6
@@ -0,0 +1,6 @@
|
||||
import type { SchemaObject } from "../../types";
|
||||
export declare type SchemaObjectMap = {
|
||||
[Ref in string]?: SchemaObject;
|
||||
};
|
||||
export declare const jtdForms: readonly ["elements", "values", "discriminator", "properties", "optionalProperties", "enum", "type", "ref"];
|
||||
export declare type JTDForm = typeof jtdForms[number];
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.jtdForms = void 0;
|
||||
exports.jtdForms = [
|
||||
"elements",
|
||||
"values",
|
||||
"discriminator",
|
||||
"properties",
|
||||
"optionalProperties",
|
||||
"enum",
|
||||
"type",
|
||||
"ref",
|
||||
];
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/compile/jtd/types.ts"],"names":[],"mappings":";;;AAIa,QAAA,QAAQ,GAAG;IACtB,UAAU;IACV,QAAQ;IACR,eAAe;IACf,YAAY;IACZ,oBAAoB;IACpB,MAAM;IACN,MAAM;IACN,KAAK;CACG,CAAA"}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { Name } from "./codegen";
|
||||
declare const names: {
|
||||
data: Name;
|
||||
valCxt: Name;
|
||||
dataPath: Name;
|
||||
parentData: Name;
|
||||
parentDataProperty: Name;
|
||||
rootData: Name;
|
||||
dynamicAnchors: Name;
|
||||
vErrors: Name;
|
||||
errors: Name;
|
||||
this: Name;
|
||||
self: Name;
|
||||
scope: Name;
|
||||
json: Name;
|
||||
jsonPos: Name;
|
||||
jsonLen: Name;
|
||||
jsonPart: Name;
|
||||
};
|
||||
export default names;
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const codegen_1 = require("./codegen");
|
||||
const names = {
|
||||
// validation function arguments
|
||||
data: new codegen_1.Name("data"),
|
||||
// args passed from referencing schema
|
||||
valCxt: new codegen_1.Name("valCxt"),
|
||||
dataPath: new codegen_1.Name("dataPath"),
|
||||
parentData: new codegen_1.Name("parentData"),
|
||||
parentDataProperty: new codegen_1.Name("parentDataProperty"),
|
||||
rootData: new codegen_1.Name("rootData"),
|
||||
dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
|
||||
// function scoped variables
|
||||
vErrors: new codegen_1.Name("vErrors"),
|
||||
errors: new codegen_1.Name("errors"),
|
||||
this: new codegen_1.Name("this"),
|
||||
// "globals"
|
||||
self: new codegen_1.Name("self"),
|
||||
scope: new codegen_1.Name("scope"),
|
||||
// JTD serialize/parse name for JSON string and position
|
||||
json: new codegen_1.Name("json"),
|
||||
jsonPos: new codegen_1.Name("jsonPos"),
|
||||
jsonLen: new codegen_1.Name("jsonLen"),
|
||||
jsonPart: new codegen_1.Name("jsonPart"),
|
||||
};
|
||||
exports.default = names;
|
||||
//# sourceMappingURL=names.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"names.js","sourceRoot":"","sources":["../../lib/compile/names.ts"],"names":[],"mappings":";;AAAA,uCAA8B;AAE9B,MAAM,KAAK,GAAG;IACZ,gCAAgC;IAChC,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,sCAAsC;IACtC,MAAM,EAAE,IAAI,cAAI,CAAC,QAAQ,CAAC;IAC1B,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC;IAC9B,UAAU,EAAE,IAAI,cAAI,CAAC,YAAY,CAAC;IAClC,kBAAkB,EAAE,IAAI,cAAI,CAAC,oBAAoB,CAAC;IAClD,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC;IAC9B,cAAc,EAAE,IAAI,cAAI,CAAC,gBAAgB,CAAC;IAC1C,4BAA4B;IAC5B,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,MAAM,EAAE,IAAI,cAAI,CAAC,QAAQ,CAAC;IAC1B,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,YAAY;IACZ,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,KAAK,EAAE,IAAI,cAAI,CAAC,OAAO,CAAC;IACxB,wDAAwD;IACxD,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC;CAC/B,CAAA;AAED,kBAAe,KAAK,CAAA"}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import type { AnySchema, AnySchemaObject } from "../types";
|
||||
import type Ajv from "../ajv";
|
||||
import * as URI from "uri-js";
|
||||
export declare type LocalRefs = {
|
||||
[Ref in string]?: AnySchemaObject;
|
||||
};
|
||||
export declare function inlineRef(schema: AnySchema, limit?: boolean | number): boolean;
|
||||
export declare function getFullPath(id?: string, normalize?: boolean): string;
|
||||
export declare function _getFullPath(p: URI.URIComponents): string;
|
||||
export declare function normalizeId(id: string | undefined): string;
|
||||
export declare function resolveUrl(baseId: string, id: string): string;
|
||||
export declare function getSchemaRefs(this: Ajv, schema: AnySchema): LocalRefs;
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
|
||||
const util_1 = require("./util");
|
||||
const equal = require("fast-deep-equal");
|
||||
const traverse = require("json-schema-traverse");
|
||||
const URI = require("uri-js");
|
||||
// TODO refactor to use keyword definitions
|
||||
const SIMPLE_INLINED = new Set([
|
||||
"type",
|
||||
"format",
|
||||
"pattern",
|
||||
"maxLength",
|
||||
"minLength",
|
||||
"maxProperties",
|
||||
"minProperties",
|
||||
"maxItems",
|
||||
"minItems",
|
||||
"maximum",
|
||||
"minimum",
|
||||
"uniqueItems",
|
||||
"multipleOf",
|
||||
"required",
|
||||
"enum",
|
||||
"const",
|
||||
]);
|
||||
function inlineRef(schema, limit = true) {
|
||||
if (typeof schema == "boolean")
|
||||
return true;
|
||||
if (limit === true)
|
||||
return !hasRef(schema);
|
||||
if (!limit)
|
||||
return false;
|
||||
return countKeys(schema) <= limit;
|
||||
}
|
||||
exports.inlineRef = inlineRef;
|
||||
const REF_KEYWORDS = new Set([
|
||||
"$ref",
|
||||
"$recursiveRef",
|
||||
"$recursiveAnchor",
|
||||
"$dynamicRef",
|
||||
"$dynamicAnchor",
|
||||
]);
|
||||
function hasRef(schema) {
|
||||
for (const key in schema) {
|
||||
if (REF_KEYWORDS.has(key))
|
||||
return true;
|
||||
const sch = schema[key];
|
||||
if (Array.isArray(sch) && sch.some(hasRef))
|
||||
return true;
|
||||
if (typeof sch == "object" && hasRef(sch))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function countKeys(schema) {
|
||||
let count = 0;
|
||||
for (const key in schema) {
|
||||
if (key === "$ref")
|
||||
return Infinity;
|
||||
count++;
|
||||
if (SIMPLE_INLINED.has(key))
|
||||
continue;
|
||||
if (typeof schema[key] == "object") {
|
||||
util_1.eachItem(schema[key], (sch) => (count += countKeys(sch)));
|
||||
}
|
||||
if (count === Infinity)
|
||||
return Infinity;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
function getFullPath(id = "", normalize) {
|
||||
if (normalize !== false)
|
||||
id = normalizeId(id);
|
||||
const p = URI.parse(id);
|
||||
return _getFullPath(p);
|
||||
}
|
||||
exports.getFullPath = getFullPath;
|
||||
function _getFullPath(p) {
|
||||
return URI.serialize(p).split("#")[0] + "#";
|
||||
}
|
||||
exports._getFullPath = _getFullPath;
|
||||
const TRAILING_SLASH_HASH = /#\/?$/;
|
||||
function normalizeId(id) {
|
||||
return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
|
||||
}
|
||||
exports.normalizeId = normalizeId;
|
||||
function resolveUrl(baseId, id) {
|
||||
id = normalizeId(id);
|
||||
return URI.resolve(baseId, id);
|
||||
}
|
||||
exports.resolveUrl = resolveUrl;
|
||||
const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
|
||||
function getSchemaRefs(schema) {
|
||||
if (typeof schema == "boolean")
|
||||
return {};
|
||||
const schemaId = normalizeId(schema.$id);
|
||||
const baseIds = { "": schemaId };
|
||||
const pathPrefix = getFullPath(schemaId, false);
|
||||
const localRefs = {};
|
||||
const schemaRefs = new Set();
|
||||
traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
|
||||
if (parentJsonPtr === undefined)
|
||||
return;
|
||||
const fullPath = pathPrefix + jsonPtr;
|
||||
let baseId = baseIds[parentJsonPtr];
|
||||
if (typeof sch.$id == "string")
|
||||
baseId = addRef.call(this, sch.$id);
|
||||
addAnchor.call(this, sch.$anchor);
|
||||
addAnchor.call(this, sch.$dynamicAnchor);
|
||||
baseIds[jsonPtr] = baseId;
|
||||
function addRef(ref) {
|
||||
ref = normalizeId(baseId ? URI.resolve(baseId, ref) : ref);
|
||||
if (schemaRefs.has(ref))
|
||||
throw ambiguos(ref);
|
||||
schemaRefs.add(ref);
|
||||
let schOrRef = this.refs[ref];
|
||||
if (typeof schOrRef == "string")
|
||||
schOrRef = this.refs[schOrRef];
|
||||
if (typeof schOrRef == "object") {
|
||||
checkAmbiguosRef(sch, schOrRef.schema, ref);
|
||||
}
|
||||
else if (ref !== normalizeId(fullPath)) {
|
||||
if (ref[0] === "#") {
|
||||
checkAmbiguosRef(sch, localRefs[ref], ref);
|
||||
localRefs[ref] = sch;
|
||||
}
|
||||
else {
|
||||
this.refs[ref] = fullPath;
|
||||
}
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
function addAnchor(anchor) {
|
||||
if (typeof anchor == "string") {
|
||||
if (!ANCHOR.test(anchor))
|
||||
throw new Error(`invalid anchor "${anchor}"`);
|
||||
addRef.call(this, `#${anchor}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
return localRefs;
|
||||
function checkAmbiguosRef(sch1, sch2, ref) {
|
||||
if (sch2 !== undefined && !equal(sch1, sch2))
|
||||
throw ambiguos(ref);
|
||||
}
|
||||
function ambiguos(ref) {
|
||||
return new Error(`reference "${ref}" resolves to more than one schema`);
|
||||
}
|
||||
}
|
||||
exports.getSchemaRefs = getSchemaRefs;
|
||||
//# sourceMappingURL=resolve.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../lib/compile/resolve.ts"],"names":[],"mappings":";;;AAEA,iCAA+B;AAC/B,yCAAwC;AACxC,iDAAgD;AAChD,8BAA6B;AAK7B,2CAA2C;AAC3C,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC;IAC7B,MAAM;IACN,QAAQ;IACR,SAAS;IACT,WAAW;IACX,WAAW;IACX,eAAe;IACf,eAAe;IACf,UAAU;IACV,UAAU;IACV,SAAS;IACT,SAAS;IACT,aAAa;IACb,YAAY;IACZ,UAAU;IACV,MAAM;IACN,OAAO;CACR,CAAC,CAAA;AAEF,SAAgB,SAAS,CAAC,MAAiB,EAAE,QAA0B,IAAI;IACzE,IAAI,OAAO,MAAM,IAAI,SAAS;QAAE,OAAO,IAAI,CAAA;IAC3C,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;IAC1C,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAA;IACxB,OAAO,SAAS,CAAC,MAAM,CAAC,IAAI,KAAK,CAAA;AACnC,CAAC;AALD,8BAKC;AAED,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC;I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AC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAA;oBAC1C,SAAS,CAAC,GAAG,CAAC,GAAG,GAAG,CAAA;iBACrB;qBAAM;oBACL,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAA;iBAC1B;aACF;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;QAED,SAAS,SAAS,CAAY,MAAe;YAC3C,IAAI,OAAO,MAAM,IAAI,QAAQ,EAAE;gBAC7B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,MAAM,GAAG,CAAC,CAAA;gBACvE,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,MAAM,EAAE,CAAC,CAAA;aAChC;QACH,CAAC;IACH,CAAC,CAAC,CAAA;IAEF,OAAO,SAAS,CAAA;IAEhB,SAAS,gBAAgB,CAAC,IAAe,EAAE,IAA2B,EAAE,GAAW;QACjF,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;YAAE,MAAM,QAAQ,CAAC,GAAG,CAAC,CAAA;IACnE,CAAC;IAED,SAAS,QAAQ,CAAC,GAAW;QAC3B,OAAO,IAAI,KAAK,CAAC,cAAc,GAAG,oCAAoC,CAAC,CAAA;IACzE,CAAC;AACH,CAAC;AArDD,sCAqDC"}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import type { AddedKeywordDefinition } from "../types";
|
||||
declare const _jsonTypes: readonly ["string", "number", "integer", "boolean", "null", "object", "array"];
|
||||
export declare type JSONType = typeof _jsonTypes[number];
|
||||
export declare function isJSONType(x: unknown): x is JSONType;
|
||||
declare type ValidationTypes = {
|
||||
[K in JSONType]: boolean | RuleGroup | undefined;
|
||||
};
|
||||
export interface ValidationRules {
|
||||
rules: RuleGroup[];
|
||||
post: RuleGroup;
|
||||
all: {
|
||||
[Key in string]?: boolean | Rule;
|
||||
};
|
||||
keywords: {
|
||||
[Key in string]?: boolean;
|
||||
};
|
||||
types: ValidationTypes;
|
||||
}
|
||||
export interface RuleGroup {
|
||||
type?: JSONType;
|
||||
rules: Rule[];
|
||||
}
|
||||
export interface Rule {
|
||||
keyword: string;
|
||||
definition: AddedKeywordDefinition;
|
||||
}
|
||||
export declare function getRules(): ValidationRules;
|
||||
export {};
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getRules = exports.isJSONType = void 0;
|
||||
const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
|
||||
const jsonTypes = new Set(_jsonTypes);
|
||||
function isJSONType(x) {
|
||||
return typeof x == "string" && jsonTypes.has(x);
|
||||
}
|
||||
exports.isJSONType = isJSONType;
|
||||
function getRules() {
|
||||
const groups = {
|
||||
number: { type: "number", rules: [] },
|
||||
string: { type: "string", rules: [] },
|
||||
array: { type: "array", rules: [] },
|
||||
object: { type: "object", rules: [] },
|
||||
};
|
||||
return {
|
||||
types: { ...groups, integer: true, boolean: true, null: true },
|
||||
rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
|
||||
post: { rules: [] },
|
||||
all: {},
|
||||
keywords: {},
|
||||
};
|
||||
}
|
||||
exports.getRules = getRules;
|
||||
//# sourceMappingURL=rules.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"rules.js","sourceRoot":"","sources":["../../lib/compile/rules.ts"],"names":[],"mappings":";;;AAEA,MAAM,UAAU,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAU,CAAA;AAIjG,MAAM,SAAS,GAAgB,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;AAElD,SAAgB,UAAU,CAAC,CAAU;IACnC,OAAO,OAAO,CAAC,IAAI,QAAQ,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC;AAFD,gCAEC;AAyBD,SAAgB,QAAQ;IACtB,MAAM,MAAM,GAAgE;QAC1E,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;QACnC,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;QACnC,KAAK,EAAE,EAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAC;QACjC,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;KACpC,CAAA;IACD,OAAO;QACL,KAAK,EAAE,EAAC,GAAG,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAC;QAC5D,KAAK,EAAE,CAAC,EAAC,KAAK,EAAE,EAAE,EAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QAC/E,IAAI,EAAE,EAAC,KAAK,EAAE,EAAE,EAAC;QACjB,GAAG,EAAE,EAAE;QACP,QAAQ,EAAE,EAAE;KACb,CAAA;AACH,CAAC;AAdD,4BAcC"}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import type { AnySchema } from "../types";
|
||||
import type { SchemaObjCxt, SchemaCxt } from "./index";
|
||||
import { Code, Name } from "./codegen";
|
||||
import { JSONType } from "./rules";
|
||||
export declare enum Type {
|
||||
Num = 0,
|
||||
Str = 1
|
||||
}
|
||||
export declare type SubschemaArgs = Partial<{
|
||||
keyword: string;
|
||||
schemaProp: string | number;
|
||||
schema: AnySchema;
|
||||
schemaPath: Code;
|
||||
errSchemaPath: string;
|
||||
topSchemaRef: Code;
|
||||
data: Name | Code;
|
||||
dataProp: Code | string | number;
|
||||
dataTypes: JSONType[];
|
||||
definedProperties: Set<string>;
|
||||
propertyName: Name;
|
||||
dataPropType: Type;
|
||||
jtdDiscriminator: string;
|
||||
jtdMetadata: boolean;
|
||||
compositeRule: true;
|
||||
createErrors: boolean;
|
||||
allErrors: boolean;
|
||||
}>;
|
||||
export declare function applySubschema(it: SchemaObjCxt, appl: SubschemaArgs, valid: Name): SchemaCxt;
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.applySubschema = exports.Type = void 0;
|
||||
const validate_1 = require("./validate");
|
||||
const util_1 = require("./util");
|
||||
const codegen_1 = require("./codegen");
|
||||
var Type;
|
||||
(function (Type) {
|
||||
Type[Type["Num"] = 0] = "Num";
|
||||
Type[Type["Str"] = 1] = "Str";
|
||||
})(Type = exports.Type || (exports.Type = {}));
|
||||
function applySubschema(it, appl, valid) {
|
||||
const subschema = getSubschema(it, appl);
|
||||
extendSubschemaData(subschema, it, appl);
|
||||
extendSubschemaMode(subschema, appl);
|
||||
const nextContext = { ...it, ...subschema, items: undefined, props: undefined };
|
||||
validate_1.subschemaCode(nextContext, valid);
|
||||
return nextContext;
|
||||
}
|
||||
exports.applySubschema = applySubschema;
|
||||
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
|
||||
if (keyword !== undefined && schema !== undefined) {
|
||||
throw new Error('both "keyword" and "schema" passed, only one allowed');
|
||||
}
|
||||
if (keyword !== undefined) {
|
||||
const sch = it.schema[keyword];
|
||||
return schemaProp === undefined
|
||||
? {
|
||||
schema: sch,
|
||||
schemaPath: codegen_1._ `${it.schemaPath}${codegen_1.getProperty(keyword)}`,
|
||||
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
|
||||
}
|
||||
: {
|
||||
schema: sch[schemaProp],
|
||||
schemaPath: codegen_1._ `${it.schemaPath}${codegen_1.getProperty(keyword)}${codegen_1.getProperty(schemaProp)}`,
|
||||
errSchemaPath: `${it.errSchemaPath}/${keyword}/${util_1.escapeFragment(schemaProp)}`,
|
||||
};
|
||||
}
|
||||
if (schema !== undefined) {
|
||||
if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
|
||||
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
|
||||
}
|
||||
return {
|
||||
schema,
|
||||
schemaPath,
|
||||
topSchemaRef,
|
||||
errSchemaPath,
|
||||
};
|
||||
}
|
||||
throw new Error('either "keyword" or "schema" must be passed');
|
||||
}
|
||||
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
|
||||
if (data !== undefined && dataProp !== undefined) {
|
||||
throw new Error('both "data" and "dataProp" passed, only one allowed');
|
||||
}
|
||||
const { gen } = it;
|
||||
if (dataProp !== undefined) {
|
||||
const { errorPath, dataPathArr, opts } = it;
|
||||
const nextData = gen.let("data", codegen_1._ `${it.data}${codegen_1.getProperty(dataProp)}`, true);
|
||||
dataContextProps(nextData);
|
||||
subschema.errorPath = codegen_1.str `${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`;
|
||||
subschema.parentDataProperty = codegen_1._ `${dataProp}`;
|
||||
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
|
||||
}
|
||||
if (data !== undefined) {
|
||||
const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once?
|
||||
dataContextProps(nextData);
|
||||
if (propertyName !== undefined)
|
||||
subschema.propertyName = propertyName;
|
||||
// TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
|
||||
}
|
||||
if (dataTypes)
|
||||
subschema.dataTypes = dataTypes;
|
||||
function dataContextProps(_nextData) {
|
||||
subschema.data = _nextData;
|
||||
subschema.dataLevel = it.dataLevel + 1;
|
||||
subschema.dataTypes = [];
|
||||
it.definedProperties = new Set();
|
||||
subschema.parentData = it.data;
|
||||
subschema.dataNames = [...it.dataNames, _nextData];
|
||||
}
|
||||
}
|
||||
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
|
||||
if (compositeRule !== undefined)
|
||||
subschema.compositeRule = compositeRule;
|
||||
if (createErrors !== undefined)
|
||||
subschema.createErrors = createErrors;
|
||||
if (allErrors !== undefined)
|
||||
subschema.allErrors = allErrors;
|
||||
subschema.jtdDiscriminator = jtdDiscriminator; // not inherited
|
||||
subschema.jtdMetadata = jtdMetadata; // not inherited
|
||||
}
|
||||
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
|
||||
// let path
|
||||
if (dataProp instanceof codegen_1.Name) {
|
||||
const isNumber = dataPropType === Type.Num;
|
||||
return jsPropertySyntax
|
||||
? isNumber
|
||||
? codegen_1._ `"[" + ${dataProp} + "]"`
|
||||
: codegen_1._ `"['" + ${dataProp} + "']"`
|
||||
: isNumber
|
||||
? codegen_1._ `"/" + ${dataProp}`
|
||||
: codegen_1._ `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer
|
||||
}
|
||||
return jsPropertySyntax ? codegen_1.getProperty(dataProp).toString() : "/" + util_1.escapeJsonPointer(dataProp);
|
||||
}
|
||||
//# sourceMappingURL=subschema.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"subschema.js","sourceRoot":"","sources":["../../lib/compile/subschema.ts"],"names":[],"mappings":";;;AAEA,yCAAwC;AACxC,iCAAwD;AACxD,uCAAyD;AAyBzD,IAAY,IAGX;AAHD,WAAY,IAAI;IACd,6BAAG,CAAA;IACH,6BAAG,CAAA;AACL,CAAC,EAHW,IAAI,GAAJ,YAAI,KAAJ,YAAI,QAGf;AAsBD,SAAgB,cAAc,CAAC,EAAgB,EAAE,IAAmB,EAAE,KAAW;IAC/E,MAAM,SAAS,GAAG,YAAY,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;IACxC,mBAAmB,CAAC,SAAS,EAAE,EAAE,EAAE,IAAI,CAAC,CAAA;IACxC,mBAAmB,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;IACp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AAY,KAAK,IAAI,CAAC,GAAG,CAAA;QAC1C,OAAO,gBAAgB;YACrB,CAAC,CAAC,QAAQ;gBACR,CAAC,CAAC,WAAC,CAAA,SAAS,QAAQ,QAAQ;gBAC5B,CAAC,CAAC,WAAC,CAAA,UAAU,QAAQ,SAAS;YAChC,CAAC,CAAC,QAAQ;gBACV,CAAC,CAAC,WAAC,CAAA,SAAS,QAAQ,EAAE;gBACtB,CAAC,CAAC,WAAC,CAAA,SAAS,QAAQ,4CAA4C,CAAA,CAAC,sCAAsC;KAC1G;IACD,OAAO,gBAAgB,CAAC,CAAC,CAAC,qBAAW,CAAC,QAAQ,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,wBAAiB,CAAC,QAAQ,CAAC,CAAA;AAChG,CAAC"}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
declare function validTimestamp(str: string): boolean;
|
||||
declare namespace validTimestamp {
|
||||
var code: import("./codegen/code")._Code;
|
||||
}
|
||||
export default validTimestamp;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const codegen_1 = require("./codegen");
|
||||
const DATE_TIME = /^(\d\d\d\d)-(\d\d)-(\d\d)(?:t|\s)(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i;
|
||||
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
function validTimestamp(str) {
|
||||
// http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
const matches = DATE_TIME.exec(str);
|
||||
if (!matches)
|
||||
return false;
|
||||
const y = +matches[1];
|
||||
const m = +matches[2];
|
||||
const d = +matches[3];
|
||||
const hr = +matches[4];
|
||||
const min = +matches[5];
|
||||
const sec = +matches[6];
|
||||
const tzH = +(matches[7] || 0);
|
||||
const tzM = +(matches[8] || 0);
|
||||
return (m >= 1 &&
|
||||
m <= 12 &&
|
||||
d >= 1 &&
|
||||
(d <= DAYS[m] ||
|
||||
// leap year: https://tools.ietf.org/html/rfc3339#appendix-C
|
||||
(m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))) &&
|
||||
((hr <= 23 && min <= 59 && sec <= 59) ||
|
||||
// leap second
|
||||
(hr - tzH === 23 && min - tzM === 59 && sec === 60)));
|
||||
}
|
||||
exports.default = validTimestamp;
|
||||
validTimestamp.code = codegen_1._ `require("ajv/dist/compile/timestamp").default`;
|
||||
//# sourceMappingURL=timestamp.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"timestamp.js","sourceRoot":"","sources":["../../lib/compile/timestamp.ts"],"names":[],"mappings":";;AAAA,uCAA2B;AAE3B,MAAM,SAAS,GAAG,gGAAgG,CAAA;AAClH,MAAM,IAAI,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAA;AAEhE,SAAwB,cAAc,CAAC,GAAW;IAChD,iDAAiD;IACjD,MAAM,OAAO,GAAoB,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IACpD,IAAI,CAAC,OAAO;QAAE,OAAO,KAAK,CAAA;IAC1B,MAAM,CAAC,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC7B,MAAM,CAAC,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC7B,MAAM,CAAC,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC7B,MAAM,EAAE,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC9B,MAAM,GAAG,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC/B,MAAM,GAAG,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC/B,MAAM,GAAG,GAAW,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;IACtC,MAAM,GAAG,GAAW,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;IACtC,OAAO,CACL,CAAC,IAAI,CAAC;QACN,CAAC,IAAI,EAAE;QACP,CAAC,IAAI,CAAC;QACN,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;YACX,4DAA4D;YAC5D,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACzE,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,CAAC;YACnC,cAAc;YACd,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,IAAI,GAAG,GAAG,GAAG,KAAK,EAAE,IAAI,GAAG,KAAK,EAAE,CAAC,CAAC,CACvD,CAAA;AACH,CAAC;AAvBD,iCAuBC;AAED,cAAc,CAAC,IAAI,GAAG,WAAC,CAAA,+CAA+C,CAAA"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export default function ucs2length(str: string): number;
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
// https://mathiasbynens.be/notes/javascript-encoding
|
||||
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
|
||||
function ucs2length(str) {
|
||||
const len = str.length;
|
||||
let length = 0;
|
||||
let pos = 0;
|
||||
let value;
|
||||
while (pos < len) {
|
||||
length++;
|
||||
value = str.charCodeAt(pos++);
|
||||
if (value >= 0xd800 && value <= 0xdbff && pos < len) {
|
||||
// high surrogate, and there is a next character
|
||||
value = str.charCodeAt(pos);
|
||||
if ((value & 0xfc00) === 0xdc00)
|
||||
pos++; // low surrogate
|
||||
}
|
||||
}
|
||||
return length;
|
||||
}
|
||||
exports.default = ucs2length;
|
||||
//# sourceMappingURL=ucs2length.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ucs2length.js","sourceRoot":"","sources":["../../lib/compile/ucs2length.ts"],"names":[],"mappings":";;AAAA,qDAAqD;AACrD,iEAAiE;AACjE,SAAwB,UAAU,CAAC,GAAW;IAC5C,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAA;IACtB,IAAI,MAAM,GAAG,CAAC,CAAA;IACd,IAAI,GAAG,GAAG,CAAC,CAAA;IACX,IAAI,KAAa,CAAA;IACjB,OAAO,GAAG,GAAG,GAAG,EAAE;QAChB,MAAM,EAAE,CAAA;QACR,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAA;QAC7B,IAAI,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,MAAM,IAAI,GAAG,GAAG,GAAG,EAAE;YACnD,gDAAgD;YAChD,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;YAC3B,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,MAAM;gBAAE,GAAG,EAAE,CAAA,CAAC,gBAAgB;SACxD;KACF;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAfD,6BAeC"}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import type { AnySchema, EvaluatedProperties, EvaluatedItems } from "../types";
|
||||
import type { SchemaCxt, SchemaObjCxt } from ".";
|
||||
import { Code, Name, CodeGen } from "./codegen";
|
||||
import type { Rule, ValidationRules } from "./rules";
|
||||
export declare function toHash<T extends string = string>(arr: T[]): {
|
||||
[K in T]?: true;
|
||||
};
|
||||
export declare function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void;
|
||||
export declare function checkUnknownRules(it: SchemaCxt, schema?: AnySchema): void;
|
||||
export declare function schemaHasRules(schema: AnySchema, rules: {
|
||||
[Key in string]?: boolean | Rule;
|
||||
}): boolean;
|
||||
export declare function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean;
|
||||
export declare function schemaRefOrVal({ topSchemaRef, schemaPath }: SchemaObjCxt, schema: unknown, keyword: string, $data?: string | false): Code | number | boolean;
|
||||
export declare function unescapeFragment(str: string): string;
|
||||
export declare function escapeFragment(str: string | number): string;
|
||||
export declare function escapeJsonPointer(str: string | number): string;
|
||||
export declare function unescapeJsonPointer(str: string): string;
|
||||
export declare function eachItem<T>(xs: T | T[], f: (x: T) => void): void;
|
||||
declare type SomeEvaluated = EvaluatedProperties | EvaluatedItems;
|
||||
declare type MergeEvaluatedFunc<T extends SomeEvaluated> = (gen: CodeGen, from: Name | T, to: Name | Exclude<T, true> | undefined, toName?: typeof Name) => Name | T;
|
||||
interface MergeEvaluated {
|
||||
props: MergeEvaluatedFunc<EvaluatedProperties>;
|
||||
items: MergeEvaluatedFunc<EvaluatedItems>;
|
||||
}
|
||||
export declare const mergeEvaluated: MergeEvaluated;
|
||||
export declare function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name;
|
||||
export declare function setEvaluated(gen: CodeGen, props: Name, ps: {
|
||||
[K in string]?: true;
|
||||
}): void;
|
||||
export declare function func(gen: CodeGen, f: {
|
||||
code: Code;
|
||||
}): Name;
|
||||
export {};
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.func = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
|
||||
const codegen_1 = require("./codegen");
|
||||
const validate_1 = require("./validate");
|
||||
// TODO refactor to use Set
|
||||
function toHash(arr) {
|
||||
const hash = {};
|
||||
for (const item of arr)
|
||||
hash[item] = true;
|
||||
return hash;
|
||||
}
|
||||
exports.toHash = toHash;
|
||||
function alwaysValidSchema(it, schema) {
|
||||
if (typeof schema == "boolean")
|
||||
return schema;
|
||||
if (Object.keys(schema).length === 0)
|
||||
return true;
|
||||
checkUnknownRules(it, schema);
|
||||
return !schemaHasRules(schema, it.self.RULES.all);
|
||||
}
|
||||
exports.alwaysValidSchema = alwaysValidSchema;
|
||||
function checkUnknownRules(it, schema = it.schema) {
|
||||
const { opts, self } = it;
|
||||
if (!opts.strict)
|
||||
return;
|
||||
if (typeof schema === "boolean")
|
||||
return;
|
||||
const rules = self.RULES.keywords;
|
||||
for (const key in schema) {
|
||||
if (!rules[key])
|
||||
validate_1.checkStrictMode(it, `unknown keyword: "${key}"`);
|
||||
}
|
||||
}
|
||||
exports.checkUnknownRules = checkUnknownRules;
|
||||
function schemaHasRules(schema, rules) {
|
||||
if (typeof schema == "boolean")
|
||||
return !schema;
|
||||
for (const key in schema)
|
||||
if (rules[key])
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
exports.schemaHasRules = schemaHasRules;
|
||||
function schemaHasRulesButRef(schema, RULES) {
|
||||
if (typeof schema == "boolean")
|
||||
return !schema;
|
||||
for (const key in schema)
|
||||
if (key !== "$ref" && RULES.all[key])
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
exports.schemaHasRulesButRef = schemaHasRulesButRef;
|
||||
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
|
||||
if (!$data) {
|
||||
if (typeof schema == "number" || typeof schema == "boolean")
|
||||
return schema;
|
||||
if (typeof schema == "string")
|
||||
return codegen_1._ `${schema}`;
|
||||
}
|
||||
return codegen_1._ `${topSchemaRef}${schemaPath}${codegen_1.getProperty(keyword)}`;
|
||||
}
|
||||
exports.schemaRefOrVal = schemaRefOrVal;
|
||||
function unescapeFragment(str) {
|
||||
return unescapeJsonPointer(decodeURIComponent(str));
|
||||
}
|
||||
exports.unescapeFragment = unescapeFragment;
|
||||
function escapeFragment(str) {
|
||||
return encodeURIComponent(escapeJsonPointer(str));
|
||||
}
|
||||
exports.escapeFragment = escapeFragment;
|
||||
function escapeJsonPointer(str) {
|
||||
if (typeof str == "number")
|
||||
return `${str}`;
|
||||
return str.replace(/~/g, "~0").replace(/\//g, "~1");
|
||||
}
|
||||
exports.escapeJsonPointer = escapeJsonPointer;
|
||||
function unescapeJsonPointer(str) {
|
||||
return str.replace(/~1/g, "/").replace(/~0/g, "~");
|
||||
}
|
||||
exports.unescapeJsonPointer = unescapeJsonPointer;
|
||||
function eachItem(xs, f) {
|
||||
if (Array.isArray(xs)) {
|
||||
for (const x of xs)
|
||||
f(x);
|
||||
}
|
||||
else {
|
||||
f(xs);
|
||||
}
|
||||
}
|
||||
exports.eachItem = eachItem;
|
||||
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
|
||||
return (gen, from, to, toName) => {
|
||||
const res = to === undefined
|
||||
? from
|
||||
: to instanceof codegen_1.Name
|
||||
? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
|
||||
: from instanceof codegen_1.Name
|
||||
? (mergeToName(gen, to, from), from)
|
||||
: mergeValues(from, to);
|
||||
return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
|
||||
};
|
||||
}
|
||||
exports.mergeEvaluated = {
|
||||
props: makeMergeEvaluated({
|
||||
mergeNames: (gen, from, to) => gen.if(codegen_1._ `${to} !== true && ${from} !== undefined`, () => {
|
||||
gen.if(codegen_1._ `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, codegen_1._ `${to} || {}`).code(codegen_1._ `Object.assign(${to}, ${from})`));
|
||||
}),
|
||||
mergeToName: (gen, from, to) => gen.if(codegen_1._ `${to} !== true`, () => {
|
||||
if (from === true) {
|
||||
gen.assign(to, true);
|
||||
}
|
||||
else {
|
||||
gen.assign(to, codegen_1._ `${to} || {}`);
|
||||
setEvaluated(gen, to, from);
|
||||
}
|
||||
}),
|
||||
mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
|
||||
resultToName: evaluatedPropsToName,
|
||||
}),
|
||||
items: makeMergeEvaluated({
|
||||
mergeNames: (gen, from, to) => gen.if(codegen_1._ `${to} !== true && ${from} !== undefined`, () => gen.assign(to, codegen_1._ `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
|
||||
mergeToName: (gen, from, to) => gen.if(codegen_1._ `${to} !== true`, () => gen.assign(to, from === true ? true : codegen_1._ `${to} > ${from} ? ${to} : ${from}`)),
|
||||
mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
|
||||
resultToName: (gen, items) => gen.var("items", items),
|
||||
}),
|
||||
};
|
||||
function evaluatedPropsToName(gen, ps) {
|
||||
if (ps === true)
|
||||
return gen.var("props", true);
|
||||
const props = gen.var("props", codegen_1._ `{}`);
|
||||
if (ps !== undefined)
|
||||
setEvaluated(gen, props, ps);
|
||||
return props;
|
||||
}
|
||||
exports.evaluatedPropsToName = evaluatedPropsToName;
|
||||
function setEvaluated(gen, props, ps) {
|
||||
Object.keys(ps).forEach((p) => gen.assign(codegen_1._ `${props}${codegen_1.getProperty(p)}`, true));
|
||||
}
|
||||
exports.setEvaluated = setEvaluated;
|
||||
function func(gen, f) {
|
||||
return gen.scopeValue("func", {
|
||||
ref: f,
|
||||
code: f.code,
|
||||
});
|
||||
}
|
||||
exports.func = func;
|
||||
//# sourceMappingURL=util.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
import type { AnySchemaObject } from "../../types";
|
||||
import type { SchemaObjCxt } from "..";
|
||||
import type { JSONType, RuleGroup, Rule } from "../rules";
|
||||
export declare function schemaHasRulesForType({ schema, self }: SchemaObjCxt, type: JSONType): boolean | undefined;
|
||||
export declare function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean;
|
||||
export declare function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined;
|
||||
Generated
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
|
||||
function schemaHasRulesForType({ schema, self }, type) {
|
||||
const group = self.RULES.types[type];
|
||||
return group && group !== true && shouldUseGroup(schema, group);
|
||||
}
|
||||
exports.schemaHasRulesForType = schemaHasRulesForType;
|
||||
function shouldUseGroup(schema, group) {
|
||||
return group.rules.some((rule) => shouldUseRule(schema, rule));
|
||||
}
|
||||
exports.shouldUseGroup = shouldUseGroup;
|
||||
function shouldUseRule(schema, rule) {
|
||||
var _a;
|
||||
return (schema[rule.keyword] !== undefined ||
|
||||
((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
|
||||
}
|
||||
exports.shouldUseRule = shouldUseRule;
|
||||
//# sourceMappingURL=applicability.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"applicability.js","sourceRoot":"","sources":["../../../lib/compile/validate/applicability.ts"],"names":[],"mappings":";;;AAIA,SAAgB,qBAAqB,CACnC,EAAC,MAAM,EAAE,IAAI,EAAe,EAC5B,IAAc;IAEd,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IACpC,OAAO,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI,cAAc,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;AACjE,CAAC;AAND,sDAMC;AAED,SAAgB,cAAc,CAAC,MAAuB,EAAE,KAAgB;IACtE,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA;AAChE,CAAC;AAFD,wCAEC;AAED,SAAgB,aAAa,CAAC,MAAuB,EAAE,IAAU;;IAC/D,OAAO,CACL,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,SAAS;SAClC,MAAA,IAAI,CAAC,UAAU,CAAC,UAAU,0CAAE,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC,CAAA,CACrE,CAAA;AACH,CAAC;AALD,sCAKC"}
|
||||
Generated
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
import type { SchemaCxt } from "..";
|
||||
import { Name } from "../codegen";
|
||||
export declare function topBoolOrEmptySchema(it: SchemaCxt): void;
|
||||
export declare function boolOrEmptySchema(it: SchemaCxt, valid: Name): void;
|
||||
Generated
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
|
||||
const errors_1 = require("../errors");
|
||||
const codegen_1 = require("../codegen");
|
||||
const names_1 = require("../names");
|
||||
const boolError = {
|
||||
message: "boolean schema is false",
|
||||
};
|
||||
function topBoolOrEmptySchema(it) {
|
||||
const { gen, schema, validateName } = it;
|
||||
if (schema === false) {
|
||||
falseSchemaError(it, false);
|
||||
}
|
||||
else if (typeof schema == "object" && schema.$async === true) {
|
||||
gen.return(names_1.default.data);
|
||||
}
|
||||
else {
|
||||
gen.assign(codegen_1._ `${validateName}.errors`, null);
|
||||
gen.return(true);
|
||||
}
|
||||
}
|
||||
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
|
||||
function boolOrEmptySchema(it, valid) {
|
||||
const { gen, schema } = it;
|
||||
if (schema === false) {
|
||||
gen.var(valid, false); // TODO var
|
||||
falseSchemaError(it);
|
||||
}
|
||||
else {
|
||||
gen.var(valid, true); // TODO var
|
||||
}
|
||||
}
|
||||
exports.boolOrEmptySchema = boolOrEmptySchema;
|
||||
function falseSchemaError(it, overrideAllErrors) {
|
||||
const { gen, data } = it;
|
||||
// TODO maybe some other interface should be used for non-keyword validation errors...
|
||||
const cxt = {
|
||||
gen,
|
||||
keyword: "false schema",
|
||||
data,
|
||||
schema: false,
|
||||
schemaCode: false,
|
||||
schemaValue: false,
|
||||
params: {},
|
||||
it,
|
||||
};
|
||||
errors_1.reportError(cxt, boolError, overrideAllErrors);
|
||||
}
|
||||
//# sourceMappingURL=boolSchema.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"boolSchema.js","sourceRoot":"","sources":["../../../lib/compile/validate/boolSchema.ts"],"names":[],"mappings":";;;AAEA,sCAAqC;AACrC,wCAAkC;AAClC,oCAAwB;AAExB,MAAM,SAAS,GAA2B;IACxC,OAAO,EAAE,yBAAyB;CACnC,CAAA;AAED,SAAgB,oBAAoB,CAAC,EAAa;IAChD,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAC,GAAG,EAAE,CAAA;IACtC,IAAI,MAAM,KAAK,KAAK,EAAE;QACpB,gBAAgB,CAAC,EAAE,EAAE,KAAK,CAAC,CAAA;KAC5B;SAAM,IAAI,OAAO,MAAM,IAAI,QAAQ,IAAI,MAAM,CAAC,MAAM,KAAK,IAAI,EAAE;QAC9D,GAAG,CAAC,MAAM,CAAC,eAAC,CAAC,IAAI,CAAC,CAAA;KACnB;SAAM;QACL,GAAG,CAAC,MAAM,CAAC,WAAC,CAAA,GAAG,YAAY,SAAS,EAAE,IAAI,CAAC,CAAA;QAC3C,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;KACjB;AACH,CAAC;AAVD,oDAUC;AAED,SAAgB,iBAAiB,CAAC,EAAa,EAAE,KAAW;IAC1D,MAAM,EAAC,GAAG,EAAE,MAAM,EAAC,GAAG,EAAE,CAAA;IACxB,IAAI,MAAM,KAAK,KAAK,EAAE;QACpB,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA,CAAC,WAAW;QACjC,gBAAgB,CAAC,EAAE,CAAC,CAAA;KACrB;SAAM;QACL,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA,CAAC,WAAW;KACjC;AACH,CAAC;AARD,8CAQC;AAED,SAAS,gBAAgB,CAAC,EAAa,EAAE,iBAA2B;IAClE,MAAM,EAAC,GAAG,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;IACtB,sFAAsF;IACtF,MAAM,GAAG,GAAoB;QAC3B,GAAG;QACH,OAAO,EAAE,cAAc;QACvB,IAAI;QACJ,MAAM,EAAE,KAAK;QACb,UAAU,EAAE,KAAK;QACjB,WAAW,EAAE,KAAK;QAClB,MAAM,EAAE,EAAE;QACV,EAAE;KACH,CAAA;IACD,oBAAW,CAAC,GAAG,EAAE,SAAS,EAAE,iBAAiB,CAAC,CAAA;AAChD,CAAC"}
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
import type { ErrorObject, AnySchemaObject } from "../../types";
|
||||
import type { SchemaObjCxt } from "..";
|
||||
import { JSONType } from "../rules";
|
||||
import { Code, Name } from "../codegen";
|
||||
export declare enum DataType {
|
||||
Correct = 0,
|
||||
Wrong = 1
|
||||
}
|
||||
export declare function getSchemaTypes(schema: AnySchemaObject): JSONType[];
|
||||
export declare function getJSONTypes(ts: unknown | unknown[]): JSONType[];
|
||||
export declare function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean;
|
||||
export declare function checkDataType(dataType: JSONType, data: Name, strictNums?: boolean | "log", correct?: DataType): Code;
|
||||
export declare function checkDataTypes(dataTypes: JSONType[], data: Name, strictNums?: boolean | "log", correct?: DataType): Code;
|
||||
export declare type TypeError = ErrorObject<"type", {
|
||||
type: string;
|
||||
}>;
|
||||
export declare function reportTypeError(it: SchemaObjCxt): void;
|
||||
Generated
Vendored
+202
@@ -0,0 +1,202 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
|
||||
const rules_1 = require("../rules");
|
||||
const applicability_1 = require("./applicability");
|
||||
const errors_1 = require("../errors");
|
||||
const codegen_1 = require("../codegen");
|
||||
const util_1 = require("../util");
|
||||
var DataType;
|
||||
(function (DataType) {
|
||||
DataType[DataType["Correct"] = 0] = "Correct";
|
||||
DataType[DataType["Wrong"] = 1] = "Wrong";
|
||||
})(DataType = exports.DataType || (exports.DataType = {}));
|
||||
function getSchemaTypes(schema) {
|
||||
const types = getJSONTypes(schema.type);
|
||||
const hasNull = types.includes("null");
|
||||
if (hasNull) {
|
||||
if (schema.nullable === false)
|
||||
throw new Error("type: null contradicts nullable: false");
|
||||
}
|
||||
else {
|
||||
if (!types.length && schema.nullable !== undefined) {
|
||||
throw new Error('"nullable" cannot be used without "type"');
|
||||
}
|
||||
if (schema.nullable === true)
|
||||
types.push("null");
|
||||
}
|
||||
return types;
|
||||
}
|
||||
exports.getSchemaTypes = getSchemaTypes;
|
||||
function getJSONTypes(ts) {
|
||||
const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
|
||||
if (types.every(rules_1.isJSONType))
|
||||
return types;
|
||||
throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
|
||||
}
|
||||
exports.getJSONTypes = getJSONTypes;
|
||||
function coerceAndCheckDataType(it, types) {
|
||||
const { gen, data, opts } = it;
|
||||
const coerceTo = coerceToTypes(types, opts.coerceTypes);
|
||||
const checkTypes = types.length > 0 &&
|
||||
!(coerceTo.length === 0 && types.length === 1 && applicability_1.schemaHasRulesForType(it, types[0]));
|
||||
if (checkTypes) {
|
||||
const wrongType = checkDataTypes(types, data, opts.strict, DataType.Wrong);
|
||||
gen.if(wrongType, () => {
|
||||
if (coerceTo.length)
|
||||
coerceData(it, types, coerceTo);
|
||||
else
|
||||
reportTypeError(it);
|
||||
});
|
||||
}
|
||||
return checkTypes;
|
||||
}
|
||||
exports.coerceAndCheckDataType = coerceAndCheckDataType;
|
||||
const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
|
||||
function coerceToTypes(types, coerceTypes) {
|
||||
return coerceTypes
|
||||
? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
|
||||
: [];
|
||||
}
|
||||
function coerceData(it, types, coerceTo) {
|
||||
const { gen, data, opts } = it;
|
||||
const dataType = gen.let("dataType", codegen_1._ `typeof ${data}`);
|
||||
const coerced = gen.let("coerced", codegen_1._ `undefined`);
|
||||
if (opts.coerceTypes === "array") {
|
||||
gen.if(codegen_1._ `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
|
||||
.assign(data, codegen_1._ `${data}[0]`)
|
||||
.assign(dataType, codegen_1._ `typeof ${data}`)
|
||||
.if(checkDataTypes(types, data, opts.strict), () => gen.assign(coerced, data)));
|
||||
}
|
||||
gen.if(codegen_1._ `${coerced} !== undefined`);
|
||||
for (const t of coerceTo) {
|
||||
if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
|
||||
coerceSpecificType(t);
|
||||
}
|
||||
}
|
||||
gen.else();
|
||||
reportTypeError(it);
|
||||
gen.endIf();
|
||||
gen.if(codegen_1._ `${coerced} !== undefined`, () => {
|
||||
gen.assign(data, coerced);
|
||||
assignParentData(it, coerced);
|
||||
});
|
||||
function coerceSpecificType(t) {
|
||||
switch (t) {
|
||||
case "string":
|
||||
gen
|
||||
.elseIf(codegen_1._ `${dataType} == "number" || ${dataType} == "boolean"`)
|
||||
.assign(coerced, codegen_1._ `"" + ${data}`)
|
||||
.elseIf(codegen_1._ `${data} === null`)
|
||||
.assign(coerced, codegen_1._ `""`);
|
||||
return;
|
||||
case "number":
|
||||
gen
|
||||
.elseIf(codegen_1._ `${dataType} == "boolean" || ${data} === null
|
||||
|| (${dataType} == "string" && ${data} && ${data} == +${data})`)
|
||||
.assign(coerced, codegen_1._ `+${data}`);
|
||||
return;
|
||||
case "integer":
|
||||
gen
|
||||
.elseIf(codegen_1._ `${dataType} === "boolean" || ${data} === null
|
||||
|| (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
|
||||
.assign(coerced, codegen_1._ `+${data}`);
|
||||
return;
|
||||
case "boolean":
|
||||
gen
|
||||
.elseIf(codegen_1._ `${data} === "false" || ${data} === 0 || ${data} === null`)
|
||||
.assign(coerced, false)
|
||||
.elseIf(codegen_1._ `${data} === "true" || ${data} === 1`)
|
||||
.assign(coerced, true);
|
||||
return;
|
||||
case "null":
|
||||
gen.elseIf(codegen_1._ `${data} === "" || ${data} === 0 || ${data} === false`);
|
||||
gen.assign(coerced, null);
|
||||
return;
|
||||
case "array":
|
||||
gen
|
||||
.elseIf(codegen_1._ `${dataType} === "string" || ${dataType} === "number"
|
||||
|| ${dataType} === "boolean" || ${data} === null`)
|
||||
.assign(coerced, codegen_1._ `[${data}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
|
||||
// TODO use gen.property
|
||||
gen.if(codegen_1._ `${parentData} !== undefined`, () => gen.assign(codegen_1._ `${parentData}[${parentDataProperty}]`, expr));
|
||||
}
|
||||
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
|
||||
const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
|
||||
let cond;
|
||||
switch (dataType) {
|
||||
case "null":
|
||||
return codegen_1._ `${data} ${EQ} null`;
|
||||
case "array":
|
||||
cond = codegen_1._ `Array.isArray(${data})`;
|
||||
break;
|
||||
case "object":
|
||||
cond = codegen_1._ `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
|
||||
break;
|
||||
case "integer":
|
||||
cond = numCond(codegen_1._ `!(${data} % 1) && !isNaN(${data})`);
|
||||
break;
|
||||
case "number":
|
||||
cond = numCond();
|
||||
break;
|
||||
default:
|
||||
return codegen_1._ `typeof ${data} ${EQ} ${dataType}`;
|
||||
}
|
||||
return correct === DataType.Correct ? cond : codegen_1.not(cond);
|
||||
function numCond(_cond = codegen_1.nil) {
|
||||
return codegen_1.and(codegen_1._ `typeof ${data} == "number"`, _cond, strictNums ? codegen_1._ `isFinite(${data})` : codegen_1.nil);
|
||||
}
|
||||
}
|
||||
exports.checkDataType = checkDataType;
|
||||
function checkDataTypes(dataTypes, data, strictNums, correct) {
|
||||
if (dataTypes.length === 1) {
|
||||
return checkDataType(dataTypes[0], data, strictNums, correct);
|
||||
}
|
||||
let cond;
|
||||
const types = util_1.toHash(dataTypes);
|
||||
if (types.array && types.object) {
|
||||
const notObj = codegen_1._ `typeof ${data} != "object"`;
|
||||
cond = types.null ? notObj : codegen_1._ `!${data} || ${notObj}`;
|
||||
delete types.null;
|
||||
delete types.array;
|
||||
delete types.object;
|
||||
}
|
||||
else {
|
||||
cond = codegen_1.nil;
|
||||
}
|
||||
if (types.number)
|
||||
delete types.integer;
|
||||
for (const t in types)
|
||||
cond = codegen_1.and(cond, checkDataType(t, data, strictNums, correct));
|
||||
return cond;
|
||||
}
|
||||
exports.checkDataTypes = checkDataTypes;
|
||||
const typeError = {
|
||||
message: ({ schema }) => codegen_1.str `should be ${schema}`,
|
||||
params: ({ schema, schemaValue }) => typeof schema == "string" ? codegen_1._ `{type: ${schema}}` : codegen_1._ `{type: ${schemaValue}}`,
|
||||
};
|
||||
function reportTypeError(it) {
|
||||
const cxt = getTypeErrorContext(it);
|
||||
errors_1.reportError(cxt, typeError);
|
||||
}
|
||||
exports.reportTypeError = reportTypeError;
|
||||
function getTypeErrorContext(it) {
|
||||
const { gen, data, schema } = it;
|
||||
const schemaCode = util_1.schemaRefOrVal(it, schema, "type");
|
||||
return {
|
||||
gen,
|
||||
keyword: "type",
|
||||
data,
|
||||
schema: schema.type,
|
||||
schemaCode,
|
||||
schemaValue: schemaCode,
|
||||
parentSchema: schema,
|
||||
params: {},
|
||||
it,
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=dataType.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import type { SchemaObjCxt } from "..";
|
||||
export declare function assignDefaults(it: SchemaObjCxt, ty?: string): void;
|
||||
Generated
Vendored
+35
@@ -0,0 +1,35 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.assignDefaults = void 0;
|
||||
const codegen_1 = require("../codegen");
|
||||
const _1 = require(".");
|
||||
function assignDefaults(it, ty) {
|
||||
const { properties, items } = it.schema;
|
||||
if (ty === "object" && properties) {
|
||||
for (const key in properties) {
|
||||
assignDefault(it, key, properties[key].default);
|
||||
}
|
||||
}
|
||||
else if (ty === "array" && Array.isArray(items)) {
|
||||
items.forEach((sch, i) => assignDefault(it, i, sch.default));
|
||||
}
|
||||
}
|
||||
exports.assignDefaults = assignDefaults;
|
||||
function assignDefault(it, prop, defaultValue) {
|
||||
const { gen, compositeRule, data, opts } = it;
|
||||
if (defaultValue === undefined)
|
||||
return;
|
||||
const childData = codegen_1._ `${data}${codegen_1.getProperty(prop)}`;
|
||||
if (compositeRule) {
|
||||
_1.checkStrictMode(it, `default is ignored for: ${childData}`);
|
||||
return;
|
||||
}
|
||||
let condition = codegen_1._ `${childData} === undefined`;
|
||||
if (opts.useDefaults === "empty") {
|
||||
condition = codegen_1._ `${condition} || ${childData} === null || ${childData} === ""`;
|
||||
}
|
||||
// `${childData} === undefined` +
|
||||
// (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
|
||||
gen.if(condition, codegen_1._ `${childData} = ${codegen_1.stringify(defaultValue)}`);
|
||||
}
|
||||
//# sourceMappingURL=defaults.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../../../lib/compile/validate/defaults.ts"],"names":[],"mappings":";;;AACA,wCAAoD;AACpD,wBAAiC;AAEjC,SAAgB,cAAc,CAAC,EAAgB,EAA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EAAE,CAAC,CAAA;AACjE,CAAC"}
|
||||
Generated
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
import type { SchemaCxt } from "..";
|
||||
import { Name } from "../codegen";
|
||||
export declare function validateFunctionCode(it: SchemaCxt): void;
|
||||
export declare function subschemaCode(it: SchemaCxt, valid: Name): void;
|
||||
export declare function schemaCxtHasRules({ schema, self }: SchemaCxt): boolean;
|
||||
export declare function checkStrictMode(it: SchemaCxt, msg: string, mode?: boolean | "log"): void;
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.checkStrictMode = exports.schemaCxtHasRules = exports.subschemaCode = exports.validateFunctionCode = void 0;
|
||||
const boolSchema_1 = require("./boolSchema");
|
||||
const dataType_1 = require("./dataType");
|
||||
const iterate_1 = require("./iterate");
|
||||
const codegen_1 = require("../codegen");
|
||||
const names_1 = require("../names");
|
||||
const resolve_1 = require("../resolve");
|
||||
const util_1 = require("../util");
|
||||
// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
|
||||
function validateFunctionCode(it) {
|
||||
if (isSchemaObj(it)) {
|
||||
checkKeywords(it);
|
||||
if (schemaCxtHasRules(it)) {
|
||||
topSchemaObjCode(it);
|
||||
return;
|
||||
}
|
||||
}
|
||||
validateFunction(it, () => boolSchema_1.topBoolOrEmptySchema(it));
|
||||
}
|
||||
exports.validateFunctionCode = validateFunctionCode;
|
||||
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
|
||||
if (opts.code.es5) {
|
||||
gen.func(validateName, codegen_1._ `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
|
||||
gen.code(codegen_1._ `"use strict"; ${funcSourceUrl(schema, opts)}`);
|
||||
destructureValCxtES5(gen, opts);
|
||||
gen.code(body);
|
||||
});
|
||||
}
|
||||
else {
|
||||
gen.func(validateName, codegen_1._ `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
|
||||
}
|
||||
}
|
||||
function destructureValCxt(opts) {
|
||||
return codegen_1._ `{${names_1.default.dataPath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? codegen_1._ `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
|
||||
}
|
||||
function destructureValCxtES5(gen, opts) {
|
||||
gen.if(names_1.default.valCxt, () => {
|
||||
gen.var(names_1.default.dataPath, codegen_1._ `${names_1.default.valCxt}.${names_1.default.dataPath}`);
|
||||
gen.var(names_1.default.parentData, codegen_1._ `${names_1.default.valCxt}.${names_1.default.parentData}`);
|
||||
gen.var(names_1.default.parentDataProperty, codegen_1._ `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
|
||||
gen.var(names_1.default.rootData, codegen_1._ `${names_1.default.valCxt}.${names_1.default.rootData}`);
|
||||
if (opts.dynamicRef)
|
||||
gen.var(names_1.default.dynamicAnchors, codegen_1._ `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
|
||||
}, () => {
|
||||
gen.var(names_1.default.dataPath, codegen_1._ `""`);
|
||||
gen.var(names_1.default.parentData, codegen_1._ `undefined`);
|
||||
gen.var(names_1.default.parentDataProperty, codegen_1._ `undefined`);
|
||||
gen.var(names_1.default.rootData, names_1.default.data);
|
||||
if (opts.dynamicRef)
|
||||
gen.var(names_1.default.dynamicAnchors, codegen_1._ `{}`);
|
||||
});
|
||||
}
|
||||
function topSchemaObjCode(it) {
|
||||
const { schema, opts, gen } = it;
|
||||
validateFunction(it, () => {
|
||||
if (opts.$comment && schema.$comment)
|
||||
commentKeyword(it);
|
||||
checkNoDefault(it);
|
||||
gen.let(names_1.default.vErrors, null);
|
||||
gen.let(names_1.default.errors, 0);
|
||||
if (opts.unevaluated)
|
||||
resetEvaluated(it);
|
||||
typeAndKeywords(it);
|
||||
returnResults(it);
|
||||
});
|
||||
return;
|
||||
}
|
||||
function resetEvaluated(it) {
|
||||
// TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
|
||||
const { gen, validateName } = it;
|
||||
it.evaluated = gen.const("evaluated", codegen_1._ `${validateName}.evaluated`);
|
||||
gen.if(codegen_1._ `${it.evaluated}.dynamicProps`, () => gen.assign(codegen_1._ `${it.evaluated}.props`, codegen_1._ `undefined`));
|
||||
gen.if(codegen_1._ `${it.evaluated}.dynamicItems`, () => gen.assign(codegen_1._ `${it.evaluated}.items`, codegen_1._ `undefined`));
|
||||
}
|
||||
function funcSourceUrl(schema, opts) {
|
||||
return typeof schema == "object" && schema.$id && (opts.code.source || opts.code.process)
|
||||
? codegen_1._ `/*# sourceURL=${schema.$id} */`
|
||||
: codegen_1.nil;
|
||||
}
|
||||
// schema compilation - this function is used recursively to generate code for sub-schemas
|
||||
function subschemaCode(it, valid) {
|
||||
if (isSchemaObj(it)) {
|
||||
checkKeywords(it);
|
||||
if (schemaCxtHasRules(it)) {
|
||||
subSchemaObjCode(it, valid);
|
||||
return;
|
||||
}
|
||||
}
|
||||
boolSchema_1.boolOrEmptySchema(it, valid);
|
||||
}
|
||||
exports.subschemaCode = subschemaCode;
|
||||
function schemaCxtHasRules({ schema, self }) {
|
||||
if (typeof schema == "boolean")
|
||||
return !schema;
|
||||
for (const key in schema)
|
||||
if (self.RULES.all[key])
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
exports.schemaCxtHasRules = schemaCxtHasRules;
|
||||
function isSchemaObj(it) {
|
||||
return typeof it.schema != "boolean";
|
||||
}
|
||||
function subSchemaObjCode(it, valid) {
|
||||
const { schema, gen, opts } = it;
|
||||
if (opts.$comment && schema.$comment)
|
||||
commentKeyword(it);
|
||||
updateContext(it);
|
||||
checkAsync(it);
|
||||
const errsCount = gen.const("_errs", names_1.default.errors);
|
||||
typeAndKeywords(it, errsCount);
|
||||
// TODO var
|
||||
gen.var(valid, codegen_1._ `${errsCount} === ${names_1.default.errors}`);
|
||||
}
|
||||
function checkKeywords(it) {
|
||||
util_1.checkUnknownRules(it);
|
||||
checkRefsAndKeywords(it);
|
||||
}
|
||||
function typeAndKeywords(it, errsCount) {
|
||||
if (it.opts.jtd)
|
||||
return iterate_1.schemaKeywords(it, [], false, errsCount);
|
||||
const types = dataType_1.getSchemaTypes(it.schema);
|
||||
const checkedTypes = dataType_1.coerceAndCheckDataType(it, types);
|
||||
iterate_1.schemaKeywords(it, types, !checkedTypes, errsCount);
|
||||
}
|
||||
function checkRefsAndKeywords(it) {
|
||||
const { schema, errSchemaPath, opts, self } = it;
|
||||
if (schema.$ref && opts.ignoreKeywordsWithRef && util_1.schemaHasRulesButRef(schema, self.RULES)) {
|
||||
self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
|
||||
}
|
||||
}
|
||||
function checkNoDefault(it) {
|
||||
const { schema, opts } = it;
|
||||
if (schema.default !== undefined && opts.useDefaults && opts.strict) {
|
||||
checkStrictMode(it, "default is ignored in the schema root");
|
||||
}
|
||||
}
|
||||
function updateContext(it) {
|
||||
if (it.schema.$id)
|
||||
it.baseId = resolve_1.resolveUrl(it.baseId, it.schema.$id);
|
||||
}
|
||||
function checkAsync(it) {
|
||||
if (it.schema.$async && !it.schemaEnv.$async)
|
||||
throw new Error("async schema in sync schema");
|
||||
}
|
||||
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
|
||||
const msg = schema.$comment;
|
||||
if (opts.$comment === true) {
|
||||
gen.code(codegen_1._ `${names_1.default.self}.logger.log(${msg})`);
|
||||
}
|
||||
else if (typeof opts.$comment == "function") {
|
||||
const schemaPath = codegen_1.str `${errSchemaPath}/$comment`;
|
||||
const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
|
||||
gen.code(codegen_1._ `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
|
||||
}
|
||||
}
|
||||
function returnResults(it) {
|
||||
const { gen, schemaEnv, validateName, ValidationError, opts } = it;
|
||||
if (schemaEnv.$async) {
|
||||
// TODO assign unevaluated
|
||||
gen.if(codegen_1._ `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw(codegen_1._ `new ${ValidationError}(${names_1.default.vErrors})`));
|
||||
}
|
||||
else {
|
||||
gen.assign(codegen_1._ `${validateName}.errors`, names_1.default.vErrors);
|
||||
if (opts.unevaluated)
|
||||
assignEvaluated(it);
|
||||
gen.return(codegen_1._ `${names_1.default.errors} === 0`);
|
||||
}
|
||||
}
|
||||
function assignEvaluated({ gen, evaluated, props, items }) {
|
||||
if (props instanceof codegen_1.Name)
|
||||
gen.assign(codegen_1._ `${evaluated}.props`, props);
|
||||
if (items instanceof codegen_1.Name)
|
||||
gen.assign(codegen_1._ `${evaluated}.items`, items);
|
||||
}
|
||||
function checkStrictMode(it, msg, mode = it.opts.strict) {
|
||||
if (!mode)
|
||||
return;
|
||||
msg = `strict mode: ${msg}`;
|
||||
if (mode === true)
|
||||
throw new Error(msg);
|
||||
it.self.logger.warn(msg);
|
||||
}
|
||||
exports.checkStrictMode = checkStrictMode;
|
||||
//# sourceMappingURL=index.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
import type { SchemaObjCxt } from "..";
|
||||
import type { JSONType } from "../rules";
|
||||
import { Name } from "../codegen";
|
||||
export declare function schemaKeywords(it: SchemaObjCxt, types: JSONType[], typeErrors: boolean, errsCount?: Name): void;
|
||||
Generated
Vendored
+109
@@ -0,0 +1,109 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.schemaKeywords = void 0;
|
||||
const applicability_1 = require("./applicability");
|
||||
const dataType_1 = require("./dataType");
|
||||
const defaults_1 = require("./defaults");
|
||||
const keyword_1 = require("./keyword");
|
||||
const util_1 = require("../util");
|
||||
const _1 = require(".");
|
||||
const codegen_1 = require("../codegen");
|
||||
const names_1 = require("../names");
|
||||
function schemaKeywords(it, types, typeErrors, errsCount) {
|
||||
const { gen, schema, data, allErrors, opts, self } = it;
|
||||
const { RULES } = self;
|
||||
if (schema.$ref && (opts.ignoreKeywordsWithRef || !util_1.schemaHasRulesButRef(schema, RULES))) {
|
||||
gen.block(() => keyword_1.keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast
|
||||
return;
|
||||
}
|
||||
if (!opts.jtd)
|
||||
checkStrictTypes(it, types);
|
||||
gen.block(() => {
|
||||
for (const group of RULES.rules)
|
||||
groupKeywords(group);
|
||||
groupKeywords(RULES.post);
|
||||
});
|
||||
function groupKeywords(group) {
|
||||
if (!applicability_1.shouldUseGroup(schema, group))
|
||||
return;
|
||||
if (group.type) {
|
||||
gen.if(dataType_1.checkDataType(group.type, data, opts.strict));
|
||||
iterateKeywords(it, group);
|
||||
if (types.length === 1 && types[0] === group.type && typeErrors) {
|
||||
gen.else();
|
||||
dataType_1.reportTypeError(it);
|
||||
}
|
||||
gen.endIf();
|
||||
}
|
||||
else {
|
||||
iterateKeywords(it, group);
|
||||
}
|
||||
// TODO make it "ok" call?
|
||||
if (!allErrors)
|
||||
gen.if(codegen_1._ `${names_1.default.errors} === ${errsCount || 0}`);
|
||||
}
|
||||
}
|
||||
exports.schemaKeywords = schemaKeywords;
|
||||
function iterateKeywords(it, group) {
|
||||
const { gen, schema, opts: { useDefaults }, } = it;
|
||||
if (useDefaults)
|
||||
defaults_1.assignDefaults(it, group.type);
|
||||
gen.block(() => {
|
||||
for (const rule of group.rules) {
|
||||
if (applicability_1.shouldUseRule(schema, rule)) {
|
||||
keyword_1.keywordCode(it, rule.keyword, rule.definition, group.type);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
function checkStrictTypes(it, types) {
|
||||
if (it.schemaEnv.meta || !it.opts.strictTypes)
|
||||
return;
|
||||
checkContextTypes(it, types);
|
||||
if (!it.opts.allowUnionTypes)
|
||||
checkMultipleTypes(it, types);
|
||||
checkKeywordTypes(it, it.dataTypes);
|
||||
}
|
||||
function checkContextTypes(it, types) {
|
||||
if (!types.length)
|
||||
return;
|
||||
if (!it.dataTypes.length) {
|
||||
it.dataTypes = types;
|
||||
return;
|
||||
}
|
||||
types.forEach((t) => {
|
||||
if (!includesType(it.dataTypes, t)) {
|
||||
strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
|
||||
}
|
||||
});
|
||||
it.dataTypes = it.dataTypes.filter((t) => includesType(types, t));
|
||||
}
|
||||
function checkMultipleTypes(it, ts) {
|
||||
if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
|
||||
strictTypesError(it, "use allowUnionTypes to allow union type keyword");
|
||||
}
|
||||
}
|
||||
function checkKeywordTypes(it, ts) {
|
||||
const rules = it.self.RULES.all;
|
||||
for (const keyword in rules) {
|
||||
const rule = rules[keyword];
|
||||
if (typeof rule == "object" && applicability_1.shouldUseRule(it.schema, rule)) {
|
||||
const { type } = rule.definition;
|
||||
if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
|
||||
strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function hasApplicableType(schTs, kwdT) {
|
||||
return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
|
||||
}
|
||||
function includesType(ts, t) {
|
||||
return ts.includes(t) || (t === "integer" && ts.includes("number"));
|
||||
}
|
||||
function strictTypesError(it, msg) {
|
||||
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
|
||||
msg += ` at "${schemaPath}" (strictTypes)`;
|
||||
_1.checkStrictMode(it, msg, it.opts.strictTypes);
|
||||
}
|
||||
//# sourceMappingURL=iterate.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"iterate.js","sourceRoot":"","sources":["../../../lib/compile/validate/iterate.ts"],"names":[],"mappings":";;;AAEA,mDAA6D;AAC7D,yCAAyD;AACzD,yCAAyC;AACzC,uCAAqC;AACrC,kCAA4C;AAC5C,wBAAiC;AACj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,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,EAAE;YAC7D,MAAM,EAAC,IAAI,EAAC,GAAG,IAAI,CAAC,UAAU,CAAA;YAC9B,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE;gBAC9D,gBAAgB,CAAC,EAAE,EAAE,iBAAiB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,kBAAkB,OAAO,GAAG,CAAC,CAAA;aAClF;SACF;KACF;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAiB,EAAE,IAAc;IAC1D,OAAO,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAA;AACjF,CAAC;AAED,SAAS,YAAY,CAAC,EAAc,EAAE,CAAW;IAC/C,OAAO,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,SAAS,IAAI,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAA;AACrE,CAAC;AAED,SAAS,gBAAgB,CAAC,EAAgB,EAAE,GAAW;IACrD,MAAM,UAAU,GAAG,EAAE,CAAC,SAAS,CAAC,MAAM,GAAG,EAAE,CAAC,aAAa,CAAA;IACzD,GAAG,IAAI,QAAQ,UAAU,iBAAiB,CAAA;IAC1C,kBAAe,CAAC,EAAE,EAAE,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;AAC/C,CAAC"}
|
||||
Generated
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
import type { AddedKeywordDefinition } from "../../types";
|
||||
import type { SchemaObjCxt } from "..";
|
||||
import type { JSONType } from "../rules";
|
||||
export declare function keywordCode(it: SchemaObjCxt, keyword: string, def: AddedKeywordDefinition, ruleType?: JSONType): void;
|
||||
Generated
Vendored
+107
@@ -0,0 +1,107 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.keywordCode = void 0;
|
||||
const context_1 = require("../context");
|
||||
const errors_1 = require("../errors");
|
||||
const code_1 = require("../../vocabularies/code");
|
||||
const codegen_1 = require("../codegen");
|
||||
const names_1 = require("../names");
|
||||
function keywordCode(it, keyword, def, ruleType) {
|
||||
const cxt = new context_1.default(it, def, keyword);
|
||||
if ("code" in def) {
|
||||
def.code(cxt, ruleType);
|
||||
}
|
||||
else if (cxt.$data && def.validate) {
|
||||
funcKeywordCode(cxt, def);
|
||||
}
|
||||
else if ("macro" in def) {
|
||||
macroKeywordCode(cxt, def);
|
||||
}
|
||||
else if (def.compile || def.validate) {
|
||||
funcKeywordCode(cxt, def);
|
||||
}
|
||||
}
|
||||
exports.keywordCode = keywordCode;
|
||||
function macroKeywordCode(cxt, def) {
|
||||
const { gen, keyword, schema, parentSchema, it } = cxt;
|
||||
const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
|
||||
const schemaRef = useKeyword(gen, keyword, macroSchema);
|
||||
if (it.opts.validateSchema !== false)
|
||||
it.self.validateSchema(macroSchema, true);
|
||||
const valid = gen.name("valid");
|
||||
cxt.subschema({
|
||||
schema: macroSchema,
|
||||
schemaPath: codegen_1.nil,
|
||||
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
|
||||
topSchemaRef: schemaRef,
|
||||
compositeRule: true,
|
||||
}, valid);
|
||||
cxt.pass(valid, () => cxt.error(true));
|
||||
}
|
||||
function funcKeywordCode(cxt, def) {
|
||||
var _a;
|
||||
const { gen, keyword, schema, parentSchema, $data, it } = cxt;
|
||||
checkAsync(it, def);
|
||||
const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
|
||||
const validateRef = useKeyword(gen, keyword, validate);
|
||||
const valid = gen.let("valid");
|
||||
cxt.block$data(valid, validateKeyword);
|
||||
cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
|
||||
function validateKeyword() {
|
||||
if (def.errors === false) {
|
||||
assignValid();
|
||||
if (def.modifying)
|
||||
modifyData(cxt);
|
||||
reportErrs(() => cxt.error());
|
||||
}
|
||||
else {
|
||||
const ruleErrs = def.async ? validateAsync() : validateSync();
|
||||
if (def.modifying)
|
||||
modifyData(cxt);
|
||||
reportErrs(() => addErrs(cxt, ruleErrs));
|
||||
}
|
||||
}
|
||||
function validateAsync() {
|
||||
const ruleErrs = gen.let("ruleErrs", null);
|
||||
gen.try(() => assignValid(codegen_1._ `await `), (e) => gen.assign(valid, false).if(codegen_1._ `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, codegen_1._ `${e}.errors`), () => gen.throw(e)));
|
||||
return ruleErrs;
|
||||
}
|
||||
function validateSync() {
|
||||
const validateErrs = codegen_1._ `${validateRef}.errors`;
|
||||
gen.assign(validateErrs, null);
|
||||
assignValid(codegen_1.nil);
|
||||
return validateErrs;
|
||||
}
|
||||
function assignValid(_await = def.async ? codegen_1._ `await ` : codegen_1.nil) {
|
||||
const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
|
||||
const passSchema = !(("compile" in def && !$data) || def.schema === false);
|
||||
gen.assign(valid, codegen_1._ `${_await}${code_1.callValidateCode(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
|
||||
}
|
||||
function reportErrs(errors) {
|
||||
var _a;
|
||||
gen.if(codegen_1.not((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
|
||||
}
|
||||
}
|
||||
function modifyData(cxt) {
|
||||
const { gen, data, it } = cxt;
|
||||
gen.if(it.parentData, () => gen.assign(data, codegen_1._ `${it.parentData}[${it.parentDataProperty}]`));
|
||||
}
|
||||
function addErrs(cxt, errs) {
|
||||
const { gen } = cxt;
|
||||
gen.if(codegen_1._ `Array.isArray(${errs})`, () => {
|
||||
gen
|
||||
.assign(names_1.default.vErrors, codegen_1._ `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
|
||||
.assign(names_1.default.errors, codegen_1._ `${names_1.default.vErrors}.length`);
|
||||
errors_1.extendErrors(cxt);
|
||||
}, () => cxt.error());
|
||||
}
|
||||
function checkAsync({ schemaEnv }, def) {
|
||||
if (def.async && !schemaEnv.$async)
|
||||
throw new Error("async keyword in sync schema");
|
||||
}
|
||||
function useKeyword(gen, keyword, result) {
|
||||
if (result === undefined)
|
||||
throw new Error(`keyword "${keyword}" failed to compile`);
|
||||
return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: codegen_1.stringify(result) });
|
||||
}
|
||||
//# sourceMappingURL=keyword.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"keyword.js","sourceRoot":"","sources":["../../../lib/compile/validate/keyword.ts"],"names":[],"mappings":";;;AAUA,wCAAmC;AACnC,sCAAsC;AACtC,kDAAwD;AACxD,wCAAsE;AACtE,oCAAwB;AAIxB,SAAgB,WAAW,CACzB,EAAgB,EAChB,OAAe,EACf,GAA2B,EAC3B,QAAmB;IAEnB,MAAM,GAAG,GAAG,IAAI,iBAAU,CAAC,EAAE,EAAE,GAAG,EAAE,OAAO,CAAC,CAAA;IAC5C,IAAI,MAAM,IAAI,GAAG,EAAE;QACjB,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;KACxB;SAAM,IAAI,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,QAAQ,EAAE;QACpC,eAAe,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;KAC1B;SAAM,IAAI,OAAO,IAAI,GAAG,EAAE;QACzB,gBAAgB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;KAC3B;SAAM,IAAI,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,QAAQ,EAAE;QACtC,eAAe,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;KAC1B;AACH,CAAC;AAhBD,kCAgB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IAAI,EAAE,mBAAS,CAAC,MAAM,CAAC,EAAC,CACrF,CAAA;AACH,CAAC"}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, AnyValidateFunction, ErrorObject, ErrorNoParams, } from "./types";
|
||||
export { SchemaCxt, SchemaObjCxt } from "./compile";
|
||||
export interface Plugin<Opts> {
|
||||
(ajv: Ajv, options?: Opts): Ajv;
|
||||
[prop: string]: any;
|
||||
}
|
||||
import KeywordCxt from "./compile/context";
|
||||
export { KeywordCxt };
|
||||
export { DefinedError } from "./vocabularies/errors";
|
||||
export { JSONType } from "./compile/rules";
|
||||
export { JSONSchemaType } from "./types/json-schema";
|
||||
export { JTDSchemaType } from "./types/jtd-schema";
|
||||
export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen";
|
||||
import type { Schema, AnySchema, AnySchemaObject, SchemaObject, AsyncSchema, Vocabulary, KeywordDefinition, AddedKeywordDefinition, AnyValidateFunction, ValidateFunction, AsyncValidateFunction, ErrorObject, Format, AddedFormat } from "./types";
|
||||
import type { JSONSchemaType } from "./types/json-schema";
|
||||
import type { JTDSchemaType } from "./types/jtd-schema";
|
||||
import { ValidationError, MissingRefError } from "./compile/error_classes";
|
||||
import { ValidationRules } from "./compile/rules";
|
||||
import { SchemaEnv } from "./compile";
|
||||
import { Code, ValueScope } from "./compile/codegen";
|
||||
export declare type Options = CurrentOptions & DeprecatedOptions;
|
||||
export interface CurrentOptions {
|
||||
strict?: boolean | "log";
|
||||
strictTypes?: boolean | "log";
|
||||
strictTuples?: boolean | "log";
|
||||
strictRequired?: boolean | "log";
|
||||
allowMatchingProperties?: boolean;
|
||||
allowUnionTypes?: boolean;
|
||||
validateFormats?: boolean;
|
||||
$data?: boolean;
|
||||
allErrors?: boolean;
|
||||
verbose?: boolean;
|
||||
$comment?: true | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown);
|
||||
formats?: {
|
||||
[Name in string]?: Format;
|
||||
};
|
||||
keywords?: Vocabulary;
|
||||
schemas?: AnySchema[] | {
|
||||
[Key in string]?: AnySchema;
|
||||
};
|
||||
logger?: Logger | false;
|
||||
loadSchema?: (uri: string) => Promise<AnySchemaObject>;
|
||||
removeAdditional?: boolean | "all" | "failing";
|
||||
useDefaults?: boolean | "empty";
|
||||
coerceTypes?: boolean | "array";
|
||||
next?: boolean;
|
||||
unevaluated?: boolean;
|
||||
dynamicRef?: boolean;
|
||||
jtd?: boolean;
|
||||
meta?: SchemaObject | boolean;
|
||||
defaultMeta?: string | AnySchemaObject;
|
||||
validateSchema?: boolean | "log";
|
||||
addUsedSchema?: boolean;
|
||||
inlineRefs?: boolean | number;
|
||||
passContext?: boolean;
|
||||
loopRequired?: number;
|
||||
loopEnum?: number;
|
||||
ownProperties?: boolean;
|
||||
multipleOfPrecision?: number;
|
||||
messages?: boolean;
|
||||
code?: CodeOptions;
|
||||
ajvErrors?: boolean;
|
||||
}
|
||||
export interface CodeOptions {
|
||||
es5?: boolean;
|
||||
lines?: boolean;
|
||||
optimize?: boolean | number;
|
||||
formats?: Code;
|
||||
source?: boolean;
|
||||
process?: (code: string, schema?: SchemaEnv) => string;
|
||||
}
|
||||
interface InstanceCodeOptions extends CodeOptions {
|
||||
optimize: number;
|
||||
}
|
||||
interface DeprecatedOptions {
|
||||
/** @deprecated */
|
||||
ignoreKeywordsWithRef?: boolean;
|
||||
/** @deprecated */
|
||||
jsPropertySyntax?: boolean;
|
||||
/** @deprecated */
|
||||
unicode?: boolean;
|
||||
}
|
||||
declare type RequiredInstanceOptions = {
|
||||
[K in "strict" | "strictTypes" | "strictTuples" | "inlineRefs" | "loopRequired" | "loopEnum" | "meta" | "messages" | "addUsedSchema" | "validateSchema" | "validateFormats"]: NonNullable<Options[K]>;
|
||||
} & {
|
||||
code: InstanceCodeOptions;
|
||||
};
|
||||
export declare type InstanceOptions = Options & RequiredInstanceOptions;
|
||||
export interface Logger {
|
||||
log(...args: unknown[]): unknown;
|
||||
warn(...args: unknown[]): unknown;
|
||||
error(...args: unknown[]): unknown;
|
||||
}
|
||||
export default class Ajv {
|
||||
opts: InstanceOptions;
|
||||
errors?: ErrorObject[] | null;
|
||||
logger: Logger;
|
||||
readonly scope: ValueScope;
|
||||
readonly schemas: {
|
||||
[Key in string]?: SchemaEnv;
|
||||
};
|
||||
readonly refs: {
|
||||
[Ref in string]?: SchemaEnv | string;
|
||||
};
|
||||
readonly formats: {
|
||||
[Name in string]?: AddedFormat;
|
||||
};
|
||||
readonly RULES: ValidationRules;
|
||||
readonly _compilations: Set<SchemaEnv>;
|
||||
private readonly _loading;
|
||||
private readonly _cache;
|
||||
private readonly _metaOpts;
|
||||
static ValidationError: typeof ValidationError;
|
||||
static MissingRefError: typeof MissingRefError;
|
||||
constructor(opts?: Options);
|
||||
_addVocabularies(): void;
|
||||
_addDefaultMetaSchema(): void;
|
||||
defaultMeta(): string | AnySchemaObject | undefined;
|
||||
validate(schema: Schema | string, data: unknown): boolean;
|
||||
validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>;
|
||||
validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T;
|
||||
validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T;
|
||||
validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>;
|
||||
validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>;
|
||||
compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>;
|
||||
compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>;
|
||||
compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>;
|
||||
compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>;
|
||||
compileAsync<T = unknown>(schema: SchemaObject | JSONSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>;
|
||||
compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>;
|
||||
compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>;
|
||||
compileAsync<T = unknown>(schema: AnySchemaObject, meta?: boolean): Promise<AnyValidateFunction<T>>;
|
||||
addSchema(schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored
|
||||
key?: string, // 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`.
|
||||
_meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
|
||||
_validateSchema?: boolean | "log"): Ajv;
|
||||
addMetaSchema(schema: AnySchemaObject, key?: string, // schema key
|
||||
_validateSchema?: boolean | "log"): Ajv;
|
||||
validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown>;
|
||||
getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined;
|
||||
removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv;
|
||||
addVocabulary(definitions: Vocabulary): Ajv;
|
||||
addKeyword(kwdOrDef: string | KeywordDefinition, def?: KeywordDefinition): Ajv;
|
||||
getKeyword(keyword: string): AddedKeywordDefinition | boolean;
|
||||
removeKeyword(keyword: string): Ajv;
|
||||
addFormat(name: string, format: Format): Ajv;
|
||||
errorsText(errors?: ErrorObject[] | null | undefined, // optional array of validation errors
|
||||
{ separator, dataVar }?: ErrorsTextOptions): string;
|
||||
$dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject;
|
||||
private _removeAllSchemas;
|
||||
_addSchema(schema: AnySchema, meta?: boolean, validateSchema?: boolean | "log", addSchema?: boolean): SchemaEnv;
|
||||
private _checkUnique;
|
||||
private _compileSchemaEnv;
|
||||
private _compileMetaSchema;
|
||||
}
|
||||
export interface ErrorsTextOptions {
|
||||
separator?: string;
|
||||
dataVar?: string;
|
||||
}
|
||||
+591
@@ -0,0 +1,591 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
|
||||
const context_1 = require("./compile/context");
|
||||
exports.KeywordCxt = context_1.default;
|
||||
var codegen_1 = require("./compile/codegen");
|
||||
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
|
||||
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
|
||||
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
|
||||
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
|
||||
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
|
||||
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
|
||||
const error_classes_1 = require("./compile/error_classes");
|
||||
const rules_1 = require("./compile/rules");
|
||||
const compile_1 = require("./compile");
|
||||
const codegen_2 = require("./compile/codegen");
|
||||
const resolve_1 = require("./compile/resolve");
|
||||
const dataType_1 = require("./compile/validate/dataType");
|
||||
const util_1 = require("./compile/util");
|
||||
const $dataRefSchema = require("./refs/data.json");
|
||||
const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
|
||||
const EXT_SCOPE_NAMES = new Set([
|
||||
"validate",
|
||||
"serialize",
|
||||
"parse",
|
||||
"wrapper",
|
||||
"root",
|
||||
"schema",
|
||||
"keyword",
|
||||
"pattern",
|
||||
"formats",
|
||||
"validate$data",
|
||||
"func",
|
||||
"obj",
|
||||
"Error",
|
||||
]);
|
||||
const removedOptions = {
|
||||
errorDataPath: "",
|
||||
format: "`validateFormats: false` can be used instead.",
|
||||
nullable: '"nullable" keyword is supported by default.',
|
||||
jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
|
||||
extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
|
||||
missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
|
||||
processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
|
||||
sourceCode: "Use option `code: {source: true}`",
|
||||
schemaId: "JSON Schema draft-04 is not supported in Ajv v7.",
|
||||
strictDefaults: "It is default now, see option `strict`.",
|
||||
strictKeywords: "It is default now, see option `strict`.",
|
||||
strictNumbers: "It is default now, see option `strict`.",
|
||||
uniqueItems: '"uniqueItems" keyword is always validated.',
|
||||
unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
|
||||
cache: "Map is used as cache, schema object as key.",
|
||||
serialize: "Map is used as cache, schema object as key.",
|
||||
};
|
||||
const deprecatedOptions = {
|
||||
ignoreKeywordsWithRef: "",
|
||||
jsPropertySyntax: "",
|
||||
unicode: '"minLength"/"maxLength" account for unicode characters by default.',
|
||||
};
|
||||
function requiredOptions(o) {
|
||||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
|
||||
const strict = (_a = o.strict) !== null && _a !== void 0 ? _a : true;
|
||||
const strictLog = strict ? "log" : false;
|
||||
const _optz = (_b = o.code) === null || _b === void 0 ? void 0 : _b.optimize;
|
||||
const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
|
||||
return {
|
||||
strict,
|
||||
strictTypes: (_c = o.strictTypes) !== null && _c !== void 0 ? _c : strictLog,
|
||||
strictTuples: (_d = o.strictTuples) !== null && _d !== void 0 ? _d : strictLog,
|
||||
code: o.code ? { ...o.code, optimize } : { optimize },
|
||||
loopRequired: (_e = o.loopRequired) !== null && _e !== void 0 ? _e : Infinity,
|
||||
loopEnum: (_f = o.loopEnum) !== null && _f !== void 0 ? _f : Infinity,
|
||||
meta: (_g = o.meta) !== null && _g !== void 0 ? _g : true,
|
||||
messages: (_h = o.messages) !== null && _h !== void 0 ? _h : true,
|
||||
inlineRefs: (_j = o.inlineRefs) !== null && _j !== void 0 ? _j : true,
|
||||
addUsedSchema: (_k = o.addUsedSchema) !== null && _k !== void 0 ? _k : true,
|
||||
validateSchema: (_l = o.validateSchema) !== null && _l !== void 0 ? _l : true,
|
||||
validateFormats: (_m = o.validateFormats) !== null && _m !== void 0 ? _m : true,
|
||||
};
|
||||
}
|
||||
class Ajv {
|
||||
constructor(opts = {}) {
|
||||
this.schemas = {};
|
||||
this.refs = {};
|
||||
this.formats = {};
|
||||
this._compilations = new Set();
|
||||
this._loading = {};
|
||||
this._cache = new Map();
|
||||
opts = this.opts = { ...opts, ...requiredOptions(opts) };
|
||||
const { es5, lines } = this.opts.code;
|
||||
this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
|
||||
this.logger = getLogger(opts.logger);
|
||||
const formatOpt = opts.validateFormats;
|
||||
opts.validateFormats = false;
|
||||
this.RULES = rules_1.getRules();
|
||||
checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
|
||||
checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
|
||||
this._metaOpts = getMetaSchemaOptions.call(this);
|
||||
if (opts.formats)
|
||||
addInitialFormats.call(this);
|
||||
this._addVocabularies();
|
||||
this._addDefaultMetaSchema();
|
||||
if (opts.keywords)
|
||||
addInitialKeywords.call(this, opts.keywords);
|
||||
if (typeof opts.meta == "object")
|
||||
this.addMetaSchema(opts.meta);
|
||||
addInitialSchemas.call(this);
|
||||
opts.validateFormats = formatOpt;
|
||||
}
|
||||
_addVocabularies() {
|
||||
this.addKeyword("$async");
|
||||
}
|
||||
_addDefaultMetaSchema() {
|
||||
const { $data, meta } = this.opts;
|
||||
if (meta && $data)
|
||||
this.addMetaSchema($dataRefSchema, $dataRefSchema.$id, false);
|
||||
}
|
||||
defaultMeta() {
|
||||
const { meta } = this.opts;
|
||||
return (this.opts.defaultMeta = typeof meta == "object" ? meta.$id || meta : undefined);
|
||||
}
|
||||
validate(schemaKeyRef, // key, ref or schema object
|
||||
data // to be validated
|
||||
) {
|
||||
let v;
|
||||
if (typeof schemaKeyRef == "string") {
|
||||
v = this.getSchema(schemaKeyRef);
|
||||
if (!v)
|
||||
throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
|
||||
}
|
||||
else {
|
||||
v = this.compile(schemaKeyRef);
|
||||
}
|
||||
const valid = v(data);
|
||||
if (!("$async" in v))
|
||||
this.errors = v.errors;
|
||||
return valid;
|
||||
}
|
||||
compile(schema, _meta) {
|
||||
const sch = this._addSchema(schema, _meta);
|
||||
return (sch.validate || this._compileSchemaEnv(sch));
|
||||
}
|
||||
compileAsync(schema, meta) {
|
||||
if (typeof this.opts.loadSchema != "function") {
|
||||
throw new Error("options.loadSchema should be a function");
|
||||
}
|
||||
const { loadSchema } = this.opts;
|
||||
return runCompileAsync.call(this, schema, meta);
|
||||
async function runCompileAsync(_schema, _meta) {
|
||||
await loadMetaSchema.call(this, _schema.$schema);
|
||||
const sch = this._addSchema(_schema, _meta);
|
||||
return sch.validate || _compileAsync.call(this, sch);
|
||||
}
|
||||
async function loadMetaSchema($ref) {
|
||||
if ($ref && !this.getSchema($ref)) {
|
||||
await runCompileAsync.call(this, { $ref }, true);
|
||||
}
|
||||
}
|
||||
async function _compileAsync(sch) {
|
||||
try {
|
||||
return this._compileSchemaEnv(sch);
|
||||
}
|
||||
catch (e) {
|
||||
if (!(e instanceof error_classes_1.MissingRefError))
|
||||
throw e;
|
||||
checkLoaded.call(this, e);
|
||||
await loadMissingSchema.call(this, e.missingSchema);
|
||||
return _compileAsync.call(this, sch);
|
||||
}
|
||||
}
|
||||
function checkLoaded({ missingSchema: ref, missingRef }) {
|
||||
if (this.refs[ref]) {
|
||||
throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
|
||||
}
|
||||
}
|
||||
async function loadMissingSchema(ref) {
|
||||
const _schema = await _loadSchema.call(this, ref);
|
||||
if (!this.refs[ref])
|
||||
await loadMetaSchema.call(this, _schema.$schema);
|
||||
if (!this.refs[ref])
|
||||
this.addSchema(_schema, ref, meta);
|
||||
}
|
||||
async function _loadSchema(ref) {
|
||||
const p = this._loading[ref];
|
||||
if (p)
|
||||
return p;
|
||||
try {
|
||||
return await (this._loading[ref] = loadSchema(ref));
|
||||
}
|
||||
finally {
|
||||
delete this._loading[ref];
|
||||
}
|
||||
}
|
||||
}
|
||||
// Adds schema to the instance
|
||||
addSchema(schema, // If array is passed, `key` will be ignored
|
||||
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`.
|
||||
_meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
|
||||
_validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
|
||||
) {
|
||||
if (Array.isArray(schema)) {
|
||||
for (const sch of schema)
|
||||
this.addSchema(sch, undefined, _meta, _validateSchema);
|
||||
return this;
|
||||
}
|
||||
let id;
|
||||
if (typeof schema === "object") {
|
||||
id = schema.$id;
|
||||
if (id !== undefined && typeof id != "string")
|
||||
throw new Error("schema id must be string");
|
||||
}
|
||||
key = resolve_1.normalizeId(key || id);
|
||||
this._checkUnique(key);
|
||||
this.schemas[key] = this._addSchema(schema, _meta, _validateSchema, true);
|
||||
return this;
|
||||
}
|
||||
// Add schema that will be used to validate other schemas
|
||||
// options in META_IGNORE_OPTIONS are alway set to false
|
||||
addMetaSchema(schema, key, // schema key
|
||||
_validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
|
||||
) {
|
||||
this.addSchema(schema, key, true, _validateSchema);
|
||||
return this;
|
||||
}
|
||||
// Validate schema against its meta-schema
|
||||
validateSchema(schema, throwOrLogError) {
|
||||
if (typeof schema == "boolean")
|
||||
return true;
|
||||
let $schema;
|
||||
$schema = schema.$schema;
|
||||
if ($schema !== undefined && typeof $schema != "string") {
|
||||
throw new Error("$schema must be a string");
|
||||
}
|
||||
$schema = $schema || this.opts.defaultMeta || this.defaultMeta();
|
||||
if (!$schema) {
|
||||
this.logger.warn("meta-schema not available");
|
||||
this.errors = null;
|
||||
return true;
|
||||
}
|
||||
const valid = this.validate($schema, schema);
|
||||
if (!valid && throwOrLogError) {
|
||||
const message = "schema is invalid: " + this.errorsText();
|
||||
if (this.opts.validateSchema === "log")
|
||||
this.logger.error(message);
|
||||
else
|
||||
throw new Error(message);
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
// Get compiled schema by `key` or `ref`.
|
||||
// (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
|
||||
getSchema(keyRef) {
|
||||
let sch;
|
||||
while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
|
||||
keyRef = sch;
|
||||
if (sch === undefined) {
|
||||
const root = new compile_1.SchemaEnv({ schema: {} });
|
||||
sch = compile_1.resolveSchema.call(this, root, keyRef);
|
||||
if (!sch)
|
||||
return;
|
||||
this.refs[keyRef] = sch;
|
||||
}
|
||||
return (sch.validate || this._compileSchemaEnv(sch));
|
||||
}
|
||||
// Remove cached schema(s).
|
||||
// If no parameter is passed all schemas but meta-schemas are removed.
|
||||
// If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
|
||||
// Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
|
||||
removeSchema(schemaKeyRef) {
|
||||
if (schemaKeyRef instanceof RegExp) {
|
||||
this._removeAllSchemas(this.schemas, schemaKeyRef);
|
||||
this._removeAllSchemas(this.refs, schemaKeyRef);
|
||||
return this;
|
||||
}
|
||||
switch (typeof schemaKeyRef) {
|
||||
case "undefined":
|
||||
this._removeAllSchemas(this.schemas);
|
||||
this._removeAllSchemas(this.refs);
|
||||
this._cache.clear();
|
||||
return this;
|
||||
case "string": {
|
||||
const sch = getSchEnv.call(this, schemaKeyRef);
|
||||
if (typeof sch == "object")
|
||||
this._cache.delete(sch.schema);
|
||||
delete this.schemas[schemaKeyRef];
|
||||
delete this.refs[schemaKeyRef];
|
||||
return this;
|
||||
}
|
||||
case "object": {
|
||||
const cacheKey = schemaKeyRef;
|
||||
this._cache.delete(cacheKey);
|
||||
let id = schemaKeyRef.$id;
|
||||
if (id) {
|
||||
id = resolve_1.normalizeId(id);
|
||||
delete this.schemas[id];
|
||||
delete this.refs[id];
|
||||
}
|
||||
return this;
|
||||
}
|
||||
default:
|
||||
throw new Error("ajv.removeSchema: invalid parameter");
|
||||
}
|
||||
}
|
||||
// add "vocabulary" - a collection of keywords
|
||||
addVocabulary(definitions) {
|
||||
for (const def of definitions)
|
||||
this.addKeyword(def);
|
||||
return this;
|
||||
}
|
||||
addKeyword(kwdOrDef, def // deprecated
|
||||
) {
|
||||
let keyword;
|
||||
if (typeof kwdOrDef == "string") {
|
||||
keyword = kwdOrDef;
|
||||
if (typeof def == "object") {
|
||||
this.logger.warn("these parameters are deprecated, see docs for addKeyword");
|
||||
def.keyword = keyword;
|
||||
}
|
||||
}
|
||||
else if (typeof kwdOrDef == "object" && def === undefined) {
|
||||
def = kwdOrDef;
|
||||
keyword = def.keyword;
|
||||
if (Array.isArray(keyword) && !keyword.length) {
|
||||
throw new Error("addKeywords: keyword must be string or non-empty array");
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new Error("invalid addKeywords parameters");
|
||||
}
|
||||
checkKeyword.call(this, keyword, def);
|
||||
if (!def) {
|
||||
util_1.eachItem(keyword, (kwd) => addRule.call(this, kwd));
|
||||
return this;
|
||||
}
|
||||
keywordMetaschema.call(this, def);
|
||||
const definition = {
|
||||
...def,
|
||||
type: dataType_1.getJSONTypes(def.type),
|
||||
schemaType: dataType_1.getJSONTypes(def.schemaType),
|
||||
};
|
||||
util_1.eachItem(keyword, definition.type.length === 0
|
||||
? (k) => addRule.call(this, k, definition)
|
||||
: (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
|
||||
return this;
|
||||
}
|
||||
getKeyword(keyword) {
|
||||
const rule = this.RULES.all[keyword];
|
||||
return typeof rule == "object" ? rule.definition : !!rule;
|
||||
}
|
||||
// Remove keyword
|
||||
removeKeyword(keyword) {
|
||||
// TODO return type should be Ajv
|
||||
const { RULES } = this;
|
||||
delete RULES.keywords[keyword];
|
||||
delete RULES.all[keyword];
|
||||
for (const group of RULES.rules) {
|
||||
const i = group.rules.findIndex((rule) => rule.keyword === keyword);
|
||||
if (i >= 0)
|
||||
group.rules.splice(i, 1);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
// Add format
|
||||
addFormat(name, format) {
|
||||
if (typeof format == "string")
|
||||
format = new RegExp(format);
|
||||
this.formats[name] = format;
|
||||
return this;
|
||||
}
|
||||
errorsText(errors = this.errors, // optional array of validation errors
|
||||
{ separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
|
||||
) {
|
||||
if (!errors || errors.length === 0)
|
||||
return "No errors";
|
||||
return errors
|
||||
.map((e) => `${dataVar}${e.dataPath} ${e.message}`)
|
||||
.reduce((text, msg) => text + separator + msg);
|
||||
}
|
||||
$dataMetaSchema(metaSchema, keywordsJsonPointers) {
|
||||
const rules = this.RULES.all;
|
||||
metaSchema = JSON.parse(JSON.stringify(metaSchema));
|
||||
for (const jsonPointer of keywordsJsonPointers) {
|
||||
const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
|
||||
let keywords = metaSchema;
|
||||
for (const seg of segments)
|
||||
keywords = keywords[seg];
|
||||
for (const key in rules) {
|
||||
const rule = rules[key];
|
||||
if (typeof rule != "object")
|
||||
continue;
|
||||
const { $data } = rule.definition;
|
||||
const schema = keywords[key];
|
||||
if ($data && schema)
|
||||
keywords[key] = schemaOrData(schema);
|
||||
}
|
||||
}
|
||||
return metaSchema;
|
||||
}
|
||||
_removeAllSchemas(schemas, regex) {
|
||||
for (const keyRef in schemas) {
|
||||
const sch = schemas[keyRef];
|
||||
if (!regex || regex.test(keyRef)) {
|
||||
if (typeof sch == "string") {
|
||||
delete schemas[keyRef];
|
||||
}
|
||||
else if (sch && !sch.meta) {
|
||||
this._cache.delete(sch.schema);
|
||||
delete schemas[keyRef];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_addSchema(schema, meta, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
|
||||
if (typeof schema != "object") {
|
||||
if (this.opts.jtd)
|
||||
throw new Error("schema must be object");
|
||||
else if (typeof schema != "boolean")
|
||||
throw new Error("schema must be object or boolean");
|
||||
}
|
||||
let sch = this._cache.get(schema);
|
||||
if (sch !== undefined)
|
||||
return sch;
|
||||
const localRefs = resolve_1.getSchemaRefs.call(this, schema);
|
||||
sch = new compile_1.SchemaEnv({ schema, meta, localRefs });
|
||||
this._cache.set(sch.schema, sch);
|
||||
const id = sch.baseId;
|
||||
if (addSchema && !id.startsWith("#")) {
|
||||
// TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
|
||||
if (id)
|
||||
this._checkUnique(id);
|
||||
this.refs[id] = sch;
|
||||
}
|
||||
if (validateSchema)
|
||||
this.validateSchema(schema, true);
|
||||
return sch;
|
||||
}
|
||||
_checkUnique(id) {
|
||||
if (this.schemas[id] || this.refs[id]) {
|
||||
throw new Error(`schema with key or id "${id}" already exists`);
|
||||
}
|
||||
}
|
||||
_compileSchemaEnv(sch) {
|
||||
if (sch.meta)
|
||||
this._compileMetaSchema(sch);
|
||||
else
|
||||
compile_1.compileSchema.call(this, sch);
|
||||
/* istanbul ignore if */
|
||||
if (!sch.validate)
|
||||
throw new Error("ajv implementation error");
|
||||
return sch.validate;
|
||||
}
|
||||
_compileMetaSchema(sch) {
|
||||
const currentOpts = this.opts;
|
||||
this.opts = this._metaOpts;
|
||||
try {
|
||||
compile_1.compileSchema.call(this, sch);
|
||||
}
|
||||
finally {
|
||||
this.opts = currentOpts;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.default = Ajv;
|
||||
Ajv.ValidationError = error_classes_1.ValidationError;
|
||||
Ajv.MissingRefError = error_classes_1.MissingRefError;
|
||||
function checkOptions(checkOpts, options, msg, log = "error") {
|
||||
for (const key in checkOpts) {
|
||||
const opt = key;
|
||||
if (opt in options)
|
||||
this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
|
||||
}
|
||||
}
|
||||
function getSchEnv(keyRef) {
|
||||
keyRef = resolve_1.normalizeId(keyRef); // TODO tests fail without this line
|
||||
return this.schemas[keyRef] || this.refs[keyRef];
|
||||
}
|
||||
function addInitialSchemas() {
|
||||
const optsSchemas = this.opts.schemas;
|
||||
if (!optsSchemas)
|
||||
return;
|
||||
if (Array.isArray(optsSchemas))
|
||||
this.addSchema(optsSchemas);
|
||||
else
|
||||
for (const key in optsSchemas)
|
||||
this.addSchema(optsSchemas[key], key);
|
||||
}
|
||||
function addInitialFormats() {
|
||||
for (const name in this.opts.formats) {
|
||||
const format = this.opts.formats[name];
|
||||
if (format)
|
||||
this.addFormat(name, format);
|
||||
}
|
||||
}
|
||||
function addInitialKeywords(defs) {
|
||||
if (Array.isArray(defs)) {
|
||||
this.addVocabulary(defs);
|
||||
return;
|
||||
}
|
||||
this.logger.warn("keywords option as map is deprecated, pass array");
|
||||
for (const keyword in defs) {
|
||||
const def = defs[keyword];
|
||||
if (!def.keyword)
|
||||
def.keyword = keyword;
|
||||
this.addKeyword(def);
|
||||
}
|
||||
}
|
||||
function getMetaSchemaOptions() {
|
||||
const metaOpts = { ...this.opts };
|
||||
for (const opt of META_IGNORE_OPTIONS)
|
||||
delete metaOpts[opt];
|
||||
return metaOpts;
|
||||
}
|
||||
const noLogs = { log() { }, warn() { }, error() { } };
|
||||
function getLogger(logger) {
|
||||
if (logger === false)
|
||||
return noLogs;
|
||||
if (logger === undefined)
|
||||
return console;
|
||||
if (logger.log && logger.warn && logger.error)
|
||||
return logger;
|
||||
throw new Error("logger must implement log, warn and error methods");
|
||||
}
|
||||
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
|
||||
function checkKeyword(keyword, def) {
|
||||
const { RULES } = this;
|
||||
util_1.eachItem(keyword, (kwd) => {
|
||||
if (RULES.keywords[kwd])
|
||||
throw new Error(`Keyword ${kwd} is already defined`);
|
||||
if (!KEYWORD_NAME.test(kwd))
|
||||
throw new Error(`Keyword ${kwd} has invalid name`);
|
||||
});
|
||||
if (!def)
|
||||
return;
|
||||
if (def.$data && !("code" in def || "validate" in def)) {
|
||||
throw new Error('$data keyword must have "code" or "validate" function');
|
||||
}
|
||||
}
|
||||
function addRule(keyword, definition, dataType) {
|
||||
var _a;
|
||||
const post = definition === null || definition === void 0 ? void 0 : definition.post;
|
||||
if (dataType && post)
|
||||
throw new Error('keyword with "post" flag cannot have "type"');
|
||||
const { RULES } = this;
|
||||
let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
|
||||
if (!ruleGroup) {
|
||||
ruleGroup = { type: dataType, rules: [] };
|
||||
RULES.rules.push(ruleGroup);
|
||||
}
|
||||
RULES.keywords[keyword] = true;
|
||||
if (!definition)
|
||||
return;
|
||||
const rule = {
|
||||
keyword,
|
||||
definition: {
|
||||
...definition,
|
||||
type: dataType_1.getJSONTypes(definition.type),
|
||||
schemaType: dataType_1.getJSONTypes(definition.schemaType),
|
||||
},
|
||||
};
|
||||
if (definition.before)
|
||||
addBeforeRule.call(this, ruleGroup, rule, definition.before);
|
||||
else
|
||||
ruleGroup.rules.push(rule);
|
||||
RULES.all[keyword] = rule;
|
||||
(_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
|
||||
}
|
||||
function addBeforeRule(ruleGroup, rule, before) {
|
||||
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
|
||||
if (i >= 0) {
|
||||
ruleGroup.rules.splice(i, 0, rule);
|
||||
}
|
||||
else {
|
||||
ruleGroup.rules.push(rule);
|
||||
this.logger.warn(`rule ${before} is not defined`);
|
||||
}
|
||||
}
|
||||
function keywordMetaschema(def) {
|
||||
let { metaSchema } = def;
|
||||
if (metaSchema === undefined)
|
||||
return;
|
||||
if (def.$data && this.opts.$data)
|
||||
metaSchema = schemaOrData(metaSchema);
|
||||
def.validateSchema = this.compile(metaSchema, true);
|
||||
}
|
||||
const $dataRef = {
|
||||
$ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
||||
};
|
||||
function schemaOrData(schema) {
|
||||
return { anyOf: [schema, $dataRef] };
|
||||
}
|
||||
//# sourceMappingURL=core.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+45
@@ -0,0 +1,45 @@
|
||||
export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, JTDParser, } from "./types";
|
||||
export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core";
|
||||
export { SchemaCxt, SchemaObjCxt } from "./compile";
|
||||
import KeywordCxt from "./compile/context";
|
||||
export { KeywordCxt };
|
||||
export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen";
|
||||
import type { AnySchemaObject, SchemaObject, JTDParser } from "./types";
|
||||
import type { JTDSchemaType, JTDDataType } from "./types/jtd-schema";
|
||||
export { JTDSchemaType, JTDDataType };
|
||||
import AjvCore, { CurrentOptions } from "./core";
|
||||
export declare type JTDOptions = CurrentOptions & {
|
||||
strictTypes?: never;
|
||||
strictTuples?: never;
|
||||
allowMatchingProperties?: never;
|
||||
allowUnionTypes?: never;
|
||||
validateFormats?: never;
|
||||
$data?: never;
|
||||
verbose?: never;
|
||||
$comment?: never;
|
||||
formats?: never;
|
||||
loadSchema?: never;
|
||||
useDefaults?: never;
|
||||
coerceTypes?: never;
|
||||
next?: never;
|
||||
unevaluated?: never;
|
||||
dynamicRef?: never;
|
||||
meta?: boolean;
|
||||
defaultMeta?: never;
|
||||
inlineRefs?: boolean;
|
||||
loopRequired?: never;
|
||||
multipleOfPrecision?: never;
|
||||
ajvErrors?: boolean;
|
||||
};
|
||||
export default class Ajv extends AjvCore {
|
||||
constructor(opts?: JTDOptions);
|
||||
_addVocabularies(): void;
|
||||
_addDefaultMetaSchema(): void;
|
||||
defaultMeta(): string | AnySchemaObject | undefined;
|
||||
compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string;
|
||||
compileSerializer<T = unknown>(schema: JTDSchemaType<T>): (data: T) => string;
|
||||
compileParser<T = unknown>(schema: SchemaObject): JTDParser<T>;
|
||||
compileParser<T = unknown>(schema: JTDSchemaType<T>): JTDParser<T>;
|
||||
private _compileSerializer;
|
||||
private _compileParser;
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
|
||||
const context_1 = require("./compile/context");
|
||||
exports.KeywordCxt = context_1.default;
|
||||
// export {DefinedError} from "./vocabularies/errors"
|
||||
var codegen_1 = require("./compile/codegen");
|
||||
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
|
||||
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
|
||||
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
|
||||
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
|
||||
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
|
||||
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
|
||||
const core_1 = require("./core");
|
||||
const jtd_1 = require("./vocabularies/jtd");
|
||||
const jtd_schema_1 = require("./refs/jtd-schema");
|
||||
const serialize_1 = require("./compile/jtd/serialize");
|
||||
const parse_1 = require("./compile/jtd/parse");
|
||||
// const META_SUPPORT_DATA = ["/properties"]
|
||||
const META_SCHEMA_ID = "JTD-meta-schema";
|
||||
class Ajv extends core_1.default {
|
||||
constructor(opts = {}) {
|
||||
var _a;
|
||||
super({
|
||||
...opts,
|
||||
jtd: true,
|
||||
messages: (_a = opts.messages) !== null && _a !== void 0 ? _a : false,
|
||||
});
|
||||
}
|
||||
_addVocabularies() {
|
||||
super._addVocabularies();
|
||||
this.addVocabulary(jtd_1.default);
|
||||
}
|
||||
_addDefaultMetaSchema() {
|
||||
super._addDefaultMetaSchema();
|
||||
if (!this.opts.meta)
|
||||
return;
|
||||
this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false);
|
||||
}
|
||||
defaultMeta() {
|
||||
return (this.opts.defaultMeta =
|
||||
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
|
||||
}
|
||||
compileSerializer(schema) {
|
||||
const sch = this._addSchema(schema);
|
||||
return sch.serialize || this._compileSerializer(sch);
|
||||
}
|
||||
compileParser(schema) {
|
||||
const sch = this._addSchema(schema);
|
||||
return (sch.parse || this._compileParser(sch));
|
||||
}
|
||||
_compileSerializer(sch) {
|
||||
serialize_1.default.call(this, sch, sch.schema.definitions || {});
|
||||
/* istanbul ignore if */
|
||||
if (!sch.serialize)
|
||||
throw new Error("ajv implementation error");
|
||||
return sch.serialize;
|
||||
}
|
||||
_compileParser(sch) {
|
||||
parse_1.default.call(this, sch, sch.schema.definitions || {});
|
||||
/* istanbul ignore if */
|
||||
if (!sch.parse)
|
||||
throw new Error("ajv implementation error");
|
||||
return sch.parse;
|
||||
}
|
||||
}
|
||||
exports.default = Ajv;
|
||||
//# sourceMappingURL=jtd.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"jtd.js","sourceRoot":"","sources":["../lib/jtd.ts"],"names":[],"mappings":";;;AAwBA,+CAA0C;AAClC,qBADD,iBAAU,CACC;AAClB,qDAAqD;AACrD,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,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AC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,CAAiB,CAAA;IAChE,CAAC;IAEO,kBAAkB,CAAI,GAAc;QAC1C,mBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAG,GAAG,CAAC,MAA0B,CAAC,WAAW,IAAI,EAAE,CAAC,CAAA;QACpF,wBAAwB;QACxB,IAAI,CAAC,GAAG,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAC/D,OAAO,GAAG,CAAC,SAAS,CAAA;IACtB,CAAC;IAEO,cAAc,CAAC,GAAc;QACnC,eAAa,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAG,GAAG,CAAC,MAA0B,CAAC,WAAW,IAAI,EAAE,CAAC,CAAA;QAChF,wBAAwB;QACxB,IAAI,CAAC,GAAG,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAC3D,OAAO,GAAG,CAAC,KAAK,CAAA;IAClB,CAAC;CACF;AAxDD,sBAwDC"}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
||||
"description": "Meta-schema for $data reference (JSON AnySchema extension proposal)",
|
||||
"type": "object",
|
||||
"required": ["$data"],
|
||||
"properties": {
|
||||
"$data": {
|
||||
"type": "string",
|
||||
"anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import type Ajv from "../../core";
|
||||
export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv;
|
||||
Generated
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const metaSchema = require("./schema.json");
|
||||
const metaApplicator = require("./meta/applicator.json");
|
||||
const metaContent = require("./meta/content.json");
|
||||
const metaCore = require("./meta/core.json");
|
||||
const metaFormat = require("./meta/format.json");
|
||||
const metaMetadata = require("./meta/meta-data.json");
|
||||
const metaValidation = require("./meta/validation.json");
|
||||
const META_SUPPORT_DATA = ["/properties"];
|
||||
function addMetaSchema2019($data) {
|
||||
;
|
||||
[
|
||||
metaSchema,
|
||||
metaApplicator,
|
||||
metaContent,
|
||||
metaCore,
|
||||
with$data(this, metaFormat),
|
||||
metaMetadata,
|
||||
with$data(this, metaValidation),
|
||||
].forEach((sch) => this.addMetaSchema(sch, undefined, false));
|
||||
return this;
|
||||
function with$data(ajv, sch) {
|
||||
return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
|
||||
}
|
||||
}
|
||||
exports.default = addMetaSchema2019;
|
||||
//# sourceMappingURL=index.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2019-09/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,yDAAwD;AACxD,mDAAkD;AAClD,6CAA4C;AAC5C,iDAAgD;AAChD,sDAAqD;AACrD,yDAAwD;AAExD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,cAAc;QACd,WAAW;QACX,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;QAC3B,YAAY;QACZ,SAAS,CAAC,IAAI,EAAE,cAAc,CAAC;KAChC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAfD,oCAeC"}
|
||||
Generated
Vendored
+53
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2019-09/schema",
|
||||
"$id": "https://json-schema.org/draft/2019-09/meta/applicator",
|
||||
"$vocabulary": {
|
||||
"https://json-schema.org/draft/2019-09/vocab/applicator": true
|
||||
},
|
||||
"$recursiveAnchor": true,
|
||||
|
||||
"title": "Applicator vocabulary meta-schema",
|
||||
"type": ["object", "boolean"],
|
||||
"properties": {
|
||||
"additionalItems": {"$recursiveRef": "#"},
|
||||
"unevaluatedItems": {"$recursiveRef": "#"},
|
||||
"items": {
|
||||
"anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}]
|
||||
},
|
||||
"contains": {"$recursiveRef": "#"},
|
||||
"additionalProperties": {"$recursiveRef": "#"},
|
||||
"unevaluatedProperties": {"$recursiveRef": "#"},
|
||||
"properties": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"$recursiveRef": "#"},
|
||||
"default": {}
|
||||
},
|
||||
"patternProperties": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"$recursiveRef": "#"},
|
||||
"propertyNames": {"format": "regex"},
|
||||
"default": {}
|
||||
},
|
||||
"dependentSchemas": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$recursiveRef": "#"
|
||||
}
|
||||
},
|
||||
"propertyNames": {"$recursiveRef": "#"},
|
||||
"if": {"$recursiveRef": "#"},
|
||||
"then": {"$recursiveRef": "#"},
|
||||
"else": {"$recursiveRef": "#"},
|
||||
"allOf": {"$ref": "#/$defs/schemaArray"},
|
||||
"anyOf": {"$ref": "#/$defs/schemaArray"},
|
||||
"oneOf": {"$ref": "#/$defs/schemaArray"},
|
||||
"not": {"$recursiveRef": "#"}
|
||||
},
|
||||
"$defs": {
|
||||
"schemaArray": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": {"$recursiveRef": "#"}
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2019-09/schema",
|
||||
"$id": "https://json-schema.org/draft/2019-09/meta/content",
|
||||
"$vocabulary": {
|
||||
"https://json-schema.org/draft/2019-09/vocab/content": true
|
||||
},
|
||||
"$recursiveAnchor": true,
|
||||
|
||||
"title": "Content vocabulary meta-schema",
|
||||
|
||||
"type": ["object", "boolean"],
|
||||
"properties": {
|
||||
"contentMediaType": {"type": "string"},
|
||||
"contentEncoding": {"type": "string"},
|
||||
"contentSchema": {"$recursiveRef": "#"}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+57
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2019-09/schema",
|
||||
"$id": "https://json-schema.org/draft/2019-09/meta/core",
|
||||
"$vocabulary": {
|
||||
"https://json-schema.org/draft/2019-09/vocab/core": true
|
||||
},
|
||||
"$recursiveAnchor": true,
|
||||
|
||||
"title": "Core vocabulary meta-schema",
|
||||
"type": ["object", "boolean"],
|
||||
"properties": {
|
||||
"$id": {
|
||||
"type": "string",
|
||||
"format": "uri-reference",
|
||||
"$comment": "Non-empty fragments not allowed.",
|
||||
"pattern": "^[^#]*#?$"
|
||||
},
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"format": "uri"
|
||||
},
|
||||
"$anchor": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$"
|
||||
},
|
||||
"$ref": {
|
||||
"type": "string",
|
||||
"format": "uri-reference"
|
||||
},
|
||||
"$recursiveRef": {
|
||||
"type": "string",
|
||||
"format": "uri-reference"
|
||||
},
|
||||
"$recursiveAnchor": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
},
|
||||
"$vocabulary": {
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"format": "uri"
|
||||
},
|
||||
"additionalProperties": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"$comment": {
|
||||
"type": "string"
|
||||
},
|
||||
"$defs": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"$recursiveRef": "#"},
|
||||
"default": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2019-09/schema",
|
||||
"$id": "https://json-schema.org/draft/2019-09/meta/format",
|
||||
"$vocabulary": {
|
||||
"https://json-schema.org/draft/2019-09/vocab/format": true
|
||||
},
|
||||
"$recursiveAnchor": true,
|
||||
|
||||
"title": "Format vocabulary meta-schema",
|
||||
"type": ["object", "boolean"],
|
||||
"properties": {
|
||||
"format": {"type": "string"}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+37
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2019-09/schema",
|
||||
"$id": "https://json-schema.org/draft/2019-09/meta/meta-data",
|
||||
"$vocabulary": {
|
||||
"https://json-schema.org/draft/2019-09/vocab/meta-data": true
|
||||
},
|
||||
"$recursiveAnchor": true,
|
||||
|
||||
"title": "Meta-data vocabulary meta-schema",
|
||||
|
||||
"type": ["object", "boolean"],
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"type": "string"
|
||||
},
|
||||
"default": true,
|
||||
"deprecated": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
},
|
||||
"readOnly": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
},
|
||||
"writeOnly": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
},
|
||||
"examples": {
|
||||
"type": "array",
|
||||
"items": true
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+90
@@ -0,0 +1,90 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2019-09/schema",
|
||||
"$id": "https://json-schema.org/draft/2019-09/meta/validation",
|
||||
"$vocabulary": {
|
||||
"https://json-schema.org/draft/2019-09/vocab/validation": true
|
||||
},
|
||||
"$recursiveAnchor": true,
|
||||
|
||||
"title": "Validation vocabulary meta-schema",
|
||||
"type": ["object", "boolean"],
|
||||
"properties": {
|
||||
"multipleOf": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"maximum": {
|
||||
"type": "number"
|
||||
},
|
||||
"exclusiveMaximum": {
|
||||
"type": "number"
|
||||
},
|
||||
"minimum": {
|
||||
"type": "number"
|
||||
},
|
||||
"exclusiveMinimum": {
|
||||
"type": "number"
|
||||
},
|
||||
"maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
|
||||
"minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
|
||||
"pattern": {
|
||||
"type": "string",
|
||||
"format": "regex"
|
||||
},
|
||||
"maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
|
||||
"minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
|
||||
"uniqueItems": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
},
|
||||
"maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
|
||||
"minContains": {
|
||||
"$ref": "#/$defs/nonNegativeInteger",
|
||||
"default": 1
|
||||
},
|
||||
"maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
|
||||
"minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
|
||||
"required": {"$ref": "#/$defs/stringArray"},
|
||||
"dependentRequired": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/$defs/stringArray"
|
||||
}
|
||||
},
|
||||
"const": true,
|
||||
"enum": {
|
||||
"type": "array",
|
||||
"items": true
|
||||
},
|
||||
"type": {
|
||||
"anyOf": [
|
||||
{"$ref": "#/$defs/simpleTypes"},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/$defs/simpleTypes"},
|
||||
"minItems": 1,
|
||||
"uniqueItems": true
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"nonNegativeInteger": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"nonNegativeIntegerDefault0": {
|
||||
"$ref": "#/$defs/nonNegativeInteger",
|
||||
"default": 0
|
||||
},
|
||||
"simpleTypes": {
|
||||
"enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
|
||||
},
|
||||
"stringArray": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"uniqueItems": true,
|
||||
"default": []
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2019-09/schema",
|
||||
"$id": "https://json-schema.org/draft/2019-09/schema",
|
||||
"$vocabulary": {
|
||||
"https://json-schema.org/draft/2019-09/vocab/core": true,
|
||||
"https://json-schema.org/draft/2019-09/vocab/applicator": true,
|
||||
"https://json-schema.org/draft/2019-09/vocab/validation": true,
|
||||
"https://json-schema.org/draft/2019-09/vocab/meta-data": true,
|
||||
"https://json-schema.org/draft/2019-09/vocab/format": false,
|
||||
"https://json-schema.org/draft/2019-09/vocab/content": true
|
||||
},
|
||||
"$recursiveAnchor": true,
|
||||
|
||||
"title": "Core and Validation specifications meta-schema",
|
||||
"allOf": [
|
||||
{"$ref": "meta/core"},
|
||||
{"$ref": "meta/applicator"},
|
||||
{"$ref": "meta/validation"},
|
||||
{"$ref": "meta/meta-data"},
|
||||
{"$ref": "meta/format"},
|
||||
{"$ref": "meta/content"}
|
||||
],
|
||||
"type": ["object", "boolean"],
|
||||
"properties": {
|
||||
"definitions": {
|
||||
"$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",
|
||||
"type": "object",
|
||||
"additionalProperties": {"$recursiveRef": "#"},
|
||||
"default": {}
|
||||
},
|
||||
"dependencies": {
|
||||
"$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"",
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+137
@@ -0,0 +1,137 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-06/schema#",
|
||||
"$id": "http://json-schema.org/draft-06/schema#",
|
||||
"title": "Core schema meta-schema",
|
||||
"definitions": {
|
||||
"schemaArray": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": {"$ref": "#"}
|
||||
},
|
||||
"nonNegativeInteger": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"nonNegativeIntegerDefault0": {
|
||||
"allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
|
||||
},
|
||||
"simpleTypes": {
|
||||
"enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
|
||||
},
|
||||
"stringArray": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"uniqueItems": true,
|
||||
"default": []
|
||||
}
|
||||
},
|
||||
"type": ["object", "boolean"],
|
||||
"properties": {
|
||||
"$id": {
|
||||
"type": "string",
|
||||
"format": "uri-reference"
|
||||
},
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"format": "uri"
|
||||
},
|
||||
"$ref": {
|
||||
"type": "string",
|
||||
"format": "uri-reference"
|
||||
},
|
||||
"title": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"type": "string"
|
||||
},
|
||||
"default": {},
|
||||
"examples": {
|
||||
"type": "array",
|
||||
"items": {}
|
||||
},
|
||||
"multipleOf": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"maximum": {
|
||||
"type": "number"
|
||||
},
|
||||
"exclusiveMaximum": {
|
||||
"type": "number"
|
||||
},
|
||||
"minimum": {
|
||||
"type": "number"
|
||||
},
|
||||
"exclusiveMinimum": {
|
||||
"type": "number"
|
||||
},
|
||||
"maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
|
||||
"minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
|
||||
"pattern": {
|
||||
"type": "string",
|
||||
"format": "regex"
|
||||
},
|
||||
"additionalItems": {"$ref": "#"},
|
||||
"items": {
|
||||
"anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
|
||||
"default": {}
|
||||
},
|
||||
"maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
|
||||
"minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
|
||||
"uniqueItems": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
},
|
||||
"contains": {"$ref": "#"},
|
||||
"maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
|
||||
"minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
|
||||
"required": {"$ref": "#/definitions/stringArray"},
|
||||
"additionalProperties": {"$ref": "#"},
|
||||
"definitions": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"$ref": "#"},
|
||||
"default": {}
|
||||
},
|
||||
"properties": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"$ref": "#"},
|
||||
"default": {}
|
||||
},
|
||||
"patternProperties": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"$ref": "#"},
|
||||
"default": {}
|
||||
},
|
||||
"dependencies": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
|
||||
}
|
||||
},
|
||||
"propertyNames": {"$ref": "#"},
|
||||
"const": {},
|
||||
"enum": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"uniqueItems": true
|
||||
},
|
||||
"type": {
|
||||
"anyOf": [
|
||||
{"$ref": "#/definitions/simpleTypes"},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/definitions/simpleTypes"},
|
||||
"minItems": 1,
|
||||
"uniqueItems": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"format": {"type": "string"},
|
||||
"allOf": {"$ref": "#/definitions/schemaArray"},
|
||||
"anyOf": {"$ref": "#/definitions/schemaArray"},
|
||||
"oneOf": {"$ref": "#/definitions/schemaArray"},
|
||||
"not": {"$ref": "#"}
|
||||
},
|
||||
"default": {}
|
||||
}
|
||||
Generated
Vendored
+151
@@ -0,0 +1,151 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "Core schema meta-schema",
|
||||
"definitions": {
|
||||
"schemaArray": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": {"$ref": "#"}
|
||||
},
|
||||
"nonNegativeInteger": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"nonNegativeIntegerDefault0": {
|
||||
"allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
|
||||
},
|
||||
"simpleTypes": {
|
||||
"enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
|
||||
},
|
||||
"stringArray": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"uniqueItems": true,
|
||||
"default": []
|
||||
}
|
||||
},
|
||||
"type": ["object", "boolean"],
|
||||
"properties": {
|
||||
"$id": {
|
||||
"type": "string",
|
||||
"format": "uri-reference"
|
||||
},
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"format": "uri"
|
||||
},
|
||||
"$ref": {
|
||||
"type": "string",
|
||||
"format": "uri-reference"
|
||||
},
|
||||
"$comment": {
|
||||
"type": "string"
|
||||
},
|
||||
"title": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"type": "string"
|
||||
},
|
||||
"default": true,
|
||||
"readOnly": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
},
|
||||
"examples": {
|
||||
"type": "array",
|
||||
"items": true
|
||||
},
|
||||
"multipleOf": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"maximum": {
|
||||
"type": "number"
|
||||
},
|
||||
"exclusiveMaximum": {
|
||||
"type": "number"
|
||||
},
|
||||
"minimum": {
|
||||
"type": "number"
|
||||
},
|
||||
"exclusiveMinimum": {
|
||||
"type": "number"
|
||||
},
|
||||
"maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
|
||||
"minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
|
||||
"pattern": {
|
||||
"type": "string",
|
||||
"format": "regex"
|
||||
},
|
||||
"additionalItems": {"$ref": "#"},
|
||||
"items": {
|
||||
"anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
|
||||
"default": true
|
||||
},
|
||||
"maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
|
||||
"minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
|
||||
"uniqueItems": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
},
|
||||
"contains": {"$ref": "#"},
|
||||
"maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
|
||||
"minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
|
||||
"required": {"$ref": "#/definitions/stringArray"},
|
||||
"additionalProperties": {"$ref": "#"},
|
||||
"definitions": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"$ref": "#"},
|
||||
"default": {}
|
||||
},
|
||||
"properties": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"$ref": "#"},
|
||||
"default": {}
|
||||
},
|
||||
"patternProperties": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"$ref": "#"},
|
||||
"propertyNames": {"format": "regex"},
|
||||
"default": {}
|
||||
},
|
||||
"dependencies": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
|
||||
}
|
||||
},
|
||||
"propertyNames": {"$ref": "#"},
|
||||
"const": true,
|
||||
"enum": {
|
||||
"type": "array",
|
||||
"items": true,
|
||||
"minItems": 1,
|
||||
"uniqueItems": true
|
||||
},
|
||||
"type": {
|
||||
"anyOf": [
|
||||
{"$ref": "#/definitions/simpleTypes"},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/definitions/simpleTypes"},
|
||||
"minItems": 1,
|
||||
"uniqueItems": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"format": {"type": "string"},
|
||||
"contentMediaType": {"type": "string"},
|
||||
"contentEncoding": {"type": "string"},
|
||||
"if": {"$ref": "#"},
|
||||
"then": {"$ref": "#"},
|
||||
"else": {"$ref": "#"},
|
||||
"allOf": {"$ref": "#/definitions/schemaArray"},
|
||||
"anyOf": {"$ref": "#/definitions/schemaArray"},
|
||||
"oneOf": {"$ref": "#/definitions/schemaArray"},
|
||||
"not": {"$ref": "#"}
|
||||
},
|
||||
"default": true
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user