@distilled.cloud/core 1.0.0-rc.15 → 1.0.0-rc.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (318) hide show
  1. package/lib/_bundle/aws.js +2 -0
  2. package/lib/_bundle/aws.js.map +1 -0
  3. package/lib/_bundle/base.js +5 -0
  4. package/lib/_bundle/base.js.map +1 -0
  5. package/lib/_bundle/graphql.js +3 -0
  6. package/lib/_bundle/graphql.js.map +1 -0
  7. package/lib/_bundle/rest.js +2 -0
  8. package/lib/_bundle/rest.js.map +1 -0
  9. package/lib/_bundle/xml.js +4 -0
  10. package/lib/_bundle/xml.js.map +1 -0
  11. package/lib/api.d.ts +118 -13
  12. package/lib/api.d.ts.map +1 -1
  13. package/lib/api.js +1 -188
  14. package/lib/category.d.ts.map +1 -1
  15. package/lib/category.js +1 -278
  16. package/lib/chunks.d.ts +3 -0
  17. package/lib/chunks.d.ts.map +1 -0
  18. package/lib/chunks.js +1 -0
  19. package/lib/codegen/boolean-string-enums.js +36 -36
  20. package/lib/codegen/chunk.d.ts +7 -0
  21. package/lib/codegen/chunk.d.ts.map +1 -0
  22. package/lib/codegen/chunk.js +139 -0
  23. package/lib/codegen/chunk.js.map +1 -0
  24. package/lib/codegen/cli.d.ts.map +1 -1
  25. package/lib/codegen/cli.js +28 -14
  26. package/lib/codegen/cli.js.map +1 -1
  27. package/lib/codegen/datafy.d.ts +14 -0
  28. package/lib/codegen/datafy.d.ts.map +1 -0
  29. package/lib/codegen/datafy.js +853 -0
  30. package/lib/codegen/datafy.js.map +1 -0
  31. package/lib/codegen/dedupe.d.ts +5 -0
  32. package/lib/codegen/dedupe.d.ts.map +1 -0
  33. package/lib/codegen/dedupe.js +153 -0
  34. package/lib/codegen/dedupe.js.map +1 -0
  35. package/lib/codegen/emit.js +56 -56
  36. package/lib/codegen/format.js +18 -18
  37. package/lib/codegen/generated-at.js +29 -29
  38. package/lib/codegen/generator.d.ts.map +1 -1
  39. package/lib/codegen/generator.js +92 -84
  40. package/lib/codegen/generator.js.map +1 -1
  41. package/lib/codegen/graph.js +36 -36
  42. package/lib/codegen/graphql-client.d.ts +2 -0
  43. package/lib/codegen/graphql-client.d.ts.map +1 -1
  44. package/lib/codegen/graphql-client.js +55 -26
  45. package/lib/codegen/graphql-client.js.map +1 -1
  46. package/lib/codegen/graphql.js +113 -113
  47. package/lib/codegen/latin1.d.ts +3 -0
  48. package/lib/codegen/latin1.d.ts.map +1 -0
  49. package/lib/codegen/latin1.js +126 -0
  50. package/lib/codegen/latin1.js.map +1 -0
  51. package/lib/codegen/members.d.ts +7 -0
  52. package/lib/codegen/members.d.ts.map +1 -1
  53. package/lib/codegen/members.js +26 -19
  54. package/lib/codegen/members.js.map +1 -1
  55. package/lib/codegen/model-diff.js +6 -6
  56. package/lib/codegen/naming.js +19 -19
  57. package/lib/codegen/openapi-cli.js +15 -15
  58. package/lib/codegen/openapi.d.ts +17 -0
  59. package/lib/codegen/openapi.d.ts.map +1 -1
  60. package/lib/codegen/openapi.js +323 -169
  61. package/lib/codegen/openapi.js.map +1 -1
  62. package/lib/codegen/operations.js +14 -14
  63. package/lib/codegen/pagination.js +11 -11
  64. package/lib/codegen/patch-audit.js +57 -57
  65. package/lib/codegen/patches.js +79 -79
  66. package/lib/codegen/prelude.js +19 -19
  67. package/lib/codegen/privatize.d.ts +21 -0
  68. package/lib/codegen/privatize.d.ts.map +1 -0
  69. package/lib/codegen/privatize.js +176 -0
  70. package/lib/codegen/privatize.js.map +1 -0
  71. package/lib/codegen/proto.js +25 -25
  72. package/lib/codegen/pure.d.ts +6 -0
  73. package/lib/codegen/pure.d.ts.map +1 -0
  74. package/lib/codegen/pure.js +91 -0
  75. package/lib/codegen/pure.js.map +1 -0
  76. package/lib/codegen/rewrite-operation-ids.js +108 -108
  77. package/lib/codegen/spec-path.js +57 -57
  78. package/lib/codegen/table.d.ts +5 -0
  79. package/lib/codegen/table.d.ts.map +1 -0
  80. package/lib/codegen/table.js +249 -0
  81. package/lib/codegen/table.js.map +1 -0
  82. package/lib/config.d.ts +27 -0
  83. package/lib/config.d.ts.map +1 -0
  84. package/lib/config.js +1 -0
  85. package/lib/crypto.d.ts +76 -0
  86. package/lib/crypto.d.ts.map +1 -0
  87. package/lib/crypto.js +1 -0
  88. package/lib/debug.d.ts +2 -0
  89. package/lib/debug.d.ts.map +1 -0
  90. package/lib/debug.js +1 -0
  91. package/lib/error-category.d.ts +1 -1
  92. package/lib/error-category.d.ts.map +1 -1
  93. package/lib/error-category.js +1 -46
  94. package/lib/errors.d.ts +62 -62
  95. package/lib/errors.d.ts.map +1 -1
  96. package/lib/errors.js +1 -195
  97. package/lib/graphql.d.ts +31 -20
  98. package/lib/graphql.d.ts.map +1 -1
  99. package/lib/graphql.js +1 -1027
  100. package/lib/graphql.types.js +1 -5
  101. package/lib/index.d.ts +3 -2
  102. package/lib/index.d.ts.map +1 -1
  103. package/lib/index.js +1 -15
  104. package/lib/json-patch.d.ts +2 -2
  105. package/lib/json-patch.js +1 -226
  106. package/lib/json-patch.js.map +1 -1
  107. package/lib/pagination.d.ts +9 -25
  108. package/lib/pagination.d.ts.map +1 -1
  109. package/lib/pagination.js +1 -266
  110. package/lib/plain-values.d.ts +10 -0
  111. package/lib/plain-values.d.ts.map +1 -0
  112. package/lib/plain-values.js +2 -0
  113. package/lib/plain-values.js.map +1 -0
  114. package/lib/protocol-http.d.ts +50 -14
  115. package/lib/protocol-http.d.ts.map +1 -1
  116. package/lib/protocol-http.js +1 -639
  117. package/lib/protocol-rest.d.ts +38 -25
  118. package/lib/protocol-rest.d.ts.map +1 -1
  119. package/lib/protocol-rest.js +1 -267
  120. package/lib/query.js +1 -27
  121. package/lib/response-validation-strict.d.ts +48 -0
  122. package/lib/response-validation-strict.d.ts.map +1 -0
  123. package/lib/response-validation-strict.js +1 -0
  124. package/lib/response-validation.d.ts +43 -25
  125. package/lib/response-validation.d.ts.map +1 -1
  126. package/lib/response-validation.js +1 -76
  127. package/lib/retry-after.d.ts +3 -3
  128. package/lib/retry-after.js +1 -112
  129. package/lib/retry.d.ts +48 -29
  130. package/lib/retry.d.ts.map +1 -1
  131. package/lib/retry.js +1 -209
  132. package/lib/schema-lite-impl.d.ts +158 -0
  133. package/lib/schema-lite-impl.d.ts.map +1 -0
  134. package/lib/schema-lite-impl.js +1 -0
  135. package/lib/schema-lite-typed.d.ts +41 -0
  136. package/lib/schema-lite-typed.d.ts.map +1 -0
  137. package/lib/schema-lite-typed.js +2 -0
  138. package/lib/schema-lite-typed.js.map +1 -0
  139. package/lib/schema-lite.d.ts +40 -0
  140. package/lib/schema-lite.d.ts.map +1 -0
  141. package/lib/schema-lite.js +1 -0
  142. package/lib/schema.d.ts +20 -6
  143. package/lib/schema.d.ts.map +1 -1
  144. package/lib/schema.js +1 -48
  145. package/lib/testing.d.ts +3 -2
  146. package/lib/testing.d.ts.map +1 -1
  147. package/lib/testing.js +1 -40
  148. package/lib/testing.js.map +1 -1
  149. package/lib/trait.d.ts +13 -13
  150. package/lib/trait.d.ts.map +1 -1
  151. package/lib/trait.js +1 -131
  152. package/lib/xml.d.ts +1 -1
  153. package/lib/xml.d.ts.map +1 -1
  154. package/lib/xml.js +1 -311
  155. package/package.json +9 -7
  156. package/src/api.ts +1080 -180
  157. package/src/category.ts +33 -33
  158. package/src/chunks.ts +30 -0
  159. package/src/codegen/chunk.ts +147 -0
  160. package/src/codegen/cli.ts +27 -1
  161. package/src/codegen/datafy.ts +874 -0
  162. package/src/codegen/dedupe.ts +173 -0
  163. package/src/codegen/generator.ts +10 -3
  164. package/src/codegen/graphql-client.ts +49 -15
  165. package/src/codegen/latin1.ts +131 -0
  166. package/src/codegen/members.ts +8 -0
  167. package/src/codegen/openapi.ts +194 -3
  168. package/src/codegen/privatize.ts +200 -0
  169. package/src/codegen/pure.ts +94 -0
  170. package/src/codegen/table.ts +254 -0
  171. package/src/config.ts +216 -0
  172. package/src/crypto.ts +202 -0
  173. package/src/debug.ts +8 -0
  174. package/src/error-category.ts +2 -1
  175. package/src/errors.ts +65 -56
  176. package/src/graphql.ts +109 -62
  177. package/src/graphql.types.ts +9 -7
  178. package/src/index.ts +3 -2
  179. package/src/json-patch.ts +2 -2
  180. package/src/pagination.ts +37 -18
  181. package/src/plain-values.ts +41 -0
  182. package/src/protocol-http.ts +378 -145
  183. package/src/protocol-rest.ts +337 -169
  184. package/src/response-validation-strict.ts +327 -0
  185. package/src/response-validation.ts +101 -50
  186. package/src/retry-after.ts +3 -3
  187. package/src/retry.ts +94 -93
  188. package/src/schema-lite-impl.ts +550 -0
  189. package/src/schema-lite-typed.ts +44 -0
  190. package/src/schema-lite.ts +44 -0
  191. package/src/schema.ts +258 -14
  192. package/src/testing.ts +4 -2
  193. package/src/trait.ts +36 -28
  194. package/src/xml.ts +31 -17
  195. package/lib/api.js.map +0 -1
  196. package/lib/category.js.map +0 -1
  197. package/lib/codegen/boolean-string-enums.test.d.ts +0 -2
  198. package/lib/codegen/boolean-string-enums.test.d.ts.map +0 -1
  199. package/lib/codegen/boolean-string-enums.test.js +0 -275
  200. package/lib/codegen/boolean-string-enums.test.js.map +0 -1
  201. package/lib/codegen/defer-naming.test.d.ts +0 -2
  202. package/lib/codegen/defer-naming.test.d.ts.map +0 -1
  203. package/lib/codegen/defer-naming.test.js +0 -105
  204. package/lib/codegen/defer-naming.test.js.map +0 -1
  205. package/lib/codegen/generated-at.test.d.ts +0 -2
  206. package/lib/codegen/generated-at.test.d.ts.map +0 -1
  207. package/lib/codegen/generated-at.test.js +0 -81
  208. package/lib/codegen/generated-at.test.js.map +0 -1
  209. package/lib/codegen/generator.test.d.ts +0 -2
  210. package/lib/codegen/generator.test.d.ts.map +0 -1
  211. package/lib/codegen/generator.test.js +0 -121
  212. package/lib/codegen/generator.test.js.map +0 -1
  213. package/lib/codegen/graphql-client.test.d.ts +0 -2
  214. package/lib/codegen/graphql-client.test.d.ts.map +0 -1
  215. package/lib/codegen/graphql-client.test.js +0 -171
  216. package/lib/codegen/graphql-client.test.js.map +0 -1
  217. package/lib/codegen/openapi-binary.test.d.ts +0 -2
  218. package/lib/codegen/openapi-binary.test.d.ts.map +0 -1
  219. package/lib/codegen/openapi-binary.test.js +0 -67
  220. package/lib/codegen/openapi-binary.test.js.map +0 -1
  221. package/lib/codegen/patch-audit.test.d.ts +0 -2
  222. package/lib/codegen/patch-audit.test.d.ts.map +0 -1
  223. package/lib/codegen/patch-audit.test.js +0 -141
  224. package/lib/codegen/patch-audit.test.js.map +0 -1
  225. package/lib/codegen/patches.test.d.ts +0 -2
  226. package/lib/codegen/patches.test.d.ts.map +0 -1
  227. package/lib/codegen/patches.test.js +0 -155
  228. package/lib/codegen/patches.test.js.map +0 -1
  229. package/lib/codegen/protocol-imports.test.d.ts +0 -2
  230. package/lib/codegen/protocol-imports.test.d.ts.map +0 -1
  231. package/lib/codegen/protocol-imports.test.js +0 -36
  232. package/lib/codegen/protocol-imports.test.js.map +0 -1
  233. package/lib/codegen/rewrite-operation-ids.test.d.ts +0 -2
  234. package/lib/codegen/rewrite-operation-ids.test.d.ts.map +0 -1
  235. package/lib/codegen/rewrite-operation-ids.test.js +0 -451
  236. package/lib/codegen/rewrite-operation-ids.test.js.map +0 -1
  237. package/lib/codegen/untagged-unions.test.d.ts +0 -2
  238. package/lib/codegen/untagged-unions.test.d.ts.map +0 -1
  239. package/lib/codegen/untagged-unions.test.js +0 -80
  240. package/lib/codegen/untagged-unions.test.js.map +0 -1
  241. package/lib/error-category.js.map +0 -1
  242. package/lib/errors.js.map +0 -1
  243. package/lib/fixtures/xml/upstream-validator.json +0 -397
  244. package/lib/graphql.js.map +0 -1
  245. package/lib/graphql.test.d.ts +0 -2
  246. package/lib/graphql.test.d.ts.map +0 -1
  247. package/lib/graphql.test.js +0 -151
  248. package/lib/graphql.test.js.map +0 -1
  249. package/lib/graphql.types.js.map +0 -1
  250. package/lib/index.js.map +0 -1
  251. package/lib/json-patch.test.d.ts +0 -2
  252. package/lib/json-patch.test.d.ts.map +0 -1
  253. package/lib/json-patch.test.js +0 -65
  254. package/lib/json-patch.test.js.map +0 -1
  255. package/lib/pagination.js.map +0 -1
  256. package/lib/pagination.test.d.ts +0 -2
  257. package/lib/pagination.test.d.ts.map +0 -1
  258. package/lib/pagination.test.js +0 -131
  259. package/lib/pagination.test.js.map +0 -1
  260. package/lib/protocol-http.js.map +0 -1
  261. package/lib/protocol-http.test.d.ts +0 -2
  262. package/lib/protocol-http.test.d.ts.map +0 -1
  263. package/lib/protocol-http.test.js +0 -228
  264. package/lib/protocol-http.test.js.map +0 -1
  265. package/lib/protocol-rest.js.map +0 -1
  266. package/lib/protocol-rest.test.d.ts +0 -2
  267. package/lib/protocol-rest.test.d.ts.map +0 -1
  268. package/lib/protocol-rest.test.js +0 -498
  269. package/lib/protocol-rest.test.js.map +0 -1
  270. package/lib/query.js.map +0 -1
  271. package/lib/response-validation.js.map +0 -1
  272. package/lib/response-validation.test.d.ts +0 -2
  273. package/lib/response-validation.test.d.ts.map +0 -1
  274. package/lib/response-validation.test.js +0 -72
  275. package/lib/response-validation.test.js.map +0 -1
  276. package/lib/retry-after.js.map +0 -1
  277. package/lib/retry-after.test.d.ts +0 -2
  278. package/lib/retry-after.test.d.ts.map +0 -1
  279. package/lib/retry-after.test.js +0 -204
  280. package/lib/retry-after.test.js.map +0 -1
  281. package/lib/retry.js.map +0 -1
  282. package/lib/retry.test.d.ts +0 -2
  283. package/lib/retry.test.d.ts.map +0 -1
  284. package/lib/retry.test.js +0 -407
  285. package/lib/retry.test.js.map +0 -1
  286. package/lib/schema.js.map +0 -1
  287. package/lib/sdks.test.d.ts +0 -2
  288. package/lib/sdks.test.d.ts.map +0 -1
  289. package/lib/sdks.test.js +0 -76
  290. package/lib/sdks.test.js.map +0 -1
  291. package/lib/trait.js.map +0 -1
  292. package/lib/xml.js.map +0 -1
  293. package/lib/xml.test.d.ts +0 -2
  294. package/lib/xml.test.d.ts.map +0 -1
  295. package/lib/xml.test.js +0 -210
  296. package/lib/xml.test.js.map +0 -1
  297. package/src/codegen/boolean-string-enums.test.ts +0 -299
  298. package/src/codegen/defer-naming.test.ts +0 -113
  299. package/src/codegen/generated-at.test.ts +0 -89
  300. package/src/codegen/generator.test.ts +0 -137
  301. package/src/codegen/graphql-client.test.ts +0 -189
  302. package/src/codegen/openapi-binary.test.ts +0 -91
  303. package/src/codegen/patch-audit.test.ts +0 -160
  304. package/src/codegen/patches.test.ts +0 -188
  305. package/src/codegen/protocol-imports.test.ts +0 -39
  306. package/src/codegen/rewrite-operation-ids.test.ts +0 -472
  307. package/src/codegen/untagged-unions.test.ts +0 -85
  308. package/src/fixtures/xml/upstream-validator.json +0 -397
  309. package/src/graphql.test.ts +0 -198
  310. package/src/json-patch.test.ts +0 -77
  311. package/src/pagination.test.ts +0 -169
  312. package/src/protocol-http.test.ts +0 -276
  313. package/src/protocol-rest.test.ts +0 -703
  314. package/src/response-validation.test.ts +0 -89
  315. package/src/retry-after.test.ts +0 -267
  316. package/src/retry.test.ts +0 -566
  317. package/src/sdks.test.ts +0 -87
  318. package/src/xml.test.ts +0 -251
