@kubb/parser-ts 5.27.1 → 5.28.1

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/index.cjs CHANGED
@@ -11,52 +11,63 @@ var compatibility = {
11
11
  "node": ">=22.22"
12
12
  };
13
13
  // package.json
14
- var version = "5.27.1";
15
- // src/inline.ts
16
- const keyStarts = /* @__PURE__ */ new Set([
17
- yuku.TokenKind.LeftBrace,
18
- yuku.TokenKind.Comma,
19
- yuku.TokenKind.Semicolon,
20
- yuku.TokenKind.LeftParen
21
- ]);
22
- /**
23
- * Calls `replace` for every identifier that references something, and swaps in what it returns.
24
- * yuku's tokens leave out strings, comments and template text; member access (`x.Name`) and keys are skipped here.
25
- */
26
- function replaceIdentifiers(text, replace, lang = "ts") {
27
- const tokens = (0, yuku.parse)(text, {
28
- lang,
29
- sourceType: "module",
30
- tokens: true
31
- }).tokens;
32
- const kinds = Array.from({ length: tokens.length }, (_, i) => tokens.kind(i));
33
- let out = "";
34
- let last = 0;
35
- for (const [i, kind] of kinds.entries()) {
36
- if (kind !== yuku.TokenKind.Identifier || kinds[i - 1] === yuku.TokenKind.Dot || kinds[i - 1] === yuku.TokenKind.OptionalChaining) continue;
37
- if ((kinds[i + 1] === yuku.TokenKind.Colon || kinds[i + 1] === yuku.TokenKind.Question && kinds[i + 2] === yuku.TokenKind.Colon) && (i === 0 || tokens.newlineBefore(i) || keyStarts.has(kinds[i - 1]))) continue;
38
- const replacement = replace(tokens.text(i));
39
- if (replacement === void 0) continue;
40
- out += text.slice(last, tokens.start(i)) + replacement;
41
- last = tokens.end(i);
42
- }
43
- return out + text.slice(last);
44
- }
45
- function createInline(lang) {
46
- return {
47
- replaceIdentifiers: (text, replace) => replaceIdentifiers(text, replace, lang),
48
- wrap: (expression) => /^[\w$.]+$/.test(expression) ? expression : `(${expression})`
49
- };
50
- }
14
+ var version = "5.28.1";
15
+ // ../../internals/utils/src/promise.ts
51
16
  /**
52
- * Inline support for TypeScript and JavaScript files: identifiers are found with {@link replaceIdentifiers},
53
- * and a definition that is more than a name or a dotted path goes in parentheses.
54
- */
55
- const inlineTs = createInline("ts");
56
- /**
57
- * {@link inlineTs} for `.tsx` and `.jsx` files, where JSX text and attribute names are not identifiers.
17
+ * Returns the value cached under `key` in `store`, computing and storing it on the first call.
18
+ * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
19
+ * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
20
+ *
21
+ * @example
22
+ * `const refs = memo(refCache, node, () => collectRefs(node))`
58
23
  */
59
- const inlineTsx = createInline("tsx");
24
+ function memo(store, key, compute) {
25
+ const cached = store.get(key);
26
+ if (cached !== void 0 || store.has(key)) return cached;
27
+ const value = compute();
28
+ store.set(key, value);
29
+ return value;
30
+ }
31
+ var BoundedStore = class {
32
+ #entry = /* @__PURE__ */ new Map();
33
+ #max;
34
+ constructor(max) {
35
+ this.#max = max;
36
+ }
37
+ has(key) {
38
+ return this.#entry.has(key);
39
+ }
40
+ get(key) {
41
+ return this.#entry.get(key);
42
+ }
43
+ set(key, value) {
44
+ if (this.#entry.size >= this.#max) this.#entry.clear();
45
+ this.#entry.set(key, value);
46
+ }
47
+ };
48
+ var LastEntryStore = class extends BoundedStore {
49
+ constructor() {
50
+ super(1);
51
+ }
52
+ #touch(key) {
53
+ if (!super.has(key)) return false;
54
+ this.set(key, super.get(key));
55
+ return true;
56
+ }
57
+ has(key) {
58
+ return this.#touch(key);
59
+ }
60
+ get(key) {
61
+ return this.#touch(key) ? super.get(key) : void 0;
62
+ }
63
+ };
64
+ function createStore({ weak, max } = {}) {
65
+ if (weak) return /* @__PURE__ */ new WeakMap();
66
+ if (max === void 0) return /* @__PURE__ */ new Map();
67
+ if (max !== 1) return new BoundedStore(max);
68
+ return new LastEntryStore();
69
+ }
70
+ memo.create = createStore;
60
71
  // ../../internals/utils/src/text.ts
