mozyfin-cli 0.2.9 → 0.2.11
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/README.md +88 -175
- package/dist/index.js +17 -17
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,37 +1,41 @@
|
|
|
1
1
|
# Mozyfin CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Mozyfin CLI brings Vietnamese market data and Mozyfin research workflows to your terminal. It is built for fast lookup, repeatable analysis, and agent-friendly command usage without exposing product internals.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Why Mozyfin CLI
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
-
|
|
10
|
-
-
|
|
11
|
-
- Built-in technical indicators and risk metrics from OHLCV candles
|
|
12
|
-
- Automatic update check that warns when a newer CLI version is available on npm
|
|
13
|
-
- Mocked CLI test suite covering command wiring, auth, config, CSV, validation, and output shape
|
|
7
|
+
- **Fast market lookup** — search symbols, view profiles, read news, and inspect company data from one command line.
|
|
8
|
+
- **Agent-friendly** — concise commands and predictable text output work well with Claude Code, Codex, GitHub Copilot, and other coding agents.
|
|
9
|
+
- **Research-ready** — ask natural-language questions, query documents, and export larger tables to CSV when needed.
|
|
10
|
+
- **Terminal-native** — use it manually, inside scripts, or as part of an agent workflow.
|
|
14
11
|
|
|
15
12
|
## Requirements
|
|
16
13
|
|
|
17
|
-
-
|
|
18
|
-
- A Mozyfin API key — required for every command (run `mozyfin login` once before using the CLI)
|
|
14
|
+
- A Mozyfin API key for authenticated features
|
|
19
15
|
|
|
20
|
-
Create
|
|
16
|
+
Create or manage your API key at:
|
|
21
17
|
|
|
22
|
-
|
|
18
|
+
```text
|
|
19
|
+
https://research.mozyfin.com/settings
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
23
|
|
|
24
24
|
```bash
|
|
25
25
|
npm install -g mozyfin-cli
|
|
26
|
+
mozyfin --help
|
|
26
27
|
```
|
|
27
28
|
|
|
28
29
|
Or with Bun:
|
|
29
30
|
|
|
30
31
|
```bash
|
|
31
32
|
bun install -g mozyfin-cli
|
|
33
|
+
mozyfin --help
|
|
32
34
|
```
|
|
33
35
|
|
|
34
|
-
|
|
36
|
+
## Login
|
|
37
|
+
|
|
38
|
+
Save your API key once:
|
|
35
39
|
|
|
36
40
|
```bash
|
|
37
41
|
mozyfin login --api-key mozy_ak_xxx
|
|
@@ -55,161 +59,119 @@ mozyfin doc "định giá HPG"
|
|
|
55
59
|
mozyfin ask "compare VNM and MSN margin trend"
|
|
56
60
|
```
|
|
57
61
|
|
|
58
|
-
##
|
|
62
|
+
## Using With Coding Agents
|
|
59
63
|
|
|
60
|
-
|
|
61
|
-
| --- | --- | --- |
|
|
62
|
-
| `login` | Save API key locally | `mozyfin login --api-key <key>` |
|
|
63
|
-
| `logout` | Remove saved API key | `mozyfin logout` |
|
|
64
|
-
| `search` | Search ticker/company/entity | `mozyfin search --query VNM` |
|
|
65
|
-
| `profile` | Company/entity profile | `mozyfin profile VNM.VN` |
|
|
66
|
-
| `news` | Market headlines and article search | `mozyfin news --entities VNM.VN --topics stock,earning` |
|
|
67
|
-
| `indices` | List supported market indices | `mozyfin indices` |
|
|
68
|
-
| `ohlcv` | Historical candles | `mozyfin ohlcv VNM.VN --timeframe 1d --limit 200` |
|
|
69
|
-
| `quote` | Historical quote stats | `mozyfin quote VNM.VN --limit 10` |
|
|
70
|
-
| `officers` | Company officers/directors | `mozyfin officers VNM.VN` |
|
|
71
|
-
| `subsidiary` | Subsidiaries | `mozyfin subsidiary VNM.VN` |
|
|
72
|
-
| `holder` | Major shareholders | `mozyfin holder VNM.VN --is-organization true` |
|
|
73
|
-
| `holder-tx` | Shareholder transactions | `mozyfin holder-tx VNM.VN --transaction-type buy --limit 100` |
|
|
74
|
-
| `financials` | Financial statements summary | `mozyfin financials VNM.VN --year 2024 --quarter 4` |
|
|
75
|
-
| `stats` | Financial statistics/ratios | `mozyfin stats VNM.VN --year 2024` |
|
|
76
|
-
| `ta` | Technical indicators | `mozyfin ta VNM.VN --sma 20,50 --rsi 14 --macd` |
|
|
77
|
-
| `risk` | Return, volatility, Sharpe, drawdown | `mozyfin risk VNM.VN --limit 252 --risk-free 0.03` |
|
|
78
|
-
| `doc` | Query analysis reports (RAG) | `mozyfin doc "định giá HPG"` |
|
|
79
|
-
| `ask` | Ask the Mozyfin agent | `mozyfin ask "analyze VNM" --timeout 300` |
|
|
80
|
-
| `credits` | Check subscription usage | `mozyfin credits` |
|
|
81
|
-
| `doctor` | Runtime/config/API health check | `mozyfin doctor` |
|
|
82
|
-
| `update` | Upgrade CLI and refresh installed agent skills | `mozyfin update` |
|
|
83
|
-
| `skill` | Install/remove/list agent skill packs | `mozyfin skill claude` |
|
|
84
|
-
|
|
85
|
-
## Command Reference
|
|
86
|
-
|
|
87
|
-
### Auth
|
|
64
|
+
Mozyfin CLI is a good fit for agent workflows because agents can call small terminal commands instead of loading large tool schemas or internal implementation details.
|
|
88
65
|
|
|
89
|
-
|
|
90
|
-
mozyfin login --api-key <key>
|
|
91
|
-
mozyfin logout
|
|
92
|
-
mozyfin credits
|
|
93
|
-
```
|
|
94
|
-
|
|
95
|
-
Auth precedence is:
|
|
96
|
-
|
|
97
|
-
1. Explicit global `--api-key <key>`
|
|
98
|
-
2. `MOZYFIN_API_KEY` environment variable
|
|
99
|
-
3. Saved config from `mozyfin login`
|
|
100
|
-
|
|
101
|
-
Config is stored at:
|
|
66
|
+
Example prompt for your agent:
|
|
102
67
|
|
|
103
68
|
```text
|
|
104
|
-
|
|
69
|
+
Use mozyfin-cli to research VNM.VN.
|
|
70
|
+
Start with `mozyfin --help`, then gather profile, news, financials, and recent candles.
|
|
71
|
+
Summarize the key risks and catalysts with command outputs as evidence.
|
|
105
72
|
```
|
|
106
73
|
|
|
107
|
-
|
|
74
|
+
For larger tabular results, ask your agent to use CSV export:
|
|
108
75
|
|
|
109
76
|
```bash
|
|
110
|
-
mozyfin
|
|
111
|
-
mozyfin search -q "Vinamilk"
|
|
112
|
-
mozyfin search -q "" # broad search/all, depending on API behavior
|
|
113
|
-
mozyfin profile VNM.VN
|
|
77
|
+
mozyfin ohlcv VNM.VN --timeframe 1d --limit 200 --csv vnm.csv
|
|
114
78
|
```
|
|
115
79
|
|
|
116
|
-
|
|
80
|
+
## Agent Skills
|
|
117
81
|
|
|
118
|
-
|
|
82
|
+
Install the Mozyfin skill into your coding agent so it knows the recommended commands and workflows:
|
|
119
83
|
|
|
120
84
|
```bash
|
|
121
|
-
mozyfin
|
|
122
|
-
mozyfin
|
|
85
|
+
mozyfin skill claude
|
|
86
|
+
mozyfin skill codex
|
|
87
|
+
mozyfin skill copilot
|
|
123
88
|
```
|
|
124
89
|
|
|
125
|
-
|
|
90
|
+
Supported agents:
|
|
126
91
|
|
|
127
92
|
```text
|
|
128
|
-
|
|
93
|
+
claude, cursor, copilot, windsurf, codex, gemini, hermes, openclaw, antigravity
|
|
129
94
|
```
|
|
130
95
|
|
|
131
|
-
|
|
96
|
+
Useful skill commands:
|
|
132
97
|
|
|
133
98
|
```bash
|
|
134
|
-
mozyfin
|
|
135
|
-
mozyfin
|
|
136
|
-
mozyfin
|
|
137
|
-
mozyfin
|
|
99
|
+
mozyfin skill --list # show supported agents and install status
|
|
100
|
+
mozyfin skill <agent> # install or refresh the skill for one agent
|
|
101
|
+
mozyfin skill all # install or refresh the skill for all supported agents
|
|
102
|
+
mozyfin skill <agent> --remove # remove the skill from one agent
|
|
138
103
|
```
|
|
139
104
|
|
|
140
|
-
|
|
105
|
+
When updating the CLI, installed skills are refreshed automatically. You can also force a skill refresh:
|
|
141
106
|
|
|
142
|
-
```
|
|
143
|
-
|
|
107
|
+
```bash
|
|
108
|
+
mozyfin update --skill claude
|
|
109
|
+
mozyfin update --skill all
|
|
144
110
|
```
|
|
145
111
|
|
|
146
|
-
|
|
112
|
+
## Commands
|
|
147
113
|
|
|
148
|
-
###
|
|
114
|
+
### Account
|
|
149
115
|
|
|
150
116
|
```bash
|
|
151
|
-
mozyfin
|
|
152
|
-
mozyfin
|
|
153
|
-
mozyfin
|
|
154
|
-
mozyfin
|
|
117
|
+
mozyfin login --api-key <key>
|
|
118
|
+
mozyfin logout
|
|
119
|
+
mozyfin credits
|
|
120
|
+
mozyfin doctor
|
|
121
|
+
mozyfin update
|
|
155
122
|
```
|
|
156
123
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
### Financials
|
|
124
|
+
### Discovery
|
|
160
125
|
|
|
161
126
|
```bash
|
|
162
|
-
mozyfin
|
|
163
|
-
mozyfin
|
|
164
|
-
mozyfin
|
|
127
|
+
mozyfin search --query VNM
|
|
128
|
+
mozyfin profile VNM.VN
|
|
129
|
+
mozyfin indices
|
|
165
130
|
```
|
|
166
131
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
### Analytics
|
|
132
|
+
### News And Research
|
|
170
133
|
|
|
171
134
|
```bash
|
|
172
|
-
mozyfin
|
|
173
|
-
mozyfin
|
|
135
|
+
mozyfin news --query "Vinamilk" --limit 10
|
|
136
|
+
mozyfin news --entities VNM.VN,MSN.VN --topics stock,earning --limit 20
|
|
137
|
+
mozyfin doc "định giá HPG"
|
|
138
|
+
mozyfin ask "summarize VNM risks and catalysts"
|
|
174
139
|
```
|
|
175
140
|
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
### Document Query
|
|
141
|
+
### Market Data
|
|
179
142
|
|
|
180
143
|
```bash
|
|
181
|
-
mozyfin
|
|
182
|
-
mozyfin
|
|
183
|
-
mozyfin doc "so sánh biên lợi nhuận VNM và MSN"
|
|
144
|
+
mozyfin ohlcv VNM.VN --timeframe 1d --limit 200
|
|
145
|
+
mozyfin quote VNM.VN --limit 10
|
|
184
146
|
```
|
|
185
147
|
|
|
186
|
-
|
|
148
|
+
Supported candle timeframes:
|
|
187
149
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
- **References** — source documents mapped to chunks
|
|
192
|
-
- **Context** — grounding instructions from the RAG system
|
|
193
|
-
|
|
194
|
-
Requires an API key.
|
|
150
|
+
```text
|
|
151
|
+
1h, 1d, 1w, 1mo, 1y
|
|
152
|
+
```
|
|
195
153
|
|
|
196
|
-
###
|
|
154
|
+
### Company Data
|
|
197
155
|
|
|
198
156
|
```bash
|
|
199
|
-
mozyfin
|
|
200
|
-
mozyfin
|
|
157
|
+
mozyfin officers VNM.VN
|
|
158
|
+
mozyfin subsidiary VNM.VN
|
|
159
|
+
mozyfin holder VNM.VN --is-organization true
|
|
160
|
+
mozyfin holder-tx VNM.VN --transaction-type buy --limit 100
|
|
201
161
|
```
|
|
202
162
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
Guidance:
|
|
163
|
+
### Financials And Analytics
|
|
206
164
|
|
|
207
|
-
|
|
208
|
-
|
|
165
|
+
```bash
|
|
166
|
+
mozyfin financials VNM.VN --year 2024 --quarter 4
|
|
167
|
+
mozyfin stats VNM.VN --year 2024
|
|
168
|
+
mozyfin ta VNM.VN --sma 20,50 --rsi 14 --macd
|
|
169
|
+
mozyfin risk VNM.VN --limit 252 --risk-free 0.03
|
|
170
|
+
```
|
|
209
171
|
|
|
210
172
|
## Output
|
|
211
173
|
|
|
212
|
-
|
|
174
|
+
Mozyfin CLI prints readable text by default, usually Markdown tables or compact key-value sections.
|
|
213
175
|
|
|
214
176
|
```bash
|
|
215
177
|
mozyfin search --query VNM
|
|
@@ -221,72 +183,23 @@ mozyfin search --query VNM
|
|
|
221
183
|
| VNM | Vietnam Dairy Products Joint Stock Company | HOSE | ... | VNM.VN |
|
|
222
184
|
```
|
|
223
185
|
|
|
224
|
-
Use CSV
|
|
186
|
+
Use CSV when you want to save or process larger datasets:
|
|
225
187
|
|
|
226
188
|
```bash
|
|
227
189
|
mozyfin ohlcv VNM.VN --timeframe 1d --limit 200 --csv vnm.csv
|
|
228
190
|
```
|
|
229
191
|
|
|
230
|
-
##
|
|
192
|
+
## Tips
|
|
231
193
|
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
194
|
+
- Use `mozyfin search --query <text>` first to find the right entity id.
|
|
195
|
+
- Pass ids like `VNM.VN` into detail commands.
|
|
196
|
+
- Use `doc` for document and report questions.
|
|
197
|
+
- Use `ask` for open-ended research prompts.
|
|
198
|
+
- Keep prompts focused; run multiple commands for multi-part research.
|
|
237
199
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
| Script | Description |
|
|
241
|
-
| --- | --- |
|
|
242
|
-
| `bun run dev -- <args>` | Run CLI from source |
|
|
243
|
-
| `bun test` | Run unit/CLI tests |
|
|
244
|
-
| `bun run lint` | Check formatting/linting |
|
|
245
|
-
| `bun run format` | Format files |
|
|
246
|
-
| `bun run check` | Format/lint with write fixes |
|
|
247
|
-
|
|
248
|
-
Run from source:
|
|
200
|
+
## Help
|
|
249
201
|
|
|
250
202
|
```bash
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
## Test Coverage
|
|
255
|
-
|
|
256
|
-
The test suite uses Bun's test runner plus a mocked local HTTP server. It covers:
|
|
257
|
-
|
|
258
|
-
- API URL construction and endpoint mapping
|
|
259
|
-
- HTTP response and error parsing
|
|
260
|
-
- CLI command output shape
|
|
261
|
-
- Query parameter mapping for command options
|
|
262
|
-
- Auth precedence and config persistence
|
|
263
|
-
- CSV file output
|
|
264
|
-
- Empty data rendering
|
|
265
|
-
- Validation errors and missing API key errors
|
|
266
|
-
- `ask` polling and malformed response handling
|
|
267
|
-
- Technical indicator and risk helper behavior
|
|
268
|
-
|
|
269
|
-
## Project Structure
|
|
270
|
-
|
|
271
|
-
```text
|
|
272
|
-
src/index.ts CLI command definitions
|
|
273
|
-
src/lib/api.ts API client, auth, rate limit, URL construction
|
|
274
|
-
src/lib/config.ts Local config load/save/clear
|
|
275
|
-
src/lib/format.ts Markdown, key-value, CSV formatting
|
|
276
|
-
src/lib/analytics.ts SMA, EMA, RSI, MACD, risk metrics
|
|
277
|
-
test/*.test.ts Unit and mocked CLI tests
|
|
203
|
+
mozyfin --help
|
|
204
|
+
mozyfin <command> --help
|
|
278
205
|
```
|
|
279
|
-
|
|
280
|
-
## Notes for AI Agents
|
|
281
|
-
|
|
282
|
-
- Prefer Markdown output for short responses and `--csv <file>` for large tables.
|
|
283
|
-
- Use `search --query <text>` to discover entity ids, then pass ids such as `VNM.VN` into detail commands.
|
|
284
|
-
- Do not use removed commands/options such as `markets`, `exchanges`, `events`, or `ask --no-wait`.
|
|
285
|
-
- `officers` returns people and roles, not physical office addresses.
|
|
286
|
-
- Every command requires an API key — call `mozyfin login --api-key <key>` (or set `MOZYFIN_API_KEY`) before any other command.
|
|
287
|
-
- Use `doc` for natural language queries against analysis reports (RAG); use `ask` for open-ended AI research that may call multiple data sources.
|
|
288
|
-
- If your CLI version is outdated the CLI prints an `⚠️` warning to stderr at the end of each run; pipe stderr separately if you parse output.
|
|
289
|
-
|
|
290
|
-
## License
|
|
291
|
-
|
|
292
|
-
Private/internal unless a license is added.
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var l0=Object.create;var{getPrototypeOf:m0,defineProperty:X0,getOwnPropertyNames:d0}=Object;var r0=Object.prototype.hasOwnProperty;var
|
|
3
|
+
var l0=Object.create;var{getPrototypeOf:m0,defineProperty:X0,getOwnPropertyNames:d0}=Object;var r0=Object.prototype.hasOwnProperty;function s0($){return this[$]}var i0,p0,t0=($,q,Q)=>{var z=$!=null&&typeof $==="object";if(z){var J=q?i0??=new WeakMap:p0??=new WeakMap,Y=J.get($);if(Y)return Y}Q=$!=null?l0(m0($)):{};let X=q||!$||!$.__esModule?X0(Q,"default",{value:$,enumerable:!0}):Q;for(let M of d0($))if(!r0.call(X,M))X0(X,M,{get:s0.bind($,M),enumerable:!0});if(z)J.set($,X);return X};var D=($,q)=>()=>(q||$((q={exports:{}}).exports,q),q.exports);var T=import.meta.require;var k=D((n0)=>{class d extends Error{constructor($,q,Q){super(Q);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=q,this.exitCode=$,this.nestedError=void 0}}class Z0 extends d{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}n0.CommanderError=d;n0.InvalidArgumentError=Z0});var C=D((q1)=>{var{InvalidArgumentError:o0}=k();class _0{constructor($,q){switch(this.description=q||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue($,q){if(q===this.defaultValue||!Array.isArray(q))return[$];return q.concat($)}default($,q){return this.defaultValue=$,this.defaultValueDescription=q,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(q,Q)=>{if(!this.argChoices.includes(q))throw new o0(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(q,Q);return q},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function $1($){let q=$.name()+($.variadic===!0?"...":"");return $.required?"<"+q+">":"["+q+"]"}q1.Argument=_0;q1.humanReadableArgName=$1});var r=D((Y1)=>{var{humanReadableArgName:J1}=C();class U0{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands($){let q=$.commands.filter((z)=>!z._hidden),Q=$._getHelpCommand();if(Q&&!Q._hidden)q.push(Q);if(this.sortSubcommands)q.sort((z,J)=>{return z.name().localeCompare(J.name())});return q}compareOptions($,q){let Q=(z)=>{return z.short?z.short.replace(/^-/,""):z.long.replace(/^--/,"")};return Q($).localeCompare(Q(q))}visibleOptions($){let q=$.options.filter((z)=>!z.hidden),Q=$._getHelpOption();if(Q&&!Q.hidden){let z=Q.short&&$._findOption(Q.short),J=Q.long&&$._findOption(Q.long);if(!z&&!J)q.push(Q);else if(Q.long&&!J)q.push($.createOption(Q.long,Q.description));else if(Q.short&&!z)q.push($.createOption(Q.short,Q.description))}if(this.sortOptions)q.sort(this.compareOptions);return q}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let q=[];for(let Q=$.parent;Q;Q=Q.parent){let z=Q.options.filter((J)=>!J.hidden);q.push(...z)}if(this.sortOptions)q.sort(this.compareOptions);return q}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((q)=>{q.description=q.description||$._argsDescription[q.name()]||""});if($.registeredArguments.find((q)=>q.description))return $.registeredArguments;return[]}subcommandTerm($){let q=$.registeredArguments.map((Q)=>J1(Q)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(q?" "+q:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,q){return q.visibleCommands($).reduce((Q,z)=>{return Math.max(Q,q.subcommandTerm(z).length)},0)}longestOptionTermLength($,q){return q.visibleOptions($).reduce((Q,z)=>{return Math.max(Q,q.optionTerm(z).length)},0)}longestGlobalOptionTermLength($,q){return q.visibleGlobalOptions($).reduce((Q,z)=>{return Math.max(Q,q.optionTerm(z).length)},0)}longestArgumentTermLength($,q){return q.visibleArguments($).reduce((Q,z)=>{return Math.max(Q,q.argumentTerm(z).length)},0)}commandUsage($){let q=$._name;if($._aliases[0])q=q+"|"+$._aliases[0];let Q="";for(let z=$.parent;z;z=z.parent)Q=z.name()+" "+Q;return Q+q+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let q=[];if($.argChoices)q.push(`choices: ${$.argChoices.map((Q)=>JSON.stringify(Q)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")q.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)q.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)q.push(`env: ${$.envVar}`);if(q.length>0)return`${$.description} (${q.join(", ")})`;return $.description}argumentDescription($){let q=[];if($.argChoices)q.push(`choices: ${$.argChoices.map((Q)=>JSON.stringify(Q)).join(", ")}`);if($.defaultValue!==void 0)q.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(q.length>0){let Q=`(${q.join(", ")})`;if($.description)return`${$.description} ${Q}`;return Q}return $.description}formatHelp($,q){let Q=q.padWidth($,q),z=q.helpWidth||80,J=2,Y=2;function X(G,N){if(N){let m=`${G.padEnd(Q+2)}${N}`;return q.wrap(m,z-2,Q+2)}return G}function M(G){return G.join(`
|
|
4
4
|
`).replace(/^/gm," ".repeat(2))}let Z=[`Usage: ${q.commandUsage($)}`,""],_=q.commandDescription($);if(_.length>0)Z=Z.concat([q.wrap(_,z,0),""]);let U=q.visibleArguments($).map((G)=>{return X(q.argumentTerm(G),q.argumentDescription(G))});if(U.length>0)Z=Z.concat(["Arguments:",M(U),""]);let W=q.visibleOptions($).map((G)=>{return X(q.optionTerm(G),q.optionDescription(G))});if(W.length>0)Z=Z.concat(["Options:",M(W),""]);if(this.showGlobalOptions){let G=q.visibleGlobalOptions($).map((N)=>{return X(q.optionTerm(N),q.optionDescription(N))});if(G.length>0)Z=Z.concat(["Global Options:",M(G),""])}let L=q.visibleCommands($).map((G)=>{return X(q.subcommandTerm(G),q.subcommandDescription(G))});if(L.length>0)Z=Z.concat(["Commands:",M(L),""]);return Z.join(`
|
|
5
5
|
`)}padWidth($,q){return Math.max(q.longestOptionTermLength($,q),q.longestGlobalOptionTermLength($,q),q.longestSubcommandTermLength($,q),q.longestArgumentTermLength($,q))}wrap($,q,Q,z=40){let Y=new RegExp(`[\\n][${" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF"}]+`);if($.match(Y))return $;let X=q-Q;if(X<z)return $;let M=$.slice(0,Q),Z=$.slice(Q).replace(`\r
|
|
6
6
|
`,`
|
|
7
7
|
`),_=" ".repeat(Q),W=`\\s${"\u200B"}`,L=new RegExp(`
|
|
8
8
|
|.{1,${X-1}}([${W}]|$)|[^${W}]+?([${W}]|$)`,"g"),G=Z.match(L)||[];return M+G.map((N,m)=>{if(N===`
|
|
9
9
|
`)return"";return(m>0?_:"")+N.trimEnd()}).join(`
|
|
10
|
-
`)}}
|
|
10
|
+
`)}}Y1.Help=U0});var s=D((U1)=>{var{InvalidArgumentError:X1}=k();class B0{constructor($,q){this.flags=$,this.description=q||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let Q=_1($);if(this.short=Q.shortFlag,this.long=Q.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default($,q){return this.defaultValue=$,this.defaultValueDescription=q,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let q=$;if(typeof $==="string")q={[$]:!0};return this.implied=Object.assign(this.implied||{},q),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_concatValue($,q){if(q===this.defaultValue||!Array.isArray(q))return[$];return q.concat($)}choices($){return this.argChoices=$.slice(),this.parseArg=(q,Q)=>{if(!this.argChoices.includes(q))throw new X1(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(q,Q);return q},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){return Z1(this.name().replace(/^no-/,""))}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class K0{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((q)=>{if(q.negate)this.negativeOptions.set(q.attributeName(),q);else this.positiveOptions.set(q.attributeName(),q)}),this.negativeOptions.forEach((q,Q)=>{if(this.positiveOptions.has(Q))this.dualOptions.add(Q)})}valueFromOption($,q){let Q=q.attributeName();if(!this.dualOptions.has(Q))return!0;let z=this.negativeOptions.get(Q).presetArg,J=z!==void 0?z:!1;return q.negate===(J===$)}}function Z1($){return $.split("-").reduce((q,Q)=>{return q+Q[0].toUpperCase()+Q.slice(1)})}function _1($){let q,Q,z=$.split(/[ |,]+/);if(z.length>1&&!/^[[<]/.test(z[1]))q=z.shift();if(Q=z.shift(),!q&&/^-[^-]$/.test(Q))q=Q,Q=void 0;return{shortFlag:q,longFlag:Q}}U1.Option=B0;U1.DualOptions=K0});var G0=D((H1)=>{function G1($,q){if(Math.abs($.length-q.length)>3)return Math.max($.length,q.length);let Q=[];for(let z=0;z<=$.length;z++)Q[z]=[z];for(let z=0;z<=q.length;z++)Q[0][z]=z;for(let z=1;z<=q.length;z++)for(let J=1;J<=$.length;J++){let Y=1;if($[J-1]===q[z-1])Y=0;else Y=1;if(Q[J][z]=Math.min(Q[J-1][z]+1,Q[J][z-1]+1,Q[J-1][z-1]+Y),J>1&&z>1&&$[J-1]===q[z-2]&&$[J-2]===q[z-1])Q[J][z]=Math.min(Q[J][z],Q[J-2][z-2]+1)}return Q[$.length][q.length]}function W1($,q){if(!q||q.length===0)return"";q=Array.from(new Set(q));let Q=$.startsWith("--");if(Q)$=$.slice(2),q=q.map((X)=>X.slice(2));let z=[],J=3,Y=0.4;if(q.forEach((X)=>{if(X.length<=1)return;let M=G1($,X),Z=Math.max($.length,X.length);if((Z-M)/Z>Y){if(M<J)J=M,z=[X];else if(M===J)z.push(X)}}),z.sort((X,M)=>X.localeCompare(M)),Q)z=z.map((X)=>`--${X}`);if(z.length>1)return`
|
|
11
11
|
(Did you mean one of ${z.join(", ")}?)`;if(z.length===1)return`
|
|
12
|
-
(Did you mean ${z[0]}?)`;return""}
|
|
13
|
-
- specify the name in Command constructor or using .name()`);if(q=q||{},q.isDefault)this._defaultCommandName=$._name;if(q.noHelp||q.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,q){return new
|
|
12
|
+
(Did you mean ${z[0]}?)`;return""}H1.suggestSimilar=W1});var L0=D((j1)=>{var L1=T("events").EventEmitter,i=T("child_process"),P=T("path"),p=T("fs"),H=T("process"),{Argument:y1,humanReadableArgName:E1}=C(),{CommanderError:t}=k(),{Help:T1}=r(),{Option:W0,DualOptions:I1}=s(),{suggestSimilar:H0}=G0();class n extends L1{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:(q)=>H.stdout.write(q),writeErr:(q)=>H.stderr.write(q),getOutHelpWidth:()=>H.stdout.isTTY?H.stdout.columns:void 0,getErrHelpWidth:()=>H.stderr.isTTY?H.stderr.columns:void 0,outputError:(q,Q)=>Q(q)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let q=this;q;q=q.parent)$.push(q);return $}command($,q,Q){let z=q,J=Q;if(typeof z==="object"&&z!==null)J=z,z=null;J=J||{};let[,Y,X]=$.match(/([^ ]+) *(.*)/),M=this.createCommand(Y);if(z)M.description(z),M._executableHandler=!0;if(J.isDefault)this._defaultCommandName=M._name;if(M._hidden=!!(J.noHelp||J.hidden),M._executableFile=J.executableFile||null,X)M.arguments(X);if(this._registerCommand(M),M.parent=this,M.copyInheritedSettings(this),z)return this;return M}createCommand($){return new n($)}createHelp(){return Object.assign(new T1,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,$),this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,q){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
|
|
13
|
+
- specify the name in Command constructor or using .name()`);if(q=q||{},q.isDefault)this._defaultCommandName=$._name;if(q.noHelp||q.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,q){return new y1($,q)}argument($,q,Q,z){let J=this.createArgument($,q);if(typeof Q==="function")J.default(z).argParser(Q);else J.default(Q);return this.addArgument(J),this}arguments($){return $.trim().split(/ +/).forEach((q)=>{this.argument(q)}),this}addArgument($){let q=this.registeredArguments.slice(-1)[0];if(q&&q.variadic)throw Error(`only the last argument can be variadic '${q.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,q){if(typeof $==="boolean")return this._addImplicitHelpCommand=$,this;$=$??"help [command]";let[,Q,z]=$.match(/([^ ]+) *(.*)/),J=q??"display help for command",Y=this.createCommand(Q);if(Y.helpOption(!1),z)Y.arguments(z);if(J)Y.description(J);return this._addImplicitHelpCommand=!0,this._helpCommand=Y,this}addHelpCommand($,q){if(typeof $!=="object")return this.helpCommand($,q),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,q){let Q=["preSubcommand","preAction","postAction"];if(!Q.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
|
|
14
14
|
Expecting one of '${Q.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(q);else this._lifeCycleHooks[$]=[q];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(q)=>{if(q.code!=="commander.executeSubCommandAsync")throw q};return this}_exit($,q,Q){if(this._exitCallback)this._exitCallback(new t($,q,Q));H.exit($)}action($){let q=(Q)=>{let z=this.registeredArguments.length,J=Q.slice(0,z);if(this._storeOptionsAsProperties)J[z]=this;else J[z]=this.opts();return J.push(this),$.apply(this,J)};return this._actionHandler=q,this}createOption($,q){return new W0($,q)}_callParseArg($,q,Q,z){try{return $.parseArg(q,Q)}catch(J){if(J.code==="commander.invalidArgument"){let Y=`${z} ${J.message}`;this.error(Y,{exitCode:J.exitCode,code:J.code})}throw J}}_registerOption($){let q=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(q){let Q=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${Q}'
|
|
15
15
|
- already used by option '${q.flags}'`)}this.options.push($)}_registerCommand($){let q=(z)=>{return[z.name()].concat(z.aliases())},Q=q($).find((z)=>this._findCommand(z));if(Q){let z=q(this._findCommand(Q)).join("|"),J=q($).join("|");throw Error(`cannot add command '${J}' as already have command '${z}'`)}this.commands.push($)}addOption($){this._registerOption($);let q=$.name(),Q=$.attributeName();if($.negate){let J=$.long.replace(/^--no-/,"--");if(!this._findOption(J))this.setOptionValueWithSource(Q,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(Q,$.defaultValue,"default");let z=(J,Y,X)=>{if(J==null&&$.presetArg!==void 0)J=$.presetArg;let M=this.getOptionValue(Q);if(J!==null&&$.parseArg)J=this._callParseArg($,J,M,Y);else if(J!==null&&$.variadic)J=$._concatValue(J,M);if(J==null)if($.negate)J=!1;else if($.isBoolean()||$.optional)J=!0;else J="";this.setOptionValueWithSource(Q,J,X)};if(this.on("option:"+q,(J)=>{let Y=`error: option '${$.flags}' argument '${J}' is invalid.`;z(J,Y,"cli")}),$.envVar)this.on("optionEnv:"+q,(J)=>{let Y=`error: option '${$.flags}' value '${J}' from env '${$.envVar}' is invalid.`;z(J,Y,"env")});return this}_optionEx($,q,Q,z,J){if(typeof q==="object"&&q instanceof W0)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Y=this.createOption(q,Q);if(Y.makeOptionMandatory(!!$.mandatory),typeof z==="function")Y.default(J).argParser(z);else if(z instanceof RegExp){let X=z;z=(M,Z)=>{let _=X.exec(M);return _?_[0]:Z},Y.default(J).argParser(z)}else Y.default(z);return this.addOption(Y)}option($,q,Q,z){return this._optionEx({},$,q,Q,z)}requiredOption($,q,Q,z){return this._optionEx({mandatory:!0},$,q,Q,z)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,q){return this.setOptionValueWithSource($,q,void 0)}setOptionValueWithSource($,q,Q){if(this._storeOptionsAsProperties)this[$]=q;else this._optionValues[$]=q;return this._optionValueSources[$]=Q,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let q;return this._getCommandAndAncestors().forEach((Q)=>{if(Q.getOptionValueSource($)!==void 0)q=Q.getOptionValueSource($)}),q}_prepareUserArgs($,q){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(q=q||{},$===void 0&&q.from===void 0){if(H.versions?.electron)q.from="electron";let z=H.execArgv??[];if(z.includes("-e")||z.includes("--eval")||z.includes("-p")||z.includes("--print"))q.from="eval"}if($===void 0)$=H.argv;this.rawArgs=$.slice();let Q;switch(q.from){case void 0:case"node":this._scriptPath=$[1],Q=$.slice(2);break;case"electron":if(H.defaultApp)this._scriptPath=$[1],Q=$.slice(2);else Q=$.slice(1);break;case"user":Q=$.slice(0);break;case"eval":Q=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${q.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",Q}parse($,q){let Q=this._prepareUserArgs($,q);return this._parseCommand([],Q),this}async parseAsync($,q){let Q=this._prepareUserArgs($,q);return await this._parseCommand([],Q),this}_executeSubCommand($,q){q=q.slice();let Q=!1,z=[".js",".ts",".tsx",".mjs",".cjs"];function J(_,U){let W=P.resolve(_,U);if(p.existsSync(W))return W;if(z.includes(P.extname(U)))return;let L=z.find((G)=>p.existsSync(`${W}${G}`));if(L)return`${W}${L}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Y=$._executableFile||`${this._name}-${$._name}`,X=this._executableDir||"";if(this._scriptPath){let _;try{_=p.realpathSync(this._scriptPath)}catch(U){_=this._scriptPath}X=P.resolve(P.dirname(_),X)}if(X){let _=J(X,Y);if(!_&&!$._executableFile&&this._scriptPath){let U=P.basename(this._scriptPath,P.extname(this._scriptPath));if(U!==this._name)_=J(X,`${U}-${$._name}`)}Y=_||Y}Q=z.includes(P.extname(Y));let M;if(H.platform!=="win32")if(Q)q.unshift(Y),q=R0(H.execArgv).concat(q),M=i.spawn(H.argv[0],q,{stdio:"inherit"});else M=i.spawn(Y,q,{stdio:"inherit"});else q.unshift(Y),q=R0(H.execArgv).concat(q),M=i.spawn(H.execPath,q,{stdio:"inherit"});if(!M.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((U)=>{H.on(U,()=>{if(M.killed===!1&&M.exitCode===null)M.kill(U)})});let Z=this._exitCallback;M.on("close",(_)=>{if(_=_??1,!Z)H.exit(_);else Z(new t(_,"commander.executeSubCommandAsync","(close)"))}),M.on("error",(_)=>{if(_.code==="ENOENT"){let U=X?`searched for local subcommand relative to directory '${X}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",W=`'${Y}' does not exist
|
|
16
16
|
- if '${$._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
@@ -18,16 +18,16 @@ Expecting one of '${Q.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycl
|
|
|
18
18
|
- ${U}`;throw Error(W)}else if(_.code==="EACCES")throw Error(`'${Y}' not executable`);if(!Z)H.exit(1);else{let U=new t(1,"commander.executeSubCommandAsync","(error)");U.nestedError=_,Z(U)}}),this.runningCommand=M}_dispatchSubcommand($,q,Q){let z=this._findCommand($);if(!z)this.help({error:!0});let J;return J=this._chainOrCallSubCommandHook(J,z,"preSubcommand"),J=this._chainOrCall(J,()=>{if(z._executableHandler)this._executeSubCommand(z,q.concat(Q));else return z._parseCommand(q,Q)}),J}_dispatchHelpCommand($){if(!$)this.help();let q=this._findCommand($);if(q&&!q._executableHandler)q.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,q)=>{if($.required&&this.args[q]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(Q,z,J)=>{let Y=z;if(z!==null&&Q.parseArg){let X=`error: command-argument value '${z}' is invalid for argument '${Q.name()}'.`;Y=this._callParseArg(Q,z,J,X)}return Y};this._checkNumberOfArguments();let q=[];this.registeredArguments.forEach((Q,z)=>{let J=Q.defaultValue;if(Q.variadic){if(z<this.args.length){if(J=this.args.slice(z),Q.parseArg)J=J.reduce((Y,X)=>{return $(Q,X,Y)},Q.defaultValue)}else if(J===void 0)J=[]}else if(z<this.args.length){if(J=this.args[z],Q.parseArg)J=$(Q,J,Q.defaultValue)}q[z]=J}),this.processedArgs=q}_chainOrCall($,q){if($&&$.then&&typeof $.then==="function")return $.then(()=>q());return q()}_chainOrCallHooks($,q){let Q=$,z=[];if(this._getCommandAndAncestors().reverse().filter((J)=>J._lifeCycleHooks[q]!==void 0).forEach((J)=>{J._lifeCycleHooks[q].forEach((Y)=>{z.push({hookedCommand:J,callback:Y})})}),q==="postAction")z.reverse();return z.forEach((J)=>{Q=this._chainOrCall(Q,()=>{return J.callback(J.hookedCommand,this)})}),Q}_chainOrCallSubCommandHook($,q,Q){let z=$;if(this._lifeCycleHooks[Q]!==void 0)this._lifeCycleHooks[Q].forEach((J)=>{z=this._chainOrCall(z,()=>{return J(this,q)})});return z}_parseCommand($,q){let Q=this.parseOptions(q);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(Q.operands),q=Q.unknown,this.args=$.concat(q),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),q);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(q),this._dispatchSubcommand(this._defaultCommandName,$,q);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(Q.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let z=()=>{if(Q.unknown.length>0)this.unknownOption(Q.unknown[0])},J=`command:${this.name()}`;if(this._actionHandler){z(),this._processArguments();let Y;if(Y=this._chainOrCallHooks(Y,"preAction"),Y=this._chainOrCall(Y,()=>this._actionHandler(this.processedArgs)),this.parent)Y=this._chainOrCall(Y,()=>{this.parent.emit(J,$,q)});return Y=this._chainOrCallHooks(Y,"postAction"),Y}if(this.parent&&this.parent.listenerCount(J))z(),this._processArguments(),this.parent.emit(J,$,q);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,q);if(this.listenerCount("command:*"))this.emit("command:*",$,q);else if(this.commands.length)this.unknownCommand();else z(),this._processArguments()}else if(this.commands.length)z(),this.help({error:!0});else z(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((q)=>q._name===$||q._aliases.includes($))}_findOption($){return this.options.find((q)=>q.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((q)=>{if(q.mandatory&&$.getOptionValue(q.attributeName())===void 0)$.missingMandatoryOptionValue(q)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((Q)=>{let z=Q.attributeName();if(this.getOptionValue(z)===void 0)return!1;return this.getOptionValueSource(z)!=="default"});$.filter((Q)=>Q.conflictsWith.length>0).forEach((Q)=>{let z=$.find((J)=>Q.conflictsWith.includes(J.attributeName()));if(z)this._conflictingOption(Q,z)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let q=[],Q=[],z=q,J=$.slice();function Y(M){return M.length>1&&M[0]==="-"}let X=null;while(J.length){let M=J.shift();if(M==="--"){if(z===Q)z.push(M);z.push(...J);break}if(X&&!Y(M)){this.emit(`option:${X.name()}`,M);continue}if(X=null,Y(M)){let Z=this._findOption(M);if(Z){if(Z.required){let _=J.shift();if(_===void 0)this.optionMissingArgument(Z);this.emit(`option:${Z.name()}`,_)}else if(Z.optional){let _=null;if(J.length>0&&!Y(J[0]))_=J.shift();this.emit(`option:${Z.name()}`,_)}else this.emit(`option:${Z.name()}`);X=Z.variadic?Z:null;continue}}if(M.length>2&&M[0]==="-"&&M[1]!=="-"){let Z=this._findOption(`-${M[1]}`);if(Z){if(Z.required||Z.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${Z.name()}`,M.slice(2));else this.emit(`option:${Z.name()}`),J.unshift(`-${M.slice(2)}`);continue}}if(/^--[^=]+=/.test(M)){let Z=M.indexOf("="),_=this._findOption(M.slice(0,Z));if(_&&(_.required||_.optional)){this.emit(`option:${_.name()}`,M.slice(Z+1));continue}}if(Y(M))z=Q;if((this._enablePositionalOptions||this._passThroughOptions)&&q.length===0&&Q.length===0){if(this._findCommand(M)){if(q.push(M),J.length>0)Q.push(...J);break}else if(this._getHelpCommand()&&M===this._getHelpCommand().name()){if(q.push(M),J.length>0)q.push(...J);break}else if(this._defaultCommandName){if(Q.push(M),J.length>0)Q.push(...J);break}}if(this._passThroughOptions){if(z.push(M),J.length>0)z.push(...J);break}z.push(M)}return{operands:q,unknown:Q}}opts(){if(this._storeOptionsAsProperties){let $={},q=this.options.length;for(let Q=0;Q<q;Q++){let z=this.options[Q].attributeName();$[z]=z===this._versionOptionName?this._version:this[z]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,q)=>Object.assign($,q.opts()),{})}error($,q){if(this._outputConfiguration.outputError(`${$}
|
|
19
19
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
20
20
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
21
|
-
`),this.outputHelp({error:!0});let Q=q||{},z=Q.exitCode||1,J=Q.code||"commander.error";this._exit(z,J,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in H.env){let q=$.attributeName();if(this.getOptionValue(q)===void 0||["default","config","env"].includes(this.getOptionValueSource(q)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,H.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new
|
|
22
|
-
`),this._exit(0,"commander.version",$)}),this}description($,q){if($===void 0&&q===void 0)return this._description;if(this._description=$,q)this._argsDescription=q;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let q=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)q=this.commands[this.commands.length-1];if($===q._name)throw Error("Command alias can't be the same as its name");let Q=this.parent?._findCommand($);if(Q){let z=[Q.name()].concat(Q.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${z}'`)}return q._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((q)=>this.alias(q)),this}usage($){if($===void 0){if(this._usage)return this._usage;let q=this.registeredArguments.map((Q)=>{return
|
|
21
|
+
`),this.outputHelp({error:!0});let Q=q||{},z=Q.exitCode||1,J=Q.code||"commander.error";this._exit(z,J,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in H.env){let q=$.attributeName();if(this.getOptionValue(q)===void 0||["default","config","env"].includes(this.getOptionValueSource(q)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,H.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new I1(this.options),q=(Q)=>{return this.getOptionValue(Q)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(Q))};this.options.filter((Q)=>Q.implied!==void 0&&q(Q.attributeName())&&$.valueFromOption(this.getOptionValue(Q.attributeName()),Q)).forEach((Q)=>{Object.keys(Q.implied).filter((z)=>!q(z)).forEach((z)=>{this.setOptionValueWithSource(z,Q.implied[z],"implied")})})}missingArgument($){let q=`error: missing required argument '${$}'`;this.error(q,{code:"commander.missingArgument"})}optionMissingArgument($){let q=`error: option '${$.flags}' argument missing`;this.error(q,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let q=`error: required option '${$.flags}' not specified`;this.error(q,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,q){let Q=(Y)=>{let X=Y.attributeName(),M=this.getOptionValue(X),Z=this.options.find((U)=>U.negate&&X===U.attributeName()),_=this.options.find((U)=>!U.negate&&X===U.attributeName());if(Z&&(Z.presetArg===void 0&&M===!1||Z.presetArg!==void 0&&M===Z.presetArg))return Z;return _||Y},z=(Y)=>{let X=Q(Y),M=X.attributeName();if(this.getOptionValueSource(M)==="env")return`environment variable '${X.envVar}'`;return`option '${X.flags}'`},J=`error: ${z($)} cannot be used with ${z(q)}`;this.error(J,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let q="";if($.startsWith("--")&&this._showSuggestionAfterError){let z=[],J=this;do{let Y=J.createHelp().visibleOptions(J).filter((X)=>X.long).map((X)=>X.long);z=z.concat(Y),J=J.parent}while(J&&!J._enablePositionalOptions);q=H0($,z)}let Q=`error: unknown option '${$}'${q}`;this.error(Q,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let q=this.registeredArguments.length,Q=q===1?"":"s",J=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${q} argument${Q} but got ${$.length}.`;this.error(J,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],q="";if(this._showSuggestionAfterError){let z=[];this.createHelp().visibleCommands(this).forEach((J)=>{if(z.push(J.name()),J.alias())z.push(J.alias())}),q=H0($,z)}let Q=`error: unknown command '${$}'${q}`;this.error(Q,{code:"commander.unknownCommand"})}version($,q,Q){if($===void 0)return this._version;this._version=$,q=q||"-V, --version",Q=Q||"output the version number";let z=this.createOption(q,Q);return this._versionOptionName=z.attributeName(),this._registerOption(z),this.on("option:"+z.name(),()=>{this._outputConfiguration.writeOut(`${$}
|
|
22
|
+
`),this._exit(0,"commander.version",$)}),this}description($,q){if($===void 0&&q===void 0)return this._description;if(this._description=$,q)this._argsDescription=q;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let q=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)q=this.commands[this.commands.length-1];if($===q._name)throw Error("Command alias can't be the same as its name");let Q=this.parent?._findCommand($);if(Q){let z=[Q.name()].concat(Q.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${z}'`)}return q._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((q)=>this.alias(q)),this}usage($){if($===void 0){if(this._usage)return this._usage;let q=this.registeredArguments.map((Q)=>{return E1(Q)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?q:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}nameFromFilename($){return this._name=P.basename($,P.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let q=this.createHelp();if(q.helpWidth===void 0)q.helpWidth=$&&$.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return q.formatHelp(this,q)}_getHelpContext($){$=$||{};let q={error:!!$.error},Q;if(q.error)Q=(z)=>this._outputConfiguration.writeErr(z);else Q=(z)=>this._outputConfiguration.writeOut(z);return q.write=$.write||Q,q.command=this,q}outputHelp($){let q;if(typeof $==="function")q=$,$=void 0;let Q=this._getHelpContext($);this._getCommandAndAncestors().reverse().forEach((J)=>J.emit("beforeAllHelp",Q)),this.emit("beforeHelp",Q);let z=this.helpInformation(Q);if(q){if(z=q(z),typeof z!=="string"&&!Buffer.isBuffer(z))throw Error("outputHelp callback must return a string or a Buffer")}if(Q.write(z),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",Q),this._getCommandAndAncestors().forEach((J)=>J.emit("afterAllHelp",Q))}helpOption($,q){if(typeof $==="boolean"){if($)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return $=$??"-h, --help",q=q??"display help for command",this._helpOption=this.createOption($,q),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this}help($){this.outputHelp($);let q=H.exitCode||0;if(q===0&&$&&typeof $!=="function"&&$.error)q=1;this._exit(q,"commander.help","(outputHelp)")}addHelpText($,q){let Q=["beforeAll","before","after","afterAll"];if(!Q.includes($))throw Error(`Unexpected value for position to addHelpText.
|
|
23
23
|
Expecting one of '${Q.join("', '")}'`);let z=`${$}Help`;return this.on(z,(J)=>{let Y;if(typeof q==="function")Y=q({error:J.error,command:J.command});else Y=q;if(Y)J.write(`${Y}
|
|
24
|
-
`)}),this}_outputHelpIfRequested($){let q=this._getHelpOption();if(q&&$.find((z)=>q.is(z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function R0($){return $.map((q)=>{if(!q.startsWith("--inspect"))return q;let Q,z="127.0.0.1",J="9229",Y;if((Y=q.match(/^(--inspect(-brk)?)$/))!==null)Q=Y[1];else if((Y=q.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Q=Y[1],/^\d+$/.test(Y[3]))J=Y[3];else z=Y[3];else if((Y=q.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Q=Y[1],z=Y[3],J=Y[4];if(Q&&J!=="0")return`${Q}=${z}:${parseInt(J)+1}`;return q})}
|
|
25
|
-
`,{mode:384})}async function f0(){await
|
|
24
|
+
`)}),this}_outputHelpIfRequested($){let q=this._getHelpOption();if(q&&$.find((z)=>q.is(z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function R0($){return $.map((q)=>{if(!q.startsWith("--inspect"))return q;let Q,z="127.0.0.1",J="9229",Y;if((Y=q.match(/^(--inspect(-brk)?)$/))!==null)Q=Y[1];else if((Y=q.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Q=Y[1],/^\d+$/.test(Y[3]))J=Y[3];else z=Y[3];else if((Y=q.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Q=Y[1],z=Y[3],J=Y[4];if(Q&&J!=="0")return`${Q}=${z}:${parseInt(J)+1}`;return q})}j1.Command=n});var I0=D((D1)=>{var{Argument:y0}=C(),{Command:a}=L0(),{CommanderError:F1,InvalidArgumentError:E0}=k(),{Help:N1}=r(),{Option:T0}=s();D1.program=new a;D1.createCommand=($)=>new a($);D1.createOption=($,q)=>new T0($,q);D1.createArgument=($,q)=>new y0($,q);D1.Command=a;D1.Option=T0;D1.Argument=y0;D1.Help=N1;D1.CommanderError=F1;D1.InvalidArgumentError=E0;D1.InvalidOptionArgumentError=E0});import{spawnSync as u0}from"child_process";import{cpSync as c,existsSync as y,mkdirSync as f,readFileSync as u,rmSync as g}from"fs";import{mkdir as a1,readFile as e1,writeFile as o1}from"fs/promises";import{homedir as F}from"os";import{dirname as l,join as K}from"path";import{fileURLToPath as $$}from"url";var j0=t0(I0(),1),{program:H$,createCommand:R$,createArgument:L$,createOption:y$,CommanderError:E$,InvalidArgumentError:T$,InvalidOptionArgumentError:I$,Command:P0,Argument:j$,Option:P$,Help:F$}=j0.default;function o($){return $.map((q)=>Number(q.close??q.c)).filter(Number.isFinite)}function F0($,q){return $.map((Q,z)=>{if(z+1<q)return null;let J=$.slice(z+1-q,z+1);return w(J)})}function e($,q){let Q=2/(q+1),z=null;return $.map((J,Y)=>{return z=Y===0||z===null?J:J*Q+z*(1-Q),z})}function N0($,q=14){return $.map((Q,z)=>{if(z<q)return null;let J=$.slice(z+1-q,z+1).map((Z,_,U)=>_===0?0:Z-U[_-1]),Y=J.filter((Z)=>Z>0),X=J.filter((Z)=>Z<0).map(Math.abs);return 100-100/(1+w(Y)/(w(X)||0.000000001))})}function D0($){let q=e($,12),Q=e($,26),z=q.map((Y,X)=>Y-Q[X]),J=e(z,9);return z.map((Y,X)=>({macd:Y,signal:J[X],histogram:Y-J[X]}))}function V0($,q=0){let Q=$.slice(1).map((M,Z)=>M/$[Z]-1).filter(Number.isFinite),z=w(Q),J=v1(Q)*Math.sqrt(252),Y=z*252,X=J===0?null:(Y-q)/J;return{count:$.length,annualReturn:Y,volatility:J,sharpe:X,maxDrawdown:u1($)}}function w($){return $.length?$.reduce((q,Q)=>q+Q,0)/$.length:0}function v1($){let q=w($);return Math.sqrt(w($.map((Q)=>(Q-q)**2)))}function u1($){let q=$[0]??0,Q=0;for(let z of $)q=Math.max(q,z),Q=Math.min(Q,z/q-1);return Q}import{mkdir as g1,readFile as c1,rm as l1,writeFile as m1}from"fs/promises";import{dirname as d1,join as S0}from"path";var w0=process.env.HOME??process.cwd(),V=S0(w0,".config","mozyfin-cli","config.json"),O=S0(w0,".config","mozyfin-cli","version-cache.json"),x="https://api.mozyfin.com";async function $0(){try{return JSON.parse(await c1(V,"utf8"))}catch{return{}}}async function A0($){await g1(d1(V),{recursive:!0}),await m1(V,`${JSON.stringify($,null,2)}
|
|
25
|
+
`,{mode:384})}async function f0(){await l1(V,{force:!0})}async function b0($){let q=await $0();return $??process.env.MOZYFIN_API_KEY??q.apiKey}function h(){return"Missing API key. Run `mozyfin login --api-key <key>` or create one at https://research.mozyfin.com/settings"}var k0=0;async function r1($=Date.now()){let q=Math.max(0,1000-($-k0));if(q>0)await new Promise((Q)=>setTimeout(Q,q));k0=Date.now()}function s1($,q,Q={}){let z=new URL(q,$);for(let[J,Y]of Object.entries(Q)){if(Y===void 0||Y==="")continue;if(Array.isArray(Y))for(let X of Y)z.searchParams.append(J,X);else z.searchParams.set(J,String(Y))}return z}function i1($){let q=$?.data?.t;return Array.isArray(q)&&q.length>0}function q0($){let q=$?.data;if(!q||!Array.isArray(q.t))return $;let Q=q.t.map((z,J)=>({timestamp:z,open:q.o?.[J],high:q.h?.[J],low:q.l?.[J],close:q.c?.[J],volume:q.v?.[J]}));return Q.reverse(),{...$,data:Q}}class v{baseUrl;apiKey;constructor($={}){this.baseUrl=$.baseUrl??x,this.apiKey=$.apiKey}static async fromConfig($){let q=await $0();return new v({baseUrl:q.baseUrl??x,apiKey:await b0($)})}async request($,q={}){if(q.auth!==!1&&!this.apiKey)throw Error(h());await r1();let Q=await fetch(s1(this.baseUrl,$,q.query),{method:q.method??"GET",headers:{"content-type":"application/json",...this.apiKey?{"X-API-Key":this.apiKey,authorization:`Bearer ${this.apiKey}`}:{}},body:q.body?JSON.stringify(q.body):void 0}),z=await Q.text(),J=z?JSON.parse(z):null;if(!Q.ok)throw Error(J?.message??J?.detail??`HTTP ${Q.status}`);return J}entities($){return this.request("/api/v1/market/exchange/entity",{query:$})}entity($){return this.request(`/api/v1/market/exchange/entity/${$}`)}news($){return this.request("/api/v1/news",{query:$})}marketIndices(){return this.request("/api/v1/market/market-index")}async ohlcv($,q){let Q=null,z=null;try{if(Q=await this.request(`/api/v2/market/exchange/entity/${$}/ohlcv`,{query:q}),i1(Q))return q0(Q)}catch(J){z=J}try{let J=await this.request(`/api/v2/market/market-index/${$}/ohlcv`,{query:q});return q0(J)}catch(J){if(Q)return q0(Q);throw z??J}}historicalQuote($,q){return this.request(`/api/v1/market/exchange/entity/${$}/historical-quote`,{query:q})}offices($){return this.request(`/api/v1/market/exchange/entity/${$}/office`)}subsidiaries($){return this.request(`/api/v1/market/exchange/entity/${$}/subsidiary`)}holders($,q){return this.request(`/api/v1/market/exchange/entity/${$}/holder`,{query:q})}holderTransactions($,q){return this.request(`/api/v1/market/exchange/entity/${$}/holder-transaction`,{query:q})}financialStatements($,q){return this.request(`/api/v1/market/exchange/entity/${$}/financial-statement`,{query:q})}financialStatistics($,q){return this.request(`/api/v1/market/exchange/entity/${$}/financial-statistic`,{query:q})}usage(){return this.request("/api/v1/subscription/usage")}createChat(){return this.request("/api/v1/chat",{method:"POST",body:{title:"mozyfin-cli",mode:"auto"}})}sendMessage($,q){return this.request(`/api/v1/chat/${$}/message`,{method:"POST",body:{content:q}})}getMessage($){return this.request(`/api/v1/chat/messages/${$}`)}queryReport($){return this.request("/api/v1/document/query-report",{method:"POST",body:{query:$}})}}import{writeFile as p1}from"fs/promises";function Q0($){return $?.data??$?.result??$}function j($){let q=Q0($);if(Array.isArray(q))return q;if(Array.isArray(q?.items))return q.items;if(Array.isArray(q?.results))return q.results;if(Array.isArray(q?.data))return q.data;return q?[q]:[]}function S($){let q=j($);if(q.length===0)return"_No data_";return z0(q,Object.keys(q[0]).slice(0,8))}function z0($,q){let Q=j($);if(Q.length===0)return"_No data_";let z=q.filter((M)=>Q.some((Z)=>Z?.[M]!==void 0));if(z.length===0)return S($);let J=`| ${z.join(" | ")} |`,Y=`| ${z.map(()=>"---").join(" | ")} |`,X=Q.map((M)=>`| ${z.map((Z)=>O0(M?.[Z])).join(" | ")} |`).join(`
|
|
26
26
|
`);return`${J}
|
|
27
27
|
${Y}
|
|
28
28
|
${X}`}function x0($,q){let[Q]=j($);if(!Q)return"_No data_";return(q?.filter((J)=>Q[J]!==void 0)??Object.keys(Q)).map((J)=>`- ${J}: ${O0(Q[J])}`).join(`
|
|
29
|
-
`)}function C0($,q="content"){let Q=j($)[0]??Q0($);return Q?.[q]??Q?.message?.[q]??Q?.data?.[q]??"_No content_"}function O0($){if($===null||$===void 0)return"";if(typeof $==="object"){let q=$,Q=q.symbol??q.id??q.name??q.title;if(Q!==void 0)return String(Q).replaceAll("|","\\|");return JSON.stringify($).replaceAll("|","\\|").slice(0,120)}return String($).replaceAll("|","\\|")}function
|
|
30
|
-
`)}function
|
|
29
|
+
`)}function C0($,q="content"){let Q=j($)[0]??Q0($);return Q?.[q]??Q?.message?.[q]??Q?.data?.[q]??"_No content_"}function O0($){if($===null||$===void 0)return"";if(typeof $==="object"){let q=$,Q=q.symbol??q.id??q.name??q.title;if(Q!==void 0)return String(Q).replaceAll("|","\\|");return JSON.stringify($).replaceAll("|","\\|").slice(0,120)}return String($).replaceAll("|","\\|")}function t1($){let q=j($);if(q.length===0)return"";let Q=Array.from(new Set(q.flatMap((z)=>Object.keys(z))));return[Q.join(","),...q.map((z)=>Q.map((J)=>n1(z[J])).join(","))].join(`
|
|
30
|
+
`)}function n1($){let q=$===null||$===void 0?"":typeof $==="object"?JSON.stringify($):String($);return/[",\n]/.test(q)?`"${q.replaceAll('"','""')}"`:q}function h0($){let q=Q0($),Q=[],z=q?.entities??[];if(z.length>0)Q.push(`### Entities (${z.length})
|
|
31
31
|
|
|
32
32
|
${S(z)}`);let J=q?.relationships??[];if(J.length>0)Q.push(`
|
|
33
33
|
### Relationships (${J.length})
|
|
@@ -42,8 +42,8 @@ ${S(X)}`);if(q?.instructions)Q.push(`
|
|
|
42
42
|
### Context
|
|
43
43
|
|
|
44
44
|
${q.instructions}`);return Q.length>0?Q.join(`
|
|
45
|
-
`):"_No data_"}async function A($,q){if(q.csv){await
|
|
46
|
-
`),console.log(S([{ok:!0,file:q.csv,rows:j($).length}]));return}console.log(S($))}var J0=l(
|
|
45
|
+
`):"_No data_"}async function A($,q){if(q.csv){await p1(q.csv,`${t1($)}
|
|
46
|
+
`),console.log(S([{ok:!0,file:q.csv,rows:j($).length}]));return}console.log(S($))}var J0=l($$(import.meta.url)),Y0=JSON.parse(u(K(J0,"..","package.json"),"utf8")),B=new P0;B.name("mozyfin").description("Vietnam stock market CLI for humans and AI agents").version(Y0.version).showHelpAfterError().addHelpText("after",`
|
|
47
47
|
|
|
48
48
|
Examples:
|
|
49
49
|
$ mozyfin login --api-key <key>
|
|
@@ -53,7 +53,7 @@ Examples:
|
|
|
53
53
|
$ mozyfin ta VNM.VN --sma 20,50 --rsi 14 --macd --csv vnm-ta.csv
|
|
54
54
|
$ mozyfin doc "VNM Q4 2024 earnings analysis"
|
|
55
55
|
$ mozyfin ask "compare VNM and MSN margin trend"
|
|
56
|
-
`).option("--api-key <key>","API key, or set MOZYFIN_API_KEY").option("--base-url <url>","API base URL",x).option("--no-color","reserved for scripts/agents; output stays plain text");function E($){return $.option("-m, --md","print Markdown table (default)").option("--csv <file>","write rows to CSV file")}async function R(){let $=B.opts(),q=await v.fromConfig($.apiKey);if(q.baseUrl=$.baseUrl,!q.apiKey)throw Error(h());return q}function v0($){if(!$)return;let q=$.split(",").map((Q)=>Q.trim()).filter(Boolean);return q.length?q:void 0}function g0($,q,Q){if(!q.includes($))throw Error(`${Q} must be one of: ${q.join(", ")}`);return $}async function I($,q,Q){if(q.csv)return A($,q);console.log(z0($,Q))}async function M0($,q,Q){if(q.csv)return A($,q);console.log(x0($,Q))}function
|
|
56
|
+
`).option("--api-key <key>","API key, or set MOZYFIN_API_KEY").option("--base-url <url>","API base URL",x).option("--no-color","reserved for scripts/agents; output stays plain text");function E($){return $.option("-m, --md","print Markdown table (default)").option("--csv <file>","write rows to CSV file")}async function R(){let $=B.opts(),q=await v.fromConfig($.apiKey);if(q.baseUrl=$.baseUrl,!q.apiKey)throw Error(h());return q}function v0($){if(!$)return;let q=$.split(",").map((Q)=>Q.trim()).filter(Boolean);return q.length?q:void 0}function g0($,q,Q){if(!q.includes($))throw Error(`${Q} must be one of: ${q.join(", ")}`);return $}async function I($,q,Q){if(q.csv)return A($,q);console.log(z0($,Q))}async function M0($,q,Q){if(q.csv)return A($,q);console.log(x0($,Q))}function q$($){return j($).map((q)=>{let Q=q.values??{};return{year:q.year,quarter:q.quarter,type:q.type,net_sales:Q["Net sales"]??Q.Sales,gross_profit:Q["Gross Profit"],profit_after_tax:Q["Net profit/(loss) after tax"],total_assets:Q["Total Assets"],owner_equity:Q["Owner's Equity"],net_operating_cash_flow:Q["Net cash inflows/(outflows) from operating activities"],public_at:q.public_at}})}B.command("login").description("Save API key locally").option("--api-key <key>").action(async($)=>{let q=$.apiKey??B.opts().apiKey;if(!q)throw Error("Missing --api-key <key>");await A0({apiKey:q,baseUrl:B.opts().baseUrl}),await A([{ok:!0,configPath:V}],{})});B.command("logout").description("Remove saved API key").action(async()=>{await f0(),await A([{ok:!0}],{})});E(B.command("search").description("Search companies/entities by ticker, name or text")).option("-q, --query [text]","search query; empty means all","").action(async($)=>I(await(await R()).entities({search:$.query}),$,["symbol","ticker","name","exchange","market","price","market_cap","id"]));E(B.command("profile").argument("<tickerOrEntityId>").description("Company profile/entity details")).action(async($,q)=>M0(await(await R()).entity($),q,["symbol","ticker","name","exchange","market","sector","industry","website","description","entity_id","id"]));E(B.command("news").description("Market headlines and article search")).option("--query <text>","search query; empty means all","").option("--entities <ids>","comma-separated entity ids; OR semantics").option("--topics <topics>","comma-separated topics: stock,crypto,forex,tariff,economic,earning,tech,housing,mergers_and_ipo; OR semantics").option("--limit <n>","max rows","20").option("--page <n>","page hint for APIs that support it","1").action(async($)=>I(await(await R()).news(Q$($)),$,["published_at","created_at","title","source","topics","entities","url","id"]));function Q$($){let q=["stock","crypto","forex","tariff","economic","earning","tech","housing","mergers_and_ipo"],Q=v0($.topics);for(let z of Q??[])g0(z,q,"topic");return{search:$.query,entities:v0($.entities),topics:Q,limit:$.limit,page:$.page}}E(B.command("indices").description("List supported market indices (use the returned id with `ohlcv`)")).action(async($)=>I(await(await R()).marketIndices(),$,["symbol","name","current_value","change_value","change_percent","id"]));E(B.command("ohlcv").argument("<entity>").description("Historical OHLCV candles")).option("--timeframe <value>","1h, 1d, 1w, 1mo, 1y","1d").option("--to <timestamp>","end timestamp").option("--limit <n>","max rows").action(async($,q)=>{return g0(q.timeframe,["1h","1d","1w","1mo","1y"],"timeframe"),I(await(await R()).ohlcv($,q),q,["timestamp","time","date","open","high","low","close","volume"])});E(B.command("quote").argument("<entity>").description("Latest daily quote snapshot")).option("--to <timestamp>","end timestamp").option("--limit <n>","max rows","1").action(async($,q)=>I(await(await R()).historicalQuote($,{to:q.to,limit:q.limit}),q,["timestamp","total_volume","deal_volume","total_value","buy_foreign_quantity","sell_foreign_quantity","current_foreign_room"]));E(B.command("officers").argument("<entity>").description("Company officers/directors")).action(async($,q)=>I(await(await R()).offices($),q,["name","position","is_foreigner","sort_order"]));E(B.command("subsidiary").argument("<entity>").description("Company subsidiaries")).action(async($,q)=>I(await(await R()).subsidiaries($),q,["name","symbol","ownership_rate","charter_capital","business_area","id"]));E(B.command("holder").argument("<entity>").description("Major shareholders")).option("--is-organization <true|false>","filter organization holders").option("--is-foreigner <true|false>","filter foreign holders").action(async($,q)=>I(await(await R()).holders($,{is_organization:q.isOrganization,is_foreigner:q.isForeigner}),q,["name","holder_name","ownership_rate","shares","is_organization","is_foreigner"]));E(B.command("holder-tx").argument("<entity>").description("Shareholder transactions")).option("--cursor <cursor>","pagination cursor").option("--limit <n>","max rows","100").option("--transaction-type <type>","transaction type filter").action(async($,q)=>I(await(await R()).holderTransactions($,{cursor:q.cursor,limit:q.limit,transaction_type:q.transactionType}),q,["name","type","registered_volume","execution_volume","start_at","end_at","position"]));E(B.command("financials").argument("<entity>").description("Financial statements")).option("--year <year>","report year").option("--quarter <quarter>","report quarter").option("--statement-type <type>","statement type filter").action(async($,q)=>I(q$(await(await R()).financialStatements($,{year:q.year,quarter:q.quarter,statement_type:q.statementType})),q,["year","quarter","type","net_sales","gross_profit","profit_after_tax","total_assets","owner_equity","net_operating_cash_flow"]));E(B.command("stats").argument("<entity>").description("Financial statistics/ratios")).option("--year <year>","report year").option("--quarter <quarter>","report quarter").action(async($,q)=>I(await(await R()).financialStatistics($,{year:q.year,quarter:q.quarter}),q,["year","quarter","pe","pb","roe","roa","gross_margin","market_cap"]));E(B.command("ta").argument("<tickerOrEntityId>").description("Technical indicators over OHLCV close prices")).option("--sma <list>","comma-separated SMA periods","20").option("--rsi <n>","RSI period").option("--macd","include MACD").option("--limit <n>","max candles","300").action(async($,q)=>{let Q=await(await R()).ohlcv($,{timeframe:"1d",limit:q.limit}),J=[...j(Q)].reverse(),Y=o(J),X=String(q.sma).split(",").map(Number).filter(Number.isFinite),M=Object.fromEntries(X.map((W)=>[W,F0(Y,W)])),Z=q.rsi?N0(Y,Number(q.rsi)):[],_=q.macd?D0(Y):[],U=J.map((W,L)=>({...W,...Object.fromEntries(X.map((G)=>[`sma_${G}`,M[G][L]])),...q.rsi?{[`rsi_${q.rsi}`]:Z[L]}:{},...q.macd?_[L]:{}})).reverse();await I(U,q,["timestamp","time","date","close",...X.map((W)=>`sma_${W}`),...q.rsi?[`rsi_${q.rsi}`]:[],...q.macd?["macd","signal","histogram"]:[]])});B.command("risk").argument("<tickerOrEntityId>").description("Risk/performance metrics: return, volatility, Sharpe, max drawdown").option("--limit <n>","max candles","252").option("--risk-free <n>","annual risk-free rate","0").action(async($,q)=>{let Q=await(await R()).ohlcv($,{timeframe:"1d",limit:q.limit});await M0([V0(o([...j(Q)].reverse()),Number(q.riskFree))],{},["count","annualReturn","volatility","sharpe","maxDrawdown"])});B.command("doc").argument("<query...>").description("Query analysis reports using natural language").action(async($)=>{let q=await(await R()).queryReport($.join(" "));console.log(h0(q))});B.command("ask").argument("<prompt...>").description("Ask Mozyfin agent in auto mode (one focused question per call \u2014 avoid multi-question prompts)").option("--timeout <seconds>","max wait time in seconds (default 300 = 5 minutes)","300").action(async($,q)=>{let Q=await R(),z=await Q.createChat(),J=z?.data?.id??z?.id;if(!J)throw Error("Could not create chat");let X=await Q.sendMessage(J,$.join(" ")),M=X?.data?.id??X?.id,Z=Date.now()+Number(q.timeout)*1000;while(M&&Date.now()<Z){let _=X?.data?.status??X?.status;if(_&&_!=="thinking"&&_!=="streaming")break;await new Promise((U)=>setTimeout(U,2000)),X=await Q.getMessage(M)}console.log(C0(X))});B.command("credits").description("Check subscription usage/credits").action(async()=>M0(await(await R()).usage(),{},["credits_used","credits_cap","remaining","plan"]));B.command("doctor").description("Check runtime, config and API health").action(async()=>{let $=u0("bun",["--version"],{encoding:"utf8"}).stdout.trim(),q=await R(),Q=await q.request("/health",{auth:!1});await A([{bun:$,configPath:V,baseUrl:q.baseUrl,health:Q}],{})});B.command("update").description("Upgrade CLI to latest version; auto-updates skills for any agents that already have it installed").option("--skill [agent]","Force update skill for specific agent (claude, cursor, copilot, windsurf, codex, gemini, hermes, openclaw, or 'all')").action(async($)=>{let q=B.version(),Q=await fetch("https://registry.npmjs.org/mozyfin-cli/latest").then((X)=>X.json()).then((X)=>X.version).catch(()=>null);if(console.log(`Current version: ${q}`),Q)if(console.log(`Latest version: ${Q}`),q===Q)console.log(`
|
|
57
57
|
You're already on the latest version!`);else if(console.log(`
|
|
58
58
|
Updating CLI...`),u0("npm",["install","-g","mozyfin-cli@latest"],{encoding:"utf8",stdio:"inherit"}).status===0)console.log(`
|
|
59
59
|
\u2713 CLI updated successfully!`);else console.log(`
|
|
@@ -66,11 +66,11 @@ ${U}
|
|
|
66
66
|
<!-- /${J} -->
|
|
67
67
|
`;T("fs").writeFileSync(Z,G),console.log(`\u2713 Updated skill for ${X}`)}else if(_==="file"){f(Z,{recursive:!0});let U=K(Z,`${J}.md`);c(K(z,"SKILL.md"),U),console.log(`\u2713 Updated skill for ${X}`)}else if(_==="directory"){let U=K(Z,J);g(U,{recursive:!0,force:!0}),f(Z,{recursive:!0}),c(z,U,{recursive:!0}),console.log(`\u2713 Updated skill for ${X}`)}}catch(U){console.log(`\u2717 Failed to update skill for ${X}: ${U}`)}}});var b={claude:{path:K(F(),".claude","skills"),format:"directory"},cursor:{path:K(F(),".cursor","commands"),format:"file"},copilot:{path:K(F(),".github","copilot-instructions.md"),format:"append"},windsurf:{path:K(F(),".windsurf","workflows"),format:"file"},codex:{path:K(F(),".agents","skills"),format:"directory"},gemini:{path:K(F(),".gemini","instructions"),format:"file"},hermes:{path:K(F(),".hermes","skills"),format:"directory"},openclaw:{path:K(F(),".openclaw","skills"),format:"directory"},antigravity:{path:K(F(),".gemini","antigravity","skills"),format:"directory"}};B.command("skill").description("Install mozyfin-cli skill into AI agents (claude, cursor, copilot, windsurf, codex, gemini, hermes, openclaw, antigravity)").argument("[agent]","Target agent (claude, cursor, copilot, windsurf, codex, gemini, hermes, openclaw, antigravity) or 'all'").option("--list","List available agents").option("--remove","Remove skill from agent").action(($,q)=>{let Q=K(J0,"..","agent-skills","mozyfin-cli"),z="mozyfin-cli";if(q.list){console.log(`Available agents:
|
|
68
68
|
`);for(let[Y,X]of Object.entries(b)){let M=!1;if(X.format==="directory")M=y(K(X.path,"mozyfin-cli","SKILL.md"));else if(X.format==="file")M=y(K(X.path,"mozyfin-cli.md"));else if(X.format==="append"){if(y(X.path))M=T("fs").readFileSync(X.path,"utf8").includes("<!-- mozyfin-cli -->")}console.log(` ${Y.padEnd(10)} ${M?"\u2713 installed":"\u25CB not installed"}`),console.log(` ${X.path}`)}return}if(!$){console.log("Usage: mozyfin skill <agent>"),console.log(`
|
|
69
|
-
Available agents: claude, cursor, copilot, windsurf, codex, gemini, hermes, openclaw, all`),console.log(`
|
|
70
|
-
Options:`),console.log(" --list List available agents"),console.log(" --remove Remove skill from agent");return}let J=$==="all"?Object.keys(b):[$];for(let Y of J){let X=b[Y];if(!X){console.log(`Unknown agent: ${Y}`),console.log("Available: claude, cursor, copilot, windsurf, codex, gemini, hermes, openclaw");continue}let{path:M,format:Z}=X;if(q.remove){if(Z==="append")if(y(M)){let U=T("fs").readFileSync(M,"utf8").replace(new RegExp("<!-- mozyfin-cli -->[\\s\\S]*<!-- /mozyfin-cli -->","g"),"").trim();T("fs").writeFileSync(M,U),console.log(`\u2713 Removed skill from ${Y}`)}else console.log(`Skill not installed in ${Y}`);else if(Z==="file"){let _=K(M,"mozyfin-cli.md");if(y(_))g(_),console.log(`\u2713 Removed skill from ${Y}`);else console.log(`Skill not installed in ${Y}`)}else if(Z==="directory"){let _=K(M,"mozyfin-cli");if(y(_))g(_,{recursive:!0,force:!0}),console.log(`\u2713 Removed skill from ${Y}`);else console.log(`Skill not installed in ${Y}`)}continue}if(!y(Q)){console.log(`Skill directory not found: ${Q}`);continue}if(Z==="append"){f(l(M),{recursive:!0});let _=T("fs").readFileSync(K(Q,"SKILL.md"),"utf8"),L=`${(y(M)?T("fs").readFileSync(M,"utf8"):"").replace(new RegExp("<!-- mozyfin-cli -->[\\s\\S]*<!-- /mozyfin-cli -->","g"),"").trim()}
|
|
69
|
+
Available agents: claude, cursor, copilot, windsurf, codex, gemini, hermes, openclaw, antigravity, all`),console.log(`
|
|
70
|
+
Options:`),console.log(" --list List available agents"),console.log(" --remove Remove skill from agent");return}let J=$==="all"?Object.keys(b):[$];for(let Y of J){let X=b[Y];if(!X){console.log(`Unknown agent: ${Y}`),console.log("Available: claude, cursor, copilot, windsurf, codex, gemini, hermes, openclaw, antigravity");continue}let{path:M,format:Z}=X;if(q.remove){if(Z==="append")if(y(M)){let U=T("fs").readFileSync(M,"utf8").replace(new RegExp("<!-- mozyfin-cli -->[\\s\\S]*<!-- /mozyfin-cli -->","g"),"").trim();T("fs").writeFileSync(M,U),console.log(`\u2713 Removed skill from ${Y}`)}else console.log(`Skill not installed in ${Y}`);else if(Z==="file"){let _=K(M,"mozyfin-cli.md");if(y(_))g(_),console.log(`\u2713 Removed skill from ${Y}`);else console.log(`Skill not installed in ${Y}`)}else if(Z==="directory"){let _=K(M,"mozyfin-cli");if(y(_))g(_,{recursive:!0,force:!0}),console.log(`\u2713 Removed skill from ${Y}`);else console.log(`Skill not installed in ${Y}`)}continue}if(!y(Q)){console.log(`Skill directory not found: ${Q}`);continue}if(Z==="append"){f(l(M),{recursive:!0});let _=T("fs").readFileSync(K(Q,"SKILL.md"),"utf8"),L=`${(y(M)?T("fs").readFileSync(M,"utf8"):"").replace(new RegExp("<!-- mozyfin-cli -->[\\s\\S]*<!-- /mozyfin-cli -->","g"),"").trim()}
|
|
71
71
|
|
|
72
72
|
<!-- mozyfin-cli -->
|
|
73
73
|
${_}
|
|
74
74
|
<!-- /mozyfin-cli -->
|
|
75
|
-
`;T("fs").writeFileSync(M,L),console.log(`\u2713 Installed skill to ${Y}`)}else if(Z==="file"){f(M,{recursive:!0});let _=K(M,"mozyfin-cli.md");c(K(Q,"SKILL.md"),_),console.log(`\u2713 Installed skill to ${Y}`)}else if(Z==="directory"){let _=K(M,"mozyfin-cli");g(_,{recursive:!0,force:!0}),f(M,{recursive:!0}),c(Q,_,{recursive:!0}),console.log(`\u2713 Installed skill to ${Y}`)}}});var
|
|
76
|
-
\u26A0\uFE0F mozyfin-cli v${Q} is outdated (latest: v${q}). Run \`mozyfin update\` to upgrade.`)}B.parseAsync().catch(($)=>{console.error(`Error: ${$.message}`),process.exitCode=1}).finally(()=>
|
|
75
|
+
`;T("fs").writeFileSync(M,L),console.log(`\u2713 Installed skill to ${Y}`)}else if(Z==="file"){f(M,{recursive:!0});let _=K(M,"mozyfin-cli.md");c(K(Q,"SKILL.md"),_),console.log(`\u2713 Installed skill to ${Y}`)}else if(Z==="directory"){let _=K(M,"mozyfin-cli");g(_,{recursive:!0,force:!0}),f(M,{recursive:!0}),c(Q,_,{recursive:!0}),console.log(`\u2713 Installed skill to ${Y}`)}}});var z$=86400000;async function J$(){try{let $=new AbortController,q=setTimeout(()=>$.abort(),1000),Q=await fetch("https://registry.npmjs.org/mozyfin-cli/latest",{signal:$.signal});clearTimeout(q);let z=await Q.json();if(!z.version)return null;return await a1(l(O),{recursive:!0}),await o1(O,JSON.stringify({latestVersion:z.version,checkedAt:Date.now()})),z.version}catch{return null}}async function Y$(){try{let $=JSON.parse(await e1(O,"utf8"));if($?.latestVersion&&Date.now()-($.checkedAt??0)<z$&&c0(Y0.version,$.latestVersion)<=0)return $.latestVersion}catch{}return J$()}function c0($,q){let Q=$.split(".").map((J)=>Number.parseInt(J,10)||0),z=q.split(".").map((J)=>Number.parseInt(J,10)||0);for(let J=0;J<3;J++){let Y=(Q[J]??0)-(z[J]??0);if(Y!==0)return Y}return 0}async function M$(){if(process.env.MOZYFIN_DISABLE_UPDATE_CHECK)return;if(process.argv.slice(2).find((z)=>!z.startsWith("-"))==="update")return;let q=await Y$(),Q=Y0.version;if(q&&c0(Q,q)<0)console.error(`
|
|
76
|
+
\u26A0\uFE0F mozyfin-cli v${Q} is outdated (latest: v${q}). Run \`mozyfin update\` to upgrade.`)}B.parseAsync().catch(($)=>{console.error(`Error: ${$.message}`),process.exitCode=1}).finally(()=>M$());
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mozyfin-cli",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.11",
|
|
4
4
|
"description": "Human- and agent-friendly CLI for Vietnamese market data via Mozyfin/Antofin APIs.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -38,5 +38,5 @@
|
|
|
38
38
|
"bugs": {
|
|
39
39
|
"url": "https://github.com/onlyai-team/mozyfin-cli/issues"
|
|
40
40
|
},
|
|
41
|
-
"homepage": "https://
|
|
41
|
+
"homepage": "https://cli.mozyfin.com"
|
|
42
42
|
}
|