@drakulavich/oura-cli 0.1.0
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/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/README.md +86 -0
- package/dist/index.js +3764 -0
- package/docs/schemas/activity.json +15 -0
- package/docs/schemas/describe.json +59 -0
- package/docs/schemas/hr.json +14 -0
- package/docs/schemas/readiness.json +15 -0
- package/docs/schemas/sleep.json +15 -0
- package/docs/schemas/spo2.json +15 -0
- package/docs/schemas/stress.json +15 -0
- package/docs/schemas/workout.json +15 -0
- package/package.json +60 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3764 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
function __accessProp(key) {
|
|
9
|
+
return this[key];
|
|
10
|
+
}
|
|
11
|
+
var __toESMCache_node;
|
|
12
|
+
var __toESMCache_esm;
|
|
13
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
14
|
+
var canCache = mod != null && typeof mod === "object";
|
|
15
|
+
if (canCache) {
|
|
16
|
+
var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
|
|
17
|
+
var cached = cache.get(mod);
|
|
18
|
+
if (cached)
|
|
19
|
+
return cached;
|
|
20
|
+
}
|
|
21
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
22
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
23
|
+
for (let key of __getOwnPropNames(mod))
|
|
24
|
+
if (!__hasOwnProp.call(to, key))
|
|
25
|
+
__defProp(to, key, {
|
|
26
|
+
get: __accessProp.bind(mod, key),
|
|
27
|
+
enumerable: true
|
|
28
|
+
});
|
|
29
|
+
if (canCache)
|
|
30
|
+
cache.set(mod, to);
|
|
31
|
+
return to;
|
|
32
|
+
};
|
|
33
|
+
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
34
|
+
var __require = import.meta.require;
|
|
35
|
+
|
|
36
|
+
// node_modules/commander/lib/error.js
|
|
37
|
+
var require_error = __commonJS((exports) => {
|
|
38
|
+
class CommanderError extends Error {
|
|
39
|
+
constructor(exitCode, code, message) {
|
|
40
|
+
super(message);
|
|
41
|
+
Error.captureStackTrace(this, this.constructor);
|
|
42
|
+
this.name = this.constructor.name;
|
|
43
|
+
this.code = code;
|
|
44
|
+
this.exitCode = exitCode;
|
|
45
|
+
this.nestedError = undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
class InvalidArgumentError extends CommanderError {
|
|
50
|
+
constructor(message) {
|
|
51
|
+
super(1, "commander.invalidArgument", message);
|
|
52
|
+
Error.captureStackTrace(this, this.constructor);
|
|
53
|
+
this.name = this.constructor.name;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
exports.CommanderError = CommanderError;
|
|
57
|
+
exports.InvalidArgumentError = InvalidArgumentError;
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
// node_modules/commander/lib/argument.js
|
|
61
|
+
var require_argument = __commonJS((exports) => {
|
|
62
|
+
var { InvalidArgumentError } = require_error();
|
|
63
|
+
|
|
64
|
+
class Argument {
|
|
65
|
+
constructor(name, description) {
|
|
66
|
+
this.description = description || "";
|
|
67
|
+
this.variadic = false;
|
|
68
|
+
this.parseArg = undefined;
|
|
69
|
+
this.defaultValue = undefined;
|
|
70
|
+
this.defaultValueDescription = undefined;
|
|
71
|
+
this.argChoices = undefined;
|
|
72
|
+
switch (name[0]) {
|
|
73
|
+
case "<":
|
|
74
|
+
this.required = true;
|
|
75
|
+
this._name = name.slice(1, -1);
|
|
76
|
+
break;
|
|
77
|
+
case "[":
|
|
78
|
+
this.required = false;
|
|
79
|
+
this._name = name.slice(1, -1);
|
|
80
|
+
break;
|
|
81
|
+
default:
|
|
82
|
+
this.required = true;
|
|
83
|
+
this._name = name;
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
if (this._name.endsWith("...")) {
|
|
87
|
+
this.variadic = true;
|
|
88
|
+
this._name = this._name.slice(0, -3);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
name() {
|
|
92
|
+
return this._name;
|
|
93
|
+
}
|
|
94
|
+
_collectValue(value, previous) {
|
|
95
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
96
|
+
return [value];
|
|
97
|
+
}
|
|
98
|
+
previous.push(value);
|
|
99
|
+
return previous;
|
|
100
|
+
}
|
|
101
|
+
default(value, description) {
|
|
102
|
+
this.defaultValue = value;
|
|
103
|
+
this.defaultValueDescription = description;
|
|
104
|
+
return this;
|
|
105
|
+
}
|
|
106
|
+
argParser(fn) {
|
|
107
|
+
this.parseArg = fn;
|
|
108
|
+
return this;
|
|
109
|
+
}
|
|
110
|
+
choices(values) {
|
|
111
|
+
this.argChoices = values.slice();
|
|
112
|
+
this.parseArg = (arg, previous) => {
|
|
113
|
+
if (!this.argChoices.includes(arg)) {
|
|
114
|
+
throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
115
|
+
}
|
|
116
|
+
if (this.variadic) {
|
|
117
|
+
return this._collectValue(arg, previous);
|
|
118
|
+
}
|
|
119
|
+
return arg;
|
|
120
|
+
};
|
|
121
|
+
return this;
|
|
122
|
+
}
|
|
123
|
+
argRequired() {
|
|
124
|
+
this.required = true;
|
|
125
|
+
return this;
|
|
126
|
+
}
|
|
127
|
+
argOptional() {
|
|
128
|
+
this.required = false;
|
|
129
|
+
return this;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function humanReadableArgName(arg) {
|
|
133
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
134
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
135
|
+
}
|
|
136
|
+
exports.Argument = Argument;
|
|
137
|
+
exports.humanReadableArgName = humanReadableArgName;
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// node_modules/commander/lib/help.js
|
|
141
|
+
var require_help = __commonJS((exports) => {
|
|
142
|
+
var { humanReadableArgName } = require_argument();
|
|
143
|
+
|
|
144
|
+
class Help {
|
|
145
|
+
constructor() {
|
|
146
|
+
this.helpWidth = undefined;
|
|
147
|
+
this.minWidthToWrap = 40;
|
|
148
|
+
this.sortSubcommands = false;
|
|
149
|
+
this.sortOptions = false;
|
|
150
|
+
this.showGlobalOptions = false;
|
|
151
|
+
}
|
|
152
|
+
prepareContext(contextOptions) {
|
|
153
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
154
|
+
}
|
|
155
|
+
visibleCommands(cmd) {
|
|
156
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
157
|
+
const helpCommand = cmd._getHelpCommand();
|
|
158
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
159
|
+
visibleCommands.push(helpCommand);
|
|
160
|
+
}
|
|
161
|
+
if (this.sortSubcommands) {
|
|
162
|
+
visibleCommands.sort((a, b) => {
|
|
163
|
+
return a.name().localeCompare(b.name());
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
return visibleCommands;
|
|
167
|
+
}
|
|
168
|
+
compareOptions(a, b) {
|
|
169
|
+
const getSortKey = (option) => {
|
|
170
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
171
|
+
};
|
|
172
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
173
|
+
}
|
|
174
|
+
visibleOptions(cmd) {
|
|
175
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
176
|
+
const helpOption = cmd._getHelpOption();
|
|
177
|
+
if (helpOption && !helpOption.hidden) {
|
|
178
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
179
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
180
|
+
if (!removeShort && !removeLong) {
|
|
181
|
+
visibleOptions.push(helpOption);
|
|
182
|
+
} else if (helpOption.long && !removeLong) {
|
|
183
|
+
visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
|
|
184
|
+
} else if (helpOption.short && !removeShort) {
|
|
185
|
+
visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (this.sortOptions) {
|
|
189
|
+
visibleOptions.sort(this.compareOptions);
|
|
190
|
+
}
|
|
191
|
+
return visibleOptions;
|
|
192
|
+
}
|
|
193
|
+
visibleGlobalOptions(cmd) {
|
|
194
|
+
if (!this.showGlobalOptions)
|
|
195
|
+
return [];
|
|
196
|
+
const globalOptions = [];
|
|
197
|
+
for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
198
|
+
const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
|
|
199
|
+
globalOptions.push(...visibleOptions);
|
|
200
|
+
}
|
|
201
|
+
if (this.sortOptions) {
|
|
202
|
+
globalOptions.sort(this.compareOptions);
|
|
203
|
+
}
|
|
204
|
+
return globalOptions;
|
|
205
|
+
}
|
|
206
|
+
visibleArguments(cmd) {
|
|
207
|
+
if (cmd._argsDescription) {
|
|
208
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
209
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
213
|
+
return cmd.registeredArguments;
|
|
214
|
+
}
|
|
215
|
+
return [];
|
|
216
|
+
}
|
|
217
|
+
subcommandTerm(cmd) {
|
|
218
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
219
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
|
|
220
|
+
}
|
|
221
|
+
optionTerm(option) {
|
|
222
|
+
return option.flags;
|
|
223
|
+
}
|
|
224
|
+
argumentTerm(argument) {
|
|
225
|
+
return argument.name();
|
|
226
|
+
}
|
|
227
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
228
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
229
|
+
return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
|
|
230
|
+
}, 0);
|
|
231
|
+
}
|
|
232
|
+
longestOptionTermLength(cmd, helper) {
|
|
233
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
234
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
235
|
+
}, 0);
|
|
236
|
+
}
|
|
237
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
238
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
239
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
240
|
+
}, 0);
|
|
241
|
+
}
|
|
242
|
+
longestArgumentTermLength(cmd, helper) {
|
|
243
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
244
|
+
return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
|
|
245
|
+
}, 0);
|
|
246
|
+
}
|
|
247
|
+
commandUsage(cmd) {
|
|
248
|
+
let cmdName = cmd._name;
|
|
249
|
+
if (cmd._aliases[0]) {
|
|
250
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
251
|
+
}
|
|
252
|
+
let ancestorCmdNames = "";
|
|
253
|
+
for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
254
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
255
|
+
}
|
|
256
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
257
|
+
}
|
|
258
|
+
commandDescription(cmd) {
|
|
259
|
+
return cmd.description();
|
|
260
|
+
}
|
|
261
|
+
subcommandDescription(cmd) {
|
|
262
|
+
return cmd.summary() || cmd.description();
|
|
263
|
+
}
|
|
264
|
+
optionDescription(option) {
|
|
265
|
+
const extraInfo = [];
|
|
266
|
+
if (option.argChoices) {
|
|
267
|
+
extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
268
|
+
}
|
|
269
|
+
if (option.defaultValue !== undefined) {
|
|
270
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
271
|
+
if (showDefault) {
|
|
272
|
+
extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (option.presetArg !== undefined && option.optional) {
|
|
276
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
277
|
+
}
|
|
278
|
+
if (option.envVar !== undefined) {
|
|
279
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
280
|
+
}
|
|
281
|
+
if (extraInfo.length > 0) {
|
|
282
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
283
|
+
if (option.description) {
|
|
284
|
+
return `${option.description} ${extraDescription}`;
|
|
285
|
+
}
|
|
286
|
+
return extraDescription;
|
|
287
|
+
}
|
|
288
|
+
return option.description;
|
|
289
|
+
}
|
|
290
|
+
argumentDescription(argument) {
|
|
291
|
+
const extraInfo = [];
|
|
292
|
+
if (argument.argChoices) {
|
|
293
|
+
extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
294
|
+
}
|
|
295
|
+
if (argument.defaultValue !== undefined) {
|
|
296
|
+
extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
|
|
297
|
+
}
|
|
298
|
+
if (extraInfo.length > 0) {
|
|
299
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
300
|
+
if (argument.description) {
|
|
301
|
+
return `${argument.description} ${extraDescription}`;
|
|
302
|
+
}
|
|
303
|
+
return extraDescription;
|
|
304
|
+
}
|
|
305
|
+
return argument.description;
|
|
306
|
+
}
|
|
307
|
+
formatItemList(heading, items, helper) {
|
|
308
|
+
if (items.length === 0)
|
|
309
|
+
return [];
|
|
310
|
+
return [helper.styleTitle(heading), ...items, ""];
|
|
311
|
+
}
|
|
312
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
313
|
+
const result = new Map;
|
|
314
|
+
unsortedItems.forEach((item) => {
|
|
315
|
+
const group = getGroup(item);
|
|
316
|
+
if (!result.has(group))
|
|
317
|
+
result.set(group, []);
|
|
318
|
+
});
|
|
319
|
+
visibleItems.forEach((item) => {
|
|
320
|
+
const group = getGroup(item);
|
|
321
|
+
if (!result.has(group)) {
|
|
322
|
+
result.set(group, []);
|
|
323
|
+
}
|
|
324
|
+
result.get(group).push(item);
|
|
325
|
+
});
|
|
326
|
+
return result;
|
|
327
|
+
}
|
|
328
|
+
formatHelp(cmd, helper) {
|
|
329
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
330
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
331
|
+
function callFormatItem(term, description) {
|
|
332
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
333
|
+
}
|
|
334
|
+
let output = [
|
|
335
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
336
|
+
""
|
|
337
|
+
];
|
|
338
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
339
|
+
if (commandDescription.length > 0) {
|
|
340
|
+
output = output.concat([
|
|
341
|
+
helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
|
|
342
|
+
""
|
|
343
|
+
]);
|
|
344
|
+
}
|
|
345
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
346
|
+
return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
|
|
347
|
+
});
|
|
348
|
+
output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
|
|
349
|
+
const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
|
|
350
|
+
optionGroups.forEach((options, group) => {
|
|
351
|
+
const optionList = options.map((option) => {
|
|
352
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
353
|
+
});
|
|
354
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
355
|
+
});
|
|
356
|
+
if (helper.showGlobalOptions) {
|
|
357
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
358
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
359
|
+
});
|
|
360
|
+
output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
|
|
361
|
+
}
|
|
362
|
+
const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
|
|
363
|
+
commandGroups.forEach((commands, group) => {
|
|
364
|
+
const commandList = commands.map((sub) => {
|
|
365
|
+
return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
|
|
366
|
+
});
|
|
367
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
368
|
+
});
|
|
369
|
+
return output.join(`
|
|
370
|
+
`);
|
|
371
|
+
}
|
|
372
|
+
displayWidth(str) {
|
|
373
|
+
return stripColor(str).length;
|
|
374
|
+
}
|
|
375
|
+
styleTitle(str) {
|
|
376
|
+
return str;
|
|
377
|
+
}
|
|
378
|
+
styleUsage(str) {
|
|
379
|
+
return str.split(" ").map((word) => {
|
|
380
|
+
if (word === "[options]")
|
|
381
|
+
return this.styleOptionText(word);
|
|
382
|
+
if (word === "[command]")
|
|
383
|
+
return this.styleSubcommandText(word);
|
|
384
|
+
if (word[0] === "[" || word[0] === "<")
|
|
385
|
+
return this.styleArgumentText(word);
|
|
386
|
+
return this.styleCommandText(word);
|
|
387
|
+
}).join(" ");
|
|
388
|
+
}
|
|
389
|
+
styleCommandDescription(str) {
|
|
390
|
+
return this.styleDescriptionText(str);
|
|
391
|
+
}
|
|
392
|
+
styleOptionDescription(str) {
|
|
393
|
+
return this.styleDescriptionText(str);
|
|
394
|
+
}
|
|
395
|
+
styleSubcommandDescription(str) {
|
|
396
|
+
return this.styleDescriptionText(str);
|
|
397
|
+
}
|
|
398
|
+
styleArgumentDescription(str) {
|
|
399
|
+
return this.styleDescriptionText(str);
|
|
400
|
+
}
|
|
401
|
+
styleDescriptionText(str) {
|
|
402
|
+
return str;
|
|
403
|
+
}
|
|
404
|
+
styleOptionTerm(str) {
|
|
405
|
+
return this.styleOptionText(str);
|
|
406
|
+
}
|
|
407
|
+
styleSubcommandTerm(str) {
|
|
408
|
+
return str.split(" ").map((word) => {
|
|
409
|
+
if (word === "[options]")
|
|
410
|
+
return this.styleOptionText(word);
|
|
411
|
+
if (word[0] === "[" || word[0] === "<")
|
|
412
|
+
return this.styleArgumentText(word);
|
|
413
|
+
return this.styleSubcommandText(word);
|
|
414
|
+
}).join(" ");
|
|
415
|
+
}
|
|
416
|
+
styleArgumentTerm(str) {
|
|
417
|
+
return this.styleArgumentText(str);
|
|
418
|
+
}
|
|
419
|
+
styleOptionText(str) {
|
|
420
|
+
return str;
|
|
421
|
+
}
|
|
422
|
+
styleArgumentText(str) {
|
|
423
|
+
return str;
|
|
424
|
+
}
|
|
425
|
+
styleSubcommandText(str) {
|
|
426
|
+
return str;
|
|
427
|
+
}
|
|
428
|
+
styleCommandText(str) {
|
|
429
|
+
return str;
|
|
430
|
+
}
|
|
431
|
+
padWidth(cmd, helper) {
|
|
432
|
+
return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
|
|
433
|
+
}
|
|
434
|
+
preformatted(str) {
|
|
435
|
+
return /\n[^\S\r\n]/.test(str);
|
|
436
|
+
}
|
|
437
|
+
formatItem(term, termWidth, description, helper) {
|
|
438
|
+
const itemIndent = 2;
|
|
439
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
440
|
+
if (!description)
|
|
441
|
+
return itemIndentStr + term;
|
|
442
|
+
const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
|
|
443
|
+
const spacerWidth = 2;
|
|
444
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
445
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
446
|
+
let formattedDescription;
|
|
447
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
448
|
+
formattedDescription = description;
|
|
449
|
+
} else {
|
|
450
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
451
|
+
formattedDescription = wrappedDescription.replace(/\n/g, `
|
|
452
|
+
` + " ".repeat(termWidth + spacerWidth));
|
|
453
|
+
}
|
|
454
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
455
|
+
${itemIndentStr}`);
|
|
456
|
+
}
|
|
457
|
+
boxWrap(str, width) {
|
|
458
|
+
if (width < this.minWidthToWrap)
|
|
459
|
+
return str;
|
|
460
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
461
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
462
|
+
const wrappedLines = [];
|
|
463
|
+
rawLines.forEach((line) => {
|
|
464
|
+
const chunks = line.match(chunkPattern);
|
|
465
|
+
if (chunks === null) {
|
|
466
|
+
wrappedLines.push("");
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
let sumChunks = [chunks.shift()];
|
|
470
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
471
|
+
chunks.forEach((chunk) => {
|
|
472
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
473
|
+
if (sumWidth + visibleWidth <= width) {
|
|
474
|
+
sumChunks.push(chunk);
|
|
475
|
+
sumWidth += visibleWidth;
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
wrappedLines.push(sumChunks.join(""));
|
|
479
|
+
const nextChunk = chunk.trimStart();
|
|
480
|
+
sumChunks = [nextChunk];
|
|
481
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
482
|
+
});
|
|
483
|
+
wrappedLines.push(sumChunks.join(""));
|
|
484
|
+
});
|
|
485
|
+
return wrappedLines.join(`
|
|
486
|
+
`);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
function stripColor(str) {
|
|
490
|
+
const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
|
|
491
|
+
return str.replace(sgrPattern, "");
|
|
492
|
+
}
|
|
493
|
+
exports.Help = Help;
|
|
494
|
+
exports.stripColor = stripColor;
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
// node_modules/commander/lib/option.js
|
|
498
|
+
var require_option = __commonJS((exports) => {
|
|
499
|
+
var { InvalidArgumentError } = require_error();
|
|
500
|
+
|
|
501
|
+
class Option {
|
|
502
|
+
constructor(flags, description) {
|
|
503
|
+
this.flags = flags;
|
|
504
|
+
this.description = description || "";
|
|
505
|
+
this.required = flags.includes("<");
|
|
506
|
+
this.optional = flags.includes("[");
|
|
507
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
508
|
+
this.mandatory = false;
|
|
509
|
+
const optionFlags = splitOptionFlags(flags);
|
|
510
|
+
this.short = optionFlags.shortFlag;
|
|
511
|
+
this.long = optionFlags.longFlag;
|
|
512
|
+
this.negate = false;
|
|
513
|
+
if (this.long) {
|
|
514
|
+
this.negate = this.long.startsWith("--no-");
|
|
515
|
+
}
|
|
516
|
+
this.defaultValue = undefined;
|
|
517
|
+
this.defaultValueDescription = undefined;
|
|
518
|
+
this.presetArg = undefined;
|
|
519
|
+
this.envVar = undefined;
|
|
520
|
+
this.parseArg = undefined;
|
|
521
|
+
this.hidden = false;
|
|
522
|
+
this.argChoices = undefined;
|
|
523
|
+
this.conflictsWith = [];
|
|
524
|
+
this.implied = undefined;
|
|
525
|
+
this.helpGroupHeading = undefined;
|
|
526
|
+
}
|
|
527
|
+
default(value, description) {
|
|
528
|
+
this.defaultValue = value;
|
|
529
|
+
this.defaultValueDescription = description;
|
|
530
|
+
return this;
|
|
531
|
+
}
|
|
532
|
+
preset(arg) {
|
|
533
|
+
this.presetArg = arg;
|
|
534
|
+
return this;
|
|
535
|
+
}
|
|
536
|
+
conflicts(names) {
|
|
537
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
538
|
+
return this;
|
|
539
|
+
}
|
|
540
|
+
implies(impliedOptionValues) {
|
|
541
|
+
let newImplied = impliedOptionValues;
|
|
542
|
+
if (typeof impliedOptionValues === "string") {
|
|
543
|
+
newImplied = { [impliedOptionValues]: true };
|
|
544
|
+
}
|
|
545
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
546
|
+
return this;
|
|
547
|
+
}
|
|
548
|
+
env(name) {
|
|
549
|
+
this.envVar = name;
|
|
550
|
+
return this;
|
|
551
|
+
}
|
|
552
|
+
argParser(fn) {
|
|
553
|
+
this.parseArg = fn;
|
|
554
|
+
return this;
|
|
555
|
+
}
|
|
556
|
+
makeOptionMandatory(mandatory = true) {
|
|
557
|
+
this.mandatory = !!mandatory;
|
|
558
|
+
return this;
|
|
559
|
+
}
|
|
560
|
+
hideHelp(hide = true) {
|
|
561
|
+
this.hidden = !!hide;
|
|
562
|
+
return this;
|
|
563
|
+
}
|
|
564
|
+
_collectValue(value, previous) {
|
|
565
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
566
|
+
return [value];
|
|
567
|
+
}
|
|
568
|
+
previous.push(value);
|
|
569
|
+
return previous;
|
|
570
|
+
}
|
|
571
|
+
choices(values) {
|
|
572
|
+
this.argChoices = values.slice();
|
|
573
|
+
this.parseArg = (arg, previous) => {
|
|
574
|
+
if (!this.argChoices.includes(arg)) {
|
|
575
|
+
throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
576
|
+
}
|
|
577
|
+
if (this.variadic) {
|
|
578
|
+
return this._collectValue(arg, previous);
|
|
579
|
+
}
|
|
580
|
+
return arg;
|
|
581
|
+
};
|
|
582
|
+
return this;
|
|
583
|
+
}
|
|
584
|
+
name() {
|
|
585
|
+
if (this.long) {
|
|
586
|
+
return this.long.replace(/^--/, "");
|
|
587
|
+
}
|
|
588
|
+
return this.short.replace(/^-/, "");
|
|
589
|
+
}
|
|
590
|
+
attributeName() {
|
|
591
|
+
if (this.negate) {
|
|
592
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
593
|
+
}
|
|
594
|
+
return camelcase(this.name());
|
|
595
|
+
}
|
|
596
|
+
helpGroup(heading) {
|
|
597
|
+
this.helpGroupHeading = heading;
|
|
598
|
+
return this;
|
|
599
|
+
}
|
|
600
|
+
is(arg) {
|
|
601
|
+
return this.short === arg || this.long === arg;
|
|
602
|
+
}
|
|
603
|
+
isBoolean() {
|
|
604
|
+
return !this.required && !this.optional && !this.negate;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
class DualOptions {
|
|
609
|
+
constructor(options) {
|
|
610
|
+
this.positiveOptions = new Map;
|
|
611
|
+
this.negativeOptions = new Map;
|
|
612
|
+
this.dualOptions = new Set;
|
|
613
|
+
options.forEach((option) => {
|
|
614
|
+
if (option.negate) {
|
|
615
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
616
|
+
} else {
|
|
617
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
618
|
+
}
|
|
619
|
+
});
|
|
620
|
+
this.negativeOptions.forEach((value, key) => {
|
|
621
|
+
if (this.positiveOptions.has(key)) {
|
|
622
|
+
this.dualOptions.add(key);
|
|
623
|
+
}
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
valueFromOption(value, option) {
|
|
627
|
+
const optionKey = option.attributeName();
|
|
628
|
+
if (!this.dualOptions.has(optionKey))
|
|
629
|
+
return true;
|
|
630
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
631
|
+
const negativeValue = preset !== undefined ? preset : false;
|
|
632
|
+
return option.negate === (negativeValue === value);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
function camelcase(str) {
|
|
636
|
+
return str.split("-").reduce((str2, word) => {
|
|
637
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
function splitOptionFlags(flags) {
|
|
641
|
+
let shortFlag;
|
|
642
|
+
let longFlag;
|
|
643
|
+
const shortFlagExp = /^-[^-]$/;
|
|
644
|
+
const longFlagExp = /^--[^-]/;
|
|
645
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
646
|
+
if (shortFlagExp.test(flagParts[0]))
|
|
647
|
+
shortFlag = flagParts.shift();
|
|
648
|
+
if (longFlagExp.test(flagParts[0]))
|
|
649
|
+
longFlag = flagParts.shift();
|
|
650
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
651
|
+
shortFlag = flagParts.shift();
|
|
652
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
653
|
+
shortFlag = longFlag;
|
|
654
|
+
longFlag = flagParts.shift();
|
|
655
|
+
}
|
|
656
|
+
if (flagParts[0].startsWith("-")) {
|
|
657
|
+
const unsupportedFlag = flagParts[0];
|
|
658
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
659
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
660
|
+
throw new Error(`${baseError}
|
|
661
|
+
- a short flag is a single dash and a single character
|
|
662
|
+
- either use a single dash and a single character (for a short flag)
|
|
663
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
|
|
664
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
665
|
+
throw new Error(`${baseError}
|
|
666
|
+
- too many short flags`);
|
|
667
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
668
|
+
throw new Error(`${baseError}
|
|
669
|
+
- too many long flags`);
|
|
670
|
+
throw new Error(`${baseError}
|
|
671
|
+
- unrecognised flag format`);
|
|
672
|
+
}
|
|
673
|
+
if (shortFlag === undefined && longFlag === undefined)
|
|
674
|
+
throw new Error(`option creation failed due to no flags found in '${flags}'.`);
|
|
675
|
+
return { shortFlag, longFlag };
|
|
676
|
+
}
|
|
677
|
+
exports.Option = Option;
|
|
678
|
+
exports.DualOptions = DualOptions;
|
|
679
|
+
});
|
|
680
|
+
|
|
681
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
682
|
+
var require_suggestSimilar = __commonJS((exports) => {
|
|
683
|
+
var maxDistance = 3;
|
|
684
|
+
function editDistance(a, b) {
|
|
685
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
686
|
+
return Math.max(a.length, b.length);
|
|
687
|
+
const d = [];
|
|
688
|
+
for (let i = 0;i <= a.length; i++) {
|
|
689
|
+
d[i] = [i];
|
|
690
|
+
}
|
|
691
|
+
for (let j = 0;j <= b.length; j++) {
|
|
692
|
+
d[0][j] = j;
|
|
693
|
+
}
|
|
694
|
+
for (let j = 1;j <= b.length; j++) {
|
|
695
|
+
for (let i = 1;i <= a.length; i++) {
|
|
696
|
+
let cost = 1;
|
|
697
|
+
if (a[i - 1] === b[j - 1]) {
|
|
698
|
+
cost = 0;
|
|
699
|
+
} else {
|
|
700
|
+
cost = 1;
|
|
701
|
+
}
|
|
702
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
703
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
704
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
return d[a.length][b.length];
|
|
709
|
+
}
|
|
710
|
+
function suggestSimilar(word, candidates) {
|
|
711
|
+
if (!candidates || candidates.length === 0)
|
|
712
|
+
return "";
|
|
713
|
+
candidates = Array.from(new Set(candidates));
|
|
714
|
+
const searchingOptions = word.startsWith("--");
|
|
715
|
+
if (searchingOptions) {
|
|
716
|
+
word = word.slice(2);
|
|
717
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
718
|
+
}
|
|
719
|
+
let similar = [];
|
|
720
|
+
let bestDistance = maxDistance;
|
|
721
|
+
const minSimilarity = 0.4;
|
|
722
|
+
candidates.forEach((candidate) => {
|
|
723
|
+
if (candidate.length <= 1)
|
|
724
|
+
return;
|
|
725
|
+
const distance = editDistance(word, candidate);
|
|
726
|
+
const length = Math.max(word.length, candidate.length);
|
|
727
|
+
const similarity = (length - distance) / length;
|
|
728
|
+
if (similarity > minSimilarity) {
|
|
729
|
+
if (distance < bestDistance) {
|
|
730
|
+
bestDistance = distance;
|
|
731
|
+
similar = [candidate];
|
|
732
|
+
} else if (distance === bestDistance) {
|
|
733
|
+
similar.push(candidate);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
});
|
|
737
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
738
|
+
if (searchingOptions) {
|
|
739
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
740
|
+
}
|
|
741
|
+
if (similar.length > 1) {
|
|
742
|
+
return `
|
|
743
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
744
|
+
}
|
|
745
|
+
if (similar.length === 1) {
|
|
746
|
+
return `
|
|
747
|
+
(Did you mean ${similar[0]}?)`;
|
|
748
|
+
}
|
|
749
|
+
return "";
|
|
750
|
+
}
|
|
751
|
+
exports.suggestSimilar = suggestSimilar;
|
|
752
|
+
});
|
|
753
|
+
|
|
754
|
+
// node_modules/commander/lib/command.js
|
|
755
|
+
var require_command = __commonJS((exports) => {
|
|
756
|
+
var EventEmitter = __require("events").EventEmitter;
|
|
757
|
+
var childProcess = __require("child_process");
|
|
758
|
+
var path = __require("path");
|
|
759
|
+
var fs = __require("fs");
|
|
760
|
+
var process2 = __require("process");
|
|
761
|
+
var { Argument, humanReadableArgName } = require_argument();
|
|
762
|
+
var { CommanderError } = require_error();
|
|
763
|
+
var { Help, stripColor } = require_help();
|
|
764
|
+
var { Option, DualOptions } = require_option();
|
|
765
|
+
var { suggestSimilar } = require_suggestSimilar();
|
|
766
|
+
|
|
767
|
+
class Command extends EventEmitter {
|
|
768
|
+
constructor(name) {
|
|
769
|
+
super();
|
|
770
|
+
this.commands = [];
|
|
771
|
+
this.options = [];
|
|
772
|
+
this.parent = null;
|
|
773
|
+
this._allowUnknownOption = false;
|
|
774
|
+
this._allowExcessArguments = false;
|
|
775
|
+
this.registeredArguments = [];
|
|
776
|
+
this._args = this.registeredArguments;
|
|
777
|
+
this.args = [];
|
|
778
|
+
this.rawArgs = [];
|
|
779
|
+
this.processedArgs = [];
|
|
780
|
+
this._scriptPath = null;
|
|
781
|
+
this._name = name || "";
|
|
782
|
+
this._optionValues = {};
|
|
783
|
+
this._optionValueSources = {};
|
|
784
|
+
this._storeOptionsAsProperties = false;
|
|
785
|
+
this._actionHandler = null;
|
|
786
|
+
this._executableHandler = false;
|
|
787
|
+
this._executableFile = null;
|
|
788
|
+
this._executableDir = null;
|
|
789
|
+
this._defaultCommandName = null;
|
|
790
|
+
this._exitCallback = null;
|
|
791
|
+
this._aliases = [];
|
|
792
|
+
this._combineFlagAndOptionalValue = true;
|
|
793
|
+
this._description = "";
|
|
794
|
+
this._summary = "";
|
|
795
|
+
this._argsDescription = undefined;
|
|
796
|
+
this._enablePositionalOptions = false;
|
|
797
|
+
this._passThroughOptions = false;
|
|
798
|
+
this._lifeCycleHooks = {};
|
|
799
|
+
this._showHelpAfterError = false;
|
|
800
|
+
this._showSuggestionAfterError = true;
|
|
801
|
+
this._savedState = null;
|
|
802
|
+
this._outputConfiguration = {
|
|
803
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
804
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
805
|
+
outputError: (str, write) => write(str),
|
|
806
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
|
|
807
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
|
|
808
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
809
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
810
|
+
stripColor: (str) => stripColor(str)
|
|
811
|
+
};
|
|
812
|
+
this._hidden = false;
|
|
813
|
+
this._helpOption = undefined;
|
|
814
|
+
this._addImplicitHelpCommand = undefined;
|
|
815
|
+
this._helpCommand = undefined;
|
|
816
|
+
this._helpConfiguration = {};
|
|
817
|
+
this._helpGroupHeading = undefined;
|
|
818
|
+
this._defaultCommandGroup = undefined;
|
|
819
|
+
this._defaultOptionGroup = undefined;
|
|
820
|
+
}
|
|
821
|
+
copyInheritedSettings(sourceCommand) {
|
|
822
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
823
|
+
this._helpOption = sourceCommand._helpOption;
|
|
824
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
825
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
826
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
827
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
828
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
829
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
830
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
831
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
832
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
833
|
+
return this;
|
|
834
|
+
}
|
|
835
|
+
_getCommandAndAncestors() {
|
|
836
|
+
const result = [];
|
|
837
|
+
for (let command = this;command; command = command.parent) {
|
|
838
|
+
result.push(command);
|
|
839
|
+
}
|
|
840
|
+
return result;
|
|
841
|
+
}
|
|
842
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
843
|
+
let desc = actionOptsOrExecDesc;
|
|
844
|
+
let opts = execOpts;
|
|
845
|
+
if (typeof desc === "object" && desc !== null) {
|
|
846
|
+
opts = desc;
|
|
847
|
+
desc = null;
|
|
848
|
+
}
|
|
849
|
+
opts = opts || {};
|
|
850
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
851
|
+
const cmd = this.createCommand(name);
|
|
852
|
+
if (desc) {
|
|
853
|
+
cmd.description(desc);
|
|
854
|
+
cmd._executableHandler = true;
|
|
855
|
+
}
|
|
856
|
+
if (opts.isDefault)
|
|
857
|
+
this._defaultCommandName = cmd._name;
|
|
858
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
859
|
+
cmd._executableFile = opts.executableFile || null;
|
|
860
|
+
if (args)
|
|
861
|
+
cmd.arguments(args);
|
|
862
|
+
this._registerCommand(cmd);
|
|
863
|
+
cmd.parent = this;
|
|
864
|
+
cmd.copyInheritedSettings(this);
|
|
865
|
+
if (desc)
|
|
866
|
+
return this;
|
|
867
|
+
return cmd;
|
|
868
|
+
}
|
|
869
|
+
createCommand(name) {
|
|
870
|
+
return new Command(name);
|
|
871
|
+
}
|
|
872
|
+
createHelp() {
|
|
873
|
+
return Object.assign(new Help, this.configureHelp());
|
|
874
|
+
}
|
|
875
|
+
configureHelp(configuration) {
|
|
876
|
+
if (configuration === undefined)
|
|
877
|
+
return this._helpConfiguration;
|
|
878
|
+
this._helpConfiguration = configuration;
|
|
879
|
+
return this;
|
|
880
|
+
}
|
|
881
|
+
configureOutput(configuration) {
|
|
882
|
+
if (configuration === undefined)
|
|
883
|
+
return this._outputConfiguration;
|
|
884
|
+
this._outputConfiguration = {
|
|
885
|
+
...this._outputConfiguration,
|
|
886
|
+
...configuration
|
|
887
|
+
};
|
|
888
|
+
return this;
|
|
889
|
+
}
|
|
890
|
+
showHelpAfterError(displayHelp = true) {
|
|
891
|
+
if (typeof displayHelp !== "string")
|
|
892
|
+
displayHelp = !!displayHelp;
|
|
893
|
+
this._showHelpAfterError = displayHelp;
|
|
894
|
+
return this;
|
|
895
|
+
}
|
|
896
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
897
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
898
|
+
return this;
|
|
899
|
+
}
|
|
900
|
+
addCommand(cmd, opts) {
|
|
901
|
+
if (!cmd._name) {
|
|
902
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
903
|
+
- specify the name in Command constructor or using .name()`);
|
|
904
|
+
}
|
|
905
|
+
opts = opts || {};
|
|
906
|
+
if (opts.isDefault)
|
|
907
|
+
this._defaultCommandName = cmd._name;
|
|
908
|
+
if (opts.noHelp || opts.hidden)
|
|
909
|
+
cmd._hidden = true;
|
|
910
|
+
this._registerCommand(cmd);
|
|
911
|
+
cmd.parent = this;
|
|
912
|
+
cmd._checkForBrokenPassThrough();
|
|
913
|
+
return this;
|
|
914
|
+
}
|
|
915
|
+
createArgument(name, description) {
|
|
916
|
+
return new Argument(name, description);
|
|
917
|
+
}
|
|
918
|
+
argument(name, description, parseArg, defaultValue) {
|
|
919
|
+
const argument = this.createArgument(name, description);
|
|
920
|
+
if (typeof parseArg === "function") {
|
|
921
|
+
argument.default(defaultValue).argParser(parseArg);
|
|
922
|
+
} else {
|
|
923
|
+
argument.default(parseArg);
|
|
924
|
+
}
|
|
925
|
+
this.addArgument(argument);
|
|
926
|
+
return this;
|
|
927
|
+
}
|
|
928
|
+
arguments(names) {
|
|
929
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
930
|
+
this.argument(detail);
|
|
931
|
+
});
|
|
932
|
+
return this;
|
|
933
|
+
}
|
|
934
|
+
addArgument(argument) {
|
|
935
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
936
|
+
if (previousArgument?.variadic) {
|
|
937
|
+
throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
|
|
938
|
+
}
|
|
939
|
+
if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
|
|
940
|
+
throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
|
|
941
|
+
}
|
|
942
|
+
this.registeredArguments.push(argument);
|
|
943
|
+
return this;
|
|
944
|
+
}
|
|
945
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
946
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
947
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
948
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) {
|
|
949
|
+
this._initCommandGroup(this._getHelpCommand());
|
|
950
|
+
}
|
|
951
|
+
return this;
|
|
952
|
+
}
|
|
953
|
+
const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
954
|
+
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
955
|
+
const helpDescription = description ?? "display help for command";
|
|
956
|
+
const helpCommand = this.createCommand(helpName);
|
|
957
|
+
helpCommand.helpOption(false);
|
|
958
|
+
if (helpArgs)
|
|
959
|
+
helpCommand.arguments(helpArgs);
|
|
960
|
+
if (helpDescription)
|
|
961
|
+
helpCommand.description(helpDescription);
|
|
962
|
+
this._addImplicitHelpCommand = true;
|
|
963
|
+
this._helpCommand = helpCommand;
|
|
964
|
+
if (enableOrNameAndArgs || description)
|
|
965
|
+
this._initCommandGroup(helpCommand);
|
|
966
|
+
return this;
|
|
967
|
+
}
|
|
968
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
969
|
+
if (typeof helpCommand !== "object") {
|
|
970
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
971
|
+
return this;
|
|
972
|
+
}
|
|
973
|
+
this._addImplicitHelpCommand = true;
|
|
974
|
+
this._helpCommand = helpCommand;
|
|
975
|
+
this._initCommandGroup(helpCommand);
|
|
976
|
+
return this;
|
|
977
|
+
}
|
|
978
|
+
_getHelpCommand() {
|
|
979
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
980
|
+
if (hasImplicitHelpCommand) {
|
|
981
|
+
if (this._helpCommand === undefined) {
|
|
982
|
+
this.helpCommand(undefined, undefined);
|
|
983
|
+
}
|
|
984
|
+
return this._helpCommand;
|
|
985
|
+
}
|
|
986
|
+
return null;
|
|
987
|
+
}
|
|
988
|
+
hook(event, listener) {
|
|
989
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
990
|
+
if (!allowedValues.includes(event)) {
|
|
991
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
992
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
993
|
+
}
|
|
994
|
+
if (this._lifeCycleHooks[event]) {
|
|
995
|
+
this._lifeCycleHooks[event].push(listener);
|
|
996
|
+
} else {
|
|
997
|
+
this._lifeCycleHooks[event] = [listener];
|
|
998
|
+
}
|
|
999
|
+
return this;
|
|
1000
|
+
}
|
|
1001
|
+
exitOverride(fn) {
|
|
1002
|
+
if (fn) {
|
|
1003
|
+
this._exitCallback = fn;
|
|
1004
|
+
} else {
|
|
1005
|
+
this._exitCallback = (err) => {
|
|
1006
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1007
|
+
throw err;
|
|
1008
|
+
} else {}
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
return this;
|
|
1012
|
+
}
|
|
1013
|
+
_exit(exitCode, code, message) {
|
|
1014
|
+
if (this._exitCallback) {
|
|
1015
|
+
this._exitCallback(new CommanderError(exitCode, code, message));
|
|
1016
|
+
}
|
|
1017
|
+
process2.exit(exitCode);
|
|
1018
|
+
}
|
|
1019
|
+
action(fn) {
|
|
1020
|
+
const listener = (args) => {
|
|
1021
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1022
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1023
|
+
if (this._storeOptionsAsProperties) {
|
|
1024
|
+
actionArgs[expectedArgsCount] = this;
|
|
1025
|
+
} else {
|
|
1026
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1027
|
+
}
|
|
1028
|
+
actionArgs.push(this);
|
|
1029
|
+
return fn.apply(this, actionArgs);
|
|
1030
|
+
};
|
|
1031
|
+
this._actionHandler = listener;
|
|
1032
|
+
return this;
|
|
1033
|
+
}
|
|
1034
|
+
createOption(flags, description) {
|
|
1035
|
+
return new Option(flags, description);
|
|
1036
|
+
}
|
|
1037
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1038
|
+
try {
|
|
1039
|
+
return target.parseArg(value, previous);
|
|
1040
|
+
} catch (err) {
|
|
1041
|
+
if (err.code === "commander.invalidArgument") {
|
|
1042
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1043
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1044
|
+
}
|
|
1045
|
+
throw err;
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
_registerOption(option) {
|
|
1049
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1050
|
+
if (matchingOption) {
|
|
1051
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1052
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1053
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1054
|
+
}
|
|
1055
|
+
this._initOptionGroup(option);
|
|
1056
|
+
this.options.push(option);
|
|
1057
|
+
}
|
|
1058
|
+
_registerCommand(command) {
|
|
1059
|
+
const knownBy = (cmd) => {
|
|
1060
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1061
|
+
};
|
|
1062
|
+
const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
|
|
1063
|
+
if (alreadyUsed) {
|
|
1064
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1065
|
+
const newCmd = knownBy(command).join("|");
|
|
1066
|
+
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
|
|
1067
|
+
}
|
|
1068
|
+
this._initCommandGroup(command);
|
|
1069
|
+
this.commands.push(command);
|
|
1070
|
+
}
|
|
1071
|
+
addOption(option) {
|
|
1072
|
+
this._registerOption(option);
|
|
1073
|
+
const oname = option.name();
|
|
1074
|
+
const name = option.attributeName();
|
|
1075
|
+
if (option.negate) {
|
|
1076
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1077
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
1078
|
+
this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
|
|
1079
|
+
}
|
|
1080
|
+
} else if (option.defaultValue !== undefined) {
|
|
1081
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1082
|
+
}
|
|
1083
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1084
|
+
if (val == null && option.presetArg !== undefined) {
|
|
1085
|
+
val = option.presetArg;
|
|
1086
|
+
}
|
|
1087
|
+
const oldValue = this.getOptionValue(name);
|
|
1088
|
+
if (val !== null && option.parseArg) {
|
|
1089
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1090
|
+
} else if (val !== null && option.variadic) {
|
|
1091
|
+
val = option._collectValue(val, oldValue);
|
|
1092
|
+
}
|
|
1093
|
+
if (val == null) {
|
|
1094
|
+
if (option.negate) {
|
|
1095
|
+
val = false;
|
|
1096
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1097
|
+
val = true;
|
|
1098
|
+
} else {
|
|
1099
|
+
val = "";
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1103
|
+
};
|
|
1104
|
+
this.on("option:" + oname, (val) => {
|
|
1105
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1106
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1107
|
+
});
|
|
1108
|
+
if (option.envVar) {
|
|
1109
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1110
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1111
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1112
|
+
});
|
|
1113
|
+
}
|
|
1114
|
+
return this;
|
|
1115
|
+
}
|
|
1116
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1117
|
+
if (typeof flags === "object" && flags instanceof Option) {
|
|
1118
|
+
throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
|
|
1119
|
+
}
|
|
1120
|
+
const option = this.createOption(flags, description);
|
|
1121
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1122
|
+
if (typeof fn === "function") {
|
|
1123
|
+
option.default(defaultValue).argParser(fn);
|
|
1124
|
+
} else if (fn instanceof RegExp) {
|
|
1125
|
+
const regex = fn;
|
|
1126
|
+
fn = (val, def) => {
|
|
1127
|
+
const m = regex.exec(val);
|
|
1128
|
+
return m ? m[0] : def;
|
|
1129
|
+
};
|
|
1130
|
+
option.default(defaultValue).argParser(fn);
|
|
1131
|
+
} else {
|
|
1132
|
+
option.default(fn);
|
|
1133
|
+
}
|
|
1134
|
+
return this.addOption(option);
|
|
1135
|
+
}
|
|
1136
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1137
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1138
|
+
}
|
|
1139
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1140
|
+
return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
|
|
1141
|
+
}
|
|
1142
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1143
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1144
|
+
return this;
|
|
1145
|
+
}
|
|
1146
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1147
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1148
|
+
return this;
|
|
1149
|
+
}
|
|
1150
|
+
allowExcessArguments(allowExcess = true) {
|
|
1151
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1152
|
+
return this;
|
|
1153
|
+
}
|
|
1154
|
+
enablePositionalOptions(positional = true) {
|
|
1155
|
+
this._enablePositionalOptions = !!positional;
|
|
1156
|
+
return this;
|
|
1157
|
+
}
|
|
1158
|
+
passThroughOptions(passThrough = true) {
|
|
1159
|
+
this._passThroughOptions = !!passThrough;
|
|
1160
|
+
this._checkForBrokenPassThrough();
|
|
1161
|
+
return this;
|
|
1162
|
+
}
|
|
1163
|
+
_checkForBrokenPassThrough() {
|
|
1164
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1165
|
+
throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1169
|
+
if (this.options.length) {
|
|
1170
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1171
|
+
}
|
|
1172
|
+
if (Object.keys(this._optionValues).length) {
|
|
1173
|
+
throw new Error("call .storeOptionsAsProperties() before setting option values");
|
|
1174
|
+
}
|
|
1175
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1176
|
+
return this;
|
|
1177
|
+
}
|
|
1178
|
+
getOptionValue(key) {
|
|
1179
|
+
if (this._storeOptionsAsProperties) {
|
|
1180
|
+
return this[key];
|
|
1181
|
+
}
|
|
1182
|
+
return this._optionValues[key];
|
|
1183
|
+
}
|
|
1184
|
+
setOptionValue(key, value) {
|
|
1185
|
+
return this.setOptionValueWithSource(key, value, undefined);
|
|
1186
|
+
}
|
|
1187
|
+
setOptionValueWithSource(key, value, source) {
|
|
1188
|
+
if (this._storeOptionsAsProperties) {
|
|
1189
|
+
this[key] = value;
|
|
1190
|
+
} else {
|
|
1191
|
+
this._optionValues[key] = value;
|
|
1192
|
+
}
|
|
1193
|
+
this._optionValueSources[key] = source;
|
|
1194
|
+
return this;
|
|
1195
|
+
}
|
|
1196
|
+
getOptionValueSource(key) {
|
|
1197
|
+
return this._optionValueSources[key];
|
|
1198
|
+
}
|
|
1199
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1200
|
+
let source;
|
|
1201
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1202
|
+
if (cmd.getOptionValueSource(key) !== undefined) {
|
|
1203
|
+
source = cmd.getOptionValueSource(key);
|
|
1204
|
+
}
|
|
1205
|
+
});
|
|
1206
|
+
return source;
|
|
1207
|
+
}
|
|
1208
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1209
|
+
if (argv !== undefined && !Array.isArray(argv)) {
|
|
1210
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1211
|
+
}
|
|
1212
|
+
parseOptions = parseOptions || {};
|
|
1213
|
+
if (argv === undefined && parseOptions.from === undefined) {
|
|
1214
|
+
if (process2.versions?.electron) {
|
|
1215
|
+
parseOptions.from = "electron";
|
|
1216
|
+
}
|
|
1217
|
+
const execArgv = process2.execArgv ?? [];
|
|
1218
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
1219
|
+
parseOptions.from = "eval";
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
if (argv === undefined) {
|
|
1223
|
+
argv = process2.argv;
|
|
1224
|
+
}
|
|
1225
|
+
this.rawArgs = argv.slice();
|
|
1226
|
+
let userArgs;
|
|
1227
|
+
switch (parseOptions.from) {
|
|
1228
|
+
case undefined:
|
|
1229
|
+
case "node":
|
|
1230
|
+
this._scriptPath = argv[1];
|
|
1231
|
+
userArgs = argv.slice(2);
|
|
1232
|
+
break;
|
|
1233
|
+
case "electron":
|
|
1234
|
+
if (process2.defaultApp) {
|
|
1235
|
+
this._scriptPath = argv[1];
|
|
1236
|
+
userArgs = argv.slice(2);
|
|
1237
|
+
} else {
|
|
1238
|
+
userArgs = argv.slice(1);
|
|
1239
|
+
}
|
|
1240
|
+
break;
|
|
1241
|
+
case "user":
|
|
1242
|
+
userArgs = argv.slice(0);
|
|
1243
|
+
break;
|
|
1244
|
+
case "eval":
|
|
1245
|
+
userArgs = argv.slice(1);
|
|
1246
|
+
break;
|
|
1247
|
+
default:
|
|
1248
|
+
throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1249
|
+
}
|
|
1250
|
+
if (!this._name && this._scriptPath)
|
|
1251
|
+
this.nameFromFilename(this._scriptPath);
|
|
1252
|
+
this._name = this._name || "program";
|
|
1253
|
+
return userArgs;
|
|
1254
|
+
}
|
|
1255
|
+
parse(argv, parseOptions) {
|
|
1256
|
+
this._prepareForParse();
|
|
1257
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1258
|
+
this._parseCommand([], userArgs);
|
|
1259
|
+
return this;
|
|
1260
|
+
}
|
|
1261
|
+
async parseAsync(argv, parseOptions) {
|
|
1262
|
+
this._prepareForParse();
|
|
1263
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1264
|
+
await this._parseCommand([], userArgs);
|
|
1265
|
+
return this;
|
|
1266
|
+
}
|
|
1267
|
+
_prepareForParse() {
|
|
1268
|
+
if (this._savedState === null) {
|
|
1269
|
+
this.saveStateBeforeParse();
|
|
1270
|
+
} else {
|
|
1271
|
+
this.restoreStateBeforeParse();
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
saveStateBeforeParse() {
|
|
1275
|
+
this._savedState = {
|
|
1276
|
+
_name: this._name,
|
|
1277
|
+
_optionValues: { ...this._optionValues },
|
|
1278
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
restoreStateBeforeParse() {
|
|
1282
|
+
if (this._storeOptionsAsProperties)
|
|
1283
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
1284
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
1285
|
+
this._name = this._savedState._name;
|
|
1286
|
+
this._scriptPath = null;
|
|
1287
|
+
this.rawArgs = [];
|
|
1288
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
1289
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
1290
|
+
this.args = [];
|
|
1291
|
+
this.processedArgs = [];
|
|
1292
|
+
}
|
|
1293
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
1294
|
+
if (fs.existsSync(executableFile))
|
|
1295
|
+
return;
|
|
1296
|
+
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
|
|
1297
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1298
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1299
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1300
|
+
- ${executableDirMessage}`;
|
|
1301
|
+
throw new Error(executableMissing);
|
|
1302
|
+
}
|
|
1303
|
+
_executeSubCommand(subcommand, args) {
|
|
1304
|
+
args = args.slice();
|
|
1305
|
+
let launchWithNode = false;
|
|
1306
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
1307
|
+
function findFile(baseDir, baseName) {
|
|
1308
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
1309
|
+
if (fs.existsSync(localBin))
|
|
1310
|
+
return localBin;
|
|
1311
|
+
if (sourceExt.includes(path.extname(baseName)))
|
|
1312
|
+
return;
|
|
1313
|
+
const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
|
|
1314
|
+
if (foundExt)
|
|
1315
|
+
return `${localBin}${foundExt}`;
|
|
1316
|
+
return;
|
|
1317
|
+
}
|
|
1318
|
+
this._checkForMissingMandatoryOptions();
|
|
1319
|
+
this._checkForConflictingOptions();
|
|
1320
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1321
|
+
let executableDir = this._executableDir || "";
|
|
1322
|
+
if (this._scriptPath) {
|
|
1323
|
+
let resolvedScriptPath;
|
|
1324
|
+
try {
|
|
1325
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
1326
|
+
} catch {
|
|
1327
|
+
resolvedScriptPath = this._scriptPath;
|
|
1328
|
+
}
|
|
1329
|
+
executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
|
|
1330
|
+
}
|
|
1331
|
+
if (executableDir) {
|
|
1332
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1333
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1334
|
+
const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
|
|
1335
|
+
if (legacyName !== this._name) {
|
|
1336
|
+
localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
executableFile = localFile || executableFile;
|
|
1340
|
+
}
|
|
1341
|
+
launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
1342
|
+
let proc;
|
|
1343
|
+
if (process2.platform !== "win32") {
|
|
1344
|
+
if (launchWithNode) {
|
|
1345
|
+
args.unshift(executableFile);
|
|
1346
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1347
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
1348
|
+
} else {
|
|
1349
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1350
|
+
}
|
|
1351
|
+
} else {
|
|
1352
|
+
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1353
|
+
args.unshift(executableFile);
|
|
1354
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1355
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
1356
|
+
}
|
|
1357
|
+
if (!proc.killed) {
|
|
1358
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
1359
|
+
signals.forEach((signal) => {
|
|
1360
|
+
process2.on(signal, () => {
|
|
1361
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
1362
|
+
proc.kill(signal);
|
|
1363
|
+
}
|
|
1364
|
+
});
|
|
1365
|
+
});
|
|
1366
|
+
}
|
|
1367
|
+
const exitCallback = this._exitCallback;
|
|
1368
|
+
proc.on("close", (code) => {
|
|
1369
|
+
code = code ?? 1;
|
|
1370
|
+
if (!exitCallback) {
|
|
1371
|
+
process2.exit(code);
|
|
1372
|
+
} else {
|
|
1373
|
+
exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
|
|
1374
|
+
}
|
|
1375
|
+
});
|
|
1376
|
+
proc.on("error", (err) => {
|
|
1377
|
+
if (err.code === "ENOENT") {
|
|
1378
|
+
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1379
|
+
} else if (err.code === "EACCES") {
|
|
1380
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
1381
|
+
}
|
|
1382
|
+
if (!exitCallback) {
|
|
1383
|
+
process2.exit(1);
|
|
1384
|
+
} else {
|
|
1385
|
+
const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
|
|
1386
|
+
wrappedError.nestedError = err;
|
|
1387
|
+
exitCallback(wrappedError);
|
|
1388
|
+
}
|
|
1389
|
+
});
|
|
1390
|
+
this.runningCommand = proc;
|
|
1391
|
+
}
|
|
1392
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1393
|
+
const subCommand = this._findCommand(commandName);
|
|
1394
|
+
if (!subCommand)
|
|
1395
|
+
this.help({ error: true });
|
|
1396
|
+
subCommand._prepareForParse();
|
|
1397
|
+
let promiseChain;
|
|
1398
|
+
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
|
|
1399
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1400
|
+
if (subCommand._executableHandler) {
|
|
1401
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1402
|
+
} else {
|
|
1403
|
+
return subCommand._parseCommand(operands, unknown);
|
|
1404
|
+
}
|
|
1405
|
+
});
|
|
1406
|
+
return promiseChain;
|
|
1407
|
+
}
|
|
1408
|
+
_dispatchHelpCommand(subcommandName) {
|
|
1409
|
+
if (!subcommandName) {
|
|
1410
|
+
this.help();
|
|
1411
|
+
}
|
|
1412
|
+
const subCommand = this._findCommand(subcommandName);
|
|
1413
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
1414
|
+
subCommand.help();
|
|
1415
|
+
}
|
|
1416
|
+
return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
|
|
1417
|
+
}
|
|
1418
|
+
_checkNumberOfArguments() {
|
|
1419
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
1420
|
+
if (arg.required && this.args[i] == null) {
|
|
1421
|
+
this.missingArgument(arg.name());
|
|
1422
|
+
}
|
|
1423
|
+
});
|
|
1424
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
1425
|
+
return;
|
|
1426
|
+
}
|
|
1427
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
1428
|
+
this._excessArguments(this.args);
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
_processArguments() {
|
|
1432
|
+
const myParseArg = (argument, value, previous) => {
|
|
1433
|
+
let parsedValue = value;
|
|
1434
|
+
if (value !== null && argument.parseArg) {
|
|
1435
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
1436
|
+
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
|
|
1437
|
+
}
|
|
1438
|
+
return parsedValue;
|
|
1439
|
+
};
|
|
1440
|
+
this._checkNumberOfArguments();
|
|
1441
|
+
const processedArgs = [];
|
|
1442
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
1443
|
+
let value = declaredArg.defaultValue;
|
|
1444
|
+
if (declaredArg.variadic) {
|
|
1445
|
+
if (index < this.args.length) {
|
|
1446
|
+
value = this.args.slice(index);
|
|
1447
|
+
if (declaredArg.parseArg) {
|
|
1448
|
+
value = value.reduce((processed, v) => {
|
|
1449
|
+
return myParseArg(declaredArg, v, processed);
|
|
1450
|
+
}, declaredArg.defaultValue);
|
|
1451
|
+
}
|
|
1452
|
+
} else if (value === undefined) {
|
|
1453
|
+
value = [];
|
|
1454
|
+
}
|
|
1455
|
+
} else if (index < this.args.length) {
|
|
1456
|
+
value = this.args[index];
|
|
1457
|
+
if (declaredArg.parseArg) {
|
|
1458
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
processedArgs[index] = value;
|
|
1462
|
+
});
|
|
1463
|
+
this.processedArgs = processedArgs;
|
|
1464
|
+
}
|
|
1465
|
+
_chainOrCall(promise, fn) {
|
|
1466
|
+
if (promise?.then && typeof promise.then === "function") {
|
|
1467
|
+
return promise.then(() => fn());
|
|
1468
|
+
}
|
|
1469
|
+
return fn();
|
|
1470
|
+
}
|
|
1471
|
+
_chainOrCallHooks(promise, event) {
|
|
1472
|
+
let result = promise;
|
|
1473
|
+
const hooks = [];
|
|
1474
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
|
|
1475
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
1476
|
+
hooks.push({ hookedCommand, callback });
|
|
1477
|
+
});
|
|
1478
|
+
});
|
|
1479
|
+
if (event === "postAction") {
|
|
1480
|
+
hooks.reverse();
|
|
1481
|
+
}
|
|
1482
|
+
hooks.forEach((hookDetail) => {
|
|
1483
|
+
result = this._chainOrCall(result, () => {
|
|
1484
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
1485
|
+
});
|
|
1486
|
+
});
|
|
1487
|
+
return result;
|
|
1488
|
+
}
|
|
1489
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
1490
|
+
let result = promise;
|
|
1491
|
+
if (this._lifeCycleHooks[event] !== undefined) {
|
|
1492
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
1493
|
+
result = this._chainOrCall(result, () => {
|
|
1494
|
+
return hook(this, subCommand);
|
|
1495
|
+
});
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
return result;
|
|
1499
|
+
}
|
|
1500
|
+
_parseCommand(operands, unknown) {
|
|
1501
|
+
const parsed = this.parseOptions(unknown);
|
|
1502
|
+
this._parseOptionsEnv();
|
|
1503
|
+
this._parseOptionsImplied();
|
|
1504
|
+
operands = operands.concat(parsed.operands);
|
|
1505
|
+
unknown = parsed.unknown;
|
|
1506
|
+
this.args = operands.concat(unknown);
|
|
1507
|
+
if (operands && this._findCommand(operands[0])) {
|
|
1508
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
1509
|
+
}
|
|
1510
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
1511
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
1512
|
+
}
|
|
1513
|
+
if (this._defaultCommandName) {
|
|
1514
|
+
this._outputHelpIfRequested(unknown);
|
|
1515
|
+
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
1516
|
+
}
|
|
1517
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
1518
|
+
this.help({ error: true });
|
|
1519
|
+
}
|
|
1520
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
1521
|
+
this._checkForMissingMandatoryOptions();
|
|
1522
|
+
this._checkForConflictingOptions();
|
|
1523
|
+
const checkForUnknownOptions = () => {
|
|
1524
|
+
if (parsed.unknown.length > 0) {
|
|
1525
|
+
this.unknownOption(parsed.unknown[0]);
|
|
1526
|
+
}
|
|
1527
|
+
};
|
|
1528
|
+
const commandEvent = `command:${this.name()}`;
|
|
1529
|
+
if (this._actionHandler) {
|
|
1530
|
+
checkForUnknownOptions();
|
|
1531
|
+
this._processArguments();
|
|
1532
|
+
let promiseChain;
|
|
1533
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
1534
|
+
promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
|
|
1535
|
+
if (this.parent) {
|
|
1536
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1537
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
1541
|
+
return promiseChain;
|
|
1542
|
+
}
|
|
1543
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
1544
|
+
checkForUnknownOptions();
|
|
1545
|
+
this._processArguments();
|
|
1546
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1547
|
+
} else if (operands.length) {
|
|
1548
|
+
if (this._findCommand("*")) {
|
|
1549
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
1550
|
+
}
|
|
1551
|
+
if (this.listenerCount("command:*")) {
|
|
1552
|
+
this.emit("command:*", operands, unknown);
|
|
1553
|
+
} else if (this.commands.length) {
|
|
1554
|
+
this.unknownCommand();
|
|
1555
|
+
} else {
|
|
1556
|
+
checkForUnknownOptions();
|
|
1557
|
+
this._processArguments();
|
|
1558
|
+
}
|
|
1559
|
+
} else if (this.commands.length) {
|
|
1560
|
+
checkForUnknownOptions();
|
|
1561
|
+
this.help({ error: true });
|
|
1562
|
+
} else {
|
|
1563
|
+
checkForUnknownOptions();
|
|
1564
|
+
this._processArguments();
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
_findCommand(name) {
|
|
1568
|
+
if (!name)
|
|
1569
|
+
return;
|
|
1570
|
+
return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
|
|
1571
|
+
}
|
|
1572
|
+
_findOption(arg) {
|
|
1573
|
+
return this.options.find((option) => option.is(arg));
|
|
1574
|
+
}
|
|
1575
|
+
_checkForMissingMandatoryOptions() {
|
|
1576
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1577
|
+
cmd.options.forEach((anOption) => {
|
|
1578
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
|
|
1579
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
1580
|
+
}
|
|
1581
|
+
});
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1584
|
+
_checkForConflictingLocalOptions() {
|
|
1585
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
1586
|
+
const optionKey = option.attributeName();
|
|
1587
|
+
if (this.getOptionValue(optionKey) === undefined) {
|
|
1588
|
+
return false;
|
|
1589
|
+
}
|
|
1590
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
1591
|
+
});
|
|
1592
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
|
|
1593
|
+
optionsWithConflicting.forEach((option) => {
|
|
1594
|
+
const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
|
|
1595
|
+
if (conflictingAndDefined) {
|
|
1596
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
1597
|
+
}
|
|
1598
|
+
});
|
|
1599
|
+
}
|
|
1600
|
+
_checkForConflictingOptions() {
|
|
1601
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1602
|
+
cmd._checkForConflictingLocalOptions();
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
parseOptions(args) {
|
|
1606
|
+
const operands = [];
|
|
1607
|
+
const unknown = [];
|
|
1608
|
+
let dest = operands;
|
|
1609
|
+
function maybeOption(arg) {
|
|
1610
|
+
return arg.length > 1 && arg[0] === "-";
|
|
1611
|
+
}
|
|
1612
|
+
const negativeNumberArg = (arg) => {
|
|
1613
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
|
|
1614
|
+
return false;
|
|
1615
|
+
return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
|
|
1616
|
+
};
|
|
1617
|
+
let activeVariadicOption = null;
|
|
1618
|
+
let activeGroup = null;
|
|
1619
|
+
let i = 0;
|
|
1620
|
+
while (i < args.length || activeGroup) {
|
|
1621
|
+
const arg = activeGroup ?? args[i++];
|
|
1622
|
+
activeGroup = null;
|
|
1623
|
+
if (arg === "--") {
|
|
1624
|
+
if (dest === unknown)
|
|
1625
|
+
dest.push(arg);
|
|
1626
|
+
dest.push(...args.slice(i));
|
|
1627
|
+
break;
|
|
1628
|
+
}
|
|
1629
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
1630
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
1631
|
+
continue;
|
|
1632
|
+
}
|
|
1633
|
+
activeVariadicOption = null;
|
|
1634
|
+
if (maybeOption(arg)) {
|
|
1635
|
+
const option = this._findOption(arg);
|
|
1636
|
+
if (option) {
|
|
1637
|
+
if (option.required) {
|
|
1638
|
+
const value = args[i++];
|
|
1639
|
+
if (value === undefined)
|
|
1640
|
+
this.optionMissingArgument(option);
|
|
1641
|
+
this.emit(`option:${option.name()}`, value);
|
|
1642
|
+
} else if (option.optional) {
|
|
1643
|
+
let value = null;
|
|
1644
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
|
|
1645
|
+
value = args[i++];
|
|
1646
|
+
}
|
|
1647
|
+
this.emit(`option:${option.name()}`, value);
|
|
1648
|
+
} else {
|
|
1649
|
+
this.emit(`option:${option.name()}`);
|
|
1650
|
+
}
|
|
1651
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
1652
|
+
continue;
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
1656
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
1657
|
+
if (option) {
|
|
1658
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
1659
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
1660
|
+
} else {
|
|
1661
|
+
this.emit(`option:${option.name()}`);
|
|
1662
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
1663
|
+
}
|
|
1664
|
+
continue;
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
1668
|
+
const index = arg.indexOf("=");
|
|
1669
|
+
const option = this._findOption(arg.slice(0, index));
|
|
1670
|
+
if (option && (option.required || option.optional)) {
|
|
1671
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
1672
|
+
continue;
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
|
|
1676
|
+
dest = unknown;
|
|
1677
|
+
}
|
|
1678
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
1679
|
+
if (this._findCommand(arg)) {
|
|
1680
|
+
operands.push(arg);
|
|
1681
|
+
unknown.push(...args.slice(i));
|
|
1682
|
+
break;
|
|
1683
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
1684
|
+
operands.push(arg, ...args.slice(i));
|
|
1685
|
+
break;
|
|
1686
|
+
} else if (this._defaultCommandName) {
|
|
1687
|
+
unknown.push(arg, ...args.slice(i));
|
|
1688
|
+
break;
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
if (this._passThroughOptions) {
|
|
1692
|
+
dest.push(arg, ...args.slice(i));
|
|
1693
|
+
break;
|
|
1694
|
+
}
|
|
1695
|
+
dest.push(arg);
|
|
1696
|
+
}
|
|
1697
|
+
return { operands, unknown };
|
|
1698
|
+
}
|
|
1699
|
+
opts() {
|
|
1700
|
+
if (this._storeOptionsAsProperties) {
|
|
1701
|
+
const result = {};
|
|
1702
|
+
const len = this.options.length;
|
|
1703
|
+
for (let i = 0;i < len; i++) {
|
|
1704
|
+
const key = this.options[i].attributeName();
|
|
1705
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
1706
|
+
}
|
|
1707
|
+
return result;
|
|
1708
|
+
}
|
|
1709
|
+
return this._optionValues;
|
|
1710
|
+
}
|
|
1711
|
+
optsWithGlobals() {
|
|
1712
|
+
return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
|
|
1713
|
+
}
|
|
1714
|
+
error(message, errorOptions) {
|
|
1715
|
+
this._outputConfiguration.outputError(`${message}
|
|
1716
|
+
`, this._outputConfiguration.writeErr);
|
|
1717
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
1718
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
1719
|
+
`);
|
|
1720
|
+
} else if (this._showHelpAfterError) {
|
|
1721
|
+
this._outputConfiguration.writeErr(`
|
|
1722
|
+
`);
|
|
1723
|
+
this.outputHelp({ error: true });
|
|
1724
|
+
}
|
|
1725
|
+
const config = errorOptions || {};
|
|
1726
|
+
const exitCode = config.exitCode || 1;
|
|
1727
|
+
const code = config.code || "commander.error";
|
|
1728
|
+
this._exit(exitCode, code, message);
|
|
1729
|
+
}
|
|
1730
|
+
_parseOptionsEnv() {
|
|
1731
|
+
this.options.forEach((option) => {
|
|
1732
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
1733
|
+
const optionKey = option.attributeName();
|
|
1734
|
+
if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
|
|
1735
|
+
if (option.required || option.optional) {
|
|
1736
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
1737
|
+
} else {
|
|
1738
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
});
|
|
1743
|
+
}
|
|
1744
|
+
_parseOptionsImplied() {
|
|
1745
|
+
const dualHelper = new DualOptions(this.options);
|
|
1746
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
1747
|
+
return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
1748
|
+
};
|
|
1749
|
+
this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
|
|
1750
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
1751
|
+
this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
|
|
1752
|
+
});
|
|
1753
|
+
});
|
|
1754
|
+
}
|
|
1755
|
+
missingArgument(name) {
|
|
1756
|
+
const message = `error: missing required argument '${name}'`;
|
|
1757
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
1758
|
+
}
|
|
1759
|
+
optionMissingArgument(option) {
|
|
1760
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
1761
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
1762
|
+
}
|
|
1763
|
+
missingMandatoryOptionValue(option) {
|
|
1764
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
1765
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
1766
|
+
}
|
|
1767
|
+
_conflictingOption(option, conflictingOption) {
|
|
1768
|
+
const findBestOptionFromValue = (option2) => {
|
|
1769
|
+
const optionKey = option2.attributeName();
|
|
1770
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
1771
|
+
const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
|
|
1772
|
+
const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
|
|
1773
|
+
if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
|
|
1774
|
+
return negativeOption;
|
|
1775
|
+
}
|
|
1776
|
+
return positiveOption || option2;
|
|
1777
|
+
};
|
|
1778
|
+
const getErrorMessage = (option2) => {
|
|
1779
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
1780
|
+
const optionKey = bestOption.attributeName();
|
|
1781
|
+
const source = this.getOptionValueSource(optionKey);
|
|
1782
|
+
if (source === "env") {
|
|
1783
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
1784
|
+
}
|
|
1785
|
+
return `option '${bestOption.flags}'`;
|
|
1786
|
+
};
|
|
1787
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
1788
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
1789
|
+
}
|
|
1790
|
+
unknownOption(flag) {
|
|
1791
|
+
if (this._allowUnknownOption)
|
|
1792
|
+
return;
|
|
1793
|
+
let suggestion = "";
|
|
1794
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
1795
|
+
let candidateFlags = [];
|
|
1796
|
+
let command = this;
|
|
1797
|
+
do {
|
|
1798
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
1799
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
1800
|
+
command = command.parent;
|
|
1801
|
+
} while (command && !command._enablePositionalOptions);
|
|
1802
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
1803
|
+
}
|
|
1804
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
1805
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
1806
|
+
}
|
|
1807
|
+
_excessArguments(receivedArgs) {
|
|
1808
|
+
if (this._allowExcessArguments)
|
|
1809
|
+
return;
|
|
1810
|
+
const expected = this.registeredArguments.length;
|
|
1811
|
+
const s = expected === 1 ? "" : "s";
|
|
1812
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
1813
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
1814
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
1815
|
+
}
|
|
1816
|
+
unknownCommand() {
|
|
1817
|
+
const unknownName = this.args[0];
|
|
1818
|
+
let suggestion = "";
|
|
1819
|
+
if (this._showSuggestionAfterError) {
|
|
1820
|
+
const candidateNames = [];
|
|
1821
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
1822
|
+
candidateNames.push(command.name());
|
|
1823
|
+
if (command.alias())
|
|
1824
|
+
candidateNames.push(command.alias());
|
|
1825
|
+
});
|
|
1826
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
1827
|
+
}
|
|
1828
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
1829
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
1830
|
+
}
|
|
1831
|
+
version(str, flags, description) {
|
|
1832
|
+
if (str === undefined)
|
|
1833
|
+
return this._version;
|
|
1834
|
+
this._version = str;
|
|
1835
|
+
flags = flags || "-V, --version";
|
|
1836
|
+
description = description || "output the version number";
|
|
1837
|
+
const versionOption = this.createOption(flags, description);
|
|
1838
|
+
this._versionOptionName = versionOption.attributeName();
|
|
1839
|
+
this._registerOption(versionOption);
|
|
1840
|
+
this.on("option:" + versionOption.name(), () => {
|
|
1841
|
+
this._outputConfiguration.writeOut(`${str}
|
|
1842
|
+
`);
|
|
1843
|
+
this._exit(0, "commander.version", str);
|
|
1844
|
+
});
|
|
1845
|
+
return this;
|
|
1846
|
+
}
|
|
1847
|
+
description(str, argsDescription) {
|
|
1848
|
+
if (str === undefined && argsDescription === undefined)
|
|
1849
|
+
return this._description;
|
|
1850
|
+
this._description = str;
|
|
1851
|
+
if (argsDescription) {
|
|
1852
|
+
this._argsDescription = argsDescription;
|
|
1853
|
+
}
|
|
1854
|
+
return this;
|
|
1855
|
+
}
|
|
1856
|
+
summary(str) {
|
|
1857
|
+
if (str === undefined)
|
|
1858
|
+
return this._summary;
|
|
1859
|
+
this._summary = str;
|
|
1860
|
+
return this;
|
|
1861
|
+
}
|
|
1862
|
+
alias(alias) {
|
|
1863
|
+
if (alias === undefined)
|
|
1864
|
+
return this._aliases[0];
|
|
1865
|
+
let command = this;
|
|
1866
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
1867
|
+
command = this.commands[this.commands.length - 1];
|
|
1868
|
+
}
|
|
1869
|
+
if (alias === command._name)
|
|
1870
|
+
throw new Error("Command alias can't be the same as its name");
|
|
1871
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
1872
|
+
if (matchingCommand) {
|
|
1873
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
1874
|
+
throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
|
|
1875
|
+
}
|
|
1876
|
+
command._aliases.push(alias);
|
|
1877
|
+
return this;
|
|
1878
|
+
}
|
|
1879
|
+
aliases(aliases) {
|
|
1880
|
+
if (aliases === undefined)
|
|
1881
|
+
return this._aliases;
|
|
1882
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
1883
|
+
return this;
|
|
1884
|
+
}
|
|
1885
|
+
usage(str) {
|
|
1886
|
+
if (str === undefined) {
|
|
1887
|
+
if (this._usage)
|
|
1888
|
+
return this._usage;
|
|
1889
|
+
const args = this.registeredArguments.map((arg) => {
|
|
1890
|
+
return humanReadableArgName(arg);
|
|
1891
|
+
});
|
|
1892
|
+
return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
|
|
1893
|
+
}
|
|
1894
|
+
this._usage = str;
|
|
1895
|
+
return this;
|
|
1896
|
+
}
|
|
1897
|
+
name(str) {
|
|
1898
|
+
if (str === undefined)
|
|
1899
|
+
return this._name;
|
|
1900
|
+
this._name = str;
|
|
1901
|
+
return this;
|
|
1902
|
+
}
|
|
1903
|
+
helpGroup(heading) {
|
|
1904
|
+
if (heading === undefined)
|
|
1905
|
+
return this._helpGroupHeading ?? "";
|
|
1906
|
+
this._helpGroupHeading = heading;
|
|
1907
|
+
return this;
|
|
1908
|
+
}
|
|
1909
|
+
commandsGroup(heading) {
|
|
1910
|
+
if (heading === undefined)
|
|
1911
|
+
return this._defaultCommandGroup ?? "";
|
|
1912
|
+
this._defaultCommandGroup = heading;
|
|
1913
|
+
return this;
|
|
1914
|
+
}
|
|
1915
|
+
optionsGroup(heading) {
|
|
1916
|
+
if (heading === undefined)
|
|
1917
|
+
return this._defaultOptionGroup ?? "";
|
|
1918
|
+
this._defaultOptionGroup = heading;
|
|
1919
|
+
return this;
|
|
1920
|
+
}
|
|
1921
|
+
_initOptionGroup(option) {
|
|
1922
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading)
|
|
1923
|
+
option.helpGroup(this._defaultOptionGroup);
|
|
1924
|
+
}
|
|
1925
|
+
_initCommandGroup(cmd) {
|
|
1926
|
+
if (this._defaultCommandGroup && !cmd.helpGroup())
|
|
1927
|
+
cmd.helpGroup(this._defaultCommandGroup);
|
|
1928
|
+
}
|
|
1929
|
+
nameFromFilename(filename) {
|
|
1930
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
1931
|
+
return this;
|
|
1932
|
+
}
|
|
1933
|
+
executableDir(path2) {
|
|
1934
|
+
if (path2 === undefined)
|
|
1935
|
+
return this._executableDir;
|
|
1936
|
+
this._executableDir = path2;
|
|
1937
|
+
return this;
|
|
1938
|
+
}
|
|
1939
|
+
helpInformation(contextOptions) {
|
|
1940
|
+
const helper = this.createHelp();
|
|
1941
|
+
const context = this._getOutputContext(contextOptions);
|
|
1942
|
+
helper.prepareContext({
|
|
1943
|
+
error: context.error,
|
|
1944
|
+
helpWidth: context.helpWidth,
|
|
1945
|
+
outputHasColors: context.hasColors
|
|
1946
|
+
});
|
|
1947
|
+
const text = helper.formatHelp(this, helper);
|
|
1948
|
+
if (context.hasColors)
|
|
1949
|
+
return text;
|
|
1950
|
+
return this._outputConfiguration.stripColor(text);
|
|
1951
|
+
}
|
|
1952
|
+
_getOutputContext(contextOptions) {
|
|
1953
|
+
contextOptions = contextOptions || {};
|
|
1954
|
+
const error = !!contextOptions.error;
|
|
1955
|
+
let baseWrite;
|
|
1956
|
+
let hasColors;
|
|
1957
|
+
let helpWidth;
|
|
1958
|
+
if (error) {
|
|
1959
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
1960
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
1961
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
1962
|
+
} else {
|
|
1963
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
1964
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
1965
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
1966
|
+
}
|
|
1967
|
+
const write = (str) => {
|
|
1968
|
+
if (!hasColors)
|
|
1969
|
+
str = this._outputConfiguration.stripColor(str);
|
|
1970
|
+
return baseWrite(str);
|
|
1971
|
+
};
|
|
1972
|
+
return { error, write, hasColors, helpWidth };
|
|
1973
|
+
}
|
|
1974
|
+
outputHelp(contextOptions) {
|
|
1975
|
+
let deprecatedCallback;
|
|
1976
|
+
if (typeof contextOptions === "function") {
|
|
1977
|
+
deprecatedCallback = contextOptions;
|
|
1978
|
+
contextOptions = undefined;
|
|
1979
|
+
}
|
|
1980
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
1981
|
+
const eventContext = {
|
|
1982
|
+
error: outputContext.error,
|
|
1983
|
+
write: outputContext.write,
|
|
1984
|
+
command: this
|
|
1985
|
+
};
|
|
1986
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
1987
|
+
this.emit("beforeHelp", eventContext);
|
|
1988
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
1989
|
+
if (deprecatedCallback) {
|
|
1990
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
1991
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
1992
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
outputContext.write(helpInformation);
|
|
1996
|
+
if (this._getHelpOption()?.long) {
|
|
1997
|
+
this.emit(this._getHelpOption().long);
|
|
1998
|
+
}
|
|
1999
|
+
this.emit("afterHelp", eventContext);
|
|
2000
|
+
this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
|
|
2001
|
+
}
|
|
2002
|
+
helpOption(flags, description) {
|
|
2003
|
+
if (typeof flags === "boolean") {
|
|
2004
|
+
if (flags) {
|
|
2005
|
+
if (this._helpOption === null)
|
|
2006
|
+
this._helpOption = undefined;
|
|
2007
|
+
if (this._defaultOptionGroup) {
|
|
2008
|
+
this._initOptionGroup(this._getHelpOption());
|
|
2009
|
+
}
|
|
2010
|
+
} else {
|
|
2011
|
+
this._helpOption = null;
|
|
2012
|
+
}
|
|
2013
|
+
return this;
|
|
2014
|
+
}
|
|
2015
|
+
this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
|
|
2016
|
+
if (flags || description)
|
|
2017
|
+
this._initOptionGroup(this._helpOption);
|
|
2018
|
+
return this;
|
|
2019
|
+
}
|
|
2020
|
+
_getHelpOption() {
|
|
2021
|
+
if (this._helpOption === undefined) {
|
|
2022
|
+
this.helpOption(undefined, undefined);
|
|
2023
|
+
}
|
|
2024
|
+
return this._helpOption;
|
|
2025
|
+
}
|
|
2026
|
+
addHelpOption(option) {
|
|
2027
|
+
this._helpOption = option;
|
|
2028
|
+
this._initOptionGroup(option);
|
|
2029
|
+
return this;
|
|
2030
|
+
}
|
|
2031
|
+
help(contextOptions) {
|
|
2032
|
+
this.outputHelp(contextOptions);
|
|
2033
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
2034
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
2035
|
+
exitCode = 1;
|
|
2036
|
+
}
|
|
2037
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
2038
|
+
}
|
|
2039
|
+
addHelpText(position, text) {
|
|
2040
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
2041
|
+
if (!allowedValues.includes(position)) {
|
|
2042
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
2043
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
2044
|
+
}
|
|
2045
|
+
const helpEvent = `${position}Help`;
|
|
2046
|
+
this.on(helpEvent, (context) => {
|
|
2047
|
+
let helpStr;
|
|
2048
|
+
if (typeof text === "function") {
|
|
2049
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
2050
|
+
} else {
|
|
2051
|
+
helpStr = text;
|
|
2052
|
+
}
|
|
2053
|
+
if (helpStr) {
|
|
2054
|
+
context.write(`${helpStr}
|
|
2055
|
+
`);
|
|
2056
|
+
}
|
|
2057
|
+
});
|
|
2058
|
+
return this;
|
|
2059
|
+
}
|
|
2060
|
+
_outputHelpIfRequested(args) {
|
|
2061
|
+
const helpOption = this._getHelpOption();
|
|
2062
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
2063
|
+
if (helpRequested) {
|
|
2064
|
+
this.outputHelp();
|
|
2065
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
function incrementNodeInspectorPort(args) {
|
|
2070
|
+
return args.map((arg) => {
|
|
2071
|
+
if (!arg.startsWith("--inspect")) {
|
|
2072
|
+
return arg;
|
|
2073
|
+
}
|
|
2074
|
+
let debugOption;
|
|
2075
|
+
let debugHost = "127.0.0.1";
|
|
2076
|
+
let debugPort = "9229";
|
|
2077
|
+
let match;
|
|
2078
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
2079
|
+
debugOption = match[1];
|
|
2080
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
2081
|
+
debugOption = match[1];
|
|
2082
|
+
if (/^\d+$/.test(match[3])) {
|
|
2083
|
+
debugPort = match[3];
|
|
2084
|
+
} else {
|
|
2085
|
+
debugHost = match[3];
|
|
2086
|
+
}
|
|
2087
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
2088
|
+
debugOption = match[1];
|
|
2089
|
+
debugHost = match[3];
|
|
2090
|
+
debugPort = match[4];
|
|
2091
|
+
}
|
|
2092
|
+
if (debugOption && debugPort !== "0") {
|
|
2093
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
2094
|
+
}
|
|
2095
|
+
return arg;
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
function useColor() {
|
|
2099
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
2100
|
+
return false;
|
|
2101
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
|
|
2102
|
+
return true;
|
|
2103
|
+
return;
|
|
2104
|
+
}
|
|
2105
|
+
exports.Command = Command;
|
|
2106
|
+
exports.useColor = useColor;
|
|
2107
|
+
});
|
|
2108
|
+
|
|
2109
|
+
// node_modules/commander/index.js
|
|
2110
|
+
var require_commander = __commonJS((exports) => {
|
|
2111
|
+
var { Argument } = require_argument();
|
|
2112
|
+
var { Command } = require_command();
|
|
2113
|
+
var { CommanderError, InvalidArgumentError } = require_error();
|
|
2114
|
+
var { Help } = require_help();
|
|
2115
|
+
var { Option } = require_option();
|
|
2116
|
+
exports.program = new Command;
|
|
2117
|
+
exports.createCommand = (name) => new Command(name);
|
|
2118
|
+
exports.createOption = (flags, description) => new Option(flags, description);
|
|
2119
|
+
exports.createArgument = (name, description) => new Argument(name, description);
|
|
2120
|
+
exports.Command = Command;
|
|
2121
|
+
exports.Option = Option;
|
|
2122
|
+
exports.Argument = Argument;
|
|
2123
|
+
exports.Help = Help;
|
|
2124
|
+
exports.CommanderError = CommanderError;
|
|
2125
|
+
exports.InvalidArgumentError = InvalidArgumentError;
|
|
2126
|
+
exports.InvalidOptionArgumentError = InvalidArgumentError;
|
|
2127
|
+
});
|
|
2128
|
+
|
|
2129
|
+
// node_modules/commander/esm.mjs
|
|
2130
|
+
var import__ = __toESM(require_commander(), 1);
|
|
2131
|
+
var {
|
|
2132
|
+
program,
|
|
2133
|
+
createCommand,
|
|
2134
|
+
createArgument,
|
|
2135
|
+
createOption,
|
|
2136
|
+
CommanderError,
|
|
2137
|
+
InvalidArgumentError,
|
|
2138
|
+
InvalidOptionArgumentError,
|
|
2139
|
+
Command,
|
|
2140
|
+
Argument,
|
|
2141
|
+
Option,
|
|
2142
|
+
Help
|
|
2143
|
+
} = import__.default;
|
|
2144
|
+
|
|
2145
|
+
// src/api/client.ts
|
|
2146
|
+
import { readFileSync } from "fs";
|
|
2147
|
+
import { resolve } from "path";
|
|
2148
|
+
import { homedir } from "os";
|
|
2149
|
+
|
|
2150
|
+
// node_modules/chalk/source/vendor/ansi-styles/index.js
|
|
2151
|
+
var ANSI_BACKGROUND_OFFSET = 10;
|
|
2152
|
+
var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
|
|
2153
|
+
var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
|
|
2154
|
+
var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
|
|
2155
|
+
var styles = {
|
|
2156
|
+
modifier: {
|
|
2157
|
+
reset: [0, 0],
|
|
2158
|
+
bold: [1, 22],
|
|
2159
|
+
dim: [2, 22],
|
|
2160
|
+
italic: [3, 23],
|
|
2161
|
+
underline: [4, 24],
|
|
2162
|
+
overline: [53, 55],
|
|
2163
|
+
inverse: [7, 27],
|
|
2164
|
+
hidden: [8, 28],
|
|
2165
|
+
strikethrough: [9, 29]
|
|
2166
|
+
},
|
|
2167
|
+
color: {
|
|
2168
|
+
black: [30, 39],
|
|
2169
|
+
red: [31, 39],
|
|
2170
|
+
green: [32, 39],
|
|
2171
|
+
yellow: [33, 39],
|
|
2172
|
+
blue: [34, 39],
|
|
2173
|
+
magenta: [35, 39],
|
|
2174
|
+
cyan: [36, 39],
|
|
2175
|
+
white: [37, 39],
|
|
2176
|
+
blackBright: [90, 39],
|
|
2177
|
+
gray: [90, 39],
|
|
2178
|
+
grey: [90, 39],
|
|
2179
|
+
redBright: [91, 39],
|
|
2180
|
+
greenBright: [92, 39],
|
|
2181
|
+
yellowBright: [93, 39],
|
|
2182
|
+
blueBright: [94, 39],
|
|
2183
|
+
magentaBright: [95, 39],
|
|
2184
|
+
cyanBright: [96, 39],
|
|
2185
|
+
whiteBright: [97, 39]
|
|
2186
|
+
},
|
|
2187
|
+
bgColor: {
|
|
2188
|
+
bgBlack: [40, 49],
|
|
2189
|
+
bgRed: [41, 49],
|
|
2190
|
+
bgGreen: [42, 49],
|
|
2191
|
+
bgYellow: [43, 49],
|
|
2192
|
+
bgBlue: [44, 49],
|
|
2193
|
+
bgMagenta: [45, 49],
|
|
2194
|
+
bgCyan: [46, 49],
|
|
2195
|
+
bgWhite: [47, 49],
|
|
2196
|
+
bgBlackBright: [100, 49],
|
|
2197
|
+
bgGray: [100, 49],
|
|
2198
|
+
bgGrey: [100, 49],
|
|
2199
|
+
bgRedBright: [101, 49],
|
|
2200
|
+
bgGreenBright: [102, 49],
|
|
2201
|
+
bgYellowBright: [103, 49],
|
|
2202
|
+
bgBlueBright: [104, 49],
|
|
2203
|
+
bgMagentaBright: [105, 49],
|
|
2204
|
+
bgCyanBright: [106, 49],
|
|
2205
|
+
bgWhiteBright: [107, 49]
|
|
2206
|
+
}
|
|
2207
|
+
};
|
|
2208
|
+
var modifierNames = Object.keys(styles.modifier);
|
|
2209
|
+
var foregroundColorNames = Object.keys(styles.color);
|
|
2210
|
+
var backgroundColorNames = Object.keys(styles.bgColor);
|
|
2211
|
+
var colorNames = [...foregroundColorNames, ...backgroundColorNames];
|
|
2212
|
+
function assembleStyles() {
|
|
2213
|
+
const codes = new Map;
|
|
2214
|
+
for (const [groupName, group] of Object.entries(styles)) {
|
|
2215
|
+
for (const [styleName, style] of Object.entries(group)) {
|
|
2216
|
+
styles[styleName] = {
|
|
2217
|
+
open: `\x1B[${style[0]}m`,
|
|
2218
|
+
close: `\x1B[${style[1]}m`
|
|
2219
|
+
};
|
|
2220
|
+
group[styleName] = styles[styleName];
|
|
2221
|
+
codes.set(style[0], style[1]);
|
|
2222
|
+
}
|
|
2223
|
+
Object.defineProperty(styles, groupName, {
|
|
2224
|
+
value: group,
|
|
2225
|
+
enumerable: false
|
|
2226
|
+
});
|
|
2227
|
+
}
|
|
2228
|
+
Object.defineProperty(styles, "codes", {
|
|
2229
|
+
value: codes,
|
|
2230
|
+
enumerable: false
|
|
2231
|
+
});
|
|
2232
|
+
styles.color.close = "\x1B[39m";
|
|
2233
|
+
styles.bgColor.close = "\x1B[49m";
|
|
2234
|
+
styles.color.ansi = wrapAnsi16();
|
|
2235
|
+
styles.color.ansi256 = wrapAnsi256();
|
|
2236
|
+
styles.color.ansi16m = wrapAnsi16m();
|
|
2237
|
+
styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
|
|
2238
|
+
styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
|
|
2239
|
+
styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
|
|
2240
|
+
Object.defineProperties(styles, {
|
|
2241
|
+
rgbToAnsi256: {
|
|
2242
|
+
value(red, green, blue) {
|
|
2243
|
+
if (red === green && green === blue) {
|
|
2244
|
+
if (red < 8) {
|
|
2245
|
+
return 16;
|
|
2246
|
+
}
|
|
2247
|
+
if (red > 248) {
|
|
2248
|
+
return 231;
|
|
2249
|
+
}
|
|
2250
|
+
return Math.round((red - 8) / 247 * 24) + 232;
|
|
2251
|
+
}
|
|
2252
|
+
return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
|
|
2253
|
+
},
|
|
2254
|
+
enumerable: false
|
|
2255
|
+
},
|
|
2256
|
+
hexToRgb: {
|
|
2257
|
+
value(hex) {
|
|
2258
|
+
const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
|
|
2259
|
+
if (!matches) {
|
|
2260
|
+
return [0, 0, 0];
|
|
2261
|
+
}
|
|
2262
|
+
let [colorString] = matches;
|
|
2263
|
+
if (colorString.length === 3) {
|
|
2264
|
+
colorString = [...colorString].map((character) => character + character).join("");
|
|
2265
|
+
}
|
|
2266
|
+
const integer = Number.parseInt(colorString, 16);
|
|
2267
|
+
return [
|
|
2268
|
+
integer >> 16 & 255,
|
|
2269
|
+
integer >> 8 & 255,
|
|
2270
|
+
integer & 255
|
|
2271
|
+
];
|
|
2272
|
+
},
|
|
2273
|
+
enumerable: false
|
|
2274
|
+
},
|
|
2275
|
+
hexToAnsi256: {
|
|
2276
|
+
value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
|
|
2277
|
+
enumerable: false
|
|
2278
|
+
},
|
|
2279
|
+
ansi256ToAnsi: {
|
|
2280
|
+
value(code) {
|
|
2281
|
+
if (code < 8) {
|
|
2282
|
+
return 30 + code;
|
|
2283
|
+
}
|
|
2284
|
+
if (code < 16) {
|
|
2285
|
+
return 90 + (code - 8);
|
|
2286
|
+
}
|
|
2287
|
+
let red;
|
|
2288
|
+
let green;
|
|
2289
|
+
let blue;
|
|
2290
|
+
if (code >= 232) {
|
|
2291
|
+
red = ((code - 232) * 10 + 8) / 255;
|
|
2292
|
+
green = red;
|
|
2293
|
+
blue = red;
|
|
2294
|
+
} else {
|
|
2295
|
+
code -= 16;
|
|
2296
|
+
const remainder = code % 36;
|
|
2297
|
+
red = Math.floor(code / 36) / 5;
|
|
2298
|
+
green = Math.floor(remainder / 6) / 5;
|
|
2299
|
+
blue = remainder % 6 / 5;
|
|
2300
|
+
}
|
|
2301
|
+
const value = Math.max(red, green, blue) * 2;
|
|
2302
|
+
if (value === 0) {
|
|
2303
|
+
return 30;
|
|
2304
|
+
}
|
|
2305
|
+
let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
|
|
2306
|
+
if (value === 2) {
|
|
2307
|
+
result += 60;
|
|
2308
|
+
}
|
|
2309
|
+
return result;
|
|
2310
|
+
},
|
|
2311
|
+
enumerable: false
|
|
2312
|
+
},
|
|
2313
|
+
rgbToAnsi: {
|
|
2314
|
+
value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
|
|
2315
|
+
enumerable: false
|
|
2316
|
+
},
|
|
2317
|
+
hexToAnsi: {
|
|
2318
|
+
value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
|
|
2319
|
+
enumerable: false
|
|
2320
|
+
}
|
|
2321
|
+
});
|
|
2322
|
+
return styles;
|
|
2323
|
+
}
|
|
2324
|
+
var ansiStyles = assembleStyles();
|
|
2325
|
+
var ansi_styles_default = ansiStyles;
|
|
2326
|
+
|
|
2327
|
+
// node_modules/chalk/source/vendor/supports-color/index.js
|
|
2328
|
+
import process2 from "process";
|
|
2329
|
+
import os from "os";
|
|
2330
|
+
import tty from "tty";
|
|
2331
|
+
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
|
|
2332
|
+
const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
|
|
2333
|
+
const position = argv.indexOf(prefix + flag);
|
|
2334
|
+
const terminatorPosition = argv.indexOf("--");
|
|
2335
|
+
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
|
|
2336
|
+
}
|
|
2337
|
+
var { env } = process2;
|
|
2338
|
+
var flagForceColor;
|
|
2339
|
+
if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
|
|
2340
|
+
flagForceColor = 0;
|
|
2341
|
+
} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
|
|
2342
|
+
flagForceColor = 1;
|
|
2343
|
+
}
|
|
2344
|
+
function envForceColor() {
|
|
2345
|
+
if ("FORCE_COLOR" in env) {
|
|
2346
|
+
if (env.FORCE_COLOR === "true") {
|
|
2347
|
+
return 1;
|
|
2348
|
+
}
|
|
2349
|
+
if (env.FORCE_COLOR === "false") {
|
|
2350
|
+
return 0;
|
|
2351
|
+
}
|
|
2352
|
+
return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
function translateLevel(level) {
|
|
2356
|
+
if (level === 0) {
|
|
2357
|
+
return false;
|
|
2358
|
+
}
|
|
2359
|
+
return {
|
|
2360
|
+
level,
|
|
2361
|
+
hasBasic: true,
|
|
2362
|
+
has256: level >= 2,
|
|
2363
|
+
has16m: level >= 3
|
|
2364
|
+
};
|
|
2365
|
+
}
|
|
2366
|
+
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
|
|
2367
|
+
const noFlagForceColor = envForceColor();
|
|
2368
|
+
if (noFlagForceColor !== undefined) {
|
|
2369
|
+
flagForceColor = noFlagForceColor;
|
|
2370
|
+
}
|
|
2371
|
+
const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
|
|
2372
|
+
if (forceColor === 0) {
|
|
2373
|
+
return 0;
|
|
2374
|
+
}
|
|
2375
|
+
if (sniffFlags) {
|
|
2376
|
+
if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
|
|
2377
|
+
return 3;
|
|
2378
|
+
}
|
|
2379
|
+
if (hasFlag("color=256")) {
|
|
2380
|
+
return 2;
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
if ("TF_BUILD" in env && "AGENT_NAME" in env) {
|
|
2384
|
+
return 1;
|
|
2385
|
+
}
|
|
2386
|
+
if (haveStream && !streamIsTTY && forceColor === undefined) {
|
|
2387
|
+
return 0;
|
|
2388
|
+
}
|
|
2389
|
+
const min = forceColor || 0;
|
|
2390
|
+
if (env.TERM === "dumb") {
|
|
2391
|
+
return min;
|
|
2392
|
+
}
|
|
2393
|
+
if (process2.platform === "win32") {
|
|
2394
|
+
const osRelease = os.release().split(".");
|
|
2395
|
+
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
|
|
2396
|
+
return Number(osRelease[2]) >= 14931 ? 3 : 2;
|
|
2397
|
+
}
|
|
2398
|
+
return 1;
|
|
2399
|
+
}
|
|
2400
|
+
if ("CI" in env) {
|
|
2401
|
+
if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => (key in env))) {
|
|
2402
|
+
return 3;
|
|
2403
|
+
}
|
|
2404
|
+
if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") {
|
|
2405
|
+
return 1;
|
|
2406
|
+
}
|
|
2407
|
+
return min;
|
|
2408
|
+
}
|
|
2409
|
+
if ("TEAMCITY_VERSION" in env) {
|
|
2410
|
+
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
|
|
2411
|
+
}
|
|
2412
|
+
if (env.COLORTERM === "truecolor") {
|
|
2413
|
+
return 3;
|
|
2414
|
+
}
|
|
2415
|
+
if (env.TERM === "xterm-kitty") {
|
|
2416
|
+
return 3;
|
|
2417
|
+
}
|
|
2418
|
+
if (env.TERM === "xterm-ghostty") {
|
|
2419
|
+
return 3;
|
|
2420
|
+
}
|
|
2421
|
+
if (env.TERM === "wezterm") {
|
|
2422
|
+
return 3;
|
|
2423
|
+
}
|
|
2424
|
+
if ("TERM_PROGRAM" in env) {
|
|
2425
|
+
const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
|
|
2426
|
+
switch (env.TERM_PROGRAM) {
|
|
2427
|
+
case "iTerm.app": {
|
|
2428
|
+
return version >= 3 ? 3 : 2;
|
|
2429
|
+
}
|
|
2430
|
+
case "Apple_Terminal": {
|
|
2431
|
+
return 2;
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
}
|
|
2435
|
+
if (/-256(color)?$/i.test(env.TERM)) {
|
|
2436
|
+
return 2;
|
|
2437
|
+
}
|
|
2438
|
+
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
|
|
2439
|
+
return 1;
|
|
2440
|
+
}
|
|
2441
|
+
if ("COLORTERM" in env) {
|
|
2442
|
+
return 1;
|
|
2443
|
+
}
|
|
2444
|
+
return min;
|
|
2445
|
+
}
|
|
2446
|
+
function createSupportsColor(stream, options = {}) {
|
|
2447
|
+
const level = _supportsColor(stream, {
|
|
2448
|
+
streamIsTTY: stream && stream.isTTY,
|
|
2449
|
+
...options
|
|
2450
|
+
});
|
|
2451
|
+
return translateLevel(level);
|
|
2452
|
+
}
|
|
2453
|
+
var supportsColor = {
|
|
2454
|
+
stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
|
|
2455
|
+
stderr: createSupportsColor({ isTTY: tty.isatty(2) })
|
|
2456
|
+
};
|
|
2457
|
+
var supports_color_default = supportsColor;
|
|
2458
|
+
|
|
2459
|
+
// node_modules/chalk/source/utilities.js
|
|
2460
|
+
function stringReplaceAll(string, substring, replacer) {
|
|
2461
|
+
let index = string.indexOf(substring);
|
|
2462
|
+
if (index === -1) {
|
|
2463
|
+
return string;
|
|
2464
|
+
}
|
|
2465
|
+
const substringLength = substring.length;
|
|
2466
|
+
let endIndex = 0;
|
|
2467
|
+
let returnValue = "";
|
|
2468
|
+
do {
|
|
2469
|
+
returnValue += string.slice(endIndex, index) + substring + replacer;
|
|
2470
|
+
endIndex = index + substringLength;
|
|
2471
|
+
index = string.indexOf(substring, endIndex);
|
|
2472
|
+
} while (index !== -1);
|
|
2473
|
+
returnValue += string.slice(endIndex);
|
|
2474
|
+
return returnValue;
|
|
2475
|
+
}
|
|
2476
|
+
function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
|
|
2477
|
+
let endIndex = 0;
|
|
2478
|
+
let returnValue = "";
|
|
2479
|
+
do {
|
|
2480
|
+
const gotCR = string[index - 1] === "\r";
|
|
2481
|
+
returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? `\r
|
|
2482
|
+
` : `
|
|
2483
|
+
`) + postfix;
|
|
2484
|
+
endIndex = index + 1;
|
|
2485
|
+
index = string.indexOf(`
|
|
2486
|
+
`, endIndex);
|
|
2487
|
+
} while (index !== -1);
|
|
2488
|
+
returnValue += string.slice(endIndex);
|
|
2489
|
+
return returnValue;
|
|
2490
|
+
}
|
|
2491
|
+
|
|
2492
|
+
// node_modules/chalk/source/index.js
|
|
2493
|
+
var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
|
|
2494
|
+
var GENERATOR = Symbol("GENERATOR");
|
|
2495
|
+
var STYLER = Symbol("STYLER");
|
|
2496
|
+
var IS_EMPTY = Symbol("IS_EMPTY");
|
|
2497
|
+
var levelMapping = [
|
|
2498
|
+
"ansi",
|
|
2499
|
+
"ansi",
|
|
2500
|
+
"ansi256",
|
|
2501
|
+
"ansi16m"
|
|
2502
|
+
];
|
|
2503
|
+
var styles2 = Object.create(null);
|
|
2504
|
+
var applyOptions = (object, options = {}) => {
|
|
2505
|
+
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
|
|
2506
|
+
throw new Error("The `level` option should be an integer from 0 to 3");
|
|
2507
|
+
}
|
|
2508
|
+
const colorLevel = stdoutColor ? stdoutColor.level : 0;
|
|
2509
|
+
object.level = options.level === undefined ? colorLevel : options.level;
|
|
2510
|
+
};
|
|
2511
|
+
var chalkFactory = (options) => {
|
|
2512
|
+
const chalk = (...strings) => strings.join(" ");
|
|
2513
|
+
applyOptions(chalk, options);
|
|
2514
|
+
Object.setPrototypeOf(chalk, createChalk.prototype);
|
|
2515
|
+
return chalk;
|
|
2516
|
+
};
|
|
2517
|
+
function createChalk(options) {
|
|
2518
|
+
return chalkFactory(options);
|
|
2519
|
+
}
|
|
2520
|
+
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
|
|
2521
|
+
for (const [styleName, style] of Object.entries(ansi_styles_default)) {
|
|
2522
|
+
styles2[styleName] = {
|
|
2523
|
+
get() {
|
|
2524
|
+
const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
|
|
2525
|
+
Object.defineProperty(this, styleName, { value: builder });
|
|
2526
|
+
return builder;
|
|
2527
|
+
}
|
|
2528
|
+
};
|
|
2529
|
+
}
|
|
2530
|
+
styles2.visible = {
|
|
2531
|
+
get() {
|
|
2532
|
+
const builder = createBuilder(this, this[STYLER], true);
|
|
2533
|
+
Object.defineProperty(this, "visible", { value: builder });
|
|
2534
|
+
return builder;
|
|
2535
|
+
}
|
|
2536
|
+
};
|
|
2537
|
+
var getModelAnsi = (model, level, type, ...arguments_) => {
|
|
2538
|
+
if (model === "rgb") {
|
|
2539
|
+
if (level === "ansi16m") {
|
|
2540
|
+
return ansi_styles_default[type].ansi16m(...arguments_);
|
|
2541
|
+
}
|
|
2542
|
+
if (level === "ansi256") {
|
|
2543
|
+
return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
|
|
2544
|
+
}
|
|
2545
|
+
return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
|
|
2546
|
+
}
|
|
2547
|
+
if (model === "hex") {
|
|
2548
|
+
return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
|
|
2549
|
+
}
|
|
2550
|
+
return ansi_styles_default[type][model](...arguments_);
|
|
2551
|
+
};
|
|
2552
|
+
var usedModels = ["rgb", "hex", "ansi256"];
|
|
2553
|
+
for (const model of usedModels) {
|
|
2554
|
+
styles2[model] = {
|
|
2555
|
+
get() {
|
|
2556
|
+
const { level } = this;
|
|
2557
|
+
return function(...arguments_) {
|
|
2558
|
+
const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
|
|
2559
|
+
return createBuilder(this, styler, this[IS_EMPTY]);
|
|
2560
|
+
};
|
|
2561
|
+
}
|
|
2562
|
+
};
|
|
2563
|
+
const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
|
|
2564
|
+
styles2[bgModel] = {
|
|
2565
|
+
get() {
|
|
2566
|
+
const { level } = this;
|
|
2567
|
+
return function(...arguments_) {
|
|
2568
|
+
const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
|
|
2569
|
+
return createBuilder(this, styler, this[IS_EMPTY]);
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
};
|
|
2573
|
+
}
|
|
2574
|
+
var proto = Object.defineProperties(() => {}, {
|
|
2575
|
+
...styles2,
|
|
2576
|
+
level: {
|
|
2577
|
+
enumerable: true,
|
|
2578
|
+
get() {
|
|
2579
|
+
return this[GENERATOR].level;
|
|
2580
|
+
},
|
|
2581
|
+
set(level) {
|
|
2582
|
+
this[GENERATOR].level = level;
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
});
|
|
2586
|
+
var createStyler = (open, close, parent) => {
|
|
2587
|
+
let openAll;
|
|
2588
|
+
let closeAll;
|
|
2589
|
+
if (parent === undefined) {
|
|
2590
|
+
openAll = open;
|
|
2591
|
+
closeAll = close;
|
|
2592
|
+
} else {
|
|
2593
|
+
openAll = parent.openAll + open;
|
|
2594
|
+
closeAll = close + parent.closeAll;
|
|
2595
|
+
}
|
|
2596
|
+
return {
|
|
2597
|
+
open,
|
|
2598
|
+
close,
|
|
2599
|
+
openAll,
|
|
2600
|
+
closeAll,
|
|
2601
|
+
parent
|
|
2602
|
+
};
|
|
2603
|
+
};
|
|
2604
|
+
var createBuilder = (self, _styler, _isEmpty) => {
|
|
2605
|
+
const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
|
|
2606
|
+
Object.setPrototypeOf(builder, proto);
|
|
2607
|
+
builder[GENERATOR] = self;
|
|
2608
|
+
builder[STYLER] = _styler;
|
|
2609
|
+
builder[IS_EMPTY] = _isEmpty;
|
|
2610
|
+
return builder;
|
|
2611
|
+
};
|
|
2612
|
+
var applyStyle = (self, string) => {
|
|
2613
|
+
if (self.level <= 0 || !string) {
|
|
2614
|
+
return self[IS_EMPTY] ? "" : string;
|
|
2615
|
+
}
|
|
2616
|
+
let styler = self[STYLER];
|
|
2617
|
+
if (styler === undefined) {
|
|
2618
|
+
return string;
|
|
2619
|
+
}
|
|
2620
|
+
const { openAll, closeAll } = styler;
|
|
2621
|
+
if (string.includes("\x1B")) {
|
|
2622
|
+
while (styler !== undefined) {
|
|
2623
|
+
string = stringReplaceAll(string, styler.close, styler.open);
|
|
2624
|
+
styler = styler.parent;
|
|
2625
|
+
}
|
|
2626
|
+
}
|
|
2627
|
+
const lfIndex = string.indexOf(`
|
|
2628
|
+
`);
|
|
2629
|
+
if (lfIndex !== -1) {
|
|
2630
|
+
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
|
|
2631
|
+
}
|
|
2632
|
+
return openAll + string + closeAll;
|
|
2633
|
+
};
|
|
2634
|
+
Object.defineProperties(createChalk.prototype, styles2);
|
|
2635
|
+
var chalk = createChalk();
|
|
2636
|
+
var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
|
|
2637
|
+
var source_default = chalk;
|
|
2638
|
+
|
|
2639
|
+
// src/lib/errors.ts
|
|
2640
|
+
class CliError extends Error {
|
|
2641
|
+
code;
|
|
2642
|
+
hint;
|
|
2643
|
+
constructor(code, message, hint) {
|
|
2644
|
+
super(message);
|
|
2645
|
+
this.code = code;
|
|
2646
|
+
this.hint = hint;
|
|
2647
|
+
this.name = "CliError";
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
var EXIT_CODE_BY_CODE = {
|
|
2651
|
+
BAD_ARGS: 1,
|
|
2652
|
+
TOKEN_MISSING: 2,
|
|
2653
|
+
TOKEN_INVALID: 2,
|
|
2654
|
+
API_ERROR: 3,
|
|
2655
|
+
DB_ERROR: 4
|
|
2656
|
+
};
|
|
2657
|
+
function exitCodeFor(err) {
|
|
2658
|
+
if (err instanceof CliError)
|
|
2659
|
+
return EXIT_CODE_BY_CODE[err.code] ?? 1;
|
|
2660
|
+
return 1;
|
|
2661
|
+
}
|
|
2662
|
+
function formatError(err, format) {
|
|
2663
|
+
const code = err instanceof CliError ? err.code : "UNKNOWN";
|
|
2664
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2665
|
+
const hint = err instanceof CliError ? err.hint : undefined;
|
|
2666
|
+
if (format === "json") {
|
|
2667
|
+
return {
|
|
2668
|
+
kind: "json",
|
|
2669
|
+
text: JSON.stringify({ error: { code, message, ...hint ? { hint } : {} } })
|
|
2670
|
+
};
|
|
2671
|
+
}
|
|
2672
|
+
const head = source_default.red(`error: ${message}`);
|
|
2673
|
+
return { kind: "text", text: hint ? `${head}
|
|
2674
|
+
hint: ${hint}` : head };
|
|
2675
|
+
}
|
|
2676
|
+
function emitError(err, format) {
|
|
2677
|
+
const env2 = formatError(err, format);
|
|
2678
|
+
process.stderr.write(env2.text + `
|
|
2679
|
+
`);
|
|
2680
|
+
}
|
|
2681
|
+
|
|
2682
|
+
// src/api/client.ts
|
|
2683
|
+
var BASE_URL = "https://api.ouraring.com/v2/usercollection";
|
|
2684
|
+
|
|
2685
|
+
class OuraClient {
|
|
2686
|
+
token;
|
|
2687
|
+
constructor(options = {}) {
|
|
2688
|
+
const direct = options.token ?? process.env.OURA_TOKEN;
|
|
2689
|
+
if (direct) {
|
|
2690
|
+
this.token = direct.trim();
|
|
2691
|
+
} else {
|
|
2692
|
+
const tokenPath = options.tokenPath ?? process.env.OURA_TOKEN_PATH ?? resolve(homedir(), ".oura-token");
|
|
2693
|
+
try {
|
|
2694
|
+
this.token = readFileSync(tokenPath, "utf-8").trim();
|
|
2695
|
+
} catch {
|
|
2696
|
+
throw new CliError("TOKEN_MISSING", `No Oura access token at ${tokenPath}.`, "Run `oura-cli login` or set OURA_TOKEN.");
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
async fetch(endpoint, startDate, endDate) {
|
|
2701
|
+
const params = new URLSearchParams({ start_date: startDate });
|
|
2702
|
+
if (endDate)
|
|
2703
|
+
params.set("end_date", endDate);
|
|
2704
|
+
const url = `${BASE_URL}/${endpoint}?${params}`;
|
|
2705
|
+
const response = await fetch(url, {
|
|
2706
|
+
headers: { Authorization: `Bearer ${this.token}` }
|
|
2707
|
+
});
|
|
2708
|
+
if (!response.ok) {
|
|
2709
|
+
const body = await response.text();
|
|
2710
|
+
if (response.status === 401 || response.status === 403) {
|
|
2711
|
+
throw new CliError("TOKEN_INVALID", `Oura API ${response.status}: ${body}`);
|
|
2712
|
+
}
|
|
2713
|
+
throw new CliError("API_ERROR", `Oura API ${response.status}: ${body}`);
|
|
2714
|
+
}
|
|
2715
|
+
const json = await response.json();
|
|
2716
|
+
return json.data ?? [];
|
|
2717
|
+
}
|
|
2718
|
+
}
|
|
2719
|
+
|
|
2720
|
+
// src/commands/helpers.ts
|
|
2721
|
+
function getClient(opts) {
|
|
2722
|
+
return new OuraClient(opts.token ? { tokenPath: opts.token } : {});
|
|
2723
|
+
}
|
|
2724
|
+
function todayDate() {
|
|
2725
|
+
return new Date().toISOString().slice(0, 10);
|
|
2726
|
+
}
|
|
2727
|
+
function dateRange(days) {
|
|
2728
|
+
const end = todayDate();
|
|
2729
|
+
const start = new Date(Date.now() - days * 86400000).toISOString().slice(0, 10);
|
|
2730
|
+
return { start, end };
|
|
2731
|
+
}
|
|
2732
|
+
|
|
2733
|
+
// src/commands/api-command.ts
|
|
2734
|
+
function createApiCommand(name, description, endpoint) {
|
|
2735
|
+
const cmd = new Command(name).description(description);
|
|
2736
|
+
cmd.command("today").description(`Today's ${name} data`).action(async (_, command) => {
|
|
2737
|
+
const opts = command.parent.parent.opts();
|
|
2738
|
+
const client = getClient(opts);
|
|
2739
|
+
const data = await client.fetch(endpoint, todayDate(), todayDate());
|
|
2740
|
+
console.log(JSON.stringify(data, null, 2));
|
|
2741
|
+
});
|
|
2742
|
+
cmd.command("date <day>").description(`${name} data for specific date (YYYY-MM-DD)`).action(async (day, _, command) => {
|
|
2743
|
+
const opts = command.parent.parent.opts();
|
|
2744
|
+
const client = getClient(opts);
|
|
2745
|
+
const data = await client.fetch(endpoint, day, day);
|
|
2746
|
+
console.log(JSON.stringify(data, null, 2));
|
|
2747
|
+
});
|
|
2748
|
+
cmd.command("week").description(`Last 7 days of ${name} data`).action(async (_, command) => {
|
|
2749
|
+
const opts = command.parent.parent.opts();
|
|
2750
|
+
const client = getClient(opts);
|
|
2751
|
+
const { start, end } = dateRange(7);
|
|
2752
|
+
const data = await client.fetch(endpoint, start, end);
|
|
2753
|
+
console.log(JSON.stringify(data, null, 2));
|
|
2754
|
+
});
|
|
2755
|
+
return cmd;
|
|
2756
|
+
}
|
|
2757
|
+
|
|
2758
|
+
// src/commands/db.ts
|
|
2759
|
+
import { mkdirSync as mkdirSync2, unlinkSync } from "fs";
|
|
2760
|
+
import { dirname } from "path";
|
|
2761
|
+
|
|
2762
|
+
// src/lib/db.ts
|
|
2763
|
+
import { Database } from "bun:sqlite";
|
|
2764
|
+
import { resolve as resolve2 } from "path";
|
|
2765
|
+
import { homedir as homedir2 } from "os";
|
|
2766
|
+
import { mkdirSync } from "fs";
|
|
2767
|
+
function getDbPath(options = {}) {
|
|
2768
|
+
if (options.dbPath)
|
|
2769
|
+
return options.dbPath;
|
|
2770
|
+
if (options.envVar && process.env[options.envVar])
|
|
2771
|
+
return process.env[options.envVar];
|
|
2772
|
+
const dir = options.defaultDir ?? ".oura-cli";
|
|
2773
|
+
const file = options.defaultFile ?? "oura.db";
|
|
2774
|
+
return resolve2(homedir2(), dir, file);
|
|
2775
|
+
}
|
|
2776
|
+
function openDatabase(options = {}) {
|
|
2777
|
+
const dbPath = getDbPath(options);
|
|
2778
|
+
if (dbPath !== ":memory:") {
|
|
2779
|
+
mkdirSync(resolve2(dbPath, ".."), { recursive: true });
|
|
2780
|
+
}
|
|
2781
|
+
const db = new Database(dbPath);
|
|
2782
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
2783
|
+
db.exec("PRAGMA foreign_keys = ON");
|
|
2784
|
+
return db;
|
|
2785
|
+
}
|
|
2786
|
+
function getSchemaVersion(db) {
|
|
2787
|
+
db.exec("CREATE TABLE IF NOT EXISTS _schema_version (version INTEGER NOT NULL)");
|
|
2788
|
+
const row = db.query("SELECT MAX(version) AS v FROM _schema_version").get();
|
|
2789
|
+
return row?.v ?? 0;
|
|
2790
|
+
}
|
|
2791
|
+
function ensureSchema(db, migrations) {
|
|
2792
|
+
const current = getSchemaVersion(db);
|
|
2793
|
+
for (const m of migrations) {
|
|
2794
|
+
if (m.version > current) {
|
|
2795
|
+
db.exec(m.sql);
|
|
2796
|
+
db.query("INSERT INTO _schema_version (version) VALUES (?)").run(m.version);
|
|
2797
|
+
}
|
|
2798
|
+
}
|
|
2799
|
+
}
|
|
2800
|
+
|
|
2801
|
+
// src/db/schema.ts
|
|
2802
|
+
var MIGRATIONS = [
|
|
2803
|
+
{
|
|
2804
|
+
version: 1,
|
|
2805
|
+
sql: `
|
|
2806
|
+
CREATE TABLE IF NOT EXISTS daily_sleep (
|
|
2807
|
+
id TEXT PRIMARY KEY,
|
|
2808
|
+
day TEXT UNIQUE,
|
|
2809
|
+
score INTEGER,
|
|
2810
|
+
contributors TEXT,
|
|
2811
|
+
timestamp TEXT
|
|
2812
|
+
);
|
|
2813
|
+
CREATE TABLE IF NOT EXISTS daily_readiness (
|
|
2814
|
+
id TEXT PRIMARY KEY,
|
|
2815
|
+
day TEXT UNIQUE,
|
|
2816
|
+
score INTEGER,
|
|
2817
|
+
contributors TEXT,
|
|
2818
|
+
temperature_deviation REAL,
|
|
2819
|
+
temperature_trend_deviation REAL,
|
|
2820
|
+
timestamp TEXT
|
|
2821
|
+
);
|
|
2822
|
+
CREATE TABLE IF NOT EXISTS daily_activity (
|
|
2823
|
+
id TEXT PRIMARY KEY,
|
|
2824
|
+
day TEXT UNIQUE,
|
|
2825
|
+
score INTEGER,
|
|
2826
|
+
active_calories INTEGER,
|
|
2827
|
+
steps INTEGER,
|
|
2828
|
+
equivalent_walking_distance REAL,
|
|
2829
|
+
high_activity_time INTEGER,
|
|
2830
|
+
medium_activity_time INTEGER,
|
|
2831
|
+
low_activity_time INTEGER,
|
|
2832
|
+
sedentary_time INTEGER,
|
|
2833
|
+
total_calories INTEGER,
|
|
2834
|
+
target_calories INTEGER,
|
|
2835
|
+
contributors TEXT,
|
|
2836
|
+
timestamp TEXT
|
|
2837
|
+
);
|
|
2838
|
+
CREATE TABLE IF NOT EXISTS daily_spo2 (
|
|
2839
|
+
id TEXT PRIMARY KEY,
|
|
2840
|
+
day TEXT UNIQUE,
|
|
2841
|
+
spo2_average REAL,
|
|
2842
|
+
breathing_disturbance_index REAL
|
|
2843
|
+
);
|
|
2844
|
+
CREATE TABLE IF NOT EXISTS daily_stress (
|
|
2845
|
+
id TEXT PRIMARY KEY,
|
|
2846
|
+
day TEXT UNIQUE,
|
|
2847
|
+
day_summary TEXT,
|
|
2848
|
+
recovery_high INTEGER,
|
|
2849
|
+
stress_high INTEGER
|
|
2850
|
+
);
|
|
2851
|
+
CREATE TABLE IF NOT EXISTS heartrate (
|
|
2852
|
+
timestamp TEXT,
|
|
2853
|
+
bpm INTEGER,
|
|
2854
|
+
source TEXT,
|
|
2855
|
+
day TEXT
|
|
2856
|
+
);
|
|
2857
|
+
CREATE INDEX IF NOT EXISTS idx_heartrate_ts ON heartrate(timestamp);
|
|
2858
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_heartrate_unique ON heartrate(timestamp, source);
|
|
2859
|
+
CREATE INDEX IF NOT EXISTS idx_heartrate_day ON heartrate(day);
|
|
2860
|
+
CREATE TABLE IF NOT EXISTS vo2max (
|
|
2861
|
+
id TEXT PRIMARY KEY,
|
|
2862
|
+
day TEXT UNIQUE,
|
|
2863
|
+
vo2_max REAL,
|
|
2864
|
+
timestamp TEXT
|
|
2865
|
+
);
|
|
2866
|
+
CREATE TABLE IF NOT EXISTS cardiovascular_age (
|
|
2867
|
+
id TEXT PRIMARY KEY,
|
|
2868
|
+
day TEXT UNIQUE,
|
|
2869
|
+
vascular_age INTEGER
|
|
2870
|
+
);
|
|
2871
|
+
CREATE TABLE IF NOT EXISTS workouts (
|
|
2872
|
+
id TEXT PRIMARY KEY,
|
|
2873
|
+
day TEXT,
|
|
2874
|
+
activity TEXT,
|
|
2875
|
+
calories REAL,
|
|
2876
|
+
distance REAL,
|
|
2877
|
+
start_datetime TEXT,
|
|
2878
|
+
end_datetime TEXT,
|
|
2879
|
+
intensity TEXT,
|
|
2880
|
+
label TEXT,
|
|
2881
|
+
source TEXT
|
|
2882
|
+
);
|
|
2883
|
+
CREATE TABLE IF NOT EXISTS sleep_model (
|
|
2884
|
+
id TEXT PRIMARY KEY,
|
|
2885
|
+
day TEXT,
|
|
2886
|
+
average_breath REAL,
|
|
2887
|
+
average_heart_rate REAL,
|
|
2888
|
+
average_hrv REAL,
|
|
2889
|
+
awake_time INTEGER,
|
|
2890
|
+
bedtime_end TEXT,
|
|
2891
|
+
bedtime_start TEXT,
|
|
2892
|
+
deep_sleep_duration INTEGER,
|
|
2893
|
+
efficiency INTEGER,
|
|
2894
|
+
latency INTEGER,
|
|
2895
|
+
light_sleep_duration INTEGER,
|
|
2896
|
+
lowest_heart_rate INTEGER,
|
|
2897
|
+
period INTEGER,
|
|
2898
|
+
rem_sleep_duration INTEGER,
|
|
2899
|
+
restless_periods INTEGER,
|
|
2900
|
+
time_in_bed INTEGER,
|
|
2901
|
+
total_sleep_duration INTEGER,
|
|
2902
|
+
type TEXT
|
|
2903
|
+
);
|
|
2904
|
+
`
|
|
2905
|
+
},
|
|
2906
|
+
{
|
|
2907
|
+
version: 2,
|
|
2908
|
+
sql: `
|
|
2909
|
+
CREATE VIEW IF NOT EXISTS v_weekly_sleep AS
|
|
2910
|
+
SELECT strftime('%Y-W%W', day) as week, ROUND(AVG(score),1) as avg_score, COUNT(*) as days
|
|
2911
|
+
FROM daily_sleep WHERE score IS NOT NULL GROUP BY week ORDER BY week DESC;
|
|
2912
|
+
|
|
2913
|
+
CREATE VIEW IF NOT EXISTS v_weekly_readiness AS
|
|
2914
|
+
SELECT strftime('%Y-W%W', day) as week, ROUND(AVG(score),1) as avg_score,
|
|
2915
|
+
ROUND(AVG(temperature_deviation),2) as avg_temp_dev, COUNT(*) as days
|
|
2916
|
+
FROM daily_readiness WHERE score IS NOT NULL GROUP BY week ORDER BY week DESC;
|
|
2917
|
+
|
|
2918
|
+
CREATE VIEW IF NOT EXISTS v_weekly_activity AS
|
|
2919
|
+
SELECT strftime('%Y-W%W', day) as week, ROUND(AVG(score),1) as avg_score,
|
|
2920
|
+
SUM(steps) as total_steps, SUM(active_calories) as total_active_cal, COUNT(*) as days
|
|
2921
|
+
FROM daily_activity WHERE score IS NOT NULL GROUP BY week ORDER BY week DESC;
|
|
2922
|
+
|
|
2923
|
+
CREATE VIEW IF NOT EXISTS v_sleep_detail AS
|
|
2924
|
+
SELECT day, ROUND(total_sleep_duration/3600.0,1) as sleep_hours,
|
|
2925
|
+
ROUND(deep_sleep_duration/3600.0,1) as deep_hours,
|
|
2926
|
+
ROUND(rem_sleep_duration/3600.0,1) as rem_hours,
|
|
2927
|
+
average_hrv, average_heart_rate as avg_hr, lowest_heart_rate as lowest_hr, efficiency
|
|
2928
|
+
FROM sleep_model ORDER BY day DESC;
|
|
2929
|
+
`
|
|
2930
|
+
}
|
|
2931
|
+
];
|
|
2932
|
+
|
|
2933
|
+
// src/db/database.ts
|
|
2934
|
+
var DB_OPTIONS = {
|
|
2935
|
+
envVar: "OURA_DB_PATH",
|
|
2936
|
+
defaultDir: ".oura-cli",
|
|
2937
|
+
defaultFile: "oura.db"
|
|
2938
|
+
};
|
|
2939
|
+
function getDbPath2(options = {}) {
|
|
2940
|
+
return getDbPath({ ...DB_OPTIONS, ...options });
|
|
2941
|
+
}
|
|
2942
|
+
function openDatabase2(options = {}) {
|
|
2943
|
+
return openDatabase({ ...DB_OPTIONS, ...options });
|
|
2944
|
+
}
|
|
2945
|
+
function ensureSchema2(db) {
|
|
2946
|
+
ensureSchema(db, MIGRATIONS);
|
|
2947
|
+
}
|
|
2948
|
+
|
|
2949
|
+
// src/db/import.ts
|
|
2950
|
+
async function importDaily(db, client, log) {
|
|
2951
|
+
const _log = log ?? (() => {});
|
|
2952
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
2953
|
+
const lastDates = [];
|
|
2954
|
+
for (const tbl of ["daily_sleep", "daily_readiness", "daily_activity"]) {
|
|
2955
|
+
const row = db.query(`SELECT MAX(day) as d FROM ${tbl}`).get();
|
|
2956
|
+
if (row?.d)
|
|
2957
|
+
lastDates.push(row.d);
|
|
2958
|
+
}
|
|
2959
|
+
const startDate = lastDates.length > 0 ? lastDates.sort()[0] : new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10);
|
|
2960
|
+
_log(`Syncing from ${startDate} to ${today}`);
|
|
2961
|
+
const counts = {};
|
|
2962
|
+
const sleepData = await client.fetch("daily_sleep", startDate, today);
|
|
2963
|
+
const insertSleep = db.query("INSERT OR REPLACE INTO daily_sleep VALUES (?,?,?,?,?)");
|
|
2964
|
+
for (const s of sleepData) {
|
|
2965
|
+
insertSleep.run(s.id, s.day, s.score, JSON.stringify(s.contributors), s.timestamp);
|
|
2966
|
+
_log(` + sleep ${s.day}`);
|
|
2967
|
+
}
|
|
2968
|
+
counts.daily_sleep = sleepData.length;
|
|
2969
|
+
const readinessData = await client.fetch("daily_readiness", startDate, today);
|
|
2970
|
+
const insertReadiness = db.query("INSERT OR REPLACE INTO daily_readiness VALUES (?,?,?,?,?,?,?)");
|
|
2971
|
+
for (const r of readinessData) {
|
|
2972
|
+
insertReadiness.run(r.id, r.day, r.score, JSON.stringify(r.contributors), r.temperature_deviation, r.temperature_trend_deviation, r.timestamp);
|
|
2973
|
+
_log(` + readiness ${r.day}`);
|
|
2974
|
+
}
|
|
2975
|
+
counts.daily_readiness = readinessData.length;
|
|
2976
|
+
const activityData = await client.fetch("daily_activity", startDate, today);
|
|
2977
|
+
const insertActivity = db.query("INSERT OR REPLACE INTO daily_activity VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
|
|
2978
|
+
for (const a of activityData) {
|
|
2979
|
+
insertActivity.run(a.id, a.day, a.score, a.active_calories, a.steps, a.equivalent_walking_distance, a.high_activity_time, a.medium_activity_time, a.low_activity_time, a.sedentary_time, a.total_calories, a.target_calories, JSON.stringify(a.contributors), a.timestamp);
|
|
2980
|
+
_log(` + activity ${a.day}`);
|
|
2981
|
+
}
|
|
2982
|
+
counts.daily_activity = activityData.length;
|
|
2983
|
+
const hrData = await client.fetch("heartrate", today, today);
|
|
2984
|
+
const insertHr = db.query("INSERT OR IGNORE INTO heartrate VALUES (?,?,?,?)");
|
|
2985
|
+
for (const h of hrData) {
|
|
2986
|
+
const day = h.timestamp.slice(0, 10);
|
|
2987
|
+
insertHr.run(h.timestamp, h.bpm, h.source, day);
|
|
2988
|
+
}
|
|
2989
|
+
counts.heartrate = hrData.length;
|
|
2990
|
+
if (hrData.length > 0)
|
|
2991
|
+
_log(` + heartrate ${hrData.length} records`);
|
|
2992
|
+
const spo2Data = await client.fetch("daily_spo2", startDate, today);
|
|
2993
|
+
const insertSpo2 = db.query("INSERT OR REPLACE INTO daily_spo2 VALUES (?,?,?,?)");
|
|
2994
|
+
for (const s of spo2Data) {
|
|
2995
|
+
const avg = s.spo2_percentage?.average ?? null;
|
|
2996
|
+
insertSpo2.run(s.id, s.day, avg, s.breathing_disturbance_index);
|
|
2997
|
+
_log(` + spo2 ${s.day}`);
|
|
2998
|
+
}
|
|
2999
|
+
counts.daily_spo2 = spo2Data.length;
|
|
3000
|
+
const stressData = await client.fetch("daily_stress", startDate, today);
|
|
3001
|
+
const insertStress = db.query("INSERT OR REPLACE INTO daily_stress VALUES (?,?,?,?,?)");
|
|
3002
|
+
for (const s of stressData) {
|
|
3003
|
+
insertStress.run(s.id, s.day, s.day_summary, s.recovery_high, s.stress_high);
|
|
3004
|
+
_log(` + stress ${s.day}`);
|
|
3005
|
+
}
|
|
3006
|
+
counts.daily_stress = stressData.length;
|
|
3007
|
+
const workoutData = await client.fetch("workout", startDate, today);
|
|
3008
|
+
const insertWorkout = db.query("INSERT OR REPLACE INTO workouts VALUES (?,?,?,?,?,?,?,?,?,?)");
|
|
3009
|
+
for (const w of workoutData) {
|
|
3010
|
+
insertWorkout.run(w.id, w.day, w.activity, w.calories, w.distance, w.start_datetime, w.end_datetime, w.intensity, w.label ?? "", w.source);
|
|
3011
|
+
_log(` + workout ${w.day} ${w.activity}`);
|
|
3012
|
+
}
|
|
3013
|
+
counts.workouts = workoutData.length;
|
|
3014
|
+
const sleepPeriods = await client.fetch("sleep", startDate, today);
|
|
3015
|
+
const insertSleepModel = db.query(`INSERT OR REPLACE INTO sleep_model VALUES (${Array(19).fill("?").join(",")})`);
|
|
3016
|
+
for (const sp of sleepPeriods) {
|
|
3017
|
+
insertSleepModel.run(sp.id, sp.day, sp.average_breath, sp.average_heart_rate, sp.average_hrv, sp.awake_time, sp.bedtime_end, sp.bedtime_start, sp.deep_sleep_duration, sp.efficiency, sp.latency, sp.light_sleep_duration, sp.lowest_heart_rate, sp.period, sp.rem_sleep_duration, sp.restless_periods, sp.time_in_bed, sp.total_sleep_duration, sp.type);
|
|
3018
|
+
_log(` + sleep_period ${sp.day} (${sp.type})`);
|
|
3019
|
+
}
|
|
3020
|
+
counts.sleep_model = sleepPeriods.length;
|
|
3021
|
+
const cvData = await client.fetch("daily_cardiovascular_age", startDate, today);
|
|
3022
|
+
const insertCv = db.query("INSERT OR REPLACE INTO cardiovascular_age VALUES (?,?,?)");
|
|
3023
|
+
for (const c of cvData) {
|
|
3024
|
+
insertCv.run(c.id, c.day, c.vascular_age);
|
|
3025
|
+
_log(` + cardiovascular_age ${c.day}`);
|
|
3026
|
+
}
|
|
3027
|
+
counts.cardiovascular_age = cvData.length;
|
|
3028
|
+
_log("Import complete.");
|
|
3029
|
+
return { startDate, endDate: today, counts };
|
|
3030
|
+
}
|
|
3031
|
+
|
|
3032
|
+
// src/db/csv-import.ts
|
|
3033
|
+
import { readFileSync as readFileSync2, existsSync } from "fs";
|
|
3034
|
+
import { join } from "path";
|
|
3035
|
+
var CSV_DIR = join(process.env.HOME ?? "", "Documents/OpenClaw/projects/oura-ring/data/App Data");
|
|
3036
|
+
function parseCSV(filename) {
|
|
3037
|
+
const path = join(CSV_DIR, filename);
|
|
3038
|
+
if (!existsSync(path))
|
|
3039
|
+
return [];
|
|
3040
|
+
const text = readFileSync2(path, "utf-8");
|
|
3041
|
+
const lines = text.split(`
|
|
3042
|
+
`).filter((l) => l.trim());
|
|
3043
|
+
if (lines.length < 2)
|
|
3044
|
+
return [];
|
|
3045
|
+
const headers = lines[0].split(";");
|
|
3046
|
+
return lines.slice(1).map((line) => {
|
|
3047
|
+
const vals = line.split(";");
|
|
3048
|
+
const row = {};
|
|
3049
|
+
headers.forEach((h, i) => {
|
|
3050
|
+
row[h] = vals[i] ?? "";
|
|
3051
|
+
});
|
|
3052
|
+
return row;
|
|
3053
|
+
});
|
|
3054
|
+
}
|
|
3055
|
+
function num(v) {
|
|
3056
|
+
if (!v || v === "")
|
|
3057
|
+
return null;
|
|
3058
|
+
const n = Number(v);
|
|
3059
|
+
return isNaN(n) ? null : n;
|
|
3060
|
+
}
|
|
3061
|
+
function str(v) {
|
|
3062
|
+
return v && v !== "" ? v : null;
|
|
3063
|
+
}
|
|
3064
|
+
function importFromCSV(db, log) {
|
|
3065
|
+
if (!existsSync(CSV_DIR)) {
|
|
3066
|
+
throw new Error(`CSV directory not found: ${CSV_DIR}`);
|
|
3067
|
+
}
|
|
3068
|
+
const sleep = parseCSV("dailysleep.csv");
|
|
3069
|
+
const insertSleep = db.query("INSERT OR REPLACE INTO daily_sleep VALUES (?,?,?,?,?)");
|
|
3070
|
+
const sleepTx = db.transaction(() => {
|
|
3071
|
+
for (const r of sleep)
|
|
3072
|
+
insertSleep.run(r.id, r.day, num(r.score), str(r.contributors), str(r.timestamp));
|
|
3073
|
+
});
|
|
3074
|
+
sleepTx();
|
|
3075
|
+
log(`daily_sleep: ${sleep.length} rows`);
|
|
3076
|
+
const readiness = parseCSV("dailyreadiness.csv");
|
|
3077
|
+
const insertReadiness = db.query("INSERT OR REPLACE INTO daily_readiness VALUES (?,?,?,?,?,?,?)");
|
|
3078
|
+
const readinessTx = db.transaction(() => {
|
|
3079
|
+
for (const r of readiness)
|
|
3080
|
+
insertReadiness.run(r.id, r.day, num(r.score), str(r.contributors), num(r.temperature_deviation), num(r.temperature_trend_deviation), str(r.timestamp));
|
|
3081
|
+
});
|
|
3082
|
+
readinessTx();
|
|
3083
|
+
log(`daily_readiness: ${readiness.length} rows`);
|
|
3084
|
+
const activity = parseCSV("dailyactivity.csv");
|
|
3085
|
+
const insertActivity = db.query("INSERT OR REPLACE INTO daily_activity VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
|
|
3086
|
+
const activityTx = db.transaction(() => {
|
|
3087
|
+
for (const r of activity)
|
|
3088
|
+
insertActivity.run(r.id, r.day, num(r.score), num(r.active_calories), num(r.steps), num(r.equivalent_walking_distance), num(r.high_activity_time), num(r.medium_activity_time), num(r.low_activity_time), num(r.sedentary_time), num(r.total_calories), num(r.target_calories), str(r.contributors), str(r.timestamp));
|
|
3089
|
+
});
|
|
3090
|
+
activityTx();
|
|
3091
|
+
log(`daily_activity: ${activity.length} rows`);
|
|
3092
|
+
const spo2 = parseCSV("dailyspo2.csv");
|
|
3093
|
+
const insertSpo2 = db.query("INSERT OR REPLACE INTO daily_spo2 VALUES (?,?,?,?)");
|
|
3094
|
+
const spo2Tx = db.transaction(() => {
|
|
3095
|
+
for (const r of spo2) {
|
|
3096
|
+
let avg = null;
|
|
3097
|
+
try {
|
|
3098
|
+
const parsed = JSON.parse(r.spo2_percentage);
|
|
3099
|
+
avg = parsed?.average ?? null;
|
|
3100
|
+
} catch {}
|
|
3101
|
+
insertSpo2.run(r.id, r.day, avg, num(r.breathing_disturbance_index));
|
|
3102
|
+
}
|
|
3103
|
+
});
|
|
3104
|
+
spo2Tx();
|
|
3105
|
+
log(`daily_spo2: ${spo2.length} rows`);
|
|
3106
|
+
const stress = parseCSV("dailystress.csv");
|
|
3107
|
+
const insertStress = db.query("INSERT OR REPLACE INTO daily_stress VALUES (?,?,?,?,?)");
|
|
3108
|
+
const stressTx = db.transaction(() => {
|
|
3109
|
+
for (const r of stress)
|
|
3110
|
+
insertStress.run(r.id, r.day, str(r.day_summary), num(r.recovery_high), num(r.stress_high));
|
|
3111
|
+
});
|
|
3112
|
+
stressTx();
|
|
3113
|
+
log(`daily_stress: ${stress.length} rows`);
|
|
3114
|
+
const hr = parseCSV("heartrate.csv");
|
|
3115
|
+
const insertHr = db.query("INSERT OR IGNORE INTO heartrate VALUES (?,?,?,?)");
|
|
3116
|
+
const hrTx = db.transaction(() => {
|
|
3117
|
+
for (const r of hr) {
|
|
3118
|
+
const day = r.timestamp?.slice(0, 10) ?? null;
|
|
3119
|
+
insertHr.run(r.timestamp, num(r.bpm), str(r.source), day);
|
|
3120
|
+
}
|
|
3121
|
+
});
|
|
3122
|
+
hrTx();
|
|
3123
|
+
log(`heartrate: ${hr.length} rows`);
|
|
3124
|
+
const sleepModel = parseCSV("sleepmodel.csv");
|
|
3125
|
+
const insertSM = db.query("INSERT OR REPLACE INTO sleep_model VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
|
|
3126
|
+
const smTx = db.transaction(() => {
|
|
3127
|
+
for (const r of sleepModel)
|
|
3128
|
+
insertSM.run(r.id, r.day, num(r.average_breath), num(r.average_heart_rate), num(r.average_hrv), num(r.awake_time), str(r.bedtime_end), str(r.bedtime_start), num(r.deep_sleep_duration), num(r.efficiency), num(r.latency), num(r.light_sleep_duration), num(r.lowest_heart_rate), num(r.period), num(r.rem_sleep_duration), num(r.restless_periods), num(r.time_in_bed), num(r.total_sleep_duration), str(r.type));
|
|
3129
|
+
});
|
|
3130
|
+
smTx();
|
|
3131
|
+
log(`sleep_model: ${sleepModel.length} rows`);
|
|
3132
|
+
const vo2 = parseCSV("vo2max.csv");
|
|
3133
|
+
const insertVo2 = db.query("INSERT OR REPLACE INTO vo2max VALUES (?,?,?,?)");
|
|
3134
|
+
const vo2Tx = db.transaction(() => {
|
|
3135
|
+
for (const r of vo2)
|
|
3136
|
+
insertVo2.run(r.id, r.day, num(r.vo2_max), str(r.timestamp));
|
|
3137
|
+
});
|
|
3138
|
+
vo2Tx();
|
|
3139
|
+
log(`vo2max: ${vo2.length} rows`);
|
|
3140
|
+
const cv = parseCSV("dailycardiovascularage.csv");
|
|
3141
|
+
const insertCv = db.query("INSERT OR REPLACE INTO cardiovascular_age VALUES (?,?,?)");
|
|
3142
|
+
const cvTx = db.transaction(() => {
|
|
3143
|
+
for (const r of cv)
|
|
3144
|
+
insertCv.run(r.id, r.day, num(r.vascular_age));
|
|
3145
|
+
});
|
|
3146
|
+
cvTx();
|
|
3147
|
+
log(`cardiovascular_age: ${cv.length} rows`);
|
|
3148
|
+
const workouts = parseCSV("workout.csv");
|
|
3149
|
+
const insertW = db.query("INSERT OR REPLACE INTO workouts VALUES (?,?,?,?,?,?,?,?,?,?)");
|
|
3150
|
+
const wTx = db.transaction(() => {
|
|
3151
|
+
for (const r of workouts)
|
|
3152
|
+
insertW.run(r.id, r.day, str(r.activity), num(r.calories), num(r.distance), str(r.start_datetime), str(r.end_datetime), str(r.intensity), str(r.label), str(r.source));
|
|
3153
|
+
});
|
|
3154
|
+
wTx();
|
|
3155
|
+
log(`workouts: ${workouts.length} rows`);
|
|
3156
|
+
log("CSV import complete.");
|
|
3157
|
+
}
|
|
3158
|
+
|
|
3159
|
+
// src/db/queries.ts
|
|
3160
|
+
function getDaySummary(db, day) {
|
|
3161
|
+
const sl = db.query("SELECT score FROM daily_sleep WHERE day=?").get(day);
|
|
3162
|
+
const rd = db.query("SELECT score, temperature_deviation FROM daily_readiness WHERE day=?").get(day);
|
|
3163
|
+
const ac = db.query("SELECT score, steps FROM daily_activity WHERE day=?").get(day);
|
|
3164
|
+
const st = db.query("SELECT day_summary FROM daily_stress WHERE day=?").get(day);
|
|
3165
|
+
const sp = db.query("SELECT spo2_average FROM daily_spo2 WHERE day=?").get(day);
|
|
3166
|
+
const sm = db.query(`SELECT total_sleep_duration, deep_sleep_duration, rem_sleep_duration, average_hrv, lowest_heart_rate, efficiency FROM sleep_model WHERE day=? AND type='long_sleep'`).get(day);
|
|
3167
|
+
return {
|
|
3168
|
+
day,
|
|
3169
|
+
sleep_score: sl?.score ?? null,
|
|
3170
|
+
readiness_score: rd?.score ?? null,
|
|
3171
|
+
activity_score: ac?.score ?? null,
|
|
3172
|
+
steps: ac?.steps ?? null,
|
|
3173
|
+
stress: st?.day_summary ?? null,
|
|
3174
|
+
spo2: sp?.spo2_average ?? null,
|
|
3175
|
+
temp_deviation: rd?.temperature_deviation ?? null,
|
|
3176
|
+
sleep_hours: sm?.total_sleep_duration ? +(sm.total_sleep_duration / 3600).toFixed(1) : null,
|
|
3177
|
+
deep_hours: sm?.deep_sleep_duration ? +(sm.deep_sleep_duration / 3600).toFixed(1) : null,
|
|
3178
|
+
rem_hours: sm?.rem_sleep_duration ? +(sm.rem_sleep_duration / 3600).toFixed(1) : null,
|
|
3179
|
+
avg_hrv: sm?.average_hrv ?? null,
|
|
3180
|
+
lowest_hr: sm?.lowest_heart_rate ?? null,
|
|
3181
|
+
efficiency: sm?.efficiency ?? null
|
|
3182
|
+
};
|
|
3183
|
+
}
|
|
3184
|
+
function getTrends(db, days) {
|
|
3185
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
3186
|
+
const start = new Date(Date.now() - days * 86400000).toISOString().slice(0, 10);
|
|
3187
|
+
const results = [];
|
|
3188
|
+
const metrics = [
|
|
3189
|
+
["Sleep Score", "daily_sleep", "score"],
|
|
3190
|
+
["Readiness", "daily_readiness", "score"],
|
|
3191
|
+
["Activity", "daily_activity", "score"],
|
|
3192
|
+
["Steps", "daily_activity", "steps"],
|
|
3193
|
+
["Active Cal", "daily_activity", "active_calories"]
|
|
3194
|
+
];
|
|
3195
|
+
for (const [label, table, col] of metrics) {
|
|
3196
|
+
const row = db.query(`SELECT AVG(${col}) as avg, MIN(${col}) as min, MAX(${col}) as max, COUNT(${col}) as count FROM ${table} WHERE day BETWEEN ? AND ?`).get(start, today);
|
|
3197
|
+
if (row.count > 0 && row.avg !== null) {
|
|
3198
|
+
results.push({ label, avg: +row.avg.toFixed(0), min: row.min, max: row.max, count: row.count });
|
|
3199
|
+
}
|
|
3200
|
+
}
|
|
3201
|
+
const sp = db.query("SELECT AVG(spo2_average) as avg, MIN(spo2_average) as min, MAX(spo2_average) as max, COUNT(*) as count FROM daily_spo2 WHERE day BETWEEN ? AND ?").get(start, today);
|
|
3202
|
+
if (sp.count > 0 && sp.avg !== null) {
|
|
3203
|
+
results.push({ label: "SpO2", avg: +sp.avg.toFixed(1), min: +sp.min.toFixed(1), max: +sp.max.toFixed(1), count: sp.count });
|
|
3204
|
+
}
|
|
3205
|
+
return results;
|
|
3206
|
+
}
|
|
3207
|
+
function getStats(db) {
|
|
3208
|
+
const tableNames = [
|
|
3209
|
+
"daily_sleep",
|
|
3210
|
+
"daily_readiness",
|
|
3211
|
+
"daily_activity",
|
|
3212
|
+
"daily_spo2",
|
|
3213
|
+
"daily_stress",
|
|
3214
|
+
"heartrate",
|
|
3215
|
+
"vo2max",
|
|
3216
|
+
"cardiovascular_age",
|
|
3217
|
+
"workouts",
|
|
3218
|
+
"sleep_model"
|
|
3219
|
+
];
|
|
3220
|
+
const tables = tableNames.map((table) => {
|
|
3221
|
+
const row = db.query(`SELECT COUNT(*) as cnt FROM ${table}`).get();
|
|
3222
|
+
return { table, rows: row.cnt };
|
|
3223
|
+
});
|
|
3224
|
+
const range = db.query("SELECT MIN(day) as first, MAX(day) as last FROM daily_sleep").get();
|
|
3225
|
+
const trends = getTrends(db, 99999);
|
|
3226
|
+
const mostSteps = db.query("SELECT day, steps FROM daily_activity WHERE steps IS NOT NULL ORDER BY steps DESC LIMIT 1").get();
|
|
3227
|
+
const bestSleep = db.query("SELECT day, score FROM daily_sleep WHERE score IS NOT NULL ORDER BY score DESC LIMIT 1").get();
|
|
3228
|
+
return {
|
|
3229
|
+
tables,
|
|
3230
|
+
dateRange: range,
|
|
3231
|
+
trends,
|
|
3232
|
+
records: {
|
|
3233
|
+
mostSteps: mostSteps ?? null,
|
|
3234
|
+
bestSleep: bestSleep ?? null
|
|
3235
|
+
}
|
|
3236
|
+
};
|
|
3237
|
+
}
|
|
3238
|
+
|
|
3239
|
+
// src/format.ts
|
|
3240
|
+
function scoreColor(score) {
|
|
3241
|
+
if (score === null)
|
|
3242
|
+
return source_default.gray("\u2014");
|
|
3243
|
+
if (score >= 85)
|
|
3244
|
+
return source_default.green(String(score));
|
|
3245
|
+
if (score >= 70)
|
|
3246
|
+
return source_default.yellow(String(score));
|
|
3247
|
+
return source_default.red(String(score));
|
|
3248
|
+
}
|
|
3249
|
+
function fmtHours(h) {
|
|
3250
|
+
if (h === null)
|
|
3251
|
+
return source_default.gray("\u2014");
|
|
3252
|
+
return `${h}h`;
|
|
3253
|
+
}
|
|
3254
|
+
function formatDaySummary(summary, format) {
|
|
3255
|
+
if (format === "json")
|
|
3256
|
+
return JSON.stringify(summary, null, 2);
|
|
3257
|
+
const lines = [
|
|
3258
|
+
"",
|
|
3259
|
+
source_default.bold(` ${summary.day}`),
|
|
3260
|
+
source_default.gray("\u2500".repeat(50)),
|
|
3261
|
+
` Sleep: ${scoreColor(summary.sleep_score)} Readiness: ${scoreColor(summary.readiness_score)} Activity: ${scoreColor(summary.activity_score)}`,
|
|
3262
|
+
` Steps: ${summary.steps ?? source_default.gray("\u2014")}`
|
|
3263
|
+
];
|
|
3264
|
+
if (summary.spo2 !== null)
|
|
3265
|
+
lines.push(` SpO2: ${summary.spo2}%`);
|
|
3266
|
+
if (summary.temp_deviation !== null) {
|
|
3267
|
+
const sign = summary.temp_deviation >= 0 ? "+" : "";
|
|
3268
|
+
lines.push(` Temp: ${sign}${summary.temp_deviation}\xB0C`);
|
|
3269
|
+
}
|
|
3270
|
+
if (summary.stress)
|
|
3271
|
+
lines.push(` Stress: ${summary.stress}`);
|
|
3272
|
+
if (summary.sleep_hours !== null) {
|
|
3273
|
+
lines.push("");
|
|
3274
|
+
lines.push(` Sleep: ${fmtHours(summary.sleep_hours)} total | ${fmtHours(summary.deep_hours)} deep | ${fmtHours(summary.rem_hours)} REM`);
|
|
3275
|
+
lines.push(` HRV: ${summary.avg_hrv ?? "\u2014"} Lowest HR: ${summary.lowest_hr ?? "\u2014"} Efficiency: ${summary.efficiency ?? "\u2014"}%`);
|
|
3276
|
+
}
|
|
3277
|
+
return lines.join(`
|
|
3278
|
+
`);
|
|
3279
|
+
}
|
|
3280
|
+
function formatWeekTable(days, format) {
|
|
3281
|
+
if (format === "json")
|
|
3282
|
+
return JSON.stringify(days, null, 2);
|
|
3283
|
+
const header = `${"Day".padEnd(12)} ${"Sleep".padStart(6)} ${"Ready".padStart(6)} ${"Activity".padStart(9)} ${"Steps".padStart(7)} ${"Stress".padEnd(10)}`;
|
|
3284
|
+
const sep = source_default.gray("\u2500".repeat(56));
|
|
3285
|
+
const rows = days.map((d) => `${d.day.padEnd(12)} ${scoreColor(d.sleep_score).padStart(6)} ${scoreColor(d.readiness_score).padStart(6)} ` + `${scoreColor(d.activity_score).padStart(9)} ${String(d.steps ?? "\u2014").padStart(7)} ${(d.stress ?? "\u2014").padEnd(10)}`);
|
|
3286
|
+
return [`
|
|
3287
|
+
Last 7 Days`, sep, ` ${header}`, sep, ...rows.map((r) => ` ${r}`)].join(`
|
|
3288
|
+
`);
|
|
3289
|
+
}
|
|
3290
|
+
function formatTrends(trends, days, format) {
|
|
3291
|
+
if (format === "json")
|
|
3292
|
+
return JSON.stringify(trends, null, 2);
|
|
3293
|
+
const lines = [
|
|
3294
|
+
"",
|
|
3295
|
+
source_default.bold(` Trends: last ${days} days`),
|
|
3296
|
+
source_default.gray("\u2500".repeat(50))
|
|
3297
|
+
];
|
|
3298
|
+
for (const t of trends) {
|
|
3299
|
+
lines.push(` ${t.label.padEnd(15)} avg: ${String(t.avg).padStart(5)} min: ${String(t.min).padStart(5)} max: ${String(t.max).padStart(5)} (${t.count} days)`);
|
|
3300
|
+
}
|
|
3301
|
+
return lines.join(`
|
|
3302
|
+
`);
|
|
3303
|
+
}
|
|
3304
|
+
function formatStats(stats, format) {
|
|
3305
|
+
if (format === "json")
|
|
3306
|
+
return JSON.stringify(stats, null, 2);
|
|
3307
|
+
const lines = [
|
|
3308
|
+
"",
|
|
3309
|
+
source_default.bold(" Database Statistics"),
|
|
3310
|
+
source_default.gray("\u2550".repeat(50))
|
|
3311
|
+
];
|
|
3312
|
+
for (const t of stats.tables) {
|
|
3313
|
+
lines.push(` ${t.table.padEnd(22)} ${String(t.rows).padStart(8)} rows`);
|
|
3314
|
+
}
|
|
3315
|
+
if (stats.dateRange.first) {
|
|
3316
|
+
lines.push(`
|
|
3317
|
+
Date range: ${stats.dateRange.first} \u2192 ${stats.dateRange.last}`);
|
|
3318
|
+
}
|
|
3319
|
+
for (const t of stats.trends) {
|
|
3320
|
+
lines.push(` ${t.label.padEnd(15)} avg: ${String(t.avg).padStart(5)} min: ${String(t.min).padStart(5)} max: ${String(t.max).padStart(5)}`);
|
|
3321
|
+
}
|
|
3322
|
+
if (stats.records.mostSteps) {
|
|
3323
|
+
lines.push(`
|
|
3324
|
+
Most steps: ${stats.records.mostSteps.steps} on ${stats.records.mostSteps.day}`);
|
|
3325
|
+
}
|
|
3326
|
+
if (stats.records.bestSleep) {
|
|
3327
|
+
lines.push(` Best sleep: ${stats.records.bestSleep.score} on ${stats.records.bestSleep.day}`);
|
|
3328
|
+
}
|
|
3329
|
+
return lines.join(`
|
|
3330
|
+
`);
|
|
3331
|
+
}
|
|
3332
|
+
|
|
3333
|
+
// src/lib/format-resolve.ts
|
|
3334
|
+
function resolveFormat({ explicit, isTty }) {
|
|
3335
|
+
if (explicit === undefined)
|
|
3336
|
+
return isTty ? "table" : "json";
|
|
3337
|
+
if (explicit === "table" || explicit === "json")
|
|
3338
|
+
return explicit;
|
|
3339
|
+
throw new CliError("BAD_ARGS", `Unknown --format value: "${explicit}". Use "table" or "json".`);
|
|
3340
|
+
}
|
|
3341
|
+
|
|
3342
|
+
// src/commands/db.ts
|
|
3343
|
+
function dbCommand() {
|
|
3344
|
+
const cmd = new Command("db").description("Query and manage the local SQLite database");
|
|
3345
|
+
cmd.command("import").description("Sync new data from Oura API into local database").action(async (_, command) => {
|
|
3346
|
+
const opts = command.parent.parent.opts();
|
|
3347
|
+
const format = resolveFormat({ explicit: opts.format, isTty: process.stdout.isTTY === true });
|
|
3348
|
+
const dbPath = getDbPath2({ dbPath: opts.db });
|
|
3349
|
+
mkdirSync2(dirname(dbPath), { recursive: true });
|
|
3350
|
+
const db = openDatabase2({ dbPath: opts.db });
|
|
3351
|
+
ensureSchema2(db);
|
|
3352
|
+
const client = getClient(opts);
|
|
3353
|
+
const log = format === "table" ? console.log : undefined;
|
|
3354
|
+
const result = await importDaily(db, client, log);
|
|
3355
|
+
if (format === "json") {
|
|
3356
|
+
console.log(JSON.stringify(result, null, 2));
|
|
3357
|
+
}
|
|
3358
|
+
db.close();
|
|
3359
|
+
});
|
|
3360
|
+
cmd.command("today").description("Today's summary from local database").action((_, command) => {
|
|
3361
|
+
const opts = command.parent.parent.opts();
|
|
3362
|
+
const format = resolveFormat({ explicit: opts.format, isTty: process.stdout.isTTY === true });
|
|
3363
|
+
const db = openDatabase2({ dbPath: opts.db });
|
|
3364
|
+
ensureSchema2(db);
|
|
3365
|
+
const summary = getDaySummary(db, todayDate());
|
|
3366
|
+
console.log(formatDaySummary(summary, format));
|
|
3367
|
+
db.close();
|
|
3368
|
+
});
|
|
3369
|
+
cmd.command("date <day>").description("Summary for specific date from local database").action((day, _, command) => {
|
|
3370
|
+
const opts = command.parent.parent.opts();
|
|
3371
|
+
const format = resolveFormat({ explicit: opts.format, isTty: process.stdout.isTTY === true });
|
|
3372
|
+
const db = openDatabase2({ dbPath: opts.db });
|
|
3373
|
+
ensureSchema2(db);
|
|
3374
|
+
const summary = getDaySummary(db, day);
|
|
3375
|
+
console.log(formatDaySummary(summary, format));
|
|
3376
|
+
db.close();
|
|
3377
|
+
});
|
|
3378
|
+
cmd.command("week").description("Last 7 days from local database").action((_, command) => {
|
|
3379
|
+
const opts = command.parent.parent.opts();
|
|
3380
|
+
const format = resolveFormat({ explicit: opts.format, isTty: process.stdout.isTTY === true });
|
|
3381
|
+
const db = openDatabase2({ dbPath: opts.db });
|
|
3382
|
+
ensureSchema2(db);
|
|
3383
|
+
const days = [];
|
|
3384
|
+
for (let i = 6;i >= 0; i--) {
|
|
3385
|
+
const d = new Date(Date.now() - i * 86400000).toISOString().slice(0, 10);
|
|
3386
|
+
days.push(getDaySummary(db, d));
|
|
3387
|
+
}
|
|
3388
|
+
console.log(formatWeekTable(days, format));
|
|
3389
|
+
db.close();
|
|
3390
|
+
});
|
|
3391
|
+
cmd.command("trends [days]").description("Score and metric trends over N days (default: 30)").action((days, _, command) => {
|
|
3392
|
+
const opts = command.parent.parent.opts();
|
|
3393
|
+
const format = resolveFormat({ explicit: opts.format, isTty: process.stdout.isTTY === true });
|
|
3394
|
+
const n = days ? parseInt(days, 10) : 30;
|
|
3395
|
+
const db = openDatabase2({ dbPath: opts.db });
|
|
3396
|
+
ensureSchema2(db);
|
|
3397
|
+
const trends = getTrends(db, n);
|
|
3398
|
+
console.log(formatTrends(trends, n, format));
|
|
3399
|
+
db.close();
|
|
3400
|
+
});
|
|
3401
|
+
cmd.command("stats").description("Row counts, date range, and record highs from local database").action((_, command) => {
|
|
3402
|
+
const opts = command.parent.parent.opts();
|
|
3403
|
+
const format = resolveFormat({ explicit: opts.format, isTty: process.stdout.isTTY === true });
|
|
3404
|
+
const db = openDatabase2({ dbPath: opts.db });
|
|
3405
|
+
ensureSchema2(db);
|
|
3406
|
+
const stats = getStats(db);
|
|
3407
|
+
console.log(formatStats(stats, format));
|
|
3408
|
+
db.close();
|
|
3409
|
+
});
|
|
3410
|
+
cmd.command("reset").description("Destroy and rebuild database from exported CSV files").option("--force", "Confirm destructive reset").action((resetOpts, command) => {
|
|
3411
|
+
if (!resetOpts.force) {
|
|
3412
|
+
console.log(JSON.stringify({ error: "Use --force to confirm destructive reset." }));
|
|
3413
|
+
process.exit(1);
|
|
3414
|
+
}
|
|
3415
|
+
const opts = command.parent.parent.opts();
|
|
3416
|
+
const format = resolveFormat({ explicit: opts.format, isTty: process.stdout.isTTY === true });
|
|
3417
|
+
const dbPath = getDbPath2({ dbPath: opts.db });
|
|
3418
|
+
try {
|
|
3419
|
+
unlinkSync(dbPath);
|
|
3420
|
+
} catch {}
|
|
3421
|
+
try {
|
|
3422
|
+
unlinkSync(dbPath + "-wal");
|
|
3423
|
+
} catch {}
|
|
3424
|
+
try {
|
|
3425
|
+
unlinkSync(dbPath + "-shm");
|
|
3426
|
+
} catch {}
|
|
3427
|
+
const log = format === "table" ? console.log : undefined;
|
|
3428
|
+
log?.("Database deleted.");
|
|
3429
|
+
mkdirSync2(dirname(dbPath), { recursive: true });
|
|
3430
|
+
const db = openDatabase2({ dbPath: opts.db });
|
|
3431
|
+
ensureSchema2(db);
|
|
3432
|
+
importFromCSV(db, log ?? (() => {}));
|
|
3433
|
+
if (format === "json") {
|
|
3434
|
+
console.log(JSON.stringify({ status: "reset complete" }));
|
|
3435
|
+
}
|
|
3436
|
+
db.close();
|
|
3437
|
+
});
|
|
3438
|
+
return cmd;
|
|
3439
|
+
}
|
|
3440
|
+
|
|
3441
|
+
// src/commands/sync.ts
|
|
3442
|
+
import { mkdirSync as mkdirSync3 } from "fs";
|
|
3443
|
+
import { dirname as dirname2 } from "path";
|
|
3444
|
+
function syncCommand() {
|
|
3445
|
+
return new Command("sync").description("Import latest data from Oura API and return today's summary").action(async (_, command) => {
|
|
3446
|
+
const opts = command.parent.opts();
|
|
3447
|
+
const format = resolveFormat({ explicit: opts.format, isTty: process.stdout.isTTY === true });
|
|
3448
|
+
const dbPath = getDbPath2({ dbPath: opts.db });
|
|
3449
|
+
mkdirSync3(dirname2(dbPath), { recursive: true });
|
|
3450
|
+
const db = openDatabase2({ dbPath: opts.db });
|
|
3451
|
+
ensureSchema2(db);
|
|
3452
|
+
const client = getClient(opts);
|
|
3453
|
+
const log = format === "table" ? console.log : undefined;
|
|
3454
|
+
const importResult = await importDaily(db, client, log);
|
|
3455
|
+
const today = getDaySummary(db, todayDate());
|
|
3456
|
+
db.close();
|
|
3457
|
+
if (format === "json") {
|
|
3458
|
+
console.log(JSON.stringify({ import: importResult, today }, null, 2));
|
|
3459
|
+
} else {
|
|
3460
|
+
console.log(formatDaySummary(today, format));
|
|
3461
|
+
}
|
|
3462
|
+
});
|
|
3463
|
+
}
|
|
3464
|
+
|
|
3465
|
+
// src/db/report.ts
|
|
3466
|
+
function dayLabel(dateStr) {
|
|
3467
|
+
const d = new Date(dateStr + "T12:00:00Z");
|
|
3468
|
+
const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
3469
|
+
const day = days[d.getUTCDay()];
|
|
3470
|
+
const dd = String(d.getUTCDate()).padStart(2, "0");
|
|
3471
|
+
const mm = String(d.getUTCMonth() + 1).padStart(2, "0");
|
|
3472
|
+
return `${day} ${dd}/${mm}`;
|
|
3473
|
+
}
|
|
3474
|
+
function getWeeklyReport(db) {
|
|
3475
|
+
const today = new Date;
|
|
3476
|
+
const weekEnd = today.toISOString().slice(0, 10);
|
|
3477
|
+
const weekStartDate = new Date(today.getTime() - 6 * 86400000);
|
|
3478
|
+
const weekStart = weekStartDate.toISOString().slice(0, 10);
|
|
3479
|
+
const prevWeekEnd = new Date(today.getTime() - 7 * 86400000).toISOString().slice(0, 10);
|
|
3480
|
+
const prevWeekStart = new Date(today.getTime() - 13 * 86400000).toISOString().slice(0, 10);
|
|
3481
|
+
const days = [];
|
|
3482
|
+
for (let i = 6;i >= 0; i--) {
|
|
3483
|
+
const d = new Date(today.getTime() - i * 86400000).toISOString().slice(0, 10);
|
|
3484
|
+
const sl = db.query("SELECT score FROM daily_sleep WHERE day=?").get(d);
|
|
3485
|
+
const rd = db.query("SELECT score FROM daily_readiness WHERE day=?").get(d);
|
|
3486
|
+
const ac = db.query("SELECT score, steps FROM daily_activity WHERE day=?").get(d);
|
|
3487
|
+
days.push({
|
|
3488
|
+
day: d,
|
|
3489
|
+
dayLabel: dayLabel(d),
|
|
3490
|
+
sleep: sl?.score ?? null,
|
|
3491
|
+
readiness: rd?.score ?? null,
|
|
3492
|
+
activity: ac?.score ?? null,
|
|
3493
|
+
steps: ac?.steps ?? null
|
|
3494
|
+
});
|
|
3495
|
+
}
|
|
3496
|
+
const metrics = [
|
|
3497
|
+
["Sleep", "daily_sleep", "score", false],
|
|
3498
|
+
["Readiness", "daily_readiness", "score", false],
|
|
3499
|
+
["Activity", "daily_activity", "score", false],
|
|
3500
|
+
["Steps", "daily_activity", "steps", true]
|
|
3501
|
+
];
|
|
3502
|
+
const averages = [];
|
|
3503
|
+
for (const [label, table, col, isSteps] of metrics) {
|
|
3504
|
+
const curr = db.query(`SELECT AVG(${col}) as avg, MIN(${col}) as min, MAX(${col}) as max, COUNT(${col}) as cnt FROM ${table} WHERE day BETWEEN ? AND ?`).get(weekStart, weekEnd);
|
|
3505
|
+
const prev = db.query(`SELECT AVG(${col}) as avg FROM ${table} WHERE day BETWEEN ? AND ?`).get(prevWeekStart, prevWeekEnd);
|
|
3506
|
+
if (curr.cnt > 0 && curr.avg !== null) {
|
|
3507
|
+
const diff = prev.avg !== null ? curr.avg - prev.avg : null;
|
|
3508
|
+
averages.push({
|
|
3509
|
+
label,
|
|
3510
|
+
avg: curr.avg,
|
|
3511
|
+
min: curr.min,
|
|
3512
|
+
max: curr.max,
|
|
3513
|
+
prevAvg: prev.avg,
|
|
3514
|
+
diff,
|
|
3515
|
+
isSteps
|
|
3516
|
+
});
|
|
3517
|
+
}
|
|
3518
|
+
}
|
|
3519
|
+
const sp = db.query("SELECT AVG(spo2_average) as avg, MIN(spo2_average) as min, MAX(spo2_average) as max, COUNT(*) as cnt FROM daily_spo2 WHERE day BETWEEN ? AND ?").get(weekStart, weekEnd);
|
|
3520
|
+
const spo2 = sp.cnt > 0 && sp.avg !== null ? { avg: +sp.avg.toFixed(1), min: +sp.min.toFixed(1), max: +sp.max.toFixed(1) } : null;
|
|
3521
|
+
const lowSleep = db.query("SELECT day, score FROM daily_sleep WHERE day BETWEEN ? AND ? AND score < 70 ORDER BY score").all(weekStart, weekEnd).map((r) => ({ ...r, dayLabel: dayLabel(r.day) }));
|
|
3522
|
+
const lowReadiness = db.query("SELECT day, score FROM daily_readiness WHERE day BETWEEN ? AND ? AND score < 70 ORDER BY score").all(weekStart, weekEnd).map((r) => ({ ...r, dayLabel: dayLabel(r.day) }));
|
|
3523
|
+
const highActivity = db.query("SELECT day, score, steps FROM daily_activity WHERE day BETWEEN ? AND ? AND score >= 90 ORDER BY score DESC").all(weekStart, weekEnd).map((r) => ({ ...r, dayLabel: dayLabel(r.day) }));
|
|
3524
|
+
const sd = db.query(`SELECT AVG(total_sleep_duration) as totalSleep, AVG(deep_sleep_duration) as deepSleep,
|
|
3525
|
+
AVG(rem_sleep_duration) as remSleep, AVG(light_sleep_duration) as lightSleep,
|
|
3526
|
+
AVG(efficiency) as efficiency, AVG(average_hrv) as hrv, AVG(lowest_heart_rate) as lowestHr
|
|
3527
|
+
FROM sleep_model WHERE day BETWEEN ? AND ? AND type='long_sleep'`).get(weekStart, weekEnd);
|
|
3528
|
+
const sleepDetails = sd.totalSleep !== null ? sd : null;
|
|
3529
|
+
const recommendations = [];
|
|
3530
|
+
const avgSleep = db.query("SELECT AVG(score) as avg FROM daily_sleep WHERE day BETWEEN ? AND ?").get(weekStart, weekEnd);
|
|
3531
|
+
const avgReady = db.query("SELECT AVG(score) as avg FROM daily_readiness WHERE day BETWEEN ? AND ?").get(weekStart, weekEnd);
|
|
3532
|
+
const avgSteps = db.query("SELECT AVG(steps) as avg FROM daily_activity WHERE day BETWEEN ? AND ?").get(weekStart, weekEnd);
|
|
3533
|
+
if (avgSleep.avg !== null && avgSleep.avg < 75) {
|
|
3534
|
+
recommendations.push("sleep_low");
|
|
3535
|
+
} else if (avgSleep.avg !== null && avgSleep.avg >= 85) {
|
|
3536
|
+
recommendations.push("sleep_great");
|
|
3537
|
+
}
|
|
3538
|
+
if (avgReady.avg !== null && avgReady.avg < 70) {
|
|
3539
|
+
recommendations.push("readiness_low");
|
|
3540
|
+
} else if (avgReady.avg !== null && avgReady.avg >= 80) {
|
|
3541
|
+
recommendations.push("readiness_great");
|
|
3542
|
+
}
|
|
3543
|
+
if (avgSteps.avg !== null && avgSteps.avg < 8000) {
|
|
3544
|
+
recommendations.push("steps_low");
|
|
3545
|
+
} else if (avgSteps.avg !== null && avgSteps.avg >= 1e4) {
|
|
3546
|
+
recommendations.push("steps_great");
|
|
3547
|
+
}
|
|
3548
|
+
return { weekStart, weekEnd, days, averages, spo2, patterns: { lowSleep, lowReadiness, highActivity }, sleepDetails, recommendations };
|
|
3549
|
+
}
|
|
3550
|
+
|
|
3551
|
+
// src/format-report.ts
|
|
3552
|
+
function fmtSeconds(s) {
|
|
3553
|
+
if (s === null)
|
|
3554
|
+
return "\u2014";
|
|
3555
|
+
const h = Math.floor(s / 3600);
|
|
3556
|
+
const m = Math.floor(s % 3600 / 60);
|
|
3557
|
+
return h > 0 ? `${h}h ${m}m` : `${m}m`;
|
|
3558
|
+
}
|
|
3559
|
+
function fmtNumber(n, isSteps) {
|
|
3560
|
+
if (isSteps)
|
|
3561
|
+
return n.toLocaleString("en-US", { maximumFractionDigits: 0 });
|
|
3562
|
+
return n.toFixed(0);
|
|
3563
|
+
}
|
|
3564
|
+
var RECOMMENDATIONS = {
|
|
3565
|
+
sleep_low: "Sleep below average \u2014 try going to bed 30 min earlier.",
|
|
3566
|
+
sleep_great: "Excellent sleep! Keep it up.",
|
|
3567
|
+
readiness_low: "Low readiness \u2014 possible sleep debt. Prioritize recovery.",
|
|
3568
|
+
readiness_great: "Readiness is high! Body is ready for load.",
|
|
3569
|
+
steps_low: "Low movement \u2014 aim for 8-10k steps daily.",
|
|
3570
|
+
steps_great: "Great activity! Step goal achieved."
|
|
3571
|
+
};
|
|
3572
|
+
function formatWeeklyReport(data, format) {
|
|
3573
|
+
if (format === "json")
|
|
3574
|
+
return JSON.stringify(data, null, 2);
|
|
3575
|
+
const lines = [];
|
|
3576
|
+
lines.push("");
|
|
3577
|
+
lines.push(source_default.bold(" Oura Weekly Report"));
|
|
3578
|
+
lines.push(source_default.gray(` ${data.weekStart} \u2014 ${data.weekEnd}`));
|
|
3579
|
+
lines.push("");
|
|
3580
|
+
lines.push(source_default.bold(" Last 7 Days:"));
|
|
3581
|
+
lines.push(source_default.gray(" " + "\u2500".repeat(52)));
|
|
3582
|
+
lines.push(` ${"Day".padEnd(10)} ${"Sleep".padStart(6)} ${"Ready".padStart(6)} ${"Active".padStart(7)} ${"Steps".padStart(8)}`);
|
|
3583
|
+
lines.push(source_default.gray(" " + "\u2500".repeat(52)));
|
|
3584
|
+
for (const d of data.days) {
|
|
3585
|
+
const sleep = d.sleep !== null ? d.sleep >= 85 ? source_default.green(String(d.sleep)) : d.sleep >= 70 ? source_default.yellow(String(d.sleep)) : source_default.red(String(d.sleep)) : source_default.gray("\u2014");
|
|
3586
|
+
const ready = d.readiness !== null ? d.readiness >= 85 ? source_default.green(String(d.readiness)) : d.readiness >= 70 ? source_default.yellow(String(d.readiness)) : source_default.red(String(d.readiness)) : source_default.gray("\u2014");
|
|
3587
|
+
const active = d.activity !== null ? d.activity >= 85 ? source_default.green(String(d.activity)) : d.activity >= 70 ? source_default.yellow(String(d.activity)) : source_default.red(String(d.activity)) : source_default.gray("\u2014");
|
|
3588
|
+
const steps = d.steps !== null ? d.steps.toLocaleString() : source_default.gray("\u2014");
|
|
3589
|
+
lines.push(` ${d.dayLabel.padEnd(10)} ${sleep.padStart(6)} ${ready.padStart(6)} ${active.padStart(7)} ${steps.padStart(8)}`);
|
|
3590
|
+
}
|
|
3591
|
+
lines.push("");
|
|
3592
|
+
lines.push(source_default.bold(" Averages (this week vs previous):"));
|
|
3593
|
+
for (const a of data.averages) {
|
|
3594
|
+
const avgStr = fmtNumber(a.avg, a.isSteps);
|
|
3595
|
+
let changeStr = "";
|
|
3596
|
+
if (a.diff !== null) {
|
|
3597
|
+
const arrow = a.diff > 0 ? source_default.green("\u2191") : a.diff < 0 ? source_default.red("\u2193") : "\u2192";
|
|
3598
|
+
const diffStr = a.isSteps ? a.diff.toLocaleString("en-US", { maximumFractionDigits: 0 }) : a.diff.toFixed(0);
|
|
3599
|
+
changeStr = ` ${arrow} ${a.diff >= 0 ? "+" : ""}${diffStr}`;
|
|
3600
|
+
}
|
|
3601
|
+
lines.push(` ${a.label.padEnd(12)} ${source_default.bold(avgStr)}${changeStr} (min: ${fmtNumber(a.min, a.isSteps)}, max: ${fmtNumber(a.max, a.isSteps)})`);
|
|
3602
|
+
}
|
|
3603
|
+
if (data.spo2) {
|
|
3604
|
+
lines.push(` ${"SpO2".padEnd(12)} ${source_default.bold(String(data.spo2.avg) + "%")} (min: ${data.spo2.min}%, max: ${data.spo2.max}%)`);
|
|
3605
|
+
}
|
|
3606
|
+
lines.push("");
|
|
3607
|
+
if (data.patterns.lowSleep.length > 0 || data.patterns.lowReadiness.length > 0 || data.patterns.highActivity.length > 0) {
|
|
3608
|
+
lines.push(source_default.bold(" Patterns:"));
|
|
3609
|
+
for (const d of data.patterns.lowSleep) {
|
|
3610
|
+
lines.push(source_default.red(` \u25BC Low sleep: ${d.dayLabel} \u2014 ${d.score}`));
|
|
3611
|
+
}
|
|
3612
|
+
for (const d of data.patterns.lowReadiness) {
|
|
3613
|
+
lines.push(source_default.red(` \u25BC Low readiness: ${d.dayLabel} \u2014 ${d.score}`));
|
|
3614
|
+
}
|
|
3615
|
+
for (const d of data.patterns.highActivity) {
|
|
3616
|
+
const steps = d.steps !== null ? ` (${d.steps.toLocaleString()} steps)` : "";
|
|
3617
|
+
lines.push(source_default.green(` \u25B2 High activity: ${d.dayLabel} \u2014 ${d.score}${steps}`));
|
|
3618
|
+
}
|
|
3619
|
+
lines.push("");
|
|
3620
|
+
}
|
|
3621
|
+
if (data.sleepDetails) {
|
|
3622
|
+
const sd = data.sleepDetails;
|
|
3623
|
+
lines.push(source_default.bold(" Sleep Details (averages):"));
|
|
3624
|
+
lines.push(` Total: ${fmtSeconds(sd.totalSleep)} Deep: ${fmtSeconds(sd.deepSleep)} REM: ${fmtSeconds(sd.remSleep)} Light: ${fmtSeconds(sd.lightSleep)}`);
|
|
3625
|
+
lines.push(` Efficiency: ${sd.efficiency !== null ? sd.efficiency.toFixed(0) + "%" : "\u2014"} HRV: ${sd.hrv !== null ? sd.hrv.toFixed(0) : "\u2014"} Lowest HR: ${sd.lowestHr !== null ? sd.lowestHr.toFixed(0) : "\u2014"}`);
|
|
3626
|
+
lines.push("");
|
|
3627
|
+
}
|
|
3628
|
+
if (data.recommendations.length > 0) {
|
|
3629
|
+
lines.push(source_default.bold(" Recommendations:"));
|
|
3630
|
+
for (const key of data.recommendations) {
|
|
3631
|
+
lines.push(` \u2022 ${RECOMMENDATIONS[key] ?? key}`);
|
|
3632
|
+
}
|
|
3633
|
+
lines.push("");
|
|
3634
|
+
}
|
|
3635
|
+
return lines.join(`
|
|
3636
|
+
`);
|
|
3637
|
+
}
|
|
3638
|
+
|
|
3639
|
+
// src/commands/report.ts
|
|
3640
|
+
function reportCommand() {
|
|
3641
|
+
const cmd = new Command("report").description("Generate health reports from local data");
|
|
3642
|
+
cmd.command("weekly").description("Weekly health summary with trends and recommendations").action((_, command) => {
|
|
3643
|
+
const opts = command.parent.parent.opts();
|
|
3644
|
+
const format = resolveFormat({ explicit: opts.format, isTty: process.stdout.isTTY === true });
|
|
3645
|
+
const db = openDatabase2({ dbPath: opts.db });
|
|
3646
|
+
ensureSchema2(db);
|
|
3647
|
+
const data = getWeeklyReport(db);
|
|
3648
|
+
console.log(formatWeeklyReport(data, format));
|
|
3649
|
+
db.close();
|
|
3650
|
+
});
|
|
3651
|
+
return cmd;
|
|
3652
|
+
}
|
|
3653
|
+
|
|
3654
|
+
// src/commands/login.ts
|
|
3655
|
+
import { writeFileSync, chmodSync, mkdirSync as mkdirSync4 } from "fs";
|
|
3656
|
+
import { resolve as resolve3, dirname as dirname3 } from "path";
|
|
3657
|
+
import { homedir as homedir3 } from "os";
|
|
3658
|
+
import { createInterface } from "readline/promises";
|
|
3659
|
+
function writeToken(path, token) {
|
|
3660
|
+
const trimmed = token.trim();
|
|
3661
|
+
if (trimmed.length === 0) {
|
|
3662
|
+
throw new CliError("BAD_ARGS", "Token cannot be empty.");
|
|
3663
|
+
}
|
|
3664
|
+
mkdirSync4(dirname3(path), { recursive: true });
|
|
3665
|
+
writeFileSync(path, trimmed, { encoding: "utf-8" });
|
|
3666
|
+
if (process.platform !== "win32") {
|
|
3667
|
+
chmodSync(path, 384);
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3670
|
+
function loginCommand() {
|
|
3671
|
+
return new Command("login").description("Save an Oura Personal Access Token for future commands.").option("--token <pat>", "Pass token non-interactively (e.g. for scripts)").option("--path <file>", "Where to save the token (default: $OURA_TOKEN_PATH or ~/.oura-token)").action(async (opts) => {
|
|
3672
|
+
const target = opts.path ?? process.env.OURA_TOKEN_PATH ?? resolve3(homedir3(), ".oura-token");
|
|
3673
|
+
let token = opts.token;
|
|
3674
|
+
if (!token) {
|
|
3675
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
3676
|
+
console.log("Get a Personal Access Token at https://cloud.ouraring.com/personal-access-tokens");
|
|
3677
|
+
token = await rl.question("Paste your token: ");
|
|
3678
|
+
rl.close();
|
|
3679
|
+
}
|
|
3680
|
+
writeToken(target, token);
|
|
3681
|
+
console.log(source_default.green(`Saved to ${target}`));
|
|
3682
|
+
});
|
|
3683
|
+
}
|
|
3684
|
+
|
|
3685
|
+
// src/commands/describe.ts
|
|
3686
|
+
var DATE_ARGS = [
|
|
3687
|
+
{ name: "--start", type: "date", format: "YYYY-MM-DD", required: false, description: "Range start (inclusive)" },
|
|
3688
|
+
{ name: "--end", type: "date", format: "YYYY-MM-DD", required: false, description: "Range end (inclusive)" }
|
|
3689
|
+
];
|
|
3690
|
+
function buildManifest(version) {
|
|
3691
|
+
return {
|
|
3692
|
+
name: "oura-cli",
|
|
3693
|
+
version,
|
|
3694
|
+
auth: {
|
|
3695
|
+
envVars: ["OURA_TOKEN", "OURA_TOKEN_PATH"],
|
|
3696
|
+
tokenFile: "~/.oura-token",
|
|
3697
|
+
loginCommand: "oura-cli login"
|
|
3698
|
+
},
|
|
3699
|
+
globalFlags: [
|
|
3700
|
+
{ name: "--format", type: "enum", values: ["table", "json"], description: "Output format (auto-detected by TTY when omitted)" },
|
|
3701
|
+
{ name: "--db", type: "string", description: "Override SQLite database path (env: OURA_DB_PATH)" },
|
|
3702
|
+
{ name: "--tz", type: "string", description: "Display timezone (env: OURA_TZ; default auto-detected)" },
|
|
3703
|
+
{ name: "--token", type: "string", description: "Inline access token (prefer env vars or `login`)" },
|
|
3704
|
+
{ name: "--no-color", type: "boolean", description: "Disable ANSI colors in human output" }
|
|
3705
|
+
],
|
|
3706
|
+
exitCodes: [
|
|
3707
|
+
{ code: 0, meaning: "success" },
|
|
3708
|
+
{ code: 1, meaning: "user error (bad arguments)" },
|
|
3709
|
+
{ code: 2, meaning: "auth error (missing or invalid token)" },
|
|
3710
|
+
{ code: 3, meaning: "API or network error" },
|
|
3711
|
+
{ code: 4, meaning: "database or local storage error" }
|
|
3712
|
+
],
|
|
3713
|
+
commands: [
|
|
3714
|
+
{ name: "login", description: "Save an Oura Personal Access Token for future commands.", args: [
|
|
3715
|
+
{ name: "--token", type: "string", required: false, description: "Pass token non-interactively" },
|
|
3716
|
+
{ name: "--path", type: "string", required: false, description: "Override token file path" }
|
|
3717
|
+
] },
|
|
3718
|
+
{ name: "describe", description: "Emit a machine-readable manifest of commands, args, and outputs.", args: [] },
|
|
3719
|
+
{ name: "sleep", description: "Fetch daily sleep scores from Oura API.", args: DATE_ARGS, outputSchema: "docs/schemas/sleep.json" },
|
|
3720
|
+
{ name: "readiness", description: "Fetch daily readiness scores from Oura API.", args: DATE_ARGS, outputSchema: "docs/schemas/readiness.json" },
|
|
3721
|
+
{ name: "activity", description: "Fetch daily activity scores from Oura API.", args: DATE_ARGS, outputSchema: "docs/schemas/activity.json" },
|
|
3722
|
+
{ name: "hr", description: "Fetch heart rate samples from Oura API.", args: DATE_ARGS, outputSchema: "docs/schemas/hr.json" },
|
|
3723
|
+
{ name: "spo2", description: "Fetch blood oxygen (SpO2) data from Oura API.", args: DATE_ARGS, outputSchema: "docs/schemas/spo2.json" },
|
|
3724
|
+
{ name: "stress", description: "Fetch daily stress data from Oura API.", args: DATE_ARGS, outputSchema: "docs/schemas/stress.json" },
|
|
3725
|
+
{ name: "workout", description: "Fetch workout data from Oura API.", args: DATE_ARGS, outputSchema: "docs/schemas/workout.json" },
|
|
3726
|
+
{ name: "sync", description: "Sync all Oura collections into the local database.", args: [] },
|
|
3727
|
+
{ name: "db", description: "Query the local SQLite cache.", args: [] },
|
|
3728
|
+
{ name: "report", description: "Render a weekly or monthly summary report.", args: [
|
|
3729
|
+
{ name: "--week", type: "boolean", description: "Render the last 7 days" },
|
|
3730
|
+
{ name: "--month", type: "boolean", description: "Render the last 30 days" }
|
|
3731
|
+
] }
|
|
3732
|
+
]
|
|
3733
|
+
};
|
|
3734
|
+
}
|
|
3735
|
+
function describeCommand(version) {
|
|
3736
|
+
return new Command("describe").description("Emit a machine-readable manifest of commands, args, and outputs.").action(() => {
|
|
3737
|
+
console.log(JSON.stringify(buildManifest(version), null, 2));
|
|
3738
|
+
});
|
|
3739
|
+
}
|
|
3740
|
+
|
|
3741
|
+
// src/index.ts
|
|
3742
|
+
var VERSION = "0.1.0";
|
|
3743
|
+
var program2 = new Command;
|
|
3744
|
+
program2.name("oura-cli").description("Oura Ring CLI \u2014 query and analyze Oura Ring health data. Designed for humans and agents.").version(VERSION).option("--format <format>", "Output format: table | json (default auto-detect by TTY)").option("--token <pat>", "Inline access token (prefer env vars or `oura-cli login`)").option("--db <path>", "Path to SQLite database file (env: OURA_DB_PATH)").option("--tz <timezone>", "Display timezone (env: OURA_TZ; default auto-detect)");
|
|
3745
|
+
program2.addCommand(loginCommand());
|
|
3746
|
+
program2.addCommand(describeCommand(VERSION));
|
|
3747
|
+
program2.addCommand(createApiCommand("sleep", "Fetch daily sleep scores from Oura API.", "daily_sleep"));
|
|
3748
|
+
program2.addCommand(createApiCommand("readiness", "Fetch daily readiness scores from Oura API.", "daily_readiness"));
|
|
3749
|
+
program2.addCommand(createApiCommand("activity", "Fetch daily activity scores from Oura API.", "daily_activity"));
|
|
3750
|
+
program2.addCommand(createApiCommand("hr", "Fetch heart rate samples from Oura API.", "heartrate"));
|
|
3751
|
+
program2.addCommand(createApiCommand("spo2", "Fetch blood oxygen (SpO2) data from Oura API.", "daily_spo2"));
|
|
3752
|
+
program2.addCommand(createApiCommand("stress", "Fetch daily stress data from Oura API.", "daily_stress"));
|
|
3753
|
+
program2.addCommand(createApiCommand("workout", "Fetch workout data from Oura API.", "workout"));
|
|
3754
|
+
program2.addCommand(syncCommand());
|
|
3755
|
+
program2.addCommand(dbCommand());
|
|
3756
|
+
program2.addCommand(reportCommand());
|
|
3757
|
+
program2.parseAsync(process.argv).catch((err) => {
|
|
3758
|
+
const fmt = resolveFormat({
|
|
3759
|
+
explicit: program2.opts().format,
|
|
3760
|
+
isTty: process.stdout.isTTY === true
|
|
3761
|
+
});
|
|
3762
|
+
emitError(err, fmt);
|
|
3763
|
+
process.exit(exitCodeFor(err));
|
|
3764
|
+
});
|