@amritk/helpers 0.2.1 → 0.3.0

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.
Files changed (39) hide show
  1. package/dist/build-dynamic-ref-map.js +5 -3
  2. package/dist/derive-root-type-name.d.ts +20 -0
  3. package/dist/derive-root-type-name.js +19 -0
  4. package/dist/generate-type-definition.js +5 -3
  5. package/dist/has-ref.d.ts +4 -0
  6. package/dist/has-ref.js +7 -0
  7. package/dist/schema-guards.d.ts +1 -5
  8. package/dist/schema-guards.js +5 -3
  9. package/package.json +15 -3
  10. package/src/build-dynamic-ref-map.test.ts +65 -0
  11. package/src/build-dynamic-ref-map.ts +42 -0
  12. package/src/derive-root-type-name.test.ts +42 -0
  13. package/src/derive-root-type-name.ts +42 -0
  14. package/src/extract-refs.test.ts +183 -0
  15. package/src/extract-refs.ts +73 -0
  16. package/src/generate-type-definition.test.ts +1210 -0
  17. package/src/generate-type-definition.ts +487 -0
  18. package/src/has-ref.ts +10 -0
  19. package/src/is-object.test.ts +65 -0
  20. package/src/is-object.ts +15 -0
  21. package/src/parse-documentation.test.ts +313 -0
  22. package/src/parse-documentation.ts +173 -0
  23. package/src/ref-to-filename.test.ts +64 -0
  24. package/src/ref-to-filename.ts +116 -0
  25. package/src/ref-to-name.test.ts +48 -0
  26. package/src/ref-to-name.ts +38 -0
  27. package/src/resolve-dynamic-refs.test.ts +94 -0
  28. package/src/resolve-dynamic-refs.ts +48 -0
  29. package/src/resolve-ref.test.ts +186 -0
  30. package/src/resolve-ref.ts +82 -0
  31. package/src/safe-accessor.test.ts +41 -0
  32. package/src/safe-accessor.ts +48 -0
  33. package/src/schema-guards.test.ts +406 -0
  34. package/src/schema-guards.ts +160 -0
  35. package/src/upgrade-draft07-schema.ts +179 -0
  36. package/src/validate-array.test.ts +52 -0
  37. package/src/validate-array.ts +15 -0
  38. package/src/validate-record.test.ts +56 -0
  39. package/src/validate-record.ts +19 -0
