@spikers/next-openapi-json-generator 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2070 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __commonJS = (cb, mod) => function __require2() {
14
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // node_modules/balanced-match/index.js
34
+ var require_balanced_match = __commonJS({
35
+ "node_modules/balanced-match/index.js"(exports, module) {
36
+ "use strict";
37
+ module.exports = balanced;
38
+ function balanced(a, b, str) {
39
+ if (a instanceof RegExp) a = maybeMatch(a, str);
40
+ if (b instanceof RegExp) b = maybeMatch(b, str);
41
+ var r = range(a, b, str);
42
+ return r && {
43
+ start: r[0],
44
+ end: r[1],
45
+ pre: str.slice(0, r[0]),
46
+ body: str.slice(r[0] + a.length, r[1]),
47
+ post: str.slice(r[1] + b.length)
48
+ };
49
+ }
50
+ function maybeMatch(reg, str) {
51
+ var m = str.match(reg);
52
+ return m ? m[0] : null;
53
+ }
54
+ balanced.range = range;
55
+ function range(a, b, str) {
56
+ var begs, beg, left, right, result;
57
+ var ai = str.indexOf(a);
58
+ var bi = str.indexOf(b, ai + 1);
59
+ var i = ai;
60
+ if (ai >= 0 && bi > 0) {
61
+ if (a === b) {
62
+ return [ai, bi];
63
+ }
64
+ begs = [];
65
+ left = str.length;
66
+ while (i >= 0 && !result) {
67
+ if (i == ai) {
68
+ begs.push(i);
69
+ ai = str.indexOf(a, i + 1);
70
+ } else if (begs.length == 1) {
71
+ result = [begs.pop(), bi];
72
+ } else {
73
+ beg = begs.pop();
74
+ if (beg < left) {
75
+ left = beg;
76
+ right = bi;
77
+ }
78
+ bi = str.indexOf(b, i + 1);
79
+ }
80
+ i = ai < bi && ai >= 0 ? ai : bi;
81
+ }
82
+ if (begs.length) {
83
+ result = [left, right];
84
+ }
85
+ }
86
+ return result;
87
+ }
88
+ }
89
+ });
90
+
91
+ // node_modules/brace-expansion/index.js
92
+ var require_brace_expansion = __commonJS({
93
+ "node_modules/brace-expansion/index.js"(exports, module) {
94
+ "use strict";
95
+ var balanced = require_balanced_match();
96
+ module.exports = expandTop;
97
+ var escSlash = "\0SLASH" + Math.random() + "\0";
98
+ var escOpen = "\0OPEN" + Math.random() + "\0";
99
+ var escClose = "\0CLOSE" + Math.random() + "\0";
100
+ var escComma = "\0COMMA" + Math.random() + "\0";
101
+ var escPeriod = "\0PERIOD" + Math.random() + "\0";
102
+ function numeric(str) {
103
+ return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
104
+ }
105
+ function escapeBraces(str) {
106
+ return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
107
+ }
108
+ function unescapeBraces(str) {
109
+ return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
110
+ }
111
+ function parseCommaParts(str) {
112
+ if (!str)
113
+ return [""];
114
+ var parts = [];
115
+ var m = balanced("{", "}", str);
116
+ if (!m)
117
+ return str.split(",");
118
+ var pre = m.pre;
119
+ var body = m.body;
120
+ var post = m.post;
121
+ var p = pre.split(",");
122
+ p[p.length - 1] += "{" + body + "}";
123
+ var postParts = parseCommaParts(post);
124
+ if (post.length) {
125
+ p[p.length - 1] += postParts.shift();
126
+ p.push.apply(p, postParts);
127
+ }
128
+ parts.push.apply(parts, p);
129
+ return parts;
130
+ }
131
+ function expandTop(str) {
132
+ if (!str)
133
+ return [];
134
+ if (str.substr(0, 2) === "{}") {
135
+ str = "\\{\\}" + str.substr(2);
136
+ }
137
+ return expand2(escapeBraces(str), true).map(unescapeBraces);
138
+ }
139
+ function embrace(str) {
140
+ return "{" + str + "}";
141
+ }
142
+ function isPadded(el) {
143
+ return /^-?0\d/.test(el);
144
+ }
145
+ function lte(i, y) {
146
+ return i <= y;
147
+ }
148
+ function gte(i, y) {
149
+ return i >= y;
150
+ }
151
+ function expand2(str, isTop) {
152
+ var expansions = [];
153
+ var m = balanced("{", "}", str);
154
+ if (!m) return [str];
155
+ var pre = m.pre;
156
+ var post = m.post.length ? expand2(m.post, false) : [""];
157
+ if (/\$$/.test(m.pre)) {
158
+ for (var k = 0; k < post.length; k++) {
159
+ var expansion = pre + "{" + m.body + "}" + post[k];
160
+ expansions.push(expansion);
161
+ }
162
+ } else {
163
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
164
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
165
+ var isSequence = isNumericSequence || isAlphaSequence;
166
+ var isOptions = m.body.indexOf(",") >= 0;
167
+ if (!isSequence && !isOptions) {
168
+ if (m.post.match(/,.*\}/)) {
169
+ str = m.pre + "{" + m.body + escClose + m.post;
170
+ return expand2(str);
171
+ }
172
+ return [str];
173
+ }
174
+ var n;
175
+ if (isSequence) {
176
+ n = m.body.split(/\.\./);
177
+ } else {
178
+ n = parseCommaParts(m.body);
179
+ if (n.length === 1) {
180
+ n = expand2(n[0], false).map(embrace);
181
+ if (n.length === 1) {
182
+ return post.map(function(p) {
183
+ return m.pre + n[0] + p;
184
+ });
185
+ }
186
+ }
187
+ }
188
+ var N;
189
+ if (isSequence) {
190
+ var x = numeric(n[0]);
191
+ var y = numeric(n[1]);
192
+ var width = Math.max(n[0].length, n[1].length);
193
+ var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
194
+ var test = lte;
195
+ var reverse = y < x;
196
+ if (reverse) {
197
+ incr *= -1;
198
+ test = gte;
199
+ }
200
+ var pad = n.some(isPadded);
201
+ N = [];
202
+ for (var i = x; test(i, y); i += incr) {
203
+ var c;
204
+ if (isAlphaSequence) {
205
+ c = String.fromCharCode(i);
206
+ if (c === "\\")
207
+ c = "";
208
+ } else {
209
+ c = String(i);
210
+ if (pad) {
211
+ var need = width - c.length;
212
+ if (need > 0) {
213
+ var z = new Array(need + 1).join("0");
214
+ if (i < 0)
215
+ c = "-" + z + c.slice(1);
216
+ else
217
+ c = z + c;
218
+ }
219
+ }
220
+ }
221
+ N.push(c);
222
+ }
223
+ } else {
224
+ N = [];
225
+ for (var j = 0; j < n.length; j++) {
226
+ N.push.apply(N, expand2(n[j], false));
227
+ }
228
+ }
229
+ for (var j = 0; j < N.length; j++) {
230
+ for (var k = 0; k < post.length; k++) {
231
+ var expansion = pre + N[j] + post[k];
232
+ if (!isTop || isSequence || expansion)
233
+ expansions.push(expansion);
234
+ }
235
+ }
236
+ }
237
+ return expansions;
238
+ }
239
+ }
240
+ });
241
+
242
+ // src/core/generateOpenApiSpec.ts
243
+ import path6 from "node:path";
244
+
245
+ // node_modules/@omer-x/package-metadata/dist/index.js
246
+ import fs from "node:fs";
247
+ import path from "node:path";
248
+ function capitalize(text) {
249
+ return text.split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
250
+ }
251
+ function getScopeName(packageName) {
252
+ const scopeRegex = /^@([^/]+)\//;
253
+ const match2 = packageName.match(scopeRegex);
254
+ return match2 ? `@${match2[1]}` : null;
255
+ }
256
+ function getModuleName(packageName) {
257
+ return packageName.split("/").pop() ?? null;
258
+ }
259
+ function getPackageMetadata() {
260
+ const filePath = path.resolve(process.cwd(), "package.json");
261
+ const content = fs.readFileSync(filePath, "utf-8");
262
+ const data = JSON.parse(content);
263
+ const packageName = data.name ?? "unnamed-app";
264
+ const moduleName = getModuleName(packageName) ?? "unknown-package";
265
+ return {
266
+ scope: getScopeName(packageName),
267
+ packageName,
268
+ moduleName,
269
+ serviceName: capitalize(moduleName.replace(/-/g, " ")),
270
+ version: data.version ?? "1.0.0"
271
+ };
272
+ }
273
+
274
+ // src/utils/object.ts
275
+ function omit(object, ...keys) {
276
+ return Object.fromEntries(Object.entries(object).filter(([key]) => !keys.includes(key)));
277
+ }
278
+
279
+ // src/core/clearUnusedSchemas.ts
280
+ function countReferences(schemaName, source) {
281
+ return (source.match(new RegExp(`"#/components/schemas/${schemaName}"`, "g")) ?? []).length;
282
+ }
283
+ function clearUnusedSchemas({
284
+ paths,
285
+ components
286
+ }) {
287
+ if (!components.schemas) return { paths, components };
288
+ const stringifiedPaths = JSON.stringify(paths);
289
+ const stringifiedSchemas = Object.fromEntries(Object.entries(components.schemas).map(([schemaName, schema]) => {
290
+ return [schemaName, JSON.stringify(schema)];
291
+ }));
292
+ return {
293
+ paths,
294
+ components: {
295
+ ...components,
296
+ schemas: Object.fromEntries(Object.entries(components.schemas).filter(([schemaName]) => {
297
+ const otherSchemas = omit(stringifiedSchemas, schemaName);
298
+ return countReferences(schemaName, stringifiedPaths) > 0 || countReferences(schemaName, Object.values(otherSchemas).join("")) > 0;
299
+ }))
300
+ }
301
+ };
302
+ }
303
+
304
+ // src/core/dir.ts
305
+ import { constants } from "fs";
306
+ import fs2 from "fs/promises";
307
+ import path3 from "node:path";
308
+
309
+ // node_modules/minimatch/dist/esm/index.js
310
+ var import_brace_expansion = __toESM(require_brace_expansion(), 1);
311
+
312
+ // node_modules/minimatch/dist/esm/assert-valid-pattern.js
313
+ var MAX_PATTERN_LENGTH = 1024 * 64;
314
+ var assertValidPattern = (pattern) => {
315
+ if (typeof pattern !== "string") {
316
+ throw new TypeError("invalid pattern");
317
+ }
318
+ if (pattern.length > MAX_PATTERN_LENGTH) {
319
+ throw new TypeError("pattern is too long");
320
+ }
321
+ };
322
+
323
+ // node_modules/minimatch/dist/esm/brace-expressions.js
324
+ var posixClasses = {
325
+ "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
326
+ "[:alpha:]": ["\\p{L}\\p{Nl}", true],
327
+ "[:ascii:]": ["\\x00-\\x7f", false],
328
+ "[:blank:]": ["\\p{Zs}\\t", true],
329
+ "[:cntrl:]": ["\\p{Cc}", true],
330
+ "[:digit:]": ["\\p{Nd}", true],
331
+ "[:graph:]": ["\\p{Z}\\p{C}", true, true],
332
+ "[:lower:]": ["\\p{Ll}", true],
333
+ "[:print:]": ["\\p{C}", true],
334
+ "[:punct:]": ["\\p{P}", true],
335
+ "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
336
+ "[:upper:]": ["\\p{Lu}", true],
337
+ "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
338
+ "[:xdigit:]": ["A-Fa-f0-9", false]
339
+ };
340
+ var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
341
+ var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
342
+ var rangesToString = (ranges) => ranges.join("");
343
+ var parseClass = (glob, position) => {
344
+ const pos = position;
345
+ if (glob.charAt(pos) !== "[") {
346
+ throw new Error("not in a brace expression");
347
+ }
348
+ const ranges = [];
349
+ const negs = [];
350
+ let i = pos + 1;
351
+ let sawStart = false;
352
+ let uflag = false;
353
+ let escaping = false;
354
+ let negate = false;
355
+ let endPos = pos;
356
+ let rangeStart = "";
357
+ WHILE: while (i < glob.length) {
358
+ const c = glob.charAt(i);
359
+ if ((c === "!" || c === "^") && i === pos + 1) {
360
+ negate = true;
361
+ i++;
362
+ continue;
363
+ }
364
+ if (c === "]" && sawStart && !escaping) {
365
+ endPos = i + 1;
366
+ break;
367
+ }
368
+ sawStart = true;
369
+ if (c === "\\") {
370
+ if (!escaping) {
371
+ escaping = true;
372
+ i++;
373
+ continue;
374
+ }
375
+ }
376
+ if (c === "[" && !escaping) {
377
+ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
378
+ if (glob.startsWith(cls, i)) {
379
+ if (rangeStart) {
380
+ return ["$.", false, glob.length - pos, true];
381
+ }
382
+ i += cls.length;
383
+ if (neg)
384
+ negs.push(unip);
385
+ else
386
+ ranges.push(unip);
387
+ uflag = uflag || u;
388
+ continue WHILE;
389
+ }
390
+ }
391
+ }
392
+ escaping = false;
393
+ if (rangeStart) {
394
+ if (c > rangeStart) {
395
+ ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
396
+ } else if (c === rangeStart) {
397
+ ranges.push(braceEscape(c));
398
+ }
399
+ rangeStart = "";
400
+ i++;
401
+ continue;
402
+ }
403
+ if (glob.startsWith("-]", i + 1)) {
404
+ ranges.push(braceEscape(c + "-"));
405
+ i += 2;
406
+ continue;
407
+ }
408
+ if (glob.startsWith("-", i + 1)) {
409
+ rangeStart = c;
410
+ i += 2;
411
+ continue;
412
+ }
413
+ ranges.push(braceEscape(c));
414
+ i++;
415
+ }
416
+ if (endPos < i) {
417
+ return ["", false, 0, false];
418
+ }
419
+ if (!ranges.length && !negs.length) {
420
+ return ["$.", false, glob.length - pos, true];
421
+ }
422
+ if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
423
+ const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
424
+ return [regexpEscape(r), false, endPos - pos, false];
425
+ }
426
+ const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
427
+ const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
428
+ const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
429
+ return [comb, uflag, endPos - pos, true];
430
+ };
431
+
432
+ // node_modules/minimatch/dist/esm/unescape.js
433
+ var unescape = (s, { windowsPathsNoEscape = false } = {}) => {
434
+ return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
435
+ };
436
+
437
+ // node_modules/minimatch/dist/esm/ast.js
438
+ var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
439
+ var isExtglobType = (c) => types.has(c);
440
+ var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
441
+ var startNoDot = "(?!\\.)";
442
+ var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
443
+ var justDots = /* @__PURE__ */ new Set(["..", "."]);
444
+ var reSpecials = new Set("().*{}+?[]^$\\!");
445
+ var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
446
+ var qmark = "[^/]";
447
+ var star = qmark + "*?";
448
+ var starNoEmpty = qmark + "+?";
449
+ var AST = class _AST {
450
+ type;
451
+ #root;
452
+ #hasMagic;
453
+ #uflag = false;
454
+ #parts = [];
455
+ #parent;
456
+ #parentIndex;
457
+ #negs;
458
+ #filledNegs = false;
459
+ #options;
460
+ #toString;
461
+ // set to true if it's an extglob with no children
462
+ // (which really means one child of '')
463
+ #emptyExt = false;
464
+ constructor(type, parent, options = {}) {
465
+ this.type = type;
466
+ if (type)
467
+ this.#hasMagic = true;
468
+ this.#parent = parent;
469
+ this.#root = this.#parent ? this.#parent.#root : this;
470
+ this.#options = this.#root === this ? options : this.#root.#options;
471
+ this.#negs = this.#root === this ? [] : this.#root.#negs;
472
+ if (type === "!" && !this.#root.#filledNegs)
473
+ this.#negs.push(this);
474
+ this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
475
+ }
476
+ get hasMagic() {
477
+ if (this.#hasMagic !== void 0)
478
+ return this.#hasMagic;
479
+ for (const p of this.#parts) {
480
+ if (typeof p === "string")
481
+ continue;
482
+ if (p.type || p.hasMagic)
483
+ return this.#hasMagic = true;
484
+ }
485
+ return this.#hasMagic;
486
+ }
487
+ // reconstructs the pattern
488
+ toString() {
489
+ if (this.#toString !== void 0)
490
+ return this.#toString;
491
+ if (!this.type) {
492
+ return this.#toString = this.#parts.map((p) => String(p)).join("");
493
+ } else {
494
+ return this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")";
495
+ }
496
+ }
497
+ #fillNegs() {
498
+ if (this !== this.#root)
499
+ throw new Error("should only call on root");
500
+ if (this.#filledNegs)
501
+ return this;
502
+ this.toString();
503
+ this.#filledNegs = true;
504
+ let n;
505
+ while (n = this.#negs.pop()) {
506
+ if (n.type !== "!")
507
+ continue;
508
+ let p = n;
509
+ let pp = p.#parent;
510
+ while (pp) {
511
+ for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
512
+ for (const part of n.#parts) {
513
+ if (typeof part === "string") {
514
+ throw new Error("string part in extglob AST??");
515
+ }
516
+ part.copyIn(pp.#parts[i]);
517
+ }
518
+ }
519
+ p = pp;
520
+ pp = p.#parent;
521
+ }
522
+ }
523
+ return this;
524
+ }
525
+ push(...parts) {
526
+ for (const p of parts) {
527
+ if (p === "")
528
+ continue;
529
+ if (typeof p !== "string" && !(p instanceof _AST && p.#parent === this)) {
530
+ throw new Error("invalid part: " + p);
531
+ }
532
+ this.#parts.push(p);
533
+ }
534
+ }
535
+ toJSON() {
536
+ const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())];
537
+ if (this.isStart() && !this.type)
538
+ ret.unshift([]);
539
+ if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) {
540
+ ret.push({});
541
+ }
542
+ return ret;
543
+ }
544
+ isStart() {
545
+ if (this.#root === this)
546
+ return true;
547
+ if (!this.#parent?.isStart())
548
+ return false;
549
+ if (this.#parentIndex === 0)
550
+ return true;
551
+ const p = this.#parent;
552
+ for (let i = 0; i < this.#parentIndex; i++) {
553
+ const pp = p.#parts[i];
554
+ if (!(pp instanceof _AST && pp.type === "!")) {
555
+ return false;
556
+ }
557
+ }
558
+ return true;
559
+ }
560
+ isEnd() {
561
+ if (this.#root === this)
562
+ return true;
563
+ if (this.#parent?.type === "!")
564
+ return true;
565
+ if (!this.#parent?.isEnd())
566
+ return false;
567
+ if (!this.type)
568
+ return this.#parent?.isEnd();
569
+ const pl = this.#parent ? this.#parent.#parts.length : 0;
570
+ return this.#parentIndex === pl - 1;
571
+ }
572
+ copyIn(part) {
573
+ if (typeof part === "string")
574
+ this.push(part);
575
+ else
576
+ this.push(part.clone(this));
577
+ }
578
+ clone(parent) {
579
+ const c = new _AST(this.type, parent);
580
+ for (const p of this.#parts) {
581
+ c.copyIn(p);
582
+ }
583
+ return c;
584
+ }
585
+ static #parseAST(str, ast, pos, opt) {
586
+ let escaping = false;
587
+ let inBrace = false;
588
+ let braceStart = -1;
589
+ let braceNeg = false;
590
+ if (ast.type === null) {
591
+ let i2 = pos;
592
+ let acc2 = "";
593
+ while (i2 < str.length) {
594
+ const c = str.charAt(i2++);
595
+ if (escaping || c === "\\") {
596
+ escaping = !escaping;
597
+ acc2 += c;
598
+ continue;
599
+ }
600
+ if (inBrace) {
601
+ if (i2 === braceStart + 1) {
602
+ if (c === "^" || c === "!") {
603
+ braceNeg = true;
604
+ }
605
+ } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {
606
+ inBrace = false;
607
+ }
608
+ acc2 += c;
609
+ continue;
610
+ } else if (c === "[") {
611
+ inBrace = true;
612
+ braceStart = i2;
613
+ braceNeg = false;
614
+ acc2 += c;
615
+ continue;
616
+ }
617
+ if (!opt.noext && isExtglobType(c) && str.charAt(i2) === "(") {
618
+ ast.push(acc2);
619
+ acc2 = "";
620
+ const ext2 = new _AST(c, ast);
621
+ i2 = _AST.#parseAST(str, ext2, i2, opt);
622
+ ast.push(ext2);
623
+ continue;
624
+ }
625
+ acc2 += c;
626
+ }
627
+ ast.push(acc2);
628
+ return i2;
629
+ }
630
+ let i = pos + 1;
631
+ let part = new _AST(null, ast);
632
+ const parts = [];
633
+ let acc = "";
634
+ while (i < str.length) {
635
+ const c = str.charAt(i++);
636
+ if (escaping || c === "\\") {
637
+ escaping = !escaping;
638
+ acc += c;
639
+ continue;
640
+ }
641
+ if (inBrace) {
642
+ if (i === braceStart + 1) {
643
+ if (c === "^" || c === "!") {
644
+ braceNeg = true;
645
+ }
646
+ } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) {
647
+ inBrace = false;
648
+ }
649
+ acc += c;
650
+ continue;
651
+ } else if (c === "[") {
652
+ inBrace = true;
653
+ braceStart = i;
654
+ braceNeg = false;
655
+ acc += c;
656
+ continue;
657
+ }
658
+ if (isExtglobType(c) && str.charAt(i) === "(") {
659
+ part.push(acc);
660
+ acc = "";
661
+ const ext2 = new _AST(c, part);
662
+ part.push(ext2);
663
+ i = _AST.#parseAST(str, ext2, i, opt);
664
+ continue;
665
+ }
666
+ if (c === "|") {
667
+ part.push(acc);
668
+ acc = "";
669
+ parts.push(part);
670
+ part = new _AST(null, ast);
671
+ continue;
672
+ }
673
+ if (c === ")") {
674
+ if (acc === "" && ast.#parts.length === 0) {
675
+ ast.#emptyExt = true;
676
+ }
677
+ part.push(acc);
678
+ acc = "";
679
+ ast.push(...parts, part);
680
+ return i;
681
+ }
682
+ acc += c;
683
+ }
684
+ ast.type = null;
685
+ ast.#hasMagic = void 0;
686
+ ast.#parts = [str.substring(pos - 1)];
687
+ return i;
688
+ }
689
+ static fromGlob(pattern, options = {}) {
690
+ const ast = new _AST(null, void 0, options);
691
+ _AST.#parseAST(pattern, ast, 0, options);
692
+ return ast;
693
+ }
694
+ // returns the regular expression if there's magic, or the unescaped
695
+ // string if not.
696
+ toMMPattern() {
697
+ if (this !== this.#root)
698
+ return this.#root.toMMPattern();
699
+ const glob = this.toString();
700
+ const [re, body, hasMagic, uflag] = this.toRegExpSource();
701
+ const anyMagic = hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase();
702
+ if (!anyMagic) {
703
+ return body;
704
+ }
705
+ const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");
706
+ return Object.assign(new RegExp(`^${re}$`, flags), {
707
+ _src: re,
708
+ _glob: glob
709
+ });
710
+ }
711
+ get options() {
712
+ return this.#options;
713
+ }
714
+ // returns the string match, the regexp source, whether there's magic
715
+ // in the regexp (so a regular expression is required) and whether or
716
+ // not the uflag is needed for the regular expression (for posix classes)
717
+ // TODO: instead of injecting the start/end at this point, just return
718
+ // the BODY of the regexp, along with the start/end portions suitable
719
+ // for binding the start/end in either a joined full-path makeRe context
720
+ // (where we bind to (^|/), or a standalone matchPart context (where
721
+ // we bind to ^, and not /). Otherwise slashes get duped!
722
+ //
723
+ // In part-matching mode, the start is:
724
+ // - if not isStart: nothing
725
+ // - if traversal possible, but not allowed: ^(?!\.\.?$)
726
+ // - if dots allowed or not possible: ^
727
+ // - if dots possible and not allowed: ^(?!\.)
728
+ // end is:
729
+ // - if not isEnd(): nothing
730
+ // - else: $
731
+ //
732
+ // In full-path matching mode, we put the slash at the START of the
733
+ // pattern, so start is:
734
+ // - if first pattern: same as part-matching mode
735
+ // - if not isStart(): nothing
736
+ // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
737
+ // - if dots allowed or not possible: /
738
+ // - if dots possible and not allowed: /(?!\.)
739
+ // end is:
740
+ // - if last pattern, same as part-matching mode
741
+ // - else nothing
742
+ //
743
+ // Always put the (?:$|/) on negated tails, though, because that has to be
744
+ // there to bind the end of the negated pattern portion, and it's easier to
745
+ // just stick it in now rather than try to inject it later in the middle of
746
+ // the pattern.
747
+ //
748
+ // We can just always return the same end, and leave it up to the caller
749
+ // to know whether it's going to be used joined or in parts.
750
+ // And, if the start is adjusted slightly, can do the same there:
751
+ // - if not isStart: nothing
752
+ // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
753
+ // - if dots allowed or not possible: (?:/|^)
754
+ // - if dots possible and not allowed: (?:/|^)(?!\.)
755
+ //
756
+ // But it's better to have a simpler binding without a conditional, for
757
+ // performance, so probably better to return both start options.
758
+ //
759
+ // Then the caller just ignores the end if it's not the first pattern,
760
+ // and the start always gets applied.
761
+ //
762
+ // But that's always going to be $ if it's the ending pattern, or nothing,
763
+ // so the caller can just attach $ at the end of the pattern when building.
764
+ //
765
+ // So the todo is:
766
+ // - better detect what kind of start is needed
767
+ // - return both flavors of starting pattern
768
+ // - attach $ at the end of the pattern when creating the actual RegExp
769
+ //
770
+ // Ah, but wait, no, that all only applies to the root when the first pattern
771
+ // is not an extglob. If the first pattern IS an extglob, then we need all
772
+ // that dot prevention biz to live in the extglob portions, because eg
773
+ // +(*|.x*) can match .xy but not .yx.
774
+ //
775
+ // So, return the two flavors if it's #root and the first child is not an
776
+ // AST, otherwise leave it to the child AST to handle it, and there,
777
+ // use the (?:^|/) style of start binding.
778
+ //
779
+ // Even simplified further:
780
+ // - Since the start for a join is eg /(?!\.) and the start for a part
781
+ // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
782
+ // or start or whatever) and prepend ^ or / at the Regexp construction.
783
+ toRegExpSource(allowDot) {
784
+ const dot = allowDot ?? !!this.#options.dot;
785
+ if (this.#root === this)
786
+ this.#fillNegs();
787
+ if (!this.type) {
788
+ const noEmpty = this.isStart() && this.isEnd();
789
+ const src = this.#parts.map((p) => {
790
+ const [re, _, hasMagic, uflag] = typeof p === "string" ? _AST.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);
791
+ this.#hasMagic = this.#hasMagic || hasMagic;
792
+ this.#uflag = this.#uflag || uflag;
793
+ return re;
794
+ }).join("");
795
+ let start2 = "";
796
+ if (this.isStart()) {
797
+ if (typeof this.#parts[0] === "string") {
798
+ const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
799
+ if (!dotTravAllowed) {
800
+ const aps = addPatternStart;
801
+ const needNoTrav = (
802
+ // dots are allowed, and the pattern starts with [ or .
803
+ dot && aps.has(src.charAt(0)) || // the pattern starts with \., and then [ or .
804
+ src.startsWith("\\.") && aps.has(src.charAt(2)) || // the pattern starts with \.\., and then [ or .
805
+ src.startsWith("\\.\\.") && aps.has(src.charAt(4))
806
+ );
807
+ const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
808
+ start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
809
+ }
810
+ }
811
+ }
812
+ let end = "";
813
+ if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") {
814
+ end = "(?:$|\\/)";
815
+ }
816
+ const final2 = start2 + src + end;
817
+ return [
818
+ final2,
819
+ unescape(src),
820
+ this.#hasMagic = !!this.#hasMagic,
821
+ this.#uflag
822
+ ];
823
+ }
824
+ const repeated = this.type === "*" || this.type === "+";
825
+ const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
826
+ let body = this.#partsToRegExp(dot);
827
+ if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
828
+ const s = this.toString();
829
+ this.#parts = [s];
830
+ this.type = null;
831
+ this.#hasMagic = void 0;
832
+ return [s, unescape(this.toString()), false, false];
833
+ }
834
+ let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true);
835
+ if (bodyDotAllowed === body) {
836
+ bodyDotAllowed = "";
837
+ }
838
+ if (bodyDotAllowed) {
839
+ body = `(?:${body})(?:${bodyDotAllowed})*?`;
840
+ }
841
+ let final = "";
842
+ if (this.type === "!" && this.#emptyExt) {
843
+ final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;
844
+ } else {
845
+ const close = this.type === "!" ? (
846
+ // !() must match something,but !(x) can match ''
847
+ "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")"
848
+ ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;
849
+ final = start + body + close;
850
+ }
851
+ return [
852
+ final,
853
+ unescape(body),
854
+ this.#hasMagic = !!this.#hasMagic,
855
+ this.#uflag
856
+ ];
857
+ }
858
+ #partsToRegExp(dot) {
859
+ return this.#parts.map((p) => {
860
+ if (typeof p === "string") {
861
+ throw new Error("string type in extglob ast??");
862
+ }
863
+ const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
864
+ this.#uflag = this.#uflag || uflag;
865
+ return re;
866
+ }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
867
+ }
868
+ static #parseGlob(glob, hasMagic, noEmpty = false) {
869
+ let escaping = false;
870
+ let re = "";
871
+ let uflag = false;
872
+ for (let i = 0; i < glob.length; i++) {
873
+ const c = glob.charAt(i);
874
+ if (escaping) {
875
+ escaping = false;
876
+ re += (reSpecials.has(c) ? "\\" : "") + c;
877
+ continue;
878
+ }
879
+ if (c === "\\") {
880
+ if (i === glob.length - 1) {
881
+ re += "\\\\";
882
+ } else {
883
+ escaping = true;
884
+ }
885
+ continue;
886
+ }
887
+ if (c === "[") {
888
+ const [src, needUflag, consumed, magic] = parseClass(glob, i);
889
+ if (consumed) {
890
+ re += src;
891
+ uflag = uflag || needUflag;
892
+ i += consumed - 1;
893
+ hasMagic = hasMagic || magic;
894
+ continue;
895
+ }
896
+ }
897
+ if (c === "*") {
898
+ if (noEmpty && glob === "*")
899
+ re += starNoEmpty;
900
+ else
901
+ re += star;
902
+ hasMagic = true;
903
+ continue;
904
+ }
905
+ if (c === "?") {
906
+ re += qmark;
907
+ hasMagic = true;
908
+ continue;
909
+ }
910
+ re += regExpEscape(c);
911
+ }
912
+ return [re, unescape(glob), !!hasMagic, uflag];
913
+ }
914
+ };
915
+
916
+ // node_modules/minimatch/dist/esm/escape.js
917
+ var escape = (s, { windowsPathsNoEscape = false } = {}) => {
918
+ return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
919
+ };
920
+
921
+ // node_modules/minimatch/dist/esm/index.js
922
+ var minimatch = (p, pattern, options = {}) => {
923
+ assertValidPattern(pattern);
924
+ if (!options.nocomment && pattern.charAt(0) === "#") {
925
+ return false;
926
+ }
927
+ return new Minimatch(pattern, options).match(p);
928
+ };
929
+ var starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
930
+ var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);
931
+ var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);
932
+ var starDotExtTestNocase = (ext2) => {
933
+ ext2 = ext2.toLowerCase();
934
+ return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);
935
+ };
936
+ var starDotExtTestNocaseDot = (ext2) => {
937
+ ext2 = ext2.toLowerCase();
938
+ return (f) => f.toLowerCase().endsWith(ext2);
939
+ };
940
+ var starDotStarRE = /^\*+\.\*+$/;
941
+ var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");
942
+ var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");
943
+ var dotStarRE = /^\.\*+$/;
944
+ var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");
945
+ var starRE = /^\*+$/;
946
+ var starTest = (f) => f.length !== 0 && !f.startsWith(".");
947
+ var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";
948
+ var qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
949
+ var qmarksTestNocase = ([$0, ext2 = ""]) => {
950
+ const noext = qmarksTestNoExt([$0]);
951
+ if (!ext2)
952
+ return noext;
953
+ ext2 = ext2.toLowerCase();
954
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
955
+ };
956
+ var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
957
+ const noext = qmarksTestNoExtDot([$0]);
958
+ if (!ext2)
959
+ return noext;
960
+ ext2 = ext2.toLowerCase();
961
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
962
+ };
963
+ var qmarksTestDot = ([$0, ext2 = ""]) => {
964
+ const noext = qmarksTestNoExtDot([$0]);
965
+ return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
966
+ };
967
+ var qmarksTest = ([$0, ext2 = ""]) => {
968
+ const noext = qmarksTestNoExt([$0]);
969
+ return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
970
+ };
971
+ var qmarksTestNoExt = ([$0]) => {
972
+ const len = $0.length;
973
+ return (f) => f.length === len && !f.startsWith(".");
974
+ };
975
+ var qmarksTestNoExtDot = ([$0]) => {
976
+ const len = $0.length;
977
+ return (f) => f.length === len && f !== "." && f !== "..";
978
+ };
979
+ var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
980
+ var path2 = {
981
+ win32: { sep: "\\" },
982
+ posix: { sep: "/" }
983
+ };
984
+ var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
985
+ minimatch.sep = sep;
986
+ var GLOBSTAR = Symbol("globstar **");
987
+ minimatch.GLOBSTAR = GLOBSTAR;
988
+ var qmark2 = "[^/]";
989
+ var star2 = qmark2 + "*?";
990
+ var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
991
+ var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
992
+ var filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
993
+ minimatch.filter = filter;
994
+ var ext = (a, b = {}) => Object.assign({}, a, b);
995
+ var defaults = (def) => {
996
+ if (!def || typeof def !== "object" || !Object.keys(def).length) {
997
+ return minimatch;
998
+ }
999
+ const orig = minimatch;
1000
+ const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
1001
+ return Object.assign(m, {
1002
+ Minimatch: class Minimatch extends orig.Minimatch {
1003
+ constructor(pattern, options = {}) {
1004
+ super(pattern, ext(def, options));
1005
+ }
1006
+ static defaults(options) {
1007
+ return orig.defaults(ext(def, options)).Minimatch;
1008
+ }
1009
+ },
1010
+ AST: class AST extends orig.AST {
1011
+ /* c8 ignore start */
1012
+ constructor(type, parent, options = {}) {
1013
+ super(type, parent, ext(def, options));
1014
+ }
1015
+ /* c8 ignore stop */
1016
+ static fromGlob(pattern, options = {}) {
1017
+ return orig.AST.fromGlob(pattern, ext(def, options));
1018
+ }
1019
+ },
1020
+ unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
1021
+ escape: (s, options = {}) => orig.escape(s, ext(def, options)),
1022
+ filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
1023
+ defaults: (options) => orig.defaults(ext(def, options)),
1024
+ makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
1025
+ braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
1026
+ match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
1027
+ sep: orig.sep,
1028
+ GLOBSTAR
1029
+ });
1030
+ };
1031
+ minimatch.defaults = defaults;
1032
+ var braceExpand = (pattern, options = {}) => {
1033
+ assertValidPattern(pattern);
1034
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
1035
+ return [pattern];
1036
+ }
1037
+ return (0, import_brace_expansion.default)(pattern);
1038
+ };
1039
+ minimatch.braceExpand = braceExpand;
1040
+ var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
1041
+ minimatch.makeRe = makeRe;
1042
+ var match = (list, pattern, options = {}) => {
1043
+ const mm = new Minimatch(pattern, options);
1044
+ list = list.filter((f) => mm.match(f));
1045
+ if (mm.options.nonull && !list.length) {
1046
+ list.push(pattern);
1047
+ }
1048
+ return list;
1049
+ };
1050
+ minimatch.match = match;
1051
+ var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
1052
+ var regExpEscape2 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
1053
+ var Minimatch = class {
1054
+ options;
1055
+ set;
1056
+ pattern;
1057
+ windowsPathsNoEscape;
1058
+ nonegate;
1059
+ negate;
1060
+ comment;
1061
+ empty;
1062
+ preserveMultipleSlashes;
1063
+ partial;
1064
+ globSet;
1065
+ globParts;
1066
+ nocase;
1067
+ isWindows;
1068
+ platform;
1069
+ windowsNoMagicRoot;
1070
+ regexp;
1071
+ constructor(pattern, options = {}) {
1072
+ assertValidPattern(pattern);
1073
+ options = options || {};
1074
+ this.options = options;
1075
+ this.pattern = pattern;
1076
+ this.platform = options.platform || defaultPlatform;
1077
+ this.isWindows = this.platform === "win32";
1078
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
1079
+ if (this.windowsPathsNoEscape) {
1080
+ this.pattern = this.pattern.replace(/\\/g, "/");
1081
+ }
1082
+ this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
1083
+ this.regexp = null;
1084
+ this.negate = false;
1085
+ this.nonegate = !!options.nonegate;
1086
+ this.comment = false;
1087
+ this.empty = false;
1088
+ this.partial = !!options.partial;
1089
+ this.nocase = !!this.options.nocase;
1090
+ this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
1091
+ this.globSet = [];
1092
+ this.globParts = [];
1093
+ this.set = [];
1094
+ this.make();
1095
+ }
1096
+ hasMagic() {
1097
+ if (this.options.magicalBraces && this.set.length > 1) {
1098
+ return true;
1099
+ }
1100
+ for (const pattern of this.set) {
1101
+ for (const part of pattern) {
1102
+ if (typeof part !== "string")
1103
+ return true;
1104
+ }
1105
+ }
1106
+ return false;
1107
+ }
1108
+ debug(..._) {
1109
+ }
1110
+ make() {
1111
+ const pattern = this.pattern;
1112
+ const options = this.options;
1113
+ if (!options.nocomment && pattern.charAt(0) === "#") {
1114
+ this.comment = true;
1115
+ return;
1116
+ }
1117
+ if (!pattern) {
1118
+ this.empty = true;
1119
+ return;
1120
+ }
1121
+ this.parseNegate();
1122
+ this.globSet = [...new Set(this.braceExpand())];
1123
+ if (options.debug) {
1124
+ this.debug = (...args) => console.error(...args);
1125
+ }
1126
+ this.debug(this.pattern, this.globSet);
1127
+ const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
1128
+ this.globParts = this.preprocess(rawGlobParts);
1129
+ this.debug(this.pattern, this.globParts);
1130
+ let set = this.globParts.map((s, _, __) => {
1131
+ if (this.isWindows && this.windowsNoMagicRoot) {
1132
+ const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
1133
+ const isDrive = /^[a-z]:/i.test(s[0]);
1134
+ if (isUNC) {
1135
+ return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))];
1136
+ } else if (isDrive) {
1137
+ return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
1138
+ }
1139
+ }
1140
+ return s.map((ss) => this.parse(ss));
1141
+ });
1142
+ this.debug(this.pattern, set);
1143
+ this.set = set.filter((s) => s.indexOf(false) === -1);
1144
+ if (this.isWindows) {
1145
+ for (let i = 0; i < this.set.length; i++) {
1146
+ const p = this.set[i];
1147
+ if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
1148
+ p[2] = "?";
1149
+ }
1150
+ }
1151
+ }
1152
+ this.debug(this.pattern, this.set);
1153
+ }
1154
+ // various transforms to equivalent pattern sets that are
1155
+ // faster to process in a filesystem walk. The goal is to
1156
+ // eliminate what we can, and push all ** patterns as far
1157
+ // to the right as possible, even if it increases the number
1158
+ // of patterns that we have to process.
1159
+ preprocess(globParts) {
1160
+ if (this.options.noglobstar) {
1161
+ for (let i = 0; i < globParts.length; i++) {
1162
+ for (let j = 0; j < globParts[i].length; j++) {
1163
+ if (globParts[i][j] === "**") {
1164
+ globParts[i][j] = "*";
1165
+ }
1166
+ }
1167
+ }
1168
+ }
1169
+ const { optimizationLevel = 1 } = this.options;
1170
+ if (optimizationLevel >= 2) {
1171
+ globParts = this.firstPhasePreProcess(globParts);
1172
+ globParts = this.secondPhasePreProcess(globParts);
1173
+ } else if (optimizationLevel >= 1) {
1174
+ globParts = this.levelOneOptimize(globParts);
1175
+ } else {
1176
+ globParts = this.adjascentGlobstarOptimize(globParts);
1177
+ }
1178
+ return globParts;
1179
+ }
1180
+ // just get rid of adjascent ** portions
1181
+ adjascentGlobstarOptimize(globParts) {
1182
+ return globParts.map((parts) => {
1183
+ let gs = -1;
1184
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
1185
+ let i = gs;
1186
+ while (parts[i + 1] === "**") {
1187
+ i++;
1188
+ }
1189
+ if (i !== gs) {
1190
+ parts.splice(gs, i - gs);
1191
+ }
1192
+ }
1193
+ return parts;
1194
+ });
1195
+ }
1196
+ // get rid of adjascent ** and resolve .. portions
1197
+ levelOneOptimize(globParts) {
1198
+ return globParts.map((parts) => {
1199
+ parts = parts.reduce((set, part) => {
1200
+ const prev = set[set.length - 1];
1201
+ if (part === "**" && prev === "**") {
1202
+ return set;
1203
+ }
1204
+ if (part === "..") {
1205
+ if (prev && prev !== ".." && prev !== "." && prev !== "**") {
1206
+ set.pop();
1207
+ return set;
1208
+ }
1209
+ }
1210
+ set.push(part);
1211
+ return set;
1212
+ }, []);
1213
+ return parts.length === 0 ? [""] : parts;
1214
+ });
1215
+ }
1216
+ levelTwoFileOptimize(parts) {
1217
+ if (!Array.isArray(parts)) {
1218
+ parts = this.slashSplit(parts);
1219
+ }
1220
+ let didSomething = false;
1221
+ do {
1222
+ didSomething = false;
1223
+ if (!this.preserveMultipleSlashes) {
1224
+ for (let i = 1; i < parts.length - 1; i++) {
1225
+ const p = parts[i];
1226
+ if (i === 1 && p === "" && parts[0] === "")
1227
+ continue;
1228
+ if (p === "." || p === "") {
1229
+ didSomething = true;
1230
+ parts.splice(i, 1);
1231
+ i--;
1232
+ }
1233
+ }
1234
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
1235
+ didSomething = true;
1236
+ parts.pop();
1237
+ }
1238
+ }
1239
+ let dd = 0;
1240
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
1241
+ const p = parts[dd - 1];
1242
+ if (p && p !== "." && p !== ".." && p !== "**") {
1243
+ didSomething = true;
1244
+ parts.splice(dd - 1, 2);
1245
+ dd -= 2;
1246
+ }
1247
+ }
1248
+ } while (didSomething);
1249
+ return parts.length === 0 ? [""] : parts;
1250
+ }
1251
+ // First phase: single-pattern processing
1252
+ // <pre> is 1 or more portions
1253
+ // <rest> is 1 or more portions
1254
+ // <p> is any portion other than ., .., '', or **
1255
+ // <e> is . or ''
1256
+ //
1257
+ // **/.. is *brutal* for filesystem walking performance, because
1258
+ // it effectively resets the recursive walk each time it occurs,
1259
+ // and ** cannot be reduced out by a .. pattern part like a regexp
1260
+ // or most strings (other than .., ., and '') can be.
1261
+ //
1262
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
1263
+ // <pre>/<e>/<rest> -> <pre>/<rest>
1264
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
1265
+ // **/**/<rest> -> **/<rest>
1266
+ //
1267
+ // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
1268
+ // this WOULD be allowed if ** did follow symlinks, or * didn't
1269
+ firstPhasePreProcess(globParts) {
1270
+ let didSomething = false;
1271
+ do {
1272
+ didSomething = false;
1273
+ for (let parts of globParts) {
1274
+ let gs = -1;
1275
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
1276
+ let gss = gs;
1277
+ while (parts[gss + 1] === "**") {
1278
+ gss++;
1279
+ }
1280
+ if (gss > gs) {
1281
+ parts.splice(gs + 1, gss - gs);
1282
+ }
1283
+ let next = parts[gs + 1];
1284
+ const p = parts[gs + 2];
1285
+ const p2 = parts[gs + 3];
1286
+ if (next !== "..")
1287
+ continue;
1288
+ if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
1289
+ continue;
1290
+ }
1291
+ didSomething = true;
1292
+ parts.splice(gs, 1);
1293
+ const other = parts.slice(0);
1294
+ other[gs] = "**";
1295
+ globParts.push(other);
1296
+ gs--;
1297
+ }
1298
+ if (!this.preserveMultipleSlashes) {
1299
+ for (let i = 1; i < parts.length - 1; i++) {
1300
+ const p = parts[i];
1301
+ if (i === 1 && p === "" && parts[0] === "")
1302
+ continue;
1303
+ if (p === "." || p === "") {
1304
+ didSomething = true;
1305
+ parts.splice(i, 1);
1306
+ i--;
1307
+ }
1308
+ }
1309
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
1310
+ didSomething = true;
1311
+ parts.pop();
1312
+ }
1313
+ }
1314
+ let dd = 0;
1315
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
1316
+ const p = parts[dd - 1];
1317
+ if (p && p !== "." && p !== ".." && p !== "**") {
1318
+ didSomething = true;
1319
+ const needDot = dd === 1 && parts[dd + 1] === "**";
1320
+ const splin = needDot ? ["."] : [];
1321
+ parts.splice(dd - 1, 2, ...splin);
1322
+ if (parts.length === 0)
1323
+ parts.push("");
1324
+ dd -= 2;
1325
+ }
1326
+ }
1327
+ }
1328
+ } while (didSomething);
1329
+ return globParts;
1330
+ }
1331
+ // second phase: multi-pattern dedupes
1332
+ // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
1333
+ // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
1334
+ // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
1335
+ //
1336
+ // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
1337
+ // ^-- not valid because ** doens't follow symlinks
1338
+ secondPhasePreProcess(globParts) {
1339
+ for (let i = 0; i < globParts.length - 1; i++) {
1340
+ for (let j = i + 1; j < globParts.length; j++) {
1341
+ const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
1342
+ if (matched) {
1343
+ globParts[i] = [];
1344
+ globParts[j] = matched;
1345
+ break;
1346
+ }
1347
+ }
1348
+ }
1349
+ return globParts.filter((gs) => gs.length);
1350
+ }
1351
+ partsMatch(a, b, emptyGSMatch = false) {
1352
+ let ai = 0;
1353
+ let bi = 0;
1354
+ let result = [];
1355
+ let which = "";
1356
+ while (ai < a.length && bi < b.length) {
1357
+ if (a[ai] === b[bi]) {
1358
+ result.push(which === "b" ? b[bi] : a[ai]);
1359
+ ai++;
1360
+ bi++;
1361
+ } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
1362
+ result.push(a[ai]);
1363
+ ai++;
1364
+ } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
1365
+ result.push(b[bi]);
1366
+ bi++;
1367
+ } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
1368
+ if (which === "b")
1369
+ return false;
1370
+ which = "a";
1371
+ result.push(a[ai]);
1372
+ ai++;
1373
+ bi++;
1374
+ } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
1375
+ if (which === "a")
1376
+ return false;
1377
+ which = "b";
1378
+ result.push(b[bi]);
1379
+ ai++;
1380
+ bi++;
1381
+ } else {
1382
+ return false;
1383
+ }
1384
+ }
1385
+ return a.length === b.length && result;
1386
+ }
1387
+ parseNegate() {
1388
+ if (this.nonegate)
1389
+ return;
1390
+ const pattern = this.pattern;
1391
+ let negate = false;
1392
+ let negateOffset = 0;
1393
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
1394
+ negate = !negate;
1395
+ negateOffset++;
1396
+ }
1397
+ if (negateOffset)
1398
+ this.pattern = pattern.slice(negateOffset);
1399
+ this.negate = negate;
1400
+ }
1401
+ // set partial to true to test if, for example,
1402
+ // "/a/b" matches the start of "/*/b/*/d"
1403
+ // Partial means, if you run out of file before you run
1404
+ // out of pattern, then that's fine, as long as all
1405
+ // the parts match.
1406
+ matchOne(file, pattern, partial = false) {
1407
+ const options = this.options;
1408
+ if (this.isWindows) {
1409
+ const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
1410
+ const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
1411
+ const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
1412
+ const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
1413
+ const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
1414
+ const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
1415
+ if (typeof fdi === "number" && typeof pdi === "number") {
1416
+ const [fd, pd] = [file[fdi], pattern[pdi]];
1417
+ if (fd.toLowerCase() === pd.toLowerCase()) {
1418
+ pattern[pdi] = fd;
1419
+ if (pdi > fdi) {
1420
+ pattern = pattern.slice(pdi);
1421
+ } else if (fdi > pdi) {
1422
+ file = file.slice(fdi);
1423
+ }
1424
+ }
1425
+ }
1426
+ }
1427
+ const { optimizationLevel = 1 } = this.options;
1428
+ if (optimizationLevel >= 2) {
1429
+ file = this.levelTwoFileOptimize(file);
1430
+ }
1431
+ this.debug("matchOne", this, { file, pattern });
1432
+ this.debug("matchOne", file.length, pattern.length);
1433
+ for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
1434
+ this.debug("matchOne loop");
1435
+ var p = pattern[pi];
1436
+ var f = file[fi];
1437
+ this.debug(pattern, p, f);
1438
+ if (p === false) {
1439
+ return false;
1440
+ }
1441
+ if (p === GLOBSTAR) {
1442
+ this.debug("GLOBSTAR", [pattern, p, f]);
1443
+ var fr = fi;
1444
+ var pr = pi + 1;
1445
+ if (pr === pl) {
1446
+ this.debug("** at the end");
1447
+ for (; fi < fl; fi++) {
1448
+ if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
1449
+ return false;
1450
+ }
1451
+ return true;
1452
+ }
1453
+ while (fr < fl) {
1454
+ var swallowee = file[fr];
1455
+ this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
1456
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
1457
+ this.debug("globstar found match!", fr, fl, swallowee);
1458
+ return true;
1459
+ } else {
1460
+ if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
1461
+ this.debug("dot detected!", file, fr, pattern, pr);
1462
+ break;
1463
+ }
1464
+ this.debug("globstar swallow a segment, and continue");
1465
+ fr++;
1466
+ }
1467
+ }
1468
+ if (partial) {
1469
+ this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
1470
+ if (fr === fl) {
1471
+ return true;
1472
+ }
1473
+ }
1474
+ return false;
1475
+ }
1476
+ let hit;
1477
+ if (typeof p === "string") {
1478
+ hit = f === p;
1479
+ this.debug("string match", p, f, hit);
1480
+ } else {
1481
+ hit = p.test(f);
1482
+ this.debug("pattern match", p, f, hit);
1483
+ }
1484
+ if (!hit)
1485
+ return false;
1486
+ }
1487
+ if (fi === fl && pi === pl) {
1488
+ return true;
1489
+ } else if (fi === fl) {
1490
+ return partial;
1491
+ } else if (pi === pl) {
1492
+ return fi === fl - 1 && file[fi] === "";
1493
+ } else {
1494
+ throw new Error("wtf?");
1495
+ }
1496
+ }
1497
+ braceExpand() {
1498
+ return braceExpand(this.pattern, this.options);
1499
+ }
1500
+ parse(pattern) {
1501
+ assertValidPattern(pattern);
1502
+ const options = this.options;
1503
+ if (pattern === "**")
1504
+ return GLOBSTAR;
1505
+ if (pattern === "")
1506
+ return "";
1507
+ let m;
1508
+ let fastTest = null;
1509
+ if (m = pattern.match(starRE)) {
1510
+ fastTest = options.dot ? starTestDot : starTest;
1511
+ } else if (m = pattern.match(starDotExtRE)) {
1512
+ fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
1513
+ } else if (m = pattern.match(qmarksRE)) {
1514
+ fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
1515
+ } else if (m = pattern.match(starDotStarRE)) {
1516
+ fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
1517
+ } else if (m = pattern.match(dotStarRE)) {
1518
+ fastTest = dotStarTest;
1519
+ }
1520
+ const re = AST.fromGlob(pattern, this.options).toMMPattern();
1521
+ if (fastTest && typeof re === "object") {
1522
+ Reflect.defineProperty(re, "test", { value: fastTest });
1523
+ }
1524
+ return re;
1525
+ }
1526
+ makeRe() {
1527
+ if (this.regexp || this.regexp === false)
1528
+ return this.regexp;
1529
+ const set = this.set;
1530
+ if (!set.length) {
1531
+ this.regexp = false;
1532
+ return this.regexp;
1533
+ }
1534
+ const options = this.options;
1535
+ const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot : twoStarNoDot;
1536
+ const flags = new Set(options.nocase ? ["i"] : []);
1537
+ let re = set.map((pattern) => {
1538
+ const pp = pattern.map((p) => {
1539
+ if (p instanceof RegExp) {
1540
+ for (const f of p.flags.split(""))
1541
+ flags.add(f);
1542
+ }
1543
+ return typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR ? GLOBSTAR : p._src;
1544
+ });
1545
+ pp.forEach((p, i) => {
1546
+ const next = pp[i + 1];
1547
+ const prev = pp[i - 1];
1548
+ if (p !== GLOBSTAR || prev === GLOBSTAR) {
1549
+ return;
1550
+ }
1551
+ if (prev === void 0) {
1552
+ if (next !== void 0 && next !== GLOBSTAR) {
1553
+ pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
1554
+ } else {
1555
+ pp[i] = twoStar;
1556
+ }
1557
+ } else if (next === void 0) {
1558
+ pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
1559
+ } else if (next !== GLOBSTAR) {
1560
+ pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
1561
+ pp[i + 1] = GLOBSTAR;
1562
+ }
1563
+ });
1564
+ return pp.filter((p) => p !== GLOBSTAR).join("/");
1565
+ }).join("|");
1566
+ const [open, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
1567
+ re = "^" + open + re + close + "$";
1568
+ if (this.negate)
1569
+ re = "^(?!" + re + ").+$";
1570
+ try {
1571
+ this.regexp = new RegExp(re, [...flags].join(""));
1572
+ } catch (ex) {
1573
+ this.regexp = false;
1574
+ }
1575
+ return this.regexp;
1576
+ }
1577
+ slashSplit(p) {
1578
+ if (this.preserveMultipleSlashes) {
1579
+ return p.split("/");
1580
+ } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
1581
+ return ["", ...p.split(/\/+/)];
1582
+ } else {
1583
+ return p.split(/\/+/);
1584
+ }
1585
+ }
1586
+ match(f, partial = this.partial) {
1587
+ this.debug("match", f, this.pattern);
1588
+ if (this.comment) {
1589
+ return false;
1590
+ }
1591
+ if (this.empty) {
1592
+ return f === "";
1593
+ }
1594
+ if (f === "/" && partial) {
1595
+ return true;
1596
+ }
1597
+ const options = this.options;
1598
+ if (this.isWindows) {
1599
+ f = f.split("\\").join("/");
1600
+ }
1601
+ const ff = this.slashSplit(f);
1602
+ this.debug(this.pattern, "split", ff);
1603
+ const set = this.set;
1604
+ this.debug(this.pattern, "set", set);
1605
+ let filename = ff[ff.length - 1];
1606
+ if (!filename) {
1607
+ for (let i = ff.length - 2; !filename && i >= 0; i--) {
1608
+ filename = ff[i];
1609
+ }
1610
+ }
1611
+ for (let i = 0; i < set.length; i++) {
1612
+ const pattern = set[i];
1613
+ let file = ff;
1614
+ if (options.matchBase && pattern.length === 1) {
1615
+ file = [filename];
1616
+ }
1617
+ const hit = this.matchOne(file, pattern, partial);
1618
+ if (hit) {
1619
+ if (options.flipNegate) {
1620
+ return true;
1621
+ }
1622
+ return !this.negate;
1623
+ }
1624
+ }
1625
+ if (options.flipNegate) {
1626
+ return false;
1627
+ }
1628
+ return this.negate;
1629
+ }
1630
+ static defaults(def) {
1631
+ return minimatch.defaults(def).Minimatch;
1632
+ }
1633
+ };
1634
+ minimatch.AST = AST;
1635
+ minimatch.Minimatch = Minimatch;
1636
+ minimatch.escape = escape;
1637
+ minimatch.unescape = unescape;
1638
+
1639
+ // src/core/dir.ts
1640
+ async function directoryExists(dirPath) {
1641
+ try {
1642
+ await fs2.access(dirPath, constants.F_OK);
1643
+ return true;
1644
+ } catch {
1645
+ return false;
1646
+ }
1647
+ }
1648
+ async function getDirectoryItems(dirPath, targetFileName) {
1649
+ const collection = [];
1650
+ const files = await fs2.readdir(dirPath);
1651
+ for (const itemName of files) {
1652
+ const itemPath = path3.resolve(dirPath, itemName);
1653
+ const stats = await fs2.stat(itemPath);
1654
+ if (stats.isDirectory()) {
1655
+ const children = await getDirectoryItems(itemPath, targetFileName);
1656
+ collection.push(...children);
1657
+ } else if (itemName === targetFileName) {
1658
+ collection.push(itemPath);
1659
+ }
1660
+ }
1661
+ return collection;
1662
+ }
1663
+ function filterDirectoryItems(rootPath, items, include, exclude) {
1664
+ const includedPatterns = include.map((pattern) => new Minimatch(pattern));
1665
+ const excludedPatterns = exclude.map((pattern) => new Minimatch(pattern));
1666
+ return items.filter((item) => {
1667
+ const relativePath = path3.relative(rootPath, item);
1668
+ const isIncluded = includedPatterns.some((pattern) => pattern.match(relativePath));
1669
+ const isExcluded = excludedPatterns.some((pattern) => pattern.match(relativePath));
1670
+ return (isIncluded || !include.length) && !isExcluded;
1671
+ });
1672
+ }
1673
+
1674
+ // src/core/isDocumentedRoute.ts
1675
+ import fs3 from "node:fs/promises";
1676
+ async function isDocumentedRoute(routePath) {
1677
+ try {
1678
+ const rawCode = await fs3.readFile(routePath, "utf-8");
1679
+ return rawCode.includes("@omer-x/next-openapi-route-handler");
1680
+ } catch {
1681
+ return false;
1682
+ }
1683
+ }
1684
+
1685
+ // src/core/next.ts
1686
+ import fs4 from "node:fs/promises";
1687
+ import path4 from "node:path";
1688
+
1689
+ // src/utils/generateRandomString.ts
1690
+ function generateRandomString(length) {
1691
+ return [...Array(length)].map(() => Math.random().toString(36)[2]).join("");
1692
+ }
1693
+
1694
+ // src/utils/string-preservation.ts
1695
+ function preserveStrings(code) {
1696
+ let replacements = {};
1697
+ const output = code.replace(/(['"`])((?:\\.|(?!\1).)*)\1/g, (match2, quote, content) => {
1698
+ const replacementId = generateRandomString(32);
1699
+ replacements = {
1700
+ ...replacements,
1701
+ [replacementId]: `${quote}${content}${quote}`
1702
+ };
1703
+ return `<@~${replacementId}~@>`;
1704
+ });
1705
+ return { output, replacements };
1706
+ }
1707
+ function restoreStrings(code, replacements) {
1708
+ return code.replace(/<@~(.*?)~@>/g, (_, replacementId) => {
1709
+ return replacements[replacementId];
1710
+ });
1711
+ }
1712
+
1713
+ // src/core/injectSchemas.ts
1714
+ function injectSchemas(code, refName) {
1715
+ const { output: preservedCode, replacements } = preserveStrings(code);
1716
+ const preservedCodeWithSchemasInjected = preservedCode.replace(new RegExp(`\\b${refName}\\.`, "g"), `global.schemas[${refName}].`).replace(new RegExp(`\\b${refName}\\b`, "g"), `"${refName}"`).replace(new RegExp(`queryParams:\\s*['"\`]${refName}['"\`]`, "g"), `queryParams: global.schemas["${refName}"]`).replace(new RegExp(`pathParams:\\s*['"\`]${refName}['"\`]`, "g"), `pathParams: global.schemas["${refName}"]`);
1717
+ return restoreStrings(preservedCodeWithSchemasInjected, replacements);
1718
+ }
1719
+
1720
+ // src/core/middleware.ts
1721
+ function detectMiddlewareName(code) {
1722
+ const match2 = code.match(/middleware:\s*(\w+)/);
1723
+ return match2 ? match2[1] : null;
1724
+ }
1725
+
1726
+ // src/core/transpile.ts
1727
+ import { transpile as tsTranspile } from "typescript";
1728
+
1729
+ // src/utils/removeImports.ts
1730
+ function removeImports(code) {
1731
+ return code.replace(/(^import\s+[^;]+;?$|^import\s+[^;]*\sfrom\s.+;?$)/gm, "").replace(/(^import\s+{[\s\S]+?}\s+from\s+["'][^"']+["'];?)/gm, "").trim();
1732
+ }
1733
+
1734
+ // src/core/transpile.ts
1735
+ function fixExports(code) {
1736
+ const validMethods = ["GET", "POST", "PUT", "PATCH", "DELETE"];
1737
+ const exportLines = validMethods.map((method) => `let ${method};
1738
+ `);
1739
+ const exportFixer = validMethods.map((method) => `exports.${method} = ${method};`).join("\n");
1740
+ return `${exportLines.join("")}
1741
+ ${code}
1742
+ ${exportFixer}`;
1743
+ }
1744
+ function injectMiddlewareFixer(middlewareName) {
1745
+ return `const ${middlewareName} = (handler) => handler;`;
1746
+ }
1747
+ function transpile(rawCode, routeDefinerName, middlewareName) {
1748
+ const code = fixExports(removeImports(rawCode));
1749
+ const parts = [
1750
+ `const ${routeDefinerName} = require('@omer-x/next-openapi-route-handler').default;`,
1751
+ "const z = require('zod');",
1752
+ middlewareName ? injectMiddlewareFixer(middlewareName) : "",
1753
+ code
1754
+ ];
1755
+ return tsTranspile(parts.join("\n"), {
1756
+ module: 1,
1757
+ // CommonJS
1758
+ target: 99
1759
+ // ESNext
1760
+ });
1761
+ }
1762
+
1763
+ // src/core/next.ts
1764
+ async function findAppFolderPath() {
1765
+ const inSrc = path4.resolve(process.cwd(), "src", "app");
1766
+ if (await directoryExists(inSrc)) {
1767
+ return inSrc;
1768
+ }
1769
+ const inRoot = path4.resolve(process.cwd(), "app");
1770
+ if (await directoryExists(inRoot)) {
1771
+ return inRoot;
1772
+ }
1773
+ return null;
1774
+ }
1775
+ function safeEval(code, routePath) {
1776
+ try {
1777
+ const fn = new Function("global", "require", `
1778
+ const module = { exports: {} };
1779
+ const exports = module.exports;
1780
+
1781
+ const NextResponse = { json: () => ({}) };
1782
+ const next = { server: { NextResponse } };
1783
+
1784
+ ${code}
1785
+
1786
+ return module.exports;
1787
+ `);
1788
+ return fn(global, __require);
1789
+ } catch (error) {
1790
+ console.log(`An error occured while evaluating the route exports from "${routePath}"`);
1791
+ throw error;
1792
+ }
1793
+ }
1794
+ async function getRouteExports(routePath, routeDefinerName, schemas) {
1795
+ const rawCode = await fs4.readFile(routePath, "utf-8");
1796
+ const middlewareName = detectMiddlewareName(rawCode);
1797
+ const code = transpile(rawCode, routeDefinerName, middlewareName);
1798
+ const fixedCode = Object.keys(schemas).reduce(injectSchemas, code);
1799
+ global.schemas = schemas;
1800
+ const result = safeEval(fixedCode, routePath);
1801
+ delete global.schemas;
1802
+ return result;
1803
+ }
1804
+
1805
+ // src/core/options.ts
1806
+ function verifyOptions(include, exclude) {
1807
+ if (process.env.NODE_ENV === "development") {
1808
+ for (const item of include) {
1809
+ if (!item.endsWith("/route.ts")) {
1810
+ console.log(`${item} is not a valid route handler path`);
1811
+ }
1812
+ }
1813
+ for (const item of exclude) {
1814
+ if (!item.endsWith("/route.ts")) {
1815
+ console.log(`${item} is not a valid route handler path`);
1816
+ }
1817
+ }
1818
+ }
1819
+ return {
1820
+ include: include.filter((item) => item.endsWith("/route.ts")),
1821
+ exclude: exclude.filter((item) => item.endsWith("/route.ts"))
1822
+ };
1823
+ }
1824
+
1825
+ // src/core/getRoutePathName.ts
1826
+ import path5 from "node:path";
1827
+ function getRoutePathName(filePath, rootPath) {
1828
+ const dirName = path5.dirname(filePath);
1829
+ return "/" + path5.relative(rootPath, dirName).replaceAll("[", "{").replaceAll("]", "}").replaceAll("\\", "/");
1830
+ }
1831
+
1832
+ // src/utils/deepEqual.ts
1833
+ function deepEqual(a, b) {
1834
+ if (typeof a !== typeof b) return false;
1835
+ switch (typeof a) {
1836
+ case "object": {
1837
+ if (!a || !b) return a === b;
1838
+ if (Array.isArray(a) && Array.isArray(b)) {
1839
+ return a.every((item, index) => deepEqual(item, b[index]));
1840
+ }
1841
+ if (Object.keys(a).length !== Object.keys(b).length) return false;
1842
+ return Object.entries(a).every(([key, value]) => {
1843
+ return deepEqual(value, b[key]);
1844
+ });
1845
+ }
1846
+ case "function":
1847
+ case "symbol":
1848
+ return false;
1849
+ default:
1850
+ return a === b;
1851
+ }
1852
+ }
1853
+
1854
+ // src/core/zod-to-openapi.ts
1855
+ import { zodToJsonSchema } from "zod-to-json-schema";
1856
+
1857
+ // src/utils/zod-schema.ts
1858
+ function isFile(schema) {
1859
+ const file = new File([], "nothing.txt");
1860
+ const plainObject = { name: "test", size: 0 };
1861
+ const fileResult = schema.safeParse(file);
1862
+ const objectResult = schema.safeParse(plainObject);
1863
+ return fileResult.success && !objectResult.success;
1864
+ }
1865
+
1866
+ // src/core/zod-to-openapi.ts
1867
+ function convertToOpenAPI(schema, isArray) {
1868
+ const result = zodToJsonSchema(isArray ? schema.array() : schema, {
1869
+ target: "openApi3",
1870
+ $refStrategy: "none"
1871
+ });
1872
+ if (result.type === "object" && result.properties) {
1873
+ for (const [propName, prop] of Object.entries(schema.shape)) {
1874
+ if (isFile(prop)) {
1875
+ result.properties[propName] = {
1876
+ type: "string",
1877
+ format: "binary",
1878
+ description: prop.description
1879
+ // contentEncoding: "base64", // swagger-ui-react doesn't support this
1880
+ };
1881
+ }
1882
+ }
1883
+ }
1884
+ return result;
1885
+ }
1886
+
1887
+ // src/core/mask.ts
1888
+ function maskWithReference(schema, storedSchemas, self) {
1889
+ if (self) {
1890
+ for (const [schemaName, zodSchema] of Object.entries(storedSchemas)) {
1891
+ if (deepEqual(schema, convertToOpenAPI(zodSchema, false))) {
1892
+ return {
1893
+ $ref: `#/components/schemas/${schemaName}`
1894
+ };
1895
+ }
1896
+ }
1897
+ }
1898
+ if ("$ref" in schema) return schema;
1899
+ if (schema.oneOf) {
1900
+ return {
1901
+ ...schema,
1902
+ oneOf: schema.oneOf.map((i) => maskWithReference(i, storedSchemas, true))
1903
+ };
1904
+ }
1905
+ if (schema.anyOf) {
1906
+ return {
1907
+ ...schema,
1908
+ anyOf: schema.anyOf.map((i) => maskWithReference(i, storedSchemas, true))
1909
+ };
1910
+ }
1911
+ switch (schema.type) {
1912
+ case "object":
1913
+ return {
1914
+ ...schema,
1915
+ properties: Object.entries(schema.properties ?? {}).reduce((props, [propName, prop]) => ({
1916
+ ...props,
1917
+ [propName]: maskWithReference(prop, storedSchemas, true)
1918
+ }), {})
1919
+ };
1920
+ case "array":
1921
+ if (Array.isArray(schema.items)) {
1922
+ return {
1923
+ ...schema,
1924
+ items: schema.items.map((i) => maskWithReference(i, storedSchemas, true))
1925
+ };
1926
+ }
1927
+ return {
1928
+ ...schema,
1929
+ items: maskWithReference(schema.items, storedSchemas, true)
1930
+ };
1931
+ }
1932
+ return schema;
1933
+ }
1934
+
1935
+ // src/core/operation-mask.ts
1936
+ function maskSchema(storedSchemas, schema) {
1937
+ if (!schema) return schema;
1938
+ return maskWithReference(schema, storedSchemas, true);
1939
+ }
1940
+ function maskParameterSchema(param, storedSchemas) {
1941
+ if ("$ref" in param) return param;
1942
+ return { ...param, schema: maskSchema(storedSchemas, param.schema) };
1943
+ }
1944
+ function maskContentSchema(storedSchemas, bodyContent) {
1945
+ if (!bodyContent) return bodyContent;
1946
+ return Object.entries(bodyContent).reduce((collection, [contentType, content]) => ({
1947
+ ...collection,
1948
+ [contentType]: {
1949
+ ...content,
1950
+ schema: maskSchema(storedSchemas, content.schema)
1951
+ }
1952
+ }), {});
1953
+ }
1954
+ function maskRequestBodySchema(storedSchemas, body) {
1955
+ if (!body || "$ref" in body) return body;
1956
+ return { ...body, content: maskContentSchema(storedSchemas, body.content) };
1957
+ }
1958
+ function maskResponseSchema(storedSchemas, response) {
1959
+ if ("$ref" in response) return response;
1960
+ return { ...response, content: maskContentSchema(storedSchemas, response.content) };
1961
+ }
1962
+ function maskSchemasInResponses(storedSchemas, responses) {
1963
+ if (!responses) return responses;
1964
+ return Object.entries(responses).reduce((collection, [key, response]) => ({
1965
+ ...collection,
1966
+ [key]: maskResponseSchema(storedSchemas, response)
1967
+ }), {});
1968
+ }
1969
+ function maskOperationSchemas(operation, storedSchemas) {
1970
+ return {
1971
+ ...operation,
1972
+ parameters: operation.parameters?.map((p) => maskParameterSchema(p, storedSchemas)),
1973
+ requestBody: maskRequestBodySchema(storedSchemas, operation.requestBody),
1974
+ responses: maskSchemasInResponses(storedSchemas, operation.responses)
1975
+ };
1976
+ }
1977
+
1978
+ // src/core/route.ts
1979
+ function createRouteRecord(method, filePath, rootPath, apiData) {
1980
+ return {
1981
+ method: method.toLocaleLowerCase(),
1982
+ path: getRoutePathName(filePath, rootPath),
1983
+ apiData
1984
+ };
1985
+ }
1986
+ function bundlePaths(source, storedSchemas) {
1987
+ source.sort((a, b) => a.path.localeCompare(b.path));
1988
+ return source.reduce((collection, route) => ({
1989
+ ...collection,
1990
+ [route.path]: {
1991
+ ...collection[route.path],
1992
+ [route.method]: maskOperationSchemas(route.apiData, storedSchemas)
1993
+ }
1994
+ }), {});
1995
+ }
1996
+
1997
+ // src/core/schema.ts
1998
+ function bundleSchemas(schemas) {
1999
+ const bundledSchemas = Object.keys(schemas).reduce((collection, schemaName) => {
2000
+ return {
2001
+ ...collection,
2002
+ [schemaName]: convertToOpenAPI(schemas[schemaName], false)
2003
+ };
2004
+ }, {});
2005
+ return Object.entries(bundledSchemas).reduce((bundle, [schemaName, schema]) => ({
2006
+ ...bundle,
2007
+ [schemaName]: maskWithReference(schema, schemas, false)
2008
+ }), {});
2009
+ }
2010
+
2011
+ // src/core/generateOpenApiSpec.ts
2012
+ async function generateOpenApiSpec(schemas, {
2013
+ include: includeOption = [],
2014
+ exclude: excludeOption = [],
2015
+ routeDefinerName = "defineRoute",
2016
+ rootPath: additionalRootPath,
2017
+ info,
2018
+ servers,
2019
+ security,
2020
+ securitySchemes,
2021
+ clearUnusedSchemas: clearUnusedSchemasOption = true
2022
+ } = {}) {
2023
+ const verifiedOptions = verifyOptions(includeOption, excludeOption);
2024
+ const appFolderPath = await findAppFolderPath();
2025
+ if (!appFolderPath) throw new Error("This is not a Next.js application!");
2026
+ const rootPath = additionalRootPath ? path6.resolve(appFolderPath, "./" + additionalRootPath) : appFolderPath;
2027
+ const routes = await getDirectoryItems(rootPath, "route.ts");
2028
+ const verifiedRoutes = filterDirectoryItems(rootPath, routes, verifiedOptions.include, verifiedOptions.exclude);
2029
+ const validRoutes = [];
2030
+ for (const route of verifiedRoutes) {
2031
+ const isDocumented = await isDocumentedRoute(route);
2032
+ if (!isDocumented) continue;
2033
+ const exportedRouteHandlers = await getRouteExports(route, routeDefinerName, schemas);
2034
+ for (const [method, routeHandler] of Object.entries(exportedRouteHandlers)) {
2035
+ if (!routeHandler || !routeHandler.apiData) continue;
2036
+ validRoutes.push(createRouteRecord(
2037
+ method.toLocaleLowerCase(),
2038
+ route,
2039
+ rootPath,
2040
+ routeHandler.apiData
2041
+ ));
2042
+ }
2043
+ }
2044
+ const metadata = getPackageMetadata();
2045
+ const pathsAndComponents = {
2046
+ paths: bundlePaths(validRoutes, schemas),
2047
+ components: {
2048
+ schemas: bundleSchemas(schemas),
2049
+ securitySchemes
2050
+ }
2051
+ };
2052
+ return {
2053
+ openapi: "3.1.0",
2054
+ info: {
2055
+ title: metadata.serviceName,
2056
+ version: metadata.version,
2057
+ ...info ?? {}
2058
+ },
2059
+ servers,
2060
+ ...clearUnusedSchemasOption ? clearUnusedSchemas(pathsAndComponents) : pathsAndComponents,
2061
+ security,
2062
+ tags: []
2063
+ };
2064
+ }
2065
+
2066
+ // src/index.ts
2067
+ var src_default = generateOpenApiSpec;
2068
+ export {
2069
+ src_default as default
2070
+ };