@kubb/core 4.32.4 → 4.33.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.
Files changed (85) hide show
  1. package/dist/hooks.d.ts +1 -1
  2. package/dist/index.cjs +1695 -82
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.ts +150 -20
  5. package/dist/index.js +1673 -65
  6. package/dist/index.js.map +1 -1
  7. package/dist/{types-f_no0d7G.d.ts → types-DfjjJb2r.d.ts} +70 -27
  8. package/package.json +3 -24
  9. package/src/BarrelManager.ts +10 -31
  10. package/src/PackageManager.ts +13 -21
  11. package/src/PluginManager.ts +65 -87
  12. package/src/PromiseManager.ts +3 -5
  13. package/src/build.ts +61 -47
  14. package/src/config.ts +1 -1
  15. package/src/constants.ts +60 -0
  16. package/src/errors.ts +1 -14
  17. package/src/index.ts +6 -3
  18. package/src/types.ts +5 -14
  19. package/src/utils/FunctionParams.ts +7 -8
  20. package/src/utils/TreeNode.ts +12 -23
  21. package/src/utils/executeStrategies.ts +5 -3
  22. package/src/utils/formatters.ts +3 -20
  23. package/src/utils/getBarrelFiles.ts +8 -2
  24. package/src/utils/getConfigs.ts +6 -15
  25. package/src/utils/getPlugins.ts +7 -7
  26. package/src/utils/linters.ts +3 -20
  27. package/dist/fs-D4eqq6bR.cjs +0 -103
  28. package/dist/fs-D4eqq6bR.cjs.map +0 -1
  29. package/dist/fs-TVBCPkE-.js +0 -67
  30. package/dist/fs-TVBCPkE-.js.map +0 -1
  31. package/dist/fs.cjs +0 -8
  32. package/dist/fs.d.ts +0 -23
  33. package/dist/fs.js +0 -2
  34. package/dist/packageManager-_7I0WFQU.d.ts +0 -82
  35. package/dist/packageManager-jzjuEj2U.cjs +0 -1103
  36. package/dist/packageManager-jzjuEj2U.cjs.map +0 -1
  37. package/dist/packageManager-wMCQlgd6.js +0 -1024
  38. package/dist/packageManager-wMCQlgd6.js.map +0 -1
  39. package/dist/transformers-BwSpAhvT.js +0 -267
  40. package/dist/transformers-BwSpAhvT.js.map +0 -1
  41. package/dist/transformers-BweFhqh-.cjs +0 -380
  42. package/dist/transformers-BweFhqh-.cjs.map +0 -1
  43. package/dist/transformers.cjs +0 -24
  44. package/dist/transformers.d.ts +0 -108
  45. package/dist/transformers.js +0 -2
  46. package/dist/utils.cjs +0 -430
  47. package/dist/utils.cjs.map +0 -1
  48. package/dist/utils.d.ts +0 -290
  49. package/dist/utils.js +0 -402
  50. package/dist/utils.js.map +0 -1
  51. package/src/BaseGenerator.ts +0 -34
  52. package/src/fs/clean.ts +0 -5
  53. package/src/fs/exists.ts +0 -16
  54. package/src/fs/index.ts +0 -5
  55. package/src/fs/read.ts +0 -13
  56. package/src/fs/utils.ts +0 -32
  57. package/src/fs/write.ts +0 -46
  58. package/src/transformers/casing.ts +0 -62
  59. package/src/transformers/combineCodes.ts +0 -3
  60. package/src/transformers/createJSDocBlockText.ts +0 -9
  61. package/src/transformers/escape.ts +0 -31
  62. package/src/transformers/indent.ts +0 -3
  63. package/src/transformers/index.ts +0 -46
  64. package/src/transformers/nameSorter.ts +0 -9
  65. package/src/transformers/searchAndReplace.ts +0 -25
  66. package/src/transformers/stringify.ts +0 -25
  67. package/src/transformers/toRegExp.ts +0 -22
  68. package/src/transformers/transformReservedWord.ts +0 -106
  69. package/src/transformers/trim.ts +0 -18
  70. package/src/utils/AsyncEventEmitter.ts +0 -48
  71. package/src/utils/Cache.ts +0 -31
  72. package/src/utils/URLPath.ts +0 -146
  73. package/src/utils/buildJSDoc.ts +0 -34
  74. package/src/utils/checkOnlineStatus.ts +0 -40
  75. package/src/utils/formatHrtime.ts +0 -33
  76. package/src/utils/getNestedAccessor.ts +0 -25
  77. package/src/utils/index.ts +0 -26
  78. package/src/utils/packageManager.ts +0 -58
  79. package/src/utils/promise.ts +0 -13
  80. package/src/utils/renderTemplate.ts +0 -31
  81. package/src/utils/serializePluginOptions.ts +0 -29
  82. package/src/utils/timeout.ts +0 -11
  83. package/src/utils/tokenize.ts +0 -23
  84. package/src/utils/types.ts +0 -1
  85. package/src/utils/uniqueName.ts +0 -20
