@monorise/react 8.3.2 → 8.4.0

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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../actions/app.action.ts","../actions/auth.action.ts","../actions/config.action.ts","../actions/core.action.ts","../lib/entity.ts","../lib/utils.ts","../helpers/transactional.ts","../actions/websocket.action.ts","../lib/api.ts","../services/auth.service.ts","../services/core.service.ts","../services/filestore.service.ts","../store/monorise.store.ts","../index.ts"],"sourcesContent":["import { produce } from 'immer';\nimport { useEffect, useState } from 'react';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type { ApplicationRequestError, ModalProps } from '../types/api.type';\n\ntype StartLoadingPayload<T> = {\n requestKey: string;\n isInterruptive?: boolean;\n message?: string | boolean;\n // Omit when this key is one of several sharing a single real HTTP call\n // (e.g. executeTransaction driving a loading signal per operation) — passing\n // it registers `requestKey` in `ongoingRequests`, which lib/api.ts's\n // `makeRequest` uses to hand back an in-flight promise to ANY other caller\n // using that same key, even one making a structurally different request.\n // The entry lasts only while `request` is in flight: once it settles, the\n // next call with the key (a retry after a failure, say) is sent afresh.\n request?: Promise<T>;\n};\n\ntype EndLoadingPayload = {\n requestKey: string;\n isInterruptive?: boolean;\n /**\n * @deprecated No longer needed: endLoading no longer touches\n * `ongoingRequests`; startLoading drops a request from it when the request\n * settles.\n */\n skipDedupe?: boolean;\n};\n\ntype SetErrorPayload = {\n requestKey: string;\n error: ApplicationRequestError;\n};\n\ntype Options = {\n modals?: Record<string, React.ComponentType<unknown>>;\n};\n\nconst initAppActions = (store: MonoriseStore) => {\n let options: Options = {};\n\n const { modals = {} } = options;\n type AppModalProps = ModalProps<typeof modals>;\n\n const startLoading = <T>({\n requestKey,\n isInterruptive,\n message,\n request,\n }: StartLoadingPayload<T>) => {\n store.setState(\n produce((state) => {\n const stackType = isInterruptive ? 'intLoadStack' : 'loadStack';\n const requestKeyCount = state.app[stackType].get(requestKey);\n\n state.app.loadingMessage =\n typeof message === 'string' ? message : 'Loading';\n if (request) {\n state.app.ongoingRequests.set(requestKey, request);\n }\n state.app[stackType].set(\n requestKey,\n requestKeyCount ? requestKeyCount + 1 : 1,\n );\n }),\n undefined,\n `mr/start-loading/${requestKey}`,\n );\n\n if (request) {\n // Share the request only while it's in flight. Checked by identity, so\n // a newer request under the same key is never the one removed.\n const forget = () => {\n if (store.getState().app.ongoingRequests.get(requestKey) !== request) {\n return;\n }\n store.setState(\n produce((state) => {\n state.app.ongoingRequests.delete(requestKey);\n }),\n undefined,\n `mr/settle-request/${requestKey}`,\n );\n };\n request.then(forget, forget);\n }\n };\n\n const endLoading = ({ requestKey, isInterruptive }: EndLoadingPayload) => {\n // The loading signal lingers briefly so it doesn't flicker. Request\n // dedupe isn't touched here: by now a retry may already be in flight\n // under the same key.\n setTimeout(() => {\n store.setState(\n produce((state) => {\n const stackType = isInterruptive ? 'intLoadStack' : 'loadStack';\n const requestKeyCount = state.app[stackType].get(requestKey);\n\n if (typeof requestKeyCount === 'number' && requestKeyCount > 1) {\n state.app[stackType].set(requestKey, requestKeyCount - 1);\n } else {\n state.app[stackType].delete(requestKey);\n }\n }),\n undefined,\n `mr/end-loading/${requestKey}`,\n );\n }, 500);\n };\n\n const checkIsLoading = (requestKey?: string) => {\n const { intLoadStack, loadStack } = store.getState().app;\n if (!requestKey) {\n return intLoadStack.size > 0 || loadStack.size > 0;\n }\n\n const activeIntLoadingCount = intLoadStack.get(requestKey);\n const isIntLoading =\n typeof activeIntLoadingCount === 'number' && activeIntLoadingCount > 0;\n\n const activeLoadingCount = loadStack.get(requestKey);\n const isLoading =\n typeof activeLoadingCount === 'number' && activeLoadingCount > 0;\n\n return isIntLoading || isLoading;\n };\n\n const setError = ({ requestKey, error }: SetErrorPayload) =>\n store.setState(\n produce((state) => {\n state.app.errorStack.set(requestKey, error);\n }),\n undefined,\n `mr/set-error/${requestKey}`,\n );\n\n const getError = (requestKey: string) => {\n const { errorStack } = store.getState().app;\n return errorStack.get(requestKey);\n };\n\n const clearError = (requestKey: string) => {\n const { errorStack } = store.getState().app;\n\n if (errorStack.has(requestKey)) {\n store.setState(\n produce((state) => {\n state.app.errorStack.delete(requestKey);\n }),\n undefined,\n `mr/clear-error/${requestKey}`,\n );\n }\n };\n\n const openModal = (modal: {\n name: keyof AppModalProps;\n context?: AppModalProps[keyof AppModalProps];\n }) =>\n store.setState(\n produce((state) => {\n state.app.modal = modal;\n }),\n undefined,\n `mr/open-modal/${modal.name}`,\n );\n\n const closeModal = () =>\n store.setState(\n produce((state) => {\n state.app.modal = { name: null };\n }),\n undefined,\n 'mr/close-modal',\n );\n\n const useLoadStore = (requestKey?: string) => {\n const { loadStack, intLoadStack } = store((state) => ({\n loadStack: state.app.loadStack,\n intLoadStack: state.app.intLoadStack,\n }));\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n if (loadStack && intLoadStack && requestKey) {\n setIsLoading(checkIsLoading(requestKey));\n }\n }, [loadStack, intLoadStack, requestKey]);\n\n return isLoading;\n };\n\n const useInterruptiveLoadStore = () => {\n const { intLoadStack, loadingMessage } = store((state) => ({\n intLoadStack: state.app.intLoadStack,\n loadingMessage: state.app.loadingMessage,\n }));\n\n return {\n isLoading: intLoadStack.size > 0,\n message: loadingMessage,\n };\n };\n\n const useErrorStore = (requestKey: string) => {\n const error = store((state) => state.app.errorStack.get(requestKey));\n\n useEffect(() => {\n if (error) {\n return () => {\n clearError(requestKey);\n };\n }\n }, [error, requestKey]);\n\n return error;\n };\n\n const useModalStore = () => {\n return store((state) => state.app.modal);\n };\n\n const setOptions = (opts: Options) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return {\n startLoading,\n endLoading,\n setError,\n getError,\n clearError,\n openModal,\n closeModal,\n checkIsLoading,\n useLoadStore,\n useInterruptiveLoadStore,\n useErrorStore,\n useModalStore,\n setOptions,\n };\n};\n\nexport { initAppActions };\n\nexport type AppActions = ReturnType<typeof initAppActions>;\n","import type { Entity } from '@monorise/base';\nimport { produce } from 'immer';\nimport type { AuthService } from '../services/auth.service';\nimport type { MonoriseStore } from '../store/monorise.store';\n\nconst initAuthActions = (store: MonoriseStore, authService: AuthService) => {\n const requestLogin = async (\n entityType: Entity,\n payload: { email: string },\n ) => {\n const { data } = await authService.requestLoginMagicLink(\n entityType,\n payload,\n );\n\n return data;\n };\n\n const useProfile = <T extends Record<string, unknown>>(): T & {\n displayName: string;\n email: string;\n accountId: string;\n impersonatorId?: string;\n } => {\n const profile = store((state) => state.auth.profile);\n\n return profile as T & typeof profile;\n };\n\n const getProfile = async () => {\n try {\n const {\n data: { displayName, email, accountId, ...rest },\n } = await authService.getSessionProfile();\n\n store.setState(\n produce((state) => {\n state.auth.profile = { displayName, email, accountId, ...rest };\n state.auth.isUnauthorized = false;\n state.auth.isLoading = false;\n }),\n undefined,\n 'mr/auth/get-profile',\n );\n } catch {\n store.setState(\n produce((state) => {\n state.auth.profile = {};\n state.auth.isUnauthorized = true;\n state.auth.isLoading = false;\n }),\n undefined,\n 'mr/auth/get-profile',\n );\n }\n };\n\n const useIsUnauthorized = () => {\n const { isUnauthorized, profile, isLoading } = store((state) => state.auth);\n\n return { isUnauthorized: isUnauthorized && !profile.accountId, isLoading };\n };\n\n const setIsUnauthorized = (isUnauthorized: boolean) =>\n store.setState(\n produce((state) => {\n state.auth.isUnauthorized = isUnauthorized;\n }),\n );\n\n const logout = () => {\n authService.logout();\n store.setState(\n produce((state) => {\n state.auth.isUnauthorized = true;\n state.auth.profile = {};\n }),\n );\n };\n\n return {\n requestLogin,\n useProfile,\n getProfile,\n useIsUnauthorized,\n setIsUnauthorized,\n logout,\n };\n};\n\nexport { initAuthActions };\n\nexport type AuthActions = ReturnType<typeof initAuthActions>;\n","import type {\n CreatedEntity,\n Entity,\n MonoriseEntityConfig,\n} from '@monorise/base';\nimport { produce } from 'immer';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type { CommonStore } from '../types/monorise.type';\n\nconst initConfigActions = (store: MonoriseStore) => {\n const setConfig = (config: Record<Entity, MonoriseEntityConfig>) => {\n const entityMaps = Object.keys(config).reduce(\n (acc, entity) => {\n acc[entity as any] = {\n dataMap: new Map<string, CreatedEntity<Entity>>(),\n isFirstFetched: false,\n lastKey: '',\n } as CommonStore<CreatedEntity<Entity>>;\n return acc;\n },\n {} as Record<Entity, CommonStore<CreatedEntity<Entity>>>,\n );\n\n store.setState(\n produce((state) => {\n state.config = config;\n state.entity = entityMaps;\n }),\n );\n };\n\n const getConfig = () => {\n return store.getState().config;\n };\n\n const useConfig = () => {\n const config = store((state) => state.config);\n\n return config;\n };\n\n return {\n setConfig,\n getConfig,\n useConfig,\n };\n};\n\nexport { initConfigActions };\n\nexport type ConfigActions = ReturnType<typeof initConfigActions>;\n","import type {\n CreatedEntity,\n DraftEntity,\n Entity,\n EntitySchemaMap,\n} from '@monorise/base';\nimport { produce } from 'immer';\nimport { useEffect, useState } from 'react';\nimport {\n byEntityId,\n constructLocal,\n constructMutual,\n flipMutual,\n} from '../lib/entity';\nimport {\n convertToMap,\n getEntityRequestKey,\n getMutualRequestKey,\n getMutualStateKey,\n getTagRequestKey,\n getTagStateKey,\n getUniqueFieldRequestKey,\n getUniqueFieldStateKey,\n parseMutualStateKey,\n} from '../lib/utils';\nimport type {\n CommonOptions,\n CoreService,\n ListEntitiesByTagParams,\n} from '../services/core.service';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type { ApplicationRequestError } from '../types/api.type';\nimport type { CommonStore } from '../types/monorise.type';\nimport type { Mutual, MutualData } from '../types/mutual.type';\nimport type { AppActions } from './app.action';\nimport {\n createTransactionCallRequestKey,\n getTransactionOperationRequestKey,\n type TransactionCreateEntity,\n type TransactionOperation,\n} from '../helpers/transactional';\n\n// ===== Important tips ======\n// Should we use store.getState() or store()?\n// USE store.getState() WHEN using within an action such as getEntity, getProfile\n// USE store() WHEN using within a react hook so that it gets the benefit of reactivity, such as useProfile, useEntity\n\nconst defaultOnError = (error: ApplicationRequestError | Error) => {\n if (!(error instanceof Error) && error.status >= 500) {\n // we only want server error to be captured by error tracking service\n throw error;\n }\n};\n\nconst initCoreActions = (\n monoriseStore: MonoriseStore,\n appActions: AppActions,\n coreService: CoreService,\n) => {\n const { makeEntityService, makeMutualService } = coreService;\n const {\n checkIsLoading,\n getError,\n useLoadStore,\n useErrorStore,\n startLoading,\n endLoading,\n setError,\n clearError,\n } = appActions;\n\n const listEntities = async <T extends Entity>(\n entityType: T,\n params: {\n skRange?: { start: string; end: string };\n all?: boolean;\n limit?: number;\n } = { limit: 20 },\n opts: CommonOptions = {},\n ) => {\n const store = monoriseStore.getState();\n const entityState = store.entity[entityType] ?? {};\n const { isFirstFetched } = entityState;\n const entityService = makeEntityService(entityType);\n const { skRange } = params;\n const requestKey = getEntityRequestKey('list', entityType);\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const onError = opts.onError ?? defaultOnError;\n\n if (error) {\n onError(error);\n return;\n }\n\n if (\n !opts.forceFetch &&\n ((isFirstFetched && !params.skRange) || isLoading)\n ) {\n return;\n }\n\n try {\n const { data: result } = await entityService.listEntities(\n {\n ...(params?.all ? {} : { limit: params?.limit }),\n start: skRange?.start,\n end: skRange?.end,\n },\n opts,\n );\n const newEntityMap = convertToMap<CreatedEntity<T>>(\n result.data,\n 'entityId',\n );\n\n const mergedMap = new Map([\n ...newEntityMap,\n ...store.entity[entityType].dataMap,\n ]);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType] = {\n dataMap: params.skRange ? newEntityMap : mergedMap,\n isFirstFetched: true,\n lastKey: result.lastKey,\n };\n }),\n undefined,\n `mr/entity/list/${entityType}`,\n );\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n const listMoreEntities = async <T extends Entity>(\n entityType: T,\n opts: CommonOptions = {},\n ) => {\n const requestKey = getEntityRequestKey('list', entityType);\n const store = monoriseStore.getState();\n const entityState = store.entity[entityType];\n const { dataMap, lastKey } = entityState;\n const entityService = makeEntityService(entityType);\n const error = getError(requestKey);\n const onError = opts.onError ?? defaultOnError;\n\n if (!lastKey) {\n return;\n }\n\n if (error) {\n onError(error);\n return;\n }\n\n try {\n const { data: result } = await entityService.listEntities(\n {\n limit: opts.limit ?? 20,\n lastKey,\n },\n opts,\n );\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].isFirstFetched = true;\n state.entity[entityType].lastKey = result.lastKey;\n for (const i in result.data) {\n state.entity[entityType].dataMap.set(\n result.data[i].entityId,\n result.data[i],\n );\n }\n }),\n undefined,\n `mr/entity/list-more/${entityType}`,\n );\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n const searchEntities = async <T extends Entity>(\n entityType: T,\n query: string,\n opts: CommonOptions = {},\n ) => {\n const requestKey = getEntityRequestKey('search', entityType);\n const entityService = makeEntityService(entityType);\n const error = getError(requestKey);\n const onError = opts.onError ?? defaultOnError;\n\n if (error) {\n onError(error);\n return;\n }\n\n try {\n const { data: result } = await entityService.searchEntities(query, opts);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].searchResults = result.data;\n for (const i in result.data) {\n state.entity[entityType].dataMap.set(\n result.data[i].entityId,\n result.data[i],\n );\n }\n }),\n );\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n const listEntitiesByTag = async <T extends Entity>(\n entityType: T,\n tagName: string,\n opts: CommonOptions & { params?: ListEntitiesByTagParams } = {},\n ) => {\n const tagKey = getTagStateKey(entityType, tagName, opts.params);\n\n const state = monoriseStore.getState();\n const tagState = state.tag[tagKey] || {};\n const { isFirstFetched, dataMap } = tagState;\n const entityService = makeEntityService(entityType);\n const { forceFetch } = opts;\n const requestKey = getTagRequestKey(\n 'list',\n entityType,\n tagName,\n opts.params,\n );\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const onError = opts.onError ?? defaultOnError;\n\n if (!forceFetch) {\n if (error) {\n onError(error);\n return { error };\n }\n\n if (isFirstFetched || isLoading) {\n return {\n data: {\n entities: Array.from(dataMap?.values() || []),\n lastKey: null,\n },\n };\n }\n }\n\n try {\n const { data } = await entityService.listEntitiesByTag(tagName, {\n ...opts,\n requestKey,\n });\n const { entities, lastKey } = data;\n\n monoriseStore.setState(\n produce((state) => {\n for (const entity of entities) {\n state.entity[entityType].dataMap.set(entity.entityId, entity);\n }\n }),\n );\n\n monoriseStore.setState(\n produce((state) => {\n // Initialize tag state if it doesn't exist\n if (!state.tag[tagKey]) {\n state.tag[tagKey] = {\n dataMap: new Map(),\n isFirstFetched: false,\n };\n }\n\n // Merge new entities into existing dataMap instead of replacing\n for (const entity of entities) {\n state.tag[tagKey].dataMap.set(entity.entityId, entity);\n }\n\n state.tag[tagKey].isFirstFetched = true;\n state.tag[tagKey].lastKey = lastKey;\n }),\n );\n\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n const getEntity = async <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ): Promise<{\n data?: CreatedEntity<T>;\n error?: ApplicationRequestError | (Error & { originalError?: unknown });\n }> => {\n const store = monoriseStore.getState();\n const entityState = store.entity[entityType];\n const { dataMap } = entityState;\n const entityService = makeEntityService(entityType);\n let entity = dataMap.get(id);\n const requestKey = getEntityRequestKey('get', entityType, id);\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const { forceFetch } = opts;\n const onError = opts.onError ?? defaultOnError;\n\n if (!forceFetch) {\n if (error) {\n // If there's an existing error, handle it and return the error.\n onError?.(error);\n return { error };\n }\n\n if (entity) {\n // If entity already exists and no force fetch, return it.\n return { data: entity };\n }\n\n if (isLoading) {\n // If already loading, return undefined data and error to indicate ongoing operation.\n return {};\n }\n }\n\n try {\n ({ data: entity } = await entityService.getEntity(id, opts));\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(entity?.entityId, entity);\n }),\n undefined,\n `mr/entity/get/${entityType}/${id}`,\n );\n\n return { data: entity };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n const getEntityByUniqueField = async <T extends Entity>(\n entityType: T,\n fieldName: string,\n value: string,\n opts: CommonOptions = {},\n ) => {\n const store = monoriseStore.getState();\n const entityState = store.entity[entityType];\n const { dataMap } = entityState;\n const entityService = makeEntityService(entityType);\n const stateKey = getUniqueFieldStateKey(fieldName, value);\n let entity = dataMap.get(stateKey);\n const requestKey = getUniqueFieldRequestKey(entityType, fieldName, value);\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const { forceFetch } = opts;\n const onError = opts.onError ?? defaultOnError;\n\n if (!forceFetch) {\n if (error) {\n onError?.(error);\n return { error };\n }\n\n if (entity) {\n return { data: entity };\n }\n\n if (isLoading) {\n return {};\n }\n }\n\n try {\n ({ data: entity } = await entityService.getEntityByUniqueField(\n fieldName,\n value,\n opts,\n ));\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(entity?.entityId, entity);\n state.entity[entityType].dataMap.set(`${stateKey}`, entity);\n }),\n undefined,\n `mr/entity/unique/${entityType}/${stateKey}`,\n );\n\n return { data: entity };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n // Populate already-loaded mutual-list caches for a freshly created entity —\n // e.g. so a `refund-line-item` created via `createEntity` or `executeTransaction`\n // immediately appears in an already-fetched\n // `useMutuals(Entity.REFUND, Entity.REFUND_LINE_ITEM, ...)` list, instead of\n // only showing up after that list's next refetch. `payload` is the raw\n // create payload (mutualFields' ids live there, not necessarily on the\n // server's returned `data.data`).\n const populateMutualsForCreatedEntity = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n state: any,\n entityType: Entity,\n data: CreatedEntity<Entity>,\n payload: Record<string, any>,\n ) => {\n const mutualFields = state.config[entityType]?.mutual?.mutualFields;\n if (!mutualFields) return;\n\n for (const [field, fieldConfig] of Object.entries(mutualFields)) {\n const byEntityType = (fieldConfig as any).entityType;\n const ids = payload[field];\n if (!Array.isArray(ids)) continue;\n\n for (const byEntityId of ids) {\n const mutualKey = getMutualStateKey(byEntityType, byEntityId, entityType);\n if (state.mutual[mutualKey] && state.mutual[mutualKey].isFirstFetched) {\n state.mutual[mutualKey].dataMap.set(data.entityId, {\n entityId: data.entityId,\n entityType,\n byEntityId,\n byEntityType,\n mutualId: '',\n data: data.data,\n mutualData: {},\n createdAt: data.createdAt,\n updatedAt: data.updatedAt,\n mutualUpdatedAt: data.updatedAt,\n });\n }\n }\n }\n };\n\n const createEntity = async <T extends Entity>(\n entityType: T,\n entity: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => {\n const entityService = makeEntityService(entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data } = await entityService.createEntity(entity, opts);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(data.entityId, data);\n\n // auto-populate tag store based on entity config\n const tagConfigs = state.config[entityType]?.tags;\n if (tagConfigs) {\n for (const tagConfig of tagConfigs) {\n const { name, processor } = tagConfig;\n const processorResults = processor(\n data as CreatedEntity<Entity>,\n );\n\n for (const tagKey of Object.keys(state.tag)) {\n const [tagEntityType, tagName, ...paramParts] =\n tagKey.split('/');\n\n if (\n (tagEntityType as unknown as Entity) !== entityType ||\n tagName !== name\n ) {\n continue;\n }\n\n if (!state.tag[tagKey]?.isFirstFetched) {\n continue;\n }\n\n // parse params from key\n const keyParams: Record<string, string> = {};\n for (const part of paramParts) {\n const colonIdx = part.indexOf(':');\n if (colonIdx > 0) {\n keyParams[part.substring(0, colonIdx)] =\n part.substring(colonIdx + 1);\n }\n }\n\n // skip query-filtered stores (can't match client-side)\n if (keyParams.query) {\n continue;\n }\n\n // check if any processor result matches this tag store's params\n const matches = processorResults.some((result) => {\n if (keyParams.group && result.group !== keyParams.group) {\n return false;\n }\n if (\n keyParams.start &&\n (!result.sortValue || result.sortValue < keyParams.start)\n ) {\n return false;\n }\n if (\n keyParams.end &&\n (!result.sortValue || result.sortValue > keyParams.end)\n ) {\n return false;\n }\n return true;\n });\n\n if (matches) {\n state.tag[tagKey].dataMap.set(data.entityId, data);\n }\n }\n }\n }\n\n // auto-populate mutual store based on entity config\n populateMutualsForCreatedEntity(\n state,\n entityType,\n data as CreatedEntity<Entity>,\n entity as Record<string, any>,\n );\n }),\n undefined,\n `mr/entity/create/${entityType}`,\n );\n\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n onError?.(error);\n\n return { error };\n }\n };\n\n const upsertEntity = async <T extends Entity>(\n entityType: T,\n id: string,\n entity: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => {\n const entityService = makeEntityService(entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data } = await entityService.upsertEntity(id, entity, opts);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(data.entityId, data);\n }),\n undefined,\n `mr/entity/upsert/${entityType}/${id}`,\n );\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n // Reconcile an entity's membership across already-loaded tag slices after a\n // data change (edit/adjust). Runs each tag's processor against the new data\n // and, per slice, keeps/adds the entity where it now matches and removes it\n // where it no longer does — so the UI re-buckets optimistically instead of\n // leaving stale members (e.g. a resolved item still sitting in the \"open\"\n // list) until the backend tag processor catches up. Mirrors the add-only\n // matcher in createEntity, extended with delete-on-mismatch.\n const reconcileTaggedEntityStore = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n state: any,\n entityType: Entity,\n id: string,\n data: CreatedEntity<Entity>,\n ) => {\n const tagConfigs = state.config[entityType]?.tags;\n if (!tagConfigs) return;\n\n for (const tagConfig of tagConfigs) {\n const { name, processor } = tagConfig;\n const processorResults = processor(data);\n\n for (const tagKey of Object.keys(state.tag)) {\n const [tagEntityType, tagName, ...paramParts] = tagKey.split('/');\n if (\n (tagEntityType as unknown as Entity) !== entityType ||\n tagName !== name\n ) {\n continue;\n }\n\n const slice = state.tag[tagKey];\n if (!slice?.dataMap) {\n continue;\n }\n\n // parse params (group/start/end/query/...) back out of the key\n const keyParams: Record<string, string> = {};\n for (const part of paramParts) {\n const colonIdx = part.indexOf(':');\n if (colonIdx > 0) {\n keyParams[part.substring(0, colonIdx)] = part.substring(\n colonIdx + 1,\n );\n }\n }\n\n // query-filtered slices can't be evaluated client-side — only patch an\n // existing member's data in place; never add or remove.\n if (keyParams.query) {\n if (slice.dataMap.has(id)) {\n slice.dataMap.set(id, data);\n }\n continue;\n }\n\n const matches = processorResults.some(\n (result: { group?: string; sortValue?: string }) => {\n if (keyParams.group && result.group !== keyParams.group) {\n return false;\n }\n if (\n keyParams.start &&\n (!result.sortValue || result.sortValue < keyParams.start)\n ) {\n return false;\n }\n if (\n keyParams.end &&\n (!result.sortValue || result.sortValue > keyParams.end)\n ) {\n return false;\n }\n return true;\n },\n );\n\n if (matches) {\n // keep/patch existing members, and add to newly-matching loaded\n // slices (appended; a later fetch restores exact sort order)\n if (slice.isFirstFetched || slice.dataMap.has(id)) {\n slice.dataMap.set(id, data);\n }\n } else if (slice.dataMap.has(id)) {\n // no longer belongs here — drop the stale member (the re-bucket)\n slice.dataMap.delete(id);\n }\n }\n }\n };\n\n // Patches an already-edited entity's new `.data` into every loaded mutual\n // list it appears in (the entity's OWN dataMap entry is set by the caller).\n // Shared by editEntity/adjustEntity/executeTransaction's update/adjust\n // branch — kept as one place so the three paths can't drift apart.\n const propagateEntityDataToMutuals = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n state: any,\n entityType: Entity,\n entityId: string,\n data: Record<string, any>,\n ) => {\n for (const key of Object.keys(state.mutual)) {\n const { entity: mutualEntityType } = parseMutualStateKey(key);\n if (mutualEntityType === entityType) {\n const mutual = state.mutual[key].dataMap.get(entityId);\n if (mutual) {\n state.mutual[key].dataMap = new Map(state.mutual[key].dataMap).set(\n entityId,\n { ...mutual, data },\n );\n }\n }\n }\n };\n\n // Removes a deleted entity's own dataMap entry, its forward-side mutual\n // entries (lists it's a MEMBER of — the reverse side, lists keyed BY this\n // entity, is deleteLocalMutualsByEntity's job, since that needs full entity\n // config), and its tag-store entries. Shared by deleteEntity/\n // executeTransaction's delete branch.\n const deleteEntityFromStores = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n state: any,\n entityType: Entity,\n entityId: string,\n ) => {\n state.entity[entityType]?.dataMap.delete(entityId);\n\n for (const key of Object.keys(state.mutual)) {\n const { entity: mutualEntityType } = parseMutualStateKey(key);\n if (mutualEntityType === entityType) {\n state.mutual[key].dataMap.delete(entityId);\n }\n }\n\n for (const tagKey of Object.keys(state.tag)) {\n const [tagEntityType] = tagKey.split('/');\n if ((tagEntityType as unknown as Entity) === entityType) {\n state.tag[tagKey]?.dataMap?.delete(entityId);\n }\n }\n };\n\n const editEntity = async <T extends Entity>(\n entityType: T,\n id: string,\n entity: Partial<DraftEntity<T>>,\n opts: CommonOptions = {},\n ) => {\n const entityService = makeEntityService(entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data } = await entityService.editEntity(id, entity, opts);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(data.entityId, data);\n\n propagateEntityDataToMutuals(state, entityType, id, data.data);\n\n // re-bucket across loaded tag slices (add where now matches, drop\n // where it no longer does) instead of only patching in place\n reconcileTaggedEntityStore(\n state,\n entityType,\n id,\n data as CreatedEntity<Entity>,\n );\n }),\n undefined,\n `mr/entity/edit/${entityType}/${id}`,\n );\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const adjustEntity = async <T extends Entity>(\n entityType: T,\n id: string,\n adjustments: Record<string, number>,\n opts: CommonOptions = {},\n ) => {\n const entityService = makeEntityService(entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data } = await entityService.adjustEntity(id, adjustments, opts);\n\n // Update local store with server response\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(data.entityId, data);\n\n propagateEntityDataToMutuals(state, entityType, id, data.data);\n\n // Propagate to tag stores — re-bucket across loaded slices (an\n // adjustment can move an entity between groups when group/sortValue\n // derive from the adjusted fields), not just patch in place.\n reconcileTaggedEntityStore(\n state,\n entityType,\n id,\n data as CreatedEntity<Entity>,\n );\n }),\n undefined,\n `mr/entity/adjust/${entityType}/${id}`,\n );\n\n return { data };\n } catch (err: any) {\n // Constraint violated — refetch entity to get latest state\n if (err?.response?.status === 409) {\n await getEntity(entityType, id, { forceFetch: true });\n }\n\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const deleteEntity = async <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ) => {\n const entityService = makeEntityService(entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n await entityService.deleteEntity(id, opts);\n deleteLocalMutualsByEntity(entityType, id);\n\n monoriseStore.setState(\n produce((state) => {\n deleteEntityFromStores(state, entityType, id);\n }),\n undefined,\n `mr/entity/delete/${entityType}/${id}`,\n );\n return { data: { entityId: id } }; // Indicate success with the deleted ID\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n // Runs a multi-entity atomic write (`coreService.executeTransaction`,\n // backed by a real DynamoDB TransactWriteItems) and folds each op's result\n // back into the local store — the same cache guarantee createEntity/\n // editEntity/adjustEntity/deleteEntity already give a single-entity call,\n // so a caller doesn't have to hand-roll cache patching (or force a\n // refetch) just because their write happened to span more than one entity.\n const executeTransaction = async (\n operations: TransactionOperation[],\n opts: CommonOptions = {},\n ) => {\n const onError = opts.onError ?? defaultOnError;\n const isInterruptive = opts.isInterruptive ?? true;\n const opRequestKeys = operations.map(getTransactionOperationRequestKey);\n // The joined key is namespaced under `transaction/` so it can never\n // match a single-entity action's own key — using e.g. opRequestKeys[0]\n // directly would let a standalone editEntity/createEntity call on that\n // same target collide with this transaction via lib/api.ts's\n // `ongoingRequests` dedupe, handing either caller the other's\n // differently-shaped response. Unique per call rather than deterministic,\n // because a transaction is a batch of non-idempotent writes -- see\n // createTransactionCallRequestKey for why deduping them silently loses\n // writes. Pass `opts.requestKey` explicitly to opt back into dedupe.\n const callRequestKey =\n opts.requestKey || createTransactionCallRequestKey(operations);\n const callPromise = coreService.executeTransaction(operations, {\n ...opts,\n requestKey: callRequestKey,\n });\n const loadingMessage = opts.feedback?.loading ?? 'Processing transaction';\n\n // Drive the same per-entity loading/error signal a standalone\n // createEntity/editEntity/adjustEntity/deleteEntity call on each op's\n // target would have driven, so a component checking any op's target via\n // useLoadStore/getError sees \"mutating\" during a transaction too. `request`\n // is deliberately omitted here — passing it would register these keys in\n // `ongoingRequests` too, letting a concurrent standalone call on the same\n // target dedupe onto (and never actually send) its own write. These keys\n // exist purely for loading/error *signaling*, not for de-duplicating this\n // HTTP call — that's callRequestKey's job.\n for (const requestKey of opRequestKeys) {\n startLoading({ requestKey, isInterruptive, message: loadingMessage });\n }\n\n // Tracks whether the network call itself has already resolved and had\n // its success-path loading/error signaling run — so if the cache-fold\n // below throws (a tag processor, a bad payload, ...), the catch block\n // doesn't ALSO run the failure-path signaling for keys that were already\n // correctly cleared, which would both mis-decrement stacks shared with\n // other concurrent calls on those same keys and report a transaction\n // that actually committed as failed.\n let settled = false;\n\n try {\n const { data } = await callPromise;\n\n for (const requestKey of opRequestKeys) {\n endLoading({ requestKey, isInterruptive, skipDedupe: true });\n clearError(requestKey);\n }\n settled = true;\n\n const deletedEntities: { entityType: Entity; entityId: string }[] = [];\n\n monoriseStore.setState(\n produce((state) => {\n data.results.forEach((entry, index) => {\n const { entityType, entityId } = entry;\n\n if (entry.operation === 'deleteEntity') {\n deleteEntityFromStores(state, entityType, entityId);\n deletedEntities.push({ entityType, entityId });\n return;\n }\n\n // createMutual / updateMutual / deleteMutual: the same store\n // updates the standalone createMutual / editMutual / deleteMutual\n // actions make, on both sides of the link.\n if (\n entry.operation === 'createMutual' ||\n entry.operation === 'updateMutual' ||\n entry.operation === 'deleteMutual'\n ) {\n const byEntityType = entry.byEntityType as Entity;\n const byEntityId = entry.byEntityId as string;\n const bySide = getMutualStateKey(\n byEntityType,\n byEntityId,\n entityType,\n );\n const side = getMutualStateKey(\n entityType,\n entityId,\n byEntityType,\n );\n\n if (entry.operation === 'deleteMutual') {\n state.mutual[bySide]?.dataMap.delete(entityId);\n state.mutual[side]?.dataMap.delete(byEntityId);\n return;\n }\n\n // An updateMutual whose post-commit read failed carries no\n // stored values — leave the cache alone rather than guess at\n // the merge, as for updateEntity below.\n if (entry.operation === 'updateMutual' && !entry.mutualData) {\n return;\n }\n\n const mutual = {\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n mutualId: entry.mutualId,\n data: entry.data ?? {},\n mutualData: entry.mutualData ?? {},\n createdAt: entry.createdAt,\n updatedAt: entry.updatedAt,\n mutualUpdatedAt: entry.mutualUpdatedAt,\n } as unknown as Mutual;\n\n if (!state.mutual[bySide]) {\n state.mutual[bySide] = { dataMap: new Map() };\n }\n state.mutual[bySide].dataMap = new Map(\n state.mutual[bySide]?.dataMap,\n ).set(entityId, mutual);\n\n if (!state.mutual[side]) {\n state.mutual[side] = { dataMap: new Map() };\n }\n const byEntityData =\n state.entity[byEntityType]?.dataMap.get(byEntityId)?.data ?? {};\n state.mutual[side].dataMap = new Map(\n state.mutual[side]?.dataMap,\n ).set(byEntityId, flipMutual(mutual, byEntityData));\n return;\n }\n\n if (entry.operation === 'createEntity') {\n const createdEntity = {\n entityId,\n entityType,\n data: entry.data ?? {},\n createdAt: entry.createdAt,\n updatedAt: entry.updatedAt,\n } as unknown as CreatedEntity<Entity>;\n\n state.entity[entityType].dataMap.set(entityId, createdEntity);\n\n const op = operations[index] as TransactionCreateEntity;\n populateMutualsForCreatedEntity(\n state,\n entityType,\n createdEntity,\n op?.payload as Record<string, any>,\n );\n reconcileTaggedEntityStore(\n state,\n entityType,\n entityId,\n createdEntity,\n );\n return;\n }\n\n // updateEntity / adjustEntity. `entry.data` is populated either\n // by the write itself or by transaction.service.ts's Phase 4\n // read-back — only patch the cache when we actually have fresh\n // data to patch it with, rather than guessing at a partial merge.\n const existing = state.entity[entityType]?.dataMap.get(entityId);\n if (!existing && !entry.data) return;\n\n if (!entry.data) {\n // No fresh data, but we do know the write landed — bump the\n // timestamp so at least `updatedAt` isn't stale, without\n // touching `.data` (and so without needing to re-bucket tags).\n if (entry.updatedAt) {\n state.entity[entityType].dataMap.set(entityId, {\n ...existing,\n updatedAt: entry.updatedAt,\n });\n }\n return;\n }\n\n const updated = {\n ...(existing ?? { entityId, entityType }),\n data: entry.data,\n updatedAt: entry.updatedAt ?? existing?.updatedAt,\n } as unknown as CreatedEntity<Entity>;\n\n state.entity[entityType].dataMap.set(entityId, updated);\n propagateEntityDataToMutuals(state, entityType, entityId, updated.data);\n reconcileTaggedEntityStore(state, entityType, entityId, updated);\n });\n }),\n undefined,\n 'mr/entity/execute-transaction',\n );\n\n // Reverse-side mutual cleanup for deletes (lists keyed BY the deleted\n // entity itself) — mirrors deleteEntity's own use of this helper, which\n // needs full entity config and does its own separate setState.\n for (const { entityType, entityId } of deletedEntities) {\n deleteLocalMutualsByEntity(entityType, entityId);\n }\n\n return { data };\n } catch (err) {\n if (!settled) {\n // The axios interceptor already ran its own error handling for\n // callRequestKey (endLoading + setError) — read back whatever\n // appError it computed and mirror it onto every op's key, rather\n // than re-deriving the AxiosError → ApplicationRequestError shaping\n // logic here.\n const callAppError = getError(callRequestKey);\n for (const requestKey of opRequestKeys) {\n endLoading({ requestKey, isInterruptive, skipDedupe: true });\n if (callAppError) {\n setError({ requestKey, error: callAppError });\n }\n }\n // A generated key cannot be recomputed by a consumer or reused by a\n // later success, so retaining its interceptor error would leak one\n // unreachable errorStack entry per failed transaction. Explicit keys\n // remain observable and are therefore left intact.\n if (!opts.requestKey) {\n clearError(callRequestKey);\n }\n }\n\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const listEntitiesByEntity = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n chainEntityQuery?: string,\n ) => {\n const onError = opts.onError ?? defaultOnError;\n const selfKey =\n opts.stateKey ??\n getMutualStateKey(\n byEntityType,\n id,\n entityType,\n undefined,\n chainEntityQuery,\n );\n const mutualService = makeMutualService(byEntityType, entityType);\n const store = monoriseStore.getState();\n const mutualState = store.mutual[selfKey] || {};\n const { isFirstFetched } = mutualState;\n const requestKey = getMutualRequestKey(\n 'list',\n byEntityType,\n entityType,\n id,\n undefined,\n chainEntityQuery,\n );\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const { forceFetch } = opts;\n\n if (!forceFetch) {\n if (error) {\n onError(error);\n return { error };\n }\n\n if (isFirstFetched || isLoading) {\n return {\n data: {\n entities: Array.from(mutualState.dataMap?.values() || []),\n lastKey: mutualState.lastKey,\n },\n };\n }\n }\n\n try {\n const { data } = await mutualService.listEntitiesByEntity(\n id,\n opts,\n chainEntityQuery,\n );\n const { entities, lastKey } = data;\n const newEntityDataMap = new Map();\n\n for (const i in entities) {\n newEntityDataMap.set(entities[i].entityId, entities[i]);\n }\n\n monoriseStore.setState(\n produce((state) => {\n for (const [key, value] of newEntityDataMap) {\n state.entity[entityType]?.dataMap.set(key, value);\n }\n\n // prepare or extend the mutual entry\n const existing = state.mutual[selfKey];\n if (existing) {\n // extend the existing map\n const incoming = convertToMap(entities, 'entityId');\n for (const [k, v] of incoming) {\n existing.dataMap.set(k, v);\n }\n existing.isFirstFetched = true;\n existing.lastKey = lastKey;\n } else {\n // first time: create it\n state.mutual[selfKey] = {\n dataMap: convertToMap(entities, 'entityId'),\n isFirstFetched: true,\n lastKey,\n };\n }\n }),\n undefined,\n `mr/mutual/list/${selfKey}`,\n );\n\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n // todo: list more mutuals by entity\n // const listMoremutualsByEntity = async (\n // entityType: Entity,\n // otherEntityType: Entity,\n // id: string,\n // ) =>\n\n const getMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string | null,\n entityId: string,\n opts: CommonOptions & {\n // if failed to retrieve, would still set a default mutual data\n defaultMutualData?: Record<string, any>;\n } = {},\n ) => {\n const selfKey = getMutualStateKey(byEntityType, byEntityId, entityType);\n const mutualService = makeMutualService(byEntityType, entityType);\n const store = monoriseStore.getState();\n const mutualState = store.mutual[selfKey] || {};\n const requestKey = getMutualRequestKey(\n 'get',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n );\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const onError = opts.onError ?? defaultOnError;\n\n if (error) {\n onError?.(error);\n return { error };\n }\n\n if (!byEntityId || isLoading) {\n return {\n data: mutualState.dataMap?.get(entityId) as Mutual<B, T>,\n };\n }\n\n if (mutualState.dataMap?.get(entityId)) {\n return {\n data: mutualState.dataMap.get(entityId) as Mutual<B, T>,\n };\n }\n\n let mutual: Omit<Mutual<B, T>, 'data'>;\n let hasRequestFailed = false;\n\n try {\n ({ data: mutual } = await mutualService.getMutual(\n byEntityId,\n entityId,\n opts,\n ));\n } catch (err) {\n if (!opts.defaultMutualData) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n return { error };\n }\n\n hasRequestFailed = true;\n mutual = {\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n mutualId: `${byEntityId}-${entityId}`,\n mutualUpdatedAt: new Date().toISOString(),\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n mutualData: opts.defaultMutualData,\n };\n }\n\n const newMutualDataMap = new Map(store.mutual[selfKey]?.dataMap);\n newMutualDataMap.set(mutual.entityId, mutual as Mutual<B, T>);\n\n if (!hasRequestFailed) {\n const entityState = store.entity[entityType];\n const { dataMap: entityDataMap } = entityState;\n\n const newEntityDataMap = new Map(entityDataMap);\n newEntityDataMap.set(mutual.entityId, mutual as any);\n\n monoriseStore.setState(\n produce((state) => {\n state.mutual[selfKey] = {\n ...(state.mutual[selfKey] || {}),\n dataMap: newMutualDataMap,\n };\n state.entity[entityType].dataMap = newEntityDataMap;\n }),\n undefined,\n `mr/mutual/get/${getMutualStateKey(\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n )}`,\n );\n }\n return { data: mutual as Mutual<B, T> };\n };\n\n const createMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, any> = {},\n opts: CommonOptions = {},\n ) => {\n const mutualService = makeMutualService(byEntityType, entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data: mutual } = await mutualService.createMutual(\n byEntityId,\n entityId,\n payload,\n opts,\n );\n\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(\n byEntityType,\n byEntityId,\n entityType,\n );\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n\n if (!state.mutual[bySide]) {\n state.mutual[bySide] = {\n dataMap: new Map(),\n };\n }\n\n state.mutual[bySide].dataMap = new Map(\n state.mutual[bySide]?.dataMap,\n ).set(mutual.entityId, mutual);\n\n if (!state.mutual[side]) {\n state.mutual[side] = {\n dataMap: new Map(),\n };\n }\n\n const byEntityData =\n state.entity[mutual.byEntityType]?.dataMap.get(mutual.byEntityId)\n ?.data ?? {};\n state.mutual[side].dataMap = new Map(state.mutual[side]?.dataMap).set(\n mutual.byEntityId,\n flipMutual(mutual, byEntityData),\n );\n }),\n undefined,\n `mr/mutual/create/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n return { data: mutual };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const createLocalMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n mutualData: MutualData<B, T>,\n data: EntitySchemaMap[T] | Record<string, any>,\n ) => {\n const mutual = constructMutual(\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n mutualData,\n data as EntitySchemaMap[T],\n );\n\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(byEntityType, byEntityId, entityType);\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n\n if (!state.mutual[bySide]) {\n state.mutual[bySide] = {\n dataMap: new Map(),\n };\n }\n\n state.mutual[bySide].dataMap = new Map(\n state.mutual[bySide]?.dataMap,\n ).set(mutual.entityId, mutual);\n\n if (!state.mutual[side]) {\n state.mutual[side] = {\n dataMap: new Map(),\n };\n }\n\n const byEntityData =\n state.entity[mutual.byEntityType]?.dataMap.get(mutual.byEntityId)\n ?.data ?? {};\n state.mutual[side].dataMap = new Map(state.mutual[side]?.dataMap).set(\n mutual.byEntityId,\n flipMutual(mutual, byEntityData),\n );\n }),\n undefined,\n `mr/mutual/create/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n };\n\n const updateLocalEntity = async <T extends Entity>(\n entityType: Entity,\n entityId: string,\n data: Partial<DraftEntity<T>> = {},\n ) => {\n const createdEntity = constructLocal(entityType, entityId, data);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(entityId, createdEntity);\n }),\n undefined,\n `mr/entity/local-update/${entityType}/${entityId}`,\n );\n };\n\n const upsertLocalMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n mutualData: MutualData<B, T>,\n data: EntitySchemaMap[T] | Record<string, any> = {},\n ) => {\n const mutual = constructMutual(\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n mutualData,\n data as EntitySchemaMap[T],\n );\n\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(byEntityType, byEntityId, entityType);\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n\n if (!state.mutual[bySide]) {\n state.mutual[bySide] = {\n dataMap: new Map(),\n };\n }\n\n state.mutual[bySide].dataMap = new Map(\n state.mutual[bySide]?.dataMap,\n ).set(entityId, mutual);\n\n if (!state.mutual[side]) {\n state.mutual[side] = {\n dataMap: new Map(),\n };\n }\n\n const byEntityData =\n state.entity[mutual.byEntityType]?.dataMap.get(mutual.byEntityId)\n ?.data ?? {};\n state.mutual[side].dataMap = new Map(state.mutual[side]?.dataMap).set(\n byEntityId,\n flipMutual(mutual, byEntityData),\n );\n }),\n undefined,\n `mr/mutual/local-update/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n };\n\n const editMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, any> = {},\n opts: CommonOptions = {},\n ) => {\n const mutualService = makeMutualService(byEntityType, entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data: mutual } = await mutualService.editMutual(\n byEntityId,\n entityId,\n payload,\n opts,\n );\n\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(\n byEntityType,\n byEntityId,\n entityType,\n );\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n\n if (!state.mutual[bySide]) {\n state.mutual[bySide] = {\n dataMap: new Map(),\n };\n }\n\n state.mutual[bySide].dataMap = new Map(\n state.mutual[bySide]?.dataMap,\n ).set(mutual.entityId, mutual);\n\n if (!state.mutual[side]) {\n state.mutual[side] = {\n dataMap: new Map(),\n };\n }\n\n const byEntityData =\n state.entity[mutual.byEntityType]?.dataMap.get(mutual.byEntityId)\n ?.data ?? {};\n state.mutual[side].dataMap = new Map(state.mutual[side]?.dataMap).set(\n mutual.byEntityId,\n flipMutual(mutual, byEntityData),\n );\n }),\n undefined,\n `mr/mutual/edit/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n return { data: mutual };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const deleteMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId = '',\n opts: CommonOptions = {},\n ) => {\n const mutualService = makeMutualService(byEntityType, entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data } = await mutualService.deleteMutual(\n byEntityId,\n entityId,\n opts,\n );\n\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(\n byEntityType,\n byEntityId,\n entityType,\n );\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n\n // Either list may never have been fetched; the delete still\n // succeeded, so don't report it as failed.\n state.mutual[bySide]?.dataMap.delete(data.entityId);\n state.mutual[side]?.dataMap.delete(data.byEntityId);\n }),\n undefined,\n `mr/mutual/delete/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const deleteLocalMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n ) => {\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(byEntityType, byEntityId, entityType);\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n const bySideDataMap = new Map(state.mutual[bySide]?.dataMap);\n const sideDataMap = new Map(state.mutual[side]?.dataMap);\n bySideDataMap.delete(entityId);\n sideDataMap.delete(byEntityId);\n\n if (state.mutual[bySide]) {\n state.mutual[bySide].dataMap.delete(entityId);\n }\n if (state.mutual[side]) {\n state.mutual[side].dataMap.delete(byEntityId);\n }\n }),\n undefined,\n `mr/mutual/local-delete/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n };\n\n const deleteLocalMutualsByEntity = <T extends Entity>(\n entityType: T,\n id: string,\n ) => {\n const store = monoriseStore.getState();\n const entityConfig = store.config; // Assuming store.config holds mutual related configurations\n let mutuals: Mutual[] = [];\n for (const i of Object.keys(entityConfig)) {\n const mutualState = store.mutual[`${entityType}/${id}/${i}`];\n mutuals = [\n ...mutuals,\n ...Array.from(mutualState?.dataMap.values() || []),\n ];\n }\n\n const updatedState = mutuals.reduce(\n (acc, mutual) => {\n const side = getMutualStateKey(\n mutual.entityType,\n mutual.entityId,\n mutual.byEntityType,\n );\n const dataMap = new Map(store.mutual[side]?.dataMap); // Use optional chaining\n dataMap.delete(id);\n acc[side] = {\n ...store.mutual[side],\n dataMap,\n };\n return acc;\n },\n {} as Record<string, CommonStore<Mutual>>,\n );\n\n monoriseStore.setState(\n produce((state) => {\n // This is a full replacement, might not be desired for partial updates.\n // If state.mutual can contain other keys, this might clear them.\n // Consider a more granular update if needed.\n for (const key in updatedState) {\n state.mutual[key] = updatedState[key];\n }\n }),\n undefined,\n `mr/mutual/local-delete-by-entity/${entityType}/${id}`,\n );\n };\n\n const useEntity = <T extends Entity>(\n entityType: T,\n id?: string,\n opts: CommonOptions = {},\n ): {\n entity: CreatedEntity<T> | undefined;\n isLoading: boolean;\n error?: ApplicationRequestError;\n requestKey: string;\n isFirstFetched?: boolean;\n refetch: () => Promise<CreatedEntity<T> | undefined>;\n } => {\n const dataMap = monoriseStore(\n (state) => state.entity[entityType]?.dataMap || new Map(),\n );\n const isFirstFetched = monoriseStore(\n (state) => state.entity[entityType]?.isFirstFetched,\n );\n const requestKey = getEntityRequestKey('get', entityType, id);\n const isLoading = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n\n useEffect(() => {\n if (id) {\n getEntity(entityType, id, opts);\n }\n }, [id, entityType, opts]);\n\n return {\n entity: id ? dataMap.get(id) : undefined,\n isLoading,\n error,\n requestKey,\n isFirstFetched,\n refetch: async () => {\n if (id) {\n const { data, error: fetchError } = await getEntity(entityType, id, {\n ...opts,\n forceFetch: true,\n });\n if (fetchError) {\n // Handle refetch error if necessary, e.g., throw or set local state\n }\n return data;\n }\n },\n };\n };\n\n const useEntityByUniqueField = <T extends Entity>(\n entityType: T,\n fieldName: string,\n value?: string,\n opts: CommonOptions = {},\n ): {\n entity: CreatedEntity<T> | undefined;\n isLoading: boolean;\n error?: ApplicationRequestError;\n requestKey: string;\n isFirstFetched?: boolean;\n refetch: () => Promise<CreatedEntity<T> | undefined>;\n } => {\n const dataMap = monoriseStore(\n (state) => state.entity[entityType]?.dataMap || new Map(),\n );\n const isFirstFetched = monoriseStore(\n (state) => state.entity[entityType]?.isFirstFetched,\n );\n const stateKey = getUniqueFieldStateKey(fieldName, value || '');\n const requestKey = getUniqueFieldRequestKey(\n entityType,\n fieldName,\n value || '',\n );\n const isLoading = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n\n useEffect(() => {\n if (value) {\n getEntityByUniqueField(entityType, fieldName, value, opts);\n }\n }, [fieldName, value, entityType, opts]);\n\n return {\n entity: value ? dataMap.get(`${stateKey}`) : undefined,\n isLoading,\n error,\n requestKey,\n isFirstFetched,\n refetch: async () => {\n if (value) {\n const { data, error: fetchError } = await getEntityByUniqueField(\n entityType,\n fieldName,\n value,\n {\n ...opts,\n forceFetch: true,\n },\n );\n if (fetchError) {\n // Handle refetch error if necessary\n }\n return data;\n }\n },\n };\n };\n\n const useEntities = <T extends Entity>(\n entityType: T,\n params: {\n skRange?: {\n start: string;\n end: string;\n };\n all?: boolean;\n limit?: number;\n } = { limit: 20 },\n opts: CommonOptions & { searchInterval?: number } = {},\n ): {\n isLoading: boolean;\n entities?: CreatedEntity<T>[];\n entitiesMap: Map<string, CreatedEntity<T>>;\n error?: ApplicationRequestError;\n requestKey: string;\n searchField: {\n value: string;\n onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;\n };\n lastKey?: string;\n isFirstFetched?: boolean;\n listMore: () => void;\n refetch: () => void;\n } => {\n const requestKey = getEntityRequestKey('list', entityType);\n const isListing = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n const state = monoriseStore((state) => state.entity[entityType]);\n const { dataMap, searchResults, isFirstFetched, lastKey } = state ?? {\n dataMap: new Map(),\n };\n const [entities, setEntities] = useState<CreatedEntity<T>[]>();\n const [query, setQuery] = useState<string>('');\n const [skRange, setBetween] = useState(params.skRange);\n const [all, setAll] = useState(params.all);\n const [limit, setLimit] = useState(params.limit);\n const [isSearching, setIsSearching] = useState(false);\n const isLoading = isListing || isSearching;\n\n useEffect(() => {\n if (\n params?.skRange &&\n skRange?.start !== params.skRange.start &&\n skRange?.end !== params.skRange.end\n ) {\n setBetween(params.skRange);\n }\n }, [skRange?.end, skRange?.start, params.skRange]);\n\n useEffect(() => {\n if (params?.all !== all) {\n setAll(params.all);\n }\n }, [all, params.all]);\n\n useEffect(() => {\n if (params?.limit !== limit) {\n setLimit(params.limit);\n }\n }, [limit, params.limit]);\n\n useEffect(() => {\n if (!isFirstFetched || opts?.forceFetch) {\n listEntities(entityType, { skRange, all, limit }, opts);\n }\n }, [all, entityType, skRange, opts, isFirstFetched, opts?.forceFetch, limit]);\n\n useEffect(() => {\n let queryTimeout: NodeJS.Timeout;\n\n if (query?.length) {\n setIsSearching(true);\n queryTimeout = setTimeout(async () => {\n await searchEntities(entityType, query);\n setIsSearching(false);\n }, opts.searchInterval ?? 700);\n }\n\n return () => queryTimeout && clearTimeout(queryTimeout);\n }, [entityType, query]);\n\n useEffect(() => {\n if (!query) {\n const dataMapArray = Array.from(dataMap.values()).sort(\n byEntityId,\n ) as CreatedEntity<T>[];\n // Compare size AND content so that edits which keep the same set of\n // entityIds but mutate their data (e.g. editEntity) still propagate\n // to the local `entities` snapshot. Matches the comparison already\n // used in `useMutuals`.\n if (\n dataMap.size !== entities?.length ||\n dataMapArray.some(\n (item, index) =>\n JSON.stringify(item) !== JSON.stringify(entities?.[index]),\n )\n ) {\n setIsSearching(false);\n setEntities(dataMapArray);\n }\n }\n\n if (query) {\n setEntities(searchResults as CreatedEntity<T>[]);\n }\n }, [\n dataMap,\n dataMap.size,\n entities,\n entities?.length,\n query,\n searchResults,\n searchResults?.length,\n ]);\n\n const handleQueryChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n setQuery(event.target.value);\n };\n\n const searchField = {\n value: query,\n onChange: handleQueryChange,\n };\n\n return {\n entities,\n entitiesMap: dataMap,\n searchField,\n isLoading,\n error,\n requestKey,\n isFirstFetched,\n lastKey,\n refetch: async () => {\n if (entityType && query) {\n await searchEntities(entityType, query);\n return;\n }\n await listEntities(\n entityType,\n { skRange, all },\n {\n ...opts,\n forceFetch: true,\n },\n );\n },\n listMore: async () => {\n if (!lastKey) return;\n\n await listMoreEntities(entityType, {\n ...opts,\n limit,\n forceFetch: true,\n });\n },\n };\n };\n\n const useMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byId: string | null,\n id: string,\n opts: CommonOptions & {\n // if failed to retrieve, would still set a default mutual data\n defaultMutualData?: Record<string, any>;\n } = {},\n ): {\n mutual?: Mutual<B, T>;\n isLoading: boolean;\n error?: ApplicationRequestError;\n requestKey: string;\n } => {\n const stateKey = getMutualStateKey(byEntityType, byId, entityType);\n const state = monoriseStore((state) => state.mutual[stateKey]);\n const requestKey = getMutualRequestKey(\n 'get',\n byEntityType,\n entityType,\n byId,\n id,\n );\n const isLoading = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n\n const { dataMap } = state || {\n dataMap: new Map(),\n };\n\n useEffect(() => {\n if (!dataMap.get(id)) {\n getMutual(byEntityType, entityType, byId, id, opts);\n }\n }, [byEntityType, byId, entityType, id, opts, dataMap]);\n\n return {\n mutual: dataMap.get(id) as Mutual<B, T>,\n isLoading,\n error,\n requestKey,\n };\n };\n\n const useMutuals = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byId?: string,\n opts: CommonOptions = {},\n chainEntityQuery?: string, // chain entity query, refer to list-entities-by-entity.controller.ts\n ): {\n mutuals: Mutual<B, T>[];\n mutualsMap: Map<string, Mutual<B, T>>;\n isLoading: boolean;\n requestKey: string;\n error?: ApplicationRequestError;\n isFirstFetched?: boolean;\n lastKey?: string;\n listMore?: () => void;\n refetch?: () => Promise<any>;\n } => {\n const stateKey = getMutualStateKey(\n byEntityType,\n byId || '',\n entityType,\n undefined,\n chainEntityQuery,\n );\n const state = monoriseStore((state) => state.mutual[stateKey]);\n const { dataMap, isFirstFetched, lastKey } = state || {\n dataMap: new Map(),\n };\n const [mutuals, setMutuals] = useState<Mutual<B, T>[]>([]);\n const requestKey = getMutualRequestKey(\n 'list',\n byEntityType,\n entityType,\n byId || '',\n undefined,\n chainEntityQuery,\n );\n const isLoading = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n\n useEffect(() => {\n if (byEntityType && entityType && byId && (!isFirstFetched || opts?.forceFetch)) {\n listEntitiesByEntity(\n byEntityType,\n entityType,\n byId,\n { ...opts, stateKey },\n chainEntityQuery,\n );\n }\n }, [\n isFirstFetched,\n byEntityType,\n byId,\n entityType,\n opts,\n chainEntityQuery,\n stateKey,\n opts?.forceFetch,\n opts?.noData,\n ]);\n\n useEffect(() => {\n const dataMapArray = Array.from(dataMap.values());\n if (\n dataMap.size !== mutuals?.length ||\n dataMapArray.some(\n (item, index) =>\n JSON.stringify(item) !== JSON.stringify(mutuals[index]),\n )\n ) {\n setMutuals(dataMapArray as Mutual<B, T>[]);\n }\n }, [dataMap, dataMap.size, mutuals?.length]);\n\n return {\n mutuals,\n mutualsMap: dataMap as Map<string, Mutual<B, T>>,\n isLoading,\n requestKey,\n error,\n isFirstFetched,\n lastKey,\n refetch: async () => {\n if (byEntityType && entityType && byId) {\n return await listEntitiesByEntity(\n byEntityType,\n entityType,\n byId,\n {\n ...opts,\n forceFetch: true,\n stateKey,\n },\n chainEntityQuery,\n );\n }\n },\n ...(lastKey && {\n listMore: () => {\n if (byEntityType && entityType && byId) {\n listEntitiesByEntity(\n byEntityType,\n entityType,\n byId,\n {\n ...opts,\n forceFetch: true,\n params: { ...opts.params, lastKey },\n stateKey,\n },\n chainEntityQuery,\n );\n }\n },\n }),\n };\n };\n\n // Order a loaded tag slice the same way the server does, so optimistic\n // edits/adjusts land in their true position instead of appending to the end.\n // The backend queries tags with ScanIndexForward:false — i.e. descending by\n // the tag sort key `${sortValue}#${entityType}#${entityId}` (see\n // TaggedEntity.get sk()). We rebuild that exact key per entity from the tag's\n // processor and sort descending, reproducing DynamoDB's ordering (sortValue\n // first, entityId tiebreak, identical string coercion). This only re-orders\n // the loaded window; on a paginated list an item whose new sortValue belongs\n // on an unfetched page may sit at the boundary until the next fetch — a\n // per-user, self-healing approximation, strictly better than not sorting.\n const sortTaggedEntitiesLikeServer = <T extends Entity>(\n arr: CreatedEntity<T>[],\n entityType: Entity,\n tagName: string,\n group?: string,\n ): CreatedEntity<T>[] => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const tagConfig = (monoriseStore.getState().config[entityType] as any)\n ?.tags?.find((t: { name: string }) => t.name === tagName);\n\n const keyOf = (entity: CreatedEntity<T>): string => {\n let sortValue: unknown;\n if (tagConfig?.processor) {\n const results = tagConfig.processor(entity) as {\n group?: string;\n sortValue?: unknown;\n }[];\n const match = group\n ? results.find((r) => r.group === group)\n : results[0];\n sortValue = match?.sortValue;\n }\n return `${sortValue ? `${sortValue}#` : ''}${entityType}#${entity.entityId}`;\n };\n\n return arr\n .map((entity) => ({ entity, key: keyOf(entity) }))\n .sort((a, b) => (a.key === b.key ? 0 : a.key < b.key ? 1 : -1))\n .map((x) => x.entity);\n };\n\n const useTaggedEntities = <T extends Entity>(\n entityType: T,\n tagName: string,\n opts: CommonOptions & { params?: ListEntitiesByTagParams } = {},\n ) => {\n const { params } = opts || {};\n const stateKey = getTagStateKey(entityType, tagName, params);\n const state = monoriseStore((state) => state.tag[stateKey]);\n const { dataMap, isFirstFetched, lastKey } = state || {\n dataMap: new Map(),\n };\n const [entities, setEntities] = useState<CreatedEntity<T>[]>([]);\n const requestKey = getTagRequestKey('list', entityType, tagName, params);\n const isLoading = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n\n useEffect(() => {\n if (entityType && tagName && Object.keys(params).length > 0) {\n listEntitiesByTag(entityType, tagName, opts);\n }\n }, [entityType, opts, tagName, params, opts?.forceFetch]);\n\n useEffect(() => {\n const dataMapArray = sortTaggedEntitiesLikeServer(\n Array.from(dataMap.values()) as CreatedEntity<T>[],\n entityType,\n tagName,\n params?.group,\n );\n if (\n dataMap.size !== entities?.length ||\n dataMapArray.some(\n (item, index) =>\n JSON.stringify(item) !== JSON.stringify(entities[index]),\n )\n ) {\n setEntities(dataMapArray);\n }\n }, [dataMap, dataMap.size, entities?.length]);\n\n return {\n entities,\n entitiesMap: dataMap as Map<string, CreatedEntity<T>>,\n isLoading,\n requestKey,\n error,\n isFirstFetched,\n lastKey,\n refetch: async () => {\n if (entityType && tagName && params?.group) {\n return await listEntitiesByTag(entityType, tagName, {\n ...opts,\n forceFetch: true,\n });\n }\n },\n listMore: async () => {\n if (entityType && tagName && params?.group) {\n return await listEntitiesByTag(entityType, tagName, {\n ...opts,\n forceFetch: true,\n params: { ...params, lastKey },\n });\n }\n },\n };\n };\n\n const useEntityState = <T extends Entity>(entityType: T) => {\n return monoriseStore((state) => state.entity[entityType]);\n };\n\n const updateLocalTaggedEntity = <T extends Entity>(\n entityType: T,\n entityId: string,\n tagName: string,\n data: Partial<DraftEntity<T>> = {},\n params?: ListEntitiesByTagParams,\n ) => {\n const tagKey = getTagStateKey(\n entityType,\n tagName,\n params as Record<string, string>,\n );\n\n monoriseStore.setState(\n produce((state) => {\n const entity = state.tag[tagKey]?.dataMap?.get(entityId);\n if (entity) {\n state.tag[tagKey].dataMap.set(entityId, {\n ...entity,\n data: { ...entity.data, ...data },\n });\n }\n }),\n undefined,\n `mr/tag/local-update/${entityType}/${entityId}`,\n );\n };\n\n const deleteLocalTaggedEntity = <T extends Entity>(\n entityType: T,\n entityId: string,\n tagName: string,\n params?: ListEntitiesByTagParams,\n ) => {\n const tagKey = getTagStateKey(\n entityType,\n tagName,\n params as Record<string, string>,\n );\n\n monoriseStore.setState(\n produce((state) => {\n if (state.tag[tagKey]?.dataMap?.has(entityId)) {\n state.tag[tagKey].dataMap.delete(entityId);\n }\n }),\n undefined,\n `mr/tag/local-delete/${entityType}/${entityId}`,\n );\n };\n\n return {\n listMoreEntities,\n createEntity,\n upsertEntity,\n getEntity,\n editEntity,\n adjustEntity,\n deleteEntity,\n executeTransaction,\n getMutual,\n updateLocalEntity,\n createMutual,\n createLocalMutual,\n upsertLocalMutual,\n editMutual,\n deleteMutual,\n deleteLocalMutual,\n useEntity,\n useEntityByUniqueField,\n useEntities,\n useMutual,\n useMutuals,\n useTaggedEntities,\n useEntityState,\n updateLocalTaggedEntity,\n deleteLocalTaggedEntity,\n };\n};\n\nexport { initCoreActions };\n\nexport type CoreActions = ReturnType<typeof initCoreActions>;\n","import type { CreatedEntity, Entity, EntitySchemaMap } from '@monorise/base';\nimport type { Mutual, MutualData } from '../types/mutual.type';\n\nexport const constructLocal = (\n entityType: Entity,\n entityId: string,\n data: any,\n): CreatedEntity<Entity> => {\n return {\n entityType: entityType as unknown as string,\n entityId,\n data,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n};\n\nexport const constructMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n byEntityId: string,\n entityType: T,\n entityId: string,\n mutualData: Partial<MutualData<B, T>>,\n data: EntitySchemaMap[T],\n): Mutual => {\n return {\n mutualId: `${byEntityId}-${entityId}`,\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n mutualData,\n data,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n mutualUpdatedAt: new Date().toISOString(),\n };\n};\n\n// A mutual is stored under two cache keys — one per direction. When we mirror\n// a record from the `BY/byId/OTHER` side to the `OTHER/otherId/BY` side, the\n// `data` field has to be substituted: on the original side `data` describes\n// the OTHER entity (the one at `entityType/entityId`); after flipping, the\n// new `entityType/entityId` points to what *was* the BY entity, so `data`\n// must now describe that entity. Callers look up the BY entity from the\n// entity store and pass its data in here. `{}` is an accepted fallback for\n// the case where the BY entity hasn't been hydrated locally yet — better to\n// surface an empty record than to leak the OTHER entity's fields onto a\n// record that no longer describes it.\nexport const flipMutual = (\n mutual: Mutual,\n byEntityData: Record<string, unknown>,\n): Mutual => {\n return {\n ...mutual,\n entityId: mutual.byEntityId,\n entityType: mutual.byEntityType,\n byEntityId: mutual.entityId,\n byEntityType: mutual.entityType,\n data: byEntityData as Mutual['data'],\n };\n};\n\nexport const byMutualIndex = (a: Mutual<any, any>, b: Mutual<any, any>) => {\n return a.mutualData.index - b.mutualData.index;\n};\n\nexport const byEntityId = (a: CreatedEntity<any>, b: CreatedEntity<any>) => {\n if (b.entityId < a.entityId) return -1;\n return 1;\n};\n\nexport const constructOrderByIndex = (mutuals: Mutual<any, any>[]) => {\n return mutuals.sort(byMutualIndex).map((mutual) => mutual.entityId);\n};\n\nexport const injectFields = <T extends Entity>(\n entity: CreatedEntity<T> | undefined,\n fields: Record<string, any>,\n): CreatedEntity<T> | undefined => {\n return entity\n ? {\n ...entity,\n data: {\n ...entity.data,\n ...fields,\n },\n }\n : undefined;\n};\n","import type { Entity } from '@monorise/base';\n\nexport const convertToMap = <T extends Record<string, any>>(\n data: T[],\n mapKey: string,\n) => {\n const map = new Map();\n\n for (const i in data) {\n map.set(data[i][mapKey], data[i]);\n }\n\n return map;\n};\n\nexport const getMutualStateKey = (\n byEntity: Entity,\n byEntityId: string | null,\n entity: Entity,\n entityId?: string,\n chainEntityQuery?: string,\n) => {\n return `${byEntity}/${byEntityId}/${entity}${entityId ? `/${entityId}` : ''}${chainEntityQuery ? `?${chainEntityQuery}` : ''}`;\n};\n\n// inverse of getMutualStateKey — the chain query is stripped off first so that\n// it never leaks into the trailing path segment\nexport const parseMutualStateKey = (stateKey: string) => {\n const queryIndex = stateKey.indexOf('?');\n const path = queryIndex === -1 ? stateKey : stateKey.slice(0, queryIndex);\n const chainEntityQuery =\n queryIndex === -1 ? undefined : stateKey.slice(queryIndex + 1);\n const [byEntity, byEntityId, entity, entityId] = path.split('/');\n\n return {\n byEntity: byEntity as unknown as Entity,\n byEntityId,\n entity: entity as unknown as Entity,\n entityId,\n chainEntityQuery,\n };\n};\n\nexport const getTagStateKey = (\n entityType: Entity,\n tagName: string,\n params: Record<string, string> = {},\n) => {\n const { lastKey, ...stateParams } = params;\n\n const paramsKey = Object.keys(stateParams)\n .map((key) => `${key}:${stateParams[key]}`)\n .join('/');\n\n return `${entityType}/${tagName}/${paramsKey}`;\n};\n\nexport const getUniqueFieldStateKey = (\n fieldName: string,\n fieldValue: string,\n) => {\n return `${fieldName}/${fieldValue}`;\n};\n\nexport const getEntityRequestKey = (\n mode: 'create' | 'upsert' | 'edit' | 'adjust' | 'delete' | 'get' | 'list' | 'search',\n entityType: Entity,\n entityId?: string,\n) => {\n return `entity/${entityType}/${mode}${entityId ? `/${entityId}` : ''}`;\n};\n\nexport const getMutualRequestKey = (\n mode: 'create' | 'update' | 'delete' | 'get' | 'list',\n byEntityType: Entity,\n entityType: Entity,\n byEntityId: string | null,\n entityId?: string,\n chainEntityQuery?: string,\n) => {\n return `mutual/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId, chainEntityQuery)}/${mode}`;\n};\n\nexport const getTagRequestKey = (\n mode: 'list',\n entityType: Entity,\n tagName: string,\n params: Record<string, string> = {},\n) => {\n return `tag/${getTagStateKey(entityType, tagName, params)}/${mode}`;\n};\n\nexport const getUniqueFieldRequestKey = (\n entityType: Entity,\n fieldName: string,\n value: string,\n) => {\n return `entity/${entityType}/unique/${getUniqueFieldStateKey(fieldName, value)}`;\n};\n","import type { Entity, EntitySchemaMap } from '@monorise/base';\nimport { nanoid } from 'nanoid';\nimport { getEntityRequestKey, getMutualRequestKey } from '../lib/utils';\n\nexport type TransactionCreateEntity<T extends Entity = Entity> = {\n operation: 'createEntity';\n entityType: T;\n entityId?: string;\n payload: EntitySchemaMap[T];\n};\n\nexport type TransactionUpdateEntity<T extends Entity = Entity> = {\n operation: 'updateEntity';\n entityType: T;\n entityId: string;\n payload: Partial<EntitySchemaMap[T]>;\n condition?: string;\n};\n\nexport type TransactionAdjustEntity<T extends Entity = Entity> = {\n operation: 'adjustEntity';\n entityType: T;\n entityId: string;\n adjustments: Record<string, number>;\n condition?: string;\n};\n\nexport type TransactionDeleteEntity<T extends Entity = Entity> = {\n operation: 'deleteEntity';\n entityType: T;\n entityId: string;\n};\n\nexport type TransactionCreateMutual<\n B extends Entity = Entity,\n T extends Entity = Entity,\n> = {\n operation: 'createMutual';\n byEntityType: B;\n byEntityId: string;\n entityType: T;\n entityId: string;\n payload?: Record<string, unknown>;\n};\n\nexport type TransactionUpdateMutual<\n B extends Entity = Entity,\n T extends Entity = Entity,\n> = {\n operation: 'updateMutual';\n byEntityType: B;\n byEntityId: string;\n entityType: T;\n entityId: string;\n payload: Record<string, unknown>;\n};\n\nexport type TransactionDeleteMutual<\n B extends Entity = Entity,\n T extends Entity = Entity,\n> = {\n operation: 'deleteMutual';\n byEntityType: B;\n byEntityId: string;\n entityType: T;\n entityId: string;\n};\n\nexport type TransactionOperation =\n | TransactionCreateEntity\n | TransactionUpdateEntity\n | TransactionAdjustEntity\n | TransactionDeleteEntity\n | TransactionCreateMutual\n | TransactionUpdateMutual\n | TransactionDeleteMutual;\n\n// Mirrors packages/core/types/transaction.ts's TransactionResultEntry/Result —\n// the client can't import from @monorise/core (server-only, pulls in the AWS\n// SDK), so the response shape is duplicated here.\nexport type TransactionResultEntry<T extends Entity = Entity> = {\n operation: TransactionOperation['operation'];\n entityType: T;\n entityId: string;\n data?: Record<string, unknown>;\n createdAt?: string;\n updatedAt?: string;\n // createMutual / updateMutual / deleteMutual entries only.\n byEntityType?: Entity;\n byEntityId?: string;\n mutualId?: string;\n mutualData?: Record<string, unknown>;\n mutualUpdatedAt?: string;\n};\n\nexport type TransactionResult = {\n results: TransactionResultEntry[];\n};\n\n// The requestKey a single-entity call for this same op's target would have\n// used (getEntityRequestKey('edit'|'adjust'|'delete', entityType, entityId),\n// or ('create', entityType) for a create — which never includes an id, same\n// as createEntity's own key). Every op already carries a real entityId\n// except an id-less create, so this never needs to invent one.\nexport const getTransactionOperationRequestKey = (\n op: TransactionOperation,\n): string => {\n switch (op.operation) {\n case 'createEntity':\n return getEntityRequestKey('create', op.entityType);\n case 'updateEntity':\n return getEntityRequestKey('edit', op.entityType, op.entityId);\n case 'adjustEntity':\n return getEntityRequestKey('adjust', op.entityType, op.entityId);\n case 'deleteEntity':\n return getEntityRequestKey('delete', op.entityType, op.entityId);\n // Same keys the standalone createMutual / editMutual / deleteMutual calls\n // use, so a component watching one sees the transaction's loading/error.\n case 'createMutual':\n return getMutualRequestKey(\n 'create',\n op.byEntityType,\n op.entityType,\n op.byEntityId,\n );\n case 'updateMutual':\n return getMutualRequestKey(\n 'update',\n op.byEntityType,\n op.entityType,\n op.byEntityId,\n op.entityId,\n );\n case 'deleteMutual':\n return getMutualRequestKey(\n 'delete',\n op.byEntityType,\n op.entityType,\n op.byEntityId,\n op.entityId,\n );\n }\n};\n\n// The segment an op contributes to the call key. Same as its loading key,\n// except for createMutual: that key leaves out the target id (as the\n// standalone createMutual's does). Keep the target here so the descriptive\n// part of call keys still distinguishes transactions linking different\n// entities; the nonce below is what guarantees uniqueness between calls.\nconst getTransactionOperationCallSegment = (\n op: TransactionOperation,\n): string =>\n op.operation === 'createMutual'\n ? getMutualRequestKey(\n 'create',\n op.byEntityType,\n op.entityType,\n op.byEntityId,\n op.entityId,\n )\n : getTransactionOperationRequestKey(op);\n\n// The requestKey for the ONE real HTTP call `executeTransaction` makes.\n//\n// UNIQUE PER CALL, deliberately. lib/api.ts's `makeRequest` hands any caller\n// with a matching `requestKey` the in-flight promise instead of issuing a\n// second request, which is right for idempotent reads and for \"the user\n// double-clicked Save\" -- and wrong for a transaction, which is a batch of\n// NON-idempotent writes. A key derived only from the operation shapes is\n// identical for every structurally identical batch, so two writes issued\n// close together (scoring twice with the same statistic, appending two events\n// to one log) silently collapse into one: the second caller awaits the first\n// call's promise, is told it succeeded, and its operations are never sent.\n//\n// Found end-to-end -- three scores recorded, one observed.\n//\n// The operation shapes stay in the key for debuggability, and the\n// `transaction/` namespace still keeps it from colliding with a\n// single-entity action's own key. A caller that genuinely wants dedupe can\n// still pass an explicit `opts.requestKey`.\nexport const createTransactionCallRequestKey = (\n operations: TransactionOperation[],\n): string =>\n `transaction/${operations.map(getTransactionOperationCallSegment).join('|')}#${nanoid()}`;\n\n// NOTE: packages/core/helpers/transactional.ts is the server-side copy of\n// this builder. Both emit the same wire format for the execute-transaction\n// endpoint — keep operation shapes in sync when changing either file.\nexport const transactional = {\n createEntity: <T extends Entity>(\n entityType: T,\n payload: EntitySchemaMap[T] & { entityId?: string },\n ): TransactionCreateEntity<T> => {\n const { entityId, ...rest } = payload as EntitySchemaMap[T] & {\n entityId?: string;\n };\n return {\n operation: 'createEntity',\n entityType,\n payload: rest as EntitySchemaMap[T],\n ...(entityId !== undefined && { entityId }),\n };\n },\n\n updateEntity: <T extends Entity>(\n entityType: T,\n entityId: string,\n payload: Partial<EntitySchemaMap[T]> & { $condition?: string },\n ): TransactionUpdateEntity<T> => {\n const { $condition, ...rest } = payload as Partial<EntitySchemaMap[T]> & {\n $condition?: string;\n };\n return {\n operation: 'updateEntity',\n entityType,\n entityId,\n payload: rest as Partial<EntitySchemaMap[T]>,\n ...($condition !== undefined && { condition: $condition }),\n };\n },\n\n adjustEntity: <T extends Entity>(\n entityType: T,\n entityId: string,\n adjustments: Record<string, number> & { $condition?: string },\n ): TransactionAdjustEntity<T> => {\n const { $condition, ...rest } = adjustments;\n return {\n operation: 'adjustEntity',\n entityType,\n entityId,\n adjustments: rest,\n ...($condition !== undefined && { condition: $condition }),\n };\n },\n\n deleteEntity: <T extends Entity>(\n entityType: T,\n entityId: string,\n ): TransactionDeleteEntity<T> => ({\n operation: 'deleteEntity',\n entityType,\n entityId,\n }),\n\n // Same argument order as the standalone createMutual / editMutual /\n // deleteMutual actions.\n createMutual: <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload?: Record<string, unknown>,\n ): TransactionCreateMutual<B, T> => ({\n operation: 'createMutual',\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n ...(payload !== undefined && { payload }),\n }),\n\n updateMutual: <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload: Record<string, unknown>,\n ): TransactionUpdateMutual<B, T> => ({\n operation: 'updateMutual',\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n payload,\n }),\n\n deleteMutual: <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n ): TransactionDeleteMutual<B, T> => ({\n operation: 'deleteMutual',\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n }),\n};\n","import type { CreatedEntity, Entity } from '@monorise/base';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { produce } from 'immer';\nimport { parseMutualStateKey } from '../lib/utils';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type {\n ConnectionState,\n ServerMessage,\n WebSocketManager,\n} from '../websocket';\n\nexport interface UseEntitySocketReturn<T extends Entity> {\n entities: CreatedEntity<T>[];\n isLoading: boolean;\n isFetchingMore: boolean;\n isSubscribed: boolean;\n error: Error | null;\n isRefreshing: boolean;\n fetchMore: () => Promise<void>;\n hasMore: boolean;\n}\n\nexport interface UseMutualSocketReturn<T extends Entity> {\n mutuals: unknown[];\n isLoading: boolean;\n isFetchingMore: boolean;\n isSubscribed: boolean;\n error: Error | null;\n isRefreshing: boolean;\n fetchMore: () => Promise<void>;\n hasMore: boolean;\n}\n\nexport interface UseEntityFeedOptions {\n entityType: Entity;\n entityId: string;\n ticketEndpoint?: string;\n}\n\nexport interface UseEntityFeedReturn {\n isConnected: boolean;\n error: { code: string; message: string } | null;\n}\n\nlet globalWsManager: WebSocketManager | null = null;\nlet wsEndpoint: string | undefined;\n\nexport const initializeWebSocketManager = (\n WebSocketManagerClass: typeof WebSocketManager,\n endpoint: string,\n token?: string,\n) => {\n if (globalWsManager) return globalWsManager;\n\n wsEndpoint = endpoint;\n globalWsManager = new WebSocketManagerClass(endpoint, token || '');\n globalWsManager.connect();\n\n return globalWsManager;\n};\n\nexport const getWebSocketManager = () => globalWsManager;\n\nexport const initWebSocketActions = (\n monoriseStore: MonoriseStore,\n httpActions?: {\n listEntities: <T extends Entity>(\n entityType: T,\n params?: { limit?: number; lastKey?: string },\n ) => Promise<{ data: CreatedEntity<T>[]; lastKey?: string }>;\n listEntitiesByEntity: <B extends Entity, T extends Entity>(\n byEntityType: B,\n byEntityId: string,\n entityType: T,\n params?: { limit?: number; lastKey?: string },\n ) => Promise<{ entities: unknown[]; lastKey?: string }>;\n },\n) => {\n const useEntitySocket = <T extends Entity>(\n entityType: T,\n opts: { limit?: number; skipInitialFetch?: boolean } = {},\n ): UseEntitySocketReturn<T> => {\n const { limit = 20, skipInitialFetch = false } = opts;\n const [isLoading, setIsLoading] = useState(!skipInitialFetch);\n const [isFetchingMore, setIsFetchingMore] = useState(false);\n const [isRefreshing, setIsRefreshing] = useState(false);\n const [isSubscribed, setIsSubscribed] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [hasMore, setHasMore] = useState(true);\n const lastKeyRef = useRef<string | undefined>(undefined);\n const isFirstFetchRef = useRef(true);\n\n const entities = monoriseStore((state) => {\n const entityState = state.entity[entityType];\n return Array.from(entityState?.dataMap?.values() || []);\n });\n\n const fetchData = async (type: 'initial' | 'more' | 'refresh') => {\n if (!httpActions) return;\n if (type === 'more') {\n setIsFetchingMore(true);\n } else if (type === 'refresh') {\n setIsRefreshing(true);\n } else {\n setIsLoading(true);\n }\n setError(null);\n\n try {\n const fetchLastKey = type === 'refresh' ? undefined : lastKeyRef.current;\n const result = await httpActions.listEntities(entityType, {\n limit,\n lastKey: fetchLastKey,\n });\n\n monoriseStore.setState(\n produce((state) => {\n if (type === 'refresh') {\n state.entity[entityType as unknown as string].dataMap.clear();\n }\n for (const entity of result.data) {\n state.entity[entityType as unknown as string].dataMap.set(entity.entityId, entity);\n }\n state.entity[entityType as unknown as string].isFirstFetched = true;\n state.entity[entityType as unknown as string].lastKey = result.lastKey;\n }),\n );\n\n lastKeyRef.current = result.lastKey;\n setHasMore(!!result.lastKey);\n } catch (err) {\n setError(err instanceof Error ? err : new Error('Failed to fetch'));\n } finally {\n setIsLoading(false);\n setIsFetchingMore(false);\n setIsRefreshing(false);\n }\n };\n\n useEffect(() => {\n if (skipInitialFetch) return;\n fetchData('initial');\n }, [entityType, limit, skipInitialFetch]);\n\n useEffect(() => {\n if (!globalWsManager) {\n setIsSubscribed(false);\n return;\n }\n\n const subKey = globalWsManager.subscribeEntityType(entityType as unknown as string);\n setIsSubscribed(true);\n\n let wasConnected = false;\n const unsubscribeState = globalWsManager.onStateChange((state) => {\n if (state === 'connected' && wasConnected === false && !isFirstFetchRef.current) {\n fetchData('refresh');\n }\n wasConnected = state === 'connected';\n isFirstFetchRef.current = false;\n });\n\n const unsubscribeMessage = globalWsManager.onMessage(\n (msg: ServerMessage) => {\n if (\n msg.type === 'entity.created' ||\n msg.type === 'entity.updated' ||\n msg.type === 'entity.deleted'\n ) {\n const payload = msg.payload as {\n entityType: string;\n entityId: string;\n data?: CreatedEntity<T>;\n };\n\n if (payload.entityType !== (entityType as unknown as string)) return;\n\n if (msg.type === 'entity.created' || msg.type === 'entity.updated') {\n if (payload.data) {\n monoriseStore.setState(\n produce((state) => {\n const key = entityType as unknown as string;\n if (!state.entity[key]) {\n state.entity[key] = { dataMap: new Map(), isFirstFetched: false, lastKey: undefined };\n }\n state.entity[key].dataMap.set(\n payload.entityId,\n payload.data!,\n );\n }),\n );\n }\n } else if (msg.type === 'entity.deleted') {\n monoriseStore.setState(\n produce((state) => {\n const key = entityType as unknown as string;\n if (state.entity[key]?.dataMap) {\n state.entity[key].dataMap.delete(payload.entityId);\n }\n }),\n );\n }\n }\n },\n );\n\n return () => {\n globalWsManager?.unsubscribeEntityType(subKey);\n unsubscribeState();\n unsubscribeMessage();\n setIsSubscribed(false);\n };\n }, [entityType]);\n\n const fetchMore = async () => {\n if (!hasMore || isFetchingMore) return;\n await fetchData('more');\n };\n\n return {\n entities,\n isLoading,\n isFetchingMore,\n isSubscribed,\n error,\n isRefreshing,\n fetchMore,\n hasMore,\n };\n };\n\n const useMutualSocket = <B extends Entity, T extends Entity>(\n byEntityType: B,\n byEntityId: string | undefined,\n mutualEntityType: T,\n opts: { limit?: number; skipInitialFetch?: boolean } = {},\n ): UseMutualSocketReturn<T> => {\n const { limit = 20, skipInitialFetch = false } = opts;\n const [isLoading, setIsLoading] = useState(\n !skipInitialFetch && !!byEntityId,\n );\n const [isFetchingMore, setIsFetchingMore] = useState(false);\n const [isRefreshing, setIsRefreshing] = useState(false);\n const [isSubscribed, setIsSubscribed] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [hasMore, setHasMore] = useState(true);\n const lastKeyRef = useRef<string | undefined>(undefined);\n const isFirstFetchRef = useRef(true);\n\n const mutualKey = byEntityId\n ? `${byEntityType}/${byEntityId}/${mutualEntityType}`\n : '';\n\n const mutuals = monoriseStore((state) => {\n return Array.from(state.mutual[mutualKey]?.dataMap?.values() || []);\n });\n\n const fetchData = async (type: 'initial' | 'more' | 'refresh') => {\n if (!byEntityId || !httpActions) return;\n\n if (type === 'more') {\n setIsFetchingMore(true);\n } else if (type === 'refresh') {\n setIsRefreshing(true);\n } else {\n setIsLoading(true);\n }\n setError(null);\n\n try {\n const fetchLastKey = type === 'refresh' ? undefined : lastKeyRef.current;\n const result = await httpActions.listEntitiesByEntity(\n byEntityType,\n byEntityId,\n mutualEntityType,\n { limit, lastKey: fetchLastKey },\n );\n\n monoriseStore.setState(\n produce((state) => {\n if (!state.mutual[mutualKey]) {\n state.mutual[mutualKey] = {\n dataMap: new Map(),\n isFirstFetched: true,\n lastKey: undefined as unknown as string,\n };\n }\n if (type === 'refresh') {\n state.mutual[mutualKey].dataMap.clear();\n }\n for (const entity of result.entities) {\n const e = entity as any;\n state.mutual[mutualKey].dataMap.set(e.entityId, entity);\n }\n state.mutual[mutualKey].lastKey = result.lastKey;\n }),\n );\n\n lastKeyRef.current = result.lastKey;\n setHasMore(!!result.lastKey);\n } catch (err) {\n setError(err instanceof Error ? err : new Error('Failed to fetch'));\n } finally {\n setIsLoading(false);\n setIsFetchingMore(false);\n setIsRefreshing(false);\n }\n };\n\n useEffect(() => {\n if (skipInitialFetch || !byEntityId) {\n setIsLoading(false);\n return;\n }\n lastKeyRef.current = undefined;\n setHasMore(true);\n isFirstFetchRef.current = true;\n fetchData('initial');\n }, [byEntityType, byEntityId, mutualEntityType, limit, skipInitialFetch]);\n\n useEffect(() => {\n if (!globalWsManager || !byEntityId) {\n setIsSubscribed(false);\n return;\n }\n\n const subKey = globalWsManager.subscribeMutualType(\n byEntityType as unknown as string,\n byEntityId,\n mutualEntityType as unknown as string,\n );\n setIsSubscribed(true);\n\n let wasConnected = false;\n const unsubscribeState = globalWsManager.onStateChange((state) => {\n if (state === 'connected' && wasConnected === false && !isFirstFetchRef.current) {\n fetchData('refresh');\n }\n wasConnected = state === 'connected';\n isFirstFetchRef.current = false;\n });\n\n const unsubscribeMessage = globalWsManager.onMessage(\n (msg: ServerMessage) => {\n if (\n msg.type === 'mutual.created' ||\n msg.type === 'mutual.updated' ||\n msg.type === 'mutual.deleted'\n ) {\n const payload = msg.payload as {\n byEntityType: string;\n byEntityId: string;\n mutualEntityType: string;\n entityId: string;\n data?: unknown;\n };\n\n if (\n payload.byEntityType !== (byEntityType as unknown as string) ||\n payload.byEntityId !== byEntityId ||\n payload.mutualEntityType !== (mutualEntityType as unknown as string)\n ) {\n return;\n }\n\n if (\n msg.type === 'mutual.created' ||\n msg.type === 'mutual.updated'\n ) {\n if (payload.data) {\n monoriseStore.setState(\n produce((state) => {\n if (!state.mutual[mutualKey]) {\n state.mutual[mutualKey] = {\n dataMap: new Map(),\n isFirstFetched: true,\n lastKey: undefined as unknown as string,\n };\n }\n state.mutual[mutualKey].dataMap.set(\n payload.entityId,\n payload.data!,\n );\n }),\n );\n }\n } else if (msg.type === 'mutual.deleted') {\n monoriseStore.setState(\n produce((state) => {\n state.mutual[mutualKey]?.dataMap.delete(payload.entityId);\n }),\n );\n }\n }\n },\n );\n\n return () => {\n globalWsManager?.unsubscribeMutualType(subKey);\n unsubscribeState();\n unsubscribeMessage();\n setIsSubscribed(false);\n };\n }, [byEntityType, byEntityId, mutualEntityType, mutualKey]);\n\n const fetchMore = async () => {\n if (!hasMore || isFetchingMore) return;\n await fetchData('more');\n };\n\n return {\n mutuals,\n isLoading,\n isFetchingMore,\n isSubscribed,\n error,\n isRefreshing,\n fetchMore,\n hasMore,\n };\n };\n\n const useEphemeralSocket = <T = unknown>(\n channel: string | undefined,\n opts?: {\n onMessage?: (data: T, senderId?: string) => void;\n },\n ): {\n isSubscribed: boolean;\n send: (data: T) => void;\n } => {\n const [isSubscribed, setIsSubscribed] = useState(false);\n\n useEffect(() => {\n if (!globalWsManager || !channel) {\n setIsSubscribed(false);\n return;\n }\n\n const subKey = globalWsManager.subscribeEphemeral(channel);\n setIsSubscribed(true);\n\n const unsubscribeMessage = globalWsManager.onMessage(\n (msg: ServerMessage) => {\n if (msg.type === 'ephemeral') {\n const payload = msg.payload as {\n channel: string;\n data: T;\n senderId?: string;\n };\n if (payload.channel !== channel) return;\n opts?.onMessage?.(payload.data, payload.senderId);\n }\n },\n );\n\n return () => {\n globalWsManager?.unsubscribeEphemeral(subKey);\n unsubscribeMessage();\n setIsSubscribed(false);\n };\n }, [channel]);\n\n const send = useCallback(\n (data: T) => {\n if (!globalWsManager || !channel) return;\n globalWsManager.sendEphemeral(channel, data);\n },\n [channel],\n );\n\n return { isSubscribed, send };\n };\n\n /**\n * Subscribe to an entity's real-time feed.\n *\n * Fetches a ticket (via ticketEndpoint or default monorise route through catch-all proxy),\n * establishes a WebSocket connection, and auto-updates entity/mutual stores.\n * Handles ticket refresh and auto-resync on reconnect.\n *\n * @example\n * ```tsx\n * // Internal app (uses catch-all proxy)\n * useEntityFeed({ entityType: Entity.USER, entityId: userId });\n *\n * // Client-facing app (custom auth endpoint)\n * useEntityFeed({ entityType: Entity.USER, entityId: userId, ticketEndpoint: '/api/ws/ticket' });\n * ```\n */\n const useEntityFeed = (opts: UseEntityFeedOptions): UseEntityFeedReturn => {\n const { entityType, entityId, ticketEndpoint } = opts;\n const [isConnected, setIsConnected] = useState(false);\n const [error, setError] = useState<{ code: string; message: string } | null>(null);\n const refreshTimerRef = useRef<NodeJS.Timeout | null>(null);\n const hasConnectedOnceRef = useRef(false);\n\n /**\n * Refill the mutual lists this feed's subject already has loaded.\n *\n * Deliberately only refetches slices that were fetched before\n * (`isFirstFetched`): a reconnect should close gaps in what the caller is\n * already showing, not start pulling lists nobody asked for. Single-mutual\n * entries (those with a trailing entityId) are skipped -- they are one row,\n * not a paginated list.\n */\n const resyncFromHttp = async () => {\n if (!httpActions) return;\n const snapshot = monoriseStore.getState();\n const keys = Object.keys(snapshot.mutual ?? {});\n\n for (const key of keys) {\n const parsed = parseMutualStateKey(key);\n if (parsed.entityId) continue;\n if (parsed.byEntityId !== entityId) continue;\n if (!snapshot.mutual[key]?.isFirstFetched) continue;\n\n try {\n const result = await httpActions.listEntitiesByEntity(\n parsed.byEntity,\n parsed.byEntityId as string,\n parsed.entity,\n );\n if (!isMountedRef.current) return;\n monoriseStore.setState(\n produce((draft) => {\n const slice = draft.mutual[key];\n if (!slice) return;\n slice.dataMap.clear();\n for (const mutual of result.entities as {\n entityId: string;\n }[]) {\n slice.dataMap.set(mutual.entityId, mutual);\n }\n slice.lastKey = result.lastKey;\n }),\n );\n } catch {\n // A failed refill leaves the existing rows in place, which is the\n // safer of the two wrong answers.\n }\n }\n };\n const wsManagerRef = useRef<WebSocketManager | null>(null);\n const isMountedRef = useRef(true);\n const connectingRef = useRef(false);\n const reconnectCountRef = useRef(0);\n const connectRef = useRef<() => void>(() => {});\n const lastConnectedAtRef = useRef(0);\n\n const fetchTicket = useCallback(async () => {\n try {\n const url = ticketEndpoint\n || `/api/core/ws/ticket/${entityType}/${entityId}`;\n\n const fetchOpts: RequestInit = {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n };\n\n // Only send body for custom endpoints (default route gets params from URL)\n if (ticketEndpoint) {\n fetchOpts.body = JSON.stringify({ entityType, entityId });\n }\n\n const response = await fetch(url, fetchOpts);\n\n if (response.status === 401 || response.status === 403) {\n return { error: { code: 'TICKET_UNAUTHORIZED', message: 'Unauthorized' } };\n }\n\n if (!response.ok) {\n return { error: { code: 'TICKET_FAILED', message: `HTTP ${response.status}` } };\n }\n\n const data = await response.json();\n return { data: data as { ticket: string; wsUrl: string; expiresIn: number } };\n } catch (err) {\n return { error: { code: 'TICKET_FAILED', message: (err as Error).message } };\n }\n }, [entityType, entityId, ticketEndpoint]);\n\n const connectWithTicket = useCallback(async () => {\n if (connectingRef.current) return;\n connectingRef.current = true;\n\n // Retry ticket fetch with backoff\n let result: Awaited<ReturnType<typeof fetchTicket>> | null = null;\n const maxRetries = 3;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n result = await fetchTicket();\n\n if (!isMountedRef.current) {\n connectingRef.current = false;\n return;\n }\n\n if (!result.error) break;\n\n // Don't retry auth errors\n if (result.error.code === 'TICKET_UNAUTHORIZED') break;\n\n if (attempt < maxRetries) {\n await new Promise((r) => setTimeout(r, 1000 * Math.pow(2, attempt)));\n if (!isMountedRef.current) {\n connectingRef.current = false;\n return;\n }\n }\n }\n\n if (result!.error) {\n setError(result!.error);\n setIsConnected(false);\n connectingRef.current = false;\n return;\n }\n\n setError(null);\n const { ticket, wsUrl, expiresIn } = result!.data!;\n // Disconnect existing connection\n if (wsManagerRef.current) {\n wsManagerRef.current.disconnect();\n }\n\n const { WebSocketManager: WsManagerClass } = await import('../websocket');\n\n const wsUrlWithTicket = `${wsUrl}?ticket=${encodeURIComponent(ticket)}`;\n const manager = new WsManagerClass(wsUrlWithTicket, '');\n manager.disableAutoReconnect = true;\n // Deliberately NOT assigned to `globalWsManager`. That global is the\n // shared socket behind `useEntitySocket`/`useMutualSocket` and the public\n // `getWebSocketManager()`. This one is a different connection: ticket\n // -scoped, feed-only, with auto-reconnect disabled. Pointing the shared\n // accessor at it makes those hooks subscribe on the wrong socket while\n // this hook is mounted, and leaves them holding a disconnected manager\n // after it unmounts, since cleanup only clears the local ref.\n wsManagerRef.current = manager;\n\n manager.onStateChange((state: ConnectionState) => {\n if (!isMountedRef.current) return;\n // Ignore events from old managers (stale callbacks)\n if (wsManagerRef.current !== manager) return;\n\n if (state === 'connected') {\n connectingRef.current = false;\n reconnectCountRef.current = 0;\n lastConnectedAtRef.current = Date.now();\n setIsConnected(true);\n setError(null);\n\n // Broadcasts sent while the socket was down are gone -- the server\n // does not replay them -- so a reconnect has to refill from HTTP or\n // the stores silently keep stale rows. Skipped on the FIRST connect,\n // where whatever loaded the list has already fetched it.\n if (hasConnectedOnceRef.current) {\n void resyncFromHttp();\n }\n hasConnectedOnceRef.current = true;\n } else if (state === 'disconnected') {\n connectingRef.current = false;\n setIsConnected(false);\n\n // Only auto-reconnect if we were connected for >5s (stable connection)\n // and haven't exceeded max reconnect attempts\n // `hasConnectedOnceRef` is load-bearing here, not belt-and-braces:\n // `lastConnectedAtRef` starts at 0, so `Date.now() - 0` is ~1.8e12\n // and the >5s test passes for a socket that never opened -- burning\n // all five reconnect attempts on exactly the first-connect failure\n // this guard exists to suppress.\n const wasStable =\n hasConnectedOnceRef.current &&\n Date.now() - lastConnectedAtRef.current > 5000;\n if (wasStable && reconnectCountRef.current < 5) {\n reconnectCountRef.current++;\n const delay = 2000 * Math.pow(2, reconnectCountRef.current - 1);\n setTimeout(() => {\n if (isMountedRef.current && !connectingRef.current) {\n connectRef.current();\n }\n }, delay);\n }\n }\n });\n\n // Route feed messages into stores\n manager.onMessage((msg: ServerMessage) => {\n if (!isMountedRef.current) return;\n\n if (msg.type === 'entity.created' || msg.type === 'entity.updated') {\n const payload = msg.payload as {\n entityType: string;\n entityId: string;\n data?: any;\n };\n if (payload.data) {\n monoriseStore.setState(\n produce((state) => {\n const key = payload.entityType;\n if (!state.entity[key]) {\n state.entity[key] = { dataMap: new Map(), isFirstFetched: false, lastKey: undefined };\n }\n state.entity[key].dataMap.set(payload.entityId, payload.data);\n }),\n );\n }\n } else if (msg.type === 'entity.deleted') {\n const payload = msg.payload as { entityType: string; entityId: string };\n monoriseStore.setState(\n produce((state) => {\n state.entity[payload.entityType]?.dataMap?.delete(payload.entityId);\n }),\n );\n } else if (msg.type === 'mutual.created' || msg.type === 'mutual.updated') {\n const payload = msg.payload as {\n byEntityType: string;\n byEntityId: string;\n mutualEntityType: string;\n entityId: string;\n data?: any;\n };\n if (payload.data) {\n const mutualKey = `${payload.byEntityType}/${payload.byEntityId}/${payload.mutualEntityType}`;\n monoriseStore.setState(\n produce((state) => {\n if (!state.mutual[mutualKey]) {\n state.mutual[mutualKey] = { dataMap: new Map(), isFirstFetched: false, lastKey: undefined };\n }\n state.mutual[mutualKey].dataMap.set(payload.entityId, payload.data);\n }),\n );\n }\n } else if (msg.type === 'mutual.deleted') {\n const payload = msg.payload as {\n byEntityType: string;\n byEntityId: string;\n mutualEntityType: string;\n entityId: string;\n };\n const mutualKey = `${payload.byEntityType}/${payload.byEntityId}/${payload.mutualEntityType}`;\n monoriseStore.setState(\n produce((state) => {\n state.mutual[mutualKey]?.dataMap?.delete(payload.entityId);\n }),\n );\n }\n });\n\n manager.connect();\n\n // Schedule proactive ticket refresh\n if (refreshTimerRef.current) {\n clearTimeout(refreshTimerRef.current);\n }\n const refreshMs = Math.max((expiresIn - 120) * 1000, 60000); // refresh 2 min before expiry, minimum 1 min\n refreshTimerRef.current = setTimeout(() => {\n if (isMountedRef.current) {\n connectRef.current();\n }\n }, refreshMs);\n }, [fetchTicket]);\n\n connectRef.current = connectWithTicket;\n\n useEffect(() => {\n isMountedRef.current = true;\n\n if (entityId) {\n connectRef.current();\n }\n\n // Detect wake from sleep using periodic check\n let lastCheckTime = Date.now();\n const sleepCheckInterval = setInterval(() => {\n const now = Date.now();\n const elapsed = now - lastCheckTime;\n lastCheckTime = now;\n\n if (elapsed > 30000 && wsManagerRef.current) {\n wsManagerRef.current.disconnect();\n wsManagerRef.current = null;\n connectingRef.current = false;\n reconnectCountRef.current = 0;\n connectRef.current();\n }\n }, 5000);\n\n // Reconnect when network comes back online\n const handleOnline = () => {\n if (!isMountedRef.current) return;\n if (wsManagerRef.current?.getState() === 'connected') return;\n if (connectingRef.current) return;\n reconnectCountRef.current = 0;\n connectRef.current();\n };\n window.addEventListener('online', handleOnline);\n\n return () => {\n isMountedRef.current = false;\n clearInterval(sleepCheckInterval);\n window.removeEventListener('online', handleOnline);\n if (refreshTimerRef.current) {\n clearTimeout(refreshTimerRef.current);\n }\n if (wsManagerRef.current) {\n wsManagerRef.current.disconnect();\n wsManagerRef.current = null;\n }\n };\n }, [entityType, entityId]);\n\n return { isConnected, error };\n };\n\n return {\n useEntitySocket,\n useMutualSocket,\n useEphemeralSocket,\n useEntityFeed,\n };\n};\n\nexport type WebSocketActions = ReturnType<typeof initWebSocketActions>;\n","import request, {\n type AxiosError,\n type AxiosRequestConfig,\n type AxiosResponse,\n} from 'axios';\nimport type { AppActions } from '../actions/app.action';\nimport type { AuthActions } from '../actions/auth.action';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type { ApplicationRequestError } from '../types/api.type';\n\ntype IntercepterAxiosRequestConfig<D> = AxiosRequestConfig<D> & {\n requestKey: string;\n isInterruptive?: boolean;\n feedback?: {\n loading?: string | boolean;\n success?: ((data: any) => string) | string | boolean;\n failure?: string | boolean;\n };\n};\n\nconst initAxiosInterceptor = (store: MonoriseStore, appActions: AppActions) => {\n const { startLoading } = appActions;\n\n const axiosInstance = request.create();\n\n function makeRequest<T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n config: AxiosRequestConfig<D>,\n data?: D,\n ): Promise<R> {\n const { requestKey, isInterruptive = false, feedback } = config;\n const { ongoingRequests } = store.getState().app;\n\n if (ongoingRequests.has(requestKey)) {\n return ongoingRequests.get(requestKey) as Promise<R>;\n }\n\n const promise = axiosInstance.request<T, R, D>({\n ...config,\n url,\n data,\n headers: {\n ...(config.headers || {}),\n 'Mr-Interruptive': String(isInterruptive),\n },\n });\n startLoading({\n requestKey,\n isInterruptive,\n message: feedback?.loading,\n request: promise,\n });\n\n return promise;\n }\n\n const axios = {\n ...axiosInstance,\n post: <T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n data: D,\n config: IntercepterAxiosRequestConfig<D>,\n ): Promise<R> => makeRequest(url, { ...config, method: 'POST' }, data),\n put: <T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n data: D,\n config: IntercepterAxiosRequestConfig<D>,\n ): Promise<R> => makeRequest(url, { ...config, method: 'PUT' }, data),\n patch: <T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n data: D,\n config: IntercepterAxiosRequestConfig<D>,\n ): Promise<R> => makeRequest(url, { ...config, method: 'PATCH' }, data),\n delete: <T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n config: IntercepterAxiosRequestConfig<D>,\n ): Promise<R> => makeRequest(url, { ...config, method: 'DELETE' }),\n get: <T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n config: IntercepterAxiosRequestConfig<D>,\n ): Promise<R> => makeRequest(url, { ...config, method: 'GET' }),\n };\n\n return axios;\n};\n\ntype ConfigOptions = {\n onApiSuccess?: <T>(\n response: AxiosResponse<T>,\n feedbackSuccess:\n | ((data: AxiosResponse<T>['data']) => React.ReactNode)\n | string\n | boolean,\n ) => void;\n};\n\nconst injectAxiosInterceptor = (\n appActions: AppActions,\n authActions: AuthActions,\n axios: ReturnType<typeof initAxiosInterceptor>,\n opts?: ConfigOptions,\n) => {\n let options: ConfigOptions = opts || {};\n const { endLoading, setError, clearError } = appActions;\n const { setIsUnauthorized } = authActions;\n\n const unknownError: ApplicationRequestError = {\n status: 500,\n code: 'UNKNOWN_EXCEPTION',\n message: \"Ops, something doesn't seems right\",\n };\n\n axios.interceptors.response.use(\n (response) => {\n const { requestKey, isInterruptive, feedback } = response.config;\n endLoading({ requestKey, isInterruptive });\n clearError(requestKey);\n\n if (feedback?.success) {\n options.onApiSuccess?.(response, feedback.success);\n }\n // switch (typeof feedback.success) {\n // case 'function':\n // toast(feedback.success(response.data));\n // break;\n // case 'string':\n // toast(\n // <Fragment>\n // <IconCircleCheckFilled color='rgb(34 197 94)' />\n // {feedback.success}\n // </Fragment>,\n // );\n // break;\n // case 'boolean':\n // toast('Request success');\n // break;\n // }\n\n return Promise.resolve(response);\n },\n (error: AxiosError<string>) => {\n const { requestKey, isInterruptive } = error.config as AxiosRequestConfig;\n endLoading({ requestKey, isInterruptive });\n\n const appError = error.response?.data\n ? {\n code: error.response?.statusText,\n status: error.response?.status,\n message: error.response?.data,\n }\n : unknownError;\n setError({ requestKey, error: appError });\n if (error.response?.status === 401) {\n setIsUnauthorized(true);\n }\n return Promise.reject(error);\n },\n );\n\n const setOptions = (opts: ConfigOptions) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return { setOptions };\n};\n\nexport { initAxiosInterceptor, injectAxiosInterceptor };\n","import type { Entity } from '@monorise/base';\nimport type { AxiosInterceptor } from '../types/api.type';\n\ntype LoginPayload = {\n email: string;\n};\n\ntype Options = {\n apiBaseUrl?: string;\n};\n\nconst initAuthService = (axios: AxiosInterceptor) => {\n let options: Options = {};\n const { apiBaseUrl = '/api/auth' } = options;\n\n const requestLoginMagicLink = (entityType: Entity, payload: LoginPayload) => {\n return axios.post(\n `${apiBaseUrl}/${entityType}`,\n {\n body: { ...payload },\n },\n {\n requestKey: `auth/${entityType}/request-login`,\n isInterruptive: true,\n feedback: {\n loading: 'Requesting login link',\n },\n },\n );\n };\n\n const getSessionProfile = <T extends Record<string, unknown>>() =>\n axios.get<\n T & {\n displayName: string;\n email: string;\n accountId: string;\n }\n >('/session', {\n requestKey: 'auth/session',\n });\n\n const logout = () =>\n axios.get('/logout', {\n requestKey: 'auth/logout',\n });\n\n const setOptions = (opts: Options) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return {\n requestLoginMagicLink,\n getSessionProfile,\n logout,\n setOptions,\n };\n};\n\nexport default initAuthService;\n\nexport type AuthService = ReturnType<typeof initAuthService>;\n","import type { CreatedEntity, DraftEntity, Entity } from '@monorise/base';\nimport type { AxiosRequestConfig } from 'axios';\nimport {\n type TransactionOperation,\n type TransactionResult,\n createTransactionCallRequestKey,\n} from '../helpers/transactional';\nimport {\n getEntityRequestKey,\n getMutualRequestKey,\n getMutualStateKey,\n getTagRequestKey,\n getUniqueFieldRequestKey,\n getUniqueFieldStateKey,\n} from '../lib/utils';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type {\n ApplicationRequestError,\n AxiosInterceptor,\n} from '../types/api.type';\nimport type { Mutual, MutualData } from '../types/mutual.type';\n\nconst ENTITY_API_BASE_URL = '/api/core/entity';\nconst MUTUAL_API_BASE_URL = '/api/core/mutual';\nconst TAG_API_BASE_URL = '/api/core/tag';\nconst TRANSACTION_API_BASE_URL = '/api/core/transaction';\n\ntype ListEntitiesPayload = {\n limit?: number;\n lastKey?: string;\n start?: string;\n end?: string;\n};\n\nexport type ListEntitiesByTagParams = {\n group?: string;\n query?: string;\n start?: string;\n end?: string;\n limit?: number;\n lastKey?: string;\n};\n\ntype ConfigOptions = {\n entityApiBaseUrl?: string;\n mutualApiBaseUrl?: string;\n tagApiBaseUrl?: string;\n};\n\nexport type CommonOptions = Partial<AxiosRequestConfig> & {\n customUrl?: string;\n isInterruptive?: boolean;\n feedback?: {\n success?: string;\n failure?: string;\n loading?: string;\n };\n stateKey?: string;\n forceFetch?: boolean;\n noData?: boolean;\n limit?: number;\n requestKey?: string;\n onError?: (error: ApplicationRequestError | Error) => void;\n entityId?: string;\n};\n\nconst initCoreService = (\n monoriseStore: MonoriseStore,\n axios: AxiosInterceptor,\n opts?: ConfigOptions,\n) => {\n let options: ConfigOptions = opts || {};\n\n const listEntities = <T extends Entity>(\n entityType: T,\n payload?: ListEntitiesPayload,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n return axios.get<{\n data: CreatedEntity<T>[];\n lastKey?: string;\n totalCount: number;\n }>(opts.customUrl || `${entityApiBaseUrl}/${entityType}`, {\n requestKey: getEntityRequestKey('list', entityType),\n params: payload ?? undefined,\n isInterruptive: opts.isInterruptive,\n feedback: opts.feedback,\n });\n };\n\n const searchEntities = <T extends Entity>(\n entityType: T,\n query: string,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n return axios.get<{ data: CreatedEntity<T>[] }>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}`,\n {\n requestKey: getEntityRequestKey('search', entityType),\n params: { query },\n isInterruptive: opts.isInterruptive,\n feedback: opts.feedback,\n },\n );\n };\n\n const listEntitiesByTag = <T extends Entity>(\n entityType: T,\n tagName: string,\n opts: CommonOptions & { params?: ListEntitiesByTagParams } = {},\n ) => {\n const { tagApiBaseUrl = TAG_API_BASE_URL } = options;\n return axios.get<{ entities: CreatedEntity<T>[]; lastKey: string }>(\n opts.customUrl || `${tagApiBaseUrl}/${entityType}/${tagName}`,\n {\n requestKey:\n opts.requestKey ||\n getTagRequestKey('list', entityType, tagName, opts.params),\n params: opts.params,\n isInterruptive: opts.isInterruptive,\n feedback: opts.feedback,\n },\n );\n };\n\n const getEntity = <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n return axios.get<CreatedEntity<T>>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}/${id}`,\n {\n requestKey: getEntityRequestKey('get', entityType, id),\n isInterruptive: opts.isInterruptive,\n feedback: {\n loading: `Retrieving ${entityType}`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const getEntityByUniqueField = <T extends Entity>(\n entityType: T,\n fieldName: string,\n value: string,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n return axios.get<CreatedEntity<T>>(\n opts.customUrl ||\n `${entityApiBaseUrl}/${entityType}/unique/${getUniqueFieldStateKey(fieldName, value)}`,\n {\n requestKey: getUniqueFieldRequestKey(entityType, fieldName, value),\n isInterruptive: opts.isInterruptive,\n feedback: {\n loading: `Retrieving ${entityType}`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const createEntity = <T extends Entity>(\n entityType: T,\n values: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n const entityConfig = monoriseStore.getState().config;\n return axios.post<CreatedEntity<T>>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}`,\n { ...values, ...(opts.entityId && { entityId: opts.entityId }) },\n {\n requestKey:\n opts.requestKey || getEntityRequestKey('create', entityType),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: `Creating ${entityConfig[entityType].displayName}`,\n success: `${entityConfig[entityType].displayName} created`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const upsertEntity = <T extends Entity>(\n entityType: T,\n id: string,\n values: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n const entityConfig = monoriseStore.getState().config;\n return axios.put<CreatedEntity<T>>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}/${id}`,\n values,\n {\n requestKey: getEntityRequestKey('upsert', entityType, id),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: `Updating ${entityConfig[entityType].displayName}`,\n success: `${entityConfig[entityType].displayName} updated`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const editEntity = <T extends Entity>(\n entityType: T,\n id: string,\n values: Partial<DraftEntity<T>> & { $condition?: string },\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n const entityConfig = monoriseStore.getState().config;\n return axios.patch<CreatedEntity<T>>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}/${id}`,\n values,\n {\n requestKey: getEntityRequestKey('edit', entityType, id),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: `Updating ${entityConfig[entityType].displayName}`,\n success: `${entityConfig[entityType].displayName} updated`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const adjustEntity = <T extends Entity>(\n entityType: T,\n id: string,\n adjustments: Record<string, number>,\n opts: CommonOptions & { condition?: string } = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n const entityConfig = monoriseStore.getState().config;\n const body = opts.condition\n ? { ...adjustments, $condition: opts.condition }\n : adjustments;\n return axios.post<CreatedEntity<T>>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}/${id}/adjust`,\n body,\n {\n requestKey: getEntityRequestKey('adjust', entityType, id),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: `Updating ${entityConfig[entityType].displayName}`,\n success: `${entityConfig[entityType].displayName} updated`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const deleteEntity = <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n const entityConfig = monoriseStore.getState().config;\n return axios.delete(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}/${id}`,\n {\n requestKey: getEntityRequestKey('delete', entityType, id),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: `Deleting ${entityConfig[entityType].displayName}`,\n success: `${entityConfig[entityType].displayName} deleted`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const executeTransaction = (\n operations: TransactionOperation[],\n opts: CommonOptions = {},\n ) => {\n const { transactionApiBaseUrl = TRANSACTION_API_BASE_URL } = options as any;\n return axios.post<TransactionResult>(\n opts.customUrl || transactionApiBaseUrl,\n { operations },\n {\n // A hardcoded requestKey would collide across concurrent transaction\n // calls, sharing one loading/error slot. Using a single operation's\n // own key (e.g. operations[0]'s) would collide the OTHER way — with\n // a standalone editEntity/createEntity call on that same target,\n // via lib/api.ts's `ongoingRequests` dedupe, which would hand either\n // caller the other's differently-shaped response. The joined key is\n // namespaced so it can never match a single-entity key and unique per\n // call so non-idempotent transaction writes cannot be silently\n // deduplicated. Callers can pass opts.requestKey to opt into dedupe.\n requestKey:\n opts.requestKey || createTransactionCallRequestKey(operations),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: 'Processing transaction',\n success: 'Transaction completed',\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const listEntitiesByEntity = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n opts: CommonOptions = {},\n chainEntityQuery?: string,\n ) => {\n const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;\n return axios.get<{ entities: Mutual<B, T>[]; lastKey: string }>(\n opts.customUrl ||\n `${mutualApiBaseUrl}/${byEntityType}/${byEntityId}/${entityType}`,\n {\n requestKey: getMutualRequestKey(\n 'list',\n byEntityType,\n entityType,\n byEntityId,\n undefined,\n chainEntityQuery,\n ),\n isInterruptive: opts.isInterruptive,\n feedback: opts.feedback,\n params: {\n chainEntityQuery,\n limit: opts.limit,\n ...opts.params,\n ...(opts.noData && { projection: 'no-data' }),\n },\n },\n );\n };\n\n const getMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => {\n const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;\n return axios.get<Mutual<B, T>>(\n opts.customUrl ||\n `${mutualApiBaseUrl}/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n {\n requestKey: getMutualRequestKey(\n 'get',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n ),\n isInterruptive: opts.isInterruptive ?? false,\n feedback: opts.feedback,\n },\n );\n };\n\n const createMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, unknown>,\n opts: CommonOptions = {},\n ) => {\n const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;\n return axios.post<Mutual<B, T>>(\n opts.customUrl ||\n `${mutualApiBaseUrl}/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n payload,\n {\n requestKey: getMutualRequestKey(\n 'create',\n byEntityType,\n entityType,\n byEntityId,\n ),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: 'Creating linkage',\n success: 'Linkage created',\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const editMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, unknown>,\n opts: CommonOptions = {},\n ) => {\n const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;\n return axios.patch<Mutual<B, T>>(\n opts.customUrl ||\n `${mutualApiBaseUrl}/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n payload,\n {\n requestKey: getMutualRequestKey(\n 'update',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n ),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: 'Updating linkage',\n success: 'Linkage updated',\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const deleteMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => {\n const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;\n return axios.delete(\n opts.customUrl ||\n `${mutualApiBaseUrl}/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n {\n requestKey: getMutualRequestKey(\n 'delete',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n ),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: 'Removing linkage',\n success: 'Linkage removed',\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const makeEntityService = <T extends Entity>(entityType: T) => ({\n listEntities: (payload: ListEntitiesPayload, opts: CommonOptions = {}) =>\n listEntities(entityType, payload, opts),\n searchEntities: (query: string, opts: CommonOptions = {}) =>\n searchEntities(entityType, query, opts),\n listEntitiesByTag: (tagName: string, opts: CommonOptions = {}) =>\n listEntitiesByTag(entityType, tagName, opts),\n getEntity: (id: string, opts: CommonOptions = {}) =>\n getEntity(entityType, id, opts),\n getEntityByUniqueField: (\n fieldName: string,\n value: string,\n opts: CommonOptions = {},\n ) => getEntityByUniqueField(entityType, fieldName, value, opts),\n createEntity: (values: DraftEntity<T>, opts: CommonOptions = {}) =>\n createEntity(entityType, values, opts),\n upsertEntity: (\n id: string,\n values: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => upsertEntity(entityType, id, values, opts),\n editEntity: (\n id: string,\n values: Partial<DraftEntity<T>> & { $condition?: string },\n opts: CommonOptions = {},\n ) => editEntity(entityType, id, values, opts),\n updateEntity: (\n id: string,\n values: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => editEntity(entityType, id, values, opts),\n adjustEntity: (\n id: string,\n adjustments: Record<string, number>,\n opts: CommonOptions = {},\n ) => adjustEntity(entityType, id, adjustments, opts),\n deleteEntity: (id: string, opts: CommonOptions = {}) =>\n deleteEntity(entityType, id, opts),\n });\n\n const makeMutualService = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n ) => ({\n listEntitiesByEntity: (\n byEntityId: string,\n opts: CommonOptions = {},\n chainEntityQuery?: string,\n ) =>\n listEntitiesByEntity(\n byEntityType,\n entityType,\n byEntityId,\n opts,\n chainEntityQuery,\n ),\n getMutual: (\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => getMutual(byEntityType, entityType, byEntityId, entityId, opts),\n createMutual: (\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, unknown>,\n opts = {},\n ) =>\n createMutual(\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n payload,\n opts,\n ),\n editMutual: (\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, unknown>,\n opts = {},\n ) =>\n editMutual(byEntityType, entityType, byEntityId, entityId, payload, opts),\n deleteMutual: (\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => deleteMutual(byEntityType, entityType, byEntityId, entityId, opts),\n });\n\n const setOptions = (opts: ConfigOptions) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return {\n makeEntityService,\n makeMutualService,\n executeTransaction,\n /** @deprecated use `executeTransaction` — kept as an alias since `coreService` is a public export and this method already existed under this name. */\n transaction: executeTransaction,\n setOptions,\n };\n};\n\nexport default initCoreService;\n\nexport type CoreService = ReturnType<typeof initCoreService>;\n","import type { AxiosInterceptor } from '../types/api.type';\n\ntype UploadFileProps = {\n file: File;\n scope: string;\n directory: string;\n name: string;\n disableLoading?: boolean;\n onProgress?: (progress: number) => void;\n};\n\ntype Options = {\n apiBaseUrl?: string;\n};\n\nconst initFilestoreService = (axios: AxiosInterceptor) => {\n let options: Options = {};\n const { apiBaseUrl = '/api/file' } = options;\n\n const uploadFile = async ({\n file,\n scope,\n directory,\n name,\n disableLoading,\n onProgress,\n }: UploadFileProps) => {\n const { data } = await axios.get(`${apiBaseUrl}/upload`, {\n requestKey: `filestore/presign/file/${name}`,\n isInterruptive: !disableLoading,\n feedback: {\n loading: 'Preparing upload',\n },\n params: {\n scope,\n directory,\n filename: name,\n },\n });\n\n return axios.put(data.url, file, {\n requestKey: `filestore/upload/${name}`,\n isInterruptive: !disableLoading,\n feedback: {\n loading: 'Uploading file',\n },\n headers: {\n 'Content-Type': file.type,\n 'Content-Disposition': 'inline',\n },\n onUploadProgress: (progressEvent) => {\n if (onProgress && progressEvent.total) {\n const progress = Math.round(\n (progressEvent.loaded / progressEvent.total) * 100,\n );\n onProgress(progress);\n }\n },\n });\n };\n\n const deleteFiles = async (keys: string[]) => {\n console.log('Deleting files', keys);\n const { data } = await axios.post(\n `${apiBaseUrl}/delete`,\n {\n keys,\n },\n {\n requestKey: 'filestore/delete',\n },\n );\n\n return data;\n };\n\n const uploadVideo = async ({\n file,\n scope,\n directory,\n name,\n }: UploadFileProps) => {\n const { data: presign } = await axios.get(`${apiBaseUrl}/upload`, {\n requestKey: `filestore/presign/video/${name}`,\n isInterruptive: true,\n feedback: {\n loading: 'Preparing upload',\n },\n params: {\n scope,\n directory,\n filename: name,\n },\n });\n\n await axios.put(presign.url, file, {\n requestKey: `filestore/upload/video/${name}`,\n isInterruptive: true,\n feedback: {\n loading: 'Uploading video',\n },\n headers: {\n 'Content-Type': file.type,\n },\n });\n\n const { data } = await axios.post(\n `${apiBaseUrl}/video/convert`,\n {\n scope,\n directory,\n filename: name,\n },\n {\n requestKey: 'filestore/convert/video',\n isInterruptive: true,\n feedback: {\n loading: 'Triggering video conversion',\n },\n },\n );\n\n return data;\n };\n\n const uploadAudio = async ({\n file,\n scope,\n directory,\n name,\n }: UploadFileProps) => {\n const { data: presign } = await axios.get(`${apiBaseUrl}/upload`, {\n requestKey: `filestore/presign/audio/${name}`,\n isInterruptive: true,\n feedback: {\n loading: 'Preparing upload',\n },\n params: {\n scope,\n directory,\n filename: name,\n },\n });\n\n await axios.put(presign.url, file, {\n requestKey: `filestore/upload/audio/${name}`,\n isInterruptive: true,\n feedback: {\n loading: 'Uploading audio',\n },\n headers: {\n 'Content-Type': file.type,\n },\n });\n\n const { data } = await axios.post(\n `${apiBaseUrl}/audio/convert`,\n {\n scope,\n directory,\n filename: name,\n },\n {\n requestKey: 'filestore/convert/audio',\n isInterruptive: true,\n feedback: {\n loading: 'Triggering audio conversion',\n },\n },\n );\n\n return data;\n };\n\n const getJobStatus = async (id: string) => {\n const { data } = await axios.get(`${apiBaseUrl}/job/${id}`, {\n requestKey: `filestore/get-job/${id}`,\n });\n\n return data;\n };\n\n const setOptions = (opts: Options) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return {\n uploadFile,\n deleteFiles,\n uploadVideo,\n uploadAudio,\n getJobStatus,\n setOptions,\n };\n};\n\nexport default initFilestoreService;\n","import type {\n CreatedEntity,\n Entity,\n MonoriseEntityConfig,\n} from '@monorise/base';\nimport { enableMapSet } from 'immer';\nimport type React from 'react';\nimport { create } from 'zustand';\nimport { devtools } from 'zustand/middleware';\nimport type { ApplicationRequestError, ModalProps } from '../types/api.type';\nimport type { CommonStore } from '../types/monorise.type';\nimport type { Mutual } from '../types/mutual.type';\n\nenableMapSet();\n\nconst configureDevtools = (storeName: string) => ({\n name: `${storeName} Store`,\n anonymousActionType: `${storeName.toLowerCase()}/action`,\n enabled: !['prod', 'dev'].includes(process.env.NEXT_PUBLIC_ENVIRONMENT ?? ''),\n serialize: {\n options: {\n map: true,\n },\n },\n});\n\ntype Options = {\n modals?: Record<string, React.ComponentType<unknown>>;\n};\n\nconst initMonoriseStore = () => {\n let options: Options = {};\n const { modals = {} } = options;\n\n type AppModalProps = ModalProps<typeof modals>;\n\n const monoriseStore = create(\n devtools(\n (): {\n app: {\n ongoingRequests: Map<string, Promise<unknown>>;\n loadStack: Map<string, number>;\n intLoadStack: Map<string, number>;\n loadingMessage: string;\n errorStack: Map<string, ApplicationRequestError>;\n modal: {\n name: keyof AppModalProps | null;\n context?: AppModalProps[keyof AppModalProps];\n };\n };\n config: Record<Entity, MonoriseEntityConfig>;\n entity: Record<Entity, CommonStore<CreatedEntity<Entity>>>;\n mutual: Record<string, CommonStore<Mutual>>;\n tag: Record<string, CommonStore<CreatedEntity<Entity>>>;\n auth: {\n isUnauthorized: boolean;\n profile: {\n displayName: string;\n email: string;\n accountId: string;\n };\n isLoading: boolean;\n };\n } => ({\n app: {\n ongoingRequests: new Map(),\n loadStack: new Map(),\n intLoadStack: new Map(),\n loadingMessage: '',\n errorStack: new Map(),\n modal: {\n name: null,\n },\n },\n config: {},\n entity: {},\n mutual: {},\n tag: {},\n auth: {\n isUnauthorized: false,\n profile: {\n displayName: '',\n email: '',\n accountId: '',\n },\n isLoading: true,\n },\n }),\n configureDevtools('monorise'),\n ),\n );\n\n const setOptions = (opts: Options) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return { setOptions, monoriseStore };\n};\n\nexport { initMonoriseStore };\n\nexport type MonoriseStore = Awaited<\n ReturnType<typeof initMonoriseStore>\n>['monoriseStore'];\n","import type { Entity, MonoriseEntityConfig } from '@monorise/base';\nimport type { AxiosResponse } from 'axios';\nimport { initAppActions } from './actions/app.action';\nimport { initAuthActions } from './actions/auth.action';\nimport { initConfigActions } from './actions/config.action';\nimport { initCoreActions } from './actions/core.action';\nimport {\n initWebSocketActions,\n initializeWebSocketManager,\n getWebSocketManager,\n} from './actions/websocket.action';\nimport {\n WebSocketManager,\n type ConnectionState,\n type ClientMessage,\n type ServerMessage,\n} from './websocket';\nimport { initAxiosInterceptor, injectAxiosInterceptor } from './lib/api';\nimport {\n getEntityRequestKey,\n getMutualRequestKey,\n getTagRequestKey,\n getUniqueFieldRequestKey,\n} from './lib/utils';\nimport initAuthService from './services/auth.service';\nimport initCoreService from './services/core.service';\nimport initFilestoreService from './services/filestore.service';\nimport { initMonoriseStore } from './store/monorise.store';\nimport {\n Mutual,\n MutualData,\n MutualDataMapping,\n MutualDataWithIndex,\n} from './types/mutual.type';\n\ntype Options<T extends Record<string, React.ComponentType<any>>> = {\n authBaseUrl?: string;\n filestoreBaseUrl?: string;\n entityBaseUrl?: string;\n mutualBaseUrl?: string;\n tagBaseUrl?: string;\n modals?: T;\n entityConfig: Record<Entity, MonoriseEntityConfig>;\n onApiSuccess?: <T>(\n response: AxiosResponse<T>,\n feedbackSuccess:\n | ((data: AxiosResponse<T>['data']) => React.ReactNode)\n | string\n | boolean,\n ) => void;\n};\n\nconst initMonorise = () => {\n const { monoriseStore: store, setOptions: setMonoriseOptions } =\n initMonoriseStore();\n const appActions = initAppActions(store);\n const configActions = initConfigActions(store);\n const axios = initAxiosInterceptor(store, appActions);\n\n const authService = initAuthService(axios);\n const filestoreService = initFilestoreService(axios);\n const coreService = initCoreService(store, axios);\n\n const authActions = initAuthActions(store, authService);\n const coreActions = initCoreActions(store, appActions, coreService);\n // The socket hooks need an HTTP read path, not just the socket: they fetch\n // the initial page on mount and re-fetch on reconnect to recover whatever\n // was missed while the connection was down. `httpActions` is optional on\n // `initWebSocketActions`, and omitting it fails quietly rather than loudly —\n // `fetchData` early-returns, so `isLoading` never leaves its initial `true`\n // and the documented resync-on-reconnect never happens.\n //\n // Note the argument order: `coreService`'s own `listEntitiesByEntity` takes\n // (byEntityType, entityType, byEntityId) while the socket actions pass\n // (byEntityType, byEntityId, entityType). They are adapted here rather than\n // passed straight through.\n const websocketActions = initWebSocketActions(store, {\n listEntities: async (entityType, params) => {\n const { data } = await coreService\n .makeEntityService(entityType)\n .listEntities({ limit: params?.limit, lastKey: params?.lastKey });\n return { data: data.data, lastKey: data.lastKey };\n },\n listEntitiesByEntity: async (\n byEntityType,\n byEntityId,\n entityType,\n params,\n ) => {\n const { data } = await coreService\n .makeMutualService(byEntityType, entityType)\n .listEntitiesByEntity(byEntityId, {\n limit: params?.limit,\n params: { lastKey: params?.lastKey },\n });\n return { entities: data.entities, lastKey: data.lastKey };\n },\n });\n\n const axiosInterceptor = injectAxiosInterceptor(\n appActions,\n authActions,\n axios,\n );\n\n const config = <T extends Record<string, React.ComponentType<any>>>(\n opts: Options<T>,\n ) => {\n setMonoriseOptions({\n modals: opts.modals,\n });\n configActions.setConfig(opts.entityConfig);\n authService.setOptions({\n apiBaseUrl: opts.authBaseUrl,\n });\n filestoreService.setOptions({\n apiBaseUrl: opts.filestoreBaseUrl,\n });\n coreService.setOptions({\n entityApiBaseUrl: opts.entityBaseUrl,\n mutualApiBaseUrl: opts.mutualBaseUrl,\n tagApiBaseUrl: opts.tagBaseUrl,\n });\n axiosInterceptor.setOptions({\n onApiSuccess: opts.onApiSuccess,\n });\n };\n\n return {\n config,\n store,\n axios,\n authService,\n filestoreService,\n coreService,\n ...configActions,\n ...appActions,\n ...authActions,\n ...coreActions,\n ...websocketActions,\n };\n};\n\nconst Monorise = initMonorise();\n\nconst {\n store,\n axios,\n authService,\n filestoreService,\n coreService,\n setConfig,\n getConfig,\n useConfig,\n startLoading,\n endLoading,\n setError,\n getError,\n clearError,\n openModal,\n closeModal,\n useLoadStore,\n useInterruptiveLoadStore,\n useErrorStore,\n useModalStore,\n requestLogin,\n useProfile,\n getProfile,\n useIsUnauthorized,\n setIsUnauthorized,\n logout,\n listMoreEntities,\n createEntity,\n upsertEntity,\n editEntity,\n adjustEntity,\n updateLocalEntity,\n deleteEntity,\n executeTransaction,\n getMutual,\n createMutual,\n createLocalMutual,\n upsertLocalMutual,\n editMutual,\n deleteMutual,\n deleteLocalMutual,\n useEntity,\n useEntityByUniqueField,\n useEntities,\n useMutual,\n useMutuals,\n useTaggedEntities,\n useEntityState,\n getEntity,\n updateLocalTaggedEntity,\n deleteLocalTaggedEntity,\n useEntitySocket,\n useMutualSocket,\n useEphemeralSocket,\n useEntityFeed,\n} = Monorise;\n\nexport {\n store,\n axios,\n authService,\n filestoreService,\n coreService,\n setConfig,\n getConfig,\n useConfig,\n startLoading,\n endLoading,\n setError,\n getError,\n clearError,\n openModal,\n closeModal,\n useLoadStore,\n useInterruptiveLoadStore,\n useErrorStore,\n useModalStore,\n requestLogin,\n useProfile,\n getProfile,\n useIsUnauthorized,\n setIsUnauthorized,\n logout,\n listMoreEntities,\n createEntity,\n upsertEntity,\n editEntity,\n adjustEntity,\n updateLocalEntity,\n deleteEntity,\n executeTransaction,\n getMutual,\n createMutual,\n createLocalMutual,\n upsertLocalMutual,\n editMutual,\n deleteMutual,\n deleteLocalMutual,\n useEntity,\n useEntityByUniqueField,\n useEntities,\n useMutual,\n useMutuals,\n useTaggedEntities,\n useEntityState,\n getEntityRequestKey,\n getMutualRequestKey,\n getTagRequestKey,\n getUniqueFieldRequestKey,\n getEntity,\n updateLocalTaggedEntity,\n deleteLocalTaggedEntity,\n useEntitySocket,\n useMutualSocket,\n useEphemeralSocket,\n useEntityFeed,\n initializeWebSocketManager,\n getWebSocketManager,\n WebSocketManager,\n type ConnectionState,\n type ClientMessage,\n type ServerMessage,\n};\n\nexport default Monorise;\n\nexport { transactional } from './helpers/transactional';\nexport { MutualDataWithIndex, MutualDataMapping, MutualData, Mutual };\n\nexport type {\n CreatedEntity,\n DraftEntity,\n Entity,\n EntitySchemaMap,\n NumericFields,\n} from '@monorise/base';\nexport type {\n TransactionOperation,\n TransactionResult,\n TransactionResultEntry,\n} from './helpers/transactional';\n"],"mappings":";;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,WAAW,gBAAgB;AAsCpC,IAAM,iBAAiB,CAACA,WAAyB;AAC/C,MAAI,UAAmB,CAAC;AAExB,QAAM,EAAE,SAAS,CAAC,EAAE,IAAI;AAGxB,QAAMC,gBAAe,CAAI;AAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAAC;AAAA,EACF,MAA8B;AAC5B,IAAAF,OAAM;AAAA,MACJ,QAAQ,CAAC,UAAU;AACjB,cAAM,YAAY,iBAAiB,iBAAiB;AACpD,cAAM,kBAAkB,MAAM,IAAI,SAAS,EAAE,IAAI,UAAU;AAE3D,cAAM,IAAI,iBACR,OAAO,YAAY,WAAW,UAAU;AAC1C,YAAIE,UAAS;AACX,gBAAM,IAAI,gBAAgB,IAAI,YAAYA,QAAO;AAAA,QACnD;AACA,cAAM,IAAI,SAAS,EAAE;AAAA,UACnB;AAAA,UACA,kBAAkB,kBAAkB,IAAI;AAAA,QAC1C;AAAA,MACF,CAAC;AAAA,MACD;AAAA,MACA,oBA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jB,QAAQ,KAAK;AAAA,IACf,CAAC;AACD,kBAAc,UAAU,KAAK,YAAY;AACzC,IAAAC,aAAY,WAAW;AAAA,MACrB,YAAY,KAAK;AAAA,IACnB,CAAC;AACD,IAAAC,kBAAiB,WAAW;AAAA,MAC1B,YAAY,KAAK;AAAA,IACnB,CAAC;AACD,IAAAC,aAAY,WAAW;AAAA,MACrB,kBAAkB,KAAK;AAAA,MACvB,kBAAkB,KAAK;AAAA,MACvB,eAAe,KAAK;AAAA,IACtB,CAAC;AACD,qBAAiB,WAAW;AAAA,MAC1B,cAAc,KAAK;AAAA,IACrB,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL;AAAA,IACA,OAAAJ;AAAA,IACA,OAAAC;AAAA,IACA,aAAAC;AAAA,IACA,kBAAAC;AAAA,IACA,aAAAC;AAAA,KACG,gBACA,aACA,cACA,cACA;AAEP;AAEA,IAAM,WAAW,aAAa;AAE9B,IAAM;AAAA,EACJ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,IAAI;AAqEJ,IAAO,gBAAQ;","names":["store","startLoading","request","endLoading","setError","getError","clearError","openModal","closeModal","useLoadStore","useInterruptiveLoadStore","useErrorStore","useModalStore","produce","store","authService","requestLogin","useProfile","getProfile","produce","useIsUnauthorized","setIsUnauthorized","logout","produce","store","setConfig","getConfig","useConfig","produce","useEffect","useState","byEntityId","byEntityId","byEntityId","coreService","getError","useLoadStore","useErrorStore","startLoading","endLoading","setError","clearError","store","produce","error","listMoreEntities","state","getEntity","byEntityId","createEntity","_a","upsertEntity","editEntity","adjustEntity","deleteEntity","executeTransaction","_b","_c","_d","getMutual","createMutual","createLocalMutual","updateLocalEntity","upsertLocalMutual","editMutual","deleteMutual","deleteLocalMutual","useEntity","useEffect","useEntityByUniqueField","useEntities","useState","useMutual","useMutuals","useTaggedEntities","useEntityState","updateLocalTaggedEntity","deleteLocalTaggedEntity","useEffect","useState","produce","useEntitySocket","useState","setError","produce","useEffect","useMutualSocket","byEntityId","useEphemeralSocket","useEntityFeed","store","startLoading","axios","endLoading","setError","clearError","setIsUnauthorized","opts","axios","logout","axios","opts","getEntity","createEntity","upsertEntity","editEntity","adjustEntity","deleteEntity","executeTransaction","byEntityId","getMutual","createMutual","editMutual","deleteMutual","axios","store","axios","authService","filestoreService","coreService","byEntityId"]}
1
+ {"version":3,"sources":["../actions/app.action.ts","../actions/auth.action.ts","../actions/config.action.ts","../actions/core.action.ts","../lib/utils.ts","../helpers/transactional.ts","../lib/entity.ts","../actions/websocket.action.ts","../lib/api.ts","../services/auth.service.ts","../services/core.service.ts","../services/filestore.service.ts","../store/monorise.store.ts","../index.ts"],"sourcesContent":["import { produce } from 'immer';\nimport { useEffect, useState } from 'react';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type { ApplicationRequestError, ModalProps } from '../types/api.type';\n\ntype StartLoadingPayload<T> = {\n requestKey: string;\n isInterruptive?: boolean;\n message?: string | boolean;\n // Omit when this key is one of several sharing a single real HTTP call\n // (e.g. executeTransaction driving a loading signal per operation) — passing\n // it registers `requestKey` in `ongoingRequests`, which lib/api.ts's\n // `makeRequest` uses to hand back an in-flight promise to ANY other caller\n // using that same key, even one making a structurally different request.\n // The entry lasts only while `request` is in flight: once it settles, the\n // next call with the key (a retry after a failure, say) is sent afresh.\n request?: Promise<T>;\n};\n\ntype EndLoadingPayload = {\n requestKey: string;\n isInterruptive?: boolean;\n /**\n * @deprecated No longer needed: endLoading no longer touches\n * `ongoingRequests`; startLoading drops a request from it when the request\n * settles.\n */\n skipDedupe?: boolean;\n};\n\ntype SetErrorPayload = {\n requestKey: string;\n error: ApplicationRequestError;\n};\n\ntype Options = {\n modals?: Record<string, React.ComponentType<unknown>>;\n};\n\nconst initAppActions = (store: MonoriseStore) => {\n let options: Options = {};\n\n const { modals = {} } = options;\n type AppModalProps = ModalProps<typeof modals>;\n\n const startLoading = <T>({\n requestKey,\n isInterruptive,\n message,\n request,\n }: StartLoadingPayload<T>) => {\n store.setState(\n produce((state) => {\n const stackType = isInterruptive ? 'intLoadStack' : 'loadStack';\n const requestKeyCount = state.app[stackType].get(requestKey);\n\n state.app.loadingMessage =\n typeof message === 'string' ? message : 'Loading';\n if (request) {\n state.app.ongoingRequests.set(requestKey, request);\n }\n state.app[stackType].set(\n requestKey,\n requestKeyCount ? requestKeyCount + 1 : 1,\n );\n }),\n undefined,\n `mr/start-loading/${requestKey}`,\n );\n\n if (request) {\n // Share the request only while it's in flight. Checked by identity, so\n // a newer request under the same key is never the one removed.\n const forget = () => {\n if (store.getState().app.ongoingRequests.get(requestKey) !== request) {\n return;\n }\n store.setState(\n produce((state) => {\n state.app.ongoingRequests.delete(requestKey);\n }),\n undefined,\n `mr/settle-request/${requestKey}`,\n );\n };\n request.then(forget, forget);\n }\n };\n\n const endLoading = ({ requestKey, isInterruptive }: EndLoadingPayload) => {\n // The loading signal lingers briefly so it doesn't flicker. Request\n // dedupe isn't touched here: by now a retry may already be in flight\n // under the same key.\n setTimeout(() => {\n store.setState(\n produce((state) => {\n const stackType = isInterruptive ? 'intLoadStack' : 'loadStack';\n const requestKeyCount = state.app[stackType].get(requestKey);\n\n if (typeof requestKeyCount === 'number' && requestKeyCount > 1) {\n state.app[stackType].set(requestKey, requestKeyCount - 1);\n } else {\n state.app[stackType].delete(requestKey);\n }\n }),\n undefined,\n `mr/end-loading/${requestKey}`,\n );\n }, 500);\n };\n\n const checkIsLoading = (requestKey?: string) => {\n const { intLoadStack, loadStack } = store.getState().app;\n if (!requestKey) {\n return intLoadStack.size > 0 || loadStack.size > 0;\n }\n\n const activeIntLoadingCount = intLoadStack.get(requestKey);\n const isIntLoading =\n typeof activeIntLoadingCount === 'number' && activeIntLoadingCount > 0;\n\n const activeLoadingCount = loadStack.get(requestKey);\n const isLoading =\n typeof activeLoadingCount === 'number' && activeLoadingCount > 0;\n\n return isIntLoading || isLoading;\n };\n\n const setError = ({ requestKey, error }: SetErrorPayload) =>\n store.setState(\n produce((state) => {\n state.app.errorStack.set(requestKey, error);\n }),\n undefined,\n `mr/set-error/${requestKey}`,\n );\n\n const getError = (requestKey: string) => {\n const { errorStack } = store.getState().app;\n return errorStack.get(requestKey);\n };\n\n const clearError = (requestKey: string) => {\n const { errorStack } = store.getState().app;\n\n if (errorStack.has(requestKey)) {\n store.setState(\n produce((state) => {\n state.app.errorStack.delete(requestKey);\n }),\n undefined,\n `mr/clear-error/${requestKey}`,\n );\n }\n };\n\n const openModal = (modal: {\n name: keyof AppModalProps;\n context?: AppModalProps[keyof AppModalProps];\n }) =>\n store.setState(\n produce((state) => {\n state.app.modal = modal;\n }),\n undefined,\n `mr/open-modal/${modal.name}`,\n );\n\n const closeModal = () =>\n store.setState(\n produce((state) => {\n state.app.modal = { name: null };\n }),\n undefined,\n 'mr/close-modal',\n );\n\n const useLoadStore = (requestKey?: string) => {\n const { loadStack, intLoadStack } = store((state) => ({\n loadStack: state.app.loadStack,\n intLoadStack: state.app.intLoadStack,\n }));\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n if (loadStack && intLoadStack && requestKey) {\n setIsLoading(checkIsLoading(requestKey));\n }\n }, [loadStack, intLoadStack, requestKey]);\n\n return isLoading;\n };\n\n const useInterruptiveLoadStore = () => {\n const { intLoadStack, loadingMessage } = store((state) => ({\n intLoadStack: state.app.intLoadStack,\n loadingMessage: state.app.loadingMessage,\n }));\n\n return {\n isLoading: intLoadStack.size > 0,\n message: loadingMessage,\n };\n };\n\n const useErrorStore = (requestKey: string) => {\n const error = store((state) => state.app.errorStack.get(requestKey));\n\n useEffect(() => {\n if (error) {\n return () => {\n clearError(requestKey);\n };\n }\n }, [error, requestKey]);\n\n return error;\n };\n\n const useModalStore = () => {\n return store((state) => state.app.modal);\n };\n\n const setOptions = (opts: Options) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return {\n startLoading,\n endLoading,\n setError,\n getError,\n clearError,\n openModal,\n closeModal,\n checkIsLoading,\n useLoadStore,\n useInterruptiveLoadStore,\n useErrorStore,\n useModalStore,\n setOptions,\n };\n};\n\nexport { initAppActions };\n\nexport type AppActions = ReturnType<typeof initAppActions>;\n","import type { Entity } from '@monorise/base';\nimport { produce } from 'immer';\nimport type { AuthService } from '../services/auth.service';\nimport type { MonoriseStore } from '../store/monorise.store';\n\nconst initAuthActions = (store: MonoriseStore, authService: AuthService) => {\n const requestLogin = async (\n entityType: Entity,\n payload: { email: string },\n ) => {\n const { data } = await authService.requestLoginMagicLink(\n entityType,\n payload,\n );\n\n return data;\n };\n\n const useProfile = <T extends Record<string, unknown>>(): T & {\n displayName: string;\n email: string;\n accountId: string;\n impersonatorId?: string;\n } => {\n const profile = store((state) => state.auth.profile);\n\n return profile as T & typeof profile;\n };\n\n const getProfile = async () => {\n try {\n const {\n data: { displayName, email, accountId, ...rest },\n } = await authService.getSessionProfile();\n\n store.setState(\n produce((state) => {\n state.auth.profile = { displayName, email, accountId, ...rest };\n state.auth.isUnauthorized = false;\n state.auth.isLoading = false;\n }),\n undefined,\n 'mr/auth/get-profile',\n );\n } catch {\n store.setState(\n produce((state) => {\n state.auth.profile = {};\n state.auth.isUnauthorized = true;\n state.auth.isLoading = false;\n }),\n undefined,\n 'mr/auth/get-profile',\n );\n }\n };\n\n const useIsUnauthorized = () => {\n const { isUnauthorized, profile, isLoading } = store((state) => state.auth);\n\n return { isUnauthorized: isUnauthorized && !profile.accountId, isLoading };\n };\n\n const setIsUnauthorized = (isUnauthorized: boolean) =>\n store.setState(\n produce((state) => {\n state.auth.isUnauthorized = isUnauthorized;\n }),\n );\n\n const logout = () => {\n authService.logout();\n store.setState(\n produce((state) => {\n state.auth.isUnauthorized = true;\n state.auth.profile = {};\n }),\n );\n };\n\n return {\n requestLogin,\n useProfile,\n getProfile,\n useIsUnauthorized,\n setIsUnauthorized,\n logout,\n };\n};\n\nexport { initAuthActions };\n\nexport type AuthActions = ReturnType<typeof initAuthActions>;\n","import type {\n CreatedEntity,\n Entity,\n MonoriseEntityConfig,\n} from '@monorise/base';\nimport { produce } from 'immer';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type { CommonStore } from '../types/monorise.type';\n\nconst initConfigActions = (store: MonoriseStore) => {\n const setConfig = (config: Record<Entity, MonoriseEntityConfig>) => {\n const entityMaps = Object.keys(config).reduce(\n (acc, entity) => {\n acc[entity as any] = {\n dataMap: new Map<string, CreatedEntity<Entity>>(),\n isFirstFetched: false,\n lastKey: '',\n } as CommonStore<CreatedEntity<Entity>>;\n return acc;\n },\n {} as Record<Entity, CommonStore<CreatedEntity<Entity>>>,\n );\n\n store.setState(\n produce((state) => {\n state.config = config;\n state.entity = entityMaps;\n }),\n );\n };\n\n const getConfig = () => {\n return store.getState().config;\n };\n\n const useConfig = () => {\n const config = store((state) => state.config);\n\n return config;\n };\n\n return {\n setConfig,\n getConfig,\n useConfig,\n };\n};\n\nexport { initConfigActions };\n\nexport type ConfigActions = ReturnType<typeof initConfigActions>;\n","import type {\n CreatedEntity,\n DraftEntity,\n Entity,\n EntitySchemaMap,\n} from '@monorise/base';\nimport { produce } from 'immer';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n type TransactionCreateEntity,\n type TransactionOperation,\n createTransactionCallRequestKey,\n getTransactionOperationRequestKeys,\n getTransactionRequestKey,\n} from '../helpers/transactional';\nimport {\n byEntityId,\n constructLocal,\n constructMutual,\n flipMutual,\n} from '../lib/entity';\nimport {\n convertToMap,\n getEntityRequestKey,\n getMutualRequestKey,\n getMutualStateKey,\n getTagRequestKey,\n getTagStateKey,\n getUniqueFieldRequestKey,\n getUniqueFieldStateKey,\n parseMutualStateKey,\n} from '../lib/utils';\nimport type {\n CommonOptions,\n CoreService,\n ListEntitiesByTagParams,\n} from '../services/core.service';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type { ApplicationRequestError } from '../types/api.type';\nimport type { CommonStore } from '../types/monorise.type';\nimport type { Mutual, MutualData } from '../types/mutual.type';\nimport type { AppActions } from './app.action';\n\n// ===== Important tips ======\n// Should we use store.getState() or store()?\n// USE store.getState() WHEN using within an action such as getEntity, getProfile\n// USE store() WHEN using within a react hook so that it gets the benefit of reactivity, such as useProfile, useEntity\n\nconst defaultOnError = (error: ApplicationRequestError | Error) => {\n if (!(error instanceof Error) && error.status >= 500) {\n // we only want server error to be captured by error tracking service\n throw error;\n }\n};\n\nconst initCoreActions = (\n monoriseStore: MonoriseStore,\n appActions: AppActions,\n coreService: CoreService,\n) => {\n const { makeEntityService, makeMutualService } = coreService;\n const {\n checkIsLoading,\n getError,\n useLoadStore,\n useErrorStore,\n startLoading,\n endLoading,\n setError,\n clearError,\n } = appActions;\n\n const listEntities = async <T extends Entity>(\n entityType: T,\n params: {\n skRange?: { start: string; end: string };\n all?: boolean;\n limit?: number;\n } = { limit: 20 },\n opts: CommonOptions = {},\n ) => {\n const store = monoriseStore.getState();\n const entityState = store.entity[entityType] ?? {};\n const { isFirstFetched } = entityState;\n const entityService = makeEntityService(entityType);\n const { skRange } = params;\n const requestKey = getEntityRequestKey('list', entityType);\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const onError = opts.onError ?? defaultOnError;\n\n if (error) {\n onError(error);\n return;\n }\n\n if (\n !opts.forceFetch &&\n ((isFirstFetched && !params.skRange) || isLoading)\n ) {\n return;\n }\n\n try {\n const { data: result } = await entityService.listEntities(\n {\n ...(params?.all ? {} : { limit: params?.limit }),\n start: skRange?.start,\n end: skRange?.end,\n },\n opts,\n );\n const newEntityMap = convertToMap<CreatedEntity<T>>(\n result.data,\n 'entityId',\n );\n\n const mergedMap = new Map([\n ...newEntityMap,\n ...store.entity[entityType].dataMap,\n ]);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType] = {\n dataMap: params.skRange ? newEntityMap : mergedMap,\n isFirstFetched: true,\n lastKey: result.lastKey,\n };\n }),\n undefined,\n `mr/entity/list/${entityType}`,\n );\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n const listMoreEntities = async <T extends Entity>(\n entityType: T,\n opts: CommonOptions = {},\n ) => {\n const requestKey = getEntityRequestKey('list', entityType);\n const store = monoriseStore.getState();\n const entityState = store.entity[entityType];\n const { dataMap, lastKey } = entityState;\n const entityService = makeEntityService(entityType);\n const error = getError(requestKey);\n const onError = opts.onError ?? defaultOnError;\n\n if (!lastKey) {\n return;\n }\n\n if (error) {\n onError(error);\n return;\n }\n\n try {\n const { data: result } = await entityService.listEntities(\n {\n limit: opts.limit ?? 20,\n lastKey,\n },\n opts,\n );\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].isFirstFetched = true;\n state.entity[entityType].lastKey = result.lastKey;\n for (const i in result.data) {\n state.entity[entityType].dataMap.set(\n result.data[i].entityId,\n result.data[i],\n );\n }\n }),\n undefined,\n `mr/entity/list-more/${entityType}`,\n );\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n const searchEntities = async <T extends Entity>(\n entityType: T,\n query: string,\n opts: CommonOptions = {},\n ) => {\n const requestKey = getEntityRequestKey('search', entityType);\n const entityService = makeEntityService(entityType);\n const error = getError(requestKey);\n const onError = opts.onError ?? defaultOnError;\n\n if (error) {\n onError(error);\n return;\n }\n\n try {\n const { data: result } = await entityService.searchEntities(query, opts);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].searchResults = result.data;\n for (const i in result.data) {\n state.entity[entityType].dataMap.set(\n result.data[i].entityId,\n result.data[i],\n );\n }\n }),\n );\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n const listEntitiesByTag = async <T extends Entity>(\n entityType: T,\n tagName: string,\n opts: CommonOptions & { params?: ListEntitiesByTagParams } = {},\n ) => {\n const tagKey = getTagStateKey(entityType, tagName, opts.params);\n\n const state = monoriseStore.getState();\n const tagState = state.tag[tagKey] || {};\n const { isFirstFetched, dataMap } = tagState;\n const entityService = makeEntityService(entityType);\n const { forceFetch } = opts;\n const requestKey = getTagRequestKey(\n 'list',\n entityType,\n tagName,\n opts.params,\n );\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const onError = opts.onError ?? defaultOnError;\n\n if (!forceFetch) {\n if (error) {\n onError(error);\n return { error };\n }\n\n if (isFirstFetched || isLoading) {\n return {\n data: {\n entities: Array.from(dataMap?.values() || []),\n lastKey: null,\n },\n };\n }\n }\n\n try {\n const { data } = await entityService.listEntitiesByTag(tagName, {\n ...opts,\n requestKey,\n });\n const { entities, lastKey } = data;\n\n monoriseStore.setState(\n produce((state) => {\n for (const entity of entities) {\n state.entity[entityType].dataMap.set(entity.entityId, entity);\n }\n }),\n );\n\n monoriseStore.setState(\n produce((state) => {\n // Initialize tag state if it doesn't exist\n if (!state.tag[tagKey]) {\n state.tag[tagKey] = {\n dataMap: new Map(),\n isFirstFetched: false,\n };\n }\n\n // Merge new entities into existing dataMap instead of replacing\n for (const entity of entities) {\n state.tag[tagKey].dataMap.set(entity.entityId, entity);\n }\n\n state.tag[tagKey].isFirstFetched = true;\n state.tag[tagKey].lastKey = lastKey;\n }),\n );\n\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n const getEntity = async <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ): Promise<{\n data?: CreatedEntity<T>;\n error?: ApplicationRequestError | (Error & { originalError?: unknown });\n }> => {\n const store = monoriseStore.getState();\n const entityState = store.entity[entityType];\n const { dataMap } = entityState;\n const entityService = makeEntityService(entityType);\n let entity = dataMap.get(id);\n const requestKey = getEntityRequestKey('get', entityType, id);\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const { forceFetch } = opts;\n const onError = opts.onError ?? defaultOnError;\n\n if (!forceFetch) {\n if (error) {\n // If there's an existing error, handle it and return the error.\n onError?.(error);\n return { error };\n }\n\n if (entity) {\n // If entity already exists and no force fetch, return it.\n return { data: entity };\n }\n\n if (isLoading) {\n // If already loading, return undefined data and error to indicate ongoing operation.\n return {};\n }\n }\n\n try {\n ({ data: entity } = await entityService.getEntity(id, opts));\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(entity?.entityId, entity);\n }),\n undefined,\n `mr/entity/get/${entityType}/${id}`,\n );\n\n return { data: entity };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n const getEntityByUniqueField = async <T extends Entity>(\n entityType: T,\n fieldName: string,\n value: string,\n opts: CommonOptions = {},\n ) => {\n const store = monoriseStore.getState();\n const entityState = store.entity[entityType];\n const { dataMap } = entityState;\n const entityService = makeEntityService(entityType);\n const stateKey = getUniqueFieldStateKey(fieldName, value);\n let entity = dataMap.get(stateKey);\n const requestKey = getUniqueFieldRequestKey(entityType, fieldName, value);\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const { forceFetch } = opts;\n const onError = opts.onError ?? defaultOnError;\n\n if (!forceFetch) {\n if (error) {\n onError?.(error);\n return { error };\n }\n\n if (entity) {\n return { data: entity };\n }\n\n if (isLoading) {\n return {};\n }\n }\n\n try {\n ({ data: entity } = await entityService.getEntityByUniqueField(\n fieldName,\n value,\n opts,\n ));\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(entity?.entityId, entity);\n state.entity[entityType].dataMap.set(`${stateKey}`, entity);\n }),\n undefined,\n `mr/entity/unique/${entityType}/${stateKey}`,\n );\n\n return { data: entity };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n // Populate already-loaded mutual-list caches for a freshly created entity —\n // e.g. so a `refund-line-item` created via `createEntity` or `executeTransaction`\n // immediately appears in an already-fetched\n // `useMutuals(Entity.REFUND, Entity.REFUND_LINE_ITEM, ...)` list, instead of\n // only showing up after that list's next refetch. `payload` is the raw\n // create payload (mutualFields' ids live there, not necessarily on the\n // server's returned `data.data`).\n const populateMutualsForCreatedEntity = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n state: any,\n entityType: Entity,\n data: CreatedEntity<Entity>,\n payload: Record<string, any>,\n ) => {\n const mutualFields = state.config[entityType]?.mutual?.mutualFields;\n if (!mutualFields) return;\n\n for (const [field, fieldConfig] of Object.entries(mutualFields)) {\n const byEntityType = (fieldConfig as any).entityType;\n const ids = payload[field];\n if (!Array.isArray(ids)) continue;\n\n for (const byEntityId of ids) {\n const mutualKey = getMutualStateKey(byEntityType, byEntityId, entityType);\n if (state.mutual[mutualKey] && state.mutual[mutualKey].isFirstFetched) {\n state.mutual[mutualKey].dataMap.set(data.entityId, {\n entityId: data.entityId,\n entityType,\n byEntityId,\n byEntityType,\n mutualId: '',\n data: data.data,\n mutualData: {},\n createdAt: data.createdAt,\n updatedAt: data.updatedAt,\n mutualUpdatedAt: data.updatedAt,\n });\n }\n }\n }\n };\n\n const createEntity = async <T extends Entity>(\n entityType: T,\n entity: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => {\n const entityService = makeEntityService(entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data } = await entityService.createEntity(entity, opts);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(data.entityId, data);\n\n // auto-populate tag store based on entity config\n const tagConfigs = state.config[entityType]?.tags;\n if (tagConfigs) {\n for (const tagConfig of tagConfigs) {\n const { name, processor } = tagConfig;\n const processorResults = processor(\n data as CreatedEntity<Entity>,\n );\n\n for (const tagKey of Object.keys(state.tag)) {\n const [tagEntityType, tagName, ...paramParts] =\n tagKey.split('/');\n\n if (\n (tagEntityType as unknown as Entity) !== entityType ||\n tagName !== name\n ) {\n continue;\n }\n\n if (!state.tag[tagKey]?.isFirstFetched) {\n continue;\n }\n\n // parse params from key\n const keyParams: Record<string, string> = {};\n for (const part of paramParts) {\n const colonIdx = part.indexOf(':');\n if (colonIdx > 0) {\n keyParams[part.substring(0, colonIdx)] =\n part.substring(colonIdx + 1);\n }\n }\n\n // skip query-filtered stores (can't match client-side)\n if (keyParams.query) {\n continue;\n }\n\n // check if any processor result matches this tag store's params\n const matches = processorResults.some(\n (result: { group?: string; sortValue?: string }) => {\n if (keyParams.group && result.group !== keyParams.group) {\n return false;\n }\n if (\n keyParams.start &&\n (!result.sortValue || result.sortValue < keyParams.start)\n ) {\n return false;\n }\n if (\n keyParams.end &&\n (!result.sortValue || result.sortValue > keyParams.end)\n ) {\n return false;\n }\n return true;\n },\n );\n\n if (matches) {\n state.tag[tagKey].dataMap.set(data.entityId, data);\n }\n }\n }\n }\n\n // auto-populate mutual store based on entity config\n populateMutualsForCreatedEntity(\n state,\n entityType,\n data as CreatedEntity<Entity>,\n entity as Record<string, any>,\n );\n }),\n undefined,\n `mr/entity/create/${entityType}`,\n );\n\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n onError?.(error);\n\n return { error };\n }\n };\n\n const upsertEntity = async <T extends Entity>(\n entityType: T,\n id: string,\n entity: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => {\n const entityService = makeEntityService(entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data } = await entityService.upsertEntity(id, entity, opts);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(data.entityId, data);\n }),\n undefined,\n `mr/entity/upsert/${entityType}/${id}`,\n );\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n // Reconcile an entity's membership across already-loaded tag slices after a\n // data change (edit/adjust). Runs each tag's processor against the new data\n // and, per slice, keeps/adds the entity where it now matches and removes it\n // where it no longer does — so the UI re-buckets optimistically instead of\n // leaving stale members (e.g. a resolved item still sitting in the \"open\"\n // list) until the backend tag processor catches up. Mirrors the add-only\n // matcher in createEntity, extended with delete-on-mismatch.\n const reconcileTaggedEntityStore = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n state: any,\n entityType: Entity,\n id: string,\n data: CreatedEntity<Entity>,\n ) => {\n const tagConfigs = state.config[entityType]?.tags;\n if (!tagConfigs) return;\n\n for (const tagConfig of tagConfigs) {\n const { name, processor } = tagConfig;\n const processorResults = processor(data);\n\n for (const tagKey of Object.keys(state.tag)) {\n const [tagEntityType, tagName, ...paramParts] = tagKey.split('/');\n if (\n (tagEntityType as unknown as Entity) !== entityType ||\n tagName !== name\n ) {\n continue;\n }\n\n const slice = state.tag[tagKey];\n if (!slice?.dataMap) {\n continue;\n }\n\n // parse params (group/start/end/query/...) back out of the key\n const keyParams: Record<string, string> = {};\n for (const part of paramParts) {\n const colonIdx = part.indexOf(':');\n if (colonIdx > 0) {\n keyParams[part.substring(0, colonIdx)] = part.substring(\n colonIdx + 1,\n );\n }\n }\n\n // query-filtered slices can't be evaluated client-side — only patch an\n // existing member's data in place; never add or remove.\n if (keyParams.query) {\n if (slice.dataMap.has(id)) {\n slice.dataMap.set(id, data);\n }\n continue;\n }\n\n const matches = processorResults.some(\n (result: { group?: string; sortValue?: string }) => {\n if (keyParams.group && result.group !== keyParams.group) {\n return false;\n }\n if (\n keyParams.start &&\n (!result.sortValue || result.sortValue < keyParams.start)\n ) {\n return false;\n }\n if (\n keyParams.end &&\n (!result.sortValue || result.sortValue > keyParams.end)\n ) {\n return false;\n }\n return true;\n },\n );\n\n if (matches) {\n // keep/patch existing members, and add to newly-matching loaded\n // slices (appended; a later fetch restores exact sort order)\n if (slice.isFirstFetched || slice.dataMap.has(id)) {\n slice.dataMap.set(id, data);\n }\n } else if (slice.dataMap.has(id)) {\n // no longer belongs here — drop the stale member (the re-bucket)\n slice.dataMap.delete(id);\n }\n }\n }\n };\n\n // Patches an already-edited entity's new `.data` into every loaded mutual\n // list it appears in (the entity's OWN dataMap entry is set by the caller).\n // Shared by editEntity/adjustEntity/executeTransaction's update/adjust\n // branch — kept as one place so the three paths can't drift apart.\n const propagateEntityDataToMutuals = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n state: any,\n entityType: Entity,\n entityId: string,\n data: Record<string, any>,\n ) => {\n for (const key of Object.keys(state.mutual)) {\n const { entity: mutualEntityType } = parseMutualStateKey(key);\n if (mutualEntityType === entityType) {\n const mutual = state.mutual[key].dataMap.get(entityId);\n if (mutual) {\n state.mutual[key].dataMap = new Map(state.mutual[key].dataMap).set(\n entityId,\n { ...mutual, data },\n );\n }\n }\n }\n };\n\n // Removes a deleted entity's own dataMap entry, its forward-side mutual\n // entries (lists it's a MEMBER of — the reverse side, lists keyed BY this\n // entity, is deleteLocalMutualsByEntity's job, since that needs full entity\n // config), and its tag-store entries. Shared by deleteEntity/\n // executeTransaction's delete branch.\n const deleteEntityFromStores = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n state: any,\n entityType: Entity,\n entityId: string,\n ) => {\n state.entity[entityType]?.dataMap.delete(entityId);\n\n for (const key of Object.keys(state.mutual)) {\n const { entity: mutualEntityType } = parseMutualStateKey(key);\n if (mutualEntityType === entityType) {\n state.mutual[key].dataMap.delete(entityId);\n }\n }\n\n for (const tagKey of Object.keys(state.tag)) {\n const [tagEntityType] = tagKey.split('/');\n if ((tagEntityType as unknown as Entity) === entityType) {\n state.tag[tagKey]?.dataMap?.delete(entityId);\n }\n }\n };\n\n const editEntity = async <T extends Entity>(\n entityType: T,\n id: string,\n entity: Partial<DraftEntity<T>>,\n opts: CommonOptions = {},\n ) => {\n const entityService = makeEntityService(entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data } = await entityService.editEntity(id, entity, opts);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(data.entityId, data);\n\n propagateEntityDataToMutuals(state, entityType, id, data.data);\n\n // re-bucket across loaded tag slices (add where now matches, drop\n // where it no longer does) instead of only patching in place\n reconcileTaggedEntityStore(\n state,\n entityType,\n id,\n data as CreatedEntity<Entity>,\n );\n }),\n undefined,\n `mr/entity/edit/${entityType}/${id}`,\n );\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const adjustEntity = async <T extends Entity>(\n entityType: T,\n id: string,\n adjustments: Record<string, number>,\n opts: CommonOptions = {},\n ) => {\n const entityService = makeEntityService(entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data } = await entityService.adjustEntity(id, adjustments, opts);\n\n // Update local store with server response\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(data.entityId, data);\n\n propagateEntityDataToMutuals(state, entityType, id, data.data);\n\n // Propagate to tag stores — re-bucket across loaded slices (an\n // adjustment can move an entity between groups when group/sortValue\n // derive from the adjusted fields), not just patch in place.\n reconcileTaggedEntityStore(\n state,\n entityType,\n id,\n data as CreatedEntity<Entity>,\n );\n }),\n undefined,\n `mr/entity/adjust/${entityType}/${id}`,\n );\n\n return { data };\n } catch (err: any) {\n // Constraint violated — refetch entity to get latest state\n if (err?.response?.status === 409) {\n await getEntity(entityType, id, { forceFetch: true });\n }\n\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const deleteEntity = async <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ) => {\n const entityService = makeEntityService(entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n await entityService.deleteEntity(id, opts);\n deleteLocalMutualsByEntity(entityType, id);\n\n monoriseStore.setState(\n produce((state) => {\n deleteEntityFromStores(state, entityType, id);\n }),\n undefined,\n `mr/entity/delete/${entityType}/${id}`,\n );\n return { data: { entityId: id } }; // Indicate success with the deleted ID\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n // Runs a multi-entity atomic write (`coreService.executeTransaction`,\n // backed by a real DynamoDB TransactWriteItems) and folds each op's result\n // back into the local store — the same cache guarantee createEntity/\n // editEntity/adjustEntity/deleteEntity already give a single-entity call,\n // so a caller doesn't have to hand-roll cache patching (or force a\n // refetch) just because their write happened to span more than one entity.\n const executeTransaction = async (\n operations: TransactionOperation[],\n opts: CommonOptions = {},\n ) => {\n const onError = opts.onError ?? defaultOnError;\n const isInterruptive = opts.isInterruptive ?? true;\n const stateRequestKeys = Array.from(\n new Set([\n getTransactionRequestKey(operations),\n ...operations.flatMap(getTransactionOperationRequestKeys),\n ]),\n );\n // The joined key is namespaced under `transaction/` so it can never\n // match a single-entity action's own key — using e.g. one operation key\n // directly would let a standalone editEntity/createEntity call on that\n // same target collide with this transaction via lib/api.ts's\n // `ongoingRequests` dedupe, handing either caller the other's\n // differently-shaped response. Unique per call rather than deterministic,\n // because a transaction is a batch of non-idempotent writes -- see\n // createTransactionCallRequestKey for why deduping them silently loses\n // writes. Pass `opts.requestKey` explicitly to opt back into dedupe.\n const callRequestKey =\n opts.requestKey ?? createTransactionCallRequestKey(operations);\n const callPromise = coreService.executeTransaction(operations, {\n ...opts,\n requestKey: callRequestKey,\n });\n const loadingMessage = opts.feedback?.loading ?? 'Processing transaction';\n\n // Drive the transaction hook's key plus the same per-target loading/error\n // signal a standalone\n // createEntity/editEntity/adjustEntity/deleteEntity call on each op's\n // target would have driven, so a component checking any op's target via\n // useLoadStore/getError sees \"mutating\" during a transaction too. `request`\n // is deliberately omitted here — passing it would register these keys in\n // `ongoingRequests` too, letting a concurrent standalone call on the same\n // target dedupe onto (and never actually send) its own write. These keys\n // exist purely for loading/error *signaling*, not for de-duplicating this\n // HTTP call — that's callRequestKey's job.\n for (const requestKey of stateRequestKeys) {\n startLoading({ requestKey, isInterruptive, message: loadingMessage });\n }\n\n // Tracks whether the network call itself has already resolved and had\n // its success-path loading/error signaling run — so if the cache-fold\n // below throws (a tag processor, a bad payload, ...), the catch block\n // doesn't ALSO run the failure-path signaling for keys that were already\n // correctly cleared, which would both mis-decrement stacks shared with\n // other concurrent calls on those same keys and report a transaction\n // that actually committed as failed.\n let settled = false;\n\n try {\n const { data } = await callPromise;\n\n for (const requestKey of stateRequestKeys) {\n endLoading({ requestKey, isInterruptive, skipDedupe: true });\n clearError(requestKey);\n }\n settled = true;\n\n const deletedEntities: { entityType: Entity; entityId: string }[] = [];\n\n monoriseStore.setState(\n produce((state) => {\n data.results.forEach((entry, index) => {\n const { entityType, entityId } = entry;\n\n if (entry.operation === 'deleteEntity') {\n deleteEntityFromStores(state, entityType, entityId);\n deletedEntities.push({ entityType, entityId });\n return;\n }\n\n // createMutual / updateMutual / deleteMutual: the same store\n // updates the standalone createMutual / editMutual / deleteMutual\n // actions make, on both sides of the link.\n if (\n entry.operation === 'createMutual' ||\n entry.operation === 'updateMutual' ||\n entry.operation === 'deleteMutual'\n ) {\n const byEntityType = entry.byEntityType as Entity;\n const byEntityId = entry.byEntityId as string;\n const bySide = getMutualStateKey(\n byEntityType,\n byEntityId,\n entityType,\n );\n const side = getMutualStateKey(\n entityType,\n entityId,\n byEntityType,\n );\n\n if (entry.operation === 'deleteMutual') {\n state.mutual[bySide]?.dataMap.delete(entityId);\n state.mutual[side]?.dataMap.delete(byEntityId);\n return;\n }\n\n // An updateMutual whose post-commit read failed carries no\n // stored values — leave the cache alone rather than guess at\n // the merge, as for updateEntity below.\n if (entry.operation === 'updateMutual' && !entry.mutualData) {\n return;\n }\n\n const mutual = {\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n mutualId: entry.mutualId,\n data: entry.data ?? {},\n mutualData: entry.mutualData ?? {},\n createdAt: entry.createdAt,\n updatedAt: entry.updatedAt,\n mutualUpdatedAt: entry.mutualUpdatedAt,\n } as unknown as Mutual;\n\n if (!state.mutual[bySide]) {\n state.mutual[bySide] = { dataMap: new Map() };\n }\n state.mutual[bySide].dataMap = new Map(\n state.mutual[bySide]?.dataMap,\n ).set(entityId, mutual);\n\n if (!state.mutual[side]) {\n state.mutual[side] = { dataMap: new Map() };\n }\n const byEntityData =\n state.entity[byEntityType]?.dataMap.get(byEntityId)?.data ?? {};\n state.mutual[side].dataMap = new Map(\n state.mutual[side]?.dataMap,\n ).set(byEntityId, flipMutual(mutual, byEntityData));\n return;\n }\n\n if (entry.operation === 'createEntity') {\n const createdEntity = {\n entityId,\n entityType,\n data: entry.data ?? {},\n createdAt: entry.createdAt,\n updatedAt: entry.updatedAt,\n } as unknown as CreatedEntity<Entity>;\n\n state.entity[entityType].dataMap.set(entityId, createdEntity);\n\n const op = operations[index] as TransactionCreateEntity;\n populateMutualsForCreatedEntity(\n state,\n entityType,\n createdEntity,\n op?.payload as Record<string, any>,\n );\n reconcileTaggedEntityStore(\n state,\n entityType,\n entityId,\n createdEntity,\n );\n return;\n }\n\n // updateEntity / adjustEntity. `entry.data` is populated either\n // by the write itself or by transaction.service.ts's Phase 4\n // read-back — only patch the cache when we actually have fresh\n // data to patch it with, rather than guessing at a partial merge.\n const existing = state.entity[entityType]?.dataMap.get(entityId);\n if (!existing && !entry.data) return;\n\n if (!entry.data) {\n // No fresh data, but we do know the write landed — bump the\n // timestamp so at least `updatedAt` isn't stale, without\n // touching `.data` (and so without needing to re-bucket tags).\n if (entry.updatedAt) {\n state.entity[entityType].dataMap.set(entityId, {\n ...existing,\n updatedAt: entry.updatedAt,\n });\n }\n return;\n }\n\n const updated = {\n ...(existing ?? { entityId, entityType }),\n data: entry.data,\n updatedAt: entry.updatedAt ?? existing?.updatedAt,\n } as unknown as CreatedEntity<Entity>;\n\n state.entity[entityType].dataMap.set(entityId, updated);\n propagateEntityDataToMutuals(state, entityType, entityId, updated.data);\n reconcileTaggedEntityStore(state, entityType, entityId, updated);\n });\n }),\n undefined,\n 'mr/entity/execute-transaction',\n );\n\n // Reverse-side mutual cleanup for deletes (lists keyed BY the deleted\n // entity itself) — mirrors deleteEntity's own use of this helper, which\n // needs full entity config and does its own separate setState.\n for (const { entityType, entityId } of deletedEntities) {\n deleteLocalMutualsByEntity(entityType, entityId);\n }\n\n return { data };\n } catch (err) {\n if (!settled) {\n // The axios interceptor already ran its own error handling for\n // callRequestKey (endLoading + setError) — read back whatever\n // appError it computed and mirror it onto every op's key, rather\n // than re-deriving the AxiosError → ApplicationRequestError shaping\n // logic here.\n const callAppError = getError(callRequestKey);\n for (const requestKey of stateRequestKeys) {\n endLoading({ requestKey, isInterruptive, skipDedupe: true });\n if (callAppError) {\n setError({ requestKey, error: callAppError });\n }\n }\n // A generated key cannot be recomputed by a consumer or reused by a\n // later success, so retaining its interceptor error would leak one\n // unreachable errorStack entry per failed transaction. Explicit keys\n // remain observable and are therefore left intact.\n if (!opts.requestKey) {\n clearError(callRequestKey);\n }\n }\n\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const listEntitiesByEntity = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n chainEntityQuery?: string,\n ) => {\n const onError = opts.onError ?? defaultOnError;\n const selfKey =\n opts.stateKey ??\n getMutualStateKey(\n byEntityType,\n id,\n entityType,\n undefined,\n chainEntityQuery,\n );\n const mutualService = makeMutualService(byEntityType, entityType);\n const store = monoriseStore.getState();\n const mutualState = store.mutual[selfKey] || {};\n const { isFirstFetched } = mutualState;\n const requestKey = getMutualRequestKey(\n 'list',\n byEntityType,\n entityType,\n id,\n undefined,\n chainEntityQuery,\n );\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const { forceFetch } = opts;\n\n if (!forceFetch) {\n if (error) {\n onError(error);\n return { error };\n }\n\n if (isFirstFetched || isLoading) {\n return {\n data: {\n entities: Array.from(mutualState.dataMap?.values() || []),\n lastKey: mutualState.lastKey,\n },\n };\n }\n }\n\n try {\n const { data } = await mutualService.listEntitiesByEntity(\n id,\n opts,\n chainEntityQuery,\n );\n const { entities, lastKey } = data;\n const newEntityDataMap = new Map();\n\n for (const i in entities) {\n newEntityDataMap.set(entities[i].entityId, entities[i]);\n }\n\n monoriseStore.setState(\n produce((state) => {\n for (const [key, value] of newEntityDataMap) {\n state.entity[entityType]?.dataMap.set(key, value);\n }\n\n // prepare or extend the mutual entry\n const existing = state.mutual[selfKey];\n if (existing) {\n // extend the existing map\n const incoming = convertToMap(entities, 'entityId');\n for (const [k, v] of incoming) {\n existing.dataMap.set(k, v);\n }\n existing.isFirstFetched = true;\n existing.lastKey = lastKey;\n } else {\n // first time: create it\n state.mutual[selfKey] = {\n dataMap: convertToMap(entities, 'entityId'),\n isFirstFetched: true,\n lastKey,\n };\n }\n }),\n undefined,\n `mr/mutual/list/${selfKey}`,\n );\n\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n\n return { error };\n }\n };\n\n // todo: list more mutuals by entity\n // const listMoremutualsByEntity = async (\n // entityType: Entity,\n // otherEntityType: Entity,\n // id: string,\n // ) =>\n\n const getMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string | null,\n entityId: string,\n opts: CommonOptions & {\n // if failed to retrieve, would still set a default mutual data\n defaultMutualData?: Record<string, any>;\n } = {},\n ) => {\n const selfKey = getMutualStateKey(byEntityType, byEntityId, entityType);\n const mutualService = makeMutualService(byEntityType, entityType);\n const store = monoriseStore.getState();\n const mutualState = store.mutual[selfKey] || {};\n const requestKey = getMutualRequestKey(\n 'get',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n );\n const isLoading = checkIsLoading(requestKey);\n const error = getError(requestKey);\n const onError = opts.onError ?? defaultOnError;\n\n if (error) {\n onError?.(error);\n return { error };\n }\n\n if (!byEntityId || isLoading) {\n return {\n data: mutualState.dataMap?.get(entityId) as Mutual<B, T>,\n };\n }\n\n if (mutualState.dataMap?.get(entityId)) {\n return {\n data: mutualState.dataMap.get(entityId) as Mutual<B, T>,\n };\n }\n\n let mutual: Omit<Mutual<B, T>, 'data'>;\n let hasRequestFailed = false;\n\n try {\n ({ data: mutual } = await mutualService.getMutual(\n byEntityId,\n entityId,\n opts,\n ));\n } catch (err) {\n if (!opts.defaultMutualData) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n return { error };\n }\n\n hasRequestFailed = true;\n mutual = {\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n mutualId: `${byEntityId}-${entityId}`,\n mutualUpdatedAt: new Date().toISOString(),\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n mutualData: opts.defaultMutualData,\n };\n }\n\n const newMutualDataMap = new Map(store.mutual[selfKey]?.dataMap);\n newMutualDataMap.set(mutual.entityId, mutual as Mutual<B, T>);\n\n if (!hasRequestFailed) {\n const entityState = store.entity[entityType];\n const { dataMap: entityDataMap } = entityState;\n\n const newEntityDataMap = new Map(entityDataMap);\n newEntityDataMap.set(mutual.entityId, mutual as any);\n\n monoriseStore.setState(\n produce((state) => {\n state.mutual[selfKey] = {\n ...(state.mutual[selfKey] || {}),\n dataMap: newMutualDataMap,\n };\n state.entity[entityType].dataMap = newEntityDataMap;\n }),\n undefined,\n `mr/mutual/get/${getMutualStateKey(\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n )}`,\n );\n }\n return { data: mutual as Mutual<B, T> };\n };\n\n const createMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, any> = {},\n opts: CommonOptions = {},\n ) => {\n const mutualService = makeMutualService(byEntityType, entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data: mutual } = await mutualService.createMutual(\n byEntityId,\n entityId,\n payload,\n opts,\n );\n\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(\n byEntityType,\n byEntityId,\n entityType,\n );\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n\n if (!state.mutual[bySide]) {\n state.mutual[bySide] = {\n dataMap: new Map(),\n };\n }\n\n state.mutual[bySide].dataMap = new Map(\n state.mutual[bySide]?.dataMap,\n ).set(mutual.entityId, mutual);\n\n if (!state.mutual[side]) {\n state.mutual[side] = {\n dataMap: new Map(),\n };\n }\n\n const byEntityData =\n state.entity[mutual.byEntityType]?.dataMap.get(mutual.byEntityId)\n ?.data ?? {};\n state.mutual[side].dataMap = new Map(state.mutual[side]?.dataMap).set(\n mutual.byEntityId,\n flipMutual(mutual, byEntityData),\n );\n }),\n undefined,\n `mr/mutual/create/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n return { data: mutual };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const createLocalMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n mutualData: MutualData<B, T>,\n data: EntitySchemaMap[T] | Record<string, any>,\n ) => {\n const mutual = constructMutual(\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n mutualData,\n data as EntitySchemaMap[T],\n );\n\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(byEntityType, byEntityId, entityType);\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n\n if (!state.mutual[bySide]) {\n state.mutual[bySide] = {\n dataMap: new Map(),\n };\n }\n\n state.mutual[bySide].dataMap = new Map(\n state.mutual[bySide]?.dataMap,\n ).set(mutual.entityId, mutual);\n\n if (!state.mutual[side]) {\n state.mutual[side] = {\n dataMap: new Map(),\n };\n }\n\n const byEntityData =\n state.entity[mutual.byEntityType]?.dataMap.get(mutual.byEntityId)\n ?.data ?? {};\n state.mutual[side].dataMap = new Map(state.mutual[side]?.dataMap).set(\n mutual.byEntityId,\n flipMutual(mutual, byEntityData),\n );\n }),\n undefined,\n `mr/mutual/create/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n };\n\n const updateLocalEntity = async <T extends Entity>(\n entityType: Entity,\n entityId: string,\n data: Partial<DraftEntity<T>> = {},\n ) => {\n const createdEntity = constructLocal(entityType, entityId, data);\n\n monoriseStore.setState(\n produce((state) => {\n state.entity[entityType].dataMap.set(entityId, createdEntity);\n }),\n undefined,\n `mr/entity/local-update/${entityType}/${entityId}`,\n );\n };\n\n const upsertLocalMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n mutualData: MutualData<B, T>,\n data: EntitySchemaMap[T] | Record<string, any> = {},\n ) => {\n const mutual = constructMutual(\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n mutualData,\n data as EntitySchemaMap[T],\n );\n\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(byEntityType, byEntityId, entityType);\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n\n if (!state.mutual[bySide]) {\n state.mutual[bySide] = {\n dataMap: new Map(),\n };\n }\n\n state.mutual[bySide].dataMap = new Map(\n state.mutual[bySide]?.dataMap,\n ).set(entityId, mutual);\n\n if (!state.mutual[side]) {\n state.mutual[side] = {\n dataMap: new Map(),\n };\n }\n\n const byEntityData =\n state.entity[mutual.byEntityType]?.dataMap.get(mutual.byEntityId)\n ?.data ?? {};\n state.mutual[side].dataMap = new Map(state.mutual[side]?.dataMap).set(\n byEntityId,\n flipMutual(mutual, byEntityData),\n );\n }),\n undefined,\n `mr/mutual/local-update/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n };\n\n const editMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, any> = {},\n opts: CommonOptions = {},\n ) => {\n const mutualService = makeMutualService(byEntityType, entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data: mutual } = await mutualService.editMutual(\n byEntityId,\n entityId,\n payload,\n opts,\n );\n\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(\n byEntityType,\n byEntityId,\n entityType,\n );\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n\n if (!state.mutual[bySide]) {\n state.mutual[bySide] = {\n dataMap: new Map(),\n };\n }\n\n state.mutual[bySide].dataMap = new Map(\n state.mutual[bySide]?.dataMap,\n ).set(mutual.entityId, mutual);\n\n if (!state.mutual[side]) {\n state.mutual[side] = {\n dataMap: new Map(),\n };\n }\n\n const byEntityData =\n state.entity[mutual.byEntityType]?.dataMap.get(mutual.byEntityId)\n ?.data ?? {};\n state.mutual[side].dataMap = new Map(state.mutual[side]?.dataMap).set(\n mutual.byEntityId,\n flipMutual(mutual, byEntityData),\n );\n }),\n undefined,\n `mr/mutual/edit/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n return { data: mutual };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const deleteMutual = async <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId = '',\n opts: CommonOptions = {},\n ) => {\n const mutualService = makeMutualService(byEntityType, entityType);\n const onError = opts.onError ?? defaultOnError;\n\n try {\n const { data } = await mutualService.deleteMutual(\n byEntityId,\n entityId,\n opts,\n );\n\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(\n byEntityType,\n byEntityId,\n entityType,\n );\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n\n // Either list may never have been fetched; the delete still\n // succeeded, so don't report it as failed.\n state.mutual[bySide]?.dataMap.delete(data.entityId);\n state.mutual[side]?.dataMap.delete(data.byEntityId);\n }),\n undefined,\n `mr/mutual/delete/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n return { data };\n } catch (err) {\n const error: Error & { originalError?: unknown } =\n err instanceof Error ? err : new Error('Unknown error occurred');\n onError(error);\n return { error };\n }\n };\n\n const deleteLocalMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n ) => {\n monoriseStore.setState(\n produce((state) => {\n const bySide = getMutualStateKey(byEntityType, byEntityId, entityType);\n const side = getMutualStateKey(entityType, entityId, byEntityType);\n const bySideDataMap = new Map(state.mutual[bySide]?.dataMap);\n const sideDataMap = new Map(state.mutual[side]?.dataMap);\n bySideDataMap.delete(entityId);\n sideDataMap.delete(byEntityId);\n\n if (state.mutual[bySide]) {\n state.mutual[bySide].dataMap.delete(entityId);\n }\n if (state.mutual[side]) {\n state.mutual[side].dataMap.delete(byEntityId);\n }\n }),\n undefined,\n `mr/mutual/local-delete/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n );\n };\n\n const deleteLocalMutualsByEntity = <T extends Entity>(\n entityType: T,\n id: string,\n ) => {\n const store = monoriseStore.getState();\n const entityConfig = store.config; // Assuming store.config holds mutual related configurations\n let mutuals: Mutual[] = [];\n for (const i of Object.keys(entityConfig)) {\n const mutualState = store.mutual[`${entityType}/${id}/${i}`];\n mutuals = [\n ...mutuals,\n ...Array.from(mutualState?.dataMap.values() || []),\n ];\n }\n\n const updatedState = mutuals.reduce(\n (acc, mutual) => {\n const side = getMutualStateKey(\n mutual.entityType,\n mutual.entityId,\n mutual.byEntityType,\n );\n const dataMap = new Map(store.mutual[side]?.dataMap); // Use optional chaining\n dataMap.delete(id);\n acc[side] = {\n ...store.mutual[side],\n dataMap,\n };\n return acc;\n },\n {} as Record<string, CommonStore<Mutual>>,\n );\n\n monoriseStore.setState(\n produce((state) => {\n // This is a full replacement, might not be desired for partial updates.\n // If state.mutual can contain other keys, this might clear them.\n // Consider a more granular update if needed.\n for (const key in updatedState) {\n state.mutual[key] = updatedState[key];\n }\n }),\n undefined,\n `mr/mutual/local-delete-by-entity/${entityType}/${id}`,\n );\n };\n\n const mergeMutationOptions = (\n hookOptions: CommonOptions,\n mutateOptions: CommonOptions,\n ): CommonOptions => ({\n ...hookOptions,\n ...mutateOptions,\n ...((hookOptions.feedback || mutateOptions.feedback) && {\n feedback: {\n ...hookOptions.feedback,\n ...mutateOptions.feedback,\n },\n }),\n });\n\n const useLatestRef = <T,>(value: T) => {\n const ref = useRef(value);\n ref.current = value;\n return ref;\n };\n\n const useMutationState = (requestKey: string) => {\n const isLoading = useLoadStore(requestKey);\n // Mutation errors are shared state. Unlike useErrorStore, this must not\n // clear on effect cleanup: replacing one error with the next runs cleanup\n // for the old value, and unmounting one observer must not affect another.\n const error = monoriseStore((state) =>\n state.app.errorStack.get(requestKey),\n );\n const clearMutationError = useCallback(\n () => clearError(requestKey),\n [requestKey],\n );\n\n return {\n isLoading,\n error,\n requestKey,\n clearError: clearMutationError,\n };\n };\n\n const useCreateEntity = <T extends Entity>(\n entityType: T,\n opts: CommonOptions = {},\n ) => {\n const optsRef = useLatestRef(opts);\n const mutation = useMutationState(\n getEntityRequestKey('create', entityType),\n );\n const mutate = useCallback(\n (entity: DraftEntity<T>, mutateOpts: CommonOptions = {}) =>\n createEntity(\n entityType,\n entity,\n mergeMutationOptions(optsRef.current, mutateOpts),\n ),\n [entityType, optsRef],\n );\n\n return { mutate, ...mutation };\n };\n\n const useUpsertEntity = <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ) => {\n const optsRef = useLatestRef(opts);\n const mutation = useMutationState(\n getEntityRequestKey('upsert', entityType, id),\n );\n const mutate = useCallback(\n (entity: DraftEntity<T>, mutateOpts: CommonOptions = {}) =>\n upsertEntity(\n entityType,\n id,\n entity,\n mergeMutationOptions(optsRef.current, mutateOpts),\n ),\n [entityType, id, optsRef],\n );\n\n return { mutate, ...mutation };\n };\n\n const useEditEntity = <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ) => {\n const optsRef = useLatestRef(opts);\n const mutation = useMutationState(\n getEntityRequestKey('edit', entityType, id),\n );\n const mutate = useCallback(\n (entity: Partial<DraftEntity<T>>, mutateOpts: CommonOptions = {}) =>\n editEntity(\n entityType,\n id,\n entity,\n mergeMutationOptions(optsRef.current, mutateOpts),\n ),\n [entityType, id, optsRef],\n );\n\n return { mutate, ...mutation };\n };\n\n const useAdjustEntity = <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ) => {\n const optsRef = useLatestRef(opts);\n const mutation = useMutationState(\n getEntityRequestKey('adjust', entityType, id),\n );\n const mutate = useCallback(\n (adjustments: Record<string, number>, mutateOpts: CommonOptions = {}) =>\n adjustEntity(\n entityType,\n id,\n adjustments,\n mergeMutationOptions(optsRef.current, mutateOpts),\n ),\n [entityType, id, optsRef],\n );\n\n return { mutate, ...mutation };\n };\n\n const useDeleteEntity = <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ) => {\n const optsRef = useLatestRef(opts);\n const mutation = useMutationState(\n getEntityRequestKey('delete', entityType, id),\n );\n const mutate = useCallback(\n (mutateOpts: CommonOptions = {}) =>\n deleteEntity(\n entityType,\n id,\n mergeMutationOptions(optsRef.current, mutateOpts),\n ),\n [entityType, id, optsRef],\n );\n\n return { mutate, ...mutation };\n };\n\n const useCreateMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => {\n const optsRef = useLatestRef(opts);\n const mutation = useMutationState(\n getMutualRequestKey(\n 'create',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n ),\n );\n const mutate = useCallback(\n (\n payload: MutualData<B, T> | Record<string, any> = {},\n mutateOpts: CommonOptions = {},\n ) =>\n createMutual(\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n payload,\n mergeMutationOptions(optsRef.current, mutateOpts),\n ),\n [byEntityType, entityType, byEntityId, entityId, optsRef],\n );\n\n return { mutate, ...mutation };\n };\n\n const useEditMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => {\n const optsRef = useLatestRef(opts);\n const mutation = useMutationState(\n getMutualRequestKey(\n 'update',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n ),\n );\n const mutate = useCallback(\n (\n payload: MutualData<B, T> | Record<string, any> = {},\n mutateOpts: CommonOptions = {},\n ) =>\n editMutual(\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n payload,\n mergeMutationOptions(optsRef.current, mutateOpts),\n ),\n [byEntityType, entityType, byEntityId, entityId, optsRef],\n );\n\n return { mutate, ...mutation };\n };\n\n const useDeleteMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => {\n const optsRef = useLatestRef(opts);\n const mutation = useMutationState(\n getMutualRequestKey(\n 'delete',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n ),\n );\n const mutate = useCallback(\n (mutateOpts: CommonOptions = {}) =>\n deleteMutual(\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n mergeMutationOptions(optsRef.current, mutateOpts),\n ),\n [byEntityType, entityType, byEntityId, entityId, optsRef],\n );\n\n return { mutate, ...mutation };\n };\n\n const useExecuteTransaction = (\n operations: TransactionOperation[],\n opts: CommonOptions = {},\n ) => {\n const operationsRef = useLatestRef(operations);\n const optsRef = useLatestRef(opts);\n const mutation = useMutationState(getTransactionRequestKey(operations));\n const mutate = useCallback(\n (mutateOpts: CommonOptions = {}) =>\n executeTransaction(\n operationsRef.current,\n mergeMutationOptions(optsRef.current, mutateOpts),\n ),\n [operationsRef, optsRef],\n );\n\n return { mutate, ...mutation };\n };\n\n const useEntity = <T extends Entity>(\n entityType: T,\n id?: string,\n opts: CommonOptions = {},\n ): {\n entity: CreatedEntity<T> | undefined;\n isLoading: boolean;\n error?: ApplicationRequestError;\n requestKey: string;\n isFirstFetched?: boolean;\n refetch: () => Promise<CreatedEntity<T> | undefined>;\n } => {\n const dataMap = monoriseStore(\n (state) => state.entity[entityType]?.dataMap || new Map(),\n );\n const isFirstFetched = monoriseStore(\n (state) => state.entity[entityType]?.isFirstFetched,\n );\n const requestKey = getEntityRequestKey('get', entityType, id);\n const isLoading = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n\n useEffect(() => {\n if (id) {\n getEntity(entityType, id, opts);\n }\n }, [id, entityType, opts]);\n\n return {\n entity: id ? dataMap.get(id) : undefined,\n isLoading,\n error,\n requestKey,\n isFirstFetched,\n refetch: async () => {\n if (id) {\n const { data, error: fetchError } = await getEntity(entityType, id, {\n ...opts,\n forceFetch: true,\n });\n if (fetchError) {\n // Handle refetch error if necessary, e.g., throw or set local state\n }\n return data;\n }\n },\n };\n };\n\n const useEntityByUniqueField = <T extends Entity>(\n entityType: T,\n fieldName: string,\n value?: string,\n opts: CommonOptions = {},\n ): {\n entity: CreatedEntity<T> | undefined;\n isLoading: boolean;\n error?: ApplicationRequestError;\n requestKey: string;\n isFirstFetched?: boolean;\n refetch: () => Promise<CreatedEntity<T> | undefined>;\n } => {\n const dataMap = monoriseStore(\n (state) => state.entity[entityType]?.dataMap || new Map(),\n );\n const isFirstFetched = monoriseStore(\n (state) => state.entity[entityType]?.isFirstFetched,\n );\n const stateKey = getUniqueFieldStateKey(fieldName, value || '');\n const requestKey = getUniqueFieldRequestKey(\n entityType,\n fieldName,\n value || '',\n );\n const isLoading = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n\n useEffect(() => {\n if (value) {\n getEntityByUniqueField(entityType, fieldName, value, opts);\n }\n }, [fieldName, value, entityType, opts]);\n\n return {\n entity: value ? dataMap.get(`${stateKey}`) : undefined,\n isLoading,\n error,\n requestKey,\n isFirstFetched,\n refetch: async () => {\n if (value) {\n const { data, error: fetchError } = await getEntityByUniqueField(\n entityType,\n fieldName,\n value,\n {\n ...opts,\n forceFetch: true,\n },\n );\n if (fetchError) {\n // Handle refetch error if necessary\n }\n return data;\n }\n },\n };\n };\n\n const useEntities = <T extends Entity>(\n entityType: T,\n params: {\n skRange?: {\n start: string;\n end: string;\n };\n all?: boolean;\n limit?: number;\n } = { limit: 20 },\n opts: CommonOptions & { searchInterval?: number } = {},\n ): {\n isLoading: boolean;\n entities?: CreatedEntity<T>[];\n entitiesMap: Map<string, CreatedEntity<T>>;\n error?: ApplicationRequestError;\n requestKey: string;\n searchField: {\n value: string;\n onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;\n };\n lastKey?: string;\n isFirstFetched?: boolean;\n listMore: () => void;\n refetch: () => void;\n } => {\n const requestKey = getEntityRequestKey('list', entityType);\n const isListing = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n const state = monoriseStore((state) => state.entity[entityType]);\n const { dataMap, searchResults, isFirstFetched, lastKey } = state ?? {\n dataMap: new Map(),\n };\n const [entities, setEntities] = useState<CreatedEntity<T>[]>();\n const [query, setQuery] = useState<string>('');\n const [skRange, setBetween] = useState(params.skRange);\n const [all, setAll] = useState(params.all);\n const [limit, setLimit] = useState(params.limit);\n const [isSearching, setIsSearching] = useState(false);\n const isLoading = isListing || isSearching;\n\n useEffect(() => {\n if (\n params?.skRange &&\n skRange?.start !== params.skRange.start &&\n skRange?.end !== params.skRange.end\n ) {\n setBetween(params.skRange);\n }\n }, [skRange?.end, skRange?.start, params.skRange]);\n\n useEffect(() => {\n if (params?.all !== all) {\n setAll(params.all);\n }\n }, [all, params.all]);\n\n useEffect(() => {\n if (params?.limit !== limit) {\n setLimit(params.limit);\n }\n }, [limit, params.limit]);\n\n useEffect(() => {\n if (!isFirstFetched || opts?.forceFetch) {\n listEntities(entityType, { skRange, all, limit }, opts);\n }\n }, [all, entityType, skRange, opts, isFirstFetched, opts?.forceFetch, limit]);\n\n useEffect(() => {\n let queryTimeout: NodeJS.Timeout;\n\n if (query?.length) {\n setIsSearching(true);\n queryTimeout = setTimeout(async () => {\n await searchEntities(entityType, query);\n setIsSearching(false);\n }, opts.searchInterval ?? 700);\n }\n\n return () => queryTimeout && clearTimeout(queryTimeout);\n }, [entityType, query]);\n\n useEffect(() => {\n if (!query) {\n const dataMapArray = Array.from(dataMap.values()).sort(\n byEntityId,\n ) as CreatedEntity<T>[];\n // Compare size AND content so that edits which keep the same set of\n // entityIds but mutate their data (e.g. editEntity) still propagate\n // to the local `entities` snapshot. Matches the comparison already\n // used in `useMutuals`.\n if (\n dataMap.size !== entities?.length ||\n dataMapArray.some(\n (item, index) =>\n JSON.stringify(item) !== JSON.stringify(entities?.[index]),\n )\n ) {\n setIsSearching(false);\n setEntities(dataMapArray);\n }\n }\n\n if (query) {\n setEntities(searchResults as CreatedEntity<T>[]);\n }\n }, [\n dataMap,\n dataMap.size,\n entities,\n entities?.length,\n query,\n searchResults,\n searchResults?.length,\n ]);\n\n const handleQueryChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n setQuery(event.target.value);\n };\n\n const searchField = {\n value: query,\n onChange: handleQueryChange,\n };\n\n return {\n entities,\n entitiesMap: dataMap,\n searchField,\n isLoading,\n error,\n requestKey,\n isFirstFetched,\n lastKey,\n refetch: async () => {\n if (entityType && query) {\n await searchEntities(entityType, query);\n return;\n }\n await listEntities(\n entityType,\n { skRange, all },\n {\n ...opts,\n forceFetch: true,\n },\n );\n },\n listMore: async () => {\n if (!lastKey) return;\n\n await listMoreEntities(entityType, {\n ...opts,\n limit,\n forceFetch: true,\n });\n },\n };\n };\n\n const useMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byId: string | null,\n id: string,\n opts: CommonOptions & {\n // if failed to retrieve, would still set a default mutual data\n defaultMutualData?: Record<string, any>;\n } = {},\n ): {\n mutual?: Mutual<B, T>;\n isLoading: boolean;\n error?: ApplicationRequestError;\n requestKey: string;\n } => {\n const stateKey = getMutualStateKey(byEntityType, byId, entityType);\n const state = monoriseStore((state) => state.mutual[stateKey]);\n const requestKey = getMutualRequestKey(\n 'get',\n byEntityType,\n entityType,\n byId,\n id,\n );\n const isLoading = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n\n const { dataMap } = state || {\n dataMap: new Map(),\n };\n\n useEffect(() => {\n if (!dataMap.get(id)) {\n getMutual(byEntityType, entityType, byId, id, opts);\n }\n }, [byEntityType, byId, entityType, id, opts, dataMap]);\n\n return {\n mutual: dataMap.get(id) as Mutual<B, T>,\n isLoading,\n error,\n requestKey,\n };\n };\n\n const useMutuals = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byId?: string,\n opts: CommonOptions = {},\n chainEntityQuery?: string, // chain entity query, refer to list-entities-by-entity.controller.ts\n ): {\n mutuals: Mutual<B, T>[];\n mutualsMap: Map<string, Mutual<B, T>>;\n isLoading: boolean;\n requestKey: string;\n error?: ApplicationRequestError;\n isFirstFetched?: boolean;\n lastKey?: string;\n listMore?: () => void;\n refetch?: () => Promise<any>;\n } => {\n const stateKey = getMutualStateKey(\n byEntityType,\n byId || '',\n entityType,\n undefined,\n chainEntityQuery,\n );\n const state = monoriseStore((state) => state.mutual[stateKey]);\n const { dataMap, isFirstFetched, lastKey } = state || {\n dataMap: new Map(),\n };\n const [mutuals, setMutuals] = useState<Mutual<B, T>[]>([]);\n const requestKey = getMutualRequestKey(\n 'list',\n byEntityType,\n entityType,\n byId || '',\n undefined,\n chainEntityQuery,\n );\n const isLoading = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n\n useEffect(() => {\n if (byEntityType && entityType && byId && (!isFirstFetched || opts?.forceFetch)) {\n listEntitiesByEntity(\n byEntityType,\n entityType,\n byId,\n { ...opts, stateKey },\n chainEntityQuery,\n );\n }\n }, [\n isFirstFetched,\n byEntityType,\n byId,\n entityType,\n opts,\n chainEntityQuery,\n stateKey,\n opts?.forceFetch,\n opts?.noData,\n ]);\n\n useEffect(() => {\n const dataMapArray = Array.from(dataMap.values());\n if (\n dataMap.size !== mutuals?.length ||\n dataMapArray.some(\n (item, index) =>\n JSON.stringify(item) !== JSON.stringify(mutuals[index]),\n )\n ) {\n setMutuals(dataMapArray as Mutual<B, T>[]);\n }\n }, [dataMap, dataMap.size, mutuals?.length]);\n\n return {\n mutuals,\n mutualsMap: dataMap as Map<string, Mutual<B, T>>,\n isLoading,\n requestKey,\n error,\n isFirstFetched,\n lastKey,\n refetch: async () => {\n if (byEntityType && entityType && byId) {\n return await listEntitiesByEntity(\n byEntityType,\n entityType,\n byId,\n {\n ...opts,\n forceFetch: true,\n stateKey,\n },\n chainEntityQuery,\n );\n }\n },\n ...(lastKey && {\n listMore: () => {\n if (byEntityType && entityType && byId) {\n listEntitiesByEntity(\n byEntityType,\n entityType,\n byId,\n {\n ...opts,\n forceFetch: true,\n params: { ...opts.params, lastKey },\n stateKey,\n },\n chainEntityQuery,\n );\n }\n },\n }),\n };\n };\n\n // Order a loaded tag slice the same way the server does, so optimistic\n // edits/adjusts land in their true position instead of appending to the end.\n // The backend queries tags with ScanIndexForward:false — i.e. descending by\n // the tag sort key `${sortValue}#${entityType}#${entityId}` (see\n // TaggedEntity.get sk()). We rebuild that exact key per entity from the tag's\n // processor and sort descending, reproducing DynamoDB's ordering (sortValue\n // first, entityId tiebreak, identical string coercion). This only re-orders\n // the loaded window; on a paginated list an item whose new sortValue belongs\n // on an unfetched page may sit at the boundary until the next fetch — a\n // per-user, self-healing approximation, strictly better than not sorting.\n const sortTaggedEntitiesLikeServer = <T extends Entity>(\n arr: CreatedEntity<T>[],\n entityType: Entity,\n tagName: string,\n group?: string,\n ): CreatedEntity<T>[] => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const tagConfig = (monoriseStore.getState().config[entityType] as any)\n ?.tags?.find((t: { name: string }) => t.name === tagName);\n\n const keyOf = (entity: CreatedEntity<T>): string => {\n let sortValue: unknown;\n if (tagConfig?.processor) {\n const results = tagConfig.processor(entity) as {\n group?: string;\n sortValue?: unknown;\n }[];\n const match = group\n ? results.find((r) => r.group === group)\n : results[0];\n sortValue = match?.sortValue;\n }\n return `${sortValue ? `${sortValue}#` : ''}${entityType}#${entity.entityId}`;\n };\n\n return arr\n .map((entity) => ({ entity, key: keyOf(entity) }))\n .sort((a, b) => (a.key === b.key ? 0 : a.key < b.key ? 1 : -1))\n .map((x) => x.entity);\n };\n\n const useTaggedEntities = <T extends Entity>(\n entityType: T,\n tagName: string,\n opts: CommonOptions & { params?: ListEntitiesByTagParams } = {},\n ) => {\n const { params } = opts || {};\n const stateKey = getTagStateKey(entityType, tagName, params);\n const state = monoriseStore((state) => state.tag[stateKey]);\n const { dataMap, isFirstFetched, lastKey } = state || {\n dataMap: new Map(),\n };\n const [entities, setEntities] = useState<CreatedEntity<T>[]>([]);\n const requestKey = getTagRequestKey('list', entityType, tagName, params);\n const isLoading = useLoadStore(requestKey);\n const error = useErrorStore(requestKey);\n\n useEffect(() => {\n if (entityType && tagName && Object.keys(params).length > 0) {\n listEntitiesByTag(entityType, tagName, opts);\n }\n }, [entityType, opts, tagName, params, opts?.forceFetch]);\n\n useEffect(() => {\n const dataMapArray = sortTaggedEntitiesLikeServer(\n Array.from(dataMap.values()) as CreatedEntity<T>[],\n entityType,\n tagName,\n params?.group,\n );\n if (\n dataMap.size !== entities?.length ||\n dataMapArray.some(\n (item, index) =>\n JSON.stringify(item) !== JSON.stringify(entities[index]),\n )\n ) {\n setEntities(dataMapArray);\n }\n }, [dataMap, dataMap.size, entities?.length]);\n\n return {\n entities,\n entitiesMap: dataMap as Map<string, CreatedEntity<T>>,\n isLoading,\n requestKey,\n error,\n isFirstFetched,\n lastKey,\n refetch: async () => {\n if (entityType && tagName && params?.group) {\n return await listEntitiesByTag(entityType, tagName, {\n ...opts,\n forceFetch: true,\n });\n }\n },\n listMore: async () => {\n if (entityType && tagName && params?.group) {\n return await listEntitiesByTag(entityType, tagName, {\n ...opts,\n forceFetch: true,\n params: { ...params, lastKey },\n });\n }\n },\n };\n };\n\n const useEntityState = <T extends Entity>(entityType: T) => {\n return monoriseStore((state) => state.entity[entityType]);\n };\n\n const updateLocalTaggedEntity = <T extends Entity>(\n entityType: T,\n entityId: string,\n tagName: string,\n data: Partial<DraftEntity<T>> = {},\n params?: ListEntitiesByTagParams,\n ) => {\n const tagKey = getTagStateKey(\n entityType,\n tagName,\n params as Record<string, string>,\n );\n\n monoriseStore.setState(\n produce((state) => {\n const entity = state.tag[tagKey]?.dataMap?.get(entityId);\n if (entity) {\n state.tag[tagKey].dataMap.set(entityId, {\n ...entity,\n data: { ...entity.data, ...data },\n });\n }\n }),\n undefined,\n `mr/tag/local-update/${entityType}/${entityId}`,\n );\n };\n\n const deleteLocalTaggedEntity = <T extends Entity>(\n entityType: T,\n entityId: string,\n tagName: string,\n params?: ListEntitiesByTagParams,\n ) => {\n const tagKey = getTagStateKey(\n entityType,\n tagName,\n params as Record<string, string>,\n );\n\n monoriseStore.setState(\n produce((state) => {\n if (state.tag[tagKey]?.dataMap?.has(entityId)) {\n state.tag[tagKey].dataMap.delete(entityId);\n }\n }),\n undefined,\n `mr/tag/local-delete/${entityType}/${entityId}`,\n );\n };\n\n return {\n listMoreEntities,\n createEntity,\n upsertEntity,\n getEntity,\n editEntity,\n adjustEntity,\n deleteEntity,\n executeTransaction,\n getMutual,\n updateLocalEntity,\n createMutual,\n createLocalMutual,\n upsertLocalMutual,\n editMutual,\n deleteMutual,\n deleteLocalMutual,\n useCreateEntity,\n useUpsertEntity,\n useEditEntity,\n useAdjustEntity,\n useDeleteEntity,\n useExecuteTransaction,\n useCreateMutual,\n useEditMutual,\n useDeleteMutual,\n useEntity,\n useEntityByUniqueField,\n useEntities,\n useMutual,\n useMutuals,\n useTaggedEntities,\n useEntityState,\n updateLocalTaggedEntity,\n deleteLocalTaggedEntity,\n };\n};\n\nexport { initCoreActions };\n\nexport type CoreActions = ReturnType<typeof initCoreActions>;\n","import type { Entity } from '@monorise/base';\nimport { nanoid } from 'nanoid';\n\nexport const convertToMap = <T extends Record<string, any>>(\n data: T[],\n mapKey: string,\n) => {\n const map = new Map();\n\n for (const i in data) {\n map.set(data[i][mapKey], data[i]);\n }\n\n return map;\n};\n\nexport const getMutualStateKey = (\n byEntity: Entity,\n byEntityId: string | null,\n entity: Entity,\n entityId?: string,\n chainEntityQuery?: string,\n) => {\n return `${byEntity}/${byEntityId}/${entity}${entityId ? `/${entityId}` : ''}${chainEntityQuery ? `?${chainEntityQuery}` : ''}`;\n};\n\n// inverse of getMutualStateKey — the chain query is stripped off first so that\n// it never leaks into the trailing path segment\nexport const parseMutualStateKey = (stateKey: string) => {\n const queryIndex = stateKey.indexOf('?');\n const path = queryIndex === -1 ? stateKey : stateKey.slice(0, queryIndex);\n const chainEntityQuery =\n queryIndex === -1 ? undefined : stateKey.slice(queryIndex + 1);\n const [byEntity, byEntityId, entity, entityId] = path.split('/');\n\n return {\n byEntity: byEntity as unknown as Entity,\n byEntityId,\n entity: entity as unknown as Entity,\n entityId,\n chainEntityQuery,\n };\n};\n\nexport const getTagStateKey = (\n entityType: Entity,\n tagName: string,\n params: Record<string, string> = {},\n) => {\n const { lastKey, ...stateParams } = params;\n\n const paramsKey = Object.keys(stateParams)\n .map((key) => `${key}:${stateParams[key]}`)\n .join('/');\n\n return `${entityType}/${tagName}/${paramsKey}`;\n};\n\nexport const getUniqueFieldStateKey = (\n fieldName: string,\n fieldValue: string,\n) => {\n return `${fieldName}/${fieldValue}`;\n};\n\nexport const getEntityRequestKey = (\n mode: 'create' | 'upsert' | 'edit' | 'adjust' | 'delete' | 'get' | 'list' | 'search',\n entityType: Entity,\n entityId?: string,\n) => {\n return `entity/${entityType}/${mode}${entityId ? `/${entityId}` : ''}`;\n};\n\n/**\n * Creates the key for one non-idempotent mutation call. The stable key stays\n * in the prefix for debugging while the nonce prevents an unrelated write\n * from receiving this call's in-flight promise.\n */\nexport const createMutationCallRequestKey = (requestKey: string) =>\n `${requestKey}#${nanoid()}`;\n\nexport const getMutualRequestKey = (\n mode: 'create' | 'update' | 'delete' | 'get' | 'list',\n byEntityType: Entity,\n entityType: Entity,\n byEntityId: string | null,\n entityId?: string,\n chainEntityQuery?: string,\n) => {\n return `mutual/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId, chainEntityQuery)}/${mode}`;\n};\n\nexport const getTagRequestKey = (\n mode: 'list',\n entityType: Entity,\n tagName: string,\n params: Record<string, string> = {},\n) => {\n return `tag/${getTagStateKey(entityType, tagName, params)}/${mode}`;\n};\n\nexport const getUniqueFieldRequestKey = (\n entityType: Entity,\n fieldName: string,\n value: string,\n) => {\n return `entity/${entityType}/unique/${getUniqueFieldStateKey(fieldName, value)}`;\n};\n","import type { Entity, EntitySchemaMap } from '@monorise/base';\nimport {\n createMutationCallRequestKey,\n getEntityRequestKey,\n getMutualRequestKey,\n} from '../lib/utils';\n\nexport type TransactionCreateEntity<T extends Entity = Entity> = {\n operation: 'createEntity';\n entityType: T;\n entityId?: string;\n payload: EntitySchemaMap[T];\n};\n\nexport type TransactionUpdateEntity<T extends Entity = Entity> = {\n operation: 'updateEntity';\n entityType: T;\n entityId: string;\n payload: Partial<EntitySchemaMap[T]>;\n condition?: string;\n};\n\nexport type TransactionAdjustEntity<T extends Entity = Entity> = {\n operation: 'adjustEntity';\n entityType: T;\n entityId: string;\n adjustments: Record<string, number>;\n condition?: string;\n};\n\nexport type TransactionDeleteEntity<T extends Entity = Entity> = {\n operation: 'deleteEntity';\n entityType: T;\n entityId: string;\n};\n\nexport type TransactionCreateMutual<\n B extends Entity = Entity,\n T extends Entity = Entity,\n> = {\n operation: 'createMutual';\n byEntityType: B;\n byEntityId: string;\n entityType: T;\n entityId: string;\n payload?: Record<string, unknown>;\n};\n\nexport type TransactionUpdateMutual<\n B extends Entity = Entity,\n T extends Entity = Entity,\n> = {\n operation: 'updateMutual';\n byEntityType: B;\n byEntityId: string;\n entityType: T;\n entityId: string;\n payload: Record<string, unknown>;\n};\n\nexport type TransactionDeleteMutual<\n B extends Entity = Entity,\n T extends Entity = Entity,\n> = {\n operation: 'deleteMutual';\n byEntityType: B;\n byEntityId: string;\n entityType: T;\n entityId: string;\n};\n\nexport type TransactionOperation =\n | TransactionCreateEntity\n | TransactionUpdateEntity\n | TransactionAdjustEntity\n | TransactionDeleteEntity\n | TransactionCreateMutual\n | TransactionUpdateMutual\n | TransactionDeleteMutual;\n\n// Mirrors packages/core/types/transaction.ts's TransactionResultEntry/Result —\n// the client can't import from @monorise/core (server-only, pulls in the AWS\n// SDK), so the response shape is duplicated here.\nexport type TransactionResultEntry<T extends Entity = Entity> = {\n operation: TransactionOperation['operation'];\n entityType: T;\n entityId: string;\n data?: Record<string, unknown>;\n createdAt?: string;\n updatedAt?: string;\n // createMutual / updateMutual / deleteMutual entries only.\n byEntityType?: Entity;\n byEntityId?: string;\n mutualId?: string;\n mutualData?: Record<string, unknown>;\n mutualUpdatedAt?: string;\n};\n\nexport type TransactionResult = {\n results: TransactionResultEntry[];\n};\n\n// The requestKey a single-entity call for this same op's target would have\n// used (getEntityRequestKey('edit'|'adjust'|'delete', entityType, entityId),\n// or ('create', entityType) for a create — which never includes an id, same\n// as createEntity's own key). Every op already carries a real entityId\n// except an id-less create, so this never needs to invent one.\nexport const getTransactionOperationRequestKey = (\n op: TransactionOperation,\n): string => {\n switch (op.operation) {\n case 'createEntity':\n return getEntityRequestKey('create', op.entityType);\n case 'updateEntity':\n return getEntityRequestKey('edit', op.entityType, op.entityId);\n case 'adjustEntity':\n return getEntityRequestKey('adjust', op.entityType, op.entityId);\n case 'deleteEntity':\n return getEntityRequestKey('delete', op.entityType, op.entityId);\n // Same keys the standalone createMutual / editMutual / deleteMutual calls\n // use, so a component watching one sees the transaction's loading/error.\n case 'createMutual':\n return getMutualRequestKey(\n 'create',\n op.byEntityType,\n op.entityType,\n op.byEntityId,\n op.entityId,\n );\n case 'updateMutual':\n return getMutualRequestKey(\n 'update',\n op.byEntityType,\n op.entityType,\n op.byEntityId,\n op.entityId,\n );\n case 'deleteMutual':\n return getMutualRequestKey(\n 'delete',\n op.byEntityType,\n op.entityType,\n op.byEntityId,\n op.entityId,\n );\n }\n};\n\n// State keys driven by one transaction operation. createMutual additionally\n// drives the pre-hook broad key so existing useLoadStore/useErrorStore callers\n// that omit the target id keep observing the request.\nexport const getTransactionOperationRequestKeys = (\n op: TransactionOperation,\n): string[] => {\n const requestKey = getTransactionOperationRequestKey(op);\n if (op.operation !== 'createMutual') return [requestKey];\n\n return [\n requestKey,\n getMutualRequestKey(\n 'create',\n op.byEntityType,\n op.entityType,\n op.byEntityId,\n ),\n ];\n};\n\n// Stable key shared by every observer of this transaction shape. Unlike the\n// call key below, this key is never used to deduplicate HTTP requests.\nexport const getTransactionRequestKey = (\n operations: TransactionOperation[],\n): string =>\n `transaction/${operations.map(getTransactionOperationRequestKey).join('|')}`;\n\n// The requestKey for the ONE real HTTP call `executeTransaction` makes.\n//\n// UNIQUE PER CALL, deliberately. lib/api.ts's `makeRequest` hands any caller\n// with a matching `requestKey` the in-flight promise instead of issuing a\n// second request, which is right for idempotent reads and for \"the user\n// double-clicked Save\" -- and wrong for a transaction, which is a batch of\n// NON-idempotent writes. A key derived only from the operation shapes is\n// identical for every structurally identical batch, so two writes issued\n// close together (scoring twice with the same statistic, appending two events\n// to one log) silently collapse into one: the second caller awaits the first\n// call's promise, is told it succeeded, and its operations are never sent.\n//\n// Found end-to-end -- three scores recorded, one observed.\n//\n// The operation shapes stay in the key for debuggability, and the\n// `transaction/` namespace still keeps it from colliding with a\n// single-entity action's own key. A caller that genuinely wants dedupe can\n// still pass an explicit `opts.requestKey`.\nexport const createTransactionCallRequestKey = (\n operations: TransactionOperation[],\n): string => createMutationCallRequestKey(getTransactionRequestKey(operations));\n\n// NOTE: packages/core/helpers/transactional.ts is the server-side copy of\n// this builder. Both emit the same wire format for the execute-transaction\n// endpoint — keep operation shapes in sync when changing either file.\nexport const transactional = {\n createEntity: <T extends Entity>(\n entityType: T,\n payload: EntitySchemaMap[T] & { entityId?: string },\n ): TransactionCreateEntity<T> => {\n const { entityId, ...rest } = payload as EntitySchemaMap[T] & {\n entityId?: string;\n };\n return {\n operation: 'createEntity',\n entityType,\n payload: rest as EntitySchemaMap[T],\n ...(entityId !== undefined && { entityId }),\n };\n },\n\n updateEntity: <T extends Entity>(\n entityType: T,\n entityId: string,\n payload: Partial<EntitySchemaMap[T]> & { $condition?: string },\n ): TransactionUpdateEntity<T> => {\n const { $condition, ...rest } = payload as Partial<EntitySchemaMap[T]> & {\n $condition?: string;\n };\n return {\n operation: 'updateEntity',\n entityType,\n entityId,\n payload: rest as Partial<EntitySchemaMap[T]>,\n ...($condition !== undefined && { condition: $condition }),\n };\n },\n\n adjustEntity: <T extends Entity>(\n entityType: T,\n entityId: string,\n adjustments: Record<string, number> & { $condition?: string },\n ): TransactionAdjustEntity<T> => {\n const { $condition, ...rest } = adjustments;\n return {\n operation: 'adjustEntity',\n entityType,\n entityId,\n adjustments: rest,\n ...($condition !== undefined && { condition: $condition }),\n };\n },\n\n deleteEntity: <T extends Entity>(\n entityType: T,\n entityId: string,\n ): TransactionDeleteEntity<T> => ({\n operation: 'deleteEntity',\n entityType,\n entityId,\n }),\n\n // Same argument order as the standalone createMutual / editMutual /\n // deleteMutual actions.\n createMutual: <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload?: Record<string, unknown>,\n ): TransactionCreateMutual<B, T> => ({\n operation: 'createMutual',\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n ...(payload !== undefined && { payload }),\n }),\n\n updateMutual: <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload: Record<string, unknown>,\n ): TransactionUpdateMutual<B, T> => ({\n operation: 'updateMutual',\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n payload,\n }),\n\n deleteMutual: <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n ): TransactionDeleteMutual<B, T> => ({\n operation: 'deleteMutual',\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n }),\n};\n","import type { CreatedEntity, Entity, EntitySchemaMap } from '@monorise/base';\nimport type { Mutual, MutualData } from '../types/mutual.type';\n\nexport const constructLocal = (\n entityType: Entity,\n entityId: string,\n data: any,\n): CreatedEntity<Entity> => {\n return {\n entityType: entityType as unknown as string,\n entityId,\n data,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n};\n\nexport const constructMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n byEntityId: string,\n entityType: T,\n entityId: string,\n mutualData: Partial<MutualData<B, T>>,\n data: EntitySchemaMap[T],\n): Mutual => {\n return {\n mutualId: `${byEntityId}-${entityId}`,\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n mutualData,\n data,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n mutualUpdatedAt: new Date().toISOString(),\n };\n};\n\n// A mutual is stored under two cache keys — one per direction. When we mirror\n// a record from the `BY/byId/OTHER` side to the `OTHER/otherId/BY` side, the\n// `data` field has to be substituted: on the original side `data` describes\n// the OTHER entity (the one at `entityType/entityId`); after flipping, the\n// new `entityType/entityId` points to what *was* the BY entity, so `data`\n// must now describe that entity. Callers look up the BY entity from the\n// entity store and pass its data in here. `{}` is an accepted fallback for\n// the case where the BY entity hasn't been hydrated locally yet — better to\n// surface an empty record than to leak the OTHER entity's fields onto a\n// record that no longer describes it.\nexport const flipMutual = (\n mutual: Mutual,\n byEntityData: Record<string, unknown>,\n): Mutual => {\n return {\n ...mutual,\n entityId: mutual.byEntityId,\n entityType: mutual.byEntityType,\n byEntityId: mutual.entityId,\n byEntityType: mutual.entityType,\n data: byEntityData as Mutual['data'],\n };\n};\n\nexport const byMutualIndex = (a: Mutual<any, any>, b: Mutual<any, any>) => {\n return a.mutualData.index - b.mutualData.index;\n};\n\nexport const byEntityId = (a: CreatedEntity<any>, b: CreatedEntity<any>) => {\n if (b.entityId < a.entityId) return -1;\n return 1;\n};\n\nexport const constructOrderByIndex = (mutuals: Mutual<any, any>[]) => {\n return mutuals.sort(byMutualIndex).map((mutual) => mutual.entityId);\n};\n\nexport const injectFields = <T extends Entity>(\n entity: CreatedEntity<T> | undefined,\n fields: Record<string, any>,\n): CreatedEntity<T> | undefined => {\n return entity\n ? {\n ...entity,\n data: {\n ...entity.data,\n ...fields,\n },\n }\n : undefined;\n};\n","import type { CreatedEntity, Entity } from '@monorise/base';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { produce } from 'immer';\nimport { parseMutualStateKey } from '../lib/utils';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type {\n ConnectionState,\n ServerMessage,\n WebSocketManager,\n} from '../websocket';\n\nexport interface UseEntitySocketReturn<T extends Entity> {\n entities: CreatedEntity<T>[];\n isLoading: boolean;\n isFetchingMore: boolean;\n isSubscribed: boolean;\n error: Error | null;\n isRefreshing: boolean;\n fetchMore: () => Promise<void>;\n hasMore: boolean;\n}\n\nexport interface UseMutualSocketReturn<T extends Entity> {\n mutuals: unknown[];\n isLoading: boolean;\n isFetchingMore: boolean;\n isSubscribed: boolean;\n error: Error | null;\n isRefreshing: boolean;\n fetchMore: () => Promise<void>;\n hasMore: boolean;\n}\n\nexport interface UseEntityFeedOptions {\n entityType: Entity;\n entityId: string;\n ticketEndpoint?: string;\n}\n\nexport interface UseEntityFeedReturn {\n isConnected: boolean;\n error: { code: string; message: string } | null;\n}\n\nlet globalWsManager: WebSocketManager | null = null;\nlet wsEndpoint: string | undefined;\n\nexport const initializeWebSocketManager = (\n WebSocketManagerClass: typeof WebSocketManager,\n endpoint: string,\n token?: string,\n) => {\n if (globalWsManager) return globalWsManager;\n\n wsEndpoint = endpoint;\n globalWsManager = new WebSocketManagerClass(endpoint, token || '');\n globalWsManager.connect();\n\n return globalWsManager;\n};\n\nexport const getWebSocketManager = () => globalWsManager;\n\nexport const initWebSocketActions = (\n monoriseStore: MonoriseStore,\n httpActions?: {\n listEntities: <T extends Entity>(\n entityType: T,\n params?: { limit?: number; lastKey?: string },\n ) => Promise<{ data: CreatedEntity<T>[]; lastKey?: string }>;\n listEntitiesByEntity: <B extends Entity, T extends Entity>(\n byEntityType: B,\n byEntityId: string,\n entityType: T,\n params?: { limit?: number; lastKey?: string },\n ) => Promise<{ entities: unknown[]; lastKey?: string }>;\n },\n) => {\n const useEntitySocket = <T extends Entity>(\n entityType: T,\n opts: { limit?: number; skipInitialFetch?: boolean } = {},\n ): UseEntitySocketReturn<T> => {\n const { limit = 20, skipInitialFetch = false } = opts;\n const [isLoading, setIsLoading] = useState(!skipInitialFetch);\n const [isFetchingMore, setIsFetchingMore] = useState(false);\n const [isRefreshing, setIsRefreshing] = useState(false);\n const [isSubscribed, setIsSubscribed] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [hasMore, setHasMore] = useState(true);\n const lastKeyRef = useRef<string | undefined>(undefined);\n const isFirstFetchRef = useRef(true);\n\n const entities = monoriseStore((state) => {\n const entityState = state.entity[entityType];\n return Array.from(entityState?.dataMap?.values() || []);\n });\n\n const fetchData = async (type: 'initial' | 'more' | 'refresh') => {\n if (!httpActions) return;\n if (type === 'more') {\n setIsFetchingMore(true);\n } else if (type === 'refresh') {\n setIsRefreshing(true);\n } else {\n setIsLoading(true);\n }\n setError(null);\n\n try {\n const fetchLastKey = type === 'refresh' ? undefined : lastKeyRef.current;\n const result = await httpActions.listEntities(entityType, {\n limit,\n lastKey: fetchLastKey,\n });\n\n monoriseStore.setState(\n produce((state) => {\n if (type === 'refresh') {\n state.entity[entityType as unknown as string].dataMap.clear();\n }\n for (const entity of result.data) {\n state.entity[entityType as unknown as string].dataMap.set(entity.entityId, entity);\n }\n state.entity[entityType as unknown as string].isFirstFetched = true;\n state.entity[entityType as unknown as string].lastKey = result.lastKey;\n }),\n );\n\n lastKeyRef.current = result.lastKey;\n setHasMore(!!result.lastKey);\n } catch (err) {\n setError(err instanceof Error ? err : new Error('Failed to fetch'));\n } finally {\n setIsLoading(false);\n setIsFetchingMore(false);\n setIsRefreshing(false);\n }\n };\n\n useEffect(() => {\n if (skipInitialFetch) return;\n fetchData('initial');\n }, [entityType, limit, skipInitialFetch]);\n\n useEffect(() => {\n if (!globalWsManager) {\n setIsSubscribed(false);\n return;\n }\n\n const subKey = globalWsManager.subscribeEntityType(entityType as unknown as string);\n setIsSubscribed(true);\n\n let wasConnected = false;\n const unsubscribeState = globalWsManager.onStateChange((state) => {\n if (state === 'connected' && wasConnected === false && !isFirstFetchRef.current) {\n fetchData('refresh');\n }\n wasConnected = state === 'connected';\n isFirstFetchRef.current = false;\n });\n\n const unsubscribeMessage = globalWsManager.onMessage(\n (msg: ServerMessage) => {\n if (\n msg.type === 'entity.created' ||\n msg.type === 'entity.updated' ||\n msg.type === 'entity.deleted'\n ) {\n const payload = msg.payload as {\n entityType: string;\n entityId: string;\n data?: CreatedEntity<T>;\n };\n\n if (payload.entityType !== (entityType as unknown as string)) return;\n\n if (msg.type === 'entity.created' || msg.type === 'entity.updated') {\n if (payload.data) {\n monoriseStore.setState(\n produce((state) => {\n const key = entityType as unknown as string;\n if (!state.entity[key]) {\n state.entity[key] = { dataMap: new Map(), isFirstFetched: false, lastKey: undefined };\n }\n state.entity[key].dataMap.set(\n payload.entityId,\n payload.data!,\n );\n }),\n );\n }\n } else if (msg.type === 'entity.deleted') {\n monoriseStore.setState(\n produce((state) => {\n const key = entityType as unknown as string;\n if (state.entity[key]?.dataMap) {\n state.entity[key].dataMap.delete(payload.entityId);\n }\n }),\n );\n }\n }\n },\n );\n\n return () => {\n globalWsManager?.unsubscribeEntityType(subKey);\n unsubscribeState();\n unsubscribeMessage();\n setIsSubscribed(false);\n };\n }, [entityType]);\n\n const fetchMore = async () => {\n if (!hasMore || isFetchingMore) return;\n await fetchData('more');\n };\n\n return {\n entities,\n isLoading,\n isFetchingMore,\n isSubscribed,\n error,\n isRefreshing,\n fetchMore,\n hasMore,\n };\n };\n\n const useMutualSocket = <B extends Entity, T extends Entity>(\n byEntityType: B,\n byEntityId: string | undefined,\n mutualEntityType: T,\n opts: { limit?: number; skipInitialFetch?: boolean } = {},\n ): UseMutualSocketReturn<T> => {\n const { limit = 20, skipInitialFetch = false } = opts;\n const [isLoading, setIsLoading] = useState(\n !skipInitialFetch && !!byEntityId,\n );\n const [isFetchingMore, setIsFetchingMore] = useState(false);\n const [isRefreshing, setIsRefreshing] = useState(false);\n const [isSubscribed, setIsSubscribed] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [hasMore, setHasMore] = useState(true);\n const lastKeyRef = useRef<string | undefined>(undefined);\n const isFirstFetchRef = useRef(true);\n\n const mutualKey = byEntityId\n ? `${byEntityType}/${byEntityId}/${mutualEntityType}`\n : '';\n\n const mutuals = monoriseStore((state) => {\n return Array.from(state.mutual[mutualKey]?.dataMap?.values() || []);\n });\n\n const fetchData = async (type: 'initial' | 'more' | 'refresh') => {\n if (!byEntityId || !httpActions) return;\n\n if (type === 'more') {\n setIsFetchingMore(true);\n } else if (type === 'refresh') {\n setIsRefreshing(true);\n } else {\n setIsLoading(true);\n }\n setError(null);\n\n try {\n const fetchLastKey = type === 'refresh' ? undefined : lastKeyRef.current;\n const result = await httpActions.listEntitiesByEntity(\n byEntityType,\n byEntityId,\n mutualEntityType,\n { limit, lastKey: fetchLastKey },\n );\n\n monoriseStore.setState(\n produce((state) => {\n if (!state.mutual[mutualKey]) {\n state.mutual[mutualKey] = {\n dataMap: new Map(),\n isFirstFetched: true,\n lastKey: undefined as unknown as string,\n };\n }\n if (type === 'refresh') {\n state.mutual[mutualKey].dataMap.clear();\n }\n for (const entity of result.entities) {\n const e = entity as any;\n state.mutual[mutualKey].dataMap.set(e.entityId, entity);\n }\n state.mutual[mutualKey].lastKey = result.lastKey;\n }),\n );\n\n lastKeyRef.current = result.lastKey;\n setHasMore(!!result.lastKey);\n } catch (err) {\n setError(err instanceof Error ? err : new Error('Failed to fetch'));\n } finally {\n setIsLoading(false);\n setIsFetchingMore(false);\n setIsRefreshing(false);\n }\n };\n\n useEffect(() => {\n if (skipInitialFetch || !byEntityId) {\n setIsLoading(false);\n return;\n }\n lastKeyRef.current = undefined;\n setHasMore(true);\n isFirstFetchRef.current = true;\n fetchData('initial');\n }, [byEntityType, byEntityId, mutualEntityType, limit, skipInitialFetch]);\n\n useEffect(() => {\n if (!globalWsManager || !byEntityId) {\n setIsSubscribed(false);\n return;\n }\n\n const subKey = globalWsManager.subscribeMutualType(\n byEntityType as unknown as string,\n byEntityId,\n mutualEntityType as unknown as string,\n );\n setIsSubscribed(true);\n\n let wasConnected = false;\n const unsubscribeState = globalWsManager.onStateChange((state) => {\n if (state === 'connected' && wasConnected === false && !isFirstFetchRef.current) {\n fetchData('refresh');\n }\n wasConnected = state === 'connected';\n isFirstFetchRef.current = false;\n });\n\n const unsubscribeMessage = globalWsManager.onMessage(\n (msg: ServerMessage) => {\n if (\n msg.type === 'mutual.created' ||\n msg.type === 'mutual.updated' ||\n msg.type === 'mutual.deleted'\n ) {\n const payload = msg.payload as {\n byEntityType: string;\n byEntityId: string;\n mutualEntityType: string;\n entityId: string;\n data?: unknown;\n };\n\n if (\n payload.byEntityType !== (byEntityType as unknown as string) ||\n payload.byEntityId !== byEntityId ||\n payload.mutualEntityType !== (mutualEntityType as unknown as string)\n ) {\n return;\n }\n\n if (\n msg.type === 'mutual.created' ||\n msg.type === 'mutual.updated'\n ) {\n if (payload.data) {\n monoriseStore.setState(\n produce((state) => {\n if (!state.mutual[mutualKey]) {\n state.mutual[mutualKey] = {\n dataMap: new Map(),\n isFirstFetched: true,\n lastKey: undefined as unknown as string,\n };\n }\n state.mutual[mutualKey].dataMap.set(\n payload.entityId,\n payload.data!,\n );\n }),\n );\n }\n } else if (msg.type === 'mutual.deleted') {\n monoriseStore.setState(\n produce((state) => {\n state.mutual[mutualKey]?.dataMap.delete(payload.entityId);\n }),\n );\n }\n }\n },\n );\n\n return () => {\n globalWsManager?.unsubscribeMutualType(subKey);\n unsubscribeState();\n unsubscribeMessage();\n setIsSubscribed(false);\n };\n }, [byEntityType, byEntityId, mutualEntityType, mutualKey]);\n\n const fetchMore = async () => {\n if (!hasMore || isFetchingMore) return;\n await fetchData('more');\n };\n\n return {\n mutuals,\n isLoading,\n isFetchingMore,\n isSubscribed,\n error,\n isRefreshing,\n fetchMore,\n hasMore,\n };\n };\n\n const useEphemeralSocket = <T = unknown>(\n channel: string | undefined,\n opts?: {\n onMessage?: (data: T, senderId?: string) => void;\n },\n ): {\n isSubscribed: boolean;\n send: (data: T) => void;\n } => {\n const [isSubscribed, setIsSubscribed] = useState(false);\n\n useEffect(() => {\n if (!globalWsManager || !channel) {\n setIsSubscribed(false);\n return;\n }\n\n const subKey = globalWsManager.subscribeEphemeral(channel);\n setIsSubscribed(true);\n\n const unsubscribeMessage = globalWsManager.onMessage(\n (msg: ServerMessage) => {\n if (msg.type === 'ephemeral') {\n const payload = msg.payload as {\n channel: string;\n data: T;\n senderId?: string;\n };\n if (payload.channel !== channel) return;\n opts?.onMessage?.(payload.data, payload.senderId);\n }\n },\n );\n\n return () => {\n globalWsManager?.unsubscribeEphemeral(subKey);\n unsubscribeMessage();\n setIsSubscribed(false);\n };\n }, [channel]);\n\n const send = useCallback(\n (data: T) => {\n if (!globalWsManager || !channel) return;\n globalWsManager.sendEphemeral(channel, data);\n },\n [channel],\n );\n\n return { isSubscribed, send };\n };\n\n /**\n * Subscribe to an entity's real-time feed.\n *\n * Fetches a ticket (via ticketEndpoint or default monorise route through catch-all proxy),\n * establishes a WebSocket connection, and auto-updates entity/mutual stores.\n * Handles ticket refresh and auto-resync on reconnect.\n *\n * @example\n * ```tsx\n * // Internal app (uses catch-all proxy)\n * useEntityFeed({ entityType: Entity.USER, entityId: userId });\n *\n * // Client-facing app (custom auth endpoint)\n * useEntityFeed({ entityType: Entity.USER, entityId: userId, ticketEndpoint: '/api/ws/ticket' });\n * ```\n */\n const useEntityFeed = (opts: UseEntityFeedOptions): UseEntityFeedReturn => {\n const { entityType, entityId, ticketEndpoint } = opts;\n const [isConnected, setIsConnected] = useState(false);\n const [error, setError] = useState<{ code: string; message: string } | null>(null);\n const refreshTimerRef = useRef<NodeJS.Timeout | null>(null);\n const hasConnectedOnceRef = useRef(false);\n\n /**\n * Refill the mutual lists this feed's subject already has loaded.\n *\n * Deliberately only refetches slices that were fetched before\n * (`isFirstFetched`): a reconnect should close gaps in what the caller is\n * already showing, not start pulling lists nobody asked for. Single-mutual\n * entries (those with a trailing entityId) are skipped -- they are one row,\n * not a paginated list.\n */\n const resyncFromHttp = async () => {\n if (!httpActions) return;\n const snapshot = monoriseStore.getState();\n const keys = Object.keys(snapshot.mutual ?? {});\n\n for (const key of keys) {\n const parsed = parseMutualStateKey(key);\n if (parsed.entityId) continue;\n if (parsed.byEntityId !== entityId) continue;\n if (!snapshot.mutual[key]?.isFirstFetched) continue;\n\n try {\n const result = await httpActions.listEntitiesByEntity(\n parsed.byEntity,\n parsed.byEntityId as string,\n parsed.entity,\n );\n if (!isMountedRef.current) return;\n monoriseStore.setState(\n produce((draft) => {\n const slice = draft.mutual[key];\n if (!slice) return;\n slice.dataMap.clear();\n for (const mutual of result.entities as {\n entityId: string;\n }[]) {\n slice.dataMap.set(mutual.entityId, mutual);\n }\n slice.lastKey = result.lastKey;\n }),\n );\n } catch {\n // A failed refill leaves the existing rows in place, which is the\n // safer of the two wrong answers.\n }\n }\n };\n const wsManagerRef = useRef<WebSocketManager | null>(null);\n const isMountedRef = useRef(true);\n const connectingRef = useRef(false);\n const reconnectCountRef = useRef(0);\n const connectRef = useRef<() => void>(() => {});\n const lastConnectedAtRef = useRef(0);\n\n const fetchTicket = useCallback(async () => {\n try {\n const url = ticketEndpoint\n || `/api/core/ws/ticket/${entityType}/${entityId}`;\n\n const fetchOpts: RequestInit = {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n };\n\n // Only send body for custom endpoints (default route gets params from URL)\n if (ticketEndpoint) {\n fetchOpts.body = JSON.stringify({ entityType, entityId });\n }\n\n const response = await fetch(url, fetchOpts);\n\n if (response.status === 401 || response.status === 403) {\n return { error: { code: 'TICKET_UNAUTHORIZED', message: 'Unauthorized' } };\n }\n\n if (!response.ok) {\n return { error: { code: 'TICKET_FAILED', message: `HTTP ${response.status}` } };\n }\n\n const data = await response.json();\n return { data: data as { ticket: string; wsUrl: string; expiresIn: number } };\n } catch (err) {\n return { error: { code: 'TICKET_FAILED', message: (err as Error).message } };\n }\n }, [entityType, entityId, ticketEndpoint]);\n\n const connectWithTicket = useCallback(async () => {\n if (connectingRef.current) return;\n connectingRef.current = true;\n\n // Retry ticket fetch with backoff\n let result: Awaited<ReturnType<typeof fetchTicket>> | null = null;\n const maxRetries = 3;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n result = await fetchTicket();\n\n if (!isMountedRef.current) {\n connectingRef.current = false;\n return;\n }\n\n if (!result.error) break;\n\n // Don't retry auth errors\n if (result.error.code === 'TICKET_UNAUTHORIZED') break;\n\n if (attempt < maxRetries) {\n await new Promise((r) => setTimeout(r, 1000 * Math.pow(2, attempt)));\n if (!isMountedRef.current) {\n connectingRef.current = false;\n return;\n }\n }\n }\n\n if (result!.error) {\n setError(result!.error);\n setIsConnected(false);\n connectingRef.current = false;\n return;\n }\n\n setError(null);\n const { ticket, wsUrl, expiresIn } = result!.data!;\n // Disconnect existing connection\n if (wsManagerRef.current) {\n wsManagerRef.current.disconnect();\n }\n\n const { WebSocketManager: WsManagerClass } = await import('../websocket');\n\n const wsUrlWithTicket = `${wsUrl}?ticket=${encodeURIComponent(ticket)}`;\n const manager = new WsManagerClass(wsUrlWithTicket, '');\n manager.disableAutoReconnect = true;\n // Deliberately NOT assigned to `globalWsManager`. That global is the\n // shared socket behind `useEntitySocket`/`useMutualSocket` and the public\n // `getWebSocketManager()`. This one is a different connection: ticket\n // -scoped, feed-only, with auto-reconnect disabled. Pointing the shared\n // accessor at it makes those hooks subscribe on the wrong socket while\n // this hook is mounted, and leaves them holding a disconnected manager\n // after it unmounts, since cleanup only clears the local ref.\n wsManagerRef.current = manager;\n\n manager.onStateChange((state: ConnectionState) => {\n if (!isMountedRef.current) return;\n // Ignore events from old managers (stale callbacks)\n if (wsManagerRef.current !== manager) return;\n\n if (state === 'connected') {\n connectingRef.current = false;\n reconnectCountRef.current = 0;\n lastConnectedAtRef.current = Date.now();\n setIsConnected(true);\n setError(null);\n\n // Broadcasts sent while the socket was down are gone -- the server\n // does not replay them -- so a reconnect has to refill from HTTP or\n // the stores silently keep stale rows. Skipped on the FIRST connect,\n // where whatever loaded the list has already fetched it.\n if (hasConnectedOnceRef.current) {\n void resyncFromHttp();\n }\n hasConnectedOnceRef.current = true;\n } else if (state === 'disconnected') {\n connectingRef.current = false;\n setIsConnected(false);\n\n // Only auto-reconnect if we were connected for >5s (stable connection)\n // and haven't exceeded max reconnect attempts\n // `hasConnectedOnceRef` is load-bearing here, not belt-and-braces:\n // `lastConnectedAtRef` starts at 0, so `Date.now() - 0` is ~1.8e12\n // and the >5s test passes for a socket that never opened -- burning\n // all five reconnect attempts on exactly the first-connect failure\n // this guard exists to suppress.\n const wasStable =\n hasConnectedOnceRef.current &&\n Date.now() - lastConnectedAtRef.current > 5000;\n if (wasStable && reconnectCountRef.current < 5) {\n reconnectCountRef.current++;\n const delay = 2000 * Math.pow(2, reconnectCountRef.current - 1);\n setTimeout(() => {\n if (isMountedRef.current && !connectingRef.current) {\n connectRef.current();\n }\n }, delay);\n }\n }\n });\n\n // Route feed messages into stores\n manager.onMessage((msg: ServerMessage) => {\n if (!isMountedRef.current) return;\n\n if (msg.type === 'entity.created' || msg.type === 'entity.updated') {\n const payload = msg.payload as {\n entityType: string;\n entityId: string;\n data?: any;\n };\n if (payload.data) {\n monoriseStore.setState(\n produce((state) => {\n const key = payload.entityType;\n if (!state.entity[key]) {\n state.entity[key] = { dataMap: new Map(), isFirstFetched: false, lastKey: undefined };\n }\n state.entity[key].dataMap.set(payload.entityId, payload.data);\n }),\n );\n }\n } else if (msg.type === 'entity.deleted') {\n const payload = msg.payload as { entityType: string; entityId: string };\n monoriseStore.setState(\n produce((state) => {\n state.entity[payload.entityType]?.dataMap?.delete(payload.entityId);\n }),\n );\n } else if (msg.type === 'mutual.created' || msg.type === 'mutual.updated') {\n const payload = msg.payload as {\n byEntityType: string;\n byEntityId: string;\n mutualEntityType: string;\n entityId: string;\n data?: any;\n };\n if (payload.data) {\n const mutualKey = `${payload.byEntityType}/${payload.byEntityId}/${payload.mutualEntityType}`;\n monoriseStore.setState(\n produce((state) => {\n if (!state.mutual[mutualKey]) {\n state.mutual[mutualKey] = { dataMap: new Map(), isFirstFetched: false, lastKey: undefined };\n }\n state.mutual[mutualKey].dataMap.set(payload.entityId, payload.data);\n }),\n );\n }\n } else if (msg.type === 'mutual.deleted') {\n const payload = msg.payload as {\n byEntityType: string;\n byEntityId: string;\n mutualEntityType: string;\n entityId: string;\n };\n const mutualKey = `${payload.byEntityType}/${payload.byEntityId}/${payload.mutualEntityType}`;\n monoriseStore.setState(\n produce((state) => {\n state.mutual[mutualKey]?.dataMap?.delete(payload.entityId);\n }),\n );\n }\n });\n\n manager.connect();\n\n // Schedule proactive ticket refresh\n if (refreshTimerRef.current) {\n clearTimeout(refreshTimerRef.current);\n }\n const refreshMs = Math.max((expiresIn - 120) * 1000, 60000); // refresh 2 min before expiry, minimum 1 min\n refreshTimerRef.current = setTimeout(() => {\n if (isMountedRef.current) {\n connectRef.current();\n }\n }, refreshMs);\n }, [fetchTicket]);\n\n connectRef.current = connectWithTicket;\n\n useEffect(() => {\n isMountedRef.current = true;\n\n if (entityId) {\n connectRef.current();\n }\n\n // Detect wake from sleep using periodic check\n let lastCheckTime = Date.now();\n const sleepCheckInterval = setInterval(() => {\n const now = Date.now();\n const elapsed = now - lastCheckTime;\n lastCheckTime = now;\n\n if (elapsed > 30000 && wsManagerRef.current) {\n wsManagerRef.current.disconnect();\n wsManagerRef.current = null;\n connectingRef.current = false;\n reconnectCountRef.current = 0;\n connectRef.current();\n }\n }, 5000);\n\n // Reconnect when network comes back online\n const handleOnline = () => {\n if (!isMountedRef.current) return;\n if (wsManagerRef.current?.getState() === 'connected') return;\n if (connectingRef.current) return;\n reconnectCountRef.current = 0;\n connectRef.current();\n };\n window.addEventListener('online', handleOnline);\n\n return () => {\n isMountedRef.current = false;\n clearInterval(sleepCheckInterval);\n window.removeEventListener('online', handleOnline);\n if (refreshTimerRef.current) {\n clearTimeout(refreshTimerRef.current);\n }\n if (wsManagerRef.current) {\n wsManagerRef.current.disconnect();\n wsManagerRef.current = null;\n }\n };\n }, [entityType, entityId]);\n\n return { isConnected, error };\n };\n\n return {\n useEntitySocket,\n useMutualSocket,\n useEphemeralSocket,\n useEntityFeed,\n };\n};\n\nexport type WebSocketActions = ReturnType<typeof initWebSocketActions>;\n","import request, {\n type AxiosError,\n type AxiosRequestConfig,\n type AxiosResponse,\n} from 'axios';\nimport type { AppActions } from '../actions/app.action';\nimport type { AuthActions } from '../actions/auth.action';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type { ApplicationRequestError } from '../types/api.type';\n\ntype IntercepterAxiosRequestConfig<D> = AxiosRequestConfig<D> & {\n requestKey: string;\n stateKeys?: string[];\n isInterruptive?: boolean;\n feedback?: {\n loading?: string | boolean;\n success?: ((data: any) => string) | string | boolean;\n failure?: string | boolean;\n };\n};\n\nconst initAxiosInterceptor = (store: MonoriseStore, appActions: AppActions) => {\n const { startLoading } = appActions;\n\n const axiosInstance = request.create();\n\n function makeRequest<T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n config: AxiosRequestConfig<D>,\n data?: D,\n ): Promise<R> {\n const {\n requestKey,\n stateKeys = [],\n isInterruptive = false,\n feedback,\n } = config;\n const { ongoingRequests } = store.getState().app;\n\n if (ongoingRequests.has(requestKey)) {\n return ongoingRequests.get(requestKey) as Promise<R>;\n }\n\n const promise = axiosInstance.request<T, R, D>({\n ...config,\n url,\n data,\n headers: {\n ...(config.headers || {}),\n 'Mr-Interruptive': String(isInterruptive),\n },\n });\n startLoading({\n requestKey,\n isInterruptive,\n message: feedback?.loading,\n request: promise,\n });\n for (const stateKey of new Set(stateKeys)) {\n if (stateKey !== requestKey) {\n // State keys are loading/error observers only. Registering the request\n // under them would make a different write to the same target dedupe.\n startLoading({\n requestKey: stateKey,\n isInterruptive,\n message: feedback?.loading,\n });\n }\n }\n\n return promise;\n }\n\n const axios = {\n ...axiosInstance,\n post: <T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n data: D,\n config: IntercepterAxiosRequestConfig<D>,\n ): Promise<R> => makeRequest(url, { ...config, method: 'POST' }, data),\n put: <T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n data: D,\n config: IntercepterAxiosRequestConfig<D>,\n ): Promise<R> => makeRequest(url, { ...config, method: 'PUT' }, data),\n patch: <T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n data: D,\n config: IntercepterAxiosRequestConfig<D>,\n ): Promise<R> => makeRequest(url, { ...config, method: 'PATCH' }, data),\n delete: <T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n config: IntercepterAxiosRequestConfig<D>,\n ): Promise<R> => makeRequest(url, { ...config, method: 'DELETE' }),\n get: <T = any, R = AxiosResponse<T, any>, D = any>(\n url: string,\n config: IntercepterAxiosRequestConfig<D>,\n ): Promise<R> => makeRequest(url, { ...config, method: 'GET' }),\n };\n\n return axios;\n};\n\ntype ConfigOptions = {\n onApiSuccess?: <T>(\n response: AxiosResponse<T>,\n feedbackSuccess:\n | ((data: AxiosResponse<T>['data']) => React.ReactNode)\n | string\n | boolean,\n ) => void;\n};\n\nconst injectAxiosInterceptor = (\n appActions: AppActions,\n authActions: AuthActions,\n axios: ReturnType<typeof initAxiosInterceptor>,\n opts?: ConfigOptions,\n) => {\n let options: ConfigOptions = opts || {};\n const { endLoading, setError, clearError } = appActions;\n const { setIsUnauthorized } = authActions;\n\n const unknownError: ApplicationRequestError = {\n status: 500,\n code: 'UNKNOWN_EXCEPTION',\n message: \"Ops, something doesn't seems right\",\n };\n\n const settleLoading = (config: AxiosRequestConfig) => {\n const { requestKey, stateKeys = [], isInterruptive } = config;\n endLoading({ requestKey, isInterruptive });\n for (const stateKey of new Set(stateKeys)) {\n if (stateKey !== requestKey) {\n endLoading({\n requestKey: stateKey,\n isInterruptive,\n skipDedupe: true,\n });\n }\n }\n };\n\n const getErrorKeys = (config: AxiosRequestConfig) => {\n const { requestKey, stateKeys = [] } = config;\n return stateKeys.length > 0 ? new Set(stateKeys) : new Set([requestKey]);\n };\n\n axios.interceptors.response.use(\n (response) => {\n const { feedback } = response.config;\n settleLoading(response.config);\n for (const errorKey of getErrorKeys(response.config)) {\n clearError(errorKey);\n }\n\n if (feedback?.success) {\n options.onApiSuccess?.(response, feedback.success);\n }\n // switch (typeof feedback.success) {\n // case 'function':\n // toast(feedback.success(response.data));\n // break;\n // case 'string':\n // toast(\n // <Fragment>\n // <IconCircleCheckFilled color='rgb(34 197 94)' />\n // {feedback.success}\n // </Fragment>,\n // );\n // break;\n // case 'boolean':\n // toast('Request success');\n // break;\n // }\n\n return Promise.resolve(response);\n },\n (error: AxiosError<string>) => {\n const config = error.config as AxiosRequestConfig;\n settleLoading(config);\n\n const appError = error.response?.data\n ? {\n code: error.response?.statusText,\n status: error.response?.status,\n message: error.response?.data,\n }\n : unknownError;\n for (const errorKey of getErrorKeys(config)) {\n setError({ requestKey: errorKey, error: appError });\n }\n if (error.response?.status === 401) {\n setIsUnauthorized(true);\n }\n return Promise.reject(error);\n },\n );\n\n const setOptions = (opts: ConfigOptions) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return { setOptions };\n};\n\nexport { initAxiosInterceptor, injectAxiosInterceptor };\n","import type { Entity } from '@monorise/base';\nimport type { AxiosInterceptor } from '../types/api.type';\n\ntype LoginPayload = {\n email: string;\n};\n\ntype Options = {\n apiBaseUrl?: string;\n};\n\nconst initAuthService = (axios: AxiosInterceptor) => {\n let options: Options = {};\n const { apiBaseUrl = '/api/auth' } = options;\n\n const requestLoginMagicLink = (entityType: Entity, payload: LoginPayload) => {\n return axios.post(\n `${apiBaseUrl}/${entityType}`,\n {\n body: { ...payload },\n },\n {\n requestKey: `auth/${entityType}/request-login`,\n isInterruptive: true,\n feedback: {\n loading: 'Requesting login link',\n },\n },\n );\n };\n\n const getSessionProfile = <T extends Record<string, unknown>>() =>\n axios.get<\n T & {\n displayName: string;\n email: string;\n accountId: string;\n }\n >('/session', {\n requestKey: 'auth/session',\n });\n\n const logout = () =>\n axios.get('/logout', {\n requestKey: 'auth/logout',\n });\n\n const setOptions = (opts: Options) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return {\n requestLoginMagicLink,\n getSessionProfile,\n logout,\n setOptions,\n };\n};\n\nexport default initAuthService;\n\nexport type AuthService = ReturnType<typeof initAuthService>;\n","import type { CreatedEntity, DraftEntity, Entity } from '@monorise/base';\nimport type { AxiosRequestConfig } from 'axios';\nimport {\n type TransactionOperation,\n type TransactionResult,\n createTransactionCallRequestKey,\n} from '../helpers/transactional';\nimport {\n createMutationCallRequestKey,\n getEntityRequestKey,\n getMutualRequestKey,\n getMutualStateKey,\n getTagRequestKey,\n getUniqueFieldRequestKey,\n getUniqueFieldStateKey,\n} from '../lib/utils';\nimport type { MonoriseStore } from '../store/monorise.store';\nimport type {\n ApplicationRequestError,\n AxiosInterceptor,\n} from '../types/api.type';\nimport type { Mutual, MutualData } from '../types/mutual.type';\n\nconst ENTITY_API_BASE_URL = '/api/core/entity';\nconst MUTUAL_API_BASE_URL = '/api/core/mutual';\nconst TAG_API_BASE_URL = '/api/core/tag';\nconst TRANSACTION_API_BASE_URL = '/api/core/transaction';\n\ntype ListEntitiesPayload = {\n limit?: number;\n lastKey?: string;\n start?: string;\n end?: string;\n};\n\nexport type ListEntitiesByTagParams = {\n group?: string;\n query?: string;\n start?: string;\n end?: string;\n limit?: number;\n lastKey?: string;\n};\n\ntype ConfigOptions = {\n entityApiBaseUrl?: string;\n mutualApiBaseUrl?: string;\n tagApiBaseUrl?: string;\n};\n\nexport type CommonOptions = Partial<AxiosRequestConfig> & {\n customUrl?: string;\n isInterruptive?: boolean;\n feedback?: {\n success?: string;\n failure?: string;\n loading?: string;\n };\n stateKey?: string;\n forceFetch?: boolean;\n noData?: boolean;\n limit?: number;\n requestKey?: string;\n onError?: (error: ApplicationRequestError | Error) => void;\n entityId?: string;\n};\n\nconst initCoreService = (\n monoriseStore: MonoriseStore,\n axios: AxiosInterceptor,\n opts?: ConfigOptions,\n) => {\n let options: ConfigOptions = opts || {};\n\n const getMutationRequestConfig = (\n stateKey: string,\n opts: CommonOptions,\n compatibilityStateKeys: string[] = [],\n ) => ({\n requestKey: opts.requestKey ?? createMutationCallRequestKey(stateKey),\n // Keep the stable mutation key reactive while requestKey remains unique\n // per write. An explicit key and any legacy observation keys remain\n // observable for backwards compatibility with useLoadStore/useErrorStore.\n stateKeys: Array.from(\n new Set([\n stateKey,\n ...compatibilityStateKeys,\n ...(opts.requestKey ? [opts.requestKey] : []),\n ]),\n ),\n });\n\n const listEntities = <T extends Entity>(\n entityType: T,\n payload?: ListEntitiesPayload,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n return axios.get<{\n data: CreatedEntity<T>[];\n lastKey?: string;\n totalCount: number;\n }>(opts.customUrl || `${entityApiBaseUrl}/${entityType}`, {\n requestKey: getEntityRequestKey('list', entityType),\n params: payload ?? undefined,\n isInterruptive: opts.isInterruptive,\n feedback: opts.feedback,\n });\n };\n\n const searchEntities = <T extends Entity>(\n entityType: T,\n query: string,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n return axios.get<{ data: CreatedEntity<T>[] }>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}`,\n {\n requestKey: getEntityRequestKey('search', entityType),\n params: { query },\n isInterruptive: opts.isInterruptive,\n feedback: opts.feedback,\n },\n );\n };\n\n const listEntitiesByTag = <T extends Entity>(\n entityType: T,\n tagName: string,\n opts: CommonOptions & { params?: ListEntitiesByTagParams } = {},\n ) => {\n const { tagApiBaseUrl = TAG_API_BASE_URL } = options;\n return axios.get<{ entities: CreatedEntity<T>[]; lastKey: string }>(\n opts.customUrl || `${tagApiBaseUrl}/${entityType}/${tagName}`,\n {\n requestKey:\n opts.requestKey ||\n getTagRequestKey('list', entityType, tagName, opts.params),\n params: opts.params,\n isInterruptive: opts.isInterruptive,\n feedback: opts.feedback,\n },\n );\n };\n\n const getEntity = <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n return axios.get<CreatedEntity<T>>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}/${id}`,\n {\n requestKey: getEntityRequestKey('get', entityType, id),\n isInterruptive: opts.isInterruptive,\n feedback: {\n loading: `Retrieving ${entityType}`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const getEntityByUniqueField = <T extends Entity>(\n entityType: T,\n fieldName: string,\n value: string,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n return axios.get<CreatedEntity<T>>(\n opts.customUrl ||\n `${entityApiBaseUrl}/${entityType}/unique/${getUniqueFieldStateKey(fieldName, value)}`,\n {\n requestKey: getUniqueFieldRequestKey(entityType, fieldName, value),\n isInterruptive: opts.isInterruptive,\n feedback: {\n loading: `Retrieving ${entityType}`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const createEntity = <T extends Entity>(\n entityType: T,\n values: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n const entityConfig = monoriseStore.getState().config;\n const stateKey = getEntityRequestKey('create', entityType);\n return axios.post<CreatedEntity<T>>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}`,\n { ...values, ...(opts.entityId && { entityId: opts.entityId }) },\n {\n ...getMutationRequestConfig(stateKey, opts),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: `Creating ${entityConfig[entityType].displayName}`,\n success: `${entityConfig[entityType].displayName} created`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const upsertEntity = <T extends Entity>(\n entityType: T,\n id: string,\n values: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n const entityConfig = monoriseStore.getState().config;\n const stateKey = getEntityRequestKey('upsert', entityType, id);\n return axios.put<CreatedEntity<T>>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}/${id}`,\n values,\n {\n ...getMutationRequestConfig(stateKey, opts),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: `Updating ${entityConfig[entityType].displayName}`,\n success: `${entityConfig[entityType].displayName} updated`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const editEntity = <T extends Entity>(\n entityType: T,\n id: string,\n values: Partial<DraftEntity<T>> & { $condition?: string },\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n const entityConfig = monoriseStore.getState().config;\n const stateKey = getEntityRequestKey('edit', entityType, id);\n return axios.patch<CreatedEntity<T>>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}/${id}`,\n values,\n {\n ...getMutationRequestConfig(stateKey, opts),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: `Updating ${entityConfig[entityType].displayName}`,\n success: `${entityConfig[entityType].displayName} updated`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const adjustEntity = <T extends Entity>(\n entityType: T,\n id: string,\n adjustments: Record<string, number>,\n opts: CommonOptions & { condition?: string } = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n const entityConfig = monoriseStore.getState().config;\n const stateKey = getEntityRequestKey('adjust', entityType, id);\n const body = opts.condition\n ? { ...adjustments, $condition: opts.condition }\n : adjustments;\n return axios.post<CreatedEntity<T>>(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}/${id}/adjust`,\n body,\n {\n ...getMutationRequestConfig(stateKey, opts),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: `Updating ${entityConfig[entityType].displayName}`,\n success: `${entityConfig[entityType].displayName} updated`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const deleteEntity = <T extends Entity>(\n entityType: T,\n id: string,\n opts: CommonOptions = {},\n ) => {\n const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;\n const entityConfig = monoriseStore.getState().config;\n const stateKey = getEntityRequestKey('delete', entityType, id);\n return axios.delete(\n opts.customUrl || `${entityApiBaseUrl}/${entityType}/${id}`,\n {\n ...getMutationRequestConfig(stateKey, opts),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: `Deleting ${entityConfig[entityType].displayName}`,\n success: `${entityConfig[entityType].displayName} deleted`,\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const executeTransaction = (\n operations: TransactionOperation[],\n opts: CommonOptions = {},\n ) => {\n const { transactionApiBaseUrl = TRANSACTION_API_BASE_URL } = options as any;\n return axios.post<TransactionResult>(\n opts.customUrl || transactionApiBaseUrl,\n { operations },\n {\n // A hardcoded requestKey would collide across concurrent transaction\n // calls, sharing one loading/error slot. Using a single operation's\n // own key (e.g. operations[0]'s) would collide the OTHER way — with\n // a standalone editEntity/createEntity call on that same target,\n // via lib/api.ts's `ongoingRequests` dedupe, which would hand either\n // caller the other's differently-shaped response. The joined key is\n // namespaced so it can never match a single-entity key and unique per\n // call so non-idempotent transaction writes cannot be silently\n // deduplicated. Callers can pass opts.requestKey to opt into dedupe.\n requestKey:\n opts.requestKey ?? createTransactionCallRequestKey(operations),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: 'Processing transaction',\n success: 'Transaction completed',\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const listEntitiesByEntity = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n opts: CommonOptions = {},\n chainEntityQuery?: string,\n ) => {\n const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;\n return axios.get<{ entities: Mutual<B, T>[]; lastKey: string }>(\n opts.customUrl ||\n `${mutualApiBaseUrl}/${byEntityType}/${byEntityId}/${entityType}`,\n {\n requestKey: getMutualRequestKey(\n 'list',\n byEntityType,\n entityType,\n byEntityId,\n undefined,\n chainEntityQuery,\n ),\n isInterruptive: opts.isInterruptive,\n feedback: opts.feedback,\n params: {\n chainEntityQuery,\n limit: opts.limit,\n ...opts.params,\n ...(opts.noData && { projection: 'no-data' }),\n },\n },\n );\n };\n\n const getMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => {\n const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;\n return axios.get<Mutual<B, T>>(\n opts.customUrl ||\n `${mutualApiBaseUrl}/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n {\n requestKey: getMutualRequestKey(\n 'get',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n ),\n isInterruptive: opts.isInterruptive ?? false,\n feedback: opts.feedback,\n },\n );\n };\n\n const createMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, unknown>,\n opts: CommonOptions = {},\n ) => {\n const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;\n const stateKey = getMutualRequestKey(\n 'create',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n );\n const legacyStateKey = getMutualRequestKey(\n 'create',\n byEntityType,\n entityType,\n byEntityId,\n );\n return axios.post<Mutual<B, T>>(\n opts.customUrl ||\n `${mutualApiBaseUrl}/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n payload,\n {\n ...getMutationRequestConfig(stateKey, opts, [legacyStateKey]),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: 'Creating linkage',\n success: 'Linkage created',\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const editMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, unknown>,\n opts: CommonOptions = {},\n ) => {\n const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;\n const stateKey = getMutualRequestKey(\n 'update',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n );\n return axios.patch<Mutual<B, T>>(\n opts.customUrl ||\n `${mutualApiBaseUrl}/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n payload,\n {\n ...getMutationRequestConfig(stateKey, opts),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: 'Updating linkage',\n success: 'Linkage updated',\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const deleteMutual = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => {\n const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;\n const stateKey = getMutualRequestKey(\n 'delete',\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n );\n return axios.delete(\n opts.customUrl ||\n `${mutualApiBaseUrl}/${getMutualStateKey(byEntityType, byEntityId, entityType, entityId)}`,\n {\n ...getMutationRequestConfig(stateKey, opts),\n isInterruptive: opts.isInterruptive ?? true,\n feedback: {\n loading: 'Removing linkage',\n success: 'Linkage removed',\n ...(opts.feedback || {}),\n },\n },\n );\n };\n\n const makeEntityService = <T extends Entity>(entityType: T) => ({\n listEntities: (payload: ListEntitiesPayload, opts: CommonOptions = {}) =>\n listEntities(entityType, payload, opts),\n searchEntities: (query: string, opts: CommonOptions = {}) =>\n searchEntities(entityType, query, opts),\n listEntitiesByTag: (tagName: string, opts: CommonOptions = {}) =>\n listEntitiesByTag(entityType, tagName, opts),\n getEntity: (id: string, opts: CommonOptions = {}) =>\n getEntity(entityType, id, opts),\n getEntityByUniqueField: (\n fieldName: string,\n value: string,\n opts: CommonOptions = {},\n ) => getEntityByUniqueField(entityType, fieldName, value, opts),\n createEntity: (values: DraftEntity<T>, opts: CommonOptions = {}) =>\n createEntity(entityType, values, opts),\n upsertEntity: (\n id: string,\n values: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => upsertEntity(entityType, id, values, opts),\n editEntity: (\n id: string,\n values: Partial<DraftEntity<T>> & { $condition?: string },\n opts: CommonOptions = {},\n ) => editEntity(entityType, id, values, opts),\n updateEntity: (\n id: string,\n values: DraftEntity<T>,\n opts: CommonOptions = {},\n ) => editEntity(entityType, id, values, opts),\n adjustEntity: (\n id: string,\n adjustments: Record<string, number>,\n opts: CommonOptions = {},\n ) => adjustEntity(entityType, id, adjustments, opts),\n deleteEntity: (id: string, opts: CommonOptions = {}) =>\n deleteEntity(entityType, id, opts),\n });\n\n const makeMutualService = <B extends Entity, T extends Entity>(\n byEntityType: B,\n entityType: T,\n ) => ({\n listEntitiesByEntity: (\n byEntityId: string,\n opts: CommonOptions = {},\n chainEntityQuery?: string,\n ) =>\n listEntitiesByEntity(\n byEntityType,\n entityType,\n byEntityId,\n opts,\n chainEntityQuery,\n ),\n getMutual: (\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => getMutual(byEntityType, entityType, byEntityId, entityId, opts),\n createMutual: (\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, unknown>,\n opts = {},\n ) =>\n createMutual(\n byEntityType,\n entityType,\n byEntityId,\n entityId,\n payload,\n opts,\n ),\n editMutual: (\n byEntityId: string,\n entityId: string,\n payload: MutualData<B, T> | Record<string, unknown>,\n opts = {},\n ) =>\n editMutual(byEntityType, entityType, byEntityId, entityId, payload, opts),\n deleteMutual: (\n byEntityId: string,\n entityId: string,\n opts: CommonOptions = {},\n ) => deleteMutual(byEntityType, entityType, byEntityId, entityId, opts),\n });\n\n const setOptions = (opts: ConfigOptions) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return {\n makeEntityService,\n makeMutualService,\n executeTransaction,\n /** @deprecated use `executeTransaction` — kept as an alias since `coreService` is a public export and this method already existed under this name. */\n transaction: executeTransaction,\n setOptions,\n };\n};\n\nexport default initCoreService;\n\nexport type CoreService = ReturnType<typeof initCoreService>;\n","import type { AxiosInterceptor } from '../types/api.type';\n\ntype UploadFileProps = {\n file: File;\n scope: string;\n directory: string;\n name: string;\n disableLoading?: boolean;\n onProgress?: (progress: number) => void;\n};\n\ntype Options = {\n apiBaseUrl?: string;\n};\n\nconst initFilestoreService = (axios: AxiosInterceptor) => {\n let options: Options = {};\n const { apiBaseUrl = '/api/file' } = options;\n\n const uploadFile = async ({\n file,\n scope,\n directory,\n name,\n disableLoading,\n onProgress,\n }: UploadFileProps) => {\n const { data } = await axios.get(`${apiBaseUrl}/upload`, {\n requestKey: `filestore/presign/file/${name}`,\n isInterruptive: !disableLoading,\n feedback: {\n loading: 'Preparing upload',\n },\n params: {\n scope,\n directory,\n filename: name,\n },\n });\n\n return axios.put(data.url, file, {\n requestKey: `filestore/upload/${name}`,\n isInterruptive: !disableLoading,\n feedback: {\n loading: 'Uploading file',\n },\n headers: {\n 'Content-Type': file.type,\n 'Content-Disposition': 'inline',\n },\n onUploadProgress: (progressEvent) => {\n if (onProgress && progressEvent.total) {\n const progress = Math.round(\n (progressEvent.loaded / progressEvent.total) * 100,\n );\n onProgress(progress);\n }\n },\n });\n };\n\n const deleteFiles = async (keys: string[]) => {\n console.log('Deleting files', keys);\n const { data } = await axios.post(\n `${apiBaseUrl}/delete`,\n {\n keys,\n },\n {\n requestKey: 'filestore/delete',\n },\n );\n\n return data;\n };\n\n const uploadVideo = async ({\n file,\n scope,\n directory,\n name,\n }: UploadFileProps) => {\n const { data: presign } = await axios.get(`${apiBaseUrl}/upload`, {\n requestKey: `filestore/presign/video/${name}`,\n isInterruptive: true,\n feedback: {\n loading: 'Preparing upload',\n },\n params: {\n scope,\n directory,\n filename: name,\n },\n });\n\n await axios.put(presign.url, file, {\n requestKey: `filestore/upload/video/${name}`,\n isInterruptive: true,\n feedback: {\n loading: 'Uploading video',\n },\n headers: {\n 'Content-Type': file.type,\n },\n });\n\n const { data } = await axios.post(\n `${apiBaseUrl}/video/convert`,\n {\n scope,\n directory,\n filename: name,\n },\n {\n requestKey: 'filestore/convert/video',\n isInterruptive: true,\n feedback: {\n loading: 'Triggering video conversion',\n },\n },\n );\n\n return data;\n };\n\n const uploadAudio = async ({\n file,\n scope,\n directory,\n name,\n }: UploadFileProps) => {\n const { data: presign } = await axios.get(`${apiBaseUrl}/upload`, {\n requestKey: `filestore/presign/audio/${name}`,\n isInterruptive: true,\n feedback: {\n loading: 'Preparing upload',\n },\n params: {\n scope,\n directory,\n filename: name,\n },\n });\n\n await axios.put(presign.url, file, {\n requestKey: `filestore/upload/audio/${name}`,\n isInterruptive: true,\n feedback: {\n loading: 'Uploading audio',\n },\n headers: {\n 'Content-Type': file.type,\n },\n });\n\n const { data } = await axios.post(\n `${apiBaseUrl}/audio/convert`,\n {\n scope,\n directory,\n filename: name,\n },\n {\n requestKey: 'filestore/convert/audio',\n isInterruptive: true,\n feedback: {\n loading: 'Triggering audio conversion',\n },\n },\n );\n\n return data;\n };\n\n const getJobStatus = async (id: string) => {\n const { data } = await axios.get(`${apiBaseUrl}/job/${id}`, {\n requestKey: `filestore/get-job/${id}`,\n });\n\n return data;\n };\n\n const setOptions = (opts: Options) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return {\n uploadFile,\n deleteFiles,\n uploadVideo,\n uploadAudio,\n getJobStatus,\n setOptions,\n };\n};\n\nexport default initFilestoreService;\n","import type {\n CreatedEntity,\n Entity,\n MonoriseEntityConfig,\n} from '@monorise/base';\nimport { enableMapSet } from 'immer';\nimport type React from 'react';\nimport { create } from 'zustand';\nimport { devtools } from 'zustand/middleware';\nimport type { ApplicationRequestError, ModalProps } from '../types/api.type';\nimport type { CommonStore } from '../types/monorise.type';\nimport type { Mutual } from '../types/mutual.type';\n\nenableMapSet();\n\nconst configureDevtools = (storeName: string) => ({\n name: `${storeName} Store`,\n anonymousActionType: `${storeName.toLowerCase()}/action`,\n enabled: !['prod', 'dev'].includes(process.env.NEXT_PUBLIC_ENVIRONMENT ?? ''),\n serialize: {\n options: {\n map: true,\n },\n },\n});\n\ntype Options = {\n modals?: Record<string, React.ComponentType<unknown>>;\n};\n\nconst initMonoriseStore = () => {\n let options: Options = {};\n const { modals = {} } = options;\n\n type AppModalProps = ModalProps<typeof modals>;\n\n const monoriseStore = create(\n devtools(\n (): {\n app: {\n ongoingRequests: Map<string, Promise<unknown>>;\n loadStack: Map<string, number>;\n intLoadStack: Map<string, number>;\n loadingMessage: string;\n errorStack: Map<string, ApplicationRequestError>;\n modal: {\n name: keyof AppModalProps | null;\n context?: AppModalProps[keyof AppModalProps];\n };\n };\n config: Record<Entity, MonoriseEntityConfig>;\n entity: Record<Entity, CommonStore<CreatedEntity<Entity>>>;\n mutual: Record<string, CommonStore<Mutual>>;\n tag: Record<string, CommonStore<CreatedEntity<Entity>>>;\n auth: {\n isUnauthorized: boolean;\n profile: {\n displayName: string;\n email: string;\n accountId: string;\n };\n isLoading: boolean;\n };\n } => ({\n app: {\n ongoingRequests: new Map(),\n loadStack: new Map(),\n intLoadStack: new Map(),\n loadingMessage: '',\n errorStack: new Map(),\n modal: {\n name: null,\n },\n },\n config: {},\n entity: {},\n mutual: {},\n tag: {},\n auth: {\n isUnauthorized: false,\n profile: {\n displayName: '',\n email: '',\n accountId: '',\n },\n isLoading: true,\n },\n }),\n configureDevtools('monorise'),\n ),\n );\n\n const setOptions = (opts: Options) => {\n options = {\n ...options,\n ...opts,\n };\n };\n\n return { setOptions, monoriseStore };\n};\n\nexport { initMonoriseStore };\n\nexport type MonoriseStore = Awaited<\n ReturnType<typeof initMonoriseStore>\n>['monoriseStore'];\n","import type { Entity, MonoriseEntityConfig } from '@monorise/base';\nimport type { AxiosResponse } from 'axios';\nimport { initAppActions } from './actions/app.action';\nimport { initAuthActions } from './actions/auth.action';\nimport { initConfigActions } from './actions/config.action';\nimport { initCoreActions } from './actions/core.action';\nimport {\n initWebSocketActions,\n initializeWebSocketManager,\n getWebSocketManager,\n} from './actions/websocket.action';\nimport {\n WebSocketManager,\n type ConnectionState,\n type ClientMessage,\n type ServerMessage,\n} from './websocket';\nimport { initAxiosInterceptor, injectAxiosInterceptor } from './lib/api';\nimport {\n getEntityRequestKey,\n getMutualRequestKey,\n getTagRequestKey,\n getUniqueFieldRequestKey,\n} from './lib/utils';\nimport initAuthService from './services/auth.service';\nimport initCoreService from './services/core.service';\nimport initFilestoreService from './services/filestore.service';\nimport { initMonoriseStore } from './store/monorise.store';\nimport {\n Mutual,\n MutualData,\n MutualDataMapping,\n MutualDataWithIndex,\n} from './types/mutual.type';\n\ntype Options<T extends Record<string, React.ComponentType<any>>> = {\n authBaseUrl?: string;\n filestoreBaseUrl?: string;\n entityBaseUrl?: string;\n mutualBaseUrl?: string;\n tagBaseUrl?: string;\n modals?: T;\n entityConfig: Record<Entity, MonoriseEntityConfig>;\n onApiSuccess?: <T>(\n response: AxiosResponse<T>,\n feedbackSuccess:\n | ((data: AxiosResponse<T>['data']) => React.ReactNode)\n | string\n | boolean,\n ) => void;\n};\n\nconst initMonorise = () => {\n const { monoriseStore: store, setOptions: setMonoriseOptions } =\n initMonoriseStore();\n const appActions = initAppActions(store);\n const configActions = initConfigActions(store);\n const axios = initAxiosInterceptor(store, appActions);\n\n const authService = initAuthService(axios);\n const filestoreService = initFilestoreService(axios);\n const coreService = initCoreService(store, axios);\n\n const authActions = initAuthActions(store, authService);\n const coreActions = initCoreActions(store, appActions, coreService);\n // The socket hooks need an HTTP read path, not just the socket: they fetch\n // the initial page on mount and re-fetch on reconnect to recover whatever\n // was missed while the connection was down. `httpActions` is optional on\n // `initWebSocketActions`, and omitting it fails quietly rather than loudly —\n // `fetchData` early-returns, so `isLoading` never leaves its initial `true`\n // and the documented resync-on-reconnect never happens.\n //\n // Note the argument order: `coreService`'s own `listEntitiesByEntity` takes\n // (byEntityType, entityType, byEntityId) while the socket actions pass\n // (byEntityType, byEntityId, entityType). They are adapted here rather than\n // passed straight through.\n const websocketActions = initWebSocketActions(store, {\n listEntities: async (entityType, params) => {\n const { data } = await coreService\n .makeEntityService(entityType)\n .listEntities({ limit: params?.limit, lastKey: params?.lastKey });\n return { data: data.data, lastKey: data.lastKey };\n },\n listEntitiesByEntity: async (\n byEntityType,\n byEntityId,\n entityType,\n params,\n ) => {\n const { data } = await coreService\n .makeMutualService(byEntityType, entityType)\n .listEntitiesByEntity(byEntityId, {\n limit: params?.limit,\n params: { lastKey: params?.lastKey },\n });\n return { entities: data.entities, lastKey: data.lastKey };\n },\n });\n\n const axiosInterceptor = injectAxiosInterceptor(\n appActions,\n authActions,\n axios,\n );\n\n const config = <T extends Record<string, React.ComponentType<any>>>(\n opts: Options<T>,\n ) => {\n setMonoriseOptions({\n modals: opts.modals,\n });\n configActions.setConfig(opts.entityConfig);\n authService.setOptions({\n apiBaseUrl: opts.authBaseUrl,\n });\n filestoreService.setOptions({\n apiBaseUrl: opts.filestoreBaseUrl,\n });\n coreService.setOptions({\n entityApiBaseUrl: opts.entityBaseUrl,\n mutualApiBaseUrl: opts.mutualBaseUrl,\n tagApiBaseUrl: opts.tagBaseUrl,\n });\n axiosInterceptor.setOptions({\n onApiSuccess: opts.onApiSuccess,\n });\n };\n\n return {\n config,\n store,\n axios,\n authService,\n filestoreService,\n coreService,\n ...configActions,\n ...appActions,\n ...authActions,\n ...coreActions,\n ...websocketActions,\n };\n};\n\nconst Monorise = initMonorise();\n\nconst {\n store,\n axios,\n authService,\n filestoreService,\n coreService,\n setConfig,\n getConfig,\n useConfig,\n startLoading,\n endLoading,\n setError,\n getError,\n clearError,\n openModal,\n closeModal,\n useLoadStore,\n useInterruptiveLoadStore,\n useErrorStore,\n useModalStore,\n requestLogin,\n useProfile,\n getProfile,\n useIsUnauthorized,\n setIsUnauthorized,\n logout,\n listMoreEntities,\n createEntity,\n upsertEntity,\n editEntity,\n adjustEntity,\n updateLocalEntity,\n deleteEntity,\n executeTransaction,\n getMutual,\n createMutual,\n createLocalMutual,\n upsertLocalMutual,\n editMutual,\n deleteMutual,\n deleteLocalMutual,\n useCreateEntity,\n useUpsertEntity,\n useEditEntity,\n useAdjustEntity,\n useDeleteEntity,\n useExecuteTransaction,\n useCreateMutual,\n useEditMutual,\n useDeleteMutual,\n useEntity,\n useEntityByUniqueField,\n useEntities,\n useMutual,\n useMutuals,\n useTaggedEntities,\n useEntityState,\n getEntity,\n updateLocalTaggedEntity,\n deleteLocalTaggedEntity,\n useEntitySocket,\n useMutualSocket,\n useEphemeralSocket,\n useEntityFeed,\n} = Monorise;\n\nexport {\n store,\n axios,\n authService,\n filestoreService,\n coreService,\n setConfig,\n getConfig,\n useConfig,\n startLoading,\n endLoading,\n setError,\n getError,\n clearError,\n openModal,\n closeModal,\n useLoadStore,\n useInterruptiveLoadStore,\n useErrorStore,\n useModalStore,\n requestLogin,\n useProfile,\n getProfile,\n useIsUnauthorized,\n setIsUnauthorized,\n logout,\n listMoreEntities,\n createEntity,\n upsertEntity,\n editEntity,\n adjustEntity,\n updateLocalEntity,\n deleteEntity,\n executeTransaction,\n getMutual,\n createMutual,\n createLocalMutual,\n upsertLocalMutual,\n editMutual,\n deleteMutual,\n deleteLocalMutual,\n useCreateEntity,\n useUpsertEntity,\n useEditEntity,\n useAdjustEntity,\n useDeleteEntity,\n useExecuteTransaction,\n useCreateMutual,\n useEditMutual,\n useDeleteMutual,\n useEntity,\n useEntityByUniqueField,\n useEntities,\n useMutual,\n useMutuals,\n useTaggedEntities,\n useEntityState,\n getEntityRequestKey,\n getMutualRequestKey,\n getTagRequestKey,\n getUniqueFieldRequestKey,\n getEntity,\n updateLocalTaggedEntity,\n deleteLocalTaggedEntity,\n useEntitySocket,\n useMutualSocket,\n useEphemeralSocket,\n useEntityFeed,\n initializeWebSocketManager,\n getWebSocketManager,\n WebSocketManager,\n type ConnectionState,\n type ClientMessage,\n type ServerMessage,\n};\n\nexport default Monorise;\n\nexport { transactional } from './helpers/transactional';\nexport { MutualDataWithIndex, MutualDataMapping, MutualData, Mutual };\n\nexport type {\n CreatedEntity,\n DraftEntity,\n Entity,\n EntitySchemaMap,\n NumericFields,\n} from '@monorise/base';\nexport type {\n TransactionOperation,\n TransactionResult,\n TransactionResultEntry,\n} from './helpers/transactional';\n"],"mappings":";;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,WAAW,gBAAgB;AAsCpC,IAAM,iBAAiB,CAACA,WAAyB;AAC/C,MAAI,UAAmB,CAAC;AAExB,QAAM,EAAE,SAAS,CAAC,EAAE,IAAI;AAGxB,QAAMC,gBAAe,CAAI;AAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAAC;AAAA,EACF,MAA8B;AAC5B,IAAAF,OAAM;AAAA,MACJ,QAAQ,CAAC,UAAU;AACjB,cAAM,YAAY,iBAAiB,iBAAiB;AACpD,cAAM,kBAAkB,MAAM,IAAI,SAAS,EAAE,IAAI,UAAU;AAE3D,cAAM,IAAI,iBACR,OAAO,YAAY,WAAW,UAAU;AAC1C,YAAIE,UAAS;AACX,gBAAM,IAAI,gBAAgB,IAAI,YAAYA,QAAO;AAAA,QACnD;AACA,cAAM,IAAI,SAAS,EAAE;AAAA,UACnB;AAAA,UACA,kBAAkB,kBAAkB,IAAI;AAAA,QAC1C;AAAA,MACF,CAAC;AAAA,MACD;AAAA,MACA,oBAAoB,UAAU;AAAA,IAChC;AAEA,QAAIA,UAAS;AAGX,YAAM,SAAS,MAAM;AACnB,YAAIF,OAAM,SAAS,EAAE,IAAI,gBAAgB,IAAI,UAAU,MAAME,UAAS;AACpE;AAAA,QACF;AACA,QAAAF,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AA,EACA;AAAA,EACA;AAAA,EACA;AACF,IAAI;AA8EJ,IAAO,gBAAQ;","names":["store","startLoading","request","endLoading","setError","getError","clearError","openModal","closeModal","useLoadStore","useInterruptiveLoadStore","useErrorStore","useModalStore","produce","store","authService","requestLogin","useProfile","getProfile","produce","useIsUnauthorized","setIsUnauthorized","logout","produce","store","setConfig","getConfig","useConfig","produce","useEffect","useState","byEntityId","byEntityId","byEntityId","coreService","getError","useLoadStore","useErrorStore","startLoading","endLoading","setError","clearError","store","produce","error","listMoreEntities","state","getEntity","byEntityId","createEntity","_a","upsertEntity","editEntity","adjustEntity","deleteEntity","executeTransaction","_b","_c","_d","_e","getMutual","createMutual","createLocalMutual","updateLocalEntity","upsertLocalMutual","editMutual","deleteMutual","deleteLocalMutual","useCreateEntity","useUpsertEntity","useEditEntity","useAdjustEntity","useDeleteEntity","useCreateMutual","useEditMutual","useDeleteMutual","useExecuteTransaction","useEntity","useEffect","useEntityByUniqueField","useEntities","useState","useMutual","useMutuals","useTaggedEntities","useEntityState","updateLocalTaggedEntity","deleteLocalTaggedEntity","useCallback","useEffect","useRef","useState","produce","useEntitySocket","useState","setError","useRef","produce","useEffect","useMutualSocket","byEntityId","useEphemeralSocket","useCallback","useEntityFeed","store","startLoading","axios","endLoading","setError","clearError","setIsUnauthorized","opts","axios","logout","axios","opts","getEntity","createEntity","upsertEntity","editEntity","adjustEntity","deleteEntity","executeTransaction","byEntityId","getMutual","createMutual","editMutual","deleteMutual","axios","store","axios","authService","filestoreService","coreService","byEntityId"]}