@ivora/cli 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Ivora
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,121 @@
1
- # Temporary Holding Version
1
+ # Ivora CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `ivora` is the command-line client for the public Ivora `/v1` API. It is meant for developers
4
+ and operators who manage charging stations, run OCPP diagnostics, test webhooks and migrate
5
+ charger networks from a terminal or a script.
6
+
7
+ The package will be published on npm as `@ivora/cli`, with the command `ivora`.
8
+
9
+ ## Status
10
+
11
+ **v0.1 (first release, read-only).** This repository holds the build, test and CI setup and the shared
12
+ library stubs (HTTP client, output, profiles, secret redaction, confirmations). Implemented so
13
+ far: `ivora login`, `ivora profiles`, `ivora whoami` and the read-only resource commands below. Nothing has been published to npm. Do not use it against a live
14
+ account.
15
+
16
+ Planned for the first release (v0.1):
17
+
18
+ - `ivora login` with an API key, profiles for the test and live environments, `ivora whoami`
19
+ - station resources: list, show, add, connect, decommission
20
+ - remote commands: trigger, reset, unlock, start, stop, with confirmations
21
+ - `ivora logs tail` (OCPP message log) and `ivora listen` (forward webhook events to a local URL)
22
+ - tariff quotes and simulations, webhook endpoints, and `ivora api` for any public `/v1` path
23
+
24
+ The CLI only calls the public `/v1` API. It has no staff or admin commands.
25
+
26
+ ## Authentication
27
+
28
+ ```sh
29
+ printf '%s' "$KEY" | ivora login # or type it at the hidden prompt
30
+ ivora --live login # live is an explicit opt-in
31
+ ivora whoami
32
+ ivora profiles list | use <name> | remove <name>
33
+ ```
34
+
35
+ - Keys are never accepted as command-line arguments. `ivora login` reads one from stdin, a
36
+ hidden prompt or `IVORA_API_KEY`, checks it with `GET /v1/access`, and stores it in the OS
37
+ keychain (macOS Keychain, or `secret-tool` on Linux). If there is no keychain the CLI refuses
38
+ to save the key rather than writing it to disk; use `IVORA_API_KEY` instead.
39
+ - The config file (`~/.config/ivora/config.toml`) holds profile names, environments and key
40
+ references only, never keys.
41
+ - Test keys (`iv_test_`) work with test profiles and live keys (`iv_live_`) with live profiles.
42
+ A live profile is never the default: pass `--live` (or `--profile <name>`) every time.
43
+
44
+ ## Read-only resources
45
+
46
+ ```sh
47
+ ivora stations list [--name N] [--charger-id ID] [--limit N] [--after CURSOR] [--all]
48
+ ivora stations get <station-id>
49
+ ivora operations list [--status S] [--kind K] [--actor A] [--station-id ID] [--before CURSOR]
50
+ ivora operations get <operation-id>
51
+ ivora tariffs list [--include-archived] | get <tariff-id>
52
+ ivora tariffs quote <tariff-id> --session session.json # a read-only price computation
53
+ ivora tariffs simulate --tariff tariff.json --session session.json
54
+ ivora webhooks list | get <webhook-id>
55
+ ivora api # list the callable operationIds
56
+ ivora api locations_read_one_location --path location_id=1
57
+ ```
58
+
59
+ - Output is a table by default and JSON with `--json`. List commands show one page and print the
60
+ next cursor on stderr; `--all` follows every page. In `--json` output `next_cursor` is `null`
61
+ once the listing has reached its end.
62
+ - With `--json`, results go to stdout as JSON; errors stay plain text on stderr
63
+ (`error: ...`), and the exit code tells scripts what happened.
64
+ - Commands use the key's only tenant, or `--tenant <id>` when it reaches several.
65
+ - `ivora api <operationId>` calls only GET operations from the built-in catalog and prints JSON.
66
+ Anything that writes or controls a charger is refused until after the first publish.
67
+ - Exit codes: 0 ok, 1 API or network error, 2 usage, 4 timeout, 5 authentication. Errors show the
68
+ API's error code and request id.
69
+
70
+ ## Install from source
71
+
72
+ Requirements: Node.js 22.12 or later and npm.
73
+
74
+ ```sh
75
+ git clone https://github.com/Ivora-Charge/ivora-cli.git
76
+ cd ivora-cli
77
+ npm ci
78
+ npm run build
79
+ node dist/bin/ivora.js --help
80
+
81
+ # optional: put `ivora` on your PATH
82
+ npm link
83
+ ivora --version
84
+ ```
85
+
86
+ The default API endpoint is `https://api.ivoracharge.com`. Set `IVORA_API_BASE` (or
87
+ `ivora login --base-url`) to point a test profile at another environment. Live profiles ignore
88
+ `IVORA_API_BASE`, so a leftover test URL never receives a live key; a live profile uses the URL
89
+ stored with `ivora --live login --base-url` or the default.
90
+
91
+ ## Development
92
+
93
+ ```sh
94
+ npm ci # install the locked dependencies
95
+ npm run build # type-check and compile src/ to dist/
96
+ npm test # unit tests and the mock /v1 server tests (no network)
97
+ npm run lint # ESLint and Prettier checks
98
+ npm run format # apply Prettier
99
+ ```
100
+
101
+ Tests use the Node.js built-in test runner (`node:test`) against a local mock of the `/v1`
102
+ API in `test/mock-server.ts`. No test talks to a real API.
103
+
104
+ ## Contributing
105
+
106
+ Issues and pull requests are welcome. Before you open a pull request:
107
+
108
+ - run `npm run build`, `npm test` and `npm run lint`;
109
+ - keep dependencies few, and do not add packages with install scripts;
110
+ - never include API keys, station passwords, webhook secrets or customer data in code, tests,
111
+ fixtures or issues. Use obviously fake values in tests.
112
+
113
+ By contributing you agree that your contribution is licensed under the Apache License 2.0.
114
+
115
+ ## Security
116
+
117
+ Please do not report security problems in public issues. See [SECURITY.md](SECURITY.md).
118
+
119
+ ## License
120
+
121
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../cli.js';
3
+ process.exitCode = await run(process.argv.slice(2));
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The command catalog: every (method, path) in the API spec is either mapped to a command or
3
+ * excluded with a reason. The catalog test fails on a spec operation that is neither, so a new
4
+ * API operation is a deliberate decision. Resource commands fill this in from the OpenAPI
5
+ * snapshot; the scaffold lists only the operations the first commands use.
6
+ */
7
+ const T = '/v1/tenants/{tenant_id}';
8
+ export const COMMANDS = [
9
+ {
10
+ method: 'GET',
11
+ path: '/v1/access',
12
+ command: 'whoami',
13
+ operationId: 'access_and_api_keys_discover_current_csms_access',
14
+ },
15
+ {
16
+ method: 'GET',
17
+ path: '/v1/capabilities',
18
+ command: 'whoami',
19
+ operationId: 'getting_started_capabilities',
20
+ },
21
+ {
22
+ method: 'GET',
23
+ path: `${T}/stations`,
24
+ command: 'stations list',
25
+ operationId: 'stations_list_tenant_charging_stations',
26
+ },
27
+ {
28
+ method: 'GET',
29
+ path: `${T}/stations/{station_id}`,
30
+ command: 'stations get',
31
+ operationId: 'stations_read_station_and_connector_state',
32
+ },
33
+ {
34
+ method: 'POST',
35
+ path: `${T}/stations`,
36
+ command: 'stations add',
37
+ operationId: 'stations_register_a_station_and_return_it',
38
+ },
39
+ {
40
+ method: 'GET',
41
+ path: `${T}/tariffs`,
42
+ command: 'tariffs list',
43
+ operationId: 'tariffs_and_bills_read_tenant_billing_tariffs',
44
+ },
45
+ {
46
+ method: 'GET',
47
+ path: `${T}/tariffs/{tariff_id}`,
48
+ command: 'tariffs get',
49
+ operationId: 'tariffs_and_bills_read_one_tariff',
50
+ },
51
+ {
52
+ method: 'POST',
53
+ path: `${T}/tariffs/{tariff_id}/quote`,
54
+ command: 'tariffs quote',
55
+ operationId: 'tariffs_and_bills_quote_a_session_s_cost_under_a_stored_tariff',
56
+ },
57
+ {
58
+ method: 'POST',
59
+ path: `${T}/tariffs/simulate`,
60
+ command: 'tariffs simulate',
61
+ operationId: 'tariffs_and_bills_simulate_a_tariff_draft_against_a_session',
62
+ },
63
+ {
64
+ method: 'GET',
65
+ path: `${T}/operations`,
66
+ command: 'operations list',
67
+ operationId: 'charging_and_operations_list_the_project_s_operations',
68
+ },
69
+ {
70
+ method: 'GET',
71
+ path: `${T}/operations/{operation_id}`,
72
+ command: 'operations get',
73
+ operationId: 'charging_and_operations_inspect_an_operation_without_redispatching_it',
74
+ },
75
+ {
76
+ method: 'GET',
77
+ path: `${T}/webhooks`,
78
+ command: 'webhooks list',
79
+ operationId: 'webhooks_and_events_list_webhook_endpoints',
80
+ },
81
+ {
82
+ method: 'GET',
83
+ path: `${T}/webhooks/{webhook_id}`,
84
+ command: 'webhooks get',
85
+ operationId: 'webhooks_and_events_read_one_webhook_endpoint',
86
+ },
87
+ // Other read-only (GET) operations, reachable through `ivora api <operationId>`.
88
+ {
89
+ method: 'GET',
90
+ path: `${T}/webhooks/{webhook_id}/deliveries`,
91
+ command: 'api',
92
+ operationId: 'webhooks_and_events_read_delivery_attempts_for_an_endpoint',
93
+ },
94
+ {
95
+ method: 'GET',
96
+ path: `${T}/events`,
97
+ command: 'api',
98
+ operationId: 'webhooks_and_events_poll_tenant_events_by_cursor',
99
+ },
100
+ {
101
+ method: 'GET',
102
+ path: `${T}/locations`,
103
+ command: 'api',
104
+ operationId: 'locations_list_tenant_locations',
105
+ },
106
+ {
107
+ method: 'GET',
108
+ path: `${T}/locations/{location_id}`,
109
+ command: 'api',
110
+ operationId: 'locations_read_one_location',
111
+ },
112
+ {
113
+ method: 'GET',
114
+ path: `${T}/transactions`,
115
+ command: 'api',
116
+ operationId: 'charging_and_operations_read_charging_usage_and_realized_billing',
117
+ },
118
+ {
119
+ method: 'GET',
120
+ path: `${T}/transactions/{transaction_id}`,
121
+ command: 'api',
122
+ operationId: 'charging_and_operations_read_one_transaction_in_detail',
123
+ },
124
+ {
125
+ method: 'GET',
126
+ path: '/v1/currencies',
127
+ command: 'api',
128
+ operationId: 'tariffs_and_bills_list_the_supported_currencies',
129
+ },
130
+ ];
131
+ /** Looks up a cataloged operation by operationId. */
132
+ export function findOperation(operationId) {
133
+ return COMMANDS.find((c) => c.operationId === operationId);
134
+ }
135
+ /** The operationIds `ivora api` may call: cataloged GET operations only. */
136
+ export function getOperationIds() {
137
+ return COMMANDS.filter((c) => c.method === 'GET' && c.operationId).map((c) => c.operationId);
138
+ }
139
+ /** Names of the `{param}` placeholders in a path template. */
140
+ export function pathParams(path) {
141
+ return [...path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]);
142
+ }
143
+ export const EXCLUDED = [];
144
+ /** Path prefixes that are never commands (the CLI ships no staff commands). */
145
+ export const EXCLUDED_PREFIXES = ['/v1/admin', '/v1/host', '/v1/internal'];
146
+ const HTTP_METHODS = ['get', 'put', 'post', 'patch', 'delete'];
147
+ export function specOperations(spec) {
148
+ const ops = [];
149
+ for (const [path, item] of Object.entries(spec.paths ?? {})) {
150
+ for (const m of HTTP_METHODS) {
151
+ if (item[m] !== undefined)
152
+ ops.push({ method: m.toUpperCase(), path });
153
+ }
154
+ }
155
+ return ops;
156
+ }
157
+ function isExcludedPrefix(path) {
158
+ return EXCLUDED_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`));
159
+ }
160
+ export function checkCatalog(spec, commands = COMMANDS, excluded = EXCLUDED) {
161
+ const key = (o) => `${o.method} ${o.path}`;
162
+ const specOps = specOperations(spec);
163
+ const ops = new Set(specOps.map(key));
164
+ const listed = new Set([...commands, ...excluded].map(key));
165
+ return {
166
+ unlisted: specOps.filter((op) => !listed.has(key(op)) && !isExcludedPrefix(op.path)).map(key),
167
+ unknown: [...listed].filter((op) => !ops.has(op)),
168
+ staff: commands.filter((c) => isExcludedPrefix(c.path)).map(key),
169
+ };
170
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,156 @@
1
+ import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
2
+ import { CliError, ExitCode, Output } from './lib/output.js';
3
+ import { ttyPrompter } from './lib/confirm.js';
4
+ import { openSecretStore } from './lib/secrets.js';
5
+ import { loginCommand } from './commands/login.js';
6
+ import { profilesCommand } from './commands/profiles.js';
7
+ import { whoamiCommand } from './commands/whoami.js';
8
+ import { stationsCommand } from './commands/stations.js';
9
+ import { operationsCommand } from './commands/operations.js';
10
+ import { tariffsCommand } from './commands/tariffs.js';
11
+ import { webhooksCommand } from './commands/webhooks.js';
12
+ import { apiCommand } from './commands/api.js';
13
+ import { validateIdempotencyKey } from './lib/http.js';
14
+ import { CLI_VERSION, DEFAULT_API_VERSION, SUPPORTED_API_VERSIONS, isSupportedApiVersion, } from './version.js';
15
+ /** Reads a line from the terminal without echoing it. */
16
+ function readHiddenLine(input, stderr, prompt) {
17
+ return new Promise((resolve, reject) => {
18
+ stderr.write(prompt);
19
+ let line = '';
20
+ const finish = (fn) => {
21
+ input.setRawMode(false);
22
+ input.pause();
23
+ input.off('data', onData);
24
+ stderr.write('\n');
25
+ fn();
26
+ };
27
+ const onData = (chunk) => {
28
+ for (const ch of chunk.toString('utf8')) {
29
+ if (ch === '\r' || ch === '\n' || ch === '\u0004')
30
+ return finish(() => resolve(line));
31
+ if (ch === '\u0003')
32
+ return finish(() => reject(new CliError('Cancelled.', ExitCode.ConfirmRefused)));
33
+ if (ch === '\u007f' || ch === '\b')
34
+ line = line.slice(0, -1);
35
+ else
36
+ line += ch;
37
+ }
38
+ };
39
+ input.setRawMode(true);
40
+ input.resume();
41
+ input.on('data', onData);
42
+ });
43
+ }
44
+ export function versionText() {
45
+ return `ivora ${CLI_VERSION} (API ${DEFAULT_API_VERSION})`;
46
+ }
47
+ function parseApiVersion(value) {
48
+ if (!isSupportedApiVersion(value)) {
49
+ throw new InvalidArgumentError(`supported versions: ${SUPPORTED_API_VERSIONS.join(', ')}`);
50
+ }
51
+ return value;
52
+ }
53
+ function parseIdempotencyKey(value) {
54
+ try {
55
+ return validateIdempotencyKey(value);
56
+ }
57
+ catch (err) {
58
+ throw new InvalidArgumentError(err.message);
59
+ }
60
+ }
61
+ /** Subcommands do not inherit exitOverride and output settings; without them they exit the process. */
62
+ function inheritSettings(parent) {
63
+ for (const sub of parent.commands) {
64
+ sub.copyInheritedSettings(parent);
65
+ inheritSettings(sub);
66
+ }
67
+ }
68
+ export function buildProgram(io = {
69
+ stdout: process.stdout,
70
+ stderr: process.stderr,
71
+ }) {
72
+ const program = new Command('ivora')
73
+ .description('Command-line client for the public Ivora /v1 API (pre-alpha).')
74
+ .version(versionText(), '-v, --version', 'print the CLI and API versions')
75
+ .option('--profile <name>', 'profile to use (default: the current profile, else "test")')
76
+ .option('--live', 'use the live profile')
77
+ .option('--json', 'machine-readable output on stdout')
78
+ .option('-y, --yes', 'skip confirmation prompts (required for writes that ask when not on a TTY)')
79
+ .addOption(new Option('--idempotency-key <key>', 'Idempotency-Key for the write request').argParser(parseIdempotencyKey))
80
+ .addOption(new Option('--api-version <date>', 'dated API version to send as Ivora-Version')
81
+ .default(DEFAULT_API_VERSION)
82
+ .argParser(parseApiVersion))
83
+ .option('--debug', 'print requests and responses to stderr, with credentials redacted')
84
+ .showHelpAfterError('(run "ivora --help" for usage)')
85
+ .exitOverride()
86
+ .configureOutput({
87
+ writeOut: (s) => io.stdout.write(s),
88
+ writeErr: (s) => io.stderr.write(s),
89
+ })
90
+ .action(function () {
91
+ io.stdout.write(this.helpInformation());
92
+ });
93
+ const env = io.env ?? process.env;
94
+ const stdin = io.stdin ?? process.stdin;
95
+ let store = io.secrets;
96
+ const ctx = {
97
+ stdout: io.stdout,
98
+ stderr: io.stderr,
99
+ stdin,
100
+ env,
101
+ prompter: io.prompter ?? ttyPrompter(),
102
+ readSecret: io.readSecret ?? ((prompt) => readHiddenLine(stdin, io.stderr, prompt)),
103
+ secrets: async () => (store ??= await openSecretStore()),
104
+ ...(io.fetch ? { fetch: io.fetch } : {}),
105
+ globals: () => program.opts(),
106
+ out: () => new Output({
107
+ stdout: io.stdout,
108
+ stderr: io.stderr,
109
+ env,
110
+ json: program.opts().json,
111
+ }),
112
+ };
113
+ program
114
+ .addCommand(loginCommand(ctx))
115
+ .addCommand(profilesCommand(ctx))
116
+ .addCommand(whoamiCommand(ctx))
117
+ .addCommand(stationsCommand(ctx))
118
+ .addCommand(operationsCommand(ctx))
119
+ .addCommand(tariffsCommand(ctx))
120
+ .addCommand(webhooksCommand(ctx));
121
+ program.addCommand(apiCommand(ctx));
122
+ inheritSettings(program);
123
+ return program;
124
+ }
125
+ /** Runs the CLI and returns the exit code. Never calls process.exit. */
126
+ export async function run(argv, io = {}) {
127
+ const stdout = io.stdout ?? process.stdout;
128
+ const stderr = io.stderr ?? process.stderr;
129
+ const program = buildProgram({ ...io, stdout, stderr });
130
+ try {
131
+ await program.parseAsync(argv, { from: 'user' });
132
+ return ExitCode.Ok;
133
+ }
134
+ catch (err) {
135
+ if (err instanceof CommanderError) {
136
+ if (err.code === 'commander.version' ||
137
+ err.code === 'commander.helpDisplayed' ||
138
+ err.code === 'commander.help') {
139
+ return ExitCode.Ok;
140
+ }
141
+ return ExitCode.Usage;
142
+ }
143
+ const out = new Output({
144
+ stdout,
145
+ stderr,
146
+ env: io.env,
147
+ json: program.opts().json,
148
+ });
149
+ if (err instanceof CliError) {
150
+ out.error(err.message);
151
+ return err.exitCode;
152
+ }
153
+ out.error(err instanceof Error ? err.message : String(err));
154
+ return ExitCode.ApiError;
155
+ }
156
+ }