@powerhousedao/pieces-framework 6.2.3-dev.100

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/dist/common.js ADDED
@@ -0,0 +1,852 @@
1
+ import { n as Property, o as assertNotNullOrUndefined, y as createAction } from "./input-BHkj_oP5.js";
2
+ import { c as isNil$1, r as tryCatchSync, s as isEmpty } from "./markdown-property-DMfHjEiL.js";
3
+ import * as z from "zod/mini";
4
+ import { PassThrough, Readable } from "node:stream";
5
+ import fs from "node:fs";
6
+
7
+ //#region upstream/common/lib/authentication/index.ts
8
+ let AuthenticationType = /* @__PURE__ */ function(AuthenticationType) {
9
+ AuthenticationType["BEARER_TOKEN"] = "BEARER_TOKEN";
10
+ AuthenticationType["BASIC"] = "BASIC";
11
+ return AuthenticationType;
12
+ }({});
13
+
14
+ //#endregion
15
+ //#region upstream/common/lib/http/core/http-header.ts
16
+ let HttpHeader = /* @__PURE__ */ function(HttpHeader) {
17
+ HttpHeader["AUTHORIZATION"] = "Authorization";
18
+ HttpHeader["ACCEPT"] = "Accept";
19
+ HttpHeader["API_KEY"] = "x-api-key";
20
+ HttpHeader["CONTENT_TYPE"] = "Content-Type";
21
+ return HttpHeader;
22
+ }({});
23
+
24
+ //#endregion
25
+ //#region upstream/common/lib/http/core/media-type.ts
26
+ let MediaType = /* @__PURE__ */ function(MediaType) {
27
+ MediaType["APPLICATION_JSON"] = "application/json";
28
+ MediaType["TEXT_CSV"] = "text/csv";
29
+ return MediaType;
30
+ }({});
31
+
32
+ //#endregion
33
+ //#region upstream/common/lib/http/core/base-http-client.ts
34
+ var BaseHttpClient = class {
35
+ baseUrl;
36
+ authenticationConverter;
37
+ constructor(baseUrl, authenticationConverter) {
38
+ this.baseUrl = baseUrl;
39
+ this.authenticationConverter = authenticationConverter;
40
+ }
41
+ getUrl(request) {
42
+ const url = new URL(`${this.baseUrl}${request.url}`);
43
+ const urlWithoutQueryParams = `${url.origin}${url.pathname}`;
44
+ const queryParams = new URLSearchParams();
45
+ url.searchParams.forEach((value, key) => {
46
+ queryParams.append(key, value);
47
+ });
48
+ return {
49
+ urlWithoutQueryParams,
50
+ queryParams
51
+ };
52
+ }
53
+ getHeaders(request) {
54
+ let requestHeaders = { ["Accept"]: "application/json" };
55
+ if (request.authentication) this.populateAuthentication(request.authentication, requestHeaders);
56
+ if (request.body) switch (request.headers?.["Content-Type"]) {
57
+ case "text/csv":
58
+ requestHeaders["Content-Type"] = "text/csv";
59
+ break;
60
+ default: requestHeaders["Content-Type"] = "application/json";
61
+ }
62
+ if (request.headers) requestHeaders = {
63
+ ...requestHeaders,
64
+ ...request.headers
65
+ };
66
+ return requestHeaders;
67
+ }
68
+ populateAuthentication(authentication, headers) {
69
+ this.authenticationConverter.convert(authentication, headers);
70
+ }
71
+ };
72
+
73
+ //#endregion
74
+ //#region upstream/common/lib/http/core/delegating-authentication-converter.ts
75
+ var DelegatingAuthenticationConverter = class {
76
+ converters;
77
+ constructor(bearerTokenConverter = new BearerTokenAuthenticationConverter(), basicTokenConverter = new BasicTokenAuthenticationConverter()) {
78
+ this.converters = {
79
+ ["BEARER_TOKEN"]: bearerTokenConverter,
80
+ ["BASIC"]: basicTokenConverter
81
+ };
82
+ }
83
+ convert(authentication, headers) {
84
+ return this.converters[authentication.type].convert(authentication, headers);
85
+ }
86
+ };
87
+ var BearerTokenAuthenticationConverter = class {
88
+ convert(authentication, headers) {
89
+ headers["Authorization"] = `Bearer ${authentication.token}`;
90
+ return headers;
91
+ }
92
+ };
93
+ var BasicTokenAuthenticationConverter = class {
94
+ convert(authentication, headers) {
95
+ const credentials = `${authentication.username}:${authentication.password}`;
96
+ const encoded = Buffer.from(credentials).toString("base64");
97
+ headers["Authorization"] = `Basic ${encoded}`;
98
+ return headers;
99
+ }
100
+ };
101
+
102
+ //#endregion
103
+ //#region upstream/common/lib/http/core/http-error.ts
104
+ var HttpError = class extends Error {
105
+ requestBody;
106
+ status;
107
+ responseBody;
108
+ constructor(requestBody, params) {
109
+ const status = params.status || 500;
110
+ const responseBody = Buffer.isBuffer(params.responseBody) ? params.responseBody.toString() : params.responseBody;
111
+ super(JSON.stringify({
112
+ response: {
113
+ status,
114
+ body: responseBody
115
+ },
116
+ request: { body: requestBody }
117
+ }));
118
+ this.requestBody = requestBody;
119
+ this.status = status;
120
+ this.responseBody = responseBody;
121
+ }
122
+ errorMessage() {
123
+ return {
124
+ response: {
125
+ status: this.status,
126
+ body: this.responseBody
127
+ },
128
+ request: { body: this.requestBody }
129
+ };
130
+ }
131
+ get response() {
132
+ return {
133
+ status: this.status,
134
+ body: this.responseBody
135
+ };
136
+ }
137
+ get request() {
138
+ return { body: this.requestBody };
139
+ }
140
+ };
141
+ function toFailsafeOutput({ error, requestBody }) {
142
+ if (error instanceof HttpError) return error.errorMessage();
143
+ return {
144
+ response: {
145
+ status: 0,
146
+ body: error instanceof Error ? error.message : String(error)
147
+ },
148
+ request: { body: requestBody }
149
+ };
150
+ }
151
+
152
+ //#endregion
153
+ //#region upstream/common/lib/http/core/http-method.ts
154
+ let HttpMethod = /* @__PURE__ */ function(HttpMethod) {
155
+ HttpMethod["GET"] = "GET";
156
+ HttpMethod["POST"] = "POST";
157
+ HttpMethod["PATCH"] = "PATCH";
158
+ HttpMethod["PUT"] = "PUT";
159
+ HttpMethod["DELETE"] = "DELETE";
160
+ HttpMethod["HEAD"] = "HEAD";
161
+ return HttpMethod;
162
+ }({});
163
+
164
+ //#endregion
165
+ //#region upstream/common/lib/http/core/fetch-http-client.ts
166
+ var FetchHttpClient = class extends BaseHttpClient {
167
+ constructor(baseUrl = "", authenticationConverter = new DelegatingAuthenticationConverter()) {
168
+ super(baseUrl, authenticationConverter);
169
+ }
170
+ async sendRequest(request, options) {
171
+ const { urlWithoutQueryParams, queryParams: urlQueryParams } = this.getUrl(request);
172
+ const requestHeaders = this.getHeaders(request);
173
+ const headers = isNativeFormData(request.body) ? withoutContentType(requestHeaders) : requestHeaders;
174
+ const queryParams = request.queryParams ?? {};
175
+ for (const [key, value] of Object.entries(queryParams)) urlQueryParams.append(key, value);
176
+ const queryString = urlQueryParams.toString();
177
+ const finalUrl = queryString ? `${urlWithoutQueryParams}?${queryString}` : urlWithoutQueryParams;
178
+ const responseType = request.responseType ?? "json";
179
+ const followRedirects = request.followRedirects ?? true;
180
+ const retries = request.retries ?? 0;
181
+ const { body, extraHeaders, isStream } = acceptsRequestBody(request.method) ? serializeBody(request.body, headers) : {
182
+ body: void 0,
183
+ extraHeaders: {},
184
+ isStream: false
185
+ };
186
+ const finalHeaders = normalizeHeaders({
187
+ ...headers,
188
+ ...extraHeaders
189
+ });
190
+ const response = await sendWithRetries(async () => {
191
+ const controller = new AbortController();
192
+ const timeoutId = request.timeout && request.timeout > 0 ? setTimeout(() => controller.abort(), request.timeout) : void 0;
193
+ try {
194
+ const init = {
195
+ method: request.method.toString(),
196
+ headers: finalHeaders,
197
+ body,
198
+ redirect: followRedirects ? "follow" : "manual",
199
+ signal: controller.signal
200
+ };
201
+ if (isStream) init.duplex = "half";
202
+ if (options?.dispatcher !== void 0) init.dispatcher = options.dispatcher;
203
+ return await fetch(finalUrl, init);
204
+ } finally {
205
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
206
+ }
207
+ }, isStream ? 0 : retries);
208
+ const successCeiling = followRedirects ? 300 : 400;
209
+ if (response.status < 200 || response.status >= successCeiling) {
210
+ const errorBody = await parseResponseBody(response, responseType === "stream" ? "text" : responseType);
211
+ throw new HttpError(request.redactBodyInErrors === true ? REDACTED_BODY : request.body, {
212
+ status: response.status,
213
+ responseBody: errorBody
214
+ });
215
+ }
216
+ const responseBody = await parseResponseBody(response, responseType);
217
+ return {
218
+ status: response.status,
219
+ headers: toHttpHeaders(response.headers),
220
+ body: responseBody
221
+ };
222
+ }
223
+ };
224
+ const REDACTED_BODY = "[redacted]";
225
+ function acceptsRequestBody(method) {
226
+ return method !== "GET" && method !== "HEAD";
227
+ }
228
+ function serializeBody(body, headers) {
229
+ if (isNil(body)) return {
230
+ body: void 0,
231
+ extraHeaders: {},
232
+ isStream: false
233
+ };
234
+ if (isNodeFormData(body)) {
235
+ const buffered = bufferFormDataIfSafe(body);
236
+ if (buffered !== null) return {
237
+ body: buffered,
238
+ extraHeaders: body.getHeaders(),
239
+ isStream: false
240
+ };
241
+ const stream = new PassThrough();
242
+ body.on("error", (error) => stream.destroy(error));
243
+ body.pipe(stream);
244
+ return {
245
+ body: stream,
246
+ extraHeaders: body.getHeaders(),
247
+ isStream: true
248
+ };
249
+ }
250
+ if (body instanceof Readable) return {
251
+ body,
252
+ extraHeaders: {},
253
+ isStream: true
254
+ };
255
+ if (typeof body === "string" || Buffer.isBuffer(body) || body instanceof URLSearchParams || body instanceof ArrayBuffer || isNativeFormData(body) || typeof Blob !== "undefined" && body instanceof Blob) return {
256
+ body,
257
+ extraHeaders: {},
258
+ isStream: false
259
+ };
260
+ if ((headers["Content-Type"] ?? headers["content-type"] ?? "").includes("application/x-www-form-urlencoded")) return {
261
+ body: new URLSearchParams(body).toString(),
262
+ extraHeaders: {},
263
+ isStream: false
264
+ };
265
+ return {
266
+ body: JSON.stringify(body),
267
+ extraHeaders: {},
268
+ isStream: false
269
+ };
270
+ }
271
+ async function parseResponseBody(response, responseType) {
272
+ switch (responseType) {
273
+ case "arraybuffer": return Buffer.from(await response.arrayBuffer());
274
+ case "stream": return isNil(response.body) ? Readable.from([]) : Readable.fromWeb(response.body);
275
+ case "blob": return await response.blob();
276
+ case "text": return await response.text();
277
+ default: {
278
+ const text = await response.text();
279
+ if (text.length === 0) return;
280
+ try {
281
+ return JSON.parse(text);
282
+ } catch {
283
+ return text;
284
+ }
285
+ }
286
+ }
287
+ }
288
+ async function sendWithRetries(fn, retries) {
289
+ let lastError;
290
+ for (let attempt = 0; attempt <= retries; attempt++) try {
291
+ const response = await fn();
292
+ if (response.status >= 500 && attempt < retries) {
293
+ await backoff(attempt);
294
+ continue;
295
+ }
296
+ return response;
297
+ } catch (error) {
298
+ lastError = error;
299
+ if (attempt < retries) {
300
+ await backoff(attempt);
301
+ continue;
302
+ }
303
+ throw error;
304
+ }
305
+ throw lastError;
306
+ }
307
+ function backoff(attempt) {
308
+ const delayMs = Math.min(1e3 * 2 ** attempt, 3e4);
309
+ return new Promise((resolve) => setTimeout(resolve, delayMs));
310
+ }
311
+ function normalizeHeaders(headers) {
312
+ const entriesByLowerCaseKey = /* @__PURE__ */ new Map();
313
+ for (const [key, value] of Object.entries(headers)) {
314
+ if (value === void 0) continue;
315
+ entriesByLowerCaseKey.set(key.toLowerCase(), [key, Array.isArray(value) ? value.join(", ") : value]);
316
+ }
317
+ return Object.fromEntries(entriesByLowerCaseKey.values());
318
+ }
319
+ function toHttpHeaders(headers) {
320
+ const result = {};
321
+ headers.forEach((value, key) => {
322
+ result[key] = value;
323
+ });
324
+ return result;
325
+ }
326
+ function bufferFormDataIfSafe(body) {
327
+ if (!body.hasKnownLength() || body.getLengthSync() > MAX_BUFFERED_FORM_DATA_BYTES) return null;
328
+ const { data } = tryCatchSync(() => body.getBuffer());
329
+ return data;
330
+ }
331
+ function isNodeFormData(body) {
332
+ return typeof body === "object" && body !== null && typeof body.getHeaders === "function" && typeof body.pipe === "function" && typeof body.on === "function";
333
+ }
334
+ function isNativeFormData(body) {
335
+ return typeof FormData !== "undefined" && body instanceof FormData;
336
+ }
337
+ function withoutContentType(headers) {
338
+ return Object.fromEntries(Object.entries(headers).filter(([key]) => key.toLowerCase() !== "content-type"));
339
+ }
340
+ function isNil(value) {
341
+ return value === null || value === void 0;
342
+ }
343
+ const MAX_BUFFERED_FORM_DATA_BYTES = 104857600;
344
+
345
+ //#endregion
346
+ //#region upstream/common/lib/http/core/http-client.ts
347
+ const httpClient = new FetchHttpClient();
348
+
349
+ //#endregion
350
+ //#region upstream/common/lib/helpers/index.ts
351
+ const CONTENT_TYPE_EXTENSIONS = {
352
+ "application/json": "json",
353
+ "application/pdf": "pdf",
354
+ "application/xml": "xml",
355
+ "text/xml": "xml",
356
+ "application/zip": "zip",
357
+ "application/gzip": "gz",
358
+ "application/x-tar": "tar",
359
+ "application/octet-stream": "bin",
360
+ "application/msword": "doc",
361
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
362
+ "application/vnd.ms-excel": "xls",
363
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
364
+ "application/vnd.ms-powerpoint": "ppt",
365
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
366
+ "application/rtf": "rtf",
367
+ "application/javascript": "js",
368
+ "application/x-www-form-urlencoded": "bin",
369
+ "text/plain": "txt",
370
+ "text/html": "html",
371
+ "text/css": "css",
372
+ "text/csv": "csv",
373
+ "text/calendar": "ics",
374
+ "text/markdown": "md",
375
+ "image/png": "png",
376
+ "image/jpeg": "jpeg",
377
+ "image/jpg": "jpg",
378
+ "image/gif": "gif",
379
+ "image/webp": "webp",
380
+ "image/svg+xml": "svg",
381
+ "image/bmp": "bmp",
382
+ "image/tiff": "tiff",
383
+ "image/x-icon": "ico",
384
+ "image/vnd.microsoft.icon": "ico",
385
+ "image/heic": "heic",
386
+ "audio/mpeg": "mp3",
387
+ "audio/mp4": "m4a",
388
+ "audio/wav": "wav",
389
+ "audio/x-wav": "wav",
390
+ "audio/ogg": "ogg",
391
+ "audio/webm": "weba",
392
+ "video/mp4": "mp4",
393
+ "video/mpeg": "mpeg",
394
+ "video/webm": "webm",
395
+ "video/quicktime": "mov",
396
+ "video/x-msvideo": "avi",
397
+ "font/woff": "woff",
398
+ "font/woff2": "woff2",
399
+ "font/ttf": "ttf",
400
+ "font/otf": "otf"
401
+ };
402
+ function contentTypeToExtension(contentType) {
403
+ const type = contentType.split(";")[0].trim().toLowerCase();
404
+ return CONTENT_TYPE_EXTENSIONS[type] ?? "";
405
+ }
406
+ const getAccessTokenOrThrow = (auth) => {
407
+ const accessToken = auth?.access_token;
408
+ if (accessToken === void 0) throw new Error("Invalid bearer token");
409
+ return accessToken;
410
+ };
411
+ const joinBaseUrlWithRelativePath = ({ baseUrl, relativePath }) => {
412
+ return `${baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`}${relativePath.startsWith("/") ? relativePath.slice(1) : relativePath}`;
413
+ };
414
+ const getBaseUrlForDescription = (baseUrl, auth) => {
415
+ const exampleBaseUrl = `https://api.example.com`;
416
+ try {
417
+ const baseUrlValue = auth ? baseUrl(auth) : void 0;
418
+ return (baseUrlValue?.endsWith("/") ? baseUrlValue.slice(0, -1) : baseUrlValue) ?? exampleBaseUrl;
419
+ } catch (error) {
420
+ return exampleBaseUrl;
421
+ }
422
+ };
423
+ function createCustomApiCallAction({ auth, baseUrl, authMapping, description, displayName, name, props, extraProps, authLocation = "headers", classification = "WRITE" }) {
424
+ return createAction({
425
+ audience: "human",
426
+ name: name ? name : "custom_api_call",
427
+ classification,
428
+ displayName: displayName ? displayName : "Custom API Call",
429
+ description: description ? description : "Make a custom API call to a specific endpoint",
430
+ auth,
431
+ requireAuth: auth ? true : false,
432
+ props: {
433
+ url: Property.DynamicProperties({
434
+ auth,
435
+ displayName: "",
436
+ required: true,
437
+ refreshers: [],
438
+ props: async ({ auth }) => {
439
+ return { url: Property.ShortText({
440
+ displayName: "URL",
441
+ description: `Full URL, or a path relative to ${getBaseUrlForDescription(baseUrl, auth)}`,
442
+ required: true,
443
+ placeholder: "/resource",
444
+ defaultValue: auth ? baseUrl(auth) : "",
445
+ ...props?.url ?? {}
446
+ }) };
447
+ }
448
+ }),
449
+ method: Property.StaticDropdown({
450
+ displayName: "Method",
451
+ required: true,
452
+ defaultValue: "GET",
453
+ options: { options: Object.values(HttpMethod).map((v) => {
454
+ return {
455
+ label: v,
456
+ value: v
457
+ };
458
+ }) },
459
+ ...props?.method ?? {}
460
+ }),
461
+ headers: Property.Object({
462
+ displayName: "Headers",
463
+ description: "Authorization headers are injected automatically from your connection.",
464
+ required: false,
465
+ ...props?.headers ?? {}
466
+ }),
467
+ queryParams: Property.Object({
468
+ displayName: "Query Parameters",
469
+ description: "Appended to the URL as ?key=value.",
470
+ required: false,
471
+ ...props?.queryParams ?? {}
472
+ }),
473
+ body_type: Property.Dropdown({
474
+ auth,
475
+ displayName: "Body Type",
476
+ required: false,
477
+ defaultValue: "none",
478
+ refreshers: ["method"],
479
+ options: async ({ method }) => {
480
+ if (!acceptsRequestBody(method)) return {
481
+ disabled: true,
482
+ placeholder: "Not available for GET or HEAD requests",
483
+ options: []
484
+ };
485
+ return {
486
+ disabled: false,
487
+ options: [
488
+ {
489
+ label: "None",
490
+ value: "none"
491
+ },
492
+ {
493
+ label: "JSON",
494
+ value: "json"
495
+ },
496
+ {
497
+ label: "Form Data",
498
+ value: "form_data"
499
+ },
500
+ {
501
+ label: "Raw",
502
+ value: "raw"
503
+ }
504
+ ]
505
+ };
506
+ }
507
+ }),
508
+ body: Property.DynamicProperties({
509
+ auth,
510
+ displayName: "Body",
511
+ refreshers: ["body_type", "method"],
512
+ required: false,
513
+ props: async ({ body_type, method }) => {
514
+ if (!body_type || !acceptsRequestBody(method)) return {};
515
+ const bodyTypeInput = body_type;
516
+ const fields = {};
517
+ switch (bodyTypeInput) {
518
+ case "none": break;
519
+ case "json":
520
+ fields["data"] = Property.Json({
521
+ displayName: "JSON Body",
522
+ required: true,
523
+ ...props?.body ?? {}
524
+ });
525
+ break;
526
+ case "raw":
527
+ fields["data"] = Property.LongText({
528
+ displayName: "Raw Body",
529
+ required: true
530
+ });
531
+ break;
532
+ case "form_data": fields["data"] = Property.Array({
533
+ displayName: "Form Data",
534
+ required: true,
535
+ properties: {
536
+ fieldName: Property.ShortText({
537
+ displayName: "Field Name",
538
+ required: true
539
+ }),
540
+ fieldType: Property.StaticDropdown({
541
+ displayName: "Field Type",
542
+ required: true,
543
+ options: {
544
+ disabled: false,
545
+ options: [{
546
+ label: "Text",
547
+ value: "text"
548
+ }, {
549
+ label: "File",
550
+ value: "file"
551
+ }]
552
+ }
553
+ }),
554
+ textFieldValue: Property.LongText({
555
+ displayName: "Text Field Value",
556
+ required: false
557
+ }),
558
+ fileFieldValue: Property.File({
559
+ displayName: "File Field Value",
560
+ required: false
561
+ })
562
+ }
563
+ });
564
+ }
565
+ return fields;
566
+ }
567
+ }),
568
+ response_is_binary: Property.Checkbox({
569
+ displayName: "Response is Binary",
570
+ description: "Enable for files like PDFs, images, etc.",
571
+ required: false,
572
+ defaultValue: false,
573
+ advanced: true,
574
+ ...props?.response_is_binary ?? {}
575
+ }),
576
+ failsafe: Property.Checkbox({
577
+ displayName: "Return Error as Output",
578
+ description: "On a failed request, output the error instead of failing the step.",
579
+ required: false,
580
+ advanced: true,
581
+ ...props?.failsafe ?? {}
582
+ }),
583
+ timeout: Property.Number({
584
+ displayName: "Timeout",
585
+ description: "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
586
+ required: false,
587
+ advanced: true,
588
+ ...props?.timeout ?? {}
589
+ }),
590
+ followRedirects: Property.Checkbox({
591
+ displayName: "Follow redirects",
592
+ description: "Follow 3xx redirects instead of returning them as the response.",
593
+ required: false,
594
+ defaultValue: false,
595
+ advanced: true,
596
+ ...props?.followRedirects ?? {}
597
+ }),
598
+ ...extraProps
599
+ },
600
+ propertyGroups: [{
601
+ key: "request",
602
+ display: "section",
603
+ label: "Request",
604
+ icon: "send",
605
+ props: [
606
+ "method",
607
+ "url",
608
+ "headers",
609
+ "queryParams"
610
+ ]
611
+ }, {
612
+ key: "payload",
613
+ display: "section",
614
+ label: "Data to send",
615
+ icon: "code",
616
+ props: ["body_type", "body"]
617
+ }],
618
+ run: async (context) => {
619
+ const { method, url, headers, queryParams, body, body_type, failsafe, timeout, response_is_binary, followRedirects } = context.propsValue;
620
+ assertNotNullOrUndefined(method, "Method");
621
+ assertNotNullOrUndefined(url, "URL");
622
+ const authValue = !isNil$1(authMapping) ? await authMapping(context.auth, context.propsValue) : {};
623
+ const urlValue = url["url"];
624
+ const request = {
625
+ method,
626
+ url: urlValue.startsWith("http://") || urlValue.startsWith("https://") ? urlValue : joinBaseUrlWithRelativePath({
627
+ baseUrl: baseUrl(context.auth),
628
+ relativePath: urlValue
629
+ }),
630
+ headers: {
631
+ ...headers ?? {},
632
+ ...authLocation === "headers" ? authValue : {}
633
+ },
634
+ queryParams: {
635
+ ...authLocation === "queryParams" ? authValue : {},
636
+ ...queryParams ?? {}
637
+ },
638
+ timeout: timeout ? timeout * 1e3 : 0,
639
+ followRedirects
640
+ };
641
+ if (response_is_binary) request.responseType = "arraybuffer";
642
+ if (body) {
643
+ if (body_type && body_type !== "none") {
644
+ const bodyInput = body["data"];
645
+ if (body_type === "form_data") {
646
+ const formBodyInput = bodyInput;
647
+ const { default: FormData } = await import("form-data");
648
+ const formData = new FormData();
649
+ for (const { fieldName, fieldType, textFieldValue, fileFieldValue } of formBodyInput) if (fieldType === "text" && !isEmpty(textFieldValue)) formData.append(fieldName, textFieldValue);
650
+ else if (fieldType === "file" && !isEmpty(fileFieldValue)) formData.append(fieldName, fileFieldValue.data, { filename: fileFieldValue?.filename });
651
+ request.body = formData;
652
+ request.headers = {
653
+ ...request.headers,
654
+ ...formData.getHeaders()
655
+ };
656
+ } else request.body = bodyInput;
657
+ } else if (!body_type) request.body = body;
658
+ }
659
+ try {
660
+ const response = await httpClient.sendRequest(request);
661
+ return await handleBinaryResponse(context.files, response.body, response.status, response.headers, response_is_binary);
662
+ } catch (error) {
663
+ if (failsafe) return toFailsafeOutput({
664
+ error,
665
+ requestBody: request.body
666
+ });
667
+ throw error;
668
+ }
669
+ }
670
+ });
671
+ }
672
+ function is_chromium_installed() {
673
+ return fs.existsSync("/usr/bin/chromium");
674
+ }
675
+ const handleBinaryResponse = async (files, bodyContent, status, headers, isBinary) => {
676
+ let body;
677
+ if (isBinary && isBinaryBody(bodyContent)) {
678
+ const fileExtension = contentTypeToExtension((Array.isArray(headers?.["content-type"]) ? headers["content-type"][0] : headers?.["content-type"]) ?? "") || "txt";
679
+ let bufferData;
680
+ if (bodyContent instanceof ArrayBuffer) bufferData = Buffer.from(new Uint8Array(bodyContent));
681
+ else if (Buffer.isBuffer(bodyContent)) bufferData = bodyContent;
682
+ else bufferData = Buffer.from(bodyContent);
683
+ body = await files.write({
684
+ fileName: `output.${fileExtension}`,
685
+ data: bufferData
686
+ });
687
+ } else body = bodyContent;
688
+ return {
689
+ status,
690
+ headers,
691
+ body
692
+ };
693
+ };
694
+ const isBinaryBody = (body) => {
695
+ return body instanceof ArrayBuffer || Buffer.isBuffer(body);
696
+ };
697
+
698
+ //#endregion
699
+ //#region upstream/common/lib/polling/index.ts
700
+ let DedupeStrategy = /* @__PURE__ */ function(DedupeStrategy) {
701
+ DedupeStrategy[DedupeStrategy["TIMEBASED"] = 0] = "TIMEBASED";
702
+ DedupeStrategy[DedupeStrategy["LAST_ITEM"] = 1] = "LAST_ITEM";
703
+ return DedupeStrategy;
704
+ }({});
705
+ const pollingHelper = {
706
+ async poll(polling, { store, auth, propsValue, maxItemsToPoll, files, server }) {
707
+ switch (polling.strategy) {
708
+ case 0: {
709
+ const lastEpochMilliSeconds = await store.get("lastPoll");
710
+ if (isNil$1(lastEpochMilliSeconds)) throw new Error("lastPoll doesn't exist in the store.");
711
+ const items = await polling.items({
712
+ store,
713
+ auth,
714
+ propsValue,
715
+ lastFetchEpochMS: lastEpochMilliSeconds,
716
+ server
717
+ });
718
+ const newLastEpochMilliSeconds = items.reduce((acc, item) => Math.max(acc, item.epochMilliSeconds), lastEpochMilliSeconds);
719
+ await store.put("lastPoll", newLastEpochMilliSeconds);
720
+ return items.filter((f) => f.epochMilliSeconds > lastEpochMilliSeconds).map((item) => item.data);
721
+ }
722
+ case 1: {
723
+ const lastItemId = await store.get("lastItem");
724
+ const items = await polling.items({
725
+ store,
726
+ auth,
727
+ propsValue,
728
+ lastItemId,
729
+ files,
730
+ server
731
+ });
732
+ const lastItemIndex = items.findIndex((f) => f.id === lastItemId);
733
+ let newItems = [];
734
+ if (isNil$1(lastItemId) || lastItemIndex == -1) newItems = items ?? [];
735
+ else newItems = items?.slice(0, lastItemIndex) ?? [];
736
+ if (!isNil$1(maxItemsToPoll)) newItems = newItems.slice(-maxItemsToPoll);
737
+ const newLastItem = newItems?.[0]?.id;
738
+ if (!isNil$1(newLastItem)) await store.put("lastItem", newLastItem);
739
+ return newItems.map((item) => item.data);
740
+ }
741
+ }
742
+ },
743
+ async onEnable(polling, { store, auth, propsValue, server, isRepublish }) {
744
+ switch (polling.strategy) {
745
+ case 0:
746
+ if (isRepublish && !isNil$1(await store.get("lastPoll"))) break;
747
+ await store.put("lastPoll", Date.now());
748
+ break;
749
+ case 1: {
750
+ if (isRepublish && !isNil$1(await store.get("lastItem"))) break;
751
+ const lastItemId = (await polling.items({
752
+ store,
753
+ auth,
754
+ propsValue,
755
+ lastItemId: null,
756
+ server
757
+ }))?.[0]?.id;
758
+ if (!isNil$1(lastItemId)) await store.put("lastItem", lastItemId);
759
+ else await store.delete("lastItem");
760
+ break;
761
+ }
762
+ }
763
+ },
764
+ async onDisable(polling, params) {
765
+ switch (polling.strategy) {
766
+ case 0:
767
+ case 1: return;
768
+ }
769
+ },
770
+ async test(polling, { auth, propsValue, store, files, server }) {
771
+ let items = [];
772
+ switch (polling.strategy) {
773
+ case 0:
774
+ items = await polling.items({
775
+ store,
776
+ auth,
777
+ propsValue,
778
+ lastFetchEpochMS: 0,
779
+ server
780
+ });
781
+ break;
782
+ case 1: items = await polling.items({
783
+ store,
784
+ auth,
785
+ propsValue,
786
+ lastItemId: null,
787
+ files,
788
+ server
789
+ });
790
+ }
791
+ return getFirstFiveOrAll(items.map((item) => item.data));
792
+ }
793
+ };
794
+ function getFirstFiveOrAll(array) {
795
+ if (array.length <= 5) return array;
796
+ else return array.slice(0, 5);
797
+ }
798
+
799
+ //#endregion
800
+ //#region upstream/common/lib/stream/index.ts
801
+ function toStreamingBody(file) {
802
+ if ("body" in file) return {
803
+ body: file.body,
804
+ size: file.size
805
+ };
806
+ return {
807
+ body: Readable.from(file.data),
808
+ size: file.data.length
809
+ };
810
+ }
811
+ async function* readChunks({ readable, chunkSize }) {
812
+ let pending = [];
813
+ let pendingLength = 0;
814
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("chunkSize must be a positive integer");
815
+ for await (const data of readable) {
816
+ pending.push(Buffer.isBuffer(data) ? data : Buffer.from(data));
817
+ pendingLength += pending[pending.length - 1].length;
818
+ while (pendingLength >= chunkSize) {
819
+ const combined = pending.length === 1 ? pending[0] : Buffer.concat(pending);
820
+ yield combined.subarray(0, chunkSize);
821
+ const rest = combined.subarray(chunkSize);
822
+ pending = rest.length > 0 ? [rest] : [];
823
+ pendingLength = rest.length;
824
+ }
825
+ }
826
+ if (pendingLength > 0) yield pending.length === 1 ? pending[0] : Buffer.concat(pending);
827
+ }
828
+ const streamUtils = {
829
+ readChunks,
830
+ toStreamingBody
831
+ };
832
+
833
+ //#endregion
834
+ //#region upstream/common/lib/validation/index.ts
835
+ const propsValidation = { async validateZod(props, schema) {
836
+ const schemaObj = z.object(Object.entries(schema).reduce((acc, [key, value]) => ({
837
+ ...acc,
838
+ [key]: value
839
+ }), {}));
840
+ const result = await z.safeParseAsync(schemaObj, props);
841
+ if (!result.success) {
842
+ const errors = result.error.issues.reduce((acc, issue) => ({
843
+ ...acc,
844
+ [issue.path.join(".")]: issue.message
845
+ }), {});
846
+ throw new Error(JSON.stringify({ errors }, null, 2));
847
+ }
848
+ } };
849
+
850
+ //#endregion
851
+ export { AuthenticationType, FetchHttpClient as AxiosHttpClient, FetchHttpClient, BaseHttpClient, DedupeStrategy, DelegatingAuthenticationConverter, HttpError, HttpHeader, HttpMethod, MediaType, acceptsRequestBody, createCustomApiCallAction, getAccessTokenOrThrow, httpClient, is_chromium_installed, pollingHelper, propsValidation, streamUtils, toFailsafeOutput };
852
+ //# sourceMappingURL=common.js.map