@distilled.cloud/core 1.0.0-rc.2 → 1.0.0-rc.21

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 (321) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -0
  3. package/lib/_bundle/aws.js +2 -0
  4. package/lib/_bundle/aws.js.map +1 -0
  5. package/lib/_bundle/base.js +5 -0
  6. package/lib/_bundle/base.js.map +1 -0
  7. package/lib/_bundle/graphql.js +3 -0
  8. package/lib/_bundle/graphql.js.map +1 -0
  9. package/lib/_bundle/grpc.js +3 -0
  10. package/lib/_bundle/grpc.js.map +1 -0
  11. package/lib/_bundle/rest.js +2 -0
  12. package/lib/_bundle/rest.js.map +1 -0
  13. package/lib/_bundle/xml.js +4 -0
  14. package/lib/_bundle/xml.js.map +1 -0
  15. package/lib/annotations.d.ts +17 -0
  16. package/lib/annotations.d.ts.map +1 -0
  17. package/lib/annotations.js +2 -0
  18. package/lib/annotations.js.map +1 -0
  19. package/lib/api.d.ts +220 -51
  20. package/lib/api.d.ts.map +1 -1
  21. package/lib/api.js +1 -178
  22. package/lib/category.d.ts +19 -16
  23. package/lib/category.d.ts.map +1 -1
  24. package/lib/category.js +1 -280
  25. package/lib/chunks.d.ts +3 -0
  26. package/lib/chunks.d.ts.map +1 -0
  27. package/lib/chunks.js +1 -0
  28. package/lib/config.d.ts +81 -0
  29. package/lib/config.d.ts.map +1 -0
  30. package/lib/config.js +1 -0
  31. package/lib/crypto.d.ts +76 -0
  32. package/lib/crypto.d.ts.map +1 -0
  33. package/lib/crypto.js +1 -0
  34. package/lib/error-category.d.ts +1 -1
  35. package/lib/error-category.d.ts.map +1 -1
  36. package/lib/error-category.js +1 -46
  37. package/lib/errors.d.ts +99 -74
  38. package/lib/errors.d.ts.map +1 -1
  39. package/lib/errors.js +1 -186
  40. package/lib/graphql.d.ts +420 -0
  41. package/lib/graphql.d.ts.map +1 -0
  42. package/lib/graphql.js +1 -0
  43. package/lib/graphql.types.d.ts +11 -0
  44. package/lib/graphql.types.d.ts.map +1 -0
  45. package/lib/graphql.types.js +1 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  47. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  48. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  49. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  51. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  53. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  54. package/lib/grpc-transport-node-http2.d.ts +19 -0
  55. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  56. package/lib/grpc-transport-node-http2.js +2 -0
  57. package/lib/grpc-transport-node-http2.js.map +1 -0
  58. package/lib/grpc-transport.d.ts +111 -0
  59. package/lib/grpc-transport.d.ts.map +1 -0
  60. package/lib/grpc-transport.js +1 -0
  61. package/lib/hpack.d.ts +34 -0
  62. package/lib/hpack.d.ts.map +1 -0
  63. package/lib/hpack.js +2 -0
  64. package/lib/hpack.js.map +1 -0
  65. package/lib/index.d.ts +32 -0
  66. package/lib/index.d.ts.map +1 -0
  67. package/lib/index.js +17 -0
  68. package/lib/max-message-bytes.d.ts +42 -0
  69. package/lib/max-message-bytes.d.ts.map +1 -0
  70. package/lib/max-message-bytes.js +2 -0
  71. package/lib/max-message-bytes.js.map +1 -0
  72. package/lib/ndjson.d.ts +3 -0
  73. package/lib/ndjson.d.ts.map +1 -0
  74. package/lib/ndjson.js +2 -0
  75. package/lib/ndjson.js.map +1 -0
  76. package/lib/pagination.d.ts +105 -25
  77. package/lib/pagination.d.ts.map +1 -1
  78. package/lib/pagination.js +1 -182
  79. package/lib/plain-values.d.ts +21 -0
  80. package/lib/plain-values.d.ts.map +1 -0
  81. package/lib/plain-values.js +2 -0
  82. package/lib/plain-values.js.map +1 -0
  83. package/lib/protobuf.d.ts +85 -0
  84. package/lib/protobuf.d.ts.map +1 -0
  85. package/lib/protobuf.js +1 -0
  86. package/lib/protocol-grpc.d.ts +123 -0
  87. package/lib/protocol-grpc.d.ts.map +1 -0
  88. package/lib/protocol-grpc.js +1 -0
  89. package/lib/protocol-http.d.ts +206 -25
  90. package/lib/protocol-http.d.ts.map +1 -1
  91. package/lib/protocol-http.js +1 -554
  92. package/lib/protocol-rest.d.ts +258 -64
  93. package/lib/protocol-rest.d.ts.map +1 -1
  94. package/lib/protocol-rest.js +1 -242
  95. package/lib/protocol.d.ts +113 -0
  96. package/lib/protocol.d.ts.map +1 -0
  97. package/lib/protocol.js +0 -0
  98. package/lib/query.d.ts +29 -0
  99. package/lib/query.d.ts.map +1 -0
  100. package/lib/query.js +1 -0
  101. package/lib/response-validation-strict.d.ts +48 -0
  102. package/lib/response-validation-strict.d.ts.map +1 -0
  103. package/lib/response-validation-strict.js +1 -0
  104. package/lib/response-validation.d.ts +86 -0
  105. package/lib/response-validation.d.ts.map +1 -0
  106. package/lib/response-validation.js +1 -0
  107. package/lib/retry-after.d.ts +4 -4
  108. package/lib/retry-after.d.ts.map +1 -1
  109. package/lib/retry-after.js +1 -112
  110. package/lib/retry-state.d.ts +26 -0
  111. package/lib/retry-state.d.ts.map +1 -0
  112. package/lib/retry-state.js +2 -0
  113. package/lib/retry-state.js.map +1 -0
  114. package/lib/retry.d.ts +141 -42
  115. package/lib/retry.d.ts.map +1 -1
  116. package/lib/retry.js +1 -210
  117. package/lib/schema-lite-impl.d.ts +179 -0
  118. package/lib/schema-lite-impl.d.ts.map +1 -0
  119. package/lib/schema-lite-impl.js +1 -0
  120. package/lib/schema-lite-typed.d.ts +41 -0
  121. package/lib/schema-lite-typed.d.ts.map +1 -0
  122. package/lib/schema-lite-typed.js +1 -0
  123. package/lib/schema-lite.d.ts +41 -0
  124. package/lib/schema-lite.d.ts.map +1 -0
  125. package/lib/schema-lite.js +1 -0
  126. package/lib/schema.d.ts +21 -7
  127. package/lib/schema.d.ts.map +1 -1
  128. package/lib/schema.js +1 -48
  129. package/lib/sdk-error.d.ts +31 -0
  130. package/lib/sdk-error.d.ts.map +1 -0
  131. package/lib/sdk-error.js +1 -0
  132. package/lib/send.d.ts +37 -0
  133. package/lib/send.d.ts.map +1 -0
  134. package/lib/send.js +2 -0
  135. package/lib/send.js.map +1 -0
  136. package/lib/sensitive.d.ts +28 -0
  137. package/lib/sensitive.d.ts.map +1 -0
  138. package/lib/sensitive.js +2 -0
  139. package/lib/sensitive.js.map +1 -0
  140. package/lib/telemetry-debug.d.ts +6 -0
  141. package/lib/telemetry-debug.d.ts.map +1 -0
  142. package/lib/telemetry-debug.js +2 -0
  143. package/lib/telemetry-debug.js.map +1 -0
  144. package/lib/telemetry-hooks.d.ts +32 -0
  145. package/lib/telemetry-hooks.d.ts.map +1 -0
  146. package/lib/telemetry-hooks.js +2 -0
  147. package/lib/telemetry-hooks.js.map +1 -0
  148. package/lib/telemetry-host-rules.d.ts +23 -0
  149. package/lib/telemetry-host-rules.d.ts.map +1 -0
  150. package/lib/telemetry-host-rules.js +2 -0
  151. package/lib/telemetry-host-rules.js.map +1 -0
  152. package/lib/telemetry-lambda-context.d.ts +17 -0
  153. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  154. package/lib/telemetry-lambda-context.js +2 -0
  155. package/lib/telemetry-lambda-context.js.map +1 -0
  156. package/lib/telemetry-message-context.d.ts +52 -0
  157. package/lib/telemetry-message-context.d.ts.map +1 -0
  158. package/lib/telemetry-message-context.js +2 -0
  159. package/lib/telemetry-message-context.js.map +1 -0
  160. package/lib/telemetry-metrics.d.ts +6 -0
  161. package/lib/telemetry-metrics.d.ts.map +1 -0
  162. package/lib/telemetry-metrics.js +2 -0
  163. package/lib/telemetry-metrics.js.map +1 -0
  164. package/lib/telemetry-name-template.d.ts +13 -0
  165. package/lib/telemetry-name-template.d.ts.map +1 -0
  166. package/lib/telemetry-name-template.js +2 -0
  167. package/lib/telemetry-name-template.js.map +1 -0
  168. package/lib/telemetry-stream.d.ts +11 -0
  169. package/lib/telemetry-stream.d.ts.map +1 -0
  170. package/lib/telemetry-stream.js +2 -0
  171. package/lib/telemetry-stream.js.map +1 -0
  172. package/lib/telemetry-xray.d.ts +28 -0
  173. package/lib/telemetry-xray.d.ts.map +1 -0
  174. package/lib/telemetry-xray.js +2 -0
  175. package/lib/telemetry-xray.js.map +1 -0
  176. package/lib/telemetry.d.ts +317 -0
  177. package/lib/telemetry.d.ts.map +1 -0
  178. package/lib/telemetry.js +3 -0
  179. package/lib/telemetry.js.map +1 -0
  180. package/lib/token-cache.d.ts +31 -0
  181. package/lib/token-cache.d.ts.map +1 -0
  182. package/lib/token-cache.js +2 -0
  183. package/lib/token-cache.js.map +1 -0
  184. package/lib/trait.d.ts +94 -20
  185. package/lib/trait.d.ts.map +1 -1
  186. package/lib/trait.js +1 -107
  187. package/lib/unknown-error.d.ts +18 -0
  188. package/lib/unknown-error.d.ts.map +1 -0
  189. package/lib/unknown-error.js +1 -0
  190. package/lib/xml.d.ts +44 -0
  191. package/lib/xml.d.ts.map +1 -0
  192. package/lib/xml.js +1 -0
  193. package/package.json +13 -13
  194. package/src/annotations.ts +53 -0
  195. package/src/api.ts +1597 -234
  196. package/src/category.ts +97 -134
  197. package/src/chunks.ts +30 -0
  198. package/src/config.ts +261 -0
  199. package/src/crypto.ts +202 -0
  200. package/src/error-category.ts +16 -29
  201. package/src/errors.ts +99 -77
  202. package/src/graphql.ts +1817 -0
  203. package/src/graphql.types.ts +120 -0
  204. package/src/grpc-transport-cloudflare-http2.ts +569 -0
  205. package/src/grpc-transport-cloudflare-sockets.ts +368 -0
  206. package/src/grpc-transport-node-http2.ts +307 -0
  207. package/src/grpc-transport.ts +287 -0
  208. package/src/hpack.ts +331 -0
  209. package/src/index.ts +31 -0
  210. package/src/max-message-bytes.ts +58 -0
  211. package/src/ndjson.ts +55 -0
  212. package/src/pagination.ts +379 -94
  213. package/src/plain-values.ts +70 -0
  214. package/src/protobuf.ts +1367 -0
  215. package/src/protocol-grpc.ts +811 -0
  216. package/src/protocol-http.ts +1045 -371
  217. package/src/protocol-rest.ts +908 -255
  218. package/src/protocol.ts +150 -0
  219. package/src/query.ts +39 -0
  220. package/src/response-validation-strict.ts +333 -0
  221. package/src/response-validation.ts +161 -0
  222. package/src/retry-after.ts +8 -14
  223. package/src/retry-state.ts +105 -0
  224. package/src/retry.ts +260 -145
  225. package/src/schema-lite-impl.ts +621 -0
  226. package/src/schema-lite-typed.ts +44 -0
  227. package/src/schema-lite.ts +45 -0
  228. package/src/schema.ts +259 -15
  229. package/src/sdk-error.ts +37 -0
  230. package/src/send.ts +156 -0
  231. package/src/sensitive.ts +188 -0
  232. package/src/telemetry-debug.ts +179 -0
  233. package/src/telemetry-hooks.ts +33 -0
  234. package/src/telemetry-host-rules.ts +39 -0
  235. package/src/telemetry-lambda-context.ts +46 -0
  236. package/src/telemetry-message-context.ts +170 -0
  237. package/src/telemetry-metrics.ts +69 -0
  238. package/src/telemetry-name-template.ts +26 -0
  239. package/src/telemetry-stream.ts +100 -0
  240. package/src/telemetry-xray.ts +66 -0
  241. package/src/telemetry.ts +800 -0
  242. package/src/token-cache.ts +117 -0
  243. package/src/trait.ts +139 -67
  244. package/src/unknown-error.ts +38 -0
  245. package/src/xml.ts +346 -0
  246. package/lib/api.js.map +0 -1
  247. package/lib/category.js.map +0 -1
  248. package/lib/codegen/cli.d.ts +0 -29
  249. package/lib/codegen/cli.d.ts.map +0 -1
  250. package/lib/codegen/cli.js +0 -165
  251. package/lib/codegen/cli.js.map +0 -1
  252. package/lib/codegen/emit.d.ts +0 -129
  253. package/lib/codegen/emit.d.ts.map +0 -1
  254. package/lib/codegen/emit.js +0 -105
  255. package/lib/codegen/emit.js.map +0 -1
  256. package/lib/codegen/format.d.ts +0 -23
  257. package/lib/codegen/format.d.ts.map +0 -1
  258. package/lib/codegen/format.js +0 -28
  259. package/lib/codegen/format.js.map +0 -1
  260. package/lib/codegen/generator.d.ts +0 -334
  261. package/lib/codegen/generator.d.ts.map +0 -1
  262. package/lib/codegen/generator.js +0 -691
  263. package/lib/codegen/generator.js.map +0 -1
  264. package/lib/codegen/graph.d.ts +0 -36
  265. package/lib/codegen/graph.d.ts.map +0 -1
  266. package/lib/codegen/graph.js +0 -136
  267. package/lib/codegen/graph.js.map +0 -1
  268. package/lib/codegen/members.d.ts +0 -25
  269. package/lib/codegen/members.d.ts.map +0 -1
  270. package/lib/codegen/members.js +0 -55
  271. package/lib/codegen/members.js.map +0 -1
  272. package/lib/codegen/naming.d.ts +0 -29
  273. package/lib/codegen/naming.d.ts.map +0 -1
  274. package/lib/codegen/naming.js +0 -74
  275. package/lib/codegen/naming.js.map +0 -1
  276. package/lib/codegen/openapi-cli.d.ts +0 -38
  277. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  278. package/lib/codegen/openapi-cli.js +0 -107
  279. package/lib/codegen/openapi-cli.js.map +0 -1
  280. package/lib/codegen/openapi.d.ts +0 -115
  281. package/lib/codegen/openapi.d.ts.map +0 -1
  282. package/lib/codegen/openapi.js +0 -1220
  283. package/lib/codegen/openapi.js.map +0 -1
  284. package/lib/codegen/operations.d.ts +0 -24
  285. package/lib/codegen/operations.d.ts.map +0 -1
  286. package/lib/codegen/operations.js +0 -56
  287. package/lib/codegen/operations.js.map +0 -1
  288. package/lib/codegen/pagination.d.ts +0 -39
  289. package/lib/codegen/pagination.d.ts.map +0 -1
  290. package/lib/codegen/pagination.js +0 -33
  291. package/lib/codegen/pagination.js.map +0 -1
  292. package/lib/codegen/prelude.d.ts +0 -15
  293. package/lib/codegen/prelude.d.ts.map +0 -1
  294. package/lib/codegen/prelude.js +0 -60
  295. package/lib/codegen/prelude.js.map +0 -1
  296. package/lib/error-category.js.map +0 -1
  297. package/lib/errors.js.map +0 -1
  298. package/lib/json-patch.d.ts +0 -44
  299. package/lib/json-patch.d.ts.map +0 -1
  300. package/lib/json-patch.js +0 -174
  301. package/lib/json-patch.js.map +0 -1
  302. package/lib/pagination.js.map +0 -1
  303. package/lib/protocol-http.js.map +0 -1
  304. package/lib/protocol-rest.js.map +0 -1
  305. package/lib/retry-after.js.map +0 -1
  306. package/lib/retry.js.map +0 -1
  307. package/lib/schema.js.map +0 -1
  308. package/lib/trait.js.map +0 -1
  309. package/src/codegen/cli.ts +0 -268
  310. package/src/codegen/emit.ts +0 -207
  311. package/src/codegen/format.ts +0 -47
  312. package/src/codegen/generator.ts +0 -1153
  313. package/src/codegen/graph.ts +0 -151
  314. package/src/codegen/members.ts +0 -71
  315. package/src/codegen/naming.ts +0 -86
  316. package/src/codegen/openapi-cli.ts +0 -166
  317. package/src/codegen/openapi.ts +0 -1450
  318. package/src/codegen/operations.ts +0 -76
  319. package/src/codegen/pagination.ts +0 -71
  320. package/src/codegen/prelude.ts +0 -70
  321. package/src/json-patch.ts +0 -222
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Secrets in values, logs and error messages: one rule for every SDK.
3
+ *
4
+ * A schema holds a secret when a value it reaches is marked sensitive
5
+ * ({@link sensitiveValueSymbol}: `T.SensitiveValue` in the REST SDKs, the
6
+ * `Sensitive*` schemas in AWS). An operation's input and its output are
7
+ * judged independently, each by its own schema:
8
+ *
9
+ * - its plain form (a serialized request, a response body, the value a
10
+ * parse failure quotes) is {@link REDACTED} whole: {@link redactPlain};
11
+ * - its parsed form shows only the sensitive values as `Redacted`:
12
+ * {@link redactParsed} for logs, {@link wrapSensitive} for decoded output.
13
+ *
14
+ * Imports only `effect/Redacted` and the AST helpers, so a protocol can use
15
+ * it without loading the REST protocol.
16
+ */
17
+ import * as Redacted from "effect/Redacted";
18
+ import type * as AST from "effect/SchemaAST";
19
+ import { getAnn, getProps, resolveNode } from "./annotations.ts";
20
+ import { isOpaqueValue } from "./plain-values.ts";
21
+
22
+ export const sensitiveValueSymbol = /*@__PURE__*/ Symbol.for(
23
+ "@distilled.cloud/core/sensitive-value",
24
+ );
25
+
26
+ /** What the plain form of a value that can hold a secret is shown as. */
27
+ export const REDACTED = "[REDACTED]";
28
+
29
+ /** Whether `ast` is marked sensitive (through optional, Suspend and encoding wrappers). */
30
+ export const isSensitive = (ast: AST.AST): boolean =>
31
+ getAnn(ast, sensitiveValueSymbol) !== undefined;
32
+
33
+ const holds = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
34
+
35
+ /**
36
+ * Whether a value of the type `ast` can hold a sensitive value, at any depth:
37
+ * the type itself, members, map values, list elements and union arms.
38
+ */
39
+ export const holdsSensitive = (ast: AST.AST): boolean => {
40
+ const cached = holds.get(ast);
41
+ if (cached !== undefined) return cached;
42
+ const seen = new Set<AST.AST>();
43
+ const visit = (n: AST.AST): boolean => {
44
+ if (isSensitive(n)) return true;
45
+ const node = resolveNode(n);
46
+ if (seen.has(node)) return false;
47
+ seen.add(node);
48
+ switch (node._tag) {
49
+ case "Union":
50
+ return node.types.some(visit);
51
+ case "Arrays":
52
+ return [...(node.elements ?? []), ...(node.rest ?? [])].some(visit);
53
+ case "Objects":
54
+ return [...(node.propertySignatures ?? []), ...(node.indexSignatures ?? [])].some((m) =>
55
+ visit(m.type),
56
+ );
57
+ default:
58
+ return false;
59
+ }
60
+ };
61
+ const result = visit(ast);
62
+ holds.set(ast, result);
63
+ return result;
64
+ };
65
+
66
+ /** `plain`, the plain form of a value of the type `ast`: {@link REDACTED} when it can hold a secret. */
67
+ export const redactPlain = <A>(ast: AST.AST, plain: A): A | typeof REDACTED =>
68
+ holdsSensitive(ast) ? REDACTED : plain;
69
+
70
+ /**
71
+ * `value`, a parsed value of the type `ast`, as a log shows it: every
72
+ * sensitive value `Redacted` whole, whatever its type, and the rest as is.
73
+ */
74
+ export const redactParsed = (ast: AST.AST, value: unknown): unknown =>
75
+ holdsSensitive(ast) ? wrap(ast, value, true) : value;
76
+
77
+ /**
78
+ * Walk a decoded (TS-named) value alongside its schema AST, wrapping values
79
+ * marked sensitive (members, map values, list elements) in `Redacted`: a
80
+ * string, or any non-null value of an untyped (`S.Unknown`) schema. A typed
81
+ * struct is walked so its own sensitive members are wrapped and its type
82
+ * stays accurate. Keys the schema doesn't model pass through. A union
83
+ * applies every arm in turn; a map arm skips keys a sibling arm names.
84
+ */
85
+ export const wrapSensitive = (
86
+ ast: AST.AST,
87
+ value: unknown,
88
+ siblingNames?: ReadonlySet<string>,
89
+ ): unknown => wrap(ast, value, false, siblingNames);
90
+
91
+ /** Whether `wrap` wraps `v`, a value of the sensitive type `type`. */
92
+ const isSecretValue = (type: AST.AST, v: unknown, whole: boolean): boolean =>
93
+ whole
94
+ ? v !== null && v !== undefined
95
+ : typeof v === "string" || (v !== null && resolveNode(type)._tag === "Unknown");
96
+
97
+ /** The member names of a union's object arms, once per union. */
98
+ const armNames = /*@__PURE__*/ new WeakMap<AST.AST, ReadonlySet<string>>();
99
+ /** A struct's members by name, once per struct. */
100
+ const membersByName = /*@__PURE__*/ new WeakMap<
101
+ AST.AST,
102
+ ReadonlyMap<string, AST.PropertySignature>
103
+ >();
104
+
105
+ const byNameOf = (
106
+ node: AST.AST,
107
+ props: ReadonlyArray<AST.PropertySignature>,
108
+ ): ReadonlyMap<string, AST.PropertySignature> => {
109
+ const byName = new Map(props.map((p) => [String(p.name), p]));
110
+ membersByName.set(node, byName);
111
+ return byName;
112
+ };
113
+
114
+ /**
115
+ * `wrap`, except that a value whose type holds no sensitive value is
116
+ * returned as is: walking it would only copy it.
117
+ */
118
+ const wrapHolding = (
119
+ ast: AST.AST,
120
+ value: unknown,
121
+ whole: boolean,
122
+ siblingNames?: ReadonlySet<string>,
123
+ ): unknown => (holdsSensitive(ast) ? wrap(ast, value, whole, siblingNames) : value);
124
+
125
+ const wrap = (
126
+ ast: AST.AST,
127
+ value: unknown,
128
+ whole: boolean,
129
+ siblingNames?: ReadonlySet<string>,
130
+ ): unknown => {
131
+ if (Redacted.isRedacted(value)) return value;
132
+ // The value's own type is sensitive: a response whose whole body is the
133
+ // secret (a bare-payload root).
134
+ if (isSensitive(ast) && isSecretValue(ast, value, whole)) return Redacted.make(value);
135
+ if (value === null || typeof value !== "object" || isOpaqueValue(value)) {
136
+ return value;
137
+ }
138
+ const node = resolveNode(ast);
139
+ if (node._tag === "Union") {
140
+ // Redact every possible sensitive member, including in partial responses.
141
+ let named = armNames.get(node);
142
+ if (named === undefined) {
143
+ named = new Set(
144
+ node.types.flatMap((arm) => {
145
+ const armNode = resolveNode(arm);
146
+ return armNode._tag === "Objects" ? getProps(armNode).map((p) => String(p.name)) : [];
147
+ }),
148
+ );
149
+ armNames.set(node, named);
150
+ }
151
+ return node.types.reduce<unknown>(
152
+ (redacted, arm) => wrapHolding(arm, redacted, whole, named),
153
+ value,
154
+ );
155
+ }
156
+ if (node._tag === "Arrays") {
157
+ if (!Array.isArray(value)) return value;
158
+ const elem = node.rest?.[0];
159
+ if (!elem) return value;
160
+ const sensitive = isSensitive(elem);
161
+ return value.map((v) =>
162
+ sensitive && isSecretValue(elem, v, whole) && !Redacted.isRedacted(v)
163
+ ? Redacted.make(v)
164
+ : wrapHolding(elem, v, whole),
165
+ );
166
+ }
167
+ if (node._tag === "Objects" && !Array.isArray(value)) {
168
+ const props = getProps(node);
169
+ const mapValue = node.indexSignatures?.[0]?.type;
170
+ if (props.length === 0 && mapValue === undefined) return value;
171
+ const byName = membersByName.get(node) ?? byNameOf(node, props);
172
+ // fromEntries keeps a `__proto__` key an entry instead of the prototype.
173
+ return Object.fromEntries(
174
+ Object.entries(value as Record<string, unknown>).flatMap<[string, unknown]>(([k, v]) => {
175
+ if (v === undefined) return [];
176
+ const prop = byName.get(k);
177
+ const type = prop?.type ?? (siblingNames?.has(k) ? undefined : mapValue);
178
+ if (type === undefined) return [[k, v]];
179
+ // Union arms run over each other's output: keep a value one already wrapped.
180
+ if (isSensitive(type) && isSecretValue(type, v, whole)) {
181
+ return [[k, Redacted.isRedacted(v) ? v : Redacted.make(v)]];
182
+ }
183
+ return [[k, wrapHolding(type, v, whole)]];
184
+ }),
185
+ );
186
+ }
187
+ return value;
188
+ };
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Debug telemetry: spans for distilled's internals, on top of the operation
3
+ * span every call records. Opt in by providing the layer; a program that
4
+ * never imports this module never bundles it.
5
+ *
6
+ * ```ts
7
+ * import { TelemetryDebug } from "@distilled.cloud/core/telemetry-debug";
8
+ * program.pipe(Effect.provide(TelemetryDebug.layer));
9
+ * ```
10
+ *
11
+ * With it, the operation span is the parent of:
12
+ *
13
+ * - one `Attempt` span per try, with Effect's HTTP span under it;
14
+ * - INTERNAL spans at trace level `Debug` for first-call setup,
15
+ * serialize, sign, deserialize, backoff sleeps and the caller's read
16
+ * of a streamed output (`Tracer.MinimumTraceLevel` can drop them);
17
+ *
18
+ * and carries the caller's `code.*` attributes.
19
+ *
20
+ * Every SDK also writes the same `Effect.logDebug` lines for each call,
21
+ * with or without an exporter. They go to the program's logger, so they
22
+ * show when `References.MinimumLogLevel` admits `Debug`, and a logger that
23
+ * reads the current span (an OTel log exporter) links them to the trace:
24
+ *
25
+ * ```
26
+ * DEBUG distilled.operation=0ms: call S3.PutObject
27
+ * distilled.operation: S3.PutObject
28
+ * url.template: /{Bucket}/{Key+}
29
+ * DEBUG distilled.operation=23ms: -> PUT my-bucket.s3.us-east-1.amazonaws.com
30
+ * DEBUG distilled.operation=25ms: <- 200
31
+ * DEBUG distilled.operation=27ms: ok S3.PutObject
32
+ * ```
33
+ *
34
+ * The `call` line carries the input and the `ok` line the output, each
35
+ * with only its sensitive values `Redacted` (`./sensitive.ts`; input and
36
+ * output judged independently). The lines hold no serialized body and no
37
+ * full URL (a URL can carry a presigned signature or a sensitive label).
38
+ */
39
+ import * as Cause from "effect/Cause";
40
+ import * as Effect from "effect/Effect";
41
+ import * as Exit from "effect/Exit";
42
+ import * as Layer from "effect/Layer";
43
+ import * as Stream from "effect/Stream";
44
+ import * as Tracer from "effect/Tracer";
45
+ import { redactParsed } from "./sensitive.ts";
46
+ import { Debug, type DebugHooks, OperationSpan, tagOf } from "./telemetry.ts";
47
+
48
+ /**
49
+ * The call's log lines. Every line inside (the HTTP ones included) carries
50
+ * the operation and its URL template, and the exit line its duration. The
51
+ * input and output show only their sensitive values `Redacted`; each is
52
+ * judged by its own schema.
53
+ */
54
+ const call: DebugHooks["call"] = (info, input, schemas, effect) => {
55
+ const template = info.attributes["url.template"];
56
+ const start =
57
+ schemas === undefined
58
+ ? Effect.logDebug(`call ${info.name}`)
59
+ : Effect.logDebug(`call ${info.name}`, redactParsed(schemas.input, input));
60
+ const logged = Effect.flatMap(start, () =>
61
+ Effect.onExit(effect, (exit) =>
62
+ Exit.isSuccess(exit)
63
+ ? schemas === undefined
64
+ ? Effect.logDebug(`ok ${info.name}`)
65
+ : Effect.logDebug(`ok ${info.name}`, redactParsed(schemas.output, exit.value))
66
+ : Cause.hasInterruptsOnly(exit.cause)
67
+ ? Effect.logDebug(`interrupted ${info.name}`)
68
+ : Effect.logDebug(`failed ${info.name}: ${tagOf(Cause.squash(exit.cause))}`),
69
+ ),
70
+ );
71
+ return Effect.annotateLogs(Effect.withLogSpan(logged, "distilled.operation"), {
72
+ "distilled.operation": info.name,
73
+ ...(typeof template === "string" ? { "url.template": template } : {}),
74
+ });
75
+ };
76
+
77
+ /** The host of `url`, without the path or query (which can carry secrets). */
78
+ const hostOf = (url: string): string => {
79
+ try {
80
+ return new URL(url).host;
81
+ } catch {
82
+ return "";
83
+ }
84
+ };
85
+
86
+ /** One HTTP exchange: method and host out, status back. */
87
+ const http: DebugHooks["http"] = (request, sent) =>
88
+ Effect.flatMap(Effect.logDebug(`-> ${request.method} ${hostOf(request.url)}`), () =>
89
+ Effect.tap(sent, (response) => Effect.logDebug(`<- ${response.status}`)),
90
+ );
91
+
92
+ const phase: DebugHooks["phase"] = (name, effect, attributes) =>
93
+ Effect.withSpan(effect, name, { level: "Debug", attributes, captureStackTrace: false });
94
+
95
+ const attempt: DebugHooks["attempt"] = (base, n) =>
96
+ Effect.withFiber((fiber) => {
97
+ const call = fiber.getRef(OperationSpan);
98
+ if (call === undefined) return base;
99
+ return Effect.useSpan(
100
+ "Attempt",
101
+ {
102
+ parent: call.span,
103
+ attributes: { "distilled.attempt": n, "http.request.resend_count": n - 1 },
104
+ },
105
+ (span) => {
106
+ call.attempt = span;
107
+ const run = Effect.tapError(base, (error) =>
108
+ Effect.sync(() => span.attribute("error.type", tagOf(error))),
109
+ );
110
+ return Effect.provideService(run, Tracer.ParentSpan, span);
111
+ },
112
+ );
113
+ });
114
+
115
+ /**
116
+ * `distilled.read_stream`: from the caller's first pull on a streamed
117
+ * output member (an S3 object body, a Bedrock event stream) to its end,
118
+ * with the member's name and how many items (and bytes) it carried. It
119
+ * fills the operation span's time after the response headers arrive.
120
+ */
121
+ const readStream: DebugHooks["readStream"] = (stream, parent, member) =>
122
+ Stream.unwrap(
123
+ Effect.map(
124
+ Effect.makeSpan("distilled.read_stream", {
125
+ parent,
126
+ level: "Debug",
127
+ attributes: { "distilled.stream.member": member },
128
+ }),
129
+ (span) => {
130
+ let items = 0;
131
+ let bytes = 0;
132
+ const counted = Stream.map(stream, (item) => {
133
+ items++;
134
+ if (item instanceof Uint8Array) bytes += item.byteLength;
135
+ return item;
136
+ });
137
+ return Stream.onExit(counted, (exit) =>
138
+ Effect.clockWith((clock) =>
139
+ Effect.sync(() => {
140
+ span.attribute("distilled.stream.items", items);
141
+ if (bytes > 0) span.attribute("distilled.stream.bytes", bytes);
142
+ if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {
143
+ span.attribute("error.type", tagOf(Cause.squash(exit.cause)));
144
+ }
145
+ span.end(clock.currentTimeNanosUnsafe(), exit);
146
+ }),
147
+ ),
148
+ );
149
+ },
150
+ ),
151
+ );
152
+
153
+ const LOCATION = /\(?((?:file:\/\/)?[^\s()]+):(\d+):(\d+)\)?$/;
154
+
155
+ /** OTel `code.*` attributes for the caller's line. */
156
+ const callSite: DebugHooks["callSite"] = (site) => {
157
+ const line = site?.();
158
+ const match = line ? LOCATION.exec(line) : null;
159
+ if (!match) return undefined;
160
+ const fn = /^at (\S+) \(/.exec(line!)?.[1];
161
+ return {
162
+ "code.file.path": match[1],
163
+ "code.line.number": Number(match[2]),
164
+ "code.column.number": Number(match[3]),
165
+ ...(fn ? { "code.function.name": fn } : {}),
166
+ };
167
+ };
168
+
169
+ export const TelemetryDebug = {
170
+ /** Turns on debug spans and debug log lines for every distilled call it is provided to. */
171
+ layer: /*@__PURE__*/ Layer.succeed(Debug, {
172
+ phase,
173
+ attempt,
174
+ readStream,
175
+ callSite,
176
+ call,
177
+ http,
178
+ }) as Layer.Layer<never>,
179
+ } as const;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * App callbacks on each recorded operation span, for attributes distilled
3
+ * does not record (an app's own ids, a custom request field):
4
+ *
5
+ * ```ts
6
+ * import { TelemetryHooks } from "@distilled.cloud/core/telemetry-hooks";
7
+ *
8
+ * program.pipe(
9
+ * Effect.provide(
10
+ * TelemetryHooks.layer({
11
+ * onStart: (span, { method, input }) => {
12
+ * if (method === "S3/PutObject") span.attribute("app.tenant", tenantOf(input));
13
+ * },
14
+ * onEnd: (span, exit) => {},
15
+ * }),
16
+ * ),
17
+ * );
18
+ * ```
19
+ *
20
+ * `onStart` runs when the span starts, before the request is built, with
21
+ * the operation's span name, its `rpc.method` and the caller's input.
22
+ * `onEnd` runs when the call ends, after every retry. Both run only when a
23
+ * span is recorded (an exporter is installed). A program that never
24
+ * imports this module never bundles it.
25
+ */
26
+ import * as Layer from "effect/Layer";
27
+ import { Hooks, type SpanHooks } from "./telemetry.ts";
28
+
29
+ export type { SpanHooks };
30
+
31
+ export const TelemetryHooks = {
32
+ layer: (hooks: SpanHooks): Layer.Layer<never> => Layer.succeed(Hooks, hooks),
33
+ } as const;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The `com.distilled.telemetry#service` trait's `hosts`: facts for requests
3
+ * to S3-compatible hosts such as Cloudflare R2. Generated code imports this
4
+ * only where a trait has one (S3). See
5
+ * `packages/dev/src/codegen/telemetry-traits.md`.
6
+ */
7
+ import type { RequestHook } from "./telemetry.ts";
8
+
9
+ /** Facts for requests to a host ending in `suffix`. */
10
+ export interface HostRule {
11
+ /** Host suffix, with its leading dot (`.r2.cloudflarestorage.com`). */
12
+ readonly suffix: string;
13
+ readonly attributes?: Readonly<Record<string, string | number | boolean>>;
14
+ /** Attribute that gets the host label just before the suffix (the account id). */
15
+ readonly hostLabel?: string;
16
+ /** Attribute values copied under a second name: `{ "aws.s3.bucket": "cloudflare.r2.bucket" }`. */
17
+ readonly copy?: Readonly<Record<string, string>>;
18
+ }
19
+
20
+ /**
21
+ * Facts recorded when a request goes to a matching host: an S3-compatible
22
+ * service such as Cloudflare R2 reached through the S3 SDK.
23
+ */
24
+ export const hostRules =
25
+ (rules: ReadonlyArray<HostRule>): RequestHook =>
26
+ (host, span, set) => {
27
+ for (const rule of rules) {
28
+ if (!host.endsWith(rule.suffix)) continue;
29
+ for (const key in rule.attributes) set(key, rule.attributes[key]);
30
+ if (rule.hostLabel !== undefined) {
31
+ const prefix = host.slice(0, host.length - rule.suffix.length);
32
+ if (prefix.length > 0) set(rule.hostLabel, prefix.slice(prefix.lastIndexOf(".") + 1));
33
+ }
34
+ for (const from in rule.copy) {
35
+ const value = span.attributes.get(from);
36
+ if (value !== undefined) set(rule.copy[from]!, value);
37
+ }
38
+ }
39
+ };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * W3C trace context in a Lambda `Invoke`'s `ClientContext` (base64 JSON),
3
+ * under `custom.traceparent`, as `@opentelemetry/instrumentation-aws-sdk`
4
+ * writes it; the invoked function reads it from `context.clientContext`.
5
+ * Generated code imports this only where an operation's `inject` has format
6
+ * `lambdaClientContext`. See `packages/dev/src/codegen/telemetry-traits.md`.
7
+ */
8
+ import type * as Tracer from "effect/Tracer";
9
+ import { traceparent } from "./telemetry-message-context.ts";
10
+
11
+ /** Lambda caps `ClientContext` at 3583 bytes of base64. */
12
+ const MAX_CLIENT_CONTEXT = 3583;
13
+
14
+ const toBase64 = (text: string): string => {
15
+ let binary = "";
16
+ for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);
17
+ return btoa(binary);
18
+ };
19
+
20
+ const fromBase64 = (text: string): string =>
21
+ new TextDecoder().decode(Uint8Array.from(atob(text), (c) => c.charCodeAt(0)));
22
+
23
+ /**
24
+ * Add `custom.traceparent` to the input's `member` (a base64 JSON client
25
+ * context). Kept as it was: a `traceparent` already there, a value that is
26
+ * not base64 JSON, and a result over Lambda's size cap.
27
+ */
28
+ export const injectLambdaClientContext =
29
+ (place: { readonly member: string }) =>
30
+ (span: Tracer.Span, input: unknown): unknown => {
31
+ if (input === null || typeof input !== "object") return input;
32
+ const record = input as Record<string, unknown>;
33
+ const current = record[place.member];
34
+ try {
35
+ const parsed =
36
+ typeof current === "string" && current.length > 0 ? JSON.parse(fromBase64(current)) : {};
37
+ if (parsed === null || typeof parsed !== "object") return input;
38
+ if (parsed.custom?.traceparent !== undefined) return input;
39
+ const encoded = toBase64(
40
+ JSON.stringify({ ...parsed, custom: { ...parsed.custom, traceparent: traceparent(span) } }),
41
+ );
42
+ return encoded.length > MAX_CLIENT_CONTEXT ? input : { ...record, [place.member]: encoded };
43
+ } catch {
44
+ return input;
45
+ }
46
+ };
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The `com.distilled.telemetry#operation` trait's `inject` and `extract`
3
+ * (format `awsMessageAttributes`): W3C trace context in SQS and SNS
4
+ * message attributes. Generated code imports this only where a trait has
5
+ * one. See `packages/dev/src/codegen/telemetry-traits.md`.
6
+ */
7
+ import * as Tracer from "effect/Tracer";
8
+ import { parseTraceHeader } from "./telemetry-xray.ts";
9
+ import type { MessageExtract } from "./telemetry.ts";
10
+
11
+ /** W3C `traceparent` of a span. */
12
+ export const traceparent = (span: Tracer.AnySpan): string =>
13
+ `00-${span.traceId}-${span.spanId}-${span.sampled ? "01" : "00"}`;
14
+
15
+ const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
16
+
17
+ /** The span a W3C `traceparent` names, if it is well formed. */
18
+ export const parseTraceparent = (value: unknown): Tracer.ExternalSpan | undefined => {
19
+ const match = typeof value === "string" ? TRACEPARENT.exec(value) : null;
20
+ if (match === null) return undefined;
21
+ return Tracer.externalSpan({
22
+ traceId: match[1]!,
23
+ spanId: match[2]!,
24
+ sampled: (Number.parseInt(match[3]!, 16) & 1) === 1,
25
+ });
26
+ };
27
+
28
+ /** Where messages sit: `member` of the value, or of every element of its `list` member. */
29
+ export interface MessagePlace {
30
+ readonly member: string;
31
+ readonly list?: string;
32
+ }
33
+
34
+ /** SQS and SNS take at most 10 message attributes. */
35
+ const MAX_MESSAGE_ATTRIBUTES = 10;
36
+
37
+ const withTraceparent = (attributes: unknown, value: string): unknown => {
38
+ const map =
39
+ attributes !== null && typeof attributes === "object"
40
+ ? (attributes as Record<string, unknown>)
41
+ : {};
42
+ if ("traceparent" in map || Object.keys(map).length >= MAX_MESSAGE_ATTRIBUTES) return attributes;
43
+ return { ...map, traceparent: { DataType: "String", StringValue: value } };
44
+ };
45
+
46
+ /**
47
+ * Write the span's `traceparent` into each message's attributes (a map of
48
+ * `{ DataType, StringValue }`, the SQS and SNS shape). Kept: a
49
+ * `traceparent` already there, and a message with 10 attributes. The
50
+ * caller's input object is not changed.
51
+ */
52
+ export const injectAwsMessageAttributes =
53
+ (place: MessagePlace) =>
54
+ (span: Tracer.Span, input: unknown): unknown => {
55
+ if (input === null || typeof input !== "object") return input;
56
+ const record = input as Record<string, unknown>;
57
+ const value = traceparent(span);
58
+ if (place.list === undefined) {
59
+ return { ...record, [place.member]: withTraceparent(record[place.member], value) };
60
+ }
61
+ const entries = record[place.list];
62
+ if (!Array.isArray(entries)) return input;
63
+ return {
64
+ ...record,
65
+ [place.list]: entries.map((entry) =>
66
+ entry !== null && typeof entry === "object"
67
+ ? {
68
+ ...entry,
69
+ [place.member]: withTraceparent(
70
+ (entry as Record<string, unknown>)[place.member],
71
+ value,
72
+ ),
73
+ }
74
+ : entry,
75
+ ),
76
+ };
77
+ };
78
+
79
+ /**
80
+ * Where else a received message can carry trace context, by generated
81
+ * property name (SQS `ReceiveMessage`):
82
+ *
83
+ * envelope the body member; an SNS notification delivered without
84
+ * raw message delivery is JSON whose `MessageAttributes`
85
+ * carry the publisher's `traceparent`
86
+ * system the system-attributes member, whose `AWSTraceHeader` is
87
+ * an X-Ray trace header (set by X-Ray-instrumented
88
+ * producers); `systemRequest` is the input member listing
89
+ * system attributes to return
90
+ */
91
+ export interface MessageExtractPlace extends MessagePlace {
92
+ readonly request?: string;
93
+ /** The message's id member: each link carries it as `messaging.message.id`. */
94
+ readonly messageId?: string;
95
+ readonly envelope?: string;
96
+ readonly system?: string;
97
+ readonly systemRequest?: string;
98
+ }
99
+
100
+ const asksFor = (names: unknown, name: string): boolean =>
101
+ Array.isArray(names) && names.some((n) => n === "All" || n === ".*" || n === name);
102
+
103
+ const askFor = (record: Record<string, unknown>, member: string | undefined, name: string) => {
104
+ if (member === undefined || asksFor(record[member], name)) return record;
105
+ const names = record[member];
106
+ return { ...record, [member]: [...(Array.isArray(names) ? names : []), name] };
107
+ };
108
+
109
+ /** The publisher's `traceparent` in an SNS notification body, if there is one. */
110
+ const envelopeTraceparent = (body: unknown): unknown => {
111
+ // Parse only bodies that can hold one: most messages are not SNS JSON.
112
+ if (typeof body !== "string" || !body.includes('"traceparent"')) return undefined;
113
+ try {
114
+ const parsed = JSON.parse(body);
115
+ return parsed?.Type === "Notification"
116
+ ? parsed.MessageAttributes?.traceparent?.Value
117
+ : undefined;
118
+ } catch {
119
+ return undefined;
120
+ }
121
+ };
122
+
123
+ /**
124
+ * Ask for `traceparent` (and `AWSTraceHeader`) back, unless the input asks
125
+ * for `All` or `.*`, and link the span to every well-formed trace context
126
+ * each message carries: its `traceparent` attribute, else the SNS
127
+ * envelope's, plus its X-Ray `AWSTraceHeader` when that names another span.
128
+ */
129
+ export const extractAwsMessageAttributes = (place: MessageExtractPlace): MessageExtract => ({
130
+ request: (input) => {
131
+ if (input === null || typeof input !== "object") return input;
132
+ let record = askFor(input as Record<string, unknown>, place.request, "traceparent");
133
+ if (place.system !== undefined) record = askFor(record, place.systemRequest, "AWSTraceHeader");
134
+ return record;
135
+ },
136
+ links: (output) => {
137
+ if (output === null || typeof output !== "object") return [];
138
+ const record = output as Record<string, unknown>;
139
+ const holders =
140
+ place.list === undefined
141
+ ? [record]
142
+ : Array.isArray(record[place.list])
143
+ ? (record[place.list] as unknown[])
144
+ : [];
145
+ const links: Tracer.SpanLink[] = [];
146
+ for (const holder of holders) {
147
+ if (holder === null || typeof holder !== "object") continue;
148
+ const message = holder as Record<string, unknown>;
149
+ const id = place.messageId === undefined ? undefined : message[place.messageId];
150
+ const linkAttributes = typeof id === "string" ? { "messaging.message.id": id } : {};
151
+ const attributes = message[place.member] as
152
+ | Record<string, { readonly StringValue?: unknown } | undefined>
153
+ | undefined;
154
+ const span =
155
+ parseTraceparent(attributes?.traceparent?.StringValue) ??
156
+ (place.envelope !== undefined
157
+ ? parseTraceparent(envelopeTraceparent(message[place.envelope]))
158
+ : undefined);
159
+ if (span !== undefined) links.push({ span, attributes: linkAttributes });
160
+ if (place.system !== undefined) {
161
+ const system = message[place.system] as Record<string, unknown> | undefined;
162
+ const xray = parseTraceHeader(system?.AWSTraceHeader);
163
+ if (xray !== undefined && xray.spanId !== span?.spanId) {
164
+ links.push({ span: xray, attributes: linkAttributes });
165
+ }
166
+ }
167
+ }
168
+ return links;
169
+ },
170
+ });