@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.cjs CHANGED
@@ -3,18 +3,19 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var pc3 = require('picocolors');
6
- var crypto = require('crypto');
7
- var path4 = require('path');
8
6
  var fs2 = require('fs-extra');
9
- var changeCase = require('change-case');
10
- var naturalOrderby = require('natural-orderby');
11
- var perf_hooks = require('perf_hooks');
12
- var events = require('events');
13
7
  var seedrandom = require('seedrandom');
8
+ var path4 = require('path');
14
9
  var jsRuntime = require('js-runtime');
15
- var dirTree = require('directory-tree');
10
+ var changeCase = require('change-case');
11
+ var crypto2 = require('crypto');
16
12
  var parser = require('@kubb/parser');
13
+ var factory = require('@kubb/parser/factory');
17
14
  var isEqual = require('lodash.isequal');
15
+ var naturalOrderby = require('natural-orderby');
16
+ var dirTree = require('directory-tree');
17
+ var events = require('events');
18
+ var perf_hooks = require('perf_hooks');
18
19
  var mod = require('module');
19
20
  var os = require('os');
20
21
  var url = require('url');
@@ -24,13 +25,32 @@ var semver = require('semver');
24
25
 
25
26
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
26
27
 
28
+ function _interopNamespace(e) {
29
+ if (e && e.__esModule) return e;
30
+ var n = Object.create(null);
31
+ if (e) {
32
+ Object.keys(e).forEach(function (k) {
33
+ if (k !== 'default') {
34
+ var d = Object.getOwnPropertyDescriptor(e, k);
35
+ Object.defineProperty(n, k, d.get ? d : {
36
+ enumerable: true,
37
+ get: function () { return e[k]; }
38
+ });
39
+ }
40
+ });
41
+ }
42
+ n.default = e;
43
+ return Object.freeze(n);
44
+ }
45
+
27
46
  var pc3__default = /*#__PURE__*/_interopDefault(pc3);
28
- var crypto__default = /*#__PURE__*/_interopDefault(crypto);
29
- var path4__default = /*#__PURE__*/_interopDefault(path4);
30
47
  var fs2__default = /*#__PURE__*/_interopDefault(fs2);
31
48
  var seedrandom__default = /*#__PURE__*/_interopDefault(seedrandom);
32
- var dirTree__default = /*#__PURE__*/_interopDefault(dirTree);
49
+ var path4__default = /*#__PURE__*/_interopDefault(path4);
50
+ var crypto2__default = /*#__PURE__*/_interopDefault(crypto2);
51
+ var factory__namespace = /*#__PURE__*/_interopNamespace(factory);
33
52
  var isEqual__default = /*#__PURE__*/_interopDefault(isEqual);
53
+ var dirTree__default = /*#__PURE__*/_interopDefault(dirTree);
34
54
  var mod__default = /*#__PURE__*/_interopDefault(mod);
35
55
  var os__default = /*#__PURE__*/_interopDefault(os);
36
56
  var process__default = /*#__PURE__*/_interopDefault(process);
@@ -43,98 +63,14 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
43
63
  return require.apply(this, arguments);
44
64
  throw Error('Dynamic require of "' + x + '" is not supported');
45
65
  });
46
-
47
- // src/utils/cache.ts
48
- function createPluginCache(Store = /* @__PURE__ */ Object.create(null)) {
49
- return {
50
- set(id, value) {
51
- Store[id] = [0, value];
52
- },
53
- get(id) {
54
- const item = Store[id];
55
- if (!item) {
56
- return null;
57
- }
58
- item[0] = 0;
59
- return item[1];
60
- },
61
- has(id) {
62
- const item = Store[id];
63
- if (!item) {
64
- return false;
65
- }
66
- item[0] = 0;
67
- return true;
68
- },
69
- delete(id) {
70
- return delete Store[id];
71
- }
72
- };
73
- }
74
66
  async function clean(path5) {
75
67
  return fs2.remove(path5);
76
68
  }
