@kubb/core 1.15.0-canary.20231025T123615 → 1.15.0-canary.20231025T223729

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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
- import path, { resolve, relative, basename, extname, dirname } from 'path';
6
3
  import fs2, { remove } from 'fs-extra';
7
- import { camelCase, camelCaseTransformMerge } from 'change-case';
8
- import { orderBy } from 'natural-orderby';
9
- import { performance } from 'perf_hooks';
10
- import { EventEmitter as EventEmitter$1 } from 'events';
11
4
  import seedrandom from 'seedrandom';
12
5
  import { switcher } from 'js-runtime';
13
- import dirTree from 'directory-tree';
14
- import { createImportDeclaration, createExportDeclaration, print } 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';
15
11
  import isEqual from 'lodash.isequal';
12
+ import { orderBy } from 'natural-orderby';
13
+ import dirTree from 'directory-tree';
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,98 +27,14 @@ 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
30
  async function clean(path3) {
59
31
  return remove(path3);
60
32
  }
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
- }
33
+ var LogLevel = {
34
+ silent: "silent",
35
+ info: "info",
36
+ debug: "debug"
99
37
  };
100
-
101
- // src/utils/isPromise.ts
102
- function isPromise(result) {
103
- return !!result && typeof result?.then === "function";
104
- }
105
- function isPromiseFulfilledResult(result) {
106
- return result.status === "fulfilled";
107
- }
108
- function isPromiseRejectedResult(result) {
109
- return result.status === "rejected";
110
- }
111
-
112
- // src/utils/jsdoc.ts
113
- function createJSDocBlockText({ comments }) {
114
- const filteredComments = comments.filter(Boolean);
115
- if (!filteredComments.length) {
116
- return "";
117
- }
118
- return `/**
119
- * ${filteredComments.join("\n * ")}
120
- */`;
121
- }
122
38
  function createLogger({ logLevel, name, spinner }) {
123
39
  const logs = [];
124
40
  const log = (message) => {
@@ -156,100 +72,6 @@ function createLogger({ logLevel, name, spinner }) {
156
72
  };
157
73
  return logger;
158
74
  }
159
-
160
- // src/utils/nameSorter.ts
161
- function nameSorter(a, b) {
162
- if (a.name < b.name) {
163
- return -1;
164
- }
165
- if (a.name > b.name) {
166
- return 1;
167
- }
168
- return 0;
169
- }
170
- var EventEmitter = class {
171
- constructor() {
172
- this.#emitter.setMaxListeners(100);
173
- }
174
- #emitter = new EventEmitter$1();
175
- emit(eventName, ...eventArg) {
176
- this.#emitter.emit(eventName, ...eventArg);
177
- }
178
- on(eventName, handler) {
179
- this.#emitter.on(eventName, handler);
180
- }
181
- off(eventName, handler) {
182
- this.#emitter.off(eventName, handler);
183
- }
184
- removeAll() {
185
- this.#emitter.removeAllListeners();
186
- }
187
- };
188
-
189
- // src/utils/Queue.ts
190
- var Queue = class {
191
- #queue = [];
192
- eventEmitter = new EventEmitter();
193
- #workerCount = 0;
194
- #maxParallel;
195
- #debug = false;
196
- constructor(maxParallel, debug = false) {
197
- this.#maxParallel = maxParallel;
198
- this.#debug = debug;
199
- }
200
- run(job, options = { controller: new AbortController(), name: crypto.randomUUID(), description: "" }) {
201
- return new Promise((resolve2, reject) => {
202
- const item = { reject, resolve: resolve2, job, name: options.name, description: options.description || options.name };
203
- options.controller?.signal.addEventListener("abort", () => {
204
- this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
205
- reject("Aborted");
206
- });
207
- this.#queue.push(item);
208
- this.#work();
209
- });
210
- }
211
- runSync(job, options = { controller: new AbortController(), name: crypto.randomUUID(), description: "" }) {
212
- new Promise((resolve2, reject) => {
213
- const item = { reject, resolve: resolve2, job, name: options.name, description: options.description || options.name };
214
- options.controller?.signal.addEventListener("abort", () => {
215
- this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
216
- });
217
- this.#queue.push(item);
218
- this.#work();
219
- });
220
- }
221
- get hasJobs() {
222
- return this.#workerCount > 0 || this.#queue.length > 0;
223
- }
224
- get count() {
225
- return this.#workerCount;
226
- }
227
- #work() {
228
- if (this.#workerCount >= this.#maxParallel) {
229
- return;
230
- }
231
- this.#workerCount++;
232
- let entry;
233
- while (entry = this.#queue.shift()) {
234
- const { reject, resolve: resolve2, job, name, description } = entry;
235
- if (this.#debug) {
236
- performance.mark(name + "_start");
237
- }
238
- job().then((result) => {
239
- this.eventEmitter.emit("jobDone", result);
240
- resolve2(result);
241
- if (this.#debug) {
242
- performance.mark(name + "_stop");
243
- performance.measure(description, name + "_start", name + "_stop");
244
- }
245
- }).catch((err) => {
246
- this.eventEmitter.emit("jobFailed", err);
247
- reject(err);
248
- });
249
- }
250
- this.#workerCount--;
251
- }
252
- };
253
75
  var defaultColours = ["black", "blue", "darkBlue", "cyan", "gray", "green", "darkGreen", "magenta", "red", "darkRed", "yellow", "darkYellow"];
