@webpieces/http-client-core 0.4.743 → 0.4.745

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/http-client-core",
3
- "version": "0.4.743",
3
+ "version": "0.4.745",
4
4
  "description": "Isomorphic core of the webpieces HTTP client: the decorator-driven ProxyClient, error translation, and the Proxy trap shared by http-client-node and http-client-browser",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -21,6 +21,6 @@
21
21
  "access": "public"
22
22
  },
23
23
  "dependencies": {
24
- "@webpieces/core-util": "0.4.743"
24
+ "@webpieces/core-util": "0.4.745"
25
25
  }
26
26
  }
@@ -27,6 +27,7 @@ export declare abstract class ProxyClient {
27
27
  protected readonly logApiCall: LogApiCallImpl;
28
28
  private routeMap;
29
29
  private apiName;
30
+ private apiClass;
30
31
  /**
31
32
  * The OUTBOUND filter chain, built once at bind time from {@link clientFilters} and reused for
32
33
  * every call. Built once rather than per call because a filter is STATELESS by contract (the
@@ -127,7 +128,7 @@ export declare abstract class ProxyClient {
127
128
  */
128
129
  protected abstract adaptDownstreamFailure(failure: TranslatedFailure, callId: string): Error;
129
130
  /**
130
- * Fires immediately BEFORE `fetch`, once per RPC — the progress "start marker". Symmetric with
131
+ * Fires before the logical call's attempts, once per RPC — the progress "start marker". Symmetric with
131
132
  * {@link onRequestEnd}: every start is followed by exactly one end, on every path, so a listener
132
133
  * can drive a counter (bar on / bar off) without leaking a permanently-spinning bar.
133
134
  *
@@ -140,7 +141,7 @@ export declare abstract class ProxyClient {
140
141
  *
141
142
  * Subsumes the older header-only hook: this is the ONLY place the `fetch` Response — and thus its
142
143
  * `Headers` — exists, so an app that needs to read a response header (e.g. a server-version stamp
143
- * for client↔server version matching) reads `outcome.headers`, still BEFORE the body is consumed
144
+ * for client↔server version matching) reads `outcome.headers` after settlement
144
145
  * and on both the ok and error paths. `outcome.ok`/`outcome.error` add the success-or-error
145
146
  * signal the header-only seam could not give.
146
147
  *
@@ -176,21 +177,11 @@ export declare abstract class ProxyClient {
176
177
  * @throws Error naming the endpoint, what it declared, and who its real caller is.
177
178
  */
178
179
  private refuseEndpointNoClientCanCall;
179
- /**
180
- * Make an HTTP request based on route metadata and arguments.
181
- *
182
- * All endpoints are POST-only. The request body is the first argument.
183
- */
184
- makeRequest(route: RouteMetadata, args: any[]): Promise<any>;
185
- /**
186
- * Execute the fetch request and handle response.
187
- *
188
- * Brackets the call with the lifecycle seam: {@link onRequestStart} once before `fetch`, then
189
- * {@link onRequestEnd} exactly once on each of the three ways a call can settle. The end hook
190
- * fires BEFORE the throw on both failure paths, so a listener always sees the stop marker even
191
- * though the caller sees an exception.
192
- */
193
- private executeFetch;
180
+ /** One logical call: one lifecycle pair and log entry across all strategy attempts. */
181
+ makeRequest(route: RouteMetadata, args: unknown[]): Promise<unknown>;
182
+ private executeCall;
183
+ /** Fresh mutable request for every attempt, including URL, headers, auth and body. */
184
+ private prepareRequest;
194
185
  /**
195
186
  * ONE transmission — the bottom of the filter chain, and the only place `fetch` is called.
196
187
  *
@@ -203,44 +194,6 @@ export declare abstract class ProxyClient {
203
194
  * will, rather than a raw platform reject.
204
195
  */
205
196
  private sendOnce;
206
- /**
207
- * Read a 2xx body, reporting the END marker on both outcomes.
208
- *
209
- * The content-type gate is the same one the error path uses: a 2xx that is not JSON (a proxy's
210
- * captive-portal page, an SPA index.html served by a misrouted CDN) is reported for WHAT ARRIVED,
211
- * instead of `SyntaxError: Unexpected token '<'`, which names nothing a reader can act on.
212
- */
213
- private readSuccessBody;
214
- /**
215
- * Turn a non-2xx response into the error the caller will see, firing the END marker first — so a
216
- * listener always gets its stop marker even though the caller sees an exception. RETURNS the
217
- * error rather than throwing it, which keeps the one `throw` visible at the call site.
218
- *
219
- * The headers still reach the seam here, so a version (or any future) header is observed even on
220
- * error responses.
221
- *
222
- * The body is read through {@link ResponseBodyReader}, which parses ONLY a body whose
223
- * content-type says it is JSON. An infra 502/503/504 (load balancer, proxy, cold start on a
224
- * scale-to-zero backend) serves HTML, and parsing that used to throw `SyntaxError: Unexpected
225
- * token '<'` — discarding the status, so the caller could not tell a booting server from a broken
226
- * client. It now becomes a synthesized ProtocolError translated BY STATUS, i.e. a real
227
- * `HttpBadGatewayError` / `HttpServiceUnavailableError` / `HttpGatewayTimeoutError`.
228
- *
229
- * The try/catch stays, for a NARROWER job than before: a body that DECLARED json and was
230
- * malformed still throws (that one is a genuine server bug), and the END marker must fire for it
231
- * too — an unreported end leaves the app's progress bar spinning forever.
232
- *
233
- * `translated` is what ClientErrorTranslator picked, and translateError RETURNS a
234
- * {@link TranslatedFailure} — so nothing in this seam is ever `unknown`.
235
- *
236
- * The translated failure then goes through {@link adaptDownstreamFailure}, which is where the two
237
- * environments part company (browser rethrows it, node turns a downstream 4xx into its own 500).
238
- *
239
- * The RequestOutcome reported to {@link onRequestEnd} carries the POST-adapt error, deliberately:
240
- * a lifecycle listener must see the SAME error the caller sees, or a progress bar / error toast
241
- * says 404 while the thrown exception says 500. That is the identical rule the network-reject path
242
- * already follows (it classifies BEFORE onRequestEnd for exactly this reason). The pre-adapt error
243
- * is not lost — it is the adapted error's `httpCause`.
244
- */
245
- private endWithTypedFailure;
197
+ /** Body consumption is inside the attempt deadline, including non-JSON error bodies. */
198
+ private readResponse;
246
199
  }
