@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,193 @@
1
+ export type BrokerLevel = 'debug' | 'info' | 'warn' | 'error';
2
+ export type BrokerSource = 'console' | 'stdout' | 'stderr' | 'runtime';
3
+
4
+ export interface BrokerEntry {
5
+ level: BrokerLevel;
6
+ message: string;
7
+ source: BrokerSource;
8
+ timestamp: number;
9
+ }
10
+
11
+ export interface OutputBrokerOptions {
12
+ interactive: boolean;
13
+ maxEntries?: number;
14
+ passthrough?: boolean;
15
+ interceptStreams?: boolean;
16
+ }
17
+
18
+ type Subscriber = (entry: BrokerEntry) => void;
19
+ type ConsoleMethod = (...args: unknown[]) => void;
20
+ type StreamWrite = (chunk: any, encoding?: BufferEncoding | ((error?: Error | null) => void), callback?: (error?: Error | null) => void) => boolean;
21
+
22
+ function stringifyArgs(args: unknown[]): string {
23
+ return args
24
+ .map((arg) => {
25
+ if (typeof arg === 'string') {
26
+ return arg;
27
+ }
28
+
29
+ if (arg instanceof Error) {
30
+ return arg.stack ?? arg.message;
31
+ }
32
+
33
+ if (typeof arg === 'object' && arg !== null) {
34
+ try {
35
+ return JSON.stringify(arg);
36
+ } catch {
37
+ return String(arg);
38
+ }
39
+ }
40
+
41
+ return String(arg);
42
+ })
43
+ .join(' ');
44
+ }
45
+
46
+ export class OutputBroker {
47
+ private readonly interactive: boolean;
48
+ private readonly maxEntries: number;
49
+ private readonly passthrough: boolean;
50
+ private readonly interceptStreams: boolean;
51
+ private readonly entries: BrokerEntry[] = [];
52
+ private readonly subscribers = new Set<Subscriber>();
53
+ private installed = false;
54
+ private originalConsole?: {
55
+ log: ConsoleMethod;
56
+ warn: ConsoleMethod;
57
+ error: ConsoleMethod;
58
+ };
59
+ private originalWrites?: {
60
+ stdout: StreamWrite;
61
+ stderr: StreamWrite;
62
+ };
63
+
64
+ constructor(options: OutputBrokerOptions) {
65
+ this.interactive = options.interactive;
66
+ this.maxEntries = options.maxEntries ?? 200;
67
+ this.passthrough = options.passthrough ?? !options.interactive;
68
+ this.interceptStreams = options.interceptStreams ?? true;
69
+ }
70
+
71
+ install(): void {
72
+ if (this.installed) {
73
+ return;
74
+ }
75
+
76
+ this.installed = true;
77
+ this.originalConsole = {
78
+ log: console.log.bind(console),
79
+ warn: console.warn.bind(console),
80
+ error: console.error.bind(console),
81
+ };
82
+ this.originalWrites = {
83
+ stdout: process.stdout.write.bind(process.stdout),
84
+ stderr: process.stderr.write.bind(process.stderr),
85
+ };
86
+
87
+ console.log = (...args: unknown[]) => {
88
+ this.forward('info', 'console', stringifyArgs(args), () => this.originalConsole?.log(...args));
89
+ };
90
+ console.warn = (...args: unknown[]) => {
91
+ this.forward('warn', 'console', stringifyArgs(args), () => this.originalConsole?.warn(...args));
92
+ };
93
+ console.error = (...args: unknown[]) => {
94
+ this.forward('error', 'console', stringifyArgs(args), () => this.originalConsole?.error(...args));
95
+ };
96
+
97
+ if (this.interceptStreams) {
98
+ process.stdout.write = ((chunk: any, encoding?: BufferEncoding | ((error?: Error | null) => void), callback?: (error?: Error | null) => void) => {
99
+ const message = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
100
+ this.forward('info', 'stdout', message, () => this.originalWrites?.stdout(chunk, encoding as any, callback));
101
+ if (this.interactive && !this.passthrough) {
102
+ if (typeof encoding === 'function') {
103
+ encoding(undefined);
104
+ } else {
105
+ callback?.(undefined);
106
+ }
107
+ }
108
+ return true;
109
+ }) as StreamWrite;
110
+
111
+ process.stderr.write = ((chunk: any, encoding?: BufferEncoding | ((error?: Error | null) => void), callback?: (error?: Error | null) => void) => {
112
+ const message = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
113
+ this.forward('error', 'stderr', message, () => this.originalWrites?.stderr(chunk, encoding as any, callback));
114
+ if (this.interactive && !this.passthrough) {
115
+ if (typeof encoding === 'function') {
116
+ encoding(undefined);
117
+ } else {
118
+ callback?.(undefined);
119
+ }
120
+ }
121
+ return true;
122
+ }) as StreamWrite;
123
+ }
124
+ }
125
+
126
+ dispose(): void {
127
+ if (!this.installed) {
128
+ return;
129
+ }
130
+
131
+ if (this.originalConsole) {
132
+ console.log = this.originalConsole.log;
133
+ console.warn = this.originalConsole.warn;
134
+ console.error = this.originalConsole.error;
135
+ }
136
+
137
+ if (this.originalWrites && this.interceptStreams) {
138
+ process.stdout.write = this.originalWrites.stdout as typeof process.stdout.write;
139
+ process.stderr.write = this.originalWrites.stderr as typeof process.stderr.write;
140
+ }
141
+
142
+ this.installed = false;
143
+ }
144
+
145
+ subscribe(listener: Subscriber): () => void {
146
+ this.subscribers.add(listener);
147
+ return () => {
148
+ this.subscribers.delete(listener);
149
+ };
150
+ }
151
+
152
+ getEntries(): BrokerEntry[] {
153
+ return [...this.entries];
154
+ }
155
+
156
+ writeRawStdout(message: string): void {
157
+ this.originalWrites?.stdout(message);
158
+ }
159
+
160
+ writeRawStderr(message: string): void {
161
+ this.originalWrites?.stderr(message);
162
+ }
163
+
164
+ write(level: BrokerLevel, message: string, source: BrokerSource = 'runtime'): void {
165
+ this.forward(level, source, message);
166
+ }
167
+
168
+ private forward(level: BrokerLevel, source: BrokerSource, message: string, passthroughWriter?: () => void): void {
169
+ const entry: BrokerEntry = {
170
+ level,
171
+ source,
172
+ message,
173
+ timestamp: Date.now(),
174
+ };
175
+
176
+ this.entries.push(entry);
177
+ if (this.entries.length > this.maxEntries) {
178
+ this.entries.splice(0, this.entries.length - this.maxEntries);
179
+ }
180
+
181
+ for (const subscriber of this.subscribers) {
182
+ subscriber(entry);
183
+ }
184
+
185
+ if (!this.interactive || this.passthrough) {
186
+ passthroughWriter?.();
187
+ }
188
+ }
189
+ }
190
+
191
+ export function createOutputBroker(options: OutputBrokerOptions): OutputBroker {
192
+ return new OutputBroker(options);
193
+ }
@@ -0,0 +1,73 @@
1
+ import type { CliLocalFlags } from '../config/cli-flags-schema';
2
+
3
+ export type OutputModeKind = 'interactive' | 'plain';
4
+
5
+ export interface OutputModeContract {
6
+ kind: OutputModeKind;
7
+ interactive: boolean;
8
+ reason:
9
+ | 'flag.interactive'
10
+ | 'flag.plain'
11
+ | 'stdin-not-tty'
12
+ | 'stdout-not-tty'
13
+ | 'stderr-not-tty'
14
+ | 'term-dumb'
15
+ | 'ci'
16
+ | 'no-color'
17
+ | 'env.non-interactive'
18
+ | 'tty-ready';
19
+ }
20
+
21
+ export interface DetectOutputModeOptions {
22
+ flags?: CliLocalFlags;
23
+ env?: NodeJS.ProcessEnv;
24
+ stdin?: Pick<NodeJS.ReadStream, 'isTTY'>;
25
+ stdout?: Pick<NodeJS.WriteStream, 'isTTY'>;
26
+ stderr?: Pick<NodeJS.WriteStream, 'isTTY'>;
27
+ }
28
+
29
+ export function detectOutputMode(options: DetectOutputModeOptions = {}): OutputModeContract {
30
+ const env = options.env ?? process.env;
31
+ const stdin = options.stdin ?? process.stdin;
32
+ const stdout = options.stdout ?? process.stdout;
33
+ const stderr = options.stderr ?? process.stderr;
34
+ const forcedMode = options.flags?.outputMode;
35
+
36
+ if (forcedMode === 'plain') {
37
+ return { kind: 'plain', interactive: false, reason: 'flag.plain' };
38
+ }
39
+
40
+ if (!stdin.isTTY) {
41
+ return { kind: 'plain', interactive: false, reason: 'stdin-not-tty' };
42
+ }
43
+
44
+ if (!stdout.isTTY) {
45
+ return { kind: 'plain', interactive: false, reason: 'stdout-not-tty' };
46
+ }
47
+
48
+ if (!stderr.isTTY) {
49
+ return { kind: 'plain', interactive: false, reason: 'stderr-not-tty' };
50
+ }
51
+
52
+ if (env.TERM === 'dumb') {
53
+ return { kind: 'plain', interactive: false, reason: 'term-dumb' };
54
+ }
55
+
56
+ if (env.OPEN_WA_NON_INTERACTIVE === '1') {
57
+ return { kind: 'plain', interactive: false, reason: 'env.non-interactive' };
58
+ }
59
+
60
+ if (env.CI) {
61
+ return { kind: 'plain', interactive: false, reason: 'ci' };
62
+ }
63
+
64
+ if (env.NO_COLOR) {
65
+ return { kind: 'plain', interactive: false, reason: 'no-color' };
66
+ }
67
+
68
+ if (forcedMode === 'interactive') {
69
+ return { kind: 'interactive', interactive: true, reason: 'flag.interactive' };
70
+ }
71
+
72
+ return { kind: 'interactive', interactive: true, reason: 'tty-ready' };
73
+ }
@@ -0,0 +1,86 @@
1
+ export interface ShutdownControllerOptions {
2
+ timeoutMs?: number;
3
+ gracefulShutdown: (signal: NodeJS.Signals) => Promise<void>;
4
+ cleanup?: () => void | Promise<void>;
5
+ exit?: (code: number) => never | void;
6
+ }
7
+
8
+ export class ShutdownController {
9
+ private readonly timeoutMs: number;
10
+ private readonly gracefulShutdown: (signal: NodeJS.Signals) => Promise<void>;
11
+ private readonly cleanup?: () => void | Promise<void>;
12
+ private readonly exit: (code: number) => never | void;
13
+ private installed = false;
14
+ private shuttingDown = false;
15
+ private cleanupStarted = false;
16
+ private readonly boundSignals = new Map<NodeJS.Signals, () => void>();
17
+
18
+ constructor(options: ShutdownControllerOptions) {
19
+ this.timeoutMs = options.timeoutMs ?? 10_000;
20
+ this.gracefulShutdown = options.gracefulShutdown;
21
+ this.cleanup = options.cleanup;
22
+ this.exit = options.exit ?? ((code: number) => process.exit(code));
23
+ }
24
+
25
+ install(signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM']): void {
26
+ if (this.installed) {
27
+ return;
28
+ }
29
+
30
+ for (const signal of signals) {
31
+ const handler = () => {
32
+ void this.handleSignal(signal);
33
+ };
34
+ this.boundSignals.set(signal, handler);
35
+ process.on(signal, handler);
36
+ }
37
+
38
+ this.installed = true;
39
+ }
40
+
41
+ dispose(): void {
42
+ for (const [signal, handler] of this.boundSignals.entries()) {
43
+ process.off(signal, handler);
44
+ }
45
+ this.boundSignals.clear();
46
+ this.installed = false;
47
+ }
48
+
49
+ async handleSignal(signal: NodeJS.Signals): Promise<void> {
50
+ if (this.shuttingDown) {
51
+ await this.runCleanup();
52
+ this.exit(1);
53
+ return;
54
+ }
55
+
56
+ this.shuttingDown = true;
57
+
58
+ try {
59
+ await Promise.race([
60
+ this.gracefulShutdown(signal),
61
+ new Promise<never>((_, reject) => {
62
+ setTimeout(() => reject(new Error(`Graceful shutdown timed out after ${this.timeoutMs}ms`)), this.timeoutMs);
63
+ }),
64
+ ]);
65
+
66
+ await this.runCleanup();
67
+ this.exit(0);
68
+ } catch {
69
+ await this.runCleanup();
70
+ this.exit(1);
71
+ }
72
+ }
73
+
74
+ private async runCleanup(): Promise<void> {
75
+ if (this.cleanupStarted) {
76
+ return;
77
+ }
78
+
79
+ this.cleanupStarted = true;
80
+ await this.cleanup?.();
81
+ }
82
+ }
83
+
84
+ export function createShutdownController(options: ShutdownControllerOptions): ShutdownController {
85
+ return new ShutdownController(options);
86
+ }
@@ -0,0 +1,166 @@
1
+ import type { HyperEmitter } from '@open-wa/hyperemitter';
2
+ import type { OpenWAEventMap } from '@open-wa/core';
3
+ import type { BrokerEntry } from '../runtime/output-broker';
4
+ import type { CliQrPayload, CliStatusUpdate } from '@open-wa/wa-automate';
5
+
6
+ export interface ProjectionSnapshot {
7
+ phase: string;
8
+ sessionId?: string;
9
+ detail?: string;
10
+ qr?: CliQrPayload;
11
+ recentLogs: BrokerEntry[];
12
+ messageCount: number;
13
+ ackCount: number;
14
+ ready: boolean;
15
+ lastEventAt?: number;
16
+ }
17
+
18
+ export interface EventProjectionStoreOptions {
19
+ maxLogs?: number;
20
+ eventDebounceMs?: number;
21
+ }
22
+
23
+ type ProjectionListener = (snapshot: ProjectionSnapshot) => void;
24
+ type RuntimeEventName = 'message.received' | 'ack.changed' | 'core.starting' | 'core.stopping' | 'core.stopped' | 'client.ready' | 'launch.auth.qr.generated';
25
+
26
+ export class EventProjectionStore {
27
+ private readonly maxLogs: number;
28
+ private readonly eventDebounceMs: number;
29
+ private readonly listeners = new Set<ProjectionListener>();
30
+ private readonly state: ProjectionSnapshot = {
31
+ phase: 'boot',
32
+ recentLogs: [],
33
+ messageCount: 0,
34
+ ackCount: 0,
35
+ ready: false,
36
+ };
37
+ private pendingMessageCount = 0;
38
+ private pendingAckCount = 0;
39
+ private flushTimer?: NodeJS.Timeout;
40
+
41
+ constructor(options: EventProjectionStoreOptions = {}) {
42
+ this.maxLogs = options.maxLogs ?? 200;
43
+ this.eventDebounceMs = options.eventDebounceMs ?? 100;
44
+ }
45
+
46
+ subscribe(listener: ProjectionListener): () => void {
47
+ this.listeners.add(listener);
48
+ listener(this.getSnapshot());
49
+ return () => {
50
+ this.listeners.delete(listener);
51
+ };
52
+ }
53
+
54
+ getSnapshot(): ProjectionSnapshot {
55
+ return {
56
+ ...this.state,
57
+ recentLogs: [...this.state.recentLogs],
58
+ };
59
+ }
60
+
61
+ projectLog(entry: BrokerEntry): void {
62
+ this.state.recentLogs.push(entry);
63
+ if (this.state.recentLogs.length > this.maxLogs) {
64
+ this.state.recentLogs.splice(0, this.state.recentLogs.length - this.maxLogs);
65
+ }
66
+ this.emit();
67
+ }
68
+
69
+ projectStatus(update: CliStatusUpdate): void {
70
+ this.state.phase = update.phase;
71
+ this.state.sessionId = update.sessionId ?? this.state.sessionId;
72
+ this.state.detail = update.detail;
73
+ if (update.phase === 'client.ready') {
74
+ this.state.ready = true;
75
+ }
76
+ if (update.phase === 'shutdown.starting') {
77
+ this.state.ready = false;
78
+ }
79
+ this.emit();
80
+ }
81
+
82
+ projectQr(payload: CliQrPayload): void {
83
+ this.state.phase = 'auth.qr';
84
+ this.state.qr = payload;
85
+ this.state.sessionId = payload.sessionId;
86
+ this.emit();
87
+ }
88
+
89
+ attachEmitter(emitter: HyperEmitter<OpenWAEventMap>): () => void {
90
+ const handlers: Array<[RuntimeEventName, (payload: any) => void]> = [
91
+ ['core.starting', () => {
92
+ this.state.phase = 'boot';
93
+ this.state.lastEventAt = Date.now();
94
+ this.emit();
95
+ }],
96
+ ['core.stopping', () => {
97
+ this.state.phase = 'shutdown.starting';
98
+ this.state.ready = false;
99
+ this.state.lastEventAt = Date.now();
100
+ this.emit();
101
+ }],
102
+ ['core.stopped', () => {
103
+ this.state.phase = 'shutdown.complete';
104
+ this.state.lastEventAt = Date.now();
105
+ this.emit();
106
+ }],
107
+ ['client.ready', () => {
108
+ this.state.phase = 'client.ready';
109
+ this.state.ready = true;
110
+ this.state.lastEventAt = Date.now();
111
+ this.emit();
112
+ }],
113
+ ['launch.auth.qr.generated', (payload) => {
114
+ const qr = payload?.details?.qr;
115
+ if (typeof qr === 'string' && this.state.sessionId) {
116
+ this.projectQr({ qr, sessionId: this.state.sessionId });
117
+ }
118
+ }],
119
+ ['message.received', () => {
120
+ this.pendingMessageCount += 1;
121
+ this.scheduleFlush();
122
+ }],
123
+ ['ack.changed', () => {
124
+ this.pendingAckCount += 1;
125
+ this.scheduleFlush();
126
+ }],
127
+ ];
128
+
129
+ for (const [event, handler] of handlers) {
130
+ emitter.on(event, handler as never);
131
+ }
132
+
133
+ return () => {
134
+ for (const [event, handler] of handlers) {
135
+ emitter.off(event, handler as never);
136
+ }
137
+ };
138
+ }
139
+
140
+ private scheduleFlush(): void {
141
+ if (this.flushTimer) {
142
+ return;
143
+ }
144
+
145
+ this.flushTimer = setTimeout(() => {
146
+ this.flushTimer = undefined;
147
+ this.state.messageCount += this.pendingMessageCount;
148
+ this.state.ackCount += this.pendingAckCount;
149
+ this.pendingMessageCount = 0;
150
+ this.pendingAckCount = 0;
151
+ this.state.lastEventAt = Date.now();
152
+ this.emit();
153
+ }, this.eventDebounceMs);
154
+ }
155
+
156
+ private emit(): void {
157
+ const snapshot = this.getSnapshot();
158
+ for (const listener of this.listeners) {
159
+ listener(snapshot);
160
+ }
161
+ }
162
+ }
163
+
164
+ export function createEventProjectionStore(options: EventProjectionStoreOptions = {}): EventProjectionStore {
165
+ return new EventProjectionStore(options);
166
+ }
@@ -0,0 +1,169 @@
1
+ import WebSocket from 'ws';
2
+
3
+ export interface TunnelClientOptions {
4
+ proxyHost: string;
5
+ proxyToken: string;
6
+ sessionId: string;
7
+ localSessionPort: number;
8
+ log?: (level: 'info' | 'warn' | 'error', message: string) => void;
9
+ }
10
+
11
+ export class TunnelClient {
12
+ private ws: WebSocket | null = null;
13
+ private reconnectTimeout: NodeJS.Timeout | null = null;
14
+ private isDestroyed = false;
15
+
16
+ constructor(private options: TunnelClientOptions) {}
17
+
18
+ private log(level: 'info' | 'warn' | 'error', message: string) {
19
+ if (this.options.log) {
20
+ this.options.log(level, message);
21
+ return;
22
+ }
23
+
24
+ if (level === 'warn') {
25
+ console.warn(message);
26
+ return;
27
+ }
28
+
29
+ if (level === 'error') {
30
+ console.error(message);
31
+ return;
32
+ }
33
+
34
+ console.log(message);
35
+ }
36
+
37
+ public connect() {
38
+ if (this.isDestroyed) return;
39
+
40
+ let urlStr = this.options.proxyHost;
41
+ if (urlStr.startsWith('http')) {
42
+ urlStr = urlStr.replace(/^http/, 'ws');
43
+ }
44
+ const connectUrl = `${urlStr}/sessions/${encodeURIComponent(this.options.sessionId)}/upstream?token=${encodeURIComponent(this.options.proxyToken)}`;
45
+
46
+ this.ws = new WebSocket(connectUrl);
47
+
48
+ this.ws.on('open', () => {
49
+ this.log('info', `[TunnelClient] Connected upstream for session ${this.options.sessionId}`);
50
+ });
51
+
52
+ this.ws.on('message', async (data: Buffer) => {
53
+ let msg: any;
54
+ try {
55
+ msg = JSON.parse(data.toString('utf-8'));
56
+ } catch {
57
+ return;
58
+ }
59
+
60
+ if (msg.type === 'ping') {
61
+ this.ws?.send(JSON.stringify({ type: 'pong' }));
62
+ return;
63
+ }
64
+
65
+ if (msg.type === 'http_request') {
66
+ await this.handleHttpRequest(msg);
67
+ } else if (msg.type === 'rpc_request') {
68
+ // Advanced hybrid mode: forward to an RPC interface if exposed, or map to HTTP.
69
+ // For now, if we get an RPC request in CLI, proxy it to HTTP.
70
+ await this.handleRpcAsHttp(msg);
71
+ }
72
+ });
73
+
74
+ this.ws.on('close', () => {
75
+ if (!this.isDestroyed) {
76
+ this.log('warn', `[TunnelClient] Disconnected. Reconnecting in 3s...`);
77
+ this.reconnectTimeout = setTimeout(() => this.connect(), 3000);
78
+ }
79
+ });
80
+
81
+ this.ws.on('error', (err: any) => {
82
+ this.log('error', `[TunnelClient] WebSocket error: ${err.message}`);
83
+ });
84
+ }
85
+
86
+ private async handleHttpRequest(msg: any) {
87
+ const localUrl = `http://localhost:${this.options.localSessionPort}${msg.path}`;
88
+ try {
89
+ const fetchOpts: RequestInit = {
90
+ method: msg.method,
91
+ // @ts-ignore
92
+ headers: msg.headers || {},
93
+ };
94
+
95
+ if (msg.body) {
96
+ if (typeof msg.body === 'string') {
97
+ fetchOpts.body = Buffer.from(msg.body, 'base64');
98
+ }
99
+ }
100
+
101
+ const res = await fetch(localUrl, fetchOpts);
102
+ const resBuffer = await res.arrayBuffer();
103
+
104
+ const responseMsg = {
105
+ type: 'http_response',
106
+ id: msg.id,
107
+ status: res.status,
108
+ headers: Object.fromEntries(res.headers.entries()),
109
+ body: Buffer.from(resBuffer).toString('base64')
110
+ };
111
+
112
+ this.ws?.send(JSON.stringify(responseMsg));
113
+ } catch (e: any) {
114
+ this.log('error', `[TunnelClient] Failed to proxy http_request: ${e instanceof Error ? e.message : String(e)}`);
115
+ this.ws?.send(JSON.stringify({
116
+ type: 'http_response',
117
+ id: msg.id,
118
+ status: 502,
119
+ headers: { 'content-type': 'text/plain' },
120
+ body: Buffer.from('Bad Gateway: ' + e.message).toString('base64')
121
+ }));
122
+ }
123
+ }
124
+
125
+ private async handleRpcAsHttp(msg: any) {
126
+ // If the proxy sends an RPC request, map it to the REST API equivalent.
127
+ // E.g. rpc 'sendText' -> HTTP POST /api/sendText
128
+ const localUrl = `http://localhost:${this.options.localSessionPort}/api/${msg.method}`;
129
+ try {
130
+ const res = await fetch(localUrl, {
131
+ method: 'POST',
132
+ headers: {
133
+ 'Content-Type': 'application/json'
134
+ },
135
+ body: JSON.stringify({ args: msg.args })
136
+ });
137
+
138
+ const resData = await res.json();
139
+
140
+ const responseMsg = {
141
+ type: 'rpc_response',
142
+ id: msg.id,
143
+ result: resData
144
+ };
145
+
146
+ this.ws?.send(JSON.stringify(responseMsg));
147
+ } catch (e: any) {
148
+ this.log('error', `[TunnelClient] Failed to proxy rpc_request: ${e instanceof Error ? e.message : String(e)}`);
149
+ this.ws?.send(JSON.stringify({
150
+ type: 'rpc_response',
151
+ id: msg.id,
152
+ error: e.message
153
+ }));
154
+ }
155
+ }
156
+
157
+ public destroy() {
158
+ this.isDestroyed = true;
159
+ if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
160
+ if (this.ws) {
161
+ this.ws.close();
162
+ this.ws = null;
163
+ }
164
+ }
165
+
166
+ public disconnect() {
167
+ this.destroy();
168
+ }
169
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": ["ES2022"],
7
+ "outDir": "./dist",
8
+ "rootDir": "./src",
9
+ "declaration": true,
10
+ "declarationMap": true,
11
+ "composite": true,
12
+ "strict": true,
13
+ "esModuleInterop": true,
14
+ "skipLibCheck": true,
15
+ "paths": {
16
+ "@open-wa/wa-automate": [
17
+ "../wa-automate/dist/index.d.ts"
18
+ ]
19
+ }
20
+ },
21
+ "include": ["src/**/*"],
22
+ "exclude": ["node_modules", "dist", "**/*.test.ts"]
23
+ }