@cayuse-test/react 1.0.3 → 1.0.5

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.
@@ -1,10 +1,28 @@
1
- import {
2
- isNonEmptyString
3
- } from "./chunk-SZMEZFAR.js";
4
1
  import {
5
2
  AUTH_DOMAIN
6
3
  } from "./chunk-MJBMK4OG.js";
7
4
 
5
+ // packages/utils/type-checks/index.ts
6
+ var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
7
+ var isString = (value) => typeof value === "string";
8
+ var isNumber = (value) => typeof value === "number";
9
+ var isBool = (value) => typeof value === "boolean";
10
+ var { isArray } = Array;
11
+ var isNonEmptyArray = (value) => Array.isArray(value) && value.length > 0;
12
+ var isNonEmptyMap = (value) => value instanceof Map && value.size > 0;
13
+ var isFunction = (value) => typeof value === "function";
14
+ var isObject = (object) => object && typeof object === "object";
15
+ var isNonEmptyObject = (object) => object && isObject(object) && Object.keys(object).length > 0;
16
+ var isObjectWithKey = (object, key) => isObject(object) && key in object;
17
+ var isMap = (value) => isObject(value) && value instanceof Map;
18
+ var isUrl = (string) => {
19
+ try {
20
+ return Boolean(new URL(string));
21
+ } catch {
22
+ return false;
23
+ }
24
+ };
25
+
8
26
  // packages/utils/auth/auth.tsx
9
27
  import React, { useState, useEffect, useContext, useCallback } from "react";
10
28
  import { jwtDecode } from "jwt-decode";
@@ -214,12 +232,181 @@ var withAuth = (Component) => {
214
232
  return (props) => /* @__PURE__ */ jsx(AuthContext.Consumer, { children: (context) => /* @__PURE__ */ jsx(Component, { ...props, context }) });
215
233
  };
216
234
 
235
+ // packages/utils/http/constants.ts
236
+ var ERROR_NOT_AUTHORIZED = "The action is not authorized. Please contact an administrator to check your permissions.";
237
+ var ERROR_INTERNAL_SERVER_ERROR = "Internal server error";
238
+ var ERROR_STATUS_CODE_400 = 400;
239
+ var ERROR_STATUS_CODE_401 = 401;
240
+ var ERROR_STATUS_CODE_403 = 403;
241
+ var ERROR_STATUS_CODE_500 = 500;
242
+ var ERROR_FORBIDDEN_FILE_EXTENSION = "FORBIDDEN_FILE_EXTENSION";
243
+ var NODE_ENV = process.env.NODE_ENV;
244
+ var APP_ENV = process.env.REACT_APP_ENVIRONMENT;
245
+ var IS_DEV = NODE_ENV === "development" || NODE_ENV === "test" || APP_ENV === "develop";
246
+ var IS_LIVE = !IS_DEV && APP_ENV === "live";
247
+ var IS_PROD_SG = !IS_DEV && APP_ENV === "prod-sg";
248
+ var PROD_ENV = IS_PROD_SG || IS_LIVE;
249
+
250
+ // packages/utils/http/index.ts
251
+ var notify = (
252
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
253
+ global.__CAYUSE__?.notify ?? (() => {
254
+ console.error(
255
+ "function is not defined. check is banner-notification package install"
256
+ );
257
+ })
258
+ );
259
+ var registerGetTokenSilently = (getTokenSilentlyFunction) => {
260
+ global.__CAYUSE__ = global.__CAYUSE__ ?? {};
261
+ if (isFunction(getTokenSilentlyFunction)) {
262
+ global.__CAYUSE__.appGetTokenSilently = getTokenSilentlyFunction;
263
+ }
264
+ };
265
+ var CayuseError = class extends Error {
266
+ name;
267
+ message;
268
+ cause;
269
+ response;
270
+ meta;
271
+ constructor(message, httpResponseObject = null) {
272
+ super(message);
273
+ this.name = "CayuseError";
274
+ this.message = message;
275
+ this.cause = httpResponseObject;
276
+ this.response = httpResponseObject;
277
+ this.meta = {
278
+ spRequestId: httpResponseObject?.headers?.get("x-sp-request-id") ?? "",
279
+ flowableDesignRequestId: httpResponseObject?.headers?.get("x-flowable-design-request-id") ?? "",
280
+ flowableEngageRequestId: httpResponseObject?.headers?.get("x-flowable-engage-request-id") ?? ""
281
+ };
282
+ }
283
+ };
284
+ function isCayuseError(error) {
285
+ return error instanceof CayuseError || error && error.name === "CayuseError" && error.message;
286
+ }
287
+ var checkErrorBody = async (error) => {
288
+ const contentType = error.headers.get("Content-Type");
289
+ if (contentType && contentType.includes("json")) {
290
+ const errorBody = await error.json().catch(() => ({})) ?? {};
291
+ if (errorBody.error === ERROR_FORBIDDEN_FILE_EXTENSION) {
292
+ notify(errorBody.message ?? "", { type: "error" });
293
+ }
294
+ if (errorBody.message) {
295
+ notify(errorBody.message, { type: "error" });
296
+ }
297
+ } else if (contentType && contentType.includes("text/plain")) {
298
+ const text = await error.text();
299
+ notify(text, { type: "error" });
300
+ } else {
301
+ notify(ERROR_NOT_AUTHORIZED, { type: "error" });
302
+ }
303
+ };
304
+ var checkResponseStatus = async (response, notifyUponError) => {
305
+ if (response.status === ERROR_STATUS_CODE_401 && notifyUponError) {
306
+ notify("", { type: "login" });
307
+ } else if ((response.status === ERROR_STATUS_CODE_403 || response.status === ERROR_STATUS_CODE_400) && notifyUponError) {
308
+ await checkErrorBody(response);
309
+ } else if (response.status === ERROR_STATUS_CODE_500) {
310
+ const err = new CayuseError(ERROR_INTERNAL_SERVER_ERROR, response);
311
+ if (notifyUponError) {
312
+ notify(ERROR_INTERNAL_SERVER_ERROR, { type: "error" });
313
+ }
314
+ throw err;
315
+ }
316
+ if (!response.ok) {
317
+ throw new CayuseError(response.statusText, response);
318
+ }
319
+ return response;
320
+ };
321
+ var fetchWithRetry = (url, options, args = {}) => {
322
+ const { numRetries, attemptNumber, notifyUponError } = {
323
+ numRetries: 2,
324
+ attemptNumber: 1,
325
+ notifyUponError: !PROD_ENV,
326
+ ...args
327
+ };
328
+ const retryTimeoutInSeconds = Math.pow(2, attemptNumber - 1);
329
+ return fetch(url, options).then((res) => checkResponseStatus(res, notifyUponError)).then((response) => {
330
+ const contentType = response.headers.get("Content-Type");
331
+ if (contentType && contentType.includes("json")) {
332
+ return response.json().catch(() => ({}));
333
+ }
334
+ return response.text();
335
+ }).catch((error) => {
336
+ if (error.message === ERROR_INTERNAL_SERVER_ERROR) {
337
+ if (numRetries === 0) {
338
+ if (notifyUponError) {
339
+ notify(error.message, { type: "error" });
340
+ }
341
+ throw error;
342
+ }
343
+ return new Promise((resolve) => {
344
+ setTimeout(
345
+ () => resolve(
346
+ fetchWithRetry(url, options, {
347
+ numRetries: numRetries - 1,
348
+ attemptNumber: attemptNumber + 1,
349
+ notifyUponError
350
+ })
351
+ ),
352
+ retryTimeoutInSeconds * 1e3
353
+ );
354
+ });
355
+ }
356
+ throw error;
357
+ });
358
+ };
359
+ var executeRequest = (url, options = {}, args = {}) => {
360
+ const doFetch = (token) => {
361
+ const allOptions = {
362
+ ...options,
363
+ headers: {
364
+ ...options.headers || {},
365
+ Authorization: `Bearer ${token}`,
366
+ "X-IDP-New-Login": "true"
367
+ }
368
+ };
369
+ if (options.method !== "GET" && !args.numRetries) {
370
+ args.numRetries = 0;
371
+ }
372
+ return fetchWithRetry(url, allOptions, args);
373
+ };
374
+ let getTokenPromise = Promise.resolve("");
375
+ if (isFunction(global.__CAYUSE__?.appGetTokenSilently)) {
376
+ const returnValue = global.__CAYUSE__.appGetTokenSilently();
377
+ getTokenPromise = returnValue instanceof Promise ? returnValue : Promise.resolve(returnValue);
378
+ }
379
+ return getTokenPromise.then((token) => doFetch(token));
380
+ };
381
+ var request = async (url, options = {}, args = {}) => {
382
+ return executeRequest(url, options, args);
383
+ };
384
+
217
385
  export {
386
+ isNonEmptyString,
387
+ isString,
388
+ isNumber,
389
+ isBool,
390
+ isArray,
391
+ isNonEmptyArray,
392
+ isNonEmptyMap,
393
+ isFunction,
394
+ isObject,
395
+ isNonEmptyObject,
396
+ isObjectWithKey,
397
+ isMap,
398
+ isUrl,
218
399
  AuthContext,
219
400
  useAuth,
220
401
  ACCESS_TOKEN,
221
402
  loginWithRedirect,
222
403
  AuthProvider,
223
- withAuth
404
+ withAuth,
405
+ registerGetTokenSilently,
406
+ CayuseError,
407
+ isCayuseError,
408
+ checkErrorBody,
409
+ executeRequest,
410
+ request
224
411
  };
