@datasworn-community/build-tools 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,80 @@
1
+ import type { JSONSchema7 } from 'json-schema'
2
+ import { Utils } from '@datasworn-community/core'
3
+ import { Keywords } from '../augmentations.js'
4
+ import { DefsKey } from '../const.js'
5
+
6
+ const { compareObjectKeys, dataswornKeyOrder, sortDataswornKeys, sortObjectKeys } =
7
+ Utils
8
+
9
+ const keywordKeys = [...Object.keys(Keywords)]
10
+
11
+ export function isSortableObjectSchema(schema: JSONSchema7) {
12
+ switch (true) {
13
+ // skip non-object schema or dictionary-like object
14
+
15
+ case schema.patternProperties != null:
16
+ return false
17
+ default:
18
+ return true
19
+ }
20
+ }
21
+
22
+ const schemaKeyOrder = [
23
+ '$schema',
24
+ '$id',
25
+ '$ref',
26
+ 'title',
27
+ 'type',
28
+ 'description',
29
+ 'remarks',
30
+ '$comment',
31
+ ...keywordKeys,
32
+ 'default',
33
+ 'examples',
34
+ // constant
35
+ 'const',
36
+ 'enum',
37
+ // string
38
+ 'format',
39
+ 'pattern',
40
+ // number
41
+ 'multipleOf',
42
+ 'minimum',
43
+ 'maximum',
44
+ // array
45
+ 'items',
46
+ 'minItems',
47
+ 'maxItems',
48
+ // object
49
+ 'required',
50
+ 'properties',
51
+ 'patternProperties',
52
+ 'additionalItems',
53
+ 'additionalProperties',
54
+ // union
55
+ 'allOf',
56
+ 'anyOf',
57
+ 'oneOf',
58
+ 'if',
59
+ 'then',
60
+ 'else',
61
+ DefsKey
62
+ ] as const
63
+
64
+ export function sortSchemaKeys<T extends JSONSchema7>(schema: T) {
65
+ const sortedSchema = sortObjectKeys(
66
+ schema as Record<string, unknown>,
67
+ schemaKeyOrder
68
+ ) as T
69
+ if (sortedSchema.properties != null)
70
+ sortedSchema.properties = sortDataswornKeys(
71
+ sortedSchema.properties as Record<string, unknown>
72
+ ) as T['properties']
73
+ if (Array.isArray(sortedSchema.required)) {
74
+ sortedSchema.required = sortedSchema.required.sort((a, b) =>
75
+ compareObjectKeys(a, b, dataswornKeyOrder)
76
+ )
77
+ }
78
+
79
+ return sortedSchema
80
+ }