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.
@@ -0,0 +1,292 @@
1
+ import { EventEmitter } from 'node:events'
2
+
3
+ const MiB = 1024 * 1024
4
+
5
+ /** Default inspector port on 127.0.0.1 (4040 is the dev gateway and ngrok). Busy ports fall back to the next ones. */
6
+ export const DEFAULT_INSPECTOR_PORT = 4041
7
+
8
+ /** Phase 1 limits: 200 entries, 32 MiB of retained bodies, 1 MiB per request body, 256 KiB per response body. */
9
+ export const INSPECTOR_LIMITS = Object.freeze({
10
+ maxEntries: 200,
11
+ maxBytes: 32 * MiB,
12
+ requestBodyLimit: MiB,
13
+ responseBodyLimit: 256 * 1024,
14
+ })
15
+
16
+ const NOOP_EXCHANGE = Object.freeze({
17
+ id: null,
18
+ requestChunk() {}, requestEnd() {}, response() {}, responseChunk() {}, frame() {}, finish() {},
19
+ })
20
+
21
+ /**
22
+ * In-memory capture of the HTTP requests and WebSocket connections that reached this CLI.
23
+ * Bodies are copied (never retained as views into tunnel frames) and bounded by per-body
24
+ * limits plus a global byte budget that includes in-flight entries. Completed entries are
25
+ * evicted oldest-first by count and by bytes; in-flight entries are never evicted.
26
+ * Emits `created`, `updated` (entry), `evicted` (ids) and `cleared`.
27
+ */
28
+ export function createInspectorStore(options = {}) {
29
+ const limits = { ...INSPECTOR_LIMITS }
30
+ for (const key of Object.keys(INSPECTOR_LIMITS)) {
31
+ if (Number.isSafeInteger(options[key]) && options[key] >= 0) limits[key] = options[key]
32
+ }
33
+ const events = new EventEmitter()
34
+ events.setMaxListeners(0)
35
+ /** Insertion order is id order, so iteration is oldest-first. */
36
+ const entries = new Map()
37
+ let nextId = 1
38
+ let usedBytes = 0
39
+
40
+ const newBody = limit => ({ chunks: [], retained: 0, bytes: 0, limit, truncated: false, complete: false })
41
+ const emit = (name, value) => { events.emit(name, value) }
42
+
43
+ function remove(entry) {
44
+ entries.delete(entry.id)
45
+ entry.removed = true
46
+ usedBytes -= entry.request.retained + entry.response.retained
47
+ entry.request.chunks = []
48
+ entry.response.chunks = []
49
+ }
50
+
51
+ /** Evict completed entries oldest-first until `needed` more bytes fit, or nothing is left to evict. */
52
+ function evictForBytes(needed) {
53
+ const evicted = []
54
+ for (const entry of entries.values()) {
55
+ if (usedBytes + needed <= limits.maxBytes) break
56
+ if (!entry.done) continue
57
+ remove(entry)
58
+ evicted.push(entry.id)
59
+ }
60
+ if (evicted.length) emit('evicted', evicted)
61
+ }
62
+
63
+ function evictForCount() {
64
+ const evicted = []
65
+ for (const entry of entries.values()) {
66
+ if (entries.size <= limits.maxEntries) break
67
+ if (!entry.done) continue
68
+ remove(entry)
69
+ evicted.push(entry.id)
70
+ }
71
+ if (evicted.length) emit('evicted', evicted)
72
+ }
73
+
74
+ function append(entry, body, chunk) {
75
+ if (entry.removed || body.complete || !chunk?.length) return
76
+ body.bytes += chunk.length
77
+ if (body.truncated) return
78
+ const wanted = Math.min(body.limit - body.retained, chunk.length)
79
+ let granted = wanted
80
+ if (wanted > 0) {
81
+ if (usedBytes + wanted > limits.maxBytes) evictForBytes(wanted)
82
+ granted = Math.max(0, Math.min(wanted, limits.maxBytes - usedBytes))
83
+ if (granted > 0) {
84
+ // Copy: tunnel chunks are views into whole WebSocket frames.
85
+ const copy = Buffer.allocUnsafeSlow(granted)
86
+ chunk.copy(copy, 0, 0, granted)
87
+ body.chunks.push(copy)
88
+ body.retained += granted
89
+ usedBytes += granted
90
+ }
91
+ }
92
+ if (granted < wanted) body.truncated = 'budget'
93
+ else if (wanted < chunk.length) body.truncated = 'limit'
94
+ }
95
+
96
+ function compact(body) {
97
+ if (body.chunks.length > 1) body.chunks = [Buffer.concat(body.chunks, body.retained)]
98
+ }
99
+
100
+ function exchange(entry) {
101
+ const live = () => !entry.removed && !entry.done
102
+ return {
103
+ id: entry.id,
104
+ requestChunk(chunk) {
105
+ if (!live()) return
106
+ append(entry, entry.request, chunk)
107
+ emit('updated', entry)
108
+ },
109
+ requestEnd() {
110
+ if (entry.removed || entry.request.complete) return
111
+ entry.request.complete = true
112
+ emit('updated', entry)
113
+ },
114
+ response(status, headers = {}, rawHeaders) {
115
+ if (!live() || entry.status !== null) return
116
+ entry.status = Number(status) || null
117
+ entry.responseHeaders = { ...headers }
118
+ entry.responseRawHeaders = Array.isArray(rawHeaders) ? rawHeaders.map(String) : null
119
+ entry.responseAtMs = Math.round(performance.now() - entry.t0)
120
+ emit('updated', entry)
121
+ },
122
+ responseChunk(chunk) {
123
+ if (!live()) return
124
+ append(entry, entry.response, chunk)
125
+ emit('updated', entry)
126
+ },
127
+ /** WebSocket frame counters; `in` = visitor to app, `out` = app to visitor. */
128
+ frame(direction, bytes) {
129
+ if (!live() || !entry.websocket) return
130
+ const ws = entry.websocket
131
+ if (direction === 'in') { ws.framesIn++; ws.bytesIn += bytes || 0 }
132
+ else { ws.framesOut++; ws.bytesOut += bytes || 0 }
133
+ emit('updated', entry)
134
+ },
135
+ finish({ error, synthetic, responseTruncated, closeCode, closeReason } = {}) {
136
+ if (!live()) return
137
+ entry.done = true
138
+ entry.durationMs = Math.round(performance.now() - entry.t0)
139
+ if (error) entry.error = error instanceof Error ? error.message : String(error)
140
+ if (synthetic) entry.synthetic = true
141
+ if (!error) entry.response.complete = true
142
+ // The gateway's end marker can trail the response; a body that matches its declared length is complete.
143
+ if (!entry.request.complete && entry.declaredRequestBytes !== null && entry.request.bytes === entry.declaredRequestBytes) entry.request.complete = true
144
+ if (responseTruncated && !entry.response.truncated) entry.response.truncated = 'tunnel'
145
+ if (entry.websocket) {
146
+ if (closeCode !== undefined) entry.websocket.closeCode = Number(closeCode) || null
147
+ if (closeReason) entry.websocket.closeReason = String(closeReason)
148
+ }
149
+ compact(entry.request)
150
+ compact(entry.response)
151
+ emit('updated', entry)
152
+ evictForCount()
153
+ },
154
+ }
155
+ }
156
+
157
+ return {
158
+ limits: Object.freeze({ ...limits }),
159
+ /** @returns {ReturnType<typeof exchange>} */
160
+ begin(info = {}) {
161
+ const kind = info.kind === 'websocket' ? 'websocket' : 'http'
162
+ const entry = {
163
+ id: nextId++,
164
+ kind,
165
+ source: info.source === 'replay' ? 'replay' : 'tunnel',
166
+ replayOf: Number.isSafeInteger(info.replayOf) ? info.replayOf : null,
167
+ replays: [],
168
+ method: String(info.method ?? 'GET').toUpperCase(),
169
+ path: String(info.path ?? '/'),
170
+ headers: { ...(info.headers ?? {}) },
171
+ publicUrl: info.publicUrl ? String(info.publicUrl) : null,
172
+ protocolVersion: info.protocolVersion ?? null,
173
+ declaredRequestBytes: Number.isSafeInteger(info.declaredRequestBytes) ? info.declaredRequestBytes : null,
174
+ startedAt: Date.now(),
175
+ t0: performance.now(),
176
+ responseAtMs: null,
177
+ durationMs: null,
178
+ done: false,
179
+ removed: false,
180
+ status: null,
181
+ responseHeaders: null,
182
+ responseRawHeaders: null,
183
+ error: null,
184
+ synthetic: false,
185
+ request: newBody(limits.requestBodyLimit),
186
+ response: newBody(limits.responseBodyLimit),
187
+ websocket: kind === 'websocket' ? { framesIn: 0, framesOut: 0, bytesIn: 0, bytesOut: 0, closeCode: null, closeReason: '' } : null,
188
+ }
189
+ entries.set(entry.id, entry)
190
+ if (entry.replayOf !== null) {
191
+ const original = entries.get(entry.replayOf)
192
+ if (original) { original.replays.push(entry.id); emit('updated', original) }
193
+ }
194
+ emit('created', entry)
195
+ evictForCount()
196
+ return exchange(entry)
197
+ },
198
+ get(id) { return entries.get(Number(id)) ?? null },
199
+ /** Entries with id > after, oldest first. */
200
+ list({ after = 0, limit = Infinity } = {}) {
201
+ const result = []
202
+ for (const entry of entries.values()) {
203
+ if (entry.id <= after) continue
204
+ result.push(entry)
205
+ if (result.length >= limit) break
206
+ }
207
+ return result
208
+ },
209
+ /** Retained bytes of a body as one Buffer. */
210
+ body(entry, side) {
211
+ const body = side === 'response' ? entry.response : entry.request
212
+ return body.chunks.length === 1 ? body.chunks[0] : Buffer.concat(body.chunks, body.retained)
213
+ },
214
+ summary,
215
+ clear() {
216
+ for (const entry of [...entries.values()]) remove(entry)
217
+ usedBytes = 0
218
+ emit('cleared')
219
+ },
220
+ stats() {
221
+ return { entries: entries.size, bytes: usedBytes, ...limits }
222
+ },
223
+ on(name, listener) { events.on(name, listener); return this },
224
+ off(name, listener) { events.off(name, listener); return this },
225
+ }
226
+ }
227
+
228
+ /** JSON-safe summary of an entry for lists and SSE. */
229
+ export function summary(entry) {
230
+ const header = name => {
231
+ const value = entry.responseHeaders?.[name]
232
+ return Array.isArray(value) ? value.join(', ') : value ?? null
233
+ }
234
+ return {
235
+ id: entry.id,
236
+ kind: entry.kind,
237
+ source: entry.source,
238
+ replayOf: entry.replayOf,
239
+ replays: [...entry.replays],
240
+ method: entry.method,
241
+ path: entry.path,
242
+ status: entry.status,
243
+ startedAt: entry.startedAt,
244
+ responseAtMs: entry.responseAtMs,
245
+ durationMs: entry.durationMs,
246
+ done: entry.done,
247
+ error: entry.error,
248
+ synthetic: entry.synthetic,
249
+ publicUrl: entry.publicUrl,
250
+ protocolVersion: entry.protocolVersion,
251
+ contentType: header('content-type'),
252
+ request: bodySummary(entry.request),
253
+ response: bodySummary(entry.response),
254
+ websocket: entry.websocket ? { ...entry.websocket } : null,
255
+ }
256
+ }
257
+
258
+ function bodySummary(body) {
259
+ return { bytes: body.bytes, retained: body.retained, truncated: body.truncated, complete: body.complete }
260
+ }
261
+
262
+ /**
263
+ * Request body size implied by the visitor's framing headers: Content-Length, 0 when neither
264
+ * Content-Length nor Transfer-Encoding is present, or null when chunked (end must be observed).
265
+ */
266
+ export function declaredBodyBytes(headers = {}) {
267
+ let length = null
268
+ for (const [name, value] of Object.entries(headers)) {
269
+ const key = name.toLowerCase()
270
+ if (key === 'transfer-encoding') return null
271
+ if (key === 'content-length') length = /^\d+$/.test(String(value).trim()) ? Number(value) : NaN
272
+ }
273
+ if (length === null) return 0
274
+ return Number.isSafeInteger(length) ? length : null
275
+ }
276
+
277
+ /**
278
+ * Begin a capture without ever letting the inspector break the tunnel: returns a no-op
279
+ * exchange when there is no store, and swallows any error thrown by the store or listeners.
280
+ */
281
+ export function beginExchange(store, info) {
282
+ if (!store) return NOOP_EXCHANGE
283
+ let exchange
284
+ try { exchange = store.begin(info) } catch { return NOOP_EXCHANGE }
285
+ if (!exchange) return NOOP_EXCHANGE
286
+ const safe = { id: exchange.id ?? null }
287
+ for (const name of Object.keys(NOOP_EXCHANGE)) {
288
+ if (name === 'id') continue
289
+ safe[name] = (...args) => { try { exchange[name]?.(...args) } catch {} }
290
+ }
291
+ return safe
292
+ }