@judo/actions 0.44.0 → 0.45.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/api/index.d.ts +4 -1
- package/dist/api/index.d.ts.map +1 -1
- package/dist/api/json-object.d.ts +3 -0
- package/dist/api/json-object.d.ts.map +1 -0
- package/dist/api/judo-rest-api.d.ts +1 -1
- package/dist/api/judo-rest-api.d.ts.map +1 -1
- package/dist/api/model-converters.d.ts +1 -1
- package/dist/api/model-converters.d.ts.map +1 -1
- package/dist/api/model-type-maps.d.ts +50 -0
- package/dist/api/model-type-maps.d.ts.map +1 -0
- package/dist/api/operation-fault.d.ts +23 -0
- package/dist/api/operation-fault.d.ts.map +1 -0
- package/dist/api/path-builder.d.ts +1 -1
- package/dist/api/path-builder.d.ts.map +1 -1
- package/dist/api/transfer-serializer.d.ts +7 -1
- package/dist/api/transfer-serializer.d.ts.map +1 -1
- package/dist/api/types.d.ts +22 -6
- package/dist/api/types.d.ts.map +1 -1
- package/dist/handlers/action.fixtures.d.ts +25 -0
- package/dist/handlers/action.fixtures.d.ts.map +1 -0
- package/dist/handlers/autocomplete/autocomplete-handlers.d.ts.map +1 -1
- package/dist/handlers/crud/crud-handlers.d.ts +4 -11
- package/dist/handlers/crud/crud-handlers.d.ts.map +1 -1
- package/dist/handlers/crud/index.d.ts +1 -1
- package/dist/handlers/crud/index.d.ts.map +1 -1
- package/dist/handlers/form/form-handlers.d.ts.map +1 -1
- package/dist/handlers/index.d.ts +2 -2
- package/dist/handlers/index.d.ts.map +1 -1
- package/dist/handlers/navigation/navigation-handlers.d.ts.map +1 -1
- package/dist/handlers/operation/operation-handlers.d.ts.map +1 -1
- package/dist/handlers/relation/index.d.ts +1 -1
- package/dist/handlers/relation/index.d.ts.map +1 -1
- package/dist/handlers/relation/relation-handlers.d.ts +4 -1
- package/dist/handlers/relation/relation-handlers.d.ts.map +1 -1
- package/dist/handlers/selector/selector-handlers.d.ts.map +1 -1
- package/dist/handlers/validation-feedback.d.ts +40 -0
- package/dist/handlers/validation-feedback.d.ts.map +1 -0
- package/dist/handlers/validation-messages.d.ts +11 -0
- package/dist/handlers/validation-messages.d.ts.map +1 -0
- package/dist/hooks/use-action-dispatcher.d.ts +9 -3
- package/dist/hooks/use-action-dispatcher.d.ts.map +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +882 -630
- package/dist/index.js.map +1 -1
- package/dist/lifecycle/execute-with-lifecycle.d.ts +2 -2
- package/dist/lifecycle/execute-with-lifecycle.d.ts.map +1 -1
- package/dist/provider/api-context.d.ts +1 -1
- package/dist/provider/api-context.d.ts.map +1 -1
- package/dist/provider/index.d.ts +1 -0
- package/dist/provider/index.d.ts.map +1 -1
- package/dist/provider/operation-fault-context.d.ts +11 -0
- package/dist/provider/operation-fault-context.d.ts.map +1 -0
- package/dist/registry/action-handler-registry.d.ts +6 -1
- package/dist/registry/action-handler-registry.d.ts.map +1 -1
- package/dist/registry/index.d.ts +1 -1
- package/dist/registry/index.d.ts.map +1 -1
- package/dist/types.d.ts +64 -7
- package/dist/types.d.ts.map +1 -1
- package/package.json +7 -5
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../model-api/dist/index.js","../src/handlers/navigation/navigation-handlers.ts","../src/handlers/form/form-handlers.ts","../src/handlers/selector/selector-handlers.ts","../src/api/constants.ts","../src/lifecycle/error-interceptor.ts","../src/handlers/crud/crud-handlers.ts","../src/handlers/relation/relation-handlers.ts","../src/handlers/table/table-handlers.ts","../src/handlers/operation/operation-handlers.ts","../src/handlers/autocomplete/autocomplete-handlers.ts","../src/handlers/other/other-handlers.ts","../src/provider/api-context.tsx","../src/lifecycle/execute-with-lifecycle.ts","../src/registry/action-handler-registry.ts","../src/hooks/use-action-dispatcher.ts","../src/hooks/use-action-handler.ts","../src/api/path-builder.ts","../src/api/judo-rest-api.ts","../src/api/types.ts","../src/api/transfer-serializer.ts","../src/api/transfer-deserializer.ts"],"sourcesContent":["//#region src/enums.ts\nvar e = {\n\tHORIZONTAL: \"HORIZONTAL\",\n\tVERTICAL: \"VERTICAL\"\n}, t = {\n\tNONE: \"NONE\",\n\tLOOSE: \"LOOSE\",\n\tTIGHT: \"TIGHT\"\n}, n = {\n\tNONE: \"NONE\",\n\tHORIZONTAL: \"HORIZONTAL\",\n\tVERTICAL: \"VERTICAL\",\n\tBOTH: \"BOTH\"\n}, r = {\n\tCENTER: \"CENTER\",\n\tEND: \"END\",\n\tSPACEAROUND: \"SPACEAROUND\",\n\tSPACEBETWEEN: \"SPACEBETWEEN\",\n\tSPACEEVENLY: \"SPACEEVENLY\",\n\tSTART: \"START\"\n}, i = {\n\tBASELINE: \"BASELINE\",\n\tCENTER: \"CENTER\",\n\tEND: \"END\",\n\tSTART: \"START\",\n\tSTRETCH: \"STRETCH\"\n}, a = {\n\tMIN: \"MIN\",\n\tMAX: \"MAX\"\n}, o = {\n\tTOP_LEFT: \"TOP_LEFT\",\n\tTOP_CENTER: \"TOP_CENTER\",\n\tTOP_RIGHT: \"TOP_RIGHT\",\n\tCENTER_LEFT: \"CENTER_LEFT\",\n\tCENTER: \"CENTER\",\n\tCENTER_RIGHT: \"CENTER_RIGHT\",\n\tBOTTOM_LEFT: \"BOTTOM_LEFT\",\n\tBOTTOM_CENTER: \"BOTTOM_CENTER\",\n\tBOTTOM_RIGHT: \"BOTTOM_RIGHT\"\n}, s = {\n\tXS: \"XS\",\n\tSM: \"SM\",\n\tMD: \"MD\",\n\tLG: \"LG\",\n\tXL: \"XL\"\n}, c = {\n\tTABLE: \"TABLE\",\n\tFORM: \"FORM\",\n\tVIEW: \"VIEW\"\n}, l = {\n\tCONTAINED: \"contained\",\n\tTEXT: \"text\",\n\tOUTLINED: \"outlined\"\n}, u = {\n\tNONE: \"NONE\",\n\tCONDITIONAL: \"CONDITIONAL\",\n\tMANDATORY: \"MANDATORY\"\n}, d = {\n\tNONE: \"NONE\",\n\tASC: \"ASC\",\n\tDESC: \"DESC\"\n}, f = {\n\tEQUAL: \"EQUAL\",\n\tNOT_EQUAL: \"NOT_EQUAL\",\n\tIS_EMPTY: \"IS_EMPTY\",\n\tIS_NOT_EMPTY: \"IS_NOT_EMPTY\",\n\tLESS: \"LESS\",\n\tLESS_OR_EQUAL: \"LESS_OR_EQUAL\",\n\tGREATER: \"GREATER\",\n\tGREATER_OR_EQUAL: \"GREATER_OR_EQUAL\",\n\tLIKE: \"LIKE\"\n}, p = {\n\tAUTO: \"AUTO\",\n\tENABLED: \"ENABLED\",\n\tDISABLED: \"DISABLED\"\n}, m = {\n\tTABLE: \"TABLE\",\n\tTAG: \"TAG\",\n\tCARD: \"CARD\"\n}, h = {\n\tVERTICAL: \"VERTICAL\",\n\tHORIZONTAL: \"HORIZONTAL\"\n}, g = {\n\tHORIZONTAL: \"HORIZONTAL\",\n\tVERTICAL: \"VERTICAL\"\n}, _ = {\n\tNANOSECOND: \"NANOSECOND\",\n\tMICROSECOND: \"MICROSECOND\",\n\tMILLISECOND: \"MILLISECOND\",\n\tSECOND: \"SECOND\",\n\tMINUTE: \"MINUTE\",\n\tHOUR: \"HOUR\",\n\tDAY: \"DAY\",\n\tWEEK: \"WEEK\",\n\tMONTH: \"MONTH\",\n\tYEAR: \"YEAR\"\n}, v = {\n\tTOP: \"TOP\",\n\tBOTTOM: \"BOTTOM\",\n\tSTART: \"START\",\n\tEND: \"END\",\n\tDEFAULT: \"DEFAULT\"\n}, y = {\n\tLABEL: \"LABEL\",\n\tATTRIBUTE: \"ATTRIBUTE\"\n}, b = {\n\tUNDEFINED: \"UNDEFINED\",\n\tEMAIL: \"EMAIL\",\n\tUSERNAME: \"USERNAME\"\n}, x = {\n\tASSOCIATION: \"ASSOCIATION\",\n\tCOMPOSITION: \"COMPOSITION\",\n\tAGGREGATION: \"AGGREGATION\",\n\tSTATIC: \"STATIC\"\n}, S = {\n\tSTORED: \"STORED\",\n\tDERIVED: \"DERIVED\",\n\tMAPPED: \"MAPPED\",\n\tTRANSIENT: \"TRANSIENT\",\n\tACCESS: \"ACCESS\"\n}, C = {\n\tLIST: \"LIST\",\n\tCREATE: \"CREATE\",\n\tSET: \"SET\",\n\tUNSET: \"UNSET\",\n\tADD: \"ADD\",\n\tREMOVE: \"REMOVE\",\n\tRANGE: \"RANGE\",\n\tVALIDATE_CREATE: \"VALIDATE_CREATE\",\n\tTEMPLATE: \"TEMPLATE\",\n\tUPDATE: \"UPDATE\",\n\tVALIDATE_UPDATE: \"VALIDATE_UPDATE\",\n\tDELETE: \"DELETE\",\n\tREFRESH: \"REFRESH\",\n\tEXPORT: \"EXPORT\"\n}, w = {\n\tREFRESH: \"REFRESH\",\n\tUPDATE: \"UPDATE\",\n\tVALIDATE_UPDATE: \"VALIDATE_UPDATE\",\n\tDELETE: \"DELETE\",\n\tTEMPLATE: \"TEMPLATE\"\n}, T = {\n\tMAPPED: \"MAPPED\",\n\tSTATIC: \"STATIC\"\n}, E = {\n\tREFRESH: \"REFRESH\",\n\tUPDATE: \"UPDATE\",\n\tDELETE: \"DELETE\",\n\tVALIDATE_INPUT: \"VALIDATE_INPUT\"\n}, D = Symbol.for(\"@judo/MODEL_LOADER_SERVICE\"), O = Symbol.for(\"@judo/MODEL_REGISTRY_SERVICE\"), k = Symbol.for(\"@judo/NAVIGATION_BADGE_SERVICE\"), A = Symbol.for(\"@judo/THEME_SERVICE\"), j = Symbol.for(\"@judo/ACTION_HANDLER_FACTORY\"), M = Symbol.for(\"@judo/COMPONENT_OVERRIDE\"), N = Symbol.for(\"@judo/COMPONENT_OVERRIDE_SERVICE\"), P = Symbol.for(\"@judo/NOTIFICATION_SERVICE\"), F = Symbol.for(\"@judo/DIALOG_SERVICE\"), I = Symbol.for(\"@judo/UNSAVED_CHANGES_GUARD\"), L = Symbol.for(\"@judo/SESSION_TIMEOUT_GUARD\"), R = Symbol.for(\"@judo/LOADING_SERVICE\"), z = Symbol.for(\"@judo/I18N_SERVICE\");\n//#endregion\nexport { j as ACTION_HANDLER_FACTORY, o as Alignment, e as Axis, l as ButtonStyle, M as COMPONENT_OVERRIDE, N as COMPONENT_OVERRIDE_SERVICE, p as CheckboxSelection, b as ClaimType, w as ClassBehaviourType, u as ConfirmationType, i as CrossAxisAlignment, F as DIALOG_SERVICE, s as DialogSize, _ as DurationUnit, f as FilterOperationType, t as Fit, z as I18N_SERVICE, R as LOADING_SERVICE, D as MODEL_LOADER_SERVICE, O as MODEL_REGISTRY_SERVICE, r as MainAxisAlignment, a as MainAxisSize, S as MemberType, h as MenuLayout, k as NAVIGATION_BADGE_SERVICE, P as NOTIFICATION_SERVICE, E as OperationTargetBehaviourType, T as OperationTypeEnum, c as PageContainerType, v as Placement, C as RelationBehaviourType, x as RelationKind, L as SESSION_TIMEOUT_GUARD, d as Sort, n as Stretch, A as THEME_SERVICE, g as TabOrientation, m as TableRepresentation, y as TitleFrom, I as UNSAVED_CHANGES_GUARD };\n","import type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext } from \"../../types\";\n\n/**\n * Handle back navigation - hook factory.\n */\nexport const useBackActionHandler = ((_action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Close dialog if open\n\t\tif (context.closeDialog) {\n\t\t\tcontext.closeDialog();\n\t\t\treturn;\n\t\t}\n\t\t// Otherwise navigate back\n\t\tcontext.navigation!.goBack();\n\t};\n}) as ActionHandlerHookWithMeta;\nuseBackActionHandler.actionType = \"BackActionDefinition\";\n\n/**\n * Handle page navigation - hook factory.\n */\nexport const useOpenPageActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenPageAction\");\n\t\t}\n\n\t\tif (!context.navigation) {\n\t\t\tthrow new Error(\"Navigation context is undefined\");\n\t\t}\n\n\t\t// For eager tables, forward isEager, parentTransferId, and relationName so the opened\n\t\t// dialog page knows it's operating on an aggregated child (no REST calls on save).\n\t\tconst eagerContext = context as TypedActionHandlerContext & {\n\t\t\tparentTransferId?: string;\n\t\t\trelationName?: string;\n\t\t};\n\n\t\t// Pass transfer data as params\n\t\tcontext.navigation.navigateTo(targetPage, {\n\t\t\ttransfer: context.transfer,\n\t\t\t...(context.isEager && {\n\t\t\t\tisEager: true,\n\t\t\t\tparentTransferId: eagerContext.parentTransferId,\n\t\t\t\trelationName: eagerContext.relationName,\n\t\t\t}),\n\t\t});\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenPageActionHandler.actionType = \"OpenPageActionDefinition\";\n\n/**\n * Handle row-based page navigation (from table row) - hook factory.\n */\nexport const useRowOpenPageActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for RowOpenPageAction\");\n\t\t}\n\n\t\tif (!context.navigation) {\n\t\t\tthrow new Error(\"Navigation context is undefined\");\n\t\t}\n\n\t\t// Navigate with row transfer\n\t\t// For eager tables, forward isEager, parentTransferId, and relationName so the opened\n\t\t// dialog page knows it's operating on an aggregated child (no REST calls on save).\n\t\tconst eagerContext = context as TypedActionHandlerContext & {\n\t\t\tparentTransferId?: string;\n\t\t\trelationName?: string;\n\t\t};\n\n\t\tcontext.navigation.navigateTo(targetPage, {\n\t\t\ttransfer: context.transfer,\n\t\t\t...(context.isEager && {\n\t\t\t\tisEager: true,\n\t\t\t\tparentTransferId: eagerContext.parentTransferId,\n\t\t\t\trelationName: eagerContext.relationName,\n\t\t\t}),\n\t\t});\n\t};\n}) as ActionHandlerHookWithMeta;\nuseRowOpenPageActionHandler.actionType = \"RowOpenPageActionDefinition\";\n\n/**\n * Handle cancel action (close dialog or go back) - hook factory.\n *\n * Behavior depends on context:\n * - In a dialog: closes the dialog\n * - On a VIEW page with edits: resets transfer to original data (no navigation)\n * - Otherwise: navigates back\n */\nexport const useCancelActionHandler = ((_action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Close dialog if open\n\t\tif (context.closeDialog) {\n\t\t\tcontext.closeDialog();\n\t\t\treturn;\n\t\t}\n\n\t\t// On VIEW pages with edits, reset transfer data instead of navigating\n\t\tif (context.pageType === \"VIEW\" && context.isEditMode && context.data && context.transfer?.__identifier) {\n\t\t\tcontext.data.resetTransfer(context.transfer.__identifier);\n\t\t\treturn;\n\t\t}\n\n\t\t// Otherwise navigate back\n\t\tcontext.navigation!.goBack();\n\t};\n}) as ActionHandlerHookWithMeta;\nuseCancelActionHandler.actionType = \"CancelActionDefinition\";\n","import type { OpenOperationInputFormActionDefinition as OpenOpInputFormDef, RelationType } from \"@judo/model-api\";\nimport type { Action, ActionHandlerHookWithMeta, TransferData, TypedActionHandlerContext } from \"../../types\";\n\n/**\n * Handle form open for editing - hook factory.\n */\nexport const useOpenFormActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenFormAction\");\n\t\t}\n\n\t\t// Open form dialog with transfer\n\t\tcontext.navigation!.openDialog(targetPage, {\n\t\t\ttransfer: context.transfer,\n\t\t});\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenFormActionHandler.actionType = \"OpenFormActionDefinition\";\n\n/**\n * Handle form open for create - hook factory.\n *\n * Creates a dialog for creating new transfers. The behavior depends on the source component:\n *\n * **Eager Components** (tables/links with isEager=true):\n * - Dialog submission returns data to the caller\n * - Caller (table/link) adds transfer to local __items array\n * - No REST call until parent transfer is saved\n * - onSubmitCreate callback is provided in dialog params\n *\n * **Lazy Components** (default):\n * - Dialog submission calls validateCreateRelation API\n * - If validation passes, calls createRelation API\n * - If validation fails, displays field errors and stays open\n * - After successful create, caller is notified via onDialogClose callback\n */\nexport const useOpenCreateFormActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenCreateFormAction\");\n\t\t}\n\n\t\t// Get relation from action (ownerDataElement is the RelationType for the target)\n\t\tconst relation = action.ownerDataElement as RelationType | undefined;\n\n\t\t// Determine if this is an eager (aggregated) creation\n\t\tconst isEager = context.isEager === true;\n\n\t\t// Get owner transfer for non-access relations\n\t\tconst ownerTransfer = context.transfer;\n\n\t\t// Get parent context for eager tables (where to add the created transfer)\n\t\tconst eagerContext = context as {\n\t\t\tparentTransferId?: string;\n\t\t\trelationName?: string;\n\t\t\tonDialogClose?: (result?: unknown) => void;\n\t\t};\n\n\t\t// Open create form dialog with necessary context\n\t\t// Pass onDialogClose callback so caller can refresh after successful create\n\t\tcontext.navigation!.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\tisCreate: true,\n\t\t\t\tisEager,\n\t\t\t\t// Relation context for API calls\n\t\t\t\trelation,\n\t\t\t\townerTransfer,\n\t\t\t\t// For eager mode, provide parent context so CreateActionHandler knows where to add the transfer\n\t\t\t\t...(isEager && {\n\t\t\t\t\tparentTransferId: eagerContext.parentTransferId,\n\t\t\t\t\trelationName: eagerContext.relationName,\n\t\t\t\t\tonSubmitCreate: async (data: TransferData) => {\n\t\t\t\t\t\t// In eager mode, the create action handler will add to local store\n\t\t\t\t\t\t// This callback is handled by the CreateActionHandler\n\t\t\t\t\t\treturn data;\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t},\n\t\t\teagerContext.onDialogClose\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenCreateFormActionHandler.actionType = \"OpenCreateFormActionDefinition\";\n\n/**\n * Handle form open for operation input - hook factory.\n */\nexport const useOpenOperationInputFormActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenOperationInputFormAction\");\n\t\t}\n\n\t\t// Cast to access formFor.operation if needed\n\t\tconst formDef = action.actionDefinition as OpenOpInputFormDef;\n\t\tconst formForAction = formDef.formFor as { operation?: unknown } | undefined;\n\n\t\t// Open operation input form dialog\n\t\tcontext.navigation!.openDialog(targetPage, {\n\t\t\ttransfer: context.transfer,\n\t\t\toperation: formForAction?.operation,\n\t\t\tisOperationInput: true,\n\t\t});\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenOperationInputFormActionHandler.actionType = \"OpenOperationInputFormActionDefinition\";\n","import type { ClassType, RelationType } from \"@judo/model-api\";\nimport type { IJudoRestApi } from \"../../api/i-judo-rest-api\";\nimport type { TransferStored } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext } from \"../../types\";\n\n// Interface for API context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Interface for relation context\ninterface RelationContext {\n\townerTransfer?: TransferStored;\n\townerClassType?: ClassType;\n\trelation?: RelationType;\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonRangeRequest?: (classType: ClassType) => void;\n}\n\n/**\n * Get RelationType from context.\n */\nfunction getRelation(relationContext: RelationContext, action: Action): RelationType | null {\n\tif (relationContext.relation) {\n\t\treturn relationContext.relation;\n\t}\n\t// Check if action has a relation in ownerDataElement\n\tconst ownerDataElement = action.ownerDataElement;\n\tif (ownerDataElement && ownerDataElement[\"@type\"] === \"RelationType\") {\n\t\treturn ownerDataElement as RelationType;\n\t}\n\treturn null;\n}\n\n/**\n * Handle selector open for single selection - hook factory.\n * Navigation action - no REST call.\n */\nexport const useOpenSelectorActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenSelectorAction\");\n\t\t}\n\n\t\tconst selectorContext = context as { onDialogClose?: (result?: unknown) => void };\n\n\t\tcontext.navigation?.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\townerTransfer: context.transfer,\n\t\t\t\tisSelector: true,\n\t\t\t\tselectionMode: \"single\",\n\t\t\t},\n\t\t\tselectorContext.onDialogClose\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenSelectorActionHandler.actionType = \"OpenSelectorActionDefinition\";\n\n/**\n * Handle selector open for add operation (multi-select) - hook factory.\n * Navigation action - no REST call.\n */\nexport const useOpenAddSelectorActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenAddSelectorAction\");\n\t\t}\n\n\t\tconst selectorContext = context as { onDialogClose?: (result?: unknown) => void };\n\n\t\tcontext.navigation?.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\townerTransfer: context.transfer,\n\t\t\t\tisSelector: true,\n\t\t\t\tselectionMode: \"multiple\",\n\t\t\t\toperation: \"add\",\n\t\t\t},\n\t\t\tselectorContext.onDialogClose\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenAddSelectorActionHandler.actionType = \"OpenAddSelectorActionDefinition\";\n\n/**\n * Handle selector open for set operation (single-select) - hook factory.\n * Navigation action - no REST call.\n */\nexport const useOpenSetSelectorActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenSetSelectorAction\");\n\t\t}\n\n\t\tconst selectorContext = context as { onDialogClose?: (result?: unknown) => void };\n\n\t\tcontext.navigation?.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\townerTransfer: context.transfer,\n\t\t\t\tisSelector: true,\n\t\t\t\tselectionMode: \"single\",\n\t\t\t\toperation: \"set\",\n\t\t\t},\n\t\t\tselectorContext.onDialogClose\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenSetSelectorActionHandler.actionType = \"OpenSetSelectorActionDefinition\";\n\n/**\n * Handle selector open for operation input - hook factory.\n * Navigation action - no REST call.\n * Registers an onClose callback to refresh the caller page after a\n * successful operation, but only when the caller is not in edit mode.\n */\nexport const useOpenOperationInputSelectorActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenOperationInputSelectorAction\");\n\t\t}\n\n\t\t// Capture caller page's refreshPage callback and edit mode state.\n\t\t// These come from ViewContainerRenderer's additionalContext.\n\t\tconst { refreshPage, isEditMode } = context as unknown as {\n\t\t\trefreshPage?: () => void;\n\t\t\tisEditMode?: boolean;\n\t\t};\n\n\t\tcontext.navigation?.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\townerTransfer: context.transfer,\n\t\t\t\tisSelector: true,\n\t\t\t\tisOperationInput: true,\n\t\t\t},\n\t\t\t(result) => {\n\t\t\t\t// Refresh caller page after successful operation, but only if not in edit mode\n\t\t\t\tif (result?.type === \"submitted\" && !isEditMode) {\n\t\t\t\t\trefreshPage?.();\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenOperationInputSelectorActionHandler.actionType = \"OpenOperationInputSelectorActionDefinition\";\n\n/**\n * Handle selector range query (fetch data for selector) - hook factory.\n * Fetches range data for selector table via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useSelectorRangeActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type defined for SelectorRangeAction\");\n\t\t}\n\n\t\tconst selectorContext = context as unknown as ApiContext &\n\t\t\tRelationContext &\n\t\t\tLegacyCallbacks & {\n\t\t\t\tqueryCustomizer?: Record<string, unknown>;\n\t\t\t\tonRangeResult?: (results: TransferStored[]) => void;\n\t\t\t};\n\n\t\tconst { onRangeRequest, api, onRangeResult } = selectorContext;\n\n\t\t// Use legacy callback if provided\n\t\tif (onRangeRequest) {\n\t\t\tonRangeRequest(targetType);\n\t\t\treturn;\n\t\t}\n\n\t\t// Use API if available\n\t\tif (api) {\n\t\t\tconst relation = getRelation(selectorContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for selector range\");\n\t\t\t}\n\n\t\t\tconst response = await api.getRelationRange(\n\t\t\t\trelation,\n\t\t\t\tselectorContext.ownerTransfer,\n\t\t\t\tselectorContext.queryCustomizer\n\t\t\t);\n\n\t\t\t// Signal results to selector component\n\t\t\tonRangeResult?.(response.data);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseSelectorRangeActionHandler.actionType = \"SelectorRangeActionDefinition\";\n","/**\n * JUDO REST API constants.\n * Based on REST_REQUEST_MAPPING_SPECIFICATION.md\n */\n\n// Header names\nexport const HEADER_SIGNED_IDENTIFIER = \"X-Judo-SignedIdentifier\";\nexport const HEADER_MASK = \"X-Judo-Mask\";\nexport const HEADER_MARK_SELECTED_RANGE_ITEMS = \"X-Judo-MarkSelectedRangeItems\";\nexport const HEADER_COUNT_RECORDS = \"X-Judo-CountRecords\";\n/** Response header carrying the total record count for list/range queries. */\nexport const HEADER_COUNT = \"x-judo-count\";\nexport const HEADER_TOKEN = \"X-Token\";\n\n// Default values\nexport const DEFAULT_COMMAND_MASK = \"{}\";\n\n// Path suffixes\nexport const SUFFIX_TEMPLATE = \"/~template\";\nexport const SUFFIX_GET = \"/~get\";\nexport const SUFFIX_UPDATE = \"/~update\";\nexport const SUFFIX_VALIDATE = \"/~validate\";\nexport const SUFFIX_DELETE = \"/~delete\";\nexport const SUFFIX_LIST = \"/~list\";\nexport const SUFFIX_RANGE = \"/~range\";\nexport const SUFFIX_CREATE = \"/~create\";\nexport const SUFFIX_SET = \"/~set\";\nexport const SUFFIX_UNSET = \"/~unset\";\nexport const SUFFIX_ADD = \"/~add\";\nexport const SUFFIX_REMOVE = \"/~remove\";\nexport const SUFFIX_EXPORT = \"/~export\";\nexport const SUFFIX_UPLOAD_TOKEN = \"/~upload-token\";\nexport const SUFFIX_PRINCIPAL = \"/~principal\";\nexport const SUFFIX_META = \"/~meta\";\n","/**\n * Error handler interceptor integration for the action error pipeline.\n *\n * Bridges the `errorHandlerInterceptor` customization (resolved in `@judo/core`\n * and threaded through the action context, so `@judo/actions` stays free of a\n * `@judo/core` dependency) into the built-in handlers' error handling.\n */\n\nimport type { ErrorHandlerInterceptorHook, ErrorHandlingOption } from \"@judo/model-api\";\n\n/**\n * Apply the error handler interceptor, if registered, to an error.\n *\n * Checks `shouldInterceptError(error, options)`; when it returns `true`, calls\n * `interceptError(error, options, payload, dataPath)` and returns `true` so the\n * caller skips its default error handling. When no interceptor is registered or\n * it declines the error, returns `false` and the caller runs default handling.\n *\n * @param error - The error thrown by the failing dispatch.\n * @param interceptor - The interceptor from the action context (optional).\n * @param options - Contextual options describing the failing operation.\n * @param payload - Optional request payload that triggered the error.\n * @param dataPath - Optional data path associated with the failing call.\n * @returns `true` when the interceptor handled the error (skip default handling).\n */\nexport function maybeInterceptError(\n\terror: unknown,\n\tinterceptor?: ErrorHandlerInterceptorHook,\n\toptions?: ErrorHandlingOption,\n\tpayload?: unknown,\n\tdataPath?: string\n): boolean {\n\tif (interceptor && interceptor.shouldInterceptError(error, options)) {\n\t\tinterceptor.interceptError(error, options, payload, dataPath);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n/**\n * Default CRUD error handling: store the error on the transfer so the container\n * error boundary can render it. When an `errorHandlerInterceptor` accepts the\n * error first, the default `setTransferError` is skipped.\n *\n * @param interceptor - The interceptor from the action context (may be undefined).\n * @param setTransferError - The data store's `setTransferError` (may be undefined).\n * @param transferId - The transfer id to associate the error with.\n * @param error - The error thrown by the failing dispatch.\n * @param options - Contextual options describing the failing operation.\n * @returns `true` when the interceptor handled the error (default handling skipped).\n */\nexport function handleCrudError(\n\tinterceptor: ErrorHandlerInterceptorHook | undefined,\n\tdata: { setTransferError(id: string, error: Error): void } | undefined,\n\ttransferId: string,\n\terror: unknown,\n\toptions?: ErrorHandlingOption\n): boolean {\n\tif (maybeInterceptError(error, interceptor, options)) {\n\t\treturn true;\n\t}\n\tdata?.setTransferError(transferId, error as Error);\n\treturn false;\n}\n","import {\n\ttype ClassType,\n\ttype DataElement,\n\ttype OperationType,\n\ttype PageDefinition,\n\tRelationBehaviourType,\n\ttype RelationType,\n} from \"@judo/model-api\";\nimport type { IJudoRestApi } from \"../../api/i-judo-rest-api\";\nimport type { TransferData, TransferStored, QueryCustomizer, ValidationError } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext } from \"../../types\";\nimport { HEADER_COUNT } from \"../../api/constants\";\nimport { handleCrudError } from \"../../lifecycle/error-interceptor\";\n\n// Interface for API context - will be provided via context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Extended context for page-level operations (e.g., table list)\ninterface PageContext {\n\t/** Transfer ID for the page (used to store table data) */\n\tpageTransferId?: string;\n\t/** Number of rows per page for table pagination */\n\trowsPerPage?: number;\n\t/** Whether this is a selector page (Add/Set selector) */\n\tisSelector?: boolean;\n\t/** Owner transfer for selector range queries */\n\townerTransfer?: TransferStored;\n\t/** Whether this is an operation input selector page */\n\tisOperationInput?: boolean;\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonRefresh?: (transferId: string, classType: ClassType) => Promise<TransferStored>;\n\tonListRelation?: (relation: RelationType) => Promise<TransferStored[]>;\n\tonCreate?: (transfer: TransferStored, classType: ClassType) => Promise<TransferStored>;\n\tonUpdate?: (transfer: TransferStored, classType: ClassType) => Promise<TransferStored>;\n\tonDelete?: (transferId: string, classType: ClassType) => Promise<void>;\n\tonBulkDelete?: (transferIds: string[], classType: ClassType) => Promise<void>;\n\tonRowDelete?: (transferId: string, classType: ClassType) => Promise<void>;\n\tonGetTemplate?: (classType: ClassType) => Promise<TransferStored>;\n\t/** Custom validation callback for create operations */\n\tonValidateCreate?: (\n\t\ttransfer: TransferStored,\n\t\trelation: RelationType,\n\t\townerTransfer?: TransferStored\n\t) => Promise<Record<string, string> | null>;\n}\n\n// Relation context for create operations - supports both new format (relation property) and legacy format (flat)\ninterface CreateRelationContext {\n\townerTransfer?: TransferStored;\n\trelationMetadata?:\n\t\t| RelationType\n\t\t| {\n\t\t\t\trelation?: RelationType;\n\t\t\t\tisAccess?: boolean;\n\t\t\t\t// Legacy format: relation props directly in relationMetadata\n\t\t\t\tname?: string;\n\t\t\t\towner?: unknown;\n\t\t\t\ttarget?: unknown;\n\t\t };\n}\n\n/**\n * Helper to check if an error is a ValidationError.\n */\nfunction isValidationError(error: unknown): error is ValidationError {\n\treturn error !== null && typeof error === \"object\" && (error as { name?: string }).name === \"ValidationError\";\n}\n\n/**\n * Resolve the target ClassType for an action.\n *\n * Resolution order:\n * 1. actionDefinition.targetType (explicitly set in the model)\n * 2. Page's dataElement (via eContainer traversal from Action to PageDefinition)\n * - If dataElement is a ClassType, use it directly\n * - If dataElement is a RelationType, follow its .target to get the ClassType\n *\n * UpdateActionDefinition, DeleteActionDefinition, and RefreshActionDefinition\n * typically don't have targetType set in the XMI model. The target type is\n * derived from the page's dataElement instead.\n */\nfunction resolveTargetClassType(action: Action): ClassType | undefined {\n\t// 1. Try explicit targetType on the action definition\n\tconst explicit = action.actionDefinition?.targetType as ClassType | undefined;\n\tif (explicit) {\n\t\treturn explicit;\n\t}\n\n\t// 2. Fall back to the page's dataElement\n\t// Action.eContainer is PageDefinition (since PageDefinition.actions contains Action[])\n\tconst page = (action as unknown as { eContainer?: unknown }).eContainer as PageDefinition | undefined;\n\tif (!page?.dataElement) {\n\t\treturn undefined;\n\t}\n\n\tconst dataElement = page.dataElement as DataElement & { target?: ClassType; \"@type\"?: string };\n\n\t// If the dataElement is a ClassType, use it directly\n\tif (dataElement[\"@type\"] === \"ClassType\" || dataElement[\"@type\"] === \"data:ClassType\") {\n\t\treturn dataElement as unknown as ClassType;\n\t}\n\n\t// If the dataElement is a RelationType, follow .target to get the ClassType\n\tif (dataElement[\"@type\"] === \"RelationType\" || dataElement[\"@type\"] === \"data:RelationType\") {\n\t\treturn dataElement.target;\n\t}\n\n\t// OperationParameterType (output/input) has no @type from the parser but inherits\n\t// .target from ReferenceType, just like RelationType. Follow .target if present.\n\tif (dataElement.target) {\n\t\treturn dataElement.target;\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Check if the action is for listing an ACCESS relation (top-level table load).\n * This is the case when:\n * - ownerDataElement is a RelationType\n * - The relation is an access relation (isAccess=true)\n * - No transfer exists in context (initial table load)\n */\nfunction isAccessRelationListAction(action: Action, transfer?: TransferStored): boolean {\n\tconst ownerDataElement = action.ownerDataElement;\n\tif (!ownerDataElement || ownerDataElement[\"@type\"] !== \"RelationType\") {\n\t\treturn false;\n\t}\n\n\tconst relation = ownerDataElement as RelationType;\n\t// isAccess can be boolean true or string \"true\" depending on model parsing\n\t// Use String() comparison to handle both cases\n\tconst isAccessRelation = String(relation.isAccess) === \"true\";\n\tconst hasNoEntity = !transfer?.__identifier && !transfer?.__signedIdentifier;\n\n\treturn isAccessRelation && hasNoEntity;\n}\n\n/**\n * Check if the action is for listing an transfer's relation (relation table page).\n * This is the case when:\n * - ownerDataElement is a RelationType\n * - The relation is NOT an access relation (isAccess=false)\n * - Transfer exists with a signedIdentifier (the owner transfer)\n */\nfunction isEntityRelationListAction(action: Action, transfer?: TransferStored): boolean {\n\tconst ownerDataElement = action.ownerDataElement;\n\n\t// Parser maps \"data:RelationType\" -> \"RelationType\"\n\tif (!ownerDataElement || ownerDataElement[\"@type\"] !== \"RelationType\") {\n\t\treturn false;\n\t}\n\n\tconst relation = ownerDataElement as RelationType;\n\tconst isAccessRelation = String(relation.isAccess) === \"true\";\n\tconst hasEntity = !!transfer?.__signedIdentifier;\n\n\treturn !isAccessRelation && hasEntity;\n}\n\n/**\n * Handle data refresh - hook factory.\n * Calls REST API to refresh transfer data OR list relation data.\n *\n * Three modes:\n * 1. Access relation list: When action.ownerDataElement is an access RelationType (top-level table)\n * 2. Transfer relation list: When action.ownerDataElement is a non-access RelationType with owner transfer\n * 3. Single transfer refresh: When context.transfer has an identifier\n *\n * Supports both legacy callback mode and API mode.\n */\nexport const useRefreshActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext & PageContext;\n\t\tconst { api, pageTransferId, rowsPerPage } = callbackContext;\n\n\t\t// Extract queryCustomizer and countRecords from action if provided (e.g., from table sorting/filtering)\n\t\tconst actionQueryCustomizer = (action as Action & { queryCustomizer?: QueryCustomizer }).queryCustomizer;\n\t\tconst countRecords = (action as Action & { countRecords?: boolean }).countRecords;\n\n\t\t// Check if this is an ACCESS relation list operation (top-level table load)\n\t\tif (isAccessRelationListAction(action, transfer)) {\n\t\t\tconst relation = action.ownerDataElement as RelationType;\n\n\t\t\t// Singleton vs collection dispatch:\n\t\t\t// The BE emits two different endpoints for access relations depending\n\t\t\t// on `isCollection`:\n\t\t\t// - isCollection === true -> `<rel>/~list` (returns Array<Transfer>)\n\t\t\t// - isCollection !== true -> `<rel>/~get` (returns Transfer | null)\n\t\t\t// This mirrors the legacy `judo-ui-react-template` generator (see\n\t\t\t// `relationServiceImpl.ts.hbs`: list-branch under `relation.isListable &&\n\t\t\t// relation.isCollection`, refresh-branch under `relation.isAccess &&\n\t\t\t// !relation.isCollection`). Without this dispatch, singleton access\n\t\t\t// relations (e.g. `profileSettings`, `userReservations` on a singleton\n\t\t\t// actor) 404 because the BE has no `~list` route for them.\n\t\t\t//\n\t\t\t// The model's EMF default for `isCollection` is `true`, so unset is\n\t\t\t// treated as collection here (matching the legacy generator and the\n\t\t\t// spec in `packages/model-api/src/data/elements.ts`).\n\t\t\tconst isCollection = relation.isCollection === undefined ? true : String(relation.isCollection) === \"true\";\n\n\t\t\t// Use provided pageTransferId or generate one from action\n\t\t\tconst tableEntityId = pageTransferId ?? `table::${action[\"xmi:id\"]}`;\n\t\t\tcontext.data?.setTransferLoading(tableEntityId, true);\n\n\t\t\ttry {\n\t\t\t\tconst { onListRelation } = callbackContext;\n\n\t\t\t\tif (onListRelation) {\n\t\t\t\t\t// Use legacy callback if provided. Callbacks are list-shaped\n\t\t\t\t\t// historically; singletons are surfaced as a single-element list.\n\t\t\t\t\tconst listData = await onListRelation(relation);\n\t\t\t\t\tconst tableData: TransferData = { __items: listData };\n\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, tableData);\n\t\t\t\t} else if (api) {\n\t\t\t\t\tif (isCollection) {\n\t\t\t\t\t\t// Collection access relation → `<rel>/~list`\n\t\t\t\t\t\tconst queryCustomizer: QueryCustomizer = {\n\t\t\t\t\t\t\t_seek: { limit: rowsPerPage ?? 10 },\n\t\t\t\t\t\t\t...actionQueryCustomizer,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst response = await api.listRelation(relation, undefined, queryCustomizer, countRecords);\n\t\t\t\t\t\tconst totalCountHeader = response.headers.get(HEADER_COUNT);\n\t\t\t\t\t\tconst totalCount = totalCountHeader ? Number.parseInt(totalCountHeader, 10) : undefined;\n\t\t\t\t\t\tconst tableData: TransferData = { __items: response.data };\n\t\t\t\t\t\tif (totalCount !== undefined && !Number.isNaN(totalCount)) {\n\t\t\t\t\t\t\ttableData.__totalCount = totalCount;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, tableData);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Singleton access relation → `<rel>/~get`. The BE rejects\n\t\t\t\t\t\t// list-style query parameters (`_seek`, `_orderBy`) on singleton\n\t\t\t\t\t\t// `~get` calls (it routes them through the same dispatcher path\n\t\t\t\t\t\t// as `~list`, where the ordering attribute is resolved against\n\t\t\t\t\t\t// the singleton transfer class — a class that has no such\n\t\t\t\t\t\t// attributes, producing\n\t\t\t\t\t\t// `NoSuchElementException: No value present` (HTTP 500)).\n\t\t\t\t\t\t// Only `_mask` is meaningful on a singleton refresh.\n\t\t\t\t\t\tconst singletonQuery: QueryCustomizer | undefined = actionQueryCustomizer?._mask\n\t\t\t\t\t\t\t? { _mask: actionQueryCustomizer._mask }\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst response = await api.refreshAccessRelation(relation, singletonQuery);\n\t\t\t\t\t\tconst single = response.data as TransferStored | null | undefined;\n\t\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, (single ?? {}) as unknown as TransferData);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(\"API not available in context\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, tableEntityId, error);\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, false);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Check if this is an ENTITY relation list operation (relation table page)\n\t\tif (isEntityRelationListAction(action, transfer)) {\n\t\t\tconst relation = action.ownerDataElement as RelationType;\n\n\t\t\t// Use provided pageTransferId or generate one from action\n\t\t\tconst tableEntityId = pageTransferId ?? `table::${action[\"xmi:id\"]}`;\n\t\t\tcontext.data?.setTransferLoading(tableEntityId, true);\n\n\t\t\ttry {\n\t\t\t\tif (api) {\n\t\t\t\t\t// For transfer relations, pass the relation directly to the API\n\t\t\t\t\t// Build query customizer: merge action's queryCustomizer with pagination\n\t\t\t\t\tconst queryCustomizer: QueryCustomizer = {\n\t\t\t\t\t\t_seek: { limit: rowsPerPage ?? 10 },\n\t\t\t\t\t\t...actionQueryCustomizer,\n\t\t\t\t\t};\n\t\t\t\t\t// Pass the owner transfer to include X-Judo-SignedIdentifier header\n\t\t\t\t\tconst response = await api.listRelation(relation, transfer, queryCustomizer, countRecords);\n\t\t\t\t\tconst listData = response.data;\n\n\t\t\t\t\t// Extract total count from response header if present\n\t\t\t\t\tconst totalCountHeader = response.headers.get(HEADER_COUNT);\n\t\t\t\t\tconst totalCount = totalCountHeader ? Number.parseInt(totalCountHeader, 10) : undefined;\n\n\t\t\t\t\t// Store the list data - wrap in object with __items key for table consumption\n\t\t\t\t\tconst tableData: TransferData = { __items: listData };\n\t\t\t\t\tif (totalCount !== undefined && !Number.isNaN(totalCount)) {\n\t\t\t\t\t\ttableData.__totalCount = totalCount;\n\t\t\t\t\t}\n\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, tableData);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(\"API not available in context\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, tableEntityId, error);\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, false);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Check if this is a SELECTOR range query (Add/Set selector dialog)\n\t\t// Selector pages need to fetch the available range of items via getRelationRange()\n\t\tif (callbackContext.isSelector) {\n\t\t\tconst ownerDataElement = action.ownerDataElement;\n\n\t\t\t// Relation selector: ownerDataElement is a RelationType → getRelationRange\n\t\t\tif (ownerDataElement && ownerDataElement[\"@type\"] === \"RelationType\") {\n\t\t\t\tconst relation = ownerDataElement as RelationType;\n\t\t\t\tconst tableEntityId = pageTransferId ?? `table::${action[\"xmi:id\"]}`;\n\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, true);\n\n\t\t\t\ttry {\n\t\t\t\t\tif (api) {\n\t\t\t\t\t\tconst queryCustomizer: QueryCustomizer = {\n\t\t\t\t\t\t\t_seek: { limit: rowsPerPage ?? 10 },\n\t\t\t\t\t\t\t...actionQueryCustomizer,\n\t\t\t\t\t\t};\n\t\t\t\t\t\t// Range calls only need __signedIdentifier on the owner - strip __identifier\n\t\t\t\t\t\tconst rangeOwner = callbackContext.ownerTransfer?.__signedIdentifier\n\t\t\t\t\t\t\t? ({\n\t\t\t\t\t\t\t\t\t__signedIdentifier: callbackContext.ownerTransfer.__signedIdentifier,\n\t\t\t\t\t\t\t\t} as TransferStored)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst response = await api.getRelationRange(relation, rangeOwner, queryCustomizer, countRecords);\n\t\t\t\t\t\tconst rangeData = response.data;\n\n\t\t\t\t\t\t// Extract total count from response header if present\n\t\t\t\t\t\tconst totalCountHeader = response.headers.get(HEADER_COUNT);\n\t\t\t\t\t\tconst totalCount = totalCountHeader ? Number.parseInt(totalCountHeader, 10) : undefined;\n\n\t\t\t\t\t\tconst tableData: TransferData = { __items: rangeData };\n\t\t\t\t\t\tif (totalCount !== undefined && !Number.isNaN(totalCount)) {\n\t\t\t\t\t\t\ttableData.__totalCount = totalCount;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, tableData);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new Error(\"API not available in context\");\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, tableEntityId, error);\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, false);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Operation input selector: ownerDataElement is an OperationType → getOperationInputRange\n\t\t\t// Derive the owning ClassType from the OperationType's eContainer (set during model resolution)\n\t\t\tif (ownerDataElement && ownerDataElement[\"@type\"] === \"OperationType\") {\n\t\t\t\tconst operationType = ownerDataElement as OperationType;\n\t\t\t\tconst ownerClassType = (ownerDataElement as unknown as { eContainer?: ClassType }).eContainer;\n\n\t\t\t\tif (!ownerClassType) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"Cannot determine owning ClassType for operation input selector (OperationType.eContainer is missing)\"\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst tableEntityId = pageTransferId ?? `table::${action[\"xmi:id\"]}`;\n\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, true);\n\n\t\t\t\ttry {\n\t\t\t\t\tif (api) {\n\t\t\t\t\t\tconst queryCustomizer: QueryCustomizer = {\n\t\t\t\t\t\t\t_seek: { limit: rowsPerPage ?? 10 },\n\t\t\t\t\t\t\t...actionQueryCustomizer,\n\t\t\t\t\t\t};\n\t\t\t\t\t\t// Range calls only need __signedIdentifier on the owner - strip __identifier\n\t\t\t\t\t\tconst rangeOwner = callbackContext.ownerTransfer?.__signedIdentifier\n\t\t\t\t\t\t\t? ({\n\t\t\t\t\t\t\t\t\t__signedIdentifier: callbackContext.ownerTransfer.__signedIdentifier,\n\t\t\t\t\t\t\t\t} as TransferStored)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst response = await api.getOperationInputRange(\n\t\t\t\t\t\t\townerClassType,\n\t\t\t\t\t\t\toperationType,\n\t\t\t\t\t\t\trangeOwner,\n\t\t\t\t\t\t\tqueryCustomizer,\n\t\t\t\t\t\t\tcountRecords\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst rangeData = response.data;\n\n\t\t\t\t\t\t// Extract total count from response header if present\n\t\t\t\t\t\tconst totalCountHeader = response.headers.get(HEADER_COUNT);\n\t\t\t\t\t\tconst totalCount = totalCountHeader ? Number.parseInt(totalCountHeader, 10) : undefined;\n\n\t\t\t\t\t\tconst tableData: TransferData = { __items: rangeData };\n\t\t\t\t\t\tif (totalCount !== undefined && !Number.isNaN(totalCount)) {\n\t\t\t\t\t\t\ttableData.__totalCount = totalCount;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, tableData);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new Error(\"API not available in context\");\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, tableEntityId, error);\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, false);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Single transfer refresh mode\n\t\tconst transferId = transfer?.__identifier ?? transfer?.__signedIdentifier;\n\t\tif (!transferId) {\n\t\t\t// No transfer to refresh and not a list operation - nothing to do\n\t\t\treturn;\n\t\t}\n\n\t\t// Eager mode: seed the data store from the parent transfer's relation array.\n\t\t// No REST call — the authoritative data lives locally in the parent and was\n\t\t// placed there by CreateActionHandler / UpdateActionHandler.\n\t\t// context.transfer only carries identifiers (ViewContainerRenderer strips\n\t\t// fields), so we must look up the full transfer from the parent's store.\n\t\tif (context.isEager) {\n\t\t\tconst eagerCtx = context as TypedActionHandlerContext & {\n\t\t\t\tparentTransferId?: string;\n\t\t\t\trelationName?: string;\n\t\t\t};\n\n\t\t\tif (eagerCtx.parentTransferId && eagerCtx.relationName && context.data) {\n\t\t\t\tconst parentData = context.data.getSnapshot((state: unknown) => {\n\t\t\t\t\tconst typedState = state as { transfers: Map<string, { data: TransferData | null }> };\n\t\t\t\t\treturn typedState.transfers.get(eagerCtx.parentTransferId!)?.data;\n\t\t\t\t}) as TransferData | undefined;\n\n\t\t\t\tif (parentData) {\n\t\t\t\t\tconst relationValue = (parentData as Record<string, unknown>)[eagerCtx.relationName!];\n\n\t\t\t\t\tif (Array.isArray(relationValue)) {\n\t\t\t\t\t\t// Collection relation (Table) — find matching transfer in array\n\t\t\t\t\t\tconst fullEntity = relationValue.find((item: TransferStored) => {\n\t\t\t\t\t\t\tif (transfer!.__signedIdentifier && item.__signedIdentifier === transfer!.__signedIdentifier) return true;\n\t\t\t\t\t\t\tif (transfer!.__identifier && item.__identifier === transfer!.__identifier) return true;\n\t\t\t\t\t\t\tconst itemTempId = (item as { __tempId?: string }).__tempId;\n\t\t\t\t\t\t\tconst entityTempId = (transfer as { __tempId?: string })?.__tempId;\n\t\t\t\t\t\t\tif (itemTempId && entityTempId && itemTempId === entityTempId) return true;\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (fullEntity) {\n\t\t\t\t\t\t\tcontext.data.setTransferData(transferId, fullEntity);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (relationValue && typeof relationValue === \"object\") {\n\t\t\t\t\t\t// Single relation (Link) — use the value directly\n\t\t\t\t\t\tcontext.data.setTransferData(transferId, relationValue as TransferStored);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Fallback: store whatever we have (at least the identifiers)\n\t\t\tcontext.data?.setTransferData(transferId, transfer!);\n\t\t\treturn;\n\t\t}\n\n\t\tcontext.data?.setTransferLoading(transferId, true);\n\n\t\ttry {\n\t\t\tconst targetType = resolveTargetClassType(action);\n\t\t\tif (!targetType) {\n\t\t\t\tthrow new Error(\"No target type for refresh\");\n\t\t\t}\n\n\t\t\tconst { onRefresh } = callbackContext;\n\n\t\t\tlet refreshedEntity: TransferStored;\n\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onRefresh) {\n\t\t\t\trefreshedEntity = await onRefresh(transferId, targetType);\n\t\t\t} else if (api) {\n\t\t\t\t// Use API if available\n\t\t\t\t// Use actionQueryCustomizer if provided (e.g., for custom masks)\n\t\t\t\tconst response = await api.refresh(targetType, transfer!, actionQueryCustomizer);\n\t\t\t\trefreshedEntity = response.data;\n\t\t\t} else {\n\t\t\t\tthrow new Error(\"API not available in context\");\n\t\t\t}\n\n\t\t\tcontext.data?.setTransferData(transferId, refreshedEntity);\n\t\t} catch (error) {\n\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, transferId, error);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tcontext.data?.setTransferLoading(transferId, false);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseRefreshActionHandler.actionType = \"RefreshActionDefinition\";\n\n// Local storage context for eager table operations\ninterface LocalStorageContext {\n\t/** Parent transfer ID for storing new items in local table data */\n\tparentTransferId?: string;\n}\n\n/**\n * Handle transfer create - hook factory.\n *\n * Create behavior varies based on context:\n *\n * 1. **Eager components** (isEager=true):\n * - Validates data via validateCreateRelation API if relation is provided\n * - If validation fails, sets field errors via validation context (dialog stays open)\n * - If validation passes, returns data to caller (no REST create call)\n * - Caller (table/link) adds transfer to local __items array\n * - Transfer is persisted when parent is saved\n *\n * 2. **Lazy components** (isEager=false, default):\n * - Validates data via validateCreateRelation API\n * - If validation fails, sets field errors via validation context (dialog stays open)\n * - If validation passes, creates transfer via createRelation API\n * - BLOCKED if on a FORM page (forms save all data together)\n * - BLOCKED if on a VIEW page that is in edit mode (unsaved changes)\n *\n * After creation, optionally navigates to view page based on autoOpenAfterCreate.\n *\n * Supports both legacy callback mode and API mode.\n */\nexport const useCreateActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Get transfer from context or from data store using pageTransferId\n\t\t// For create forms, transfer data is stored in data store by GetTemplateActionHandler\n\t\tlet transfer = context.transfer as TransferStored | undefined;\n\t\tif (!transfer && context.data) {\n\t\t\tconst pageTransferId = (context as { pageTransferId?: string }).pageTransferId;\n\t\t\tif (pageTransferId) {\n\t\t\t\ttransfer = context.data.getSnapshot((state: unknown) => {\n\t\t\t\t\tconst typedState = state as { transfers: Map<string, { data: TransferData | null }> };\n\t\t\t\t\treturn typedState.transfers.get(pageTransferId)?.data;\n\t\t\t\t}) as TransferStored | undefined;\n\t\t\t}\n\t\t}\n\n\t\tif (!transfer) {\n\t\t\tthrow new Error(\"No transfer data to create\");\n\t\t}\n\n\t\tconst { isEager, pageType, isEditMode, isPageAction, validation, createDialog } = context;\n\n\t\t// For lazy components, check if create is allowed\n\t\t// Page-level actions (dialog footer buttons) are always allowed\n\t\tif (!isEager && !isPageAction) {\n\t\t\tif (pageType === \"FORM\") {\n\t\t\t\tthrow new Error(\"Create operation is not allowed on FORM pages. Save the form first.\");\n\t\t\t}\n\t\t\tif (pageType === \"VIEW\" && isEditMode) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Create operation is not allowed while the view has unsaved changes. Save or cancel changes first.\"\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Use pageTransferId if available (for dialogs), otherwise transfer.__identifier or \"new\"\n\t\tconst pageTransferId = (context as { pageTransferId?: string }).pageTransferId;\n\t\tconst transferId = pageTransferId ?? transfer.__identifier ?? \"new\";\n\t\tcontext.data?.setTransferLoading(transferId, true);\n\n\t\t// Clear any previous validation errors before attempting create\n\t\tvalidation?.clearErrors();\n\n\t\ttry {\n\t\t\tconst callbackContext = context as unknown as LegacyCallbacks &\n\t\t\t\tApiContext &\n\t\t\t\tCreateRelationContext &\n\t\t\t\tLocalStorageContext;\n\t\t\tconst { onCreate, onValidateCreate, api, relationMetadata, ownerTransfer, parentTransferId } = callbackContext;\n\n\t\t\t// Get relation from createDialog context or relationMetadata or action.ownerDataElement\n\t\t\t// Support both new format (relationMetadata.relation) and legacy format (relationMetadata as RelationType)\n\t\t\t// Priority: action.ownerDataElement is most authoritative (model-defined for this specific action),\n\t\t\t// then createDialog context (set by the dialog opener), then relationMetadata (legacy).\n\t\t\tlet relation: RelationType | undefined;\n\t\t\t// 1. Prefer action.ownerDataElement - it's the model-defined relation for this specific create action\n\t\t\t// (e.g., the form page's Create action points to \"stars\", not the parent \"galaxies\" access relation)\n\t\t\tif (action.ownerDataElement?.[\"@type\"] === \"RelationType\") {\n\t\t\t\trelation = action.ownerDataElement as RelationType;\n\t\t\t}\n\t\t\t// 2. Fall back to createDialog context (set by the dialog opener)\n\t\t\tif (!relation) {\n\t\t\t\trelation = createDialog?.relation as RelationType | undefined;\n\t\t\t}\n\t\t\t// 3. Fall back to relationMetadata\n\t\t\tif (!relation && relationMetadata) {\n\t\t\t\t// Check if relationMetadata has nested relation property\n\t\t\t\tif (\"relation\" in relationMetadata && relationMetadata.relation) {\n\t\t\t\t\trelation = relationMetadata.relation as RelationType;\n\t\t\t\t} else if (\"name\" in relationMetadata && relationMetadata.name) {\n\t\t\t\t\t// Legacy format: relationMetadata is the relation itself\n\t\t\t\t\trelation = relationMetadata as unknown as RelationType;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Get targetType from relation.target or actionDefinition.targetType\n\t\t\tconst targetType =\n\t\t\t\t(relation?.target as ClassType | undefined) ?? (action.actionDefinition.targetType as ClassType | undefined);\n\t\t\tif (!targetType) {\n\t\t\t\tthrow new Error(\"No target type for create\");\n\t\t\t}\n\t\t\tconst dialogOwnerEntity = (createDialog?.ownerTransfer as TransferStored) ?? ownerTransfer;\n\n\t\t\tlet createdEntity: TransferStored;\n\n\t\t\t// --- VALIDATION STEP (EAGER MODE ONLY) ---\n\t\t\t// For eager mode, validate before adding to local store since there's no immediate server call\n\t\t\t// For lazy mode, skip separate validation - the createRelation API will validate during create\n\t\t\t// and return validation errors which we'll handle there\n\t\t\tconst hasValidateCreateBehaviour = relation?.behaviours?.includes(RelationBehaviourType.VALIDATE_CREATE);\n\n\t\t\tif (isEager && hasValidateCreateBehaviour && api) {\n\t\t\t\ttry {\n\t\t\t\t\t// Call validateCreateRelation API (eager mode only)\n\t\t\t\t\tawait api.validateCreateRelation(relation!, dialogOwnerEntity, transfer);\n\t\t\t\t} catch (validationError) {\n\t\t\t\t\t// Check if it's a validation error with field-level feedback\n\t\t\t\t\tif (isValidationError(validationError)) {\n\t\t\t\t\t\t// Set field errors in validation context so form can display them\n\t\t\t\t\t\tconst fieldErrors = validationError.toFieldErrors();\n\t\t\t\t\t\tif (validation && Object.keys(fieldErrors).length > 0) {\n\t\t\t\t\t\t\tvalidation.setErrors(fieldErrors);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Re-throw to stop the create process (dialog stays open)\n\t\t\t\t\t\tthrow validationError;\n\t\t\t\t\t}\n\t\t\t\t\t// For other errors, re-throw as-is\n\t\t\t\t\tthrow validationError;\n\t\t\t\t}\n\t\t\t} else if (isEager && hasValidateCreateBehaviour && onValidateCreate && relation) {\n\t\t\t\t// Use legacy validation callback if provided (only if relation supports validation)\n\t\t\t\tconst fieldErrors = await onValidateCreate(transfer, relation, dialogOwnerEntity);\n\t\t\t\tif (fieldErrors && Object.keys(fieldErrors).length > 0) {\n\t\t\t\t\tvalidation?.setErrors(fieldErrors);\n\t\t\t\t\tthrow new Error(\"Validation failed\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// --- CREATE STEP ---\n\t\t\t// Eager mode: add to local store only, no REST call\n\t\t\tif (isEager) {\n\t\t\t\t// Generate a temporary client-side ID for tracking the new transfer\n\t\t\t\t// Note: __identifier is backend-assigned, so we use __tempId for frontend-created transfers\n\t\t\t\tconst tempId = `temp::${Date.now()}::${Math.random().toString(36).substring(2, 9)}`;\n\t\t\t\tcreatedEntity = {\n\t\t\t\t\t...transfer,\n\t\t\t\t\t__tempId: tempId, // Frontend-only temporary ID (not __identifier which is backend-assigned)\n\t\t\t\t\t__isNew: true, // Mark as new/unsaved\n\t\t\t\t};\n\n\t\t\t\t// Get parent context from createDialog (preferred) or legacy context\n\t\t\t\tconst eagerParentEntityId = createDialog?.parentTransferId ?? parentTransferId;\n\t\t\t\tconst eagerRelationName = createDialog?.relationName;\n\n\t\t\t\t// If we have a parent transfer ID, add the created transfer to the parent's data\n\t\t\t\tif (eagerParentEntityId && context.data) {\n\t\t\t\t\tconst parentData = context.data.getSnapshot((state: unknown) => {\n\t\t\t\t\t\tconst typedState = state as { transfers: Map<string, { data: TransferData | null }> };\n\t\t\t\t\t\treturn typedState.transfers.get(eagerParentEntityId)?.data;\n\t\t\t\t\t}) as TransferData | undefined;\n\n\t\t\t\t\tif (eagerRelationName) {\n\t\t\t\t\t\t// Eager component embedded in VIEW page: add to parent transfer's relation property\n\t\t\t\t\t\tconst currentValue = (parentData as any)?.[eagerRelationName];\n\n\t\t\t\t\t\tif (Array.isArray(currentValue)) {\n\t\t\t\t\t\t\t// Collection relation (Table) — append to array\n\t\t\t\t\t\t\tcontext.data.updateTransferFields(eagerParentEntityId, {\n\t\t\t\t\t\t\t\t[eagerRelationName]: [...currentValue, createdEntity],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Single relation (Link) — set the field directly\n\t\t\t\t\t\t\tcontext.data.updateTransferFields(eagerParentEntityId, {\n\t\t\t\t\t\t\t\t[eagerRelationName]: createdEntity,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Fallback: add to __items array (legacy behavior for standalone tables)\n\t\t\t\t\t\tconst currentItems = (parentData?.__items as TransferStored[] | undefined) ?? [];\n\t\t\t\t\t\tconst newItems = [...currentItems, createdEntity];\n\n\t\t\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\t\t\tcontext.data.updateTransferFields(eagerParentEntityId, {\n\t\t\t\t\t\t\t__items: newItems,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// For eager mode with onSubmitCreate callback, invoke it\n\t\t\t\tif (createDialog?.onSubmitCreate) {\n\t\t\t\t\tawait createDialog.onSubmitCreate(createdEntity);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Lazy mode: create via REST API\n\t\t\t\tif (onCreate) {\n\t\t\t\t\t// Use legacy callback if provided\n\t\t\t\t\tcreatedEntity = await onCreate(transfer, targetType);\n\t\t\t\t} else if (api && relation) {\n\t\t\t\t\t// Use API if available - pass the relation directly\n\t\t\t\t\t// Handle validation errors from create endpoint\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await api.createRelation(relation, dialogOwnerEntity, transfer);\n\t\t\t\t\t\tcreatedEntity = result.data;\n\t\t\t\t\t} catch (createError) {\n\t\t\t\t\t\t// Check if it's a validation error with field-level feedback\n\t\t\t\t\t\tif (isValidationError(createError)) {\n\t\t\t\t\t\t\t// Set field errors in validation context so form can display them\n\t\t\t\t\t\t\tconst fieldErrors = createError.toFieldErrors();\n\t\t\t\t\t\t\tif (validation && Object.keys(fieldErrors).length > 0) {\n\t\t\t\t\t\t\t\tvalidation.setErrors(fieldErrors);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Re-throw to stop the create process (dialog stays open)\n\t\t\t\t\t\t\tthrow createError;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// For other errors, re-throw as-is\n\t\t\t\t\t\tthrow createError;\n\t\t\t\t\t}\n\t\t\t\t} else if (!onCreate && !api) {\n\t\t\t\t\t// No callback or API - nothing to do\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"Create requires relation context. Provide relation in createDialog or relationMetadata in additionalContext.\"\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Close dialog with success result so caller can refresh\n\t\t\tif (context.closeDialog) {\n\t\t\t\tcontext.closeDialog({ type: \"created\", isEager: isEager ?? false });\n\t\t\t}\n\n\t\t\t// Navigate to view page with created transfer if autoOpenAfterCreate is enabled\n\t\t\t// CreateActionDefinition has autoOpenAfterCreate attribute (defaults to true based on meta-model)\n\t\t\tconst actionDef = action.actionDefinition as { autoOpenAfterCreate?: boolean };\n\t\t\tconst shouldAutoOpen = actionDef.autoOpenAfterCreate !== false; // Default true\n\n\t\t\tconst viewPage = action.targetPageDefinition;\n\t\t\tif (shouldAutoOpen && viewPage && context.navigation && !isEager) {\n\t\t\t\t// Only navigate for lazy (persisted) transfers\n\t\t\t\tcontext.navigation.replacePage(viewPage, { transfer: createdEntity });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// For validation errors, don't set transfer error (let validation context handle it)\n\t\t\tif (!isValidationError(error)) {\n\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, transferId, error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tcontext.data?.setTransferLoading(transferId, false);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseCreateActionHandler.actionType = \"CreateActionDefinition\";\n\n/**\n * Handle transfer update - hook factory.\n * Updates an existing transfer via REST API.\n * Supports both legacy callback mode and API mode.\n *\n * In eager mode (aggregated child transfers opened from an eager table):\n * - Skips REST API calls entirely\n * - Updates the parent transfer's relation array with the modified transfer data\n * - The actual persistence happens when the aggregate root (parent) is saved\n */\nexport const useUpdateActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst contextEntity = context.transfer as TransferStored | undefined;\n\t\tconst rawEntityId = contextEntity?.__identifier ?? contextEntity?.__signedIdentifier;\n\t\tif (!rawEntityId) {\n\t\t\tthrow new Error(\"No transfer to update (missing identifier)\");\n\t\t}\n\n\t\t// For dialog dispatchers, context.transfer carries the original transfer identifiers\n\t\t// (e.g., from params.transfer), while the actual data is stored under the\n\t\t// dialog-specific pageTransferId (e.g., \"dialog::transfer::abc123\").\n\t\t// Prefer pageTransferId for data store lookups when available.\n\t\tconst pageTransferId = (context as { pageTransferId?: string }).pageTransferId;\n\t\tconst transferId = pageTransferId ?? rawEntityId;\n\n\t\t// Read the full transfer from the data store.\n\t\t// context.transfer may only contain identifiers (__identifier / __signedIdentifier)\n\t\t// because the dispatcher receives a minimal stub. The actual user-modified fields\n\t\t// are in the data store, populated by the initial refresh and updated by bindings.\n\t\tlet transfer: TransferStored | undefined;\n\t\tif (context.data) {\n\t\t\ttransfer = context.data.getSnapshot((state: unknown) => {\n\t\t\t\tconst typedState = state as { transfers: Map<string, { data: TransferData | null }> };\n\t\t\t\treturn typedState.transfers.get(transferId)?.data;\n\t\t\t}) as TransferStored | undefined;\n\t\t}\n\n\t\t// Fall back to context.transfer if data store lookup fails (e.g., legacy callback mode)\n\t\tif (!transfer) {\n\t\t\ttransfer = contextEntity;\n\t\t}\n\n\t\tcontext.data?.setTransferLoading(transferId, true);\n\n\t\ttry {\n\t\t\tconst { isEager } = context;\n\t\t\tconst eagerContext = context as TypedActionHandlerContext & {\n\t\t\t\tparentTransferId?: string;\n\t\t\t\trelationName?: string;\n\t\t\t};\n\n\t\t\t// Eager mode: update parent transfer's local relation data, no REST call\n\t\t\tif (isEager) {\n\t\t\t\tconst { parentTransferId, relationName } = eagerContext;\n\n\t\t\t\tif (parentTransferId && relationName && context.data) {\n\t\t\t\t\tconst parentData = context.data.getSnapshot((state: unknown) => {\n\t\t\t\t\t\tconst typedState = state as { transfers: Map<string, { data: TransferData | null }> };\n\t\t\t\t\t\treturn typedState.transfers.get(parentTransferId)?.data;\n\t\t\t\t\t}) as TransferData | undefined;\n\n\t\t\t\t\tif (parentData) {\n\t\t\t\t\t\tconst currentValue = (parentData as Record<string, unknown>)[relationName];\n\n\t\t\t\t\t\tif (Array.isArray(currentValue)) {\n\t\t\t\t\t\t\t// Collection relation (Table) — find and replace matching transfer in array\n\t\t\t\t\t\t\tconst updatedItems = currentValue.map((item: TransferStored) => {\n\t\t\t\t\t\t\t\tconst itemTempId = (item as { __tempId?: string }).__tempId;\n\t\t\t\t\t\t\t\tconst entityTempId = (transfer as { __tempId?: string }).__tempId;\n\n\t\t\t\t\t\t\t\tif (itemTempId && entityTempId && itemTempId === entityTempId) {\n\t\t\t\t\t\t\t\t\treturn { ...transfer! };\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (item.__identifier && item.__identifier === transfer!.__identifier) {\n\t\t\t\t\t\t\t\t\treturn { ...transfer! };\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (item.__signedIdentifier && item.__signedIdentifier === transfer!.__signedIdentifier) {\n\t\t\t\t\t\t\t\t\treturn { ...transfer! };\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn item;\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t\t\t\t[relationName]: updatedItems,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Single relation (Link) — replace the entire field value\n\t\t\t\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t\t\t\t[relationName]: { ...transfer! },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Reset the transfer in the data store (marks it as \"saved\" within the dialog)\n\t\t\t\tcontext.data?.setTransferData(transferId, transfer!);\n\n\t\t\t\t// Navigate back (close the dialog) after successful eager update\n\t\t\t\tcontext.navigation?.goBack();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Lazy mode: update via REST API\n\t\t\tconst targetType = resolveTargetClassType(action);\n\t\t\tif (!targetType) {\n\t\t\t\tthrow new Error(\"No target type for update\");\n\t\t\t}\n\n\t\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\t\tconst { onUpdate, api } = callbackContext;\n\n\t\t\tlet updatedEntity: TransferStored;\n\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onUpdate) {\n\t\t\t\tupdatedEntity = await onUpdate(transfer!, targetType);\n\t\t\t} else if (api) {\n\t\t\t\t// Use API if available - pass the ClassType directly\n\t\t\t\tconst response = await api.update(targetType, transfer!);\n\t\t\t\tupdatedEntity = response.data;\n\n\t\t\t\t// Refresh after successful update to get the complete transfer state\n\t\t\t\t// (the update response may only contain the masked subset of fields)\n\t\t\t\tconst refreshResponse = await api.refresh(targetType, updatedEntity);\n\t\t\t\tupdatedEntity = refreshResponse.data;\n\t\t\t} else {\n\t\t\t\t// No callback or API - nothing to do\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tcontext.data?.setTransferData(transferId, updatedEntity);\n\t\t} catch (error) {\n\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, transferId, error);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tcontext.data?.setTransferLoading(transferId, false);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseUpdateActionHandler.actionType = \"UpdateActionDefinition\";\n\n/**\n * Handle transfer delete - hook factory.\n * Deletes an transfer via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useDeleteActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = transfer?.__identifier ?? transfer?.__signedIdentifier;\n\t\tif (!transferId) {\n\t\t\tthrow new Error(\"No transfer to delete (missing identifier)\");\n\t\t}\n\n\t\tcontext.data?.setTransferLoading(transferId, true);\n\n\t\ttry {\n\t\t\tconst targetType = resolveTargetClassType(action);\n\t\t\tif (!targetType) {\n\t\t\t\tthrow new Error(\"No target type for delete\");\n\t\t\t}\n\n\t\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\t\tconst { onDelete, api } = callbackContext;\n\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onDelete) {\n\t\t\t\tawait onDelete(transferId, targetType);\n\t\t\t} else if (api) {\n\t\t\t\t// Use API if available - pass the ClassType directly\n\t\t\t\tawait api.delete(targetType, transfer!);\n\t\t\t} else {\n\t\t\t\t// No callback or API - nothing to do\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Clear transfer from store and navigate back\n\t\t\tcontext.data?.clearTransfer(transferId);\n\t\t\tcontext.navigation?.goBack();\n\t\t} catch (error) {\n\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, transferId, error);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseDeleteActionHandler.actionType = \"DeleteActionDefinition\";\n\n/**\n * Handle bulk delete - hook factory.\n * Deletes multiple selected transfers via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useBulkDeleteActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst selectedRows = context.selectedRows as TransferStored[] | undefined;\n\t\tif (!selectedRows || selectedRows.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type for bulk delete\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onBulkDelete, api } = callbackContext;\n\n\t\tconst transferIds = selectedRows\n\t\t\t.map((row) => row.__identifier ?? row.__signedIdentifier)\n\t\t\t.filter(Boolean) as string[];\n\n\t\t// Use legacy callback if provided\n\t\tif (onBulkDelete) {\n\t\t\tawait onBulkDelete(transferIds, targetType);\n\t\t} else if (api) {\n\t\t\t// Use API if available - pass the ClassType directly\n\t\t\t// Delete all selected transfers\n\t\t\tconst deletePromises = selectedRows\n\t\t\t\t.filter((row) => row.__signedIdentifier)\n\t\t\t\t.map((row) => api.delete(targetType, row));\n\n\t\t\tawait Promise.all(deletePromises);\n\t\t} else {\n\t\t\t// No callback or API - nothing to do\n\t\t\treturn;\n\t\t}\n\n\t\t// Clear deleted transfers from store\n\t\tfor (const rowId of transferIds) {\n\t\t\tcontext.data?.clearTransfer(rowId);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseBulkDeleteActionHandler.actionType = \"BulkDeleteActionDefinition\";\n\n/**\n * Handle single row delete from table - hook factory.\n * Deletes a single transfer from a table row via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useRowDeleteActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = transfer?.__identifier ?? transfer?.__signedIdentifier;\n\n\t\tconst eagerContext = context as unknown as {\n\t\t\tisEager?: boolean;\n\t\t\tparentTransferId?: string;\n\t\t\trelationName?: string;\n\t\t};\n\t\tconst { isEager, parentTransferId, relationName } = eagerContext;\n\n\t\t// Eager mode: remove transfer from parent's local data store\n\t\tif (isEager && parentTransferId && context.data) {\n\t\t\tconst parentData = context.data.getSnapshot((state: unknown) => {\n\t\t\t\tconst typedState = state as { transfers: Map<string, { data: TransferData | null }> };\n\t\t\t\treturn typedState.transfers.get(parentTransferId)?.data;\n\t\t\t}) as TransferData | undefined;\n\n\t\t\tif (relationName) {\n\t\t\t\tconst currentValue = (parentData as any)?.[relationName];\n\n\t\t\t\tif (Array.isArray(currentValue)) {\n\t\t\t\t\t// Collection relation (Table) — remove matching transfer from array\n\t\t\t\t\tconst newItems = currentValue.filter((item: TransferStored) => {\n\t\t\t\t\t\tconst itemId = item.__identifier ?? item.__signedIdentifier ?? (item as any).__tempId;\n\t\t\t\t\t\tconst targetId = transferId ?? (transfer as any)?.__tempId;\n\t\t\t\t\t\treturn itemId !== targetId;\n\t\t\t\t\t});\n\n\t\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t\t[relationName]: newItems,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// Single relation (Link) — set the field to null\n\t\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t\t[relationName]: null,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Fallback: remove from __items array\n\t\t\t\tconst currentItems = (parentData?.__items as TransferStored[] | undefined) ?? [];\n\t\t\t\tconst newItems = currentItems.filter((item) => {\n\t\t\t\t\tconst itemId = item.__identifier ?? item.__signedIdentifier ?? (item as any).__tempId;\n\t\t\t\t\tconst targetId = transferId ?? (transfer as any)?.__tempId;\n\t\t\t\t\treturn itemId !== targetId;\n\t\t\t\t});\n\n\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t__items: newItems,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Lazy mode: delete via REST API\n\t\tif (!transferId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type for row delete\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onRowDelete, api } = callbackContext;\n\n\t\t// Use legacy callback if provided\n\t\tif (onRowDelete) {\n\t\t\tawait onRowDelete(transferId, targetType);\n\t\t} else if (api) {\n\t\t\t// Use API if available - pass the ClassType directly\n\t\t\tawait api.delete(targetType, transfer!);\n\t\t} else {\n\t\t\t// No callback or API - nothing to do\n\t\t\treturn;\n\t\t}\n\n\t\t// Clear transfer from store\n\t\tcontext.data?.clearTransfer(transferId);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseRowDeleteActionHandler.actionType = \"RowDeleteActionDefinition\";\n\n/**\n * Get template for new transfer - hook factory.\n * Fetches default values for a new transfer via REST API.\n * Supports both legacy callback mode and API mode.\n *\n * Stores template data using pageTransferId from context (if available) or \"new\" as fallback.\n * This ensures the form bindings can find the data at the correct transfer ID.\n */\nexport const useGetTemplateActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type for get template\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onGetTemplate, api } = callbackContext;\n\n\t\tlet template: TransferStored;\n\n\t\t// Use legacy callback if provided\n\t\tif (onGetTemplate) {\n\t\t\ttemplate = await onGetTemplate(targetType);\n\t\t} else if (api) {\n\t\t\t// Use API if available - pass the ClassType directly\n\t\t\tconst response = await api.getTemplate(targetType);\n\t\t\ttemplate = response.data;\n\t\t} else {\n\t\t\tthrow new Error(\"API not available in context\");\n\t\t}\n\n\t\t// Store template using pageTransferId from context, fallback to \"new\"\n\t\t// This ensures form bindings can find the data at the correct transfer ID\n\t\tconst transferId = (context as { pageTransferId?: string }).pageTransferId ?? \"new\";\n\t\tcontext.data?.setTransferData(transferId, template);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseGetTemplateActionHandler.actionType = \"GetTemplateActionDefinition\";\n","import type { ClassType, RelationType } from \"@judo/model-api\";\nimport type { IJudoRestApi } from \"../../api/i-judo-rest-api\";\nimport type { TransferData, TransferStored } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext } from \"../../types\";\n\n// Interface for API context - will be provided via context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Interface for relation context - provides relation metadata\ninterface RelationContext {\n\townerTransfer?: TransferStored;\n\townerClassType?: ClassType;\n\trelation?: RelationType;\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonSet?: (ownerId: string, relationName: string, targetId: string) => Promise<void>;\n\tonUnset?: (transferId: string, relationName: string) => Promise<void>;\n\tonAdd?: (ownerId: string, relationName: string, targetIds: string[]) => Promise<void>;\n\tonRemove?: (ownerId: string, relationName: string, targetIds: string[]) => Promise<void>;\n\tonBulkRemove?: (ownerId: string, relationName: string, targetIds: string[]) => Promise<void>;\n\tonClear?: (transferId: string, relationName: string) => Promise<void>;\n\tonRefreshRelation?: (transferId: string, relationName: string) => Promise<void>;\n\tonFilterRelation?: (relationName: string) => void;\n}\n\n/**\n * Get RelationType from context.\n */\nfunction getRelation(relationContext: RelationContext, action: Action): RelationType | null {\n\tif (relationContext.relation) {\n\t\treturn relationContext.relation;\n\t}\n\t// Check if action has a relation in ownerDataElement\n\tconst ownerDataElement = action.ownerDataElement;\n\tif (ownerDataElement && ownerDataElement[\"@type\"] === \"RelationType\") {\n\t\treturn ownerDataElement as RelationType;\n\t}\n\treturn null;\n}\n\n/**\n * Handle relation set (single) - hook factory.\n * Sets a single-valued relation to a selected transfer.\n * Supports both legacy callback mode and API mode.\n */\nexport const useSetActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst relationContext = context as unknown as RelationContext & {\n\t\t\tselectedEntity?: TransferStored;\n\t\t} & ApiContext &\n\t\t\tLegacyCallbacks;\n\n\t\tconst { ownerTransfer, selectedEntity, api, onSet } = relationContext;\n\n\t\tif (!ownerTransfer || !selectedEntity) {\n\t\t\tthrow new Error(\"Missing owner or selected transfer for set\");\n\t\t}\n\n\t\tconst ownerId = ownerTransfer.__identifier ?? ownerTransfer.__signedIdentifier;\n\t\tconst selectedId = selectedEntity.__identifier ?? selectedEntity.__signedIdentifier;\n\n\t\tif (!ownerId || !selectedId) {\n\t\t\tthrow new Error(\"Missing transfer identifiers for set\");\n\t\t}\n\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onSet) {\n\t\t\tawait onSet(ownerId, relationName, selectedId);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(relationContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for set action\");\n\t\t\t}\n\t\t\tawait api.setRelation(relation, ownerTransfer, selectedEntity);\n\t\t}\n\n\t\tcontext.closeDialog?.({ type: \"selected\", data: selectedEntity });\n\t};\n}) as ActionHandlerHookWithMeta;\nuseSetActionHandler.actionType = \"SetActionDefinition\";\n\n/**\n * Handle relation unset - hook factory.\n * Clears a single-valued relation.\n * Supports both legacy callback mode and API mode.\n */\nexport const useUnsetActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = transfer?.__identifier ?? transfer?.__signedIdentifier;\n\t\tif (!transferId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext & RelationContext;\n\t\tconst { onUnset, api } = callbackContext;\n\n\t\t// Use legacy callback if provided\n\t\tif (onUnset) {\n\t\t\tawait onUnset(transferId, relationName);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(callbackContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for unset action\");\n\t\t\t}\n\t\t\tawait api.unsetRelation(relation, transfer!);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseUnsetActionHandler.actionType = \"UnsetActionDefinition\";\n\n/**\n * Handle relation add (multi) - hook factory.\n * Adds selected transfers to a collection relation.\n * Supports both legacy callback mode and API mode.\n */\nexport const useAddActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst addContext = context as unknown as RelationContext & {\n\t\t\tselectedEntities?: TransferStored[];\n\t\t} & ApiContext &\n\t\t\tLegacyCallbacks;\n\n\t\tconst { ownerTransfer, selectedEntities, api, onAdd } = addContext;\n\n\t\tif (!ownerTransfer || !selectedEntities?.length) {\n\t\t\tthrow new Error(\"Missing transfers for add\");\n\t\t}\n\n\t\tconst ownerId = ownerTransfer.__identifier ?? ownerTransfer.__signedIdentifier;\n\t\tif (!ownerId) {\n\t\t\tthrow new Error(\"Missing owner transfer identifier for add\");\n\t\t}\n\n\t\tconst selectedIds = selectedEntities.map((e) => e.__identifier ?? e.__signedIdentifier).filter(Boolean) as string[];\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onAdd) {\n\t\t\tawait onAdd(ownerId, relationName, selectedIds);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(addContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for add action\");\n\t\t\t}\n\t\t\tawait api.addToRelation(relation, ownerTransfer, selectedEntities);\n\t\t}\n\n\t\tcontext.closeDialog?.({ type: \"selected\", data: selectedEntities });\n\t};\n}) as ActionHandlerHookWithMeta;\nuseAddActionHandler.actionType = \"AddActionDefinition\";\n\n/**\n * Handle relation remove - hook factory.\n * Removes a single transfer from a collection relation.\n * Supports both legacy callback mode and API mode.\n */\nexport const useRemoveActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst removeContext = context as unknown as RelationContext & ApiContext & LegacyCallbacks;\n\t\tconst eagerContext = context as unknown as {\n\t\t\tisEager?: boolean;\n\t\t\tparentTransferId?: string;\n\t\t\trelationName?: string;\n\t\t};\n\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = transfer?.__identifier ?? transfer?.__signedIdentifier;\n\n\t\t// Eager mode: remove transfer from parent's local data store\n\t\tif (eagerContext.isEager && eagerContext.parentTransferId && context.data) {\n\t\t\tconst parentTransferId = eagerContext.parentTransferId;\n\t\t\tconst eagerRelationName = eagerContext.relationName;\n\n\t\t\tconst parentData = context.data.getSnapshot((state: unknown) => {\n\t\t\t\tconst typedState = state as { transfers: Map<string, { data: TransferData | null }> };\n\t\t\t\treturn typedState.transfers.get(parentTransferId)?.data;\n\t\t\t}) as TransferData | undefined;\n\n\t\t\tif (eagerRelationName) {\n\t\t\t\tconst currentItems = ((parentData as any)?.[eagerRelationName] as TransferStored[] | undefined) ?? [];\n\t\t\t\tconst newItems = currentItems.filter((item) => {\n\t\t\t\t\tconst itemId = item.__identifier ?? item.__signedIdentifier ?? (item as any).__tempId;\n\t\t\t\t\tconst targetId = transferId ?? (transfer as any)?.__tempId;\n\t\t\t\t\treturn itemId !== targetId;\n\t\t\t\t});\n\n\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t[eagerRelationName]: newItems,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst currentItems = (parentData?.__items as TransferStored[] | undefined) ?? [];\n\t\t\t\tconst newItems = currentItems.filter((item) => {\n\t\t\t\t\tconst itemId = item.__identifier ?? item.__signedIdentifier ?? (item as any).__tempId;\n\t\t\t\t\tconst targetId = transferId ?? (transfer as any)?.__tempId;\n\t\t\t\t\treturn itemId !== targetId;\n\t\t\t\t});\n\n\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t__items: newItems,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Lazy mode: remove via REST API\n\t\tconst { ownerTransfer, api, onRemove } = removeContext;\n\n\t\tconst ownerId = ownerTransfer?.__identifier ?? ownerTransfer?.__signedIdentifier;\n\n\t\tif (!ownerId || !transferId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onRemove) {\n\t\t\tawait onRemove(ownerId, relationName, [transferId]);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(removeContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for remove action\");\n\t\t\t}\n\t\t\tawait api.removeFromRelation(relation, ownerTransfer!, [transfer!]);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseRemoveActionHandler.actionType = \"RemoveActionDefinition\";\n\n/**\n * Handle bulk remove - hook factory.\n * Removes multiple selected transfers from a collection relation.\n * Supports both legacy callback mode and API mode.\n */\nexport const useBulkRemoveActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst removeContext = context as unknown as RelationContext & ApiContext & LegacyCallbacks;\n\t\tconst eagerContext = context as unknown as {\n\t\t\tisEager?: boolean;\n\t\t\tparentTransferId?: string;\n\t\t\trelationName?: string;\n\t\t};\n\n\t\tconst selectedRows = context.selectedRows as TransferStored[] | undefined;\n\n\t\tif (!selectedRows?.length) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Eager mode: remove transfers from parent's local data store\n\t\tif (eagerContext.isEager && eagerContext.parentTransferId && context.data) {\n\t\t\tconst parentTransferId = eagerContext.parentTransferId;\n\t\t\tconst eagerRelationName = eagerContext.relationName;\n\n\t\t\t// Collect IDs of transfers to remove (support both backend and frontend IDs)\n\t\t\tconst removeIds = new Set(\n\t\t\t\tselectedRows.map((e) => e.__identifier ?? e.__signedIdentifier ?? (e as any).__tempId).filter(Boolean)\n\t\t\t);\n\n\t\t\tconst parentData = context.data.getSnapshot((state: unknown) => {\n\t\t\t\tconst typedState = state as { transfers: Map<string, { data: TransferData | null }> };\n\t\t\t\treturn typedState.transfers.get(parentTransferId)?.data;\n\t\t\t}) as TransferData | undefined;\n\n\t\t\tif (eagerRelationName) {\n\t\t\t\tconst currentItems = ((parentData as any)?.[eagerRelationName] as TransferStored[] | undefined) ?? [];\n\t\t\t\tconst newItems = currentItems.filter((item) => {\n\t\t\t\t\tconst itemId = item.__identifier ?? item.__signedIdentifier ?? (item as any).__tempId;\n\t\t\t\t\treturn !removeIds.has(itemId);\n\t\t\t\t});\n\n\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t[eagerRelationName]: newItems,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst currentItems = (parentData?.__items as TransferStored[] | undefined) ?? [];\n\t\t\t\tconst newItems = currentItems.filter((item) => {\n\t\t\t\t\tconst itemId = item.__identifier ?? item.__signedIdentifier ?? (item as any).__tempId;\n\t\t\t\t\treturn !removeIds.has(itemId);\n\t\t\t\t});\n\n\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t__items: newItems,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Lazy mode: remove via REST API\n\t\tconst { ownerTransfer, api, onBulkRemove } = removeContext;\n\n\t\tconst ownerId = ownerTransfer?.__identifier ?? ownerTransfer?.__signedIdentifier;\n\n\t\tif (!ownerId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst selectedIds = selectedRows.map((e) => e.__identifier ?? e.__signedIdentifier).filter(Boolean) as string[];\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onBulkRemove) {\n\t\t\tawait onBulkRemove(ownerId, relationName, selectedIds);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(removeContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for bulk remove action\");\n\t\t\t}\n\t\t\tconst entitiesToRemove = selectedRows.filter((row) => row.__signedIdentifier);\n\t\t\tawait api.removeFromRelation(relation, ownerTransfer!, entitiesToRemove);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseBulkRemoveActionHandler.actionType = \"BulkRemoveActionDefinition\";\n\n/**\n * Handle relation clear - hook factory.\n * Clears all transfers from a collection relation (unset for collection).\n * Supports both legacy callback mode and API mode.\n */\nexport const useClearActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = transfer?.__identifier ?? transfer?.__signedIdentifier;\n\t\tif (!transferId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst callbackContext = context as unknown as ApiContext & RelationContext & LegacyCallbacks;\n\t\tconst { api, onClear } = callbackContext;\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onClear) {\n\t\t\tawait onClear(transferId, relationName);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(callbackContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for clear action\");\n\t\t\t}\n\t\t\t// Collection relations: set to empty array; single-valued: unset\n\t\t\tif (relation.isCollection !== false) {\n\t\t\t\tawait api.setRelation(relation, transfer!, []);\n\t\t\t} else {\n\t\t\t\tawait api.unsetRelation(relation, transfer!);\n\t\t\t}\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseClearActionHandler.actionType = \"ClearActionDefinition\";\n\n/**\n * Handle relation refresh - hook factory.\n * Refreshes/reloads a relation's data.\n * Supports both legacy callback mode and API mode.\n */\nexport const useRefreshRelationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = transfer?.__identifier ?? transfer?.__signedIdentifier;\n\t\tif (!transferId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst callbackContext = context as unknown as ApiContext & RelationContext & LegacyCallbacks;\n\t\tconst { api, onRefreshRelation } = callbackContext;\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onRefreshRelation) {\n\t\t\tawait onRefreshRelation(transferId, relationName);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(callbackContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for refresh action\");\n\t\t\t}\n\t\t\t// For collection relations, list; for single, get\n\t\t\tif (relation.isCollection !== false) {\n\t\t\t\tawait api.listRelation(relation, transfer!);\n\t\t\t} else {\n\t\t\t\tawait api.getRelation(relation, transfer!);\n\t\t\t}\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseRefreshRelationActionHandler.actionType = \"RefreshRelationActionDefinition\";\n\n/**\n * Handle relation filter - hook factory.\n * Applies a filter to a relation (UI-side operation, no REST call).\n */\nexport const useFilterRelationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Filter is a UI-side operation - signal the intent\n\t\tconst filterContext = context as unknown as LegacyCallbacks;\n\n\t\tif (filterContext.onFilterRelation) {\n\t\t\tfilterContext.onFilterRelation(action.actionDefinition.name ?? \"\");\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseFilterRelationActionHandler.actionType = \"FilterRelationActionDefinition\";\n","import type { ClassType, RelationType } from \"@judo/model-api\";\nimport type { IJudoRestApi } from \"../../api/i-judo-rest-api\";\nimport type { TransferStored } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext } from \"../../types\";\n\n// Interface for API context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Interface for relation context\ninterface RelationContext {\n\townerTransfer?: TransferStored;\n\townerClassType?: ClassType;\n\trelation?: RelationType;\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonFilterRequest?: () => void;\n\tonExport?: (classType: ClassType) => Promise<void>;\n\tonInlineCreateRow?: () => void;\n}\n\n/**\n * Get relation from context.\n */\nfunction getRelation(relationContext: RelationContext): RelationType | null {\n\treturn relationContext.relation ?? null;\n}\n\n/**\n * Handle filter action (opens filter dialog) - hook factory.\n * Filter is primarily a UI operation - signals filter intent.\n */\nexport const useFilterActionHandler = ((_action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Filter handling is typically done by Table component\n\t\t// This handler just signals filter intent\n\t\tconst filterContext = context as unknown as LegacyCallbacks;\n\t\tfilterContext.onFilterRequest?.();\n\t};\n}) as ActionHandlerHookWithMeta;\nuseFilterActionHandler.actionType = \"FilterActionDefinition\";\n\n/**\n * Handle export action - hook factory.\n * Exports relation data as a downloadable file via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useExportActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type for export\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as ApiContext & RelationContext & LegacyCallbacks;\n\t\tconst { onExport, api } = callbackContext;\n\n\t\t// Use legacy callback if provided\n\t\tif (onExport) {\n\t\t\tawait onExport(targetType);\n\t\t\treturn;\n\t\t}\n\n\t\t// Use API if available\n\t\tif (api) {\n\t\t\tconst relation = getRelation(callbackContext);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for export action\");\n\t\t\t}\n\n\t\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\t\tconst response = await api.exportRelation(relation, transfer);\n\t\t\tconst blob = response.data;\n\n\t\t\t// Download file\n\t\t\tconst url = URL.createObjectURL(blob);\n\t\t\tconst a = document.createElement(\"a\");\n\t\t\ta.href = url;\n\t\t\ta.download = `export_${targetType.simpleName ?? targetType.name}_${Date.now()}.csv`;\n\t\t\ta.click();\n\t\t\tURL.revokeObjectURL(url);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseExportActionHandler.actionType = \"ExportActionDefinition\";\n\n/**\n * Handle inline row creation in table - hook factory.\n * Inline creation is primarily a UI operation.\n */\nexport const useInlineCreateRowActionHandler = ((_action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Signal inline create intent (UI-side operation)\n\t\tconst inlineContext = context as unknown as LegacyCallbacks;\n\t\tinlineContext.onInlineCreateRow?.();\n\t};\n}) as ActionHandlerHookWithMeta;\nuseInlineCreateRowActionHandler.actionType = \"InlineCreateRowActionDefinition\";\n","import type {\n\tCallOperationActionDefinition as CallOpDef,\n\tClassType,\n\tOperationType,\n\tPageDefinition,\n} from \"@judo/model-api\";\nimport type { IJudoRestApi, OperationInfo } from \"../../api/i-judo-rest-api\";\nimport type { TransferStored, ValidationError } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext } from \"../../types\";\nimport { maybeInterceptError } from \"../../lifecycle/error-interceptor\";\n\n// Interface for API context - will be provided via context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Interface for page-level refresh callback provided by ViewContainerRenderer\ninterface RefreshPageContext {\n\trefreshPage?: () => void;\n}\n\n/**\n * Helper to check if an error is a ValidationError (400 response).\n */\nfunction isValidationError(error: unknown): error is ValidationError {\n\treturn error !== null && typeof error === \"object\" && (error as { name?: string }).name === \"ValidationError\";\n}\n\n/**\n * Helper to check if an error has a specific HTTP status code.\n */\nfunction hasStatus(error: unknown, ...statuses: number[]): boolean {\n\tif (error !== null && typeof error === \"object\") {\n\t\tconst status = (error as { status?: number }).status;\n\t\treturn status !== undefined && statuses.includes(status);\n\t}\n\treturn false;\n}\n\n/**\n * Handle operation errors with appropriate notifications.\n * - 400: Validation error toast + set field errors\n * - 401/403: Access denied toast\n * - Other 4xx/5xx: Generic error toast\n */\nfunction handleOperationError(error: unknown, operationName: string, context: TypedActionHandlerContext): void {\n\tconst { notifications, validation } = context;\n\t// Custom error handler interceptor takes priority over default handling.\n\tif (maybeInterceptError(error, context.errorHandlerInterceptor, { key: operationName })) {\n\t\treturn;\n\t}\n\tif (isValidationError(error)) {\n\t\t// 400 - Validation error\n\t\tconst fieldErrors = error.toFieldErrors();\n\t\tif (validation && Object.keys(fieldErrors).length > 0) {\n\t\t\tvalidation.setErrors(fieldErrors);\n\t\t}\n\t\tnotifications?.error(`Validation failed for ${operationName}`);\n\t} else if (hasStatus(error, 401, 403)) {\n\t\t// 401/403 - Access denied\n\t\tnotifications?.error(`Access denied: You don't have permission to execute ${operationName}`);\n\t} else if (hasStatus(error, 404)) {\n\t\t// 404 - Not found\n\t\tnotifications?.error(`Resource not found for ${operationName}`);\n\t} else {\n\t\t// Other errors (5xx, network, etc.)\n\t\tconst message = error instanceof Error ? error.message : \"Unknown error\";\n\t\tnotifications?.error(`Operation ${operationName} failed: ${message}`);\n\t}\n}\n\n/**\n * Open operation output page/dialog if action has a target page and operation returned data.\n * Uses `navigateTo` for full-page output or `openDialog` when the target page has `openInDialog=true`.\n */\nfunction openOperationOutputPage(\n\taction: Action,\n\tresult: TransferStored | undefined,\n\toperation: OperationType,\n\tcontext: TypedActionHandlerContext\n): void {\n\t// Check if operation returned data and action has a target page for the output\n\tconst targetPage = action.targetPageDefinition as PageDefinition | undefined;\n\tif (!result || !targetPage) {\n\t\treturn;\n\t}\n\n\t// Determine if output is mapped (has lifecycle) based on operation.output.behaviours\n\tconst outputParam = operation.output;\n\tconst behaviours = (outputParam as { behaviours?: string[] } | undefined)?.behaviours ?? [];\n\tconst isMappedOutput = behaviours.some((b) => [\"UPDATE\", \"DELETE\", \"REFRESH\"].includes(b));\n\n\tconst params = {\n\t\ttransfer: result,\n\t\tisOperationOutput: true,\n\t\tisMappedOutput,\n\t};\n\n\t// Check PageDefinition.openInDialog to decide between dialog and page navigation\n\tif (String(targetPage.openInDialog) === \"true\") {\n\t\tcontext.navigation?.openDialog(targetPage, params);\n\t} else {\n\t\tcontext.navigation?.navigateTo(targetPage, params);\n\t}\n}\n\n/**\n * Trigger a full page refresh after a successful operation.\n * Calls the refreshPage callback provided by ViewContainerRenderer\n * via additionalContext. This causes the transfer data AND all embedded\n * tables to re-fetch their data.\n */\nfunction triggerPageRefresh(context: TypedActionHandlerContext): void {\n\tconst { refreshPage } = context as unknown as RefreshPageContext;\n\trefreshPage?.();\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonCallOperation?: (\n\t\toperation: OperationType,\n\t\towner: TransferStored | undefined,\n\t\ttarget: TransferStored | undefined\n\t) => Promise<unknown>;\n\tonBulkCallOperation?: (operation: OperationType, transfers: TransferStored[]) => Promise<void>;\n\tonInputFormCallOperation?: (\n\t\toperation: OperationType,\n\t\ttransfer: TransferStored | undefined,\n\t\tinputData: TransferStored\n\t) => Promise<unknown>;\n\tonInputSelectorCallOperation?: (\n\t\toperation: OperationType,\n\t\ttransfer: TransferStored | undefined,\n\t\tselectedEntity: TransferStored\n\t) => Promise<unknown>;\n\tonParameterlessCallOperation?: (operation: OperationType, transfer: TransferStored | undefined) => Promise<unknown>;\n}\n\n/**\n * Convert OperationType to OperationInfo for the REST API.\n */\nfunction toOperationInfo(operation: OperationType): OperationInfo {\n\treturn {\n\t\tname: operation.name,\n\t\tisStatic: operation.operationType === \"STATIC\",\n\t\tisMapped: operation.operationType === \"MAPPED\",\n\t\thasInput: !!operation.input,\n\t\tinputType: operation.input?.target,\n\t};\n}\n\n/**\n * Handle operation calls - hook factory.\n * Calls a bound operation via REST API.\n * Supports both legacy callback mode and API mode.\n * Opens output dialog if operation returns data and action has targetPageDefinition.\n * Shows success toast on success, error toast on failure.\n */\nexport const useCallOperationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Cast actionDefinition to CallOperationActionDefinition to access operation\n\t\tconst opDef = action.actionDefinition as CallOpDef;\n\t\tconst operation = opDef.operation as OperationType | undefined;\n\t\tif (!operation) {\n\t\t\tthrow new Error(\"No operation defined for CallOperationAction\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onCallOperation, api } = callbackContext;\n\t\tconst { notifications } = context;\n\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\n\t\ttry {\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onCallOperation) {\n\t\t\t\tconst result = await onCallOperation(operation, transfer, transfer);\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, result as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\t// Get the owner ClassType - either from actionDefinition.targetType or operation's eContainer\n\t\t\t\tconst ownerType = (opDef.targetType ?? operation.eContainer) as ClassType | undefined;\n\t\t\t\tif (!ownerType) {\n\t\t\t\t\tthrow new Error(\"No owner type for operation call\");\n\t\t\t\t}\n\n\t\t\t\tconst operationInfo = toOperationInfo(operation);\n\n\t\t\t\t// Invoke the operation\n\t\t\t\tconst response = await api.invokeOperation(ownerType, operationInfo, transfer, transfer);\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, response.data as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleOperationError(error, operation.name, context);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseCallOperationActionHandler.actionType = \"CallOperationActionDefinition\";\n\n/**\n * Handle bulk operation calls - hook factory.\n * Calls an operation on multiple selected transfers.\n * Supports both legacy callback mode and API mode.\n * Shows success toast on success, error toast on failure.\n */\nexport const useBulkCallOperationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Cast actionDefinition to access operation\n\t\tconst opDef = action.actionDefinition as CallOpDef;\n\t\tconst operation = opDef.operation as OperationType | undefined;\n\t\tif (!operation) {\n\t\t\tthrow new Error(\"No operation defined for BulkCallOperationAction\");\n\t\t}\n\n\t\tconst selectedRows = context.selectedRows as TransferStored[] | undefined;\n\t\tif (!selectedRows || selectedRows.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onBulkCallOperation, api } = callbackContext;\n\t\tconst { notifications } = context;\n\n\t\ttry {\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onBulkCallOperation) {\n\t\t\t\tawait onBulkCallOperation(operation, selectedRows);\n\t\t\t\tnotifications?.success(`${operation.name} completed on ${selectedRows.length} item(s)`);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\t// Get the owner ClassType - either from actionDefinition.targetType or operation's eContainer\n\t\t\t\tconst ownerType = (opDef.targetType ?? operation.eContainer) as ClassType | undefined;\n\t\t\t\tif (!ownerType) {\n\t\t\t\t\tthrow new Error(\"No owner type for bulk operation call\");\n\t\t\t\t}\n\n\t\t\t\tconst operationInfo = toOperationInfo(operation);\n\n\t\t\t\t// Call operation on each selected transfer\n\t\t\t\tconst operationPromises = selectedRows.map((row) => api.invokeOperation(ownerType, operationInfo, row, row));\n\n\t\t\t\tawait Promise.all(operationPromises);\n\t\t\t\tnotifications?.success(`${operation.name} completed on ${selectedRows.length} item(s)`);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleOperationError(error, operation.name, context);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseBulkCallOperationActionHandler.actionType = \"BulkCallOperationActionDefinition\";\n\n/**\n * Handle operation with input form - hook factory.\n * Calls an operation with form data as input.\n * Supports both legacy callback mode and API mode.\n * Opens output dialog if operation returns data and action has targetPageDefinition.\n * Shows success toast on success, error toast on failure.\n * Only closes dialog on success.\n */\nexport const useInputFormCallOperationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Cast actionDefinition to access operation\n\t\tconst opDef = action.actionDefinition as CallOpDef;\n\t\tconst operation = opDef.operation as OperationType | undefined;\n\t\tif (!operation) {\n\t\t\tthrow new Error(\"No operation defined for InputFormCallOperationAction\");\n\t\t}\n\n\t\tconst inputFormContext = context as unknown as {\n\t\t\tinputData?: TransferStored;\n\t\t\tpageTransferId?: string;\n\t\t} & LegacyCallbacks &\n\t\t\tApiContext;\n\n\t\tconst { onInputFormCallOperation, api, pageTransferId } = inputFormContext;\n\t\tconst { notifications } = context;\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\n\t\t// Get input data from context or from data store using pageTransferId\n\t\t// For input forms, the form data is stored in data store by the form components\n\t\tlet inputData = inputFormContext.inputData;\n\t\tif (!inputData && context.data && pageTransferId) {\n\t\t\tinputData = context.data.getSnapshot((state: unknown) => {\n\t\t\t\tconst typedState = state as { transfers: Map<string, { data: TransferStored | null }> };\n\t\t\t\treturn typedState.transfers.get(pageTransferId)?.data;\n\t\t\t}) as TransferStored | undefined;\n\t\t}\n\n\t\tif (!inputData) {\n\t\t\t// No input data - cannot proceed\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onInputFormCallOperation) {\n\t\t\t\tconst result = await onInputFormCallOperation(operation, transfer, inputData);\n\t\t\t\t// Success: close input dialog first, then show toast and open output page\n\t\t\t\tcontext.closeDialog?.({ type: \"submitted\" });\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, result as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\t// Get the owner ClassType - either from actionDefinition.targetType or operation's eContainer\n\t\t\t\tconst ownerType = (opDef.targetType ?? operation.eContainer) as ClassType | undefined;\n\t\t\t\tif (!ownerType) {\n\t\t\t\t\tthrow new Error(\"No owner type for input form operation call\");\n\t\t\t\t}\n\n\t\t\t\tconst operationInfo = toOperationInfo(operation);\n\n\t\t\t\t// Invoke operation with form input\n\t\t\t\tconst response = await api.invokeOperation(ownerType, operationInfo, transfer, inputData);\n\n\t\t\t\t// Success: close input dialog first, then show toast and open output page\n\t\t\t\tcontext.closeDialog?.({ type: \"submitted\" });\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, response.data as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Error: do NOT close dialog, show error toast\n\t\t\thandleOperationError(error, operation.name, context);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseInputFormCallOperationActionHandler.actionType = \"InputFormCallOperationActionDefinition\";\n\n/**\n * Handle operation with input selector - hook factory.\n * Calls an operation with selected transfer as input.\n * Supports both legacy callback mode and API mode.\n * Opens output dialog if operation returns data and action has targetPageDefinition.\n * Shows success toast on success, error toast on failure.\n * Only closes dialog on success.\n */\nexport const useInputSelectorCallOperationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Cast actionDefinition to access operation\n\t\tconst opDef = action.actionDefinition as CallOpDef;\n\t\tconst operation = opDef.operation as OperationType | undefined;\n\t\tif (!operation) {\n\t\t\tthrow new Error(\"No operation defined for InputSelectorCallOperationAction\");\n\t\t}\n\n\t\tconst selectorContext = context as unknown as {\n\t\t\tselectedEntity?: TransferStored;\n\t\t\townerTransfer?: TransferStored;\n\t\t} & LegacyCallbacks &\n\t\t\tApiContext;\n\n\t\tconst { onInputSelectorCallOperation, api, selectedEntity, ownerTransfer } = selectorContext;\n\t\tconst { notifications } = context;\n\t\t// In selector dialogs, context.transfer is undefined because the dialog was\n\t\t// opened without a transfer param. The ownerTransfer (the entity that owns\n\t\t// the operation) is injected by pageActionDispatch from the selection context.\n\t\t// Use ownerTransfer as the API owner so X-Judo-SignedIdentifier is sent.\n\t\tconst transfer = (context.transfer ?? ownerTransfer) as TransferStored | undefined;\n\n\t\tif (!selectedEntity) {\n\t\t\t// No selected transfer - cannot proceed\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onInputSelectorCallOperation) {\n\t\t\t\tconst result = await onInputSelectorCallOperation(operation, transfer, selectedEntity);\n\t\t\t\t// Success: close selector dialog first, then show toast and open output page\n\t\t\t\tcontext.closeDialog?.({ type: \"submitted\" });\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, result as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\t// Get the owner ClassType - either from actionDefinition.targetType or operation's eContainer\n\t\t\t\tconst ownerType = (opDef.targetType ?? operation.eContainer) as ClassType | undefined;\n\t\t\t\tif (!ownerType) {\n\t\t\t\t\tthrow new Error(\"No owner type for input selector operation call\");\n\t\t\t\t}\n\n\t\t\t\tconst operationInfo = toOperationInfo(operation);\n\n\t\t\t\t// Invoke operation with selected transfer as input\n\t\t\t\tconst response = await api.invokeOperation(ownerType, operationInfo, transfer, selectedEntity);\n\n\t\t\t\t// Success: close selector dialog first, then show toast and open output page\n\t\t\t\tcontext.closeDialog?.({ type: \"submitted\" });\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, response.data as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Error: do NOT close dialog, show error toast\n\t\t\thandleOperationError(error, operation.name, context);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseInputSelectorCallOperationActionHandler.actionType = \"InputSelectorCallOperationActionDefinition\";\n\n/**\n * Handle parameterless operation calls - hook factory.\n * Calls an operation with no input.\n * Supports both legacy callback mode and API mode.\n * Opens output dialog if operation returns data and action has targetPageDefinition.\n * Shows success toast on success, error toast on failure.\n */\nexport const useParameterlessCallOperationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Cast actionDefinition to access operation\n\t\tconst opDef = action.actionDefinition as CallOpDef;\n\t\tconst operation = opDef.operation as OperationType | undefined;\n\t\tif (!operation) {\n\t\t\tthrow new Error(\"No operation defined for ParameterlessCallOperationAction\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onParameterlessCallOperation, api } = callbackContext;\n\t\tconst { notifications } = context;\n\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\n\t\ttry {\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onParameterlessCallOperation) {\n\t\t\t\tconst result = await onParameterlessCallOperation(operation, transfer);\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, result as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\t// Get the owner ClassType - either from actionDefinition.targetType or operation's eContainer\n\t\t\t\tconst ownerType = (opDef.targetType ?? operation.eContainer) as ClassType | undefined;\n\t\t\t\tif (!ownerType) {\n\t\t\t\t\tthrow new Error(\"No owner type for parameterless operation call\");\n\t\t\t\t}\n\n\t\t\t\tconst operationInfo = toOperationInfo(operation);\n\n\t\t\t\t// Invoke operation without input parameters\n\t\t\t\tconst response = await api.invokeOperation(ownerType, operationInfo, transfer, undefined);\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, response.data as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleOperationError(error, operation.name, context);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseParameterlessCallOperationActionHandler.actionType = \"ParameterlessCallOperationActionDefinition\";\n","import type { ClassType, RelationType } from \"@judo/model-api\";\nimport type { IJudoRestApi } from \"../../api/i-judo-rest-api\";\nimport type { TransferStored } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext } from \"../../types\";\n\n// Interface for API context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Interface for relation context\ninterface RelationContext {\n\townerTransfer?: TransferStored;\n\townerClassType?: ClassType;\n\trelation?: RelationType;\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonAutocompleteRange?: (classType: ClassType, searchText: string) => Promise<TransferStored[]>;\n\tonAutocompleteSet?: (ownerId: string, relationName: string, selectedId: string) => Promise<void>;\n\tonAutocompleteAdd?: (ownerId: string, relationName: string, selectedIds: string[]) => Promise<void>;\n}\n\n/**\n * Get RelationType from context.\n */\nfunction getRelation(relationContext: RelationContext, action: Action): RelationType | null {\n\tif (relationContext.relation) {\n\t\treturn relationContext.relation;\n\t}\n\t// Check if action has a relation in ownerDataElement\n\tconst ownerDataElement = action.ownerDataElement;\n\tif (ownerDataElement && ownerDataElement[\"@type\"] === \"RelationType\") {\n\t\treturn ownerDataElement as RelationType;\n\t}\n\treturn null;\n}\n\n/**\n * Handle autocomplete range query - hook factory.\n * Fetches range data for autocomplete via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useAutocompleteRangeActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type for autocomplete range\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as ApiContext &\n\t\t\tRelationContext &\n\t\t\tLegacyCallbacks & {\n\t\t\t\tsearchText?: string;\n\t\t\t\tonRangeResult?: (results: TransferStored[]) => void;\n\t\t\t};\n\n\t\tconst { onAutocompleteRange, api, onRangeResult } = callbackContext;\n\t\tconst searchText = callbackContext.searchText ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onAutocompleteRange) {\n\t\t\tconst results = await onAutocompleteRange(targetType, searchText);\n\t\t\tonRangeResult?.(results);\n\t\t\treturn;\n\t\t}\n\n\t\t// Use API if available\n\t\tif (api) {\n\t\t\tconst relation = getRelation(callbackContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for autocomplete range\");\n\t\t\t}\n\n\t\t\t// Build query customizer for search\n\t\t\tconst queryCustomizer = searchText\n\t\t\t\t? {\n\t\t\t\t\t\t_filter: { contains: searchText },\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\n\t\t\tconst response = await api.getRelationRange(relation, callbackContext.ownerTransfer, queryCustomizer);\n\n\t\t\t// Signal results to UI\n\t\t\tonRangeResult?.(response.data);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseAutocompleteRangeActionHandler.actionType = \"AutocompleteRangeActionDefinition\";\n\n/**\n * Handle autocomplete set action - hook factory.\n * Sets a single-valued relation via autocomplete selection.\n * Supports both legacy callback mode and API mode.\n */\nexport const useAutocompleteSetActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst autocompleteContext = context as unknown as RelationContext & {\n\t\t\tselectedEntity?: TransferStored;\n\t\t} & ApiContext &\n\t\t\tLegacyCallbacks;\n\n\t\tconst { ownerTransfer, selectedEntity, api, onAutocompleteSet } = autocompleteContext;\n\n\t\tconst ownerId = ownerTransfer?.__identifier ?? ownerTransfer?.__signedIdentifier;\n\t\tconst selectedId = selectedEntity?.__identifier ?? selectedEntity?.__signedIdentifier;\n\n\t\tif (!ownerId || !selectedId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onAutocompleteSet) {\n\t\t\tawait onAutocompleteSet(ownerId, relationName, selectedId);\n\t\t\treturn;\n\t\t}\n\n\t\t// Use API if available\n\t\tif (api) {\n\t\t\tconst relation = getRelation(autocompleteContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for autocomplete set\");\n\t\t\t}\n\n\t\t\tawait api.setRelation(relation, ownerTransfer!, selectedEntity!);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseAutocompleteSetActionHandler.actionType = \"AutocompleteSetActionDefinition\";\n\n/**\n * Handle autocomplete add action - hook factory.\n * Adds selected transfers to a collection relation via autocomplete.\n * Supports both legacy callback mode and API mode.\n */\nexport const useAutocompleteAddActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst autocompleteContext = context as unknown as RelationContext & {\n\t\t\tselectedEntities?: TransferStored[];\n\t\t} & ApiContext &\n\t\t\tLegacyCallbacks;\n\n\t\tconst { ownerTransfer, selectedEntities, api, onAutocompleteAdd } = autocompleteContext;\n\n\t\tconst ownerId = ownerTransfer?.__identifier ?? ownerTransfer?.__signedIdentifier;\n\n\t\tif (!ownerId || !selectedEntities?.length) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst selectedIds = selectedEntities.map((e) => e.__identifier ?? e.__signedIdentifier).filter(Boolean) as string[];\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onAutocompleteAdd) {\n\t\t\tawait onAutocompleteAdd(ownerId, relationName, selectedIds);\n\t\t\treturn;\n\t\t}\n\n\t\t// Use API if available\n\t\tif (api) {\n\t\t\tconst relation = getRelation(autocompleteContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for autocomplete add\");\n\t\t\t}\n\n\t\t\tconst entitiesToAdd = selectedEntities.filter((e) => e.__signedIdentifier);\n\t\t\tawait api.addToRelation(relation, ownerTransfer!, entitiesToAdd);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseAutocompleteAddActionHandler.actionType = \"AutocompleteAddActionDefinition\";\n","import type { Action, ActionHandlerHookWithMeta, TransferData, TypedActionHandlerContext } from \"../../types\";\n\n/**\n * Handle pre-fetch action (load data before navigation) - hook factory.\n */\nexport const usePreFetchActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst classType = action.actionDefinition.targetType;\n\t\tif (!classType) {\n\t\t\tthrow new Error(\"No target type for pre-fetch\");\n\t\t}\n\n\t\tconst preFetchContext = context as unknown as {\n\t\t\tonPreFetch?: (classType: unknown, transferId: string | undefined) => Promise<TransferData>;\n\t\t};\n\n\t\tif (preFetchContext.onPreFetch) {\n\t\t\tconst data = await preFetchContext.onPreFetch(classType, context.transfer?.__identifier);\n\t\t\tif (data.__identifier) {\n\t\t\t\tcontext.data!.setTransferData(data.__identifier, data);\n\t\t\t}\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nusePreFetchActionHandler.actionType = \"PreFetchActionDefinition\";\n\n/**\n * Handle custom action (user-defined logic) - hook factory.\n */\nexport const useCustomActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst customContext = context as unknown as {\n\t\t\tonCustomAction?: (action: Action, context: TypedActionHandlerContext) => Promise<void>;\n\t\t};\n\n\t\tif (customContext.onCustomAction) {\n\t\t\tawait customContext.onCustomAction(action, context);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseCustomActionHandler.actionType = \"CustomActionDefinition\";\n","import { type ReactNode, createContext, useContext } from \"react\";\nimport type { IJudoRestApi } from \"../api/i-judo-rest-api\";\n\n/**\n * API context type.\n */\nexport interface ApiContextType {\n\t/** JUDO REST API client */\n\tapi: IJudoRestApi;\n}\n\nconst ApiContext = createContext<ApiContextType | null>(null);\n\n/**\n * Hook to access the JUDO REST API client.\n *\n * @returns IJudoRestApi\n * @throws Error if used outside ApiProvider\n */\nexport function useApi(): IJudoRestApi {\n\tconst context = useContext(ApiContext);\n\tif (!context) {\n\t\tthrow new Error(\"useApi must be used within ApiProvider\");\n\t}\n\treturn context.api;\n}\n\n/**\n * Props for ApiProvider.\n */\nexport interface ApiProviderProps {\n\tchildren: ReactNode;\n\t/** JUDO REST API client instance */\n\tapi: IJudoRestApi;\n}\n\n/**\n * Provider for JUDO REST API client.\n * Makes the API client available to action handlers via the useApi hook.\n */\nexport function ApiProvider({ children, api }: ApiProviderProps) {\n\tconst value: ApiContextType = { api };\n\treturn <ApiContext.Provider value={value}>{children}</ApiContext.Provider>;\n}\n","/**\n * Action lifecycle execution engine.\n *\n * Composes lifecycle overrides with built-in action handlers.\n * The lifecycle wraps the default handler with before/after/onError hooks\n * and allows full replacement of the execute phase.\n */\n\nimport type { ActionLifecycle, ActionLifecycleContext } from \"@judo/model-api\";\nimport type { ActionHandlerContext, ActionHandlerFn } from \"@judo/model-api\";\nimport type { Action } from \"../types\";\n\n/**\n * Execute an action with lifecycle overrides composed around a default handler.\n *\n * Lifecycle execution order:\n * 1. override.before() → return false to cancel\n * 2. override.execute() ?? defaultHandler() → core execution\n * 3. override.after() → post-processing\n * 4. override.onError() → error handling (return true to suppress)\n *\n * @param defaultHandler - The built-in action handler function\n * @param overrides - Partial lifecycle overrides from the developer\n * @param baseContext - The base action handler context\n * @param action - The Action model object\n * @param page - The PageDefinition\n * @returns Promise resolving to the action result\n */\nexport async function executeWithLifecycle(\n\tdefaultHandler: ActionHandlerFn,\n\toverrides: Partial<ActionLifecycle>,\n\tbaseContext: ActionHandlerContext,\n\taction: Action\n): Promise<unknown> {\n\t// Build lifecycle context with callDefault\n\tconst callDefault = () => defaultHandler(baseContext);\n\n\tconst lifecycleContext: ActionLifecycleContext = {\n\t\t...(baseContext as unknown as Record<string, unknown>),\n\t\taction,\n\t\tactionDefinition: action.actionDefinition,\n\t\tpage: (baseContext as unknown as Record<string, unknown>).page as ActionLifecycleContext[\"page\"],\n\t\tcallDefault,\n\t};\n\n\t// BEFORE phase\n\tif (overrides.before) {\n\t\tconst proceed = await overrides.before(lifecycleContext);\n\t\tif (proceed === false) return undefined; // cancelled\n\t}\n\n\ttry {\n\t\t// EXECUTE phase\n\t\tlet result: unknown;\n\t\tif (overrides.execute) {\n\t\t\t// Developer provided custom execution\n\t\t\t// callDefault is available on context for wrapping\n\t\t\tresult = await overrides.execute(lifecycleContext);\n\t\t} else {\n\t\t\t// Use built-in handler\n\t\t\tresult = await defaultHandler(baseContext);\n\t\t}\n\n\t\t// AFTER phase\n\t\tif (overrides.after) {\n\t\t\tawait overrides.after(lifecycleContext, result);\n\t\t}\n\n\t\treturn result;\n\t} catch (error) {\n\t\t// ERROR phase\n\t\tif (overrides.onError) {\n\t\t\tconst suppressed = await overrides.onError(lifecycleContext, error);\n\t\t\tif (suppressed === true) return undefined; // error handled by override\n\t\t}\n\t\tthrow error; // re-throw for default error handling\n\t}\n}\n","import type { Action, ActionHandlerHook } from \"../types\";\n\n// Import all built-in handlers\nimport {\n\tuseBackActionHandler,\n\tuseCancelActionHandler,\n\tuseOpenPageActionHandler,\n\tuseRowOpenPageActionHandler,\n} from \"../handlers/navigation\";\n\nimport {\n\tuseOpenCreateFormActionHandler,\n\tuseOpenFormActionHandler,\n\tuseOpenOperationInputFormActionHandler,\n} from \"../handlers/form\";\n\nimport {\n\tuseOpenAddSelectorActionHandler,\n\tuseOpenOperationInputSelectorActionHandler,\n\tuseOpenSelectorActionHandler,\n\tuseOpenSetSelectorActionHandler,\n\tuseSelectorRangeActionHandler,\n} from \"../handlers/selector\";\n\nimport {\n\tuseBulkDeleteActionHandler,\n\tuseCreateActionHandler,\n\tuseDeleteActionHandler,\n\tuseGetTemplateActionHandler,\n\tuseRefreshActionHandler,\n\tuseRowDeleteActionHandler,\n\tuseUpdateActionHandler,\n} from \"../handlers/crud\";\n\nimport {\n\tuseAddActionHandler,\n\tuseBulkRemoveActionHandler,\n\tuseClearActionHandler,\n\tuseFilterRelationActionHandler,\n\tuseRefreshRelationActionHandler,\n\tuseRemoveActionHandler,\n\tuseSetActionHandler,\n\tuseUnsetActionHandler,\n} from \"../handlers/relation\";\n\nimport { useExportActionHandler, useFilterActionHandler, useInlineCreateRowActionHandler } from \"../handlers/table\";\n\nimport {\n\tuseBulkCallOperationActionHandler,\n\tuseCallOperationActionHandler,\n\tuseInputFormCallOperationActionHandler,\n\tuseInputSelectorCallOperationActionHandler,\n\tuseParameterlessCallOperationActionHandler,\n} from \"../handlers/operation\";\n\nimport {\n\tuseAutocompleteAddActionHandler,\n\tuseAutocompleteRangeActionHandler,\n\tuseAutocompleteSetActionHandler,\n} from \"../handlers/autocomplete\";\n\nimport { useCustomActionHandler, usePreFetchActionHandler } from \"../handlers/other\";\n\n/**\n * Registry of all built-in action handlers.\n * Maps action type to handler hook.\n * Built-in handlers use TypedActionHandlerContext, cast to base type for compatibility.\n */\nconst BUILTIN_HANDLERS = new Map<string, ActionHandlerHook>([\n\t// Navigation (4)\n\t[\"BackActionDefinition\", useBackActionHandler as ActionHandlerHook],\n\t[\"OpenPageActionDefinition\", useOpenPageActionHandler as ActionHandlerHook],\n\t[\"RowOpenPageActionDefinition\", useRowOpenPageActionHandler as ActionHandlerHook],\n\t[\"CancelActionDefinition\", useCancelActionHandler as ActionHandlerHook],\n\n\t// Form (3)\n\t[\"OpenFormActionDefinition\", useOpenFormActionHandler as ActionHandlerHook],\n\t[\"OpenCreateFormActionDefinition\", useOpenCreateFormActionHandler as ActionHandlerHook],\n\t[\"OpenOperationInputFormActionDefinition\", useOpenOperationInputFormActionHandler as ActionHandlerHook],\n\n\t// Selector (5)\n\t[\"OpenSelectorActionDefinition\", useOpenSelectorActionHandler as ActionHandlerHook],\n\t[\"OpenAddSelectorActionDefinition\", useOpenAddSelectorActionHandler as ActionHandlerHook],\n\t[\"OpenSetSelectorActionDefinition\", useOpenSetSelectorActionHandler as ActionHandlerHook],\n\t[\"OpenOperationInputSelectorActionDefinition\", useOpenOperationInputSelectorActionHandler as ActionHandlerHook],\n\t[\"SelectorRangeActionDefinition\", useSelectorRangeActionHandler as ActionHandlerHook],\n\n\t// CRUD (7)\n\t[\"RefreshActionDefinition\", useRefreshActionHandler as ActionHandlerHook],\n\t[\"CreateActionDefinition\", useCreateActionHandler as ActionHandlerHook],\n\t[\"UpdateActionDefinition\", useUpdateActionHandler as ActionHandlerHook],\n\t[\"DeleteActionDefinition\", useDeleteActionHandler as ActionHandlerHook],\n\t[\"BulkDeleteActionDefinition\", useBulkDeleteActionHandler as ActionHandlerHook],\n\t[\"RowDeleteActionDefinition\", useRowDeleteActionHandler as ActionHandlerHook],\n\t[\"GetTemplateActionDefinition\", useGetTemplateActionHandler as ActionHandlerHook],\n\n\t// Relation (8)\n\t[\"SetActionDefinition\", useSetActionHandler as ActionHandlerHook],\n\t[\"UnsetActionDefinition\", useUnsetActionHandler as ActionHandlerHook],\n\t[\"AddActionDefinition\", useAddActionHandler as ActionHandlerHook],\n\t[\"RemoveActionDefinition\", useRemoveActionHandler as ActionHandlerHook],\n\t[\"BulkRemoveActionDefinition\", useBulkRemoveActionHandler as ActionHandlerHook],\n\t[\"ClearActionDefinition\", useClearActionHandler as ActionHandlerHook],\n\t[\"RefreshRelationActionDefinition\", useRefreshRelationActionHandler as ActionHandlerHook],\n\t[\"FilterRelationActionDefinition\", useFilterRelationActionHandler as ActionHandlerHook],\n\n\t// Table (3)\n\t[\"FilterActionDefinition\", useFilterActionHandler as ActionHandlerHook],\n\t[\"ExportActionDefinition\", useExportActionHandler as ActionHandlerHook],\n\t[\"InlineCreateRowActionDefinition\", useInlineCreateRowActionHandler as ActionHandlerHook],\n\n\t// Operation (5)\n\t[\"BulkCallOperationActionDefinition\", useBulkCallOperationActionHandler as ActionHandlerHook],\n\t[\"CallOperationActionDefinition\", useCallOperationActionHandler as ActionHandlerHook],\n\t[\"InputFormCallOperationActionDefinition\", useInputFormCallOperationActionHandler as ActionHandlerHook],\n\t[\"InputSelectorCallOperationActionDefinition\", useInputSelectorCallOperationActionHandler as ActionHandlerHook],\n\t[\"ParameterlessCallOperationActionDefinition\", useParameterlessCallOperationActionHandler as ActionHandlerHook],\n\n\t// Autocomplete (3)\n\t[\"AutocompleteAddActionDefinition\", useAutocompleteAddActionHandler as ActionHandlerHook],\n\t[\"AutocompleteRangeActionDefinition\", useAutocompleteRangeActionHandler as ActionHandlerHook],\n\t[\"AutocompleteSetActionDefinition\", useAutocompleteSetActionHandler as ActionHandlerHook],\n\n\t// Other (2)\n\t[\"PreFetchActionDefinition\", usePreFetchActionHandler as ActionHandlerHook],\n\t[\"CustomActionDefinition\", useCustomActionHandler as ActionHandlerHook],\n]);\n\n/**\n * Get the handler for an action.\n * Returns the handler hook if found, undefined otherwise.\n */\nexport function getActionHandler(action: Action): ActionHandlerHook | undefined {\n\tconst actionType = action.actionDefinition[\"@type\"];\n\treturn BUILTIN_HANDLERS.get(actionType);\n}\n\n/**\n * Check if a handler exists for the given action.\n */\nexport function hasActionHandler(action: Action): boolean {\n\treturn getActionHandler(action) !== undefined;\n}\n","import type { ActionHandlerContext } from \"@judo/model-api\";\nimport type { ActionLifecycle } from \"@judo/model-api\";\nimport { useCallback, useMemo } from \"react\";\nimport type { IJudoRestApi } from \"../api/i-judo-rest-api\";\nimport { executeWithLifecycle } from \"../lifecycle/execute-with-lifecycle\";\nimport { hasActionHandler as checkHandler, getActionHandler } from \"../registry/action-handler-registry\";\nimport type { Action, DataStore, TransferData, ModelRegistry, NavigationContext, NotificationService } from \"../types\";\n\n/**\n * Options for useActionDispatcher hook.\n */\nexport interface UseActionDispatcherOptions {\n\t/** Navigation context */\n\tnavigation: NavigationContext;\n\t/** Data store */\n\tdata: DataStore;\n\t/** Model registry */\n\tregistry: ModelRegistry;\n\t/** JUDO REST API client (optional - enables API-mode handlers) */\n\tapi?: IJudoRestApi | null;\n\t/** Current transfer data */\n\ttransfer?: TransferData;\n\t/** Selected rows for bulk operations */\n\tselectedRows?: TransferData[];\n\t/** Dialog closer for form actions */\n\tcloseDialog?: () => void;\n\t/** Notification service for showing toasts */\n\tnotifications?: NotificationService;\n\t/** Additional context properties */\n\tadditionalContext?: Record<string, unknown>;\n\t/**\n\t * Resolved action lifecycle overrides for the current page.\n\t * Key: action sourceId, Value: lifecycle overrides.\n\t * Typically provided by PageActionOverridesProvider via useResolvedPageActionOverrides().\n\t */\n\tactionOverrides?: Record<string, Partial<ActionLifecycle>> | null;\n}\n\n/**\n * Result of useActionDispatcher hook.\n */\nexport interface UseActionDispatcherResult {\n\t/** Dispatch an action, optionally with context overrides */\n\tdispatch: (action: Action, contextOverrides?: Record<string, unknown>) => Promise<void>;\n\t/** Check if an action can be handled */\n\tcanHandle: (action: Action) => boolean;\n}\n\n/**\n * Hook for dispatching actions to registered handlers.\n * Uses hook factory pattern - handlers are resolved and called as hooks.\n *\n * @example\n * ```tsx\n * const { dispatch } = useActionDispatcher({\n * navigation,\n * data,\n * registry,\n * transfer: currentTransfer,\n * });\n *\n * const handleClick = async () => {\n * await dispatch(saveAction);\n * };\n * ```\n */\nexport function useActionDispatcher(options: UseActionDispatcherOptions): UseActionDispatcherResult {\n\tconst {\n\t\tnavigation,\n\t\tdata,\n\t\tregistry,\n\t\tapi,\n\t\ttransfer,\n\t\tselectedRows,\n\t\tcloseDialog,\n\t\tnotifications,\n\t\tadditionalContext,\n\t\tactionOverrides,\n\t} = options;\n\n\tconst context: ActionHandlerContext = useMemo(\n\t\t() =>\n\t\t\t({\n\t\t\t\tnavigation,\n\t\t\t\tdata,\n\t\t\t\tregistry,\n\t\t\t\tapi,\n\t\t\t\ttransfer,\n\t\t\t\tselectedRows,\n\t\t\t\tcloseDialog,\n\t\t\t\tnotifications,\n\t\t\t\t...additionalContext,\n\t\t\t}) as unknown as ActionHandlerContext,\n\t\t[navigation, data, registry, api, transfer, selectedRows, closeDialog, notifications, additionalContext]\n\t);\n\n\tconst canHandle = useCallback((action: Action): boolean => {\n\t\treturn checkHandler(action);\n\t}, []);\n\n\tconst dispatch = useCallback(\n\t\tasync (action: Action, contextOverrides?: Record<string, unknown>): Promise<void> => {\n\t\t\tconst handlerHook = getActionHandler(action);\n\n\t\t\tif (!handlerHook) {\n\t\t\t\tconst actionType = action.actionDefinition[\"@type\"];\n\t\t\t\tthrow new Error(`No handler for action type: ${actionType}`);\n\t\t\t}\n\n\t\t\t// Call the hook to get the handler function\n\t\t\tconst handlerFn = handlerHook(action);\n\n\t\t\t// Merge context with overrides\n\t\t\tconst mergedContext = contextOverrides ? ({ ...context, ...contextOverrides } as ActionHandlerContext) : context;\n\n\t\t\t// Check for lifecycle overrides\n\t\t\tconst actionSourceId = action[\"xmi:id\"];\n\t\t\tconst lifecycle = actionSourceId ? actionOverrides?.[actionSourceId] : undefined;\n\n\t\t\tif (lifecycle && Object.keys(lifecycle).length > 0) {\n\t\t\t\t// Execute with lifecycle composition\n\t\t\t\tawait executeWithLifecycle(handlerFn, lifecycle, mergedContext, action);\n\t\t\t} else {\n\t\t\t\t// No overrides — run default handler directly\n\t\t\t\tawait handlerFn(mergedContext);\n\t\t\t}\n\t\t},\n\t\t[context, actionOverrides]\n\t);\n\n\treturn { dispatch, canHandle };\n}\n","import type { Action, ActionHandlerFn } from \"@judo/model-api\";\nimport { useMemo } from \"react\";\nimport { hasActionHandler as checkHandler, getActionHandler } from \"../registry/action-handler-registry\";\n\n/**\n * Hook to get the handler for an action.\n *\n * @param action - The Action to get handler for\n * @returns Handler function to execute the action\n *\n * @example\n * ```tsx\n * function ActionButton({ action }: { action: Action }) {\n * const handler = useActionHandler(action);\n *\n * const handleClick = async () => {\n * await handler({ transfer: currentTransfer });\n * };\n *\n * return <Button onClick={handleClick}>{action.label}</Button>;\n * }\n * ```\n */\nexport function useActionHandler(action: Action): ActionHandlerFn {\n\tconst handler = useMemo(() => {\n\t\tconst handlerHook = getActionHandler(action);\n\n\t\tif (!handlerHook) {\n\t\t\tconst actionType = action.actionDefinition[\"@type\"];\n\t\t\tthrow new Error(`No handler for action type: ${actionType}`);\n\t\t}\n\n\t\t// Call the hook with the action to get the handler function\n\t\treturn handlerHook(action);\n\t}, [action]);\n\n\treturn handler;\n}\n\n/**\n * Check if a handler exists for the given action.\n *\n * @param action - The Action to check\n * @returns True if a handler exists\n */\nexport function hasActionHandler(action: Action): boolean {\n\treturn checkHandler(action);\n}\n","/**\n * Path building utilities for JUDO REST API.\n * Based on REST_REQUEST_MAPPING_SPECIFICATION.md\n */\n\nimport type { ClassType, RelationType } from \"@judo/model-api\";\nimport type { Application } from \"../types\";\n\nconst SPLITTER = \"::\";\nconst TRANSFER_SKIP_SEGMENT = \"_default_transferobjecttypes\";\n\n/**\n * Builds a REST path for a class type with optional prefix/suffix for relation or operation names.\n *\n * @param classType - The class type containing packageNameTokens and simpleName\n * @param first - Prefix to add before the name (e.g., \"/\" for relations)\n * @param name - The relation or operation name (may contain ::)\n * @param second - Optional suffix (e.g., \"/~list\")\n * @returns The constructed path\n */\nfunction restPath(classType: ClassType, first: string, name: string, second?: string): string {\n\tconst suffix = `${first}${name ? name.split(SPLITTER).join(\"/\") : \"\"}${second ?? \"\"}`;\n\tconst packages = classType.packageNameTokens?.length ? `${classType.packageNameTokens.join(\"/\")}/` : \"\";\n\tconst simplePath = (classType.simpleName ?? \"\")\n\t\t.split(SPLITTER)\n\t\t.filter((i) => !i.includes(TRANSFER_SKIP_SEGMENT))\n\t\t.join(\"/\");\n\treturn `/${packages}${simplePath}${suffix}`;\n}\n\n/**\n * Builds a path with the application's model name prefix.\n *\n * @param application - The application context\n * @param path - Optional path to append\n * @returns The path prefixed with the model name (with leading slash for URL construction)\n * @throws Error if application is not provided\n */\nfunction getPathForApp(application: Application, path?: string): string {\n\tif (!application) {\n\t\tthrow new Error(\n\t\t\t\"Application context is required for path building. Ensure the API is properly initialized with an Application.\"\n\t\t);\n\t}\n\tconst tmp = path ? path : \"\";\n\treturn `/${application.modelName}${tmp.length && !tmp.startsWith(\"/\") ? `/${tmp}` : tmp}`;\n}\n\n/**\n * Builds the root path for the actor from the application.\n *\n * @param app - The application context\n * @returns The actor root path (e.g., \"admin/Admin\")\n * @throws Error if application or actor is not provided\n */\nfunction rootPathForApp(app: Application): string {\n\tif (!app?.actor) {\n\t\tthrow new Error(\n\t\t\t\"Application.actor is required for path building. Ensure the Application has a valid actor ClassType.\"\n\t\t);\n\t}\n\tconst packagePath = app.actor.packageNameTokens?.length ? `${app.actor.packageNameTokens.join(\"/\")}/` : \"\";\n\treturn `${packagePath}${app.actor.simpleName ?? app.actor.name ?? \"Actor\"}`;\n}\n\n/**\n * Builds a path for the actor with optional additional path segments.\n *\n * @param application - The application context\n * @param path - Optional path to append after the actor path\n * @returns The full path including model name and actor path\n */\nexport function getPathForActor(application: Application, path = \"\"): string {\n\treturn getPathForApp(\n\t\tapplication,\n\t\trootPathForApp(application) + (path.length && !path.startsWith(\"/\") ? `/${path}` : path)\n\t);\n}\n\n/**\n * Builds the REST path for a relation with a given suffix.\n *\n * @param relation - The relation type\n * @param application - The application context\n * @param suffix - The operation suffix (e.g., \"/~list\", \"/~get\", \"/~range\")\n * @returns The full path for the relation endpoint\n */\nexport function getRelationPath(relation: RelationType, application: Application, suffix = \"/~list\"): string {\n\treturn getPathForActor(application, restPath(relation?.eContainer as ClassType, \"/\", relation!.name, suffix));\n}\n\n/**\n * Builds the REST path for a class type with a given suffix.\n *\n * @param classType - The class type\n * @param application - The application context\n * @param suffix - The operation suffix (e.g., \"/~template\", \"/~get\", \"/~update\")\n * @returns The full path for the class endpoint\n */\nexport function getClassPath(classType: ClassType, application: Application, suffix = \"\"): string {\n\treturn getPathForActor(application, restPath(classType, \"\", \"\", suffix));\n}\n\n/**\n * Builds the REST path for a mutation relation operation (create, set, unset, add, remove).\n * These use the /~update/ prefix for non-access relations.\n *\n * @param relation - The relation type\n * @param application - The application context\n * @param suffix - The operation suffix (e.g., \"/~create\", \"/~set\")\n * @param isAccess - Whether this is an access relation (skips /~update/ prefix)\n * @returns The full path for the mutation endpoint\n */\nexport function getMutationRelationPath(\n\trelation: RelationType,\n\tapplication: Application,\n\tsuffix: string,\n\tisAccess = false\n): string {\n\tconst classType = relation?.eContainer as ClassType;\n\tif (isAccess) {\n\t\t// Access relations don't use /~update/ prefix\n\t\treturn getPathForActor(application, restPath(classType, \"/\", relation!.name, suffix));\n\t}\n\t// Regular relations: /{classPath}/~update/{relationName}{suffix}\n\treturn getPathForActor(application, restPath(classType, \"/~update/\", relation!.name, suffix));\n}\n\n/**\n * Builds the REST path for an operation.\n *\n * @param classType - The class type containing the operation\n * @param operationName - The operation name\n * @param application - The application context\n * @param suffix - Optional suffix (e.g., \"/~validate\", \"/~range\")\n * @returns The full path for the operation endpoint\n */\nexport function getOperationPath(\n\tclassType: ClassType,\n\toperationName: string,\n\tapplication: Application,\n\tsuffix = \"\"\n): string {\n\treturn getPathForActor(application, restPath(classType, \"/\", operationName, suffix));\n}\n","/**\n * JUDO REST API client implementation.\n * Based on REST_REQUEST_MAPPING_SPECIFICATION.md\n *\n * This module provides a complete REST client for the JUDO backend,\n * implementing all operations defined in the specification:\n * - Transfer operations (get, template, update, delete)\n * - Relation operations (list, get, range, create, set, unset, add, remove)\n * - Operation invocations\n * - Access service operations (principal, metadata, file operations)\n */\n\nimport type { ClassType, RelationType } from \"@judo/model-api\";\nimport type { Application } from \"../types\";\nimport {\n\tDEFAULT_COMMAND_MASK,\n\tHEADER_COUNT_RECORDS,\n\tHEADER_MARK_SELECTED_RANGE_ITEMS,\n\tHEADER_MASK,\n\tHEADER_SIGNED_IDENTIFIER,\n\tHEADER_TOKEN,\n\tSUFFIX_ADD,\n\tSUFFIX_CREATE,\n\tSUFFIX_DELETE,\n\tSUFFIX_EXPORT,\n\tSUFFIX_GET,\n\tSUFFIX_LIST,\n\tSUFFIX_META,\n\tSUFFIX_PRINCIPAL,\n\tSUFFIX_RANGE,\n\tSUFFIX_REMOVE,\n\tSUFFIX_SET,\n\tSUFFIX_TEMPLATE,\n\tSUFFIX_UNSET,\n\tSUFFIX_UPDATE,\n\tSUFFIX_UPLOAD_TOKEN,\n\tSUFFIX_VALIDATE,\n} from \"./constants\";\nimport type { IJudoRestApi, OperationInfo } from \"./i-judo-rest-api\";\n\nexport type { OperationInfo } from \"./i-judo-rest-api\";\nimport { getClassPath, getMutationRelationPath, getOperationPath, getRelationPath } from \"./path-builder\";\nimport type {\n\tTransferData,\n\tTransferDeserializer,\n\tTransferSerializer,\n\tTransferStored,\n\tJudoRestResponse,\n\tQueryCustomizer,\n\tRangeRequestBody,\n} from \"./types\";\n\n/**\n * Configuration for JUDO REST API client.\n */\nexport interface JudoRestApiConfig {\n\t/** Base URL for the API (e.g., http://localhost:8080) */\n\tbaseUrl: string;\n\t/** The application context containing model name and actor info */\n\tapplication: Application;\n\t/** Request timeout in milliseconds */\n\ttimeout?: number;\n\t/** Default headers to include in all requests */\n\tdefaultHeaders?: Record<string, string>;\n\t/** Optional custom fetch implementation */\n\tfetch?: typeof fetch;\n\t/** Optional request interceptor */\n\tonRequest?: (request: RequestInit) => RequestInit | Promise<RequestInit>;\n\t/** Optional response interceptor */\n\tonResponse?: (response: Response) => Response | Promise<Response>;\n\t/** Optional error handler */\n\tonError?: (error: Error) => void;\n\t/** Optional transfer serializer for transforming transfers before sending */\n\ttransferSerializer?: TransferSerializer;\n\t/** Optional transfer deserializer for transforming responses */\n\ttransferDeserializer?: TransferDeserializer;\n}\n\n/**\n * JUDO REST API client.\n * Implements all REST operations according to the specification.\n */\nexport class JudoRestApi implements IJudoRestApi {\n\tprivate readonly config: JudoRestApiConfig;\n\tprivate readonly fetchImpl: typeof fetch;\n\tprivate _defaultHeaders: Record<string, string>;\n\n\tconstructor(config: JudoRestApiConfig) {\n\t\tif (!config.application) {\n\t\t\tthrow new Error(\n\t\t\t\t\"JudoRestApi requires 'application' in config. Ensure the API is created with a valid Application context.\"\n\t\t\t);\n\t\t}\n\t\tif (!config.application.actor) {\n\t\t\tthrow new Error(\n\t\t\t\t\"JudoRestApi requires 'application.actor' in config. Ensure the Application has a valid actor ClassType.\"\n\t\t\t);\n\t\t}\n\t\tthis.config = config;\n\t\tthis.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);\n\t\tthis._defaultHeaders = { ...config.defaultHeaders };\n\t}\n\n\t/**\n\t * Update the default headers applied to every request.\n\t * Use this to set or remove the Authorization header when the auth token changes.\n\t */\n\tsetDefaultHeaders(headers: Record<string, string>): void {\n\t\tthis._defaultHeaders = headers;\n\t}\n\n\t/**\n\t * Gets the full URL for a path.\n\t */\n\tprivate getUrl(path: string): string {\n\t\treturn `${this.config.baseUrl}${path}`;\n\t}\n\n\t/**\n\t * Serializes an transfer for sending in request body.\n\t * Uses the configured transferSerializer if provided, otherwise returns the transfer as-is.\n\t */\n\tprivate serializeTransfer<T>(transfer: T): unknown {\n\t\tif (this.config.transferSerializer) {\n\t\t\treturn this.config.transferSerializer.serialize(transfer);\n\t\t}\n\t\treturn transfer;\n\t}\n\n\t/**\n\t * Deserializes response data into an transfer.\n\t * Uses the configured transferDeserializer if provided, otherwise returns the data as-is.\n\t */\n\tprivate deserializeTransfer<T>(data: unknown): T {\n\t\tif (this.config.transferDeserializer) {\n\t\t\treturn this.config.transferDeserializer.deserialize(data) as T;\n\t\t}\n\t\treturn data as T;\n\t}\n\n\t/**\n\t * Deserializes an array of transfers from response data.\n\t */\n\tprivate deserializeArray<T>(data: unknown): T[] {\n\t\tif (!Array.isArray(data)) {\n\t\t\treturn [];\n\t\t}\n\t\tif (this.config.transferDeserializer) {\n\t\t\treturn data.map((item) => this.config.transferDeserializer!.deserialize(item) as T);\n\t\t}\n\t\treturn data as T[];\n\t}\n\n\t/**\n\t * Makes a request with optional interceptors.\n\t */\n\tprivate async request<T>(\n\t\tmethod: \"GET\" | \"POST\",\n\t\tpath: string,\n\t\toptions: {\n\t\t\tbody?: unknown;\n\t\t\theaders?: Record<string, string>;\n\t\t\tresponseType?: \"json\" | \"blob\";\n\t\t} = {}\n\t): Promise<JudoRestResponse<T>> {\n\t\tconst url = this.getUrl(path);\n\t\tconst headers: Record<string, string> = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t...this._defaultHeaders,\n\t\t\t...options.headers,\n\t\t};\n\n\t\tlet init: RequestInit = {\n\t\t\tmethod,\n\t\t\theaders,\n\t\t\tbody: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n\t\t};\n\n\t\t// Apply request interceptor\n\t\tif (this.config.onRequest) {\n\t\t\tinit = await this.config.onRequest(init);\n\t\t}\n\n\t\ttry {\n\t\t\tlet response = await this.fetchImpl(url, init);\n\n\t\t\t// Apply response interceptor\n\t\t\tif (this.config.onResponse) {\n\t\t\t\tresponse = await this.config.onResponse(response);\n\t\t\t}\n\n\t\t\tif (!response.ok) {\n\t\t\t\t// Try to parse error response as JSON for validation errors\n\t\t\t\tconst errorText = await response.text();\n\n\t\t\t\t// Handle validation errors (400 status)\n\t\t\t\tif (response.status === 400 && errorText.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst errorData = JSON.parse(errorText);\n\t\t\t\t\t\t// Check if it's a FeedbackItem array\n\t\t\t\t\t\tif (Array.isArray(errorData)) {\n\t\t\t\t\t\t\tconst { ValidationError } = await import(\"./types\");\n\t\t\t\t\t\t\tthrow new ValidationError(errorData);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (parseError) {\n\t\t\t\t\t\t// If not valid JSON or not FeedbackItem, fall through to generic error\n\t\t\t\t\t\tif (parseError instanceof Error && parseError.name === \"ValidationError\") {\n\t\t\t\t\t\t\tthrow parseError;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthrow new Error(`HTTP ${response.status}: ${errorText}`);\n\t\t\t}\n\n\t\t\tlet data: T;\n\t\t\tif (options.responseType === \"blob\") {\n\t\t\t\tdata = (await response.blob()) as T;\n\t\t\t} else {\n\t\t\t\tconst text = await response.text();\n\t\t\t\tdata = text.length > 0 ? JSON.parse(text) : (undefined as T);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdata,\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (this.config.onError) {\n\t\t\t\tthis.config.onError(error as Error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// ============================================\n\t// ENTITY OPERATIONS\n\t// ============================================\n\n\t/**\n\t * Gets a template (default values) for creating a new transfer.\n\t *\n\t * GET /{classPath}/~template\n\t */\n\tasync getTemplate(classType: ClassType): Promise<JudoRestResponse<TransferData>> {\n\t\tconst path = getClassPath(classType, this.config.application, SUFFIX_TEMPLATE);\n\t\tconst response = await this.request<TransferData>(\"GET\", path);\n\t\treturn { ...response, data: this.deserializeTransfer<TransferData>(response.data) };\n\t}\n\n\t/**\n\t * Refreshes (retrieves) an transfer by its signed identifier.\n\t *\n\t * POST /{classPath}/~get\n\t * Headers: X-Judo-SignedIdentifier\n\t */\n\tasync refresh(\n\t\tclassType: ClassType,\n\t\ttarget: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer\n\t): Promise<JudoRestResponse<TransferStored>> {\n\t\tconst path = getClassPath(classType, this.config.application, SUFFIX_GET);\n\t\tconst response = await this.request<TransferStored>(\"POST\", path, {\n\t\t\tbody: queryCustomizer ?? {},\n\t\t\theaders: {\n\t\t\t\t[HEADER_SIGNED_IDENTIFIER]: target.__signedIdentifier!,\n\t\t\t},\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Updates an existing transfer.\n\t *\n\t * POST /{classPath}/~update\n\t * Headers: X-Judo-SignedIdentifier, X-Judo-Mask\n\t */\n\tasync update(classType: ClassType, target: TransferStored, mask?: string): Promise<JudoRestResponse<TransferStored>> {\n\t\tconst path = getClassPath(classType, this.config.application, SUFFIX_UPDATE);\n\t\tconst response = await this.request<TransferStored>(\"POST\", path, {\n\t\t\tbody: this.serializeTransfer(target),\n\t\t\theaders: {\n\t\t\t\t[HEADER_SIGNED_IDENTIFIER]: target.__signedIdentifier!,\n\t\t\t\t[HEADER_MASK]: mask ?? DEFAULT_COMMAND_MASK,\n\t\t\t},\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Validates an transfer update without persisting.\n\t *\n\t * POST /{classPath}/~validate\n\t * Headers: X-Judo-SignedIdentifier\n\t */\n\tasync validateUpdate(classType: ClassType, target: TransferStored): Promise<JudoRestResponse<TransferStored>> {\n\t\tconst path = getClassPath(classType, this.config.application, SUFFIX_VALIDATE);\n\t\tconst response = await this.request<TransferStored>(\"POST\", path, {\n\t\t\tbody: this.serializeTransfer(target),\n\t\t\theaders: {\n\t\t\t\t[HEADER_SIGNED_IDENTIFIER]: target.__signedIdentifier!,\n\t\t\t},\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Deletes an existing transfer.\n\t *\n\t * POST /{classPath}/~delete\n\t * Headers: X-Judo-SignedIdentifier\n\t */\n\tasync delete(classType: ClassType, target: TransferStored): Promise<JudoRestResponse<void>> {\n\t\tconst path = getClassPath(classType, this.config.application, SUFFIX_DELETE);\n\t\treturn this.request<void>(\"POST\", path, {\n\t\t\theaders: {\n\t\t\t\t[HEADER_SIGNED_IDENTIFIER]: target.__signedIdentifier!,\n\t\t\t},\n\t\t});\n\t}\n\n\t// ============================================\n\t// RELATION OPERATIONS\n\t// ============================================\n\n\t/**\n\t * Lists transfers in a collection relation.\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~list\n\t * Headers: X-Judo-SignedIdentifier (if owner provided), X-Judo-CountRecords (if countRecords true)\n\t */\n\tasync listRelation(\n\t\trelation: RelationType,\n\t\towner?: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer,\n\t\tcountRecords?: boolean\n\t): Promise<JudoRestResponse<TransferStored[]>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_LIST);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\tif (countRecords) {\n\t\t\theaders[HEADER_COUNT_RECORDS] = \"true\";\n\t\t}\n\n\t\tconst response = await this.request<TransferStored[]>(\"POST\", path, {\n\t\t\tbody: queryCustomizer ?? {},\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeArray<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Gets a single transfer from a non-collection relation.\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~get\n\t * Headers: X-Judo-SignedIdentifier\n\t */\n\tasync getRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer\n\t): Promise<JudoRestResponse<TransferStored | null>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_GET);\n\t\tconst response = await this.request<TransferStored | undefined>(\"POST\", path, {\n\t\t\tbody: queryCustomizer ?? {},\n\t\t\theaders: {\n\t\t\t\t[HEADER_SIGNED_IDENTIFIER]: owner.__signedIdentifier!,\n\t\t\t},\n\t\t});\n\n\t\t// Handle null/empty/undefined response (nullable deserialization)\n\t\tconst data =\n\t\t\tresponse.data === undefined || response.data === null\n\t\t\t\t? null\n\t\t\t\t: this.deserializeTransfer<TransferStored>(response.data);\n\n\t\treturn { ...response, data };\n\t}\n\n\t/**\n\t * Refreshes a non-collection access relation directly.\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~get\n\t * No owner header (access relation)\n\t */\n\tasync refreshAccessRelation(\n\t\trelation: RelationType,\n\t\tqueryCustomizer?: QueryCustomizer\n\t): Promise<JudoRestResponse<TransferStored>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_GET);\n\t\tconst response = await this.request<TransferStored>(\"POST\", path, {\n\t\t\tbody: queryCustomizer ?? {},\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Gets the available range of transfers for a relation.\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~range\n\t * Headers: X-Judo-Mark-Selected-Range-Items\n\t */\n\tasync getRelationRange(\n\t\trelation: RelationType,\n\t\towner?: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer,\n\t\tcountRecords?: boolean\n\t): Promise<JudoRestResponse<TransferStored[]>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_RANGE);\n\t\tconst body: RangeRequestBody = {\n\t\t\towner: owner ?? {},\n\t\t\tqueryCustomizer: queryCustomizer ?? {},\n\t\t};\n\n\t\tconst headers: Record<string, string> = {\n\t\t\t[HEADER_MARK_SELECTED_RANGE_ITEMS]: \"true\",\n\t\t};\n\n\t\tif (countRecords) {\n\t\t\theaders[HEADER_COUNT_RECORDS] = \"true\";\n\t\t}\n\n\t\tconst response = await this.request<TransferStored[]>(\"POST\", path, {\n\t\t\tbody,\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeArray<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Gets template for relation target.\n\t *\n\t * GET /{targetClassPath}/~template\n\t */\n\tasync getRelationTemplate(relation: RelationType): Promise<JudoRestResponse<TransferData>> {\n\t\tconst path = getClassPath(relation.target as ClassType, this.config.application, SUFFIX_TEMPLATE);\n\t\tconst response = await this.request<TransferData>(\"GET\", path);\n\t\treturn { ...response, data: this.deserializeTransfer<TransferData>(response.data) };\n\t}\n\n\t/**\n\t * Creates a new transfer through a relation.\n\t *\n\t * Non-access: POST /{ownerClassPath}/~update/{relationName}/~create\n\t * Access: POST /{ownerClassPath}/{relationName}/~create\n\t */\n\tasync createRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored | undefined,\n\t\tdata: TransferData,\n\t\tmask?: string\n\t): Promise<JudoRestResponse<TransferStored>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = isAccess\n\t\t\t? getRelationPath(relation, this.config.application, SUFFIX_CREATE)\n\t\t\t: getMutationRelationPath(relation, this.config.application, SUFFIX_CREATE);\n\n\t\tconst headers: Record<string, string> = {\n\t\t\t[HEADER_MASK]: mask ?? DEFAULT_COMMAND_MASK,\n\t\t};\n\n\t\tif (!isAccess && owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\tconst response = await this.request<TransferStored>(\"POST\", path, {\n\t\t\tbody: this.serializeTransfer(data),\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Validates creation through a relation.\n\t *\n\t * Non-access: POST /{ownerClassPath}/~update/{relationName}/~validate\n\t * Access: POST /{ownerClassPath}/{relationName}/~validate\n\t */\n\tasync validateCreateRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored | undefined,\n\t\tdata: TransferData\n\t): Promise<JudoRestResponse<TransferData>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = isAccess\n\t\t\t? getRelationPath(relation, this.config.application, SUFFIX_VALIDATE)\n\t\t\t: getMutationRelationPath(relation, this.config.application, SUFFIX_VALIDATE);\n\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (!isAccess && owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\tconst response = await this.request<TransferData>(\"POST\", path, {\n\t\t\tbody: this.serializeTransfer(data),\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferData>(response.data) };\n\t}\n\n\t/**\n\t * Sets a relation to point to specific transfer/transfers.\n\t *\n\t * POST /{ownerClassPath}/~update/{relationName}/~set\n\t * Headers: X-Judo-SignedIdentifier (non-access only)\n\t */\n\tasync setRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored,\n\t\tselected: TransferStored | TransferStored[]\n\t): Promise<JudoRestResponse<void>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = getMutationRelationPath(relation, this.config.application, SUFFIX_SET, isAccess);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (!isAccess) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier!;\n\t\t}\n\n\t\t// Serialize single or array based on what's passed\n\t\tconst body = Array.isArray(selected)\n\t\t\t? selected.map((s) => this.serializeTransfer(s))\n\t\t\t: this.serializeTransfer(selected);\n\n\t\treturn this.request<void>(\"POST\", path, {\n\t\t\tbody,\n\t\t\theaders,\n\t\t});\n\t}\n\n\t/**\n\t * Clears a relation (sets to null/empty).\n\t *\n\t * POST /{ownerClassPath}/~update/{relationName}/~unset\n\t * Headers: X-Judo-SignedIdentifier (non-access only)\n\t */\n\tasync unsetRelation(relation: RelationType, owner: TransferStored): Promise<JudoRestResponse<void>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = getMutationRelationPath(relation, this.config.application, SUFFIX_UNSET, isAccess);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (!isAccess) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier!;\n\t\t}\n\n\t\treturn this.request<void>(\"POST\", path, {\n\t\t\theaders,\n\t\t});\n\t}\n\n\t/**\n\t * Adds transfers to a collection relation.\n\t *\n\t * POST /{ownerClassPath}/~update/{relationName}/~add\n\t * Headers: X-Judo-SignedIdentifier (non-access only)\n\t */\n\tasync addToRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored,\n\t\tselected: TransferStored[]\n\t): Promise<JudoRestResponse<void>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = getMutationRelationPath(relation, this.config.application, SUFFIX_ADD, isAccess);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (!isAccess) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier!;\n\t\t}\n\n\t\treturn this.request<void>(\"POST\", path, {\n\t\t\tbody: selected.map((s) => this.serializeTransfer(s)),\n\t\t\theaders,\n\t\t});\n\t}\n\n\t/**\n\t * Removes transfers from a collection relation.\n\t *\n\t * POST /{ownerClassPath}/~update/{relationName}/~remove\n\t * Headers: X-Judo-SignedIdentifier (non-access only)\n\t */\n\tasync removeFromRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored,\n\t\tselected: TransferStored[]\n\t): Promise<JudoRestResponse<void>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = getMutationRelationPath(relation, this.config.application, SUFFIX_REMOVE, isAccess);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (!isAccess) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier!;\n\t\t}\n\n\t\treturn this.request<void>(\"POST\", path, {\n\t\t\tbody: selected.map((s) => this.serializeTransfer(s)),\n\t\t\theaders,\n\t\t});\n\t}\n\n\t/**\n\t * Exports relation data as a file (CSV/Excel).\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~export\n\t * Headers: X-Judo-SignedIdentifier (if owner provided)\n\t */\n\tasync exportRelation(\n\t\trelation: RelationType,\n\t\towner?: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer\n\t): Promise<JudoRestResponse<Blob>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_EXPORT);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\treturn this.request<Blob>(\"POST\", path, {\n\t\t\tbody: queryCustomizer ?? {},\n\t\t\theaders,\n\t\t\tresponseType: \"blob\",\n\t\t});\n\t}\n\n\t// ============================================\n\t// OPERATION INVOCATIONS\n\t// ============================================\n\n\t/**\n\t * Invokes an operation on an transfer.\n\t *\n\t * POST /{classPath}/{operationName}\n\t * Headers: X-Judo-SignedIdentifier (if mapped/non-static)\n\t */\n\tasync invokeOperation<TInput = unknown, TOutput = unknown>(\n\t\tclassType: ClassType,\n\t\toperation: OperationInfo,\n\t\towner?: TransferStored,\n\t\tinput?: TInput\n\t): Promise<JudoRestResponse<TOutput | undefined>> {\n\t\tconst path = getOperationPath(classType, operation.name, this.config.application);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (operation.isMapped && !operation.isStatic && owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\tconst response = await this.request<TOutput | undefined>(\"POST\", path, {\n\t\t\tbody: operation.hasInput ? this.serializeTransfer(input) : undefined,\n\t\t\theaders,\n\t\t});\n\n\t\t// Deserialize output if present\n\t\tif (response.data !== undefined && response.data !== null) {\n\t\t\treturn { ...response, data: this.deserializeTransfer<TOutput>(response.data) };\n\t\t}\n\t\treturn response;\n\t}\n\n\t/**\n\t * Validates operation input without execution.\n\t *\n\t * POST /{classPath}/{operationName}/~validate\n\t * Headers: X-Judo-SignedIdentifier (if mapped/non-static)\n\t */\n\tasync validateOperationInput<TInput = unknown>(\n\t\tclassType: ClassType,\n\t\toperation: OperationInfo,\n\t\towner?: TransferStored,\n\t\tinput?: TInput\n\t): Promise<JudoRestResponse<TInput>> {\n\t\tconst path = getOperationPath(classType, operation.name, this.config.application, SUFFIX_VALIDATE);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (operation.isMapped && !operation.isStatic && owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\tconst response = await this.request<TInput>(\"POST\", path, {\n\t\t\tbody: this.serializeTransfer(input),\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TInput>(response.data) };\n\t}\n\n\t/**\n\t * Gets template for operation input.\n\t *\n\t * GET /{inputClassPath}/~template\n\t */\n\tasync getOperationInputTemplate(operation: OperationInfo): Promise<JudoRestResponse<TransferData>> {\n\t\tif (!operation.inputType) {\n\t\t\tthrow new Error(`Operation ${operation.name} has no input type`);\n\t\t}\n\t\tconst path = getClassPath(operation.inputType, this.config.application, SUFFIX_TEMPLATE);\n\t\tconst response = await this.request<TransferData>(\"GET\", path);\n\t\treturn { ...response, data: this.deserializeTransfer<TransferData>(response.data) };\n\t}\n\n\t/**\n\t * Gets range for operation input (selector operations).\n\t *\n\t * POST /{classPath}/{operationName}/~range\n\t * Headers: X-Judo-Mark-Selected-Range-Items\n\t */\n\tasync getOperationInputRange(\n\t\tclassType: ClassType,\n\t\toperation: OperationInfo,\n\t\towner?: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer,\n\t\tcountRecords?: boolean\n\t): Promise<JudoRestResponse<TransferStored[]>> {\n\t\tconst path = getOperationPath(classType, operation.name, this.config.application, SUFFIX_RANGE);\n\t\tconst body: RangeRequestBody = {\n\t\t\towner: owner ?? {},\n\t\t\tqueryCustomizer: queryCustomizer ?? {},\n\t\t};\n\n\t\tconst headers: Record<string, string> = {\n\t\t\t[HEADER_MARK_SELECTED_RANGE_ITEMS]: \"true\",\n\t\t};\n\n\t\tif (countRecords) {\n\t\t\theaders[HEADER_COUNT_RECORDS] = \"true\";\n\t\t}\n\n\t\tconst response = await this.request<TransferStored[]>(\"POST\", path, {\n\t\t\tbody,\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeArray<TransferStored>(response.data) };\n\t}\n\n\t// ============================================\n\t// ACCESS SERVICE OPERATIONS\n\t// ============================================\n\n\t/**\n\t * Gets the current authenticated user's principal data.\n\t *\n\t * GET /{actorPath}/{actorPath}/~principal — the JAX-RS service is mounted\n\t * at `/{actorPath}` AND every resource inside it is `@Path`-ed as\n\t * `{actorPath}/...`, producing the duplicated segment that the BE WADL\n\t * confirms (see `getClassPath`, which adds the inner repeat via `restPath`).\n\t */\n\tasync getPrincipal(): Promise<JudoRestResponse<TransferStored>> {\n\t\tif (!this.config.application.actor) {\n\t\t\tthrow new Error(\"Application.actor is required to fetch principal data.\");\n\t\t}\n\t\tconst path = getClassPath(this.config.application.actor, this.config.application, SUFFIX_PRINCIPAL);\n\t\tconst response = await this.request<TransferStored>(\"GET\", path);\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Gets application metadata.\n\t *\n\t * GET /{actorPath}/{actorPath}/~meta — same double-prefix shape as ~principal.\n\t */\n\tasync getMetadata(): Promise<JudoRestResponse<unknown>> {\n\t\tif (!this.config.application.actor) {\n\t\t\tthrow new Error(\"Application.actor is required to fetch metadata.\");\n\t\t}\n\t\tconst path = getClassPath(this.config.application.actor, this.config.application, SUFFIX_META);\n\t\treturn this.request<unknown>(\"GET\", path);\n\t}\n\n\t/**\n\t * Uploads a file to a binary attribute.\n\t *\n\t * 1. POST {attributePath}/~upload-token to get token\n\t * 2. POST /upload with token and file\n\t */\n\tasync uploadFile(attributePath: string, file: File): Promise<JudoRestResponse<unknown>> {\n\t\t// Step 1: Get upload token\n\t\tconst tokenResponse = await this.request<{ token: string }>(\"POST\", `${attributePath}${SUFFIX_UPLOAD_TOKEN}`);\n\t\tconst token = tokenResponse.data.token;\n\n\t\t// Step 2: Upload file\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", file);\n\n\t\tconst url = `${this.config.baseUrl}/upload`;\n\t\tconst response = await this.fetchImpl(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...this._defaultHeaders,\n\t\t\t\t[HEADER_TOKEN]: token,\n\t\t\t},\n\t\t\tbody: formData,\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`Upload failed: HTTP ${response.status}`);\n\t\t}\n\n\t\treturn {\n\t\t\tdata: await response.json(),\n\t\t\tstatus: response.status,\n\t\t\theaders: response.headers,\n\t\t};\n\t}\n\n\t/**\n\t * Downloads a file from a binary attribute.\n\t *\n\t * GET /download?disposition={disposition}\n\t * Headers: X-Token\n\t */\n\tasync downloadFile(\n\t\tdownloadToken: string,\n\t\tdisposition: \"inline\" | \"attachment\" = \"attachment\"\n\t): Promise<JudoRestResponse<Blob>> {\n\t\tconst url = `${this.config.baseUrl}/download?disposition=${disposition}`;\n\t\tconst response = await this.fetchImpl(url, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: {\n\t\t\t\t...this._defaultHeaders,\n\t\t\t\t[HEADER_TOKEN]: downloadToken,\n\t\t\t},\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`Download failed: HTTP ${response.status}`);\n\t\t}\n\n\t\treturn {\n\t\t\tdata: await response.blob(),\n\t\t\tstatus: response.status,\n\t\t\theaders: response.headers,\n\t\t};\n\t}\n\n\t/**\n\t * Finds a specific transfer instance from an access relation by identifier.\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~list\n\t * Body: { _identifier, _mask?, _seek: { limit: 1 } }\n\t */\n\tasync findInstance(\n\t\trelation: RelationType,\n\t\tidentifier: string,\n\t\tmask?: string\n\t): Promise<JudoRestResponse<TransferStored | null>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_LIST);\n\t\tconst body: QueryCustomizer = {\n\t\t\t_identifier: identifier,\n\t\t\t_seek: { limit: 1 },\n\t\t};\n\n\t\tif (mask) {\n\t\t\tbody._mask = mask;\n\t\t}\n\n\t\tconst response = await this.request<TransferStored[]>(\"POST\", path, { body });\n\n\t\t// Return first item (deserialized) or null\n\t\tconst items = this.deserializeArray<TransferStored>(response.data);\n\t\tconst data = items.length > 0 ? items[0] : null;\n\t\treturn { ...response, data };\n\t}\n}\n\n/**\n * Factory function to create a JUDO REST API client.\n */\nexport function createJudoRestApi(config: JudoRestApiConfig): JudoRestApi {\n\treturn new JudoRestApi(config);\n}\n","/**\n * JUDO REST API types.\n * Based on REST_REQUEST_MAPPING_SPECIFICATION.md\n */\n\n// ============================================\n// HTTP/Response Types\n// ============================================\n\n/**\n * HTTP method types used in the REST layer.\n * GET is used for template retrieval, file downloads, metadata, principal.\n * POST is used for all other operations (CRUD, list, range, operations, validation).\n */\nexport type HttpMethod = \"GET\" | \"POST\";\n\n/**\n * Response type indicating how to handle the response body.\n */\nexport type ResponseType = \"json\" | \"blob\";\n\n/**\n * How to deserialize the response.\n * - single: Deserialize as a single transfer\n * - array: Deserialize as an array of transfers\n * - void: No deserialization needed (response is empty)\n * - nullable: Deserialize as single transfer or null\n */\nexport type DeserializationType = \"single\" | \"array\" | \"void\" | \"nullable\";\n\n/**\n * Service type categories.\n */\nexport type ServiceType = \"class\" | \"relation\" | \"access\";\n\n// ============================================\n// Serialization/Deserialization\n// ============================================\n\n/**\n * Configuration for deserializing the response.\n */\nexport interface ResponseDeserializerConfig {\n\t/** Type of deserialization to apply */\n\ttype: DeserializationType;\n\t/** Target class FQName for deserialization (if applicable) */\n\ttargetClassFqName?: string;\n\t/** Whether the target is a stored (persisted) transfer */\n\tisStored: boolean;\n}\n\n/**\n * Transfer serializer interface for transforming transfers before sending.\n * The input type is unknown to support any transfer type.\n */\nexport interface TransferSerializer {\n\t/** Serialize an transfer for sending in request body */\n\tserialize(transfer: unknown): unknown;\n}\n\n/**\n * Transfer deserializer interface for transforming responses.\n * The output type is unknown to support any transfer type.\n */\nexport interface TransferDeserializer {\n\t/** Deserialize a response into an transfer */\n\tdeserialize(data: unknown): unknown;\n}\n\n// ============================================\n// Temporal Field Types\n// ============================================\n\n/**\n * Classification of temporal (date/time) field types.\n *\n * - `date`: Date-only value (`YYYY-MM-DD`) — converted to `Date` at local midnight\n * - `time`: Time-only value (`HH:mm[:ss]`) — kept as `string` (no `Date` conversion)\n * - `timestamp`: Full datetime with timezone (`YYYY-MM-DDTHH:mm:ss[.SSS]Z`) — converted to `Date`\n */\nexport type TemporalFieldType = \"date\" | \"time\" | \"timestamp\";\n\n/**\n * Registry mapping transfer type FQNs to their temporal field declarations.\n *\n * Keys match `__entityType` values from API responses (e.g., `\"Demo::OrderDTO\"`).\n * Values map field names to their temporal type for serialization/deserialization.\n *\n * @example\n * ```typescript\n * const registry: TemporalFieldRegistry = {\n * \"Demo::OrderDTO\": { orderDate: \"date\", createdAt: \"timestamp\" },\n * \"Demo::MissionDTO\": { startDate: \"date\", endDate: \"date\" },\n * };\n * ```\n */\nexport type TemporalFieldRegistry = Record<string, Record<string, TemporalFieldType>>;\n\n// ============================================\n// API Configuration\n// ============================================\n\n/**\n * Configuration for JUDO REST API client.\n */\nexport interface JudoRestApiConfig {\n\t/** Base URL for the API (e.g., http://localhost:8080) */\n\tbaseUrl: string;\n\t/** Application base path (e.g., /api) */\n\tbasePath: string;\n\t/** Application model name (e.g., edemokracia) */\n\tmodelName: string;\n\t/** Actor path (e.g., admin/Admin) */\n\tactorPath: string;\n\t/** Request timeout in milliseconds */\n\ttimeout?: number;\n\t/** Default headers to include in all requests */\n\tdefaultHeaders?: Record<string, string>;\n\t/** Optional custom fetch implementation */\n\tfetch?: typeof fetch;\n\t/** Optional request interceptor */\n\tonRequest?: (request: RequestInit) => RequestInit | Promise<RequestInit>;\n\t/** Optional response interceptor */\n\tonResponse?: (response: Response) => Response | Promise<Response>;\n\t/** Optional error handler */\n\tonError?: (error: Error) => void;\n\t/**\n\t * Optional transfer serializer for transforming transfers before sending.\n\t * If not provided, transfers are sent as-is (JSON.stringify).\n\t */\n\ttransferSerializer?: TransferSerializer;\n\t/**\n\t * Optional transfer deserializer for transforming responses.\n\t * If not provided, responses are used as-is (JSON.parse result).\n\t */\n\ttransferDeserializer?: TransferDeserializer;\n}\n\n/**\n * Query customizer for list/get operations.\n */\nexport interface QueryCustomizer {\n\t_mask?: string;\n\t_orderBy?: Array<{ attribute: string; descending?: boolean }>;\n\t_seek?: { limit?: number; lastItem?: unknown };\n\t_filter?: unknown;\n\t_identifier?: string;\n}\n\n/**\n * Base transfer data interface.\n *\n */\nexport interface TransferData {\n\t[key: string]: unknown;\n}\n\n/**\n * Strict transfer data — a TransferData whose *own* properties conform to `T`.\n *\n * Use in generated code and userland APIs where the exact field set is known.\n *\n * @typeParam T - Strict field definitions (e.g. `{ name: string; age: number }`)\n */\nexport type StrictTransferData<T extends Record<string, unknown> = Record<string, unknown>> = TransferData & T;\n\n/**\n * Stored transfer with identifiers.\n */\nexport interface TransferStored extends TransferData {\n\t__identifier?: string;\n\t__signedIdentifier?: string;\n\t__typename?: string;\n\t__entityType?: string;\n}\n\n/**\n * Strict stored transfer — a TransferStored with compile-time field types from `T`.\n *\n * @typeParam T - Strict field definitions\n */\nexport type StrictTransferStored<T extends Record<string, unknown> = Record<string, unknown>> = TransferStored & T;\n\n/**\n * Response wrapper for JUDO REST responses.\n */\nexport interface JudoRestResponse<T> {\n\tdata: T;\n\tstatus: number;\n\theaders: Headers;\n}\n\n/**\n * Path context for building REST paths.\n */\nexport interface PathContext {\n\t/** Package name tokens (e.g., [\"admin\"]) */\n\tpackageNameTokens: string[];\n\t/** Simple name (e.g., \"Issue\") */\n\tsimpleName: string;\n}\n\n/**\n * Class type metadata for path building.\n */\nexport interface ClassTypeMetadata extends PathContext {\n\t/** Fully qualified name */\n\tfqName?: string;\n\t/** Whether the class is mapped */\n\tisMapped?: boolean;\n}\n\n/**\n * Relation type metadata for path building.\n */\nexport interface RelationMetadata {\n\t/** Relation name */\n\tname: string;\n\t/** Owner class metadata */\n\towner: ClassTypeMetadata;\n\t/** Target class metadata */\n\ttarget: ClassTypeMetadata;\n\t/** Whether this is an access relation */\n\tisAccess?: boolean;\n\t/** Whether this is a collection relation */\n\tisCollection?: boolean;\n}\n\n/**\n * Operation type metadata.\n */\nexport interface OperationMetadata {\n\t/** Operation name */\n\tname: string;\n\t/** Whether the operation is static */\n\tisStatic?: boolean;\n\t/** Whether the operation is mapped */\n\tisMapped?: boolean;\n\t/** Whether the operation has input */\n\thasInput?: boolean;\n\t/** Whether the operation has output */\n\thasOutput?: boolean;\n\t/** Input type metadata */\n\tinputType?: ClassTypeMetadata;\n\t/** Output type metadata */\n\toutputType?: ClassTypeMetadata;\n}\n\n/**\n * Range request body structure.\n */\nexport interface RangeRequestBody {\n\towner?: TransferStored;\n\tqueryCustomizer?: QueryCustomizer;\n}\n\n// ============================================\n// Validation & Error Types\n// ============================================\n\n/**\n * Validation feedback item from REST API.\n * Returned in response body for 400 validation errors.\n */\nexport interface FeedbackItem {\n\t/** Error code identifier */\n\tcode: string;\n\t/** Severity level of the feedback */\n\tlevel: \"ERROR\" | \"WARNING\" | \"INFO\";\n\t/**\n\t * Location of the error - typically the attribute path.\n\t * For nested properties, format is: \"relationName.attributeName\"\n\t * For simple attributes, format is: \"attributeName\"\n\t */\n\tlocation: string;\n\t/** Human-readable error message */\n\tmessage?: string;\n}\n\n/**\n * Validation error thrown when API returns 400 status.\n * Contains array of FeedbackItem with field-level error details.\n */\nexport class ValidationError extends Error {\n\treadonly feedbackItems: FeedbackItem[];\n\treadonly status: number = 400;\n\n\tconstructor(feedbackItems: FeedbackItem[]) {\n\t\tconst firstError = feedbackItems.find((f) => f.level === \"ERROR\");\n\t\tsuper(firstError?.message ?? \"Validation failed\");\n\t\tthis.name = \"ValidationError\";\n\t\tthis.feedbackItems = feedbackItems;\n\t}\n\n\t/**\n\t * Get errors as a map of field location to error message.\n\t * Useful for setting form field errors.\n\t */\n\ttoFieldErrors(): Record<string, string> {\n\t\tconst errors: Record<string, string> = {};\n\t\tfor (const item of this.feedbackItems) {\n\t\t\tif (item.level === \"ERROR\" && item.location) {\n\t\t\t\terrors[item.location] = item.message ?? item.code;\n\t\t\t}\n\t\t}\n\t\treturn errors;\n\t}\n}\n\n// ============================================\n// Dialog Response Types\n// ============================================\n\n/**\n * Result type for dialog submission.\n * Used for create dialogs opened from eager/lazy components.\n */\nexport type DialogResult<T = TransferData> = { outcome: \"cancel\" } | { outcome: \"submit\"; data: T };\n\n/**\n * Callback for dialog submission.\n * Called when user submits the create form.\n */\nexport type OnDialogSubmit<T = TransferData> = (data: T) => Promise<void>;\n\n/**\n * Callback for dialog validation.\n * Called before submission to validate form data.\n * Returns field errors or null if valid.\n */\nexport type OnDialogValidate<T = TransferData> = (data: T) => Promise<Record<string, string> | null>;\n","/**\n * Default transfer serializer for JUDO REST API.\n *\n * Strips properties that should not be sent to the API:\n *\n * ## Backend-Provided Properties (read-only, never send back)\n * These properties are provided by the backend when retrieving transfers.\n * The frontend must NOT create or mutate these - they are server-managed:\n *\n * - `__identifier`: Backend-assigned transfer identifier\n * - `__signedIdentifier`: Signed token for transfer operations (exception: IS sent)\n * - `__entityType`: Backend type information\n * - `__deleteable`: Permission flag from backend\n * - `__updateable`: Permission flag from backend\n * - `__version`: Optimistic locking version\n *\n * ## Frontend-Only Properties (client-side state, never serialize)\n * These are created by the frontend for local state management:\n *\n * - `__isNew`: Marker for locally-created transfers not yet persisted\n * - `__items`: Array of related transfers for eager table state\n * - `__tempId`: Temporary client-side ID for tracking new transfers\n *\n * The only preserved `__*` property is `__signedIdentifier`, which is required\n * by the API for transfer operations.\n */\n\nimport type { TemporalFieldRegistry, TemporalFieldType, TransferData, TransferSerializer } from \"./types\";\n\n/**\n * Properties provided by the backend that should not be sent in requests.\n * These are read-only metadata assigned by the server.\n */\nexport const BACKEND_PROPERTIES = new Set<string>([\n\t\"__identifier\",\n\t\"__entityType\",\n\t\"__deleteable\",\n\t\"__updateable\",\n\t\"__version\",\n]);\n\n/**\n * Properties created by the frontend for local state management.\n * These should never be serialized to the API.\n */\nexport const FRONTEND_PROPERTIES = new Set<string>([\"__isNew\", \"__items\", \"__tempId\"]);\n\n/**\n * Combined set of all internal properties that should not be serialized.\n */\nexport const INTERNAL_PROPERTIES = new Set<string>([...BACKEND_PROPERTIES, ...FRONTEND_PROPERTIES]);\n\n/**\n * Check if a property is internal and should be stripped from serialization.\n * A property is internal if:\n * 1. It's in the INTERNAL_PROPERTIES set, OR\n * 2. It starts with `__` but is NOT `__signedIdentifier`\n *\n * @param key - Property name to check\n * @returns true if the property should be stripped\n */\nexport function isInternalProperty(key: string): boolean {\n\t// Always allow __signedIdentifier - it's required by the API\n\tif (key === \"__signedIdentifier\") {\n\t\treturn false;\n\t}\n\n\t// Check explicit internal properties\n\tif (INTERNAL_PROPERTIES.has(key)) {\n\t\treturn true;\n\t}\n\n\t// Any other double-underscore prefix is internal\n\treturn key.startsWith(\"__\");\n}\n\n/**\n * Strip internal properties from an transfer.\n * Creates a new object with only non-internal properties.\n *\n * @param transfer - Transfer to clean\n * @returns New object without internal properties\n */\nexport function stripInternalProperties<T extends TransferData>(transfer: T): Partial<T> {\n\tconst result: Partial<T> = {};\n\n\tfor (const [key, value] of Object.entries(transfer)) {\n\t\tif (!isInternalProperty(key)) {\n\t\t\t(result as TransferData)[key] = value;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Default transfer serializer that strips internal properties.\n * Use this when configuring JudoRestApi to ensure internal metadata\n * is not sent to the server.\n *\n * @example\n * ```typescript\n * const api = new JudoRestApi({\n * baseUrl: 'http://localhost:8080',\n * basePath: '/api',\n * modelName: 'myapp',\n * actorPath: 'admin/Admin',\n * transferSerializer: defaultTransferSerializer,\n * });\n * ```\n */\nexport const defaultTransferSerializer: TransferSerializer = {\n\tserialize(transfer: unknown): unknown {\n\t\tif (transfer === null || transfer === undefined) {\n\t\t\treturn transfer;\n\t\t}\n\n\t\tif (typeof transfer !== \"object\") {\n\t\t\treturn transfer;\n\t\t}\n\n\t\tif (Array.isArray(transfer)) {\n\t\t\treturn transfer.map((item) => this.serialize(item));\n\t\t}\n\n\t\treturn stripInternalProperties(transfer as TransferData);\n\t},\n};\n\n// ============================================\n// Model-Aware Serializer\n// ============================================\n\n/**\n * Serialize a `Date` value to its wire format based on temporal field type.\n *\n * - `date` → `\"YYYY-MM-DD\"` using **local** date components (avoids timezone shift)\n * - `timestamp` → full ISO 8601 UTC string via `Date.toISOString()`\n * - `time` → `\"HH:mm:ss\"` using local time components\n *\n * @param date - The `Date` to serialize\n * @param fieldType - The temporal field classification\n * @returns Formatted string for the API wire format\n */\nexport function serializeTemporalValue(date: Date, fieldType: TemporalFieldType): string {\n\tswitch (fieldType) {\n\t\tcase \"date\": {\n\t\t\tconst y = date.getFullYear();\n\t\t\tconst m = String(date.getMonth() + 1).padStart(2, \"0\");\n\t\t\tconst d = String(date.getDate()).padStart(2, \"0\");\n\t\t\treturn `${y}-${m}-${d}`;\n\t\t}\n\t\tcase \"timestamp\":\n\t\t\treturn date.toISOString();\n\t\tcase \"time\": {\n\t\t\tconst h = String(date.getHours()).padStart(2, \"0\");\n\t\t\tconst mi = String(date.getMinutes()).padStart(2, \"0\");\n\t\t\tconst s = String(date.getSeconds()).padStart(2, \"0\");\n\t\t\treturn `${h}:${mi}:${s}`;\n\t\t}\n\t}\n}\n\n/**\n * Create a model-aware transfer serializer that converts `Date` objects to\n * the appropriate wire format **and** strips internal `__*` properties.\n *\n * Uses `__entityType` from the transfer (before stripping) to look up\n * the field type in the registry and format `Date` values accordingly.\n * Falls back to `Date.toISOString()` for `Date` values on unregistered fields.\n *\n * @param registry - Mapping of entity type FQNs to temporal field declarations\n * @returns `TransferSerializer` that handles Date→string conversion and property stripping\n *\n * @example\n * ```typescript\n * import { temporalFieldRegistry } from './generated/transfers/_registry';\n *\n * const api = createJudoRestApi({\n * // ...\n * transferSerializer: createModelAwareSerializer(temporalFieldRegistry),\n * });\n * ```\n */\nexport function createModelAwareSerializer(registry: TemporalFieldRegistry): TransferSerializer {\n\treturn {\n\t\tserialize(transfer: unknown): unknown {\n\t\t\tif (transfer == null) return transfer;\n\t\t\tif (typeof transfer !== \"object\") return transfer;\n\t\t\tif (Array.isArray(transfer)) return transfer.map((item) => this.serialize(item));\n\n\t\t\tconst obj = transfer as Record<string, unknown>;\n\t\t\tconst entityType = obj.__entityType as string | undefined;\n\t\t\tconst temporalFields = entityType ? registry[entityType] : undefined;\n\t\t\tconst result: Record<string, unknown> = {};\n\n\t\t\tfor (const [key, value] of Object.entries(obj)) {\n\t\t\t\tif (isInternalProperty(key)) continue;\n\n\t\t\t\tif (value instanceof Date) {\n\t\t\t\t\tconst fieldType = temporalFields?.[key];\n\t\t\t\t\tresult[key] = fieldType ? serializeTemporalValue(value, fieldType) : value.toISOString();\n\t\t\t\t} else if (value != null && typeof value === \"object\") {\n\t\t\t\t\tresult[key] = this.serialize(value);\n\t\t\t\t} else {\n\t\t\t\t\tresult[key] = value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t},\n\t};\n}\n","/**\n * Model-aware transfer deserializer for JUDO REST API.\n *\n * Converts temporal field values from their wire format (ISO strings) to\n * native JavaScript `Date` objects at the API boundary. This eliminates\n * the need for developers to handle date parsing, timezone conversion,\n * and format differences.\n *\n * ## Supported conversions\n *\n * | Field type | Wire format (string) | Runtime type |\n * | ------------- | -------------------------------- | ------------------------- |\n * | `date` | `\"YYYY-MM-DD\"` | `Date` (local midnight) |\n * | `timestamp` | `\"YYYY-MM-DDTHH:mm:ss[.SSS]Z\"` | `Date` (UTC) |\n * | `time` | `\"HH:mm[:ss]\"` | `string` (pass-through) |\n *\n * ## How it works\n *\n * The deserializer reads `__entityType` from each response payload to look up\n * the transfer type in the provided {@link TemporalFieldRegistry}. Fields\n * declared as `date` or `timestamp` are converted from ISO strings to `Date`\n * objects. Nested objects and arrays are processed recursively.\n */\n\nimport type { TemporalFieldRegistry, TemporalFieldType, TransferDeserializer } from \"./types\";\n\n/**\n * Parse a date-only string (`YYYY-MM-DD`) as a local-timezone `Date`.\n *\n * Avoids the timezone-shift problem of `new Date(\"YYYY-MM-DD\")` which creates\n * a UTC midnight `Date` — displaying as the previous day in negative-offset timezones.\n *\n * @param value - Date string in `YYYY-MM-DD` format\n * @returns `Date` at local midnight, or invalid `Date` if parsing fails\n */\nexport function parseLocalDate(value: string): Date {\n\tconst parts = value.split(\"-\");\n\tif (parts.length !== 3) return new Date(Number.NaN);\n\tconst [y, m, d] = parts.map(Number);\n\treturn new Date(y, m - 1, d);\n}\n\n/**\n * Deserialize a temporal string value to its runtime representation.\n *\n * - `date` → local-midnight `Date` via {@link parseLocalDate}\n * - `timestamp` → `Date` via `new Date(isoString)`\n * - `time` → original string (pass-through)\n *\n * @param value - The string value from the API response\n * @param fieldType - The temporal field type\n * @returns `Date` for `date`/`timestamp`, original string for `time`\n */\nexport function deserializeTemporalValue(value: string, fieldType: TemporalFieldType): Date | string {\n\tswitch (fieldType) {\n\t\tcase \"date\":\n\t\t\treturn parseLocalDate(value);\n\t\tcase \"timestamp\":\n\t\t\treturn new Date(value);\n\t\tcase \"time\":\n\t\t\treturn value;\n\t}\n}\n\n/**\n * Create a model-aware transfer deserializer that converts temporal fields\n * from ISO strings to native `Date` objects.\n *\n * Uses `__entityType` in the response payload to look up the transfer type\n * in the provided registry and convert matching fields. Nested objects and\n * arrays are processed recursively.\n *\n * @param registry - Mapping of entity type FQNs to temporal field declarations\n * @returns `TransferDeserializer` that converts `date`/`timestamp` strings to `Date`\n *\n * @example\n * ```typescript\n * import { temporalFieldRegistry } from './generated/transfers/_registry';\n *\n * const api = createJudoRestApi({\n * // ...\n * transferDeserializer: createModelAwareDeserializer(temporalFieldRegistry),\n * });\n * ```\n */\nexport function createModelAwareDeserializer(registry: TemporalFieldRegistry): TransferDeserializer {\n\treturn {\n\t\tdeserialize(data: unknown): unknown {\n\t\t\tif (data == null || typeof data !== \"object\") return data;\n\n\t\t\tif (Array.isArray(data)) {\n\t\t\t\treturn data.map((item) => this.deserialize(item));\n\t\t\t}\n\n\t\t\tconst obj = data as Record<string, unknown>;\n\t\t\tconst entityType = obj.__entityType as string | undefined;\n\t\t\tconst temporalFields = entityType ? registry[entityType] : undefined;\n\n\t\t\tconst result = { ...obj };\n\n\t\t\t// Recurse into nested objects and arrays\n\t\t\tfor (const [key, value] of Object.entries(result)) {\n\t\t\t\tif (value != null && typeof value === \"object\") {\n\t\t\t\t\tresult[key] = this.deserialize(value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Convert temporal fields for this object\n\t\t\tif (temporalFields) {\n\t\t\t\tfor (const [field, fieldType] of Object.entries(temporalFields)) {\n\t\t\t\t\tconst value = result[field];\n\t\t\t\t\tif (typeof value === \"string\") {\n\t\t\t\t\t\tresult[field] = deserializeTemporalValue(value, fieldType);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;GAwHG,IAAI;CACN,MAAM;CACN,QAAQ;CACR,KAAK;CACL,OAAO;CACP,KAAK;CACL,QAAQ;CACR,OAAO;CACP,iBAAiB;CACjB,UAAU;CACV,QAAQ;CACR,iBAAiB;CACjB,QAAQ;CACR,SAAS;CACT,QAAQ;AACT,GAc0L,IAAI,OAAO,IAAI,8BAA8B,GChJ1N,MAAyB,MAG9B,OAAO,MAAsD;CAEnE,IAAI,EAAQ,aAAa;EACxB,EAAQ,YAAY;EACpB;CACD;CAEA,EAAQ,WAAY,OAAO;AAC5B;AAED,EAAqB,aAAa;AAKlC,IAAa,MAA6B,MAGlC,OAAO,MAAsD;CACnE,IAAM,IAAa,EAAO;CAC1B,IAAI,CAAC,GACJ,MAAU,MAAM,2CAA2C;CAG5D,IAAI,CAAC,EAAQ,YACZ,MAAU,MAAM,iCAAiC;CAKlD,IAAM,IAAe;CAMrB,EAAQ,WAAW,WAAW,GA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AAO,AAAqB,OAAO,KAAU,YAAlC,IACV,EAAO,KAAO,KAAK,UAAU,CAAK,IAElC,EAAO,KAAO;EAIhB,OAAO;CACR,EACD;AACD;;;ACjLA,SAAgB,GAAe,GAAqB;CACnD,IAAM,IAAQ,EAAM,MAAM,GAAG;CAC7B,IAAI,EAAM,WAAW,GAAG,uBAAO,IAAI,KAAK,GAAU;CAClD,IAAM,CAAC,GAAG,GAAG,KAAK,EAAM,IAAI,MAAM;CAClC,OAAO,IAAI,KAAK,GAAG,IAAI,GAAG,CAAC;AAC5B;AAaA,SAAgB,GAAyB,GAAe,GAA6C;CACpG,QAAQ,GAAR;EACC,KAAK,QACJ,OAAO,GAAe,CAAK;EAC5B,KAAK,aACJ,OAAO,IAAI,KAAK,CAAK;EACtB,KAAK,QACJ,OAAO;CACT;AACD;AAuBA,SAAgB,GAA6B,GAAuD;CACnG,OAAO,EACN,YAAY,GAAwB;EACnC,IAAoB,OAAO,KAAS,aAAhC,GAA0C,OAAO;EAErD,IAAI,MAAM,QAAQ,CAAI,GACrB,OAAO,EAAK,KAAK,MAAS,KAAK,YAAY,CAAI,CAAC;EAGjD,IAAM,IAAM,GACN,IAAa,EAAI,cACjB,IAAiB,IAAa,EAAS,KAAc,KAAA,GAErD,IAAS,EAAE,GAAG,EAAI;EAGxB,KAAK,IAAM,CAAC,GAAK,MAAU,OAAO,QAAQ,CAAM,GAC/C,AAAqB,OAAO,KAAU,YAAlC,MACH,EAAO,KAAO,KAAK,YAAY,CAAK;EAKtC,IAAI,GACH,KAAK,IAAM,CAAC,GAAO,MAAc,OAAO,QAAQ,CAAc,GAAG;GAChE,IAAM,IAAQ,EAAO;GACrB,AAAI,OAAO,KAAU,aACpB,EAAO,KAAS,GAAyB,GAAO,CAAS;EAE3D;EAGD,OAAO;CACR,EACD;AACD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["getRelation","selectorContext","forEachVisualElement","boundElementName","isRangeInput","isValidationError","relation","callbackContext","RelationBehaviourType","eagerContext","getRelation","resolveTransferId","targetId","getRelation","filterContext","typeSimpleName","inlineContext","callbackContext","selectorContext","isRelationType","_jsx","hasActionHandler","checkHandler","checkHandler","typeSimpleName","typeSimpleName","modelTypeName","typeSimpleName","createContext","useCallback","useContext","useMemo","jsx","__defProp","__exportAll","all","flags","target","name","S","A","j","M","N","P","F","I","L","R","z","B","V","H","X","Z","re","openTargetPage","context","navigation","targetPage","useBackActionHandler","_action","useOpenPageActionHandler","action","useRowOpenPageActionHandler","useCancelActionHandler","useOpenFormActionHandler","useOpenCreateFormActionHandler","relation","isEager","ownerTransfer","eagerContext","data","useOpenOperationInputFormActionHandler","formForAction","refreshPage","isEditMode","result","getRelation$3","relationContext","ownerDataElement","useOpenSelectorActionHandler","useOpenAddSelectorActionHandler","selectorContext","useOpenSetSelectorActionHandler","useOpenOperationInputSelectorActionHandler","useSelectorRangeActionHandler","targetType","onRangeRequest","api","onRangeResult","response","types_exports","ValidationError","relationItems","owner","relationName","value","feedbackItems","firstError","f","errors","item","HEADER_SIGNED_IDENTIFIER","HEADER_MASK","HEADER_MARK_SELECTED_RANGE_ITEMS","HEADER_COUNT_RECORDS","HEADER_COUNT","HEADER_TOKEN","DEFAULT_COMMAND_MASK","SUFFIX_TEMPLATE","SUFFIX_GET","SUFFIX_UPDATE","SUFFIX_VALIDATE","SUFFIX_DELETE","SUFFIX_LIST","SUFFIX_RANGE","SUFFIX_CREATE","SUFFIX_SET","SUFFIX_UNSET","SUFFIX_ADD","SUFFIX_REMOVE","SUFFIX_EXPORT","SUFFIX_UPLOAD_TOKEN","SUFFIX_PRINCIPAL","SUFFIX_META","maybeInterceptError","error","interceptor","options","payload","dataPath","handleCrudError","transferId","DEFAULT_VALIDATION_FAILED_MESSAGE","DEFAULT_VALIDATION_MESSAGES","isValidationFailureCode","code","validationMessage","values","translated","faultMessage","defaultValue","t","toValidationMessages","items","messages","relations","message","split","part","key","list","reportValidationError","validation","notifications","translate","passesLocalValidation","container","requiredBy","rangeInputs","element","field","flag","missing","isValidationError$1","resolveTargetClassType","explicit","page","dataElement","isPagedItems","isTransferDirty","state","isAccessRelationListAction","transfer","isEntityRelationListAction","useRefreshActionHandler","callbackContext","pageTransferId","rowsPerPage","actionQueryCustomizer","countRecords","isCollection","tableEntityId","onListRelation","tableData","totalCountHeader","totalCount","single","listData","rangeData","operationType","ownerClassType","isEagerReadFromServer","parentTransferId","parentData","relationValue","fullEntity","itemTempId","entityTempId","onRefresh","refreshedEntity","useCreateActionHandler","stored","pageType","isPageAction","createDialog","onCreate","onValidateCreate","relationMetadata","dialogOwnerEntity","createdEntity","hasValidateCreateBehaviour","validationError","fieldErrors","tempId","eagerParentEntityId","eagerRelationName","currentValue","newItems","createError","shouldAutoOpen","viewPage","closesOnSave","definition","useUpdateActionHandler","contextEntity","rawEntityId","updatedItems","onUpdate","updatedEntity","useDeleteActionHandler","targetId","targetSigned","isTarget","onDelete","useBulkDeleteActionHandler","selectedRows","onBulkDelete","transferIds","row","deletePromises","rowId","useRowDeleteActionHandler","createRowDeleteHandler","onRowDelete","useGetTemplateActionHandler","onGetTemplate","template","getRelation$2","useSetActionHandler","selectedEntity","onSet","ownerId","selectedId","useUnsetActionHandler","onUnset","useAddActionHandler","addContext","selectedEntities","onAdd","currentItems","selectedIds","useRemoveActionHandler","createRemoveRowHandler","removeContext","onRemove","useBulkRemoveActionHandler","removeIds","itemId","onBulkRemove","entitiesToRemove","useClearActionHandler","onClear","useRefreshRelationActionHandler","onRefreshRelation","useFilterRelationActionHandler","filterContext","getRelation$1","useFilterActionHandler","useExportActionHandler","onExport","blob","url","a","useInlineCreateRowActionHandler","isJsonObject","operation_fault_exports","HttpError","status","bodyText","parseBody","text","OPERATION_FAULT_STATUS","getOperationFault","body","faultKey","isValidationError","hasStatus","statuses","handleOperationError","operationName","fault","openOperationOutputPage","operation","params","b","triggerPageRefresh","toOperationInfo","useCallOperationActionHandler","opDef","onCallOperation","ownerType","operationInfo","useBulkCallOperationActionHandler","onBulkCallOperation","operationPromises","useInputFormCallOperationActionHandler","inputFormContext","onInputFormCallOperation","inputData","useInputSelectorCallOperationActionHandler","onInputSelectorCallOperation","input","useParameterlessCallOperationActionHandler","onParameterlessCallOperation","getRelation","rangeQuery","searchText","callerQuery","useAutocompleteRangeActionHandler","onAutocompleteRange","results","queryCustomizer","useAutocompleteSetActionHandler","autocompleteContext","onAutocompleteSet","useAutocompleteAddActionHandler","onAutocompleteAdd","id","entitiesToAdd","usePreFetchActionHandler","classType","preFetchContext","useCustomActionHandler","customContext","ApiContext","useApi","ApiProvider","children","OperationFaultContext","useShowOperationFault","executeWithLifecycle","defaultHandler","overrides","baseContext","callDefault","lifecycleContext","BUILTIN_HANDLERS","getActionHandler","getTypedActionHandler","hasActionHandler$1","useActionDispatcher","registry","closeDialog","additionalContext","actionOverrides","showOperationFault","canHandle","contextOverrides","handlerHook","handlerFn","mergedContext","actionSourceId","lifecycle","useActionHandler","hasActionHandler","SPLITTER","TRANSFER_SKIP_SEGMENT","restPath","first","second","suffix","i","getPathForApp","application","path","tmp","rootPathForApp","app","getPathForActor","getRelationPath","getClassPath","getMutationRelationPath","isAccess","getOperationPath","JudoRestApi","config","headers","typeName","method","init","errorText","errorData","parseError","mask","selected","s","attributePath","file","token","formData","downloadToken","disposition","identifier","createJudoRestApi","BACKEND_PROPERTIES","FRONTEND_PROPERTIES","INTERNAL_PROPERTIES","isInternalProperty","serializeTemporalValue","date","fieldType","createModelAwareSerializer","relationTypes","obj","reported","candidates","entityType","candidate","temporalFields","parseLocalDate","parts","y","m","d","deserializeTemporalValue","createModelAwareDeserializer","TEMPORAL_DATA_TYPES","CLASS_TYPES","isClassType","buildRelationTypeMapFromModel","classTypes","byXmiId","map","targets","ref","targetName","buildTemporalFieldRegistryFromModel","declaredTypes","dataType","temporalTypeOf","fields","attribute","temporalType"],"sources":["../../model-api/dist/index.js","../src/handlers/navigation/navigation-handlers.ts","../src/handlers/form/form-handlers.ts","../src/handlers/selector/selector-handlers.ts","../src/api/types.ts","../src/api/constants.ts","../src/lifecycle/error-interceptor.ts","../src/handlers/validation-messages.ts","../src/handlers/validation-feedback.ts","../src/handlers/crud/crud-handlers.ts","../src/handlers/relation/relation-handlers.ts","../src/handlers/table/table-handlers.ts","../src/api/json-object.ts","../src/api/operation-fault.ts","../src/handlers/operation/operation-handlers.ts","../src/handlers/autocomplete/autocomplete-handlers.ts","../src/handlers/other/other-handlers.ts","../src/provider/api-context.tsx","../src/provider/operation-fault-context.tsx","../src/lifecycle/execute-with-lifecycle.ts","../src/registry/action-handler-registry.ts","../src/hooks/use-action-dispatcher.ts","../src/hooks/use-action-handler.ts","../src/api/path-builder.ts","../src/api/judo-rest-api.ts","../src/api/transfer-serializer.ts","../src/api/transfer-deserializer.ts","../src/api/model-type-maps.ts"],"sourcesContent":["// src/enums.ts\nvar e = {\n\tHORIZONTAL: \"HORIZONTAL\",\n\tVERTICAL: \"VERTICAL\"\n}, t = {\n\tNONE: \"NONE\",\n\tLOOSE: \"LOOSE\",\n\tTIGHT: \"TIGHT\"\n}, n = {\n\tNONE: \"NONE\",\n\tHORIZONTAL: \"HORIZONTAL\",\n\tVERTICAL: \"VERTICAL\",\n\tBOTH: \"BOTH\"\n}, r = {\n\tCENTER: \"CENTER\",\n\tEND: \"END\",\n\tSPACEAROUND: \"SPACEAROUND\",\n\tSPACEBETWEEN: \"SPACEBETWEEN\",\n\tSPACEEVENLY: \"SPACEEVENLY\",\n\tSTART: \"START\"\n}, i = {\n\tBASELINE: \"BASELINE\",\n\tCENTER: \"CENTER\",\n\tEND: \"END\",\n\tSTART: \"START\",\n\tSTRETCH: \"STRETCH\"\n}, a = {\n\tMIN: \"MIN\",\n\tMAX: \"MAX\"\n}, o = {\n\tTOP_LEFT: \"TOP_LEFT\",\n\tTOP_CENTER: \"TOP_CENTER\",\n\tTOP_RIGHT: \"TOP_RIGHT\",\n\tCENTER_LEFT: \"CENTER_LEFT\",\n\tCENTER: \"CENTER\",\n\tCENTER_RIGHT: \"CENTER_RIGHT\",\n\tBOTTOM_LEFT: \"BOTTOM_LEFT\",\n\tBOTTOM_CENTER: \"BOTTOM_CENTER\",\n\tBOTTOM_RIGHT: \"BOTTOM_RIGHT\"\n}, ee = {\n\tXS: \"XS\",\n\tSM: \"SM\",\n\tMD: \"MD\",\n\tLG: \"LG\",\n\tXL: \"XL\"\n}, s = {\n\tTABLE: \"TABLE\",\n\tFORM: \"FORM\",\n\tVIEW: \"VIEW\"\n}, c = {\n\tCONTAINED: \"contained\",\n\tTEXT: \"text\",\n\tOUTLINED: \"outlined\"\n}, l = {\n\tNONE: \"NONE\",\n\tCONDITIONAL: \"CONDITIONAL\",\n\tMANDATORY: \"MANDATORY\"\n}, u = {\n\tNONE: \"NONE\",\n\tASC: \"ASC\",\n\tDESC: \"DESC\"\n}, d = {\n\tEQUAL: \"EQUAL\",\n\tNOT_EQUAL: \"NOT_EQUAL\",\n\tIS_EMPTY: \"IS_EMPTY\",\n\tIS_NOT_EMPTY: \"IS_NOT_EMPTY\",\n\tLESS: \"LESS\",\n\tLESS_OR_EQUAL: \"LESS_OR_EQUAL\",\n\tGREATER: \"GREATER\",\n\tGREATER_OR_EQUAL: \"GREATER_OR_EQUAL\",\n\tLIKE: \"LIKE\"\n}, f = {\n\tAUTO: \"AUTO\",\n\tENABLED: \"ENABLED\",\n\tDISABLED: \"DISABLED\"\n}, p = {\n\tTABLE: \"TABLE\",\n\tTAG: \"TAG\",\n\tCARD: \"CARD\"\n}, m = {\n\tVERTICAL: \"VERTICAL\",\n\tHORIZONTAL: \"HORIZONTAL\"\n}, h = {\n\tHORIZONTAL: \"HORIZONTAL\",\n\tVERTICAL: \"VERTICAL\"\n}, g = {\n\tNANOSECOND: \"NANOSECOND\",\n\tMICROSECOND: \"MICROSECOND\",\n\tMILLISECOND: \"MILLISECOND\",\n\tSECOND: \"SECOND\",\n\tMINUTE: \"MINUTE\",\n\tHOUR: \"HOUR\",\n\tDAY: \"DAY\",\n\tWEEK: \"WEEK\",\n\tMONTH: \"MONTH\",\n\tYEAR: \"YEAR\"\n}, _ = {\n\tTOP: \"TOP\",\n\tBOTTOM: \"BOTTOM\",\n\tSTART: \"START\",\n\tEND: \"END\",\n\tDEFAULT: \"DEFAULT\"\n}, v = {\n\tLABEL: \"LABEL\",\n\tATTRIBUTE: \"ATTRIBUTE\"\n}, y = {\n\tUNDEFINED: \"UNDEFINED\",\n\tEMAIL: \"EMAIL\",\n\tUSERNAME: \"USERNAME\"\n}, b = {\n\tASSOCIATION: \"ASSOCIATION\",\n\tCOMPOSITION: \"COMPOSITION\",\n\tAGGREGATION: \"AGGREGATION\",\n\tSTATIC: \"STATIC\"\n}, x = {\n\tSTORED: \"STORED\",\n\tDERIVED: \"DERIVED\",\n\tMAPPED: \"MAPPED\",\n\tTRANSIENT: \"TRANSIENT\",\n\tACCESS: \"ACCESS\"\n}, S = {\n\tLIST: \"LIST\",\n\tCREATE: \"CREATE\",\n\tSET: \"SET\",\n\tUNSET: \"UNSET\",\n\tADD: \"ADD\",\n\tREMOVE: \"REMOVE\",\n\tRANGE: \"RANGE\",\n\tVALIDATE_CREATE: \"VALIDATE_CREATE\",\n\tTEMPLATE: \"TEMPLATE\",\n\tUPDATE: \"UPDATE\",\n\tVALIDATE_UPDATE: \"VALIDATE_UPDATE\",\n\tDELETE: \"DELETE\",\n\tREFRESH: \"REFRESH\",\n\tEXPORT: \"EXPORT\"\n}, C = {\n\tREFRESH: \"REFRESH\",\n\tUPDATE: \"UPDATE\",\n\tVALIDATE_UPDATE: \"VALIDATE_UPDATE\",\n\tDELETE: \"DELETE\",\n\tTEMPLATE: \"TEMPLATE\"\n}, w = {\n\tMAPPED: \"MAPPED\",\n\tSTATIC: \"STATIC\"\n}, T = {\n\tREFRESH: \"REFRESH\",\n\tUPDATE: \"UPDATE\",\n\tDELETE: \"DELETE\",\n\tVALIDATE_INPUT: \"VALIDATE_INPUT\"\n}, E = {\n\tBackActionDefinition: \"BackActionDefinition\",\n\tOpenPageActionDefinition: \"OpenPageActionDefinition\",\n\tRowOpenPageActionDefinition: \"RowOpenPageActionDefinition\",\n\tOpenFormActionDefinition: \"OpenFormActionDefinition\",\n\tOpenCreateFormActionDefinition: \"OpenCreateFormActionDefinition\",\n\tOpenOperationInputFormActionDefinition: \"OpenOperationInputFormActionDefinition\",\n\tOpenSelectorActionDefinition: \"OpenSelectorActionDefinition\",\n\tOpenAddSelectorActionDefinition: \"OpenAddSelectorActionDefinition\",\n\tOpenSetSelectorActionDefinition: \"OpenSetSelectorActionDefinition\",\n\tOpenOperationInputSelectorActionDefinition: \"OpenOperationInputSelectorActionDefinition\",\n\tSelectorRangeActionDefinition: \"SelectorRangeActionDefinition\",\n\tRefreshActionDefinition: \"RefreshActionDefinition\",\n\tCreateActionDefinition: \"CreateActionDefinition\",\n\tUpdateActionDefinition: \"UpdateActionDefinition\",\n\tDeleteActionDefinition: \"DeleteActionDefinition\",\n\tBulkDeleteActionDefinition: \"BulkDeleteActionDefinition\",\n\tRowDeleteActionDefinition: \"RowDeleteActionDefinition\",\n\tGetTemplateActionDefinition: \"GetTemplateActionDefinition\",\n\tSetActionDefinition: \"SetActionDefinition\",\n\tUnsetActionDefinition: \"UnsetActionDefinition\",\n\tAddActionDefinition: \"AddActionDefinition\",\n\tRemoveActionDefinition: \"RemoveActionDefinition\",\n\tBulkRemoveActionDefinition: \"BulkRemoveActionDefinition\",\n\tClearActionDefinition: \"ClearActionDefinition\",\n\tRefreshRelationActionDefinition: \"RefreshRelationActionDefinition\",\n\tFilterRelationActionDefinition: \"FilterRelationActionDefinition\",\n\tFilterActionDefinition: \"FilterActionDefinition\",\n\tExportActionDefinition: \"ExportActionDefinition\",\n\tInlineCreateRowActionDefinition: \"InlineCreateRowActionDefinition\",\n\tCallOperationActionDefinition: \"CallOperationActionDefinition\",\n\tBulkCallOperationActionDefinition: \"BulkCallOperationActionDefinition\",\n\tInputFormCallOperationActionDefinition: \"InputFormCallOperationActionDefinition\",\n\tInputSelectorCallOperationActionDefinition: \"InputSelectorCallOperationActionDefinition\",\n\tParameterlessCallOperationActionDefinition: \"ParameterlessCallOperationActionDefinition\",\n\tAutocompleteRangeActionDefinition: \"AutocompleteRangeActionDefinition\",\n\tAutocompleteSetActionDefinition: \"AutocompleteSetActionDefinition\",\n\tAutocompleteAddActionDefinition: \"AutocompleteAddActionDefinition\",\n\tPreFetchActionDefinition: \"PreFetchActionDefinition\",\n\tCancelActionDefinition: \"CancelActionDefinition\",\n\tCustomActionDefinition: \"CustomActionDefinition\"\n};\n// src/structural/action-type.ts\nfunction D(e) {\n\treturn Object.hasOwn(E, e);\n}\nvar O = \"ui:\";\nfunction k(e) {\n\tlet t = e?.actionDefinition?.[\"@type\"];\n\tif (t == null) return;\n\tlet n = t.startsWith(O) ? t.slice(3) : t;\n\tif (D(n)) return n;\n}\n// src/data/transfer-identity.ts\nfunction A(e, t) {\n\tlet n = e?.__signedIdentifier ?? e?.__identifier ?? e?.__tempId ?? (e?.id == null ? void 0 : String(e.id));\n\treturn n === void 0 ? t === void 0 ? void 0 : `idx-${t}` : n;\n}\n// src/data/element-guards.ts\nvar j = /* @__PURE__ */ new Set([\"RelationType\", \"data:RelationType\"]);\nfunction M(e) {\n\treturn typeof e == \"object\" && !!e && \"@type\" in e && typeof e[\"@type\"] == \"string\" && j.has(e[\"@type\"]);\n}\nvar N = /* @__PURE__ */ new Set([\"AttributeType\", \"data:AttributeType\"]);\nfunction P(e) {\n\treturn typeof e == \"object\" && !!e && \"@type\" in e && typeof e[\"@type\"] == \"string\" && N.has(e[\"@type\"]);\n}\nvar F = /* @__PURE__ */ new Set([\n\t\"NumericInput\",\n\t\"DateInput\",\n\t\"DateTimeInput\",\n\t\"TimeInput\"\n]);\nfunction I(e) {\n\treturn F.has(e[\"@type\"]);\n}\nfunction L(e) {\n\treturn \"children\" in e && Array.isArray(e.children);\n}\nfunction R(e) {\n\treturn e[\"@type\"] === \"TabController\";\n}\nfunction z(e, t) {\n\tif (t(e), L(e)) for (let n of e.children) z(n, t);\n\tif (R(e)) for (let n of e.tabs) z(n.element, t);\n}\nfunction B(e) {\n\treturn \"attributeType\" in e && P(e.attributeType);\n}\nfunction V(e) {\n\treturn \"dataElement\" in e && typeof e.dataElement == \"object\" && e.dataElement !== null && \"name\" in e.dataElement && typeof e.dataElement.name == \"string\";\n}\nfunction H(e) {\n\tlet t = B(e) ? e.attributeType.name : V(e) && e.dataElement.name;\n\tif (t) return t;\n}\nfunction U(e) {\n\treturn I(e) ? {\n\t\tminValueBy: e.minValueBy,\n\t\tmaxValueBy: e.maxValueBy\n\t} : {};\n}\nvar W = /* @__PURE__ */ new Set([\"ClassType\", \"data:ClassType\"]);\nfunction G(e) {\n\treturn typeof e == \"object\" && !!e && \"@type\" in e && typeof e[\"@type\"] == \"string\" && W.has(e[\"@type\"]);\n}\nvar K = /* @__PURE__ */ new Set([\"EnumerationType\", \"data:EnumerationType\"]);\nfunction q(e) {\n\treturn typeof e == \"object\" && !!e && \"@type\" in e && typeof e[\"@type\"] == \"string\" && K.has(e[\"@type\"]);\n}\nvar J = /* @__PURE__ */ new Set([\"OperationType\", \"data:OperationType\"]);\nfunction Y(e) {\n\treturn typeof e == \"object\" && !!e && \"@type\" in e && typeof e[\"@type\"] == \"string\" && J.has(e[\"@type\"]);\n}\n// src/data/type-name.ts\nfunction X(e) {\n\treturn e?.simpleName ?? e?.name;\n}\nfunction Z(e) {\n\treturn e.replaceAll(\".\", \"::\");\n}\n// src/services.ts\nvar Q = Symbol.for(\"@judo/MODEL_LOADER_SERVICE\"), $ = Symbol.for(\"@judo/MODEL_REGISTRY_SERVICE\"), te = Symbol.for(\"@judo/NAVIGATION_BADGE_SERVICE\"), ne = Symbol.for(\"@judo/THEME_SERVICE\"), re = Symbol.for(\"@judo/ACTION_HANDLER_FACTORY\"), ie = Symbol.for(\"@judo/COMPONENT_OVERRIDE\"), ae = Symbol.for(\"@judo/COMPONENT_OVERRIDE_SERVICE\"), oe = Symbol.for(\"@judo/NOTIFICATION_SERVICE\"), se = Symbol.for(\"@judo/DIALOG_SERVICE\"), ce = Symbol.for(\"@judo/UNSAVED_CHANGES_GUARD\"), le = Symbol.for(\"@judo/SESSION_TIMEOUT_GUARD\"), ue = Symbol.for(\"@judo/LOADING_SERVICE\"), de = Symbol.for(\"@judo/I18N_SERVICE\");\nexport { re as ACTION_HANDLER_FACTORY, E as ActionDefinitionType, o as Alignment, e as Axis, c as ButtonStyle, ie as COMPONENT_OVERRIDE, ae as COMPONENT_OVERRIDE_SERVICE, f as CheckboxSelection, y as ClaimType, C as ClassBehaviourType, l as ConfirmationType, i as CrossAxisAlignment, se as DIALOG_SERVICE, ee as DialogSize, g as DurationUnit, d as FilterOperationType, t as Fit, de as I18N_SERVICE, ue as LOADING_SERVICE, Q as MODEL_LOADER_SERVICE, $ as MODEL_REGISTRY_SERVICE, r as MainAxisAlignment, a as MainAxisSize, x as MemberType, m as MenuLayout, te as NAVIGATION_BADGE_SERVICE, oe as NOTIFICATION_SERVICE, T as OperationTargetBehaviourType, w as OperationTypeEnum, s as PageContainerType, _ as Placement, S as RelationBehaviourType, b as RelationKind, le as SESSION_TIMEOUT_GUARD, u as Sort, n as Stretch, ne as THEME_SERVICE, h as TabOrientation, p as TableRepresentation, v as TitleFrom, ce as UNSAVED_CHANGES_GUARD, k as actionTypeOf, H as boundElementName, z as forEachVisualElement, B as hasAttributeType, V as hasDataElement, D as isActionDefinitionType, P as isAttributeType, G as isClassType, L as isContainer, q as isEnumerationType, Y as isOperationType, I as isRangeInput, M as isRelationType, R as isTabController, Z as modelTypeName, A as resolveTransferId, X as typeSimpleName, U as valueBounds };\n","import type { Action, ActionHandlerHookWithMeta, NavigationContext, TypedActionHandlerContext } from \"../../types\";\n\n/**\n * Open the target page. An eager row is opened as a draft (`isEager`): its dialog\n * stages the edit into the owner. Otherwise a dialog page with an `onDialogClose`\n * caller is opened through `openDialog`, so the caller hears about the close, like\n * React's `await open...Page(...); await refresh();`. A draft forwards its owner\n * (`parentTransferId`, `relationName`), so the dialog saves into it with no REST call.\n */\nfunction openTargetPage(\n\tcontext: TypedActionHandlerContext,\n\tnavigation: NavigationContext,\n\ttargetPage: NonNullable<Action[\"targetPageDefinition\"]>\n): void {\n\tif (context.isEager) {\n\t\tnavigation.navigateTo(targetPage, {\n\t\t\ttransfer: context.transfer,\n\t\t\tisEager: true,\n\t\t\tparentTransferId: context.parentTransferId,\n\t\t\trelationName: context.relationName,\n\t\t});\n\t\treturn;\n\t}\n\tif (targetPage.openInDialog && context.onDialogClose) {\n\t\tnavigation.openDialog(targetPage, { transfer: context.transfer }, context.onDialogClose);\n\t\treturn;\n\t}\n\tnavigation.navigateTo(targetPage, { transfer: context.transfer });\n}\n\n/**\n * Handle back navigation - hook factory.\n */\nexport const useBackActionHandler = ((_action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Close dialog if open\n\t\tif (context.closeDialog) {\n\t\t\tcontext.closeDialog();\n\t\t\treturn;\n\t\t}\n\t\t// Otherwise navigate back\n\t\tcontext.navigation!.goBack();\n\t};\n}) as ActionHandlerHookWithMeta;\nuseBackActionHandler.actionType = \"BackActionDefinition\";\n\n/**\n * Handle page navigation - hook factory.\n */\nexport const useOpenPageActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenPageAction\");\n\t\t}\n\n\t\tif (!context.navigation) {\n\t\t\tthrow new Error(\"Navigation context is undefined\");\n\t\t}\n\n\t\topenTargetPage(context, context.navigation, targetPage);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenPageActionHandler.actionType = \"OpenPageActionDefinition\";\n\n/**\n * Handle row-based page navigation (from table row) - hook factory.\n */\nexport const useRowOpenPageActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for RowOpenPageAction\");\n\t\t}\n\n\t\tif (!context.navigation) {\n\t\t\tthrow new Error(\"Navigation context is undefined\");\n\t\t}\n\n\t\t// Navigate with row transfer\n\t\topenTargetPage(context, context.navigation, targetPage);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseRowOpenPageActionHandler.actionType = \"RowOpenPageActionDefinition\";\n\n/**\n * Handle cancel action (close dialog or go back) - hook factory.\n *\n * Behavior depends on context:\n * - In a dialog: closes the dialog\n * - On a VIEW page with edits: resets transfer to original data (no navigation)\n * - Otherwise: navigates back\n */\nexport const useCancelActionHandler = ((_action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// React CancelAction: `setValidation(new Map())` before anything else\n\t\tcontext.validation?.clearErrors();\n\n\t\t// Close dialog if open\n\t\tif (context.closeDialog) {\n\t\t\tcontext.closeDialog();\n\t\t\treturn;\n\t\t}\n\n\t\t// On VIEW pages with edits, reset transfer data instead of navigating\n\t\tif (context.pageType === \"VIEW\" && context.isEditMode && context.data && context.transfer?.__identifier) {\n\t\t\tcontext.data.resetTransfer(context.transfer.__identifier);\n\t\t\treturn;\n\t\t}\n\n\t\t// Otherwise navigate back\n\t\tcontext.navigation!.goBack();\n\t};\n}) as ActionHandlerHookWithMeta;\nuseCancelActionHandler.actionType = \"CancelActionDefinition\";\n","import type { OpenOperationInputFormActionDefinition as OpenOpInputFormDef, RelationType } from \"@judo/model-api\";\nimport type { Action, ActionHandlerHookWithMeta, TransferData, TypedActionHandlerContext } from \"../../types\";\n\n/**\n * Handle form open for editing - hook factory.\n */\nexport const useOpenFormActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenFormAction\");\n\t\t}\n\n\t\t// Open form dialog with transfer\n\t\tcontext.navigation!.openDialog(targetPage, {\n\t\t\ttransfer: context.transfer,\n\t\t});\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenFormActionHandler.actionType = \"OpenFormActionDefinition\";\n\n/**\n * Handle form open for create - hook factory.\n *\n * Creates a dialog for creating new transfers. The behavior depends on the source component:\n *\n * **Eager Components** (tables/links with isEager=true):\n * - Dialog submission returns data to the caller\n * - Caller (table/link) adds transfer to local __items array\n * - No REST call until parent transfer is saved\n * - onSubmitCreate callback is provided in dialog params\n *\n * **Lazy Components** (default):\n * - Dialog submission calls validateCreateRelation API\n * - If validation passes, calls createRelation API\n * - If validation fails, displays field errors and stays open\n * - After successful create, caller is notified via onDialogClose callback\n */\nexport const useOpenCreateFormActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenCreateFormAction\");\n\t\t}\n\n\t\t// Get relation from action (ownerDataElement is the RelationType for the target)\n\t\tconst relation = action.ownerDataElement as RelationType | undefined;\n\n\t\t// Determine if this is an eager (aggregated) creation\n\t\tconst isEager = context.isEager === true;\n\n\t\t// Get owner transfer for non-access relations\n\t\tconst ownerTransfer = context.transfer;\n\n\t\t// Get parent context for eager tables (where to add the created transfer)\n\t\tconst eagerContext = context as {\n\t\t\tparentTransferId?: string;\n\t\t\trelationName?: string;\n\t\t\tonDialogClose?: (result?: unknown) => void;\n\t\t};\n\n\t\t// Open create form dialog with necessary context\n\t\t// Pass onDialogClose callback so caller can refresh after successful create\n\t\tcontext.navigation!.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\tisCreate: true,\n\t\t\t\tisEager,\n\t\t\t\t// Relation context for API calls\n\t\t\t\trelation,\n\t\t\t\townerTransfer,\n\t\t\t\t// For eager mode, provide parent context so CreateActionHandler knows where to add the transfer\n\t\t\t\t...(isEager && {\n\t\t\t\t\tparentTransferId: eagerContext.parentTransferId,\n\t\t\t\t\trelationName: eagerContext.relationName,\n\t\t\t\t\tonSubmitCreate: async (data: TransferData) => {\n\t\t\t\t\t\t// In eager mode, the create action handler will add to local store\n\t\t\t\t\t\t// This callback is handled by the CreateActionHandler\n\t\t\t\t\t\treturn data;\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t},\n\t\t\teagerContext.onDialogClose\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenCreateFormActionHandler.actionType = \"OpenCreateFormActionDefinition\";\n\n/**\n * Handle form open for operation input - hook factory.\n */\nexport const useOpenOperationInputFormActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenOperationInputFormAction\");\n\t\t}\n\n\t\t// Cast to access formFor.operation if needed\n\t\tconst formDef = action.actionDefinition as OpenOpInputFormDef;\n\t\tconst formForAction = formDef.formFor as { operation?: unknown } | undefined;\n\n\t\t// Capture the caller page's refreshPage callback and edit mode state, the\n\t\t// same way the operation input *selector* does. The operation itself is\n\t\t// invoked from inside the dialog, whose handler context does not carry the\n\t\t// caller's refreshPage — so without this the caller keeps showing the\n\t\t// pre-operation data.\n\t\tconst { refreshPage, isEditMode } = context;\n\n\t\t// Open operation input form dialog\n\t\tcontext.navigation!.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\ttransfer: context.transfer,\n\t\t\t\toperation: formForAction?.operation,\n\t\t\t\tisOperationInput: true,\n\t\t\t},\n\t\t\t(result) => {\n\t\t\t\tif (result?.type === \"submitted\" && !isEditMode) {\n\t\t\t\t\trefreshPage?.();\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenOperationInputFormActionHandler.actionType = \"OpenOperationInputFormActionDefinition\";\n","import type { ClassType, RelationType } from \"@judo/model-api\";\nimport type { IJudoRestApi } from \"../../api/i-judo-rest-api\";\nimport type { TransferStored } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext } from \"../../types\";\n\n// Interface for API context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Interface for relation context\ninterface RelationContext {\n\townerTransfer?: TransferStored;\n\townerClassType?: ClassType;\n\trelation?: RelationType;\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonRangeRequest?: (classType: ClassType) => void;\n}\n\n/**\n * Get RelationType from context.\n */\nfunction getRelation(relationContext: RelationContext, action: Action): RelationType | null {\n\tif (relationContext.relation) {\n\t\treturn relationContext.relation;\n\t}\n\t// Check if action has a relation in ownerDataElement\n\tconst ownerDataElement = action.ownerDataElement;\n\tif (ownerDataElement && ownerDataElement[\"@type\"] === \"RelationType\") {\n\t\treturn ownerDataElement as RelationType;\n\t}\n\treturn null;\n}\n\n/**\n * Handle selector open for single selection - hook factory.\n * Navigation action - no REST call.\n */\nexport const useOpenSelectorActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenSelectorAction\");\n\t\t}\n\n\t\tconst selectorContext = context as { onDialogClose?: (result?: unknown) => void };\n\n\t\tcontext.navigation?.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\townerTransfer: context.transfer,\n\t\t\t\tisSelector: true,\n\t\t\t\tselectionMode: \"single\",\n\t\t\t},\n\t\t\tselectorContext.onDialogClose\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenSelectorActionHandler.actionType = \"OpenSelectorActionDefinition\";\n\n/**\n * Handle selector open for add operation (multi-select) - hook factory.\n * Navigation action - no REST call.\n */\nexport const useOpenAddSelectorActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenAddSelectorAction\");\n\t\t}\n\n\t\tconst selectorContext: Pick<\n\t\t\tTypedActionHandlerContext,\n\t\t\t\"onDialogClose\" | \"isEager\" | \"parentTransferId\" | \"relationName\"\n\t\t> = context;\n\n\t\tcontext.navigation?.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\townerTransfer: context.transfer,\n\t\t\t\tisSelector: true,\n\t\t\t\tselectionMode: \"multiple\",\n\t\t\t\toperation: \"add\",\n\t\t\t\t...(selectorContext.isEager && {\n\t\t\t\t\tisEager: true,\n\t\t\t\t\tparentTransferId: selectorContext.parentTransferId,\n\t\t\t\t\trelationName: selectorContext.relationName,\n\t\t\t\t}),\n\t\t\t},\n\t\t\tselectorContext.onDialogClose\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenAddSelectorActionHandler.actionType = \"OpenAddSelectorActionDefinition\";\n\n/**\n * Handle selector open for set operation (single-select) - hook factory.\n * Navigation action - no REST call.\n */\nexport const useOpenSetSelectorActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenSetSelectorAction\");\n\t\t}\n\n\t\tconst selectorContext: Pick<\n\t\t\tTypedActionHandlerContext,\n\t\t\t\"onDialogClose\" | \"isEager\" | \"parentTransferId\" | \"relationName\"\n\t\t> = context;\n\n\t\tcontext.navigation?.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\townerTransfer: context.transfer,\n\t\t\t\tisSelector: true,\n\t\t\t\tselectionMode: \"single\",\n\t\t\t\toperation: \"set\",\n\t\t\t\t...(selectorContext.isEager && {\n\t\t\t\t\tisEager: true,\n\t\t\t\t\tparentTransferId: selectorContext.parentTransferId,\n\t\t\t\t\trelationName: selectorContext.relationName,\n\t\t\t\t}),\n\t\t\t},\n\t\t\tselectorContext.onDialogClose\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenSetSelectorActionHandler.actionType = \"OpenSetSelectorActionDefinition\";\n\n/**\n * Handle selector open for operation input - hook factory.\n * Navigation action - no REST call.\n * Registers an onClose callback to refresh the caller page after a\n * successful operation, but only when the caller is not in edit mode.\n */\nexport const useOpenOperationInputSelectorActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetPage = action.targetPageDefinition;\n\t\tif (!targetPage) {\n\t\t\tthrow new Error(\"No target page defined for OpenOperationInputSelectorAction\");\n\t\t}\n\n\t\t// Capture caller page's refreshPage callback and edit mode state.\n\t\t// These come from ViewContainerRenderer's additionalContext.\n\t\tconst { refreshPage, isEditMode } = context;\n\n\t\tcontext.navigation?.openDialog(\n\t\t\ttargetPage,\n\t\t\t{\n\t\t\t\townerTransfer: context.transfer,\n\t\t\t\tisSelector: true,\n\t\t\t\tisOperationInput: true,\n\t\t\t},\n\t\t\t(result) => {\n\t\t\t\t// Refresh caller page after successful operation, but only if not in edit mode\n\t\t\t\tif (result?.type === \"submitted\" && !isEditMode) {\n\t\t\t\t\trefreshPage?.();\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseOpenOperationInputSelectorActionHandler.actionType = \"OpenOperationInputSelectorActionDefinition\";\n\n/**\n * Handle selector range query (fetch data for selector) - hook factory.\n * Fetches range data for selector table via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useSelectorRangeActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type defined for SelectorRangeAction\");\n\t\t}\n\n\t\tconst selectorContext = context as unknown as ApiContext &\n\t\t\tRelationContext &\n\t\t\tLegacyCallbacks & {\n\t\t\t\tqueryCustomizer?: Record<string, unknown>;\n\t\t\t\tonRangeResult?: (results: TransferStored[]) => void;\n\t\t\t};\n\n\t\tconst { onRangeRequest, api, onRangeResult } = selectorContext;\n\n\t\t// Use legacy callback if provided\n\t\tif (onRangeRequest) {\n\t\t\tonRangeRequest(targetType);\n\t\t\treturn;\n\t\t}\n\n\t\t// Use API if available\n\t\tif (api) {\n\t\t\tconst relation = getRelation(selectorContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for selector range\");\n\t\t\t}\n\n\t\t\tconst response = await api.getRelationRange(\n\t\t\t\trelation,\n\t\t\t\tselectorContext.ownerTransfer,\n\t\t\t\tselectorContext.queryCustomizer\n\t\t\t);\n\n\t\t\t// Signal results to selector component\n\t\t\tonRangeResult?.(response.data);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseSelectorRangeActionHandler.actionType = \"SelectorRangeActionDefinition\";\n","/**\n * JUDO REST API types.\n * Based on REST_REQUEST_MAPPING_SPECIFICATION.md\n */\n\nimport type { TransferIdentity } from \"@judo/model-api\";\n\n// ============================================\n// HTTP/Response Types\n// ============================================\n\n/**\n * HTTP method types used in the REST layer.\n * GET is used for template retrieval, file downloads, metadata, principal.\n * POST is used for all other operations (CRUD, list, range, operations, validation).\n */\nexport type HttpMethod = \"GET\" | \"POST\";\n\n/**\n * Response type indicating how to handle the response body.\n */\nexport type ResponseType = \"json\" | \"blob\";\n\n/**\n * How to deserialize the response.\n * - single: Deserialize as a single transfer\n * - array: Deserialize as an array of transfers\n * - void: No deserialization needed (response is empty)\n * - nullable: Deserialize as single transfer or null\n */\nexport type DeserializationType = \"single\" | \"array\" | \"void\" | \"nullable\";\n\n/**\n * Service type categories.\n */\nexport type ServiceType = \"class\" | \"relation\" | \"access\";\n\n// ============================================\n// Serialization/Deserialization\n// ============================================\n\n/**\n * Configuration for deserializing the response.\n */\nexport interface ResponseDeserializerConfig {\n\t/** Type of deserialization to apply */\n\ttype: DeserializationType;\n\t/** Target class FQName for deserialization (if applicable) */\n\ttargetClassFqName?: string;\n\t/** Whether the target is a stored (persisted) transfer */\n\tisStored: boolean;\n}\n\n/**\n * Transfer serializer interface for transforming transfers before sending.\n * The input type is unknown to support any transfer type.\n */\nexport interface TransferSerializer {\n\t/**\n\t * Serialize an transfer for sending in request body.\n\t *\n\t * `typeName` names the transfer's type when the caller knows it. A transfer\n\t * that was never persisted carries no `__entityType` (a `~template` response is\n\t * `{}`), so without the hint its temporal attributes cannot be classified and\n\t * a date would be sent as a UTC instant.\n\t */\n\tserialize(transfer: unknown, typeName?: string): unknown;\n}\n\n/**\n * Transfer deserializer interface for transforming responses.\n * The output type is unknown to support any transfer type.\n */\nexport interface TransferDeserializer {\n\t/** Deserialize a response into an transfer */\n\tdeserialize(data: unknown): unknown;\n}\n\n// ============================================\n// Temporal Field Types\n// ============================================\n\n/**\n * Classification of temporal (date/time) field types.\n *\n * - `date`: Date-only value (`YYYY-MM-DD`) — converted to `Date` at local midnight\n * - `time`: Time-only value (`HH:mm[:ss]`) — kept as `string` (no `Date` conversion)\n * - `timestamp`: Full datetime with timezone (`YYYY-MM-DDTHH:mm:ss[.SSS]Z`) — converted to `Date`\n */\nexport type TemporalFieldType = \"date\" | \"time\" | \"timestamp\";\n\n/**\n * Registry mapping transfer type FQNs to their temporal field declarations.\n *\n * Keys match `__entityType` values from API responses (e.g., `\"Demo::OrderDTO\"`).\n * Values map field names to their temporal type for serialization/deserialization.\n *\n * @example\n * ```typescript\n * const registry: TemporalFieldRegistry = {\n * \"Demo::OrderDTO\": { orderDate: \"date\", createdAt: \"timestamp\" },\n * \"Demo::MissionDTO\": { startDate: \"date\", endDate: \"date\" },\n * };\n * ```\n */\nexport type TemporalFieldRegistry = Record<string, Record<string, TemporalFieldType>>;\n\n// ============================================\n// API Configuration\n// ============================================\n\n/**\n * Configuration for JUDO REST API client.\n */\nexport interface JudoRestApiConfig {\n\t/** Base URL for the API (e.g., http://localhost:8080) */\n\tbaseUrl: string;\n\t/** Application base path (e.g., /api) */\n\tbasePath: string;\n\t/** Application model name (e.g., edemokracia) */\n\tmodelName: string;\n\t/** Actor path (e.g., admin/Admin) */\n\tactorPath: string;\n\t/** Request timeout in milliseconds */\n\ttimeout?: number;\n\t/** Default headers to include in all requests */\n\tdefaultHeaders?: Record<string, string>;\n\t/** Optional custom fetch implementation */\n\tfetch?: typeof fetch;\n\t/** Optional request interceptor */\n\tonRequest?: (request: RequestInit) => RequestInit | Promise<RequestInit>;\n\t/** Optional response interceptor */\n\tonResponse?: (response: Response) => Response | Promise<Response>;\n\t/** Optional error handler */\n\tonError?: (error: Error) => void;\n\t/**\n\t * Optional transfer serializer for transforming transfers before sending.\n\t * If not provided, transfers are sent as-is (JSON.stringify).\n\t */\n\ttransferSerializer?: TransferSerializer;\n\t/**\n\t * Optional transfer deserializer for transforming responses.\n\t * If not provided, responses are used as-is (JSON.parse result).\n\t */\n\ttransferDeserializer?: TransferDeserializer;\n}\n\n/**\n * Query customizer for list/get operations.\n */\nexport interface QueryCustomizer {\n\t_mask?: string;\n\t_orderBy?: Array<{ attribute: string; descending?: boolean }>;\n\t/** Paging: `offset` for page-based tables and selectors, `lastItem` for seek paging. */\n\t_seek?: { limit?: number; offset?: number; lastItem?: unknown };\n\t_filter?: unknown;\n\t_identifier?: string;\n\t/** Filter criteria are sent at the top level, keyed by attribute name. */\n\t[filterField: string]: unknown;\n}\n\n/**\n * Base transfer data interface.\n *\n */\nexport interface TransferData {\n\t[key: string]: unknown;\n}\n\n/**\n * Strict transfer data — a TransferData whose *own* properties conform to `T`.\n *\n * Use in generated code and userland APIs where the exact field set is known.\n *\n * @typeParam T - Strict field definitions (e.g. `{ name: string; age: number }`)\n */\nexport type StrictTransferData<T extends Record<string, unknown> = Record<string, unknown>> = TransferData & T;\n\n/**\n * Stored transfer with identifiers. The identity fields come from the canonical `TransferIdentity`;\n * `__tempId` identifies a row staged into an eager owner that was never persisted.\n */\nexport interface TransferStored\n\textends TransferData, Pick<TransferIdentity, \"__identifier\" | \"__signedIdentifier\" | \"__tempId\"> {\n\t__typename?: string;\n\t__entityType?: string;\n}\n\n/**\n * Reads a collection relation of a transfer held in the data store: the array\n * itself, or `[]` when the field is unset or not a list.\n */\nexport function relationItems(owner: TransferData | null | undefined, relationName: string): TransferStored[] {\n\tconst value = owner?.[relationName];\n\treturn Array.isArray(value) ? value : [];\n}\n\n/**\n * Strict stored transfer — a TransferStored with compile-time field types from `T`.\n *\n * @typeParam T - Strict field definitions\n */\nexport type StrictTransferStored<T extends Record<string, unknown> = Record<string, unknown>> = TransferStored & T;\n\n/**\n * Response wrapper for JUDO REST responses.\n */\nexport interface JudoRestResponse<T> {\n\tdata: T;\n\tstatus: number;\n\theaders: Headers;\n}\n\n/**\n * Path context for building REST paths.\n */\nexport interface PathContext {\n\t/** Package name tokens (e.g., [\"admin\"]) */\n\tpackageNameTokens: string[];\n\t/** Simple name (e.g., \"Issue\") */\n\tsimpleName: string;\n}\n\n/**\n * Class type metadata for path building.\n */\nexport interface ClassTypeMetadata extends PathContext {\n\t/** Fully qualified name */\n\tfqName?: string;\n\t/** Whether the class is mapped */\n\tisMapped?: boolean;\n}\n\n/**\n * Relation type metadata for path building.\n */\nexport interface RelationMetadata {\n\t/** Relation name */\n\tname: string;\n\t/** Owner class metadata */\n\towner: ClassTypeMetadata;\n\t/** Target class metadata */\n\ttarget: ClassTypeMetadata;\n\t/** Whether this is an access relation */\n\tisAccess?: boolean;\n\t/** Whether this is a collection relation */\n\tisCollection?: boolean;\n}\n\n/**\n * Operation type metadata.\n */\nexport interface OperationMetadata {\n\t/** Operation name */\n\tname: string;\n\t/** Whether the operation is static */\n\tisStatic?: boolean;\n\t/** Whether the operation is mapped */\n\tisMapped?: boolean;\n\t/** Whether the operation has input */\n\thasInput?: boolean;\n\t/** Whether the operation has output */\n\thasOutput?: boolean;\n\t/** Input type metadata */\n\tinputType?: ClassTypeMetadata;\n\t/** Output type metadata */\n\toutputType?: ClassTypeMetadata;\n}\n\n/**\n * Range request body structure.\n */\nexport interface RangeRequestBody {\n\towner?: TransferStored;\n\tqueryCustomizer?: QueryCustomizer;\n}\n\n// ============================================\n// Validation & Error Types\n// ============================================\n\n/**\n * Validation feedback item from REST API.\n * Returned in response body for 400 validation errors.\n */\nexport interface FeedbackItem {\n\t/** Error code identifier */\n\tcode: string;\n\t/** Severity level of the feedback */\n\tlevel: \"ERROR\" | \"WARNING\" | \"INFO\";\n\t/**\n\t * Location of the error - typically the attribute path.\n\t * For nested properties, format is: \"relationName.attributeName\"\n\t * For simple attributes, format is: \"attributeName\"\n\t */\n\tlocation: string;\n\t/** Human-readable error message */\n\tmessage?: string;\n}\n\n/**\n * Validation error thrown when API returns 400 status.\n * Contains array of FeedbackItem with field-level error details.\n */\nexport class ValidationError extends Error {\n\treadonly feedbackItems: FeedbackItem[];\n\treadonly status: number = 400;\n\n\tconstructor(feedbackItems: FeedbackItem[]) {\n\t\tconst firstError = feedbackItems.find((f) => f.level === \"ERROR\");\n\t\tsuper(firstError?.message ?? \"Validation failed\");\n\t\tthis.name = \"ValidationError\";\n\t\tthis.feedbackItems = feedbackItems;\n\t}\n\n\t/**\n\t * Get errors as a map of field location to error message.\n\t * Useful for setting form field errors.\n\t */\n\ttoFieldErrors(): Record<string, string> {\n\t\tconst errors: Record<string, string> = {};\n\t\tfor (const item of this.feedbackItems) {\n\t\t\tif (item.level === \"ERROR\" && item.location) {\n\t\t\t\terrors[item.location] = item.message ?? item.code;\n\t\t\t}\n\t\t}\n\t\treturn errors;\n\t}\n}\n\n// ============================================\n// Dialog Response Types\n// ============================================\n\n/**\n * Result type for dialog submission.\n * Used for create dialogs opened from eager/lazy components.\n */\nexport type DialogResult<T = TransferData> = { outcome: \"cancel\" } | { outcome: \"submit\"; data: T };\n\n/**\n * Callback for dialog submission.\n * Called when user submits the create form.\n */\nexport type OnDialogSubmit<T = TransferData> = (data: T) => Promise<void>;\n\n/**\n * Callback for dialog validation.\n * Called before submission to validate form data.\n * Returns field errors or null if valid.\n */\nexport type OnDialogValidate<T = TransferData> = (data: T) => Promise<Record<string, string> | null>;\n","/**\n * JUDO REST API constants.\n * Based on REST_REQUEST_MAPPING_SPECIFICATION.md\n */\n\n// Header names\nexport const HEADER_SIGNED_IDENTIFIER = \"X-Judo-SignedIdentifier\";\nexport const HEADER_MASK = \"X-Judo-Mask\";\nexport const HEADER_MARK_SELECTED_RANGE_ITEMS = \"X-Judo-MarkSelectedRangeItems\";\nexport const HEADER_COUNT_RECORDS = \"X-Judo-CountRecords\";\n/** Response header carrying the total record count for list/range queries. */\nexport const HEADER_COUNT = \"x-judo-count\";\nexport const HEADER_TOKEN = \"X-Token\";\n\n// Default values\nexport const DEFAULT_COMMAND_MASK = \"{}\";\n\n// Path suffixes\nexport const SUFFIX_TEMPLATE = \"/~template\";\nexport const SUFFIX_GET = \"/~get\";\nexport const SUFFIX_UPDATE = \"/~update\";\nexport const SUFFIX_VALIDATE = \"/~validate\";\nexport const SUFFIX_DELETE = \"/~delete\";\nexport const SUFFIX_LIST = \"/~list\";\nexport const SUFFIX_RANGE = \"/~range\";\nexport const SUFFIX_CREATE = \"/~create\";\nexport const SUFFIX_SET = \"/~set\";\nexport const SUFFIX_UNSET = \"/~unset\";\nexport const SUFFIX_ADD = \"/~add\";\nexport const SUFFIX_REMOVE = \"/~remove\";\nexport const SUFFIX_EXPORT = \"/~export\";\nexport const SUFFIX_UPLOAD_TOKEN = \"/~upload-token\";\nexport const SUFFIX_PRINCIPAL = \"/~principal\";\nexport const SUFFIX_META = \"/~meta\";\n","/**\n * Error handler interceptor integration for the action error pipeline.\n *\n * Bridges the `errorHandlerInterceptor` customization (resolved in `@judo/core`\n * and threaded through the action context, so `@judo/actions` stays free of a\n * `@judo/core` dependency) into the built-in handlers' error handling.\n */\n\nimport type { ErrorHandlerInterceptorHook, ErrorHandlingOption } from \"@judo/model-api\";\n\n/**\n * Apply the error handler interceptor, if registered, to an error.\n *\n * Checks `shouldInterceptError(error, options)`; when it returns `true`, calls\n * `interceptError(error, options, payload, dataPath)` and returns `true` so the\n * caller skips its default error handling. When no interceptor is registered or\n * it declines the error, returns `false` and the caller runs default handling.\n *\n * @param error - The error thrown by the failing dispatch.\n * @param interceptor - The interceptor from the action context (optional).\n * @param options - Contextual options describing the failing operation.\n * @param payload - Optional request payload that triggered the error.\n * @param dataPath - Optional data path associated with the failing call.\n * @returns `true` when the interceptor handled the error (skip default handling).\n */\nexport function maybeInterceptError(\n\terror: unknown,\n\tinterceptor?: ErrorHandlerInterceptorHook,\n\toptions?: ErrorHandlingOption,\n\tpayload?: unknown,\n\tdataPath?: string\n): boolean {\n\tif (interceptor && interceptor.shouldInterceptError(error, options)) {\n\t\tinterceptor.interceptError(error, options, payload, dataPath);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n/**\n * Default CRUD error handling: store the error on the transfer so the container\n * error boundary can render it. When an `errorHandlerInterceptor` accepts the\n * error first, the default `setTransferError` is skipped.\n *\n * @param interceptor - The interceptor from the action context (may be undefined).\n * @param setTransferError - The data store's `setTransferError` (may be undefined).\n * @param transferId - The transfer id to associate the error with.\n * @param error - The error thrown by the failing dispatch.\n * @param options - Contextual options describing the failing operation.\n * @returns `true` when the interceptor handled the error (default handling skipped).\n */\nexport function handleCrudError(\n\tinterceptor: ErrorHandlerInterceptorHook | undefined,\n\tdata: { setTransferError(id: string, error: Error): void } | undefined,\n\ttransferId: string,\n\terror: unknown,\n\toptions?: ErrorHandlingOption\n): boolean {\n\tif (maybeInterceptError(error, interceptor, options)) {\n\t\treturn true;\n\t}\n\tdata?.setTransferError(transferId, error as Error);\n\treturn false;\n}\n","/**\n * React template default texts for validation feedback (English), used as i18next `defaultValue`\n * when the application has no translation for the key.\n */\n\n/** React's `judo.error.validation-failed` toast text. */\nexport const DEFAULT_VALIDATION_FAILED_MESSAGE = \"Please make sure all fields are filled in correctly.\";\n\n/** A backend `validation-failed` code that has a React message. */\nexport type ValidationFailureCode =\n\t| \"TOO_FEW_PARAMETERS\"\n\t| \"TOO_MANY_PARAMETERS\"\n\t| \"MISSING_REQUIRED_PARAMETER\"\n\t| \"CONVERSION_FAILED\"\n\t| \"TOO_FEW_ITEMS\"\n\t| \"TOO_MANY_ITEMS\"\n\t| \"MISSING_REQUIRED_RELATION\"\n\t| \"MISSING_REQUIRED_ATTRIBUTE\"\n\t| \"MAX_LENGTH_VALIDATION_FAILED\"\n\t| \"MIN_LENGTH_VALIDATION_FAILED\"\n\t| \"PATTERN_VALIDATION_FAILED\"\n\t| \"PRECISION_VALIDATION_FAILED\"\n\t| \"SCALE_VALIDATION_FAILED\"\n\t| \"IDENTIFIER_ATTRIBUTE_UNIQUENESS_VIOLATION\"\n\t| \"NOT_ACCEPTED_BY_RANGE\"\n\t| \"MIN_DATE_VALIDATION_FAILED\"\n\t| \"MAX_DATE_VALIDATION_FAILED\"\n\t| \"MIN_TIME_VALIDATION_FAILED\"\n\t| \"MAX_TIME_VALIDATION_FAILED\"\n\t| \"MIN_NUMERIC_VALUE_VALIDATION_FAILED\"\n\t| \"MAX_NUMERIC_VALUE_VALIDATION_FAILED\";\n\n/** Default texts copied from React's `system_default.json.hbs` (`judo.error.validation-failed.<CODE>`). */\nexport const DEFAULT_VALIDATION_MESSAGES: Record<ValidationFailureCode, string> = {\n\tTOO_FEW_PARAMETERS: \"Must contain at least {{error.details.size}} parameters.\",\n\tTOO_MANY_PARAMETERS: \"Must contain at most {{error.details.size}} parameters.\",\n\tMISSING_REQUIRED_PARAMETER: \"Missing required parameter.\",\n\tCONVERSION_FAILED: \"Failed to convert value to expected type.\",\n\tTOO_FEW_ITEMS: \"Must contain at least {{error.details.size}} items.\",\n\tTOO_MANY_ITEMS: \"Must contain at most {{error.details.size}} items.\",\n\tMISSING_REQUIRED_RELATION: \"Missing required relation.\",\n\tMISSING_REQUIRED_ATTRIBUTE: \"Missing required attribute.\",\n\tMAX_LENGTH_VALIDATION_FAILED: \"Value must not exceed the length of {{error.details.maxLength}} characters.\",\n\tMIN_LENGTH_VALIDATION_FAILED: \"Value must be at least {{error.details.maxLength}} characters long.\",\n\tPATTERN_VALIDATION_FAILED: \"Value does not match the pattern requirements.\",\n\tPRECISION_VALIDATION_FAILED: \"Number of digits must not exceed {{error.details.precision}}.\",\n\tSCALE_VALIDATION_FAILED: \"Number of decimals must not exceed {{error.details.scale}}.\",\n\tIDENTIFIER_ATTRIBUTE_UNIQUENESS_VIOLATION: \"Identifier attribute is not unique.\",\n\tNOT_ACCEPTED_BY_RANGE: \"Not accepted by the range.\",\n\tMIN_DATE_VALIDATION_FAILED: \"The selected date must be after the minimum allowed date ({{minDate}}).\",\n\tMAX_DATE_VALIDATION_FAILED: \"The selected date must be before the maximum allowed date ({{maxDate}}).\",\n\tMIN_TIME_VALIDATION_FAILED: \"The selected time must be after the minimum allowed time ({{minTime}}).\",\n\tMAX_TIME_VALIDATION_FAILED: \"The selected time must be before the maximum allowed time ({{maxTime}}).\",\n\tMIN_NUMERIC_VALUE_VALIDATION_FAILED: \"The value must be at least ({{minValue}}).\",\n\tMAX_NUMERIC_VALUE_VALIDATION_FAILED: \"The value cannot exceed ({{maxValue}}).\",\n};\n","/**\n * Field-level display of backend `validation-failed` faults, mirroring the React\n * template's `utilities/error-handling.ts.hbs` (`useErrorHandler`, case 400, and\n * `validateWithNestedErrors`) and the texts of `public/i18n/system_default.json.hbs`.\n */\nimport {\n\ttype PageContainer,\n\ttype VisualElement,\n\tboundElementName,\n\tforEachVisualElement,\n\tisRangeInput,\n} from \"@judo/model-api\";\nimport type { FeedbackItem, TransferData, ValidationError } from \"../api/types\";\nimport type { TFunction } from \"i18next\";\nimport type { TypedActionHandlerContext, ValidationContext } from \"../types\";\nimport {\n\tDEFAULT_VALIDATION_FAILED_MESSAGE,\n\tDEFAULT_VALIDATION_MESSAGES,\n\ttype ValidationFailureCode,\n} from \"./validation-messages\";\n\n/** Whether a backend fault code has a React message (fault codes arrive as plain strings). */\nfunction isValidationFailureCode(code: string): code is ValidationFailureCode {\n\treturn Object.hasOwn(DEFAULT_VALIDATION_MESSAGES, code);\n}\n\n/**\n * Message for a `validation-failed` code: `t('judo.error.validation-failed.<CODE>')`\n * with React's English text as the default.\n */\nexport function validationMessage(\n\tcode: ValidationFailureCode,\n\tt: TFunction,\n\tvalues: Record<string, unknown> = {}\n): string {\n\treturn translated(code, DEFAULT_VALIDATION_MESSAGES[code], t, values);\n}\n\n/** Message for a backend fault code; an unknown code shows the code itself, like React. */\nfunction faultMessage(code: string, t: TFunction, values: Record<string, unknown>): string {\n\treturn isValidationFailureCode(code) ? validationMessage(code, t, values) : translated(code, code, t, values);\n}\n\nfunction translated(code: string, defaultValue: string, t: TFunction, values: Record<string, unknown>): string {\n\treturn t(`judo.error.validation-failed.${code}`, { defaultValue, ...values });\n}\n\n/**\n * Map faults to field messages exactly like React's `validateWithNestedErrors`: a plain\n * location keys its own field; a nested location (`rel[0].attr`, `rel.attr`) is grouped\n * on the relation key, its messages joined by `\", \"`.\n */\nexport function toValidationMessages(items: FeedbackItem[], t: TFunction): Record<string, string> {\n\tconst messages: Record<string, string> = {};\n\tconst relations: Record<string, string[]> = {};\n\tfor (const item of items) {\n\t\tconst message = faultMessage(item.code, t, { error: item });\n\t\tconst split = item.location.split(/\\[|\\./).filter((part) => part.length);\n\t\tif (split.length > 1) {\n\t\t\t(relations[split[0]] ??= []).push(message);\n\t\t} else {\n\t\t\tmessages[item.location] = message;\n\t\t}\n\t}\n\tfor (const [key, list] of Object.entries(relations)) {\n\t\tmessages[key] = list.join(\", \");\n\t}\n\treturn messages;\n}\n\n/**\n * React's 400 branch: an error toast, and — when the first fault has a location —\n * the field errors are *replaced* by the new set (`setValidation(new Map(...))`).\n */\nexport function reportValidationError(\n\terror: ValidationError,\n\tcontext: Pick<TypedActionHandlerContext, \"validation\" | \"notifications\" | \"translate\">\n): void {\n\tconst { validation, notifications, translate } = context;\n\tnotifications?.error(translate(\"judo.error.validation-failed\", { defaultValue: DEFAULT_VALIDATION_FAILED_MESSAGE }));\n\tif (validation && error.feedbackItems[0]?.location) {\n\t\tvalidation.clearErrors();\n\t\tvalidation.setErrors(toValidationMessages(error.feedbackItems, translate));\n\t}\n}\n\n/** A widget with a `requiredBy` flag attribute and the field it marks. */\ninterface RequiredByField {\n\tflag: string;\n\tfield: string;\n}\n\n/**\n * React's pre-save check (`fragments/page/local-validate.fragment.hbs` +\n * `utilities/form-utils.ts.hbs` `passesLocalValidation`), run by Create, Update and\n * InputForm operation actions on pages that have `requiredBy` widgets\n * (`hasPageRequiredBy`):\n * - an empty field whose `requiredBy` flag is set gets `MISSING_REQUIRED_ATTRIBUTE`;\n * - otherwise a non-read-only date/datetime/time/numeric input still showing an error\n * (e.g. its modeled range) blocks the save.\n *\n * @param data - The transfer being saved, keyed by attribute and relation name.\n * @returns `false` when the save must not reach the backend.\n */\nexport function passesLocalValidation(\n\tcontainer: PageContainer | undefined,\n\tdata: TransferData,\n\tvalidation: ValidationContext | undefined,\n\tt: TFunction\n): boolean {\n\tif (!container || !validation) return true;\n\tconst requiredBy: RequiredByField[] = [];\n\tconst rangeInputs: string[] = [];\n\tforEachVisualElement(container, (element: VisualElement) => {\n\t\tconst field = boundElementName(element);\n\t\tif (!field) return;\n\t\tconst flag = element.requiredBy?.name;\n\t\tif (flag) requiredBy.push({ flag, field });\n\t\tif (isRangeInput(element) && element.isReadOnly !== true) rangeInputs.push(field);\n\t});\n\tif (requiredBy.length === 0) return true;\n\n\tconst missing: Record<string, string> = {};\n\tfor (const { flag, field } of requiredBy) {\n\t\tconst value = data[field];\n\t\tif (data[flag] && (value === null || value === undefined || value === \"\")) {\n\t\t\tmissing[field] = validationMessage(\"MISSING_REQUIRED_ATTRIBUTE\", t);\n\t\t}\n\t}\n\tif (Object.keys(missing).length > 0) {\n\t\tvalidation.setErrors(missing);\n\t\treturn false;\n\t}\n\treturn !rangeInputs.some((field) => !!validation.getError?.(field));\n}\n","import {\n\ttype ActionDefinition,\n\ttype ActionResult,\n\ttype ClassType,\n\ttype DataElement,\n\ttype OperationType,\n\ttype PageDefinition,\n\tRelationBehaviourType,\n\ttype RelationType,\n} from \"@judo/model-api\";\nimport type { IJudoRestApi } from \"../../api/i-judo-rest-api\";\nimport {\n\ttype TransferData,\n\ttype TransferStored,\n\ttype QueryCustomizer,\n\ttype ValidationError,\n\trelationItems,\n} from \"../../api/types\";\nimport type {\n\tAction,\n\tActionHandlerHookWithMeta,\n\tQueryAction,\n\tRowActionInput,\n\tTypedActionHandlerContext,\n} from \"../../types\";\nimport { HEADER_COUNT } from \"../../api/constants\";\nimport { handleCrudError, maybeInterceptError } from \"../../lifecycle/error-interceptor\";\nimport { passesLocalValidation, reportValidationError } from \"../validation-feedback\";\n\n// Interface for API context - will be provided via context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Extended context for page-level operations (e.g., table list)\ninterface PageContext {\n\t/** Transfer ID for the page (used to store table data) */\n\tpageTransferId?: string;\n\t/** Number of rows per page for table pagination */\n\trowsPerPage?: number;\n\t/** Whether this is a selector page (Add/Set selector) */\n\tisSelector?: boolean;\n\t/** Owner transfer for selector range queries */\n\townerTransfer?: TransferStored;\n\t/** Whether this is an operation input selector page */\n\tisOperationInput?: boolean;\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonRefresh?: (transferId: string, classType: ClassType) => Promise<TransferStored>;\n\tonListRelation?: (relation: RelationType) => Promise<TransferStored[]>;\n\tonCreate?: (transfer: TransferStored, classType: ClassType) => Promise<TransferStored>;\n\tonUpdate?: (transfer: TransferStored, classType: ClassType) => Promise<TransferStored>;\n\tonDelete?: (transferId: string, classType: ClassType) => Promise<void>;\n\tonBulkDelete?: (transferIds: string[], classType: ClassType) => Promise<void>;\n\tonRowDelete?: (transferId: string, classType: ClassType) => Promise<void>;\n\tonGetTemplate?: (classType: ClassType) => Promise<TransferStored>;\n\t/** Custom validation callback for create operations */\n\tonValidateCreate?: (\n\t\ttransfer: TransferStored,\n\t\trelation: RelationType,\n\t\townerTransfer?: TransferStored\n\t) => Promise<Record<string, string> | null>;\n}\n\n// Relation context for create operations - supports both new format (relation property) and legacy format (flat)\ninterface CreateRelationContext {\n\townerTransfer?: TransferStored;\n\trelationMetadata?:\n\t\t| RelationType\n\t\t| {\n\t\t\t\trelation?: RelationType;\n\t\t\t\tisAccess?: boolean;\n\t\t\t\t// Legacy format: relation props directly in relationMetadata\n\t\t\t\tname?: string;\n\t\t\t\towner?: unknown;\n\t\t\t\ttarget?: unknown;\n\t\t };\n}\n\n/**\n * Helper to check if an error is a ValidationError.\n */\nfunction isValidationError(error: unknown): error is ValidationError {\n\treturn error !== null && typeof error === \"object\" && (error as { name?: string }).name === \"ValidationError\";\n}\n\n/**\n * Resolve the target ClassType for an action.\n *\n * Resolution order:\n * 1. actionDefinition.targetType (explicitly set in the model)\n * 2. Page's dataElement (via eContainer traversal from Action to PageDefinition)\n * - If dataElement is a ClassType, use it directly\n * - If dataElement is a RelationType, follow its .target to get the ClassType\n *\n * UpdateActionDefinition, DeleteActionDefinition, and RefreshActionDefinition\n * typically don't have targetType set in the XMI model. The target type is\n * derived from the page's dataElement instead.\n */\nfunction resolveTargetClassType(action: Action): ClassType | undefined {\n\t// 1. Try explicit targetType on the action definition\n\tconst explicit = action.actionDefinition?.targetType as ClassType | undefined;\n\tif (explicit) {\n\t\treturn explicit;\n\t}\n\n\t// 2. Fall back to the page's dataElement\n\t// Action.eContainer is PageDefinition (since PageDefinition.actions contains Action[])\n\tconst page = (action as unknown as { eContainer?: unknown }).eContainer as PageDefinition | undefined;\n\tif (!page?.dataElement) {\n\t\treturn undefined;\n\t}\n\n\tconst dataElement = page.dataElement as DataElement & { target?: ClassType; \"@type\"?: string };\n\n\t// If the dataElement is a ClassType, use it directly\n\tif (dataElement[\"@type\"] === \"ClassType\" || dataElement[\"@type\"] === \"data:ClassType\") {\n\t\treturn dataElement as unknown as ClassType;\n\t}\n\n\t// If the dataElement is a RelationType, follow .target to get the ClassType\n\tif (dataElement[\"@type\"] === \"RelationType\" || dataElement[\"@type\"] === \"data:RelationType\") {\n\t\treturn dataElement.target;\n\t}\n\n\t// OperationParameterType (output/input) has no @type from the parser but inherits\n\t// .target from ReferenceType, just like RelationType. Follow .target if present.\n\tif (dataElement.target) {\n\t\treturn dataElement.target;\n\t}\n\n\treturn undefined;\n}\n\n/** The paged shape a table relation can keep between nested dialogs. */\ninterface PagedItems {\n\t__items: unknown[];\n}\n\nfunction isPagedItems(value: unknown): value is PagedItems {\n\treturn typeof value === \"object\" && value !== null && \"__items\" in value && Array.isArray(value.__items);\n}\n\n/**\n * Whether a transfer carries unsaved local edits.\n *\n * Reads the same per-transfer `isDirty` flag the DataStore maintains and\n * `useEditMode` derives a page's edit mode from, so \"the user has changed this\n * and not saved it\" means one thing across the runtime.\n */\nfunction isTransferDirty(context: TypedActionHandlerContext, transferId: string): boolean {\n\tif (!context.data) {\n\t\treturn false;\n\t}\n\tconst isDirty = context.data.getSnapshot((state) => state.transfers.get(transferId)?.isDirty);\n\treturn isDirty ?? false;\n}\n\n/**\n * Check if the action is for listing an ACCESS relation (top-level table load).\n * This is the case when:\n * - ownerDataElement is a RelationType\n * - The relation is an access relation (isAccess=true)\n * - No transfer exists in context (initial table load)\n */\nfunction isAccessRelationListAction(action: Action, transfer?: TransferStored): boolean {\n\tconst ownerDataElement = action.ownerDataElement;\n\tif (!ownerDataElement || ownerDataElement[\"@type\"] !== \"RelationType\") {\n\t\treturn false;\n\t}\n\n\tconst relation = ownerDataElement as RelationType;\n\t// isAccess can be boolean true or string \"true\" depending on model parsing\n\t// Use String() comparison to handle both cases\n\tconst isAccessRelation = String(relation.isAccess) === \"true\";\n\tconst hasNoEntity = !transfer?.__identifier && !transfer?.__signedIdentifier;\n\n\treturn isAccessRelation && hasNoEntity;\n}\n\n/**\n * Check if the action is for listing an transfer's relation (relation table page).\n * This is the case when:\n * - ownerDataElement is a RelationType\n * - The relation is NOT an access relation (isAccess=false)\n * - Transfer exists with a signedIdentifier (the owner transfer)\n */\nfunction isEntityRelationListAction(action: Action, transfer?: TransferStored): boolean {\n\tconst ownerDataElement = action.ownerDataElement;\n\n\t// Parser maps \"data:RelationType\" -> \"RelationType\"\n\tif (!ownerDataElement || ownerDataElement[\"@type\"] !== \"RelationType\") {\n\t\treturn false;\n\t}\n\n\tconst relation = ownerDataElement as RelationType;\n\tconst isAccessRelation = String(relation.isAccess) === \"true\";\n\tconst hasEntity = !!transfer?.__signedIdentifier;\n\n\treturn !isAccessRelation && hasEntity;\n}\n\n/**\n * Handle data refresh - hook factory.\n * Calls REST API to refresh transfer data OR list relation data.\n *\n * Three modes:\n * 1. Access relation list: When action.ownerDataElement is an access RelationType (top-level table)\n * 2. Transfer relation list: When action.ownerDataElement is a non-access RelationType with owner transfer\n * 3. Single transfer refresh: When context.transfer has an identifier\n *\n * Supports both legacy callback mode and API mode.\n */\nexport const useRefreshActionHandler = ((action: QueryAction) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext & PageContext;\n\t\tconst { api, pageTransferId, rowsPerPage } = callbackContext;\n\n\t\t// Extract queryCustomizer and countRecords from action if provided (e.g., from table sorting/filtering)\n\t\tconst { queryCustomizer: actionQueryCustomizer, countRecords } = action;\n\n\t\t// Check if this is an ACCESS relation list operation (top-level table load)\n\t\tif (isAccessRelationListAction(action, transfer)) {\n\t\t\tconst relation = action.ownerDataElement as RelationType;\n\n\t\t\t// Singleton vs collection dispatch:\n\t\t\t// The BE emits two different endpoints for access relations depending\n\t\t\t// on `isCollection`:\n\t\t\t// - isCollection === true -> `<rel>/~list` (returns Array<Transfer>)\n\t\t\t// - isCollection !== true -> `<rel>/~get` (returns Transfer | null)\n\t\t\t// This mirrors the legacy `judo-ui-react-template` generator (see\n\t\t\t// `relationServiceImpl.ts.hbs`: list-branch under `relation.isListable &&\n\t\t\t// relation.isCollection`, refresh-branch under `relation.isAccess &&\n\t\t\t// !relation.isCollection`). Without this dispatch, singleton access\n\t\t\t// relations (e.g. `profileSettings`, `userReservations` on a singleton\n\t\t\t// actor) 404 because the BE has no `~list` route for them.\n\t\t\t//\n\t\t\t// The model's EMF default for `isCollection` is `true`, so unset is\n\t\t\t// treated as collection here (matching the legacy generator and the\n\t\t\t// spec in `packages/model-api/src/data/elements.ts`).\n\t\t\tconst isCollection = relation.isCollection === undefined ? true : String(relation.isCollection) === \"true\";\n\n\t\t\t// Use provided pageTransferId or generate one from action\n\t\t\tconst tableEntityId = pageTransferId ?? `table::${action[\"xmi:id\"]}`;\n\t\t\tcontext.data?.setTransferLoading(tableEntityId, true);\n\n\t\t\ttry {\n\t\t\t\tconst { onListRelation } = callbackContext;\n\n\t\t\t\tif (onListRelation) {\n\t\t\t\t\t// Use legacy callback if provided. Callbacks are list-shaped\n\t\t\t\t\t// historically; singletons are surfaced as a single-element list.\n\t\t\t\t\tconst listData = await onListRelation(relation);\n\t\t\t\t\tconst tableData: TransferData = { __items: listData };\n\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, tableData);\n\t\t\t\t} else if (api) {\n\t\t\t\t\tif (isCollection) {\n\t\t\t\t\t\t// Collection access relation → `<rel>/~list`\n\t\t\t\t\t\tconst queryCustomizer: QueryCustomizer = {\n\t\t\t\t\t\t\t_seek: { limit: rowsPerPage ?? 10 },\n\t\t\t\t\t\t\t...actionQueryCustomizer,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst response = await api.listRelation(relation, undefined, queryCustomizer, countRecords);\n\t\t\t\t\t\tconst totalCountHeader = response.headers.get(HEADER_COUNT);\n\t\t\t\t\t\tconst totalCount = totalCountHeader ? Number.parseInt(totalCountHeader, 10) : undefined;\n\t\t\t\t\t\tconst tableData: TransferData = { __items: response.data };\n\t\t\t\t\t\tif (totalCount !== undefined && !Number.isNaN(totalCount)) {\n\t\t\t\t\t\t\ttableData.__totalCount = totalCount;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, tableData);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Singleton access relation → `<rel>/~get`. The BE rejects\n\t\t\t\t\t\t// list-style query parameters (`_seek`, `_orderBy`) on singleton\n\t\t\t\t\t\t// `~get` calls (it routes them through the same dispatcher path\n\t\t\t\t\t\t// as `~list`, where the ordering attribute is resolved against\n\t\t\t\t\t\t// the singleton transfer class — a class that has no such\n\t\t\t\t\t\t// attributes, producing\n\t\t\t\t\t\t// `NoSuchElementException: No value present` (HTTP 500)).\n\t\t\t\t\t\t// Only `_mask` is meaningful on a singleton refresh.\n\t\t\t\t\t\tconst singletonQuery: QueryCustomizer | undefined = actionQueryCustomizer?._mask\n\t\t\t\t\t\t\t? { _mask: actionQueryCustomizer._mask }\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst response = await api.refreshAccessRelation(relation, singletonQuery);\n\t\t\t\t\t\tconst single = response.data as TransferStored | null | undefined;\n\t\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, (single ?? {}) as unknown as TransferData);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(\"API not available in context\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, tableEntityId, error);\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, false);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Check if this is an ENTITY relation list operation (relation table page)\n\t\tif (isEntityRelationListAction(action, transfer)) {\n\t\t\tconst relation = action.ownerDataElement as RelationType;\n\n\t\t\t// Use provided pageTransferId or generate one from action\n\t\t\tconst tableEntityId = pageTransferId ?? `table::${action[\"xmi:id\"]}`;\n\t\t\tcontext.data?.setTransferLoading(tableEntityId, true);\n\n\t\t\ttry {\n\t\t\t\tif (api) {\n\t\t\t\t\t// For transfer relations, pass the relation directly to the API\n\t\t\t\t\t// Build query customizer: merge action's queryCustomizer with pagination\n\t\t\t\t\tconst queryCustomizer: QueryCustomizer = {\n\t\t\t\t\t\t_seek: { limit: rowsPerPage ?? 10 },\n\t\t\t\t\t\t...actionQueryCustomizer,\n\t\t\t\t\t};\n\t\t\t\t\t// Pass the owner transfer to include X-Judo-SignedIdentifier header\n\t\t\t\t\tconst response = await api.listRelation(relation, transfer, queryCustomizer, countRecords);\n\t\t\t\t\tconst listData = response.data;\n\n\t\t\t\t\t// Extract total count from response header if present\n\t\t\t\t\tconst totalCountHeader = response.headers.get(HEADER_COUNT);\n\t\t\t\t\tconst totalCount = totalCountHeader ? Number.parseInt(totalCountHeader, 10) : undefined;\n\n\t\t\t\t\t// Store the list data - wrap in object with __items key for table consumption\n\t\t\t\t\tconst tableData: TransferData = { __items: listData };\n\t\t\t\t\tif (totalCount !== undefined && !Number.isNaN(totalCount)) {\n\t\t\t\t\t\ttableData.__totalCount = totalCount;\n\t\t\t\t\t}\n\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, tableData);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(\"API not available in context\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, tableEntityId, error);\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, false);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Check if this is a SELECTOR range query (Add/Set selector dialog)\n\t\t// Selector pages need to fetch the available range of items via getRelationRange()\n\t\tif (callbackContext.isSelector) {\n\t\t\tconst ownerDataElement = action.ownerDataElement;\n\n\t\t\t// Relation selector: ownerDataElement is a RelationType → getRelationRange\n\t\t\tif (ownerDataElement && ownerDataElement[\"@type\"] === \"RelationType\") {\n\t\t\t\tconst relation = ownerDataElement as RelationType;\n\t\t\t\tconst tableEntityId = pageTransferId ?? `table::${action[\"xmi:id\"]}`;\n\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, true);\n\n\t\t\t\ttry {\n\t\t\t\t\tif (api) {\n\t\t\t\t\t\tconst queryCustomizer: QueryCustomizer = {\n\t\t\t\t\t\t\t_seek: { limit: rowsPerPage ?? 10 },\n\t\t\t\t\t\t\t...actionQueryCustomizer,\n\t\t\t\t\t\t};\n\t\t\t\t\t\t// Range calls only need __signedIdentifier on the owner - strip __identifier\n\t\t\t\t\t\tconst rangeOwner = callbackContext.ownerTransfer?.__signedIdentifier\n\t\t\t\t\t\t\t? ({\n\t\t\t\t\t\t\t\t\t__signedIdentifier: callbackContext.ownerTransfer.__signedIdentifier,\n\t\t\t\t\t\t\t\t} as TransferStored)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst response = await api.getRelationRange(relation, rangeOwner, queryCustomizer, countRecords);\n\t\t\t\t\t\tconst rangeData = response.data;\n\n\t\t\t\t\t\t// Extract total count from response header if present\n\t\t\t\t\t\tconst totalCountHeader = response.headers.get(HEADER_COUNT);\n\t\t\t\t\t\tconst totalCount = totalCountHeader ? Number.parseInt(totalCountHeader, 10) : undefined;\n\n\t\t\t\t\t\tconst tableData: TransferData = { __items: rangeData };\n\t\t\t\t\t\tif (totalCount !== undefined && !Number.isNaN(totalCount)) {\n\t\t\t\t\t\t\ttableData.__totalCount = totalCount;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, tableData);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new Error(\"API not available in context\");\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, tableEntityId, error);\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, false);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Operation input selector: ownerDataElement is an OperationType → getOperationInputRange\n\t\t\t// Derive the owning ClassType from the OperationType's eContainer (set during model resolution)\n\t\t\tif (ownerDataElement && ownerDataElement[\"@type\"] === \"OperationType\") {\n\t\t\t\tconst operationType = ownerDataElement as OperationType;\n\t\t\t\tconst ownerClassType = (ownerDataElement as unknown as { eContainer?: ClassType }).eContainer;\n\n\t\t\t\tif (!ownerClassType) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"Cannot determine owning ClassType for operation input selector (OperationType.eContainer is missing)\"\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst tableEntityId = pageTransferId ?? `table::${action[\"xmi:id\"]}`;\n\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, true);\n\n\t\t\t\ttry {\n\t\t\t\t\tif (api) {\n\t\t\t\t\t\tconst queryCustomizer: QueryCustomizer = {\n\t\t\t\t\t\t\t_seek: { limit: rowsPerPage ?? 10 },\n\t\t\t\t\t\t\t...actionQueryCustomizer,\n\t\t\t\t\t\t};\n\t\t\t\t\t\t// Range calls only need __signedIdentifier on the owner - strip __identifier\n\t\t\t\t\t\tconst rangeOwner = callbackContext.ownerTransfer?.__signedIdentifier\n\t\t\t\t\t\t\t? ({\n\t\t\t\t\t\t\t\t\t__signedIdentifier: callbackContext.ownerTransfer.__signedIdentifier,\n\t\t\t\t\t\t\t\t} as TransferStored)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst response = await api.getOperationInputRange(\n\t\t\t\t\t\t\townerClassType,\n\t\t\t\t\t\t\toperationType,\n\t\t\t\t\t\t\trangeOwner,\n\t\t\t\t\t\t\tqueryCustomizer,\n\t\t\t\t\t\t\tcountRecords\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst rangeData = response.data;\n\n\t\t\t\t\t\t// Extract total count from response header if present\n\t\t\t\t\t\tconst totalCountHeader = response.headers.get(HEADER_COUNT);\n\t\t\t\t\t\tconst totalCount = totalCountHeader ? Number.parseInt(totalCountHeader, 10) : undefined;\n\n\t\t\t\t\t\tconst tableData: TransferData = { __items: rangeData };\n\t\t\t\t\t\tif (totalCount !== undefined && !Number.isNaN(totalCount)) {\n\t\t\t\t\t\t\ttableData.__totalCount = totalCount;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontext.data?.setTransferData(tableEntityId, tableData);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new Error(\"API not available in context\");\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, tableEntityId, error);\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\tcontext.data?.setTransferLoading(tableEntityId, false);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Single transfer refresh mode\n\t\tconst transferId = transfer?.__identifier ?? transfer?.__signedIdentifier;\n\t\tif (!transferId) {\n\t\t\t// No transfer to refresh and not a list operation - nothing to do\n\t\t\treturn;\n\t\t}\n\n\t\t// Eager mode: the parent's relation array is authoritative only for what is not\n\t\t// on the server yet.\n\t\t//\n\t\t// A row that has no server identity is staged: it was created into the relation\n\t\t// by CreateActionHandler and is committed by the owner's save, so reading it\n\t\t// would 404 and discard the staged values. The same holds for a row that does\n\t\t// have a server identity but carries unsaved local edits — a row adopted through\n\t\t// a Set/Add selector is persisted while its adoption is still staged on the\n\t\t// owner, and re-reading it would silently drop those edits.\n\t\t//\n\t\t// Every other eager row is persisted and clean, and the parent's copy of it is\n\t\t// only as deep as the parent page's own mask — for a Galaxy that renders\n\t\t// `stars{name}`, the star's persisted planets are simply absent. Such a row is\n\t\t// therefore read from the server under the mask the opened view dispatched,\n\t\t// through the normal refresh path below.\n\t\tconst isEagerReadFromServer =\n\t\t\t!!context.isEager && !!transfer?.__signedIdentifier && !isTransferDirty(context, transferId);\n\n\t\t// context.transfer only carries identifiers (ViewContainerRenderer strips\n\t\t// fields), so we must look up the full transfer from the parent's store.\n\t\tif (context.isEager && !isEagerReadFromServer) {\n\t\t\tconst { parentTransferId, relationName } = context;\n\n\t\t\tif (parentTransferId && relationName && context.data) {\n\t\t\t\tconst parentData = context.data.getSnapshot((state) => state.transfers.get(parentTransferId)?.data);\n\n\t\t\t\tif (parentData) {\n\t\t\t\t\tconst relationValue = parentData[relationName];\n\n\t\t\t\t\tif (Array.isArray(relationValue)) {\n\t\t\t\t\t\t// Collection relation (Table) — find matching transfer in array\n\t\t\t\t\t\tconst fullEntity = relationValue.find((item: TransferStored) => {\n\t\t\t\t\t\t\tif (transfer!.__signedIdentifier && item.__signedIdentifier === transfer!.__signedIdentifier) return true;\n\t\t\t\t\t\t\tif (transfer!.__identifier && item.__identifier === transfer!.__identifier) return true;\n\t\t\t\t\t\t\tconst itemTempId = (item as { __tempId?: string }).__tempId;\n\t\t\t\t\t\t\tconst entityTempId = (transfer as { __tempId?: string })?.__tempId;\n\t\t\t\t\t\t\tif (itemTempId && entityTempId && itemTempId === entityTempId) return true;\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (fullEntity) {\n\t\t\t\t\t\t\tcontext.data.setTransferData(transferId, fullEntity);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (relationValue && typeof relationValue === \"object\") {\n\t\t\t\t\t\t// Single relation (Link) — use the value directly\n\t\t\t\t\t\tcontext.data.setTransferData(transferId, relationValue as TransferStored);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Fallback: store whatever we have (at least the identifiers)\n\t\t\tcontext.data?.setTransferData(transferId, transfer!);\n\t\t\treturn;\n\t\t}\n\n\t\tcontext.data?.setTransferLoading(transferId, true);\n\n\t\ttry {\n\t\t\tconst targetType = resolveTargetClassType(action);\n\t\t\tif (!targetType) {\n\t\t\t\tthrow new Error(\"No target type for refresh\");\n\t\t\t}\n\n\t\t\tconst { onRefresh } = callbackContext;\n\n\t\t\tlet refreshedEntity: TransferStored;\n\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onRefresh) {\n\t\t\t\trefreshedEntity = await onRefresh(transferId, targetType);\n\t\t\t} else if (api) {\n\t\t\t\t// Use API if available\n\t\t\t\t// Use actionQueryCustomizer if provided (e.g., for custom masks)\n\t\t\t\tconst response = await api.refresh(targetType, transfer!, actionQueryCustomizer);\n\t\t\t\trefreshedEntity = response.data;\n\t\t\t} else {\n\t\t\t\tthrow new Error(\"API not available in context\");\n\t\t\t}\n\n\t\t\tcontext.data?.setTransferData(transferId, refreshedEntity);\n\t\t} catch (error) {\n\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, transferId, error);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tcontext.data?.setTransferLoading(transferId, false);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseRefreshActionHandler.actionType = \"RefreshActionDefinition\";\n\n// Local storage context for eager table operations\ninterface LocalStorageContext {\n\t/** Parent transfer ID for storing new items in local table data */\n\tparentTransferId?: string;\n}\n\n/**\n * Handle transfer create - hook factory.\n *\n * Create behavior varies based on context:\n *\n * 1. **Eager components** (isEager=true):\n * - Validates data via validateCreateRelation API if relation is provided\n * - If validation fails, sets field errors via validation context (dialog stays open)\n * - If validation passes, returns data to caller (no REST create call)\n * - Caller (table/link) adds transfer to local __items array\n * - Transfer is persisted when parent is saved\n *\n * 2. **Lazy components** (isEager=false, default):\n * - Validates data via validateCreateRelation API\n * - If validation fails, sets field errors via validation context (dialog stays open)\n * - If validation passes, creates transfer via createRelation API\n * - BLOCKED if on a FORM page (forms save all data together)\n * - BLOCKED if on a VIEW page that is in edit mode (unsaved changes)\n *\n * After creation, optionally navigates to view page based on autoOpenAfterCreate.\n *\n * Supports both legacy callback mode and API mode.\n */\nexport const useCreateActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Get transfer from context or from data store using pageTransferId\n\t\t// For create forms, transfer data is stored in data store by GetTemplateActionHandler\n\t\tlet transfer = context.transfer as TransferStored | undefined;\n\t\tif (!transfer && context.data) {\n\t\t\tconst pageTransferId = (context as { pageTransferId?: string }).pageTransferId;\n\t\t\tif (pageTransferId) {\n\t\t\t\tconst stored = context.data.getSnapshot((state) => state.transfers.get(pageTransferId)?.data);\n\t\t\t\tif (stored) transfer = stored;\n\t\t\t}\n\t\t}\n\n\t\tif (!transfer) {\n\t\t\tthrow new Error(\"No transfer data to create\");\n\t\t}\n\n\t\tconst { isEager, pageType, isEditMode, isPageAction, validation, createDialog } = context;\n\n\t\t// For lazy components, check if create is allowed\n\t\t// Page-level actions (dialog footer buttons) are always allowed\n\t\tif (!isEager && !isPageAction) {\n\t\t\tif (pageType === \"FORM\") {\n\t\t\t\tthrow new Error(\"Create operation is not allowed on FORM pages. Save the form first.\");\n\t\t\t}\n\t\t\tif (pageType === \"VIEW\" && isEditMode) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Create operation is not allowed while the view has unsaved changes. Save or cancel changes first.\"\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Use pageTransferId if available (for dialogs), otherwise transfer.__identifier or \"new\"\n\t\tconst pageTransferId = (context as { pageTransferId?: string }).pageTransferId;\n\t\tconst transferId = pageTransferId ?? transfer.__identifier ?? \"new\";\n\n\t\t// React CreateAction: local check (requiredBy, range errors) before setIsLoading(true),\n\t\t// so a refused submit never leaves the page loading (and its buttons disabled) (E36)\n\t\tif (!passesLocalValidation(context.pageContainer, transfer, validation, context.translate)) {\n\t\t\treturn;\n\t\t}\n\t\tcontext.data?.setTransferLoading(transferId, true);\n\n\t\t// Clear any previous validation errors before attempting create\n\t\tvalidation?.clearErrors();\n\n\t\ttry {\n\t\t\tconst callbackContext = context as unknown as LegacyCallbacks &\n\t\t\t\tApiContext &\n\t\t\t\tCreateRelationContext &\n\t\t\t\tLocalStorageContext;\n\t\t\tconst { onCreate, onValidateCreate, api, relationMetadata, ownerTransfer, parentTransferId } = callbackContext;\n\n\t\t\t// Get relation from createDialog context or relationMetadata or action.ownerDataElement\n\t\t\t// Support both new format (relationMetadata.relation) and legacy format (relationMetadata as RelationType)\n\t\t\t// Priority: action.ownerDataElement is most authoritative (model-defined for this specific action),\n\t\t\t// then createDialog context (set by the dialog opener), then relationMetadata (legacy).\n\t\t\tlet relation: RelationType | undefined;\n\t\t\t// 1. Prefer action.ownerDataElement - it's the model-defined relation for this specific create action\n\t\t\t// (e.g., the form page's Create action points to \"stars\", not the parent \"galaxies\" access relation)\n\t\t\tif (action.ownerDataElement?.[\"@type\"] === \"RelationType\") {\n\t\t\t\trelation = action.ownerDataElement as RelationType;\n\t\t\t}\n\t\t\t// 2. Fall back to createDialog context (set by the dialog opener)\n\t\t\tif (!relation) {\n\t\t\t\trelation = createDialog?.relation as RelationType | undefined;\n\t\t\t}\n\t\t\t// 3. Fall back to relationMetadata\n\t\t\tif (!relation && relationMetadata) {\n\t\t\t\t// Check if relationMetadata has nested relation property\n\t\t\t\tif (\"relation\" in relationMetadata && relationMetadata.relation) {\n\t\t\t\t\trelation = relationMetadata.relation as RelationType;\n\t\t\t\t} else if (\"name\" in relationMetadata && relationMetadata.name) {\n\t\t\t\t\t// Legacy format: relationMetadata is the relation itself\n\t\t\t\t\trelation = relationMetadata as unknown as RelationType;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Get targetType from relation.target or actionDefinition.targetType\n\t\t\tconst targetType = relation?.target ?? action.actionDefinition.targetType;\n\t\t\tif (!targetType) {\n\t\t\t\tthrow new Error(\"No target type for create\");\n\t\t\t}\n\t\t\tconst dialogOwnerEntity = (createDialog?.ownerTransfer as TransferStored) ?? ownerTransfer;\n\n\t\t\tlet createdEntity: TransferStored;\n\n\t\t\t// --- VALIDATION STEP (EAGER MODE ONLY) ---\n\t\t\t// For eager mode, validate before adding to local store since there's no immediate server call\n\t\t\t// For lazy mode, skip separate validation - the createRelation API will validate during create\n\t\t\t// and return validation errors which we'll handle there\n\t\t\tconst hasValidateCreateBehaviour = relation?.behaviours?.includes(RelationBehaviourType.VALIDATE_CREATE);\n\t\t\tconst canValidateCreate = relation?.isAccess || !!dialogOwnerEntity?.__signedIdentifier;\n\n\t\t\tif (isEager && hasValidateCreateBehaviour && canValidateCreate && api) {\n\t\t\t\ttry {\n\t\t\t\t\t// Call validateCreateRelation API (eager mode only)\n\t\t\t\t\tawait api.validateCreateRelation(relation!, dialogOwnerEntity, transfer);\n\t\t\t\t} catch (validationError) {\n\t\t\t\t\t// Check if it's a validation error with field-level feedback\n\t\t\t\t\tif (isValidationError(validationError)) {\n\t\t\t\t\t\t// Field errors + toast, like React's handleError (dialog stays open)\n\t\t\t\t\t\treportValidationError(validationError, context);\n\t\t\t\t\t\tthrow validationError;\n\t\t\t\t\t}\n\t\t\t\t\t// For other errors, re-throw as-is\n\t\t\t\t\tthrow validationError;\n\t\t\t\t}\n\t\t\t} else if (isEager && hasValidateCreateBehaviour && onValidateCreate && relation) {\n\t\t\t\t// Use legacy validation callback if provided (only if relation supports validation)\n\t\t\t\tconst fieldErrors = await onValidateCreate(transfer, relation, dialogOwnerEntity);\n\t\t\t\tif (fieldErrors && Object.keys(fieldErrors).length > 0) {\n\t\t\t\t\tvalidation?.setErrors(fieldErrors);\n\t\t\t\t\tthrow new Error(\"Validation failed\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// --- CREATE STEP ---\n\t\t\t// Eager mode: add to local store only, no REST call\n\t\t\tif (isEager) {\n\t\t\t\t// Generate a temporary client-side ID for tracking the new transfer\n\t\t\t\t// Note: __identifier is backend-assigned, so we use __tempId for frontend-created transfers\n\t\t\t\tconst tempId = `temp::${Date.now()}::${Math.random().toString(36).substring(2, 9)}`;\n\t\t\t\tcreatedEntity = {\n\t\t\t\t\t...transfer,\n\t\t\t\t\t__tempId: tempId, // Frontend-only temporary ID (not __identifier which is backend-assigned)\n\t\t\t\t\t__isNew: true, // Mark as new/unsaved\n\t\t\t\t};\n\n\t\t\t\t// Get parent context from createDialog (preferred) or legacy context\n\t\t\t\tconst eagerParentEntityId = createDialog?.parentTransferId ?? parentTransferId;\n\t\t\t\tconst eagerRelationName = createDialog?.relationName;\n\n\t\t\t\t// If we have a parent transfer ID, add the created transfer to the parent's data\n\t\t\t\tif (eagerParentEntityId && context.data) {\n\t\t\t\t\tconst parentData = context.data.getSnapshot((state) => state.transfers.get(eagerParentEntityId)?.data);\n\n\t\t\t\t\tif (eagerRelationName) {\n\t\t\t\t\t\t// Eager component embedded in VIEW page: add to parent transfer's relation property\n\t\t\t\t\t\tconst currentValue = parentData?.[eagerRelationName];\n\n\t\t\t\t\t\t// The model parser coerces `isCollection` to a boolean (parser.ts BOOLEAN_PROPERTIES).\n\t\t\t\t\t\tconst isCollection = relation?.isCollection === true;\n\t\t\t\t\t\tif (Array.isArray(currentValue)) {\n\t\t\t\t\t\t\t// Collection relation (Table) — append to array\n\t\t\t\t\t\t\tcontext.data.updateTransferFields(eagerParentEntityId, {\n\t\t\t\t\t\t\t\t[eagerRelationName]: [...currentValue, createdEntity],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else if (isPagedItems(currentValue)) {\n\t\t\t\t\t\t\t// Table relation data can retain the paged __items shape between nested dialogs.\n\t\t\t\t\t\t\tcontext.data.updateTransferFields(eagerParentEntityId, {\n\t\t\t\t\t\t\t\t[eagerRelationName]: {\n\t\t\t\t\t\t\t\t\t...currentValue,\n\t\t\t\t\t\t\t\t\t__items: [...currentValue.__items, createdEntity],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else if (isCollection) {\n\t\t\t\t\t\t\tcontext.data.updateTransferFields(eagerParentEntityId, {\n\t\t\t\t\t\t\t\t[eagerRelationName]: [createdEntity],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Single relation (Link) — set the field directly\n\t\t\t\t\t\t\tcontext.data.updateTransferFields(eagerParentEntityId, {\n\t\t\t\t\t\t\t\t[eagerRelationName]: createdEntity,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Fallback: add to __items array (legacy behavior for standalone tables)\n\t\t\t\t\t\tconst currentItems = relationItems(parentData, \"__items\");\n\t\t\t\t\t\tconst newItems = [...currentItems, createdEntity];\n\n\t\t\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\t\t\tcontext.data.updateTransferFields(eagerParentEntityId, {\n\t\t\t\t\t\t\t__items: newItems,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// For eager mode with onSubmitCreate callback, invoke it\n\t\t\t\tif (createDialog?.onSubmitCreate) {\n\t\t\t\t\tawait createDialog.onSubmitCreate(createdEntity);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Lazy mode: create via REST API\n\t\t\t\tif (onCreate) {\n\t\t\t\t\t// Use legacy callback if provided\n\t\t\t\t\tcreatedEntity = await onCreate(transfer, targetType);\n\t\t\t\t} else if (api && relation) {\n\t\t\t\t\t// Use API if available - pass the relation directly\n\t\t\t\t\t// Handle validation errors from create endpoint\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await api.createRelation(relation, dialogOwnerEntity, transfer);\n\t\t\t\t\t\tcreatedEntity = result.data;\n\t\t\t\t\t} catch (createError) {\n\t\t\t\t\t\t// Check if it's a validation error with field-level feedback\n\t\t\t\t\t\tif (isValidationError(createError)) {\n\t\t\t\t\t\t\t// Field errors + toast, like React's handleError (dialog stays open)\n\t\t\t\t\t\t\treportValidationError(createError, context);\n\t\t\t\t\t\t\tthrow createError;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// For other errors, re-throw as-is\n\t\t\t\t\t\tthrow createError;\n\t\t\t\t\t}\n\t\t\t\t} else if (!onCreate && !api) {\n\t\t\t\t\t// No callback or API - nothing to do\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"Create requires relation context. Provide relation in createDialog or relationMetadata in additionalContext.\"\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Close dialog with success result so caller can refresh\n\t\t\tif (context.closeDialog) {\n\t\t\t\t// The created transfer travels with the result so an opener (e.g. a\n\t\t\t\t// relation selector) can adopt it without re-querying.\n\t\t\t\tcontext.closeDialog({ type: \"created\", isEager: isEager ?? false, data: createdEntity });\n\t\t\t}\n\n\t\t\t// Navigate to view page with created transfer if autoOpenAfterCreate is enabled\n\t\t\t// CreateActionDefinition has autoOpenAfterCreate attribute (defaults to true based on meta-model)\n\t\t\tconst actionDef = action.actionDefinition as { autoOpenAfterCreate?: boolean };\n\t\t\tconst shouldAutoOpen = actionDef.autoOpenAfterCreate !== false; // Default true\n\n\t\t\tconst viewPage = action.targetPageDefinition;\n\t\t\t// Only auto-open for standalone (non-dialog) form pages. When the\n\t\t\t// create form is a dialog, the opener refreshes on close and the\n\t\t\t// created record must not hijack the navigation (matching the React\n\t\t\t// template, which returns to the calling table after create).\n\t\t\tif (shouldAutoOpen && viewPage && context.navigation && !isEager && !context.closeDialog) {\n\t\t\t\t// Only navigate for lazy (persisted) transfers\n\t\t\t\tcontext.navigation.replacePage(viewPage, { transfer: createdEntity });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// For validation errors, don't set transfer error (let validation context handle it)\n\t\t\tif (!isValidationError(error)) {\n\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, transferId, error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tcontext.data?.setTransferLoading(transferId, false);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseCreateActionHandler.actionType = \"CreateActionDefinition\";\n\n/**\n * Handle transfer update - hook factory.\n * Updates an existing transfer via REST API.\n * Supports both legacy callback mode and API mode.\n *\n * In eager mode (aggregated child transfers opened from an eager table):\n * - Skips REST API calls entirely\n * - Updates the parent transfer's relation array with the modified transfer data\n * - The actual persistence happens when the aggregate root (parent) is saved\n */\n/** React UpdateAction closes its dialog after a save only with `autoCloseOnSave`. */\nfunction closesOnSave(definition: ActionDefinition): boolean {\n\treturn \"autoCloseOnSave\" in definition && definition.autoCloseOnSave === true;\n}\n\nexport const useUpdateActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst contextEntity = context.transfer as TransferStored | undefined;\n\t\t// A row staged into an eager owner (React draft) has only the frontend `__tempId`.\n\t\tconst draftTempId = context.isEager && contextEntity?.__tempId;\n\t\tconst rawEntityId = contextEntity?.__identifier ?? contextEntity?.__signedIdentifier ?? draftTempId;\n\t\tif (!contextEntity || !rawEntityId) {\n\t\t\tthrow new Error(\"No transfer to update (missing identifier)\");\n\t\t}\n\n\t\t// For dialog dispatchers, context.transfer carries the original transfer identifiers\n\t\t// (e.g., from params.transfer), while the actual data is stored under the\n\t\t// dialog-specific pageTransferId (e.g., \"dialog::transfer::abc123\").\n\t\t// Prefer pageTransferId for data store lookups when available.\n\t\tconst pageTransferId = (context as { pageTransferId?: string }).pageTransferId;\n\t\tconst transferId = pageTransferId ?? rawEntityId;\n\n\t\t// Read the full transfer from the data store.\n\t\t// context.transfer may only contain identifiers (__identifier / __signedIdentifier)\n\t\t// because the dispatcher receives a minimal stub. The actual user-modified fields\n\t\t// are in the data store, populated by the initial refresh and updated by bindings.\n\t\tlet transfer: TransferStored | undefined;\n\t\tif (context.data) {\n\t\t\tconst stored = context.data.getSnapshot((state) => state.transfers.get(transferId)?.data);\n\t\t\tif (stored) transfer = stored;\n\t\t}\n\n\t\t// Fall back to context.transfer if data store lookup fails (e.g., legacy callback mode)\n\t\tif (!transfer) {\n\t\t\ttransfer = contextEntity;\n\t\t}\n\n\t\t// React UpdateAction: local check (requiredBy, range errors) before the request\n\t\tif (!passesLocalValidation(context.pageContainer, transfer, context.validation, context.translate)) {\n\t\t\treturn;\n\t\t}\n\n\t\tcontext.data?.setTransferLoading(transferId, true);\n\n\t\ttry {\n\t\t\tconst { isEager } = context;\n\t\t\tconst eagerContext = context as TypedActionHandlerContext & {\n\t\t\t\tparentTransferId?: string;\n\t\t\t\trelationName?: string;\n\t\t\t};\n\n\t\t\t// Eager mode: update parent transfer's local relation data, no REST call\n\t\t\tif (isEager) {\n\t\t\t\tconst { parentTransferId, relationName } = eagerContext;\n\n\t\t\t\tif (parentTransferId && relationName && context.data) {\n\t\t\t\t\tconst parentData = context.data.getSnapshot((state) => state.transfers.get(parentTransferId)?.data);\n\n\t\t\t\t\tif (parentData) {\n\t\t\t\t\t\tconst currentValue = (parentData as Record<string, unknown>)[relationName];\n\n\t\t\t\t\t\tif (Array.isArray(currentValue)) {\n\t\t\t\t\t\t\t// Collection relation (Table) — find and replace matching transfer in array\n\t\t\t\t\t\t\tconst updatedItems = currentValue.map((item: TransferStored) => {\n\t\t\t\t\t\t\t\tconst itemTempId = (item as { __tempId?: string }).__tempId;\n\t\t\t\t\t\t\t\tconst entityTempId = (transfer as { __tempId?: string }).__tempId;\n\n\t\t\t\t\t\t\t\tif (itemTempId && entityTempId && itemTempId === entityTempId) {\n\t\t\t\t\t\t\t\t\treturn { ...transfer! };\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (item.__identifier && item.__identifier === transfer!.__identifier) {\n\t\t\t\t\t\t\t\t\treturn { ...transfer! };\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (item.__signedIdentifier && item.__signedIdentifier === transfer!.__signedIdentifier) {\n\t\t\t\t\t\t\t\t\treturn { ...transfer! };\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn item;\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t\t\t\t[relationName]: updatedItems,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Single relation (Link) — replace the entire field value\n\t\t\t\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t\t\t\t[relationName]: { ...transfer! },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Reset the transfer in the data store (marks it as \"saved\" within the dialog)\n\t\t\t\tcontext.data?.setTransferData(transferId, transfer!);\n\n\t\t\t\t// Navigate back (close the dialog) after successful eager update\n\t\t\t\tcontext.navigation?.goBack();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Lazy mode: update via REST API\n\t\t\tconst targetType = resolveTargetClassType(action);\n\t\t\tif (!targetType) {\n\t\t\t\tthrow new Error(\"No target type for update\");\n\t\t\t}\n\n\t\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\t\tconst { onUpdate, api } = callbackContext;\n\n\t\t\tlet updatedEntity: TransferStored;\n\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onUpdate) {\n\t\t\t\tupdatedEntity = await onUpdate(transfer!, targetType);\n\t\t\t} else if (api) {\n\t\t\t\t// Use API if available - pass the ClassType directly\n\t\t\t\tconst response = await api.update(targetType, transfer!);\n\t\t\t\tupdatedEntity = response.data;\n\n\t\t\t\t// Refresh after successful update to get the complete transfer state\n\t\t\t\t// (the update response may only contain the masked subset of fields)\n\t\t\t\tconst refreshResponse = await api.refresh(targetType, updatedEntity);\n\t\t\t\tupdatedEntity = refreshResponse.data;\n\t\t\t} else {\n\t\t\t\t// No callback or API - nothing to do\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tcontext.data?.setTransferData(transferId, updatedEntity);\n\t\t\t// React UpdateAction: a successful save clears the field errors\n\t\t\tcontext.validation?.clearErrors();\n\t\t\t// React UpdateAction: a dialog closes only with autoCloseOnSave; otherwise it\n\t\t\t// stays open in view mode with the refreshed data.\n\t\t\tif (closesOnSave(action.actionDefinition) && context.closeDialog) {\n\t\t\t\tcontext.closeDialog({ type: \"updated\", data: updatedEntity });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (isValidationError(error)) {\n\t\t\t\t// React UpdateAction -> handleError: field errors + toast\n\t\t\t\tif (!maybeInterceptError(error, context.errorHandlerInterceptor)) {\n\t\t\t\t\treportValidationError(error, context);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, transferId, error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tcontext.data?.setTransferLoading(transferId, false);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseUpdateActionHandler.actionType = \"UpdateActionDefinition\";\n\n/**\n * Handle transfer delete - hook factory.\n * Deletes an transfer via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useDeleteActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\n\t\t// React DeleteAction: a draft dialog (opened from an eager row) hands the delete to\n\t\t// the owner, which drops the row from its relation; nothing is sent. A staged row is\n\t\t// identified by its `__tempId` (the draft view also carries a synthetic\n\t\t// `__identifier`, which the owner row does not have), a persisted one by its ids.\n\t\tconst { parentTransferId, relationName } = context;\n\t\tif (context.isEager && parentTransferId && relationName && context.data && transfer) {\n\t\t\tconst { __tempId: tempId, __identifier: targetId, __signedIdentifier: targetSigned } = transfer;\n\t\t\tif (!tempId && !targetId && !targetSigned) {\n\t\t\t\tthrow new Error(\"No transfer to delete (missing identifier)\");\n\t\t\t}\n\t\t\tconst isTarget = (item: TransferStored) =>\n\t\t\t\ttempId\n\t\t\t\t\t? item.__tempId === tempId\n\t\t\t\t\t: (!!targetSigned && item.__signedIdentifier === targetSigned) ||\n\t\t\t\t\t\t(!!targetId && item.__identifier === targetId);\n\t\t\tconst parentData = context.data.getSnapshot((state) => state.transfers.get(parentTransferId)?.data);\n\t\t\tconst currentValue = parentData?.[relationName];\n\t\t\tif (Array.isArray(currentValue)) {\n\t\t\t\t// React OpenPageAction `result === 'delete'`: an unknown row leaves the list as is\n\t\t\t\tif (!currentValue.some(isTarget)) return;\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t[relationName]: currentValue.filter((item) => !isTarget(item)),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, { [relationName]: null });\n\t\t\t}\n\t\t\tcontext.navigation?.goBack();\n\t\t\treturn;\n\t\t}\n\n\t\tconst transferId = transfer?.__identifier ?? transfer?.__signedIdentifier;\n\t\tif (!transferId) {\n\t\t\tthrow new Error(\"No transfer to delete (missing identifier)\");\n\t\t}\n\n\t\tcontext.data?.setTransferLoading(transferId, true);\n\n\t\ttry {\n\t\t\tconst targetType = resolveTargetClassType(action);\n\t\t\tif (!targetType) {\n\t\t\t\tthrow new Error(\"No target type for delete\");\n\t\t\t}\n\n\t\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\t\tconst { onDelete, api } = callbackContext;\n\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onDelete) {\n\t\t\t\tawait onDelete(transferId, targetType);\n\t\t\t} else if (api) {\n\t\t\t\t// Use API if available - pass the ClassType directly\n\t\t\t\tawait api.delete(targetType, transfer!);\n\t\t\t} else {\n\t\t\t\t// No callback or API - nothing to do\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Clear transfer from store. React DeleteAction: a view dialog closes with\n\t\t\t// `onSubmit(target, 'delete')` and its opener refreshes; a page navigates back.\n\t\t\tcontext.data?.clearTransfer(transferId);\n\t\t\tif (context.closeDialog) {\n\t\t\t\tcontext.closeDialog({ type: \"deleted\", data: transfer });\n\t\t\t} else {\n\t\t\t\tcontext.navigation?.goBack();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleCrudError(context.errorHandlerInterceptor, context.data, transferId, error);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseDeleteActionHandler.actionType = \"DeleteActionDefinition\";\n\n/**\n * Handle bulk delete - hook factory.\n * Deletes multiple selected transfers via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useBulkDeleteActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst selectedRows = context.selectedRows as TransferStored[] | undefined;\n\t\tif (!selectedRows || selectedRows.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type for bulk delete\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onBulkDelete, api } = callbackContext;\n\n\t\tconst transferIds = selectedRows\n\t\t\t.map((row) => row.__identifier ?? row.__signedIdentifier)\n\t\t\t.filter(Boolean) as string[];\n\n\t\t// Use legacy callback if provided\n\t\tif (onBulkDelete) {\n\t\t\tawait onBulkDelete(transferIds, targetType);\n\t\t} else if (api) {\n\t\t\t// Use API if available - pass the ClassType directly\n\t\t\t// Delete all selected transfers\n\t\t\tconst deletePromises = selectedRows\n\t\t\t\t.filter((row) => row.__signedIdentifier)\n\t\t\t\t.map((row) => api.delete(targetType, row));\n\n\t\t\tawait Promise.all(deletePromises);\n\t\t} else {\n\t\t\t// No callback or API - nothing to do\n\t\t\treturn;\n\t\t}\n\n\t\t// Clear deleted transfers from store\n\t\tfor (const rowId of transferIds) {\n\t\t\tcontext.data?.clearTransfer(rowId);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseBulkDeleteActionHandler.actionType = \"BulkDeleteActionDefinition\";\n\n/**\n * Handle single row delete from table - hook factory.\n * Deletes a single transfer from a table row via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useRowDeleteActionHandler: ActionHandlerHookWithMeta = Object.assign(\n\t(action: Action) => createRowDeleteHandler(action),\n\t{ actionType: \"RowDeleteActionDefinition\" as const }\n);\n\n/** Row delete handler for a row button, from the fields it reads (no page `Action` needed). */\nexport function createRowDeleteHandler(action: RowActionInput) {\n\treturn async (context: TypedActionHandlerContext): Promise<ActionResult> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = transfer?.__identifier ?? transfer?.__signedIdentifier;\n\n\t\tconst eagerContext = context as unknown as {\n\t\t\tisEager?: boolean;\n\t\t\tparentTransferId?: string;\n\t\t\trelationName?: string;\n\t\t};\n\t\tconst { isEager, parentTransferId, relationName } = eagerContext;\n\n\t\t// Eager mode: remove transfer from parent's local data store\n\t\tif (isEager && parentTransferId && context.data) {\n\t\t\tconst parentData = context.data.getSnapshot((state) => state.transfers.get(parentTransferId)?.data);\n\n\t\t\tif (relationName) {\n\t\t\t\tconst currentValue = (parentData as any)?.[relationName];\n\n\t\t\t\tif (Array.isArray(currentValue)) {\n\t\t\t\t\t// Collection relation (Table) — remove matching transfer from array\n\t\t\t\t\tconst newItems = currentValue.filter((item: TransferStored) => {\n\t\t\t\t\t\tconst itemId = item.__identifier ?? item.__signedIdentifier ?? (item as any).__tempId;\n\t\t\t\t\t\tconst targetId = transferId ?? (transfer as any)?.__tempId;\n\t\t\t\t\t\treturn itemId !== targetId;\n\t\t\t\t\t});\n\n\t\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t\t[relationName]: newItems,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// Single relation (Link) — set the field to null\n\t\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t\t[relationName]: null,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Fallback: remove from __items array\n\t\t\t\tconst currentItems = relationItems(parentData, \"__items\");\n\t\t\t\tconst newItems = currentItems.filter((item) => {\n\t\t\t\t\tconst itemId = item.__identifier ?? item.__signedIdentifier ?? (item as any).__tempId;\n\t\t\t\t\tconst targetId = transferId ?? (transfer as any)?.__tempId;\n\t\t\t\t\treturn itemId !== targetId;\n\t\t\t\t});\n\n\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t__items: newItems,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Lazy mode: delete via REST API\n\t\tif (!transferId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type for row delete\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onRowDelete, api } = callbackContext;\n\n\t\t// Use legacy callback if provided\n\t\tif (onRowDelete) {\n\t\t\tawait onRowDelete(transferId, targetType);\n\t\t} else if (api) {\n\t\t\t// Use API if available - pass the ClassType directly\n\t\t\tawait api.delete(targetType, transfer!);\n\t\t} else {\n\t\t\t// No callback or API - nothing to do\n\t\t\treturn;\n\t\t}\n\n\t\t// Clear transfer from store\n\t\tcontext.data?.clearTransfer(transferId);\n\t};\n}\n\n/**\n * Get template for new transfer - hook factory.\n * Fetches default values for a new transfer via REST API.\n * Supports both legacy callback mode and API mode.\n *\n * Stores template data using pageTransferId from context (if available) or \"new\" as fallback.\n * This ensures the form bindings can find the data at the correct transfer ID.\n */\nexport const useGetTemplateActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type for get template\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onGetTemplate, api } = callbackContext;\n\n\t\tlet template: TransferStored;\n\n\t\t// Use legacy callback if provided\n\t\tif (onGetTemplate) {\n\t\t\ttemplate = await onGetTemplate(targetType);\n\t\t} else if (api) {\n\t\t\t// Use API if available - pass the ClassType directly\n\t\t\tconst response = await api.getTemplate(targetType);\n\t\t\ttemplate = response.data;\n\t\t} else {\n\t\t\tthrow new Error(\"API not available in context\");\n\t\t}\n\n\t\t// Store template using pageTransferId from context, fallback to \"new\"\n\t\t// This ensures form bindings can find the data at the correct transfer ID\n\t\tconst transferId = (context as { pageTransferId?: string }).pageTransferId ?? \"new\";\n\t\tcontext.data?.setTransferData(transferId, template);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseGetTemplateActionHandler.actionType = \"GetTemplateActionDefinition\";\n","import { type ActionResult, type ClassType, type RelationType, resolveTransferId } from \"@judo/model-api\";\nimport type { IJudoRestApi } from \"../../api/i-judo-rest-api\";\nimport { type TransferStored, relationItems } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, RowActionInput, TypedActionHandlerContext } from \"../../types\";\n\n// Interface for API context - will be provided via context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Interface for relation context - provides relation metadata\ninterface RelationContext {\n\townerTransfer?: TransferStored;\n\townerClassType?: ClassType;\n\trelation?: RelationType;\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonSet?: (ownerId: string, relationName: string, targetId: string) => Promise<void>;\n\tonUnset?: (transferId: string, relationName: string) => Promise<void>;\n\tonAdd?: (ownerId: string, relationName: string, targetIds: string[]) => Promise<void>;\n\tonRemove?: (ownerId: string, relationName: string, targetIds: string[]) => Promise<void>;\n\tonBulkRemove?: (ownerId: string, relationName: string, targetIds: string[]) => Promise<void>;\n\tonClear?: (transferId: string, relationName: string) => Promise<void>;\n\tonRefreshRelation?: (transferId: string, relationName: string) => Promise<void>;\n\tonFilterRelation?: (relationName: string) => void;\n}\n\n/**\n * Get RelationType from context.\n */\nfunction getRelation(relationContext: RelationContext, action: Pick<Action, \"ownerDataElement\">): RelationType | null {\n\tif (relationContext.relation) {\n\t\treturn relationContext.relation;\n\t}\n\t// Check if action has a relation in ownerDataElement\n\tconst ownerDataElement = action.ownerDataElement;\n\tif (ownerDataElement && ownerDataElement[\"@type\"] === \"RelationType\") {\n\t\treturn ownerDataElement as RelationType;\n\t}\n\treturn null;\n}\n\n/**\n * Handle relation set (single) - hook factory.\n * Sets a single-valued relation to a selected transfer.\n * Supports both legacy callback mode and API mode.\n */\nexport const useSetActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst relationContext = context as unknown as RelationContext & {\n\t\t\tselectedEntity?: TransferStored;\n\t\t} & ApiContext &\n\t\t\tLegacyCallbacks;\n\n\t\tconst { ownerTransfer, selectedEntity, api, onSet } = relationContext;\n\t\tconst { isEager, parentTransferId, relationName: eagerRelationName } = context;\n\n\t\tif (!ownerTransfer || !selectedEntity) {\n\t\t\tthrow new Error(\"Missing owner or selected transfer for set\");\n\t\t}\n\n\t\tif (isEager && parentTransferId && eagerRelationName && context.data) {\n\t\t\tcontext.data.updateTransferFields(parentTransferId, { [eagerRelationName]: selectedEntity });\n\t\t\tcontext.closeDialog?.({ type: \"selected\", data: selectedEntity });\n\t\t\treturn;\n\t\t}\n\n\t\tconst ownerId = resolveTransferId(ownerTransfer);\n\t\tconst selectedId = resolveTransferId(selectedEntity);\n\n\t\tif (!ownerId || !selectedId) {\n\t\t\tthrow new Error(\"Missing transfer identifiers for set\");\n\t\t}\n\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onSet) {\n\t\t\tawait onSet(ownerId, relationName, selectedId);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(relationContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for set action\");\n\t\t\t}\n\t\t\tawait api.setRelation(relation, ownerTransfer, selectedEntity);\n\t\t}\n\n\t\tcontext.closeDialog?.({ type: \"selected\", data: selectedEntity });\n\t};\n}) as ActionHandlerHookWithMeta;\nuseSetActionHandler.actionType = \"SetActionDefinition\";\n\n/**\n * Handle relation unset - hook factory.\n * Clears a single-valued relation.\n * Supports both legacy callback mode and API mode.\n */\nexport const useUnsetActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = resolveTransferId(transfer);\n\t\tif (!transferId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext & RelationContext;\n\t\tconst { onUnset, api } = callbackContext;\n\n\t\t// Use legacy callback if provided\n\t\tif (onUnset) {\n\t\t\tawait onUnset(transferId, relationName);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(callbackContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for unset action\");\n\t\t\t}\n\t\t\tawait api.unsetRelation(relation, transfer!);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseUnsetActionHandler.actionType = \"UnsetActionDefinition\";\n\n/**\n * Handle relation add (multi) - hook factory.\n * Adds selected transfers to a collection relation.\n * Supports both legacy callback mode and API mode.\n */\nexport const useAddActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst addContext = context as unknown as RelationContext & {\n\t\t\tselectedEntities?: TransferStored[];\n\t\t} & ApiContext &\n\t\t\tLegacyCallbacks;\n\n\t\tconst { ownerTransfer, selectedEntities, api, onAdd } = addContext;\n\t\tconst { isEager, parentTransferId, relationName: eagerRelationName } = context;\n\n\t\tif (!ownerTransfer || !selectedEntities?.length) {\n\t\t\tthrow new Error(\"Missing transfers for add\");\n\t\t}\n\n\t\tif (isEager && parentTransferId && eagerRelationName && context.data) {\n\t\t\tconst parentData = context.data.getSnapshot((state) => state.transfers.get(parentTransferId)?.data);\n\t\t\tconst currentItems = relationItems(parentData, eagerRelationName);\n\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t[eagerRelationName]: [...currentItems, ...selectedEntities],\n\t\t\t});\n\t\t\tcontext.closeDialog?.({ type: \"selected\", data: selectedEntities });\n\t\t\treturn;\n\t\t}\n\n\t\tconst ownerId = resolveTransferId(ownerTransfer);\n\t\tif (!ownerId) {\n\t\t\tthrow new Error(\"Missing owner transfer identifier for add\");\n\t\t}\n\n\t\tconst selectedIds = selectedEntities.flatMap((e) => resolveTransferId(e) || []);\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onAdd) {\n\t\t\tawait onAdd(ownerId, relationName, selectedIds);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(addContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for add action\");\n\t\t\t}\n\t\t\tawait api.addToRelation(relation, ownerTransfer, selectedEntities);\n\t\t}\n\n\t\tcontext.closeDialog?.({ type: \"selected\", data: selectedEntities });\n\t};\n}) as ActionHandlerHookWithMeta;\nuseAddActionHandler.actionType = \"AddActionDefinition\";\n\n/**\n * Handle relation remove - hook factory.\n * Removes a single transfer from a collection relation.\n * Supports both legacy callback mode and API mode.\n */\nexport const useRemoveActionHandler: ActionHandlerHookWithMeta = Object.assign(\n\t(action: Action) => createRemoveRowHandler(action),\n\t{ actionType: \"RemoveActionDefinition\" as const }\n);\n\n/** Remove handler for a row button, from the fields it reads (no page `Action` needed). */\nexport function createRemoveRowHandler(action: RowActionInput) {\n\treturn async (context: TypedActionHandlerContext): Promise<ActionResult> => {\n\t\tconst removeContext = context as unknown as RelationContext & ApiContext & LegacyCallbacks;\n\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = resolveTransferId(transfer);\n\n\t\t// Eager mode: remove transfer from parent's local data store\n\t\tconst { isEager, parentTransferId, relationName: eagerRelationName } = context;\n\t\tif (isEager && parentTransferId && context.data) {\n\t\t\tconst parentData = context.data.getSnapshot((state) => state.transfers.get(parentTransferId)?.data);\n\n\t\t\tif (eagerRelationName) {\n\t\t\t\tconst currentItems = relationItems(parentData, eagerRelationName);\n\t\t\t\tconst newItems = currentItems.filter((item) => {\n\t\t\t\t\tconst itemId = resolveTransferId(item);\n\t\t\t\t\tconst targetId = transferId;\n\t\t\t\t\treturn itemId !== targetId;\n\t\t\t\t});\n\n\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t[eagerRelationName]: newItems,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst currentItems = relationItems(parentData, \"__items\");\n\t\t\t\tconst newItems = currentItems.filter((item) => {\n\t\t\t\t\tconst itemId = resolveTransferId(item);\n\t\t\t\t\tconst targetId = transferId;\n\t\t\t\t\treturn itemId !== targetId;\n\t\t\t\t});\n\n\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t__items: newItems,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Lazy mode: remove via REST API\n\t\tconst { ownerTransfer, api, onRemove } = removeContext;\n\n\t\tconst ownerId = resolveTransferId(ownerTransfer);\n\n\t\tif (!ownerId || !transferId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onRemove) {\n\t\t\tawait onRemove(ownerId, relationName, [transferId]);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(removeContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for remove action\");\n\t\t\t}\n\t\t\tawait api.removeFromRelation(relation, ownerTransfer!, [transfer!]);\n\t\t}\n\t};\n}\n\n/**\n * Handle bulk remove - hook factory.\n * Removes multiple selected transfers from a collection relation.\n * Supports both legacy callback mode and API mode.\n */\nexport const useBulkRemoveActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst removeContext = context as unknown as RelationContext & ApiContext & LegacyCallbacks;\n\n\t\tconst selectedRows = context.selectedRows as TransferStored[] | undefined;\n\n\t\tif (!selectedRows?.length) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Eager mode: remove transfers from parent's local data store\n\t\tconst { isEager, parentTransferId, relationName: eagerRelationName } = context;\n\t\tif (isEager && parentTransferId && context.data) {\n\t\t\t// Collect IDs of transfers to remove (support both backend and frontend IDs)\n\t\t\tconst removeIds = new Set(selectedRows.map((e) => resolveTransferId(e)).filter(Boolean));\n\n\t\t\tconst parentData = context.data.getSnapshot((state) => state.transfers.get(parentTransferId)?.data);\n\n\t\t\tif (eagerRelationName) {\n\t\t\t\tconst currentItems = relationItems(parentData, eagerRelationName);\n\t\t\t\tconst newItems = currentItems.filter((item) => {\n\t\t\t\t\tconst itemId = resolveTransferId(item);\n\t\t\t\t\treturn !removeIds.has(itemId);\n\t\t\t\t});\n\n\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t[eagerRelationName]: newItems,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst currentItems = relationItems(parentData, \"__items\");\n\t\t\t\tconst newItems = currentItems.filter((item) => {\n\t\t\t\t\tconst itemId = resolveTransferId(item);\n\t\t\t\t\treturn !removeIds.has(itemId);\n\t\t\t\t});\n\n\t\t\t\t// Use updateTransferFields to preserve dirty tracking and trigger edit mode\n\t\t\t\tcontext.data.updateTransferFields(parentTransferId, {\n\t\t\t\t\t__items: newItems,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Lazy mode: remove via REST API\n\t\tconst { ownerTransfer, api, onBulkRemove } = removeContext;\n\n\t\tconst ownerId = resolveTransferId(ownerTransfer);\n\n\t\tif (!ownerId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst selectedIds = selectedRows.flatMap((e) => resolveTransferId(e) || []);\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onBulkRemove) {\n\t\t\tawait onBulkRemove(ownerId, relationName, selectedIds);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(removeContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for bulk remove action\");\n\t\t\t}\n\t\t\tconst entitiesToRemove = selectedRows.filter((row) => row.__signedIdentifier);\n\t\t\tawait api.removeFromRelation(relation, ownerTransfer!, entitiesToRemove);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseBulkRemoveActionHandler.actionType = \"BulkRemoveActionDefinition\";\n\n/**\n * Handle relation clear - hook factory.\n * Clears all transfers from a collection relation (unset for collection).\n * Supports both legacy callback mode and API mode.\n */\nexport const useClearActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = resolveTransferId(transfer);\n\t\tif (!transferId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst callbackContext = context as unknown as ApiContext & RelationContext & LegacyCallbacks;\n\t\tconst { api, onClear } = callbackContext;\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onClear) {\n\t\t\tawait onClear(transferId, relationName);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(callbackContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for clear action\");\n\t\t\t}\n\t\t\t// Collection relations: set to empty array; single-valued: unset\n\t\t\tif (relation.isCollection !== false) {\n\t\t\t\tawait api.setRelation(relation, transfer!, []);\n\t\t\t} else {\n\t\t\t\tawait api.unsetRelation(relation, transfer!);\n\t\t\t}\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseClearActionHandler.actionType = \"ClearActionDefinition\";\n\n/**\n * Handle relation refresh - hook factory.\n * Refreshes/reloads a relation's data.\n * Supports both legacy callback mode and API mode.\n */\nexport const useRefreshRelationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\tconst transferId = resolveTransferId(transfer);\n\t\tif (!transferId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst callbackContext = context as unknown as ApiContext & RelationContext & LegacyCallbacks;\n\t\tconst { api, onRefreshRelation } = callbackContext;\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onRefreshRelation) {\n\t\t\tawait onRefreshRelation(transferId, relationName);\n\t\t} else if (api) {\n\t\t\t// Use API if available\n\t\t\tconst relation = getRelation(callbackContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for refresh action\");\n\t\t\t}\n\t\t\t// For collection relations, list; for single, get\n\t\t\tif (relation.isCollection !== false) {\n\t\t\t\tawait api.listRelation(relation, transfer!);\n\t\t\t} else {\n\t\t\t\tawait api.getRelation(relation, transfer!);\n\t\t\t}\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseRefreshRelationActionHandler.actionType = \"RefreshRelationActionDefinition\";\n\n/**\n * Handle relation filter - hook factory.\n * Applies a filter to a relation (UI-side operation, no REST call).\n */\nexport const useFilterRelationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Filter is a UI-side operation - signal the intent\n\t\tconst filterContext = context as unknown as LegacyCallbacks;\n\n\t\tif (filterContext.onFilterRelation) {\n\t\t\tfilterContext.onFilterRelation(action.actionDefinition.name ?? \"\");\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseFilterRelationActionHandler.actionType = \"FilterRelationActionDefinition\";\n","import { type ClassType, type RelationType, typeSimpleName } from \"@judo/model-api\";\nimport type { IJudoRestApi } from \"../../api/i-judo-rest-api\";\nimport type { TransferStored } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext } from \"../../types\";\n\n// Interface for API context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Interface for relation context\ninterface RelationContext {\n\townerTransfer?: TransferStored;\n\townerClassType?: ClassType;\n\trelation?: RelationType;\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonFilterRequest?: () => void;\n\tonExport?: (classType: ClassType) => Promise<void>;\n\tonInlineCreateRow?: (action: Action) => Promise<void> | void;\n}\n\n/**\n * Get relation from context.\n */\nfunction getRelation(relationContext: RelationContext): RelationType | null {\n\treturn relationContext.relation ?? null;\n}\n\n/**\n * Handle filter action (opens filter dialog) - hook factory.\n * Filter is primarily a UI operation - signals filter intent.\n */\nexport const useFilterActionHandler = ((_action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Filter handling is typically done by Table component\n\t\t// This handler just signals filter intent\n\t\tconst filterContext = context as unknown as LegacyCallbacks;\n\t\tfilterContext.onFilterRequest?.();\n\t};\n}) as ActionHandlerHookWithMeta;\nuseFilterActionHandler.actionType = \"FilterActionDefinition\";\n\n/**\n * Handle export action - hook factory.\n * Exports relation data as a downloadable file via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useExportActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst targetType = action.actionDefinition.targetType as ClassType | undefined;\n\t\tif (!targetType) {\n\t\t\tthrow new Error(\"No target type for export\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as ApiContext & RelationContext & LegacyCallbacks;\n\t\tconst { onExport, api } = callbackContext;\n\n\t\t// Use legacy callback if provided\n\t\tif (onExport) {\n\t\t\tawait onExport(targetType);\n\t\t\treturn;\n\t\t}\n\n\t\t// Use API if available\n\t\tif (api) {\n\t\t\tconst relation = getRelation(callbackContext);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for export action\");\n\t\t\t}\n\n\t\t\tconst transfer = context.transfer as TransferStored | undefined;\n\t\t\tconst response = await api.exportRelation(relation, transfer);\n\t\t\tconst blob = response.data;\n\n\t\t\t// Download file\n\t\t\tconst url = URL.createObjectURL(blob);\n\t\t\tconst a = document.createElement(\"a\");\n\t\t\ta.href = url;\n\t\t\ta.download = `export_${typeSimpleName(targetType)}_${Date.now()}.csv`;\n\t\t\ta.click();\n\t\t\tURL.revokeObjectURL(url);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseExportActionHandler.actionType = \"ExportActionDefinition\";\n\n/**\n * Handle inline row creation in table - hook factory.\n * Inline creation is primarily a UI operation.\n */\nexport const useInlineCreateRowActionHandler = ((_action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Signal inline create intent (UI-side operation)\n\t\tconst inlineContext = context as unknown as LegacyCallbacks;\n\t\tawait inlineContext.onInlineCreateRow?.(_action);\n\t};\n}) as ActionHandlerHookWithMeta;\nuseInlineCreateRowActionHandler.actionType = \"InlineCreateRowActionDefinition\";\n","/** A parsed JSON object (not null, not an array): an open attribute bag such as a fault's `details`. */\nexport function isJsonObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { isJsonObject } from \"./json-object\";\n\n/**\n * Error thrown for a non-OK response that is not a validation error.\n * Keeps the status and the parsed body (JSON, else the raw text) for typed handling.\n */\nexport class HttpError extends Error {\n\treadonly status: number;\n\treadonly body: unknown;\n\n\tconstructor(status: number, bodyText: string) {\n\t\tsuper(`HTTP ${status}: ${bodyText}`);\n\t\tthis.name = \"HttpError\";\n\t\tthis.status = status;\n\t\tthis.body = parseBody(bodyText);\n\t}\n}\n\nfunction parseBody(text: string): unknown {\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch {\n\t\treturn text;\n\t}\n}\n\n/** A modeled operation fault: fault type FQ name and its attribute values. */\nexport interface OperationFault {\n\tfaultKey: string;\n\t/** The fault's attribute values: open data, its attributes depend on the modeled fault type. */\n\tpayload: Record<string, unknown>;\n}\n\n/** HTTP status of a modeled operation fault (React `error-handling.ts.hbs` case 422). */\nexport const OPERATION_FAULT_STATUS = 422;\n\n/**\n * Read a modeled operation fault from an error: a 422 whose body is\n * `{\"<FQ fault type>\": {<attr>: <value>}}`. Like React, the first body key is the fault.\n */\nexport function getOperationFault(error: unknown): OperationFault | undefined {\n\tif (!(error instanceof HttpError) || error.status !== OPERATION_FAULT_STATUS) return;\n\tconst body = error.body;\n\tif (!isJsonObject(body)) return;\n\tconst [faultKey] = Object.keys(body);\n\tif (faultKey === undefined) return;\n\tconst payload = body[faultKey];\n\treturn { faultKey, payload: isJsonObject(payload) ? payload : {} };\n}\n","import type {\n\tCallOperationActionDefinition as CallOpDef,\n\tClassType,\n\tOperationType,\n\tPageDefinition,\n} from \"@judo/model-api\";\nimport type { IJudoRestApi, OperationInfo } from \"../../api/i-judo-rest-api\";\nimport { getOperationFault } from \"../../api/operation-fault\";\nimport type { TransferStored, ValidationError } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext } from \"../../types\";\nimport { maybeInterceptError } from \"../../lifecycle/error-interceptor\";\nimport { passesLocalValidation, reportValidationError } from \"../validation-feedback\";\n\n// Interface for API context - will be provided via context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n/**\n * Helper to check if an error is a ValidationError (400 response).\n */\nfunction isValidationError(error: unknown): error is ValidationError {\n\treturn error !== null && typeof error === \"object\" && (error as { name?: string }).name === \"ValidationError\";\n}\n\n/**\n * Helper to check if an error has a specific HTTP status code.\n */\nfunction hasStatus(error: unknown, ...statuses: number[]): boolean {\n\tif (error !== null && typeof error === \"object\") {\n\t\tconst status = (error as { status?: number }).status;\n\t\treturn status !== undefined && statuses.includes(status);\n\t}\n\treturn false;\n}\n\n/**\n * Handle operation errors with appropriate notifications.\n * - 400: Validation error toast + set field errors\n * - 422: Operation fault dialog (when a presenter is in the context)\n * - 401/403: Access denied toast\n * - Other 4xx/5xx: Generic error toast\n */\nfunction handleOperationError(error: unknown, operationName: string, context: TypedActionHandlerContext): void {\n\tconst { notifications } = context;\n\t// Custom error handler interceptor takes priority over default handling.\n\tif (maybeInterceptError(error, context.errorHandlerInterceptor, { key: operationName })) {\n\t\treturn;\n\t}\n\tconst fault = getOperationFault(error);\n\tif (isValidationError(error)) {\n\t\t// 400 - field errors + toast, like React's handleError\n\t\treportValidationError(error, context);\n\t} else if (fault && context.showOperationFault) {\n\t\t// 422 - modeled operation fault: React opens the fault dialog, no toast\n\t\tcontext.showOperationFault(fault);\n\t} else if (hasStatus(error, 401, 403)) {\n\t\t// 401/403 - Access denied\n\t\tnotifications?.error(`Access denied: You don't have permission to execute ${operationName}`);\n\t} else if (hasStatus(error, 404)) {\n\t\t// 404 - Not found\n\t\tnotifications?.error(`Resource not found for ${operationName}`);\n\t} else {\n\t\t// Other errors (5xx, network, etc.)\n\t\tconst message = error instanceof Error ? error.message : \"Unknown error\";\n\t\tnotifications?.error(`Operation ${operationName} failed: ${message}`);\n\t}\n}\n\n/**\n * Open operation output page/dialog if action has a target page and operation returned data.\n * Uses `navigateTo` for full-page output or `openDialog` when the target page has `openInDialog=true`.\n */\nfunction openOperationOutputPage(\n\taction: Action,\n\tresult: TransferStored | undefined,\n\toperation: OperationType,\n\tcontext: TypedActionHandlerContext\n): void {\n\t// Check if operation returned data and action has a target page for the output\n\tconst targetPage = action.targetPageDefinition as PageDefinition | undefined;\n\tif (!result || !targetPage) {\n\t\treturn;\n\t}\n\n\t// Determine if output is mapped (has lifecycle) based on operation.output.behaviours\n\tconst outputParam = operation.output;\n\tconst behaviours = (outputParam as { behaviours?: string[] } | undefined)?.behaviours ?? [];\n\tconst isMappedOutput = behaviours.some((b) => [\"UPDATE\", \"DELETE\", \"REFRESH\"].includes(b));\n\n\tconst params = {\n\t\ttransfer: result,\n\t\tisOperationOutput: true,\n\t\tisMappedOutput,\n\t};\n\n\t// Check PageDefinition.openInDialog to decide between dialog and page navigation\n\tif (String(targetPage.openInDialog) === \"true\") {\n\t\tcontext.navigation?.openDialog(targetPage, params);\n\t} else {\n\t\tcontext.navigation?.navigateTo(targetPage, params);\n\t}\n}\n\n/**\n * Trigger a full page refresh after a successful operation.\n * Calls the refreshPage callback provided by ViewContainerRenderer\n * via additionalContext. This causes the transfer data AND all embedded\n * tables to re-fetch their data.\n */\nfunction triggerPageRefresh(context: TypedActionHandlerContext): void {\n\tconst { refreshPage } = context;\n\trefreshPage?.();\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonCallOperation?: (\n\t\toperation: OperationType,\n\t\towner: TransferStored | undefined,\n\t\ttarget: TransferStored | undefined\n\t) => Promise<unknown>;\n\tonBulkCallOperation?: (operation: OperationType, transfers: TransferStored[]) => Promise<void>;\n\tonInputFormCallOperation?: (\n\t\toperation: OperationType,\n\t\ttransfer: TransferStored | undefined,\n\t\tinputData: TransferStored\n\t) => Promise<unknown>;\n\tonInputSelectorCallOperation?: (\n\t\toperation: OperationType,\n\t\ttransfer: TransferStored | undefined,\n\t\tselectedEntity: TransferStored | null\n\t) => Promise<unknown>;\n\tonParameterlessCallOperation?: (operation: OperationType, transfer: TransferStored | undefined) => Promise<unknown>;\n}\n\n/**\n * Convert OperationType to OperationInfo for the REST API.\n */\nfunction toOperationInfo(operation: OperationType): OperationInfo {\n\treturn {\n\t\tname: operation.name,\n\t\tisStatic: operation.operationType === \"STATIC\",\n\t\tisMapped: operation.operationType === \"MAPPED\",\n\t\thasInput: !!operation.input,\n\t\tinputType: operation.input?.target,\n\t};\n}\n\n/**\n * Handle operation calls - hook factory.\n * Calls a bound operation via REST API.\n * Supports both legacy callback mode and API mode.\n * Opens output dialog if operation returns data and action has targetPageDefinition.\n * Shows success toast on success, error toast on failure.\n */\nexport const useCallOperationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Cast actionDefinition to CallOperationActionDefinition to access operation\n\t\tconst opDef = action.actionDefinition as CallOpDef;\n\t\tconst operation = opDef.operation as OperationType | undefined;\n\t\tif (!operation) {\n\t\t\tthrow new Error(\"No operation defined for CallOperationAction\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onCallOperation, api } = callbackContext;\n\t\tconst { notifications } = context;\n\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\n\t\ttry {\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onCallOperation) {\n\t\t\t\tconst result = await onCallOperation(operation, transfer, transfer);\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, result as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\t// Get the owner ClassType - either from actionDefinition.targetType or operation's eContainer\n\t\t\t\tconst ownerType = (opDef.targetType ?? operation.eContainer) as ClassType | undefined;\n\t\t\t\tif (!ownerType) {\n\t\t\t\t\tthrow new Error(\"No owner type for operation call\");\n\t\t\t\t}\n\n\t\t\t\tconst operationInfo = toOperationInfo(operation);\n\n\t\t\t\t// Invoke the operation\n\t\t\t\tconst response = await api.invokeOperation(ownerType, operationInfo, transfer, transfer);\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, response.data as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleOperationError(error, operation.name, context);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseCallOperationActionHandler.actionType = \"CallOperationActionDefinition\";\n\n/**\n * Handle bulk operation calls - hook factory.\n * Calls an operation on multiple selected transfers.\n * Supports both legacy callback mode and API mode.\n * Shows success toast on success, error toast on failure.\n */\nexport const useBulkCallOperationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Cast actionDefinition to access operation\n\t\tconst opDef = action.actionDefinition as CallOpDef;\n\t\tconst operation = opDef.operation as OperationType | undefined;\n\t\tif (!operation) {\n\t\t\tthrow new Error(\"No operation defined for BulkCallOperationAction\");\n\t\t}\n\n\t\tconst selectedRows = context.selectedRows as TransferStored[] | undefined;\n\t\tif (!selectedRows || selectedRows.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onBulkCallOperation, api } = callbackContext;\n\t\tconst { notifications } = context;\n\n\t\ttry {\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onBulkCallOperation) {\n\t\t\t\tawait onBulkCallOperation(operation, selectedRows);\n\t\t\t\tnotifications?.success(`${operation.name} completed on ${selectedRows.length} item(s)`);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\t// Get the owner ClassType - either from actionDefinition.targetType or operation's eContainer\n\t\t\t\tconst ownerType = (opDef.targetType ?? operation.eContainer) as ClassType | undefined;\n\t\t\t\tif (!ownerType) {\n\t\t\t\t\tthrow new Error(\"No owner type for bulk operation call\");\n\t\t\t\t}\n\n\t\t\t\tconst operationInfo = toOperationInfo(operation);\n\n\t\t\t\t// Call operation on each selected transfer\n\t\t\t\tconst operationPromises = selectedRows.map((row) => api.invokeOperation(ownerType, operationInfo, row, row));\n\n\t\t\t\tawait Promise.all(operationPromises);\n\t\t\t\tnotifications?.success(`${operation.name} completed on ${selectedRows.length} item(s)`);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleOperationError(error, operation.name, context);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseBulkCallOperationActionHandler.actionType = \"BulkCallOperationActionDefinition\";\n\n/**\n * Handle operation with input form - hook factory.\n * Calls an operation with form data as input.\n * Supports both legacy callback mode and API mode.\n * Opens output dialog if operation returns data and action has targetPageDefinition.\n * Shows success toast on success, error toast on failure.\n * Only closes dialog on success.\n */\nexport const useInputFormCallOperationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Cast actionDefinition to access operation\n\t\tconst opDef = action.actionDefinition as CallOpDef;\n\t\tconst operation = opDef.operation as OperationType | undefined;\n\t\tif (!operation) {\n\t\t\tthrow new Error(\"No operation defined for InputFormCallOperationAction\");\n\t\t}\n\n\t\tconst inputFormContext = context as unknown as {\n\t\t\tinputData?: TransferStored;\n\t\t\tpageTransferId?: string;\n\t\t} & LegacyCallbacks &\n\t\t\tApiContext;\n\n\t\tconst { onInputFormCallOperation, api, pageTransferId } = inputFormContext;\n\t\tconst { notifications } = context;\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\n\t\t// Get input data from context or from data store using pageTransferId\n\t\t// For input forms, the form data is stored in data store by the form components\n\t\tlet inputData = inputFormContext.inputData;\n\t\tif (!inputData && context.data && pageTransferId) {\n\t\t\tconst stored = context.data.getSnapshot((state) => state.transfers.get(pageTransferId)?.data);\n\t\t\tif (stored) inputData = stored;\n\t\t}\n\n\t\tif (!inputData) {\n\t\t\t// No input data - cannot proceed\n\t\t\treturn;\n\t\t}\n\n\t\t// React InputFormCallOperationAction: local check before the call\n\t\tif (!passesLocalValidation(context.pageContainer, inputData, context.validation, context.translate)) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onInputFormCallOperation) {\n\t\t\t\tconst result = await onInputFormCallOperation(operation, transfer, inputData);\n\t\t\t\t// Success: close input dialog first, then show toast and open output page\n\t\t\t\tcontext.closeDialog?.({ type: \"submitted\" });\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, result as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\t// Get the owner ClassType - either from actionDefinition.targetType or operation's eContainer\n\t\t\t\tconst ownerType = (opDef.targetType ?? operation.eContainer) as ClassType | undefined;\n\t\t\t\tif (!ownerType) {\n\t\t\t\t\tthrow new Error(\"No owner type for input form operation call\");\n\t\t\t\t}\n\n\t\t\t\tconst operationInfo = toOperationInfo(operation);\n\n\t\t\t\t// Invoke operation with form input\n\t\t\t\tconst response = await api.invokeOperation(ownerType, operationInfo, transfer, inputData);\n\n\t\t\t\t// Success: close input dialog first, then show toast and open output page\n\t\t\t\tcontext.closeDialog?.({ type: \"submitted\" });\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, response.data as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Error: do NOT close dialog, show error toast\n\t\t\thandleOperationError(error, operation.name, context);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseInputFormCallOperationActionHandler.actionType = \"InputFormCallOperationActionDefinition\";\n\n/**\n * Handle operation with input selector - hook factory.\n * Calls an operation with selected transfer as input.\n * Supports both legacy callback mode and API mode.\n * Opens output dialog if operation returns data and action has targetPageDefinition.\n * Shows success toast on success, error toast on failure.\n * Only closes dialog on success.\n */\nexport const useInputSelectorCallOperationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Cast actionDefinition to access operation\n\t\tconst opDef = action.actionDefinition as CallOpDef;\n\t\tconst operation = opDef.operation as OperationType | undefined;\n\t\tif (!operation) {\n\t\t\tthrow new Error(\"No operation defined for InputSelectorCallOperationAction\");\n\t\t}\n\n\t\tconst selectorContext = context as unknown as {\n\t\t\tselectedEntity?: TransferStored;\n\t\t\townerTransfer?: TransferStored;\n\t\t} & LegacyCallbacks &\n\t\t\tApiContext;\n\n\t\tconst { onInputSelectorCallOperation, api, selectedEntity, ownerTransfer } = selectorContext;\n\t\tconst { notifications } = context;\n\t\t// In selector dialogs, context.transfer is undefined because the dialog was\n\t\t// opened without a transfer param. The ownerTransfer (the entity that owns\n\t\t// the operation) is injected by pageActionDispatch from the selection context.\n\t\t// Use ownerTransfer as the API owner so X-Judo-SignedIdentifier is sent.\n\t\tconst transfer = (context.transfer ?? ownerTransfer) as TransferStored | undefined;\n\n\t\t// React: a required (1..1) input needs a selected row; an optional (0..1)\n\t\t// input submitted empty calls the operation with a null input.\n\t\tif (!selectedEntity && operation.input?.isOptional === false) {\n\t\t\treturn;\n\t\t}\n\t\tconst input = selectedEntity ?? null;\n\n\t\ttry {\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onInputSelectorCallOperation) {\n\t\t\t\tconst result = await onInputSelectorCallOperation(operation, transfer, input);\n\t\t\t\t// Success: close selector dialog first, then show toast and open output page\n\t\t\t\tcontext.closeDialog?.({ type: \"submitted\" });\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, result as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\t// Get the owner ClassType - either from actionDefinition.targetType or operation's eContainer\n\t\t\t\tconst ownerType = (opDef.targetType ?? operation.eContainer) as ClassType | undefined;\n\t\t\t\tif (!ownerType) {\n\t\t\t\t\tthrow new Error(\"No owner type for input selector operation call\");\n\t\t\t\t}\n\n\t\t\t\tconst operationInfo = toOperationInfo(operation);\n\n\t\t\t\t// Invoke operation with selected transfer as input\n\t\t\t\tconst response = await api.invokeOperation(ownerType, operationInfo, transfer, input);\n\n\t\t\t\t// Success: close selector dialog first, then show toast and open output page\n\t\t\t\tcontext.closeDialog?.({ type: \"submitted\" });\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, response.data as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Error: do NOT close dialog, show error toast\n\t\t\thandleOperationError(error, operation.name, context);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseInputSelectorCallOperationActionHandler.actionType = \"InputSelectorCallOperationActionDefinition\";\n\n/**\n * Handle parameterless operation calls - hook factory.\n * Calls an operation with no input.\n * Supports both legacy callback mode and API mode.\n * Opens output dialog if operation returns data and action has targetPageDefinition.\n * Shows success toast on success, error toast on failure.\n */\nexport const useParameterlessCallOperationActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\t// Cast actionDefinition to access operation\n\t\tconst opDef = action.actionDefinition as CallOpDef;\n\t\tconst operation = opDef.operation as OperationType | undefined;\n\t\tif (!operation) {\n\t\t\tthrow new Error(\"No operation defined for ParameterlessCallOperationAction\");\n\t\t}\n\n\t\tconst callbackContext = context as unknown as LegacyCallbacks & ApiContext;\n\t\tconst { onParameterlessCallOperation, api } = callbackContext;\n\t\tconst { notifications } = context;\n\n\t\tconst transfer = context.transfer as TransferStored | undefined;\n\n\t\ttry {\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onParameterlessCallOperation) {\n\t\t\t\tconst result = await onParameterlessCallOperation(operation, transfer);\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, result as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\t// Get the owner ClassType - either from actionDefinition.targetType or operation's eContainer\n\t\t\t\tconst ownerType = (opDef.targetType ?? operation.eContainer) as ClassType | undefined;\n\t\t\t\tif (!ownerType) {\n\t\t\t\t\tthrow new Error(\"No owner type for parameterless operation call\");\n\t\t\t\t}\n\n\t\t\t\tconst operationInfo = toOperationInfo(operation);\n\n\t\t\t\t// Invoke operation without input parameters\n\t\t\t\tconst response = await api.invokeOperation(ownerType, operationInfo, transfer, undefined);\n\t\t\t\tnotifications?.success(`${operation.name} completed successfully`);\n\t\t\t\topenOperationOutputPage(action, response.data as TransferStored | undefined, operation, context);\n\t\t\t\ttriggerPageRefresh(context);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleOperationError(error, operation.name, context);\n\t\t\tthrow error;\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseParameterlessCallOperationActionHandler.actionType = \"ParameterlessCallOperationActionDefinition\";\n","import { type ClassType, type RelationType, isRelationType } from \"@judo/model-api\";\nimport type { IJudoRestApi } from \"../../api/i-judo-rest-api\";\nimport type { QueryCustomizer, TransferStored } from \"../../api/types\";\nimport type { Action, ActionHandlerHookWithMeta, TypedActionHandlerContext, TypedActionHandlerFn } from \"../../types\";\n\n// Interface for API context\ninterface ApiContext {\n\tapi?: IJudoRestApi;\n}\n\n// Interface for relation context\ninterface RelationContext {\n\townerTransfer?: TransferStored;\n\townerClassType?: ClassType;\n\trelation?: RelationType;\n}\n\n// Legacy callback interfaces for backward compatibility\ninterface LegacyCallbacks {\n\tonAutocompleteRange?: (classType: ClassType, searchText: string) => Promise<TransferStored[]>;\n\tonAutocompleteSet?: (ownerId: string, relationName: string, selectedId: string) => Promise<void>;\n\tonAutocompleteAdd?: (ownerId: string, relationName: string, selectedIds: string[]) => Promise<void>;\n}\n\n/**\n * Get RelationType from context.\n */\nfunction getRelation(relationContext: RelationContext, action: Action): RelationType | null {\n\tif (relationContext.relation) {\n\t\treturn relationContext.relation;\n\t}\n\treturn isRelationType(action.ownerDataElement) ? action.ownerDataElement : null;\n}\n\n/** Context the range handler reads; every extra field is optional, so every action context fits. */\ntype RangeHandlerContext = TypedActionHandlerContext &\n\tApiContext &\n\tRelationContext &\n\tLegacyCallbacks & {\n\t\tsearchText?: string;\n\t\t/** Query built by the caller (link field, selector dialog); used as is when given. */\n\t\tqueryCustomizer?: QueryCustomizer;\n\t\tonRangeResult?: (results: TransferStored[]) => void;\n\t};\n\n/** The caller's query when it built one, else a `contains` filter on the typed text (empty text: no filter). */\nfunction rangeQuery(searchText: string, callerQuery: QueryCustomizer | undefined): QueryCustomizer {\n\tif (callerQuery) return callerQuery;\n\treturn searchText ? { _filter: { contains: searchText } } : {};\n}\n\n/**\n * Handle autocomplete range query - hook factory.\n * Fetches range data for autocomplete via REST API.\n * Supports both legacy callback mode and API mode.\n */\nexport const useAutocompleteRangeActionHandler: ActionHandlerHookWithMeta = Object.assign(\n\t(action: Action): TypedActionHandlerFn =>\n\t\tasync (callbackContext: RangeHandlerContext): Promise<TransferStored[]> => {\n\t\t\tconst { targetType } = action.actionDefinition;\n\t\t\tif (!targetType) {\n\t\t\t\tthrow new Error(\"No target type for autocomplete range\");\n\t\t\t}\n\n\t\t\tconst { onAutocompleteRange, api, onRangeResult, searchText = \"\" } = callbackContext;\n\n\t\t\t// Use legacy callback if provided\n\t\t\tif (onAutocompleteRange) {\n\t\t\t\tconst results = await onAutocompleteRange(targetType, searchText);\n\t\t\t\tonRangeResult?.(results);\n\t\t\t\treturn results;\n\t\t\t}\n\n\t\t\t// Use API if available\n\t\t\tif (api) {\n\t\t\t\tconst relation = getRelation(callbackContext, action);\n\t\t\t\tif (!relation) {\n\t\t\t\t\tthrow new Error(\"Cannot determine relation for autocomplete range\");\n\t\t\t\t}\n\n\t\t\t\tconst queryCustomizer = rangeQuery(searchText, callbackContext.queryCustomizer);\n\t\t\t\tconst response = await api.getRelationRange(relation, callbackContext.ownerTransfer, queryCustomizer);\n\n\t\t\t\t// Signal results to UI\n\t\t\t\tonRangeResult?.(response.data);\n\t\t\t\treturn response.data;\n\t\t\t}\n\t\t\t// Neither a legacy callback nor an API: nothing to query.\n\t\t\treturn [];\n\t\t},\n\t{ actionType: \"AutocompleteRangeActionDefinition\" as const }\n);\n\n/**\n * Handle autocomplete set action - hook factory.\n * Sets a single-valued relation via autocomplete selection.\n * Supports both legacy callback mode and API mode.\n */\nexport const useAutocompleteSetActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst autocompleteContext = context as unknown as RelationContext & {\n\t\t\tselectedEntity?: TransferStored;\n\t\t} & ApiContext &\n\t\t\tLegacyCallbacks;\n\n\t\tconst { ownerTransfer, selectedEntity, api, onAutocompleteSet } = autocompleteContext;\n\n\t\tconst ownerId = ownerTransfer?.__identifier ?? ownerTransfer?.__signedIdentifier;\n\t\tconst selectedId = selectedEntity?.__identifier ?? selectedEntity?.__signedIdentifier;\n\n\t\tif (!ownerId || !selectedId) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onAutocompleteSet) {\n\t\t\tawait onAutocompleteSet(ownerId, relationName, selectedId);\n\t\t\treturn;\n\t\t}\n\n\t\t// Use API if available\n\t\tif (api) {\n\t\t\tconst relation = getRelation(autocompleteContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for autocomplete set\");\n\t\t\t}\n\n\t\t\tawait api.setRelation(relation, ownerTransfer!, selectedEntity!);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseAutocompleteSetActionHandler.actionType = \"AutocompleteSetActionDefinition\";\n\n/**\n * Handle autocomplete add action - hook factory.\n * Adds selected transfers to a collection relation via autocomplete.\n * Supports both legacy callback mode and API mode.\n */\nexport const useAutocompleteAddActionHandler = ((action: Action) => {\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst autocompleteContext = context as unknown as RelationContext & {\n\t\t\tselectedEntities?: TransferStored[];\n\t\t} & ApiContext &\n\t\t\tLegacyCallbacks;\n\n\t\tconst { ownerTransfer, selectedEntities, api, onAutocompleteAdd } = autocompleteContext;\n\n\t\tconst ownerId = ownerTransfer?.__identifier ?? ownerTransfer?.__signedIdentifier;\n\n\t\tif (!ownerId || !selectedEntities?.length) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst selectedIds = selectedEntities\n\t\t\t.map((e) => e.__identifier ?? e.__signedIdentifier)\n\t\t\t.filter((id): id is string => Boolean(id));\n\t\tconst relationName = action.actionDefinition.name ?? \"\";\n\n\t\t// Use legacy callback if provided\n\t\tif (onAutocompleteAdd) {\n\t\t\tawait onAutocompleteAdd(ownerId, relationName, selectedIds);\n\t\t\treturn;\n\t\t}\n\n\t\t// Use API if available\n\t\tif (api) {\n\t\t\tconst relation = getRelation(autocompleteContext, action);\n\t\t\tif (!relation) {\n\t\t\t\tthrow new Error(\"Cannot determine relation for autocomplete add\");\n\t\t\t}\n\n\t\t\tconst entitiesToAdd = selectedEntities.filter((e) => e.__signedIdentifier);\n\t\t\tawait api.addToRelation(relation, ownerTransfer!, entitiesToAdd);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseAutocompleteAddActionHandler.actionType = \"AutocompleteAddActionDefinition\";\n","import type { Action, ActionHandlerHookWithMeta, TransferData, TypedActionHandlerContext } from \"../../types\";\n\n/**\n * Handle pre-fetch action (load data before navigation) - hook factory.\n */\nexport const usePreFetchActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst classType = action.actionDefinition.targetType;\n\t\tif (!classType) {\n\t\t\tthrow new Error(\"No target type for pre-fetch\");\n\t\t}\n\n\t\tconst preFetchContext = context as unknown as {\n\t\t\tonPreFetch?: (classType: unknown, transferId: string | undefined) => Promise<TransferData>;\n\t\t};\n\n\t\tif (preFetchContext.onPreFetch) {\n\t\t\tconst data = await preFetchContext.onPreFetch(classType, context.transfer?.__identifier);\n\t\t\tif (data.__identifier) {\n\t\t\t\tcontext.data!.setTransferData(data.__identifier, data);\n\t\t\t}\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nusePreFetchActionHandler.actionType = \"PreFetchActionDefinition\";\n\n/**\n * Handle custom action (user-defined logic) - hook factory.\n */\nexport const useCustomActionHandler = ((action: Action) => {\n\t// React hooks can be called here\n\n\treturn async (context: TypedActionHandlerContext): Promise<void> => {\n\t\tconst customContext = context as unknown as {\n\t\t\tonCustomAction?: (action: Action, context: TypedActionHandlerContext) => Promise<void>;\n\t\t};\n\n\t\tif (customContext.onCustomAction) {\n\t\t\tawait customContext.onCustomAction(action, context);\n\t\t}\n\t};\n}) as ActionHandlerHookWithMeta;\nuseCustomActionHandler.actionType = \"CustomActionDefinition\";\n","import { type ReactNode, createContext, useContext } from \"react\";\nimport type { IJudoRestApi } from \"../api/i-judo-rest-api\";\n\n/**\n * API context type.\n */\nexport interface ApiContextType {\n\t/** JUDO REST API client */\n\tapi: IJudoRestApi;\n}\n\nconst ApiContext = createContext<ApiContextType | null>(null);\n\n/**\n * Hook to access the JUDO REST API client.\n *\n * @returns IJudoRestApi\n * @throws Error if used outside ApiProvider\n */\nexport function useApi(): IJudoRestApi {\n\tconst context = useContext(ApiContext);\n\tif (!context) {\n\t\tthrow new Error(\"useApi must be used within ApiProvider\");\n\t}\n\treturn context.api;\n}\n\n/**\n * Props for ApiProvider.\n */\nexport interface ApiProviderProps {\n\tchildren: ReactNode;\n\t/** JUDO REST API client instance */\n\tapi: IJudoRestApi;\n}\n\n/**\n * Provider for JUDO REST API client.\n * Makes the API client available to action handlers via the useApi hook.\n */\nexport function ApiProvider({ children, api }: ApiProviderProps) {\n\tconst value: ApiContextType = { api };\n\treturn <ApiContext.Provider value={value}>{children}</ApiContext.Provider>;\n}\n","import { createContext, useContext } from \"react\";\nimport type { OperationFault } from \"../api/operation-fault\";\n\n/** Shows a modeled operation fault (React `useFaultDialog`). */\nexport type ShowOperationFault = (fault: OperationFault) => void;\n\n/**\n * Supplies the operation fault presenter to action handlers. `useActionDispatcher`\n * adds it to the action context as `showOperationFault`; the UI layer provides it\n * (`@judo/components` `OperationFaultProvider`) so `@judo/actions` stays UI-free.\n */\nexport const OperationFaultContext = createContext<ShowOperationFault | null>(null);\n\nexport function useShowOperationFault(): ShowOperationFault | null {\n\treturn useContext(OperationFaultContext);\n}\n","/**\n * Action lifecycle execution engine.\n *\n * Composes lifecycle overrides with built-in action handlers.\n * The lifecycle wraps the default handler with before/after/onError hooks\n * and allows full replacement of the execute phase.\n */\n\nimport type { ActionLifecycle, ActionLifecycleContext } from \"@judo/model-api\";\nimport type { ActionHandlerContext, ActionHandlerFn, ActionResult } from \"@judo/model-api\";\nimport type { Action } from \"../types\";\n\n/**\n * Execute an action with lifecycle overrides composed around a default handler.\n *\n * Lifecycle execution order:\n * 1. override.before() → return false to cancel\n * 2. override.execute() ?? defaultHandler() → core execution\n * 3. override.after() → post-processing\n * 4. override.onError() → error handling (return true to suppress)\n *\n * @param defaultHandler - The built-in action handler function\n * @param overrides - Partial lifecycle overrides from the developer\n * @param baseContext - The base action handler context\n * @param action - The Action model object\n * @param page - The PageDefinition\n * @returns Promise resolving to the action result\n */\nexport async function executeWithLifecycle(\n\tdefaultHandler: ActionHandlerFn,\n\toverrides: Partial<ActionLifecycle>,\n\tbaseContext: ActionHandlerContext,\n\taction: Action\n): Promise<ActionResult> {\n\t// Build lifecycle context with callDefault\n\tconst callDefault = () => defaultHandler(baseContext);\n\n\tconst lifecycleContext: ActionLifecycleContext = {\n\t\t...(baseContext as unknown as Record<string, unknown>),\n\t\taction,\n\t\tactionDefinition: action.actionDefinition,\n\t\tpage: (baseContext as unknown as Record<string, unknown>).page as ActionLifecycleContext[\"page\"],\n\t\tcallDefault,\n\t};\n\n\t// BEFORE phase\n\tif (overrides.before) {\n\t\tconst proceed = await overrides.before(lifecycleContext);\n\t\tif (proceed === false) return undefined; // cancelled\n\t}\n\n\ttry {\n\t\t// EXECUTE phase\n\t\tlet result: ActionResult;\n\t\tif (overrides.execute) {\n\t\t\t// Developer provided custom execution\n\t\t\t// callDefault is available on context for wrapping\n\t\t\tresult = await overrides.execute(lifecycleContext);\n\t\t} else {\n\t\t\t// Use built-in handler\n\t\t\tresult = await defaultHandler(baseContext);\n\t\t}\n\n\t\t// AFTER phase\n\t\tif (overrides.after) {\n\t\t\tawait overrides.after(lifecycleContext, result);\n\t\t}\n\n\t\treturn result;\n\t} catch (error) {\n\t\t// ERROR phase\n\t\tif (overrides.onError) {\n\t\t\tconst suppressed = await overrides.onError(lifecycleContext, error);\n\t\t\tif (suppressed === true) return undefined; // error handled by override\n\t\t}\n\t\tthrow error; // re-throw for default error handling\n\t}\n}\n","import type { Action, ActionHandlerHook, ActionHandlerHookWithMeta, TypedActionHandlerHook } from \"../types\";\n\n// Import all built-in handlers\nimport {\n\tuseBackActionHandler,\n\tuseCancelActionHandler,\n\tuseOpenPageActionHandler,\n\tuseRowOpenPageActionHandler,\n} from \"../handlers/navigation\";\n\nimport {\n\tuseOpenCreateFormActionHandler,\n\tuseOpenFormActionHandler,\n\tuseOpenOperationInputFormActionHandler,\n} from \"../handlers/form\";\n\nimport {\n\tuseOpenAddSelectorActionHandler,\n\tuseOpenOperationInputSelectorActionHandler,\n\tuseOpenSelectorActionHandler,\n\tuseOpenSetSelectorActionHandler,\n\tuseSelectorRangeActionHandler,\n} from \"../handlers/selector\";\n\nimport {\n\tuseBulkDeleteActionHandler,\n\tuseCreateActionHandler,\n\tuseDeleteActionHandler,\n\tuseGetTemplateActionHandler,\n\tuseRefreshActionHandler,\n\tuseRowDeleteActionHandler,\n\tuseUpdateActionHandler,\n} from \"../handlers/crud\";\n\nimport {\n\tuseAddActionHandler,\n\tuseBulkRemoveActionHandler,\n\tuseClearActionHandler,\n\tuseFilterRelationActionHandler,\n\tuseRefreshRelationActionHandler,\n\tuseRemoveActionHandler,\n\tuseSetActionHandler,\n\tuseUnsetActionHandler,\n} from \"../handlers/relation\";\n\nimport { useExportActionHandler, useFilterActionHandler, useInlineCreateRowActionHandler } from \"../handlers/table\";\n\nimport {\n\tuseBulkCallOperationActionHandler,\n\tuseCallOperationActionHandler,\n\tuseInputFormCallOperationActionHandler,\n\tuseInputSelectorCallOperationActionHandler,\n\tuseParameterlessCallOperationActionHandler,\n} from \"../handlers/operation\";\n\nimport {\n\tuseAutocompleteAddActionHandler,\n\tuseAutocompleteRangeActionHandler,\n\tuseAutocompleteSetActionHandler,\n} from \"../handlers/autocomplete\";\n\nimport { useCustomActionHandler, usePreFetchActionHandler } from \"../handlers/other\";\n\n/**\n * Registry of all built-in action handlers.\n * Maps action type to handler hook.\n * Built-in handlers use TypedActionHandlerContext; the map keeps that type.\n */\nconst BUILTIN_HANDLERS = new Map<string, ActionHandlerHookWithMeta>([\n\t// Navigation (4)\n\t[\"BackActionDefinition\", useBackActionHandler],\n\t[\"OpenPageActionDefinition\", useOpenPageActionHandler],\n\t[\"RowOpenPageActionDefinition\", useRowOpenPageActionHandler],\n\t[\"CancelActionDefinition\", useCancelActionHandler],\n\n\t// Form (3)\n\t[\"OpenFormActionDefinition\", useOpenFormActionHandler],\n\t[\"OpenCreateFormActionDefinition\", useOpenCreateFormActionHandler],\n\t[\"OpenOperationInputFormActionDefinition\", useOpenOperationInputFormActionHandler],\n\n\t// Selector (5)\n\t[\"OpenSelectorActionDefinition\", useOpenSelectorActionHandler],\n\t[\"OpenAddSelectorActionDefinition\", useOpenAddSelectorActionHandler],\n\t[\"OpenSetSelectorActionDefinition\", useOpenSetSelectorActionHandler],\n\t[\"OpenOperationInputSelectorActionDefinition\", useOpenOperationInputSelectorActionHandler],\n\t[\"SelectorRangeActionDefinition\", useSelectorRangeActionHandler],\n\n\t// CRUD (7)\n\t[\"RefreshActionDefinition\", useRefreshActionHandler],\n\t[\"CreateActionDefinition\", useCreateActionHandler],\n\t[\"UpdateActionDefinition\", useUpdateActionHandler],\n\t[\"DeleteActionDefinition\", useDeleteActionHandler],\n\t[\"BulkDeleteActionDefinition\", useBulkDeleteActionHandler],\n\t[\"RowDeleteActionDefinition\", useRowDeleteActionHandler],\n\t[\"GetTemplateActionDefinition\", useGetTemplateActionHandler],\n\n\t// Relation (8)\n\t[\"SetActionDefinition\", useSetActionHandler],\n\t[\"UnsetActionDefinition\", useUnsetActionHandler],\n\t[\"AddActionDefinition\", useAddActionHandler],\n\t[\"RemoveActionDefinition\", useRemoveActionHandler],\n\t[\"BulkRemoveActionDefinition\", useBulkRemoveActionHandler],\n\t[\"ClearActionDefinition\", useClearActionHandler],\n\t[\"RefreshRelationActionDefinition\", useRefreshRelationActionHandler],\n\t[\"FilterRelationActionDefinition\", useFilterRelationActionHandler],\n\n\t// Table (3)\n\t[\"FilterActionDefinition\", useFilterActionHandler],\n\t[\"ExportActionDefinition\", useExportActionHandler],\n\t[\"InlineCreateRowActionDefinition\", useInlineCreateRowActionHandler],\n\n\t// Operation (5)\n\t[\"BulkCallOperationActionDefinition\", useBulkCallOperationActionHandler],\n\t[\"CallOperationActionDefinition\", useCallOperationActionHandler],\n\t[\"InputFormCallOperationActionDefinition\", useInputFormCallOperationActionHandler],\n\t[\"InputSelectorCallOperationActionDefinition\", useInputSelectorCallOperationActionHandler],\n\t[\"ParameterlessCallOperationActionDefinition\", useParameterlessCallOperationActionHandler],\n\n\t// Autocomplete (3)\n\t[\"AutocompleteAddActionDefinition\", useAutocompleteAddActionHandler],\n\t[\"AutocompleteRangeActionDefinition\", useAutocompleteRangeActionHandler],\n\t[\"AutocompleteSetActionDefinition\", useAutocompleteSetActionHandler],\n\n\t// Other (2)\n\t[\"PreFetchActionDefinition\", usePreFetchActionHandler],\n\t[\"CustomActionDefinition\", useCustomActionHandler],\n]);\n\n/**\n * Get the handler for an action.\n * Returns the handler hook if found, undefined otherwise.\n */\nexport function getActionHandler(action: Action): ActionHandlerHook | undefined {\n\t// The base hook type is the public contract for callers that pass a model-api\n\t// context; built-ins read the typed context, as before.\n\treturn getTypedActionHandler(action) as ActionHandlerHook | undefined;\n}\n\n/**\n * Get the built-in handler for an action with its typed context, so a caller\n * that builds the context itself gets it checked against `TypedActionHandlerContext`.\n */\nexport function getTypedActionHandler(action: Action): TypedActionHandlerHook | undefined {\n\treturn BUILTIN_HANDLERS.get(action.actionDefinition[\"@type\"]);\n}\n\n/**\n * Check if a handler exists for the given action.\n */\nexport function hasActionHandler(action: Action): boolean {\n\treturn getActionHandler(action) !== undefined;\n}\n","import type { ActionHandlerContext, ActionLifecycle, ActionResult } from \"@judo/model-api\";\nimport { useCallback, useMemo } from \"react\";\nimport type { IJudoRestApi } from \"../api/i-judo-rest-api\";\nimport { executeWithLifecycle } from \"../lifecycle/execute-with-lifecycle\";\nimport { useShowOperationFault } from \"../provider/operation-fault-context\";\nimport { hasActionHandler as checkHandler, getActionHandler } from \"../registry/action-handler-registry\";\nimport type { Action, DataStore, TransferData, ModelRegistry, NavigationContext, NotificationService } from \"../types\";\nimport type { TFunction } from \"i18next\";\n\n/**\n * Options for useActionDispatcher hook.\n */\nexport interface UseActionDispatcherOptions {\n\t/** Navigation context */\n\tnavigation: NavigationContext;\n\t/** Data store */\n\tdata: DataStore;\n\t/** Model registry */\n\tregistry: ModelRegistry;\n\t/** JUDO REST API client (optional - enables API-mode handlers) */\n\tapi?: IJudoRestApi | null;\n\t/** Current transfer data */\n\ttransfer?: TransferData;\n\t/** Selected rows for bulk operations */\n\tselectedRows?: TransferData[];\n\t/** Dialog closer for form actions */\n\tcloseDialog?: () => void;\n\t/** Notification service for showing toasts */\n\tnotifications?: NotificationService;\n\t/** i18next `t` of the rendering layer; handlers build their messages with it. */\n\ttranslate: TFunction;\n\t/** Additional context properties */\n\tadditionalContext?: Record<string, unknown>;\n\t/**\n\t * Resolved action lifecycle overrides for the current page.\n\t * Key: action sourceId, Value: lifecycle overrides.\n\t * Typically provided by PageActionOverridesProvider via useResolvedPageActionOverrides().\n\t */\n\tactionOverrides?: Record<string, Partial<ActionLifecycle>> | null;\n}\n\n/**\n * Result of useActionDispatcher hook.\n */\nexport interface UseActionDispatcherResult {\n\t/**\n\t * Dispatch an action, optionally with context overrides: fields of `ActionHandlerContext`\n\t * that replace the page's for this one call (e.g. `{ selectedRows }` for a bulk action).\n\t */\n\tdispatch: (action: Action, contextOverrides?: Record<string, unknown>) => Promise<ActionResult>;\n\t/** Check if an action can be handled */\n\tcanHandle: (action: Action) => boolean;\n}\n\n/**\n * Hook for dispatching actions to registered handlers.\n * Uses hook factory pattern - handlers are resolved and called as hooks.\n *\n * @example\n * ```tsx\n * const { dispatch } = useActionDispatcher({\n * navigation,\n * data,\n * registry,\n * transfer: currentTransfer,\n * });\n *\n * const handleClick = async () => {\n * await dispatch(saveAction);\n * };\n * ```\n */\nexport function useActionDispatcher(options: UseActionDispatcherOptions): UseActionDispatcherResult {\n\tconst {\n\t\tnavigation,\n\t\tdata,\n\t\tregistry,\n\t\tapi,\n\t\ttransfer,\n\t\tselectedRows,\n\t\tcloseDialog,\n\t\tnotifications,\n\t\ttranslate,\n\t\tadditionalContext,\n\t\tactionOverrides,\n\t} = options;\n\tconst showOperationFault = useShowOperationFault();\n\n\tconst context: ActionHandlerContext = useMemo(\n\t\t() =>\n\t\t\t({\n\t\t\t\tnavigation,\n\t\t\t\tdata,\n\t\t\t\tregistry,\n\t\t\t\tapi,\n\t\t\t\ttransfer,\n\t\t\t\tselectedRows,\n\t\t\t\tcloseDialog,\n\t\t\t\tnotifications,\n\t\t\t\ttranslate,\n\t\t\t\t...(showOperationFault && { showOperationFault }),\n\t\t\t\t...additionalContext,\n\t\t\t}) as unknown as ActionHandlerContext,\n\t\t[\n\t\t\tnavigation,\n\t\t\tdata,\n\t\t\tregistry,\n\t\t\tapi,\n\t\t\ttransfer,\n\t\t\tselectedRows,\n\t\t\tcloseDialog,\n\t\t\tnotifications,\n\t\t\ttranslate,\n\t\t\tshowOperationFault,\n\t\t\tadditionalContext,\n\t\t]\n\t);\n\n\tconst canHandle = useCallback((action: Action): boolean => {\n\t\treturn checkHandler(action);\n\t}, []);\n\n\tconst dispatch = useCallback(\n\t\tasync (action: Action, contextOverrides?: Record<string, unknown>): Promise<ActionResult> => {\n\t\t\tconst handlerHook = getActionHandler(action);\n\n\t\t\tif (!handlerHook) {\n\t\t\t\tconst actionType = action.actionDefinition[\"@type\"];\n\t\t\t\tthrow new Error(`No handler for action type: ${actionType}`);\n\t\t\t}\n\n\t\t\t// Call the hook to get the handler function\n\t\t\tconst handlerFn = handlerHook(action);\n\n\t\t\t// Merge context with overrides\n\t\t\tconst mergedContext: ActionHandlerContext = contextOverrides ? { ...context, ...contextOverrides } : context;\n\n\t\t\t// Check for lifecycle overrides\n\t\t\tconst actionSourceId = action[\"xmi:id\"];\n\t\t\tconst lifecycle = actionSourceId ? actionOverrides?.[actionSourceId] : undefined;\n\n\t\t\tif (lifecycle && Object.keys(lifecycle).length > 0) {\n\t\t\t\t// Execute with lifecycle composition\n\t\t\t\treturn executeWithLifecycle(handlerFn, lifecycle, mergedContext, action);\n\t\t\t} else {\n\t\t\t\t// No overrides — run default handler directly\n\t\t\t\treturn handlerFn(mergedContext);\n\t\t\t}\n\t\t},\n\t\t[context, actionOverrides]\n\t);\n\n\treturn { dispatch, canHandle };\n}\n","import type { Action, ActionHandlerFn } from \"@judo/model-api\";\nimport { useMemo } from \"react\";\nimport { hasActionHandler as checkHandler, getActionHandler } from \"../registry/action-handler-registry\";\n\n/**\n * Hook to get the handler for an action.\n *\n * @param action - The Action to get handler for\n * @returns Handler function to execute the action\n *\n * @example\n * ```tsx\n * function ActionButton({ action }: { action: Action }) {\n * const handler = useActionHandler(action);\n *\n * const handleClick = async () => {\n * await handler({ transfer: currentTransfer });\n * };\n *\n * return <Button onClick={handleClick}>{action.label}</Button>;\n * }\n * ```\n */\nexport function useActionHandler(action: Action): ActionHandlerFn {\n\tconst handler = useMemo(() => {\n\t\tconst handlerHook = getActionHandler(action);\n\n\t\tif (!handlerHook) {\n\t\t\tconst actionType = action.actionDefinition[\"@type\"];\n\t\t\tthrow new Error(`No handler for action type: ${actionType}`);\n\t\t}\n\n\t\t// Call the hook with the action to get the handler function\n\t\treturn handlerHook(action);\n\t}, [action]);\n\n\treturn handler;\n}\n\n/**\n * Check if a handler exists for the given action.\n *\n * @param action - The Action to check\n * @returns True if a handler exists\n */\nexport function hasActionHandler(action: Action): boolean {\n\treturn checkHandler(action);\n}\n","/**\n * Path building utilities for JUDO REST API.\n * Based on REST_REQUEST_MAPPING_SPECIFICATION.md\n */\n\nimport { type ClassType, type RelationType, typeSimpleName } from \"@judo/model-api\";\nimport type { Application } from \"../types\";\n\nconst SPLITTER = \"::\";\nconst TRANSFER_SKIP_SEGMENT = \"_default_transferobjecttypes\";\n\n/**\n * Builds a REST path for a class type with optional prefix/suffix for relation or operation names.\n *\n * @param classType - The class type containing packageNameTokens and simpleName\n * @param first - Prefix to add before the name (e.g., \"/\" for relations)\n * @param name - The relation or operation name (may contain ::)\n * @param second - Optional suffix (e.g., \"/~list\")\n * @returns The constructed path\n */\nfunction restPath(classType: ClassType, first: string, name: string, second?: string): string {\n\tconst suffix = `${first}${name ? name.split(SPLITTER).join(\"/\") : \"\"}${second ?? \"\"}`;\n\tconst packages = classType.packageNameTokens?.length ? `${classType.packageNameTokens.join(\"/\")}/` : \"\";\n\tconst simplePath = (classType.simpleName ?? \"\")\n\t\t.split(SPLITTER)\n\t\t.filter((i) => !i.includes(TRANSFER_SKIP_SEGMENT))\n\t\t.join(\"/\");\n\treturn `/${packages}${simplePath}${suffix}`;\n}\n\n/**\n * Builds a path with the application's model name prefix.\n *\n * @param application - The application context\n * @param path - Optional path to append\n * @returns The path prefixed with the model name (with leading slash for URL construction)\n * @throws Error if application is not provided\n */\nfunction getPathForApp(application: Application, path?: string): string {\n\tif (!application) {\n\t\tthrow new Error(\n\t\t\t\"Application context is required for path building. Ensure the API is properly initialized with an Application.\"\n\t\t);\n\t}\n\tconst tmp = path ? path : \"\";\n\treturn `/${application.modelName}${tmp.length && !tmp.startsWith(\"/\") ? `/${tmp}` : tmp}`;\n}\n\n/**\n * Builds the root path for the actor from the application.\n *\n * @param app - The application context\n * @returns The actor root path (e.g., \"admin/Admin\")\n * @throws Error if application or actor is not provided\n */\nfunction rootPathForApp(app: Application): string {\n\tif (!app?.actor) {\n\t\tthrow new Error(\n\t\t\t\"Application.actor is required for path building. Ensure the Application has a valid actor ClassType.\"\n\t\t);\n\t}\n\tconst packagePath = app.actor.packageNameTokens?.length ? `${app.actor.packageNameTokens.join(\"/\")}/` : \"\";\n\treturn `${packagePath}${typeSimpleName(app.actor) ?? \"Actor\"}`;\n}\n\n/**\n * Builds a path for the actor with optional additional path segments.\n *\n * @param application - The application context\n * @param path - Optional path to append after the actor path\n * @returns The full path including model name and actor path\n */\nexport function getPathForActor(application: Application, path = \"\"): string {\n\treturn getPathForApp(\n\t\tapplication,\n\t\trootPathForApp(application) + (path.length && !path.startsWith(\"/\") ? `/${path}` : path)\n\t);\n}\n\n/**\n * Builds the REST path for a relation with a given suffix.\n *\n * @param relation - The relation type\n * @param application - The application context\n * @param suffix - The operation suffix (e.g., \"/~list\", \"/~get\", \"/~range\")\n * @returns The full path for the relation endpoint\n */\nexport function getRelationPath(relation: RelationType, application: Application, suffix = \"/~list\"): string {\n\treturn getPathForActor(application, restPath(relation?.eContainer as ClassType, \"/\", relation!.name, suffix));\n}\n\n/**\n * Builds the REST path for a class type with a given suffix.\n *\n * @param classType - The class type\n * @param application - The application context\n * @param suffix - The operation suffix (e.g., \"/~template\", \"/~get\", \"/~update\")\n * @returns The full path for the class endpoint\n */\nexport function getClassPath(classType: ClassType, application: Application, suffix = \"\"): string {\n\treturn getPathForActor(application, restPath(classType, \"\", \"\", suffix));\n}\n\n/**\n * Builds the REST path for a mutation relation operation (create, set, unset, add, remove).\n * These use the /~update/ prefix for non-access relations.\n *\n * @param relation - The relation type\n * @param application - The application context\n * @param suffix - The operation suffix (e.g., \"/~create\", \"/~set\")\n * @param isAccess - Whether this is an access relation (skips /~update/ prefix)\n * @returns The full path for the mutation endpoint\n */\nexport function getMutationRelationPath(\n\trelation: RelationType,\n\tapplication: Application,\n\tsuffix: string,\n\tisAccess = false\n): string {\n\tconst classType = relation?.eContainer as ClassType;\n\tif (isAccess) {\n\t\t// Access relations don't use /~update/ prefix\n\t\treturn getPathForActor(application, restPath(classType, \"/\", relation!.name, suffix));\n\t}\n\t// Regular relations: /{classPath}/~update/{relationName}{suffix}\n\treturn getPathForActor(application, restPath(classType, \"/~update/\", relation!.name, suffix));\n}\n\n/**\n * Builds the REST path for an operation.\n *\n * @param classType - The class type containing the operation\n * @param operationName - The operation name\n * @param application - The application context\n * @param suffix - Optional suffix (e.g., \"/~validate\", \"/~range\")\n * @returns The full path for the operation endpoint\n */\nexport function getOperationPath(\n\tclassType: ClassType,\n\toperationName: string,\n\tapplication: Application,\n\tsuffix = \"\"\n): string {\n\treturn getPathForActor(application, restPath(classType, \"/\", operationName, suffix));\n}\n","/**\n * JUDO REST API client implementation.\n * Based on REST_REQUEST_MAPPING_SPECIFICATION.md\n *\n * This module provides a complete REST client for the JUDO backend,\n * implementing all operations defined in the specification:\n * - Transfer operations (get, template, update, delete)\n * - Relation operations (list, get, range, create, set, unset, add, remove)\n * - Operation invocations\n * - Access service operations (principal, metadata, file operations)\n */\n\nimport { type ClassType, type RelationType, typeSimpleName } from \"@judo/model-api\";\nimport type { Application } from \"../types\";\nimport {\n\tDEFAULT_COMMAND_MASK,\n\tHEADER_COUNT_RECORDS,\n\tHEADER_MARK_SELECTED_RANGE_ITEMS,\n\tHEADER_MASK,\n\tHEADER_SIGNED_IDENTIFIER,\n\tHEADER_TOKEN,\n\tSUFFIX_ADD,\n\tSUFFIX_CREATE,\n\tSUFFIX_DELETE,\n\tSUFFIX_EXPORT,\n\tSUFFIX_GET,\n\tSUFFIX_LIST,\n\tSUFFIX_META,\n\tSUFFIX_PRINCIPAL,\n\tSUFFIX_RANGE,\n\tSUFFIX_REMOVE,\n\tSUFFIX_SET,\n\tSUFFIX_TEMPLATE,\n\tSUFFIX_UNSET,\n\tSUFFIX_UPDATE,\n\tSUFFIX_UPLOAD_TOKEN,\n\tSUFFIX_VALIDATE,\n} from \"./constants\";\nimport type { IJudoRestApi, OperationInfo } from \"./i-judo-rest-api\";\n\nexport type { OperationInfo } from \"./i-judo-rest-api\";\nimport { getClassPath, getMutationRelationPath, getOperationPath, getRelationPath } from \"./path-builder\";\nimport type {\n\tTransferData,\n\tTransferDeserializer,\n\tTransferSerializer,\n\tTransferStored,\n\tJudoRestResponse,\n\tQueryCustomizer,\n\tRangeRequestBody,\n} from \"./types\";\n\n/**\n * Configuration for JUDO REST API client.\n */\nexport interface JudoRestApiConfig {\n\t/** Base URL for the API (e.g., http://localhost:8080) */\n\tbaseUrl: string;\n\t/** The application context containing model name and actor info */\n\tapplication: Application;\n\t/** Request timeout in milliseconds */\n\ttimeout?: number;\n\t/** Default headers to include in all requests */\n\tdefaultHeaders?: Record<string, string>;\n\t/** Optional custom fetch implementation */\n\tfetch?: typeof fetch;\n\t/** Optional request interceptor */\n\tonRequest?: (request: RequestInit) => RequestInit | Promise<RequestInit>;\n\t/** Optional response interceptor */\n\tonResponse?: (response: Response) => Response | Promise<Response>;\n\t/** Optional error handler */\n\tonError?: (error: Error) => void;\n\t/** Optional transfer serializer for transforming transfers before sending */\n\ttransferSerializer?: TransferSerializer;\n\t/** Optional transfer deserializer for transforming responses */\n\ttransferDeserializer?: TransferDeserializer;\n}\n\n/**\n * JUDO REST API client.\n * Implements all REST operations according to the specification.\n */\nexport class JudoRestApi implements IJudoRestApi {\n\tprivate readonly config: JudoRestApiConfig;\n\tprivate readonly fetchImpl: typeof fetch;\n\tprivate _defaultHeaders: Record<string, string>;\n\n\tconstructor(config: JudoRestApiConfig) {\n\t\tif (!config.application) {\n\t\t\tthrow new Error(\n\t\t\t\t\"JudoRestApi requires 'application' in config. Ensure the API is created with a valid Application context.\"\n\t\t\t);\n\t\t}\n\t\tif (!config.application.actor) {\n\t\t\tthrow new Error(\n\t\t\t\t\"JudoRestApi requires 'application.actor' in config. Ensure the Application has a valid actor ClassType.\"\n\t\t\t);\n\t\t}\n\t\tthis.config = config;\n\t\tthis.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);\n\t\tthis._defaultHeaders = { ...config.defaultHeaders };\n\t}\n\n\t/**\n\t * Update the default headers applied to every request.\n\t * Use this to set or remove the Authorization header when the auth token changes.\n\t */\n\tsetDefaultHeaders(headers: Record<string, string>): void {\n\t\tthis._defaultHeaders = headers;\n\t}\n\n\t/**\n\t * Gets the full URL for a path.\n\t */\n\tprivate getUrl(path: string): string {\n\t\treturn `${this.config.baseUrl}${path}`;\n\t}\n\n\t/**\n\t * Serializes an transfer for sending in request body.\n\t * Uses the configured transferSerializer if provided, otherwise returns the transfer as-is.\n\t */\n\tprivate serializeTransfer<T>(transfer: T, typeName?: string): unknown {\n\t\tif (this.config.transferSerializer) {\n\t\t\treturn this.config.transferSerializer.serialize(transfer, typeName);\n\t\t}\n\t\treturn transfer;\n\t}\n\n\t/**\n\t * Deserializes response data into an transfer.\n\t * Uses the configured transferDeserializer if provided, otherwise returns the data as-is.\n\t */\n\tprivate deserializeTransfer<T>(data: unknown): T {\n\t\tif (this.config.transferDeserializer) {\n\t\t\treturn this.config.transferDeserializer.deserialize(data) as T;\n\t\t}\n\t\treturn data as T;\n\t}\n\n\t/**\n\t * Deserializes an array of transfers from response data.\n\t */\n\tprivate deserializeArray<T>(data: unknown): T[] {\n\t\tif (!Array.isArray(data)) {\n\t\t\treturn [];\n\t\t}\n\t\tif (this.config.transferDeserializer) {\n\t\t\treturn data.map((item) => this.config.transferDeserializer!.deserialize(item) as T);\n\t\t}\n\t\treturn data as T[];\n\t}\n\n\t/**\n\t * Makes a request with optional interceptors.\n\t */\n\tprivate async request<T>(\n\t\tmethod: \"GET\" | \"POST\",\n\t\tpath: string,\n\t\toptions: {\n\t\t\tbody?: unknown;\n\t\t\theaders?: Record<string, string>;\n\t\t\tresponseType?: \"json\" | \"blob\";\n\t\t} = {}\n\t): Promise<JudoRestResponse<T>> {\n\t\tconst url = this.getUrl(path);\n\t\tconst headers: Record<string, string> = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t...this._defaultHeaders,\n\t\t\t...options.headers,\n\t\t};\n\n\t\tlet init: RequestInit = {\n\t\t\tmethod,\n\t\t\theaders,\n\t\t\tbody: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n\t\t};\n\n\t\t// Apply request interceptor\n\t\tif (this.config.onRequest) {\n\t\t\tinit = await this.config.onRequest(init);\n\t\t}\n\n\t\ttry {\n\t\t\tlet response = await this.fetchImpl(url, init);\n\n\t\t\t// Apply response interceptor\n\t\t\tif (this.config.onResponse) {\n\t\t\t\tresponse = await this.config.onResponse(response);\n\t\t\t}\n\n\t\t\tif (!response.ok) {\n\t\t\t\t// Try to parse error response as JSON for validation errors\n\t\t\t\tconst errorText = await response.text();\n\n\t\t\t\t// Handle validation errors (400 status)\n\t\t\t\tif (response.status === 400 && errorText.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst errorData = JSON.parse(errorText);\n\t\t\t\t\t\t// Check if it's a FeedbackItem array\n\t\t\t\t\t\tif (Array.isArray(errorData)) {\n\t\t\t\t\t\t\tconst { ValidationError } = await import(\"./types\");\n\t\t\t\t\t\t\tthrow new ValidationError(errorData);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (parseError) {\n\t\t\t\t\t\t// If not valid JSON or not FeedbackItem, fall through to generic error\n\t\t\t\t\t\tif (parseError instanceof Error && parseError.name === \"ValidationError\") {\n\t\t\t\t\t\t\tthrow parseError;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst { HttpError } = await import(\"./operation-fault\");\n\t\t\t\tthrow new HttpError(response.status, errorText);\n\t\t\t}\n\n\t\t\tlet data: T;\n\t\t\tif (options.responseType === \"blob\") {\n\t\t\t\tdata = (await response.blob()) as T;\n\t\t\t} else {\n\t\t\t\tconst text = await response.text();\n\t\t\t\tdata = text.length > 0 ? JSON.parse(text) : (undefined as T);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdata,\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (this.config.onError) {\n\t\t\t\tthis.config.onError(error as Error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// ============================================\n\t// ENTITY OPERATIONS\n\t// ============================================\n\n\t/**\n\t * Gets a template (default values) for creating a new transfer.\n\t *\n\t * GET /{classPath}/~template\n\t */\n\tasync getTemplate(classType: ClassType): Promise<JudoRestResponse<TransferData>> {\n\t\tconst path = getClassPath(classType, this.config.application, SUFFIX_TEMPLATE);\n\t\tconst response = await this.request<TransferData>(\"GET\", path);\n\t\treturn { ...response, data: this.deserializeTransfer<TransferData>(response.data) };\n\t}\n\n\t/**\n\t * Refreshes (retrieves) an transfer by its signed identifier.\n\t *\n\t * POST /{classPath}/~get\n\t * Headers: X-Judo-SignedIdentifier\n\t */\n\tasync refresh(\n\t\tclassType: ClassType,\n\t\ttarget: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer\n\t): Promise<JudoRestResponse<TransferStored>> {\n\t\tconst path = getClassPath(classType, this.config.application, SUFFIX_GET);\n\t\tconst response = await this.request<TransferStored>(\"POST\", path, {\n\t\t\tbody: queryCustomizer ?? {},\n\t\t\theaders: {\n\t\t\t\t[HEADER_SIGNED_IDENTIFIER]: target.__signedIdentifier!,\n\t\t\t},\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Updates an existing transfer.\n\t *\n\t * POST /{classPath}/~update\n\t * Headers: X-Judo-SignedIdentifier, X-Judo-Mask\n\t */\n\tasync update(classType: ClassType, target: TransferStored, mask?: string): Promise<JudoRestResponse<TransferStored>> {\n\t\tconst path = getClassPath(classType, this.config.application, SUFFIX_UPDATE);\n\t\tconst response = await this.request<TransferStored>(\"POST\", path, {\n\t\t\tbody: this.serializeTransfer(target, typeSimpleName(classType)),\n\t\t\theaders: {\n\t\t\t\t[HEADER_SIGNED_IDENTIFIER]: target.__signedIdentifier!,\n\t\t\t\t[HEADER_MASK]: mask ?? DEFAULT_COMMAND_MASK,\n\t\t\t},\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Validates an transfer update without persisting.\n\t *\n\t * POST /{classPath}/~validate\n\t * Headers: X-Judo-SignedIdentifier\n\t */\n\tasync validateUpdate(classType: ClassType, target: TransferStored): Promise<JudoRestResponse<TransferStored>> {\n\t\tconst path = getClassPath(classType, this.config.application, SUFFIX_VALIDATE);\n\t\tconst response = await this.request<TransferStored>(\"POST\", path, {\n\t\t\tbody: this.serializeTransfer(target, typeSimpleName(classType)),\n\t\t\theaders: {\n\t\t\t\t[HEADER_SIGNED_IDENTIFIER]: target.__signedIdentifier!,\n\t\t\t},\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Deletes an existing transfer.\n\t *\n\t * POST /{classPath}/~delete\n\t * Headers: X-Judo-SignedIdentifier\n\t */\n\tasync delete(classType: ClassType, target: TransferStored): Promise<JudoRestResponse<void>> {\n\t\tconst path = getClassPath(classType, this.config.application, SUFFIX_DELETE);\n\t\treturn this.request<void>(\"POST\", path, {\n\t\t\theaders: {\n\t\t\t\t[HEADER_SIGNED_IDENTIFIER]: target.__signedIdentifier!,\n\t\t\t},\n\t\t});\n\t}\n\n\t// ============================================\n\t// RELATION OPERATIONS\n\t// ============================================\n\n\t/**\n\t * Lists transfers in a collection relation.\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~list\n\t * Headers: X-Judo-SignedIdentifier (if owner provided), X-Judo-CountRecords (if countRecords true)\n\t */\n\tasync listRelation(\n\t\trelation: RelationType,\n\t\towner?: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer,\n\t\tcountRecords?: boolean\n\t): Promise<JudoRestResponse<TransferStored[]>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_LIST);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\tif (countRecords) {\n\t\t\theaders[HEADER_COUNT_RECORDS] = \"true\";\n\t\t}\n\n\t\tconst response = await this.request<TransferStored[]>(\"POST\", path, {\n\t\t\tbody: queryCustomizer ?? {},\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeArray<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Gets a single transfer from a non-collection relation.\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~get\n\t * Headers: X-Judo-SignedIdentifier\n\t */\n\tasync getRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer\n\t): Promise<JudoRestResponse<TransferStored | null>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_GET);\n\t\tconst response = await this.request<TransferStored | undefined>(\"POST\", path, {\n\t\t\tbody: queryCustomizer ?? {},\n\t\t\theaders: {\n\t\t\t\t[HEADER_SIGNED_IDENTIFIER]: owner.__signedIdentifier!,\n\t\t\t},\n\t\t});\n\n\t\t// Handle null/empty/undefined response (nullable deserialization)\n\t\tconst data =\n\t\t\tresponse.data === undefined || response.data === null\n\t\t\t\t? null\n\t\t\t\t: this.deserializeTransfer<TransferStored>(response.data);\n\n\t\treturn { ...response, data };\n\t}\n\n\t/**\n\t * Refreshes a non-collection access relation directly.\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~get\n\t * No owner header (access relation)\n\t */\n\tasync refreshAccessRelation(\n\t\trelation: RelationType,\n\t\tqueryCustomizer?: QueryCustomizer\n\t): Promise<JudoRestResponse<TransferStored>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_GET);\n\t\tconst response = await this.request<TransferStored>(\"POST\", path, {\n\t\t\tbody: queryCustomizer ?? {},\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Gets the available range of transfers for a relation.\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~range\n\t * Headers: X-Judo-Mark-Selected-Range-Items\n\t */\n\tasync getRelationRange(\n\t\trelation: RelationType,\n\t\towner?: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer,\n\t\tcountRecords?: boolean\n\t): Promise<JudoRestResponse<TransferStored[]>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_RANGE);\n\t\tconst body: RangeRequestBody = {\n\t\t\towner: owner ?? {},\n\t\t\tqueryCustomizer: queryCustomizer ?? {},\n\t\t};\n\n\t\tconst headers: Record<string, string> = {\n\t\t\t[HEADER_MARK_SELECTED_RANGE_ITEMS]: \"true\",\n\t\t};\n\n\t\tif (countRecords) {\n\t\t\theaders[HEADER_COUNT_RECORDS] = \"true\";\n\t\t}\n\n\t\tconst response = await this.request<TransferStored[]>(\"POST\", path, {\n\t\t\tbody,\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeArray<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Gets template for relation target.\n\t *\n\t * GET /{targetClassPath}/~template\n\t */\n\tasync getRelationTemplate(relation: RelationType): Promise<JudoRestResponse<TransferData>> {\n\t\tconst path = getClassPath(relation.target as ClassType, this.config.application, SUFFIX_TEMPLATE);\n\t\tconst response = await this.request<TransferData>(\"GET\", path);\n\t\treturn { ...response, data: this.deserializeTransfer<TransferData>(response.data) };\n\t}\n\n\t/**\n\t * Creates a new transfer through a relation.\n\t *\n\t * Non-access: POST /{ownerClassPath}/~update/{relationName}/~create\n\t * Access: POST /{ownerClassPath}/{relationName}/~create\n\t */\n\tasync createRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored | undefined,\n\t\tdata: TransferData,\n\t\tmask?: string\n\t): Promise<JudoRestResponse<TransferStored>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = isAccess\n\t\t\t? getRelationPath(relation, this.config.application, SUFFIX_CREATE)\n\t\t\t: getMutationRelationPath(relation, this.config.application, SUFFIX_CREATE);\n\n\t\tconst headers: Record<string, string> = {\n\t\t\t[HEADER_MASK]: mask ?? DEFAULT_COMMAND_MASK,\n\t\t};\n\n\t\tif (!isAccess && owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\tconst response = await this.request<TransferStored>(\"POST\", path, {\n\t\t\tbody: this.serializeTransfer(data, typeSimpleName(relation.target)),\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Validates creation through a relation.\n\t *\n\t * Non-access: POST /{ownerClassPath}/~update/{relationName}/~validate\n\t * Access: POST /{ownerClassPath}/{relationName}/~validate\n\t */\n\tasync validateCreateRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored | undefined,\n\t\tdata: TransferData\n\t): Promise<JudoRestResponse<TransferData>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = isAccess\n\t\t\t? getRelationPath(relation, this.config.application, SUFFIX_VALIDATE)\n\t\t\t: getMutationRelationPath(relation, this.config.application, SUFFIX_VALIDATE);\n\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (!isAccess && owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\tconst response = await this.request<TransferData>(\"POST\", path, {\n\t\t\tbody: this.serializeTransfer(data, typeSimpleName(relation.target)),\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TransferData>(response.data) };\n\t}\n\n\t/**\n\t * Sets a relation to point to specific transfer/transfers.\n\t *\n\t * POST /{ownerClassPath}/~update/{relationName}/~set\n\t * Headers: X-Judo-SignedIdentifier (non-access only)\n\t */\n\tasync setRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored,\n\t\tselected: TransferStored | TransferStored[]\n\t): Promise<JudoRestResponse<void>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = getMutationRelationPath(relation, this.config.application, SUFFIX_SET, isAccess);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (!isAccess) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier!;\n\t\t}\n\n\t\t// Serialize single or array based on what's passed\n\t\tconst body = Array.isArray(selected)\n\t\t\t? selected.map((s) => this.serializeTransfer(s))\n\t\t\t: this.serializeTransfer(selected);\n\n\t\treturn this.request<void>(\"POST\", path, {\n\t\t\tbody,\n\t\t\theaders,\n\t\t});\n\t}\n\n\t/**\n\t * Clears a relation (sets to null/empty).\n\t *\n\t * POST /{ownerClassPath}/~update/{relationName}/~unset\n\t * Headers: X-Judo-SignedIdentifier (non-access only)\n\t */\n\tasync unsetRelation(relation: RelationType, owner: TransferStored): Promise<JudoRestResponse<void>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = getMutationRelationPath(relation, this.config.application, SUFFIX_UNSET, isAccess);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (!isAccess) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier!;\n\t\t}\n\n\t\treturn this.request<void>(\"POST\", path, {\n\t\t\theaders,\n\t\t});\n\t}\n\n\t/**\n\t * Adds transfers to a collection relation.\n\t *\n\t * POST /{ownerClassPath}/~update/{relationName}/~add\n\t * Headers: X-Judo-SignedIdentifier (non-access only)\n\t */\n\tasync addToRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored,\n\t\tselected: TransferStored[]\n\t): Promise<JudoRestResponse<void>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = getMutationRelationPath(relation, this.config.application, SUFFIX_ADD, isAccess);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (!isAccess) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier!;\n\t\t}\n\n\t\treturn this.request<void>(\"POST\", path, {\n\t\t\tbody: selected.map((s) => this.serializeTransfer(s)),\n\t\t\theaders,\n\t\t});\n\t}\n\n\t/**\n\t * Removes transfers from a collection relation.\n\t *\n\t * POST /{ownerClassPath}/~update/{relationName}/~remove\n\t * Headers: X-Judo-SignedIdentifier (non-access only)\n\t */\n\tasync removeFromRelation(\n\t\trelation: RelationType,\n\t\towner: TransferStored,\n\t\tselected: TransferStored[]\n\t): Promise<JudoRestResponse<void>> {\n\t\tconst isAccess = relation.isAccess;\n\t\tconst path = getMutationRelationPath(relation, this.config.application, SUFFIX_REMOVE, isAccess);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (!isAccess) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier!;\n\t\t}\n\n\t\treturn this.request<void>(\"POST\", path, {\n\t\t\tbody: selected.map((s) => this.serializeTransfer(s)),\n\t\t\theaders,\n\t\t});\n\t}\n\n\t/**\n\t * Exports relation data as a file (CSV/Excel).\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~export\n\t * Headers: X-Judo-SignedIdentifier (if owner provided)\n\t */\n\tasync exportRelation(\n\t\trelation: RelationType,\n\t\towner?: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer\n\t): Promise<JudoRestResponse<Blob>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_EXPORT);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\treturn this.request<Blob>(\"POST\", path, {\n\t\t\tbody: queryCustomizer ?? {},\n\t\t\theaders,\n\t\t\tresponseType: \"blob\",\n\t\t});\n\t}\n\n\t// ============================================\n\t// OPERATION INVOCATIONS\n\t// ============================================\n\n\t/**\n\t * Invokes an operation on an transfer.\n\t *\n\t * POST /{classPath}/{operationName}\n\t * Headers: X-Judo-SignedIdentifier (if mapped/non-static)\n\t */\n\tasync invokeOperation<TInput = unknown, TOutput = unknown>(\n\t\tclassType: ClassType,\n\t\toperation: OperationInfo,\n\t\towner?: TransferStored,\n\t\tinput?: TInput\n\t): Promise<JudoRestResponse<TOutput | undefined>> {\n\t\tconst path = getOperationPath(classType, operation.name, this.config.application);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (operation.isMapped && !operation.isStatic && owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\tconst response = await this.request<TOutput | undefined>(\"POST\", path, {\n\t\t\t...(operation.hasInput && { body: this.serializeTransfer(input, typeSimpleName(operation.inputType)) }),\n\t\t\theaders,\n\t\t});\n\n\t\t// Deserialize output if present\n\t\tif (response.data !== undefined && response.data !== null) {\n\t\t\treturn { ...response, data: this.deserializeTransfer<TOutput>(response.data) };\n\t\t}\n\t\treturn response;\n\t}\n\n\t/**\n\t * Validates operation input without execution.\n\t *\n\t * POST /{classPath}/{operationName}/~validate\n\t * Headers: X-Judo-SignedIdentifier (if mapped/non-static)\n\t */\n\tasync validateOperationInput<TInput = unknown>(\n\t\tclassType: ClassType,\n\t\toperation: OperationInfo,\n\t\towner?: TransferStored,\n\t\tinput?: TInput\n\t): Promise<JudoRestResponse<TInput>> {\n\t\tconst path = getOperationPath(classType, operation.name, this.config.application, SUFFIX_VALIDATE);\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (operation.isMapped && !operation.isStatic && owner?.__signedIdentifier) {\n\t\t\theaders[HEADER_SIGNED_IDENTIFIER] = owner.__signedIdentifier;\n\t\t}\n\n\t\tconst response = await this.request<TInput>(\"POST\", path, {\n\t\t\tbody: this.serializeTransfer(input, typeSimpleName(operation.inputType)),\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeTransfer<TInput>(response.data) };\n\t}\n\n\t/**\n\t * Gets template for operation input.\n\t *\n\t * GET /{inputClassPath}/~template\n\t */\n\tasync getOperationInputTemplate(operation: OperationInfo): Promise<JudoRestResponse<TransferData>> {\n\t\tif (!operation.inputType) {\n\t\t\tthrow new Error(`Operation ${operation.name} has no input type`);\n\t\t}\n\t\tconst path = getClassPath(operation.inputType, this.config.application, SUFFIX_TEMPLATE);\n\t\tconst response = await this.request<TransferData>(\"GET\", path);\n\t\treturn { ...response, data: this.deserializeTransfer<TransferData>(response.data) };\n\t}\n\n\t/**\n\t * Gets range for operation input (selector operations).\n\t *\n\t * POST /{classPath}/{operationName}/~range\n\t * Headers: X-Judo-Mark-Selected-Range-Items\n\t */\n\tasync getOperationInputRange(\n\t\tclassType: ClassType,\n\t\toperation: OperationInfo,\n\t\towner?: TransferStored,\n\t\tqueryCustomizer?: QueryCustomizer,\n\t\tcountRecords?: boolean\n\t): Promise<JudoRestResponse<TransferStored[]>> {\n\t\tconst path = getOperationPath(classType, operation.name, this.config.application, SUFFIX_RANGE);\n\t\tconst body: RangeRequestBody = {\n\t\t\towner: owner ?? {},\n\t\t\tqueryCustomizer: queryCustomizer ?? {},\n\t\t};\n\n\t\tconst headers: Record<string, string> = {\n\t\t\t[HEADER_MARK_SELECTED_RANGE_ITEMS]: \"true\",\n\t\t};\n\n\t\tif (countRecords) {\n\t\t\theaders[HEADER_COUNT_RECORDS] = \"true\";\n\t\t}\n\n\t\tconst response = await this.request<TransferStored[]>(\"POST\", path, {\n\t\t\tbody,\n\t\t\theaders,\n\t\t});\n\t\treturn { ...response, data: this.deserializeArray<TransferStored>(response.data) };\n\t}\n\n\t// ============================================\n\t// ACCESS SERVICE OPERATIONS\n\t// ============================================\n\n\t/**\n\t * Gets the current authenticated user's principal data.\n\t *\n\t * GET /{actorPath}/{actorPath}/~principal — the JAX-RS service is mounted\n\t * at `/{actorPath}` AND every resource inside it is `@Path`-ed as\n\t * `{actorPath}/...`, producing the duplicated segment that the BE WADL\n\t * confirms (see `getClassPath`, which adds the inner repeat via `restPath`).\n\t */\n\tasync getPrincipal(): Promise<JudoRestResponse<TransferStored>> {\n\t\tif (!this.config.application.actor) {\n\t\t\tthrow new Error(\"Application.actor is required to fetch principal data.\");\n\t\t}\n\t\tconst path = getClassPath(this.config.application.actor, this.config.application, SUFFIX_PRINCIPAL);\n\t\tconst response = await this.request<TransferStored>(\"GET\", path);\n\t\treturn { ...response, data: this.deserializeTransfer<TransferStored>(response.data) };\n\t}\n\n\t/**\n\t * Gets application metadata.\n\t *\n\t * GET /{actorPath}/{actorPath}/~meta — same double-prefix shape as ~principal.\n\t */\n\tasync getMetadata(): Promise<JudoRestResponse<unknown>> {\n\t\tif (!this.config.application.actor) {\n\t\t\tthrow new Error(\"Application.actor is required to fetch metadata.\");\n\t\t}\n\t\tconst path = getClassPath(this.config.application.actor, this.config.application, SUFFIX_META);\n\t\treturn this.request<unknown>(\"GET\", path);\n\t}\n\n\t/**\n\t * Uploads a file to a binary attribute.\n\t *\n\t * 1. POST {attributePath}/~upload-token to get token\n\t * 2. POST /upload with token and file\n\t */\n\tasync uploadFile(attributePath: string, file: File): Promise<JudoRestResponse<unknown>> {\n\t\t// Step 1: Get upload token\n\t\tconst tokenResponse = await this.request<{ token: string }>(\"POST\", `${attributePath}${SUFFIX_UPLOAD_TOKEN}`);\n\t\tconst token = tokenResponse.data.token;\n\n\t\t// Step 2: Upload file\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", file);\n\n\t\tconst url = `${this.config.baseUrl}/upload`;\n\t\tconst response = await this.fetchImpl(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...this._defaultHeaders,\n\t\t\t\t[HEADER_TOKEN]: token,\n\t\t\t},\n\t\t\tbody: formData,\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`Upload failed: HTTP ${response.status}`);\n\t\t}\n\n\t\treturn {\n\t\t\tdata: await response.json(),\n\t\t\tstatus: response.status,\n\t\t\theaders: response.headers,\n\t\t};\n\t}\n\n\t/**\n\t * Downloads a file from a binary attribute.\n\t *\n\t * GET /download?disposition={disposition}\n\t * Headers: X-Token\n\t */\n\tasync downloadFile(\n\t\tdownloadToken: string,\n\t\tdisposition: \"inline\" | \"attachment\" = \"attachment\"\n\t): Promise<JudoRestResponse<Blob>> {\n\t\tconst url = `${this.config.baseUrl}/download?disposition=${disposition}`;\n\t\tconst response = await this.fetchImpl(url, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: {\n\t\t\t\t...this._defaultHeaders,\n\t\t\t\t[HEADER_TOKEN]: downloadToken,\n\t\t\t},\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`Download failed: HTTP ${response.status}`);\n\t\t}\n\n\t\treturn {\n\t\t\tdata: await response.blob(),\n\t\t\tstatus: response.status,\n\t\t\theaders: response.headers,\n\t\t};\n\t}\n\n\t/**\n\t * Finds a specific transfer instance from an access relation by identifier.\n\t *\n\t * POST /{ownerClassPath}/{relationName}/~list\n\t * Body: { _identifier, _mask?, _seek: { limit: 1 } }\n\t */\n\tasync findInstance(\n\t\trelation: RelationType,\n\t\tidentifier: string,\n\t\tmask?: string\n\t): Promise<JudoRestResponse<TransferStored | null>> {\n\t\tconst path = getRelationPath(relation, this.config.application, SUFFIX_LIST);\n\t\tconst body: QueryCustomizer = {\n\t\t\t_identifier: identifier,\n\t\t\t_seek: { limit: 1 },\n\t\t};\n\n\t\tif (mask) {\n\t\t\tbody._mask = mask;\n\t\t}\n\n\t\tconst response = await this.request<TransferStored[]>(\"POST\", path, { body });\n\n\t\t// Return first item (deserialized) or null\n\t\tconst items = this.deserializeArray<TransferStored>(response.data);\n\t\tconst data = items.length > 0 ? items[0] : null;\n\t\treturn { ...response, data };\n\t}\n}\n\n/**\n * Factory function to create a JUDO REST API client.\n */\nexport function createJudoRestApi(config: JudoRestApiConfig): JudoRestApi {\n\treturn new JudoRestApi(config);\n}\n","/**\n * Default transfer serializer for JUDO REST API.\n *\n * Strips properties that should not be sent to the API:\n *\n * ## Backend-Provided Properties (read-only, never send back)\n * These properties are provided by the backend when retrieving transfers.\n * The frontend must NOT create or mutate these - they are server-managed:\n *\n * - `__identifier`: Backend-assigned transfer identifier\n * - `__signedIdentifier`: Signed token for transfer operations (exception: IS sent)\n * - `__entityType`: Backend type information\n * - `__deleteable`: Permission flag from backend\n * - `__updateable`: Permission flag from backend\n * - `__version`: Optimistic locking version\n *\n * ## Frontend-Only Properties (client-side state, never serialize)\n * These are created by the frontend for local state management:\n *\n * - `__isNew`: Marker for locally-created transfers not yet persisted\n * - `__items`: Array of related transfers for eager table state\n * - `__tempId`: Temporary client-side ID for tracking new transfers\n *\n * The only preserved `__*` property is `__signedIdentifier`, which is required\n * by the API for transfer operations.\n */\n\nimport { modelTypeName } from \"@judo/model-api\";\nimport type { TemporalFieldRegistry, TemporalFieldType, TransferData, TransferSerializer } from \"./types\";\n\n/**\n * Properties provided by the backend that should not be sent in requests.\n * These are read-only metadata assigned by the server.\n */\nexport const BACKEND_PROPERTIES = new Set<string>([\n\t\"__identifier\",\n\t\"__entityType\",\n\t\"__deleteable\",\n\t\"__updateable\",\n\t\"__version\",\n]);\n\n/**\n * Properties created by the frontend for local state management.\n * These should never be serialized to the API.\n */\nexport const FRONTEND_PROPERTIES = new Set<string>([\"__isNew\", \"__items\", \"__tempId\"]);\n\n/**\n * Combined set of all internal properties that should not be serialized.\n */\nexport const INTERNAL_PROPERTIES = new Set<string>([...BACKEND_PROPERTIES, ...FRONTEND_PROPERTIES]);\n\n/**\n * Check if a property is internal and should be stripped from serialization.\n * A property is internal if:\n * 1. It's in the INTERNAL_PROPERTIES set, OR\n * 2. It starts with `__` but is NOT `__signedIdentifier`\n *\n * @param key - Property name to check\n * @returns true if the property should be stripped\n */\nexport function isInternalProperty(key: string): boolean {\n\t// Always allow __signedIdentifier - it's required by the API\n\tif (key === \"__signedIdentifier\") {\n\t\treturn false;\n\t}\n\n\t// Check explicit internal properties\n\tif (INTERNAL_PROPERTIES.has(key)) {\n\t\treturn true;\n\t}\n\n\t// Any other double-underscore prefix is internal\n\treturn key.startsWith(\"__\");\n}\n\n/**\n * Strip internal properties from an transfer.\n * Creates a new object with only non-internal properties.\n *\n * @param transfer - Transfer to clean\n * @returns New object without internal properties\n */\nexport function stripInternalProperties<T extends TransferData>(transfer: T): Partial<T> {\n\tconst result: Partial<T> = {};\n\n\tfor (const [key, value] of Object.entries(transfer)) {\n\t\tif (!isInternalProperty(key)) {\n\t\t\t(result as TransferData)[key] = value;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Default transfer serializer that strips internal properties.\n * Use this when configuring JudoRestApi to ensure internal metadata\n * is not sent to the server.\n *\n * @example\n * ```typescript\n * const api = new JudoRestApi({\n * baseUrl: 'http://localhost:8080',\n * basePath: '/api',\n * modelName: 'myapp',\n * actorPath: 'admin/Admin',\n * transferSerializer: defaultTransferSerializer,\n * });\n * ```\n */\nexport const defaultTransferSerializer: TransferSerializer = {\n\tserialize(transfer: unknown): unknown {\n\t\tif (transfer === null || transfer === undefined) {\n\t\t\treturn transfer;\n\t\t}\n\n\t\tif (typeof transfer !== \"object\") {\n\t\t\treturn transfer;\n\t\t}\n\n\t\tif (Array.isArray(transfer)) {\n\t\t\treturn transfer.map((item) => this.serialize(item));\n\t\t}\n\n\t\treturn stripInternalProperties(transfer as TransferData);\n\t},\n};\n\n// ============================================\n// Model-Aware Serializer\n// ============================================\n\n/**\n * Serialize a `Date` value to its wire format based on temporal field type.\n *\n * - `date` → `\"YYYY-MM-DD\"` using **local** date components (avoids timezone shift)\n * - `timestamp` → full ISO 8601 UTC string via `Date.toISOString()`\n * - `time` → `\"HH:mm:ss\"` using local time components\n *\n * @param date - The `Date` to serialize\n * @param fieldType - The temporal field classification\n * @returns Formatted string for the API wire format\n */\nexport function serializeTemporalValue(date: Date, fieldType: TemporalFieldType): string {\n\tswitch (fieldType) {\n\t\tcase \"date\": {\n\t\t\tconst y = date.getFullYear();\n\t\t\tconst m = String(date.getMonth() + 1).padStart(2, \"0\");\n\t\t\tconst d = String(date.getDate()).padStart(2, \"0\");\n\t\t\treturn `${y}-${m}-${d}`;\n\t\t}\n\t\tcase \"timestamp\":\n\t\t\treturn date.toISOString();\n\t\tcase \"time\": {\n\t\t\tconst h = String(date.getHours()).padStart(2, \"0\");\n\t\t\tconst mi = String(date.getMinutes()).padStart(2, \"0\");\n\t\t\tconst s = String(date.getSeconds()).padStart(2, \"0\");\n\t\t\treturn `${h}:${mi}:${s}`;\n\t\t}\n\t}\n}\n\n/**\n * Create a model-aware transfer serializer that converts `Date` objects to\n * the appropriate wire format **and** strips internal `__*` properties.\n *\n * Uses `__entityType` from the transfer (before stripping) to look up\n * the field type in the registry and format `Date` values accordingly.\n * Falls back to `Date.toISOString()` for `Date` values on unregistered fields.\n *\n * @param registry - Mapping of entity type FQNs to temporal field declarations\n * @returns `TransferSerializer` that handles Date→string conversion and property stripping\n *\n * @example\n * ```typescript\n * import { temporalFieldRegistry } from './generated/transfers/_registry';\n *\n * const api = createJudoRestApi({\n * // ...\n * transferSerializer: createModelAwareSerializer(temporalFieldRegistry),\n * });\n * ```\n */\nexport function createModelAwareSerializer(\n\tregistry: TemporalFieldRegistry,\n\t/**\n\t * Per owner type, the target type of each relation. A nested transfer that was\n\t * never persisted carries no `__entityType`, so this is the only way to classify\n\t * its temporal attributes.\n\t */\n\trelationTypes: Record<string, Record<string, string>> = {}\n): TransferSerializer {\n\treturn {\n\t\tserialize(transfer: unknown, typeName?: string): unknown {\n\t\t\tif (transfer == null) return transfer;\n\t\t\tif (typeof transfer !== \"object\") return transfer;\n\t\t\tif (Array.isArray(transfer)) return transfer.map((item) => this.serialize(item, typeName));\n\n\t\t\tconst obj = transfer as Record<string, unknown>;\n\t\t\t// A persisted transfer reports its own type, dot-separated (`Pkg.Type`) while\n\t\t\t// the model names it `Pkg::Type`; a transfer that was never persisted has none.\n\t\t\t// The caller's hint classifies whatever the reported type does not.\n\t\t\tconst reported = obj.__entityType;\n\t\t\tconst candidates = typeof reported === \"string\" ? [reported, modelTypeName(reported), typeName] : [typeName];\n\t\t\tconst entityType =\n\t\t\t\tcandidates.find(\n\t\t\t\t\t(candidate) => candidate !== undefined && (candidate in registry || candidate in relationTypes)\n\t\t\t\t) ?? candidates[0];\n\t\t\tconst temporalFields = entityType ? registry[entityType] : undefined;\n\t\t\tconst result: Record<string, unknown> = {};\n\n\t\t\tfor (const [key, value] of Object.entries(obj)) {\n\t\t\t\tif (isInternalProperty(key)) continue;\n\n\t\t\t\tif (value instanceof Date) {\n\t\t\t\t\tconst fieldType = temporalFields?.[key];\n\t\t\t\t\tresult[key] = fieldType ? serializeTemporalValue(value, fieldType) : value.toISOString();\n\t\t\t\t} else if (value != null && typeof value === \"object\") {\n\t\t\t\t\tresult[key] = this.serialize(value, entityType && relationTypes[entityType]?.[key]);\n\t\t\t\t} else {\n\t\t\t\t\tresult[key] = value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t},\n\t};\n}\n","/**\n * Model-aware transfer deserializer for JUDO REST API.\n *\n * Converts temporal field values from their wire format (ISO strings) to\n * native JavaScript `Date` objects at the API boundary. This eliminates\n * the need for developers to handle date parsing, timezone conversion,\n * and format differences.\n *\n * ## Supported conversions\n *\n * | Field type | Wire format (string) | Runtime type |\n * | ------------- | -------------------------------- | ------------------------- |\n * | `date` | `\"YYYY-MM-DD\"` | `Date` (local midnight) |\n * | `timestamp` | `\"YYYY-MM-DDTHH:mm:ss[.SSS]Z\"` | `Date` (UTC) |\n * | `time` | `\"HH:mm[:ss]\"` | `string` (pass-through) |\n *\n * ## How it works\n *\n * The deserializer reads `__entityType` from each response payload to look up\n * the transfer type in the provided {@link TemporalFieldRegistry}. Fields\n * declared as `date` or `timestamp` are converted from ISO strings to `Date`\n * objects. Nested objects and arrays are processed recursively.\n */\n\nimport type { TemporalFieldRegistry, TemporalFieldType, TransferDeserializer } from \"./types\";\n\n/**\n * Parse a date-only string (`YYYY-MM-DD`) as a local-timezone `Date`.\n *\n * Avoids the timezone-shift problem of `new Date(\"YYYY-MM-DD\")` which creates\n * a UTC midnight `Date` — displaying as the previous day in negative-offset timezones.\n *\n * @param value - Date string in `YYYY-MM-DD` format\n * @returns `Date` at local midnight, or invalid `Date` if parsing fails\n */\nexport function parseLocalDate(value: string): Date {\n\tconst parts = value.split(\"-\");\n\tif (parts.length !== 3) return new Date(Number.NaN);\n\tconst [y, m, d] = parts.map(Number);\n\treturn new Date(y, m - 1, d);\n}\n\n/**\n * Deserialize a temporal string value to its runtime representation.\n *\n * - `date` → local-midnight `Date` via {@link parseLocalDate}\n * - `timestamp` → `Date` via `new Date(isoString)`\n * - `time` → original string (pass-through)\n *\n * @param value - The string value from the API response\n * @param fieldType - The temporal field type\n * @returns `Date` for `date`/`timestamp`, original string for `time`\n */\nexport function deserializeTemporalValue(value: string, fieldType: TemporalFieldType): Date | string {\n\tswitch (fieldType) {\n\t\tcase \"date\":\n\t\t\treturn parseLocalDate(value);\n\t\tcase \"timestamp\":\n\t\t\treturn new Date(value);\n\t\tcase \"time\":\n\t\t\treturn value;\n\t}\n}\n\n/**\n * Create a model-aware transfer deserializer that converts temporal fields\n * from ISO strings to native `Date` objects.\n *\n * Uses `__entityType` in the response payload to look up the transfer type\n * in the provided registry and convert matching fields. Nested objects and\n * arrays are processed recursively.\n *\n * @param registry - Mapping of entity type FQNs to temporal field declarations\n * @returns `TransferDeserializer` that converts `date`/`timestamp` strings to `Date`\n *\n * @example\n * ```typescript\n * import { temporalFieldRegistry } from './generated/transfers/_registry';\n *\n * const api = createJudoRestApi({\n * // ...\n * transferDeserializer: createModelAwareDeserializer(temporalFieldRegistry),\n * });\n * ```\n */\nexport function createModelAwareDeserializer(registry: TemporalFieldRegistry): TransferDeserializer {\n\treturn {\n\t\tdeserialize(data: unknown): unknown {\n\t\t\tif (data == null || typeof data !== \"object\") return data;\n\n\t\t\tif (Array.isArray(data)) {\n\t\t\t\treturn data.map((item) => this.deserialize(item));\n\t\t\t}\n\n\t\t\tconst obj = data as Record<string, unknown>;\n\t\t\tconst entityType = obj.__entityType as string | undefined;\n\t\t\tconst temporalFields = entityType ? registry[entityType] : undefined;\n\n\t\t\tconst result = { ...obj };\n\n\t\t\t// Recurse into nested objects and arrays\n\t\t\tfor (const [key, value] of Object.entries(result)) {\n\t\t\t\tif (value != null && typeof value === \"object\") {\n\t\t\t\t\tresult[key] = this.deserialize(value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Convert temporal fields for this object\n\t\t\tif (temporalFields) {\n\t\t\t\tfor (const [field, fieldType] of Object.entries(temporalFields)) {\n\t\t\t\t\tconst value = result[field];\n\t\t\t\t\tif (typeof value === \"string\") {\n\t\t\t\t\t\tresult[field] = deserializeTemporalValue(value, fieldType);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t},\n\t};\n}\n","import { type ClassType, type DataElement, type DataType, type TypeNames, typeSimpleName } from \"@judo/model-api\";\nimport type { TemporalFieldRegistry, TemporalFieldType } from \"./types\";\n\n/**\n * Per-type lookups the transfer serializer derives from the loaded model: which\n * attributes are temporal, and which type each relation points at.\n */\n\n/**\n * Modeled data types whose values travel as formatted temporal strings.\n *\n * Both discriminator forms are accepted: the model parser strips the `data:`\n * prefix, while raw XMI carries it.\n */\nconst TEMPORAL_DATA_TYPES: Readonly<Record<string, TemporalFieldType>> = {\n\t\"data:DateType\": \"date\",\n\tDateType: \"date\",\n\t\"data:TimestampType\": \"timestamp\",\n\tTimestampType: \"timestamp\",\n\t\"data:TimeType\": \"time\",\n\tTimeType: \"time\",\n};\n\n/** Class-type discriminators, in parsed and raw form. */\nconst CLASS_TYPES: ReadonlySet<string | undefined> = new Set([\"data:ClassType\", \"ClassType\"]);\n\n/**\n * A freshly loaded model leaves a reference as the target's `xmi:id`; a resolved\n * model carries the object. The model-api types describe the resolved form only.\n */\ntype ModelRef<T> = T | string;\n\n/** Maps an owner type name to the target type name of each of its relations. */\nexport type RelationTypeMap = Record<string, Record<string, string>>;\n\n/**\n * The part of a model these maps read, in loaded or resolved form. An\n * `Application` satisfies it.\n */\nexport interface ModelTypeSource {\n\tdataTypes?: readonly Pick<DataType, \"@type\" | \"xmi:id\">[];\n\tdataElements?: readonly DataElementSource[];\n}\n\ntype DataElementSource = Pick<DataElement, \"@type\"> &\n\tPartial<Pick<ClassType, \"xmi:id\">> &\n\tTypeNames & {\n\t\tattributes?: readonly (Pick<DataElement, \"@type\" | \"name\"> & {\n\t\t\tdataType?: ModelRef<Pick<DataType, \"@type\">>;\n\t\t})[];\n\t\trelations?: readonly (Pick<DataElement, \"@type\" | \"name\"> & { target?: ModelRef<TypeNames> })[];\n\t};\n\nfunction isClassType(element: DataElementSource): boolean {\n\treturn CLASS_TYPES.has(element[\"@type\"]);\n}\n\n/**\n * Derives, per type, which type each of its relations points at.\n *\n * A nested transfer travels inside its owner's payload, and one that was never\n * persisted carries no `__entityType`. Without this map the serializer cannot\n * classify the nested temporal attributes, and the owner's save is rejected with\n * `CONVERSION_FAILED` on `<relation>.<attribute>`.\n */\nexport function buildRelationTypeMapFromModel(application: ModelTypeSource | undefined): RelationTypeMap {\n\tconst classTypes = (application?.dataElements ?? []).filter(isClassType);\n\tconst byXmiId = new Map<string, TypeNames>();\n\tfor (const classType of classTypes) {\n\t\tif (classType[\"xmi:id\"]) byXmiId.set(classType[\"xmi:id\"], classType);\n\t}\n\n\tconst map: RelationTypeMap = {};\n\tfor (const classType of classTypes) {\n\t\tconst targets: Record<string, string> = {};\n\t\tfor (const relation of classType.relations ?? []) {\n\t\t\tconst ref = relation.target;\n\t\t\tconst targetName = typeSimpleName(typeof ref === \"string\" ? byXmiId.get(ref) : ref);\n\t\t\tif (relation.name && targetName) targets[relation.name] = targetName;\n\t\t}\n\t\tif (Object.keys(targets).length === 0) continue;\n\n\t\tfor (const key of [classType.name, classType.simpleName]) {\n\t\t\tif (key) map[key] = { ...map[key], ...targets };\n\t\t}\n\t}\n\n\treturn map;\n}\n\n/**\n * Derives the temporal field registry from the loaded model.\n *\n * The wire format of a temporal value depends on its modeled attribute type: a\n * `date` is a calendar day (`YYYY-MM-DD`), a `timestamp` is an instant. Without\n * that classification a `Date` is serialized as a UTC instant, which the backend\n * rejects for a date attribute (`CONVERSION_FAILED`) and whose timezone shift can\n * move the day.\n *\n * Each type is registered under its qualified name and under its `simpleName`,\n * because API responses report the simple name in `__entityType`, the value the\n * serializer looks up.\n */\nexport function buildTemporalFieldRegistryFromModel(application: ModelTypeSource | undefined): TemporalFieldRegistry {\n\tconst registry: TemporalFieldRegistry = {};\n\tconst declaredTypes = new Map((application?.dataTypes ?? []).map((dataType) => [dataType[\"xmi:id\"], dataType]));\n\n\tconst temporalTypeOf = (ref: ModelRef<Pick<DataType, \"@type\">> | undefined): TemporalFieldType | undefined => {\n\t\tconst dataType = typeof ref === \"string\" ? declaredTypes.get(ref) : ref;\n\t\treturn dataType && TEMPORAL_DATA_TYPES[dataType[\"@type\"]];\n\t};\n\n\tfor (const classType of (application?.dataElements ?? []).filter(isClassType)) {\n\t\tconst fields: Record<string, TemporalFieldType> = {};\n\t\tfor (const attribute of classType.attributes ?? []) {\n\t\t\tconst temporalType = temporalTypeOf(attribute.dataType);\n\t\t\tif (temporalType && attribute.name) fields[attribute.name] = temporalType;\n\t\t}\n\t\tif (Object.keys(fields).length === 0) continue;\n\n\t\tif (classType.name) {\n\t\t\tregistry[classType.name] = { ...registry[classType.name], ...fields };\n\t\t}\n\t\tif (classType.simpleName && classType.simpleName !== classType.name) {\n\t\t\t// Types sharing a simple name describe the same entity's attributes, so\n\t\t\t// merging keeps every field resolvable under the reported __entityType.\n\t\t\tregistry[classType.simpleName] = { ...registry[classType.simpleName], ...fields };\n\t\t}\n\t}\n\n\treturn registry;\n}\n"],"mappings":";;;;;;;;;;A,GAwHGuC,IAAI;CACN,MAAM;CACN,QAAQ;CACR,KAAK;CACL,OAAO;CACP,KAAK;CACL,QAAQ;CACR,OAAO;CACP,iBAAiB;CACjB,UAAU;CACV,QAAQ;CACR,iBAAiB;CACjB,QAAQ;CACR,SAAS;CACT,QAAQ;AACT;AAoEA,SAASC,EAAE,GAAG,GAAG;CAChB,IAAI,IAAI,GAAG,sBAAsB,GAAG,gBAAgB,GAAG,aAAa,GAAG,MAAM,OAAO,KAAK,IAAI,OAAO,EAAE,EAAE;CACxG,OAAO,MAAM,KAAK,IAAI,MAAM,KAAK,IAAI,KAAK,IAAI,OAAO,MAAM;AAC5D;AAEA,IAAIC,oBAAoB,IAAI,IAAI,CAAC,gBAAgB,mBAAmB,CAAC;AACrE,SAAS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