@apia/api 0.0.9-alpha.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,43 +1,1557 @@
1
- 'use strict';
2
-
3
- var ce = require('axios');
4
- var lodash = require('lodash');
5
- var J = require('qs');
6
- var session = require('@apia/session');
7
- var util = require('@apia/util');
8
- var notifications = require('@apia/notifications');
9
- var p = require('react');
10
- var themeUi = require('theme-ui');
11
- var validations = require('@apia/validations');
12
- var components = require('@apia/components');
13
- var theme = require('@apia/theme');
14
- var jsxRuntime = require('theme-ui/jsx-runtime');
15
-
16
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
17
-
18
- function _interopNamespace(e) {
19
- if (e && e.__esModule) return e;
20
- var n = Object.create(null);
21
- if (e) {
22
- Object.keys(e).forEach(function (k) {
23
- if (k !== 'default') {
24
- var d = Object.getOwnPropertyDescriptor(e, k);
25
- Object.defineProperty(n, k, d.get ? d : {
26
- enumerable: true,
27
- get: function () { return e[k]; }
28
- });
29
- }
30
- });
31
- }
32
- n.default = e;
33
- return Object.freeze(n);
34
- }
35
-
36
- var ce__default = /*#__PURE__*/_interopDefault(ce);
37
- var J__default = /*#__PURE__*/_interopDefault(J);
38
- var p__namespace = /*#__PURE__*/_interopNamespace(p);
39
-
40
- var Ae=Object.defineProperty,ye=Object.defineProperties;var Te=Object.getOwnPropertyDescriptors;var P=Object.getOwnPropertySymbols;var G=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable;var j=(e,t,n)=>t in e?Ae(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d=(e,t)=>{for(var n in t||(t={}))G.call(t,n)&&j(e,n,t[n]);if(P)for(var n of P(t))Y.call(t,n)&&j(e,n,t[n]);return e},T=(e,t)=>ye(e,Te(t));var q=(e,t)=>{var n={};for(var o in e)G.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&P)for(var o of P(e))t.indexOf(o)<0&&Y.call(e,o)&&(n[o]=e[o]);return n};var k=(e,t,n)=>new Promise((o,a)=>{var l=c=>{try{i(n.next(c));}catch(f){a(f);}},s=c=>{try{i(n.throw(c));}catch(f){a(f);}},i=c=>c.done?o(c.value):Promise.resolve(c.value).then(l,s);i((n=n.apply(e,t)).next());});var we=p.createContext("apiaApi"),xe=({children:e,id:t})=>(jsxRuntime.jsx(we.Provider,{value:t,children:e})),ee=p__namespace.memo(xe);var V=new class extends util.EventEmitter{},W=new class extends util.EventEmitter{},O="ApiaApiForm",ne={};function ie(e,t){return k(this,null,function*(){return new Promise(n=>{var o,a,l;try{let s=/^\/?([\w\d_-]+)\/?(?:\(([^)]*)\))?$/,i=e.match(s);if(i){let c=i[1],f=i[2],A=[...(l=(a=(o=t.configuration)==null?void 0:o.methodsPath)==null?void 0:a.split("/").filter(g=>!!g))!=null?l:[],c].join("/"),R=g=>{typeof g.default!="function"&&m();let h=g.default;ne[c]=w=>{var L;return h(t,T(d({},w),{inlineArguments:(L=f==null?void 0:f.split(",").map(r=>r.startsWith("'")||r.startsWith('"')?r.slice(1,r.length-1):r))!=null?L:[]}))},n(ne[c]);},m=()=>{throw new Error(`${c}.ts not found at ${A}.ts nor ./${c}.ts`)};import(`/api/methods/${A}.ts`).then(R).catch(()=>{var g;((g=t.configuration)==null?void 0:g.methodsPath)!==void 0?import(`/api/methods/${c}.ts`).then(R).catch(m):m();});}}catch(s){console.error(s),t.reset(),t.setError({type:"danger",message:"Error while loading current method."});}})})}function He(e){return typeof e.canClose=="boolean"&&typeof e.type=="string"&&!!e.form}function Pe(e){return typeof e.canClose=="boolean"&&typeof e.type=="string"&&!!e.function}function Ue(e){return !!(typeof e.canClose=="boolean"&&typeof e.type=="string"&&typeof e.text=="object"&&e.text&&typeof e.text.label=="string")}var z=new util.WithEventsValue;function Ne(){let[,e,t]=util.useStateRef(void 0),n=p__namespace.useCallback(o=>{e(o);},[e]);return util.useMount(()=>{z.on("update",n);}),util.useUnmount(()=>z.off("update",n)),t}var _=new class extends util.EventEmitter{emit(t,n){super.emit(t,n);}};function ae(e,t,n){return z.value=n,He(e)?(_.emit("form",e),!0):Pe(e)?(W.emit("method",{name:e.function.name,props:{messages:e.function.messages,attributes:e.function,currentUrl:t}}),!0):Ue(e)?(V.emit("message",{predicate:e.text.label,title:e.text.title}),!0):!1}var U={disabled:!1,isLoading:!1,isMultipart:!1,progress:0,errors:{}},Fe=()=>{var h,w,L;let e=Ne(),[t,n]=p__namespace.useState(T(d({},U),{windowIndex:-1})),[o,a]=p__namespace.useState(void 0);p__namespace.useEffect(()=>_.on("form",a),[]);let l=p__namespace.useCallback((r,u)=>validations.validationsStore.setFieldValue(O,r,u),[]);p__namespace.useEffect(()=>{var C,M,b;if(!o)return;let r=util.arrayOrArray((b=(M=(C=o==null?void 0:o.form)==null?void 0:C.elements)==null?void 0:M.element)!=null?b:[]),u=!1,x=Object.values(r),y=0;for(;y<x.length&&!u;)x[y++].type==="file"&&(u=!0);n(H=>T(d(d({},H),U),{isMultipart:u}));},[o]);let g=components.useModal(),{show:s,onClose:i}=g,c=q(g,["show","onClose"]),f=p__namespace.useCallback(()=>{var r,u;i(),_.emit("form",void 0),n(x=>d(d({},x),U)),(u=(r=e.current)==null?void 0:r.modalConfiguration)!=null&&u.onClose&&e.current.modalConfiguration.onClose();},[i,e]),A=p__namespace.useRef(null);p__namespace.useEffect(()=>{var u;let r=(u=A.current)==null?void 0:u.querySelectorAll("a,input,textarea,button");(r==null?void 0:r.length)===1&&components.focus.on([...r][0]);});let R=p__namespace.useCallback(r=>{notifications.notify(d({},r));},[]),m=p__namespace.useCallback(()=>({alert,close:f,configuration:e.current,formDefinition:o,reset:()=>n(u=>d(d({},u),U)),setError:R,setMessage:u=>{var x,y;(y=(x=e.current)==null?void 0:x.modalConfiguration)!=null&&y.onMessage&&e.current.modalConfiguration.onMessage(u);},setState:n,state:t,setValue:l}),[f,e,o,R,t,l]);return p__namespace.useEffect(()=>{let r=H=>k(void 0,[H],function*({name:y,props:{messages:C,attributes:M,currentUrl:b}}){let v=yield ie(`${y}`,m());v&&v({messages:C,attributes:M,currentUrl:b});}),u=y=>{var b,H,v,K;let C=m();notifications.notify({message:y.predicate,type:"warning",onClose:(H=(b=C.configuration)==null?void 0:b.modalConfiguration)==null?void 0:H.onMessageClose});let M=(K=(v=C.configuration)==null?void 0:v.modalConfiguration)==null?void 0:K.onMessage;M&&M(y);},x=y=>k(void 0,null,function*(){if(y.toDo==="ajaxHiddeAll"&&f(),y.toDo==="functionTimedCall"){let C=yield ie(util.arrayOrArray(y.param)[1],m());C&&setTimeout(()=>{var M;return C({currentUrl:(M=o==null?void 0:o.form.action)!=null?M:"noUrl"})},Number(y.param[0]));}});return V.on("message",u),W.on("method",r),N.on("action",x),()=>{V.off("message",u),W.off("method",r),N.off("action",x);}},[t.windowIndex,i,f]),p__namespace.useEffect(()=>{o&&s();},[o]),jsxRuntime.jsx(ee,{id:O,children:jsxRuntime.jsx(components.Modal,T(d({ref:A,onClose:f,id:O,title:(L=(w=(h=e.current)==null?void 0:h.modalConfiguration)==null?void 0:w.modalTitle)!=null?L:o==null?void 0:o.form.title,size:"md-fixed",shouldCloseOnEsc:!t.disabled,shouldCloseOnOverlayClick:!t.disabled,initialFocusGetter:p__namespace.useCallback(r=>r==null?void 0:r.querySelector(util.focusSelector),[])},c),{children:o&&jsxRuntime.jsxs(themeUi.Box,T(d({},theme.getVariant("layout.common.modals.apiaApi")),{children:["NO EST\xC1 IMPLEMENTADA LA PROPIEDAD handleLoad. Falta pasar:",jsxRuntime.jsxs("ul",{children:[jsxRuntime.jsx("li",{children:"todos los componentes de validaci\xF3n (input, check, etc)"}),jsxRuntime.jsxs("li",{children:["M\xE9todos y componentes del apiaApiHandler (./fields, ./buttons, etc)"," ",jsxRuntime.jsx("strong",{children:"Ver que quiz\xE1s no es necesario pasar todos los m\xE9todos en este momento"}),", sino solamente aquellos que sean necesarios al momento de realizar alguna acci\xF3n particular."," ",jsxRuntime.jsx("strong",{children:"De hecho es un buen momento para hacer limpieza y refactoreo"})]})]}),"En cambio ",jsxRuntime.jsx("strong",{children:"el validationsStore si est\xE1 pasado"}),". Solamente faltan los componentes."]}))}))})};p__namespace.memo(Fe);util.debugDispatcher.on("parseXml",t=>k(void 0,[t],function*([e]){let n=yield util.parseXmlAsync(e);console.info(n);}),"Acepta un par\xE1metro de tipo string y realiza un parseo como si fuera xml, convirti\xE9ndolo a objeto javascript.");var E={debug:!0,colors:{exception:"red",alert:"yellow",message:"lightgreen"},handleLoad:!1},Je="ApiaApiConfig",ue={},re=localStorage.getItem(Je);re&&(ue=JSON.parse(re));function D(e){return lodash.merge({},E,e,ue)}function pe(e,t,n){let o=e,a=o.indexOf("?");a===-1?o+="?":a!==o.length-1&&!o.endsWith("&")&&(o+="&");let l=`${o}${t?J__default.default.stringify(t,n):""}`;return (l.endsWith("&")||l.endsWith("?"))&&(l=l.slice(0,l.length-1)),l}var fe=e=>{var n;let t=(n=e.match(/action=(\w+)/))==null?void 0:n[1];return t!=null?t:"noAction"},N=new class extends util.EventEmitter{};function I(e,t=(n=>(n=E.colors)!=null?n:{exception:"red",alert:"yellow",message:"green"})()){return t[e]}var $=e=>{let t;typeof e!="string"?e.message?t=e.message:t=e.toString():t=e,notifications.notify({type:"danger",message:e.message}),console.log("%c ","font-size:10vh"),console.log("%cError in ApiaApi","color:red;font-size:2em;font-weight:bold"),console.log(`red/${t}`,{error:e}),console.log("%c ","font-size:10vh");};function Be(e){return e.headers["content-type"].match("application/json")}function Ke(e){return e.headers["content-type"].match(/(?:application|text)?\/xml/)}function je(e){return e.headers["content-type"].match(/(?:application|text)?\/html/)}function Ge(e){var t,n;e&&(D().debug&&console.log("%cHandled actions: ",`color: ${(n=(t=D().colors)==null?void 0:t.message)!=null?n:"green"}`,{actions:e}),util.arrayOrArray(e.action).forEach(a=>{N.emit("action",T(d({},a),{param:util.arrayOrArray(a.param)}));}));}function le({exceptions:e,onClose:t,sysExceptions:n,sysMessages:o}){try{import(`/api/onClose/${t}.ts`).then(a=>{if(e||n||o){let l=notifications.getNotificationMessageObj({exceptions:e,onClose:t,sysExceptions:n,sysMessages:o});l?l.forEach(s=>{notifications.notify(T(d({},s),{onClose:a.default}));}):a.default();}else a.default();},a=>{notifications.notify({message:`onClose action not found: ${String(a)}`,type:"danger"});});}catch(a){ge({exceptions:e,sysExceptions:n,sysMessages:o}),console.error("Error while handling onClose"),console.error(a);}}function ge(e){if(!e)return;let{exceptions:t,sysMessages:n,sysExceptions:o}=e;if(t||o||n)try{notifications.dispatchNotifications({exceptions:t,sysExceptions:o,sysMessages:n});}catch(a){$(new Error(a));}}var Ye=(o,a,...l)=>k(void 0,[o,a,...l],function*(e,t,n=E){var c;let s=D(n),i;if(Be(e))typeof e.data=="string"?i=JSON.parse(e.data.trim()):typeof e.data=="object"&&e.data&&(i=e.data);else if(Ke(e))i=yield util.parseXmlAsync(e.data).catch(A=>{$(new Error(A));});else if(je(e))return console.error("El contenido devuelto es Html, no se esperaba esa respuesta"),null;if(s.validateResponse){let A=yield s.validateResponse(T(d({},e),{data:(c=i==null?void 0:i.load)!=null?c:i}));if(typeof A=="string")throw new Error(`Validation error: ${A}`);if(!A)throw new Error("Error")}if(i){let f=i,{actions:A,onClose:R,exceptions:m,sysExceptions:g,sysMessages:h,load:w}=f,L=q(f,["actions","onClose","exceptions","sysExceptions","sysMessages","load"]);return L.code==="-1"&&m?(session.session.invalidate(),null):(m&&s.debug&&console.log(`${I("exception",s.colors)}/parseSuccessfulResponse`,{exceptions:m}),g&&s.debug&&console.log(`${I("exception",s.colors)}/parseSuccessfulResponse`,{sysExceptions:g}),h&&s.debug&&console.log(`${I("alert",s.colors)}/parseSuccessfulResponse`,{sysMessages:h}),Ge(A),s.handleLoad&&R?le({exceptions:m,onClose:R,sysExceptions:g,sysMessages:h}):ge({exceptions:m,sysExceptions:g,sysMessages:h}),w?(s.handleLoad&&(console.log(`${I("message",s.colors)}/handleLoad`,{load:w}),ae(w,t,{methodsPath:n.methodsPath,modalConfiguration:T(d({},s.modalConfiguration),{onClose:()=>{var r,u;R&&le({exceptions:m,onClose:R,sysExceptions:g,sysMessages:h}),(r=s.modalConfiguration)!=null&&r.onClose&&((u=s.modalConfiguration)==null||u.onClose());}})})||console.log(`${I("exception",s.colors)}/unhandledLoad -> There is no handler defined`,{load:w})),T(d({},w),{sysMessages:h,exceptions:m,sysExceptions:g})):T(d({},L),{sysMessages:h,exceptions:m,sysExceptions:g}))}return null});function me(o,a){return k(this,arguments,function*(e,t,n=E){var s;let l=D(n);try{if(!e||e.data===void 0)l.debug&&console.log(`${I("alert",l.colors)}/ApiaApi wrong response`);else {let i=yield Ye(e,t,l),c=fe(t);return l.debug&&console.log(`${I("message",l.colors)}/ <- ApiaApi.${(s=e.config.method)!=null?s:""} ${c} `,{data:i}),T(d({},e),{data:i,hasError:!!(i!=null&&i.exceptions)||!!(i!=null&&i.sysExceptions),hasMessages:!!(i!=null&&i.sysMessages)})}}catch(i){return $(new Error(i)),null}return null})}function Ze(e,t){return k(this,null,function*(){let n=typeof e!="string"?B():e,o=typeof e=="string"?t!=null?t:E:e,a=T(d({},D(o)),{postData:o.postDataTreatement==="stringify"?J__default.default.stringify(o.postData,o.stringifyOptions):o.postData}),l=pe(n,a.queryData,a.stringifyOptions);if(a.debug){let i=n.split("&"),c=fe(n);console.log(`${I("message",a.colors)}/ApiaApi.post ${c}`,{url:l,queryDataInURL:[...i],queryData:a.queryData,formData:a.postData,stringifyOptiopns:a.stringifyOptions});}let s=yield ce__default.default.post(l,a.postData,a.axiosConfig).catch(i=>{$(new Error(i));});return s?me(s,n,a):null})}function et(e,t){return k(this,null,function*(){let n=typeof e!="string"?B():e,o=D(typeof e=="string"?t!=null?t:E:e),a=pe(n,o.queryData,o.stringifyOptions);o.debug&&console.log(`${I("message",o.colors)}/ApiaApi.get`,{url:a});let l=yield ce__default.default.get(a,o.axiosConfig).catch(s=>{$(new Error(s));});return l?yield me(l,n,o):null})}var tt={get:et,getConfig:D,post:Ze};function B(e){var f,A;let t={};if(e){let c=e,r=q(c,["ajaxUrl","queryString","stringifyOptions","shouldAvoidTabId","preventAsXmlParameter","avoidTabId"]);t=d({},r);}let n=J__default.default.stringify(t,(f=e==null?void 0:e.stringifyOptions)!=null?f:{arrayFormat:"repeat",encodeValuesOnly:!1}),o=(A=e==null?void 0:e.ajaxUrl)!=null?A:window.URL_REQUEST_AJAX;o.indexOf("?")===o.length-1&&(o=o.slice(0,o.length-1)),o.startsWith("/")||(o=`/${o}`);let a=window.TAB_ID_REQUEST.match(/tokenId=(\w+)/),l=(a!=null?a:[])[1],s=(e!=null&&e.tabId?`&tabId=${e.tabId}&tokenId=${l}`:window.TAB_ID_REQUEST).slice(1);e!=null&&e.avoidTabId&&(s="");let{CONTEXT:i}=window;return i!=null&&i.endsWith("/")&&(i+=i.slice(0,i.length-1)),`${i}${o}?${e!=null&&e.preventAsXmlParameter?"":"asXml=true&"}${e!=null&&e.queryString?`${e.queryString}&`:""}${n?`${n}&`:""}${s}`}var ot=tt;
41
-
42
- exports.ApiaApi = ot;
43
- exports.makeApiaUrl = B;
1
+ import { jsx, jsxs } from 'react/jsx-runtime';
2
+ import * as React from 'react';
3
+ import React__default, { createContext, useMemo } from 'react';
4
+ import { Box } from 'theme-ui';
5
+ import { debugDispatcher, EventEmitter, parseXmlAsync, arrayOrArray, useMount, encrypt, WithEventsValue, focus, focusSelector, useStateRef, useUnmount } from '@apia/util';
6
+ import { notify, getNotificationMessageObj, dispatchNotifications } from '@apia/notifications';
7
+ import { classToValidate, Checkbox, FileInput, classToValidationFunction, Input, Radio, Select, useFormContext, validationsStore, hasSucceedFormValidation, Form } from '@apia/validations';
8
+ import { SimpleButton, useModal, Modal, ProgressBar } from '@apia/components';
9
+ import { getVariant } from '@apia/theme';
10
+ import axios from 'axios';
11
+ import { merge, uniqueId } from 'lodash';
12
+ import QueryString from 'qs';
13
+ import { session } from '@apia/session';
14
+
15
+ const ApiaApiId = createContext("apiaApi");
16
+ const ApiaApiContext = ({
17
+ children,
18
+ id
19
+ }) => {
20
+ return /* @__PURE__ */ jsx(ApiaApiId.Provider, { value: id, children });
21
+ };
22
+ var ApiaApiContext$1 = React.memo(ApiaApiContext);
23
+
24
+ var __defProp$8 = Object.defineProperty;
25
+ var __defProps$4 = Object.defineProperties;
26
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
27
+ var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
28
+ var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
29
+ var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
30
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
31
+ var __spreadValues$8 = (a, b) => {
32
+ for (var prop in b || (b = {}))
33
+ if (__hasOwnProp$8.call(b, prop))
34
+ __defNormalProp$8(a, prop, b[prop]);
35
+ if (__getOwnPropSymbols$8)
36
+ for (var prop of __getOwnPropSymbols$8(b)) {
37
+ if (__propIsEnum$8.call(b, prop))
38
+ __defNormalProp$8(a, prop, b[prop]);
39
+ }
40
+ return a;
41
+ };
42
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
43
+ var __objRest$1 = (source, exclude) => {
44
+ var target = {};
45
+ for (var prop in source)
46
+ if (__hasOwnProp$8.call(source, prop) && exclude.indexOf(prop) < 0)
47
+ target[prop] = source[prop];
48
+ if (source != null && __getOwnPropSymbols$8)
49
+ for (var prop of __getOwnPropSymbols$8(source)) {
50
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$8.call(source, prop))
51
+ target[prop] = source[prop];
52
+ }
53
+ return target;
54
+ };
55
+ var __async$2 = (__this, __arguments, generator) => {
56
+ return new Promise((resolve, reject) => {
57
+ var fulfilled = (value) => {
58
+ try {
59
+ step(generator.next(value));
60
+ } catch (e) {
61
+ reject(e);
62
+ }
63
+ };
64
+ var rejected = (value) => {
65
+ try {
66
+ step(generator.throw(value));
67
+ } catch (e) {
68
+ reject(e);
69
+ }
70
+ };
71
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
72
+ step((generator = generator.apply(__this, __arguments)).next());
73
+ });
74
+ };
75
+ debugDispatcher.on(
76
+ "parseXml",
77
+ (_0) => __async$2(void 0, [_0], function* ([text]) {
78
+ const result = yield parseXmlAsync(text);
79
+ console.info(result);
80
+ }),
81
+ "Acepta un par\xE1metro de tipo string y realiza un parseo como si fuera xml, convirti\xE9ndolo a objeto javascript."
82
+ );
83
+ const defaultConfig = {
84
+ debug: true,
85
+ colors: {
86
+ exception: "red",
87
+ alert: "yellow",
88
+ message: "lightgreen"
89
+ },
90
+ handleLoad: false
91
+ };
92
+ const STORED_CONFIG = "ApiaApiConfig";
93
+ let forcedConfig = {};
94
+ const storedConfig = localStorage.getItem(STORED_CONFIG);
95
+ if (storedConfig)
96
+ forcedConfig = JSON.parse(storedConfig);
97
+ function getConfig(outerBehaveConfig) {
98
+ return merge({}, defaultConfig, outerBehaveConfig, forcedConfig);
99
+ }
100
+ function makeUrl(url, queryData, stringifyOptions) {
101
+ let finalUrl = url;
102
+ const questionMarkIndex = finalUrl.indexOf("?");
103
+ if (questionMarkIndex === -1)
104
+ finalUrl += "?";
105
+ else if (questionMarkIndex !== finalUrl.length - 1 && !finalUrl.endsWith("&"))
106
+ finalUrl += "&";
107
+ let parsedUrl = `${finalUrl}${queryData ? QueryString.stringify(queryData, stringifyOptions) : ""}`;
108
+ if (parsedUrl.endsWith("&") || parsedUrl.endsWith("?")) {
109
+ parsedUrl = parsedUrl.slice(0, parsedUrl.length - 1);
110
+ }
111
+ return parsedUrl;
112
+ }
113
+ const getURLActionName = (url) => {
114
+ var _a;
115
+ const actionIdx = (_a = url.match(/action=(\w+)/)) == null ? void 0 : _a[1];
116
+ return actionIdx != null ? actionIdx : "noAction";
117
+ };
118
+ const ApiaActions = new class ApiaActions2 extends EventEmitter {
119
+ }();
120
+ function getColor(color, colors = ((_a) => (_a = defaultConfig.colors) != null ? _a : {
121
+ exception: "red",
122
+ alert: "yellow",
123
+ message: "green"
124
+ })()) {
125
+ return colors[color];
126
+ }
127
+ const handleWrongResponse = (error) => {
128
+ let errorMessage;
129
+ if (typeof error !== "string") {
130
+ if (error.message)
131
+ errorMessage = error.message;
132
+ else
133
+ errorMessage = error.toString();
134
+ } else
135
+ errorMessage = error;
136
+ notify({
137
+ type: "danger",
138
+ message: error.message.replaceAll("AxiosError", "Error")
139
+ });
140
+ console.log("%c ", "font-size:10vh");
141
+ console.log("%cError in ApiaApi", "color:red;font-size:2em;font-weight:bold");
142
+ console.log(`red/${errorMessage}`, { error });
143
+ console.log("%c ", "font-size:10vh");
144
+ };
145
+ function isJsonResponse(response) {
146
+ return response.headers["content-type"].match("application/json");
147
+ }
148
+ function isXmlResponse(response) {
149
+ return response.headers["content-type"].match(
150
+ /(?:application|text)?\/xml/
151
+ );
152
+ }
153
+ function isHtmlResponse(response) {
154
+ return response.headers["content-type"].match(
155
+ /(?:application|text)?\/html/
156
+ );
157
+ }
158
+ function handleActions(actions) {
159
+ var _a, _b;
160
+ if (actions) {
161
+ if (getConfig().debug)
162
+ console.log(
163
+ "%cHandled actions: ",
164
+ `color: ${(_b = (_a = getConfig().colors) == null ? void 0 : _a.message) != null ? _b : "green"}`,
165
+ { actions }
166
+ );
167
+ const actionsArray = arrayOrArray(actions.action);
168
+ actionsArray.forEach((action) => {
169
+ ApiaActions.emit("action", __spreadProps$4(__spreadValues$8({}, action), {
170
+ param: arrayOrArray(action.param)
171
+ }));
172
+ });
173
+ }
174
+ }
175
+ function handleOnClose({
176
+ exceptions,
177
+ onClose,
178
+ sysExceptions,
179
+ sysMessages
180
+ }) {
181
+ try {
182
+ import(
183
+ /* webpackChunkName: "api-[request]" */
184
+ `/api/onClose/${onClose}.ts`
185
+ ).then(
186
+ (func) => {
187
+ if (exceptions || sysExceptions || sysMessages) {
188
+ const notificationsObject = getNotificationMessageObj({
189
+ exceptions,
190
+ onClose,
191
+ sysExceptions,
192
+ sysMessages
193
+ });
194
+ if (notificationsObject)
195
+ notificationsObject.forEach((notification) => {
196
+ notify(__spreadProps$4(__spreadValues$8({}, notification), {
197
+ onClose: func.default
198
+ }));
199
+ });
200
+ else
201
+ func.default();
202
+ } else
203
+ func.default();
204
+ },
205
+ (e) => {
206
+ notify({
207
+ message: `onClose action not found: ${String(e)}`,
208
+ type: "danger"
209
+ });
210
+ }
211
+ );
212
+ } catch (e) {
213
+ parseMessages({ exceptions, sysExceptions, sysMessages });
214
+ console.error("Error while handling onClose");
215
+ console.error(e);
216
+ }
217
+ }
218
+ function parseMessages(response) {
219
+ if (!response)
220
+ return;
221
+ const { exceptions, sysMessages, sysExceptions } = response;
222
+ if (exceptions || sysExceptions || sysMessages) {
223
+ try {
224
+ dispatchNotifications({
225
+ exceptions,
226
+ sysExceptions,
227
+ sysMessages
228
+ });
229
+ } catch (e) {
230
+ handleWrongResponse(new Error(e));
231
+ }
232
+ }
233
+ }
234
+ const parseSuccessfulResponse = (_0, _1, ..._2) => __async$2(void 0, [_0, _1, ..._2], function* (response, currentUrl, outerBehaveConfig = defaultConfig) {
235
+ var _a;
236
+ const behaveConfig = getConfig(outerBehaveConfig);
237
+ let parsedObj;
238
+ if (isJsonResponse(response)) {
239
+ if (typeof response.data === "string")
240
+ parsedObj = JSON.parse(
241
+ response.data.trim()
242
+ );
243
+ else if (typeof response.data === "object" && response.data)
244
+ parsedObj = response.data;
245
+ } else if (isXmlResponse(response)) {
246
+ parsedObj = yield parseXmlAsync(response.data).catch(
247
+ (e) => {
248
+ handleWrongResponse(new Error(e));
249
+ }
250
+ );
251
+ } else if (isHtmlResponse(response)) {
252
+ console.error(
253
+ "El contenido devuelto es Html, no se esperaba esa respuesta"
254
+ );
255
+ return null;
256
+ }
257
+ if (behaveConfig.validateResponse) {
258
+ const validateResult = yield behaveConfig.validateResponse(__spreadProps$4(__spreadValues$8({}, response), {
259
+ data: (_a = parsedObj == null ? void 0 : parsedObj.load) != null ? _a : parsedObj
260
+ }));
261
+ if (typeof validateResult === "string")
262
+ throw new Error(`Validation error: ${validateResult}`);
263
+ else if (!validateResult) {
264
+ throw new Error("Error");
265
+ }
266
+ }
267
+ if (parsedObj) {
268
+ const _b = parsedObj, {
269
+ actions,
270
+ onClose,
271
+ exceptions,
272
+ sysExceptions,
273
+ sysMessages,
274
+ load
275
+ } = _b, rest = __objRest$1(_b, [
276
+ "actions",
277
+ "onClose",
278
+ "exceptions",
279
+ "sysExceptions",
280
+ "sysMessages",
281
+ "load"
282
+ ]);
283
+ if (rest.code === "-1" && exceptions) {
284
+ session.invalidate();
285
+ return null;
286
+ }
287
+ if (exceptions && behaveConfig.debug) {
288
+ console.log(
289
+ `%cparseSuccessfulResponse`,
290
+ `color: ${getColor("exception", behaveConfig.colors)}`,
291
+ {
292
+ exceptions
293
+ }
294
+ );
295
+ }
296
+ if (sysExceptions && behaveConfig.debug) {
297
+ console.log(
298
+ `%cparseSuccessfulResponse`,
299
+ `color: ${getColor("exception", behaveConfig.colors)}`,
300
+ {
301
+ sysExceptions
302
+ }
303
+ );
304
+ }
305
+ if (sysMessages && behaveConfig.debug) {
306
+ console.log(
307
+ `%cparseSuccessfulResponse`,
308
+ `color: ${getColor("alert", behaveConfig.colors)}`,
309
+ {
310
+ sysMessages
311
+ }
312
+ );
313
+ }
314
+ handleActions(actions);
315
+ if (behaveConfig.handleLoad && onClose)
316
+ handleOnClose({
317
+ exceptions,
318
+ onClose,
319
+ sysExceptions,
320
+ sysMessages
321
+ });
322
+ else
323
+ parseMessages({ exceptions, sysExceptions, sysMessages });
324
+ if (load) {
325
+ if (behaveConfig.handleLoad) {
326
+ console.log(
327
+ `%chandleLoad`,
328
+ `color: ${getColor("message", behaveConfig.colors)}`,
329
+ {
330
+ load
331
+ }
332
+ );
333
+ if (!handle(load, currentUrl, {
334
+ methodsPath: outerBehaveConfig.methodsPath,
335
+ modalConfiguration: __spreadProps$4(__spreadValues$8({}, behaveConfig.modalConfiguration), {
336
+ onClose: () => {
337
+ var _a2, _b2;
338
+ if (onClose)
339
+ handleOnClose({
340
+ exceptions,
341
+ onClose,
342
+ sysExceptions,
343
+ sysMessages
344
+ });
345
+ if ((_a2 = behaveConfig.modalConfiguration) == null ? void 0 : _a2.onClose)
346
+ (_b2 = behaveConfig.modalConfiguration) == null ? void 0 : _b2.onClose();
347
+ }
348
+ })
349
+ })) {
350
+ console.log(
351
+ `%cunhandledLoad -> There is no handler defined`,
352
+ `color: ${getColor("exception", behaveConfig.colors)}`,
353
+ {
354
+ load
355
+ }
356
+ );
357
+ }
358
+ }
359
+ return __spreadProps$4(__spreadValues$8({}, load), { sysMessages, exceptions, sysExceptions });
360
+ }
361
+ return __spreadProps$4(__spreadValues$8({}, rest), { sysMessages, exceptions, sysExceptions });
362
+ }
363
+ return null;
364
+ });
365
+ function handleResponse(_0, _1) {
366
+ return __async$2(this, arguments, function* (result, currentUrl, outerBehaveConfig = defaultConfig) {
367
+ var _a;
368
+ const behaveConfig = getConfig(outerBehaveConfig);
369
+ try {
370
+ if (!result || result.data === void 0) {
371
+ if (behaveConfig.debug)
372
+ console.log(
373
+ `%cApiaApi wrong response`,
374
+ `color: ${getColor("alert", behaveConfig.colors)}`
375
+ );
376
+ } else {
377
+ const parsedResponse = yield parseSuccessfulResponse(
378
+ result,
379
+ currentUrl,
380
+ behaveConfig
381
+ );
382
+ const action = getURLActionName(currentUrl);
383
+ if (behaveConfig.debug)
384
+ console.log(
385
+ `%c <- ApiaApi.${(_a = result.config.method) != null ? _a : ""} ${action} `,
386
+ `color: ${getColor("message", behaveConfig.colors)}`,
387
+ {
388
+ data: parsedResponse
389
+ }
390
+ );
391
+ return __spreadProps$4(__spreadValues$8({}, result), {
392
+ data: parsedResponse,
393
+ hasError: !!(parsedResponse == null ? void 0 : parsedResponse.exceptions) || !!(parsedResponse == null ? void 0 : parsedResponse.sysExceptions),
394
+ hasMessages: !!(parsedResponse == null ? void 0 : parsedResponse.sysMessages)
395
+ });
396
+ }
397
+ } catch (e) {
398
+ handleWrongResponse(new Error(e));
399
+ return null;
400
+ }
401
+ return null;
402
+ });
403
+ }
404
+ function post(par1, par2) {
405
+ return __async$2(this, null, function* () {
406
+ const actualUrl = typeof par1 !== "string" ? makeApiaUrl() : par1;
407
+ const configParameter = typeof par1 === "string" ? par2 != null ? par2 : defaultConfig : par1;
408
+ const behaveConfig = __spreadProps$4(__spreadValues$8({}, getConfig(configParameter)), {
409
+ postData: configParameter.postDataTreatement === "stringify" ? QueryString.stringify(
410
+ configParameter.postData,
411
+ configParameter.stringifyOptions
412
+ ) : configParameter.postData
413
+ });
414
+ const parsedUrl = makeUrl(
415
+ actualUrl,
416
+ behaveConfig.queryData,
417
+ behaveConfig.stringifyOptions
418
+ );
419
+ if (behaveConfig.debug) {
420
+ const queryString = actualUrl.split("&");
421
+ const action = getURLActionName(actualUrl);
422
+ console.log(
423
+ `%cApiaApi.post ${action}`,
424
+ `color: ${getColor("message", behaveConfig.colors)}`,
425
+ {
426
+ url: parsedUrl,
427
+ queryDataInURL: [...queryString],
428
+ queryData: behaveConfig.queryData,
429
+ formData: behaveConfig.postData,
430
+ stringifyOptiopns: behaveConfig.stringifyOptions
431
+ }
432
+ );
433
+ }
434
+ const response = yield axios.post(
435
+ parsedUrl,
436
+ behaveConfig.postData,
437
+ behaveConfig.axiosConfig
438
+ ).catch((e) => {
439
+ handleWrongResponse(new Error(e));
440
+ });
441
+ if (response) {
442
+ const result = handleResponse(response, actualUrl, behaveConfig);
443
+ return result;
444
+ }
445
+ return null;
446
+ });
447
+ }
448
+ function get(par1, par2) {
449
+ return __async$2(this, null, function* () {
450
+ const actualUrl = typeof par1 !== "string" ? makeApiaUrl() : par1;
451
+ const behaveConfig = getConfig(
452
+ typeof par1 === "string" ? par2 != null ? par2 : defaultConfig : par1
453
+ );
454
+ const parsedUrl = makeUrl(
455
+ actualUrl,
456
+ behaveConfig.queryData,
457
+ behaveConfig.stringifyOptions
458
+ );
459
+ if (behaveConfig.debug)
460
+ console.log(
461
+ `%cApiaApi.get`,
462
+ `color: ${getColor("message", behaveConfig.colors)}`,
463
+ {
464
+ url: parsedUrl
465
+ }
466
+ );
467
+ const response = yield axios.get(parsedUrl, behaveConfig.axiosConfig).catch((e) => {
468
+ handleWrongResponse(new Error(e));
469
+ });
470
+ if (response) {
471
+ const result = yield handleResponse(
472
+ response,
473
+ actualUrl,
474
+ behaveConfig
475
+ );
476
+ return result;
477
+ }
478
+ return null;
479
+ });
480
+ }
481
+ const ApiaApi = {
482
+ get,
483
+ getConfig,
484
+ post
485
+ };
486
+ function makeApiaUrl(props) {
487
+ var _b, _c;
488
+ let actualQueryData = {};
489
+ if (props) {
490
+ const _a = props, rest = __objRest$1(_a, [
491
+ "ajaxUrl",
492
+ "queryString",
493
+ "stringifyOptions",
494
+ "shouldAvoidTabId",
495
+ "preventAsXmlParameter",
496
+ "avoidTabId"
497
+ ]);
498
+ actualQueryData = __spreadValues$8({}, rest);
499
+ }
500
+ const queryString = QueryString.stringify(
501
+ actualQueryData,
502
+ (_b = props == null ? void 0 : props.stringifyOptions) != null ? _b : {
503
+ arrayFormat: "repeat",
504
+ encodeValuesOnly: false
505
+ }
506
+ );
507
+ let actualAjaxUrl = (_c = props == null ? void 0 : props.ajaxUrl) != null ? _c : window.URL_REQUEST_AJAX;
508
+ if (actualAjaxUrl.indexOf("?") === actualAjaxUrl.length - 1)
509
+ actualAjaxUrl = actualAjaxUrl.slice(0, actualAjaxUrl.length - 1);
510
+ if (!actualAjaxUrl.startsWith("/"))
511
+ actualAjaxUrl = `/${actualAjaxUrl}`;
512
+ const match = window.TAB_ID_REQUEST.match(/tokenId=(\w+)/);
513
+ const currentTokenId = (match != null ? match : [])[1];
514
+ let tabId = ((props == null ? void 0 : props.tabId) ? `&tabId=${props.tabId}&tokenId=${currentTokenId}` : window.TAB_ID_REQUEST).slice(1);
515
+ if (props == null ? void 0 : props.avoidTabId)
516
+ tabId = "";
517
+ let { CONTEXT } = window;
518
+ if (CONTEXT == null ? void 0 : CONTEXT.endsWith("/"))
519
+ CONTEXT += CONTEXT.slice(0, CONTEXT.length - 1);
520
+ return `${CONTEXT}${actualAjaxUrl}?${!(props == null ? void 0 : props.preventAsXmlParameter) ? "asXml=true&" : ""}${(props == null ? void 0 : props.queryString) ? `${props.queryString}&` : ""}${queryString ? `${queryString}&` : ""}${tabId}`;
521
+ }
522
+
523
+ var __defProp$7 = Object.defineProperty;
524
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
525
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
526
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
527
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
528
+ var __spreadValues$7 = (a, b) => {
529
+ for (var prop in b || (b = {}))
530
+ if (__hasOwnProp$7.call(b, prop))
531
+ __defNormalProp$7(a, prop, b[prop]);
532
+ if (__getOwnPropSymbols$7)
533
+ for (var prop of __getOwnPropSymbols$7(b)) {
534
+ if (__propIsEnum$7.call(b, prop))
535
+ __defNormalProp$7(a, prop, b[prop]);
536
+ }
537
+ return a;
538
+ };
539
+ const ApiaApiCheckbox = (props) => {
540
+ const element = React__default.useMemo(() => props.element, [props.element]);
541
+ const className = React__default.useMemo(
542
+ () => element.class ? `handler__checkbox ${element.class}` : "handler__checkbox",
543
+ [element.class]
544
+ );
545
+ const validationRules = React__default.useMemo(
546
+ () => __spreadValues$7({
547
+ required: element.mandatory
548
+ }, classToValidate(element.class)),
549
+ [element.class, element.mandatory]
550
+ );
551
+ const submitValueParser = React__default.useCallback(
552
+ (value) => value === "on" || value === true,
553
+ []
554
+ );
555
+ return /* @__PURE__ */ jsx(
556
+ Checkbox,
557
+ {
558
+ className,
559
+ name: element.id || element.name,
560
+ label: element.text,
561
+ title: element.title || element.text,
562
+ initialValue: String(element.selected) === "true",
563
+ disabled: element.readonly || element.disabled,
564
+ validationRules,
565
+ onChange: element.onChange,
566
+ submitValueParser
567
+ }
568
+ );
569
+ };
570
+
571
+ var __defProp$6 = Object.defineProperty;
572
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
573
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
574
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
575
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
576
+ var __spreadValues$6 = (a, b) => {
577
+ for (var prop in b || (b = {}))
578
+ if (__hasOwnProp$6.call(b, prop))
579
+ __defNormalProp$6(a, prop, b[prop]);
580
+ if (__getOwnPropSymbols$6)
581
+ for (var prop of __getOwnPropSymbols$6(b)) {
582
+ if (__propIsEnum$6.call(b, prop))
583
+ __defNormalProp$6(a, prop, b[prop]);
584
+ }
585
+ return a;
586
+ };
587
+ const ApiaApiFileInput = (props) => {
588
+ const element = React__default.useMemo(() => props.element, [props.element]);
589
+ const className = React__default.useMemo(
590
+ () => element.class ? `handler__file ${element.class}` : "handler__file",
591
+ [element.class]
592
+ );
593
+ const validationRules = React__default.useMemo(
594
+ () => __spreadValues$6({
595
+ required: element.mandatory
596
+ }, classToValidate(element.class)),
597
+ [element.class, element.mandatory]
598
+ );
599
+ return /* @__PURE__ */ jsx(
600
+ FileInput,
601
+ {
602
+ className,
603
+ name: element.id || element.name,
604
+ label: element.text,
605
+ title: element.title || element.text,
606
+ readOnly: element.readonly,
607
+ disabled: element.disabled,
608
+ validationRules
609
+ }
610
+ );
611
+ };
612
+ ApiaApiFileInput.displayName = "ApiaApiFileInput";
613
+
614
+ var __defProp$5 = Object.defineProperty;
615
+ var __defProps$3 = Object.defineProperties;
616
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
617
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
618
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
619
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
620
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
621
+ var __spreadValues$5 = (a, b) => {
622
+ for (var prop in b || (b = {}))
623
+ if (__hasOwnProp$5.call(b, prop))
624
+ __defNormalProp$5(a, prop, b[prop]);
625
+ if (__getOwnPropSymbols$5)
626
+ for (var prop of __getOwnPropSymbols$5(b)) {
627
+ if (__propIsEnum$5.call(b, prop))
628
+ __defNormalProp$5(a, prop, b[prop]);
629
+ }
630
+ return a;
631
+ };
632
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
633
+ const ApiaApiInput = (props) => {
634
+ const element = React__default.useMemo(() => props.element, [props.element]);
635
+ const getModal = React__default.useCallback((path) => {
636
+ return React__default.lazy(() => {
637
+ return new Promise((resolve) => {
638
+ import(
639
+ /* webpackChunkName: "handlerModal" */
640
+ /* webpackInclude: /\.tsx?$/ */
641
+ `/api/modals/${path}`
642
+ ).then((result) => {
643
+ resolve(
644
+ result
645
+ );
646
+ }).catch((error) => {
647
+ resolve({
648
+ default: () => {
649
+ console.error(error);
650
+ throw new Error(
651
+ `The above error ocurred at component ApiaApiHandler/${path}, does it exist?`
652
+ );
653
+ }
654
+ });
655
+ });
656
+ });
657
+ });
658
+ }, []);
659
+ const [Submodal, setSubmodal] = React__default.useState(null);
660
+ useMount(() => {
661
+ if (element.modalFunction) {
662
+ const found = element.modalFunction.match(/(?:fnc)?(\w+)\(?\)?$/);
663
+ if (found) {
664
+ const modalName = found[found.length - 1];
665
+ setSubmodal(getModal(modalName));
666
+ }
667
+ }
668
+ });
669
+ const className = React__default.useMemo(
670
+ () => element.class ? `handler__${element.type} ${element.class}` : `handler__${element.type}`,
671
+ [element.class, element.type]
672
+ );
673
+ const validationRules = React__default.useMemo(
674
+ () => __spreadValues$5({
675
+ required: element.mandatory,
676
+ maxLength: element.maxlength ? Number(element.maxlength) : void 0,
677
+ pattern: element.regExp,
678
+ patternMessage: element.regExpMessage
679
+ }, classToValidate(element.class)),
680
+ [
681
+ element.class,
682
+ element.mandatory,
683
+ element.maxlength,
684
+ element.regExp,
685
+ element.regExpMessage
686
+ ]
687
+ );
688
+ const validationFunction = React__default.useMemo(
689
+ () => classToValidationFunction(element.class),
690
+ [element.class]
691
+ );
692
+ const submitValueParser = React__default.useCallback(
693
+ (value) => {
694
+ if (element.type === "password") {
695
+ return encrypt(
696
+ window.SALT,
697
+ window.IV,
698
+ window.PASSPHRASE,
699
+ value,
700
+ Number(window.KEY_SIZE),
701
+ Number(window.ITERATION_COUNT)
702
+ );
703
+ }
704
+ return value;
705
+ },
706
+ [element.type]
707
+ );
708
+ if (element.modalFunction) {
709
+ if (Submodal) {
710
+ return /* @__PURE__ */ jsx(React__default.Suspense, { children: /* @__PURE__ */ jsx(Submodal, __spreadProps$3(__spreadValues$5({}, props), { element })) });
711
+ }
712
+ return null;
713
+ }
714
+ return /* @__PURE__ */ jsx(
715
+ Input,
716
+ {
717
+ type: element.type,
718
+ className,
719
+ name: element.id || element.name,
720
+ label: element.text,
721
+ title: element.title || element.text,
722
+ value: element.value,
723
+ readOnly: element.readonly,
724
+ disabled: element.disabled,
725
+ validationFunction,
726
+ validationRules,
727
+ submitValueParser,
728
+ onChange: element.onChange,
729
+ autoComplete: element.type === "password" ? "new-password" : void 0
730
+ }
731
+ );
732
+ };
733
+ ApiaApiInput.displayName = "ApiaApiInput";
734
+
735
+ var __defProp$4 = Object.defineProperty;
736
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
737
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
738
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
739
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
740
+ var __spreadValues$4 = (a, b) => {
741
+ for (var prop in b || (b = {}))
742
+ if (__hasOwnProp$4.call(b, prop))
743
+ __defNormalProp$4(a, prop, b[prop]);
744
+ if (__getOwnPropSymbols$4)
745
+ for (var prop of __getOwnPropSymbols$4(b)) {
746
+ if (__propIsEnum$4.call(b, prop))
747
+ __defNormalProp$4(a, prop, b[prop]);
748
+ }
749
+ return a;
750
+ };
751
+ const ApiaApiRadio = (props) => {
752
+ var _a;
753
+ const element = React__default.useMemo(() => props.element, [props.element]);
754
+ const className = React__default.useMemo(
755
+ () => element.class ? `handler__radio ${element.class}` : "handler__radio",
756
+ [element.class]
757
+ );
758
+ const options = React__default.useMemo(
759
+ () => {
760
+ var _a2;
761
+ return arrayOrArray((_a2 = element.options) == null ? void 0 : _a2.option).map((currOption) => {
762
+ return { value: currOption.value, label: currOption.content };
763
+ });
764
+ },
765
+ [(_a = element.options) == null ? void 0 : _a.option]
766
+ );
767
+ const validationRules = React__default.useMemo(
768
+ () => __spreadValues$4({
769
+ required: element.mandatory
770
+ }, classToValidate(element.class)),
771
+ [element.class, element.mandatory]
772
+ );
773
+ return /* @__PURE__ */ jsx(
774
+ Radio,
775
+ {
776
+ className,
777
+ name: element.id || element.name,
778
+ label: element.text,
779
+ title: element.title || element.text,
780
+ value: element.value,
781
+ disabled: element.readonly || element.disabled,
782
+ validationRules,
783
+ options,
784
+ onChange: element.onChange
785
+ }
786
+ );
787
+ };
788
+ ApiaApiRadio.displayName = "ApiaApiRadio";
789
+
790
+ var __defProp$3 = Object.defineProperty;
791
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
792
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
793
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
794
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
795
+ var __spreadValues$3 = (a, b) => {
796
+ for (var prop in b || (b = {}))
797
+ if (__hasOwnProp$3.call(b, prop))
798
+ __defNormalProp$3(a, prop, b[prop]);
799
+ if (__getOwnPropSymbols$3)
800
+ for (var prop of __getOwnPropSymbols$3(b)) {
801
+ if (__propIsEnum$3.call(b, prop))
802
+ __defNormalProp$3(a, prop, b[prop]);
803
+ }
804
+ return a;
805
+ };
806
+ const ApiaApiSelect = (props) => {
807
+ var _a;
808
+ const element = React__default.useMemo(() => props.element, [props.element]);
809
+ const className = React__default.useMemo(
810
+ () => element.class ? `handler__select ${element.class}` : "handler__select",
811
+ [element.class]
812
+ );
813
+ const options = React__default.useMemo(
814
+ () => {
815
+ var _a2;
816
+ return arrayOrArray((_a2 = element.options) == null ? void 0 : _a2.option).map((currOption) => {
817
+ return { value: currOption.value, label: currOption.content };
818
+ });
819
+ },
820
+ [(_a = element.options) == null ? void 0 : _a.option]
821
+ );
822
+ const validationRules = React__default.useMemo(
823
+ () => __spreadValues$3({
824
+ required: element.mandatory
825
+ }, classToValidate(element.class)),
826
+ [element.class, element.mandatory]
827
+ );
828
+ const initialValue = useMemo(
829
+ () => {
830
+ var _a2, _b, _c, _d;
831
+ return (_d = (_c = (_a2 = options.find((current) => current.value === props.element.value)) == null ? void 0 : _a2.value) != null ? _c : (_b = options[0]) == null ? void 0 : _b.value) != null ? _d : "";
832
+ },
833
+ // eslint-disable-next-line react-hooks/exhaustive-deps
834
+ []
835
+ );
836
+ return /* @__PURE__ */ jsx(
837
+ Select,
838
+ {
839
+ className,
840
+ name: element.id || element.name,
841
+ label: element.text,
842
+ title: element.title || element.text,
843
+ value: element.value,
844
+ disabled: element.readonly || element.disabled,
845
+ validationRules,
846
+ options,
847
+ onChange: element.onChange,
848
+ initialValue
849
+ }
850
+ );
851
+ };
852
+ ApiaApiSelect.displayName = "ApiaApiSelect";
853
+
854
+ var __defProp$2 = Object.defineProperty;
855
+ var __defProps$2 = Object.defineProperties;
856
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
857
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
858
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
859
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
860
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
861
+ var __spreadValues$2 = (a, b) => {
862
+ for (var prop in b || (b = {}))
863
+ if (__hasOwnProp$2.call(b, prop))
864
+ __defNormalProp$2(a, prop, b[prop]);
865
+ if (__getOwnPropSymbols$2)
866
+ for (var prop of __getOwnPropSymbols$2(b)) {
867
+ if (__propIsEnum$2.call(b, prop))
868
+ __defNormalProp$2(a, prop, b[prop]);
869
+ }
870
+ return a;
871
+ };
872
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
873
+ const ApiaApiFieldsContainer = (props) => {
874
+ var _a, _b;
875
+ const elements = React__default.useMemo(
876
+ () => {
877
+ var _a2, _b2, _c;
878
+ return arrayOrArray((_c = (_b2 = (_a2 = props == null ? void 0 : props.definition) == null ? void 0 : _a2.form.elements) == null ? void 0 : _b2.element) != null ? _c : []);
879
+ },
880
+ [(_b = (_a = props == null ? void 0 : props.definition) == null ? void 0 : _a.form.elements) == null ? void 0 : _b.element]
881
+ );
882
+ const getSections = React__default.useCallback(() => {
883
+ var _a2;
884
+ const removeEndingSpacers = (sectionElements) => {
885
+ if (sectionElements.length > 1) {
886
+ for (let i = sectionElements.length - 1; i >= 0; i--) {
887
+ if (sectionElements[i].type === "empty") {
888
+ sectionElements.pop();
889
+ } else {
890
+ return sectionElements;
891
+ }
892
+ }
893
+ }
894
+ return sectionElements;
895
+ };
896
+ const sectionIndexes = [];
897
+ if (((_a2 = elements[0]) == null ? void 0 : _a2.type) !== "2columnTitle") {
898
+ sectionIndexes.push(-1);
899
+ }
900
+ elements.forEach((element, index) => {
901
+ if (element.type === "2columnTitle") {
902
+ sectionIndexes.push(index);
903
+ }
904
+ });
905
+ const sections2 = [];
906
+ sectionIndexes.forEach((sectionIndex, arrayIndex) => {
907
+ const start = sectionIndex + 1 < elements.length ? sectionIndex + 1 : elements.length - 1;
908
+ const end = arrayIndex + 1 < sectionIndexes.length ? sectionIndexes[arrayIndex + 1] : void 0;
909
+ sections2.push({
910
+ sectionHeader: sectionIndex !== -1 ? elements[sectionIndex] : void 0,
911
+ sectionElements: removeEndingSpacers(elements.slice(start, end))
912
+ });
913
+ });
914
+ return sections2;
915
+ }, [elements]);
916
+ const sections = getSections();
917
+ const renderSectionContent = React__default.useCallback(
918
+ (sectionElements) => {
919
+ const isVisible = sectionElements.findIndex((element) => element.type !== "hidden") !== -1;
920
+ return /* @__PURE__ */ jsx(
921
+ Box,
922
+ {
923
+ className: isVisible ? "handler__form__elements__section__content" : `handler__form__elements__section__content handler__hidden`,
924
+ children: sectionElements.map((current) => {
925
+ const element = __spreadProps$2(__spreadValues$2({}, current), {
926
+ onChange() {
927
+ getFunction(current.onChange, props).then((onChangeMethod) => {
928
+ if (onChangeMethod) {
929
+ onChangeMethod();
930
+ }
931
+ }).catch(console.error);
932
+ }
933
+ });
934
+ const elementKey = element.id || element.name || uniqueId();
935
+ switch (element.type) {
936
+ case "table": {
937
+ const data = JSON.parse(element.text);
938
+ return /* @__PURE__ */ jsx(
939
+ Box,
940
+ __spreadProps$2(__spreadValues$2({}, getVariant("layout.common.tables.information")), {
941
+ children: /* @__PURE__ */ jsxs("table", { sx: { width: "100%" }, children: [
942
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: data.columns.map((column) => {
943
+ return /* @__PURE__ */ jsx("th", { children: column }, column);
944
+ }) }) }),
945
+ /* @__PURE__ */ jsx("tbody", { children: data.rows.map((row) => {
946
+ return /* @__PURE__ */ jsx("tr", { children: row.cells.map((cell, i) => {
947
+ return /* @__PURE__ */ jsx("td", { children: cell }, `${cell}_${data.columns[i]}`);
948
+ }) }, row.cells.join("-"));
949
+ }) })
950
+ ] })
951
+ }),
952
+ elementKey
953
+ );
954
+ }
955
+ case "2columnSubTitle":
956
+ return /* @__PURE__ */ jsx(Box, { className: element.class, as: "h6", children: element.value || element.text }, elementKey);
957
+ case "2column":
958
+ return /* @__PURE__ */ jsx(
959
+ Box,
960
+ {
961
+ dangerouslySetInnerHTML: {
962
+ __html: element.value || element.text
963
+ },
964
+ className: element.class
965
+ },
966
+ elementKey
967
+ );
968
+ case "checkbox":
969
+ return /* @__PURE__ */ jsx(
970
+ ApiaApiCheckbox,
971
+ __spreadProps$2(__spreadValues$2({}, props), {
972
+ element
973
+ }),
974
+ elementKey
975
+ );
976
+ case "file":
977
+ return /* @__PURE__ */ jsx(
978
+ ApiaApiFileInput,
979
+ __spreadProps$2(__spreadValues$2({}, props), {
980
+ element
981
+ }),
982
+ elementKey
983
+ );
984
+ case "hidden":
985
+ case "password":
986
+ case "text":
987
+ return /* @__PURE__ */ jsx(ApiaApiInput, __spreadProps$2(__spreadValues$2({}, props), { element }), elementKey);
988
+ case "select":
989
+ return /* @__PURE__ */ jsx(
990
+ ApiaApiSelect,
991
+ __spreadProps$2(__spreadValues$2({}, props), {
992
+ element
993
+ }),
994
+ elementKey
995
+ );
996
+ case "radio":
997
+ return /* @__PURE__ */ jsx(ApiaApiRadio, __spreadProps$2(__spreadValues$2({}, props), { element }), elementKey);
998
+ case "empty":
999
+ return /* @__PURE__ */ jsx(Box, { className: "spacer" }, elementKey);
1000
+ default:
1001
+ console.warn(
1002
+ `Unhandled element type: ${element.type}`,
1003
+ element
1004
+ );
1005
+ return null;
1006
+ }
1007
+ })
1008
+ },
1009
+ uniqueId()
1010
+ );
1011
+ },
1012
+ [props]
1013
+ );
1014
+ return /* @__PURE__ */ jsx(Box, { className: "handler__form__elements", children: sections.map((section) => {
1015
+ if (section.sectionHeader) {
1016
+ return renderSectionContent(section.sectionElements);
1017
+ }
1018
+ return renderSectionContent(section.sectionElements);
1019
+ }) });
1020
+ };
1021
+ ApiaApiFieldsContainer.displayName = "ApiaApiFieldsContainer";
1022
+
1023
+ var __defProp$1 = Object.defineProperty;
1024
+ var __defProps$1 = Object.defineProperties;
1025
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
1026
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
1027
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
1028
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
1029
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1030
+ var __spreadValues$1 = (a, b) => {
1031
+ for (var prop in b || (b = {}))
1032
+ if (__hasOwnProp$1.call(b, prop))
1033
+ __defNormalProp$1(a, prop, b[prop]);
1034
+ if (__getOwnPropSymbols$1)
1035
+ for (var prop of __getOwnPropSymbols$1(b)) {
1036
+ if (__propIsEnum$1.call(b, prop))
1037
+ __defNormalProp$1(a, prop, b[prop]);
1038
+ }
1039
+ return a;
1040
+ };
1041
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1042
+ var __async$1 = (__this, __arguments, generator) => {
1043
+ return new Promise((resolve, reject) => {
1044
+ var fulfilled = (value) => {
1045
+ try {
1046
+ step(generator.next(value));
1047
+ } catch (e) {
1048
+ reject(e);
1049
+ }
1050
+ };
1051
+ var rejected = (value) => {
1052
+ try {
1053
+ step(generator.throw(value));
1054
+ } catch (e) {
1055
+ reject(e);
1056
+ }
1057
+ };
1058
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1059
+ step((generator = generator.apply(__this, __arguments)).next());
1060
+ });
1061
+ };
1062
+ var __forAwait = (obj, it, method) => {
1063
+ it = obj[Symbol.asyncIterator];
1064
+ method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((resolve, reject, done) => {
1065
+ arg = fn.call(obj, arg);
1066
+ done = arg.done;
1067
+ return Promise.resolve(arg.value).then((value) => resolve({ value, done }), reject);
1068
+ }));
1069
+ return it ? it.call(obj) : (obj = obj[Symbol.iterator](), it = {}, method("next"), method("return"), it);
1070
+ };
1071
+ const NonMemoizedApiaApiButtonsContainer = (props) => {
1072
+ var _a, _b, _c, _d, _e;
1073
+ const buttons = arrayOrArray((_c = (_b = (_a = props.definition) == null ? void 0 : _a.form.buttons) == null ? void 0 : _b.button) != null ? _c : []);
1074
+ const modalConfiguration = (_d = props.configuration) == null ? void 0 : _d.modalConfiguration;
1075
+ const methodsPath = (_e = props.configuration) == null ? void 0 : _e.methodsPath;
1076
+ const { name: apiaApiForm } = useFormContext();
1077
+ const renderButton = React__default.useCallback(
1078
+ (button) => {
1079
+ const key = uniqueId();
1080
+ const buttonType = ["submitAjax", "submit"].includes(button.type) && !button.onclick ? "submit" : "button";
1081
+ const className = `handler__${buttonType}`;
1082
+ const onClick = () => {
1083
+ void function submitForm() {
1084
+ return __async$1(this, null, function* () {
1085
+ const validationResult = yield validationsStore.validateForm(
1086
+ apiaApiForm
1087
+ );
1088
+ if (!hasSucceedFormValidation(validationResult)) {
1089
+ return;
1090
+ }
1091
+ const { submitValues } = validationResult;
1092
+ if ((props == null ? void 0 : props.definition) && ["submitAjax", "submit"].includes(button.type)) {
1093
+ const formData = new FormData();
1094
+ Object.entries(submitValues).forEach(([name, value]) => {
1095
+ formData.append(name, value != null ? value : "");
1096
+ });
1097
+ const hasContext = props == null ? void 0 : props.definition.form.action.match(
1098
+ new RegExp(`^${window.CONTEXT}/`)
1099
+ );
1100
+ const url = `${hasContext ? "" : window.CONTEXT}${!(props == null ? void 0 : props.definition.form.action.startsWith("/")) ? "/" : ""}${props == null ? void 0 : props.definition.form.action}`;
1101
+ props.setState((current) => __spreadProps$1(__spreadValues$1({}, current), {
1102
+ isLoading: true
1103
+ }));
1104
+ void ApiaApi.post(url, {
1105
+ postData: props.state.isMultipart ? formData : QueryString.stringify(
1106
+ [...formData.entries(), ["isAjax", true]].reduce((accumulated, [name, value]) => {
1107
+ const retValue = __spreadValues$1({}, accumulated);
1108
+ retValue[name.toString()] = value.toString();
1109
+ return retValue;
1110
+ }, {})
1111
+ ),
1112
+ handleLoad: true,
1113
+ notificationsCategory: "apiaApiHandler",
1114
+ modalConfiguration,
1115
+ methodsPath
1116
+ }).finally(() => {
1117
+ void (() => __async$1(this, null, function* () {
1118
+ var _a2, _b2, _c2, _d2;
1119
+ if (button.onclick) {
1120
+ const actions = button.onclick.split(";");
1121
+ try {
1122
+ for (var iter = __forAwait(actions), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
1123
+ const action = temp.value;
1124
+ const method = yield getFunction(action, __spreadValues$1({}, props));
1125
+ if (method)
1126
+ method({
1127
+ currentUrl: (_b2 = (_a2 = props.definition) == null ? void 0 : _a2.form.action) != null ? _b2 : "noUrl"
1128
+ });
1129
+ else {
1130
+ throw new Error(
1131
+ `The requested action is not defined: "${(_d2 = (_c2 = props.definition) == null ? void 0 : _c2.form.action) != null ? _d2 : ""}"`
1132
+ );
1133
+ }
1134
+ }
1135
+ } catch (temp) {
1136
+ error = [temp];
1137
+ } finally {
1138
+ try {
1139
+ more && (temp = iter.return) && (yield temp.call(iter));
1140
+ } finally {
1141
+ if (error)
1142
+ throw error[0];
1143
+ }
1144
+ }
1145
+ }
1146
+ }))();
1147
+ });
1148
+ }
1149
+ });
1150
+ }();
1151
+ };
1152
+ return /* @__PURE__ */ jsx(
1153
+ SimpleButton,
1154
+ {
1155
+ className,
1156
+ disabled: props.state.disabled,
1157
+ id: button.id || button.text,
1158
+ isLoading: props.state.isLoading,
1159
+ title: button.text,
1160
+ type: buttonType,
1161
+ onClick,
1162
+ children: button.text
1163
+ },
1164
+ key
1165
+ );
1166
+ },
1167
+ [apiaApiForm, methodsPath, modalConfiguration, props]
1168
+ );
1169
+ return /* @__PURE__ */ jsx(Box, { className: "handler__form__buttons", children: buttons.map((currentButton) => renderButton(currentButton)) });
1170
+ };
1171
+ const ApiaApiButtonsContainer = React__default.memo(
1172
+ NonMemoizedApiaApiButtonsContainer
1173
+ );
1174
+
1175
+ var __defProp = Object.defineProperty;
1176
+ var __defProps = Object.defineProperties;
1177
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1178
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1179
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1180
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
1181
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1182
+ var __spreadValues = (a, b) => {
1183
+ for (var prop in b || (b = {}))
1184
+ if (__hasOwnProp.call(b, prop))
1185
+ __defNormalProp(a, prop, b[prop]);
1186
+ if (__getOwnPropSymbols)
1187
+ for (var prop of __getOwnPropSymbols(b)) {
1188
+ if (__propIsEnum.call(b, prop))
1189
+ __defNormalProp(a, prop, b[prop]);
1190
+ }
1191
+ return a;
1192
+ };
1193
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1194
+ var __objRest = (source, exclude) => {
1195
+ var target = {};
1196
+ for (var prop in source)
1197
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
1198
+ target[prop] = source[prop];
1199
+ if (source != null && __getOwnPropSymbols)
1200
+ for (var prop of __getOwnPropSymbols(source)) {
1201
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
1202
+ target[prop] = source[prop];
1203
+ }
1204
+ return target;
1205
+ };
1206
+ var __async = (__this, __arguments, generator) => {
1207
+ return new Promise((resolve, reject) => {
1208
+ var fulfilled = (value) => {
1209
+ try {
1210
+ step(generator.next(value));
1211
+ } catch (e) {
1212
+ reject(e);
1213
+ }
1214
+ };
1215
+ var rejected = (value) => {
1216
+ try {
1217
+ step(generator.throw(value));
1218
+ } catch (e) {
1219
+ reject(e);
1220
+ }
1221
+ };
1222
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1223
+ step((generator = generator.apply(__this, __arguments)).next());
1224
+ });
1225
+ };
1226
+ const ApiaApiMessenger = new class extends EventEmitter {
1227
+ }();
1228
+ const FunctionsDispatcher = new class extends EventEmitter {
1229
+ }();
1230
+ const apiaApiForm = "ApiaApiForm";
1231
+ const methods = {};
1232
+ function getFunction(name, handler) {
1233
+ return __async(this, null, function* () {
1234
+ return new Promise((resolve) => {
1235
+ var _a, _b, _c;
1236
+ try {
1237
+ const separateNameFromParametersRegex = /^\/?([\w\d_-]+)\/?(?:\(([^)]*)\))?$/;
1238
+ const match = name.match(separateNameFromParametersRegex);
1239
+ if (match) {
1240
+ const functionName = match[1];
1241
+ const parameters = match[2];
1242
+ const path = [
1243
+ ...(_c = (_b = (_a = handler.configuration) == null ? void 0 : _a.methodsPath) == null ? void 0 : _b.split("/").filter((current) => {
1244
+ return !!current;
1245
+ })) != null ? _c : [],
1246
+ functionName
1247
+ ].join("/");
1248
+ const storeMethodAndResolve = (result) => {
1249
+ if (typeof result.default !== "function")
1250
+ notFound();
1251
+ const method = result.default;
1252
+ methods[functionName] = (props) => {
1253
+ var _a2;
1254
+ return method(handler, __spreadProps(__spreadValues({}, props), {
1255
+ inlineArguments: (_a2 = parameters == null ? void 0 : parameters.split(",").map((argument) => {
1256
+ if (argument.startsWith("'") || argument.startsWith('"'))
1257
+ return argument.slice(1, argument.length - 1);
1258
+ return argument;
1259
+ })) != null ? _a2 : []
1260
+ }));
1261
+ };
1262
+ resolve(methods[functionName]);
1263
+ };
1264
+ const notFound = () => {
1265
+ throw new Error(
1266
+ `${functionName}.ts not found at ${path}.ts nor ./${functionName}.ts`
1267
+ );
1268
+ };
1269
+ import(
1270
+ /* webpackChunkName: "api-methods-[request]" */
1271
+ `/api/methods/${path}.ts`
1272
+ ).then(storeMethodAndResolve).catch(() => {
1273
+ var _a2;
1274
+ if (((_a2 = handler.configuration) == null ? void 0 : _a2.methodsPath) !== void 0)
1275
+ import(
1276
+ /* webpackChunkName: "api-methods-[request]" */
1277
+ `/api/methods/${functionName}.ts`
1278
+ ).then(storeMethodAndResolve).catch(notFound);
1279
+ else
1280
+ notFound();
1281
+ });
1282
+ }
1283
+ } catch (e) {
1284
+ console.error(e);
1285
+ handler.reset();
1286
+ handler.setError({
1287
+ type: "danger",
1288
+ message: "Error while loading current method."
1289
+ });
1290
+ }
1291
+ });
1292
+ });
1293
+ }
1294
+ function isForm(responseObject) {
1295
+ return typeof responseObject.canClose === "boolean" && typeof responseObject.type === "string" && !!responseObject.form;
1296
+ }
1297
+ function isFunction(responseObject) {
1298
+ return typeof responseObject.canClose === "boolean" && typeof responseObject.type === "string" && !!responseObject.function;
1299
+ }
1300
+ function isMessage(responseObject) {
1301
+ if (typeof responseObject.canClose === "boolean" && typeof responseObject.type === "string" && typeof responseObject.text === "object" && responseObject.text && typeof responseObject.text.label === "string") {
1302
+ return true;
1303
+ }
1304
+ return false;
1305
+ }
1306
+ const modalConfigurationHandler = new WithEventsValue();
1307
+ function useModalConfiguration() {
1308
+ const [, setValue, value] = useStateRef(
1309
+ void 0
1310
+ );
1311
+ const handleChange = React.useCallback(
1312
+ (newEventsHandler) => {
1313
+ setValue(newEventsHandler);
1314
+ },
1315
+ [setValue]
1316
+ );
1317
+ useMount(() => {
1318
+ modalConfigurationHandler.on("update", handleChange);
1319
+ });
1320
+ useUnmount(() => {
1321
+ return modalConfigurationHandler.off("update", handleChange);
1322
+ });
1323
+ return value;
1324
+ }
1325
+ const currentFormDispatcher = new class currentFormDispatcher2 extends EventEmitter {
1326
+ emit(eventName, params) {
1327
+ super.emit(eventName, params);
1328
+ }
1329
+ }();
1330
+ function handle(responseObject, currentUrl, configuration) {
1331
+ modalConfigurationHandler.value = configuration;
1332
+ if (isForm(responseObject)) {
1333
+ currentFormDispatcher.emit("form", responseObject);
1334
+ return true;
1335
+ }
1336
+ if (isFunction(responseObject)) {
1337
+ FunctionsDispatcher.emit("method", {
1338
+ name: responseObject.function.name,
1339
+ props: {
1340
+ messages: responseObject.function.messages,
1341
+ attributes: responseObject.function,
1342
+ currentUrl
1343
+ }
1344
+ });
1345
+ return true;
1346
+ }
1347
+ if (isMessage(responseObject)) {
1348
+ ApiaApiMessenger.emit("message", {
1349
+ predicate: responseObject.text.content,
1350
+ title: responseObject.text.title
1351
+ });
1352
+ return true;
1353
+ }
1354
+ return false;
1355
+ }
1356
+ const initialState = {
1357
+ disabled: false,
1358
+ isLoading: false,
1359
+ isMultipart: false,
1360
+ progress: 0,
1361
+ errors: {}
1362
+ };
1363
+ const ApiaApiHandlerNonMemoized = () => {
1364
+ var _b, _c, _d;
1365
+ const configuration = useModalConfiguration();
1366
+ const [state, setState] = React.useState(__spreadProps(__spreadValues({}, initialState), {
1367
+ windowIndex: -1
1368
+ }));
1369
+ const [currentForm2, setCurrentForm] = React.useState(
1370
+ void 0
1371
+ );
1372
+ React.useEffect(() => {
1373
+ return currentFormDispatcher.on("form", setCurrentForm);
1374
+ }, []);
1375
+ const setValue = React.useCallback((name, value) => {
1376
+ return validationsStore.setFieldValue(apiaApiForm, name, value);
1377
+ }, []);
1378
+ React.useEffect(() => {
1379
+ var _a2, _b2, _c2;
1380
+ if (!currentForm2)
1381
+ return;
1382
+ const elements = arrayOrArray((_c2 = (_b2 = (_a2 = currentForm2 == null ? void 0 : currentForm2.form) == null ? void 0 : _a2.elements) == null ? void 0 : _b2.element) != null ? _c2 : []);
1383
+ let isMultipart = false;
1384
+ const elementsValues = Object.values(elements);
1385
+ let i = 0;
1386
+ while (i < elementsValues.length && !isMultipart) {
1387
+ if (elementsValues[i++].type === "file") {
1388
+ isMultipart = true;
1389
+ }
1390
+ }
1391
+ setState((currentState) => {
1392
+ return __spreadProps(__spreadValues(__spreadValues({}, currentState), initialState), {
1393
+ isMultipart
1394
+ });
1395
+ });
1396
+ }, [currentForm2]);
1397
+ const _a = useModal(), { show, onClose } = _a, modalProps = __objRest(_a, ["show", "onClose"]);
1398
+ const close = React.useCallback(() => {
1399
+ var _a2, _b2;
1400
+ onClose();
1401
+ currentFormDispatcher.emit("form", void 0);
1402
+ setState((currentState) => {
1403
+ return __spreadValues(__spreadValues({}, currentState), initialState);
1404
+ });
1405
+ if ((_b2 = (_a2 = configuration.current) == null ? void 0 : _a2.modalConfiguration) == null ? void 0 : _b2.onClose)
1406
+ configuration.current.modalConfiguration.onClose();
1407
+ validationsStore.unregisterForm(apiaApiForm);
1408
+ }, [onClose, configuration]);
1409
+ const modalRef = React.useRef(null);
1410
+ React.useEffect(() => {
1411
+ var _a2;
1412
+ const elements = (_a2 = modalRef.current) == null ? void 0 : _a2.querySelectorAll(
1413
+ "a,input,textarea,button"
1414
+ );
1415
+ if ((elements == null ? void 0 : elements.length) === 1)
1416
+ void focus.on([...elements][0]);
1417
+ });
1418
+ const setError = React.useCallback(
1419
+ (notification) => {
1420
+ notify(__spreadValues({}, notification));
1421
+ },
1422
+ []
1423
+ );
1424
+ const getHandler = React.useCallback(() => {
1425
+ const newHandler = {
1426
+ alert,
1427
+ close,
1428
+ configuration: configuration.current,
1429
+ formDefinition: currentForm2,
1430
+ reset: () => {
1431
+ return setState((currentState) => {
1432
+ return __spreadValues(__spreadValues({}, currentState), initialState);
1433
+ });
1434
+ },
1435
+ setError,
1436
+ setMessage: (message) => {
1437
+ var _a2, _b2;
1438
+ if ((_b2 = (_a2 = configuration.current) == null ? void 0 : _a2.modalConfiguration) == null ? void 0 : _b2.onMessage)
1439
+ configuration.current.modalConfiguration.onMessage(message);
1440
+ },
1441
+ setState,
1442
+ state,
1443
+ setValue
1444
+ };
1445
+ return newHandler;
1446
+ }, [close, configuration, currentForm2, setError, state, setValue]);
1447
+ React.useEffect(() => {
1448
+ const handleFunction = (_0) => __async(void 0, [_0], function* ({
1449
+ name,
1450
+ props: { messages, attributes, currentUrl }
1451
+ }) {
1452
+ const method = yield getFunction(`${name}`, getHandler());
1453
+ if (method) {
1454
+ method({ messages, attributes, currentUrl });
1455
+ }
1456
+ });
1457
+ const handleMessage = (ev) => {
1458
+ var _a2, _b2, _c2, _d2;
1459
+ const handler2 = getHandler();
1460
+ notify({
1461
+ message: ev.predicate,
1462
+ type: "warning",
1463
+ onClose: (_b2 = (_a2 = handler2.configuration) == null ? void 0 : _a2.modalConfiguration) == null ? void 0 : _b2.onMessageClose
1464
+ });
1465
+ const onMessage = (_d2 = (_c2 = handler2.configuration) == null ? void 0 : _c2.modalConfiguration) == null ? void 0 : _d2.onMessage;
1466
+ if (onMessage)
1467
+ onMessage(ev);
1468
+ };
1469
+ const handleAction = (action) => __async(void 0, null, function* () {
1470
+ if (action.toDo === "ajaxHiddeAll") {
1471
+ close();
1472
+ }
1473
+ if (action.toDo === "functionTimedCall") {
1474
+ const method = yield getFunction(
1475
+ arrayOrArray(action.param)[1],
1476
+ getHandler()
1477
+ );
1478
+ if (method)
1479
+ setTimeout(() => {
1480
+ var _a2;
1481
+ return method({
1482
+ currentUrl: (_a2 = currentForm2 == null ? void 0 : currentForm2.form.action) != null ? _a2 : "noUrl"
1483
+ });
1484
+ }, Number(action.param[0]));
1485
+ }
1486
+ });
1487
+ ApiaApiMessenger.on("message", handleMessage);
1488
+ FunctionsDispatcher.on("method", handleFunction);
1489
+ ApiaActions.on("action", handleAction);
1490
+ return () => {
1491
+ ApiaApiMessenger.off("message", handleMessage);
1492
+ FunctionsDispatcher.off("method", handleFunction);
1493
+ ApiaActions.off("action", handleAction);
1494
+ };
1495
+ }, [state.windowIndex, onClose, close]);
1496
+ React.useEffect(() => {
1497
+ if (currentForm2) {
1498
+ show();
1499
+ }
1500
+ }, [currentForm2]);
1501
+ const handler = getHandler();
1502
+ const formRef = React.useCallback(
1503
+ (el) => __async(void 0, null, function* () {
1504
+ if (el && (currentForm2 == null ? void 0 : currentForm2.form.onLoad)) {
1505
+ const method = yield getFunction(
1506
+ `${currentForm2 == null ? void 0 : currentForm2.form.onLoad}`,
1507
+ getHandler()
1508
+ );
1509
+ if (method) {
1510
+ method();
1511
+ }
1512
+ }
1513
+ }),
1514
+ [currentForm2 == null ? void 0 : currentForm2.form.onLoad, getHandler]
1515
+ );
1516
+ return /* @__PURE__ */ jsx(ApiaApiContext$1, { id: apiaApiForm, children: /* @__PURE__ */ jsx(
1517
+ Modal,
1518
+ __spreadProps(__spreadValues({
1519
+ ref: modalRef,
1520
+ onClose: close,
1521
+ id: apiaApiForm,
1522
+ title: (_d = (_c = (_b = configuration.current) == null ? void 0 : _b.modalConfiguration) == null ? void 0 : _c.modalTitle) != null ? _d : currentForm2 == null ? void 0 : currentForm2.form.title,
1523
+ size: "md-fixed",
1524
+ shouldCloseOnEsc: !state.disabled,
1525
+ shouldCloseOnOverlayClick: !state.disabled,
1526
+ initialFocusGetter: React.useCallback((ref) => {
1527
+ return ref == null ? void 0 : ref.querySelector(focusSelector);
1528
+ }, [])
1529
+ }, modalProps), {
1530
+ children: currentForm2 && /* @__PURE__ */ jsx(Box, __spreadProps(__spreadValues({}, getVariant("layout.common.modals.apiaApi")), { children: /* @__PURE__ */ jsxs(
1531
+ Form,
1532
+ {
1533
+ name: apiaApiForm,
1534
+ avoidFieldsOverride: true,
1535
+ className: "handler__form",
1536
+ children: [
1537
+ /* @__PURE__ */ jsx(ApiaApiFieldsContainer, __spreadValues({ definition: currentForm2 }, handler)),
1538
+ state.isMultipart && state.progress > 0 && /* @__PURE__ */ jsx(Box, { className: "progressBox", children: /* @__PURE__ */ jsx(
1539
+ ProgressBar,
1540
+ {
1541
+ id: "ApiaApiHandler progress",
1542
+ progress: state.progress,
1543
+ loading: true
1544
+ }
1545
+ ) }),
1546
+ /* @__PURE__ */ jsx(Box, { ref: formRef }),
1547
+ /* @__PURE__ */ jsx(ApiaApiButtonsContainer, __spreadValues({ definition: currentForm2 }, handler))
1548
+ ]
1549
+ }
1550
+ ) }))
1551
+ })
1552
+ ) });
1553
+ };
1554
+ const ApiaApiHandler = React.memo(ApiaApiHandlerNonMemoized);
1555
+
1556
+ export { ApiaApi, ApiaApiHandler, makeApiaUrl };
1557
+ //# sourceMappingURL=index.js.map