@@ -32,6 +32,7 @@ class ProxyClient {
32
32
  // Assigned by initRoutes(), which every subclass's init() calls immediately after construction.
33
33
  routeMap;
34
34
  apiName;
35
+ apiClass;
35
36
  /**
36
37
  * The OUTBOUND filter chain, built once at bind time from {@link clientFilters} and reused for
37
38
  * every call. Built once rather than per call because a filter is STATELESS by contract (the
@@ -102,7 +103,7 @@ class ProxyClient {
102
103
  return [];
103
104
  }
104
105
  /**
105
- * Fires immediately BEFORE `fetch`, once per RPC — the progress "start marker". Symmetric with
106
+ * Fires before the logical call's attempts, once per RPC — the progress "start marker". Symmetric with
106
107
  * {@link onRequestEnd}: every start is followed by exactly one end, on every path, so a listener
107
108
  * can drive a counter (bar on / bar off) without leaking a permanently-spinning bar.
108
109
  *
@@ -115,7 +116,7 @@ class ProxyClient {
115
116
  *
116
117
  * Subsumes the older header-only hook: this is the ONLY place the `fetch` Response — and thus its
117
118
  * `Headers` — exists, so an app that needs to read a response header (e.g. a server-version stamp
118
- * for client↔server version matching) reads `outcome.headers`, still BEFORE the body is consumed
119
+ * for client↔server version matching) reads `outcome.headers` after settlement
119
120
  * and on both the ok and error paths. `outcome.ok`/`outcome.error` add the success-or-error
120
121
  * signal the header-only seam could not give.
121
122
  *
@@ -135,6 +136,7 @@ class ProxyClient {
135
136
  */
136
137
  initRoutes(apiPrototype, appFilters) {
137
138
  this.appFilters = appFilters;
139
+ this.apiClass = apiPrototype;
138
140
  if (!(0, core_util_1.isApiPath)(apiPrototype)) {
139
141
  const className = apiPrototype.name || 'Unknown';
140
142
  throw new Error(`Class ${className} must be decorated with @ApiPath()`);
@@ -217,82 +219,51 @@ class ProxyClient {
217
219
  // outbound-auth filter asks its bound signer to produce the signature, which is the exact
218
220
  // mirror of the inbound WebhookAuthCallback that verifies one.
219
221
  }
220
- /**
221
- * Make an HTTP request based on route metadata and arguments.
222
- *
223
- * All endpoints are POST-only. The request body is the first argument.
224
- */
225
- // webpieces-disable no-any-unknown -- proxy method: the request DTO (args) + response are erased at the client boundary
222
+ /** One logical call: one lifecycle pair and log entry across all strategy attempts. */
223
+ // webpieces-disable no-any-unknown -- request and response DTOs are erased at the proxy boundary
226
224
  async makeRequest(route, args) {
227
225
  this.refuseEndpointNoClientCanCall(route);
228
- // Resolved per call (memoized underneath on a server), so building a client stayed synchronous.
229
- const baseUrl = await this.resolveBaseUrl();
230
- const httpHeaders = new Map([['Content-Type', 'application/json']]);
231
- // Transferred context, request-id chained. The server impl throws here when there is no
232
- // active RequestContext — an outbound call with no trace is a bug, not a default. The
233
- // destination's own auth mode decides whether trusted keys are part of that set.
234
- const contextHeaders = this.outboundContextHeaders(core_util_1.DestinationTrust.forAuthMode(route.authMeta?.mode));
235
- for (const entry of contextHeaders.entries()) {
236
- httpHeaders.set(entry[0], entry[1]);
237
- }
238
- // NOTHING mints a credential here. The endpoint's outbound auth is a FILTER, sitting at the
239
- // very bottom of the chain, because the URL at this point is only where the call STARTS: an
240
- // app filter above may re-point it, and an OIDC token whose audience is the pre-filter URL
241
- // is a token for the wrong peer. The minter has to run last, against the settled
242
- // destination — see the environment's `clientFilters()`.
243
- //
244
- // POST body is the first argument as JSON. Serialized HERE, before the filter chain, so a
245
- // filter that signs the request signs the exact bytes {@link sendOnce} will transmit.
246
- // webpieces-disable no-any-unknown -- the request DTO's type is erased at the proxy boundary
247
- let requestDto;
248
- let body;
249
- if (args.length > 0) {
250
- requestDto = args[0];
251
- body = JSON.stringify(requestDto);
252
- }
253
- const request = new ClientRequest_1.ClientRequest(route, this.apiName, baseUrl, httpHeaders, body, requestDto);
254
- // Wrap the send in a method for LogApiCall.execute
255
- // webpieces-disable no-any-unknown -- the response DTO's type is erased at the proxy boundary
256
- const method = async () => {
257
- return this.executeFetch(request);
258
- };
259
- return await this.execute(route, requestDto, method);
226
+ const requestDto = args[0];
227
+ return this.execute(route, requestDto, () => this.executeCall(route, requestDto));
260
228
  }
261
- /**
262
- * Execute the fetch request and handle response.
263
- *
264
- * Brackets the call with the lifecycle seam: {@link onRequestStart} once before `fetch`, then
265
- * {@link onRequestEnd} exactly once on each of the three ways a call can settle. The end hook
266
- * fires BEFORE the throw on both failure paths, so a listener always sees the stop marker even
267
- * though the caller sees an exception.
268
- */
269
- // webpieces-disable no-any-unknown -- the response DTO's type is erased at the proxy boundary
270
- async executeFetch(request) {
271
- const route = request.route;
229
+ // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary
230
+ async executeCall(route, requestDto) {
272
231
  this.onRequestStart(route);
273
- // The START marker fires ONCE per RPC even though a filter may send more than once (the SSRF
274
- // guard re-invokes the chain to follow a validated redirect) — start and end still pair up
275
- // exactly, which is what lets a listener drive a progress counter.
276
232
  let response;
277
- // webpieces-disable no-unmanaged-exceptions -- translate a send failure into a lifecycle END, then rethrow
233
+ // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary
234
+ let result;
235
+ // webpieces-disable no-unmanaged-exceptions -- report one logical END, preserving the original thrown value
278
236
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
279
237
  try {
280
- response = await this.chain.execute(request, () => this.sendOnce(request));
238
+ result = await core_util_1.CallRegistry.execute(this.apiClass, route.methodName, (timeoutMs) => {
239
+ response = undefined;
240
+ return core_util_1.CallDeadline.run(timeoutMs, new core_util_1.CallContext(this.apiName, route.methodName), async (signal) => {
241
+ const request = await this.prepareRequest(route, requestDto);
242
+ signal.throwIfAborted();
243
+ const received = await this.chain.execute(request, () => this.sendOnce(request, signal));
244
+ signal.throwIfAborted();
245
+ response = received;
246
+ return this.readResponse(received, route);
247
+ });
248
+ }, 30_000);
281
249
  }
282
250
  catch (err) {
283
- // No Response ever existed — a network reject already classified by sendOnce, or a filter
284
- // that refused to send at all (an SSRF policy rejecting a partner's URL). Either way there
285
- // is no status and no headers to report, only status 0 and the failure itself, and the
286
- // lifecycle listener must see the SAME error the caller is about to.
287
251
  const error = (0, core_util_1.toError)(err);
288
- this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(false, 0, undefined, error));
289
- throw error;
252
+ this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(false, response?.status ?? 0, response?.headers, error));
253
+ throw err;
290
254
  }
291
- const callId = `${this.apiName}.${route.methodName}`;
292
- if (response.ok) {
293
- return this.readSuccessBody(response, route, callId);
294
- }
295
- throw await this.endWithTypedFailure(response, route, callId);
255
+ this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(true, response?.status ?? 0, response?.headers));
256
+ return result;
257
+ }
258
+ /** Fresh mutable request for every attempt, including URL, headers, auth and body. */
259
+ // webpieces-disable no-any-unknown -- request DTO is erased at the proxy boundary
260
+ async prepareRequest(route, requestDto) {
261
+ const baseUrl = await this.resolveBaseUrl();
262
+ const headers = new Map([['Content-Type', 'application/json']]);
263
+ const context = this.outboundContextHeaders(core_util_1.DestinationTrust.forAuthMode(route.authMeta?.mode));
264
+ for (const entry of context.entries())
265
+ headers.set(entry[0], entry[1]);
266
+ return new ClientRequest_1.ClientRequest(route, this.apiName, baseUrl, headers, JSON.stringify(requestDto), requestDto);
296
267
  }
297
268
  /**
298
269
  * ONE transmission — the bottom of the filter chain, and the only place `fetch` is called.
@@ -305,9 +276,11 @@ class ProxyClient {
305
276
  * genuine bug passes through untouched) so that filters above see the same typed error the caller
306
277
  * will, rather than a raw platform reject.
307
278
  */
308
- async sendOnce(request) {
279
+ async sendOnce(request, signal) {
280
+ signal.throwIfAborted();
309
281
  const options = {
310
282
  method: request.route.httpMethod,
283
+ signal,
311
284
  headers: request.headersAsRecord(),
312
285
  redirect: request.followRedirects ? 'follow' : 'manual',
313
286
  };
@@ -325,81 +298,19 @@ class ProxyClient {
325
298
  throw this.networkRejectClassifier.toNetworkError(error, request.url);
326
299
  }
327
300
  }
328
- /**
329
- * Read a 2xx body, reporting the END marker on both outcomes.
330
- *
331
- * The content-type gate is the same one the error path uses: a 2xx that is not JSON (a proxy's
332
- * captive-portal page, an SPA index.html served by a misrouted CDN) is reported for WHAT ARRIVED,
333
- * instead of `SyntaxError: Unexpected token '<'`, which names nothing a reader can act on.
334
- */
335
- // webpieces-disable no-any-unknown -- the response DTO's type is erased at the proxy boundary
336
- async readSuccessBody(response, route, callId) {
337
- // webpieces-disable no-unmanaged-exceptions -- a malformed 2xx body must still report the END marker
338
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
339
- try {
301
+ /** Body consumption is inside the attempt deadline, including non-JSON error bodies. */
302
+ // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary
303
+ async readResponse(response, route) {
304
+ const callId = `${this.apiName}.${route.methodName}`;
305
+ if (response.ok) {
340
306
  if (!this.bodyReader.isJson(response)) {
341
307
  throw new Error(this.bodyReader.describeForeignBody(response, callId, await response.text()));
342
308
  }
343
- const body = await response.json();
344
- this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(true, response.status, response.headers));
345
- return body;
346
- }
347
- catch (err) {
348
- const error = (0, core_util_1.toError)(err);
349
- this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(false, response.status, response.headers, error));
350
- throw error;
351
- }
352
- }
353
- /**
354
- * Turn a non-2xx response into the error the caller will see, firing the END marker first — so a
355
- * listener always gets its stop marker even though the caller sees an exception. RETURNS the
356
- * error rather than throwing it, which keeps the one `throw` visible at the call site.
357
- *
358
- * The headers still reach the seam here, so a version (or any future) header is observed even on
359
- * error responses.
360
- *
361
- * The body is read through {@link ResponseBodyReader}, which parses ONLY a body whose
362
- * content-type says it is JSON. An infra 502/503/504 (load balancer, proxy, cold start on a
363
- * scale-to-zero backend) serves HTML, and parsing that used to throw `SyntaxError: Unexpected
364
- * token '<'` — discarding the status, so the caller could not tell a booting server from a broken
365
- * client. It now becomes a synthesized ProtocolError translated BY STATUS, i.e. a real
366
- * `HttpBadGatewayError` / `HttpServiceUnavailableError` / `HttpGatewayTimeoutError`.
367
- *
368
- * The try/catch stays, for a NARROWER job than before: a body that DECLARED json and was
369
- * malformed still throws (that one is a genuine server bug), and the END marker must fire for it
370
- * too — an unreported end leaves the app's progress bar spinning forever.
371
- *
372
- * `translated` is what ClientErrorTranslator picked, and translateError RETURNS a
373
- * {@link TranslatedFailure} — so nothing in this seam is ever `unknown`.
374
- *
375
- * The translated failure then goes through {@link adaptDownstreamFailure}, which is where the two
376
- * environments part company (browser rethrows it, node turns a downstream 4xx into its own 500).
377
- *
378
- * The RequestOutcome reported to {@link onRequestEnd} carries the POST-adapt error, deliberately:
379
- * a lifecycle listener must see the SAME error the caller sees, or a progress bar / error toast
380
- * says 404 while the thrown exception says 500. That is the identical rule the network-reject path
381
- * already follows (it classifies BEFORE onRequestEnd for exactly this reason). The pre-adapt error
382
- * is not lost — it is the adapted error's `httpCause`.
383
- */
384
- async endWithTypedFailure(response, route, callId) {
385
- let translated;
386
- // webpieces-disable no-unmanaged-exceptions -- a malformed JSON error body must still report the END marker
387
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
388
- try {
389
- const protocolError = await this.bodyReader.readErrorBody(response, callId);
390
- translated = ClientErrorTranslator_1.ClientErrorTranslator.translateError(this.responseDtoFactory.fromFetch(response, protocolError));
391
- }
392
- catch (err) {
393
- const error = (0, core_util_1.toError)(err);
394
- // The response CLAIMED JSON and was not parseable — report that failure as the outcome.
395
- // It never reaches adaptDownstreamFailure: there is no translated status to adapt, and a
396
- // body that broke its own content-type promise is already a defect, not a status answer.
397
- this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(false, response.status, response.headers, error));
398
- return error;
309
+ return response.json();
399
310
  }
400
- const adapted = this.adaptDownstreamFailure(translated, callId);
401
- this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(false, response.status, response.headers, adapted));
402
- return adapted;
311
+ const protocolError = await this.bodyReader.readErrorBody(response, callId);
312
+ const translated = ClientErrorTranslator_1.ClientErrorTranslator.translateError(this.responseDtoFactory.fromFetch(response, protocolError));
313
+ throw this.adaptDownstreamFailure(translated, callId);
403
314
  }
