@nice-code/commander 0.86.0 → 0.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/cli.mjs CHANGED
@@ -1119,111 +1119,6 @@ function staggerFor(config, terms) {
1119
1119
  return stagger;
1120
1120
  }
1121
1121
  //#endregion
1122
- //#region ../nice-wire/src/Carrier/duplex/ws/ws_util.ts
1123
- /**
1124
- * Send a text or binary frame over a socket. A binary formatter may hand back a `Uint8Array` whose
1125
- * backing buffer is typed as `ArrayBufferLike` (msgpackr pools buffers / may be `SharedArrayBuffer`),
1126
- * which `WebSocket.send`'s `BufferSource` parameter rejects — copy it into a fresh `ArrayBuffer`-backed
1127
- * view so the type (and the bytes) are safe to send.
1128
- */
1129
- function sendFrame(ws, data) {
1130
- if (typeof data === "string" || data instanceof ArrayBuffer) {
1131
- ws.send(data);
1132
- return;
1133
- }
1134
- ws.send(new Uint8Array(data));
1135
- }
1136
- /** Compact a WebSocket URL to `host/pathname` for devtools display, falling back to the raw url. */
1137
- function shortWs(url) {
1138
- try {
1139
- const u = new URL(url);
1140
- return `${u.host}${u.pathname}`;
1141
- } catch {
1142
- return url;
1143
- }
1144
- }
1145
- //#endregion
1146
- //#region ../nice-wire/src/Carrier/duplex/ws/webSocketByteChannel.ts
1147
- /**
1148
- * Adapt a `WebSocket` to the carrier-agnostic {@link IDuplexCarrier}, so the WebSocket becomes
1149
- * "just another carrier" under the shared secure session. It owns every WebSocket-specific concern —
1150
- * awaiting `open`, normalizing `Blob` frames to bytes, suppressing the log on a deliberate `close`, and
1151
- * buffering any frame that arrives before the session attaches its handler — leaving the session itself
1152
- * carrier-neutral.
1153
- */
1154
- function webSocketByteChannel(ws) {
1155
- let intentional = false;
1156
- /**
1157
- * True once the socket actually opened. A failure *before* this is a failed **dial**, not an
1158
- * outage: it is reported by rejecting `ready` (and the connector's keep-alive ladder retries it
1159
- * with backoff). Logging it here would spam the console on every attempt while a peer boots — the
1160
- * routine dev-restart race — so the pre-open path stays silent and lets `ready` do the talking.
1161
- */
1162
- let opened = ws.readyState === WebSocket.OPEN;
1163
- let onMessage;
1164
- let onClose;
1165
- const preAttach = [];
1166
- const deliver = (frame) => {
1167
- if (onMessage != null) onMessage(frame);
1168
- else preAttach.push(frame);
1169
- };
1170
- ws.addEventListener("open", () => {
1171
- opened = true;
1172
- });
1173
- ws.addEventListener("message", async (event) => {
1174
- const frame = await normalizeFrame(event.data);
1175
- if (frame !== void 0) deliver(frame);
1176
- });
1177
- ws.addEventListener("close", (event) => {
1178
- if (opened && !intentional) console.warn("WebSocket closed:", event);
1179
- onClose?.();
1180
- });
1181
- ws.addEventListener("error", () => {
1182
- if (opened) console.warn(`WebSocket error: ${describeSocket(ws)}`);
1183
- onClose?.();
1184
- });
1185
- return {
1186
- ready: new Promise((resolve, reject) => {
1187
- if (ws.readyState === WebSocket.OPEN) {
1188
- resolve();
1189
- return;
1190
- }
1191
- ws.addEventListener("open", () => resolve(), { once: true });
1192
- ws.addEventListener("error", () => reject(dialFailedError(ws)), { once: true });
1193
- ws.addEventListener("close", (event) => reject(/* @__PURE__ */ new Error(`WebSocket closed before open (code=${event.code}): ${describeSocket(ws)}`)), { once: true });
1194
- }),
1195
- isOpen: () => ws.readyState === WebSocket.OPEN,
1196
- send: (frame) => sendFrame(ws, frame),
1197
- attach: (handlers) => {
1198
- onMessage = handlers.onMessage;
1199
- onClose = handlers.onClose;
1200
- for (const frame of preAttach) handlers.onMessage(frame);
1201
- preAttach.length = 0;
1202
- },
1203
- close: () => {
1204
- intentional = true;
1205
- try {
1206
- ws.close();
1207
- } catch {}
1208
- },
1209
- get label() {
1210
- return ws.url != null && ws.url !== "" ? ws.url : void 0;
1211
- }
1212
- };
1213
- }
1214
- /** A failed dial, as a structured error the error pipeline (and a consumer's logs) can actually read. */
1215
- function dialFailedError(ws) {
1216
- return /* @__PURE__ */ new Error(`WebSocket dial failed: ${describeSocket(ws)}`);
1217
- }
1218
- function describeSocket(ws) {
1219
- return ws.url != null && ws.url !== "" ? ws.url : "(no url)";
1220
- }
1221
- /** Accept text + binary frames (ArrayBuffer / Uint8Array / Blob); Blobs are converted to a buffer. */
1222
- async function normalizeFrame(data) {
1223
- if (typeof data === "string" || data instanceof ArrayBuffer || data instanceof Uint8Array) return data;
1224
- if (typeof Blob !== "undefined" && data instanceof Blob) return await data.arrayBuffer();
1225
- }
1226
- //#endregion
1227
1122
  //#region ../nice-error/src/internal/internal_errors.ts
