-
-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathindex.js
1006 lines (864 loc) · 27 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
/* eslint no-prototype-builtins: 0 */
const merge = require('@fastify/deepmerge')()
const clone = require('rfdc')({ proto: true })
const fjsCloned = Symbol('fast-json-stringify.cloned')
const { randomUUID } = require('crypto')
const validate = require('./schema-validator')
const Serializer = require('./serializer')
const buildAjv = require('./ajv')
let largeArraySize = 2e4
let largeArrayMechanism = 'default'
const validLargeArrayMechanisms = [
'default',
'json-stringify'
]
const addComma = `
if (addComma) {
json += ','
} else {
addComma = true
}
`
function isValidSchema (schema, name) {
if (!validate(schema)) {
if (name) {
name = `"${name}" `
} else {
name = ''
}
const first = validate.errors[0]
const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`)
err.errors = isValidSchema.errors
throw err
}
}
function mergeLocation (location, key) {
return {
schema: location.schema[key],
schemaId: location.schemaId,
jsonPointer: location.jsonPointer + '/' + key
}
}
function resolveRef (location, ref) {
let hashIndex = ref.indexOf('#')
if (hashIndex === -1) {
hashIndex = ref.length
}
const schemaId = ref.slice(0, hashIndex) || location.schemaId
const jsonPointer = ref.slice(hashIndex) || '#'
const schemaRef = schemaId + jsonPointer
let ajvSchema
try {
ajvSchema = ajvInstance.getSchema(schemaRef)
} catch (error) {
throw new Error(`Cannot find reference "${ref}"`)
}
if (ajvSchema === undefined) {
throw new Error(`Cannot find reference "${ref}"`)
}
const schema = ajvSchema.schema
if (schema.$ref !== undefined) {
return resolveRef({ schema, schemaId, jsonPointer }, schema.$ref)
}
return { schema, schemaId, jsonPointer }
}
const arrayItemsReferenceSerializersMap = new Map()
const objectReferenceSerializersMap = new Map()
let rootSchemaId = null
let ajvInstance = null
let contextFunctions = null
function build (schema, options) {
schema = clone(schema)
arrayItemsReferenceSerializersMap.clear()
objectReferenceSerializersMap.clear()
contextFunctions = []
options = options || {}
ajvInstance = buildAjv(options.ajv)
rootSchemaId = schema.$id || randomUUID()
isValidSchema(schema)
extendDateTimeType(schema)
ajvInstance.addSchema(schema, rootSchemaId)
if (options.schema) {
const externalSchemas = clone(options.schema)
for (const key of Object.keys(externalSchemas)) {
const externalSchema = externalSchemas[key]
isValidSchema(externalSchema, key)
extendDateTimeType(externalSchema)
let schemaKey = externalSchema.$id || key
if (externalSchema.$id !== undefined && externalSchema.$id[0] === '#') {
schemaKey = key + externalSchema.$id // relative URI
}
if (ajvInstance.getSchema(schemaKey) === undefined) {
ajvInstance.addSchema(externalSchema, schemaKey)
}
}
}
if (options.rounding) {
if (!['floor', 'ceil', 'round'].includes(options.rounding)) {
throw new Error(`Unsupported integer rounding method ${options.rounding}`)
}
}
if (options.largeArrayMechanism) {
if (validLargeArrayMechanisms.includes(options.largeArrayMechanism)) {
largeArrayMechanism = options.largeArrayMechanism
} else {
throw new Error(`Unsupported large array mechanism ${options.rounding}`)
}
}
if (options.largeArraySize) {
if (!Number.isNaN(Number.parseInt(options.largeArraySize, 10))) {
largeArraySize = options.largeArraySize
} else {
throw new Error(`Unsupported large array size. Expected integer-like, got ${options.largeArraySize}`)
}
}
const serializer = new Serializer(options)
const location = { schema, schemaId: rootSchemaId, jsonPointer: '#' }
const code = buildValue(location, 'input')
const contextFunctionCode = `
function main (input) {
let json = ''
${code}
return json
}
${contextFunctions.join('\n')}
return main
`
const dependenciesName = ['ajv', 'serializer', contextFunctionCode]
if (options.debugMode) {
options.mode = 'debug'
}
if (options.mode === 'debug') {
return { code: dependenciesName.join('\n'), ajv: ajvInstance }
}
if (options.mode === 'standalone') {
// lazy load
const buildStandaloneCode = require('./standalone')
return buildStandaloneCode(options, ajvInstance, contextFunctionCode)
}
/* eslint no-new-func: "off" */
const contextFunc = new Function('ajv', 'serializer', contextFunctionCode)
const stringifyFunc = contextFunc(ajvInstance, serializer)
ajvInstance = null
rootSchemaId = null
contextFunctions = null
arrayItemsReferenceSerializersMap.clear()
objectReferenceSerializersMap.clear()
return stringifyFunc
}
const objectKeywords = [
'maxProperties',
'minProperties',
'required',
'properties',
'patternProperties',
'additionalProperties',
'dependencies'
]
const arrayKeywords = [
'items',
'additionalItems',
'maxItems',
'minItems',
'uniqueItems',
'contains'
]
const stringKeywords = [
'maxLength',
'minLength',
'pattern'
]
const numberKeywords = [
'multipleOf',
'maximum',
'exclusiveMaximum',
'minimum',
'exclusiveMinimum'
]
/**
* Infer type based on keyword in order to generate optimized code
* https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6
*/
function inferTypeByKeyword (schema) {
// eslint-disable-next-line
for (var keyword of objectKeywords) {
if (keyword in schema) return 'object'
}
// eslint-disable-next-line
for (var keyword of arrayKeywords) {
if (keyword in schema) return 'array'
}
// eslint-disable-next-line
for (var keyword of stringKeywords) {
if (keyword in schema) return 'string'
}
// eslint-disable-next-line
for (var keyword of numberKeywords) {
if (keyword in schema) return 'number'
}
return schema.type
}
function addPatternProperties (location) {
const schema = location.schema
const pp = schema.patternProperties
let code = `
var properties = ${JSON.stringify(schema.properties)} || {}
var keys = Object.keys(obj)
for (var i = 0; i < keys.length; i++) {
if (properties[keys[i]]) continue
`
const patternPropertiesLocation = mergeLocation(location, 'patternProperties')
Object.keys(pp).forEach((regex) => {
let ppLocation = mergeLocation(patternPropertiesLocation, regex)
if (pp[regex].$ref) {
ppLocation = resolveRef(ppLocation, pp[regex].$ref)
pp[regex] = ppLocation.schema
}
try {
RegExp(regex)
} catch (err) {
throw new Error(`${err.message}. Found at ${regex} matching ${JSON.stringify(pp[regex])}`)
}
const valueCode = buildValue(ppLocation, 'obj[keys[i]]')
code += `
if (/${regex.replace(/\\*\//g, '\\/')}/.test(keys[i])) {
${addComma}
json += serializer.asString(keys[i]) + ':'
${valueCode}
continue
}
`
})
if (schema.additionalProperties) {
code += additionalProperty(location)
}
code += `
}
`
return code
}
function additionalProperty (location) {
const ap = location.schema.additionalProperties
let code = ''
if (ap === true) {
code += `
if (obj[keys[i]] !== undefined && typeof obj[keys[i]] !== 'function' && typeof obj[keys[i]] !== 'symbol') {
${addComma}
json += serializer.asString(keys[i]) + ':' + JSON.stringify(obj[keys[i]])
}
`
return code
}
let apLocation = mergeLocation(location, 'additionalProperties')
if (apLocation.schema.$ref) {
apLocation = resolveRef(apLocation, apLocation.schema.$ref)
}
const valueCode = buildValue(apLocation, 'obj[keys[i]]')
code += `
${addComma}
json += serializer.asString(keys[i]) + ':'
${valueCode}
`
return code
}
function addAdditionalProperties (location) {
return `
var properties = ${JSON.stringify(location.schema.properties)} || {}
var keys = Object.keys(obj)
for (var i = 0; i < keys.length; i++) {
if (properties[keys[i]]) continue
${additionalProperty(location)}
}
`
}
function buildCode (location) {
if (location.schema.$ref) {
location = resolveRef(location, location.schema.$ref)
}
const schema = location.schema
const required = schema.required || []
let code = ''
const propertiesLocation = mergeLocation(location, 'properties')
Object.keys(schema.properties || {}).forEach((key) => {
let propertyLocation = mergeLocation(propertiesLocation, key)
if (schema.properties[key].$ref) {
propertyLocation = resolveRef(location, schema.properties[key].$ref)
schema.properties[key] = propertyLocation.schema
}
const sanitized = JSON.stringify(key)
const asString = JSON.stringify(sanitized)
// Using obj['key'] !== undefined instead of obj.hasOwnProperty(prop) for perf reasons,
// see https://github.com/mcollina/fast-json-stringify/pull/3 for discussion.
code += `
if (obj[${sanitized}] !== undefined) {
${addComma}
json += ${asString} + ':'
`
code += buildValue(propertyLocation, `obj[${JSON.stringify(key)}]`)
const defaultValue = schema.properties[key].default
if (defaultValue !== undefined) {
code += `
} else {
${addComma}
json += ${asString} + ':' + ${JSON.stringify(JSON.stringify(defaultValue))}
`
} else if (required.includes(key)) {
code += `
} else {
throw new Error('${sanitized} is required!')
`
}
code += `
}
`
})
for (const requiredProperty of required) {
if (schema.properties && schema.properties[requiredProperty] !== undefined) continue
code += `if (obj['${requiredProperty}'] === undefined) throw new Error('"${requiredProperty}" is required!')\n`
}
return code
}
function mergeAllOfSchema (location, schema, mergedSchema) {
const allOfLocation = mergeLocation(location, 'allOf')
for (let i = 0; i < schema.allOf.length; i++) {
let allOfSchema = schema.allOf[i]
if (allOfSchema.$ref) {
const allOfSchemaLocation = mergeLocation(allOfLocation, i)
allOfSchema = resolveRef(allOfSchemaLocation, allOfSchema.$ref).schema
}
let allOfSchemaType = allOfSchema.type
if (allOfSchemaType === undefined) {
allOfSchemaType = inferTypeByKeyword(allOfSchema)
}
if (allOfSchemaType !== undefined) {
if (
mergedSchema.type !== undefined &&
mergedSchema.type !== allOfSchemaType
) {
throw new Error('allOf schemas have different type values')
}
mergedSchema.type = allOfSchemaType
}
if (allOfSchema.format !== undefined) {
if (
mergedSchema.format !== undefined &&
mergedSchema.format !== allOfSchema.format
) {
throw new Error('allOf schemas have different format values')
}
mergedSchema.format = allOfSchema.format
}
if (allOfSchema.nullable !== undefined) {
if (
mergedSchema.nullable !== undefined &&
mergedSchema.nullable !== allOfSchema.nullable
) {
throw new Error('allOf schemas have different nullable values')
}
mergedSchema.nullable = allOfSchema.nullable
}
if (allOfSchema.properties !== undefined) {
if (mergedSchema.properties === undefined) {
mergedSchema.properties = {}
}
Object.assign(mergedSchema.properties, allOfSchema.properties)
}
if (allOfSchema.additionalProperties !== undefined) {
if (mergedSchema.additionalProperties === undefined) {
mergedSchema.additionalProperties = {}
}
Object.assign(mergedSchema.additionalProperties, allOfSchema.additionalProperties)
}
if (allOfSchema.patternProperties !== undefined) {
if (mergedSchema.patternProperties === undefined) {
mergedSchema.patternProperties = {}
}
Object.assign(mergedSchema.patternProperties, allOfSchema.patternProperties)
}
if (allOfSchema.required !== undefined) {
if (mergedSchema.required === undefined) {
mergedSchema.required = []
}
mergedSchema.required.push(...allOfSchema.required)
}
if (allOfSchema.oneOf !== undefined) {
if (mergedSchema.oneOf === undefined) {
mergedSchema.oneOf = []
}
mergedSchema.oneOf.push(...allOfSchema.oneOf)
}
if (allOfSchema.anyOf !== undefined) {
if (mergedSchema.anyOf === undefined) {
mergedSchema.anyOf = []
}
mergedSchema.anyOf.push(...allOfSchema.anyOf)
}
if (allOfSchema.fjs_type !== undefined) {
if (
mergedSchema.fjs_type !== undefined &&
mergedSchema.fjs_type !== allOfSchema.fjs_type
) {
throw new Error('allOf schemas have different fjs_type values')
}
mergedSchema.fjs_type = allOfSchema.fjs_type
}
if (allOfSchema.allOf !== undefined) {
mergeAllOfSchema(location, allOfSchema, mergedSchema)
}
}
delete mergedSchema.allOf
mergedSchema.$id = `merged_${randomUUID()}`
ajvInstance.addSchema(mergedSchema)
location.schemaId = mergedSchema.$id
location.jsonPointer = '#'
}
function buildInnerObject (location) {
const schema = location.schema
let code = buildCode(location)
if (schema.patternProperties) {
code += addPatternProperties(location)
} else if (schema.additionalProperties && !schema.patternProperties) {
code += addAdditionalProperties(location)
}
return code
}
function addIfThenElse (location) {
const schema = merge({}, location.schema)
const thenSchema = schema.then
const elseSchema = schema.else || { additionalProperties: true }
delete schema.if
delete schema.then
delete schema.else
const ifLocation = mergeLocation(location, 'if')
const ifSchemaRef = ifLocation.schemaId + ifLocation.jsonPointer
let code = `
if (ajv.validate("${ifSchemaRef}", obj)) {
`
const thenLocation = mergeLocation(location, 'then')
thenLocation.schema = merge(schema, thenSchema)
if (thenSchema.if && thenSchema.then) {
code += addIfThenElse(thenLocation)
} else {
code += buildInnerObject(thenLocation)
}
code += `
}
`
const elseLocation = mergeLocation(location, 'else')
elseLocation.schema = merge(schema, elseSchema)
code += `
else {
`
if (elseSchema.if && elseSchema.then) {
code += addIfThenElse(elseLocation)
} else {
code += buildInnerObject(elseLocation)
}
code += `
}
`
return code
}
function toJSON (variableName) {
return `(${variableName} && typeof ${variableName}.toJSON === 'function')
? ${variableName}.toJSON()
: ${variableName}
`
}
function buildObject (location) {
const schema = location.schema
if (objectReferenceSerializersMap.has(schema)) {
return objectReferenceSerializersMap.get(schema)
}
const functionName = generateFuncName()
objectReferenceSerializersMap.set(schema, functionName)
const schemaId = location.schemaId === rootSchemaId ? '' : location.schemaId
let functionCode = `
function ${functionName} (input) {
// ${schemaId + location.jsonPointer}
`
if (schema.nullable) {
functionCode += `
if (input === null) {
return 'null';
}
`
}
functionCode += `
var obj = ${toJSON('input')}
var json = '{'
var addComma = false
`
if (schema.if && schema.then) {
functionCode += addIfThenElse(location)
} else {
functionCode += buildInnerObject(location)
}
functionCode += `
json += '}'
return json
}
`
contextFunctions.push(functionCode)
return functionName
}
function buildArray (location) {
let schema = location.schema
// default to any items type
if (!schema.items) {
schema.items = {}
}
let itemsLocation = mergeLocation(location, 'items')
if (schema.items.$ref) {
if (!schema[fjsCloned]) {
location.schema = clone(location.schema)
schema = location.schema
schema[fjsCloned] = true
}
location = resolveRef(location, schema.items.$ref)
itemsLocation = location
schema.items = location.schema
}
if (arrayItemsReferenceSerializersMap.has(schema.items)) {
return arrayItemsReferenceSerializersMap.get(schema.items)
}
const functionName = generateFuncName()
arrayItemsReferenceSerializersMap.set(schema.items, functionName)
const schemaId = location.schemaId === rootSchemaId ? '' : location.schemaId
let functionCode = `
function ${functionName} (obj) {
// ${schemaId + location.jsonPointer}
`
if (schema.nullable) {
functionCode += `
if (obj === null) {
return 'null';
}
`
}
functionCode += `
if (!Array.isArray(obj)) {
throw new TypeError(\`The value '$\{obj}' does not match schema definition.\`)
}
const arrayLength = obj.length
`
if (!schema.additionalItems) {
functionCode += `
if (arrayLength > ${schema.items.length}) {
throw new Error(\`Item at ${schema.items.length} does not match schema definition.\`)
}
`
}
if (largeArrayMechanism !== 'default') {
if (largeArrayMechanism === 'json-stringify') {
functionCode += `if (arrayLength && arrayLength >= ${largeArraySize}) return JSON.stringify(obj)\n`
} else {
throw new Error(`Unsupported large array mechanism ${largeArrayMechanism}`)
}
}
functionCode += `
let jsonOutput = ''
`
if (Array.isArray(schema.items)) {
for (let i = 0; i < schema.items.length; i++) {
const item = schema.items[i]
const tmpRes = buildValue(mergeLocation(itemsLocation, i), `obj[${i}]`)
functionCode += `
if (${i} < arrayLength) {
if (${buildArrayTypeCondition(item.type, `[${i}]`)}) {
let json = ''
${tmpRes}
jsonOutput += json
if (${i} < arrayLength - 1) {
jsonOutput += ','
}
} else {
throw new Error(\`Item at ${i} does not match schema definition.\`)
}
}
`
}
if (schema.additionalItems) {
functionCode += `
for (let i = ${schema.items.length}; i < arrayLength; i++) {
let json = JSON.stringify(obj[i])
jsonOutput += json
if (i < arrayLength - 1) {
jsonOutput += ','
}
}`
}
} else {
const code = buildValue(itemsLocation, 'obj[i]')
functionCode += `
for (let i = 0; i < arrayLength; i++) {
let json = ''
${code}
jsonOutput += json
if (i < arrayLength - 1) {
jsonOutput += ','
}
}`
}
functionCode += `
return \`[\${jsonOutput}]\`
}`
contextFunctions.push(functionCode)
return functionName
}
function buildArrayTypeCondition (type, accessor) {
let condition
switch (type) {
case 'null':
condition = `obj${accessor} === null`
break
case 'string':
condition = `typeof obj${accessor} === 'string'`
break
case 'integer':
condition = `Number.isInteger(obj${accessor})`
break
case 'number':
condition = `Number.isFinite(obj${accessor})`
break
case 'boolean':
condition = `typeof obj${accessor} === 'boolean'`
break
case 'object':
condition = `obj${accessor} && typeof obj${accessor} === 'object' && obj${accessor}.constructor === Object`
break
case 'array':
condition = `Array.isArray(obj${accessor})`
break
default:
if (Array.isArray(type)) {
const conditions = type.map((subType) => {
return buildArrayTypeCondition(subType, accessor)
})
condition = `(${conditions.join(' || ')})`
} else {
throw new Error(`${type} unsupported`)
}
}
return condition
}
let genFuncNameCounter = 0
function generateFuncName () {
return 'anonymous' + genFuncNameCounter++
}
function buildValue (location, input) {
let schema = location.schema
if (typeof schema === 'boolean') {
return `json += JSON.stringify(${input})`
}
if (schema.$ref) {
location = resolveRef(location, schema.$ref)
schema = location.schema
}
if (schema.type === undefined) {
const inferredType = inferTypeByKeyword(schema)
if (inferredType) {
schema.type = inferredType
}
}
if (schema.allOf) {
const mergedSchema = clone(schema)
mergeAllOfSchema(location, schema, mergedSchema)
schema = mergedSchema
location.schema = mergedSchema
}
let type = schema.type
const nullable = schema.nullable === true
let code = ''
let funcName
if (schema.fjs_type === 'string' && schema.format === undefined && Array.isArray(schema.type) && schema.type.length === 2) {
type = 'string'
}
switch (type) {
case 'null':
code += 'json += serializer.asNull()'
break
case 'string': {
funcName = nullable ? 'serializer.asStringNullable.bind(serializer)' : 'serializer.asString.bind(serializer)'
code += `json += ${funcName}(${input})`
break
}
case 'integer':
funcName = nullable ? 'serializer.asIntegerNullable.bind(serializer)' : 'serializer.asInteger.bind(serializer)'
code += `json += ${funcName}(${input})`
break
case 'number':
funcName = nullable ? 'serializer.asNumberNullable.bind(serializer)' : 'serializer.asNumber.bind(serializer)'
code += `json += ${funcName}(${input})`
break
case 'boolean':
funcName = nullable ? 'serializer.asBooleanNullable.bind(serializer)' : 'serializer.asBoolean.bind(serializer)'
code += `json += ${funcName}(${input})`
break
case 'object':
if (schema.format === 'date-time') {
funcName = nullable ? 'serializer.asDateTimeNullable.bind(serializer)' : 'serializer.asDateTime.bind(serializer)'
} else if (schema.format === 'date') {
funcName = nullable ? 'serializer.asDateNullable.bind(serializer)' : 'serializer.asDate.bind(serializer)'
} else if (schema.format === 'time') {
funcName = nullable ? 'serializer.asTimeNullable.bind(serializer)' : 'serializer.asTime.bind(serializer)'
} else {
funcName = buildObject(location)
}
code += `json += ${funcName}(${input})`
break
case 'array':
funcName = buildArray(location)
code += `json += ${funcName}(${input})`
break
case undefined:
if (schema.anyOf || schema.oneOf) {
// beware: dereferenceOfRefs has side effects and changes schema.anyOf
const type = schema.anyOf ? 'anyOf' : 'oneOf'
const anyOfLocation = mergeLocation(location, type)
for (let index = 0; index < location.schema[type].length; index++) {
const optionLocation = mergeLocation(anyOfLocation, index)
const schemaRef = optionLocation.schemaId + optionLocation.jsonPointer
const nestedResult = buildValue(optionLocation, input)
code += `
${index === 0 ? 'if' : 'else if'}(ajv.validate("${schemaRef}", ${input}))
${nestedResult}
`
}
code += `
else throw new Error(\`The value $\{JSON.stringify(${input})} does not match schema definition.\`)
`
} else if (isEmpty(schema)) {
code += `
json += JSON.stringify(${input})
`
} else if ('const' in schema) {
code += `
if(ajv.validate(${JSON.stringify(schema)}, ${input}))
json += '${JSON.stringify(schema.const)}'
else
throw new Error(\`Item $\{JSON.stringify(${input})} does not match schema definition.\`)
`
} else if (schema.type === undefined) {
code += `
json += JSON.stringify(${input})
`
} else {
throw new Error(`${schema.type} unsupported`)
}
break
default:
if (Array.isArray(type)) {
let sortedTypes = type
const nullable = schema.nullable === true || type.includes('null')
if (nullable) {
sortedTypes = sortedTypes.filter(type => type !== 'null')
code += `
if (${input} === null) {
json += null
} else {`
}
const locationClone = clone(location)
sortedTypes.forEach((type, index) => {
const statement = index === 0 ? 'if' : 'else if'
locationClone.schema.type = type
const nestedResult = buildValue(locationClone, input)
switch (type) {
case 'string': {
code += `
${statement}(${input} === null || typeof ${input} === "${type}" || ${input} instanceof RegExp || (typeof ${input} === "object" && Object.prototype.hasOwnProperty.call(${input}, "toString")))
${nestedResult}
`
break
}
case 'array': {
code += `
${statement}(Array.isArray(${input}))
${nestedResult}
`
break
}
case 'integer': {
code += `
${statement}(Number.isInteger(${input}) || ${input} === null)
${nestedResult}
`
break
}
case 'object': {
if (schema.fjs_type) {
code += `
${statement}(${input} instanceof Date || ${input} === null)
${nestedResult}
`
} else {
code += `
${statement}(typeof ${input} === "object" || ${input} === null)
${nestedResult}
`
}
break
}
default: {
code += `
${statement}(typeof ${input} === "${type}" || ${input} === null)
${nestedResult}
`
break
}
}
})
code += `
else throw new Error(\`The value $\{JSON.stringify(${input})} does not match schema definition.\`)
`
if (nullable) {
code += `
}
`
}
} else {
throw new Error(`${type} unsupported`)
}
}
return code
}
// Ajv does not support js date format. In order to properly validate objects containing a date,
// it needs to replace all occurrences of the string date format with a custom keyword fjs_type.
// (see https://github.com/fastify/fast-json-stringify/pull/441)
function extendDateTimeType (schema) {
if (schema === null) return
if (schema.type === 'string') {
schema.fjs_type = 'string'
schema.type = ['string', 'object']
} else if (
Array.isArray(schema.type) &&
schema.type.includes('string') &&
!schema.type.includes('object')
) {
schema.fjs_type = 'string'
schema.type.push('object')
}
for (const property in schema) {
if (typeof schema[property] === 'object') {
extendDateTimeType(schema[property])
}
}
}
function isEmpty (schema) {
// eslint-disable-next-line
for (var key in schema) {
if (Object.prototype.hasOwnProperty.call(schema, key) && schema[key] !== undefined) {
return false
}
}
return true
}
module.exports = build
module.exports.validLargeArrayMechanisms = validLargeArrayMechanisms