@liveport/agent-sdk 0.1.1 → 0.1.2

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/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  // src/index.ts
2
+ import WebSocket from "ws";
2
3
  var TunnelTimeoutError = class extends Error {
3
4
  constructor(timeout) {
4
5
  super(`Tunnel not available within ${timeout}ms timeout`);
@@ -15,23 +16,150 @@ var ApiError = class extends Error {
15
16
  this.code = code;
16
17
  }
17
18
  };
19
+ var ConnectionError = class extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = "ConnectionError";
23
+ }
24
+ };
18
25
  var LivePortAgent = class {
19
26
  config;
20
27
  abortController = null;
21
- waitInProgress = false;
28
+ wsConnection = null;
22
29
  constructor(config) {
23
30
  if (!config.key) {
24
31
  throw new Error("Bridge key is required");
25
32
  }
26
- if (config.timeout !== void 0 && config.timeout <= 0) {
27
- throw new Error("Timeout must be greater than 0");
28
- }
29
33
  this.config = {
30
34
  key: config.key,
31
- apiUrl: config.apiUrl || "https://app.liveport.dev",
35
+ apiUrl: config.apiUrl || "https://liveport.dev",
36
+ tunnelUrl: config.tunnelUrl || "https://tunnel.liveport.online",
32
37
  timeout: config.timeout || 3e4
33
38
  };
34
39
  }
40
+ /**
41
+ * Connect to the tunnel server and create a tunnel for the given local port.
42
+ *
43
+ * Opens a WebSocket to the tunnel server, authenticates with the bridge key,
44
+ * and waits for a tunnel assignment. Incoming HTTP requests from the tunnel
45
+ * are forwarded to localhost:<port>.
46
+ *
47
+ * @param port - The local port to tunnel
48
+ * @param options - Connection options
49
+ * @returns The tunnel info once connected
50
+ * @throws ConnectionError if the connection fails or times out
51
+ */
52
+ async connect(port, options) {
53
+ if (this.wsConnection) {
54
+ throw new ConnectionError("Already connected \u2014 call disconnect() first");
55
+ }
56
+ const serverUrl = options?.serverUrl || this.config.tunnelUrl;
57
+ const timeout = options?.timeout ?? this.config.timeout;
58
+ const WS = options?._WebSocketClass ?? WebSocket;
59
+ return new Promise((resolve, reject) => {
60
+ const wsUrl = this.buildWebSocketUrl(serverUrl);
61
+ const headers = {
62
+ "X-Bridge-Key": this.config.key,
63
+ "X-Local-Port": String(port)
64
+ };
65
+ const socket = new WS(wsUrl, {
66
+ headers,
67
+ perMessageDeflate: false
68
+ });
69
+ this.wsConnection = socket;
70
+ let settled = false;
71
+ const connectTimeout = setTimeout(() => {
72
+ if (!settled) {
73
+ settled = true;
74
+ socket.close();
75
+ reject(new ConnectionError("Connection timeout"));
76
+ }
77
+ }, timeout);
78
+ socket.on("open", () => {
79
+ });
80
+ socket.on("message", (data) => {
81
+ try {
82
+ const message = JSON.parse(data.toString());
83
+ this.handleWsMessage(message, port, socket);
84
+ if (message.type === "connected" && !settled) {
85
+ clearTimeout(connectTimeout);
86
+ settled = true;
87
+ const payload = message.payload;
88
+ const tunnel = {
89
+ tunnelId: payload.tunnelId,
90
+ subdomain: payload.subdomain,
91
+ url: payload.url,
92
+ localPort: port,
93
+ // Use server-provided createdAt if the server sends it; fall back to client time
94
+ // (ConnectedPayload doesn't include createdAt today, but may in a future server version)
95
+ createdAt: payload.createdAt ? new Date(payload.createdAt) : /* @__PURE__ */ new Date(),
96
+ expiresAt: new Date(payload.expiresAt)
97
+ };
98
+ resolve(tunnel);
99
+ } else if (message.type === "error" && message.payload?.fatal && !settled) {
100
+ clearTimeout(connectTimeout);
101
+ settled = true;
102
+ reject(new ConnectionError(message.payload.message));
103
+ }
104
+ } catch {
105
+ }
106
+ });
107
+ socket.on("close", () => {
108
+ clearTimeout(connectTimeout);
109
+ if (!settled) {
110
+ settled = true;
111
+ reject(new ConnectionError("Connection closed before tunnel was established"));
112
+ }
113
+ if (this.wsConnection === socket) {
114
+ this.wsConnection = null;
115
+ }
116
+ });
117
+ socket.on("error", (err) => {
118
+ clearTimeout(connectTimeout);
119
+ if (!settled) {
120
+ settled = true;
121
+ if (this.wsConnection === socket) {
122
+ this.wsConnection = null;
123
+ }
124
+ reject(new ConnectionError(err.message));
125
+ }
126
+ });
127
+ });
128
+ }
129
+ /**
130
+ * Wait for the tunnel's public URL to become reachable.
131
+ *
132
+ * Polls the tunnel's public URL (not localhost) with HTTP GET requests
133
+ * until a 2xx response is received, or the timeout is exceeded. This
134
+ * validates the full tunnel path end-to-end.
135
+ *
136
+ * @param tunnel - The tunnel to check
137
+ * @param options - Wait options
138
+ * @throws TunnelTimeoutError if the tunnel is not ready within timeout
139
+ */
140
+ async waitForReady(tunnel, options) {
141
+ const timeout = options?.timeout ?? this.config.timeout;
142
+ const pollInterval = options?.pollInterval ?? 1e3;
143
+ const healthPath = options?.healthPath ?? "/";
144
+ const url = tunnel.url + healthPath;
145
+ const startTime = Date.now();
146
+ while (Date.now() - startTime < timeout) {
147
+ try {
148
+ const response = await fetch(url, {
149
+ method: "GET",
150
+ signal: AbortSignal.timeout(Math.max(1, Math.min(5e3, timeout - (Date.now() - startTime))))
151
+ });
152
+ if (response.ok) {
153
+ return;
154
+ }
155
+ } catch {
156
+ }
157
+ const remaining = timeout - (Date.now() - startTime);
158
+ if (remaining <= 0) break;
159
+ await this.sleep(Math.min(pollInterval, remaining));
160
+ }
161
+ throw new TunnelTimeoutError(timeout);
162
+ }
35
163
  /**
36
164
  * Wait for a tunnel to become available
37
165
  *
@@ -43,54 +171,35 @@ var LivePortAgent = class {
43
171
  * @throws ApiError if the API request fails
44
172
  */
45
173
  async waitForTunnel(options) {
46
- if (this.waitInProgress) {
47
- throw new Error(
48
- "Wait already in progress. Call disconnect() first or wait for the current operation to complete."
49
- );
50
- }
51
174
  const timeout = options?.timeout ?? this.config.timeout;
52
175
  const pollInterval = options?.pollInterval ?? 1e3;
53
- if (timeout <= 0) {
54
- throw new Error("Timeout must be greater than 0");
55
- }
56
- if (pollInterval <= 0) {
57
- throw new Error("Poll interval must be greater than 0");
58
- }
59
- if (pollInterval > timeout) {
60
- throw new Error("Poll interval cannot exceed timeout");
61
- }
62
- this.waitInProgress = true;
63
176
  this.abortController = new AbortController();
64
177
  const startTime = Date.now();
65
- try {
66
- while (Date.now() - startTime < timeout) {
67
- try {
68
- const response = await this.makeRequest(
69
- `/api/agent/tunnels/wait?timeout=${Math.min(pollInterval * 5, timeout - (Date.now() - startTime))}`,
70
- { signal: this.abortController.signal }
71
- );
72
- if (response.ok) {
73
- const data = await response.json();
74
- if (data.tunnel) {
75
- return this.parseTunnel(data.tunnel);
76
- }
77
- } else if (response.status === 408) {
78
- } else {
79
- const error = await response.json().catch(() => ({ code: "UNKNOWN", message: "Request failed" }));
80
- throw new ApiError(response.status, error.code, error.message);
81
- }
82
- } catch (err) {
83
- if (err instanceof ApiError) throw err;
84
- if (err.name === "AbortError") {
85
- throw new Error("Wait cancelled");
178
+ while (Date.now() - startTime < timeout) {
179
+ try {
180
+ const response = await this.makeRequest(
181
+ `/api/agent/tunnels/wait?timeout=${Math.min(pollInterval * 5, timeout - (Date.now() - startTime))}`,
182
+ { signal: this.abortController.signal }
183
+ );
184
+ if (response.ok) {
185
+ const data = await response.json();
186
+ if (data.tunnel) {
187
+ return this.parseTunnel(data.tunnel);
86
188
  }
189
+ } else if (response.status === 408) {
190
+ } else {
191
+ const error = await response.json().catch(() => ({ code: "UNKNOWN", message: "Request failed" }));
192
+ throw new ApiError(response.status, error.code, error.message);
193
+ }
194
+ } catch (err) {
195
+ if (err instanceof ApiError) throw err;
196
+ if (err.name === "AbortError") {
197
+ throw new Error("Wait cancelled");
87
198
  }
88
- await this.sleep(pollInterval);
89
199
  }
90
- throw new TunnelTimeoutError(timeout);
91
- } finally {
92
- this.waitInProgress = false;
200
+ await this.sleep(pollInterval);
93
201
  }
202
+ throw new TunnelTimeoutError(timeout);
94
203
  }
95
204
  /**
96
205
  * List all active tunnels for this bridge key
@@ -110,13 +219,115 @@ var LivePortAgent = class {
110
219
  /**
111
220
  * Disconnect and clean up
112
221
  *
113
- * Cancels any pending waitForTunnel calls.
222
+ * Cancels any pending waitForTunnel calls and closes any WebSocket
223
+ * connection created by connect().
114
224
  */
115
225
  async disconnect() {
116
226
  if (this.abortController) {
117
227
  this.abortController.abort();
118
228
  this.abortController = null;
119
229
  }
230
+ if (this.wsConnection) {
231
+ const ws = this.wsConnection;
232
+ this.wsConnection = null;
233
+ if (ws.readyState === 1 || ws.readyState === 0) {
234
+ ws.close(1e3, "Agent disconnect");
235
+ }
236
+ }
237
+ }
238
+ /**
239
+ * Build WebSocket URL from server URL
240
+ */
241
+ buildWebSocketUrl(serverUrl) {
242
+ const url = new URL(serverUrl);
243
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
244
+ url.pathname = "/connect";
245
+ return url.toString();
246
+ }
247
+ /**
248
+ * Handle incoming WebSocket messages from the tunnel server
249
+ */
250
+ handleWsMessage(message, localPort, socket) {
251
+ switch (message.type) {
252
+ case "http_request":
253
+ void this.handleHttpRequest(message, localPort, socket).catch(() => {
254
+ });
255
+ break;
256
+ case "heartbeat":
257
+ if (socket.readyState === 1) {
258
+ socket.send(JSON.stringify({
259
+ type: "heartbeat_ack",
260
+ timestamp: Date.now()
261
+ }));
262
+ }
263
+ break;
264
+ }
265
+ }
266
+ /**
267
+ * Forward an HTTP request from the tunnel server to localhost
268
+ */
269
+ async handleHttpRequest(message, localPort, socket) {
270
+ const payload = message.payload;
271
+ try {
272
+ const safePath = payload.path?.startsWith("/") ? payload.path : `/${payload.path || ""}`;
273
+ const url = `http://localhost:${localPort}${safePath}`;
274
+ const HOP_BY_HOP = /* @__PURE__ */ new Set([
275
+ "host",
276
+ "connection",
277
+ "transfer-encoding",
278
+ "te",
279
+ "trailer",
280
+ "upgrade",
281
+ "keep-alive",
282
+ "proxy-authenticate",
283
+ "proxy-authorization"
284
+ ]);
285
+ const safeHeaders = Object.fromEntries(
286
+ Object.entries(payload.headers || {}).filter(([k]) => !HOP_BY_HOP.has(k.toLowerCase()))
287
+ );
288
+ const requestInit = {
289
+ method: payload.method,
290
+ headers: safeHeaders
291
+ };
292
+ if (payload.body) {
293
+ requestInit.body = Buffer.from(payload.body, "base64");
294
+ }
295
+ const response = await fetch(url, requestInit);
296
+ const responseBody = await response.arrayBuffer();
297
+ const responseHeaders = {};
298
+ response.headers.forEach((value, key) => {
299
+ responseHeaders[key] = value;
300
+ });
301
+ const responseMessage = {
302
+ type: "http_response",
303
+ id: message.id,
304
+ timestamp: Date.now(),
305
+ payload: {
306
+ status: response.status,
307
+ headers: responseHeaders,
308
+ body: responseBody.byteLength > 0 ? Buffer.from(responseBody).toString("base64") : void 0
309
+ }
310
+ };
311
+ if (socket.readyState === 1) {
312
+ socket.send(JSON.stringify(responseMessage));
313
+ }
314
+ } catch (err) {
315
+ const errorResponse = {
316
+ type: "http_response",
317
+ id: message.id,
318
+ timestamp: Date.now(),
319
+ payload: {
320
+ status: 502,
321
+ headers: { "Content-Type": "text/plain" },
322
+ body: Buffer.from(
323
+ `Error connecting to local server: ${err.message}`
324
+ ).toString("base64")
325
+ }
326
+ };
327
+ if (socket.readyState === 1) {
328
+ socket.send(JSON.stringify(errorResponse));
329
+ }
330
+ }
120
331
  }
121
332
  /**
122
333
  * Make an authenticated API request
@@ -136,45 +347,25 @@ var LivePortAgent = class {
136
347
  * Parse tunnel response into AgentTunnel
137
348
  */
138
349
  parseTunnel(data) {
139
- const tunnelId = data.tunnelId || data.id;
350
+ const tunnelId = data.tunnelId ?? data.id;
140
351
  const subdomain = data.subdomain;
141
352
  const url = data.url;
142
353
  const localPort = data.localPort;
143
- const createdAt = data.createdAt;
144
- const expiresAt = data.expiresAt;
145
- if (!tunnelId || typeof tunnelId !== "string") {
146
- throw new ApiError(500, "INVALID_RESPONSE", "Missing or invalid tunnelId in response");
147
- }
148
- if (!subdomain || typeof subdomain !== "string") {
149
- throw new ApiError(500, "INVALID_RESPONSE", "Missing or invalid subdomain in response");
150
- }
151
- if (!url || typeof url !== "string") {
152
- throw new ApiError(500, "INVALID_RESPONSE", "Missing or invalid url in response");
153
- }
154
- if (typeof localPort !== "number" || localPort <= 0 || localPort > 65535) {
155
- throw new ApiError(500, "INVALID_RESPONSE", "Missing or invalid localPort in response");
156
- }
157
- if (!createdAt || typeof createdAt !== "string") {
158
- throw new ApiError(500, "INVALID_RESPONSE", "Missing or invalid createdAt in response");
159
- }
160
- if (!expiresAt || typeof expiresAt !== "string") {
161
- throw new ApiError(500, "INVALID_RESPONSE", "Missing or invalid expiresAt in response");
162
- }
163
- const createdAtDate = new Date(createdAt);
164
- const expiresAtDate = new Date(expiresAt);
165
- if (isNaN(createdAtDate.getTime())) {
166
- throw new ApiError(500, "INVALID_RESPONSE", "Invalid createdAt date format");
354
+ if (!tunnelId || !subdomain || !url || localPort == null || typeof localPort !== "number") {
355
+ throw new Error(
356
+ `parseTunnel: missing required fields in API response (tunnelId=${tunnelId}, subdomain=${subdomain}, url=${url}, localPort=${localPort})`
357
+ );
167
358
  }
168
- if (isNaN(expiresAtDate.getTime())) {
169
- throw new ApiError(500, "INVALID_RESPONSE", "Invalid expiresAt date format");
359
+ if (!data.expiresAt) {
360
+ throw new Error("parseTunnel: missing expiresAt in API response");
170
361
  }
171
362
  return {
172
363
  tunnelId,
173
364
  subdomain,
174
365
  url,
175
366
  localPort,
176
- createdAt: createdAtDate,
177
- expiresAt: expiresAtDate
367
+ createdAt: data.createdAt ? new Date(data.createdAt) : /* @__PURE__ */ new Date(),
368
+ expiresAt: new Date(data.expiresAt)
178
369
  };
179
370
  }
180
371
  /**
@@ -186,6 +377,7 @@ var LivePortAgent = class {
186
377
  };
187
378
  export {
188
379
  ApiError,
380
+ ConnectionError,
189
381
  LivePortAgent,
190
382
  TunnelTimeoutError
191
383
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * LivePort Agent SDK\n *\n * TypeScript SDK for AI agents to wait for and access localhost tunnels.\n */\n\nimport type { Tunnel } from \"@liveport/shared\";\n\nexport interface LivePortAgentConfig {\n /** Bridge key for authentication */\n key: string;\n /** API base URL (default: https://app.liveport.dev) */\n apiUrl?: string;\n /** Default timeout in milliseconds (default: 30000) */\n timeout?: number;\n}\n\nexport interface WaitForTunnelOptions {\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Poll interval in milliseconds (default: 1000) */\n pollInterval?: number;\n}\n\nexport interface AgentTunnel {\n tunnelId: string;\n subdomain: string;\n url: string;\n localPort: number;\n createdAt: Date;\n expiresAt: Date;\n}\n\n/** Error thrown when tunnel wait times out */\nexport class TunnelTimeoutError extends Error {\n constructor(timeout: number) {\n super(`Tunnel not available within ${timeout}ms timeout`);\n this.name = \"TunnelTimeoutError\";\n }\n}\n\n/** Error thrown when API request fails */\nexport class ApiError extends Error {\n public readonly statusCode: number;\n public readonly code: string;\n\n constructor(statusCode: number, code: string, message: string) {\n super(message);\n this.name = \"ApiError\";\n this.statusCode = statusCode;\n this.code = code;\n }\n}\n\n/**\n * LivePort Agent SDK\n *\n * Allows AI agents to wait for and access localhost tunnels.\n *\n * @example\n * ```typescript\n * import { LivePortAgent } from '@liveport/agent-sdk';\n *\n * const agent = new LivePortAgent({\n * key: process.env.LIVEPORT_BRIDGE_KEY!\n * });\n *\n * // Wait for a tunnel to become available\n * const tunnel = await agent.waitForTunnel({ timeout: 30000 });\n * console.log(`Testing at: ${tunnel.url}`);\n *\n * // Run your tests against tunnel.url\n *\n * // Clean up when done\n * await agent.disconnect();\n * ```\n */\nexport class LivePortAgent {\n private config: Required<LivePortAgentConfig>;\n private abortController: AbortController | null = null;\n private waitInProgress = false;\n\n constructor(config: LivePortAgentConfig) {\n if (!config.key) {\n throw new Error(\"Bridge key is required\");\n }\n\n // Validate timeout before applying default\n if (config.timeout !== undefined && config.timeout <= 0) {\n throw new Error(\"Timeout must be greater than 0\");\n }\n\n this.config = {\n key: config.key,\n apiUrl: config.apiUrl || \"https://app.liveport.dev\",\n timeout: config.timeout || 30000,\n };\n }\n\n /**\n * Wait for a tunnel to become available\n *\n * Long-polls the API until a tunnel is ready or timeout is reached.\n *\n * @param options - Wait options\n * @returns The tunnel info once available\n * @throws TunnelTimeoutError if no tunnel becomes available within timeout\n * @throws ApiError if the API request fails\n */\n async waitForTunnel(options?: WaitForTunnelOptions): Promise<AgentTunnel> {\n // Prevent concurrent calls\n if (this.waitInProgress) {\n throw new Error(\n \"Wait already in progress. Call disconnect() first or wait for the current operation to complete.\"\n );\n }\n\n const timeout = options?.timeout ?? this.config.timeout;\n const pollInterval = options?.pollInterval ?? 1000;\n\n // Validate options\n if (timeout <= 0) {\n throw new Error(\"Timeout must be greater than 0\");\n }\n if (pollInterval <= 0) {\n throw new Error(\"Poll interval must be greater than 0\");\n }\n if (pollInterval > timeout) {\n throw new Error(\"Poll interval cannot exceed timeout\");\n }\n\n this.waitInProgress = true;\n this.abortController = new AbortController();\n const startTime = Date.now();\n\n try {\n while (Date.now() - startTime < timeout) {\n try {\n const response = await this.makeRequest(\n `/api/agent/tunnels/wait?timeout=${Math.min(pollInterval * 5, timeout - (Date.now() - startTime))}`,\n { signal: this.abortController.signal }\n );\n\n if (response.ok) {\n const data = await response.json() as { tunnel?: Record<string, unknown> };\n if (data.tunnel) {\n return this.parseTunnel(data.tunnel);\n }\n } else if (response.status === 408) {\n // Timeout from server, continue polling\n } else {\n const error = await response.json().catch(() => ({ code: \"UNKNOWN\", message: \"Request failed\" })) as { code: string; message: string };\n throw new ApiError(response.status, error.code, error.message);\n }\n } catch (err) {\n if (err instanceof ApiError) throw err;\n if ((err as Error).name === \"AbortError\") {\n throw new Error(\"Wait cancelled\");\n }\n // Network error, wait and retry\n }\n\n // Wait before next poll\n await this.sleep(pollInterval);\n }\n\n throw new TunnelTimeoutError(timeout);\n } finally {\n this.waitInProgress = false;\n }\n }\n\n /**\n * List all active tunnels for this bridge key\n *\n * @returns Array of active tunnels\n * @throws ApiError if the API request fails\n */\n async listTunnels(): Promise<AgentTunnel[]> {\n const response = await this.makeRequest(\"/api/agent/tunnels\");\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({ code: \"UNKNOWN\", message: \"Request failed\" })) as { code: string; message: string };\n throw new ApiError(response.status, error.code, error.message);\n }\n\n const data = await response.json() as { tunnels?: Record<string, unknown>[] };\n return (data.tunnels || []).map((t) => this.parseTunnel(t));\n }\n\n /**\n * Disconnect and clean up\n *\n * Cancels any pending waitForTunnel calls.\n */\n async disconnect(): Promise<void> {\n if (this.abortController) {\n this.abortController.abort();\n this.abortController = null;\n }\n }\n\n /**\n * Make an authenticated API request\n */\n private async makeRequest(\n path: string,\n options: RequestInit = {}\n ): Promise<Response> {\n const url = `${this.config.apiUrl}${path}`;\n\n return fetch(url, {\n ...options,\n headers: {\n \"Authorization\": `Bearer ${this.config.key}`,\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n });\n }\n\n /**\n * Parse tunnel response into AgentTunnel\n */\n private parseTunnel(data: Record<string, unknown>): AgentTunnel {\n const tunnelId = (data.tunnelId || data.id) as string;\n const subdomain = data.subdomain as string;\n const url = data.url as string;\n const localPort = data.localPort as number;\n const createdAt = data.createdAt as string;\n const expiresAt = data.expiresAt as string;\n\n // Validate required fields\n if (!tunnelId || typeof tunnelId !== \"string\") {\n throw new ApiError(500, \"INVALID_RESPONSE\", \"Missing or invalid tunnelId in response\");\n }\n if (!subdomain || typeof subdomain !== \"string\") {\n throw new ApiError(500, \"INVALID_RESPONSE\", \"Missing or invalid subdomain in response\");\n }\n if (!url || typeof url !== \"string\") {\n throw new ApiError(500, \"INVALID_RESPONSE\", \"Missing or invalid url in response\");\n }\n if (typeof localPort !== \"number\" || localPort <= 0 || localPort > 65535) {\n throw new ApiError(500, \"INVALID_RESPONSE\", \"Missing or invalid localPort in response\");\n }\n if (!createdAt || typeof createdAt !== \"string\") {\n throw new ApiError(500, \"INVALID_RESPONSE\", \"Missing or invalid createdAt in response\");\n }\n if (!expiresAt || typeof expiresAt !== \"string\") {\n throw new ApiError(500, \"INVALID_RESPONSE\", \"Missing or invalid expiresAt in response\");\n }\n\n const createdAtDate = new Date(createdAt);\n const expiresAtDate = new Date(expiresAt);\n\n // Validate dates are valid\n if (isNaN(createdAtDate.getTime())) {\n throw new ApiError(500, \"INVALID_RESPONSE\", \"Invalid createdAt date format\");\n }\n if (isNaN(expiresAtDate.getTime())) {\n throw new ApiError(500, \"INVALID_RESPONSE\", \"Invalid expiresAt date format\");\n }\n\n return {\n tunnelId,\n subdomain,\n url,\n localPort,\n createdAt: createdAtDate,\n expiresAt: expiresAtDate,\n };\n }\n\n /**\n * Sleep helper\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n// Re-export types\nexport type { Tunnel } from \"@liveport/shared\";\n"],"mappings":";AAkCO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YAAY,SAAiB;AAC3B,UAAM,+BAA+B,OAAO,YAAY;AACxD,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClB;AAAA,EACA;AAAA,EAEhB,YAAY,YAAoB,MAAc,SAAiB;AAC7D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,OAAO;AAAA,EACd;AACF;AAyBO,IAAM,gBAAN,MAAoB;AAAA,EACjB;AAAA,EACA,kBAA0C;AAAA,EAC1C,iBAAiB;AAAA,EAEzB,YAAY,QAA6B;AACvC,QAAI,CAAC,OAAO,KAAK;AACf,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC1C;AAGA,QAAI,OAAO,YAAY,UAAa,OAAO,WAAW,GAAG;AACvD,YAAM,IAAI,MAAM,gCAAgC;AAAA,IAClD;AAEA,SAAK,SAAS;AAAA,MACZ,KAAK,OAAO;AAAA,MACZ,QAAQ,OAAO,UAAU;AAAA,MACzB,SAAS,OAAO,WAAW;AAAA,IAC7B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,cAAc,SAAsD;AAExE,QAAI,KAAK,gBAAgB;AACvB,YAAM,IAAI;AAAA,QACR;AAAA,MACF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CAAC,aAAa,OAAO,cAAc,UAAU;AAC/C,YAAM,IAAI,SAAS,KAAK,oBAAoB,0CAA0C;AAAA,IACxF;AACA,QAAI,CAAC,OAAO,OAAO,QAAQ,UAAU;AACnC,YAAM,IAAI,SAAS,KAAK,oBAAoB,oCAAoC;AAAA,IAClF;AACA,QAAI,OAAO,cAAc,YAAY,aAAa,KAAK,YAAY,OAAO;AACxE,YAAM,IAAI,SAAS,KAAK,oBAAoB,0CAA0C;AAAA,IACxF;AACA,QAAI,CAAC,aAAa,OAAO,cAAc,UAAU;AAC/C,YAAM,IAAI,SAAS,KAAK,oBAAoB,0CAA0C;AAAA,IACxF;AACA,QAAI,CAAC,aAAa,OAAO,cAAc,UAAU;AAC/C,YAAM,IAAI,SAAS,KAAK,oBAAoB,0CAA0C;AAAA,IACxF;AAEA,UAAM,gBAAgB,IAAI,KAAK,SAAS;AACxC,UAAM,gBAAgB,IAAI,KAAK,SAAS;AAGxC,QAAI,MAAM,cAAc,QAAQ,CAAC,GAAG;AAClC,YAAM,IAAI,SAAS,KAAK,oBAAoB,+BAA+B;AAAA,IAC7E;AACA,QAAI,MAAM,cAAc,QAAQ,CAAC,GAAG;AAClC,YAAM,IAAI,SAAS,KAAK,oBAAoB,+BAA+B;AAAA,IAC7E;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,MAAM,IAA2B;AACvC,WAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAAA,EACzD;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * LivePort Agent SDK\n *\n * TypeScript SDK for AI agents to wait for and access localhost tunnels.\n */\n\nimport WebSocket from \"ws\";\n\n/**\n * Tunnel record as stored in the database.\n *\n * TODO: Remove this duplicate once @liveport/shared is published to npm\n * and agent-sdk can depend on it directly. Until then, keep in sync with\n * the Tunnel type in packages/shared/src/types/index.ts.\n */\nexport interface Tunnel {\n id: string;\n userId: string;\n bridgeKeyId?: string;\n subdomain: string;\n name?: string;\n localPort: number;\n publicUrl: string;\n region: string;\n connectedAt: Date;\n disconnectedAt?: Date;\n requestCount: number;\n bytesTransferred: number;\n}\n\nexport interface LivePortAgentConfig {\n /** Bridge key for authentication */\n key: string;\n /** API base URL (default: https://liveport.dev) */\n apiUrl?: string;\n /** Tunnel server URL for connect() (default: https://tunnel.liveport.online) */\n tunnelUrl?: string;\n /** Default timeout in milliseconds (default: 30000) */\n timeout?: number;\n}\n\nexport interface WaitForTunnelOptions {\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Poll interval in milliseconds (default: 1000) */\n pollInterval?: number;\n}\n\nexport interface ConnectOptions {\n /** Tunnel server URL (overrides tunnelUrl from config) */\n serverUrl?: string;\n /** Connection timeout in milliseconds (default: 30000) */\n timeout?: number;\n}\n\n/** @internal Extended connect options with injectable WebSocket class for testing */\ninterface InternalConnectOptions extends ConnectOptions {\n _WebSocketClass?: typeof WebSocket;\n}\n\nexport interface WaitForReadyOptions {\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Poll interval in milliseconds (default: 1000) */\n pollInterval?: number;\n /** Health check path (default: \"/\") */\n healthPath?: string;\n}\n\nexport interface AgentTunnel {\n tunnelId: string;\n subdomain: string;\n url: string;\n localPort: number;\n createdAt: Date;\n expiresAt: Date;\n}\n\n/** Error thrown when tunnel wait times out */\nexport class TunnelTimeoutError extends Error {\n constructor(timeout: number) {\n super(`Tunnel not available within ${timeout}ms timeout`);\n this.name = \"TunnelTimeoutError\";\n }\n}\n\n/** Error thrown when API request fails */\nexport class ApiError extends Error {\n public readonly statusCode: number;\n public readonly code: string;\n\n constructor(statusCode: number, code: string, message: string) {\n super(message);\n this.name = \"ApiError\";\n this.statusCode = statusCode;\n this.code = code;\n }\n}\n\n/** Error thrown when WebSocket connection fails */\nexport class ConnectionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConnectionError\";\n }\n}\n\n/**\n * LivePort Agent SDK\n *\n * Allows AI agents to wait for, connect to, and access localhost tunnels.\n *\n * @example\n * ```typescript\n * import { LivePortAgent } from '@liveport/agent-sdk';\n *\n * const agent = new LivePortAgent({\n * key: process.env.LIVEPORT_BRIDGE_KEY!\n * });\n *\n * // Create a tunnel to local port 3000\n * const tunnel = await agent.connect(3000);\n * console.log(`Tunnel URL: ${tunnel.url}`);\n *\n * // Wait for the local server to be reachable through the tunnel\n * await agent.waitForReady(tunnel);\n *\n * // Run your tests against tunnel.url\n *\n * // Clean up when done\n * await agent.disconnect();\n * ```\n */\nexport class LivePortAgent {\n private config: Required<LivePortAgentConfig>;\n private abortController: AbortController | null = null;\n private wsConnection: WebSocket | null = null;\n\n constructor(config: LivePortAgentConfig) {\n if (!config.key) {\n throw new Error(\"Bridge key is required\");\n }\n\n this.config = {\n key: config.key,\n apiUrl: config.apiUrl || \"https://liveport.dev\",\n tunnelUrl: config.tunnelUrl || \"https://tunnel.liveport.online\",\n timeout: config.timeout || 30000,\n };\n }\n\n /**\n * Connect to the tunnel server and create a tunnel for the given local port.\n *\n * Opens a WebSocket to the tunnel server, authenticates with the bridge key,\n * and waits for a tunnel assignment. Incoming HTTP requests from the tunnel\n * are forwarded to localhost:<port>.\n *\n * @param port - The local port to tunnel\n * @param options - Connection options\n * @returns The tunnel info once connected\n * @throws ConnectionError if the connection fails or times out\n */\n async connect(port: number, options?: ConnectOptions): Promise<AgentTunnel> {\n if (this.wsConnection) {\n throw new ConnectionError(\"Already connected — call disconnect() first\");\n }\n\n const serverUrl = options?.serverUrl || this.config.tunnelUrl;\n const timeout = options?.timeout ?? this.config.timeout;\n const WS = (options as InternalConnectOptions)?._WebSocketClass ?? WebSocket;\n\n return new Promise<AgentTunnel>((resolve, reject) => {\n const wsUrl = this.buildWebSocketUrl(serverUrl);\n\n const headers: Record<string, string> = {\n \"X-Bridge-Key\": this.config.key,\n \"X-Local-Port\": String(port),\n };\n\n const socket = new WS(wsUrl, {\n headers,\n perMessageDeflate: false,\n });\n\n this.wsConnection = socket;\n\n let settled = false;\n\n const connectTimeout = setTimeout(() => {\n if (!settled) {\n settled = true;\n socket.close();\n reject(new ConnectionError(\"Connection timeout\"));\n }\n }, timeout);\n\n socket.on(\"open\", () => {\n // Waiting for \"connected\" message from server\n });\n\n socket.on(\"message\", (data: Buffer | string) => {\n try {\n const message = JSON.parse(data.toString());\n this.handleWsMessage(message, port, socket);\n\n if (message.type === \"connected\" && !settled) {\n clearTimeout(connectTimeout);\n settled = true;\n const payload = message.payload;\n const tunnel: AgentTunnel = {\n tunnelId: payload.tunnelId,\n subdomain: payload.subdomain,\n url: payload.url,\n localPort: port,\n // Use server-provided createdAt if the server sends it; fall back to client time\n // (ConnectedPayload doesn't include createdAt today, but may in a future server version)\n createdAt: payload.createdAt ? new Date(payload.createdAt as string | number) : new Date(),\n expiresAt: new Date(payload.expiresAt),\n };\n resolve(tunnel);\n } else if (message.type === \"error\" && message.payload?.fatal && !settled) {\n clearTimeout(connectTimeout);\n settled = true;\n reject(new ConnectionError(message.payload.message));\n }\n } catch {\n // Non-JSON messages (e.g. binary frames, malformed data) are\n // silently dropped. The connect timeout will fire if the\n // \"connected\" message never arrives.\n }\n });\n\n socket.on(\"close\", () => {\n clearTimeout(connectTimeout);\n if (!settled) {\n settled = true;\n reject(new ConnectionError(\"Connection closed before tunnel was established\"));\n }\n // Only null wsConnection if it's still this socket (avoid clobbering\n // a new connection created after disconnect() + connect())\n if (this.wsConnection === socket) {\n this.wsConnection = null;\n }\n });\n\n socket.on(\"error\", (err: Error) => {\n clearTimeout(connectTimeout);\n if (!settled) {\n settled = true;\n // Clear wsConnection on error so a new connect() call can proceed\n if (this.wsConnection === socket) {\n this.wsConnection = null;\n }\n reject(new ConnectionError(err.message));\n }\n });\n });\n }\n\n /**\n * Wait for the tunnel's public URL to become reachable.\n *\n * Polls the tunnel's public URL (not localhost) with HTTP GET requests\n * until a 2xx response is received, or the timeout is exceeded. This\n * validates the full tunnel path end-to-end.\n *\n * @param tunnel - The tunnel to check\n * @param options - Wait options\n * @throws TunnelTimeoutError if the tunnel is not ready within timeout\n */\n async waitForReady(tunnel: AgentTunnel, options?: WaitForReadyOptions): Promise<void> {\n const timeout = options?.timeout ?? this.config.timeout;\n const pollInterval = options?.pollInterval ?? 1000;\n const healthPath = options?.healthPath ?? \"/\";\n\n const url = tunnel.url + healthPath;\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n try {\n const response = await fetch(url, {\n method: \"GET\",\n signal: AbortSignal.timeout(Math.max(1, Math.min(5000, timeout - (Date.now() - startTime)))),\n });\n if (response.ok) {\n return;\n }\n } catch {\n // Network error or timeout, continue polling\n }\n\n const remaining = timeout - (Date.now() - startTime);\n if (remaining <= 0) break;\n await this.sleep(Math.min(pollInterval, remaining));\n }\n\n throw new TunnelTimeoutError(timeout);\n }\n\n /**\n * Wait for a tunnel to become available\n *\n * Long-polls the API until a tunnel is ready or timeout is reached.\n *\n * @param options - Wait options\n * @returns The tunnel info once available\n * @throws TunnelTimeoutError if no tunnel becomes available within timeout\n * @throws ApiError if the API request fails\n */\n async waitForTunnel(options?: WaitForTunnelOptions): Promise<AgentTunnel> {\n const timeout = options?.timeout ?? this.config.timeout;\n const pollInterval = options?.pollInterval ?? 1000;\n\n this.abortController = new AbortController();\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n try {\n const response = await this.makeRequest(\n `/api/agent/tunnels/wait?timeout=${Math.min(pollInterval * 5, timeout - (Date.now() - startTime))}`,\n { signal: this.abortController.signal }\n );\n\n if (response.ok) {\n const data = await response.json() as { tunnel?: Record<string, unknown> };\n if (data.tunnel) {\n return this.parseTunnel(data.tunnel);\n }\n } else if (response.status === 408) {\n // Timeout from server, continue polling\n } else {\n const error = await response.json().catch(() => ({ code: \"UNKNOWN\", message: \"Request failed\" })) as { code: string; message: string };\n throw new ApiError(response.status, error.code, error.message);\n }\n } catch (err) {\n if (err instanceof ApiError) throw err;\n if ((err as Error).name === \"AbortError\") {\n throw new Error(\"Wait cancelled\");\n }\n // Network error, wait and retry\n }\n\n // Wait before next poll\n await this.sleep(pollInterval);\n }\n\n throw new TunnelTimeoutError(timeout);\n }\n\n /**\n * List all active tunnels for this bridge key\n *\n * @returns Array of active tunnels\n * @throws ApiError if the API request fails\n */\n async listTunnels(): Promise<AgentTunnel[]> {\n const response = await this.makeRequest(\"/api/agent/tunnels\");\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({ code: \"UNKNOWN\", message: \"Request failed\" })) as { code: string; message: string };\n throw new ApiError(response.status, error.code, error.message);\n }\n\n const data = await response.json() as { tunnels?: Record<string, unknown>[] };\n return (data.tunnels || []).map((t) => this.parseTunnel(t));\n }\n\n /**\n * Disconnect and clean up\n *\n * Cancels any pending waitForTunnel calls and closes any WebSocket\n * connection created by connect().\n */\n async disconnect(): Promise<void> {\n if (this.abortController) {\n this.abortController.abort();\n this.abortController = null;\n }\n\n if (this.wsConnection) {\n const ws = this.wsConnection;\n this.wsConnection = null; // Clear reference first so connect() can be called after\n\n // Use numeric constants (OPEN=1, CONNECTING=0) to avoid coupling to\n // the imported WebSocket class, which may differ from the injected one\n if (ws.readyState === 1 || ws.readyState === 0) {\n ws.close(1000, \"Agent disconnect\");\n }\n }\n }\n\n /**\n * Build WebSocket URL from server URL\n */\n private buildWebSocketUrl(serverUrl: string): string {\n const url = new URL(serverUrl);\n url.protocol = url.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n url.pathname = \"/connect\";\n return url.toString();\n }\n\n /**\n * Handle incoming WebSocket messages from the tunnel server\n */\n private handleWsMessage(\n message: { type: string; id?: string; payload?: Record<string, unknown> },\n localPort: number,\n socket: WebSocket\n ): void {\n switch (message.type) {\n case \"http_request\":\n void this.handleHttpRequest(message, localPort, socket).catch(() => {\n // Errors are handled inside handleHttpRequest (sends 502 response)\n });\n break;\n\n case \"heartbeat\":\n // Respond with heartbeat_ack\n if (socket.readyState === 1 /* OPEN */) {\n socket.send(JSON.stringify({\n type: \"heartbeat_ack\",\n timestamp: Date.now(),\n }));\n }\n break;\n\n // connected and error are handled in the connect() promise\n // Other message types can be extended in the future\n }\n }\n\n /**\n * Forward an HTTP request from the tunnel server to localhost\n */\n private async handleHttpRequest(\n message: { type: string; id?: string; payload?: Record<string, unknown> },\n localPort: number,\n socket: WebSocket\n ): Promise<void> {\n const payload = message.payload as {\n method: string;\n path: string;\n headers: Record<string, string>;\n body?: string;\n };\n\n try {\n // Validate path to prevent injection (e.g. path traversal or host override)\n const safePath = payload.path?.startsWith(\"/\") ? payload.path : `/${payload.path || \"\"}`;\n const url = `http://localhost:${localPort}${safePath}`;\n\n // Strip hop-by-hop headers that could cause request smuggling or\n // confuse the local server when forwarded from the tunnel\n const HOP_BY_HOP = new Set([\n \"host\", \"connection\", \"transfer-encoding\", \"te\", \"trailer\",\n \"upgrade\", \"keep-alive\", \"proxy-authenticate\", \"proxy-authorization\",\n ]);\n const safeHeaders = Object.fromEntries(\n Object.entries(payload.headers || {}).filter(([k]) => !HOP_BY_HOP.has(k.toLowerCase()))\n );\n\n const requestInit: RequestInit = {\n method: payload.method,\n headers: safeHeaders,\n };\n\n if (payload.body) {\n requestInit.body = Buffer.from(payload.body, \"base64\");\n }\n\n const response = await fetch(url, requestInit);\n const responseBody = await response.arrayBuffer();\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n const responseMessage = {\n type: \"http_response\",\n id: message.id,\n timestamp: Date.now(),\n payload: {\n status: response.status,\n headers: responseHeaders,\n body: responseBody.byteLength > 0\n ? Buffer.from(responseBody).toString(\"base64\")\n : undefined,\n },\n };\n\n if (socket.readyState === 1 /* OPEN */) {\n socket.send(JSON.stringify(responseMessage));\n }\n } catch (err) {\n const errorResponse = {\n type: \"http_response\",\n id: message.id,\n timestamp: Date.now(),\n payload: {\n status: 502,\n headers: { \"Content-Type\": \"text/plain\" },\n body: Buffer.from(\n `Error connecting to local server: ${(err as Error).message}`\n ).toString(\"base64\"),\n },\n };\n\n if (socket.readyState === 1 /* OPEN */) {\n socket.send(JSON.stringify(errorResponse));\n }\n }\n }\n\n /**\n * Make an authenticated API request\n */\n private async makeRequest(\n path: string,\n options: RequestInit = {}\n ): Promise<Response> {\n const url = `${this.config.apiUrl}${path}`;\n\n return fetch(url, {\n ...options,\n headers: {\n \"Authorization\": `Bearer ${this.config.key}`,\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n });\n }\n\n /**\n * Parse tunnel response into AgentTunnel\n */\n private parseTunnel(data: Record<string, unknown>): AgentTunnel {\n // Accept both tunnelId (new API shape) and id (legacy shape) for backward compatibility\n const tunnelId = (data.tunnelId ?? data.id) as string;\n const subdomain = data.subdomain as string;\n const url = data.url as string;\n const localPort = data.localPort as number;\n\n if (!tunnelId || !subdomain || !url || localPort == null || typeof localPort !== \"number\") {\n throw new Error(\n `parseTunnel: missing required fields in API response (tunnelId=${tunnelId}, subdomain=${subdomain}, url=${url}, localPort=${localPort})`\n );\n }\n\n if (!data.expiresAt) {\n throw new Error(\"parseTunnel: missing expiresAt in API response\");\n }\n\n return {\n tunnelId,\n subdomain,\n url,\n localPort,\n createdAt: data.createdAt ? new Date(data.createdAt as string | number) : new Date(),\n expiresAt: new Date(data.expiresAt as string | number),\n };\n }\n\n /**\n * Sleep helper\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n"],"mappings":";AAMA,OAAO,eAAe;AAyEf,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YAAY,SAAiB;AAC3B,UAAM,+BAA+B,OAAO,YAAY;AACxD,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClB;AAAA,EACA;AAAA,EAEhB,YAAY,YAAoB,MAAc,SAAiB;AAC7D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,S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AAG,KAAK,OAAO,MAAM,GAAG,IAAI;AAExC,WAAO,MAAM,KAAK;AAAA,MAChB,GAAG;AAAA,MACH,SAAS;AAAA,QACP,iBAAiB,UAAU,KAAK,OAAO,GAAG;AAAA,QAC1C,gBAAgB;AAAA,QAChB,GAAG,QAAQ;AAAA,MACb;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKQ,YAAY,MAA4C;AAE9D,UAAM,WAAY,KAAK,YAAY,KAAK;AACxC,UAAM,YAAY,KAAK;AACvB,UAAM,MAAM,KAAK;AACjB,UAAM,YAAY,KAAK;AAEvB,QAAI,CAAC,YAAY,CAAC,aAAa,CAAC,OAAO,aAAa,QAAQ,OAAO,cAAc,UAAU;AACzF,YAAM,IAAI;AAAA,QACR,kEAAkE,QAAQ,eAAe,SAAS,SAAS,GAAG,eAAe,SAAS;AAAA,MACxI;AAAA,IACF;AAEA,QAAI,CAAC,KAAK,WAAW;AACnB,YAAM,IAAI,MAAM,gDAAgD;AAAA,IAClE;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW,KAAK,YAAY,IAAI,KAAK,KAAK,SAA4B,IAAI,oBAAI,KAAK;AAAA,MACnF,WAAW,IAAI,KAAK,KAAK,SAA4B;AAAA,IACvD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,MAAM,IAA2B;AACvC,WAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAAA,EACzD;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liveport/agent-sdk",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "TypeScript SDK for AI agents to access LivePort tunnels",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -14,13 +14,12 @@
14
14
  },
15
15
  "files": [
16
16
  "dist",
17
- "examples",
18
17
  "README.md"
19
18
  ],
20
19
  "scripts": {
21
20
  "build": "tsup",
22
21
  "dev": "tsup --watch",
23
- "lint": "eslint src/",
22
+ "lint": "echo 'Skipping lint - ESLint not configured' && exit 0",
24
23
  "test": "vitest run --passWithNoTests",
25
24
  "test:watch": "vitest",
26
25
  "clean": "rm -rf dist",
@@ -45,7 +44,7 @@
45
44
  },
46
45
  "repository": {
47
46
  "type": "git",
48
- "url": "git+https://github.com/dundas/liveport-private.git",
47
+ "url": "git+https://github.com/dundas/liveport.git",
49
48
  "directory": "packages/agent-sdk"
50
49
  },
51
50
  "publishConfig": {
@@ -56,11 +55,12 @@
56
55
  },
57
56
  "devDependencies": {
58
57
  "@types/node": "^20.10.0",
58
+ "@types/ws": "^8.5.0",
59
59
  "tsup": "^8.0.0",
60
60
  "typescript": "^5.3.0",
61
61
  "vitest": "^2.0.0"
62
62
  },
63
63
  "dependencies": {
64
- "@liveport/shared": "workspace:*"
64
+ "ws": "^8.18.0"
65
65
  }
66
66
  }
@@ -1,40 +0,0 @@
1
- /**
2
- * Basic Usage Example
3
- *
4
- * This example shows the simplest way to use the LivePort Agent SDK
5
- * to wait for a tunnel and access a local development server.
6
- */
7
-
8
- import { LivePortAgent } from "@liveport/agent-sdk";
9
-
10
- async function main() {
11
- // Create agent instance with your bridge key
12
- const agent = new LivePortAgent({
13
- key: process.env.LIVEPORT_KEY || "lpk_your_bridge_key_here",
14
- });
15
-
16
- console.log("Waiting for tunnel to become available...");
17
-
18
- try {
19
- // Wait for tunnel (default 30 second timeout)
20
- const tunnel = await agent.waitForTunnel();
21
-
22
- console.log("✓ Tunnel established!");
23
- console.log(` URL: ${tunnel.url}`);
24
- console.log(` Local Port: ${tunnel.localPort}`);
25
- console.log(` Subdomain: ${tunnel.subdomain}`);
26
-
27
- // Now you can make requests to the tunnel URL
28
- const response = await fetch(`${tunnel.url}/api/health`);
29
- const data = await response.json();
30
-
31
- console.log("Health check response:", data);
32
- } catch (error) {
33
- console.error("Failed to get tunnel:", error);
34
- } finally {
35
- // Clean up
36
- await agent.disconnect();
37
- }
38
- }
39
-
40
- main();
@@ -1,75 +0,0 @@
1
- /**
2
- * Testing Integration Example
3
- *
4
- * This example shows how to integrate LivePort Agent SDK
5
- * into your automated test suite (Vitest, Jest, etc.)
6
- */
7
-
8
- import { LivePortAgent, TunnelTimeoutError } from "@liveport/agent-sdk";
9
- import { describe, it, expect, beforeAll, afterAll } from "vitest";
10
-
11
- describe("API Integration Tests", () => {
12
- let agent: LivePortAgent;
13
- let tunnelUrl: string;
14
-
15
- beforeAll(async () => {
16
- // Initialize agent
17
- agent = new LivePortAgent({
18
- key: process.env.LIVEPORT_KEY!,
19
- timeout: 60000, // 60 second timeout
20
- });
21
-
22
- try {
23
- // Wait for developer to start their local server
24
- console.log("⏳ Waiting for tunnel...");
25
- const tunnel = await agent.waitForTunnel({ timeout: 60000 });
26
- tunnelUrl = tunnel.url;
27
- console.log(`✓ Connected to ${tunnelUrl}`);
28
- } catch (error) {
29
- if (error instanceof TunnelTimeoutError) {
30
- throw new Error(
31
- "Tunnel not available. Make sure the developer has started " +
32
- "'liveport connect <port>' before running tests."
33
- );
34
- }
35
- throw error;
36
- }
37
- });
38
-
39
- afterAll(async () => {
40
- await agent?.disconnect();
41
- });
42
-
43
- it("should return healthy status", async () => {
44
- const response = await fetch(`${tunnelUrl}/api/health`);
45
- expect(response.ok).toBe(true);
46
-
47
- const data = await response.json();
48
- expect(data.status).toBe("healthy");
49
- });
50
-
51
- it("should list users", async () => {
52
- const response = await fetch(`${tunnelUrl}/api/users`);
53
- expect(response.ok).toBe(true);
54
-
55
- const users = await response.json();
56
- expect(Array.isArray(users)).toBe(true);
57
- });
58
-
59
- it("should create a new user", async () => {
60
- const response = await fetch(`${tunnelUrl}/api/users`, {
61
- method: "POST",
62
- headers: { "Content-Type": "application/json" },
63
- body: JSON.stringify({
64
- name: "Test User",
65
- email: "test@example.com",
66
- }),
67
- });
68
-
69
- expect(response.status).toBe(201);
70
-
71
- const user = await response.json();
72
- expect(user.name).toBe("Test User");
73
- expect(user.email).toBe("test@example.com");
74
- });
75
- });