@kubb/core 1.15.0-canary.20231112T135011 → 2.0.0-alpha.10

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 (55) hide show
  1. package/README.md +1 -1
  2. package/dist/index.cjs +1253 -1088
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +396 -411
  5. package/dist/index.d.ts +396 -411
  6. package/dist/index.js +1194 -1018
  7. package/dist/index.js.map +1 -1
  8. package/dist/utils.cjs +1272 -0
  9. package/dist/utils.cjs.map +1 -0
  10. package/dist/utils.d.cts +239 -0
  11. package/dist/utils.d.ts +239 -0
  12. package/dist/utils.js +1219 -0
  13. package/dist/utils.js.map +1 -0
  14. package/globals.d.ts +33 -16
  15. package/package.json +21 -14
  16. package/src/BarrelManager.ts +123 -0
  17. package/src/FileManager.ts +524 -0
  18. package/src/Generator.ts +34 -0
  19. package/src/PackageManager.ts +178 -0
  20. package/src/PluginManager.ts +629 -0
  21. package/src/PromiseManager.ts +51 -0
  22. package/src/SchemaGenerator.ts +8 -0
  23. package/src/build.ts +207 -0
  24. package/src/config.ts +22 -0
  25. package/src/errors.ts +12 -0
  26. package/src/index.ts +28 -0
  27. package/src/plugin.ts +80 -0
  28. package/src/types.ts +353 -0
  29. package/src/utils/EventEmitter.ts +24 -0
  30. package/src/utils/FunctionParams.ts +85 -0
  31. package/src/utils/Queue.ts +110 -0
  32. package/src/utils/TreeNode.ts +122 -0
  33. package/src/utils/URLPath.ts +133 -0
  34. package/src/utils/cache.ts +35 -0
  35. package/src/utils/clean.ts +5 -0
  36. package/src/utils/executeStrategies.ts +83 -0
  37. package/src/utils/index.ts +19 -0
  38. package/src/utils/logger.ts +76 -0
  39. package/src/utils/promise.ts +13 -0
  40. package/src/utils/randomColour.ts +39 -0
  41. package/src/utils/read.ts +68 -0
  42. package/src/utils/renderTemplate.ts +31 -0
  43. package/src/utils/throttle.ts +30 -0
  44. package/src/utils/timeout.ts +7 -0
  45. package/src/utils/transformers/combineCodes.ts +3 -0
  46. package/src/utils/transformers/createJSDocBlockText.ts +15 -0
  47. package/src/utils/transformers/escape.ts +31 -0
  48. package/src/utils/transformers/indent.ts +3 -0
  49. package/src/utils/transformers/index.ts +22 -0
  50. package/src/utils/transformers/nameSorter.ts +9 -0
  51. package/src/utils/transformers/searchAndReplace.ts +25 -0
  52. package/src/utils/transformers/transformReservedWord.ts +97 -0
  53. package/src/utils/transformers/trim.ts +3 -0
  54. package/src/utils/uniqueName.ts +20 -0
  55. package/src/utils/write.ts +63 -0
package/dist/index.js CHANGED
@@ -1,18 +1,18 @@
1
1
  import mod, { createRequire } from 'module';
2
2
  import pc3 from 'picocolors';
3
- export { default as pc } from 'picocolors';
4
- import crypto from 'crypto';
5
3
  import fs2, { remove } from 'fs-extra';
6
- import { camelCase, camelCaseTransformMerge } from 'change-case';
7
- import { orderBy } from 'natural-orderby';
8
- import { performance } from 'perf_hooks';
9
4
  import seedrandom from 'seedrandom';
10
- import pathParser from 'path';
11
5
  import { switcher } from 'js-runtime';
12
- import dirTree from 'directory-tree';
13
- import { createImportDeclaration, print, createExportDeclaration } from '@kubb/parser';
6
+ import { camelCase, camelCaseTransformMerge } from 'change-case';
7
+ import crypto2 from 'crypto';
8
+ import path, { resolve, dirname, extname } from 'path';
9
+ import { print } from '@kubb/parser';
10
+ import * as factory from '@kubb/parser/factory';
14
11
  import isEqual from 'lodash.isequal';
12
+ import { orderBy } from 'natural-orderby';
13
+ import dirTree from 'directory-tree';
15
14
  import { EventEmitter as EventEmitter$1 } from 'events';
15
+ import { performance } from 'perf_hooks';
16
16
  import os from 'os';
17
17
  import { pathToFileURL } from 'url';
18
18
  import { findUp, findUpSync } from 'find-up';
@@ -27,110 +27,45 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
27
27
  return require.apply(this, arguments);
28
28
  throw Error('Dynamic require of "' + x + '" is not supported');
29
29
  });
