@apia/api 0.1.0 → 0.1.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.
package/dist/index.js CHANGED
@@ -1,1557 +1 @@
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
1
+ import{jsx as p,jsxs as de}from"react/jsx-runtime";import*as O from"react";import y,{createContext as Ge,useMemo as et}from"react";import{Box as S}from"theme-ui";import{debugDispatcher as tt,EventEmitter as Q,parseXmlAsync as pe,arrayOrArray as N,useMount as me,encrypt as nt,WithEventsValue as ot,focus as rt,focusSelector as at,useStateRef as lt,useUnmount as st}from"@apia/util";import{notify as V,getNotificationMessageObj as it,dispatchNotifications as ct}from"@apia/notifications";import{classToValidate as H,Checkbox as ut,FileInput as dt,classToValidationFunction as pt,Input as mt,Radio as ft,Select as yt,useFormContext as vt,validationsStore as te,hasSucceedFormValidation as gt,Form as ht}from"@apia/validations";import{SimpleButton as bt,useModal as xt,Modal as $t,ProgressBar as wt}from"@apia/components";import{getVariant as fe}from"@apia/theme";import ye from"axios";import{merge as Ot,uniqueId as ne}from"lodash";import Z from"qs";import{session as At}from"@apia/session";const Ct=Ge("apiaApi"),Et=({children:t,id:e})=>p(Ct.Provider,{value:e,children:t});var jt=O.memo(Et),_t=Object.defineProperty,Pt=Object.defineProperties,St=Object.getOwnPropertyDescriptors,K=Object.getOwnPropertySymbols,ve=Object.prototype.hasOwnProperty,ge=Object.prototype.propertyIsEnumerable,he=(t,e,n)=>e in t?_t(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,M=(t,e)=>{for(var n in e||(e={}))ve.call(e,n)&&he(t,n,e[n]);if(K)for(var n of K(e))ge.call(e,n)&&he(t,n,e[n]);return t},T=(t,e)=>Pt(t,St(e)),be=(t,e)=>{var n={};for(var o in t)ve.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&K)for(var o of K(t))e.indexOf(o)<0&&ge.call(t,o)&&(n[o]=t[o]);return n},W=(t,e,n)=>new Promise((o,s)=>{var c=a=>{try{l(n.next(a))}catch(i){s(i)}},r=a=>{try{l(n.throw(a))}catch(i){s(i)}},l=a=>a.done?o(a.value):Promise.resolve(a.value).then(c,r);l((n=n.apply(t,e)).next())});tt.on("parseXml",t=>W(void 0,[t],function*([e]){const n=yield pe(e);console.info(n)}),"Acepta un par\xE1metro de tipo string y realiza un parseo como si fuera xml, convirti\xE9ndolo a objeto javascript.");const U={debug:!0,colors:{exception:"red",alert:"yellow",message:"lightgreen"},handleLoad:!1},Mt="ApiaApiConfig";let xe={};const $e=localStorage.getItem(Mt);$e&&(xe=JSON.parse($e));function D(t){return Ot({},U,t,xe)}function we(t,e,n){let o=t;const s=o.indexOf("?");s===-1?o+="?":s!==o.length-1&&!o.endsWith("&")&&(o+="&");let c=`${o}${e?Z.stringify(e,n):""}`;return(c.endsWith("&")||c.endsWith("?"))&&(c=c.slice(0,c.length-1)),c}const Oe=t=>{var e;const n=(e=t.match(/action=(\w+)/))==null?void 0:e[1];return n??"noAction"},oe=new class extends Q{};function I(t,e=(n=>(n=U.colors)!=null?n:{exception:"red",alert:"yellow",message:"green"})()){return e[t]}const X=t=>{let e;typeof t!="string"?t.message?e=t.message:e=t.toString():e=t,V({type:"danger",message:t.message.replaceAll("AxiosError","Error")}),console.log("%c ","font-size:10vh"),console.log("%cError in ApiaApi","color:red;font-size:2em;font-weight:bold"),console.log(`red/${e}`,{error:t}),console.log("%c ","font-size:10vh")};function It(t){return t.headers["content-type"].match("application/json")}function Nt(t){return t.headers["content-type"].match(/(?:application|text)?\/xml/)}function Tt(t){return t.headers["content-type"].match(/(?:application|text)?\/html/)}function kt(t){var e,n;t&&(D().debug&&console.log("%cHandled actions: ",`color: ${(n=(e=D().colors)==null?void 0:e.message)!=null?n:"green"}`,{actions:t}),N(t.action).forEach(o=>{oe.emit("action",T(M({},o),{param:N(o.param)}))}))}function Ae({exceptions:t,onClose:e,sysExceptions:n,sysMessages:o}){try{import(`/api/onClose/${e}.ts`).then(s=>{if(t||n||o){const c=it({exceptions:t,onClose:e,sysExceptions:n,sysMessages:o});c?c.forEach(r=>{V(T(M({},r),{onClose:s.default}))}):s.default()}else s.default()},s=>{V({message:`onClose action not found: ${String(s)}`,type:"danger"})})}catch(s){Ce({exceptions:t,sysExceptions:n,sysMessages:o}),console.error("Error while handling onClose"),console.error(s)}}function Ce(t){if(!t)return;const{exceptions:e,sysMessages:n,sysExceptions:o}=t;if(e||o||n)try{ct({exceptions:e,sysExceptions:o,sysMessages:n})}catch(s){X(new Error(s))}}const Rt=(t,e,...n)=>W(void 0,[t,e,...n],function*(o,s,c=U){var r;const l=D(c);let a;if(It(o))typeof o.data=="string"?a=JSON.parse(o.data.trim()):typeof o.data=="object"&&o.data&&(a=o.data);else if(Nt(o))a=yield pe(o.data).catch(i=>{X(new Error(i))});else if(Tt(o))return console.error("El contenido devuelto es Html, no se esperaba esa respuesta"),null;if(l.validateResponse){const i=yield l.validateResponse(T(M({},o),{data:(r=a?.load)!=null?r:a}));if(typeof i=="string")throw new Error(`Validation error: ${i}`);if(!i)throw new Error("Error")}if(a){const i=a,{actions:d,onClose:u,exceptions:v,sysExceptions:m,sysMessages:x,load:j}=i,A=be(i,["actions","onClose","exceptions","sysExceptions","sysMessages","load"]);return A.code==="-1"&&v?(At.invalidate(),null):(v&&l.debug&&console.log("%cparseSuccessfulResponse",`color: ${I("exception",l.colors)}`,{exceptions:v}),m&&l.debug&&console.log("%cparseSuccessfulResponse",`color: ${I("exception",l.colors)}`,{sysExceptions:m}),x&&l.debug&&console.log("%cparseSuccessfulResponse",`color: ${I("alert",l.colors)}`,{sysMessages:x}),kt(d),l.handleLoad&&u?Ae({exceptions:v,onClose:u,sysExceptions:m,sysMessages:x}):Ce({exceptions:v,sysExceptions:m,sysMessages:x}),j?(l.handleLoad&&(console.log("%chandleLoad",`color: ${I("message",l.colors)}`,{load:j}),Mn(j,s,{methodsPath:c.methodsPath,modalConfiguration:T(M({},l.modalConfiguration),{onClose:()=>{var C,k;u&&Ae({exceptions:v,onClose:u,sysExceptions:m,sysMessages:x}),(C=l.modalConfiguration)!=null&&C.onClose&&((k=l.modalConfiguration)==null||k.onClose())}})})||console.log("%cunhandledLoad -> There is no handler defined",`color: ${I("exception",l.colors)}`,{load:j})),T(M({},j),{sysMessages:x,exceptions:v,sysExceptions:m})):T(M({},A),{sysMessages:x,exceptions:v,sysExceptions:m}))}return null});function Ee(t,e){return W(this,arguments,function*(n,o,s=U){var c;const r=D(s);try{if(!n||n.data===void 0)r.debug&&console.log("%cApiaApi wrong response",`color: ${I("alert",r.colors)}`);else{const l=yield Rt(n,o,r),a=Oe(o);return r.debug&&console.log(`%c <- ApiaApi.${(c=n.config.method)!=null?c:""} ${a} `,`color: ${I("message",r.colors)}`,{data:l}),T(M({},n),{data:l,hasError:!!(l!=null&&l.exceptions)||!!(l!=null&&l.sysExceptions),hasMessages:!!(l!=null&&l.sysMessages)})}}catch(l){return X(new Error(l)),null}return null})}function Dt(t,e){return W(this,null,function*(){const n=typeof t!="string"?re():t,o=typeof t=="string"?e??U:t,s=T(M({},D(o)),{postData:o.postDataTreatement==="stringify"?Z.stringify(o.postData,o.stringifyOptions):o.postData}),c=we(n,s.queryData,s.stringifyOptions);if(s.debug){const l=n.split("&"),a=Oe(n);console.log(`%cApiaApi.post ${a}`,`color: ${I("message",s.colors)}`,{url:c,queryDataInURL:[...l],queryData:s.queryData,formData:s.postData,stringifyOptiopns:s.stringifyOptions})}const r=yield ye.post(c,s.postData,s.axiosConfig).catch(l=>{X(new Error(l))});return r?Ee(r,n,s):null})}function Ft(t,e){return W(this,null,function*(){const n=typeof t!="string"?re():t,o=D(typeof t=="string"?e??U:t),s=we(n,o.queryData,o.stringifyOptions);o.debug&&console.log("%cApiaApi.get",`color: ${I("message",o.colors)}`,{url:s});const c=yield ye.get(s,o.axiosConfig).catch(r=>{X(new Error(r))});return c?yield Ee(c,n,o):null})}const je={get:Ft,getConfig:D,post:Dt};function re(t){var e,n,o;let s={};if(t){const m=t,x=be(m,["ajaxUrl","queryString","stringifyOptions","shouldAvoidTabId","preventAsXmlParameter","avoidTabId","tabId"]);s=M({},x)}const c=Z.stringify(s,(e=t?.stringifyOptions)!=null?e:{arrayFormat:"repeat",encodeValuesOnly:!1});let r=(n=t?.ajaxUrl)!=null?n:window.URL_REQUEST_AJAX;r.indexOf("?")===r.length-1&&(r=r.slice(0,r.length-1)),r.startsWith("/")||(r=`/${r}`);const l=window.TAB_ID_REQUEST.match(/tokenId=(\w+)/),a=(l??[])[1];let i=(t!=null&&t.tabId?`&tabId=${t.tabId}&tokenId=${a}`:window.TAB_ID_REQUEST).slice(1);t!=null&&t.avoidTabId&&(i="");let{CONTEXT:d}=window;d!=null&&d.endsWith("/")&&(d+=d.slice(0,d.length-1));let u=`timestamp=${Date.now()}&`;(t!=null&&t.queryString&&t.queryString.includes("timestamp=")||c!=null&&c.includes("timestamp="))&&(u="");const v=d.replaceAll("/","");return r=(o=r.match(new RegExp(`^(?:(?:/?${v})?/)?(.+)$`)))==null?void 0:o[1],`${v?"/":""}${v}/${r}?${u}${t!=null&&t.preventAsXmlParameter?"":"asXml=true&"}${t!=null&&t.queryString?`${t.queryString}&`:""}${c?`${c}&`:""}${i}`}var Lt=Object.defineProperty,_e=Object.getOwnPropertySymbols,qt=Object.prototype.hasOwnProperty,Ut=Object.prototype.propertyIsEnumerable,Pe=(t,e,n)=>e in t?Lt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vt=(t,e)=>{for(var n in e||(e={}))qt.call(e,n)&&Pe(t,n,e[n]);if(_e)for(var n of _e(e))Ut.call(e,n)&&Pe(t,n,e[n]);return t};const Ht=t=>{const e=y.useMemo(()=>t.element,[t.element]),n=y.useMemo(()=>e.class?`handler__checkbox ${e.class}`:"handler__checkbox",[e.class]),o=y.useMemo(()=>Vt({required:e.mandatory},H(e.class)),[e.class,e.mandatory]),s=y.useCallback(c=>c==="on"||c===!0,[]);return p(ut,{className:n,name:e.id||e.name,label:e.text,title:e.title||e.text,initialValue:String(e.selected)==="true",disabled:e.readonly||e.disabled,validationRules:o,onChange:e.onChange,submitValueParser:s})};var Wt=Object.defineProperty,Se=Object.getOwnPropertySymbols,Xt=Object.prototype.hasOwnProperty,Bt=Object.prototype.propertyIsEnumerable,Me=(t,e,n)=>e in t?Wt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,zt=(t,e)=>{for(var n in e||(e={}))Xt.call(e,n)&&Me(t,n,e[n]);if(Se)for(var n of Se(e))Bt.call(e,n)&&Me(t,n,e[n]);return t};const Ie=t=>{const e=y.useMemo(()=>t.element,[t.element]),n=y.useMemo(()=>e.class?`handler__file ${e.class}`:"handler__file",[e.class]),o=y.useMemo(()=>zt({required:e.mandatory},H(e.class)),[e.class,e.mandatory]);return p(dt,{className:n,name:e.id||e.name,label:e.text,title:e.title||e.text,readOnly:e.readonly,disabled:e.disabled,validationRules:o})};Ie.displayName="ApiaApiFileInput";var Jt=Object.defineProperty,Qt=Object.defineProperties,Zt=Object.getOwnPropertyDescriptors,Ne=Object.getOwnPropertySymbols,Kt=Object.prototype.hasOwnProperty,Yt=Object.prototype.propertyIsEnumerable,Te=(t,e,n)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ke=(t,e)=>{for(var n in e||(e={}))Kt.call(e,n)&&Te(t,n,e[n]);if(Ne)for(var n of Ne(e))Yt.call(e,n)&&Te(t,n,e[n]);return t},Gt=(t,e)=>Qt(t,Zt(e));const Re=t=>{const e=y.useMemo(()=>t.element,[t.element]),n=y.useCallback(i=>y.lazy(()=>new Promise(d=>{import(`/api/modals/${i}`).then(u=>{d(u)}).catch(u=>{d({default:()=>{throw console.error(u),new Error(`The above error ocurred at component ApiaApiHandler/${i}, does it exist?`)}})})})),[]),[o,s]=y.useState(null);me(()=>{if(e.modalFunction){const i=e.modalFunction.match(/(?:fnc)?(\w+)\(?\)?$/);if(i){const d=i[i.length-1];s(n(d))}}});const c=y.useMemo(()=>e.class?`handler__${e.type} ${e.class}`:`handler__${e.type}`,[e.class,e.type]),r=y.useMemo(()=>ke({required:e.mandatory,maxLength:e.maxlength?Number(e.maxlength):void 0,pattern:e.regExp,patternMessage:e.regExpMessage},H(e.class)),[e.class,e.mandatory,e.maxlength,e.regExp,e.regExpMessage]),l=y.useMemo(()=>pt(e.class),[e.class]),a=y.useCallback(i=>e.type==="password"?nt(window.SALT,window.IV,window.PASSPHRASE,i,Number(window.KEY_SIZE),Number(window.ITERATION_COUNT)):i,[e.type]);return e.modalFunction?o?p(y.Suspense,{children:p(o,Gt(ke({},t),{element:e}))}):null:p(mt,{type:e.type,className:c,name:e.id||e.name,label:e.text,title:e.title||e.text,value:e.value,readOnly:e.readonly,disabled:e.disabled,validationFunction:l,validationRules:r,submitValueParser:a,onChange:e.onChange,autoComplete:e.type==="password"?"new-password":void 0})};Re.displayName="ApiaApiInput";var en=Object.defineProperty,De=Object.getOwnPropertySymbols,tn=Object.prototype.hasOwnProperty,nn=Object.prototype.propertyIsEnumerable,Fe=(t,e,n)=>e in t?en(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,on=(t,e)=>{for(var n in e||(e={}))tn.call(e,n)&&Fe(t,n,e[n]);if(De)for(var n of De(e))nn.call(e,n)&&Fe(t,n,e[n]);return t};const Le=t=>{var e;const n=y.useMemo(()=>t.element,[t.element]),o=y.useMemo(()=>n.class?`handler__radio ${n.class}`:"handler__radio",[n.class]),s=y.useMemo(()=>{var r;return N((r=n.options)==null?void 0:r.option).map(l=>({value:l.value,label:l.content}))},[(e=n.options)==null?void 0:e.option]),c=y.useMemo(()=>on({required:n.mandatory},H(n.class)),[n.class,n.mandatory]);return p(ft,{className:o,name:n.id||n.name,label:n.text,title:n.title||n.text,value:n.value,disabled:n.readonly||n.disabled,validationRules:c,options:s,onChange:n.onChange})};Le.displayName="ApiaApiRadio";var rn=Object.defineProperty,qe=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,ln=Object.prototype.propertyIsEnumerable,Ue=(t,e,n)=>e in t?rn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,sn=(t,e)=>{for(var n in e||(e={}))an.call(e,n)&&Ue(t,n,e[n]);if(qe)for(var n of qe(e))ln.call(e,n)&&Ue(t,n,e[n]);return t};const Ve=t=>{var e;const n=y.useMemo(()=>t.element,[t.element]),o=y.useMemo(()=>n.class?`handler__select ${n.class}`:"handler__select",[n.class]),s=y.useMemo(()=>{var l;return N((l=n.options)==null?void 0:l.option).map(a=>({value:a.value,label:a.content}))},[(e=n.options)==null?void 0:e.option]),c=y.useMemo(()=>sn({required:n.mandatory},H(n.class)),[n.class,n.mandatory]),r=et(()=>{var l,a,i,d;return(d=(i=(l=s.find(u=>u.value===t.element.value))==null?void 0:l.value)!=null?i:(a=s[0])==null?void 0:a.value)!=null?d:""},[]);return p(yt,{className:o,name:n.id||n.name,label:n.text,title:n.title||n.text,value:n.value,disabled:n.readonly||n.disabled,validationRules:c,options:s,onChange:n.onChange,initialValue:r})};Ve.displayName="ApiaApiSelect";var cn=Object.defineProperty,un=Object.defineProperties,dn=Object.getOwnPropertyDescriptors,He=Object.getOwnPropertySymbols,pn=Object.prototype.hasOwnProperty,mn=Object.prototype.propertyIsEnumerable,We=(t,e,n)=>e in t?cn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,F=(t,e)=>{for(var n in e||(e={}))pn.call(e,n)&&We(t,n,e[n]);if(He)for(var n of He(e))mn.call(e,n)&&We(t,n,e[n]);return t},L=(t,e)=>un(t,dn(e));const Xe=t=>{var e,n;const o=y.useMemo(()=>{var r,l,a;return N((a=(l=(r=t?.definition)==null?void 0:r.form.elements)==null?void 0:l.element)!=null?a:[])},[(n=(e=t?.definition)==null?void 0:e.form.elements)==null?void 0:n.element]),s=y.useCallback(()=>{var r;const l=d=>{if(d.length>1)for(let u=d.length-1;u>=0;u--)if(d[u].type==="empty")d.pop();else return d;return d},a=[];((r=o[0])==null?void 0:r.type)!=="2columnTitle"&&a.push(-1),o.forEach((d,u)=>{d.type==="2columnTitle"&&a.push(u)});const i=[];return a.forEach((d,u)=>{const v=d+1<o.length?d+1:o.length-1,m=u+1<a.length?a[u+1]:void 0;i.push({sectionHeader:d!==-1?o[d]:void 0,sectionElements:l(o.slice(v,m))})}),i},[o])(),c=y.useCallback(r=>{const l=r.findIndex(a=>a.type!=="hidden")!==-1;return p(S,{className:l?"handler__form__elements__section__content":"handler__form__elements__section__content handler__hidden",children:r.map(a=>{const i=L(F({},a),{onChange(){J(a.onChange,t).then(u=>{u&&u()}).catch(console.error)}}),d=i.id||i.name||ne();switch(i.type){case"table":{const u=JSON.parse(i.text);return p(S,L(F({},fe("layout.common.tables.information")),{children:de("table",{sx:{width:"100%"},children:[p("thead",{children:p("tr",{children:u.columns.map(v=>p("th",{children:v},v))})}),p("tbody",{children:u.rows.map(v=>p("tr",{children:v.cells.map((m,x)=>p("td",{children:m},`${m}_${u.columns[x]}`))},v.cells.join("-")))})]})}),d)}case"2columnSubTitle":return p(S,{className:i.class,as:"h6",children:i.value||i.text},d);case"2column":return p(S,{dangerouslySetInnerHTML:{__html:i.value||i.text},className:i.class},d);case"checkbox":return p(Ht,L(F({},t),{element:i}),d);case"file":return p(Ie,L(F({},t),{element:i}),d);case"hidden":case"password":case"text":return p(Re,L(F({},t),{element:i}),d);case"select":return p(Ve,L(F({},t),{element:i}),d);case"radio":return p(Le,L(F({},t),{element:i}),d);case"empty":return p(S,{className:"spacer"},d);default:return console.warn(`Unhandled element type: ${i.type}`,i),null}})},ne())},[t]);return p(S,{className:"handler__form__elements",children:s.map(r=>(r.sectionHeader,c(r.sectionElements)))})};Xe.displayName="ApiaApiFieldsContainer";var fn=Object.defineProperty,yn=Object.defineProperties,vn=Object.getOwnPropertyDescriptors,Be=Object.getOwnPropertySymbols,gn=Object.prototype.hasOwnProperty,hn=Object.prototype.propertyIsEnumerable,ze=(t,e,n)=>e in t?fn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ae=(t,e)=>{for(var n in e||(e={}))gn.call(e,n)&&ze(t,n,e[n]);if(Be)for(var n of Be(e))hn.call(e,n)&&ze(t,n,e[n]);return t},bn=(t,e)=>yn(t,vn(e)),Je=(t,e,n)=>new Promise((o,s)=>{var c=a=>{try{l(n.next(a))}catch(i){s(i)}},r=a=>{try{l(n.throw(a))}catch(i){s(i)}},l=a=>a.done?o(a.value):Promise.resolve(a.value).then(c,r);l((n=n.apply(t,e)).next())}),xn=(t,e,n)=>(e=t[Symbol.asyncIterator],n=(o,s)=>(s=t[o])&&(e[o]=c=>new Promise((r,l,a)=>(c=s.call(t,c),a=c.done,Promise.resolve(c.value).then(i=>r({value:i,done:a}),l)))),e?e.call(t):(t=t[Symbol.iterator](),e={},n("next"),n("return"),e));const $n=t=>{var e,n,o,s,c;const r=N((o=(n=(e=t.definition)==null?void 0:e.form.buttons)==null?void 0:n.button)!=null?o:[]),l=(s=t.configuration)==null?void 0:s.modalConfiguration,a=(c=t.configuration)==null?void 0:c.methodsPath,{name:i}=vt(),d=y.useCallback(u=>{const v=ne(),m=["submitAjax","submit"].includes(u.type)&&!u.onclick?"submit":"button",x=`handler__${m}`,j=()=>{(function(){return Je(this,null,function*(){const A=yield te.validateForm(i);if(!gt(A))return;const{submitValues:C}=A;function k(){Je(this,null,function*(){var f,g,b,h;if(u.onclick){const R=u.onclick.split(";");try{for(var $=xn(R),w,_,P;w=!(_=yield $.next()).done;w=!1){const q=_.value,ue=yield J(q,ae({},t));if(ue)ue({currentUrl:(g=(f=t.definition)==null?void 0:f.form.action)!=null?g:"noUrl"});else throw new Error(`The requested action is not defined: "${(h=(b=t.definition)==null?void 0:b.form.action)!=null?h:""}"`)}}catch(q){P=[q]}finally{try{w&&(_=$.return)&&(yield _.call($))}finally{if(P)throw P[0]}}}})}if(t!=null&&t.definition&&["submitAjax","submit"].includes(u.type)){const f=new FormData;Object.entries(C).forEach(([b,h])=>{f.append(b,h??"")});const g=`${t?.definition.form.action.match(new RegExp(`^${window.CONTEXT}/`))?"":window.CONTEXT}${t!=null&&t.definition.form.action.startsWith("/")?"":"/"}${t?.definition.form.action}`;t.setState(b=>bn(ae({},b),{isLoading:!0})),je.post(g,{postData:t.state.isMultipart?f:Z.stringify([...f.entries(),["isAjax",!0]].reduce((b,[h,$])=>{const w=ae({},b);return w[h.toString()]=$.toString(),w},{})),handleLoad:!0,notificationsCategory:"apiaApiHandler",modalConfiguration:l,methodsPath:a}).finally(()=>{k()})}else k()})})()};return p(bt,{className:x,disabled:t.state.disabled,id:u.id||u.text,isLoading:t.state.isLoading,title:u.text,type:m,onClick:j,children:u.text},v)},[i,a,l,t]);return p(S,{className:"handler__form__buttons",children:r.map(u=>d(u))})},wn=y.memo($n);var On=Object.defineProperty,An=Object.defineProperties,Cn=Object.getOwnPropertyDescriptors,Y=Object.getOwnPropertySymbols,Qe=Object.prototype.hasOwnProperty,Ze=Object.prototype.propertyIsEnumerable,Ke=(t,e,n)=>e in t?On(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,E=(t,e)=>{for(var n in e||(e={}))Qe.call(e,n)&&Ke(t,n,e[n]);if(Y)for(var n of Y(e))Ze.call(e,n)&&Ke(t,n,e[n]);return t},B=(t,e)=>An(t,Cn(e)),En=(t,e)=>{var n={};for(var o in t)Qe.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&Y)for(var o of Y(t))e.indexOf(o)<0&&Ze.call(t,o)&&(n[o]=t[o]);return n},G=(t,e,n)=>new Promise((o,s)=>{var c=a=>{try{l(n.next(a))}catch(i){s(i)}},r=a=>{try{l(n.throw(a))}catch(i){s(i)}},l=a=>a.done?o(a.value):Promise.resolve(a.value).then(c,r);l((n=n.apply(t,e)).next())});const le=new class extends Q{},se=new class extends Q{},z="ApiaApiForm",Ye={};function J(t,e){return G(this,null,function*(){return new Promise(n=>{var o,s,c;try{const r=/^\/?([\w\d_-]+)\/?(?:\(([^)]*)\))?$/,l=t.match(r);if(l){const a=l[1],i=l[2],d=[...(c=(s=(o=e.configuration)==null?void 0:o.methodsPath)==null?void 0:s.split("/").filter(m=>!!m))!=null?c:[],a].join("/"),u=m=>{typeof m.default!="function"&&v();const x=m.default;Ye[a]=j=>{var A;return x(e,B(E({},j),{inlineArguments:(A=i?.split(",").map(C=>C.startsWith("'")||C.startsWith('"')?C.slice(1,C.length-1):C))!=null?A:[]}))},n(Ye[a])},v=()=>{throw new Error(`${a}.ts not found at ${d}.ts nor ./${a}.ts`)};import(`/api/methods/${d}.ts`).then(u).catch(()=>{var m;((m=e.configuration)==null?void 0:m.methodsPath)!==void 0?import(`/api/methods/${a}.ts`).then(u).catch(v):v()})}}catch(r){console.error(r),e.reset(),e.setError({type:"danger",message:"Error while loading current method."})}})})}function jn(t){return t.form!==void 0&&typeof t.form=="object"&&!!t.form}function _n(t){return typeof t.canClose=="boolean"&&typeof t.type=="string"&&!!t.function}function Pn(t){return!!(typeof t.canClose=="boolean"&&typeof t.type=="string"&&typeof t.text=="object"&&t.text&&typeof t.text.label=="string")}const ie=new ot;function Sn(){const[,t,e]=lt(void 0),n=O.useCallback(o=>{t(o)},[t]);return me(()=>{ie.on("update",n)}),st(()=>ie.off("update",n)),e}const ce=new class extends Q{emit(t,e){super.emit(t,e)}};function Mn(t,e,n){return ie.value=n,jn(t)?(ce.emit("form",t),!0):_n(t)?(se.emit("method",{name:t.function.name,props:{messages:t.function.messages,attributes:t.function,currentUrl:e}}),!0):Pn(t)?(le.emit("message",{predicate:t.text.content,title:t.text.title}),!0):!1}const ee={disabled:!1,isLoading:!1,isMultipart:!1,progress:0,errors:{}},In=()=>{var t,e,n;const o=Sn(),[s,c]=O.useState(B(E({},ee),{windowIndex:-1})),[r,l]=O.useState(void 0);O.useEffect(()=>ce.on("form",l),[]);const a=O.useCallback((f,g)=>te.setFieldValue(z,f,g),[]);O.useEffect(()=>{var f,g,b;if(!r)return;const h=N((b=(g=(f=r?.form)==null?void 0:f.elements)==null?void 0:g.element)!=null?b:[]);let $=!1;const w=Object.values(h);let _=0;for(;_<w.length&&!$;)w[_++].type==="file"&&($=!0);c(P=>B(E(E({},P),ee),{isMultipart:$}))},[r]);const i=xt(),{show:d,onClose:u}=i,v=En(i,["show","onClose"]),m=O.useCallback(()=>{var f,g,b;u(),ce.emit("form",void 0),c(h=>E(E({},h),ee)),(b=(g=(f=o.current)==null?void 0:f.modalConfiguration)==null?void 0:g.onClose)==null||b.call(g),te.unregisterForm(z)},[u,o]),x=O.useRef(null);O.useEffect(()=>{var f;const g=(f=x.current)==null?void 0:f.querySelectorAll("a,input,textarea,button");g?.length===1&&rt.on([...g][0])});const j=O.useCallback(f=>{V(E({},f))},[]),A=O.useCallback(()=>({alert,close:m,configuration:o.current,formDefinition:r,reset:()=>c(f=>E(E({},f),ee)),setError:j,setMessage:f=>{var g,b;(b=(g=o.current)==null?void 0:g.modalConfiguration)!=null&&b.onMessage&&o.current.modalConfiguration.onMessage(f)},setState:c,state:s,setValue:a}),[m,o,r,j,s,a]);O.useEffect(()=>{const f=h=>G(void 0,[h],function*({name:$,props:{messages:w,attributes:_,currentUrl:P}}){const R=yield J(`${$}`,A());R&&R({messages:w,attributes:_,currentUrl:P})}),g=h=>{var $,w,_,P;const R=A();V({message:h.predicate,type:"warning",onClose:(w=($=R.configuration)==null?void 0:$.modalConfiguration)==null?void 0:w.onMessageClose});const q=(P=(_=R.configuration)==null?void 0:_.modalConfiguration)==null?void 0:P.onMessage;q&&q(h)},b=h=>G(void 0,null,function*(){if(h.toDo==="ajaxHiddeAll"&&m(),h.toDo==="functionTimedCall"){const $=yield J(N(h.param)[1],A());$&&setTimeout(()=>{var w;return $({currentUrl:(w=r?.form.action)!=null?w:"noUrl"})},Number(h.param[0]))}});return le.on("message",g),se.on("method",f),oe.on("action",b),()=>{le.off("message",g),se.off("method",f),oe.off("action",b)}},[s.windowIndex,u,m]),O.useEffect(()=>{r&&d()},[r]);const C=A(),k=O.useCallback(f=>G(void 0,null,function*(){if(f&&r!=null&&r.form.onLoad){const g=yield J(`${r?.form.onLoad}`,A());g&&g()}}),[r?.form.onLoad,A]);return p(jt,{id:z,children:p($t,B(E({ref:x,onClose:m,id:z,title:(n=(e=(t=o.current)==null?void 0:t.modalConfiguration)==null?void 0:e.modalTitle)!=null?n:r?.form.title,size:"md-fixed",shouldCloseOnEsc:!s.disabled,shouldCloseOnOverlayClick:!s.disabled,initialFocusGetter:O.useCallback(f=>f?.querySelector(at),[])},v),{children:r&&p(S,B(E({},fe("layout.common.modals.apiaApi")),{children:de(ht,{name:z,avoidFieldsOverride:!0,className:"handler__form",children:[p(Xe,E({definition:r},C)),s.isMultipart&&s.progress>0&&p(S,{className:"progressBox",children:p(wt,{id:"ApiaApiHandler progress",progress:s.progress,loading:!0})}),p(S,{ref:k}),p(wn,E({definition:r},C))]})}))}))})},Nn=O.memo(In);export{je as ApiaApi,Nn as ApiaApiHandler,re as makeApiaUrl};