@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
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Checks that run against every SDK package in the repo. Generated code is
3
+ * tested once, here in core; these catch a package whose hand-written glue
4
+ * drifted from what the generator and protocols expect.
5
+ */
6
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { describe, expect, test } from "vitest";
9
+
10
+ const PACKAGES = join(import.meta.dirname, "..", "..");
11
+
12
+ const sdks = readdirSync(PACKAGES)
13
+ .filter((name) => name !== "core" && existsSync(join(PACKAGES, name, "package.json")))
14
+ .sort();
15
+
16
+ /** Packages without a `<Sdk>OpError` union over a REST/RPC protocol, and why. */
17
+ const NO_OP_ERROR: Record<string, string> = {
18
+ aws: "hand-written protocols; ParseError is part of CommonErrors in src/errors.ts",
19
+ railway: "GraphQL Query SDK; errors are typed per root by core/graphql",
20
+ };
21
+
22
+ const read = (pkg: string, file: string): string | undefined => {
23
+ const p = join(PACKAGES, pkg, file);
24
+ return existsSync(p) ? readFileSync(p, "utf8") : undefined;
25
+ };
26
+
27
+ /** Hand-written sources: `src/*.ts` without tests (generated code lives in `src/services/`). */
28
+ const handWritten = (pkg: string): string[] => {
29
+ const dir = join(PACKAGES, pkg, "src");
30
+ return readdirSync(dir)
31
+ .filter((f) => f.endsWith(".ts") && !f.endsWith(".test.ts"))
32
+ .map((f) => readFileSync(join(dir, f), "utf8"));
33
+ };
34
+
35
+ /** Every `export type <Name> = …` in the package's hand-written sources. */
36
+ const typeAliases = (pkg: string): Map<string, string> => {
37
+ const aliases = new Map<string, string>();
38
+ for (const source of handWritten(pkg)) {
39
+ for (const match of source.matchAll(/^export type (\w+)\s*=([\s\S]*?);[ \t]*$/gm)) {
40
+ aliases.set(match[1]!, match[2]!);
41
+ }
42
+ }
43
+ return aliases;
44
+ };
45
+
46
+ /** Names reachable from `root` through the package's own aliases (`DefaultErrors`, `ClientErrors`, …). */
47
+ const reachable = (aliases: Map<string, string>, root: string): Set<string> => {
48
+ const seen = new Set<string>();
49
+ const stack = [root];
50
+ while (stack.length > 0) {
51
+ const name = stack.pop()!;
52
+ if (seen.has(name)) continue;
53
+ seen.add(name);
54
+ for (const ref of aliases.get(name)?.match(/\b[A-Z]\w*\b/g) ?? []) stack.push(ref);
55
+ }
56
+ return seen;
57
+ };
58
+
59
+ describe("every SDK", () => {
60
+ test("the exemption list names real packages", () => {
61
+ for (const pkg of Object.keys(NO_OP_ERROR)) expect(sdks).toContain(pkg);
62
+ });
63
+
64
+ describe.each(sdks.filter((pkg) => !(pkg in NO_OP_ERROR)))("%s", (pkg) => {
65
+ test("declares its ParseError in the operation error union and constructs it in the protocol", () => {
66
+ const aliases = typeAliases(pkg);
67
+ const opError = [...aliases.keys()].find((name) => name.endsWith("OpError"));
68
+ expect(opError, `packages/${pkg}/src declares no \`export type <Sdk>OpError\``).toBeDefined();
69
+ const parseError = [...reachable(aliases, opError!)].find((name) =>
70
+ name.endsWith("ParseError"),
71
+ );
72
+ // Without it, `Effect.catchTag("<Sdk>ParseError")` on a strict call is a type error.
73
+ expect(parseError, `${opError} has no ParseError member`).toBeDefined();
74
+ expect(
75
+ handWritten(pkg).some((source) => source.includes(`new ${parseError}(`)),
76
+ `nothing outside src/services constructs ${parseError}`,
77
+ ).toBe(true);
78
+ expect(read(pkg, "src/errors.ts")).toMatch(new RegExp(`export class ${parseError}\\b`));
79
+ });
80
+ });
81
+
82
+ test("aws keeps ParseError in CommonErrors", () => {
83
+ const errors = read("aws", "src/errors.ts")!;
84
+ expect(errors).toMatch(/export class ParseError\b/);
85
+ expect(/export type CommonErrors =([^;]*);/.exec(errors)?.[1]).toMatch(/\bParseError\b/);
86
+ });
87
+ });
package/src/testing.ts ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Test helpers for SDK packages: a canned-response `HttpClient` and a runner
3
+ * that executes one operation under both response-validation modes.
4
+ *
5
+ * ```ts
6
+ * const { lenient, strict } = await runValidationModes(
7
+ * Pkg.getThing({ id: "a" }).pipe(Retry.none, Effect.provide(TestCredentials)),
8
+ * { body: "{}" },
9
+ * );
10
+ * expect(lenient).toMatchObject({ _tag: "Success", success: {} });
11
+ * expect(strict).toMatchObject({ _tag: "Failure" });
12
+ * ```
13
+ */
14
+ import * as Effect from "effect/Effect";
15
+ import * as HttpClient from "effect/http/HttpClient";
16
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
17
+ import * as HttpClientResponse from "effect/http/HttpClientResponse";
18
+ import * as Layer from "effect/Layer";
19
+ import type * as Result from "effect/Result";
20
+ import * as ResponseValidation from "./response-validation.ts";
21
+
22
+ export interface MockResponse {
23
+ /** Default 200. */
24
+ readonly status?: number;
25
+ /** Default `application/json`. */
26
+ readonly headers?: Record<string, string>;
27
+ readonly body: string;
28
+ }
29
+
30
+ /**
31
+ * An `HttpClient` that answers every request with `response` (or with what
32
+ * `response(request)` returns, for protocols that make more than one call).
33
+ */
34
+ export const mockHttpClient = (
35
+ response: MockResponse | ((request: HttpClientRequest.HttpClientRequest) => MockResponse),
36
+ ): Layer.Layer<HttpClient.HttpClient> =>
37
+ Layer.succeed(
38
+ HttpClient.HttpClient,
39
+ HttpClient.make((request) =>
40
+ Effect.sync(() => {
41
+ const r = typeof response === "function" ? response(request) : response;
42
+ return HttpClientResponse.fromWeb(
43
+ request,
44
+ new Response(r.body, {
45
+ status: r.status ?? 200,
46
+ headers: r.headers ?? { "content-type": "application/json" },
47
+ }),
48
+ );
49
+ }),
50
+ ),
51
+ );
52
+
53
+ /**
54
+ * Run `effect` against `mockHttpClient(response)` once in lenient mode and
55
+ * once in strict mode.
56
+ */
57
+ export const runValidationModes = <A, E>(
58
+ effect: Effect.Effect<A, E, HttpClient.HttpClient>,
59
+ response: Parameters<typeof mockHttpClient>[0],
60
+ ): Promise<{
61
+ readonly lenient: Result.Result<A, E>;
62
+ readonly strict: Result.Result<A, E>;
63
+ }> => {
64
+ const run = (mode: Layer.Layer<never>) =>
65
+ effect.pipe(Effect.provide(mockHttpClient(response)), Effect.provide(mode), Effect.result);
66
+ return Effect.runPromise(
67
+ Effect.all({
68
+ lenient: run(ResponseValidation.lenient),
69
+ strict: run(ResponseValidation.strict),
70
+ }),
71
+ );
72
+ };
package/src/trait.ts CHANGED
@@ -1,6 +1,4 @@
1
- export const annotationMetaSymbol = Symbol.for(
2
- "@distilled.cloud/core/annotation-meta",
3
- );
1
+ export const annotationMetaSymbol = Symbol.for("@distilled.cloud/core/annotation-meta");
4
2
 
