@reqray/cli 0.0.0-stage → 0.1.1

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 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/render/width.ts","../src/render/format.ts","../src/render/row.ts","../src/filter.ts","../src/render/screens.ts","../src/render/theme.ts","../src/args.ts","../src/options.ts","../src/commands/context.ts","../src/render/findings.ts","../src/render/waterfall.ts","../src/render/detail.ts","../src/render/sql.ts","../src/commands/show.ts","../src/commands/watch.ts","../src/commands/index.ts","../src/version.ts","../src/app.ts"],"sourcesContent":["/**\n * Failures, as a person reads them.\n *\n * Every way this client can fail ends in one of these: a headline in plain\n * words, hypotheses about what to do next, and — only under `--verbose` — the\n * technical cause. A stack trace is what a tool prints when it has nothing\n * useful to say.\n */\n\n/** Exit codes, as documented in DESIGN.md. */\nexport const EXIT_OK = 0;\n/** Something went wrong, including a collector that cannot be reached. */\nexport const EXIT_FAILED = 1;\n/** The arguments, or the terminal, made the command impossible to run. */\nexport const EXIT_USAGE = 2;\n\n/** A failure with an exit code and something to say about it. */\nexport class CliError extends Error {\n readonly exitCode: number;\n /**\n * Lines printed under the headline: what to check, what to run next.\n *\n * Rendered as given, so they carry their own indentation.\n */\n readonly hints: readonly string[];\n\n constructor(\n message: string,\n options: { exitCode?: number; hints?: readonly string[]; cause?: unknown } = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'CliError';\n this.exitCode = options.exitCode ?? EXIT_FAILED;\n this.hints = options.hints ?? [];\n }\n}\n\n/** Bad arguments, a missing value, a terminal too narrow to print in. */\nexport class UsageError extends CliError {\n constructor(message: string, hints: readonly string[] = []) {\n super(message, { exitCode: EXIT_USAGE, hints });\n this.name = 'UsageError';\n }\n}\n\n/**\n * The collector did not answer.\n *\n * The three hypotheses are ordered by how often each one turns out to be the\n * answer, and the concrete values sit on the right because they get copied.\n */\nexport class UnreachableError extends CliError {\n constructor(url: string, cause: unknown) {\n super('cannot reach the collector', {\n exitCode: EXIT_FAILED,\n hints: [\n '',\n ' the panel is served by your app. check that',\n ' 1 reqray is attached reqray({ panel: true }) before the routes',\n ' 2 the app is running and that NODE_ENV is not production',\n ` 3 the address matches REQRAY_URL=${url}`,\n ],\n cause,\n });\n this.name = 'UnreachableError';\n }\n}\n\n/**\n * The technical cause, for `--verbose`. Never shown by default.\n *\n * `null` when there is nothing underneath — a mistyped flag has no cause, and\n * offering `--verbose` for one would promise something that is not there.\n */\nexport function causeOf(error: unknown): string | null {\n const cause = error instanceof Error ? (error.cause ?? null) : null;\n if (cause instanceof Error) {\n // `fetch failed` on its own says nothing; the reason underneath does.\n const inner = cause.cause;\n return inner instanceof Error ? `${cause.message} — ${inner.message}` : cause.message;\n }\n return cause === null ? null : String(cause);\n}\n","/**\n * The panel API, over HTTP.\n *\n * This client carries no instrumentation and imports no part of `@reqray/core`:\n * it talks to the same endpoints the web panel talks to, and the shapes it\n * receives come from `@reqray/protocol` as types only. A collector reached\n * through an ssh tunnel is an ordinary URL and needs nothing else.\n *\n * Built-in `fetch`, and a hand-rolled reader for the event stream. `undici` is\n * a dependency an `npx` user waits for, and the global `EventSource` cannot\n * set the header a token-protected collector requires.\n */\n\nimport type {\n ApiError,\n BaselineResponse,\n PanelMeta,\n RequestDetail,\n RequestSort,\n RequestsResponse,\n} from '@reqray/protocol';\nimport { CliError, UnreachableError } from './errors.js';\n\n/**\n * Parses what the panel sent, with every string made safe to print.\n *\n * A record is written by whoever sent the request: a path, a test name, an\n * exception message, a body. Printed as they came, an escape sequence in any\n * of them is an instruction to the reader's terminal — clear the screen,\n * retitle the window, rewrite a line already read. Stripped here, once, so no\n * renderer has to remember. Tabs and line breaks are layout, and stay.\n */\nexport function parsePrintable(text: string): unknown {\n return JSON.parse(text, (_key, value: unknown) =>\n typeof value === 'string' ? value.replace(/(?![\\t\\n])\\p{Cc}/gu, '') : value,\n );\n}\n\n/** Where the panel is, and how to get past its gate. */\nexport interface ClientOptions {\n /** Base URL of the panel, e.g. `http://localhost:3000/_reqray`. */\n readonly url: string;\n /** Shared secret, for a collector that was started with one. */\n readonly token?: string | null;\n /** Swapped out in tests. */\n readonly fetch?: typeof globalThis.fetch;\n}\n\n/** What to ask the list for. Mirrors the panel's own query parameters. */\nexport interface ListQuery {\n readonly limit?: number;\n /** Substring of the method, path, status or query string. */\n readonly query?: string;\n readonly cursor?: string | null;\n readonly minDurationMs?: number;\n readonly methods?: readonly string[];\n readonly statusClasses?: readonly number[];\n readonly onlyFindings?: boolean;\n readonly onlyErrors?: boolean;\n readonly sort?: RequestSort;\n}\n\n/** What a live stream reports back. */\nexport interface StreamHandlers {\n /** A request just finished. */\n onRow(row: unknown): void;\n /** Something the reader should know about the connection itself. */\n onNotice(text: string): void;\n /** Aborting it ends the stream and the retry loop with it. */\n readonly signal: AbortSignal;\n /** Swapped out in tests, so backoff costs no wall-clock time. */\n sleep?(ms: number): Promise<void>;\n}\n\n/** First delay after a dropped connection, ms. Doubles from here. */\nconst BACKOFF_START = 500;\n/** The ceiling. A collector that is down stays polled once every ten seconds. */\nconst BACKOFF_MAX = 10_000;\n\nconst wait = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.();\n });\n\n/** A client for one panel. */\nexport class ReqrayClient {\n readonly #url: string;\n readonly #token: string | null;\n readonly #fetch: typeof globalThis.fetch;\n\n constructor(options: ClientOptions) {\n this.#url = options.url.replace(/\\/+$/, '');\n this.#token = options.token ?? null;\n this.#fetch = options.fetch ?? globalThis.fetch;\n }\n\n /** The panel's address, as it was resolved. */\n get url(): string {\n return this.#url;\n }\n\n /** What the process behind the panel is. */\n async meta(signal?: AbortSignal): Promise<PanelMeta> {\n return this.#json<PanelMeta>('/api/meta', signal);\n }\n\n /** One page of the list. */\n async list(query: ListQuery = {}, signal?: AbortSignal): Promise<RequestsResponse> {\n return this.#json<RequestsResponse>(`/api/requests${searchOf(query)}`, signal);\n }\n\n /** One request, whole. */\n async detail(id: string, signal?: AbortSignal): Promise<RequestDetail> {\n return this.#json<RequestDetail>(`/api/requests/${encodeURIComponent(id)}`, signal);\n }\n\n /**\n * How the request compares against its route's own history, and whether\n * the process underneath was struggling at the time.\n *\n * Empty when there is nothing to compare against, and empty too when the\n * collector is older than the endpoint: a verdict is worth printing when it\n * is there and worth nothing said when it is not.\n */\n async baseline(id: string, signal?: AbortSignal): Promise<BaselineResponse> {\n try {\n return await this.#json<BaselineResponse>(\n `/api/requests/${encodeURIComponent(id)}/baseline`,\n signal,\n );\n } catch {\n return { baseline: null, pressure: null };\n }\n }\n\n /** The same, unparsed — what `--json` prints. */\n async detailRaw(id: string, signal?: AbortSignal): Promise<string> {\n const response = await this.#get(`/api/requests/${encodeURIComponent(id)}`, signal);\n const text = await response.text();\n if (!response.ok) throw await refusal(response.status, text);\n return text;\n }\n\n /**\n * The live feed, until the signal is aborted.\n *\n * A dropped connection is reported and retried with a doubling delay: the\n * application restarting is the common case, and a client that dies with it\n * is a client nobody leaves running.\n */\n async stream(handlers: StreamHandlers): Promise<void> {\n const sleep = handlers.sleep ?? wait;\n let backoff = BACKOFF_START;\n let attempt = 0;\n\n while (!handlers.signal.aborted) {\n try {\n const response = await this.#get('/api/stream', handlers.signal, {\n accept: 'text/event-stream',\n });\n if (!response.ok || !response.body) {\n throw await refusal(response.status, await response.text());\n }\n\n // The connection stood up: whatever went wrong before is over.\n backoff = BACKOFF_START;\n if (attempt > 0) handlers.onNotice('reconnected');\n attempt = 0;\n\n await readEvents(response.body, handlers);\n if (handlers.signal.aborted) return;\n // The server closed a stream that has no natural end — reconnect.\n } catch (error) {\n if (handlers.signal.aborted) return;\n if (error instanceof CliError && !(error instanceof UnreachableError)) throw error;\n }\n\n if (handlers.signal.aborted) return;\n attempt++;\n handlers.onNotice(\n `connection lost, reconnecting in ${seconds(backoff)} (attempt ${attempt})`,\n );\n await sleep(backoff);\n backoff = Math.min(backoff * 2, BACKOFF_MAX);\n }\n }\n\n async #json<T>(path: string, signal?: AbortSignal): Promise<T> {\n const response = await this.#get(path, signal);\n const text = await response.text();\n if (!response.ok) throw await refusal(response.status, text);\n try {\n return parsePrintable(text) as T;\n } catch (error) {\n throw new CliError(`the panel answered something that is not JSON (${path})`, {\n cause: error,\n });\n }\n }\n\n async #get(\n path: string,\n signal?: AbortSignal,\n headers: Record<string, string> = {},\n ): Promise<Response> {\n const request: RequestInit = {\n headers: this.#token ? { ...headers, 'x-reqray-token': this.#token } : headers,\n ...(signal ? { signal } : {}),\n };\n try {\n return await this.#fetch(`${this.#url}${path}`, request);\n } catch (error) {\n if (signal?.aborted) throw error;\n throw new UnreachableError(this.#url, error);\n }\n }\n}\n\n/** Turns a refusal into something addressed to a person. */\nasync function refusal(status: number, body: string): Promise<CliError> {\n let message = body.trim();\n try {\n const parsed = JSON.parse(body) as ApiError;\n if (typeof parsed.error === 'string') message = parsed.error;\n } catch {\n // Not JSON — whatever the body says is still better than nothing.\n }\n\n if (status === 404) {\n return new CliError(message || 'no such request — it may have left the buffer already');\n }\n if (status === 401 || status === 403) {\n return new CliError(`the panel refused: ${message || 'access denied'}`, {\n hints: [\n '',\n ' a collector started with a token wants it back:',\n ' reqray watch --token <token> or REQRAY_TOKEN=<token>',\n ],\n });\n }\n return new CliError(message || `the panel answered ${status}`);\n}\n\n/** Query string for a list request, leaving out what was not asked. */\nfunction searchOf(query: ListQuery): string {\n const params = new URLSearchParams();\n if (query.limit !== undefined) params.set('limit', String(query.limit));\n if (query.query) params.set('q', query.query);\n if (query.cursor) params.set('cursor', query.cursor);\n if (query.minDurationMs !== undefined) params.set('minDurationMs', String(query.minDurationMs));\n if (query.methods?.length) params.set('method', query.methods.join(','));\n if (query.statusClasses?.length) params.set('status', query.statusClasses.join(','));\n if (query.onlyFindings) params.set('findings', '1');\n if (query.onlyErrors) params.set('errors', '1');\n if (query.sort) params.set('sort', query.sort);\n const search = params.toString();\n return search ? `?${search}` : '';\n}\n\n/**\n * Reads `text/event-stream` until it ends.\n *\n * Events are separated by a blank line and may be split across chunks, so the\n * tail of a chunk is kept until the rest of it arrives. Comment lines — the\n * keep-alive pings — are skipped without a word.\n */\nasync function readEvents(\n body: ReadableStream<Uint8Array>,\n handlers: StreamHandlers,\n): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffered = '';\n\n const stop = (): void => void reader.cancel().catch(() => {});\n handlers.signal.addEventListener('abort', stop, { once: true });\n\n try {\n while (!handlers.signal.aborted) {\n const { done, value } = await reader.read();\n if (done) return;\n\n buffered += decoder.decode(value, { stream: true });\n let split = buffered.indexOf('\\n\\n');\n while (split !== -1) {\n const event = buffered.slice(0, split);\n buffered = buffered.slice(split + 2);\n const payload = dataOf(event);\n if (payload !== null) {\n try {\n handlers.onRow(parsePrintable(payload) as Parameters<typeof handlers.onRow>[0]);\n } catch {\n // A row we cannot read is one row, not a reason to stop watching.\n }\n }\n split = buffered.indexOf('\\n\\n');\n }\n }\n } finally {\n handlers.signal.removeEventListener('abort', stop);\n reader.releaseLock();\n }\n}\n\n/** The `data:` payload of one event, or `null` for a comment or a ping. */\nfunction dataOf(event: string): string | null {\n const lines = event.split('\\n').filter((line) => line.startsWith('data:'));\n if (lines.length === 0) return null;\n return lines.map((line) => line.slice(5).trimStart()).join('\\n');\n}\n\n/** A delay as the notice prints it: `2 s`, `500 ms`. */\nfunction seconds(ms: number): string {\n return ms >= 1000 ? `${Math.round(ms / 100) / 10} s` : `${ms} ms`;\n}\n","/**\n * Fitting a line into the terminal.\n *\n * One column is flexible — the path — and everything else keeps its place, so\n * output at 80 columns and at 200 reads the same way. When the flexible column\n * hits its floor, whole columns are dropped in a fixed order rather than the\n * grid collapsing.\n *\n * The numbers are in DESIGN.md and the table there is what these functions\n * produce; the tests check both ends of it.\n */\n\n/** Below this the grid cannot be drawn at all. */\nexport const MIN_WIDTH = 56;\n\n/** Shortest path column worth printing. */\nconst PATH_FLOOR = 21;\n\n/**\n * The fixed part of a stream line.\n *\n * gutter 2, time 12, method 6, status 3, duration 7, queries 4, six spaces\n * between them, a flag reserve of 8, and one column left unused at the right\n * edge so a full line never wraps.\n */\nconst FIXED = 51;\n/** What the queries column costs, separator included. */\nconst QUERIES = 5;\n/** What the status column costs, separator included. */\nconst STATUS = 4;\n\n/** What the id column costs, separator included. */\nconst IDS = 13;\n\n/** Which columns a stream line has room for. */\nexport interface StreamColumns {\n readonly path: number;\n readonly queries: boolean;\n readonly status: boolean;\n /** Printed only when asked for: it is a handle, not information. */\n readonly ids: boolean;\n}\n\n/**\n * How a stream line is laid out at this width.\n *\n * The queries column goes first — it is a number that repeats what the\n * duration already implies — and the status second, because it is only\n * interesting when it is not 200, and a non-2xx keeps its code in the flag\n * column instead.\n */\nexport function streamColumns(width: number, ids = false): StreamColumns {\n // The id column is taken out of the path's budget, so everything else keeps\n // its place whether it is printed or not.\n const room = width - (ids ? IDS : 0);\n\n if (room - FIXED >= PATH_FLOOR) {\n return { path: room - FIXED, queries: true, status: true, ids };\n }\n if (room - FIXED + QUERIES >= PATH_FLOOR - 3) {\n return { path: room - FIXED + QUERIES, queries: false, status: true, ids };\n }\n return {\n path: Math.max(8, room - FIXED + QUERIES + STATUS),\n queries: false,\n status: false,\n ids,\n };\n}\n\n/** Pads to a width, cutting anything longer. */\nexport function pad(text: string, width: number): string {\n return text.length >= width ? text.slice(0, width) : text + ' '.repeat(width - text.length);\n}\n\n/** The same, against the right edge — for numbers. */\nexport function padStart(text: string, width: number): string {\n return text.length >= width ? text.slice(-width) : ' '.repeat(width - text.length) + text;\n}\n\n/** Cuts to a width, marking that something was cut. */\nexport function cut(text: string, width: number, ellipsis: string): string {\n if (text.length <= width) return text;\n if (width <= ellipsis.length) return text.slice(0, width);\n return text.slice(0, width - ellipsis.length) + ellipsis;\n}\n\n/**\n * A path and its query string, fitted into a column.\n *\n * Whole segments go, never characters: a truncated path stays a path and can\n * still be recognised, where `/api/v2/organizat…` tells the reader nothing.\n * The query string is the first thing given up, then the segments in the\n * middle — the first says which service, the last which handler, and the\n * identifiers between them are what nobody reads.\n */\nexport function fitPath(\n path: string,\n query: string | null,\n width: number,\n ellipsis: string,\n): string {\n const whole = query ? `${path}?${query}` : path;\n if (whole.length <= width) return whole;\n\n // Step one: the query string becomes a marker.\n const marker = query ? `?${ellipsis}` : '';\n if (path.length + marker.length <= width) return path + marker;\n\n // Step two: the middle segments collapse, keeping the head and as much of\n // the tail as fits.\n const segments = path.split('/').filter(Boolean);\n const head = segments[0] ?? '';\n const tail = segments.slice(1);\n\n for (const withHead of [true, false]) {\n const prefix = withHead ? `/${head}/${ellipsis}` : `/${ellipsis}`;\n let taken: string[] = [];\n for (let index = tail.length - 1; index >= (withHead ? 1 : 0); index--) {\n const candidate = [tail[index] as string, ...taken];\n const length = prefix.length + candidate.join('/').length + 1 + marker.length;\n if (length > width) break;\n taken = candidate;\n }\n if (taken.length > 0) return `${prefix}/${taken.join('/')}${marker}`;\n }\n\n // Step three: not even the leaf fits, so the leaf is cut.\n const leaf = segments[segments.length - 1] ?? path;\n return cut(`/${ellipsis}/${leaf}`, width, ellipsis);\n}\n","/**\n * Numbers, as they are read.\n *\n * Two duration formats, because the two screens ask different questions. The\n * stream is scanned for outliers, so 61 ms and 92 ms are near enough to\n * print whole. The waterfall is read for proportion, where a span of 0.4 ms\n * and one of 41.2 ms both have to be tellable apart from their neighbours.\n */\n\nimport type { Theme } from './theme.js';\n\n/** Above this a request is worth a mark in the gutter, ms. */\nexport const SLOW_MS = 300;\n/** Above this it is worth the strongest mark the stream has, ms. */\nexport const VERY_SLOW_MS = 1_000;\n/** More queries than this in one request is worth colouring. */\nexport const MANY_QUERIES = 20;\n\n/** A duration in the stream: `1.2ms`, `47ms`, `2.14s`. */\nexport function duration(ms: number): string {\n if (ms >= 100_000) return `${Math.round(ms / 1000)}s`;\n if (ms >= 1_000) return `${(ms / 1000).toFixed(2)}s`;\n if (ms >= 10) return `${Math.round(ms)}ms`;\n return `${ms.toFixed(1)}ms`;\n}\n\n/** A duration in the waterfall: `0.4ms`, `41.2ms`, `268ms`, `2.14s`. */\nexport function spanDuration(ms: number): string {\n if (ms >= 100_000) return `${Math.round(ms / 1000)}s`;\n if (ms >= 1_000) return `${(ms / 1000).toFixed(2)}s`;\n if (ms >= 100) return `${Math.round(ms)}ms`;\n return `${ms.toFixed(1)}ms`;\n}\n\n/** A size, as a response header would have said it: `4.1 KB`. */\nexport function bytes(count: number): string {\n if (count < 1024) return `${count} B`;\n if (count < 1024 * 1024) return `${(count / 1024).toFixed(1)} KB`;\n return `${(count / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/** Wall-clock time of a request, to the millisecond, in the reader's zone. */\nexport function clock(at: number): string {\n const when = new Date(at);\n const two = (value: number) => String(value).padStart(2, '0');\n const three = String(when.getMilliseconds()).padStart(3, '0');\n return `${two(when.getHours())}:${two(when.getMinutes())}:${two(when.getSeconds())}.${three}`;\n}\n\n/**\n * Short badge for a detector.\n *\n * The panel's own words, shortened where the flag column cannot hold them:\n * `SEQ HTTP` reads as `SEQ` here and means the same thing. An unknown\n * detector prints its own id rather than a shrug.\n */\nexport function badgeFor(detector: string): string {\n switch (detector) {\n case 'n_plus_one':\n return 'N+1';\n case 'sequential_http':\n return 'SEQ';\n case 'dup_http':\n case 'dup_cache':\n return 'DUP';\n case 'slow_budget':\n return 'SLOW';\n case 'heavy_response':\n return 'HEAVY';\n default:\n return detector.toUpperCase();\n }\n}\n\n/** A share of the request, as the findings block prints it. */\nexport function share(part: number, whole: number): string {\n if (whole <= 0) return '';\n return `${Math.round((part / whole) * 100)}% of total`;\n}\n\n/** A count of queries: `6q`, or nothing at all when there were none. */\nexport function queries(count: number, theme: Theme): string {\n return count === 0 ? theme.glyph('none') : `${count}q`;\n}\n","/**\n * One request, on one line.\n *\n * The grid is fixed so the eye can hold a vertical: the same fact is always in\n * the same place, and the gutter reserves its two columns even when they are\n * empty, so a `!` appearing does not shift the line under it.\n *\n * Severity is carried by a glyph first and by colour second. Every renderer\n * here paints padded text, never pads painted text — an escape sequence has\n * no width, and measuring one is how columns drift.\n */\n\nimport type { RequestDetail, RequestRow } from '@reqray/protocol';\nimport {\n badgeFor,\n clock,\n duration,\n MANY_QUERIES,\n queries,\n SLOW_MS,\n VERY_SLOW_MS,\n} from './format.js';\nimport type { Style, Theme } from './theme.js';\nimport { fitPath, pad, padStart, streamColumns } from './width.js';\n\n/** A painted cell: what it says, and what it means. */\ntype Cell = readonly [Style, string];\n\n/** The flag at the right edge — the one thing the eye scans for. */\nfunction flagOf(row: RequestRow, showStatus: boolean): Cell | null {\n // With the status column dropped, a non-2xx prints its code here instead:\n // the code is the more serious fact, and the flag is one `show` away.\n if (!showStatus && row.status >= 400) {\n return [row.status >= 500 ? 'errLoud' : 'warn', String(row.status)];\n }\n if (row.hasError) return ['errLoud', 'ERR'];\n if (row.flag) return [row.flag === 'n_plus_one' ? 'warnLoud' : 'warn', badgeFor(row.flag)];\n if (row.test) return ['cmd', 'TEST'];\n return null;\n}\n\n/** Two columns of severity, before any colour is involved. */\nfunction gutterOf(row: RequestRow): Cell {\n if (row.hasError) return ['err', '!!'];\n if (row.findingCount > 0 || row.durationMs >= SLOW_MS) return ['warn', '!'];\n return ['dim', ''];\n}\n\nfunction statusStyle(status: number): Style {\n if (status >= 500) return 'errLoud';\n if (status >= 400) return 'warn';\n // 2xx is not green: in a stream that would be a green column on every line,\n // and the rare thing worth seeing would weigh no more than the usual one.\n return 'dim';\n}\n\nfunction durationStyle(ms: number): Style {\n if (ms >= VERY_SLOW_MS) return 'err';\n if (ms >= SLOW_MS) return 'warn';\n return 'plain';\n}\n\n/**\n * Paints a fitted path.\n *\n * What reqray added — the ellipsis, the `?` that stands in for a query string\n * — is muted; what was in the request is not. Colour is what separates the\n * two, which is why the markers are never painted as data.\n */\nfunction paintPath(text: string, theme: Theme): string {\n const ellipsis = theme.glyph('ellipsis');\n const parts = text.split(ellipsis);\n return parts\n .map((part, index) => {\n const last = index === parts.length - 1;\n // A `?` right before an ellipsis belongs to the marker, not to the path.\n if (!last && part.endsWith('?')) {\n return theme.paint('plain', part.slice(0, -1)) + theme.paint('dim', '?');\n }\n return theme.paint('plain', part);\n })\n .join(theme.paint('dim', ellipsis));\n}\n\n/**\n * Paints cells and puts them together.\n *\n * Never trims: a separator at the end of a chunk is a column boundary, and\n * trimming one is how the status column ends up glued to the path. Only the\n * finished line is trimmed, once, at the end.\n */\nfunction join(theme: Theme, cells: readonly Cell[]): string {\n return cells.map(([style, text]) => theme.paint(style, text)).join('');\n}\n\n/**\n * How wide an id is printed: an eight-character process prefix and room for\n * the first million and a half requests of that process. A cut id opens\n * nothing, so the column is as wide as an id really is.\n */\nconst ID = 12;\n\n/** What a stream line may show beyond the fixed grid. */\nexport interface RowOptions {\n /** Print the identifier `show` takes, so a row on screen can be opened. */\n readonly ids?: boolean;\n}\n\n/** The column heads. Coordinates, so all of it is muted. */\nexport function streamHead(theme: Theme, options: RowOptions = {}): string {\n const columns = streamColumns(theme.width, options.ids);\n const cells: Cell[] = [['dim', ' ']];\n if (columns.ids) cells.push(['dim', pad('ID', ID)], ['dim', ' ']);\n cells.push(['dim', pad('TIME', 12)], ['dim', ' '], ['dim', pad('METHOD', 6)], ['dim', ' ']);\n if (columns.status) cells.push(['dim', pad('ST', 3)], ['dim', ' ']);\n cells.push(['dim', pad('PATH', columns.path)], ['dim', ' '], ['dim', padStart('DUR', 7)]);\n if (columns.queries) cells.push(['dim', ' '], ['dim', padStart('Q', 4)]);\n cells.push(['dim', ' '], ['dim', 'FLAGS']);\n return join(theme, cells);\n}\n\n/** One request. */\nexport function streamRow(row: RequestRow, theme: Theme, options: RowOptions = {}): string {\n const columns = streamColumns(theme.width, options.ids);\n const gutter = gutterOf(row);\n const flag = flagOf(row, columns.status);\n const path = fitPath(row.path, row.query, columns.path, theme.glyph('ellipsis'));\n\n const cells: Cell[] = [\n [gutter[0], pad(gutter[1], 2)],\n ['dim', ' '],\n ];\n // Cyan, like every other string here that can be copied into a command.\n if (columns.ids) cells.push(['cmd', pad(row.id, ID)], ['dim', ' ']);\n cells.push(\n ['dim', pad(clock(row.startedAt), 12)],\n ['dim', ' '],\n // POST and DELETE read louder than GET without a colour of their own —\n // only by contrast with a muted one.\n [row.method === 'GET' ? 'dim' : 'plain', pad(row.method, 6)],\n ['dim', ' '],\n );\n if (columns.status) {\n cells.push([statusStyle(row.status), pad(String(row.status), 3)], ['dim', ' ']);\n }\n\n const painted = [\n join(theme, cells),\n paintPath(pad(path, columns.path), theme),\n theme.paint('dim', ' '),\n theme.paint(durationStyle(row.durationMs), padStart(duration(row.durationMs), 7)),\n ];\n if (columns.queries) {\n painted.push(\n theme.paint('dim', ' '),\n theme.paint(\n row.sqlCount > MANY_QUERIES ? 'warn' : 'dim',\n padStart(queries(row.sqlCount, theme), 4),\n ),\n );\n }\n painted.push(theme.paint('dim', ' '), flag ? theme.paint(flag[0], flag[1]) : '');\n\n return painted.join('').trimEnd();\n}\n\n/**\n * The second line a failed request gets.\n *\n * The only exception to one line per request. An exception with neither type\n * nor file would send the reader to `show` immediately — cheaper to print it\n * here, where they are already looking.\n */\nexport function failureLines(\n row: RequestRow,\n detail: RequestDetail | null,\n theme: Theme,\n): string[] {\n const error = detail?.error ?? null;\n const command = `reqray show ${row.id}`;\n const corner = theme.glyph('corner');\n\n if (!error) {\n return [` ${theme.paint('dim', corner)} ${theme.paint('cmd', command)}`];\n }\n\n const lines = [\n ` ${theme.paint('dim', corner)} ${theme.paint('err', error.name)}${theme.paint('dim', `: ${error.message}`)}`,\n ];\n\n const frame = frameOf(error.stack);\n const left = ` ${frame ?? ''}`;\n if (frame && left.length + command.length + 3 <= theme.width) {\n const gap = ' '.repeat(theme.width - left.length - command.length - 1);\n lines.push(theme.paint('dim', left) + gap + theme.paint('cmd', command));\n } else {\n if (frame) lines.push(theme.paint('dim', left));\n lines.push(` ${theme.paint('cmd', command)}`);\n }\n return lines;\n}\n\n/**\n * The first frame of a stack that belongs to the application.\n *\n * Two path segments, which is what a reader needs to find the file, and all\n * that can be said without knowing where the project root is — the client is\n * on the other side of an HTTP boundary from the process that threw.\n */\nexport function frameOf(stack: string | null): string | null {\n if (!stack) return null;\n for (const raw of stack.split('\\n')) {\n const line = raw.trim();\n if (!line.startsWith('at ')) continue;\n\n // The whole location, not a piece of it: `node:internal/process/x` has a\n // slash in it, and a pattern looking for one finds a frame that is not a\n // file at all.\n const match = /^at\\s+(?:.*?\\s+\\()?(.+?):(\\d+):(\\d+)\\)?$/.exec(line);\n const file = match?.[1];\n if (!file || file.startsWith('node:') || file.includes('node_modules')) continue;\n\n const parts = file.split(/[/\\\\]/).filter((part) => part !== '' && part !== 'file:');\n return `${parts.slice(-2).join('/')}:${match?.[2]}`;\n }\n return null;\n}\n","/**\n * Narrowing the live stream.\n *\n * The stream endpoint sends every request and takes no parameters, so this is\n * decided here — the same way the web panel narrows its own feed. It is also\n * the only sensible place for it: `--path` is a glob, and a glob is a\n * question about a string, not about a store.\n */\n\nimport type { RequestRow } from '@reqray/protocol';\n\n/** What `watch` was asked to show. */\nexport interface StreamFilter {\n readonly slowerThanMs?: number | null;\n /** `404`, `4xx`, `5xx` — codes and classes together. */\n readonly statuses?: readonly string[];\n readonly methods?: readonly string[];\n /** A glob over the path: `*` is any run of characters, `?` is one. */\n readonly path?: string | null;\n readonly findingsOnly?: boolean;\n}\n\n/** Whether a row belongs on screen. */\nexport function matches(row: RequestRow, filter: StreamFilter): boolean {\n if (filter.slowerThanMs != null && row.durationMs < filter.slowerThanMs) return false;\n if (filter.findingsOnly && row.findingCount === 0) return false;\n\n const methods = filter.methods ?? [];\n if (methods.length > 0 && !methods.some((method) => method.toUpperCase() === row.method)) {\n return false;\n }\n\n const statuses = filter.statuses ?? [];\n if (statuses.length > 0 && !statuses.some((spec) => matchesStatus(row.status, spec))) {\n return false;\n }\n\n if (filter.path && !globOf(filter.path).test(row.path)) return false;\n return true;\n}\n\n/** `404` matches one code; `4xx` matches the class. */\nexport function matchesStatus(status: number, spec: string): boolean {\n const trimmed = spec.trim().toLowerCase();\n if (/^[1-5]xx$/.test(trimmed)) return Math.floor(status / 100) === Number(trimmed[0]);\n const exact = Number(trimmed);\n return Number.isFinite(exact) && exact === status;\n}\n\nconst globCache = new Map<string, RegExp>();\n\n/**\n * A path glob.\n *\n * `*` crosses slashes: `--path '/api/*'` means everything under `/api`, which\n * is what someone typing it means, whatever a shell would have done with it.\n */\nexport function globOf(glob: string): RegExp {\n const cached = globCache.get(glob);\n if (cached) return cached;\n\n const pattern = glob\n .split('')\n .map((char) => {\n if (char === '*') return '.*';\n if (char === '?') return '.';\n return /[a-zA-Z0-9/_-]/.test(char) ? char : `\\\\${char}`;\n })\n .join('');\n const expression = new RegExp(`^${pattern}$`);\n globCache.set(glob, expression);\n return expression;\n}\n","/**\n * The screens that are text rather than data.\n *\n * Both of them — nothing recorded yet, and nothing answering — have to end in\n * something to do. A state that only states itself leaves the reader to guess\n * whether they are looking at a bug or at an empty afternoon.\n */\n\nimport type { PanelMeta } from '@reqray/protocol';\nimport { CliError, causeOf } from '../errors.js';\nimport type { Theme } from './theme.js';\nimport { padStart } from './width.js';\n\n/** The line every command prints first. */\nexport function header(version: string, url: string, meta: PanelMeta, theme: Theme): string[] {\n const host = hostOf(url);\n return [\n theme.paint('plain', `reqray ${version}`) +\n theme.paint('dim', ` watching ${host} pid ${meta.pid} ctrl-c to stop`),\n '',\n ];\n}\n\n/**\n * The collector answered, and has nothing to show.\n *\n * Not an error, so nothing here is red: the header is the one a working\n * stream prints, and the only coloured thing on screen is a command that can\n * be copied into the next tab.\n */\nexport function emptyState(url: string, meta: PanelMeta, theme: Theme): string[] {\n const origin = new URL(url).origin;\n const waiting = ' waiting';\n const status = `buffer ${meta.bufferSize}, empty`;\n const gap = Math.max(2, theme.width - waiting.length - status.length - 1);\n\n return [\n theme.paint('plain', ' collector attached — no requests recorded yet'),\n '',\n theme.paint('dim', ' try ') + theme.paint('cmd', `curl -s ${origin}/`),\n theme.paint('dim', ' or just reload the application in a browser'),\n '',\n theme.paint('dim', waiting) + ' '.repeat(gap) + theme.paint('dim', status),\n ];\n}\n\n/**\n * A failure, as a person reads it.\n *\n * One bright line, then what to check. The technical cause is a `--verbose`\n * away: it belongs in a bug report, and putting it above the hypotheses\n * would bury them.\n */\nexport function renderFailure(error: unknown, theme: Theme, verbose: boolean): string[] {\n const message = error instanceof Error ? error.message : String(error);\n const lines = [theme.paint('errLoud', `reqray: ${message}`)];\n\n const cause = causeOf(error);\n if (verbose && cause) lines.push('', theme.paint('dim', ` ${cause}`));\n\n if (error instanceof CliError) lines.push(...error.hints.map((hint) => theme.paint('dim', hint)));\n\n if (!verbose && cause) {\n lines.push(\n '',\n theme.paint('dim', ' ') +\n theme.paint('cmd', 'reqray --verbose') +\n theme.paint('dim', ' prints what actually failed'),\n );\n }\n return lines;\n}\n\n/** A stream that dropped, or came back. Muted: it is not the reader's doing. */\nexport function noticeLine(text: string, theme: Theme): string {\n return theme.paint('dim', ` ${theme.glyph('ellipsis')} ${text}`);\n}\n\n/** The status line under a list that has been narrowed. */\nexport function countLine(shown: number, total: number, theme: Theme): string {\n const left = ` ${shown} shown`;\n const right = `${total} recorded`;\n const gap = Math.max(2, theme.width - left.length - right.length - 1);\n return theme.paint('dim', left) + ' '.repeat(gap) + theme.paint('dim', right);\n}\n\n/** Host and port, as the header names the thing being watched. */\nexport function hostOf(url: string): string {\n try {\n return new URL(url).host;\n } catch {\n return url;\n }\n}\n\n/** Right-aligns a trailing command against the terminal's edge. */\nexport function trailing(left: string, command: string, theme: Theme): string {\n const gap = theme.width - left.length - command.length - 1;\n if (gap < 2) return `${theme.paint('dim', left)} ${theme.paint('cmd', command)}`;\n return theme.paint('dim', left) + ' '.repeat(gap) + theme.paint('cmd', command);\n}\n\n/** Used by `show` for the \"N more\" tail; kept here so padding lives together. */\nexport function rightAligned(text: string, width: number): string {\n return padStart(text, width);\n}\n","/**\n * Colour and glyphs, decided once.\n *\n * Every renderer asks the theme rather than reading the environment itself:\n * one place decides whether this output is going to a terminal, a pipe or a\n * CI log, and one place knows what to draw when the font cannot be trusted.\n *\n * Sixteen colours, no backgrounds, no emoji. Colour is a second layer over\n * glyphs that already carry the meaning — turning it off must lose nothing.\n */\n\n/** What a piece of output means, not what colour it is. */\nexport type Style =\n /** Coordinates: time, units, rules, column heads. */\n | 'dim'\n /** The data itself. */\n | 'plain'\n /** Cache spans — the one thing 37 white carries. */\n | 'faint'\n /** SQL, and improvements. */\n | 'ok'\n /** Slow, and the context around a finding. */\n | 'warn'\n /** A finding. At most two of these on a screen. */\n | 'warnLoud'\n /** 5xx context, regressions. */\n | 'err'\n /** A 500, and the headline of a failure. */\n | 'errLoud'\n /** A handler span, and any command that can be copied and run. */\n | 'cmd'\n /** Reverse video. One verdict, nowhere else. */\n | 'invert';\n\nconst SGR: Readonly<Record<Style, number>> = {\n dim: 90,\n plain: 39,\n faint: 37,\n ok: 32,\n warn: 33,\n warnLoud: 93,\n err: 31,\n errLoud: 91,\n cmd: 36,\n invert: 7,\n};\n\n/** Things drawn with characters a non-UTF-8 terminal cannot show. */\nexport type GlyphName =\n | 'barFull'\n | 'barSliver'\n | 'bracketOpen'\n | 'bracketClose'\n | 'bracketFill'\n | 'rulerTick'\n | 'ellipsis'\n | 'corner'\n | 'times'\n | 'none';\n\nconst UNICODE: Readonly<Record<GlyphName, string>> = {\n barFull: '█',\n barSliver: '▏',\n bracketOpen: '├',\n bracketClose: '┤',\n bracketFill: '─',\n rulerTick: '┼',\n ellipsis: '…',\n corner: '└',\n times: '×',\n none: '—',\n};\n\n/**\n * ASCII stand-ins.\n *\n * One character each, so no column moves — except the ellipsis, which is\n * three and is accounted for wherever truncation is measured.\n */\nconst ASCII: Readonly<Record<GlyphName, string>> = {\n barFull: '#',\n barSliver: '|',\n bracketOpen: '[',\n bracketClose: ']',\n bracketFill: '-',\n rulerTick: '+',\n ellipsis: '...',\n corner: '\\\\_',\n times: 'x',\n none: '-',\n};\n\n/** How this run draws. */\nexport interface Theme {\n readonly color: boolean;\n readonly unicode: boolean;\n /** Terminal width in columns. */\n readonly width: number;\n paint(style: Style, text: string): string;\n glyph(name: GlyphName): string;\n}\n\n/** What the command line asked for, before the environment is consulted. */\nexport interface ThemeFlags {\n /** `auto` follows the terminal; the other two are the explicit flags. */\n readonly color?: 'auto' | 'always' | 'never';\n readonly ascii?: boolean;\n /** Overrides the detected width. Tests need a stable one. */\n readonly width?: number;\n}\n\n/** The stream a theme is resolved for. */\nexport interface OutputStream {\n readonly isTTY?: boolean;\n readonly columns?: number;\n}\n\n/** Width used when nothing says otherwise. */\nexport const FALLBACK_WIDTH = 80;\n\n/** Start of an SGR sequence, written as an escape so no control byte lives in the source. */\nconst ESC = '\\u001b[';\n\n/**\n * Whether colour is wanted.\n *\n * `NO_COLOR` and `TERM=dumb` are conventions worth honouring even when the\n * output is a terminal; a pipe or a file gets no escape codes at all, so what\n * lands in a log stays greppable.\n */\nfunction wantsColor(env: NodeJS.ProcessEnv, stdout: OutputStream, flags: ThemeFlags): boolean {\n if (flags.color === 'always') return true;\n if (flags.color === 'never') return false;\n if (env['NO_COLOR'] !== undefined && env['NO_COLOR'] !== '') return false;\n if (env['TERM'] === 'dumb') return false;\n return stdout.isTTY === true;\n}\n\n/**\n * Whether the box-drawing characters are safe to use.\n *\n * A locale that names an encoding other than UTF-8 is taken at its word. No\n * locale at all is taken as UTF-8: that is what modern terminals are, and\n * drawing a waterfall out of hyphens because a variable is unset would be a\n * downgrade nobody asked for.\n */\nfunction wantsUnicode(env: NodeJS.ProcessEnv, flags: ThemeFlags): boolean {\n if (flags.ascii) return false;\n if (env['REQRAY_ASCII'] === '1') return false;\n const locale = env['LC_ALL'] ?? env['LC_CTYPE'] ?? env['LANG'];\n if (!locale) return true;\n return /utf-?8/i.test(locale);\n}\n\n/** Resolves how this run draws, once, at startup. */\nexport function resolveTheme(\n env: NodeJS.ProcessEnv,\n stdout: OutputStream,\n flags: ThemeFlags = {},\n): Theme {\n const color = wantsColor(env, stdout, flags);\n const unicode = wantsUnicode(env, flags);\n const glyphs = unicode ? UNICODE : ASCII;\n const columns = Number(env['COLUMNS']);\n const detected =\n Number.isFinite(columns) && columns > 0\n ? Math.floor(columns)\n : (stdout.columns ?? FALLBACK_WIDTH);\n\n return {\n color,\n unicode,\n width: flags.width ?? detected,\n // Whitespace is painted only by reverse video, which is the one style\n // that shows on a space. Everything else would be an escape sequence\n // around nothing — invisible on screen and noise in a pipe.\n paint: (style, text) =>\n color && text.trim() !== '' && style !== 'invert'\n ? `${ESC}${SGR[style]}m${text}${ESC}0m`\n : style === 'invert' && color && text !== ''\n ? `${ESC}${SGR.invert}m${text}${ESC}0m`\n : text,\n glyph: (name) => glyphs[name],\n };\n}\n\n/** A theme for tests and for measuring: no colour, a width that holds still. */\nexport function plainTheme(width = FALLBACK_WIDTH, unicode = true): Theme {\n return resolveTheme({}, {}, { color: 'never', width, ascii: !unicode });\n}\n","/**\n * Command line, parsed.\n *\n * Fifty lines instead of a dependency: an `npx` user waits for every package\n * in the tree, and what this needs — long flags, values attached or separate,\n * one command word — is smaller than the README of anything that would do it\n * for us. `node:util`'s `parseArgs` is close, but its errors are addressed to\n * a programmer and half the work here is the error.\n */\n\nimport { UsageError } from './errors.js';\n\n/**\n * What a flag carries.\n *\n * `list` accumulates — `--method GET --method POST` means both — while\n * `string` takes the last value given, which is what anyone repeating\n * `--url` means. `optional` is for a flag that says one thing on its own and\n * something narrower with a value: `--sql` is every query, `--sql q2` is one.\n */\nexport type FlagKind = 'boolean' | 'string' | 'optional' | 'list';\n\n/** The flags a command accepts. */\nexport type FlagSpec = Readonly<Record<string, FlagKind>>;\n\n/**\n * What the command line said.\n *\n * The command word is picked off before this runs — a parser that also\n * decides which command it is parsing for cannot know which flags are legal.\n */\nexport interface ParsedArgs {\n /** Everything that is not a flag or the value of one. */\n readonly positionals: readonly string[];\n readonly flags: Readonly<Record<string, string | boolean>>;\n}\n\n/** Short forms worth having. Nothing else is abbreviated. */\nconst ALIASES: Readonly<Record<string, string>> = {\n h: 'help',\n V: 'version',\n};\n\n/** Reads `argv`, or explains what is wrong with it. */\nexport function parseArgs(argv: readonly string[], spec: FlagSpec): ParsedArgs {\n const flags: Record<string, string | boolean> = {};\n const positionals: string[] = [];\n\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index] as string;\n\n if (token === '--') {\n positionals.push(...argv.slice(index + 1));\n break;\n }\n\n if (!token.startsWith('-') || token === '-') {\n positionals.push(token);\n continue;\n }\n\n const bare = token.replace(/^--?/, '');\n const equals = bare.indexOf('=');\n const rawName = equals === -1 ? bare : bare.slice(0, equals);\n const name = ALIASES[rawName] ?? rawName;\n const kind = spec[name];\n\n if (kind === undefined) throw unknownFlag(token, spec);\n\n if (kind === 'boolean') {\n if (equals !== -1) {\n throw new UsageError(`${token.split('=')[0]} takes no value`);\n }\n flags[name] = true;\n continue;\n }\n\n const attached = equals === -1 ? undefined : bare.slice(equals + 1);\n const next = argv[index + 1];\n const separate = next !== undefined && !next.startsWith('-') ? next : undefined;\n\n if (kind === 'optional') {\n // Present with no value is an answer in itself, so nothing is required\n // and the next token is only taken when it cannot be anything else.\n if (attached === undefined && separate !== undefined) index++;\n flags[name] = attached ?? separate ?? '';\n continue;\n }\n\n if (attached === undefined && separate !== undefined) index++;\n const value = attached ?? separate;\n if (value === undefined) throw new UsageError(`--${name} needs a value`);\n\n const existing = flags[name];\n flags[name] = kind === 'list' && typeof existing === 'string' ? `${existing},${value}` : value;\n }\n\n return { positionals, flags };\n}\n\n/** An unknown flag, with the nearest thing that would have worked. */\nfunction unknownFlag(token: string, spec: FlagSpec): UsageError {\n const typed = token.replace(/^--?/, '').split('=')[0] ?? '';\n const known = Object.keys(spec).sort();\n const near = known.filter(\n (flag) => flag.startsWith(typed.slice(0, 3)) || typed.startsWith(flag.slice(0, 3)),\n );\n\n const hints = near.length\n ? ['', ` did you mean ${near.map((flag) => `--${flag}`).join(' ')}`]\n : ['', ` flags here ${known.map((flag) => `--${flag}`).join(' ')}`];\n return new UsageError(`unknown flag ${token}`, hints);\n}\n\n/** Reads a flag that must be a string, if it was given at all. */\nexport function stringFlag(args: ParsedArgs, name: string): string | null {\n const value = args.flags[name];\n return typeof value === 'string' ? value : null;\n}\n\n/** Reads a flag that must be a number. */\nexport function numberFlag(args: ParsedArgs, name: string): number | null {\n const raw = stringFlag(args, name);\n if (raw === null) return null;\n const value = Number(raw);\n if (!Number.isFinite(value) || value < 0) {\n throw new UsageError(`--${name} wants a number of milliseconds, not \"${raw}\"`);\n }\n return value;\n}\n\n/** Whether a boolean flag was given. */\nexport function boolFlag(args: ParsedArgs, name: string): boolean {\n return args.flags[name] === true;\n}\n\n/** Splits a comma-separated flag into its parts. */\nexport function listFlag(args: ParsedArgs, name: string): string[] {\n const raw = stringFlag(args, name);\n if (raw === null) return [];\n return raw\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean);\n}\n","/**\n * What every command needs before it can do anything.\n *\n * The address of the panel, the token to get past its gate, and how this run\n * draws. Resolved once, in one place, so `watch` and `show` cannot disagree\n * about where the collector is or whether the terminal takes colour.\n */\n\nimport { boolFlag, type FlagSpec, type ParsedArgs, stringFlag } from './args.js';\nimport { UsageError } from './errors.js';\nimport { resolveTheme, type Theme } from './render/theme.js';\n\n/**\n * Where a locally running application serves its panel.\n *\n * A collector on another machine is an ordinary URL: forward its port over\n * ssh and `--url http://localhost:4300/_reqray` needs nothing else.\n */\nexport const DEFAULT_URL = 'http://localhost:3000/_reqray';\n\n/** The flags every command takes. */\nexport const GLOBAL_FLAGS: FlagSpec = {\n url: 'string',\n token: 'string',\n color: 'string',\n 'no-color': 'boolean',\n ascii: 'boolean',\n verbose: 'boolean',\n help: 'boolean',\n version: 'boolean',\n};\n\n/** Settings shared by every command. */\nexport interface Globals {\n readonly url: string;\n readonly token: string | null;\n readonly verbose: boolean;\n readonly theme: Theme;\n}\n\n/** The environment and streams a run reads. Swapped out in tests. */\nexport interface Environment {\n readonly env: NodeJS.ProcessEnv;\n readonly stdout: { isTTY?: boolean; columns?: number };\n}\n\n/**\n * Normalizes a panel address.\n *\n * A bare origin gets the default mount point: someone who types the address\n * of their application means the panel on it, and answering that with a 404\n * from the application's own router would be a puzzle rather than an error.\n */\nexport function normalizeUrl(raw: string): string {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw new UsageError(`--url wants an address, not \"${raw}\"`, [\n '',\n ` for example ${DEFAULT_URL}`,\n ]);\n }\n\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new UsageError(`--url speaks http or https, not ${parsed.protocol.replace(':', '')}`);\n }\n const path = parsed.pathname.replace(/\\/+$/, '');\n return `${parsed.origin}${path === '' ? '/_reqray' : path}`;\n}\n\n/** Resolves everything shared, from the flags and the environment. */\nexport function resolveGlobals(args: ParsedArgs, runtime: Environment): Globals {\n const url = normalizeUrl(stringFlag(args, 'url') ?? runtime.env['REQRAY_URL'] ?? DEFAULT_URL);\n const token = stringFlag(args, 'token') ?? runtime.env['REQRAY_TOKEN'] ?? null;\n\n const asked = stringFlag(args, 'color');\n if (asked !== null && asked !== 'always' && asked !== 'never' && asked !== 'auto') {\n throw new UsageError(`--color takes auto, always or never, not \"${asked}\"`);\n }\n const color = boolFlag(args, 'no-color') ? 'never' : ((asked ?? 'auto') as 'auto');\n\n return {\n url,\n token,\n verbose: boolFlag(args, 'verbose'),\n theme: resolveTheme(runtime.env, runtime.stdout, { color, ascii: boolFlag(args, 'ascii') }),\n };\n}\n","/**\n * What a command is handed.\n *\n * The same shape for every command, so `top` and `check` land here without\n * anything being rearranged: a client, the resolved globals, the parsed\n * flags, somewhere to write, and one signal that ends everything.\n */\n\nimport type { FlagSpec, ParsedArgs } from '../args.js';\nimport type { ReqrayClient } from '../client.js';\nimport type { Globals } from '../options.js';\n\n/** Where output goes. A test collects the lines; a terminal prints them. */\nexport interface Writer {\n line(text: string): void;\n}\n\n/** Everything a command runs with. */\nexport interface CommandContext {\n readonly client: ReqrayClient;\n readonly globals: Globals;\n readonly args: ParsedArgs;\n readonly out: Writer;\n /** Aborted by Ctrl+C. Every request and the stream carry it. */\n readonly signal: AbortSignal;\n /** The version in the header line. */\n readonly version: string;\n}\n\nexport interface Command {\n readonly name: string;\n /** One line for the usage screen. */\n readonly summary: string;\n /** What this command accepts on top of the global flags. */\n readonly flags: FlagSpec;\n /** @returns the exit code. */\n run(context: CommandContext): Promise<number>;\n}\n\n/** Writes to a stream, one line at a time. */\nexport function streamWriter(stream: { write(chunk: string): unknown }): Writer {\n return {\n line(text) {\n stream.write(`${text}\\n`);\n },\n };\n}\n","/**\n * What the detectors found, and what to do about it.\n *\n * Two levels, and the reason is the two-bright rule: at most the two\n * costliest findings get the loud form — a mark in the gutter, a bright tag,\n * the sample, the callsite and the fix. Everything else is stated quietly.\n * Three alarms on one screen is not a report, it is a siren.\n */\n\nimport type { Finding, RequestDetail } from '@reqray/protocol';\nimport { badgeFor, bytes, share, spanDuration } from './format.js';\nimport type { Theme } from './theme.js';\nimport { pad, padStart } from './width.js';\n\n/** How many findings may shout. */\nconst LOUD = 2;\n/** Below this a finding is real but not worth a mark, ms. */\nconst LOUD_FLOOR_MS = 1;\n/** Right-aligned columns stop here, however wide the terminal is. */\nexport const BLOCK = 100;\n\n/** Loudest first, so a sort can put the worse of two findings above. */\nconst SEVERITY: Record<string, number> = { critical: 2, warn: 1, info: 0 };\n\n/**\n * Findings, worst first.\n *\n * By severity and then by cost, the same order the collector sorts them in.\n * Cost alone was enough while every detector measured its damage in\n * milliseconds; a twelve-megabyte response costs bytes, and it would sort\n * below a duplicate cache read that wasted a third of one.\n */\nexport function ranked(detail: RequestDetail): Finding[] {\n return [...detail.findings].sort(\n (a, b) => (SEVERITY[b.severity] ?? 0) - (SEVERITY[a.severity] ?? 0) || b.costMs - a.costMs,\n );\n}\n\n/**\n * What the finding costs, in whatever it costs.\n *\n * Milliseconds for the detectors that measure time. A response that is too\n * large costs bytes, and printing `0ms` for it would be stating the one\n * number the screen treats as measured, wrongly.\n */\nfunction costOf(finding: Finding): string {\n const evidence = finding.evidence;\n return evidence.kind === 'heavy_response' ? bytes(evidence.bytes) : spanDuration(finding.costMs);\n}\n\n/**\n * The right-hand note: a share of the request, or what the response was.\n *\n * For a heavy response the title already carries the size and the rows, and\n * the content type is the thing it does not say — and the thing the detector's\n * judgement turned on, since a document of this size is a document and a JSON\n * body of it is a mistake.\n */\nfunction noteOf(finding: Finding, durationMs: number): string {\n const evidence = finding.evidence;\n if (evidence.kind !== 'heavy_response') return share(finding.costMs, durationMs);\n return evidence.contentType ?? '';\n}\n\n/** Whether a finding is worth the gutter mark and the loud tag. */\nfunction worthShouting(finding: Finding): boolean {\n // A finding whose cost is not time cannot clear a floor measured in it.\n return finding.evidence.kind === 'heavy_response' || finding.costMs >= LOUD_FLOOR_MS;\n}\n\n/** Where a finding points, as one line of text. */\nfunction where(finding: Finding): string {\n const site = finding.callsite;\n return site ? `${site.relative}:${site.line}` : '';\n}\n\n/** The sample a finding carries, if its evidence has one. */\nfunction sampleOf(finding: Finding): string | null {\n return 'sample' in finding.evidence ? finding.evidence.sample : null;\n}\n\n/** The findings block, heading excluded. */\nexport function findingLines(detail: RequestDetail, theme: Theme): string[] {\n const width = Math.min(theme.width, BLOCK);\n const lines: string[] = [];\n const findings = ranked(detail);\n\n findings.forEach((finding, index) => {\n const loud = index < LOUD && worthShouting(finding);\n const cost = costOf(finding);\n const percent = noteOf(finding, detail.durationMs);\n const tag = badgeFor(finding.detector);\n\n if (index > 0) lines.push('');\n\n if (loud) {\n const head = ` ${theme.paint('warn', '! ')}${theme.paint('warnLoud', pad(tag, 6))}`;\n const title = finding.title;\n const room = width - 10 - 8 - 3 - percent.length;\n lines.push(\n head +\n theme.paint('plain', pad(title, Math.max(10, room))) +\n theme.paint('plain', padStart(cost, 8)) +\n theme.paint('dim', ` ${percent}`),\n );\n\n const sample = sampleOf(finding);\n if (sample) lines.push(theme.paint('plain', ` ${sample}`));\n const site = where(finding);\n if (site) lines.push(theme.paint('dim', ` ${site}`));\n lines.push(theme.paint('dim', ' fix ') + theme.paint('plain', finding.hint));\n return;\n }\n\n // The quiet form: lower case, no gutter, one line of context under it.\n const room = width - 10 - 8;\n lines.push(\n theme.paint(\n 'dim',\n ` ${pad(tag.toLowerCase(), 6)}${pad(finding.title, Math.max(10, room))}`,\n ) + theme.paint('dim', padStart(cost, 8)),\n );\n const context = [sampleOf(finding), where(finding)].filter(Boolean).join(' ');\n if (context) lines.push(theme.paint('dim', ` ${context}`));\n });\n\n return lines.map((line) => line.trimEnd());\n}\n","/**\n * Where the time went, drawn with characters.\n *\n * The bar is the only flexible column; the tag and the label keep their width\n * so the shape of a request is comparable between two terminals. A span\n * shorter than one cell is drawn as a sliver rather than dropped — losing a\n * span is worse than showing it imprecisely.\n *\n * Spans belonging to one N+1 collapse into a single `47× SELECT line_items`,\n * exactly as they do in the panel: forty-seven identical bars are one fact\n * printed forty-seven times.\n */\n\nimport type { RequestDetail, Span } from '@reqray/protocol';\nimport { buildWaterfall as buildBars, type WaterfallBar } from '@reqray/waterfall';\nimport { badgeFor, duration, spanDuration } from './format.js';\nimport type { Style, Theme } from './theme.js';\nimport { cut, pad, padStart } from './width.js';\n\n/** Width of the kind tag, `sql` and friends. */\nconst TAG = 6;\n/** Width of the label column. */\nconst LABEL = 28;\n/** Everything left of the bar: two spaces, the tag, the label, a space. */\nexport const INDENT = 2 + TAG + LABEL + 1;\n/** Bar plus two spaces, the duration and a badge. */\nconst RIGHT = 2 + 7 + 1 + 4;\n\n/** One line of the waterfall. */\nexport interface WaterfallRow {\n readonly tag: string;\n readonly label: string;\n readonly depth: number;\n /** Offset from the request start, ms. */\n readonly startedAt: number;\n readonly duration: number;\n readonly badge: string | null;\n readonly style: Style;\n /** Handler spans are drawn as a bracket: a container, not work. */\n readonly bracket: boolean;\n /**\n * Milliseconds this query queued for a connection before it ran.\n *\n * The panel draws it as a lead-in on the bar. The terminal has one cell to\n * spare, so it says so in the label instead — but it must not simply drop\n * it: a query that took 340 ms because it waited for 338 of them looks\n * exactly like one that worked for 340.\n */\n readonly waitMs: number;\n}\n\n/**\n * How many cells the bar gets at this width.\n *\n * `width - 55` at a glance: the indent, the duration and the badge, plus four\n * columns that stay empty so a badge at the right edge never wraps.\n */\nexport function barCells(width: number): number {\n return Math.max(12, Math.min(60, width - INDENT - RIGHT - 4));\n}\n\nconst KIND_STYLE: Readonly<Record<WaterfallBar['kind'], Style>> = {\n middleware: 'dim',\n handler: 'cmd',\n db: 'ok',\n http: 'warn',\n cache: 'faint',\n // Faint on purpose: a gap is the absence of an answer, and it must not read\n // as louder than the work around it.\n gap: 'faint',\n};\n\nconst KIND_TAG: Readonly<Record<WaterfallBar['kind'], string>> = {\n middleware: 'mw',\n handler: 'fn',\n db: 'sql',\n http: 'http',\n cache: 'cache',\n gap: '—',\n};\n\n/**\n * A query, shortened to what identifies it.\n *\n * The table and the clause that selects inside it are what tell two queries\n * apart at a glance; the column list never is.\n */\nexport function sqlLabel(sql: string): string {\n const flat = sql.replace(/\\s+/g, ' ').trim();\n const select = /^select\\b.*?\\bfrom\\s+([\\w.\"]+)(.*)$/i.exec(flat);\n if (select) return tidy(`SELECT ${table(select[1])}${select[2] ?? ''}`);\n\n const insert = /^insert\\s+into\\s+([\\w.\"]+)/i.exec(flat);\n if (insert) return `INSERT ${table(insert[1])}`;\n\n const update = /^update\\s+([\\w.\"]+)(.*)$/i.exec(flat);\n if (update) return tidy(`UPDATE ${table(update[1])}${update[2] ?? ''}`);\n\n const remove = /^delete\\s+from\\s+([\\w.\"]+)(.*)$/i.exec(flat);\n if (remove) return tidy(`DELETE ${table(remove[1])}${remove[2] ?? ''}`);\n\n return flat;\n}\n\n/** The table name without its schema or quotes. */\nfunction table(name: string | undefined): string {\n return (name ?? '?').replace(/\"/g, '').split('.').pop() ?? '?';\n}\n\n/** Keeps the clause that narrows the query and drops the joins between. */\nfunction tidy(text: string): string {\n const clause = /\\b(where|limit|order by|group by)\\b/i.exec(text);\n const head = clause ? text.slice(0, clause.index).trim() : text.trim();\n const tail = clause ? ` ${text.slice(clause.index).trim()}` : '';\n return `${head}${tail}`.replace(/\\s*=\\s*/g, '=').replace(/\\s+/g, ' ');\n}\n\n/** The label a span carries in the waterfall. */\nexport function labelOf(span: Span): string {\n switch (span.kind) {\n case 'middleware':\n case 'handler':\n return span.label;\n case 'db':\n return sqlLabel(span.sql);\n case 'http': {\n try {\n const url = new URL(span.url);\n return `${url.host} ${url.pathname}`;\n } catch {\n return span.url;\n }\n }\n case 'cache':\n return span.key;\n }\n}\n\n/** Which spans a finding is about, by detector. */\nfunction spanIdsOf(detail: RequestDetail, detector: string): Set<number> {\n const ids = new Set<number>();\n for (const finding of detail.findings) {\n if (finding.detector !== detector) continue;\n for (const id of finding.evidence.spanIds) ids.add(id);\n }\n return ids;\n}\n\n/**\n * The repeats of a duplicated call — every one of them but the first.\n *\n * The first call is the work; the ones after it are what was wasted. Marking\n * all of them would say the request did something wrong twice when it did it\n * once too often.\n */\nfunction repeatsOf(detail: RequestDetail, detectors: readonly string[]): Set<number> {\n const ids = new Set<number>();\n for (const finding of detail.findings) {\n if (!detectors.includes(finding.detector)) continue;\n for (const id of [...finding.evidence.spanIds].sort((a, b) => a - b).slice(1)) ids.add(id);\n }\n return ids;\n}\n\n/** The rows a waterfall is made of. */\nexport function buildWaterfall(detail: RequestDetail, theme: Theme): WaterfallRow[] {\n // Structure from the shared model, words from here: the same request must\n // not show a different number of bars in the terminal and in the panel.\n const duplicated = repeatsOf(detail, ['dup_http', 'dup_cache']);\n const sequential = spanIdsOf(detail, 'sequential_http');\n\n return buildBars(detail).map((bar): WaterfallRow => {\n const label =\n bar.span === null\n ? 'uninstrumented'\n : bar.count > 1\n ? `${bar.count}${theme.glyph('times')} ${labelOf(bar.span)}`\n : labelOf(bar.span);\n\n return {\n tag: KIND_TAG[bar.kind],\n label,\n depth: bar.depth,\n startedAt: bar.startedAt,\n duration: bar.duration,\n badge: badgeOf(bar, duplicated, sequential),\n style: KIND_STYLE[bar.kind],\n bracket: bar.kind === 'handler',\n waitMs: bar.waitMs,\n };\n });\n}\n\n/** What is worth saying about a bar in four columns. */\nfunction badgeOf(\n bar: WaterfallBar,\n duplicated: ReadonlySet<number>,\n sequential: ReadonlySet<number>,\n): string | null {\n if (bar.finding === 'n_plus_one') return 'N+1';\n if (bar.finding !== null) return badgeFor(bar.finding);\n if (bar.span === null) return null;\n if (duplicated.has(bar.span.id)) return 'DUP';\n return sequential.has(bar.span.id) ? badgeFor('sequential_http') : null;\n}\n\n/**\n * One bar.\n *\n * A span narrower than three fifths of a cell becomes a sliver in its own\n * cell; anything wider is rounded to at least two, so a bar always reads as a\n * bar. A bar that would run past the last cell is pulled back rather than\n * clipped — the total is the scale, and nothing may draw outside it.\n */\nexport function barParts(\n startedAt: number,\n length: number,\n total: number,\n cells: number,\n theme: Theme,\n bracket = false,\n): { lead: string; body: string; trail: string } {\n const per = total > 0 ? total / cells : 1;\n let offset = Math.max(0, Math.floor(startedAt / per));\n let width = length / per;\n let body: string;\n\n if (width < 0.6) {\n body = theme.glyph('barSliver');\n width = 1;\n } else {\n width = Math.max(2, Math.round(width));\n body = bracket\n ? theme.glyph('bracketOpen') +\n theme.glyph('bracketFill').repeat(width - 2) +\n theme.glyph('bracketClose')\n : theme.glyph('barFull').repeat(width);\n }\n\n if (offset + width > cells) offset = Math.max(0, cells - width);\n return {\n lead: ' '.repeat(offset),\n body,\n trail: ' '.repeat(Math.max(0, cells - offset - width)),\n };\n}\n\n/** The same bar as one string. The parts exist so only the bar is painted. */\nexport function bar(\n startedAt: number,\n length: number,\n total: number,\n cells: number,\n theme: Theme,\n bracket = false,\n): string {\n const { lead, body, trail } = barParts(startedAt, length, total, cells, theme, bracket);\n return lead + body + trail;\n}\n\n/** The ruler under the scale, and where its ticks sit. */\nexport function ruler(cells: number, theme: Theme): { line: string; ticks: number[] } {\n const inner = Math.max(4, cells - 5);\n const segments = [0, 1, 2, 3].map((index) => Math.floor(inner / 4) + (index < inner % 4 ? 1 : 0));\n\n let line = theme.glyph('bracketOpen');\n const ticks = [0];\n segments.forEach((length, index) => {\n line += theme.glyph('bracketFill').repeat(length);\n line += index === segments.length - 1 ? theme.glyph('bracketClose') : theme.glyph('rulerTick');\n ticks.push(line.length - 1);\n });\n return { line, ticks };\n}\n\n/**\n * The times printed above the ruler.\n *\n * Five of them when they fit, three when they do not, two when even that is\n * too many. A narrow terminal gets a coarser scale rather than five numbers\n * running into each other.\n */\nexport function scale(total: number, ticks: readonly number[], room?: number): string {\n const cells = (ticks[ticks.length - 1] ?? 0) + 1;\n // The scale line carries nothing else, so it may run a little past the\n // ruler — up to the edge of the terminal, which is what `room` is.\n const allowed = Math.max(cells, room ?? cells);\n\n for (const step of [1, 2, 4]) {\n const line = layout(total, ticks, step);\n if (line.length <= allowed) return line;\n }\n // Nothing fits but the total, which is the number the scale is for.\n return padStart(duration(total), cells);\n}\n\n/** Places every `step`-th label along the ruler. */\nfunction layout(total: number, ticks: readonly number[], step: number): string {\n const last = ticks.length - 1;\n let line = '';\n\n ticks.forEach((position, index) => {\n if (index % step !== 0 && index !== last) return;\n const at = (total * index) / last;\n const text = at === 0 ? '0ms' : duration(at);\n const start =\n index === 0\n ? 0\n : index === last\n ? position - text.length + 1\n : position - Math.floor(text.length / 2);\n line += ' '.repeat(Math.max(index === 0 ? 0 : 1, start - line.length)) + text;\n });\n return line;\n}\n\n/** The whole waterfall: scale, ruler, one line per span. */\nexport function waterfallLines(detail: RequestDetail, theme: Theme): string[] {\n const cells = barCells(theme.width);\n const { line, ticks } = ruler(cells, theme);\n const rows = buildWaterfall(detail, theme);\n const total = Math.max(detail.durationMs, ...rows.map((row) => row.startedAt + row.duration));\n\n const lines = [\n theme.paint('dim', ' '.repeat(INDENT) + scale(total, ticks, theme.width - INDENT)),\n theme.paint('dim', ' '.repeat(INDENT) + line),\n ];\n\n for (const row of rows) {\n // A query that took 340 ms because it queued for 338 of them looks exactly\n // like one that worked for 340. The panel draws the wait as a lead-in on\n // the bar; a terminal has no room for that, so it says it in words.\n const waited = row.waitMs >= 1 ? ` (${spanDuration(row.waitMs)} queued)` : '';\n const label = cut(\n ' '.repeat(row.depth * 2) + row.label + waited,\n LABEL,\n theme.glyph('ellipsis'),\n );\n const drawn = barParts(row.startedAt, row.duration, total, cells, theme, row.bracket);\n lines.push(\n theme.paint('dim', ` ${pad(row.tag, TAG)}`) +\n theme.paint(row.tag === 'mw' ? 'dim' : 'plain', pad(label, LABEL)) +\n ' ' +\n drawn.lead +\n theme.paint(row.style, drawn.body) +\n drawn.trail +\n ' ' +\n theme.paint('plain', padStart(spanDuration(row.duration), 7)) +\n ' ' +\n (row.badge ? theme.paint(row.badge === 'N+1' ? 'warnLoud' : 'warn', row.badge) : ''),\n );\n }\n return lines.map((entry) => entry.trimEnd());\n}\n","/**\n * One request, whole.\n *\n * Waterfall, then findings, then the response. The order is the reading\n * order: where the time went, what to do about it, and what came back. Each\n * block is a heading in the left margin and its summary in one column, so the\n * three read as a table when they are scrolled past.\n */\n\nimport type { BaselineResponse, RequestDetail } from '@reqray/protocol';\nimport { findingLines } from './findings.js';\nimport { bytes, clock, duration } from './format.js';\nimport { frameOf } from './row.js';\nimport type { Theme } from './theme.js';\nimport { waterfallLines } from './waterfall.js';\nimport { cut } from './width.js';\n\n/** Where a block's summary starts. */\nconst SUMMARY = 31;\n/**\n * Below this the loop was on time and saying so is noise: one sampling\n * interval of lateness is the measurement's granularity, not an event.\n */\nconst LOOP_WORTH_SAYING = 15;\n/** Right-aligned columns stop here, however wide the terminal is. */\nconst BLOCK = 100;\n\n/** A block heading: a word in the margin, the numbers beside it. */\nfunction heading(label: string, summary: string, theme: Theme): string {\n const left = ` ${label}`;\n return theme.paint('dim', left + ' '.repeat(Math.max(2, SUMMARY - left.length)) + summary);\n}\n\n/** The line that says which request this is. */\nexport function detailHeader(detail: RequestDetail, theme: Theme): string {\n const status = statusStyle(detail.status);\n const from = detail.test ? ` from ${detail.test}` : '';\n return (\n theme.paint('plain', ` ${detail.method} ${detail.path}`) +\n theme.paint(status, ` ${detail.status}`) +\n theme.paint('plain', ` ${duration(detail.durationMs)}`) +\n theme.paint('dim', ` ${clock(detail.startedAt)} #${detail.id}${from}`)\n );\n}\n\nfunction statusStyle(status: number): 'dim' | 'warn' | 'errLoud' {\n if (status >= 500) return 'errLoud';\n if (status >= 400) return 'warn';\n return 'dim';\n}\n\n/**\n * Where the time went, and whether this call was unusual.\n *\n * Two facts the duration cannot carry on its own: which layer spent it, and\n * whether spending that much is normal for this route. Both are read off the\n * record — the arithmetic happens in the collector, so this line and the\n * panel's cannot drift apart.\n */\nexport function timingLines(\n detail: RequestDetail,\n compared: BaselineResponse,\n theme: Theme,\n): string[] {\n const timing = detail.timing;\n if (!timing) return [];\n\n // A layer that cost nothing is left out rather than printed as zero.\n const waited: Array<[string, number]> = (\n [\n ['sql', timing.sqlMs],\n ['external', timing.externalMs],\n ['cache', timing.cacheMs],\n ] as Array<[string, number]>\n ).filter(([, ms]) => ms >= 0.05);\n const own: Array<[string, number]> = timing.selfMs >= 0.05 ? [['your code', timing.selfMs]] : [];\n\n // The loop, when it was behind far enough for the granularity not to be\n // the story. A property of the process, and the wording says so.\n const loopText =\n detail.host && detail.host.loopMaxMs >= LOOP_WORTH_SAYING\n ? ` loop behind ${duration(detail.host.loopMaxMs)}`\n : '';\n const parallelText = timing.parallel ? ' (overlapping)' : '';\n\n // What the layers have left after the notes have taken their share: the\n // note is the news, and the layer it displaces is the one nobody was going\n // to read anyway.\n const full = Math.min(theme.width, BLOCK) - SUMMARY;\n const line = (shown: ReadonlyArray<[string, number]>): string =>\n [\n duration(detail.durationMs),\n ...shown.map(([label, ms]) => `${duration(ms)} ${label}`),\n ...own.map(([label, ms]) => `${duration(ms)} ${label}`),\n ].join(' ');\n\n // A narrow screen gives up the cheapest layer it waited on first — never\n // the total, and never the application's own time, which is the one figure\n // here that nothing else on the screen carries and the only one the reader\n // can go and change.\n const fit = (room: number): Array<[string, number]> => {\n let shown = waited;\n while (shown.length > 1 && line(shown).length > room) {\n const cheapest = shown.reduce((least, part) => (part[1] < least[1] ? part : least));\n shown = shown.filter((part) => part !== cheapest);\n }\n return shown;\n };\n\n // The notes go before the last layer does. A line reading \"94ms · 36ms your\n // code · loop behind 45ms\" has quietly dropped the 58 ms of SQL that was the\n // largest thing in the request, which is not a summary of anything.\n let notes = parallelText + loopText;\n let shown = fit(full - notes.length);\n if (line(shown).length > full - notes.length) {\n notes = '';\n shown = fit(full);\n }\n const summary = line(shown);\n\n const lines = [\n heading('TIME', summary, theme) +\n theme.paint('dim', notes.includes('(overlapping)') ? parallelText : '') +\n theme.paint('warn', notes.includes('loop behind') ? loopText : ''),\n ];\n const { baseline, pressure } = compared;\n if (baseline) {\n lines.push(\n theme.paint(\n baseline.verdict === 'slower' ? 'warn' : 'dim',\n ' '.repeat(SUMMARY) + verdictOf(baseline),\n ),\n );\n }\n if (pressure) {\n // Said as a property of the process, never of this request: what follows\n // is the route's own calls compared against themselves.\n const calls = pressure.elevated.calls + pressure.normal.calls;\n const slower = `${pressure.ratio.toFixed(1)}× slower`;\n const forms = [\n `when the loop was over ${duration(pressure.cutoffMs)} behind, this route's p95 was ${slower} — ${Math.round(pressure.share)}% of ${calls} calls`,\n `loop over ${duration(pressure.cutoffMs)} behind → p95 ${slower} on ${Math.round(pressure.share)}% of ${calls} calls`,\n `loop over ${duration(pressure.cutoffMs)} → p95 ${slower} (${Math.round(pressure.share)}%)`,\n ];\n const fits = forms.find((form) => form.length <= full) ?? (forms.at(-1) as string);\n lines.push(theme.paint('dim', ' '.repeat(SUMMARY) + fits));\n }\n return lines;\n}\n\n/** The verdict as a sentence, with the sample it rests on. */\nfunction verdictOf(baseline: NonNullable<BaselineResponse['baseline']>): string {\n const of = `${baseline.samples} call${baseline.samples === 1 ? '' : 's'} to ${baseline.route}`;\n if (baseline.verdict === 'slower') return `slower than 95% of ${of}`;\n if (baseline.verdict === 'faster') return `faster than the average of ${of}`;\n return `typical for this route, over ${of}`;\n}\n\n/** How many spans the waterfall stands for, and what is odd about them. */\nfunction spanSummary(detail: RequestDetail): string {\n // Counted the way the waterfall badges them: every repeat but the first.\n const duplicated = new Set<number>();\n for (const finding of detail.findings) {\n if (finding.detector === 'dup_http' || finding.detector === 'dup_cache') {\n for (const id of [...finding.evidence.spanIds].sort((a, b) => a - b).slice(1)) {\n duplicated.add(id);\n }\n }\n }\n const parts = [`${detail.spans.length} spans`];\n if (duplicated.size > 0) parts.push(`${duplicated.size} of them duplicated`);\n if (detail.droppedSpans > 0) parts.push(`${detail.droppedSpans} dropped`);\n return parts.join(', ');\n}\n\n/** Status, type, size and etag — what the response was, in one line. */\nfunction responseSummary(detail: RequestDetail, theme: Theme): string {\n const headers = detail.responseHeaders;\n const type = headers['content-type']?.split(';')[0];\n const length = Number(headers['content-length'] ?? Number.NaN);\n const size = Number.isFinite(length)\n ? bytes(length)\n : detail.responseBody\n ? bytes(Buffer.byteLength(detail.responseBody.text))\n : null;\n\n // Rows sit next to the size on purpose: a small response built out of a\n // hundred thousand rows is a different mistake from a large one.\n const rows = detail.weight?.rows ? `${detail.weight.rows.toLocaleString('en-US')} rows` : null;\n const parts = [\n String(detail.status),\n type,\n size,\n rows,\n headers['etag'] ? `etag ${headers['etag']}` : null,\n ];\n return cut(\n parts.filter(Boolean).join(' '),\n Math.min(theme.width, BLOCK) - SUMMARY - 1,\n theme.glyph('ellipsis'),\n );\n}\n\n/** The response block: the summary line, timings, and the body's first line. */\nexport function responseLines(detail: RequestDetail, theme: Theme): string[] {\n const lines = [heading('RESPONSE', responseSummary(detail, theme), theme)];\n const timing = detail.responseHeaders['server-timing'];\n if (timing) {\n lines.push(theme.paint('dim', ` server-timing ${timing.split(/,\\s*/).join(' ')}`));\n }\n if (detail.responseBody) {\n const room = Math.min(theme.width, BLOCK) - 16;\n const body = detail.responseBody.text.replace(/\\s+/g, ' ').trim();\n lines.push(\n theme.paint('dim', ' body ') +\n theme.paint('plain', cut(body, room, theme.glyph('ellipsis'))),\n );\n }\n if (detail.error) {\n lines.push(\n '',\n theme.paint('err', ` ${detail.error.name}`) +\n theme.paint('dim', `: ${detail.error.message}`),\n );\n const frame = frameOf(detail.error.stack);\n if (frame) lines.push(theme.paint('dim', ` ${frame}`));\n }\n return lines;\n}\n\n/** What else can be asked about this request. */\nexport function trailingCommands(detail: RequestDetail, theme: Theme): string[] {\n const queries = detail.sqlCount;\n const commands: Array<[string, string]> = [];\n if (detail.responseBody) {\n commands.push([`reqray show ${detail.id} --body`, 'the whole response body']);\n }\n if (queries > 0) {\n commands.push([\n `reqray show ${detail.id} --sql`,\n queries === 1\n ? 'the query it ran, and where from'\n : `all ${queries} queries with their callsites`,\n ]);\n }\n\n const column = Math.max(...commands.map(([command]) => command.length), 0) + 8;\n return commands.map(\n ([command, note]) =>\n theme.paint('cmd', ` ${command}`) +\n theme.paint('dim', ' '.repeat(Math.max(2, column - command.length)) + note),\n );\n}\n\n/** The whole screen. */\nexport function detailScreen(\n detail: RequestDetail,\n theme: Theme,\n compared: BaselineResponse = { baseline: null, pressure: null },\n): string[] {\n const lines = [detailHeader(detail, theme), ''];\n\n const timing = timingLines(detail, compared, theme);\n if (timing.length > 0) lines.push(...timing, '');\n\n if (detail.spans.length > 0) {\n lines.push(heading('WATERFALL', spanSummary(detail), theme));\n lines.push(...waterfallLines(detail, theme));\n lines.push('');\n }\n\n if (detail.findings.length > 0) {\n lines.push(heading('FINDINGS', String(detail.findings.length), theme), '');\n lines.push(...findingLines(detail, theme));\n lines.push('');\n }\n\n lines.push(...responseLines(detail, theme));\n\n const trailing = trailingCommands(detail, theme);\n if (trailing.length > 0) lines.push('', ...trailing);\n return lines;\n}\n","/**\n * Every query the request ran.\n *\n * SQL is wrapped rather than truncated: a path can be recognised from a\n * fragment and a query cannot. Wrapping is capped at three lines, and the\n * line that says how many are left ends in the command that shows them —\n * truncation without a way out is a dead end.\n */\n\nimport type { DbSpan, RequestDetail } from '@reqray/protocol';\nimport { spanDuration } from './format.js';\nimport type { Theme } from './theme.js';\nimport { pad } from './width.js';\n\n/** How many lines of one query are printed before the rest is behind a flag. */\nconst MAX_LINES = 3;\n/** The hanging indent a wrapped query lines up under. */\nconst HANG = 7;\n/** Right-aligned columns stop here, however wide the terminal is. */\nconst BLOCK = 100;\n\n/** One query, or one group of identical ones. */\nexport interface QueryEntry {\n /** How it is referred to on the command line: `q2`. */\n readonly ref: string;\n readonly sql: string;\n readonly totalMs: number;\n /** How many times it ran. More than one means a loop. */\n readonly calls: number;\n readonly rows: number | null;\n readonly callsite: string | null;\n /** Set when the group is what a detector flagged. */\n readonly badge: string | null;\n}\n\nconst isDb = (span: { kind: string }): span is DbSpan => span.kind === 'db';\n\n/**\n * The queries of a request, in the order they ran.\n *\n * Identical queries flagged as an N+1 are one entry: the point of the screen\n * is which queries the request ran, and forty-seven copies of one of them is\n * a single answer.\n */\nexport function queriesOf(detail: RequestDetail): QueryEntry[] {\n const looped = new Set<number>();\n for (const finding of detail.findings) {\n if (finding.detector !== 'n_plus_one') continue;\n for (const id of finding.evidence.spanIds) looped.add(id);\n }\n\n const entries: QueryEntry[] = [];\n let loopDone = false;\n\n for (const span of detail.spans.filter(isDb)) {\n if (looped.has(span.id)) {\n if (loopDone) continue;\n loopDone = true;\n const group = detail.spans.filter((entry) => isDb(entry) && looped.has(entry.id)) as DbSpan[];\n entries.push({\n ref: `q${entries.length + 1}`,\n sql: span.sql,\n totalMs: group.reduce((sum, entry) => sum + entry.duration, 0),\n calls: group.length,\n rows: span.rowCount,\n callsite: siteOf(span),\n badge: 'N+1',\n });\n continue;\n }\n\n entries.push({\n ref: `q${entries.length + 1}`,\n sql: span.sql,\n totalMs: span.duration,\n calls: 1,\n rows: span.rowCount,\n callsite: siteOf(span),\n badge: null,\n });\n }\n return entries;\n}\n\nfunction siteOf(span: DbSpan): string | null {\n return span.callsite ? `${span.callsite.relative}:${span.callsite.line}` : null;\n}\n\nconst KEYWORDS =\n /^(SELECT|FROM|WHERE|INNER|OUTER|LEFT|RIGHT|JOIN|ON|AND|OR|ORDER|GROUP|BY|LIMIT|OFFSET|IN|AS|COUNT|SUM|AVG|MIN|MAX|NOT|NULL|IS|DESC|ASC|INSERT|INTO|VALUES|UPDATE|SET|DELETE|RETURNING|DISTINCT|HAVING|WITH|CASE|WHEN|THEN|ELSE|END)$/i;\n\n/**\n * Paints one line of SQL.\n *\n * Keywords cyan, literals and placeholders green — the same two colours the\n * panel uses, and the only place in this client where colour is applied\n * inside a line rather than to a column.\n */\nexport function paintSql(line: string, theme: Theme): string {\n return line\n .split(/(\\s+|,|\\(|\\))/)\n .filter((token) => token !== '')\n .map((token) => {\n const bare = token.trim();\n if (!bare) return token;\n if (KEYWORDS.test(bare)) return theme.paint('cmd', token);\n if (/^'.*'$/.test(bare) || /^\\$\\d+$/.test(bare) || /^\\d+$/.test(bare)) {\n return theme.paint('ok', token);\n }\n return theme.paint('plain', token);\n })\n .join('');\n}\n\n/** Breaks a query into lines that fit, on whitespace. */\nexport function wrapSql(sql: string, width: number): string[] {\n const words = sql.replace(/\\s+/g, ' ').trim().split(' ');\n const lines: string[] = [];\n let current = '';\n\n for (const word of words) {\n if (current === '') current = word;\n else if (current.length + 1 + word.length <= width) current += ` ${word}`;\n else {\n lines.push(current);\n current = word;\n }\n }\n if (current !== '') lines.push(current);\n return lines;\n}\n\n/** The `--sql` screen. */\nexport function sqlLines(\n detail: RequestDetail,\n theme: Theme,\n options: { only?: string | null; full?: boolean } = {},\n): string[] {\n const entries = queriesOf(detail);\n const asked = options.only?.toLowerCase() ?? null;\n const wanted = asked ? entries.filter((entry) => entry.ref === asked) : entries;\n\n if (entries.length === 0) {\n return [theme.paint('plain', ' this request ran no queries')];\n }\n if (wanted.length === 0) {\n return [\n theme.paint('plain', ` no query called ${options.only} in this request`),\n theme.paint('dim', ` it has ${entries.length}: ${entries.map((e) => e.ref).join(' ')}`),\n ];\n }\n\n const width = Math.max(20, Math.min(theme.width, BLOCK) - HANG - 1);\n const lines: string[] = [];\n\n wanted.forEach((entry, index) => {\n if (index > 0) lines.push('');\n\n // Built twice on purpose: once plain to measure, once painted to print.\n // Measuring painted text means measuring escape sequences.\n const cells: Array<[string, (text: string) => string]> = [\n [entry.badge ? '! ' : ' ', (text) => theme.paint('warn', text)],\n [pad(entry.ref, 5), (text) => theme.paint('dim', text)],\n [pad(spanDuration(entry.totalMs), 8), (text) => theme.paint('plain', text)],\n [\n pad(entry.calls > 1 ? `${entry.calls} calls` : rowsOf(entry), 12),\n (t) => theme.paint('dim', t),\n ],\n [entry.callsite ?? '', (text) => theme.paint('dim', text)],\n ];\n const plain = cells\n .map(([text]) => text)\n .join('')\n .trimEnd();\n let head = cells\n .map(([text, paint]) => paint(text))\n .join('')\n .trimEnd();\n\n if (entry.badge) {\n const gap = Math.max(3, Math.min(theme.width, BLOCK) - plain.length - entry.badge.length - 1);\n head += ' '.repeat(gap) + theme.paint('warnLoud', entry.badge);\n }\n lines.push(head, '');\n\n const wrapped = wrapSql(entry.sql, width);\n const shown = options.full ? wrapped : wrapped.slice(0, MAX_LINES);\n for (const line of shown) lines.push(' '.repeat(HANG) + paintSql(line, theme));\n\n const rest = wrapped.length - shown.length;\n if (rest > 0) {\n const tail = `${' '.repeat(HANG)}${theme.glyph('ellipsis')} ${rest} more lines`;\n const command = `reqray show ${detail.id} --sql ${entry.ref} --full`;\n const gap = Math.max(3, Math.min(theme.width, BLOCK) - tail.length - command.length - 1);\n lines.push(theme.paint('dim', tail) + ' '.repeat(gap) + theme.paint('cmd', command));\n }\n });\n\n return lines.map((line) => line.trimEnd());\n}\n\n/** `25 rows`, or nothing when the driver did not say. */\nfunction rowsOf(entry: QueryEntry): string {\n return entry.rows === null ? '' : `${entry.rows} rows`;\n}\n","/**\n * `reqray show` — one request, whole.\n *\n * Either by id, or by a question: the last one, the last one that failed, the\n * slowest. The question is asked of the server rather than answered here —\n * \"the slowest request\" over a history on disk is not something a client can\n * work out from a page of it.\n */\n\nimport type { RequestDetail } from '@reqray/protocol';\nimport { boolFlag, type FlagSpec, stringFlag } from '../args.js';\nimport type { ListQuery } from '../client.js';\nimport { EXIT_OK, UsageError } from '../errors.js';\nimport { detailScreen } from '../render/detail.js';\nimport { sqlLines } from '../render/sql.js';\nimport type { Command, CommandContext } from './context.js';\n\nconst FLAGS: FlagSpec = {\n last: 'boolean',\n failed: 'boolean',\n slowest: 'boolean',\n path: 'string',\n json: 'boolean',\n body: 'boolean',\n sql: 'optional',\n full: 'boolean',\n};\n\n/**\n * `--sql` with no reference means all of them.\n *\n * The flag takes a value, so a bare `--sql` would swallow whatever came next;\n * an empty string is how \"no reference given\" arrives here.\n */\nfunction sqlRef(context: CommandContext): string | null | undefined {\n const raw = stringFlag(context.args, 'sql');\n if (raw === null) return undefined;\n return raw.trim() === '' ? null : raw.trim();\n}\n\nexport const show: Command = {\n name: 'show',\n summary: 'one request, whole',\n flags: FLAGS,\n\n async run(context): Promise<number> {\n const { client, globals, out, signal } = context;\n const id = await resolveId(context);\n if (id === null) return EXIT_OK;\n\n if (boolFlag(context.args, 'json')) {\n out.line(await client.detailRaw(id, signal));\n return EXIT_OK;\n }\n\n const detail = await client.detail(id, signal);\n\n if (boolFlag(context.args, 'body')) {\n out.line(bodyOf(detail));\n return EXIT_OK;\n }\n\n const ref = sqlRef(context);\n if (ref !== undefined) {\n const lines = sqlLines(detail, globals.theme, {\n only: ref,\n full: boolFlag(context.args, 'full'),\n });\n for (const line of lines) out.line(line);\n return EXIT_OK;\n }\n\n // Asked for after the request itself, and allowed to come back empty: a\n // verdict is worth printing when there is one and worth no words when\n // there is not.\n const compared = await client.baseline(id, signal);\n for (const line of detailScreen(detail, globals.theme, compared)) out.line(line);\n return EXIT_OK;\n },\n};\n\n/**\n * What `--path` searches for.\n *\n * A substring rather than a glob, because the store is what searches: asking\n * the collector \"the last request whose path contains this\" is one question\n * with one true answer, where matching a glob here would mean \"the last one\n * among however many rows happened to come back\". Surrounding `*` is dropped\n * so a glob typed out of habit still means what it looks like.\n */\nfunction pathQuery(context: CommandContext): string | null {\n const raw = stringFlag(context.args, 'path');\n if (raw === null) return null;\n const trimmed = raw.replace(/^\\*+/, '').replace(/\\*+$/, '').trim();\n if (trimmed === '') {\n throw new UsageError('--path wants something to look for, not just a wildcard');\n }\n return trimmed;\n}\n\n/** The response body as it was recorded, truncation noted. */\nfunction bodyOf(detail: RequestDetail): string {\n if (!detail.responseBody) return 'this request recorded no response body';\n const { text, truncated } = detail.responseBody;\n return truncated ? `${text}\\n… cut at the recorded limit` : text;\n}\n\n/** The forms `show` takes, printed whenever it is asked for one it has not. */\nconst FORMS = [\n '',\n ' reqray show 8974 that request',\n ' reqray show --last the one that just finished',\n ' reqray show --last --failed the last one that failed',\n ' reqray show --last --slowest the slowest one recorded',\n ' reqray show --last --path /orders the last one to a path',\n '',\n ' reqray watch --ids prints the identifier of every row',\n];\n\n/**\n * Which request to show.\n *\n * `null` means the collector answered and had nothing — not an error, so it\n * is said plainly and the command succeeds.\n */\nasync function resolveId(context: CommandContext): Promise<string | null> {\n const { args, client, out, globals, signal } = context;\n const given = args.positionals[0];\n const failed = boolFlag(args, 'failed');\n const slowest = boolFlag(args, 'slowest');\n const path = pathQuery(context);\n const last = boolFlag(args, 'last') || failed || slowest || path !== null;\n\n if (given && last) {\n throw new UsageError('give show an id or a question, not both', FORMS);\n }\n if (given) return given;\n if (!last) {\n throw new UsageError('show needs an id, or a question to ask instead', FORMS);\n }\n\n const query: ListQuery = {\n limit: 1,\n ...(failed ? { onlyErrors: true } : {}),\n ...(slowest ? { sort: 'slowest' as const } : {}),\n ...(path ? { query: path } : {}),\n };\n const page = await client.list(query, signal);\n const row = page.requests[0];\n if (row) return row.id;\n\n const what = path\n ? `nothing recorded matches \"${path}\"`\n : failed\n ? 'no request has failed yet'\n : 'nothing has been recorded yet';\n out.line(globals.theme.paint('plain', ` ${what}`));\n out.line(\n globals.theme.paint(\n 'dim',\n ' the panel is attached and answering — it just has nothing to show',\n ),\n );\n return null;\n}\n","/**\n * `reqray watch` — the stream.\n *\n * `tail -f` for requests: one line each, as they finish. Everything that\n * narrows it is decided here rather than by the server, because the stream\n * endpoint sends every request and takes no parameters — the same arrangement\n * the web panel's own feed runs on.\n *\n * A request that failed gets a second line with the exception on it. That\n * needs the record rather than the row, so it is fetched — with a short\n * deadline, because a stream that stalls waiting for a detail is worse than\n * one that admits it could not get it.\n */\n\nimport type { RequestDetail, RequestRow } from '@reqray/protocol';\nimport { boolFlag, type FlagSpec, listFlag, numberFlag, stringFlag } from '../args.js';\nimport { EXIT_OK } from '../errors.js';\nimport type { StreamFilter } from '../filter.js';\nimport { matches } from '../filter.js';\nimport { failureLines, streamHead, streamRow } from '../render/row.js';\nimport { emptyState, header, noticeLine } from '../render/screens.js';\nimport type { Command, CommandContext } from './context.js';\n\n/** How long a failed row may hold the stream while its detail is fetched. */\nconst DETAIL_TIMEOUT_MS = 1_000;\n\nconst FLAGS: FlagSpec = {\n ids: 'boolean',\n 'slower-than': 'string',\n status: 'list',\n method: 'list',\n path: 'string',\n 'findings-only': 'boolean',\n};\n\n/** Reads the flags that narrow the stream. */\nexport function filterFrom(context: CommandContext): StreamFilter {\n return {\n slowerThanMs: numberFlag(context.args, 'slower-than'),\n statuses: listFlag(context.args, 'status'),\n methods: listFlag(context.args, 'method'),\n path: stringFlag(context.args, 'path'),\n findingsOnly: boolFlag(context.args, 'findings-only'),\n };\n}\n\nexport const watch: Command = {\n name: 'watch',\n summary: 'follow requests as they happen',\n flags: FLAGS,\n\n async run(context): Promise<number> {\n const { client, globals, out, signal } = context;\n const filter = filterFrom(context);\n\n // Asked first, and deliberately: this is the request that finds out the\n // collector is not there, while there is still nothing on screen to\n // interrupt.\n const meta = await client.meta(signal);\n for (const line of header(context.version, globals.url, meta, globals.theme)) out.line(line);\n\n // The identifier is a handle, not information, so it is printed only when\n // asked for — but without it a row on screen cannot be opened.\n const ids = { ids: boolFlag(context.args, 'ids') };\n\n const recorded = await client.list({ limit: 1 }, signal);\n let headPrinted = false;\n if (recorded.requests.length === 0) {\n for (const line of emptyState(globals.url, meta, globals.theme)) out.line(line);\n } else {\n out.line(streamHead(globals.theme, ids));\n headPrinted = true;\n }\n\n /** Rows are printed one at a time, in the order they arrived. */\n let printing: Promise<void> = Promise.resolve();\n\n await client.stream({\n signal,\n onNotice: (text) => {\n printing = printing.then(() => {\n out.line(noticeLine(text, globals.theme));\n });\n },\n onRow: (payload) => {\n const row = payload as RequestRow;\n if (!matches(row, filter)) return;\n\n printing = printing.then(async () => {\n if (!headPrinted) {\n out.line('');\n out.line(streamHead(globals.theme, ids));\n headPrinted = true;\n }\n out.line(streamRow(row, globals.theme, ids));\n if (!row.hasError) return;\n\n const detail = await detailFor(context, row);\n for (const line of failureLines(row, detail, globals.theme)) out.line(line);\n });\n },\n });\n\n await printing;\n return EXIT_OK;\n },\n};\n\n/**\n * The record behind a failed row, if it can be had quickly.\n *\n * `null` rather than an error: the exception type is a nicety, and the row\n * itself has already said the request failed.\n */\nasync function detailFor(context: CommandContext, row: RequestRow): Promise<RequestDetail | null> {\n const timeout = AbortSignal.timeout(DETAIL_TIMEOUT_MS);\n const signal = AbortSignal.any([context.signal, timeout]);\n try {\n return await context.client.detail(row.id, signal);\n } catch {\n return null;\n }\n}\n","/**\n * The commands this client has.\n *\n * A list rather than a switch: the usage screen is generated from it, and a\n * new command is one entry plus a file.\n */\n\nimport type { Command } from './context.js';\nimport { show } from './show.js';\nimport { watch } from './watch.js';\n\nexport const COMMANDS: readonly Command[] = [watch, show];\n\n/** The command with this name, or `null`. */\nexport function commandNamed(name: string): Command | null {\n return COMMANDS.find((command) => command.name === name) ?? null;\n}\n\nexport type { Command, CommandContext, Writer } from './context.js';\n","/**\n * The version in the header line.\n *\n * Read from the manifest rather than baked in by the build, so a copy running\n * from source says the same thing as one installed from npm.\n */\n\nimport { readFileSync } from 'node:fs';\n\nlet cached: string | null = null;\n\n/** This package's version, or `0.0.0` if the manifest cannot be read. */\nexport function cliVersion(): string {\n if (cached !== null) return cached;\n try {\n const manifest = readFileSync(new URL('../package.json', import.meta.url), 'utf8');\n cached = (JSON.parse(manifest) as { version?: string }).version ?? '0.0.0';\n } catch {\n cached = '0.0.0';\n }\n return cached;\n}\n","/**\n * One run of the client.\n *\n * Separated from the executable so a test can run a whole command — argv in,\n * lines and an exit code out — without a subprocess and without the signal\n * handling that only makes sense around a real process.\n */\n\nimport { parseArgs } from './args.js';\nimport { ReqrayClient } from './client.js';\nimport { streamWriter } from './commands/context.js';\nimport { COMMANDS, commandNamed } from './commands/index.js';\nimport { CliError, EXIT_FAILED, EXIT_OK, EXIT_USAGE, UsageError } from './errors.js';\nimport { DEFAULT_URL, GLOBAL_FLAGS, resolveGlobals } from './options.js';\nimport { renderFailure } from './render/screens.js';\nimport { resolveTheme } from './render/theme.js';\nimport { MIN_WIDTH } from './render/width.js';\nimport { cliVersion } from './version.js';\n\n/** The process a run reads and writes. */\nexport interface Runtime {\n readonly env: NodeJS.ProcessEnv;\n readonly stdout: { isTTY?: boolean; columns?: number; write(chunk: string): unknown };\n readonly stderr: { write(chunk: string): unknown };\n /** Aborted on Ctrl+C. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Runs one command.\n *\n * @returns the exit code. Failures are printed here and never thrown at the\n * caller: an exception reaching a terminal is a stack trace, and a stack\n * trace is what a tool prints when it has nothing useful to say.\n */\nexport async function run(argv: readonly string[], runtime: Runtime): Promise<number> {\n const version = cliVersion();\n const out = streamWriter(runtime.stdout);\n const errors = streamWriter(runtime.stderr);\n\n try {\n const first = argv[0];\n\n if (first === undefined || first === '--help' || first === '-h') {\n for (const line of usage(version, runtime)) out.line(line);\n return first === undefined ? EXIT_USAGE : EXIT_OK;\n }\n if (first === '--version' || first === '-V') {\n out.line(version);\n return EXIT_OK;\n }\n if (first.startsWith('-')) {\n throw new UsageError(`reqray needs a command before ${first}`, [\n '',\n ` commands ${COMMANDS.map((command) => command.name).join(' ')}`,\n ]);\n }\n\n const command = commandNamed(first);\n if (!command) {\n throw new UsageError(`there is no command called \"${first}\"`, [\n '',\n ` commands ${COMMANDS.map((entry) => entry.name).join(' ')}`,\n ]);\n }\n\n const args = parseArgs(argv.slice(1), { ...GLOBAL_FLAGS, ...command.flags });\n if (args.flags['help'] === true) {\n for (const line of usage(version, runtime)) out.line(line);\n return EXIT_OK;\n }\n\n const globals = resolveGlobals(args, runtime);\n // A grid cannot be drawn narrower than this, and a wrapped grid is worse\n // than an explanation.\n if (globals.theme.width < MIN_WIDTH && args.flags['json'] !== true) {\n throw new UsageError(\n `this terminal is ${globals.theme.width} columns wide; reqray needs ${MIN_WIDTH}`,\n ['', ' widen the window, or pipe the output somewhere that has room'],\n );\n }\n\n const client = new ReqrayClient({ url: globals.url, token: globals.token });\n return await command.run({\n client,\n globals,\n args,\n out,\n version,\n signal: runtime.signal ?? new AbortController().signal,\n });\n } catch (error) {\n if (isAbort(error)) return EXIT_OK;\n const theme = resolveTheme(runtime.env, runtime.stderr as { isTTY?: boolean });\n for (const line of renderFailure(error, theme, argv.includes('--verbose'))) errors.line(line);\n return error instanceof CliError ? error.exitCode : EXIT_FAILED;\n }\n}\n\n/** Ctrl+C, not a failure. */\nfunction isAbort(error: unknown): boolean {\n return error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');\n}\n\n/** The usage screen, built from the command list. */\nfunction usage(version: string, runtime: Runtime): string[] {\n const theme = resolveTheme(runtime.env, runtime.stdout);\n const command = (name: string, summary: string) =>\n theme.paint('cmd', ` reqray ${name}`.padEnd(22)) + theme.paint('dim', summary);\n const flag = (name: string, summary: string) =>\n theme.paint('dim', ` ${name.padEnd(20)}${summary}`);\n\n return [\n theme.paint('plain', `reqray ${version}`) +\n theme.paint('dim', ' the panel, from the terminal'),\n '',\n command('watch', 'follow requests as they happen'),\n command('show <id>', 'one request, whole'),\n '',\n flag('--ids', 'watch: print the identifier show takes'),\n flag('--last --path <s>', 'show: the last request to a path'),\n '',\n flag('--url <address>', `where the panel is (${DEFAULT_URL})`),\n flag('--token <token>', 'for a collector started with one'),\n flag('--no-color', 'no escape codes, whatever the terminal is'),\n flag('--ascii', 'no box-drawing characters'),\n flag('--verbose', 'print what actually failed'),\n '',\n the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W,2BAA2B;AAAA,IAC3C,KAAK,aAAa,4BAA4B;AAAA,IAC9C;AAAA,IACA,MAAM,MAAM,OAAO,8DAA8D;AAAA,EACnF;AACF;","names":["cached","room","BLOCK","statusStyle","shown","queries","BLOCK","FLAGS","command"]}
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ run
4
+ } from "./chunk-V6ZCA7CU.js";
5
+
6
+ // src/cli.ts
7
+ var controller = new AbortController();
8
+ for (const signal of ["SIGINT", "SIGTERM"]) {
9
+ process.on(signal, () => {
10
+ controller.abort();
11
+ process.exit(0);
12
+ });
13
+ }
14
+ var code = await run(process.argv.slice(2), {
15
+ env: process.env,
16
+ stdout: process.stdout,
17
+ stderr: process.stderr,
18
+ signal: controller.signal
19
+ });
20
+ process.exitCode = code;
21
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `reqray` — the executable.\n *\n * Nothing but the wiring: the signal that Ctrl+C sends, the streams, and the\n * exit code. Everything a test needs is in `app.ts`, one import away.\n */\n\nimport { run } from './app.js';\n\nconst controller = new AbortController();\n\nfor (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, () => {\n // Ctrl+C ends the stream and the process with it: instantly, quietly, and\n // without a stack trace on the way out.\n controller.abort();\n process.exit(0);\n });\n}\n\nconst code = await run(process.argv.slice(2), {\n env: process.env,\n stdout: process.stdout,\n stderr: process.stderr,\n signal: controller.signal,\n});\n\nprocess.exitCode = code;\n"],"mappings":";;;;;;AAUA,IAAM,aAAa,IAAI,gBAAgB;AAEvC,WAAW,UAAU,CAAC,UAAU,SAAS,GAAY;AACnD,UAAQ,GAAG,QAAQ,MAAM;AAGvB,eAAW,MAAM;AACjB,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;AAEA,IAAM,OAAO,MAAM,IAAI,QAAQ,KAAK,MAAM,CAAC,GAAG;AAAA,EAC5C,KAAK,QAAQ;AAAA,EACb,QAAQ,QAAQ;AAAA,EAChB,QAAQ,QAAQ;AAAA,EAChB,QAAQ,WAAW;AACrB,CAAC;AAED,QAAQ,WAAW;","names":[]}