225
- //# sourceMappingURL=chunk-KJUT65VD.js.map
412
+ //# sourceMappingURL=chunk-LDCYFDOO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../packages/utils/type-checks/index.ts","../packages/utils/auth/auth.tsx","../packages/utils/http/constants.ts","../packages/utils/http/index.ts"],"sourcesContent":["export const isNonEmptyString = (value: unknown): value is string =>\n\ttypeof value === 'string' && value.length > 0;\n\nexport const isString = (value: unknown): value is string =>\n\ttypeof value === 'string';\n\nexport const isNumber = (value: unknown): value is number =>\n\ttypeof value === 'number';\n\nexport const isBool = (value: unknown): value is boolean =>\n\ttypeof value === 'boolean';\n\nexport const { isArray } = Array;\n\nexport const isNonEmptyArray = (value: unknown) =>\n\tArray.isArray(value) && value.length > 0;\n\nexport const isNonEmptyMap = (value: unknown) =>\n\tvalue instanceof Map && value.size > 0;\n\nexport const isFunction = (value: unknown) => typeof value === 'function';\n\nexport const isObject = (object: object) => object && typeof object === 'object';\n\nexport const isNonEmptyObject = (object?: object) =>\n\tobject && isObject(object) && Object.keys(object).length > 0;\n\nexport const isObjectWithKey = <T extends object>(object: T, key: string) =>\n\tisObject(object) && key in object;\n\nexport const isMap = (value: object) => isObject(value) && value instanceof Map;\n\nexport const isUrl = (string: string) => {\n\ttry {\n\t\treturn Boolean(new URL(string));\n\t} catch {\n\t\treturn false;\n\t}\n};\n","import React, { useState, useEffect, useContext, useCallback } from 'react';\nimport { jwtDecode } from 'jwt-decode';\nimport { isNonEmptyString } from '@/utils/type-checks';\nimport { AUTH_DOMAIN } from '@/globals/constants';\n\ninterface User {\n\tusername: string;\n\ttenantId?: string;\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t[key: string]: any;\n}\n\ninterface AuthContextValue {\n\tisAuthenticated: boolean;\n\tloading: boolean;\n\tuser: User | null;\n\tloginWithRedirect: (params: LoginParams) => void;\n\trefreshToken: () => Promise<boolean>;\n}\n\ninterface LoginParams {\n\ttenantId?: string;\n\tisGuest?: boolean;\n}\n\ninterface CayuseHeader {\n\tproduct: string;\n\thost: string;\n\tuserId: string;\n\tauthenticationToken: string;\n}\n\ninterface AuthProviderProps {\n\tchildren: React.ReactNode;\n\tPRODUCT_KEY: string;\n\tsetCayuseHeader: (header: CayuseHeader) => void;\n\ttokenRefreshUrl?: string;\n\tisGuest?: boolean;\n}\n\nexport const AuthContext = React.createContext<AuthContextValue | undefined>(\n\tundefined,\n);\n\nexport const useAuth = () => {\n\tconst context = useContext(AuthContext);\n\tif (!context) {\n\t\tthrow new Error('useAuth must be used within an AuthProvider');\n\t}\n\treturn context;\n};\n\nconst CAYUSE_LOGOUT_URL = `https://${AUTH_DOMAIN}/logout` as const;\nconst CAYUSE_LOGIN_URL = `https://${AUTH_DOMAIN}/authorize` as const;\nexport const ACCESS_TOKEN = 'fk_accessToken' as const;\nconst ACCESS_TOKEN_EXP = 'fk_accessTokenExp' as const;\n\nexport function loginWithRedirect({ tenantId, isGuest }: LoginParams): void {\n\tconst currentUrl = window.location.href;\n\tconst encodedUri = encodeURIComponent(currentUrl);\n\tlet url = `${CAYUSE_LOGIN_URL}?redirect_uri=${encodedUri}&response_type=TOKEN`;\n\n\tif (isNonEmptyString(tenantId)) {\n\t\turl += `&tenant_id=${tenantId}`;\n\t}\n\n\tif (isGuest) {\n\t\turl += '&guest=true';\n\t}\n\n\twindow.location.replace(url);\n}\n\nexport const AuthProvider: React.FC<AuthProviderProps> = ({\n\tchildren,\n\tPRODUCT_KEY,\n\tsetCayuseHeader,\n\ttokenRefreshUrl,\n\tisGuest,\n}) => {\n\tconst [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);\n\tconst [loading, setLoading] = useState<boolean>(true);\n\tconst [user, setUser] = useState<User | null>(null);\n\tconst [accessToken, setAccessToken] = useState<string | null>(null);\n\tconst [refreshingToken, setRefreshingToken] = useState<boolean>(false);\n\n\tconst retrieveAccessTokenFromLocationHash = (): void => {\n\t\tconst { hash } = window.location;\n\n\t\tif (hash) {\n\t\t\tconst tokens = hash.substring(1, hash.length).split('&');\n\t\t\tfor (const token of tokens) {\n\t\t\t\tif (token) {\n\t\t\t\t\tconst [key, value] = token.split('=');\n\t\t\t\t\tif (key === 'access_token' && value) {\n\t\t\t\t\t\tconst newAccessToken = value;\n\t\t\t\t\t\tlocalStorage.setItem(ACCESS_TOKEN, newAccessToken);\n\t\t\t\t\t\tconst decodedToken = jwtDecode<{ exp: number }>(newAccessToken);\n\t\t\t\t\t\tlocalStorage.setItem(ACCESS_TOKEN_EXP, decodedToken.exp.toString());\n\t\t\t\t\t\tsetAccessToken(newAccessToken);\n\t\t\t\t\t\tsetIsAuthenticated(true);\n\n\t\t\t\t\t\tconst url = new URL(window.location.href);\n\t\t\t\t\t\twindow.history.replaceState(\n\t\t\t\t\t\t\t{},\n\t\t\t\t\t\t\tdocument.title,\n\t\t\t\t\t\t\turl.pathname + url.search,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\tconst isAccessTokenExpired = (): boolean => {\n\t\tconst accessTokenFromStorage = localStorage.getItem(ACCESS_TOKEN);\n\n\t\tif (!accessTokenFromStorage) {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst accessTokenExpirationFromStorage = localStorage.getItem(ACCESS_TOKEN_EXP);\n\t\tlet timeUntilTokenExpires: number;\n\n\t\tif (accessTokenExpirationFromStorage) {\n\t\t\ttimeUntilTokenExpires =\n\t\t\t\tparseInt(accessTokenExpirationFromStorage, 10) -\n\t\t\t\tMath.floor(new Date().getTime() / 1000);\n\t\t} else {\n\t\t\tconst decodedToken = jwtDecode<{ exp: number }>(accessTokenFromStorage);\n\t\t\ttimeUntilTokenExpires =\n\t\t\t\tdecodedToken.exp - Math.floor(new Date().getTime() / 1000);\n\t\t}\n\n\t\treturn timeUntilTokenExpires < 60;\n\t};\n\n\tconst refreshTokenSilently = useCallback(async (): Promise<boolean> => {\n\t\tif (refreshingToken) return false;\n\n\t\ttry {\n\t\t\tsetRefreshingToken(true);\n\n\t\t\tlet refreshUrl = isNonEmptyString(tokenRefreshUrl)\n\t\t\t\t? tokenRefreshUrl!\n\t\t\t\t: `${window.location.protocol}//${window.location.host}/api/refresh-token`;\n\n\t\t\tif (user?.tenantId) {\n\t\t\t\trefreshUrl += `?tenant_id=${user.tenantId}`;\n\t\t\t}\n\n\t\t\tif (isGuest) {\n\t\t\t\trefreshUrl += refreshUrl.includes('?') ? '&guest=true' : '?guest=true';\n\t\t\t}\n\n\t\t\tif (!refreshUrl) {\n\t\t\t\tthrow new Error('Refresh URL is undefined');\n\t\t\t}\n\n\t\t\tconst response = await fetch(refreshUrl, {\n\t\t\t\tmethod: 'GET',\n\t\t\t\tcredentials: 'include',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\tAuthorization: `Bearer ${localStorage.getItem(ACCESS_TOKEN)}`,\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error('Token refresh failed');\n\t\t\t}\n\n\t\t\tconst data: { access_token?: string } = await response.json();\n\n\t\t\tif (data.access_token) {\n\t\t\t\tlocalStorage.setItem(ACCESS_TOKEN, data.access_token);\n\t\t\t\tconst decodedToken = jwtDecode<{ exp: number }>(data.access_token);\n\t\t\t\tlocalStorage.setItem(ACCESS_TOKEN_EXP, decodedToken.exp.toString());\n\t\t\t\tsetAccessToken(data.access_token);\n\t\t\t\tsetIsAuthenticated(true);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t} catch (error) {\n\t\t\tconsole.error('Error refreshing token:', error);\n\t\t\treturn false;\n\t\t} finally {\n\t\t\tsetRefreshingToken(false);\n\t\t}\n\t}, [refreshingToken, tokenRefreshUrl, user, isGuest]);\n\n\tuseEffect(() => {\n\t\tconst initAuth = async (): Promise<void> => {\n\t\t\tif (window.location.hash.includes('access_token=')) {\n\t\t\t\tretrieveAccessTokenFromLocationHash();\n\t\t\t\tsetLoading(false);\n\t\t\t} else if (localStorage.getItem(ACCESS_TOKEN)) {\n\t\t\t\tif (isAccessTokenExpired()) {\n\t\t\t\t\tsetIsAuthenticated(false);\n\t\t\t\t\tsetLoading(false);\n\t\t\t\t} else {\n\t\t\t\t\tconst accessTokenFromStorage = localStorage.getItem(ACCESS_TOKEN)!;\n\t\t\t\t\tsetAccessToken(accessTokenFromStorage);\n\t\t\t\t\tsetIsAuthenticated(true);\n\t\t\t\t\tsetLoading(false);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsetIsAuthenticated(false);\n\t\t\t\tsetLoading(false);\n\t\t\t}\n\t\t};\n\n\t\tinitAuth();\n\t}, []);\n\n\tuseEffect(() => {\n\t\tif (accessToken) {\n\t\t\tconst token = localStorage.getItem(ACCESS_TOKEN);\n\t\t\tif (isNonEmptyString(token) && token === accessToken) {\n\t\t\t\tconst decodedUser = jwtDecode<User>(token);\n\t\t\t\tsetIsAuthenticated(true);\n\t\t\t\tsetUser(decodedUser);\n\n\t\t\t\tconst host = window.location.origin;\n\t\t\t\tsetCayuseHeader({\n\t\t\t\t\tproduct: PRODUCT_KEY,\n\t\t\t\t\thost,\n\t\t\t\t\tuserId: decodedUser.username,\n\t\t\t\t\tauthenticationToken: token,\n\t\t\t\t});\n\t\t\t} else if (user?.tenantId) {\n\t\t\t\tloginWithRedirect({ tenantId: user.tenantId, isGuest });\n\t\t\t}\n\t\t}\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [accessToken, isGuest]);\n\n\tuseEffect(() => {\n\t\tif (isAuthenticated) {\n\t\t\tconst interval = setInterval(async () => {\n\t\t\t\tif (isAccessTokenExpired()) {\n\t\t\t\t\tconst refreshed = await refreshTokenSilently();\n\t\t\t\t\tif (!refreshed) {\n\t\t\t\t\t\tsetAccessToken(null);\n\t\t\t\t\t\tlocalStorage.removeItem(ACCESS_TOKEN);\n\t\t\t\t\t\tlocalStorage.removeItem(ACCESS_TOKEN_EXP);\n\t\t\t\t\t\tsetIsAuthenticated(false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, 5_000);\n\n\t\t\treturn () => clearInterval(interval);\n\t\t}\n\t}, [isAuthenticated, refreshTokenSilently]);\n\n\tconst logout = useCallback((event: CustomEvent): void => {\n\t\tif (event.detail === '/logout') {\n\t\t\tsetAccessToken(null);\n\t\t\tlocalStorage.removeItem(ACCESS_TOKEN);\n\t\t\tlocalStorage.removeItem(ACCESS_TOKEN_EXP);\n\t\t\twindow.location.href = CAYUSE_LOGOUT_URL;\n\t\t}\n\t}, []) as EventListener;\n\n\tuseEffect(() => {\n\t\twindow.addEventListener('navigationChange', logout);\n\n\t\treturn () => window.removeEventListener('navigationChange', logout);\n\t}, [logout]);\n\n\t// Context value with proper typing\n\tconst contextValue: AuthContextValue = {\n\t\tisAuthenticated,\n\t\tloading,\n\t\tuser,\n\t\tloginWithRedirect: (params: LoginParams) =>\n\t\t\tloginWithRedirect({\n\t\t\t\t...params,\n\t\t\t\tisGuest: params.isGuest || isGuest,\n\t\t\t}),\n\t\trefreshToken: refreshTokenSilently,\n\t};\n\n\treturn (\n\t\t<AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>\n\t);\n};\n\nexport const withAuth = <P extends object>(\n\tComponent: React.ComponentType<P & { context: AuthContextValue }>,\n) => {\n\treturn (props: P) => (\n\t\t<AuthContext.Consumer>\n\t\t\t{(context) => <Component {...props} context={context!} />}\n\t\t</AuthContext.Consumer>\n\t);\n};\n","export const ERROR_NOT_AUTHORIZED =\n\t'The action is not authorized. Please contact an administrator to check your permissions.';\nexport const ERROR_INTERNAL_SERVER_ERROR = 'Internal server error';\nexport const ERROR_STATUS_CODE_400 = 400;\nexport const ERROR_STATUS_CODE_401 = 401;\nexport const ERROR_STATUS_CODE_403 = 403;\nexport const ERROR_STATUS_CODE_500 = 500;\nexport const ERROR_FORBIDDEN_FILE_EXTENSION = 'FORBIDDEN_FILE_EXTENSION';\n\nconst NODE_ENV = process.env.NODE_ENV;\nconst APP_ENV = process.env.REACT_APP_ENVIRONMENT;\n\nconst IS_DEV =\n\tNODE_ENV === 'development' || NODE_ENV === 'test' || APP_ENV === 'develop';\nconst IS_LIVE = !IS_DEV && APP_ENV === 'live';\nconst IS_PROD_SG = !IS_DEV && APP_ENV === 'prod-sg';\n\nexport const PROD_ENV = IS_PROD_SG || IS_LIVE;\n","import { isFunction } from '@/utils/type-checks';\nimport {\n\tERROR_FORBIDDEN_FILE_EXTENSION,\n\tERROR_INTERNAL_SERVER_ERROR,\n\tERROR_NOT_AUTHORIZED,\n\tERROR_STATUS_CODE_400,\n\tERROR_STATUS_CODE_401,\n\tERROR_STATUS_CODE_403,\n\tERROR_STATUS_CODE_500,\n\tPROD_ENV,\n} from './constants.js';\n\ninterface CayuseGlobal {\n\tappGetTokenSilently?: () => string | Promise<string>;\n}\n\ndeclare global {\n\tvar global: typeof globalThis & {\n\t\t__CAYUSE__: CayuseGlobal | undefined;\n\t};\n}\n\nconst notify =\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t(global as any).__CAYUSE__?.notify ??\n\t(() => {\n\t\tconsole.error(\n\t\t\t'function is not defined. check is banner-notification package install',\n\t\t);\n\t});\n\n/**\n * Apps must \"register\" a global function to get tokens in the background using registerGetTokenSilently\n */\nexport const registerGetTokenSilently = (\n\tgetTokenSilentlyFunction: () => string | Promise<string>,\n): void => {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t(global as any).__CAYUSE__ = (global as any).__CAYUSE__ ?? {};\n\n\tif (isFunction(getTokenSilentlyFunction)) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t(global as any).__CAYUSE__.appGetTokenSilently = getTokenSilentlyFunction;\n\t}\n};\n\nexport class CayuseError extends Error {\n\tname: string;\n\tmessage: string;\n\tcause: Response | null;\n\tresponse: Response | null;\n\tmeta: {\n\t\tspRequestId: string;\n\t\tflowableDesignRequestId: string;\n\t\tflowableEngageRequestId: string;\n\t};\n\n\tconstructor(message: string, httpResponseObject: Response | null = null) {\n\t\tsuper(message);\n\n\t\tthis.name = 'CayuseError';\n\t\tthis.message = message;\n\t\tthis.cause = httpResponseObject;\n\t\tthis.response = httpResponseObject;\n\t\tthis.meta = {\n\t\t\tspRequestId: httpResponseObject?.headers?.get('x-sp-request-id') ?? '',\n\t\t\tflowableDesignRequestId:\n\t\t\t\thttpResponseObject?.headers?.get('x-flowable-design-request-id') ?? '',\n\t\t\tflowableEngageRequestId:\n\t\t\t\thttpResponseObject?.headers?.get('x-flowable-engage-request-id') ?? '',\n\t\t};\n\t}\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isCayuseError(error: any): error is CayuseError {\n\treturn (\n\t\terror instanceof CayuseError ||\n\t\t(error && error.name === 'CayuseError' && error.message)\n\t);\n}\n\nexport const checkErrorBody = async (error: Response): Promise<void> => {\n\tconst contentType = error.headers.get('Content-Type');\n\n\tif (contentType && contentType.includes('json')) {\n\t\tconst errorBody: { error?: string; message?: string } =\n\t\t\t(await error.json().catch(() => ({}))) ?? {};\n\n\t\tif (errorBody.error === ERROR_FORBIDDEN_FILE_EXTENSION) {\n\t\t\tnotify(errorBody.message ?? '', { type: 'error' });\n\t\t}\n\n\t\tif (errorBody.message) {\n\t\t\tnotify(errorBody.message, { type: 'error' });\n\t\t}\n\t} else if (contentType && contentType.includes('text/plain')) {\n\t\tconst text = await error.text();\n\t\tnotify(text, { type: 'error' });\n\t} else {\n\t\tnotify(ERROR_NOT_AUTHORIZED, { type: 'error' });\n\t}\n};\n\nconst checkResponseStatus = async (\n\tresponse: Response,\n\tnotifyUponError: boolean,\n): Promise<Response> => {\n\tif (response.status === ERROR_STATUS_CODE_401 && notifyUponError) {\n\t\tnotify('', { type: 'login' });\n\t} else if (\n\t\t(response.status === ERROR_STATUS_CODE_403 ||\n\t\t\tresponse.status === ERROR_STATUS_CODE_400) &&\n\t\tnotifyUponError\n\t) {\n\t\tawait checkErrorBody(response);\n\t} else if (response.status === ERROR_STATUS_CODE_500) {\n\t\tconst err = new CayuseError(ERROR_INTERNAL_SERVER_ERROR, response);\n\n\t\tif (notifyUponError) {\n\t\t\tnotify(ERROR_INTERNAL_SERVER_ERROR, { type: 'error' });\n\t\t}\n\t\tthrow err;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow new CayuseError(response.statusText, response);\n\t}\n\n\treturn response;\n};\n\ninterface FetchArgs {\n\tnumRetries?: number;\n\tattemptNumber?: number;\n\tnotifyUponError?: boolean;\n}\n\nconst fetchWithRetry = (\n\turl: string,\n\toptions: RequestInit,\n\targs: FetchArgs = {},\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<any> => {\n\tconst { numRetries, attemptNumber, notifyUponError } = {\n\t\tnumRetries: 2,\n\t\tattemptNumber: 1,\n\t\tnotifyUponError: !PROD_ENV,\n\t\t...args,\n\t};\n\n\tconst retryTimeoutInSeconds = Math.pow(2, attemptNumber - 1);\n\n\treturn fetch(url, options)\n\t\t.then((res) => checkResponseStatus(res, notifyUponError))\n\t\t.then((response) => {\n\t\t\tconst contentType = response.headers.get('Content-Type');\n\n\t\t\tif (contentType && contentType.includes('json')) {\n\t\t\t\treturn response.json().catch(() => ({}));\n\t\t\t}\n\t\t\treturn response.text();\n\t\t})\n\t\t.catch((error: CayuseError) => {\n\t\t\tif (error.message === ERROR_INTERNAL_SERVER_ERROR) {\n\t\t\t\tif (numRetries === 0) {\n\t\t\t\t\tif (notifyUponError) {\n\t\t\t\t\t\tnotify(error.message, { type: 'error' });\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\n\t\t\t\treturn new Promise((resolve) => {\n\t\t\t\t\tsetTimeout(\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tresolve(\n\t\t\t\t\t\t\t\tfetchWithRetry(url, options, {\n\t\t\t\t\t\t\t\t\tnumRetries: numRetries - 1,\n\t\t\t\t\t\t\t\t\tattemptNumber: attemptNumber + 1,\n\t\t\t\t\t\t\t\t\tnotifyUponError,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tretryTimeoutInSeconds * 1000,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n};\n\nexport const executeRequest = (\n\turl: string,\n\toptions: RequestInit = {},\n\targs: FetchArgs = {},\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<any> => {\n\tconst doFetch = (token: string) => {\n\t\tconst allOptions: RequestInit = {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...(options.headers || {}),\n\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t'X-IDP-New-Login': 'true',\n\t\t\t},\n\t\t};\n\n\t\tif (options.method !== 'GET' && !args.numRetries) {\n\t\t\targs.numRetries = 0;\n\t\t}\n\n\t\treturn fetchWithRetry(url, allOptions, args);\n\t};\n\n\tlet getTokenPromise: Promise<string> = Promise.resolve('');\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tif (isFunction((global as any).__CAYUSE__?.appGetTokenSilently)) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\tconst returnValue = (global as any).__CAYUSE__.appGetTokenSilently();\n\n\t\tgetTokenPromise =\n\t\t\treturnValue instanceof Promise ? returnValue : Promise.resolve(returnValue);\n\t}\n\n\treturn getTokenPromise.then((token) => doFetch(token));\n};\n\nexport const request = async (url: string, options = {}, args = {}) => {\n\treturn executeRequest(url, options, args);\n};\n"],"mappings":";;;;;AAAO,IAAM,mBAAmB,CAAC,UAChC,OAAO,UAAU,YAAY,MAAM,SAAS;AAEtC,IAAM,WAAW,CAAC,UACxB,OAAO,UAAU;AAEX,IAAM,WAAW,CAAC,UACxB,OAAO,UAAU;AAEX,IAAM,SAAS,CAAC,UACtB,OAAO,UAAU;AAEX,IAAM,EAAE,QAAQ,IAAI;AAEpB,IAAM,kBAAkB,CAAC,UAC/B,MAAM,QAAQ,KAAK,KAAK,MAAM,SAAS;AAEjC,IAAM,gBAAgB,CAAC,UAC7B,iBAAiB,OAAO,MAAM,OAAO;AAE/B,IAAM,aAAa,CAAC,UAAmB,OAAO,UAAU;AAExD,IAAM,WAAW,CAAC,WAAmB,UAAU,OAAO,WAAW;AAEjE,I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AEA,aAAO,IAAI,QAAQ,CAAC,YAAY;AAC/B;AAAA,UACC,MACC;AAAA,YACC,eAAe,KAAK,SAAS;AAAA,cAC5B,YAAY,aAAa;AAAA,cACzB,eAAe,gBAAgB;AAAA,cAC/B;AAAA,YACD,CAAC;AAAA,UACF;AAAA,UACD,wBAAwB;AAAA,QACzB;AAAA,MACD,CAAC;AAAA,IACF;AACA,UAAM;AAAA,EACP,CAAC;AACH;AAEO,IAAM,iBAAiB,CAC7B,KACA,UAAuB,CAAC,GACxB,OAAkB,CAAC,MAED;AAClB,QAAM,UAAU,CAAC,UAAkB;AAClC,UAAM,aAA0B;AAAA,MAC/B,GAAG;AAAA,MACH,SAAS;AAAA,QACR,GAAI,QAAQ,WAAW,CAAC;AAAA,QACxB,eAAe,UAAU,KAAK;AAAA,QAC9B,mBAAmB;AAAA,MACpB;AAAA,IACD;AAEA,QAAI,QAAQ,WAAW,SAAS,CAAC,KAAK,YAAY;AACjD,WAAK,aAAa;AAAA,IACnB;AAEA,WAAO,eAAe,KAAK,YAAY,IAAI;AAAA,EAC5C;AAEA,MAAI,kBAAmC,QAAQ,QAAQ,EAAE;AAEzD,MAAI,WAAY,OAAe,YAAY,mBAAmB,GAAG;AAEhE,UAAM,cAAe,OAAe,WAAW,oBAAoB;AAEnE,sBACC,uBAAuB,UAAU,cAAc,QAAQ,QAAQ,WAAW;AAAA,EAC5E;AAEA,SAAO,gBAAgB,KAAK,CAAC,UAAU,QAAQ,KAAK,CAAC;AACtD;AAEO,IAAM,UAAU,OAAO,KAAa,UAAU,CAAC,GAAG,OAAO,CAAC,MAAM;AACtE,SAAO,eAAe,KAAK,SAAS,IAAI;AACzC;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isFunction
3
- } from "./chunk-SZMEZFAR.js";
3
+ } from "./chunk-LDCYFDOO.js";
4
4
 