@@ -0,0 +1,48 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { refToName } from './ref-to-name'
4
+
5
+ describe('ref-to-name', () => {
6
+ it('converts simple ref to PascalCase', () => {
7
+ expect(refToName('#/$defs/contact')).toBe('ContactObject')
8
+ })
9
+
10
+ it('converts kebab-case ref to PascalCase', () => {
11
+ expect(refToName('#/$defs/server-variable')).toBe('ServerVariableObject')
12
+ })
13
+
14
+ it('converts multi-word kebab-case ref to PascalCase', () => {
15
+ expect(refToName('#/$defs/external-documentation')).toBe('ExternalDocumentationObject')
16
+ })
17
+
18
+ it('handles refs with multiple path segments', () => {
19
+ expect(refToName('#/components/schemas/user-profile')).toBe('UserProfileObject')
20
+ })
21
+
22
+ it('handles single word refs', () => {
23
+ expect(refToName('#/$defs/info')).toBe('InfoObject')
24
+ })
25
+
26
+ it('handles refs with numbers', () => {
27
+ expect(refToName('#/$defs/oauth2-flow')).toBe('Oauth2FlowObject')
28
+ })
29
+
30
+ it('converts uppercase acronym keys to PascalCase via kebab normalization', () => {
31
+ expect(refToName('#/$defs/APIKey')).toBe('ApiKeyObject')
32
+ })
33
+
34
+ it('derives type name from a URI ref', () => {
35
+ expect(refToName('http://asyncapi.com/definitions/3.1.0/channel.json')).toBe('ChannelObject')
36
+ expect(refToName('http://asyncapi.com/definitions/3.1.0/info.json')).toBe('InfoObject')
37
+ })
38
+
39
+ it('derives type name from a URI ref with a fragment', () => {
40
+ expect(refToName('http://asyncapi.com/bindings/sns/0.1.0/channel.json#/definitions/queue')).toBe(
41
+ 'BindingsSns010ChannelQueueObject',
42
+ )
43
+ })
44
+
45
+ it('handles draft-07 schema URI', () => {
46
+ expect(refToName('http://json-schema.org/draft-07/schema')).toBe('Draft07SchemaObject')
47
+ })
48
+ })
@@ -0,0 +1,38 @@
1
+ import { refToFilename } from './ref-to-filename'
2
+
3
+ /**
4
+ * Converts a kebab-case filename to PascalCase with an "Object" suffix.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * kebabToPascal('server-variable') // 'ServerVariableObject'
9
+ * kebabToPascal('channel') // 'ChannelObject'
10
+ * ```
11
+ */
12
+ const kebabToPascal = (kebab: string): string => {
13
+ const words = kebab.split('-')
14
+ let pascalCase = ''
15
+ for (const word of words) {
16
+ pascalCase += word.charAt(0).toUpperCase() + word.slice(1)
17
+ }
18
+ return pascalCase + 'Object'
19
+ }
20
+
21
+ /**
22
+ * Converts a JSON Schema $ref to a type name.
23
+ * Derives the filename via `refToFilename` then converts to PascalCase with
24
+ * an "Object" suffix.
25
+ *
26
+ * Handles all ref forms: internal `#/$defs/...`, `#/definitions/...`, and URI refs.
27
+ *
28
+ * @param ref - The $ref string
29
+ * @returns The type name in PascalCase with "Object" suffix
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * refToName('#/$defs/contact') // 'ContactObject'
34
+ * refToName('#/$defs/server-variable') // 'ServerVariableObject'
35
+ * refToName('http://asyncapi.com/definitions/3.1.0/channel.json') // 'ChannelObject'
36
+ * ```
37
+ */
38
+ export const refToName = (ref: string): string => kebabToPascal(refToFilename(ref))
@@ -0,0 +1,94 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { resolveDynamicRefs } from './resolve-dynamic-refs'
4
+
5
+ describe('resolve-dynamic-refs', () => {
6
+ it('replaces $dynamicRef with $ref in properties', () => {
7
+ const schema = {
8
+ type: 'object' as const,
9
+ properties: {
10
+ schema: { $dynamicRef: '#meta' },
11
+ },
12
+ }
13
+
14
+ const result = resolveDynamicRefs(schema, { '#meta': '#/$defs/schema' })
15
+
16
+ expect(result).toEqual({
17
+ type: 'object',
18
+ properties: {
19
+ schema: { $ref: '#/$defs/schema' },
20
+ },
21
+ })
22
+ })
23
+
24
+ it('replaces $dynamicRef in additionalProperties', () => {
25
+ const schema = {
26
+ type: 'object' as const,
27
+ additionalProperties: { $dynamicRef: '#meta' },
28
+ }
29
+
30
+ const result = resolveDynamicRefs(schema, { '#meta': '#/$defs/schema' })
31
+
32
+ expect(result).toEqual({
33
+ type: 'object',
34
+ additionalProperties: { $ref: '#/$defs/schema' },
35
+ })
36
+ })
37
+
38
+ it('does not mutate the original schema', () => {
39
+ const schema = {
40
+ type: 'object' as const,
41
+ properties: {
42
+ schema: { $dynamicRef: '#meta' },
43
+ },
44
+ }
45
+
46
+ resolveDynamicRefs(schema, { '#meta': '#/$defs/schema' })
47
+
48
+ // Original should be unchanged
49
+ expect(schema.properties.schema).toEqual({ $dynamicRef: '#meta' })
50
+ })
51
+
52
+ it('returns schema unchanged when dynamicRefMap is empty', () => {
53
+ const schema = {
54
+ type: 'object' as const,
55
+ properties: {
56
+ schema: { $dynamicRef: '#meta' },
57
+ },
58
+ }
59
+
60
+ const result = resolveDynamicRefs(schema, {})
61
+
62
+ expect(result).toEqual(schema)
63
+ })
64
+
65
+ it('returns non-object schemas unchanged', () => {
66
+ expect(resolveDynamicRefs(true, { '#meta': '#/$defs/schema' })).toBe(true)
67
+ expect(resolveDynamicRefs(false, { '#meta': '#/$defs/schema' })).toBe(false)
68
+ })
69
+
70
+ it('handles nested $dynamicRef in property sub-schemas', () => {
71
+ const schema = {
72
+ type: 'object' as const,
73
+ properties: {
74
+ schemas: {
75
+ type: 'object' as const,
76
+ additionalProperties: { $dynamicRef: '#meta' },
77
+ },
78
+ },
79
+ }
80
+
81
+ const result = resolveDynamicRefs(schema, { '#meta': '#/$defs/schema' })
82
+
83
+ const expected = {
84
+ type: 'object',
85
+ properties: {
86
+ schemas: {
87
+ type: 'object',
88
+ additionalProperties: { $ref: '#/$defs/schema' },
89
+ },
90
+ },
91
+ }
92
+ expect(result).toEqual(expected)
93
+ })
94
+ })
@@ -0,0 +1,48 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
+
3
+ /**
4
+ * Replaces $dynamicRef with $ref in a schema using the provided anchor-to-path map.
5
+ *
6
+ * This creates a deep clone of the schema to avoid mutating the original, then walks
7
+ * the clone and converts any { $dynamicRef: "#meta" } to { $ref: "#/$defs/schema" }
8
+ * (or whatever the dynamicRefMap dictates).
9
+ *
10
+ * Only the direct properties and their nested schemas are walked — this does not need
11
+ * to be infinitely deep because the build system generates separate files for each $def,
12
+ * so each schema is relatively shallow.
13
+ */
14
+ export const resolveDynamicRefs = (schema: JSONSchema, dynamicRefMap: Record<string, string>): JSONSchema => {
15
+ if (typeof schema !== 'object' || schema === null) {
16
+ return schema
17
+ }
18
+
19
+ // Skip if there are no dynamic refs to resolve
20
+ if (Object.keys(dynamicRefMap).length === 0) {
21
+ return schema
22
+ }
23
+
24
+ const clone = JSON.parse(JSON.stringify(schema)) as Record<string, unknown>
25
+
26
+ const walk = (obj: unknown): void => {
27
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
28
+ return
29
+ }
30
+
31
+ const record = obj as Record<string, unknown>
32
+
33
+ if ('$dynamicRef' in record && typeof record['$dynamicRef'] === 'string') {
34
+ const resolved = dynamicRefMap[record['$dynamicRef'] as string]
35
+ if (resolved) {
36
+ record['$ref'] = resolved
37
+ delete record['$dynamicRef']
38
+ }
39
+ }
40
+
41
+ for (const key in record) {
42
+ walk(record[key])
43
+ }
44
+ }
45
+
46
+ walk(clone)
47
+ return clone as JSONSchema
48
+ }
@@ -0,0 +1,186 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { resolveRef } from './resolve-ref'
4
+
5
+ describe('resolveRef', () => {
6
+ it('resolves a simple $ref to $defs', () => {
7
+ const schema = {
8
+ $defs: {
9
+ contact: {
10
+ type: 'object',
11
+ properties: {
12
+ email: { type: 'string' },
13
+ phone: { type: 'string' },
14
+ },
15
+ },
16
+ },
17
+ }
18
+
19
+ const result = resolveRef('#/$defs/contact', schema)
20
+
21
+ expect(result).toEqual({
22
+ type: 'object',
23
+ properties: {
24
+ email: { type: 'string' },
25
+ phone: { type: 'string' },
26
+ },
27
+ })
28
+ })
29
+
30
+ it('resolves a nested $ref', () => {
31
+ const schema = {
32
+ components: {
33
+ schemas: {
34
+ User: {
35
+ type: 'object',
36
+ properties: {
37
+ name: { type: 'string' },
38
+ age: { type: 'number' },
39
+ },
40
+ },
41
+ },
42
+ },
43
+ }
44
+
45
+ const result = resolveRef('#/components/schemas/User', schema)
46
+
47
+ expect(result).toEqual({
48
+ type: 'object',
49
+ properties: {
50
+ name: { type: 'string' },
51
+ age: { type: 'number' },
52
+ },
53
+ })
54
+ })
55
+
56
+ it('returns undefined for non-existent $ref', () => {
57
+ const schema = {
58
+ $defs: {
59
+ contact: { type: 'object' },
60
+ },
61
+ }
62
+
63
+ const result = resolveRef('#/$defs/nonexistent', schema)
64
+
65
+ expect(result).toBeUndefined()
66
+ })
67
+
68
+ it('returns undefined for URI refs not present in $defs', () => {
69
+ const schema = {
70
+ $defs: {
71
+ contact: { type: 'object' },
72
+ },
73
+ }
74
+
75
+ const result = resolveRef('http://example.com/schema.json', schema)
76
+
77
+ expect(result).toBeUndefined()
78
+ })
79
+
80
+ it('resolves a URI ref that is a $defs key', () => {
81
+ const schema = {
82
+ $defs: {
83
+ 'http://example.com/channel.json': { type: 'object', properties: { name: { type: 'string' } } },
84
+ },
85
+ }
86
+
87
+ const result = resolveRef('http://example.com/channel.json', schema)
88
+
89
+ expect(result).toEqual({ type: 'object', properties: { name: { type: 'string' } } })
90
+ })
91
+
92
+ it('resolves a URI ref with a fragment into a nested definition', () => {
93
+ const schema = {
94
+ $defs: {
95
+ 'http://example.com/channel.json': {
96
+ type: 'object',
97
+ $defs: {
98
+ queue: { type: 'object', properties: { name: { type: 'string' } } },
99
+ },
100
+ },
101
+ },
102
+ }
103
+
104
+ const result = resolveRef('http://example.com/channel.json#/$defs/queue', schema)
105
+
106
+ expect(result).toEqual({ type: 'object', properties: { name: { type: 'string' } } })
107
+ })
108
+
109
+ it('handles URI-encoded characters in $ref', () => {
110
+ const schema = {
111
+ $defs: {
112
+ 'my~field': {
113
+ type: 'string',
114
+ },
115
+ },
116
+ }
117
+
118
+ // ~0 represents ~
119
+ const result = resolveRef('#/$defs/my~0field', schema)
120
+
121
+ expect(result).toEqual({ type: 'string' })
122
+ })
123
+
124
+ it('resolves deeply nested $ref', () => {
125
+ const schema = {
126
+ definitions: {
127
+ nested: {
128
+ deep: {
129
+ value: {
130
+ type: 'boolean',
131
+ },
132
+ },
133
+ },
134
+ },
135
+ }
136
+
137
+ const result = resolveRef('#/definitions/nested/deep/value', schema)
138
+
139
+ expect(result).toEqual({ type: 'boolean' })
140
+ })
141
+
142
+ it('returns undefined for empty $ref', () => {
143
+ const schema = {
144
+ $defs: {
145
+ contact: { type: 'object' },
146
+ },
147
+ }
148
+
149
+ const result = resolveRef('#', schema)
150
+
151
+ expect(result).toEqual(schema)
152
+ })
153
+
154
+ it('handles $ref to array items', () => {
155
+ const schema = {
156
+ $defs: {
157
+ stringArray: {
158
+ type: 'array',
159
+ items: { type: 'string' },
160
+ },
161
+ },
162
+ }
163
+
164
+ const result = resolveRef('#/$defs/stringArray', schema)
165
+
166
+ expect(result).toEqual({
167
+ type: 'array',
168
+ items: { type: 'string' },
169
+ })
170
+ })
171
+
172
+ it('returns undefined when a path segment resolves to a non-object value', () => {
173
+ // When a path segment exists but its value is a primitive (not an object),
174
+ // navigation cannot continue and the ref is unresolvable.
175
+ const schema = {
176
+ $defs: {
177
+ // "count" is a number, not an object — resolveRef cannot navigate into it
178
+ count: 42,
179
+ },
180
+ }
181
+
182
+ const result = resolveRef('#/$defs/count', schema as unknown as Record<string, unknown>)
183
+
184
+ expect(result).toBeUndefined()
185
+ })
186
+ })
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Navigates a JSON Pointer fragment (e.g. `/$defs/foo` or `/definitions/bar`)
3
+ * through a schema object, returning the target or undefined if not found.
4
+ */
5
+ const navigatePointer = (pointer: string, schema: Record<string, unknown>): Record<string, unknown> | undefined => {
6
+ const parts = pointer.split('/').filter(Boolean)
7
+ let current = schema
8
+
9
+ for (const part of parts) {
10
+ const decodedPart = part.replace(/~1/g, '/').replace(/~0/g, '~')
11
+
12
+ if (current && typeof current === 'object' && decodedPart in current) {
13
+ const next = current[decodedPart as keyof typeof current]
14
+ if (typeof next === 'object' && next !== null) {
15
+ current = next as Record<string, unknown>
16
+ } else {
17
+ return undefined
18
+ }
19
+ } else {
20
+ return undefined
21
+ }
22
+ }
23
+
24
+ return current
25
+ }
26
+
27
+ /**
28
+ * Resolves a JSON Schema $ref pointer to the actual schema definition.
29
+ *
30
+ * Supports three ref forms:
31
+ * - Internal: `#/$defs/contact` — navigates the root schema by JSON Pointer
32
+ * - URI key: `http://example.com/foo.json` — looks up the key directly in `$defs`
33
+ * - URI with fragment: `http://example.com/foo.json#/definitions/bar` — looks up
34
+ * the base URI in `$defs`, then navigates the fragment within that definition
35
+ *
36
+ * @param ref - The $ref string
37
+ * @param rootSchema - The root schema containing the definitions
38
+ * @returns The resolved schema or undefined if not found
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * const rootSchema = {
43
+ * $defs: {
44
+ * contact: { type: 'object', properties: { email: { type: 'string' } } },
45
+ * 'http://example.com/server.json': { type: 'object' },
46
+ * }
47
+ * }
48
+ * resolveRef('#/$defs/contact', rootSchema)
49
+ * resolveRef('http://example.com/server.json', rootSchema)
50
+ * ```
51
+ */
52
+ export const resolveRef = (ref: string, rootSchema: Record<string, unknown>): Record<string, unknown> | undefined => {
53
+ // Internal reference: navigate from root by JSON Pointer
54
+ if (ref.startsWith('#')) {
55
+ return navigatePointer(ref.slice(1), rootSchema)
56
+ }
57
+
58
+ // URI ref: may have a fragment (e.g. "http://foo.com/bar.json#/definitions/baz")
59
+ // A trailing bare "#" (e.g. "http://foo.com/schema#") means "the whole document" — treat as no fragment
60
+ const hashIndex = ref.indexOf('#')
61
+ const baseUri = hashIndex === -1 ? ref : ref.slice(0, hashIndex)
62
+ const rawFragment = hashIndex === -1 ? '' : ref.slice(hashIndex + 1)
63
+ const fragment = rawFragment === '' || rawFragment === '/' ? '' : rawFragment
64
+
65
+ // Look up the base URI as a key in $defs
66
+ const defs = rootSchema['$defs']
67
+ if (typeof defs !== 'object' || defs === null) return undefined
68
+
69
+ const defsRecord = defs as Record<string, unknown>
70
+ const base = defsRecord[baseUri]
71
+ if (typeof base !== 'object' || base === null) return undefined
72
+
73
+ // No fragment — return the definition directly
74
+ if (!fragment) return base as Record<string, unknown>
75
+
76
+ // Normalize the fragment: draft-07 schemas use `/definitions/` but after
77
+ // upgradeDraft07Schema the key is renamed to `/$defs/`
78
+ const normalizedFragment = fragment.replace(/^\/definitions\//, '/$defs/')
79
+
80
+ // Navigate the fragment within the resolved definition
81
+ return navigatePointer(normalizedFragment, base as Record<string, unknown>)
82
+ }
@@ -0,0 +1,41 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { safeAccessor, safeKey } from './safe-accessor'
4
+
5
+ describe('safe-accessor', () => {
6
+ it('uses dot notation for simple identifiers', () => {
7
+ expect(safeAccessor('input', 'name')).toBe('input.name')
8
+ })
9
+
10
+ it('uses bracket notation for hyphenated keys', () => {
11
+ expect(safeAccessor('input', 'x-linkedin')).toBe("input['x-linkedin']")
12
+ })
13
+
14
+ it('uses optional chaining with bracket notation for hyphenated keys', () => {
15
+ expect(safeAccessor('input?', 'x-linkedin')).toBe("input?.['x-linkedin']")
16
+ })
17
+
18
+ it('uses dot notation for underscored identifiers', () => {
19
+ expect(safeAccessor('input', '_private')).toBe('input._private')
20
+ })
21
+
22
+ it('uses bracket notation for keys starting with numbers', () => {
23
+ expect(safeAccessor('input', '0foo')).toBe("input['0foo']")
24
+ })
25
+
26
+ it('uses bracket notation for keys with dots', () => {
27
+ expect(safeAccessor('input', 'foo.bar')).toBe("input['foo.bar']")
28
+ })
29
+
30
+ it('returns unquoted key for simple identifiers', () => {
31
+ expect(safeKey('name')).toBe('name')
32
+ })
33
+
34
+ it('returns quoted key for hyphenated names', () => {
35
+ expect(safeKey('x-linkedin')).toBe("'x-linkedin'")
36
+ })
37
+
38
+ it('returns quoted key for names with dots', () => {
39
+ expect(safeKey('foo.bar')).toBe("'foo.bar'")
40
+ })
41
+ })
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Checks whether a property name is a valid JavaScript identifier that can be
3
+ * accessed with dot notation. Property names containing hyphens, dots, or
4
+ * other special characters (e.g., "x-linkedin") must use bracket notation.
5
+ */
6
+ const JS_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/
7
+
8
+ /**
9
+ * Generates a safe property accessor for a given key on an object variable.
10
+ * Uses dot notation for simple identifiers and bracket notation for keys
11
+ * that contain special characters like hyphens.
12
+ *
13
+ * @param variable - The variable name (e.g., "input", "input?")
14
+ * @param key - The property name to access
15
+ * @returns A valid JS property access expression
16
+ *
17
+ * @example
18
+ * safeAccessor("input", "name") // "input.name"
19
+ * safeAccessor("input?", "x-linkedin") // "input?.['x-linkedin']"
20
+ * safeAccessor("input", "x-linkedin") // "input['x-linkedin']"
21
+ */
22
+ export const safeAccessor = (variable: string, key: string): string => {
23
+ if (JS_IDENTIFIER.test(key)) {
24
+ return `${variable}.${key}`
25
+ }
26
+
27
+ // Handle optional chaining: "input?" -> "input?.['key']"
28
+ if (variable.endsWith('?')) {
29
+ return `${variable}.['${key}']`
30
+ }
31
+
32
+ return `${variable}['${key}']`
33
+ }
34
+
35
+ /**
36
+ * Generates a safe property key for use in object literals.
37
+ * Wraps keys that are not valid identifiers in quotes.
38
+ *
39
+ * @example
40
+ * safeKey("name") // "name"
41
+ * safeKey("x-linkedin") // "'x-linkedin'"
42
+ */
43
+ export const safeKey = (key: string): string => {
44
+ if (JS_IDENTIFIER.test(key)) {
45
+ return key
46
+ }
47
+ return `'${key}'`
48
+ }