-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
362 lines (322 loc) · 11.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
'use strict'
let Field = require('./Field.js'),
Type = require('./Type.js')
module.exports = function () {
/** Store types defined by a string */
let simpleTypes = Object.create(null)
/** Store types defined in terms of other ones */
let typedefs = Object.create(null)
/** Store types defined by an object */
let objectTypes = {
objects: [],
types: []
}
/** Store types defined by a callback */
let callbackTypes = {
fns: [],
types: []
}
/** Store types defined by tags */
let taggedTypes = Object.create(null)
/**
* Validate the given value against the given schema
* @param {*} schema
* @param {*} value The value can be altered by the validation
* @param {Object} [options] Validation options
* @returns {boolean} whether the value is valid or nor
* @throw if the schema is invalid
*/
function context(schema, value, options) {
schema = context.parse(schema)
let ret = schema.validate(value, options)
context.lastError = schema.lastError
context.lastErrorMessage = schema.lastErrorMessage
context.lastErrorPath = schema.lastErrorPath
return ret
}
/**
* Store the last error message
* @property {string}
*/
context.lastError = ''
/**
* Parse the given fields definition
* @param {Object} fields
* @returns {Field} The parsed object that can be used with validate()
* @throw if the definition is invalid
*/
context.parse = function (fields) {
let pos, i, extra, field
if (typeof fields === 'string' && fields in simpleTypes) {
// Type defined by a string
return new Field(simpleTypes[fields])
} else if (typeof fields === 'string' && fields in typedefs) {
// Type defined by a string
return typedefs[fields]
} else if ((pos = objectTypes.objects.indexOf(fields)) !== -1) {
// Type defined by an object
return new Field(objectTypes.types[pos])
} else if (typeof fields === 'string' && (field = parseTagged(fields, taggedTypes))) {
return field
}
// Search by a type, executing the callbacks
for (i = 0; i < callbackTypes.fns.length; i++) {
extra = callbackTypes.fns[i](fields, context.parse)
if (extra !== undefined) {
return new Field(callbackTypes.types[i], extra)
}
}
// Nothing found
throw new Error('I couldn\'t understand field definition: ' + fields)
}
/**
* Define a new simple type based on existing types
* @param {string} name
* @param {*} definition
* @param {?checkCallback} preHook
* @param {?checkCallback} postHook
* @throws if definition could not be understood or this type already exists
*/
context.typedef = function (name, definition, preHook = null, postHook = null) {
if (typeof name !== 'string') {
throw new Error('Invalid argument type for name, it must be a string')
}
definition = context.parse(definition)
if (name in simpleTypes || name in typedefs) {
throw new Error('Type ' + name + ' already registered')
}
definition.typedefName = name
definition.preHook = preHook
definition.postHook = postHook
typedefs[name] = definition
}
/**
* @callback parseCallback
* @param {*} definition the value being parsed
* @param {function} parse the root parse function, used to create recursive definitions
* @returns {*} undefined if the definition could not be parsed or a value (any other) to indicate the definition was parsed. The returned value will be sent to checkCallback afterwards
*/
/**
* @callback parseTaggedArgsCallback
* @param {Array<string|number|undefined>} args the parsed arguments
* @returns {*} will be sent to checkCallback afterwards as extra
*/
/**
* @callback checkCallback
* @param {*} value the value to check
* @param {*} extra the result of String.prototype.match if the type is defined with a regexp or the parseCallback result if defined with a function
* @param {Object} options
* @param {string} path a string used in the error message
* @returns {*} optionally return the altered value
* @throws {string} if the value is invalid, the message will be put in the lastError property of the validation schema
*/
/**
* @callback toJSONCallback
* @param {*} extra
* @returns {*}
*/
/**
* @callback toJSONSchemaCallback
* @param {*} extra
* @param {string} componentsPath
* @returns {Object}
*/
/**
* Register a new type
* @param {(string|Object|RegExp|parseCallback)} definition
* @param {string} jsonType One of: number, string, boolean, object, array, *, raw
* @param {checkCallback} [checkFn=function(){}]
* @param {toJSONCallback|string} [toJSON] - Used only by core types
* @param {toJSONSchemaCallback} [toJSONSchema] - Used only by core types
*/
context.registerType = function (definition, jsonType, checkFn, toJSON, toJSONSchema) {
let type = new Type(jsonType, checkFn || (() => {}), toJSON, toJSONSchema)
if (typeof definition === 'string') {
// Simple definition: match a single string
if (definition in simpleTypes || definition in typedefs) {
throw new Error('Type ' + definition + ' already registered')
}
simpleTypes[definition] = type
} else if (definition instanceof RegExp) {
// Defined by a RegExp: create a callback
callbackTypes.fns.push(def2 => {
let match
if (typeof def2 === 'string' && (match = def2.match(definition))) {
return match
}
})
callbackTypes.types.push(type)
} else if (typeof definition === 'object' ||
(typeof definition === 'function' &&
typeof definition.name === 'string' &&
definition.name.match(/^[A-Z]/))) {
// Defined by an Object or a constructor
if (objectTypes.objects.indexOf(definition) !== -1) {
throw new Error('Type ' + definition + ' already registered')
}
objectTypes.objects.push(definition)
objectTypes.types.push(type)
} else if (typeof definition === 'function') {
// Defined by a callback
if (callbackTypes.fns.indexOf(definition) !== -1) {
throw new Error('Type ' + definition + ' already registered')
}
callbackTypes.fns.push(definition)
callbackTypes.types.push(type)
} else {
throw new Error('Invalid definition (' + definition + '), it must be a string, object, regexp or function')
}
}
/**
* Register a new type with an Object, used to register with constructors
* @param {Object} definition
* @param {string} jsonType One of: number, string, boolean, object, array, *, raw
* @param {checkCallback} [checkFn=function(){}]
* @param {toJSONCallback|string} [toJSON] - Used only by core types
* @param {toJSONSchemaCallback} [toJSONSchema] - Used only by core types
*/
context.registerObjectType = function (definition, jsonType, checkFn, toJSON, toJSONSchema) {
let type = new Type(jsonType, checkFn || (() => {}), toJSON, toJSONSchema)
if (objectTypes.objects.indexOf(definition) !== -1) {
throw new Error('Type ' + definition + ' already registered')
}
objectTypes.objects.push(definition)
objectTypes.types.push(type)
}
/**
* Register a new tagged type
* @param {Object} definition
* @param {string} definition.tag
* @param {string} definition.jsonType One of 'number', 'string', 'boolean', 'object' or 'array'
* @param {number} [definition.minArgs=0]
* @param {number} [definition.maxArgs=0] Zero means no limit
* @param {boolean} [definition.sparse=false] true let some args to be skipped: 'tag(,2,,4)'
* @param {boolean} [definition.numeric=false] true will parse all args as numbers
* @param {?parseTaggedArgsCallback} [definition.parseArgs=null] process arguments
* @param {checkCallback} [checkFn=function(){}]
* @param {toJSONCallback|string} [toJSON] - Used only by core types
* @param {toJSONSchemaCallback} [toJSONSchema] - Used only by core types
*/
context.registerTaggedType = function (definition, checkFn, toJSON, toJSONSchema) {
if (!definition || typeof definition !== 'object') {
throw new Error('Invalid definition (' + definition + '), it must be an object')
} else if (!definition.tag || !definition.jsonType) {
throw new Error('definition.tag and definition.jsonType are required')
}
let tag = definition.tag,
type = new Type(definition.jsonType, checkFn || (() => {}), toJSON, toJSONSchema)
if (tag in taggedTypes) {
throw new Error('Tag ' + tag + ' already registered')
}
taggedTypes[tag] = {
type,
minArgs: definition.minArgs || 0,
maxArgs: definition.maxArgs || 0,
sparse: Boolean(definition.sparse),
numeric: Boolean(definition.numeric),
parseArgs: definition.parseArgs
}
}
/**
* Return a reference to all registered types
* You can change it to alter the very inner working of this module
* The two main types are:
* * Hash map: callbackTypes.fns[0], callbackTypes.types[0]
* * Array: callbackTypes.fns[1], callbackTypes.types[1]
* @returns {{simpleTypes: Object.<string, Type>, typedefs: Field, objectTypes: {objects: Object[], types: Type[]}, callbackTypes: {fns: Function[], types: Type[]}}, taggedTypes: Object<string, {type: string, minArgs: number, maxArgs: number, sparse: boolean, numeric: boolean, parseArgs: ?parseTaggedArgsCallback}>}
*/
context.getRegisteredTypes = function () {
return {
simpleTypes,
typedefs,
objectTypes,
callbackTypes,
taggedTypes
}
}
// Static link to global reviver
context.reviver = module.exports.reviver
// Register standard types
require('./types')(context)
return context
}
/**
* Try to parse a string definition as a tagged type
* @private
* @param {string} definition
* @param {Object<String, Object>} taggedTypes
* @returns {?Field}
*/
function parseTagged(definition, taggedTypes) {
let match = definition.match(/^(\w+)(?:\((.*)\))?$/),
tag, args, typeInfo
if (!match) {
return
}
// Get type info
tag = match[1]
typeInfo = taggedTypes[tag]
if (!typeInfo) {
return
}
// Special no-'()' case: only match 'tag' if minArgs is zero
if (typeInfo.minArgs > 0 && match[2] === undefined) {
return
}
// Parse and check args
args = (match[2] || '').trim().split(/\s*,\s*/)
if (args.length === 1 && args[0] === '') {
// Especial empty case
args = []
}
args = args.map((arg, i) => {
if (!arg) {
if (!typeInfo.sparse) {
throw new Error('Missing argument at position ' + i + ' for tagged type ' + tag)
}
return
}
if (typeInfo.numeric) {
arg = Number(arg)
if (isNaN(arg)) {
throw new Error('Invalid numeric argument at position ' + i + ' for tagged type ' + tag)
}
}
return arg
})
args.original = definition
if (args.length < typeInfo.minArgs) {
throw new Error('Too few arguments for tagged type ' + tag)
} else if (typeInfo.maxArgs && args.length > typeInfo.maxArgs) {
throw new Error('Too many arguments for tagged type ' + tag)
}
return new Field(typeInfo.type, typeInfo.parseArgs ? typeInfo.parseArgs(args) : args)
}
let JSONMap = {
$Number: Number,
$String: String,
$Object: Object,
$Array: Array,
$Boolean: Boolean,
$Date: Date
}
/**
* This function is given to be used with JSON.parse() as the 2nd parameter:
* parse(JSON.parse(JSON.stringify(aField), reviver)) would give the aField back
* @param {string} key
* @param {*} value
* @returns {*}
*/
module.exports.reviver = function (key, value) {
let match
if (typeof value === 'string' && value[0] === '$') {
// Special types
if (value.indexOf('$RegExp:') === 0) {
match = value.match(/^\$RegExp:(.*?):(.*)$/)
return new RegExp(match[2], match[1])
} else if (value in JSONMap) {
return JSONMap[value]
}
}
return value
}