@dev-fastn-ai/react-core 2.3.6 → 2.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +465 -0
  2. package/dist/{react-core/src/core → core}/provider.d.ts +2 -2
  3. package/dist/{react-core/src/core → core}/use-configuration-form.d.ts +1 -1
  4. package/dist/{react-core/src/core → core}/use-configurations.d.ts +1 -1
  5. package/dist/core/use-connectors.d.ts +1 -0
  6. package/dist/{react-core/src/core → core}/use-field-options.d.ts +4 -1
  7. package/dist/index.cjs.js +39 -1655
  8. package/dist/index.cjs.js.map +1 -1
  9. package/dist/index.d.ts +10 -202
  10. package/dist/index.esm.js +39 -1654
  11. package/dist/index.esm.js.map +1 -1
  12. package/package.json +5 -3
  13. package/dist/core/src/core/activate-connector.d.ts +0 -40
  14. package/dist/core/src/core/config.d.ts +0 -3
  15. package/dist/core/src/core/configuration-form.d.ts +0 -27
  16. package/dist/core/src/core/configurations.d.ts +0 -2
  17. package/dist/core/src/core/connectors.d.ts +0 -7
  18. package/dist/core/src/core/execute-flow.d.ts +0 -9
  19. package/dist/core/src/core/register-refetch-functions.d.ts +0 -4
  20. package/dist/core/src/index.d.ts +0 -13
  21. package/dist/core/src/services/apis.d.ts +0 -86
  22. package/dist/core/src/types/config.d.ts +0 -10
  23. package/dist/core/src/types/index.d.ts +0 -272
  24. package/dist/core/src/utils/constants.d.ts +0 -12
  25. package/dist/core/src/utils/errors.d.ts +0 -22
  26. package/dist/core/src/utils/event-bus.d.ts +0 -6
  27. package/dist/core/src/utils/google-files-picker.d.ts +0 -13
  28. package/dist/core/src/utils/misc.d.ts +0 -40
  29. package/dist/react-core/src/core/use-connectors.d.ts +0 -1
  30. package/dist/react-core/src/index.d.ts +0 -7
package/dist/index.cjs.js CHANGED
@@ -5,1664 +5,10 @@ var react = require('react');
5
5
  var reactQuery = require('@tanstack/react-query');
6
6
  var core = require('@dev-fastn-ai/core');
7
7
 