254
76
  function randomColour(text, colours = defaultColours) {
255
77
  if (!text) {
@@ -276,24 +98,6 @@ function randomPicoColour(text, colors = defaultColours) {
276
98
  }
277
99
  return formatter(text);
278
100
  }
279
- function slash(path3, platform = "linux") {
280
- const isWindowsPath = /^\\\\\?\\/.test(path3);
281
- if (["linux", "mac"].includes(platform) && !isWindowsPath) {
282
- return path3.replaceAll(/\\/g, "/").replace("../", "").trimEnd();
283
- }
284
- return path3.replaceAll(/\\/g, "/").replace("../", "").trimEnd();
285
- }
286
- function getRelativePath(rootDir, filePath, platform = "linux") {
287
- if (!rootDir || !filePath) {
288
- throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ""} ${filePath || ""}`);
289
- }
290
- const relativePath = relative(rootDir, filePath);
291
- const slashedPath = slash(relativePath, platform);
292
- if (slashedPath.startsWith("../")) {
293
- return slashedPath.replace(basename(slashedPath), basename(slashedPath, extname(filePath)));
294
- }
295
- return `./${slashedPath.replace(basename(slashedPath), basename(slashedPath, extname(filePath)))}`;
296
- }
297
101
  var reader = switcher(
298
102
  {
299
103
  node: async (path3) => {
@@ -306,7 +110,7 @@ var reader = switcher(
306
110
  },
307
111
  "node"
308
112
  );
309
- var syncReader = switcher(
113
+ switcher(
310
114
  {
311
115
  node: (path3) => {
312
116
  return fs2.readFileSync(path3, { encoding: "utf8" });
@@ -320,71 +124,108 @@ var syncReader = switcher(
320
124
  async function read(path3) {
321
125
  return reader(path3);
322
126
  }
323
- function readSync(path3) {
324
- return syncReader(path3);
325
- }
326
-
327
- // src/utils/renderTemplate.ts
328
- function renderTemplate(template, data = void 0) {
329
- if (!data || !Object.keys(data).length) {
330
- return template.replace(/{{(.*?)}}/g, "");
331
- }
332
- const matches = template.match(/{{(.*?)}}/g);
333
- return matches?.reduce((prev, curr) => {
334
- const index = curr.split(/{{|}}/).filter(Boolean)[0]?.trim();
335
- if (index === void 0) {
336
- return prev;
337
- }
338
- const value = data[index];
339
- if (value === void 0) {
340
- return prev;
341
- }
342
- return prev.replace(curr, () => {
343
- if (typeof value === "boolean") {
344
- return `${value.toString()}` || "false";
345
- }
346
- return value || "";
347
- }).trim();
348
- }, template) || "";
349
- }
350
-
351
- // src/utils/SummaryError.ts
352
- var SummaryError = class extends Error {
353
- summary;
354
- constructor(message, options) {
355
- super(message, { cause: options.cause });
356
- this.name = "SummaryError";
357
- this.summary = options.summary || [];
127
+ var URLPath = class {
128
+ path;
129
+ constructor(path3) {
130
+ this.path = path3;
131
+ return this;
358
132
  }
359
- };
360
-
361
- // src/utils/throttle.ts
362
- var throttle = (fn, delay) => {
363
- let wait = false;
364
- let timeout2;
365
- let cancelled = false;
366
- return [
367
- (...args) => {
368
- if (cancelled) {
369
- return void 0;
133
+ /**
134
+ * Convert Swagger path to URLPath(syntax of Express)
135
+ * @example /pet/{petId} => /pet/:petId
136
+ */
137
+ get URL() {
138
+ return this.toURLPath();
139
+ }
140
+ get isURL() {
141
+ try {
142
+ const url = new URL(this.path);
143
+ if (url?.href) {
144
+ return true;
370
145
  }
371
- if (wait) {
372
- return void 0;
146
+ } catch (error) {
147
+ return false;
148
+ }
149
+ return false;
150
+ }
151
+ /**
152
+ * Convert Swagger path to template literals/ template strings(camelcase)
153
+ * @example /pet/{petId} => `/pet/${petId}`
154
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
155
+ * @example /account/userID => `/account/${userId}`
156
+ */
157
+ get template() {
158
+ return this.toTemplateString();
159
+ }
160
+ get object() {
161
+ return this.toObject();
162
+ }
163
+ get params() {
164
+ return this.getParams();
165
+ }
166
+ toObject({ type = "path", replacer, stringify } = {}) {
167
+ const object = {
168
+ url: type === "path" ? this.toURLPath() : this.toTemplateString(replacer),
169
+ params: this.getParams()
170
+ };
171
+ if (stringify) {
172
+ if (type !== "template") {
173
+ throw new Error("Type should be `template` when using stringiyf");
373
174
  }
374
- const val = fn(...args);
375
- wait = true;
376
- timeout2 = setTimeout(() => {
377
- wait = false;
378
- }, delay);
379
- return val;
380
- },
381
- () => {
382
- cancelled = true;
383
- clearTimeout(timeout2);
175
+ return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
384
176
  }
385
- ];
177
+ return object;
178
+ }
179
+ /**
180
+ * Convert Swagger path to template literals/ template strings(camelcase)
181
+ * @example /pet/{petId} => `/pet/${petId}`
182
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
183
+ * @example /account/userID => `/account/${userId}`
184
+ */
185
+ toTemplateString(replacer) {
186
+ const regex = /{(\w|-)*}/g;
187
+ const found = this.path.match(regex);
188
+ let newPath = this.path.replaceAll("{", "${");
189
+ if (found) {
190
+ newPath = found.reduce((prev, curr) => {
191
+ const pathParam = replacer ? replacer(camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge })) : camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge });
192
+ const replacement = `\${${pathParam}}`;
193
+ return prev.replace(curr, replacement);
194
+ }, this.path);
195
+ }
196
+ return `\`${newPath}\``;
197
+ }
198
+ getParams(replacer) {
199
+ const regex = /{(\w|-)*}/g;
200
+ const found = this.path.match(regex);
201
+ if (!found) {
202
+ return void 0;
203
+ }
204
+ const params = {};
205
+ found.forEach((item) => {
206
+ item = item.replaceAll("{", "").replaceAll("}", "");
207
+ const pathParam = replacer ? replacer(camelCase(item, { delimiter: "", transform: camelCaseTransformMerge })) : camelCase(item, { delimiter: "", transform: camelCaseTransformMerge });
208
+ params[pathParam] = pathParam;
209
+ }, this.path);
210
+ return params;
211
+ }
212
+ /**
213
+ * Convert Swagger path to URLPath(syntax of Express)
214
+ * @example /pet/{petId} => /pet/:petId
215
+ */
216
+ toURLPath() {
217
+ return this.path.replaceAll("{", ":").replaceAll("}", "");
218
+ }
386
219
  };
387
220
 
221
+ // src/config.ts
222
+ function defineConfig(options) {
223
+ return options;
224
+ }
225
+ function isInputPath(result) {
226
+ return !!result && "path" in result;
227
+ }
228
+
388
229
  // src/utils/timeout.ts
