@clerc/plugin-completions 1.0.0-beta.24 → 1.0.0-beta.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,152 +1,1582 @@
1
- import { DOUBLE_DASH, Types, definePlugin, normalizeFlagValue, resolveCommand } from "@clerc/core";
2
- import tabtab, { getShellFromEnv } from "@pnpm/tabtab";
1
+ import t from "@bomb.sh/tab";
2
+ import { Clerc, NoCommandSpecifiedError, NoSuchCommandError, Types, definePlugin, normalizeFlagValue, resolveCommand } from "@clerc/core";
3
+ import tty from "node:tty";
3
4
 
5
+ //#region rolldown:runtime
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
13
+ var __export = (all, symbols) => {
14
+ let target = {};
15
+ for (var name in all) {
16
+ __defProp(target, name, {
17
+ get: all[name],
18
+ enumerable: true
19
+ });
20
+ }
21
+ if (symbols) {
22
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
23
+ }
24
+ return target;
25
+ };
26
+ var __copyProps = (to, from, except, desc) => {
27
+ if (from && typeof from === "object" || typeof from === "function") {
28
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
29
+ key = keys[i];
30
+ if (!__hasOwnProp.call(to, key) && key !== except) {
31
+ __defProp(to, key, {
32
+ get: ((k) => from[k]).bind(null, key),
33
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
34
+ });
35
+ }
36
+ }
37
+ }
38
+ return to;
39
+ };
40
+ var __reExport = (target, mod, secondTarget, symbols) => {
41
+ if (symbols) {
42
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
43
+ secondTarget && __defProp(secondTarget, Symbol.toStringTag, { value: "Module" });
44
+ }
45
+ __copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default");
46
+ };
47
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
48
+ value: mod,
49
+ enumerable: true
50
+ }) : target, mod));
51
+
52
+ //#endregion
4
53
  //#region ../utils/src/index.ts
5
54
  const toArray = (a) => Array.isArray(a) ? a : [a];
55
+ function joinWithAnd(values) {
56
+ if (values.length === 0) return "";
57
+ if (values.length === 1) return values[0];
58
+ const last = values.pop();
59
+ return `${values.join(", ")} and ${last}`;
60
+ }
6
61
  const kebabCase = (s) => s.replace(/([A-Z])/g, (_, c) => `-${c.toLowerCase()}`);
7
62
  const formatFlagName = (n) => n.length <= 1 ? `-${n}` : `--${kebabCase(n)}`;
63
+ const formatVersion = (v) => v.length === 0 ? "" : v.startsWith("v") ? v : `v${v}`;
64
+ const isTruthy = Boolean;
65
+ const objectIsEmpty = (obj) => Object.keys(obj).length === 0;
66
+
67
+ //#endregion
68
+ //#region ../plugin-help/src/utils.ts
69
+ function formatTypeValue(type) {
70
+ if (typeof type === "function") return type.display ?? type.name;
71
+ const innerType = type[0];
72
+ return `Array<${innerType.displayName ?? innerType.name}>`;
73
+ }
74
+ function formatFlagDefault(value) {
75
+ if (typeof value === "function" && "display" in value && value.display) return value.display;
76
+ return String(value);
77
+ }
78
+ function formatCommandName(name) {
79
+ if (name === "") return "(root)";
80
+ return name;
81
+ }
82
+
83
+ //#endregion
84
+ //#region ../plugin-help/src/formatters.ts
85
+ const defaultFormatters = {
86
+ formatTypeValue,
87
+ formatFlagDefault
88
+ };
89
+
90
+ //#endregion
91
+ //#region ../../node_modules/.pnpm/ansi-regex@6.1.0/node_modules/ansi-regex/index.js
92
+ function ansiRegex({ onlyFirst = false } = {}) {
93
+ const pattern = [`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`, "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
94
+ return new RegExp(pattern, onlyFirst ? void 0 : "g");
95
+ }
96
+
97
+ //#endregion
98
+ //#region ../../node_modules/.pnpm/strip-ansi@7.1.0/node_modules/strip-ansi/index.js
99
+ const regex = ansiRegex();
100
+ function stripAnsi(string) {
101
+ if (typeof string !== "string") throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
102
+ return string.replace(regex, "");
103
+ }
104
+
105
+ //#endregion
106
+ //#region ../../node_modules/.pnpm/get-east-asian-width@1.3.0/node_modules/get-east-asian-width/lookup.js
107
+ function isAmbiguous(x) {
108
+ return x === 161 || x === 164 || x === 167 || x === 168 || x === 170 || x === 173 || x === 174 || x >= 176 && x <= 180 || x >= 182 && x <= 186 || x >= 188 && x <= 191 || x === 198 || x === 208 || x === 215 || x === 216 || x >= 222 && x <= 225 || x === 230 || x >= 232 && x <= 234 || x === 236 || x === 237 || x === 240 || x === 242 || x === 243 || x >= 247 && x <= 250 || x === 252 || x === 254 || x === 257 || x === 273 || x === 275 || x === 283 || x === 294 || x === 295 || x === 299 || x >= 305 && x <= 307 || x === 312 || x >= 319 && x <= 322 || x === 324 || x >= 328 && x <= 331 || x === 333 || x === 338 || x === 339 || x === 358 || x === 359 || x === 363 || x === 462 || x === 464 || x === 466 || x === 468 || x === 470 || x === 472 || x === 474 || x === 476 || x === 593 || x === 609 || x === 708 || x === 711 || x >= 713 && x <= 715 || x === 717 || x === 720 || x >= 728 && x <= 731 || x === 733 || x === 735 || x >= 768 && x <= 879 || x >= 913 && x <= 929 || x >= 931 && x <= 937 || x >= 945 && x <= 961 || x >= 963 && x <= 969 || x === 1025 || x >= 1040 && x <= 1103 || x === 1105 || x === 8208 || x >= 8211 && x <= 8214 || x === 8216 || x === 8217 || x === 8220 || x === 8221 || x >= 8224 && x <= 8226 || x >= 8228 && x <= 8231 || x === 8240 || x === 8242 || x === 8243 || x === 8245 || x === 8251 || x === 8254 || x === 8308 || x === 8319 || x >= 8321 && x <= 8324 || x === 8364 || x === 8451 || x === 8453 || x === 8457 || x === 8467 || x === 8470 || x === 8481 || x === 8482 || x === 8486 || x === 8491 || x === 8531 || x === 8532 || x >= 8539 && x <= 8542 || x >= 8544 && x <= 8555 || x >= 8560 && x <= 8569 || x === 8585 || x >= 8592 && x <= 8601 || x === 8632 || x === 8633 || x === 8658 || x === 8660 || x === 8679 || x === 8704 || x === 8706 || x === 8707 || x === 8711 || x === 8712 || x === 8715 || x === 8719 || x === 8721 || x === 8725 || x === 8730 || x >= 8733 && x <= 8736 || x === 8739 || x === 8741 || x >= 8743 && x <= 8748 || x === 8750 || x >= 8756 && x <= 8759 || x === 8764 || x === 8765 || x === 8776 || x === 8780 || x === 8786 || x === 8800 || x === 8801 || x >= 8804 && x <= 8807 || x === 8810 || x === 8811 || x === 8814 || x === 8815 || x === 8834 || x === 8835 || x === 8838 || x === 8839 || x === 8853 || x === 8857 || x === 8869 || x === 8895 || x === 8978 || x >= 9312 && x <= 9449 || x >= 9451 && x <= 9547 || x >= 9552 && x <= 9587 || x >= 9600 && x <= 9615 || x >= 9618 && x <= 9621 || x === 9632 || x === 9633 || x >= 9635 && x <= 9641 || x === 9650 || x === 9651 || x === 9654 || x === 9655 || x === 9660 || x === 9661 || x === 9664 || x === 9665 || x >= 9670 && x <= 9672 || x === 9675 || x >= 9678 && x <= 9681 || x >= 9698 && x <= 9701 || x === 9711 || x === 9733 || x === 9734 || x === 9737 || x === 9742 || x === 9743 || x === 9756 || x === 9758 || x === 9792 || x === 9794 || x === 9824 || x === 9825 || x >= 9827 && x <= 9829 || x >= 9831 && x <= 9834 || x === 9836 || x === 9837 || x === 9839 || x === 9886 || x === 9887 || x === 9919 || x >= 9926 && x <= 9933 || x >= 9935 && x <= 9939 || x >= 9941 && x <= 9953 || x === 9955 || x === 9960 || x === 9961 || x >= 9963 && x <= 9969 || x === 9972 || x >= 9974 && x <= 9977 || x === 9979 || x === 9980 || x === 9982 || x === 9983 || x === 10045 || x >= 10102 && x <= 10111 || x >= 11094 && x <= 11097 || x >= 12872 && x <= 12879 || x >= 57344 && x <= 63743 || x >= 65024 && x <= 65039 || x === 65533 || x >= 127232 && x <= 127242 || x >= 127248 && x <= 127277 || x >= 127280 && x <= 127337 || x >= 127344 && x <= 127373 || x === 127375 || x === 127376 || x >= 127387 && x <= 127404 || x >= 917760 && x <= 917999 || x >= 983040 && x <= 1048573 || x >= 1048576 && x <= 1114109;
109
+ }
110
+ function isFullWidth(x) {
111
+ return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510;
112
+ }
113
+ function isWide(x) {
114
+ return x >= 4352 && x <= 4447 || x === 8986 || x === 8987 || x === 9001 || x === 9002 || x >= 9193 && x <= 9196 || x === 9200 || x === 9203 || x === 9725 || x === 9726 || x === 9748 || x === 9749 || x >= 9776 && x <= 9783 || x >= 9800 && x <= 9811 || x === 9855 || x >= 9866 && x <= 9871 || x === 9875 || x === 9889 || x === 9898 || x === 9899 || x === 9917 || x === 9918 || x === 9924 || x === 9925 || x === 9934 || x === 9940 || x === 9962 || x === 9970 || x === 9971 || x === 9973 || x === 9978 || x === 9981 || x === 9989 || x === 9994 || x === 9995 || x === 10024 || x === 10060 || x === 10062 || x >= 10067 && x <= 10069 || x === 10071 || x >= 10133 && x <= 10135 || x === 10160 || x === 10175 || x === 11035 || x === 11036 || x === 11088 || x === 11093 || x >= 11904 && x <= 11929 || x >= 11931 && x <= 12019 || x >= 12032 && x <= 12245 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12353 && x <= 12438 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12773 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 42124 || x >= 42128 && x <= 42182 || x >= 43360 && x <= 43388 || x >= 44032 && x <= 55203 || x >= 63744 && x <= 64255 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 94176 && x <= 94180 || x === 94192 || x === 94193 || x >= 94208 && x <= 100343 || x >= 100352 && x <= 101589 || x >= 101631 && x <= 101640 || x >= 110576 && x <= 110579 || x >= 110581 && x <= 110587 || x === 110589 || x === 110590 || x >= 110592 && x <= 110882 || x === 110898 || x >= 110928 && x <= 110930 || x === 110933 || x >= 110948 && x <= 110951 || x >= 110960 && x <= 111355 || x >= 119552 && x <= 119638 || x >= 119648 && x <= 119670 || x === 126980 || x === 127183 || x === 127374 || x >= 127377 && x <= 127386 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x === 127568 || x === 127569 || x >= 127584 && x <= 127589 || x >= 127744 && x <= 127776 || x >= 127789 && x <= 127797 || x >= 127799 && x <= 127868 || x >= 127870 && x <= 127891 || x >= 127904 && x <= 127946 || x >= 127951 && x <= 127955 || x >= 127968 && x <= 127984 || x === 127988 || x >= 127992 && x <= 128062 || x === 128064 || x >= 128066 && x <= 128252 || x >= 128255 && x <= 128317 || x >= 128331 && x <= 128334 || x >= 128336 && x <= 128359 || x === 128378 || x === 128405 || x === 128406 || x === 128420 || x >= 128507 && x <= 128591 || x >= 128640 && x <= 128709 || x === 128716 || x >= 128720 && x <= 128722 || x >= 128725 && x <= 128727 || x >= 128732 && x <= 128735 || x === 128747 || x === 128748 || x >= 128756 && x <= 128764 || x >= 128992 && x <= 129003 || x === 129008 || x >= 129292 && x <= 129338 || x >= 129340 && x <= 129349 || x >= 129351 && x <= 129535 || x >= 129648 && x <= 129660 || x >= 129664 && x <= 129673 || x >= 129679 && x <= 129734 || x >= 129742 && x <= 129756 || x >= 129759 && x <= 129769 || x >= 129776 && x <= 129784 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141;
115
+ }
116
+
117
+ //#endregion
118
+ //#region ../../node_modules/.pnpm/get-east-asian-width@1.3.0/node_modules/get-east-asian-width/index.js
119
+ function validate(codePoint) {
120
+ if (!Number.isSafeInteger(codePoint)) throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
121
+ }
122
+ function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
123
+ validate(codePoint);
124
+ if (isFullWidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) return 2;
125
+ return 1;
126
+ }
8
127
 
