@apia/api 5.0.0 → 5.0.3

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.
Files changed (124) hide show
  1. package/dist/ApiaApiContext.js +15 -0
  2. package/dist/ApiaApiContext.js.map +1 -0
  3. package/dist/ApiaApiHandler.d.ts +67 -0
  4. package/dist/ApiaApiHandler.d.ts.map +1 -0
  5. package/dist/ApiaApiHandler.js +390 -0
  6. package/dist/ApiaApiHandler.js.map +1 -0
  7. package/dist/apiaApi.d.ts +174 -0
  8. package/dist/apiaApi.d.ts.map +1 -0
  9. package/dist/apiaApi.js +478 -0
  10. package/dist/apiaApi.js.map +1 -0
  11. package/dist/buttons/ApiaApiButtonsContainer.js +129 -0
  12. package/dist/buttons/ApiaApiButtonsContainer.js.map +1 -0
  13. package/dist/fields/ApiaApiCheckbox.js +39 -0
  14. package/dist/fields/ApiaApiCheckbox.js.map +1 -0
  15. package/dist/fields/ApiaApiEnvironmentsModalField.js +172 -0
  16. package/dist/fields/ApiaApiEnvironmentsModalField.js.map +1 -0
  17. package/dist/fields/ApiaApiFieldsContainer.d.ts +9 -0
  18. package/dist/fields/ApiaApiFieldsContainer.d.ts.map +1 -0
  19. package/dist/fields/ApiaApiFieldsContainer.js +288 -0
  20. package/dist/fields/ApiaApiFieldsContainer.js.map +1 -0
  21. package/dist/fields/ApiaApiFileInput.js +34 -0
  22. package/dist/fields/ApiaApiFileInput.js.map +1 -0
  23. package/dist/fields/ApiaApiInput.d.ts +20 -0
  24. package/dist/fields/ApiaApiInput.d.ts.map +1 -0
  25. package/dist/fields/ApiaApiInput.js +111 -0
  26. package/dist/fields/ApiaApiInput.js.map +1 -0
  27. package/dist/fields/ApiaApiPoolsModalField.js +172 -0
  28. package/dist/fields/ApiaApiPoolsModalField.js.map +1 -0
  29. package/dist/fields/ApiaApiProcessesModalField.js +172 -0
  30. package/dist/fields/ApiaApiProcessesModalField.js.map +1 -0
  31. package/dist/fields/ApiaApiRadio.js +43 -0
  32. package/dist/fields/ApiaApiRadio.js.map +1 -0
  33. package/dist/fields/ApiaApiSelect.js +64 -0
  34. package/dist/fields/ApiaApiSelect.js.map +1 -0
  35. package/dist/fields/ApiaApiTasksModalField.js +172 -0
  36. package/dist/fields/ApiaApiTasksModalField.js.map +1 -0
  37. package/dist/fields/ApiaApiTextArea.js +50 -0
  38. package/dist/fields/ApiaApiTextArea.js.map +1 -0
  39. package/dist/fields/ApiaApiUsersModalField.js +170 -0
  40. package/dist/fields/ApiaApiUsersModalField.js.map +1 -0
  41. package/dist/index.d.ts +13 -575
  42. package/dist/index.js +11 -5208
  43. package/dist/index.js.map +1 -1
  44. package/dist/modals/apia/components/ApiaEnvironmentsModal.js +162 -0
  45. package/dist/modals/apia/components/ApiaEnvironmentsModal.js.map +1 -0
  46. package/dist/modals/apia/components/ApiaPoolsModal.js +165 -0
  47. package/dist/modals/apia/components/ApiaPoolsModal.js.map +1 -0
  48. package/dist/modals/apia/components/ApiaProcessesModal.js +164 -0
  49. package/dist/modals/apia/components/ApiaProcessesModal.js.map +1 -0
  50. package/dist/modals/apia/components/ApiaTasksModal.js +161 -0
  51. package/dist/modals/apia/components/ApiaTasksModal.js.map +1 -0
  52. package/dist/modals/apia/components/ApiaUsersModal.js +158 -0
  53. package/dist/modals/apia/components/ApiaUsersModal.js.map +1 -0
  54. package/dist/modals/apia/components/generics/ApiaFormsModal2.d.ts +8 -0
  55. package/dist/modals/apia/components/generics/ApiaFormsModal2.d.ts.map +1 -0
  56. package/dist/modals/apia/components/generics/ApiaFormsModal2.js +57 -0
  57. package/dist/modals/apia/components/generics/ApiaFormsModal2.js.map +1 -0
  58. package/dist/modals/apia/components/generics/ApiaMonDocModal2.d.ts +27 -0
  59. package/dist/modals/apia/components/generics/ApiaMonDocModal2.d.ts.map +1 -0
  60. package/dist/modals/apia/components/generics/ApiaMonDocModal2.js +390 -0
  61. package/dist/modals/apia/components/generics/ApiaMonDocModal2.js.map +1 -0
  62. package/dist/modals/apia/components/generics/ApiaPoolsModal2.d.ts +11 -0
  63. package/dist/modals/apia/components/generics/ApiaPoolsModal2.d.ts.map +1 -0
  64. package/dist/modals/apia/components/generics/ApiaPoolsModal2.js +49 -0
  65. package/dist/modals/apia/components/generics/ApiaPoolsModal2.js.map +1 -0
  66. package/dist/modals/apia/components/generics/ApiaUsersModal2.d.ts +6 -0
  67. package/dist/modals/apia/components/generics/ApiaUsersModal2.d.ts.map +1 -0
  68. package/dist/modals/apia/components/generics/ApiaUsersModal2.js +42 -0
  69. package/dist/modals/apia/components/generics/ApiaUsersModal2.js.map +1 -0
  70. package/dist/modals/apia/components/generics/GenericListQuery.d.ts +20 -0
  71. package/dist/modals/apia/components/generics/GenericListQuery.d.ts.map +1 -0
  72. package/dist/modals/apia/components/generics/GenericListQuery.js +71 -0
  73. package/dist/modals/apia/components/generics/GenericListQuery.js.map +1 -0
  74. package/dist/modals/apia/components/generics/LangsModal2.d.ts +8 -0
  75. package/dist/modals/apia/components/generics/LangsModal2.d.ts.map +1 -0
  76. package/dist/modals/apia/components/generics/LangsModal2.js +57 -0
  77. package/dist/modals/apia/components/generics/LangsModal2.js.map +1 -0
  78. package/dist/modals/apia/components/util/FiltersModal.js +46 -0
  79. package/dist/modals/apia/components/util/FiltersModal.js.map +1 -0
  80. package/dist/modals/apia/hooks/defaultFetcher.js +143 -0
  81. package/dist/modals/apia/hooks/defaultFetcher.js.map +1 -0
  82. package/dist/queries/FilterTypesComponent.js +37 -0
  83. package/dist/queries/FilterTypesComponent.js.map +1 -0
  84. package/dist/queries/QueryController.d.ts +88 -0
  85. package/dist/queries/QueryController.d.ts.map +1 -0
  86. package/dist/queries/QueryController.js +422 -0
  87. package/dist/queries/QueryController.js.map +1 -0
  88. package/dist/queries/QueryModalController.d.ts +29 -0
  89. package/dist/queries/QueryModalController.d.ts.map +1 -0
  90. package/dist/queries/QueryModalController.js +169 -0
  91. package/dist/queries/QueryModalController.js.map +1 -0
  92. package/dist/queries/filters/Filter.d.ts +20 -0
  93. package/dist/queries/filters/Filter.d.ts.map +1 -0
  94. package/dist/queries/filters/Filter.js +98 -0
  95. package/dist/queries/filters/Filter.js.map +1 -0
  96. package/dist/queries/filters/FilterLabel.js +43 -0
  97. package/dist/queries/filters/FilterLabel.js.map +1 -0
  98. package/dist/queries/filters/renderers/DateFilterRenderer.js +124 -0
  99. package/dist/queries/filters/renderers/DateFilterRenderer.js.map +1 -0
  100. package/dist/queries/filters/renderers/FreeLabelFilterRenderer.js +115 -0
  101. package/dist/queries/filters/renderers/FreeLabelFilterRenderer.js.map +1 -0
  102. package/dist/queries/filters/renderers/InputFilterRenderer.js +40 -0
  103. package/dist/queries/filters/renderers/InputFilterRenderer.js.map +1 -0
  104. package/dist/queries/filters/renderers/RangeFilterRenderer.js +112 -0
  105. package/dist/queries/filters/renderers/RangeFilterRenderer.js.map +1 -0
  106. package/dist/queries/filters/renderers/SelectFilterRenderer.js +32 -0
  107. package/dist/queries/filters/renderers/SelectFilterRenderer.js.map +1 -0
  108. package/dist/queries/filters/types.d.ts +34 -0
  109. package/dist/queries/filters/types.d.ts.map +1 -0
  110. package/dist/queries/table/AdditionalFilters/AdditionalFiltersModal.js +74 -0
  111. package/dist/queries/table/AdditionalFilters/AdditionalFiltersModal.js.map +1 -0
  112. package/dist/queries/table/AdditionalFilters/components/AdditionalFiltersComponent.js +134 -0
  113. package/dist/queries/table/AdditionalFilters/components/AdditionalFiltersComponent.js.map +1 -0
  114. package/dist/queries/table/TableController.d.ts +37 -0
  115. package/dist/queries/table/TableController.d.ts.map +1 -0
  116. package/dist/queries/table/TableController.js +209 -0
  117. package/dist/queries/table/TableController.js.map +1 -0
  118. package/dist/queries/table/types.d.ts +31 -0
  119. package/dist/queries/table/types.d.ts.map +1 -0
  120. package/dist/queries/types.d.ts +23 -0
  121. package/dist/queries/types.d.ts.map +1 -0
  122. package/dist/types.d.ts +76 -0
  123. package/dist/types.d.ts.map +1 -0
  124. package/package.json +11 -11