389
230
  async function timeout(ms) {
390
231
  return new Promise((resolve2) => {
@@ -399,6 +240,17 @@ function combineCodes(codes) {
399
240
  return codes.join("\n");
400
241
  }
401
242
 
243
+ // src/utils/transformers/createJSDocBlockText.ts
244
+ function createJSDocBlockText({ comments }) {
245
+ const filteredComments = comments.filter(Boolean);
246
+ if (!filteredComments.length) {
247
+ return "";
248
+ }
249
+ return `/**
250
+ * ${filteredComments.join("\n * ")}
251
+ */`;
252
+ }
253
+
402
254
  // src/utils/transformers/escape.ts
403
255
  function escape(text) {
404
256
  return text ? text.replaceAll("`", "\\`") : "";
@@ -424,9 +276,37 @@ function jsStringEscape(input) {
424
276
  });
425
277
  }
426
278
 
427
- // src/utils/transformers/indent.ts
428
- function createIndent(size) {
429
- return Array.from({ length: size + 1 }).join(" ");
279
+ // src/utils/transformers/indent.ts
280
+ function createIndent(size) {
281
+ return Array.from({ length: size + 1 }).join(" ");
282
+ }
283
+
284
+ // src/utils/transformers/nameSorter.ts
285
+ function nameSorter(a, b) {
286
+ if (a.name < b.name) {
287
+ return -1;
288
+ }
289
+ if (a.name > b.name) {
290
+ return 1;
291
+ }
292
+ return 0;
293
+ }
294
+
295
+ // src/utils/transformers/searchAndReplace.ts
296
+ function searchAndReplace(options) {
297
+ const { text, replaceBy, prefix = "", key } = options;
298
+ const searchValues = options.searchValues?.(prefix, key) || [
299
+ `${prefix}["${key}"]`,
300
+ `${prefix}['${key}']`,
301
+ `${prefix}[\`${key}\`]`,
302
+ `${prefix}"${key}"`,
303
+ `${prefix}'${key}'`,
304
+ `${prefix}\`${key}\``,
305
+ new RegExp(`${prefix}${key}`, "g")
306
+ ];
307
+ return searchValues.reduce((prev, searchValue) => {
308
+ return prev.toString().replaceAll(searchValue, replaceBy);
309
+ }, text);
430
310
  }
431
311
 
432
312
  // src/utils/transformers/transformReservedWord.ts
@@ -528,8 +408,73 @@ var transformers = {
528
408
  escape,
529
409
  jsStringEscape,
530
410
  createIndent,
531
- transformReservedWord
411
+ transformReservedWord,
412
+ nameSorter,
413
+ searchAndReplace,
414
+ JSDoc: {
415
+ createJSDocBlockText
416
+ }
532
417
  };
418
+ async function saveCreateDirectory(path3) {
419
+ const passedPath = dirname(resolve(path3));
420
+ await fs2.mkdir(passedPath, { recursive: true });
421
+ }
422
+ var writer = switcher(
423
+ {
424
+ node: async (path3, data) => {
425
+ try {
426
+ await fs2.stat(resolve(path3));
427
+ const oldContent = await fs2.readFile(resolve(path3), { encoding: "utf-8" });
428
+ if (oldContent?.toString() === data?.toString()) {
429
+ return;
430
+ }
431
+ } catch (_err) {
432
+ }
433
+ await saveCreateDirectory(path3);
434
+ await fs2.writeFile(resolve(path3), data, { encoding: "utf-8" });
435
+ const savedData = await fs2.readFile(resolve(path3), { encoding: "utf-8" });
436
+ if (savedData?.toString() !== data?.toString()) {
437
+ throw new Error(`Sanity check failed for ${path3}
438
+
439
+ Data[${data.length}]:
440
+ ${data}
441
+
442
+ Saved[${savedData.length}]:
443
+ ${savedData}
444
+ `);
445
+ }
446
+ return savedData;
447
+ },
448
+ bun: async (path3, data) => {
449
+ try {
450
+ await saveCreateDirectory(path3);
451
+ await Bun.write(resolve(path3), data);
452
+ const file = Bun.file(resolve(path3));
453
+ const savedData = await file.text();
454
+ if (savedData?.toString() !== data?.toString()) {
455
+ throw new Error(`Sanity check failed for ${path3}
456
+
457
+ Data[${data.length}]:
458
+ ${data}
459
+
460
+ Saved[${savedData.length}]:
461
+ ${savedData}
462
+ `);
463
+ }
464
+ return savedData;
465
+ } catch (e) {
466
+ console.log(e, resolve(path3));
467
+ }
468
+ }
469
+ },
470
+ "node"
471
+ );
472
+ async function write(data, path3) {
473
+ if (data.trim() === "") {
474
+ return void 0;
475
+ }
476
+ return writer(path3, data.trim());
477
+ }
533
478
  var TreeNode = class _TreeNode {
534
479
  data;
535
480
  parent;
@@ -607,249 +552,56 @@ var TreeNode = class _TreeNode {
607
552
  if (item.children?.length) {
608
553
  item.children?.forEach((child) => {
609
554
  recurse(subNode, child);
610
- });
611
- }
612
- };
613
- filteredTree.children?.forEach((child) => recurse(treeNode, child));
614
- return treeNode;
615
- } catch (e) {
616
- throw new Error("Something went wrong with creating index files with the TreehNode class", { cause: e });
617
- }
618
- }
619
- };
620
-
621
- // src/utils/uniqueIdFactory.ts
622
- var uniqueIdFactory = (counter) => (str = "") => `${str}${++counter}`;
623
-
624
- // src/utils/uniqueName.ts
625
- function getUniqueName(originalName, data) {
626
- let used = data[originalName] || 0;
627
- if (used) {
628
- data[originalName] = ++used;
629
- originalName += used;
630
- }
631
- data[originalName] = 1;
632
- return originalName;
633
- }
634
- function setUniqueName(originalName, data) {
635
- let used = data[originalName] || 0;
636
- if (used) {
637
- data[originalName] = ++used;
638
- return originalName;
639
- }
640
- data[originalName] = 1;
641
- return originalName;
642
- }
643
- var URLPath = class {
644
- path;
645
- constructor(path3) {
646
- this.path = path3;
647
- return this;
648
- }
649
- /**
650
- * Convert Swagger path to URLPath(syntax of Express)
651
- * @example /pet/{petId} => /pet/:petId
652
- */
653
- get URL() {
654
- return this.toURLPath();
655
- }
656
- get isURL() {
657
- try {
658
- const url = new URL(this.path);
659
- if (url?.href) {
660
- return true;
661
- }
662
- } catch (error) {
663
- return false;
664
- }
665
- return false;
666
- }
667
- /**
668
- * Convert Swagger path to template literals/ template strings(camelcase)
669
- * @example /pet/{petId} => `/pet/${petId}`
670
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
671
- * @example /account/userID => `/account/${userId}`
672
- */
673
- get template() {
674
- return this.toTemplateString();
675
- }
676
- get object() {
677
- return this.toObject();
678
- }
679
- get params() {
680
- return this.getParams();
681
- }
682
- toObject({ type = "path", replacer, stringify } = {}) {
683
- const object = {
684
- url: type === "path" ? this.toURLPath() : this.toTemplateString(replacer),
685
- params: this.getParams()
686
- };
687
- if (stringify) {
688
- if (type !== "template") {
689
- throw new Error("Type should be `template` when using stringiyf");
690
- }
691
- return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
692
- }
693
- return object;
694
- }
695
- /**
696
- * Convert Swagger path to template literals/ template strings(camelcase)
697
- * @example /pet/{petId} => `/pet/${petId}`
698
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
699
- * @example /account/userID => `/account/${userId}`
700
- */
701
- toTemplateString(replacer) {
702
- const regex = /{(\w|-)*}/g;
703
- const found = this.path.match(regex);
704
- let newPath = this.path.replaceAll("{", "${");
705
- if (found) {
706
- newPath = found.reduce((prev, curr) => {
707
- const pathParam = replacer ? replacer(camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge })) : camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge });
708
- const replacement = `\${${pathParam}}`;
709
- return prev.replace(curr, replacement);
710
- }, this.path);
711
- }
712
- return `\`${newPath}\``;
713
- }
714
- getParams(replacer) {
715
- const regex = /{(\w|-)*}/g;
716
- const found = this.path.match(regex);
717
- if (!found) {
718
- return void 0;
719
- }
720
- const params = {};
721
- found.forEach((item) => {
722
- item = item.replaceAll("{", "").replaceAll("}", "");
723
- const pathParam = replacer ? replacer(camelCase(item, { delimiter: "", transform: camelCaseTransformMerge })) : camelCase(item, { delimiter: "", transform: camelCaseTransformMerge });
724
- params[pathParam] = pathParam;
725
- }, this.path);
726
- return params;
727
- }
728
- /**
729
- * Convert Swagger path to URLPath(syntax of Express)
730
- * @example /pet/{petId} => /pet/:petId
731
- */
732
- toURLPath() {
733
- return this.path.replaceAll("{", ":").replaceAll("}", "");
734
- }
735
- };
736
-
737
- // src/utils/Warning.ts
738
- var Warning = class extends Error {
739
- constructor(message, options) {
740
- super(message, { cause: options?.cause });
741
- this.name = "Warning";
742
- }
743
- };
744
- async function saveCreateDirectory(path3) {
745
- const passedPath = dirname(resolve(path3));
746
- await fs2.mkdir(passedPath, { recursive: true });
747
- }
748
- var writer = switcher(
749
- {
750
- node: async (path3, data) => {
751
- try {
752
- await fs2.stat(resolve(path3));
753
- const oldContent = await fs2.readFile(resolve(path3), { encoding: "utf-8" });
754
- if (oldContent?.toString() === data?.toString()) {
755
- return;
756
- }
757
- } catch (_err) {
758
- }
759
- await saveCreateDirectory(path3);
760
- await fs2.writeFile(resolve(path3), data, { encoding: "utf-8" });
761
- const savedData = await fs2.readFile(resolve(path3), { encoding: "utf-8" });
762
- if (savedData?.toString() !== data?.toString()) {
763
- throw new Error(`Sanity check failed for ${path3}
764
-
765
- Data[${data.length}]:
766
- ${data}
767
-
768
- Saved[${savedData.length}]:
769
- ${savedData}
770
- `);
771
- }
772
- return savedData;
773
- },
774
- bun: async (path3, data) => {
775
- try {
776
- await saveCreateDirectory(path3);
777
- await Bun.write(resolve(path3), data);
778
- const file = Bun.file(resolve(path3));
779
- const savedData = await file.text();
780
- if (savedData?.toString() !== data?.toString()) {
781
- throw new Error(`Sanity check failed for ${path3}
782
-
783
- Data[${data.length}]:
784
- ${data}
785
-
786
- Saved[${savedData.length}]:
787
- ${savedData}
788
- `);
555
+ });
789
556
  }
790
- return savedData;
791
- } catch (e) {
792
- console.log(e, resolve(path3));
793
- }
557
+ };
558
+ filteredTree.children?.forEach((child) => recurse(treeNode, child));
559
+ return treeNode;
560
+ } catch (e) {
561
+ throw new Error("Something went wrong with creating index files with the TreehNode class", { cause: e });
794
562
  }