61
72
  /**
62
73
  * Indents every non-empty line of `text` by `unit`, leaving blank lines empty.
@@ -84,6 +95,641 @@ function dedent(text) {
84
95
  const min = indents.reduce((lowest, indent) => indent !== -1 && indent < lowest ? indent : lowest, 1e400);
85
96
  return lines.slice(start, end + 1).map((line, i) => indents[start + i] === -1 ? "" : line.slice(min)).join("\n");
86
97
  }
98
+ /**
99
+ * Returns `name` when it is free, otherwise the first free `name2`, `name3`, and so on.
100
+ * @example
101
+ * `uniqueName('Options', (name) => name === 'Options') // 'Options2'`
102
+ */
103
+ function uniqueName(name, isTaken) {
104
+ let candidate = name;
105
+ for (let suffix = 2; isTaken(candidate); suffix++) candidate = `${name}${suffix}`;
106
+ return candidate;
107
+ }
108
+ // ../../internals/utils/src/renamer.ts
109
+ const reserved = Symbol("reserved");
110
+ /**
111
+ * Hands out names that do not clash, adding 2, 3 and so on when a name is taken, and remembers which owner holds each.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * const renamer = createRenamer()
116
+ * renamer.reserve({ name: 'Response' }) // a global the file uses
117
+ * renamer.assign({ name: 'Response' }) // 'Response2'
118
+ * ```
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * const renamer = createRenamer()
123
+ * renamer.bind({ name: 'Options', owner: '@kubb/client' })
124
+ * renamer.assign({ name: 'Options', owner: '@kubb/client' }) // 'Options', the same owner
125
+ * renamer.assign({ name: 'Options', owner: './models.ts' }) // 'Options2'
126
+ * ```
127
+ */
128
+ var Renamer = class {
129
+ #owners = /* @__PURE__ */ new Map();
130
+ /**
131
+ * Keeps `name` from being assigned, unless something already holds it.
132
+ */
133
+ reserve({ name }) {
134
+ if (!this.#owners.has(name)) this.#owners.set(name, reserved);
135
+ }
136
+ /**
137
+ * Gives `name` to `owner` as it is, such as a name a file already imports.
138
+ */
139
+ bind({ name, owner }) {
140
+ this.#owners.set(name, owner);
141
+ }
142
+ /**
143
+ * Returns the first free name from `name`, and claims every name it emits for `owner`.
144
+ */
145
+ assign({ name, owner, emits = (candidate) => candidate }) {
146
+ const holder = owner ?? Symbol(name);
147
+ const read = /* @__PURE__ */ new Map();
148
+ const claimed = (candidate) => {
149
+ const known = read.get(candidate);
150
+ if (known) return known;
151
+ const names = emits(candidate);
152
+ const list = typeof names === "string" ? [names] : names;
153
+ read.set(candidate, list);
154
+ return list;
155
+ };
156
+ const isTaken = (candidate) => claimed(candidate).some((emitted) => this.#owners.has(emitted) && this.#owners.get(emitted) !== holder);
157
+ const local = uniqueName(name, isTaken);
158
+ for (const emitted of claimed(local)) this.#owners.set(emitted, holder);
159
+ return local;
160
+ }
161
+ };
162
+ /**
163
+ * Creates an empty renamer.
164
+ */
165
+ function createRenamer() {
166
+ return new Renamer();
167
+ }
168
+ // src/inline.ts
169
+ const placeholder = "__kubb";
170
+ const contexts = {
171
+ code: ["", ""],
172
+ type: [`type ${placeholder} = `, ""],
173
+ value: [`const ${placeholder} = (`, "\n)"],
174
+ parameters: [`function ${placeholder}(`, "\n) {}"],
175
+ typeParameters: [`function ${placeholder}<`, "\n>() {}"]
176
+ };
177
+ const kinds = Object.keys(contexts);
178
+ const analyses = memo.create({ max: 1e3 });
179
+ function analyze(text, lang, kind) {
180
+ return memo(analyses, `${lang}\0${kind ?? ""}\0${text}`, () => {
181
+ const first = kind ?? "code";
182
+ const fallback = parseAs(text, lang, first);
183
+ if (fallback.clean) return fallback.analysis;
184
+ for (const candidate of kinds.filter((item) => item !== first)) {
185
+ const parsed = parseAs(text, lang, candidate);
186
+ if (parsed.clean) return parsed.analysis;
187
+ }
188
+ return fallback.analysis;
189
+ });
190
+ }
191
+ function parseAs(text, lang, kind) {
192
+ const [before, after] = contexts[kind];
193
+ const file = (0, yuku.parse)(before + text + after, {
194
+ lang,
195
+ sourceType: "module",
196
+ analyze: true
197
+ });
198
+ return {
199
+ analysis: {
200
+ references: file.references.filter((reference) => !reference.binding && reference.node.type !== "JSXIdentifier").map((reference) => {
201
+ const parent = file.parentOf(reference.node);
202
+ const shorthand = parent?.type === "Property" && parent.shorthand;
203
+ const exported = parent?.type === "ExportSpecifier" && parent.exported.start === parent.local.start;
204
+ return {
205
+ name: reference.name,
206
+ start: reference.node.start - before.length,
207
+ end: reference.node.end - before.length,
208
+ shorthand,
209
+ exported
210
+ };
211
+ }),
212
+ names: [...file.bindings.map((binding) => binding.name), ...file.references.map((reference) => reference.name)].filter((name) => name !== placeholder)
213
+ },
214
+ clean: !file.diagnostics.some((diagnostic) => diagnostic.severity === "error")
215
+ };
216
+ }
217
+ /**
218
+ * Calls `replace` for every name in `text` that refers to something declared outside it, and swaps in what it returns.
219
+ * Bound names (parameters, type parameters, locals), keys, members, strings, comments and JSX tag names are left alone. A
220
+ * shorthand property `{ x }` keeps its key, so it becomes `{ x: replacement }`, and `export { x }` keeps its export name.
221
+ */
222
+ function replaceIdentifiers(text, replace, lang = "ts", kind) {
223
+ let out = "";
224
+ let last = 0;
225
+ for (const { name, start, end, shorthand, exported } of analyze(text, lang, kind).references) {
226
+ const replacement = replace(name);
227
+ if (replacement === void 0) continue;
228
+ out += text.slice(last, start) + (shorthand ? `${name}: ${replacement}` : exported ? `${replacement} as ${name}` : replacement);
229
+ last = end;
230
+ }
231
+ return out + text.slice(last);
232
+ }
233
+ /**
234
+ * The free names in `text`, in order, the same ones `replaceIdentifiers` would offer to replace.
235
+ */
236
+ function referencesIn(text, lang, kind) {
237
+ return analyze(text, lang, kind).references.map((reference) => reference.name);
238
+ }
239
+ /**
240
+ * Every name `text` declares or uses, so a declaration added next to it never shadows one.
241
+ */
242
+ function namesIn(text, lang, kind) {
243
+ return analyze(text, lang, kind).names;
244
+ }
245
+ /**
246
+ * Makes `expression` safe to put where a name was: a name or dotted path stays bare, and anything else goes in parentheses.
247
+ */
248
+ function wrap(expression) {
249
+ return /^[\w$.]+$/.test(expression) ? expression : `(${expression})`;
250
+ }
251
+ // src/definitions.ts
252
+ /**
253
+ * Every definition of the virtual files in one run, and the fragments that refer to them. Each is read on first use and
254
+ * kept, because the same virtual bodies are read for every file that imports them.
255
+ *
256
+ * @example
257
+ * ```ts
258
+ * const definitions = createDefinitions({ virtual, lang: 'ts' })
259
+ * definitions.resolve({ file, name: 'AddPetOptions' }) // the definition the name points at, or `undefined`
260
+ * definitions.fragment({ file, text: 'options: AddPetOptions', kind: 'parameters' })
261
+ * ```
262
+ */
263
+ var Definitions = class {
264
+ lang;
265
+ #virtual;
266
+ #bindings = /* @__PURE__ */ new WeakMap();
267
+ #definitions = /* @__PURE__ */ new Map();
268
+ #fragments = /* @__PURE__ */ new Map();
269
+ constructor({ virtual, lang }) {
270
+ this.#virtual = virtual;
271
+ this.lang = lang;
272
+ }
273
+ isVirtual(path) {
274
+ return this.#virtual.has(path);
275
+ }
276
+ /**
277
+ * The virtual definition `name` points at in `file`, or `undefined` when it points at nothing virtual.
278
+ */
279
+ resolve({ file, name }) {
280
+ const binding = this.#bindingsOf(file).get(name);
281
+ return binding && this.#definitionOf(binding);
282
+ }
283
+ fragment({ file, text, kind }) {
284
+ const id = `${file.path}\0${kind}\0${text}`;
285
+ const known = this.#fragments.get(id);
286
+ if (known) return known;
287
+ const names = referencesIn(text, this.lang, kind);
288
+ const references = names.map((name) => this.resolve({
289
+ file,
290
+ name
291
+ }));
292
+ const external = new Set(names.filter((_, index) => !references[index]));
293
+ const fragment = {
294
+ file,
295
+ text,
296
+ kind,
297
+ references,
298
+ imports: file.imports.flatMap((imp) => this.isVirtual(imp.path) ? [] : pickNames({
299
+ imp,
300
+ used: external
301
+ })),
302
+ unresolved: namesIn(text, this.lang, kind).filter((name) => !this.resolve({
303
+ file,
304
+ name
305
+ }) && !importsName({
306
+ file,
307
+ name
308
+ }))
309
+ };
310
+ this.#fragments.set(id, fragment);
311
+ return fragment;
312
+ }
313
+ body(definition) {
314
+ return this.fragment({
315
+ file: definition.file,
316
+ text: definition.body ?? "",
317
+ kind: definition.space
318
+ });
319
+ }
320
+ #bindingsOf(file) {
321
+ const known = this.#bindings.get(file);
322
+ if (known) return known;
323
+ const bindings = /* @__PURE__ */ new Map();
324
+ for (const imp of file.imports) {
325
+ if (!this.isVirtual(imp.path)) continue;
326
+ for (const item of _kubb_ast.ast.file.getNames(imp)) if (!bindings.has(localName(item))) bindings.set(localName(item), {
327
+ path: imp.path,
328
+ name: item.name
329
+ });
330
+ }
331
+ if (this.isVirtual(file.path)) {
332
+ for (const source of file.sources) if (source.name) bindings.set(source.name, {
333
+ path: file.path,
334
+ name: source.name
335
+ });
336
+ }
337
+ this.#bindings.set(file, bindings);
338
+ return bindings;
339
+ }
340
+ #definitionOf(binding) {
341
+ const id = idOf(binding);
342
+ const known = this.#definitions.get(id);
343
+ if (known) return known;
344
+ const definition = readDefinition({
345
+ ...binding,
346
+ id,
347
+ file: this.#virtual.get(binding.path)
348
+ });
349
+ this.#definitions.set(id, definition);
350
+ return definition;
351
+ }
352
+ };
353
+ function readDefinition({ id, name, path, file }) {
354
+ const [source, ...others] = file.sources.filter((item) => item.name === name);
355
+ const node = declarationOf(source);
356
+ const body = bodyOf({
357
+ source,
358
+ node
359
+ });
360
+ return {
361
+ id,
362
+ name,
363
+ file,
364
+ space: source ? _kubb_ast.ast.file.getSpace(source) : "value",
365
+ body,
366
+ isPath: isPath(body),
367
+ constant: node?.kind === _kubb_ast.ast.node.kinds.const ? node : void 0,
368
+ problem: problemOf({
369
+ name,
370
+ path,
371
+ body,
372
+ duplicated: others.length > 0
373
+ })
374
+ };
375
+ }
376
+ function bodyOf({ source, node }) {
377
+ if (source?.inline) return source.inline.expression;
378
+ if (!node) return void 0;
379
+ return _kubb_ast.ast.node.getText(node.nodes) || void 0;
380
+ }
381
+ function isPath(body) {
382
+ if (body === void 0) return false;
383
+ const trimmed = body.trim();
384
+ return wrap(trimmed) === trimmed;
385
+ }
386
+ /**
387
+ * Creates the definition table for the virtual files of one run.
388
+ */
389
+ function createDefinitions(options) {
390
+ return new Definitions(options);
391
+ }
392
+ /**
393
+ * The id of a name in a module: the module's path and the name it exports.
394
+ */
395
+ function idOf({ path, name }) {
396
+ return `${path}\0${name}`;
397
+ }
398
+ /**
399
+ * The name an import entry binds in its file: its alias, or else its name.
400
+ */
401
+ function localName(item) {
402
+ return item.alias ?? item.name;
403
+ }
404
+ function withNames({ imp, names }) {
405
+ return _kubb_ast.ast.factory.createImport({
406
+ path: imp.path,
407
+ ...imp.root != null ? { root: imp.root } : {},
408
+ names
409
+ });
410
+ }
411
+ function problemOf({ name, path, body, duplicated }) {
412
+ if (body === void 0) return `"${name}" is imported from "${path}", which never writes it and has no inline definition for it.`;
413
+ if (duplicated) return `"${name}" from "${path}" has more than one declaration, so its uses cannot be told apart.`;
414
+ }
415
+ function declarationOf(source) {
416
+ const node = source?.nodes?.length === 1 ? source.nodes[0] : void 0;
417
+ return node?.kind === _kubb_ast.ast.node.kinds.const || node?.kind === _kubb_ast.ast.node.kinds.type ? node : void 0;
418
+ }
419
+ function importsName({ file, name }) {
420
+ return file.imports.some((imp) => _kubb_ast.ast.file.getNames(imp).some((item) => localName(item) === name));
421
+ }
422
+ function pickNames({ imp, used }) {
423
+ const names = _kubb_ast.ast.file.getNames(imp).filter((item) => used.has(localName(item)));
424
+ return names.length > 0 ? [withNames({
425
+ imp,
426
+ names
427
+ })] : [];
428
+ }
429
+ // src/nodeText.ts
430
+ const TEXT_FIELDS = {
431
+ Text: { value: "inherit" },
432
+ Jsx: { value: "inherit" },
433
+ Function: {
434
+ params: "parameters",
435
+ generics: "typeParameters",
436
+ returnType: "type"
437
+ },
438
+ ArrowFunction: {
439
+ params: "parameters",
440
+ generics: "typeParameters",
441
+ returnType: "type"
442
+ },
443
+ Const: { type: "type" }
444
+ };
445
+ const NESTED_KIND = {
446
+ Type: "type",
447
+ Const: "value",
448
+ Function: "code",
449
+ ArrowFunction: "code"
450
+ };
451
+ /**
452
+ * Rewrites every string field of `nodes`, passing what each one holds. JSDoc stays as written.
453
+ */
454
+ function rewriteNodes(nodes, rewrite, kind = "code") {
455
+ return nodes?.map((node) => {
456
+ if (typeof node === "string") return rewrite(node, kind);
457
+ if (node.kind === _kubb_ast.ast.node.kinds.break) return node;
458
+ const next = { ...node };
459
+ for (const [field, fieldKind] of Object.entries(TEXT_FIELDS[node.kind] ?? {})) next[field] = rewriteField(next[field], (text) => rewrite(text, fieldKind === "inherit" ? kind : fieldKind));
460
+ if ("nodes" in node && node.nodes) next.nodes = rewriteNodes(node.nodes, rewrite, NESTED_KIND[node.kind] ?? kind);
461
+ return next;
462
+ });
463
+ }
464
+ function rewriteField(value, rewrite) {
465
+ if (Array.isArray(value)) return value.map(rewrite);
466
+ return typeof value === "string" && value ? rewrite(value) : value;
467
+ }
468
+ // src/fileRewriter.ts
469
+ var FileRewriter = class {
470
+ #file;
471
+ #definitions;
472
+ #renamer;
473
+ #uses = /* @__PURE__ */ new Map();
474
+ #following = /* @__PURE__ */ new Set();
475
+ #writing = /* @__PURE__ */ new Set();
476
+ #locals = /* @__PURE__ */ new Map();
477
+ #declarations = [];
478
+ #carried = [];
479
+ #problems = [];
480
+ constructor({ file, definitions }) {
481
+ this.#file = file;
482
+ this.#definitions = definitions;
483
+ this.#renamer = createFileRenamer(file);
484
+ }
485
+ rewrite() {
486
+ const file = this.#file;
487
+ const { lang } = this.#definitions;
488
+ for (const source of file.sources) rewriteNodes(source.nodes, (text, kind) => {
489
+ for (const name of namesIn(text, lang, kind)) this.#renamer.reserve({ name });
490
+ this.#count(this.#definitions.fragment({
491
+ file,
492
+ text,
493
+ kind
494
+ }));
495
+ return text;
496
+ });
497
+ const sources = file.sources.map((source) => ({
498
+ ...source,
499
+ nodes: rewriteNodes(source.nodes, (text, kind) => replaceIdentifiers(text, (name) => this.#replacement({
500
+ from: file,
501
+ name
502
+ }), lang, kind))
503
+ }));
504
+ const carried = this.#carried.map((imp) => imp.root ? {
505
+ ...imp,
506
+ root: file.path
507
+ } : imp);
508
+ const imports = [...file.imports.filter((imp) => !this.#definitions.isVirtual(imp.path)), ...carried];
509
+ return {
510
+ file: _kubb_ast.ast.factory.createFile({
511
+ ...file,
512
+ sources: [...this.#declarations, ...sources],
513
+ imports
514
+ }),
515
+ problems: this.#problems
516
+ };
517
+ }
518
+ #count(fragment) {
519
+ for (const name of fragment.unresolved) this.#renamer.reserve({ name });
520
+ for (const definition of fragment.references) if (definition?.body !== void 0) this.#countUse(definition);
521
+ }
522
+ #countUse(definition) {
523
+ const { id } = definition;
524
+ const seen = this.#uses.get(id) ?? 0;
525
+ this.#uses.set(id, seen + 1);
526
+ if (definition.isPath && !this.#following.has(id)) {
527
+ this.#following.add(id);
528
+ this.#count(this.#definitions.body(definition));
529
+ this.#following.delete(id);
530
+ return;
531
+ }
532
+ if (seen === 0) this.#count(this.#definitions.body(definition));
533
+ }
534
+ #replacement({ from, name }) {
535
+ const definition = this.#definitions.resolve({
536
+ file: from,
537
+ name
538
+ });
539
+ const written = definition && this.#write({
540
+ from,
541
+ definition
542
+ });
543
+ return written === name ? void 0 : written;
544
+ }
545
+ #write({ from, definition }) {
546
+ if (definition.problem) return this.#report({
547
+ from,
548
+ message: definition.problem
549
+ });
550
+ return this.#locals.get(definition.id) ?? this.#writeOnce({
551
+ from,
552
+ definition
553
+ });
554
+ }
555
+ #writeOnce({ from, definition }) {
556
+ const declare = this.#declares(definition);
557
+ const early = declare && definition.space === "type" ? this.#claim(definition) : void 0;
558
+ if (!early && this.#writing.has(definition.id)) return this.#report({
559
+ from,
560
+ message: `"${definition.name}" from "${definition.file.path}" is defined in terms of itself.`
561
+ });
562
+ const body = this.#writeBody(definition);
563
+ return declare ? this.#declare({
564
+ definition,
565
+ local: early ?? this.#claim(definition),
566
+ body
567
+ }) : wrap(body);
568
+ }
569
+ #declares({ id, isPath, space }) {
570
+ if (isPath) return false;
571
+ return space === "value" || (this.#uses.get(id) ?? 0) > 1;
572
+ }
573
+ #writeBody(definition) {
574
+ this.#writing.add(definition.id);
575
+ const body = this.#rewriteFragment(this.#definitions.body(definition));
576
+ this.#writing.delete(definition.id);
577
+ return body;
578
+ }
579
+ #rewriteFragment(fragment) {
580
+ const aliases = this.#carry(fragment.imports);
581
+ const { lang } = this.#definitions;
582
+ return replaceIdentifiers(fragment.text, (name) => this.#replacement({
583
+ from: fragment.file,
584
+ name
585
+ }) ?? aliases.get(name), lang, fragment.kind);
586
+ }
587
+ #declare({ definition, local, body }) {
588
+ const { constant, space } = definition;
589
+ const type = constant?.type ? this.#rewriteFragment(this.#definitions.fragment({
590
+ file: definition.file,
591
+ text: constant.type,
592
+ kind: "type"
593
+ })) : void 0;
594
+ const node = space === "type" ? _kubb_ast.ast.factory.createType({
595
+ name: local,
596
+ nodes: [_kubb_ast.ast.factory.createText(body)]
597
+ }) : _kubb_ast.ast.factory.createConst({
598
+ name: local,
599
+ ...type ? { type } : {},
600
+ ...constant?.asConst ? { asConst: true } : {},
601
+ nodes: [_kubb_ast.ast.factory.createText(body)]
602
+ });
603
+ this.#declarations.push(_kubb_ast.ast.factory.createSource({
604
+ name: local,
605
+ isTypeOnly: space === "type",
606
+ nodes: [node]
607
+ }));
608
+ return local;
609
+ }
610
+ #claim(definition) {
611
+ const local = this.#renamer.assign({
612
+ name: definition.name,
613
+ owner: definition.id
614
+ });
615
+ this.#locals.set(definition.id, local);
616
+ return local;
617
+ }
618
+ #carry(imports) {
619
+ const aliases = /* @__PURE__ */ new Map();
620
+ for (const imp of imports) {
621
+ const before = aliases.size;
622
+ const names = _kubb_ast.ast.file.getNames(imp).map((item) => {
623
+ const local = localName(item);
624
+ const name = this.#renamer.assign({
625
+ name: local,
626
+ owner: idOf({
627
+ path: imp.path,
628
+ name: item.name
629
+ })
630
+ });
631
+ if (name === local) return item;
632
+ aliases.set(local, name);
633
+ return {
634
+ ...item,
635
+ alias: name
636
+ };
637
+ });
638
+ this.#carried.push(aliases.size > before ? withNames({
639
+ imp,
640
+ names
641
+ }) : imp);
642
+ }
643
+ return aliases;
644
+ }
645
+ #report({ from, message }) {
646
+ this.#problems.push({
647
+ path: from.path,
648
+ message
649
+ });
650
+ }
651
+ };
652
+ /**
653
+ * Rewrites one file that imports from virtual files, in two passes. The first counts how often each definition is used and
654
+ * reserves every name in sight. The second writes each use: a path in place, a value as one local constant, and a type as
655
+ * one local type when it is used more than once, or in place otherwise.
656
+ *
657
+ * @example
658
+ * ```ts
659
+ * const { file, problems } = rewriteFile({ file: clientFile, definitions })
660
+ * ```
661
+ */
662
+ function rewriteFile(options) {
663
+ return new FileRewriter(options).rewrite();
664
+ }
665
+ function createFileRenamer(file) {
666
+ const renamer = createRenamer();
667
+ for (const imp of file.imports) for (const item of _kubb_ast.ast.file.getNames(imp)) renamer.bind({
668
+ name: localName(item),
669
+ owner: idOf({
670
+ path: imp.path,
671
+ name: item.name
672
+ })
673
+ });
674
+ for (const source of file.sources) if (source.name) renamer.bind({
675
+ name: source.name,
676
+ owner: file.path
677
+ });
678
+ return renamer;
679
+ }
680
+ // src/inlineFiles.ts
681
+ /**
682
+ * The parser's `inline` hook for `lang`. It also carries the deprecated `InlineLanguage` members, so a `@kubb/core` from
683
+ * before the hook, which reads `inline` as an object, still inlines these files.
684
+ *
685
+ * @example
686
+ * ```ts
687
+ * const inline = createInline({ lang: 'ts', extNames: ['.ts', '.js'] })
688
+ * inline(files) // { files, virtualPaths, problems }
689
+ * ```
690
+ */
691
+ function createInline({ lang, extNames }) {
692
+ return Object.assign((files) => inlineFiles({
693
+ files,
694
+ lang,
695
+ extNames
696
+ }), {
697
+ replaceIdentifiers(text, replace) {
698
+ return replaceIdentifiers(text, replace, lang);
699
+ },
700
+ wrap
701
+ });
702
+ }
703
+ /**
704
+ * Moves what a file imports from a virtual file (one marked `inline`, so it is never written) into that file. A value, and a
705
+ * type used more than once, becomes one local, non-exported declaration. A type used once or a bare name is written in place.
706
+ * The moved declarations' own imports move to the importing file.
707
+ */
708
+ function inlineFiles({ files, lang, extNames }) {
709
+ const virtual = new Map(files.filter(isInlineFile).map((file) => [file.path, file]));
710
+ const result = {
711
+ files: [],
712
+ virtualPaths: [...virtual.keys()],
713
+ problems: []
714
+ };
715
+ const definitions = createDefinitions({
716
+ virtual,
717
+ lang
718
+ });
719
+ for (const file of files) {
720
+ if (!extNames.includes(file.extname) || virtual.has(file.path) || !file.imports.some((imp) => virtual.has(imp.path))) continue;
721
+ const inlined = rewriteFile({
722
+ file,
723
+ definitions
724
+ });
725
+ result.files.push(inlined.file);
726
+ result.problems.push(...inlined.problems);
727
+ }
728
+ return result;
729
+ }
730
+ function isInlineFile(file) {
731
+ return !!file.inline || file.sources.length > 0 && file.sources.every((source) => source.inline);
732
+ }
87
733
  // src/utils.ts
88
734
  let compiler;
89
735
  /**
@@ -480,7 +1126,10 @@ const parserTs = (0, _kubb_core.defineExtension)({
480
1126
  return {
481
1127
  extNames: [".ts", ".js"],
482
1128
  print,
483
- inline: inlineTs,
1129
+ inline: createInline({
1130
+ lang: "ts",
1131
+ extNames: [".ts", ".js"]
1132
+ }),
484
1133
  parse(file) {
485
1134
  const extname = extension[file.extname] || void 0;
486
1135
  const source = file.sources.map((item) => printSource(item)).filter(Boolean).map((text) => text.trimEnd()).join("\n\n");
@@ -547,7 +1196,10 @@ const parserTsx = (0, _kubb_core.defineExtension)({
547
1196
  build: (options) => ({
548
1197
  ...parserTs(options),
549
1198
  extNames: [".tsx", ".jsx"],
550
- inline: inlineTsx
1199
+ inline: createInline({
1200
+ lang: "tsx",
1201
+ extNames: [".tsx", ".jsx"]
1202
+ })
551
1203
  })
552
1204
  });
553
1205
  exports.parserTs = parserTs;