8
- const REQUEST_TRACE_ID_HEADER_KEY = 'x-fastn-request-trace-id';
9
- const PROJECT_ID_HEADER_KEY = 'x-fastn-space-id';
10
- const TENANT_ID_HEADER_KEY = 'x-fastn-space-tenantid';
11
- const REALM = 'fastn';
12
- const DEFAULT_BASE_URL = 'https://live.fastn.ai/api';
13
- const PROD_OAUTH_REDIRECT_URL = 'https://oauth.live.fastn.ai';
14
- const CUSTOM_AUTH_CONTEXT_HEADER_KEY = 'x-fastn-custom-auth-context';
15
- const CUSTOM_AUTH_HEADER_KEY = 'x-fastn-custom-auth';
16
- const GOOGLE_FILES_PICKER_API_KEY = "AIzaSyClOJ0PYR0NJJkE79VLpKGOjgABbhjj9x4";
17
- const ACTIVATE_CONNECTOR_ACCESS_KEY = "7e9456eb-5fa1-44ca-8464-d63eb4a1c9a8";
18
- const ACTIVATE_CONNECTOR_PROJECT_ID = "e9289c72-9c15-42af-98e5-8bc6114a362f";
19
- const ACTIVATE_CONNECTOR_URL = "/api/v1/ActivateConnector";
20
-
21
- let config;
22
- function setConfig(userConfig) {
23
- var _a;
24
- config = {
25
- baseUrl: userConfig.baseUrl || DEFAULT_BASE_URL,
26
- environment: userConfig.environment || 'DRAFT',
27
- flowsEnvironment: userConfig.flowsEnvironment || 'LIVE',
28
- authToken: userConfig.authToken,
29
- tenantId: userConfig.tenantId,
30
- spaceId: userConfig.spaceId,
31
- customAuth: (_a = userConfig.customAuth) !== null && _a !== void 0 ? _a : true,
32
- };
33
- }
34
- function getConfig() {
35
- if (!config)
36
- throw new Error('Fastn not initialized.');
37
- return config;
38
- }
39
-
40
- // Unique ID creation requires a high quality random # generator. In the browser we therefore
41
- // require the crypto API and do not support built-in fallback to lower quality random number
42
- // generators (like Math.random()).
43
- let getRandomValues;
44
- const rnds8 = new Uint8Array(16);
45
- function rng() {
46
- // lazy load so that environments that need to polyfill have a chance to do so
47
- if (!getRandomValues) {
48
- // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
49
- getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
50
-
51
- if (!getRandomValues) {
52
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
53
- }
54
- }
55
-
56
- return getRandomValues(rnds8);
57
- }
58
-
59
- /**
60
- * Convert array of 16 byte values to UUID string format of the form:
61
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
62
- */
63
-
64
- const byteToHex = [];
65
-
66
- for (let i = 0; i < 256; ++i) {
67
- byteToHex.push((i + 0x100).toString(16).slice(1));
68
- }
69
-
70
- function unsafeStringify(arr, offset = 0) {
71
- // Note: Be careful editing this code! It's been tuned for performance
72
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
73
- return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
74
- }
75
-
76
- const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
77
- var native = {
78
- randomUUID
79
- };
80
-
81
- function v4(options, buf, offset) {
82
- if (native.randomUUID && true && !options) {
83
- return native.randomUUID();
84
- }
85
-
86
- options = options || {};
87
- const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
88
-
89
- rnds[6] = rnds[6] & 0x0f | 0x40;
90
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
91
-
92
- return unsafeStringify(rnds);
93
- }
94
-
95
- /**
96
- * Supported field types for connector forms.
97
- */
98
- var ConnectorFieldType;
99
- (function (ConnectorFieldType) {
100
- ConnectorFieldType["TEXT"] = "text";
101
- ConnectorFieldType["NUMBER"] = "number";
102
- ConnectorFieldType["CHECKBOX"] = "checkbox";
103
- ConnectorFieldType["DATE"] = "date";
104
- ConnectorFieldType["DATETIME"] = "datetime";
105
- ConnectorFieldType["TIME"] = "time";
106
- ConnectorFieldType["DATETIME_LOCAL"] = "datetime-local";
107
- ConnectorFieldType["MULTI_SELECT"] = "multi-select";
108
- ConnectorFieldType["SELECT"] = "select";
109
- ConnectorFieldType["GOOGLE_FILES_PICKER_SELECT"] = "google-files-picker-select";
110
- ConnectorFieldType["GOOGLE_FILES_PICKER_MULTI_SELECT"] = "google-files-picker-multi-select";
111
- })(ConnectorFieldType || (ConnectorFieldType = {}));
112
- /**
113
- * Supported action types for connectors and configurations.
114
- */
115
- var ConnectorActionType;
116
- (function (ConnectorActionType) {
117
- ConnectorActionType["ACTIVATION"] = "ACTIVATION";
118
- ConnectorActionType["DEACTIVATION"] = "DEACTIVATION";
119
- ConnectorActionType["NONE"] = "NONE";
120
- ConnectorActionType["ENABLE"] = "ENABLE";
121
- ConnectorActionType["DISABLE"] = "DISABLE";
122
- ConnectorActionType["DELETE"] = "DELETE";
123
- })(ConnectorActionType || (ConnectorActionType = {}));
124
- /**
125
- * Status of a connector.
126
- */
127
- var ConnectorStatus;
128
- (function (ConnectorStatus) {
129
- ConnectorStatus["ACTIVE"] = "ACTIVE";
130
- ConnectorStatus["INACTIVE"] = "INACTIVE";
131
- ConnectorStatus["ALL"] = "ALL";
132
- })(ConnectorStatus || (ConnectorStatus = {}));
133
- /**
134
- * Supported resource actions for connectors and configurations.
135
- */
136
- var ResourceAction;
137
- (function (ResourceAction) {
138
- ResourceAction["ACTIVATION"] = "ACTIVATION";
139
- ResourceAction["DEACTIVATION"] = "DEACTIVATION";
140
- ResourceAction["CONFIGURE"] = "CONFIGURE";
141
- ResourceAction["UNCONFIGURE"] = "UNCONFIGURE";
142
- ResourceAction["FLOW_EXECUTION"] = "FLOW_EXECUTION";
143
- ResourceAction["QUERY"] = "QUERY";
144
- ResourceAction["ENABLE_CONFIGURATION"] = "ENABLE_CONFIGURATION";
145
- ResourceAction["UPDATE_CONFIGURATION"] = "UPDATE_CONFIGURATION";
146
- ResourceAction["DISABLE_CONFIGURATION"] = "DISABLE_CONFIGURATION";
147
- ResourceAction["DELETE_CONFIGURATION"] = "DELETE_CONFIGURATION";
148
- })(ResourceAction || (ResourceAction = {}));
149
-
150
- const getCustomAuthContextValue = (operationName, variables) => {
151
- var _a;
152
- try {
153
- if (!operationName)
154
- return "";
155
- return btoa(JSON.stringify(getCustomAuthContext(operationName, (_a = variables === null || variables === void 0 ? void 0 : variables.input) !== null && _a !== void 0 ? _a : {})));
156
- }
157
- catch (error) {
158
- console.error("Error getting custom auth context value:", error);
159
- return "";
160
- }
161
- };
162
- const getCustomAuthContext = (operationName, input) => {
163
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
164
- if (!operationName)
165
- return {};
166
- try {
167
- let action = ResourceAction.QUERY;
168
- let resourceId = "";
169
- switch (operationName) {
170
- case "metadata":
171
- case "connectors":
172
- case "api":
173
- case "tenantflow":
174
- case "generateaccesstoken":
175
- break;
176
- case "deactivateconnector":
177
- action = ResourceAction.DEACTIVATION;
178
- resourceId = (_a = input.connectorId) !== null && _a !== void 0 ? _a : "";
179
- break;
180
- case "configuretenantflow":
181
- action = ResourceAction.CONFIGURE;
182
- resourceId = (_b = input.connectorId) !== null && _b !== void 0 ? _b : "";
183
- break;
184
- case "deletetenantconfiguration":
185
- action = ResourceAction.UNCONFIGURE;
186
- resourceId = (_c = input.connectorId) !== null && _c !== void 0 ? _c : "";
187
- break;
188
- case "createtenantconfiguration":
189
- action = ResourceAction.ENABLE_CONFIGURATION;
190
- resourceId = (_d = input.connectorId) !== null && _d !== void 0 ? _d : "";
191
- break;
192
- case "updatetenantconfiguration":
193
- action = ResourceAction.UPDATE_CONFIGURATION;
194
- resourceId = (_e = input.connectorId) !== null && _e !== void 0 ? _e : "";
195
- break;
196
- case "disabletenantconfig":
197
- action = ResourceAction.DISABLE_CONFIGURATION;
198
- resourceId = (_f = input.connectorId) !== null && _f !== void 0 ? _f : "";
199
- break;
200
- case "deletetenantconfig":
201
- action = ResourceAction.DELETE_CONFIGURATION;
202
- resourceId = (_g = input.connectorId) !== null && _g !== void 0 ? _g : "";
203
- break;
204
- default:
205
- resourceId = (_j = (_h = input.clientId) !== null && _h !== void 0 ? _h : input.projectId) !== null && _j !== void 0 ? _j : "";
206
- }
207
- return { action, resourceId };
208
- }
209
- catch (error) {
210
- console.error("Error parsing custom auth context:", error);
211
- return {};
212
- }
213
- };
214
- const addCustomAuthContextHeader = (headers, context) => {
215
- try {
216
- const contextString = JSON.stringify(context);
217
- const encodedContext = btoa(contextString);
218
- headers[CUSTOM_AUTH_CONTEXT_HEADER_KEY] = encodedContext;
219
- }
220
- catch (error) {
221
- console.warn("Error adding custom auth context header:", error);
222
- }
223
- return headers;
224
- };
225
- const getOauthPopUpDimensions = () => {
226
- const screenWidth = window.innerWidth;
227
- const screenHeight = window.innerHeight;
228
- const width = Math.min(screenWidth - 100, 900);
229
- const height = Math.min(screenHeight - 100, 900);
230
- const top = Math.max((screenHeight - height) / 2, 100);
231
- const left = Math.max((screenWidth - width) / 2, 50);
232
- return { width, height, top, left };
233
- };
234
- function encodeState(state) {
235
- const { domain, uuid } = state;
236
- return btoa(`${domain}#${uuid}`);
237
- }
238
- const templateObjectValues = (obj, values) => {
239
- try {
240
- let objString = JSON.stringify(obj);
241
- Object.keys(values).forEach((key) => {
242
- objString = objString.replace(new RegExp(`{{${key}}}`, "g"), values[key]);
243
- });
244
- return JSON.parse(objString);
245
- }
246
- catch (error) {
247
- console.warn("Error templating object values", error);
248
- return undefined;
249
- }
250
- };
251
- const generateAuthUrl = ({ oauthDetails, formData = {}, }) => {
252
- var _a, _b;
253
- try {
254
- const templatedDetails = (_a = templateObjectValues(oauthDetails, formData)) !== null && _a !== void 0 ? _a : oauthDetails;
255
- const params = Object.assign({}, ((_b = templatedDetails === null || templatedDetails === void 0 ? void 0 : templatedDetails.params) !== null && _b !== void 0 ? _b : {}));
256
- if (templatedDetails.clientId)
257
- params.client_id = templatedDetails.clientId;
258
- params.redirect_uri = PROD_OAUTH_REDIRECT_URL;
259
- params.state = encodeState({ domain: "widget", uuid: "none" });
260
- const paramsString = Object.entries(params)
261
- .map(([key, val]) => `${key}=${encodeURIComponent(val)}`)
262
- .join("&");
263
- return templatedDetails.baseUrl ? `${templatedDetails.baseUrl}?${paramsString}` : "";
264
- }
265
- catch (error) {
266
- console.error("Error generating auth URL:", error);
267
- return "";
268
- }
269
- };
270
- const getParams = (paramsString = window.location.search) => {
271
- try {
272
- const searchParams = new URLSearchParams(paramsString);
273
- const params = {};
274
- for (const [key, value] of searchParams.entries()) {
275
- params[key] = value;
276
- }
277
- return params;
278
- }
279
- catch (_a) {
280
- return {};
281
- }
282
- };
283
- const getFieldsFromContract = (contract) => {
284
- return Object.keys(contract)
285
- .map((key) => {
286
- var _a, _b, _c, _d, _e, _f, _g, _h;
287
- const field = contract[key];
288
- if (typeof field !== "object")
289
- return null;
290
- return {
291
- name: key,
292
- label: (_a = field.description) !== null && _a !== void 0 ? _a : "",
293
- initialValue: (_d = (_c = (_b = field.default) !== null && _b !== void 0 ? _b : field.defaultValue) !== null && _c !== void 0 ? _c : field.initialValue) !== null && _d !== void 0 ? _d : field.v,
294
- required: (_e = field.required) !== null && _e !== void 0 ? _e : false,
295
- type: (_f = field.type) !== null && _f !== void 0 ? _f : "text",
296
- hidden: (_g = field.hidden) !== null && _g !== void 0 ? _g : false,
297
- disabled: (_h = field.disabled) !== null && _h !== void 0 ? _h : false,
298
- };
299
- })
300
- .filter(Boolean);
301
- };
302
- const inputContractToFormData = (inputContract) => {
303
- var _a, _b;
304
- try {
305
- const fields = getFieldsFromContract(inputContract !== null && inputContract !== void 0 ? inputContract : {});
306
- if (!fields.length)
307
- return null;
308
- return {
309
- fields,
310
- description: (_a = inputContract.description) !== null && _a !== void 0 ? _a : "",
311
- submitButtonLabel: (_b = inputContract.submitLabel) !== null && _b !== void 0 ? _b : "Connect",
312
- };
313
- }
314
- catch (error) {
315
- console.warn("Error converting input contract to form data:", error);
316
- return null;
317
- }
318
- };
319
- const convertUiCodeFormDataToFormData = (formData) => {
320
- try {
321
- const { target, targetType } = formData;
322
- if (targetType === "object" && typeof target === "object" && target !== null) {
323
- const data = {};
324
- Object.keys(target).forEach((key) => {
325
- data[key] = convertUiCodeFormDataToFormData(target[key]);
326
- });
327
- return data;
328
- }
329
- else if (targetType === "array" && Array.isArray(target)) {
330
- return target.map((item) => convertUiCodeFormDataToFormData(item));
331
- }
332
- else {
333
- return target;
334
- }
335
- }
336
- catch (_a) {
337
- return formData;
338
- }
339
- };
340
- const safeParse = (jsonString) => {
341
- try {
342
- if (typeof jsonString === "object")
343
- return jsonString;
344
- return JSON.parse(jsonString);
345
- }
346
- catch (_a) {
347
- return {};
348
- }
349
- };
350
- const safeStringify = (json) => {
351
- try {
352
- return typeof json === "string" ? json : JSON.stringify(json);
353
- }
354
- catch (_a) {
355
- return "";
356
- }
357
- };
358
- function formatApolloErrors(error) {
359
- var _a;
360
- if (!error)
361
- return "";
362
- const code = (_a = error === null || error === void 0 ? void 0 : error.cause) === null || _a === void 0 ? void 0 : _a.code;
363
- try {
364
- switch (code) {
365
- case "RESOURCE_NOT_FOUND":
366
- case "resource_not_found":
367
- return "The requested resource could not be found";
368
- case "RESOURCE_ALREADY_EXISTS":
369
- case "resource_already_exists":
370
- return "The resource you are trying to create already exists";
371
- case "UNAUTHORIZED":
372
- case "unauthorized":
373
- case "UNAUTHORIZED_ERROR":
374
- return "You are not authorized to perform this operation";
375
- case "UNAUTHENTICATED":
376
- case "unauthenticated":
377
- case "UNAUTHENTICATED_ERROR":
378
- return "You are not authenticated to perform this operation";
379
- case "INTERNAL_SERVER_ERROR":
380
- case "internal_server_error":
381
- return "An unexpected error occurred on the server. Please try again later";
382
- default:
383
- return (error === null || error === void 0 ? void 0 : error.message) || "An unknown error occurred. Please try again.";
384
- }
385
- }
386
- catch (err) {
387
- return "An error occurred while processing the error. Please try again.";
388
- }
389
- }
390
- const getFieldType = (field) => {
391
- if (field.targetType === "array" && field.configs.selection.enable)
392
- return ConnectorFieldType.MULTI_SELECT;
393
- if (field.targetType === "object" && field.configs.selection.enable)
394
- return ConnectorFieldType.SELECT;
395
- if (field.targetType === "string")
396
- return ConnectorFieldType.TEXT;
397
- if (field.targetType === "number")
398
- return ConnectorFieldType.NUMBER;
399
- if (field.targetType === "boolean")
400
- return ConnectorFieldType.CHECKBOX;
401
- if (field.targetType === "date")
402
- return ConnectorFieldType.DATE;
403
- if (field.targetType === "datetime")
404
- return ConnectorFieldType.DATETIME;
405
- if (field.targetType === "time")
406
- return ConnectorFieldType.TIME;
407
- if (field.targetType === "datetime-local")
408
- return ConnectorFieldType.DATETIME_LOCAL;
409
- return ConnectorFieldType.TEXT;
410
- };
411
- const uiCodeToFormFields = (uiCodeString, options) => {
412
- try {
413
- const parsed = safeParse(uiCodeString);
414
- const { targetType, target } = parsed;
415
- const values = convertUiCodeFormDataToFormData(parsed);
416
- if (targetType !== 'object' || typeof target !== 'object' || target === null) {
417
- return [];
418
- }
419
- return Object.entries(target).map(([key, rawField]) => {
420
- var _a;
421
- const { configs = {}, default: defaultValue, } = rawField;
422
- const { label = key, description = '', required = false, placeholder = '', hideOption = {}, selection, } = configs;
423
- const field = {
424
- key,
425
- name: key,
426
- label: label !== null && label !== void 0 ? label : key,
427
- description,
428
- initialValue: (_a = values[key]) !== null && _a !== void 0 ? _a : defaultValue,
429
- type: getFieldType(rawField),
430
- required: Boolean(required),
431
- hidden: Boolean((hideOption === null || hideOption === void 0 ? void 0 : hideOption.enable) || key === "connectorId" || key === "id"),
432
- disabled: Boolean((hideOption === null || hideOption === void 0 ? void 0 : hideOption.enable) || key === "connectorId" || key === "id"),
433
- placeholder,
434
- };
435
- if (selection === null || selection === void 0 ? void 0 : selection.enable) {
436
- if (selection.type === 'CUSTOM' && selection.customSelector === 'GOOGLE_FILES_PICKER') {
437
- return Object.assign(Object.assign({}, field), { type: field.type === ConnectorFieldType.MULTI_SELECT ? ConnectorFieldType.GOOGLE_FILES_PICKER_MULTI_SELECT : ConnectorFieldType.GOOGLE_FILES_PICKER_SELECT, optionsSource: {
438
- type: 'GOOGLE_FILES_PICKER',
439
- openGoogleFilesPicker: options.openGoogleFilesPicker,
440
- } });
441
- }
442
- else if (selection.flowId) {
443
- const pagination = Object.assign(Object.assign({ sourceId: selection.flowId, sourceProject: selection.isSameProject ? 'self' : 'community', limit: selection.limit, type: selection.type }, (selection.type === 'OFFSET' && selection.offset != null ? { offset: selection.offset } : {})), (selection.type === 'CURSOR' && selection.cursor != null ? { cursor: selection.cursor } : {}));
444
- return Object.assign(Object.assign({}, field), { optionsSource: {
445
- type: 'DYNAMIC',
446
- pagination,
447
- getOptions: options.getOptions,
448
- loadMore: options.loadMore,
449
- refresh: options.refresh,
450
- searchOptions: options.searchOptions,
451
- } });
452
- }
453
- else if (Array.isArray(selection.list)) {
454
- return Object.assign(Object.assign({}, field), { optionsSource: {
455
- type: 'STATIC',
456
- staticOptions: selection.list.map((item) => ({
457
- label: item.title,
458
- value: item.value,
459
- })),
460
- } });
461
- }
462
- }
463
- return field;
464
- });
465
- }
466
- catch (error) {
467
- console.warn('Error parsing UI code to form fields:', error);
468
- return [];
469
- }
470
- };
471
- function populateFormDataInUiCode(uiCodeString, formData) {
472
- const uiCode = safeParse(uiCodeString) || {};
473
- const { target, targetType } = uiCode;
474
- if (!target || !targetType)
475
- return uiCode;
476
- if (targetType === "object") {
477
- const updatedTarget = Object.keys(target).reduce((acc, key) => {
478
- var _a;
479
- const value = formData[key];
480
- if (value !== undefined) {
481
- acc[key] = Object.assign(Object.assign({}, target[key]), { target: (_a = convertFormDataToUiCodeFormData(value)) === null || _a === void 0 ? void 0 : _a.target });
482
- }
483
- else {
484
- acc[key] = target[key];
485
- }
486
- return acc;
487
- }, {});
488
- return Object.assign(Object.assign({}, uiCode), { target: updatedTarget });
489
- }
490
- else if (targetType === "array" && Array.isArray(target)) {
491
- const updatedTarget = target.map((item, index) => {
492
- const updatedItem = Object.assign({}, item);
493
- // Assuming item has a unique key (e.g., id or name) to match formData fields
494
- Object.keys(item).forEach((key) => {
495
- var _a, _b;
496
- const formValue = (_a = formData[`${index}.${key}`]) !== null && _a !== void 0 ? _a : formData[key];
497
- if (formValue !== undefined) {
498
- updatedItem[key] = Object.assign(Object.assign({}, item[key]), { target: (_b = convertFormDataToUiCodeFormData(formValue)) === null || _b === void 0 ? void 0 : _b.target });
499
- }
500
- });
501
- return updatedItem;
502
- });
503
- return Object.assign(Object.assign({}, uiCode), { target: updatedTarget });
504
- }
505
- return uiCode;
506
- }
507
- const convertFormDataToUiCodeFormData = (formData) => {
508
- if (Array.isArray(formData)) {
509
- return {
510
- actionType: "map",
511
- targetType: "array",
512
- target: formData.map((item) => convertFormDataToUiCodeFormData(item)),
513
- };
514
- }
515
- else if (formData !== null && typeof formData === "object") {
516
- const target = {};
517
- for (const key in formData) {
518
- target[key] = convertFormDataToUiCodeFormData(formData[key]);
519
- }
520
- return {
521
- actionType: "map",
522
- targetType: "object",
523
- target,
524
- };
525
- }
526
- else if (typeof formData === "string") {
527
- return {
528
- actionType: "map",
529
- targetType: "string",
530
- target: formData,
531
- };
532
- }
533
- else if (typeof formData === "number") {
534
- return {
535
- actionType: "map",
536
- targetType: "number",
537
- target: formData,
538
- };
539
- }
540
- else if (typeof formData === "boolean") {
541
- return {
542
- actionType: "map",
543
- targetType: "boolean",
544
- target: formData,
545
- };
546
- }
547
- else {
548
- return {
549
- actionType: "map",
550
- targetType: "string",
551
- target: formData,
552
- };
553
- }
554
- };
555
- /**
556
- * Recursively removes __typename fields from an object or array.
557
- */
558
- function stripTypename(obj) {
559
- if (Array.isArray(obj)) {
560
- return obj.map(stripTypename);
561
- }
562
- else if (obj && typeof obj === 'object') {
563
- const newObj = {};
564
- for (const key in obj) {
565
- if (key === '__typename')
566
- continue;
567
- newObj[key] = stripTypename(obj[key]);
568
- }
569
- return newObj;
570
- }
571
- return obj;
572
- }
573
-
574
- // GraphQL endpoint (customize as needed)
575
- const GRAPHQL_ENDPOINT = "/graphql";
576
- // Utility to perform GraphQL queries/mutations using fetch
577
- async function fetchGraphQL({ query, variables, operationName }) {
578
- const config = getConfig();
579
- const response = await fetch(config.baseUrl + GRAPHQL_ENDPOINT, {
580
- method: "POST",
581
- headers: {
582
- "Content-Type": "application/json",
583
- authorization: `Bearer ${config.authToken}`,
584
- realm: REALM,
585
- [CUSTOM_AUTH_HEADER_KEY]: String(config.customAuth),
586
- [PROJECT_ID_HEADER_KEY]: config.spaceId,
587
- [TENANT_ID_HEADER_KEY]: config.tenantId,
588
- [REQUEST_TRACE_ID_HEADER_KEY]: `react-ai-core-${v4()}`,
589
- [CUSTOM_AUTH_CONTEXT_HEADER_KEY]: getCustomAuthContextValue(operationName, variables),
590
- },
591
- body: JSON.stringify({ query, variables }),
592
- });
593
- if (!response.ok) {
594
- switch (response.status) {
595
- case 401:
596
- throw new Error("Unauthorized: Please check your auth token");
597
- case 403:
598
- throw new Error("Forbidden: Please check your access");
599
- case 404:
600
- throw new Error("Not Found: Please check your request");
601
- default:
602
- throw new Error("Failed to fetch: Please check your request");
603
- }
604
- }
605
- const result = await response.json();
606
- if (result.errors) {
607
- throw new Error(result.errors.map((e) => e.message).join("; "));
608
- }
609
- return {
610
- data: result.data,
611
- errors: result.errors
612
- };
613
- }
614
- // GraphQL Queries & Mutations (as plain strings)
615
- const GET_WIDGET_CONNECTORS = `
616
- query Connectors($input: GetConnectorsListInput!) {
617
- connectors(input: $input) {
618
- name
619
- id
620
- imageUri
621
- description
622
- content
623
- actions {
624
- name
625
- handler
626
- actionType
627
- activatedStateLabel
628
- content
629
- shows
630
- handlerPayload
631
- multiConnectorWidgetConnectors {
632
- name
633
- id
634
- imageUri
635
- description
636
- content
637
- connectionId
638
- actions {
639
- name
640
- handler
641
- actionType
642
- activatedStateLabel
643
- content
644
- shows
645
- handlerPayload
646
- }
647
- events {
648
- name
649
- eventId
650
- content
651
- payload
652
- }
653
- connectedConnectors {
654
- id
655
- imageUrl
656
- clientId
657
- name
658
- enableActivate
659
- activateStatus
660
- authMethods {
661
- title
662
- inputContract
663
- type
664
- details
665
- isDefault
666
- }
667
- }
668
- status
669
- }
670
- }
671
- events {
672
- name
673
- eventId
674
- content
675
- payload
676
- }
677
- connectedConnectors {
678
- id
679
- imageUrl
680
- clientId
681
- name
682
- enableActivate
683
- activateStatus
684
- authMethods {
685
- title
686
- inputContract
687
- type
688
- details
689
- isDefault
690
- }
691
- }
692
- status
693
- }
694
- }
695
- `;
696
- const SAVE_ACTIVATE_CONNECTOR_STATUS = `
697
- mutation SaveActivateConnectorStatus(
698
- $input: SaveWidgetConnectorStatusInput!
699
- ) {
700
- saveWidgetConnectorStatus(input: $input)
701
- }
702
- `;
703
- const DEACTIVATE_CONNECTOR = `
704
- mutation DeactivateConnector($input: DeactivateConnectorInput!) {
705
- deactivateConnector(input: $input)
706
- }
707
- `;
708
- const GET_FIELD_DATA_QUERY = `
709
- query executeGetFieldDataFlow($input: ApiPrimaryResolverInvocationInput!) {
710
- executeGetFieldDataFlow(input: $input) {
711
- data
712
- }
713
- }
714
- `;
715
- const GET_TENANT_CONFIGURATIONS = `
716
- query GetConfigurationSubscription($input: ConfigurationSubscriptionInput!) {
717
- getConfigurationSubscription(input: $input) {
718
- connector {
719
- id
720
- name
721
- description
722
- imageUri
723
- status
724
- active
725
- actions {
726
- name
727
- handler
728
- actionType
729
- }
730
- connectedConnectors {
731
- id
732
- name
733
- clientId
734
- imageUrl
735
- enableActivate
736
- activateStatus
737
- authMethods {
738
- title
739
- inputContract
740
- type
741
- details
742
- isDefault
743
- }
744
- }
745
- }
746
- status
747
- metaData
748
- }
749
- }
750
- `;
751
- const GET_TENANT_CONFIGURATIONS_BY_ID = `
752
- query GetConfigurationSubscription($input: GetTenantConfigurationsInput) {
753
- tenantConfigurationsById(input: $input) {
754
- uiCode
755
- flowId
756
- stepId
757
- status
758
- configurations
759
- configuredStepSetting {
760
- keyIsEditable
761
- addButton {
762
- label
763
- isDisabled
764
- fieldsLimit
765
- }
766
- description
767
- label
768
- validation {
769
- fieldValidation
770
- submitValidation
771
- modelId
772
- jsonSchema
773
- submitValidationFunction
774
- }
775
- }
776
- }
777
- }
778
- `;
779
- const CREATE_TENANT_CONFIGURATION = `
780
- mutation CreateTenantConfiguration($input: TenantConfigurationsInput!) {
781
- createTenantConfiguration(input: $input) {
782
- id
783
- }
784
- }
785
- `;
786
- const UPDATE_TENANT_CONFIGURATION = `
787
- mutation UpdateTenantConfiguration($input: TenantConfigurationsInput!) {
788
- updateTenantConfiguration(input: $input) {
789
- id
790
- }
791
- }
792
- `;
793
- const DELETE_TENANT_CONFIG = `
794
- mutation DeleteTenantConfig($input: GetTenantConfigurationsInput!) {
795
- deleteTenantConfig(input: $input) {
796
- id
797
- }
798
- }
799
- `;
800
- const DISABLE_TENANT_CONFIG = `
801
- mutation DisableTenantConfig($input: GetTenantConfigurationsInput!) {
802
- disableTenantConfig(input: $input) {
803
- id
804
- }
805
- }
806
- `;
807
- const GENERATE_ACCESS_TOKEN = `
808
- query GenerateAccessToken($input: ConnectorConnectionInput!) {
809
- connectorConnection(input: $input)
810
- }
811
- `;
812
- // Refactored functions using fetchGraphQL
813
- async function getConnectors$1(variables) {
814
- return fetchGraphQL({ query: GET_WIDGET_CONNECTORS, variables, operationName: "connectors" });
815
- }
816
- async function saveActivateConnectorStatus(variables) {
817
- return fetchGraphQL({ query: SAVE_ACTIVATE_CONNECTOR_STATUS, variables, operationName: "saveactivatconnectorstatus" });
818
- }
819
- async function deactivateConnector$1(variables) {
820
- return fetchGraphQL({ query: DEACTIVATE_CONNECTOR, variables, operationName: "deactivateConnector" });
821
- }
822
- async function getFieldData(variables) {
823
- return fetchGraphQL({ query: GET_FIELD_DATA_QUERY, variables, operationName: "executeGetFieldDataFlow" });
824
- }
825
- async function getConfigurationSubscriptions(variables) {
826
- return fetchGraphQL({ query: GET_TENANT_CONFIGURATIONS, variables, operationName: "getconfigurationsubscription" });
827
- }
828
- async function getConfigurationSubscriptionById(variables) {
829
- return fetchGraphQL({ query: GET_TENANT_CONFIGURATIONS_BY_ID, variables, operationName: "getconfigurationsubscriptionbyid" });
830
- }
831
- async function createTenantConfiguration(variables) {
832
- return fetchGraphQL({ query: CREATE_TENANT_CONFIGURATION, variables, operationName: "createtenantconfiguration" });
833
- }
834
- async function updateTenantConfiguration(variables) {
835
- return fetchGraphQL({ query: UPDATE_TENANT_CONFIGURATION, variables, operationName: "updatetenantconfiguration" });
836
- }
837
- async function deleteTenantConfig(variables) {
838
- return fetchGraphQL({ query: DELETE_TENANT_CONFIG, variables, operationName: "deletetenantconfig" });
839
- }
840
- async function disableTenantConfig(variables) {
841
- return fetchGraphQL({ query: DISABLE_TENANT_CONFIG, variables, operationName: "disabletenantconfig" });
842
- }
843
- async function generateAccessToken(variables) {
844
- return fetchGraphQL({ query: GENERATE_ACCESS_TOKEN, variables, operationName: "generateaccesstoken" });
845
- }
846
-
847
- /**
848
- * Returns the backend URL for flow execution, appending /v1 if needed.
849
- */
850
- const getBackendUrl = () => {
851
- var _a;
852
- const config = getConfig();
853
- return ((_a = config.baseUrl) === null || _a === void 0 ? void 0 : _a.endsWith("/api")) ? config.baseUrl + "/v1" : `${config.baseUrl}/api/v1`;
854
- };
855
- /**
856
- * Executes a backend flow with the given path, input, and headers.
857
- * @returns {Promise<any>} The response data from the backend.
858
- */
859
- const executeFLow = async ({ path, input = {}, headers = {} }) => {
860
- try {
861
- const config = getConfig();
862
- const backendUrl = getBackendUrl();
863
- const response = await fetch(`${backendUrl}/${path}`, {
864
- method: "POST",
865
- headers: Object.assign({ "Content-Type": "application/json", [PROJECT_ID_HEADER_KEY]: config.spaceId, [TENANT_ID_HEADER_KEY]: config.tenantId, authorization: `${config.authToken}`, stage: config.flowsEnvironment }, headers),
866
- body: JSON.stringify({
867
- "input": input
868
- })
869
- });
870
- if (!response.ok) {
871
- throw new Error(`Failed to execute flow: ${response.statusText}`);
872
- }
873
- const data = await response.json();
874
- return data;
875
- }
876
- catch (error) {
877
- console.error("Error in executeFLow:", error);
878
- throw error;
879
- }
880
- };
881
-
882
- /**
883
- * Builds the request input for connector activation.
884
- */
885
- const buildRequestInput = (dependencyConnector, authMethod, formData) => {
886
- var _a;
887
- const config = getConfig();
888
- return {
889
- fastn_connection: {
890
- projectId: config === null || config === void 0 ? void 0 : config.spaceId,
891
- domain: (_a = config.baseUrl) === null || _a === void 0 ? void 0 : _a.replace("https://", "").replace("/api", "").replace("api", ""),
892
- redirectUri: PROD_OAUTH_REDIRECT_URL
893
- },
894
- oauth: {
895
- connector: {
896
- id: dependencyConnector === null || dependencyConnector === void 0 ? void 0 : dependencyConnector.id,
897
- clientId: dependencyConnector === null || dependencyConnector === void 0 ? void 0 : dependencyConnector.clientId,
898
- name: dependencyConnector === null || dependencyConnector === void 0 ? void 0 : dependencyConnector.name,
899
- isOauth: (authMethod === null || authMethod === void 0 ? void 0 : authMethod.type) === "OAUTH",
900
- oauth: authMethod === null || authMethod === void 0 ? void 0 : authMethod.details,
901
- input: formData,
902
- },
903
- response: {}
904
- }
905
- };
906
- };
907
- /**
908
- * Calls the backend to activate a connector.
909
- */
910
- const callActivateConnector = async (input, headers) => {
911
- const config = getConfig();
912
- const url = config.baseUrl + ACTIVATE_CONNECTOR_URL;
913
- const response = await fetch(url, {
914
- method: "POST",
915
- headers: Object.assign(Object.assign({ "Content-Type": "application/json" }, headers), { "x-fastn-api-key": ACTIVATE_CONNECTOR_ACCESS_KEY, "x-fastn-space-id": ACTIVATE_CONNECTOR_PROJECT_ID, "x-fastn-space-client-id": config.spaceId, 'stage': "LIVE" }),
916
- body: JSON.stringify({
917
- input
918
- })
919
- });
920
- if (!response.ok) {
921
- throw new Error(`Failed to activate connector: ${response.statusText}`);
922
- }
923
- const responseData = await response.json();
924
- return responseData.data;
925
- };
926
- /**
927
- * Handles the OAuth flow for connector activation.
928
- */
929
- const handleOauthFlow = async (authMethod, formData, input) => {
930
- const config = getConfig();
931
- const authUrl = generateAuthUrl({ oauthDetails: authMethod.details, formData });
932
- const { width, height, top, left } = getOauthPopUpDimensions();
933
- const oAuthPopUpWindow = window.open(authUrl, "OAuthPopup", `width=${width},height=${height},top=${top},left=${left}`);
934
- return new Promise((resolve, reject) => {
935
- let params = null;
936
- const messageListener = async (event) => {
937
- var _a;
938
- if (event.origin === PROD_OAUTH_REDIRECT_URL && ((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) === "oauth_complete" && !params) {
939
- params = getParams(event.data.params);
940
- window.removeEventListener("message", messageListener);
941
- clearInterval(closePopupInterval);
942
- try {
943
- input.oauth.response = params;
944
- const data = await callActivateConnector(input, {
945
- [TENANT_ID_HEADER_KEY]: config === null || config === void 0 ? void 0 : config.tenantId,
946
- [CUSTOM_AUTH_HEADER_KEY]: String(config === null || config === void 0 ? void 0 : config.customAuth),
947
- authorization: config === null || config === void 0 ? void 0 : config.authToken
948
- });
949
- resolve({ data, status: "SUCCESS" });
950
- }
951
- catch (error) {
952
- console.error("Error in handleOauthFlow", error);
953
- reject(error);
954
- }
955
- finally {
956
- }
957
- }
958
- };
959
- const closePopupInterval = setInterval(() => {
960
- if (oAuthPopUpWindow.closed) {
961
- clearInterval(closePopupInterval);
962
- if (!params) {
963
- window.removeEventListener("message", messageListener);
964
- resolve({
965
- data: { message: "Popup closed without completing OAuth" },
966
- status: "CANCELLED"
967
- });
968
- }
969
- }
970
- }, 1000);
971
- window.addEventListener("message", messageListener);
972
- });
973
- };
974
- /**
975
- * Framework-agnostic activateConnector utility.
976
- * @param args - Activation arguments (connectorId, action, dependencyConnector, authMethod, input, saveStatusFn, executeActionHandlerFn, config)
977
- * @returns {Promise<{ status: string; data: any }>}
978
- */
979
- const activateConnector = async ({ connectorId, action, dependencyConnector, authMethod, input = {}, }) => {
980
- try {
981
- const config = getConfig();
982
- // Activate the connector
983
- let response = await activateConnectorCore({
984
- dependencyConnector,
985
- authMethod,
986
- formData: input,
987
- });
988
- if ((response === null || response === void 0 ? void 0 : response.status) === "CANCELLED") {
989
- return { data: null, status: "CANCELLED" };
990
- }
991
- // Execute the action handler
992
- response = await executeActionHandler(action === null || action === void 0 ? void 0 : action.handler, addCustomAuthContextHeader({}, { resourceId: connectorId, action: ResourceAction.ACTIVATION }));
993
- // Save connector status
994
- await saveActivateConnectorStatus({
995
- input: {
996
- projectId: config.spaceId,
997
- tenantId: config.tenantId,
998
- connectorId,
999
- isDependencyConnector: false,
1000
- }
1001
- });
1002
- return {
1003
- status: "SUCCESS",
1004
- data: response,
1005
- };
1006
- }
1007
- catch (error) {
1008
- console.error("Error in activateConnector:", error);
1009
- throw error;
1010
- }
1011
- };
1012
- /**
1013
- * Framework-agnostic deactivateConnector utility.
1014
- * @param args - Deactivation arguments (connectorId, action, deactivateConnectorFn, executeActionHandlerFn, config)
1015
- * @returns {Promise<{ status: string; data: any }>}
1016
- */
1017
- const deactivateConnector = async ({ connectorId, action, }) => {
1018
- try {
1019
- const config = getConfig();
1020
- // Execute the action handler
1021
- let response = {};
1022
- response = await executeActionHandler(action === null || action === void 0 ? void 0 : action.handler, addCustomAuthContextHeader({}, { resourceId: connectorId, action: ResourceAction.DEACTIVATION }));
1023
- // Deactivate the connector
1024
- await deactivateConnector$1({
1025
- input: {
1026
- projectId: config.spaceId,
1027
- tenantId: config.tenantId,
1028
- connectorId,
1029
- }
1030
- });
1031
- return {
1032
- status: "SUCCESS",
1033
- data: response,
1034
- };
1035
- }
1036
- catch (error) {
1037
- console.error("Error in deactivateConnector:", error);
1038
- throw error;
1039
- }
1040
- };
1041
- /**
1042
- * Framework-agnostic executeActionHandler utility.
1043
- * @param handler - The handler path or function
1044
- * @param headers - Optional headers
1045
- * @returns {Promise<any>}
1046
- */
1047
- const executeActionHandler = async (handler, headers = {}) => {
1048
- try {
1049
- if (!handler) {
1050
- return {
1051
- status: "SUCCESS",
1052
- data: {},
1053
- };
1054
- }
1055
- const response = await executeFLow({ path: handler, headers });
1056
- return response;
1057
- }
1058
- catch (error) {
1059
- console.warn("Error executing action handler:", error);
1060
- throw error;
1061
- }
1062
- };
1063
- // Core activation logic for internal use
1064
- const activateConnectorCore = async ({ dependencyConnector, authMethod, formData }) => {
1065
- try {
1066
- const input = buildRequestInput(dependencyConnector, authMethod, formData);
1067
- const isOauth = (authMethod === null || authMethod === void 0 ? void 0 : authMethod.type) === "OAUTH";
1068
- if (isOauth) {
1069
- return await handleOauthFlow(authMethod, formData, input);
1070
- }
1071
- const config = getConfig();
1072
- const data = await callActivateConnector(input, {
1073
- [TENANT_ID_HEADER_KEY]: config === null || config === void 0 ? void 0 : config.tenantId,
1074
- [CUSTOM_AUTH_HEADER_KEY]: String(config === null || config === void 0 ? void 0 : config.customAuth),
1075
- authorization: config === null || config === void 0 ? void 0 : config.authToken
1076
- });
1077
- return { data, status: "SUCCESS" };
1078
- }
1079
- catch (error) {
1080
- console.error("Error in activateConnectorCore", error);
1081
- throw error;
1082
- }
1083
- };
1084
-
1085
- // eventBus.ts
1086
- // Internal listener registry
1087
- const listeners = {
1088
- 'REFETCH_CONNECTORS': new Set(),
1089
- 'REFETCH_CONFIGURATIONS': new Set(),
1090
- 'REFRESH_CONFIGURATION_FORM': new Set(),
1091
- 'INVALIDATE_CONFIGURATION_FORM': new Set(),
1092
- 'INVALIDATE_CONFIGURATIONS': new Set(),
1093
- 'INVALIDATE_CONNECTORS': new Set(),
1094
- };
1095
- // Send a cross-context-safe event
1096
- const sendEvent = (event) => {
1097
- window.postMessage({ __eventBus: true, event }, '*');
1098
- };
1099
- // Register a callback for a specific event
1100
- const onEvent = (event, callback) => {
1101
- var _a;
1102
- (_a = listeners[event]) === null || _a === void 0 ? void 0 : _a.add(callback);
1103
- };
1104
- // Unregister a callback
1105
- const offEvent = (event, callback) => {
1106
- var _a;
1107
- (_a = listeners[event]) === null || _a === void 0 ? void 0 : _a.delete(callback);
1108
- };
1109
- // Internal postMessage listener
1110
- const handleMessage = (e) => {
1111
- const data = e.data;
1112
- if (!data || !data.__eventBus || !data.event)
1113
- return;
1114
- const callbacks = listeners[data.event];
1115
- callbacks === null || callbacks === void 0 ? void 0 : callbacks.forEach((cb) => cb());
1116
- };
1117
- // Register listener once
1118
- window.addEventListener('message', handleMessage);
1119
-
1120
- /**
1121
- * Fetches connectors and maps their actions for use in the application.
1122
- * Updates the global state store.
1123
- * @returns {Promise<Connector[]>}
1124
- */
1125
- async function getConnectors({ disabled = false, status = "ALL", refetch } = {}) {
1126
- try {
1127
- const config = getConfig();
1128
- const { data } = await getConnectors$1({
1129
- input: {
1130
- projectId: config.spaceId,
1131
- tenantId: config.tenantId,
1132
- onlyActive: !disabled,
1133
- environment: config.environment,
1134
- },
1135
- });
1136
- const connectors = data === null || data === void 0 ? void 0 : data.connectors;
1137
- const mappedConnectors = connectors.map((connector) => {
1138
- const actions = (connector.actions || [])
1139
- .filter((action) => {
1140
- // Only allow ACTIVATION, DEACTIVATION, or NONE
1141
- if (action.actionType !== "ACTIVATION" && action.actionType !== "DEACTIVATION" && action.actionType !== "NONE") {
1142
- return false;
1143
- }
1144
- if (!action.shows || action.shows === "ALWAYS") {
1145
- return true;
1146
- }
1147
- if (action.shows === "WHEN_ACTIVE" && connector.status === "ACTIVE") {
1148
- return true;
1149
- }
1150
- if (action.shows === "WHEN_INACTIVE" && connector.status === "INACTIVE") {
1151
- return true;
1152
- }
1153
- return false;
1154
- })
1155
- .map((action) => {
1156
- var _a, _b, _c, _d;
1157
- const handler = async (formData = {}) => {
1158
- var _a, _b, _c, _d;
1159
- try {
1160
- let response = null;
1161
- if ((action === null || action === void 0 ? void 0 : action.actionType) === "ACTIVATION") {
1162
- response = await activateConnector({
1163
- connectorId: connector.id,
1164
- action,
1165
- dependencyConnector: (_a = connector === null || connector === void 0 ? void 0 : connector.connectedConnectors) === null || _a === void 0 ? void 0 : _a[0],
1166
- authMethod: (_d = (_c = (_b = connector === null || connector === void 0 ? void 0 : connector.connectedConnectors) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.authMethods) === null || _d === void 0 ? void 0 : _d[0],
1167
- input: formData,
1168
- });
1169
- }
1170
- else if ((action === null || action === void 0 ? void 0 : action.actionType) === "DEACTIVATION") {
1171
- response = await deactivateConnector({
1172
- connectorId: connector.id,
1173
- action,
1174
- });
1175
- await (refetch === null || refetch === void 0 ? void 0 : refetch());
1176
- }
1177
- else {
1178
- response = await executeActionHandler(action === null || action === void 0 ? void 0 : action.handler);
1179
- }
1180
- sendEvent("REFETCH_CONFIGURATIONS");
1181
- sendEvent("REFETCH_CONNECTORS");
1182
- return response;
1183
- }
1184
- catch (e) {
1185
- return {
1186
- data: {
1187
- error: e instanceof Error ? e.message : "Unknown error",
1188
- },
1189
- status: "ERROR",
1190
- };
1191
- }
1192
- };
1193
- const form = inputContractToFormData((_d = (_c = (_b = (_a = connector === null || connector === void 0 ? void 0 : connector.connectedConnectors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.authMethods) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.inputContract);
1194
- // Construct the action object with all properties at creation
1195
- return Object.assign({ name: action.name, actionType: action.actionType, form }, (form
1196
- ? { onSubmit: async (formData) => await handler(formData) }
1197
- : { onClick: async () => await handler() }));
1198
- });
1199
- return {
1200
- id: connector.id,
1201
- name: connector.name,
1202
- description: connector.description,
1203
- imageUri: connector === null || connector === void 0 ? void 0 : connector.imageUri,
1204
- status: connector.status,
1205
- actions,
1206
- };
1207
- }).filter((connector) => {
1208
- if (status === "ALL")
1209
- return true;
1210
- if (status === "ACTIVE" && connector.status === "ACTIVE")
1211
- return true;
1212
- if (status === "INACTIVE" && connector.status === "INACTIVE")
1213
- return true;
1214
- return false;
1215
- });
1216
- return mappedConnectors;
1217
- }
1218
- catch (error) {
1219
- throw new Error(formatApolloErrors(error));
1220
- }
1221
- }
1222
-
1223
- const handleDisableConfiguration = async ({ id, connectorId, }) => {
1224
- try {
1225
- const config = getConfig();
1226
- await disableTenantConfig({
1227
- input: {
1228
- clientId: config.spaceId,
1229
- tenantId: config.tenantId,
1230
- id: id,
1231
- connectorId,
1232
- widgetConnectorId: connectorId,
1233
- },
1234
- });
1235
- sendEvent("REFETCH_CONFIGURATIONS");
1236
- }
1237
- catch (error) {
1238
- throw new Error(formatApolloErrors(error));
1239
- }
1240
- };
1241
- const handleDeleteConfiguration = async ({ id, connectorId, }) => {
1242
- try {
1243
- const config = getConfig();
1244
- await deleteTenantConfig({
1245
- input: {
1246
- clientId: config.spaceId,
1247
- tenantId: config.tenantId,
1248
- id: id,
1249
- connectorId,
1250
- widgetConnectorId: connectorId,
1251
- },
1252
- });
1253
- sendEvent("REFETCH_CONFIGURATIONS");
1254
- }
1255
- catch (error) {
1256
- throw new Error(formatApolloErrors(error));
1257
- }
1258
- };
1259
- async function getConfigurations({ configurationId, status = "ALL", }) {
1260
- try {
1261
- const config = getConfig();
1262
- const { data } = await getConfigurationSubscriptions({
1263
- input: {
1264
- clientId: config.spaceId,
1265
- tenantId: config.tenantId,
1266
- id: configurationId,
1267
- status,
1268
- }
1269
- });
1270
- const configurations = (data.getConfigurationSubscription || [])
1271
- .map((configSubscription) => {
1272
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1273
- const configureAction = (_b = (_a = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _a === void 0 ? void 0 : _a.actions) === null || _b === void 0 ? void 0 : _b.find((action) => action.actionType === "CONFIGURATION");
1274
- if (!configureAction || ((_c = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _c === void 0 ? void 0 : _c.active) === false)
1275
- return null;
1276
- const actions = [];
1277
- if ((configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.status) === "ENABLED") {
1278
- actions.push({
1279
- name: "Disable",
1280
- actionType: ConnectorActionType.DISABLE,
1281
- onClick: async () => {
1282
- await handleDisableConfiguration({ connectorId: configSubscription.connector.id, id: configurationId });
1283
- return { data: null, status: "SUCCESS" };
1284
- },
1285
- });
1286
- actions.push({
1287
- name: "Delete",
1288
- actionType: ConnectorActionType.DELETE,
1289
- onClick: async () => {
1290
- await handleDeleteConfiguration({ connectorId: configSubscription.connector.id, id: configurationId });
1291
- return { data: null, status: "SUCCESS" };
1292
- },
1293
- });
1294
- }
1295
- else {
1296
- const form = inputContractToFormData((_h = (_g = (_f = (_e = (_d = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _d === void 0 ? void 0 : _d.connectedConnectors) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.authMethods) === null || _g === void 0 ? void 0 : _g.find((authMethod) => authMethod.isDefault)) === null || _h === void 0 ? void 0 : _h.inputContract);
1297
- const handler = async (formData = {}) => {
1298
- var _a, _b, _c, _d, _e, _f, _g, _h;
1299
- if (((_a = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _a === void 0 ? void 0 : _a.status) === "ACTIVE")
1300
- return { status: "SUCCESS" };
1301
- const result = await activateConnector({
1302
- connectorId: configSubscription.connector.id,
1303
- action: (_c = (_b = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _b === void 0 ? void 0 : _b.actions) === null || _c === void 0 ? void 0 : _c.find((action) => action.actionType === ResourceAction.ACTIVATION),
1304
- dependencyConnector: (_e = (_d = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _d === void 0 ? void 0 : _d.connectedConnectors) === null || _e === void 0 ? void 0 : _e[0],
1305
- authMethod: (_h = (_g = (_f = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _f === void 0 ? void 0 : _f.connectedConnectors) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.authMethods[0],
1306
- input: formData,
1307
- });
1308
- sendEvent("REFETCH_CONFIGURATIONS");
1309
- sendEvent("REFETCH_CONNECTORS");
1310
- return result;
1311
- };
1312
- actions.push({
1313
- name: "Enable",
1314
- actionType: ConnectorActionType.ENABLE,
1315
- form,
1316
- onClick: handler,
1317
- onSubmit: handler,
1318
- });
1319
- }
1320
- return {
1321
- id: configSubscription.connector.id,
1322
- connectorId: (_j = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _j === void 0 ? void 0 : _j.id,
1323
- configurationId,
1324
- name: configSubscription.connector.name,
1325
- flowId: configureAction.handler,
1326
- description: configSubscription.connector.description,
1327
- imageUri: configSubscription.connector.imageUri,
1328
- status: configSubscription.status,
1329
- actions,
1330
- metadata: configSubscription.metaData,
1331
- };
1332
- })
1333
- .filter(Boolean);
1334
- return configurations;
1335
- }
1336
- catch (err) {
1337
- throw new Error(formatApolloErrors(err));
1338
- }
1339
- }
1340
-
1341
- function loadGapiClient() {
1342
- return new Promise((resolve, reject) => {
1343
- const script = document.createElement('script');
1344
- script.src = 'https://apis.google.com/js/api.js';
1345
- script.onload = () => resolve();
1346
- script.onerror = () => reject(new Error('Failed to load gapi'));
1347
- document.body.appendChild(script);
1348
- });
1349
- }
1350
- async function initializeGooglePicker() {
1351
- await loadGapiClient();
1352
- return new Promise((resolve) => {
1353
- // @ts-ignore
1354
- gapi.load('picker', () => {
1355
- resolve();
1356
- });
1357
- });
1358
- }
1359
- async function createGooglePicker(developerKey, accessToken) {
1360
- // Ensure Google Picker API is initialized
1361
- await initializeGooglePicker();
1362
- return new Promise((resolve, reject) => {
1363
- try {
1364
- // @ts-ignore: `google.picker` is loaded via Google APIs script
1365
- const picker = new google.picker.PickerBuilder()
1366
- // @ts-ignore
1367
- .addView(google.picker.ViewId.DOCS)
1368
- // @ts-ignore
1369
- .addView(new google.picker.DocsView(google.picker.ViewId.FOLDERS)
1370
- .setIncludeFolders(true)
1371
- .setSelectFolderEnabled(true))
1372
- // @ts-ignore
1373
- .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
1374
- .setOAuthToken(accessToken)
1375
- .setDeveloperKey(developerKey || GOOGLE_FILES_PICKER_API_KEY)
1376
- .setCallback((data) => {
1377
- if ((data === null || data === void 0 ? void 0 : data.action) === "picked") {
1378
- resolve(data === null || data === void 0 ? void 0 : data.docs);
1379
- }
1380
- })
1381
- .build();
1382
- picker.setVisible(true);
1383
- const iframe = document.querySelector("iframe.picker-dialog-frame");
1384
- const pickerDialogBg = document.querySelector(".picker-dialog-bg");
1385
- if (iframe) {
1386
- iframe.style.pointerEvents = "auto";
1387
- pickerDialogBg.style.pointerEvents = "auto";
1388
- // Step 3: Allow only iframe to be clickable
1389
- iframe.addEventListener("click", (event) => {
1390
- event.preventDefault();
1391
- event.stopPropagation();
1392
- });
1393
- pickerDialogBg.addEventListener("click", (event) => {
1394
- event.preventDefault();
1395
- event.stopPropagation();
1396
- });
1397
- }
1398
- }
1399
- catch (error) {
1400
- reject(new Error('Failed to create Google Picker'));
1401
- }
1402
- });
1403
- }
1404
-
1405
- function openGoogleFilesPicker(parentArgs) {
1406
- return async (args) => {
1407
- var _a, _b;
1408
- try {
1409
- const config = getConfig();
1410
- let accessToken = null;
1411
- let apiKey = null;
1412
- const cachedToken = localStorage.getItem(config.spaceId +
1413
- parentArgs.connectorId +
1414
- config.tenantId +
1415
- "access_token");
1416
- if (cachedToken) {
1417
- const token = safeParse(cachedToken);
1418
- if ((token === null || token === void 0 ? void 0 : token.expires_at) && token.expires_at > Date.now()) {
1419
- accessToken = token.access_token;
1420
- }
1421
- }
1422
- if (!accessToken) {
1423
- const { data } = await generateAccessToken({
1424
- input: {
1425
- orgId: config.spaceId,
1426
- tenantId: config.tenantId,
1427
- connectorId: parentArgs.connectorId,
1428
- refresh: true,
1429
- },
1430
- });
1431
- const token = data === null || data === void 0 ? void 0 : data.connectorConnection;
1432
- // cache token in local storage
1433
- localStorage.setItem(config.spaceId +
1434
- parentArgs.connectorId +
1435
- config.tenantId +
1436
- "access_token", safeStringify({
1437
- access_token: token.access_token,
1438
- api_key: (_a = token.metadata) === null || _a === void 0 ? void 0 : _a.google_picker_api_key,
1439
- expires_at: token.expires_at || Date.now() + token.expires_in * 1000,
1440
- }));
1441
- accessToken = token.access_token;
1442
- apiKey = (_b = token.metadata) === null || _b === void 0 ? void 0 : _b.google_picker_api_key;
1443
- }
1444
- const docs = await createGooglePicker(args.apiKey || apiKey, accessToken);
1445
- const files = (docs || []).map((doc) => ({
1446
- label: doc === null || doc === void 0 ? void 0 : doc.name,
1447
- value: doc === null || doc === void 0 ? void 0 : doc.id,
1448
- }));
1449
- await args.onComplete(files);
1450
- }
1451
- catch (err) {
1452
- const error = err instanceof Error ? err : new Error("Unknown error");
1453
- await args.onError(error);
1454
- }
1455
- };
1456
- }
1457
- /**
1458
- * Returns a submit handler for a configuration form.
1459
- * Handles both creation and update flows.
1460
- */
1461
- function getSubmitHandler({ configuration, configurationId, connectorId, connectorIdUiCode, configurationIdUiCode, }) {
1462
- return async ({ formData }) => {
1463
- var _a, _b, _c, _d, _e;
1464
- const config = getConfig();
1465
- const uiCodeObject = Object.assign(Object.assign({}, safeParse(configuration.uiCode)), { target: Object.assign(Object.assign({}, (_a = safeParse(configuration.uiCode)) === null || _a === void 0 ? void 0 : _a.target), { connectorId: Object.assign(Object.assign({}, (_c = (_b = safeParse(configuration.uiCode)) === null || _b === void 0 ? void 0 : _b.target) === null || _c === void 0 ? void 0 : _c.connectorId), { target: connectorIdUiCode }), id: Object.assign(Object.assign({}, (_e = (_d = safeParse(configuration.uiCode)) === null || _d === void 0 ? void 0 : _d.target) === null || _e === void 0 ? void 0 : _e.id), { target: configurationIdUiCode }) }) });
1466
- const formDataObject = Object.assign(Object.assign({}, formData), { connectorId: connectorId, id: configurationId });
1467
- const uiCode = populateFormDataInUiCode(safeStringify(uiCodeObject), formDataObject);
1468
- try {
1469
- if (configuration.status === "ENABLED") {
1470
- await updateTenantConfiguration({
1471
- input: stripTypename({
1472
- clientId: config.spaceId,
1473
- tenantId: config.tenantId,
1474
- flowId: configuration === null || configuration === void 0 ? void 0 : configuration.flowId,
1475
- stepId: configuration === null || configuration === void 0 ? void 0 : configuration.stepId,
1476
- uiCode: safeStringify(uiCode),
1477
- id: configurationId,
1478
- connectorId: connectorId,
1479
- configurations: formDataObject,
1480
- }),
1481
- });
1482
- }
1483
- else {
1484
- await createTenantConfiguration({
1485
- input: stripTypename({
1486
- clientId: config.spaceId,
1487
- tenantId: config.tenantId,
1488
- flowId: configuration === null || configuration === void 0 ? void 0 : configuration.flowId,
1489
- stepId: configuration === null || configuration === void 0 ? void 0 : configuration.stepId,
1490
- uiCode: safeStringify(uiCode),
1491
- id: configurationId,
1492
- connectorId: connectorId,
1493
- configurations: formDataObject,
1494
- }),
1495
- });
1496
- }
1497
- sendEvent("REFRESH_CONFIGURATION_FORM");
1498
- sendEvent("REFETCH_CONFIGURATIONS");
1499
- }
1500
- catch (error) {
1501
- throw new Error(formatApolloErrors(error));
1502
- }
1503
- };
1504
- }
1505
- /**
1506
- * Fetches options for select fields, supporting pagination and search.
1507
- * Extensible for custom loaders.
1508
- */
1509
- async function fetchOptions(context, pagination, resetCursor = false, query) {
1510
- var _a, _b, _c;
1511
- const config = getConfig();
1512
- try {
1513
- const { data } = await getFieldData({
1514
- input: {
1515
- id: pagination.sourceId,
1516
- clientId: config.spaceId,
1517
- // sameProjectFlow: pagination.sourceProject === "self",
1518
- input: {
1519
- data: {
1520
- input: {
1521
- data: context,
1522
- limit: pagination.limit || 10,
1523
- cursor: resetCursor ? null : pagination.cursor,
1524
- curser: resetCursor ? null : pagination.cursor,
1525
- offset: resetCursor ? 0 : pagination.offset,
1526
- query,
1527
- },
1528
- headers: { [TENANT_ID_HEADER_KEY]: config.tenantId },
1529
- },
1530
- },
1531
- },
1532
- });
1533
- const response = ((_a = data === null || data === void 0 ? void 0 : data.executeGetFieldDataFlow) === null || _a === void 0 ? void 0 : _a.data) || {};
1534
- const newOptions = response.options || [];
1535
- const limit = pagination.limit || 0;
1536
- const offset = resetCursor ? 0 : pagination.offset || 0;
1537
- const newOffset = newOptions.length > 0 ? offset + limit : offset;
1538
- const total = (_b = response.total) !== null && _b !== void 0 ? _b : pagination.total;
1539
- const cursor = response.cursor || response.curser;
1540
- const hasNextPage = Boolean(cursor || response.hasNextPage) ||
1541
- (typeof total === "number"
1542
- ? total > newOffset
1543
- : newOptions.length === limit && !pagination.cursor);
1544
- return {
1545
- options: newOptions,
1546
- pagination: Object.assign(Object.assign({}, pagination), { cursor, offset: newOffset, total,
1547
- hasNextPage, loaded: newOptions.length }),
1548
- searchable: (_c = response === null || response === void 0 ? void 0 : response.searchable) !== null && _c !== void 0 ? _c : false,
1549
- };
1550
- }
1551
- catch (error) {
1552
- throw new Error(formatApolloErrors(error));
1553
- }
1554
- }
1555
- /**
1556
- * Loads more options for a select field.
1557
- */
1558
- async function loadMoreOptions(pagination, context) {
1559
- return fetchOptions(context || {}, pagination, false);
1560
- }
1561
- /**
1562
- * Refreshes options for a select field.
1563
- */
1564
- async function refreshOptions(pagination, context) {
1565
- return fetchOptions(context || {}, pagination, true);
1566
- }
1567
- /**
1568
- * Gets options for a select field.
1569
- */
1570
- async function getOptions(pagination, context, query) {
1571
- return fetchOptions(context || {}, pagination, false, query);
1572
- }
1573
- /**
1574
- * Searches options for a select field.
1575
- */
1576
- async function searchOptions(query, pagination, context) {
1577
- return fetchOptions(context || {}, pagination, false, query);
1578
- }
1579
- /**
1580
- * Fetches and builds a configuration form for a connector.
1581
- * Integrates with state management for loading/error.
1582
- * @param input - ConfigurationFormInput
1583
- * @returns Promise<ConfigurationForm>
1584
- */
1585
- async function getConfigurationForm(input) {
1586
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1587
- try {
1588
- const config = getConfig();
1589
- const { data: configurationFormData } = await getConfigurationSubscriptionById({
1590
- input: {
1591
- clientId: config.spaceId,
1592
- tenantId: config.tenantId,
1593
- id: input.configurationId,
1594
- connectorId: input.connectorId,
1595
- widgetConnectorId: input.connectorId,
1596
- flowId: (_a = input === null || input === void 0 ? void 0 : input.configuration) === null || _a === void 0 ? void 0 : _a.flowId,
1597
- },
1598
- });
1599
- const uiCodeString = (_b = configurationFormData === null || configurationFormData === void 0 ? void 0 : configurationFormData.tenantConfigurationsById) === null || _b === void 0 ? void 0 : _b.uiCode;
1600
- const uiCode = safeParse(uiCodeString || "") || {};
1601
- // remove connectorId and id field from uiCode.target and save that in separate fields
1602
- const connectorIdUiCode = (_c = uiCode === null || uiCode === void 0 ? void 0 : uiCode.target) === null || _c === void 0 ? void 0 : _c.connectorId;
1603
- const configurationIdUiCode = (_d = uiCode === null || uiCode === void 0 ? void 0 : uiCode.target) === null || _d === void 0 ? void 0 : _d.id;
1604
- (_e = uiCode === null || uiCode === void 0 ? void 0 : uiCode.target) === null || _e === void 0 ? true : delete _e.connectorId;
1605
- (_f = uiCode === null || uiCode === void 0 ? void 0 : uiCode.target) === null || _f === void 0 ? true : delete _f.id;
1606
- const fields = uiCodeToFormFields(uiCode, {
1607
- getOptions,
1608
- loadMore: loadMoreOptions,
1609
- refresh: refreshOptions,
1610
- searchOptions,
1611
- openGoogleFilesPicker: openGoogleFilesPicker({
1612
- connectorId: input.connectorId,
1613
- }),
1614
- });
1615
- return {
1616
- name: ((_g = input === null || input === void 0 ? void 0 : input.configuration) === null || _g === void 0 ? void 0 : _g.name) || "",
1617
- description: ((_h = input === null || input === void 0 ? void 0 : input.configuration) === null || _h === void 0 ? void 0 : _h.description) || "",
1618
- imageUri: ((_j = input === null || input === void 0 ? void 0 : input.configuration) === null || _j === void 0 ? void 0 : _j.imageUri) || "",
1619
- fields: fields,
1620
- submitHandler: getSubmitHandler({
1621
- configuration: configurationFormData === null || configurationFormData === void 0 ? void 0 : configurationFormData.tenantConfigurationsById,
1622
- configurationId: input === null || input === void 0 ? void 0 : input.configurationId,
1623
- connectorId: input === null || input === void 0 ? void 0 : input.connectorId,
1624
- connectorIdUiCode: connectorIdUiCode,
1625
- configurationIdUiCode: configurationIdUiCode,
1626
- }),
1627
- };
1628
- }
1629
- catch (error) {
1630
- throw new Error(formatApolloErrors(error));
1631
- }
1632
- }
1633
-
1634
- const registerRefetchFunction = (input) => {
1635
- const { refetchFunction, refetchKey } = input;
1636
- };
1637
-
1638
- class Fastn {
1639
- constructor(config) {
1640
- setConfig(config);
1641
- }
1642
- getConnectors(input) {
1643
- return getConnectors(input);
1644
- }
1645
- getConfigurations(input) {
1646
- return getConfigurations(input);
1647
- }
1648
- getConfigurationForm(input) {
1649
- return getConfigurationForm(input);
1650
- }
1651
- registerRefetchFunction(input) {
1652
- return registerRefetchFunction(input);
1653
- }
1654
- onEvent(event, callback) {
1655
- return onEvent(event, callback);
1656
- }
1657
- offEvent(event, callback) {
1658
- return offEvent(event, callback);
1659
- }
1660
- }
1661
-
1662
8
  const FastnContext = react.createContext(null);
1663
9
  const FastnProvider = ({ children, config, queryClient, }) => {
1664
10
  const fastn = react.useMemo(() => {
1665
- return new Fastn(config);
11
+ return new core.Fastn(config);
1666
12
  }, [config]);
1667
13
  return (jsxRuntime.jsx(reactQuery.QueryClientProvider, { client: queryClient || new reactQuery.QueryClient(), children: jsxRuntime.jsx(FastnContext.Provider, { value: fastn, children: children }) }));
1668
14
  };
@@ -2425,6 +771,41 @@ function useFieldOptions(field) {
2425
771
  var _a, _b, _c, _d, _e, _f, _g;
2426
772
  const [searchQuery, setSearchQuery] = react.useState("");
2427
773
  const queryClient = reactQuery.useQueryClient();
774
+ const configs = field === null || field === void 0 ? void 0 : field.configs;
775
+ const selection = configs === null || configs === void 0 ? void 0 : configs.selection;
776
+ const getSourceOptions = async (context) => {
777
+ var _a, _b, _c;
778
+ if (!((_a = field.optionsSource) === null || _a === void 0 ? void 0 : _a.getOptions))
779
+ return null;
780
+ const data = {
781
+ sameProjectFlow: (_b = selection === null || selection === void 0 ? void 0 : selection.source) === null || _b === void 0 ? void 0 : _b.isSameProject,
782
+ sourceId: (_c = selection === null || selection === void 0 ? void 0 : selection.source) === null || _c === void 0 ? void 0 : _c.flowId,
783
+ sourceProject: "",
784
+ limit: 10,
785
+ offset: 0,
786
+ type: "OFFSET",
787
+ hasNextPage: false,
788
+ };
789
+ const res = await field.optionsSource.getOptions(data, context, searchQuery);
790
+ return res;
791
+ };
792
+ const getDestinationOptions = async (context) => {
793
+ var _a, _b, _c, _d;
794
+ console.log("selectionss", (_a = selection === null || selection === void 0 ? void 0 : selection.destination) === null || _a === void 0 ? void 0 : _a.flowId);
795
+ if (!((_b = field.optionsSource) === null || _b === void 0 ? void 0 : _b.getOptions))
796
+ return null;
797
+ const data = {
798
+ sameProjectFlow: (_c = selection === null || selection === void 0 ? void 0 : selection.destination) === null || _c === void 0 ? void 0 : _c.isSameProject,
799
+ sourceId: (_d = selection === null || selection === void 0 ? void 0 : selection.destination) === null || _d === void 0 ? void 0 : _d.flowId,
800
+ sourceProject: "",
801
+ limit: 10,
802
+ offset: 0,
803
+ type: "OFFSET",
804
+ hasNextPage: false,
805
+ };
806
+ const res = await field.optionsSource.getOptions(data, context, searchQuery);
807
+ return res;
808
+ };
2428
809
  // Generate a unique query key for this field
2429
810
  const queryKey = react.useMemo(() => {
2430
811
  return ["field-options", field.key, field.name];
@@ -2556,6 +937,9 @@ function useFieldOptions(field) {
2556
937
  field,
2557
938
  ]);
2558
939
  return {
940
+ getSourceOptions: getSourceOptions,
941
+ getDestinationOptions: getDestinationOptions,
942
+ selectionConfig: selection,
2559
943
  options: filteredOptions,
2560
944
  loading: initialQuery.isLoading || infiniteQuery.isLoading,
2561
945
  loadingMore: infiniteQuery.isFetchingNextPage,