@amritk/helpers 0.10.0 → 0.10.2
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.
- package/dist/escape-regex-pattern.d.ts +15 -5
- package/dist/escape-regex-pattern.js +48 -10
- package/dist/generate-index-barrel.js +3 -2
- package/dist/generate-type-definition.js +72 -53
- package/dist/multiple-of-check.d.ts +4 -0
- package/dist/multiple-of-check.js +30 -0
- package/dist/parse-documentation.js +6 -2
- package/dist/ref-to-name.js +17 -2
- package/dist/resolve-dynamic-refs.js +24 -0
- package/dist/safe-accessor.d.ts +3 -3
- package/dist/safe-accessor.js +10 -6
- package/dist/validate-record.js +11 -1
- package/dist/walk-ref-graph.js +4 -2
- package/package.json +4 -2
- package/src/build-dynamic-ref-map.ts +42 -0
- package/src/derive-root-type-name.ts +42 -0
- package/src/escape-regex-pattern.ts +59 -0
- package/src/extract-dynamic-anchor-defs.ts +33 -0
- package/src/extract-refs.ts +73 -0
- package/src/generate-index-barrel.ts +63 -0
- package/src/generate-type-definition.ts +599 -0
- package/src/has-ref.ts +10 -0
- package/src/is-object.ts +15 -0
- package/src/mjst-extension.ts +81 -0
- package/src/multiple-of-check.ts +32 -0
- package/src/parse-documentation.ts +177 -0
- package/src/ref-to-filename.ts +116 -0
- package/src/ref-to-name.ts +54 -0
- package/src/resolve-dynamic-refs.ts +74 -0
- package/src/resolve-ref.ts +82 -0
- package/src/safe-accessor.ts +53 -0
- package/src/schema-guards.ts +195 -0
- package/src/unknown-key-check.ts +68 -0
- package/src/upgrade-draft07-schema.ts +179 -0
- package/src/validate-array.ts +15 -0
- package/src/validate-record.ts +28 -0
- package/src/walk-ref-graph.ts +186 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { isObject } from './is-object'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Converts an arbitrary title string into a PascalCase TypeScript identifier.
|
|
5
|
+
* Splits on any run of non-alphanumeric characters, capitalizes the first
|
|
6
|
+
* letter of each word while preserving the rest (so acronyms like "API" or
|
|
7
|
+
* "JSON" survive intact), and drops leading digits since an identifier may not
|
|
8
|
+
* start with a number.
|
|
9
|
+
*/
|
|
10
|
+
const titleToPascalCase = (title: string): string => {
|
|
11
|
+
const words = title.split(/[^a-zA-Z0-9]+/).filter(Boolean)
|
|
12
|
+
const pascal = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join('')
|
|
13
|
+
return pascal.replace(/^\d+/, '')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Derives the root type name for a generated schema from its `title` keyword.
|
|
18
|
+
*
|
|
19
|
+
* We name the root after the schema itself instead of a generic "Document" so
|
|
20
|
+
* the generated types and parsers read naturally (e.g. an OpenAPI schema yields
|
|
21
|
+
* `OpenApi` / `parseOpenApi`). When the schema has no usable `title`, we fall
|
|
22
|
+
* back to "Document" to keep output deterministic.
|
|
23
|
+
*
|
|
24
|
+
* @param schema - The root JSON Schema. A boolean schema or one without a
|
|
25
|
+
* string `title` falls back to the default.
|
|
26
|
+
* @returns A PascalCase type name derived from the title, or "Document".
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* deriveRootTypeName({ title: 'OpenAPI Document' }) // 'OpenAPIDocument'
|
|
31
|
+
* deriveRootTypeName({ title: 'my-config' }) // 'MyConfig'
|
|
32
|
+
* deriveRootTypeName({ type: 'object' }) // 'Document'
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export const deriveRootTypeName = (schema: unknown): string => {
|
|
36
|
+
if (!isObject(schema) || typeof schema['title'] !== 'string') {
|
|
37
|
+
return 'Document'
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const name = titleToPascalCase(schema['title'])
|
|
41
|
+
return name || 'Document'
|
|
42
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Escapes a JSON Schema `pattern` so it can be embedded between the slashes of
|
|
3
|
+
* a generated regex literal (`/…/`), and validates that the pattern is a legal
|
|
4
|
+
* regex at generation time.
|
|
5
|
+
*
|
|
6
|
+
* A `pattern` is an ECMA-262 regex *body*, and the generated text goes into a
|
|
7
|
+
* regex literal — not a string literal — so backslashes are regex syntax and
|
|
8
|
+
* must be left exactly as-is (doubling `\d` to `\\d` would change it from "a
|
|
9
|
+
* digit" to "a literal backslash followed by d"). Two things would otherwise
|
|
10
|
+
* corrupt the surrounding literal:
|
|
11
|
+
* - an *unescaped* `/`, which would close the literal early; and
|
|
12
|
+
* - a raw line terminator (LF, CR, U+2028, U+2029), which is not allowed
|
|
13
|
+
* inside a regex literal and would split the emitted `/…/` across lines (a
|
|
14
|
+
* syntax error). Each is rewritten to its backslash escape, which matches
|
|
15
|
+
* the identical character, so the regex's meaning is unchanged.
|
|
16
|
+
*
|
|
17
|
+
* Additionally, an *invalid* pattern (e.g. `([`) would be emitted verbatim as
|
|
18
|
+
* `/([/…` and produce output that does not parse. We compile the pattern with
|
|
19
|
+
* `new RegExp` here and throw a clear generator-time error instead, so a bad
|
|
20
|
+
* schema fails loudly during generation rather than emitting broken code.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* escapeRegexPattern('\\d{4}/\\d{2}') // → '\\d{4}\\/\\d{2}' (i.e. \d{4}\/\d{2})
|
|
24
|
+
* @throws if `pattern` is not a valid regular expression.
|
|
25
|
+
*/
|
|
26
|
+
export const escapeRegexPattern = (pattern: string): string => {
|
|
27
|
+
// Validate at generation time — an invalid pattern must fail here, not emit
|
|
28
|
+
// a `/([/` literal that breaks the generated file.
|
|
29
|
+
try {
|
|
30
|
+
new RegExp(pattern)
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw new Error(
|
|
33
|
+
`Invalid regex pattern ${JSON.stringify(pattern)}: ${error instanceof Error ? error.message : String(error)}`,
|
|
34
|
+
)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Line terminators, keyed by code point, and the backslash escape each maps to.
|
|
38
|
+
// These are the four characters disallowed *raw* inside a regex literal.
|
|
39
|
+
const lineTerminatorEscapes: Record<number, string> = {
|
|
40
|
+
0x0a: '\\n', // LF
|
|
41
|
+
0x0d: '\\r', // CR
|
|
42
|
+
0x2028: '\\u2028', // LINE SEPARATOR
|
|
43
|
+
0x2029: '\\u2029', // PARAGRAPH SEPARATOR
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Match either an escape sequence (`\` + any char, kept verbatim) or a single
|
|
47
|
+
// character that would corrupt the literal (a bare `/` or a line terminator).
|
|
48
|
+
// The line terminators are written as `\u….` escapes so this source file is
|
|
49
|
+
// itself free of the raw characters it guards against. Consuming escape pairs
|
|
50
|
+
// first means the slash in `\/` is never seen as bare, so it is not
|
|
51
|
+
// double-escaped.
|
|
52
|
+
return pattern.replace(/\\[\s\S]|[/\n\r\u2028\u2029]/g, (match) => {
|
|
53
|
+
if (match === '/') return '\\/'
|
|
54
|
+
const terminatorEscape = lineTerminatorEscapes[match.charCodeAt(0)]
|
|
55
|
+
if (terminatorEscape !== undefined && match.length === 1) return terminatorEscape
|
|
56
|
+
// An escape pair like `\/` or `\d`: keep exactly as authored.
|
|
57
|
+
return match
|
|
58
|
+
})
|
|
59
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Collects `#/$defs/<key>` refs for every root definition that carries a
|
|
5
|
+
* `$dynamicAnchor`.
|
|
6
|
+
*
|
|
7
|
+
* These definitions are reachable only through `$dynamicRef`, which the ref
|
|
8
|
+
* walker does not follow directly (a `$dynamicRef` is rewritten to a concrete
|
|
9
|
+
* `$ref` by `resolveDynamicRefs` *after* the schema is extracted, so plain
|
|
10
|
+
* `extractRefs` never sees it). Seeding them explicitly guarantees a file is
|
|
11
|
+
* generated for each dynamic-anchor target — without this, a generator would
|
|
12
|
+
* emit code that imports a type whose file was never produced.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* // $defs.schema has $dynamicAnchor: "meta"
|
|
17
|
+
* extractDynamicAnchorDefs(rootSchema) // ['#/$defs/schema']
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export const extractDynamicAnchorDefs = (schema: JSONSchema): string[] => {
|
|
21
|
+
const refs: string[] = []
|
|
22
|
+
|
|
23
|
+
if (typeof schema !== 'object' || schema === null) return refs
|
|
24
|
+
if (!('$defs' in schema) || typeof schema['$defs'] !== 'object' || schema['$defs'] === null) return refs
|
|
25
|
+
|
|
26
|
+
for (const [key, value] of Object.entries(schema['$defs'])) {
|
|
27
|
+
if (typeof value === 'object' && value !== null && '$dynamicAnchor' in value) {
|
|
28
|
+
refs.push(`#/$defs/${key}`)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return refs
|
|
33
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Returns true if a $ref value should be queued for processing.
|
|
5
|
+
*
|
|
6
|
+
* Accepted forms:
|
|
7
|
+
* - Internal: `#/$defs/foo` or `#/definitions/foo`
|
|
8
|
+
* - URI key: `http://example.com/foo.json` (no fragment, or empty fragment)
|
|
9
|
+
* - URI with fragment: `http://example.com/foo.json#/definitions/bar`
|
|
10
|
+
*
|
|
11
|
+
* Excluded:
|
|
12
|
+
* - `#` alone (self-reference, not a standalone definition)
|
|
13
|
+
* - Relative path refs (e.g. `/components/messages/foo`) — these point into
|
|
14
|
+
* example data in the schema document, not into type definitions
|
|
15
|
+
*/
|
|
16
|
+
const isResolvableRef = (ref: string): boolean => {
|
|
17
|
+
if (ref === '#') return false
|
|
18
|
+
if (ref.startsWith('#')) return true
|
|
19
|
+
if (ref.startsWith('http://') || ref.startsWith('https://')) return true
|
|
20
|
+
return false
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Extracts all $ref values from a JSON Schema recursively.
|
|
25
|
+
* Returns both internal (`#`-prefixed) and URI refs so the build pipeline
|
|
26
|
+
* can resolve and generate files for all referenced definitions.
|
|
27
|
+
*
|
|
28
|
+
* @param schema - The JSON Schema to extract refs from
|
|
29
|
+
* @returns A Set of unique ref strings found in the schema
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* const schema = {
|
|
34
|
+
* type: 'object',
|
|
35
|
+
* properties: {
|
|
36
|
+
* contact: { $ref: '#/$defs/contact' },
|
|
37
|
+
* channel: { $ref: 'http://example.com/channel.json' },
|
|
38
|
+
* }
|
|
39
|
+
* }
|
|
40
|
+
* const refs = extractRefs(schema)
|
|
41
|
+
* // refs = Set(['#/$defs/contact', 'http://example.com/channel.json'])
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export const extractRefs = (schema: JSONSchema): Set<string> => {
|
|
45
|
+
const refs = new Set<string>()
|
|
46
|
+
|
|
47
|
+
const traverse = (obj: unknown): void => {
|
|
48
|
+
if (typeof obj !== 'object' || obj === null) {
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (Array.isArray(obj)) {
|
|
53
|
+
for (const item of obj) {
|
|
54
|
+
traverse(item)
|
|
55
|
+
}
|
|
56
|
+
return
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const record = obj as Record<string, unknown>
|
|
60
|
+
|
|
61
|
+
if ('$ref' in record && typeof record['$ref'] === 'string' && isResolvableRef(record['$ref'] as string)) {
|
|
62
|
+
refs.add(record['$ref'] as string)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Recursively traverse all properties using for...in to avoid intermediate array allocation
|
|
66
|
+
for (const key in record) {
|
|
67
|
+
traverse(record[key])
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
traverse(schema)
|
|
72
|
+
return refs
|
|
73
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** A generated file: its name (with extension) and TypeScript source. */
|
|
2
|
+
export type IndexBarrelFile = {
|
|
3
|
+
filename: string
|
|
4
|
+
content: string
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/** Options controlling how the barrel re-exports each module. */
|
|
8
|
+
export type GenerateIndexBarrelOptions = {
|
|
9
|
+
/**
|
|
10
|
+
* When true, every re-export is type-only (`export type { ... }`). Used by the
|
|
11
|
+
* types-only parser output, where no runtime values exist to re-export.
|
|
12
|
+
* Defaults to `false`.
|
|
13
|
+
*/
|
|
14
|
+
readonly typesOnly?: boolean
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Generated files declare their public surface with these two forms, so we can
|
|
18
|
+
// recover the export names from the source text without parsing it.
|
|
19
|
+
const TYPE_EXPORT_RE = /^export type (\w+)/gm
|
|
20
|
+
const CONST_EXPORT_RE = /^export const (\w+)/gm
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Builds the `index.ts` barrel that re-exports every generated module. This is
|
|
24
|
+
* the shared version of the near-identical barrel each generator used to build
|
|
25
|
+
* inline: it scans each file's source for `export type` / `export const`
|
|
26
|
+
* declarations and emits one re-export line per module, sorted by filename.
|
|
27
|
+
*
|
|
28
|
+
* Files under `_helpers/` are internal runtime helpers (embedded-mode output)
|
|
29
|
+
* and are never re-exported. Modules that expose nothing are skipped.
|
|
30
|
+
*
|
|
31
|
+
* @param files - The generated files to barrel (the `index.ts` itself excluded).
|
|
32
|
+
* @param options - See {@link GenerateIndexBarrelOptions}.
|
|
33
|
+
* @returns The `index.ts` file content.
|
|
34
|
+
*/
|
|
35
|
+
export const generateIndexBarrel = (files: IndexBarrelFile[], options: GenerateIndexBarrelOptions = {}): string => {
|
|
36
|
+
const typesOnly = options.typesOnly ?? false
|
|
37
|
+
|
|
38
|
+
const sortedFiles = files
|
|
39
|
+
.filter((file) => !file.filename.startsWith('_helpers/'))
|
|
40
|
+
.sort((a, b) => a.filename.localeCompare(b.filename))
|
|
41
|
+
|
|
42
|
+
let indexContent = ''
|
|
43
|
+
for (const file of sortedFiles) {
|
|
44
|
+
const moduleName = file.filename.replace(/\.ts$/, '')
|
|
45
|
+
const typeNames: string[] = []
|
|
46
|
+
const constNames: string[] = []
|
|
47
|
+
|
|
48
|
+
for (const match of file.content.matchAll(TYPE_EXPORT_RE)) typeNames.push(match[1] as string)
|
|
49
|
+
for (const match of file.content.matchAll(CONST_EXPORT_RE)) constNames.push(match[1] as string)
|
|
50
|
+
|
|
51
|
+
if (typeNames.length === 0 && constNames.length === 0) continue
|
|
52
|
+
|
|
53
|
+
// `.js` extension so the barrel resolves under Node ESM, not only Bun.
|
|
54
|
+
if (typesOnly) {
|
|
55
|
+
indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}.js';\n`
|
|
56
|
+
} else {
|
|
57
|
+
const typeExports = typeNames.map((name) => `type ${name}`)
|
|
58
|
+
indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}.js';\n`
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return indexContent
|
|
63
|
+
}
|