@sankhyalabs/sankhyablocks 1.1.23 → 1.1.24

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.
@@ -2,1223 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- const index = require('./index-20a7d705.js');
6
-
7
- /**
8
- * Classe com utiliários comuns para Strings.
9
- */
10
- class StringUtils {
11
- /**
12
- * Verifica se a string está vazia.
13
- * Valores null e undefined são considerados como vazio.
14
- *
15
- * @param value String para ser validada.
16
- */
17
- static isEmpty(value) {
18
- if (value == undefined || value === null) {
19
- return true;
20
- }
21
- value = value.toString();
22
- value = value.trim();
23
- if (value.length === 0) {
24
- return true;
25
- }
26
- return false;
27
- }
28
- /**
29
- * Remove acentos de vogais, substitui Ç por c e retorna a string em caixa alta.
30
- *
31
- * @param value String para ser transformada.
32
- */
33
- static replaceAccentuatedChars(text) {
34
- text = text.toUpperCase();
35
- text = text.replace(/[À]/, "A");
36
- text = text.replace(/[Á]/, "A");
37
- text = text.replace(/[Â]/, "A");
38
- text = text.replace(/[Ã]/, "A");
39
- text = text.replace(/[Ä]/, "A");
40
- text = text.replace(/[È]/, "E");
41
- text = text.replace(/[É]/, "E");
42
- text = text.replace(/[Ê]/, "E");
43
- text = text.replace(/[Ë]/, "E");
44
- text = text.replace(/[Ì]/, "I");
45
- text = text.replace(/[Í]/, "I");
46
- text = text.replace(/[Î]/, "I");
47
- text = text.replace(/[Ï]/, "I");
48
- text = text.replace(/[Ò]/, "O");
49
- text = text.replace(/[Ó]/, "O");
50
- text = text.replace(/[Ô]/, "O");
51
- text = text.replace(/[Ö]/, "O");
52
- text = text.replace(/[Ù]/, "U");
53
- text = text.replace(/[Ú]/, "U");
54
- text = text.replace(/[Û]/, "U");
55
- text = text.replace(/[Ü]/, "U");
56
- text = text.replace(/[Ç]/, "C");
57
- return text.replace(/[^a-z0-9]/gi, '');
58
- }
59
- }
60
-
61
- /**
62
- * `MaskFormatter` é usado para formatar strings. Seu comportamento
63
- * é controlado pela formato do atributo `mask` que especifica quais
64
- * caracteres são válidos e onde devem estar posicionados, intercalando-os
65
- * com eventuais caracteres literais expressados no padrão informado.
66
- * Sua implementação é inspirada pela implementação em Java do [MaskFormatter](https://docs.oracle.com/javase/7/docs/api/javax/swing/text/MaskFormatter.html).
67
- *
68
- * Para o padrão da máscara podem ser usados os seguintes caracteres especiais:
69
- *
70
- * | Caractere | Comportamento |
71
- * |:---------:|-------------------------------------------------------------------------------------------------------------|
72
- * | # | Qualquer número |
73
- * | ' | "Escapa" o caractere que vem na sequência. Útil quando desejamos converter um caractere especial em literal.|
74
- * | U | Qualquer letra. Transforma letras maiúsculas em maiúsculas. |
75
- * | L | Qualquer letra. Transforma letras maiúsculas em minúsculas. |
76
- * | A | Qualquer letra ou número. |
77
- * | ? | Qualquer letra. Preserva maiúsculas e minúsculas. |
78
- * | * | Qualquer caractere. |
79
- *
80
- * Os demais caracteres presentes no padrão serão tratados como literais, isto é,
81
- * serão apenas inseridos naquela posição.
82
- *
83
- * Quando o o valor a ser formatado é menor que a máscara um 'placeHolder'
84
- * será inserido em cada posição ausente, completando a formatação.
85
- * Por padrão será usado um espaço em branco como 'placeHolder' mas
86
- * esse valor pode ser alterado.
87
- *
88
- * For por exemplo:
89
- * '''
90
- * const formatter: MaskFormatter = new MaskFormatter("###-####");
91
- * formatter.placeholder = '_';
92
- * console.log(formatter.format("123"));
93
- * '''
94
- * resultaria na string '123-____'.
95
- *
96
- * ##Veja mais alguns exemplos:
97
- * |Padrão |Máscara |Entrada |Saída |
98
- * |----------------|------------------|--------------|------------------|
99
- * |Telefone |(##) ####-#### |3432192515 |(34) 3219-2515 |
100
- * |CPF |###.###.###-## |12345678901 |123.456.789-01 |
101
- * |CNPJ |##.###.###/####-##|12345678901234|12.345.678/9012-34|
102
- * |CEP |##.###-### |12345678 |12.345-678 |
103
- * |PLACA (veículo) |UUU-#### |abc1234 |ABC-1234 |
104
- * |Cor RGB |'#AAAAAA |00000F0 |#0000F0 |
105
- *
106
- */
107
- class MaskFormatter {
108
- constructor(mask) {
109
- this._mask = '';
110
- this._maskChars = new Array();
111
- /**
112
- * Determina qual caractere será usado dos caracteres não presentes no valor
113
- * ou seja, aqueles que o usuário ainda não informou. Por padrão usamos um espaço
114
- */
115
- this.placeholder = ' ';
116
- this.mask = mask;
117
- }
118
- /**
119
- * Setter para mask. Trata-se do padrão que se espera ao formatar o texto.
120
- */
121
- set mask(mask) {
122
- this._mask = mask;
123
- this.updateInternalMask();
124
- }
125
- /**
126
- * Getter para mask
127
- *
128
- * @return A última máscara informada.
129
- */
130
- get mask() {
131
- return this._mask;
132
- }
133
- /**
134
- * Formata a string passada baseada na máscara definda pelo atributo mask.
135
- *
136
- * @param value Valor a ser formatado
137
- * @return O valor processado de acordo com o padrão
138
- */
139
- format(value) {
140
- let result = '';
141
- const index = [0];
142
- let counter = 0;
143
- const maxCounter = this._maskChars.length;
144
- while (counter < maxCounter) {
145
- result = this._maskChars[counter].append(result, value, index);
146
- counter++;
147
- }
148
- return result;
149
- }
150
- /**
151
- * Preparamos a formatação internamente de acordo com o padrão.
152
- */
153
- updateInternalMask() {
154
- this._maskChars.length = 0;
155
- if (this.mask != null) {
156
- let counter = 0;
157
- const maxCounter = this.mask.length;
158
- while (counter < maxCounter) {
159
- let maskChar = this.mask.charAt(counter);
160
- switch (maskChar) {
161
- case MaskFormatter.DIGIT_KEY:
162
- this._maskChars.push(new MaskFormatter.DigitMaskCharacter(this, maskChar));
163
- break;
164
- case MaskFormatter.LITERAL_KEY:
165
- if (++counter < maxCounter) {
166
- maskChar = this.mask.charAt(counter);
167
- this._maskChars.push(new MaskFormatter.LiteralCharacter(this, maskChar));
168
- }
169
- break;
170
- case MaskFormatter.UPPERCASE_KEY:
171
- this._maskChars.push(new MaskFormatter.UpperCaseCharacter(this, maskChar));
172
- break;
173
- case MaskFormatter.LOWERCASE_KEY:
174
- this._maskChars.push(new MaskFormatter.LowerCaseCharacter(this, maskChar));
175
- break;
176
- case MaskFormatter.ALPHA_NUMERIC_KEY:
177
- this._maskChars.push(new MaskFormatter.AlphaNumericCharacter(this, maskChar));
178
- break;
179
- case MaskFormatter.CHARACTER_KEY:
180
- this._maskChars.push(new MaskFormatter.CharCharacter(this, maskChar));
181
- break;
182
- case MaskFormatter.ANYTHING_KEY:
183
- this._maskChars.push(new MaskFormatter.MaskCharacter(this, maskChar));
184
- break;
185
- default:
186
- this._maskChars.push(new MaskFormatter.LiteralCharacter(this, maskChar));
187
- break;
188
- }
189
- counter++;
190
- }
191
- }
192
- }
193
- }
194
- MaskFormatter.DIGIT_KEY = "#";
195
- MaskFormatter.LITERAL_KEY = "'";
196
- MaskFormatter.UPPERCASE_KEY = "U";
197
- MaskFormatter.LOWERCASE_KEY = "L";
198
- MaskFormatter.ALPHA_NUMERIC_KEY = "A";
199
- MaskFormatter.CHARACTER_KEY = "?";
200
- MaskFormatter.ANYTHING_KEY = "*";
201
- //
202
- // Classes internas usadas para representar a máscara.
203
- //
204
- MaskFormatter.MaskCharacter = class {
205
- constructor(maskFormatter, type) {
206
- this.maskFormatter = maskFormatter;
207
- this.type = type;
208
- }
209
- /**
210
- * Cada subclasse deve sobrescrever o retornando true, caso represente
211
- * um caractere literal. Por padrão o retorno é false.
212
- */
213
- isLiteral() {
214
- return false;
215
- }
216
- /**
217
- * Returns true if <code>aChar</code> is a valid reprensentation of
218
- * the receiver. The default implementation returns true if the
219
- * receiver represents a literal character and <code>getChar</code>
220
- * == aChar. Otherwise, this will return true is <code>aChar</code>
221
- * is contained in the valid characters and not contained
222
- * in the invalid characters.
223
- */
224
- isValidCharacter(aChar) {
225
- if (this.isLiteral()) {
226
- return (this.getChar(aChar) == aChar);
227
- }
228
- aChar = this.getChar(aChar);
229
- return true;
230
- }
231
- /**
232
- * Returns the character to insert for <code>aChar</code>. The
233
- * default implementation returns <code>aChar</code>. Subclasses
234
- * that wish to do some sort of mapping, perhaps lower case to upper
235
- * case should override this and do the necessary mapping.
236
- */
237
- getChar(aChar) {
238
- return aChar;
239
- }
240
- /**
241
- * Appends the necessary character in <code>formatting</code> at
242
- * <code>index</code> to <code>buff</code>.
243
- */
244
- append(result, formatting, index) {
245
- const inString = index[0] < formatting.length;
246
- const aChar = inString ? formatting.charAt(index[0]) : '';
247
- if (this.isLiteral()) {
248
- const literal = this.getChar(aChar);
249
- result += literal;
250
- if (literal === aChar) {
251
- index[0] = index[0] + 1;
252
- }
253
- }
254
- else if (index[0] >= formatting.length) {
255
- result += this.maskFormatter.placeholder;
256
- index[0] = index[0] + 1;
257
- }
258
- else if (this.isValidCharacter(aChar)) {
259
- result += this.getChar(aChar);
260
- index[0] = index[0] + 1;
261
- }
262
- else {
263
- throw new Error(`Valor inválido: "${aChar}". Na posição ${index[0] + 1} espera-se ${this.getFormatMessage()}.`);
264
- }
265
- return result;
266
- }
267
- getFormatMessage() {
268
- let message;
269
- switch (this.type) {
270
- case MaskFormatter.UPPERCASE_KEY:
271
- case MaskFormatter.LOWERCASE_KEY:
272
- case MaskFormatter.CHARACTER_KEY:
273
- message = 'uma letra';
274
- break;
275
- case MaskFormatter.DIGIT_KEY:
276
- message = 'um número';
277
- break;
278
- case MaskFormatter.ALPHA_NUMERIC_KEY:
279
- message = 'uma letra ou um número';
280
- break;
281
- default:
282
- message = '';
283
- }
284
- return message;
285
- }
286
- };
287
- MaskFormatter.LiteralCharacter = class extends MaskFormatter.MaskCharacter {
288
- constructor(maskFormatter, fixedChar) {
289
- super(maskFormatter, fixedChar);
290
- this._fixedChar = fixedChar;
291
- }
292
- isLiteral() {
293
- return true;
294
- }
295
- getChar(aChar) {
296
- return this._fixedChar;
297
- }
298
- };
299
- MaskFormatter.DigitMaskCharacter = class extends MaskFormatter.MaskCharacter {
300
- isValidCharacter(aChar) {
301
- return (this.isDigit(aChar) && super.isValidCharacter(aChar));
302
- }
303
- isDigit(char) {
304
- return char >= '0' && char <= '9';
305
- }
306
- };
307
- MaskFormatter.UpperCaseCharacter = class extends MaskFormatter.MaskCharacter {
308
- isValidCharacter(aChar) {
309
- return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
310
- }
311
- getChar(aChar) {
312
- return aChar.toUpperCase();
313
- }
314
- };
315
- MaskFormatter.LowerCaseCharacter = class extends MaskFormatter.MaskCharacter {
316
- isValidCharacter(aChar) {
317
- return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
318
- }
319
- getChar(aChar) {
320
- return aChar.toLocaleLowerCase();
321
- }
322
- };
323
- MaskFormatter.AlphaNumericCharacter = class extends MaskFormatter.MaskCharacter {
324
- isValidCharacter(aChar) {
325
- //FIXME: talvez seja problema usar regex aqui... avaliar se existe forma mais barata
326
- return (/[a-z0-9]/i.test(aChar)) && super.isValidCharacter(aChar);
327
- }
328
- };
329
- MaskFormatter.CharCharacter = class extends MaskFormatter.MaskCharacter {
330
- isValidCharacter(aChar) {
331
- //FIXME: talvez seja problema usar regex aqui... avaliar se existe forma mais barata
332
- return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
333
- }
334
- };
335
-
336
- class DateUtils {
337
- static clearTime(date, adjustDayLightSavingTime = true) {
338
- const newDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0);
339
- return adjustDayLightSavingTime ? DateUtils.adjustDLST(newDate) : newDate;
340
- }
341
- static strToDate(strValue, adjustDayLightSavingTime = true, monthYearMode = false) {
342
- /** monthYearMode é um booleano para usar o formato MM/YYYY.
343
- * Quando ativado, é retornado o primeiro dia do mês apenas para construir a data.
344
- * Não há necessidade de verificar o horário de verão quando utilizado esse modo. */
345
- let parts;
346
- if (monthYearMode) {
347
- parts = /^(1[0-2]|0[1-9]|[1-9])[^\d]?(\d{2}|\d{4})(?:\s(\d{1,2}):(\d{1,2}):?(\d{0,2}))?$/.exec(strValue);
348
- }
349
- else {
350
- parts = /^(3[01]|[1-2]\d|0[1-9]|[1-9])[^\d]?(1[0-2]|0[1-9]|[1-9])[^\d]?(\d{2}|\d{4})(?:\s(\d{1,2}):(\d{1,2}):?(\d{0,2}))?$/.exec(strValue);
351
- }
352
- if (!parts) {
353
- return undefined;
354
- }
355
- var day = monthYearMode ? 1 : Number(parts[1]);
356
- var month = Number(parts[(monthYearMode ? 1 : 2)]);
357
- var year = Number(parts[(monthYearMode ? 2 : 3)]);
358
- var hour = Number(parts[(monthYearMode ? 3 : 4)] || 0);
359
- var min = Number(parts[(monthYearMode ? 4 : 5)] || 0);
360
- var sec = Number(parts[(monthYearMode ? 5 : 6)] || 0);
361
- if (year < 100) {
362
- year += year < 30 ? 2000 : 1900;
363
- }
364
- let date = new Date(year, month - 1, day, hour, min, sec, 0);
365
- if (adjustDayLightSavingTime === true && !monthYearMode && hour == 0) {
366
- date = DateUtils.adjustDLST(date);
367
- }
368
- return date;
369
- }
370
- static adjustDLST(date) {
371
- //Work around para corrigir o Bug do horário de verão.
372
- if (date.getHours() == 23) {
373
- return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1, 1, 0, 0, 0);
374
- }
375
- return date;
376
- }
377
- }
378
-
379
- new MaskFormatter("##:##");
380
-
381
- /**
382
- * Representa as propriedades necessárias para se executar uma requisição.
383
- */
384
- /** Representa os verbos HTTP suportados */
385
- var Method;
386
- (function (Method) {
387
- Method[Method["GET"] = 0] = "GET";
388
- Method[Method["PUT"] = 1] = "PUT";
389
- Method[Method["POST"] = 2] = "POST";
390
- Method[Method["DELETE"] = 3] = "DELETE";
391
- })(Method || (Method = {}));
392
-
393
- var DataType;
394
- (function (DataType) {
395
- DataType["NUMBER"] = "NUMBER";
396
- DataType["DATE"] = "DATE";
397
- DataType["TEXT"] = "TEXT";
398
- DataType["BOOLEAN"] = "BOOLEAN";
399
- DataType["OBJECT"] = "OBJECT";
400
- })(DataType || (DataType = {}));
401
- const convertType = (dataType, value) => {
402
- if (value === undefined || value === null) {
403
- return value;
404
- }
405
- switch (dataType) {
406
- case DataType.NUMBER:
407
- return value === "" || isNaN(value) ? null : Number(value);
408
- case DataType.OBJECT:
409
- return typeof value === "string" ? JSON.parse(value) : value;
410
- case DataType.BOOLEAN:
411
- return Boolean(value);
412
- case DataType.DATE:
413
- return new Date(value.toString());
414
- default:
415
- return value;
416
- }
417
- };
418
-
419
- class DataUnitAction {
420
- constructor(type, payload) {
421
- this._type = type;
422
- this._payload = payload;
423
- }
424
- get type() {
425
- return this._type;
426
- }
427
- get payload() {
428
- return this._payload;
429
- }
430
- }
431
- var Action;
432
- (function (Action) {
433
- Action["LOADING_METADATA"] = "loadingMetadata";
434
- Action["METADATA_LOADED"] = "metadataLoaded";
435
- Action["LOADING_DATA"] = "loadingData";
436
- Action["DATA_LOADED"] = "dataLoaded";
437
- Action["SAVING_DATA"] = "savingData";
438
- Action["DATA_SAVED"] = "dataSaved";
439
- Action["REMOVING_RECORDS"] = "removingRecords";
440
- Action["RECORDS_REMOVED"] = "recordsRemoved";
441
- Action["RECORDS_ADDED"] = "recordsAdded";
442
- Action["RECORDS_COPIED"] = "recordsCopied";
443
- Action["DATA_CHANGED"] = "dataChanged";
444
- Action["EDITION_CANCELED"] = "editionCanceled";
445
- Action["CHANGE_UNDONE"] = "changeUndone";
446
- Action["CHANGE_REDONE"] = "changeRedone";
447
- Action["SELECTION_CHANGED"] = "selectionChanged";
448
- Action["NEXT_SELECTED"] = "nextSelected";
449
- Action["PREVIOUS_SELECTED"] = "previousSelected";
450
- Action["STATE_CHANGED"] = "stateChanged";
451
- })(Action || (Action = {}));
452
-
453
- /**
454
- * Essa classe representa uma interpretação do padrão de projetos Flux.
455
- * No padrão Flux os dados da aplicação são chamados de "estado" e existem
456
- * algumas regras para gerenciamento/manipulação desse estado:
457
- *
458
- * 1 - O estado é imutável.
459
- * 2 - Toda modificação de estado é representada por uma "ação".
460
- * 3 - Quando "ações" acontecem a "store" cria um novo estado e notifica a todos interessados.
461
- *
462
- * Nessa interpretação desse design pattern, o StateManager faz o papel da store,
463
- * notificando os manipuladores de estado (handlers), que são responsáveis por pedaços
464
- * do estado (slices).
465
- *
466
- * O StateManager mantém dois tipos de estados: "Histórico" e "Não Histórico". No estado
467
- * "Histórico", sempre que uma alteração de estado acontece, o estado anterior é guardado em
468
- * uma pilha, o que permite que possamos voltar no tempo, desfazendo algumas ações
469
- */
470
- class StateManager {
471
- constructor(reducers) {
472
- this._past = [];
473
- this._future = [];
474
- this._present = {};
475
- this._nonHist = {};
476
- this._histClean = false;
477
- this._reducers = reducers;
478
- }
479
- process(action) {
480
- const oldPresent = this._present;
481
- let hasHistChange = false;
482
- this._histClean = false;
483
- this._reducers.forEach(reducer => {
484
- const sliceName = reducer.sliceName;
485
- const isHistoric = this.isHistoric(sliceName);
486
- const oldSlice = this.getSlice(sliceName, isHistoric);
487
- const newSlice = reducer.reduce(this, oldSlice, action);
488
- if (newSlice !== oldSlice) {
489
- this.updateSlice(sliceName, newSlice, isHistoric);
490
- hasHistChange || (hasHistChange = isHistoric);
491
- }
492
- });
493
- if (hasHistChange && !this._histClean) {
494
- this._past.push(oldPresent);
495
- this._future = [];
496
- document.dispatchEvent(new CustomEvent("undoableAction", { detail: this }));
497
- }
498
- }
499
- select(sliceName, selector) {
500
- const isHistoric = this.isHistoric(sliceName);
501
- return selector(this.getSlice(sliceName, isHistoric));
502
- }
503
- isHistoric(slice) {
504
- return slice.startsWith("hist::");
505
- }
506
- updateSlice(name, slice, isHistoric) {
507
- if (isHistoric) {
508
- this._present = Object.assign(Object.assign({}, this._present), { [name]: slice });
509
- if (slice === undefined) {
510
- delete this._present[name];
511
- }
512
- }
513
- else {
514
- this._nonHist = Object.assign(Object.assign({}, this._nonHist), { [name]: slice });
515
- if (slice === undefined) {
516
- delete this._nonHist[name];
517
- }
518
- }
519
- }
520
- getSlice(name, isHistoric) {
521
- return isHistoric ? this._present[name] : this._nonHist[name];
522
- }
523
- canUndo() {
524
- return this._past.length > 0;
525
- }
526
- canRedo() {
527
- return this._future.length > 0;
528
- }
529
- undo() {
530
- if (this.canUndo()) {
531
- this._future.push(this._present);
532
- this._present = this._past.pop();
533
- }
534
- }
535
- redo() {
536
- if (this.canRedo()) {
537
- this._past.push(this._present);
538
- this._present = this._future.pop();
539
- }
540
- }
541
- clearUndo() {
542
- this._histClean = true;
543
- this._past = [];
544
- this._future = [];
545
- }
546
- persist() {
547
- }
548
- }
549
-
550
- class HistReducerImpl {
551
- constructor() {
552
- this.sliceName = "";
553
- }
554
- reduce(stateManager, _currentState, action) {
555
- switch (action.type) {
556
- case Action.DATA_SAVED:
557
- case Action.EDITION_CANCELED:
558
- stateManager.clearUndo();
559
- break;
560
- case Action.CHANGE_UNDONE:
561
- stateManager.undo();
562
- break;
563
- case Action.CHANGE_REDONE:
564
- stateManager.redo();
565
- break;
566
- }
567
- }
568
- }
569
- const HistReducer = new HistReducerImpl();
570
- const canUndo = (stateManager) => {
571
- return stateManager.canUndo();
572
- };
573
- const canRedo = (stateManager) => {
574
- return stateManager.canRedo();
575
- };
576
-
577
- class UnitMetadataReducerImpl {
578
- constructor() {
579
- this.sliceName = "unitMetadata";
580
- }
581
- reduce(_stateManager, currentState, action) {
582
- if (action.type === Action.METADATA_LOADED) {
583
- return action.payload;
584
- }
585
- return currentState;
586
- }
587
- }
588
- const UnitMetadataReducer = new UnitMetadataReducerImpl();
589
- const getMetadata = (stateManager) => {
590
- return stateManager.select(UnitMetadataReducer.sliceName, (state) => state);
591
- };
592
- const getField = (stateManager, fieldName) => {
593
- const md = getMetadata(stateManager);
594
- return md ? md.fields.find(fmd => fmd.name === fieldName) : undefined;
595
- };
596
-
597
- class RemovedRecordsReducerImpl {
598
- constructor() {
599
- this.sliceName = "hist::removedRecords";
600
- }
601
- reduce(_stateManager, currentState, action) {
602
- switch (action.type) {
603
- case Action.RECORDS_REMOVED:
604
- const { records, buffered } = action.payload;
605
- if (buffered) {
606
- return (currentState || []).concat(records);
607
- }
608
- return currentState;
609
- case Action.EDITION_CANCELED:
610
- case Action.DATA_SAVED:
611
- return undefined;
612
- }
613
- return currentState;
614
- }
615
- }
616
- const RemovedRecordsReducer = new RemovedRecordsReducerImpl();
617
- const getRemovedRecords = (stateManager) => {
618
- return stateManager.select(RemovedRecordsReducer.sliceName, (state) => state);
619
- };
620
-
621
- class RecordsReducerImpl {
622
- constructor() {
623
- this.sliceName = "records";
624
- }
625
- reduce(stateManager, currentState, action) {
626
- switch (action.type) {
627
- case Action.DATA_LOADED:
628
- return action.payload;
629
- case Action.RECORDS_REMOVED:
630
- const { records, buffered } = action.payload;
631
- if (!buffered) {
632
- return currentState.filter(r => !records.includes(r.__record__id__));
633
- }
634
- return currentState;
635
- case Action.DATA_SAVED:
636
- const recordsMap = new Map();
637
- const currentRecords = getRecords(stateManager);
638
- if (currentRecords) {
639
- const removed = getRemovedRecords(stateManager) || [];
640
- currentRecords.forEach(r => {
641
- if (!removed.includes(r.__record__id__)) {
642
- recordsMap.set(r.__record__id__, r);
643
- }
644
- });
645
- }
646
- const savedRecords = action.payload.records;
647
- savedRecords.forEach(sr => {
648
- const recordId = sr.__old__id__ || sr.__record__id__;
649
- const newRecord = Object.assign({}, sr);
650
- delete newRecord["__old__id__"];
651
- recordsMap.set(recordId, newRecord);
652
- });
653
- return Array.from(recordsMap.values());
654
- }
655
- return currentState;
656
- }
657
- }
658
- const RecordsReducer = new RecordsReducerImpl();
659
- const getRecords = (stateManager) => {
660
- return stateManager.select(RecordsReducer.sliceName, (state) => state);
661
- };
662
-
663
- class AddedRecordsReducerImpl {
664
- constructor() {
665
- this.sliceName = "hist::addedRecords";
666
- }
667
- reduce(_stateManager, currentState, action) {
668
- switch (action.type) {
669
- case Action.RECORDS_ADDED:
670
- case Action.RECORDS_COPIED:
671
- return (currentState || []).concat(action.payload);
672
- case Action.DATA_SAVED:
673
- case Action.EDITION_CANCELED:
674
- return undefined;
675
- }
676
- return currentState;
677
- }
678
- }
679
- const AddedRecordsReducer = new AddedRecordsReducerImpl();
680
- const getAddedRecords = (stateManager) => {
681
- return stateManager.select(AddedRecordsReducer.sliceName, (state) => state);
682
- };
683
- const prepareAddedRecordId = (stateManager, source) => {
684
- let index = (getAddedRecords(stateManager) || []).length;
685
- return source.map(item => { return Object.assign(Object.assign({}, item), { __record__id__: "NEW_" + (index++) }); });
686
- };
687
-
688
- class ChangesReducerImpl {
689
- constructor() {
690
- this.sliceName = "hist::changes";
691
- }
692
- reduce(stateManager, currentState, action) {
693
- switch (action.type) {
694
- case Action.DATA_CHANGED:
695
- const selection = action.payload.records || getSelection(stateManager);
696
- if (selection) {
697
- const newState = new Map(currentState);
698
- selection.forEach(recordId => {
699
- const newChanges = Object.assign(Object.assign({}, newState.get(recordId)), action.payload);
700
- delete newChanges.records;
701
- newState.set(recordId, newChanges);
702
- });
703
- return newState;
704
- }
705
- return currentState;
706
- case Action.DATA_SAVED:
707
- case Action.EDITION_CANCELED:
708
- return undefined;
709
- }
710
- return currentState;
711
- }
712
- }
713
- const ChangesReducer = new ChangesReducerImpl();
714
- const getChanges = (stateManager) => {
715
- return stateManager.select(ChangesReducer.sliceName, (state) => state);
716
- };
717
- const isDirty = (stateManager) => {
718
- if (getAddedRecords(stateManager) !== undefined) {
719
- return true;
720
- }
721
- if (getRemovedRecords(stateManager) !== undefined) {
722
- return true;
723
- }
724
- return getChanges(stateManager) !== undefined;
725
- };
726
- const getChangesToSave = (dataUnit, stateManager) => {
727
- const result = [];
728
- const changes = getChanges(stateManager);
729
- const records = getRecords(stateManager);
730
- records === null || records === void 0 ? void 0 : records.forEach(r => {
731
- if (changes) {
732
- const c = changes.get(r.__record__id__);
733
- if (c) {
734
- result.push(new Change(dataUnit, r, c, ChangeOperation.UPDATE));
735
- }
736
- }
737
- });
738
- const addedRecords = getAddedRecords(stateManager);
739
- if (addedRecords) {
740
- addedRecords.forEach(r => {
741
- result.push(new Change(dataUnit, r, changes === null || changes === void 0 ? void 0 : changes.get(r.__record__id__), ChangeOperation.INSERT));
742
- });
743
- }
744
- const removedRecords = getRemovedRecords(stateManager);
745
- const recordsById = {};
746
- records === null || records === void 0 ? void 0 : records.forEach(r => recordsById[r.__record__id__] = r);
747
- if (removedRecords) {
748
- removedRecords.forEach(id => {
749
- result.push(new Change(dataUnit, recordsById[id], undefined, ChangeOperation.DELETE));
750
- });
751
- }
752
- return result;
753
- };
754
-
755
- class CurrentRecordsReducerImpl {
756
- constructor() {
757
- this.sliceName = "currentRecords";
758
- }
759
- reduce(stateManager, _currentState, _action) {
760
- let records = getRecords(stateManager);
761
- const added = getAddedRecords(stateManager);
762
- if (!records && !added) {
763
- return undefined;
764
- }
765
- if (added) {
766
- records = (records || []).concat(added);
767
- }
768
- const removedRecords = getRemovedRecords(stateManager);
769
- if (removedRecords) {
770
- records = records.filter(r => !removedRecords.includes(r.__record__id__));
771
- }
772
- const changes = getChanges(stateManager);
773
- return new Map(records.map(r => {
774
- const recordId = r.__record__id__;
775
- const record = Object.assign(Object.assign({}, r), changes === null || changes === void 0 ? void 0 : changes.get(recordId));
776
- return [recordId, record];
777
- }));
778
- }
779
- }
780
- const CurrentRecordsReducer = new CurrentRecordsReducerImpl();
781
- const getCurrentRecords = (stateManager) => {
782
- return stateManager.select(CurrentRecordsReducer.sliceName, (state) => state);
783
- };
784
- const getFieldValue = (stateManager, fieldName) => {
785
- const selection = getSelection(stateManager);
786
- if (selection && selection.length > 0) {
787
- const currentRecords = getCurrentRecords(stateManager);
788
- if (currentRecords) {
789
- const record = currentRecords.get(selection[0]);
790
- return record ? record[fieldName] : undefined;
791
- }
792
- }
793
- return undefined;
794
- };
795
-
796
- class SelectionReducerImpl {
797
- constructor() {
798
- this.sliceName = "hist::selection";
799
- }
800
- reduce(stateManager, currentState, action) {
801
- switch (action.type) {
802
- case Action.RECORDS_ADDED:
803
- case Action.RECORDS_COPIED:
804
- return action.payload.map((r) => r.__record__id__);
805
- case Action.DATA_SAVED:
806
- return updateSavedIds(stateManager, action.payload.records);
807
- case Action.RECORDS_REMOVED:
808
- const removed = action.payload.records;
809
- if (currentState && removed) {
810
- return currentState.filter(recordId => !removed.includes(recordId));
811
- }
812
- return currentState;
813
- case Action.NEXT_SELECTED:
814
- case Action.PREVIOUS_SELECTED:
815
- const currentRecords = getCurrentRecords(stateManager);
816
- if (currentRecords && currentRecords.size > 0) {
817
- let index;
818
- if (!currentState || currentState.length === 0) {
819
- index = action.type === Action.PREVIOUS_SELECTED ? 0 : Math.min(1, currentRecords.size);
820
- }
821
- else {
822
- index = getItemIndex(currentState[0], currentRecords) + (action.type === Action.PREVIOUS_SELECTED ? -1 : 1);
823
- }
824
- if (index < currentRecords.size && index >= 0) {
825
- return [Array.from(currentRecords.values())[index].__record__id__];
826
- }
827
- }
828
- return undefined;
829
- case Action.SELECTION_CHANGED:
830
- const { type, selection: selectionSource } = action.payload;
831
- if (selectionSource && type === "index") {
832
- const currentRecords = getCurrentRecords(stateManager);
833
- if (currentRecords) {
834
- const records = Array.from(currentRecords.values());
835
- const selectionById = [];
836
- selectionSource.forEach((i) => {
837
- if (i > 0 && i < currentRecords.size) {
838
- selectionById.push(records[i].__record__id__);
839
- }
840
- });
841
- return selectionById;
842
- }
843
- }
844
- return selectionSource;
845
- }
846
- return currentState;
847
- }
848
- }
849
- const SelectionReducer = new SelectionReducerImpl();
850
- const getSelection = (stateManager) => {
851
- let selection = stateManager.select(SelectionReducer.sliceName, (state) => state);
852
- const currentRecords = Array.from((getCurrentRecords(stateManager) || new Map()).keys());
853
- if (selection) {
854
- selection = selection.filter(id => currentRecords.includes(id));
855
- }
856
- if (!selection || selection.length === 0) {
857
- if (currentRecords && currentRecords.length > 0) {
858
- return [currentRecords[0]];
859
- }
860
- }
861
- return selection;
862
- };
863
- const hasNext = (stateManager) => {
864
- const records = getCurrentRecords(stateManager);
865
- if (records) {
866
- const selection = stateManager.select(SelectionReducer.sliceName, (state) => state);
867
- if (!selection || selection.length === 0) {
868
- return records.size > 0;
869
- }
870
- return records.size > (getItemIndex(selection[0], records) + 1);
871
- }
872
- return false;
873
- };
874
- const hasPrevious = (stateManager) => {
875
- const records = getCurrentRecords(stateManager);
876
- if (records) {
877
- const selection = stateManager.select(SelectionReducer.sliceName, (state) => state);
878
- if (!selection || selection.length === 0) {
879
- return false;
880
- }
881
- return getItemIndex(selection[0], records) > 0;
882
- }
883
- return false;
884
- };
885
- function getItemIndex(key, map) {
886
- return Array.from(map.keys()).indexOf(key);
887
- }
888
- function updateSavedIds(stateManager, savedRecords) {
889
- const currentSelection = getSelection(stateManager);
890
- if (currentSelection) {
891
- const newSelection = [];
892
- currentSelection.forEach(id => {
893
- const record = savedRecords.find(r => r.__old__id__ === id);
894
- if (record) {
895
- newSelection.push(record.__record__id__);
896
- }
897
- else {
898
- newSelection.push(id);
899
- }
900
- });
901
- return newSelection;
902
- }
903
- return currentSelection;
904
- }
905
-
906
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
907
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
908
- return new (P || (P = Promise))(function (resolve, reject) {
909
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
910
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
911
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
912
- step((generator = generator.apply(thisArg, _arguments || [])).next());
913
- });
914
- };
915
- class DataUnit {
916
- constructor(name) {
917
- this._name = name;
918
- this._stateManager = new StateManager([
919
- HistReducer,
920
- UnitMetadataReducer,
921
- RecordsReducer,
922
- RemovedRecordsReducer,
923
- AddedRecordsReducer,
924
- SelectionReducer,
925
- ChangesReducer,
926
- CurrentRecordsReducer
927
- ]);
928
- this._observers = [];
929
- this._filterProviders = [];
930
- this._sortingProvider = undefined;
931
- this._interceptors = [];
932
- }
933
- get name() {
934
- return this._name;
935
- }
936
- // Métodos privados
937
- validateAndTypeValue(fieldName, newValue) {
938
- //FIXME: Validações devem ser feitas aqui
939
- const descriptor = this.getField(fieldName);
940
- return descriptor ? convertType(descriptor.dataType, newValue) : newValue;
941
- }
942
- getFilters() {
943
- let filters = undefined;
944
- this._filterProviders.forEach(p => {
945
- const f = p.getFilter(this.name);
946
- if (f) {
947
- filters = (filters || []).concat(f);
948
- }
949
- });
950
- return filters;
951
- }
952
- getSort() {
953
- return this._sortingProvider ? this._sortingProvider.getSort(this._name) : undefined;
954
- }
955
- // Loaders
956
- loadMetadata() {
957
- return __awaiter(this, void 0, void 0, function* () {
958
- this.dispatchAction(Action.LOADING_METADATA);
959
- return new Promise((resolve, fail) => {
960
- if (this.metadataLoader) {
961
- this.metadataLoader(this).then(metadata => {
962
- this.metadata = metadata;
963
- resolve(this.metadata);
964
- }).catch(error => fail(error));
965
- }
966
- });
967
- });
968
- }
969
- loadData() {
970
- return __awaiter(this, void 0, void 0, function* () {
971
- this.dispatchAction(Action.LOADING_DATA);
972
- return new Promise((resolve, fail) => {
973
- if (this.dataLoader) {
974
- const sort = this.getSort();
975
- const filters = this.getFilters();
976
- this.dataLoader(this, sort, filters).then(records => {
977
- this.records = records;
978
- resolve(this.records);
979
- }).catch(error => fail(error));
980
- }
981
- });
982
- });
983
- }
984
- saveData() {
985
- return __awaiter(this, void 0, void 0, function* () {
986
- const changes = getChangesToSave(this._name, this._stateManager);
987
- if (changes.length > 0) {
988
- this.dispatchAction(Action.SAVING_DATA);
989
- return new Promise((resolve, fail) => {
990
- if (this.saveLoader) {
991
- this.saveLoader(this, changes).then(records => this.dispatchAction(Action.DATA_SAVED, { changes, records })).catch(error => fail(error));
992
- }
993
- });
994
- }
995
- return Promise.resolve();
996
- });
997
- }
998
- removeSelectedRecords(buffered = false) {
999
- return __awaiter(this, void 0, void 0, function* () {
1000
- const selection = getSelection(this._stateManager);
1001
- if (selection) {
1002
- return this.removeRecords(selection, buffered);
1003
- }
1004
- return Promise.resolve(selection);
1005
- });
1006
- }
1007
- removeRecords(records, buffered = false) {
1008
- return __awaiter(this, void 0, void 0, function* () {
1009
- if (records) {
1010
- if (buffered || !this.removeLoader) {
1011
- this.dispatchAction(Action.RECORDS_REMOVED, { records, buffered: true });
1012
- }
1013
- else {
1014
- this.dispatchAction(Action.REMOVING_RECORDS);
1015
- return new Promise((resolve, fail) => {
1016
- if (this.removeLoader) {
1017
- this.removeLoader(this, records).then(records => {
1018
- this.dispatchAction(Action.RECORDS_REMOVED, { records, buffered: false });
1019
- resolve(records);
1020
- }).catch(error => fail(error));
1021
- }
1022
- });
1023
- }
1024
- }
1025
- return Promise.resolve(records);
1026
- });
1027
- }
1028
- // API
1029
- valueFromString(fieldName, value) {
1030
- const descriptor = this.getField(fieldName);
1031
- return descriptor ? convertType(descriptor.dataType, value) : value;
1032
- }
1033
- addInterceptor(interceptor) {
1034
- this._interceptors.push(interceptor);
1035
- }
1036
- addFilterProvider(provider) {
1037
- this._filterProviders.push(provider);
1038
- }
1039
- set sortingProvider(provider) {
1040
- this._sortingProvider = provider;
1041
- }
1042
- set metadata(md) {
1043
- this.dispatchAction(Action.METADATA_LOADED, md);
1044
- }
1045
- get metadata() {
1046
- return getMetadata(this._stateManager);
1047
- }
1048
- set records(r) {
1049
- this.dispatchAction(Action.DATA_LOADED, r);
1050
- }
1051
- get records() {
1052
- const records = getCurrentRecords(this._stateManager);
1053
- return records ? Array.from(records.values()) : [];
1054
- }
1055
- getField(fieldName) {
1056
- return getField(this._stateManager, fieldName);
1057
- }
1058
- addRecord() {
1059
- this.dispatchAction(Action.RECORDS_ADDED, prepareAddedRecordId(this._stateManager, [{}]));
1060
- }
1061
- copySelected() {
1062
- const selectedRecords = this.getSelectedRecords();
1063
- if (selectedRecords) {
1064
- this.dispatchAction(Action.RECORDS_COPIED, prepareAddedRecordId(this._stateManager, selectedRecords));
1065
- }
1066
- }
1067
- getFieldValue(fieldName) {
1068
- return getFieldValue(this._stateManager, fieldName);
1069
- }
1070
- setFieldValue(fieldName, newValue, records) {
1071
- const typedValue = this.validateAndTypeValue(fieldName, newValue);
1072
- const currentValue = this.getFieldValue(fieldName);
1073
- if (currentValue !== typedValue) {
1074
- this.dispatchAction(Action.DATA_CHANGED, { [fieldName]: typedValue, records });
1075
- }
1076
- }
1077
- getSelection() {
1078
- return getSelection(this._stateManager);
1079
- }
1080
- setSelection(selection) {
1081
- this.dispatchAction(Action.SELECTION_CHANGED, { type: "id", selection });
1082
- }
1083
- setSelectionByIndex(selection) {
1084
- this.dispatchAction(Action.SELECTION_CHANGED, { type: "index", selection });
1085
- }
1086
- getSelectedRecords() {
1087
- const selection = this.getSelection();
1088
- if (selection) {
1089
- const currentRecords = this.records;
1090
- return currentRecords === null || currentRecords === void 0 ? void 0 : currentRecords.filter(r => selection.includes(r.__record__id__));
1091
- }
1092
- }
1093
- nextRecord() {
1094
- this.dispatchAction(Action.NEXT_SELECTED);
1095
- }
1096
- previousRecord() {
1097
- this.dispatchAction(Action.PREVIOUS_SELECTED);
1098
- }
1099
- cancelEdition() {
1100
- this.dispatchAction(Action.EDITION_CANCELED);
1101
- }
1102
- isDirty() {
1103
- return isDirty(this._stateManager);
1104
- }
1105
- hasNext() {
1106
- return hasNext(this._stateManager);
1107
- }
1108
- hasPrevious() {
1109
- return hasPrevious(this._stateManager);
1110
- }
1111
- canUndo() {
1112
- return canUndo(this._stateManager);
1113
- }
1114
- canRedo() {
1115
- return canRedo(this._stateManager);
1116
- }
1117
- undo() {
1118
- this.dispatchAction(Action.CHANGE_UNDONE);
1119
- }
1120
- redo() {
1121
- this.dispatchAction(Action.CHANGE_REDONE);
1122
- }
1123
- toString() {
1124
- return this.name;
1125
- }
1126
- // Actions / State manager
1127
- dispatchAction(actionType, payload) {
1128
- var _a;
1129
- let action = new DataUnitAction(actionType, payload);
1130
- (_a = this._interceptors) === null || _a === void 0 ? void 0 : _a.forEach(interceptor => {
1131
- if (action) {
1132
- action = interceptor.interceptAction(action);
1133
- }
1134
- });
1135
- if (action) {
1136
- this._stateManager.process(action);
1137
- this._observers.forEach(f => f(action));
1138
- }
1139
- }
1140
- subscribe(observer) {
1141
- this._observers.push(observer);
1142
- }
1143
- unsubscribe(observer) {
1144
- this._observers = this._observers.filter(f => f !== observer);
1145
- }
1146
- }
1147
- var ChangeOperation;
1148
- (function (ChangeOperation) {
1149
- ChangeOperation["INSERT"] = "INSERT";
1150
- ChangeOperation["UPDATE"] = "UPDATE";
1151
- ChangeOperation["DELETE"] = "DELETE";
1152
- })(ChangeOperation || (ChangeOperation = {}));
1153
- class Change {
1154
- constructor(dataUnit, record, updates, operation) {
1155
- this.dataUnit = dataUnit;
1156
- this.record = record;
1157
- this.updatingFields = updates;
1158
- this._operation = operation;
1159
- }
1160
- get operation() {
1161
- return this._operation.toString();
1162
- }
1163
- isInsert() {
1164
- return this._operation === ChangeOperation.INSERT;
1165
- }
1166
- isDelete() {
1167
- return this._operation === ChangeOperation.DELETE;
1168
- }
1169
- isUpdate() {
1170
- return this._operation === ChangeOperation.UPDATE;
1171
- }
1172
- }
1173
-
1174
- var SortMode;
1175
- (function (SortMode) {
1176
- SortMode["ASC"] = "ASC";
1177
- SortMode["DESC"] = "DESC";
1178
- })(SortMode || (SortMode = {}));
1179
- var DependencyType;
1180
- (function (DependencyType) {
1181
- DependencyType["SEARCHING"] = "SEARCHING";
1182
- DependencyType["REQUIREMENT"] = "REQUIREMENT";
1183
- DependencyType["VISIBILITY"] = "REQUIREMENT";
1184
- })(DependencyType || (DependencyType = {}));
1185
- var UserInterface;
1186
- (function (UserInterface) {
1187
- UserInterface["FILE"] = "FILE";
1188
- UserInterface["IMAGE"] = "IMAGE";
1189
- UserInterface["DATE"] = "DATE";
1190
- UserInterface["DATETIME"] = "DATETIME";
1191
- UserInterface["TIME"] = "TIME";
1192
- UserInterface["ELAPSEDTIME"] = "ELAPSEDTIME";
1193
- UserInterface["CHECKBOX"] = "CHECKBOX";
1194
- UserInterface["SWITCH"] = "SWITCH";
1195
- UserInterface["OPTIONSELECTOR"] = "OPTIONSELECTOR";
1196
- UserInterface["DECIMALNUMBER"] = "DECIMALNUMBER";
1197
- UserInterface["INTEGERNUMBER"] = "INTEGERNUMBER";
1198
- UserInterface["SEARCH"] = "SEARCH";
1199
- UserInterface["SHORTTEXT"] = "SHORTTEXT";
1200
- UserInterface["PASSWORD"] = "PASSWORD";
1201
- UserInterface["MASKEDTEXT"] = "MASKEDTEXT";
1202
- UserInterface["LONGTEXT"] = "LONGTEXT";
1203
- UserInterface["HTML"] = "HTML";
1204
- })(UserInterface || (UserInterface = {}));
1205
-
1206
- class ApplicationContext {
1207
- static getContextValue(key) {
1208
- return ApplicationContext.getCtx()[key];
1209
- }
1210
- static setContextValue(key, value) {
1211
- ApplicationContext.getCtx()[key] = value;
1212
- }
1213
- static getCtx() {
1214
- let ctx = window.___snkcore___ctx___;
1215
- if (!ctx) {
1216
- ctx = {};
1217
- window.___snkcore___ctx___ = ctx;
1218
- }
1219
- return ctx;
1220
- }
1221
- }
5
+ const index = require('./index-4720dab8.js');
6
+ const core = require('@sankhyalabs/core');
1222
7
 
