@superblocksteam/sdk-api 2.0.165-next.0 → 2.0.166-next.0
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.
- package/README.md +1 -2
- package/dist/errors.d.ts +36 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +244 -8
- package/dist/errors.js.map +1 -1
- package/dist/errors.test.d.ts +2 -0
- package/dist/errors.test.d.ts.map +1 -0
- package/dist/errors.test.js +189 -0
- package/dist/errors.test.js.map +1 -0
- package/dist/integrations/base/decode-worker-binary-response.d.ts.map +1 -1
- package/dist/integrations/base/decode-worker-binary-response.js +2 -5
- package/dist/integrations/base/decode-worker-binary-response.js.map +1 -1
- package/dist/integrations/base/index.d.ts +2 -1
- package/dist/integrations/base/index.d.ts.map +1 -1
- package/dist/integrations/base/index.js +1 -0
- package/dist/integrations/base/index.js.map +1 -1
- package/dist/integrations/base/request-body.d.ts +29 -0
- package/dist/integrations/base/request-body.d.ts.map +1 -0
- package/dist/integrations/base/request-body.js +238 -0
- package/dist/integrations/base/request-body.js.map +1 -0
- package/dist/integrations/base/request-body.test.d.ts +2 -0
- package/dist/integrations/base/request-body.test.d.ts.map +1 -0
- package/dist/integrations/base/request-body.test.js +466 -0
- package/dist/integrations/base/request-body.test.js.map +1 -0
- package/dist/integrations/base/rest-api-client-base.d.ts.map +1 -1
- package/dist/integrations/base/rest-api-client-base.js +15 -14
- package/dist/integrations/base/rest-api-client-base.js.map +1 -1
- package/dist/integrations/base/rest-api-integration-client.d.ts +2 -2
- package/dist/integrations/base/rest-api-integration-client.d.ts.map +1 -1
- package/dist/integrations/base/rest-api-integration-client.js +5 -6
- package/dist/integrations/base/rest-api-integration-client.js.map +1 -1
- package/dist/integrations/base/types.d.ts +55 -11
- package/dist/integrations/base/types.d.ts.map +1 -1
- package/dist/integrations/base/types.js +7 -0
- package/dist/integrations/base/types.js.map +1 -1
- package/dist/integrations/cosmosdb/client.d.ts.map +1 -1
- package/dist/integrations/cosmosdb/client.js +2 -5
- package/dist/integrations/cosmosdb/client.js.map +1 -1
- package/dist/integrations/documentation-resolver.test.js +106 -1
- package/dist/integrations/documentation-resolver.test.js.map +1 -1
- package/dist/integrations/dynamodb/client.d.ts.map +1 -1
- package/dist/integrations/dynamodb/client.js +2 -5
- package/dist/integrations/dynamodb/client.js.map +1 -1
- package/dist/integrations/gcs/client.d.ts.map +1 -1
- package/dist/integrations/gcs/client.js +2 -5
- package/dist/integrations/gcs/client.js.map +1 -1
- package/dist/integrations/gsheets/client.d.ts.map +1 -1
- package/dist/integrations/gsheets/client.js +2 -5
- package/dist/integrations/gsheets/client.js.map +1 -1
- package/dist/integrations/mongodb/client.d.ts.map +1 -1
- package/dist/integrations/mongodb/client.js +2 -5
- package/dist/integrations/mongodb/client.js.map +1 -1
- package/dist/integrations/restapiintegration/client.body-types.test.d.ts +2 -0
- package/dist/integrations/restapiintegration/client.body-types.test.d.ts.map +1 -0
- package/dist/integrations/restapiintegration/client.body-types.test.js +227 -0
- package/dist/integrations/restapiintegration/client.body-types.test.js.map +1 -0
- package/dist/integrations/restapiintegration/client.test.js +56 -30
- package/dist/integrations/restapiintegration/client.test.js.map +1 -1
- package/dist/integrations/s3/client.d.ts.map +1 -1
- package/dist/integrations/s3/client.js +2 -5
- package/dist/integrations/s3/client.js.map +1 -1
- package/dist/integrations/salesforce/client.d.ts.map +1 -1
- package/dist/integrations/salesforce/client.js +2 -5
- package/dist/integrations/salesforce/client.js.map +1 -1
- package/dist/integrations/slack/client.d.ts.map +1 -1
- package/dist/integrations/slack/client.js +4 -13
- package/dist/integrations/slack/client.js.map +1 -1
- package/dist/integrations/slack/client.test.js +20 -0
- package/dist/integrations/slack/client.test.js.map +1 -1
- package/dist/integrations/utils.d.ts +8 -3
- package/dist/integrations/utils.d.ts.map +1 -1
- package/dist/integrations/utils.js +42 -1
- package/dist/integrations/utils.js.map +1 -1
- package/package.json +2 -2
- package/src/errors.test.ts +257 -0
- package/src/errors.ts +304 -10
- package/src/integrations/base/decode-worker-binary-response.ts +5 -7
- package/src/integrations/base/index.ts +3 -0
- package/src/integrations/base/request-body.test.ts +565 -0
- package/src/integrations/base/request-body.ts +392 -0
- package/src/integrations/base/rest-api-client-base.ts +24 -19
- package/src/integrations/base/rest-api-integration-client.ts +14 -10
- package/src/integrations/base/types.ts +66 -11
- package/src/integrations/box/README.md +4 -60
- package/src/integrations/cosmosdb/client.ts +8 -7
- package/src/integrations/documentation-resolver.test.ts +130 -1
- package/src/integrations/dropbox/README.md +1 -71
- package/src/integrations/dropbox/docs.manifest.json +10 -1
- package/src/integrations/dropbox/overlays/upload-unsupported.md +3 -0
- package/src/integrations/dropbox/overlays/upload.md +89 -0
- package/src/integrations/dynamodb/client.ts +8 -7
- package/src/integrations/elasticsearch/README.md +0 -80
- package/src/integrations/elasticsearch/docs.manifest.json +10 -1
- package/src/integrations/elasticsearch/overlays/bulk-unsupported.md +3 -0
- package/src/integrations/elasticsearch/overlays/bulk.md +80 -0
- package/src/integrations/gcs/client.ts +8 -7
- package/src/integrations/googledrive/README.md +10 -36
- package/src/integrations/gsheets/client.ts +8 -7
- package/src/integrations/jira/README.md +0 -26
- package/src/integrations/jira/docs.manifest.json +10 -1
- package/src/integrations/jira/overlays/attachments-unsupported.md +3 -0
- package/src/integrations/jira/overlays/attachments.md +30 -0
- package/src/integrations/lakebase/README.md +1 -3
- package/src/integrations/mongodb/client.ts +8 -7
- package/src/integrations/postgres/README.md +1 -3
- package/src/integrations/restapiintegration/client.body-types.test.ts +323 -0
- package/src/integrations/restapiintegration/client.test.ts +68 -32
- package/src/integrations/restapiintegration/docs.manifest.json +8 -0
- package/src/integrations/restapiintegration/overlays/request-body-types-unsupported.md +7 -0
- package/src/integrations/restapiintegration/overlays/request-body-types.md +115 -0
- package/src/integrations/restapiintegration/overlays/response-types-binary.md +4 -8
- package/src/integrations/s3/client.ts +8 -7
- package/src/integrations/salesforce/client.ts +9 -7
- package/src/integrations/slack/client.test.ts +30 -0
- package/src/integrations/slack/client.ts +13 -19
- package/src/integrations/snowflakepostgres/README.md +1 -3
- package/src/integrations/stabilityai/README.md +0 -87
- package/src/integrations/stabilityai/docs.manifest.json +10 -1
- package/src/integrations/stabilityai/overlays/image-uploads-unsupported.md +3 -0
- package/src/integrations/stabilityai/overlays/image-uploads.md +120 -0
- package/src/integrations/stripe/README.md +0 -201
- package/src/integrations/stripe/docs.manifest.json +10 -1
- package/src/integrations/stripe/overlays/request-bodies-unsupported.md +3 -0
- package/src/integrations/stripe/overlays/request-bodies.md +204 -0
- package/src/integrations/utils.ts +51 -1
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
import type { PartialMessage } from "@bufbuild/protobuf";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
import type { Property } from "@superblocksteam/types/dist/src/common/v1/plugin_pb";
|
|
5
|
+
|
|
6
|
+
import { findBinaryDataPath, isBinaryData } from "../../errors.js";
|
|
7
|
+
import { describeOptionValue, validationError } from "../utils.js";
|
|
8
|
+
import { REST_API_BODY_TYPES } from "./types.js";
|
|
9
|
+
|
|
10
|
+
type BinaryBody = ArrayBuffer | ArrayBufferView;
|
|
11
|
+
|
|
12
|
+
type RequestBodyWireType =
|
|
13
|
+
| "jsonBody"
|
|
14
|
+
| "rawBody"
|
|
15
|
+
| "formDataBase64"
|
|
16
|
+
| "binaryBody";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Fields safe to spread directly onto the proto `RestApiRequest`. Never
|
|
20
|
+
* carries `contentType`: that is a header directive, not a wire field, and
|
|
21
|
+
* lives on `EncodedRequestBody` instead so a caller cannot spread it onto
|
|
22
|
+
* the wire message by mistake.
|
|
23
|
+
*/
|
|
24
|
+
export type RequestBodyWireFields = {
|
|
25
|
+
readonly body?: string;
|
|
26
|
+
readonly formData?: PartialMessage<Property>[];
|
|
27
|
+
readonly bodyType?: RequestBodyWireType;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The encoder's full result: wire fields plus an optional Content-Type the
|
|
32
|
+
* caller must push onto request headers itself.
|
|
33
|
+
*/
|
|
34
|
+
export type EncodedRequestBody = {
|
|
35
|
+
readonly wire: RequestBodyWireFields;
|
|
36
|
+
readonly contentType?: string;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const requestBodyTypeSchema = z.enum(REST_API_BODY_TYPES);
|
|
40
|
+
|
|
41
|
+
export function encodeRequestBody(input: {
|
|
42
|
+
body: unknown;
|
|
43
|
+
bodyType?: unknown;
|
|
44
|
+
headers?: Record<string, string>;
|
|
45
|
+
}): EncodedRequestBody {
|
|
46
|
+
const bodyTypeResult = requestBodyTypeSchema.safeParse(
|
|
47
|
+
input.bodyType === undefined ? "json" : input.bodyType,
|
|
48
|
+
);
|
|
49
|
+
if (!bodyTypeResult.success) {
|
|
50
|
+
throw validationError(
|
|
51
|
+
`Unsupported bodyType ${describeOptionValue(input.bodyType)} - expected one of: ${REST_API_BODY_TYPES.join(", ")}`,
|
|
52
|
+
["bodyType"],
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const bodyType = bodyTypeResult.data;
|
|
57
|
+
if (input.body === undefined) {
|
|
58
|
+
if (bodyType === "json") return { wire: {} };
|
|
59
|
+
throw validationError(`bodyType "${bodyType}" requires a request body`, [
|
|
60
|
+
"body",
|
|
61
|
+
]);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
switch (bodyType) {
|
|
65
|
+
case "json":
|
|
66
|
+
return { wire: encodeJsonBody(input.body) };
|
|
67
|
+
case "raw":
|
|
68
|
+
return { wire: encodeRawBody(input.body) };
|
|
69
|
+
case "formUrlencoded":
|
|
70
|
+
return encodeFormUrlencodedBody(input.body, input.headers);
|
|
71
|
+
case "multipartForm":
|
|
72
|
+
return { wire: encodeMultipartFormBody(input.body, input.headers) };
|
|
73
|
+
case "binary":
|
|
74
|
+
return encodeBinaryBody(input.body, input.headers);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// JSON.stringify's own error text is unbounded: a circular-structure message
|
|
79
|
+
// embeds the caller's full property path and constructor names, and a
|
|
80
|
+
// throwing toJSON()/getter contributes an arbitrary caller-authored string.
|
|
81
|
+
// Every other message in this module goes through describeOptionValue's
|
|
82
|
+
// bounded conventions; classify the failure instead of echoing its text.
|
|
83
|
+
function describeJsonSerializationFailure(error: unknown): string {
|
|
84
|
+
if (
|
|
85
|
+
error instanceof TypeError &&
|
|
86
|
+
/circular (structure|reference)/i.test(error.message)
|
|
87
|
+
) {
|
|
88
|
+
return "the body contains a circular reference";
|
|
89
|
+
}
|
|
90
|
+
if (error instanceof TypeError && /BigInt/i.test(error.message)) {
|
|
91
|
+
return "the body contains a BigInt value";
|
|
92
|
+
}
|
|
93
|
+
return "a nested value's toJSON, toString, or getter threw while serializing the body";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function encodeJsonBody(body: unknown): RequestBodyWireFields {
|
|
97
|
+
if (isBinaryData(body)) {
|
|
98
|
+
throw validationError('Binary request bodies require bodyType: "binary"', [
|
|
99
|
+
"body",
|
|
100
|
+
]);
|
|
101
|
+
}
|
|
102
|
+
// The walk itself only ever throws MAX_BINARY_SCAN_DEPTH's RangeError
|
|
103
|
+
// (see errors.ts); anything else (a throwing getter, an unusual toJSON)
|
|
104
|
+
// is left for JSON.stringify to judge below, which reports the same
|
|
105
|
+
// failure as a serialization error. A depth-capped walk fails closed
|
|
106
|
+
// instead: treat the body as containing binary at an unknown location
|
|
107
|
+
// rather than assume none, because JSON.stringify does not throw on a
|
|
108
|
+
// Uint8Array/Buffer/typed array -- the exact shape this check exists to
|
|
109
|
+
// catch -- it silently serializes them into digit-keyed garbage.
|
|
110
|
+
let binaryPath: (string | number)[] | undefined;
|
|
111
|
+
try {
|
|
112
|
+
binaryPath = findBinaryDataPath(body, isBinaryData);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
binaryPath = error instanceof RangeError ? [] : undefined;
|
|
115
|
+
}
|
|
116
|
+
if (binaryPath !== undefined) {
|
|
117
|
+
const location =
|
|
118
|
+
binaryPath.length > 0
|
|
119
|
+
? ` at ${describeOptionValue(binaryPath.join("."))}`
|
|
120
|
+
: "";
|
|
121
|
+
throw validationError(
|
|
122
|
+
`bodyType "json" request body contains binary data${location}; send file parts with bodyType: "multipartForm" as { value, filename }, or send bytes alone with bodyType: "binary"`,
|
|
123
|
+
["body", ...binaryPath],
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
let serialized: string | undefined;
|
|
127
|
+
try {
|
|
128
|
+
serialized = JSON.stringify(body);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
throw validationError(
|
|
131
|
+
`bodyType "json" request body is not JSON-serializable: ${describeJsonSerializationFailure(error)}`,
|
|
132
|
+
["body"],
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
if (serialized === undefined) {
|
|
136
|
+
throw validationError(
|
|
137
|
+
`bodyType "json" cannot serialize a ${typeof body} request body`,
|
|
138
|
+
["body"],
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
return { body: serialized, bodyType: "jsonBody" };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function encodeRawBody(body: unknown): RequestBodyWireFields {
|
|
145
|
+
if (typeof body !== "string" || body.length === 0) {
|
|
146
|
+
throw validationError(
|
|
147
|
+
'bodyType "raw" requires a non-empty string request body',
|
|
148
|
+
["body"],
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
return { body, bodyType: "rawBody" };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// A field's value may be a scalar or an array; either way, undefined items
|
|
155
|
+
// (an explicitly-undefined optional field, or an undefined array element)
|
|
156
|
+
// are omitted rather than encoded, matching JSON.stringify's default-body
|
|
157
|
+
// semantics. Shared by encodeFormUrlencodedBody and encodeMultipartFormBody.
|
|
158
|
+
function definedArrayValues(value: unknown): unknown[] {
|
|
159
|
+
return (Array.isArray(value) ? value : [value]).filter(
|
|
160
|
+
(item) => item !== undefined,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function encodeFormUrlencodedBody(
|
|
165
|
+
body: unknown,
|
|
166
|
+
headers: Record<string, string> | undefined,
|
|
167
|
+
): EncodedRequestBody {
|
|
168
|
+
if (!isPlainRecord(body)) {
|
|
169
|
+
throw validationError(
|
|
170
|
+
'bodyType "formUrlencoded" requires a plain object request body',
|
|
171
|
+
["body"],
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
const pairs: string[] = [];
|
|
175
|
+
for (const [key, value] of Object.entries(body)) {
|
|
176
|
+
if (value === undefined) continue;
|
|
177
|
+
if (key.length === 0) {
|
|
178
|
+
throw validationError(
|
|
179
|
+
"formUrlencoded body keys must be non-empty strings",
|
|
180
|
+
["body", key],
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
const encodedKey = formUrlencode(key, key);
|
|
184
|
+
for (const item of definedArrayValues(value)) {
|
|
185
|
+
pairs.push(
|
|
186
|
+
`${encodedKey}=${formUrlencode(formUrlencodedPrimitiveToString(key, item), key)}`,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (pairs.length === 0) {
|
|
191
|
+
throw validationError(
|
|
192
|
+
"formUrlencoded body must encode at least one field",
|
|
193
|
+
["body"],
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
wire: { body: pairs.join("&"), bodyType: "rawBody" },
|
|
198
|
+
contentType: contentTypeIfMissing(
|
|
199
|
+
headers,
|
|
200
|
+
"application/x-www-form-urlencoded",
|
|
201
|
+
),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// The WASM sdk-api sandbox has no URLSearchParams global, so encode by hand.
|
|
206
|
+
// encodeURIComponent's unreserved set leaves `! ' ( ) ~` unescaped, but the
|
|
207
|
+
// WHATWG application/x-www-form-urlencoded safe set (what URLSearchParams
|
|
208
|
+
// produces) escapes those five; only alphanumerics, `* - . _`, and space
|
|
209
|
+
// (as `+`) stay literal.
|
|
210
|
+
function formUrlencode(value: string, key: string): string {
|
|
211
|
+
try {
|
|
212
|
+
return encodeURIComponent(value)
|
|
213
|
+
.replace(/%20/g, "+")
|
|
214
|
+
.replace(
|
|
215
|
+
/[!'()~]/g,
|
|
216
|
+
(char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
|
|
217
|
+
);
|
|
218
|
+
} catch {
|
|
219
|
+
throw validationError(
|
|
220
|
+
`formUrlencoded field ${describeOptionValue(key)} contains a lone surrogate and cannot be percent-encoded`,
|
|
221
|
+
["body", key],
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function formUrlencodedPrimitiveToString(key: string, value: unknown): string {
|
|
227
|
+
if (typeof value === "string" || typeof value === "boolean")
|
|
228
|
+
return String(value);
|
|
229
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
230
|
+
if (typeof value === "object" && value !== null) {
|
|
231
|
+
throw validationError(
|
|
232
|
+
`formUrlencoded field ${describeOptionValue(key)} is nested; flatten it using bracket notation such as "metadata[order_id]"`,
|
|
233
|
+
["body", key],
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
throw validationError(
|
|
237
|
+
`formUrlencoded field ${describeOptionValue(key)} must be a string, finite number, boolean, or array of those values`,
|
|
238
|
+
["body", key],
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function encodeBinaryBody(
|
|
243
|
+
body: unknown,
|
|
244
|
+
headers: Record<string, string> | undefined,
|
|
245
|
+
): EncodedRequestBody {
|
|
246
|
+
if (!isBinaryData(body)) {
|
|
247
|
+
throw validationError(
|
|
248
|
+
'bodyType "binary" requires an ArrayBuffer or ArrayBufferView request body',
|
|
249
|
+
["body"],
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
if (body.byteLength === 0) {
|
|
253
|
+
throw validationError("binary request bodies must be non-empty", ["body"]);
|
|
254
|
+
}
|
|
255
|
+
return {
|
|
256
|
+
wire: { body: toBuffer(body).toString("base64"), bodyType: "binaryBody" },
|
|
257
|
+
contentType: contentTypeIfMissing(headers, "application/octet-stream"),
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function encodeMultipartFormBody(
|
|
262
|
+
body: unknown,
|
|
263
|
+
headers: Record<string, string> | undefined,
|
|
264
|
+
): RequestBodyWireFields {
|
|
265
|
+
if (hasHeader(headers, "content-type")) {
|
|
266
|
+
throw validationError(
|
|
267
|
+
"multipartForm bodies cannot provide Content-Type because the multipart boundary is generated at execution time",
|
|
268
|
+
["headers", "Content-Type"],
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
if (!isPlainRecord(body)) {
|
|
272
|
+
throw validationError(
|
|
273
|
+
'bodyType "multipartForm" requires a plain object request body',
|
|
274
|
+
["body"],
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
const formData = Object.entries(body).flatMap(([key, value]) =>
|
|
278
|
+
definedArrayValues(value).map((item) => parseMultipartPart(key, item)),
|
|
279
|
+
);
|
|
280
|
+
if (formData.length === 0) {
|
|
281
|
+
throw validationError("multipartForm body must encode at least one field", [
|
|
282
|
+
"body",
|
|
283
|
+
]);
|
|
284
|
+
}
|
|
285
|
+
return { bodyType: "formDataBase64", formData };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function parseMultipartPart(
|
|
289
|
+
key: string,
|
|
290
|
+
value: unknown,
|
|
291
|
+
): PartialMessage<Property> {
|
|
292
|
+
if (key.length === 0)
|
|
293
|
+
throw validationError("multipartForm body keys must be non-empty strings", [
|
|
294
|
+
"body",
|
|
295
|
+
key,
|
|
296
|
+
]);
|
|
297
|
+
if (
|
|
298
|
+
typeof value === "string" ||
|
|
299
|
+
typeof value === "boolean" ||
|
|
300
|
+
(typeof value === "number" && Number.isFinite(value))
|
|
301
|
+
) {
|
|
302
|
+
return { key, value: String(value) };
|
|
303
|
+
}
|
|
304
|
+
if (isBinaryData(value)) {
|
|
305
|
+
throw validationError(
|
|
306
|
+
`multipartForm binary field ${describeOptionValue(key)} must be wrapped as { value, filename }`,
|
|
307
|
+
["body", key],
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
if (!isPlainRecord(value)) {
|
|
311
|
+
throw validationError(
|
|
312
|
+
`multipartForm field ${describeOptionValue(key)} must be a primitive value or { value, filename } file part`,
|
|
313
|
+
["body", key],
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
const keys = Object.keys(value).filter(
|
|
317
|
+
(partKey) => value[partKey] !== undefined,
|
|
318
|
+
);
|
|
319
|
+
const missingKeys = ["value", "filename"].filter(
|
|
320
|
+
(requiredKey) => !keys.includes(requiredKey),
|
|
321
|
+
);
|
|
322
|
+
if (missingKeys.length > 0) {
|
|
323
|
+
throw validationError(
|
|
324
|
+
`multipartForm file part ${describeOptionValue(key)} is missing required ${pluralize("key", missingKeys)}: ${missingKeys.join(", ")}`,
|
|
325
|
+
["body", key],
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
const unexpectedKeys = keys.filter(
|
|
329
|
+
(partKey) => partKey !== "value" && partKey !== "filename",
|
|
330
|
+
);
|
|
331
|
+
if (unexpectedKeys.length > 0) {
|
|
332
|
+
const shown = unexpectedKeys.slice(0, 5).map(describeOptionValue);
|
|
333
|
+
const suffix = unexpectedKeys.length > 5 ? ", ..." : "";
|
|
334
|
+
throw validationError(
|
|
335
|
+
`multipartForm file part ${describeOptionValue(key)} has unexpected ${pluralize("key", unexpectedKeys)}: ${shown.join(", ")}${suffix}`,
|
|
336
|
+
["body", key],
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
if (typeof value.filename !== "string" || value.filename.length === 0) {
|
|
340
|
+
throw validationError(
|
|
341
|
+
`multipartForm file part ${describeOptionValue(key)} requires a non-empty filename`,
|
|
342
|
+
["body", key, "filename"],
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
if (typeof value.value !== "string" && !isBinaryData(value.value)) {
|
|
346
|
+
throw validationError(
|
|
347
|
+
`multipartForm file part ${describeOptionValue(key)} value must be a string or binary body`,
|
|
348
|
+
["body", key, "value"],
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
return {
|
|
352
|
+
key,
|
|
353
|
+
value: toBuffer(value.value).toString("base64"),
|
|
354
|
+
file: { filename: value.filename },
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
359
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
360
|
+
return false;
|
|
361
|
+
const prototype = Object.getPrototypeOf(value);
|
|
362
|
+
return prototype === Object.prototype || prototype === null;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function toBuffer(value: string | BinaryBody): Buffer {
|
|
366
|
+
if (typeof value === "string") return Buffer.from(value, "utf8");
|
|
367
|
+
if (value instanceof ArrayBuffer) return Buffer.from(value);
|
|
368
|
+
return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function contentTypeIfMissing(
|
|
372
|
+
headers: Record<string, string> | undefined,
|
|
373
|
+
value: string,
|
|
374
|
+
): string | undefined {
|
|
375
|
+
return hasHeader(headers, "content-type") ? undefined : value;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function hasHeader(
|
|
379
|
+
headers: Record<string, string> | undefined,
|
|
380
|
+
headerName: string,
|
|
381
|
+
): boolean {
|
|
382
|
+
return (
|
|
383
|
+
!!headers &&
|
|
384
|
+
Object.keys(headers).some(
|
|
385
|
+
(key) => key.toLowerCase() === headerName.toLowerCase(),
|
|
386
|
+
)
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function pluralize(word: string, values: readonly unknown[]): string {
|
|
391
|
+
return values.length === 1 ? word : `${word}s`;
|
|
392
|
+
}
|
|
@@ -4,10 +4,15 @@ import { z } from "zod";
|
|
|
4
4
|
import type { Property } from "@superblocksteam/types/dist/src/common/v1/plugin_pb";
|
|
5
5
|
import type { Plugin as RestApiIntegrationPlugin } from "@superblocksteam/types/dist/src/plugins/restapiintegration/v1/plugin_pb";
|
|
6
6
|
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
RestApiValidationError,
|
|
9
|
+
restApiValidationErrorFromZodError,
|
|
10
|
+
} from "../../errors.js";
|
|
8
11
|
import type { QueryExecutor, TraceMetadata } from "../registry.js";
|
|
9
12
|
import type { IntegrationConfig, IntegrationClientImpl } from "../types.js";
|
|
13
|
+
import { describeOptionValue, validationError } from "../utils.js";
|
|
10
14
|
import { decodeWorkerBinaryResponse } from "./decode-worker-binary-response.js";
|
|
15
|
+
import { encodeRequestBody } from "./request-body.js";
|
|
11
16
|
import { REST_API_RESPONSE_TYPES } from "./types.js";
|
|
12
17
|
import type { ApiRequestOptions } from "./types.js";
|
|
13
18
|
|
|
@@ -45,12 +50,10 @@ export abstract class RestApiClientBase implements IntegrationClientImpl {
|
|
|
45
50
|
if (options.body !== undefined && bodySchema) {
|
|
46
51
|
const bodyParseResult = bodySchema.safeParse(options.body);
|
|
47
52
|
if (!bodyParseResult.success) {
|
|
48
|
-
throw
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
data: options.body,
|
|
53
|
-
},
|
|
53
|
+
throw restApiValidationErrorFromZodError(
|
|
54
|
+
"Request body validation failed",
|
|
55
|
+
bodyParseResult.error,
|
|
56
|
+
options.body,
|
|
54
57
|
);
|
|
55
58
|
}
|
|
56
59
|
}
|
|
@@ -73,16 +76,22 @@ export abstract class RestApiClientBase implements IntegrationClientImpl {
|
|
|
73
76
|
.enum(REST_API_RESPONSE_TYPES)
|
|
74
77
|
.safeParse(options.responseType ?? "json");
|
|
75
78
|
if (!responseTypeResult.success) {
|
|
76
|
-
throw
|
|
77
|
-
`Unsupported responseType ${
|
|
78
|
-
|
|
79
|
-
zodError: responseTypeResult.error,
|
|
80
|
-
data: options.responseType,
|
|
81
|
-
},
|
|
79
|
+
throw validationError(
|
|
80
|
+
`Unsupported responseType ${describeOptionValue(options.responseType)} - expected one of: ${REST_API_RESPONSE_TYPES.join(", ")}`,
|
|
81
|
+
["responseType"],
|
|
82
82
|
);
|
|
83
83
|
}
|
|
84
84
|
const responseType = responseTypeResult.data;
|
|
85
85
|
|
|
86
|
+
const { wire: bodyWire, contentType } = encodeRequestBody({
|
|
87
|
+
body: options.body,
|
|
88
|
+
bodyType: options.bodyType,
|
|
89
|
+
headers: options.headers,
|
|
90
|
+
});
|
|
91
|
+
if (contentType !== undefined) {
|
|
92
|
+
headers.push(this.createParam("Content-Type", contentType));
|
|
93
|
+
}
|
|
94
|
+
|
|
86
95
|
const request: RestApiRequest = {
|
|
87
96
|
openApiAction: "genericHttpRequest",
|
|
88
97
|
httpMethod: options.method.toUpperCase(),
|
|
@@ -90,14 +99,10 @@ export abstract class RestApiClientBase implements IntegrationClientImpl {
|
|
|
90
99
|
headers,
|
|
91
100
|
params,
|
|
92
101
|
responseType,
|
|
102
|
+
...bodyWire,
|
|
93
103
|
};
|
|
94
104
|
|
|
95
|
-
|
|
96
|
-
request.body = JSON.stringify(options.body);
|
|
97
|
-
request.bodyType = "jsonBody";
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
const result = await this.executeQuery({ ...request }, undefined, metadata);
|
|
105
|
+
const result = await this.executeQuery(request, undefined, metadata);
|
|
101
106
|
|
|
102
107
|
if (result === null || result === undefined) {
|
|
103
108
|
throw new RestApiValidationError(
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
RestApiValidationError,
|
|
5
|
+
restApiValidationErrorFromZodError,
|
|
6
|
+
} from "../../errors.js";
|
|
4
7
|
import type { TraceMetadata } from "../registry.js";
|
|
5
8
|
import { RestApiClientBase } from "./rest-api-client-base.js";
|
|
6
9
|
import type {
|
|
7
10
|
ApiRequestOptions,
|
|
8
11
|
ApiRequestSchema,
|
|
12
|
+
BinaryApiRequestSchema,
|
|
9
13
|
RestApiResponseType,
|
|
10
14
|
SupportsApiRequest,
|
|
11
15
|
} from "./types.js";
|
|
@@ -27,7 +31,7 @@ export abstract class RestApiIntegrationClient
|
|
|
27
31
|
options: ApiRequestOptions<TBody> & {
|
|
28
32
|
responseType: "binary";
|
|
29
33
|
},
|
|
30
|
-
schema?:
|
|
34
|
+
schema?: BinaryApiRequestSchema<TBody>,
|
|
31
35
|
metadata?: TraceMetadata,
|
|
32
36
|
): Promise<Uint8Array>;
|
|
33
37
|
async apiRequest<TBody>(
|
|
@@ -39,7 +43,7 @@ export abstract class RestApiIntegrationClient
|
|
|
39
43
|
): Promise<unknown>;
|
|
40
44
|
async apiRequest<TBody, TResponse>(
|
|
41
45
|
options: ApiRequestOptions<TBody>,
|
|
42
|
-
schema?: ApiRequestSchema<TBody, TResponse>,
|
|
46
|
+
schema?: ApiRequestSchema<TBody, TResponse> | BinaryApiRequestSchema<TBody>,
|
|
43
47
|
metadata?: TraceMetadata,
|
|
44
48
|
): Promise<TResponse | Uint8Array | unknown> {
|
|
45
49
|
if ((options.responseType ?? "json") === "json" && !schema?.response) {
|
|
@@ -64,19 +68,19 @@ export abstract class RestApiIntegrationClient
|
|
|
64
68
|
metadata,
|
|
65
69
|
);
|
|
66
70
|
|
|
67
|
-
|
|
71
|
+
// Binary bodies are validated while decoding. A caller's schema cannot
|
|
72
|
+
// check them: the sandbox's Uint8Array is not the SDK's constructor.
|
|
73
|
+
if (options.responseType === "binary" || !schema?.response) {
|
|
68
74
|
return result;
|
|
69
75
|
}
|
|
70
76
|
|
|
71
77
|
const responseParseResult = schema.response.safeParse(result);
|
|
72
78
|
|
|
73
79
|
if (!responseParseResult.success) {
|
|
74
|
-
throw
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
zodError: responseParseResult.error,
|
|
79
|
-
},
|
|
80
|
+
throw restApiValidationErrorFromZodError(
|
|
81
|
+
"Response validation failed",
|
|
82
|
+
responseParseResult.error,
|
|
83
|
+
result,
|
|
80
84
|
);
|
|
81
85
|
}
|
|
82
86
|
|
|
@@ -8,6 +8,16 @@ export const REST_API_RESPONSE_TYPES = ["binary", "json", "text"] as const;
|
|
|
8
8
|
|
|
9
9
|
export type RestApiResponseType = (typeof REST_API_RESPONSE_TYPES)[number];
|
|
10
10
|
|
|
11
|
+
export const REST_API_BODY_TYPES = [
|
|
12
|
+
"json",
|
|
13
|
+
"raw",
|
|
14
|
+
"formUrlencoded",
|
|
15
|
+
"multipartForm",
|
|
16
|
+
"binary",
|
|
17
|
+
] as const;
|
|
18
|
+
|
|
19
|
+
export type RestApiBodyType = (typeof REST_API_BODY_TYPES)[number];
|
|
20
|
+
|
|
11
21
|
export interface ApiRequestOptions<TBody = unknown> {
|
|
12
22
|
/**
|
|
13
23
|
* HTTP method for the request.
|
|
@@ -25,6 +35,18 @@ export interface ApiRequestOptions<TBody = unknown> {
|
|
|
25
35
|
*/
|
|
26
36
|
body?: TBody;
|
|
27
37
|
|
|
38
|
+
/**
|
|
39
|
+
* How the request body should be encoded. Defaults to `"json"`.
|
|
40
|
+
*
|
|
41
|
+
* Use `"raw"` for caller-encoded string bodies, `"formUrlencoded"` for
|
|
42
|
+
* `application/x-www-form-urlencoded` payloads, `"multipartForm"` for
|
|
43
|
+
* multipart form fields and file parts, and `"binary"` for byte payloads.
|
|
44
|
+
* Worker wire values such as `"jsonBody"`, `"rawBody"`, `"formData"`,
|
|
45
|
+
* `"fileForm"`, `"binaryBody"`, and `"formDataBase64"` are not public SDK
|
|
46
|
+
* `bodyType` values.
|
|
47
|
+
*/
|
|
48
|
+
bodyType?: RestApiBodyType;
|
|
49
|
+
|
|
28
50
|
/**
|
|
29
51
|
* Optional query parameters
|
|
30
52
|
*/
|
|
@@ -39,10 +61,10 @@ export interface ApiRequestOptions<TBody = unknown> {
|
|
|
39
61
|
* How the response body should be decoded. Defaults to `"json"`.
|
|
40
62
|
*
|
|
41
63
|
* Use `"text"` for endpoints that return non-JSON payloads such as
|
|
42
|
-
* XML. Use `"binary"` for PDFs and other byte payloads.
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
* `
|
|
64
|
+
* XML. Use `"binary"` for PDFs and other byte payloads. Text responses
|
|
65
|
+
* may omit the response schema or use one matching the decoded value,
|
|
66
|
+
* e.g. `z.string()`. Binary responses never take a response schema; the
|
|
67
|
+
* decoded `Uint8Array` is already validated.
|
|
46
68
|
*/
|
|
47
69
|
responseType?: RestApiResponseType;
|
|
48
70
|
}
|
|
@@ -61,19 +83,41 @@ export interface ApiRequestSchema<TBody = unknown, TResponse = unknown> {
|
|
|
61
83
|
response?: z.ZodSchema<TResponse>;
|
|
62
84
|
}
|
|
63
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Schemas accepted by `apiRequest()` with `responseType: "binary"`.
|
|
88
|
+
*
|
|
89
|
+
* There is no response schema: the SDK decodes and validates the bytes
|
|
90
|
+
* itself. API code runs in a sandbox whose `Uint8Array` is a different
|
|
91
|
+
* constructor from the SDK's, so `z.instanceof(Uint8Array)` would reject
|
|
92
|
+
* every binary response. A `response` passed at runtime is ignored.
|
|
93
|
+
*/
|
|
94
|
+
export interface BinaryApiRequestSchema<TBody = unknown> {
|
|
95
|
+
/**
|
|
96
|
+
* Optional Zod schema for request body validation.
|
|
97
|
+
* When omitted, `options.body` is sent without validation.
|
|
98
|
+
*/
|
|
99
|
+
body?: z.ZodSchema<TBody>;
|
|
100
|
+
|
|
101
|
+
response?: never;
|
|
102
|
+
}
|
|
103
|
+
|
|
64
104
|
/**
|
|
65
105
|
* Interface for integration clients that support generic API requests.
|
|
66
106
|
*
|
|
67
|
-
* Providing a response schema gives type-safe, validated results. Omitting
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
107
|
+
* Providing a response schema gives type-safe, validated results. Omitting it
|
|
108
|
+
* returns the decoded response: `Uint8Array` for `responseType: "binary"`, or
|
|
109
|
+
* `unknown` for `responseType: "text"`. JSON still requires a schema. Object
|
|
110
|
+
* schemas only make sense for JSON-shaped results.
|
|
111
|
+
*
|
|
112
|
+
* Request bodies default to JSON. Set `bodyType` to one of `"json"`, `"raw"`,
|
|
113
|
+
* `"formUrlencoded"`, `"multipartForm"`, or `"binary"` when the endpoint
|
|
114
|
+
* expects a different request encoding.
|
|
71
115
|
*/
|
|
72
116
|
export interface SupportsApiRequest {
|
|
73
117
|
/**
|
|
74
118
|
* Execute a generic API request with type-safe validation.
|
|
75
119
|
*
|
|
76
|
-
* @param options - Request configuration including method, path, params, and
|
|
120
|
+
* @param options - Request configuration including method, path, params, body, and bodyType
|
|
77
121
|
* @param schema - Zod schemas for request body and response validation
|
|
78
122
|
* @param metadata - Optional trace metadata for observability (label, description)
|
|
79
123
|
* @returns Validated response data
|
|
@@ -101,6 +145,16 @@ export interface SupportsApiRequest {
|
|
|
101
145
|
* { label: 'slack.postMessage', description: 'Post a message to #alerts' }
|
|
102
146
|
* );
|
|
103
147
|
* // result is typed as { ts: string; channel: string }
|
|
148
|
+
*
|
|
149
|
+
* await ctx.integrations.stripe.apiRequest(
|
|
150
|
+
* {
|
|
151
|
+
* method: 'POST',
|
|
152
|
+
* path: '/v1/charges',
|
|
153
|
+
* bodyType: 'formUrlencoded',
|
|
154
|
+
* body: { amount: 2000, currency: 'usd' },
|
|
155
|
+
* },
|
|
156
|
+
* { response: StripeChargeSchema }
|
|
157
|
+
* );
|
|
104
158
|
* ```
|
|
105
159
|
*/
|
|
106
160
|
apiRequest<TBody, TResponse>(
|
|
@@ -117,7 +171,8 @@ export interface SupportsApiRequest {
|
|
|
117
171
|
* Execute a generic API request that returns binary data.
|
|
118
172
|
*
|
|
119
173
|
* @param options - Request configuration; `responseType` must be "binary"
|
|
120
|
-
* @param schema - Optional Zod
|
|
174
|
+
* @param schema - Optional Zod schema for request body validation. Binary
|
|
175
|
+
* responses do not take a response schema.
|
|
121
176
|
* @param metadata - Optional trace metadata for observability (label, description)
|
|
122
177
|
* @returns The decoded body as a `Uint8Array`
|
|
123
178
|
*
|
|
@@ -135,7 +190,7 @@ export interface SupportsApiRequest {
|
|
|
135
190
|
options: ApiRequestOptions<TBody> & {
|
|
136
191
|
responseType: "binary";
|
|
137
192
|
},
|
|
138
|
-
schema?:
|
|
193
|
+
schema?: BinaryApiRequestSchema<TBody>,
|
|
139
194
|
metadata?: TraceMetadata,
|
|
140
195
|
): Promise<Uint8Array>;
|
|
141
196
|
|