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

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 (132) hide show
  1. package/lib/api.d.ts +165 -0
  2. package/lib/api.d.ts.map +1 -0
  3. package/lib/api.js +178 -0
  4. package/lib/api.js.map +1 -0
  5. package/lib/codegen/cli.d.ts +29 -0
  6. package/lib/codegen/cli.d.ts.map +1 -0
  7. package/lib/codegen/cli.js +165 -0
  8. package/lib/codegen/cli.js.map +1 -0
  9. package/lib/codegen/emit.d.ts +129 -0
  10. package/lib/codegen/emit.d.ts.map +1 -0
  11. package/lib/codegen/emit.js +105 -0
  12. package/lib/codegen/emit.js.map +1 -0
  13. package/lib/codegen/format.d.ts +23 -0
  14. package/lib/codegen/format.d.ts.map +1 -0
  15. package/lib/codegen/format.js +28 -0
  16. package/lib/codegen/format.js.map +1 -0
  17. package/lib/codegen/generator.d.ts +334 -0
  18. package/lib/codegen/generator.d.ts.map +1 -0
  19. package/lib/codegen/generator.js +691 -0
  20. package/lib/codegen/generator.js.map +1 -0
  21. package/lib/codegen/graph.d.ts +36 -0
  22. package/lib/codegen/graph.d.ts.map +1 -0
  23. package/lib/codegen/graph.js +136 -0
  24. package/lib/codegen/graph.js.map +1 -0
  25. package/lib/codegen/members.d.ts +25 -0
  26. package/lib/codegen/members.d.ts.map +1 -0
  27. package/lib/codegen/members.js +55 -0
  28. package/lib/codegen/members.js.map +1 -0
  29. package/lib/codegen/naming.d.ts +29 -0
  30. package/lib/codegen/naming.d.ts.map +1 -0
  31. package/lib/codegen/naming.js +74 -0
  32. package/lib/codegen/naming.js.map +1 -0
  33. package/lib/codegen/openapi-cli.d.ts +38 -0
  34. package/lib/codegen/openapi-cli.d.ts.map +1 -0
  35. package/lib/codegen/openapi-cli.js +107 -0
  36. package/lib/codegen/openapi-cli.js.map +1 -0
  37. package/lib/codegen/openapi.d.ts +115 -0
  38. package/lib/codegen/openapi.d.ts.map +1 -0
  39. package/lib/codegen/openapi.js +1220 -0
  40. package/lib/codegen/openapi.js.map +1 -0
  41. package/lib/codegen/operations.d.ts +24 -0
  42. package/lib/codegen/operations.d.ts.map +1 -0
  43. package/lib/codegen/operations.js +56 -0
  44. package/lib/codegen/operations.js.map +1 -0
  45. package/lib/codegen/pagination.d.ts +39 -0
  46. package/lib/codegen/pagination.d.ts.map +1 -0
  47. package/lib/codegen/pagination.js +33 -0
  48. package/lib/codegen/pagination.js.map +1 -0
  49. package/lib/codegen/prelude.d.ts +15 -0
  50. package/lib/codegen/prelude.d.ts.map +1 -0
  51. package/lib/codegen/prelude.js +60 -0
  52. package/lib/codegen/prelude.js.map +1 -0
  53. package/lib/error-category.d.ts +28 -0
  54. package/lib/error-category.d.ts.map +1 -0
  55. package/lib/error-category.js +46 -0
  56. package/lib/error-category.js.map +1 -0
  57. package/lib/errors.d.ts +1 -0
  58. package/lib/errors.d.ts.map +1 -1
  59. package/lib/errors.js +1 -0
  60. package/lib/errors.js.map +1 -1
  61. package/lib/json-patch.d.ts +25 -32
  62. package/lib/json-patch.d.ts.map +1 -1
  63. package/lib/json-patch.js +23 -95
  64. package/lib/json-patch.js.map +1 -1
  65. package/lib/pagination.d.ts +37 -51
  66. package/lib/pagination.d.ts.map +1 -1
  67. package/lib/pagination.js +72 -90
  68. package/lib/pagination.js.map +1 -1
  69. package/lib/protocol-http.d.ts +74 -0
  70. package/lib/protocol-http.d.ts.map +1 -0
  71. package/lib/protocol-http.js +554 -0
  72. package/lib/protocol-http.js.map +1 -0
  73. package/lib/protocol-rest.d.ts +124 -0
  74. package/lib/protocol-rest.d.ts.map +1 -0
  75. package/lib/protocol-rest.js +242 -0
  76. package/lib/protocol-rest.js.map +1 -0
  77. package/lib/retry.d.ts +8 -2
  78. package/lib/retry.d.ts.map +1 -1
  79. package/lib/retry.js +21 -15
  80. package/lib/retry.js.map +1 -1
  81. package/lib/schema.d.ts +7 -8
  82. package/lib/schema.d.ts.map +1 -1
  83. package/lib/schema.js +7 -8
  84. package/lib/schema.js.map +1 -1
  85. package/lib/trait.d.ts +150 -0
  86. package/lib/trait.d.ts.map +1 -0
  87. package/lib/trait.js +107 -0
  88. package/lib/trait.js.map +1 -0
  89. package/package.json +18 -75
  90. package/src/api.ts +446 -0
  91. package/src/codegen/cli.ts +268 -0
  92. package/src/codegen/emit.ts +207 -0
  93. package/src/codegen/format.ts +47 -0
  94. package/src/codegen/generator.ts +1153 -0
  95. package/src/codegen/graph.ts +151 -0
  96. package/src/codegen/members.ts +71 -0
  97. package/src/codegen/naming.ts +86 -0
  98. package/src/codegen/openapi-cli.ts +166 -0
  99. package/src/codegen/openapi.ts +1450 -0
  100. package/src/codegen/operations.ts +76 -0
  101. package/src/codegen/pagination.ts +71 -0
  102. package/src/codegen/prelude.ts +70 -0
  103. package/src/error-category.ts +84 -0
  104. package/src/errors.ts +2 -0
  105. package/src/json-patch.ts +26 -110
  106. package/src/pagination.ts +86 -142
  107. package/src/protocol-http.ts +699 -0
  108. package/src/protocol-rest.ts +367 -0
  109. package/src/retry.ts +20 -21
  110. package/src/schema.ts +7 -8
  111. package/src/trait.ts +238 -0
  112. package/README.md +0 -30
  113. package/lib/client.d.ts +0 -167
  114. package/lib/client.d.ts.map +0 -1
  115. package/lib/client.js +0 -659
  116. package/lib/client.js.map +0 -1
  117. package/lib/schemas.d.ts +0 -60
  118. package/lib/schemas.d.ts.map +0 -1
  119. package/lib/schemas.js +0 -79
  120. package/lib/schemas.js.map +0 -1
  121. package/lib/sensitive.d.ts +0 -71
  122. package/lib/sensitive.d.ts.map +0 -1
  123. package/lib/sensitive.js +0 -96
  124. package/lib/sensitive.js.map +0 -1
  125. package/lib/traits.d.ts +0 -421
  126. package/lib/traits.d.ts.map +0 -1
  127. package/lib/traits.js +0 -737
  128. package/lib/traits.js.map +0 -1
  129. package/src/client.ts +0 -1177
  130. package/src/schemas.ts +0 -128
  131. package/src/sensitive.ts +0 -119
  132. package/src/traits.ts +0 -996