1228
1123
  let _build;
1229
1124
  /** Wired once by `nice_core_errors` at module init to avoid an import cycle. */
@@ -2247,8 +2142,12 @@ const err_wire_connect = err_nice.createChildDomain({
2247
2142
  connect_exhausted: err({ message: ({ peerId, attempted }) => `connect() to peer [${peerId}] exhausted its transport chain (tried: ${attempted.join(", ") || "none configured"}).` }),
2248
2143
  /** Phase 2 — `connect()` after `close()`; a closed client is terminal, build a new one. */
2249
2144
  connect_closed: err({ message: ({ peerId }) => `connect() to peer [${peerId}] on a closed WireClient — closed is terminal; create a new client.` }),
2250
- /** Phase 2 — one transport's dial or handshake failed (the chain item detail inside `connect_exhausted`). */
2251
- dial_failed: err({ message: ({ peerId, carrierLabel, reason }) => `Dialing peer [${peerId}] over "${carrierLabel}" failed: ${reason}` }),
2145
+ /**
2146
+ * Phase 2 — one transport's dial or handshake failed (the chain item detail inside
2147
+ * `connect_exhausted`). `endpoint`/`kind` are the feedback W2/W3 additions: the URL actually
2148
+ * dialed, and the typed class of failure (see `EWireConnectFailureKind`).
2149
+ */
2150
+ dial_failed: err({ message: ({ peerId, carrierLabel, reason, endpoint }) => `Dialing peer [${peerId}] over "${carrierLabel}"${endpoint != null ? ` against ${endpoint}` : ""} failed: ${reason}` }),
2252
2151
  /**
2253
2152
  * Resilience-surface §6 — the carrier has **no valid endpoint right now** (`createRequest`
2254
2153
  * returned `null`, e.g. a torn-down session's mutable dial context). Not a failure: a policy
@@ -2256,6 +2155,34 @@ const err_wire_connect = err_nice.createChildDomain({
2256
2155
  * it — no dialing garbage, no backoff churn — until the next explicit `connect()`/dispatch.
2257
2156
  */
2258
2157
  dial_unavailable: err({ message: ({ carrierLabel }) => `Dial over "${carrierLabel}" unavailable — createRequest returned null (no valid endpoint right now). A keep-alive redial parks on this until the next explicit connect()/dispatch.` }),
2158
+ /**
2159
+ * Consumer feedback (meteor-connect-bridge W1/W3) — **something answered, and it is not
2160
+ * nice-wire**. The dominant real-world causes are a wrong URL/port, an intercepting proxy or
2161
+ * WAF, or an endpoint that is simply a different server. Thrown where the evidence still
2162
+ * exists (the carrier holds the HTTP status; the handshake holds the frame), so the data
2163
+ * carries what came back instead of only what we wanted. Branch on it with
2164
+ * `err.hasId("endpoint_answered_non_protocol")` — never on the message text.
2165
+ */
2166
+ endpoint_answered_non_protocol: err({ message: ({ stage, expected, url, httpStatus, contentType, receivedKind, bodyPreview }) => {
2167
+ const received = httpStatus != null ? `an HTTP ${httpStatus}${contentType != null ? ` ${contentType}` : ""} response` : receivedKind != null ? `a "${receivedKind}" frame` : "a response it could not decode";
2168
+ return `[${stage}] expected ${expected ?? "a nice-wire frame"} but received ${received} — the endpoint answered but is not speaking the nice-wire protocol (wrong URL, an intercepting proxy/WAF, or a different server)${url != null ? `. Dialed: ${url}` : ""}${bodyPreview != null ? `. Body: ${JSON.stringify(bodyPreview)}` : ""}.`;
2169
+ } }),
2170
+ /**
2171
+ * Consumer feedback (meteor-connect-bridge W3) — **nothing answered**: DNS/refused/TLS/offline,
2172
+ * or a socket that errored before it opened. The sibling of
2173
+ * `endpoint_answered_non_protocol`, and the reason the two are separate ids: they need
2174
+ * opposite developer responses (start the server / open the firewall, vs fix the URL or the
2175
+ * proxy in front of it).
2176
+ */
2177
+ endpoint_unreachable: err({ message: ({ url, carrierLabel, reason }) => `Could not reach ${url ?? (carrierLabel != null ? `the "${carrierLabel}" endpoint` : "the endpoint")}: ${reason} — nothing answered there (wrong host/port, the server is not running, or a firewall/offline network).` }),
2178
+ /**
2179
+ * The peer **is** a nice-code backend and refused the handshake for a reason that carries no
2180
+ * machine-readable id of its own (an older peer, a dictionary/security mismatch, a custom
2181
+ * gate). Typed so `classifyConnectFailure` can report `handshake_rejected` — a third
2182
+ * developer response ("fix the identity/version"), distinct from a wrong URL or a dead host.
2183
+ * `identity_pin_mismatch` stays its own id: it is permanent and the redial loop parks on it.
2184
+ */
2185
+ handshake_rejected: err({ message: ({ stage, reason }) => `[${stage}] rejected by peer: ${reason}` }),
2259
2186
  /** Phase 3 — a protocol sent on a connection whose peer did not advertise it (or the host never registered it). */
2260
2187
  protocol_unsupported: err({ message: ({ protocolId }) => `Protocol "${protocolId}" cannot speak on this connection — the peer did not advertise "proto:${protocolId}" (or it is not registered here).` }),
2261
2188
  /** Phase 6 — a prefixed protocol registered on an exchange-only connection (protocols need duplex; plan D-11). */
@@ -2278,6 +2205,123 @@ const err_wire_connect = err_nice.createChildDomain({
2278
2205
  }
2279
2206
  });
2280
2207
  //#endregion
2208
+ //#region ../nice-wire/src/Carrier/duplex/ws/ws_util.ts
2209
+ /**
2210
+ * Send a text or binary frame over a socket. A binary formatter may hand back a `Uint8Array` whose
2211
+ * backing buffer is typed as `ArrayBufferLike` (msgpackr pools buffers / may be `SharedArrayBuffer`),
2212
+ * which `WebSocket.send`'s `BufferSource` parameter rejects — copy it into a fresh `ArrayBuffer`-backed
2213
+ * view so the type (and the bytes) are safe to send.
2214
+ */
2215
+ function sendFrame(ws, data) {
2216
+ if (typeof data === "string" || data instanceof ArrayBuffer) {
2217
+ ws.send(data);
2218
+ return;
2219
+ }
2220
+ ws.send(new Uint8Array(data));
2221
+ }
2222
+ /** Compact a WebSocket URL to `host/pathname` for devtools display, falling back to the raw url. */
2223
+ function shortWs(url) {
2224
+ try {
2225
+ const u = new URL(url);
2226
+ return `${u.host}${u.pathname}`;
2227
+ } catch {
2228
+ return url;
2229
+ }
2230
+ }
2231
+ //#endregion
2232
+ //#region ../nice-wire/src/Carrier/duplex/ws/webSocketByteChannel.ts
2233
+ /**
2234
+ * Adapt a `WebSocket` to the carrier-agnostic {@link IDuplexCarrier}, so the WebSocket becomes
2235
+ * "just another carrier" under the shared secure session. It owns every WebSocket-specific concern —
2236
+ * awaiting `open`, normalizing `Blob` frames to bytes, suppressing the log on a deliberate `close`, and
2237
+ * buffering any frame that arrives before the session attaches its handler — leaving the session itself
2238
+ * carrier-neutral.
2239
+ */
2240
+ function webSocketByteChannel(ws) {
2241
+ let intentional = false;
2242
+ /**
2243
+ * True once the socket actually opened. A failure *before* this is a failed **dial**, not an
2244
+ * outage: it is reported by rejecting `ready` (and the connector's keep-alive ladder retries it
2245
+ * with backoff). Logging it here would spam the console on every attempt while a peer boots — the
2246
+ * routine dev-restart race — so the pre-open path stays silent and lets `ready` do the talking.
2247
+ */
2248
+ let opened = ws.readyState === WebSocket.OPEN;
2249
+ let onMessage;
2250
+ let onClose;
2251
+ const preAttach = [];
2252
+ const deliver = (frame) => {
2253
+ if (onMessage != null) onMessage(frame);
2254
+ else preAttach.push(frame);
2255
+ };
2256
+ ws.addEventListener("open", () => {
2257
+ opened = true;
2258
+ });
2259
+ ws.addEventListener("message", async (event) => {
2260
+ const frame = await normalizeFrame(event.data);
2261
+ if (frame !== void 0) deliver(frame);
2262
+ });
2263
+ ws.addEventListener("close", (event) => {
2264
+ if (opened && !intentional) console.warn("WebSocket closed:", event);
2265
+ onClose?.();
2266
+ });
2267
+ ws.addEventListener("error", () => {
2268
+ if (opened) console.warn(`WebSocket error: ${describeSocket(ws)}`);
2269
+ onClose?.();
2270
+ });
2271
+ return {
2272
+ ready: new Promise((resolve, reject) => {
2273
+ if (ws.readyState === WebSocket.OPEN) {
2274
+ resolve();
2275
+ return;
2276
+ }
2277
+ ws.addEventListener("open", () => resolve(), { once: true });
2278
+ ws.addEventListener("error", () => reject(dialFailedError(ws)), { once: true });
2279
+ ws.addEventListener("close", (event) => reject(unreachableError(ws, `WebSocket closed before open (code=${event.code})`)), { once: true });
2280
+ }),
2281
+ isOpen: () => ws.readyState === WebSocket.OPEN,
2282
+ send: (frame) => sendFrame(ws, frame),
2283
+ attach: (handlers) => {
2284
+ onMessage = handlers.onMessage;
2285
+ onClose = handlers.onClose;
2286
+ for (const frame of preAttach) handlers.onMessage(frame);
2287
+ preAttach.length = 0;
2288
+ },
2289
+ close: () => {
2290
+ intentional = true;
2291
+ try {
2292
+ ws.close();
2293
+ } catch {}
2294
+ },
2295
+ get label() {
2296
+ return ws.url != null && ws.url !== "" ? ws.url : void 0;
2297
+ }
2298
+ };
2299
+ }
2300
+ /**
2301
+ * A failed dial, as a structured error the error pipeline (and a consumer's logs) can actually
2302
+ * read. A socket that errors or closes *before* it opened means nothing answered, so it carries
2303
+ * the same typed `endpoint_unreachable` id as the HTTP carrier's `fetch` rejection — that is what
2304
+ * makes `EWireConnectFailureKind` trustworthy on both carriers rather than HTTP-only (feedback W3).
2305
+ */
2306
+ function dialFailedError(ws) {
2307
+ return unreachableError(ws, "WebSocket dial failed");
2308
+ }
2309
+ function unreachableError(ws, reason) {
2310
+ return err_wire_connect.fromId("endpoint_unreachable", {
2311
+ url: ws.url != null && ws.url !== "" ? ws.url : void 0,
2312
+ carrierLabel: "ws",
2313
+ reason
2314
+ });
2315
+ }
2316
+ function describeSocket(ws) {
2317
+ return ws.url != null && ws.url !== "" ? ws.url : "(no url)";
2318
+ }
2319
+ /** Accept text + binary frames (ArrayBuffer / Uint8Array / Blob); Blobs are converted to a buffer. */
2320
+ async function normalizeFrame(data) {
2321
+ if (typeof data === "string" || data instanceof ArrayBuffer || data instanceof Uint8Array) return data;
2322
+ if (typeof Blob !== "undefined" && data instanceof Blob) return await data.arrayBuffer();
2323
+ }
2324
+ //#endregion
2281
2325
  //#region ../nice-wire/src/Carrier/duplex/ws/wsCarrier.ts
2282
2326
  /**
2283
2327
  * A WebSocket {@link IWireDuplexCarrierSource}: opens an `arraybuffer` socket (cached per endpoint)
@@ -2322,6 +2366,43 @@ function wsCarrier$1(createRequest, options = {}) {
2322
2366
  };
2323
2367
  }
2324
2368
  //#endregion
2369
+ //#region ../nice-wire/src/Connect/endpointEvidence.ts
2370
+ /**
2371
+ * How much of a non-protocol body an error message may carry. Deliberately short: a WAF's 40 KB
2372
+ * HTML page pasted into an error is worse DX than no preview at all.
2373
+ */
2374
+ const BODY_PREVIEW_LIMIT = 200;
2375
+ /** C0 + DEL + C1 — a raw control character in an error message corrupts terminals and log lines. */
2376
+ const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]+/g;
2377
+ /**
2378
+ * A bounded, single-line, control-character-free head of whatever a non-protocol endpoint sent
2379
+ * back — enough to recognize an HTML error page or a proxy banner on sight. Only the *response* is
2380
+ * ever summarized: no request headers, no request body.
2381
+ */
2382
+ function describeNonProtocolBody(raw) {
2383
+ if (typeof raw !== "string") return void 0;
2384
+ const flattened = raw.replace(CONTROL_CHARS, " ").replace(/\s+/g, " ").trim();
2385
+ if (flattened.length === 0) return void 0;
2386
+ return flattened.length > BODY_PREVIEW_LIMIT ? `${flattened.slice(0, BODY_PREVIEW_LIMIT)}…` : flattened;
2387
+ }
2388
+ /**
2389
+ * Classify a dial failure. Reads typed ids only — the ids are raised at the layer that still holds
2390
+ * the evidence precisely so this never has to sniff message text.
2391
+ */
2392
+ function classifyConnectFailure(error) {
2393
+ if (!err_wire_connect.isExact(error)) return "unknown";
2394
+ if (error.hasId("endpoint_answered_non_protocol")) return "endpoint_answered_non_protocol";
2395
+ if (error.hasId("endpoint_unreachable")) return "endpoint_unreachable";
2396
+ if (error.hasId("identity_pin_mismatch") || error.hasId("handshake_rejected")) return "handshake_rejected";
2397
+ return "unknown";
2398
+ }
2399
+ /** The endpoint a failure names, when it carries one — the URL actually dialed. */
2400
+ function endpointFromConnectFailure(error) {
2401
+ if (!err_wire_connect.isExact(error)) return void 0;
2402
+ if (error.hasId("endpoint_answered_non_protocol")) return error.getContext("endpoint_answered_non_protocol").url;
2403
+ if (error.hasId("endpoint_unreachable")) return error.getContext("endpoint_unreachable").url;
2404
+ }
2405
+ //#endregion
2325
2406
  //#region ../nice-wire/src/Connect/ConnectionTransportManager.ts