77
- var FunctionParams = class {
78
- type;
79
- items = [];
80
- constructor(type) {
81
- this.type = type;
82
- return this;
83
- }
84
- add(item) {
85
- if (!item) {
86
- return this;
87
- }
88
- if (Array.isArray(item)) {
89
- item.filter(Boolean).forEach((it) => this.items.push(it));
90
- return this;
91
- }
92
- this.items.push(item);
93
- return this;
94
- }
95
- toString() {
96
- const sortedData = naturalOrderby.orderBy(this.items.filter(Boolean), [(v) => !v.default, (v) => v.required ?? true], ["desc", "desc"]);
97
- return sortedData.filter(({ enabled = true }) => enabled).reduce((acc, { name, type, required = true, ...rest }) => {
98
- if (!name) {
99
- acc.push(`${type}${rest.default ? ` = ${rest.default}` : ""}`);
100
- return acc;
101
- }
102
- const parameterName = name.startsWith("{") ? name : changeCase.camelCase(name, { delimiter: "", transform: changeCase.camelCaseTransformMerge });
103
- if (type) {
104
- if (required) {
105
- acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ""}`);
106
- } else {
107
- acc.push(`${parameterName}?: ${type}`);
108
- }
109
- } else {
110
- acc.push(`${parameterName}`);
111
- }
112
- return acc;
113
- }, []).join(", ");
114
- }
69
+ var LogLevel = {
70
+ silent: "silent",
71
+ info: "info",
72
+ debug: "debug"
115
73
  };
116
-
117
- // src/utils/isPromise.ts
118
- function isPromise(result) {
119
- return !!result && typeof result?.then === "function";
120
- }
121
- function isPromiseFulfilledResult(result) {
122
- return result.status === "fulfilled";
123
- }
124
- function isPromiseRejectedResult(result) {
125
- return result.status === "rejected";
126
- }
127
-
128
- // src/utils/jsdoc.ts
129
- function createJSDocBlockText({ comments }) {
130
- const filteredComments = comments.filter(Boolean);
131
- if (!filteredComments.length) {
132
- return "";
133
- }
134
- return `/**
135
- * ${filteredComments.join("\n * ")}
136
- */`;
137
- }
138
74
  function createLogger({ logLevel, name, spinner }) {
139
75
  const logs = [];
140
76
  const log = (message) => {
@@ -172,100 +108,6 @@ function createLogger({ logLevel, name, spinner }) {
172
108
  };
173
109
  return logger;
174
110
  }
175
-
176
- // src/utils/nameSorter.ts
177
- function nameSorter(a, b) {
178
- if (a.name < b.name) {
179
- return -1;
180
- }
181
- if (a.name > b.name) {
182
- return 1;
183
- }
184
- return 0;
185
- }
186
- var EventEmitter = class {
187
- constructor() {
188
- this.#emitter.setMaxListeners(100);
189
- }
190
- #emitter = new events.EventEmitter();
191
- emit(eventName, ...eventArg) {
192
- this.#emitter.emit(eventName, ...eventArg);
193
- }
194
- on(eventName, handler) {
195
- this.#emitter.on(eventName, handler);
196
- }
197
- off(eventName, handler) {
198
- this.#emitter.off(eventName, handler);
199
- }
200
- removeAll() {
201
- this.#emitter.removeAllListeners();
202
- }
203
- };
204
-
205
- // src/utils/Queue.ts
206
- var Queue = class {
207
- #queue = [];
208
- eventEmitter = new EventEmitter();
209
- #workerCount = 0;
210
- #maxParallel;
211
- #debug = false;
212
- constructor(maxParallel, debug = false) {
213
- this.#maxParallel = maxParallel;
214
- this.#debug = debug;
215
- }
216
- run(job, options = { controller: new AbortController(), name: crypto__default.default.randomUUID(), description: "" }) {
217
- return new Promise((resolve2, reject) => {
218
- const item = { reject, resolve: resolve2, job, name: options.name, description: options.description || options.name };
219
- options.controller?.signal.addEventListener("abort", () => {
220
- this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
221
- reject("Aborted");
222
- });
223
- this.#queue.push(item);
224
- this.#work();
225
- });
226
- }
227
- runSync(job, options = { controller: new AbortController(), name: crypto__default.default.randomUUID(), description: "" }) {
228
- new Promise((resolve2, reject) => {
229
- const item = { reject, resolve: resolve2, job, name: options.name, description: options.description || options.name };
230
- options.controller?.signal.addEventListener("abort", () => {
231
- this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
232
- });
233
- this.#queue.push(item);
234
- this.#work();
235
- });
236
- }
237
- get hasJobs() {
238
- return this.#workerCount > 0 || this.#queue.length > 0;
239
- }
240
- get count() {
241
- return this.#workerCount;
242
- }
243
- #work() {
244
- if (this.#workerCount >= this.#maxParallel) {
245
- return;
246
- }
247
- this.#workerCount++;
248
- let entry;
249
- while (entry = this.#queue.shift()) {
250
- const { reject, resolve: resolve2, job, name, description } = entry;
251
- if (this.#debug) {
252
- perf_hooks.performance.mark(name + "_start");
253
- }
254
- job().then((result) => {
255
- this.eventEmitter.emit("jobDone", result);
256
- resolve2(result);
257
- if (this.#debug) {
258
- perf_hooks.performance.mark(name + "_stop");
259
- perf_hooks.performance.measure(description, name + "_start", name + "_stop");
260
- }
261
- }).catch((err) => {
262
- this.eventEmitter.emit("jobFailed", err);
263
- reject(err);
264
- });
265
- }
266
- this.#workerCount--;
267
- }
268
- };
269
111
  var defaultColours = ["black", "blue", "darkBlue", "cyan", "gray", "green", "darkGreen", "magenta", "red", "darkRed", "yellow", "darkYellow"];
270
112
  function randomColour(text, colours = defaultColours) {
271
113
  if (!text) {
@@ -292,24 +134,6 @@ function randomPicoColour(text, colors = defaultColours) {
292
134
  }
293
135
  return formatter(text);
294
136
  }
295
- function slash(path5, platform = "linux") {
296
- const isWindowsPath = /^\\\\\?\\/.test(path5);
297
- if (["linux", "mac"].includes(platform) && !isWindowsPath) {
298
- return path5.replaceAll(/\\/g, "/").replace("../", "").trimEnd();
299
- }
300
- return path5.replaceAll(/\\/g, "/").replace("../", "").trimEnd();
301
- }
302
- function getRelativePath(rootDir, filePath, platform = "linux") {
303
- if (!rootDir || !filePath) {
304
- throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ""} ${filePath || ""}`);
305
- }
306
- const relativePath = path4.relative(rootDir, filePath);
307
- const slashedPath = slash(relativePath, platform);
308
- if (slashedPath.startsWith("../")) {
309
- return slashedPath.replace(path4.basename(slashedPath), path4.basename(slashedPath, path4.extname(filePath)));
310
- }
311
- return `./${slashedPath.replace(path4.basename(slashedPath), path4.basename(slashedPath, path4.extname(filePath)))}`;
312
- }
313
137
  var reader = jsRuntime.switcher(
314
138
  {
315
139
  node: async (path5) => {
@@ -322,7 +146,7 @@ var reader = jsRuntime.switcher(
322
146
  },
323
147
  "node"
324
148
  );
325
- var syncReader = jsRuntime.switcher(
149
+ jsRuntime.switcher(
326
150
  {
327
151
  node: (path5) => {
328
152
  return fs2__default.default.readFileSync(path5, { encoding: "utf8" });
@@ -336,75 +160,112 @@ var syncReader = jsRuntime.switcher(
336
160
  async function read(path5) {
337
161
  return reader(path5);
338
162
  }
339
- function readSync(path5) {
340
- return syncReader(path5);
341
- }
342
-
343
- // src/utils/renderTemplate.ts
344
- function renderTemplate(template, data = void 0) {
345
- if (!data || !Object.keys(data).length) {
346
- return template.replace(/{{(.*?)}}/g, "");
347
- }
348
- const matches = template.match(/{{(.*?)}}/g);
349
- return matches?.reduce((prev, curr) => {
350
- const index = curr.split(/{{|}}/).filter(Boolean)[0]?.trim();
351
- if (index === void 0) {
352
- return prev;
353
- }
354
- const value = data[index];
355
- if (value === void 0) {
356
- return prev;
357
- }
358
- return prev.replace(curr, () => {
359
- if (typeof value === "boolean") {
360
- return `${value.toString()}` || "false";
361
- }
362
- return value || "";
363
- }).trim();
364
- }, template) || "";
365
- }
366
-
367
- // src/utils/SummaryError.ts
368
- var SummaryError = class extends Error {
369
- summary;
370
- constructor(message, options) {
371
- super(message, { cause: options.cause });
372
- this.name = "SummaryError";
373
- this.summary = options.summary || [];
163
+ var URLPath = class {
164
+ path;
165
+ constructor(path5) {
166
+ this.path = path5;
167
+ return this;
374
168
  }
375
- };
376
-
377
- // src/utils/throttle.ts
378
- var throttle = (fn, delay) => {
379
- let wait = false;
380
- let timeout2;
381
- let cancelled = false;
382
- return [
383
- (...args) => {
384
- if (cancelled) {
385
- return void 0;
169
+ /**
170
+ * Convert Swagger path to URLPath(syntax of Express)
171
+ * @example /pet/{petId} => /pet/:petId
172
+ */
173
+ get URL() {
174
+ return this.toURLPath();
175
+ }
176
+ get isURL() {
177
+ try {
178
+ const url = new URL(this.path);
179
+ if (url?.href) {
180
+ return true;
386
181
  }
387
- if (wait) {
388
- return void 0;
182
+ } catch (error) {
183
+ return false;
184
+ }
185
+ return false;
186
+ }
187
+ /**
188
+ * Convert Swagger path to template literals/ template strings(camelcase)
189
+ * @example /pet/{petId} => `/pet/${petId}`
190
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
191
+ * @example /account/userID => `/account/${userId}`
192
+ */
193
+ get template() {
194
+ return this.toTemplateString();
195
+ }
196
+ get object() {
197
+ return this.toObject();
198
+ }
199
+ get params() {
200
+ return this.getParams();
201
+ }
202
+ toObject({ type = "path", replacer, stringify } = {}) {
203
+ const object = {
204
+ url: type === "path" ? this.toURLPath() : this.toTemplateString(replacer),
205
+ params: this.getParams()
206
+ };
207
+ if (stringify) {
208
+ if (type !== "template") {
209
+ throw new Error("Type should be `template` when using stringiyf");
389
210
  }
390
- const val = fn(...args);
391
- wait = true;
392
- timeout2 = setTimeout(() => {
393
- wait = false;
394
- }, delay);
395
- return val;
396
- },
397
- () => {
398
- cancelled = true;
399
- clearTimeout(timeout2);
211
+ return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
400
212
  }
401
- ];
402
- };
403
-
404
- // src/utils/timeout.ts
405
- async function timeout(ms) {
406
- return new Promise((resolve2) => {
407
- setTimeout(() => {
213
+ return object;
214
+ }
215
+ /**
216
+ * Convert Swagger path to template literals/ template strings(camelcase)
217
+ * @example /pet/{petId} => `/pet/${petId}`
218
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
219
+ * @example /account/userID => `/account/${userId}`
220
+ */
221
+ toTemplateString(replacer) {
222
+ const regex = /{(\w|-)*}/g;
223
+ const found = this.path.match(regex);
224
+ let newPath = this.path.replaceAll("{", "${");
225
+ if (found) {
226
+ newPath = found.reduce((prev, curr) => {
227
+ const pathParam = replacer ? replacer(changeCase.camelCase(curr, { delimiter: "", transform: changeCase.camelCaseTransformMerge })) : changeCase.camelCase(curr, { delimiter: "", transform: changeCase.camelCaseTransformMerge });
228
+ const replacement = `\${${pathParam}}`;
229
+ return prev.replace(curr, replacement);
230
+ }, this.path);
231
+ }
232
+ return `\`${newPath}\``;
233
+ }
234
+ getParams(replacer) {
235
+ const regex = /{(\w|-)*}/g;
236
+ const found = this.path.match(regex);
237
+ if (!found) {
238
+ return void 0;
239
+ }
240
+ const params = {};
241
+ found.forEach((item) => {
242
+ item = item.replaceAll("{", "").replaceAll("}", "");
243
+ const pathParam = replacer ? replacer(changeCase.camelCase(item, { delimiter: "", transform: changeCase.camelCaseTransformMerge })) : changeCase.camelCase(item, { delimiter: "", transform: changeCase.camelCaseTransformMerge });
244
+ params[pathParam] = pathParam;
245
+ }, this.path);
246
+ return params;
247
+ }
248
+ /**
249
+ * Convert Swagger path to URLPath(syntax of Express)
250
+ * @example /pet/{petId} => /pet/:petId
251
+ */
252
+ toURLPath() {
253
+ return this.path.replaceAll("{", ":").replaceAll("}", "");
254
+ }
255
+ };
256
+
257
+ // src/config.ts
258
+ function defineConfig(options) {
259
+ return options;
260
+ }
261
+ function isInputPath(result) {
262
+ return !!result && "path" in result;
263
+ }
264
+
265
+ // src/utils/timeout.ts
266
+ async function timeout(ms) {
267
+ return new Promise((resolve2) => {
268
+ setTimeout(() => {
408
269
  resolve2(true);
409
270
  }, ms);
410
271
  });
@@ -415,6 +276,17 @@ function combineCodes(codes) {
415
276
  return codes.join("\n");
416
277
  }
417
278
 
279
+ // src/utils/transformers/createJSDocBlockText.ts
280
+ function createJSDocBlockText({ comments }) {
281
+ const filteredComments = comments.filter(Boolean);
282
+ if (!filteredComments.length) {
283
+ return "";
284
+ }
285
+ return `/**
286
+ * ${filteredComments.join("\n * ")}
287
+ */`;
288
+ }
289
+
418
290
  // src/utils/transformers/escape.ts
419
291
  function escape(text) {
420
292
  return text ? text.replaceAll("`", "\\`") : "";
@@ -445,6 +317,34 @@ function createIndent(size) {
445
317
  return Array.from({ length: size + 1 }).join(" ");
446
318
  }
447
319
 
320
+ // src/utils/transformers/nameSorter.ts
321
+ function nameSorter(a, b) {
322
+ if (a.name < b.name) {
323
+ return -1;
324
+ }
325
+ if (a.name > b.name) {
326
+ return 1;
327
+ }
328
+ return 0;
329
+ }
330
+
331
+ // src/utils/transformers/searchAndReplace.ts
332
+ function searchAndReplace(options) {
333
+ const { text, replaceBy, prefix = "", key } = options;
334
+ const searchValues = options.searchValues?.(prefix, key) || [
335
+ `${prefix}["${key}"]`,
336
+ `${prefix}['${key}']`,
337
+ `${prefix}[\`${key}\`]`,
338
+ `${prefix}"${key}"`,
339
+ `${prefix}'${key}'`,
340
+ `${prefix}\`${key}\``,
341
+ new RegExp(`${prefix}${key}`, "g")
342
+ ];
343
+ return searchValues.reduce((prev, searchValue) => {
344
+ return prev.toString().replaceAll(searchValue, replaceBy);
345
+ }, text);
346
+ }
347
+
448
348
  // src/utils/transformers/transformReservedWord.ts
449
349
  var reservedWords = [
450
350
  "abstract",
@@ -544,8 +444,73 @@ var transformers = {
544
444
  escape,
545
445
  jsStringEscape,
546
446
  createIndent,
547
- transformReservedWord
447
+ transformReservedWord,
448
+ nameSorter,
449
+ searchAndReplace,
450
+ JSDoc: {
451
+ createJSDocBlockText
452
+ }
548
453
  };
454
+ async function saveCreateDirectory(path5) {
455
+ const passedPath = path4.dirname(path4.resolve(path5));
456
+ await fs2__default.default.mkdir(passedPath, { recursive: true });
457
+ }
458
+ var writer = jsRuntime.switcher(
459
+ {
460
+ node: async (path5, data) => {
461
+ try {
462
+ await fs2__default.default.stat(path4.resolve(path5));
463
+ const oldContent = await fs2__default.default.readFile(path4.resolve(path5), { encoding: "utf-8" });
464
+ if (oldContent?.toString() === data?.toString()) {
465
+ return;
466
+ }
467
+ } catch (_err) {
468
+ }
469
+ await saveCreateDirectory(path5);
470
+ await fs2__default.default.writeFile(path4.resolve(path5), data, { encoding: "utf-8" });
471
+ const savedData = await fs2__default.default.readFile(path4.resolve(path5), { encoding: "utf-8" });
472
+ if (savedData?.toString() !== data?.toString()) {
473
+ throw new Error(`Sanity check failed for ${path5}
474
+
475
+ Data[${data.length}]:
476
+ ${data}
477
+
478
+ Saved[${savedData.length}]:
479
+ ${savedData}
480
+ `);
481
+ }
482
+ return savedData;
483
+ },
484
+ bun: async (path5, data) => {
485
+ try {
486
+ await saveCreateDirectory(path5);
487
+ await Bun.write(path4.resolve(path5), data);
488
+ const file = Bun.file(path4.resolve(path5));
489
+ const savedData = await file.text();
490
+ if (savedData?.toString() !== data?.toString()) {
491
+ throw new Error(`Sanity check failed for ${path5}
492
+
493
+ Data[${data.length}]:
494
+ ${data}
495
+
496
+ Saved[${savedData.length}]:
497
+ ${savedData}
498
+ `);
499
+ }
500
+ return savedData;
501
+ } catch (e) {
502
+ console.log(e, path4.resolve(path5));
503
+ }
504
+ }
505
+ },
506
+ "node"
507
+ );
508
+ async function write(data, path5) {
509
+ if (data.trim() === "") {
510
+ return void 0;
511
+ }
512
+ return writer(path5, data.trim());
513
+ }
549
514
  var TreeNode = class _TreeNode {
550
515
  data;
551
516
  parent;
@@ -634,282 +599,263 @@ var TreeNode = class _TreeNode {
634
599
  }
635
600
  };
636
601
 
637
- // src/utils/uniqueIdFactory.ts
638
- var uniqueIdFactory = (counter) => (str = "") => `${str}${++counter}`;
639
-
640
- // src/utils/uniqueName.ts
641
- function getUniqueName(originalName, data) {
642
- let used = data[originalName] || 0;
643
- if (used) {
644
- data[originalName] = ++used;
645
- originalName += used;
646
- }
647
- data[originalName] = 1;
648
- return originalName;
649
- }
650
- function setUniqueName(originalName, data) {
651
- let used = data[originalName] || 0;
652
- if (used) {
653
- data[originalName] = ++used;
654
- return originalName;
655
- }
656
- data[originalName] = 1;
657
- return originalName;
658
- }
659
- var URLPath = class {
660
- path;
661
- constructor(path5) {
662
- this.path = path5;
602
+ // src/BarrelManager.ts
603
+ var BarrelManager = class {
604
+ #options = {};
605
+ constructor(options = {}) {
606
+ this.#options = options;
663
607
  return this;
664
608
  }
665
- /**
666
- * Convert Swagger path to URLPath(syntax of Express)
667
- * @example /pet/{petId} => /pet/:petId
668
- */
669
- get URL() {
670
- return this.toURLPath();
671
- }
672
- get isURL() {
673
- try {
674
- const url = new URL(this.path);
675
- if (url?.href) {
676
- return true;
609
+ getIndexes(root, extName) {
610
+ const { treeNode = {}, isTypeOnly, filter, map, output, includeExt } = this.#options;
611
+ const extMapper = {
612
+ ".ts": {
613
+ extensions: /\.ts/,
614
+ exclude: [/schemas/, /json/]
615
+ },
616
+ ".json": {
617
+ extensions: /\.json/,
618
+ exclude: []
677
619
  }
678
- } catch (error) {
679
- return false;
620
+ };
621
+ const tree = TreeNode.build(root, { ...extMapper[extName] || {}, ...treeNode });
622
+ if (!tree) {
623
+ return null;
680
624
  }
681
- return false;
625
+ const fileReducer = (files2, currentTree) => {
626
+ if (!currentTree.children) {
627
+ return [];
628
+ }
629
+ if (currentTree.children?.length > 1) {
630
+ const indexPath = path4__default.default.resolve(currentTree.data.path, "index.ts");
631
+ const exports = currentTree.children.filter(Boolean).map((file) => {
632
+ const importPath = file.data.type === "directory" ? `./${file.data.name}` : `./${file.data.name.replace(/\.[^.]*$/, "")}`;
633
+ if (importPath.includes("index") && indexPath.includes("index")) {
634
+ return void 0;
635
+ }
636
+ return {
637
+ path: includeExt ? file.data.type === "directory" ? `${importPath}/index${extName}` : `${importPath}${extName}` : importPath,
638
+ isTypeOnly
639
+ };
640
+ }).filter(Boolean);
641
+ files2.push({
642
+ path: indexPath,
643
+ baseName: "index.ts",
644
+ source: "",
645
+ exports: output ? exports?.filter((item) => {
646
+ return item.path.endsWith(output.replace(/\.[^.]*$/, ""));
647
+ }) : exports
648
+ });
649
+ } else {
650
+ currentTree.children?.forEach((child) => {
651
+ const indexPath = path4__default.default.resolve(currentTree.data.path, "index.ts");
652
+ const importPath = child.data.type === "directory" ? `./${child.data.name}` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
653
+ const exports = [
654
+ {
655
+ path: includeExt ? child.data.type === "directory" ? `${importPath}/index${extName}` : `${importPath}${extName}` : importPath,
656
+ isTypeOnly
657
+ }
658
+ ];
659
+ files2.push({
660
+ path: indexPath,
661
+ baseName: "index.ts",
662
+ source: "",
663
+ exports: output ? exports?.filter((item) => {
664
+ return item.path.endsWith(output.replace(/\.[^.]*$/, ""));
665
+ }) : exports
666
+ });
667
+ });
668
+ }
669
+ currentTree.children.forEach((childItem) => {
670
+ fileReducer(files2, childItem);
671
+ });
672
+ return files2;
673
+ };
674
+ const files = fileReducer([], tree).reverse();
675
+ const filteredFiles = filter ? files.filter(filter) : files;
676
+ return map ? filteredFiles.map(map) : filteredFiles;
682
677
  }
678
+ };
679
+
680
+ // src/FileManager.ts
681
+ var FileManager = class _FileManager {
682
+ #cache = /* @__PURE__ */ new Map();
683
+ #task;
684
+ #isWriting = false;
683
685
  /**
684
- * Convert Swagger path to template literals/ template strings(camelcase)
685
- * @example /pet/{petId} => `/pet/${petId}`
686
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
687
- * @example /account/userID => `/account/${userId}`
686
+ * Timeout between writes
688
687
  */
689
- get template() {
690
- return this.toTemplateString();
688
+ #timeout = 0;
689
+ #queue;
690
+ constructor(options) {
691
+ if (options) {
692
+ this.#task = options.task;
693
+ this.#queue = options.queue;
694
+ this.#timeout = options.timeout || 0;
695
+ }
696
+ return this;
691
697
  }
692
- get object() {
693
- return this.toObject();
698
+ get files() {
699
+ const files = [];
700
+ this.#cache.forEach((item) => {
701
+ files.push(...item.flat(1));
702
+ });
703
+ return files;
694
704
  }
695
- get params() {
696
- return this.getParams();
705
+ get isExecuting() {
706
+ return this.#queue?.hasJobs ?? this.#isWriting ?? false;
697
707
  }
698
- toObject({ type = "path", replacer, stringify } = {}) {
699
- const object = {
700
- url: type === "path" ? this.toURLPath() : this.toTemplateString(replacer),
701
- params: this.getParams()
702
- };
703
- if (stringify) {
704
- if (type !== "template") {
705
- throw new Error("Type should be `template` when using stringiyf");
706
- }
707
- return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
708
+ #validate(file) {
709
+ if (!file.validate) {
710
+ return;
711
+ }
712
+ if (!file.path.toLowerCase().endsWith(file.baseName.toLowerCase())) {
713
+ throw new Error(`${file.path} should end with the baseName ${file.baseName}`);
708
714
  }
709
- return object;
710
715
  }
711
- /**
712
- * Convert Swagger path to template literals/ template strings(camelcase)
713
- * @example /pet/{petId} => `/pet/${petId}`
714
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
715
- * @example /account/userID => `/account/${userId}`
716
- */
717
- toTemplateString(replacer) {
718
- const regex = /{(\w|-)*}/g;
719
- const found = this.path.match(regex);
720
- let newPath = this.path.replaceAll("{", "${");
721
- if (found) {
722
- newPath = found.reduce((prev, curr) => {
723
- const pathParam = replacer ? replacer(changeCase.camelCase(curr, { delimiter: "", transform: changeCase.camelCaseTransformMerge })) : changeCase.camelCase(curr, { delimiter: "", transform: changeCase.camelCaseTransformMerge });
724
- const replacement = `\${${pathParam}}`;
725
- return prev.replace(curr, replacement);
726
- }, this.path);
716
+ async add(...files) {
717
+ const promises = files.map((file) => {
718
+ this.#validate(file);
719
+ if (file.override) {
720
+ return this.#add(file);
721
+ }
722
+ return this.#addOrAppend(file);
723
+ });
724
+ const resolvedFiles = await Promise.all(promises);
725
+ if (files.length > 1) {
726
+ return resolvedFiles;
727
727
  }
728
- return `\`${newPath}\``;
728
+ return resolvedFiles[0];
729
729
  }
730
- getParams(replacer) {
731
- const regex = /{(\w|-)*}/g;
732
- const found = this.path.match(regex);
733
- if (!found) {
730
+ async #add(file) {
731
+ const controller = new AbortController();
732
+ const resolvedFile = { id: crypto2__default.default.randomUUID(), ...file };
733
+ this.#cache.set(resolvedFile.path, [{ cancel: () => controller.abort(), ...resolvedFile }]);
734
+ if (this.#queue) {
735
+ await this.#queue.run(
736
+ async () => {
737
+ return this.#task?.(resolvedFile);
738
+ },
739
+ { controller }
740
+ );
741
+ }
742
+ return resolvedFile;
743
+ }
744
+ async #addOrAppend(file) {
745
+ const previousCaches = this.#cache.get(file.path);
746
+ const previousCache = previousCaches ? previousCaches.at(previousCaches.length - 1) : void 0;
747
+ if (previousCache) {
748
+ this.#cache.delete(previousCache.path);
749
+ return this.#add({
750
+ ...file,
751
+ source: previousCache.source && file.source ? `${previousCache.source}
752
+ ${file.source}` : "",
753
+ imports: [...previousCache.imports || [], ...file.imports || []],
754
+ exports: [...previousCache.exports || [], ...file.exports || []],
755
+ env: { ...previousCache.env || {}, ...file.env || {} }
756
+ });
757
+ }
758
+ return this.#add(file);
759
+ }
760
+ async addIndexes({ root, extName = ".ts", meta, options = {} }) {
761
+ const barrelManager = new BarrelManager(options);
762
+ const files = barrelManager.getIndexes(root, extName);
763
+ if (!files) {
734
764
  return void 0;
735
765
  }
736
- const params = {};
737
- found.forEach((item) => {
738
- item = item.replaceAll("{", "").replaceAll("}", "");
739
- const pathParam = replacer ? replacer(changeCase.camelCase(item, { delimiter: "", transform: changeCase.camelCaseTransformMerge })) : changeCase.camelCase(item, { delimiter: "", transform: changeCase.camelCaseTransformMerge });
740
- params[pathParam] = pathParam;
741
- }, this.path);
742
- return params;
766
+ return await Promise.all(
767
+ files.map((file) => {
768
+ return this.#addOrAppend({
769
+ ...file,
770
+ meta: meta ? meta : file.meta
771
+ });
772
+ })
773
+ );
743
774
  }
744
- /**
745
- * Convert Swagger path to URLPath(syntax of Express)
746
- * @example /pet/{petId} => /pet/:petId
747
- */
748
- toURLPath() {
749
- return this.path.replaceAll("{", ":").replaceAll("}", "");
775
+ getCacheByUUID(UUID) {
776
+ let cache;
777
+ this.#cache.forEach((files) => {
778
+ cache = files.find((item) => item.id === UUID);
779
+ });
780
+ return cache;
750
781
  }
751
- };
752
-
753
- // src/utils/Warning.ts
754
- var Warning = class extends Error {
755
- constructor(message, options) {
756
- super(message, { cause: options?.cause });
757
- this.name = "Warning";
782
+ get(path5) {
783
+ return this.#cache.get(path5);
758
784
  }
759
- };
760
- async function saveCreateDirectory(path5) {
761
- const passedPath = path4.dirname(path4.resolve(path5));
762
- await fs2__default.default.mkdir(passedPath, { recursive: true });
763
- }
764
- var writer = jsRuntime.switcher(
765
- {
766
- node: async (path5, data) => {
767
- try {
768
- await fs2__default.default.stat(path4.resolve(path5));
769
- const oldContent = await fs2__default.default.readFile(path4.resolve(path5), { encoding: "utf-8" });
770
- if (oldContent?.toString() === data?.toString()) {
771
- return;
772
- }
773
- } catch (_err) {
774
- }
775
- await saveCreateDirectory(path5);
776
- await fs2__default.default.writeFile(path4.resolve(path5), data, { encoding: "utf-8" });
777
- const savedData = await fs2__default.default.readFile(path4.resolve(path5), { encoding: "utf-8" });
778
- if (savedData?.toString() !== data?.toString()) {
779
- throw new Error(`Sanity check failed for ${path5}
780
-
781
- Data[${data.length}]:
782
- ${data}
783
-
784
- Saved[${savedData.length}]:
785
- ${savedData}
786
- `);
787
- }
788
- return savedData;
789
- },
790
- bun: async (path5, data) => {
791
- try {
792
- await saveCreateDirectory(path5);
793
- await Bun.write(path4.resolve(path5), data);
794
- const file = Bun.file(path4.resolve(path5));
795
- const savedData = await file.text();
796
- if (savedData?.toString() !== data?.toString()) {
797
- throw new Error(`Sanity check failed for ${path5}
798
-
799
- Data[${data.length}]:
800
- ${data}
801
-
802
- Saved[${savedData.length}]:
803
- ${savedData}
804
- `);
805
- }
806
- return savedData;
807
- } catch (e) {
808
- console.log(e, path4.resolve(path5));
809
- }
785
+ remove(path5) {
786
+ const cacheItem = this.get(path5);
787
+ if (!cacheItem) {
788
+ return;
810
789
  }
811
- },
812
- "node"
813
- );
814
- async function write(data, path5) {
815
- if (data.trim() === "") {
816
- return void 0;
790
+ this.#cache.delete(path5);
817
791
  }
818
- return writer(path5, data.trim());
819
- }
820
- function getIndexes(root, extName, { treeNode = {}, isTypeOnly, filter, map, output, includeExt } = {}) {
821
- const extMapper = {
822
- ".ts": {
823
- extensions: /\.ts/,
824
- exclude: [/schemas/, /json/]
825
- },
826
- ".json": {
827
- extensions: /\.json/,
828
- exclude: []
792
+ async write(...params) {
793
+ if (!this.#isWriting) {
794
+ this.#isWriting = true;
795
+ const text = await write(...params);
796
+ this.#isWriting = false;
797
+ return text;
829
798
  }
830
- };
831
- const tree = TreeNode.build(root, { ...extMapper[extName] || {}, ...treeNode });
832
- if (!tree) {
833
- return null;
799
+ await timeout(this.#timeout);
800
+ return this.write(...params);
834
801
  }
835
- const fileReducer = (files2, currentTree) => {
836
- if (!currentTree.children) {
837
- return [];
838
- }
839
- if (currentTree.children?.length > 1) {
840
- const indexPath = path4__default.default.resolve(currentTree.data.path, "index.ts");
841
- const exports = currentTree.children.filter(Boolean).map((file) => {
842
- const importPath = file.data.type === "directory" ? `./${file.data.name}` : `./${file.data.name.replace(/\.[^.]*$/, "")}`;
843
- if (importPath.includes("index") && indexPath.includes("index")) {
844
- return void 0;
845
- }
846
- return {
847
- path: includeExt ? file.data.type === "directory" ? `${importPath}/index${extName}` : `${importPath}${extName}` : importPath,
848
- isTypeOnly
849
- };
850
- }).filter(Boolean);
851
- files2.push({
852
- path: indexPath,
853
- baseName: "index.ts",
854
- source: "",
855
- exports: output ? exports?.filter((item) => {
856
- return item.path.endsWith(output.replace(/\.[^.]*$/, ""));
857
- }) : exports
858
- });
859
- } else {
860
- currentTree.children?.forEach((child) => {
861
- const indexPath = path4__default.default.resolve(currentTree.data.path, "index.ts");
862
- const importPath = child.data.type === "directory" ? `./${child.data.name}` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
863
- const exports = [
864
- {
865
- path: includeExt ? child.data.type === "directory" ? `${importPath}/index${extName}` : `${importPath}${extName}` : importPath,
866
- isTypeOnly
867
- }
868
- ];
869
- files2.push({
870
- path: indexPath,
871
- baseName: "index.ts",
872
- source: "",
873
- exports: output ? exports?.filter((item) => {
874
- return item.path.endsWith(output.replace(/\.[^.]*$/, ""));
875
- }) : exports
876
- });
877
- });
878
- }
879
- currentTree.children.forEach((childItem) => {
880
- fileReducer(files2, childItem);
881
- });
882
- return files2;
883
- };
884
- const files = fileReducer([], tree).reverse();
885
- const filteredFiles = filter ? files.filter(filter) : files;
886
- return map ? filteredFiles.map(map) : filteredFiles;
887
- }
888
- function combineFiles(files) {
889
- return files.filter(Boolean).reduce((acc, curr) => {
890
- const prevIndex = acc.findIndex((item) => item.path === curr.path);
891
- if (prevIndex !== -1) {
802
+ async read(...params) {
803
+ return read(...params);
804
+ }
805
+ // statics
806
+ static getSource(file) {
807
+ if (!_FileManager.isExtensionAllowed(file.baseName)) {
808
+ return file.source;
809
+ }
810
+ const exports = file.exports ? combineExports(file.exports) : [];
811
+ const imports = file.imports ? combineImports(file.imports, exports, file.source) : [];
812
+ const importNodes = imports.map((item) => factory__namespace.createImportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly }));
813
+ const exportNodes = exports.map(
814
+ (item) => factory__namespace.createExportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly, asAlias: item.asAlias })
815
+ );
816
+ return [parser.print([...importNodes, ...exportNodes]), getEnvSource(file.source, file.env)].join("\n");
817
+ }
818
+ static combineFiles(files) {
819
+ return files.filter(Boolean).reduce((acc, file) => {
820
+ const prevIndex = acc.findIndex((item) => item.path === file.path);
821
+ if (prevIndex === -1) {
822
+ return [...acc, file];
823
+ }
892
824
  const prev = acc[prevIndex];
825
+ if (prev && file.override) {
826
+ acc[prevIndex] = {
827
+ imports: [],
828
+ exports: [],
829
+ ...file
830
+ };
831
+ return acc;
832
+ }
893
833
  if (prev) {
894
834
  acc[prevIndex] = {
895
- ...curr,
896
- source: prev.source && curr.source ? `${prev.source}
897
- ${curr.source}` : "",
898
- imports: [...prev.imports || [], ...curr.imports || []],
899
- exports: [...prev.exports || [], ...curr.exports || []],
900
- env: { ...prev.env || {}, ...curr.env || {} }
835
+ ...file,
836
+ source: prev.source && file.source ? `${prev.source}
837
+ ${file.source}` : "",
838
+ imports: [...prev.imports || [], ...file.imports || []],
839
+ exports: [...prev.exports || [], ...file.exports || []],
840
+ env: { ...prev.env || {}, ...file.env || {} }
901
841
  };
902
842
  }
903
- } else {
904
- acc.push(curr);
843
+ return acc;
844
+ }, []);
845
+ }
846
+ static getMode(path5) {
847
+ if (!path5) {
848
+ return "directory";
905
849
  }
906
- return acc;
907
- }, []);
908
- }
909
- var extensions = [".js", ".ts", ".tsx"];
910
- function isExtensionAllowed(baseName) {
911
- return extensions.some((extension) => baseName.endsWith(extension));
912
- }
850
+ return path4.extname(path5) ? "file" : "directory";
851
+ }
852
+ static get extensions() {
853
+ return [".js", ".ts", ".tsx"];
854
+ }
855
+ static isExtensionAllowed(baseName) {
856
+ return _FileManager.extensions.some((extension) => baseName.endsWith(extension));
857
+ }
858
+ };
913
859
  function combineExports(exports) {
914
860
  const combinedExports = naturalOrderby.orderBy(exports, [(v) => !v.isTypeOnly], ["asc"]).reduce((prev, curr) => {
915
861
  const name = curr.name;
@@ -983,31 +929,6 @@ function combineImports(imports, exports, source) {
983
929
  }, []);
984
930
  return naturalOrderby.orderBy(combinedImports, [(v) => !v.isTypeOnly], ["desc"]);
985
931
  }
986
- function createFileSource(file) {
987
- if (!isExtensionAllowed(file.baseName)) {
988
- return file.source;
989
- }
990
- const exports = file.exports ? combineExports(file.exports) : [];
991
- const imports = file.imports ? combineImports(file.imports, exports, file.source) : [];
992
- const importNodes = imports.map((item) => parser.createImportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly }));
993
- const exportNodes = exports.map((item) => parser.createExportDeclaration({ name: item.name, path: item.path, isTypeOnly: item.isTypeOnly, asAlias: item.asAlias }));
994
- return [parser.print([...importNodes, ...exportNodes]), getEnvSource(file.source, file.env)].join("\n");
995
- }
996
- function searchAndReplace(options) {
997
- const { text, replaceBy, prefix = "", key } = options;
998
- const searchValues = options.searchValues?.(prefix, key) || [
999
- `${prefix}["${key}"]`,
1000
- `${prefix}['${key}']`,
1001
- `${prefix}[\`${key}\`]`,
1002
- `${prefix}"${key}"`,
1003
- `${prefix}'${key}'`,
1004
- `${prefix}\`${key}\``,
1005
- new RegExp(`${prefix}${key}`, "g")
1006
- ];
1007
- return searchValues.reduce((prev, searchValue) => {
1008
- return prev.toString().replaceAll(searchValue, replaceBy);
1009
- }, text);
1010
- }
1011
932
  function getEnvSource(source, env) {
1012
933
  if (!env) {
1013
934
  return source;
@@ -1023,156 +944,117 @@ function getEnvSource(source, env) {
1023
944
  throw new TypeError(`Environment should be in upperCase for ${key}`);
1024
945
  }
1025
946
  if (typeof replaceBy === "string") {
1026
- prev = searchAndReplace({ text: prev.replaceAll(`process.env.${key}`, replaceBy), replaceBy, prefix: "process.env", key });
1027
- prev = searchAndReplace({ text: prev.replaceAll(new RegExp(`(declare const).*
947
+ prev = transformers.searchAndReplace({ text: prev.replaceAll(`process.env.${key}`, replaceBy), replaceBy, prefix: "process.env", key });
948
+ prev = transformers.searchAndReplace({ text: prev.replaceAll(new RegExp(`(declare const).*
1028
949
  `, "ig"), ""), replaceBy, key });
1029
950
  }
1030
951
  return prev;
1031
952
  }, source);
1032
953
  }
1033
-
1034
- // src/managers/fileManager/FileManager.ts
1035
- var FileManager = class {
1036
- #cache = /* @__PURE__ */ new Map();
1037
- #task;
1038
- #isWriting = false;
1039
- /**
1040
- * Timeout between writes
1041
- */
1042
- #timeout = 0;
1043
- #queue;
1044
- constructor(options) {
1045
- if (options) {
1046
- this.#task = options.task;
1047
- this.#queue = options.queue;
1048
- this.#timeout = options.timeout || 0;
1049
- }
1050
- return this;
1051
- }
1052
- get extensions() {
1053
- return extensions;
1054
- }
1055
- get files() {
1056
- const files = [];
1057
- this.#cache.forEach((item) => {
1058
- files.push(...item.flat(1));
1059
- });
1060
- return files;
1061
- }
1062
- get isExecuting() {
1063
- return this.#queue?.hasJobs ?? this.#isWriting ?? false;
1064
- }
1065
- async add(file) {
1066
- const controller = new AbortController();
1067
- const resolvedFile = { id: crypto__default.default.randomUUID(), ...file };
1068
- this.#cache.set(resolvedFile.path, [{ cancel: () => controller.abort(), ...resolvedFile }]);
1069
- if (this.#queue) {
1070
- await this.#queue.run(
1071
- async () => {
1072
- return this.#task?.(resolvedFile);
1073
- },
1074
- { controller }
1075
- );
1076
- }
1077
- return resolvedFile;
1078
- }
1079
- async addOrAppend(file) {
1080
- const previousCaches = this.#cache.get(file.path);
1081
- const previousCache = previousCaches ? previousCaches.at(previousCaches.length - 1) : void 0;
1082
- if (previousCache) {
1083
- this.#cache.delete(previousCache.path);
1084
- return this.add({
1085
- ...file,
1086
- source: previousCache.source && file.source ? `${previousCache.source}
1087
- ${file.source}` : "",
1088
- imports: [...previousCache.imports || [], ...file.imports || []],
1089
- exports: [...previousCache.exports || [], ...file.exports || []],
1090
- env: { ...previousCache.env || {}, ...file.env || {} }
1091
- });
1092
- }
1093
- return this.add(file);
954
+ var EventEmitter = class {
955
+ constructor() {
956
+ this.#emitter.setMaxListeners(100);
1094
957
  }
1095
- async addIndexes({ root, extName = ".ts", meta, options = {} }) {
1096
- const files = getIndexes(root, extName, options);
1097
- if (!files) {
1098
- return void 0;
1099
- }
1100
- return await Promise.all(
1101
- files.map((file) => {
1102
- return this.addOrAppend({
1103
- ...file,
1104
- meta: meta ? meta : file.meta
1105
- });
1106
- })
1107
- );
958
+ #emitter = new events.EventEmitter();
959
+ emit(eventName, ...eventArg) {
960
+ this.#emitter.emit(eventName, ...eventArg);
1108
961
  }
1109
- getCacheByUUID(UUID) {
1110
- let cache;
1111
- this.#cache.forEach((files) => {
1112
- cache = files.find((item) => item.id === UUID);
1113
- });
1114
- return cache;
962
+ on(eventName, handler) {
963
+ this.#emitter.on(eventName, handler);
1115
964
  }
1116
- get(path5) {
1117
- return this.#cache.get(path5);
965
+ off(eventName, handler) {
966
+ this.#emitter.off(eventName, handler);
1118
967
  }
1119
- remove(path5) {
1120
- const cacheItem = this.get(path5);
1121
- if (!cacheItem) {
1122
- return;
1123
- }
1124
- this.#cache.delete(path5);
968
+ removeAll() {
969
+ this.#emitter.removeAllListeners();
1125
970
  }
1126
- async write(...params) {
1127
- if (!this.#isWriting) {
1128
- this.#isWriting = true;
1129
- const text = await write(...params);
1130
- this.#isWriting = false;
1131
- return text;
1132
- }
1133
- await timeout(this.#timeout);
1134
- return this.write(...params);
971
+ };
972
+ var Queue = class {
973
+ #queue = [];
974
+ eventEmitter = new EventEmitter();
975
+ #workerCount = 0;
976
+ #maxParallel;
977
+ #debug = false;
978
+ constructor(maxParallel, debug = false) {
979
+ this.#maxParallel = maxParallel;
980
+ this.#debug = debug;
1135
981
  }
1136
- async read(...params) {
1137
- return read(...params);
982
+ run(job, options = { controller: new AbortController(), name: crypto2__default.default.randomUUID(), description: "" }) {
983
+ return new Promise((resolve2, reject) => {
984
+ const item = { reject, resolve: resolve2, job, name: options.name, description: options.description || options.name };
985
+ options.controller?.signal.addEventListener("abort", () => {
986
+ this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
987
+ reject("Aborted");
988
+ });
989
+ this.#queue.push(item);
990
+ this.#work();
991
+ });
1138
992
  }
1139
- // statics
1140
- static getSource(file) {
1141
- return createFileSource(file);
993
+ runSync(job, options = { controller: new AbortController(), name: crypto2__default.default.randomUUID(), description: "" }) {
994
+ new Promise((resolve2, reject) => {
995
+ const item = { reject, resolve: resolve2, job, name: options.name, description: options.description || options.name };
996
+ options.controller?.signal.addEventListener("abort", () => {
997
+ this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
998
+ });
999
+ this.#queue.push(item);
1000
+ this.#work();
1001
+ });
1142
1002
  }
1143
- static combineFiles(files) {
1144
- return combineFiles(files);
1003
+ get hasJobs() {
1004
+ return this.#workerCount > 0 || this.#queue.length > 0;
1145
1005
  }
1146
- static getMode(path5) {
1147
- if (!path5) {
1148
- return "directory";
1149
- }
1150
- return path4.extname(path5) ? "file" : "directory";
1006
+ get count() {
1007
+ return this.#workerCount;
1151
1008
  }
1152
- };
1153
-
1154
- // src/managers/pluginManager/executeStrategies.ts
1155
- function hookSeq(promises) {
1156
- return promises.reduce(
1157
- (promise, func) => {
1158
- if (!func || typeof func !== "function") {
1159
- throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
1009
+ #work() {
1010
+ if (this.#workerCount >= this.#maxParallel) {
1011
+ return;
1012
+ }
1013
+ this.#workerCount++;
1014
+ let entry;
1015
+ while (entry = this.#queue.shift()) {
1016
+ const { reject, resolve: resolve2, job, name, description } = entry;
1017
+ if (this.#debug) {
1018
+ perf_hooks.performance.mark(name + "_start");
1160
1019
  }
1161
- return promise.then((result) => {
1162
- const calledFunc = func();
1163
- if (calledFunc) {
1164
- return calledFunc.then(Array.prototype.concat.bind(result));
1020
+ job().then((result) => {
1021
+ this.eventEmitter.emit("jobDone", result);
1022
+ resolve2(result);
1023
+ if (this.#debug) {
1024
+ perf_hooks.performance.mark(name + "_stop");
1025
+ perf_hooks.performance.measure(description, name + "_start", name + "_stop");
1165
1026
  }
1027
+ }).catch((err) => {
1028
+ this.eventEmitter.emit("jobFailed", err);
1029
+ reject(err);
1166
1030
  });
1167
- },
1168
- Promise.resolve([])
1169
- );
1170
- }
1171
- var executeStrategies = {
1172
- hookSeq
1031
+ }
1032
+ this.#workerCount--;
1033
+ }
1173
1034
  };
1174
1035
 
1175
- // src/managers/pluginManager/ParallelPluginError.ts
1036
+ // src/utils/uniqueName.ts
1037
+ function setUniqueName(originalName, data) {
1038
+ let used = data[originalName] || 0;
1039
+ if (used) {
1040
+ data[originalName] = ++used;
1041
+ return originalName;
1042
+ }
1043
+ data[originalName] = 1;
1044
+ return originalName;
1045
+ }
1046
+
1047
+ // src/errors.ts
1048
+ var PluginError = class extends Error {
1049
+ pluginManager;
1050
+ cause;
1051
+ constructor(message, options) {
1052
+ super(message, { cause: options.cause });
1053
+ this.name = "PluginError";
1054
+ this.cause = options.cause;
1055
+ this.pluginManager = options.pluginManager;
1056
+ }
1057
+ };
1176
1058
  var ParallelPluginError = class extends Error {
1177
1059
  errors = [];
1178
1060
  pluginManager;
@@ -1197,21 +1079,55 @@ var ParallelPluginError = class extends Error {
1197
1079
  })?.cause;
1198
1080
  }
1199
1081
  };
1200
-
1201
- // src/managers/pluginManager/PluginError.ts
1202
- var PluginError = class extends Error {
1203
- pluginManager;
1204
- cause;
1082
+ var SummaryError = class extends Error {
1083
+ summary;
1205
1084
  constructor(message, options) {
1206
1085
  super(message, { cause: options.cause });
1207
- this.name = "PluginError";
1208
- this.cause = options.cause;
1209
- this.pluginManager = options.pluginManager;
1086
+ this.name = "SummaryError";
1087
+ this.summary = options.summary || [];
1088
+ }
1089
+ };
1090
+ var Warning = class extends Error {
1091
+ constructor(message, options) {
1092
+ super(message, { cause: options?.cause });
1093
+ this.name = "Warning";
1210
1094
  }
1211
1095
  };
1212
- function createPlugin(factory) {
1096
+ var ValidationPluginError = class extends Error {
1097
+ };
1098
+
1099
+ // src/utils/cache.ts
1100
+ function createPluginCache(Store = /* @__PURE__ */ Object.create(null)) {
1101
+ return {
1102
+ set(id, value) {
1103
+ Store[id] = [0, value];
1104
+ },
1105
+ get(id) {
1106
+ const item = Store[id];
1107
+ if (!item) {
1108
+ return null;
1109
+ }
1110
+ item[0] = 0;
1111
+ return item[1];
1112
+ },
1113
+ has(id) {
1114
+ const item = Store[id];
1115
+ if (!item) {
1116
+ return false;
1117
+ }
1118
+ item[0] = 0;
1119
+ return true;
1120
+ },
1121
+ delete(id) {
1122
+ return delete Store[id];
1123
+ }
1124
+ };
1125
+ }
1126
+
1127
+ // src/plugin.ts
1128
+ function createPlugin(factory2) {
1213
1129
  return (options) => {
1214
- return factory(options);
1130
+ return factory2(options);
1215
1131
  };
1216
1132
  }
1217
1133
  var pluginName = "core";
@@ -1237,14 +1153,11 @@ var definePlugin = createPlugin((options) => {
1237
1153
  fileManager,
1238
1154
  pluginManager,
1239
1155
  async addFile(...files) {
1240
- return Promise.all(
1241
- files.map((file) => {
1242
- if (file.override) {
1243
- return fileManager.add(file);
1244
- }
1245
- return fileManager.addOrAppend(file);
1246
- })
1247
- );
1156
+ const resolvedFiles = await fileManager.add(...files);
1157
+ if (!Array.isArray(resolvedFiles)) {
1158
+ return [resolvedFiles];
1159
+ }
1160
+ return resolvedFiles;
1248
1161
  },
1249
1162
  resolvePath,
1250
1163
  resolveName,
@@ -1261,52 +1174,49 @@ var definePlugin = createPlugin((options) => {
1261
1174
  };
1262
1175
  });
1263
1176
 
1264
- // src/types.ts
1265
- var LogLevel = {
1266
- silent: "silent",
1267
- info: "info",
1268
- debug: "debug"
1269
- };
1177
+ // src/utils/executeStrategies.ts
1178
+ function hookSeq(promises) {
1179
+ return promises.reduce(
1180
+ (promise, func) => {
1181
+ if (!func || typeof func !== "function") {
1182
+ throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
1183
+ }
1184
+ return promise.then((result) => {
1185
+ const calledFunc = func();
1186
+ if (calledFunc) {
1187
+ return calledFunc.then(Array.prototype.concat.bind(result));
1188
+ }
1189
+ });
1190
+ },
1191
+ Promise.resolve([])
1192
+ );
1193
+ }
1270
1194
 
1271
- // src/managers/pluginManager/pluginParser.ts
1272
- function pluginParser(plugin, pluginManager, context) {
1273
- const usedPluginNames = pluginManager.usedPluginNames;
1274
- setUniqueName(plugin.name, usedPluginNames);
1275
- const key = plugin.key || [plugin.kind, plugin.name, usedPluginNames[plugin.name]].filter(Boolean);
1276
- if (plugin.name !== "core" && usedPluginNames[plugin.name] >= 2) {
1277
- pluginManager.logger.warn("Using multiple of the same plugin is an experimental feature");
1278
- }
1279
- if (!plugin.transform) {
1280
- plugin.transform = function transform(code) {
1281
- return code;
1282
- };
1195
+ // src/PromiseManager.ts
1196
+ var PromiseManager = class {
1197
+ #options = {};
1198
+ constructor(options = {}) {
1199
+ this.#options = options;
1200
+ return this;
1283
1201
  }
1284
- if (plugin.api && typeof plugin.api === "function") {
1285
- const api = plugin.api.call(context);
1286
- return {
1287
- ...plugin,
1288
- key,
1289
- api
1290
- };
1202
+ run(strategy, promises) {
1203
+ if (strategy === "seq") {
1204
+ return hookSeq(promises);
1205
+ }
1206
+ throw new Error(`${strategy} not implemented`);
1291
1207
  }
1292
- return {
1293
- ...plugin,
1294
- key
1295
- };
1208
+ };
1209
+ function isPromise(result) {
1210
+ return !!result && typeof result?.then === "function";
1211
+ }
1212
+ function isPromiseFulfilledResult(result) {
1213
+ return result.status === "fulfilled";
1214
+ }
1215
+ function isPromiseRejectedResult(result) {
1216
+ return result.status === "rejected";
1296
1217
  }
1297
1218
 
1298
- // src/managers/pluginManager/PluginManager.ts
1299
- var hookNames = {
1300
- validate: 1,
1301
- buildStart: 1,
1302
- resolvePath: 1,
1303
- resolveName: 1,
1304
- load: 1,
1305
- transform: 1,
1306
- writeFile: 1,
1307
- buildEnd: 1
1308
- };
1309
- var hooks = Object.keys(hookNames);
1219
+ // src/PluginManager.ts
1310
1220
  var PluginManager = class {
1311
1221
  plugins;
1312
1222
  fileManager;
@@ -1315,11 +1225,13 @@ var PluginManager = class {
1315
1225
  executed = [];
1316
1226
  logger;
1317
1227
  #core;
1318
- usedPluginNames = {};
1228
+ #usedPluginNames = {};
1229
+ #promiseManager;
1319
1230
  constructor(config, options) {
1320
1231
  this.logger = options.logger;
1321
1232
  this.queue = new Queue(100, this.logger.logLevel === LogLevel.debug);
1322
1233
  this.fileManager = new FileManager({ task: options.task, queue: this.queue, timeout: options.writeTimeout });
1234
+ this.#promiseManager = new PromiseManager();
1323
1235
  const plugins = config.plugins || [];
1324
1236
  const core = definePlugin({
1325
1237
  config,
@@ -1330,9 +1242,9 @@ var PluginManager = class {
1330
1242
  resolveName: this.resolveName.bind(this),
1331
1243
  getPlugins: this.#getSortedPlugins.bind(this)
1332
1244
  });
1333
- this.#core = pluginParser(core, this, core.api.call(null));
1245
+ this.#core = this.#parse(core, this, core.api.call(null));
1334
1246
  this.plugins = [this.#core, ...plugins].map((plugin) => {
1335
- return pluginParser(plugin, this, this.#core.api);
1247
+ return this.#parse(plugin, this, this.#core.api);
1336
1248
  });
1337
1249
  return this;
1338
1250
  }
@@ -1538,7 +1450,7 @@ Names: ${JSON.stringify(names, void 0, 2)}`
1538
1450
  plugin
1539
1451
  });
1540
1452
  });
1541
- return executeStrategies.hookSeq(promises);
1453
+ return this.#promiseManager.run("seq", promises);
1542
1454
  }
1543
1455
  #getSortedPlugins(hookName) {
1544
1456
  const plugins = [...this.plugins].filter((plugin) => plugin.name !== "core");
@@ -1677,35 +1589,52 @@ Names: ${JSON.stringify(names, void 0, 2)}`
1677
1589
  this.eventEmitter.emit("error", pluginError);
1678
1590
  throw pluginError;
1679
1591
  }
1592
+ #parse(plugin, pluginManager, context) {
1593
+ const usedPluginNames = pluginManager.#usedPluginNames;
1594
+ setUniqueName(plugin.name, usedPluginNames);
1595
+ const key = plugin.key || [plugin.kind, plugin.name, usedPluginNames[plugin.name]].filter(Boolean);
1596
+ if (plugin.name !== "core" && usedPluginNames[plugin.name] >= 2) {
1597
+ pluginManager.logger.warn("Using multiple of the same plugin is an experimental feature");
1598
+ }
1599
+ if (!plugin.transform) {
1600
+ plugin.transform = function transform(code) {
1601
+ return code;
1602
+ };
1603
+ }
1604
+ if (plugin.api && typeof plugin.api === "function") {
1605
+ const api = plugin.api.call(context);
1606
+ return {
1607
+ ...plugin,
1608
+ key,
1609
+ api
1610
+ };
1611
+ }
1612
+ return {
1613
+ ...plugin,
1614
+ key
1615
+ };
1616
+ }
1617
+ static getDependedPlugins(plugins, dependedPluginNames) {
1618
+ let pluginNames = [];
1619
+ if (typeof dependedPluginNames === "string") {
1620
+ pluginNames = [dependedPluginNames];
1621
+ } else {
1622
+ pluginNames = dependedPluginNames;
1623
+ }
1624
+ return pluginNames.map((pluginName2) => {
1625
+ const plugin = plugins.find((plugin2) => plugin2.name === pluginName2);
1626
+ if (!plugin) {
1627
+ throw new ValidationPluginError(`This plugin depends on the ${pluginName2} plugin.`);
1628
+ }
1629
+ return plugin;
1630
+ });
1631
+ }
1632
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
1633
+ static get hooks() {
1634
+ return ["validate", "buildStart", "resolvePath", "resolveName", "load", "transform", "writeFile", "buildEnd"];
1635
+ }
1680
1636
  };
1681
1637
 
1682
- // src/managers/pluginManager/validate.ts
1683
- var ValidationPluginError = class extends Error {
1684
- };
1685
- function getDependedPlugins(plugins, dependedPluginNames) {
1686
- let pluginNames = [];
1687
- if (typeof dependedPluginNames === "string") {
1688
- pluginNames = [dependedPluginNames];
1689
- } else {
1690
- pluginNames = dependedPluginNames;
1691
- }
1692
- return pluginNames.map((pluginName2) => {
1693
- const plugin = plugins.find((plugin2) => plugin2.name === pluginName2);
1694
- if (!plugin) {
1695
- throw new ValidationPluginError(`This plugin depends on the ${pluginName2} plugin.`);
1696
- }
1697
- return plugin;
1698
- });
1699
- }
1700
-
1701
- // src/config.ts
1702
- function defineConfig(options) {
1703
- return options;
1704
- }
1705
- function isInputPath(result) {
1706
- return !!result && "path" in result;
1707
- }
1708
-
1709
1638
  // src/build.ts
1710
1639
  async function transformReducer(_previousCode, result, _plugin) {
1711
1640
  return result;
@@ -1818,7 +1747,7 @@ ${code}`);
1818
1747
  return { files: fileManager.files.map((file) => ({ ...file, source: FileManager.getSource(file) })), pluginManager };
1819
1748
  }
1820
1749
 
1821
- // src/generators/Generator.ts
1750
+ // src/Generator.ts
1822
1751
  var Generator = class {
1823
1752
  #options = {};
1824
1753
  #context = {};
@@ -1842,10 +1771,6 @@ var Generator = class {
1842
1771
  }
1843
1772
  };
1844
1773
 
1845
- // src/generators/SchemaGenerator.ts
1846
- var SchemaGenerator = class extends Generator {
1847
- };
1848
-
1849
1774
  // ../../node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js
1850
1775
  var Node = class {
1851
1776
  value;
@@ -2220,58 +2145,33 @@ var PackageManager = class _PackageManager {
2220
2145
  }
2221
2146
  };
2222
2147
 
2148
+ // src/SchemaGenerator.ts
2149
+ var SchemaGenerator = class extends Generator {
2150
+ };
2151
+
2223
2152
  // src/index.ts
2224
2153
  var src_default = build;
2225
2154
 
2226
- Object.defineProperty(exports, 'pc', {
2227
- enumerable: true,
2228
- get: function () { return pc3__default.default; }
2229
- });
2230
2155
  exports.FileManager = FileManager;
2231
- exports.FunctionParams = FunctionParams;
2232
2156
  exports.Generator = Generator;
2233
- exports.LogLevel = LogLevel;
2234
2157
  exports.PackageManager = PackageManager;
2235
2158
  exports.ParallelPluginError = ParallelPluginError;
2236
2159
  exports.PluginError = PluginError;
2237
2160
  exports.PluginManager = PluginManager;
2238
- exports.Queue = Queue;
2161
+ exports.PromiseManager = PromiseManager;
2239
2162
  exports.SchemaGenerator = SchemaGenerator;
2240
2163
  exports.SummaryError = SummaryError;
2241
- exports.TreeNode = TreeNode;
2242
- exports.URLPath = URLPath;
2243
2164
  exports.ValidationPluginError = ValidationPluginError;
2244
2165
  exports.Warning = Warning;
2245
2166
  exports.build = build;
2246
- exports.clean = clean;
2247
- exports.createJSDocBlockText = createJSDocBlockText;
2248
- exports.createLogger = createLogger;
2249
2167
  exports.createPlugin = createPlugin;
2250
- exports.createPluginCache = createPluginCache;
2251
2168
  exports.default = src_default;
2252
2169
  exports.defineConfig = defineConfig;
2253
- exports.executeStrategies = executeStrategies;
2254
- exports.getDependedPlugins = getDependedPlugins;
2255
- exports.getRelativePath = getRelativePath;
2256
- exports.getUniqueName = getUniqueName;
2257
- exports.hooks = hooks;
2258
2170
  exports.isInputPath = isInputPath;
2259
2171
  exports.isPromise = isPromise;
2260
2172
  exports.isPromiseFulfilledResult = isPromiseFulfilledResult;
2261
2173
  exports.isPromiseRejectedResult = isPromiseRejectedResult;
2262
2174
  exports.name = pluginName;
2263
- exports.nameSorter = nameSorter;
2264
2175
  exports.pluginName = pluginName;
2265
- exports.randomColour = randomColour;
2266
- exports.randomPicoColour = randomPicoColour;
2267
- exports.read = read;
2268
- exports.readSync = readSync;
2269
- exports.renderTemplate = renderTemplate;
2270
- exports.setUniqueName = setUniqueName;
2271
- exports.throttle = throttle;
2272
- exports.timeout = timeout;
2273
- exports.transformers = transformers;
2274
- exports.uniqueIdFactory = uniqueIdFactory;
2275
- exports.write = write;
2276
2176
  //# sourceMappingURL=out.js.map
2277
2177
  //# sourceMappingURL=index.cjs.map