795
- },
796
- "node"
797
- );
798
- async function write(data, path3) {
799
- if (data.trim() === "") {
800
- return void 0;
801
563
  }
802
- return writer(path3, data.trim());
803
- }
804
- function getIndexes(root, extName, { treeNode = {}, isTypeOnly, filter, map, output, includeExt } = {}) {
805
- const extMapper = {
806
- ".ts": {
807
- extensions: /\.ts/,
808
- exclude: [/schemas/, /json/]
809
- },
810
- ".json": {
811
- extensions: /\.json/,
812
- exclude: []
813
- }
814
- };
815
- const tree = TreeNode.build(root, { ...extMapper[extName] || {}, ...treeNode });
816
- if (!tree) {
817
- return null;
564
+ };
565
+
566
+ // src/BarrelManager.ts
567
+ var BarrelManager = class {
568
+ #options = {};
569
+ constructor(options = {}) {
570
+ this.#options = options;
571
+ return this;
818
572
  }
819
- const fileReducer = (files2, currentTree) => {
820
- if (!currentTree.children) {
821
- return [];
573
+ getIndexes(root, extName) {
574
+ const { treeNode = {}, isTypeOnly, filter, map, output, includeExt } = this.#options;
575
+ const extMapper = {
576
+ ".ts": {
577
+ extensions: /\.ts/,
578
+ exclude: [/schemas/, /json/]
579
+ },
580
+ ".json": {
581
+ extensions: /\.json/,
582
+ exclude: []
583
+ }
584
+ };
585
+ const tree = TreeNode.build(root, { ...extMapper[extName] || {}, ...treeNode });
586
+ if (!tree) {
587
+ return null;
822
588
  }
823
- if (currentTree.children?.length > 1) {
824
- const indexPath = path.resolve(currentTree.data.path, "index.ts");
825
- const exports = currentTree.children.filter(Boolean).map((file) => {
826
- const importPath = file.data.type === "directory" ? `./${file.data.name}` : `./${file.data.name.replace(/\.[^.]*$/, "")}`;
827
- if (importPath.includes("index") && indexPath.includes("index")) {
828
- return void 0;
829
- }
830
- return {
831
- path: includeExt ? file.data.type === "directory" ? `${importPath}/index${extName}` : `${importPath}${extName}` : importPath,
832
- isTypeOnly
833
- };
834
- }).filter(Boolean);
835
- files2.push({
836
- path: indexPath,
837
- baseName: "index.ts",
838
- source: "",
839
- exports: output ? exports?.filter((item) => {
840
- return item.path.endsWith(output.replace(/\.[^.]*$/, ""));
841
- }) : exports
842
- });
843
- } else {
844
- currentTree.children?.forEach((child) => {
589
+ const fileReducer = (files2, currentTree) => {
590
+ if (!currentTree.children) {
591
+ return [];
592
+ }
593
+ if (currentTree.children?.length > 1) {
845
594
  const indexPath = path.resolve(currentTree.data.path, "index.ts");
846
- const importPath = child.data.type === "directory" ? `./${child.data.name}` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
847
- const exports = [
848
- {
849
- path: includeExt ? child.data.type === "directory" ? `${importPath}/index${extName}` : `${importPath}${extName}` : importPath,
850
- isTypeOnly
595
+ const exports = currentTree.children.filter(Boolean).map((file) => {
596
+ const importPath = file.data.type === "directory" ? `./${file.data.name}` : `./${file.data.name.replace(/\.[^.]*$/, "")}`;
597
+ if (importPath.includes("index") && indexPath.includes("index")) {
598
+ return void 0;
851
599
  }
852
- ];
600
+ return {
601
+ path: includeExt ? file.data.type === "directory" ? `${importPath}/index${extName}` : `${importPath}${extName}` : importPath,
602
+ isTypeOnly
603
+ };
604
+ }).filter(Boolean);
853
605
  files2.push({
854
606
  path: indexPath,
855
607
  baseName: "index.ts",
@@ -858,42 +610,216 @@ function getIndexes(root, extName, { treeNode = {}, isTypeOnly, filter, map, out
858
610
  return item.path.endsWith(output.replace(/\.[^.]*$/, ""));
859
611
  }) : exports
860
612
  });
613
+ } else {
614
+ currentTree.children?.forEach((child) => {
615
+ const indexPath = path.resolve(currentTree.data.path, "index.ts");
616
+ const importPath = child.data.type === "directory" ? `./${child.data.name}` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
617
+ const exports = [
618
+ {
619
+ path: includeExt ? child.data.type === "directory" ? `${importPath}/index${extName}` : `${importPath}${extName}` : importPath,
620
+ isTypeOnly
621
+ }
622
+ ];
623
+ files2.push({
624
+ path: indexPath,
625
+ baseName: "index.ts",
626
+ source: "",
627
+ exports: output ? exports?.filter((item) => {
628
+ return item.path.endsWith(output.replace(/\.[^.]*$/, ""));
629
+ }) : exports
630
+ });
631
+ });
632
+ }
633
+ currentTree.children.forEach((childItem) => {
634
+ fileReducer(files2, childItem);
635
+ });
636
+ return files2;
637
+ };
638
+ const files = fileReducer([], tree).reverse();
639
+ const filteredFiles = filter ? files.filter(filter) : files;
640
+ return map ? filteredFiles.map(map) : filteredFiles;
641
+ }
642
+ };
643
+
644
+ // src/FileManager.ts
645
+ var FileManager = class _FileManager {
646
+ #cache = /* @__PURE__ */ new Map();
647
+ #task;
648
+ #isWriting = false;
649
+ /**
650
+ * Timeout between writes
651
+ */
652
+ #timeout = 0;
653
+ #queue;
654
+ constructor(options) {
655
+ if (options) {
656
+ this.#task = options.task;
657
+ this.#queue = options.queue;
658
+ this.#timeout = options.timeout || 0;
659
+ }
660
+ return this;
661
+ }
662
+ get files() {
663
+ const files = [];
664
+ this.#cache.forEach((item) => {
665
+ files.push(...item.flat(1));
666
+ });
667
+ return files;
668
+ }
669
+ get isExecuting() {
670
+ return this.#queue?.hasJobs ?? this.#isWriting ?? false;
671
+ }
672
+ #validate(file) {
673
+ if (!file.validate) {
674
+ return;
675
+ }
676
+ if (!file.path.toLowerCase().endsWith(file.baseName.toLowerCase())) {
677
+ throw new Error(`${file.path} should end with the baseName ${file.baseName}`);
678
+ }
679
+ }
680
+ async add(...files) {
681
+ const promises = files.map((file) => {
682
+ this.#validate(file);
683
+ if (file.override) {
684
+ return this.#add(file);
685
+ }
686
+ return this.#addOrAppend(file);
687
+ });
688
+ const resolvedFiles = await Promise.all(promises);
689
+ if (files.length > 1) {
690
+ return resolvedFiles;
691
+ }
692
+ return resolvedFiles[0];
693
+ }
694
+ async #add(file) {
695
+ const controller = new AbortController();
696
+ const resolvedFile = { id: crypto2.randomUUID(), ...file };
697
+ this.#cache.set(resolvedFile.path, [{ cancel: () => controller.abort(), ...resolvedFile }]);
698
+ if (this.#queue) {
699
+ await this.#queue.run(
700
+ async () => {
701
+ return this.#task?.(resolvedFile);
702
+ },
703
+ { controller }
704
+ );
705
+ }
706
+ return resolvedFile;
707
+ }
708
+ async #addOrAppend(file) {
709
+ const previousCaches = this.#cache.get(file.path);
710
+ const previousCache = previousCaches ? previousCaches.at(previousCaches.length - 1) : void 0;
711
+ if (previousCache) {
712
+ this.#cache.delete(previousCache.path);
713
+ return this.#add({
714
+ ...file,
715
+ source: previousCache.source && file.source ? `${previousCache.source}
716
+ ${file.source}` : "",
717
+ imports: [...previousCache.imports || [], ...file.imports || []],
718
+ exports: [...previousCache.exports || [], ...file.exports || []],
719
+ env: { ...previousCache.env || {}, ...file.env || {} }
861
720
  });
862
721
  }
863
- currentTree.children.forEach((childItem) => {
864
- fileReducer(files2, childItem);
722
+ return this.#add(file);
723
+ }
724
+ async addIndexes({ root, extName = ".ts", meta, options = {} }) {
725
+ const barrelManager = new BarrelManager(options);
726
+ const files = barrelManager.getIndexes(root, extName);
727
+ if (!files) {
728
+ return void 0;
729
+ }
730
+ return await Promise.all(
731
+ files.map((file) => {
732
+ return this.#addOrAppend({
733
+ ...file,
734
+ meta: meta ? meta : file.meta
735
+ });
736
+ })
737
+ );
738
+ }
739
+ getCacheByUUID(UUID) {
740
+ let cache;
741
+ this.#cache.forEach((files) => {
742
+ cache = files.find((item) => item.id === UUID);
865
743
  });