404
315
  }
405
316
  exports.ProxyClient = ProxyClient;
@@ -1 +1 @@
1
- {"version":3,"file":"ProxyClient.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/ProxyClient.ts"],"names":[],"mappings":";;;AAAA,oDAgB8B;AAG9B,mDAAgD;AAChD,mEAAgE;AAChE,qEAAkE;AAClE,qDAAkD;AAClD,6DAA0D;AAG1D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAsB,WAAW;IAwCE;IAvC/B,gGAAgG;IACxF,QAAQ,CAA8B;IACtC,OAAO,CAAU;IAEzB;;;;OAIG;IACK,KAAK,CAAwC;IAErD;;;;;;OAMG;IACO,UAAU,GAA6B,EAAE,CAAC;IAEpD,oFAAoF;IACnE,uBAAuB,GAAG,IAAI,mCAAu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AAC,KAAK,EAAE,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;YAC9F,OAAO,KAAK,CAAC;QACjB,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,sBAAsB,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;QAChE,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,IAAI,+BAAc,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;QAChG,OAAO,OAAO,CAAC;IACnB,CAAC;CACJ;AAvdD,kCAudC","sourcesContent":["import {\n isApiPath,\n getApiPath,\n getEndpoints,\n getAuthMeta,\n isFormPost,\n isRawBody,\n getMaskSpec,\n AuthMeta,\n DestinationTrust,\n RouteMetadata,\n LogApiCallImpl,\n ApiMethodInfo,\n toError,\n NetworkRejectClassifier,\n FilterChain,\n} from '@webpieces/core-util';\nimport { ApiPrototype } from './ApiPrototype';\nimport { ClientFilterDefinition } from './ClientFilter';\nimport { ClientRequest } from './ClientRequest';\nimport { ClientErrorTranslator } from './ClientErrorTranslator';\nimport { HttpResponseDtoFactory } from './HttpResponseDtoFactory';\nimport { RequestOutcome } from './RequestOutcome';\nimport { ResponseBodyReader } from './ResponseBodyReader';\nimport { TranslatedFailure } from './TranslatedFailure';\n\n/**\n * ProxyClient - the HTTP call engine behind one API contract's client proxy.\n *\n * Contains ONLY what a browser can run: the route map built from the contract's decorators, URL\n * assembly, `fetch`, error translation, and logging. It holds no context object, no credentials,\n * and no recorder — it ASKS ITSELF for those through the hooks below, and each subclass answers\n * from its own environment.\n *\n * That is why the class is abstract rather than parameterized by a collaborator: a shared\n * header-provider seam would drag Node's AsyncLocalStorage vocabulary into a browser bundle and the\n * browser's store vocabulary into a server, and neither has any use for the other.\n *\n * NodeProxyClient (@webpieces/http-client-node) -> RequestContext, Secrets, mintIdToken, recording\n * BrowserProxyClient (@webpieces/http-client-browser) -> an app-held store, no credentials, no recording\n *\n * TWO-PHASE: collaborators arrive on the subclass constructor (so a DI container can supply them),\n * while the per-client state — which contract, which target — arrives on the subclass's `init`,\n * which calls {@link initRoutes}. That is what lets a factory hold a `Provider<ProxyClient>` and\n * hand out a fresh, independently-configured client per contract.\n */\nexport abstract class ProxyClient {\n // Assigned by initRoutes(), which every subclass's init() calls immediately after construction.\n private routeMap!: Map<string, RouteMetadata>;\n private apiName!: string;\n\n /**\n * The OUTBOUND filter chain, built once at bind time from {@link clientFilters} and reused for\n * every call. Built once rather than per call because a filter is STATELESS by contract (the\n * per-call state is the {@link ClientRequest} the chain is handed), exactly as on the server.\n */\n private chain!: FilterChain<ClientRequest, Response>;\n\n /**\n * The app's own filters, as handed to `createRpcClient`. Set by {@link initRoutes} BEFORE it\n * calls {@link clientFilters}, so an environment's built-ins may read the app's intent off them\n * — @webpieces/http-client-node takes the SSRF policy from an installed `ContextBaseUrlFilter`\n * that way, which keeps the one legitimate relaxation at the same construction site as the\n * decision to be re-pointable at all.\n */\n protected appFilters: ClientFilterDefinition[] = [];\n\n // Stateless + dependency-free, so the browser bundle keeps no DI on the fetch path.\n private readonly networkRejectClassifier = new NetworkRejectClassifier();\n\n // Same shape and same reason: stateless, so it is constructed here rather than injected.\n private readonly bodyReader = new ResponseBodyReader();\n\n /**\n * fetch `Response` -> the transport-neutral {@link HttpResponseDto} an app's `ErrorTranslators`\n * sees. Normalising HERE is what makes `fromWire` receive the identical shape in node and in the\n * browser: both environments share this class, and this is the only place either builds a DTO.\n */\n private readonly responseDtoFactory = new HttpResponseDtoFactory();\n\n /**\n * @param logApiCall - built by the SUBCLASS's package around that environment's ApiCallContext\n * (node: RequestContextApiCallContext; browser: BrowserApiCallContext). REQUIRED, with no\n * default: core-util cannot construct either one, and a default here would have to reach for a\n * process-global — which is exactly the throw-on-first-call this parameter deleted.\n */\n constructor(protected readonly logApiCall: LogApiCallImpl) {}\n\n // ---------------------------------------------------------------- environment hooks\n\n /** The callee's base URL. Async because a server may derive it from container metadata. */\n protected abstract resolveBaseUrl(): Promise<string>;\n\n /**\n * Context headers to put on the wire. Server reads RequestContext; browser reads its store.\n *\n * `destination` is derived from THIS route's auth mode and decides whether TRUSTED context keys\n * (`x-user-id`, `x-org-id`, `x-webpieces-roles`) may ride along — see {@link DestinationTrust}.\n * It is a required argument on purpose: a defaulted \"send everything\" would put the permissive\n * answer one keystroke away and make the safe one opt-in.\n *\n * RENAMED from `outboundHeaders()` in the same change that added `destination`, and the rename IS\n * the migration. TypeScript accepts an override that declares FEWER parameters than its base, so a\n * downstream `protected override outboundHeaders(): Map<string, string>` would have kept compiling\n * and silently ignored the gate — the permissive behaviour surviving as a second spelling. Against\n * the NEW name that subclass fails twice over: `override` names a member the base no longer has,\n * and this abstract member is left unimplemented.\n */\n protected abstract outboundContextHeaders(destination: DestinationTrust): Map<string, string>;\n\n /**\n * Run the call. The default just logs it. Test-case RECORDING is a server concept, so\n * NodeProxyClient overrides this to capture the call when a recorder is in the context.\n *\n * Context fields are NOT passed in: a logging backend stamps them onto every record itself.\n */\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n protected async execute(\n route: RouteMetadata,\n requestDto: unknown,\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n method: () => Promise<unknown>,\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n ): Promise<unknown> {\n // apiClass = the CONTRACT name (this.apiName, e.g. 'SaveApi') so this client log line MATCHES\n // the server's for the same call. A client has no impl class, so controllerName is omitted.\n const info = new ApiMethodInfo('client', this.apiName, route.methodName, undefined, route.mask);\n return this.logApiCall.execute(info, requestDto, method);\n }\n\n /**\n * Reject, at bind time, an endpoint this environment cannot satisfy — e.g. a browser cannot\n * mint the OIDC token an @AuthOidc endpoint demands. Surfacing it here beats failing on the\n * first call in production. The default accepts everything.\n */\n protected assertEndpointSupported(_authMeta: AuthMeta | undefined, _methodName: string): void {}\n\n /**\n * The FRAMEWORK filters this environment installs on every client it builds, BENEATH whatever\n * the app passed to `createRpcClient`. The default installs none, so the browser runs the exact\n * code path it ran before the chain existed.\n *\n * \"Beneath\" is not a priority — see {@link initRoutes}. These are the filters that must judge\n * and sign what is ACTUALLY about to be sent, so no app priority may be allowed to get under\n * them: @webpieces/http-client-node installs its SSRF guard and its outbound-auth minter here,\n * and both would be defeated by an app filter that re-pointed the URL below them. Neither\n * concept can live in this class, because reading a RequestContext, resolving DNS and minting\n * an OIDC token are all things a browser bundle must never contain.\n */\n protected clientFilters(): ClientFilterDefinition[] {\n return [];\n }\n\n /**\n * Adapt a translated downstream failure into the error THIS environment's caller should see.\n *\n * THE INVARIANT, and the reason this hook exists at all:\n *\n * A status received from a downstream dependency describes OUR request to it. It is never the\n * status we return to OUR caller. The server that answered 404 is correct; the server that\n * asked for a route that does not exist is broken, and must say so as a 500.\n *\n * That invariant reads differently in the two environments, which is exactly why the ISOMORPHIC\n * {@link ClientErrorTranslator} cannot settle it:\n * - BROWSER: the client IS the end user's agent, so the downstream IS the answer. Pass it through\n * unchanged.\n * - NODE: server-to-server. A 4xx from a dependency is a caller-side defect (wrong path, wrong\n * base URL, an undeployed dependency, bad service credentials), so the caller owns it as a 500.\n *\n * ABSTRACT, not a defaulted pass-through, for the same reason\n * {@link outboundContextHeaders} takes a required `destination`: a permissive default puts the\n * wrong answer one keystroke away. A new environment subclass must SAY which of the two it is,\n * and there are exactly two subclasses in the repo, so the compile error is the migration.\n *\n * @param failure - the translated error, its provenance (app-registered vs built-in), and the\n * downstream status\n * @param callId - `ApiName.methodName`, so a rewritten message can still name the call\n */\n protected abstract adaptDownstreamFailure(failure: TranslatedFailure, callId: string): Error;\n\n /**\n * Fires immediately BEFORE `fetch`, once per RPC — the progress \"start marker\". Symmetric with\n * {@link onRequestEnd}: every start is followed by exactly one end, on every path, so a listener\n * can drive a counter (bar on / bar off) without leaking a permanently-spinning bar.\n *\n * The default is a no-op, so every existing subclass is unaffected.\n */\n protected onRequestStart(_route: RouteMetadata): void {}\n\n /**\n * Fires exactly ONCE after the call settles, on EVERY path (2xx, HTTP error, network reject) —\n * the \"stop marker\", carrying how it settled.\n *\n * Subsumes the older header-only hook: this is the ONLY place the `fetch` Response — and thus its\n * `Headers` — exists, so an app that needs to read a response header (e.g. a server-version stamp\n * for client↔server version matching) reads `outcome.headers`, still BEFORE the body is consumed\n * and on both the ok and error paths. `outcome.ok`/`outcome.error` add the success-or-error\n * signal the header-only seam could not give.\n *\n * The default is a no-op, so every existing subclass is unaffected.\n */\n protected onRequestEnd(_route: RouteMetadata, _outcome: RequestOutcome): void {}\n\n // ---------------------------------------------------------------- contract binding\n\n /**\n * Bind this client to one API contract: read @ApiPath/@Endpoint/@Auth* off the prototype and\n * build the route map once. Each subclass's `init(api, config)` stores its own config, then\n * calls this.\n *\n * @param appFilters the app's OUTBOUND filters for this client, from `createRpcClient`. They are\n * merged with {@link clientFilters} and sorted by priority, highest OUTERMOST.\n * @throws Error if the prototype lacks @ApiPath, or declares an endpoint this environment\n * cannot satisfy (see {@link assertEndpointSupported}).\n */\n protected initRoutes(apiPrototype: ApiPrototype<object>, appFilters: ClientFilterDefinition[]): void {\n this.appFilters = appFilters;\n if (!isApiPath(apiPrototype)) {\n const className = apiPrototype.name || 'Unknown';\n throw new Error(`Class ${className} must be decorated with @ApiPath()`);\n }\n\n const basePath = getApiPath(apiPrototype)!;\n const endpoints = getEndpoints(apiPrototype) || {};\n\n // apiName as the class name so client logs read \"SaveApi.save\", not \"undefined.save\"\n this.apiName = apiPrototype.name || 'UnknownApi';\n\n this.routeMap = new Map<string, RouteMetadata>();\n for (const [methodName, endpointPath] of Object.entries(endpoints)) {\n const fullPath = basePath + endpointPath;\n // Capture the endpoint's auth mode so the client can mint delivery auth per\n // @AuthOidc / @AuthSharedSecret, exactly as the server verifies it.\n const authMeta = getAuthMeta(apiPrototype, methodName);\n this.assertEndpointSupported(authMeta, methodName);\n const formPost = isFormPost(apiPrototype, methodName);\n this.routeMap.set(\n methodName,\n new RouteMetadata(\n 'POST', fullPath, methodName, this.apiName, authMeta, undefined, formPost,\n getMaskSpec(apiPrototype, methodName), isRawBody(apiPrototype, methodName),\n ),\n );\n }\n\n // APP filters first (highest priority OUTERMOST, matching the server's FilterMatcher), then\n // the framework built-ins, ALWAYS innermost. Two separate sorts rather than one over the\n // union, deliberately: an app priority orders app filters against each other and nothing\n // else, so no number an app can type — however large — gets underneath the SSRF guard or the\n // credential minter. A single sorted list would make \"displace the guard\" a matter of typing\n // a bigger integer, and a security control an app can outrank by accident is not a control.\n //\n // Sorted here, once, so FilterChain itself never sorts — priority lives on the DEFINITION,\n // not on the filter.\n const byPriority = (a: ClientFilterDefinition, b: ClientFilterDefinition): number =>\n b.priority - a.priority;\n const ordered = [...[...this.appFilters].sort(byPriority), ...[...this.clientFilters()].sort(byPriority)];\n this.chain = new FilterChain<ClientRequest, Response>(\n ordered.map((definition: ClientFilterDefinition) => definition.filter),\n );\n }\n\n /** The contract's class name, for logs and recordings. */\n protected contractName(): string {\n return this.apiName;\n }\n\n /** Check if a route exists for the given method name. */\n hasRoute(methodName: string): boolean {\n return this.routeMap.has(methodName);\n }\n\n /**\n * Get route metadata for a method name.\n * @throws Error if no route found\n */\n getRoute(methodName: string): RouteMetadata {\n const route = this.routeMap.get(methodName);\n if (!route) {\n throw new Error(`No route found for method ${methodName}`);\n }\n return route;\n }\n\n // ---------------------------------------------------------------- the call\n\n /**\n * FAIL FAST, PER METHOD, at call time: some endpoints exist for a caller that is not us, and this\n * proxy could only ever build a request they are obliged to reject. Refusing here rather than at\n * bind time means an api that MIXES such endpoints with normal ones still yields a working client\n * for the normal ones; only calling the un-callable method throws.\n *\n * @throws Error naming the endpoint, what it declared, and who its real caller is.\n */\n private refuseEndpointNoClientCanCall(route: RouteMetadata): void {\n // formPost exists ONLY for EXTERNAL inbound webhooks (e.g. Twilio is the caller). This proxy\n // JSON.stringifies the body, so calling one would silently send a wrong-encoded body.\n if (route.formPost) {\n throw new Error(\n `${this.apiName}.${route.methodName} is @Endpoint(..., { formPost: true }) — the ` +\n `webpieces client does not support calling form-encoded endpoints yet. formPost is ` +\n `for EXTERNAL inbound webhooks (e.g. Twilio) only. If this endpoint needs a ` +\n `service-to-service client, set formPost:false (or remove it) so it uses JSON.`,\n );\n }\n const authMode = route.authMeta?.mode;\n // @AuthApiKey: the credential is a CUSTOMER-held key, and the header carrying it is the app's\n // ApiKeyHook's choice, so this client has nothing to send and the call is a guaranteed 401.\n if (authMode?.kind === 'apikey') {\n throw new Error(\n `${this.apiName}.${route.methodName} is @AuthApiKey('${authMode.regime}') — only the partner ` +\n `holding that api key can call it, and the header carrying it is the app's ApiKeyHook's choice, ` +\n `so a webpieces client has no credential to send.`,\n );\n }\n // @AuthWebhook is DELIBERATELY absent from this list. It used to be here, on the assumption\n // that the vendor is always somebody else — but `@AuthWebhook(name)` names a signing SCHEME,\n // not a direction, and for an OUTBOUND partner webhook WE are the vendor. The environment's\n // outbound-auth filter asks its bound signer to produce the signature, which is the exact\n // mirror of the inbound WebhookAuthCallback that verifies one.\n }\n\n /**\n * Make an HTTP request based on route metadata and arguments.\n *\n * All endpoints are POST-only. The request body is the first argument.\n */\n // webpieces-disable no-any-unknown -- proxy method: the request DTO (args) + response are erased at the client boundary\n async makeRequest(route: RouteMetadata, args: any[]): Promise<any> {\n this.refuseEndpointNoClientCanCall(route);\n // Resolved per call (memoized underneath on a server), so building a client stayed synchronous.\n const baseUrl = await this.resolveBaseUrl();\n\n const httpHeaders = new Map<string, string>([['Content-Type', 'application/json']]);\n\n // Transferred context, request-id chained. The server impl throws here when there is no\n // active RequestContext — an outbound call with no trace is a bug, not a default. The\n // destination's own auth mode decides whether trusted keys are part of that set.\n const contextHeaders = this.outboundContextHeaders(DestinationTrust.forAuthMode(route.authMeta?.mode));\n for (const entry of contextHeaders.entries()) {\n httpHeaders.set(entry[0], entry[1]);\n }\n\n // NOTHING mints a credential here. The endpoint's outbound auth is a FILTER, sitting at the\n // very bottom of the chain, because the URL at this point is only where the call STARTS: an\n // app filter above may re-point it, and an OIDC token whose audience is the pre-filter URL\n // is a token for the wrong peer. The minter has to run last, against the settled\n // destination — see the environment's `clientFilters()`.\n //\n // POST body is the first argument as JSON. Serialized HERE, before the filter chain, so a\n // filter that signs the request signs the exact bytes {@link sendOnce} will transmit.\n // webpieces-disable no-any-unknown -- the request DTO's type is erased at the proxy boundary\n let requestDto: unknown;\n let body: string | undefined;\n if (args.length > 0) {\n requestDto = args[0];\n body = JSON.stringify(requestDto);\n }\n\n const request = new ClientRequest(route, this.apiName, baseUrl, httpHeaders, body, requestDto);\n\n // Wrap the send in a method for LogApiCall.execute\n // webpieces-disable no-any-unknown -- the response DTO's type is erased at the proxy boundary\n const method = async (): Promise<unknown> => {\n return this.executeFetch(request);\n };\n\n return await this.execute(route, requestDto, method);\n }\n\n /**\n * Execute the fetch request and handle response.\n *\n * Brackets the call with the lifecycle seam: {@link onRequestStart} once before `fetch`, then\n * {@link onRequestEnd} exactly once on each of the three ways a call can settle. The end hook\n * fires BEFORE the throw on both failure paths, so a listener always sees the stop marker even\n * though the caller sees an exception.\n */\n // webpieces-disable no-any-unknown -- the response DTO's type is erased at the proxy boundary\n private async executeFetch(request: ClientRequest): Promise<unknown> {\n const route = request.route;\n this.onRequestStart(route);\n\n // The START marker fires ONCE per RPC even though a filter may send more than once (the SSRF\n // guard re-invokes the chain to follow a validated redirect) — start and end still pair up\n // exactly, which is what lets a listener drive a progress counter.\n let response: Response;\n // webpieces-disable no-unmanaged-exceptions -- translate a send failure into a lifecycle END, then rethrow\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n response = await this.chain.execute(request, () => this.sendOnce(request));\n } catch (err: unknown) {\n // No Response ever existed — a network reject already classified by sendOnce, or a filter\n // that refused to send at all (an SSRF policy rejecting a partner's URL). Either way there\n // is no status and no headers to report, only status 0 and the failure itself, and the\n // lifecycle listener must see the SAME error the caller is about to.\n const error = toError(err);\n this.onRequestEnd(route, new RequestOutcome(false, 0, undefined, error));\n throw error;\n }\n\n const callId = `${this.apiName}.${route.methodName}`;\n if (response.ok) {\n return this.readSuccessBody(response, route, callId);\n }\n throw await this.endWithTypedFailure(response, route, callId);\n }\n\n /**\n * ONE transmission — the bottom of the filter chain, and the only place `fetch` is called.\n *\n * Everything it sends comes off the {@link ClientRequest} as the chain left it, so a filter's\n * edits to the url, the headers or the serialized body are exactly what goes on the wire. It may\n * run more than once for a single RPC when a filter follows a redirect.\n *\n * A network reject (offline, DNS, CORS preflight) is classified into a typed OfflineError here (a\n * genuine bug passes through untouched) so that filters above see the same typed error the caller\n * will, rather than a raw platform reject.\n */\n private async sendOnce(request: ClientRequest): Promise<Response> {\n const options: RequestInit = {\n method: request.route.httpMethod,\n headers: request.headersAsRecord(),\n redirect: request.followRedirects ? 'follow' : 'manual',\n };\n if (request.body !== undefined) {\n options.body = request.body;\n }\n // webpieces-disable no-unmanaged-exceptions -- classify a network reject, then rethrow it typed\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-fetch -- this IS the generated-client implementation the rule points everyone to\n return await fetch(request.url, options);\n } catch (err: unknown) {\n const error = toError(err);\n throw this.networkRejectClassifier.toNetworkError(error, request.url);\n }\n }\n\n /**\n * Read a 2xx body, reporting the END marker on both outcomes.\n *\n * The content-type gate is the same one the error path uses: a 2xx that is not JSON (a proxy's\n * captive-portal page, an SPA index.html served by a misrouted CDN) is reported for WHAT ARRIVED,\n * instead of `SyntaxError: Unexpected token '<'`, which names nothing a reader can act on.\n */\n // webpieces-disable no-any-unknown -- the response DTO's type is erased at the proxy boundary\n private async readSuccessBody(response: Response, route: RouteMetadata, callId: string): Promise<unknown> {\n // webpieces-disable no-unmanaged-exceptions -- a malformed 2xx body must still report the END marker\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!this.bodyReader.isJson(response)) {\n throw new Error(this.bodyReader.describeForeignBody(response, callId, await response.text()));\n }\n const body = await response.json();\n this.onRequestEnd(route, new RequestOutcome(true, response.status, response.headers));\n return body;\n } catch (err: unknown) {\n const error = toError(err);\n this.onRequestEnd(route, new RequestOutcome(false, response.status, response.headers, error));\n throw error;\n }\n }\n\n /**\n * Turn a non-2xx response into the error the caller will see, firing the END marker first — so a\n * listener always gets its stop marker even though the caller sees an exception. RETURNS the\n * error rather than throwing it, which keeps the one `throw` visible at the call site.\n *\n * The headers still reach the seam here, so a version (or any future) header is observed even on\n * error responses.\n *\n * The body is read through {@link ResponseBodyReader}, which parses ONLY a body whose\n * content-type says it is JSON. An infra 502/503/504 (load balancer, proxy, cold start on a\n * scale-to-zero backend) serves HTML, and parsing that used to throw `SyntaxError: Unexpected\n * token '<'` — discarding the status, so the caller could not tell a booting server from a broken\n * client. It now becomes a synthesized ProtocolError translated BY STATUS, i.e. a real\n * `HttpBadGatewayError` / `HttpServiceUnavailableError` / `HttpGatewayTimeoutError`.\n *\n * The try/catch stays, for a NARROWER job than before: a body that DECLARED json and was\n * malformed still throws (that one is a genuine server bug), and the END marker must fire for it\n * too — an unreported end leaves the app's progress bar spinning forever.\n *\n * `translated` is what ClientErrorTranslator picked, and translateError RETURNS a\n * {@link TranslatedFailure} — so nothing in this seam is ever `unknown`.\n *\n * The translated failure then goes through {@link adaptDownstreamFailure}, which is where the two\n * environments part company (browser rethrows it, node turns a downstream 4xx into its own 500).\n *\n * The RequestOutcome reported to {@link onRequestEnd} carries the POST-adapt error, deliberately:\n * a lifecycle listener must see the SAME error the caller sees, or a progress bar / error toast\n * says 404 while the thrown exception says 500. That is the identical rule the network-reject path\n * already follows (it classifies BEFORE onRequestEnd for exactly this reason). The pre-adapt error\n * is not lost — it is the adapted error's `httpCause`.\n */\n private async endWithTypedFailure(response: Response, route: RouteMetadata, callId: string): Promise<Error> {\n let translated: TranslatedFailure;\n // webpieces-disable no-unmanaged-exceptions -- a malformed JSON error body must still report the END marker\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const protocolError = await this.bodyReader.readErrorBody(response, callId);\n translated = ClientErrorTranslator.translateError(\n this.responseDtoFactory.fromFetch(response, protocolError),\n );\n } catch (err: unknown) {\n const error = toError(err);\n // The response CLAIMED JSON and was not parseable — report that failure as the outcome.\n // It never reaches adaptDownstreamFailure: there is no translated status to adapt, and a\n // body that broke its own content-type promise is already a defect, not a status answer.\n this.onRequestEnd(route, new RequestOutcome(false, response.status, response.headers, error));\n return error;\n }\n\n const adapted = this.adaptDownstreamFailure(translated, callId);\n this.onRequestEnd(route, new RequestOutcome(false, response.status, response.headers, adapted));\n return adapted;\n }\n}\n"]}
1
+ {"version":3,"file":"ProxyClient.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/ProxyClient.ts"],"names":[],"mappings":";;;AAAA,oDAmB8B;AAG9B,mDAAgD;AAChD,mEAAgE;AAChE,qEAAkE;AAClE,qDAAkD;AAClD,6DAA0D;AAG1D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAsB,WAAW;IAyCE;IAxC/B,gGAAgG;IACxF,QAAQ,CAA8B;IACtC,OAAO,CAAU;IACjB,QAAQ,CAAwB;IAExC;;;;OAIG;IACK,KAAK,CAAwC;IAErD;;;;;;OAMG;IACO,UAAU,GAA6B,EAAE,CAAC;IAEpD,oFAAoF;IACnE,uBAAuB,GAAG,IAAI,mCAAuB,EAAE,CAAC;IAEzE,yFAAyF;IACxE,UAAU,GAAG,IAAI,uCAAkB,EAAE,CAAC;IAEvD;;;;OAIG;IACc,kBAAkB,GAAG,IAAI,+CAAsB,EAAE,CAAC;IAEnE;;;;;OAKG;IACH,YAA+B,UAA0B;QAA1B,eAAU,GAAV,UAAU,CAAgB;IAAG,CAAC;IAwB7D;;;;;OAKG;IACH,iFAAiF;IACvE,KAAK,CAAC,OAAO,CACnB,KAAoB,EACpB,UAAmB;IACnB,iFAAiF;IACjF,MAA8B;QAG9B,8FAA8F;QAC9F,4FAA4F;QAC5F,MAAM,IAAI,GAAG,IAAI,yBAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,OAAO,EA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CAAC,UAAU,CAAC,aAAa,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAC5E,MAAM,UAAU,GAAG,6CAAqB,CAAC,cAAc,CACnD,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,QAAQ,EAAE,aAAa,CAAC,CAC7D,CAAC;QACF,MAAM,IAAI,CAAC,sBAAsB,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IAC1D,CAAC;CACJ;AAvXD,kCAuXC","sourcesContent":["import {\n isApiPath,\n getApiPath,\n getEndpoints,\n getAuthMeta,\n isFormPost,\n isRawBody,\n getMaskSpec,\n AuthMeta,\n DestinationTrust,\n RouteMetadata,\n LogApiCallImpl,\n ApiMethodInfo,\n toError,\n NetworkRejectClassifier,\n FilterChain,\n CallRegistry,\n CallDeadline,\n CallContext,\n} from '@webpieces/core-util';\nimport { ApiPrototype } from './ApiPrototype';\nimport { ClientFilterDefinition } from './ClientFilter';\nimport { ClientRequest } from './ClientRequest';\nimport { ClientErrorTranslator } from './ClientErrorTranslator';\nimport { HttpResponseDtoFactory } from './HttpResponseDtoFactory';\nimport { RequestOutcome } from './RequestOutcome';\nimport { ResponseBodyReader } from './ResponseBodyReader';\nimport { TranslatedFailure } from './TranslatedFailure';\n\n/**\n * ProxyClient - the HTTP call engine behind one API contract's client proxy.\n *\n * Contains ONLY what a browser can run: the route map built from the contract's decorators, URL\n * assembly, `fetch`, error translation, and logging. It holds no context object, no credentials,\n * and no recorder — it ASKS ITSELF for those through the hooks below, and each subclass answers\n * from its own environment.\n *\n * That is why the class is abstract rather than parameterized by a collaborator: a shared\n * header-provider seam would drag Node's AsyncLocalStorage vocabulary into a browser bundle and the\n * browser's store vocabulary into a server, and neither has any use for the other.\n *\n * NodeProxyClient (@webpieces/http-client-node) -> RequestContext, Secrets, mintIdToken, recording\n * BrowserProxyClient (@webpieces/http-client-browser) -> an app-held store, no credentials, no recording\n *\n * TWO-PHASE: collaborators arrive on the subclass constructor (so a DI container can supply them),\n * while the per-client state — which contract, which target — arrives on the subclass's `init`,\n * which calls {@link initRoutes}. That is what lets a factory hold a `Provider<ProxyClient>` and\n * hand out a fresh, independently-configured client per contract.\n */\nexport abstract class ProxyClient {\n // Assigned by initRoutes(), which every subclass's init() calls immediately after construction.\n private routeMap!: Map<string, RouteMetadata>;\n private apiName!: string;\n private apiClass!: ApiPrototype<object>;\n\n /**\n * The OUTBOUND filter chain, built once at bind time from {@link clientFilters} and reused for\n * every call. Built once rather than per call because a filter is STATELESS by contract (the\n * per-call state is the {@link ClientRequest} the chain is handed), exactly as on the server.\n */\n private chain!: FilterChain<ClientRequest, Response>;\n\n /**\n * The app's own filters, as handed to `createRpcClient`. Set by {@link initRoutes} BEFORE it\n * calls {@link clientFilters}, so an environment's built-ins may read the app's intent off them\n * — @webpieces/http-client-node takes the SSRF policy from an installed `ContextBaseUrlFilter`\n * that way, which keeps the one legitimate relaxation at the same construction site as the\n * decision to be re-pointable at all.\n */\n protected appFilters: ClientFilterDefinition[] = [];\n\n // Stateless + dependency-free, so the browser bundle keeps no DI on the fetch path.\n private readonly networkRejectClassifier = new NetworkRejectClassifier();\n\n // Same shape and same reason: stateless, so it is constructed here rather than injected.\n private readonly bodyReader = new ResponseBodyReader();\n\n /**\n * fetch `Response` -> the transport-neutral {@link HttpResponseDto} an app's `ErrorTranslators`\n * sees. Normalising HERE is what makes `fromWire` receive the identical shape in node and in the\n * browser: both environments share this class, and this is the only place either builds a DTO.\n */\n private readonly responseDtoFactory = new HttpResponseDtoFactory();\n\n /**\n * @param logApiCall - built by the SUBCLASS's package around that environment's ApiCallContext\n * (node: RequestContextApiCallContext; browser: BrowserApiCallContext). REQUIRED, with no\n * default: core-util cannot construct either one, and a default here would have to reach for a\n * process-global — which is exactly the throw-on-first-call this parameter deleted.\n */\n constructor(protected readonly logApiCall: LogApiCallImpl) {}\n\n // ---------------------------------------------------------------- environment hooks\n\n /** The callee's base URL. Async because a server may derive it from container metadata. */\n protected abstract resolveBaseUrl(): Promise<string>;\n\n /**\n * Context headers to put on the wire. Server reads RequestContext; browser reads its store.\n *\n * `destination` is derived from THIS route's auth mode and decides whether TRUSTED context keys\n * (`x-user-id`, `x-org-id`, `x-webpieces-roles`) may ride along — see {@link DestinationTrust}.\n * It is a required argument on purpose: a defaulted \"send everything\" would put the permissive\n * answer one keystroke away and make the safe one opt-in.\n *\n * RENAMED from `outboundHeaders()` in the same change that added `destination`, and the rename IS\n * the migration. TypeScript accepts an override that declares FEWER parameters than its base, so a\n * downstream `protected override outboundHeaders(): Map<string, string>` would have kept compiling\n * and silently ignored the gate — the permissive behaviour surviving as a second spelling. Against\n * the NEW name that subclass fails twice over: `override` names a member the base no longer has,\n * and this abstract member is left unimplemented.\n */\n protected abstract outboundContextHeaders(destination: DestinationTrust): Map<string, string>;\n\n /**\n * Run the call. The default just logs it. Test-case RECORDING is a server concept, so\n * NodeProxyClient overrides this to capture the call when a recorder is in the context.\n *\n * Context fields are NOT passed in: a logging backend stamps them onto every record itself.\n */\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n protected async execute(\n route: RouteMetadata,\n requestDto: unknown,\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n method: () => Promise<unknown>,\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n ): Promise<unknown> {\n // apiClass = the CONTRACT name (this.apiName, e.g. 'SaveApi') so this client log line MATCHES\n // the server's for the same call. A client has no impl class, so controllerName is omitted.\n const info = new ApiMethodInfo('client', this.apiName, route.methodName, undefined, route.mask);\n return this.logApiCall.execute(info, requestDto, method);\n }\n\n /**\n * Reject, at bind time, an endpoint this environment cannot satisfy — e.g. a browser cannot\n * mint the OIDC token an @AuthOidc endpoint demands. Surfacing it here beats failing on the\n * first call in production. The default accepts everything.\n */\n protected assertEndpointSupported(_authMeta: AuthMeta | undefined, _methodName: string): void {}\n\n /**\n * The FRAMEWORK filters this environment installs on every client it builds, BENEATH whatever\n * the app passed to `createRpcClient`. The default installs none, so the browser runs the exact\n * code path it ran before the chain existed.\n *\n * \"Beneath\" is not a priority — see {@link initRoutes}. These are the filters that must judge\n * and sign what is ACTUALLY about to be sent, so no app priority may be allowed to get under\n * them: @webpieces/http-client-node installs its SSRF guard and its outbound-auth minter here,\n * and both would be defeated by an app filter that re-pointed the URL below them. Neither\n * concept can live in this class, because reading a RequestContext, resolving DNS and minting\n * an OIDC token are all things a browser bundle must never contain.\n */\n protected clientFilters(): ClientFilterDefinition[] {\n return [];\n }\n\n /**\n * Adapt a translated downstream failure into the error THIS environment's caller should see.\n *\n * THE INVARIANT, and the reason this hook exists at all:\n *\n * A status received from a downstream dependency describes OUR request to it. It is never the\n * status we return to OUR caller. The server that answered 404 is correct; the server that\n * asked for a route that does not exist is broken, and must say so as a 500.\n *\n * That invariant reads differently in the two environments, which is exactly why the ISOMORPHIC\n * {@link ClientErrorTranslator} cannot settle it:\n * - BROWSER: the client IS the end user's agent, so the downstream IS the answer. Pass it through\n * unchanged.\n * - NODE: server-to-server. A 4xx from a dependency is a caller-side defect (wrong path, wrong\n * base URL, an undeployed dependency, bad service credentials), so the caller owns it as a 500.\n *\n * ABSTRACT, not a defaulted pass-through, for the same reason\n * {@link outboundContextHeaders} takes a required `destination`: a permissive default puts the\n * wrong answer one keystroke away. A new environment subclass must SAY which of the two it is,\n * and there are exactly two subclasses in the repo, so the compile error is the migration.\n *\n * @param failure - the translated error, its provenance (app-registered vs built-in), and the\n * downstream status\n * @param callId - `ApiName.methodName`, so a rewritten message can still name the call\n */\n protected abstract adaptDownstreamFailure(failure: TranslatedFailure, callId: string): Error;\n\n /**\n * Fires before the logical call's attempts, once per RPC — the progress \"start marker\". Symmetric with\n * {@link onRequestEnd}: every start is followed by exactly one end, on every path, so a listener\n * can drive a counter (bar on / bar off) without leaking a permanently-spinning bar.\n *\n * The default is a no-op, so every existing subclass is unaffected.\n */\n protected onRequestStart(_route: RouteMetadata): void {}\n\n /**\n * Fires exactly ONCE after the call settles, on EVERY path (2xx, HTTP error, network reject) —\n * the \"stop marker\", carrying how it settled.\n *\n * Subsumes the older header-only hook: this is the ONLY place the `fetch` Response — and thus its\n * `Headers` — exists, so an app that needs to read a response header (e.g. a server-version stamp\n * for client↔server version matching) reads `outcome.headers` after settlement\n * and on both the ok and error paths. `outcome.ok`/`outcome.error` add the success-or-error\n * signal the header-only seam could not give.\n *\n * The default is a no-op, so every existing subclass is unaffected.\n */\n protected onRequestEnd(_route: RouteMetadata, _outcome: RequestOutcome): void {}\n\n // ---------------------------------------------------------------- contract binding\n\n /**\n * Bind this client to one API contract: read @ApiPath/@Endpoint/@Auth* off the prototype and\n * build the route map once. Each subclass's `init(api, config)` stores its own config, then\n * calls this.\n *\n * @param appFilters the app's OUTBOUND filters for this client, from `createRpcClient`. They are\n * merged with {@link clientFilters} and sorted by priority, highest OUTERMOST.\n * @throws Error if the prototype lacks @ApiPath, or declares an endpoint this environment\n * cannot satisfy (see {@link assertEndpointSupported}).\n */\n protected initRoutes(apiPrototype: ApiPrototype<object>, appFilters: ClientFilterDefinition[]): void {\n this.appFilters = appFilters;\n this.apiClass = apiPrototype;\n if (!isApiPath(apiPrototype)) {\n const className = apiPrototype.name || 'Unknown';\n throw new Error(`Class ${className} must be decorated with @ApiPath()`);\n }\n\n const basePath = getApiPath(apiPrototype)!;\n const endpoints = getEndpoints(apiPrototype) || {};\n\n // apiName as the class name so client logs read \"SaveApi.save\", not \"undefined.save\"\n this.apiName = apiPrototype.name || 'UnknownApi';\n\n this.routeMap = new Map<string, RouteMetadata>();\n for (const [methodName, endpointPath] of Object.entries(endpoints)) {\n const fullPath = basePath + endpointPath;\n // Capture the endpoint's auth mode so the client can mint delivery auth per\n // @AuthOidc / @AuthSharedSecret, exactly as the server verifies it.\n const authMeta = getAuthMeta(apiPrototype, methodName);\n this.assertEndpointSupported(authMeta, methodName);\n const formPost = isFormPost(apiPrototype, methodName);\n this.routeMap.set(\n methodName,\n new RouteMetadata(\n 'POST', fullPath, methodName, this.apiName, authMeta, undefined, formPost,\n getMaskSpec(apiPrototype, methodName), isRawBody(apiPrototype, methodName),\n ),\n );\n }\n\n // APP filters first (highest priority OUTERMOST, matching the server's FilterMatcher), then\n // the framework built-ins, ALWAYS innermost. Two separate sorts rather than one over the\n // union, deliberately: an app priority orders app filters against each other and nothing\n // else, so no number an app can type — however large — gets underneath the SSRF guard or the\n // credential minter. A single sorted list would make \"displace the guard\" a matter of typing\n // a bigger integer, and a security control an app can outrank by accident is not a control.\n //\n // Sorted here, once, so FilterChain itself never sorts — priority lives on the DEFINITION,\n // not on the filter.\n const byPriority = (a: ClientFilterDefinition, b: ClientFilterDefinition): number =>\n b.priority - a.priority;\n const ordered = [...[...this.appFilters].sort(byPriority), ...[...this.clientFilters()].sort(byPriority)];\n this.chain = new FilterChain<ClientRequest, Response>(\n ordered.map((definition: ClientFilterDefinition) => definition.filter),\n );\n }\n\n /** The contract's class name, for logs and recordings. */\n protected contractName(): string {\n return this.apiName;\n }\n\n /** Check if a route exists for the given method name. */\n hasRoute(methodName: string): boolean {\n return this.routeMap.has(methodName);\n }\n\n /**\n * Get route metadata for a method name.\n * @throws Error if no route found\n */\n getRoute(methodName: string): RouteMetadata {\n const route = this.routeMap.get(methodName);\n if (!route) {\n throw new Error(`No route found for method ${methodName}`);\n }\n return route;\n }\n\n // ---------------------------------------------------------------- the call\n\n /**\n * FAIL FAST, PER METHOD, at call time: some endpoints exist for a caller that is not us, and this\n * proxy could only ever build a request they are obliged to reject. Refusing here rather than at\n * bind time means an api that MIXES such endpoints with normal ones still yields a working client\n * for the normal ones; only calling the un-callable method throws.\n *\n * @throws Error naming the endpoint, what it declared, and who its real caller is.\n */\n private refuseEndpointNoClientCanCall(route: RouteMetadata): void {\n // formPost exists ONLY for EXTERNAL inbound webhooks (e.g. Twilio is the caller). This proxy\n // JSON.stringifies the body, so calling one would silently send a wrong-encoded body.\n if (route.formPost) {\n throw new Error(\n `${this.apiName}.${route.methodName} is @Endpoint(..., { formPost: true }) — the ` +\n `webpieces client does not support calling form-encoded endpoints yet. formPost is ` +\n `for EXTERNAL inbound webhooks (e.g. Twilio) only. If this endpoint needs a ` +\n `service-to-service client, set formPost:false (or remove it) so it uses JSON.`,\n );\n }\n const authMode = route.authMeta?.mode;\n // @AuthApiKey: the credential is a CUSTOMER-held key, and the header carrying it is the app's\n // ApiKeyHook's choice, so this client has nothing to send and the call is a guaranteed 401.\n if (authMode?.kind === 'apikey') {\n throw new Error(\n `${this.apiName}.${route.methodName} is @AuthApiKey('${authMode.regime}') — only the partner ` +\n `holding that api key can call it, and the header carrying it is the app's ApiKeyHook's choice, ` +\n `so a webpieces client has no credential to send.`,\n );\n }\n // @AuthWebhook is DELIBERATELY absent from this list. It used to be here, on the assumption\n // that the vendor is always somebody else — but `@AuthWebhook(name)` names a signing SCHEME,\n // not a direction, and for an OUTBOUND partner webhook WE are the vendor. The environment's\n // outbound-auth filter asks its bound signer to produce the signature, which is the exact\n // mirror of the inbound WebhookAuthCallback that verifies one.\n }\n\n /** One logical call: one lifecycle pair and log entry across all strategy attempts. */\n // webpieces-disable no-any-unknown -- request and response DTOs are erased at the proxy boundary\n async makeRequest(route: RouteMetadata, args: unknown[]): Promise<unknown> {\n this.refuseEndpointNoClientCanCall(route);\n const requestDto = args[0];\n return this.execute(route, requestDto, () => this.executeCall(route, requestDto));\n }\n\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n private async executeCall(route: RouteMetadata, requestDto: unknown): Promise<unknown> {\n this.onRequestStart(route);\n let response: Response | undefined;\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n let result: unknown;\n // webpieces-disable no-unmanaged-exceptions -- report one logical END, preserving the original thrown value\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = await CallRegistry.execute(this.apiClass, route.methodName, (timeoutMs: number) => {\n response = undefined;\n return CallDeadline.run(timeoutMs, new CallContext(this.apiName, route.methodName),\n async (signal: AbortSignal) => {\n const request = await this.prepareRequest(route, requestDto);\n signal.throwIfAborted();\n const received = await this.chain.execute(request, () => this.sendOnce(request, signal));\n signal.throwIfAborted();\n response = received;\n return this.readResponse(received, route);\n });\n }, 30_000);\n } catch (err: unknown) {\n const error = toError(err);\n this.onRequestEnd(route, new RequestOutcome(false, response?.status ?? 0, response?.headers, error));\n throw err;\n }\n this.onRequestEnd(route, new RequestOutcome(true, response?.status ?? 0, response?.headers));\n return result;\n }\n\n /** Fresh mutable request for every attempt, including URL, headers, auth and body. */\n // webpieces-disable no-any-unknown -- request DTO is erased at the proxy boundary\n private async prepareRequest(route: RouteMetadata, requestDto: unknown): Promise<ClientRequest> {\n const baseUrl = await this.resolveBaseUrl();\n const headers = new Map<string, string>([['Content-Type', 'application/json']]);\n const context = this.outboundContextHeaders(DestinationTrust.forAuthMode(route.authMeta?.mode));\n for (const entry of context.entries()) headers.set(entry[0], entry[1]);\n return new ClientRequest(route, this.apiName, baseUrl, headers, JSON.stringify(requestDto), requestDto);\n }\n\n /**\n * ONE transmission — the bottom of the filter chain, and the only place `fetch` is called.\n *\n * Everything it sends comes off the {@link ClientRequest} as the chain left it, so a filter's\n * edits to the url, the headers or the serialized body are exactly what goes on the wire. It may\n * run more than once for a single RPC when a filter follows a redirect.\n *\n * A network reject (offline, DNS, CORS preflight) is classified into a typed OfflineError here (a\n * genuine bug passes through untouched) so that filters above see the same typed error the caller\n * will, rather than a raw platform reject.\n */\n private async sendOnce(request: ClientRequest, signal: AbortSignal): Promise<Response> {\n signal.throwIfAborted();\n const options: RequestInit = {\n method: request.route.httpMethod,\n signal,\n headers: request.headersAsRecord(),\n redirect: request.followRedirects ? 'follow' : 'manual',\n };\n if (request.body !== undefined) {\n options.body = request.body;\n }\n // webpieces-disable no-unmanaged-exceptions -- classify a network reject, then rethrow it typed\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-fetch -- this IS the generated-client implementation the rule points everyone to\n return await fetch(request.url, options);\n } catch (err: unknown) {\n const error = toError(err);\n throw this.networkRejectClassifier.toNetworkError(error, request.url);\n }\n }\n\n /** Body consumption is inside the attempt deadline, including non-JSON error bodies. */\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n private async readResponse(response: Response, route: RouteMetadata): Promise<unknown> {\n const callId = `${this.apiName}.${route.methodName}`;\n if (response.ok) {\n if (!this.bodyReader.isJson(response)) {\n throw new Error(this.bodyReader.describeForeignBody(response, callId, await response.text()));\n }\n return response.json();\n }\n const protocolError = await this.bodyReader.readErrorBody(response, callId);\n const translated = ClientErrorTranslator.translateError(\n this.responseDtoFactory.fromFetch(response, protocolError),\n );\n throw this.adaptDownstreamFailure(translated, callId);\n }\n}\n"]}
@@ -2,7 +2,7 @@
2
2
  * How one RPC call SETTLED — the payload of {@link ProxyClient.onRequestEnd}.
