@distilled.cloud/core 1.0.0-rc.2 → 1.0.0-rc.20
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/LICENSE +201 -0
- package/lib/_bundle/aws.js +2 -0
- package/lib/_bundle/aws.js.map +1 -0
- package/lib/_bundle/base.js +5 -0
- package/lib/_bundle/base.js.map +1 -0
- package/lib/_bundle/graphql.js +3 -0
- package/lib/_bundle/graphql.js.map +1 -0
- package/lib/_bundle/grpc.js +2 -0
- package/lib/_bundle/grpc.js.map +1 -0
- package/lib/_bundle/rest.js +2 -0
- package/lib/_bundle/rest.js.map +1 -0
- package/lib/_bundle/xml.js +4 -0
- package/lib/_bundle/xml.js.map +1 -0
- package/lib/annotations.d.ts +17 -0
- package/lib/annotations.d.ts.map +1 -0
- package/lib/annotations.js +2 -0
- package/lib/annotations.js.map +1 -0
- package/lib/api.d.ts +174 -18
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +1 -178
- package/lib/category.d.ts +4 -4
- package/lib/category.d.ts.map +1 -1
- package/lib/category.js +1 -280
- package/lib/chunks.d.ts +3 -0
- package/lib/chunks.d.ts.map +1 -0
- package/lib/chunks.js +1 -0
- package/lib/config.d.ts +68 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +1 -0
- package/lib/crypto.d.ts +76 -0
- package/lib/crypto.d.ts.map +1 -0
- package/lib/crypto.js +1 -0
- package/lib/error-category.d.ts +1 -1
- package/lib/error-category.d.ts.map +1 -1
- package/lib/error-category.js +1 -46
- package/lib/errors.d.ts +64 -72
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -186
- package/lib/graphql.d.ts +403 -0
- package/lib/graphql.d.ts.map +1 -0
- package/lib/graphql.js +1 -0
- package/lib/graphql.types.d.ts +12 -0
- package/lib/graphql.types.d.ts.map +1 -0
- package/lib/graphql.types.js +1 -0
- package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-http2.js +6 -0
- package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.js +5 -0
- package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
- package/lib/grpc-transport-node-http2.d.ts +19 -0
- package/lib/grpc-transport-node-http2.d.ts.map +1 -0
- package/lib/grpc-transport-node-http2.js +2 -0
- package/lib/grpc-transport-node-http2.js.map +1 -0
- package/lib/grpc-transport.d.ts +76 -0
- package/lib/grpc-transport.d.ts.map +1 -0
- package/lib/grpc-transport.js +1 -0
- package/lib/hpack.d.ts +34 -0
- package/lib/hpack.d.ts.map +1 -0
- package/lib/hpack.js +2 -0
- package/lib/hpack.js.map +1 -0
- package/lib/index.d.ts +32 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +17 -0
- package/lib/pagination.d.ts +101 -24
- package/lib/pagination.d.ts.map +1 -1
- package/lib/pagination.js +1 -182
- package/lib/plain-values.d.ts +10 -0
- package/lib/plain-values.d.ts.map +1 -0
- package/lib/plain-values.js +2 -0
- package/lib/plain-values.js.map +1 -0
- package/lib/protobuf.d.ts +92 -0
- package/lib/protobuf.d.ts.map +1 -0
- package/lib/protobuf.js +1 -0
- package/lib/protocol-grpc.d.ts +86 -0
- package/lib/protocol-grpc.d.ts.map +1 -0
- package/lib/protocol-grpc.js +1 -0
- package/lib/protocol-http.d.ts +102 -23
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-http.js +1 -554
- package/lib/protocol-rest.d.ts +120 -50
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/protocol-rest.js +1 -242
- package/lib/query.d.ts +29 -0
- package/lib/query.d.ts.map +1 -0
- package/lib/query.js +1 -0
- package/lib/response-validation-strict.d.ts +48 -0
- package/lib/response-validation-strict.d.ts.map +1 -0
- package/lib/response-validation-strict.js +1 -0
- package/lib/response-validation.d.ts +86 -0
- package/lib/response-validation.d.ts.map +1 -0
- package/lib/response-validation.js +1 -0
- package/lib/retry-after.d.ts +3 -3
- package/lib/retry-after.d.ts.map +1 -1
- package/lib/retry-after.js +1 -112
- package/lib/retry.d.ts +48 -29
- package/lib/retry.d.ts.map +1 -1
- package/lib/retry.js +1 -210
- package/lib/schema-lite-impl.d.ts +158 -0
- package/lib/schema-lite-impl.d.ts.map +1 -0
- package/lib/schema-lite-impl.js +1 -0
- package/lib/schema-lite-typed.d.ts +41 -0
- package/lib/schema-lite-typed.d.ts.map +1 -0
- package/lib/schema-lite-typed.js +1 -0
- package/lib/schema-lite.d.ts +40 -0
- package/lib/schema-lite.d.ts.map +1 -0
- package/lib/schema-lite.js +1 -0
- package/lib/schema.d.ts +21 -7
- package/lib/schema.d.ts.map +1 -1
- package/lib/schema.js +1 -48
- package/lib/sdk-error.d.ts +27 -0
- package/lib/sdk-error.d.ts.map +1 -0
- package/lib/sdk-error.js +1 -0
- package/lib/sensitive.d.ts +28 -0
- package/lib/sensitive.d.ts.map +1 -0
- package/lib/sensitive.js +2 -0
- package/lib/sensitive.js.map +1 -0
- package/lib/telemetry-debug.d.ts +6 -0
- package/lib/telemetry-debug.d.ts.map +1 -0
- package/lib/telemetry-debug.js +2 -0
- package/lib/telemetry-debug.js.map +1 -0
- package/lib/telemetry-hooks.d.ts +32 -0
- package/lib/telemetry-hooks.d.ts.map +1 -0
- package/lib/telemetry-hooks.js +2 -0
- package/lib/telemetry-hooks.js.map +1 -0
- package/lib/telemetry-host-rules.d.ts +23 -0
- package/lib/telemetry-host-rules.d.ts.map +1 -0
- package/lib/telemetry-host-rules.js +2 -0
- package/lib/telemetry-host-rules.js.map +1 -0
- package/lib/telemetry-lambda-context.d.ts +17 -0
- package/lib/telemetry-lambda-context.d.ts.map +1 -0
- package/lib/telemetry-lambda-context.js +2 -0
- package/lib/telemetry-lambda-context.js.map +1 -0
- package/lib/telemetry-message-context.d.ts +52 -0
- package/lib/telemetry-message-context.d.ts.map +1 -0
- package/lib/telemetry-message-context.js +2 -0
- package/lib/telemetry-message-context.js.map +1 -0
- package/lib/telemetry-metrics.d.ts +6 -0
- package/lib/telemetry-metrics.d.ts.map +1 -0
- package/lib/telemetry-metrics.js +2 -0
- package/lib/telemetry-metrics.js.map +1 -0
- package/lib/telemetry-name-template.d.ts +13 -0
- package/lib/telemetry-name-template.d.ts.map +1 -0
- package/lib/telemetry-name-template.js +2 -0
- package/lib/telemetry-name-template.js.map +1 -0
- package/lib/telemetry-stream.d.ts +11 -0
- package/lib/telemetry-stream.d.ts.map +1 -0
- package/lib/telemetry-stream.js +2 -0
- package/lib/telemetry-stream.js.map +1 -0
- package/lib/telemetry-xray.d.ts +28 -0
- package/lib/telemetry-xray.d.ts.map +1 -0
- package/lib/telemetry-xray.js +2 -0
- package/lib/telemetry-xray.js.map +1 -0
- package/lib/telemetry.d.ts +288 -0
- package/lib/telemetry.d.ts.map +1 -0
- package/lib/telemetry.js +3 -0
- package/lib/telemetry.js.map +1 -0
- package/lib/trait.d.ts +71 -20
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +1 -107
- package/lib/unknown-error.d.ts +18 -0
- package/lib/unknown-error.d.ts.map +1 -0
- package/lib/unknown-error.js +1 -0
- package/lib/xml.d.ts +44 -0
- package/lib/xml.d.ts.map +1 -0
- package/lib/xml.js +1 -0
- package/package.json +13 -13
- package/src/annotations.ts +53 -0
- package/src/api.ts +1370 -200
- package/src/category.ts +76 -106
- package/src/chunks.ts +30 -0
- package/src/config.ts +245 -0
- package/src/crypto.ts +202 -0
- package/src/error-category.ts +16 -29
- package/src/errors.ts +75 -75
- package/src/graphql.ts +1778 -0
- package/src/graphql.types.ts +105 -0
- package/src/grpc-transport-cloudflare-http2.ts +494 -0
- package/src/grpc-transport-cloudflare-sockets.ts +299 -0
- package/src/grpc-transport-node-http2.ts +234 -0
- package/src/grpc-transport.ts +118 -0
- package/src/hpack.ts +331 -0
- package/src/index.ts +31 -0
- package/src/pagination.ts +368 -94
- package/src/plain-values.ts +41 -0
- package/src/protobuf.ts +1332 -0
- package/src/protocol-grpc.ts +641 -0
- package/src/protocol-http.ts +622 -322
- package/src/protocol-rest.ts +440 -227
- package/src/query.ts +39 -0
- package/src/response-validation-strict.ts +327 -0
- package/src/response-validation.ts +161 -0
- package/src/retry-after.ts +7 -13
- package/src/retry.ts +96 -110
- package/src/schema-lite-impl.ts +550 -0
- package/src/schema-lite-typed.ts +44 -0
- package/src/schema-lite.ts +44 -0
- package/src/schema.ts +259 -15
- package/src/sdk-error.ts +33 -0
- package/src/sensitive.ts +154 -0
- package/src/telemetry-debug.ts +179 -0
- package/src/telemetry-hooks.ts +33 -0
- package/src/telemetry-host-rules.ts +39 -0
- package/src/telemetry-lambda-context.ts +46 -0
- package/src/telemetry-message-context.ts +170 -0
- package/src/telemetry-metrics.ts +69 -0
- package/src/telemetry-name-template.ts +26 -0
- package/src/telemetry-stream.ts +100 -0
- package/src/telemetry-xray.ts +66 -0
- package/src/telemetry.ts +832 -0
- package/src/trait.ts +106 -67
- package/src/unknown-error.ts +38 -0
- package/src/xml.ts +346 -0
- package/lib/api.js.map +0 -1
- package/lib/category.js.map +0 -1
- package/lib/codegen/cli.d.ts +0 -29
- package/lib/codegen/cli.d.ts.map +0 -1
- package/lib/codegen/cli.js +0 -165
- package/lib/codegen/cli.js.map +0 -1
- package/lib/codegen/emit.d.ts +0 -129
- package/lib/codegen/emit.d.ts.map +0 -1
- package/lib/codegen/emit.js +0 -105
- package/lib/codegen/emit.js.map +0 -1
- package/lib/codegen/format.d.ts +0 -23
- package/lib/codegen/format.d.ts.map +0 -1
- package/lib/codegen/format.js +0 -28
- package/lib/codegen/format.js.map +0 -1
- package/lib/codegen/generator.d.ts +0 -334
- package/lib/codegen/generator.d.ts.map +0 -1
- package/lib/codegen/generator.js +0 -691
- package/lib/codegen/generator.js.map +0 -1
- package/lib/codegen/graph.d.ts +0 -36
- package/lib/codegen/graph.d.ts.map +0 -1
- package/lib/codegen/graph.js +0 -136
- package/lib/codegen/graph.js.map +0 -1
- package/lib/codegen/members.d.ts +0 -25
- package/lib/codegen/members.d.ts.map +0 -1
- package/lib/codegen/members.js +0 -55
- package/lib/codegen/members.js.map +0 -1
- package/lib/codegen/naming.d.ts +0 -29
- package/lib/codegen/naming.d.ts.map +0 -1
- package/lib/codegen/naming.js +0 -74
- package/lib/codegen/naming.js.map +0 -1
- package/lib/codegen/openapi-cli.d.ts +0 -38
- package/lib/codegen/openapi-cli.d.ts.map +0 -1
- package/lib/codegen/openapi-cli.js +0 -107
- package/lib/codegen/openapi-cli.js.map +0 -1
- package/lib/codegen/openapi.d.ts +0 -115
- package/lib/codegen/openapi.d.ts.map +0 -1
- package/lib/codegen/openapi.js +0 -1220
- package/lib/codegen/openapi.js.map +0 -1
- package/lib/codegen/operations.d.ts +0 -24
- package/lib/codegen/operations.d.ts.map +0 -1
- package/lib/codegen/operations.js +0 -56
- package/lib/codegen/operations.js.map +0 -1
- package/lib/codegen/pagination.d.ts +0 -39
- package/lib/codegen/pagination.d.ts.map +0 -1
- package/lib/codegen/pagination.js +0 -33
- package/lib/codegen/pagination.js.map +0 -1
- package/lib/codegen/prelude.d.ts +0 -15
- package/lib/codegen/prelude.d.ts.map +0 -1
- package/lib/codegen/prelude.js +0 -60
- package/lib/codegen/prelude.js.map +0 -1
- package/lib/error-category.js.map +0 -1
- package/lib/errors.js.map +0 -1
- package/lib/json-patch.d.ts +0 -44
- package/lib/json-patch.d.ts.map +0 -1
- package/lib/json-patch.js +0 -174
- package/lib/json-patch.js.map +0 -1
- package/lib/pagination.js.map +0 -1
- package/lib/protocol-http.js.map +0 -1
- package/lib/protocol-rest.js.map +0 -1
- package/lib/retry-after.js.map +0 -1
- package/lib/retry.js.map +0 -1
- package/lib/schema.js.map +0 -1
- package/lib/trait.js.map +0 -1
- package/src/codegen/cli.ts +0 -268
- package/src/codegen/emit.ts +0 -207
- package/src/codegen/format.ts +0 -47
- package/src/codegen/generator.ts +0 -1153
- package/src/codegen/graph.ts +0 -151
- package/src/codegen/members.ts +0 -71
- package/src/codegen/naming.ts +0 -86
- package/src/codegen/openapi-cli.ts +0 -166
- package/src/codegen/openapi.ts +0 -1450
- package/src/codegen/operations.ts +0 -76
- package/src/codegen/pagination.ts +0 -71
- package/src/codegen/prelude.ts +0 -70
- package/src/json-patch.ts +0 -222
package/src/protocol-http.ts
CHANGED
|
@@ -1,18 +1,27 @@
|
|
|
1
|
+
import * as Effect from "effect/Effect";
|
|
2
|
+
import * as Headers from "effect/http/Headers";
|
|
3
|
+
import * as HttpBody from "effect/http/HttpBody";
|
|
4
|
+
import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
1
5
|
/**
|
|
2
6
|
* Generic REST protocol machinery, shared by SDK protocol layers.
|
|
3
7
|
*
|
|
4
8
|
* Everything here is driven purely by the trait annotations in
|
|
5
|
-
* `core/trait.ts`
|
|
9
|
+
* `core/trait.ts` -- nothing is provider-specific. An SDK protocol (e.g.
|
|
6
10
|
* cloudflare's) supplies credentials/base-URL, calls {@link buildRequest} to
|
|
7
11
|
* encode, and layers its own response-envelope handling on top of the
|
|
8
12
|
* decode-side helpers ({@link getProps}/{@link mapKeys}/
|
|
9
13
|
* {@link matchTypedError}).
|
|
10
14
|
*/
|
|
11
15
|
import type * as AST from "effect/SchemaAST";
|
|
12
|
-
import
|
|
13
|
-
import * as
|
|
16
|
+
import { getAnn, getProps, resolveNode } from "./annotations.ts";
|
|
17
|
+
import * as Category from "./category.ts";
|
|
18
|
+
import { isOpaqueValue } from "./plain-values.ts";
|
|
19
|
+
import * as Schema from "./schema-lite-typed.ts";
|
|
20
|
+
import { SdkError } from "./sdk-error.ts";
|
|
21
|
+
import { restoreStack, suppressStack } from "./telemetry.ts";
|
|
14
22
|
import {
|
|
15
23
|
bodySymbol,
|
|
24
|
+
commaDelimitedSymbol,
|
|
16
25
|
deepQuerySymbol,
|
|
17
26
|
formDataFileSymbol,
|
|
18
27
|
getErrorMatchers,
|
|
@@ -21,83 +30,93 @@ import {
|
|
|
21
30
|
httpSymbol,
|
|
22
31
|
keyDictionarySymbol,
|
|
23
32
|
labelSymbol,
|
|
33
|
+
labelEncodingSymbol,
|
|
24
34
|
querySymbol,
|
|
35
|
+
stringEncodedSymbol,
|
|
25
36
|
unionCasesSymbol,
|
|
26
37
|
type ErrorMatcher,
|
|
38
|
+
type ErrorTextMatcher,
|
|
27
39
|
type HttpTrait,
|
|
28
40
|
type KeyDictionaryEntries,
|
|
41
|
+
type UnionDiscriminator,
|
|
29
42
|
} from "./trait.ts";
|
|
30
43
|
|
|
31
44
|
//#region AST helpers (survive S.optional / Suspend / transforms)
|
|
32
45
|
|
|
33
|
-
export
|
|
34
|
-
if (ast._tag === "Objects") return ast.propertySignatures;
|
|
35
|
-
if (ast._tag === "Suspend") return getProps(ast.thunk());
|
|
36
|
-
if (ast.encoding && ast.encoding.length > 0)
|
|
37
|
-
return getProps(ast.encoding[0]!.to);
|
|
38
|
-
return [];
|
|
39
|
-
};
|
|
40
|
-
|
|
41
|
-
export const getAnn = (ast: AST.AST, symbol: symbol): unknown => {
|
|
42
|
-
const direct = (ast.annotations as Record<symbol, unknown> | undefined)?.[
|
|
43
|
-
symbol
|
|
44
|
-
];
|
|
45
|
-
if (direct !== undefined) return direct;
|
|
46
|
-
if (ast._tag === "Suspend") return getAnn(ast.thunk(), symbol);
|
|
47
|
-
if (ast.encoding && ast.encoding.length > 0)
|
|
48
|
-
return getAnn(ast.encoding[0]!.to, symbol);
|
|
49
|
-
// S.optional → Union[self, Undefined]; descend into the single real member.
|
|
50
|
-
if (ast._tag === "Union") {
|
|
51
|
-
const real = (ast as AST.Union).types.filter(
|
|
52
|
-
(t) =>
|
|
53
|
-
t._tag !== "Undefined" &&
|
|
54
|
-
!(t._tag === "Literal" && (t as any).literal === null),
|
|
55
|
-
);
|
|
56
|
-
if (real.length === 1) return getAnn(real[0]!, symbol);
|
|
57
|
-
}
|
|
58
|
-
return undefined;
|
|
59
|
-
};
|
|
46
|
+
export { getAnn, getProps, resolveNode } from "./annotations.ts";
|
|
60
47
|
|
|
61
|
-
export const getPropAnn = (
|
|
62
|
-
prop
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
export const hasPropAnn = (
|
|
66
|
-
prop: AST.PropertySignature,
|
|
67
|
-
symbol: symbol,
|
|
68
|
-
): boolean => getPropAnn(prop, symbol) !== undefined;
|
|
48
|
+
export const getPropAnn = (prop: AST.PropertySignature, symbol: symbol): unknown =>
|
|
49
|
+
getAnn(prop.type, symbol);
|
|
50
|
+
export const hasPropAnn = (prop: AST.PropertySignature, symbol: symbol): boolean =>
|
|
51
|
+
getPropAnn(prop, symbol) !== undefined;
|
|
69
52
|
export const nameOf = (prop: AST.PropertySignature, symbol: symbol): string => {
|
|
70
53
|
const v = getPropAnn(prop, symbol);
|
|
71
54
|
return typeof v === "string" ? v : String(prop.name);
|
|
72
55
|
};
|
|
73
56
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
57
|
+
//#endregion
|
|
58
|
+
|
|
59
|
+
//#region Response headers on outputs
|
|
60
|
+
|
|
61
|
+
/** An output member read from a response header (`T.Header`). */
|
|
62
|
+
export interface ResponseHeaderMember {
|
|
63
|
+
readonly key: string;
|
|
64
|
+
/** Lowercase header name. */
|
|
65
|
+
readonly wire: string;
|
|
66
|
+
/** The member is a number; the header's text is parsed. */
|
|
67
|
+
readonly number: boolean;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const noHeaderMembers: ReadonlyArray<ResponseHeaderMember> = [];
|
|
71
|
+
const headerMemberCache = /*@__PURE__*/ new WeakMap<AST.AST, ReadonlyArray<ResponseHeaderMember>>();
|
|
72
|
+
|
|
73
|
+
/** The output's header-bound members, read from the schema once. */
|
|
74
|
+
export const responseHeaderMembers = (outputAst: AST.AST): ReadonlyArray<ResponseHeaderMember> => {
|
|
75
|
+
let members = headerMemberCache.get(outputAst);
|
|
76
|
+
if (members !== undefined) return members;
|
|
77
|
+
const found: ResponseHeaderMember[] = [];
|
|
78
|
+
for (const prop of getProps(outputAst)) {
|
|
79
|
+
if (!hasPropAnn(prop, headerSymbol)) continue;
|
|
80
|
+
found.push({
|
|
81
|
+
key: String(prop.name),
|
|
82
|
+
wire: nameOf(prop, headerSymbol).toLowerCase(),
|
|
83
|
+
number: resolveNode(prop.type)._tag === "Number",
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
members = found.length === 0 ? noHeaderMembers : found;
|
|
87
|
+
headerMemberCache.set(outputAst, members);
|
|
88
|
+
return members;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Copy the response headers an output declares onto its decoded body. A
|
|
93
|
+
* number member gets the header parsed; text that is not a number is kept
|
|
94
|
+
* as sent, so strict validation reports it. A body that is not an object
|
|
95
|
+
* (a raw root) is returned as is -- generators bind no headers there.
|
|
96
|
+
*/
|
|
97
|
+
export const withResponseHeaders = (
|
|
98
|
+
members: ReadonlyArray<ResponseHeaderMember>,
|
|
99
|
+
body: unknown,
|
|
100
|
+
headers: Record<string, string | undefined>,
|
|
101
|
+
): unknown => {
|
|
102
|
+
if (members.length === 0 || body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
103
|
+
return body;
|
|
104
|
+
}
|
|
105
|
+
let result: Record<string, unknown> | undefined;
|
|
106
|
+
for (const m of members) {
|
|
107
|
+
const raw = headers[m.wire];
|
|
108
|
+
if (raw === undefined) continue;
|
|
109
|
+
result ??= { ...(body as Record<string, unknown>) };
|
|
110
|
+
const parsed = m.number && raw.trim() !== "" ? Number(raw) : Number.NaN;
|
|
111
|
+
result[m.key] = Number.isNaN(parsed) ? raw : parsed;
|
|
87
112
|
}
|
|
88
|
-
return
|
|
113
|
+
return result ?? body;
|
|
89
114
|
};
|
|
90
115
|
//#endregion
|
|
91
116
|
|
|
92
117
|
//#region Recursive wire-name mapping
|
|
93
118
|
|
|
94
|
-
|
|
95
|
-
export const isOpaqueValue = (v: unknown): boolean =>
|
|
96
|
-
v instanceof Blob ||
|
|
97
|
-
v instanceof File ||
|
|
98
|
-
v instanceof ArrayBuffer ||
|
|
99
|
-
v instanceof Uint8Array ||
|
|
100
|
-
v instanceof Date;
|
|
119
|
+
export { isOpaqueValue };
|
|
101
120
|
|
|
102
121
|
/**
|
|
103
122
|
* Deep-rename keys via a plain dictionary (see `T.KeyDictionary`). An entry
|
|
@@ -119,9 +138,7 @@ export const mapKeysByDictionary = (
|
|
|
119
138
|
direction === "decode"
|
|
120
139
|
? Object.fromEntries(
|
|
121
140
|
Object.entries(dict).flatMap(([ts, wire]) =>
|
|
122
|
-
typeof wire === "string"
|
|
123
|
-
? [[wire, ts] as const]
|
|
124
|
-
: wire.map((w) => [w, ts] as const),
|
|
141
|
+
typeof wire === "string" ? [[wire, ts] as const] : wire.map((w) => [w, ts] as const),
|
|
125
142
|
),
|
|
126
143
|
)
|
|
127
144
|
: Object.fromEntries(
|
|
@@ -141,66 +158,129 @@ export const mapKeysByDictionary = (
|
|
|
141
158
|
/**
|
|
142
159
|
* Recursively rename keys between TS names and wire names, per the schema.
|
|
143
160
|
*
|
|
144
|
-
* `fallback` is the nearest ancestor `T.KeyDictionary`
|
|
161
|
+
* `fallback` is the nearest ancestor `T.KeyDictionary` -- schema-known members
|
|
145
162
|
* always map via their own annotations, but opaque values (Document members,
|
|
146
163
|
* keys the schema doesn't know) deep-rename via the dictionary so nested
|
|
147
164
|
* TS-cased content still reaches the wire in wire case. Content with no
|
|
148
165
|
* dictionary in scope passes through verbatim.
|
|
149
166
|
*/
|
|
167
|
+
/**
|
|
168
|
+
* Value form for a `StringEncoded()` member: the string spelling of the
|
|
169
|
+
* value, element-wise for lists. `null` stays `null` -- an API that models a
|
|
170
|
+
* flag as `"true" | "false"` still means "unset" by null, not `"null"`.
|
|
171
|
+
*/
|
|
172
|
+
const stringEncode = (value: unknown): unknown =>
|
|
173
|
+
value === null ? null : Array.isArray(value) ? value.map(stringEncode) : String(value);
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Whether {@link mapKeys} returns every value of `root` unchanged (as a deep
|
|
177
|
+
* copy) in `direction` with no fallback dictionary: no member is renamed,
|
|
178
|
+
* string-encoded (encode) or picked by `T.UnionCases` (decode), and no
|
|
179
|
+
* `T.KeyDictionary` is in scope anywhere below `root`. Protocols use it to
|
|
180
|
+
* skip the walk. Computed once per schema node and direction.
|
|
181
|
+
*/
|
|
182
|
+
export const mapsVerbatim = (root: AST.AST, direction: "encode" | "decode"): boolean => {
|
|
183
|
+
const cache = direction === "encode" ? verbatimEncode : verbatimDecode;
|
|
184
|
+
let result = cache.get(root);
|
|
185
|
+
if (result !== undefined) return result;
|
|
186
|
+
result = true;
|
|
187
|
+
const seen = new Set<AST.AST>();
|
|
188
|
+
const stack: AST.AST[] = [root];
|
|
189
|
+
walk: while (stack.length > 0) {
|
|
190
|
+
const ast = stack.pop()!;
|
|
191
|
+
if (seen.has(ast)) continue;
|
|
192
|
+
seen.add(ast);
|
|
193
|
+
if (getAnn(ast, keyDictionarySymbol) !== undefined) {
|
|
194
|
+
result = false;
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
if (direction === "decode" && getAnn(ast, unionCasesSymbol) !== undefined) {
|
|
198
|
+
result = false;
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
const node = resolveNode(ast);
|
|
202
|
+
if (node._tag === "Union") {
|
|
203
|
+
for (const t of (node as AST.Union).types) stack.push(resolveNode(t));
|
|
204
|
+
} else if (node._tag === "Arrays") {
|
|
205
|
+
const elem = (node as any).rest?.[0] as AST.AST | undefined;
|
|
206
|
+
if (elem) stack.push(elem);
|
|
207
|
+
} else if (node._tag === "Objects") {
|
|
208
|
+
for (const p of (node as any).propertySignatures as readonly AST.PropertySignature[]) {
|
|
209
|
+
if (
|
|
210
|
+
nameOf(p, bodySymbol) !== String(p.name) ||
|
|
211
|
+
(direction === "encode" && hasPropAnn(p, stringEncodedSymbol))
|
|
212
|
+
) {
|
|
213
|
+
result = false;
|
|
214
|
+
break walk;
|
|
215
|
+
}
|
|
216
|
+
stack.push(p.type);
|
|
217
|
+
}
|
|
218
|
+
for (const s of ((node as any).indexSignatures ?? []) as readonly { type: AST.AST }[]) {
|
|
219
|
+
stack.push(s.type);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
cache.set(root, result);
|
|
224
|
+
return result;
|
|
225
|
+
};
|
|
226
|
+
const verbatimEncode = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
|
|
227
|
+
const verbatimDecode = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
|
|
228
|
+
|
|
150
229
|
export const mapKeys = (
|
|
151
230
|
ast: AST.AST,
|
|
152
231
|
value: unknown,
|
|
153
232
|
direction: "encode" | "decode",
|
|
154
233
|
fallback?: KeyDictionaryEntries,
|
|
155
234
|
): unknown => {
|
|
156
|
-
if (
|
|
157
|
-
value === null ||
|
|
158
|
-
value === undefined ||
|
|
159
|
-
typeof value !== "object" ||
|
|
160
|
-
isOpaqueValue(value)
|
|
161
|
-
) {
|
|
235
|
+
if (value === null || value === undefined || typeof value !== "object" || isOpaqueValue(value)) {
|
|
162
236
|
return value;
|
|
163
237
|
}
|
|
164
|
-
const dict =
|
|
165
|
-
(getAnn(ast, keyDictionarySymbol) as KeyDictionaryEntries | undefined) ??
|
|
166
|
-
fallback;
|
|
238
|
+
const dict = (getAnn(ast, keyDictionarySymbol) as KeyDictionaryEntries | undefined) ?? fallback;
|
|
167
239
|
|
|
168
240
|
// Discriminated union whose cases the API returns merged (every case's
|
|
169
241
|
// keys present, `null` for the inactive ones). Map wire names, then keep
|
|
170
|
-
// only the active case's keys.
|
|
171
|
-
//
|
|
172
|
-
//
|
|
173
|
-
//
|
|
174
|
-
//
|
|
242
|
+
// only the active case's keys. The case is read off the union's
|
|
243
|
+
// discriminator when it has one -- cases that share a key set (every
|
|
244
|
+
// resource kind of `resource_tagging`, every page-rule action) are
|
|
245
|
+
// indistinguishable by keys alone. Without one, a case does NOT need every
|
|
246
|
+
// key present -- arms carry optional members the wire may omit -- so the
|
|
247
|
+
// active case is the one that best EXPLAINS the value: most present,
|
|
248
|
+
// non-null keys covered, minus present keys the case cannot explain (ties
|
|
249
|
+
// break by coverage, then declaration order).
|
|
175
250
|
const unionCases = getAnn(ast, unionCasesSymbol) as
|
|
176
|
-
|
|
|
251
|
+
| {
|
|
252
|
+
readonly cases: ReadonlyArray<ReadonlyArray<string>>;
|
|
253
|
+
readonly discriminator?: UnionDiscriminator;
|
|
254
|
+
}
|
|
177
255
|
| undefined;
|
|
178
256
|
if (unionCases && direction === "decode" && !Array.isArray(value)) {
|
|
179
|
-
const obj = (
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
257
|
+
const obj = (dict ? mapKeysByDictionary(dict, value, "decode") : value) as Record<
|
|
258
|
+
string,
|
|
259
|
+
unknown
|
|
260
|
+
>;
|
|
261
|
+
const present = Object.keys(obj).filter((k) => obj[k] !== undefined && obj[k] !== null);
|
|
262
|
+
const disc = unionCases.discriminator;
|
|
263
|
+
const tag = disc ? obj[disc.key] : undefined;
|
|
264
|
+
const tagged = typeof tag === "string" ? disc!.values.indexOf(tag) : -1;
|
|
265
|
+
let best: { keys: ReadonlyArray<string>; score: number; matched: number } | undefined;
|
|
266
|
+
if (tagged >= 0) {
|
|
267
|
+
best = { keys: unionCases.cases[tagged]!, score: 0, matched: 0 };
|
|
268
|
+
} else {
|
|
269
|
+
for (const keys of unionCases.cases) {
|
|
270
|
+
const set = new Set(keys);
|
|
271
|
+
let matched = 0;
|
|
272
|
+
let excess = 0;
|
|
273
|
+
for (const k of present) {
|
|
274
|
+
if (set.has(k)) matched++;
|
|
275
|
+
else excess++;
|
|
276
|
+
}
|
|
277
|
+
const score = matched - excess;
|
|
278
|
+
if (
|
|
279
|
+
matched > 0 &&
|
|
280
|
+
(!best || score > best.score || (score === best.score && matched > best.matched))
|
|
281
|
+
) {
|
|
282
|
+
best = { keys, score, matched };
|
|
283
|
+
}
|
|
204
284
|
}
|
|
205
285
|
}
|
|
206
286
|
if (best) {
|
|
@@ -214,12 +294,12 @@ export const mapKeys = (
|
|
|
214
294
|
const node = resolveNode(ast);
|
|
215
295
|
|
|
216
296
|
// Schema-level union member (a merged response struct whose arms disagree
|
|
217
|
-
// on a member's type
|
|
297
|
+
// on a member's type -- see the codegen's response-union merge): pick the
|
|
218
298
|
// arm that explains the value best and map with it. Object values score
|
|
219
299
|
// arms by how many of their declared keys are present; array values take
|
|
220
300
|
// the first array arm. Anything unmatched deep-renames via the dictionary
|
|
221
|
-
// fallback, like other opaque content. (Single-real-member unions
|
|
222
|
-
// optional/null wrappers
|
|
301
|
+
// fallback, like other opaque content. (Single-real-member unions --
|
|
302
|
+
// optional/null wrappers -- were already collapsed by resolveNode; the
|
|
223
303
|
// opaque `T.UnionCases` mechanism never produces a Union node and is
|
|
224
304
|
// handled above.)
|
|
225
305
|
if (node._tag === "Union") {
|
|
@@ -233,10 +313,8 @@ export const mapKeys = (
|
|
|
233
313
|
for (const t of arms) {
|
|
234
314
|
if (t._tag !== "Objects") continue;
|
|
235
315
|
let score = 0;
|
|
236
|
-
for (const p of (t as any)
|
|
237
|
-
|
|
238
|
-
const from =
|
|
239
|
-
direction === "encode" ? String(p.name) : nameOf(p, bodySymbol);
|
|
316
|
+
for (const p of (t as any).propertySignatures as readonly AST.PropertySignature[]) {
|
|
317
|
+
const from = direction === "encode" ? String(p.name) : nameOf(p, bodySymbol);
|
|
240
318
|
if ((value as Record<string, unknown>)[from] !== undefined) score++;
|
|
241
319
|
}
|
|
242
320
|
if (score > bestScore) {
|
|
@@ -260,13 +338,10 @@ export const mapKeys = (
|
|
|
260
338
|
}
|
|
261
339
|
|
|
262
340
|
if (node._tag === "Objects" && !Array.isArray(value)) {
|
|
263
|
-
const props = (node as any)
|
|
264
|
-
|
|
265
|
-
const isigs = (node as any).indexSignatures as
|
|
266
|
-
| readonly { type: AST.AST }[]
|
|
267
|
-
| undefined;
|
|
341
|
+
const props = (node as any).propertySignatures as readonly AST.PropertySignature[];
|
|
342
|
+
const isigs = (node as any).indexSignatures as readonly { type: AST.AST }[] | undefined;
|
|
268
343
|
if (props.length === 0 && !(isigs && isigs.length)) {
|
|
269
|
-
// opaque object
|
|
344
|
+
// opaque object -- dictionary fallback or verbatim
|
|
270
345
|
return dict ? mapKeysByDictionary(dict, value, direction) : value;
|
|
271
346
|
}
|
|
272
347
|
const out: Record<string, unknown> = {};
|
|
@@ -279,7 +354,13 @@ export const mapKeys = (
|
|
|
279
354
|
consumed.add(from);
|
|
280
355
|
const v = (value as Record<string, unknown>)[from];
|
|
281
356
|
if (v === undefined) continue;
|
|
282
|
-
|
|
357
|
+
// A `StringEncoded()` member nested in a body struct (e.g. Azure's
|
|
358
|
+
// `hardwareProfile.dynamicMemoryEnabled`) stringifies here -- the
|
|
359
|
+
// top-level pass in `buildRequest` only sees the outermost member.
|
|
360
|
+
out[to] =
|
|
361
|
+
direction === "encode" && hasPropAnn(p, stringEncodedSymbol)
|
|
362
|
+
? stringEncode(v)
|
|
363
|
+
: mapKeys(p.type, v, direction, dict);
|
|
283
364
|
}
|
|
284
365
|
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
285
366
|
if (consumed.has(k) || v === undefined) continue;
|
|
@@ -299,7 +380,7 @@ export const mapKeys = (
|
|
|
299
380
|
return out;
|
|
300
381
|
}
|
|
301
382
|
|
|
302
|
-
// Scalar-typed schema node holding object content (spec drift)
|
|
383
|
+
// Scalar-typed schema node holding object content (spec drift) --
|
|
303
384
|
// dictionary fallback or verbatim.
|
|
304
385
|
return dict ? mapKeysByDictionary(dict, value, direction) : value;
|
|
305
386
|
};
|
|
@@ -307,30 +388,22 @@ export const mapKeys = (
|
|
|
307
388
|
|
|
308
389
|
//#region Request building
|
|
309
390
|
|
|
310
|
-
const BODYLESS = new Set(["GET", "HEAD"]);
|
|
391
|
+
const BODYLESS = /*@__PURE__*/ new Set(["GET", "HEAD"]);
|
|
311
392
|
|
|
312
393
|
/**
|
|
313
394
|
* Serialize one query member. Scalars go as `k=v`, arrays as repeated `k=v`
|
|
314
|
-
* pairs, and nested plain objects recurse as DOTTED params
|
|
395
|
+
* pairs, and nested plain objects recurse as DOTTED params -- several list
|
|
315
396
|
* endpoints model their filters as structs (e.g. Cloudflare DNS listRecords
|
|
316
397
|
* takes `name: { exact, contains, ... }`) that must go over the wire as
|
|
317
398
|
* `name.exact=value`. Without this they fell through to `String(value)` and
|
|
318
399
|
* were sent as `name=[object Object]`, which servers happily treat as a
|
|
319
|
-
* filter matching nothing
|
|
400
|
+
* filter matching nothing -- the call "succeeds" with zero results and the
|
|
320
401
|
* bug is invisible to the caller.
|
|
321
402
|
*/
|
|
322
|
-
const appendQuery = (
|
|
323
|
-
query: URLSearchParams,
|
|
324
|
-
name: string,
|
|
325
|
-
value: unknown,
|
|
326
|
-
): void => {
|
|
403
|
+
const appendQuery = (query: URLSearchParams, name: string, value: unknown): void => {
|
|
327
404
|
if (Array.isArray(value)) {
|
|
328
405
|
for (const v of value) appendQuery(query, name, v);
|
|
329
|
-
} else if (
|
|
330
|
-
value !== null &&
|
|
331
|
-
typeof value === "object" &&
|
|
332
|
-
!(value instanceof Date)
|
|
333
|
-
) {
|
|
406
|
+
} else if (value !== null && typeof value === "object" && !(value instanceof Date)) {
|
|
334
407
|
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
335
408
|
if (v !== undefined) appendQuery(query, `${name}.${k}`, v);
|
|
336
409
|
}
|
|
@@ -352,34 +425,34 @@ export interface BuildRequestOptions {
|
|
|
352
425
|
*/
|
|
353
426
|
readonly mapMemberHeader?: (name: string, value: string) => string;
|
|
354
427
|
/**
|
|
355
|
-
* Wire name for input keys the schema doesn't declare (spec drift
|
|
428
|
+
* Wire name for input keys the schema doesn't declare (spec drift --
|
|
356
429
|
* unknown keys pass through as body fields rather than being dropped).
|
|
357
430
|
* Defaults to the key verbatim.
|
|
358
431
|
*/
|
|
359
432
|
readonly unknownKeyToWire?: (key: string) => string;
|
|
433
|
+
/**
|
|
434
|
+
* Send `{}` on a method that takes a body even when the input declares no
|
|
435
|
+
* body members. Connect unary RPCs (E2B's envd) POST JSON for every call,
|
|
436
|
+
* and refuse a bodyless one with 415.
|
|
437
|
+
*/
|
|
438
|
+
readonly emptyJsonBody?: boolean;
|
|
360
439
|
}
|
|
361
440
|
|
|
362
441
|
/**
|
|
363
|
-
*
|
|
364
|
-
*
|
|
365
|
-
*
|
|
366
|
-
*
|
|
367
|
-
* query params, `HttpBody()` sends the member as the whole body,
|
|
368
|
-
* `FormDataFile()` members become multipart file parts, and everything else
|
|
369
|
-
* is a JSON body field (wire-named via `Body()` / `KeyDictionary`).
|
|
370
|
-
*
|
|
371
|
-
* Throws when the input schema is missing the `Http()` trait — a codegen
|
|
372
|
-
* bug, surfaced as a defect by the calling protocol's Effect context.
|
|
442
|
+
* Encode a greedy `{name+}` label: the value may span several path
|
|
443
|
+
* segments (e.g. an Azure scope `/subscriptions/{id}/resourceGroups/{rg}`),
|
|
444
|
+
* so each segment is encoded on its own and the `/` separators are kept.
|
|
445
|
+
* Leading slashes are dropped because the URI template already supplies one.
|
|
373
446
|
*/
|
|
447
|
+
export const encodeGreedyLabel = (value: string): string =>
|
|
448
|
+
value.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
|
|
449
|
+
|
|
374
450
|
/**
|
|
375
451
|
* Flatten a nested object into Stripe-style bracket notation pairs for
|
|
376
452
|
* form-urlencoded bodies: nested objects become `a[b][c]`, arrays index as
|
|
377
453
|
* `a[0]`; null/undefined dropped, booleans as "true"/"false".
|
|
378
454
|
*/
|
|
379
|
-
const flattenToFormPairs = (
|
|
380
|
-
obj: Record<string, unknown>,
|
|
381
|
-
prefix = "",
|
|
382
|
-
): Array<[string, string]> => {
|
|
455
|
+
const flattenToFormPairs = (obj: Record<string, unknown>, prefix = ""): Array<[string, string]> => {
|
|
383
456
|
const pairs: Array<[string, string]> = [];
|
|
384
457
|
for (const [key, value] of Object.entries(obj)) {
|
|
385
458
|
if (value === undefined || value === null) continue;
|
|
@@ -389,20 +462,13 @@ const flattenToFormPairs = (
|
|
|
389
462
|
const item = value[i];
|
|
390
463
|
if (item === undefined || item === null) continue;
|
|
391
464
|
if (typeof item === "object" && !Array.isArray(item)) {
|
|
392
|
-
pairs.push(
|
|
393
|
-
...flattenToFormPairs(
|
|
394
|
-
item as Record<string, unknown>,
|
|
395
|
-
`${fullKey}[${i}]`,
|
|
396
|
-
),
|
|
397
|
-
);
|
|
465
|
+
pairs.push(...flattenToFormPairs(item as Record<string, unknown>, `${fullKey}[${i}]`));
|
|
398
466
|
} else {
|
|
399
467
|
pairs.push([`${fullKey}[${i}]`, String(item)]);
|
|
400
468
|
}
|
|
401
469
|
}
|
|
402
470
|
} else if (typeof value === "object") {
|
|
403
|
-
pairs.push(
|
|
404
|
-
...flattenToFormPairs(value as Record<string, unknown>, fullKey),
|
|
405
|
-
);
|
|
471
|
+
pairs.push(...flattenToFormPairs(value as Record<string, unknown>, fullKey));
|
|
406
472
|
} else {
|
|
407
473
|
pairs.push([fullKey, String(value)]);
|
|
408
474
|
}
|
|
@@ -410,138 +476,315 @@ const flattenToFormPairs = (
|
|
|
410
476
|
return pairs;
|
|
411
477
|
};
|
|
412
478
|
|
|
413
|
-
|
|
479
|
+
/** How an input member binds to the request. */
|
|
480
|
+
type Bind = "label" | "header" | "query" | "deepQuery" | "file" | "httpBody" | "body";
|
|
481
|
+
|
|
482
|
+
/** One input member, with its binding read from the schema once. */
|
|
483
|
+
interface MemberPlan {
|
|
484
|
+
readonly key: string;
|
|
485
|
+
readonly bind: Bind;
|
|
486
|
+
/** Label token, lower-cased header name, query name or body wire name. */
|
|
487
|
+
readonly name: string;
|
|
488
|
+
readonly type: AST.AST;
|
|
489
|
+
/** `LabelEncoding` characters kept unescaped. */
|
|
490
|
+
readonly preserve: string | undefined;
|
|
491
|
+
/** `{name+}` placeholder. */
|
|
492
|
+
readonly greedy: boolean;
|
|
493
|
+
readonly stringEncoded: boolean;
|
|
494
|
+
/** A list query member sent as one comma-separated parameter. */
|
|
495
|
+
readonly commaDelimited: boolean;
|
|
496
|
+
/** `mapKeys(type, value, "encode", rootDict)` returns the value unchanged. */
|
|
497
|
+
readonly verbatim: boolean;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** What `buildRequest` reads from an input schema, computed once per schema. */
|
|
501
|
+
interface RequestPlan {
|
|
502
|
+
readonly http: HttpTrait;
|
|
503
|
+
readonly rootDict: KeyDictionaryEntries | undefined;
|
|
504
|
+
readonly members: ReadonlyArray<MemberPlan>;
|
|
505
|
+
readonly known: ReadonlySet<string>;
|
|
506
|
+
/** The schema declares a member that is sent in the body. */
|
|
507
|
+
readonly hasBodyMembers: boolean;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const plans = /*@__PURE__*/ new WeakMap<AST.AST, RequestPlan>();
|
|
511
|
+
|
|
512
|
+
const planFor = (inputAst: AST.AST): RequestPlan | SdkError => {
|
|
513
|
+
let plan = plans.get(inputAst);
|
|
514
|
+
if (plan !== undefined) return plan;
|
|
515
|
+
const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
|
|
516
|
+
if (!http) {
|
|
517
|
+
return new SdkError({ message: "operation input is missing the Http() trait" });
|
|
518
|
+
}
|
|
519
|
+
const rootDict = getAnn(inputAst, keyDictionarySymbol) as KeyDictionaryEntries | undefined;
|
|
520
|
+
const members: MemberPlan[] = [];
|
|
521
|
+
const known = new Set<string>();
|
|
522
|
+
let hasBodyMembers = false;
|
|
523
|
+
for (const prop of getProps(inputAst)) {
|
|
524
|
+
const key = String(prop.name);
|
|
525
|
+
known.add(key);
|
|
526
|
+
let bind: Bind;
|
|
527
|
+
let name: string;
|
|
528
|
+
let greedy = false;
|
|
529
|
+
if (hasPropAnn(prop, labelSymbol)) {
|
|
530
|
+
bind = "label";
|
|
531
|
+
name = nameOf(prop, labelSymbol);
|
|
532
|
+
greedy = http.uri.includes(`{${name}+}`);
|
|
533
|
+
} else if (hasPropAnn(prop, headerSymbol)) {
|
|
534
|
+
bind = "header";
|
|
535
|
+
name = nameOf(prop, headerSymbol).toLowerCase();
|
|
536
|
+
} else if (hasPropAnn(prop, querySymbol)) {
|
|
537
|
+
bind = "query";
|
|
538
|
+
name = nameOf(prop, querySymbol);
|
|
539
|
+
} else if (hasPropAnn(prop, deepQuerySymbol)) {
|
|
540
|
+
bind = "deepQuery";
|
|
541
|
+
name = nameOf(prop, deepQuerySymbol);
|
|
542
|
+
} else {
|
|
543
|
+
hasBodyMembers = true;
|
|
544
|
+
bind = hasPropAnn(prop, formDataFileSymbol)
|
|
545
|
+
? "file"
|
|
546
|
+
: hasPropAnn(prop, httpBodySymbol)
|
|
547
|
+
? "httpBody"
|
|
548
|
+
: "body";
|
|
549
|
+
name = nameOf(prop, bodySymbol);
|
|
550
|
+
}
|
|
551
|
+
const preserve = getPropAnn(prop, labelEncodingSymbol);
|
|
552
|
+
members.push({
|
|
553
|
+
key,
|
|
554
|
+
bind,
|
|
555
|
+
name,
|
|
556
|
+
type: prop.type,
|
|
557
|
+
preserve: typeof preserve === "string" ? preserve : undefined,
|
|
558
|
+
greedy,
|
|
559
|
+
stringEncoded: hasPropAnn(prop, stringEncodedSymbol),
|
|
560
|
+
commaDelimited: hasPropAnn(prop, commaDelimitedSymbol),
|
|
561
|
+
verbatim: rootDict === undefined && mapsVerbatim(prop.type, "encode"),
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
plan = { http, rootDict, members, known, hasBodyMembers };
|
|
565
|
+
plans.set(inputAst, plan);
|
|
566
|
+
return plan;
|
|
567
|
+
};
|
|
568
|
+
|
|
569
|
+
const emptyRequest = /*@__PURE__*/ HttpClientRequest.get("");
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* `HttpClientRequest.make(method)(url)` with `headers` set, in one object:
|
|
573
|
+
* the same request as `make(...).pipe(setHeaders(headers))` without the
|
|
574
|
+
* intermediate copies. `url` may carry a query string.
|
|
575
|
+
*/
|
|
576
|
+
export const makeRequest = (
|
|
577
|
+
method: HttpTrait["method"],
|
|
578
|
+
url: string,
|
|
579
|
+
headers: Record<string, string>,
|
|
580
|
+
): HttpClientRequest.HttpClientRequest =>
|
|
581
|
+
HttpClientRequest.makeWith(
|
|
582
|
+
method,
|
|
583
|
+
url,
|
|
584
|
+
emptyRequest.urlParams,
|
|
585
|
+
emptyRequest.hash,
|
|
586
|
+
Headers.fromInput(headers),
|
|
587
|
+
HttpBody.empty,
|
|
588
|
+
);
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* The input cannot be sent: a path label whose value would address another
|
|
592
|
+
* resource (`.` or `..`, which the URL parser resolves to the parent path).
|
|
593
|
+
* Raised before anything is sent.
|
|
594
|
+
*/
|
|
595
|
+
export class InvalidInput
|
|
596
|
+
extends /*@__PURE__*/ Schema.TaggedError<InvalidInput>()("InvalidInput", {
|
|
597
|
+
member: Schema.String,
|
|
598
|
+
message: Schema.String,
|
|
599
|
+
}).pipe(Category.withBadRequestError) {}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* The refusal for a path label value that would address another resource,
|
|
603
|
+
* or `undefined`. The URL parser resolves a `.` or `..` segment,
|
|
604
|
+
* percent-encoded or not, so no encoding can carry one
|
|
605
|
+
* (`/projects/p1/branches/..` -> `/projects/p1/`). A greedy label keeps its
|
|
606
|
+
* `/`, so each of its segments counts.
|
|
607
|
+
*/
|
|
608
|
+
export const invalidLabel = (
|
|
609
|
+
member: string,
|
|
610
|
+
value: unknown,
|
|
611
|
+
greedy?: boolean,
|
|
612
|
+
): InvalidInput | undefined => {
|
|
613
|
+
const text = String(value);
|
|
614
|
+
return (greedy ? text.split("/") : [text]).some((s) => s === "." || s === "..")
|
|
615
|
+
? new InvalidInput({
|
|
616
|
+
member,
|
|
617
|
+
message: `Input member ${member} cannot be ${JSON.stringify(text)}: as a path label it would address another resource`,
|
|
618
|
+
})
|
|
619
|
+
: undefined;
|
|
620
|
+
};
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* Build an HTTP request from an operation input and its schema, driven by
|
|
624
|
+
* the trait annotations: `Http()` supplies method + URI template, `Label()`
|
|
625
|
+
* members fill URI placeholders, `Header()`/`Query()` members bind to
|
|
626
|
+
* headers/query params, `DeepQuery()` struct members expand into dotted
|
|
627
|
+
* query params, `HttpBody()` sends the member as the whole body,
|
|
628
|
+
* `FormDataFile()` members become multipart file parts, and everything else
|
|
629
|
+
* is a JSON body field (wire-named via `Body()` / `KeyDictionary`).
|
|
630
|
+
*
|
|
631
|
+
* The schema is read once per input schema (see `planFor`); later calls only
|
|
632
|
+
* walk the input value.
|
|
633
|
+
*
|
|
634
|
+
* Fails with {@link InvalidInput}, before anything is sent, when a label is
|
|
635
|
+
* `.` or `..` (for a greedy `{name+}` label, when any of its segments is).
|
|
636
|
+
* Fails with {@link SdkError} when the input schema is missing the `Http()`
|
|
637
|
+
* trait (a codegen bug the generator refuses).
|
|
638
|
+
*/
|
|
639
|
+
export const buildRequest = (
|
|
640
|
+
options: BuildRequestOptions,
|
|
641
|
+
): Effect.Effect<HttpClientRequest.HttpClientRequest, InvalidInput | SdkError> => {
|
|
642
|
+
const request = requestOrInvalid(options);
|
|
643
|
+
return request instanceof InvalidInput || request instanceof SdkError
|
|
644
|
+
? Effect.fail(request)
|
|
645
|
+
: Effect.succeed(request);
|
|
646
|
+
};
|
|
647
|
+
|
|
648
|
+
const requestOrInvalid = ({
|
|
414
649
|
input,
|
|
415
650
|
inputAst,
|
|
416
651
|
baseUrl,
|
|
417
652
|
headers: baseHeaders,
|
|
418
653
|
mapMemberHeader,
|
|
419
654
|
unknownKeyToWire,
|
|
420
|
-
|
|
655
|
+
emptyJsonBody,
|
|
656
|
+
}: BuildRequestOptions): HttpClientRequest.HttpClientRequest | InvalidInput | SdkError => {
|
|
421
657
|
const inputObj = (input ?? {}) as Record<string, unknown>;
|
|
422
|
-
const
|
|
423
|
-
if (
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
// Root key dictionary: fallback wire mapping for opaque/unknown content
|
|
427
|
-
// the schema doesn't model.
|
|
428
|
-
const rootDict = getAnn(inputAst, keyDictionarySymbol) as
|
|
429
|
-
| KeyDictionaryEntries
|
|
430
|
-
| undefined;
|
|
658
|
+
const plan = planFor(inputAst);
|
|
659
|
+
if (plan instanceof SdkError) return plan;
|
|
660
|
+
const { http, rootDict, members, known } = plan;
|
|
661
|
+
let hasBodyMembers = plan.hasBodyMembers;
|
|
431
662
|
|
|
432
663
|
const headers: Record<string, string> = { ...baseHeaders };
|
|
433
664
|
const body: Record<string, unknown> = {};
|
|
434
|
-
let
|
|
435
|
-
|
|
436
|
-
|
|
665
|
+
let bodyKeys = 0;
|
|
666
|
+
let rawBody: unknown; // whole-body member (T.HttpBody) -- sent as-is
|
|
667
|
+
let files: Array<Blob | File> | undefined;
|
|
668
|
+
let query: URLSearchParams | undefined;
|
|
437
669
|
let uri = http.uri;
|
|
438
|
-
|
|
439
|
-
|
|
670
|
+
// Value of a modeled `Content-Type` header member, e.g. R2 putObject's
|
|
671
|
+
// `contentType`. A raw body is sent under it (see below).
|
|
672
|
+
let memberContentType: string | undefined;
|
|
440
673
|
|
|
441
|
-
for (
|
|
442
|
-
const
|
|
443
|
-
|
|
444
|
-
const value = inputObj[key];
|
|
445
|
-
const isBodyMember =
|
|
446
|
-
!hasPropAnn(prop, labelSymbol) &&
|
|
447
|
-
!hasPropAnn(prop, headerSymbol) &&
|
|
448
|
-
!hasPropAnn(prop, querySymbol) &&
|
|
449
|
-
!hasPropAnn(prop, deepQuerySymbol);
|
|
450
|
-
if (isBodyMember) hasBodyMembers = true;
|
|
674
|
+
for (let i = 0; i < members.length; i++) {
|
|
675
|
+
const m = members[i]!;
|
|
676
|
+
const value = inputObj[m.key];
|
|
451
677
|
if (value === undefined) continue;
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
)
|
|
473
|
-
|
|
474
|
-
|
|
678
|
+
switch (m.bind) {
|
|
679
|
+
case "label": {
|
|
680
|
+
const invalid = invalidLabel(m.key, value, m.greedy);
|
|
681
|
+
if (invalid) return invalid;
|
|
682
|
+
const encoded = encodeURIComponent(String(value));
|
|
683
|
+
const preserve = m.preserve;
|
|
684
|
+
const label =
|
|
685
|
+
preserve !== undefined
|
|
686
|
+
? encoded.replace(/%[0-9A-F]{2}/g, (escape) => {
|
|
687
|
+
const character = String.fromCharCode(Number.parseInt(escape.slice(1), 16));
|
|
688
|
+
return preserve.includes(character) ? character : escape;
|
|
689
|
+
})
|
|
690
|
+
: encoded;
|
|
691
|
+
uri = m.greedy
|
|
692
|
+
? uri.replace(`{${m.name}+}`, () => encodeGreedyLabel(String(value)))
|
|
693
|
+
: uri.replace(`{${m.name}}`, () => label);
|
|
694
|
+
break;
|
|
695
|
+
}
|
|
696
|
+
case "header": {
|
|
697
|
+
const hVal = String(value);
|
|
698
|
+
headers[m.name] = mapMemberHeader ? mapMemberHeader(m.name, hVal) : hVal;
|
|
699
|
+
if (m.name === "content-type") memberContentType = headers[m.name];
|
|
700
|
+
break;
|
|
701
|
+
}
|
|
702
|
+
case "query":
|
|
703
|
+
if (m.commaDelimited && Array.isArray(value)) {
|
|
704
|
+
(query ??= new URLSearchParams()).append(m.name, value.map(String).join(","));
|
|
705
|
+
} else {
|
|
706
|
+
appendQuery((query ??= new URLSearchParams()), m.name, value);
|
|
707
|
+
}
|
|
708
|
+
break;
|
|
709
|
+
case "deepQuery": {
|
|
710
|
+
// Deep-object query member (T.DeepQuery): a nested struct expands into
|
|
711
|
+
// dotted query keys (`account.id=...`) under the member's wire name.
|
|
712
|
+
// Wire-name the nested content via the schema first, skip null/
|
|
713
|
+
// undefined entries; deeper nesting recurses through appendQuery.
|
|
714
|
+
const mapped = m.verbatim ? value : mapKeys(m.type, value, "encode", rootDict);
|
|
715
|
+
if (mapped !== null && typeof mapped === "object") {
|
|
716
|
+
for (const [k, v] of Object.entries(mapped as Record<string, unknown>)) {
|
|
717
|
+
if (v !== undefined && v !== null) {
|
|
718
|
+
appendQuery((query ??= new URLSearchParams()), `${m.name}.${k}`, v);
|
|
719
|
+
}
|
|
475
720
|
}
|
|
476
721
|
}
|
|
722
|
+
break;
|
|
477
723
|
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
724
|
+
case "file":
|
|
725
|
+
files ??= [];
|
|
726
|
+
for (const f of Array.isArray(value) ? value : [value]) {
|
|
727
|
+
files.push(f as Blob | File);
|
|
728
|
+
}
|
|
729
|
+
break;
|
|
730
|
+
case "httpBody":
|
|
731
|
+
rawBody = m.verbatim ? value : mapKeys(m.type, value, "encode", rootDict);
|
|
732
|
+
break;
|
|
733
|
+
default:
|
|
734
|
+
// T.StringEncoded(): the API takes this member's value only as its
|
|
735
|
+
// string spelling (`true` -> `"true"`), while the TS surface keeps the
|
|
736
|
+
// natural type. Explicit here so a JSON body carries the string too,
|
|
737
|
+
// rather than relying on the multipart encoder's own `String()`.
|
|
738
|
+
body[m.name] = m.stringEncoded
|
|
739
|
+
? stringEncode(value)
|
|
740
|
+
: m.verbatim
|
|
741
|
+
? value
|
|
742
|
+
: mapKeys(m.type, value, "encode", rootDict);
|
|
743
|
+
bodyKeys++;
|
|
491
744
|
}
|
|
492
745
|
}
|
|
493
746
|
|
|
494
|
-
// Input keys the schema doesn't know pass through as body fields
|
|
747
|
+
// Input keys the schema doesn't know pass through as body fields -- the
|
|
495
748
|
// generated schemas can lag the real API, and silently dropping them
|
|
496
749
|
// would break working callers. The key dictionary maps them when it knows
|
|
497
750
|
// the key, otherwise `unknownKeyToWire` decides the wire name.
|
|
498
|
-
for (const
|
|
499
|
-
if (
|
|
500
|
-
const
|
|
501
|
-
|
|
751
|
+
for (const key in inputObj) {
|
|
752
|
+
if (known.has(key) || !Object.hasOwn(inputObj, key)) continue;
|
|
753
|
+
const value = inputObj[key];
|
|
754
|
+
if (value === undefined) continue;
|
|
755
|
+
const wire = rootDict?.[key] ?? (unknownKeyToWire ? unknownKeyToWire(key) : key);
|
|
502
756
|
body[typeof wire === "string" ? wire : wire[0]] = rootDict
|
|
503
757
|
? mapKeysByDictionary(rootDict, value, "encode")
|
|
504
758
|
: value;
|
|
759
|
+
bodyKeys++;
|
|
505
760
|
hasBodyMembers = true;
|
|
506
761
|
}
|
|
507
762
|
|
|
508
|
-
const qs = query.toString();
|
|
509
|
-
const url = `${baseUrl}${uri}
|
|
510
|
-
if (process.env.DISTILLED_DEBUG_HTTP) {
|
|
511
|
-
console.error(
|
|
512
|
-
`[distilled] ${http.method} ${url}` +
|
|
513
|
-
(Object.keys(body).length
|
|
514
|
-
? ` body=${JSON.stringify(body).slice(0, 400)}`
|
|
515
|
-
: ""),
|
|
516
|
-
);
|
|
517
|
-
}
|
|
763
|
+
const qs = query === undefined ? "" : query.toString();
|
|
764
|
+
const url = qs ? `${baseUrl}${uri}?${qs}` : `${baseUrl}${uri}`;
|
|
518
765
|
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
);
|
|
766
|
+
const request = makeRequest(http.method, url, headers);
|
|
767
|
+
const bodied = !BODYLESS.has(http.method);
|
|
522
768
|
if (http.contentType === "multipart") {
|
|
523
769
|
// Multipart upload: each body member is a form part (objects
|
|
524
770
|
// JSON-encoded under their wire name), each file appends under its own
|
|
525
771
|
// filename. A whole-body member (T.HttpBody) that is a record of files
|
|
526
772
|
// becomes one part per entry (e.g. asset upload: { <hash>: File }).
|
|
527
|
-
//
|
|
528
|
-
// appended, object → JSON string, primitive → string.
|
|
773
|
+
// Files and byte buffers become binary parts; objects become JSON parts.
|
|
529
774
|
const form = new FormData();
|
|
530
775
|
const parts =
|
|
531
776
|
rawBody !== undefined && typeof rawBody === "object"
|
|
532
777
|
? (rawBody as Record<string, unknown>)
|
|
533
778
|
: body;
|
|
534
|
-
const isFileOrBlob = (v: unknown): v is Blob =>
|
|
535
|
-
v instanceof Blob || v instanceof File;
|
|
779
|
+
const isFileOrBlob = (v: unknown): v is Blob => v instanceof Blob || v instanceof File;
|
|
536
780
|
for (const [key, value] of Object.entries(parts)) {
|
|
537
781
|
if (value === undefined || value === null) continue;
|
|
538
782
|
if (isFileOrBlob(value)) {
|
|
539
783
|
form.append(key, value, value instanceof File ? value.name : key);
|
|
540
|
-
} else if (
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
) {
|
|
784
|
+
} else if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
|
|
785
|
+
const bytes = value instanceof Uint8Array ? new Uint8Array(value).buffer : value;
|
|
786
|
+
form.append(key, new Blob([bytes]), key);
|
|
787
|
+
} else if (Array.isArray(value) && value.length > 0 && isFileOrBlob(value[0])) {
|
|
545
788
|
for (const file of value as Blob[]) {
|
|
546
789
|
if (isFileOrBlob(file)) {
|
|
547
790
|
form.append(
|
|
@@ -557,72 +800,72 @@ export const buildRequest = ({
|
|
|
557
800
|
form.append(key, String(value));
|
|
558
801
|
}
|
|
559
802
|
}
|
|
560
|
-
for (const f of files) {
|
|
803
|
+
for (const f of files ?? []) {
|
|
561
804
|
const filename = (f as File).name ?? "file";
|
|
562
805
|
form.append(filename, f, filename);
|
|
563
806
|
}
|
|
564
|
-
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
!BODYLESS.has(http.method)
|
|
568
|
-
) {
|
|
807
|
+
return HttpClientRequest.setBody(request, HttpBody.formData(form));
|
|
808
|
+
}
|
|
809
|
+
if (http.contentType === "form-urlencoded" && bodied) {
|
|
569
810
|
// application/x-www-form-urlencoded with Stripe-style deepObject bracket
|
|
570
|
-
// notation: { shipping: { address: { city } } }
|
|
571
|
-
// arrays indexed ({ expand: ["a"] }
|
|
811
|
+
// notation: { shipping: { address: { city } } } -> shipping[address][city],
|
|
812
|
+
// arrays indexed ({ expand: ["a"] } -> expand[0]=a).
|
|
572
813
|
const source =
|
|
573
814
|
rawBody !== undefined && typeof rawBody === "object"
|
|
574
815
|
? (rawBody as Record<string, unknown>)
|
|
575
816
|
: body;
|
|
576
817
|
const params = new URLSearchParams();
|
|
577
818
|
for (const [k, v] of flattenToFormPairs(source)) params.append(k, v);
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
),
|
|
819
|
+
return HttpClientRequest.setBody(
|
|
820
|
+
request,
|
|
821
|
+
HttpBody.text(params.toString(), "application/x-www-form-urlencoded"),
|
|
582
822
|
);
|
|
583
|
-
}
|
|
584
|
-
|
|
823
|
+
}
|
|
824
|
+
if (rawBody !== undefined && bodied) {
|
|
825
|
+
// Whole-body member (raw arrays/scalars) -- sent as the body itself.
|
|
585
826
|
// Binary payloads (Blob / ArrayBuffer / Uint8Array) send verbatim
|
|
586
|
-
// (raw object uploads
|
|
587
|
-
//
|
|
588
|
-
//
|
|
589
|
-
//
|
|
590
|
-
//
|
|
827
|
+
// (raw object uploads). With a bodyMediaType, the member is a
|
|
828
|
+
// preserialized payload (string / bytes) sent verbatim; otherwise it's
|
|
829
|
+
// JSON.
|
|
830
|
+
//
|
|
831
|
+
// `setBody` overwrites the Content-Type header with the body's media
|
|
832
|
+
// type (and removes it when that is undefined), so the body carries the
|
|
833
|
+
// modeled Content-Type member when the caller set one, else the declared
|
|
834
|
+
// bodyMediaType (e.g. application/x-ndjson for Vectorize insert/upsert).
|
|
835
|
+
const mediaType = memberContentType ?? http.bodyMediaType;
|
|
591
836
|
if (rawBody instanceof Blob || rawBody instanceof ArrayBuffer) {
|
|
592
|
-
//
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
request
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
HttpBody.uint8Array(rawBody, http.bodyMediaType),
|
|
605
|
-
),
|
|
606
|
-
);
|
|
607
|
-
} else if (http.bodyMediaType) {
|
|
608
|
-
request = request.pipe(
|
|
609
|
-
HttpClientRequest.setBody(
|
|
610
|
-
typeof rawBody === "string"
|
|
611
|
-
? HttpBody.text(rawBody, http.bodyMediaType)
|
|
612
|
-
: HttpBody.uint8Array(rawBody as Uint8Array, http.bodyMediaType),
|
|
613
|
-
),
|
|
837
|
+
// With no media type at all, fetch falls back to the Blob's own type.
|
|
838
|
+
return HttpClientRequest.setBody(request, HttpBody.raw(rawBody, { contentType: mediaType }));
|
|
839
|
+
}
|
|
840
|
+
if (rawBody instanceof Uint8Array) {
|
|
841
|
+
return HttpClientRequest.setBody(request, HttpBody.uint8Array(rawBody, mediaType));
|
|
842
|
+
}
|
|
843
|
+
if (http.bodyMediaType) {
|
|
844
|
+
return HttpClientRequest.setBody(
|
|
845
|
+
request,
|
|
846
|
+
typeof rawBody === "string"
|
|
847
|
+
? HttpBody.text(rawBody, mediaType)
|
|
848
|
+
: HttpBody.uint8Array(rawBody as Uint8Array, mediaType),
|
|
614
849
|
);
|
|
615
|
-
} else {
|
|
616
|
-
request = request.pipe(HttpClientRequest.bodyJsonUnsafe(rawBody));
|
|
617
850
|
}
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
851
|
+
return HttpClientRequest.setBody(request, HttpBody.jsonUnsafe(rawBody));
|
|
852
|
+
}
|
|
853
|
+
if (
|
|
854
|
+
// A GET/HEAD sends a body only when body members actually carry values.
|
|
855
|
+
// Some APIs really do document GET-with-body: MongoDB Atlas's
|
|
856
|
+
// `.../lineItems:search` declares a `requestBody` on `get`, and AWS EFS's
|
|
857
|
+
// DescribeAccountPreferences takes `{ MaxResults, NextToken }` on a GET.
|
|
858
|
+
// Suppressing it outright dropped those members silently -- the request
|
|
859
|
+
// succeeded, unfiltered, with nothing on the wire to show why.
|
|
860
|
+
//
|
|
861
|
+
// The `{}`-when-empty rule below stays limited to methods that expect a
|
|
862
|
+
// body, so a bodyless method with nothing set still sends nothing.
|
|
863
|
+
bodyKeys > 0 ||
|
|
864
|
+
((hasBodyMembers || emptyJsonBody === true) && bodied && http.method !== "DELETE")
|
|
622
865
|
) {
|
|
623
|
-
// Send `{}` rather than no body when the schema declares body members
|
|
866
|
+
// Send `{}` rather than no body when the schema declares body members --
|
|
624
867
|
// some endpoints reject a missing JSON body outright.
|
|
625
|
-
|
|
868
|
+
return HttpClientRequest.setBody(request, HttpBody.jsonUnsafe(body));
|
|
626
869
|
}
|
|
627
870
|
return request;
|
|
628
871
|
};
|
|
@@ -630,59 +873,109 @@ export const buildRequest = ({
|
|
|
630
873
|
|
|
631
874
|
//#region Typed error matching
|
|
632
875
|
|
|
633
|
-
/**
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
876
|
+
/** Parsed response metadata supplied by a protocol after it detects a failure. */
|
|
877
|
+
export interface ErrorResponse {
|
|
878
|
+
readonly body?: unknown;
|
|
879
|
+
readonly headers?: Readonly<Record<string, string | undefined>>;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
const matchesText = (matcher: ErrorTextMatcher, value: unknown): boolean => {
|
|
883
|
+
if (typeof value !== "string") return false;
|
|
884
|
+
if (typeof matcher === "string") return matcher === value;
|
|
885
|
+
const { includes, matches } = matcher;
|
|
886
|
+
return (
|
|
887
|
+
(includes !== undefined || matches !== undefined) &&
|
|
888
|
+
(includes === undefined || value.includes(includes)) &&
|
|
889
|
+
(matches === undefined || new RegExp(matches).test(value))
|
|
890
|
+
);
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
// Own properties only: inherited properties are not JSON response members.
|
|
894
|
+
const atPointer = (body: unknown, pointer: string): unknown => {
|
|
895
|
+
if (pointer === "") return body;
|
|
896
|
+
if (!pointer.startsWith("/") || /~(?![01])/u.test(pointer)) return undefined;
|
|
897
|
+
let value = body;
|
|
898
|
+
for (const segment of pointer.slice(1).split("/")) {
|
|
899
|
+
const key = segment.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
900
|
+
if (
|
|
901
|
+
value === null ||
|
|
902
|
+
typeof value !== "object" ||
|
|
903
|
+
!Object.hasOwn(value, key) ||
|
|
904
|
+
(Array.isArray(value) && !/^(0|[1-9][0-9]*)$/.test(key))
|
|
905
|
+
)
|
|
906
|
+
return undefined;
|
|
907
|
+
value = (value as Record<string, unknown>)[key];
|
|
908
|
+
}
|
|
909
|
+
return value;
|
|
910
|
+
};
|
|
911
|
+
|
|
912
|
+
const matcherSpecificity = (m: ErrorMatcher): number =>
|
|
913
|
+
(m.code !== undefined ? 1 : 0) +
|
|
914
|
+
(m.status !== undefined ? 1 : 0) +
|
|
915
|
+
(m.message !== undefined ? 1 : 0) +
|
|
916
|
+
(m.body === undefined ? 0 : Object.keys(m.body).length) +
|
|
917
|
+
(m.headers === undefined ? 0 : Object.keys(m.headers).length);
|
|
918
|
+
|
|
919
|
+
/** Every supplied constraint must match; an unconstrained matcher matches nothing. */
|
|
638
920
|
export const matchesExpression = (
|
|
639
921
|
m: ErrorMatcher,
|
|
640
922
|
code: number | undefined,
|
|
641
923
|
status: number,
|
|
642
924
|
message: string,
|
|
925
|
+
response: ErrorResponse = {},
|
|
643
926
|
): boolean => {
|
|
644
|
-
if (
|
|
927
|
+
if (
|
|
928
|
+
m.code === undefined &&
|
|
929
|
+
m.status === undefined &&
|
|
930
|
+
m.message === undefined &&
|
|
931
|
+
matcherSpecificity(m) === 0
|
|
932
|
+
)
|
|
645
933
|
return false;
|
|
646
934
|
if (m.code !== undefined && m.code !== code) return false;
|
|
647
935
|
if (m.status !== undefined && m.status !== status) return false;
|
|
648
|
-
if (m.message !== undefined)
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
if (
|
|
655
|
-
|
|
656
|
-
|
|
936
|
+
if (m.message !== undefined && !matchesText(m.message, message)) return false;
|
|
937
|
+
if (m.body !== undefined) {
|
|
938
|
+
for (const [pointer, expected] of Object.entries(m.body)) {
|
|
939
|
+
const actual = atPointer(response.body, pointer);
|
|
940
|
+
if (typeof expected === "string" || (expected !== null && typeof expected === "object")) {
|
|
941
|
+
if (!matchesText(expected, actual)) return false;
|
|
942
|
+
} else if (actual !== expected) return false;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
if (m.headers !== undefined) {
|
|
946
|
+
for (const [name, expected] of Object.entries(m.headers)) {
|
|
947
|
+
if (response.headers === undefined) return false;
|
|
948
|
+
const actual = Object.entries(response.headers).find(
|
|
949
|
+
([key]) => key.toLowerCase() === name.toLowerCase(),
|
|
950
|
+
)?.[1];
|
|
951
|
+
if (!matchesText(expected, actual)) return false;
|
|
657
952
|
}
|
|
658
953
|
}
|
|
659
954
|
return true;
|
|
660
955
|
};
|
|
661
956
|
|
|
662
|
-
const matcherSpecificity = (m: ErrorMatcher): number =>
|
|
663
|
-
(m.code !== undefined ? 1 : 0) +
|
|
664
|
-
(m.status !== undefined ? 1 : 0) +
|
|
665
|
-
(m.message !== undefined ? 1 : 0);
|
|
666
|
-
|
|
667
957
|
/**
|
|
668
958
|
* Pick the operation's typed error class for a failed response: among all
|
|
669
959
|
* declared classes whose matchers (see `applyErrorMatchers`) match the wire
|
|
670
960
|
* failure, the most specific matcher wins (ties break by declaration order).
|
|
961
|
+
* Empty error lists use an HTTP-status message so body/header-only failures can
|
|
962
|
+
* still match. The constructor receives the raw body and headers as well as
|
|
963
|
+
* code/message; error schemas can declare these fields to expose them to callers.
|
|
671
964
|
*/
|
|
672
965
|
export const matchTypedError = (
|
|
673
966
|
errorClasses: ReadonlyArray<unknown>,
|
|
674
967
|
status: number,
|
|
675
968
|
errors: ReadonlyArray<{ code?: number; message: string }>,
|
|
969
|
+
response: ErrorResponse = {},
|
|
676
970
|
): unknown | undefined => {
|
|
677
|
-
let best:
|
|
678
|
-
|
|
679
|
-
| undefined;
|
|
971
|
+
let best: { cls: unknown; specificity: number; code?: number; message: string } | undefined;
|
|
972
|
+
const wireErrors = errors.length > 0 ? errors : [{ message: `HTTP ${status}` }];
|
|
680
973
|
for (const cls of errorClasses) {
|
|
681
974
|
const matchers = getErrorMatchers(cls);
|
|
682
975
|
if (!matchers) continue;
|
|
683
976
|
for (const m of matchers) {
|
|
684
|
-
for (const e of
|
|
685
|
-
if (!matchesExpression(m, e.code, status, e.message)) continue;
|
|
977
|
+
for (const e of wireErrors) {
|
|
978
|
+
if (!matchesExpression(m, e.code, status, e.message, response)) continue;
|
|
686
979
|
const specificity = matcherSpecificity(m);
|
|
687
980
|
if (!best || specificity > best.specificity) {
|
|
688
981
|
best = { cls, specificity, code: e.code, message: e.message };
|
|
@@ -691,9 +984,16 @@ export const matchTypedError = (
|
|
|
691
984
|
}
|
|
692
985
|
}
|
|
693
986
|
if (!best) return undefined;
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
987
|
+
const saved = suppressStack();
|
|
988
|
+
try {
|
|
989
|
+
return new (best.cls as new (args: any) => unknown)({
|
|
990
|
+
code: best.code ?? 0,
|
|
991
|
+
message: best.message,
|
|
992
|
+
body: response.body,
|
|
993
|
+
headers: response.headers,
|
|
994
|
+
});
|
|
995
|
+
} finally {
|
|
996
|
+
restoreStack(saved);
|
|
997
|
+
}
|
|
698
998
|
};
|
|
699
999
|
//#endregion
|