package/lib/traits.js DELETED
@@ -1,737 +0,0 @@
1
- /**
2
- * Annotation-based traits for declarative operation definitions.
3
- *
4
- * This module provides a type-safe annotation system for defining HTTP operations
5
- * using Schema annotations. Traits can be applied via `.pipe()` or composed with `all()`.
6
- *
7
- * The annotation system is shared across all SDKs. Individual SDKs can extend it
8
- * with provider-specific traits (e.g., AWS Smithy traits, Cloudflare-specific traits).
9
- *
10
- * @example
11
- * ```ts
12
- * import * as T from "@distilled.cloud/core/traits";
13
- *
14
- * const GetDatabaseInput = Schema.Struct({
15
- * organization: Schema.String.pipe(T.PathParam()),
16
- * database: Schema.String.pipe(T.PathParam()),
17
- * }).pipe(
18
- * T.Http({ method: "GET", path: "/organizations/{organization}/databases/{database}" })
19
- * );
20
- * ```
21
- */
22
- import * as Redacted from "effect/Redacted";
23
- import * as Schema from "effect/Schema";
24
- import * as AST from "effect/SchemaAST";
25
- // ============================================================================
26
- // Annotation Primitives
27
- // ============================================================================
28
- /**
29
- * Internal symbol for annotation metadata storage.
30
- */
31
- const annotationMetaSymbol = Symbol.for("@distilled.cloud/annotation-meta");
32
- /**
33
- * Create an annotation builder for a given symbol and value.
34
- * This is the core primitive used to build all trait annotations.
35
- */
36
- export function makeAnnotation(sym, value) {
37
- const fn = (schema) => schema.annotate({ [sym]: value });
38
- fn[annotationMetaSymbol] = [{ symbol: sym, value }];
39
- fn[sym] = value;
40
- return fn;
41
- }
42
- /**
43
- * Combine multiple annotations into one.
44
- * Use when you need multiple annotations on the same schema.
45
- *
46
- * @example
47
- * ```ts
48
- * const MyInput = Schema.Struct({
49
- * id: Schema.String.pipe(T.all(T.PathParam(), T.Required())),
50
- * });
51
- * ```
52
- */
53
- export function all(...annotations) {
54
- const entries = [];
55
- const raw = {};
56
- for (const a of annotations) {
57
- for (const entry of a[annotationMetaSymbol]) {
58
- entries.push(entry);
59
- raw[entry.symbol] = entry.value;
60
- }
61
- }
62
- const fn = (schema) => schema.annotate(raw);
63
- fn[annotationMetaSymbol] = entries;
64
- for (const { symbol, value } of entries) {
65
- fn[symbol] = value;
66
- }
67
- return fn;
68
- }
69
- // =============================================================================
70
- // HTTP Operation Traits
71
- // =============================================================================
72
- /** Symbol for HTTP operation metadata (method + path template) */
73
- export const httpSymbol = Symbol.for("@distilled.cloud/http");
74
- /**
75
- * Http trait - defines the HTTP method and path template for an operation.
76
- * Path parameters are specified using {paramName} syntax.
77
- *
78
- * @example
79
- * ```ts
80
- * const GetDatabaseInput = Schema.Struct({
81
- * organization: Schema.String.pipe(T.PathParam()),
82
- * database: Schema.String.pipe(T.PathParam()),
83
- * }).pipe(
84
- * T.Http({ method: "GET", path: "/organizations/{organization}/databases/{database}" })
85
- * );
86
- * ```
87
- */
88
- export const Http = (trait) => makeAnnotation(httpSymbol, trait);
89
- // =============================================================================
90
- // Path Parameter Traits
91
- // =============================================================================
92
- /** Symbol for path parameter annotation */
93
- export const pathParamSymbol = Symbol.for("@distilled.cloud/path-param");
94
- /**
95
- * PathParam trait - marks a field as a path parameter.
96
- * The field name is used as the placeholder name in the path template.
97
- *
98
- * @example
99
- * ```ts
100
- * const Input = Schema.Struct({
101
- * organization: Schema.String.pipe(T.PathParam()),
102
- * }).pipe(
103
- * T.Http({ method: "GET", path: "/organizations/{organization}" })
104
- * );
105
- * ```
106
- */
107
- export const PathParam = () => makeAnnotation(pathParamSymbol, true);
108
- // =============================================================================
109
- // Query Parameter Traits
110
- // =============================================================================
111
- /** Symbol for query parameter annotation */
112
- export const queryParamSymbol = Symbol.for("@distilled.cloud/query-param");
113
- /**
114
- * QueryParam trait - marks a field as a query parameter.
115
- * Optionally specify a different wire name.
116
- *
117
- * @example
118
- * ```ts
119
- * const Input = Schema.Struct({
120
- * perPage: Schema.optional(Schema.Number).pipe(T.QueryParam("per_page")),
121
- * });
122
- * ```
123
- */
124
- export const QueryParam = (name) => makeAnnotation(queryParamSymbol, name ?? true);
125
- // =============================================================================
126
- // Header Parameter Traits
127
- // =============================================================================
128
- /** Symbol for header parameter annotation */
129
- export const headerParamSymbol = Symbol.for("@distilled.cloud/header-param");
130
- /**
131
- * HeaderParam trait - marks a field as a header parameter.
132
- * Specify the header name.
133
- *
134
- * @example
135
- * ```ts
136
- * const Input = Schema.Struct({
137
- * apiToken: Schema.String.pipe(T.HeaderParam("X-API-Token")),
138
- * });
139
- * ```
140
- */
141
- export const HeaderParam = (name) => makeAnnotation(headerParamSymbol, name);
142
- // =============================================================================
143
- // Convenience Aliases (used by Cloudflare/GCP generators)
144
- // =============================================================================
145
- /**
146
- * HttpPath - alias for PathParam that also carries the wire name.
147
- * Used in generated code: `Schema.String.pipe(T.HttpPath("account_id"))`
148
- */
149
- export const HttpPath = (name) => makeAnnotation(pathParamSymbol, name);
150
- /**
151
- * HttpQuery - alias for QueryParam with an explicit wire name.
152
- * Used in generated code: `Schema.optional(Schema.String).pipe(T.HttpQuery("per_page"))`
153
- */
154
- export const HttpQuery = (name) => makeAnnotation(queryParamSymbol, name);
155
- /**
156
- * HttpHeader - alias for HeaderParam.
157
- * Used in generated code: `Schema.String.pipe(T.HttpHeader("X-Custom-Header"))`
158
- */
159
- export const HttpHeader = (name) => makeAnnotation(headerParamSymbol, name);
160
- /** Symbol for HTTP body annotation */
161
- export const httpBodySymbol = Symbol.for("@distilled.cloud/http-body");
162
- /**
163
- * HttpBody - marks a field as the raw HTTP body.
164
- * Used for operations where a field IS the entire request body
165
- * (not a named field within a JSON body).
166
- */
167
- export const HttpBody = () => makeAnnotation(httpBodySymbol, true);
168
- /** Symbol for binary response body annotation */
169
- export const binaryResponseBodySymbol = Symbol.for("@distilled.cloud/binary-response-body");
170
- /**
171
- * BinaryResponseBody - marks a response struct field as the raw binary body
172
- * of an `application/octet-stream` download. The runtime fills the field
173
- * with an Effect `Stream.Stream<Uint8Array>` of the response body. Sibling
174
- * fields annotated with `T.HttpResponseHeader` are populated from the
175
- * matching response headers.
176
- */
177
- export const BinaryResponseBody = () => makeAnnotation(binaryResponseBodySymbol, true);
178
- /** Symbol for response header annotation */
179
- export const responseHeaderSymbol = Symbol.for("@distilled.cloud/response-header");
180
- /**
181
- * HttpResponseHeader - marks a response struct field as a value pulled from
182
- * a named HTTP response header (e.g. `etag`, `content-type`). The runtime
183
- * populates the field with the (lowercased) header value if present, and
184
- * leaves it `undefined` otherwise. Mirror of `T.HttpHeader` for response-
185
- * side header extraction.
186
- *
187
- * Currently consumed by binary-download operations (operations whose
188
- * `T.Http({ responseContentType: "binary" })` trait is set), where the
189
- * response struct's shape is `{ body: Stream.Stream<Uint8Array>, ...headers }`.
190
- */
191
- export const HttpResponseHeader = (name) => makeAnnotation(responseHeaderSymbol, name);
192
- /** Symbol for GraphQL operation metadata (query string + operation name) */
193
- export const graphqlOpSymbol = Symbol.for("@distilled.cloud/graphql-op");
194
- /**
195
- * GraphQLOp trait - declares an operation as GraphQL. When present, the client
196
- * wraps the request body as `{ query, operationName, variables: <inputs> }` and
197
- * extracts the response from `data.<operationName>`. The Http trait's path is
198
- * still used as the GraphQL endpoint (typically `/graphql`).
199
- *
200
- * @example
201
- * ```ts
202
- * const GetUserInput = Schema.Struct({
203
- * id: Schema.String,
204
- * }).pipe(
205
- * T.Http({ method: "POST", path: "/graphql" }),
206
- * T.GraphQLOp({
207
- * query: "query getUser($id: ID!) { user(id: $id) { id name } }",
208
- * operationName: "getUser",
209
- * type: "query",
210
- * }),
211
- * );
212
- * ```
213
- */
214
- export const GraphQLOp = (trait) => makeAnnotation(graphqlOpSymbol, trait);
215
- /** Symbol for response body path transformation */
216
- export const responsePathSymbol = Symbol.for("@distilled.cloud/response-path");
217
- /**
218
- * ResponsePath - decode the response from a nested path within the raw body.
219
- * Useful for providers that wrap successful responses in envelopes like
220
- * `{ result: <payload>, result_info: ... }`.
221
- */
222
- export const ResponsePath = (path) => makeAnnotation(responsePathSymbol, path);
223
- /** Symbol for form data file annotation */
224
- export const httpFormDataFileSymbol = Symbol.for("@distilled.cloud/http-form-data-file");
225
- /**
226
- * HttpFormDataFile - marks a field as a file upload in multipart form data.
227
- */
228
- export const HttpFormDataFile = () => makeAnnotation(httpFormDataFileSymbol, true);
229
- // =============================================================================
230
- // Redirect-as-Response Trait
231
- // =============================================================================
232
- /** Symbol for "do not follow redirects; treat 3xx Location header as success body" */
233
- export const httpNoFollowRedirectSymbol = Symbol.for("@distilled.cloud/http-no-follow-redirect");
234
- /**
235
- * NoFollowRedirect trait - opts an operation out of the underlying HTTP
236
- * client's automatic redirect-following.
237
- *
238
- * Some endpoints — notably OAuth/SSO authorize endpoints — return their
239
- * useful result as a `Location` header on a 302 response. The default
240
- * `fetch` follows that redirect to the IdP's HTML login page, so by the
241
- * time the client sees a body it's no longer the SDK's expected JSON.
242
- *
243
- * Marking an operation with this trait makes the runtime client:
244
- * 1. Issue the request with `redirect: "manual"` so the 3xx surfaces
245
- * to user code.
246
- * 2. On a 3xx, build a synthetic body `{ [locationField]: <Location> }`
247
- * and decode that into the output schema (default field name `"url"`).
248
- *
249
- * @example
250
- * ```ts
251
- * const SsoAuthorizeInput = Schema.Struct({...}).pipe(
252
- * T.Http({ method: "GET", path: "/sso/authorize" }),
253
- * T.NoFollowRedirect(),
254
- * );
255
- * const SsoAuthorizeOutput = Schema.Struct({ url: Schema.String });
256
- * ```
257
- */
258
- export const NoFollowRedirect = (trait = {}) => makeAnnotation(httpNoFollowRedirectSymbol, trait);
259
- // =============================================================================
260
- // API Error Code Trait
261
- // =============================================================================
262
- /** Symbol for API error code mapping */
263
- export const apiErrorCodeSymbol = Symbol.for("@distilled.cloud/api-error-code");
264
- /**
265
- * ApiErrorCode trait - maps an error class to an API error code.
266
- * Used to match API error responses to typed error classes.
267
- *
268
- * @example
269
- * ```ts
270
- * class NotFoundError extends Schema.TaggedErrorClass<NotFoundError>()(
271
- * "NotFoundError",
272
- * { message: Schema.String },
273
- * ).pipe(T.ApiErrorCode("not_found")) {}
274
- * ```
275
- */
276
- export const ApiErrorCode = (code) => makeAnnotation(apiErrorCodeSymbol, code);
277
- // =============================================================================
278
- // Service Metadata Trait
279
- // =============================================================================
280
- /** Symbol for service metadata */
281
- export const serviceSymbol = Symbol.for("@distilled.cloud/service");
282
- /**
283
- * Service trait - attaches service metadata to a schema.
284
- */
285
- export const Service = (trait) => makeAnnotation(serviceSymbol, trait);
286
- // =============================================================================
287
- // Annotation Retrieval Helpers
288
- // =============================================================================
289
- /**
290
- * Get annotation value from an AST node, following encoding chain if needed.
291
- */
292
- export const getAnnotation = (ast, symbol) => {
293
- // Direct annotation
294
- const annotations = ast.annotations;
295
- const direct = annotations?.[symbol];
296
- if (direct !== undefined)
297
- return direct;
298
- // Follow encoding chain (replaces v3 Transformation handling)
299
- if (ast.encoding && ast.encoding.length > 0) {
300
- return getAnnotation(ast.encoding[0].to, symbol);
301
- }
302
- // Follow `Schema.suspend` thunks. Generated SDKs defer schema construction
303
- // by wrapping structs in `Schema.suspend(() => ...)`; a trait applied to an
304
- // already-suspended schema (e.g. `T.ResponsePath` on a shared, suspended
305
- // response struct) lands on the Suspend node itself, so we must force the
306
- // thunk to discover annotations attached beneath it.
307
- if (ast._tag === "Suspend") {
308
- return getAnnotation(ast.thunk(), symbol);
309
- }
310
- return undefined;
311
- };
312
- /**
313
- * Get HTTP trait from a schema's AST.
314
- */
315
- export const getHttpTrait = (ast) => getAnnotation(ast, httpSymbol);
316
- export const getResponsePath = (ast) => getAnnotation(ast, responsePathSymbol);
317
- /**
318
- * Get GraphQL operation trait from a schema's AST.
319
- */
320
- export const getGraphQLOp = (ast) => getAnnotation(ast, graphqlOpSymbol);
321
- /**
322
- * Get the `NoFollowRedirect` trait config from an input schema's AST, if any.
323
- */
324
- export const getNoFollowRedirect = (ast) => getAnnotation(ast, httpNoFollowRedirectSymbol);
325
- /**
326
- * Check if a PropertySignature has the pathParam annotation.
327
- * Works for both PathParam() (annotation value = true) and HttpPath("wire_name") (annotation value = string).
328
- */
329
- export const isPathParam = (prop) => {
330
- const value = getAnnotation(prop.type, pathParamSymbol);
331
- return value !== undefined;
332
- };
333
- /**
334
- * Get query param name from a PropertySignature (returns true if unnamed, string if named).
335
- */
336
- export const getQueryParam = (prop) => {
337
- return getAnnotation(prop.type, queryParamSymbol);
338
- };
339
- /**
340
- * Get header param name from a PropertySignature.
341
- */
342
- export const getHeaderParam = (prop) => {
343
- return getAnnotation(prop.type, headerParamSymbol);
344
- };
345
- /**
346
- * Get API error code from an error class AST.
347
- */
348
- export const getApiErrorCode = (ast) => getAnnotation(ast, apiErrorCodeSymbol);
349
- /**
350
- * Get service metadata from a schema's AST.
351
- */
352
- export const getServiceTrait = (ast) => getAnnotation(ast, serviceSymbol);
353
- /**
354
- * Extract path parameters from a schema's struct properties.
355
- * Returns an array of field names that have the PathParam annotation.
356
- */
357
- export const getPathParams = (ast) => {
358
- // Handle Objects (struct) - v4 renamed from TypeLiteral
359
- if (ast._tag === "Objects") {
360
- return ast.propertySignatures
361
- .filter((prop) => isPathParam(prop))
362
- .map((prop) => String(prop.name));
363
- }
364
- // Follow encoding chain (replaces v3 Transformation handling)
365
- if (ast.encoding && ast.encoding.length > 0) {
366
- return getPathParams(ast.encoding[0].to);
367
- }
368
- return [];
369
- };
370
- /**
371
- * Build the request path by substituting path parameters into the template.
372
- * Simple version that assumes input keys match template placeholders.
373
- * For schema-aware path building (with camelCase → wire_name mapping), use buildPathFromSchema.
374
- */
375
- export const buildPath = (template, input) => {
376
- return template.replace(/\{(\w+)\}/g, (_, name) => {
377
- const value = input[name];
378
- if (value === undefined || value === null) {
379
- throw new Error(`Missing path parameter: ${name}`);
380
- }
381
- return encodeURIComponent(String(value));
382
- });
383
- };
384
- /**
385
- * Extract AST property signatures from a schema AST, following encoding chain and suspends.
386
- */
387
- export const getStructProps = (ast) => {
388
- if (ast.encoding && ast.encoding.length > 0) {
389
- return getStructProps(ast.encoding[0].to);
390
- }
391
- if (ast._tag === "Suspend") {
392
- return getStructProps(ast.thunk());
393
- }
394
- if (ast._tag === "Objects") {
395
- return [...ast.propertySignatures];
396
- }
397
- return [];
398
- };
399
- /**
400
- * Get the path parameter wire name from a PropertySignature.
401
- * - For HttpPath("wire_name"), returns the wire name string.
402
- * - For PathParam(), returns the property name (since annotation is `true`).
403
- * - Returns undefined if not a path param.
404
- */
405
- export const getPathParamWireName = (prop) => {
406
- const value = getAnnotation(prop.type, pathParamSymbol);
407
- if (value === undefined)
408
- return undefined;
409
- if (typeof value === "string")
410
- return value;
411
- // PathParam() stores `true` — use property name as wire name
412
- return String(prop.name);
413
- };
414
- /**
415
- * Schema-aware request builder. Categorizes input properties into path, query, header,
416
- * and body parts using annotations on the schema AST.
417
- *
418
- * Handles camelCase → wire_name mapping for path params (HttpPath), query params (HttpQuery),
419
- * and header params (HttpHeader).
420
- *
421
- * When `inputSchema` is provided, uses `Schema.encodeSync` to encode the input through the
422
- * schema's encoding pipeline (e.g., `encodeKeys` for camelCase → snake_case mapping).
423
- * The encoded output is used for body construction, ensuring wire-format key names.
424
- */
425
- /**
426
- * Recursively unwrap any `Redacted<T>` values in a structure into their
427
- * underlying `T`.
428
- *
429
- * Sensitive response fields surface to callers as `Redacted<string>` (so
430
- * they don't accidentally land in logs). Those same values often need to be
431
- * passed straight back into a follow-up request — e.g. WorkOS's password
432
- * reset flow returns a redacted `password_reset_token` whose shape is
433
- * `Redacted<string>` and which is then sent into `ResetPassword({ token })`,
434
- * where `token` is declared as plain `Schema.String`. Without this unwrap
435
- * the input encoder sees a `Redacted` (whose toString is `"<redacted>"`)
436
- * and rejects the value with `Expected string, got <redacted>`.
437
- *
438
- * Doing the unwrap right before `Schema.encodeSync` keeps the contract
439
- * simple: callers can hand a `Redacted` to any field and the wire payload
440
- * still contains the underlying value. Schemas that *want* a `Redacted` on
441
- * the wire (i.e. `SensitiveString`) handle it through their own encode
442
- * transform, so they're unaffected — by the time encodeSync sees the value
443
- * it's already a plain string, which is what the wire format wants anyway.
444
- */
445
- const unwrapRedactedDeep = (value) => {
446
- if (Redacted.isRedacted(value))
447
- return Redacted.value(value);
448
- if (Array.isArray(value))
449
- return value.map(unwrapRedactedDeep);
450
- if (value !== null && typeof value === "object") {
451
- // Only walk into plain objects. Builtins like File, Blob, FormData,
452
- // ArrayBuffer, TypedArrays, Map/Set, Date, Streams, etc. don't contain
453
- // Redacted values and would be destroyed by Object.entries() — `new
454
- // File([], "x")` has no own enumerable keys, so a recursive copy returns
455
- // `{}` and the schema encoder later rejects the empty object with
456
- // "Expected File, got {}". Preserve any non-plain object as-is.
457
- const proto = Object.getPrototypeOf(value);
458
- if (proto !== null && proto !== Object.prototype)
459
- return value;
460
- const out = {};
461
- for (const [k, v] of Object.entries(value)) {
462
- out[k] = unwrapRedactedDeep(v);
463
- }
464
- return out;
465
- }
466
- return value;
467
- };
468
- /**
469
- * RFC 6570 §3.2.3 reserved-expansion: encode everything outside the RFC 3986
470
- * unreserved (`A-Za-z0-9-._~`) and reserved (`:/?#[]@!$&'()*+,;=`) sets.
471
- */
472
- const RFC3986_NEEDS_ENCODING = /[^A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=]/g;
473
- const encodeReserved = (v) => v.replace(RFC3986_NEEDS_ENCODING, encodeURIComponent);
474
- const isPlainObject = (v) => {
475
- if (typeof v !== "object" || v === null || Array.isArray(v))
476
- return false;
477
- const proto = Object.getPrototypeOf(v);
478
- return proto === Object.prototype || proto === null;
479
- };
480
- /**
481
- * Serialize a query-param value onto `query`, flattening plain objects
482
- * using OpenAPI `deepObject`-style dot notation.
483
- *
484
- * Several Cloudflare list endpoints model their filters as nested structs
485
- * (e.g. DNS `listRecords` takes `name: { exact, contains, ... }`) that must
486
- * go over the wire as `name.exact=value`. Previously these fell through to
487
- * `String(value)` and were sent as `name=[object Object]`, which the server
488
- * happily treats as a filter that matches nothing — the call "succeeds"
489
- * with zero results and the bug is invisible to the caller.
490
- *
491
- * Scalars and arrays keep their existing serialization (`k=v` /
492
- * repeated `k=v` pairs). Nested plain objects recurse, so deeper filter
493
- * shapes flatten to `a.b.c=value`. `undefined`/`null` members are skipped
494
- * like top-level params. Non-plain objects (class instances, `Date`, …)
495
- * keep the legacy `String(value)` behavior.
496
- */
497
- const setQueryValue = (query, wireName, value) => {
498
- if (Array.isArray(value)) {
499
- query[wireName] = value.map(String);
500
- }
501
- else if (isPlainObject(value)) {
502
- for (const [key, member] of Object.entries(value)) {
503
- if (member === undefined || member === null)
504
- continue;
505
- setQueryValue(query, `${wireName}.${key}`, member);
506
- }
507
- }
508
- else {
509
- query[wireName] = String(value);
510
- }
511
- };
512
- export const buildRequestParts = (ast, httpTrait, rawInput,
513
- // biome-ignore lint: using any for generic schema parameter
514
- inputSchema) => {
515
- // Unwrap any `Redacted<T>` values in the input up front so the schema
516
- // encoder never sees them. See `unwrapRedactedDeep` for rationale.
517
- const input = unwrapRedactedDeep(rawInput);
518
- let path = httpTrait.path;
519
- const query = {};
520
- const headers = {};
521
- let rawBody = undefined;
522
- let hasRawBody = false;
523
- const isMultipart = httpTrait.contentType === "multipart";
524
- // Track which TS property names are path/query/header params (not body)
525
- const nonBodyKeys = new Set();
526
- const props = getStructProps(ast);
527
- for (const prop of props) {
528
- const tsName = String(prop.name);
529
- const value = input[tsName];
530
- if (value === undefined || value === null) {
531
- continue;
532
- }
533
- // Path parameter — `{+name}` is RFC 6570 reserved-expansion (preserves
534
- // `/` and other RFC 3986 reserved chars); `{name}` is simple expansion.
535
- const pathWireName = getPathParamWireName(prop);
536
- if (pathWireName !== undefined) {
537
- nonBodyKeys.add(tsName);
538
- const reservedPlaceholder = `{+${pathWireName}}`;
539
- if (path.includes(reservedPlaceholder)) {
540
- path = path.replace(reservedPlaceholder, encodeReserved(String(value)));
541
- }
542
- else {
543
- path = path.replace(`{${pathWireName}}`, encodeURIComponent(String(value)));
544
- }
545
- continue;
546
- }
547
- // Query parameter
548
- const queryParam = getQueryParam(prop);
549
- if (queryParam !== undefined) {
550
- nonBodyKeys.add(tsName);
551
- const wireName = typeof queryParam === "string" ? queryParam : tsName;
552
- setQueryValue(query, wireName, value);
553
- continue;
554
- }
555
- // Header parameter
556
- const headerParam = getHeaderParam(prop);
557
- if (headerParam !== undefined) {
558
- nonBodyKeys.add(tsName);
559
- headers[headerParam] = String(value);
560
- continue;
561
- }
562
- // Body field (HttpBody annotation means this IS the entire body)
563
- const isBodyField = getAnnotation(prop.type, httpBodySymbol);
564
- if (isBodyField) {
565
- rawBody = value;
566
- hasRawBody = true;
567
- nonBodyKeys.add(tsName);
568
- continue;
569
- }
570
- }
571
- // Build body from remaining (non-path/query/header) properties
572
- let finalBody;
573
- if (hasRawBody) {
574
- // For HttpBody fields, encode through the schema to get wire-format keys
575
- // (e.g., camelCase → snake_case via encodeKeys on nested schemas)
576
- if (inputSchema) {
577
- const encoded = Schema.encodeSync(inputSchema)(input);
578
- const encodedRecord = encoded;
579
- // Find the body field name in the encoded output
580
- for (const prop of props) {
581
- const tsName = String(prop.name);
582
- const isBody = getAnnotation(prop.type, httpBodySymbol);
583
- if (isBody && encodedRecord[tsName] !== undefined) {
584
- finalBody = encodedRecord[tsName];
585
- break;
586
- }
587
- }
588
- // Fallback to raw body if encoding didn't produce it
589
- if (finalBody === undefined) {
590
- finalBody = rawBody;
591
- }
592
- }
593
- else {
594
- finalBody = rawBody;
595
- }
596
- }
597
- else {
598
- // Encode the input through the schema to get wire-format keys
599
- // This handles encodeKeys (camelCase → snake_case) and any other encoding transforms
600
- if (inputSchema) {
601
- const encoded = Schema.encodeSync(inputSchema)(input);
602
- const encodedRecord = encoded;
603
- // Build a mapping from tsName → encoded key name
604
- // by encoding a minimal test object to discover key mappings
605
- const bodyFromEncoded = {};
606
- let hasBodyFields = false;
607
- for (const [key, value] of Object.entries(encodedRecord)) {
608
- // Check if this encoded key corresponds to a non-body TS property
609
- // by seeing if any non-body prop encodes to this key
610
- let isNonBody = false;
611
- for (const nbKey of nonBodyKeys) {
612
- // Simple heuristic: if the encoded key matches the non-body key or its encoding
613
- if (key === nbKey) {
614
- isNonBody = true;
615
- break;
616
- }
617
- }
618
- if (!isNonBody && value !== undefined) {
619
- bodyFromEncoded[key] = value;
620
- hasBodyFields = true;
621
- }
622
- }
623
- finalBody = hasBodyFields ? bodyFromEncoded : undefined;
624
- }
625
- else {
626
- // Fallback: no schema encoding, use TS property names as-is (for backwards compat)
627
- const body = {};
628
- let hasBody = false;
629
- for (const prop of props) {
630
- const tsName = String(prop.name);
631
- if (nonBodyKeys.has(tsName))
632
- continue;
633
- const value = input[tsName];
634
- if (value === undefined || value === null)
635
- continue;
636
- body[tsName] = value;
637
- hasBody = true;
638
- }
639
- finalBody = hasBody ? body : undefined;
640
- }
641
- }
642
- return {
643
- path,
644
- query,
645
- headers,
646
- body: finalBody,
647
- isMultipart,
648
- };
649
- };
650
- /**
651
- * Build the response object for a binary-download operation
652
- * (`T.Http({ responseContentType: "binary" })`).
653
- *
654
- * The output schema is expected to be a Struct with one field annotated
655
- * `T.BinaryResponseBody()` (the `body` field — populated with the supplied
656
- * `Stream`) and zero-or-more sibling fields annotated
657
- * `T.HttpResponseHeader(name)` (populated by reading the named response
658
- * header). Header lookups are case-insensitive.
659
- *
660
- * Header values are coerced to the field's declared primitive type so that
661
- * `content-length` lands as a `number`, `last-modified` as a `Date` (when
662
- * the schema declares `Schema.Date`), etc. Anything more exotic stays a
663
- * raw string.
664
- */
665
- export const buildBinaryResponse = (ast, body, responseHeaders) => {
666
- const lowercased = {};
667
- for (const [k, v] of Object.entries(responseHeaders)) {
668
- lowercased[k.toLowerCase()] = v;
669
- }
670
- const props = getStructProps(ast);
671
- const result = {};
672
- for (const prop of props) {
673
- const tsName = String(prop.name);
674
- const isBody = getAnnotation(prop.type, binaryResponseBodySymbol);
675
- if (isBody) {
676
- result[tsName] = body;
677
- continue;
678
- }
679
- const headerName = getAnnotation(prop.type, responseHeaderSymbol);
680
- if (headerName !== undefined) {
681
- const raw = lowercased[headerName.toLowerCase()];
682
- if (raw === undefined)
683
- continue;
684
- result[tsName] = coerceHeaderValue(raw, prop.type);
685
- }
686
- }
687
- return result;
688
- };
689
- /**
690
- * Best-effort coercion of a raw HTTP header string to whichever primitive
691
- * the response schema declares. Falls back to the original string for
692
- * anything we don't recognize — the schema's decode step (which the binary
693
- * runtime path skips) would have done the same coercion for JSON bodies.
694
- */
695
- const coerceHeaderValue = (raw, propType) => {
696
- // Walk through Suspends / Optionals / Encoded chains to the underlying type.
697
- let inner = propType;
698
- while (inner.encoding && inner.encoding.length > 0) {
699
- inner = inner.encoding[0].to;
700
- }
701
- if (inner._tag === "Suspend")
702
- inner = inner.thunk();
703
- // `Schema.optional(Schema.X)` shows up as a Union with `undefined`/void.
704
- if (inner._tag === "Union") {
705
- const nonOptional = inner.types.find((t) => t._tag !== "Void" && t._tag !== "Never");
706
- if (nonOptional)
707
- inner = nonOptional;
708
- }
709
- if (inner._tag === "Number") {
710
- const n = Number(raw);
711
- return Number.isFinite(n) ? n : raw;
712
- }
713
- if (inner._tag === "Boolean") {
714
- if (raw === "true")
715
- return true;
716
- if (raw === "false")
717
- return false;
718
- return raw;
719
- }
720
- return raw;
721
- };
722
- /**
723
- * Helper to get a value from an object using a dot-separated path.
724
- * Used for pagination traits and nested property access.
725
- */
726
- export const getPath = (obj, path) => {
727
- const parts = path.split(".");
728
- let current = obj;
729
- for (const part of parts) {
730
- if (current == null || typeof current !== "object") {
731
- return undefined;
732
- }
733
- current = current[part];
734
- }
735
- return current;
736
- };
737
- //# sourceMappingURL=traits.js.map