@@ -0,0 +1,174 @@
1
+ import { IApiaApiRequestConfig, TApiaApiResult, TApiaMessage } from './types.js';
2
+ import { AxiosResponse } from 'axios';
3
+ import QueryString from 'qs';
4
+ import { TModify } from '@apia/util';
5
+
6
+ declare function getConfig<LoadType>(outerBehaveConfig?: IApiaApiRequestConfig<LoadType>): IApiaApiRequestConfig<unknown> & IApiaApiRequestConfig<LoadType> & Partial<IApiaApiRequestConfig<unknown>>;
7
+ declare function isXmlResponse(response: AxiosResponse<unknown>): RegExpMatchArray | null;
8
+ declare function isHtmlResponse(response: AxiosResponse<unknown>): RegExpMatchArray | null;
9
+ declare const parseSuccessfulResponse: <LoadType extends Record<string, unknown>>(response: AxiosResponse<string>, currentUrl: string, outerBehaveConfig?: IApiaApiRequestConfig<LoadType>) => Promise<(LoadType & {
10
+ sysMessages: {
11
+ message: TApiaMessage | TApiaMessage[];
12
+ } | undefined;
13
+ exceptions: {
14
+ exception: TApiaMessage | TApiaMessage[];
15
+ } | undefined;
16
+ sysExceptions: {
17
+ exception: TApiaMessage | TApiaMessage[];
18
+ } | undefined;
19
+ }) | null>;
20
+ type TApiaApiAxiosResponse<LoadType> = AxiosResponse<LoadType | null> & {
21
+ hasError: boolean;
22
+ hasMessages: boolean;
23
+ };
24
+ /**
25
+ * IMPORTANT!! The ApiaApi is programmed under the slogan that
26
+ * **should never throw an exception**. **Errors** coming from
27
+ * connectivity or exceptions on the server **will be handled
28
+ * automatically** by ApiaApi, using the notification system
29
+ * of the application. It is possible to determine in what context they should
30
+ * be thrown those exceptions (global, main, modal) using the
31
+ * alertsCategory configuration properties **(see errorsHandling.md)**.
32
+ *
33
+ * @param url String, the url you want to call
34
+ * @param config interface IApiaApiRequestConfig<DataType>;
35
+ *
36
+ * @throws Nothing
37
+ *
38
+ * @example
39
+ *
40
+ * ApiaApi.post<ResponseType>('url...', {
41
+ axiosConfig?: AxiosRequestConfig;
42
+
43
+ // Configuración de postData
44
+ postData? unknown;
45
+ postDataTreatement?: 'stringify' | undefined;
46
+
47
+ // Configuración de queryString
48
+ queryData?: string | Record<string, unknown>;
49
+ stringifyOptions?: QueryString.IStringifyOptions;
50
+
51
+ // Response validator,
52
+ // If it returns true, everything continues correctly
53
+ // If it returns false, the ApiaApi throws a standard error.
54
+ // If it returns string, ApiaApi throws the error returned in the string.
55
+ validateResponse?: (
56
+ response: AxiosResponse<DataType | null>,
57
+ ) => boolean | string;
58
+
59
+ // Configuración de alertas
60
+ alertsImportance?: TAlertImportance;
61
+
62
+ // Configuración de ApiaApiHandler, falta documentar
63
+ handleLoad?: boolean;
64
+ eventsHandler?: IEventsHandler;
65
+
66
+ // other configuration
67
+ colors?: TColors;
68
+ debug?: boolean;
69
+ }
70
+ * @returns The type of the return value depends on the type passed when calling the function. If there was an error it returns null.
71
+ */
72
+ declare function post<LoadType extends Record<string, unknown> = Record<string, unknown>, DataType = unknown>(url: string | TModify<IApiaApiRequestConfig<LoadType>, {
73
+ postData?: DataType;
74
+ postDataTreatement?: 'stringify';
75
+ }>, config?: TModify<IApiaApiRequestConfig<LoadType>, {
76
+ postData?: DataType;
77
+ postDataTreatement?: 'stringify';
78
+ }>): TApiaApiResult<LoadType>;
79
+ declare function post<LoadType extends Record<string, unknown> = Record<string, unknown>, DataType = unknown>(config: TModify<IApiaApiRequestConfig<LoadType>, {
80
+ postData?: DataType;
81
+ postDataTreatement?: 'stringify';
82
+ }>): TApiaApiResult<LoadType>;
83
+ /**
84
+ * IMPORTANTE!! El ApiaApi está programado bajo la consigna de que
85
+ * **no debe tirar núnca una excepción**. **Los errores** provenientes
86
+ * de la conectividad o de excepciones en el servidor **serán manejados
87
+ * automáticamente** por el ApiaApi utilizando el sistema de notificaciones
88
+ * de la aplicación. Es posible determinar en qué contexto deben
89
+ * ser lanzadas esas excepciones (global, main, modal) utilizando las
90
+ * propiedades de configuración alertsCategory **(ver errorsHandling.md)**.
91
+ *
92
+ * @param url String, el url al que se desea llamar
93
+ * @param config interface IApiaApiRequestConfig<DataType>;
94
+ *
95
+ * @throws Nothing
96
+ *
97
+ * @example
98
+ *
99
+ * ApiaApi.get<TipoDeRespuesta>('url...', {
100
+ axiosConfig?: AxiosRequestConfig;
101
+
102
+ // Configuración de queryString
103
+ queryData?: string | Record<string, unknown>;
104
+ stringifyOptions?: QueryString.IStringifyOptions;
105
+
106
+ // Validador de respuesta,
107
+ // Si devuelve true, todo sigue correctamente
108
+ // Si devuelve false, el ApiaApi tira un error estándar.
109
+ // Si devuelve string, el ApiaApi tira el error devuelto en el string.
110
+ validateResponse?: (
111
+ response: AxiosResponse<DataType | null>,
112
+ ) => boolean | string;
113
+
114
+ // Configuración de alertas
115
+ alertsImportance?: TAlertImportance;
116
+
117
+ // Configuración de ApiaApiHandler, falta documentar
118
+ handleLoad?: boolean;
119
+ eventsHandler?: IEventsHandler;
120
+
121
+ // Otra configuración
122
+ colors?: TColors;
123
+ debug?: boolean;
124
+ }
125
+ * @returns El tipo del valor devuelto depende del tipo pasado al llamar a la función. Si hubo un error devuelve null
126
+ */
127
+ declare function get<LoadType extends Record<string, unknown> = Record<string, unknown>>(url: string | IApiaApiRequestConfig<LoadType>, config?: IApiaApiRequestConfig<LoadType>): TApiaApiResult<LoadType>;
128
+ declare function get<LoadType extends Record<string, unknown> = Record<string, unknown>>(config: IApiaApiRequestConfig<LoadType>): TApiaApiResult<LoadType>;
129
+ declare const ApiaApi: {
130
+ get: typeof get;
131
+ getConfig: typeof getConfig;
132
+ post: typeof post;
133
+ };
134
+ /**
135
+ * Creates an url based on the general requirements of Apia.
136
+ * If the ajaxUrl property is not passed, it will use the
137
+ * window.URL_REQUEST_AJAX. Its use is very simple, just pass the objects you
138
+ * want to appear in the query string.
139
+ *
140
+ * @example makeApiaUrl({
141
+ * ajaxUrl: 'the.endpoint.you.want',
142
+ * queryString: 'an=existent&query=string',
143
+ * action: 'theAction',
144
+ * anotherProp: 15
145
+ * })
146
+ *
147
+ * @returns the well formed url, in the example, the response url is:
148
+ * /context/the.endpoint.you.want?an=existent&query=string&anotherProp=15&tabId=...&tokenId=...&action=theAction
149
+ */
150
+ declare function makeApiaUrl(props?: {
151
+ action?: string;
152
+ ajaxUrl?: string;
153
+ queryString?: string;
154
+ stringifyOptions?: QueryString.IStringifyOptions;
155
+ tabId?: string | number;
156
+ preventAsXmlParameter?: boolean;
157
+ avoidTabId?: boolean;
158
+ [key: string]: unknown;
159
+ }): string;
160
+ declare global {
161
+ interface Window {
162
+ TAB_ID_REQUEST: string;
163
+ CONTEXT: string;
164
+ URL_REQUEST_AJAX: string;
165
+ FILTERS_LABEL: string;
166
+ BTN_DELETE_FILTERS: string;
167
+ FINDER_ORDER_BY: string;
168
+ FINDER_FILTERS: string;
169
+ ADDITIONAL_FILTERS_LABEL: string;
170
+ }
171
+ }
172
+
173
+ export { type TApiaApiAxiosResponse, ApiaApi as default, isHtmlResponse, isXmlResponse, makeApiaUrl, parseSuccessfulResponse };
174
+ //# sourceMappingURL=apiaApi.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiaApi.d.ts","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,478 @@
1
+ import axios, { AxiosError } from 'axios';
2
+ import merge from 'lodash-es/merge';
3
+ import QueryString from 'qs';
4
+ import { session } from '@apia/session';
5
+ import { debugDispatcher, parseXmlAsync, arrayOrArray, EventEmitter } from '@apia/util';
6
+ import { notify, getNotificationMessageObj, dispatchNotifications } from '@apia/notifications';
7
+ import { handle } from './ApiaApiHandler.js';
8
+
9
+ debugDispatcher.on(
10
+ "parseXml",
11
+ async ([text]) => {
12
+ const result = await parseXmlAsync(text);
13
+ console.info(result);
14
+ },
15
+ "Acepta un par\xE1metro de tipo string y realiza un parseo como si fuera xml, convirti\xE9ndolo a objeto javascript."
16
+ );
17
+ const defaultConfig = {
18
+ debug: false,
19
+ colors: {
20
+ exception: "red",
21
+ alert: "yellow",
22
+ message: "lightgreen"
23
+ },
24
+ handleLoad: false
25
+ };
26
+ const STORED_CONFIG = "ApiaApiConfig";
27
+ let forcedConfig = {};
28
+ const storedConfig = localStorage.getItem(STORED_CONFIG);
29
+ if (storedConfig)
30
+ forcedConfig = JSON.parse(storedConfig);
31
+ function getConfig(outerBehaveConfig) {
32
+ return merge({}, defaultConfig, outerBehaveConfig, forcedConfig);
33
+ }
34
+ function makeUrl(url, queryData, stringifyOptions) {
35
+ let finalUrl = url;
36
+ const questionMarkIndex = finalUrl.indexOf("?");
37
+ if (questionMarkIndex === -1)
38
+ finalUrl += "?";
39
+ else if (questionMarkIndex !== finalUrl.length - 1 && !finalUrl.endsWith("&"))
40
+ finalUrl += "&";
41
+ let parsedUrl = `${finalUrl}${queryData ? QueryString.stringify(queryData, stringifyOptions) : ""}`;
42
+ if (parsedUrl.endsWith("&") || parsedUrl.endsWith("?")) {
43
+ parsedUrl = parsedUrl.slice(0, parsedUrl.length - 1);
44
+ }
45
+ return parsedUrl;
46
+ }
47
+ const getURLActionName = (url) => {
48
+ const actionIdx = url.match(/action=(\w+)/)?.[1];
49
+ return actionIdx ?? "noAction";
50
+ };
51
+ class ApiaActionsClass extends EventEmitter {
52
+ }
53
+ const ApiaActions = new ApiaActionsClass();
54
+ function getColor(color, colors = defaultConfig.colors ?? {
55
+ exception: "red",
56
+ alert: "yellow",
57
+ message: "green"
58
+ }) {
59
+ return colors[color];
60
+ }
61
+ const handleWrongResponse = (error) => {
62
+ if (error instanceof AxiosError && (error.status === 403 || error.response?.status === 403)) {
63
+ session.invalidate();
64
+ return;
65
+ }
66
+ let errorMessage;
67
+ if (typeof error !== "string") {
68
+ if (error.message)
69
+ errorMessage = error.message;
70
+ else
71
+ errorMessage = error.toString();
72
+ } else
73
+ errorMessage = error;
74
+ notify({
75
+ type: "danger",
76
+ message: error.message.replaceAll("AxiosError", "Error")
77
+ });
78
+ console.log("%c ", "font-size:10vh");
79
+ console.log("%cError in ApiaApi", "color:red;font-size:2em;font-weight:bold");
80
+ console.log(`red/${errorMessage}`, { error });
81
+ console.log("%c ", "font-size:10vh");
82
+ };
83
+ function isJsonResponse(response) {
84
+ return response.headers["content-type"].match("application/json");
85
+ }
86
+ function isXmlResponse(response) {
87
+ return response.headers["content-type"].match(
88
+ /(?:application|text)?\/xml/
89
+ );
90
+ }
91
+ function isHtmlResponse(response) {
92
+ return response.headers["content-type"].match(
93
+ /(?:application|text)?\/html/
94
+ );
95
+ }
96
+ function handleActions(actions) {
97
+ if (actions) {
98
+ if (getConfig().debug)
99
+ console.log(
100
+ "%cHandled actions: ",
101
+ `color: ${getConfig().colors?.message ?? "green"}`,
102
+ { actions }
103
+ );
104
+ const actionsArray = arrayOrArray(actions.action);
105
+ actionsArray.forEach((action) => {
106
+ ApiaActions.emit("action", {
107
+ ...action,
108
+ param: arrayOrArray(action.param)
109
+ });
110
+ });
111
+ }
112
+ }
113
+ function handleOnClose({
114
+ exceptions,
115
+ onClose,
116
+ sysExceptions,
117
+ sysMessages
118
+ }) {
119
+ try {
120
+ import(
121
+ /* @vite-ignore */
122
+ /* webpackChunkName: "api-[request]" */
123
+ `/api/onClose/${onClose}.ts`
124
+ ).then(
125
+ (func) => {
126
+ if (exceptions || sysExceptions || sysMessages) {
127
+ const notificationsObject = getNotificationMessageObj({
128
+ exceptions,
129
+ onClose,
130
+ sysExceptions,
131
+ sysMessages
132
+ });
133
+ if (notificationsObject)
134
+ notificationsObject.forEach((notification) => {
135
+ notify({
136
+ ...notification,
137
+ onClose: func.default
138
+ });
139
+ });
140
+ else
141
+ func.default();
142
+ } else
143
+ func.default();
144
+ },
145
+ (e) => {
146
+ notify({
147
+ message: `onClose action not found: ${String(e)}`,
148
+ type: "danger"
149
+ });
150
+ }
151
+ );
152
+ } catch (e) {
153
+ parseMessages({ exceptions, sysExceptions, sysMessages });
154
+ console.error("Error while handling onClose");
155
+ console.error(e);
156
+ }
157
+ }
158
+ function parseMessages2(messages) {
159
+ for (const m of messages) {
160
+ notify({ message: m.text, title: m.title, trace: m.stack, type: m.type });
161
+ }
162
+ }
163
+ function parseMessages(response) {
164
+ if (!response)
165
+ return;
166
+ const { exceptions, sysMessages, sysExceptions } = response;
167
+ if (exceptions || sysExceptions || sysMessages) {
168
+ try {
169
+ dispatchNotifications({
170
+ exceptions,
171
+ sysExceptions,
172
+ sysMessages
173
+ });
174
+ } catch (e) {
175
+ handleWrongResponse(new Error(e));
176
+ }
177
+ }
178
+ }
179
+ const parseSuccessfulResponse = async (response, currentUrl, outerBehaveConfig = defaultConfig) => {
180
+ const behaveConfig = getConfig(outerBehaveConfig);
181
+ let parsedObj = void 0;
182
+ if (isJsonResponse(response)) {
183
+ if (typeof response.data === "string")
184
+ parsedObj = JSON.parse(
185
+ response.data.trim()
186
+ );
187
+ else if (typeof response.data === "object" && response.data)
188
+ parsedObj = response.data;
189
+ } else if (isXmlResponse(response)) {
190
+ parsedObj = await parseXmlAsync(response.data).catch(
191
+ (e) => {
192
+ handleWrongResponse(new Error(e));
193
+ }
194
+ );
195
+ } else if (isHtmlResponse(response)) {
196
+ console.error(
197
+ "El contenido devuelto es Html, no se esperaba esa respuesta"
198
+ );
199
+ return null;
200
+ }
201
+ if (behaveConfig.validateResponse) {
202
+ const validateResult = await behaveConfig.validateResponse({
203
+ ...response,
204
+ data: parsedObj?.load ?? parsedObj
205
+ });
206
+ if (typeof validateResult === "string")
207
+ throw new Error(`Validation error: ${validateResult}`);
208
+ else if (!validateResult) {
209
+ throw new Error("Error");
210
+ }
211
+ }
212
+ if (parsedObj) {
213
+ const {
214
+ actions,
215
+ onClose,
216
+ exceptions,
217
+ sysExceptions,
218
+ sysMessages,
219
+ messages,
220
+ load,
221
+ ...rest
222
+ } = parsedObj;
223
+ if (rest.code === "-1" && exceptions) {
224
+ session.invalidate();
225
+ return null;
226
+ }
227
+ if (messages) {
228
+ parseMessages2(arrayOrArray(messages?.message));
229
+ }
230
+ if (exceptions && behaveConfig.debug) {
231
+ console.log(
232
+ `%cparseSuccessfulResponse`,
233
+ `color: ${getColor("exception", behaveConfig.colors)}`,
234
+ {
235
+ exceptions
236
+ }
237
+ );
238
+ }
239
+ if (sysExceptions && behaveConfig.debug) {
240
+ console.log(
241
+ `%cparseSuccessfulResponse`,
242
+ `color: ${getColor("exception", behaveConfig.colors)}`,
243
+ {
244
+ sysExceptions
245
+ }
246
+ );
247
+ }
248
+ if (sysMessages && behaveConfig.debug) {
249
+ console.log(
250
+ `%cparseSuccessfulResponse`,
251
+ `color: ${getColor("alert", behaveConfig.colors)}`,
252
+ {
253
+ sysMessages
254
+ }
255
+ );
256
+ }
257
+ handleActions(actions);
258
+ if (behaveConfig.handleLoad && onClose)
259
+ handleOnClose({
260
+ exceptions,
261
+ onClose,
262
+ sysExceptions,
263
+ sysMessages
264
+ });
265
+ else
266
+ parseMessages({ exceptions, sysExceptions, sysMessages });
267
+ if (load) {
268
+ if (behaveConfig.handleLoad) {
269
+ console.log(
270
+ `%chandleLoad`,
271
+ `color: ${getColor("message", behaveConfig.colors)}`,
272
+ {
273
+ load
274
+ }
275
+ );
276
+ if (!handle(load, currentUrl, {
277
+ methodsPath: outerBehaveConfig.methodsPath,
278
+ modalConfiguration: {
279
+ ...behaveConfig.modalConfiguration,
280
+ onClose: () => {
281
+ if (onClose)
282
+ handleOnClose({
283
+ exceptions,
284
+ onClose,
285
+ sysExceptions,
286
+ sysMessages
287
+ });
288
+ if (behaveConfig.modalConfiguration?.onClose)
289
+ behaveConfig.modalConfiguration?.onClose();
290
+ }
291
+ }
292
+ })) {
293
+ console.log(
294
+ `%cunhandledLoad -> There is no handler defined`,
295
+ `color: ${getColor("exception", behaveConfig.colors)}`,
296
+ {
297
+ load
298
+ }
299
+ );
300
+ }
301
+ }
302
+ return { ...load, sysMessages, exceptions, sysExceptions };
303
+ }
304
+ return { ...rest, sysMessages, exceptions, sysExceptions };
305
+ }
306
+ return null;
307
+ };
308
+ async function handleResponse(result, currentUrl, outerBehaveConfig = defaultConfig) {
309
+ const behaveConfig = getConfig(outerBehaveConfig);
310
+ try {
311
+ if (!result || result.data === void 0) {
312
+ if (behaveConfig.debug)
313
+ console.log(
314
+ `%cApiaApi wrong response`,
315
+ `color: ${getColor("alert", behaveConfig.colors)}`
316
+ );
317
+ } else {
318
+ const parsedResponse = await parseSuccessfulResponse(
319
+ result,
320
+ currentUrl,
321
+ behaveConfig
322
+ );
323
+ const action = getURLActionName(currentUrl);
324
+ if (behaveConfig.debug)
325
+ console.log(
326
+ `%c <- ApiaApi.${result.config.method ?? ""} ${action} `,
327
+ `color: ${getColor("message", behaveConfig.colors)}`,
328
+ {
329
+ data: parsedResponse
330
+ }
331
+ );
332
+ return {
333
+ ...result,
334
+ data: parsedResponse,
335
+ hasError: !!parsedResponse?.exceptions || !!parsedResponse?.sysExceptions,
336
+ hasMessages: !!parsedResponse?.sysMessages
337
+ };
338
+ }
339
+ } catch (e) {
340
+ handleWrongResponse(new Error(e));
341
+ return null;
342
+ }
343
+ return null;
344
+ }
345
+ async function post(par1, par2) {
346
+ const actualUrl = typeof par1 !== "string" ? makeApiaUrl() : par1;
347
+ const configParameter = typeof par1 === "string" ? par2 ?? defaultConfig : par1;
348
+ const behaveConfig = {
349
+ ...getConfig(configParameter),
350
+ postData: configParameter.postDataTreatement === "stringify" ? QueryString.stringify(
351
+ configParameter.postData,
352
+ configParameter.stringifyOptions
353
+ ) : configParameter.postData
354
+ };
355
+ const parsedUrl = makeUrl(
356
+ actualUrl,
357
+ behaveConfig.queryData,
358
+ behaveConfig.stringifyOptions
359
+ );
360
+ if (behaveConfig.debug) {
361
+ const queryString = actualUrl.split("&");
362
+ const action = getURLActionName(actualUrl);
363
+ console.log(
364
+ `%cApiaApi.post ${action}`,
365
+ `color: ${getColor("message", behaveConfig.colors)}`,
366
+ {
367
+ url: parsedUrl,
368
+ queryDataInURL: [...queryString],
369
+ queryData: behaveConfig.queryData,
370
+ formData: behaveConfig.postData,
371
+ stringifyOptiopns: behaveConfig.stringifyOptions
372
+ }
373
+ );
374
+ }
375
+ const response = await axios.post(parsedUrl, behaveConfig.postData, behaveConfig.axiosConfig).catch((e) => {
376
+ handleWrongResponse(e instanceof AxiosError ? e : new Error(e));
377
+ });
378
+ if (response) {
379
+ const result = handleResponse(response, actualUrl, behaveConfig);
380
+ return result;
381
+ }
382
+ return null;
383
+ }
384
+ async function get(par1, par2) {
385
+ const actualUrl = typeof par1 !== "string" ? makeApiaUrl() : par1;
386
+ const behaveConfig = getConfig(
387
+ typeof par1 === "string" ? par2 ?? defaultConfig : par1
388
+ );
389
+ const parsedUrl = makeUrl(
390
+ actualUrl,
391
+ behaveConfig.queryData,
392
+ behaveConfig.stringifyOptions
393
+ );
394
+ if (behaveConfig.debug)
395
+ console.log(
396
+ `%cApiaApi.get`,
397
+ `color: ${getColor("message", behaveConfig.colors)}`,
398
+ {
399
+ url: parsedUrl
400
+ }
401
+ );
402
+ const response = await axios.get(parsedUrl, behaveConfig.axiosConfig).catch((e) => {
403
+ handleWrongResponse(e instanceof AxiosError ? e : new Error(e));
404
+ });
405
+ if (response) {
406
+ const result = await handleResponse(
407
+ response,
408
+ actualUrl,
409
+ behaveConfig
410
+ );
411
+ return result;
412
+ }
413
+ return null;
414
+ }
415
+ const ApiaApi = {
416
+ get,
417
+ getConfig,
418
+ post
419
+ };
420
+ function makeApiaUrl(props) {
421
+ let actualQueryData = {};
422
+ if (props) {
423
+ const {
424
+ ajaxUrl,
425
+ queryString: queryString2,
426
+ stringifyOptions,
427
+ shouldAvoidTabId,
428
+ preventAsXmlParameter,
429
+ avoidTabId,
430
+ tabId: outerTabId,
431
+ ...rest
432
+ } = props;
433
+ actualQueryData = { ...rest };
434
+ }
435
+ const queryString = QueryString.stringify(
436
+ actualQueryData,
437
+ props?.stringifyOptions ?? {
438
+ arrayFormat: "repeat",
439
+ encodeValuesOnly: false
440
+ }
441
+ );
442
+ let actualAjaxUrl = props?.ajaxUrl ?? window.URL_REQUEST_AJAX;
443
+ if (actualAjaxUrl.indexOf("?") === actualAjaxUrl.length - 1) {
444
+ actualAjaxUrl = actualAjaxUrl.slice(0, actualAjaxUrl.length - 1);
445
+ }
446
+ if (!actualAjaxUrl.startsWith("/")) {
447
+ actualAjaxUrl = `/${actualAjaxUrl}`;
448
+ }
449
+ const match = window.TAB_ID_REQUEST.match(/tokenId=(\w+)/);
450
+ const currentTokenId = (match ?? [])[1];
451
+ let tabId = (props?.tabId ? `&tabId=${props.tabId}&tokenId=${currentTokenId}` : window.TAB_ID_REQUEST).slice(1);
452
+ if (props?.avoidTabId) {
453
+ tabId = "";
454
+ }
455
+ let { CONTEXT } = window;
456
+ if (CONTEXT?.endsWith("/")) {
457
+ CONTEXT += CONTEXT.slice(0, CONTEXT.length - 1);
458
+ }
459
+ let timestamp = `timestamp=${Date.now()}&`;
460
+ if (props?.queryString && props.queryString.includes("timestamp=") || queryString?.includes("timestamp=")) {
461
+ timestamp = "";
462
+ }
463
+ const contextWord = CONTEXT.replace(/^\/?(.+?)\/?$/, "$1");
464
+ actualAjaxUrl = actualAjaxUrl.match(
465
+ new RegExp(`^(?:(?:/?${contextWord})?/)?(.+)$`)
466
+ )?.[1];
467
+ let returnUrl = `${contextWord ? "/" : ""}${contextWord}/${actualAjaxUrl}?${timestamp}${!props?.preventAsXmlParameter ? "asXml=true&" : ""}${props?.queryString ? `${props.queryString}&` : ""}${queryString ? `${queryString}&` : ""}${tabId}`;
468
+ if (returnUrl.endsWith("&")) {
469
+ returnUrl = returnUrl.substring(0, returnUrl.length - 1);
470
+ }
471
+ return returnUrl;
472
+ }
473
+ function getModal(name) {
474
+ return window[name];
475
+ }
476
+
477
+ export { ApiaActions, ApiaApi as default, getModal, isHtmlResponse, isJsonResponse, isXmlResponse, makeApiaUrl, parseMessages, parseMessages2, parseSuccessfulResponse };
478
+ //# sourceMappingURL=apiaApi.js.map