@bigbinary/neeto-webhooks-frontend 1.5.9 → 1.6.1

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,2962 +1,176 @@
1
- import React, { createElement, isValidElement, cloneElement, createContext, useContext, useState, useRef, useEffect, useCallback } from 'react';
2
- import { useParams, Link, useRouteMatch, Switch, Route } from 'react-router-dom';
3
- import classNames from 'classnames';
4
- import { removeBy, removeById } from '@bigbinary/neeto-commons-frontend/pure';
5
- import { dateFormat, buildUrl } from '@bigbinary/neeto-commons-frontend/utils';
6
- import { Close, Check, Info, MenuHorizontal } from '@bigbinary/neeto-icons';
1
+ import React, { useState, useRef, useCallback } from 'react';
2
+ import { useParams, useRouteMatch, Switch as Switch$1, Route } from 'react-router-dom';
3
+ import { isPresent, removeBy, isNotEmpty, removeById, findBy } from '@bigbinary/neeto-cist';
4
+ import Container from '@bigbinary/neeto-molecules/Container';
7
5
  import Header$2 from '@bigbinary/neeto-molecules/Header';
8
6
  import PageLoader from '@bigbinary/neeto-molecules/PageLoader';
9
- import { Spinner, Tab, Button, Typography, Accordion, Tag, NoData, Pane, Dropdown, Alert } from '@bigbinary/neetoui';
10
- import { isEmpty, pluck } from 'ramda';
7
+ import TableWrapper from '@bigbinary/neeto-molecules/TableWrapper';
8
+ import { Spinner, Typography, Tag, Tab, Pane, Button, Table, NoData, Dropdown, Alert } from '@bigbinary/neetoui';
9
+ import { useTranslation, Trans } from 'react-i18next';
11
10
  import { QueryClient, QueryCache, QueryClientProvider, useQuery, useQueryClient, useMutation } from 'react-query';
12
11
  import { ReactQueryDevtools } from 'react-query/devtools';
12
+ import { DEFAULT_STALE_TIME, SINGULAR, PLURAL } from '@bigbinary/neeto-commons-frontend/constants';
13
13
  import axios from 'axios';
14
- import { Form, Input, ActionBlock } from '@bigbinary/neetoui/formik';
14
+ import DateFormat from '@bigbinary/neeto-molecules/DateFormat';
15
+ import { t as t$1 } from 'i18next';
16
+ import { prop, pluck, assoc } from 'ramda';
17
+ import { MenuHorizontal, Info } from '@bigbinary/neeto-icons';
18
+ import { Form, Input, Select, Switch, ActionBlock } from '@bigbinary/neetoui/formik';
19
+ import { buildUrl } from '@bigbinary/neeto-commons-frontend/utils';
15
20
  import * as yup from 'yup';
16
21
 