5
5
  // packages/hooks/use-dictionary/use-dictionary.tsx
6
6
  import { useMemo } from "react";
@@ -94,4 +94,4 @@ export {
94
94
  useDebounceCallback,
95
95
  useModalState
96
96
  };
97
- //# sourceMappingURL=chunk-LFWPG3ND.js.map
97
+ //# sourceMappingURL=chunk-OYNDGU67.js.map
@@ -3,7 +3,7 @@ import {
3
3
  isNonEmptyArray,
4
4
  isNonEmptyString,
5
5
  isObject
6
- } from "./chunk-SZMEZFAR.js";
6
+ } from "./chunk-LDCYFDOO.js";
7
7
  import {
8
8
  DATETIME_FORMATS
9
9
  } from "./chunk-MJBMK4OG.js";
@@ -191,4 +191,4 @@ export {
191
191
  extractQuestionsFromSection,
192
192
  getFormElementsByIds
193
193
  };
194
- //# sourceMappingURL=chunk-WAQWICRJ.js.map
194
+ //# sourceMappingURL=chunk-QPEQWFAR.js.map
@@ -65,12 +65,11 @@ import {
65
65
  setDictionary,
66
66
  setLoginTenantId,
67
67
  useActiveColumns
68
- } from "../chunk-RYAW4XZF.js";
69
- import "../chunk-TYZPOXN5.js";
70
- import "../chunk-WAQWICRJ.js";
71
- import "../chunk-QCQVYXFA.js";
72
- import "../chunk-KJUT65VD.js";
73
- import "../chunk-SZMEZFAR.js";
68
+ } from "../chunk-JKHZBLRB.js";
69
+ import "../chunk-BVB7EXJY.js";
70
+ import "../chunk-QPEQWFAR.js";
71
+ import "../chunk-HRVK43NB.js";
72
+ import "../chunk-LDCYFDOO.js";
74
73
  import "../chunk-MJBMK4OG.js";
