@powerhousedao/pieces-framework 6.2.3-dev.11

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/host.js ADDED
@@ -0,0 +1,723 @@
1
+ import { A as PropertyType, b as ApFile, c as isNil, d as parseToJsonIfPossible, l as isString, o as isBase64, r as tryCatchSync, v as DateRangeValue } from "./markdown-property-Df2l6_y_.js";
2
+ import { g as AUTHENTICATION_PROPERTY_NAME, i as getAuthPropertyForValue, m as isObject } from "./authentication-B7brX_It.js";
3
+ import ipaddr from "ipaddr.js";
4
+ import { Readable } from "node:stream";
5
+ import dayjs from "dayjs";
6
+ import timezone from "dayjs/plugin/timezone.js";
7
+ import utc from "dayjs/plugin/utc.js";
8
+
9
+ //#region upstream/core-utils/lib/friendly-piece-error.ts
10
+ const FRIENDLY_PIECE_ERROR_VERSION = 1;
11
+ const STACK_LINE_REGEX = /\n\s*at\s+.+$/gm;
12
+ const HTTP_ERROR_MESSAGE_MAX_LENGTH = 2e3;
13
+ const RAW_ERROR_MAX_LENGTH = 16e3;
14
+ const HTTP_STATUS_MIN = 100;
15
+ const HTTP_STATUS_MAX = 599;
16
+ const MAX_MESSAGE_DEPTH = 12;
17
+ const MAX_SERIALIZED_DEPTH = 64;
18
+ const CIRCULAR_PLACEHOLDER = "[Circular]";
19
+ const TOO_DEEP_PLACEHOLDER = "[Too deep]";
20
+ const UNSERIALIZABLE_PLACEHOLDER = "[Unserializable]";
21
+ const isObjectRecord = (value) => {
22
+ return !isNil(value) && typeof value === "object" && !Array.isArray(value);
23
+ };
24
+ const safeJsonParse = (value) => {
25
+ try {
26
+ return JSON.parse(value);
27
+ } catch {
28
+ return value;
29
+ }
30
+ };
31
+ const stripStack = (value) => {
32
+ return value.replace(STACK_LINE_REGEX, "").trim();
33
+ };
34
+ const truncate = (value) => {
35
+ if (value.length <= HTTP_ERROR_MESSAGE_MAX_LENGTH) return value;
36
+ return `${value.slice(0, HTTP_ERROR_MESSAGE_MAX_LENGTH)}…`;
37
+ };
38
+ const truncateRaw = (value) => {
39
+ if (value.length <= RAW_ERROR_MAX_LENGTH) return value;
40
+ return `${value.slice(0, RAW_ERROR_MAX_LENGTH)}\n…[truncated]`;
41
+ };
42
+ const HTML_DOC_REGEX = /^\s*(<!doctype\s+html|<html\b|<\?xml)/i;
43
+ const HTML_TAG_LIKE_REGEX = /<\s*(html|body|head|title|meta|p|div|span|h[1-6]|table|script|style)\b/i;
44
+ const isLikelyMarkupBody = (value) => {
45
+ if (HTML_DOC_REGEX.test(value)) return true;
46
+ if (!value.includes("<") || !value.includes(">")) return false;
47
+ return HTML_TAG_LIKE_REGEX.test(value);
48
+ };
49
+ const decodeHtmlEntities = (value) => {
50
+ return value.replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&apos;/g, "'");
51
+ };
52
+ const stripMarkup = (value) => {
53
+ const titleMatch = value.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
54
+ const title = titleMatch ? decodeHtmlEntities(titleMatch[1]).replace(/\s+/g, " ").trim() : "";
55
+ const textOnly = decodeHtmlEntities(value.replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<head[\s\S]*?<\/head>/gi, " ").replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim();
56
+ if (textOnly.length > 0 && title.length > 0 && !textOnly.startsWith(title)) return `${title} — ${textOnly}`;
57
+ return textOnly.length > 0 ? textOnly : title;
58
+ };
59
+ const readString = (record, key) => {
60
+ const value = record[key];
61
+ return isString(value) ? value : void 0;
62
+ };
63
+ const collectMessageFrom = ({ value, depth, seen }) => {
64
+ if (isNil(value) || depth > MAX_MESSAGE_DEPTH) return;
65
+ if (isString(value)) {
66
+ const trimmed = value.trim();
67
+ if (trimmed.length === 0) return;
68
+ if (isLikelyMarkupBody(trimmed)) {
69
+ const stripped = stripMarkup(trimmed);
70
+ return stripped.length > 0 ? stripped : void 0;
71
+ }
72
+ return trimmed;
73
+ }
74
+ if (Array.isArray(value)) {
75
+ if (seen.has(value)) return;
76
+ seen.add(value);
77
+ const parts = value.map((entry) => collectMessageFrom({
78
+ value: entry,
79
+ depth: depth + 1,
80
+ seen
81
+ })).filter((entry) => isString(entry) && entry.length > 0);
82
+ return parts.length > 0 ? parts.join("; ") : void 0;
83
+ }
84
+ if (isObjectRecord(value)) {
85
+ if (seen.has(value)) return;
86
+ seen.add(value);
87
+ return collectMessageFrom({
88
+ value: value["message"] ?? value["detail"] ?? value["description"] ?? value["reason"] ?? value["error"],
89
+ depth: depth + 1,
90
+ seen
91
+ });
92
+ }
93
+ };
94
+ const collectMessage = (value) => {
95
+ return collectMessageFrom({
96
+ value,
97
+ depth: 0,
98
+ seen: /* @__PURE__ */ new WeakSet()
99
+ });
100
+ };
101
+ const extractApiMessage = (responseBody) => {
102
+ if (isNil(responseBody)) return;
103
+ if (isString(responseBody) || Array.isArray(responseBody)) {
104
+ const collected = collectMessage(responseBody);
105
+ return collected ? truncate(collected) : void 0;
106
+ }
107
+ if (!isObjectRecord(responseBody)) return truncate(String(responseBody));
108
+ const candidates = [
109
+ responseBody["message"],
110
+ responseBody["error_description"],
111
+ responseBody["errorDescription"],
112
+ responseBody["detail"],
113
+ responseBody["title"],
114
+ responseBody["error_message"],
115
+ responseBody["errorMessage"],
116
+ responseBody["errorMessages"],
117
+ responseBody["errors"],
118
+ responseBody["error"],
119
+ responseBody["faultstring"],
120
+ responseBody["fault"],
121
+ responseBody["reason"],
122
+ responseBody["description"]
123
+ ];
124
+ for (const candidate of candidates) {
125
+ const collected = collectMessage(candidate);
126
+ if (collected) return truncate(collected);
127
+ }
128
+ };
129
+ const toHttpStatus = (value) => {
130
+ return typeof value === "number" && value >= HTTP_STATUS_MIN && value <= HTTP_STATUS_MAX ? value : void 0;
131
+ };
132
+ const extractResponseHttpDetails = (error) => {
133
+ const response = error["response"];
134
+ if (!isObjectRecord(response)) return null;
135
+ const statusValue = response["status"];
136
+ const status = typeof statusValue === "number" ? statusValue : void 0;
137
+ const responseBody = response["body"];
138
+ const headersValue = response["headers"];
139
+ const headers = isObjectRecord(headersValue) ? headersValue : void 0;
140
+ const requestRaw = error["request"];
141
+ const request = isObjectRecord(requestRaw) ? requestRaw : void 0;
142
+ const requestBody = request?.["body"];
143
+ const requestUrl = request === void 0 ? void 0 : readString(request, "url");
144
+ const requestMethod = request === void 0 ? void 0 : readString(request, "method");
145
+ if (isNil(status) && isNil(responseBody) && isNil(requestBody)) return null;
146
+ return {
147
+ status,
148
+ responseBody,
149
+ responseHeaders: headers,
150
+ requestBody,
151
+ requestUrl,
152
+ requestMethod,
153
+ apiMessage: extractApiMessage(responseBody)
154
+ };
155
+ };
156
+ const extractClientHttpDetails = (error) => {
157
+ const status = toHttpStatus(error["status"]);
158
+ if (isNil(status)) return null;
159
+ const responseBody = error["error"] ?? error["body"];
160
+ const headersValue = error["headers"];
161
+ return {
162
+ status,
163
+ responseBody,
164
+ responseHeaders: isObjectRecord(headersValue) ? headersValue : void 0,
165
+ apiMessage: extractApiMessage(responseBody)
166
+ };
167
+ };
168
+ const extractHttpDetails = (error) => {
169
+ return extractResponseHttpDetails(error) ?? extractClientHttpDetails(error);
170
+ };
171
+ const rebuildSerializable = ({ value, depth, seen }) => {
172
+ if (isNil(value) || isString(value) || typeof value === "number" || typeof value === "boolean") return value;
173
+ if (Array.isArray(value) || isObjectRecord(value)) {
174
+ if (seen.has(value)) return CIRCULAR_PLACEHOLDER;
175
+ if (depth >= MAX_SERIALIZED_DEPTH) return TOO_DEEP_PLACEHOLDER;
176
+ seen.add(value);
177
+ if (Array.isArray(value)) return value.map((entry) => rebuildSerializable({
178
+ value: entry,
179
+ depth: depth + 1,
180
+ seen
181
+ }));
182
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, rebuildSerializable({
183
+ value: entry,
184
+ depth: depth + 1,
185
+ seen
186
+ })]));
187
+ }
188
+ return String(value);
189
+ };
190
+ const toSerializable = (value) => {
191
+ if (isNil(value)) return value;
192
+ const { error } = tryCatchSync(() => JSON.stringify(value));
193
+ if (isNil(error)) return value;
194
+ const rebuilt = tryCatchSync(() => rebuildSerializable({
195
+ value,
196
+ depth: 0,
197
+ seen: /* @__PURE__ */ new WeakSet()
198
+ }));
199
+ return isNil(rebuilt.error) ? rebuilt.data : UNSERIALIZABLE_PLACEHOLDER;
200
+ };
201
+ const toSerializableHttpDetails = (httpDetails) => {
202
+ if (isNil(httpDetails)) return null;
203
+ const { responseBody, requestBody, responseHeaders } = httpDetails;
204
+ return {
205
+ ...httpDetails,
206
+ responseBody: toSerializable(responseBody),
207
+ requestBody: toSerializable(requestBody),
208
+ responseHeaders: isNil(responseHeaders) ? void 0 : Object.fromEntries(Object.entries(responseHeaders).map(([key, value]) => [key, toSerializable(value)]))
209
+ };
210
+ };
211
+ const readErrorName = (error) => {
212
+ const name = readString(error, "name");
213
+ if (!isNil(name) && name.length > 0 && name !== "Error") return name;
214
+ const ctor = error["constructor"];
215
+ if (typeof ctor === "function" && isString(ctor.name) && ctor.name.length > 0 && ctor.name !== "Object" && ctor.name !== "Error") return ctor.name;
216
+ };
217
+ const readErrorMessage = (error) => {
218
+ const messageString = readString(error, "message");
219
+ if (!isNil(messageString)) return messageString;
220
+ const stringified = String(error);
221
+ if (stringified.length > 0 && stringified !== "[object Object]") return stringified;
222
+ return "Unknown error";
223
+ };
224
+ const pickPlainMessage = ({ httpDetails, rawMessage }) => {
225
+ if (httpDetails?.apiMessage) return httpDetails.apiMessage;
226
+ const cleaned = stripStack(rawMessage);
227
+ if (cleaned.length > 0) return truncate(cleaned);
228
+ return "Unknown error";
229
+ };
230
+ const isFriendlyPieceError = (value) => {
231
+ if (!isObjectRecord(value)) return false;
232
+ return value["__apErrorVersion"] === FRIENDLY_PIECE_ERROR_VERSION && typeof value["message"] === "string";
233
+ };
234
+ const formatPieceError = (error, options) => {
235
+ const raw = options?.raw;
236
+ const withRaw = (base) => {
237
+ if (isNil(raw) || raw.length === 0 || !isNil(base.raw)) return base;
238
+ return {
239
+ ...base,
240
+ raw: truncateRaw(raw)
241
+ };
242
+ };
243
+ if (isNil(error)) return withRaw({
244
+ __apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,
245
+ message: "Unknown error"
246
+ });
247
+ if (isString(error)) {
248
+ const cleaned = stripStack(error);
249
+ return withRaw({
250
+ __apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,
251
+ message: cleaned.length > 0 ? cleaned : "Unknown error"
252
+ });
253
+ }
254
+ if (!isObjectRecord(error)) return withRaw({
255
+ __apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,
256
+ message: truncate(String(error))
257
+ });
258
+ if (isFriendlyPieceError(error)) return withRaw(error);
259
+ const httpDetails = extractHttpDetails(error);
260
+ const errorName = readErrorName(error);
261
+ return withRaw({
262
+ __apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,
263
+ message: pickPlainMessage({
264
+ httpDetails,
265
+ rawMessage: readErrorMessage(error)
266
+ }),
267
+ errorName,
268
+ ...toSerializableHttpDetails(httpDetails) ?? {}
269
+ });
270
+ };
271
+ const tryParseFriendlyPieceError = (value) => {
272
+ if (isNil(value)) return null;
273
+ const candidate = isString(value) ? safeJsonParse(value) : value;
274
+ return isFriendlyPieceError(candidate) ? candidate : null;
275
+ };
276
+
277
+ //#endregion
278
+ //#region upstream/core-utils/lib/ssrf-ip-classifier.ts
279
+ function parseOrNull(ip) {
280
+ try {
281
+ return ipaddr.parse(ip);
282
+ } catch {
283
+ return null;
284
+ }
285
+ }
286
+ function isInAllowList({ ip, allowList }) {
287
+ if (allowList.includes(ip)) return true;
288
+ const addr = parseOrNull(ip);
289
+ if (!addr) return false;
290
+ return allowList.some((entry) => entry.includes("/") && matchesCidr({
291
+ addr,
292
+ cidr: entry
293
+ }));
294
+ }
295
+ function matchesCidr({ addr, cidr }) {
296
+ try {
297
+ const range = ipaddr.parseCIDR(cidr);
298
+ if (addr.kind() !== range[0].kind()) return false;
299
+ return addr.match(range);
300
+ } catch {
301
+ return false;
302
+ }
303
+ }
304
+ function isBlockedRange(addr) {
305
+ if (addr.kind() === "ipv6") {
306
+ const v6 = addr;
307
+ if (v6.isIPv4MappedAddress()) return isBlockedRange(v6.toIPv4Address());
308
+ }
309
+ return addr.range() !== "unicast";
310
+ }
311
+ function isBlockedIp({ ip, allowList }) {
312
+ if (isInAllowList({
313
+ ip,
314
+ allowList
315
+ })) return false;
316
+ const addr = parseOrNull(ip);
317
+ if (!addr) return true;
318
+ return isBlockedRange(addr);
319
+ }
320
+ const ssrfIpClassifier = { isBlockedIp };
321
+
322
+ //#endregion
323
+ //#region upstream/engine/lib/helper/dynamic-prop-keys.ts
324
+ function escapePropsKeys(props) {
325
+ return Object.fromEntries(Object.entries(props).map(([key, property]) => [escapeKey(key), property]));
326
+ }
327
+ function unescapePropsKeys(props) {
328
+ return Object.fromEntries(Object.entries(props).map(([key, property]) => [unescapeKey(key), property]));
329
+ }
330
+ function unescapeInputKeys(value) {
331
+ if (!isObject(value)) return value;
332
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [unescapeKey(key), child]));
333
+ }
334
+ function escapeKey(key) {
335
+ if (!RESERVED_CHARS.test(key)) return key;
336
+ return ESCAPED_KEY_MARKER + key.replace(/[~.[\]"']/g, (char) => ESCAPE_SEQUENCES[char]);
337
+ }
338
+ function unescapeKey(key) {
339
+ if (!key.startsWith(ESCAPED_KEY_MARKER)) return key;
340
+ return key.slice(ESCAPED_KEY_MARKER.length).replace(/~[0-5]/g, (sequence) => UNESCAPE_SEQUENCES[sequence]);
341
+ }
342
+ const ESCAPED_KEY_MARKER = "~ap~";
343
+ const RESERVED_CHARS = /[~.[\]"']/;
344
+ const ESCAPE_SEQUENCES = {
345
+ "~": "~0",
346
+ ".": "~1",
347
+ "[": "~2",
348
+ "]": "~3",
349
+ "\"": "~4",
350
+ "'": "~5"
351
+ };
352
+ const UNESCAPE_SEQUENCES = Object.fromEntries(Object.entries(ESCAPE_SEQUENCES).map(([char, sequence]) => [sequence, char]));
353
+ const dynamicPropKeys = {
354
+ escapePropsKeys,
355
+ unescapePropsKeys,
356
+ unescapeInputKeys
357
+ };
358
+
359
+ //#endregion
360
+ //#region upstream/engine/lib/variables/processors/array-zipper.ts
361
+ function getLongestArrayLengthInObject(props) {
362
+ return Math.max(...Object.values(props).map((value) => Array.isArray(value) ? value.length : 1));
363
+ }
364
+ function constructResultForIndex(props, index) {
365
+ return Object.entries(props).reduce((result, [key, value]) => {
366
+ result[key] = Array.isArray(value) ? value[index] : value;
367
+ return result;
368
+ }, {});
369
+ }
370
+ const arrayZipperProcessor = (_property, value) => {
371
+ if (Array.isArray(value) || !isObject(value)) return value;
372
+ return Array.from({ length: getLongestArrayLengthInObject(value) }, (_, index) => constructResultForIndex(value, index));
373
+ };
374
+
375
+ //#endregion
376
+ //#region upstream/engine/lib/variables/processors/checkbox.ts
377
+ const checkboxProcessor = (_property, value) => {
378
+ if (isNil(value) || typeof value === "boolean") return value;
379
+ if (typeof value === "string" && value.trim().length === 0) return;
380
+ const parsed = parseToJsonIfPossible(value);
381
+ return typeof parsed === "boolean" ? parsed : value;
382
+ };
383
+
384
+ //#endregion
385
+ //#region upstream/engine/lib/variables/processors/date-time.ts
386
+ const dateTimeProcessor = (_property, value) => {
387
+ dayjs.extend(utc);
388
+ dayjs.extend(timezone);
389
+ const dateTimeString = value;
390
+ try {
391
+ if (!dateTimeString) throw Error("Undefined input");
392
+ return dayjs.tz(dateTimeString, "UTC").toISOString();
393
+ } catch (error) {
394
+ console.error(error);
395
+ return;
396
+ }
397
+ };
398
+
399
+ //#endregion
400
+ //#region upstream/engine/lib/variables/processors/file.ts
401
+ const fileProcessor = async (property, urlOrBase64) => {
402
+ if (isNil(urlOrBase64) || !isString(urlOrBase64)) return null;
403
+ const streaming = property.type === PropertyType.FILE && property.streaming === true;
404
+ try {
405
+ if (streaming) return await handleStreamingFile(urlOrBase64);
406
+ const file = handleBase64File(urlOrBase64);
407
+ if (!isNil(file)) return file;
408
+ return await handleUrlFile(urlOrBase64);
409
+ } catch (e) {
410
+ console.error(e);
411
+ return null;
412
+ }
413
+ };
414
+ function parseBase64File(propertyValue) {
415
+ if (!isBase64(propertyValue, { allowMime: true })) return null;
416
+ const matches = propertyValue.match(/^data:([A-Za-z-+/]+);base64,(.+)$/);
417
+ if (!matches || matches?.length !== 3) return null;
418
+ return {
419
+ extension: mimeExtension(matches[1]) || "bin",
420
+ buffer: Buffer.from(matches[2], "base64")
421
+ };
422
+ }
423
+ function handleBase64File(propertyValue) {
424
+ const parsed = parseBase64File(propertyValue);
425
+ if (isNil(parsed)) return null;
426
+ return new ApFile(`unknown.${parsed.extension}`, parsed.buffer, parsed.extension);
427
+ }
428
+ async function handleUrlFile(path) {
429
+ const fileResponse = await fetch(path);
430
+ if (!fileResponse.ok) return null;
431
+ const filename = getFileName(path, fileResponse.headers.get("content-disposition"), fileResponse.headers.get("content-type") ?? void 0) ?? "unknown";
432
+ const extension = extensionFromFilename(filename);
433
+ return new ApFile(filename, Buffer.from(await fileResponse.arrayBuffer()), extension);
434
+ }
435
+ async function handleStreamingFile(propertyValue) {
436
+ const parsed = parseBase64File(propertyValue);
437
+ if (!isNil(parsed)) return {
438
+ filename: `unknown.${parsed.extension}`,
439
+ extension: parsed.extension,
440
+ size: parsed.buffer.length,
441
+ body: Readable.from(parsed.buffer)
442
+ };
443
+ const fileResponse = await fetch(propertyValue);
444
+ if (!fileResponse.ok || isNil(fileResponse.body)) {
445
+ await fileResponse.body?.cancel();
446
+ return null;
447
+ }
448
+ const filename = getFileName(propertyValue, fileResponse.headers.get("content-disposition"), fileResponse.headers.get("content-type") ?? void 0) ?? "unknown";
449
+ const extension = extensionFromFilename(filename);
450
+ const contentEncoding = fileResponse.headers.get("content-encoding");
451
+ const contentLength = Number(fileResponse.headers.get("content-length"));
452
+ return {
453
+ filename,
454
+ extension,
455
+ size: (isNil(contentEncoding) || contentEncoding.toLowerCase() === "identity") && Number.isInteger(contentLength) && contentLength > 0 ? contentLength : void 0,
456
+ body: Readable.fromWeb(fileResponse.body)
457
+ };
458
+ }
459
+ function extensionFromFilename(filename) {
460
+ const parts = filename.split(".");
461
+ const last = parts.length > 1 ? parts.pop() : void 0;
462
+ return last ? last : void 0;
463
+ }
464
+ function getFileName(path, disposition, mimeType) {
465
+ const url = new URL(path);
466
+ if (isNil(disposition)) {
467
+ const fileNameFromUrl = url.pathname.includes("/") && url.pathname.split("/").pop()?.includes(".") ? url.pathname.split("/").pop() : null;
468
+ if (!isNil(fileNameFromUrl)) return fileNameFromUrl;
469
+ return `unknown.${(mimeType ? mimeExtension(mimeType) : null) ?? "bin"}`;
470
+ }
471
+ const utf8FilenameRegex = /filename\*=UTF-8''([\w%\-.]+)(?:; ?|$)/i;
472
+ if (utf8FilenameRegex.test(disposition)) {
473
+ const result = utf8FilenameRegex.exec(disposition);
474
+ if (result && result.length > 1) return decodeURIComponent(result[1]);
475
+ }
476
+ const filenameStart = disposition.toLowerCase().indexOf("filename=");
477
+ const asciiFilenameRegex = /^filename=(["']?)(.*?[^\\])\1(?:; ?|$)/i;
478
+ if (filenameStart >= 0) {
479
+ const partialDisposition = disposition.slice(filenameStart);
480
+ const matches = asciiFilenameRegex.exec(partialDisposition);
481
+ if (matches != null && matches[2]) return matches[2];
482
+ }
483
+ return null;
484
+ }
485
+ function mimeExtension(mimeType) {
486
+ return MIME_EXTENSIONS[mimeType.split(";")[0].trim().toLowerCase()] ?? null;
487
+ }
488
+ const MIME_EXTENSIONS = {
489
+ "application/json": "json",
490
+ "application/pdf": "pdf",
491
+ "application/xml": "xml",
492
+ "application/zip": "zip",
493
+ "application/gzip": "gz",
494
+ "application/x-7z-compressed": "7z",
495
+ "application/x-tar": "tar",
496
+ "application/octet-stream": "bin",
497
+ "application/msword": "doc",
498
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
499
+ "application/vnd.ms-excel": "xls",
500
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
501
+ "application/vnd.ms-powerpoint": "ppt",
502
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
503
+ "application/rtf": "rtf",
504
+ "application/javascript": "js",
505
+ "application/x-javascript": "js",
506
+ "application/x-yaml": "yaml",
507
+ "application/yaml": "yaml",
508
+ "application/x-httpd-php": "php",
509
+ "application/x-sh": "sh",
510
+ "image/png": "png",
511
+ "image/jpeg": "jpg",
512
+ "image/jpg": "jpg",
513
+ "image/gif": "gif",
514
+ "image/webp": "webp",
515
+ "image/svg+xml": "svg",
516
+ "image/bmp": "bmp",
517
+ "image/tiff": "tiff",
518
+ "image/x-icon": "ico",
519
+ "image/vnd.microsoft.icon": "ico",
520
+ "image/heic": "heic",
521
+ "image/heif": "heif",
522
+ "image/avif": "avif",
523
+ "text/plain": "txt",
524
+ "text/html": "html",
525
+ "text/css": "css",
526
+ "text/csv": "csv",
527
+ "text/javascript": "js",
528
+ "text/markdown": "md",
529
+ "text/xml": "xml",
530
+ "text/tab-separated-values": "tsv",
531
+ "text/yaml": "yaml",
532
+ "audio/mpeg": "mp3",
533
+ "audio/mp3": "mp3",
534
+ "audio/mp4": "m4a",
535
+ "audio/wav": "wav",
536
+ "audio/x-wav": "wav",
537
+ "audio/ogg": "ogg",
538
+ "audio/webm": "weba",
539
+ "audio/flac": "flac",
540
+ "audio/aac": "aac",
541
+ "video/mp4": "mp4",
542
+ "video/mpeg": "mpeg",
543
+ "video/webm": "webm",
544
+ "video/quicktime": "mov",
545
+ "video/x-msvideo": "avi",
546
+ "video/ogg": "ogv",
547
+ "font/woff": "woff",
548
+ "font/woff2": "woff2",
549
+ "font/ttf": "ttf",
550
+ "font/otf": "otf"
551
+ };
552
+
553
+ //#endregion
554
+ //#region upstream/engine/lib/variables/processors/json.ts
555
+ const jsonProcessor = (_property, value) => {
556
+ if (isNil(value)) return value;
557
+ try {
558
+ if (typeof value === "object") return value;
559
+ return JSON.parse(value);
560
+ } catch (error) {
561
+ console.error(error);
562
+ return;
563
+ }
564
+ };
565
+
566
+ //#endregion
567
+ //#region upstream/engine/lib/variables/processors/multi-select.ts
568
+ const multiSelectProcessor = (_property, value) => {
569
+ if (isNil(value) || Array.isArray(value)) return value;
570
+ if (typeof value === "string" && value.trim().length === 0) return;
571
+ const parsed = parseToJsonIfPossible(value);
572
+ return Array.isArray(parsed) ? parsed : [value];
573
+ };
574
+
575
+ //#endregion
576
+ //#region upstream/engine/lib/variables/processors/number.ts
577
+ const numberProcessor = (_property, value) => {
578
+ if (isNil(value)) return value;
579
+ if (value === "") return;
580
+ return Number(value);
581
+ };
582
+
583
+ //#endregion
584
+ //#region upstream/engine/lib/variables/processors/object.ts
585
+ const objectProcessor = (_property, value) => {
586
+ if (isNil(value)) return value;
587
+ if (typeof value === "string") try {
588
+ return JSON.parse(value);
589
+ } catch (e) {
590
+ return;
591
+ }
592
+ if (typeof value === "object" && !Array.isArray(value)) return value;
593
+ };
594
+
595
+ //#endregion
596
+ //#region upstream/engine/lib/variables/processors/text.ts
597
+ const textProcessor = (property, value) => {
598
+ if (isNil(value)) return value;
599
+ if (typeof value === "object") return JSON.stringify(value);
600
+ const result = value.toString();
601
+ if (result.length === 0 && !property.required) return;
602
+ return result;
603
+ };
604
+
605
+ //#endregion
606
+ //#region upstream/engine/lib/variables/processors/index.ts
607
+ const processors = {
608
+ JSON: jsonProcessor,
609
+ OBJECT: objectProcessor,
610
+ NUMBER: numberProcessor,
611
+ LONG_TEXT: textProcessor,
612
+ SHORT_TEXT: textProcessor,
613
+ SECRET_TEXT: textProcessor,
614
+ DATE_TIME: dateTimeProcessor,
615
+ FILE: fileProcessor,
616
+ MULTI_SELECT_DROPDOWN: multiSelectProcessor,
617
+ STATIC_MULTI_SELECT_DROPDOWN: multiSelectProcessor,
618
+ CHECKBOX: checkboxProcessor
619
+ };
620
+
621
+ //#endregion
622
+ //#region upstream/engine/lib/variables/props-processor.ts
623
+ const propsProcessor = { applyProcessorsAndValidators: async (resolvedInput, props, auth, requireAuth, propertySettings) => {
624
+ let dynamaicPropertiesSchema = void 0;
625
+ if (Object.keys(propertySettings).length > 0) dynamaicPropertiesSchema = Object.fromEntries(Object.entries(propertySettings).map(([key, propertySetting]) => [key, propertySetting.schema]));
626
+ const processedInput = { ...resolvedInput };
627
+ const errors = {};
628
+ const authValue = resolvedInput[AUTHENTICATION_PROPERTY_NAME];
629
+ if (authValue && requireAuth) {
630
+ const authPropsToProcess = getAuthPropsToProcess(authValue, auth);
631
+ if (authPropsToProcess) {
632
+ const { processedInput: authProcessedInput, errors: authErrors } = await propsProcessor.applyProcessorsAndValidators(resolvedInput[AUTHENTICATION_PROPERTY_NAME], authPropsToProcess, void 0, false, {});
633
+ processedInput[AUTHENTICATION_PROPERTY_NAME] = authProcessedInput;
634
+ if (Object.keys(authErrors).length > 0) errors[AUTHENTICATION_PROPERTY_NAME] = authErrors;
635
+ }
636
+ }
637
+ for (const [key, value] of Object.entries(resolvedInput)) {
638
+ const property = props[key];
639
+ if (isNil(property)) continue;
640
+ if (property.type === PropertyType.DYNAMIC) {
641
+ const valueWithOriginalKeys = dynamicPropKeys.unescapeInputKeys(value);
642
+ processedInput[key] = valueWithOriginalKeys;
643
+ if (!isNil(dynamaicPropertiesSchema?.[key])) {
644
+ const { processedInput: itemProcessedInput, errors: itemErrors } = await propsProcessor.applyProcessorsAndValidators(valueWithOriginalKeys, dynamicPropKeys.unescapePropsKeys(dynamaicPropertiesSchema[key]), void 0, false, {});
645
+ processedInput[key] = itemProcessedInput;
646
+ if (Object.keys(itemErrors).length > 0) errors[key] = itemErrors;
647
+ }
648
+ }
649
+ if (property.type === PropertyType.ARRAY && property.properties) {
650
+ const arrayOfObjects = arrayZipperProcessor(property, value) ?? [];
651
+ const processedArray = [];
652
+ const processedErrors = [];
653
+ for (const item of arrayOfObjects) {
654
+ const { processedInput: itemProcessedInput, errors: itemErrors } = await propsProcessor.applyProcessorsAndValidators(item, property.properties, void 0, false, {});
655
+ processedArray.push(itemProcessedInput);
656
+ processedErrors.push(itemErrors);
657
+ }
658
+ processedInput[key] = processedArray;
659
+ if (processedErrors.some((error) => Object.keys(error).length > 0)) errors[key] = { properties: processedErrors };
660
+ }
661
+ if (!property.required && isNil(processedInput[key])) processedInput[key] = void 0;
662
+ const processor = processors[property.type];
663
+ if (processor) processedInput[key] = await processor(property, processedInput[key]);
664
+ if (!(key !== "auth" && property.type !== PropertyType.MARKDOWN)) continue;
665
+ }
666
+ for (const [key, value] of Object.entries(processedInput)) {
667
+ const property = props[key];
668
+ if (isNil(property)) continue;
669
+ const validationErrors = validateProperty(property, value, resolvedInput[key]);
670
+ if (validationErrors.length > 0) errors[key] = validationErrors;
671
+ }
672
+ if (Object.keys(errors).length > 0) destroyOpenStreams(processedInput);
673
+ return {
674
+ processedInput,
675
+ errors
676
+ };
677
+ } };
678
+ function destroyOpenStreams(value) {
679
+ if (isNil(value) || typeof value !== "object" || Buffer.isBuffer(value)) return;
680
+ if (value instanceof Readable) {
681
+ value.destroy();
682
+ return;
683
+ }
684
+ for (const child of Object.values(value)) destroyOpenStreams(child);
685
+ }
686
+ const validateProperty = (property, value, originalValue) => {
687
+ if (property.type === PropertyType.JSON) {
688
+ if (!property.required && originalValue === "") return [];
689
+ if (!isNil(originalValue) && isNil(value)) return [`Expected JSON, received: ${originalValue}`];
690
+ if (!property.required && isNil(value)) return [];
691
+ if (!isObject(value) && !Array.isArray(value)) return [`Expected JSON, received: ${originalValue}`];
692
+ return [];
693
+ }
694
+ if (!property.required && isNil(value)) return [];
695
+ switch (property.type) {
696
+ case PropertyType.SHORT_TEXT:
697
+ case PropertyType.LONG_TEXT:
698
+ case PropertyType.RICH_TEXT: return typeof value === "string" ? [] : [`Expected string, received: ${originalValue}`];
699
+ case PropertyType.NUMBER: return typeof value === "number" && !Number.isNaN(value) ? [] : [`Expected number, received: ${originalValue}`];
700
+ case PropertyType.CHECKBOX: return typeof value === "boolean" ? [] : [`Expected boolean, received: ${originalValue}`];
701
+ case PropertyType.DATE_TIME: return typeof value === "string" ? [] : [`Invalid datetime format. Expected ISO format (e.g. 2024-03-14T12:00:00.000Z), received: ${originalValue}`];
702
+ case PropertyType.DATE_RANGE: return DateRangeValue.safeParse(value).success ? [] : [`Expected date range, received: ${originalValue}`];
703
+ case PropertyType.ARRAY:
704
+ case PropertyType.MULTI_SELECT_DROPDOWN:
705
+ case PropertyType.STATIC_MULTI_SELECT_DROPDOWN: return Array.isArray(value) ? [] : [`Expected array, received: ${originalValue}`];
706
+ case PropertyType.OBJECT: return isObject(value) ? [] : [`Expected object, received: ${originalValue}`];
707
+ case PropertyType.FILE: return isObject(value) ? [] : [`Expected file url or base64 with mimeType, received: ${originalValue}`];
708
+ default: return [];
709
+ }
710
+ };
711
+ function getAuthPropsToProcess(authValue, auth) {
712
+ if (isNil(auth)) return null;
713
+ const usedAuthProperty = getAuthPropertyForValue({
714
+ authValueType: authValue.type,
715
+ pieceAuth: auth
716
+ });
717
+ if ((usedAuthProperty?.type === PropertyType.CUSTOM_AUTH || usedAuthProperty?.type === PropertyType.OAUTH2 || usedAuthProperty?.type === PropertyType.OIDC) && !isNil(usedAuthProperty?.props)) return usedAuthProperty.props;
718
+ return null;
719
+ }
720
+
721
+ //#endregion
722
+ export { arrayZipperProcessor, checkboxProcessor, dateTimeProcessor, dynamicPropKeys, fileProcessor, formatPieceError, jsonProcessor, multiSelectProcessor, numberProcessor, objectProcessor, processors, propsProcessor, ssrfIpClassifier, textProcessor, tryParseFriendlyPieceError };
723
+ //# sourceMappingURL=host.js.map