2326
2407
  /**
2327
2408
  * Preference-ordered transport selection over a shared connection cache — moved from nice-action
@@ -2363,13 +2444,19 @@ var ConnectionTransportManager$1 = class {
2363
2444
  const cached = this._cache.get(cacheKey);
2364
2445
  if (cached != null) {
2365
2446
  if (cached instanceof Promise) {
2366
- candidates.push(cached);
2447
+ candidates.push({
2448
+ transport,
2449
+ promise: cached
2450
+ });
2367
2451
  continue;
2368
2452
  }
2369
- candidates.push(Promise.resolve({
2370
- ...cached,
2371
- transport
2372
- }));
2453
+ candidates.push({
2454
+ transport,
2455
+ promise: Promise.resolve({
2456
+ ...cached,
2457
+ transport
2458
+ })
2459
+ });
2373
2460
  break;
2374
2461
  }
2375
2462
  }
@@ -2386,10 +2473,13 @@ var ConnectionTransportManager$1 = class {
2386
2473
  if (this._cache.get(cacheKey) === entry) this._cache.delete(cacheKey);
2387
2474
  });
2388
2475
  }
2389
- candidates.push(Promise.resolve({
2390
- methods: readyData,
2391
- transport
2392
- }));
2476
+ candidates.push({
2477
+ transport,
2478
+ promise: Promise.resolve({
2479
+ methods: readyData,
2480
+ transport
2481
+ })
2482
+ });
2393
2483
  break;
2394
2484
  }
2395
2485
  if (statusInfo.status === "unsupported") {
@@ -2417,7 +2507,10 @@ var ConnectionTransportManager$1 = class {
2417
2507
  throw e;
2418
2508
  });
2419
2509
  if (cacheKey != null) this._cache.set(cacheKey, promise);
2420
- candidates.push(promise);
2510
+ candidates.push({
2511
+ transport,
2512
+ promise
2513
+ });
2421
2514
  }
2422
2515
  }
2423
2516
  if (candidates.length === 0) {
@@ -2425,13 +2518,20 @@ var ConnectionTransportManager$1 = class {
2425
2518
  throw this._errors.notFound(input);
2426
2519
  }
2427
2520
  let lastError;
2521
+ let lastTransport;
2428
2522
  for (const candidate of candidates) try {
2429
- return await candidate;
2523
+ return await candidate.promise;
2430
2524
  } catch (e) {
2431
2525
  lastError = e;
2526
+ lastTransport = candidate.transport;
2432
2527
  }
2433
2528
  if (err_wire_connect.isExact(lastError) && (lastError.hasId("dial_unavailable") || lastError.hasId("identity_pin_mismatch"))) throw lastError;
2434
- throw this._errors.initializationFailed(input, describeTransportFailure(lastError), lastError);
2529
+ throw this._errors.initializationFailed(input, {
2530
+ cause: describeTransportFailure(lastError),
2531
+ endpoint: endpointFromConnectFailure(lastError) ?? lastTransport?.getRouteInfo(input)?.url,
2532
+ kind: classifyConnectFailure(lastError),
2533
+ origin: lastError
2534
+ });
2435
2535
  }
2436
2536
  };
2437
2537
  /**
@@ -8305,16 +8405,31 @@ function wireFrameByteSize(frame) {
8305
8405
  * §3). A reject carrying a machine-readable `id` becomes the matching typed `err_wire_connect`
8306
8406
  * error — today `identity_pin_mismatch`, which the transport selection rethrows UNWRAPPED (like
8307
8407
  * `dial_unavailable`) so `err.hasId("identity_pin_mismatch")` works at the `connect()`/dispatch
8308
- * caller and the keep-alive redial loop can park on it. A reject without an id (or from an older
8309
- * peer, whose frames never carry one) keeps the plain-Error shape it always had.
8408
+ * caller and the keep-alive redial loop can park on it. A reject without an id (an older peer,
8409
+ * whose frames never carry one) becomes `handshake_rejected` — same message text, now typed, so
8410
+ * `classifyConnectFailure` can tell "the backend said no" from "wrong address" (feedback W3).
8310
8411
  */