75
74
  import "../chunk-M2L7SQBQ.js";
76
75
  export {
@@ -2,9 +2,8 @@ import {
2
2
  TenantContext,
3
3
  TenantProvider,
4
4
  useTenantContext
5
- } from "../../chunk-QCQVYXFA.js";
6
- import "../../chunk-KJUT65VD.js";
7
- import "../../chunk-SZMEZFAR.js";
5
+ } from "../../chunk-HRVK43NB.js";
6
+ import "../../chunk-LDCYFDOO.js";
8
7
  import "../../chunk-MJBMK4OG.js";
9
8
  export {
10
9
  TenantContext,
@@ -19,7 +19,7 @@ declare const useDebounceCallback: (callback: any, delayInMs?: number) => (...ar
19
19
 
20
20
  type UppyEvent = 'file-added' | 'files-added' | 'file-removed' | 'upload' | 'progress' | 'preprocess-complete' | 'upload-progress' | 'upload-success' | 'complete' | 'error' | 'upload-error' | 'upload-retry' | 'retry-all' | 'info-visible' | 'info-hidden' | 'cancel-all' | 'restriction-failed' | 'reset-progress';
21
21
  declare const uppyEvents: UppyEvent[];
22
- interface UppyState {
22
+ interface UppyState$1 {
23
23
  plugins: {
24
24
  [key: string]: any;
25
25
  };
@@ -49,7 +49,7 @@ interface UppyState {
49
49
  [key: string]: any;
50
50
  };
51
51
  }
52
- declare const uppyInitialState: UppyState;
52
+ declare const uppyInitialState: UppyState$1;
53
53
  declare const MAX_FILE_SIZE_75_MB: number;
54
54
  interface DefaultDictionary {
55
55
  exeFileTypeRestriction: string;
@@ -57,7 +57,7 @@ interface DefaultDictionary {
57
57
  }
58
58
  declare const defaultDictionary: DefaultDictionary;
59
59
 
60
- interface UppyDefaultOptions {
60
+ interface UppyDefaultOptions$1 {
61
61
  autoProceed?: boolean;
62
62
  restrictions?: {
63
63
  maxFileSize?: number;
@@ -71,7 +71,7 @@ declare class UppyService {
71
71
  private retryCount;
72
72
  private defaultOptions;
73
73
  getInstance(id: string): Uppy | null;
74
- register(options: UppyDefaultOptions): Uppy;
74
+ register(options: UppyDefaultOptions$1): Uppy;
75
75
  destroy(id: string): void;
76
76
  onAnyEvent(id: string, eventCallback: (eventName: UppyEvent, ...args: any[]) => void): void;
77
77
  }
@@ -116,10 +116,119 @@ declare const api: {
116
116
  }>;
117
117
  };
118
118
 
119
+ interface FileObject {
120
+ uppyId: string;
121
+ id: string;
122
+ name: string;
123
+ size: number;
124
+ downloadUrl: string;
125
+ uploadedBy: string;
126
+ createdAt: string;
127
+ finalizedAt: string;
128
+ completedAt: string;
129
+ tenantId: string;
130
+ type: string;
131
+ progress: {
132
+ [key: string]: any;
133
+ };
134
+ uploadMetadataId: string;
135
+ error: string;
136
+ }
137
+ interface UppyInstance {
138
+ id: string;
139
+ emit: (eventName: string, ...args: any[]) => void;
140
+ addFiles: (files: Array<{
141
+ source: string;
142
+ name: string;
143
+ type: string;
144
+ data: File;
145
+ }>) => void;
146
+ removeFile: (fileId: string, reason?: string, event?: Event) => void;
147
+ getState: () => UppyState;
148
+ log: (message: any, ...args: any[]) => void;
149
+ }
150
+ interface UppyDefaultOptions {
151
+ autoProceed?: boolean;
152
+ restrictions?: {
153
+ maxFileSize?: number;
154
+ maxNumberOfFiles?: number;
155
+ allowedFileTypes?: string[] | null;
156
+ };
157
+ }
158
+ interface UseFileUploaderOptions {
159
+ dictionary?: {
160
+ fileUploaderHook?: {
161
+ [key: string]: string;
162
+ };
163
+ };
164
+ options?: UppyDefaultOptions;
165
+ onErrorCallback?: (error: any) => void;
166
+ }
167
+ interface UppyState {
168
+ files: {
169
+ [key: string]: {
170
+ id: string;
171
+ name: string;
172
+ size: number;
173
+ meta: {
174
+ id: string;
175
+ downloadUrl: string;
176
+ uploadedBy: string;
177
+ createdAt: string;
178
+ finalizedAt: string;
179
+ completedAt: string;
180
+ tenantId: string;
181
+ type: string;
182
+ uploadedByInfo: any;
183
+ uploadMetadataId: string;
184
+ };
185
+ progress: {
186
+ [key: string]: any;
187
+ };
188
+ error: string;
189
+ };
190
+ };
191
+ info: Array<{
192
+ type: string;
193
+ message: string;
194
+ details: string;
195
+ }>;
196
+ error: string;
197
+ }
198
+ declare const useFileUploader: (hookProps?: UseFileUploaderOptions) => {
199
+ info: {
200
+ type: string;
201
+ message: string;
202
+ details: string;
203
+ }[];
204
+ error: string;
205
+ files: {
206
+ uppyId: string;
207
+ id: string;
208
+ name: string;
209
+ size: number;
210
+ downloadUrl: string;
211
+ uploadedBy: string;
212
+ createdAt: string;
213
+ finalizedAt: string;
214
+ completedAt: string;
215
+ tenantId: string;
216
+ type: string;
217
+ uploadedByInfo: any;
218
+ progress: {
219
+ [key: string]: any;
220
+ };
221
+ uploadMetadataId: string;
222
+ error: string;
223
+ }[];
224
+ addFiles: (files: File[], onSuccessCallback?: (acceptedFiles: File[]) => void, onRejectCallback?: (invalidExtensionFiles: File[], exceedSizeFiles: File[]) => void) => void;
225
+ removeFile: (file: FileObject, reason: string, event?: Event) => void;
226
+ };
227
+
119
228
  declare const useModalState: (initialIsOpen?: boolean) => {
120
229
  openModal: () => void;
121
230
  closeModal: () => void;
122
231
  isOpen: boolean;
123
232
  };
124
233
 
125
- export { MAX_FILE_SIZE_75_MB, type UppyEvent, UppyService, api, defaultDictionary, uppyEvents, uppyInitialState, useClickOutside, useConfirmNavigation, useDebounceCallback, useDictionary, useModalState };
234
+ export { type FileObject, MAX_FILE_SIZE_75_MB, type UppyDefaultOptions, type UppyEvent, type UppyInstance, UppyService, type UppyState, type UseFileUploaderOptions, api, defaultDictionary, uppyEvents, uppyInitialState, useClickOutside, useConfirmNavigation, useDebounceCallback, useDictionary, useFileUploader, useModalState };
@@ -3,7 +3,7 @@ import {
3
3
  useDebounceCallback,
4
4
  useDictionary,
5
5
  useModalState
6
- } from "../chunk-LFWPG3ND.js";
6
+ } from "../chunk-OYNDGU67.js";
7
7
  import {
8
8
  MAX_FILE_SIZE_75_MB,
9
9
  UppyService,
@@ -11,9 +11,12 @@ import {
11
11
  defaultDictionary,
12
12
  uppyEvents,
13
13
  uppyInitialState,
14
- useClickOutside
15
- } from "../chunk-TYZPOXN5.js";
16
- import "../chunk-SZMEZFAR.js";
14
+ useClickOutside,
15
+ useFileUploader
16
+ } from "../chunk-BVB7EXJY.js";
17
+ import "../chunk-QPEQWFAR.js";
18
+ import "../chunk-LDCYFDOO.js";
19
+ import "../chunk-MJBMK4OG.js";
17
20
  export {
18
21
  MAX_FILE_SIZE_75_MB,
19
22
  UppyService,
@@ -25,6 +28,7 @@ export {
25
28
  useConfirmNavigation,
26
29
  useDebounceCallback,
27
30
  useDictionary,
31
+ useFileUploader,
28
32
  useModalState
29
33
  };
30
34
  //# sourceMappingURL=index.js.map
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { AccordionAttachmentsForm, AccordionFormWrapper, AccordionFormWrapperProps, AlertDialog, Attachment, AttachmentType, AttachmentsForm, AttachmentsFormProps, BannerNotifications, BasePadding, BreadcrumbItem, BreadcrumbProps, Breadcrumbs, Button, ButtonGroup, ButtonGroupProps, ButtonProps, CayuseCommonHeader, Checkbox, CheckboxProps, ClockIcon, Column, Combobox, ComboboxOption, ComboboxProps, ConfirmationModal, ConfirmationModalProps, CovertButton, CustomDropdown, CustomDropdownProps, DateSelector, Divider, DropdownMenu, DropdownMenuProps, DynamicTable, DynamicTableColumn, DynamicTableProps, DynamicTableRow, FileData, FileUpload, FileUploadProps, FormNoteAttachmentsView, FormNoteAttachmentsViewProps, FormattedDate, FormattedDateProps, FormattedDatetime, FormattedDatetimeProps, FormattedRichText, FormattedRichTextProps, FormattedValue, FormattedValueProps, Icon, IconButton, IconButtonProps, IconProps, Input, InputProps, LinkToMilestone, LoadingIndicator, MilestoneForm, MilestoneProgress, MilestoneProgressView, ModalDialog, MultiFileUpload, MultiFileUploadProps, NavLink, Note, NoteWithAttachments, Number, NumberProps, OnSortChange, Option, PaddedCell, Pagination, Pendo, Popup, PopupProps, PreventLeaveDialog, Radio, RadioGroup, RadioGroupProps, RadioProps, RenderCellCallback, RichText, RichTextProps, Row, RowSelectionChangeArgs, SectionHeader, SectionHeaderProps, SetView, SetViewProps, SortDirection, SubHeader, Submenu, Tabs, TaskForm, TaskFormHeader, TaskTitleCell, TaskWithVariables, TextArea, TextAreaProps, Toggle, UploadResource, UseUploadServiceReturn, UserSelect, UserSelectProps, adminLoadOptions, baseClearIcon, dateToTimezoneDate, findFirstActiveAttachmentType, linkTasksToMilestone, notify, setDictionary, setLoginTenantId, useActiveColumns } from './components/index.js';
2
2
  export { Affiliation, ExternalAffiliation, Group, ITenantContext, Person, Tenant, TenantContext, TenantContextData, TenantProduct, TenantProvider, User, useTenantContext } from './context/tenant/index.js';
3
3
  export { APP_ENV, AUTH_DOMAIN, CAYUSE_TYPES, COLUMN_HEADER_KEYS, DATETIME_FORMATS, DateTimeFormat, FIELD_TYPES, FLOWABLE_BASE_URL, KEY_CODES, NEW_RULE_ID, NODE_ENV, RULE_TYPES, SELECT_ANY_KEY, TARGET_WEB_COMPONENTS_BUCKET } from './globals/constants/index.js';
4
- export { MAX_FILE_SIZE_75_MB, UppyEvent, UppyService, api, defaultDictionary, uppyEvents, uppyInitialState, useClickOutside, useConfirmNavigation, useDebounceCallback, useDictionary, useModalState } from './hooks/index.js';
4
+ export { FileObject, MAX_FILE_SIZE_75_MB, UppyDefaultOptions, UppyEvent, UppyInstance, UppyService, UppyState, UseFileUploaderOptions, api, defaultDictionary, uppyEvents, uppyInitialState, useClickOutside, useConfirmNavigation, useDebounceCallback, useDictionary, useFileUploader, useModalState } from './hooks/index.js';
5
5
  export { IUploadService, ProgressState, UploadError, UploadMetadataResource, UploadService, UploadServiceProps, createUploadService } from './services/upload-s3/index.js';
6
6
  export { ACCESS_TOKEN, AuthContext, AuthProvider, CayuseError, alphaSortCollectionByKey, capitalizeAndJoin, checkErrorBody, crunchClasses, debounce, encodeSearchTerms, executeRequest, extractQuestionsFromSection, flushStorage, generateId, getDatetimeFormat, getElementAncestorComponent, getFormElementsByIds, getStoredItem, injectScript, isArray, isBool, isCayuseError, isFunction, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptyString, isNumber, isObject, isObjectWithKey, isString, isUrl, loginWithRedirect, registerGetTokenSilently, removeDOMNode, request, simulateInputBlur, simulateInputChange, sortCollectionByKey, storeItem, trim, useAuth, withAuth } from './utils/index.js';
7
7
  import 'react';
package/dist/index.js CHANGED
@@ -65,13 +65,13 @@ import {
65
65
  setDictionary,
66
66
  setLoginTenantId,
67
67
  useActiveColumns
68
- } from "./chunk-RYAW4XZF.js";
68
+ } from "./chunk-JKHZBLRB.js";
69
69
  import {
70
70
  useConfirmNavigation,
71
71
  useDebounceCallback,
72
72
  useDictionary,
73
73
  useModalState
74
- } from "./chunk-LFWPG3ND.js";
74
+ } from "./chunk-OYNDGU67.js";
75
75
  import {
76
76
  MAX_FILE_SIZE_75_MB,
77
77
  UppyService,
@@ -79,8 +79,9 @@ import {
79
79
  defaultDictionary,
80
80
  uppyEvents,
81
81
  uppyInitialState,
82
- useClickOutside
83
- } from "./chunk-TYZPOXN5.js";
82
+ useClickOutside,
83
+ useFileUploader
84
+ } from "./chunk-BVB7EXJY.js";
84
85
  import {
85
86
  alphaSortCollectionByKey,
86
87
  capitalizeAndJoin,
@@ -101,21 +102,16 @@ import {
101
102
  sortCollectionByKey,
102
103
  storeItem,
103
104
  trim
104
- } from "./chunk-WAQWICRJ.js";
105
+ } from "./chunk-QPEQWFAR.js";
105
106
  import {
106
107
  TenantContext,
107
108
  TenantProvider,
108
109
  useTenantContext
109
- } from "./chunk-QCQVYXFA.js";
110
+ } from "./chunk-HRVK43NB.js";
110
111
  import {
111
112
  ACCESS_TOKEN,
112
113
  AuthContext,
113
114
  AuthProvider,
114
- loginWithRedirect,
115
- useAuth,
116
- withAuth
117
- } from "./chunk-KJUT65VD.js";
118
- import {
119
115
  CayuseError,
120
116
  checkErrorBody,
121
117
  executeRequest,
@@ -133,9 +129,12 @@ import {
133
129
  isObjectWithKey,
134
130
  isString,
135
131
  isUrl,
132
+ loginWithRedirect,
136
133
  registerGetTokenSilently,
137
- request
138
- } from "./chunk-SZMEZFAR.js";
134
+ request,
135
+ useAuth,
136
+ withAuth
137
+ } from "./chunk-LDCYFDOO.js";
139
138
  import {
140
139
  APP_ENV,
141
140
  AUTH_DOMAIN,
@@ -295,6 +294,7 @@ export {
295
294
  useConfirmNavigation,
296
295
  useDebounceCallback,
297
296
  useDictionary,
297
+ useFileUploader,
298
298
  useModalState,
299
299
  useTenantContext,
300
300
  withAuth
@@ -18,16 +18,11 @@ import {
18
18
  sortCollectionByKey,
19
19
  storeItem,
20
20
  trim
21
- } from "../chunk-WAQWICRJ.js";
21
+ } from "../chunk-QPEQWFAR.js";
22
22
  import {
23
23
  ACCESS_TOKEN,
24
24
  AuthContext,
25
25
  AuthProvider,
26
- loginWithRedirect,
27
- useAuth,
28
- withAuth
29
- } from "../chunk-KJUT65VD.js";
30
- import {
31
26
  CayuseError,
32
27
  checkErrorBody,
33
28
  executeRequest,
@@ -45,9 +40,12 @@ import {
45
40
  isObjectWithKey,
46
41
  isString,
47
42
  isUrl,
43
+ loginWithRedirect,
48
44
  registerGetTokenSilently,
49
- request
50
- } from "../chunk-SZMEZFAR.js";
45
+ request,
46
+ useAuth,
47
+ withAuth
48
+ } from "../chunk-LDCYFDOO.js";
51
49
  import "../chunk-MJBMK4OG.js";
52
50
  export {
53
51
  ACCESS_TOKEN,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cayuse-test/react",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",