portpreview 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +186 -1
- package/NOTICE +4 -0
- package/README.md +97 -1
- package/lib/cli-main.mjs +11 -4
- package/lib/config.mjs +59 -6
- package/lib/index.mjs +2 -0
- package/lib/inspector-server.mjs +445 -0
- package/lib/inspector-store.mjs +292 -0
- package/lib/inspector-ui.mjs +625 -0
- package/lib/tcp-client.mjs +70 -0
- package/lib/tunnel-client.mjs +83 -21
- package/package.json +6 -1
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import net from 'node:net'
|
|
2
|
+
import { createHttpStream } from './http-stream.mjs'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Handles `tcp_open` from the gateway: connects to the local port and pipes the public TCP
|
|
6
|
+
* connection through the flow-controlled stream channel (`http_data` / `http_end` frames).
|
|
7
|
+
*
|
|
8
|
+
* @param {import('ws').WebSocket} ws
|
|
9
|
+
* @param {Record<string, unknown>} message
|
|
10
|
+
* @param {{
|
|
11
|
+
* host: string,
|
|
12
|
+
* port: number,
|
|
13
|
+
* streams: Map<string, { channel: ReturnType<typeof createHttpStream>, upstream: import('node:net').Socket }>,
|
|
14
|
+
* onTcpConnection?: (info: { remoteAddress: string | null, durationMs: number, bytesIn: number, bytesOut: number, error?: string }) => void,
|
|
15
|
+
* }} ctx
|
|
16
|
+
*/
|
|
17
|
+
export function openLocalTcpStream(ws, message, ctx) {
|
|
18
|
+
const id = String(message.id ?? '')
|
|
19
|
+
if (!id || ctx.streams.has(id)) return
|
|
20
|
+
const startedAt = performance.now()
|
|
21
|
+
const remoteAddress = typeof message.remoteAddress === 'string' ? message.remoteAddress : null
|
|
22
|
+
const local = net.connect({ host: ctx.host, port: ctx.port, allowHalfOpen: true })
|
|
23
|
+
let sentEnd = false, receivedEnd = false, finished = false, bytesIn = 0, bytesOut = 0
|
|
24
|
+
const finish = (error) => {
|
|
25
|
+
if (finished) return
|
|
26
|
+
finished = true
|
|
27
|
+
ctx.streams.delete(id)
|
|
28
|
+
channel.stop()
|
|
29
|
+
local.destroy()
|
|
30
|
+
ctx.onTcpConnection?.({
|
|
31
|
+
remoteAddress, durationMs: Math.round(performance.now() - startedAt), bytesIn, bytesOut,
|
|
32
|
+
...(error ? { error: localTcpError(error) } : {}),
|
|
33
|
+
})
|
|
34
|
+
}
|
|
35
|
+
// The gateway owns the idle timeout; the client only mirrors what it is told.
|
|
36
|
+
const channel = createHttpStream({
|
|
37
|
+
ws, id, outgoing: 'response', idleTimeoutMs: 0,
|
|
38
|
+
onReceive: (chunk) => { bytesIn += chunk.length },
|
|
39
|
+
onSend: (chunk) => { bytesOut += chunk.length },
|
|
40
|
+
onError: finish,
|
|
41
|
+
onSentEnd: () => { sentEnd = true; if (receivedEnd) finish() },
|
|
42
|
+
onEnd: () => { receivedEnd = true; if (sentEnd) finish() },
|
|
43
|
+
})
|
|
44
|
+
ctx.streams.set(id, { channel, upstream: local })
|
|
45
|
+
// The destination is set before the socket connects (writes and end() queue until then), so a visitor
|
|
46
|
+
// that half-closes at once is half-closed locally instead of being aborted.
|
|
47
|
+
try { channel.setDestination(local) } catch (error) { channel.cancel(error); return }
|
|
48
|
+
local.once('connect', () => {
|
|
49
|
+
local.setNoDelay(true)
|
|
50
|
+
try { channel.setSource(local) } catch (error) { channel.cancel(error) }
|
|
51
|
+
})
|
|
52
|
+
local.on('error', (error) => channel.cancel(error))
|
|
53
|
+
local.once('close', () => { if (!finished) channel.cancel(new Error('Local connection closed')) })
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function localTcpError(error) {
|
|
57
|
+
const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : ''
|
|
58
|
+
if (code === 'ECONNREFUSED') return 'nothing is listening on the local port'
|
|
59
|
+
if (error instanceof Error && /idle timeout/i.test(error.message)) return 'idle timeout'
|
|
60
|
+
return code || (error instanceof Error ? error.message : String(error))
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** `1.2 KB`, `3.4 MB` for the terminal log. */
|
|
64
|
+
export function formatBytes(bytes) {
|
|
65
|
+
if (bytes < 1024) return `${bytes} B`
|
|
66
|
+
const units = ['KB', 'MB', 'GB', 'TB']
|
|
67
|
+
let value = bytes / 1024, unit = 0
|
|
68
|
+
while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1 }
|
|
69
|
+
return `${value >= 100 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`
|
|
70
|
+
}
|
package/lib/tunnel-client.mjs
CHANGED
|
@@ -14,11 +14,13 @@ import {
|
|
|
14
14
|
send,
|
|
15
15
|
} from './protocol.mjs'
|
|
16
16
|
import { createHttpStream } from './http-stream.mjs'
|
|
17
|
+
import { formatBytes, openLocalTcpStream } from './tcp-client.mjs'
|
|
18
|
+
import { beginExchange, declaredBodyBytes } from './inspector-store.mjs'
|
|
17
19
|
|
|
18
20
|
function abortError() { const error = new Error('Tunnel connection cancelled'); error.name = 'AbortError'; return error }
|
|
19
21
|
|
|
20
22
|
/** @param {{ host: string, port: number, signal?: AbortSignal }} options */
|
|
21
|
-
export function waitForLocalPort({ host, port, signal }) {
|
|
23
|
+
export function waitForLocalPort({ host, port, signal, scheme = 'http://' }) {
|
|
22
24
|
return new Promise((resolve, reject) => {
|
|
23
25
|
if (signal?.aborted) { reject(abortError()); return }
|
|
24
26
|
const socket = net.connect({ host, port })
|
|
@@ -26,8 +28,8 @@ export function waitForLocalPort({ host, port, signal }) {
|
|
|
26
28
|
const aborted = () => { cleanup(); socket.destroy(); reject(abortError()) }
|
|
27
29
|
signal?.addEventListener('abort', aborted, { once: true })
|
|
28
30
|
socket.once('connect', () => { cleanup(); socket.end(); resolve() })
|
|
29
|
-
socket.once('error', err => { cleanup(); reject(new Error(`Nothing is listening on
|
|
30
|
-
socket.setTimeout(3000, () => { cleanup(); socket.destroy(); reject(new Error(`Timed out waiting for
|
|
31
|
+
socket.once('error', err => { cleanup(); reject(new Error(`Nothing is listening on ${scheme}${host}:${port} (${err.message})`)) })
|
|
32
|
+
socket.setTimeout(3000, () => { cleanup(); socket.destroy(); reject(new Error(`Timed out waiting for ${scheme}${host}:${port}`)) })
|
|
31
33
|
})
|
|
32
34
|
}
|
|
33
35
|
|
|
@@ -117,7 +119,7 @@ export async function openTunnel(options) {
|
|
|
117
119
|
}
|
|
118
120
|
catch (error) { options.signal?.removeEventListener('abort', externalAbort); controller.abort(); throw error }
|
|
119
121
|
const terminal = (detail) => [4000, 4001, 4003, 1002, 1008].includes(detail.code)
|
|
120
|
-
const terminalError = error => [4000, 4001, 4003, 1002, 1008].includes(Number(error.closeCode ?? error.gatewayCode)) || /AUTH|ACCESS_REVOKED|SESSION_EXPIRED|MALFORMED_REGISTER|INVALID_REGISTER|UNSUPPORTED_PROTOCOL/.test(String(error.gatewayCode ?? '')) || /Gateway did not assign|Invalid message|authorization failed|access revoked|Invalid subdomain|Unsupported protocol version|Expected register|Reserved subdomains require|Authenticated tunnels are not configured/i.test(error.message)
|
|
122
|
+
const terminalError = error => [4000, 4001, 4003, 1002, 1008].includes(Number(error.closeCode ?? error.gatewayCode)) || /AUTH|ACCESS_REVOKED|SESSION_EXPIRED|MALFORMED_REGISTER|INVALID_REGISTER|UNSUPPORTED_PROTOCOL/.test(String(error.gatewayCode ?? '')) || /Gateway did not assign|Invalid message|authorization failed|access revoked|Invalid subdomain|Unsupported protocol version|Expected register|Reserved subdomains require|Authenticated tunnels are not configured|TCP tunnels|paid plan/i.test(error.message)
|
|
121
123
|
const watch = connection => {
|
|
122
124
|
void connection.closed.then(detail => {
|
|
123
125
|
if (stopped) return
|
|
@@ -168,18 +170,20 @@ export async function openTunnel(options) {
|
|
|
168
170
|
get url() { return current.url }, get subdomain() { return current.subdomain },
|
|
169
171
|
get expiresAt() { return current.expiresAt }, get protocolVersion() { return current.protocolVersion },
|
|
170
172
|
get streaming() { return current.streaming },
|
|
173
|
+
get kind() { return current.kind }, get tcpHost() { return current.tcpHost }, get tcpPort() { return current.tcpPort },
|
|
171
174
|
closed, close: stop,
|
|
172
175
|
}
|
|
173
176
|
}
|
|
174
177
|
|
|
175
178
|
async function openTunnelConnection(options) {
|
|
176
179
|
const { host, port, subdomain, apiToken, gatewayUrl, tunnelDomain, quiet, onRequest } = options
|
|
180
|
+
const kind = options.kind === 'tcp' ? 'tcp' : 'http'
|
|
177
181
|
/** @type {Map<string, { socket: import('ws').WebSocket, queue: Array<{ data: Buffer, isBinary: boolean }> }>} */
|
|
178
182
|
const localSockets = new Map()
|
|
179
183
|
|
|
180
184
|
const streams = new Map()
|
|
181
185
|
const protocolVersion = options.protocolVersion ?? PROTOCOL_VERSION
|
|
182
|
-
await waitForLocalPort({ host, port, signal: options.signal })
|
|
186
|
+
await waitForLocalPort({ host, port, signal: options.signal, scheme: kind === 'tcp' ? '' : 'http://' })
|
|
183
187
|
|
|
184
188
|
const ws = new WebSocket(gatewayUrl, { maxPayload: MAX_FRAME_BYTES, handshakeTimeout: 10_000 })
|
|
185
189
|
ws.on('error', () => {})
|
|
@@ -208,6 +212,7 @@ async function openTunnelConnection(options) {
|
|
|
208
212
|
host,
|
|
209
213
|
subdomain,
|
|
210
214
|
apiToken,
|
|
215
|
+
...(kind === 'tcp' ? { kind } : {}),
|
|
211
216
|
})
|
|
212
217
|
|
|
213
218
|
let registered
|
|
@@ -215,7 +220,7 @@ async function openTunnelConnection(options) {
|
|
|
215
220
|
catch (error) {
|
|
216
221
|
ws.terminate()
|
|
217
222
|
if (options.signal?.aborted) throw abortError()
|
|
218
|
-
if (protocolVersion === PROTOCOL_VERSION && /Unsupported protocol version/.test(error.message)) {
|
|
223
|
+
if (kind !== 'tcp' && protocolVersion === PROTOCOL_VERSION && /Unsupported protocol version/.test(error.message)) {
|
|
219
224
|
if (!quiet) console.error('Gateway supports legacy v2 only: HTTP bodies remain limited to 1 MiB. Upgrade the gateway for streaming.')
|
|
220
225
|
return openTunnelConnection({ ...options, protocolVersion: LEGACY_PROTOCOL_VERSION })
|
|
221
226
|
}
|
|
@@ -223,16 +228,26 @@ async function openTunnelConnection(options) {
|
|
|
223
228
|
}
|
|
224
229
|
const assignedSubdomain = String(registered.subdomain ?? '')
|
|
225
230
|
if (!assignedSubdomain) { ws.terminate(); throw new Error('Gateway did not assign a subdomain') }
|
|
231
|
+
// A gateway without TCP support ignores `kind` and would hand back an HTTP tunnel.
|
|
232
|
+
if (kind === 'tcp' && (registered.kind !== 'tcp' || !registered.tcpHost || !Number.isInteger(registered.tcpPort))) {
|
|
233
|
+
ws.terminate()
|
|
234
|
+
throw new Error('This gateway does not support TCP tunnels')
|
|
235
|
+
}
|
|
226
236
|
options.signal?.removeEventListener('abort', aborted)
|
|
227
237
|
if (options.signal?.aborted) { ws.terminate(); throw abortError() }
|
|
228
238
|
|
|
229
|
-
const url =
|
|
230
|
-
|
|
239
|
+
const url = kind === 'tcp'
|
|
240
|
+
? `tcp://${registered.tcpHost}:${registered.tcpPort}`
|
|
241
|
+
: tunnelDomain.includes(':') || tunnelDomain === 'localhost'
|
|
231
242
|
? localGatewayHttpUrl(assignedSubdomain, tunnelDomain)
|
|
232
243
|
: publicUrl(assignedSubdomain, tunnelDomain)
|
|
244
|
+
const onTcpConnection = (info) => {
|
|
245
|
+
options.onTcpConnection?.(info)
|
|
246
|
+
if (!quiet) console.log(`TCP ${info.remoteAddress ?? 'unknown'} ${(info.durationMs / 1000).toFixed(1)}s in ${formatBytes(info.bytesIn)} out ${formatBytes(info.bytesOut)}${info.error ? ` (${info.error})` : ''}`)
|
|
247
|
+
}
|
|
233
248
|
|
|
234
249
|
ws.on('message', (data) => {
|
|
235
|
-
void handleGatewayMessage(ws, data, { host, port, quiet, onRequest, localSockets, streams, streamIdleTimeoutMs: options.streamIdleTimeoutMs })
|
|
250
|
+
void handleGatewayMessage(ws, data, { host, port, quiet, onRequest, localSockets, streams, streamIdleTimeoutMs: options.streamIdleTimeoutMs, inspector: options.inspector, publicUrl: url, kind, onTcpConnection })
|
|
236
251
|
})
|
|
237
252
|
|
|
238
253
|
let alive = true
|
|
@@ -264,6 +279,9 @@ async function openTunnelConnection(options) {
|
|
|
264
279
|
expiresAt: registered.expiresAt ?? null,
|
|
265
280
|
protocolVersion: registered.version ?? LEGACY_PROTOCOL_VERSION,
|
|
266
281
|
streaming: Boolean(registered.streaming),
|
|
282
|
+
kind,
|
|
283
|
+
tcpHost: kind === 'tcp' ? String(registered.tcpHost) : null,
|
|
284
|
+
tcpPort: kind === 'tcp' ? registered.tcpPort : null,
|
|
267
285
|
close: async () => {
|
|
268
286
|
await new Promise((resolve) => {
|
|
269
287
|
if (ws.readyState === ws.CLOSED) {
|
|
@@ -301,6 +319,14 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
301
319
|
|
|
302
320
|
const id = String(message.id ?? '')
|
|
303
321
|
|
|
322
|
+
// A TCP tunnel only carries raw connections; an HTTP tunnel never accepts them.
|
|
323
|
+
if (ctx.kind === 'tcp') {
|
|
324
|
+
if (message.type === 'tcp_open') openLocalTcpStream(ws, message, ctx)
|
|
325
|
+
else if (String(message.type).startsWith('http_') && message.type !== 'http_request') ctx.streams.get(id)?.channel.handle(message)
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
if (message.type === 'tcp_open') return
|
|
329
|
+
|
|
304
330
|
if (message.type === 'http_request') {
|
|
305
331
|
try { openLocalHttpStream(ws, message, ctx) }
|
|
306
332
|
catch (error) { sendIfOpen(ws, { type: 'http_cancel', id, reason: error.message }) }
|
|
@@ -323,6 +349,7 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
323
349
|
data: attachedBody(message),
|
|
324
350
|
isBinary: Boolean(message.isBinary),
|
|
325
351
|
}
|
|
352
|
+
connection.inspect?.frame('in', frame.data.length)
|
|
326
353
|
if (connection.socket.readyState === connection.socket.OPEN) {
|
|
327
354
|
connection.socket.send(frame.data, { binary: frame.isBinary })
|
|
328
355
|
} else if (connection.socket.readyState === connection.socket.CONNECTING) {
|
|
@@ -341,6 +368,7 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
341
368
|
const connection = ctx.localSockets.get(id)
|
|
342
369
|
if (!connection) return
|
|
343
370
|
ctx.localSockets.delete(id)
|
|
371
|
+
connection.inspect?.finish({ closeCode: message.code, closeReason: message.reason })
|
|
344
372
|
const close = () => {
|
|
345
373
|
closeWebSocket(connection.socket, message.code, message.reason)
|
|
346
374
|
}
|
|
@@ -361,9 +389,10 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
361
389
|
const requestBody = body.length ? body : undefined
|
|
362
390
|
|
|
363
391
|
ctx.onRequest?.({ method, path })
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
392
|
+
const startedAt = performance.now()
|
|
393
|
+
const inspect = beginExchange(ctx.inspector, { kind: 'http', method, path, headers: stripHopByHop(headers), publicUrl: ctx.publicUrl, protocolVersion: 2 })
|
|
394
|
+
inspect.requestChunk(body)
|
|
395
|
+
inspect.requestEnd()
|
|
367
396
|
|
|
368
397
|
try {
|
|
369
398
|
const response = await forwardToLocal({
|
|
@@ -374,9 +403,10 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
374
403
|
headers,
|
|
375
404
|
body: requestBody,
|
|
376
405
|
})
|
|
377
|
-
if (!ctx.quiet
|
|
378
|
-
|
|
379
|
-
|
|
406
|
+
if (!ctx.quiet) logRequest(method, path, response.status, startedAt, response.truncated ? 'truncated to 1MB' : '')
|
|
407
|
+
inspect.response(response.status, response.headers)
|
|
408
|
+
inspect.responseChunk(response.body)
|
|
409
|
+
inspect.finish({ responseTruncated: response.truncated })
|
|
380
410
|
send(
|
|
381
411
|
ws,
|
|
382
412
|
{
|
|
@@ -389,6 +419,10 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
389
419
|
response.body,
|
|
390
420
|
)
|
|
391
421
|
} catch (err) {
|
|
422
|
+
if (!ctx.quiet) logRequest(method, path, 502, startedAt, localErrorReason(err))
|
|
423
|
+
inspect.response(502, { 'content-type': 'text/plain' })
|
|
424
|
+
inspect.responseChunk(Buffer.from(String(err instanceof Error ? err.message : err)))
|
|
425
|
+
inspect.finish({ error: err, synthetic: true })
|
|
392
426
|
send(
|
|
393
427
|
ws,
|
|
394
428
|
{
|
|
@@ -420,14 +454,23 @@ function openLocalHttpStream(ws, message, ctx) {
|
|
|
420
454
|
sendIfOpen(ws, { type: 'http_cancel', id, reason: 'Invalid local HTTP path' }); return
|
|
421
455
|
}
|
|
422
456
|
ctx.onRequest?.({ method, path })
|
|
423
|
-
|
|
424
|
-
|
|
457
|
+
const startedAt = performance.now()
|
|
458
|
+
let logged = false
|
|
459
|
+
const log = (status, note = '') => { if (!ctx.quiet && !logged) { logged = true; logRequest(method, path, status, startedAt, note) } }
|
|
460
|
+
const headers = stripHopByHop(message.headers ?? {})
|
|
461
|
+
const upstream = http.request({ host: ctx.host, port: ctx.port, method, path, headers })
|
|
462
|
+
const inspect = beginExchange(ctx.inspector, { kind: 'http', method, path, headers, publicUrl: ctx.publicUrl, protocolVersion: 3, declaredRequestBytes: declaredBodyBytes(message.headers ?? {}) })
|
|
425
463
|
let localSocket
|
|
426
464
|
upstream.once('socket', socket => { localSocket = socket })
|
|
427
465
|
const channel = createHttpStream({
|
|
428
466
|
ws, id, outgoing: 'response', idleTimeoutMs: ctx.streamIdleTimeoutMs ?? 120_000,
|
|
429
|
-
|
|
467
|
+
onReceive: chunk => inspect.requestChunk(chunk),
|
|
468
|
+
onSend: chunk => inspect.responseChunk(chunk),
|
|
469
|
+
onEnd: () => inspect.requestEnd(),
|
|
470
|
+
onError: (error) => { inspect.finish({ error }); upstream.destroy(); ctx.streams.delete(id) },
|
|
430
471
|
onSentEnd: () => {
|
|
472
|
+
if (upstream.writableEnded) inspect.requestEnd()
|
|
473
|
+
inspect.finish()
|
|
431
474
|
channel.stop(); ctx.streams.delete(id)
|
|
432
475
|
if (!upstream.writableFinished) { upstream.destroy(); localSocket?.destroy() }
|
|
433
476
|
},
|
|
@@ -435,13 +478,15 @@ function openLocalHttpStream(ws, message, ctx) {
|
|
|
435
478
|
ctx.streams.set(id, { channel, upstream })
|
|
436
479
|
upstream.once('response', (response) => {
|
|
437
480
|
try {
|
|
481
|
+
log(response.statusCode ?? 502)
|
|
482
|
+
inspect.response(response.statusCode ?? 502, response.headers, response.rawHeaders)
|
|
438
483
|
send(ws, { type: 'http_response', id, status: response.statusCode ?? 502, headers: stripHopByHop(response.headers) })
|
|
439
484
|
channel.setSource(response)
|
|
440
485
|
response.once('aborted', () => channel.cancel(new Error('Local response aborted')))
|
|
441
486
|
} catch (error) { channel.cancel(error) }
|
|
442
487
|
})
|
|
443
|
-
upstream.on('error', error => channel.cancel(error))
|
|
444
|
-
channel.setDestination(upstream)
|
|
488
|
+
upstream.on('error', error => { log(502, localErrorReason(error)); channel.cancel(error) })
|
|
489
|
+
try { channel.setDestination(upstream) } catch (error) { inspect.finish({ error }); throw error }
|
|
445
490
|
}
|
|
446
491
|
|
|
447
492
|
function openLocalWebSocket(gateway, message, ctx) {
|
|
@@ -461,8 +506,10 @@ function openLocalWebSocket(gateway, message, ctx) {
|
|
|
461
506
|
}
|
|
462
507
|
const url = new URL(`ws://${net.isIPv6(ctx.host) ? `[${ctx.host}]` : ctx.host}:${ctx.port}${path}`)
|
|
463
508
|
const local = protocol ? new WebSocket(url, protocol, options) : new WebSocket(url, options)
|
|
464
|
-
const
|
|
509
|
+
const inspect = beginExchange(ctx.inspector, { kind: 'websocket', method: 'GET', path, headers: protocol ? { ...options.headers, 'sec-websocket-protocol': protocol } : options.headers, publicUrl: ctx.publicUrl })
|
|
510
|
+
const connection = { socket: local, queue: [], inspect }
|
|
465
511
|
ctx.localSockets.set(id, connection)
|
|
512
|
+
local.once('upgrade', response => inspect.response(101, response.headers, response.rawHeaders))
|
|
466
513
|
|
|
467
514
|
local.on('open', () => {
|
|
468
515
|
for (const frame of connection.queue) {
|
|
@@ -472,10 +519,12 @@ function openLocalWebSocket(gateway, message, ctx) {
|
|
|
472
519
|
})
|
|
473
520
|
|
|
474
521
|
local.on('message', (data, isBinary) => {
|
|
522
|
+
inspect.frame('out', data.length ?? data.byteLength ?? 0)
|
|
475
523
|
sendIfOpen(gateway, { type: 'ws_data', id, isBinary }, Buffer.from(data))
|
|
476
524
|
})
|
|
477
525
|
|
|
478
526
|
local.on('close', (code, reason) => {
|
|
527
|
+
inspect.finish({ closeCode: code, closeReason: reason.toString() })
|
|
479
528
|
if (ctx.localSockets.get(id)?.socket !== local) return
|
|
480
529
|
ctx.localSockets.delete(id)
|
|
481
530
|
sendIfOpen(gateway, {
|
|
@@ -487,6 +536,7 @@ function openLocalWebSocket(gateway, message, ctx) {
|
|
|
487
536
|
})
|
|
488
537
|
|
|
489
538
|
local.on('error', (err) => {
|
|
539
|
+
inspect.finish({ error: err })
|
|
490
540
|
sendIfOpen(gateway, {
|
|
491
541
|
type: 'ws_error',
|
|
492
542
|
id,
|
|
@@ -575,6 +625,18 @@ function stripHopByHop(headers) {
|
|
|
575
625
|
* @param {Record<string, unknown>} message
|
|
576
626
|
* @param {unknown} [body]
|
|
577
627
|
*/
|
|
628
|
+
/** One terminal line per request, printed once the local response status is known: `POST /hook 200 32ms`. */
|
|
629
|
+
function logRequest(method, path, status, startedAt, note) {
|
|
630
|
+
const ms = Math.max(0, Math.round(performance.now() - startedAt))
|
|
631
|
+
console.log(`${method} ${path} ${status} ${ms}ms${note ? ` (${note})` : ''}`)
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function localErrorReason(error) {
|
|
635
|
+
const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : ''
|
|
636
|
+
if (code === 'ECONNREFUSED') return 'nothing is listening on the local port'
|
|
637
|
+
return code || (error instanceof Error ? error.message : String(error))
|
|
638
|
+
}
|
|
639
|
+
|
|
578
640
|
function sendIfOpen(ws, message, body) {
|
|
579
641
|
if (ws.readyState === ws.OPEN) send(ws, message, body)
|
|
580
642
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "portpreview",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Instant secure previews for localhost apps — expose a local port through a public HTTPS URL.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.mjs",
|
|
@@ -21,10 +21,15 @@
|
|
|
21
21
|
"lib/geo.mjs",
|
|
22
22
|
"lib/http-stream.mjs",
|
|
23
23
|
"lib/index.mjs",
|
|
24
|
+
"lib/inspector-server.mjs",
|
|
25
|
+
"lib/inspector-store.mjs",
|
|
26
|
+
"lib/inspector-ui.mjs",
|
|
24
27
|
"lib/protocol.mjs",
|
|
28
|
+
"lib/tcp-client.mjs",
|
|
25
29
|
"lib/tunnel-client.mjs",
|
|
26
30
|
"lib/user-config.mjs",
|
|
27
31
|
"LICENSE",
|
|
32
|
+
"NOTICE",
|
|
28
33
|
"README.md"
|
|
29
34
|
],
|
|
30
35
|
"scripts": {
|