8311
8412
  function handshakeRejectError(stage, rejectFrame) {
8312
8413
  if (rejectFrame.id === "identity_pin_mismatch") return err_wire_connect.fromId("identity_pin_mismatch", { reason: rejectFrame.reason });
8313
- return /* @__PURE__ */ new Error(`[${stage}] rejected by peer: ${rejectFrame.reason}`);
8414
+ return err_wire_connect.fromId("handshake_rejected", {
8415
+ stage,
8416
+ reason: rejectFrame.reason
8417
+ });
8314
8418
  }
8315
8419
  //#endregion
8316
8420
  //#region ../nice-wire/src/Connect/duplexLinkSession.ts
8317
8421
  const HANDSHAKE_TIMEOUT_MS$1 = 15e3;
8422
+ const LINK_HANDSHAKE_STAGE = "link-handshake";
8423
+ /** The duplex twin of the exchange path's `nonProtocolReply` — same typed id, so a consumer's
8424
+ * `kind` branch means the same thing whichever carrier served the dial. */
8425
+ function wrongHandshakeFrame(channel, expected, receivedKind) {
8426
+ return err_wire_connect.fromId("endpoint_answered_non_protocol", {
8427
+ stage: LINK_HANDSHAKE_STAGE,
8428
+ expected,
8429
+ url: channel.label,
8430
+ receivedKind: `hs/${receivedKind}`
8431
+ });
8432
+ }
8318
8433
  /** The literal wire keepalive frames — the acceptor answers raw, before any session dispatch. */
