@kubb/ast 5.0.0-beta.42 → 5.0.0-beta.44

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,295 @@
1
+ import { isIdentifier, pascalCase, singleQuote } from '@internals/utils'
2
+ import { INDENT } from '../constants.ts'
3
+
4
+ export { ensureValidVarName, isValidVarName } from '@internals/utils'
5
+
6
+ /**
7
+ * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
8
+ * Returns the string unchanged when no balanced quote pair is found.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * trimQuotes('"hello"') // 'hello'
13
+ * trimQuotes('hello') // 'hello'
14
+ * ```
15
+ */
16
+ export function trimQuotes(text: string): string {
17
+ if (text.length >= 2) {
18
+ const first = text[0]
19
+ const last = text[text.length - 1]
20
+ if ((first === '"' && last === '"') || (first === "'" && last === "'") || (first === '`' && last === '`')) {
21
+ return text.slice(1, -1)
22
+ }
23
+ }
24
+ return text
25
+ }
26
+
27
+ /**
28
+ * Serializes a primitive value to a single-quoted string literal, stripping any surrounding quote
29
+ * characters first. Escaping comes from `JSON.stringify`, then the quote style switches to single
30
+ * quotes so generated code matches the repo style without a formatter.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * stringify('hello') // "'hello'"
35
+ * stringify('"hello"') // "'hello'"
36
+ * ```
37
+ */
38
+ export function stringify(value: string | number | boolean | undefined): string {
39
+ if (value === undefined || value === null) return "''"
40
+ const json = JSON.stringify(trimQuotes(value.toString()))
41
+ const inner = json.slice(1, -1).replace(/\\"/g, '"').replace(/'/g, "\\'")
42
+ return `'${inner}'`
43
+ }
44
+
45
+ /**
46
+ * Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
47
+ * and the Unicode line terminators U+2028 and U+2029.
48
+ *
49
+ * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
54
+ * ```
55
+ */
56
+ export function jsStringEscape(input: unknown): string {
57
+ return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
58
+ switch (character) {
59
+ case '"':
60
+ case "'":
61
+ case '\\':
62
+ return `\\${character}`
63
+ case '\n':
64
+ return '\\n'
65
+ case '\r':
66
+ return '\\r'
67
+ case '\u2028':
68
+ return '\\u2028'
69
+ case '\u2029':
70
+ return '\\u2029'
71
+ default:
72
+ return ''
73
+ }
74
+ })
75
+ }
76
+
77
+ /**
78
+ * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
79
+ * Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
80
+ * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
85
+ * toRegExpString('^(?im)foo', null) // '/^foo/im'
86
+ * ```
87
+ */
88
+ export function toRegExpString(text: string, func: string | null = 'RegExp'): string {
89
+ const raw = trimQuotes(text)
90
+
91
+ const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i)
92
+ const replacementTarget = match?.[1] ?? ''
93
+ const matchedFlags = match?.[2]
94
+ const cleaned = raw
95
+ .replace(/^\\?\//, '')
96
+ .replace(/\\?\/$/, '')
97
+ .replace(replacementTarget, '')
98
+
99
+ const { source, flags } = new RegExp(cleaned, matchedFlags)
100
+
101
+ if (func === null) return `/${source}/${flags}`
102
+
103
+ return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ''})`
104
+ }
105
+
106
+ /**
107
+ * Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
108
+ * objects recurse with fixed indentation, so the result drops straight into an object literal
109
+ * without re-parsing.
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * stringifyObject({ foo: 'bar', nested: { a: 1 } })
114
+ * // 'foo: bar,\nnested: {\n a: 1\n }'
115
+ * ```
116
+ */
117
+ export function stringifyObject(value: Record<string, unknown>): string {
118
+ const items = Object.entries(value)
119
+ .map(([key, val]) => {
120
+ if (val !== null && typeof val === 'object') {
121
+ return `${key}: {\n ${stringifyObject(val as Record<string, unknown>)}\n }`
122
+ }
123
+ return `${key}: ${val}`
124
+ })
125
+ .filter(Boolean)
126
+ return items.join(',\n')
127
+ }
128
+
129
+ /**
130
+ * Renders a dotted path or string array as an optional-chaining accessor expression rooted at
131
+ * `accessor`. Returns `null` for an empty path.
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * getNestedAccessor('pagination.next.id', 'lastPage')
136
+ * // "lastPage?.['pagination']?.['next']?.['id']"
137
+ * ```
138
+ */
139
+ export function getNestedAccessor(param: string | Array<string>, accessor: string): string | null {
140
+ const parts = Array.isArray(param) ? param : param.split('.')
141
+ if (parts.length === 0 || (parts.length === 1 && parts[0] === '')) return null
142
+ return `${accessor}?.['${`${parts.join("']?.['")}']`}`
143
+ }
144
+
145
+ /**
146
+ * Builds a JSDoc comment block from an array of lines, returning `fallback` when there are no
147
+ * comments so callers always get a usable string.
148
+ *
149
+ * @example
150
+ * ```ts
151
+ * buildJSDoc(['@type string', '@example hello'])
152
+ * // '/**\n * @type string\n * @example hello\n *\/\n '
153
+ * ```
154
+ */
155
+ export function buildJSDoc(
156
+ comments: Array<string>,
157
+ options: {
158
+ /**
159
+ * String used to indent each comment line.
160
+ * @default ' * '
161
+ */
162
+ indent?: string
163
+ /**
164
+ * String appended after the closing tag.
165
+ * @default '\n '
166
+ */
167
+ suffix?: string
168
+ /**
169
+ * Returned as-is when `comments` is empty.
170
+ * @default ' '
171
+ */
172
+ fallback?: string
173
+ } = {},
174
+ ): string {
175
+ const { indent = ' * ', suffix = '\n ', fallback = ' ' } = options
176
+
177
+ if (comments.length === 0) return fallback
178
+
179
+ return `/**\n${comments.map((c) => `${indent}${c}`).join('\n')}\n */${suffix}`
180
+ }
181
+
182
+ /**
183
+ * Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
184
+ */
185
+ function indentLines(text: string): string {
186
+ if (!text) return ''
187
+ return text
188
+ .split('\n')
189
+ .map((line) => (line.trim() ? `${INDENT}${line}` : ''))
190
+ .join('\n')
191
+ }
192
+
193
+ /**
194
+ * Renders an object key, quoting it with single quotes only when it is not a valid identifier.
195
+ * Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * objectKey('name') // 'name'
200
+ * objectKey('x-total') // "'x-total'"
201
+ * ```
202
+ */
203
+ export function objectKey(name: string): string {
204
+ return isIdentifier(name) ? name : singleQuote(name)
205
+ }
206
+
207
+ /**
208
+ * Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
209
+ * level and closing the brace at column zero. Nested objects built the same way indent cumulatively,
210
+ * so callers never re-parse the generated code. A trailing comma is added per entry to match the
211
+ * formatter's multi-line style.
212
+ *
213
+ * @example
214
+ * ```ts
215
+ * buildObject(['id: z.number()', 'name: z.string()'])
216
+ * // '{\n id: z.number(),\n name: z.string(),\n}'
217
+ * ```
218
+ */
219
+ export function buildObject(entries: Array<string>): string {
220
+ if (entries.length === 0) return '{}'
221
+ const body = entries.map((entry) => `${indentLines(entry)},`).join('\n')
222
+ return `{\n${body}\n}`
223
+ }
224
+
225
+ /**
226
+ * Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
227
+ * one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
228
+ * one level with a trailing comma and the closing bracket at column zero. Use it for `z.union([…])`,
229
+ * `z.array([…])`, and similar member lists so objects inside them nest correctly.
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * buildList(['z.string()', 'z.number()'])
234
+ * // '[z.string(), z.number()]'
235
+ * ```
236
+ */
237
+ export function buildList(items: Array<string>, brackets: [open: string, close: string] = ['[', ']']): string {
238
+ const [open, close] = brackets
239
+ if (items.length === 0) return `${open}${close}`
240
+ if (!items.some((item) => item.includes('\n'))) return `${open}${items.join(', ')}${close}`
241
+ const body = items.map((item) => `${indentLines(item)},`).join('\n')
242
+ return `${open}\n${body}\n${close}`
243
+ }
244
+
245
+ /**
246
+ * Returns the last path segment of a reference string.
247
+ *
248
+ * @example
249
+ * ```ts
250
+ * extractRefName('#/components/schemas/Pet') // 'Pet'
251
+ * ```
252
+ */
253
+ export function extractRefName(ref: string): string {
254
+ return ref.split('/').at(-1) ?? ref
255
+ }
256
+
257
+ /**
258
+ * Builds a PascalCase child schema name by joining a parent name and property name.
259
+ * Returns `null` when there is no parent to nest under.
260
+ *
261
+ * @example
262
+ * ```ts
263
+ * childName('Order', 'shipping_address') // 'OrderShippingAddress'
264
+ * childName(undefined, 'params') // null
265
+ * ```
266
+ */
267
+ export function childName(parentName: string | null | undefined, propName: string): string | null {
268
+ return parentName ? pascalCase([parentName, propName].join(' ')) : null
269
+ }
270
+
271
+ /**
272
+ * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
273
+ * empty parts.
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
278
+ * ```
279
+ */
280
+ export function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string {
281
+ return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))
282
+ }
283
+
284
+ /**
285
+ * Returns the discriminator key whose mapping value matches `ref`, or `null` when there is no match.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * findDiscriminator({ dog: '#/components/schemas/Dog' }, '#/components/schemas/Dog') // 'dog'
290
+ * ```
291
+ */
292
+ export function findDiscriminator(mapping: Record<string, string> | undefined, ref: string | undefined): string | null {
293
+ if (!mapping || !ref) return null
294
+ return Object.entries(mapping).find(([, value]) => value === ref)?.[0] ?? null
295
+ }
package/src/refs.ts DELETED
@@ -1,13 +0,0 @@
1
- /**
2
- * Returns the last path segment of a reference string.
3
- *
4
- * Example: `#/components/schemas/Pet` becomes `Pet`.
5
- *
6
- * @example
7
- * ```ts
8
- * extractRefName('#/components/schemas/Pet') // 'Pet'
9
- * ```
10
- */
11
- export function extractRefName(ref: string): string {
12
- return ref.split('/').at(-1) ?? ref
13
- }