@distilled.cloud/core 1.0.0-rc.12 → 1.0.0-rc.14

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 (276) hide show
  1. package/lib/api.d.ts +4 -4
  2. package/lib/api.d.ts.map +1 -1
  3. package/lib/api.js +3 -5
  4. package/lib/api.js.map +1 -1
  5. package/lib/category.d.ts.map +1 -1
  6. package/lib/category.js +3 -5
  7. package/lib/category.js.map +1 -1
  8. package/lib/codegen/boolean-string-enums.d.ts +8 -8
  9. package/lib/codegen/boolean-string-enums.d.ts.map +1 -1
  10. package/lib/codegen/boolean-string-enums.js +83 -30
  11. package/lib/codegen/boolean-string-enums.js.map +1 -1
  12. package/lib/codegen/boolean-string-enums.test.js +130 -2
  13. package/lib/codegen/boolean-string-enums.test.js.map +1 -1
  14. package/lib/codegen/cli.d.ts +5 -4
  15. package/lib/codegen/cli.d.ts.map +1 -1
  16. package/lib/codegen/cli.js +12 -9
  17. package/lib/codegen/cli.js.map +1 -1
  18. package/lib/codegen/defer-naming.test.d.ts +2 -0
  19. package/lib/codegen/defer-naming.test.d.ts.map +1 -0
  20. package/lib/codegen/defer-naming.test.js +105 -0
  21. package/lib/codegen/defer-naming.test.js.map +1 -0
  22. package/lib/codegen/emit.d.ts.map +1 -1
  23. package/lib/codegen/emit.js +1 -3
  24. package/lib/codegen/emit.js.map +1 -1
  25. package/lib/codegen/format.d.ts +0 -12
  26. package/lib/codegen/format.d.ts.map +1 -1
  27. package/lib/codegen/format.js +10 -6
  28. package/lib/codegen/format.js.map +1 -1
  29. package/lib/codegen/generated-at.d.ts +29 -0
  30. package/lib/codegen/generated-at.d.ts.map +1 -0
  31. package/lib/codegen/generated-at.js +78 -0
  32. package/lib/codegen/generated-at.js.map +1 -0
  33. package/lib/codegen/generated-at.test.d.ts +2 -0
  34. package/lib/codegen/generated-at.test.d.ts.map +1 -0
  35. package/lib/codegen/generated-at.test.js +81 -0
  36. package/lib/codegen/generated-at.test.js.map +1 -0
  37. package/lib/codegen/generator.d.ts +24 -5
  38. package/lib/codegen/generator.d.ts.map +1 -1
  39. package/lib/codegen/generator.js +69 -80
  40. package/lib/codegen/generator.js.map +1 -1
  41. package/lib/codegen/generator.test.d.ts +2 -0
  42. package/lib/codegen/generator.test.d.ts.map +1 -0
  43. package/lib/codegen/generator.test.js +121 -0
  44. package/lib/codegen/generator.test.js.map +1 -0
  45. package/lib/codegen/graphql-client.d.ts +7 -1
  46. package/lib/codegen/graphql-client.d.ts.map +1 -1
  47. package/lib/codegen/graphql-client.js +264 -148
  48. package/lib/codegen/graphql-client.js.map +1 -1
  49. package/lib/codegen/graphql-client.test.js +98 -238
  50. package/lib/codegen/graphql-client.test.js.map +1 -1
  51. package/lib/codegen/graphql.d.ts.map +1 -1
  52. package/lib/codegen/graphql.js +7 -20
  53. package/lib/codegen/graphql.js.map +1 -1
  54. package/lib/codegen/model-diff.d.ts +10 -0
  55. package/lib/codegen/model-diff.d.ts.map +1 -0
  56. package/lib/codegen/model-diff.js +67 -0
  57. package/lib/codegen/model-diff.js.map +1 -0
  58. package/lib/codegen/naming.d.ts.map +1 -1
  59. package/lib/codegen/naming.js.map +1 -1
  60. package/lib/codegen/openapi-binary.test.d.ts +2 -0
  61. package/lib/codegen/openapi-binary.test.d.ts.map +1 -0
  62. package/lib/codegen/openapi-binary.test.js +67 -0
  63. package/lib/codegen/openapi-binary.test.js.map +1 -0
  64. package/lib/codegen/openapi-cli.d.ts +11 -11
  65. package/lib/codegen/openapi-cli.d.ts.map +1 -1
  66. package/lib/codegen/openapi-cli.js +26 -51
  67. package/lib/codegen/openapi-cli.js.map +1 -1
  68. package/lib/codegen/openapi.d.ts +16 -2
  69. package/lib/codegen/openapi.d.ts.map +1 -1
  70. package/lib/codegen/openapi.js +56 -39
  71. package/lib/codegen/openapi.js.map +1 -1
  72. package/lib/codegen/operations.d.ts.map +1 -1
  73. package/lib/codegen/operations.js.map +1 -1
  74. package/lib/codegen/pagination.d.ts.map +1 -1
  75. package/lib/codegen/pagination.js +2 -4
  76. package/lib/codegen/pagination.js.map +1 -1
  77. package/lib/codegen/patch-audit.d.ts +84 -0
  78. package/lib/codegen/patch-audit.d.ts.map +1 -0
  79. package/lib/codegen/patch-audit.js +366 -0
  80. package/lib/codegen/patch-audit.js.map +1 -0
  81. package/lib/codegen/patch-audit.test.d.ts +2 -0
  82. package/lib/codegen/patch-audit.test.d.ts.map +1 -0
  83. package/lib/codegen/patch-audit.test.js +141 -0
  84. package/lib/codegen/patch-audit.test.js.map +1 -0
  85. package/lib/codegen/patches.d.ts +75 -11
  86. package/lib/codegen/patches.d.ts.map +1 -1
  87. package/lib/codegen/patches.js +301 -65
  88. package/lib/codegen/patches.js.map +1 -1
  89. package/lib/codegen/patches.test.js +55 -5
  90. package/lib/codegen/patches.test.js.map +1 -1
  91. package/lib/codegen/prelude.js +1 -1
  92. package/lib/codegen/prelude.js.map +1 -1
  93. package/lib/codegen/proto.d.ts.map +1 -1
  94. package/lib/codegen/proto.js +2 -4
  95. package/lib/codegen/proto.js.map +1 -1
  96. package/lib/codegen/protocol-imports.test.d.ts +2 -0
  97. package/lib/codegen/protocol-imports.test.d.ts.map +1 -0
  98. package/lib/codegen/protocol-imports.test.js +36 -0
  99. package/lib/codegen/protocol-imports.test.js.map +1 -0
  100. package/lib/codegen/rewrite-operation-ids.d.ts +23 -0
  101. package/lib/codegen/rewrite-operation-ids.d.ts.map +1 -1
  102. package/lib/codegen/rewrite-operation-ids.js +97 -59
  103. package/lib/codegen/rewrite-operation-ids.js.map +1 -1
  104. package/lib/codegen/rewrite-operation-ids.test.js +19 -101
  105. package/lib/codegen/rewrite-operation-ids.test.js.map +1 -1
  106. package/lib/codegen/spec-path.d.ts +1 -1
  107. package/lib/codegen/spec-path.d.ts.map +1 -1
  108. package/lib/codegen/spec-path.js +1 -1
  109. package/lib/codegen/spec-path.js.map +1 -1
  110. package/lib/codegen/untagged-unions.test.d.ts +2 -0
  111. package/lib/codegen/untagged-unions.test.d.ts.map +1 -0
  112. package/lib/codegen/untagged-unions.test.js +80 -0
  113. package/lib/codegen/untagged-unions.test.js.map +1 -0
  114. package/lib/error-category.d.ts.map +1 -1
  115. package/lib/error-category.js.map +1 -1
  116. package/lib/errors.d.ts +2 -1
  117. package/lib/errors.d.ts.map +1 -1
  118. package/lib/errors.js +9 -4
  119. package/lib/errors.js.map +1 -1
  120. package/lib/fixtures/xml/upstream-validator.json +397 -0
  121. package/lib/graphql.d.ts +292 -205
  122. package/lib/graphql.d.ts.map +1 -1
  123. package/lib/graphql.js +945 -636
  124. package/lib/graphql.js.map +1 -1
  125. package/lib/graphql.test.js +135 -764
  126. package/lib/graphql.test.js.map +1 -1
  127. package/lib/graphql.types.d.ts +10 -0
  128. package/lib/graphql.types.d.ts.map +1 -1
  129. package/lib/graphql.types.js +4 -44
  130. package/lib/graphql.types.js.map +1 -1
  131. package/lib/index.d.ts +27 -0
  132. package/lib/index.d.ts.map +1 -0
  133. package/lib/index.js +27 -0
  134. package/lib/index.js.map +1 -0
  135. package/lib/json-patch.d.ts +13 -6
  136. package/lib/json-patch.d.ts.map +1 -1
  137. package/lib/json-patch.js +34 -19
  138. package/lib/json-patch.js.map +1 -1
  139. package/lib/json-patch.test.d.ts +2 -0
  140. package/lib/json-patch.test.d.ts.map +1 -0
  141. package/lib/json-patch.test.js +65 -0
  142. package/lib/json-patch.test.js.map +1 -0
  143. package/lib/pagination.d.ts +2 -1
  144. package/lib/pagination.d.ts.map +1 -1
  145. package/lib/pagination.js +28 -30
  146. package/lib/pagination.js.map +1 -1
  147. package/lib/pagination.test.d.ts +2 -0
  148. package/lib/pagination.test.d.ts.map +1 -0
  149. package/lib/pagination.test.js +131 -0
  150. package/lib/pagination.test.js.map +1 -0
  151. package/lib/protocol-http.d.ts +30 -16
  152. package/lib/protocol-http.d.ts.map +1 -1
  153. package/lib/protocol-http.js +133 -84
  154. package/lib/protocol-http.js.map +1 -1
  155. package/lib/protocol-http.test.js +141 -1
  156. package/lib/protocol-http.test.js.map +1 -1
  157. package/lib/protocol-rest.d.ts +18 -1
  158. package/lib/protocol-rest.d.ts.map +1 -1
  159. package/lib/protocol-rest.js +32 -21
  160. package/lib/protocol-rest.js.map +1 -1
  161. package/lib/protocol-rest.test.d.ts +2 -0
  162. package/lib/protocol-rest.test.d.ts.map +1 -0
  163. package/lib/protocol-rest.test.js +498 -0
  164. package/lib/protocol-rest.test.js.map +1 -0
  165. package/lib/query.d.ts +29 -0
  166. package/lib/query.d.ts.map +1 -0
  167. package/lib/query.js +27 -0
  168. package/lib/query.js.map +1 -0
  169. package/lib/response-validation.d.ts +67 -0
  170. package/lib/response-validation.d.ts.map +1 -0
  171. package/lib/response-validation.js +76 -0
  172. package/lib/response-validation.js.map +1 -0
  173. package/lib/response-validation.test.d.ts +2 -0
  174. package/lib/response-validation.test.d.ts.map +1 -0
  175. package/lib/response-validation.test.js +72 -0
  176. package/lib/response-validation.test.js.map +1 -0
  177. package/lib/retry-after.d.ts.map +1 -1
  178. package/lib/retry-after.js +1 -1
  179. package/lib/retry-after.js.map +1 -1
  180. package/lib/retry-after.test.d.ts +2 -0
  181. package/lib/retry-after.test.d.ts.map +1 -0
  182. package/lib/retry-after.test.js +204 -0
  183. package/lib/retry-after.test.js.map +1 -0
  184. package/lib/retry.d.ts.map +1 -1
  185. package/lib/retry.js +1 -2
  186. package/lib/retry.js.map +1 -1
  187. package/lib/retry.test.d.ts +2 -0
  188. package/lib/retry.test.d.ts.map +1 -0
  189. package/lib/retry.test.js +407 -0
  190. package/lib/retry.test.js.map +1 -0
  191. package/lib/sdks.test.d.ts +2 -0
  192. package/lib/sdks.test.d.ts.map +1 -0
  193. package/lib/sdks.test.js +76 -0
  194. package/lib/sdks.test.js.map +1 -0
  195. package/lib/testing.d.ts +39 -0
  196. package/lib/testing.d.ts.map +1 -0
  197. package/lib/testing.js +41 -0
  198. package/lib/testing.js.map +1 -0
  199. package/lib/trait.d.ts +29 -9
  200. package/lib/trait.d.ts.map +1 -1
  201. package/lib/trait.js +8 -0
  202. package/lib/trait.js.map +1 -1
  203. package/lib/xml.d.ts +44 -0
  204. package/lib/xml.d.ts.map +1 -0
  205. package/lib/xml.js +311 -0
  206. package/lib/xml.js.map +1 -0
  207. package/lib/xml.test.d.ts +2 -0
  208. package/lib/xml.test.d.ts.map +1 -0
  209. package/lib/xml.test.js +210 -0
  210. package/lib/xml.test.js.map +1 -0
  211. package/package.json +8 -11
  212. package/src/api.ts +38 -55
  213. package/src/category.ts +21 -50
  214. package/src/codegen/boolean-string-enums.test.ts +148 -17
  215. package/src/codegen/boolean-string-enums.ts +81 -32
  216. package/src/codegen/cli.ts +29 -47
  217. package/src/codegen/defer-naming.test.ts +113 -0
  218. package/src/codegen/emit.ts +2 -5
  219. package/src/codegen/format.ts +12 -10
  220. package/src/codegen/generated-at.test.ts +89 -0
  221. package/src/codegen/generated-at.ts +88 -0
  222. package/src/codegen/generator.test.ts +137 -0
  223. package/src/codegen/generator.ts +132 -193
  224. package/src/codegen/graphql-client.test.ts +100 -297
  225. package/src/codegen/graphql-client.ts +302 -210
  226. package/src/codegen/graphql.ts +22 -94
  227. package/src/codegen/model-diff.ts +67 -0
  228. package/src/codegen/naming.ts +1 -2
  229. package/src/codegen/openapi-binary.test.ts +91 -0
  230. package/src/codegen/openapi-cli.ts +38 -79
  231. package/src/codegen/openapi.ts +98 -133
  232. package/src/codegen/operations.ts +2 -5
  233. package/src/codegen/pagination.ts +4 -11
  234. package/src/codegen/patch-audit.test.ts +160 -0
  235. package/src/codegen/patch-audit.ts +480 -0
  236. package/src/codegen/patches.test.ts +73 -15
  237. package/src/codegen/patches.ts +389 -99
  238. package/src/codegen/prelude.ts +1 -1
  239. package/src/codegen/proto.ts +18 -54
  240. package/src/codegen/protocol-imports.test.ts +39 -0
  241. package/src/codegen/rewrite-operation-ids.test.ts +23 -114
  242. package/src/codegen/rewrite-operation-ids.ts +111 -98
  243. package/src/codegen/spec-path.ts +3 -6
  244. package/src/codegen/untagged-unions.test.ts +85 -0
  245. package/src/error-category.ts +5 -17
  246. package/src/errors.ts +18 -30
  247. package/src/fixtures/xml/upstream-validator.json +397 -0
  248. package/src/graphql.test.ts +173 -949
  249. package/src/graphql.ts +1468 -1186
  250. package/src/graphql.types.ts +78 -164
  251. package/src/index.ts +26 -0
  252. package/src/json-patch.test.ts +77 -0
  253. package/src/json-patch.ts +54 -60
  254. package/src/pagination.test.ts +169 -0
  255. package/src/pagination.ts +46 -103
  256. package/src/protocol-http.test.ts +178 -9
  257. package/src/protocol-http.ts +174 -163
  258. package/src/protocol-rest.test.ts +703 -0
  259. package/src/protocol-rest.ts +76 -65
  260. package/src/query.ts +39 -0
  261. package/src/response-validation.test.ts +89 -0
  262. package/src/response-validation.ts +107 -0
  263. package/src/retry-after.test.ts +267 -0
  264. package/src/retry-after.ts +4 -10
  265. package/src/retry.test.ts +566 -0
  266. package/src/retry.ts +6 -21
  267. package/src/sdks.test.ts +87 -0
  268. package/src/testing.ts +72 -0
  269. package/src/trait.ts +48 -63
  270. package/src/xml.test.ts +251 -0
  271. package/src/xml.ts +323 -0
  272. package/lib/graphql.fixture.d.ts +0 -249
  273. package/lib/graphql.fixture.d.ts.map +0 -1
  274. package/lib/graphql.fixture.js +0 -240
  275. package/lib/graphql.fixture.js.map +0 -1
  276. package/src/graphql.fixture.ts +0 -371