5
3
  export type Annotatable = {
6
4
  annotate(annotations: any): Annotatable;
@@ -24,8 +22,7 @@ export interface Annotation {
24
22
  * annotation dictionaries accept both.
25
23
  */
26
24
  export function makeAnnotation<T>(sym: symbol | string, value: T): Annotation {
27
- const fn = <A extends Annotatable>(schema: A): A =>
28
- schema.annotate({ [sym]: value }) as A;
25
+ const fn = <A extends Annotatable>(schema: A): A => schema.annotate({ [sym]: value }) as A;
29
26
  (fn as any)[annotationMetaSymbol] = [{ symbol: sym, value }];
30
27
  (fn as any)[sym] = value;
31
28
  return fn as Annotation;
@@ -59,14 +56,7 @@ export function all(...annotations: Annotation[]): Annotation {
59
56
  //#region Generic Http traits
60
57
 
61
58
  export interface HttpTrait {
62
- readonly method:
63
- | "GET"
64
- | "POST"
65
- | "PUT"
66
- | "PATCH"
67
- | "DELETE"
68
- | "HEAD"
69
- | "OPTIONS";
59
+ readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
70
60
  /** URI template relative to the service base URL, e.g. `/accounts/{account_id}/foo`. */
71
61
  readonly uri: string;
72
62
  /** Default success status code (a `ResponseCode()` member can still read the actual code). */
@@ -106,28 +96,30 @@ export const Http = (trait: HttpTrait) => makeAnnotation(httpSymbol, trait);
106
96
 
107
97
  export const labelSymbol = Symbol.for("@distilled.cloud/core/http/label");
108
98
  /** Bind a member to a `{name}` placeholder in the operation's URI template. */
109
- export const Label = (name?: string) =>
110
- makeAnnotation(labelSymbol, name ?? true);
99
+ export const Label = (name?: string) => makeAnnotation(labelSymbol, name ?? true);
111
100
 
112
- export const responseCodeSymbol = Symbol.for(
113
- "@distilled.cloud/core/http/response-code",
114
- );
101
+ export const labelEncodingSymbol = Symbol.for("@distilled.cloud/core/http/label-encoding");
102
+ /** Preserve selected RFC 3986 pchar delimiters inside a single URI label. */
103
+ export const LabelEncoding = (options: { readonly preserve: string }) => {
104
+ if (!/^[!$&'()*+,;=:@]*$/.test(options.preserve)) {
105
+ throw new TypeError("LabelEncoding can preserve only URI path-segment delimiters");
106
+ }
107
+ return makeAnnotation(labelEncodingSymbol, options.preserve);
108
+ };
109
+
110
+ export const responseCodeSymbol = Symbol.for("@distilled.cloud/core/http/response-code");
115
111
  export const ResponseCode = () => makeAnnotation(responseCodeSymbol, true);
116
112
 
117
113
  export const headerSymbol = Symbol.for("@distilled.cloud/core/http/header");
118
- export const Header = (name?: string) =>
119
- makeAnnotation(headerSymbol, name ?? true);
114
+ export const Header = (name?: string) => makeAnnotation(headerSymbol, name ?? true);
120
115
 
121
116
  export const bodySymbol = Symbol.for("@distilled.cloud/core/http/body");
122
117
  export const Body = (name?: string) => makeAnnotation(bodySymbol, name ?? true);
123
118
 
124
119
  export const querySymbol = Symbol.for("@distilled.cloud/core/http/query");
125
- export const Query = (name?: string) =>
126
- makeAnnotation(querySymbol, name ?? true);
120
+ export const Query = (name?: string) => makeAnnotation(querySymbol, name ?? true);
127
121
 
128
- export const deepQuerySymbol = Symbol.for(
129
- "@distilled.cloud/core/http/deep-query",
130
- );
122
+ export const deepQuerySymbol = Symbol.for("@distilled.cloud/core/http/deep-query");
131
123
  /**
132
124
  * Binds a struct-valued input member to a family of DOTTED query parameters:
133
125
  * `{ account: { id, name } }` with `DeepQuery("account")` serializes as
@@ -136,8 +128,7 @@ export const deepQuerySymbol = Symbol.for(
136
128
  * Cloudflare zones list `account.id` / `account.name`) while the TS surface
137
129
  * keeps the nested-object shape (v0 parity).
138
130
  */
139
- export const DeepQuery = (name?: string) =>
140
- makeAnnotation(deepQuerySymbol, name ?? true);
131
+ export const DeepQuery = (name?: string) => makeAnnotation(deepQuerySymbol, name ?? true);
141
132
 
142
133
  export const httpBodySymbol = Symbol.for("@distilled.cloud/core/http-body");
143
134
  /**
@@ -147,9 +138,7 @@ export const httpBodySymbol = Symbol.for("@distilled.cloud/core/http-body");
147
138
  */
148
139
  export const HttpBody = () => makeAnnotation(httpBodySymbol, true);
149
140
 
150
- export const stringEncodedSymbol = Symbol.for(
151
- "@distilled.cloud/core/http/string-encoded",
152
- );
141
+ export const stringEncodedSymbol = Symbol.for("@distilled.cloud/core/http/string-encoded");
153
142
  /**
154
143
  * Marks a member the API only accepts as the STRING spelling of its value —
155
144
  * `true` travels as `"true"`, `3` as `"3"` — while the TS surface keeps the
@@ -161,9 +150,7 @@ export const stringEncodedSymbol = Symbol.for(
161
150
  */
162
151
  export const StringEncoded = () => makeAnnotation(stringEncodedSymbol, true);
163
152
 
164
- export const formDataFileSymbol = Symbol.for(
165
- "@distilled.cloud/core/form-data-file",
166
- );
153
+ export const formDataFileSymbol = Symbol.for("@distilled.cloud/core/form-data-file");
167
154
  /**
168
155
  * Marks an input member holding `File`/`Blob` parts for a multipart upload
169
156
  * (`Http({ contentType: "multipart" })`). Each file is appended to the form
@@ -174,9 +161,7 @@ export const FormDataFile = () => makeAnnotation(formDataFileSymbol, true);
174
161
 
175
162
  //#region Generic JSON traits
176
163
 
177
- export const keyDictionarySymbol = Symbol.for(
178
- "@distilled.cloud/core/key-dictionary",
179
- );
164
+ export const keyDictionarySymbol = Symbol.for("@distilled.cloud/core/key-dictionary");
180
165
  /**
181
166
  * Deep TS-name→wire-name key dictionary for members whose full structure is
182
167
  * not modeled (opaque `Document` content). The protocol renames any matching
@@ -189,10 +174,7 @@ export const keyDictionarySymbol = Symbol.for(
189
174
  * wire name used on encode; decode maps every listed spelling back to the
190
175
  * TS name.
191
176
  */
192
- export type KeyDictionaryEntries = Record<
193
- string,
194
- string | ReadonlyArray<string>
195
- >;
177
+ export type KeyDictionaryEntries = Record<string, string | ReadonlyArray<string>>;
196
178
 
197
179
  export const KeyDictionary = (dict: KeyDictionaryEntries) =>
198
180
  makeAnnotation(keyDictionarySymbol, dict);
@@ -224,32 +206,40 @@ export interface UnionDiscriminator {
224
206
  export const UnionCases = (
225
207
  cases: ReadonlyArray<ReadonlyArray<string>>,
226
208
  discriminator?: UnionDiscriminator,
227
- ) =>
228
- makeAnnotation(
229
- unionCasesSymbol,
230
- discriminator ? { cases, discriminator } : { cases },
231
- );
209
+ ) => makeAnnotation(unionCasesSymbol, discriminator ? { cases, discriminator } : { cases });
232
210
  //#endregion
233
211
 
234
212
  //#region Error matcher traits
235
213
 
236
- export const errorMatchersSymbol = Symbol.for(
237
- "@distilled.cloud/core/error-matchers",
238
- );
214
+ export const errorMatchersSymbol = Symbol.for("@distilled.cloud/core/error-matchers");
215
+
216
+ /** Exact text, or the conjunction of substring and regular-expression constraints. */
217
+ export type ErrorTextMatcher = string | { readonly includes?: string; readonly matches?: string };
239
218
 
240
219
  /**
241
- * One wire-matching rule for a typed error class. A matcher matches a wire
242
- * failure when every present field matches: `code` equals the wire error's
243
- * code, `status` equals the HTTP status, and `message` either equals the
244
- * error message (string form) or satisfies `includes` (substring) /
245
- * `matches` (regex). A matcher with no fields matches nothing.
220
+ * One wire-matching rule. All supplied constraints must match; separate
221
+ * matchers on a class are alternatives. Empty matchers match nothing.
222
+ *
223
+ * `body` maps RFC 6901 JSON Pointers to scalar constraints. For example,
224
+ * `{ "/success": false, "/result/status": "error" }`. Strings also accept
225
+ * `includes` / `matches`. Missing fields never match, including against null.
226
+ * The empty pointer addresses the entire body; array indices are supported.
227
+ * Header names are case-insensitive; their value constraints are case-sensitive.
228
+ * Each body path and header adds one specificity point, like code/status/message.
229
+ * Protocols evaluate these rules only after identifying a failed response.
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * { status: 200, body: { "/success": false, "/result/status": "error" } }
234
+ * { status: 409, headers: { "x-error-type": { includes: "Conflict" } } }
235
+ * ```
246
236
  */
247
237
  export interface ErrorMatcher {
248
238
  readonly code?: number;
249
239
  readonly status?: number;
250
- readonly message?:
251
- | string
252
- | { readonly includes?: string; readonly matches?: string };
240
+ readonly message?: ErrorTextMatcher;
241
+ readonly body?: Readonly<Record<string, ErrorTextMatcher | number | boolean | null>>;
242
+ readonly headers?: Readonly<Record<string, ErrorTextMatcher>>;
253
243
  }
254
244
 
255
245
  /**
@@ -258,17 +248,12 @@ export interface ErrorMatcher {
258
248
  * response should surface as (most specific matcher wins; ties break by
259
249
  * declaration order — see `matchTypedError` in `core/protocol-http`).
260
250
  */
261
- export const applyErrorMatchers = <C>(
262
- cls: C,
263
- matchers: ReadonlyArray<ErrorMatcher>,
264
- ): C => {
251
+ export const applyErrorMatchers = <C>(cls: C, matchers: ReadonlyArray<ErrorMatcher>): C => {
265
252
  (cls as any)[errorMatchersSymbol] = matchers;
266
253
  return cls;
267
254
  };
268
255
 
269
256
  /** Read the matchers stamped on an error class, if any. */
270
- export const getErrorMatchers = (
271
- cls: unknown,
272
- ): ReadonlyArray<ErrorMatcher> | undefined =>
257
+ export const getErrorMatchers = (cls: unknown): ReadonlyArray<ErrorMatcher> | undefined =>
273
258
  (cls as any)?.[errorMatchersSymbol];
274
259
  //#endregion
@@ -0,0 +1,251 @@
1
+ import assert from "node:assert/strict";
2
+ import * as Effect from "effect/Effect";
3
+ import { describe, it } from "vitest";
4
+ import fixtures from "./fixtures/xml/upstream-validator.json" with { type: "json" };
5
+ import { escapeXml, parseXml, parseXmlSync, XmlParseError } from "./xml.ts";
6
+
7
+ function parse(xml: string) {
8
+ // Compare the wire values independently of the null prototypes used for safety.
9
+ return JSON.parse(JSON.stringify(parseXmlSync(xml)));
10
+ }
11
+
12
+ describe("upstream fast-xml-parser validation corpus", () => {
13
+ for (const [index, fixture] of fixtures.entries()) {
14
+ it(`${index}: ${fixture.name}`, () => {
15
+ if (fixture.parserValid ?? fixture.valid) {
16
+ assert.doesNotThrow(() => parseXmlSync(fixture.xml));
17
+ } else {
18
+ assert.throws(() => parseXmlSync(fixture.xml), XmlParseError);
19
+ }
20
+ });
21
+ }
22
+ });
23
+
24
+ describe("XML object format", () => {
25
+ it("keeps primitives as strings and groups repeated children", () => {
26
+ assert.deepEqual(parse("<R><x>001</x><x>false</x><x>1e3</x><empty/><empty></empty></R>"), {
27
+ R: { x: ["001", "false", "1e3"], empty: ["", ""] },
28
+ });
29
+ });
30
+
31
+ it("preserves namespace names, attributes, and text with attributes", () => {
32
+ assert.deepEqual(
33
+ parse('<ns:R xmlns:ns="urn:r"><ns:x ns:id="01">value</ns:x><empty a=""/></ns:R>'),
34
+ {
35
+ "ns:R": {
36
+ "@_xmlns:ns": "urn:r",
37
+ "ns:x": { "@_ns:id": "01", "#text": "value" },
38
+ empty: { "@_a": "" },
39
+ },
40
+ },
41
+ );
42
+ });
43
+
44
+ it("preserves string whitespace, including attribute and CDATA values", () => {
45
+ assert.deepEqual(
46
+ parse(
47
+ '<R><Key> key </Key><blank> \t </blank><x a=" b "> text </x><c><![CDATA[ c ]]></c></R>',
48
+ ),
49
+ {
50
+ R: {
51
+ Key: " key ",
52
+ blank: " \t ",
53
+ x: { "@_a": " b ", "#text": " text " },
54
+ c: " c ",
55
+ },
56
+ },
57
+ );
58
+ });
59
+
60
+ it("discards layout-only container text but preserves mixed content", () => {
61
+ assert.deepEqual(parse("<R>\n <x/>\n <y/>\n</R>"), {
62
+ R: { x: "", y: "" },
63
+ });
64
+ assert.deepEqual(parse("<R>Hello <b>world</b> !</R>"), {
65
+ R: { b: "world", "#text": "Hello !" },
66
+ });
67
+ assert.deepEqual(parse("<R><![CDATA[ ]]><b/></R>"), {
68
+ R: { b: "", "#text": " " },
69
+ });
70
+ });
71
+
72
+ it("decodes predefined and numeric entities exactly once", () => {
73
+ assert.deepEqual(parse('<R a="&quot;&apos;&#9;">&amp;&lt;&gt;&#65;&#x1F600;&amp;lt;</R>'), {
74
+ R: { "@_a": "\"'\t", "#text": "&<>A😀&lt;" },
75
+ });
76
+ });
77
+
78
+ it("normalizes literal line endings and attribute whitespace, not character references", () => {
79
+ assert.deepEqual(parse('<R a="x\r\ny\tz\r&#13;&#10;&#9;">a\r\nb\rc&#13;</R>'), {
80
+ R: { "@_a": "x y z \r\n\t", "#text": "a\nb\nc\r" },
81
+ });
82
+ });
83
+
84
+ it("joins CDATA and text without decoding CDATA entities", () => {
85
+ assert.deepEqual(parse("<R>a<![CDATA[<b>&amp;]]><![CDATA[c]]>d&amp;</R>"), {
86
+ R: "a<b>&amp;cd&",
87
+ });
88
+ assert.deepEqual(parse("<R><![CDATA[]]></R>"), { R: "" });
89
+ });
90
+
91
+ it("ignores declarations, comments and processing instructions", () => {
92
+ assert.deepEqual(
93
+ parse(
94
+ '\uFEFF<?xml version="1.0" encoding="UTF-8" standalone="yes"?><!--before--><?before a?><R>a<!--ignored--><?in x?>b</R><?after?><!--after-->',
95
+ ),
96
+ { R: "ab" },
97
+ );
98
+ });
99
+
100
+ it("supports XML Unicode names", () => {
101
+ assert.deepEqual(parse('<根 é="oui"><𐀀>😀</𐀀><á/></根>'), {
102
+ 根: { "@_é": "oui", 𐀀: "😀", á: "" },
103
+ });
104
+ });
105
+
106
+ it("accepts empty HTTP bodies", () => {
107
+ for (const xml of ["", " \r\n\t", "\uFEFF"]) assert.deepEqual(parse(xml), {});
108
+ });
109
+
110
+ it("stores prototype-related names as own data properties", () => {
111
+ const result = parseXmlSync(
112
+ "<__proto__><constructor>one</constructor><constructor>two</constructor><__proto__>safe</__proto__><toString/></__proto__>",
113
+ );
114
+ const root = result.__proto__;
115
+ assert.equal(Object.getPrototypeOf(result), null);
116
+ assert.equal(Object.getPrototypeOf(root), null);
117
+ assert.deepEqual(
118
+ JSON.parse(JSON.stringify(root)),
119
+ JSON.parse('{"constructor":["one","two"],"__proto__":"safe","toString":""}'),
120
+ );
121
+ assert.equal(Object.hasOwn(Object.prototype, "safe"), false);
122
+ });
123
+
124
+ it("round trips escaped strings", () => {
125
+ for (const text of [' <tag a="x">&\'😀 ', "", "false", "001", "&#13;", "\t\n"]) {
126
+ assert.deepEqual(parse(`<R>${escapeXml(text)}</R>`), { R: text });
127
+ }
128
+ });
129
+
130
+ it("handles large lists without recursion", () => {
131
+ const result = parse(`<R>${'<item a="1">value</item>'.repeat(10_000)}</R>`);
132
+ assert.equal(result.R.item.length, 10_000);
133
+ assert.deepEqual(result.R.item[9_999], { "@_a": "1", "#text": "value" });
134
+ });
135
+ });
136
+
137
+ describe("malformed and unsupported XML", () => {
138
+ const invalid = [
139
+ '<R a="1"a="2"/>',
140
+ '<R a="<"/>',
141
+ '<R a="&bad;"/>',
142
+ "<R a=1/>",
143
+ '<R a="1" a="2"/>',
144
+ "<R/ >",
145
+ "< R/>",
146
+ "<R></ R>",
147
+ "<R></R x>",
148
+ "<R>]]></R>",
149
+ "<R>&</R>",
150
+ "<R>&amp</R>",
151
+ "<R>&nope;</R>",
152
+ "<R>&#0;</R>",
153
+ "<R>&#xD800;</R>",
154
+ "<R>&#x110000;</R>",
155
+ "<R>&#xFFFE;</R>",
156
+ "<R>&#-1;</R>",
157
+ "<R>&#X41;</R>",
158
+ "<R>&#x;</R>",
159
+ "<R>&#;</R>",
160
+ "<R>\u0000</R>",
161
+ "<R>\u000B</R>",
162
+ "<R>\uD800</R>",
163
+ "<R>\uDC00</R>",
164
+ "<R>\uFFFE</R>",
165
+ "<R>\uFFFF</R>",
166
+ "<R><!--a--b--></R>",
167
+ "<R><!--a---></R>",
168
+ "<R><!--",
169
+ "<R><![CDATA[",
170
+ "<![CDATA[x]]><R/>",
171
+ "<R/><![CDATA[x]]>",
172
+ "<R><?pi",
173
+ "<R><?1bad?></R>",
174
+ "<R><?pi!?></R>",
175
+ '<?XML version="1.0"?><R/>',
176
+ "<?xml?><R/>",
177
+ '<?xml version="1.1"?><R/>',
178
+ '<?xml encoding="UTF-8"?><R/>',
179
+ '<?xml version="1.0" junk="x"?><R/>',
180
+ '<R><?xml version="1.0"?></R>',
181
+ '<!--x--><?xml version="1.0"?><R/>',
182
+ '<?xml version="1.0"?>',
183
+ "<!--only-->",
184
+ "<!DOCTYPE R><R/>",
185
+ '<!DOCTYPE R SYSTEM "file:///etc/passwd"><R/>',
186
+ '<!DOCTYPE R [<!ENTITY a "&a;">]><R>&a;</R>',
187
+ "<R/><R/>",
188
+ "before<R/>",
189
+ "<R/>after",
190
+ "<R><x></R>",
191
+ "<R>",
192
+ "<",
193
+ '<R a="',
194
+ "<R a",
195
+ "<R a=",
196
+ "<R ",
197
+ "</R>",
198
+ "<1bad/>",
199
+ '<R\u00A0a="x"/>',
200
+ ];
201
+ for (const xml of invalid) {
202
+ it(`rejects ${JSON.stringify(xml)}`, () => {
203
+ assert.throws(
204
+ () => parseXmlSync(xml),
205
+ (error) => {
206
+ assert.ok(error instanceof XmlParseError);
207
+ assert.ok(error.offset >= 0 && error.offset <= xml.length);
208
+ return true;
209
+ },
210
+ );
211
+ });
212
+ }
213
+
214
+ it("reports original input offsets and CRLF-aware line numbers", () => {
215
+ const xml = "<R>\r\n&bad;</R>";
216
+ assert.throws(
217
+ () => parseXmlSync(xml),
218
+ (error) => {
219
+ assert.ok(error instanceof XmlParseError);
220
+ assert.equal(error.offset, 5);
221
+ assert.equal(error.line, 2);
222
+ assert.equal(error.column, 1);
223
+ return true;
224
+ },
225
+ );
226
+ });
227
+
228
+ it("enforces depth and input length limits", () => {
229
+ assert.doesNotThrow(() => parseXmlSync("<a><b/></a>", { maxDepth: 2 }));
230
+ assert.throws(() => parseXmlSync("<a><b/></a>", { maxDepth: 1 }), XmlParseError);
231
+ assert.doesNotThrow(() => parseXmlSync("<a/>", { maxLength: 4 }));
232
+ assert.throws(() => parseXmlSync("<a/>", { maxLength: 3 }), XmlParseError);
233
+ assert.throws(() => parseXmlSync("<a/>", { maxDepth: NaN }), XmlParseError);
234
+ assert.throws(() => parseXmlSync("<a/>", { maxLength: -1 }), XmlParseError);
235
+ const nested = "<a>".repeat(2_000) + "</a>".repeat(2_000);
236
+ assert.throws(() => parseXmlSync(nested), XmlParseError);
237
+ assert.doesNotThrow(() => parseXmlSync(nested, { maxDepth: 2_000 }));
238
+ });
239
+
240
+ it("exposes parser failures through Effect's typed channel", () => {
241
+ const result = Effect.runSync(Effect.flip(parseXml("<R>")));
242
+ assert.ok(result instanceof XmlParseError);
243
+ assert.match(result.message, /Unclosed element/);
244
+ });
245
+
246
+ it("can execute the same lazy Effect repeatedly", () => {
247
+ const effect = parseXml("<R>ok</R>");
248
+ assert.equal(Effect.runSync(effect).R, "ok");
249
+ assert.equal(Effect.runSync(effect).R, "ok");
250
+ });
251
+ });