package/dist/utils.d.ts DELETED
@@ -1,290 +0,0 @@
1
- import { t as __name } from "./chunk--u3MIqq1.js";
2
- import { A as AsyncEventEmitter, E as PossiblePromise, S as UserConfig, n as Config } from "./types-f_no0d7G.js";
3
- import { a as getBarrelFiles, n as PackageManagerName, o as CLIOptions, r as detectPackageManager, s as defineConfig, t as PackageManagerInfo } from "./packageManager-_7I0WFQU.js";
4
-
5
- //#region src/utils/buildJSDoc.d.ts
6
- /**
7
- * Builds a JSDoc comment block with custom indentation.
8
- * @param comments - Array of comment strings to include in the JSDoc block
9
- * @param options - Configuration options for formatting
10
- * @returns Formatted JSDoc string or fallback string if no comments
11
- */
12
- declare function buildJSDoc(comments: Array<string>, options?: {
13
- /**
14
- * String to use for indenting each line of the JSDoc comment
15
- * @default ' * ' (3 spaces + asterisk + space)
16
- */
17
- indent?: string;
18
- /**
19
- * String to append after the closing JSDoc tag
20
- * @default '\n ' (newline + 2 spaces)
21
- */
22
- suffix?: string;
23
- /**
24
- * String to return when there are no comments
25
- * @default ' ' (2 spaces)
26
- */
27
- fallback?: string;
28
- }): string;
29
- //#endregion
30
- //#region src/utils/Cache.d.ts
31
- declare class Cache<T> {
32
- #private;
33
- get(key: string): Promise<T | null>;
34
- set(key: string, value: T): Promise<void>;
35
- delete(key: string): Promise<void>;
36
- clear(): Promise<void>;
37
- keys(): Promise<string[]>;
38
- values(): Promise<T[]>;
39
- flush(): Promise<void>;
40
- }
41
- //#endregion
42
- //#region src/utils/checkOnlineStatus.d.ts
43
- /**
44
- * Check if the system has internet connectivity
45
- * Uses DNS lookup to well-known stable domains as a lightweight connectivity test
46
- */
47
- declare function isOnline(): Promise<boolean>;
48
- /**
49
- * Execute a function only if online, otherwise silently skip
50
- */
51
- declare function executeIfOnline<T>(fn: () => Promise<T>): Promise<T | null>;
52
- //#endregion
53
- //#region src/utils/FunctionParams.d.ts
54
- type FunctionParamsASTWithoutType = {
55
- name?: string;
56
- type?: string;
57
- /**
58
- * @default true
59
- */
60
- required?: boolean;
61
- /**
62
- * @default true
63
- */
64
- enabled?: boolean;
65
- default?: string;
66
- };
67
- type FunctionParamsASTWithType = {
68
- name?: never;
69
- type: string;
70
- /**
71
- * @default true
72
- */
73
- required?: boolean;
74
- /**
75
- * @default true
76
- */
77
- enabled?: boolean;
78
- default?: string;
79
- };
80
- /**
81
- * @deprecated
82
- */
83
- type FunctionParamsAST = FunctionParamsASTWithoutType | FunctionParamsASTWithType;
84
- /**
85
- * @deprecated
86
- */
87
- declare class FunctionParams {
88
- #private;
89
- constructor();
90
- get items(): FunctionParamsAST[];
91
- add(item: FunctionParamsAST | Array<FunctionParamsAST | FunctionParamsAST[] | undefined> | undefined): FunctionParams;
92
- static toObject(items: FunctionParamsAST[]): FunctionParamsAST;
93
- toObject(): FunctionParamsAST;
94
- static toString(items: (FunctionParamsAST | FunctionParamsAST[])[]): string;
95
- toString(): string;
96
- }
97
- //#endregion
98
- //#region src/utils/formatHrtime.d.ts
99
- /**
100
- * Calculates elapsed time in milliseconds from a high-resolution start time.
101
- * Rounds to 2 decimal places to provide sub-millisecond precision without noise.
102
- */
103
- declare function getElapsedMs(hrStart: [number, number]): number;
104
- /**
105
- * Converts a millisecond duration into a human-readable string.
106
- * Adjusts units (ms, s, m s) based on the magnitude of the duration.
107
- */
108
- declare function formatMs(ms: number): string;
109
- /**
110
- * Convenience helper to get and format elapsed time in one step.
111
- */
112
- declare function formatHrtime(hrStart: [number, number]): string;
113
- //#endregion
114
- //#region src/utils/formatters.d.ts
115
- declare const formatters: {
116
- readonly prettier: {
117
- readonly command: "prettier";
118
- readonly args: (outputPath: string) => string[];
119
- readonly errorMessage: "Prettier not found";
120
- };
121
- readonly biome: {
122
- readonly command: "biome";
123
- readonly args: (outputPath: string) => string[];
124
- readonly errorMessage: "Biome not found";
125
- };
126
- readonly oxfmt: {
127
- readonly command: "oxfmt";
128
- readonly args: (outputPath: string) => string[];
129
- readonly errorMessage: "Oxfmt not found";
130
- };
131
- };
132
- type Formatter = keyof typeof formatters;
133
- /**
134
- * Detect which formatter is available in the system.
135
- *
136
- * @returns Promise that resolves to the first available formatter or undefined if none are found
137
- *
138
- * @remarks
139
- * Checks in order of preference: biome, oxfmt, prettier.
140
- * Uses the `--version` flag to detect if each formatter command is available.
141
- * This is a reliable method as all supported formatters implement this flag.
142
- *
143
- * @example
144
- * ```typescript
145
- * const formatter = await detectFormatter()
146
- * if (formatter) {
147
- * console.log(`Using ${formatter} for formatting`)
148
- * } else {
149
- * console.log('No formatter found')
150
- * }
151
- * ```
152
- */
153
- declare function detectFormatter(): Promise<Formatter | undefined>;
154
- //#endregion
155
- //#region src/utils/getConfigs.d.ts
156
- /**
157
- * Converting UserConfig to Config Array without a change in the object beside the JSON convert.
158
- */
159
- declare function getConfigs(config: ReturnType<typeof defineConfig> | UserConfig, args: CLIOptions): Promise<Array<Config>>;
160
- //#endregion
161
- //#region src/utils/getNestedAccessor.d.ts
162
- /**
163
- * Converts a param path (string with dot notation or array of strings) to a JavaScript accessor expression.
164
- * @param param - The param path, e.g., 'pagination.next.id' or ['pagination', 'next', 'id']
165
- * @param accessor - The base accessor, e.g., 'lastPage' or 'firstPage'
166
- * @returns A JavaScript accessor expression, e.g., "lastPage?.['pagination']?.['next']?.['id']", or undefined if param is empty
167
- *
168
- * @example
169
- * ```ts
170
- * getNestedAccessor('pagination.next.id', 'lastPage')
171
- * // returns: "lastPage?.['pagination']?.['next']?.['id']"
172
- *
173
- * getNestedAccessor(['pagination', 'next', 'id'], 'lastPage')
174
- * // returns: "lastPage?.['pagination']?.['next']?.['id']"
175
- *
176
- * getNestedAccessor('', 'lastPage')
177
- * // returns: undefined
178
- * ```
179
- */
180
- declare function getNestedAccessor(param: string | string[], accessor: string): string | undefined;
181
- //#endregion
182
- //#region src/utils/linters.d.ts
183
- declare const linters: {
184
- readonly eslint: {
185
- readonly command: "eslint";
186
- readonly args: (outputPath: string) => string[];
187
- readonly errorMessage: "Eslint not found";
188
- };
189
- readonly biome: {
190
- readonly command: "biome";
191
- readonly args: (outputPath: string) => string[];
192
- readonly errorMessage: "Biome not found";
193
- };
194
- readonly oxlint: {
195
- readonly command: "oxlint";
196
- readonly args: (outputPath: string) => string[];
197
- readonly errorMessage: "Oxlint not found";
198
- };
199
- };
200
- type Linter = keyof typeof linters;
201
- declare function detectLinter(): Promise<Linter | undefined>;
202
- //#endregion
203
- //#region src/utils/promise.d.ts
204
- declare function isPromise<T>(result: PossiblePromise<T>): result is Promise<T>;
205
- declare function isPromiseFulfilledResult<T = unknown>(result: PromiseSettledResult<unknown>): result is PromiseFulfilledResult<T>;
206
- declare function isPromiseRejectedResult<T>(result: PromiseSettledResult<unknown>): result is Omit<PromiseRejectedResult, 'reason'> & {
207
- reason: T;
208
- };
209
- //#endregion
210
- //#region src/utils/renderTemplate.d.ts
211
- declare function renderTemplate<TData extends Record<string, unknown> = Record<string, unknown>>(template: string, data?: TData | undefined): string;
212
- //#endregion
213
- //#region src/utils/serializePluginOptions.d.ts
214
- /**
215
- * Serialize plugin options for safe JSON transport.
216
- * Strips functions, symbols, and undefined values recursively.
217
- */
218
- declare function serializePluginOptions<TOptions extends object = object>(options: TOptions): TOptions;
219
- //#endregion
220
- //#region src/utils/timeout.d.ts
221
- declare function timeout(ms: number): Promise<unknown>;
222
- //#endregion
223
- //#region src/utils/tokenize.d.ts
224
- /** Shell-like tokenizer: splits a command string respecting single/double quotes. */
225
- declare function tokenize(command: string): string[];
226
- //#endregion
227
- //#region src/utils/URLPath.d.ts
228
- type URLObject = {
229
- url: string;
230
- params?: Record<string, string>;
231
- };
232
- type ObjectOptions = {
233
- type?: 'path' | 'template';
234
- replacer?: (pathParam: string) => string;
235
- stringify?: boolean;
236
- };
237
- type Options = {
238
- casing?: 'camelcase';
239
- };
240
- declare class URLPath {
241
- #private;
242
- path: string;
243
- constructor(path: string, options?: Options);
244
- /**
245
- * Convert Swagger path to URLPath(syntax of Express)
246
- * @example /pet/{petId} => /pet/:petId
247
- */
248
- get URL(): string;
249
- get isURL(): boolean;
250
- /**
251
- * Convert Swagger path to template literals/ template strings(camelcase)
252
- * @example /pet/{petId} => `/pet/${petId}`
253
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
254
- * @example /account/userID => `/account/${userId}`
255
- */
256
- get template(): string;
257
- get object(): URLObject | string;
258
- get params(): Record<string, string> | undefined;
259
- toObject({
260
- type,
261
- replacer,
262
- stringify
263
- }?: ObjectOptions): URLObject | string;
264
- /**
265
- * Convert Swagger path to template literals/ template strings(camelcase)
266
- * @example /pet/{petId} => `/pet/${petId}`
267
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
268
- * @example /account/userID => `/account/${userId}`
269
- */
270
- toTemplateString({
271
- prefix,
272
- replacer
273
- }?: {
274
- prefix?: string;
275
- replacer?: (pathParam: string) => string;
276
- }): string;
277
- getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined;
278
- /**
279
- * Convert Swagger path to URLPath(syntax of Express)
280
- * @example /pet/{petId} => /pet/:petId
281
- */
282
- toURLPath(): string;
283
- }
284
- //#endregion
285
- //#region src/utils/uniqueName.d.ts
286
- declare function getUniqueName(originalName: string, data: Record<string, number>): string;
287
- declare function setUniqueName(originalName: string, data: Record<string, number>): string;
288
- //#endregion
289
- export { AsyncEventEmitter, Cache, FunctionParams, type FunctionParamsAST, type PackageManagerInfo, type PackageManagerName, type URLObject, URLPath, buildJSDoc, detectFormatter, detectLinter, detectPackageManager, executeIfOnline, formatHrtime, formatMs, formatters, getBarrelFiles, getConfigs, getElapsedMs, getNestedAccessor, getUniqueName, isOnline, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, linters, renderTemplate, serializePluginOptions, setUniqueName, timeout, tokenize };
290
- //# sourceMappingURL=utils.d.ts.map
package/dist/utils.js DELETED
@@ -1,402 +0,0 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { a as formatMs, d as setUniqueName, i as formatHrtime, n as getBarrelFiles, o as getElapsedMs, r as URLPath, s as AsyncEventEmitter, t as detectPackageManager, u as getUniqueName } from "./packageManager-wMCQlgd6.js";
3
- import { f as camelCase } from "./transformers-BwSpAhvT.js";
4
- import dns from "node:dns";
5
- import { sortBy } from "remeda";
6
- import { x } from "tinyexec";
7
- //#region src/utils/buildJSDoc.ts
8
- /**
9
- * Builds a JSDoc comment block with custom indentation.
10
- * @param comments - Array of comment strings to include in the JSDoc block
11
- * @param options - Configuration options for formatting
12
- * @returns Formatted JSDoc string or fallback string if no comments
13
- */
14
- function buildJSDoc(comments, options = {}) {
15
- const { indent = " * ", suffix = "\n ", fallback = " " } = options;
16
- if (comments.length === 0) return fallback;
17
- return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
18
- }
19
- //#endregion
20
- //#region src/utils/Cache.ts
21
- var Cache = class {
22
- #buffer = /* @__PURE__ */ new Map();
23
- async get(key) {
24
- return this.#buffer.get(key) ?? null;
25
- }
26
- async set(key, value) {
27
- this.#buffer.set(key, value);
28
- }
29
- async delete(key) {
30
- this.#buffer.delete(key);
31
- }
32
- async clear() {
33
- this.#buffer.clear();
34
- }
35
- async keys() {
36
- return [...this.#buffer.keys()];
37
- }
38
- async values() {
39
- return [...this.#buffer.values()];
40
- }
41
- async flush() {}
42
- };
43
- //#endregion
44
- //#region src/utils/checkOnlineStatus.ts
45
- /**
46
- * Check if the system has internet connectivity
47
- * Uses DNS lookup to well-known stable domains as a lightweight connectivity test
48
- */
49
- async function isOnline() {
50
- for (const domain of [
51
- "dns.google.com",
52
- "cloudflare.com",
53
- "one.one.one.one"
54
- ]) try {
55
- await dns.promises.resolve(domain);
56
- return true;
57
- } catch {}
58
- return false;
59
- }
60
- /**
61
- * Execute a function only if online, otherwise silently skip
62
- */
63
- async function executeIfOnline(fn) {
64
- if (!await isOnline()) return null;
65
- try {
66
- return await fn();
67
- } catch {
68
- return null;
69
- }
70
- }
71
- //#endregion
72
- //#region src/utils/FunctionParams.ts
73
- /**
74
- * @deprecated
75
- */
76
- var FunctionParams = class FunctionParams {
77
- #items = [];
78
- constructor() {
79
- return this;
80
- }
81
- get items() {
82
- return this.#items.flat();
83
- }
84
- add(item) {
85
- if (!item) return this;
86
- if (Array.isArray(item)) {
87
- item.filter(Boolean).forEach((it) => {
88
- this.#items.push(it);
89
- });
90
- return this;
91
- }
92
- this.#items.push(item);
93
- return this;
94
- }
95
- static #orderItems(items) {
96
- return sortBy(items.filter(Boolean), [(item) => Array.isArray(item), "desc"], [(item) => !Array.isArray(item) && item.default !== void 0, "asc"], [(item) => Array.isArray(item) || (item.required ?? true), "desc"]);
97
- }
98
- static #addParams(acc, item) {
99
- const { enabled = true, name, type, required = true, ...rest } = item;
100
- if (!enabled) return acc;
101
- if (!name) {
102
- acc.push(`${type}${rest.default ? ` = ${rest.default}` : ""}`);
103
- return acc;
104
- }
105
- const parameterName = name.startsWith("{") ? name : camelCase(name);
106
- if (type) if (required) acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ""}`);
107
- else acc.push(`${parameterName}?: ${type}`);
108
- else acc.push(`${parameterName}`);
109
- return acc;
110
- }
111
- static toObject(items) {
112
- let type = [];
113
- let name = [];
114
- const enabled = items.every((item) => item.enabled) ? items.at(0)?.enabled : true;
115
- const required = items.every((item) => item.required) ?? true;
116
- items.forEach((item) => {
117
- name = FunctionParams.#addParams(name, {
118
- ...item,
119
- type: void 0
120
- });
121
- if (items.some((item) => item.type)) type = FunctionParams.#addParams(type, item);
122
- });
123
- return {
124
- name: `{ ${name.join(", ")} }`,
125
- type: type.length ? `{ ${type.join("; ")} }` : void 0,
126
- enabled,
127
- required
128
- };
129
- }
130
- toObject() {
131
- const items = FunctionParams.#orderItems(this.#items).flat();
132
- return FunctionParams.toObject(items);
133
- }
134
- static toString(items) {
135
- return FunctionParams.#orderItems(items).reduce((acc, item) => {
136
- if (Array.isArray(item)) {
137
- if (item.length <= 0) return acc;
138
- const subItems = FunctionParams.#orderItems(item);
139
- const objectItem = FunctionParams.toObject(subItems);
140
- return FunctionParams.#addParams(acc, objectItem);
141
- }
142
- return FunctionParams.#addParams(acc, item);
143
- }, []).join(", ");
144
- }
145
- toString() {
146
- const items = FunctionParams.#orderItems(this.#items);
147
- return FunctionParams.toString(items);
148
- }
149
- };
150
- //#endregion
151
- //#region src/utils/formatters.ts
152
- const formatters = {
153
- prettier: {
154
- command: "prettier",
155
- args: (outputPath) => [
156
- "--ignore-unknown",
157
- "--write",
158
- outputPath
159
- ],
160
- errorMessage: "Prettier not found"
161
- },
162
- biome: {
163
- command: "biome",
164
- args: (outputPath) => [
165
- "format",
166
- "--write",
167
- outputPath
168
- ],
169
- errorMessage: "Biome not found"
170
- },
171
- oxfmt: {
172
- command: "oxfmt",
173
- args: (outputPath) => [outputPath],
174
- errorMessage: "Oxfmt not found"
175
- }
176
- };
177
- /**
178
- * Check if a formatter command is available in the system.
179
- *
180
- * @param formatter - The formatter to check ('biome', 'prettier', or 'oxfmt')
181
- * @returns Promise that resolves to true if the formatter is available, false otherwise
182
- *
183
- * @remarks
184
- * This function checks availability by running `<formatter> --version` command.
185
- * All supported formatters (biome, prettier, oxfmt) implement the --version flag.
186
- */
187
- async function isFormatterAvailable(formatter) {
188
- try {
189
- await x(formatter, ["--version"], { nodeOptions: { stdio: "ignore" } });
190
- return true;
191
- } catch {
192
- return false;
193
- }
194
- }
195
- /**
196
- * Detect which formatter is available in the system.
197
- *
198
- * @returns Promise that resolves to the first available formatter or undefined if none are found
199
- *
200
- * @remarks
201
- * Checks in order of preference: biome, oxfmt, prettier.
202
- * Uses the `--version` flag to detect if each formatter command is available.
203
- * This is a reliable method as all supported formatters implement this flag.
204
- *
205
- * @example
206
- * ```typescript
207
- * const formatter = await detectFormatter()
208
- * if (formatter) {
209
- * console.log(`Using ${formatter} for formatting`)
210
- * } else {
211
- * console.log('No formatter found')
212
- * }
213
- * ```
214
- */
215
- async function detectFormatter() {
216
- for (const formatter of [
217
- "biome",
218
- "oxfmt",
219
- "prettier"
220
- ]) if (await isFormatterAvailable(formatter)) return formatter;
221
- }
222
- //#endregion
223
- //#region src/utils/getPlugins.ts
224
- function isJSONPlugins(plugins) {
225
- return !!plugins?.some((plugin) => {
226
- return Array.isArray(plugin) && typeof plugin?.at(0) === "string";
227
- });
228
- }
229
- function isObjectPlugins(plugins) {
230
- return plugins instanceof Object && !Array.isArray(plugins);
231
- }
232
- function getPlugins(plugins) {
233
- if (isObjectPlugins(plugins)) throw new Error("Object plugins are not supported anymore, best to use http://kubb.dev/getting-started/configure#json");
234
- if (isJSONPlugins(plugins)) throw new Error("JSON plugins are not supported anymore, best to use http://kubb.dev/getting-started/configure#json");
235
- return Promise.resolve(plugins);
236
- }
237
- //#endregion
238
- //#region src/utils/promise.ts
239
- function isPromise(result) {
240
- return !!result && typeof result?.then === "function";
241
- }
242
- function isPromiseFulfilledResult(result) {
243
- return result.status === "fulfilled";
244
- }
245
- function isPromiseRejectedResult(result) {
246
- return result.status === "rejected";
247
- }
248
- //#endregion
249
- //#region src/utils/getConfigs.ts
250
- /**
251
- * Converting UserConfig to Config Array without a change in the object beside the JSON convert.
252
- */
253
- async function getConfigs(config, args) {
254
- let kubbUserConfig = Promise.resolve(config);
255
- if (typeof config === "function") {
256
- const possiblePromise = config(args);
257
- if (isPromise(possiblePromise)) kubbUserConfig = possiblePromise;
258
- kubbUserConfig = Promise.resolve(possiblePromise);
259
- }
260
- let JSONConfig = await kubbUserConfig;
261
- if (!Array.isArray(JSONConfig)) JSONConfig = [JSONConfig];
262
- const results = [];
263
- for (const item of JSONConfig) {
264
- const plugins = item.plugins ? await getPlugins(item.plugins) : void 0;
265
- results.push({
266
- ...item,
267
- plugins
268
- });
269
- }
270
- return results;
271
- }
272
- //#endregion
273
- //#region src/utils/getNestedAccessor.ts
274
- /**
275
- * Converts a param path (string with dot notation or array of strings) to a JavaScript accessor expression.
276
- * @param param - The param path, e.g., 'pagination.next.id' or ['pagination', 'next', 'id']
277
- * @param accessor - The base accessor, e.g., 'lastPage' or 'firstPage'
278
- * @returns A JavaScript accessor expression, e.g., "lastPage?.['pagination']?.['next']?.['id']", or undefined if param is empty
279
- *
280
- * @example
281
- * ```ts
282
- * getNestedAccessor('pagination.next.id', 'lastPage')
283
- * // returns: "lastPage?.['pagination']?.['next']?.['id']"
284
- *
285
- * getNestedAccessor(['pagination', 'next', 'id'], 'lastPage')
286
- * // returns: "lastPage?.['pagination']?.['next']?.['id']"
287
- *
288
- * getNestedAccessor('', 'lastPage')
289
- * // returns: undefined
290
- * ```
291
- */
292
- function getNestedAccessor(param, accessor) {
293
- const parts = Array.isArray(param) ? param : param.split(".");
294
- if (parts.length === 0 || parts.length === 1 && parts[0] === "") return;
295
- return parts.reduce((acc, part) => `${acc}?.['${part}']`, accessor);
296
- }
297
- //#endregion
298
- //#region src/utils/linters.ts
299
- const linters = {
300
- eslint: {
301
- command: "eslint",
302
- args: (outputPath) => [outputPath, "--fix"],
303
- errorMessage: "Eslint not found"
304
- },
305
- biome: {
306
- command: "biome",
307
- args: (outputPath) => [
308
- "lint",
309
- "--fix",
310
- outputPath
311
- ],
312
- errorMessage: "Biome not found"
313
- },
314
- oxlint: {
315
- command: "oxlint",
316
- args: (outputPath) => ["--fix", outputPath],
317
- errorMessage: "Oxlint not found"
318
- }
319
- };
320
- async function isLinterAvailable(linter) {
321
- try {
322
- await x(linter, ["--version"], { nodeOptions: { stdio: "ignore" } });
323
- return true;
324
- } catch {
325
- return false;
326
- }
327
- }
328
- async function detectLinter() {
329
- for (const linter of [
330
- "biome",
331
- "oxlint",
332
- "eslint"
333
- ]) if (await isLinterAvailable(linter)) return linter;
334
- }
335
- //#endregion
336
- //#region src/utils/renderTemplate.ts
337
- function renderTemplate(template, data = void 0) {
338
- if (!data || !Object.keys(data).length) return template.replace(/{{(.*?)}}/g, "");
339
- return template.match(/{{(.*?)}}/g)?.reduce((prev, curr) => {
340
- const index = curr.split(/{{|}}/).filter(Boolean)[0]?.trim();
341
- if (index === void 0) return prev;
342
- const value = data[index];
343
- if (value === void 0) return prev;
344
- return prev.replace(curr, () => {
345
- if (typeof value === "boolean") return `${value.toString()}` || "false";
346
- return value || "";
347
- }).trim();
348
- }, template) || "";
349
- }
350
- //#endregion
351
- //#region src/utils/serializePluginOptions.ts
352
- /**
353
- * Serialize plugin options for safe JSON transport.
354
- * Strips functions, symbols, and undefined values recursively.
355
- */
356
- function serializePluginOptions(options) {
357
- if (options === null || options === void 0) return {};
358
- if (typeof options !== "object") return options;
359
- if (Array.isArray(options)) return options.map(serializePluginOptions);
360
- const serialized = {};
361
- for (const [key, value] of Object.entries(options)) {
362
- if (typeof value === "function" || typeof value === "symbol" || value === void 0) continue;
363
- if (typeof value === "object" && value !== null) serialized[key] = serializePluginOptions(value);
364
- else serialized[key] = value;
365
- }
366
- return serialized;
367
- }
368
- //#endregion
369
- //#region src/utils/timeout.ts
370
- async function timeout(ms) {
371
- return new Promise((resolve) => {
372
- const timeout = setTimeout(() => {
373
- resolve(timeout);
374
- }, ms);
375
- }).then((timeout) => {
376
- clearTimeout(timeout);
377
- return true;
378
- });
379
- }
380
- //#endregion
381
- //#region src/utils/tokenize.ts
382
- /** Shell-like tokenizer: splits a command string respecting single/double quotes. */
383
- function tokenize(command) {
384
- const args = [];
385
- let current = "";
386
- let quote = "";
387
- for (const ch of command) if (quote) if (ch === quote) quote = "";
388
- else current += ch;
389
- else if (ch === "\"" || ch === "'") quote = ch;
390
- else if (ch === " " || ch === " ") {
391
- if (current) {
392
- args.push(current);
393
- current = "";
394
- }
395
- } else current += ch;
396
- if (current) args.push(current);
397
- return args;
398
- }
399
- //#endregion
400
- export { AsyncEventEmitter, Cache, FunctionParams, URLPath, buildJSDoc, detectFormatter, detectLinter, detectPackageManager, executeIfOnline, formatHrtime, formatMs, formatters, getBarrelFiles, getConfigs, getElapsedMs, getNestedAccessor, getUniqueName, isOnline, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, linters, renderTemplate, serializePluginOptions, setUniqueName, timeout, tokenize };
401
-
402
- //# sourceMappingURL=utils.js.map