@flowcore/sdk 1.24.4 → 1.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +208 -0
- package/esm/commands/ai-agent-coordinator/context-add-item.command.d.ts +28 -0
- package/esm/commands/ai-agent-coordinator/context-add-item.command.d.ts.map +1 -0
- package/esm/commands/ai-agent-coordinator/context-add-item.command.js +34 -0
- package/esm/commands/ai-agent-coordinator/context-remove-item.command.d.ts +28 -0
- package/esm/commands/ai-agent-coordinator/context-remove-item.command.d.ts.map +1 -0
- package/esm/commands/ai-agent-coordinator/context-remove-item.command.js +32 -0
- package/esm/commands/ai-agent-coordinator/conversation-delete.command.d.ts +25 -0
- package/esm/commands/ai-agent-coordinator/conversation-delete.command.d.ts.map +1 -0
- package/esm/commands/ai-agent-coordinator/conversation-delete.command.js +30 -0
- package/esm/commands/ai-agent-coordinator/conversation-get.command.d.ts +27 -0
- package/esm/commands/ai-agent-coordinator/conversation-get.command.d.ts.map +1 -0
- package/esm/commands/ai-agent-coordinator/conversation-get.command.js +36 -0
- package/esm/commands/ai-agent-coordinator/conversation-list.command.d.ts +23 -0
- package/esm/commands/ai-agent-coordinator/conversation-list.command.d.ts.map +1 -0
- package/esm/commands/ai-agent-coordinator/conversation-list.command.js +29 -0
- package/esm/commands/ai-agent-coordinator/conversation-stream.command.d.ts +30 -0
- package/esm/commands/ai-agent-coordinator/conversation-stream.command.d.ts.map +1 -0
- package/esm/commands/ai-agent-coordinator/conversation-stream.command.js +36 -0
- package/esm/commands/ai-agent-coordinator/mod.d.ts +7 -0
- package/esm/commands/ai-agent-coordinator/mod.d.ts.map +1 -0
- package/esm/commands/ai-agent-coordinator/mod.js +6 -0
- package/esm/common/command.d.ts.map +1 -1
- package/esm/common/command.js +3 -2
- package/esm/common/websocket-client.d.ts +109 -0
- package/esm/common/websocket-client.d.ts.map +1 -0
- package/esm/common/websocket-client.js +391 -0
- package/esm/common/websocket-command.d.ts +54 -0
- package/esm/common/websocket-command.d.ts.map +1 -0
- package/esm/common/websocket-command.js +1 -0
- package/esm/contracts/ai-agent-coordinator-stream.d.ts +85 -0
- package/esm/contracts/ai-agent-coordinator-stream.d.ts.map +1 -0
- package/esm/contracts/ai-agent-coordinator-stream.js +1 -0
- package/esm/contracts/ai-agent-coordinator.d.ts +41 -0
- package/esm/contracts/ai-agent-coordinator.d.ts.map +1 -0
- package/esm/contracts/ai-agent-coordinator.js +1 -0
- package/esm/mod.d.ts +8 -2
- package/esm/mod.d.ts.map +1 -1
- package/esm/mod.js +8 -2
- package/package.json +1 -1
- package/script/commands/ai-agent-coordinator/context-add-item.command.d.ts +28 -0
- package/script/commands/ai-agent-coordinator/context-add-item.command.d.ts.map +1 -0
- package/script/commands/ai-agent-coordinator/context-add-item.command.js +38 -0
- package/script/commands/ai-agent-coordinator/context-remove-item.command.d.ts +28 -0
- package/script/commands/ai-agent-coordinator/context-remove-item.command.d.ts.map +1 -0
- package/script/commands/ai-agent-coordinator/context-remove-item.command.js +36 -0
- package/script/commands/ai-agent-coordinator/conversation-delete.command.d.ts +25 -0
- package/script/commands/ai-agent-coordinator/conversation-delete.command.d.ts.map +1 -0
- package/script/commands/ai-agent-coordinator/conversation-delete.command.js +34 -0
- package/script/commands/ai-agent-coordinator/conversation-get.command.d.ts +27 -0
- package/script/commands/ai-agent-coordinator/conversation-get.command.d.ts.map +1 -0
- package/script/commands/ai-agent-coordinator/conversation-get.command.js +40 -0
- package/script/commands/ai-agent-coordinator/conversation-list.command.d.ts +23 -0
- package/script/commands/ai-agent-coordinator/conversation-list.command.d.ts.map +1 -0
- package/script/commands/ai-agent-coordinator/conversation-list.command.js +33 -0
- package/script/commands/ai-agent-coordinator/conversation-stream.command.d.ts +30 -0
- package/script/commands/ai-agent-coordinator/conversation-stream.command.d.ts.map +1 -0
- package/script/commands/ai-agent-coordinator/conversation-stream.command.js +40 -0
- package/script/commands/ai-agent-coordinator/mod.d.ts +7 -0
- package/script/commands/ai-agent-coordinator/mod.d.ts.map +1 -0
- package/script/commands/ai-agent-coordinator/mod.js +22 -0
- package/script/common/command.d.ts.map +1 -1
- package/script/common/command.js +27 -3
- package/script/common/websocket-client.d.ts +109 -0
- package/script/common/websocket-client.d.ts.map +1 -0
- package/script/common/websocket-client.js +418 -0
- package/script/common/websocket-command.d.ts +54 -0
- package/script/common/websocket-command.d.ts.map +1 -0
- package/script/common/websocket-command.js +2 -0
- package/script/contracts/ai-agent-coordinator-stream.d.ts +85 -0
- package/script/contracts/ai-agent-coordinator-stream.d.ts.map +1 -0
- package/script/contracts/ai-agent-coordinator-stream.js +2 -0
- package/script/contracts/ai-agent-coordinator.d.ts +41 -0
- package/script/contracts/ai-agent-coordinator.d.ts.map +1 -0
- package/script/contracts/ai-agent-coordinator.js +2 -0
- package/script/mod.d.ts +8 -2
- package/script/mod.d.ts.map +1 -1
- package/script/mod.js +11 -2
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./context-add-item.command.js"), exports);
|
|
18
|
+
__exportStar(require("./context-remove-item.command.js"), exports);
|
|
19
|
+
__exportStar(require("./conversation-delete.command.js"), exports);
|
|
20
|
+
__exportStar(require("./conversation-get.command.js"), exports);
|
|
21
|
+
__exportStar(require("./conversation-list.command.js"), exports);
|
|
22
|
+
__exportStar(require("./conversation-stream.command.js"), exports);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"command.d.ts","sourceRoot":"","sources":["../../src/common/command.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAA;AAE3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAG1D;;GAEG;AACH,8BAAsB,OAAO,CAAC,KAAK,EAAE,MAAM;IACzC;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAO;IAEjD;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAE9C;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,YAAY,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC,EAAE,CAAuB;IAE/E;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAA;gBAEnB,KAAK,EAAE,KAAK;IAOxB;;OAEG;cACa,mBAAmB,CAAC,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"command.d.ts","sourceRoot":"","sources":["../../src/common/command.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAA;AAE3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAG1D;;GAEG;AACH,8BAAsB,OAAO,CAAC,KAAK,EAAE,MAAM;IACzC;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAO;IAEjD;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAE9C;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,YAAY,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC,EAAE,CAAuB;IAE/E;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAA;gBAEnB,KAAK,EAAE,KAAK;IAOxB;;OAEG;cACa,mBAAmB,CAAC,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IA0CnF;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,UAAU,IAAI,MAAM;IAEvC;;OAEG;IACH,SAAS,CAAC,SAAS,IAAI,MAAM;IAI7B;;OAEG;IACH,SAAS,CAAC,OAAO,IAAI,MAAM;IAI3B;;OAEG;IACH,SAAS,CAAC,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,SAAS;IAOzE;;OAEG;IACH,SAAS,CAAC,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAQ9C;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,aAAa,CAAC,QAAQ,EAAE,OAAO,GAAG,MAAM;IAE3D;;OAEG;IACH,SAAS,CAAC,iBAAiB,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI;IAIrD;;OAEG;IACU,UAAU,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC;QACzE,YAAY,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC,EAAE,CAAA;QACrC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,SAAS,CAAA;QACnE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAC/B,OAAO,EAAE,MAAM,CAAA;QACf,IAAI,EAAE,MAAM,CAAA;QACZ,MAAM,EAAE,MAAM,CAAA;QACd,aAAa,EAAE,CAAC,QAAQ,EAAE,OAAO,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;QAC9D,eAAe,EAAE,CAAC,MAAM,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA;QAC9E,iBAAiB,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,CAAA;QAC/C,cAAc,EAAE,OAAO,CAAA;QACvB,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,cAAc,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;KAC7D,CAAC;IAeF;;OAEG;cAEa,eAAe,CAAC,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAG5F"}
|
package/script/common/command.js
CHANGED
|
@@ -1,7 +1,29 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
2
25
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
26
|
exports.Command = void 0;
|
|
4
|
-
const tenant_fetch_js_1 = require("../commands/tenant/tenant.fetch.js");
|
|
5
27
|
const client_error_js_1 = require("../exceptions/client-error.js");
|
|
6
28
|
const command_error_js_1 = require("../exceptions/command-error.js");
|
|
7
29
|
const tenant_cache_js_1 = require("./tenant.cache.js");
|
|
@@ -65,13 +87,15 @@ class Command {
|
|
|
65
87
|
}
|
|
66
88
|
let tenant = tenant_cache_js_1.tenantCache.get(inputTenant);
|
|
67
89
|
if (!tenant) {
|
|
68
|
-
|
|
90
|
+
// Dynamically import TenantFetchCommand only when needed
|
|
91
|
+
const { TenantFetchCommand } = await Promise.resolve().then(() => __importStar(require("../commands/tenant/tenant.fetch.js")));
|
|
92
|
+
tenant = await client.execute(new TenantFetchCommand({ tenant: inputTenant }))
|
|
69
93
|
.catch((error) => {
|
|
70
94
|
if (error instanceof client_error_js_1.ClientError && error.status === 403) {
|
|
71
95
|
return {
|
|
72
96
|
isDedicated: false,
|
|
73
97
|
dedicated: null,
|
|
74
|
-
};
|
|
98
|
+
}; // Cast needed as we are not returning the full Tenant shape
|
|
75
99
|
}
|
|
76
100
|
throw error;
|
|
77
101
|
});
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import { type Logger } from "../utils/logger.js";
|
|
3
|
+
import type { ClientOptions } from "./flowcore-client.js";
|
|
4
|
+
import type { ActiveStreamInterface, WebSocketCommand } from "./websocket-command.js";
|
|
5
|
+
/**
|
|
6
|
+
* Interface for OIDC authentication client (reused from NotificationClient context)
|
|
7
|
+
*/
|
|
8
|
+
export type OidcClient = {
|
|
9
|
+
getToken: () => Promise<{
|
|
10
|
+
accessToken: string;
|
|
11
|
+
}>;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Configuration options for the WebSocketClient
|
|
15
|
+
*/
|
|
16
|
+
export type WebSocketClientOptions = {
|
|
17
|
+
/** Interval between reconnect attempts (ms). Defaults to 1000. */
|
|
18
|
+
reconnectInterval?: number;
|
|
19
|
+
/** Maximum number of reconnect attempts. Defaults to undefined (infinite). */
|
|
20
|
+
maxReconnects?: number;
|
|
21
|
+
/** Optional logger instance. */
|
|
22
|
+
logger?: Logger;
|
|
23
|
+
};
|
|
24
|
+
interface MinimalWebSocket {
|
|
25
|
+
readyState: number;
|
|
26
|
+
onopen: (() => void) | null;
|
|
27
|
+
onmessage: ((event: {
|
|
28
|
+
data: string | ArrayBuffer | Buffer;
|
|
29
|
+
}) => void) | null;
|
|
30
|
+
onclose: ((event: {
|
|
31
|
+
code: number;
|
|
32
|
+
reason: string;
|
|
33
|
+
wasClean: boolean;
|
|
34
|
+
}) => void) | null;
|
|
35
|
+
onerror: ((event: Event) => void) | null;
|
|
36
|
+
send(data: string): void;
|
|
37
|
+
close(code?: number, reason?: string): void;
|
|
38
|
+
}
|
|
39
|
+
type WebSocketFactory = (url: string) => MinimalWebSocket;
|
|
40
|
+
/**
|
|
41
|
+
* Generic client for managing a single, persistent WebSocket connection based on a command.
|
|
42
|
+
* Handles connection lifecycle, authentication, reconnection, and message sending/receiving.
|
|
43
|
+
*/
|
|
44
|
+
export declare class WebSocketClient {
|
|
45
|
+
private readonly authOptions;
|
|
46
|
+
private overrideBaseUrl;
|
|
47
|
+
private webSocket;
|
|
48
|
+
private options;
|
|
49
|
+
private logger;
|
|
50
|
+
private reconnectInterval;
|
|
51
|
+
private reconnectAttempts;
|
|
52
|
+
private _isOpen;
|
|
53
|
+
private _isConnecting;
|
|
54
|
+
private webSocketFactory;
|
|
55
|
+
private internalSubject;
|
|
56
|
+
private currentCommand;
|
|
57
|
+
private currentConfig;
|
|
58
|
+
/**
|
|
59
|
+
* Creates a new WebSocketClient instance.
|
|
60
|
+
* @param authOptions - Authentication options (Bearer token via OIDC client or API Key).
|
|
61
|
+
* @param options - Configuration options for the client.
|
|
62
|
+
* @param webSocketFactory - Optional WebSocket factory for testing.
|
|
63
|
+
*/
|
|
64
|
+
constructor(authOptions: ClientOptions, options?: WebSocketClientOptions, webSocketFactory?: WebSocketFactory);
|
|
65
|
+
/**
|
|
66
|
+
* Override the base URL provided by commands.
|
|
67
|
+
* @param baseUrl - The new base URL to use (e.g., "wss://staging-server.api.flowcore.io").
|
|
68
|
+
*/
|
|
69
|
+
setBaseUrl(baseUrl: string): void;
|
|
70
|
+
/**
|
|
71
|
+
* Returns true if the WebSocket connection is currently open.
|
|
72
|
+
*/
|
|
73
|
+
get isOpen(): boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Returns true if the client is currently attempting to establish a WebSocket connection.
|
|
76
|
+
*/
|
|
77
|
+
get isConnecting(): boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Establishes WebSocket connection based on the provided command.
|
|
80
|
+
* Disconnects any existing connection before starting the new one.
|
|
81
|
+
* @param command - The command defining the stream connection details.
|
|
82
|
+
* @returns An interface to interact with the active stream.
|
|
83
|
+
*/
|
|
84
|
+
connect<Config, SendPayload>(command: WebSocketCommand<Config, SendPayload>): Promise<ActiveStreamInterface<SendPayload>>;
|
|
85
|
+
/**
|
|
86
|
+
* Sets up the WebSocket event handlers (onopen, onmessage, onclose, onerror).
|
|
87
|
+
*/
|
|
88
|
+
private setupEventHandlers;
|
|
89
|
+
/**
|
|
90
|
+
* Attempts to reconnect to the WebSocket server using exponential backoff.
|
|
91
|
+
* Requires `currentConfig` to be set.
|
|
92
|
+
*/
|
|
93
|
+
private attemptReconnect;
|
|
94
|
+
/**
|
|
95
|
+
* Sends a message to the currently connected WebSocket.
|
|
96
|
+
* @param message - The message object to send (e.g., { content: "user input" }).
|
|
97
|
+
*/
|
|
98
|
+
private sendMessage;
|
|
99
|
+
/**
|
|
100
|
+
* Closes the WebSocket connection gracefully.
|
|
101
|
+
*/
|
|
102
|
+
disconnect(): void;
|
|
103
|
+
/**
|
|
104
|
+
* Implements the Disposable interface for clean resource management.
|
|
105
|
+
*/
|
|
106
|
+
[Symbol.dispose](): void;
|
|
107
|
+
}
|
|
108
|
+
export {};
|
|
109
|
+
//# sourceMappingURL=websocket-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"websocket-client.d.ts","sourceRoot":"","sources":["../../src/common/websocket-client.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.WebSocketClient = void 0;
|
|
27
|
+
const dntShim = __importStar(require("../_dnt.shims.js"));
|
|
28
|
+
const node_buffer_1 = require("node:buffer");
|
|
29
|
+
const rxjs_1 = require("rxjs");
|
|
30
|
+
const logger_js_1 = require("../utils/logger.js");
|
|
31
|
+
// Maximum reconnection interval in milliseconds
|
|
32
|
+
const MAX_RECONNECT_INTERVAL = 30_000;
|
|
33
|
+
/**
|
|
34
|
+
* Generic client for managing a single, persistent WebSocket connection based on a command.
|
|
35
|
+
* Handles connection lifecycle, authentication, reconnection, and message sending/receiving.
|
|
36
|
+
*/
|
|
37
|
+
class WebSocketClient {
|
|
38
|
+
/**
|
|
39
|
+
* Creates a new WebSocketClient instance.
|
|
40
|
+
* @param authOptions - Authentication options (Bearer token via OIDC client or API Key).
|
|
41
|
+
* @param options - Configuration options for the client.
|
|
42
|
+
* @param webSocketFactory - Optional WebSocket factory for testing.
|
|
43
|
+
*/
|
|
44
|
+
constructor(authOptions, options, webSocketFactory) {
|
|
45
|
+
Object.defineProperty(this, "authOptions", {
|
|
46
|
+
enumerable: true,
|
|
47
|
+
configurable: true,
|
|
48
|
+
writable: true,
|
|
49
|
+
value: authOptions
|
|
50
|
+
});
|
|
51
|
+
Object.defineProperty(this, "overrideBaseUrl", {
|
|
52
|
+
enumerable: true,
|
|
53
|
+
configurable: true,
|
|
54
|
+
writable: true,
|
|
55
|
+
value: void 0
|
|
56
|
+
}); // Field to store the override URL
|
|
57
|
+
Object.defineProperty(this, "webSocket", {
|
|
58
|
+
enumerable: true,
|
|
59
|
+
configurable: true,
|
|
60
|
+
writable: true,
|
|
61
|
+
value: void 0
|
|
62
|
+
});
|
|
63
|
+
Object.defineProperty(this, "options", {
|
|
64
|
+
enumerable: true,
|
|
65
|
+
configurable: true,
|
|
66
|
+
writable: true,
|
|
67
|
+
value: void 0
|
|
68
|
+
});
|
|
69
|
+
Object.defineProperty(this, "logger", {
|
|
70
|
+
enumerable: true,
|
|
71
|
+
configurable: true,
|
|
72
|
+
writable: true,
|
|
73
|
+
value: void 0
|
|
74
|
+
});
|
|
75
|
+
Object.defineProperty(this, "reconnectInterval", {
|
|
76
|
+
enumerable: true,
|
|
77
|
+
configurable: true,
|
|
78
|
+
writable: true,
|
|
79
|
+
value: void 0
|
|
80
|
+
});
|
|
81
|
+
Object.defineProperty(this, "reconnectAttempts", {
|
|
82
|
+
enumerable: true,
|
|
83
|
+
configurable: true,
|
|
84
|
+
writable: true,
|
|
85
|
+
value: 0
|
|
86
|
+
});
|
|
87
|
+
Object.defineProperty(this, "_isOpen", {
|
|
88
|
+
enumerable: true,
|
|
89
|
+
configurable: true,
|
|
90
|
+
writable: true,
|
|
91
|
+
value: false
|
|
92
|
+
});
|
|
93
|
+
Object.defineProperty(this, "_isConnecting", {
|
|
94
|
+
enumerable: true,
|
|
95
|
+
configurable: true,
|
|
96
|
+
writable: true,
|
|
97
|
+
value: false
|
|
98
|
+
});
|
|
99
|
+
Object.defineProperty(this, "webSocketFactory", {
|
|
100
|
+
enumerable: true,
|
|
101
|
+
configurable: true,
|
|
102
|
+
writable: true,
|
|
103
|
+
value: void 0
|
|
104
|
+
});
|
|
105
|
+
// Internal subject to push received data
|
|
106
|
+
Object.defineProperty(this, "internalSubject", {
|
|
107
|
+
enumerable: true,
|
|
108
|
+
configurable: true,
|
|
109
|
+
writable: true,
|
|
110
|
+
value: new rxjs_1.Subject()
|
|
111
|
+
});
|
|
112
|
+
// Store the current command and config for reconnects and sending
|
|
113
|
+
Object.defineProperty(this, "currentCommand", {
|
|
114
|
+
enumerable: true,
|
|
115
|
+
configurable: true,
|
|
116
|
+
writable: true,
|
|
117
|
+
value: null
|
|
118
|
+
});
|
|
119
|
+
Object.defineProperty(this, "currentConfig", {
|
|
120
|
+
enumerable: true,
|
|
121
|
+
configurable: true,
|
|
122
|
+
writable: true,
|
|
123
|
+
value: null
|
|
124
|
+
});
|
|
125
|
+
this.options = { reconnectInterval: 1000, ...options };
|
|
126
|
+
this.logger = options?.logger ?? logger_js_1.defaultLogger;
|
|
127
|
+
this.reconnectInterval = this.options.reconnectInterval;
|
|
128
|
+
this.webSocketFactory = webSocketFactory ?? ((url) => new dntShim.WebSocket(url));
|
|
129
|
+
this.overrideBaseUrl = undefined; // Initialize override URL
|
|
130
|
+
if ("getBearerToken" in authOptions === false && ("apiKey" in authOptions === false)) {
|
|
131
|
+
throw new Error("Invalid authOptions: Must provide either getBearerToken or apiKey/apiKeyId");
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Override the base URL provided by commands.
|
|
136
|
+
* @param baseUrl - The new base URL to use (e.g., "wss://staging-server.api.flowcore.io").
|
|
137
|
+
*/
|
|
138
|
+
setBaseUrl(baseUrl) {
|
|
139
|
+
this.logger.info(`WebSocket base URL overridden to: ${baseUrl}`);
|
|
140
|
+
this.overrideBaseUrl = baseUrl;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Returns true if the WebSocket connection is currently open.
|
|
144
|
+
*/
|
|
145
|
+
get isOpen() {
|
|
146
|
+
return this._isOpen;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Returns true if the client is currently attempting to establish a WebSocket connection.
|
|
150
|
+
*/
|
|
151
|
+
get isConnecting() {
|
|
152
|
+
return this._isConnecting;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Establishes WebSocket connection based on the provided command.
|
|
156
|
+
* Disconnects any existing connection before starting the new one.
|
|
157
|
+
* @param command - The command defining the stream connection details.
|
|
158
|
+
* @returns An interface to interact with the active stream.
|
|
159
|
+
*/
|
|
160
|
+
// Using generic types for the command
|
|
161
|
+
async connect(command) {
|
|
162
|
+
if (this._isConnecting || this._isOpen) {
|
|
163
|
+
this.logger.info("Disconnecting existing stream before starting new one.");
|
|
164
|
+
this.disconnect(); // Ensure clean state
|
|
165
|
+
// Add a small delay to allow disconnect process to settle if needed
|
|
166
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
167
|
+
}
|
|
168
|
+
this.currentCommand = command; // Store command (cast needed)
|
|
169
|
+
const config = command.getConfig();
|
|
170
|
+
this.currentConfig = config; // Store config
|
|
171
|
+
this._isConnecting = true;
|
|
172
|
+
// Use override URL if set, otherwise use command's base URL
|
|
173
|
+
const baseUrl = this.overrideBaseUrl ?? command.getWebSocketBaseUrl();
|
|
174
|
+
const pathSegment = command.getWebSocketPathSegment(config); // Get path segment from command
|
|
175
|
+
this.logger.info(`Attempting to connect stream: ${baseUrl}${pathSegment}`);
|
|
176
|
+
try {
|
|
177
|
+
const urlParams = new URLSearchParams();
|
|
178
|
+
if ("getBearerToken" in this.authOptions && this.authOptions.getBearerToken) {
|
|
179
|
+
const token = await this.authOptions.getBearerToken();
|
|
180
|
+
if (!token)
|
|
181
|
+
throw new Error("Failed to get bearer token");
|
|
182
|
+
urlParams.set("token", token);
|
|
183
|
+
}
|
|
184
|
+
else if ("apiKey" in this.authOptions && this.authOptions.apiKey && this.authOptions.apiKeyId) {
|
|
185
|
+
urlParams.set("api_key", this.authOptions.apiKey);
|
|
186
|
+
urlParams.set("api_key_id", this.authOptions.apiKeyId);
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
throw new Error("Invalid authentication configuration.");
|
|
190
|
+
}
|
|
191
|
+
const streamUrl = `${baseUrl}${pathSegment}?${urlParams.toString()}`; // Construct URL from command parts
|
|
192
|
+
this.logger.debug(`Connecting to WebSocket URL: ${streamUrl}`);
|
|
193
|
+
this.webSocket = this.webSocketFactory(streamUrl);
|
|
194
|
+
this.setupEventHandlers(); // Sets up handlers that push to internalSubject
|
|
195
|
+
// Return the active stream interface
|
|
196
|
+
return {
|
|
197
|
+
output$: this.internalSubject.asObservable(),
|
|
198
|
+
send: (payload) => this.sendMessage(payload),
|
|
199
|
+
disconnect: () => this.disconnect(),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
this.logger.error(`Failed to initiate connection: ${error}`);
|
|
204
|
+
this._isConnecting = false;
|
|
205
|
+
this.currentCommand = null; // Clear command/config on failure
|
|
206
|
+
this.currentConfig = null;
|
|
207
|
+
// Rethrow or handle differently? For now, rethrow.
|
|
208
|
+
throw error; // Make connect promise reject on failure
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Sets up the WebSocket event handlers (onopen, onmessage, onclose, onerror).
|
|
213
|
+
*/
|
|
214
|
+
setupEventHandlers() {
|
|
215
|
+
this.webSocket.onopen = () => {
|
|
216
|
+
this._isOpen = true;
|
|
217
|
+
this._isConnecting = false;
|
|
218
|
+
// Use potentially overridden base URL in logging
|
|
219
|
+
const baseUrl = this.overrideBaseUrl ?? this.currentCommand?.getWebSocketBaseUrl();
|
|
220
|
+
const pathSegment = this.currentCommand?.getWebSocketPathSegment(this.currentConfig);
|
|
221
|
+
this.logger.info(`WebSocket connection opened: ${baseUrl}${pathSegment}`);
|
|
222
|
+
this.reconnectInterval = this.options.reconnectInterval;
|
|
223
|
+
this.reconnectAttempts = 0;
|
|
224
|
+
};
|
|
225
|
+
this.webSocket.onmessage = (event) => {
|
|
226
|
+
try {
|
|
227
|
+
let parsedData;
|
|
228
|
+
// Handle various data types from WebSocket
|
|
229
|
+
if (event.data instanceof ArrayBuffer) {
|
|
230
|
+
parsedData = new TextDecoder().decode(event.data);
|
|
231
|
+
}
|
|
232
|
+
else if (node_buffer_1.Buffer.isBuffer(event.data)) {
|
|
233
|
+
parsedData = event.data.toString();
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
parsedData = event.data;
|
|
237
|
+
}
|
|
238
|
+
const chunk = JSON.parse(parsedData); // Assume valid JSON structure
|
|
239
|
+
// Basic validation - check if it has a 'type' property
|
|
240
|
+
if (typeof chunk !== "object" || chunk === null || typeof chunk.type !== "string") {
|
|
241
|
+
this.logger.warn(`Received invalid chunk format: ${parsedData}`);
|
|
242
|
+
return; // Ignore invalid chunks
|
|
243
|
+
}
|
|
244
|
+
this.logger.debug(`Received chunk: ${chunk.type}`); // Log chunk type
|
|
245
|
+
this.internalSubject.next(chunk); // Push to internal subject
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
this.logger.error(`Error processing received message: ${error}`);
|
|
249
|
+
// Optionally emit an error on the subject?
|
|
250
|
+
// this.internalSubject.error(new Error(`Failed to parse message: ${error.message}`));
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
this.webSocket.onclose = (event) => {
|
|
254
|
+
const wasOpen = this._isOpen;
|
|
255
|
+
this._isOpen = false;
|
|
256
|
+
this._isConnecting = false;
|
|
257
|
+
// Use potentially overridden base URL in logging
|
|
258
|
+
const baseUrl = this.overrideBaseUrl ?? this.currentCommand?.getWebSocketBaseUrl();
|
|
259
|
+
const pathSegment = this.currentCommand?.getWebSocketPathSegment(this.currentConfig);
|
|
260
|
+
this.logger.info(`WebSocket connection closed: ${baseUrl}${pathSegment} Code [${event.code}], Reason: ${event.reason || "No reason given"}. Was open: ${wasOpen}`);
|
|
261
|
+
if (wasOpen && event.code !== 1000 && this.currentCommand) { // Only reconnect if command is still set
|
|
262
|
+
this.attemptReconnect();
|
|
263
|
+
}
|
|
264
|
+
else {
|
|
265
|
+
this.logger.info(`Completing internal subject due to close event.`);
|
|
266
|
+
this.internalSubject.complete(); // Complete subject on final close
|
|
267
|
+
this.currentCommand = null; // Clear state
|
|
268
|
+
this.currentConfig = null;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
this.webSocket.onerror = () => {
|
|
272
|
+
// Use potentially overridden base URL in logging
|
|
273
|
+
const baseUrl = this.overrideBaseUrl ?? this.currentCommand?.getWebSocketBaseUrl();
|
|
274
|
+
const pathSegment = this.currentCommand?.getWebSocketPathSegment(this.currentConfig);
|
|
275
|
+
this.logger.error(`WebSocket encountered an error for stream: ${baseUrl}${pathSegment}.`);
|
|
276
|
+
if (this.webSocket.readyState !== dntShim.WebSocket.CLOSED &&
|
|
277
|
+
this.webSocket.readyState !== dntShim.WebSocket.CLOSING) {
|
|
278
|
+
this.webSocket.close(1011, "WebSocket error");
|
|
279
|
+
}
|
|
280
|
+
// Error event usually followed by onclose, which handles completion/reconnect
|
|
281
|
+
// Emit error on subject *before* close handling potentially completes it
|
|
282
|
+
this.internalSubject.error(new Error("WebSocket encountered an error"));
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Attempts to reconnect to the WebSocket server using exponential backoff.
|
|
287
|
+
* Requires `currentConfig` to be set.
|
|
288
|
+
*/
|
|
289
|
+
attemptReconnect() {
|
|
290
|
+
if (!this.currentCommand || !this.currentConfig) {
|
|
291
|
+
this.logger.error("Cannot reconnect without current command/config.");
|
|
292
|
+
if (!this.internalSubject.closed)
|
|
293
|
+
this.internalSubject.complete();
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (this._isConnecting) {
|
|
297
|
+
this.logger.debug("Reconnect attempt already in progress.");
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
// Use potentially overridden base URL
|
|
301
|
+
const baseUrl = this.overrideBaseUrl ?? this.currentCommand.getWebSocketBaseUrl();
|
|
302
|
+
const pathSegment = this.currentCommand.getWebSocketPathSegment(this.currentConfig);
|
|
303
|
+
if (this.options.maxReconnects && this.reconnectAttempts >= this.options.maxReconnects) {
|
|
304
|
+
this.logger.error(`Max reconnect attempts (${this.reconnectAttempts}/${this.options.maxReconnects}) reached. Giving up: ${baseUrl}${pathSegment}`);
|
|
305
|
+
if (!this.internalSubject.closed)
|
|
306
|
+
this.internalSubject.complete();
|
|
307
|
+
this.currentCommand = null;
|
|
308
|
+
this.currentConfig = null;
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
this.reconnectAttempts++;
|
|
312
|
+
this._isConnecting = true;
|
|
313
|
+
this.logger.info(`Attempting reconnection ${this.reconnectAttempts}${this.options.maxReconnects ? `/${this.options.maxReconnects}` : ""}
|
|
314
|
+
for ${baseUrl}${pathSegment} in ${this.reconnectInterval} ms...`);
|
|
315
|
+
setTimeout(async () => {
|
|
316
|
+
// Check if disconnect was called while waiting
|
|
317
|
+
if (!this.currentCommand || !this.currentConfig) {
|
|
318
|
+
this.logger.info("Reconnect cancelled as disconnect was called.");
|
|
319
|
+
this._isConnecting = false; // Ensure flag is reset
|
|
320
|
+
if (!this.internalSubject.closed)
|
|
321
|
+
this.internalSubject.complete();
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
// Directly attempt to establish connection *without* calling this.connect()
|
|
325
|
+
try {
|
|
326
|
+
const urlParams = new URLSearchParams();
|
|
327
|
+
// --- Reuse auth logic from connect() ---
|
|
328
|
+
if ("getBearerToken" in this.authOptions && this.authOptions.getBearerToken) {
|
|
329
|
+
const token = await this.authOptions.getBearerToken();
|
|
330
|
+
if (!token)
|
|
331
|
+
throw new Error("Reconnect failed: Could not get bearer token");
|
|
332
|
+
urlParams.set("token", token);
|
|
333
|
+
}
|
|
334
|
+
else if ("apiKey" in this.authOptions && this.authOptions.apiKey && this.authOptions.apiKeyId) {
|
|
335
|
+
urlParams.set("api_key", this.authOptions.apiKey);
|
|
336
|
+
urlParams.set("api_key_id", this.authOptions.apiKeyId);
|
|
337
|
+
}
|
|
338
|
+
else {
|
|
339
|
+
throw new Error("Reconnect failed: Invalid authentication configuration.");
|
|
340
|
+
}
|
|
341
|
+
// --- End auth logic ---
|
|
342
|
+
// Use potentially overridden base URL for reconnect URL
|
|
343
|
+
const streamUrl = `${baseUrl}${pathSegment}?${urlParams.toString()}`;
|
|
344
|
+
this.logger.debug(`Reconnecting to WebSocket URL: ${streamUrl}`);
|
|
345
|
+
this.webSocket = this.webSocketFactory(streamUrl);
|
|
346
|
+
// Connecting flag will be reset in onopen/onerror/onclose
|
|
347
|
+
this.setupEventHandlers();
|
|
348
|
+
}
|
|
349
|
+
catch (error) {
|
|
350
|
+
this.logger.error(`Reconnect attempt connection failed: ${error}`);
|
|
351
|
+
this._isConnecting = false; // Reset connection flag on immediate error
|
|
352
|
+
// Error during reconnect setup, trigger another attempt after backoff
|
|
353
|
+
// We might get stuck here if auth always fails, consider adding specific error handling
|
|
354
|
+
this.reconnectInterval = Math.min(MAX_RECONNECT_INTERVAL, this.reconnectInterval * 2); // Apply backoff before retrying
|
|
355
|
+
this.attemptReconnect();
|
|
356
|
+
}
|
|
357
|
+
}, this.reconnectInterval);
|
|
358
|
+
// Apply backoff interval for the *next* potential reconnect attempt
|
|
359
|
+
this.reconnectInterval = Math.min(MAX_RECONNECT_INTERVAL, this.reconnectInterval * 2);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Sends a message to the currently connected WebSocket.
|
|
363
|
+
* @param message - The message object to send (e.g., { content: "user input" }).
|
|
364
|
+
*/
|
|
365
|
+
sendMessage(payload) {
|
|
366
|
+
const openState = 1; // WebSocket.OPEN is typically 1
|
|
367
|
+
if (!this._isOpen || this.webSocket.readyState !== openState || !this.currentCommand) {
|
|
368
|
+
this.logger.warn("Cannot send message: WebSocket is not open or command not set.");
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
try {
|
|
372
|
+
// Use command's serializer or default to JSON.stringify
|
|
373
|
+
const serializer = this.currentCommand.serializeSendPayload ?? JSON.stringify;
|
|
374
|
+
const dataToSend = serializer(payload);
|
|
375
|
+
this.webSocket.send(dataToSend);
|
|
376
|
+
this.logger.debug(`Sent message: ${dataToSend}`);
|
|
377
|
+
return true;
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
this.logger.error(`Failed to send message: ${error}`);
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Closes the WebSocket connection gracefully.
|
|
386
|
+
*/
|
|
387
|
+
disconnect() {
|
|
388
|
+
this.logger.info("Disconnect called by user.");
|
|
389
|
+
const commandToClear = this.currentCommand; // Store ref before clearing
|
|
390
|
+
this.currentCommand = null; // Prevent reconnects
|
|
391
|
+
this.currentConfig = null;
|
|
392
|
+
if (this.webSocket) {
|
|
393
|
+
if (this._isOpen || this._isConnecting) {
|
|
394
|
+
this.webSocket.close(1000, "Disconnected by user");
|
|
395
|
+
}
|
|
396
|
+
else {
|
|
397
|
+
this.logger.debug("WebSocket already closed or closing.");
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
else {
|
|
401
|
+
this.logger.debug("No WebSocket instance to disconnect.");
|
|
402
|
+
}
|
|
403
|
+
this._isOpen = false;
|
|
404
|
+
this._isConnecting = false;
|
|
405
|
+
// Complete the subject if it hasn't been completed by onclose
|
|
406
|
+
if (commandToClear && !this.internalSubject.closed) {
|
|
407
|
+
this.logger.info("Completing internal subject due to disconnect call.");
|
|
408
|
+
this.internalSubject.complete();
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Implements the Disposable interface for clean resource management.
|
|
413
|
+
*/
|
|
414
|
+
[Symbol.dispose]() {
|
|
415
|
+
this.disconnect();
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
exports.WebSocketClient = WebSocketClient;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Observable } from "rxjs";
|
|
2
|
+
import type { StreamChunk } from "../contracts/ai-agent-coordinator-stream.js";
|
|
3
|
+
/**
|
|
4
|
+
* Interface for a command that configures a WebSocket stream connection.
|
|
5
|
+
* @template Config - The type of the configuration data needed to initiate the stream.
|
|
6
|
+
* @template SendPayload - The type of data that can be sent *to* the stream after connection.
|
|
7
|
+
*/
|
|
8
|
+
export interface WebSocketCommand<Config, SendPayload> {
|
|
9
|
+
/**
|
|
10
|
+
* Gets the configuration data needed to establish the connection.
|
|
11
|
+
*/
|
|
12
|
+
getConfig(): Config;
|
|
13
|
+
/**
|
|
14
|
+
* Gets the base WebSocket URL (e.g., wss://server.api.flowcore.io).
|
|
15
|
+
* @returns The base WebSocket URL string.
|
|
16
|
+
*/
|
|
17
|
+
getWebSocketBaseUrl(): string;
|
|
18
|
+
/**
|
|
19
|
+
* Gets the specific path segment for the WebSocket URL based on the config
|
|
20
|
+
* (e.g., /api/v1/stream/entity/{id}).
|
|
21
|
+
* @param config - The configuration object.
|
|
22
|
+
* @returns The path segment string.
|
|
23
|
+
*/
|
|
24
|
+
getWebSocketPathSegment(config: Config): string;
|
|
25
|
+
/**
|
|
26
|
+
* Serializes the payload to be sent over the WebSocket.
|
|
27
|
+
* Default implementation might be JSON.stringify.
|
|
28
|
+
* @param payload - The payload object to send.
|
|
29
|
+
* @returns The serialized string representation.
|
|
30
|
+
*/
|
|
31
|
+
serializeSendPayload?(payload: SendPayload): string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Interface representing an active WebSocket stream connection.
|
|
35
|
+
* @template SendPayload - The type of data that can be sent to the stream.
|
|
36
|
+
*/
|
|
37
|
+
export interface ActiveStreamInterface<SendPayload> {
|
|
38
|
+
/**
|
|
39
|
+
* An Observable emitting the raw data chunks received from the WebSocket.
|
|
40
|
+
* Consumers should filter/map this observable based on the specific stream protocol.
|
|
41
|
+
*/
|
|
42
|
+
output$: Observable<StreamChunk>;
|
|
43
|
+
/**
|
|
44
|
+
* Sends a payload to the WebSocket stream.
|
|
45
|
+
* @param payload - The data to send, conforming to the SendPayload type.
|
|
46
|
+
* @returns True if the message was queued to be sent, false otherwise (e.g., socket not open).
|
|
47
|
+
*/
|
|
48
|
+
send(payload: SendPayload): boolean;
|
|
49
|
+
/**
|
|
50
|
+
* Disconnects the WebSocket stream gracefully.
|
|
51
|
+
*/
|
|
52
|
+
disconnect(): void;
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=websocket-command.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"websocket-command.d.ts","sourceRoot":"","sources":["../../src/common/websocket-command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,MAAM,CAAA;AACtC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6CAA6C,CAAA;AAE9E;;;;GAIG;AACH,MAAM,WAAW,gBAAgB,CAAC,MAAM,EAAE,WAAW;IACnD;;OAEG;IACH,SAAS,IAAI,MAAM,CAAA;IAEnB;;;OAGG;IACH,mBAAmB,IAAI,MAAM,CAAA;IAE7B;;;;;OAKG;IACH,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAA;IAE/C;;;;;OAKG;IACH,oBAAoB,CAAC,CAAC,OAAO,EAAE,WAAW,GAAG,MAAM,CAAA;CACpD;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAqB,CAAC,WAAW;IAChD;;;OAGG;IACH,OAAO,EAAE,UAAU,CAAC,WAAW,CAAC,CAAA;IAEhC;;;;OAIG;IACH,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAA;IAEnC;;OAEG;IACH,UAAU,IAAI,IAAI,CAAA;CACnB"}
|