30
-
31
- // src/utils/cache.ts
32
- function createPluginCache(Store = /* @__PURE__ */ Object.create(null)) {
33
- return {
34
- set(id, value) {
35
- Store[id] = [0, value];
36
- },
37
- get(id) {
38
- const item = Store[id];
39
- if (!item) {
40
- return null;
41
- }
42
- item[0] = 0;
43
- return item[1];
44
- },
45
- has(id) {
46
- const item = Store[id];
47
- if (!item) {
48
- return false;
49
- }
50
- item[0] = 0;
51
- return true;
52
- },
53
- delete(id) {
54
- return delete Store[id];
55
- }
56
- };
57
- }
58
- async function clean(path) {
59
- return remove(path);
60
- }
61
- var FunctionParams = class {
62
- type;
63
- items = [];
64
- constructor(type) {
65
- this.type = type;
66
- return this;
67
- }
68
- add(item) {
69
- if (!item) {
70
- return this;
71
- }
72
- if (Array.isArray(item)) {
73
- item.filter(Boolean).forEach((it) => this.items.push(it));
74
- return this;
75
- }
76
- this.items.push(item);
77
- return this;
78
- }
79
- toString() {
80
- const sortedData = orderBy(this.items.filter(Boolean), [(v) => !v.default, (v) => v.required ?? true], ["desc", "desc"]);
81
- return sortedData.filter(({ enabled = true }) => enabled).reduce((acc, { name, type, required = true, ...rest }) => {
82
- if (!name) {
83
- acc.push(`${type}${rest.default ? ` = ${rest.default}` : ""}`);
84
- return acc;
85
- }
86
- const parameterName = name.startsWith("{") ? name : camelCase(name, { delimiter: "", transform: camelCaseTransformMerge });
87
- if (type) {
88
- if (required) {
89
- acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ""}`);
90
- } else {
91
- acc.push(`${parameterName}?: ${type}`);
92
- }
93
- } else {
94
- acc.push(`${parameterName}`);
95
- }
96
- return acc;
97
- }, []).join(", ");
98
- }
30
+ var __accessCheck = (obj, member, msg) => {
31
+ if (!member.has(obj))
32
+ throw TypeError("Cannot " + msg);
99
33
  };
100
-
101
- // src/utils/getUniqueName.ts
102
- function getUniqueName(originalName, data) {
103
- let used = data[originalName] || 0;
104
- if (used) {
105
- data[originalName] = ++used;
106
- originalName += used;
107
- }
108
- data[originalName] = 1;
109
- return originalName;
110
- }
111
-
112
- // src/utils/isPromise.ts
113
- function isPromise(result) {
114
- return typeof result?.then === "function";
115
- }
116
- function isPromiseFulfilledResult(result) {
117
- return result.status === "fulfilled";
118
- }
119
- function isPromiseRejectedResult(result) {
120
- return result.status === "rejected";
121
- }
122
-
123
- // src/utils/jsdoc.ts
124
- function createJSDocBlockText({ comments }) {
125
- const filteredComments = comments.filter(Boolean);
126
- if (!filteredComments.length) {
127
- return "";
34
+ var __privateGet = (obj, member, getter) => {
35
+ __accessCheck(obj, member, "read from private field");
36
+ return getter ? getter.call(obj) : member.get(obj);
37
+ };
38
+ var __privateAdd = (obj, member, value) => {
39
+ if (member.has(obj))
40
+ throw TypeError("Cannot add the same private member more than once");
41
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
42
+ };
43
+ var __privateSet = (obj, member, value, setter) => {
44
+ __accessCheck(obj, member, "write to private field");
45
+ setter ? setter.call(obj, value) : member.set(obj, value);
46
+ return value;
47
+ };
48
+ var __privateWrapper = (obj, member, setter, getter) => ({
49
+ set _(value) {
50
+ __privateSet(obj, member, value, setter);
51
+ },
52
+ get _() {
53
+ return __privateGet(obj, member, getter);
128
54
  }
129
- return `/**
130
- * ${filteredComments.join("\n * ")}
131
- */`;
55
+ });
56
+ var __privateMethod = (obj, member, method) => {
57
+ __accessCheck(obj, member, "access private method");
58
+ return method;
59
+ };
60
+ async function clean(path3) {
61
+ return remove(path3);
132
62
  }
133
- function createLogger(spinner) {
63
+ var LogLevel = {
64
+ silent: "silent",
65
+ info: "info",
66
+ debug: "debug"
67
+ };
68
+ function createLogger({ logLevel, name, spinner }) {
134
69
  const logs = [];
135
70
  const log = (message) => {
136
71
  if (message && spinner) {
@@ -150,12 +85,14 @@ function createLogger(spinner) {
150
85
  }
151
86
  };
152
87
  const info = (message) => {
153
- if (message && spinner) {
88
+ if (message && spinner && logLevel !== LogLevel.silent) {
154
89
  spinner.info(message);
155
90
  logs.push(message);
156
91
  }
157
92
  };
158
93
  const logger = {
94
+ name,
95
+ logLevel,
159
96
  log,
160
97
  error,
161
98
  warn,
@@ -165,75 +102,6 @@ function createLogger(spinner) {
165
102
  };
166
103
  return logger;
167
104
  }
168
-
169
- // src/utils/nameSorter.ts
170
- function nameSorter(a, b) {
171
- if (a.name < b.name) {
172
- return -1;
173
- }
174
- if (a.name > b.name) {
175
- return 1;
176
- }
177
- return 0;
178
- }
179
- var Queue = class {
180
- #queue = [];
181
- #workerCount = 0;
182
- #maxParallel;
183
- #debug = false;
184
- constructor(maxParallel, debug = false) {
185
- this.#maxParallel = maxParallel;
186
- this.#debug = debug;
187
- }
188
- run(job, options = { controller: new AbortController(), name: crypto.randomUUID(), description: "" }) {
189
- return new Promise((resolve, reject) => {
190
- const item = { reject, resolve, job, name: options.name, description: options.description || options.name };
191
- options.controller?.signal.addEventListener("abort", () => {
192
- this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
193
- reject("Aborted");
194
- });
195
- this.#queue.push(item);
196
- this.#work();
197
- });
198
- }
199
- runSync(job, options = { controller: new AbortController(), name: crypto.randomUUID(), description: "" }) {
200
- new Promise((resolve, reject) => {
201
- const item = { reject, resolve, job, name: options.name, description: options.description || options.name };
202
- options.controller?.signal.addEventListener("abort", () => {
203
- this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
204
- });
205
- this.#queue.push(item);
206
- this.#work();
207
- });
208
- }
209
- get hasJobs() {
210
- return this.#workerCount > 0 || this.#queue.length > 0;
211
- }
212
- get count() {
213
- return this.#workerCount;
214
- }
215
- #work() {
216
- if (this.#workerCount >= this.#maxParallel) {
217
- return;
218
- }
219
- this.#workerCount++;
220
- let entry;
221
- while (entry = this.#queue.shift()) {
222
- const { reject, resolve, job, name, description } = entry;
223
- if (this.#debug) {
224
- performance.mark(name + "_start");
225
- }
226
- job().then((result) => {
227
- resolve(result);
228
- if (this.#debug) {
229
- performance.mark(name + "_stop");
230
- performance.measure(description, name + "_start", name + "_stop");
231
- }
232
- }).catch((err) => reject(err));
233
- }
234
- this.#workerCount--;
235
- }
236
- };
237
105
  var defaultColours = ["black", "blue", "darkBlue", "cyan", "gray", "green", "darkGreen", "magenta", "red", "darkRed", "yellow", "darkYellow"];
238
106
  function randomColour(text, colours = defaultColours) {
239
107
  if (!text) {
@@ -260,46 +128,22 @@ function randomPicoColour(text, colors = defaultColours) {
260
128
  }
261
129
  return formatter(text);
262
130
  }
263
- function slash(path, platform = "linux") {
264
- const isWindowsPath = /^\\\\\?\\/.test(path);
265
- if (["linux", "mac"].includes(platform) && !isWindowsPath) {
266
- return path.replaceAll(/\\/g, "/").replace("../", "").trimEnd();
267
- }
268
- return path.replaceAll(/\\/g, "/").replace("../", "").trimEnd();
269
- }
270
- function getRelativePath(rootDir, filePath, platform = "linux") {
271
- if (!rootDir || !filePath) {
272
- throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ""} ${filePath || ""}`);
273
- }
274
- const relativePath = pathParser.relative(rootDir, filePath);
275
- const path = slash(relativePath, platform);
276
- if (path.startsWith("../")) {
277
- return path.replace(pathParser.basename(path), pathParser.basename(path, pathParser.extname(filePath)));
278
- }
279
- return `./${path.replace(pathParser.basename(path), pathParser.basename(path, pathParser.extname(filePath)))}`;
280
- }
281
- function getPathMode(path) {
282
- if (!path) {
283
- return "directory";
284
- }
285
- return pathParser.extname(path) ? "file" : "directory";
286
- }
287
131
  var reader = switcher(
288
132
  {
289
- node: async (path) => {
290
- return fs2.readFile(path, { encoding: "utf8" });
133
+ node: async (path3) => {
134
+ return fs2.readFile(path3, { encoding: "utf8" });
291
135
  },
292
- bun: async (path) => {
293
- const file = Bun.file(path);
136
+ bun: async (path3) => {
137
+ const file = Bun.file(path3);
294
138
  return file.text();
295
139
  }
296
140
  },
297
141
  "node"
298
142
  );
299
- var syncReader = switcher(
143
+ switcher(
300
144
  {
301
- node: (path) => {
302
- return fs2.readFileSync(path, { encoding: "utf8" });
145
+ node: (path3) => {
146
+ return fs2.readFileSync(path3, { encoding: "utf8" });
303
147
  },
304
148
  bun: () => {
305
149
  throw new Error("Bun cannot read sync");
@@ -307,79 +151,118 @@ var syncReader = switcher(
307
151
  },
308
152
  "node"
309
153
  );
310
- async function read(path) {
311
- return reader(path);
154
+ async function read(path3) {
155
+ return reader(path3);
312
156
  }
313
- function readSync(path) {
314
- return syncReader(path);
315
- }
316
-
317
- // src/utils/renderTemplate.ts
318
- function renderTemplate(template, data = void 0) {
319
- if (!data || !Object.keys(data).length) {
320
- return template.replace(/{{(.*?)}}/g, "");
321
- }
322
- const matches = template.match(/{{(.*?)}}/g);
323
- return matches?.reduce((prev, curr) => {
324
- const index = curr.split(/{{|}}/).filter(Boolean)[0]?.trim();
325
- if (index === void 0) {
326
- return prev;
327
- }
328
- const value = data[index];
329
- if (value === void 0) {
330
- return prev;
331
- }
332
- return prev.replace(curr, () => {
333
- if (typeof value === "boolean") {
334
- return `${value.toString()}` || "false";
157
+ var URLPath = class {
158
+ constructor(path3) {
159
+ this.path = path3;
160
+ return this;
161
+ }
162
+ /**
163
+ * Convert Swagger path to URLPath(syntax of Express)
164
+ * @example /pet/{petId} => /pet/:petId
165
+ */
166
+ get URL() {
167
+ return this.toURLPath();
168
+ }
169
+ get isURL() {
170
+ try {
171
+ const url = new URL(this.path);
172
+ if (url?.href) {
173
+ return true;
335
174
  }
336
- return value || "";
337
- }).trim();
338
- }, template) || "";
339
- }
340
-
341
- // src/utils/SummaryError.ts
342
- var SummaryError = class extends Error {
343
- summary;
344
- constructor(message, options) {
345
- super(message, { cause: options.cause });
346
- this.name = "SummaryError";
347
- this.summary = options.summary || [];
175
+ } catch (error) {
176
+ return false;
177
+ }
178
+ return false;
348
179
  }
349
- };
350
-
351
- // src/utils/throttle.ts
352
- var throttle = (fn, delay) => {
353
- let wait = false;
354
- let timeout2;
355
- let cancelled = false;
356
- return [
357
- (...args) => {
358
- if (cancelled) {
359
- return void 0;
180
+ /**
181
+ * Convert Swagger path to template literals/ template strings(camelcase)
182
+ * @example /pet/{petId} => `/pet/${petId}`
183
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
184
+ * @example /account/userID => `/account/${userId}`
185
+ */
186
+ get template() {
187
+ return this.toTemplateString();
188
+ }
189
+ get object() {
190
+ return this.toObject();
191
+ }
192
+ get params() {
193
+ return this.getParams();
194
+ }
195
+ toObject({ type = "path", replacer, stringify } = {}) {
196
+ const object = {
197
+ url: type === "path" ? this.toURLPath() : this.toTemplateString(replacer),
198
+ params: this.getParams()
199
+ };
200
+ if (stringify) {
201
+ if (type === "template") {
202
+ return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
360
203
  }
361
- if (wait) {
362
- return void 0;
204
+ if (object.params) {
205
+ return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
363
206
  }
364
- const val = fn(...args);
365
- wait = true;
366
- timeout2 = setTimeout(() => {
367
- wait = false;
368
- }, delay);
369
- return val;
370
- },
371
- () => {
372
- cancelled = true;
373
- clearTimeout(timeout2);
207
+ return `{ url: '${object.url}' }`;
374
208
  }
375
- ];
209
+ return object;
210
+ }
211
+ /**
212
+ * Convert Swagger path to template literals/ template strings(camelcase)
213
+ * @example /pet/{petId} => `/pet/${petId}`
214
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
215
+ * @example /account/userID => `/account/${userId}`
216
+ */
217
+ toTemplateString(replacer) {
218
+ const regex = /{(\w|-)*}/g;
219
+ const found = this.path.match(regex);
220
+ let newPath = this.path.replaceAll("{", "${");
221
+ if (found) {
222
+ newPath = found.reduce((prev, curr) => {
223
+ const pathParam = replacer ? replacer(camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge })) : camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge });
224
+ const replacement = `\${${pathParam}}`;
225
+ return prev.replace(curr, replacement);
226
+ }, this.path);
227
+ }
228
+ return `\`${newPath}\``;
229
+ }
230
+ getParams(replacer) {
231
+ const regex = /{(\w|-)*}/g;
232
+ const found = this.path.match(regex);
233
+ if (!found) {
234
+ return void 0;
235
+ }
236
+ const params = {};
237
+ found.forEach((item) => {
238
+ item = item.replaceAll("{", "").replaceAll("}", "");
239
+ const pathParam = replacer ? replacer(camelCase(item, { delimiter: "", transform: camelCaseTransformMerge })) : camelCase(item, { delimiter: "", transform: camelCaseTransformMerge });
240
+ params[pathParam] = pathParam;
241
+ }, this.path);
242
+ return params;
243
+ }
244
+ /**
245
+ * Convert Swagger path to URLPath(syntax of Express)
246
+ * @example /pet/{petId} => /pet/:petId
247
+ */
248
+ toURLPath() {
249
+ return this.path.replaceAll("{", ":").replaceAll("}", "");
250
+ }
376
251
  };
377
252
 
253
+ // src/config.ts
254
+ function defineConfig(options) {
255
+ return options;
256
+ }
257
+ function isInputPath(result) {
258
+ return !!result && "path" in result;
259
+ }
260
+
378
261
  // src/utils/timeout.ts
379
262
  async function timeout(ms) {
380
- return new Promise((resolve) => {
263
+ return new Promise((resolve2) => {
381
264
  setTimeout(() => {
382
- resolve(true);
265
+ resolve2(true);
383
266
  }, ms);
384
267
  });
385
268
  }
@@ -389,6 +272,22 @@ function combineCodes(codes) {
389
272
  return codes.join("\n");
390
273
  }
391
274
 
275
+ // src/utils/transformers/createJSDocBlockText.ts
276
+ function createJSDocBlockText({ comments, newLine }) {
277
+ const filteredComments = comments.filter(Boolean);
278
+ if (!filteredComments.length) {
279
+ return "";
280
+ }
281
+ const source = `/**
282
+ * ${filteredComments.join("\n * ")}
283
+ */`;
284
+ if (newLine) {
285
+ return `${source}
286
+ `;
287
+ }
288
+ return source;
289
+ }
290
+
392
291
  // src/utils/transformers/escape.ts
393
292
  function escape(text) {
394
293
  return text ? text.replaceAll("`", "\\`") : "";
@@ -414,24 +313,57 @@ function jsStringEscape(input) {
414
313
  });
415
314
  }
416
315
 
417
- // src/utils/transformers/transformReservedWord.ts
418
- var reservedWords = [
419
- "abstract",
420
- "arguments",
421
- "boolean",
422
- "break",
423
- "byte",
424
- "case",
425
- "catch",
426
- "char",
427
- "class",
428
- "const",
429
- "continue",
430
- "debugger",
431
- "default",
432
- "delete",
433
- "do",
434
- "double",
316
+ // src/utils/transformers/indent.ts
317
+ function createIndent(size) {
318
+ return Array.from({ length: size + 1 }).join(" ");
319
+ }
320
+
321
+ // src/utils/transformers/nameSorter.ts
322
+ function nameSorter(a, b) {
323
+ if (a.name < b.name) {
324
+ return -1;
325
+ }
326
+ if (a.name > b.name) {
327
+ return 1;
328
+ }
329
+ return 0;
330
+ }
331
+
332
+ // src/utils/transformers/searchAndReplace.ts
333
+ function searchAndReplace(options) {
334
+ const { text, replaceBy, prefix = "", key } = options;
335
+ const searchValues = options.searchValues?.(prefix, key) || [
336
+ `${prefix}["${key}"]`,
337
+ `${prefix}['${key}']`,
338
+ `${prefix}[\`${key}\`]`,
339
+ `${prefix}"${key}"`,
340
+ `${prefix}'${key}'`,
341
+ `${prefix}\`${key}\``,
342
+ new RegExp(`${prefix}${key}`, "g")
343
+ ];
344
+ return searchValues.reduce((prev, searchValue) => {
345
+ return prev.toString().replaceAll(searchValue, replaceBy);
346
+ }, text);
347
+ }
348
+
349
+ // src/utils/transformers/transformReservedWord.ts
350
+ var reservedWords = [
351
+ "abstract",
352
+ "arguments",
353
+ "boolean",
354
+ "break",
355
+ "byte",
356
+ "case",
357
+ "catch",
358
+ "char",
359
+ "class",
360
+ "const",
361
+ "continue",
362
+ "debugger",
363
+ "default",
364
+ "delete",
365
+ "do",
366
+ "double",
435
367
  "else",
436
368
  "enum",
437
369
  "eval",
@@ -506,11 +438,89 @@ function transformReservedWord(word) {
506
438
  }
507
439
  return word;
508
440
  }
441
+
442
+ // src/utils/transformers/trim.ts
443
+ function trim(text) {
444
+ return text.replaceAll(/\n/g, "").trim();
445
+ }
446
+
447
+ // src/utils/transformers/index.ts
448
+ var transformers = {
449
+ combineCodes,
450
+ escape,
451
+ jsStringEscape,
452
+ createIndent,
453
+ transformReservedWord,
454
+ nameSorter,
455
+ searchAndReplace,
456
+ trim,
457
+ JSDoc: {
458
+ createJSDocBlockText
459
+ }
460
+ };
461
+ async function saveCreateDirectory(path3) {
462
+ const passedPath = dirname(resolve(path3));
463
+ await fs2.mkdir(passedPath, { recursive: true });
464
+ }
465
+ var writer = switcher(
466
+ {
467
+ node: async (path3, data) => {
468
+ try {
469
+ await fs2.stat(resolve(path3));
470
+ const oldContent = await fs2.readFile(resolve(path3), { encoding: "utf-8" });
471
+ if (oldContent?.toString() === data?.toString()) {
472
+ return;
473
+ }
474
+ } catch (_err) {
475
+ }
476
+ await saveCreateDirectory(path3);
477
+ await fs2.writeFile(resolve(path3), data, { encoding: "utf-8" });
478
+ const savedData = await fs2.readFile(resolve(path3), { encoding: "utf-8" });
479
+ if (savedData?.toString() !== data?.toString()) {
480
+ throw new Error(`Sanity check failed for ${path3}
481
+
482
+ Data[${data.length}]:
483
+ ${data}
484
+
485
+ Saved[${savedData.length}]:
486
+ ${savedData}
487
+ `);
488
+ }
489
+ return savedData;
490
+ },
491
+ bun: async (path3, data) => {
492
+ try {
493
+ await saveCreateDirectory(path3);
494
+ await Bun.write(resolve(path3), data);
495
+ const file = Bun.file(resolve(path3));
496
+ const savedData = await file.text();
497
+ if (savedData?.toString() !== data?.toString()) {
498
+ throw new Error(`Sanity check failed for ${path3}
499
+
500
+ Data[${data.length}]:
501
+ ${data}
502
+
503
+ Saved[${savedData.length}]:
504
+ ${savedData}
505
+ `);
506
+ }
507
+ return savedData;
508
+ } catch (e) {
509
+ console.log(e, resolve(path3));
510
+ }
511
+ }
512
+ },
513
+ "node"
514
+ );
515
+ async function write(data, path3) {
516
+ if (data.trim() === "") {
517
+ return void 0;
518
+ }
519
+ return writer(path3, data.trim());
520
+ }
509
521
  var TreeNode = class _TreeNode {
510
- data;
511
- parent;
512
- children = [];
513
522
  constructor(data, parent) {
523
+ this.children = [];
514
524
  this.data = data;
515
525
  this.parent = parent;
516
526
  return this;
@@ -570,16 +580,16 @@ var TreeNode = class _TreeNode {
570
580
  }
571
581
  return this;
572
582
  }
573
- static build(path, options = {}) {
583
+ static build(path3, options = {}) {
574
584
  try {
575
585
  const exclude = Array.isArray(options.exclude) ? options.exclude : [options.exclude].filter(Boolean);
576
- const filteredTree = dirTree(path, { extensions: options.extensions, exclude: [/node_modules/, ...exclude] });
586
+ const filteredTree = dirTree(path3, { extensions: options.extensions, exclude: [/node_modules/, ...exclude] });
577
587
  if (!filteredTree) {
578
588
  return null;
579
589
  }
580
- const treeNode = new _TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type || getPathMode(filteredTree.path) });
590
+ const treeNode = new _TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type || FileManager.getMode(filteredTree.path) });
581
591
  const recurse = (node, item) => {
582
- const subNode = node.addChild({ name: item.name, path: item.path, type: item.type || getPathMode(item.path) });
592
+ const subNode = node.addChild({ name: item.name, path: item.path, type: item.type || FileManager.getMode(item.path) });
583
593
  if (item.children?.length) {
584
594
  item.children?.forEach((child) => {
585
595
  recurse(subNode, child);
@@ -594,227 +604,290 @@ var TreeNode = class _TreeNode {
594
604
  }
595
605
  };
596
606
 
597
- // src/utils/uniqueIdFactory.ts
598
- var uniqueIdFactory = (counter) => (str = "") => `${str}${++counter}`;
599
- var URLPath = class {
600
- path;
601
- constructor(path) {
602
- this.path = path;
607
+ // src/BarrelManager.ts
608
+ var _options;
609
+ var BarrelManager = class {
610
+ constructor(options = {}) {
611
+ __privateAdd(this, _options, {});
612
+ __privateSet(this, _options, options);
603
613
  return this;
604
614
  }
605
- /**
606
- * Convert Swagger path to URLPath(syntax of Express)
607
- * @example /pet/{petId} => /pet/:petId
608
- */
609
- get URL() {
610
- return this.toURLPath();
611
- }
612
- get isURL() {
613
- try {
614
- const url = new URL(this.path);
615
- if (url?.href) {
616
- return true;
615
+ getIndexes(root, extName) {
616
+ const { treeNode = {}, isTypeOnly, filter, map, output, includeExt } = __privateGet(this, _options);
617
+ const extMapper = {
618
+ ".ts": {
619
+ extensions: /\.ts/,
620
+ exclude: [/schemas/, /json/]
621
+ },
622
+ ".json": {
623
+ extensions: /\.json/,
624
+ exclude: []
617
625
  }
618
- } catch (error) {
619
- return false;
626
+ };
627
+ const tree = TreeNode.build(root, { ...extMapper[extName] || {}, ...treeNode });
628
+ if (!tree) {
629
+ return null;
620
630
  }
621
- return false;
631
+ const fileReducer = (files2, currentTree) => {
632
+ if (!currentTree.children) {
633
+ return [];
634
+ }
635
+ if (currentTree.children?.length > 1) {
636
+ const indexPath = path.resolve(currentTree.data.path, "index.ts");
637
+ const exports = currentTree.children.filter(Boolean).map((file) => {
638
+ const importPath = file.data.type === "directory" ? `./${file.data.name}/index` : `./${file.data.name.replace(/\.[^.]*$/, "")}`;
639
+ if (importPath.includes("index") && file.data.type === "file") {
640
+ return void 0;
641
+ }
642
+ return {
643
+ path: includeExt ? `${importPath}${extName}` : importPath,
644
+ isTypeOnly
645
+ };
646
+ }).filter(Boolean);
647
+ files2.push({
648
+ path: indexPath,
649
+ baseName: "index.ts",
650
+ source: "",
651
+ exports: output ? exports?.filter((item) => {
652
+ return item.path.endsWith(output.replace(/\.[^.]*$/, ""));
653
+ }) : exports
654
+ });
655
+ } else {
656
+ currentTree.children?.forEach((child) => {
657
+ const indexPath = path.resolve(currentTree.data.path, "index.ts");
658
+ const importPath = child.data.type === "directory" ? `./${child.data.name}/index` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
659
+ const exports = [
660
+ {
661
+ path: includeExt ? `${importPath}${extName}` : importPath,
662
+ isTypeOnly
663
+ }
664
+ ];
665
+ files2.push({
666
+ path: indexPath,
667
+ baseName: "index.ts",
668
+ source: "",
669
+ exports: output ? exports?.filter((item) => {
670
+ return item.path.endsWith(output.replace(/\.[^.]*$/, ""));
671
+ }) : exports
672
+ });
673
+ });
674
+ }
675
+ currentTree.children.forEach((childItem) => {
676
+ fileReducer(files2, childItem);
677
+ });
678
+ return files2;
679
+ };
680
+ const files = fileReducer([], tree).reverse();
681
+ const filteredFiles = filter ? files.filter(filter) : files;
682
+ return map ? filteredFiles.map(map) : filteredFiles;
622
683
  }
623
- /**
624
- * Convert Swagger path to template literals/ template strings(camelcase)
625
- * @example /pet/{petId} => `/pet/${petId}`
626
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
627
- * @example /account/userID => `/account/${userId}`
628
- */
629
- get template() {
630
- return this.toTemplateString();
684
+ };
685
+ _options = new WeakMap();
686
+
687
+ // src/FileManager.ts
688
+ var KubbFile;
689
+ ((KubbFile2) => {
690
+ })(KubbFile || (KubbFile = {}));
691
+ var _cache, _task, _isWriting, _timeout, _queue, _validate, validate_fn, _add, add_fn, _addOrAppend, addOrAppend_fn;
692
+ var _FileManager = class _FileManager {
693
+ constructor(options) {
694
+ __privateAdd(this, _validate);
695
+ __privateAdd(this, _add);
696
+ __privateAdd(this, _addOrAppend);
697
+ __privateAdd(this, _cache, /* @__PURE__ */ new Map());
698
+ __privateAdd(this, _task, void 0);
699
+ __privateAdd(this, _isWriting, false);
700
+ /**
701
+ * Timeout between writes
702
+ */
703
+ __privateAdd(this, _timeout, 0);
704
+ __privateAdd(this, _queue, void 0);
705
+ if (options) {
706
+ __privateSet(this, _task, options.task);
707
+ __privateSet(this, _queue, options.queue);
708
+ __privateSet(this, _timeout, options.timeout || 0);
709
+ }
710
+ return this;
631
711
  }
632
- get object() {
633
- return this.toObject();
712
+ get files() {
713
+ const files = [];
714
+ __privateGet(this, _cache).forEach((item) => {
715
+ files.push(...item.flat(1));
716
+ });
717
+ return files;
634
718
  }
635
- get params() {
636
- return this.getParams();
719
+ get isExecuting() {
720
+ return __privateGet(this, _queue)?.hasJobs ?? __privateGet(this, _isWriting) ?? false;
637
721
  }
638
- toObject({ type = "path", replacer, stringify } = {}) {
639
- const object = {
640
- url: type === "path" ? this.toURLPath() : this.toTemplateString(replacer),
641
- params: this.getParams()
642
- };
643
- if (stringify) {
644
- if (type !== "template") {
645
- throw new Error("Type should be `template` when using stringiyf");
722
+ async add(...files) {
723
+ const promises = files.map((file) => {
724
+ __privateMethod(this, _validate, validate_fn).call(this, file);
725
+ if (file.override) {
726
+ return __privateMethod(this, _add, add_fn).call(this, file);
646
727
  }
647
- return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
648
- }
649
- return object;
650
- }
651
- /**
652
- * Convert Swagger path to template literals/ template strings(camelcase)
653
- * @example /pet/{petId} => `/pet/${petId}`
654
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
655
- * @example /account/userID => `/account/${userId}`
656
- */
657
- toTemplateString(replacer) {
658
- const regex = /{(\w|-)*}/g;
659
- const found = this.path.match(regex);
660
- let newPath = this.path.replaceAll("{", "${");
661
- if (found) {
662
- newPath = found.reduce((prev, curr) => {
663
- const pathParam = replacer ? replacer(camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge })) : camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge });
664
- const replacement = `\${${pathParam}}`;
665
- return prev.replace(curr, replacement);
666
- }, this.path);
728
+ return __privateMethod(this, _addOrAppend, addOrAppend_fn).call(this, file);
729
+ });
730
+ const resolvedFiles = await Promise.all(promises);
731
+ if (files.length > 1) {
732
+ return resolvedFiles;
667
733
  }
668
- return `\`${newPath}\``;
734
+ return resolvedFiles[0];
669
735
  }
670
- getParams(replacer) {
671
- const regex = /{(\w|-)*}/g;
672
- const found = this.path.match(regex);
673
- if (!found) {
736
+ async addIndexes({ root, extName = ".ts", meta, options = {} }) {
737
+ const barrelManager = new BarrelManager(options);
738
+ const files = barrelManager.getIndexes(root, extName);
739
+ if (!files) {
674
740
  return void 0;
675
741
  }
676
- const params = {};
677
- found.forEach((item) => {
678
- item = item.replaceAll("{", "").replaceAll("}", "");
679
- const pathParam = replacer ? replacer(camelCase(item, { delimiter: "", transform: camelCaseTransformMerge })) : camelCase(item, { delimiter: "", transform: camelCaseTransformMerge });
680
- params[pathParam] = pathParam;
681
- }, this.path);
682
- return params;
742
+ return await Promise.all(
743
+ files.map((file) => {
744
+ return __privateMethod(this, _addOrAppend, addOrAppend_fn).call(this, {
745
+ ...file,
746
+ meta: meta ? meta : file.meta
747
+ });
748
+ })
749
+ );
683
750
  }
684
- /**
685
- * Convert Swagger path to URLPath(syntax of Express)
686
- * @example /pet/{petId} => /pet/:petId
687
- */
688
- toURLPath() {
689
- return this.path.replaceAll("{", ":").replaceAll("}", "");
751
+ getCacheByUUID(UUID) {
752
+ let cache;
753
+ __privateGet(this, _cache).forEach((files) => {
754
+ cache = files.find((item) => item.id === UUID);
755
+ });
756
+ return cache;
690
757
  }
691
- };
692
-
693
- // src/utils/Warning.ts
694
- var Warning = class extends Error {
695
- constructor(message, options) {
696
- super(message, { cause: options?.cause });
697
- this.name = "Warning";
758
+ get(path3) {
759
+ return __privateGet(this, _cache).get(path3);
698
760
  }
699
- };
700
- async function saveCreateDirectory(path) {
701
- const passedPath = pathParser.dirname(pathParser.resolve(path));
702
- await fs2.mkdir(passedPath, { recursive: true });
703
- }
704
- var writer = switcher(
705
- {
706
- node: async (path, data) => {
707
- try {
708
- await fs2.stat(path);
709
- const oldContent = await fs2.readFile(path, { encoding: "utf-8" });
710
- if (oldContent?.toString() === data) {
711
- return;
712
- }
713
- } catch (_err) {
714
- }
715
- await saveCreateDirectory(path);
716
- return fs2.writeFile(pathParser.resolve(path), data, { encoding: "utf-8" });
717
- },
718
- bun: async (path, data) => {
719
- try {
720
- await saveCreateDirectory(path);
721
- await Bun.write(pathParser.resolve(path), data);
722
- } catch (e) {
723
- console.log(e, pathParser.resolve(path));
724
- }
725
- }
726
- },
727
- "node"
728
- );
729
- async function write(data, path) {
730
- return writer(path, data);
731
- }
732
- function getIndexes(root, extName, options = {}) {
733
- const extMapper = {
734
- ".ts": {
735
- extensions: /\.ts/,
736
- exclude: [/schemas/, /json/]
737
- },
738
- ".json": {
739
- extensions: /\.json/,
740
- exclude: []
761
+ remove(path3) {
762
+ const cacheItem = this.get(path3);
763
+ if (!cacheItem) {
764
+ return;
741
765
  }
742
- };
743
- const tree = TreeNode.build(root, { ...extMapper[extName] || {}, ...options });
744
- if (!tree) {
745
- return null;
766
+ __privateGet(this, _cache).delete(path3);
746
767
  }
747
- const fileReducer = (files2, currentTree) => {
748
- if (!currentTree.children) {
749
- return [];
768
+ async write(...params) {
769
+ if (!__privateGet(this, _isWriting)) {
770
+ __privateSet(this, _isWriting, true);
771
+ const text = await write(...params);
772
+ __privateSet(this, _isWriting, false);
773
+ return text;
750
774
  }
751
- if (currentTree.children?.length > 1) {
752
- const path = pathParser.resolve(currentTree.data.path, "index.ts");
753
- const exports = currentTree.children.map((file) => {
754
- if (!file) {
755
- return void 0;
756
- }
757
- const importPath = file.data.type === "directory" ? `./${file.data.name}` : `./${file.data.name.replace(/\.[^.]*$/, "")}`;
758
- if (importPath.includes("index") && path.includes("index")) {
759
- return void 0;
760
- }
761
- return { path: importPath };
762
- }).filter(Boolean);
763
- files2.push({
764
- path,
765
- baseName: "index.ts",
766
- source: "",
767
- exports
768
- });
769
- } else {
770
- currentTree.children?.forEach((child) => {
771
- const path = pathParser.resolve(currentTree.data.path, "index.ts");
772
- const importPath = child.data.type === "directory" ? `./${child.data.name}` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
773
- files2.push({
774
- path,
775
- baseName: "index.ts",
776
- source: "",
777
- exports: [{ path: importPath }]
778
- });
779
- });
775
+ await timeout(__privateGet(this, _timeout));
776
+ return this.write(...params);
777
+ }
778
+ async read(...params) {
779
+ return read(...params);
780
+ }
781
+ // statics
782
+ static getSource(file) {
783
+ if (!_FileManager.isExtensionAllowed(file.baseName)) {
784
+ return file.source;
780
785
  }
781
- currentTree.children.forEach((childItem) => {
782
- fileReducer(files2, childItem);
783
- });
784
- return files2;
785
- };
786
- const files = fileReducer([], tree);
787
- return files;
788
- }
789
- function combineFiles(files) {
790
- return files.filter(Boolean).reduce((acc, curr) => {
791
- const prevIndex = acc.findIndex((item) => item.path === curr.path);
792
- if (prevIndex !== -1) {
786
+ const exports = file.exports ? combineExports(file.exports) : [];
787
+ const imports = file.imports ? combineImports(file.imports, exports, file.source) : [];
788
+ const importNodes = imports.map((item) => factory.createImportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly }));
789
+ const exportNodes = exports.map(
790
+ (item) => factory.createExportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly, asAlias: item.asAlias })
791
+ );
792
+ return [print([...importNodes, ...exportNodes]), getEnvSource(file.source, file.env)].join("\n");
793
+ }
794
+ static combineFiles(files) {
795
+ return files.filter(Boolean).reduce((acc, file) => {
796
+ const prevIndex = acc.findIndex((item) => item.path === file.path);
797
+ if (prevIndex === -1) {
798
+ return [...acc, file];
799
+ }
793
800
  const prev = acc[prevIndex];
801
+ if (prev && file.override) {
802
+ acc[prevIndex] = {
803
+ imports: [],
804
+ exports: [],
805
+ ...file
806
+ };
807
+ return acc;
808
+ }
794
809
  if (prev) {
795
810
  acc[prevIndex] = {
796
- ...curr,
797
- source: prev.source && curr.source ? `${prev.source}
798
- ${curr.source}` : "",
799
- imports: [...prev.imports || [], ...curr.imports || []],
800
- exports: [...prev.exports || [], ...curr.exports || []],
801
- env: { ...prev.env || {}, ...curr.env || {} }
811
+ ...file,
812
+ source: prev.source && file.source ? `${prev.source}
813
+ ${file.source}` : "",
814
+ imports: [...prev.imports || [], ...file.imports || []],
815
+ exports: [...prev.exports || [], ...file.exports || []],
816
+ env: { ...prev.env || {}, ...file.env || {} }
802
817
  };
803
818
  }
804
- } else {
805
- acc.push(curr);
819
+ return acc;
820
+ }, []);
821
+ }
822
+ static getMode(path3) {
823
+ if (!path3) {
824
+ return "directory";
806
825
  }
807
- return acc;
808
- }, []);
809
- }
810
- var extensions = [".js", ".ts", ".tsx"];
811
- function isExtensionAllowed(baseName) {
812
- return extensions.some((extension) => baseName.endsWith(extension));
813
- }
826
+ return extname(path3) ? "file" : "directory";
827
+ }
828
+ static get extensions() {
829
+ return [".js", ".ts", ".tsx"];
830
+ }
831
+ static isExtensionAllowed(baseName) {
832
+ return _FileManager.extensions.some((extension) => baseName.endsWith(extension));
833
+ }
834
+ };
835
+ _cache = new WeakMap();
836
+ _task = new WeakMap();
837
+ _isWriting = new WeakMap();
838
+ _timeout = new WeakMap();
839
+ _queue = new WeakMap();
840
+ _validate = new WeakSet();
841
+ validate_fn = function(file) {
842
+ if (!file.validate) {
843
+ return;
844
+ }
845
+ if (!file.path.toLowerCase().endsWith(file.baseName.toLowerCase())) {
846
+ throw new Error(`${file.path} should end with the baseName ${file.baseName}`);
847
+ }
848
+ };
849
+ _add = new WeakSet();
850
+ add_fn = async function(file) {
851
+ const controller = new AbortController();
852
+ const resolvedFile = { id: crypto2.randomUUID(), ...file };
853
+ __privateGet(this, _cache).set(resolvedFile.path, [{ cancel: () => controller.abort(), ...resolvedFile }]);
854
+ if (__privateGet(this, _queue)) {
855
+ await __privateGet(this, _queue).run(
856
+ async () => {
857
+ var _a;
858
+ return (_a = __privateGet(this, _task)) == null ? void 0 : _a.call(this, resolvedFile);
859
+ },
860
+ { controller }
861
+ );
862
+ }
863
+ return resolvedFile;
864
+ };
865
+ _addOrAppend = new WeakSet();
866
+ addOrAppend_fn = async function(file) {
867
+ const previousCaches = __privateGet(this, _cache).get(file.path);
868
+ const previousCache = previousCaches ? previousCaches.at(previousCaches.length - 1) : void 0;
869
+ if (previousCache) {
870
+ __privateGet(this, _cache).delete(previousCache.path);
871
+ return __privateMethod(this, _add, add_fn).call(this, {
872
+ ...file,
873
+ source: previousCache.source && file.source ? `${previousCache.source}
874
+ ${file.source}` : "",
875
+ imports: [...previousCache.imports || [], ...file.imports || []],
876
+ exports: [...previousCache.exports || [], ...file.exports || []],
877
+ env: { ...previousCache.env || {}, ...file.env || {} }
878
+ });
879
+ }
880
+ return __privateMethod(this, _add, add_fn).call(this, file);
881
+ };
882
+ var FileManager = _FileManager;
814
883
  function combineExports(exports) {
815
- return exports.reduce((prev, curr) => {
884
+ const combinedExports = orderBy(exports, [(v) => !v.isTypeOnly], ["asc"]).reduce((prev, curr) => {
816
885
  const name = curr.name;
817
886
  const prevByPath = prev.findLast((imp) => imp.path === curr.path);
887
+ const prevByPathAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && isEqual(imp.name, name) && imp.isTypeOnly);
888
+ if (prevByPathAndIsTypeOnly) {
889
+ return prev;
890
+ }
818
891
  const uniquePrev = prev.findLast(
819
892
  (imp) => imp.path === curr.path && isEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly && imp.asAlias === curr.asAlias
820
893
  );
@@ -836,12 +909,16 @@ function combineExports(exports) {
836
909
  }
837
910
  return [...prev, curr];
838
911
  }, []);
912
+ return orderBy(combinedExports, [(v) => !v.isTypeOnly, (v) => v.asAlias], ["desc", "desc"]);
839
913
  }
840
914
  function combineImports(imports, exports, source) {
841
- return imports.reduce((prev, curr) => {
915
+ const combinedImports = orderBy(imports, [(v) => !v.isTypeOnly], ["asc"]).reduce((prev, curr) => {
842
916
  let name = Array.isArray(curr.name) ? [...new Set(curr.name)] : curr.name;
843
917
  const hasImportInSource = (importName) => {
844
- const checker = (name2) => name2 && !!source.includes(`${name2}`);
918
+ if (!source) {
919
+ return true;
920
+ }
921
+ const checker = (name2) => name2 && !!source.includes(name2);
845
922
  return checker(importName) || exports.some(({ name: name2 }) => Array.isArray(name2) ? name2.some(checker) : checker(name2));
846
923
  };
847
924
  if (Array.isArray(name)) {
@@ -849,6 +926,10 @@ function combineImports(imports, exports, source) {
849
926
  }
850
927
  const prevByPath = prev.findLast((imp) => imp.path === curr.path && imp.isTypeOnly === curr.isTypeOnly);
851
928
  const uniquePrev = prev.findLast((imp) => imp.path === curr.path && isEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly);
929
+ const prevByPathNameAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && isEqual(imp.name, name) && imp.isTypeOnly);
930
+ if (prevByPathNameAndIsTypeOnly) {
931
+ return prev;
932
+ }
852
933
  if (uniquePrev || Array.isArray(name) && !name.length) {
853
934
  return prev;
854
935
  }
@@ -870,43 +951,7 @@ function combineImports(imports, exports, source) {
870
951
  }
871
952
  return [...prev, curr];
872
953
  }, []);
873
- }
874
- function createFileSource(file) {
875
- let { source } = file;
876
- if (!isExtensionAllowed(file.baseName)) {
877
- return file.source;
878
- }
879
- const exports = file.exports ? combineExports(file.exports) : [];
880
- const imports = file.imports ? combineImports(file.imports, exports, source) : [];
881
- const importNodes = imports.map((item) => createImportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly }));
882
- const importSource = print(importNodes);
883
- const exportNodes = exports.map((item) => createExportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly, asAlias: item.asAlias }));
884
- const exportSource = print(exportNodes);
885
- source = getEnvSource(file.source, file.env);
886
- if (importSource) {
887
- source = `${importSource}
888
- ${source}`;
889
- }
890
- if (exportSource) {
891
- source = `${exportSource}
892
- ${source}`;
893
- }
894
- return source;
895
- }
896
- function searchAndReplace(options) {
897
- const { text, replaceBy, prefix = "", key } = options;
898
- const searchValues = options.searchValues?.(prefix, key) || [
899
- `${prefix}["${key}"]`,
900
- `${prefix}['${key}']`,
901
- `${prefix}[\`${key}\`]`,
902
- `${prefix}"${key}"`,
903
- `${prefix}'${key}'`,
904
- `${prefix}\`${key}\``,
905
- new RegExp(`${prefix}${key}`, "g")
906
- ];
907
- return searchValues.reduce((prev, searchValue) => {
908
- return prev.toString().replaceAll(searchValue, replaceBy);
909
- }, text);
954
+ return orderBy(combinedImports, [(v) => !v.isTypeOnly], ["desc"]);
910
955
  }
911
956
  function getEnvSource(source, env) {
912
957
  if (!env) {
@@ -923,175 +968,157 @@ function getEnvSource(source, env) {
923
968
  throw new TypeError(`Environment should be in upperCase for ${key}`);
924
969
  }
925
970
  if (typeof replaceBy === "string") {
926
- prev = searchAndReplace({ text: prev.replaceAll(`process.env.${key}`, replaceBy), replaceBy, prefix: "process.env", key });
927
- prev = searchAndReplace({ text: prev.replaceAll(new RegExp(`(declare const).*
971
+ prev = transformers.searchAndReplace({ text: prev.replaceAll(`process.env.${key}`, replaceBy), replaceBy, prefix: "process.env", key });
972
+ prev = transformers.searchAndReplace({ text: prev.replaceAll(new RegExp(`(declare const).*
928
973
  `, "ig"), ""), replaceBy, key });
929
974
  }
930
975
  return prev;
931
976
  }, source);
932
977
  }
933
-
934
- // src/managers/fileManager/FileManager.ts
935
- var FileManager = class {
936
- #cache = /* @__PURE__ */ new Map();
937
- #task;
938
- #queue;
939
- constructor(options) {
940
- if (options) {
941
- this.#task = options.task;
942
- this.#queue = options.queue;
943
- }
944
- return this;
978
+ var _emitter;
979
+ var EventEmitter = class {
980
+ constructor() {
981
+ __privateAdd(this, _emitter, new EventEmitter$1());
982
+ __privateGet(this, _emitter).setMaxListeners(100);
945
983
  }
946
- get extensions() {
947
- return extensions;
984
+ emit(eventName, ...eventArg) {
985
+ __privateGet(this, _emitter).emit(eventName, ...eventArg);
948
986
  }
949
- get files() {
950
- const files = [];
951
- this.#cache.forEach((item) => {
952
- files.push(...item.flat(1));
953
- });
954
- return files;
987
+ on(eventName, handler) {
988
+ __privateGet(this, _emitter).on(eventName, handler);
955
989
  }
956
- get isExecuting() {
957
- return this.#queue?.hasJobs ?? false;
990
+ off(eventName, handler) {
991
+ __privateGet(this, _emitter).off(eventName, handler);
958
992
  }
959
- async add(file) {
960
- const controller = new AbortController();
961
- const resolvedFile = { id: crypto.randomUUID(), ...file };
962
- this.#cache.set(resolvedFile.path, [{ cancel: () => controller.abort(), ...resolvedFile }]);
963
- if (this.#queue) {
964
- try {
965
- await this.#queue.run(
966
- async () => {
967
- return this.#task?.(resolvedFile);
968
- },
969
- { controller }
970
- );
971
- } catch {
972
- return resolvedFile;
973
- }
974
- }
975
- return resolvedFile;
993
+ removeAll() {
994
+ __privateGet(this, _emitter).removeAllListeners();
976
995
  }
977
- async addOrAppend(file) {
978
- const previousCaches = this.#cache.get(file.path);
979
- const previousCache = previousCaches ? previousCaches.at(previousCaches.length - 1) : void 0;
980
- if (previousCache) {
981
- this.#cache.delete(previousCache.path);
982
- return this.add({
983
- ...file,
984
- source: previousCache.source && file.source ? `${previousCache.source}
985
- ${file.source}` : "",
986
- imports: [...previousCache.imports || [], ...file.imports || []],
987
- exports: [...previousCache.exports || [], ...file.exports || []],
988
- env: { ...previousCache.env || {}, ...file.env || {} }
996
+ };
997
+ _emitter = new WeakMap();
998
+ var _queue2, _workerCount, _maxParallel, _debug, _work, work_fn;
999
+ var Queue = class {
1000
+ constructor(maxParallel, debug = false) {
1001
+ __privateAdd(this, _work);
1002
+ __privateAdd(this, _queue2, []);
1003
+ this.eventEmitter = new EventEmitter();
1004
+ __privateAdd(this, _workerCount, 0);
1005
+ __privateAdd(this, _maxParallel, void 0);
1006
+ __privateAdd(this, _debug, false);
1007
+ __privateSet(this, _maxParallel, maxParallel);
1008
+ __privateSet(this, _debug, debug);
1009
+ }
1010
+ run(job, options = { controller: new AbortController(), name: crypto2.randomUUID(), description: "" }) {
1011
+ return new Promise((resolve2, reject) => {
1012
+ const item = { reject, resolve: resolve2, job, name: options.name, description: options.description || options.name };
1013
+ options.controller?.signal.addEventListener("abort", () => {
1014
+ __privateSet(this, _queue2, __privateGet(this, _queue2).filter((queueItem) => queueItem.name === item.name));
1015
+ reject("Aborted");
989
1016
  });
990
- }
991
- return this.add(file);
992
- }
993
- async addIndexes(root, extName = ".ts", options = {}) {
994
- const files = await getIndexes(root, extName, options);
995
- if (!files) {
996
- return void 0;
997
- }
998
- return Promise.all(
999
- files.map((file) => {
1000
- if (file.override) {
1001
- return this.add(file);
1002
- }
1003
- return this.addOrAppend(file);
1004
- })
1005
- );
1006
- }
1007
- #append(path, file) {
1008
- const previousFiles = this.#cache.get(path) || [];
1009
- this.#cache.set(path, [...previousFiles, file]);
1010
- }
1011
- getCacheByUUID(UUID) {
1012
- let cache;
1013
- this.#cache.forEach((files) => {
1014
- cache = files.find((item) => item.id === UUID);
1017
+ __privateGet(this, _queue2).push(item);
1018
+ __privateMethod(this, _work, work_fn).call(this);
1015
1019
  });
1016
- return cache;
1017
1020
  }
1018
- get(path) {
1019
- return this.#cache.get(path);
1021
+ runSync(job, options = { controller: new AbortController(), name: crypto2.randomUUID(), description: "" }) {
1022
+ new Promise((resolve2, reject) => {
1023
+ const item = { reject, resolve: resolve2, job, name: options.name, description: options.description || options.name };
1024
+ options.controller?.signal.addEventListener("abort", () => {
1025
+ __privateSet(this, _queue2, __privateGet(this, _queue2).filter((queueItem) => queueItem.name === item.name));
1026
+ });
1027
+ __privateGet(this, _queue2).push(item);
1028
+ __privateMethod(this, _work, work_fn).call(this);
1029
+ });
1020
1030
  }
1021
- remove(path) {
1022
- const cacheItem = this.get(path);
1023
- if (!cacheItem) {
1024
- return;
1025
- }
1026
- this.#cache.delete(path);
1031
+ get hasJobs() {
1032
+ return __privateGet(this, _workerCount) > 0 || __privateGet(this, _queue2).length > 0;
1027
1033
  }
1028
- async write(...params) {
1029
- if (this.#queue) {
1030
- return this.#queue.run(async () => {
1031
- return write(...params);
1032
- });
1033
- }
1034
- return write(...params);
1034
+ get count() {
1035
+ return __privateGet(this, _workerCount);
1035
1036
  }
1036
- async read(...params) {
1037
- if (this.#queue) {
1038
- return this.#queue.run(async () => {
1039
- return read(...params);
1040
- });
1041
- }
1042
- return read(...params);
1037
+ };
1038
+ _queue2 = new WeakMap();
1039
+ _workerCount = new WeakMap();
1040
+ _maxParallel = new WeakMap();
1041
+ _debug = new WeakMap();
1042
+ _work = new WeakSet();
1043
+ work_fn = function() {
1044
+ if (__privateGet(this, _workerCount) >= __privateGet(this, _maxParallel)) {
1045
+ return;
1046
+ }
1047
+ __privateWrapper(this, _workerCount)._++;
1048
+ let entry;
1049
+ while (entry = __privateGet(this, _queue2).shift()) {
1050
+ const { reject, resolve: resolve2, job, name, description } = entry;
1051
+ if (__privateGet(this, _debug)) {
1052
+ performance.mark(name + "_start");
1053
+ }
1054
+ job().then((result) => {
1055
+ this.eventEmitter.emit("jobDone", result);
1056
+ resolve2(result);
1057
+ if (__privateGet(this, _debug)) {
1058
+ performance.mark(name + "_stop");
1059
+ performance.measure(description, name + "_start", name + "_stop");
1060
+ }
1061
+ }).catch((err) => {
1062
+ this.eventEmitter.emit("jobFailed", err);
1063
+ reject(err);
1064
+ });
1043
1065
  }
1066
+ __privateWrapper(this, _workerCount)._--;
1044
1067
  };
1045
1068
 
1046
- // src/managers/pluginManager/ParallelPluginError.ts
1047
- var ParallelPluginError = class extends Error {
1048
- errors = [];
1049
- pluginManager;
1069
+ // src/utils/uniqueName.ts
1070
+ function setUniqueName(originalName, data) {
1071
+ let used = data[originalName] || 0;
1072
+ if (used) {
1073
+ data[originalName] = ++used;
1074
+ return originalName;
1075
+ }
1076
+ data[originalName] = 1;
1077
+ return originalName;
1078
+ }
1079
+
1080
+ // src/errors.ts
1081
+ var Warning = class extends Error {
1050
1082
  constructor(message, options) {
1051
- super(message, { cause: options.cause });
1052
- this.name = "ParallelPluginError";
1053
- this.errors = options.errors;
1054
- this.pluginManager = options.pluginManager;
1083
+ super(message, { cause: options?.cause });
1084
+ this.name = "Warning";
1055
1085
  }
1056
- findError(searchError) {
1057
- if (!searchError) {
1058
- return void 0;
1059
- }
1060
- return this.errors.find((error) => {
1061
- if (error.cause) {
1062
- if (error.cause.name == searchError.name) {
1063
- return true;
1064
- }
1065
- return !!this.findError(error.cause);
1086
+ };
1087
+ var ValidationPluginError = class extends Error {
1088
+ };
1089
+
1090
+ // src/utils/cache.ts
1091
+ function createPluginCache(Store = /* @__PURE__ */ Object.create(null)) {
1092
+ return {
1093
+ set(id, value) {
1094
+ Store[id] = [0, value];
1095
+ },
1096
+ get(id) {
1097
+ const item = Store[id];
1098
+ if (!item) {
1099
+ return null;
1100
+ }
1101
+ item[0] = 0;
1102
+ return item[1];
1103
+ },
1104
+ has(id) {
1105
+ const item = Store[id];
1106
+ if (!item) {
1107
+ return false;
1066
1108
  }
1067
- return error.name === searchError.name;
1068
- })?.cause;
1069
- }
1070
- };
1109
+ item[0] = 0;
1110
+ return true;
1111
+ },
1112
+ delete(id) {
1113
+ return delete Store[id];
1114
+ }
1115
+ };
1116
+ }
1071
1117
 
1072
- // src/managers/pluginManager/PluginError.ts
1073
- var PluginError = class extends Error {
1074
- pluginManager;
1075
- cause;
1076
- constructor(message, options) {
1077
- super(message, { cause: options.cause });
1078
- this.name = "PluginError";
1079
- this.cause = options.cause;
1080
- this.pluginManager = options.pluginManager;
1081
- }
1082
- };
1083
- function createPlugin(factory) {
1118
+ // src/plugin.ts
1119
+ function createPlugin(factory2) {
1084
1120
  return (options) => {
1085
- const plugin = factory(options);
1086
- if (Array.isArray(plugin)) {
1087
- throw new Error("Not implemented");
1088
- }
1089
- if (!plugin.transform) {
1090
- plugin.transform = function transform(code) {
1091
- return code;
1092
- };
1093
- }
1094
- return plugin;
1121
+ return factory2(options);
1095
1122
  };
1096
1123
  }
1097
1124
  var pluginName = "core";
@@ -1100,6 +1127,8 @@ var definePlugin = createPlugin((options) => {
1100
1127
  return {
1101
1128
  name: pluginName,
1102
1129
  options,
1130
+ key: ["controller", "core"],
1131
+ kind: "controller",
1103
1132
  api() {
1104
1133
  return {
1105
1134
  get config() {
@@ -1108,18 +1137,18 @@ var definePlugin = createPlugin((options) => {
1108
1137
  get plugins() {
1109
1138
  return options.getPlugins();
1110
1139
  },
1140
+ get plugin() {
1141
+ return options.plugin;
1142
+ },
1111
1143
  logger,
1112
1144
  fileManager,
1113
1145
  pluginManager,
1114
1146
  async addFile(...files) {
1115
- return Promise.all(
1116
- files.map((file) => {
1117
- if (file.override) {
1118
- return fileManager.add(file);
1119
- }
1120
- return fileManager.addOrAppend(file);
1121
- })
1122
- );
1147
+ const resolvedFiles = await fileManager.add(...files);
1148
+ if (!Array.isArray(resolvedFiles)) {
1149
+ return [resolvedFiles];
1150
+ }
1151
+ return resolvedFiles;
1123
1152
  },
1124
1153
  resolvePath,
1125
1154
  resolveName,
@@ -1127,75 +1156,156 @@ var definePlugin = createPlugin((options) => {
1127
1156
  };
1128
1157
  },
1129
1158
  resolvePath(baseName) {
1130
- const root = pathParser.resolve(this.config.root, this.config.output.path);
1131
- return pathParser.resolve(root, baseName);
1159
+ const root = path.resolve(this.config.root, this.config.output.path);
1160
+ return path.resolve(root, baseName);
1132
1161
  },
1133
1162
  resolveName(name) {
1134
1163
  return name;
1135
1164
  }
1136
1165
  };
1137
1166
  });
1138
- var EventEmitter = class {
1139
- constructor() {
1140
- this.#emitter.setMaxListeners(100);
1141
- }
1142
- #emitter = new EventEmitter$1();
1143
- emit(eventName, ...eventArg) {
1144
- this.#emitter.emit(eventName, ...eventArg);
1145
- }
1146
- on(eventName, handler) {
1147
- this.#emitter.on(eventName, handler);
1167
+
1168
+ // src/utils/executeStrategies.ts
1169
+ function hookSeq(promises) {
1170
+ return promises.filter(Boolean).reduce(
1171
+ (promise, func) => {
1172
+ if (typeof func !== "function") {
1173
+ throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
1174
+ }
1175
+ return promise.then((state) => {
1176
+ const calledFunc = func(state);
1177
+ if (calledFunc) {
1178
+ return calledFunc.then(Array.prototype.concat.bind(state));
1179
+ }
1180
+ });
1181
+ },
1182
+ Promise.resolve([])
1183
+ );
1184
+ }
1185
+ function hookFirst(promises, nullCheck = (state) => state !== null) {
1186
+ let promise = Promise.resolve(null);
1187
+ for (const func of promises.filter(Boolean)) {
1188
+ promise = promise.then((state) => {
1189
+ if (nullCheck(state)) {
1190
+ return state;
1191
+ }
1192
+ const calledFunc = func(state);
1193
+ return calledFunc;
1194
+ });
1148
1195
  }
1149
- off(eventName, handler) {
1150
- this.#emitter.off(eventName, handler);
1196
+ return promise;
1197
+ }
1198
+ function hookParallel(promises) {
1199
+ return Promise.allSettled(promises.filter(Boolean).map((promise) => promise()));
1200
+ }
1201
+
1202
+ // src/PromiseManager.ts
1203
+ var _options2;
1204
+ var PromiseManager = class {
1205
+ constructor(options = {}) {
1206
+ __privateAdd(this, _options2, {});
1207
+ __privateSet(this, _options2, options);
1208
+ return this;
1151
1209
  }
1152
- removeAll() {
1153
- this.#emitter.removeAllListeners();
1210
+ run(strategy, promises) {
1211
+ if (strategy === "seq") {
1212
+ return hookSeq(promises);
1213
+ }
1214
+ if (strategy === "first") {
1215
+ return hookFirst(promises, __privateGet(this, _options2).nullCheck);
1216
+ }
1217
+ if (strategy === "parallel") {
1218
+ return hookParallel(promises);
1219
+ }
1220
+ throw new Error(`${strategy} not implemented`);
1154
1221
  }
1155
1222
  };
1156
-
1157
- // src/managers/pluginManager/pluginParser.ts
1158
- var usedPluginNames = {};
1159
- function pluginParser(plugin, context) {
1160
- const key = [plugin.kind, plugin.name, getUniqueName(plugin.name, usedPluginNames).split(plugin.name).at(1)];
1161
- if (plugin.api && typeof plugin.api === "function") {
1162
- const api = plugin.api.call(context);
1163
- return {
1164
- ...plugin,
1165
- key,
1166
- api
1167
- };
1168
- }
1169
- return {
1170
- ...plugin,
1171
- key
1172
- };
1223
+ _options2 = new WeakMap();
1224
+ function isPromise(result) {
1225
+ return !!result && typeof result?.then === "function";
1226
+ }
1227
+ function isPromiseRejectedResult(result) {
1228
+ return result.status === "rejected";
1173
1229
  }
1174
1230
 
1175
- // src/managers/pluginManager/PluginManager.ts
1176
- var hookNames = {
1177
- validate: 1,
1178
- buildStart: 1,
1179
- resolvePath: 1,
1180
- resolveName: 1,
1181
- load: 1,
1182
- transform: 1,
1183
- writeFile: 1,
1184
- buildEnd: 1
1185
- };
1186
- var hooks = Object.keys(hookNames);
1231
+ // src/PluginManager.ts
1232
+ var _core, _usedPluginNames, _promiseManager, _getSortedPlugins, getSortedPlugins_fn, _addExecutedToCallStack, addExecutedToCallStack_fn, _execute, execute_fn, _executeSync, executeSync_fn, _catcher, catcher_fn, _parse, parse_fn;
1187
1233
  var PluginManager = class {
1188
- plugins;
1189
- fileManager;
1190
- eventEmitter = new EventEmitter();
1191
- queue;
1192
- executed = [];
1193
- logger;
1194
- #core;
1195
1234
  constructor(config, options) {
1235
+ __privateAdd(this, _getSortedPlugins);
1236
+ __privateAdd(this, _addExecutedToCallStack);
1237
+ /**
1238
+ * Run an async plugin hook and return the result.
1239
+ * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
1240
+ * @param args Arguments passed to the plugin hook.
1241
+ * @param plugin The actual pluginObject to run.
1242
+ */
1243
+ // Implementation signature
1244
+ __privateAdd(this, _execute);
1245
+ /**
1246
+ * Run a sync plugin hook and return the result.
1247
+ * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
1248
+ * @param args Arguments passed to the plugin hook.
1249
+ * @param plugin The acutal plugin
1250
+ * @param replaceContext When passed, the plugin context can be overridden.
1251
+ */
1252
+ __privateAdd(this, _executeSync);
1253
+ __privateAdd(this, _catcher);
1254
+ __privateAdd(this, _parse);
1255
+ this.eventEmitter = new EventEmitter();
1256
+ this.executed = [];
1257
+ __privateAdd(this, _core, void 0);
1258
+ __privateAdd(this, _usedPluginNames, {});
1259
+ __privateAdd(this, _promiseManager, void 0);
1260
+ this.resolvePath = (params) => {
1261
+ if (params.pluginKey) {
1262
+ const paths = this.hookForPluginSync({
1263
+ pluginKey: params.pluginKey,
1264
+ hookName: "resolvePath",
1265
+ parameters: [params.baseName, params.directory, params.options]
1266
+ });
1267
+ if (paths && paths?.length > 1) {
1268
+ throw new Error(
1269
+ `Cannot return a path where the 'pluginKey' ${params.pluginKey ? JSON.stringify(params.pluginKey) : '"'} is not unique enough
1270
+
1271
+ Paths: ${JSON.stringify(paths, void 0, 2)}`
1272
+ );
1273
+ }
1274
+ return paths?.at(0);
1275
+ }
1276
+ return this.hookFirstSync({
1277
+ hookName: "resolvePath",
1278
+ parameters: [params.baseName, params.directory, params.options]
1279
+ }).result;
1280
+ };
1281
+ this.resolveName = (params) => {
1282
+ if (params.pluginKey) {
1283
+ const names = this.hookForPluginSync({
1284
+ pluginKey: params.pluginKey,
1285
+ hookName: "resolveName",
1286
+ parameters: [params.name, params.type]
1287
+ });
1288
+ if (names && names?.length > 1) {
1289
+ throw new Error(
1290
+ `Cannot return a name where the 'pluginKey' ${params.pluginKey ? JSON.stringify(params.pluginKey) : '"'} is not unique enough
1291
+
1292
+ Names: ${JSON.stringify(names, void 0, 2)}`
1293
+ );
1294
+ }
1295
+ return transformReservedWord(names?.at(0) || params.name);
1296
+ }
1297
+ const name = this.hookFirstSync({
1298
+ hookName: "resolveName",
1299
+ parameters: [params.name, params.type]
1300
+ }).result;
1301
+ return transformReservedWord(name);
1302
+ };
1303
+ this.config = config;
1196
1304
  this.logger = options.logger;
1197
- this.queue = new Queue(100, options.debug);
1198
- this.fileManager = new FileManager({ task: options.task, queue: this.queue });
1305
+ this.queue = new Queue(100, this.logger.logLevel === LogLevel.debug);
1306
+ this.fileManager = new FileManager({ task: options.task, queue: this.queue, timeout: options.writeTimeout });
1307
+ __privateSet(this, _promiseManager, new PromiseManager({ nullCheck: (state) => !!state?.result }));
1308
+ const plugins = config.plugins || [];
1199
1309
  const core = definePlugin({
1200
1310
  config,
1201
1311
  logger: this.logger,
@@ -1203,44 +1313,14 @@ var PluginManager = class {
1203
1313
  fileManager: this.fileManager,
1204
1314
  resolvePath: this.resolvePath.bind(this),
1205
1315
  resolveName: this.resolveName.bind(this),
1206
- getPlugins: this.#getSortedPlugins.bind(this),
1207
- plugin: void 0
1316
+ getPlugins: __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).bind(this)
1317
+ });
1318
+ __privateSet(this, _core, __privateMethod(this, _parse, parse_fn).call(this, core, this, core.api.call(null)));
1319
+ this.plugins = [__privateGet(this, _core), ...plugins].map((plugin) => {
1320
+ return __privateMethod(this, _parse, parse_fn).call(this, plugin, this, __privateGet(this, _core).api);
1208
1321
  });
1209
- this.#core = pluginParser(core, core.api.call(null));
1210
- this.plugins = [this.#core, ...config.plugins || []].reduce((prev, plugin) => {
1211
- const convertedApi = pluginParser(plugin, this.#core?.api);
1212
- return [...prev, convertedApi];
1213
- }, []);
1214
1322
  return this;
1215
1323
  }
1216
- resolvePath = (params) => {
1217
- if (params.pluginName) {
1218
- return this.hookForPluginSync({
1219
- pluginName: params.pluginName,
1220
- hookName: "resolvePath",
1221
- parameters: [params.baseName, params.directory, params.options]
1222
- });
1223
- }
1224
- return this.hookFirstSync({
1225
- hookName: "resolvePath",
1226
- parameters: [params.baseName, params.directory, params.options]
1227
- }).result;
1228
- };
1229
- resolveName = (params) => {
1230
- if (params.pluginName) {
1231
- const name2 = this.hookForPluginSync({
1232
- pluginName: params.pluginName,
1233
- hookName: "resolveName",
1234
- parameters: [params.name, params.type]
1235
- });
1236
- return transformReservedWord(name2 || params.name);
1237
- }
1238
- const name = this.hookFirstSync({
1239
- hookName: "resolveName",
1240
- parameters: [params.name, params.type]
1241
- }).result;
1242
- return transformReservedWord(name);
1243
- };
1244
1324
  on(eventName, handler) {
1245
1325
  this.eventEmitter.on(eventName, handler);
1246
1326
  }
@@ -1248,49 +1328,49 @@ var PluginManager = class {
1248
1328
  * Run only hook for a specific plugin name
1249
1329
  */
1250
1330
  hookForPlugin({
1251
- pluginName: pluginName2,
1331
+ pluginKey,
1252
1332
  hookName,
1253
1333
  parameters
1254
1334
  }) {
1255
- const plugin = this.getPlugin(hookName, pluginName2);
1256
- return this.#execute({
1257
- strategy: "hookFirst",
1258
- hookName,
1259
- parameters,
1260
- plugin
1261
- });
1335
+ const plugins = this.getPluginsByKey(hookName, pluginKey);
1336
+ const promises = plugins.map((plugin) => {
1337
+ return __privateMethod(this, _execute, execute_fn).call(this, {
1338
+ strategy: "hookFirst",
1339
+ hookName,
1340
+ parameters,
1341
+ plugin
1342
+ });
1343
+ }).filter(Boolean);
1344
+ return Promise.all(promises);
1262
1345
  }
1263
1346
  hookForPluginSync({
1264
- pluginName: pluginName2,
1347
+ pluginKey,
1265
1348
  hookName,
1266
1349
  parameters
1267
1350
  }) {
1268
- const plugin = this.getPlugin(hookName, pluginName2);
1269
- return this.#executeSync({
1270
- strategy: "hookFirst",
1271
- hookName,
1272
- parameters,
1273
- plugin
1274
- });
1351
+ const plugins = this.getPluginsByKey(hookName, pluginKey);
1352
+ return plugins.map((plugin) => {
1353
+ return __privateMethod(this, _executeSync, executeSync_fn).call(this, {
1354
+ strategy: "hookFirst",
1355
+ hookName,
1356
+ parameters,
1357
+ plugin
1358
+ });
1359
+ }).filter(Boolean);
1275
1360
  }
1276
1361
  /**
1277
1362
  * Chains, first non-null result stops and returns
1278
1363
  */
1279
- hookFirst({
1364
+ async hookFirst({
1280
1365
  hookName,
1281
1366
  parameters,
1282
1367
  skipped
1283
1368
  }) {
1284
- let promise = Promise.resolve(null);
1285
- for (const plugin of this.#getSortedPlugins()) {
1286
- if (skipped && skipped.has(plugin)) {
1287
- continue;
1288
- }
1289
- promise = promise.then(async (parseResult) => {
1290
- if (parseResult?.result != null) {
1291
- return parseResult;
1292
- }
1293
- const value = await this.#execute({
1369
+ const promises = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this).filter((plugin) => {
1370
+ return skipped ? skipped.has(plugin) : true;
1371
+ }).map((plugin) => {
1372
+ return async () => {
1373
+ const value = await __privateMethod(this, _execute, execute_fn).call(this, {
1294
1374
  strategy: "hookFirst",
1295
1375
  hookName,
1296
1376
  parameters,
@@ -1302,9 +1382,9 @@ var PluginManager = class {
1302
1382
  result: value
1303
1383
  }
1304
1384
  );
1305
- });
1306
- }
1307
- return promise;
1385
+ };
1386
+ });
1387
+ return __privateGet(this, _promiseManager).run("first", promises);
1308
1388
  }
1309
1389
  /**
1310
1390
  * Chains, first non-null result stops and returns
@@ -1315,12 +1395,12 @@ var PluginManager = class {
1315
1395
  skipped
1316
1396
  }) {
1317
1397
  let parseResult = null;
1318
- for (const plugin of this.#getSortedPlugins()) {
1398
+ for (const plugin of __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this)) {
1319
1399
  if (skipped && skipped.has(plugin)) {
1320
1400
  continue;
1321
1401
  }
1322
1402
  parseResult = {
1323
- result: this.#executeSync({
1403
+ result: __privateMethod(this, _executeSync, executeSync_fn).call(this, {
1324
1404
  strategy: "hookFirst",
1325
1405
  hookName,
1326
1406
  parameters,
@@ -1341,23 +1421,16 @@ var PluginManager = class {
1341
1421
  hookName,
1342
1422
  parameters
1343
1423
  }) {
1344
- const parallelPromises = [];
1345
- for (const plugin of this.#getSortedPlugins()) {
1346
- const promise = this.#execute({ strategy: "hookParallel", hookName, parameters, plugin });
1347
- if (promise) {
1348
- parallelPromises.push(promise);
1349
- }
1350
- }
1351
- const results = await Promise.allSettled(parallelPromises);
1352
- const errors = results.map((result) => {
1353
- if (isPromiseRejectedResult(result) && result.reason instanceof PluginError) {
1354
- return result.reason;
1424
+ const promises = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this).map((plugin) => {
1425
+ return () => __privateMethod(this, _execute, execute_fn).call(this, { strategy: "hookParallel", hookName, parameters, plugin });
1426
+ });
1427
+ const results = await __privateGet(this, _promiseManager).run("parallel", promises);
1428
+ results.forEach((result, index) => {
1429
+ if (isPromiseRejectedResult(result)) {
1430
+ const plugin = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this)[index];
1431
+ __privateMethod(this, _catcher, catcher_fn).call(this, result.reason, plugin, hookName);
1355
1432
  }
1356
- return void 0;
1357
- }).filter(Boolean);
1358
- if (errors.length) {
1359
- throw new ParallelPluginError("Error", { errors, pluginManager: this });
1360
- }
1433
+ });
1361
1434
  return results.filter((result) => result.status === "fulfilled").map((result) => result.value);
1362
1435
  }
1363
1436
  /**
@@ -1370,191 +1443,220 @@ var PluginManager = class {
1370
1443
  }) {
1371
1444
  const [argument0, ...rest] = parameters;
1372
1445
  let promise = Promise.resolve(argument0);
1373
- for (const plugin of this.#getSortedPlugins()) {
1446
+ for (const plugin of __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this)) {
1374
1447
  promise = promise.then((arg0) => {
1375
- const value = this.#execute({
1448
+ const value = __privateMethod(this, _execute, execute_fn).call(this, {
1376
1449
  strategy: "hookReduceArg0",
1377
1450
  hookName,
1378
1451
  parameters: [arg0, ...rest],
1379
1452
  plugin
1380
1453
  });
1381
1454
  return value;
1382
- }).then((result) => reduce.call(this.#core.api, argument0, result, plugin));
1455
+ }).then((result) => reduce.call(__privateGet(this, _core).api, argument0, result, plugin));
1383
1456
  }
1384
1457
  return promise;
1385
1458
  }
1386
1459
  /**
1387
1460
  * Chains plugins
1388
1461
  */
1389
- hookSeq({ hookName, parameters }) {
1390
- let promise = Promise.resolve();
1391
- for (const plugin of this.#getSortedPlugins()) {
1392
- promise = promise.then(() => {
1393
- this.#execute({
1394
- strategy: "hookSeq",
1395
- hookName,
1396
- parameters,
1397
- plugin
1398
- });
1462
+ async hookSeq({ hookName, parameters }) {
1463
+ const promises = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this).map((plugin) => {
1464
+ return () => __privateMethod(this, _execute, execute_fn).call(this, {
1465
+ strategy: "hookSeq",
1466
+ hookName,
1467
+ parameters,
1468
+ plugin
1399
1469
  });
1400
- }
1401
- return promise.then(noReturn);
1402
- }
1403
- #getSortedPlugins(hookName) {
1404
- const plugins = [...this.plugins].filter((plugin) => plugin.name !== "core");
1405
- if (hookName) {
1406
- return plugins.filter((item) => item[hookName]);
1407
- }
1408
- return plugins;
1470
+ });
1471
+ return __privateGet(this, _promiseManager).run("seq", promises);
1409
1472
  }
1410
- getPlugin(hookName, pluginName2) {
1473
+ getPluginsByKey(hookName, pluginKey) {
1411
1474
  const plugins = [...this.plugins];
1412
- const pluginByPluginName = plugins.find((item) => item.name === pluginName2 && item[hookName]);
1413
- if (!pluginByPluginName) {
1414
- return this.#core;
1475
+ const [searchKind, searchPluginName, searchIdentifier] = pluginKey;
1476
+ const pluginByPluginName = plugins.filter((plugin) => plugin[hookName]).filter((item) => {
1477
+ const [kind, name, identifier] = item.key;
1478
+ const identifierCheck = identifier?.toString() === searchIdentifier?.toString();
1479
+ const kindCheck = kind === searchKind;
1480
+ const nameCheck = name === searchPluginName;
1481
+ if (searchIdentifier) {
1482
+ return identifierCheck && kindCheck && nameCheck;
1483
+ }
1484
+ return kindCheck && nameCheck;
1485
+ });
1486
+ if (!pluginByPluginName?.length) {
1487
+ const corePlugin = plugins.find((plugin) => plugin.name === "core" && plugin[hookName]);
1488
+ if (this.logger.logLevel === "info") {
1489
+ if (corePlugin) {
1490
+ this.logger.warn(`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, falling back on the '@kubb/core' plugin`);
1491
+ } else {
1492
+ this.logger.warn(`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, no fallback found in the '@kubb/core' plugin`);
1493
+ }
1494
+ }
1495
+ return corePlugin ? [corePlugin] : [];
1415
1496
  }
1416
1497
  return pluginByPluginName;
1417
1498
  }
1418
- #addExecutedToCallStack(executer) {
1419
- if (executer) {
1420
- this.eventEmitter.emit("execute", executer);
1421
- this.executed.push(executer);
1422
- }
1423
- }
1424
- /**
1425
- * Run an async plugin hook and return the result.
1426
- * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
1427
- * @param args Arguments passed to the plugin hook.
1428
- * @param plugin The actual pluginObject to run.
1429
- */
1430
- // Implementation signature
1431
- #execute({
1432
- strategy,
1433
- hookName,
1434
- parameters,
1435
- plugin
1436
- }) {
1437
- const hook = plugin[hookName];
1438
- let output;
1439
- if (!hook) {
1440
- return null;
1499
+ static getDependedPlugins(plugins, dependedPluginNames) {
1500
+ let pluginNames = [];
1501
+ if (typeof dependedPluginNames === "string") {
1502
+ pluginNames = [dependedPluginNames];
1503
+ } else {
1504
+ pluginNames = dependedPluginNames;
1441
1505
  }
1442
- this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1443
- const task = Promise.resolve().then(() => {
1444
- if (typeof hook === "function") {
1445
- const possiblePromiseResult = hook.apply({ ...this.#core.api, plugin }, parameters);
1446
- if (isPromise(possiblePromiseResult)) {
1447
- return Promise.resolve(possiblePromiseResult);
1448
- }
1449
- return possiblePromiseResult;
1506
+ return pluginNames.map((pluginName2) => {
1507
+ const plugin = plugins.find((plugin2) => plugin2.name === pluginName2);
1508
+ if (!plugin) {
1509
+ throw new ValidationPluginError(`This plugin depends on the ${pluginName2} plugin.`);
1450
1510
  }
1451
- return hook;
1452
- }).then((result) => {
1453
- output = result;
1454
- return result;
1455
- }).catch((e) => {
1456
- this.#catcher(e, plugin, hookName);
1457
- return null;
1458
- }).finally(() => {
1459
- this.#addExecutedToCallStack({
1460
- parameters,
1461
- output,
1462
- strategy,
1463
- hookName,
1464
- plugin
1465
- });
1511
+ return plugin;
1466
1512
  });
1467
- return task;
1468
1513
  }
1469
- /**
1470
- * Run a sync plugin hook and return the result.
1471
- * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
1472
- * @param args Arguments passed to the plugin hook.
1473
- * @param plugin The acutal plugin
1474
- * @param replaceContext When passed, the plugin context can be overridden.
1475
- */
1476
- #executeSync({
1477
- strategy,
1478
- hookName,
1479
- parameters,
1480
- plugin
1481
- }) {
1482
- const hook = plugin[hookName];
1483
- let output;
1484
- if (!hook) {
1485
- return null;
1514
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
1515
+ static get hooks() {
1516
+ return ["validate", "buildStart", "resolvePath", "resolveName", "load", "transform", "writeFile", "buildEnd"];
1517
+ }
1518
+ };
1519
+ _core = new WeakMap();
1520
+ _usedPluginNames = new WeakMap();
1521
+ _promiseManager = new WeakMap();
1522
+ _getSortedPlugins = new WeakSet();
1523
+ getSortedPlugins_fn = function(hookName) {
1524
+ const plugins = [...this.plugins].filter((plugin) => plugin.name !== "core");
1525
+ if (hookName) {
1526
+ if (this.logger.logLevel === "info") {
1527
+ const containsHookName = plugins.some((item) => item[hookName]);
1528
+ if (!containsHookName) {
1529
+ this.logger.warn(`No hook ${hookName} found`);
1530
+ }
1486
1531
  }
1487
- this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1488
- try {
1489
- if (typeof hook === "function") {
1490
- const fn = hook.apply(this.#core.api, parameters);
1491
- output = fn;
1492
- return fn;
1532
+ return plugins.filter((item) => item[hookName]);
1533
+ }
1534
+ return plugins;
1535
+ };
1536
+ _addExecutedToCallStack = new WeakSet();
1537
+ addExecutedToCallStack_fn = function(executer) {
1538
+ if (executer) {
1539
+ this.eventEmitter.emit("executed", executer);
1540
+ this.executed.push(executer);
1541
+ }
1542
+ };
1543
+ _execute = new WeakSet();
1544
+ execute_fn = function({
1545
+ strategy,
1546
+ hookName,
1547
+ parameters,
1548
+ plugin
1549
+ }) {
1550
+ const hook = plugin[hookName];
1551
+ let output;
1552
+ if (!hook) {
1553
+ return null;
1554
+ }
1555
+ this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1556
+ const task = Promise.resolve().then(() => {
1557
+ if (typeof hook === "function") {
1558
+ const possiblePromiseResult = hook.apply({ ...__privateGet(this, _core).api, plugin }, parameters);
1559
+ if (isPromise(possiblePromiseResult)) {
1560
+ return Promise.resolve(possiblePromiseResult);
1493
1561
  }
1494
- output = hook;
1495
- return hook;
1496
- } catch (e) {
1497
- this.#catcher(e, plugin, hookName);
1498
- return null;
1499
- } finally {
1500
- this.#addExecutedToCallStack({
1501
- parameters,
1502
- output,
1503
- strategy,
1504
- hookName,
1505
- plugin
1506
- });
1562
+ return possiblePromiseResult;
1507
1563
  }
1564
+ return hook;
1565
+ }).then((result) => {
1566
+ output = result;
1567
+ __privateMethod(this, _addExecutedToCallStack, addExecutedToCallStack_fn).call(this, {
1568
+ parameters,
1569
+ output,
1570
+ strategy,
1571
+ hookName,
1572
+ plugin
1573
+ });
1574
+ return result;
1575
+ }).catch((e) => {
1576
+ __privateMethod(this, _catcher, catcher_fn).call(this, e, plugin, hookName);
1577
+ return null;
1578
+ });
1579
+ return task;
1580
+ };
1581
+ _executeSync = new WeakSet();
1582
+ executeSync_fn = function({
1583
+ strategy,
1584
+ hookName,
1585
+ parameters,
1586
+ plugin
1587
+ }) {
1588
+ const hook = plugin[hookName];
1589
+ let output;
1590
+ if (!hook) {
1591
+ return null;
1508
1592
  }
1509
- #catcher(e, plugin, hookName) {
1510
- const text = `${e.message} (plugin: ${plugin.name}, hook: ${hookName})
1511
- `;
1512
- const pluginError = new PluginError(text, { cause: e, pluginManager: this });
1513
- this.eventEmitter.emit("error", pluginError);
1514
- throw pluginError;
1593
+ this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1594
+ try {
1595
+ if (typeof hook === "function") {
1596
+ const fn = hook.apply({ ...__privateGet(this, _core).api, plugin }, parameters);
1597
+ output = fn;
1598
+ return fn;
1599
+ }
1600
+ output = hook;
1601
+ __privateMethod(this, _addExecutedToCallStack, addExecutedToCallStack_fn).call(this, {
1602
+ parameters,
1603
+ output,
1604
+ strategy,
1605
+ hookName,
1606
+ plugin
1607
+ });
1608
+ return hook;
1609
+ } catch (e) {
1610
+ __privateMethod(this, _catcher, catcher_fn).call(this, e, plugin, hookName);
1611
+ return null;
1515
1612
  }
1516
1613
  };
1517
- function noReturn() {
1518
- }
1519
-
1520
- // src/managers/pluginManager/validate.ts
1521
- var ValidationPluginError = class extends Error {
1614
+ _catcher = new WeakSet();
1615
+ catcher_fn = function(e, plugin, hookName) {
1616
+ const text = `${e.message} (plugin: ${plugin?.name || "unknown"}, hook: ${hookName || "unknown"})
1617
+ `;
1618
+ this.logger.error(text);
1619
+ this.eventEmitter.emit("error", e);
1522
1620
  };
1523
- function getDependedPlugins(plugins, dependedPluginNames) {
1524
- let pluginNames = [];
1525
- if (typeof dependedPluginNames === "string") {
1526
- pluginNames = [dependedPluginNames];
1527
- } else {
1528
- pluginNames = dependedPluginNames;
1529
- }
1530
- return pluginNames.map((pluginName2) => {
1531
- const plugin = plugins.find((plugin2) => plugin2.name === pluginName2);
1532
- if (!plugin) {
1533
- throw new ValidationPluginError(`This plugin depends on the ${pluginName2} plugin.`);
1534
- }
1535
- return plugin;
1536
- });
1537
- }
1538
-
1539
- // src/types.ts
1540
- var LogLevel = {
1541
- silent: "silent",
1542
- info: "info",
1543
- debug: "debug"
1621
+ _parse = new WeakSet();
1622
+ parse_fn = function(plugin, pluginManager, context) {
1623
+ const usedPluginNames = __privateGet(pluginManager, _usedPluginNames);
1624
+ setUniqueName(plugin.name, usedPluginNames);
1625
+ const key = plugin.key || [plugin.kind, plugin.name, usedPluginNames[plugin.name]].filter(Boolean);
1626
+ if (plugin.name !== "core" && usedPluginNames[plugin.name] >= 2) {
1627
+ pluginManager.logger.warn("Using multiple of the same plugin is an experimental feature");
1628
+ }
1629
+ if (!plugin.transform) {
1630
+ plugin.transform = function transform(code) {
1631
+ return code;
1632
+ };
1633
+ }
1634
+ if (plugin.api && typeof plugin.api === "function") {
1635
+ const api = plugin.api.call(context);
1636
+ return {
1637
+ ...plugin,
1638
+ key,
1639
+ api
1640
+ };
1641
+ }
1642
+ return {
1643
+ ...plugin,
1644
+ key
1645
+ };
1544
1646
  };
1545
1647
 
1546
1648
  // src/build.ts
1547
1649
  async function transformReducer(_previousCode, result, _plugin) {
1548
1650
  return result;
1549
1651
  }
1550
- async function build(options) {
1551
- const { config, logLevel, logger = createLogger() } = options;
1652
+ async function setup(options) {
1653
+ const { config, logger = createLogger({ logLevel: LogLevel.silent }) } = options;
1552
1654
  try {
1553
- if ("path" in config.input && !new URLPath(config.input.path).isURL) {
1655
+ if (isInputPath(config) && !new URLPath(config.input.path).isURL) {
1554
1656
  await read(config.input.path);
1555
1657
  }
1556
1658
  } catch (e) {
1557
- if ("path" in config.input) {
1659
+ if (isInputPath(config)) {
1558
1660
  throw new Error(
1559
1661
  "Cannot read file/URL defined in `input.path` or set with `kubb generate PATH` in the CLI of your Kubb config " + pc3.dim(config.input.path),
1560
1662
  {
@@ -1567,11 +1669,11 @@ async function build(options) {
1567
1669
  await clean(config.output.path);
1568
1670
  }
1569
1671
  const queueTask = async (file) => {
1570
- const { path } = file;
1571
- let code = createFileSource(file);
1672
+ const { path: path3 } = file;
1673
+ let code = FileManager.getSource(file);
1572
1674
  const { result: loadedResult } = await pluginManager.hookFirst({
1573
1675
  hookName: "load",
1574
- parameters: [path]
1676
+ parameters: [path3]
1575
1677
  });
1576
1678
  if (loadedResult && isPromise(loadedResult)) {
1577
1679
  code = await loadedResult;
@@ -1582,28 +1684,52 @@ async function build(options) {
1582
1684
  if (code) {
1583
1685
  const transformedCode = await pluginManager.hookReduceArg0({
1584
1686
  hookName: "transform",
1585
- parameters: [code, path],
1687
+ parameters: [code, path3],
1586
1688
  reduce: transformReducer
1587
1689
  });
1588
1690
  if (config.output.write || config.output.write === void 0) {
1589
- await pluginManager.hookParallel({
1691
+ if (file.meta?.pluginKey) {
1692
+ return pluginManager.hookForPlugin({
1693
+ pluginKey: file.meta?.pluginKey,
1694
+ hookName: "writeFile",
1695
+ parameters: [transformedCode, path3]
1696
+ });
1697
+ }
1698
+ return pluginManager.hookFirst({
1590
1699
  hookName: "writeFile",
1591
- parameters: [transformedCode, path]
1700
+ parameters: [transformedCode, path3]
1592
1701
  });
1593
1702
  }
1594
1703
  }
1595
1704
  };
1596
- const pluginManager = new PluginManager(config, { debug: logLevel === LogLevel.debug, logger, task: queueTask });
1597
- const { plugins, fileManager } = pluginManager;
1705
+ const pluginManager = new PluginManager(config, { logger, task: queueTask, writeTimeout: 0 });
1598
1706
  pluginManager.on("execute", (executer) => {
1707
+ const { hookName, parameters, plugin } = executer;
1708
+ if (hookName === "writeFile" && logger.spinner) {
1709
+ const [code] = parameters;
1710
+ if (logger.logLevel === LogLevel.info) {
1711
+ logger.spinner.start(`\u{1F4BE} Writing`);
1712
+ }
1713
+ if (logger.logLevel === "debug") {
1714
+ logger.info(`PluginKey ${pc3.dim(JSON.stringify(plugin.key))}
1715
+ with source
1716
+
1717
+ ${code}`);
1718
+ }
1719
+ }
1720
+ });
1721
+ pluginManager.on("executed", (executer) => {
1599
1722
  const { hookName, plugin, output, parameters } = executer;
1600
1723
  const messsage = `${randomPicoColour(plugin.name)} Executing ${hookName}`;
1601
- if (logLevel === LogLevel.info) {
1602
- if (logger.spinner) {
1724
+ if (logger.logLevel === LogLevel.info && logger.spinner) {
1725
+ if (hookName === "writeFile") {
1726
+ const [_code, path3] = parameters;
1727
+ logger.spinner.suffixText = pc3.dim(path3);
1728
+ } else {
1603
1729
  logger.spinner.suffixText = messsage;
1604
1730
  }
1605
1731
  }
1606
- if (logLevel === LogLevel.debug) {
1732
+ if (logger.logLevel === LogLevel.debug) {
1607
1733
  logger.info(messsage);
1608
1734
  const logs = [
1609
1735
  parameters && `${pc3.bgWhite(`Parameters`)} ${randomPicoColour(plugin.name)} ${hookName}`,
@@ -1614,83 +1740,109 @@ async function build(options) {
1614
1740
  console.log(logs.join("\n"));
1615
1741
  }
1616
1742
  });
1743
+ return pluginManager;
1744
+ }
1745
+ async function build(options) {
1746
+ const pluginManager = await setup(options);
1747
+ const { fileManager, logger } = pluginManager;
1617
1748
  await pluginManager.hookParallel({
1618
1749
  hookName: "validate",
1619
- parameters: [plugins]
1750
+ parameters: [pluginManager.plugins]
1620
1751
  });
1621
1752
  await pluginManager.hookParallel({
1622
1753
  hookName: "buildStart",
1623
- parameters: [config]
1754
+ parameters: [options.config]
1624
1755
  });
1625
1756
  await pluginManager.hookParallel({ hookName: "buildEnd" });
1626
- return { files: fileManager.files.map((file) => ({ ...file, source: createFileSource(file) })), pluginManager };
1757
+ if (!fileManager.isExecuting && logger.spinner) {
1758
+ logger.spinner.suffixText = "";
1759
+ logger.spinner.succeed(`\u{1F4BE} Writing completed`);
1760
+ }
1761
+ return { files: fileManager.files.map((file) => ({ ...file, source: FileManager.getSource(file) })), pluginManager };
1627
1762
  }
1628
-
1629
- // src/config.ts
1630
- function defineConfig(options) {
1631
- return options;
1763
+ async function safeBuild(options) {
1764
+ const pluginManager = await setup(options);
1765
+ const { fileManager, logger } = pluginManager;
1766
+ try {
1767
+ await pluginManager.hookParallel({
1768
+ hookName: "validate",
1769
+ parameters: [pluginManager.plugins]
1770
+ });
1771
+ await pluginManager.hookParallel({
1772
+ hookName: "buildStart",
1773
+ parameters: [options.config]
1774
+ });
1775
+ await pluginManager.hookParallel({ hookName: "buildEnd" });
1776
+ if (!fileManager.isExecuting && logger.spinner) {
1777
+ logger.spinner.suffixText = "";
1778
+ logger.spinner.succeed(`\u{1F4BE} Writing completed`);
1779
+ }
1780
+ } catch (e) {
1781
+ return { files: fileManager.files.map((file) => ({ ...file, source: FileManager.getSource(file) })), pluginManager, error: e };
1782
+ }
1783
+ return { files: fileManager.files.map((file) => ({ ...file, source: FileManager.getSource(file) })), pluginManager };
1632
1784
  }
1633
1785
 
1634
- // src/generators/Generator.ts
1786
+ // src/Generator.ts
1787
+ var _options3, _context;
1635
1788
  var Generator = class {
1636
- #options = {};
1637
- #context = {};
1638
1789
  constructor(options, context) {
1790
+ __privateAdd(this, _options3, {});
1791
+ __privateAdd(this, _context, {});
1639
1792
  if (context) {
1640
- this.#context = context;
1793
+ __privateSet(this, _context, context);
1641
1794
  }
1642
1795
  if (options) {
1643
- this.#options = options;
1796
+ __privateSet(this, _options3, options);
1644
1797
  }
1645
1798
  return this;
1646
1799
  }
1647
1800
  get options() {
1648
- return this.#options;
1801
+ return __privateGet(this, _options3);
1649
1802
  }
1650
1803
  get context() {
1651
- return this.#context;
1804
+ return __privateGet(this, _context);
1652
1805
  }
1653
1806
  set options(options) {
1654
- this.#options = { ...this.#options, ...options };
1807
+ __privateSet(this, _options3, { ...__privateGet(this, _options3), ...options });
1655
1808
  }
1656
1809
  };
1657
-
1658
- // src/generators/SchemaGenerator.ts
1659
- var SchemaGenerator = class extends Generator {
1660
- };
1661
- var PackageManager = class _PackageManager {
1662
- static #cache = {};
1663
- #cwd;
1664
- #SLASHES = /* @__PURE__ */ new Set(["/", "\\"]);
1810
+ _options3 = new WeakMap();
1811
+ _context = new WeakMap();
1812
+ var _cache2, _cwd, _SLASHES, _match, match_fn;
1813
+ var _PackageManager = class _PackageManager {
1665
1814
  constructor(workspace) {
1815
+ __privateAdd(this, _match);
1816
+ __privateAdd(this, _cwd, void 0);
1817
+ __privateAdd(this, _SLASHES, /* @__PURE__ */ new Set(["/", "\\"]));
1666
1818
  if (workspace) {
1667
- this.#cwd = workspace;
1819
+ __privateSet(this, _cwd, workspace);
1668
1820
  }
1669
1821
  return this;
1670
1822
  }
1671
1823
  set workspace(workspace) {
1672
- this.#cwd = workspace;
1824
+ __privateSet(this, _cwd, workspace);
1673
1825
  }
1674
1826
  get workspace() {
1675
- return this.#cwd;
1827
+ return __privateGet(this, _cwd);
1676
1828
  }
1677
1829
  normalizeDirectory(directory) {
1678
- if (!this.#SLASHES.has(directory[directory.length - 1])) {
1830
+ if (!__privateGet(this, _SLASHES).has(directory[directory.length - 1])) {
1679
1831
  return `${directory}/`;
1680
1832
  }
1681
1833
  return directory;
1682
1834
  }
1683
- getLocation(path) {
1684
- let location = path;
1685
- if (this.#cwd) {
1686
- const require2 = mod.createRequire(this.normalizeDirectory(this.#cwd));
1687
- location = require2.resolve(path);
1835
+ getLocation(path3) {
1836
+ let location = path3;
1837
+ if (__privateGet(this, _cwd)) {
1838
+ const require2 = mod.createRequire(this.normalizeDirectory(__privateGet(this, _cwd)));
1839
+ location = require2.resolve(path3);
1688
1840
  }
1689
1841
  return location;
1690
1842
  }
1691
- async import(path) {
1843
+ async import(path3) {
1692
1844
  try {
1693
- let location = this.getLocation(path);
1845
+ let location = this.getLocation(path3);
1694
1846
  if (os.platform() == "win32") {
1695
1847
  location = pathToFileURL(location).href;
1696
1848
  }
@@ -1703,7 +1855,7 @@ var PackageManager = class _PackageManager {
1703
1855
  }
1704
1856
  async getPackageJSON() {
1705
1857
  const pkgPath = await findUp(["package.json"], {
1706
- cwd: this.#cwd
1858
+ cwd: __privateGet(this, _cwd)
1707
1859
  });
1708
1860
  if (!pkgPath) {
1709
1861
  return void 0;
@@ -1712,7 +1864,7 @@ var PackageManager = class _PackageManager {
1712
1864
  }
1713
1865
  getPackageJSONSync() {
1714
1866
  const pkgPath = findUpSync(["package.json"], {
1715
- cwd: this.#cwd
1867
+ cwd: __privateGet(this, _cwd)
1716
1868
  });
1717
1869
  if (!pkgPath) {
1718
1870
  return void 0;
@@ -1720,33 +1872,36 @@ var PackageManager = class _PackageManager {
1720
1872
  return __require(pkgPath);
1721
1873
  }
1722
1874
  static setVersion(dependency, version) {
1723
- _PackageManager.#cache[dependency] = version;
1875
+ __privateGet(_PackageManager, _cache2)[dependency] = version;
1724
1876
  }
1725
1877
  async getVersion(dependency) {
1726
- if (_PackageManager.#cache[dependency]) {
1727
- return _PackageManager.#cache[dependency];
1878
+ if (typeof dependency === "string" && __privateGet(_PackageManager, _cache2)[dependency]) {
1879
+ return __privateGet(_PackageManager, _cache2)[dependency];
1728
1880
  }
1729
1881
  const packageJSON = await this.getPackageJSON();
1730
1882
  if (!packageJSON) {
1731
1883
  return void 0;
1732
1884
  }
1733
- return packageJSON["dependencies"]?.[dependency] || packageJSON["devDependencies"]?.[dependency];
1885
+ return __privateMethod(this, _match, match_fn).call(this, packageJSON, dependency);
1734
1886
  }
1735
1887
  getVersionSync(dependency) {
1736
- if (_PackageManager.#cache[dependency]) {
1737
- return _PackageManager.#cache[dependency];
1888
+ if (typeof dependency === "string" && __privateGet(_PackageManager, _cache2)[dependency]) {
1889
+ return __privateGet(_PackageManager, _cache2)[dependency];
1738
1890
  }
1739
1891
  const packageJSON = this.getPackageJSONSync();
1740
1892
  if (!packageJSON) {
1741
1893
  return void 0;
1742
1894
  }
1743
- return packageJSON["dependencies"]?.[dependency] || packageJSON["devDependencies"]?.[dependency];
1895
+ return __privateMethod(this, _match, match_fn).call(this, packageJSON, dependency);
1744
1896
  }
1745
1897
  async isValid(dependency, version) {
1746
1898
  const packageVersion = await this.getVersion(dependency);
1747
1899
  if (!packageVersion) {
1748
1900
  return false;
1749
1901
  }
1902
+ if (packageVersion === version) {
1903
+ return true;
1904
+ }
1750
1905
  const semVer = coerce(packageVersion);
1751
1906
  if (!semVer) {
1752
1907
  throw new Error(`${packageVersion} is not valid`);
@@ -1765,10 +1920,31 @@ var PackageManager = class _PackageManager {
1765
1920
  return satisfies(semVer, version);
1766
1921
  }
1767
1922
  };
1923
+ _cache2 = new WeakMap();
1924
+ _cwd = new WeakMap();
1925
+ _SLASHES = new WeakMap();
1926
+ _match = new WeakSet();
1927
+ match_fn = function(packageJSON, dependency) {
1928
+ const dependencies = {
1929
+ ...packageJSON["dependencies"] || {},
1930
+ ...packageJSON["devDependencies"] || {}
1931
+ };
1932
+ if (typeof dependency === "string" && dependencies[dependency]) {
1933
+ return dependencies[dependency];
1934
+ }
1935
+ const matchedDependency = Object.keys(dependencies).find((dep) => dep.match(dependency));
1936
+ return matchedDependency ? dependencies[matchedDependency] : void 0;
1937
+ };
1938
+ __privateAdd(_PackageManager, _cache2, {});
1939
+ var PackageManager = _PackageManager;
1940
+
1941
+ // src/SchemaGenerator.ts
1942
+ var SchemaGenerator = class extends Generator {
1943
+ };
1768
1944
 
1769
1945
  // src/index.ts
1770
1946
  var src_default = build;
1771
1947
 
1772
- export { FileManager, FunctionParams, Generator, LogLevel, PackageManager, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, SummaryError, TreeNode, URLPath, ValidationPluginError, Warning, build, clean, combineCodes, combineExports, combineFiles, combineImports, createFileSource, createJSDocBlockText, createLogger, createPlugin, createPluginCache, src_default as default, defaultColours, defineConfig, escape, extensions, getDependedPlugins, getIndexes, getPathMode, getRelativePath, getUniqueName, hooks, isExtensionAllowed, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, jsStringEscape, pluginName as name, nameSorter, pluginName, randomColour, randomPicoColour, read, readSync, renderTemplate, throttle, timeout, transformReservedWord, uniqueIdFactory, write };
1948
+ export { FileManager, Generator, KubbFile, PackageManager, PluginManager, PromiseManager, SchemaGenerator, ValidationPluginError, Warning, build, combineExports, combineImports, createPlugin, src_default as default, defineConfig, isInputPath, pluginName as name, pluginName, safeBuild };
1773
1949
  //# sourceMappingURL=out.js.map
1774
1950
  //# sourceMappingURL=index.js.map