@@ -1,3 +1,5 @@
1
+ import * as HttpBody from "effect/http/HttpBody";
2
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
1
3
  /**
2
4
  * Generic REST protocol machinery, shared by SDK protocol layers.
3
5
  *
@@ -9,8 +11,6 @@
9
11
  * {@link matchTypedError}).
10
12
  */
11
13
  import type * as AST from "effect/SchemaAST";
12
- import * as HttpBody from "effect/unstable/http/HttpBody";
13
- import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
14
14
  import {
15
15
  bodySymbol,
16
16
  deepQuerySymbol,
@@ -21,10 +21,12 @@ import {
21
21
  httpSymbol,
22
22
  keyDictionarySymbol,
23
23
  labelSymbol,
24
+ labelEncodingSymbol,
24
25
  querySymbol,
25
26
  stringEncodedSymbol,
26
27
  unionCasesSymbol,
27
28
  type ErrorMatcher,
29
+ type ErrorTextMatcher,
28
30
  type HttpTrait,
29
31
  type KeyDictionaryEntries,
30
32
  type UnionDiscriminator,
@@ -35,39 +37,29 @@ import {
35
37
  export const getProps = (ast: AST.AST): readonly AST.PropertySignature[] => {
36
38
  if (ast._tag === "Objects") return ast.propertySignatures;
37
39
  if (ast._tag === "Suspend") return getProps(ast.thunk());
38
- if (ast.encoding && ast.encoding.length > 0)
39
- return getProps(ast.encoding[0]!.to);
40
+ if (ast.encoding && ast.encoding.length > 0) return getProps(ast.encoding[0]!.to);
40
41
  return [];
41
42
  };
42
43
 
43
44
  export const getAnn = (ast: AST.AST, symbol: symbol): unknown => {
44
- const direct = (ast.annotations as Record<symbol, unknown> | undefined)?.[
45
- symbol
46
- ];
45
+ const direct = (ast.annotations as Record<symbol, unknown> | undefined)?.[symbol];
47
46
  if (direct !== undefined) return direct;
48
47
  if (ast._tag === "Suspend") return getAnn(ast.thunk(), symbol);
49
- if (ast.encoding && ast.encoding.length > 0)
50
- return getAnn(ast.encoding[0]!.to, symbol);
48
+ if (ast.encoding && ast.encoding.length > 0) return getAnn(ast.encoding[0]!.to, symbol);
51
49
  // S.optional → Union[self, Undefined]; descend into the single real member.
52
50
  if (ast._tag === "Union") {
53
51
  const real = (ast as AST.Union).types.filter(
54
- (t) =>
55
- t._tag !== "Undefined" &&
56
- !(t._tag === "Literal" && (t as any).literal === null),
52
+ (t) => t._tag !== "Undefined" && !(t._tag === "Literal" && (t as any).literal === null),
57
53
  );
58
54
  if (real.length === 1) return getAnn(real[0]!, symbol);
59
55
  }
60
56
  return undefined;
61
57
  };
62
58
 
63
- export const getPropAnn = (
64
- prop: AST.PropertySignature,
65
- symbol: symbol,
66
- ): unknown => getAnn(prop.type, symbol);
67
- export const hasPropAnn = (
68
- prop: AST.PropertySignature,
69
- symbol: symbol,
70
- ): boolean => getPropAnn(prop, symbol) !== undefined;
59
+ export const getPropAnn = (prop: AST.PropertySignature, symbol: symbol): unknown =>
60
+ getAnn(prop.type, symbol);
61
+ export const hasPropAnn = (prop: AST.PropertySignature, symbol: symbol): boolean =>
62
+ getPropAnn(prop, symbol) !== undefined;
71
63
  export const nameOf = (prop: AST.PropertySignature, symbol: symbol): string => {
72
64
  const v = getPropAnn(prop, symbol);
73
65
  return typeof v === "string" ? v : String(prop.name);
@@ -76,8 +68,7 @@ export const nameOf = (prop: AST.PropertySignature, symbol: symbol): string => {
76
68
  /** Resolve wrappers to the real node: Suspend, encoding, optional/null unions. */
77
69
  export const resolveNode = (ast: AST.AST): AST.AST => {
78
70
  if (ast._tag === "Suspend") return resolveNode(ast.thunk());
79
- if (ast.encoding && ast.encoding.length > 0)
80
- return resolveNode(ast.encoding[0]!.to);
71
+ if (ast.encoding && ast.encoding.length > 0) return resolveNode(ast.encoding[0]!.to);
81
72
  if (ast._tag === "Union") {
82
73
  const real = (ast as AST.Union).types.filter(
83
74
  (t) =>
@@ -121,9 +112,7 @@ export const mapKeysByDictionary = (
121
112
  direction === "decode"
122
113
  ? Object.fromEntries(
123
114
  Object.entries(dict).flatMap(([ts, wire]) =>
124
- typeof wire === "string"
125
- ? [[wire, ts] as const]
126
- : wire.map((w) => [w, ts] as const),
115
+ typeof wire === "string" ? [[wire, ts] as const] : wire.map((w) => [w, ts] as const),
127
116
  ),
128
117
  )
129
118
  : Object.fromEntries(
@@ -149,23 +138,24 @@ export const mapKeysByDictionary = (
149
138
  * TS-cased content still reaches the wire in wire case. Content with no
150
139
  * dictionary in scope passes through verbatim.
151
140
  */
141
+ /**
142
+ * 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
144
+ * flag as `"true" | "false"` still means "unset" by null, not `"null"`.
145
+ */
146
+ const stringEncode = (value: unknown): unknown =>
147
+ value === null ? null : Array.isArray(value) ? value.map(stringEncode) : String(value);
148
+
152
149
  export const mapKeys = (
153
150
  ast: AST.AST,
154
151
  value: unknown,
155
152
  direction: "encode" | "decode",
156
153
  fallback?: KeyDictionaryEntries,
157
154
  ): unknown => {
158
- if (
159
- value === null ||
160
- value === undefined ||
161
- typeof value !== "object" ||
162
- isOpaqueValue(value)
163
- ) {
155
+ if (value === null || value === undefined || typeof value !== "object" || isOpaqueValue(value)) {
164
156
  return value;
165
157
  }
166
- const dict =
167
- (getAnn(ast, keyDictionarySymbol) as KeyDictionaryEntries | undefined) ??
168
- fallback;
158
+ const dict = (getAnn(ast, keyDictionarySymbol) as KeyDictionaryEntries | undefined) ?? fallback;
169
159
 
170
160
  // Discriminated union whose cases the API returns merged (every case's
171
161
  // keys present, `null` for the inactive ones). Map wire names, then keep
@@ -184,18 +174,15 @@ export const mapKeys = (
184
174
  }
185
175
  | undefined;
186
176
  if (unionCases && direction === "decode" && !Array.isArray(value)) {
187
- const obj = (
188
- dict ? mapKeysByDictionary(dict, value, "decode") : value
189
- ) as Record<string, unknown>;
190
- const present = Object.keys(obj).filter(
191
- (k) => obj[k] !== undefined && obj[k] !== null,
192
- );
177
+ const obj = (dict ? mapKeysByDictionary(dict, value, "decode") : value) as Record<
178
+ string,
179
+ unknown
180
+ >;
181
+ const present = Object.keys(obj).filter((k) => obj[k] !== undefined && obj[k] !== null);
193
182
  const disc = unionCases.discriminator;
194
183
  const tag = disc ? obj[disc.key] : undefined;
195
184
  const tagged = typeof tag === "string" ? disc!.values.indexOf(tag) : -1;
196
- let best:
197
- | { keys: ReadonlyArray<string>; score: number; matched: number }
198
- | undefined;
185
+ let best: { keys: ReadonlyArray<string>; score: number; matched: number } | undefined;
199
186
  if (tagged >= 0) {
200
187
  best = { keys: unionCases.cases[tagged]!, score: 0, matched: 0 };
201
188
  } else {
@@ -210,9 +197,7 @@ export const mapKeys = (
210
197
  const score = matched - excess;
211
198
  if (
212
199
  matched > 0 &&
213
- (!best ||
214
- score > best.score ||
215
- (score === best.score && matched > best.matched))
200
+ (!best || score > best.score || (score === best.score && matched > best.matched))
216
201
  ) {
217
202
  best = { keys, score, matched };
218
203
  }
@@ -248,10 +233,8 @@ export const mapKeys = (
248
233
  for (const t of arms) {
249
234
  if (t._tag !== "Objects") continue;
250
235
  let score = 0;
251
- for (const p of (t as any)
252
- .propertySignatures as readonly AST.PropertySignature[]) {
253
- const from =
254
- direction === "encode" ? String(p.name) : nameOf(p, bodySymbol);
236
+ for (const p of (t as any).propertySignatures as readonly AST.PropertySignature[]) {
237
+ const from = direction === "encode" ? String(p.name) : nameOf(p, bodySymbol);
255
238
  if ((value as Record<string, unknown>)[from] !== undefined) score++;
256
239
  }
257
240
  if (score > bestScore) {
@@ -275,11 +258,8 @@ export const mapKeys = (
275
258
  }
276
259
 
277
260
  if (node._tag === "Objects" && !Array.isArray(value)) {
278
- const props = (node as any)
279
- .propertySignatures as readonly AST.PropertySignature[];
280
- const isigs = (node as any).indexSignatures as
281
- | readonly { type: AST.AST }[]
282
- | undefined;
261
+ const props = (node as any).propertySignatures as readonly AST.PropertySignature[];
262
+ const isigs = (node as any).indexSignatures as readonly { type: AST.AST }[] | undefined;
283
263
  if (props.length === 0 && !(isigs && isigs.length)) {
284
264
  // opaque object — dictionary fallback or verbatim
285
265
  return dict ? mapKeysByDictionary(dict, value, direction) : value;
@@ -294,7 +274,13 @@ export const mapKeys = (
294
274
  consumed.add(from);
295
275
  const v = (value as Record<string, unknown>)[from];
296
276
  if (v === undefined) continue;
297
- out[to] = mapKeys(p.type, v, direction, dict);
277
+ // A `StringEncoded()` member nested in a body struct (e.g. Azure's
278
+ // `hardwareProfile.dynamicMemoryEnabled`) stringifies here — the
279
+ // top-level pass in `buildRequest` only sees the outermost member.
280
+ out[to] =
281
+ direction === "encode" && hasPropAnn(p, stringEncodedSymbol)
282
+ ? stringEncode(v)
283
+ : mapKeys(p.type, v, direction, dict);
298
284
  }
299
285
  for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
300
286
  if (consumed.has(k) || v === undefined) continue;
@@ -334,30 +320,10 @@ const BODYLESS = new Set(["GET", "HEAD"]);
334
320
  * filter matching nothing — the call "succeeds" with zero results and the
335
321
  * bug is invisible to the caller.
336
322
  */
337
- /**
338
- * Value form for a `StringEncoded()` member: the string spelling of the
339
- * value, element-wise for lists. `null` stays `null` — an API that models a
340
- * flag as `"true" | "false"` still means "unset" by null, not `"null"`.
341
- */
342
- const stringEncode = (value: unknown): unknown =>
343
- value === null
344
- ? null
345
- : Array.isArray(value)
346
- ? value.map(stringEncode)
347
- : String(value);
348
-
349
- const appendQuery = (
350
- query: URLSearchParams,
351
- name: string,
352
- value: unknown,
353
- ): void => {
323
+ const appendQuery = (query: URLSearchParams, name: string, value: unknown): void => {
354
324
  if (Array.isArray(value)) {
355
325
  for (const v of value) appendQuery(query, name, v);
356
- } else if (
357
- value !== null &&
358
- typeof value === "object" &&
359
- !(value instanceof Date)
360
- ) {
326
+ } else if (value !== null && typeof value === "object" && !(value instanceof Date)) {
361
327
  for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
362
328
  if (v !== undefined) appendQuery(query, `${name}.${k}`, v);
363
329
  }
@@ -398,15 +364,21 @@ export interface BuildRequestOptions {
398
364
  * Throws when the input schema is missing the `Http()` trait — a codegen
399
365
  * bug, surfaced as a defect by the calling protocol's Effect context.
400
366
  */
367
+ /**
368
+ * Encode a greedy `{name+}` label: the value may span several path
369
+ * segments (e.g. an Azure scope `/subscriptions/{id}/resourceGroups/{rg}`),
370
+ * so each segment is encoded on its own and the `/` separators are kept.
371
+ * Leading slashes are dropped because the URI template already supplies one.
372
+ */
373
+ export const encodeGreedyLabel = (value: string): string =>
374
+ value.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
375
+
401
376
  /**
402
377
  * Flatten a nested object into Stripe-style bracket notation pairs for
403
378
  * form-urlencoded bodies: nested objects become `a[b][c]`, arrays index as
404
379
  * `a[0]`; null/undefined dropped, booleans as "true"/"false".
405
380
  */
406
- const flattenToFormPairs = (
407
- obj: Record<string, unknown>,
408
- prefix = "",
409
- ): Array<[string, string]> => {
381
+ const flattenToFormPairs = (obj: Record<string, unknown>, prefix = ""): Array<[string, string]> => {
410
382
  const pairs: Array<[string, string]> = [];
411
383
  for (const [key, value] of Object.entries(obj)) {
412
384
  if (value === undefined || value === null) continue;
@@ -416,20 +388,13 @@ const flattenToFormPairs = (
416
388
  const item = value[i];
417
389
  if (item === undefined || item === null) continue;
418
390
  if (typeof item === "object" && !Array.isArray(item)) {
419
- pairs.push(
420
- ...flattenToFormPairs(
421
- item as Record<string, unknown>,
422
- `${fullKey}[${i}]`,
423
- ),
424
- );
391
+ pairs.push(...flattenToFormPairs(item as Record<string, unknown>, `${fullKey}[${i}]`));
425
392
  } else {
426
393
  pairs.push([`${fullKey}[${i}]`, String(item)]);
427
394
  }
428
395
  }
429
396
  } else if (typeof value === "object") {
430
- pairs.push(
431
- ...flattenToFormPairs(value as Record<string, unknown>, fullKey),
432
- );
397
+ pairs.push(...flattenToFormPairs(value as Record<string, unknown>, fullKey));
433
398
  } else {
434
399
  pairs.push([fullKey, String(value)]);
435
400
  }
@@ -452,9 +417,7 @@ export const buildRequest = ({
452
417
  }
453
418
  // Root key dictionary: fallback wire mapping for opaque/unknown content
454
419
  // the schema doesn't model.
455
- const rootDict = getAnn(inputAst, keyDictionarySymbol) as
456
- | KeyDictionaryEntries
457
- | undefined;
420
+ const rootDict = getAnn(inputAst, keyDictionarySymbol) as KeyDictionaryEntries | undefined;
458
421
 
459
422
  const headers: Record<string, string> = { ...baseHeaders };
460
423
  const body: Record<string, unknown> = {};
@@ -464,6 +427,9 @@ export const buildRequest = ({
464
427
  let uri = http.uri;
465
428
  const consumed = new Set<string>();
466
429
  let hasBodyMembers = false;
430
+ // Value of a modeled `Content-Type` header member, e.g. R2 putObject's
431
+ // `contentType`. A raw body is sent under it (see below).
432
+ let memberContentType: string | undefined;
467
433
 
468
434
  for (const prop of getProps(inputAst)) {
469
435
  const key = String(prop.name);
@@ -479,11 +445,23 @@ export const buildRequest = ({
479
445
 
480
446
  if (hasPropAnn(prop, labelSymbol)) {
481
447
  const token = nameOf(prop, labelSymbol);
482
- uri = uri.replace(`{${token}}`, encodeURIComponent(String(value)));
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);
483
460
  } else if (hasPropAnn(prop, headerSymbol)) {
484
461
  const hName = nameOf(prop, headerSymbol).toLowerCase();
485
462
  const hVal = String(value);
486
463
  headers[hName] = mapMemberHeader ? mapMemberHeader(hName, hVal) : hVal;
464
+ if (hName === "content-type") memberContentType = headers[hName];
487
465
  } else if (hasPropAnn(prop, querySymbol)) {
488
466
  appendQuery(query, nameOf(prop, querySymbol), value);
489
467
  } else if (hasPropAnn(prop, deepQuerySymbol)) {
@@ -494,9 +472,7 @@ export const buildRequest = ({
494
472
  const base = nameOf(prop, deepQuerySymbol);
495
473
  const mapped = mapKeys(prop.type, value, "encode", rootDict);
496
474
  if (mapped !== null && typeof mapped === "object") {
497
- for (const [k, v] of Object.entries(
498
- mapped as Record<string, unknown>,
499
- )) {
475
+ for (const [k, v] of Object.entries(mapped as Record<string, unknown>)) {
500
476
  if (v !== undefined && v !== null) {
501
477
  appendQuery(query, `${base}.${k}`, v);
502
478
  }
@@ -525,8 +501,7 @@ export const buildRequest = ({
525
501
  // the key, otherwise `unknownKeyToWire` decides the wire name.
526
502
  for (const [key, value] of Object.entries(inputObj)) {
527
503
  if (consumed.has(key) || value === undefined) continue;
528
- const wire =
529
- rootDict?.[key] ?? (unknownKeyToWire ? unknownKeyToWire(key) : key);
504
+ const wire = rootDict?.[key] ?? (unknownKeyToWire ? unknownKeyToWire(key) : key);
530
505
  body[typeof wire === "string" ? wire : wire[0]] = rootDict
531
506
  ? mapKeysByDictionary(rootDict, value, "encode")
532
507
  : value;
@@ -536,12 +511,7 @@ export const buildRequest = ({
536
511
  const qs = query.toString();
537
512
  const url = `${baseUrl}${uri}${qs ? `?${qs}` : ""}`;
538
513
  if (process.env.DISTILLED_DEBUG_HTTP) {
539
- console.error(
540
- `[distilled] ${http.method} ${url}` +
541
- (Object.keys(body).length
542
- ? ` body=${JSON.stringify(body).slice(0, 400)}`
543
- : ""),
544
- );
514
+ console.error(`[distilled] -> ${http.method} ${http.uri}`);
545
515
  }
546
516
 
547
517
  let request = HttpClientRequest.make(http.method)(url).pipe(
@@ -552,24 +522,21 @@ export const buildRequest = ({
552
522
  // JSON-encoded under their wire name), each file appends under its own
553
523
  // filename. A whole-body member (T.HttpBody) that is a record of files
554
524
  // becomes one part per entry (e.g. asset upload: { <hash>: File }).
555
- // File/Blob → binary part (filename = File.name), array of files → each
556
- // appended, object → JSON string, primitive → string.
525
+ // Files and byte buffers become binary parts; objects become JSON parts.
557
526
  const form = new FormData();
558
527
  const parts =
559
528
  rawBody !== undefined && typeof rawBody === "object"
560
529
  ? (rawBody as Record<string, unknown>)
561
530
  : body;
562
- const isFileOrBlob = (v: unknown): v is Blob =>
563
- v instanceof Blob || v instanceof File;
531
+ const isFileOrBlob = (v: unknown): v is Blob => v instanceof Blob || v instanceof File;
564
532
  for (const [key, value] of Object.entries(parts)) {
565
533
  if (value === undefined || value === null) continue;
566
534
  if (isFileOrBlob(value)) {
567
535
  form.append(key, value, value instanceof File ? value.name : key);
568
- } else if (
569
- Array.isArray(value) &&
570
- value.length > 0 &&
571
- isFileOrBlob(value[0])
572
- ) {
536
+ } else if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
537
+ const bytes = value instanceof Uint8Array ? new Uint8Array(value).buffer : value;
538
+ form.append(key, new Blob([bytes]), key);
539
+ } else if (Array.isArray(value) && value.length > 0 && isFileOrBlob(value[0])) {
573
540
  for (const file of value as Blob[]) {
574
541
  if (isFileOrBlob(file)) {
575
542
  form.append(
@@ -590,10 +557,7 @@ export const buildRequest = ({
590
557
  form.append(filename, f, filename);
591
558
  }
592
559
  request = request.pipe(HttpClientRequest.bodyFormData(form));
593
- } else if (
594
- http.contentType === "form-urlencoded" &&
595
- !BODYLESS.has(http.method)
596
- ) {
560
+ } else if (http.contentType === "form-urlencoded" && !BODYLESS.has(http.method)) {
597
561
  // application/x-www-form-urlencoded with Stripe-style deepObject bracket
598
562
  // notation: { shipping: { address: { city } } } → shipping[address][city],
599
563
  // arrays indexed ({ expand: ["a"] } → expand[0]=a).
@@ -611,33 +575,28 @@ export const buildRequest = ({
611
575
  } else if (rawBody !== undefined && !BODYLESS.has(http.method)) {
612
576
  // Whole-body member (raw arrays/scalars) — sent as the body itself.
613
577
  // Binary payloads (Blob / ArrayBuffer / Uint8Array) send verbatim
614
- // (raw object uploads — the Content-Type header member, when modeled,
615
- // rides alongside). With a bodyMediaType, the member is a
616
- // preserialized payload (string / bytes) sent verbatim under that
617
- // media type (e.g. application/x-ndjson for Vectorize
618
- // insert/upsert); otherwise it's JSON.
578
+ // (raw object uploads). With a bodyMediaType, the member is a
579
+ // preserialized payload (string / bytes) sent verbatim; otherwise it's
580
+ // JSON.
581
+ //
582
+ // `setBody` overwrites the Content-Type header with the body's media
583
+ // type (and removes it when that is undefined), so the body carries the
584
+ // modeled Content-Type member when the caller set one, else the declared
585
+ // bodyMediaType (e.g. application/x-ndjson for Vectorize insert/upsert).
586
+ const mediaType = memberContentType ?? http.bodyMediaType;
619
587
  if (rawBody instanceof Blob || rawBody instanceof ArrayBuffer) {
620
- // Honor the declared media type (e.g. application/x-ndjson for
621
- // Vectorize insert/upsert) — without it the server may fall back to
622
- // JSON parsing. When no bodyMediaType is modeled the header is left
623
- // untouched (a modeled Content-Type header member rides alongside).
588
+ // With no media type at all, fetch falls back to the Blob's own type.
624
589
  request = request.pipe(
625
- HttpClientRequest.setBody(
626
- HttpBody.raw(rawBody, { contentType: http.bodyMediaType }),
627
- ),
590
+ HttpClientRequest.setBody(HttpBody.raw(rawBody, { contentType: mediaType })),
628
591
  );
629
592
  } else if (rawBody instanceof Uint8Array) {
630
- request = request.pipe(
631
- HttpClientRequest.setBody(
632
- HttpBody.uint8Array(rawBody, http.bodyMediaType),
633
- ),
634
- );
593
+ request = request.pipe(HttpClientRequest.setBody(HttpBody.uint8Array(rawBody, mediaType)));
635
594
  } else if (http.bodyMediaType) {
636
595
  request = request.pipe(
637
596
  HttpClientRequest.setBody(
638
597
  typeof rawBody === "string"
639
- ? HttpBody.text(rawBody, http.bodyMediaType)
640
- : HttpBody.uint8Array(rawBody as Uint8Array, http.bodyMediaType),
598
+ ? HttpBody.text(rawBody, mediaType)
599
+ : HttpBody.uint8Array(rawBody as Uint8Array, mediaType),
641
600
  ),
642
601
  );
643
602
  } else {
@@ -666,59 +625,109 @@ export const buildRequest = ({
666
625
 
667
626
  //#region Typed error matching
668
627
 
669
- /**
670
- * Whether one matcher matches one wire error: every present field must
671
- * match; a matcher (or a message object) with no constraints matches
672
- * nothing.
673
- */
628
+ /** Parsed response metadata supplied by a protocol after it detects a failure. */
629
+ export interface ErrorResponse {
630
+ readonly body?: unknown;
631
+ readonly headers?: Readonly<Record<string, string | undefined>>;
632
+ }
633
+
634
+ const matchesText = (matcher: ErrorTextMatcher, value: unknown): boolean => {
635
+ if (typeof value !== "string") return false;
636
+ if (typeof matcher === "string") return matcher === value;
637
+ const { includes, matches } = matcher;
638
+ return (
639
+ (includes !== undefined || matches !== undefined) &&
640
+ (includes === undefined || value.includes(includes)) &&
641
+ (matches === undefined || new RegExp(matches).test(value))
642
+ );
643
+ };
644
+
645
+ // Own properties only: inherited properties are not JSON response members.
646
+ const atPointer = (body: unknown, pointer: string): unknown => {
647
+ if (pointer === "") return body;
648
+ if (!pointer.startsWith("/") || /~(?![01])/u.test(pointer)) return undefined;
649
+ let value = body;
650
+ for (const segment of pointer.slice(1).split("/")) {
651
+ const key = segment.replace(/~1/g, "/").replace(/~0/g, "~");
652
+ if (
653
+ value === null ||
654
+ typeof value !== "object" ||
655
+ !Object.hasOwn(value, key) ||
656
+ (Array.isArray(value) && !/^(0|[1-9][0-9]*)$/.test(key))
657
+ )
658
+ return undefined;
659
+ value = (value as Record<string, unknown>)[key];
660
+ }
661
+ return value;
662
+ };
663
+
664
+ const matcherSpecificity = (m: ErrorMatcher): number =>
665
+ (m.code !== undefined ? 1 : 0) +
666
+ (m.status !== undefined ? 1 : 0) +
667
+ (m.message !== undefined ? 1 : 0) +
668
+ (m.body === undefined ? 0 : Object.keys(m.body).length) +
669
+ (m.headers === undefined ? 0 : Object.keys(m.headers).length);
670
+
671
+ /** Every supplied constraint must match; an unconstrained matcher matches nothing. */
674
672
  export const matchesExpression = (
675
673
  m: ErrorMatcher,
676
674
  code: number | undefined,
677
675
  status: number,
678
676
  message: string,
677
+ response: ErrorResponse = {},
679
678
  ): boolean => {
680
- if (m.code === undefined && m.status === undefined && m.message === undefined)
679
+ if (
680
+ m.code === undefined &&
681
+ m.status === undefined &&
682
+ m.message === undefined &&
683
+ matcherSpecificity(m) === 0
684
+ )
681
685
  return false;
682
686
  if (m.code !== undefined && m.code !== code) return false;
683
687
  if (m.status !== undefined && m.status !== status) return false;
684
- if (m.message !== undefined) {
685
- if (typeof m.message === "string") {
686
- if (m.message !== message) return false;
687
- } else {
688
- const { includes, matches } = m.message;
689
- if (includes === undefined && matches === undefined) return false;
690
- if (includes !== undefined && !message.includes(includes)) return false;
691
- if (matches !== undefined && !new RegExp(matches).test(message))
692
- return false;
688
+ if (m.message !== undefined && !matchesText(m.message, message)) return false;
689
+ if (m.body !== undefined) {
690
+ for (const [pointer, expected] of Object.entries(m.body)) {
691
+ const actual = atPointer(response.body, pointer);
692
+ if (typeof expected === "string" || (expected !== null && typeof expected === "object")) {
693
+ if (!matchesText(expected, actual)) return false;
694
+ } else if (actual !== expected) return false;
695
+ }
696
+ }
697
+ if (m.headers !== undefined) {
698
+ for (const [name, expected] of Object.entries(m.headers)) {
699
+ if (response.headers === undefined) return false;
700
+ const actual = Object.entries(response.headers).find(
701
+ ([key]) => key.toLowerCase() === name.toLowerCase(),
702
+ )?.[1];
703
+ if (!matchesText(expected, actual)) return false;
693
704
  }
694
705
  }
695
706
  return true;
696
707
  };
697
708
 
698
- const matcherSpecificity = (m: ErrorMatcher): number =>
699
- (m.code !== undefined ? 1 : 0) +
700
- (m.status !== undefined ? 1 : 0) +
701
- (m.message !== undefined ? 1 : 0);
702
-
703
709
  /**
704
710
  * Pick the operation's typed error class for a failed response: among all
705
711
  * declared classes whose matchers (see `applyErrorMatchers`) match the wire
706
712
  * failure, the most specific matcher wins (ties break by declaration order).
713
+ * Empty error lists use an HTTP-status message so body/header-only failures can
714
+ * still match. The constructor receives the raw body and headers as well as
715
+ * code/message; error schemas can declare these fields to expose them to callers.
707
716
  */
708
717
  export const matchTypedError = (
709
718
  errorClasses: ReadonlyArray<unknown>,
710
719
  status: number,
711
720
  errors: ReadonlyArray<{ code?: number; message: string }>,
721
+ response: ErrorResponse = {},
712
722
  ): unknown | undefined => {
713
- let best:
714
- | { cls: unknown; specificity: number; code?: number; message: string }
715
- | undefined;
723
+ let best: { cls: unknown; specificity: number; code?: number; message: string } | undefined;
724
+ const wireErrors = errors.length > 0 ? errors : [{ message: `HTTP ${status}` }];
716
725
  for (const cls of errorClasses) {
717
726
  const matchers = getErrorMatchers(cls);
718
727
  if (!matchers) continue;
719
728
  for (const m of matchers) {
720
- for (const e of errors) {
721
- if (!matchesExpression(m, e.code, status, e.message)) continue;
729
+ for (const e of wireErrors) {
730
+ if (!matchesExpression(m, e.code, status, e.message, response)) continue;
722
731
  const specificity = matcherSpecificity(m);
723
732
  if (!best || specificity > best.specificity) {
724
733
  best = { cls, specificity, code: e.code, message: e.message };
@@ -730,6 +739,8 @@ export const matchTypedError = (
730
739
  return new (best.cls as new (args: any) => unknown)({
731
740
  code: best.code ?? 0,
732
741
  message: best.message,
742
+ body: response.body,
743
+ headers: response.headers,
733
744
  });
734
745
  };
735
746
  //#endregion