@webpieces/http-client-core 0.4.790 → 0.4.792
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 +2 -2
- package/src/ClientErrorTranslator.d.ts +32 -8
- package/src/ClientErrorTranslator.js +39 -79
- package/src/ClientErrorTranslator.js.map +1 -1
- package/src/HttpResponseDtoFactory.d.ts +1 -1
- package/src/HttpResponseDtoFactory.js +1 -1
- package/src/HttpResponseDtoFactory.js.map +1 -1
- package/src/ProxyClient.d.ts +1 -28
- package/src/ProxyClient.js +12 -4
- package/src/ProxyClient.js.map +1 -1
- package/src/RequestOutcome.d.ts +4 -4
- package/src/RequestOutcome.js +2 -2
- package/src/RequestOutcome.js.map +1 -1
- package/src/index.d.ts +0 -2
- package/src/index.js +2 -6
- package/src/index.js.map +1 -1
- package/src/TranslatedFailure.d.ts +0 -50
- package/src/TranslatedFailure.js +0 -48
- package/src/TranslatedFailure.js.map +0 -1
- package/src/UnexpectedApiResponseError.d.ts +0 -5
- package/src/UnexpectedApiResponseError.js +0 -14
- package/src/UnexpectedApiResponseError.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/http-client-core",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.792",
|
|
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.
|
|
24
|
+
"@webpieces/core-util": "0.4.792"
|
|
25
25
|
}
|
|
26
26
|
}
|
|
@@ -1,11 +1,35 @@
|
|
|
1
1
|
import { HttpResponseDto } from '@webpieces/core-util';
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
/**
|
|
3
|
+
* The CLIENT half of the wire seam: hand every response to THE registered
|
|
4
|
+
* {@link ErrorTranslator}'s `fromWire`, and guarantee the one invariant a typed caller depends on.
|
|
5
|
+
*
|
|
6
|
+
* There is no "was a translator registered" question here — {@link ClientRegistry.getErrorTranslator}
|
|
7
|
+
* is non-optional — and no `TranslatedFailure` provenance record either. Provenance existed only to
|
|
8
|
+
* feed `ProxyClient.adaptDownstreamFailure`, and the uniform 4xx/5xx rule in
|
|
9
|
+
* {@link WebpiecesDefaultErrorTranslator} deleted that hook: an app that wants a downstream status
|
|
10
|
+
* relayed as its own type says so by THROWING it from its own `fromWire`.
|
|
11
|
+
*/
|
|
4
12
|
export declare class ClientErrorTranslator {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Run `fromWire` over a response, and make it impossible for a FAILURE response to be handed to a
|
|
15
|
+
* typed caller as if it were data.
|
|
16
|
+
*
|
|
17
|
+
* Every response goes through here, 2xx included, so an app whose 200 body signals failure can
|
|
18
|
+
* turn it into a throw (see {@link ErrorTranslator.fromWire}).
|
|
19
|
+
*
|
|
20
|
+
* The second call is BUG CONTAINMENT, not a fallback branch: an app translator that returns
|
|
21
|
+
* normally for a non-2xx has a bug whose symptom would otherwise be `undefined` arriving where
|
|
22
|
+
* the contract promised a DTO. The webpieces default answers instead — and for a genuine 2xx it
|
|
23
|
+
* returns silently, so the normal path costs one predicate.
|
|
24
|
+
*/
|
|
25
|
+
static throwIfFailure(response: HttpResponseDto): void;
|
|
26
|
+
/**
|
|
27
|
+
* {@link throwIfFailure} for a response the CALLER has already established is not an ordinary
|
|
28
|
+
* success (not 2xx, or a 266). Typed `never`, which is what lets `ProxyClient.readResponse` end on
|
|
29
|
+
* this call instead of on a `return undefined` the contract forbids.
|
|
30
|
+
*
|
|
31
|
+
* The trailing throw is NOT dead code standing in for a type: it fires exactly when this is
|
|
32
|
+
* called with an ordinary 2xx, which is a framework bug in the caller, and says so.
|
|
33
|
+
*/
|
|
34
|
+
static throwFailure(response: HttpResponseDto): never;
|
|
11
35
|
}
|
|
@@ -2,88 +2,48 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ClientErrorTranslator = void 0;
|
|
4
4
|
const core_util_1 = require("@webpieces/core-util");
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
/**
|
|
6
|
+
* The CLIENT half of the wire seam: hand every response to THE registered
|
|
7
|
+
* {@link ErrorTranslator}'s `fromWire`, and guarantee the one invariant a typed caller depends on.
|
|
8
|
+
*
|
|
9
|
+
* There is no "was a translator registered" question here — {@link ClientRegistry.getErrorTranslator}
|
|
10
|
+
* is non-optional — and no `TranslatedFailure` provenance record either. Provenance existed only to
|
|
11
|
+
* feed `ProxyClient.adaptDownstreamFailure`, and the uniform 4xx/5xx rule in
|
|
12
|
+
* {@link WebpiecesDefaultErrorTranslator} deleted that hook: an app that wants a downstream status
|
|
13
|
+
* relayed as its own type says so by THROWING it from its own `fromWire`.
|
|
14
|
+
*/
|
|
8
15
|
class ClientErrorTranslator {
|
|
16
|
+
/**
|
|
17
|
+
* Run `fromWire` over a response, and make it impossible for a FAILURE response to be handed to a
|
|
18
|
+
* typed caller as if it were data.
|
|
19
|
+
*
|
|
20
|
+
* Every response goes through here, 2xx included, so an app whose 200 body signals failure can
|
|
21
|
+
* turn it into a throw (see {@link ErrorTranslator.fromWire}).
|
|
22
|
+
*
|
|
23
|
+
* The second call is BUG CONTAINMENT, not a fallback branch: an app translator that returns
|
|
24
|
+
* normally for a non-2xx has a bug whose symptom would otherwise be `undefined` arriving where
|
|
25
|
+
* the contract promised a DTO. The webpieces default answers instead — and for a genuine 2xx it
|
|
26
|
+
* returns silently, so the normal path costs one predicate.
|
|
27
|
+
*/
|
|
9
28
|
// webpieces-disable no-function-outside-class -- pure stateless mapping shared by browser and node
|
|
10
|
-
static
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
// status apart from the framework's generic default for it.
|
|
14
|
-
const custom = core_util_1.ClientRegistry.getErrorTranslators()?.fromWire(response);
|
|
15
|
-
if (custom !== undefined)
|
|
16
|
-
return new TranslatedFailure_1.TranslatedFailure(custom, true, response.status.code);
|
|
17
|
-
return new TranslatedFailure_1.TranslatedFailure(this.builtInError(response), false, response.status.code);
|
|
29
|
+
static throwIfFailure(response) {
|
|
30
|
+
core_util_1.ClientRegistry.getErrorTranslator().fromWire(response);
|
|
31
|
+
core_util_1.WEBPIECES_DEFAULT_ERROR_TRANSLATOR.fromWire(response);
|
|
18
32
|
}
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
return this.fromStatus(response.status.code, this.fallbackMessage(response.body, response.status.reason));
|
|
34
|
-
}
|
|
35
|
-
/** Non-Webpieces responders: named statuses map to their class, any other 100-599 to ApiCodedError. */
|
|
36
|
-
// webpieces-disable no-function-outside-class -- fallback for non-Webpieces HTTP responders
|
|
37
|
-
static fromStatus(statusCode, message) {
|
|
38
|
-
switch (statusCode) {
|
|
39
|
-
case 266:
|
|
40
|
-
return new core_util_1.ApiEndUserError(message);
|
|
41
|
-
case 400:
|
|
42
|
-
return new core_util_1.ApiBadRequestError(message);
|
|
43
|
-
case 401:
|
|
44
|
-
return new core_util_1.ApiUnauthorizedError(message);
|
|
45
|
-
case 403:
|
|
46
|
-
return new core_util_1.ApiForbiddenError(message);
|
|
47
|
-
case 404:
|
|
48
|
-
return new core_util_1.ApiNotFoundError(message);
|
|
49
|
-
case 408:
|
|
50
|
-
return new core_util_1.ApiRequestTimeoutError(message);
|
|
51
|
-
case 409:
|
|
52
|
-
return new core_util_1.ApiConflictError(message);
|
|
53
|
-
case 412:
|
|
54
|
-
return new core_util_1.ApiPreconditionFailedError(message);
|
|
55
|
-
case 415:
|
|
56
|
-
return new core_util_1.ApiUnsupportedMediaTypeError(message);
|
|
57
|
-
case 422:
|
|
58
|
-
return new core_util_1.ApiUnprocessableError(message);
|
|
59
|
-
case 429:
|
|
60
|
-
return new core_util_1.ApiRateLimitedError(message);
|
|
61
|
-
case 500:
|
|
62
|
-
return new core_util_1.ApiImplementationError('Internal Error', undefined, true);
|
|
63
|
-
case 501:
|
|
64
|
-
return new core_util_1.ApiNotImplementedError(message);
|
|
65
|
-
case 502:
|
|
66
|
-
return new core_util_1.ApiDependencyError(message);
|
|
67
|
-
case 503:
|
|
68
|
-
return new core_util_1.ApiUnavailableError(message);
|
|
69
|
-
case 504:
|
|
70
|
-
return new core_util_1.ApiDependencyTimeoutError(message);
|
|
71
|
-
default:
|
|
72
|
-
// Any other real HTTP status keeps its code; only a value no HTTP status can hold is unexpected.
|
|
73
|
-
if (core_util_1.ApiCodedError.isStatusCode(statusCode))
|
|
74
|
-
return new core_util_1.ApiCodedError(message, statusCode);
|
|
75
|
-
return new UnexpectedApiResponseError_1.UnexpectedApiResponseError(statusCode, message);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
// webpieces-disable no-any-unknown -- HTTP response bodies are app-owned until this boundary safely inspects them
|
|
79
|
-
// webpieces-disable no-function-outside-class -- bounds diagnostic text from a foreign responder
|
|
80
|
-
static fallbackMessage(body, reason) {
|
|
81
|
-
if (typeof body === 'object' && body !== null) {
|
|
82
|
-
const message = Object.getOwnPropertyDescriptor(body, 'message')?.value;
|
|
83
|
-
if (typeof message === 'string' && message.length > 0)
|
|
84
|
-
return message.slice(0, 4096);
|
|
85
|
-
}
|
|
86
|
-
return reason || 'Request Failed';
|
|
33
|
+
/**
|
|
34
|
+
* {@link throwIfFailure} for a response the CALLER has already established is not an ordinary
|
|
35
|
+
* success (not 2xx, or a 266). Typed `never`, which is what lets `ProxyClient.readResponse` end on
|
|
36
|
+
* this call instead of on a `return undefined` the contract forbids.
|
|
37
|
+
*
|
|
38
|
+
* The trailing throw is NOT dead code standing in for a type: it fires exactly when this is
|
|
39
|
+
* called with an ordinary 2xx, which is a framework bug in the caller, and says so.
|
|
40
|
+
*/
|
|
41
|
+
// webpieces-disable no-function-outside-class -- pure stateless mapping shared by browser and node
|
|
42
|
+
static throwFailure(response) {
|
|
43
|
+
ClientErrorTranslator.throwIfFailure(response);
|
|
44
|
+
throw new core_util_1.ApiImplementationError(`ClientErrorTranslator.throwFailure was called for HTTP ${response.status.code}, ` +
|
|
45
|
+
`which is an ordinary success. Only a non-2xx (or a 266) response reaches here; ` +
|
|
46
|
+
`use throwIfFailure for a response that may legitimately pass.`);
|
|
87
47
|
}
|
|
88
48
|
}
|
|
89
49
|
exports.ClientErrorTranslator = ClientErrorTranslator;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ClientErrorTranslator.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/ClientErrorTranslator.ts"],"names":[],"mappings":";;;AAAA,
|
|
1
|
+
{"version":3,"file":"ClientErrorTranslator.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/ClientErrorTranslator.ts"],"names":[],"mappings":";;;AAAA,oDAK8B;AAE9B;;;;;;;;;GASG;AACH,MAAa,qBAAqB;IAC9B;;;;;;;;;;;OAWG;IACH,mGAAmG;IACnG,MAAM,CAAC,cAAc,CAAC,QAAyB;QAC3C,0BAAc,CAAC,kBAAkB,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACvD,8CAAkC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC1D,CAAC;IAED;;;;;;;OAOG;IACH,mGAAmG;IACnG,MAAM,CAAC,YAAY,CAAC,QAAyB;QACzC,qBAAqB,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;QAC/C,MAAM,IAAI,kCAAsB,CAC5B,0DAA0D,QAAQ,CAAC,MAAM,CAAC,IAAI,IAAI;YAC9E,iFAAiF;YACjF,+DAA+D,CACtE,CAAC;IACN,CAAC;CACJ;AApCD,sDAoCC","sourcesContent":["import {\n ApiImplementationError,\n ClientRegistry,\n HttpResponseDto,\n WEBPIECES_DEFAULT_ERROR_TRANSLATOR,\n} from '@webpieces/core-util';\n\n/**\n * The CLIENT half of the wire seam: hand every response to THE registered\n * {@link ErrorTranslator}'s `fromWire`, and guarantee the one invariant a typed caller depends on.\n *\n * There is no \"was a translator registered\" question here — {@link ClientRegistry.getErrorTranslator}\n * is non-optional — and no `TranslatedFailure` provenance record either. Provenance existed only to\n * feed `ProxyClient.adaptDownstreamFailure`, and the uniform 4xx/5xx rule in\n * {@link WebpiecesDefaultErrorTranslator} deleted that hook: an app that wants a downstream status\n * relayed as its own type says so by THROWING it from its own `fromWire`.\n */\nexport class ClientErrorTranslator {\n /**\n * Run `fromWire` over a response, and make it impossible for a FAILURE response to be handed to a\n * typed caller as if it were data.\n *\n * Every response goes through here, 2xx included, so an app whose 200 body signals failure can\n * turn it into a throw (see {@link ErrorTranslator.fromWire}).\n *\n * The second call is BUG CONTAINMENT, not a fallback branch: an app translator that returns\n * normally for a non-2xx has a bug whose symptom would otherwise be `undefined` arriving where\n * the contract promised a DTO. The webpieces default answers instead — and for a genuine 2xx it\n * returns silently, so the normal path costs one predicate.\n */\n // webpieces-disable no-function-outside-class -- pure stateless mapping shared by browser and node\n static throwIfFailure(response: HttpResponseDto): void {\n ClientRegistry.getErrorTranslator().fromWire(response);\n WEBPIECES_DEFAULT_ERROR_TRANSLATOR.fromWire(response);\n }\n\n /**\n * {@link throwIfFailure} for a response the CALLER has already established is not an ordinary\n * success (not 2xx, or a 266). Typed `never`, which is what lets `ProxyClient.readResponse` end on\n * this call instead of on a `return undefined` the contract forbids.\n *\n * The trailing throw is NOT dead code standing in for a type: it fires exactly when this is\n * called with an ordinary 2xx, which is a framework bug in the caller, and says so.\n */\n // webpieces-disable no-function-outside-class -- pure stateless mapping shared by browser and node\n static throwFailure(response: HttpResponseDto): never {\n ClientErrorTranslator.throwIfFailure(response);\n throw new ApiImplementationError(\n `ClientErrorTranslator.throwFailure was called for HTTP ${response.status.code}, ` +\n `which is an ordinary success. Only a non-2xx (or a 266) response reaches here; ` +\n `use throwIfFailure for a response that may legitimately pass.`,\n );\n }\n}\n"]}
|
|
@@ -4,7 +4,7 @@ import { HttpResponseDto } from '@webpieces/core-util';
|
|
|
4
4
|
* form an app is allowed to see.
|
|
5
5
|
*
|
|
6
6
|
* A fetch `Response` and an express `res` model a response completely differently, and an app's
|
|
7
|
-
* `
|
|
7
|
+
* `ErrorTranslator` is written ONCE and serves both. So neither is handed to the app: the server
|
|
8
8
|
* writes an {@link HttpResponseDto} out (`ExpressWrapper`), and this reads one in. One form, both
|
|
9
9
|
* transports, both directions — which is what makes `fromWire` receive the identical shape whether
|
|
10
10
|
* the caller was `http-client-node` or `http-client-browser` (both share `ProxyClient`, and this is
|
|
@@ -7,7 +7,7 @@ const core_util_1 = require("@webpieces/core-util");
|
|
|
7
7
|
* form an app is allowed to see.
|
|
8
8
|
*
|
|
9
9
|
* A fetch `Response` and an express `res` model a response completely differently, and an app's
|
|
10
|
-
* `
|
|
10
|
+
* `ErrorTranslator` is written ONCE and serves both. So neither is handed to the app: the server
|
|
11
11
|
* writes an {@link HttpResponseDto} out (`ExpressWrapper`), and this reads one in. One form, both
|
|
12
12
|
* transports, both directions — which is what makes `fromWire` receive the identical shape whether
|
|
13
13
|
* the caller was `http-client-node` or `http-client-browser` (both share `ProxyClient`, and this is
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HttpResponseDtoFactory.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/HttpResponseDtoFactory.ts"],"names":[],"mappings":";;;AAAA,oDAAuF;AAWvF;;;;;;;;;;;;GAYG;AACH,MAAa,sBAAsB;IAC/B;;;;;;;;;;;OAWG;IACH,qIAAqI;IAC9H,SAAS,CAAC,QAAkB,EAAE,IAAa;QAC9C,MAAM,OAAO,GAAiB,EAAE,CAAC;QACjC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,KAAa,EAAE,IAAY,EAAE,EAAE;YACrD,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,YAAY,EAAE,CAAC;gBACtC,OAAO,CAAC,IAAI,CAAC,IAAI,sBAAU,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;YAC9C,CAAC;QACL,CAAC,CAAC,CAAC;QACH,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7C,OAAO,CAAC,IAAI,CAAC,IAAI,sBAAU,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC,CAAC;QACvD,CAAC;QACD,OAAO,IAAI,2BAAe,CACtB,IAAI,8BAAkB,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC,EAC5D,OAAO,EACP,IAAI,CACP,CAAC;IACN,CAAC;IAED;;;;OAIG;IACK,UAAU,CAAC,QAAkB;QACjC,6FAA6F;QAC7F,MAAM,OAAO,GAAG,QAAQ,CAAC,OAA2C,CAAC;QACrE,OAAO,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC9D,CAAC;CACJ;AAzCD,wDAyCC","sourcesContent":["import { HttpHeader, HttpResponseDto, HttpResponseStatus } from '@webpieces/core-util';\n\n/**\n * fetch `Headers` as it exists on runtimes that expose repeated `Set-Cookie` values. `getSetCookie`\n * is OPTIONAL because older browsers and older node do not have it at all — its absence is a fact\n * about the runtime, not an error.\n */\ninterface SetCookieAwareHeaders {\n getSetCookie?: () => string[];\n}\n\n/**\n * HttpResponseDtoFactory - webpieces' CLIENT-side boundary between a transport and the one response\n * form an app is allowed to see.\n *\n * A fetch `Response` and an express `res` model a response completely differently, and an app's\n * `
|
|
1
|
+
{"version":3,"file":"HttpResponseDtoFactory.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/HttpResponseDtoFactory.ts"],"names":[],"mappings":";;;AAAA,oDAAuF;AAWvF;;;;;;;;;;;;GAYG;AACH,MAAa,sBAAsB;IAC/B;;;;;;;;;;;OAWG;IACH,qIAAqI;IAC9H,SAAS,CAAC,QAAkB,EAAE,IAAa;QAC9C,MAAM,OAAO,GAAiB,EAAE,CAAC;QACjC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,KAAa,EAAE,IAAY,EAAE,EAAE;YACrD,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,YAAY,EAAE,CAAC;gBACtC,OAAO,CAAC,IAAI,CAAC,IAAI,sBAAU,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;YAC9C,CAAC;QACL,CAAC,CAAC,CAAC;QACH,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7C,OAAO,CAAC,IAAI,CAAC,IAAI,sBAAU,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC,CAAC;QACvD,CAAC;QACD,OAAO,IAAI,2BAAe,CACtB,IAAI,8BAAkB,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC,EAC5D,OAAO,EACP,IAAI,CACP,CAAC;IACN,CAAC;IAED;;;;OAIG;IACK,UAAU,CAAC,QAAkB;QACjC,6FAA6F;QAC7F,MAAM,OAAO,GAAG,QAAQ,CAAC,OAA2C,CAAC;QACrE,OAAO,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC9D,CAAC;CACJ;AAzCD,wDAyCC","sourcesContent":["import { HttpHeader, HttpResponseDto, HttpResponseStatus } from '@webpieces/core-util';\n\n/**\n * fetch `Headers` as it exists on runtimes that expose repeated `Set-Cookie` values. `getSetCookie`\n * is OPTIONAL because older browsers and older node do not have it at all — its absence is a fact\n * about the runtime, not an error.\n */\ninterface SetCookieAwareHeaders {\n getSetCookie?: () => string[];\n}\n\n/**\n * HttpResponseDtoFactory - webpieces' CLIENT-side boundary between a transport and the one response\n * form an app is allowed to see.\n *\n * A fetch `Response` and an express `res` model a response completely differently, and an app's\n * `ErrorTranslator` is written ONCE and serves both. So neither is handed to the app: the server\n * writes an {@link HttpResponseDto} out (`ExpressWrapper`), and this reads one in. One form, both\n * transports, both directions — which is what makes `fromWire` receive the identical shape whether\n * the caller was `http-client-node` or `http-client-browser` (both share `ProxyClient`, and this is\n * the only place either builds a DTO).\n *\n * Stateless; one instance per client is fine.\n */\nexport class HttpResponseDtoFactory {\n /**\n * fetch `Response` + the already-parsed body -> the DTO.\n *\n * Headers come out as a LIST, and `getSetCookie()` is consulted where the runtime has it: fetch's\n * `Headers` JOINS repeated headers into one comma-separated string for every name EXCEPT\n * `set-cookie`, which it hides from iteration entirely. A Map-shaped response type would have\n * lost them either way; the list keeps each cookie its own entry, which is the whole reason\n * {@link HttpResponseDto.headers} is a list.\n *\n * `statusText` is the reason phrase as the server sent it; an empty one (HTTP/2 does not carry\n * reason phrases at all) stays empty rather than being invented here.\n */\n // webpieces-disable no-any-unknown -- the already-parsed body is app-owned data, carried through verbatim (see HttpResponseDto.body)\n public fromFetch(response: Response, body: unknown): HttpResponseDto {\n const headers: HttpHeader[] = [];\n response.headers.forEach((value: string, name: string) => {\n if (name.toLowerCase() !== 'set-cookie') {\n headers.push(new HttpHeader(name, value));\n }\n });\n for (const cookie of this.setCookies(response)) {\n headers.push(new HttpHeader('set-cookie', cookie));\n }\n return new HttpResponseDto(\n new HttpResponseStatus(response.status, response.statusText),\n headers,\n body,\n );\n }\n\n /**\n * Every `Set-Cookie` as its own value, or none where the runtime predates `getSetCookie()`\n * (older browsers, older node). Absent is not an error — it only means this runtime never\n * exposed repeated cookies to script in the first place.\n */\n private setCookies(response: Response): string[] {\n // webpieces-disable no-any-unknown -- getSetCookie() is absent on older lib.dom/node Headers\n const headers = response.headers as unknown as SetCookieAwareHeaders;\n return headers.getSetCookie ? headers.getSetCookie() : [];\n }\n}\n"]}
|
package/src/ProxyClient.d.ts
CHANGED
|
@@ -3,7 +3,6 @@ import { ApiPrototype } from './ApiPrototype';
|
|
|
3
3
|
import { ClientFilterDefinition } from './ClientFilter';
|
|
4
4
|
import { ClientRequest } from './ClientRequest';
|
|
5
5
|
import { RequestOutcome } from './RequestOutcome';
|
|
6
|
-
import { TranslatedFailure } from './TranslatedFailure';
|
|
7
6
|
import { ByteReadableStream } from './ByteStream';
|
|
8
7
|
/**
|
|
9
8
|
* ProxyClient - the HTTP call engine behind one API contract's client proxy.
|
|
@@ -47,7 +46,7 @@ export declare abstract class ProxyClient {
|
|
|
47
46
|
private readonly networkRejectClassifier;
|
|
48
47
|
private readonly bodyReader;
|
|
49
48
|
/**
|
|
50
|
-
* fetch `Response` -> the transport-neutral {@link HttpResponseDto}
|
|
49
|
+
* fetch `Response` -> the transport-neutral {@link HttpResponseDto} the registered `ErrorTranslator`
|
|
51
50
|
* sees. Normalising HERE is what makes `fromWire` receive the identical shape in node and in the
|
|
52
51
|
* browser: both environments share this class, and this is the only place either builds a DTO.
|
|
53
52
|
*/
|
|
@@ -103,32 +102,6 @@ export declare abstract class ProxyClient {
|
|
|
103
102
|
* an OIDC token are all things a browser bundle must never contain.
|
|
104
103
|
*/
|
|
105
104
|
protected clientFilters(): ClientFilterDefinition[];
|
|
106
|
-
/**
|
|
107
|
-
* Adapt a translated downstream failure into the error THIS environment's caller should see.
|
|
108
|
-
*
|
|
109
|
-
* THE INVARIANT, and the reason this hook exists at all:
|
|
110
|
-
*
|
|
111
|
-
* A status received from a downstream dependency describes OUR request to it. It is never the
|
|
112
|
-
* status we return to OUR caller. The server that answered 404 is correct; the server that
|
|
113
|
-
* asked for a route that does not exist is broken, and must say so as a 500.
|
|
114
|
-
*
|
|
115
|
-
* That invariant reads differently in the two environments, which is exactly why the ISOMORPHIC
|
|
116
|
-
* {@link ClientErrorTranslator} cannot settle it:
|
|
117
|
-
* - BROWSER: the client IS the end user's agent, so the downstream IS the answer. Pass it through
|
|
118
|
-
* unchanged.
|
|
119
|
-
* - NODE: server-to-server. A 4xx from a dependency is a caller-side defect (wrong path, wrong
|
|
120
|
-
* base URL, an undeployed dependency, bad service credentials), so the caller owns it as a 500.
|
|
121
|
-
*
|
|
122
|
-
* ABSTRACT, not a defaulted pass-through, for the same reason
|
|
123
|
-
* {@link outboundContextHeaders} takes a required `destination`: a permissive default puts the
|
|
124
|
-
* wrong answer one keystroke away. A new environment subclass must SAY which of the two it is,
|
|
125
|
-
* and there are exactly two subclasses in the repo, so the compile error is the migration.
|
|
126
|
-
*
|
|
127
|
-
* @param failure - the translated error, its provenance (app-registered vs built-in), and the
|
|
128
|
-
* downstream status
|
|
129
|
-
* @param callId - `ApiName.methodName`, so a rewritten message can still name the call
|
|
130
|
-
*/
|
|
131
|
-
protected abstract adaptDownstreamFailure(failure: TranslatedFailure, callId: string): Error;
|
|
132
105
|
/** Whether fetch can read the response while its streaming request body remains open. */
|
|
133
106
|
protected abstract supportsConcurrentDuplexFetch(): boolean;
|
|
134
107
|
/** Environment-owned full-duplex transport after the shared filter chain has prepared it. */
|
package/src/ProxyClient.js
CHANGED
|
@@ -63,7 +63,7 @@ class ProxyClient {
|
|
|
63
63
|
// Same shape and same reason: stateless, so it is constructed here rather than injected.
|
|
64
64
|
bodyReader = new ResponseBodyReader_1.ResponseBodyReader();
|
|
65
65
|
/**
|
|
66
|
-
* fetch `Response` -> the transport-neutral {@link HttpResponseDto}
|
|
66
|
+
* fetch `Response` -> the transport-neutral {@link HttpResponseDto} the registered `ErrorTranslator`
|
|
67
67
|
* sees. Normalising HERE is what makes `fromWire` receive the identical shape in node and in the
|
|
68
68
|
* browser: both environments share this class, and this is the only place either builds a DTO.
|
|
69
69
|
*/
|
|
@@ -451,11 +451,19 @@ class ProxyClient {
|
|
|
451
451
|
if (!this.bodyReader.isJson(response)) {
|
|
452
452
|
throw new Error(this.bodyReader.describeForeignBody(response, callId, await response.text()));
|
|
453
453
|
}
|
|
454
|
-
|
|
454
|
+
// webpieces-disable no-any-unknown -- a success body is the caller's own DTO, erased here
|
|
455
|
+
const body = await response.json();
|
|
456
|
+
// EVERY response passes the seam, 2xx included: an app whose 200 body signals failure
|
|
457
|
+
// turns it into a throw here. The webpieces default returns silently, so the success
|
|
458
|
+
// path is unchanged — and the body is parsed ONCE, because a fetch body reads once.
|
|
459
|
+
ClientErrorTranslator_1.ClientErrorTranslator.throwIfFailure(this.responseDtoFactory.fromFetch(response, body));
|
|
460
|
+
return body;
|
|
455
461
|
}
|
|
456
462
|
const protocolError = await this.bodyReader.readErrorBody(response, callId);
|
|
457
|
-
|
|
458
|
-
|
|
463
|
+
// The mirror of what the SERVER's `toWire` wrote. `fromWire` throws, so this method cannot
|
|
464
|
+
// return for a failure response — `throwIfFailure` puts the webpieces default behind an app
|
|
465
|
+
// translator that forgets to, so the guarantee does not depend on app code being correct.
|
|
466
|
+
ClientErrorTranslator_1.ClientErrorTranslator.throwFailure(this.responseDtoFactory.fromFetch(response, protocolError));
|
|
459
467
|
}
|
|
460
468
|
/** Preserve empty, JSON, and protocol text bodies for caller-owned full responses. */
|
|
461
469
|
// webpieces-disable no-any-unknown -- a full response deliberately preserves the caller-owned body
|
package/src/ProxyClient.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProxyClient.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/ProxyClient.ts"],"names":[],"mappings":";;;AAAA,oDAoB8B;AAG9B,mDAAgD;AAChD,mEAAgE;AAChE,qEAAkE;AAClE,qDAAkD;AAClD,6DAA0D;AAE1D,+DAA4D;AAC5D,2DAAwD;AACxD,yEAAsE;AAGtE,MAAM,wBAAwB;IAEb;IACA;IAFb,YACa,QAAkB,EAClB,MAA2B;QAD3B,aAAQ,GAAR,QAAQ,CAAU;QAClB,WAAM,GAAN,MAAM,CAAqB;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BAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAC/E,CAAC;YACN,CAAC;YACD,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC3B,CAAC;QACD,MAAM,aAAa,GAAG,MAAM,IAAI,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;IAED,sFAAsF;IACtF,mGAAmG;IAC3F,KAAK,CAAC,oBAAoB,CAAC,QAAkB;QACjD,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG;YAAE,OAAO,SAAS,CAAC;QACzE,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,IAAI,IAAI,KAAK,EAAE;YAAE,OAAO,SAAS,CAAC;QAClC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,CAAC;QACnD,qGAAqG;QACrG,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAY,CAAC;IACvC,CAAC;CACJ;AA1nBD,kCA0nBC","sourcesContent":["import {\n isApiPath,\n getEndpoints,\n AuthMeta,\n DestinationTrust,\n RouteMetadata,\n LogApiCallImpl,\n ApiMethodInfo,\n toError,\n NetworkRejectClassifier,\n HttpContractMapper,\n RouteMetadataFactory,\n FilterChain,\n CallRegistry,\n CallDeadline,\n CallContext,\n DtoValue,\n RequestStream,\n ResponseStream,\n StreamTransportError,\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';\nimport { NdjsonRequestStream } from './NdjsonRequestStream';\nimport { SseResponseStream } from './SseResponseStream';\nimport { StreamingCapabilityError } from './StreamingCapabilityError';\nimport { ByteReadableStream } from './ByteStream';\n\nclass OpenedStreamingTransport {\n constructor(\n readonly response: Response,\n readonly upload: NdjsonRequestStream,\n ) {}\n}\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` / `ContextFullUrlFilter`\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(\n 'client',\n this.apiName,\n route.methodName,\n undefined,\n route.mask,\n );\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 @WpAuthOidc 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 /** Whether fetch can read the response while its streaming request body remains open. */\n protected abstract supportsConcurrentDuplexFetch(): boolean;\n\n /** Environment-owned full-duplex transport after the shared filter chain has prepared it. */\n protected abstract sendStreamingTransport(\n request: ClientRequest,\n signal: AbortSignal,\n body: ByteReadableStream,\n ): Promise<Response>;\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(\n apiPrototype: ApiPrototype<object>,\n appFilters: ClientFilterDefinition[],\n ): 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 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 // Two endpoints on one method + path would dial the same URL; refuse the contract up front.\n RouteMetadataFactory.assertNoDuplicateRoutes(apiPrototype);\n\n this.routeMap = new Map<string, RouteMetadata>();\n for (const methodName of Object.keys(endpoints)) {\n // One shared factory joins and validates method/path/query/body metadata for every\n // transport, rather than letting each generated client reinterpret the decorators.\n const route = RouteMetadataFactory.create(apiPrototype, methodName);\n const authMeta = route.authMeta;\n this.assertEndpointSupported(authMeta, methodName);\n this.routeMap.set(methodName, route);\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 = [\n ...[...this.appFilters].sort(byPriority),\n ...[...this.clientFilters()].sort(byPriority),\n ];\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 const authMode = route.authMeta?.mode;\n // @WpAuthApiKey: 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 @WpAuthApiKey('${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 // @WpAuthWebhook is DELIBERATELY absent from this list. It used to be here, on the assumption\n // that the vendor is always somebody else — but `@WpAuthWebhook(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 if (route.streaming) return this.makeStreamingRequest(route, args);\n const mapped = HttpContractMapper.toWire(\n route.path,\n route.parameterBindings,\n route.bodyParameterIndex,\n args,\n );\n const logValue = mapped.body === undefined ? args : mapped.body;\n return this.execute(route, logValue, () => this.executeCall(route, args));\n }\n\n /** Open a typed stream without bypassing the ordinary context/auth/filter request pipeline. */\n // webpieces-disable no-any-unknown -- generated proxy arguments are runtime-validated here\n private async makeStreamingRequest(route: RouteMetadata, args: unknown[]): Promise<unknown> {\n if (!this.supportsConcurrentDuplexFetch()) {\n throw new StreamingCapabilityError(\n 'browser',\n 'Fetch request streaming is half-duplex and has no protocol-compatible full-duplex fallback.',\n );\n }\n const destination = this.responseStream(args);\n return this.execute(route, 'stream-open', () =>\n this.executeStreamingCall(route, destination),\n );\n }\n\n // webpieces-disable no-any-unknown -- generated proxy arguments are runtime-validated here\n private responseStream(args: unknown[]): ResponseStream<DtoValue> {\n const candidate = args[0];\n if (args.length !== 1 || typeof candidate !== 'object' || candidate === null) {\n throw new StreamTransportError(\n `${this.apiName} streaming methods require exactly one ResponseStream argument.`,\n );\n }\n // webpieces-disable no-any-unknown -- reflected method argument is narrowed by the method checks below\n const record = candidate as Record<string, unknown>;\n if (\n typeof record['event'] !== 'function' ||\n typeof record['fail'] !== 'function' ||\n typeof record['complete'] !== 'function' ||\n typeof record['onCancel'] !== 'function'\n ) {\n throw new StreamTransportError(\n `${this.apiName} streaming method argument does not implement ResponseStream.`,\n );\n }\n return candidate as ResponseStream<DtoValue>;\n }\n\n /** One streaming handshake. Subsequent events stay on this established transport. */\n private async executeStreamingCall(\n route: RouteMetadata,\n destination: ResponseStream<DtoValue>,\n ): Promise<RequestStream<DtoValue>> {\n this.onRequestStart(route);\n let response: Response | undefined;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- lifecycle reports the original handshake failure\n try {\n const requestStream = await CallRegistry.execute(\n this.apiClass,\n route.methodName,\n (timeoutMs: number) =>\n CallDeadline.run(\n timeoutMs,\n new CallContext(this.apiName, route.methodName),\n async (deadlineSignal: AbortSignal) => {\n const result = await this.openStreamingTransport(\n route,\n destination,\n deadlineSignal,\n );\n response = result.response;\n return result.upload;\n },\n ),\n 30_000,\n );\n this.onRequestEnd(\n route,\n new RequestOutcome(true, response?.status ?? 0, response?.headers),\n );\n return requestStream;\n } catch (err: unknown) {\n const error = toError(err);\n this.onRequestEnd(\n route,\n new RequestOutcome(false, response?.status ?? 0, response?.headers, error),\n );\n throw err;\n }\n }\n\n private async openStreamingTransport(\n route: RouteMetadata,\n destination: ResponseStream<DtoValue>,\n deadlineSignal: AbortSignal,\n ): Promise<OpenedStreamingTransport> {\n const metadata = route.streaming;\n if (!metadata) throw new StreamTransportError('Streaming metadata disappeared.');\n const request = await this.prepareStreamingRequest(route);\n const controller = new AbortController();\n deadlineSignal.addEventListener('abort', (): void => controller.abort(), { once: true });\n const upload = new NdjsonRequestStream(\n metadata,\n // webpieces-disable no-any-unknown -- AbortController accepts a platform-defined cancellation reason\n (reason?: unknown) => controller.abort(reason),\n );\n const response = await this.chain.execute(request, () =>\n this.sendStreamingOnce(request, controller.signal, upload.body),\n );\n if (!response.ok) {\n await upload.transportFailed(\n new StreamTransportError(\n `Streaming handshake failed with HTTP ${response.status}.`,\n ),\n );\n await this.readResponse(response, route);\n throw new StreamTransportError('Streaming handshake was rejected.');\n }\n const contentType = response.headers.get('content-type') ?? '';\n if (!contentType.toLowerCase().startsWith('text/event-stream')) {\n const error = new StreamTransportError(\n `Streaming response requires text/event-stream, received '${contentType || 'missing'}'.`,\n );\n await upload.transportFailed(error);\n throw error;\n }\n void new SseResponseStream()\n .consume(response, destination, metadata, upload)\n .catch(() => undefined);\n return new OpenedStreamingTransport(response, upload);\n }\n\n /** Fresh filter-visible request metadata; the live request body is transport-owned. */\n private async prepareStreamingRequest(route: RouteMetadata): Promise<ClientRequest> {\n const baseUrl = await this.resolveBaseUrl();\n const headers = new Map<string, string>();\n headers.set('Content-Type', 'application/x-ndjson');\n headers.set('Accept', 'text/event-stream');\n const context = this.outboundContextHeaders(\n DestinationTrust.forAuthMode(route.authMeta?.mode),\n );\n for (const entry of context.entries()) headers.set(entry[0], entry[1]);\n return new ClientRequest(route, this.apiName, baseUrl, headers, undefined, undefined);\n }\n\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n private async executeCall(route: RouteMetadata, args: 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(\n this.apiClass,\n route.methodName,\n (timeoutMs: number) => {\n response = undefined;\n return CallDeadline.run(\n timeoutMs,\n new CallContext(this.apiName, route.methodName),\n async (signal: AbortSignal) => {\n const request = await this.prepareRequest(route, args);\n CallDeadline.throwIfAborted(signal);\n const received = await this.chain.execute(request, () =>\n this.sendOnce(request, signal),\n );\n CallDeadline.throwIfAborted(signal);\n response = received;\n return this.readResponse(received, route);\n },\n );\n },\n 30_000,\n );\n } catch (err: unknown) {\n const error = toError(err);\n this.onRequestEnd(\n route,\n new RequestOutcome(false, response?.status ?? 0, response?.headers, error),\n );\n throw err;\n }\n this.onRequestEnd(\n route,\n new RequestOutcome(true, response?.status ?? 0, response?.headers),\n );\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, args: unknown[]): Promise<ClientRequest> {\n const baseUrl = await this.resolveBaseUrl();\n const mapped = HttpContractMapper.toWire(\n route.path,\n route.parameterBindings,\n route.bodyParameterIndex,\n args,\n );\n const headers = new Map<string, string>();\n const body = this.serializeBody(route, mapped.body, headers);\n const context = this.outboundContextHeaders(\n DestinationTrust.forAuthMode(route.authMeta?.mode),\n );\n for (const entry of context.entries()) headers.set(entry[0], entry[1]);\n return new ClientRequest(\n route,\n this.apiName,\n baseUrl,\n headers,\n body,\n mapped.body,\n mapped.path,\n );\n }\n\n /** Serialize exactly the encoding the endpoint declared; GET is always bodyless. */\n // webpieces-disable no-any-unknown -- request DTO type is erased at the generated proxy boundary\n private serializeBody(\n route: RouteMetadata,\n requestDto: unknown,\n headers: Map<string, string>,\n ): string | undefined {\n if (route.httpMethod === 'GET' || requestDto === undefined) return undefined;\n if (route.formPost) {\n headers.set('Content-Type', 'application/x-www-form-urlencoded');\n return this.serializeForm(requestDto, route);\n }\n headers.set('Content-Type', 'application/json');\n return JSON.stringify(requestDto);\n }\n\n /** Flat form DTO -> deterministic urlencoded bytes, repeating array-valued fields. */\n // webpieces-disable no-any-unknown -- form DTO fields are contract-owned and heterogeneous\n private serializeForm(requestDto: unknown, route: RouteMetadata): string {\n if (requestDto === null || typeof requestDto !== 'object' || Array.isArray(requestDto)) {\n throw new Error(\n `${this.apiName}.${route.methodName} declares formPost:true, so its body must be a flat object.`,\n );\n }\n const params = new URLSearchParams();\n // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag\n for (const key of Object.keys(requestDto as Record<string, unknown>).sort()) {\n // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag\n const value = (requestDto as Record<string, unknown>)[key];\n if (value === undefined || value === null) continue;\n const values = Array.isArray(value) ? value : [value];\n for (const item of values) {\n if (item !== undefined && item !== null) params.append(key, String(item));\n }\n }\n return params.toString();\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 ApiConnectionError 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 CallDeadline.throwIfAborted(signal);\n const options: RequestInit = {\n method: request.route.httpMethod,\n signal,\n headers: request.headersAsRecord(),\n redirect:\n request.route.responseType === 'full' || !request.followRedirects\n ? 'manual'\n : 'follow',\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 /** Node fetch's streaming upload option. Browser callers are refused before reaching here. */\n private async sendStreamingOnce(\n request: ClientRequest,\n signal: AbortSignal,\n body: ByteReadableStream,\n ): Promise<Response> {\n CallDeadline.throwIfAborted(signal);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- platform rejects are normalized below\n try {\n return await this.sendStreamingTransport(request, signal, body);\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 (route.responseType === 'full') {\n return this.responseDtoFactory.fromFetch(\n response,\n await this.readFullResponseBody(response),\n );\n }\n // 266 is protocol success, but its body represents an expected user exception.\n if (response.ok && response.status !== 266) {\n if (!this.bodyReader.isJson(response)) {\n throw new Error(\n this.bodyReader.describeForeignBody(response, callId, await response.text()),\n );\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 /** Preserve empty, JSON, and protocol text bodies for caller-owned full responses. */\n // webpieces-disable no-any-unknown -- a full response deliberately preserves the caller-owned body\n private async readFullResponseBody(response: Response): Promise<unknown> {\n if (response.status === 204 || response.status === 304) return undefined;\n const text = await response.text();\n if (text === '') return undefined;\n if (!this.bodyReader.isJson(response)) return text;\n // webpieces-disable no-any-unknown -- parsed JSON is returned untouched to the typed contract caller\n return JSON.parse(text) as unknown;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ProxyClient.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/ProxyClient.ts"],"names":[],"mappings":";;;AAAA,oDAoB8B;AAG9B,mDAAgD;AAChD,mEAAgE;AAChE,qEAAkE;AAClE,qDAAkD;AAClD,6DAA0D;AAC1D,+DAA4D;AAC5D,2DAAwD;AACxD,yEAAsE;AAGtE,MAAM,wBAAwB;IAEb;IACA;IAFb,YACa,QAAkB,EAClB,MAA2B;QAD3B,aAAQ,GAAR,QAAQ,CAAU;QAClB,WAAM,GAAN,MAAM,CAAqB;IACrC,CAAC;CACP;AAED;;;;;;;;;;;;;;;;;;;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,CAA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AAa,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAC5E,2FAA2F;QAC3F,4FAA4F;QAC5F,0FAA0F;QAC1F,6CAAqB,CAAC,YAAY,CAC9B,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,QAAQ,EAAE,aAAa,CAAC,CAC7D,CAAC;IACN,CAAC;IAED,sFAAsF;IACtF,mGAAmG;IAC3F,KAAK,CAAC,oBAAoB,CAAC,QAAkB;QACjD,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG;YAAE,OAAO,SAAS,CAAC;QACzE,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,IAAI,IAAI,KAAK,EAAE;YAAE,OAAO,SAAS,CAAC;QAClC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,CAAC;QACnD,qGAAqG;QACrG,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAY,CAAC;IACvC,CAAC;CACJ;AAzmBD,kCAymBC","sourcesContent":["import {\n isApiPath,\n getEndpoints,\n AuthMeta,\n DestinationTrust,\n RouteMetadata,\n LogApiCallImpl,\n ApiMethodInfo,\n toError,\n NetworkRejectClassifier,\n HttpContractMapper,\n RouteMetadataFactory,\n FilterChain,\n CallRegistry,\n CallDeadline,\n CallContext,\n DtoValue,\n RequestStream,\n ResponseStream,\n StreamTransportError,\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 { NdjsonRequestStream } from './NdjsonRequestStream';\nimport { SseResponseStream } from './SseResponseStream';\nimport { StreamingCapabilityError } from './StreamingCapabilityError';\nimport { ByteReadableStream } from './ByteStream';\n\nclass OpenedStreamingTransport {\n constructor(\n readonly response: Response,\n readonly upload: NdjsonRequestStream,\n ) {}\n}\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` / `ContextFullUrlFilter`\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} the registered `ErrorTranslator`\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(\n 'client',\n this.apiName,\n route.methodName,\n undefined,\n route.mask,\n );\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 @WpAuthOidc 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 /** Whether fetch can read the response while its streaming request body remains open. */\n protected abstract supportsConcurrentDuplexFetch(): boolean;\n\n /** Environment-owned full-duplex transport after the shared filter chain has prepared it. */\n protected abstract sendStreamingTransport(\n request: ClientRequest,\n signal: AbortSignal,\n body: ByteReadableStream,\n ): Promise<Response>;\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(\n apiPrototype: ApiPrototype<object>,\n appFilters: ClientFilterDefinition[],\n ): 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 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 // Two endpoints on one method + path would dial the same URL; refuse the contract up front.\n RouteMetadataFactory.assertNoDuplicateRoutes(apiPrototype);\n\n this.routeMap = new Map<string, RouteMetadata>();\n for (const methodName of Object.keys(endpoints)) {\n // One shared factory joins and validates method/path/query/body metadata for every\n // transport, rather than letting each generated client reinterpret the decorators.\n const route = RouteMetadataFactory.create(apiPrototype, methodName);\n const authMeta = route.authMeta;\n this.assertEndpointSupported(authMeta, methodName);\n this.routeMap.set(methodName, route);\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 = [\n ...[...this.appFilters].sort(byPriority),\n ...[...this.clientFilters()].sort(byPriority),\n ];\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 const authMode = route.authMeta?.mode;\n // @WpAuthApiKey: 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 @WpAuthApiKey('${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 // @WpAuthWebhook is DELIBERATELY absent from this list. It used to be here, on the assumption\n // that the vendor is always somebody else — but `@WpAuthWebhook(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 if (route.streaming) return this.makeStreamingRequest(route, args);\n const mapped = HttpContractMapper.toWire(\n route.path,\n route.parameterBindings,\n route.bodyParameterIndex,\n args,\n );\n const logValue = mapped.body === undefined ? args : mapped.body;\n return this.execute(route, logValue, () => this.executeCall(route, args));\n }\n\n /** Open a typed stream without bypassing the ordinary context/auth/filter request pipeline. */\n // webpieces-disable no-any-unknown -- generated proxy arguments are runtime-validated here\n private async makeStreamingRequest(route: RouteMetadata, args: unknown[]): Promise<unknown> {\n if (!this.supportsConcurrentDuplexFetch()) {\n throw new StreamingCapabilityError(\n 'browser',\n 'Fetch request streaming is half-duplex and has no protocol-compatible full-duplex fallback.',\n );\n }\n const destination = this.responseStream(args);\n return this.execute(route, 'stream-open', () =>\n this.executeStreamingCall(route, destination),\n );\n }\n\n // webpieces-disable no-any-unknown -- generated proxy arguments are runtime-validated here\n private responseStream(args: unknown[]): ResponseStream<DtoValue> {\n const candidate = args[0];\n if (args.length !== 1 || typeof candidate !== 'object' || candidate === null) {\n throw new StreamTransportError(\n `${this.apiName} streaming methods require exactly one ResponseStream argument.`,\n );\n }\n // webpieces-disable no-any-unknown -- reflected method argument is narrowed by the method checks below\n const record = candidate as Record<string, unknown>;\n if (\n typeof record['event'] !== 'function' ||\n typeof record['fail'] !== 'function' ||\n typeof record['complete'] !== 'function' ||\n typeof record['onCancel'] !== 'function'\n ) {\n throw new StreamTransportError(\n `${this.apiName} streaming method argument does not implement ResponseStream.`,\n );\n }\n return candidate as ResponseStream<DtoValue>;\n }\n\n /** One streaming handshake. Subsequent events stay on this established transport. */\n private async executeStreamingCall(\n route: RouteMetadata,\n destination: ResponseStream<DtoValue>,\n ): Promise<RequestStream<DtoValue>> {\n this.onRequestStart(route);\n let response: Response | undefined;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- lifecycle reports the original handshake failure\n try {\n const requestStream = await CallRegistry.execute(\n this.apiClass,\n route.methodName,\n (timeoutMs: number) =>\n CallDeadline.run(\n timeoutMs,\n new CallContext(this.apiName, route.methodName),\n async (deadlineSignal: AbortSignal) => {\n const result = await this.openStreamingTransport(\n route,\n destination,\n deadlineSignal,\n );\n response = result.response;\n return result.upload;\n },\n ),\n 30_000,\n );\n this.onRequestEnd(\n route,\n new RequestOutcome(true, response?.status ?? 0, response?.headers),\n );\n return requestStream;\n } catch (err: unknown) {\n const error = toError(err);\n this.onRequestEnd(\n route,\n new RequestOutcome(false, response?.status ?? 0, response?.headers, error),\n );\n throw err;\n }\n }\n\n private async openStreamingTransport(\n route: RouteMetadata,\n destination: ResponseStream<DtoValue>,\n deadlineSignal: AbortSignal,\n ): Promise<OpenedStreamingTransport> {\n const metadata = route.streaming;\n if (!metadata) throw new StreamTransportError('Streaming metadata disappeared.');\n const request = await this.prepareStreamingRequest(route);\n const controller = new AbortController();\n deadlineSignal.addEventListener('abort', (): void => controller.abort(), { once: true });\n const upload = new NdjsonRequestStream(\n metadata,\n // webpieces-disable no-any-unknown -- AbortController accepts a platform-defined cancellation reason\n (reason?: unknown) => controller.abort(reason),\n );\n const response = await this.chain.execute(request, () =>\n this.sendStreamingOnce(request, controller.signal, upload.body),\n );\n if (!response.ok) {\n await upload.transportFailed(\n new StreamTransportError(\n `Streaming handshake failed with HTTP ${response.status}.`,\n ),\n );\n await this.readResponse(response, route);\n throw new StreamTransportError('Streaming handshake was rejected.');\n }\n const contentType = response.headers.get('content-type') ?? '';\n if (!contentType.toLowerCase().startsWith('text/event-stream')) {\n const error = new StreamTransportError(\n `Streaming response requires text/event-stream, received '${contentType || 'missing'}'.`,\n );\n await upload.transportFailed(error);\n throw error;\n }\n void new SseResponseStream()\n .consume(response, destination, metadata, upload)\n .catch(() => undefined);\n return new OpenedStreamingTransport(response, upload);\n }\n\n /** Fresh filter-visible request metadata; the live request body is transport-owned. */\n private async prepareStreamingRequest(route: RouteMetadata): Promise<ClientRequest> {\n const baseUrl = await this.resolveBaseUrl();\n const headers = new Map<string, string>();\n headers.set('Content-Type', 'application/x-ndjson');\n headers.set('Accept', 'text/event-stream');\n const context = this.outboundContextHeaders(\n DestinationTrust.forAuthMode(route.authMeta?.mode),\n );\n for (const entry of context.entries()) headers.set(entry[0], entry[1]);\n return new ClientRequest(route, this.apiName, baseUrl, headers, undefined, undefined);\n }\n\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n private async executeCall(route: RouteMetadata, args: 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(\n this.apiClass,\n route.methodName,\n (timeoutMs: number) => {\n response = undefined;\n return CallDeadline.run(\n timeoutMs,\n new CallContext(this.apiName, route.methodName),\n async (signal: AbortSignal) => {\n const request = await this.prepareRequest(route, args);\n CallDeadline.throwIfAborted(signal);\n const received = await this.chain.execute(request, () =>\n this.sendOnce(request, signal),\n );\n CallDeadline.throwIfAborted(signal);\n response = received;\n return this.readResponse(received, route);\n },\n );\n },\n 30_000,\n );\n } catch (err: unknown) {\n const error = toError(err);\n this.onRequestEnd(\n route,\n new RequestOutcome(false, response?.status ?? 0, response?.headers, error),\n );\n throw err;\n }\n this.onRequestEnd(\n route,\n new RequestOutcome(true, response?.status ?? 0, response?.headers),\n );\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, args: unknown[]): Promise<ClientRequest> {\n const baseUrl = await this.resolveBaseUrl();\n const mapped = HttpContractMapper.toWire(\n route.path,\n route.parameterBindings,\n route.bodyParameterIndex,\n args,\n );\n const headers = new Map<string, string>();\n const body = this.serializeBody(route, mapped.body, headers);\n const context = this.outboundContextHeaders(\n DestinationTrust.forAuthMode(route.authMeta?.mode),\n );\n for (const entry of context.entries()) headers.set(entry[0], entry[1]);\n return new ClientRequest(\n route,\n this.apiName,\n baseUrl,\n headers,\n body,\n mapped.body,\n mapped.path,\n );\n }\n\n /** Serialize exactly the encoding the endpoint declared; GET is always bodyless. */\n // webpieces-disable no-any-unknown -- request DTO type is erased at the generated proxy boundary\n private serializeBody(\n route: RouteMetadata,\n requestDto: unknown,\n headers: Map<string, string>,\n ): string | undefined {\n if (route.httpMethod === 'GET' || requestDto === undefined) return undefined;\n if (route.formPost) {\n headers.set('Content-Type', 'application/x-www-form-urlencoded');\n return this.serializeForm(requestDto, route);\n }\n headers.set('Content-Type', 'application/json');\n return JSON.stringify(requestDto);\n }\n\n /** Flat form DTO -> deterministic urlencoded bytes, repeating array-valued fields. */\n // webpieces-disable no-any-unknown -- form DTO fields are contract-owned and heterogeneous\n private serializeForm(requestDto: unknown, route: RouteMetadata): string {\n if (requestDto === null || typeof requestDto !== 'object' || Array.isArray(requestDto)) {\n throw new Error(\n `${this.apiName}.${route.methodName} declares formPost:true, so its body must be a flat object.`,\n );\n }\n const params = new URLSearchParams();\n // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag\n for (const key of Object.keys(requestDto as Record<string, unknown>).sort()) {\n // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag\n const value = (requestDto as Record<string, unknown>)[key];\n if (value === undefined || value === null) continue;\n const values = Array.isArray(value) ? value : [value];\n for (const item of values) {\n if (item !== undefined && item !== null) params.append(key, String(item));\n }\n }\n return params.toString();\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 ApiConnectionError 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 CallDeadline.throwIfAborted(signal);\n const options: RequestInit = {\n method: request.route.httpMethod,\n signal,\n headers: request.headersAsRecord(),\n redirect:\n request.route.responseType === 'full' || !request.followRedirects\n ? 'manual'\n : 'follow',\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 /** Node fetch's streaming upload option. Browser callers are refused before reaching here. */\n private async sendStreamingOnce(\n request: ClientRequest,\n signal: AbortSignal,\n body: ByteReadableStream,\n ): Promise<Response> {\n CallDeadline.throwIfAborted(signal);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- platform rejects are normalized below\n try {\n return await this.sendStreamingTransport(request, signal, body);\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 (route.responseType === 'full') {\n return this.responseDtoFactory.fromFetch(\n response,\n await this.readFullResponseBody(response),\n );\n }\n // 266 is protocol success, but its body represents an expected user exception.\n if (response.ok && response.status !== 266) {\n if (!this.bodyReader.isJson(response)) {\n throw new Error(\n this.bodyReader.describeForeignBody(response, callId, await response.text()),\n );\n }\n // webpieces-disable no-any-unknown -- a success body is the caller's own DTO, erased here\n const body: unknown = await response.json();\n // EVERY response passes the seam, 2xx included: an app whose 200 body signals failure\n // turns it into a throw here. The webpieces default returns silently, so the success\n // path is unchanged — and the body is parsed ONCE, because a fetch body reads once.\n ClientErrorTranslator.throwIfFailure(\n this.responseDtoFactory.fromFetch(response, body),\n );\n return body;\n }\n const protocolError = await this.bodyReader.readErrorBody(response, callId);\n // The mirror of what the SERVER's `toWire` wrote. `fromWire` throws, so this method cannot\n // return for a failure response — `throwIfFailure` puts the webpieces default behind an app\n // translator that forgets to, so the guarantee does not depend on app code being correct.\n ClientErrorTranslator.throwFailure(\n this.responseDtoFactory.fromFetch(response, protocolError),\n );\n }\n\n /** Preserve empty, JSON, and protocol text bodies for caller-owned full responses. */\n // webpieces-disable no-any-unknown -- a full response deliberately preserves the caller-owned body\n private async readFullResponseBody(response: Response): Promise<unknown> {\n if (response.status === 204 || response.status === 304) return undefined;\n const text = await response.text();\n if (text === '') return undefined;\n if (!this.bodyReader.isJson(response)) return text;\n // webpieces-disable no-any-unknown -- parsed JSON is returned untouched to the typed contract caller\n return JSON.parse(text) as unknown;\n }\n}\n"]}
|
package/src/RequestOutcome.d.ts
CHANGED
|
@@ -25,11 +25,11 @@ export declare class RequestOutcome {
|
|
|
25
25
|
readonly headers?: Headers | undefined;
|
|
26
26
|
/**
|
|
27
27
|
* Set on every non-success path: for a non-2xx, the error the CALLER will see — i.e. what
|
|
28
|
-
* `
|
|
28
|
+
* the registered `ErrorTranslator`'s `fromWire` threw, so a
|
|
29
29
|
* listener never disagrees with the thrown exception (on a server that is the 500 wrapping a
|
|
30
30
|
* downstream 4xx, with the original reachable as `cause`). Otherwise the network/parse
|
|
31
31
|
* failure normalized through `toError`. Always a real `Error` — never `unknown`, because
|
|
32
|
-
* nothing here is untyped: `
|
|
32
|
+
* nothing here is untyped: `fromWire` THROWS a typed error, and every
|
|
33
33
|
* rejection reaching this class has been through `toError`.
|
|
34
34
|
*/
|
|
35
35
|
readonly error?: Error | undefined;
|
|
@@ -46,11 +46,11 @@ export declare class RequestOutcome {
|
|
|
46
46
|
headers?: Headers | undefined,
|
|
47
47
|
/**
|
|
48
48
|
* Set on every non-success path: for a non-2xx, the error the CALLER will see — i.e. what
|
|
49
|
-
* `
|
|
49
|
+
* the registered `ErrorTranslator`'s `fromWire` threw, so a
|
|
50
50
|
* listener never disagrees with the thrown exception (on a server that is the 500 wrapping a
|
|
51
51
|
* downstream 4xx, with the original reachable as `cause`). Otherwise the network/parse
|
|
52
52
|
* failure normalized through `toError`. Always a real `Error` — never `unknown`, because
|
|
53
|
-
* nothing here is untyped: `
|
|
53
|
+
* nothing here is untyped: `fromWire` THROWS a typed error, and every
|
|
54
54
|
* rejection reaching this class has been through `toError`.
|
|
55
55
|
*/
|
|
56
56
|
error?: Error | undefined);
|
package/src/RequestOutcome.js
CHANGED
|
@@ -33,11 +33,11 @@ class RequestOutcome {
|
|
|
33
33
|
headers,
|
|
34
34
|
/**
|
|
35
35
|
* Set on every non-success path: for a non-2xx, the error the CALLER will see — i.e. what
|
|
36
|
-
* `
|
|
36
|
+
* the registered `ErrorTranslator`'s `fromWire` threw, so a
|
|
37
37
|
* listener never disagrees with the thrown exception (on a server that is the 500 wrapping a
|
|
38
38
|
* downstream 4xx, with the original reachable as `cause`). Otherwise the network/parse
|
|
39
39
|
* failure normalized through `toError`. Always a real `Error` — never `unknown`, because
|
|
40
|
-
* nothing here is untyped: `
|
|
40
|
+
* nothing here is untyped: `fromWire` THROWS a typed error, and every
|
|
41
41
|
* rejection reaching this class has been through `toError`.
|
|
42
42
|
*/
|
|
43
43
|
error) {
|
|
@@ -1 +1 @@
|
|
|
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 API error\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 * `
|
|
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 API error\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 * the registered `ErrorTranslator`'s `fromWire` threw, 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 `cause`). Otherwise the network/parse\n * failure normalized through `toError`. Always a real `Error` — never `unknown`, because\n * nothing here is untyped: `fromWire` THROWS a typed error, and every\n * rejection reaching this class has been through `toError`.\n */\n public readonly error?: Error,\n ) {}\n}\n"]}
|
package/src/index.d.ts
CHANGED
|
@@ -29,9 +29,7 @@ export { RequestOutcome } from './RequestOutcome';
|
|
|
29
29
|
export type { ApiPrototype } from './ApiPrototype';
|
|
30
30
|
export { buildClientProxy } from './buildClientProxy';
|
|
31
31
|
export { ClientErrorTranslator } from './ClientErrorTranslator';
|
|
32
|
-
export { UnexpectedApiResponseError } from './UnexpectedApiResponseError';
|
|
33
32
|
export { HttpResponseDtoFactory } from './HttpResponseDtoFactory';
|
|
34
|
-
export { TranslatedFailure } from './TranslatedFailure';
|
|
35
33
|
export { ResponseBodyReader } from './ResponseBodyReader';
|
|
36
34
|
export { ClientRequest } from './ClientRequest';
|
|
37
35
|
export { ClientFilterDefinition } from './ClientFilter';
|
package/src/index.js
CHANGED
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
* a browser bundle, and nothing browser-only (a ContextReader store) reaches a server.
|
|
27
27
|
*/
|
|
28
28
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
-
exports.Utf8Codec = exports.StreamingCapabilityError = exports.StreamEnvelopeCodec = exports.SseResponseStream = exports.SseEventParser = exports.SseEvent = exports.NdjsonRequestStream = exports.ClientFilterDefinition = exports.ClientRequest = exports.ResponseBodyReader = exports.
|
|
29
|
+
exports.Utf8Codec = exports.StreamingCapabilityError = exports.StreamEnvelopeCodec = exports.SseResponseStream = exports.SseEventParser = exports.SseEvent = exports.NdjsonRequestStream = exports.ClientFilterDefinition = exports.ClientRequest = exports.ResponseBodyReader = exports.HttpResponseDtoFactory = exports.ClientErrorTranslator = exports.buildClientProxy = exports.RequestOutcome = exports.ProxyClient = void 0;
|
|
30
30
|
var ProxyClient_1 = require("./ProxyClient");
|
|
31
31
|
Object.defineProperty(exports, "ProxyClient", { enumerable: true, get: function () { return ProxyClient_1.ProxyClient; } });
|
|
32
32
|
var RequestOutcome_1 = require("./RequestOutcome");
|
|
@@ -35,14 +35,10 @@ var buildClientProxy_1 = require("./buildClientProxy");
|
|
|
35
35
|
Object.defineProperty(exports, "buildClientProxy", { enumerable: true, get: function () { return buildClientProxy_1.buildClientProxy; } });
|
|
36
36
|
var ClientErrorTranslator_1 = require("./ClientErrorTranslator");
|
|
37
37
|
Object.defineProperty(exports, "ClientErrorTranslator", { enumerable: true, get: function () { return ClientErrorTranslator_1.ClientErrorTranslator; } });
|
|
38
|
-
var UnexpectedApiResponseError_1 = require("./UnexpectedApiResponseError");
|
|
39
|
-
Object.defineProperty(exports, "UnexpectedApiResponseError", { enumerable: true, get: function () { return UnexpectedApiResponseError_1.UnexpectedApiResponseError; } });
|
|
40
38
|
// The CLIENT-side transport boundary: a fetch Response becomes the ONE HttpResponseDto an app's
|
|
41
|
-
//
|
|
39
|
+
// ErrorTranslator sees, so node and browser hand `fromWire` the identical shape.
|
|
42
40
|
var HttpResponseDtoFactory_1 = require("./HttpResponseDtoFactory");
|
|
43
41
|
Object.defineProperty(exports, "HttpResponseDtoFactory", { enumerable: true, get: function () { return HttpResponseDtoFactory_1.HttpResponseDtoFactory; } });
|
|
44
|
-
var TranslatedFailure_1 = require("./TranslatedFailure");
|
|
45
|
-
Object.defineProperty(exports, "TranslatedFailure", { enumerable: true, get: function () { return TranslatedFailure_1.TranslatedFailure; } });
|
|
46
42
|
var ResponseBodyReader_1 = require("./ResponseBodyReader");
|
|
47
43
|
Object.defineProperty(exports, "ResponseBodyReader", { enumerable: true, get: function () { return ResponseBodyReader_1.ResponseBodyReader; } });
|
|
48
44
|
// The OUTBOUND filter chain: the mutable request a filter edits, and one registration of a filter
|
package/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;;;AAEH,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AACpB,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AAEvB,uDAAsD;AAA7C,oHAAA,gBAAgB,OAAA;AACzB,iEAAgE;AAAvD,8HAAA,qBAAqB,OAAA;AAC9B,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;;;AAEH,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AACpB,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AAEvB,uDAAsD;AAA7C,oHAAA,gBAAgB,OAAA;AACzB,iEAAgE;AAAvD,8HAAA,qBAAqB,OAAA;AAC9B,gGAAgG;AAChG,iFAAiF;AACjF,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,2DAA0D;AAAjD,wHAAA,kBAAkB,OAAA;AAC3B,kGAAkG;AAClG,kFAAkF;AAClF,gEAAgE;AAChE,iDAAgD;AAAvC,8GAAA,aAAa,OAAA;AACtB,+CAAwD;AAA/C,sHAAA,sBAAsB,OAAA;AAE/B,6FAA6F;AAC7F,+FAA+F;AAC/F,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,mDAA4D;AAAnD,0GAAA,QAAQ,OAAA;AAAE,gHAAA,cAAc,OAAA;AACjC,yDAAwD;AAA/C,sHAAA,iBAAiB,OAAA;AAC1B,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,uEAAsE;AAA7D,oIAAA,wBAAwB,OAAA;AACjC,yCAAwC;AAA/B,sGAAA,SAAS,OAAA","sourcesContent":["/**\n * @webpieces/http-client-core\n *\n * The ISOMORPHIC core of the webpieces HTTP client — everything that reads an API contract's\n * decorators and turns a method call into an HTTP request, with no opinion about where the\n * magic context comes from or whether a DI container exists.\n *\n * You almost certainly want one of its two environment packages instead:\n * - Server: @webpieces/http-client-node (inversify-wired, reads RequestContext, mints OIDC)\n * - Browser: @webpieces/http-client-browser (no DI — React or Angular, app-managed context store)\n *\n * Architecture:\n * ```\n * http-api (defines the contract)\n * ^\n * +-- http-routing (server: contract -> handlers)\n * +-- http-client-core (contract -> HTTP requests) <- YOU ARE HERE\n * +-- http-client-node (RequestContext + Secrets + OIDC + inversify factory)\n * +-- http-client-browser (app-held store + plain factory, no DI)\n * ```\n *\n * There is no context/credential/recording seam here at all: ProxyClient is ABSTRACT and asks its\n * subclass for the base URL, the context headers, the log map, the outbound credential, and the\n * recorder. Nothing server-only (RequestContext, Secrets, mintIdToken, TestCaseRecorder) can reach\n * a browser bundle, and nothing browser-only (a ContextReader store) reaches a server.\n */\n\nexport { ProxyClient } from './ProxyClient';\nexport { RequestOutcome } from './RequestOutcome';\nexport type { ApiPrototype } from './ApiPrototype';\nexport { buildClientProxy } from './buildClientProxy';\nexport { ClientErrorTranslator } from './ClientErrorTranslator';\n// The CLIENT-side transport boundary: a fetch Response becomes the ONE HttpResponseDto an app's\n// ErrorTranslator sees, so node and browser hand `fromWire` the identical shape.\nexport { HttpResponseDtoFactory } from './HttpResponseDtoFactory';\nexport { ResponseBodyReader } from './ResponseBodyReader';\n// The OUTBOUND filter chain: the mutable request a filter edits, and one registration of a filter\n// at a priority. The `Filter`/`Service`/`FilterChain` abstraction itself lives in\n// @webpieces/core-util, shared with the server's inbound chain.\nexport { ClientRequest } from './ClientRequest';\nexport { ClientFilterDefinition } from './ClientFilter';\nexport type { ClientFilter } from './ClientFilter';\n// Generic streaming wire adapters: NDJSON uploads, request-scoped SSE downloads, and a typed\n// capability failure for runtimes that cannot safely keep both fetch halves open concurrently.\nexport { NdjsonRequestStream } from './NdjsonRequestStream';\nexport { SseEvent, SseEventParser } from './SseEventParser';\nexport { SseResponseStream } from './SseResponseStream';\nexport { StreamEnvelopeCodec } from './StreamEnvelopeCodec';\nexport { StreamingCapabilityError } from './StreamingCapabilityError';\nexport { Utf8Codec } from './Utf8Codec';\nexport type { ByteReadableStream, ByteStreamReader, ByteReadResult } from './ByteStream';\n"]}
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* What {@link ClientErrorTranslator.translateError} decided about ONE non-2xx downstream response —
|
|
3
|
-
* the typed error, plus WHO decided it.
|
|
4
|
-
*
|
|
5
|
-
* DATA ONLY (no behavior), so it is a class with an explicit constructor rather than an interface,
|
|
6
|
-
* exactly like {@link RequestOutcome}.
|
|
7
|
-
*
|
|
8
|
-
* WHY IT CARRIES `appRegistered` AT ALL: the translated error alone is not enough for an environment
|
|
9
|
-
* hook to act on. `ApiNotFoundError` produced by the BUILT-IN 404 branch and `ApiNotFoundError`
|
|
10
|
-
* produced by an app's own `ErrorTranslators` are indistinguishable as values, yet they mean opposite
|
|
11
|
-
* things — the first is the framework's generic default, the second is the app saying out loud, at
|
|
12
|
-
* startup and greppably, "relay this status as my own". `ProxyClient.adaptDownstreamFailure` must
|
|
13
|
-
* honour the second and is free to replace the first, so the provenance has to travel WITH the error
|
|
14
|
-
* rather than be re-derived by consulting `ClientRegistry` a second time.
|
|
15
|
-
*
|
|
16
|
-
* `statusCode` is the status the DOWNSTREAM answered — carried explicitly rather than read back off
|
|
17
|
-
* `error.code`, because an app-registered translation may legitimately return an error whose `code`
|
|
18
|
-
* is nothing like the status that produced it, and need not be a portable `ApiError` at all.
|
|
19
|
-
*/
|
|
20
|
-
export declare class TranslatedFailure {
|
|
21
|
-
/** The typed error the translator picked for this response. Always a real `Error`. */
|
|
22
|
-
readonly error: Error;
|
|
23
|
-
/**
|
|
24
|
-
* True when an app-registered `ClientRegistry` translation claimed this status — i.e. the app
|
|
25
|
-
* chose this error type deliberately, at startup, in one greppable place. False when the
|
|
26
|
-
* framework's built-in status mapping produced it.
|
|
27
|
-
*
|
|
28
|
-
* This IS the caller's explicit opt-out from any environment-specific rewrite: see
|
|
29
|
-
* `NodeProxyClient.adaptDownstreamFailure`, where an app-registered 4xx wins over the
|
|
30
|
-
* server-to-server 4xx-to-500 wrap.
|
|
31
|
-
*/
|
|
32
|
-
readonly appRegistered: boolean;
|
|
33
|
-
/** The HTTP status the downstream dependency actually answered with. */
|
|
34
|
-
readonly statusCode: number;
|
|
35
|
-
constructor(
|
|
36
|
-
/** The typed error the translator picked for this response. Always a real `Error`. */
|
|
37
|
-
error: Error,
|
|
38
|
-
/**
|
|
39
|
-
* True when an app-registered `ClientRegistry` translation claimed this status — i.e. the app
|
|
40
|
-
* chose this error type deliberately, at startup, in one greppable place. False when the
|
|
41
|
-
* framework's built-in status mapping produced it.
|
|
42
|
-
*
|
|
43
|
-
* This IS the caller's explicit opt-out from any environment-specific rewrite: see
|
|
44
|
-
* `NodeProxyClient.adaptDownstreamFailure`, where an app-registered 4xx wins over the
|
|
45
|
-
* server-to-server 4xx-to-500 wrap.
|
|
46
|
-
*/
|
|
47
|
-
appRegistered: boolean,
|
|
48
|
-
/** The HTTP status the downstream dependency actually answered with. */
|
|
49
|
-
statusCode: number);
|
|
50
|
-
}
|
package/src/TranslatedFailure.js
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.TranslatedFailure = void 0;
|
|
4
|
-
/**
|
|
5
|
-
* What {@link ClientErrorTranslator.translateError} decided about ONE non-2xx downstream response —
|
|
6
|
-
* the typed error, plus WHO decided it.
|
|
7
|
-
*
|
|
8
|
-
* DATA ONLY (no behavior), so it is a class with an explicit constructor rather than an interface,
|
|
9
|
-
* exactly like {@link RequestOutcome}.
|
|
10
|
-
*
|
|
11
|
-
* WHY IT CARRIES `appRegistered` AT ALL: the translated error alone is not enough for an environment
|
|
12
|
-
* hook to act on. `ApiNotFoundError` produced by the BUILT-IN 404 branch and `ApiNotFoundError`
|
|
13
|
-
* produced by an app's own `ErrorTranslators` are indistinguishable as values, yet they mean opposite
|
|
14
|
-
* things — the first is the framework's generic default, the second is the app saying out loud, at
|
|
15
|
-
* startup and greppably, "relay this status as my own". `ProxyClient.adaptDownstreamFailure` must
|
|
16
|
-
* honour the second and is free to replace the first, so the provenance has to travel WITH the error
|
|
17
|
-
* rather than be re-derived by consulting `ClientRegistry` a second time.
|
|
18
|
-
*
|
|
19
|
-
* `statusCode` is the status the DOWNSTREAM answered — carried explicitly rather than read back off
|
|
20
|
-
* `error.code`, because an app-registered translation may legitimately return an error whose `code`
|
|
21
|
-
* is nothing like the status that produced it, and need not be a portable `ApiError` at all.
|
|
22
|
-
*/
|
|
23
|
-
class TranslatedFailure {
|
|
24
|
-
error;
|
|
25
|
-
appRegistered;
|
|
26
|
-
statusCode;
|
|
27
|
-
constructor(
|
|
28
|
-
/** The typed error the translator picked for this response. Always a real `Error`. */
|
|
29
|
-
error,
|
|
30
|
-
/**
|
|
31
|
-
* True when an app-registered `ClientRegistry` translation claimed this status — i.e. the app
|
|
32
|
-
* chose this error type deliberately, at startup, in one greppable place. False when the
|
|
33
|
-
* framework's built-in status mapping produced it.
|
|
34
|
-
*
|
|
35
|
-
* This IS the caller's explicit opt-out from any environment-specific rewrite: see
|
|
36
|
-
* `NodeProxyClient.adaptDownstreamFailure`, where an app-registered 4xx wins over the
|
|
37
|
-
* server-to-server 4xx-to-500 wrap.
|
|
38
|
-
*/
|
|
39
|
-
appRegistered,
|
|
40
|
-
/** The HTTP status the downstream dependency actually answered with. */
|
|
41
|
-
statusCode) {
|
|
42
|
-
this.error = error;
|
|
43
|
-
this.appRegistered = appRegistered;
|
|
44
|
-
this.statusCode = statusCode;
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
exports.TranslatedFailure = TranslatedFailure;
|
|
48
|
-
//# sourceMappingURL=TranslatedFailure.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"TranslatedFailure.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/TranslatedFailure.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,iBAAiB;IAGN;IAUA;IAEA;IAdpB;IACI,sFAAsF;IACtE,KAAY;IAC5B;;;;;;;;OAQG;IACa,aAAsB;IACtC,wEAAwE;IACxD,UAAkB;QAZlB,UAAK,GAAL,KAAK,CAAO;QAUZ,kBAAa,GAAb,aAAa,CAAS;QAEtB,eAAU,GAAV,UAAU,CAAQ;IACnC,CAAC;CACP;AAjBD,8CAiBC","sourcesContent":["/**\n * What {@link ClientErrorTranslator.translateError} decided about ONE non-2xx downstream response —\n * the typed error, plus WHO decided it.\n *\n * DATA ONLY (no behavior), so it is a class with an explicit constructor rather than an interface,\n * exactly like {@link RequestOutcome}.\n *\n * WHY IT CARRIES `appRegistered` AT ALL: the translated error alone is not enough for an environment\n * hook to act on. `ApiNotFoundError` produced by the BUILT-IN 404 branch and `ApiNotFoundError`\n * produced by an app's own `ErrorTranslators` are indistinguishable as values, yet they mean opposite\n * things — the first is the framework's generic default, the second is the app saying out loud, at\n * startup and greppably, \"relay this status as my own\". `ProxyClient.adaptDownstreamFailure` must\n * honour the second and is free to replace the first, so the provenance has to travel WITH the error\n * rather than be re-derived by consulting `ClientRegistry` a second time.\n *\n * `statusCode` is the status the DOWNSTREAM answered — carried explicitly rather than read back off\n * `error.code`, because an app-registered translation may legitimately return an error whose `code`\n * is nothing like the status that produced it, and need not be a portable `ApiError` at all.\n */\nexport class TranslatedFailure {\n constructor(\n /** The typed error the translator picked for this response. Always a real `Error`. */\n public readonly error: Error,\n /**\n * True when an app-registered `ClientRegistry` translation claimed this status — i.e. the app\n * chose this error type deliberately, at startup, in one greppable place. False when the\n * framework's built-in status mapping produced it.\n *\n * This IS the caller's explicit opt-out from any environment-specific rewrite: see\n * `NodeProxyClient.adaptDownstreamFailure`, where an app-registered 4xx wins over the\n * server-to-server 4xx-to-500 wrap.\n */\n public readonly appRegistered: boolean,\n /** The HTTP status the downstream dependency actually answered with. */\n public readonly statusCode: number,\n ) {}\n}\n"]}
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.UnexpectedApiResponseError = void 0;
|
|
4
|
-
/** HTTP adapter failure for a status outside 100-599 (so not an ApiCodedError) not claimed by an app translator. */
|
|
5
|
-
class UnexpectedApiResponseError extends Error {
|
|
6
|
-
statusCode;
|
|
7
|
-
constructor(statusCode, message) {
|
|
8
|
-
super(message);
|
|
9
|
-
this.statusCode = statusCode;
|
|
10
|
-
this.name = 'UnexpectedApiResponseError';
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
exports.UnexpectedApiResponseError = UnexpectedApiResponseError;
|
|
14
|
-
//# sourceMappingURL=UnexpectedApiResponseError.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"UnexpectedApiResponseError.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/UnexpectedApiResponseError.ts"],"names":[],"mappings":";;;AAAA,oHAAoH;AACpH,MAAa,0BAA2B,SAAQ,KAAK;IAE7B;IADpB,YACoB,UAAkB,EAClC,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,eAAU,GAAV,UAAU,CAAQ;QAIlC,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAC;IAC7C,CAAC;CACJ;AARD,gEAQC","sourcesContent":["/** HTTP adapter failure for a status outside 100-599 (so not an ApiCodedError) not claimed by an app translator. */\nexport class UnexpectedApiResponseError extends Error {\n constructor(\n public readonly statusCode: number,\n message: string,\n ) {\n super(message);\n this.name = 'UnexpectedApiResponseError';\n }\n}\n"]}
|