17
- const consoleLogger = {
18
- type: 'logger',
19
- log(args) {
20
- this.output('log', args);
21
- },
22
- warn(args) {
23
- this.output('warn', args);
24
- },
25
- error(args) {
26
- this.output('error', args);
27
- },
28
- output(type, args) {
29
- if (console && console[type]) console[type].apply(console, args);
30
- }
31
- };
32
- class Logger {
33
- constructor(concreteLogger) {
34
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
35
- this.init(concreteLogger, options);
36
- }
37
- init(concreteLogger) {
38
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
39
- this.prefix = options.prefix || 'i18next:';
40
- this.logger = concreteLogger || consoleLogger;
41
- this.options = options;
42
- this.debug = options.debug;
43
- }
44
- log() {
45
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
46
- args[_key] = arguments[_key];
47
- }
48
- return this.forward(args, 'log', '', true);
49
- }
50
- warn() {
51
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
52
- args[_key2] = arguments[_key2];
53
- }
54
- return this.forward(args, 'warn', '', true);
55
- }
56
- error() {
57
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
58
- args[_key3] = arguments[_key3];
59
- }
60
- return this.forward(args, 'error', '');
61
- }
62
- deprecate() {
63
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
64
- args[_key4] = arguments[_key4];
65
- }
66
- return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
67
- }
68
- forward(args, lvl, prefix, debugOnly) {
69
- if (debugOnly && !this.debug) return null;
70
- if (typeof args[0] === 'string') args[0] = `${prefix}${this.prefix} ${args[0]}`;
71
- return this.logger[lvl](args);
72
- }
73
- create(moduleName) {
74
- return new Logger(this.logger, {
75
- ...{
76
- prefix: `${this.prefix}:${moduleName}:`
77
- },
78
- ...this.options
79
- });
80
- }
81
- clone(options) {
82
- options = options || this.options;
83
- options.prefix = options.prefix || this.prefix;
84
- return new Logger(this.logger, options);
85
- }
86
- }
87
- var baseLogger = new Logger();
88
-
89
- class EventEmitter {
90
- constructor() {
91
- this.observers = {};
92
- }
93
- on(events, listener) {
94
- events.split(' ').forEach(event => {
95
- this.observers[event] = this.observers[event] || [];
96
- this.observers[event].push(listener);
97
- });
98
- return this;
99
- }
100
- off(event, listener) {
101
- if (!this.observers[event]) return;
102
- if (!listener) {
103
- delete this.observers[event];
104
- return;
105
- }
106
- this.observers[event] = this.observers[event].filter(l => l !== listener);
107
- }
108
- emit(event) {
109
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
110
- args[_key - 1] = arguments[_key];
111
- }
112
- if (this.observers[event]) {
113
- const cloned = [].concat(this.observers[event]);
114
- cloned.forEach(observer => {
115
- observer(...args);
116
- });
117
- }
118
- if (this.observers['*']) {
119
- const cloned = [].concat(this.observers['*']);
120
- cloned.forEach(observer => {
121
- observer.apply(observer, [event, ...args]);
122
- });
123
- }
124
- }
125
- }
126
-
127
- function defer() {
128
- let res;
129
- let rej;
130
- const promise = new Promise((resolve, reject) => {
131
- res = resolve;
132
- rej = reject;
133
- });
134
- promise.resolve = res;
135
- promise.reject = rej;
136
- return promise;
137
- }
138
- function makeString(object) {
139
- if (object == null) return '';
140
- return '' + object;
141
- }
142
- function copy(a, s, t) {
143
- a.forEach(m => {
144
- if (s[m]) t[m] = s[m];
145
- });
146
- }
147
- function getLastOfPath(object, path, Empty) {
148
- function cleanKey(key) {
149
- return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
150
- }
151
- function canNotTraverseDeeper() {
152
- return !object || typeof object === 'string';
153
- }
154
- const stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
155
- while (stack.length > 1) {
156
- if (canNotTraverseDeeper()) return {};
157
- const key = cleanKey(stack.shift());
158
- if (!object[key] && Empty) object[key] = new Empty();
159
- if (Object.prototype.hasOwnProperty.call(object, key)) {
160
- object = object[key];
161
- } else {
162
- object = {};
163
- }
164
- }
165
- if (canNotTraverseDeeper()) return {};
166
- return {
167
- obj: object,
168
- k: cleanKey(stack.shift())
169
- };
170
- }
171
- function setPath(object, path, newValue) {
172
- const {
173
- obj,
174
- k
175
- } = getLastOfPath(object, path, Object);
176
- obj[k] = newValue;
177
- }
178
- function pushPath(object, path, newValue, concat) {
179
- const {
180
- obj,
181
- k
182
- } = getLastOfPath(object, path, Object);
183
- obj[k] = obj[k] || [];
184
- if (concat) obj[k] = obj[k].concat(newValue);
185
- if (!concat) obj[k].push(newValue);
186
- }
187
- function getPath(object, path) {
188
- const {
189
- obj,
190
- k
191
- } = getLastOfPath(object, path);
192
- if (!obj) return undefined;
193
- return obj[k];
194
- }
195
- function getPathWithDefaults(data, defaultData, key) {
196
- const value = getPath(data, key);
197
- if (value !== undefined) {
198
- return value;
199
- }
200
- return getPath(defaultData, key);
201
- }
202
- function deepExtend(target, source, overwrite) {
203
- for (const prop in source) {
204
- if (prop !== '__proto__' && prop !== 'constructor') {
205
- if (prop in target) {
206
- if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
207
- if (overwrite) target[prop] = source[prop];
208
- } else {
209
- deepExtend(target[prop], source[prop], overwrite);
210
- }
211
- } else {
212
- target[prop] = source[prop];
213
- }
214
- }
215
- }
216
- return target;
217
- }
218
- function regexEscape(str) {
219
- return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
220
- }
221
- var _entityMap = {
222
- '&': '&amp;',
223
- '<': '&lt;',
224
- '>': '&gt;',
225
- '"': '&quot;',
226
- "'": '&#39;',
227
- '/': '&#x2F;'
228
- };
229
- function escape(data) {
230
- if (typeof data === 'string') {
231
- return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
232
- }
233
- return data;
234
- }
235
- const chars = [' ', ',', '?', '!', ';'];
236
- function looksLikeObjectPath(key, nsSeparator, keySeparator) {
237
- nsSeparator = nsSeparator || '';
238
- keySeparator = keySeparator || '';
239
- const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
240
- if (possibleChars.length === 0) return true;
241
- const r = new RegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
242
- let matched = !r.test(key);
243
- if (!matched) {
244
- const ki = key.indexOf(keySeparator);
245
- if (ki > 0 && !r.test(key.substring(0, ki))) {
246
- matched = true;
247
- }
248
- }
249
- return matched;
250
- }
251
- function deepFind(obj, path) {
252
- let keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
253
- if (!obj) return undefined;
254
- if (obj[path]) return obj[path];
255
- const paths = path.split(keySeparator);
256
- let current = obj;
257
- for (let i = 0; i < paths.length; ++i) {
258
- if (!current) return undefined;
259
- if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {
260
- return undefined;
261
- }
262
- if (current[paths[i]] === undefined) {
263
- let j = 2;
264
- let p = paths.slice(i, i + j).join(keySeparator);
265
- let mix = current[p];
266
- while (mix === undefined && paths.length > i + j) {
267
- j++;
268
- p = paths.slice(i, i + j).join(keySeparator);
269
- mix = current[p];
270
- }
271
- if (mix === undefined) return undefined;
272
- if (mix === null) return null;
273
- if (path.endsWith(p)) {
274
- if (typeof mix === 'string') return mix;
275
- if (p && typeof mix[p] === 'string') return mix[p];
276
- }
277
- const joinedPath = paths.slice(i + j).join(keySeparator);
278
- if (joinedPath) return deepFind(mix, joinedPath, keySeparator);
279
- return undefined;
280
- }
281
- current = current[paths[i]];
282
- }
283
- return current;
284
- }
285
- function getCleanedCode(code) {
286
- if (code && code.indexOf('_') > 0) return code.replace('_', '-');
287
- return code;
288
- }
289
-
290
- class ResourceStore extends EventEmitter {
291
- constructor(data) {
292
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
293
- ns: ['translation'],
294
- defaultNS: 'translation'
295
- };
296
- super();
297
- this.data = data || {};
298
- this.options = options;
299
- if (this.options.keySeparator === undefined) {
300
- this.options.keySeparator = '.';
301
- }
302
- if (this.options.ignoreJSONStructure === undefined) {
303
- this.options.ignoreJSONStructure = true;
304
- }
305
- }
306
- addNamespaces(ns) {
307
- if (this.options.ns.indexOf(ns) < 0) {
308
- this.options.ns.push(ns);
309
- }
310
- }
311
- removeNamespaces(ns) {
312
- const index = this.options.ns.indexOf(ns);
313
- if (index > -1) {
314
- this.options.ns.splice(index, 1);
315
- }
316
- }
317
- getResource(lng, ns, key) {
318
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
319
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
320
- const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
321
- let path = [lng, ns];
322
- if (key && typeof key !== 'string') path = path.concat(key);
323
- if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
324
- if (lng.indexOf('.') > -1) {
325
- path = lng.split('.');
326
- }
327
- const result = getPath(this.data, path);
328
- if (result || !ignoreJSONStructure || typeof key !== 'string') return result;
329
- return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
330
- }
331
- addResource(lng, ns, key, value) {
332
- let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
333
- silent: false
334
- };
335
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
336
- let path = [lng, ns];
337
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
338
- if (lng.indexOf('.') > -1) {
339
- path = lng.split('.');
340
- value = ns;
341
- ns = path[1];
342
- }
343
- this.addNamespaces(ns);
344
- setPath(this.data, path, value);
345
- if (!options.silent) this.emit('added', lng, ns, key, value);
346
- }
347
- addResources(lng, ns, resources) {
348
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
349
- silent: false
350
- };
351
- for (const m in resources) {
352
- if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {
353
- silent: true
354
- });
355
- }
356
- if (!options.silent) this.emit('added', lng, ns, resources);
357
- }
358
- addResourceBundle(lng, ns, resources, deep, overwrite) {
359
- let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
360
- silent: false
361
- };
362
- let path = [lng, ns];
363
- if (lng.indexOf('.') > -1) {
364
- path = lng.split('.');
365
- deep = resources;
366
- resources = ns;
367
- ns = path[1];
368
- }
369
- this.addNamespaces(ns);
370
- let pack = getPath(this.data, path) || {};
371
- if (deep) {
372
- deepExtend(pack, resources, overwrite);
373
- } else {
374
- pack = {
375
- ...pack,
376
- ...resources
377
- };
378
- }
379
- setPath(this.data, path, pack);
380
- if (!options.silent) this.emit('added', lng, ns, resources);
381
- }
382
- removeResourceBundle(lng, ns) {
383
- if (this.hasResourceBundle(lng, ns)) {
384
- delete this.data[lng][ns];
385
- }
386
- this.removeNamespaces(ns);
387
- this.emit('removed', lng, ns);
388
- }
389
- hasResourceBundle(lng, ns) {
390
- return this.getResource(lng, ns) !== undefined;
391
- }
392
- getResourceBundle(lng, ns) {
393
- if (!ns) ns = this.options.defaultNS;
394
- if (this.options.compatibilityAPI === 'v1') return {
395
- ...{},
396
- ...this.getResource(lng, ns)
397
- };
398
- return this.getResource(lng, ns);
399
- }
400
- getDataByLanguage(lng) {
401
- return this.data[lng];
402
- }
403
- hasLanguageSomeTranslations(lng) {
404
- const data = this.getDataByLanguage(lng);
405
- const n = data && Object.keys(data) || [];
406
- return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
407
- }
408
- toJSON() {
409
- return this.data;
410
- }
411
- }
412
-
413
- var postProcessor = {
414
- processors: {},
415
- addPostProcessor(module) {
416
- this.processors[module.name] = module;
417
- },
418
- handle(processors, value, key, options, translator) {
419
- processors.forEach(processor => {
420
- if (this.processors[processor]) value = this.processors[processor].process(value, key, options, translator);
421
- });
422
- return value;
423
- }
424
- };
425
-
426
- const checkedLoadedFor = {};
427
- class Translator extends EventEmitter {
428
- constructor(services) {
429
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
430
- super();
431
- copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
432
- this.options = options;
433
- if (this.options.keySeparator === undefined) {
434
- this.options.keySeparator = '.';
435
- }
436
- this.logger = baseLogger.create('translator');
437
- }
438
- changeLanguage(lng) {
439
- if (lng) this.language = lng;
440
- }
441
- exists(key) {
442
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
443
- interpolation: {}
444
- };
445
- if (key === undefined || key === null) {
446
- return false;
447
- }
448
- const resolved = this.resolve(key, options);
449
- return resolved && resolved.res !== undefined;
450
- }
451
- extractFromKey(key, options) {
452
- let nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
453
- if (nsSeparator === undefined) nsSeparator = ':';
454
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
455
- let namespaces = options.ns || this.options.defaultNS || [];
456
- const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
457
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
458
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
459
- const m = key.match(this.interpolator.nestingRegexp);
460
- if (m && m.length > 0) {
461
- return {
462
- key,
463
- namespaces
464
- };
465
- }
466
- const parts = key.split(nsSeparator);
467
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
468
- key = parts.join(keySeparator);
469
- }
470
- if (typeof namespaces === 'string') namespaces = [namespaces];
471
- return {
472
- key,
473
- namespaces
474
- };
475
- }
476
- translate(keys, options, lastKey) {
477
- if (typeof options !== 'object' && this.options.overloadTranslationOptionHandler) {
478
- options = this.options.overloadTranslationOptionHandler(arguments);
479
- }
480
- if (typeof options === 'object') options = {
481
- ...options
482
- };
483
- if (!options) options = {};
484
- if (keys === undefined || keys === null) return '';
485
- if (!Array.isArray(keys)) keys = [String(keys)];
486
- const returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails;
487
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
488
- const {
489
- key,
490
- namespaces
491
- } = this.extractFromKey(keys[keys.length - 1], options);
492
- const namespace = namespaces[namespaces.length - 1];
493
- const lng = options.lng || this.language;
494
- const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
495
- if (lng && lng.toLowerCase() === 'cimode') {
496
- if (appendNamespaceToCIMode) {
497
- const nsSeparator = options.nsSeparator || this.options.nsSeparator;
498
- if (returnDetails) {
499
- return {
500
- res: `${namespace}${nsSeparator}${key}`,
501
- usedKey: key,
502
- exactUsedKey: key,
503
- usedLng: lng,
504
- usedNS: namespace
505
- };
506
- }
507
- return `${namespace}${nsSeparator}${key}`;
508
- }
509
- if (returnDetails) {
510
- return {
511
- res: key,
512
- usedKey: key,
513
- exactUsedKey: key,
514
- usedLng: lng,
515
- usedNS: namespace
516
- };
517
- }
518
- return key;
519
- }
520
- const resolved = this.resolve(keys, options);
521
- let res = resolved && resolved.res;
522
- const resUsedKey = resolved && resolved.usedKey || key;
523
- const resExactUsedKey = resolved && resolved.exactUsedKey || key;
524
- const resType = Object.prototype.toString.apply(res);
525
- const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
526
- const joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
527
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
528
- const handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';
529
- if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {
530
- if (!options.returnObjects && !this.options.returnObjects) {
531
- if (!this.options.returnedObjectHandler) {
532
- this.logger.warn('accessing an object - but returnObjects options is not enabled!');
533
- }
534
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, {
535
- ...options,
536
- ns: namespaces
537
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
538
- if (returnDetails) {
539
- resolved.res = r;
540
- return resolved;
541
- }
542
- return r;
543
- }
544
- if (keySeparator) {
545
- const resTypeIsArray = resType === '[object Array]';
546
- const copy = resTypeIsArray ? [] : {};
547
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
548
- for (const m in res) {
549
- if (Object.prototype.hasOwnProperty.call(res, m)) {
550
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
551
- copy[m] = this.translate(deepKey, {
552
- ...options,
553
- ...{
554
- joinArrays: false,
555
- ns: namespaces
556
- }
557
- });
558
- if (copy[m] === deepKey) copy[m] = res[m];
559
- }
560
- }
561
- res = copy;
562
- }
563
- } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {
564
- res = res.join(joinArrays);
565
- if (res) res = this.extendTranslation(res, keys, options, lastKey);
566
- } else {
567
- let usedDefault = false;
568
- let usedKey = false;
569
- const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
570
- const hasDefaultValue = Translator.hasDefaultValue(options);
571
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';
572
- const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {
573
- ordinal: false
574
- }) : '';
575
- const defaultValue = options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;
576
- if (!this.isValidLookup(res) && hasDefaultValue) {
577
- usedDefault = true;
578
- res = defaultValue;
579
- }
580
- if (!this.isValidLookup(res)) {
581
- usedKey = true;
582
- res = key;
583
- }
584
- const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
585
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
586
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
587
- if (usedKey || usedDefault || updateMissing) {
588
- this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
589
- if (keySeparator) {
590
- const fk = this.resolve(key, {
591
- ...options,
592
- keySeparator: false
593
- });
594
- if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');
595
- }
596
- let lngs = [];
597
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
598
- if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
599
- for (let i = 0; i < fallbackLngs.length; i++) {
600
- lngs.push(fallbackLngs[i]);
601
- }
602
- } else if (this.options.saveMissingTo === 'all') {
603
- lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
604
- } else {
605
- lngs.push(options.lng || this.language);
606
- }
607
- const send = (l, k, specificDefaultValue) => {
608
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
609
- if (this.options.missingKeyHandler) {
610
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
611
- } else if (this.backendConnector && this.backendConnector.saveMissing) {
612
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
613
- }
614
- this.emit('missingKey', l, namespace, k, res);
615
- };
616
- if (this.options.saveMissing) {
617
- if (this.options.saveMissingPlurals && needsPluralHandling) {
618
- lngs.forEach(language => {
619
- this.pluralResolver.getSuffixes(language, options).forEach(suffix => {
620
- send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue);
621
- });
622
- });
623
- } else {
624
- send(lngs, key, defaultValue);
625
- }
626
- }
627
- }
628
- res = this.extendTranslation(res, keys, options, resolved, lastKey);
629
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`;
630
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
631
- if (this.options.compatibilityAPI !== 'v1') {
632
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : undefined);
633
- } else {
634
- res = this.options.parseMissingKeyHandler(res);
635
- }
636
- }
637
- }
638
- if (returnDetails) {
639
- resolved.res = res;
640
- return resolved;
641
- }
642
- return res;
643
- }
644
- extendTranslation(res, key, options, resolved, lastKey) {
645
- var _this = this;
646
- if (this.i18nFormat && this.i18nFormat.parse) {
647
- res = this.i18nFormat.parse(res, {
648
- ...this.options.interpolation.defaultVariables,
649
- ...options
650
- }, resolved.usedLng, resolved.usedNS, resolved.usedKey, {
651
- resolved
652
- });
653
- } else if (!options.skipInterpolation) {
654
- if (options.interpolation) this.interpolator.init({
655
- ...options,
656
- ...{
657
- interpolation: {
658
- ...this.options.interpolation,
659
- ...options.interpolation
660
- }
661
- }
662
- });
663
- const skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
664
- let nestBef;
665
- if (skipOnVariables) {
666
- const nb = res.match(this.interpolator.nestingRegexp);
667
- nestBef = nb && nb.length;
668
- }
669
- let data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
670
- if (this.options.interpolation.defaultVariables) data = {
671
- ...this.options.interpolation.defaultVariables,
672
- ...data
673
- };
674
- res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
675
- if (skipOnVariables) {
676
- const na = res.match(this.interpolator.nestingRegexp);
677
- const nestAft = na && na.length;
678
- if (nestBef < nestAft) options.nest = false;
679
- }
680
- if (!options.lng && this.options.compatibilityAPI !== 'v1' && resolved && resolved.res) options.lng = resolved.usedLng;
681
- if (options.nest !== false) res = this.interpolator.nest(res, function () {
682
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
683
- args[_key] = arguments[_key];
684
- }
685
- if (lastKey && lastKey[0] === args[0] && !options.context) {
686
- _this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
687
- return null;
688
- }
689
- return _this.translate(...args, key);
690
- }, options);
691
- if (options.interpolation) this.interpolator.reset();
692
- }
693
- const postProcess = options.postProcess || this.options.postProcess;
694
- const postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
695
- if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
696
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
697
- i18nResolved: resolved,
698
- ...options
699
- } : options, this);
700
- }
701
- return res;
702
- }
703
- resolve(keys) {
704
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
705
- let found;
706
- let usedKey;
707
- let exactUsedKey;
708
- let usedLng;
709
- let usedNS;
710
- if (typeof keys === 'string') keys = [keys];
711
- keys.forEach(k => {
712
- if (this.isValidLookup(found)) return;
713
- const extracted = this.extractFromKey(k, options);
714
- const key = extracted.key;
715
- usedKey = key;
716
- let namespaces = extracted.namespaces;
717
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
718
- const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
719
- const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();
720
- const needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';
721
- const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);
722
- namespaces.forEach(ns => {
723
- if (this.isValidLookup(found)) return;
724
- usedNS = ns;
725
- if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils && this.utils.hasLoadedNamespace && !this.utils.hasLoadedNamespace(usedNS)) {
726
- checkedLoadedFor[`${codes[0]}-${ns}`] = true;
727
- this.logger.warn(`key "${usedKey}" for languages "${codes.join(', ')}" won't get resolved as namespace "${usedNS}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
728
- }
729
- codes.forEach(code => {
730
- if (this.isValidLookup(found)) return;
731
- usedLng = code;
732
- const finalKeys = [key];
733
- if (this.i18nFormat && this.i18nFormat.addLookupKeys) {
734
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
735
- } else {
736
- let pluralSuffix;
737
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);
738
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
739
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
740
- if (needsPluralHandling) {
741
- finalKeys.push(key + pluralSuffix);
742
- if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
743
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
744
- }
745
- if (needsZeroSuffixLookup) {
746
- finalKeys.push(key + zeroSuffix);
747
- }
748
- }
749
- if (needsContextHandling) {
750
- const contextKey = `${key}${this.options.contextSeparator}${options.context}`;
751
- finalKeys.push(contextKey);
752
- if (needsPluralHandling) {
753
- finalKeys.push(contextKey + pluralSuffix);
754
- if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
755
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
756
- }
757
- if (needsZeroSuffixLookup) {
758
- finalKeys.push(contextKey + zeroSuffix);
759
- }
760
- }
761
- }
762
- }
763
- let possibleKey;
764
- while (possibleKey = finalKeys.pop()) {
765
- if (!this.isValidLookup(found)) {
766
- exactUsedKey = possibleKey;
767
- found = this.getResource(code, ns, possibleKey, options);
768
- }
769
- }
770
- });
771
- });
772
- });
773
- return {
774
- res: found,
775
- usedKey,
776
- exactUsedKey,
777
- usedLng,
778
- usedNS
779
- };
780
- }
781
- isValidLookup(res) {
782
- return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
783
- }
784
- getResource(code, ns, key) {
785
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
786
- if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
787
- return this.resourceStore.getResource(code, ns, key, options);
788
- }
789
- static hasDefaultValue(options) {
790
- const prefix = 'defaultValue';
791
- for (const option in options) {
792
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
793
- return true;
794
- }
795
- }
796
- return false;
797
- }
798
- }
799
-
800
- function capitalize(string) {
801
- return string.charAt(0).toUpperCase() + string.slice(1);
802
- }
803
- class LanguageUtil {
804
- constructor(options) {
805
- this.options = options;
806
- this.supportedLngs = this.options.supportedLngs || false;
807
- this.logger = baseLogger.create('languageUtils');
808
- }
809
- getScriptPartFromCode(code) {
810
- code = getCleanedCode(code);
811
- if (!code || code.indexOf('-') < 0) return null;
812
- const p = code.split('-');
813
- if (p.length === 2) return null;
814
- p.pop();
815
- if (p[p.length - 1].toLowerCase() === 'x') return null;
816
- return this.formatLanguageCode(p.join('-'));
817
- }
818
- getLanguagePartFromCode(code) {
819
- code = getCleanedCode(code);
820
- if (!code || code.indexOf('-') < 0) return code;
821
- const p = code.split('-');
822
- return this.formatLanguageCode(p[0]);
823
- }
824
- formatLanguageCode(code) {
825
- if (typeof code === 'string' && code.indexOf('-') > -1) {
826
- const specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
827
- let p = code.split('-');
828
- if (this.options.lowerCaseLng) {
829
- p = p.map(part => part.toLowerCase());
830
- } else if (p.length === 2) {
831
- p[0] = p[0].toLowerCase();
832
- p[1] = p[1].toUpperCase();
833
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
834
- } else if (p.length === 3) {
835
- p[0] = p[0].toLowerCase();
836
- if (p[1].length === 2) p[1] = p[1].toUpperCase();
837
- if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
838
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
839
- if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
840
- }
841
- return p.join('-');
842
- }
843
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
844
- }
845
- isSupportedCode(code) {
846
- if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
847
- code = this.getLanguagePartFromCode(code);
848
- }
849
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
850
- }
851
- getBestMatchFromCodes(codes) {
852
- if (!codes) return null;
853
- let found;
854
- codes.forEach(code => {
855
- if (found) return;
856
- const cleanedLng = this.formatLanguageCode(code);
857
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
858
- });
859
- if (!found && this.options.supportedLngs) {
860
- codes.forEach(code => {
861
- if (found) return;
862
- const lngOnly = this.getLanguagePartFromCode(code);
863
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
864
- found = this.options.supportedLngs.find(supportedLng => {
865
- if (supportedLng === lngOnly) return supportedLng;
866
- if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
867
- if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;
868
- });
869
- });
870
- }
871
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
872
- return found;
873
- }
874
- getFallbackCodes(fallbacks, code) {
875
- if (!fallbacks) return [];
876
- if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
877
- if (typeof fallbacks === 'string') fallbacks = [fallbacks];
878
- if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
879
- if (!code) return fallbacks.default || [];
880
- let found = fallbacks[code];
881
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
882
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
883
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
884
- if (!found) found = fallbacks.default;
885
- return found || [];
886
- }
887
- toResolveHierarchy(code, fallbackCode) {
888
- const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
889
- const codes = [];
890
- const addCode = c => {
891
- if (!c) return;
892
- if (this.isSupportedCode(c)) {
893
- codes.push(c);
894
- } else {
895
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
896
- }
897
- };
898
- if (typeof code === 'string' && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
899
- if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
900
- if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
901
- if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
902
- } else if (typeof code === 'string') {
903
- addCode(this.formatLanguageCode(code));
904
- }
905
- fallbackCodes.forEach(fc => {
906
- if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
907
- });
908
- return codes;
909
- }
910
- }
911
-
912
- let sets = [{
913
- lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],
914
- nr: [1, 2],
915
- fc: 1
916
- }, {
917
- lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],
918
- nr: [1, 2],
919
- fc: 2
920
- }, {
921
- lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
922
- nr: [1],
923
- fc: 3
924
- }, {
925
- lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
926
- nr: [1, 2, 5],
927
- fc: 4
928
- }, {
929
- lngs: ['ar'],
930
- nr: [0, 1, 2, 3, 11, 100],
931
- fc: 5
932
- }, {
933
- lngs: ['cs', 'sk'],
934
- nr: [1, 2, 5],
935
- fc: 6
936
- }, {
937
- lngs: ['csb', 'pl'],
938
- nr: [1, 2, 5],
939
- fc: 7
940
- }, {
941
- lngs: ['cy'],
942
- nr: [1, 2, 3, 8],
943
- fc: 8
944
- }, {
945
- lngs: ['fr'],
946
- nr: [1, 2],
947
- fc: 9
948
- }, {
949
- lngs: ['ga'],
950
- nr: [1, 2, 3, 7, 11],
951
- fc: 10
952
- }, {
953
- lngs: ['gd'],
954
- nr: [1, 2, 3, 20],
955
- fc: 11
956
- }, {
957
- lngs: ['is'],
958
- nr: [1, 2],
959
- fc: 12
960
- }, {
961
- lngs: ['jv'],
962
- nr: [0, 1],
963
- fc: 13
964
- }, {
965
- lngs: ['kw'],
966
- nr: [1, 2, 3, 4],
967
- fc: 14
968
- }, {
969
- lngs: ['lt'],
970
- nr: [1, 2, 10],
971
- fc: 15
972
- }, {
973
- lngs: ['lv'],
974
- nr: [1, 2, 0],
975
- fc: 16
976
- }, {
977
- lngs: ['mk'],
978
- nr: [1, 2],
979
- fc: 17
980
- }, {
981
- lngs: ['mnk'],
982
- nr: [0, 1, 2],
983
- fc: 18
984
- }, {
985
- lngs: ['mt'],
986
- nr: [1, 2, 11, 20],
987
- fc: 19
988
- }, {
989
- lngs: ['or'],
990
- nr: [2, 1],
991
- fc: 2
992
- }, {
993
- lngs: ['ro'],
994
- nr: [1, 2, 20],
995
- fc: 20
996
- }, {
997
- lngs: ['sl'],
998
- nr: [5, 1, 2, 3],
999
- fc: 21
1000
- }, {
1001
- lngs: ['he', 'iw'],
1002
- nr: [1, 2, 20, 21],
1003
- fc: 22
1004
- }];
1005
- let _rulesPluralsTypes = {
1006
- 1: function (n) {
1007
- return Number(n > 1);
1008
- },
1009
- 2: function (n) {
1010
- return Number(n != 1);
1011
- },
1012
- 3: function (n) {
1013
- return 0;
1014
- },
1015
- 4: function (n) {
1016
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1017
- },
1018
- 5: function (n) {
1019
- return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
1020
- },
1021
- 6: function (n) {
1022
- return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
1023
- },
1024
- 7: function (n) {
1025
- return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1026
- },
1027
- 8: function (n) {
1028
- return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
1029
- },
1030
- 9: function (n) {
1031
- return Number(n >= 2);
1032
- },
1033
- 10: function (n) {
1034
- return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
1035
- },
1036
- 11: function (n) {
1037
- return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
1038
- },
1039
- 12: function (n) {
1040
- return Number(n % 10 != 1 || n % 100 == 11);
1041
- },
1042
- 13: function (n) {
1043
- return Number(n !== 0);
1044
- },
1045
- 14: function (n) {
1046
- return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
1047
- },
1048
- 15: function (n) {
1049
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1050
- },
1051
- 16: function (n) {
1052
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
1053
- },
1054
- 17: function (n) {
1055
- return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);
1056
- },
1057
- 18: function (n) {
1058
- return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
1059
- },
1060
- 19: function (n) {
1061
- return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
1062
- },
1063
- 20: function (n) {
1064
- return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
1065
- },
1066
- 21: function (n) {
1067
- return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
1068
- },
1069
- 22: function (n) {
1070
- return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
1071
- }
1072
- };
1073
- const nonIntlVersions = ['v1', 'v2', 'v3'];
1074
- const intlVersions = ['v4'];
1075
- const suffixesOrder = {
1076
- zero: 0,
1077
- one: 1,
1078
- two: 2,
1079
- few: 3,
1080
- many: 4,
1081
- other: 5
1082
- };
1083
- function createRules() {
1084
- const rules = {};
1085
- sets.forEach(set => {
1086
- set.lngs.forEach(l => {
1087
- rules[l] = {
1088
- numbers: set.nr,
1089
- plurals: _rulesPluralsTypes[set.fc]
1090
- };
1091
- });
1092
- });
1093
- return rules;
1094
- }
1095
- class PluralResolver {
1096
- constructor(languageUtils) {
1097
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1098
- this.languageUtils = languageUtils;
1099
- this.options = options;
1100
- this.logger = baseLogger.create('pluralResolver');
1101
- if ((!this.options.compatibilityJSON || intlVersions.includes(this.options.compatibilityJSON)) && (typeof Intl === 'undefined' || !Intl.PluralRules)) {
1102
- this.options.compatibilityJSON = 'v3';
1103
- this.logger.error('Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.');
1104
- }
1105
- this.rules = createRules();
1106
- }
1107
- addRule(lng, obj) {
1108
- this.rules[lng] = obj;
1109
- }
1110
- getRule(code) {
1111
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1112
- if (this.shouldUseIntlApi()) {
1113
- try {
1114
- return new Intl.PluralRules(getCleanedCode(code), {
1115
- type: options.ordinal ? 'ordinal' : 'cardinal'
1116
- });
1117
- } catch {
1118
- return;
1119
- }
1120
- }
1121
- return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
1122
- }
1123
- needsPlural(code) {
1124
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1125
- const rule = this.getRule(code, options);
1126
- if (this.shouldUseIntlApi()) {
1127
- return rule && rule.resolvedOptions().pluralCategories.length > 1;
1128
- }
1129
- return rule && rule.numbers.length > 1;
1130
- }
1131
- getPluralFormsOfKey(code, key) {
1132
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1133
- return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
1134
- }
1135
- getSuffixes(code) {
1136
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1137
- const rule = this.getRule(code, options);
1138
- if (!rule) {
1139
- return [];
1140
- }
1141
- if (this.shouldUseIntlApi()) {
1142
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
1143
- }
1144
- return rule.numbers.map(number => this.getSuffix(code, number, options));
1145
- }
1146
- getSuffix(code, count) {
1147
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1148
- const rule = this.getRule(code, options);
1149
- if (rule) {
1150
- if (this.shouldUseIntlApi()) {
1151
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
1152
- }
1153
- return this.getSuffixRetroCompatible(rule, count);
1154
- }
1155
- this.logger.warn(`no plural rule found for: ${code}`);
1156
- return '';
1157
- }
1158
- getSuffixRetroCompatible(rule, count) {
1159
- const idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
1160
- let suffix = rule.numbers[idx];
1161
- if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
1162
- if (suffix === 2) {
1163
- suffix = 'plural';
1164
- } else if (suffix === 1) {
1165
- suffix = '';
1166
- }
1167
- }
1168
- const returnSuffix = () => this.options.prepend && suffix.toString() ? this.options.prepend + suffix.toString() : suffix.toString();
1169
- if (this.options.compatibilityJSON === 'v1') {
1170
- if (suffix === 1) return '';
1171
- if (typeof suffix === 'number') return `_plural_${suffix.toString()}`;
1172
- return returnSuffix();
1173
- } else if (this.options.compatibilityJSON === 'v2') {
1174
- return returnSuffix();
1175
- } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
1176
- return returnSuffix();
1177
- }
1178
- return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
1179
- }
1180
- shouldUseIntlApi() {
1181
- return !nonIntlVersions.includes(this.options.compatibilityJSON);
1182
- }
1183
- }
1184
-
1185
- function deepFindWithDefaults(data, defaultData, key) {
1186
- let keySeparator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '.';
1187
- let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
1188
- let path = getPathWithDefaults(data, defaultData, key);
1189
- if (!path && ignoreJSONStructure && typeof key === 'string') {
1190
- path = deepFind(data, key, keySeparator);
1191
- if (path === undefined) path = deepFind(defaultData, key, keySeparator);
1192
- }
1193
- return path;
1194
- }
1195
- class Interpolator {
1196
- constructor() {
1197
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1198
- this.logger = baseLogger.create('interpolator');
1199
- this.options = options;
1200
- this.format = options.interpolation && options.interpolation.format || (value => value);
1201
- this.init(options);
1202
- }
1203
- init() {
1204
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1205
- if (!options.interpolation) options.interpolation = {
1206
- escapeValue: true
1207
- };
1208
- const iOpts = options.interpolation;
1209
- this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
1210
- this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
1211
- this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;
1212
- this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
1213
- this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
1214
- this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
1215
- this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
1216
- this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
1217
- this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
1218
- this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
1219
- this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';
1220
- this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
1221
- this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;
1222
- this.resetRegExp();
1223
- }
1224
- reset() {
1225
- if (this.options) this.init(this.options);
1226
- }
1227
- resetRegExp() {
1228
- const regexpStr = `${this.prefix}(.+?)${this.suffix}`;
1229
- this.regexp = new RegExp(regexpStr, 'g');
1230
- const regexpUnescapeStr = `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;
1231
- this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
1232
- const nestingRegexpStr = `${this.nestingPrefix}(.+?)${this.nestingSuffix}`;
1233
- this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
1234
- }
1235
- interpolate(str, data, lng, options) {
1236
- let match;
1237
- let value;
1238
- let replaces;
1239
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1240
- function regexSafe(val) {
1241
- return val.replace(/\$/g, '$$$$');
1242
- }
1243
- const handleFormat = key => {
1244
- if (key.indexOf(this.formatSeparator) < 0) {
1245
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1246
- return this.alwaysFormat ? this.format(path, undefined, lng, {
1247
- ...options,
1248
- ...data,
1249
- interpolationkey: key
1250
- }) : path;
1251
- }
1252
- const p = key.split(this.formatSeparator);
1253
- const k = p.shift().trim();
1254
- const f = p.join(this.formatSeparator).trim();
1255
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1256
- ...options,
1257
- ...data,
1258
- interpolationkey: k
1259
- });
1260
- };
1261
- this.resetRegExp();
1262
- const missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
1263
- const skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1264
- const todos = [{
1265
- regex: this.regexpUnescape,
1266
- safeValue: val => regexSafe(val)
1267
- }, {
1268
- regex: this.regexp,
1269
- safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1270
- }];
1271
- todos.forEach(todo => {
1272
- replaces = 0;
1273
- while (match = todo.regex.exec(str)) {
1274
- const matchedVar = match[1].trim();
1275
- value = handleFormat(matchedVar);
1276
- if (value === undefined) {
1277
- if (typeof missingInterpolationHandler === 'function') {
1278
- const temp = missingInterpolationHandler(str, match, options);
1279
- value = typeof temp === 'string' ? temp : '';
1280
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1281
- value = '';
1282
- } else if (skipOnVariables) {
1283
- value = match[0];
1284
- continue;
1285
- } else {
1286
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1287
- value = '';
1288
- }
1289
- } else if (typeof value !== 'string' && !this.useRawValueToEscape) {
1290
- value = makeString(value);
1291
- }
1292
- const safeValue = todo.safeValue(value);
1293
- str = str.replace(match[0], safeValue);
1294
- if (skipOnVariables) {
1295
- todo.regex.lastIndex += value.length;
1296
- todo.regex.lastIndex -= match[0].length;
1297
- } else {
1298
- todo.regex.lastIndex = 0;
1299
- }
1300
- replaces++;
1301
- if (replaces >= this.maxReplaces) {
1302
- break;
1303
- }
1304
- }
1305
- });
1306
- return str;
1307
- }
1308
- nest(str, fc) {
1309
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1310
- let match;
1311
- let value;
1312
- let clonedOptions;
1313
- function handleHasOptions(key, inheritedOptions) {
1314
- const sep = this.nestingOptionsSeparator;
1315
- if (key.indexOf(sep) < 0) return key;
1316
- const c = key.split(new RegExp(`${sep}[ ]*{`));
1317
- let optionsString = `{${c[1]}`;
1318
- key = c[0];
1319
- optionsString = this.interpolate(optionsString, clonedOptions);
1320
- const matchedSingleQuotes = optionsString.match(/'/g);
1321
- const matchedDoubleQuotes = optionsString.match(/"/g);
1322
- if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1323
- optionsString = optionsString.replace(/'/g, '"');
1324
- }
1325
- try {
1326
- clonedOptions = JSON.parse(optionsString);
1327
- if (inheritedOptions) clonedOptions = {
1328
- ...inheritedOptions,
1329
- ...clonedOptions
1330
- };
1331
- } catch (e) {
1332
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1333
- return `${key}${sep}${optionsString}`;
1334
- }
1335
- delete clonedOptions.defaultValue;
1336
- return key;
1337
- }
1338
- while (match = this.nestingRegexp.exec(str)) {
1339
- let formatters = [];
1340
- clonedOptions = {
1341
- ...options
1342
- };
1343
- clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== 'string' ? clonedOptions.replace : clonedOptions;
1344
- clonedOptions.applyPostProcessor = false;
1345
- delete clonedOptions.defaultValue;
1346
- let doReduce = false;
1347
- if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
1348
- const r = match[1].split(this.formatSeparator).map(elem => elem.trim());
1349
- match[1] = r.shift();
1350
- formatters = r;
1351
- doReduce = true;
1352
- }
1353
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1354
- if (value && match[0] === str && typeof value !== 'string') return value;
1355
- if (typeof value !== 'string') value = makeString(value);
1356
- if (!value) {
1357
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1358
- value = '';
1359
- }
1360
- if (doReduce) {
1361
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1362
- ...options,
1363
- interpolationkey: match[1].trim()
1364
- }), value.trim());
1365
- }
1366
- str = str.replace(match[0], value);
1367
- this.regexp.lastIndex = 0;
1368
- }
1369
- return str;
1370
- }
1371
- }
1372
-
1373
- function parseFormatStr(formatStr) {
1374
- let formatName = formatStr.toLowerCase().trim();
1375
- const formatOptions = {};
1376
- if (formatStr.indexOf('(') > -1) {
1377
- const p = formatStr.split('(');
1378
- formatName = p[0].toLowerCase().trim();
1379
- const optStr = p[1].substring(0, p[1].length - 1);
1380
- if (formatName === 'currency' && optStr.indexOf(':') < 0) {
1381
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1382
- } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
1383
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1384
- } else {
1385
- const opts = optStr.split(';');
1386
- opts.forEach(opt => {
1387
- if (!opt) return;
1388
- const [key, ...rest] = opt.split(':');
1389
- const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
1390
- if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val;
1391
- if (val === 'false') formatOptions[key.trim()] = false;
1392
- if (val === 'true') formatOptions[key.trim()] = true;
1393
- if (!isNaN(val)) formatOptions[key.trim()] = parseInt(val, 10);
1394
- });
1395
- }
1396
- }
1397
- return {
1398
- formatName,
1399
- formatOptions
1400
- };
1401
- }
1402
- function createCachedFormatter(fn) {
1403
- const cache = {};
1404
- return function invokeFormatter(val, lng, options) {
1405
- const key = lng + JSON.stringify(options);
1406
- let formatter = cache[key];
1407
- if (!formatter) {
1408
- formatter = fn(getCleanedCode(lng), options);
1409
- cache[key] = formatter;
1410
- }
1411
- return formatter(val);
1412
- };
1413
- }
1414
- class Formatter {
1415
- constructor() {
1416
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1417
- this.logger = baseLogger.create('formatter');
1418
- this.options = options;
1419
- this.formats = {
1420
- number: createCachedFormatter((lng, opt) => {
1421
- const formatter = new Intl.NumberFormat(lng, {
1422
- ...opt
1423
- });
1424
- return val => formatter.format(val);
1425
- }),
1426
- currency: createCachedFormatter((lng, opt) => {
1427
- const formatter = new Intl.NumberFormat(lng, {
1428
- ...opt,
1429
- style: 'currency'
1430
- });
1431
- return val => formatter.format(val);
1432
- }),
1433
- datetime: createCachedFormatter((lng, opt) => {
1434
- const formatter = new Intl.DateTimeFormat(lng, {
1435
- ...opt
1436
- });
1437
- return val => formatter.format(val);
1438
- }),
1439
- relativetime: createCachedFormatter((lng, opt) => {
1440
- const formatter = new Intl.RelativeTimeFormat(lng, {
1441
- ...opt
1442
- });
1443
- return val => formatter.format(val, opt.range || 'day');
1444
- }),
1445
- list: createCachedFormatter((lng, opt) => {
1446
- const formatter = new Intl.ListFormat(lng, {
1447
- ...opt
1448
- });
1449
- return val => formatter.format(val);
1450
- })
1451
- };
1452
- this.init(options);
1453
- }
1454
- init(services) {
1455
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
1456
- interpolation: {}
1457
- };
1458
- const iOpts = options.interpolation;
1459
- this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
1460
- }
1461
- add(name, fc) {
1462
- this.formats[name.toLowerCase().trim()] = fc;
1463
- }
1464
- addCached(name, fc) {
1465
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1466
- }
1467
- format(value, format, lng) {
1468
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1469
- const formats = format.split(this.formatSeparator);
1470
- const result = formats.reduce((mem, f) => {
1471
- const {
1472
- formatName,
1473
- formatOptions
1474
- } = parseFormatStr(f);
1475
- if (this.formats[formatName]) {
1476
- let formatted = mem;
1477
- try {
1478
- const valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
1479
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1480
- formatted = this.formats[formatName](mem, l, {
1481
- ...formatOptions,
1482
- ...options,
1483
- ...valOptions
1484
- });
1485
- } catch (error) {
1486
- this.logger.warn(error);
1487
- }
1488
- return formatted;
1489
- } else {
1490
- this.logger.warn(`there was no format function for ${formatName}`);
1491
- }
1492
- return mem;
1493
- }, value);
1494
- return result;
1495
- }
1496
- }
1497
-
1498
- function removePending(q, name) {
1499
- if (q.pending[name] !== undefined) {
1500
- delete q.pending[name];
1501
- q.pendingCount--;
1502
- }
1503
- }
1504
- class Connector extends EventEmitter {
1505
- constructor(backend, store, services) {
1506
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1507
- super();
1508
- this.backend = backend;
1509
- this.store = store;
1510
- this.services = services;
1511
- this.languageUtils = services.languageUtils;
1512
- this.options = options;
1513
- this.logger = baseLogger.create('backendConnector');
1514
- this.waitingReads = [];
1515
- this.maxParallelReads = options.maxParallelReads || 10;
1516
- this.readingCalls = 0;
1517
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1518
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1519
- this.state = {};
1520
- this.queue = [];
1521
- if (this.backend && this.backend.init) {
1522
- this.backend.init(services, options.backend, options);
1523
- }
1524
- }
1525
- queueLoad(languages, namespaces, options, callback) {
1526
- const toLoad = {};
1527
- const pending = {};
1528
- const toLoadLanguages = {};
1529
- const toLoadNamespaces = {};
1530
- languages.forEach(lng => {
1531
- let hasAllNamespaces = true;
1532
- namespaces.forEach(ns => {
1533
- const name = `${lng}|${ns}`;
1534
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1535
- this.state[name] = 2;
1536
- } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
1537
- if (pending[name] === undefined) pending[name] = true;
1538
- } else {
1539
- this.state[name] = 1;
1540
- hasAllNamespaces = false;
1541
- if (pending[name] === undefined) pending[name] = true;
1542
- if (toLoad[name] === undefined) toLoad[name] = true;
1543
- if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
1544
- }
1545
- });
1546
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1547
- });
1548
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1549
- this.queue.push({
1550
- pending,
1551
- pendingCount: Object.keys(pending).length,
1552
- loaded: {},
1553
- errors: [],
1554
- callback
1555
- });
1556
- }
1557
- return {
1558
- toLoad: Object.keys(toLoad),
1559
- pending: Object.keys(pending),
1560
- toLoadLanguages: Object.keys(toLoadLanguages),
1561
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1562
- };
1563
- }
1564
- loaded(name, err, data) {
1565
- const s = name.split('|');
1566
- const lng = s[0];
1567
- const ns = s[1];
1568
- if (err) this.emit('failedLoading', lng, ns, err);
1569
- if (data) {
1570
- this.store.addResourceBundle(lng, ns, data);
1571
- }
1572
- this.state[name] = err ? -1 : 2;
1573
- const loaded = {};
1574
- this.queue.forEach(q => {
1575
- pushPath(q.loaded, [lng], ns);
1576
- removePending(q, name);
1577
- if (err) q.errors.push(err);
1578
- if (q.pendingCount === 0 && !q.done) {
1579
- Object.keys(q.loaded).forEach(l => {
1580
- if (!loaded[l]) loaded[l] = {};
1581
- const loadedKeys = q.loaded[l];
1582
- if (loadedKeys.length) {
1583
- loadedKeys.forEach(n => {
1584
- if (loaded[l][n] === undefined) loaded[l][n] = true;
1585
- });
1586
- }
1587
- });
1588
- q.done = true;
1589
- if (q.errors.length) {
1590
- q.callback(q.errors);
1591
- } else {
1592
- q.callback();
1593
- }
1594
- }
1595
- });
1596
- this.emit('loaded', loaded);
1597
- this.queue = this.queue.filter(q => !q.done);
1598
- }
1599
- read(lng, ns, fcName) {
1600
- let tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
1601
- let wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout;
1602
- let callback = arguments.length > 5 ? arguments[5] : undefined;
1603
- if (!lng.length) return callback(null, {});
1604
- if (this.readingCalls >= this.maxParallelReads) {
1605
- this.waitingReads.push({
1606
- lng,
1607
- ns,
1608
- fcName,
1609
- tried,
1610
- wait,
1611
- callback
1612
- });
1613
- return;
1614
- }
1615
- this.readingCalls++;
1616
- const resolver = (err, data) => {
1617
- this.readingCalls--;
1618
- if (this.waitingReads.length > 0) {
1619
- const next = this.waitingReads.shift();
1620
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1621
- }
1622
- if (err && data && tried < this.maxRetries) {
1623
- setTimeout(() => {
1624
- this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1625
- }, wait);
1626
- return;
1627
- }
1628
- callback(err, data);
1629
- };
1630
- const fc = this.backend[fcName].bind(this.backend);
1631
- if (fc.length === 2) {
1632
- try {
1633
- const r = fc(lng, ns);
1634
- if (r && typeof r.then === 'function') {
1635
- r.then(data => resolver(null, data)).catch(resolver);
1636
- } else {
1637
- resolver(null, r);
1638
- }
1639
- } catch (err) {
1640
- resolver(err);
1641
- }
1642
- return;
1643
- }
1644
- return fc(lng, ns, resolver);
1645
- }
1646
- prepareLoading(languages, namespaces) {
1647
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1648
- let callback = arguments.length > 3 ? arguments[3] : undefined;
1649
- if (!this.backend) {
1650
- this.logger.warn('No backend was added via i18next.use. Will not load resources.');
1651
- return callback && callback();
1652
- }
1653
- if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);
1654
- if (typeof namespaces === 'string') namespaces = [namespaces];
1655
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
1656
- if (!toLoad.toLoad.length) {
1657
- if (!toLoad.pending.length) callback();
1658
- return null;
1659
- }
1660
- toLoad.toLoad.forEach(name => {
1661
- this.loadOne(name);
1662
- });
1663
- }
1664
- load(languages, namespaces, callback) {
1665
- this.prepareLoading(languages, namespaces, {}, callback);
1666
- }
1667
- reload(languages, namespaces, callback) {
1668
- this.prepareLoading(languages, namespaces, {
1669
- reload: true
1670
- }, callback);
1671
- }
1672
- loadOne(name) {
1673
- let prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
1674
- const s = name.split('|');
1675
- const lng = s[0];
1676
- const ns = s[1];
1677
- this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
1678
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1679
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1680
- this.loaded(name, err, data);
1681
- });
1682
- }
1683
- saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
1684
- let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
1685
- let clb = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : () => {};
1686
- if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
1687
- this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
1688
- return;
1689
- }
1690
- if (key === undefined || key === null || key === '') return;
1691
- if (this.backend && this.backend.create) {
1692
- const opts = {
1693
- ...options,
1694
- isUpdate
1695
- };
1696
- const fc = this.backend.create.bind(this.backend);
1697
- if (fc.length < 6) {
1698
- try {
1699
- let r;
1700
- if (fc.length === 5) {
1701
- r = fc(languages, namespace, key, fallbackValue, opts);
1702
- } else {
1703
- r = fc(languages, namespace, key, fallbackValue);
1704
- }
1705
- if (r && typeof r.then === 'function') {
1706
- r.then(data => clb(null, data)).catch(clb);
1707
- } else {
1708
- clb(null, r);
1709
- }
1710
- } catch (err) {
1711
- clb(err);
1712
- }
1713
- } else {
1714
- fc(languages, namespace, key, fallbackValue, clb, opts);
1715
- }
1716
- }
1717
- if (!languages || !languages[0]) return;
1718
- this.store.addResource(languages[0], namespace, key, fallbackValue);
1719
- }
1720
- }
1721
-
1722
- function get() {
1723
- return {
1724
- debug: false,
1725
- initImmediate: true,
1726
- ns: ['translation'],
1727
- defaultNS: ['translation'],
1728
- fallbackLng: ['dev'],
1729
- fallbackNS: false,
1730
- supportedLngs: false,
1731
- nonExplicitSupportedLngs: false,
1732
- load: 'all',
1733
- preload: false,
1734
- simplifyPluralSuffix: true,
1735
- keySeparator: '.',
1736
- nsSeparator: ':',
1737
- pluralSeparator: '_',
1738
- contextSeparator: '_',
1739
- partialBundledLanguages: false,
1740
- saveMissing: false,
1741
- updateMissing: false,
1742
- saveMissingTo: 'fallback',
1743
- saveMissingPlurals: true,
1744
- missingKeyHandler: false,
1745
- missingInterpolationHandler: false,
1746
- postProcess: false,
1747
- postProcessPassResolved: false,
1748
- returnNull: false,
1749
- returnEmptyString: true,
1750
- returnObjects: false,
1751
- joinArrays: false,
1752
- returnedObjectHandler: false,
1753
- parseMissingKeyHandler: false,
1754
- appendNamespaceToMissingKey: false,
1755
- appendNamespaceToCIMode: false,
1756
- overloadTranslationOptionHandler: function handle(args) {
1757
- let ret = {};
1758
- if (typeof args[1] === 'object') ret = args[1];
1759
- if (typeof args[1] === 'string') ret.defaultValue = args[1];
1760
- if (typeof args[2] === 'string') ret.tDescription = args[2];
1761
- if (typeof args[2] === 'object' || typeof args[3] === 'object') {
1762
- const options = args[3] || args[2];
1763
- Object.keys(options).forEach(key => {
1764
- ret[key] = options[key];
1765
- });
1766
- }
1767
- return ret;
1768
- },
1769
- interpolation: {
1770
- escapeValue: true,
1771
- format: (value, format, lng, options) => value,
1772
- prefix: '{{',
1773
- suffix: '}}',
1774
- formatSeparator: ',',
1775
- unescapePrefix: '-',
1776
- nestingPrefix: '$t(',
1777
- nestingSuffix: ')',
1778
- nestingOptionsSeparator: ',',
1779
- maxReplaces: 1000,
1780
- skipOnVariables: true
1781
- }
1782
- };
1783
- }
1784
- function transformOptions(options) {
1785
- if (typeof options.ns === 'string') options.ns = [options.ns];
1786
- if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
1787
- if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];
1788
- if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
1789
- options.supportedLngs = options.supportedLngs.concat(['cimode']);
1790
- }
1791
- return options;
1792
- }
1793
-
1794
- function noop() {}
1795
- function bindMemberFunctions(inst) {
1796
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1797
- mems.forEach(mem => {
1798
- if (typeof inst[mem] === 'function') {
1799
- inst[mem] = inst[mem].bind(inst);
1800
- }
1801
- });
1802
- }
1803
- class I18n extends EventEmitter {
1804
- constructor() {
1805
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1806
- let callback = arguments.length > 1 ? arguments[1] : undefined;
1807
- super();
1808
- this.options = transformOptions(options);
1809
- this.services = {};
1810
- this.logger = baseLogger;
1811
- this.modules = {
1812
- external: []
1813
- };
1814
- bindMemberFunctions(this);
1815
- if (callback && !this.isInitialized && !options.isClone) {
1816
- if (!this.options.initImmediate) {
1817
- this.init(options, callback);
1818
- return this;
1819
- }
1820
- setTimeout(() => {
1821
- this.init(options, callback);
1822
- }, 0);
1823
- }
1824
- }
1825
- init() {
1826
- var _this = this;
1827
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1828
- let callback = arguments.length > 1 ? arguments[1] : undefined;
1829
- if (typeof options === 'function') {
1830
- callback = options;
1831
- options = {};
1832
- }
1833
- if (!options.defaultNS && options.defaultNS !== false && options.ns) {
1834
- if (typeof options.ns === 'string') {
1835
- options.defaultNS = options.ns;
1836
- } else if (options.ns.indexOf('translation') < 0) {
1837
- options.defaultNS = options.ns[0];
1838
- }
1839
- }
1840
- const defOpts = get();
1841
- this.options = {
1842
- ...defOpts,
1843
- ...this.options,
1844
- ...transformOptions(options)
1845
- };
1846
- if (this.options.compatibilityAPI !== 'v1') {
1847
- this.options.interpolation = {
1848
- ...defOpts.interpolation,
1849
- ...this.options.interpolation
1850
- };
1851
- }
1852
- if (options.keySeparator !== undefined) {
1853
- this.options.userDefinedKeySeparator = options.keySeparator;
1854
- }
1855
- if (options.nsSeparator !== undefined) {
1856
- this.options.userDefinedNsSeparator = options.nsSeparator;
1857
- }
1858
- function createClassOnDemand(ClassOrObject) {
1859
- if (!ClassOrObject) return null;
1860
- if (typeof ClassOrObject === 'function') return new ClassOrObject();
1861
- return ClassOrObject;
1862
- }
1863
- if (!this.options.isClone) {
1864
- if (this.modules.logger) {
1865
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1866
- } else {
1867
- baseLogger.init(null, this.options);
1868
- }
1869
- let formatter;
1870
- if (this.modules.formatter) {
1871
- formatter = this.modules.formatter;
1872
- } else if (typeof Intl !== 'undefined') {
1873
- formatter = Formatter;
1874
- }
1875
- const lu = new LanguageUtil(this.options);
1876
- this.store = new ResourceStore(this.options.resources, this.options);
1877
- const s = this.services;
1878
- s.logger = baseLogger;
1879
- s.resourceStore = this.store;
1880
- s.languageUtils = lu;
1881
- s.pluralResolver = new PluralResolver(lu, {
1882
- prepend: this.options.pluralSeparator,
1883
- compatibilityJSON: this.options.compatibilityJSON,
1884
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
1885
- });
1886
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1887
- s.formatter = createClassOnDemand(formatter);
1888
- s.formatter.init(s, this.options);
1889
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1890
- }
1891
- s.interpolator = new Interpolator(this.options);
1892
- s.utils = {
1893
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1894
- };
1895
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1896
- s.backendConnector.on('*', function (event) {
1897
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1898
- args[_key - 1] = arguments[_key];
1899
- }
1900
- _this.emit(event, ...args);
1901
- });
1902
- if (this.modules.languageDetector) {
1903
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1904
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1905
- }
1906
- if (this.modules.i18nFormat) {
1907
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1908
- if (s.i18nFormat.init) s.i18nFormat.init(this);
1909
- }
1910
- this.translator = new Translator(this.services, this.options);
1911
- this.translator.on('*', function (event) {
1912
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1913
- args[_key2 - 1] = arguments[_key2];
1914
- }
1915
- _this.emit(event, ...args);
1916
- });
1917
- this.modules.external.forEach(m => {
1918
- if (m.init) m.init(this);
1919
- });
1920
- }
1921
- this.format = this.options.interpolation.format;
1922
- if (!callback) callback = noop;
1923
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1924
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1925
- if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
1926
- }
1927
- if (!this.services.languageDetector && !this.options.lng) {
1928
- this.logger.warn('init: no languageDetector is used and no lng is defined');
1929
- }
1930
- const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
1931
- storeApi.forEach(fcName => {
1932
- this[fcName] = function () {
1933
- return _this.store[fcName](...arguments);
1934
- };
1935
- });
1936
- const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
1937
- storeApiChained.forEach(fcName => {
1938
- this[fcName] = function () {
1939
- _this.store[fcName](...arguments);
1940
- return _this;
1941
- };
1942
- });
1943
- const deferred = defer();
1944
- const load = () => {
1945
- const finish = (err, t) => {
1946
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
1947
- this.isInitialized = true;
1948
- if (!this.options.isClone) this.logger.log('initialized', this.options);
1949
- this.emit('initialized', this.options);
1950
- deferred.resolve(t);
1951
- callback(err, t);
1952
- };
1953
- if (this.languages && this.options.compatibilityAPI !== 'v1' && !this.isInitialized) return finish(null, this.t.bind(this));
1954
- this.changeLanguage(this.options.lng, finish);
1955
- };
1956
- if (this.options.resources || !this.options.initImmediate) {
1957
- load();
1958
- } else {
1959
- setTimeout(load, 0);
1960
- }
1961
- return deferred;
1962
- }
1963
- loadResources(language) {
1964
- let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
1965
- let usedCallback = callback;
1966
- const usedLng = typeof language === 'string' ? language : this.language;
1967
- if (typeof language === 'function') usedCallback = language;
1968
- if (!this.options.resources || this.options.partialBundledLanguages) {
1969
- if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback();
1970
- const toLoad = [];
1971
- const append = lng => {
1972
- if (!lng) return;
1973
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1974
- lngs.forEach(l => {
1975
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
1976
- });
1977
- };
1978
- if (!usedLng) {
1979
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1980
- fallbacks.forEach(l => append(l));
1981
- } else {
1982
- append(usedLng);
1983
- }
1984
- if (this.options.preload) {
1985
- this.options.preload.forEach(l => append(l));
1986
- }
1987
- this.services.backendConnector.load(toLoad, this.options.ns, e => {
1988
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1989
- usedCallback(e);
1990
- });
1991
- } else {
1992
- usedCallback(null);
1993
- }
1994
- }
1995
- reloadResources(lngs, ns, callback) {
1996
- const deferred = defer();
1997
- if (!lngs) lngs = this.languages;
1998
- if (!ns) ns = this.options.ns;
1999
- if (!callback) callback = noop;
2000
- this.services.backendConnector.reload(lngs, ns, err => {
2001
- deferred.resolve();
2002
- callback(err);
2003
- });
2004
- return deferred;
2005
- }
2006
- use(module) {
2007
- if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
2008
- if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
2009
- if (module.type === 'backend') {
2010
- this.modules.backend = module;
2011
- }
2012
- if (module.type === 'logger' || module.log && module.warn && module.error) {
2013
- this.modules.logger = module;
2014
- }
2015
- if (module.type === 'languageDetector') {
2016
- this.modules.languageDetector = module;
2017
- }
2018
- if (module.type === 'i18nFormat') {
2019
- this.modules.i18nFormat = module;
2020
- }
2021
- if (module.type === 'postProcessor') {
2022
- postProcessor.addPostProcessor(module);
2023
- }
2024
- if (module.type === 'formatter') {
2025
- this.modules.formatter = module;
2026
- }
2027
- if (module.type === '3rdParty') {
2028
- this.modules.external.push(module);
2029
- }
2030
- return this;
2031
- }
2032
- setResolvedLanguage(l) {
2033
- if (!l || !this.languages) return;
2034
- if (['cimode', 'dev'].indexOf(l) > -1) return;
2035
- for (let li = 0; li < this.languages.length; li++) {
2036
- const lngInLngs = this.languages[li];
2037
- if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
2038
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2039
- this.resolvedLanguage = lngInLngs;
2040
- break;
2041
- }
2042
- }
2043
- }
2044
- changeLanguage(lng, callback) {
2045
- var _this2 = this;
2046
- this.isLanguageChangingTo = lng;
2047
- const deferred = defer();
2048
- this.emit('languageChanging', lng);
2049
- const setLngProps = l => {
2050
- this.language = l;
2051
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
2052
- this.resolvedLanguage = undefined;
2053
- this.setResolvedLanguage(l);
2054
- };
2055
- const done = (err, l) => {
2056
- if (l) {
2057
- setLngProps(l);
2058
- this.translator.changeLanguage(l);
2059
- this.isLanguageChangingTo = undefined;
2060
- this.emit('languageChanged', l);
2061
- this.logger.log('languageChanged', l);
2062
- } else {
2063
- this.isLanguageChangingTo = undefined;
2064
- }
2065
- deferred.resolve(function () {
2066
- return _this2.t(...arguments);
2067
- });
2068
- if (callback) callback(err, function () {
2069
- return _this2.t(...arguments);
2070
- });
2071
- };
2072
- const setLng = lngs => {
2073
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
2074
- const l = typeof lngs === 'string' ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);
2075
- if (l) {
2076
- if (!this.language) {
2077
- setLngProps(l);
2078
- }
2079
- if (!this.translator.language) this.translator.changeLanguage(l);
2080
- if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage) this.services.languageDetector.cacheUserLanguage(l);
2081
- }
2082
- this.loadResources(l, err => {
2083
- done(err, l);
2084
- });
2085
- };
2086
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2087
- setLng(this.services.languageDetector.detect());
2088
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2089
- if (this.services.languageDetector.detect.length === 0) {
2090
- this.services.languageDetector.detect().then(setLng);
2091
- } else {
2092
- this.services.languageDetector.detect(setLng);
2093
- }
2094
- } else {
2095
- setLng(lng);
2096
- }
2097
- return deferred;
2098
- }
2099
- getFixedT(lng, ns, keyPrefix) {
2100
- var _this3 = this;
2101
- const fixedT = function (key, opts) {
2102
- let options;
2103
- if (typeof opts !== 'object') {
2104
- for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
2105
- rest[_key3 - 2] = arguments[_key3];
2106
- }
2107
- options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2108
- } else {
2109
- options = {
2110
- ...opts
2111
- };
2112
- }
2113
- options.lng = options.lng || fixedT.lng;
2114
- options.lngs = options.lngs || fixedT.lngs;
2115
- options.ns = options.ns || fixedT.ns;
2116
- options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
2117
- const keySeparator = _this3.options.keySeparator || '.';
2118
- let resultKey;
2119
- if (options.keyPrefix && Array.isArray(key)) {
2120
- resultKey = key.map(k => `${options.keyPrefix}${keySeparator}${k}`);
2121
- } else {
2122
- resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;
2123
- }
2124
- return _this3.t(resultKey, options);
2125
- };
2126
- if (typeof lng === 'string') {
2127
- fixedT.lng = lng;
2128
- } else {
2129
- fixedT.lngs = lng;
2130
- }
2131
- fixedT.ns = ns;
2132
- fixedT.keyPrefix = keyPrefix;
2133
- return fixedT;
2134
- }
2135
- t() {
2136
- return this.translator && this.translator.translate(...arguments);
2137
- }
2138
- exists() {
2139
- return this.translator && this.translator.exists(...arguments);
2140
- }
2141
- setDefaultNamespace(ns) {
2142
- this.options.defaultNS = ns;
2143
- }
2144
- hasLoadedNamespace(ns) {
2145
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2146
- if (!this.isInitialized) {
2147
- this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
2148
- return false;
2149
- }
2150
- if (!this.languages || !this.languages.length) {
2151
- this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
2152
- return false;
2153
- }
2154
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
2155
- const fallbackLng = this.options ? this.options.fallbackLng : false;
2156
- const lastLng = this.languages[this.languages.length - 1];
2157
- if (lng.toLowerCase() === 'cimode') return true;
2158
- const loadNotPending = (l, n) => {
2159
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
2160
- return loadState === -1 || loadState === 2;
2161
- };
2162
- if (options.precheck) {
2163
- const preResult = options.precheck(this, loadNotPending);
2164
- if (preResult !== undefined) return preResult;
2165
- }
2166
- if (this.hasResourceBundle(lng, ns)) return true;
2167
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2168
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2169
- return false;
2170
- }
2171
- loadNamespaces(ns, callback) {
2172
- const deferred = defer();
2173
- if (!this.options.ns) {
2174
- if (callback) callback();
2175
- return Promise.resolve();
2176
- }
2177
- if (typeof ns === 'string') ns = [ns];
2178
- ns.forEach(n => {
2179
- if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2180
- });
2181
- this.loadResources(err => {
2182
- deferred.resolve();
2183
- if (callback) callback(err);
2184
- });
2185
- return deferred;
2186
- }
2187
- loadLanguages(lngs, callback) {
2188
- const deferred = defer();
2189
- if (typeof lngs === 'string') lngs = [lngs];
2190
- const preloaded = this.options.preload || [];
2191
- const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0);
2192
- if (!newLngs.length) {
2193
- if (callback) callback();
2194
- return Promise.resolve();
2195
- }
2196
- this.options.preload = preloaded.concat(newLngs);
2197
- this.loadResources(err => {
2198
- deferred.resolve();
2199
- if (callback) callback(err);
2200
- });
2201
- return deferred;
2202
- }
2203
- dir(lng) {
2204
- if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
2205
- if (!lng) return 'rtl';
2206
- const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
2207
- const languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());
2208
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
2209
- }
2210
- static createInstance() {
2211
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2212
- let callback = arguments.length > 1 ? arguments[1] : undefined;
2213
- return new I18n(options, callback);
2214
- }
2215
- cloneInstance() {
2216
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2217
- let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
2218
- const forkResourceStore = options.forkResourceStore;
2219
- if (forkResourceStore) delete options.forkResourceStore;
2220
- const mergedOptions = {
2221
- ...this.options,
2222
- ...options,
2223
- ...{
2224
- isClone: true
2225
- }
2226
- };
2227
- const clone = new I18n(mergedOptions);
2228
- if (options.debug !== undefined || options.prefix !== undefined) {
2229
- clone.logger = clone.logger.clone(options);
2230
- }
2231
- const membersToCopy = ['store', 'services', 'language'];
2232
- membersToCopy.forEach(m => {
2233
- clone[m] = this[m];
2234
- });
2235
- clone.services = {
2236
- ...this.services
2237
- };
2238
- clone.services.utils = {
2239
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2240
- };
2241
- if (forkResourceStore) {
2242
- clone.store = new ResourceStore(this.store.data, mergedOptions);
2243
- clone.services.resourceStore = clone.store;
2244
- }
2245
- clone.translator = new Translator(clone.services, mergedOptions);
2246
- clone.translator.on('*', function (event) {
2247
- for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
2248
- args[_key4 - 1] = arguments[_key4];
2249
- }
2250
- clone.emit(event, ...args);
2251
- });
2252
- clone.init(mergedOptions, callback);
2253
- clone.translator.options = mergedOptions;
2254
- clone.translator.backendConnector.services.utils = {
2255
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2256
- };
2257
- return clone;
2258
- }
2259
- toJSON() {
2260
- return {
2261
- options: this.options,
2262
- store: this.store,
2263
- language: this.language,
2264
- languages: this.languages,
2265
- resolvedLanguage: this.resolvedLanguage
2266
- };
2267
- }
2268
- }
2269
- const instance = I18n.createInstance();
2270
- instance.createInstance = I18n.createInstance;
2271
-
2272
- instance.createInstance;
2273
- instance.dir;
2274
- instance.init;
2275
- instance.loadResources;
2276
- instance.reloadResources;
2277
- instance.use;
2278
- instance.changeLanguage;
2279
- instance.getFixedT;
2280
- const t$2 = instance.t;
2281
- instance.exists;
2282
- instance.setDefaultNamespace;
2283
- instance.hasLoadedNamespace;
2284
- instance.loadNamespaces;
2285
- instance.loadLanguages;
2286
-
2287
- function getDefaultExportFromCjs (x) {
2288
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2289
- }
2290
-
2291
- /**
2292
- * This file automatically generated from `pre-publish.js`.
2293
- * Do not manually edit.
2294
- */
2295
-
2296
- var voidElements = {
2297
- "area": true,
2298
- "base": true,
2299
- "br": true,
2300
- "col": true,
2301
- "embed": true,
2302
- "hr": true,
2303
- "img": true,
2304
- "input": true,
2305
- "link": true,
2306
- "meta": true,
2307
- "param": true,
2308
- "source": true,
2309
- "track": true,
2310
- "wbr": true
22
+ var getDeliveriesPath = function getDeliveriesPath(webhooksPath) {
23
+ return "".concat(webhooksPath, "/:webhookId/deliveries");
2311
24
  };
2312
25
 
2313
- var e$1 = /*@__PURE__*/getDefaultExportFromCjs(voidElements);
2314
-
2315
- var t$1=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function n$1(n){var r={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},i=n.match(/<\/?([^\s]+?)[/\s>]/);if(i&&(r.name=i[1],(e$1[i[1]]||"/"===n.charAt(n.length-2))&&(r.voidElement=!0),r.name.startsWith("!--"))){var s=n.indexOf("--\x3e");return {type:"comment",comment:-1!==s?n.slice(4,s):""}}for(var a=new RegExp(t$1),c=null;null!==(c=a.exec(n));)if(c[0].trim())if(c[1]){var o=c[1].trim(),l=[o,""];o.indexOf("=")>-1&&(l=o.split("=")),r.attrs[l[0]]=l[1],a.lastIndex--;}else c[2]&&(r.attrs[c[2]]=c[3].trim().substring(1,c[3].length-1));return r}var r=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,i=/^\s*$/,s=Object.create(null);function a(e,t){switch(t.type){case"text":return e+t.content;case"tag":return e+="<"+t.name+(t.attrs?function(e){var t=[];for(var n in e)t.push(n+'="'+e[n]+'"');return t.length?" "+t.join(" "):""}(t.attrs):"")+(t.voidElement?"/>":">"),t.voidElement?e:e+t.children.reduce(a,"")+"</"+t.name+">";case"comment":return e+"\x3c!--"+t.comment+"--\x3e"}}var c={parse:function(e,t){t||(t={}),t.components||(t.components=s);var a,c=[],o=[],l=-1,m=!1;if(0!==e.indexOf("<")){var u=e.indexOf("<");c.push({type:"text",content:-1===u?e:e.substring(0,u)});}return e.replace(r,function(r,s){if(m){if(r!=="</"+a.name+">")return;m=!1;}var u,f="/"!==r.charAt(1),h=r.startsWith("\x3c!--"),p=s+r.length,d=e.charAt(p);if(h){var v=n$1(r);return l<0?(c.push(v),c):((u=o[l]).children.push(v),c)}if(f&&(l++,"tag"===(a=n$1(r)).type&&t.components[a.name]&&(a.type="component",m=!0),a.voidElement||m||!d||"<"===d||a.children.push({type:"text",content:e.slice(p,e.indexOf("<",p))}),0===l&&c.push(a),(u=o[l-1])&&u.children.push(a),o[l]=a),(!f||a.voidElement)&&(l>-1&&(a.voidElement||a.name===r.slice(2,-1))&&(l--,a=-1===l?c:o[l]),!m&&"<"!==d&&d)){u=-1===l?c:o[l].children;var x=e.indexOf("<",p),g=e.slice(p,-1===x?void 0:x);i.test(g)&&(g=" "),(x>-1&&l+u.length>=0||" "!==g)&&u.push({type:"text",content:g});}}),c},stringify:function(e){return e.reduce(function(e,t){return e+a("",t)},"")}};
2316
-
2317
- function warn() {
2318
- if (console && console.warn) {
2319
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2320
- args[_key] = arguments[_key];
2321
- }
2322
- if (typeof args[0] === 'string') args[0] = `react-i18next:: ${args[0]}`;
2323
- console.warn(...args);
2324
- }
2325
- }
2326
- const alreadyWarned = {};
2327
- function warnOnce() {
2328
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
2329
- args[_key2] = arguments[_key2];
2330
- }
2331
- if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return;
2332
- if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date();
2333
- warn(...args);
2334
- }
2335
- const loadedClb = (i18n, cb) => () => {
2336
- if (i18n.isInitialized) {
2337
- cb();
2338
- } else {
2339
- const initialized = () => {
2340
- setTimeout(() => {
2341
- i18n.off('initialized', initialized);
2342
- }, 0);
2343
- cb();
2344
- };
2345
- i18n.on('initialized', initialized);
2346
- }
2347
- };
2348
- function loadNamespaces(i18n, ns, cb) {
2349
- i18n.loadNamespaces(ns, loadedClb(i18n, cb));
2350
- }
2351
- function loadLanguages(i18n, lng, ns, cb) {
2352
- if (typeof ns === 'string') ns = [ns];
2353
- ns.forEach(n => {
2354
- if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);
2355
- });
2356
- i18n.loadLanguages(lng, loadedClb(i18n, cb));
2357
- }
2358
- function oldI18nextHasLoadedNamespace(ns, i18n) {
2359
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2360
- const lng = i18n.languages[0];
2361
- const fallbackLng = i18n.options ? i18n.options.fallbackLng : false;
2362
- const lastLng = i18n.languages[i18n.languages.length - 1];
2363
- if (lng.toLowerCase() === 'cimode') return true;
2364
- const loadNotPending = (l, n) => {
2365
- const loadState = i18n.services.backendConnector.state[`${l}|${n}`];
2366
- return loadState === -1 || loadState === 2;
2367
- };
2368
- if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false;
2369
- if (i18n.hasResourceBundle(lng, ns)) return true;
2370
- if (!i18n.services.backendConnector.backend || i18n.options.resources && !i18n.options.partialBundledLanguages) return true;
2371
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2372
- return false;
2373
- }
2374
- function hasLoadedNamespace(ns, i18n) {
2375
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2376
- if (!i18n.languages || !i18n.languages.length) {
2377
- warnOnce('i18n.languages were undefined or empty', i18n.languages);
2378
- return true;
2379
- }
2380
- const isNewerI18next = i18n.options.ignoreJSONStructure !== undefined;
2381
- if (!isNewerI18next) {
2382
- return oldI18nextHasLoadedNamespace(ns, i18n, options);
2383
- }
2384
- return i18n.hasLoadedNamespace(ns, {
2385
- lng: options.lng,
2386
- precheck: (i18nInstance, loadNotPending) => {
2387
- if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;
2388
- }
2389
- });
26
+ function _arrayLikeToArray(arr, len) {
27
+ if (len == null || len > arr.length) len = arr.length;
28
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
29
+ return arr2;
2390
30
  }
2391
31
 
2392
- const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
2393
- const htmlEntities = {
2394
- '&amp;': '&',
2395
- '&#38;': '&',
2396
- '&lt;': '<',
2397
- '&#60;': '<',
2398
- '&gt;': '>',
2399
- '&#62;': '>',
2400
- '&apos;': "'",
2401
- '&#39;': "'",
2402
- '&quot;': '"',
2403
- '&#34;': '"',
2404
- '&nbsp;': ' ',
2405
- '&#160;': ' ',
2406
- '&copy;': '©',
2407
- '&#169;': '©',
2408
- '&reg;': '®',
2409
- '&#174;': '®',
2410
- '&hellip;': '…',
2411
- '&#8230;': '…',
2412
- '&#x2F;': '/',
2413
- '&#47;': '/'
2414
- };
2415
- const unescapeHtmlEntity = m => htmlEntities[m];
2416
- const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);
2417
-
2418
- let defaultOptions = {
2419
- bindI18n: 'languageChanged',
2420
- bindI18nStore: '',
2421
- transEmptyNodeValue: '',
2422
- transSupportBasicHtmlNodes: true,
2423
- transWrapTextNodes: '',
2424
- transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
2425
- useSuspense: true,
2426
- unescape
2427
- };
2428
- function setDefaults() {
2429
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2430
- defaultOptions = {
2431
- ...defaultOptions,
2432
- ...options
2433
- };
2434
- }
2435
- function getDefaults() {
2436
- return defaultOptions;
32
+ function _arrayWithoutHoles(arr) {
33
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
2437
34
  }
2438
35
 
2439
- let i18nInstance;
2440
- function setI18n(instance) {
2441
- i18nInstance = instance;
2442
- }
2443
- function getI18n() {
2444
- return i18nInstance;
36
+ function _iterableToArray(iter) {
37
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
2445
38
  }
2446
39
 
2447
- function hasChildren(node, checkLength) {
2448
- if (!node) return false;
2449
- const base = node.props ? node.props.children : node.children;
2450
- if (checkLength) return base.length > 0;
2451
- return !!base;
2452
- }
2453
- function getChildren(node) {
2454
- if (!node) return [];
2455
- return node.props ? node.props.children : node.children;
40
+ function _unsupportedIterableToArray(o, minLen) {
41
+ if (!o) return;
42
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
43
+ var n = Object.prototype.toString.call(o).slice(8, -1);
44
+ if (n === "Object" && o.constructor) n = o.constructor.name;
45
+ if (n === "Map" || n === "Set") return Array.from(o);
46
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
2456
47
  }
2457
- function hasValidReactChildren(children) {
2458
- if (Object.prototype.toString.call(children) !== '[object Array]') return false;
2459
- return children.every(child => isValidElement(child));
48
+
49
+ function _nonIterableSpread() {
50
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2460
51
  }
2461
- function getAsArray(data) {
2462
- return Array.isArray(data) ? data : [data];
52
+
53
+ function _toConsumableArray(arr) {
54
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
2463
55
  }
2464
- function mergeProps(source, target) {
2465
- const newTarget = {
2466
- ...target
2467
- };
2468
- newTarget.props = Object.assign(source.props, target.props);
2469
- return newTarget;
56
+
57
+ function _arrayWithHoles(arr) {
58
+ if (Array.isArray(arr)) return arr;
2470
59
  }
2471
- function nodesToString(children, i18nOptions) {
2472
- if (!children) return '';
2473
- let stringNode = '';
2474
- const childrenArray = getAsArray(children);
2475
- const keepArray = i18nOptions.transSupportBasicHtmlNodes && i18nOptions.transKeepBasicHtmlNodesFor ? i18nOptions.transKeepBasicHtmlNodesFor : [];
2476
- childrenArray.forEach((child, childIndex) => {
2477
- if (typeof child === 'string') {
2478
- stringNode += `${child}`;
2479
- } else if (isValidElement(child)) {
2480
- const childPropsCount = Object.keys(child.props).length;
2481
- const shouldKeepChild = keepArray.indexOf(child.type) > -1;
2482
- const childChildren = child.props.children;
2483
- if (!childChildren && shouldKeepChild && childPropsCount === 0) {
2484
- stringNode += `<${child.type}/>`;
2485
- } else if (!childChildren && (!shouldKeepChild || childPropsCount !== 0)) {
2486
- stringNode += `<${childIndex}></${childIndex}>`;
2487
- } else if (child.props.i18nIsDynamicList) {
2488
- stringNode += `<${childIndex}></${childIndex}>`;
2489
- } else if (shouldKeepChild && childPropsCount === 1 && typeof childChildren === 'string') {
2490
- stringNode += `<${child.type}>${childChildren}</${child.type}>`;
2491
- } else {
2492
- const content = nodesToString(childChildren, i18nOptions);
2493
- stringNode += `<${childIndex}>${content}</${childIndex}>`;
2494
- }
2495
- } else if (child === null) {
2496
- warn(`Trans: the passed in value is invalid - seems you passed in a null child.`);
2497
- } else if (typeof child === 'object') {
2498
- const {
2499
- format,
2500
- ...clone
2501
- } = child;
2502
- const keys = Object.keys(clone);
2503
- if (keys.length === 1) {
2504
- const value = format ? `${keys[0]}, ${format}` : keys[0];
2505
- stringNode += `{{${value}}}`;
2506
- } else {
2507
- warn(`react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.`, child);
60
+
61
+ function _iterableToArrayLimit(arr, i) {
62
+ var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
63
+ if (null != _i) {
64
+ var _s,
65
+ _e,
66
+ _x,
67
+ _r,
68
+ _arr = [],
69
+ _n = !0,
70
+ _d = !1;
71
+ try {
72
+ if (_x = (_i = _i.call(arr)).next, 0 === i) {
73
+ if (Object(_i) !== _i) return;
74
+ _n = !1;
75
+ } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
76
+ } catch (err) {
77
+ _d = !0, _e = err;
78
+ } finally {
79
+ try {
80
+ if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return;
81
+ } finally {
82
+ if (_d) throw _e;
2508
83
  }
2509
- } else {
2510
- warn(`Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.`, child);
2511
84
  }
2512
- });
2513
- return stringNode;
2514
- }
2515
- function renderNodes(children, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) {
2516
- if (targetString === '') return [];
2517
- const keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
2518
- const emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.join('|')).test(targetString);
2519
- if (!children && !emptyChildrenButNeedsHandling) return [targetString];
2520
- const data = {};
2521
- function getData(childs) {
2522
- const childrenArray = getAsArray(childs);
2523
- childrenArray.forEach(child => {
2524
- if (typeof child === 'string') return;
2525
- if (hasChildren(child)) getData(getChildren(child));else if (typeof child === 'object' && !isValidElement(child)) Object.assign(data, child);
2526
- });
2527
- }
2528
- getData(children);
2529
- const ast = c.parse(`<0>${targetString}</0>`);
2530
- const opts = {
2531
- ...data,
2532
- ...combinedTOpts
2533
- };
2534
- function renderInner(child, node, rootReactNode) {
2535
- const childs = getChildren(child);
2536
- const mappedChildren = mapAST(childs, node.children, rootReactNode);
2537
- return hasValidReactChildren(childs) && mappedChildren.length === 0 ? childs : mappedChildren;
2538
- }
2539
- function pushTranslatedJSX(child, inner, mem, i, isVoid) {
2540
- if (child.dummy) child.children = inner;
2541
- mem.push(cloneElement(child, {
2542
- ...child.props,
2543
- key: i
2544
- }, isVoid ? undefined : inner));
2545
- }
2546
- function mapAST(reactNode, astNode, rootReactNode) {
2547
- const reactNodes = getAsArray(reactNode);
2548
- const astNodes = getAsArray(astNode);
2549
- return astNodes.reduce((mem, node, i) => {
2550
- const translationContent = node.children && node.children[0] && node.children[0].content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);
2551
- if (node.type === 'tag') {
2552
- let tmp = reactNodes[parseInt(node.name, 10)];
2553
- if (!tmp && rootReactNode.length === 1 && rootReactNode[0][node.name]) tmp = rootReactNode[0][node.name];
2554
- if (!tmp) tmp = {};
2555
- const child = Object.keys(node.attrs).length !== 0 ? mergeProps({
2556
- props: node.attrs
2557
- }, tmp) : tmp;
2558
- const isElement = isValidElement(child);
2559
- const isValidTranslationWithChildren = isElement && hasChildren(node, true) && !node.voidElement;
2560
- const isEmptyTransWithHTML = emptyChildrenButNeedsHandling && typeof child === 'object' && child.dummy && !isElement;
2561
- const isKnownComponent = typeof children === 'object' && children !== null && Object.hasOwnProperty.call(children, node.name);
2562
- if (typeof child === 'string') {
2563
- const value = i18n.services.interpolator.interpolate(child, opts, i18n.language);
2564
- mem.push(value);
2565
- } else if (hasChildren(child) || isValidTranslationWithChildren) {
2566
- const inner = renderInner(child, node, rootReactNode);
2567
- pushTranslatedJSX(child, inner, mem, i);
2568
- } else if (isEmptyTransWithHTML) {
2569
- const inner = mapAST(reactNodes, node.children, rootReactNode);
2570
- mem.push(cloneElement(child, {
2571
- ...child.props,
2572
- key: i
2573
- }, inner));
2574
- } else if (Number.isNaN(parseFloat(node.name))) {
2575
- if (isKnownComponent) {
2576
- const inner = renderInner(child, node, rootReactNode);
2577
- pushTranslatedJSX(child, inner, mem, i, node.voidElement);
2578
- } else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
2579
- if (node.voidElement) {
2580
- mem.push(createElement(node.name, {
2581
- key: `${node.name}-${i}`
2582
- }));
2583
- } else {
2584
- const inner = mapAST(reactNodes, node.children, rootReactNode);
2585
- mem.push(createElement(node.name, {
2586
- key: `${node.name}-${i}`
2587
- }, inner));
2588
- }
2589
- } else if (node.voidElement) {
2590
- mem.push(`<${node.name} />`);
2591
- } else {
2592
- const inner = mapAST(reactNodes, node.children, rootReactNode);
2593
- mem.push(`<${node.name}>${inner}</${node.name}>`);
2594
- }
2595
- } else if (typeof child === 'object' && !isElement) {
2596
- const content = node.children[0] ? translationContent : null;
2597
- if (content) mem.push(content);
2598
- } else if (node.children.length === 1 && translationContent) {
2599
- mem.push(cloneElement(child, {
2600
- ...child.props,
2601
- key: i
2602
- }, translationContent));
2603
- } else {
2604
- mem.push(cloneElement(child, {
2605
- ...child.props,
2606
- key: i
2607
- }));
2608
- }
2609
- } else if (node.type === 'text') {
2610
- const wrapTextNodes = i18nOptions.transWrapTextNodes;
2611
- const content = shouldUnescape ? i18nOptions.unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);
2612
- if (wrapTextNodes) {
2613
- mem.push(createElement(wrapTextNodes, {
2614
- key: `${node.name}-${i}`
2615
- }, content));
2616
- } else {
2617
- mem.push(content);
2618
- }
2619
- }
2620
- return mem;
2621
- }, []);
2622
- }
2623
- const result = mapAST([{
2624
- dummy: true,
2625
- children: children || []
2626
- }], ast, getAsArray(children || []));
2627
- return getChildren(result[0]);
2628
- }
2629
- function Trans$1(_ref) {
2630
- let {
2631
- children,
2632
- count,
2633
- parent,
2634
- i18nKey,
2635
- context,
2636
- tOptions = {},
2637
- values,
2638
- defaults,
2639
- components,
2640
- ns,
2641
- i18n: i18nFromProps,
2642
- t: tFromProps,
2643
- shouldUnescape,
2644
- ...additionalProps
2645
- } = _ref;
2646
- const i18n = i18nFromProps || getI18n();
2647
- if (!i18n) {
2648
- warnOnce('You will need to pass in an i18next instance by using i18nextReactModule');
2649
- return children;
85
+ return _arr;
2650
86
  }
2651
- const t = tFromProps || i18n.t.bind(i18n) || (k => k);
2652
- if (context) tOptions.context = context;
2653
- const reactI18nextOptions = {
2654
- ...getDefaults(),
2655
- ...(i18n.options && i18n.options.react)
2656
- };
2657
- let namespaces = ns || t.ns || i18n.options && i18n.options.defaultNS;
2658
- namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
2659
- const defaultValue = defaults || nodesToString(children, reactI18nextOptions) || reactI18nextOptions.transEmptyNodeValue || i18nKey;
2660
- const {
2661
- hashTransKey
2662
- } = reactI18nextOptions;
2663
- const key = i18nKey || (hashTransKey ? hashTransKey(defaultValue) : defaultValue);
2664
- const interpolationOverride = values ? tOptions.interpolation : {
2665
- interpolation: {
2666
- ...tOptions.interpolation,
2667
- prefix: '#$?',
2668
- suffix: '?$#'
2669
- }
2670
- };
2671
- const combinedTOpts = {
2672
- ...tOptions,
2673
- count,
2674
- ...values,
2675
- ...interpolationOverride,
2676
- defaultValue,
2677
- ns: namespaces
2678
- };
2679
- const translation = key ? t(key, combinedTOpts) : defaultValue;
2680
- const content = renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);
2681
- const useAsParent = parent !== undefined ? parent : reactI18nextOptions.defaultTransParent;
2682
- return useAsParent ? createElement(useAsParent, additionalProps, content) : content;
2683
87
  }
2684
88
 
2685
- const initReactI18next = {
2686
- type: '3rdParty',
2687
- init(instance) {
2688
- setDefaults(instance.options.react);
2689
- setI18n(instance);
2690
- }
2691
- };
2692
-
2693
- const I18nContext = createContext();
2694
- class ReportNamespaces {
2695
- constructor() {
2696
- this.usedNamespaces = {};
2697
- }
2698
- addUsedNamespaces(namespaces) {
2699
- namespaces.forEach(ns => {
2700
- if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;
2701
- });
2702
- }
2703
- getUsedNamespaces() {
2704
- return Object.keys(this.usedNamespaces);
2705
- }
89
+ function _nonIterableRest() {
90
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2706
91
  }
2707
92
 
2708
- function Trans(_ref) {
2709
- let {
2710
- children,
2711
- count,
2712
- parent,
2713
- i18nKey,
2714
- context,
2715
- tOptions = {},
2716
- values,
2717
- defaults,
2718
- components,
2719
- ns,
2720
- i18n: i18nFromProps,
2721
- t: tFromProps,
2722
- shouldUnescape,
2723
- ...additionalProps
2724
- } = _ref;
2725
- const {
2726
- i18n: i18nFromContext,
2727
- defaultNS: defaultNSFromContext
2728
- } = useContext(I18nContext) || {};
2729
- const i18n = i18nFromProps || i18nFromContext || getI18n();
2730
- const t = tFromProps || i18n && i18n.t.bind(i18n);
2731
- return Trans$1({
2732
- children,
2733
- count,
2734
- parent,
2735
- i18nKey,
2736
- context,
2737
- tOptions,
2738
- values,
2739
- defaults,
2740
- components,
2741
- ns: ns || t && t.ns || defaultNSFromContext || i18n && i18n.options && i18n.options.defaultNS,
2742
- i18n,
2743
- t: tFromProps,
2744
- shouldUnescape,
2745
- ...additionalProps
2746
- });
93
+ function _slicedToArray(arr, i) {
94
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
2747
95
  }
2748
96
 
2749
- const usePrevious = (value, ignore) => {
2750
- const ref = useRef();
2751
- useEffect(() => {
2752
- ref.current = ignore ? ref.current : value;
2753
- }, [value, ignore]);
2754
- return ref.current;
2755
- };
2756
- function useTranslation(ns) {
2757
- let props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2758
- const {
2759
- i18n: i18nFromProps
2760
- } = props;
2761
- const {
2762
- i18n: i18nFromContext,
2763
- defaultNS: defaultNSFromContext
2764
- } = useContext(I18nContext) || {};
2765
- const i18n = i18nFromProps || i18nFromContext || getI18n();
2766
- if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
2767
- if (!i18n) {
2768
- warnOnce('You will need to pass in an i18next instance by using initReactI18next');
2769
- const notReadyT = (k, optsOrDefaultValue) => {
2770
- if (typeof optsOrDefaultValue === 'string') return optsOrDefaultValue;
2771
- if (optsOrDefaultValue && typeof optsOrDefaultValue === 'object' && typeof optsOrDefaultValue.defaultValue === 'string') return optsOrDefaultValue.defaultValue;
2772
- return Array.isArray(k) ? k[k.length - 1] : k;
2773
- };
2774
- const retNotReady = [notReadyT, {}, false];
2775
- retNotReady.t = notReadyT;
2776
- retNotReady.i18n = {};
2777
- retNotReady.ready = false;
2778
- return retNotReady;
2779
- }
2780
- if (i18n.options.react && i18n.options.react.wait !== undefined) warnOnce('It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');
2781
- const i18nOptions = {
2782
- ...getDefaults(),
2783
- ...i18n.options.react,
2784
- ...props
2785
- };
2786
- const {
2787
- useSuspense,
2788
- keyPrefix
2789
- } = i18nOptions;
2790
- let namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
2791
- namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
2792
- if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces);
2793
- const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));
2794
- function getT() {
2795
- return i18n.getFixedT(props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
2796
- }
2797
- const [t, setT] = useState(getT);
2798
- let joinedNS = namespaces.join();
2799
- if (props.lng) joinedNS = `${props.lng}${joinedNS}`;
2800
- const previousJoinedNS = usePrevious(joinedNS);
2801
- const isMounted = useRef(true);
2802
- useEffect(() => {
2803
- const {
2804
- bindI18n,
2805
- bindI18nStore
2806
- } = i18nOptions;
2807
- isMounted.current = true;
2808
- if (!ready && !useSuspense) {
2809
- if (props.lng) {
2810
- loadLanguages(i18n, props.lng, namespaces, () => {
2811
- if (isMounted.current) setT(getT);
2812
- });
2813
- } else {
2814
- loadNamespaces(i18n, namespaces, () => {
2815
- if (isMounted.current) setT(getT);
2816
- });
2817
- }
2818
- }
2819
- if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {
2820
- setT(getT);
2821
- }
2822
- function boundReset() {
2823
- if (isMounted.current) setT(getT);
2824
- }
2825
- if (bindI18n && i18n) i18n.on(bindI18n, boundReset);
2826
- if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset);
2827
- return () => {
2828
- isMounted.current = false;
2829
- if (bindI18n && i18n) bindI18n.split(' ').forEach(e => i18n.off(e, boundReset));
2830
- if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset));
2831
- };
2832
- }, [i18n, joinedNS]);
2833
- const isInitial = useRef(true);
2834
- useEffect(() => {
2835
- if (isMounted.current && !isInitial.current) {
2836
- setT(getT);
2837
- }
2838
- isInitial.current = false;
2839
- }, [i18n, keyPrefix]);
2840
- const ret = [t, i18n, ready];
2841
- ret.t = t;
2842
- ret.i18n = i18n;
2843
- ret.ready = ready;
2844
- if (ready) return ret;
2845
- if (!ready && !useSuspense) return ret;
2846
- throw new Promise(resolve => {
2847
- if (props.lng) {
2848
- loadLanguages(i18n, props.lng, namespaces, () => resolve());
2849
- } else {
2850
- loadNamespaces(i18n, namespaces, () => resolve());
97
+ var queryClient = new QueryClient({
98
+ queryCache: new QueryCache(),
99
+ defaultOptions: {
100
+ queries: {
101
+ staleTime: DEFAULT_STALE_TIME
2851
102
  }
2852
- });
2853
- }
103
+ }
104
+ });
2854
105
 
2855
- var entity = {
2856
- webhook: "webhook",
2857
- configure: "Configure"
2858
- };
2859
- var buttons = {
2860
- saveChanges: "Save changes",
2861
- cancel: "Cancel",
2862
- "delete": "Delete"
2863
- };
2864
- var errors = {
2865
- webhook: {
2866
- required: "Please enter your endpoint URL",
2867
- invalidUrl: "Please enter a valid URL",
2868
- invalidUrlProtocol: "Please enter a valid URL. URL must begin with http or https",
2869
- urlNotUnique: "Endpoint URL must be unique"
2870
- }
2871
- };
2872
- var delivery = {
2873
- title: "Deliveries",
2874
- redeliver: "Redeliver",
2875
- redelivery: "redelivery",
2876
- request: "Request",
2877
- response: "Response",
2878
- header: "Header",
2879
- body: "Body",
2880
- payload: "Payload",
2881
- empty: {
2882
- title: "There are no deliveries to show.",
2883
- description: "No events have been sent to this webhook"
2884
- }
2885
- };
2886
- var webhook = {
2887
- title: "Webhooks",
2888
- description: "All new action event details will be posted to the configured webhook URLs",
2889
- empty: "There are no webhooks defined currently",
2890
- add: "Add new webhook",
2891
- endpoint: "Endpoint",
2892
- endpointPlaceholder: "Enter endpoint URL",
2893
- secret: "Secret key (optional) <helpLink><info></helpLink>",
2894
- secretPlaceholder: "Enter secret key",
2895
- edit: "Edit Webhook"
106
+ /* eslint-disable @bigbinary/neeto/file-name-and-export-name-standards */
107
+ var withReactQuery = function withReactQuery(Component) {
108
+ var QueryWrapper = function QueryWrapper(props) {
109
+ return /*#__PURE__*/React.createElement(QueryClientProvider, {
110
+ client: queryClient
111
+ }, /*#__PURE__*/React.createElement(Component, props), /*#__PURE__*/React.createElement(ReactQueryDevtools, {
112
+ initialIsOpen: false,
113
+ position: "bottom-right"
114
+ }));
115
+ };
116
+ return QueryWrapper;
2896
117
  };
2897
- var operation = {
2898
- edit: "Edit",
2899
- "delete": "Delete"
118
+
119
+ var baseUrl$2 = "/webhooks/deliveries";
120
+ var fetch$1 = function fetch(params) {
121
+ return axios.get(baseUrl$2, {
122
+ params: params
123
+ });
2900
124
  };
2901
- var alert = {
2902
- "delete": {
2903
- title: "Delete {{entity}}?",
2904
- message: "You are deleting the {{entity}}."
2905
- }
125
+ var show$1 = function show(id) {
126
+ return axios.get("".concat(baseUrl$2, "/").concat(id));
2906
127
  };
2907
- var en = {
2908
- entity: entity,
2909
- buttons: buttons,
2910
- errors: errors,
2911
- delivery: delivery,
2912
- webhook: webhook,
2913
- operation: operation,
2914
- alert: alert
128
+ var redeliver = function redeliver(id) {
129
+ return axios.post("".concat(baseUrl$2, "/").concat(id, "/redeliver"));
2915
130
  };
2916
-
2917
- instance.use(initReactI18next).init({
2918
- resources: {
2919
- en: {
2920
- translation: en
2921
- }
2922
- },
2923
- fallbackLng: "en"
2924
- });
2925
-
2926
- var getDeliveriesPath = function getDeliveriesPath(webhooksPath) {
2927
- return "".concat(webhooksPath, "/:webhookId/deliveries");
131
+ var deliveriesApi = {
132
+ fetch: fetch$1,
133
+ show: show$1,
134
+ redeliver: redeliver
2928
135
  };
2929
136
 
2930
- function _arrayLikeToArray(arr, len) {
2931
- if (len == null || len > arr.length) len = arr.length;
2932
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
2933
- return arr2;
2934
- }
2935
-
2936
- function _arrayWithoutHoles(arr) {
2937
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
2938
- }
2939
-
2940
- function _iterableToArray(iter) {
2941
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
2942
- }
2943
-
2944
- function _unsupportedIterableToArray(o, minLen) {
2945
- if (!o) return;
2946
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
2947
- var n = Object.prototype.toString.call(o).slice(8, -1);
2948
- if (n === "Object" && o.constructor) n = o.constructor.name;
2949
- if (n === "Map" || n === "Set") return Array.from(o);
2950
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
2951
- }
137
+ var QUERY_KEYS = {
138
+ DELIVERY_LIST: "delivery-list",
139
+ DELIVERY_DETAILS: "delivery-details",
140
+ WEBHOOK_LIST: "webhook-list",
141
+ WEBHOOK_DETAILS: "webhook-details",
142
+ EVENTS_LIST: "events-list"
143
+ };
144
+ var DELIVERY_STALE_TIME = 3200000; // 1 hour
145
+ var WEBHOOK_STALE_TIME = 3200000; // 1 hour
146
+ var POST_REDELIVERY_ON_SUCCESS_TIMEOUT = 5000; // 5 seconds
2952
147
 
2953
- function _nonIterableSpread() {
2954
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2955
- }
148
+ var useFetchDeliveries = function useFetchDeliveries(params) {
149
+ return useQuery([QUERY_KEYS.DELIVERY_LIST, params], function () {
150
+ return deliveriesApi.fetch(params);
151
+ }, {
152
+ staleTime: DELIVERY_STALE_TIME
153
+ });
154
+ };
155
+ var useShowDelivery = function useShowDelivery(id) {
156
+ return useQuery([QUERY_KEYS.DELIVERY_DETAILS, id], function () {
157
+ return deliveriesApi.show(id);
158
+ }, {
159
+ staleTime: DELIVERY_STALE_TIME
160
+ });
161
+ };
162
+ var useRedeliverWebhook = function useRedeliverWebhook() {
163
+ var queryClient = useQueryClient();
164
+ return useMutation(deliveriesApi.redeliver, {
165
+ onSuccess: function onSuccess() {
166
+ setTimeout(function () {
167
+ return queryClient.invalidateQueries(QUERY_KEYS.DELIVERY_LIST);
168
+ }, POST_REDELIVERY_ON_SUCCESS_TIMEOUT);
169
+ }
170
+ });
171
+ };
2956
172
 
2957
- function _toConsumableArray(arr) {
2958
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
2959
- }
173
+ var DEFAULT_PAGE_SIZE = 10;
2960
174
 
2961
175
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2962
176
  try {
@@ -2989,6 +203,10 @@ function _asyncToGenerator(fn) {
2989
203
  };
2990
204
  }
2991
205
 
206
+ function getDefaultExportFromCjs (x) {
207
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
208
+ }
209
+
2992
210
  var regeneratorRuntime$1 = {exports: {}};
2993
211
 
2994
212
  var _typeof$1 = {exports: {}};
@@ -3338,137 +556,24 @@ try {
3338
556
 
3339
557
  var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator);
3340
558
 
3341
- var queryClient = new QueryClient({
3342
- queryCache: new QueryCache()
3343
- });
3344
-
3345
- var withReactQuery = function withReactQuery(Component) {
3346
- var QueryWrapper = function QueryWrapper(props) {
3347
- return /*#__PURE__*/React.createElement(QueryClientProvider, {
3348
- client: queryClient
3349
- }, /*#__PURE__*/React.createElement(Component, props), /*#__PURE__*/React.createElement(ReactQueryDevtools, {
3350
- initialIsOpen: false,
3351
- position: "bottom-right"
3352
- }));
3353
- };
3354
- return QueryWrapper;
3355
- };
3356
-
3357
- var baseUrl$1 = "/webhooks/deliveries";
3358
- var fetch$1 = function fetch(webhook_id) {
3359
- return axios.get(baseUrl$1, {
3360
- params: {
3361
- webhook_id: webhook_id
3362
- }
3363
- });
3364
- };
3365
- var show$1 = function show(id) {
3366
- return axios.get("".concat(baseUrl$1, "/").concat(id));
3367
- };
3368
- var redeliver = function redeliver(id) {
3369
- return axios.post("".concat(baseUrl$1, "/").concat(id, "/redeliver"));
3370
- };
3371
- var deliveriesApi = {
3372
- fetch: fetch$1,
3373
- show: show$1,
3374
- redeliver: redeliver
3375
- };
3376
-
3377
- var QUERY_KEYS = {
3378
- DELIVERY_LIST: "delivery-list",
3379
- DELIVERY_DETAILS: "delivery-details",
3380
- WEBHOOK_LIST: "webhook-list",
3381
- WEBHOOK_DETAILS: "webhook-details"
3382
- };
3383
- var DELIVERY_STALE_TIME = 3200000; // 1 hour
3384
- var WEBHOOK_STALE_TIME = 3200000; // 1 hour
3385
- var POST_REDELIVERY_ON_SUCCESS_TIMEOUT = 5000; // 5 seconds
3386
-
3387
- var useFetchDeliveries = function useFetchDeliveries(webhookId) {
3388
- return useQuery([QUERY_KEYS.DELIVERY_LIST, webhookId], function () {
3389
- return deliveriesApi.fetch(webhookId);
3390
- }, {
3391
- staleTime: DELIVERY_STALE_TIME
3392
- });
3393
- };
3394
- var useShowDelivery = function useShowDelivery(id) {
3395
- return useQuery([QUERY_KEYS.DELIVERY_DETAILS, id], function () {
3396
- return deliveriesApi.show(id);
3397
- }, {
3398
- staleTime: DELIVERY_STALE_TIME
3399
- });
3400
- };
3401
- var useRedeliverWebhook = function useRedeliverWebhook() {
3402
- var queryClient = useQueryClient();
3403
- return useMutation(deliveriesApi.redeliver, {
3404
- onSuccess: function onSuccess() {
3405
- setTimeout(function () {
3406
- return queryClient.invalidateQueries(QUERY_KEYS.DELIVERY_LIST);
3407
- }, POST_REDELIVERY_ON_SUCCESS_TIMEOUT);
3408
- }
3409
- });
3410
- };
3411
-
3412
559
  var DELIVERY_TAB = {
3413
560
  response: "response",
3414
561
  request: "request"
3415
562
  };
3416
- var DELIVERY_STATUS = {
3417
- failure: "failure",
3418
- success: "success"
3419
- };
3420
-
3421
- function _arrayWithHoles(arr) {
3422
- if (Array.isArray(arr)) return arr;
3423
- }
3424
-
3425
- function _iterableToArrayLimit(arr, i) {
3426
- var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
3427
- if (null != _i) {
3428
- var _s,
3429
- _e,
3430
- _x,
3431
- _r,
3432
- _arr = [],
3433
- _n = !0,
3434
- _d = !1;
3435
- try {
3436
- if (_x = (_i = _i.call(arr)).next, 0 === i) {
3437
- if (Object(_i) !== _i) return;
3438
- _n = !1;
3439
- } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
3440
- } catch (err) {
3441
- _d = !0, _e = err;
3442
- } finally {
3443
- try {
3444
- if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return;
3445
- } finally {
3446
- if (_d) throw _e;
3447
- }
3448
- }
3449
- return _arr;
3450
- }
3451
- }
3452
-
3453
- function _nonIterableRest() {
3454
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
3455
- }
3456
-
3457
- function _slicedToArray(arr, i) {
3458
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
3459
- }
3460
563
 
3461
564
  var Snippet = function Snippet(_ref) {
3462
565
  var children = _ref.children;
3463
566
  return /*#__PURE__*/React.createElement("div", {
3464
- className: "my-2 whitespace-pre-wrap break-all rounded border border-gray-300 bg-gray-100 p-4"
567
+ className: "neeto-ui-rounded neeto-ui-border-gray-300 neeto-ui-bg-gray-100 my-2 whitespace-pre-wrap break-all border p-4"
3465
568
  }, children);
3466
569
  };
3467
570
 
3468
- var DeliveryItem = function DeliveryItem(_ref) {
3469
- var deliveryId = _ref.deliveryId,
3470
- isRedelivering = _ref.isRedelivering,
3471
- onRedeliverClick = _ref.onRedeliverClick;
571
+ var TransactionDetails = function TransactionDetails(_ref) {
572
+ var delivery = _ref.delivery;
573
+ var deliveryId = delivery.id,
574
+ status = delivery.status,
575
+ identifier = delivery.identifier,
576
+ responseStatusCode = delivery.responseStatusCode;
3472
577
  var _useState = useState(DELIVERY_TAB.request),
3473
578
  _useState2 = _slicedToArray(_useState, 2),
3474
579
  activeHeader = _useState2[0],
@@ -3480,176 +585,289 @@ var DeliveryItem = function DeliveryItem(_ref) {
3480
585
  _useShowDelivery$data = _useShowDelivery.data,
3481
586
  _useShowDelivery$data2 = _useShowDelivery$data === void 0 ? {} : _useShowDelivery$data,
3482
587
  _useShowDelivery$data3 = _useShowDelivery$data2.delivery,
3483
- delivery = _useShowDelivery$data3 === void 0 ? {} : _useShowDelivery$data3;
588
+ deliveryDetails = _useShowDelivery$data3 === void 0 ? {} : _useShowDelivery$data3;
3484
589
  if (isLoading) {
3485
590
  return /*#__PURE__*/React.createElement("div", {
3486
- className: "flex items-center justify-center py-6"
591
+ className: "flex w-full items-center justify-center py-6"
3487
592
  }, /*#__PURE__*/React.createElement(Spinner, null));
3488
593
  }
3489
- return /*#__PURE__*/React.createElement("div", {
3490
- className: "p-4"
3491
- }, /*#__PURE__*/React.createElement(Tab, {
3492
- className: "mb-4"
3493
- }, /*#__PURE__*/React.createElement(Tab.Item, {
594
+ return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
595
+ className: "neeto-ui-bg-white sticky top-0 mb-2 flex w-full flex-col"
596
+ }, /*#__PURE__*/React.createElement("div", {
597
+ className: "flex w-full flex-col space-y-2 pb-4"
598
+ }, /*#__PURE__*/React.createElement("span", {
599
+ className: "flex items-center space-x-1"
600
+ }, t("neetoWebhooks.delivery.identifier"), ":", /*#__PURE__*/React.createElement(Typography, {
601
+ className: "px-2 font-bold",
602
+ style: "body2"
603
+ }, identifier)), /*#__PURE__*/React.createElement("span", {
604
+ className: "flex items-center"
605
+ }, t("neetoWebhooks.common.responseStatus"), ":", /*#__PURE__*/React.createElement(Typography, {
606
+ className: "px-2 font-bold",
607
+ style: "body2"
608
+ }, responseStatusCode), /*#__PURE__*/React.createElement(Tag, {
609
+ style: status === "success" ? "success" : "warning"
610
+ }, status))), /*#__PURE__*/React.createElement(Tab, null, /*#__PURE__*/React.createElement(Tab.Item, {
3494
611
  active: activeHeader === DELIVERY_TAB.request,
3495
612
  onClick: function onClick() {
3496
613
  return setActiveHeader(DELIVERY_TAB.request);
3497
614
  }
3498
- }, t("delivery.request")), /*#__PURE__*/React.createElement(Tab.Item, {
615
+ }, t("neetoWebhooks.delivery.request")), /*#__PURE__*/React.createElement(Tab.Item, {
3499
616
  active: activeHeader === DELIVERY_TAB.response,
3500
617
  onClick: function onClick() {
3501
618
  return setActiveHeader(DELIVERY_TAB.response);
3502
619
  }
3503
- }, t("delivery.response")), /*#__PURE__*/React.createElement("div", {
3504
- className: "flex flex-1 justify-end"
3505
- }, /*#__PURE__*/React.createElement(Button, {
3506
- className: "mr-2 mb-2",
3507
- label: t("delivery.redeliver"),
3508
- loading: isRedelivering,
3509
- style: "secondary",
3510
- onClick: function onClick() {
3511
- return onRedeliverClick(delivery.id);
3512
- }
3513
- }))), activeHeader === DELIVERY_TAB.request ? /*#__PURE__*/React.createElement("div", {
620
+ }, t("neetoWebhooks.delivery.response")))), /*#__PURE__*/React.createElement("div", {
621
+ className: "mt-2"
622
+ }, activeHeader === DELIVERY_TAB.request ? /*#__PURE__*/React.createElement("div", {
3514
623
  className: "space-y-4"
3515
624
  }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Typography, {
3516
625
  style: "h5"
3517
- }, t("delivery.header")), /*#__PURE__*/React.createElement(Snippet, null, delivery.requestHeader)), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Typography, {
626
+ }, t("neetoWebhooks.delivery.header")), /*#__PURE__*/React.createElement(Snippet, null, deliveryDetails.requestHeader)), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Typography, {
3518
627
  style: "h5"
3519
- }, t("delivery.payload")), /*#__PURE__*/React.createElement(Snippet, null, JSON.stringify(JSON.parse(delivery.requestBody), null, 2)))) : /*#__PURE__*/React.createElement("div", {
628
+ }, t("neetoWebhooks.delivery.payload")), /*#__PURE__*/React.createElement(Snippet, null, JSON.stringify(JSON.parse(deliveryDetails.requestBody), null, 2)))) : /*#__PURE__*/React.createElement("div", {
3520
629
  className: "space-y-4"
3521
630
  }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Typography, {
3522
631
  style: "h5"
3523
- }, t("delivery.header")), /*#__PURE__*/React.createElement(Snippet, null, delivery.responseHeader)), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Typography, {
632
+ }, t("neetoWebhooks.delivery.header")), /*#__PURE__*/React.createElement(Snippet, null, deliveryDetails.responseHeader)), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Typography, {
3524
633
  style: "h5"
3525
- }, t("delivery.body")), /*#__PURE__*/React.createElement(Snippet, null, delivery.responseBody))));
634
+ }, t("neetoWebhooks.delivery.body")), /*#__PURE__*/React.createElement(Snippet, null, deliveryDetails.responseBody)))));
3526
635
  };
3527
636
 
3528
- var Deliveries = function Deliveries(_ref) {
3529
- var webhooksUrl = _ref.webhooksUrl,
3530
- hostBreadcrumbs = _ref.breadcrumbs;
637
+ var Details = function Details(_ref) {
638
+ var delivery = _ref.delivery,
639
+ onClose = _ref.onClose;
640
+ var createdAt = delivery.createdAt,
641
+ id = delivery.id,
642
+ event = delivery.event;
3531
643
  var _useTranslation = useTranslation(),
3532
644
  t = _useTranslation.t;
3533
- var _useParams = useParams(),
3534
- webhookId = _useParams.webhookId;
3535
- var _useFetchDeliveries = useFetchDeliveries(webhookId),
3536
- isLoading = _useFetchDeliveries.isLoading,
3537
- _useFetchDeliveries$d = _useFetchDeliveries.data,
3538
- _useFetchDeliveries$d2 = _useFetchDeliveries$d === void 0 ? {} : _useFetchDeliveries$d,
3539
- endpoint = _useFetchDeliveries$d2.endpoint,
3540
- _useFetchDeliveries$d3 = _useFetchDeliveries$d2.deliveries,
3541
- deliveries = _useFetchDeliveries$d3 === void 0 ? [] : _useFetchDeliveries$d3;
3542
645
  var _useRedeliverWebhook = useRedeliverWebhook(),
3543
646
  isRedelivering = _useRedeliverWebhook.isLoading,
3544
647
  redeliverWebhook = _useRedeliverWebhook.mutateAsync;
3545
- var onRedeliverClick = /*#__PURE__*/function () {
3546
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(deliveryId) {
648
+ var handleRedeliverClick = /*#__PURE__*/function () {
649
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
3547
650
  return _regeneratorRuntime.wrap(function _callee$(_context) {
3548
651
  while (1) switch (_context.prev = _context.next) {
3549
652
  case 0:
3550
653
  _context.next = 2;
3551
- return redeliverWebhook(deliveryId);
654
+ return redeliverWebhook(id);
3552
655
  case 2:
3553
656
  case "end":
3554
657
  return _context.stop();
3555
658
  }
3556
659
  }, _callee);
3557
660
  }));
3558
- return function onRedeliverClick(_x) {
661
+ return function handleRedeliverClick() {
3559
662
  return _ref2.apply(this, arguments);
3560
663
  };
3561
664
  }();
665
+ return /*#__PURE__*/React.createElement(Pane, {
666
+ isOpen: isPresent(delivery),
667
+ size: "large",
668
+ onClose: onClose
669
+ }, /*#__PURE__*/React.createElement(Pane.Header, null, /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DateFormat.Date, {
670
+ date: createdAt,
671
+ typographyProps: {
672
+ style: "h2",
673
+ weight: "semibold"
674
+ }
675
+ }), /*#__PURE__*/React.createElement("span", null, " \u2022 "), /*#__PURE__*/React.createElement(DateFormat.Time, {
676
+ date: createdAt,
677
+ typographyProps: {
678
+ style: "h2",
679
+ weight: "normal"
680
+ }
681
+ }))), /*#__PURE__*/React.createElement(Pane.Body, null, isPresent(delivery) && /*#__PURE__*/React.createElement(TransactionDetails, {
682
+ delivery: delivery
683
+ })), /*#__PURE__*/React.createElement(Pane.Footer, {
684
+ className: "gap-x-2"
685
+ }, event && /*#__PURE__*/React.createElement(Button, {
686
+ disabled: isRedelivering,
687
+ label: t("neetoWebhooks.delivery.redeliver"),
688
+ loading: isRedelivering,
689
+ style: "primary",
690
+ onClick: handleRedeliverClick
691
+ }), /*#__PURE__*/React.createElement(Button, {
692
+ label: t("neetoWebhooks.buttons.cancel"),
693
+ style: "text",
694
+ onClick: onClose
695
+ })));
696
+ };
697
+
698
+ var buildColumns$1 = function buildColumns(_ref) {
699
+ var handleDetailsClick = _ref.handleDetailsClick;
700
+ return [{
701
+ title: t$1("neetoWebhooks.delivery.identifier", SINGULAR),
702
+ key: "identifier",
703
+ width: 300,
704
+ render: function render(_ref2) {
705
+ var identifier = _ref2.identifier,
706
+ redelivery = _ref2.redelivery;
707
+ return /*#__PURE__*/React.createElement("div", {
708
+ className: "flex space-x-1"
709
+ }, /*#__PURE__*/React.createElement(Typography, {
710
+ className: "px-2",
711
+ style: "body2",
712
+ weight: "semibold"
713
+ }, identifier), redelivery && /*#__PURE__*/React.createElement(Tag, {
714
+ style: "info"
715
+ }, t$1("neetoWebhooks.delivery.redelivery")));
716
+ }
717
+ }, {
718
+ title: t$1("neetoWebhooks.tableHeaders.createdAt"),
719
+ key: "createdAt",
720
+ dataIndex: "createdAt",
721
+ width: 300,
722
+ render: function render(createdAt) {
723
+ return /*#__PURE__*/React.createElement("div", {
724
+ className: "flex items-center justify-between space-x-1"
725
+ }, /*#__PURE__*/React.createElement(Typography, null, /*#__PURE__*/React.createElement(DateFormat.Date, {
726
+ date: createdAt,
727
+ typographyProps: {
728
+ style: "body1",
729
+ weight: "semibold"
730
+ }
731
+ }), /*#__PURE__*/React.createElement("span", null, " \u2022 "), /*#__PURE__*/React.createElement(DateFormat.Time, {
732
+ date: createdAt,
733
+ typographyProps: {
734
+ style: "body1"
735
+ }
736
+ })));
737
+ }
738
+ }, {
739
+ title: t$1("neetoWebhooks.common.responseStatus"),
740
+ key: "responseStatusCode",
741
+ width: 150,
742
+ render: function render(_ref3) {
743
+ var responseStatusCode = _ref3.responseStatusCode,
744
+ status = _ref3.status;
745
+ return /*#__PURE__*/React.createElement("span", {
746
+ className: "flex items-center"
747
+ }, /*#__PURE__*/React.createElement(Typography, {
748
+ className: "px-2 font-bold",
749
+ style: "body2"
750
+ }, responseStatusCode), /*#__PURE__*/React.createElement(Tag, {
751
+ style: status === "success" ? "success" : "warning"
752
+ }, status));
753
+ }
754
+ }, {
755
+ title: t$1("neetoWebhooks.common.event", SINGULAR),
756
+ key: "event",
757
+ dataIndex: "event",
758
+ width: 100,
759
+ render: prop("label")
760
+ }, {
761
+ title: t$1("neetoWebhooks.tableHeaders.details"),
762
+ key: "details",
763
+ dataIndex: "details",
764
+ width: 150,
765
+ render: function render(_, delivery) {
766
+ return /*#__PURE__*/React.createElement(Button, {
767
+ label: t$1("neetoWebhooks.buttons.viewDetails"),
768
+ size: "small",
769
+ onClick: function onClick() {
770
+ return handleDetailsClick(delivery);
771
+ }
772
+ });
773
+ }
774
+ }];
775
+ };
776
+
777
+ var Deliveries = function Deliveries(_ref) {
778
+ var webhooksUrl = _ref.webhooksUrl,
779
+ hostBreadcrumbs = _ref.breadcrumbs;
780
+ var _useState = useState(1),
781
+ _useState2 = _slicedToArray(_useState, 2),
782
+ pageNumber = _useState2[0],
783
+ setPageNumber = _useState2[1];
784
+ var _useState3 = useState({}),
785
+ _useState4 = _slicedToArray(_useState3, 2),
786
+ selectedDelivery = _useState4[0],
787
+ setSelectedDelivery = _useState4[1];
788
+ var _useTranslation = useTranslation(),
789
+ t = _useTranslation.t;
790
+ var _useParams = useParams(),
791
+ webhookId = _useParams.webhookId;
792
+ var _useFetchDeliveries = useFetchDeliveries({
793
+ webhookId: webhookId,
794
+ page: pageNumber,
795
+ limit: DEFAULT_PAGE_SIZE
796
+ }),
797
+ isLoading = _useFetchDeliveries.isLoading,
798
+ isFetching = _useFetchDeliveries.isFetching,
799
+ _useFetchDeliveries$d = _useFetchDeliveries.data,
800
+ _useFetchDeliveries$d2 = _useFetchDeliveries$d === void 0 ? {} : _useFetchDeliveries$d,
801
+ endpoint = _useFetchDeliveries$d2.endpoint,
802
+ totalCount = _useFetchDeliveries$d2.totalCount,
803
+ _useFetchDeliveries$d3 = _useFetchDeliveries$d2.deliveries,
804
+ deliveries = _useFetchDeliveries$d3 === void 0 ? [] : _useFetchDeliveries$d3;
3562
805
  var breadcrumbsWithoutWebhooksTitle = removeBy({
3563
- text: t("webhook.title")
806
+ text: t("neetoWebhooks.webhook.title")
3564
807
  }, hostBreadcrumbs);
3565
808
  var breadcrumbs = [].concat(_toConsumableArray(breadcrumbsWithoutWebhooksTitle), [{
3566
809
  link: webhooksUrl,
3567
- text: t("webhook.title")
810
+ text: t("neetoWebhooks.webhook.title")
3568
811
  }, {
3569
812
  link: window.location.pathname,
3570
813
  text: endpoint
3571
814
  }]);
3572
815
  if (isLoading) return /*#__PURE__*/React.createElement(PageLoader, null);
3573
- return /*#__PURE__*/React.createElement("div", {
3574
- className: "w-full px-6"
816
+ return /*#__PURE__*/React.createElement(Container, {
817
+ className: "w-full"
3575
818
  }, /*#__PURE__*/React.createElement(Header$2, {
3576
819
  breadcrumbs: breadcrumbs,
3577
- title: t("delivery.title")
3578
- }), /*#__PURE__*/React.createElement("div", {
3579
- className: "deliveries__list"
3580
- }, /*#__PURE__*/React.createElement(Accordion, {
3581
- className: classNames("neeto-ui-rounded", {
3582
- border: deliveries.length
820
+ title: t("neetoWebhooks.delivery.title")
821
+ }), isNotEmpty(deliveries) ? /*#__PURE__*/React.createElement(TableWrapper, {
822
+ hasPagination: totalCount > DEFAULT_PAGE_SIZE
823
+ }, /*#__PURE__*/React.createElement(Table, {
824
+ totalCount: totalCount,
825
+ fixedHeight: true,
826
+ currentPageNumber: pageNumber,
827
+ defaultPageSize: DEFAULT_PAGE_SIZE,
828
+ handlePageChange: function handlePageChange(page) {
829
+ return setPageNumber(page);
830
+ },
831
+ loading: isFetching,
832
+ rowData: deliveries,
833
+ columnData: buildColumns$1({
834
+ handleDetailsClick: setSelectedDelivery
3583
835
  })
3584
- }, deliveries.map(function (_ref3) {
3585
- var id = _ref3.id,
3586
- status = _ref3.status,
3587
- identifier = _ref3.identifier,
3588
- action = _ref3.action,
3589
- redelivery = _ref3.redelivery,
3590
- createdAt = _ref3.createdAt;
3591
- return /*#__PURE__*/React.createElement(Accordion.Item, {
3592
- key: id,
3593
- title: /*#__PURE__*/React.createElement("div", {
3594
- className: "flex flex-1 justify-between"
3595
- }, /*#__PURE__*/React.createElement("div", {
3596
- className: "flex items-center gap-2"
3597
- }, /*#__PURE__*/React.createElement("span", null, status === DELIVERY_STATUS.failure ? /*#__PURE__*/React.createElement(Close, {
3598
- className: "neeto-ui-text-error-600",
3599
- size: 20,
3600
- strokeWidth: 2.5
3601
- }) : /*#__PURE__*/React.createElement(Check, {
3602
- className: "neeto-ui-text-success-600",
3603
- size: 24,
3604
- strokeWidth: 2
3605
- })), /*#__PURE__*/React.createElement(Typography, {
3606
- style: "h5"
3607
- }, identifier), /*#__PURE__*/React.createElement(Tag, {
3608
- label: action,
3609
- style: "info"
3610
- }), redelivery && /*#__PURE__*/React.createElement(Tag, {
3611
- label: t("delivery.redelivery")
3612
- })), /*#__PURE__*/React.createElement(Typography, {
3613
- className: "mr-8",
3614
- style: "body2"
3615
- }, dateFormat.dateTime(createdAt)))
3616
- }, /*#__PURE__*/React.createElement(DeliveryItem, {
3617
- deliveryId: id,
3618
- isRedelivering: isRedelivering,
3619
- onRedeliverClick: onRedeliverClick
3620
- }));
3621
- })), isEmpty(deliveries) && /*#__PURE__*/React.createElement("div", {
3622
- className: "flex h-full items-center justify-center"
836
+ })) : /*#__PURE__*/React.createElement("div", {
837
+ className: "flex h-full w-full items-center justify-center"
3623
838
  }, /*#__PURE__*/React.createElement(NoData, {
3624
- description: t("delivery.empty.description"),
3625
- title: t("delivery.empty.title")
3626
- }))));
839
+ description: t("neetoWebhooks.delivery.empty.description"),
840
+ title: t("neetoWebhooks.delivery.empty.title")
841
+ })), /*#__PURE__*/React.createElement(Details, {
842
+ delivery: selectedDelivery,
843
+ onClose: function onClose() {
844
+ return setSelectedDelivery({});
845
+ }
846
+ }));
3627
847
  };
3628
848
  var Deliveries$1 = withReactQuery(Deliveries);
3629
849
 
3630
- var baseUrl = "/webhooks/webhooks";
3631
- var fetch = function fetch(entity_id) {
3632
- return axios.get(baseUrl, {
3633
- params: {
3634
- entity_id: entity_id
3635
- }
850
+ var baseUrl$1 = "/webhooks/webhooks";
851
+ var fetch = function fetch(params) {
852
+ return axios.get(baseUrl$1, {
853
+ params: params
3636
854
  });
3637
855
  };
3638
856
  var create = function create(payload) {
3639
- return axios.post(baseUrl, {
857
+ return axios.post(baseUrl$1, {
3640
858
  webhook: payload
3641
859
  });
3642
860
  };
3643
861
  var show = function show(id) {
3644
- return axios.get("".concat(baseUrl, "/").concat(id));
862
+ return axios.get("".concat(baseUrl$1, "/").concat(id));
3645
863
  };
3646
864
  var update = function update(id, payload) {
3647
- return axios.put("".concat(baseUrl, "/").concat(id), {
865
+ return axios.put("".concat(baseUrl$1, "/").concat(id), {
3648
866
  webhook: payload
3649
867
  });
3650
868
  };
3651
869
  var destroy = function destroy(id) {
3652
- return axios["delete"]("".concat(baseUrl, "/").concat(id));
870
+ return axios["delete"]("".concat(baseUrl$1, "/").concat(id));
3653
871
  };
3654
872
  var webhooksApi = {
3655
873
  fetch: fetch,
@@ -3659,9 +877,9 @@ var webhooksApi = {
3659
877
  destroy: destroy
3660
878
  };
3661
879
 
3662
- var useFetchWebhooks = function useFetchWebhooks(entityId) {
3663
- return useQuery([QUERY_KEYS.WEBHOOK_LIST, entityId], function () {
3664
- return webhooksApi.fetch(entityId);
880
+ var useFetchWebhooks = function useFetchWebhooks(params) {
881
+ return useQuery([QUERY_KEYS.WEBHOOK_LIST, params], function () {
882
+ return webhooksApi.fetch(params);
3665
883
  }, {
3666
884
  staleTime: WEBHOOK_STALE_TIME
3667
885
  });
@@ -3752,16 +970,125 @@ function _defineProperty(obj, key, value) {
3752
970
  return obj;
3753
971
  }
3754
972
 
973
+ var baseUrl = "/webhooks/events/all";
974
+ var all = function all() {
975
+ return axios.get(baseUrl);
976
+ };
977
+ var eventsApi = {
978
+ all: all
979
+ };
980
+
981
+ var useFetchEvents = function useFetchEvents() {
982
+ return useQuery([QUERY_KEYS.EVENTS_LIST], eventsApi.all, {
983
+ staleTime: WEBHOOK_STALE_TIME
984
+ });
985
+ };
986
+
3755
987
  var WEBHOOK_HELP_URL = "https://help.neetocal.com/articles/webhook";
3756
988
 
989
+ var Menu = Dropdown.Menu,
990
+ MenuItem = Dropdown.MenuItem;
991
+ var ActionDropdown = function ActionDropdown(_ref) {
992
+ var onEdit = _ref.onEdit,
993
+ onDelete = _ref.onDelete;
994
+ var _useTranslation = useTranslation(),
995
+ t = _useTranslation.t;
996
+ return /*#__PURE__*/React.createElement(Dropdown, {
997
+ buttonStyle: "text",
998
+ icon: MenuHorizontal,
999
+ strategy: "fixed"
1000
+ }, /*#__PURE__*/React.createElement(Menu, null, /*#__PURE__*/React.createElement(MenuItem.Button, {
1001
+ onClick: onEdit
1002
+ }, t("neetoWebhooks.buttons.edit")), /*#__PURE__*/React.createElement(MenuItem.Button, {
1003
+ style: "danger",
1004
+ onClick: onDelete
1005
+ }, t("neetoWebhooks.buttons.delete"))));
1006
+ };
1007
+
1008
+ function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
1009
+ function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3757
1010
  var getValidationSchema = function getValidationSchema(webhooks) {
3758
1011
  return yup.object().shape({
3759
- endpoint: yup.string().trim().matches(/^(https?):\/\//i, t$2("errors.webhook.invalidUrlProtocol")).url(t$2("errors.webhook.invalidUrl")).required(t$2("errors.webhook.required")).test("Is endpoint unique", t$2("errors.webhook.urlNotUnique"), function (endpoint, ctx) {
1012
+ endpoint: yup.string().trim().matches(/^(https?):\/\//i, t$1("neetoWebhooks.errors.webhook.invalidUrlProtocol")).url(t$1("neetoWebhooks.errors.webhook.invalidUrl")).required(t$1("neetoWebhooks.errors.webhook.required")).test("Is endpoint unique", t$1("neetoWebhooks.errors.webhook.urlNotUnique"), function (endpoint, ctx) {
3760
1013
  return !pluck("endpoint", removeById(ctx.parent.id, webhooks)).includes(endpoint === null || endpoint === void 0 ? void 0 : endpoint.trim());
3761
1014
  }),
1015
+ events: yup.array().min(1, t$1("neetoWebhooks.errors.webhook.events.required")),
3762
1016
  secret: yup.string().trim().nullable()
3763
1017
  });
3764
1018
  };
1019
+ var buildPayload = function buildPayload(_ref) {
1020
+ var _initialValues$events;
1021
+ var isEditing = _ref.isEditing,
1022
+ values = _ref.values,
1023
+ initialValues = _ref.initialValues;
1024
+ var events = values.events.map(function (_ref2) {
1025
+ var identifier = _ref2.identifier;
1026
+ return {
1027
+ identifier: identifier
1028
+ };
1029
+ });
1030
+ if (!isEditing) return _objectSpread$1(_objectSpread$1({}, values), {}, {
1031
+ eventsAttributes: events
1032
+ });
1033
+ var deletable = ((_initialValues$events = initialValues.events) !== null && _initialValues$events !== void 0 ? _initialValues$events : []).filter(function (_ref3) {
1034
+ var identifier = _ref3.identifier;
1035
+ return !findBy({
1036
+ identifier: identifier
1037
+ }, values.events);
1038
+ }).map(assoc("_destroy", true));
1039
+ var creatable = values.events.filter(function (_ref4) {
1040
+ var identifier = _ref4.identifier;
1041
+ return !findBy({
1042
+ identifier: identifier
1043
+ }, initialValues.events);
1044
+ });
1045
+ return _objectSpread$1(_objectSpread$1({}, values), {}, {
1046
+ eventsAttributes: [].concat(_toConsumableArray(creatable), _toConsumableArray(deletable))
1047
+ });
1048
+ };
1049
+ var buildColumns = function buildColumns(_ref5) {
1050
+ var handleDelete = _ref5.handleDelete,
1051
+ handleEdit = _ref5.handleEdit,
1052
+ deliveriesPath = _ref5.deliveriesPath;
1053
+ return [{
1054
+ title: t$1("neetoWebhooks.common.endpoint"),
1055
+ key: "endpoint",
1056
+ dataIndex: "endpoint",
1057
+ render: function render(endpoint, webhook) {
1058
+ return /*#__PURE__*/React.createElement("div", {
1059
+ className: "flex items-center justify-between space-x-3"
1060
+ }, /*#__PURE__*/React.createElement(Button, {
1061
+ style: "link",
1062
+ to: buildUrl(deliveriesPath, {
1063
+ webhookId: webhook.id
1064
+ })
1065
+ }, endpoint), /*#__PURE__*/React.createElement(ActionDropdown, {
1066
+ onDelete: function onDelete() {
1067
+ return handleDelete(webhook.id);
1068
+ },
1069
+ onEdit: function onEdit() {
1070
+ return handleEdit(webhook.id);
1071
+ }
1072
+ }));
1073
+ }
1074
+ }, {
1075
+ title: t$1("neetoWebhooks.webhook.active"),
1076
+ key: "isActive",
1077
+ dataIndex: "isActive",
1078
+ render: function render(isActive) {
1079
+ return isActive ? t$1("neetoWebhooks.webhook.activeStatuses.yes") : t$1("neetoWebhooks.webhook.activeStatuses.no");
1080
+ },
1081
+ width: 100
1082
+ }, {
1083
+ title: t$1("neetoWebhooks.common.event", PLURAL),
1084
+ dataIndex: "events",
1085
+ key: "events",
1086
+ render: function render(events) {
1087
+ return pluck("label", events).sort().join(", ");
1088
+ },
1089
+ width: 200
1090
+ }];
1091
+ };
3765
1092
 
3766
1093
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
3767
1094
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
@@ -3792,15 +1119,25 @@ var AddWebhookPane = function AddWebhookPane(_ref) {
3792
1119
  }),
3793
1120
  updateWebhook = _useUpdateWebhook.mutate;
3794
1121
  var endpointRef = useRef();
1122
+ var _useFetchEvents = useFetchEvents(),
1123
+ events = _useFetchEvents.data,
1124
+ isLoading = _useFetchEvents.isLoading;
3795
1125
  var initialValues = editingWebhookId ? webhook : {
3796
1126
  endpoint: "",
3797
- secret: ""
1127
+ events: events,
1128
+ secret: "",
1129
+ isActive: true
3798
1130
  };
3799
1131
  var handleSubmit = function handleSubmit(values) {
1132
+ var payload = buildPayload({
1133
+ isEditing: editingWebhookId,
1134
+ values: values,
1135
+ initialValues: initialValues
1136
+ });
3800
1137
  editingWebhookId ? updateWebhook({
3801
1138
  id: editingWebhookId,
3802
- payload: values
3803
- }) : createWebhook(_objectSpread(_objectSpread({}, values), {}, {
1139
+ payload: payload
1140
+ }) : createWebhook(_objectSpread(_objectSpread({}, payload), {}, {
3804
1141
  entityId: entityId,
3805
1142
  entityType: entityType
3806
1143
  }));
@@ -3815,7 +1152,7 @@ var AddWebhookPane = function AddWebhookPane(_ref) {
3815
1152
  "data-cy": "add-new-webhook-pane-header",
3816
1153
  style: "h2",
3817
1154
  weight: "semibold"
3818
- }, editingWebhookId ? t("webhook.edit") : t("webhook.add")), /*#__PURE__*/React.createElement("a", {
1155
+ }, editingWebhookId ? t("neetoWebhooks.webhook.edit") : t("neetoWebhooks.webhook.add")), /*#__PURE__*/React.createElement("a", {
3819
1156
  href: WEBHOOK_HELP_URL,
3820
1157
  rel: "noreferrer",
3821
1158
  target: "_blank"
@@ -3833,20 +1170,32 @@ var AddWebhookPane = function AddWebhookPane(_ref) {
3833
1170
  }
3834
1171
  }, function (_ref2) {
3835
1172
  var dirty = _ref2.dirty,
3836
- isSubmitting = _ref2.isSubmitting;
3837
- return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Pane.Body, null, /*#__PURE__*/React.createElement("div", {
1173
+ isSubmitting = _ref2.isSubmitting,
1174
+ isValid = _ref2.isValid;
1175
+ return isLoading ? /*#__PURE__*/React.createElement("div", {
1176
+ className: "flex items-center justify-center"
1177
+ }, /*#__PURE__*/React.createElement(Spinner, null)) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Pane.Body, null, /*#__PURE__*/React.createElement("div", {
3838
1178
  className: "w-full space-y-4"
3839
1179
  }, /*#__PURE__*/React.createElement(Input, {
3840
1180
  required: true,
3841
1181
  "data-cy": "endpoint-input-field",
3842
- label: t("webhook.endpoint"),
1182
+ label: t("neetoWebhooks.webhook.endpoint"),
3843
1183
  name: "endpoint",
3844
- placeholder: t("webhook.endpointPlaceholder"),
1184
+ placeholder: t("neetoWebhooks.webhook.endpointPlaceholder"),
3845
1185
  ref: endpointRef
1186
+ }), !isLoading && /*#__PURE__*/React.createElement(Select, {
1187
+ isMulti: true,
1188
+ required: true,
1189
+ getOptionLabel: prop("label"),
1190
+ getOptionValue: prop("identifier"),
1191
+ label: t("neetoWebhooks.common.event", PLURAL),
1192
+ name: "events",
1193
+ options: events,
1194
+ placeholder: t("neetoWebhooks.webhook.eventPlaceholder")
3846
1195
  }), /*#__PURE__*/React.createElement(Input, {
3847
1196
  "data-cy": "secret-key-input-field",
3848
1197
  name: "secret",
3849
- placeholder: t("webhook.secretPlaceholder"),
1198
+ placeholder: t("neetoWebhooks.webhook.secretPlaceholder"),
3850
1199
  label: /*#__PURE__*/React.createElement(Trans, {
3851
1200
  i18nKey: "webhook.secret",
3852
1201
  components: {
@@ -3861,6 +1210,9 @@ var AddWebhookPane = function AddWebhookPane(_ref) {
3861
1210
  })
3862
1211
  }
3863
1212
  })
1213
+ }), /*#__PURE__*/React.createElement(Switch, {
1214
+ label: t("neetoWebhooks.webhook.active"),
1215
+ name: "isActive"
3864
1216
  }))), /*#__PURE__*/React.createElement(Pane.Footer, {
3865
1217
  className: "flex gap-2"
3866
1218
  }, /*#__PURE__*/React.createElement(ActionBlock, {
@@ -3868,11 +1220,11 @@ var AddWebhookPane = function AddWebhookPane(_ref) {
3868
1220
  cancelButtonProps: {
3869
1221
  onClick: onClose,
3870
1222
  disabled: false,
3871
- label: t("buttons.cancel")
1223
+ label: t("neetoWebhooks.buttons.cancel")
3872
1224
  },
3873
1225
  submitButtonProps: {
3874
- label: t("buttons.saveChanges"),
3875
- disabled: !dirty,
1226
+ label: t("neetoWebhooks.buttons.saveChanges"),
1227
+ disabled: !dirty || !isValid,
3876
1228
  loading: isSubmitting
3877
1229
  }
3878
1230
  })));
@@ -3886,10 +1238,10 @@ var Header = function Header(_ref) {
3886
1238
  t = _useTranslation.t;
3887
1239
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Header$2, {
3888
1240
  breadcrumbs: breadcrumbs,
3889
- title: t("webhook.title"),
1241
+ title: t("neetoWebhooks.webhook.title"),
3890
1242
  actionBlock: /*#__PURE__*/React.createElement(Button, {
3891
1243
  "data-cy": "add-new-webhook-button",
3892
- label: t("webhook.add"),
1244
+ label: t("neetoWebhooks.webhook.add"),
3893
1245
  onClick: function onClick() {
3894
1246
  return setIsAddWebhookPaneOpen(true);
3895
1247
  }
@@ -3899,48 +1251,10 @@ var Header = function Header(_ref) {
3899
1251
  "data-cy": "webhook-description-header",
3900
1252
  style: "h5",
3901
1253
  weight: "normal"
3902
- }, t("webhook.description")));
1254
+ }, t("neetoWebhooks.webhook.description")));
3903
1255
  };
3904
1256
  var Header$1 = /*#__PURE__*/React.memo(Header);
3905
1257
 
3906
- var Menu = Dropdown.Menu,
3907
- MenuItem = Dropdown.MenuItem;
3908
- var WebhookItem = function WebhookItem(_ref) {
3909
- var webhook = _ref.webhook,
3910
- onDeleteClick = _ref.onDeleteClick,
3911
- onEditClick = _ref.onEditClick,
3912
- deliveriesPath = _ref.deliveriesPath;
3913
- var _useTranslation = useTranslation(),
3914
- t = _useTranslation.t;
3915
- return /*#__PURE__*/React.createElement(Link, {
3916
- className: "neeto-ui-rounded-lg neeto-ui-border-gray-300 flex cursor-pointer items-center justify-between gap-4 border px-4 py-2",
3917
- to: buildUrl(deliveriesPath, {
3918
- webhookId: webhook.id
3919
- })
3920
- }, /*#__PURE__*/React.createElement(Typography, {
3921
- className: "neeto-ui-text-primary-800 break-all",
3922
- component: "span",
3923
- style: "body1"
3924
- }, webhook.endpoint), /*#__PURE__*/React.createElement("div", {
3925
- onClick: function onClick(e) {
3926
- e.preventDefault();
3927
- e.stopPropagation();
3928
- }
3929
- }, /*#__PURE__*/React.createElement(Dropdown, {
3930
- buttonStyle: "text",
3931
- icon: MenuHorizontal
3932
- }, /*#__PURE__*/React.createElement(Menu, null, /*#__PURE__*/React.createElement(MenuItem.Button, {
3933
- onClick: function onClick() {
3934
- return onEditClick(webhook.id);
3935
- }
3936
- }, t("operation.edit")), /*#__PURE__*/React.createElement(MenuItem.Button, {
3937
- onClick: function onClick() {
3938
- return onDeleteClick(webhook.id);
3939
- }
3940
- }, t("operation.delete"))))));
3941
- };
3942
- var WebhookItem$1 = /*#__PURE__*/React.memo(WebhookItem);
3943
-
3944
1258
  var Webhooks = function Webhooks(_ref) {
3945
1259
  var deliveriesPath = _ref.deliveriesPath,
3946
1260
  entityType = _ref.entityType,
@@ -3962,14 +1276,25 @@ var Webhooks = function Webhooks(_ref) {
3962
1276
  _useState8 = _slicedToArray(_useState7, 2),
3963
1277
  isDeleteAlertOpen = _useState8[0],
3964
1278
  setIsDeleteAlertOpen = _useState8[1];
1279
+ var _useState9 = useState(1),
1280
+ _useState10 = _slicedToArray(_useState9, 2),
1281
+ pageNumber = _useState10[0],
1282
+ setPageNumber = _useState10[1];
3965
1283
  var _useTranslation = useTranslation(),
3966
1284
  t = _useTranslation.t;
3967
- var _useFetchWebhooks = useFetchWebhooks(entityId),
1285
+ var _useFetchWebhooks = useFetchWebhooks({
1286
+ entityId: entityId,
1287
+ page: pageNumber,
1288
+ limit: DEFAULT_PAGE_SIZE
1289
+ }),
3968
1290
  isLoading = _useFetchWebhooks.isLoading,
1291
+ isFetching = _useFetchWebhooks.isFetching,
3969
1292
  _useFetchWebhooks$dat = _useFetchWebhooks.data,
3970
1293
  _useFetchWebhooks$dat2 = _useFetchWebhooks$dat === void 0 ? {} : _useFetchWebhooks$dat,
3971
1294
  _useFetchWebhooks$dat3 = _useFetchWebhooks$dat2.webhooks,
3972
- webhooks = _useFetchWebhooks$dat3 === void 0 ? [] : _useFetchWebhooks$dat3;
1295
+ webhooks = _useFetchWebhooks$dat3 === void 0 ? [] : _useFetchWebhooks$dat3,
1296
+ _useFetchWebhooks$dat4 = _useFetchWebhooks$dat2.totalCount,
1297
+ totalCount = _useFetchWebhooks$dat4 === void 0 ? 0 : _useFetchWebhooks$dat4;
3973
1298
  var _useDestroyWebhook = useDestroyWebhook({
3974
1299
  onSuccess: function onSuccess() {
3975
1300
  return setIsDeleteAlertOpen(false);
@@ -3992,43 +1317,48 @@ var Webhooks = function Webhooks(_ref) {
3992
1317
  if (isLoading) {
3993
1318
  return /*#__PURE__*/React.createElement(PageLoader, null);
3994
1319
  }
3995
- return /*#__PURE__*/React.createElement("div", {
3996
- className: "w-full px-6"
3997
- }, /*#__PURE__*/React.createElement("div", {
3998
- className: "neeto-ui-bg-white sticky top-0 z-50 w-full"
3999
- }), /*#__PURE__*/React.createElement(Header$1, {
1320
+ return /*#__PURE__*/React.createElement(Container, {
1321
+ className: "w-full"
1322
+ }, /*#__PURE__*/React.createElement(Header$1, {
4000
1323
  breadcrumbs: breadcrumbs,
4001
1324
  setIsAddWebhookPaneOpen: setIsAddWebhookPaneOpen
4002
- }), /*#__PURE__*/React.createElement("div", {
4003
- className: "webhooks__list space-y-2"
4004
- }, webhooks.map(function (webhook) {
4005
- return /*#__PURE__*/React.createElement(WebhookItem$1, {
4006
- deliveriesPath: deliveriesPath,
4007
- key: webhook.id,
4008
- webhook: webhook,
4009
- onDeleteClick: handleDelete,
4010
- onEditClick: handleEdit
4011
- });
4012
- }), isEmpty(webhooks) && /*#__PURE__*/React.createElement("div", {
4013
- className: "flex h-full items-center justify-center"
1325
+ }), isNotEmpty(webhooks) ? /*#__PURE__*/React.createElement(TableWrapper, {
1326
+ hasPagination: totalCount > DEFAULT_PAGE_SIZE
1327
+ }, /*#__PURE__*/React.createElement(Table, {
1328
+ totalCount: totalCount,
1329
+ fixedHeight: true,
1330
+ currentPageNumber: pageNumber,
1331
+ defaultPageSize: DEFAULT_PAGE_SIZE,
1332
+ handlePageChange: function handlePageChange(page) {
1333
+ return setPageNumber(page);
1334
+ },
1335
+ loading: isFetching,
1336
+ rowData: webhooks,
1337
+ columnData: buildColumns({
1338
+ handleDelete: handleDelete,
1339
+ handleEdit: handleEdit,
1340
+ deliveriesPath: deliveriesPath
1341
+ })
1342
+ })) : /*#__PURE__*/React.createElement("div", {
1343
+ className: "flex h-full w-full items-center justify-center"
4014
1344
  }, /*#__PURE__*/React.createElement(NoData, {
4015
- title: t("webhook.empty")
4016
- }))), /*#__PURE__*/React.createElement(AddWebhookPane, {
1345
+ title: t("neetoWebhooks.webhook.empty")
1346
+ })), /*#__PURE__*/React.createElement(AddWebhookPane, {
4017
1347
  editingWebhookId: editingWebhookId,
4018
1348
  entityId: entityId,
4019
1349
  entityType: entityType,
4020
- isOpen: isAddWebhookPaneOpen,
4021
1350
  webhooks: webhooks,
1351
+ isOpen: isAddWebhookPaneOpen,
4022
1352
  onClose: handlePaneClose
4023
1353
  }), /*#__PURE__*/React.createElement(Alert, {
4024
1354
  isOpen: isDeleteAlertOpen,
4025
1355
  isSubmitting: isDeleting,
4026
- submitButtonLabel: t("buttons.delete"),
4027
- message: t("alert.delete.message", {
4028
- entity: t("entity.webhook")
1356
+ submitButtonLabel: t("neetoWebhooks.buttons.delete"),
1357
+ message: t("neetoWebhooks.alert.delete.message", {
1358
+ entity: t("neetoWebhooks.entity.webhook")
4029
1359
  }),
4030
- title: t("alert.delete.title", {
4031
- entity: t("entity.webhook")
1360
+ title: t("neetoWebhooks.alert.delete.title", {
1361
+ entity: t("neetoWebhooks.entity.webhook")
4032
1362
  }),
4033
1363
  onClose: function onClose() {
4034
1364
  return setIsDeleteAlertOpen(false);
@@ -4049,7 +1379,7 @@ var NeetoWebhooks = function NeetoWebhooks(_ref) {
4049
1379
  webhooksPath = _useRouteMatch.path,
4050
1380
  webhooksUrl = _useRouteMatch.url;
4051
1381
  var deliveriesPath = getDeliveriesPath(webhooksUrl);
4052
- return /*#__PURE__*/React.createElement(Switch, null, /*#__PURE__*/React.createElement(Route, {
1382
+ return /*#__PURE__*/React.createElement(Switch$1, null, /*#__PURE__*/React.createElement(Route, {
4053
1383
  exact: true,
4054
1384
  path: webhooksPath,
4055
1385
  component: function component() {