@open-wa/cli 5.0.0-alpha.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.
@@ -0,0 +1,4 @@
1
+ {
2
+ "executablePath": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
3
+ "updatedAt": "2026-04-05T00:37:41.198Z"
4
+ }
@@ -0,0 +1,20 @@
1
+
2
+ > @open-wa/cli@5.0.0-alpha.0 build /Users/Mohammed/projects/tools/wa/packages/cli
3
+ > tsdown src/index.ts src/bin.ts --format cjs
4
+
5
+ ℹ tsdown v0.21.7 powered by rolldown v1.0.0-rc.12
6
+ ℹ config file: /Users/Mohammed/projects/tools/wa/packages/cli/tsdown.config.ts
7
+ ℹ entry: src/index.ts, src/bin.ts
8
+ ℹ tsconfig: tsconfig.json
9
+ ℹ Build start
10
+ ℹ Cleaning 6 files
11
+ ℹ Granting execute permission to dist/bin.cjs
12
+ ℹ dist/bin.cjs 12.64 kB │ gzip: 3.93 kB
13
+ ℹ dist/index.cjs  1.54 kB │ gzip: 0.43 kB
14
+ ℹ dist/event-projection-store-BM9eOQXx.cjs 13.64 kB │ gzip: 3.38 kB
15
+ ℹ 3 files, total: 27.82 kB
16
+ ℹ dist/index.d.cts.map 10.54 kB │ gzip: 3.68 kB
17
+ ℹ dist/index.d.cts  8.50 kB │ gzip: 2.43 kB
18
+ ℹ dist/bin.d.cts  0.01 kB │ gzip: 0.03 kB
19
+ ℹ 3 files, total: 19.05 kB
20
+ ✔ Build complete in 5381ms
@@ -0,0 +1,20 @@
1
+
2
+ > @open-wa/cli@5.0.0-alpha.0 test /Users/Mohammed/projects/tools/wa/packages/cli
3
+ > vitest run
4
+
5
+
6
+  RUN  v4.1.2 /Users/Mohammed/projects/tools/wa/packages/cli
7
+
8
+ ✓ src/__tests__/cli-termination.test.ts (2 tests) 5ms
9
+ ✓ src/__tests__/output-broker.test.ts (4 tests) 5ms
10
+ ✓ src/__tests__/shutdown-controller.test.ts (3 tests) 8ms
11
+ ✓ src/__tests__/interactive-terminal.test.ts (1 test) 48ms
12
+ ✓ src/__tests__/output-mode.test.ts (5 tests) 7ms
13
+ ✓ src/__tests__/event-projection-store.test.ts (2 tests) 5ms
14
+ ✓ src/__tests__/interactive-session.test.ts (2 tests) 62ms
15
+
16
+  Test Files  7 passed (7)
17
+  Tests  19 passed (19)
18
+  Start at  15:26:24
19
+  Duration  457ms (transform 459ms, setup 0ms, import 557ms, tests 140ms, environment 1ms)
20
+
package/CHANGELOG.md ADDED
@@ -0,0 +1,23 @@
1
+ # @open-wa/cli
2
+
3
+ ## 6.0.0-alpha.2
4
+
5
+ ### Minor Changes
6
+
7
+ - Dry run minor bump
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies []:
12
+ - @open-wa/core@6.0.0-alpha.2
13
+ - @open-wa/wa-automate@6.0.0-alpha.2
14
+
15
+ ## 5.0.1-alpha.2
16
+
17
+ ### Patch Changes
18
+
19
+ - Dry run patch bump
20
+
21
+ - Updated dependencies []:
22
+ - @open-wa/core@5.0.1-alpha.2
23
+ - @open-wa/wa-automate@5.0.1-alpha.2
package/LICENSE.md ADDED
@@ -0,0 +1,67 @@
1
+ ### Copyright (c) 2020 Mohammed Shah
2
+
3
+ # Hippocratic + Do Not Harm (H-DNH) Version 1.1
4
+
5
+ ## Preamble
6
+
7
+ Most software today is developed with little to no thought of how it will be used, or the consequences for our society and planet.
8
+
9
+ As software developers, we engineer the infrastructure of the 21st century. We recognise that our infrastructure has great power to shape the world and the lives of those we share it with, and we choose to consciously take responsibility for the social and environmental impacts of what we build.
10
+
11
+ We envisage a world free from injustice, inequality, and the reckless destruction of lives and our planet. We reject slavery in all its forms, whether by force, indebtedness, or by algorithms that hack human vulnerabilities. We seek a world where humankind is at peace with our neighbours, nature, and ourselves. We want our work to enrich the physical, mental and spiritual wellbeing of all society.
12
+
13
+ We build software to further this vision of a just world, or at the very least, to not put that vision further from reach.
14
+
15
+ ## Terms
16
+
17
+ Licensor hereby grants permission by this license ("License"), free of charge, to any person or entity (the "Licensee") obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
18
+
19
+ 1. All redistribution of source code or binary form, including any modifications must be under these terms. You must inform recipients that the code is governed by these conditions, and how they can obtain a copy of this license. You may not attempt to alter the conditions of who may/may not use this software.
20
+
21
+ 2. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
22
+
23
+ 3. This software must not be used by any organisation, website, product or service that:
24
+
25
+ a) lobbies for, promotes, or derives a majority of income from actions that support or contribute to:
26
+ * sex trafficking
27
+ * human trafficking
28
+ * slavery
29
+ * indentured servitude
30
+ * gambling
31
+ * tobacco
32
+ * adversely addictive behaviours
33
+ * nuclear energy
34
+ * warfare
35
+ * weapons manufacturing
36
+ * war crimes
37
+ * settler colonialism
38
+ * apartheid
39
+ * vaccine misinformation
40
+ * climate misinformation
41
+ * child endangerment
42
+ * violence (except when required to protect public safety)
43
+ * burning of forests
44
+ * deforestation
45
+ * hate speech or discrimination based on age, gender, gender identity, race, sexuality, religion, nationality
46
+
47
+ b) lobbies against, or derives a majority of income from actions that discourage or frustrate:
48
+ * peace
49
+ * access to the rights set out in the Universal Declaration of Human Rights and the Convention on the Rights of the Child
50
+ * peaceful assembly and association (including worker associations)
51
+ * a safe environment or action to curtail the use of fossil fuels or prevent climate change
52
+ * democratic processes
53
+
54
+
55
+ 4. Compliance with Human Rights Laws and Human Rights Principles:
56
+
57
+ a. **Human Rights Laws**. The Software shall not be used by any person or entity for any systems, activities, or other uses that violate any applicable laws, regulations, or rules that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights (the "Human Rights Laws"). Where the Human Rights Laws of more than one jurisdiction are applicable to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply.
58
+
59
+ b. **Human Rights Principles**. Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights (https://www.un.org/en/universal-declaration-human-rights/) and the United Nations Global Compact (https://www.unglobalcompact.org/ what-is-gc/mission/principles) that define recognized principles of international human rights (the "Human Rights Principles"). It is Licensor's express intent that all use of the Software be consistent with Human Rights Principles. If Licensor receives notification or otherwise learns of an alleged violation of any Human Rights Principles relating to Licensee's use of the Software, Licensor may in its discretion and without obligation (i) (a) notify Licensee of such allegation and (b) allow Licensee 90 days from notification under (i)(a) to investigate and respond to Licensor regarding the allegation and (ii) (a) after the earlier of 90 days from notification under (i)(a), or Licensee's response under (i)(b), notify Licensee of License termination and (b) allow Licensee an additional 90 days from notification under (ii)(a) to cease use of the Software.
60
+
61
+ c. **Indemnity**. Licensee shall hold harmless and indemnify Licensor against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor's reasonable attorneys' fees, arising out of or relating to Licensee's non-compliance with this License or use of the Software in violation of Human Rights Laws or Human Rights Principles. 
62
+
63
+ 5. Enforceability: If any portion or provision of this License is determined to be invalid, illegal, or unenforceable by a court of competent jurisdiction, then such invalidity, illegality, or unenforceability shall not affect any other term or provision of this License or invalidate or render unenforceable such term or provision in any other jurisdiction. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by applicable law, the court may modify this License to affect the original intent of the parties as closely as possible. The section headings are for convenience only and are not intended to affect the construction or interpretation of this License. Any rule of construction to the effect that ambiguities are to be resolved against the drafting party shall not apply in interpreting this License. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party.
64
+
65
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
66
+
67
+ This license is an extension of the Hippocratic License - an Ethical Source license (https://ethicalsource.dev) and the Do Not Harm License - (https://github.com/raisely/NoHarm)
package/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # @open-wa/cli
2
+
3
+ > Command line tool for the Open-WA WhatsApp automation stack.
4
+
5
+ Part of the [@open-wa v5 monorepo](https://github.com/open-wa/wa-automate-nodejs).
6
+
7
+ ## Features
8
+
9
+ - **Easy API mode**: Start a WhatsApp server with a single command.
10
+ - **Session Auth**: Interactive QR code scanning in the terminal.
11
+ - **Diagnostics**: Built-in tools for testing connections and drivers.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pnpm add -g @open-wa/cli
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```bash
22
+ wa-automate --help
23
+ ```
24
+
25
+ ## Documentation
26
+
27
+ See the [CLI reference](https://docs.openwa.dev/reference/cli) on our docs site.
28
+
29
+ ## License
30
+
31
+ [H-DNH V1.0](https://github.com/open-wa/wa-automate-nodejs/blob/main/LICENSE.md) — Hippocratic + Do Not Harm
package/dist/bin.cjs ADDED
@@ -0,0 +1,398 @@
1
+ #!/usr/bin/env node
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ //#region \0rolldown/runtime.js
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
21
+ value: mod,
22
+ enumerable: true
23
+ }) : target, mod));
24
+ //#endregion
25
+ const require_event_projection_store = require("./event-projection-store-BM9eOQXx.cjs");
26
+ let _open_wa_wa_automate = require("@open-wa/wa-automate");
27
+ let ws = require("ws");
28
+ ws = __toESM(ws);
29
+ let qrcode = require("qrcode");
30
+ qrcode = __toESM(qrcode);
31
+ //#region src/tunnel-client.ts
32
+ var TunnelClient = class {
33
+ ws = null;
34
+ reconnectTimeout = null;
35
+ isDestroyed = false;
36
+ constructor(options) {
37
+ this.options = options;
38
+ }
39
+ log(level, message) {
40
+ if (this.options.log) {
41
+ this.options.log(level, message);
42
+ return;
43
+ }
44
+ if (level === "warn") {
45
+ console.warn(message);
46
+ return;
47
+ }
48
+ if (level === "error") {
49
+ console.error(message);
50
+ return;
51
+ }
52
+ console.log(message);
53
+ }
54
+ connect() {
55
+ if (this.isDestroyed) return;
56
+ let urlStr = this.options.proxyHost;
57
+ if (urlStr.startsWith("http")) urlStr = urlStr.replace(/^http/, "ws");
58
+ this.ws = new ws.default(`${urlStr}/sessions/${encodeURIComponent(this.options.sessionId)}/upstream?token=${encodeURIComponent(this.options.proxyToken)}`);
59
+ this.ws.on("open", () => {
60
+ this.log("info", `[TunnelClient] Connected upstream for session ${this.options.sessionId}`);
61
+ });
62
+ this.ws.on("message", async (data) => {
63
+ let msg;
64
+ try {
65
+ msg = JSON.parse(data.toString("utf-8"));
66
+ } catch {
67
+ return;
68
+ }
69
+ if (msg.type === "ping") {
70
+ this.ws?.send(JSON.stringify({ type: "pong" }));
71
+ return;
72
+ }
73
+ if (msg.type === "http_request") await this.handleHttpRequest(msg);
74
+ else if (msg.type === "rpc_request") await this.handleRpcAsHttp(msg);
75
+ });
76
+ this.ws.on("close", () => {
77
+ if (!this.isDestroyed) {
78
+ this.log("warn", `[TunnelClient] Disconnected. Reconnecting in 3s...`);
79
+ this.reconnectTimeout = setTimeout(() => this.connect(), 3e3);
80
+ }
81
+ });
82
+ this.ws.on("error", (err) => {
83
+ this.log("error", `[TunnelClient] WebSocket error: ${err.message}`);
84
+ });
85
+ }
86
+ async handleHttpRequest(msg) {
87
+ const localUrl = `http://localhost:${this.options.localSessionPort}${msg.path}`;
88
+ try {
89
+ const fetchOpts = {
90
+ method: msg.method,
91
+ headers: msg.headers || {}
92
+ };
93
+ if (msg.body) {
94
+ if (typeof msg.body === "string") fetchOpts.body = Buffer.from(msg.body, "base64");
95
+ }
96
+ const res = await fetch(localUrl, fetchOpts);
97
+ const resBuffer = await res.arrayBuffer();
98
+ const responseMsg = {
99
+ type: "http_response",
100
+ id: msg.id,
101
+ status: res.status,
102
+ headers: Object.fromEntries(res.headers.entries()),
103
+ body: Buffer.from(resBuffer).toString("base64")
104
+ };
105
+ this.ws?.send(JSON.stringify(responseMsg));
106
+ } catch (e) {
107
+ this.log("error", `[TunnelClient] Failed to proxy http_request: ${e instanceof Error ? e.message : String(e)}`);
108
+ this.ws?.send(JSON.stringify({
109
+ type: "http_response",
110
+ id: msg.id,
111
+ status: 502,
112
+ headers: { "content-type": "text/plain" },
113
+ body: Buffer.from("Bad Gateway: " + e.message).toString("base64")
114
+ }));
115
+ }
116
+ }
117
+ async handleRpcAsHttp(msg) {
118
+ const localUrl = `http://localhost:${this.options.localSessionPort}/api/${msg.method}`;
119
+ try {
120
+ const resData = await (await fetch(localUrl, {
121
+ method: "POST",
122
+ headers: { "Content-Type": "application/json" },
123
+ body: JSON.stringify({ args: msg.args })
124
+ })).json();
125
+ const responseMsg = {
126
+ type: "rpc_response",
127
+ id: msg.id,
128
+ result: resData
129
+ };
130
+ this.ws?.send(JSON.stringify(responseMsg));
131
+ } catch (e) {
132
+ this.log("error", `[TunnelClient] Failed to proxy rpc_request: ${e instanceof Error ? e.message : String(e)}`);
133
+ this.ws?.send(JSON.stringify({
134
+ type: "rpc_response",
135
+ id: msg.id,
136
+ error: e.message
137
+ }));
138
+ }
139
+ }
140
+ destroy() {
141
+ this.isDestroyed = true;
142
+ if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
143
+ if (this.ws) {
144
+ this.ws.close();
145
+ this.ws = null;
146
+ }
147
+ }
148
+ disconnect() {
149
+ this.destroy();
150
+ }
151
+ };
152
+ //#endregion
153
+ //#region src/presenter/interactive-terminal.ts
154
+ var InteractiveTerminalPresenter = class {
155
+ store;
156
+ stdout;
157
+ stderr;
158
+ ink;
159
+ unsubscribe;
160
+ started = false;
161
+ stopped = false;
162
+ snapshot;
163
+ qrAscii;
164
+ qrValue;
165
+ renderTree;
166
+ qrSequence = 0;
167
+ constructor(options) {
168
+ this.store = options.store;
169
+ this.stdout = options.stdout ?? process.stdout;
170
+ this.stderr = options.stderr ?? process.stderr;
171
+ this.snapshot = this.store.getSnapshot();
172
+ }
173
+ async start() {
174
+ if (this.started) return;
175
+ this.started = true;
176
+ const React = await import("react");
177
+ const ink = await import("ink");
178
+ await this.updateQrAscii(this.snapshot);
179
+ const LogStream = ({ snapshot }) => {
180
+ if (snapshot.recentLogs.length === 0) return null;
181
+ return React.createElement(ink.Box, {
182
+ flexDirection: "column",
183
+ marginTop: 1
184
+ }, React.createElement(ink.Text, { color: "cyan" }, "Recent Logs"), ...snapshot.recentLogs.slice(-12).map((entry, index) => React.createElement(ink.Text, {
185
+ key: `${entry.timestamp}-${index}`,
186
+ color: entry.level === "error" ? "red" : entry.level === "warn" ? "yellow" : "white"
187
+ }, `[${entry.level}] ${entry.message}`)));
188
+ };
189
+ const QrBlock = ({ snapshot, qrAscii }) => {
190
+ if (!snapshot.qr) return null;
191
+ if (!qrAscii) return React.createElement(ink.Text, { color: "yellow" }, "Generating QR view...");
192
+ const qrLines = qrAscii.split("\n");
193
+ return React.createElement(ink.Box, {
194
+ flexDirection: "column",
195
+ marginTop: 1
196
+ }, React.createElement(ink.Text, { color: "green" }, "QR Code"), ...qrLines.map((line, index) => React.createElement(ink.Text, { key: `qr-${index}` }, line)));
197
+ };
198
+ const App = ({ snapshot, qrAscii }) => React.createElement(ink.Box, {
199
+ flexDirection: "column",
200
+ paddingX: 1
201
+ }, React.createElement(ink.Text, { color: "greenBright" }, "[VT-OS] OPEN-WA CLI"), React.createElement(ink.Text, null, "Mode: ink-interactive"), React.createElement(ink.Text, null, `Phase: ${snapshot.phase}`), React.createElement(ink.Text, null, `Session: ${snapshot.sessionId ?? "pending"}`), React.createElement(ink.Text, null, `Ready: ${snapshot.ready ? "yes" : "no"}`), React.createElement(ink.Text, null, `Messages: ${snapshot.messageCount} | Ack updates: ${snapshot.ackCount}`), snapshot.detail ? React.createElement(ink.Text, { color: snapshot.phase === "error" ? "red" : "yellow" }, `Detail: ${snapshot.detail}`) : null, React.createElement(QrBlock, {
202
+ snapshot,
203
+ qrAscii
204
+ }), React.createElement(LogStream, { snapshot }));
205
+ this.renderTree = () => React.createElement(App, {
206
+ snapshot: this.snapshot,
207
+ qrAscii: this.qrAscii
208
+ });
209
+ this.ink = ink.render(this.renderTree(), {
210
+ stdout: this.stdout,
211
+ stderr: this.stderr,
212
+ patchConsole: false,
213
+ exitOnCtrlC: false
214
+ });
215
+ this.unsubscribe = this.store.subscribe((snapshot) => {
216
+ this.handleSnapshot(snapshot);
217
+ });
218
+ }
219
+ stop(options = {}) {
220
+ if (this.stopped) return;
221
+ this.stopped = true;
222
+ const clear = options.clear ?? true;
223
+ this.unsubscribe?.();
224
+ this.unsubscribe = void 0;
225
+ if (clear) this.ink?.clear?.();
226
+ this.ink?.unmount();
227
+ this.ink = void 0;
228
+ }
229
+ async handleSnapshot(snapshot) {
230
+ if (this.stopped) return;
231
+ this.snapshot = snapshot;
232
+ await this.updateQrAscii(snapshot);
233
+ this.rerender();
234
+ }
235
+ rerender() {
236
+ if (this.stopped || !this.renderTree) return;
237
+ this.ink?.rerender?.(this.renderTree());
238
+ }
239
+ async updateQrAscii(snapshot) {
240
+ if (!snapshot.qr?.qr) {
241
+ this.qrValue = void 0;
242
+ this.qrAscii = void 0;
243
+ return;
244
+ }
245
+ if (snapshot.qr.qr === this.qrValue && this.qrAscii) return;
246
+ this.qrValue = snapshot.qr.qr;
247
+ const sequence = ++this.qrSequence;
248
+ const qrAscii = await qrcode.default.toString(snapshot.qr.qr, {
249
+ type: "terminal",
250
+ small: true
251
+ });
252
+ if (this.stopped || sequence !== this.qrSequence) return;
253
+ this.qrAscii = qrAscii;
254
+ }
255
+ };
256
+ //#endregion
257
+ //#region src/runtime/interactive-session.ts
258
+ function createBrokeredSink(broker, store) {
259
+ return {
260
+ write(entry) {
261
+ broker.write(entry.level, entry.message);
262
+ },
263
+ status(update) {
264
+ store.projectStatus(update);
265
+ },
266
+ qr(payload) {
267
+ store.projectQr(payload);
268
+ broker.write("info", `QR code generated for session ${payload.sessionId}`);
269
+ }
270
+ };
271
+ }
272
+ async function createInteractiveCliSession() {
273
+ const broker = require_event_projection_store.createOutputBroker({
274
+ interactive: true,
275
+ maxEntries: 200,
276
+ passthrough: false,
277
+ interceptStreams: false
278
+ });
279
+ broker.install();
280
+ const store = require_event_projection_store.createEventProjectionStore({
281
+ maxLogs: 200,
282
+ eventDebounceMs: 100
283
+ });
284
+ const detachLogs = broker.subscribe((entry) => {
285
+ store.projectLog(entry);
286
+ });
287
+ const presenter = new InteractiveTerminalPresenter({
288
+ store,
289
+ stdout: process.stdout,
290
+ stderr: process.stderr
291
+ });
292
+ await presenter.start();
293
+ return {
294
+ broker,
295
+ store,
296
+ presenter,
297
+ sink: createBrokeredSink(broker, store),
298
+ cleanup: (options = {}) => {
299
+ detachLogs();
300
+ presenter.stop({ clear: options.clearPresenter ?? true });
301
+ broker.dispose();
302
+ }
303
+ };
304
+ }
305
+ //#endregion
306
+ //#region src/bin.ts
307
+ async function main() {
308
+ const parsedLocalFlags = require_event_projection_store.parseCliLocalFlags(process.argv.slice(2));
309
+ const outputMode = require_event_projection_store.detectOutputMode({ flags: parsedLocalFlags.flags });
310
+ let broker;
311
+ let store;
312
+ let detachEvents;
313
+ let interactiveCleanup;
314
+ const cleanupCliResources = (options = {}) => {
315
+ const clearPresenter = options.clearPresenter ?? true;
316
+ detachEvents?.();
317
+ detachEvents = void 0;
318
+ (0, _open_wa_wa_automate.resetCliOutputSink)();
319
+ interactiveCleanup?.({ clearPresenter });
320
+ interactiveCleanup = void 0;
321
+ broker = void 0;
322
+ store = void 0;
323
+ };
324
+ if (outputMode.interactive) {
325
+ const session = await createInteractiveCliSession();
326
+ broker = session.broker;
327
+ store = session.store;
328
+ interactiveCleanup = session.cleanup;
329
+ (0, _open_wa_wa_automate.setCliOutputSink)(session.sink);
330
+ }
331
+ let runtime;
332
+ let tunnelClient;
333
+ const shutdownController = require_event_projection_store.createShutdownController({
334
+ timeoutMs: 1e4,
335
+ gracefulShutdown: async (signal) => {
336
+ await require_event_projection_store.performGracefulShutdown({
337
+ runtime,
338
+ tunnelClient,
339
+ store
340
+ }, signal);
341
+ },
342
+ cleanup: async () => {
343
+ cleanupCliResources();
344
+ }
345
+ });
346
+ shutdownController.install();
347
+ try {
348
+ runtime = await (0, _open_wa_wa_automate.runCli)(parsedLocalFlags.forwardedArgs);
349
+ if (!runtime) {
350
+ shutdownController.dispose();
351
+ cleanupCliResources();
352
+ return;
353
+ }
354
+ if (store) detachEvents = store.attachEmitter(runtime.events);
355
+ if (runtime?.config.proxyHost && runtime.config.proxyToken) {
356
+ const log = (level, message) => {
357
+ if (broker) {
358
+ broker.write(level, message);
359
+ return;
360
+ }
361
+ if (level === "warn") {
362
+ console.warn(message);
363
+ return;
364
+ }
365
+ if (level === "error") {
366
+ console.error(message);
367
+ return;
368
+ }
369
+ console.log(message);
370
+ };
371
+ log("info", `[CLI] Starting TunnelClient connecting to ${runtime.config.proxyHost}...`);
372
+ tunnelClient = new TunnelClient({
373
+ proxyHost: runtime.config.proxyHost,
374
+ proxyToken: runtime.config.proxyToken,
375
+ sessionId: runtime.config.sessionId,
376
+ localSessionPort: runtime.config.port,
377
+ log
378
+ });
379
+ tunnelClient.connect();
380
+ }
381
+ } catch (err) {
382
+ const message = err instanceof Error ? `${err.message}${err.stack ? `\n${err.stack}` : ""}` : String(err);
383
+ store?.projectStatus({
384
+ phase: "error",
385
+ detail: message
386
+ });
387
+ shutdownController.dispose();
388
+ if (broker) {
389
+ broker.write("error", `Fatal error: ${message}`);
390
+ require_event_projection_store.writeVisibleFatalError(message, (rawMessage) => broker?.writeRawStderr(rawMessage));
391
+ cleanupCliResources({ clearPresenter: false });
392
+ } else console.error("Fatal error:", err);
393
+ process.exit(1);
394
+ }
395
+ }
396
+ main();
397
+ //#endregion
398
+ exports.__toESM = __toESM;
package/dist/bin.d.cts ADDED
@@ -0,0 +1 @@
1
+ export { };