8319
8434
  const KEEPALIVE_PING$1 = "ping";
8320
8435
  const KEEPALIVE_PONG$1 = "pong";
@@ -8457,6 +8572,7 @@ async function establishSecureDuplexSession(ctx) {
8457
8572
  const handshakeQueue = [];
8458
8573
  const handshakeWaiters = [];
8459
8574
  const pendingFrames = [];
8575
+ let nonProtocolFrame;
8460
8576
  let keepalive;
8461
8577
  const mux = ctx.mux;
8462
8578
  channel.attach({
@@ -8487,6 +8603,7 @@ async function establishSecureDuplexSession(ctx) {
8487
8603
  else handshakeQueue.push(message);
8488
8604
  return;
8489
8605
  }
8606
+ nonProtocolFrame ??= frame;
8490
8607
  }
8491
8608
  pendingFrames.push(frame);
8492
8609
  },
@@ -8497,7 +8614,12 @@ async function establishSecureDuplexSession(ctx) {
8497
8614
  const queued = handshakeQueue.shift();
8498
8615
  if (queued != null) return Promise.resolve(queued);
8499
8616
  return new Promise((resolve, reject) => {
8500
- const timeout = setTimeout(() => reject(/* @__PURE__ */ new Error("[link-handshake] timed out waiting for peer reply")), HANDSHAKE_TIMEOUT_MS$1);
8617
+ const timeout = setTimeout(() => reject(nonProtocolFrame != null ? err_wire_connect.fromId("endpoint_answered_non_protocol", {
8618
+ stage: LINK_HANDSHAKE_STAGE,
8619
+ expected: "a handshake frame",
8620
+ url: channel.label,
8621
+ bodyPreview: describeNonProtocolBody(nonProtocolFrame)
8622
+ }) : /* @__PURE__ */ new Error(`[${LINK_HANDSHAKE_STAGE}] timed out waiting for peer reply`)), HANDSHAKE_TIMEOUT_MS$1);
8501
8623
  handshakeWaiters.push((message) => {
8502
8624
  clearTimeout(timeout);
8503
8625
  resolve(message);
@@ -8585,12 +8707,12 @@ async function runClientHandshake(ctx, nextHandshakeMessage) {
8585
8707
  });
8586
8708
  sendHandshake(encodeHandshakeMessage(await handshake.createHello()));
8587
8709
  const welcome = await nextHandshakeMessage();
8588
- if (welcome.t === "reject") throw handshakeRejectError("link-handshake", welcome);
8589
- if (welcome.t !== "welcome") throw new Error(`[link-handshake] expected welcome, got ${welcome.t}`);
8710
+ if (welcome.t === "reject") throw handshakeRejectError(LINK_HANDSHAKE_STAGE, welcome);
8711
+ if (welcome.t !== "welcome") throw wrongHandshakeFrame(ctx.channel, "a welcome frame", welcome.t);
8590
8712
  sendHandshake(encodeHandshakeMessage(await handshake.onWelcome(welcome)));
8591
8713
  const accept = await nextHandshakeMessage();
8592
- if (accept.t === "reject") throw handshakeRejectError("link-handshake", accept);
8593
- if (accept.t !== "accept") throw new Error(`[link-handshake] expected accept, got ${accept.t}`);
8714
+ if (accept.t === "reject") throw handshakeRejectError(LINK_HANDSHAKE_STAGE, accept);
8715
+ if (accept.t !== "accept") throw wrongHandshakeFrame(ctx.channel, "an accept frame", accept.t);
8594
8716
  const result = await handshake.onAccept(accept);
8595
8717
  return {
8596
8718
  crypto: result.securityLevel === "encrypted" && result.encryptionKeyMaterial != null ? createActionFrameCrypto({
@@ -8990,29 +9112,25 @@ async function runConnectorExchangeHandshake(carrier, secure, lane) {
8990
9112
  securityLevel: secure.securityLevel,
8991
9113
  channelTags: lane.channels
8992
9114
  });
8993
- const hello = await handshake.createHello();
8994
- const welcomeReply = decodeExchangeReply(asString(await carrier.exchange(encodeExchange({
9115
+ const welcomeReply = await exchangeHandshakeFrame(carrier, {
8995
9116
  k: "hs",
8996
- m: encodeHandshakeMessage(hello)
8997
- }))));
8998
- if (welcomeReply?.k !== "hs") throw new Error("[exchange-handshake] expected a welcome reply");
9117
+ m: encodeHandshakeMessage(await handshake.createHello())
9118
+ }, "a welcome frame");
8999
9119
  const welcome = decodeHandshakeMessage(welcomeReply.m);
9000
- if (welcome == null) throw new Error("[exchange-handshake] malformed welcome");
9001
- if (welcome.t === "reject") throw handshakeRejectError("exchange-handshake", welcome);
9002
- if (welcome.t !== "welcome") throw new Error(`[exchange-handshake] expected welcome, got ${welcome.t}`);
9003
- if (welcomeReply.hsc == null) throw new Error("[exchange-handshake] welcome missing handshake continuation token");
9004
- const prove = await handshake.onWelcome(welcome);
9005
- const acceptReply = decodeExchangeReply(asString(await carrier.exchange(encodeExchange({
9120
+ if (welcome == null) throw nonProtocolReply(carrier, "a welcome frame", "hs (undecodable)");
9121
+ if (welcome.t === "reject") throw handshakeRejectError(HANDSHAKE_STAGE, welcome);
9122
+ if (welcome.t !== "welcome") throw nonProtocolReply(carrier, "a welcome frame", `hs/${welcome.t}`);
9123
+ if (welcomeReply.hsc == null) throw new Error(`[${HANDSHAKE_STAGE}] welcome missing handshake continuation token${at(carrier)}`);
9124
+ const acceptReply = await exchangeHandshakeFrame(carrier, {
9006
9125
  k: "hs",
9007
- m: encodeHandshakeMessage(prove),
9126
+ m: encodeHandshakeMessage(await handshake.onWelcome(welcome)),
9008
9127
  hsc: welcomeReply.hsc
9009
- }))));
9010
- if (acceptReply?.k !== "hs") throw new Error("[exchange-handshake] expected an accept reply");
9128
+ }, "an accept frame");
9011
9129
  const accept = decodeHandshakeMessage(acceptReply.m);
9012
- if (accept == null) throw new Error("[exchange-handshake] malformed accept");
9013
- if (accept.t === "reject") throw handshakeRejectError("exchange-handshake", accept);
9014
- if (accept.t !== "accept") throw new Error(`[exchange-handshake] expected accept, got ${accept.t}`);
9015
- if (acceptReply.t == null) throw new Error("[exchange-handshake] accept missing session token");
9130
+ if (accept == null) throw nonProtocolReply(carrier, "an accept frame", "hs (undecodable)");
9131
+ if (accept.t === "reject") throw handshakeRejectError(HANDSHAKE_STAGE, accept);
9132
+ if (accept.t !== "accept") throw nonProtocolReply(carrier, "an accept frame", `hs/${accept.t}`);
9133
+ if (acceptReply.t == null) throw new Error(`[${HANDSHAKE_STAGE}] accept missing session token${at(carrier)}`);
9016
9134
  const result = await handshake.onAccept(accept);
9017
9135
  const crypto = result.securityLevel === "encrypted" && result.encryptionKeyMaterial != null ? createActionFrameCrypto({
9018
9136
  link: secure.link,
@@ -9023,6 +9141,42 @@ async function runConnectorExchangeHandshake(carrier, secure, lane) {
9023
9141
  crypto
9024
9142
  };
9025
9143
  }
9144
+ const HANDSHAKE_STAGE = "exchange-handshake";
9145
+ /**
9146
+ * One handshake exchange, with the failure told from the *reply's* point of view (feedback W1).
9147
+ * The reply is in hand at the throw site, so the error says what came back — a frame kind, or a
9148
+ * bounded preview of a body that was never a protocol frame at all — instead of only what we
9149
+ * hoped for. A body preview is attached ONLY when nothing decoded: a decodable `act` envelope may
9150
+ * carry application data, which has no business in a connection error.
9151
+ */
9152
+ async function exchangeHandshakeFrame(carrier, request, expected) {
9153
+ const raw = asString(await carrier.exchange(encodeExchange(request)));
9154
+ const reply = decodeExchangeReply(raw);
9155
+ if (reply == null) throw err_wire_connect.fromId("endpoint_answered_non_protocol", {
9156
+ stage: HANDSHAKE_STAGE,
9157
+ expected,
9158
+ url: carrier.label,
9159
+ bodyPreview: describeNonProtocolBody(raw)
9160
+ });
9161
+ if (reply.k === "err") throw err_wire_connect.fromId("handshake_rejected", {
9162
+ stage: HANDSHAKE_STAGE,
9163
+ reason: reply.message
9164
+ });
9165
+ if (reply.k !== "hs") throw nonProtocolReply(carrier, expected, reply.k);
9166
+ return reply;
9167
+ }
9168
+ function nonProtocolReply(carrier, expected, receivedKind) {
9169
+ return err_wire_connect.fromId("endpoint_answered_non_protocol", {
9170
+ stage: HANDSHAKE_STAGE,
9171
+ expected,
9172
+ url: carrier.label,
9173
+ receivedKind
9174
+ });
9175
+ }
9176
+ /** Make a peer-bug message self-locating without inventing a typed id for it. */
9177
+ function at(carrier) {
9178
+ return carrier.label != null ? ` (endpoint: ${carrier.label})` : "";
9179
+ }
9026
9180
  function asString(frame) {
9027
9181
  if (typeof frame === "string") return frame;
9028
9182
  return textDecoder$1.decode(frame instanceof ArrayBuffer ? new Uint8Array(frame) : frame);
@@ -12497,7 +12651,11 @@ const err_nice_transport = err_nice_action.createChildDomain({
12497
12651
  ["timeout"]: err({ message: ({ timeout }) => `ActionConnect transport timed out after ${timeout}ms.` }),
12498
12652
  ["not_found"]: err({ message: ({ actionId }) => `No connected transport found for action "${actionId}".` }),
12499
12653
  ["unsupported"]: err({ message: ({ transportShapes }) => `${transportShapes.length} Transport(s) [${transportShapes.join(", ")}] found but returned "unsupported" status.` }),
12500
- ["initialization_failed"]: err({ message: ({ actionId, cause }) => `Could not connect any transport for action "${actionId}"${cause != null ? `: ${cause}` : " (all transports failed to initialize)"}.` }),
12654
+ ["initialization_failed"]: err({ message: ({ actionId, cause, endpoint }) => {
12655
+ const head = `Could not connect any transport for action "${actionId}"${endpoint != null ? ` against ${endpoint}` : ""}`;
12656
+ if (cause == null) return `${head} (all transports failed to initialize).`;
12657
+ return `${head}: ${cause}${cause.endsWith(".") ? "" : "."}`;
12658
+ } }),
12501
12659
  ["send_failed"]: err({
12502
12660
  message: ({ actionId, httpStatusCode, message }) => `Failed to send action "${actionId}" [${httpStatusCode ?? "Unknown status"}]: ${message ?? "Unknown error"}.`,
12503
12661
  httpStatusCode: ({ httpStatusCode }) => httpStatusCode ?? 500
@@ -12522,10 +12680,12 @@ var ConnectionTransportManager = class extends ConnectionTransportManager$1 {
12522
12680
  super(cache, {
12523
12681
  unsupported: (transportShapes) => err_nice_transport.fromId("unsupported", { transportShapes }),
12524
12682
  notFound: (input) => err_nice_transport.fromId("not_found", { actionId: input.action == null ? "connect()" : input.action.id }),
12525
- initializationFailed: (input, cause, origin) => err_nice_transport.fromId("initialization_failed", {
12683
+ initializationFailed: (input, failure) => err_nice_transport.fromId("initialization_failed", {
12526
12684
  actionId: input.action == null ? "connect()" : input.action.id,
12527
- cause
12528
- }).withOriginError(origin)
12685
+ cause: failure.cause,
12686
+ endpoint: failure.endpoint,
12687
+ kind: failure.kind
12688
+ }).withOriginError(failure.origin)
12529
12689
  });
12530
12690
  }
12531
12691
  };
@@ -18254,8 +18414,16 @@ function applyPatchesToStore(store, patches) {
18254
18414
  * An updater that returned an object while leaving its draft untouched almost certainly meant
18255
18415
  * exactly that, so it throws here instead. (Concise-arrow returns like `(d) => d.count++` or
18256
18416
  * `(d) => (d.x = value)` modify the draft and stay allowed.)
18417
+ *
18418
+ * **A returned *draft* is not the footgun** — `Object.assign(draft, next)` already applied the
18419
+ * mutation, and returning the draft is merely redundant. Judging it by whether the draft happened
18420
+ * to change made the throw data-dependent: the pattern passed every first run and blew up later
18421
+ * on the one reset where `next` was identical (meteor-connect-bridge feedback S1). Splitting on
18422
+ * draft identity instead is deterministic — a returned draft always passes, a returned
18423
+ * *replacement* with an untouched draft always throws.
18257
18424
  */
18258
- function assertNoReturnedState(returned, draftWasModified) {
18425
+ function assertNoReturnedState(returned, draftWasModified, returnedIsDraft) {
18426
+ if (returnedIsDraft) return;
18259
18427
  if (!draftWasModified && typeof returned === "object" && returned != null) throw new Error("@nice-code/state: an update function returned a value without modifying its draft. Update functions are mutate-only — a returned state is ignored (unlike immer's produce). To reset or swap the state wholesale, use store.replace(next); to change part of it, mutate the draft.");
18260
18428
  }
18261
18429
  /**
@@ -18266,10 +18434,12 @@ function assertNoReturnedState(returned, draftWasModified) {
18266
18434
  function applyUpdaterWithPatches(currentState, updater) {
18267
18435
  if (typeof updater === "function") {
18268
18436
  let returned;
18437
+ let returnedIsDraft = false;
18269
18438
  const [next, patches, inversePatches] = produceWithPatches(currentState, (draft) => {
18270
18439
  returned = updater(draft, currentState);
18440
+ returnedIsDraft = returned === draft;
18271
18441
  });
18272
- assertNoReturnedState(returned, next !== currentState);
18442
+ assertNoReturnedState(returned, next !== currentState, returnedIsDraft);
18273
18443
  return [
18274
18444
  next,
18275
18445
  patches,
@@ -18281,10 +18451,12 @@ function applyUpdaterWithPatches(currentState, updater) {
18281
18451
  const inversePatches = [];
18282
18452
  for (const single of updater) {
18283
18453
  let returned;
18454
+ let returnedIsDraft = false;
18284
18455
  const [next, p, ip] = produceWithPatches(state, (draft) => {
18285
18456
  returned = single(draft, state);
18457
+ returnedIsDraft = returned === draft;
18286
18458
  });
18287
- assertNoReturnedState(returned, next !== state);
18459
+ assertNoReturnedState(returned, next !== state, returnedIsDraft);
18288
18460
  state = next;
18289
18461
  patches.push(...p);
18290
18462
  inversePatches.push(...ip);
@@ -18303,18 +18475,22 @@ function applyUpdaterWithPatches(currentState, updater) {
18303
18475
  function applyUpdater(currentState, updater) {
18304
18476
  if (typeof updater === "function") {
18305
18477
  let returned;
18478
+ let returnedIsDraft = false;
18306
18479
  const next = produce(currentState, (draft) => {
18307
18480
  returned = updater(draft, currentState);
18481
+ returnedIsDraft = returned === draft;
18308
18482
  });
18309
- assertNoReturnedState(returned, next !== currentState);
18483
+ assertNoReturnedState(returned, next !== currentState, returnedIsDraft);
18310
18484
  return next;
18311
18485
  }
18312
18486
  return updater.reduce((previousState, single) => {
18313
18487
  let returned;
18488
+ let returnedIsDraft = false;
18314
18489
  const next = produce(previousState, (draft) => {
18315
18490
  returned = single(draft, previousState);
18491
+ returnedIsDraft = returned === draft;
18316
18492
  });
18317
- assertNoReturnedState(returned, next !== previousState);
18493
+ assertNoReturnedState(returned, next !== previousState, returnedIsDraft);
18318
18494
  return next;
18319
18495
  }, currentState);
18320
18496
  }