@@ -1,16 +1,19 @@
1
+ import * as Headers from "effect/http/Headers";
1
2
  import * as HttpBody from "effect/http/HttpBody";
2
3
  import * as HttpClientRequest from "effect/http/HttpClientRequest";
3
4
  /**
4
5
  * Generic REST protocol machinery, shared by SDK protocol layers.
5
6
  *
6
7
  * Everything here is driven purely by the trait annotations in
7
- * `core/trait.ts` — nothing is provider-specific. An SDK protocol (e.g.
8
+ * `core/trait.ts` -- nothing is provider-specific. An SDK protocol (e.g.
8
9
  * cloudflare's) supplies credentials/base-URL, calls {@link buildRequest} to
9
10
  * encode, and layers its own response-envelope handling on top of the
10
11
  * decode-side helpers ({@link getProps}/{@link mapKeys}/
11
12
  * {@link matchTypedError}).
12
13
  */
13
14
  import type * as AST from "effect/SchemaAST";
15
+ import { debugHttp } from "./debug.ts";
16
+ import { isOpaqueValue } from "./plain-values.ts";
14
17
  import {
15
18
  bodySymbol,
16
19
  deepQuerySymbol,
@@ -46,7 +49,7 @@ export const getAnn = (ast: AST.AST, symbol: symbol): unknown => {
46
49
  if (direct !== undefined) return direct;
47
50
  if (ast._tag === "Suspend") return getAnn(ast.thunk(), symbol);
48
51
  if (ast.encoding && ast.encoding.length > 0) return getAnn(ast.encoding[0]!.to, symbol);
49
- // S.optional → Union[self, Undefined]; descend into the single real member.
52
+ // S.optional -> Union[self, Undefined]; descend into the single real member.
50
53
  if (ast._tag === "Union") {
51
54
  const real = (ast as AST.Union).types.filter(
52
55
  (t) => t._tag !== "Undefined" && !(t._tag === "Literal" && (t as any).literal === null),
@@ -82,15 +85,67 @@ export const resolveNode = (ast: AST.AST): AST.AST => {
82
85
  };
83
86
  //#endregion
84
87
 
88
+ //#region Response headers on outputs
89
+
90
+ /** An output member read from a response header (`T.Header`). */
91
+ export interface ResponseHeaderMember {
92
+ readonly key: string;
93
+ /** Lowercase header name. */
94
+ readonly wire: string;
95
+ /** The member is a number; the header's text is parsed. */
96
+ readonly number: boolean;
97
+ }
98
+
99
+ const noHeaderMembers: ReadonlyArray<ResponseHeaderMember> = [];
100
+ const headerMemberCache = /*@__PURE__*/ new WeakMap<AST.AST, ReadonlyArray<ResponseHeaderMember>>();
101
+
102
+ /** The output's header-bound members, read from the schema once. */
103
+ export const responseHeaderMembers = (outputAst: AST.AST): ReadonlyArray<ResponseHeaderMember> => {
104
+ let members = headerMemberCache.get(outputAst);
105
+ if (members !== undefined) return members;
106
+ const found: ResponseHeaderMember[] = [];
107
+ for (const prop of getProps(outputAst)) {
108
+ if (!hasPropAnn(prop, headerSymbol)) continue;
109
+ found.push({
110
+ key: String(prop.name),
111
+ wire: nameOf(prop, headerSymbol).toLowerCase(),
112
+ number: resolveNode(prop.type)._tag === "Number",
113
+ });
114
+ }
115
+ members = found.length === 0 ? noHeaderMembers : found;
116
+ headerMemberCache.set(outputAst, members);
117
+ return members;
118
+ };
119
+
120
+ /**
121
+ * Copy the response headers an output declares onto its decoded body. A
122
+ * number member gets the header parsed; text that is not a number is kept
123
+ * as sent, so strict validation reports it. A body that is not an object
124
+ * (a raw root) is returned as is -- generators bind no headers there.
125
+ */
126
+ export const withResponseHeaders = (
127
+ members: ReadonlyArray<ResponseHeaderMember>,
128
+ body: unknown,
129
+ headers: Record<string, string | undefined>,
130
+ ): unknown => {
131
+ if (members.length === 0 || body === null || typeof body !== "object" || Array.isArray(body)) {
132
+ return body;
133
+ }
134
+ let result: Record<string, unknown> | undefined;
135
+ for (const m of members) {
136
+ const raw = headers[m.wire];
137
+ if (raw === undefined) continue;
138
+ result ??= { ...(body as Record<string, unknown>) };
139
+ const parsed = m.number && raw.trim() !== "" ? Number(raw) : Number.NaN;
140
+ result[m.key] = Number.isNaN(parsed) ? raw : parsed;
141
+ }
142
+ return result ?? body;
143
+ };
144
+ //#endregion
145
+
85
146
  //#region Recursive wire-name mapping
86
147
 
87
- /** Binary/opaque values that must never be treated as key-value objects. */
88
- export const isOpaqueValue = (v: unknown): boolean =>
89
- v instanceof Blob ||
90
- v instanceof File ||
91
- v instanceof ArrayBuffer ||
92
- v instanceof Uint8Array ||
93
- v instanceof Date;
148
+ export { isOpaqueValue };
94
149
 
95
150
  /**
96
151
  * Deep-rename keys via a plain dictionary (see `T.KeyDictionary`). An entry
@@ -132,7 +187,7 @@ export const mapKeysByDictionary = (
132
187
  /**
133
188
  * Recursively rename keys between TS names and wire names, per the schema.
134
189
  *
135
- * `fallback` is the nearest ancestor `T.KeyDictionary` — schema-known members
190
+ * `fallback` is the nearest ancestor `T.KeyDictionary` -- schema-known members
136
191
  * always map via their own annotations, but opaque values (Document members,
137
192
  * keys the schema doesn't know) deep-rename via the dictionary so nested
138
193
  * TS-cased content still reaches the wire in wire case. Content with no
@@ -140,12 +195,66 @@ export const mapKeysByDictionary = (
140
195
  */
141
196
  /**
142
197
  * Value form for a `StringEncoded()` member: the string spelling of the
143
- * value, element-wise for lists. `null` stays `null` — an API that models a
198
+ * value, element-wise for lists. `null` stays `null` -- an API that models a
144
199
  * flag as `"true" | "false"` still means "unset" by null, not `"null"`.
145
200
  */
146
201
  const stringEncode = (value: unknown): unknown =>
147
202
  value === null ? null : Array.isArray(value) ? value.map(stringEncode) : String(value);
148
203
 
204
+ /**
205
+ * Whether {@link mapKeys} returns every value of `root` unchanged (as a deep
206
+ * copy) in `direction` with no fallback dictionary: no member is renamed,
207
+ * string-encoded (encode) or picked by `T.UnionCases` (decode), and no
208
+ * `T.KeyDictionary` is in scope anywhere below `root`. Protocols use it to
209
+ * skip the walk. Computed once per schema node and direction.
210
+ */
211
+ export const mapsVerbatim = (root: AST.AST, direction: "encode" | "decode"): boolean => {
212
+ const cache = direction === "encode" ? verbatimEncode : verbatimDecode;
213
+ let result = cache.get(root);
214
+ if (result !== undefined) return result;
215
+ result = true;
216
+ const seen = new Set<AST.AST>();
217
+ const stack: AST.AST[] = [root];
218
+ walk: while (stack.length > 0) {
219
+ const ast = stack.pop()!;
220
+ if (seen.has(ast)) continue;
221
+ seen.add(ast);
222
+ if (getAnn(ast, keyDictionarySymbol) !== undefined) {
223
+ result = false;
224
+ break;
225
+ }
226
+ if (direction === "decode" && getAnn(ast, unionCasesSymbol) !== undefined) {
227
+ result = false;
228
+ break;
229
+ }
230
+ const node = resolveNode(ast);
231
+ if (node._tag === "Union") {
232
+ for (const t of (node as AST.Union).types) stack.push(resolveNode(t));
233
+ } else if (node._tag === "Arrays") {
234
+ const elem = (node as any).rest?.[0] as AST.AST | undefined;
235
+ if (elem) stack.push(elem);
236
+ } else if (node._tag === "Objects") {
237
+ for (const p of (node as any).propertySignatures as readonly AST.PropertySignature[]) {
238
+ if (
239
+ nameOf(p, bodySymbol) !== String(p.name) ||
240
+ (direction === "encode" && hasPropAnn(p, stringEncodedSymbol))
241
+ ) {
242
+ result = false;
243
+ break walk;
244
+ }
245
+ stack.push(p.type);
246
+ }
247
+ for (const s of ((node as any).indexSignatures ?? []) as readonly { type: AST.AST }[]) {
248
+ stack.push(s.type);
249
+ }
250
+ }
251
+ }
252
+ cache.set(root, result);
253
+ return result;
254
+ };
255
+ const verbatimEncode = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
256
+ const verbatimDecode = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
257
+
149
258
  export const mapKeys = (
150
259
  ast: AST.AST,
151
260
  value: unknown,
@@ -160,10 +269,10 @@ export const mapKeys = (
160
269
  // Discriminated union whose cases the API returns merged (every case's
161
270
  // keys present, `null` for the inactive ones). Map wire names, then keep
162
271
  // only the active case's keys. The case is read off the union's
163
- // discriminator when it has one — cases that share a key set (every
272
+ // discriminator when it has one -- cases that share a key set (every
164
273
  // resource kind of `resource_tagging`, every page-rule action) are
165
274
  // indistinguishable by keys alone. Without one, a case does NOT need every
166
- // key present — arms carry optional members the wire may omit — so the
275
+ // key present -- arms carry optional members the wire may omit -- so the
167
276
  // active case is the one that best EXPLAINS the value: most present,
168
277
  // non-null keys covered, minus present keys the case cannot explain (ties
169
278
  // break by coverage, then declaration order).
@@ -214,12 +323,12 @@ export const mapKeys = (
214
323
  const node = resolveNode(ast);
215
324
 
216
325
  // Schema-level union member (a merged response struct whose arms disagree
217
- // on a member's type — see the codegen's response-union merge): pick the
326
+ // on a member's type -- see the codegen's response-union merge): pick the
218
327
  // arm that explains the value best and map with it. Object values score
219
328
  // arms by how many of their declared keys are present; array values take
220
329
  // 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 — were already collapsed by resolveNode; the
330
+ // fallback, like other opaque content. (Single-real-member unions --
331
+ // optional/null wrappers -- were already collapsed by resolveNode; the
223
332
  // opaque `T.UnionCases` mechanism never produces a Union node and is
224
333
  // handled above.)
225
334
  if (node._tag === "Union") {
@@ -261,7 +370,7 @@ export const mapKeys = (
261
370
  const props = (node as any).propertySignatures as readonly AST.PropertySignature[];
262
371
  const isigs = (node as any).indexSignatures as readonly { type: AST.AST }[] | undefined;
263
372
  if (props.length === 0 && !(isigs && isigs.length)) {
264
- // opaque object — dictionary fallback or verbatim
373
+ // opaque object -- dictionary fallback or verbatim
265
374
  return dict ? mapKeysByDictionary(dict, value, direction) : value;
266
375
  }
267
376
  const out: Record<string, unknown> = {};
@@ -275,7 +384,7 @@ export const mapKeys = (
275
384
  const v = (value as Record<string, unknown>)[from];
276
385
  if (v === undefined) continue;
277
386
  // A `StringEncoded()` member nested in a body struct (e.g. Azure's
278
- // `hardwareProfile.dynamicMemoryEnabled`) stringifies here — the
387
+ // `hardwareProfile.dynamicMemoryEnabled`) stringifies here -- the
279
388
  // top-level pass in `buildRequest` only sees the outermost member.
280
389
  out[to] =
281
390
  direction === "encode" && hasPropAnn(p, stringEncodedSymbol)
@@ -300,7 +409,7 @@ export const mapKeys = (
300
409
  return out;
301
410
  }
302
411
 
303
- // Scalar-typed schema node holding object content (spec drift) —
412
+ // Scalar-typed schema node holding object content (spec drift) --
304
413
  // dictionary fallback or verbatim.
305
414
  return dict ? mapKeysByDictionary(dict, value, direction) : value;
306
415
  };
@@ -308,16 +417,16 @@ export const mapKeys = (
308
417
 
309
418
  //#region Request building
310
419
 
311
- const BODYLESS = new Set(["GET", "HEAD"]);
420
+ const BODYLESS = /*@__PURE__*/ new Set(["GET", "HEAD"]);
312
421
 
313
422
  /**
314
423
  * Serialize one query member. Scalars go as `k=v`, arrays as repeated `k=v`
315
- * pairs, and nested plain objects recurse as DOTTED params — several list
424
+ * pairs, and nested plain objects recurse as DOTTED params -- several list
316
425
  * endpoints model their filters as structs (e.g. Cloudflare DNS listRecords
317
426
  * takes `name: { exact, contains, ... }`) that must go over the wire as
318
427
  * `name.exact=value`. Without this they fell through to `String(value)` and
319
428
  * were sent as `name=[object Object]`, which servers happily treat as a
320
- * filter matching nothing — the call "succeeds" with zero results and the
429
+ * filter matching nothing -- the call "succeeds" with zero results and the
321
430
  * bug is invisible to the caller.
322
431
  */
323
432
  const appendQuery = (query: URLSearchParams, name: string, value: unknown): void => {
@@ -345,25 +454,13 @@ export interface BuildRequestOptions {
345
454
  */
346
455
  readonly mapMemberHeader?: (name: string, value: string) => string;
347
456
  /**
348
- * Wire name for input keys the schema doesn't declare (spec drift —
457
+ * Wire name for input keys the schema doesn't declare (spec drift --
349
458
  * unknown keys pass through as body fields rather than being dropped).
350
459
  * Defaults to the key verbatim.
351
460
  */
352
461
  readonly unknownKeyToWire?: (key: string) => string;
353
462
  }
354
463
 
355
- /**
356
- * Build an HTTP request from an operation input and its schema, driven by
357
- * the trait annotations: `Http()` supplies method + URI template, `Label()`
358
- * members fill URI placeholders, `Header()`/`Query()` members bind to
359
- * headers/query params, `DeepQuery()` struct members expand into dotted
360
- * query params, `HttpBody()` sends the member as the whole body,
361
- * `FormDataFile()` members become multipart file parts, and everything else
362
- * is a JSON body field (wire-named via `Body()` / `KeyDictionary`).
363
- *
364
- * Throws when the input schema is missing the `Http()` trait — a codegen
365
- * bug, surfaced as a defect by the calling protocol's Effect context.
366
- */
367
464
  /**
368
465
  * Encode a greedy `{name+}` label: the value may span several path
369
466
  * segments (e.g. an Azure scope `/subscriptions/{id}/resourceGroups/{rg}`),
@@ -402,6 +499,131 @@ const flattenToFormPairs = (obj: Record<string, unknown>, prefix = ""): Array<[s
402
499
  return pairs;
403
500
  };
404
501
 
502
+ /** How an input member binds to the request. */
503
+ type Bind = "label" | "header" | "query" | "deepQuery" | "file" | "httpBody" | "body";
504
+
505
+ /** One input member, with its binding read from the schema once. */
506
+ interface MemberPlan {
507
+ readonly key: string;
508
+ readonly bind: Bind;
509
+ /** Label token, lower-cased header name, query name or body wire name. */
510
+ readonly name: string;
511
+ readonly type: AST.AST;
512
+ /** `LabelEncoding` characters kept unescaped. */
513
+ readonly preserve: string | undefined;
514
+ /** `{name+}` placeholder. */
515
+ readonly greedy: boolean;
516
+ readonly stringEncoded: boolean;
517
+ /** `mapKeys(type, value, "encode", rootDict)` returns the value unchanged. */
518
+ readonly verbatim: boolean;
519
+ }
520
+
521
+ /** What `buildRequest` reads from an input schema, computed once per schema. */
522
+ interface RequestPlan {
523
+ readonly http: HttpTrait;
524
+ readonly rootDict: KeyDictionaryEntries | undefined;
525
+ readonly members: ReadonlyArray<MemberPlan>;
526
+ readonly known: ReadonlySet<string>;
527
+ /** The schema declares a member that is sent in the body. */
528
+ readonly hasBodyMembers: boolean;
529
+ }
530
+
531
+ const plans = /*@__PURE__*/ new WeakMap<AST.AST, RequestPlan>();
532
+
533
+ const planFor = (inputAst: AST.AST): RequestPlan => {
534
+ let plan = plans.get(inputAst);
535
+ if (plan !== undefined) return plan;
536
+ const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
537
+ if (!http) {
538
+ throw new Error("operation input is missing the Http() trait");
539
+ }
540
+ const rootDict = getAnn(inputAst, keyDictionarySymbol) as KeyDictionaryEntries | undefined;
541
+ const members: MemberPlan[] = [];
542
+ const known = new Set<string>();
543
+ let hasBodyMembers = false;
544
+ for (const prop of getProps(inputAst)) {
545
+ const key = String(prop.name);
546
+ known.add(key);
547
+ let bind: Bind;
548
+ let name: string;
549
+ let greedy = false;
550
+ if (hasPropAnn(prop, labelSymbol)) {
551
+ bind = "label";
552
+ name = nameOf(prop, labelSymbol);
553
+ greedy = http.uri.includes(`{${name}+}`);
554
+ } else if (hasPropAnn(prop, headerSymbol)) {
555
+ bind = "header";
556
+ name = nameOf(prop, headerSymbol).toLowerCase();
557
+ } else if (hasPropAnn(prop, querySymbol)) {
558
+ bind = "query";
559
+ name = nameOf(prop, querySymbol);
560
+ } else if (hasPropAnn(prop, deepQuerySymbol)) {
561
+ bind = "deepQuery";
562
+ name = nameOf(prop, deepQuerySymbol);
563
+ } else {
564
+ hasBodyMembers = true;
565
+ bind = hasPropAnn(prop, formDataFileSymbol)
566
+ ? "file"
567
+ : hasPropAnn(prop, httpBodySymbol)
568
+ ? "httpBody"
569
+ : "body";
570
+ name = nameOf(prop, bodySymbol);
571
+ }
572
+ const preserve = getPropAnn(prop, labelEncodingSymbol);
573
+ members.push({
574
+ key,
575
+ bind,
576
+ name,
577
+ type: prop.type,
578
+ preserve: typeof preserve === "string" ? preserve : undefined,
579
+ greedy,
580
+ stringEncoded: hasPropAnn(prop, stringEncodedSymbol),
581
+ verbatim: rootDict === undefined && mapsVerbatim(prop.type, "encode"),
582
+ });
583
+ }
584
+ plan = { http, rootDict, members, known, hasBodyMembers };
585
+ plans.set(inputAst, plan);
586
+ return plan;
587
+ };
588
+
589
+ const emptyRequest = /*@__PURE__*/ HttpClientRequest.get("");
590
+
591
+ /**
592
+ * `HttpClientRequest.make(method)(url)` with `headers` set, in one object:
593
+ * the same request as `make(...).pipe(setHeaders(headers))` without the
594
+ * intermediate copies. `url` may carry a query string.
595
+ */
596
+ export const makeRequest = (
597
+ method: HttpTrait["method"],
598
+ url: string,
599
+ headers: Record<string, string>,
600
+ ): HttpClientRequest.HttpClientRequest =>
601
+ HttpClientRequest.makeWith(
602
+ method,
603
+ url,
604
+ emptyRequest.urlParams,
605
+ emptyRequest.hash,
606
+ Headers.fromInput(headers),
607
+ HttpBody.empty,
608
+ );
609
+
610
+ /**
611
+ * Build an HTTP request from an operation input and its schema, driven by
612
+ * the trait annotations: `Http()` supplies method + URI template, `Label()`
613
+ * members fill URI placeholders, `Header()`/`Query()` members bind to
614
+ * headers/query params, `DeepQuery()` struct members expand into dotted
615
+ * query params, `HttpBody()` sends the member as the whole body,
616
+ * `FormDataFile()` members become multipart file parts, and everything else
617
+ * is a JSON body field (wire-named via `Body()` / `KeyDictionary`).
618
+ *
619
+ * The schema is read once per input schema (see `planFor`); later calls only
620
+ * walk the input value.
621
+ *
622
+ * Throws when the input schema is missing the `Http()` trait -- a codegen
623
+ * bug -- and, before anything is sent, when a label is `.` or `..` (for a
624
+ * greedy `{name+}` label, when any of its segments is). Each surfaces as a
625
+ * defect by the calling protocol's Effect context.
626
+ */
405
627
  export const buildRequest = ({
406
628
  input,
407
629
  inputAst,
@@ -411,112 +633,123 @@ export const buildRequest = ({
411
633
  unknownKeyToWire,
412
634
  }: BuildRequestOptions): HttpClientRequest.HttpClientRequest => {
413
635
  const inputObj = (input ?? {}) as Record<string, unknown>;
414
- const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
415
- if (!http) {
416
- throw new Error("operation input is missing the Http() trait");
417
- }
418
- // Root key dictionary: fallback wire mapping for opaque/unknown content
419
- // the schema doesn't model.
420
- const rootDict = getAnn(inputAst, keyDictionarySymbol) as KeyDictionaryEntries | undefined;
636
+ const plan = planFor(inputAst);
637
+ const { http, rootDict, members, known } = plan;
638
+ let hasBodyMembers = plan.hasBodyMembers;
421
639
 
422
640
  const headers: Record<string, string> = { ...baseHeaders };
423
641
  const body: Record<string, unknown> = {};
424
- let rawBody: unknown; // whole-body member (T.HttpBody) — sent as-is
425
- const files: Array<Blob | File> = [];
426
- const query = new URLSearchParams();
642
+ let bodyKeys = 0;
643
+ let rawBody: unknown; // whole-body member (T.HttpBody) -- sent as-is
644
+ let files: Array<Blob | File> | undefined;
645
+ let query: URLSearchParams | undefined;
427
646
  let uri = http.uri;
428
- const consumed = new Set<string>();
429
- let hasBodyMembers = false;
430
647
  // Value of a modeled `Content-Type` header member, e.g. R2 putObject's
431
648
  // `contentType`. A raw body is sent under it (see below).
432
649
  let memberContentType: string | undefined;
433
650
 
434
- for (const prop of getProps(inputAst)) {
435
- const key = String(prop.name);
436
- consumed.add(key);
437
- const value = inputObj[key];
438
- const isBodyMember =
439
- !hasPropAnn(prop, labelSymbol) &&
440
- !hasPropAnn(prop, headerSymbol) &&
441
- !hasPropAnn(prop, querySymbol) &&
442
- !hasPropAnn(prop, deepQuerySymbol);
443
- if (isBodyMember) hasBodyMembers = true;
651
+ for (let i = 0; i < members.length; i++) {
652
+ const m = members[i]!;
653
+ const value = inputObj[m.key];
444
654
  if (value === undefined) continue;
445
-
446
- if (hasPropAnn(prop, labelSymbol)) {
447
- const token = nameOf(prop, labelSymbol);
448
- const preserve = getPropAnn(prop, labelEncodingSymbol);
449
- const encoded = encodeURIComponent(String(value));
450
- const label =
451
- typeof preserve === "string"
452
- ? encoded.replace(/%[0-9A-F]{2}/g, (escape) => {
453
- const character = String.fromCharCode(Number.parseInt(escape.slice(1), 16));
454
- return preserve.includes(character) ? character : escape;
455
- })
456
- : encoded;
457
- uri = uri.includes(`{${token}+}`)
458
- ? uri.replace(`{${token}+}`, () => encodeGreedyLabel(String(value)))
459
- : uri.replace(`{${token}}`, () => label);
460
- } else if (hasPropAnn(prop, headerSymbol)) {
461
- const hName = nameOf(prop, headerSymbol).toLowerCase();
462
- const hVal = String(value);
463
- headers[hName] = mapMemberHeader ? mapMemberHeader(hName, hVal) : hVal;
464
- if (hName === "content-type") memberContentType = headers[hName];
465
- } else if (hasPropAnn(prop, querySymbol)) {
466
- appendQuery(query, nameOf(prop, querySymbol), value);
467
- } else if (hasPropAnn(prop, deepQuerySymbol)) {
468
- // Deep-object query member (T.DeepQuery): a nested struct expands into
469
- // dotted query keys (`account.id=…`) under the member's wire name.
470
- // Wire-name the nested content via the schema first, skip null/
471
- // undefined entries; deeper nesting recurses through appendQuery.
472
- const base = nameOf(prop, deepQuerySymbol);
473
- const mapped = mapKeys(prop.type, value, "encode", rootDict);
474
- if (mapped !== null && typeof mapped === "object") {
475
- for (const [k, v] of Object.entries(mapped as Record<string, unknown>)) {
476
- if (v !== undefined && v !== null) {
477
- appendQuery(query, `${base}.${k}`, v);
478
- }
655
+ switch (m.bind) {
656
+ case "label": {
657
+ // The URL parser resolves a `.` or `..` segment, percent-encoded or
658
+ // not, so no encoding can carry one: it would address another path
659
+ // (`/projects/p1/branches/..` -> `/projects/p1/`). A greedy label keeps
660
+ // its `/`, so each of its segments counts.
661
+ if (
662
+ (m.greedy ? String(value).split("/") : [String(value)]).some(
663
+ (s) => s === "." || s === "..",
664
+ )
665
+ ) {
666
+ throw new Error(`invalid value for input HTTP label: ${m.key}`);
479
667
  }
668
+ const encoded = encodeURIComponent(String(value));
669
+ const preserve = m.preserve;
670
+ const label =
671
+ preserve !== undefined
672
+ ? encoded.replace(/%[0-9A-F]{2}/g, (escape) => {
673
+ const character = String.fromCharCode(Number.parseInt(escape.slice(1), 16));
674
+ return preserve.includes(character) ? character : escape;
675
+ })
676
+ : encoded;
677
+ uri = m.greedy
678
+ ? uri.replace(`{${m.name}+}`, () => encodeGreedyLabel(String(value)))
679
+ : uri.replace(`{${m.name}}`, () => label);
680
+ break;
480
681
  }
481
- } else if (hasPropAnn(prop, formDataFileSymbol)) {
482
- for (const f of Array.isArray(value) ? value : [value]) {
483
- files.push(f as Blob | File);
682
+ case "header": {
683
+ const hVal = String(value);
684
+ headers[m.name] = mapMemberHeader ? mapMemberHeader(m.name, hVal) : hVal;
685
+ if (m.name === "content-type") memberContentType = headers[m.name];
686
+ break;
484
687
  }
485
- } else if (hasPropAnn(prop, httpBodySymbol)) {
486
- rawBody = mapKeys(prop.type, value, "encode", rootDict);
487
- } else {
488
- // T.StringEncoded(): the API takes this member's value only as its
489
- // string spelling (`true` → `"true"`), while the TS surface keeps the
490
- // natural type. Explicit here so a JSON body carries the string too,
491
- // rather than relying on the multipart encoder's own `String()`.
492
- body[nameOf(prop, bodySymbol)] = hasPropAnn(prop, stringEncodedSymbol)
493
- ? stringEncode(value)
494
- : mapKeys(prop.type, value, "encode", rootDict);
688
+ case "query":
689
+ appendQuery((query ??= new URLSearchParams()), m.name, value);
690
+ break;
691
+ case "deepQuery": {
692
+ // Deep-object query member (T.DeepQuery): a nested struct expands into
693
+ // dotted query keys (`account.id=...`) under the member's wire name.
694
+ // Wire-name the nested content via the schema first, skip null/
695
+ // undefined entries; deeper nesting recurses through appendQuery.
696
+ const mapped = m.verbatim ? value : mapKeys(m.type, value, "encode", rootDict);
697
+ if (mapped !== null && typeof mapped === "object") {
698
+ for (const [k, v] of Object.entries(mapped as Record<string, unknown>)) {
699
+ if (v !== undefined && v !== null) {
700
+ appendQuery((query ??= new URLSearchParams()), `${m.name}.${k}`, v);
701
+ }
702
+ }
703
+ }
704
+ break;
705
+ }
706
+ case "file":
707
+ files ??= [];
708
+ for (const f of Array.isArray(value) ? value : [value]) {
709
+ files.push(f as Blob | File);
710
+ }
711
+ break;
712
+ case "httpBody":
713
+ rawBody = m.verbatim ? value : mapKeys(m.type, value, "encode", rootDict);
714
+ break;
715
+ default:
716
+ // T.StringEncoded(): the API takes this member's value only as its
717
+ // string spelling (`true` -> `"true"`), while the TS surface keeps the
718
+ // natural type. Explicit here so a JSON body carries the string too,
719
+ // rather than relying on the multipart encoder's own `String()`.
720
+ body[m.name] = m.stringEncoded
721
+ ? stringEncode(value)
722
+ : m.verbatim
723
+ ? value
724
+ : mapKeys(m.type, value, "encode", rootDict);
725
+ bodyKeys++;
495
726
  }
496
727
  }
497
728
 
498
- // Input keys the schema doesn't know pass through as body fields — the
729
+ // Input keys the schema doesn't know pass through as body fields -- the
499
730
  // generated schemas can lag the real API, and silently dropping them
500
731
  // would break working callers. The key dictionary maps them when it knows
501
732
  // the key, otherwise `unknownKeyToWire` decides the wire name.
502
- for (const [key, value] of Object.entries(inputObj)) {
503
- if (consumed.has(key) || value === undefined) continue;
733
+ for (const key in inputObj) {
734
+ if (known.has(key) || !Object.hasOwn(inputObj, key)) continue;
735
+ const value = inputObj[key];
736
+ if (value === undefined) continue;
504
737
  const wire = rootDict?.[key] ?? (unknownKeyToWire ? unknownKeyToWire(key) : key);
505
738
  body[typeof wire === "string" ? wire : wire[0]] = rootDict
506
739
  ? mapKeysByDictionary(rootDict, value, "encode")
507
740
  : value;
741
+ bodyKeys++;
508
742
  hasBodyMembers = true;
509
743
  }
510
744
 
511
- const qs = query.toString();
512
- const url = `${baseUrl}${uri}${qs ? `?${qs}` : ""}`;
513
- if (process.env.DISTILLED_DEBUG_HTTP) {
745
+ const qs = query === undefined ? "" : query.toString();
746
+ const url = qs ? `${baseUrl}${uri}?${qs}` : `${baseUrl}${uri}`;
747
+ if (debugHttp()) {
514
748
  console.error(`[distilled] -> ${http.method} ${http.uri}`);
515
749
  }
516
750
 
517
- let request = HttpClientRequest.make(http.method)(url).pipe(
518
- HttpClientRequest.setHeaders(headers),
519
- );
751
+ const request = makeRequest(http.method, url, headers);
752
+ const bodied = !BODYLESS.has(http.method);
520
753
  if (http.contentType === "multipart") {
521
754
  // Multipart upload: each body member is a form part (objects
522
755
  // JSON-encoded under their wire name), each file appends under its own
@@ -552,28 +785,29 @@ export const buildRequest = ({
552
785
  form.append(key, String(value));
553
786
  }
554
787
  }
555
- for (const f of files) {
788
+ for (const f of files ?? []) {
556
789
  const filename = (f as File).name ?? "file";
557
790
  form.append(filename, f, filename);
558
791
  }
559
- request = request.pipe(HttpClientRequest.bodyFormData(form));
560
- } else if (http.contentType === "form-urlencoded" && !BODYLESS.has(http.method)) {
792
+ return HttpClientRequest.setBody(request, HttpBody.formData(form));
793
+ }
794
+ if (http.contentType === "form-urlencoded" && bodied) {
561
795
  // application/x-www-form-urlencoded with Stripe-style deepObject bracket
562
- // notation: { shipping: { address: { city } } } → shipping[address][city],
563
- // arrays indexed ({ expand: ["a"] } → expand[0]=a).
796
+ // notation: { shipping: { address: { city } } } -> shipping[address][city],
797
+ // arrays indexed ({ expand: ["a"] } -> expand[0]=a).
564
798
  const source =
565
799
  rawBody !== undefined && typeof rawBody === "object"
566
800
  ? (rawBody as Record<string, unknown>)
567
801
  : body;
568
802
  const params = new URLSearchParams();
569
803
  for (const [k, v] of flattenToFormPairs(source)) params.append(k, v);
570
- request = request.pipe(
571
- HttpClientRequest.setBody(
572
- HttpBody.text(params.toString(), "application/x-www-form-urlencoded"),
573
- ),
804
+ return HttpClientRequest.setBody(
805
+ request,
806
+ HttpBody.text(params.toString(), "application/x-www-form-urlencoded"),
574
807
  );
575
- } else if (rawBody !== undefined && !BODYLESS.has(http.method)) {
576
- // Whole-body member (raw arrays/scalars) — sent as the body itself.
808
+ }
809
+ if (rawBody !== undefined && bodied) {
810
+ // Whole-body member (raw arrays/scalars) -- sent as the body itself.
577
811
  // Binary payloads (Blob / ArrayBuffer / Uint8Array) send verbatim
578
812
  // (raw object uploads). With a bodyMediaType, the member is a
579
813
  // preserialized payload (string / bytes) sent verbatim; otherwise it's
@@ -586,38 +820,37 @@ export const buildRequest = ({
586
820
  const mediaType = memberContentType ?? http.bodyMediaType;
587
821
  if (rawBody instanceof Blob || rawBody instanceof ArrayBuffer) {
588
822
  // With no media type at all, fetch falls back to the Blob's own type.
589
- request = request.pipe(
590
- HttpClientRequest.setBody(HttpBody.raw(rawBody, { contentType: mediaType })),
591
- );
592
- } else if (rawBody instanceof Uint8Array) {
593
- request = request.pipe(HttpClientRequest.setBody(HttpBody.uint8Array(rawBody, mediaType)));
594
- } else if (http.bodyMediaType) {
595
- request = request.pipe(
596
- HttpClientRequest.setBody(
597
- typeof rawBody === "string"
598
- ? HttpBody.text(rawBody, mediaType)
599
- : HttpBody.uint8Array(rawBody as Uint8Array, mediaType),
600
- ),
823
+ return HttpClientRequest.setBody(request, HttpBody.raw(rawBody, { contentType: mediaType }));
824
+ }
825
+ if (rawBody instanceof Uint8Array) {
826
+ return HttpClientRequest.setBody(request, HttpBody.uint8Array(rawBody, mediaType));
827
+ }
828
+ if (http.bodyMediaType) {
829
+ return HttpClientRequest.setBody(
830
+ request,
831
+ typeof rawBody === "string"
832
+ ? HttpBody.text(rawBody, mediaType)
833
+ : HttpBody.uint8Array(rawBody as Uint8Array, mediaType),
601
834
  );
602
- } else {
603
- request = request.pipe(HttpClientRequest.bodyJsonUnsafe(rawBody));
604
835
  }
605
- } else if (
836
+ return HttpClientRequest.setBody(request, HttpBody.jsonUnsafe(rawBody));
837
+ }
838
+ if (
606
839
  // A GET/HEAD sends a body only when body members actually carry values.
607
840
  // Some APIs really do document GET-with-body: MongoDB Atlas's
608
- // `…/lineItems:search` declares a `requestBody` on `get`, and AWS EFS's
841
+ // `.../lineItems:search` declares a `requestBody` on `get`, and AWS EFS's
609
842
  // DescribeAccountPreferences takes `{ MaxResults, NextToken }` on a GET.
610
- // Suppressing it outright dropped those members silently — the request
843
+ // Suppressing it outright dropped those members silently -- the request
611
844
  // succeeded, unfiltered, with nothing on the wire to show why.
612
845
  //
613
846
  // The `{}`-when-empty rule below stays limited to methods that expect a
614
847
  // body, so a bodyless method with nothing set still sends nothing.
615
- Object.keys(body).length > 0 ||
616
- (hasBodyMembers && !BODYLESS.has(http.method) && http.method !== "DELETE")
848
+ bodyKeys > 0 ||
849
+ (hasBodyMembers && bodied && http.method !== "DELETE")
617
850
  ) {
618
- // Send `{}` rather than no body when the schema declares body members —
851
+ // Send `{}` rather than no body when the schema declares body members --
619
852
  // some endpoints reject a missing JSON body outright.
620
- request = request.pipe(HttpClientRequest.bodyJsonUnsafe(body));
853
+ return HttpClientRequest.setBody(request, HttpBody.jsonUnsafe(body));
621
854
  }
622
855
  return request;
623
856
  };