@kubb/ast 5.0.0-beta.80 → 5.0.0-beta.81

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/utils.cjs DELETED
@@ -1,613 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_visitor = require("./visitor-h6dEM3vR.cjs");
3
- const require_refs = require("./refs-Bg3rmujP.cjs");
4
- //#region ../../internals/utils/src/promise.ts
5
- /**
6
- * Wraps `factory` with a keyed cache backed by the provided store.
7
- *
8
- * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
9
- * collected) or a `Map` for primitive keys. For multi-argument functions,
10
- * nest two `memoize` calls — the outer keyed by the first argument, the
11
- * inner (created once per outer miss) keyed by the second.
12
- *
13
- * Because the cache is owned by the caller, it can be shared, inspected, or
14
- * cleared independently of the memoized function.
15
- *
16
- * @example Single WeakMap key
17
- * ```ts
18
- * const cache = new WeakMap<SchemaNode, Set<string>>()
19
- * const getRefs = memoize(cache, (node) => collectRefs(node))
20
- * ```
21
- *
22
- * @example Single Map key (primitive)
23
- * ```ts
24
- * const cache = new Map<string, Resolver>()
25
- * const getResolver = memoize(cache, (name) => buildResolver(name))
26
- * ```
27
- *
28
- * @example Two-level (object + primitive)
29
- * ```ts
30
- * const outer = new WeakMap<Params[], Map<string, Params[]>>()
31
- * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
32
- * fn(params)('camelcase')
33
- * ```
34
- */
35
- function memoize(store, factory) {
36
- return (key) => {
37
- if (store.has(key)) return store.get(key);
38
- const value = factory(key);
39
- store.set(key, value);
40
- return value;
41
- };
42
- }
43
- //#endregion
44
- //#region ../../internals/utils/src/reserved.ts
45
- /**
46
- * JavaScript and Java reserved words.
47
- * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
48
- */
49
- const reservedWords = /* @__PURE__ */ new Set([
50
- "abstract",
51
- "arguments",
52
- "boolean",
53
- "break",
54
- "byte",
55
- "case",
56
- "catch",
57
- "char",
58
- "class",
59
- "const",
60
- "continue",
61
- "debugger",
62
- "default",
63
- "delete",
64
- "do",
65
- "double",
66
- "else",
67
- "enum",
68
- "eval",
69
- "export",
70
- "extends",
71
- "false",
72
- "final",
73
- "finally",
74
- "float",
75
- "for",
76
- "function",
77
- "goto",
78
- "if",
79
- "implements",
80
- "import",
81
- "in",
82
- "instanceof",
83
- "int",
84
- "interface",
85
- "let",
86
- "long",
87
- "native",
88
- "new",
89
- "null",
90
- "package",
91
- "private",
92
- "protected",
93
- "public",
94
- "return",
95
- "short",
96
- "static",
97
- "super",
98
- "switch",
99
- "synchronized",
100
- "this",
101
- "throw",
102
- "throws",
103
- "transient",
104
- "true",
105
- "try",
106
- "typeof",
107
- "var",
108
- "void",
109
- "volatile",
110
- "while",
111
- "with",
112
- "yield",
113
- "Array",
114
- "Date",
115
- "hasOwnProperty",
116
- "Infinity",
117
- "isFinite",
118
- "isNaN",
119
- "isPrototypeOf",
120
- "length",
121
- "Math",
122
- "name",
123
- "NaN",
124
- "Number",
125
- "Object",
126
- "prototype",
127
- "String",
128
- "toString",
129
- "undefined",
130
- "valueOf"
131
- ]);
132
- /**
133
- * Returns `true` when `name` is a syntactically valid JavaScript variable name.
134
- *
135
- * @example
136
- * ```ts
137
- * isValidVarName('status') // true
138
- * isValidVarName('class') // false (reserved word)
139
- * isValidVarName('42foo') // false (starts with digit)
140
- * ```
141
- */
142
- function isValidVarName(name) {
143
- if (!name || reservedWords.has(name)) return false;
144
- return isIdentifier(name);
145
- }
146
- /**
147
- * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
148
- *
149
- * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
150
- * even though they are not valid variable names, so use this (not {@link isValidVarName}) when
151
- * deciding whether an object key needs quoting.
152
- *
153
- * @example
154
- * ```ts
155
- * isIdentifier('name') // true
156
- * isIdentifier('x-total')// false
157
- * ```
158
- */
159
- function isIdentifier(name) {
160
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
161
- }
162
- //#endregion
163
- //#region ../../internals/utils/src/string.ts
164
- /**
165
- * Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping
166
- * any backslash or single quote in the content.
167
- *
168
- * @example
169
- * ```ts
170
- * singleQuote('foo') // "'foo'"
171
- * singleQuote("o'clock") // "'o\\'clock'"
172
- * ```
173
- */
174
- function singleQuote(value) {
175
- if (value === void 0 || value === null) return "''";
176
- return `'${String(value).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
177
- }
178
- //#endregion
179
- //#region src/utils/codegen.ts
180
- /**
181
- * Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no
182
- * comments.
183
- *
184
- * @example
185
- * ```ts
186
- * buildJSDoc(['@type string', '@example hello'])
187
- * // '/**\n * @type string\n * @example hello\n *\/\n '
188
- * ```
189
- */
190
- function buildJSDoc(comments, options = {}) {
191
- const { indent = " * ", suffix = "\n ", fallback = " " } = options;
192
- if (comments.length === 0) return fallback;
193
- return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
194
- }
195
- /**
196
- * Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
197
- */
198
- function indentLines(text) {
199
- if (!text) return "";
200
- return text.split("\n").map((line) => line.trim() ? ` ${line}` : "").join("\n");
201
- }
202
- /**
203
- * Renders an object key, quoting it with single quotes only when it is not a valid identifier.
204
- * Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
205
- *
206
- * @example
207
- * ```ts
208
- * objectKey('name') // 'name'
209
- * objectKey('x-total') // "'x-total'"
210
- * ```
211
- */
212
- function objectKey(name) {
213
- return isIdentifier(name) ? name : singleQuote(name);
214
- }
215
- /**
216
- * Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
217
- * level and closing the brace at column zero. Entries that are themselves multi-line objects indent
218
- * cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.
219
- *
220
- * @example
221
- * ```ts
222
- * buildObject(['id: z.number()', 'name: z.string()'])
223
- * // '{\n id: z.number(),\n name: z.string(),\n}'
224
- * ```
225
- */
226
- function buildObject(entries) {
227
- if (entries.length === 0) return "{}";
228
- return `{\n${entries.map((entry) => `${indentLines(entry)},`).join("\n")}\n}`;
229
- }
230
- /**
231
- * Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
232
- * one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
233
- * one level with a trailing comma and the closing bracket at column zero. Used for member lists such
234
- * as `z.union([…])` and `z.array([…])`.
235
- *
236
- * @example
237
- * ```ts
238
- * buildList(['z.string()', 'z.number()'])
239
- * // '[z.string(), z.number()]'
240
- * ```
241
- */
242
- function buildList(items, brackets = ["[", "]"]) {
243
- const [open, close] = brackets;
244
- if (items.length === 0) return `${open}${close}`;
245
- if (!items.some((item) => item.includes("\n"))) return `${open}${items.join(", ")}${close}`;
246
- return `${open}\n${items.map((item) => `${indentLines(item)},`).join("\n")}\n${close}`;
247
- }
248
- //#endregion
249
- //#region src/utils/schemaMerge.ts
250
- /**
251
- * Merges a run of adjacent anonymous object members into one. Named or non-object members break the
252
- * run and pass through unchanged. The merge follows member order, so callers control which members
253
- * combine by where they place them in the sequence.
254
- *
255
- * @example
256
- * ```ts
257
- * const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
258
- * ```
259
- */
260
- function* mergeAdjacentObjectsLazy(members) {
261
- let acc;
262
- for (const member of members) {
263
- const objectMember = require_visitor.narrowSchema(member, "object");
264
- if (objectMember && !objectMember.name && acc !== void 0) {
265
- const accObject = require_visitor.narrowSchema(acc, "object");
266
- if (accObject && !accObject.name) {
267
- acc = require_visitor.createSchema({
268
- ...accObject,
269
- properties: [...accObject.properties ?? [], ...objectMember.properties ?? []]
270
- });
271
- continue;
272
- }
273
- }
274
- if (acc !== void 0) yield acc;
275
- acc = member;
276
- }
277
- if (acc !== void 0) yield acc;
278
- }
279
- //#endregion
280
- //#region src/utils/strings.ts
281
- /**
282
- * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
283
- * Returns the string unchanged when no balanced quote pair is found.
284
- *
285
- * @example
286
- * ```ts
287
- * trimQuotes('"hello"') // 'hello'
288
- * trimQuotes('hello') // 'hello'
289
- * ```
290
- */
291
- function trimQuotes(text) {
292
- if (text.length >= 2) {
293
- const first = text[0];
294
- const last = text[text.length - 1];
295
- if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
296
- }
297
- return text;
298
- }
299
- /**
300
- * Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
301
- *
302
- * Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
303
- * code matches the repo style without a formatter.
304
- *
305
- * @example
306
- * ```ts
307
- * stringify('hello') // "'hello'"
308
- * stringify('"hello"') // "'hello'"
309
- * ```
310
- */
311
- function stringify(value) {
312
- if (value === void 0 || value === null) return "''";
313
- return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
314
- }
315
- /**
316
- * Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
317
- * and the Unicode line terminators U+2028 and U+2029.
318
- *
319
- * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
320
- *
321
- * @example
322
- * ```ts
323
- * jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
324
- * ```
325
- */
326
- function jsStringEscape(input) {
327
- return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
328
- switch (character) {
329
- case "\"":
330
- case "'":
331
- case "\\": return `\\${character}`;
332
- case "\n": return "\\n";
333
- case "\r": return "\\r";
334
- case "\u2028": return "\\u2028";
335
- case "\u2029": return "\\u2029";
336
- default: return "";
337
- }
338
- });
339
- }
340
- /**
341
- * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
342
- * Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
343
- * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
344
- *
345
- * @example
346
- * ```ts
347
- * toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
348
- * toRegExpString('^(?im)foo', null) // '/^foo/im'
349
- * ```
350
- */
351
- function toRegExpString(text, func = "RegExp") {
352
- const raw = trimQuotes(text);
353
- const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
354
- const replacementTarget = match?.[1] ?? "";
355
- const matchedFlags = match?.[2];
356
- const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
357
- const { source, flags } = new RegExp(cleaned, matchedFlags);
358
- if (func === null) return `/${source}/${flags}`;
359
- return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
360
- }
361
- /**
362
- * Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
363
- * objects recurse with fixed indentation, so the result drops straight into an object literal
364
- * without re-parsing.
365
- *
366
- * @example
367
- * ```ts
368
- * stringifyObject({ foo: 'bar', nested: { a: 1 } })
369
- * // 'foo: bar,\nnested: {\n a: 1\n }'
370
- * ```
371
- */
372
- function stringifyObject(value) {
373
- return Object.entries(value).map(([key, val]) => {
374
- if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
375
- return `${key}: ${val}`;
376
- }).filter(Boolean).join(",\n");
377
- }
378
- /**
379
- * Renders a dotted path or string array as an optional-chaining accessor expression rooted at
380
- * `accessor`. Returns `null` for an empty path.
381
- *
382
- * @example
383
- * ```ts
384
- * getNestedAccessor('pagination.next.id', 'lastPage')
385
- * // "lastPage?.['pagination']?.['next']?.['id']"
386
- * ```
387
- */
388
- function getNestedAccessor(param, accessor) {
389
- const parts = Array.isArray(param) ? param : param.split(".");
390
- if (parts.length === 0 || parts.length === 1 && parts[0] === "") return null;
391
- return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
392
- }
393
- //#endregion
394
- //#region src/utils/schemaGraph.ts
395
- /**
396
- * Memoized inner pass that walks a single node and returns the names of every schema it references.
397
- */
398
- const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
399
- const refs = /* @__PURE__ */ new Set();
400
- require_visitor.collect(node, { schema(child) {
401
- if (child.type === "ref") {
402
- const name = require_refs.resolveRefName(child);
403
- if (name) refs.add(name);
404
- }
405
- } });
406
- return refs;
407
- });
408
- /**
409
- * Collects the names of every ref found anywhere inside a node's own subtree.
410
- *
411
- * Each ref contributes its name only, so the schema it points to is never traversed here. Pass `out`
412
- * to accumulate names from several nodes into one set.
413
- *
414
- * @example Collect refs from a single schema
415
- * ```ts
416
- * const names = collectReferencedSchemaNames(petSchema)
417
- * // Set { 'Category', 'Tag' }
418
- * ```
419
- *
420
- * @example Accumulate refs from multiple schemas into one set
421
- * ```ts
422
- * const out = new Set<string>()
423
- * for (const schema of schemas) {
424
- * collectReferencedSchemaNames(schema, out)
425
- * }
426
- * ```
427
- */
428
- function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
429
- if (!node) return out;
430
- for (const name of collectSchemaRefs(node)) out.add(name);
431
- return out;
432
- }
433
- /**
434
- * Memoized two-level cache keyed first on the operations array, then on the schemas array.
435
- */
436
- const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
437
- function computeUsedSchemaNames(operations, schemas) {
438
- const schemaMap = /* @__PURE__ */ new Map();
439
- for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
440
- const result = /* @__PURE__ */ new Set();
441
- function visitSchema(schema) {
442
- const directRefs = collectReferencedSchemaNames(schema);
443
- for (const name of directRefs) if (!result.has(name)) {
444
- result.add(name);
445
- const namedSchema = schemaMap.get(name);
446
- if (namedSchema) visitSchema(namedSchema);
447
- }
448
- }
449
- for (const op of operations) for (const schema of require_visitor.collectLazy(op, {
450
- depth: "shallow",
451
- schema: (node) => node
452
- })) visitSchema(schema);
453
- return result;
454
- }
455
- /**
456
- * Collects the names of all top-level schemas transitively used by a set of operations.
457
- *
458
- * An operation uses a schema when its parameters, request body, or responses reference it, directly
459
- * or through other named schemas. Once a name is added to the result it is not revisited, so
460
- * reference cycles terminate.
461
- *
462
- * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
463
- *
464
- * @example Only generate schemas referenced by included operations
465
- * ```ts
466
- * const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
467
- * const allowed = collectUsedSchemaNames(includedOps, schemas)
468
- *
469
- * for (const schema of schemas) {
470
- * if (schema.name && !allowed.has(schema.name)) continue
471
- * // generate schema
472
- * }
473
- * ```
474
- */
475
- function collectUsedSchemaNames(operations, schemas) {
476
- return collectUsedSchemaNamesMemo(operations)(schemas);
477
- }
478
- const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
479
- const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
480
- const graph = /* @__PURE__ */ new Map();
481
- for (const schema of schemas) {
482
- if (!schema.name) continue;
483
- graph.set(schema.name, collectReferencedSchemaNames(schema));
484
- }
485
- const circular = /* @__PURE__ */ new Set();
486
- for (const start of graph.keys()) {
487
- const visited = /* @__PURE__ */ new Set();
488
- const stack = [...graph.get(start) ?? []];
489
- while (stack.length > 0) {
490
- const node = stack.pop();
491
- if (node === start) {
492
- circular.add(start);
493
- break;
494
- }
495
- if (visited.has(node)) continue;
496
- visited.add(node);
497
- const next = graph.get(node);
498
- if (next) for (const r of next) stack.push(r);
499
- }
500
- }
501
- return circular;
502
- });
503
- /**
504
- * Finds every schema that takes part in a circular dependency chain, including direct self-loops.
505
- *
506
- * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
507
- * the generated code does not recurse forever. Refs are followed by name only, so the walk stays
508
- * linear in the size of the schema graph.
509
- *
510
- * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
511
- */
512
- function findCircularSchemas(schemas) {
513
- if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
514
- return findCircularSchemasMemo(schemas);
515
- }
516
- /**
517
- * Returns `true` when a schema, or anything nested inside it, references a circular schema.
518
- *
519
- * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
520
- * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
521
- *
522
- * @note Stops at the first matching circular ref.
523
- */
524
- function containsCircularRef(node, { circularSchemas, excludeName }) {
525
- if (!node || circularSchemas.size === 0) return false;
526
- for (const _ of require_visitor.collectLazy(node, { schema(child) {
527
- if (child.type !== "ref") return null;
528
- const name = require_refs.resolveRefName(child);
529
- return name && name !== excludeName && circularSchemas.has(name) ? true : null;
530
- } })) return true;
531
- return false;
532
- }
533
- //#endregion
534
- //#region src/utils/schemaTraversal.ts
535
- /**
536
- * Maps each property of an object schema to its transformed output. Pairs every result with the
537
- * original property so the printer keeps full control over modifiers, getters, and key syntax.
538
- *
539
- * @example
540
- * ```ts
541
- * const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
542
- * // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
543
- * ```
544
- */
545
- function mapSchemaProperties(node, transform) {
546
- return node.properties.map((property) => ({
547
- name: property.name,
548
- property,
549
- output: transform(property.schema)
550
- }));
551
- }
552
- /**
553
- * Maps each member of a union or intersection schema to its transformed output, pairing every
554
- * result with the original member.
555
- */
556
- function mapSchemaMembers(node, transform) {
557
- return (node.members ?? []).map((schema) => ({
558
- schema,
559
- output: transform(schema)
560
- }));
561
- }
562
- /**
563
- * Maps each item of an array or tuple schema to its transformed output, pairing every result with
564
- * the original item.
565
- */
566
- function mapSchemaItems(node, transform) {
567
- return (node.items ?? []).map((schema) => ({
568
- schema,
569
- output: transform(schema)
570
- }));
571
- }
572
- /**
573
- * Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key
574
- * is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation
575
- * of a recursive schema until first access.
576
- *
577
- * @example
578
- * ```ts
579
- * lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })
580
- * // "get parent() { return z.lazy(() => Pet) }"
581
- * ```
582
- */
583
- function lazyGetter({ name, body }) {
584
- return `get ${objectKey(name)}() { return ${body} }`;
585
- }
586
- //#endregion
587
- exports.buildJSDoc = buildJSDoc;
588
- exports.buildList = buildList;
589
- exports.buildObject = buildObject;
590
- exports.childName = require_refs.childName;
591
- exports.collectUsedSchemaNames = collectUsedSchemaNames;
592
- exports.containsCircularRef = containsCircularRef;
593
- exports.enumPropName = require_refs.enumPropName;
594
- exports.extractRefName = require_refs.extractRefName;
595
- exports.extractStringsFromNodes = require_visitor.extractStringsFromNodes;
596
- exports.findCircularSchemas = findCircularSchemas;
597
- exports.getNestedAccessor = getNestedAccessor;
598
- exports.isStringType = require_refs.isStringType;
599
- exports.isValidVarName = isValidVarName;
600
- exports.jsStringEscape = jsStringEscape;
601
- exports.lazyGetter = lazyGetter;
602
- exports.mapSchemaItems = mapSchemaItems;
603
- exports.mapSchemaMembers = mapSchemaMembers;
604
- exports.mapSchemaProperties = mapSchemaProperties;
605
- exports.mergeAdjacentObjectsLazy = mergeAdjacentObjectsLazy;
606
- exports.objectKey = objectKey;
607
- exports.stringify = stringify;
608
- exports.stringifyObject = stringifyObject;
609
- exports.syncSchemaRef = require_refs.syncSchemaRef;
610
- exports.toRegExpString = toRegExpString;
611
- exports.trimQuotes = trimQuotes;
612
-
613
- //# sourceMappingURL=utils.cjs.map