1223
8
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
1224
9
 
@@ -6884,6 +5669,280 @@ exports.ClientError = ClientError;
6884
5669
  //# sourceMappingURL=types.js.map
6885
5670
  });
6886
5671
 
5672
+ var graphqlWs = createCommonjsModule(function (module, exports) {
5673
+ var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
5674
+ __assign = Object.assign || function(t) {
5675
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5676
+ s = arguments[i];
5677
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
5678
+ t[p] = s[p];
5679
+ }
5680
+ return t;
5681
+ };
5682
+ return __assign.apply(this, arguments);
5683
+ };
5684
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
5685
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5686
+ return new (P || (P = Promise))(function (resolve, reject) {
5687
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5688
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
5689
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
5690
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
5691
+ });
5692
+ };
5693
+ var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
5694
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
5695
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
5696
+ function verb(n) { return function (v) { return step([n, v]); }; }
5697
+ function step(op) {
5698
+ if (f) throw new TypeError("Generator is already executing.");
5699
+ while (_) try {
5700
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
5701
+ if (y = 0, t) op = [op[0] & 2, t.value];
5702
+ switch (op[0]) {
5703
+ case 0: case 1: t = op; break;
5704
+ case 4: _.label++; return { value: op[1], done: false };
5705
+ case 5: _.label++; y = op[1]; op = [0]; continue;
5706
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
5707
+ default:
5708
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
5709
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
5710
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
5711
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
5712
+ if (t[2]) _.ops.pop();
5713
+ _.trys.pop(); continue;
5714
+ }
5715
+ op = body.call(thisArg, _);
5716
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
5717
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
5718
+ }
5719
+ };
5720
+ Object.defineProperty(exports, "__esModule", { value: true });
5721
+ exports.GraphQLWebSocketClient = void 0;
5722
+
5723
+
5724
+ var CONNECTION_INIT = 'connection_init';
5725
+ var CONNECTION_ACK = 'connection_ack';
5726
+ var PING = 'ping';
5727
+ var PONG = 'pong';
5728
+ var SUBSCRIBE = 'subscribe';
5729
+ var NEXT = 'next';
5730
+ var ERROR = 'error';
5731
+ var COMPLETE = 'complete';
5732
+ var GraphQLWebSocketMessage = /** @class */ (function () {
5733
+ function GraphQLWebSocketMessage(type, payload, id) {
5734
+ this._type = type;
5735
+ this._payload = payload;
5736
+ this._id = id;
5737
+ }
5738
+ Object.defineProperty(GraphQLWebSocketMessage.prototype, "type", {
5739
+ get: function () { return this._type; },
5740
+ enumerable: false,
5741
+ configurable: true
5742
+ });
5743
+ Object.defineProperty(GraphQLWebSocketMessage.prototype, "id", {
5744
+ get: function () { return this._id; },
5745
+ enumerable: false,
5746
+ configurable: true
5747
+ });
5748
+ Object.defineProperty(GraphQLWebSocketMessage.prototype, "payload", {
5749
+ get: function () { return this._payload; },
5750
+ enumerable: false,
5751
+ configurable: true
5752
+ });
5753
+ Object.defineProperty(GraphQLWebSocketMessage.prototype, "text", {
5754
+ get: function () {
5755
+ var result = { type: this.type };
5756
+ if (this.id != null && this.id != undefined)
5757
+ result.id = this.id;
5758
+ if (this.payload != null && this.payload != undefined)
5759
+ result.payload = this.payload;
5760
+ return JSON.stringify(result);
5761
+ },
5762
+ enumerable: false,
5763
+ configurable: true
5764
+ });
5765
+ GraphQLWebSocketMessage.parse = function (data, f) {
5766
+ var _a = JSON.parse(data), type = _a.type, payload = _a.payload, id = _a.id;
5767
+ return new GraphQLWebSocketMessage(type, f(payload), id);
5768
+ };
5769
+ return GraphQLWebSocketMessage;
5770
+ }());
5771
+ var GraphQLWebSocketClient = /** @class */ (function () {
5772
+ function GraphQLWebSocketClient(socket, _a) {
5773
+ var _this = this;
5774
+ var onInit = _a.onInit, onAcknowledged = _a.onAcknowledged, onPing = _a.onPing, onPong = _a.onPong;
5775
+ this.socketState = { acknowledged: false, lastRequestId: 0, subscriptions: {} };
5776
+ this.socket = socket;
5777
+ socket.onopen = function (e) { return __awaiter(_this, void 0, void 0, function () {
5778
+ var _a, _b, _c, _d;
5779
+ return __generator(this, function (_e) {
5780
+ switch (_e.label) {
5781
+ case 0:
5782
+ this.socketState.acknowledged = false;
5783
+ this.socketState.subscriptions = {};
5784
+ _b = (_a = socket).send;
5785
+ _c = ConnectionInit;
5786
+ if (!onInit) return [3 /*break*/, 2];
5787
+ return [4 /*yield*/, onInit()];
5788
+ case 1:
5789
+ _d = _e.sent();
5790
+ return [3 /*break*/, 3];
5791
+ case 2:
5792
+ _d = null;
5793
+ _e.label = 3;
5794
+ case 3:
5795
+ _b.apply(_a, [_c.apply(void 0, [_d]).text]);
5796
+ return [2 /*return*/];
5797
+ }
5798
+ });
5799
+ }); };
5800
+ socket.onclose = function (e) {
5801
+ _this.socketState.acknowledged = false;
5802
+ _this.socketState.subscriptions = {};
5803
+ };
5804
+ socket.onerror = function (e) {
5805
+ console.error(e);
5806
+ };
5807
+ socket.onmessage = function (e) {
5808
+ try {
5809
+ var message = parseMessage(e.data);
5810
+ switch (message.type) {
5811
+ case CONNECTION_ACK: {
5812
+ if (_this.socketState.acknowledged) {
5813
+ console.warn("Duplicate CONNECTION_ACK message ignored");
5814
+ }
5815
+ else {
5816
+ _this.socketState.acknowledged = true;
5817
+ if (onAcknowledged)
5818
+ onAcknowledged(message.payload);
5819
+ }
5820
+ return;
5821
+ }
5822
+ case PING: {
5823
+ if (onPing)
5824
+ onPing(message.payload).then(function (r) { return socket.send(Pong(r).text); });
5825
+ else
5826
+ socket.send(Pong(null).text);
5827
+ return;
5828
+ }
5829
+ case PONG: {
5830
+ if (onPong)
5831
+ onPong(message.payload);
5832
+ return;
5833
+ }
5834
+ }
5835
+ if (!_this.socketState.acknowledged) {
5836
+ // Web-socket connection not acknowledged
5837
+ return;
5838
+ }
5839
+ if (message.id === undefined || message.id === null || !_this.socketState.subscriptions[message.id]) {
5840
+ // No subscription identifer or subscription indentifier is not found
5841
+ return;
5842
+ }
5843
+ var _a = _this.socketState.subscriptions[message.id], query = _a.query, variables = _a.variables, subscriber = _a.subscriber;
5844
+ switch (message.type) {
5845
+ case NEXT: {
5846
+ if (!message.payload.errors && message.payload.data) {
5847
+ subscriber.next && subscriber.next(message.payload.data);
5848
+ }
5849
+ if (message.payload.errors) {
5850
+ subscriber.error && subscriber.error(new types.ClientError(__assign(__assign({}, message.payload), { status: 200 }), { query: query, variables: variables }));
5851
+ }
5852
+ return;
5853
+ }
5854
+ case ERROR: {
5855
+ subscriber.error && subscriber.error(new types.ClientError({ errors: message.payload, status: 200 }, { query: query, variables: variables }));
5856
+ return;
5857
+ }
5858
+ case COMPLETE: {
5859
+ subscriber.complete && subscriber.complete();
5860
+ delete _this.socketState.subscriptions[message.id];
5861
+ return;
5862
+ }
5863
+ }
5864
+ }
5865
+ catch (e) {
5866
+ // Unexpected errors while handling graphql-ws message
5867
+ console.error(e);
5868
+ socket.close(1006);
5869
+ }
5870
+ socket.close(4400, "Unknown graphql-ws message.");
5871
+ };
5872
+ }
5873
+ GraphQLWebSocketClient.prototype.makeSubscribe = function (query, operationName, variables, subscriber) {
5874
+ var _this = this;
5875
+ var subscriptionId = (this.socketState.lastRequestId++).toString();
5876
+ this.socketState.subscriptions[subscriptionId] = { query: query, variables: variables, subscriber: subscriber };
5877
+ this.socket.send(Subscribe(subscriptionId, { query: query, operationName: operationName, variables: variables }).text);
5878
+ return function () {
5879
+ _this.socket.send(Complete(subscriptionId).text);
5880
+ delete _this.socketState.subscriptions[subscriptionId];
5881
+ };
5882
+ };
5883
+ GraphQLWebSocketClient.prototype.rawRequest = function (query, variables) {
5884
+ var _this = this;
5885
+ return new Promise(function (resolve, reject) {
5886
+ var result;
5887
+ _this.rawSubscribe(query, {
5888
+ next: function (data, extensions) { return (result = { data: data, extensions: extensions }); },
5889
+ error: reject,
5890
+ complete: function () { return resolve(result); },
5891
+ }, variables);
5892
+ });
5893
+ };
5894
+ GraphQLWebSocketClient.prototype.request = function (document, variables) {
5895
+ var _this = this;
5896
+ return new Promise(function (resolve, reject) {
5897
+ var result;
5898
+ _this.subscribe(document, {
5899
+ next: function (data) { return (result = data); },
5900
+ error: reject,
5901
+ complete: function () { return resolve(result); },
5902
+ }, variables);
5903
+ });
5904
+ };
5905
+ GraphQLWebSocketClient.prototype.subscribe = function (document, subscriber, variables) {
5906
+ var _a = dist.resolveRequestDocument(document), query = _a.query, operationName = _a.operationName;
5907
+ return this.makeSubscribe(query, operationName, variables, subscriber);
5908
+ };
5909
+ GraphQLWebSocketClient.prototype.rawSubscribe = function (query, subscriber, variables) {
5910
+ return this.makeSubscribe(query, undefined, variables, subscriber);
5911
+ };
5912
+ GraphQLWebSocketClient.prototype.ping = function (payload) {
5913
+ this.socket.send(Ping(payload).text);
5914
+ };
5915
+ GraphQLWebSocketClient.prototype.close = function () {
5916
+ this.socket.close(1000);
5917
+ };
5918
+ GraphQLWebSocketClient.PROTOCOL = "graphql-transport-ws";
5919
+ return GraphQLWebSocketClient;
5920
+ }());
5921
+ exports.GraphQLWebSocketClient = GraphQLWebSocketClient;
5922
+ // Helper functions
5923
+ function parseMessage(data, f) {
5924
+ if (f === void 0) { f = function (a) { return a; }; }
5925
+ var m = GraphQLWebSocketMessage.parse(data, f);
5926
+ return m;
5927
+ }
5928
+ function ConnectionInit(payload) {
5929
+ return new GraphQLWebSocketMessage(CONNECTION_INIT, payload);
5930
+ }
5931
+ function Ping(payload) {
5932
+ return new GraphQLWebSocketMessage(PING, payload, undefined);
5933
+ }
5934
+ function Pong(payload) {
5935
+ return new GraphQLWebSocketMessage(PONG, payload, undefined);
5936
+ }
5937
+ function Subscribe(id, payload) {
5938
+ return new GraphQLWebSocketMessage(SUBSCRIBE, payload, id);
5939
+ }
5940
+ function Complete(id) {
5941
+ return new GraphQLWebSocketMessage(COMPLETE, undefined, id);
5942
+ }
5943
+ //# sourceMappingURL=graphql-ws.js.map
5944
+ });
5945
+
6887
5946
  var dist = createCommonjsModule(function (module, exports) {
6888
5947
  var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
6889
5948
  __assign = Object.assign || function(t) {
@@ -6966,7 +6025,7 @@ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || func
6966
6025
  return (mod && mod.__esModule) ? mod : { "default": mod };
6967
6026
  };
6968
6027
  Object.defineProperty(exports, "__esModule", { value: true });
6969
- exports.gql = exports.batchRequests = exports.request = exports.rawRequest = exports.GraphQLClient = exports.ClientError = void 0;
6028
+ exports.GraphQLWebSocketClient = exports.gql = exports.resolveRequestDocument = exports.batchRequests = exports.request = exports.rawRequest = exports.GraphQLClient = exports.ClientError = void 0;
6970
6029
  var cross_fetch_1 = __importStar(browserPonyfill), CrossFetch = cross_fetch_1;
6971
6030
 
6972
6031
 
@@ -7100,7 +6159,7 @@ var GraphQLClient = /** @class */ (function () {
7100
6159
  url: url,
7101
6160
  query: rawRequestOptions.query,
7102
6161
  variables: rawRequestOptions.variables,
7103
- headers: __assign(__assign({}, resolveHeaders(headers)), resolveHeaders(rawRequestOptions.requestHeaders)),
6162
+ headers: __assign(__assign({}, resolveHeaders(callOrIdentity(headers))), resolveHeaders(rawRequestOptions.requestHeaders)),
7104
6163
  operationName: operationName,
7105
6164
  fetch: fetch,
7106
6165
  method: method,
@@ -7126,7 +6185,7 @@ var GraphQLClient = /** @class */ (function () {
7126
6185
  url: url,
7127
6186
  query: query,
7128
6187
  variables: requestOptions.variables,
7129
- headers: __assign(__assign({}, resolveHeaders(headers)), resolveHeaders(requestOptions.requestHeaders)),
6188
+ headers: __assign(__assign({}, resolveHeaders(callOrIdentity(headers))), resolveHeaders(requestOptions.requestHeaders)),
7130
6189
  operationName: operationName,
7131
6190
  fetch: fetch,
7132
6191
  method: method,
@@ -7163,7 +6222,7 @@ var GraphQLClient = /** @class */ (function () {
7163
6222
  url: url,
7164
6223
  query: queries,
7165
6224
  variables: variables,
7166
- headers: __assign(__assign({}, resolveHeaders(headers)), resolveHeaders(batchRequestOptions.requestHeaders)),
6225
+ headers: __assign(__assign({}, resolveHeaders(callOrIdentity(headers))), resolveHeaders(batchRequestOptions.requestHeaders)),
7167
6226
  operationName: undefined,
7168
6227
  fetch: fetch,
7169
6228
  method: method,
@@ -7209,7 +6268,7 @@ exports.GraphQLClient = GraphQLClient;
7209
6268
  function makeRequest(_a) {
7210
6269
  var url = _a.url, query = _a.query, variables = _a.variables, headers = _a.headers, operationName = _a.operationName, fetch = _a.fetch, _b = _a.method, method = _b === void 0 ? 'POST' : _b, fetchOptions = _a.fetchOptions;
7211
6270
  return __awaiter(this, void 0, void 0, function () {
7212
- var fetcher, isBathchingQuery, response, result, successfullyReceivedData, headers_1, status_1, errorResult;
6271
+ var fetcher, isBathchingQuery, response, result, successfullyReceivedData, successfullyPassedErrorPolicy, headers_1, status_1, rest, data, errorResult;
7213
6272
  return __generator(this, function (_c) {
7214
6273
  switch (_c.label) {
7215
6274
  case 0:
@@ -7233,9 +6292,12 @@ function makeRequest(_a) {
7233
6292
  var data = _a.data;
7234
6293
  return !data;
7235
6294
  }) : !!result.data;
7236
- if (response.ok && !result.errors && successfullyReceivedData) {
6295
+ successfullyPassedErrorPolicy = !result.errors || fetchOptions.errorPolicy === 'all' || fetchOptions.errorPolicy === 'ignore';
6296
+ if (response.ok && successfullyPassedErrorPolicy && successfullyReceivedData) {
7237
6297
  headers_1 = response.headers, status_1 = response.status;
7238
- return [2 /*return*/, __assign(__assign({}, (isBathchingQuery ? { data: result } : result)), { headers: headers_1, status: status_1 })];
6298
+ rest = __rest(result, ["errors"]);
6299
+ data = fetchOptions.errorPolicy === 'ignore' ? rest : result;
6300
+ return [2 /*return*/, __assign(__assign({}, (isBathchingQuery ? { data: data } : data)), { headers: headers_1, status: status_1 })];
7239
6301
  }
7240
6302
  else {
7241
6303
  errorResult = typeof result === 'string' ? { error: result } : result;
@@ -7330,6 +6392,10 @@ function resolveRequestDocument(document) {
7330
6392
  var operationName = extractOperationName(document);
7331
6393
  return { query: printer.print(document), operationName: operationName };
7332
6394
  }
6395
+ exports.resolveRequestDocument = resolveRequestDocument;
6396
+ function callOrIdentity(value) {
6397
+ return typeof value === 'function' ? value() : value;
6398
+ }
7333
6399
  /**
7334
6400
  * Convenience passthrough template tag to get the benefits of tooling for the gql template tag. This does not actually parse the input into a GraphQL DocumentNode like graphql-tag package does. It just returns the string with any variables given interpolated. Can save you a bit of performance and having to install another package.
7335
6401
  *
@@ -7361,6 +6427,8 @@ function HeadersInstanceToPlainObject(headers) {
7361
6427
  });
7362
6428
  return o;
7363
6429
  }
6430
+
6431
+ Object.defineProperty(exports, "GraphQLWebSocketClient", { enumerable: true, get: function () { return graphqlWs.GraphQLWebSocketClient; } });
7364
6432
  //# sourceMappingURL=index.js.map
7365
6433
  });
7366
6434
 
@@ -7580,7 +6648,7 @@ class DataUnitFetcher {
7580
6648
  }`);
7581
6649
  }
7582
6650
  getDataUnit(entityName, resourceID) {
7583
- const dataUnit = new DataUnit(`dd://${entityName}/${resourceID}`);
6651
+ const dataUnit = new core.DataUnit(`dd://${entityName}/${resourceID}`);
7584
6652
  dataUnit.metadataLoader = (dataUnit) => this.loadMetadata(dataUnit);
7585
6653
  dataUnit.dataLoader = (dataUnit, sort, filters) => this.loadData(dataUnit, sort, filters);
7586
6654
  dataUnit.saveLoader = (dataUnit, changes) => this.saveData(dataUnit, changes);
@@ -7690,7 +6758,7 @@ class DataUnitFetcher {
7690
6758
  }
7691
6759
  removeRecords(dataUnit, recordIds) {
7692
6760
  const changes = recordIds.map((recordId) => {
7693
- return { dataUnit: dataUnit.name, operation: ChangeOperation.DELETE, recordId };
6761
+ return { dataUnit: dataUnit.name, operation: core.ChangeOperation.DELETE, recordId };
7694
6762
  });
7695
6763
  return new Promise((resolve, reject) => {
7696
6764
  HttpFetcher.get()
@@ -7778,7 +6846,7 @@ class ParametersFetcher {
7778
6846
  }
7779
6847
  async asDate(name, resourceID) {
7780
6848
  const paramArr = await this.getParam(name, resourceID);
7781
- return DateUtils.strToDate(this.getValue(paramArr));
6849
+ return core.DateUtils.strToDate(this.getValue(paramArr));
7782
6850
  }
7783
6851
  async getBatchParams(names, resourceID) {
7784
6852
  const paramArr = await this.getParam(names.join(","), resourceID);
@@ -7791,7 +6859,7 @@ class ParametersFetcher {
7791
6859
  if (Array.isArray(obj) && obj.length > 0) {
7792
6860
  obj = obj[0];
7793
6861
  }
7794
- if (StringUtils.isEmpty(obj.resource))
6862
+ if (core.StringUtils.isEmpty(obj.resource))
7795
6863
  return "";
7796
6864
  return obj.resource;
7797
6865
  }
@@ -7817,17 +6885,21 @@ class ApplicationUtils {
7817
6885
  static async confirm(title, message, icon = null, critical = false) {
7818
6886
  return ApplicationUtils.showDialog(title, message, icon, true, critical);
7819
6887
  }
7820
- static async info(message) {
6888
+ static async info(message, options = ApplicationUtils.defaultMessageOptions) {
7821
6889
  let toast = document.querySelector("ez-toast");
7822
6890
  if (!toast) {
7823
6891
  toast = document.createElement("ez-toast");
7824
6892
  window.document.body.appendChild(toast);
7825
6893
  }
6894
+ toast.canClose = options.canClose;
7826
6895
  toast.message = message;
7827
6896
  toast.fadeTime = 4000;
7828
6897
  toast.show();
7829
6898
  }
7830
- }
6899
+ }
6900
+ ApplicationUtils.defaultMessageOptions = {
6901
+ canClose: true
6902
+ };
7831
6903
 
7832
6904
  class ResourceFetcher {
7833
6905
  constructor() {
@@ -7986,8 +7058,8 @@ const SnkApplication = class {
7986
7058
  async confirm(title, message, icon, critical) {
7987
7059
  return ApplicationUtils.confirm(title, message, icon, critical);
7988
7060
  }
7989
- async info(message) {
7990
- return ApplicationUtils.info(message);
7061
+ async info(message, options = undefined) {
7062
+ return ApplicationUtils.info(message, options);
7991
7063
  }
7992
7064
  async loadFormConfig(name) {
7993
7065
  return this.formConfigFetcher.loadFormConfig(name, this.resourceID);
@@ -8011,7 +7083,7 @@ const SnkApplication = class {
8011
7083
  return this._formConfigFetcher;
8012
7084
  }
8013
7085
  componentWillLoad() {
8014
- ApplicationContext.setContextValue("__EZUI__SEARCH__OPTION__LOADER__", pesquisaLoadOptions);
7086
+ core.ApplicationContext.setContextValue("__EZUI__SEARCH__OPTION__LOADER__", pesquisaLoadOptions);
8015
7087
  }
8016
7088
  componentDidLoad() {
8017
7089
  this.applicationLoading.emit(true);