Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1913 lines (1664 loc) · 60.2 KB
/
Copy pathindex.js
File metadata and controls
1913 lines (1664 loc) · 60.2 KB
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 { RefResolver } = require('json-schema-ref-resolver')
const { MergeError } = require('@fastify/merge-json-schemas')
const Serializer = require('./lib/serializer')
const Validator = require('./lib/validator')
const { buildProjection } = require('./lib/projection')
const Location = require('./lib/location')
const validate = require('./lib/schema-validator')
const mergeSchemas = require('./lib/merge-schemas')
const DEFAULT_MAX_DEPTH = 100
const NAMED_FRAGMENT_REF = /^#[a-z_][-\w._]*$/i
// Minimum array lengths at which copying into a plain array and
// calling native JSON.stringify beats the generated per-item loop. Measured
// against main with tinybench (alternating rounds, median ops/s, output
// consumed with Buffer.byteLength) on Node 20, 22, 24 and 26 x64.
//
// Node 22+: floats win from 32 elements, but integer-valued elements under a
// `number` schema only break even around 100 on Node 26 (-25% at 32), and a
// `number` schema cannot tell the two apart at build time, so numbers wait
// for 128. Integers win from 512 because small-int ToString is cached, so
// the loop is already cheap below that.
//
// Node 20: JSON.stringify only beats the loop for every element kind from
// ~3e5 (1e5 is machine-dependent), so both kinds wait for 3e5 there.
//
// Strings: the generated loop escapes each element in JS (asString), which
// is far slower than the native serializer, so the copy wins almost
// immediately. Node 22+: from 2 elements for every string length and content
// (2-6x faster from 8 elements on). Node 20: from 32 elements for short
// strings, but only from 128 for long (~120 chars) strings without escapes,
// so Node 20 waits for 128. Measured on Node 20, 22, 24 and 26 (arm64) with
// 8, 40 and 120 char strings, with and without characters to escape.
//
// Booleans never win and keep the loop. The array lookup instead of a
// ternary keeps both branches covered on every Node.
// TODO: drop the Node 20 tier (and this version check) once Node 20 is no
// longer supported.
const nodeMajor = Number.parseInt(process.versions.node, 10)
// V8 13.8 (Node 25+) introduced the side-effect-free JSON.stringify fast path
// that objectMechanism: 'native' relies on.
const PROJECTION_SUPPORTED = nodeMajor >= 25
const PRIMITIVE_FAST_PATH_MIN_LENGTH = [{ integer: 3e5, number: 3e5, string: 128 }, { integer: 512, number: 128, string: 8 }][+(nodeMajor >= 22)]
const STRING_ARRAY_FAST_PATH_MIN_LENGTH = PRIMITIVE_FAST_PATH_MIN_LENGTH.string
const INTEGER_ARRAY_FAST_PATH = { condition: 'Number.isInteger(v)', minLength: PRIMITIVE_FAST_PATH_MIN_LENGTH.integer }
const NUMBER_ARRAY_FAST_PATH = { condition: 'typeof v === \'number\' && v === v', minLength: PRIMITIVE_FAST_PATH_MIN_LENGTH.number }
const singleSchemaKeywords = [
'additionalItems',
'additionalProperties',
'contains',
'else',
'if',
'not',
'propertyNames',
'then'
]
const arraySchemaKeywords = [
'allOf',
'anyOf',
'oneOf'
]
const objectSchemaKeywords = [
'definitions',
'patternProperties',
'properties'
]
const serializerFns = `
const {
asString,
asNumber,
asBoolean,
asDateTime,
asDate,
asTime,
asUnsafeString,
asPlainStringArray
} = serializer
const asInteger = serializer.asInteger.bind(serializer)
`
const validRoundingMethods = new Set([
'floor',
'ceil',
'round',
'trunc'
])
const validLargeArrayMechanisms = new Set([
'default',
'json-stringify'
])
const validObjectMechanisms = new Set([
'default',
'native'
])
// Keywords that do not change the output, so a $ref carrying only these
// can still be dereferenced directly instead of merged with its target.
const IGNORED_REF_SIBLING_KEYWORDS = new Set([
'$ref',
'$comment',
'title',
'description',
'examples',
'deprecated',
'readOnly',
'writeOnly'
])
let schemaIdCounter = 0
function getMaxDepth (options) {
const maxDepth = options.maxDepth === undefined ? DEFAULT_MAX_DEPTH : options.maxDepth
if (!Number.isInteger(maxDepth) || maxDepth < 0 || maxDepth > DEFAULT_MAX_DEPTH) {
throw new Error(`Unsupported max schema depth ${maxDepth}. Expected an integer between 0 and ${DEFAULT_MAX_DEPTH}.`)
}
return maxDepth
}
function schemaDepthError (maxDepth, name) {
const prefix = name ? `"${name}" ` : ''
return new Error(`${prefix}schema exceeds maximum depth of ${maxDepth}`)
}
function assertObjectDepth (schema, maxDepth, name) {
const stack = [{ value: schema, depth: 0, exit: false }]
const path = new WeakSet()
let hasRef = false
while (stack.length > 0) {
const entry = stack.pop()
const value = entry.value
if (typeof value !== 'object' || value === null) continue
// Schema maps and arrays add at most one container between schema nodes.
// Keep dependency traversals within the same stack-safety envelope while
// still allowing maxDepth schema nodes nested through `properties`.
if (entry.depth > maxDepth * 2) {
throw schemaDepthError(maxDepth, name)
}
if (entry.exit) {
path.delete(value)
continue
}
if (path.has(value)) {
throw new Error('schema contains a circular object reference; use $ref instead')
}
path.add(value)
stack.push({ value, depth: entry.depth, exit: true })
for (const key in value) {
const child = value[key]
if (key === '$ref' && typeof child === 'string') {
hasRef = true
}
// Primitive values cannot contain cycles or contribute object depth.
// Avoid allocating stack entries that the next iteration would discard.
if (typeof child === 'object' && child !== null) {
stack.push({ value: child, depth: entry.depth + 1, exit: false })
}
}
}
return hasRef
}
function assertSchemaDepth (schema, maxDepth, name) {
const stack = [{ schema, depth: 0 }]
while (stack.length > 0) {
const entry = stack.pop()
const currentSchema = entry.schema
if (entry.depth > maxDepth) {
throw schemaDepthError(maxDepth, name)
}
if (typeof currentSchema !== 'object' || currentSchema === null) continue
const nestedDepth = entry.depth + 1
for (const keyword of singleSchemaKeywords) {
if (typeof currentSchema[keyword] === 'object' && currentSchema[keyword] !== null) {
stack.push({ schema: currentSchema[keyword], depth: nestedDepth })
}
}
for (const keyword of arraySchemaKeywords) {
const schemas = currentSchema[keyword]
if (Array.isArray(schemas)) {
for (const nestedSchema of schemas) {
stack.push({ schema: nestedSchema, depth: nestedDepth })
}
}
}
const items = currentSchema.items
if (Array.isArray(items)) {
for (const nestedSchema of items) {
stack.push({ schema: nestedSchema, depth: nestedDepth })
}
} else if (typeof items === 'object' && items !== null) {
stack.push({ schema: items, depth: nestedDepth })
}
for (const keyword of objectSchemaKeywords) {
const schemas = currentSchema[keyword]
if (typeof schemas === 'object' && schemas !== null) {
for (const key of Object.keys(schemas)) {
stack.push({ schema: schemas[key], depth: nestedDepth })
}
}
}
const dependencies = currentSchema.dependencies
if (typeof dependencies === 'object' && dependencies !== null) {
for (const key of Object.keys(dependencies)) {
const dependency = dependencies[key]
if (!Array.isArray(dependency)) {
stack.push({ schema: dependency, depth: nestedDepth })
}
}
}
}
}
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 resolveRef (context, location) {
const seen = new Set()
const siblingLocations = []
let depth = 0
while (location.schema.$ref !== undefined) {
const refSchema = location.schema
const ref = refSchema.$ref
const locationRef = location.getSchemaRef()
if (seen.has(locationRef)) {
throw new Error(`Cannot resolve circular reference "${ref}"`)
}
seen.add(locationRef)
if (depth++ > context.maxDepth) {
throw schemaDepthError(context.maxDepth)
}
let hashIndex = ref.indexOf('#')
if (hashIndex === -1) {
hashIndex = ref.length
}
const schemaId = ref.slice(0, hashIndex) || location.schemaId
const jsonPointer = ref.slice(hashIndex) || '#'
const schema = context.refResolver.getSchema(schemaId, jsonPointer)
if (schema === null) {
throw new Error(`Cannot find reference "${ref}"`)
}
const siblingSchema = {}
for (const key in refSchema) {
if (!IGNORED_REF_SIBLING_KEYWORDS.has(key)) {
siblingSchema[key] = refSchema[key]
}
}
if (Object.keys(siblingSchema).length !== 0) {
siblingLocations.unshift(new Location(
cloneOriginSchema(context, siblingSchema, location.schemaId),
location.schemaId,
location.jsonPointer
))
}
location = new Location(schema, schemaId, jsonPointer)
}
if (siblingLocations.length === 0) {
return location
}
// Keyed by content, not by identity: a merged schema is cloned on every
// merge, so a recursive $ref would otherwise be merged again on each level.
const mergedSchemaKey = location.getSchemaRef() + JSON.stringify(siblingLocations.map((l) => l.schema))
let mergedSchemaId = context.mergedRefsIds.get(mergedSchemaKey)
if (mergedSchemaId === undefined) {
mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`
try {
mergeLocations(context, mergedSchemaId, [location, ...siblingLocations])
} catch (err) {
if (!(err instanceof MergeError)) throw err
return location
}
context.mergedRefsIds.set(mergedSchemaKey, mergedSchemaId)
}
return getMergedLocation(context, mergedSchemaId)
}
function getSchemaDependencies (refResolver, schemaId) {
const dependencies = {}
const processed = new Set()
const pending = [schemaId]
while (pending.length > 0) {
const currentSchemaId = pending.pop()
if (processed.has(currentSchemaId)) continue
processed.add(currentSchemaId)
for (const ref of refResolver.getSchemaRefs(currentSchemaId)) {
const dependencySchemaId = ref.schemaId
if (
dependencySchemaId === currentSchemaId ||
dependencies[dependencySchemaId] !== undefined
) continue
dependencies[dependencySchemaId] = refResolver.getSchema(dependencySchemaId)
pending.push(dependencySchemaId)
}
}
return dependencies
}
function getMergedLocation (context, mergedSchemaId) {
const mergedSchema = context.refResolver.getSchema(mergedSchemaId, '#')
return new Location(mergedSchema, mergedSchemaId, '#')
}
function getSchemaId (schema, rootSchemaId) {
if (typeof schema.$id === 'string' && schema.$id.charAt(0) !== '#') {
return schema.$id
}
return rootSchemaId
}
// a schema ref on a comment line of the generated code: a line terminator in a property name
// would end the comment and turn the rest of the name into code. JSON.stringify covers \n and
// \r, the two separators JS also treats as line terminators are escaped by hand
const LINE_SEPARATORS = /[\u2028\u2029]/g
function asComment (schemaRef) {
return JSON.stringify(schemaRef).replace(LINE_SEPARATORS, (c) => '\\u' + c.charCodeAt(0).toString(16))
}
function getSafeSchemaRef (context, location) {
let schemaRef = location.getSchemaRef() || ''
if (schemaRef.startsWith(context.rootSchemaId)) {
schemaRef = schemaRef.replace(context.rootSchemaId, '') || '#'
}
return schemaRef
}
function getValidatorSchemaRef (context, location) {
let schemaRef = location.getSchemaRef()
const schema = location.schema
// A schema that is only a registered $ref can validate against that target
// instead of a JSON-pointer path through the root schema.
if (
typeof schema.$ref !== 'string' ||
Object.keys(schema).length !== 1
) {
return schemaRef
}
const ref = schema.$ref
const hashIndex = ref.indexOf('#')
const refSchemaId = hashIndex === -1 ? ref : ref.slice(0, hashIndex)
const refJsonPointer = hashIndex === -1 ? '' : ref.slice(hashIndex)
const isBareRef = refJsonPointer === '' || refJsonPointer === '#'
const isNamedFragmentRef = NAMED_FRAGMENT_REF.test(refJsonPointer)
const isJsonPointerRef = refJsonPointer.startsWith('#/')
if (
(isBareRef || isNamedFragmentRef || isJsonPointerRef) &&
refSchemaId &&
context.refResolver.hasSchema(refSchemaId)
) {
const refSchema = context.refResolver.getSchema(refSchemaId)
const refSubSchema = isBareRef
? refSchema
: context.refResolver.getSchema(refSchemaId, refJsonPointer)
const hasRelativeSchemaId = (
typeof refSchema.$id === 'string' &&
refSchema.$id.charAt(0) === '#'
)
if (
refSubSchema !== null &&
(!hasRelativeSchemaId || refSchema.$id === refJsonPointer)
) {
schemaRef = refSchemaId + (isBareRef ? '#' : refJsonPointer)
}
}
return schemaRef
}
function build (schema, options) {
options = options || {}
const maxDepth = getMaxDepth(options)
// assertObjectDepth also reports whether any $ref appears; recursive-schema
// detection is only needed when $ref can form cycles.
let hasRef = assertObjectDepth(schema, maxDepth)
assertSchemaDepth(schema, maxDepth)
isValidSchema(schema)
const context = {
functions: [],
functionsCounter: 0,
functionsNamesBySchema: new Map(),
options,
refResolver: new RefResolver(),
rootSchemaId: schema.$id || `__fjs_root_${schemaIdCounter++}`,
validatorSchemasIds: new Set(),
validatorSchemaRefs: new Set(),
mergedSchemasIds: new Map(),
mergedRefsIds: new Map(),
maxDepth,
recursiveSchemas: new Set(),
recursivePaths: new Set(),
buildingSet: new Set(),
largeArraySize: 2e4,
largeArrayMechanism: 'default',
objectMechanism: 'default',
uid: 0
}
const schemaId = getSchemaId(schema, context.rootSchemaId)
if (!context.refResolver.hasSchema(schemaId)) {
context.refResolver.addSchema(schema, context.rootSchemaId)
}
if (options.schema) {
for (const key in options.schema) {
const schema = options.schema[key]
const schemaId = getSchemaId(schema, key)
if (!context.refResolver.hasSchema(schemaId)) {
if (assertObjectDepth(schema, maxDepth, key)) {
hasRef = true
}
assertSchemaDepth(schema, maxDepth, key)
isValidSchema(schema, key)
context.refResolver.addSchema(schema, key)
}
}
}
if (options.rounding) {
if (!validRoundingMethods.has(options.rounding)) {
throw new Error(`Unsupported integer rounding method ${options.rounding}`)
}
}
if (options.largeArrayMechanism) {
if (validLargeArrayMechanisms.has(options.largeArrayMechanism)) {
context.largeArrayMechanism = options.largeArrayMechanism
} else {
throw new Error(`Unsupported large array mechanism ${options.largeArrayMechanism}`)
}
}
if (options.objectMechanism) {
if (validObjectMechanisms.has(options.objectMechanism)) {
context.objectMechanism = options.objectMechanism
} else {
throw new Error(`Unsupported object mechanism ${options.objectMechanism}`)
}
}
if (options.largeArraySize) {
const largeArraySizeType = typeof options.largeArraySize
let parsedNumber
if (largeArraySizeType === 'string' && Number.isFinite((parsedNumber = Number.parseInt(options.largeArraySize, 10)))) {
context.largeArraySize = parsedNumber
} else if (largeArraySizeType === 'number' && Number.isInteger(options.largeArraySize)) {
context.largeArraySize = options.largeArraySize
} else if (largeArraySizeType === 'bigint') {
context.largeArraySize = Number(options.largeArraySize)
} else {
throw new Error(`Unsupported large array size. Expected integer-like, got ${typeof options.largeArraySize} with value ${options.largeArraySize}`)
}
}
const location = new Location(schema, context.rootSchemaId)
// Without $ref, json-pointer paths are unique in a tree walk, so no cycle
// can appear in recursivePaths. Skip the third full-schema traversal.
if (hasRef) {
detectRecursiveSchemas(context, location)
}
// objectMechanism: 'native' projects the input into shape-stable scratch
// objects and delegates to the native JSON.stringify. Only whole schemas
// made of objects, arrays and primitives qualify; anything else falls back
// to the string codegen below, so output never changes for unsupported shapes.
// The projection only pays off where V8 has the side-effect-free
// JSON.stringify fast path (V8 13.8+, Node 25+): on older runtimes the
// string codegen is up to 2x faster, so the option is a no-op there.
let code = null
let projection = null
// `forceProjection` is an internal, undocumented escape hatch used by the
// test suite to exercise the projection on runtimes where it is gated off.
if (context.objectMechanism === 'native' && (options.forceProjection === true || PROJECTION_SUPPORTED)) {
projection = buildProjection(schema)
}
if (projection === null) {
code = buildValue(context, location, 'input')
}
let contextFunctionCode = `
${serializerFns}
const JSON_STR_BEGIN_OBJECT = '{'
const JSON_STR_END_OBJECT = '}'
const JSON_STR_BEGIN_ARRAY = '['
const JSON_STR_END_ARRAY = ']'
const JSON_STR_COMMA = ','
const JSON_STR_COLONS = ':'
const JSON_STR_QUOTE = '"'
const JSON_STR_EMPTY_OBJECT = JSON_STR_BEGIN_OBJECT + JSON_STR_END_OBJECT
const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY
const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE
const JSON_STR_NULL = 'null'
`
// If we have only the invocation of the 'anonymous0' function, we would
// basically just wrap the 'anonymous0' function in the 'main' function and
// and the overhead of the intermediate variable 'json'. We can avoid the
// wrapping and the unnecessary memory allocation by aliasing 'anonymous0' to
// 'main'
if (projection !== null) {
contextFunctionCode += projection
} else if (code === 'json += anonymous0(input)') {
contextFunctionCode += `
${context.functions.join('\n')}
const main = anonymous0
return main
`
} else {
contextFunctionCode += `
function main (input) {
let json = ''
${code}
return json
}
${context.functions.join('\n')}
return main
`
}
const serializer = new Serializer(options)
// Ajv construction dominates tiny build() cost. Only create a Validator when
// generated code needs validator.validate (anyOf/oneOf/if-then-else), or when
// debug mode exposes the instance. Standalone already emits `validator = null`
// when validatorSchemasIds is empty.
const needsValidator =
context.validatorSchemasIds.size > 0 ||
options.mode === 'debug'
const validator = needsValidator
? new Validator(
options.ajv,
options.mode === 'standalone' && options.inlineValidators
)
: null
if (validator !== null) {
for (const schemaId of context.validatorSchemasIds) {
const schema = context.refResolver.getSchema(schemaId)
validator.addSchema(schema, schemaId)
const dependencies = getSchemaDependencies(context.refResolver, schemaId)
for (const [schemaId, schema] of Object.entries(dependencies)) {
validator.addSchema(schema, schemaId)
}
}
if (options.compileValidators) {
validator.compileSchemas(context.validatorSchemaRefs)
}
}
if (options.mode === 'debug') {
return {
validator,
serializer,
code: `validator\nserializer\n${contextFunctionCode}`,
ajv: validator.ajv
}
}
/* eslint no-new-func: "off" */
const contextFunc = new Function('validator', 'serializer', contextFunctionCode)
if (options.mode === 'standalone') {
const buildStandaloneCode = require('./lib/standalone')
return buildStandaloneCode(contextFunc, context, serializer, validator)
}
return contextFunc(validator, serializer)
}
const objectKeywords = [
'properties',
'required',
'additionalProperties',
'patternProperties',
'maxProperties',
'minProperties',
'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) {
for (const keyword of objectKeywords) {
if (keyword in schema) return 'object'
}
for (const keyword of arrayKeywords) {
if (keyword in schema) return 'array'
}
for (const keyword of stringKeywords) {
if (keyword in schema) return 'string'
}
for (const keyword of numberKeywords) {
if (keyword in schema) return 'number'
}
return schema.type
}
function buildExtraObjectPropertiesSerializer (context, location, addComma, objVar) {
const schema = location.schema
const propertiesKeys = Object.keys(schema.properties || {})
let code = `
for (const key of Object.keys(${objVar})) {
if (
${propertiesKeys.length > 0 ? propertiesKeys.map(k => `key === ${JSON.stringify(k)}`).join(' || ') + ' ||' : ''}
${objVar}[key] === undefined ||
typeof ${objVar}[key] === 'function' ||
typeof ${objVar}[key] === 'symbol'
) continue
const value = ${objVar}[key]
`
const patternPropertiesLocation = location.getPropertyLocation('patternProperties')
const patternPropertiesSchema = patternPropertiesLocation.schema
if (patternPropertiesSchema !== undefined) {
for (const propertyKey in patternPropertiesSchema) {
const propertyLocation = patternPropertiesLocation.getPropertyLocation(propertyKey)
code += `
if (/${propertyKey.replace(/\\*\//g, '\\/')}/.test(key)) {
${addComma}
json += asString(key) + JSON_STR_COLONS
${buildValue(context, propertyLocation, 'value')}
continue
}
`
}
}
const additionalPropertiesLocation = location.getPropertyLocation('additionalProperties')
const additionalPropertiesSchema = additionalPropertiesLocation.schema
// `additionalProperties: false` means every property that is not declared in
// `properties` nor matched by `patternProperties` is dropped, so no branch is
// emitted for it. Without this guard the `false` schema reaches buildValue,
// which serializes any boolean schema with `JSON.stringify(value)` and lets
// the property through.
if (additionalPropertiesSchema !== undefined && additionalPropertiesSchema !== false) {
if (additionalPropertiesSchema === true) {
code += `
${addComma}
json += asString(key) + JSON_STR_COLONS + JSON.stringify(value)
`
} else {
const propertyLocation = location.getPropertyLocation('additionalProperties')
code += `
${addComma}
json += asString(key) + JSON_STR_COLONS
${buildValue(context, propertyLocation, 'value')}
`
}
}
code += `
}
`
return code
}
function buildInnerObject (context, location, objVar, isReturnForm) {
const schema = location.schema
const propertiesLocation = location.getPropertyLocation('properties')
const requiredProperties = schema.required || []
// Should serialize required properties first
const propertiesKeys = Object.keys(schema.properties || {}).sort(
(key1, key2) => {
const required1 = requiredProperties.includes(key1)
const required2 = requiredProperties.includes(key2)
return required1 === required2 ? 0 : required1 ? -1 : 1
}
)
let code = ''
for (const key of requiredProperties) {
if (!propertiesKeys.includes(key)) {
const sanitizedKey = JSON.stringify(key)
code += `if (${objVar}[${sanitizedKey}] === undefined) throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')\n`
}
}
const localUid = context.uid++
let addComma = ''
let emptyObjectGuard = null
// propertiesKeys is sorted required-first; the guard checks [0] is required because
// otherwise additionalProperties/patternProperties would emit a stray `{ ,"k":v }`.
if (propertiesKeys.length > 0 && requiredProperties.includes(propertiesKeys[0])) {
// The first property is required, so it always emits (or throws): fold the
// object-open brace into its key prefix. Subsequent properties fold the
// comma into their key prefix the same way, cutting one append per property.
for (let i = 0; i < propertiesKeys.length; i++) {
const key = propertiesKeys[i]
const propertyLocation = propertiesLocation.getPropertyLocation(key)
let resolvedLocation = propertyLocation
if (propertyLocation.schema.$ref) {
resolvedLocation = resolveRef(context, propertyLocation)
}
const sanitizedKey = JSON.stringify(key)
const value = `value_${key.replace(/[^a-zA-Z0-9]/g, '_')}_${context.uid++}`
const defaultValue = resolvedLocation.schema.default
const isRequired = requiredProperties.includes(key)
const keyPrefix = (i === 0 ? '{' : ',') + sanitizedKey + ':'
code += `
const ${value} = ${objVar}[${sanitizedKey}]
if (${value} !== undefined) {
json += ${JSON.stringify(keyPrefix)}
${buildValue(context, resolvedLocation, `${value}`)}
}`
if (defaultValue !== undefined) {
code += ` else {
json += ${JSON.stringify(keyPrefix + JSON.stringify(defaultValue))}
}
`
} else if (isRequired) {
code += ` else {
throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')
}
`
} else {
code += '\n'
}
}
addComma = 'json += JSON_STR_COMMA'
} else {
// No property is guaranteed to emit: fold `{` into whichever property
// emits first, and only emit a bare `{` when none does.
const needsRuntimeComma = propertiesKeys.length > 1 || schema.patternProperties || (schema.additionalProperties !== undefined && schema.additionalProperties !== false)
if (needsRuntimeComma) {
code += `let addComma_${localUid} = false\n`
addComma = `json += addComma_${localUid} ? JSON_STR_COMMA : ((addComma_${localUid} = true), JSON_STR_BEGIN_OBJECT)`
emptyObjectGuard = `if (!addComma_${localUid}) json += JSON_STR_BEGIN_OBJECT\n`
} else if (propertiesKeys.length === 0) {
code += 'json += JSON_STR_BEGIN_OBJECT\n'
}
for (const key of propertiesKeys) {
let propertyLocation = propertiesLocation.getPropertyLocation(key)
if (propertyLocation.schema.$ref) {
propertyLocation = resolveRef(context, propertyLocation)
}
const sanitizedKey = JSON.stringify(key)
const value = `value_${key.replace(/[^a-zA-Z0-9]/g, '_')}_${context.uid++}`
const defaultValue = propertyLocation.schema.default
const isRequired = requiredProperties.includes(key) // Should be false here but good to keep
const keyColon = sanitizedKey + ':'
const addProperty = needsRuntimeComma
? `json += addComma_${localUid} ? ${JSON.stringify(',' + keyColon)} : ((addComma_${localUid} = true), ${JSON.stringify('{' + keyColon)})`
: `json += ${JSON.stringify('{' + keyColon)}`
code += `
const ${value} = ${objVar}[${sanitizedKey}]
if (${value} !== undefined) {
${addProperty}
${buildValue(context, propertyLocation, `${value}`)}
}`
if (defaultValue !== undefined) {
const defaultValueLiteral = JSON.stringify(sanitizedKey + ':' + JSON.stringify(defaultValue))
if (needsRuntimeComma) {
code += ` else {
${addComma}
json += ${defaultValueLiteral}
}
`
} else {
// Single optional property with default: `{` is folded into the
// default literal so the absent branch still opens the object.
code += ` else {
json += ${JSON.stringify('{' + sanitizedKey + ':' + JSON.stringify(defaultValue))}
}
`
}
} else if (isRequired) {
// Should not happen if requiredProperties.length === 0 but safety
code += ` else {
throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')
}
`
} else if (!needsRuntimeComma) {
// Single optional property: `{` is folded into its key, so emit `{`
// when the property is absent.
code += ` else {
json += JSON_STR_BEGIN_OBJECT
}
`
} else {
code += '\n'
}
}
}
if (schema.patternProperties || schema.additionalProperties) {
code += buildExtraObjectPropertiesSerializer(context, location, addComma, objVar)
}
if (emptyObjectGuard !== null) {
code += emptyObjectGuard
}
// Named object serializers can return `json + '}'` directly, saving one
// append + intermediate assignment in the hot per-item path.
code += isReturnForm
? '\nreturn json + JSON_STR_END_OBJECT\n'
: '\njson += JSON_STR_END_OBJECT\n'
return code
}
function mergeLocations (context, mergedSchemaId, mergedLocations) {
for (let i = 0, mergedLocationsLength = mergedLocations.length; i < mergedLocationsLength; i++) {
const location = mergedLocations[i]
const schema = location.schema
if (schema.$ref) {
mergedLocations[i] = resolveRef(context, location)
}
}
const mergedSchemas = []
for (const location of mergedLocations) {
const schema = cloneOriginSchema(context, location.schema, location.schemaId)
delete schema.$id
mergedSchemas.push(schema)
}
const mergedSchema = mergeSchemas(mergedSchemas)
const mergedLocation = new Location(mergedSchema, mergedSchemaId)
context.refResolver.addSchema(mergedSchema, mergedSchemaId)
return mergedLocation
}
function cloneOriginSchema (context, schema, schemaId) {
const clonedSchema = Array.isArray(schema) ? [] : {}
if (
typeof schema.$id === 'string' &&
schema.$id.charAt(0) !== '#'
) {
schemaId = schema.$id
}
const mergedSchemaRef = context.mergedSchemasIds.get(schema)
if (mergedSchemaRef) {
context.mergedSchemasIds.set(clonedSchema, mergedSchemaRef)
}
for (const key in schema) {
let value = schema[key]
if (key === '$ref' && typeof value === 'string' && value.charAt(0) === '#') {
value = schemaId + value
}
if (typeof value === 'object' && value !== null) {
value = cloneOriginSchema(context, value, schemaId)
}
clonedSchema[key] = value
}
return clonedSchema
}
function toJSON (variableName) {
return `(${variableName} && typeof ${variableName}.toJSON === 'function')
? ${variableName}.toJSON()
: ${variableName}
`
}
function buildObject (context, location, input) {
const schema = location.schema
if (context.functionsNamesBySchema.has(schema)) {
const funcName = context.functionsNamesBySchema.get(schema)
return `json += ${funcName}(${input})`
}
const nullable = schema.nullable === true
const schemaId = location.schemaId || ''
const jsonPointer = location.jsonPointer || ''
const fullPath = `${schemaId}#${jsonPointer}`
if (context.recursivePaths.has(fullPath) || context.buildingSet.has(schema) || schemaId !== '') {
const functionName = generateFuncName(context)
context.functionsNamesBySchema.set(schema, functionName)
const schemaRef = getSafeSchemaRef(context, location)
const functionCode = `
// ${asComment(schemaRef)}
function ${functionName} (input) {
const obj = ${toJSON('input')}
if (obj === null) return ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_OBJECT'}
let json = ''
${buildInnerObject(context, location, 'obj', true)}
}
`
context.functions.push(functionCode)