866
- return files2;
867
- };
868
- const files = fileReducer([], tree).reverse();
869
- const filteredFiles = filter ? files.filter(filter) : files;
870
- return map ? filteredFiles.map(map) : filteredFiles;
871
- }
872
- function combineFiles(files) {
873
- return files.filter(Boolean).reduce((acc, curr) => {
874
- const prevIndex = acc.findIndex((item) => item.path === curr.path);
875
- if (prevIndex !== -1) {
744
+ return cache;
745
+ }
746
+ get(path3) {
747
+ return this.#cache.get(path3);
748
+ }
749
+ remove(path3) {
750
+ const cacheItem = this.get(path3);
751
+ if (!cacheItem) {
752
+ return;
753
+ }
754
+ this.#cache.delete(path3);
755
+ }
756
+ async write(...params) {
757
+ if (!this.#isWriting) {
758
+ this.#isWriting = true;
759
+ const text = await write(...params);
760
+ this.#isWriting = false;
761
+ return text;
762
+ }
763
+ await timeout(this.#timeout);
764
+ return this.write(...params);
765
+ }
766
+ async read(...params) {
767
+ return read(...params);
768
+ }
769
+ // statics
770
+ static getSource(file) {
771
+ if (!_FileManager.isExtensionAllowed(file.baseName)) {
772
+ return file.source;
773
+ }
774
+ const exports = file.exports ? combineExports(file.exports) : [];
775
+ const imports = file.imports ? combineImports(file.imports, exports, file.source) : [];
776
+ const importNodes = imports.map((item) => factory.createImportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly }));
777
+ const exportNodes = exports.map(
778
+ (item) => factory.createExportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly, asAlias: item.asAlias })
779
+ );
780
+ return [print([...importNodes, ...exportNodes]), getEnvSource(file.source, file.env)].join("\n");
781
+ }
782
+ static combineFiles(files) {
783
+ return files.filter(Boolean).reduce((acc, file) => {
784
+ const prevIndex = acc.findIndex((item) => item.path === file.path);
785
+ if (prevIndex === -1) {
786
+ return [...acc, file];
787
+ }
876
788
  const prev = acc[prevIndex];
789
+ if (prev && file.override) {
790
+ acc[prevIndex] = {
791
+ imports: [],
792
+ exports: [],
793
+ ...file
794
+ };
795
+ return acc;
796
+ }
877
797
  if (prev) {
878
798
  acc[prevIndex] = {
879
- ...curr,
880
- source: prev.source && curr.source ? `${prev.source}
881
- ${curr.source}` : "",
882
- imports: [...prev.imports || [], ...curr.imports || []],
883
- exports: [...prev.exports || [], ...curr.exports || []],
884
- env: { ...prev.env || {}, ...curr.env || {} }
799
+ ...file,
800
+ source: prev.source && file.source ? `${prev.source}
801
+ ${file.source}` : "",
802
+ imports: [...prev.imports || [], ...file.imports || []],
803
+ exports: [...prev.exports || [], ...file.exports || []],
804
+ env: { ...prev.env || {}, ...file.env || {} }
885
805
  };
886
806
  }
887
- } else {
888
- acc.push(curr);
807
+ return acc;
808
+ }, []);
809
+ }
810
+ static getMode(path3) {
811
+ if (!path3) {
812
+ return "directory";
889
813
  }
890
- return acc;
891
- }, []);
892
- }
893
- var extensions = [".js", ".ts", ".tsx"];
894
- function isExtensionAllowed(baseName) {
895
- return extensions.some((extension) => baseName.endsWith(extension));
896
- }
814
+ return extname(path3) ? "file" : "directory";
815
+ }
816
+ static get extensions() {
817
+ return [".js", ".ts", ".tsx"];
818
+ }
819
+ static isExtensionAllowed(baseName) {
820
+ return _FileManager.extensions.some((extension) => baseName.endsWith(extension));
821
+ }
822
+ };
897
823
  function combineExports(exports) {
898
824
  const combinedExports = orderBy(exports, [(v) => !v.isTypeOnly], ["asc"]).reduce((prev, curr) => {
899
825
  const name = curr.name;
@@ -967,31 +893,6 @@ function combineImports(imports, exports, source) {
967
893
  }, []);
968
894
  return orderBy(combinedImports, [(v) => !v.isTypeOnly], ["desc"]);
969
895
  }
970
- function createFileSource(file) {
971
- if (!isExtensionAllowed(file.baseName)) {
972
- return file.source;
973
- }
974
- const exports = file.exports ? combineExports(file.exports) : [];
975
- const imports = file.imports ? combineImports(file.imports, exports, file.source) : [];
976
- const importNodes = imports.map((item) => createImportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly }));
977
- const exportNodes = exports.map((item) => createExportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly, asAlias: item.asAlias }));
978
- return [print([...importNodes, ...exportNodes]), getEnvSource(file.source, file.env)].join("\n");
979
- }
980
- function searchAndReplace(options) {
981
- const { text, replaceBy, prefix = "", key } = options;
982
- const searchValues = options.searchValues?.(prefix, key) || [
983
- `${prefix}["${key}"]`,
984
- `${prefix}['${key}']`,
985
- `${prefix}[\`${key}\`]`,
986
- `${prefix}"${key}"`,
987
- `${prefix}'${key}'`,
988
- `${prefix}\`${key}\``,
989
- new RegExp(`${prefix}${key}`, "g")
990
- ];
991
- return searchValues.reduce((prev, searchValue) => {
992
- return prev.toString().replaceAll(searchValue, replaceBy);
993
- }, text);
994
- }
995
896
  function getEnvSource(source, env) {
996
897
  if (!env) {
997
898
  return source;
@@ -1007,156 +908,117 @@ function getEnvSource(source, env) {
1007
908
  throw new TypeError(`Environment should be in upperCase for ${key}`);
1008
909
  }
1009
910
  if (typeof replaceBy === "string") {
1010
- prev = searchAndReplace({ text: prev.replaceAll(`process.env.${key}`, replaceBy), replaceBy, prefix: "process.env", key });
1011
- prev = searchAndReplace({ text: prev.replaceAll(new RegExp(`(declare const).*
911
+ prev = transformers.searchAndReplace({ text: prev.replaceAll(`process.env.${key}`, replaceBy), replaceBy, prefix: "process.env", key });
912
+ prev = transformers.searchAndReplace({ text: prev.replaceAll(new RegExp(`(declare const).*
1012
913
  `, "ig"), ""), replaceBy, key });
1013
914
  }
1014
915
  return prev;
1015
916
  }, source);
1016
917
  }
1017
-
1018
- // src/managers/fileManager/FileManager.ts
1019
- var FileManager = class {
1020
- #cache = /* @__PURE__ */ new Map();
1021
- #task;
1022
- #isWriting = false;
1023
- /**
1024
- * Timeout between writes
1025
- */
1026
- #timeout = 0;
1027
- #queue;
1028
- constructor(options) {
1029
- if (options) {
1030
- this.#task = options.task;
1031
- this.#queue = options.queue;
1032
- this.#timeout = options.timeout || 0;
1033
- }
1034
- return this;
1035
- }
1036
- get extensions() {
1037
- return extensions;
1038
- }
1039
- get files() {
1040
- const files = [];
1041
- this.#cache.forEach((item) => {
1042
- files.push(...item.flat(1));
1043
- });
1044
- return files;
1045
- }
1046
- get isExecuting() {
1047
- return this.#queue?.hasJobs ?? this.#isWriting ?? false;
1048
- }
1049
- async add(file) {
1050
- const controller = new AbortController();
1051
- const resolvedFile = { id: crypto.randomUUID(), ...file };
1052
- this.#cache.set(resolvedFile.path, [{ cancel: () => controller.abort(), ...resolvedFile }]);
1053
- if (this.#queue) {
1054
- await this.#queue.run(
1055
- async () => {
1056
- return this.#task?.(resolvedFile);
1057
- },
1058
- { controller }
1059
- );
1060
- }
1061
- return resolvedFile;
1062
- }
1063
- async addOrAppend(file) {
1064
- const previousCaches = this.#cache.get(file.path);
1065
- const previousCache = previousCaches ? previousCaches.at(previousCaches.length - 1) : void 0;
1066
- if (previousCache) {
1067
- this.#cache.delete(previousCache.path);
1068
- return this.add({
1069
- ...file,
1070
- source: previousCache.source && file.source ? `${previousCache.source}
1071
- ${file.source}` : "",
1072
- imports: [...previousCache.imports || [], ...file.imports || []],
1073
- exports: [...previousCache.exports || [], ...file.exports || []],
1074
- env: { ...previousCache.env || {}, ...file.env || {} }
1075
- });
1076
- }
1077
- return this.add(file);
1078
- }
1079
- async addIndexes({ root, extName = ".ts", meta, options = {} }) {
1080
- const files = getIndexes(root, extName, options);
1081
- if (!files) {
1082
- return void 0;
1083
- }
1084
- return await Promise.all(
1085
- files.map((file) => {
1086
- return this.addOrAppend({
1087
- ...file,
1088
- meta: meta ? meta : file.meta
1089
- });
1090
- })
1091
- );
918
+ var EventEmitter = class {
919
+ constructor() {
920
+ this.#emitter.setMaxListeners(100);
1092
921
  }
1093
- getCacheByUUID(UUID) {
1094
- let cache;
1095
- this.#cache.forEach((files) => {
1096
- cache = files.find((item) => item.id === UUID);
1097
- });
1098
- return cache;
922
+ #emitter = new EventEmitter$1();
923
+ emit(eventName, ...eventArg) {
924
+ this.#emitter.emit(eventName, ...eventArg);
1099
925
  }
1100
- get(path3) {
1101
- return this.#cache.get(path3);
926
+ on(eventName, handler) {
927
+ this.#emitter.on(eventName, handler);
1102
928
  }
1103
- remove(path3) {
1104
- const cacheItem = this.get(path3);
1105
- if (!cacheItem) {
1106
- return;
1107
- }
1108
- this.#cache.delete(path3);
929
+ off(eventName, handler) {
930
+ this.#emitter.off(eventName, handler);
1109
931
  }
1110
- async write(...params) {
1111
- if (!this.#isWriting) {
1112
- this.#isWriting = true;
1113
- const text = await write(...params);
1114
- this.#isWriting = false;
1115
- return text;
1116
- }
1117
- await timeout(this.#timeout);
1118
- return this.write(...params);
932
+ removeAll() {
933
+ this.#emitter.removeAllListeners();
1119
934
  }
1120
- async read(...params) {
1121
- return read(...params);
935
+ };
936
+ var Queue = class {
937
+ #queue = [];
938
+ eventEmitter = new EventEmitter();
939
+ #workerCount = 0;
940
+ #maxParallel;
941
+ #debug = false;
942
+ constructor(maxParallel, debug = false) {
943
+ this.#maxParallel = maxParallel;
944
+ this.#debug = debug;
1122
945
  }
1123
- // statics
1124
- static getSource(file) {
1125
- return createFileSource(file);
946
+ run(job, options = { controller: new AbortController(), name: crypto2.randomUUID(), description: "" }) {
947
+ return new Promise((resolve2, reject) => {
948
+ const item = { reject, resolve: resolve2, job, name: options.name, description: options.description || options.name };
949
+ options.controller?.signal.addEventListener("abort", () => {
950
+ this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
951
+ reject("Aborted");
952
+ });
953
+ this.#queue.push(item);
954
+ this.#work();
955
+ });
1126
956
  }
1127
- static combineFiles(files) {
1128
- return combineFiles(files);
957
+ runSync(job, options = { controller: new AbortController(), name: crypto2.randomUUID(), description: "" }) {
958
+ new Promise((resolve2, reject) => {
959
+ const item = { reject, resolve: resolve2, job, name: options.name, description: options.description || options.name };
960
+ options.controller?.signal.addEventListener("abort", () => {
961
+ this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
962
+ });
963
+ this.#queue.push(item);
964
+ this.#work();
965
+ });
1129
966
  }
1130
- static getMode(path3) {
1131
- if (!path3) {
1132
- return "directory";
1133
- }
1134
- return extname(path3) ? "file" : "directory";
967
+ get hasJobs() {
968
+ return this.#workerCount > 0 || this.#queue.length > 0;
1135
969
  }
1136
- };
1137
-
1138
- // src/managers/pluginManager/executeStrategies.ts
1139
- function hookSeq(promises) {
1140
- return promises.reduce(
1141
- (promise, func) => {
1142
- if (!func || typeof func !== "function") {
1143
- throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
970
+ get count() {
971
+ return this.#workerCount;
972
+ }
973
+ #work() {
974
+ if (this.#workerCount >= this.#maxParallel) {
975
+ return;
976
+ }
977
+ this.#workerCount++;
978
+ let entry;
979
+ while (entry = this.#queue.shift()) {
980
+ const { reject, resolve: resolve2, job, name, description } = entry;
981
+ if (this.#debug) {
982
+ performance.mark(name + "_start");
1144
983
  }
1145
- return promise.then((result) => {
1146
- const calledFunc = func();
1147
- if (calledFunc) {
1148
- return calledFunc.then(Array.prototype.concat.bind(result));
984
+ job().then((result) => {
985
+ this.eventEmitter.emit("jobDone", result);
986
+ resolve2(result);
987
+ if (this.#debug) {
988
+ performance.mark(name + "_stop");
989
+ performance.measure(description, name + "_start", name + "_stop");
1149
990
  }
991
+ }).catch((err) => {
992
+ this.eventEmitter.emit("jobFailed", err);
993
+ reject(err);
1150
994
  });
1151
- },
1152
- Promise.resolve([])
1153
- );
1154
- }
1155
- var executeStrategies = {
1156
- hookSeq
995
+ }
996
+ this.#workerCount--;
997
+ }
1157
998
  };
1158
999
 
1159
- // src/managers/pluginManager/ParallelPluginError.ts
1000
+ // src/utils/uniqueName.ts
1001
+ function setUniqueName(originalName, data) {
1002
+ let used = data[originalName] || 0;
1003
+ if (used) {
1004
+ data[originalName] = ++used;
1005
+ return originalName;
1006
+ }
1007
+ data[originalName] = 1;
1008
+ return originalName;
1009
+ }
1010
+
1011
+ // src/errors.ts
1012
+ var PluginError = class extends Error {
1013
+ pluginManager;
1014
+ cause;
1015
+ constructor(message, options) {
1016
+ super(message, { cause: options.cause });
1017
+ this.name = "PluginError";
1018
+ this.cause = options.cause;
1019
+ this.pluginManager = options.pluginManager;
1020
+ }
1021
+ };
1160
1022
  var ParallelPluginError = class extends Error {
1161
1023
  errors = [];
1162
1024
  pluginManager;
@@ -1181,21 +1043,55 @@ var ParallelPluginError = class extends Error {
1181
1043
  })?.cause;
1182
1044
  }
1183
1045
  };
1184
-
1185
- // src/managers/pluginManager/PluginError.ts
1186
- var PluginError = class extends Error {
1187
- pluginManager;
1188
- cause;
1046
+ var SummaryError = class extends Error {
1047
+ summary;
1189
1048
  constructor(message, options) {
1190
1049
  super(message, { cause: options.cause });
1191
- this.name = "PluginError";
1192
- this.cause = options.cause;
1193
- this.pluginManager = options.pluginManager;
1050
+ this.name = "SummaryError";
1051
+ this.summary = options.summary || [];
1052
+ }
1053
+ };
1054
+ var Warning = class extends Error {
1055
+ constructor(message, options) {
1056
+ super(message, { cause: options?.cause });
1057
+ this.name = "Warning";
1194
1058
  }
1195
1059
  };
1196
- function createPlugin(factory) {
1060
+ var ValidationPluginError = class extends Error {
1061
+ };
1062
+
1063
+ // src/utils/cache.ts
1064
+ function createPluginCache(Store = /* @__PURE__ */ Object.create(null)) {
1065
+ return {
1066
+ set(id, value) {
1067
+ Store[id] = [0, value];
1068
+ },
1069
+ get(id) {
1070
+ const item = Store[id];
1071
+ if (!item) {
1072
+ return null;
1073
+ }
1074
+ item[0] = 0;
1075
+ return item[1];
1076
+ },
1077
+ has(id) {
1078
+ const item = Store[id];
1079
+ if (!item) {
1080
+ return false;
1081
+ }
1082
+ item[0] = 0;
1083
+ return true;
1084
+ },
1085
+ delete(id) {
1086
+ return delete Store[id];
1087
+ }
1088
+ };
1089
+ }
1090
+
1091
+ // src/plugin.ts
1092
+ function createPlugin(factory2) {
1197
1093
  return (options) => {
1198
- return factory(options);
1094
+ return factory2(options);
1199
1095
  };
1200
1096
  }
1201
1097
  var pluginName = "core";
@@ -1221,14 +1117,11 @@ var definePlugin = createPlugin((options) => {
1221
1117
  fileManager,
1222
1118
  pluginManager,
1223
1119
  async addFile(...files) {
1224
- return Promise.all(
1225
- files.map((file) => {
1226
- if (file.override) {
1227
- return fileManager.add(file);
1228
- }
1229
- return fileManager.addOrAppend(file);
1230
- })
1231
- );
1120
+ const resolvedFiles = await fileManager.add(...files);
1121
+ if (!Array.isArray(resolvedFiles)) {
1122
+ return [resolvedFiles];
1123
+ }
1124
+ return resolvedFiles;
1232
1125
  },
1233
1126
  resolvePath,
1234
1127
  resolveName,
@@ -1245,52 +1138,49 @@ var definePlugin = createPlugin((options) => {
1245
1138
  };
1246
1139
  });
1247
1140
 
1248
- // src/types.ts
1249
- var LogLevel = {
1250
- silent: "silent",
1251
- info: "info",
1252
- debug: "debug"
1253
- };
1141
+ // src/utils/executeStrategies.ts
1142
+ function hookSeq(promises) {
1143
+ return promises.reduce(
1144
+ (promise, func) => {
1145
+ if (!func || typeof func !== "function") {
1146
+ throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
1147
+ }
1148
+ return promise.then((result) => {
1149
+ const calledFunc = func();
1150
+ if (calledFunc) {
1151
+ return calledFunc.then(Array.prototype.concat.bind(result));
1152
+ }
1153
+ });
1154
+ },
1155
+ Promise.resolve([])
1156
+ );
1157
+ }
1254
1158
 
1255
- // src/managers/pluginManager/pluginParser.ts
1256
- function pluginParser(plugin, pluginManager, context) {
1257
- const usedPluginNames = pluginManager.usedPluginNames;
1258
- setUniqueName(plugin.name, usedPluginNames);
1259
- const key = plugin.key || [plugin.kind, plugin.name, usedPluginNames[plugin.name]].filter(Boolean);
1260
- if (plugin.name !== "core" && usedPluginNames[plugin.name] >= 2) {
1261
- pluginManager.logger.warn("Using multiple of the same plugin is an experimental feature");
1262
- }
1263
- if (!plugin.transform) {
1264
- plugin.transform = function transform(code) {
1265
- return code;
1266
- };
1159
+ // src/PromiseManager.ts
1160
+ var PromiseManager = class {
1161
+ #options = {};
1162
+ constructor(options = {}) {
1163
+ this.#options = options;
1164
+ return this;
1267
1165
  }
1268
- if (plugin.api && typeof plugin.api === "function") {
1269
- const api = plugin.api.call(context);
1270
- return {
1271
- ...plugin,
1272
- key,
1273
- api
1274
- };
1166
+ run(strategy, promises) {
1167
+ if (strategy === "seq") {
1168
+ return hookSeq(promises);
1169
+ }
1170
+ throw new Error(`${strategy} not implemented`);
1275
1171
  }
1276
- return {
1277
- ...plugin,
1278
- key
1279
- };
1172
+ };
1173
+ function isPromise(result) {
1174
+ return !!result && typeof result?.then === "function";
1175
+ }
1176
+ function isPromiseFulfilledResult(result) {
1177
+ return result.status === "fulfilled";
1178
+ }
1179
+ function isPromiseRejectedResult(result) {
1180
+ return result.status === "rejected";
1280
1181
  }
1281
1182
 
1282
- // src/managers/pluginManager/PluginManager.ts
1283
- var hookNames = {
1284
- validate: 1,
1285
- buildStart: 1,
1286
- resolvePath: 1,
1287
- resolveName: 1,
1288
- load: 1,
1289
- transform: 1,
1290
- writeFile: 1,
1291
- buildEnd: 1
1292
- };
1293
- var hooks = Object.keys(hookNames);
1183
+ // src/PluginManager.ts
1294
1184
  var PluginManager = class {
1295
1185
  plugins;
1296
1186
  fileManager;
@@ -1299,11 +1189,13 @@ var PluginManager = class {
1299
1189
  executed = [];
1300
1190
  logger;
1301
1191
  #core;
1302
- usedPluginNames = {};
1192
+ #usedPluginNames = {};
1193
+ #promiseManager;
1303
1194
  constructor(config, options) {
1304
1195
  this.logger = options.logger;
1305
1196
  this.queue = new Queue(100, this.logger.logLevel === LogLevel.debug);
1306
1197
  this.fileManager = new FileManager({ task: options.task, queue: this.queue, timeout: options.writeTimeout });
1198
+ this.#promiseManager = new PromiseManager();
1307
1199
  const plugins = config.plugins || [];
1308
1200
  const core = definePlugin({
1309
1201
  config,
@@ -1314,9 +1206,9 @@ var PluginManager = class {
1314
1206
  resolveName: this.resolveName.bind(this),
1315
1207
  getPlugins: this.#getSortedPlugins.bind(this)
1316
1208
  });
1317
- this.#core = pluginParser(core, this, core.api.call(null));
1209
+ this.#core = this.#parse(core, this, core.api.call(null));
1318
1210
  this.plugins = [this.#core, ...plugins].map((plugin) => {
1319
- return pluginParser(plugin, this, this.#core.api);
1211
+ return this.#parse(plugin, this, this.#core.api);
1320
1212
  });
1321
1213
  return this;
1322
1214
  }
@@ -1522,7 +1414,7 @@ Names: ${JSON.stringify(names, void 0, 2)}`
1522
1414
  plugin
1523
1415
  });
1524
1416
  });
1525
- return executeStrategies.hookSeq(promises);
1417
+ return this.#promiseManager.run("seq", promises);
1526
1418
  }
1527
1419
  #getSortedPlugins(hookName) {
1528
1420
  const plugins = [...this.plugins].filter((plugin) => plugin.name !== "core");
@@ -1661,35 +1553,52 @@ Names: ${JSON.stringify(names, void 0, 2)}`
1661
1553
  this.eventEmitter.emit("error", pluginError);
1662
1554
  throw pluginError;
1663
1555
  }
1556
+ #parse(plugin, pluginManager, context) {
1557
+ const usedPluginNames = pluginManager.#usedPluginNames;
1558
+ setUniqueName(plugin.name, usedPluginNames);
1559
+ const key = plugin.key || [plugin.kind, plugin.name, usedPluginNames[plugin.name]].filter(Boolean);
1560
+ if (plugin.name !== "core" && usedPluginNames[plugin.name] >= 2) {
1561
+ pluginManager.logger.warn("Using multiple of the same plugin is an experimental feature");
1562
+ }
1563
+ if (!plugin.transform) {
1564
+ plugin.transform = function transform(code) {
1565
+ return code;
1566
+ };
1567
+ }
1568
+ if (plugin.api && typeof plugin.api === "function") {
1569
+ const api = plugin.api.call(context);
1570
+ return {
1571
+ ...plugin,
1572
+ key,
1573
+ api
1574
+ };
1575
+ }
1576
+ return {
1577
+ ...plugin,
1578
+ key
1579
+ };
1580
+ }
1581
+ static getDependedPlugins(plugins, dependedPluginNames) {
1582
+ let pluginNames = [];
1583
+ if (typeof dependedPluginNames === "string") {
1584
+ pluginNames = [dependedPluginNames];
1585
+ } else {
1586
+ pluginNames = dependedPluginNames;
1587
+ }
1588
+ return pluginNames.map((pluginName2) => {
1589
+ const plugin = plugins.find((plugin2) => plugin2.name === pluginName2);
1590
+ if (!plugin) {
1591
+ throw new ValidationPluginError(`This plugin depends on the ${pluginName2} plugin.`);
1592
+ }
1593
+ return plugin;
1594
+ });
1595
+ }
1596
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
1597
+ static get hooks() {
1598
+ return ["validate", "buildStart", "resolvePath", "resolveName", "load", "transform", "writeFile", "buildEnd"];
1599
+ }
1664
1600
  };
1665
1601
 
1666
- // src/managers/pluginManager/validate.ts
1667
- var ValidationPluginError = class extends Error {
1668
- };
1669
- function getDependedPlugins(plugins, dependedPluginNames) {
1670
- let pluginNames = [];
1671
- if (typeof dependedPluginNames === "string") {
1672
- pluginNames = [dependedPluginNames];
1673
- } else {
1674
- pluginNames = dependedPluginNames;
1675
- }
1676
- return pluginNames.map((pluginName2) => {
1677
- const plugin = plugins.find((plugin2) => plugin2.name === pluginName2);
1678
- if (!plugin) {
1679
- throw new ValidationPluginError(`This plugin depends on the ${pluginName2} plugin.`);
1680
- }
1681
- return plugin;
1682
- });
1683
- }
1684
-
1685
- // src/config.ts
1686
- function defineConfig(options) {
1687
- return options;
1688
- }
1689
- function isInputPath(result) {
1690
- return !!result && "path" in result;
1691
- }
1692
-
1693
1602
  // src/build.ts
1694
1603
  async function transformReducer(_previousCode, result, _plugin) {
1695
1604
  return result;
@@ -1802,7 +1711,7 @@ ${code}`);
1802
1711
  return { files: fileManager.files.map((file) => ({ ...file, source: FileManager.getSource(file) })), pluginManager };
1803
1712
  }