3
3
  *
4
4
  * DATA ONLY (no behavior), so it is a class with an explicit constructor rather than an interface:
5
- * each of the three settle paths in `ProxyClient.executeFetch` constructs it by name, and a reader
5
+ * `ProxyClient.executeCall` constructs it by name on settlement, and a reader
6
6
  * can see at the call site which path produced which shape.
7
7
  *
8
8
  * The three shapes, one per path:
@@ -10,17 +10,16 @@
10
10
  * - HTTP error `new RequestOutcome(false, status, headers, error)` — the translated HttpError
11
11
  * - network reject `new RequestOutcome(false, 0, undefined, error)` — no Response ever existed
12
12
  *
13
- * A fourth path exists but is not a fourth SHAPE: a body that fails to parse (an infra 502 serving
14
- * HTML) settles as an HTTP error carrying the parse failure.
13
+ * A timeout or body parse failure uses the failure shape, with headers/status if they arrived.
15
14
  */
16
15
  export declare class RequestOutcome {
17
- /** `response.ok` — true only on a 2xx. */
16
+ /** True when the logical call succeeded, including a strategy recovering from an error. */
18
17
  readonly ok: boolean;
19
- /** The HTTP status; 0 when `fetch` itself rejected (network / offline), where there is no status. */
18
+ /** The last attempt's HTTP status, or 0 when no response arrived. */
20
19
  readonly status: number;
21
20
  /**
22
21
  * The Response headers, present whenever an HTTP Response existed (ok OR error) and absent
23
- * only on a network reject. Read BEFORE the body is consumed, which is what lets an app pull
22
+ * when no response arrived. Available after settlement, which lets an app pull
24
23
  * a server-version stamp off an error response.
25
24
  */
26
25
  readonly headers?: Headers | undefined;
@@ -35,13 +34,13 @@ export declare class RequestOutcome {
35
34
  */
36
35
  readonly error?: Error | undefined;
37
36
  constructor(
38
- /** `response.ok` — true only on a 2xx. */
37
+ /** True when the logical call succeeded, including a strategy recovering from an error. */
39
38
  ok: boolean,
40
- /** The HTTP status; 0 when `fetch` itself rejected (network / offline), where there is no status. */
39
+ /** The last attempt's HTTP status, or 0 when no response arrived. */
41
40
  status: number,
42
41
  /**
43
42
  * The Response headers, present whenever an HTTP Response existed (ok OR error) and absent
44
- * only on a network reject. Read BEFORE the body is consumed, which is what lets an app pull
43
+ * when no response arrived. Available after settlement, which lets an app pull
45
44
  * a server-version stamp off an error response.
46
45
  */
47
46
  headers?: Headers | undefined,
@@ -5,7 +5,7 @@ exports.RequestOutcome = void 0;
5
5
  * How one RPC call SETTLED — the payload of {@link ProxyClient.onRequestEnd}.
6
6
  *
7
7
  * DATA ONLY (no behavior), so it is a class with an explicit constructor rather than an interface:
8
- * each of the three settle paths in `ProxyClient.executeFetch` constructs it by name, and a reader
8
+ * `ProxyClient.executeCall` constructs it by name on settlement, and a reader
9
9
  * can see at the call site which path produced which shape.
10
10
  *
11
11
  * The three shapes, one per path:
@@ -13,8 +13,7 @@ exports.RequestOutcome = void 0;
13
13
  * - HTTP error `new RequestOutcome(false, status, headers, error)` — the translated HttpError
14
14
  * - network reject `new RequestOutcome(false, 0, undefined, error)` — no Response ever existed
15
15
  *
16
- * A fourth path exists but is not a fourth SHAPE: a body that fails to parse (an infra 502 serving
17
- * HTML) settles as an HTTP error carrying the parse failure.
16
+ * A timeout or body parse failure uses the failure shape, with headers/status if they arrived.
18
17
  */
19
18
  class RequestOutcome {
20
19
  ok;
@@ -22,13 +21,13 @@ class RequestOutcome {
22
21
  headers;
23
22
  error;
24
23
  constructor(
25
- /** `response.ok` — true only on a 2xx. */
24
+ /** True when the logical call succeeded, including a strategy recovering from an error. */
26
25
  ok,
27
- /** The HTTP status; 0 when `fetch` itself rejected (network / offline), where there is no status. */
26
+ /** The last attempt's HTTP status, or 0 when no response arrived. */
28
27
  status,
29
28
  /**
30
29
  * The Response headers, present whenever an HTTP Response existed (ok OR error) and absent
31
- * only on a network reject. Read BEFORE the body is consumed, which is what lets an app pull
30
+ * when no response arrived. Available after settlement, which lets an app pull
32
31
  * a server-version stamp off an error response.
33
32
  */
34
33
  headers,
@@ -1 +1 @@
1
- {"version":3,"file":"RequestOutcome.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/RequestOutcome.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,MAAa,cAAc;IAGH;IAEA;IAMA;IAUA;IApBpB;IACI,0CAA0C;IAC1B,EAAW;IAC3B,qGAAqG;IACrF,MAAc;IAC9B;;;;OAIG;IACa,OAAiB;IACjC;;;;;;;;OAQG;IACa,KAAa;QAlBb,OAAE,GAAF,EAAE,CAAS;QAEX,WAAM,GAAN,MAAM,CAAQ;QAMd,YAAO,GAAP,OAAO,CAAU;QAUjB,UAAK,GAAL,KAAK,CAAQ;IAC9B,CAAC;CACP;AAvBD,wCAuBC","sourcesContent":["/**\n * How one RPC call SETTLED — the payload of {@link ProxyClient.onRequestEnd}.\n *\n * DATA ONLY (no behavior), so it is a class with an explicit constructor rather than an interface:\n * each of the three settle paths in `ProxyClient.executeFetch` constructs it by name, and a reader\n * can see at the call site which path produced which shape.\n *\n * The three shapes, one per path:\n * - 2xx `new RequestOutcome(true, status, headers)` — no error\n * - HTTP error `new RequestOutcome(false, status, headers, error)` — the translated HttpError\n * - network reject `new RequestOutcome(false, 0, undefined, error)` — no Response ever existed\n *\n * A fourth path exists but is not a fourth SHAPE: a body that fails to parse (an infra 502 serving\n * HTML) settles as an HTTP error carrying the parse failure.\n */\nexport class RequestOutcome {\n constructor(\n /** `response.ok` — true only on a 2xx. */\n public readonly ok: boolean,\n /** The HTTP status; 0 when `fetch` itself rejected (network / offline), where there is no status. */\n public readonly status: number,\n /**\n * The Response headers, present whenever an HTTP Response existed (ok OR error) and absent\n * only on a network reject. Read BEFORE the body is consumed, which is what lets an app pull\n * a server-version stamp off an error response.\n */\n public readonly headers?: Headers,\n /**\n * Set on every non-success path: for a non-2xx, the error the CALLER will see — i.e. what\n * `ClientErrorTranslator` picked AFTER `ProxyClient.adaptDownstreamFailure` had its say, so a\n * listener never disagrees with the thrown exception (on a server that is the 500 wrapping a\n * downstream 4xx, with the original reachable as `httpCause`). Otherwise the network/parse\n * failure normalized through `toError`. Always a real `Error` — never `unknown`, because\n * nothing here is untyped: `translateError` RETURNS a typed `TranslatedFailure`, and every\n * rejection reaching this class has been through `toError`.\n */\n public readonly error?: Error,\n ) {}\n}\n"]}
1
+ {"version":3,"file":"RequestOutcome.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/RequestOutcome.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;GAaG;AACH,MAAa,cAAc;IAGH;IAEA;IAMA;IAUA;IApBpB;IACI,2FAA2F;IAC3E,EAAW;IAC3B,qEAAqE;IACrD,MAAc;IAC9B;;;;OAIG;IACa,OAAiB;IACjC;;;;;;;;OAQG;IACa,KAAa;QAlBb,OAAE,GAAF,EAAE,CAAS;QAEX,WAAM,GAAN,MAAM,CAAQ;QAMd,YAAO,GAAP,OAAO,CAAU;QAUjB,UAAK,GAAL,KAAK,CAAQ;IAC9B,CAAC;CACP;AAvBD,wCAuBC","sourcesContent":["/**\n * How one RPC call SETTLED — the payload of {@link ProxyClient.onRequestEnd}.\n *\n * DATA ONLY (no behavior), so it is a class with an explicit constructor rather than an interface:\n * `ProxyClient.executeCall` constructs it by name on settlement, and a reader\n * can see at the call site which path produced which shape.\n *\n * The three shapes, one per path:\n * - 2xx `new RequestOutcome(true, status, headers)` — no error\n * - HTTP error `new RequestOutcome(false, status, headers, error)` — the translated HttpError\n * - network reject `new RequestOutcome(false, 0, undefined, error)` — no Response ever existed\n *\n * A timeout or body parse failure uses the failure shape, with headers/status if they arrived.\n */\nexport class RequestOutcome {\n constructor(\n /** True when the logical call succeeded, including a strategy recovering from an error. */\n public readonly ok: boolean,\n /** The last attempt's HTTP status, or 0 when no response arrived. */\n public readonly status: number,\n /**\n * The Response headers, present whenever an HTTP Response existed (ok OR error) and absent\n * when no response arrived. Available after settlement, which lets an app pull\n * a server-version stamp off an error response.\n */\n public readonly headers?: Headers,\n /**\n * Set on every non-success path: for a non-2xx, the error the CALLER will see — i.e. what\n * `ClientErrorTranslator` picked AFTER `ProxyClient.adaptDownstreamFailure` had its say, so a\n * listener never disagrees with the thrown exception (on a server that is the 500 wrapping a\n * downstream 4xx, with the original reachable as `httpCause`). Otherwise the network/parse\n * failure normalized through `toError`. Always a real `Error` — never `unknown`, because\n * nothing here is untyped: `translateError` RETURNS a typed `TranslatedFailure`, and every\n * rejection reaching this class has been through `toError`.\n */\n public readonly error?: Error,\n ) {}\n}\n"]}