@dev-fastn-ai/react-core 2.3.5 → 2.3.7

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