1804
1713
 
1805
- // src/generators/Generator.ts
1714
+ // src/Generator.ts
1806
1715
  var Generator = class {
1807
1716
  #options = {};
1808
1717
  #context = {};
@@ -1825,10 +1734,6 @@ var Generator = class {
1825
1734
  this.#options = { ...this.#options, ...options };
1826
1735
  }
1827
1736
  };
1828
-
1829
- // src/generators/SchemaGenerator.ts
1830
- var SchemaGenerator = class extends Generator {
1831
- };
1832
1737
  var PackageManager = class _PackageManager {
1833
1738
  static #cache = {};
1834
1739
  #cwd;
@@ -1937,9 +1842,13 @@ var PackageManager = class _PackageManager {
1937
1842
  }
1938
1843
  };
1939
1844
 
1845
+ // src/SchemaGenerator.ts
1846
+ var SchemaGenerator = class extends Generator {
1847
+ };
1848
+
1940
1849
  // src/index.ts
1941
1850
  var src_default = build;
1942
1851
 
1943
- export { FileManager, FunctionParams, Generator, LogLevel, PackageManager, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, SummaryError, TreeNode, URLPath, ValidationPluginError, Warning, build, clean, createJSDocBlockText, createLogger, createPlugin, createPluginCache, src_default as default, defineConfig, executeStrategies, getDependedPlugins, getRelativePath, getUniqueName, hooks, isInputPath, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, pluginName as name, nameSorter, pluginName, randomColour, randomPicoColour, read, readSync, renderTemplate, setUniqueName, throttle, timeout, transformers, uniqueIdFactory, write };
1852
+ export { FileManager, Generator, PackageManager, ParallelPluginError, PluginError, PluginManager, PromiseManager, SchemaGenerator, SummaryError, ValidationPluginError, Warning, build, createPlugin, src_default as default, defineConfig, isInputPath, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, pluginName as name, pluginName };
1944
1853
  //# sourceMappingURL=out.js.map
1945
1854
  //# sourceMappingURL=index.js.map