9
128
  //#endregion
10
- //#region src/complete.ts
11
- function splitCommand(cmd) {
12
- const args = [];
13
- let current = "";
14
- let quote = null;
15
- let escape = false;
16
- for (const char of cmd) {
17
- if (escape) {
18
- current += char;
19
- escape = false;
129
+ //#region ../../node_modules/.pnpm/string-width@8.1.0/node_modules/string-width/index.js
130
+ /**
131
+ Logic:
132
+ - Segment graphemes to match how terminals render clusters.
133
+ - Width rules:
134
+ 1. Skip non-printing clusters (Default_Ignorable, Control, pure Mark, lone Surrogates). Tabs are ignored by design.
135
+ 2. RGI emoji clusters (\p{RGI_Emoji}) are double-width.
136
+ 3. Otherwise use East Asian Width of the cluster’s first visible code point, and add widths for trailing Halfwidth/Fullwidth Forms within the same cluster (e.g., dakuten/handakuten/prolonged sound mark).
137
+ */
138
+ const segmenter = new Intl.Segmenter();
139
+ const zeroWidthClusterRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v;
140
+ const leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v;
141
+ const rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
142
+ function baseVisible(segment) {
143
+ return segment.replace(leadingNonPrintingRegex, "");
144
+ }
145
+ function isZeroWidthCluster(segment) {
146
+ return zeroWidthClusterRegex.test(segment);
147
+ }
148
+ function trailingHalfwidthWidth(segment, eastAsianWidthOptions) {
149
+ let extra = 0;
150
+ if (segment.length > 1) {
151
+ for (const char of segment.slice(1)) if (char >= "＀" && char <= "￯") extra += eastAsianWidth(char.codePointAt(0), eastAsianWidthOptions);
152
+ }
153
+ return extra;
154
+ }
155
+ function stringWidth(input, options = {}) {
156
+ if (typeof input !== "string" || input.length === 0) return 0;
157
+ const { ambiguousIsNarrow = true, countAnsiEscapeCodes = false } = options;
158
+ let string = input;
159
+ if (!countAnsiEscapeCodes) string = stripAnsi(string);
160
+ if (string.length === 0) return 0;
161
+ let width = 0;
162
+ const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
163
+ for (const { segment } of segmenter.segment(string)) {
164
+ if (isZeroWidthCluster(segment)) continue;
165
+ if (rgiEmojiRegex.test(segment)) {
166
+ width += 2;
20
167
  continue;
21
168
  }
22
- if (char === "\\") {
23
- escape = true;
24
- continue;
169
+ const codePoint = baseVisible(segment).codePointAt(0);
170
+ width += eastAsianWidth(codePoint, eastAsianWidthOptions);
171
+ width += trailingHalfwidthWidth(segment, eastAsianWidthOptions);
172
+ }
173
+ return width;
174
+ }
175
+
176
+ //#endregion
177
+ //#region ../../node_modules/.pnpm/text-table@0.2.0/node_modules/text-table/index.js
178
+ var require_text_table = /* @__PURE__ */ __commonJSMin(((exports, module) => {
179
+ module.exports = function(rows_, opts) {
180
+ if (!opts) opts = {};
181
+ var hsep = opts.hsep === void 0 ? " " : opts.hsep;
182
+ var align = opts.align || [];
183
+ var stringLength = opts.stringLength || function(s) {
184
+ return String(s).length;
185
+ };
186
+ var dotsizes = reduce(rows_, function(acc, row) {
187
+ forEach(row, function(c, ix) {
188
+ var n = dotindex(c);
189
+ if (!acc[ix] || n > acc[ix]) acc[ix] = n;
190
+ });
191
+ return acc;
192
+ }, []);
193
+ var rows = map(rows_, function(row) {
194
+ return map(row, function(c_, ix) {
195
+ var c = String(c_);
196
+ if (align[ix] === ".") {
197
+ var index = dotindex(c);
198
+ var size = dotsizes[ix] + (/\./.test(c) ? 1 : 2) - (stringLength(c) - index);
199
+ return c + Array(size).join(" ");
200
+ } else return c;
201
+ });
202
+ });
203
+ var sizes = reduce(rows, function(acc, row) {
204
+ forEach(row, function(c, ix) {
205
+ var n = stringLength(c);
206
+ if (!acc[ix] || n > acc[ix]) acc[ix] = n;
207
+ });
208
+ return acc;
209
+ }, []);
210
+ return map(rows, function(row) {
211
+ return map(row, function(c, ix) {
212
+ var n = sizes[ix] - stringLength(c) || 0;
213
+ var s = Array(Math.max(n + 1, 1)).join(" ");
214
+ if (align[ix] === "r" || align[ix] === ".") return s + c;
215
+ if (align[ix] === "c") return Array(Math.ceil(n / 2 + 1)).join(" ") + c + Array(Math.floor(n / 2 + 1)).join(" ");
216
+ return c + s;
217
+ }).join(hsep).replace(/\s+$/, "");
218
+ }).join("\n");
219
+ };
220
+ function dotindex(c) {
221
+ var m = /\.[^.]*$/.exec(c);
222
+ return m ? m.index + 1 : c.length;
223
+ }
224
+ function reduce(xs, f, init) {
225
+ if (xs.reduce) return xs.reduce(f, init);
226
+ var i = 0;
227
+ var acc = arguments.length >= 3 ? init : xs[i++];
228
+ for (; i < xs.length; i++) f(acc, xs[i], i);
229
+ return acc;
230
+ }
231
+ function forEach(xs, f) {
232
+ if (xs.forEach) return xs.forEach(f);
233
+ for (var i = 0; i < xs.length; i++) f.call(xs, xs[i], i);
234
+ }
235
+ function map(xs, f) {
236
+ if (xs.map) return xs.map(f);
237
+ var res = [];
238
+ for (var i = 0; i < xs.length; i++) res.push(f.call(xs, xs[i], i));
239
+ return res;
240
+ }
241
+ }));
242
+
243
+ //#endregion
244
+ //#region ../../node_modules/.pnpm/yoctocolors@2.1.2/node_modules/yoctocolors/base.js
245
+ const hasColors = tty?.WriteStream?.prototype?.hasColors?.() ?? false;
246
+ const format = (open, close) => {
247
+ if (!hasColors) return (input) => input;
248
+ const openCode = `\u001B[${open}m`;
249
+ const closeCode = `\u001B[${close}m`;
250
+ return (input) => {
251
+ const string = input + "";
252
+ let index = string.indexOf(closeCode);
253
+ if (index === -1) return openCode + string + closeCode;
254
+ let result = openCode;
255
+ let lastIndex = 0;
256
+ const replaceCode = (close === 22 ? closeCode : "") + openCode;
257
+ while (index !== -1) {
258
+ result += string.slice(lastIndex, index) + replaceCode;
259
+ lastIndex = index + closeCode.length;
260
+ index = string.indexOf(closeCode, lastIndex);
261
+ }
262
+ result += string.slice(lastIndex) + closeCode;
263
+ return result;
264
+ };
265
+ };
266
+ const reset = format(0, 0);
267
+ const bold = format(1, 22);
268
+ const dim = format(2, 22);
269
+ const italic = format(3, 23);
270
+ const underline = format(4, 24);
271
+ const overline = format(53, 55);
272
+ const inverse = format(7, 27);
273
+ const hidden = format(8, 28);
274
+ const strikethrough = format(9, 29);
275
+ const black = format(30, 39);
276
+ const red = format(31, 39);
277
+ const green = format(32, 39);
278
+ const yellow = format(33, 39);
279
+ const blue = format(34, 39);
280
+ const magenta = format(35, 39);
281
+ const cyan = format(36, 39);
282
+ const white = format(37, 39);
283
+ const gray = format(90, 39);
284
+ const bgBlack = format(40, 49);
285
+ const bgRed = format(41, 49);
286
+ const bgGreen = format(42, 49);
287
+ const bgYellow = format(43, 49);
288
+ const bgBlue = format(44, 49);
289
+ const bgMagenta = format(45, 49);
290
+ const bgCyan = format(46, 49);
291
+ const bgWhite = format(47, 49);
292
+ const bgGray = format(100, 49);
293
+ const redBright = format(91, 39);
294
+ const greenBright = format(92, 39);
295
+ const yellowBright = format(93, 39);
296
+ const blueBright = format(94, 39);
297
+ const magentaBright = format(95, 39);
298
+ const cyanBright = format(96, 39);
299
+ const whiteBright = format(97, 39);
300
+ const bgRedBright = format(101, 49);
301
+ const bgGreenBright = format(102, 49);
302
+ const bgYellowBright = format(103, 49);
303
+ const bgBlueBright = format(104, 49);
304
+ const bgMagentaBright = format(105, 49);
305
+ const bgCyanBright = format(106, 49);
306
+ const bgWhiteBright = format(107, 49);
307
+
308
+ //#endregion
309
+ //#region ../plugin-help/src/renderer.ts
310
+ var import_text_table = /* @__PURE__ */ __toESM(require_text_table(), 1);
311
+ const DEFAULT_GROUP_KEY = "default";
312
+ const table = (items) => (0, import_text_table.default)(items, { stringLength: stringWidth });
313
+ const splitTable = (items) => table(items).split("\n");
314
+ const DELIMITER = "-";
315
+ const INDENT = " ".repeat(2);
316
+ const withIndent = (str) => `${INDENT}${str}`;
317
+ function groupDefinitionsToMap(definitions) {
318
+ const map$1 = /* @__PURE__ */ new Map();
319
+ if (definitions) for (const [key, name] of definitions) map$1.set(key, name);
320
+ return map$1;
321
+ }
322
+ function validateGroup(group, groupMap, itemType, itemName) {
323
+ if (group && group !== DEFAULT_GROUP_KEY && !groupMap.has(group)) throw new Error(`Unknown ${itemType} group "${group}" for "${itemName}". Available groups: ${[...groupMap.keys()].join(", ") || "(none)"}`);
324
+ }
325
+ var HelpRenderer = class {
326
+ _command;
327
+ get _commandGroups() {
328
+ return groupDefinitionsToMap(this._getGroups().commands);
329
+ }
330
+ get _flagGroups() {
331
+ return groupDefinitionsToMap(this._getGroups().flags);
332
+ }
333
+ get _globalFlagGroups() {
334
+ return groupDefinitionsToMap(this._getGroups().globalFlags);
335
+ }
336
+ constructor(_formatters, _cli, _globalFlags, _getGroups, _getExamples, _notes) {
337
+ this._formatters = _formatters;
338
+ this._cli = _cli;
339
+ this._globalFlags = _globalFlags;
340
+ this._getGroups = _getGroups;
341
+ this._getExamples = _getExamples;
342
+ this._notes = _notes;
343
+ }
344
+ setCommand(command) {
345
+ if (command) {
346
+ this._command = command;
347
+ this._getExamples = () => command?.help?.examples;
348
+ this._notes = command?.help?.notes;
349
+ }
350
+ }
351
+ renderSections(sections) {
352
+ return sections.filter(isTruthy).map((section) => {
353
+ const body = Array.isArray(section.body) ? section.body.filter((s) => s !== void 0).join("\n") : section.body;
354
+ if (!section.title) return body;
355
+ return `${underline(bold(section.title))}\n${body.split("\n").map(withIndent).join("\n")}`;
356
+ }).join("\n\n");
357
+ }
358
+ render() {
359
+ const sections = [
360
+ this.renderHeader(),
361
+ this.renderUsage(),
362
+ this.renderParameters(),
363
+ this.renderCommandFlags(),
364
+ this.renderGlobalFlags(),
365
+ this.renderCommands(),
366
+ this.renderExamples(),
367
+ this.renderNotes()
368
+ ];
369
+ return this.renderSections(sections);
370
+ }
371
+ renderHeader() {
372
+ const { _name, _version, _description } = this._cli;
373
+ const command = this._command;
374
+ const description = command ? command.description : _description;
375
+ const formattedCommandName = command?.name ? ` ${bold(command.name)}` : "";
376
+ const headerLine = command ? `${dim(_name)}${formattedCommandName}` : `${bold(_name)} ${formatVersion(_version)}`;
377
+ const alias = command?.alias ? `Alias${toArray(command.alias).length > 1 ? "es" : ""}: ${toArray(command.alias).map((a) => bold(a)).join(", ")}` : void 0;
378
+ return { body: [`${headerLine}${description ? ` ${DELIMITER} ${description}` : ""}`, alias] };
379
+ }
380
+ renderUsage() {
381
+ const { _scriptName } = this._cli;
382
+ const command = this._command;
383
+ let usage = `$ ${_scriptName}`;
384
+ if (command) {
385
+ if (command.name) usage += ` ${command.name}`;
386
+ if (command.parameters) usage += ` ${command.parameters.map((p$1) => typeof p$1 === "string" ? p$1 : p$1.key).join(" ")}`;
387
+ } else if (this._cli._commands.size > 0 && !(this._cli._commands.has("") && this._cli._commands.size === 1)) usage += this._cli._commands.has("") ? " [command]" : " <command>";
388
+ if (command?.flags && !objectIsEmpty(command.flags) || !objectIsEmpty(this._globalFlags)) usage += " [flags]";
389
+ return {
390
+ title: "Usage",
391
+ body: [usage]
392
+ };
393
+ }
394
+ renderParameters() {
395
+ const command = this._command;
396
+ if (!command?.parameters || command.parameters.length === 0) return;
397
+ return {
398
+ title: "Parameters",
399
+ body: splitTable(command.parameters.map((parameter) => {
400
+ const key = typeof parameter === "string" ? parameter : parameter.key;
401
+ const type = typeof parameter === "string" ? void 0 : parameter.type;
402
+ const description = typeof parameter === "string" ? void 0 : parameter.description;
403
+ return [
404
+ bold(key),
405
+ type ? this._formatters.formatTypeValue(type) : "string",
406
+ description
407
+ ].filter(isTruthy);
408
+ }))
409
+ };
410
+ }
411
+ getSubcommands(parentCommandName) {
412
+ const subcommands = /* @__PURE__ */ new Map();
413
+ if (parentCommandName === "") return subcommands;
414
+ const prefix = `${parentCommandName} `;
415
+ for (const [name, command] of this._cli._commands) if (name.startsWith(prefix)) {
416
+ const subcommandName = name.slice(prefix.length);
417
+ subcommands.set(subcommandName, command);
418
+ }
419
+ return subcommands;
420
+ }
421
+ buildGroupedCommandsBody(commandsToShow, prefix) {
422
+ const groupedCommands = /* @__PURE__ */ new Map();
423
+ const defaultCommands = [];
424
+ let rootCommand = [];
425
+ for (const command of commandsToShow.values()) {
426
+ if (command.__isAlias || command.help?.show === false) continue;
427
+ const group = command.help?.group;
428
+ validateGroup(group, this._commandGroups, "command", command.name);
429
+ const item = [`${bold(formatCommandName(command.name.slice(prefix.length)))}${command.alias ? ` (${toArray(command.alias).join(", ")})` : ""}`, command.description].filter(isTruthy);
430
+ if (command.name === "") rootCommand = item;
431
+ else if (group && group !== DEFAULT_GROUP_KEY) {
432
+ const groupItems = groupedCommands.get(group) ?? [];
433
+ groupItems.push(item);
434
+ groupedCommands.set(group, groupItems);
435
+ } else defaultCommands.push(item);
25
436
  }
26
- if (quote) if (char === quote) quote = null;
27
- else current += char;
28
- else if (char === "\"" || char === "'") quote = char;
29
- else if (/\s/.test(char)) {
30
- if (current) {
31
- args.push(current);
32
- current = "";
437
+ const body = [];
438
+ const defaultGroup = [];
439
+ if (rootCommand.length > 0) defaultGroup.push(rootCommand);
440
+ if (defaultCommands.length > 0) defaultGroup.push(...defaultCommands);
441
+ if (defaultGroup.length > 0) body.push(...splitTable(defaultGroup));
442
+ for (const [key, name] of this._commandGroups) {
443
+ const items = groupedCommands.get(key);
444
+ if (items && items.length > 0) {
445
+ if (body.length > 0) body.push("");
446
+ body.push(`${dim(name)}`);
447
+ body.push(...splitTable(items).map(withIndent));
33
448
  }
34
- } else current += char;
35
- }
36
- if (current) args.push(current);
37
- return args;
38
- }
39
- async function getCompletion(cli, env) {
40
- const inputArgv = splitCommand(env.partial.slice(0, env.partial.length - env.lastPartial.length)).slice(1);
41
- if (inputArgv.includes(DOUBLE_DASH)) return [];
42
- const [command, commandName] = resolveCommand(cli._commands, inputArgv);
43
- if (env.lastPartial.startsWith("-")) {
44
- const flags = command ? {
45
- ...cli._globalFlags,
46
- ...command.flags
47
- } : cli._globalFlags;
48
- const candidates$1 = [];
49
- for (const [name, def] of Object.entries(flags)) {
50
- const normalized = normalizeFlagValue(def);
51
- candidates$1.push({
52
- name: formatFlagName(name),
53
- description: normalized.description
54
- });
55
- if (normalized.alias) {
56
- const aliases = toArray(normalized.alias);
57
- for (const alias of aliases) candidates$1.push({
58
- name: formatFlagName(alias),
59
- description: normalized.description
449
+ }
450
+ return body;
451
+ }
452
+ renderAvailableSubcommands(parentCommandName) {
453
+ const subcommands = this.getSubcommands(parentCommandName);
454
+ if (subcommands.size === 0) return "";
455
+ const prefix = `${parentCommandName} `;
456
+ const body = this.buildGroupedCommandsBody(subcommands, prefix);
457
+ if (body.length === 0) return "";
458
+ const sections = [{ body: `${this._cli._name} ${bold(parentCommandName)} not found` }, {
459
+ title: "Available Subcommands",
460
+ body
461
+ }];
462
+ return this.renderSections(sections);
463
+ }
464
+ renderCommands() {
465
+ const commands = this._cli._commands;
466
+ let commandsToShow;
467
+ let title = "Commands";
468
+ let prefix = "";
469
+ if (this._command) {
470
+ prefix = this._command.name ? `${this._command.name} ` : "";
471
+ title = "Subcommands";
472
+ commandsToShow = this.getSubcommands(this._command.name);
473
+ if (commandsToShow.size === 0) return;
474
+ } else commandsToShow = commands;
475
+ if (commandsToShow.size === 0) return;
476
+ const body = this.buildGroupedCommandsBody(commandsToShow, prefix);
477
+ return {
478
+ title,
479
+ body
480
+ };
481
+ }
482
+ renderFlagItem(name, flag) {
483
+ flag = normalizeFlagValue(flag);
484
+ const flagName = formatFlagName(name);
485
+ const shortFlag = flag.short ? formatFlagName(flag.short) : "";
486
+ const type = this._formatters.formatTypeValue(flag.type);
487
+ return [
488
+ bold([flagName, shortFlag].filter(Boolean).join(", ")),
489
+ dim(type),
490
+ flag.description,
491
+ flag.default !== void 0 && dim(`[default: ${bold(this._formatters.formatFlagDefault(flag.default))}]`)
492
+ ].filter(isTruthy);
493
+ }
494
+ renderGroupedFlags(flags, groupMap, itemType) {
495
+ const groupedFlags = /* @__PURE__ */ new Map();
496
+ const defaultFlags = [];
497
+ for (const [name, flag] of Object.entries(flags)) {
498
+ const group = flag.help?.group;
499
+ validateGroup(group, groupMap, itemType, name);
500
+ const item = this.renderFlagItem(name, flag);
501
+ if (group && group !== DEFAULT_GROUP_KEY) {
502
+ const groupItems = groupedFlags.get(group) ?? [];
503
+ groupItems.push(item);
504
+ groupedFlags.set(group, groupItems);
505
+ } else defaultFlags.push(item);
506
+ }
507
+ const body = [];
508
+ if (defaultFlags.length > 0) body.push(...splitTable(defaultFlags));
509
+ for (const [key, name] of groupMap) {
510
+ const items = groupedFlags.get(key);
511
+ if (items && items.length > 0) {
512
+ if (body.length > 0) body.push("");
513
+ body.push(`${dim(name)}`);
514
+ body.push(...splitTable(items).map(withIndent));
515
+ }
516
+ }
517
+ return body;
518
+ }
519
+ renderCommandFlags() {
520
+ const command = this._command;
521
+ if (!command?.flags || objectIsEmpty(command.flags)) return;
522
+ return {
523
+ title: "Flags",
524
+ body: this.renderGroupedFlags(command.flags, this._flagGroups, "flag")
525
+ };
526
+ }
527
+ renderGlobalFlags() {
528
+ if (!this._globalFlags || objectIsEmpty(this._globalFlags)) return;
529
+ return {
530
+ title: "Global Flags",
531
+ body: this.renderGroupedFlags(this._globalFlags, this._globalFlagGroups, "global flag")
532
+ };
533
+ }
534
+ renderNotes() {
535
+ if (!this._notes?.length) return;
536
+ return {
537
+ title: "Notes",
538
+ body: this._notes
539
+ };
540
+ }
541
+ renderExamples() {
542
+ const examples = this._getExamples();
543
+ if (!examples?.length) return;
544
+ return {
545
+ title: "Examples",
546
+ body: splitTable(examples.map(([command, description]) => {
547
+ return [
548
+ command,
549
+ DELIMITER,
550
+ description
551
+ ];
552
+ }))
553
+ };
554
+ }
555
+ };
556
+
557
+ //#endregion
558
+ //#region ../plugin-help/src/store.ts
559
+ function addStoreApi(cli, { groups }) {
560
+ cli.store.help = { addGroup: (options) => {
561
+ if (options.commands) groups.commands = [...groups.commands ?? [], ...options.commands];
562
+ if (options.flags) groups.flags = [...groups.flags ?? [], ...options.flags];
563
+ if (options.globalFlags) groups.globalFlags = [...groups.globalFlags ?? [], ...options.globalFlags];
564
+ } };
565
+ }
566
+
567
+ //#endregion
568
+ //#region ../plugin-help/src/index.ts
569
+ const helpPlugin = ({ command = true, flag = true, showHelpWhenNoCommandSpecified = true, notes, examples, banner, formatters, groups = {} } = {}) => definePlugin({ setup: (cli) => {
570
+ addStoreApi(cli, { groups });
571
+ const mergedFormatters = {
572
+ ...defaultFormatters,
573
+ ...formatters
574
+ };
575
+ const generalHelpNotes = [
576
+ "If no command is specified, show help for the CLI.",
577
+ "If a command is specified, show help for the command.",
578
+ flag && "-h is an alias for --help."
579
+ ].filter(isTruthy);
580
+ const getGeneralHelpExamples = () => [
581
+ command && [`$ ${cli._scriptName} help`, "Show help"],
582
+ command && [`$ ${cli._scriptName} help <command>`, "Show help for a specific command"],
583
+ flag && [`$ ${cli._scriptName} <command> --help`, "Show help for a specific command"]
584
+ ].filter(isTruthy);
585
+ const effectiveNotes = notes ?? generalHelpNotes;
586
+ const getEffectiveExamples = () => examples ?? getGeneralHelpExamples();
587
+ function printHelp(s) {
588
+ if (banner) console.log(banner);
589
+ console.log(s);
590
+ }
591
+ const renderer = new HelpRenderer(mergedFormatters, cli, cli._globalFlags, () => groups, getEffectiveExamples, effectiveNotes);
592
+ function tryPrintSubcommandsHelp(commandName) {
593
+ const subcommandsOutput = renderer.renderAvailableSubcommands(commandName);
594
+ if (subcommandsOutput) {
595
+ printHelp(subcommandsOutput);
596
+ return true;
597
+ }
598
+ return false;
599
+ }
600
+ if (command) cli.command("help", "Show help", {
601
+ parameters: ["[command...]"],
602
+ help: {
603
+ notes: generalHelpNotes,
604
+ examples: getGeneralHelpExamples()
605
+ }
606
+ }).on("help", (ctx) => {
607
+ const commandName = ctx.parameters.command;
608
+ let command$1;
609
+ if (commandName.length > 0) {
610
+ [command$1] = resolveCommand(cli._commands, commandName);
611
+ if (!command$1) {
612
+ const parentCommandName = commandName.join(" ");
613
+ if (tryPrintSubcommandsHelp(parentCommandName)) return;
614
+ throw new NoSuchCommandError(parentCommandName);
615
+ }
616
+ }
617
+ renderer.setCommand(command$1);
618
+ printHelp(renderer.render());
619
+ });
620
+ if (flag) cli.globalFlag("help", "Show help", {
621
+ short: "h",
622
+ type: Boolean,
623
+ default: false
624
+ });
625
+ cli.interceptor({
626
+ enforce: "post",
627
+ handler: async (ctx, next) => {
628
+ if (ctx.flags.help) {
629
+ const command$1 = ctx.command;
630
+ if (!command$1 && ctx.rawParsed.parameters.length > 0) {
631
+ if (tryPrintSubcommandsHelp(ctx.rawParsed.parameters.join(" "))) return;
632
+ await next();
633
+ }
634
+ renderer.setCommand(command$1);
635
+ printHelp(renderer.render());
636
+ } else if (showHelpWhenNoCommandSpecified && !ctx.command && ctx.rawParsed.parameters.length === 0) printHelp(renderer.render());
637
+ else await next();
638
+ }
639
+ });
640
+ } });
641
+
642
+ //#endregion
643
+ //#region ../plugin-version/src/index.ts
644
+ const versionPlugin = ({ command = true, flag = true } = {}) => definePlugin({ setup: (cli) => {
645
+ const formattedVersion = formatVersion(cli._version);
646
+ if (command) cli.command("version", "Prints current version", {}).on("version", () => {
647
+ console.log(formattedVersion);
648
+ });
649
+ if (flag) cli.globalFlag("version", "Prints current version", {
650
+ short: "V",
651
+ type: Boolean,
652
+ default: false
653
+ }).interceptor({
654
+ enforce: "pre",
655
+ handler: async (ctx, next) => {
656
+ if (ctx.flags.version) console.log(formattedVersion);
657
+ else await next();
658
+ }
659
+ });
660
+ } });
661
+
662
+ //#endregion
663
+ //#region ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
664
+ var require_picocolors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
665
+ let p = process || {}, argv = p.argv || [], env = p.env || {};
666
+ let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
667
+ let formatter = (open, close, replace = open) => (input) => {
668
+ let string = "" + input, index = string.indexOf(close, open.length);
669
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
670
+ };
671
+ let replaceClose = (string, close, replace, index) => {
672
+ let result = "", cursor = 0;
673
+ do {
674
+ result += string.substring(cursor, index) + replace;
675
+ cursor = index + close.length;
676
+ index = string.indexOf(close, cursor);
677
+ } while (~index);
678
+ return result + string.substring(cursor);
679
+ };
680
+ let createColors = (enabled = isColorSupported) => {
681
+ let f = enabled ? formatter : () => String;
682
+ return {
683
+ isColorSupported: enabled,
684
+ reset: f("\x1B[0m", "\x1B[0m"),
685
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
686
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
687
+ italic: f("\x1B[3m", "\x1B[23m"),
688
+ underline: f("\x1B[4m", "\x1B[24m"),
689
+ inverse: f("\x1B[7m", "\x1B[27m"),
690
+ hidden: f("\x1B[8m", "\x1B[28m"),
691
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
692
+ black: f("\x1B[30m", "\x1B[39m"),
693
+ red: f("\x1B[31m", "\x1B[39m"),
694
+ green: f("\x1B[32m", "\x1B[39m"),
695
+ yellow: f("\x1B[33m", "\x1B[39m"),
696
+ blue: f("\x1B[34m", "\x1B[39m"),
697
+ magenta: f("\x1B[35m", "\x1B[39m"),
698
+ cyan: f("\x1B[36m", "\x1B[39m"),
699
+ white: f("\x1B[37m", "\x1B[39m"),
700
+ gray: f("\x1B[90m", "\x1B[39m"),
701
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
702
+ bgRed: f("\x1B[41m", "\x1B[49m"),
703
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
704
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
705
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
706
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
707
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
708
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
709
+ blackBright: f("\x1B[90m", "\x1B[39m"),
710
+ redBright: f("\x1B[91m", "\x1B[39m"),
711
+ greenBright: f("\x1B[92m", "\x1B[39m"),
712
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
713
+ blueBright: f("\x1B[94m", "\x1B[39m"),
714
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
715
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
716
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
717
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
718
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
719
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
720
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
721
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
722
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
723
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
724
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
725
+ };
726
+ };
727
+ module.exports = createColors();
728
+ module.exports.createColors = createColors;
729
+ }));
730
+
731
+ //#endregion
732
+ //#region ../../node_modules/.pnpm/kons@0.7.1/node_modules/kons/dist/utils-6230ae77.mjs
733
+ var import_picocolors$1 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
734
+ function parseStack(stack) {
735
+ return stack.split("\n").splice(1).map((l) => l.trim().replace("file://", ""));
736
+ }
737
+ function formatStack(stack) {
738
+ return `
739
+ ${parseStack(stack).map((line) => ` ${line.replace(/^at ([\s\S]+) \((.+)\)/, (_, m1, m2) => import_picocolors$1.default.gray(`at ${m1} (${import_picocolors$1.default.cyan(m2)})`))}`).join("\n")}`;
740
+ }
741
+ const NEWLINE_RE = /\r?\n/g;
742
+ function formatMessage(messages) {
743
+ return messages.map((m) => {
744
+ if (typeof (m == null ? void 0 : m.stack) === "string") return [m.message, formatStack(m.stack)];
745
+ if (typeof m === "string") return m.split(NEWLINE_RE);
746
+ return m;
747
+ }).flat();
748
+ }
749
+ function createBadge(badgeType, bgColor) {
750
+ const upperType = badgeType.toUpperCase();
751
+ const bgColorFormatter = import_picocolors$1.default[bgColor];
752
+ return import_picocolors$1.default.bold(import_picocolors$1.default.inverse(bgColorFormatter(` ${upperType} `)));
753
+ }
754
+
755
+ //#endregion
756
+ //#region ../../node_modules/.pnpm/kons@0.7.1/node_modules/kons/dist/index.mjs
757
+ var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
758
+ function createFormatter(type, bgColor, { target = console.log, textColor, newline = true } = {}) {
759
+ const bgColorFormatter = import_picocolors.default[bgColor];
760
+ const textColorFormatter = textColor ? import_picocolors.default[textColor] : bgColorFormatter;
761
+ return (...messages) => {
762
+ const formattedMessages = formatMessage(messages);
763
+ const badge = createBadge(type, bgColor);
764
+ for (const message of formattedMessages) target(`${badge} ${textColorFormatter(message)}${newline ? "\n" : ""}`);
765
+ };
766
+ }
767
+ const log = createFormatter("log", "gray");
768
+ const info = createFormatter("info", "blue", { target: console.info });
769
+ const warn = createFormatter("warn", "yellow", { target: console.warn });
770
+ const success = createFormatter("success", "green");
771
+ const error = createFormatter("error", "red", { target: console.error });
772
+
773
+ //#endregion
774
+ //#region ../plugin-friendly-error/src/index.ts
775
+ const friendlyErrorPlugin = ({ target = error } = {}) => definePlugin({ setup: (cli) => cli.errorHandler((err) => {
776
+ target(err.message);
777
+ process.exit(1);
778
+ }) });
779
+
780
+ //#endregion
781
+ //#region ../../node_modules/.pnpm/fastest-levenshtein@1.0.16/node_modules/fastest-levenshtein/mod.js
782
+ var require_fastest_levenshtein = /* @__PURE__ */ __commonJSMin(((exports) => {
783
+ exports.__esModule = true;
784
+ exports.distance = exports.closest = void 0;
785
+ var peq = new Uint32Array(65536);
786
+ var myers_32 = function(a, b) {
787
+ var n = a.length;
788
+ var m = b.length;
789
+ var lst = 1 << n - 1;
790
+ var pv = -1;
791
+ var mv = 0;
792
+ var sc = n;
793
+ var i = n;
794
+ while (i--) peq[a.charCodeAt(i)] |= 1 << i;
795
+ for (i = 0; i < m; i++) {
796
+ var eq = peq[b.charCodeAt(i)];
797
+ var xv = eq | mv;
798
+ eq |= (eq & pv) + pv ^ pv;
799
+ mv |= ~(eq | pv);
800
+ pv &= eq;
801
+ if (mv & lst) sc++;
802
+ if (pv & lst) sc--;
803
+ mv = mv << 1 | 1;
804
+ pv = pv << 1 | ~(xv | mv);
805
+ mv &= xv;
806
+ }
807
+ i = n;
808
+ while (i--) peq[a.charCodeAt(i)] = 0;
809
+ return sc;
810
+ };
811
+ var myers_x = function(b, a) {
812
+ var n = a.length;
813
+ var m = b.length;
814
+ var mhc = [];
815
+ var phc = [];
816
+ var hsize = Math.ceil(n / 32);
817
+ var vsize = Math.ceil(m / 32);
818
+ for (var i = 0; i < hsize; i++) {
819
+ phc[i] = -1;
820
+ mhc[i] = 0;
821
+ }
822
+ var j = 0;
823
+ for (; j < vsize - 1; j++) {
824
+ var mv_1 = 0;
825
+ var pv_1 = -1;
826
+ var start_1 = j * 32;
827
+ var vlen_1 = Math.min(32, m) + start_1;
828
+ for (var k = start_1; k < vlen_1; k++) peq[b.charCodeAt(k)] |= 1 << k;
829
+ for (var i = 0; i < n; i++) {
830
+ var eq = peq[a.charCodeAt(i)];
831
+ var pb = phc[i / 32 | 0] >>> i & 1;
832
+ var mb = mhc[i / 32 | 0] >>> i & 1;
833
+ var xv = eq | mv_1;
834
+ var xh = ((eq | mb) & pv_1) + pv_1 ^ pv_1 | eq | mb;
835
+ var ph = mv_1 | ~(xh | pv_1);
836
+ var mh = pv_1 & xh;
837
+ if (ph >>> 31 ^ pb) phc[i / 32 | 0] ^= 1 << i;
838
+ if (mh >>> 31 ^ mb) mhc[i / 32 | 0] ^= 1 << i;
839
+ ph = ph << 1 | pb;
840
+ mh = mh << 1 | mb;
841
+ pv_1 = mh | ~(xv | ph);
842
+ mv_1 = ph & xv;
843
+ }
844
+ for (var k = start_1; k < vlen_1; k++) peq[b.charCodeAt(k)] = 0;
845
+ }
846
+ var mv = 0;
847
+ var pv = -1;
848
+ var start = j * 32;
849
+ var vlen = Math.min(32, m - start) + start;
850
+ for (var k = start; k < vlen; k++) peq[b.charCodeAt(k)] |= 1 << k;
851
+ var score = m;
852
+ for (var i = 0; i < n; i++) {
853
+ var eq = peq[a.charCodeAt(i)];
854
+ var pb = phc[i / 32 | 0] >>> i & 1;
855
+ var mb = mhc[i / 32 | 0] >>> i & 1;
856
+ var xv = eq | mv;
857
+ var xh = ((eq | mb) & pv) + pv ^ pv | eq | mb;
858
+ var ph = mv | ~(xh | pv);
859
+ var mh = pv & xh;
860
+ score += ph >>> m - 1 & 1;
861
+ score -= mh >>> m - 1 & 1;
862
+ if (ph >>> 31 ^ pb) phc[i / 32 | 0] ^= 1 << i;
863
+ if (mh >>> 31 ^ mb) mhc[i / 32 | 0] ^= 1 << i;
864
+ ph = ph << 1 | pb;
865
+ mh = mh << 1 | mb;
866
+ pv = mh | ~(xv | ph);
867
+ mv = ph & xv;
868
+ }
869
+ for (var k = start; k < vlen; k++) peq[b.charCodeAt(k)] = 0;
870
+ return score;
871
+ };
872
+ var distance$1 = function(a, b) {
873
+ if (a.length < b.length) {
874
+ var tmp = b;
875
+ b = a;
876
+ a = tmp;
877
+ }
878
+ if (b.length === 0) return a.length;
879
+ if (a.length <= 32) return myers_32(a, b);
880
+ return myers_x(a, b);
881
+ };
882
+ exports.distance = distance$1;
883
+ var closest = function(str, arr) {
884
+ var min_distance = Infinity;
885
+ var min_index = 0;
886
+ for (var i = 0; i < arr.length; i++) {
887
+ var dist = distance$1(str, arr[i]);
888
+ if (dist < min_distance) {
889
+ min_distance = dist;
890
+ min_index = i;
891
+ }
892
+ }
893
+ return arr[min_index];
894
+ };
895
+ exports.closest = closest;
896
+ }));
897
+
898
+ //#endregion
899
+ //#region ../../node_modules/.pnpm/lodash.deburr@4.1.0/node_modules/lodash.deburr/index.js
900
+ var require_lodash = /* @__PURE__ */ __commonJSMin(((exports, module) => {
901
+ /**
902
+ * lodash (Custom Build) <https://lodash.com/>
903
+ * Build: `lodash modularize exports="npm" -o ./`
904
+ * Copyright jQuery Foundation and other contributors <https://jquery.org/>
905
+ * Released under MIT license <https://lodash.com/license>
906
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
907
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
908
+ */
909
+ /** Used as references for various `Number` constants. */
910
+ var INFINITY = Infinity;
911
+ /** `Object#toString` result references. */
912
+ var symbolTag = "[object Symbol]";
913
+ /** Used to match Latin Unicode letters (excluding mathematical operators). */
914
+ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
915
+ /**
916
+ * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
917
+ * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
918
+ */
919
+ var reComboMark = RegExp("[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]", "g");
920
+ /** Used to map Latin Unicode letters to basic Latin letters. */
921
+ var deburredLetters = {
922
+ "À": "A",
923
+ "Á": "A",
924
+ "Â": "A",
925
+ "Ã": "A",
926
+ "Ä": "A",
927
+ "Å": "A",
928
+ "à": "a",
929
+ "á": "a",
930
+ "â": "a",
931
+ "ã": "a",
932
+ "ä": "a",
933
+ "å": "a",
934
+ "Ç": "C",
935
+ "ç": "c",
936
+ "Ð": "D",
937
+ "ð": "d",
938
+ "È": "E",
939
+ "É": "E",
940
+ "Ê": "E",
941
+ "Ë": "E",
942
+ "è": "e",
943
+ "é": "e",
944
+ "ê": "e",
945
+ "ë": "e",
946
+ "Ì": "I",
947
+ "Í": "I",
948
+ "Î": "I",
949
+ "Ï": "I",
950
+ "ì": "i",
951
+ "í": "i",
952
+ "î": "i",
953
+ "ï": "i",
954
+ "Ñ": "N",
955
+ "ñ": "n",
956
+ "Ò": "O",
957
+ "Ó": "O",
958
+ "Ô": "O",
959
+ "Õ": "O",
960
+ "Ö": "O",
961
+ "Ø": "O",
962
+ "ò": "o",
963
+ "ó": "o",
964
+ "ô": "o",
965
+ "õ": "o",
966
+ "ö": "o",
967
+ "ø": "o",
968
+ "Ù": "U",
969
+ "Ú": "U",
970
+ "Û": "U",
971
+ "Ü": "U",
972
+ "ù": "u",
973
+ "ú": "u",
974
+ "û": "u",
975
+ "ü": "u",
976
+ "Ý": "Y",
977
+ "ý": "y",
978
+ "ÿ": "y",
979
+ "Æ": "Ae",
980
+ "æ": "ae",
981
+ "Þ": "Th",
982
+ "þ": "th",
983
+ "ß": "ss",
984
+ "Ā": "A",
985
+ "Ă": "A",
986
+ "Ą": "A",
987
+ "ā": "a",
988
+ "ă": "a",
989
+ "ą": "a",
990
+ "Ć": "C",
991
+ "Ĉ": "C",
992
+ "Ċ": "C",
993
+ "Č": "C",
994
+ "ć": "c",
995
+ "ĉ": "c",
996
+ "ċ": "c",
997
+ "č": "c",
998
+ "Ď": "D",
999
+ "Đ": "D",
1000
+ "ď": "d",
1001
+ "đ": "d",
1002
+ "Ē": "E",
1003
+ "Ĕ": "E",
1004
+ "Ė": "E",
1005
+ "Ę": "E",
1006
+ "Ě": "E",
1007
+ "ē": "e",
1008
+ "ĕ": "e",
1009
+ "ė": "e",
1010
+ "ę": "e",
1011
+ "ě": "e",
1012
+ "Ĝ": "G",
1013
+ "Ğ": "G",
1014
+ "Ġ": "G",
1015
+ "Ģ": "G",
1016
+ "ĝ": "g",
1017
+ "ğ": "g",
1018
+ "ġ": "g",
1019
+ "ģ": "g",
1020
+ "Ĥ": "H",
1021
+ "Ħ": "H",
1022
+ "ĥ": "h",
1023
+ "ħ": "h",
1024
+ "Ĩ": "I",
1025
+ "Ī": "I",
1026
+ "Ĭ": "I",
1027
+ "Į": "I",
1028
+ "İ": "I",
1029
+ "ĩ": "i",
1030
+ "ī": "i",
1031
+ "ĭ": "i",
1032
+ "į": "i",
1033
+ "ı": "i",
1034
+ "Ĵ": "J",
1035
+ "ĵ": "j",
1036
+ "Ķ": "K",
1037
+ "ķ": "k",
1038
+ "ĸ": "k",
1039
+ "Ĺ": "L",
1040
+ "Ļ": "L",
1041
+ "Ľ": "L",
1042
+ "Ŀ": "L",
1043
+ "Ł": "L",
1044
+ "ĺ": "l",
1045
+ "ļ": "l",
1046
+ "ľ": "l",
1047
+ "ŀ": "l",
1048
+ "ł": "l",
1049
+ "Ń": "N",
1050
+ "Ņ": "N",
1051
+ "Ň": "N",
1052
+ "Ŋ": "N",
1053
+ "ń": "n",
1054
+ "ņ": "n",
1055
+ "ň": "n",
1056
+ "ŋ": "n",
1057
+ "Ō": "O",
1058
+ "Ŏ": "O",
1059
+ "Ő": "O",
1060
+ "ō": "o",
1061
+ "ŏ": "o",
1062
+ "ő": "o",
1063
+ "Ŕ": "R",
1064
+ "Ŗ": "R",
1065
+ "Ř": "R",
1066
+ "ŕ": "r",
1067
+ "ŗ": "r",
1068
+ "ř": "r",
1069
+ "Ś": "S",
1070
+ "Ŝ": "S",
1071
+ "Ş": "S",
1072
+ "Š": "S",
1073
+ "ś": "s",
1074
+ "ŝ": "s",
1075
+ "ş": "s",
1076
+ "š": "s",
1077
+ "Ţ": "T",
1078
+ "Ť": "T",
1079
+ "Ŧ": "T",
1080
+ "ţ": "t",
1081
+ "ť": "t",
1082
+ "ŧ": "t",
1083
+ "Ũ": "U",
1084
+ "Ū": "U",
1085
+ "Ŭ": "U",
1086
+ "Ů": "U",
1087
+ "Ű": "U",
1088
+ "Ų": "U",
1089
+ "ũ": "u",
1090
+ "ū": "u",
1091
+ "ŭ": "u",
1092
+ "ů": "u",
1093
+ "ű": "u",
1094
+ "ų": "u",
1095
+ "Ŵ": "W",
1096
+ "ŵ": "w",
1097
+ "Ŷ": "Y",
1098
+ "ŷ": "y",
1099
+ "Ÿ": "Y",
1100
+ "Ź": "Z",
1101
+ "Ż": "Z",
1102
+ "Ž": "Z",
1103
+ "ź": "z",
1104
+ "ż": "z",
1105
+ "ž": "z",
1106
+ "IJ": "IJ",
1107
+ "ij": "ij",
1108
+ "Œ": "Oe",
1109
+ "œ": "oe",
1110
+ "ʼn": "'n",
1111
+ "ſ": "ss"
1112
+ };
1113
+ /** Detect free variable `global` from Node.js. */
1114
+ var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
1115
+ /** Detect free variable `self`. */
1116
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
1117
+ /** Used as a reference to the global object. */
1118
+ var root = freeGlobal || freeSelf || Function("return this")();
1119
+ /**
1120
+ * The base implementation of `_.propertyOf` without support for deep paths.
1121
+ *
1122
+ * @private
1123
+ * @param {Object} object The object to query.
1124
+ * @returns {Function} Returns the new accessor function.
1125
+ */
1126
+ function basePropertyOf(object) {
1127
+ return function(key) {
1128
+ return object == null ? void 0 : object[key];
1129
+ };
1130
+ }
1131
+ /**
1132
+ * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
1133
+ * letters to basic Latin letters.
1134
+ *
1135
+ * @private
1136
+ * @param {string} letter The matched letter to deburr.
1137
+ * @returns {string} Returns the deburred letter.
1138
+ */
1139
+ var deburrLetter = basePropertyOf(deburredLetters);
1140
+ /**
1141
+ * Used to resolve the
1142
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
1143
+ * of values.
1144
+ */
1145
+ var objectToString = Object.prototype.toString;
1146
+ /** Built-in value references. */
1147
+ var Symbol$1 = root.Symbol;
1148
+ /** Used to convert symbols to primitives and strings. */
1149
+ var symbolProto = Symbol$1 ? Symbol$1.prototype : void 0, symbolToString = symbolProto ? symbolProto.toString : void 0;
1150
+ /**
1151
+ * The base implementation of `_.toString` which doesn't convert nullish
1152
+ * values to empty strings.
1153
+ *
1154
+ * @private
1155
+ * @param {*} value The value to process.
1156
+ * @returns {string} Returns the string.
1157
+ */
1158
+ function baseToString(value) {
1159
+ if (typeof value == "string") return value;
1160
+ if (isSymbol(value)) return symbolToString ? symbolToString.call(value) : "";
1161
+ var result = value + "";
1162
+ return result == "0" && 1 / value == -INFINITY ? "-0" : result;
1163
+ }
1164
+ /**
1165
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
1166
+ * and has a `typeof` result of "object".
1167
+ *
1168
+ * @static
1169
+ * @memberOf _
1170
+ * @since 4.0.0
1171
+ * @category Lang
1172
+ * @param {*} value The value to check.
1173
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
1174
+ * @example
1175
+ *
1176
+ * _.isObjectLike({});
1177
+ * // => true
1178
+ *
1179
+ * _.isObjectLike([1, 2, 3]);
1180
+ * // => true
1181
+ *
1182
+ * _.isObjectLike(_.noop);
1183
+ * // => false
1184
+ *
1185
+ * _.isObjectLike(null);
1186
+ * // => false
1187
+ */
1188
+ function isObjectLike(value) {
1189
+ return !!value && typeof value == "object";
1190
+ }
1191
+ /**
1192
+ * Checks if `value` is classified as a `Symbol` primitive or object.
1193
+ *
1194
+ * @static
1195
+ * @memberOf _
1196
+ * @since 4.0.0
1197
+ * @category Lang
1198
+ * @param {*} value The value to check.
1199
+ * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
1200
+ * @example
1201
+ *
1202
+ * _.isSymbol(Symbol.iterator);
1203
+ * // => true
1204
+ *
1205
+ * _.isSymbol('abc');
1206
+ * // => false
1207
+ */
1208
+ function isSymbol(value) {
1209
+ return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
1210
+ }
1211
+ /**
1212
+ * Converts `value` to a string. An empty string is returned for `null`
1213
+ * and `undefined` values. The sign of `-0` is preserved.
1214
+ *
1215
+ * @static
1216
+ * @memberOf _
1217
+ * @since 4.0.0
1218
+ * @category Lang
1219
+ * @param {*} value The value to process.
1220
+ * @returns {string} Returns the string.
1221
+ * @example
1222
+ *
1223
+ * _.toString(null);
1224
+ * // => ''
1225
+ *
1226
+ * _.toString(-0);
1227
+ * // => '-0'
1228
+ *
1229
+ * _.toString([1, 2, 3]);
1230
+ * // => '1,2,3'
1231
+ */
1232
+ function toString(value) {
1233
+ return value == null ? "" : baseToString(value);
1234
+ }
1235
+ /**
1236
+ * Deburrs `string` by converting
1237
+ * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
1238
+ * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
1239
+ * letters to basic Latin letters and removing
1240
+ * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
1241
+ *
1242
+ * @static
1243
+ * @memberOf _
1244
+ * @since 3.0.0
1245
+ * @category String
1246
+ * @param {string} [string=''] The string to deburr.
1247
+ * @returns {string} Returns the deburred string.
1248
+ * @example
1249
+ *
1250
+ * _.deburr('déjà vu');
1251
+ * // => 'deja vu'
1252
+ */
1253
+ function deburr$1(string) {
1254
+ string = toString(string);
1255
+ return string && string.replace(reLatin, deburrLetter).replace(reComboMark, "");
1256
+ }
1257
+ module.exports = deburr$1;
1258
+ }));
1259
+
1260
+ //#endregion
1261
+ //#region ../../node_modules/.pnpm/didyoumean2@7.0.4/node_modules/didyoumean2/dist/index.mjs
1262
+ var import_fastest_levenshtein = require_fastest_levenshtein();
1263
+ var import_lodash = /* @__PURE__ */ __toESM(require_lodash(), 1);
1264
+ let ReturnTypeEnums = /* @__PURE__ */ function(ReturnTypeEnums$1) {
1265
+ ReturnTypeEnums$1["ALL_CLOSEST_MATCHES"] = "all-closest-matches";
1266
+ ReturnTypeEnums$1["ALL_MATCHES"] = "all-matches";
1267
+ ReturnTypeEnums$1["ALL_SORTED_MATCHES"] = "all-sorted-matches";
1268
+ ReturnTypeEnums$1["FIRST_CLOSEST_MATCH"] = "first-closest-match";
1269
+ ReturnTypeEnums$1["FIRST_MATCH"] = "first-match";
1270
+ return ReturnTypeEnums$1;
1271
+ }({});
1272
+ let ThresholdTypeEnums = /* @__PURE__ */ function(ThresholdTypeEnums$1) {
1273
+ ThresholdTypeEnums$1["EDIT_DISTANCE"] = "edit-distance";
1274
+ ThresholdTypeEnums$1["SIMILARITY"] = "similarity";
1275
+ return ThresholdTypeEnums$1;
1276
+ }({});
1277
+ const fillDefaultOptions = (options) => {
1278
+ const optionsWithDefaultValues = {
1279
+ caseSensitive: false,
1280
+ deburr: true,
1281
+ matchPath: [],
1282
+ returnType: ReturnTypeEnums.FIRST_CLOSEST_MATCH,
1283
+ thresholdType: ThresholdTypeEnums.SIMILARITY,
1284
+ trimSpaces: true,
1285
+ ...options
1286
+ };
1287
+ if (!Object.values(ReturnTypeEnums).includes(optionsWithDefaultValues.returnType)) throw new TypeError("unknown returnType");
1288
+ if (!Object.values(ThresholdTypeEnums).includes(optionsWithDefaultValues.thresholdType)) throw new TypeError("unknown thresholdType");
1289
+ switch (optionsWithDefaultValues.thresholdType) {
1290
+ case ThresholdTypeEnums.EDIT_DISTANCE: return {
1291
+ threshold: 20,
1292
+ ...optionsWithDefaultValues
1293
+ };
1294
+ case ThresholdTypeEnums.SIMILARITY: return {
1295
+ threshold: .4,
1296
+ ...optionsWithDefaultValues
1297
+ };
1298
+ }
1299
+ };
1300
+ /**
1301
+ * Using edit distance between `a` and `b` to calculate similarity
1302
+ *
1303
+ * @param {string} a - `input`
1304
+ * @param {string} b - String from `matchList`
1305
+ * @returns {number} similarity between `a` and `b`
1306
+ */
1307
+ const getSimilarity = (a, b) => {
1308
+ if (!a || !b) return 0;
1309
+ if (a === b) return 1;
1310
+ const editDistance = (0, import_fastest_levenshtein.distance)(a, b);
1311
+ const longestLength = Math.max(a.length, b.length);
1312
+ return (longestLength - editDistance) / longestLength;
1313
+ };
1314
+ /**
1315
+ * Normalize a string
1316
+ *
1317
+ * @param {string} str - any string
1318
+ * @param {object} options - options that allows you to modify the behavior
1319
+ * @returns {string} - normalized string
1320
+ */
1321
+ const normalizeString = (str, options) => {
1322
+ let s = str;
1323
+ if (options.trimSpaces) s = s.trim().replaceAll(/\s+/gu, " ");
1324
+ if (options.deburr) s = (0, import_lodash.default)(s);
1325
+ if (!options.caseSensitive) s = s.toLowerCase();
1326
+ return s;
1327
+ };
1328
+ const getMatchItemStr = (matchItem, matchPath) => {
1329
+ const matchItemStr = matchPath.length > 0 ? matchPath.reduce((acc, prop) => {
1330
+ return acc?.[prop];
1331
+ }, matchItem) : matchItem;
1332
+ if (typeof matchItemStr !== "string") return "";
1333
+ return matchItemStr;
1334
+ };
1335
+ /**
1336
+ * Process matchItem according to options
1337
+ *
1338
+ * @param {object | string} matchItem - Item for matching with `input`
1339
+ * @param {object} options - options that allows you to modify the behavior
1340
+ * @returns {string} - processed matchItem
1341
+ */
1342
+ const matchItemProcessor = (matchItem, options) => {
1343
+ const { matchPath } = options;
1344
+ return normalizeString(getMatchItemStr(matchItem, matchPath), options);
1345
+ };
1346
+ /**
1347
+ * Generate result
1348
+ *
1349
+ * @param {object[] | string[]} matchList - List for matching with `input`
1350
+ * @param {number[]} matchedIndexes - indexes of matchList that need to be returned as result
1351
+ * @param {ReturnTypeEnums} returnType - how the result will response to user
1352
+ * @returns {Array | null | object | string} - matched result(s), return object if `match` is `{Object[]}`
1353
+ */
1354
+ const resultProcessor = (matchList, matchedIndexes, returnType) => {
1355
+ switch (returnType) {
1356
+ case ReturnTypeEnums.ALL_CLOSEST_MATCHES:
1357
+ case ReturnTypeEnums.ALL_MATCHES:
1358
+ case ReturnTypeEnums.ALL_SORTED_MATCHES: return matchedIndexes.map((matchedIndex) => matchList[matchedIndex]);
1359
+ case ReturnTypeEnums.FIRST_CLOSEST_MATCH:
1360
+ case ReturnTypeEnums.FIRST_MATCH: {
1361
+ const matchedIndex = matchedIndexes[0];
1362
+ if (matchedIndex === void 0) return null;
1363
+ return matchList[matchedIndex];
1364
+ }
1365
+ }
1366
+ };
1367
+ /**
1368
+ * Main function for didyoumean2
1369
+ *
1370
+ * @param {string} input - string that you are not sure and want to match with `matchList`
1371
+ * @param {object[] | string[]} matchList - List for matching with `input`
1372
+ * @param {null | object | undefined} options - options that allows you to modify the behavior
1373
+ * @returns {Array | null | object | string} - matched result(s), return object if `match` is `{Object[]}`
1374
+ */
1375
+ function didYouMean(input, matchList, options) {
1376
+ const optionsWithDefaults = fillDefaultOptions(options);
1377
+ const { returnType, threshold, thresholdType } = optionsWithDefaults;
1378
+ const normalizedInput = normalizeString(input, optionsWithDefaults);
1379
+ let checkIfMatched;
1380
+ let scoreProcessor;
1381
+ switch (thresholdType) {
1382
+ case ThresholdTypeEnums.EDIT_DISTANCE:
1383
+ checkIfMatched = (score) => score <= threshold;
1384
+ scoreProcessor = (matchItem) => (0, import_fastest_levenshtein.distance)(normalizedInput, matchItemProcessor(matchItem, optionsWithDefaults));
1385
+ break;
1386
+ case ThresholdTypeEnums.SIMILARITY:
1387
+ checkIfMatched = (score) => score >= threshold;
1388
+ scoreProcessor = (matchItem) => getSimilarity(normalizedInput, matchItemProcessor(matchItem, optionsWithDefaults));
1389
+ break;
1390
+ }
1391
+ const matchedIndexes = [];
1392
+ switch (returnType) {
1393
+ case ReturnTypeEnums.ALL_CLOSEST_MATCHES:
1394
+ case ReturnTypeEnums.FIRST_CLOSEST_MATCH: {
1395
+ const scores = [];
1396
+ let marginValue;
1397
+ switch (thresholdType) {
1398
+ case ThresholdTypeEnums.EDIT_DISTANCE:
1399
+ marginValue = Number.POSITIVE_INFINITY;
1400
+ for (const matchItem of matchList) {
1401
+ const score = scoreProcessor(matchItem);
1402
+ if (marginValue > score) marginValue = score;
1403
+ scores.push(score);
1404
+ }
1405
+ break;
1406
+ case ThresholdTypeEnums.SIMILARITY:
1407
+ marginValue = 0;
1408
+ for (const matchItem of matchList) {
1409
+ const score = scoreProcessor(matchItem);
1410
+ if (marginValue < score) marginValue = score;
1411
+ scores.push(score);
1412
+ }
1413
+ break;
1414
+ }
1415
+ for (const [i, score] of scores.entries()) if (checkIfMatched(score) && score === marginValue) matchedIndexes.push(i);
1416
+ break;
1417
+ }
1418
+ case ReturnTypeEnums.ALL_MATCHES:
1419
+ for (const [i, matchItem] of matchList.entries()) {
1420
+ const score = scoreProcessor(matchItem);
1421
+ if (checkIfMatched(score)) matchedIndexes.push(i);
1422
+ }
1423
+ break;
1424
+ case ReturnTypeEnums.ALL_SORTED_MATCHES: {
1425
+ const unsortedResults = [];
1426
+ for (const [i, matchItem] of matchList.entries()) {
1427
+ const score = scoreProcessor(matchItem);
1428
+ if (checkIfMatched(score)) unsortedResults.push({
1429
+ score,
1430
+ index: i
60
1431
  });
61
1432
  }
1433
+ switch (thresholdType) {
1434
+ case ThresholdTypeEnums.EDIT_DISTANCE:
1435
+ unsortedResults.sort((a, b) => a.score - b.score);
1436
+ break;
1437
+ case ThresholdTypeEnums.SIMILARITY:
1438
+ unsortedResults.sort((a, b) => b.score - a.score);
1439
+ break;
1440
+ }
1441
+ for (const unsortedResult of unsortedResults) matchedIndexes.push(unsortedResult.index);
1442
+ break;
62
1443
  }
63
- return candidates$1;
64
- }
65
- const candidates = [];
66
- let prefix = "";
67
- if (commandName) {
68
- const matchedParts = commandName.split(" ");
69
- const remainingArgs = inputArgv.slice(matchedParts.length);
70
- prefix = `${[command.name, ...remainingArgs].join(" ")} `;
71
- } else prefix = inputArgv.length > 0 ? `${inputArgv.join(" ")} ` : "";
72
- for (const command$1 of cli._commands.values()) {
73
- if (command$1.completions?.show === false) continue;
74
- if (command$1.name.startsWith(prefix)) {
75
- const nextWord = command$1.name.slice(prefix.length).split(" ")[0];
76
- if (nextWord) candidates.push({
77
- name: nextWord,
78
- description: command$1.description
79
- });
1444
+ case ReturnTypeEnums.FIRST_MATCH:
1445
+ for (const [i, matchItem] of matchList.entries()) {
1446
+ const score = scoreProcessor(matchItem);
1447
+ if (checkIfMatched(score)) {
1448
+ matchedIndexes.push(i);
1449
+ break;
1450
+ }
1451
+ }
1452
+ break;
1453
+ }
1454
+ return resultProcessor(matchList, matchedIndexes, returnType);
1455
+ }
1456
+
1457
+ //#endregion
1458
+ //#region ../plugin-not-found/src/index.ts
1459
+ const notFoundPlugin = () => definePlugin({ setup: (cli) => cli.interceptor({
1460
+ enforce: "post",
1461
+ handler: async (_ctx, next) => {
1462
+ const commandKeys = [...cli._commands.keys()];
1463
+ const hasCommands = commandKeys.length > 0;
1464
+ try {
1465
+ await next();
1466
+ } catch (e) {
1467
+ if (!(e instanceof NoSuchCommandError || e instanceof NoCommandSpecifiedError)) throw e;
1468
+ if (e instanceof NoCommandSpecifiedError) {
1469
+ let text$1 = "No command specified.";
1470
+ if (hasCommands) text$1 += `\nPossible commands: ${commandKeys.join(", ")}.`;
1471
+ throw new NoCommandSpecifiedError(text$1);
1472
+ }
1473
+ const { commandName } = e;
1474
+ const closestCommandName = didYouMean(commandName, commandKeys);
1475
+ let text = `Command "${strikethrough(commandName)}" not found.`;
1476
+ if (hasCommands && closestCommandName) text += `\nDid you mean "${bold(closestCommandName)}"?`;
1477
+ else if (!hasCommands) text += "\nNo commands registered.";
1478
+ throw new NoSuchCommandError(commandName, text);
1479
+ }
1480
+ }
1481
+ }) });
1482
+
1483
+ //#endregion
1484
+ //#region ../plugin-strict-flags/src/index.ts
1485
+ const strictFlagsPlugin = () => definePlugin({ setup: (cli) => {
1486
+ cli.interceptor(async (ctx, next) => {
1487
+ const keys = Object.keys(ctx.rawParsed.unknown);
1488
+ if (!ctx.resolved || keys.length === 0) await next();
1489
+ else throw keys.length > 1 ? /* @__PURE__ */ new Error(`Unexpected flags: ${joinWithAnd(keys)}`) : /* @__PURE__ */ new Error(`Unexpected flag: ${keys[0]}`);
1490
+ });
1491
+ } });
1492
+
1493
+ //#endregion
1494
+ //#region ../clerc/src/re-exports.ts
1495
+ var re_exports_exports = /* @__PURE__ */ __export({
1496
+ completionsPlugin: () => completionsPlugin,
1497
+ defaultFormatters: () => defaultFormatters,
1498
+ friendlyErrorPlugin: () => friendlyErrorPlugin,
1499
+ helpPlugin: () => helpPlugin,
1500
+ notFoundPlugin: () => notFoundPlugin,
1501
+ strictFlagsPlugin: () => strictFlagsPlugin,
1502
+ versionPlugin: () => versionPlugin
1503
+ });
1504
+ import * as import___clerc_core from "@clerc/core";
1505
+ __reExport(re_exports_exports, import___clerc_core);
1506
+
1507
+ //#endregion
1508
+ //#region ../clerc/src/index.ts
1509
+ var src_exports = /* @__PURE__ */ __export({
1510
+ Cli: () => Cli,
1511
+ completionsPlugin: () => completionsPlugin,
1512
+ defaultFormatters: () => defaultFormatters,
1513
+ friendlyErrorPlugin: () => friendlyErrorPlugin,
1514
+ helpPlugin: () => helpPlugin,
1515
+ notFoundPlugin: () => notFoundPlugin,
1516
+ strictFlagsPlugin: () => strictFlagsPlugin,
1517
+ versionPlugin: () => versionPlugin
1518
+ });
1519
+ __reExport(src_exports, re_exports_exports);
1520
+ const Cli = (options) => Clerc.create(options).use(versionPlugin()).use(helpPlugin());
1521
+
1522
+ //#endregion
1523
+ //#region src/t.ts
1524
+ function resetTab() {
1525
+ t.commands.clear();
1526
+ t.options.clear();
1527
+ t.arguments.clear();
1528
+ t.completions = [];
1529
+ }
1530
+ function registerGlobalFlags(globalFlags, tc) {
1531
+ for (const [flagName, def] of Object.entries(globalFlags)) {
1532
+ const normalized = (0, src_exports.normalizeFlagValue)(def);
1533
+ const desc = normalized.description ?? "";
1534
+ tc.option(flagName, desc, normalized.short);
1535
+ }
1536
+ }
1537
+ function buildTabModel(globalFlags, commands) {
1538
+ resetTab();
1539
+ registerGlobalFlags(globalFlags, t);
1540
+ for (const cmd of commands.values()) {
1541
+ if (cmd.completions?.show === false) continue;
1542
+ const command = t.command(cmd.name, cmd.description ?? "");
1543
+ registerGlobalFlags(globalFlags, command);
1544
+ for (const [flagName, def] of Object.entries(cmd.flags ?? {})) {
1545
+ const normalized = (0, src_exports.normalizeFlagValue)(def);
1546
+ const desc = normalized.description ?? "";
1547
+ command.option(flagName, desc, normalized.short);
80
1548
  }
81
1549
  }
82
- const uniqueCandidates = /* @__PURE__ */ new Map();
83
- for (const c of candidates) uniqueCandidates.set(c.name, c);
84
- return [...uniqueCandidates.values()];
85
1550
  }
86
1551
 
87
1552
  //#endregion
88
1553
  //#region src/index.ts
89
- const completionsPlugin = (options = {}) => definePlugin({ setup: (cli) => {
90
- const { managementCommands = true } = options;
91
- cli.store.help?.addGroup({ commands: [["completions", "Completions"]] });
92
- const supportedShellEnum = Types.Enum(...tabtab.SUPPORTED_SHELLS);
93
- if (managementCommands) {
94
- cli.command("completions install", "Install shell completions", {
95
- help: { group: "completions" },
96
- flags: { shell: {
97
- description: "Shell type",
98
- type: supportedShellEnum
99
- } },
100
- parameters: [{
101
- key: "[shell]",
102
- description: "Shell type",
103
- type: supportedShellEnum
104
- }]
105
- }).on("completions install", async (ctx) => {
106
- const shell = ctx.parameters.shell ?? ctx.flags.shell;
107
- if (!shell) throw new Error("Please specify the shell type via the --shell flag or the [shell] parameter.");
108
- if (!tabtab.SUPPORTED_SHELLS.includes(shell)) throw new Error(`Unsupported shell: ${shell}. Supported shells are: ${tabtab.SUPPORTED_SHELLS.join(", ")}.`);
109
- await tabtab.install({
110
- name: cli._scriptName,
111
- completer: cli._scriptName,
112
- shell
113
- });
114
- });
115
- cli.command("completions uninstall", "Uninstall shell completions", { help: { group: "completions" } }).on("completions uninstall", async () => {
116
- await tabtab.uninstall({ name: cli._scriptName });
117
- });
118
- }
119
- cli.command("completions", "Generate completions script", {
120
- help: { group: "completions" },
1554
+ const completionsPlugin = () => definePlugin({ setup: (cli) => {
1555
+ const supportedShellEnum = Types.Enum("zsh", "bash", "fish", "powershell");
1556
+ cli.command("completions", "Generate shell completion scripts", {
121
1557
  flags: { shell: {
122
1558
  description: "Shell type",
123
1559
  type: supportedShellEnum
124
1560
  } },
125
1561
  parameters: [{
126
1562
  key: "[shell]",
127
- description: "Shell type",
1563
+ description: "Shell type (zsh, bash, fish, powershell)",
128
1564
  type: supportedShellEnum
129
1565
  }]
130
1566
  }).on("completions", async (ctx) => {
131
1567
  const shell = ctx.parameters.shell ?? ctx.flags.shell;
132
- if (!shell) throw new Error("Please specify the shell type via the --shell flag or the [shell] parameter.");
133
- if (!tabtab.SUPPORTED_SHELLS.includes(shell)) throw new Error(`Unsupported shell: ${shell}. Supported shells are: ${tabtab.SUPPORTED_SHELLS.join(", ")}.`);
134
- const script = await tabtab.getCompletionScript({
135
- name: cli._scriptName,
136
- completer: cli._scriptName,
137
- shell
138
- });
139
- console.log(script);
1568
+ if (!shell) throw new Error("Shell type is required. Please provide it via --shell flag or [shell] parameter.");
1569
+ buildTabModel(cli._globalFlags, cli._commands);
1570
+ t.setup(cli._scriptName, cli._scriptName, shell);
140
1571
  });
141
- cli.command("completion-server", "Handle completions", {
1572
+ cli.command("complete", {
142
1573
  help: { show: false },
143
- completions: { show: false }
144
- }).on("completion-server", async () => {
145
- const env = tabtab.parseEnv(process.env);
146
- if (!env.complete) return;
147
- const shell = getShellFromEnv(process.env);
148
- const candidates = await getCompletion(cli, env);
149
- tabtab.log(candidates, shell);
1574
+ completions: { show: false },
1575
+ parameters: ["--", "[input...]"]
1576
+ }).on("complete", async (ctx) => {
1577
+ buildTabModel(cli._globalFlags, cli._commands);
1578
+ const { input } = ctx.parameters;
1579
+ t.parse(input);
150
1580
  });
151
1581
  return cli;
152
1582
  } });