3 var IDENTIFIER = /^[a-z_$][a-z0-9_$\-]*$/i;
4 var customRuleCode = require('./dotjs/custom');
13 * Define custom keyword
15 * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
16 * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
18 function addKeyword(keyword, definition) {
19 /* jshint validthis: true */
20 /* eslint no-shadow: 0 */
21 var RULES = this.RULES;
23 if (RULES.keywords[keyword])
24 throw new Error('Keyword ' + keyword + ' is already defined');
26 if (!IDENTIFIER.test(keyword))
27 throw new Error('Keyword ' + keyword + ' is not a valid identifier');
30 if (definition.macro && definition.valid !== undefined)
31 throw new Error('"valid" option cannot be used with macro keywords');
33 var dataType = definition.type;
34 if (Array.isArray(dataType)) {
35 var i, len = dataType.length;
36 for (i=0; i<len; i++) checkDataType(dataType[i]);
37 for (i=0; i<len; i++) _addRule(keyword, dataType[i], definition);
39 if (dataType) checkDataType(dataType);
40 _addRule(keyword, dataType, definition);
43 var $data = definition.$data === true && this._opts.v5;
44 if ($data && !definition.validate)
45 throw new Error('$data support: "validate" function is not defined');
47 var metaSchema = definition.metaSchema;
53 { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#/definitions/$data' }
57 definition.validateSchema = this.compile(metaSchema, true);
61 RULES.keywords[keyword] = RULES.all[keyword] = true;
64 function _addRule(keyword, dataType, definition) {
66 for (var i=0; i<RULES.length; i++) {
68 if (rg.type == dataType) {
75 ruleGroup = { type: dataType, rules: [] };
76 RULES.push(ruleGroup);
81 definition: definition,
85 ruleGroup.rules.push(rule);
86 RULES.custom[keyword] = rule;
90 function checkDataType(dataType) {
91 if (!RULES.types[dataType]) throw new Error('Unknown type ' + dataType);
99 * @param {String} keyword pre-defined or custom keyword.
100 * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
102 function getKeyword(keyword) {
103 /* jshint validthis: true */
104 var rule = this.RULES.custom[keyword];
105 return rule ? rule.definition : this.RULES.keywords[keyword] || false;
112 * @param {String} keyword pre-defined or custom keyword.
114 function removeKeyword(keyword) {
115 /* jshint validthis: true */
116 var RULES = this.RULES;
117 delete RULES.keywords[keyword];
118 delete RULES.all[keyword];
119 delete RULES.custom[keyword];
120 for (var i=0; i<RULES.length; i++) {
121 var rules = RULES[i].rules;
122 for (var j=0; j<rules.length; j++) {
123 if (rules[j].keyword == keyword) {