@testsprite/testsprite-cli 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +62 -45
  2. package/dist/commands/agent.d.ts +3 -0
  3. package/dist/commands/agent.js +79 -10
  4. package/dist/commands/ci.d.ts +88 -0
  5. package/dist/commands/ci.js +432 -0
  6. package/dist/commands/doctor.js +100 -1
  7. package/dist/commands/init.d.ts +45 -2
  8. package/dist/commands/init.js +198 -29
  9. package/dist/commands/project.d.ts +78 -0
  10. package/dist/commands/project.js +439 -5
  11. package/dist/commands/test.d.ts +193 -4
  12. package/dist/commands/test.js +1948 -398
  13. package/dist/commands/testlist.js +15 -9
  14. package/dist/commands/tunnel.d.ts +72 -0
  15. package/dist/commands/tunnel.js +367 -0
  16. package/dist/index.js +107 -38
  17. package/dist/lib/agent-detect.d.ts +53 -0
  18. package/dist/lib/agent-detect.js +198 -0
  19. package/dist/lib/dry-run/samples.d.ts +9 -0
  20. package/dist/lib/dry-run/samples.js +116 -0
  21. package/dist/lib/gh-output.d.ts +7 -0
  22. package/dist/lib/gh-output.js +50 -7
  23. package/dist/lib/http.d.ts +104 -0
  24. package/dist/lib/http.js +126 -7
  25. package/dist/lib/interrupt.d.ts +38 -13
  26. package/dist/lib/interrupt.js +130 -15
  27. package/dist/lib/local-target.d.ts +95 -0
  28. package/dist/lib/local-target.js +184 -0
  29. package/dist/lib/plan-poll.d.ts +171 -0
  30. package/dist/lib/plan-poll.js +442 -0
  31. package/dist/lib/plans.types.d.ts +130 -0
  32. package/dist/lib/plans.types.js +31 -0
  33. package/dist/lib/poll-support.d.ts +26 -0
  34. package/dist/lib/poll-support.js +65 -0
  35. package/dist/lib/poll.d.ts +1 -0
  36. package/dist/lib/poll.js +2 -40
  37. package/dist/lib/response-schemas.d.ts +13 -0
  38. package/dist/lib/response-schemas.js +46 -0
  39. package/dist/lib/run-progress.d.ts +41 -0
  40. package/dist/lib/run-progress.js +56 -0
  41. package/dist/lib/runs.types.d.ts +50 -0
  42. package/dist/lib/skill-nudge.d.ts +13 -5
  43. package/dist/lib/skill-nudge.js +40 -14
  44. package/dist/lib/target-url-preflight.js +3 -3
  45. package/dist/lib/target-url.d.ts +54 -8
  46. package/dist/lib/target-url.js +274 -68
  47. package/dist/lib/telemetry.d.ts +11 -0
  48. package/dist/lib/telemetry.js +1 -0
  49. package/dist/lib/ticker.d.ts +8 -0
  50. package/dist/lib/ticker.js +3 -0
  51. package/dist/lib/tunnel-session.d.ts +138 -0
  52. package/dist/lib/tunnel-session.js +249 -0
  53. package/dist/lib/tunnel.types.d.ts +54 -0
  54. package/dist/lib/tunnel.types.js +8 -0
  55. package/dist/vendor/tunnel-client/client.d.ts +82 -0
  56. package/dist/vendor/tunnel-client/client.js +924 -0
  57. package/dist/vendor/tunnel-client/config.d.ts +49 -0
  58. package/dist/vendor/tunnel-client/config.js +50 -0
  59. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  60. package/dist/vendor/tunnel-client/index.js +9 -0
  61. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  62. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  63. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  64. package/dist/vendor/tunnel-client/protocol.js +143 -0
  65. package/dist/vendor/tunnel-client/types.d.ts +101 -0
  66. package/dist/vendor/tunnel-client/types.js +10 -0
  67. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  68. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. package/package.json +2 -1
  72. package/skills/testsprite-onboard.skill.md +60 -4
  73. package/skills/testsprite-verify.codex.md +22 -16
  74. package/skills/testsprite-verify.skill.md +27 -18
@@ -12,8 +12,10 @@
12
12
  * Broken pipe: when output is piped to a reader that closes early
13
13
  * (`testsprite ... | head`), the kernel raises `EPIPE` on the next stdout write.
14
14
  * Node turns an `'error'` with no listener into an uncaughtException and dumps a
15
- * raw `write EPIPE` stack (exit 1). The guard swallows it and exits 0, the
16
- * conventional SIGPIPE-equivalent result for "the reader went away".
15
+ * raw `write EPIPE` stack (exit 1). Outside an armed lifetime the guard exits
16
+ * 0 immediately, the conventional SIGPIPE-equivalent result. While armed it
17
+ * first requests coordinated shutdown so tunnel cleanup can finish, then the
18
+ * same synthetic interrupt reason preserves exit 0.
17
19
  *
18
20
  * `process` and the streams are injectable so the wiring is unit-testable
19
21
  * without spawning a subprocess or sending a real signal.
@@ -31,7 +33,7 @@ export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
31
33
  * Two modes, chosen by whether a graceful-detach scope is armed when the
32
34
  * signal arrives:
33
35
  *
34
- * - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
36
+ * - **Armed** (inside `pollRunUntilTerminal` or a tunnel lifetime): the handler only aborts
35
37
  * `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
36
38
  * and every backoff sleep bail immediately; the `--wait` catch blocks own
37
39
  * the cleanup (finalize the ticker, print the honest partial envelope +
@@ -41,13 +43,14 @@ export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
41
43
  * immediately, preserving the pre-DEV-331 behavior. An abort nobody
42
44
  * observes must never leave the process hanging at e.g. a readline prompt.
43
45
  *
44
- * A second signal while the armed cleanup is in flight is the documented
45
- * escape hatch: immediate hard exit.
46
+ * A repeated signal still provides a bounded escape hatch: the second waits
47
+ * briefly only when critical cleanup is in flight, and the third exits at once.
46
48
  */
47
49
  export class ShutdownController {
48
50
  controller = new AbortController();
51
+ criticalOperations = new Set();
49
52
  armedCount = 0;
50
- receivedSignal = null;
53
+ receivedCause = null;
51
54
  constructor() {
52
55
  // Every fetch and every poll iteration composes this signal via
53
56
  // AbortSignal.any — a 50-run batch fan-out legitimately holds >10
@@ -57,9 +60,9 @@ export class ShutdownController {
57
60
  get signal() {
58
61
  return this.controller.signal;
59
62
  }
60
- /** The first termination signal received, or null if none yet. */
63
+ /** The first graceful-shutdown cause received, or null if none yet. */
61
64
  get received() {
62
- return this.receivedSignal;
65
+ return this.receivedCause;
63
66
  }
64
67
  get isArmed() {
65
68
  return this.armedCount > 0;
@@ -78,11 +81,56 @@ export class ShutdownController {
78
81
  this.armedCount -= 1;
79
82
  };
80
83
  }
84
+ /** Whether teardown currently has work whose abrupt loss is security-sensitive. */
85
+ get hasCriticalOperations() {
86
+ return this.criticalOperations.size > 0;
87
+ }
88
+ /**
89
+ * Register cleanup before it starts and remove it automatically when it
90
+ * settles. Rejections retain their original semantics for the caller.
91
+ */
92
+ runCriticalOperation(operation) {
93
+ const started = Promise.resolve().then(operation);
94
+ const tracked = started.finally(() => {
95
+ this.criticalOperations.delete(tracked);
96
+ });
97
+ this.criticalOperations.add(tracked);
98
+ return tracked;
99
+ }
100
+ /** Wait until all current and directly chained critical cleanup settles. */
101
+ async waitForCriticalOperations() {
102
+ while (this.criticalOperations.size > 0) {
103
+ await Promise.allSettled([...this.criticalOperations]);
104
+ }
105
+ }
81
106
  /** Record the signal and abort with an `InterruptError` carrying it. */
82
107
  interrupt(signal) {
83
- this.receivedSignal = signal;
108
+ this.receivedCause = signal;
84
109
  this.controller.abort(new InterruptError(signal));
85
110
  }
111
+ /**
112
+ * Abort an armed lifetime after stdout's reader closes. The InterruptError
113
+ * subtype deliberately keeps the existing graceful-detach catch paths in
114
+ * play (including tunnel cancellation), while its exit code stays the
115
+ * SIGPIPE-equivalent success code 0.
116
+ */
117
+ brokenPipe() {
118
+ if (this.receivedCause !== null)
119
+ return;
120
+ this.receivedCause = 'EPIPE';
121
+ this.controller.abort(new BrokenPipeInterruptError());
122
+ }
123
+ }
124
+ class BrokenPipeInterruptError extends InterruptError {
125
+ exitCode = 0;
126
+ constructor() {
127
+ // Existing graceful-detach consumers read `.signal` to render their
128
+ // partial status. The distinct name/message and exitCode carry the real
129
+ // cause without widening the OS-signal contract in errors.ts.
130
+ super('SIGINT');
131
+ this.name = 'BrokenPipeInterruptError';
132
+ this.message = 'Output pipe closed.';
133
+ }
86
134
  }
87
135
  /**
88
136
  * The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
@@ -95,6 +143,38 @@ export function formatInterruptMessage(signal = 'SIGINT') {
95
143
  return (`Interrupted (${signal}). Any run already started keeps executing on the server; ` +
96
144
  'check it with `testsprite test list` or `testsprite test wait <runId>`.');
97
145
  }
146
+ const CRITICAL_OPERATION_GRACE_MS = 2_000;
147
+ /** How often the grace period re-checks whether teardown is still running. */
148
+ const CRITICAL_OPERATION_POLL_MS = 10;
149
+ function afterDelay(ms) {
150
+ return new Promise(resolve => {
151
+ const timer = setTimeout(resolve, ms);
152
+ timer.unref?.();
153
+ });
154
+ }
155
+ async function waitForCriticalOperationsWithGrace(shutdown) {
156
+ const graceExpired = afterDelay(CRITICAL_OPERATION_GRACE_MS);
157
+ const teardownFinished = (async () => {
158
+ // An armed scope is the honest signal that teardown has not finished. On a
159
+ // tunnel run it spans the whole unwind — cancel, then close, then the
160
+ // credential delete — and those register one at a time with gaps between
161
+ // them, so "no critical operation right now" does not mean "done". A fixed
162
+ // settle window is the wrong shape: measured against the real command, the
163
+ // first registration lands well after any window short enough to keep the
164
+ // escape hatch snappy. Waiting for the scope to close instead tracks the
165
+ // actual work, and the caller's overall cap keeps it bounded.
166
+ while (shutdown.isArmed) {
167
+ if (shutdown.hasCriticalOperations) {
168
+ await shutdown.waitForCriticalOperations();
169
+ }
170
+ else {
171
+ await afterDelay(CRITICAL_OPERATION_POLL_MS);
172
+ }
173
+ }
174
+ await shutdown.waitForCriticalOperations();
175
+ })();
176
+ await Promise.race([graceExpired, teardownFinished]);
177
+ }
98
178
  /**
99
179
  * Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
100
180
  * single top-level call in `index.ts`; not designed to be installed twice.
@@ -102,8 +182,9 @@ export function formatInterruptMessage(signal = 'SIGINT') {
102
182
  * First signal, armed scope: abort-only — the `--wait` catch paths own the
103
183
  * honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
104
184
  * First signal, disarmed: print the generic explanation + exit `128+signum`.
105
- * Second signal (any mode): immediate hard exit — the escape hatch when the
106
- * graceful cleanup itself wedges.
185
+ * Second signal: exit immediately unless critical cleanup is registered; when
186
+ * it is, wait at most two seconds before exiting. Third signal: always exit
187
+ * immediately, including while that grace period is active.
107
188
  */
108
189
  export function installSignalHandlers(deps = {}) {
109
190
  const on = deps.on ??
@@ -124,13 +205,38 @@ export function installSignalHandlers(deps = {}) {
124
205
  });
125
206
  const exit = deps.exit ?? ((code) => process.exit(code));
126
207
  const shutdown = deps.shutdown ?? globalShutdown;
208
+ let signalCount = 0;
209
+ let graceGeneration = 0;
127
210
  for (const signal of Object.keys(TERMINATION_EXIT_CODES)) {
128
211
  on(signal, () => {
129
- if (shutdown.received !== null) {
130
- // Second signal while graceful cleanup is in flight: hard exit now.
212
+ signalCount += 1;
213
+ if (signalCount >= 3) {
214
+ // Invalidate any second-signal grace continuation before hard exit.
215
+ graceGeneration += 1;
131
216
  exit(TERMINATION_EXIT_CODES[signal]);
132
217
  return;
133
218
  }
219
+ if (signalCount === 2) {
220
+ // `isArmed` matters as much as an already-registered operation: on a
221
+ // tunnel run the lifecycle scope stays armed across teardown, and the
222
+ // credential delete is registered only after the poll loop unwinds. A
223
+ // second signal that arrives in between — which is what a reflexive
224
+ // double Ctrl-C actually does — would otherwise hard-exit and strand a
225
+ // live inbound credential until its TTL, the exact outcome the grace
226
+ // period exists to prevent.
227
+ if (!shutdown.hasCriticalOperations && !shutdown.isArmed) {
228
+ exit(TERMINATION_EXIT_CODES[signal]);
229
+ return;
230
+ }
231
+ const generation = ++graceGeneration;
232
+ void waitForCriticalOperationsWithGrace(shutdown).then(() => {
233
+ // A third signal already took the immediate path.
234
+ if (graceGeneration !== generation)
235
+ return;
236
+ exit(TERMINATION_EXIT_CODES[signal]);
237
+ });
238
+ return;
239
+ }
134
240
  if (shutdown.isArmed) {
135
241
  // Graceful detach: abort only (sync, signal-safe — no I/O here so a
136
242
  // pending stdout `drain` wait can settle); the armed catch paths
@@ -154,18 +260,27 @@ export function installSignalHandlers(deps = {}) {
154
260
  /**
155
261
  * Guard against `EPIPE` on stdout/stderr so piping to a reader that closes
156
262
  * early (`testsprite ... | head`) exits cleanly instead of crashing with an
157
- * unhandled `write EPIPE` stack. Only `EPIPE` is swallowed; any other stream
158
- * error is left to surface normally.
263
+ * unhandled `write EPIPE` stack. An armed stdout path requests graceful
264
+ * shutdown before exiting 0; a disarmed one exits 0 immediately. Only `EPIPE`
265
+ * is swallowed; any other stream error is left to surface normally.
159
266
  */
160
267
  export function installBrokenPipeGuard(deps = {}) {
161
268
  const stdout = deps.stdout ?? process.stdout;
162
269
  const stderr = deps.stderr ?? process.stderr;
163
270
  const exit = deps.exit ?? ((code) => process.exit(code));
271
+ const shutdown = deps.shutdown ?? globalShutdown;
164
272
  stdout.on('error', (error) => {
165
273
  // Reader went away (`| head`, `| less` then q): exit cleanly like SIGPIPE
166
274
  // rather than dumping an unhandled `write EPIPE` stack. Any other stdout
167
275
  // error is a genuine, actionable failure, so re-throw it (Node's default).
168
276
  if (error.code === 'EPIPE') {
277
+ if (shutdown.isArmed) {
278
+ // A tunnel lifetime owns credential teardown in its `finally`. Abort
279
+ // through the same coordinator as the first signal and let that
280
+ // cleanup finish; the synthetic reason exits 0 once it propagates.
281
+ shutdown.brokenPipe();
282
+ return;
283
+ }
169
284
  exit(0);
170
285
  return;
171
286
  }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * `--local <port>` argument handling and the pre-charge port probe.
3
+ *
4
+ * Separate from `target-url-preflight.ts` on purpose, even though both answer
5
+ * "is the thing I am about to bill a run against actually there". They probe
6
+ * two different mechanisms and must not share one:
7
+ *
8
+ * - `--target-url` is fetched by a browser inside a Lambda, so probing it
9
+ * with `fetch()` (proxy dispatcher and all) is the closest local analogue,
10
+ * and an ambiguous result downgrades to a warning because the CLI is not
11
+ * the machine that will do the fetching.
12
+ * - `--local <port>` is dialled by the vendored tunnel client running *in
13
+ * this very process*, with `net.connect`, against the candidate set
14
+ * {@link resolveDialCandidates} produces. So the probe uses that same
15
+ * function and the same kind of socket. A pass means at least one TCP
16
+ * connection actually completed; every other result refuses. In
17
+ * particular, `ETIMEDOUT` can be a dropped SYN with no listener at all,
18
+ * so it is not evidence that something is bound. That is why this one is
19
+ * allowed to be the gate that runs BEFORE the mint and therefore before
20
+ * any run row or credit spend exists.
21
+ */
22
+ /**
23
+ * The loopback spellings a tunnel target may use.
24
+ *
25
+ * This is a MIRROR of the server's `isLoopbackString`
26
+ * (backend-v2.0 `libs/net/private-address.ts`), which accepts exactly
27
+ * `localhost`, `127.0.0.1` and `::1` — not "anything in 127.0.0.0/8". Keeping
28
+ * the two identical is the whole point of validating client-side at all: a
29
+ * value this accepts and the server rejects would fail with
30
+ * `tunnel-target-not-local` AFTER a tunnel had already been minted, and a
31
+ * value this rejects but the server accepts is a capability silently withheld.
32
+ */
33
+ export declare const LOOPBACK_HOSTS: readonly ["localhost", "127.0.0.1", "::1"];
34
+ export type LoopbackHost = (typeof LOOPBACK_HOSTS)[number];
35
+ /** Default `--local-host`. An IP literal, so no resolver is involved at all. */
36
+ export declare const DEFAULT_LOCAL_HOST: LoopbackHost;
37
+ /**
38
+ * Per-candidate dial budget. Deliberately short: this is a loopback connect on
39
+ * the caller's own machine, where a live listener answers in microseconds. A
40
+ * long budget would only lengthen the wait before an honest refusal.
41
+ */
42
+ export declare const LOCAL_PORT_PROBE_TIMEOUT_MS = 2000;
43
+ export type LocalPortProbeOutcome = {
44
+ verdict: 'ok';
45
+ } | {
46
+ verdict: 'refuse';
47
+ reason: string;
48
+ };
49
+ export interface LocalPortProbeDeps {
50
+ /**
51
+ * Dial one candidate; resolve on connect, reject on failure. Defaults to a
52
+ * real `net.connect`. Injectable so a test can prove the
53
+ * `--skip-preflight` path makes ZERO attempts — the assertion that matters
54
+ * for the pre-charge guarantee.
55
+ */
56
+ connect?: (host: string, port: number, timeoutMs: number) => Promise<void>;
57
+ /** Candidate resolver. Defaults to the vendored client's own. */
58
+ resolveCandidates?: (host: string, port: number) => Promise<Array<{
59
+ host: string;
60
+ port: number;
61
+ }>>;
62
+ }
63
+ /** Parse `--local <port>`. Strict: this becomes part of a URL a run is billed against. */
64
+ export declare function parseLocalPort(raw: string): number;
65
+ /**
66
+ * Normalise and validate `--local-host`. Rejects everything outside
67
+ * {@link LOOPBACK_HOSTS} with zero network calls — a tunnel reaches the
68
+ * caller's own machine and nothing else, so a non-loopback value here is a
69
+ * misunderstanding to correct immediately, not a request to forward.
70
+ */
71
+ export declare function normalizeLocalHost(raw: string | undefined): LoopbackHost;
72
+ /** `http://<host>:<port>`, with IPv6 bracketed as the URL grammar requires. */
73
+ export declare function buildLocalTargetUrl(host: LoopbackHost, port: number): string;
74
+ /**
75
+ * Dial every candidate {@link resolveDialCandidates} produces for
76
+ * `host:port`. ANY successful connect is a pass — `localhost` resolves to both
77
+ * `127.0.0.1` and `::1`, and a dev server bound to one family must never be
78
+ * reported dead because the other refused.
79
+ */
80
+ export declare function probeLocalPort(host: string, port: number, deps?: LocalPortProbeDeps): Promise<LocalPortProbeOutcome>;
81
+ /**
82
+ * Run {@link probeLocalPort} and either throw (refuse) or no-op (ok / skipped).
83
+ *
84
+ * Call this BEFORE minting a tunnel. That ordering is the feature: DEV-243
85
+ * measured 1,003 blocked-with-URL CLI runs, 55.5% of the third-party-tunnel
86
+ * ones blocked, every one of them charged, because the run row and its credit
87
+ * spend happen before the Lambda ever discovers the target is dead. A dev
88
+ * server that is not running is the single most likely `--local` mistake, and
89
+ * this is the only place it can be caught for free.
90
+ *
91
+ * `skipPreflight: true` is a pure no-op with ZERO connection attempts.
92
+ */
93
+ export declare function assertLocalPortListening(host: LoopbackHost | string, port: number, opts: {
94
+ skipPreflight?: boolean;
95
+ }, _stderrFn: (line: string) => void, deps?: LocalPortProbeDeps): Promise<void>;
@@ -0,0 +1,184 @@
1
+ /**
2
+ * `--local <port>` argument handling and the pre-charge port probe.
3
+ *
4
+ * Separate from `target-url-preflight.ts` on purpose, even though both answer
5
+ * "is the thing I am about to bill a run against actually there". They probe
6
+ * two different mechanisms and must not share one:
7
+ *
8
+ * - `--target-url` is fetched by a browser inside a Lambda, so probing it
9
+ * with `fetch()` (proxy dispatcher and all) is the closest local analogue,
10
+ * and an ambiguous result downgrades to a warning because the CLI is not
11
+ * the machine that will do the fetching.
12
+ * - `--local <port>` is dialled by the vendored tunnel client running *in
13
+ * this very process*, with `net.connect`, against the candidate set
14
+ * {@link resolveDialCandidates} produces. So the probe uses that same
15
+ * function and the same kind of socket. A pass means at least one TCP
16
+ * connection actually completed; every other result refuses. In
17
+ * particular, `ETIMEDOUT` can be a dropped SYN with no listener at all,
18
+ * so it is not evidence that something is bound. That is why this one is
19
+ * allowed to be the gate that runs BEFORE the mint and therefore before
20
+ * any run row or credit spend exists.
21
+ */
22
+ import * as net from 'node:net';
23
+ import { ApiError, localValidationError } from './errors.js';
24
+ import { resolveDialCandidates } from '../vendor/tunnel-client/index.js';
25
+ /**
26
+ * The loopback spellings a tunnel target may use.
27
+ *
28
+ * This is a MIRROR of the server's `isLoopbackString`
29
+ * (backend-v2.0 `libs/net/private-address.ts`), which accepts exactly
30
+ * `localhost`, `127.0.0.1` and `::1` — not "anything in 127.0.0.0/8". Keeping
31
+ * the two identical is the whole point of validating client-side at all: a
32
+ * value this accepts and the server rejects would fail with
33
+ * `tunnel-target-not-local` AFTER a tunnel had already been minted, and a
34
+ * value this rejects but the server accepts is a capability silently withheld.
35
+ */
36
+ export const LOOPBACK_HOSTS = ['localhost', '127.0.0.1', '::1'];
37
+ /** Default `--local-host`. An IP literal, so no resolver is involved at all. */
38
+ export const DEFAULT_LOCAL_HOST = '127.0.0.1';
39
+ /**
40
+ * Per-candidate dial budget. Deliberately short: this is a loopback connect on
41
+ * the caller's own machine, where a live listener answers in microseconds. A
42
+ * long budget would only lengthen the wait before an honest refusal.
43
+ */
44
+ export const LOCAL_PORT_PROBE_TIMEOUT_MS = 2_000;
45
+ /** Parse `--local <port>`. Strict: this becomes part of a URL a run is billed against. */
46
+ export function parseLocalPort(raw) {
47
+ const port = Number(raw);
48
+ if (raw.trim() !== raw ||
49
+ raw.length === 0 ||
50
+ !Number.isInteger(port) ||
51
+ port < 1 ||
52
+ port > 65535) {
53
+ throw localValidationError('local', 'must be a port number between 1 and 65535');
54
+ }
55
+ return port;
56
+ }
57
+ /**
58
+ * Normalise and validate `--local-host`. Rejects everything outside
59
+ * {@link LOOPBACK_HOSTS} with zero network calls — a tunnel reaches the
60
+ * caller's own machine and nothing else, so a non-loopback value here is a
61
+ * misunderstanding to correct immediately, not a request to forward.
62
+ */
63
+ export function normalizeLocalHost(raw) {
64
+ if (raw === undefined)
65
+ return DEFAULT_LOCAL_HOST;
66
+ const unbracketed = raw.startsWith('[') && raw.endsWith(']') ? raw.slice(1, -1) : raw;
67
+ const candidate = unbracketed.trim().toLowerCase();
68
+ const match = LOOPBACK_HOSTS.find(host => host === candidate);
69
+ if (match === undefined) {
70
+ throw localValidationError('local-host', `must name your own machine — one of ${LOOPBACK_HOSTS.join(', ')}. ` +
71
+ 'A tunnel only reaches the machine running this CLI; to test a reachable ' +
72
+ 'address use --target-url instead', [...LOOPBACK_HOSTS]);
73
+ }
74
+ return match;
75
+ }
76
+ /** `http://<host>:<port>`, with IPv6 bracketed as the URL grammar requires. */
77
+ export function buildLocalTargetUrl(host, port) {
78
+ const authority = host.includes(':') ? `[${host}]` : host;
79
+ return `http://${authority}:${port}`;
80
+ }
81
+ function dialOnce(host, port, timeoutMs) {
82
+ return new Promise((resolve, reject) => {
83
+ const socket = net.connect({ host, port });
84
+ const cleanup = () => {
85
+ clearTimeout(timer);
86
+ socket.removeAllListeners();
87
+ socket.destroy();
88
+ };
89
+ const timer = setTimeout(() => {
90
+ cleanup();
91
+ const err = new Error(`connect timeout ${timeoutMs}ms`);
92
+ err.code = 'ETIMEDOUT';
93
+ reject(err);
94
+ }, timeoutMs);
95
+ socket.once('connect', () => {
96
+ cleanup();
97
+ resolve();
98
+ });
99
+ socket.once('error', err => {
100
+ cleanup();
101
+ reject(err);
102
+ });
103
+ });
104
+ }
105
+ function formatDialTarget(host, port) {
106
+ const authority = host.includes(':') ? `[${host}]` : host;
107
+ return `${authority}:${port}`;
108
+ }
109
+ function describeDialFailure(err) {
110
+ const code = err?.code;
111
+ const message = err instanceof Error ? err.message : String(err);
112
+ if (code === undefined || code === message)
113
+ return message;
114
+ return `${code} (${message})`;
115
+ }
116
+ /**
117
+ * Dial every candidate {@link resolveDialCandidates} produces for
118
+ * `host:port`. ANY successful connect is a pass — `localhost` resolves to both
119
+ * `127.0.0.1` and `::1`, and a dev server bound to one family must never be
120
+ * reported dead because the other refused.
121
+ */
122
+ export async function probeLocalPort(host, port, deps = {}) {
123
+ const resolveCandidates = deps.resolveCandidates ?? resolveDialCandidates;
124
+ const connect = deps.connect ?? dialOnce;
125
+ const candidates = await resolveCandidates(host, port);
126
+ if (candidates.length === 0) {
127
+ return {
128
+ verdict: 'refuse',
129
+ reason: `tried resolving ${formatDialTarget(host, port)}; resolver returned no dial candidates`,
130
+ };
131
+ }
132
+ const failures = [];
133
+ for (const candidate of candidates) {
134
+ try {
135
+ await connect(candidate.host, candidate.port, LOCAL_PORT_PROBE_TIMEOUT_MS);
136
+ return { verdict: 'ok' };
137
+ }
138
+ catch (err) {
139
+ failures.push(`${formatDialTarget(candidate.host, candidate.port)} -> ${describeDialFailure(err)}`);
140
+ }
141
+ }
142
+ return {
143
+ verdict: 'refuse',
144
+ reason: `no candidate connected to ${formatDialTarget(host, port)}; attempts: ` + failures.join('; '),
145
+ };
146
+ }
147
+ /** Shared refusal wording that names the one explicit bypass exactly once. */
148
+ const SKIP_HINT = 'Skip this check with --skip-preflight.';
149
+ /**
150
+ * Run {@link probeLocalPort} and either throw (refuse) or no-op (ok / skipped).
151
+ *
152
+ * Call this BEFORE minting a tunnel. That ordering is the feature: DEV-243
153
+ * measured 1,003 blocked-with-URL CLI runs, 55.5% of the third-party-tunnel
154
+ * ones blocked, every one of them charged, because the run row and its credit
155
+ * spend happen before the Lambda ever discovers the target is dead. A dev
156
+ * server that is not running is the single most likely `--local` mistake, and
157
+ * this is the only place it can be caught for free.
158
+ *
159
+ * `skipPreflight: true` is a pure no-op with ZERO connection attempts.
160
+ */
161
+ export async function assertLocalPortListening(host, port, opts, _stderrFn, deps = {}) {
162
+ if (opts.skipPreflight === true)
163
+ return;
164
+ const outcome = await probeLocalPort(host, port, deps);
165
+ if (outcome.verdict === 'refuse') {
166
+ throw ApiError.fromEnvelope({
167
+ error: {
168
+ code: 'VALIDATION_ERROR',
169
+ message: `Nothing is listening on ${host}:${port}, so a tunnel run would fail after being billed.`,
170
+ nextAction: `Start your app on port ${port} first, or point --local at the port it is actually ` +
171
+ `serving. ${SKIP_HINT}`,
172
+ requestId: 'local',
173
+ details: {
174
+ field: 'local',
175
+ reason: 'local-port-not-listening',
176
+ host,
177
+ port,
178
+ probeReason: outcome.reason,
179
+ },
180
+ },
181
+ });
182
+ }
183
+ }
184
+ //# sourceMappingURL=local-target.js.map