@bigbinary/neeto-api-keys-frontend 1.0.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/README.md +29 -0
- package/dist/index.cjs.js +3464 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.js +3432 -0
- package/dist/index.js.map +1 -0
- package/package.json +179 -0
- package/types.d.ts +12 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3432 @@
|
|
|
1
|
+
import React, { createElement, isValidElement, cloneElement, createContext, useContext, useRef, useState, useEffect } from 'react';
|
|
2
|
+
import { DEFAULT_PAGE_INDEX, PLURAL } from '@bigbinary/neeto-commons-frontend/constants';
|
|
3
|
+
import { isPresent, isNotPresent, isNotEmpty } from '@bigbinary/neeto-commons-frontend/pure';
|
|
4
|
+
import { useMutationWithInvalidation, withT, useDebounce } from '@bigbinary/neeto-commons-frontend/react-utils';
|
|
5
|
+
import Container from '@bigbinary/neeto-molecules/Container';
|
|
6
|
+
import Header from '@bigbinary/neeto-molecules/Header';
|
|
7
|
+
import { Dropdown, Typography, Button, Tag, DatePicker as DatePicker$1, Pane, NoData, Table as Table$1, Alert } from '@bigbinary/neetoui';
|
|
8
|
+
import { useQuery } from 'react-query';
|
|
9
|
+
import axios from 'axios';
|
|
10
|
+
import { Form as Form$1, Input, Checkbox, ActionBlock } from '@bigbinary/neetoui/formik';
|
|
11
|
+
import { Field } from 'formik';
|
|
12
|
+
import { prop, isEmpty } from 'ramda';
|
|
13
|
+
import { copyToClipboard, dateFormat, getQueryParams, buildUrl } from '@bigbinary/neeto-commons-frontend/utils';
|
|
14
|
+
import { MenuHorizontal, Copy } from '@bigbinary/neeto-icons';
|
|
15
|
+
import * as yup from 'yup';
|
|
16
|
+
import PageLoader from '@bigbinary/neeto-molecules/PageLoader';
|
|
17
|
+
import TableWrapper from '@bigbinary/neeto-molecules/TableWrapper';
|
|
18
|
+
import { useHistory } from 'react-router-dom';
|
|
19
|
+
|
|
20
|
+
const consoleLogger = {
|
|
21
|
+
type: 'logger',
|
|
22
|
+
log(args) {
|
|
23
|
+
this.output('log', args);
|
|
24
|
+
},
|
|
25
|
+
warn(args) {
|
|
26
|
+
this.output('warn', args);
|
|
27
|
+
},
|
|
28
|
+
error(args) {
|
|
29
|
+
this.output('error', args);
|
|
30
|
+
},
|
|
31
|
+
output(type, args) {
|
|
32
|
+
if (console && console[type]) console[type].apply(console, args);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
class Logger {
|
|
36
|
+
constructor(concreteLogger) {
|
|
37
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
38
|
+
this.init(concreteLogger, options);
|
|
39
|
+
}
|
|
40
|
+
init(concreteLogger) {
|
|
41
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
42
|
+
this.prefix = options.prefix || 'i18next:';
|
|
43
|
+
this.logger = concreteLogger || consoleLogger;
|
|
44
|
+
this.options = options;
|
|
45
|
+
this.debug = options.debug;
|
|
46
|
+
}
|
|
47
|
+
log() {
|
|
48
|
+
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
|
49
|
+
args[_key] = arguments[_key];
|
|
50
|
+
}
|
|
51
|
+
return this.forward(args, 'log', '', true);
|
|
52
|
+
}
|
|
53
|
+
warn() {
|
|
54
|
+
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
|
|
55
|
+
args[_key2] = arguments[_key2];
|
|
56
|
+
}
|
|
57
|
+
return this.forward(args, 'warn', '', true);
|
|
58
|
+
}
|
|
59
|
+
error() {
|
|
60
|
+
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
|
|
61
|
+
args[_key3] = arguments[_key3];
|
|
62
|
+
}
|
|
63
|
+
return this.forward(args, 'error', '');
|
|
64
|
+
}
|
|
65
|
+
deprecate() {
|
|
66
|
+
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
|
|
67
|
+
args[_key4] = arguments[_key4];
|
|
68
|
+
}
|
|
69
|
+
return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
|
|
70
|
+
}
|
|
71
|
+
forward(args, lvl, prefix, debugOnly) {
|
|
72
|
+
if (debugOnly && !this.debug) return null;
|
|
73
|
+
if (typeof args[0] === 'string') args[0] = `${prefix}${this.prefix} ${args[0]}`;
|
|
74
|
+
return this.logger[lvl](args);
|
|
75
|
+
}
|
|
76
|
+
create(moduleName) {
|
|
77
|
+
return new Logger(this.logger, {
|
|
78
|
+
...{
|
|
79
|
+
prefix: `${this.prefix}:${moduleName}:`
|
|
80
|
+
},
|
|
81
|
+
...this.options
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
clone(options) {
|
|
85
|
+
options = options || this.options;
|
|
86
|
+
options.prefix = options.prefix || this.prefix;
|
|
87
|
+
return new Logger(this.logger, options);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
var baseLogger = new Logger();
|
|
91
|
+
|
|
92
|
+
class EventEmitter {
|
|
93
|
+
constructor() {
|
|
94
|
+
this.observers = {};
|
|
95
|
+
}
|
|
96
|
+
on(events, listener) {
|
|
97
|
+
events.split(' ').forEach(event => {
|
|
98
|
+
this.observers[event] = this.observers[event] || [];
|
|
99
|
+
this.observers[event].push(listener);
|
|
100
|
+
});
|
|
101
|
+
return this;
|
|
102
|
+
}
|
|
103
|
+
off(event, listener) {
|
|
104
|
+
if (!this.observers[event]) return;
|
|
105
|
+
if (!listener) {
|
|
106
|
+
delete this.observers[event];
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
this.observers[event] = this.observers[event].filter(l => l !== listener);
|
|
110
|
+
}
|
|
111
|
+
emit(event) {
|
|
112
|
+
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
|
113
|
+
args[_key - 1] = arguments[_key];
|
|
114
|
+
}
|
|
115
|
+
if (this.observers[event]) {
|
|
116
|
+
const cloned = [].concat(this.observers[event]);
|
|
117
|
+
cloned.forEach(observer => {
|
|
118
|
+
observer(...args);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
if (this.observers['*']) {
|
|
122
|
+
const cloned = [].concat(this.observers['*']);
|
|
123
|
+
cloned.forEach(observer => {
|
|
124
|
+
observer.apply(observer, [event, ...args]);
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function defer() {
|
|
131
|
+
let res;
|
|
132
|
+
let rej;
|
|
133
|
+
const promise = new Promise((resolve, reject) => {
|
|
134
|
+
res = resolve;
|
|
135
|
+
rej = reject;
|
|
136
|
+
});
|
|
137
|
+
promise.resolve = res;
|
|
138
|
+
promise.reject = rej;
|
|
139
|
+
return promise;
|
|
140
|
+
}
|
|
141
|
+
function makeString(object) {
|
|
142
|
+
if (object == null) return '';
|
|
143
|
+
return '' + object;
|
|
144
|
+
}
|
|
145
|
+
function copy(a, s, t) {
|
|
146
|
+
a.forEach(m => {
|
|
147
|
+
if (s[m]) t[m] = s[m];
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
function getLastOfPath(object, path, Empty) {
|
|
151
|
+
function cleanKey(key) {
|
|
152
|
+
return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
|
|
153
|
+
}
|
|
154
|
+
function canNotTraverseDeeper() {
|
|
155
|
+
return !object || typeof object === 'string';
|
|
156
|
+
}
|
|
157
|
+
const stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
|
|
158
|
+
while (stack.length > 1) {
|
|
159
|
+
if (canNotTraverseDeeper()) return {};
|
|
160
|
+
const key = cleanKey(stack.shift());
|
|
161
|
+
if (!object[key] && Empty) object[key] = new Empty();
|
|
162
|
+
if (Object.prototype.hasOwnProperty.call(object, key)) {
|
|
163
|
+
object = object[key];
|
|
164
|
+
} else {
|
|
165
|
+
object = {};
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (canNotTraverseDeeper()) return {};
|
|
169
|
+
return {
|
|
170
|
+
obj: object,
|
|
171
|
+
k: cleanKey(stack.shift())
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function setPath(object, path, newValue) {
|
|
175
|
+
const {
|
|
176
|
+
obj,
|
|
177
|
+
k
|
|
178
|
+
} = getLastOfPath(object, path, Object);
|
|
179
|
+
obj[k] = newValue;
|
|
180
|
+
}
|
|
181
|
+
function pushPath(object, path, newValue, concat) {
|
|
182
|
+
const {
|
|
183
|
+
obj,
|
|
184
|
+
k
|
|
185
|
+
} = getLastOfPath(object, path, Object);
|
|
186
|
+
obj[k] = obj[k] || [];
|
|
187
|
+
if (concat) obj[k] = obj[k].concat(newValue);
|
|
188
|
+
if (!concat) obj[k].push(newValue);
|
|
189
|
+
}
|
|
190
|
+
function getPath(object, path) {
|
|
191
|
+
const {
|
|
192
|
+
obj,
|
|
193
|
+
k
|
|
194
|
+
} = getLastOfPath(object, path);
|
|
195
|
+
if (!obj) return undefined;
|
|
196
|
+
return obj[k];
|
|
197
|
+
}
|
|
198
|
+
function getPathWithDefaults(data, defaultData, key) {
|
|
199
|
+
const value = getPath(data, key);
|
|
200
|
+
if (value !== undefined) {
|
|
201
|
+
return value;
|
|
202
|
+
}
|
|
203
|
+
return getPath(defaultData, key);
|
|
204
|
+
}
|
|
205
|
+
function deepExtend(target, source, overwrite) {
|
|
206
|
+
for (const prop in source) {
|
|
207
|
+
if (prop !== '__proto__' && prop !== 'constructor') {
|
|
208
|
+
if (prop in target) {
|
|
209
|
+
if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
|
|
210
|
+
if (overwrite) target[prop] = source[prop];
|
|
211
|
+
} else {
|
|
212
|
+
deepExtend(target[prop], source[prop], overwrite);
|
|
213
|
+
}
|
|
214
|
+
} else {
|
|
215
|
+
target[prop] = source[prop];
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return target;
|
|
220
|
+
}
|
|
221
|
+
function regexEscape(str) {
|
|
222
|
+
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
|
|
223
|
+
}
|
|
224
|
+
var _entityMap = {
|
|
225
|
+
'&': '&',
|
|
226
|
+
'<': '<',
|
|
227
|
+
'>': '>',
|
|
228
|
+
'"': '"',
|
|
229
|
+
"'": ''',
|
|
230
|
+
'/': '/'
|
|
231
|
+
};
|
|
232
|
+
function escape(data) {
|
|
233
|
+
if (typeof data === 'string') {
|
|
234
|
+
return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
|
|
235
|
+
}
|
|
236
|
+
return data;
|
|
237
|
+
}
|
|
238
|
+
const chars = [' ', ',', '?', '!', ';'];
|
|
239
|
+
function looksLikeObjectPath(key, nsSeparator, keySeparator) {
|
|
240
|
+
nsSeparator = nsSeparator || '';
|
|
241
|
+
keySeparator = keySeparator || '';
|
|
242
|
+
const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
|
|
243
|
+
if (possibleChars.length === 0) return true;
|
|
244
|
+
const r = new RegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
|
|
245
|
+
let matched = !r.test(key);
|
|
246
|
+
if (!matched) {
|
|
247
|
+
const ki = key.indexOf(keySeparator);
|
|
248
|
+
if (ki > 0 && !r.test(key.substring(0, ki))) {
|
|
249
|
+
matched = true;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return matched;
|
|
253
|
+
}
|
|
254
|
+
function deepFind(obj, path) {
|
|
255
|
+
let keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
|
|
256
|
+
if (!obj) return undefined;
|
|
257
|
+
if (obj[path]) return obj[path];
|
|
258
|
+
const paths = path.split(keySeparator);
|
|
259
|
+
let current = obj;
|
|
260
|
+
for (let i = 0; i < paths.length; ++i) {
|
|
261
|
+
if (!current) return undefined;
|
|
262
|
+
if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {
|
|
263
|
+
return undefined;
|
|
264
|
+
}
|
|
265
|
+
if (current[paths[i]] === undefined) {
|
|
266
|
+
let j = 2;
|
|
267
|
+
let p = paths.slice(i, i + j).join(keySeparator);
|
|
268
|
+
let mix = current[p];
|
|
269
|
+
while (mix === undefined && paths.length > i + j) {
|
|
270
|
+
j++;
|
|
271
|
+
p = paths.slice(i, i + j).join(keySeparator);
|
|
272
|
+
mix = current[p];
|
|
273
|
+
}
|
|
274
|
+
if (mix === undefined) return undefined;
|
|
275
|
+
if (mix === null) return null;
|
|
276
|
+
if (path.endsWith(p)) {
|
|
277
|
+
if (typeof mix === 'string') return mix;
|
|
278
|
+
if (p && typeof mix[p] === 'string') return mix[p];
|
|
279
|
+
}
|
|
280
|
+
const joinedPath = paths.slice(i + j).join(keySeparator);
|
|
281
|
+
if (joinedPath) return deepFind(mix, joinedPath, keySeparator);
|
|
282
|
+
return undefined;
|
|
283
|
+
}
|
|
284
|
+
current = current[paths[i]];
|
|
285
|
+
}
|
|
286
|
+
return current;
|
|
287
|
+
}
|
|
288
|
+
function getCleanedCode(code) {
|
|
289
|
+
if (code && code.indexOf('_') > 0) return code.replace('_', '-');
|
|
290
|
+
return code;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
class ResourceStore extends EventEmitter {
|
|
294
|
+
constructor(data) {
|
|
295
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
|
|
296
|
+
ns: ['translation'],
|
|
297
|
+
defaultNS: 'translation'
|
|
298
|
+
};
|
|
299
|
+
super();
|
|
300
|
+
this.data = data || {};
|
|
301
|
+
this.options = options;
|
|
302
|
+
if (this.options.keySeparator === undefined) {
|
|
303
|
+
this.options.keySeparator = '.';
|
|
304
|
+
}
|
|
305
|
+
if (this.options.ignoreJSONStructure === undefined) {
|
|
306
|
+
this.options.ignoreJSONStructure = true;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
addNamespaces(ns) {
|
|
310
|
+
if (this.options.ns.indexOf(ns) < 0) {
|
|
311
|
+
this.options.ns.push(ns);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
removeNamespaces(ns) {
|
|
315
|
+
const index = this.options.ns.indexOf(ns);
|
|
316
|
+
if (index > -1) {
|
|
317
|
+
this.options.ns.splice(index, 1);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
getResource(lng, ns, key) {
|
|
321
|
+
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
|
|
322
|
+
const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
|
|
323
|
+
const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
|
|
324
|
+
let path = [lng, ns];
|
|
325
|
+
if (key && typeof key !== 'string') path = path.concat(key);
|
|
326
|
+
if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
|
|
327
|
+
if (lng.indexOf('.') > -1) {
|
|
328
|
+
path = lng.split('.');
|
|
329
|
+
}
|
|
330
|
+
const result = getPath(this.data, path);
|
|
331
|
+
if (result || !ignoreJSONStructure || typeof key !== 'string') return result;
|
|
332
|
+
return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
|
|
333
|
+
}
|
|
334
|
+
addResource(lng, ns, key, value) {
|
|
335
|
+
let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
|
|
336
|
+
silent: false
|
|
337
|
+
};
|
|
338
|
+
const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
|
|
339
|
+
let path = [lng, ns];
|
|
340
|
+
if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
|
|
341
|
+
if (lng.indexOf('.') > -1) {
|
|
342
|
+
path = lng.split('.');
|
|
343
|
+
value = ns;
|
|
344
|
+
ns = path[1];
|
|
345
|
+
}
|
|
346
|
+
this.addNamespaces(ns);
|
|
347
|
+
setPath(this.data, path, value);
|
|
348
|
+
if (!options.silent) this.emit('added', lng, ns, key, value);
|
|
349
|
+
}
|
|
350
|
+
addResources(lng, ns, resources) {
|
|
351
|
+
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
|
|
352
|
+
silent: false
|
|
353
|
+
};
|
|
354
|
+
for (const m in resources) {
|
|
355
|
+
if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {
|
|
356
|
+
silent: true
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
if (!options.silent) this.emit('added', lng, ns, resources);
|
|
360
|
+
}
|
|
361
|
+
addResourceBundle(lng, ns, resources, deep, overwrite) {
|
|
362
|
+
let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
|
|
363
|
+
silent: false
|
|
364
|
+
};
|
|
365
|
+
let path = [lng, ns];
|
|
366
|
+
if (lng.indexOf('.') > -1) {
|
|
367
|
+
path = lng.split('.');
|
|
368
|
+
deep = resources;
|
|
369
|
+
resources = ns;
|
|
370
|
+
ns = path[1];
|
|
371
|
+
}
|
|
372
|
+
this.addNamespaces(ns);
|
|
373
|
+
let pack = getPath(this.data, path) || {};
|
|
374
|
+
if (deep) {
|
|
375
|
+
deepExtend(pack, resources, overwrite);
|
|
376
|
+
} else {
|
|
377
|
+
pack = {
|
|
378
|
+
...pack,
|
|
379
|
+
...resources
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
setPath(this.data, path, pack);
|
|
383
|
+
if (!options.silent) this.emit('added', lng, ns, resources);
|
|
384
|
+
}
|
|
385
|
+
removeResourceBundle(lng, ns) {
|
|
386
|
+
if (this.hasResourceBundle(lng, ns)) {
|
|
387
|
+
delete this.data[lng][ns];
|
|
388
|
+
}
|
|
389
|
+
this.removeNamespaces(ns);
|
|
390
|
+
this.emit('removed', lng, ns);
|
|
391
|
+
}
|
|
392
|
+
hasResourceBundle(lng, ns) {
|
|
393
|
+
return this.getResource(lng, ns) !== undefined;
|
|
394
|
+
}
|
|
395
|
+
getResourceBundle(lng, ns) {
|
|
396
|
+
if (!ns) ns = this.options.defaultNS;
|
|
397
|
+
if (this.options.compatibilityAPI === 'v1') return {
|
|
398
|
+
...{},
|
|
399
|
+
...this.getResource(lng, ns)
|
|
400
|
+
};
|
|
401
|
+
return this.getResource(lng, ns);
|
|
402
|
+
}
|
|
403
|
+
getDataByLanguage(lng) {
|
|
404
|
+
return this.data[lng];
|
|
405
|
+
}
|
|
406
|
+
hasLanguageSomeTranslations(lng) {
|
|
407
|
+
const data = this.getDataByLanguage(lng);
|
|
408
|
+
const n = data && Object.keys(data) || [];
|
|
409
|
+
return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
|
|
410
|
+
}
|
|
411
|
+
toJSON() {
|
|
412
|
+
return this.data;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
var postProcessor = {
|
|
417
|
+
processors: {},
|
|
418
|
+
addPostProcessor(module) {
|
|
419
|
+
this.processors[module.name] = module;
|
|
420
|
+
},
|
|
421
|
+
handle(processors, value, key, options, translator) {
|
|
422
|
+
processors.forEach(processor => {
|
|
423
|
+
if (this.processors[processor]) value = this.processors[processor].process(value, key, options, translator);
|
|
424
|
+
});
|
|
425
|
+
return value;
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
const checkedLoadedFor = {};
|
|
430
|
+
class Translator extends EventEmitter {
|
|
431
|
+
constructor(services) {
|
|
432
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
433
|
+
super();
|
|
434
|
+
copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
|
|
435
|
+
this.options = options;
|
|
436
|
+
if (this.options.keySeparator === undefined) {
|
|
437
|
+
this.options.keySeparator = '.';
|
|
438
|
+
}
|
|
439
|
+
this.logger = baseLogger.create('translator');
|
|
440
|
+
}
|
|
441
|
+
changeLanguage(lng) {
|
|
442
|
+
if (lng) this.language = lng;
|
|
443
|
+
}
|
|
444
|
+
exists(key) {
|
|
445
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
|
|
446
|
+
interpolation: {}
|
|
447
|
+
};
|
|
448
|
+
if (key === undefined || key === null) {
|
|
449
|
+
return false;
|
|
450
|
+
}
|
|
451
|
+
const resolved = this.resolve(key, options);
|
|
452
|
+
return resolved && resolved.res !== undefined;
|
|
453
|
+
}
|
|
454
|
+
extractFromKey(key, options) {
|
|
455
|
+
let nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
|
|
456
|
+
if (nsSeparator === undefined) nsSeparator = ':';
|
|
457
|
+
const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
|
|
458
|
+
let namespaces = options.ns || this.options.defaultNS || [];
|
|
459
|
+
const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
|
|
460
|
+
const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
|
|
461
|
+
if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
|
|
462
|
+
const m = key.match(this.interpolator.nestingRegexp);
|
|
463
|
+
if (m && m.length > 0) {
|
|
464
|
+
return {
|
|
465
|
+
key,
|
|
466
|
+
namespaces
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
const parts = key.split(nsSeparator);
|
|
470
|
+
if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
|
|
471
|
+
key = parts.join(keySeparator);
|
|
472
|
+
}
|
|
473
|
+
if (typeof namespaces === 'string') namespaces = [namespaces];
|
|
474
|
+
return {
|
|
475
|
+
key,
|
|
476
|
+
namespaces
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
translate(keys, options, lastKey) {
|
|
480
|
+
if (typeof options !== 'object' && this.options.overloadTranslationOptionHandler) {
|
|
481
|
+
options = this.options.overloadTranslationOptionHandler(arguments);
|
|
482
|
+
}
|
|
483
|
+
if (typeof options === 'object') options = {
|
|
484
|
+
...options
|
|
485
|
+
};
|
|
486
|
+
if (!options) options = {};
|
|
487
|
+
if (keys === undefined || keys === null) return '';
|
|
488
|
+
if (!Array.isArray(keys)) keys = [String(keys)];
|
|
489
|
+
const returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails;
|
|
490
|
+
const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
|
|
491
|
+
const {
|
|
492
|
+
key,
|
|
493
|
+
namespaces
|
|
494
|
+
} = this.extractFromKey(keys[keys.length - 1], options);
|
|
495
|
+
const namespace = namespaces[namespaces.length - 1];
|
|
496
|
+
const lng = options.lng || this.language;
|
|
497
|
+
const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
|
|
498
|
+
if (lng && lng.toLowerCase() === 'cimode') {
|
|
499
|
+
if (appendNamespaceToCIMode) {
|
|
500
|
+
const nsSeparator = options.nsSeparator || this.options.nsSeparator;
|
|
501
|
+
if (returnDetails) {
|
|
502
|
+
return {
|
|
503
|
+
res: `${namespace}${nsSeparator}${key}`,
|
|
504
|
+
usedKey: key,
|
|
505
|
+
exactUsedKey: key,
|
|
506
|
+
usedLng: lng,
|
|
507
|
+
usedNS: namespace
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
return `${namespace}${nsSeparator}${key}`;
|
|
511
|
+
}
|
|
512
|
+
if (returnDetails) {
|
|
513
|
+
return {
|
|
514
|
+
res: key,
|
|
515
|
+
usedKey: key,
|
|
516
|
+
exactUsedKey: key,
|
|
517
|
+
usedLng: lng,
|
|
518
|
+
usedNS: namespace
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
return key;
|
|
522
|
+
}
|
|
523
|
+
const resolved = this.resolve(keys, options);
|
|
524
|
+
let res = resolved && resolved.res;
|
|
525
|
+
const resUsedKey = resolved && resolved.usedKey || key;
|
|
526
|
+
const resExactUsedKey = resolved && resolved.exactUsedKey || key;
|
|
527
|
+
const resType = Object.prototype.toString.apply(res);
|
|
528
|
+
const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
|
|
529
|
+
const joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
|
|
530
|
+
const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
|
|
531
|
+
const handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';
|
|
532
|
+
if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {
|
|
533
|
+
if (!options.returnObjects && !this.options.returnObjects) {
|
|
534
|
+
if (!this.options.returnedObjectHandler) {
|
|
535
|
+
this.logger.warn('accessing an object - but returnObjects options is not enabled!');
|
|
536
|
+
}
|
|
537
|
+
const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, {
|
|
538
|
+
...options,
|
|
539
|
+
ns: namespaces
|
|
540
|
+
}) : `key '${key} (${this.language})' returned an object instead of string.`;
|
|
541
|
+
if (returnDetails) {
|
|
542
|
+
resolved.res = r;
|
|
543
|
+
return resolved;
|
|
544
|
+
}
|
|
545
|
+
return r;
|
|
546
|
+
}
|
|
547
|
+
if (keySeparator) {
|
|
548
|
+
const resTypeIsArray = resType === '[object Array]';
|
|
549
|
+
const copy = resTypeIsArray ? [] : {};
|
|
550
|
+
const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
|
|
551
|
+
for (const m in res) {
|
|
552
|
+
if (Object.prototype.hasOwnProperty.call(res, m)) {
|
|
553
|
+
const deepKey = `${newKeyToUse}${keySeparator}${m}`;
|
|
554
|
+
copy[m] = this.translate(deepKey, {
|
|
555
|
+
...options,
|
|
556
|
+
...{
|
|
557
|
+
joinArrays: false,
|
|
558
|
+
ns: namespaces
|
|
559
|
+
}
|
|
560
|
+
});
|
|
561
|
+
if (copy[m] === deepKey) copy[m] = res[m];
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
res = copy;
|
|
565
|
+
}
|
|
566
|
+
} else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {
|
|
567
|
+
res = res.join(joinArrays);
|
|
568
|
+
if (res) res = this.extendTranslation(res, keys, options, lastKey);
|
|
569
|
+
} else {
|
|
570
|
+
let usedDefault = false;
|
|
571
|
+
let usedKey = false;
|
|
572
|
+
const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
|
|
573
|
+
const hasDefaultValue = Translator.hasDefaultValue(options);
|
|
574
|
+
const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';
|
|
575
|
+
const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {
|
|
576
|
+
ordinal: false
|
|
577
|
+
}) : '';
|
|
578
|
+
const defaultValue = options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;
|
|
579
|
+
if (!this.isValidLookup(res) && hasDefaultValue) {
|
|
580
|
+
usedDefault = true;
|
|
581
|
+
res = defaultValue;
|
|
582
|
+
}
|
|
583
|
+
if (!this.isValidLookup(res)) {
|
|
584
|
+
usedKey = true;
|
|
585
|
+
res = key;
|
|
586
|
+
}
|
|
587
|
+
const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
|
|
588
|
+
const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
|
|
589
|
+
const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
|
|
590
|
+
if (usedKey || usedDefault || updateMissing) {
|
|
591
|
+
this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
|
|
592
|
+
if (keySeparator) {
|
|
593
|
+
const fk = this.resolve(key, {
|
|
594
|
+
...options,
|
|
595
|
+
keySeparator: false
|
|
596
|
+
});
|
|
597
|
+
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.');
|
|
598
|
+
}
|
|
599
|
+
let lngs = [];
|
|
600
|
+
const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
|
|
601
|
+
if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
|
|
602
|
+
for (let i = 0; i < fallbackLngs.length; i++) {
|
|
603
|
+
lngs.push(fallbackLngs[i]);
|
|
604
|
+
}
|
|
605
|
+
} else if (this.options.saveMissingTo === 'all') {
|
|
606
|
+
lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
|
|
607
|
+
} else {
|
|
608
|
+
lngs.push(options.lng || this.language);
|
|
609
|
+
}
|
|
610
|
+
const send = (l, k, specificDefaultValue) => {
|
|
611
|
+
const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
|
|
612
|
+
if (this.options.missingKeyHandler) {
|
|
613
|
+
this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
|
|
614
|
+
} else if (this.backendConnector && this.backendConnector.saveMissing) {
|
|
615
|
+
this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
|
|
616
|
+
}
|
|
617
|
+
this.emit('missingKey', l, namespace, k, res);
|
|
618
|
+
};
|
|
619
|
+
if (this.options.saveMissing) {
|
|
620
|
+
if (this.options.saveMissingPlurals && needsPluralHandling) {
|
|
621
|
+
lngs.forEach(language => {
|
|
622
|
+
this.pluralResolver.getSuffixes(language, options).forEach(suffix => {
|
|
623
|
+
send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue);
|
|
624
|
+
});
|
|
625
|
+
});
|
|
626
|
+
} else {
|
|
627
|
+
send(lngs, key, defaultValue);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
res = this.extendTranslation(res, keys, options, resolved, lastKey);
|
|
632
|
+
if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`;
|
|
633
|
+
if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
|
|
634
|
+
if (this.options.compatibilityAPI !== 'v1') {
|
|
635
|
+
res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : undefined);
|
|
636
|
+
} else {
|
|
637
|
+
res = this.options.parseMissingKeyHandler(res);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
if (returnDetails) {
|
|
642
|
+
resolved.res = res;
|
|
643
|
+
return resolved;
|
|
644
|
+
}
|
|
645
|
+
return res;
|
|
646
|
+
}
|
|
647
|
+
extendTranslation(res, key, options, resolved, lastKey) {
|
|
648
|
+
var _this = this;
|
|
649
|
+
if (this.i18nFormat && this.i18nFormat.parse) {
|
|
650
|
+
res = this.i18nFormat.parse(res, {
|
|
651
|
+
...this.options.interpolation.defaultVariables,
|
|
652
|
+
...options
|
|
653
|
+
}, resolved.usedLng, resolved.usedNS, resolved.usedKey, {
|
|
654
|
+
resolved
|
|
655
|
+
});
|
|
656
|
+
} else if (!options.skipInterpolation) {
|
|
657
|
+
if (options.interpolation) this.interpolator.init({
|
|
658
|
+
...options,
|
|
659
|
+
...{
|
|
660
|
+
interpolation: {
|
|
661
|
+
...this.options.interpolation,
|
|
662
|
+
...options.interpolation
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
});
|
|
666
|
+
const skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
|
|
667
|
+
let nestBef;
|
|
668
|
+
if (skipOnVariables) {
|
|
669
|
+
const nb = res.match(this.interpolator.nestingRegexp);
|
|
670
|
+
nestBef = nb && nb.length;
|
|
671
|
+
}
|
|
672
|
+
let data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
|
|
673
|
+
if (this.options.interpolation.defaultVariables) data = {
|
|
674
|
+
...this.options.interpolation.defaultVariables,
|
|
675
|
+
...data
|
|
676
|
+
};
|
|
677
|
+
res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
|
|
678
|
+
if (skipOnVariables) {
|
|
679
|
+
const na = res.match(this.interpolator.nestingRegexp);
|
|
680
|
+
const nestAft = na && na.length;
|
|
681
|
+
if (nestBef < nestAft) options.nest = false;
|
|
682
|
+
}
|
|
683
|
+
if (!options.lng && this.options.compatibilityAPI !== 'v1' && resolved && resolved.res) options.lng = resolved.usedLng;
|
|
684
|
+
if (options.nest !== false) res = this.interpolator.nest(res, function () {
|
|
685
|
+
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
|
686
|
+
args[_key] = arguments[_key];
|
|
687
|
+
}
|
|
688
|
+
if (lastKey && lastKey[0] === args[0] && !options.context) {
|
|
689
|
+
_this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
|
|
690
|
+
return null;
|
|
691
|
+
}
|
|
692
|
+
return _this.translate(...args, key);
|
|
693
|
+
}, options);
|
|
694
|
+
if (options.interpolation) this.interpolator.reset();
|
|
695
|
+
}
|
|
696
|
+
const postProcess = options.postProcess || this.options.postProcess;
|
|
697
|
+
const postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
|
|
698
|
+
if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
|
|
699
|
+
res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
|
|
700
|
+
i18nResolved: resolved,
|
|
701
|
+
...options
|
|
702
|
+
} : options, this);
|
|
703
|
+
}
|
|
704
|
+
return res;
|
|
705
|
+
}
|
|
706
|
+
resolve(keys) {
|
|
707
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
708
|
+
let found;
|
|
709
|
+
let usedKey;
|
|
710
|
+
let exactUsedKey;
|
|
711
|
+
let usedLng;
|
|
712
|
+
let usedNS;
|
|
713
|
+
if (typeof keys === 'string') keys = [keys];
|
|
714
|
+
keys.forEach(k => {
|
|
715
|
+
if (this.isValidLookup(found)) return;
|
|
716
|
+
const extracted = this.extractFromKey(k, options);
|
|
717
|
+
const key = extracted.key;
|
|
718
|
+
usedKey = key;
|
|
719
|
+
let namespaces = extracted.namespaces;
|
|
720
|
+
if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
|
|
721
|
+
const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
|
|
722
|
+
const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();
|
|
723
|
+
const needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';
|
|
724
|
+
const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);
|
|
725
|
+
namespaces.forEach(ns => {
|
|
726
|
+
if (this.isValidLookup(found)) return;
|
|
727
|
+
usedNS = ns;
|
|
728
|
+
if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils && this.utils.hasLoadedNamespace && !this.utils.hasLoadedNamespace(usedNS)) {
|
|
729
|
+
checkedLoadedFor[`${codes[0]}-${ns}`] = true;
|
|
730
|
+
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!!!');
|
|
731
|
+
}
|
|
732
|
+
codes.forEach(code => {
|
|
733
|
+
if (this.isValidLookup(found)) return;
|
|
734
|
+
usedLng = code;
|
|
735
|
+
const finalKeys = [key];
|
|
736
|
+
if (this.i18nFormat && this.i18nFormat.addLookupKeys) {
|
|
737
|
+
this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
|
|
738
|
+
} else {
|
|
739
|
+
let pluralSuffix;
|
|
740
|
+
if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);
|
|
741
|
+
const zeroSuffix = `${this.options.pluralSeparator}zero`;
|
|
742
|
+
const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
|
|
743
|
+
if (needsPluralHandling) {
|
|
744
|
+
finalKeys.push(key + pluralSuffix);
|
|
745
|
+
if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
|
|
746
|
+
finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
|
|
747
|
+
}
|
|
748
|
+
if (needsZeroSuffixLookup) {
|
|
749
|
+
finalKeys.push(key + zeroSuffix);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
if (needsContextHandling) {
|
|
753
|
+
const contextKey = `${key}${this.options.contextSeparator}${options.context}`;
|
|
754
|
+
finalKeys.push(contextKey);
|
|
755
|
+
if (needsPluralHandling) {
|
|
756
|
+
finalKeys.push(contextKey + pluralSuffix);
|
|
757
|
+
if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
|
|
758
|
+
finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
|
|
759
|
+
}
|
|
760
|
+
if (needsZeroSuffixLookup) {
|
|
761
|
+
finalKeys.push(contextKey + zeroSuffix);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
let possibleKey;
|
|
767
|
+
while (possibleKey = finalKeys.pop()) {
|
|
768
|
+
if (!this.isValidLookup(found)) {
|
|
769
|
+
exactUsedKey = possibleKey;
|
|
770
|
+
found = this.getResource(code, ns, possibleKey, options);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
});
|
|
774
|
+
});
|
|
775
|
+
});
|
|
776
|
+
return {
|
|
777
|
+
res: found,
|
|
778
|
+
usedKey,
|
|
779
|
+
exactUsedKey,
|
|
780
|
+
usedLng,
|
|
781
|
+
usedNS
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
isValidLookup(res) {
|
|
785
|
+
return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
|
|
786
|
+
}
|
|
787
|
+
getResource(code, ns, key) {
|
|
788
|
+
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
|
|
789
|
+
if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
|
|
790
|
+
return this.resourceStore.getResource(code, ns, key, options);
|
|
791
|
+
}
|
|
792
|
+
static hasDefaultValue(options) {
|
|
793
|
+
const prefix = 'defaultValue';
|
|
794
|
+
for (const option in options) {
|
|
795
|
+
if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
|
|
796
|
+
return true;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
return false;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
function capitalize(string) {
|
|
804
|
+
return string.charAt(0).toUpperCase() + string.slice(1);
|
|
805
|
+
}
|
|
806
|
+
class LanguageUtil {
|
|
807
|
+
constructor(options) {
|
|
808
|
+
this.options = options;
|
|
809
|
+
this.supportedLngs = this.options.supportedLngs || false;
|
|
810
|
+
this.logger = baseLogger.create('languageUtils');
|
|
811
|
+
}
|
|
812
|
+
getScriptPartFromCode(code) {
|
|
813
|
+
code = getCleanedCode(code);
|
|
814
|
+
if (!code || code.indexOf('-') < 0) return null;
|
|
815
|
+
const p = code.split('-');
|
|
816
|
+
if (p.length === 2) return null;
|
|
817
|
+
p.pop();
|
|
818
|
+
if (p[p.length - 1].toLowerCase() === 'x') return null;
|
|
819
|
+
return this.formatLanguageCode(p.join('-'));
|
|
820
|
+
}
|
|
821
|
+
getLanguagePartFromCode(code) {
|
|
822
|
+
code = getCleanedCode(code);
|
|
823
|
+
if (!code || code.indexOf('-') < 0) return code;
|
|
824
|
+
const p = code.split('-');
|
|
825
|
+
return this.formatLanguageCode(p[0]);
|
|
826
|
+
}
|
|
827
|
+
formatLanguageCode(code) {
|
|
828
|
+
if (typeof code === 'string' && code.indexOf('-') > -1) {
|
|
829
|
+
const specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
|
|
830
|
+
let p = code.split('-');
|
|
831
|
+
if (this.options.lowerCaseLng) {
|
|
832
|
+
p = p.map(part => part.toLowerCase());
|
|
833
|
+
} else if (p.length === 2) {
|
|
834
|
+
p[0] = p[0].toLowerCase();
|
|
835
|
+
p[1] = p[1].toUpperCase();
|
|
836
|
+
if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
|
|
837
|
+
} else if (p.length === 3) {
|
|
838
|
+
p[0] = p[0].toLowerCase();
|
|
839
|
+
if (p[1].length === 2) p[1] = p[1].toUpperCase();
|
|
840
|
+
if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
|
|
841
|
+
if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
|
|
842
|
+
if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
|
|
843
|
+
}
|
|
844
|
+
return p.join('-');
|
|
845
|
+
}
|
|
846
|
+
return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
|
|
847
|
+
}
|
|
848
|
+
isSupportedCode(code) {
|
|
849
|
+
if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
|
|
850
|
+
code = this.getLanguagePartFromCode(code);
|
|
851
|
+
}
|
|
852
|
+
return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
|
|
853
|
+
}
|
|
854
|
+
getBestMatchFromCodes(codes) {
|
|
855
|
+
if (!codes) return null;
|
|
856
|
+
let found;
|
|
857
|
+
codes.forEach(code => {
|
|
858
|
+
if (found) return;
|
|
859
|
+
const cleanedLng = this.formatLanguageCode(code);
|
|
860
|
+
if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
|
|
861
|
+
});
|
|
862
|
+
if (!found && this.options.supportedLngs) {
|
|
863
|
+
codes.forEach(code => {
|
|
864
|
+
if (found) return;
|
|
865
|
+
const lngOnly = this.getLanguagePartFromCode(code);
|
|
866
|
+
if (this.isSupportedCode(lngOnly)) return found = lngOnly;
|
|
867
|
+
found = this.options.supportedLngs.find(supportedLng => {
|
|
868
|
+
if (supportedLng === lngOnly) return supportedLng;
|
|
869
|
+
if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
|
|
870
|
+
if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;
|
|
871
|
+
});
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
|
|
875
|
+
return found;
|
|
876
|
+
}
|
|
877
|
+
getFallbackCodes(fallbacks, code) {
|
|
878
|
+
if (!fallbacks) return [];
|
|
879
|
+
if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
|
|
880
|
+
if (typeof fallbacks === 'string') fallbacks = [fallbacks];
|
|
881
|
+
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
|
|
882
|
+
if (!code) return fallbacks.default || [];
|
|
883
|
+
let found = fallbacks[code];
|
|
884
|
+
if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
|
|
885
|
+
if (!found) found = fallbacks[this.formatLanguageCode(code)];
|
|
886
|
+
if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
|
|
887
|
+
if (!found) found = fallbacks.default;
|
|
888
|
+
return found || [];
|
|
889
|
+
}
|
|
890
|
+
toResolveHierarchy(code, fallbackCode) {
|
|
891
|
+
const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
|
|
892
|
+
const codes = [];
|
|
893
|
+
const addCode = c => {
|
|
894
|
+
if (!c) return;
|
|
895
|
+
if (this.isSupportedCode(c)) {
|
|
896
|
+
codes.push(c);
|
|
897
|
+
} else {
|
|
898
|
+
this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
|
|
899
|
+
}
|
|
900
|
+
};
|
|
901
|
+
if (typeof code === 'string' && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
|
|
902
|
+
if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
|
|
903
|
+
if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
|
|
904
|
+
if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
|
|
905
|
+
} else if (typeof code === 'string') {
|
|
906
|
+
addCode(this.formatLanguageCode(code));
|
|
907
|
+
}
|
|
908
|
+
fallbackCodes.forEach(fc => {
|
|
909
|
+
if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
|
|
910
|
+
});
|
|
911
|
+
return codes;
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
let sets = [{
|
|
916
|
+
lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],
|
|
917
|
+
nr: [1, 2],
|
|
918
|
+
fc: 1
|
|
919
|
+
}, {
|
|
920
|
+
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'],
|
|
921
|
+
nr: [1, 2],
|
|
922
|
+
fc: 2
|
|
923
|
+
}, {
|
|
924
|
+
lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
|
|
925
|
+
nr: [1],
|
|
926
|
+
fc: 3
|
|
927
|
+
}, {
|
|
928
|
+
lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
|
|
929
|
+
nr: [1, 2, 5],
|
|
930
|
+
fc: 4
|
|
931
|
+
}, {
|
|
932
|
+
lngs: ['ar'],
|
|
933
|
+
nr: [0, 1, 2, 3, 11, 100],
|
|
934
|
+
fc: 5
|
|
935
|
+
}, {
|
|
936
|
+
lngs: ['cs', 'sk'],
|
|
937
|
+
nr: [1, 2, 5],
|
|
938
|
+
fc: 6
|
|
939
|
+
}, {
|
|
940
|
+
lngs: ['csb', 'pl'],
|
|
941
|
+
nr: [1, 2, 5],
|
|
942
|
+
fc: 7
|
|
943
|
+
}, {
|
|
944
|
+
lngs: ['cy'],
|
|
945
|
+
nr: [1, 2, 3, 8],
|
|
946
|
+
fc: 8
|
|
947
|
+
}, {
|
|
948
|
+
lngs: ['fr'],
|
|
949
|
+
nr: [1, 2],
|
|
950
|
+
fc: 9
|
|
951
|
+
}, {
|
|
952
|
+
lngs: ['ga'],
|
|
953
|
+
nr: [1, 2, 3, 7, 11],
|
|
954
|
+
fc: 10
|
|
955
|
+
}, {
|
|
956
|
+
lngs: ['gd'],
|
|
957
|
+
nr: [1, 2, 3, 20],
|
|
958
|
+
fc: 11
|
|
959
|
+
}, {
|
|
960
|
+
lngs: ['is'],
|
|
961
|
+
nr: [1, 2],
|
|
962
|
+
fc: 12
|
|
963
|
+
}, {
|
|
964
|
+
lngs: ['jv'],
|
|
965
|
+
nr: [0, 1],
|
|
966
|
+
fc: 13
|
|
967
|
+
}, {
|
|
968
|
+
lngs: ['kw'],
|
|
969
|
+
nr: [1, 2, 3, 4],
|
|
970
|
+
fc: 14
|
|
971
|
+
}, {
|
|
972
|
+
lngs: ['lt'],
|
|
973
|
+
nr: [1, 2, 10],
|
|
974
|
+
fc: 15
|
|
975
|
+
}, {
|
|
976
|
+
lngs: ['lv'],
|
|
977
|
+
nr: [1, 2, 0],
|
|
978
|
+
fc: 16
|
|
979
|
+
}, {
|
|
980
|
+
lngs: ['mk'],
|
|
981
|
+
nr: [1, 2],
|
|
982
|
+
fc: 17
|
|
983
|
+
}, {
|
|
984
|
+
lngs: ['mnk'],
|
|
985
|
+
nr: [0, 1, 2],
|
|
986
|
+
fc: 18
|
|
987
|
+
}, {
|
|
988
|
+
lngs: ['mt'],
|
|
989
|
+
nr: [1, 2, 11, 20],
|
|
990
|
+
fc: 19
|
|
991
|
+
}, {
|
|
992
|
+
lngs: ['or'],
|
|
993
|
+
nr: [2, 1],
|
|
994
|
+
fc: 2
|
|
995
|
+
}, {
|
|
996
|
+
lngs: ['ro'],
|
|
997
|
+
nr: [1, 2, 20],
|
|
998
|
+
fc: 20
|
|
999
|
+
}, {
|
|
1000
|
+
lngs: ['sl'],
|
|
1001
|
+
nr: [5, 1, 2, 3],
|
|
1002
|
+
fc: 21
|
|
1003
|
+
}, {
|
|
1004
|
+
lngs: ['he', 'iw'],
|
|
1005
|
+
nr: [1, 2, 20, 21],
|
|
1006
|
+
fc: 22
|
|
1007
|
+
}];
|
|
1008
|
+
let _rulesPluralsTypes = {
|
|
1009
|
+
1: function (n) {
|
|
1010
|
+
return Number(n > 1);
|
|
1011
|
+
},
|
|
1012
|
+
2: function (n) {
|
|
1013
|
+
return Number(n != 1);
|
|
1014
|
+
},
|
|
1015
|
+
3: function (n) {
|
|
1016
|
+
return 0;
|
|
1017
|
+
},
|
|
1018
|
+
4: function (n) {
|
|
1019
|
+
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
|
|
1020
|
+
},
|
|
1021
|
+
5: function (n) {
|
|
1022
|
+
return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
|
|
1023
|
+
},
|
|
1024
|
+
6: function (n) {
|
|
1025
|
+
return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
|
|
1026
|
+
},
|
|
1027
|
+
7: function (n) {
|
|
1028
|
+
return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
|
|
1029
|
+
},
|
|
1030
|
+
8: function (n) {
|
|
1031
|
+
return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
|
|
1032
|
+
},
|
|
1033
|
+
9: function (n) {
|
|
1034
|
+
return Number(n >= 2);
|
|
1035
|
+
},
|
|
1036
|
+
10: function (n) {
|
|
1037
|
+
return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
|
|
1038
|
+
},
|
|
1039
|
+
11: function (n) {
|
|
1040
|
+
return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
|
|
1041
|
+
},
|
|
1042
|
+
12: function (n) {
|
|
1043
|
+
return Number(n % 10 != 1 || n % 100 == 11);
|
|
1044
|
+
},
|
|
1045
|
+
13: function (n) {
|
|
1046
|
+
return Number(n !== 0);
|
|
1047
|
+
},
|
|
1048
|
+
14: function (n) {
|
|
1049
|
+
return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
|
|
1050
|
+
},
|
|
1051
|
+
15: function (n) {
|
|
1052
|
+
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
|
|
1053
|
+
},
|
|
1054
|
+
16: function (n) {
|
|
1055
|
+
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
|
|
1056
|
+
},
|
|
1057
|
+
17: function (n) {
|
|
1058
|
+
return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);
|
|
1059
|
+
},
|
|
1060
|
+
18: function (n) {
|
|
1061
|
+
return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
|
|
1062
|
+
},
|
|
1063
|
+
19: function (n) {
|
|
1064
|
+
return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
|
|
1065
|
+
},
|
|
1066
|
+
20: function (n) {
|
|
1067
|
+
return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
|
|
1068
|
+
},
|
|
1069
|
+
21: function (n) {
|
|
1070
|
+
return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
|
|
1071
|
+
},
|
|
1072
|
+
22: function (n) {
|
|
1073
|
+
return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
const nonIntlVersions = ['v1', 'v2', 'v3'];
|
|
1077
|
+
const intlVersions = ['v4'];
|
|
1078
|
+
const suffixesOrder = {
|
|
1079
|
+
zero: 0,
|
|
1080
|
+
one: 1,
|
|
1081
|
+
two: 2,
|
|
1082
|
+
few: 3,
|
|
1083
|
+
many: 4,
|
|
1084
|
+
other: 5
|
|
1085
|
+
};
|
|
1086
|
+
function createRules() {
|
|
1087
|
+
const rules = {};
|
|
1088
|
+
sets.forEach(set => {
|
|
1089
|
+
set.lngs.forEach(l => {
|
|
1090
|
+
rules[l] = {
|
|
1091
|
+
numbers: set.nr,
|
|
1092
|
+
plurals: _rulesPluralsTypes[set.fc]
|
|
1093
|
+
};
|
|
1094
|
+
});
|
|
1095
|
+
});
|
|
1096
|
+
return rules;
|
|
1097
|
+
}
|
|
1098
|
+
class PluralResolver {
|
|
1099
|
+
constructor(languageUtils) {
|
|
1100
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
1101
|
+
this.languageUtils = languageUtils;
|
|
1102
|
+
this.options = options;
|
|
1103
|
+
this.logger = baseLogger.create('pluralResolver');
|
|
1104
|
+
if ((!this.options.compatibilityJSON || intlVersions.includes(this.options.compatibilityJSON)) && (typeof Intl === 'undefined' || !Intl.PluralRules)) {
|
|
1105
|
+
this.options.compatibilityJSON = 'v3';
|
|
1106
|
+
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.');
|
|
1107
|
+
}
|
|
1108
|
+
this.rules = createRules();
|
|
1109
|
+
}
|
|
1110
|
+
addRule(lng, obj) {
|
|
1111
|
+
this.rules[lng] = obj;
|
|
1112
|
+
}
|
|
1113
|
+
getRule(code) {
|
|
1114
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
1115
|
+
if (this.shouldUseIntlApi()) {
|
|
1116
|
+
try {
|
|
1117
|
+
return new Intl.PluralRules(getCleanedCode(code), {
|
|
1118
|
+
type: options.ordinal ? 'ordinal' : 'cardinal'
|
|
1119
|
+
});
|
|
1120
|
+
} catch {
|
|
1121
|
+
return;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
|
|
1125
|
+
}
|
|
1126
|
+
needsPlural(code) {
|
|
1127
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
1128
|
+
const rule = this.getRule(code, options);
|
|
1129
|
+
if (this.shouldUseIntlApi()) {
|
|
1130
|
+
return rule && rule.resolvedOptions().pluralCategories.length > 1;
|
|
1131
|
+
}
|
|
1132
|
+
return rule && rule.numbers.length > 1;
|
|
1133
|
+
}
|
|
1134
|
+
getPluralFormsOfKey(code, key) {
|
|
1135
|
+
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
|
1136
|
+
return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
|
|
1137
|
+
}
|
|
1138
|
+
getSuffixes(code) {
|
|
1139
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
1140
|
+
const rule = this.getRule(code, options);
|
|
1141
|
+
if (!rule) {
|
|
1142
|
+
return [];
|
|
1143
|
+
}
|
|
1144
|
+
if (this.shouldUseIntlApi()) {
|
|
1145
|
+
return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
|
|
1146
|
+
}
|
|
1147
|
+
return rule.numbers.map(number => this.getSuffix(code, number, options));
|
|
1148
|
+
}
|
|
1149
|
+
getSuffix(code, count) {
|
|
1150
|
+
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
|
1151
|
+
const rule = this.getRule(code, options);
|
|
1152
|
+
if (rule) {
|
|
1153
|
+
if (this.shouldUseIntlApi()) {
|
|
1154
|
+
return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
|
|
1155
|
+
}
|
|
1156
|
+
return this.getSuffixRetroCompatible(rule, count);
|
|
1157
|
+
}
|
|
1158
|
+
this.logger.warn(`no plural rule found for: ${code}`);
|
|
1159
|
+
return '';
|
|
1160
|
+
}
|
|
1161
|
+
getSuffixRetroCompatible(rule, count) {
|
|
1162
|
+
const idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
|
|
1163
|
+
let suffix = rule.numbers[idx];
|
|
1164
|
+
if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
|
|
1165
|
+
if (suffix === 2) {
|
|
1166
|
+
suffix = 'plural';
|
|
1167
|
+
} else if (suffix === 1) {
|
|
1168
|
+
suffix = '';
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
const returnSuffix = () => this.options.prepend && suffix.toString() ? this.options.prepend + suffix.toString() : suffix.toString();
|
|
1172
|
+
if (this.options.compatibilityJSON === 'v1') {
|
|
1173
|
+
if (suffix === 1) return '';
|
|
1174
|
+
if (typeof suffix === 'number') return `_plural_${suffix.toString()}`;
|
|
1175
|
+
return returnSuffix();
|
|
1176
|
+
} else if (this.options.compatibilityJSON === 'v2') {
|
|
1177
|
+
return returnSuffix();
|
|
1178
|
+
} else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
|
|
1179
|
+
return returnSuffix();
|
|
1180
|
+
}
|
|
1181
|
+
return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
|
|
1182
|
+
}
|
|
1183
|
+
shouldUseIntlApi() {
|
|
1184
|
+
return !nonIntlVersions.includes(this.options.compatibilityJSON);
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
function deepFindWithDefaults(data, defaultData, key) {
|
|
1189
|
+
let keySeparator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '.';
|
|
1190
|
+
let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
|
|
1191
|
+
let path = getPathWithDefaults(data, defaultData, key);
|
|
1192
|
+
if (!path && ignoreJSONStructure && typeof key === 'string') {
|
|
1193
|
+
path = deepFind(data, key, keySeparator);
|
|
1194
|
+
if (path === undefined) path = deepFind(defaultData, key, keySeparator);
|
|
1195
|
+
}
|
|
1196
|
+
return path;
|
|
1197
|
+
}
|
|
1198
|
+
class Interpolator {
|
|
1199
|
+
constructor() {
|
|
1200
|
+
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
1201
|
+
this.logger = baseLogger.create('interpolator');
|
|
1202
|
+
this.options = options;
|
|
1203
|
+
this.format = options.interpolation && options.interpolation.format || (value => value);
|
|
1204
|
+
this.init(options);
|
|
1205
|
+
}
|
|
1206
|
+
init() {
|
|
1207
|
+
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
1208
|
+
if (!options.interpolation) options.interpolation = {
|
|
1209
|
+
escapeValue: true
|
|
1210
|
+
};
|
|
1211
|
+
const iOpts = options.interpolation;
|
|
1212
|
+
this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
|
|
1213
|
+
this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
|
|
1214
|
+
this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;
|
|
1215
|
+
this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
|
|
1216
|
+
this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
|
|
1217
|
+
this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
|
|
1218
|
+
this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
|
|
1219
|
+
this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
|
|
1220
|
+
this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
|
|
1221
|
+
this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
|
|
1222
|
+
this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';
|
|
1223
|
+
this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
|
|
1224
|
+
this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;
|
|
1225
|
+
this.resetRegExp();
|
|
1226
|
+
}
|
|
1227
|
+
reset() {
|
|
1228
|
+
if (this.options) this.init(this.options);
|
|
1229
|
+
}
|
|
1230
|
+
resetRegExp() {
|
|
1231
|
+
const regexpStr = `${this.prefix}(.+?)${this.suffix}`;
|
|
1232
|
+
this.regexp = new RegExp(regexpStr, 'g');
|
|
1233
|
+
const regexpUnescapeStr = `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;
|
|
1234
|
+
this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
|
|
1235
|
+
const nestingRegexpStr = `${this.nestingPrefix}(.+?)${this.nestingSuffix}`;
|
|
1236
|
+
this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
|
|
1237
|
+
}
|
|
1238
|
+
interpolate(str, data, lng, options) {
|
|
1239
|
+
let match;
|
|
1240
|
+
let value;
|
|
1241
|
+
let replaces;
|
|
1242
|
+
const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
|
|
1243
|
+
function regexSafe(val) {
|
|
1244
|
+
return val.replace(/\$/g, '$$$$');
|
|
1245
|
+
}
|
|
1246
|
+
const handleFormat = key => {
|
|
1247
|
+
if (key.indexOf(this.formatSeparator) < 0) {
|
|
1248
|
+
const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
|
|
1249
|
+
return this.alwaysFormat ? this.format(path, undefined, lng, {
|
|
1250
|
+
...options,
|
|
1251
|
+
...data,
|
|
1252
|
+
interpolationkey: key
|
|
1253
|
+
}) : path;
|
|
1254
|
+
}
|
|
1255
|
+
const p = key.split(this.formatSeparator);
|
|
1256
|
+
const k = p.shift().trim();
|
|
1257
|
+
const f = p.join(this.formatSeparator).trim();
|
|
1258
|
+
return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
|
|
1259
|
+
...options,
|
|
1260
|
+
...data,
|
|
1261
|
+
interpolationkey: k
|
|
1262
|
+
});
|
|
1263
|
+
};
|
|
1264
|
+
this.resetRegExp();
|
|
1265
|
+
const missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
|
|
1266
|
+
const skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
|
|
1267
|
+
const todos = [{
|
|
1268
|
+
regex: this.regexpUnescape,
|
|
1269
|
+
safeValue: val => regexSafe(val)
|
|
1270
|
+
}, {
|
|
1271
|
+
regex: this.regexp,
|
|
1272
|
+
safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
|
|
1273
|
+
}];
|
|
1274
|
+
todos.forEach(todo => {
|
|
1275
|
+
replaces = 0;
|
|
1276
|
+
while (match = todo.regex.exec(str)) {
|
|
1277
|
+
const matchedVar = match[1].trim();
|
|
1278
|
+
value = handleFormat(matchedVar);
|
|
1279
|
+
if (value === undefined) {
|
|
1280
|
+
if (typeof missingInterpolationHandler === 'function') {
|
|
1281
|
+
const temp = missingInterpolationHandler(str, match, options);
|
|
1282
|
+
value = typeof temp === 'string' ? temp : '';
|
|
1283
|
+
} else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
|
|
1284
|
+
value = '';
|
|
1285
|
+
} else if (skipOnVariables) {
|
|
1286
|
+
value = match[0];
|
|
1287
|
+
continue;
|
|
1288
|
+
} else {
|
|
1289
|
+
this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
|
|
1290
|
+
value = '';
|
|
1291
|
+
}
|
|
1292
|
+
} else if (typeof value !== 'string' && !this.useRawValueToEscape) {
|
|
1293
|
+
value = makeString(value);
|
|
1294
|
+
}
|
|
1295
|
+
const safeValue = todo.safeValue(value);
|
|
1296
|
+
str = str.replace(match[0], safeValue);
|
|
1297
|
+
if (skipOnVariables) {
|
|
1298
|
+
todo.regex.lastIndex += value.length;
|
|
1299
|
+
todo.regex.lastIndex -= match[0].length;
|
|
1300
|
+
} else {
|
|
1301
|
+
todo.regex.lastIndex = 0;
|
|
1302
|
+
}
|
|
1303
|
+
replaces++;
|
|
1304
|
+
if (replaces >= this.maxReplaces) {
|
|
1305
|
+
break;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
});
|
|
1309
|
+
return str;
|
|
1310
|
+
}
|
|
1311
|
+
nest(str, fc) {
|
|
1312
|
+
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
|
1313
|
+
let match;
|
|
1314
|
+
let value;
|
|
1315
|
+
let clonedOptions;
|
|
1316
|
+
function handleHasOptions(key, inheritedOptions) {
|
|
1317
|
+
const sep = this.nestingOptionsSeparator;
|
|
1318
|
+
if (key.indexOf(sep) < 0) return key;
|
|
1319
|
+
const c = key.split(new RegExp(`${sep}[ ]*{`));
|
|
1320
|
+
let optionsString = `{${c[1]}`;
|
|
1321
|
+
key = c[0];
|
|
1322
|
+
optionsString = this.interpolate(optionsString, clonedOptions);
|
|
1323
|
+
const matchedSingleQuotes = optionsString.match(/'/g);
|
|
1324
|
+
const matchedDoubleQuotes = optionsString.match(/"/g);
|
|
1325
|
+
if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
|
|
1326
|
+
optionsString = optionsString.replace(/'/g, '"');
|
|
1327
|
+
}
|
|
1328
|
+
try {
|
|
1329
|
+
clonedOptions = JSON.parse(optionsString);
|
|
1330
|
+
if (inheritedOptions) clonedOptions = {
|
|
1331
|
+
...inheritedOptions,
|
|
1332
|
+
...clonedOptions
|
|
1333
|
+
};
|
|
1334
|
+
} catch (e) {
|
|
1335
|
+
this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
|
|
1336
|
+
return `${key}${sep}${optionsString}`;
|
|
1337
|
+
}
|
|
1338
|
+
delete clonedOptions.defaultValue;
|
|
1339
|
+
return key;
|
|
1340
|
+
}
|
|
1341
|
+
while (match = this.nestingRegexp.exec(str)) {
|
|
1342
|
+
let formatters = [];
|
|
1343
|
+
clonedOptions = {
|
|
1344
|
+
...options
|
|
1345
|
+
};
|
|
1346
|
+
clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== 'string' ? clonedOptions.replace : clonedOptions;
|
|
1347
|
+
clonedOptions.applyPostProcessor = false;
|
|
1348
|
+
delete clonedOptions.defaultValue;
|
|
1349
|
+
let doReduce = false;
|
|
1350
|
+
if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
|
|
1351
|
+
const r = match[1].split(this.formatSeparator).map(elem => elem.trim());
|
|
1352
|
+
match[1] = r.shift();
|
|
1353
|
+
formatters = r;
|
|
1354
|
+
doReduce = true;
|
|
1355
|
+
}
|
|
1356
|
+
value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
|
|
1357
|
+
if (value && match[0] === str && typeof value !== 'string') return value;
|
|
1358
|
+
if (typeof value !== 'string') value = makeString(value);
|
|
1359
|
+
if (!value) {
|
|
1360
|
+
this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
|
|
1361
|
+
value = '';
|
|
1362
|
+
}
|
|
1363
|
+
if (doReduce) {
|
|
1364
|
+
value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
|
|
1365
|
+
...options,
|
|
1366
|
+
interpolationkey: match[1].trim()
|
|
1367
|
+
}), value.trim());
|
|
1368
|
+
}
|
|
1369
|
+
str = str.replace(match[0], value);
|
|
1370
|
+
this.regexp.lastIndex = 0;
|
|
1371
|
+
}
|
|
1372
|
+
return str;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
function parseFormatStr(formatStr) {
|
|
1377
|
+
let formatName = formatStr.toLowerCase().trim();
|
|
1378
|
+
const formatOptions = {};
|
|
1379
|
+
if (formatStr.indexOf('(') > -1) {
|
|
1380
|
+
const p = formatStr.split('(');
|
|
1381
|
+
formatName = p[0].toLowerCase().trim();
|
|
1382
|
+
const optStr = p[1].substring(0, p[1].length - 1);
|
|
1383
|
+
if (formatName === 'currency' && optStr.indexOf(':') < 0) {
|
|
1384
|
+
if (!formatOptions.currency) formatOptions.currency = optStr.trim();
|
|
1385
|
+
} else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
|
|
1386
|
+
if (!formatOptions.range) formatOptions.range = optStr.trim();
|
|
1387
|
+
} else {
|
|
1388
|
+
const opts = optStr.split(';');
|
|
1389
|
+
opts.forEach(opt => {
|
|
1390
|
+
if (!opt) return;
|
|
1391
|
+
const [key, ...rest] = opt.split(':');
|
|
1392
|
+
const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
|
|
1393
|
+
if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val;
|
|
1394
|
+
if (val === 'false') formatOptions[key.trim()] = false;
|
|
1395
|
+
if (val === 'true') formatOptions[key.trim()] = true;
|
|
1396
|
+
if (!isNaN(val)) formatOptions[key.trim()] = parseInt(val, 10);
|
|
1397
|
+
});
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
return {
|
|
1401
|
+
formatName,
|
|
1402
|
+
formatOptions
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
function createCachedFormatter(fn) {
|
|
1406
|
+
const cache = {};
|
|
1407
|
+
return function invokeFormatter(val, lng, options) {
|
|
1408
|
+
const key = lng + JSON.stringify(options);
|
|
1409
|
+
let formatter = cache[key];
|
|
1410
|
+
if (!formatter) {
|
|
1411
|
+
formatter = fn(getCleanedCode(lng), options);
|
|
1412
|
+
cache[key] = formatter;
|
|
1413
|
+
}
|
|
1414
|
+
return formatter(val);
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
class Formatter {
|
|
1418
|
+
constructor() {
|
|
1419
|
+
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
1420
|
+
this.logger = baseLogger.create('formatter');
|
|
1421
|
+
this.options = options;
|
|
1422
|
+
this.formats = {
|
|
1423
|
+
number: createCachedFormatter((lng, opt) => {
|
|
1424
|
+
const formatter = new Intl.NumberFormat(lng, {
|
|
1425
|
+
...opt
|
|
1426
|
+
});
|
|
1427
|
+
return val => formatter.format(val);
|
|
1428
|
+
}),
|
|
1429
|
+
currency: createCachedFormatter((lng, opt) => {
|
|
1430
|
+
const formatter = new Intl.NumberFormat(lng, {
|
|
1431
|
+
...opt,
|
|
1432
|
+
style: 'currency'
|
|
1433
|
+
});
|
|
1434
|
+
return val => formatter.format(val);
|
|
1435
|
+
}),
|
|
1436
|
+
datetime: createCachedFormatter((lng, opt) => {
|
|
1437
|
+
const formatter = new Intl.DateTimeFormat(lng, {
|
|
1438
|
+
...opt
|
|
1439
|
+
});
|
|
1440
|
+
return val => formatter.format(val);
|
|
1441
|
+
}),
|
|
1442
|
+
relativetime: createCachedFormatter((lng, opt) => {
|
|
1443
|
+
const formatter = new Intl.RelativeTimeFormat(lng, {
|
|
1444
|
+
...opt
|
|
1445
|
+
});
|
|
1446
|
+
return val => formatter.format(val, opt.range || 'day');
|
|
1447
|
+
}),
|
|
1448
|
+
list: createCachedFormatter((lng, opt) => {
|
|
1449
|
+
const formatter = new Intl.ListFormat(lng, {
|
|
1450
|
+
...opt
|
|
1451
|
+
});
|
|
1452
|
+
return val => formatter.format(val);
|
|
1453
|
+
})
|
|
1454
|
+
};
|
|
1455
|
+
this.init(options);
|
|
1456
|
+
}
|
|
1457
|
+
init(services) {
|
|
1458
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
|
|
1459
|
+
interpolation: {}
|
|
1460
|
+
};
|
|
1461
|
+
const iOpts = options.interpolation;
|
|
1462
|
+
this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
|
|
1463
|
+
}
|
|
1464
|
+
add(name, fc) {
|
|
1465
|
+
this.formats[name.toLowerCase().trim()] = fc;
|
|
1466
|
+
}
|
|
1467
|
+
addCached(name, fc) {
|
|
1468
|
+
this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
|
|
1469
|
+
}
|
|
1470
|
+
format(value, format, lng) {
|
|
1471
|
+
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
|
|
1472
|
+
const formats = format.split(this.formatSeparator);
|
|
1473
|
+
const result = formats.reduce((mem, f) => {
|
|
1474
|
+
const {
|
|
1475
|
+
formatName,
|
|
1476
|
+
formatOptions
|
|
1477
|
+
} = parseFormatStr(f);
|
|
1478
|
+
if (this.formats[formatName]) {
|
|
1479
|
+
let formatted = mem;
|
|
1480
|
+
try {
|
|
1481
|
+
const valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
|
|
1482
|
+
const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
|
|
1483
|
+
formatted = this.formats[formatName](mem, l, {
|
|
1484
|
+
...formatOptions,
|
|
1485
|
+
...options,
|
|
1486
|
+
...valOptions
|
|
1487
|
+
});
|
|
1488
|
+
} catch (error) {
|
|
1489
|
+
this.logger.warn(error);
|
|
1490
|
+
}
|
|
1491
|
+
return formatted;
|
|
1492
|
+
} else {
|
|
1493
|
+
this.logger.warn(`there was no format function for ${formatName}`);
|
|
1494
|
+
}
|
|
1495
|
+
return mem;
|
|
1496
|
+
}, value);
|
|
1497
|
+
return result;
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
function removePending(q, name) {
|
|
1502
|
+
if (q.pending[name] !== undefined) {
|
|
1503
|
+
delete q.pending[name];
|
|
1504
|
+
q.pendingCount--;
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
class Connector extends EventEmitter {
|
|
1508
|
+
constructor(backend, store, services) {
|
|
1509
|
+
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
|
|
1510
|
+
super();
|
|
1511
|
+
this.backend = backend;
|
|
1512
|
+
this.store = store;
|
|
1513
|
+
this.services = services;
|
|
1514
|
+
this.languageUtils = services.languageUtils;
|
|
1515
|
+
this.options = options;
|
|
1516
|
+
this.logger = baseLogger.create('backendConnector');
|
|
1517
|
+
this.waitingReads = [];
|
|
1518
|
+
this.maxParallelReads = options.maxParallelReads || 10;
|
|
1519
|
+
this.readingCalls = 0;
|
|
1520
|
+
this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
|
|
1521
|
+
this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
|
|
1522
|
+
this.state = {};
|
|
1523
|
+
this.queue = [];
|
|
1524
|
+
if (this.backend && this.backend.init) {
|
|
1525
|
+
this.backend.init(services, options.backend, options);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
queueLoad(languages, namespaces, options, callback) {
|
|
1529
|
+
const toLoad = {};
|
|
1530
|
+
const pending = {};
|
|
1531
|
+
const toLoadLanguages = {};
|
|
1532
|
+
const toLoadNamespaces = {};
|
|
1533
|
+
languages.forEach(lng => {
|
|
1534
|
+
let hasAllNamespaces = true;
|
|
1535
|
+
namespaces.forEach(ns => {
|
|
1536
|
+
const name = `${lng}|${ns}`;
|
|
1537
|
+
if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
|
|
1538
|
+
this.state[name] = 2;
|
|
1539
|
+
} else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
|
|
1540
|
+
if (pending[name] === undefined) pending[name] = true;
|
|
1541
|
+
} else {
|
|
1542
|
+
this.state[name] = 1;
|
|
1543
|
+
hasAllNamespaces = false;
|
|
1544
|
+
if (pending[name] === undefined) pending[name] = true;
|
|
1545
|
+
if (toLoad[name] === undefined) toLoad[name] = true;
|
|
1546
|
+
if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
|
|
1547
|
+
}
|
|
1548
|
+
});
|
|
1549
|
+
if (!hasAllNamespaces) toLoadLanguages[lng] = true;
|
|
1550
|
+
});
|
|
1551
|
+
if (Object.keys(toLoad).length || Object.keys(pending).length) {
|
|
1552
|
+
this.queue.push({
|
|
1553
|
+
pending,
|
|
1554
|
+
pendingCount: Object.keys(pending).length,
|
|
1555
|
+
loaded: {},
|
|
1556
|
+
errors: [],
|
|
1557
|
+
callback
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
return {
|
|
1561
|
+
toLoad: Object.keys(toLoad),
|
|
1562
|
+
pending: Object.keys(pending),
|
|
1563
|
+
toLoadLanguages: Object.keys(toLoadLanguages),
|
|
1564
|
+
toLoadNamespaces: Object.keys(toLoadNamespaces)
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
loaded(name, err, data) {
|
|
1568
|
+
const s = name.split('|');
|
|
1569
|
+
const lng = s[0];
|
|
1570
|
+
const ns = s[1];
|
|
1571
|
+
if (err) this.emit('failedLoading', lng, ns, err);
|
|
1572
|
+
if (data) {
|
|
1573
|
+
this.store.addResourceBundle(lng, ns, data);
|
|
1574
|
+
}
|
|
1575
|
+
this.state[name] = err ? -1 : 2;
|
|
1576
|
+
const loaded = {};
|
|
1577
|
+
this.queue.forEach(q => {
|
|
1578
|
+
pushPath(q.loaded, [lng], ns);
|
|
1579
|
+
removePending(q, name);
|
|
1580
|
+
if (err) q.errors.push(err);
|
|
1581
|
+
if (q.pendingCount === 0 && !q.done) {
|
|
1582
|
+
Object.keys(q.loaded).forEach(l => {
|
|
1583
|
+
if (!loaded[l]) loaded[l] = {};
|
|
1584
|
+
const loadedKeys = q.loaded[l];
|
|
1585
|
+
if (loadedKeys.length) {
|
|
1586
|
+
loadedKeys.forEach(n => {
|
|
1587
|
+
if (loaded[l][n] === undefined) loaded[l][n] = true;
|
|
1588
|
+
});
|
|
1589
|
+
}
|
|
1590
|
+
});
|
|
1591
|
+
q.done = true;
|
|
1592
|
+
if (q.errors.length) {
|
|
1593
|
+
q.callback(q.errors);
|
|
1594
|
+
} else {
|
|
1595
|
+
q.callback();
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
});
|
|
1599
|
+
this.emit('loaded', loaded);
|
|
1600
|
+
this.queue = this.queue.filter(q => !q.done);
|
|
1601
|
+
}
|
|
1602
|
+
read(lng, ns, fcName) {
|
|
1603
|
+
let tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
|
|
1604
|
+
let wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout;
|
|
1605
|
+
let callback = arguments.length > 5 ? arguments[5] : undefined;
|
|
1606
|
+
if (!lng.length) return callback(null, {});
|
|
1607
|
+
if (this.readingCalls >= this.maxParallelReads) {
|
|
1608
|
+
this.waitingReads.push({
|
|
1609
|
+
lng,
|
|
1610
|
+
ns,
|
|
1611
|
+
fcName,
|
|
1612
|
+
tried,
|
|
1613
|
+
wait,
|
|
1614
|
+
callback
|
|
1615
|
+
});
|
|
1616
|
+
return;
|
|
1617
|
+
}
|
|
1618
|
+
this.readingCalls++;
|
|
1619
|
+
const resolver = (err, data) => {
|
|
1620
|
+
this.readingCalls--;
|
|
1621
|
+
if (this.waitingReads.length > 0) {
|
|
1622
|
+
const next = this.waitingReads.shift();
|
|
1623
|
+
this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
|
|
1624
|
+
}
|
|
1625
|
+
if (err && data && tried < this.maxRetries) {
|
|
1626
|
+
setTimeout(() => {
|
|
1627
|
+
this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
|
|
1628
|
+
}, wait);
|
|
1629
|
+
return;
|
|
1630
|
+
}
|
|
1631
|
+
callback(err, data);
|
|
1632
|
+
};
|
|
1633
|
+
const fc = this.backend[fcName].bind(this.backend);
|
|
1634
|
+
if (fc.length === 2) {
|
|
1635
|
+
try {
|
|
1636
|
+
const r = fc(lng, ns);
|
|
1637
|
+
if (r && typeof r.then === 'function') {
|
|
1638
|
+
r.then(data => resolver(null, data)).catch(resolver);
|
|
1639
|
+
} else {
|
|
1640
|
+
resolver(null, r);
|
|
1641
|
+
}
|
|
1642
|
+
} catch (err) {
|
|
1643
|
+
resolver(err);
|
|
1644
|
+
}
|
|
1645
|
+
return;
|
|
1646
|
+
}
|
|
1647
|
+
return fc(lng, ns, resolver);
|
|
1648
|
+
}
|
|
1649
|
+
prepareLoading(languages, namespaces) {
|
|
1650
|
+
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
|
1651
|
+
let callback = arguments.length > 3 ? arguments[3] : undefined;
|
|
1652
|
+
if (!this.backend) {
|
|
1653
|
+
this.logger.warn('No backend was added via i18next.use. Will not load resources.');
|
|
1654
|
+
return callback && callback();
|
|
1655
|
+
}
|
|
1656
|
+
if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);
|
|
1657
|
+
if (typeof namespaces === 'string') namespaces = [namespaces];
|
|
1658
|
+
const toLoad = this.queueLoad(languages, namespaces, options, callback);
|
|
1659
|
+
if (!toLoad.toLoad.length) {
|
|
1660
|
+
if (!toLoad.pending.length) callback();
|
|
1661
|
+
return null;
|
|
1662
|
+
}
|
|
1663
|
+
toLoad.toLoad.forEach(name => {
|
|
1664
|
+
this.loadOne(name);
|
|
1665
|
+
});
|
|
1666
|
+
}
|
|
1667
|
+
load(languages, namespaces, callback) {
|
|
1668
|
+
this.prepareLoading(languages, namespaces, {}, callback);
|
|
1669
|
+
}
|
|
1670
|
+
reload(languages, namespaces, callback) {
|
|
1671
|
+
this.prepareLoading(languages, namespaces, {
|
|
1672
|
+
reload: true
|
|
1673
|
+
}, callback);
|
|
1674
|
+
}
|
|
1675
|
+
loadOne(name) {
|
|
1676
|
+
let prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
|
|
1677
|
+
const s = name.split('|');
|
|
1678
|
+
const lng = s[0];
|
|
1679
|
+
const ns = s[1];
|
|
1680
|
+
this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
|
|
1681
|
+
if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
|
|
1682
|
+
if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
|
|
1683
|
+
this.loaded(name, err, data);
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
|
|
1687
|
+
let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
|
|
1688
|
+
let clb = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : () => {};
|
|
1689
|
+
if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
|
|
1690
|
+
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!!!');
|
|
1691
|
+
return;
|
|
1692
|
+
}
|
|
1693
|
+
if (key === undefined || key === null || key === '') return;
|
|
1694
|
+
if (this.backend && this.backend.create) {
|
|
1695
|
+
const opts = {
|
|
1696
|
+
...options,
|
|
1697
|
+
isUpdate
|
|
1698
|
+
};
|
|
1699
|
+
const fc = this.backend.create.bind(this.backend);
|
|
1700
|
+
if (fc.length < 6) {
|
|
1701
|
+
try {
|
|
1702
|
+
let r;
|
|
1703
|
+
if (fc.length === 5) {
|
|
1704
|
+
r = fc(languages, namespace, key, fallbackValue, opts);
|
|
1705
|
+
} else {
|
|
1706
|
+
r = fc(languages, namespace, key, fallbackValue);
|
|
1707
|
+
}
|
|
1708
|
+
if (r && typeof r.then === 'function') {
|
|
1709
|
+
r.then(data => clb(null, data)).catch(clb);
|
|
1710
|
+
} else {
|
|
1711
|
+
clb(null, r);
|
|
1712
|
+
}
|
|
1713
|
+
} catch (err) {
|
|
1714
|
+
clb(err);
|
|
1715
|
+
}
|
|
1716
|
+
} else {
|
|
1717
|
+
fc(languages, namespace, key, fallbackValue, clb, opts);
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
if (!languages || !languages[0]) return;
|
|
1721
|
+
this.store.addResource(languages[0], namespace, key, fallbackValue);
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
function get() {
|
|
1726
|
+
return {
|
|
1727
|
+
debug: false,
|
|
1728
|
+
initImmediate: true,
|
|
1729
|
+
ns: ['translation'],
|
|
1730
|
+
defaultNS: ['translation'],
|
|
1731
|
+
fallbackLng: ['dev'],
|
|
1732
|
+
fallbackNS: false,
|
|
1733
|
+
supportedLngs: false,
|
|
1734
|
+
nonExplicitSupportedLngs: false,
|
|
1735
|
+
load: 'all',
|
|
1736
|
+
preload: false,
|
|
1737
|
+
simplifyPluralSuffix: true,
|
|
1738
|
+
keySeparator: '.',
|
|
1739
|
+
nsSeparator: ':',
|
|
1740
|
+
pluralSeparator: '_',
|
|
1741
|
+
contextSeparator: '_',
|
|
1742
|
+
partialBundledLanguages: false,
|
|
1743
|
+
saveMissing: false,
|
|
1744
|
+
updateMissing: false,
|
|
1745
|
+
saveMissingTo: 'fallback',
|
|
1746
|
+
saveMissingPlurals: true,
|
|
1747
|
+
missingKeyHandler: false,
|
|
1748
|
+
missingInterpolationHandler: false,
|
|
1749
|
+
postProcess: false,
|
|
1750
|
+
postProcessPassResolved: false,
|
|
1751
|
+
returnNull: false,
|
|
1752
|
+
returnEmptyString: true,
|
|
1753
|
+
returnObjects: false,
|
|
1754
|
+
joinArrays: false,
|
|
1755
|
+
returnedObjectHandler: false,
|
|
1756
|
+
parseMissingKeyHandler: false,
|
|
1757
|
+
appendNamespaceToMissingKey: false,
|
|
1758
|
+
appendNamespaceToCIMode: false,
|
|
1759
|
+
overloadTranslationOptionHandler: function handle(args) {
|
|
1760
|
+
let ret = {};
|
|
1761
|
+
if (typeof args[1] === 'object') ret = args[1];
|
|
1762
|
+
if (typeof args[1] === 'string') ret.defaultValue = args[1];
|
|
1763
|
+
if (typeof args[2] === 'string') ret.tDescription = args[2];
|
|
1764
|
+
if (typeof args[2] === 'object' || typeof args[3] === 'object') {
|
|
1765
|
+
const options = args[3] || args[2];
|
|
1766
|
+
Object.keys(options).forEach(key => {
|
|
1767
|
+
ret[key] = options[key];
|
|
1768
|
+
});
|
|
1769
|
+
}
|
|
1770
|
+
return ret;
|
|
1771
|
+
},
|
|
1772
|
+
interpolation: {
|
|
1773
|
+
escapeValue: true,
|
|
1774
|
+
format: (value, format, lng, options) => value,
|
|
1775
|
+
prefix: '{{',
|
|
1776
|
+
suffix: '}}',
|
|
1777
|
+
formatSeparator: ',',
|
|
1778
|
+
unescapePrefix: '-',
|
|
1779
|
+
nestingPrefix: '$t(',
|
|
1780
|
+
nestingSuffix: ')',
|
|
1781
|
+
nestingOptionsSeparator: ',',
|
|
1782
|
+
maxReplaces: 1000,
|
|
1783
|
+
skipOnVariables: true
|
|
1784
|
+
}
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
function transformOptions(options) {
|
|
1788
|
+
if (typeof options.ns === 'string') options.ns = [options.ns];
|
|
1789
|
+
if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
|
|
1790
|
+
if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];
|
|
1791
|
+
if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
|
|
1792
|
+
options.supportedLngs = options.supportedLngs.concat(['cimode']);
|
|
1793
|
+
}
|
|
1794
|
+
return options;
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
function noop() {}
|
|
1798
|
+
function bindMemberFunctions(inst) {
|
|
1799
|
+
const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
|
|
1800
|
+
mems.forEach(mem => {
|
|
1801
|
+
if (typeof inst[mem] === 'function') {
|
|
1802
|
+
inst[mem] = inst[mem].bind(inst);
|
|
1803
|
+
}
|
|
1804
|
+
});
|
|
1805
|
+
}
|
|
1806
|
+
class I18n extends EventEmitter {
|
|
1807
|
+
constructor() {
|
|
1808
|
+
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
1809
|
+
let callback = arguments.length > 1 ? arguments[1] : undefined;
|
|
1810
|
+
super();
|
|
1811
|
+
this.options = transformOptions(options);
|
|
1812
|
+
this.services = {};
|
|
1813
|
+
this.logger = baseLogger;
|
|
1814
|
+
this.modules = {
|
|
1815
|
+
external: []
|
|
1816
|
+
};
|
|
1817
|
+
bindMemberFunctions(this);
|
|
1818
|
+
if (callback && !this.isInitialized && !options.isClone) {
|
|
1819
|
+
if (!this.options.initImmediate) {
|
|
1820
|
+
this.init(options, callback);
|
|
1821
|
+
return this;
|
|
1822
|
+
}
|
|
1823
|
+
setTimeout(() => {
|
|
1824
|
+
this.init(options, callback);
|
|
1825
|
+
}, 0);
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
init() {
|
|
1829
|
+
var _this = this;
|
|
1830
|
+
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
1831
|
+
let callback = arguments.length > 1 ? arguments[1] : undefined;
|
|
1832
|
+
if (typeof options === 'function') {
|
|
1833
|
+
callback = options;
|
|
1834
|
+
options = {};
|
|
1835
|
+
}
|
|
1836
|
+
if (!options.defaultNS && options.defaultNS !== false && options.ns) {
|
|
1837
|
+
if (typeof options.ns === 'string') {
|
|
1838
|
+
options.defaultNS = options.ns;
|
|
1839
|
+
} else if (options.ns.indexOf('translation') < 0) {
|
|
1840
|
+
options.defaultNS = options.ns[0];
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
const defOpts = get();
|
|
1844
|
+
this.options = {
|
|
1845
|
+
...defOpts,
|
|
1846
|
+
...this.options,
|
|
1847
|
+
...transformOptions(options)
|
|
1848
|
+
};
|
|
1849
|
+
if (this.options.compatibilityAPI !== 'v1') {
|
|
1850
|
+
this.options.interpolation = {
|
|
1851
|
+
...defOpts.interpolation,
|
|
1852
|
+
...this.options.interpolation
|
|
1853
|
+
};
|
|
1854
|
+
}
|
|
1855
|
+
if (options.keySeparator !== undefined) {
|
|
1856
|
+
this.options.userDefinedKeySeparator = options.keySeparator;
|
|
1857
|
+
}
|
|
1858
|
+
if (options.nsSeparator !== undefined) {
|
|
1859
|
+
this.options.userDefinedNsSeparator = options.nsSeparator;
|
|
1860
|
+
}
|
|
1861
|
+
function createClassOnDemand(ClassOrObject) {
|
|
1862
|
+
if (!ClassOrObject) return null;
|
|
1863
|
+
if (typeof ClassOrObject === 'function') return new ClassOrObject();
|
|
1864
|
+
return ClassOrObject;
|
|
1865
|
+
}
|
|
1866
|
+
if (!this.options.isClone) {
|
|
1867
|
+
if (this.modules.logger) {
|
|
1868
|
+
baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
|
|
1869
|
+
} else {
|
|
1870
|
+
baseLogger.init(null, this.options);
|
|
1871
|
+
}
|
|
1872
|
+
let formatter;
|
|
1873
|
+
if (this.modules.formatter) {
|
|
1874
|
+
formatter = this.modules.formatter;
|
|
1875
|
+
} else if (typeof Intl !== 'undefined') {
|
|
1876
|
+
formatter = Formatter;
|
|
1877
|
+
}
|
|
1878
|
+
const lu = new LanguageUtil(this.options);
|
|
1879
|
+
this.store = new ResourceStore(this.options.resources, this.options);
|
|
1880
|
+
const s = this.services;
|
|
1881
|
+
s.logger = baseLogger;
|
|
1882
|
+
s.resourceStore = this.store;
|
|
1883
|
+
s.languageUtils = lu;
|
|
1884
|
+
s.pluralResolver = new PluralResolver(lu, {
|
|
1885
|
+
prepend: this.options.pluralSeparator,
|
|
1886
|
+
compatibilityJSON: this.options.compatibilityJSON,
|
|
1887
|
+
simplifyPluralSuffix: this.options.simplifyPluralSuffix
|
|
1888
|
+
});
|
|
1889
|
+
if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
|
|
1890
|
+
s.formatter = createClassOnDemand(formatter);
|
|
1891
|
+
s.formatter.init(s, this.options);
|
|
1892
|
+
this.options.interpolation.format = s.formatter.format.bind(s.formatter);
|
|
1893
|
+
}
|
|
1894
|
+
s.interpolator = new Interpolator(this.options);
|
|
1895
|
+
s.utils = {
|
|
1896
|
+
hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
|
|
1897
|
+
};
|
|
1898
|
+
s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
|
|
1899
|
+
s.backendConnector.on('*', function (event) {
|
|
1900
|
+
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
|
1901
|
+
args[_key - 1] = arguments[_key];
|
|
1902
|
+
}
|
|
1903
|
+
_this.emit(event, ...args);
|
|
1904
|
+
});
|
|
1905
|
+
if (this.modules.languageDetector) {
|
|
1906
|
+
s.languageDetector = createClassOnDemand(this.modules.languageDetector);
|
|
1907
|
+
if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
|
|
1908
|
+
}
|
|
1909
|
+
if (this.modules.i18nFormat) {
|
|
1910
|
+
s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
|
|
1911
|
+
if (s.i18nFormat.init) s.i18nFormat.init(this);
|
|
1912
|
+
}
|
|
1913
|
+
this.translator = new Translator(this.services, this.options);
|
|
1914
|
+
this.translator.on('*', function (event) {
|
|
1915
|
+
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
|
|
1916
|
+
args[_key2 - 1] = arguments[_key2];
|
|
1917
|
+
}
|
|
1918
|
+
_this.emit(event, ...args);
|
|
1919
|
+
});
|
|
1920
|
+
this.modules.external.forEach(m => {
|
|
1921
|
+
if (m.init) m.init(this);
|
|
1922
|
+
});
|
|
1923
|
+
}
|
|
1924
|
+
this.format = this.options.interpolation.format;
|
|
1925
|
+
if (!callback) callback = noop;
|
|
1926
|
+
if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
|
|
1927
|
+
const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
|
|
1928
|
+
if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
|
|
1929
|
+
}
|
|
1930
|
+
if (!this.services.languageDetector && !this.options.lng) {
|
|
1931
|
+
this.logger.warn('init: no languageDetector is used and no lng is defined');
|
|
1932
|
+
}
|
|
1933
|
+
const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
|
|
1934
|
+
storeApi.forEach(fcName => {
|
|
1935
|
+
this[fcName] = function () {
|
|
1936
|
+
return _this.store[fcName](...arguments);
|
|
1937
|
+
};
|
|
1938
|
+
});
|
|
1939
|
+
const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
|
|
1940
|
+
storeApiChained.forEach(fcName => {
|
|
1941
|
+
this[fcName] = function () {
|
|
1942
|
+
_this.store[fcName](...arguments);
|
|
1943
|
+
return _this;
|
|
1944
|
+
};
|
|
1945
|
+
});
|
|
1946
|
+
const deferred = defer();
|
|
1947
|
+
const load = () => {
|
|
1948
|
+
const finish = (err, t) => {
|
|
1949
|
+
if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
|
|
1950
|
+
this.isInitialized = true;
|
|
1951
|
+
if (!this.options.isClone) this.logger.log('initialized', this.options);
|
|
1952
|
+
this.emit('initialized', this.options);
|
|
1953
|
+
deferred.resolve(t);
|
|
1954
|
+
callback(err, t);
|
|
1955
|
+
};
|
|
1956
|
+
if (this.languages && this.options.compatibilityAPI !== 'v1' && !this.isInitialized) return finish(null, this.t.bind(this));
|
|
1957
|
+
this.changeLanguage(this.options.lng, finish);
|
|
1958
|
+
};
|
|
1959
|
+
if (this.options.resources || !this.options.initImmediate) {
|
|
1960
|
+
load();
|
|
1961
|
+
} else {
|
|
1962
|
+
setTimeout(load, 0);
|
|
1963
|
+
}
|
|
1964
|
+
return deferred;
|
|
1965
|
+
}
|
|
1966
|
+
loadResources(language) {
|
|
1967
|
+
let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
|
|
1968
|
+
let usedCallback = callback;
|
|
1969
|
+
const usedLng = typeof language === 'string' ? language : this.language;
|
|
1970
|
+
if (typeof language === 'function') usedCallback = language;
|
|
1971
|
+
if (!this.options.resources || this.options.partialBundledLanguages) {
|
|
1972
|
+
if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback();
|
|
1973
|
+
const toLoad = [];
|
|
1974
|
+
const append = lng => {
|
|
1975
|
+
if (!lng) return;
|
|
1976
|
+
const lngs = this.services.languageUtils.toResolveHierarchy(lng);
|
|
1977
|
+
lngs.forEach(l => {
|
|
1978
|
+
if (toLoad.indexOf(l) < 0) toLoad.push(l);
|
|
1979
|
+
});
|
|
1980
|
+
};
|
|
1981
|
+
if (!usedLng) {
|
|
1982
|
+
const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
|
|
1983
|
+
fallbacks.forEach(l => append(l));
|
|
1984
|
+
} else {
|
|
1985
|
+
append(usedLng);
|
|
1986
|
+
}
|
|
1987
|
+
if (this.options.preload) {
|
|
1988
|
+
this.options.preload.forEach(l => append(l));
|
|
1989
|
+
}
|
|
1990
|
+
this.services.backendConnector.load(toLoad, this.options.ns, e => {
|
|
1991
|
+
if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
|
|
1992
|
+
usedCallback(e);
|
|
1993
|
+
});
|
|
1994
|
+
} else {
|
|
1995
|
+
usedCallback(null);
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
reloadResources(lngs, ns, callback) {
|
|
1999
|
+
const deferred = defer();
|
|
2000
|
+
if (!lngs) lngs = this.languages;
|
|
2001
|
+
if (!ns) ns = this.options.ns;
|
|
2002
|
+
if (!callback) callback = noop;
|
|
2003
|
+
this.services.backendConnector.reload(lngs, ns, err => {
|
|
2004
|
+
deferred.resolve();
|
|
2005
|
+
callback(err);
|
|
2006
|
+
});
|
|
2007
|
+
return deferred;
|
|
2008
|
+
}
|
|
2009
|
+
use(module) {
|
|
2010
|
+
if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
|
|
2011
|
+
if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
|
|
2012
|
+
if (module.type === 'backend') {
|
|
2013
|
+
this.modules.backend = module;
|
|
2014
|
+
}
|
|
2015
|
+
if (module.type === 'logger' || module.log && module.warn && module.error) {
|
|
2016
|
+
this.modules.logger = module;
|
|
2017
|
+
}
|
|
2018
|
+
if (module.type === 'languageDetector') {
|
|
2019
|
+
this.modules.languageDetector = module;
|
|
2020
|
+
}
|
|
2021
|
+
if (module.type === 'i18nFormat') {
|
|
2022
|
+
this.modules.i18nFormat = module;
|
|
2023
|
+
}
|
|
2024
|
+
if (module.type === 'postProcessor') {
|
|
2025
|
+
postProcessor.addPostProcessor(module);
|
|
2026
|
+
}
|
|
2027
|
+
if (module.type === 'formatter') {
|
|
2028
|
+
this.modules.formatter = module;
|
|
2029
|
+
}
|
|
2030
|
+
if (module.type === '3rdParty') {
|
|
2031
|
+
this.modules.external.push(module);
|
|
2032
|
+
}
|
|
2033
|
+
return this;
|
|
2034
|
+
}
|
|
2035
|
+
setResolvedLanguage(l) {
|
|
2036
|
+
if (!l || !this.languages) return;
|
|
2037
|
+
if (['cimode', 'dev'].indexOf(l) > -1) return;
|
|
2038
|
+
for (let li = 0; li < this.languages.length; li++) {
|
|
2039
|
+
const lngInLngs = this.languages[li];
|
|
2040
|
+
if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
|
|
2041
|
+
if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
|
|
2042
|
+
this.resolvedLanguage = lngInLngs;
|
|
2043
|
+
break;
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
changeLanguage(lng, callback) {
|
|
2048
|
+
var _this2 = this;
|
|
2049
|
+
this.isLanguageChangingTo = lng;
|
|
2050
|
+
const deferred = defer();
|
|
2051
|
+
this.emit('languageChanging', lng);
|
|
2052
|
+
const setLngProps = l => {
|
|
2053
|
+
this.language = l;
|
|
2054
|
+
this.languages = this.services.languageUtils.toResolveHierarchy(l);
|
|
2055
|
+
this.resolvedLanguage = undefined;
|
|
2056
|
+
this.setResolvedLanguage(l);
|
|
2057
|
+
};
|
|
2058
|
+
const done = (err, l) => {
|
|
2059
|
+
if (l) {
|
|
2060
|
+
setLngProps(l);
|
|
2061
|
+
this.translator.changeLanguage(l);
|
|
2062
|
+
this.isLanguageChangingTo = undefined;
|
|
2063
|
+
this.emit('languageChanged', l);
|
|
2064
|
+
this.logger.log('languageChanged', l);
|
|
2065
|
+
} else {
|
|
2066
|
+
this.isLanguageChangingTo = undefined;
|
|
2067
|
+
}
|
|
2068
|
+
deferred.resolve(function () {
|
|
2069
|
+
return _this2.t(...arguments);
|
|
2070
|
+
});
|
|
2071
|
+
if (callback) callback(err, function () {
|
|
2072
|
+
return _this2.t(...arguments);
|
|
2073
|
+
});
|
|
2074
|
+
};
|
|
2075
|
+
const setLng = lngs => {
|
|
2076
|
+
if (!lng && !lngs && this.services.languageDetector) lngs = [];
|
|
2077
|
+
const l = typeof lngs === 'string' ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);
|
|
2078
|
+
if (l) {
|
|
2079
|
+
if (!this.language) {
|
|
2080
|
+
setLngProps(l);
|
|
2081
|
+
}
|
|
2082
|
+
if (!this.translator.language) this.translator.changeLanguage(l);
|
|
2083
|
+
if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage) this.services.languageDetector.cacheUserLanguage(l);
|
|
2084
|
+
}
|
|
2085
|
+
this.loadResources(l, err => {
|
|
2086
|
+
done(err, l);
|
|
2087
|
+
});
|
|
2088
|
+
};
|
|
2089
|
+
if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
|
|
2090
|
+
setLng(this.services.languageDetector.detect());
|
|
2091
|
+
} else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
|
|
2092
|
+
if (this.services.languageDetector.detect.length === 0) {
|
|
2093
|
+
this.services.languageDetector.detect().then(setLng);
|
|
2094
|
+
} else {
|
|
2095
|
+
this.services.languageDetector.detect(setLng);
|
|
2096
|
+
}
|
|
2097
|
+
} else {
|
|
2098
|
+
setLng(lng);
|
|
2099
|
+
}
|
|
2100
|
+
return deferred;
|
|
2101
|
+
}
|
|
2102
|
+
getFixedT(lng, ns, keyPrefix) {
|
|
2103
|
+
var _this3 = this;
|
|
2104
|
+
const fixedT = function (key, opts) {
|
|
2105
|
+
let options;
|
|
2106
|
+
if (typeof opts !== 'object') {
|
|
2107
|
+
for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
|
|
2108
|
+
rest[_key3 - 2] = arguments[_key3];
|
|
2109
|
+
}
|
|
2110
|
+
options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));
|
|
2111
|
+
} else {
|
|
2112
|
+
options = {
|
|
2113
|
+
...opts
|
|
2114
|
+
};
|
|
2115
|
+
}
|
|
2116
|
+
options.lng = options.lng || fixedT.lng;
|
|
2117
|
+
options.lngs = options.lngs || fixedT.lngs;
|
|
2118
|
+
options.ns = options.ns || fixedT.ns;
|
|
2119
|
+
options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
|
|
2120
|
+
const keySeparator = _this3.options.keySeparator || '.';
|
|
2121
|
+
let resultKey;
|
|
2122
|
+
if (options.keyPrefix && Array.isArray(key)) {
|
|
2123
|
+
resultKey = key.map(k => `${options.keyPrefix}${keySeparator}${k}`);
|
|
2124
|
+
} else {
|
|
2125
|
+
resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;
|
|
2126
|
+
}
|
|
2127
|
+
return _this3.t(resultKey, options);
|
|
2128
|
+
};
|
|
2129
|
+
if (typeof lng === 'string') {
|
|
2130
|
+
fixedT.lng = lng;
|
|
2131
|
+
} else {
|
|
2132
|
+
fixedT.lngs = lng;
|
|
2133
|
+
}
|
|
2134
|
+
fixedT.ns = ns;
|
|
2135
|
+
fixedT.keyPrefix = keyPrefix;
|
|
2136
|
+
return fixedT;
|
|
2137
|
+
}
|
|
2138
|
+
t() {
|
|
2139
|
+
return this.translator && this.translator.translate(...arguments);
|
|
2140
|
+
}
|
|
2141
|
+
exists() {
|
|
2142
|
+
return this.translator && this.translator.exists(...arguments);
|
|
2143
|
+
}
|
|
2144
|
+
setDefaultNamespace(ns) {
|
|
2145
|
+
this.options.defaultNS = ns;
|
|
2146
|
+
}
|
|
2147
|
+
hasLoadedNamespace(ns) {
|
|
2148
|
+
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
2149
|
+
if (!this.isInitialized) {
|
|
2150
|
+
this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
|
|
2151
|
+
return false;
|
|
2152
|
+
}
|
|
2153
|
+
if (!this.languages || !this.languages.length) {
|
|
2154
|
+
this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
|
|
2155
|
+
return false;
|
|
2156
|
+
}
|
|
2157
|
+
const lng = options.lng || this.resolvedLanguage || this.languages[0];
|
|
2158
|
+
const fallbackLng = this.options ? this.options.fallbackLng : false;
|
|
2159
|
+
const lastLng = this.languages[this.languages.length - 1];
|
|
2160
|
+
if (lng.toLowerCase() === 'cimode') return true;
|
|
2161
|
+
const loadNotPending = (l, n) => {
|
|
2162
|
+
const loadState = this.services.backendConnector.state[`${l}|${n}`];
|
|
2163
|
+
return loadState === -1 || loadState === 2;
|
|
2164
|
+
};
|
|
2165
|
+
if (options.precheck) {
|
|
2166
|
+
const preResult = options.precheck(this, loadNotPending);
|
|
2167
|
+
if (preResult !== undefined) return preResult;
|
|
2168
|
+
}
|
|
2169
|
+
if (this.hasResourceBundle(lng, ns)) return true;
|
|
2170
|
+
if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
|
|
2171
|
+
if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
|
|
2172
|
+
return false;
|
|
2173
|
+
}
|
|
2174
|
+
loadNamespaces(ns, callback) {
|
|
2175
|
+
const deferred = defer();
|
|
2176
|
+
if (!this.options.ns) {
|
|
2177
|
+
if (callback) callback();
|
|
2178
|
+
return Promise.resolve();
|
|
2179
|
+
}
|
|
2180
|
+
if (typeof ns === 'string') ns = [ns];
|
|
2181
|
+
ns.forEach(n => {
|
|
2182
|
+
if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
|
|
2183
|
+
});
|
|
2184
|
+
this.loadResources(err => {
|
|
2185
|
+
deferred.resolve();
|
|
2186
|
+
if (callback) callback(err);
|
|
2187
|
+
});
|
|
2188
|
+
return deferred;
|
|
2189
|
+
}
|
|
2190
|
+
loadLanguages(lngs, callback) {
|
|
2191
|
+
const deferred = defer();
|
|
2192
|
+
if (typeof lngs === 'string') lngs = [lngs];
|
|
2193
|
+
const preloaded = this.options.preload || [];
|
|
2194
|
+
const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0);
|
|
2195
|
+
if (!newLngs.length) {
|
|
2196
|
+
if (callback) callback();
|
|
2197
|
+
return Promise.resolve();
|
|
2198
|
+
}
|
|
2199
|
+
this.options.preload = preloaded.concat(newLngs);
|
|
2200
|
+
this.loadResources(err => {
|
|
2201
|
+
deferred.resolve();
|
|
2202
|
+
if (callback) callback(err);
|
|
2203
|
+
});
|
|
2204
|
+
return deferred;
|
|
2205
|
+
}
|
|
2206
|
+
dir(lng) {
|
|
2207
|
+
if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
|
|
2208
|
+
if (!lng) return 'rtl';
|
|
2209
|
+
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'];
|
|
2210
|
+
const languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());
|
|
2211
|
+
return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
|
|
2212
|
+
}
|
|
2213
|
+
static createInstance() {
|
|
2214
|
+
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
2215
|
+
let callback = arguments.length > 1 ? arguments[1] : undefined;
|
|
2216
|
+
return new I18n(options, callback);
|
|
2217
|
+
}
|
|
2218
|
+
cloneInstance() {
|
|
2219
|
+
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
2220
|
+
let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
|
|
2221
|
+
const forkResourceStore = options.forkResourceStore;
|
|
2222
|
+
if (forkResourceStore) delete options.forkResourceStore;
|
|
2223
|
+
const mergedOptions = {
|
|
2224
|
+
...this.options,
|
|
2225
|
+
...options,
|
|
2226
|
+
...{
|
|
2227
|
+
isClone: true
|
|
2228
|
+
}
|
|
2229
|
+
};
|
|
2230
|
+
const clone = new I18n(mergedOptions);
|
|
2231
|
+
if (options.debug !== undefined || options.prefix !== undefined) {
|
|
2232
|
+
clone.logger = clone.logger.clone(options);
|
|
2233
|
+
}
|
|
2234
|
+
const membersToCopy = ['store', 'services', 'language'];
|
|
2235
|
+
membersToCopy.forEach(m => {
|
|
2236
|
+
clone[m] = this[m];
|
|
2237
|
+
});
|
|
2238
|
+
clone.services = {
|
|
2239
|
+
...this.services
|
|
2240
|
+
};
|
|
2241
|
+
clone.services.utils = {
|
|
2242
|
+
hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
|
|
2243
|
+
};
|
|
2244
|
+
if (forkResourceStore) {
|
|
2245
|
+
clone.store = new ResourceStore(this.store.data, mergedOptions);
|
|
2246
|
+
clone.services.resourceStore = clone.store;
|
|
2247
|
+
}
|
|
2248
|
+
clone.translator = new Translator(clone.services, mergedOptions);
|
|
2249
|
+
clone.translator.on('*', function (event) {
|
|
2250
|
+
for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
|
|
2251
|
+
args[_key4 - 1] = arguments[_key4];
|
|
2252
|
+
}
|
|
2253
|
+
clone.emit(event, ...args);
|
|
2254
|
+
});
|
|
2255
|
+
clone.init(mergedOptions, callback);
|
|
2256
|
+
clone.translator.options = mergedOptions;
|
|
2257
|
+
clone.translator.backendConnector.services.utils = {
|
|
2258
|
+
hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
|
|
2259
|
+
};
|
|
2260
|
+
return clone;
|
|
2261
|
+
}
|
|
2262
|
+
toJSON() {
|
|
2263
|
+
return {
|
|
2264
|
+
options: this.options,
|
|
2265
|
+
store: this.store,
|
|
2266
|
+
language: this.language,
|
|
2267
|
+
languages: this.languages,
|
|
2268
|
+
resolvedLanguage: this.resolvedLanguage
|
|
2269
|
+
};
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
const instance = I18n.createInstance();
|
|
2273
|
+
instance.createInstance = I18n.createInstance;
|
|
2274
|
+
|
|
2275
|
+
instance.createInstance;
|
|
2276
|
+
instance.dir;
|
|
2277
|
+
instance.init;
|
|
2278
|
+
instance.loadResources;
|
|
2279
|
+
instance.reloadResources;
|
|
2280
|
+
instance.use;
|
|
2281
|
+
instance.changeLanguage;
|
|
2282
|
+
instance.getFixedT;
|
|
2283
|
+
const t$1 = instance.t;
|
|
2284
|
+
instance.exists;
|
|
2285
|
+
instance.setDefaultNamespace;
|
|
2286
|
+
instance.hasLoadedNamespace;
|
|
2287
|
+
instance.loadNamespaces;
|
|
2288
|
+
instance.loadLanguages;
|
|
2289
|
+
|
|
2290
|
+
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
|
2291
|
+
|
|
2292
|
+
function getDefaultExportFromCjs (x) {
|
|
2293
|
+
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
2294
|
+
}
|
|
2295
|
+
|
|
2296
|
+
/**
|
|
2297
|
+
* This file automatically generated from `pre-publish.js`.
|
|
2298
|
+
* Do not manually edit.
|
|
2299
|
+
*/
|
|
2300
|
+
|
|
2301
|
+
var voidElements = {
|
|
2302
|
+
"area": true,
|
|
2303
|
+
"base": true,
|
|
2304
|
+
"br": true,
|
|
2305
|
+
"col": true,
|
|
2306
|
+
"embed": true,
|
|
2307
|
+
"hr": true,
|
|
2308
|
+
"img": true,
|
|
2309
|
+
"input": true,
|
|
2310
|
+
"link": true,
|
|
2311
|
+
"meta": true,
|
|
2312
|
+
"param": true,
|
|
2313
|
+
"source": true,
|
|
2314
|
+
"track": true,
|
|
2315
|
+
"wbr": true
|
|
2316
|
+
};
|
|
2317
|
+
|
|
2318
|
+
var e = /*@__PURE__*/getDefaultExportFromCjs(voidElements);
|
|
2319
|
+
|
|
2320
|
+
var t=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function n(n){var r={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},i=n.match(/<\/?([^\s]+?)[/\s>]/);if(i&&(r.name=i[1],(e[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),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(r);return l<0?(c.push(v),c):((u=o[l]).children.push(v),c)}if(f&&(l++,"tag"===(a=n(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)},"")}};
|
|
2321
|
+
|
|
2322
|
+
function warn() {
|
|
2323
|
+
if (console && console.warn) {
|
|
2324
|
+
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
|
2325
|
+
args[_key] = arguments[_key];
|
|
2326
|
+
}
|
|
2327
|
+
if (typeof args[0] === 'string') args[0] = `react-i18next:: ${args[0]}`;
|
|
2328
|
+
console.warn(...args);
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
const alreadyWarned = {};
|
|
2332
|
+
function warnOnce() {
|
|
2333
|
+
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
|
|
2334
|
+
args[_key2] = arguments[_key2];
|
|
2335
|
+
}
|
|
2336
|
+
if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return;
|
|
2337
|
+
if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date();
|
|
2338
|
+
warn(...args);
|
|
2339
|
+
}
|
|
2340
|
+
|
|
2341
|
+
const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
|
|
2342
|
+
const htmlEntities = {
|
|
2343
|
+
'&': '&',
|
|
2344
|
+
'&': '&',
|
|
2345
|
+
'<': '<',
|
|
2346
|
+
'<': '<',
|
|
2347
|
+
'>': '>',
|
|
2348
|
+
'>': '>',
|
|
2349
|
+
''': "'",
|
|
2350
|
+
''': "'",
|
|
2351
|
+
'"': '"',
|
|
2352
|
+
'"': '"',
|
|
2353
|
+
' ': ' ',
|
|
2354
|
+
' ': ' ',
|
|
2355
|
+
'©': '©',
|
|
2356
|
+
'©': '©',
|
|
2357
|
+
'®': '®',
|
|
2358
|
+
'®': '®',
|
|
2359
|
+
'…': '…',
|
|
2360
|
+
'…': '…',
|
|
2361
|
+
'/': '/',
|
|
2362
|
+
'/': '/'
|
|
2363
|
+
};
|
|
2364
|
+
const unescapeHtmlEntity = m => htmlEntities[m];
|
|
2365
|
+
const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);
|
|
2366
|
+
|
|
2367
|
+
let defaultOptions = {
|
|
2368
|
+
bindI18n: 'languageChanged',
|
|
2369
|
+
bindI18nStore: '',
|
|
2370
|
+
transEmptyNodeValue: '',
|
|
2371
|
+
transSupportBasicHtmlNodes: true,
|
|
2372
|
+
transWrapTextNodes: '',
|
|
2373
|
+
transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
|
|
2374
|
+
useSuspense: true,
|
|
2375
|
+
unescape
|
|
2376
|
+
};
|
|
2377
|
+
function setDefaults() {
|
|
2378
|
+
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
2379
|
+
defaultOptions = {
|
|
2380
|
+
...defaultOptions,
|
|
2381
|
+
...options
|
|
2382
|
+
};
|
|
2383
|
+
}
|
|
2384
|
+
function getDefaults() {
|
|
2385
|
+
return defaultOptions;
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
let i18nInstance;
|
|
2389
|
+
function setI18n(instance) {
|
|
2390
|
+
i18nInstance = instance;
|
|
2391
|
+
}
|
|
2392
|
+
function getI18n() {
|
|
2393
|
+
return i18nInstance;
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
function hasChildren(node, checkLength) {
|
|
2397
|
+
if (!node) return false;
|
|
2398
|
+
const base = node.props ? node.props.children : node.children;
|
|
2399
|
+
if (checkLength) return base.length > 0;
|
|
2400
|
+
return !!base;
|
|
2401
|
+
}
|
|
2402
|
+
function getChildren(node) {
|
|
2403
|
+
if (!node) return [];
|
|
2404
|
+
return node.props ? node.props.children : node.children;
|
|
2405
|
+
}
|
|
2406
|
+
function hasValidReactChildren(children) {
|
|
2407
|
+
if (Object.prototype.toString.call(children) !== '[object Array]') return false;
|
|
2408
|
+
return children.every(child => isValidElement(child));
|
|
2409
|
+
}
|
|
2410
|
+
function getAsArray(data) {
|
|
2411
|
+
return Array.isArray(data) ? data : [data];
|
|
2412
|
+
}
|
|
2413
|
+
function mergeProps(source, target) {
|
|
2414
|
+
const newTarget = {
|
|
2415
|
+
...target
|
|
2416
|
+
};
|
|
2417
|
+
newTarget.props = Object.assign(source.props, target.props);
|
|
2418
|
+
return newTarget;
|
|
2419
|
+
}
|
|
2420
|
+
function nodesToString(children, i18nOptions) {
|
|
2421
|
+
if (!children) return '';
|
|
2422
|
+
let stringNode = '';
|
|
2423
|
+
const childrenArray = getAsArray(children);
|
|
2424
|
+
const keepArray = i18nOptions.transSupportBasicHtmlNodes && i18nOptions.transKeepBasicHtmlNodesFor ? i18nOptions.transKeepBasicHtmlNodesFor : [];
|
|
2425
|
+
childrenArray.forEach((child, childIndex) => {
|
|
2426
|
+
if (typeof child === 'string') {
|
|
2427
|
+
stringNode += `${child}`;
|
|
2428
|
+
} else if (isValidElement(child)) {
|
|
2429
|
+
const childPropsCount = Object.keys(child.props).length;
|
|
2430
|
+
const shouldKeepChild = keepArray.indexOf(child.type) > -1;
|
|
2431
|
+
const childChildren = child.props.children;
|
|
2432
|
+
if (!childChildren && shouldKeepChild && childPropsCount === 0) {
|
|
2433
|
+
stringNode += `<${child.type}/>`;
|
|
2434
|
+
} else if (!childChildren && (!shouldKeepChild || childPropsCount !== 0)) {
|
|
2435
|
+
stringNode += `<${childIndex}></${childIndex}>`;
|
|
2436
|
+
} else if (child.props.i18nIsDynamicList) {
|
|
2437
|
+
stringNode += `<${childIndex}></${childIndex}>`;
|
|
2438
|
+
} else if (shouldKeepChild && childPropsCount === 1 && typeof childChildren === 'string') {
|
|
2439
|
+
stringNode += `<${child.type}>${childChildren}</${child.type}>`;
|
|
2440
|
+
} else {
|
|
2441
|
+
const content = nodesToString(childChildren, i18nOptions);
|
|
2442
|
+
stringNode += `<${childIndex}>${content}</${childIndex}>`;
|
|
2443
|
+
}
|
|
2444
|
+
} else if (child === null) {
|
|
2445
|
+
warn(`Trans: the passed in value is invalid - seems you passed in a null child.`);
|
|
2446
|
+
} else if (typeof child === 'object') {
|
|
2447
|
+
const {
|
|
2448
|
+
format,
|
|
2449
|
+
...clone
|
|
2450
|
+
} = child;
|
|
2451
|
+
const keys = Object.keys(clone);
|
|
2452
|
+
if (keys.length === 1) {
|
|
2453
|
+
const value = format ? `${keys[0]}, ${format}` : keys[0];
|
|
2454
|
+
stringNode += `{{${value}}}`;
|
|
2455
|
+
} else {
|
|
2456
|
+
warn(`react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.`, child);
|
|
2457
|
+
}
|
|
2458
|
+
} else {
|
|
2459
|
+
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);
|
|
2460
|
+
}
|
|
2461
|
+
});
|
|
2462
|
+
return stringNode;
|
|
2463
|
+
}
|
|
2464
|
+
function renderNodes(children, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) {
|
|
2465
|
+
if (targetString === '') return [];
|
|
2466
|
+
const keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
|
|
2467
|
+
const emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.join('|')).test(targetString);
|
|
2468
|
+
if (!children && !emptyChildrenButNeedsHandling) return [targetString];
|
|
2469
|
+
const data = {};
|
|
2470
|
+
function getData(childs) {
|
|
2471
|
+
const childrenArray = getAsArray(childs);
|
|
2472
|
+
childrenArray.forEach(child => {
|
|
2473
|
+
if (typeof child === 'string') return;
|
|
2474
|
+
if (hasChildren(child)) getData(getChildren(child));else if (typeof child === 'object' && !isValidElement(child)) Object.assign(data, child);
|
|
2475
|
+
});
|
|
2476
|
+
}
|
|
2477
|
+
getData(children);
|
|
2478
|
+
const ast = c.parse(`<0>${targetString}</0>`);
|
|
2479
|
+
const opts = {
|
|
2480
|
+
...data,
|
|
2481
|
+
...combinedTOpts
|
|
2482
|
+
};
|
|
2483
|
+
function renderInner(child, node, rootReactNode) {
|
|
2484
|
+
const childs = getChildren(child);
|
|
2485
|
+
const mappedChildren = mapAST(childs, node.children, rootReactNode);
|
|
2486
|
+
return hasValidReactChildren(childs) && mappedChildren.length === 0 ? childs : mappedChildren;
|
|
2487
|
+
}
|
|
2488
|
+
function pushTranslatedJSX(child, inner, mem, i, isVoid) {
|
|
2489
|
+
if (child.dummy) child.children = inner;
|
|
2490
|
+
mem.push(cloneElement(child, {
|
|
2491
|
+
...child.props,
|
|
2492
|
+
key: i
|
|
2493
|
+
}, isVoid ? undefined : inner));
|
|
2494
|
+
}
|
|
2495
|
+
function mapAST(reactNode, astNode, rootReactNode) {
|
|
2496
|
+
const reactNodes = getAsArray(reactNode);
|
|
2497
|
+
const astNodes = getAsArray(astNode);
|
|
2498
|
+
return astNodes.reduce((mem, node, i) => {
|
|
2499
|
+
const translationContent = node.children && node.children[0] && node.children[0].content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);
|
|
2500
|
+
if (node.type === 'tag') {
|
|
2501
|
+
let tmp = reactNodes[parseInt(node.name, 10)];
|
|
2502
|
+
if (!tmp && rootReactNode.length === 1 && rootReactNode[0][node.name]) tmp = rootReactNode[0][node.name];
|
|
2503
|
+
if (!tmp) tmp = {};
|
|
2504
|
+
const child = Object.keys(node.attrs).length !== 0 ? mergeProps({
|
|
2505
|
+
props: node.attrs
|
|
2506
|
+
}, tmp) : tmp;
|
|
2507
|
+
const isElement = isValidElement(child);
|
|
2508
|
+
const isValidTranslationWithChildren = isElement && hasChildren(node, true) && !node.voidElement;
|
|
2509
|
+
const isEmptyTransWithHTML = emptyChildrenButNeedsHandling && typeof child === 'object' && child.dummy && !isElement;
|
|
2510
|
+
const isKnownComponent = typeof children === 'object' && children !== null && Object.hasOwnProperty.call(children, node.name);
|
|
2511
|
+
if (typeof child === 'string') {
|
|
2512
|
+
const value = i18n.services.interpolator.interpolate(child, opts, i18n.language);
|
|
2513
|
+
mem.push(value);
|
|
2514
|
+
} else if (hasChildren(child) || isValidTranslationWithChildren) {
|
|
2515
|
+
const inner = renderInner(child, node, rootReactNode);
|
|
2516
|
+
pushTranslatedJSX(child, inner, mem, i);
|
|
2517
|
+
} else if (isEmptyTransWithHTML) {
|
|
2518
|
+
const inner = mapAST(reactNodes, node.children, rootReactNode);
|
|
2519
|
+
mem.push(cloneElement(child, {
|
|
2520
|
+
...child.props,
|
|
2521
|
+
key: i
|
|
2522
|
+
}, inner));
|
|
2523
|
+
} else if (Number.isNaN(parseFloat(node.name))) {
|
|
2524
|
+
if (isKnownComponent) {
|
|
2525
|
+
const inner = renderInner(child, node, rootReactNode);
|
|
2526
|
+
pushTranslatedJSX(child, inner, mem, i, node.voidElement);
|
|
2527
|
+
} else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
|
|
2528
|
+
if (node.voidElement) {
|
|
2529
|
+
mem.push(createElement(node.name, {
|
|
2530
|
+
key: `${node.name}-${i}`
|
|
2531
|
+
}));
|
|
2532
|
+
} else {
|
|
2533
|
+
const inner = mapAST(reactNodes, node.children, rootReactNode);
|
|
2534
|
+
mem.push(createElement(node.name, {
|
|
2535
|
+
key: `${node.name}-${i}`
|
|
2536
|
+
}, inner));
|
|
2537
|
+
}
|
|
2538
|
+
} else if (node.voidElement) {
|
|
2539
|
+
mem.push(`<${node.name} />`);
|
|
2540
|
+
} else {
|
|
2541
|
+
const inner = mapAST(reactNodes, node.children, rootReactNode);
|
|
2542
|
+
mem.push(`<${node.name}>${inner}</${node.name}>`);
|
|
2543
|
+
}
|
|
2544
|
+
} else if (typeof child === 'object' && !isElement) {
|
|
2545
|
+
const content = node.children[0] ? translationContent : null;
|
|
2546
|
+
if (content) mem.push(content);
|
|
2547
|
+
} else if (node.children.length === 1 && translationContent) {
|
|
2548
|
+
mem.push(cloneElement(child, {
|
|
2549
|
+
...child.props,
|
|
2550
|
+
key: i
|
|
2551
|
+
}, translationContent));
|
|
2552
|
+
} else {
|
|
2553
|
+
mem.push(cloneElement(child, {
|
|
2554
|
+
...child.props,
|
|
2555
|
+
key: i
|
|
2556
|
+
}));
|
|
2557
|
+
}
|
|
2558
|
+
} else if (node.type === 'text') {
|
|
2559
|
+
const wrapTextNodes = i18nOptions.transWrapTextNodes;
|
|
2560
|
+
const content = shouldUnescape ? i18nOptions.unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);
|
|
2561
|
+
if (wrapTextNodes) {
|
|
2562
|
+
mem.push(createElement(wrapTextNodes, {
|
|
2563
|
+
key: `${node.name}-${i}`
|
|
2564
|
+
}, content));
|
|
2565
|
+
} else {
|
|
2566
|
+
mem.push(content);
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
return mem;
|
|
2570
|
+
}, []);
|
|
2571
|
+
}
|
|
2572
|
+
const result = mapAST([{
|
|
2573
|
+
dummy: true,
|
|
2574
|
+
children: children || []
|
|
2575
|
+
}], ast, getAsArray(children || []));
|
|
2576
|
+
return getChildren(result[0]);
|
|
2577
|
+
}
|
|
2578
|
+
function Trans$1(_ref) {
|
|
2579
|
+
let {
|
|
2580
|
+
children,
|
|
2581
|
+
count,
|
|
2582
|
+
parent,
|
|
2583
|
+
i18nKey,
|
|
2584
|
+
context,
|
|
2585
|
+
tOptions = {},
|
|
2586
|
+
values,
|
|
2587
|
+
defaults,
|
|
2588
|
+
components,
|
|
2589
|
+
ns,
|
|
2590
|
+
i18n: i18nFromProps,
|
|
2591
|
+
t: tFromProps,
|
|
2592
|
+
shouldUnescape,
|
|
2593
|
+
...additionalProps
|
|
2594
|
+
} = _ref;
|
|
2595
|
+
const i18n = i18nFromProps || getI18n();
|
|
2596
|
+
if (!i18n) {
|
|
2597
|
+
warnOnce('You will need to pass in an i18next instance by using i18nextReactModule');
|
|
2598
|
+
return children;
|
|
2599
|
+
}
|
|
2600
|
+
const t = tFromProps || i18n.t.bind(i18n) || (k => k);
|
|
2601
|
+
if (context) tOptions.context = context;
|
|
2602
|
+
const reactI18nextOptions = {
|
|
2603
|
+
...getDefaults(),
|
|
2604
|
+
...(i18n.options && i18n.options.react)
|
|
2605
|
+
};
|
|
2606
|
+
let namespaces = ns || t.ns || i18n.options && i18n.options.defaultNS;
|
|
2607
|
+
namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
|
|
2608
|
+
const defaultValue = defaults || nodesToString(children, reactI18nextOptions) || reactI18nextOptions.transEmptyNodeValue || i18nKey;
|
|
2609
|
+
const {
|
|
2610
|
+
hashTransKey
|
|
2611
|
+
} = reactI18nextOptions;
|
|
2612
|
+
const key = i18nKey || (hashTransKey ? hashTransKey(defaultValue) : defaultValue);
|
|
2613
|
+
const interpolationOverride = values ? tOptions.interpolation : {
|
|
2614
|
+
interpolation: {
|
|
2615
|
+
...tOptions.interpolation,
|
|
2616
|
+
prefix: '#$?',
|
|
2617
|
+
suffix: '?$#'
|
|
2618
|
+
}
|
|
2619
|
+
};
|
|
2620
|
+
const combinedTOpts = {
|
|
2621
|
+
...tOptions,
|
|
2622
|
+
count,
|
|
2623
|
+
...values,
|
|
2624
|
+
...interpolationOverride,
|
|
2625
|
+
defaultValue,
|
|
2626
|
+
ns: namespaces
|
|
2627
|
+
};
|
|
2628
|
+
const translation = key ? t(key, combinedTOpts) : defaultValue;
|
|
2629
|
+
const content = renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);
|
|
2630
|
+
const useAsParent = parent !== undefined ? parent : reactI18nextOptions.defaultTransParent;
|
|
2631
|
+
return useAsParent ? createElement(useAsParent, additionalProps, content) : content;
|
|
2632
|
+
}
|
|
2633
|
+
|
|
2634
|
+
const initReactI18next = {
|
|
2635
|
+
type: '3rdParty',
|
|
2636
|
+
init(instance) {
|
|
2637
|
+
setDefaults(instance.options.react);
|
|
2638
|
+
setI18n(instance);
|
|
2639
|
+
}
|
|
2640
|
+
};
|
|
2641
|
+
|
|
2642
|
+
const I18nContext = createContext();
|
|
2643
|
+
|
|
2644
|
+
function Trans(_ref) {
|
|
2645
|
+
let {
|
|
2646
|
+
children,
|
|
2647
|
+
count,
|
|
2648
|
+
parent,
|
|
2649
|
+
i18nKey,
|
|
2650
|
+
context,
|
|
2651
|
+
tOptions = {},
|
|
2652
|
+
values,
|
|
2653
|
+
defaults,
|
|
2654
|
+
components,
|
|
2655
|
+
ns,
|
|
2656
|
+
i18n: i18nFromProps,
|
|
2657
|
+
t: tFromProps,
|
|
2658
|
+
shouldUnescape,
|
|
2659
|
+
...additionalProps
|
|
2660
|
+
} = _ref;
|
|
2661
|
+
const {
|
|
2662
|
+
i18n: i18nFromContext,
|
|
2663
|
+
defaultNS: defaultNSFromContext
|
|
2664
|
+
} = useContext(I18nContext) || {};
|
|
2665
|
+
const i18n = i18nFromProps || i18nFromContext || getI18n();
|
|
2666
|
+
const t = tFromProps || i18n && i18n.t.bind(i18n);
|
|
2667
|
+
return Trans$1({
|
|
2668
|
+
children,
|
|
2669
|
+
count,
|
|
2670
|
+
parent,
|
|
2671
|
+
i18nKey,
|
|
2672
|
+
context,
|
|
2673
|
+
tOptions,
|
|
2674
|
+
values,
|
|
2675
|
+
defaults,
|
|
2676
|
+
components,
|
|
2677
|
+
ns: ns || t && t.ns || defaultNSFromContext || i18n && i18n.options && i18n.options.defaultNS,
|
|
2678
|
+
i18n,
|
|
2679
|
+
t: tFromProps,
|
|
2680
|
+
shouldUnescape,
|
|
2681
|
+
...additionalProps
|
|
2682
|
+
});
|
|
2683
|
+
}
|
|
2684
|
+
|
|
2685
|
+
var common = {
|
|
2686
|
+
apiKey_one: "API key",
|
|
2687
|
+
apiKey_other: "API keys",
|
|
2688
|
+
never: "Never"
|
|
2689
|
+
};
|
|
2690
|
+
var headers = {
|
|
2691
|
+
createApiKey: "Create API key",
|
|
2692
|
+
updateApiKey: "Update API key"
|
|
2693
|
+
};
|
|
2694
|
+
var noData = {
|
|
2695
|
+
title: "There are no API Keys"
|
|
2696
|
+
};
|
|
2697
|
+
var alert = {
|
|
2698
|
+
titles: {
|
|
2699
|
+
deleteApiKey: "Delete API key?"
|
|
2700
|
+
},
|
|
2701
|
+
descriptions: {
|
|
2702
|
+
deleteApiKey: "You are deleting the API key named <strong>{{name}}</strong>. This cannot be undone."
|
|
2703
|
+
}
|
|
2704
|
+
};
|
|
2705
|
+
var buttons = {
|
|
2706
|
+
"delete": "Delete",
|
|
2707
|
+
addApiKey: "Add API key",
|
|
2708
|
+
edit: "Edit",
|
|
2709
|
+
submit: "Submit",
|
|
2710
|
+
cancel: "Cancel"
|
|
2711
|
+
};
|
|
2712
|
+
var placeholders = {
|
|
2713
|
+
search: "Search API keys",
|
|
2714
|
+
selectExpiryDate: "Select an expiry date",
|
|
2715
|
+
label: "Add a label for the API key"
|
|
2716
|
+
};
|
|
2717
|
+
var notifications = {
|
|
2718
|
+
copiedToClipboard: "API key has been copied to clipboard"
|
|
2719
|
+
};
|
|
2720
|
+
var tooltips = {
|
|
2721
|
+
copyToClipboard: "Copy to clipboard"
|
|
2722
|
+
};
|
|
2723
|
+
var table = {
|
|
2724
|
+
headers: {
|
|
2725
|
+
label: "Label",
|
|
2726
|
+
token: "Token",
|
|
2727
|
+
expiresAt: "Expires at",
|
|
2728
|
+
createdAt: "Created at",
|
|
2729
|
+
status: "Status"
|
|
2730
|
+
}
|
|
2731
|
+
};
|
|
2732
|
+
var fields = {
|
|
2733
|
+
label: "Label",
|
|
2734
|
+
expiryDate: "Expiry date",
|
|
2735
|
+
neverExpire: "Never expire"
|
|
2736
|
+
};
|
|
2737
|
+
var validations = {
|
|
2738
|
+
expiry: "$t(fields.expiryDate) should be at least {{date}}",
|
|
2739
|
+
required: "{{entity}} is required"
|
|
2740
|
+
};
|
|
2741
|
+
var tags = {
|
|
2742
|
+
expired: "Expired",
|
|
2743
|
+
active: "Active"
|
|
2744
|
+
};
|
|
2745
|
+
var en = {
|
|
2746
|
+
common: common,
|
|
2747
|
+
headers: headers,
|
|
2748
|
+
noData: noData,
|
|
2749
|
+
alert: alert,
|
|
2750
|
+
buttons: buttons,
|
|
2751
|
+
placeholders: placeholders,
|
|
2752
|
+
notifications: notifications,
|
|
2753
|
+
tooltips: tooltips,
|
|
2754
|
+
table: table,
|
|
2755
|
+
fields: fields,
|
|
2756
|
+
validations: validations,
|
|
2757
|
+
tags: tags
|
|
2758
|
+
};
|
|
2759
|
+
|
|
2760
|
+
instance.use(initReactI18next).init({
|
|
2761
|
+
resources: {
|
|
2762
|
+
en: {
|
|
2763
|
+
translation: en
|
|
2764
|
+
}
|
|
2765
|
+
},
|
|
2766
|
+
fallbackLng: "en"
|
|
2767
|
+
});
|
|
2768
|
+
|
|
2769
|
+
function _arrayWithHoles(arr) {
|
|
2770
|
+
if (Array.isArray(arr)) return arr;
|
|
2771
|
+
}
|
|
2772
|
+
|
|
2773
|
+
function _iterableToArrayLimit(arr, i) {
|
|
2774
|
+
var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
|
|
2775
|
+
if (null != _i) {
|
|
2776
|
+
var _s,
|
|
2777
|
+
_e,
|
|
2778
|
+
_x,
|
|
2779
|
+
_r,
|
|
2780
|
+
_arr = [],
|
|
2781
|
+
_n = !0,
|
|
2782
|
+
_d = !1;
|
|
2783
|
+
try {
|
|
2784
|
+
if (_x = (_i = _i.call(arr)).next, 0 === i) {
|
|
2785
|
+
if (Object(_i) !== _i) return;
|
|
2786
|
+
_n = !1;
|
|
2787
|
+
} else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
|
|
2788
|
+
} catch (err) {
|
|
2789
|
+
_d = !0, _e = err;
|
|
2790
|
+
} finally {
|
|
2791
|
+
try {
|
|
2792
|
+
if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return;
|
|
2793
|
+
} finally {
|
|
2794
|
+
if (_d) throw _e;
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
return _arr;
|
|
2798
|
+
}
|
|
2799
|
+
}
|
|
2800
|
+
|
|
2801
|
+
function _arrayLikeToArray(arr, len) {
|
|
2802
|
+
if (len == null || len > arr.length) len = arr.length;
|
|
2803
|
+
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
|
|
2804
|
+
return arr2;
|
|
2805
|
+
}
|
|
2806
|
+
|
|
2807
|
+
function _unsupportedIterableToArray(o, minLen) {
|
|
2808
|
+
if (!o) return;
|
|
2809
|
+
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
|
|
2810
|
+
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
2811
|
+
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
2812
|
+
if (n === "Map" || n === "Set") return Array.from(o);
|
|
2813
|
+
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
function _nonIterableRest() {
|
|
2817
|
+
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
2818
|
+
}
|
|
2819
|
+
|
|
2820
|
+
function _slicedToArray(arr, i) {
|
|
2821
|
+
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
|
|
2822
|
+
}
|
|
2823
|
+
|
|
2824
|
+
var API_KEYS_BASE_URL = "/neeto_api_keys_engine/api/v1/api_keys";
|
|
2825
|
+
|
|
2826
|
+
var fetch = function fetch(params) {
|
|
2827
|
+
return axios.get(API_KEYS_BASE_URL, {
|
|
2828
|
+
params: params
|
|
2829
|
+
});
|
|
2830
|
+
};
|
|
2831
|
+
var create = function create(payload) {
|
|
2832
|
+
return axios.post(API_KEYS_BASE_URL, {
|
|
2833
|
+
apiKey: payload
|
|
2834
|
+
});
|
|
2835
|
+
};
|
|
2836
|
+
var update = function update(_ref) {
|
|
2837
|
+
var id = _ref.id,
|
|
2838
|
+
payload = _ref.payload;
|
|
2839
|
+
return axios.put("".concat(API_KEYS_BASE_URL, "/").concat(id), {
|
|
2840
|
+
apiKey: payload
|
|
2841
|
+
});
|
|
2842
|
+
};
|
|
2843
|
+
var destroy = function destroy(id) {
|
|
2844
|
+
return axios["delete"]("".concat(API_KEYS_BASE_URL, "/").concat(id));
|
|
2845
|
+
};
|
|
2846
|
+
var apiKeysApi = {
|
|
2847
|
+
fetch: fetch,
|
|
2848
|
+
create: create,
|
|
2849
|
+
update: update,
|
|
2850
|
+
destroy: destroy
|
|
2851
|
+
};
|
|
2852
|
+
|
|
2853
|
+
var QUERY_KEYS = {
|
|
2854
|
+
API_KEYS: "api-keys"
|
|
2855
|
+
};
|
|
2856
|
+
|
|
2857
|
+
var useFetchApiKeys = function useFetchApiKeys(_ref) {
|
|
2858
|
+
var params = _ref.params,
|
|
2859
|
+
options = _ref.options;
|
|
2860
|
+
return useQuery([QUERY_KEYS.API_KEYS, params], function () {
|
|
2861
|
+
return apiKeysApi.fetch(params);
|
|
2862
|
+
}, options);
|
|
2863
|
+
};
|
|
2864
|
+
var useCreateApiKey = function useCreateApiKey(onSuccess) {
|
|
2865
|
+
return useMutationWithInvalidation(apiKeysApi.create, {
|
|
2866
|
+
keysToInvalidate: [QUERY_KEYS.API_KEYS],
|
|
2867
|
+
onSuccess: onSuccess
|
|
2868
|
+
});
|
|
2869
|
+
};
|
|
2870
|
+
var useUpdateApiKey = function useUpdateApiKey(onSuccess) {
|
|
2871
|
+
return useMutationWithInvalidation(function (_ref2) {
|
|
2872
|
+
var id = _ref2.id,
|
|
2873
|
+
payload = _ref2.payload;
|
|
2874
|
+
return apiKeysApi.update({
|
|
2875
|
+
id: id,
|
|
2876
|
+
payload: payload
|
|
2877
|
+
});
|
|
2878
|
+
}, {
|
|
2879
|
+
keysToInvalidate: [QUERY_KEYS.API_KEYS],
|
|
2880
|
+
onSuccess: onSuccess
|
|
2881
|
+
});
|
|
2882
|
+
};
|
|
2883
|
+
var useDeleteApiKey = function useDeleteApiKey(onSuccess) {
|
|
2884
|
+
return useMutationWithInvalidation(apiKeysApi.destroy, {
|
|
2885
|
+
keysToInvalidate: [QUERY_KEYS.API_KEYS],
|
|
2886
|
+
onSuccess: onSuccess
|
|
2887
|
+
});
|
|
2888
|
+
};
|
|
2889
|
+
|
|
2890
|
+
function _extends() {
|
|
2891
|
+
_extends = Object.assign ? Object.assign.bind() : function (target) {
|
|
2892
|
+
for (var i = 1; i < arguments.length; i++) {
|
|
2893
|
+
var source = arguments[i];
|
|
2894
|
+
for (var key in source) {
|
|
2895
|
+
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
|
2896
|
+
target[key] = source[key];
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2900
|
+
return target;
|
|
2901
|
+
};
|
|
2902
|
+
return _extends.apply(this, arguments);
|
|
2903
|
+
}
|
|
2904
|
+
|
|
2905
|
+
var dayjs_min = {exports: {}};
|
|
2906
|
+
|
|
2907
|
+
dayjs_min.exports;
|
|
2908
|
+
|
|
2909
|
+
(function (module, exports) {
|
|
2910
|
+
!function(t,e){module.exports=e();}(commonjsGlobal,(function(){var t=1e3,e=6e4,n=36e5,r="millisecond",i="second",s="minute",u="hour",a="day",o="week",c="month",f="quarter",h="year",d="date",l="Invalid Date",$=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(t){var e=["th","st","nd","rd"],n=t%100;return "["+t+(e[(n-20)%10]||e[n]||e[0])+"]"}},m=function(t,e,n){var r=String(t);return !r||r.length>=e?t:""+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return (e<=0?"+":"-")+m(r,2,"0")+":"+m(i,2,"0")},m:function t(e,n){if(e.date()<n.date())return -t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,c),s=n-i<0,u=e.clone().add(r+(s?-1:1),c);return +(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return {M:c,y:h,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:f}[t]||String(t||"").toLowerCase().replace(/s$/,"")},u:function(t){return void 0===t}},g="en",D={};D[g]=M;var p=function(t){return t instanceof b},S=function t(e,n,r){var i;if(!e)return g;if("string"==typeof e){var s=e.toLowerCase();D[s]&&(i=s),n&&(D[s]=n,i=s);var u=e.split("-");if(!i&&u.length>1)return t(u[0])}else {var a=e.name;D[a]=e,i=a;}return !r&&i&&(g=i),i||!r&&g},w=function(t,e){if(p(t))return t.clone();var n="object"==typeof e?e:{};return n.date=t,n.args=arguments,new b(n)},O=v;O.l=S,O.i=p,O.w=function(t,e){return w(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var b=function(){function M(t){this.$L=S(t.locale,null,!0),this.parse(t);}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(O.u(e))return new Date;if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.$x=t.x||{},this.init();},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds();},m.$utils=function(){return O},m.isValid=function(){return !(this.$d.toString()===l)},m.isSame=function(t,e){var n=w(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return w(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<w(t)},m.$g=function(t,e,n){return O.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!O.u(e)||e,f=O.p(t),l=function(t,e){var i=O.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},$=function(t,e){return O.w(n.toDate()[t].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,v="set"+(this.$u?"UTC":"");switch(f){case h:return r?l(1,0):l(31,11);case c:return r?l(1,M):l(0,M+1);case o:var g=this.$locale().weekStart||0,D=(y<g?y+7:y)-g;return l(r?m-D:m+(6-D),M);case a:case d:return $(v+"Hours",0);case u:return $(v+"Minutes",1);case s:return $(v+"Seconds",2);case i:return $(v+"Milliseconds",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=O.p(t),f="set"+(this.$u?"UTC":""),l=(n={},n[a]=f+"Date",n[d]=f+"Date",n[c]=f+"Month",n[h]=f+"FullYear",n[u]=f+"Hours",n[s]=f+"Minutes",n[i]=f+"Seconds",n[r]=f+"Milliseconds",n)[o],$=o===a?this.$D+(e-this.$W):e;if(o===c||o===h){var y=this.clone().set(d,1);y.$d[l]($),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d;}else l&&this.$d[l]($);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[O.p(t)]()},m.add=function(r,f){var d,l=this;r=Number(r);var $=O.p(f),y=function(t){var e=w(l);return O.w(e.date(e.date()+Math.round(t*r)),l)};if($===c)return this.set(c,this.$M+r);if($===h)return this.set(h,this.$y+r);if($===a)return y(1);if($===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[$]||1,m=this.$d.getTime()+r*M;return O.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||l;var r=t||"YYYY-MM-DDTHH:mm:ssZ",i=O.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,c=n.months,f=n.meridiem,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].slice(0,s)},d=function(t){return O.s(s%12||12,t,"0")},$=f||function(t,e,n){var r=t<12?"AM":"PM";return n?r.toLowerCase():r};return r.replace(y,(function(t,r){return r||function(t){switch(t){case"YY":return String(e.$y).slice(-2);case"YYYY":return O.s(e.$y,4,"0");case"M":return a+1;case"MM":return O.s(a+1,2,"0");case"MMM":return h(n.monthsShort,a,c,3);case"MMMM":return h(c,a);case"D":return e.$D;case"DD":return O.s(e.$D,2,"0");case"d":return String(e.$W);case"dd":return h(n.weekdaysMin,e.$W,o,2);case"ddd":return h(n.weekdaysShort,e.$W,o,3);case"dddd":return o[e.$W];case"H":return String(s);case"HH":return O.s(s,2,"0");case"h":return d(1);case"hh":return d(2);case"a":return $(s,u,!0);case"A":return $(s,u,!1);case"m":return String(u);case"mm":return O.s(u,2,"0");case"s":return String(e.$s);case"ss":return O.s(e.$s,2,"0");case"SSS":return O.s(e.$ms,3,"0");case"Z":return i}return null}(t)||i.replace(":","")}))},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(r,d,l){var $,y=this,M=O.p(d),m=w(r),v=(m.utcOffset()-this.utcOffset())*e,g=this-m,D=function(){return O.m(y,m)};switch(M){case h:$=D()/12;break;case c:$=D();break;case f:$=D()/3;break;case o:$=(g-v)/6048e5;break;case a:$=(g-v)/864e5;break;case u:$=g/n;break;case s:$=g/e;break;case i:$=g/t;break;default:$=g;}return l?$:O.a($)},m.daysInMonth=function(){return this.endOf(c).$D},m.$locale=function(){return D[this.$L]},m.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=S(t,e,!0);return r&&(n.$L=r),n},m.clone=function(){return O.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},M}(),_=b.prototype;return w.prototype=_,[["$ms",r],["$s",i],["$m",s],["$H",u],["$W",a],["$M",c],["$y",h],["$D",d]].forEach((function(t){_[t[1]]=function(e){return this.$g(e,t[0],t[1])};})),w.extend=function(t,e){return t.$i||(t(e,b,w),t.$i=!0),w},w.locale=S,w.isDayjs=p,w.unix=function(t){return w(1e3*t)},w.en=D[g],w.Ls=D,w.p={},w}));
|
|
2911
|
+
} (dayjs_min, dayjs_min.exports));
|
|
2912
|
+
|
|
2913
|
+
var dayjs_minExports = dayjs_min.exports;
|
|
2914
|
+
var dayjs = /*@__PURE__*/getDefaultExportFromCjs(dayjs_minExports);
|
|
2915
|
+
|
|
2916
|
+
var Menu = Dropdown.Menu,
|
|
2917
|
+
MenuItem = Dropdown.MenuItem;
|
|
2918
|
+
var ActionDropdown = withT(function (_ref) {
|
|
2919
|
+
var t = _ref.t,
|
|
2920
|
+
handleEdit = _ref.handleEdit,
|
|
2921
|
+
handleDelete = _ref.handleDelete;
|
|
2922
|
+
return /*#__PURE__*/React.createElement(Dropdown, {
|
|
2923
|
+
buttonStyle: "text",
|
|
2924
|
+
icon: MenuHorizontal,
|
|
2925
|
+
strategy: "fixed"
|
|
2926
|
+
}, /*#__PURE__*/React.createElement(Menu, null, /*#__PURE__*/React.createElement(MenuItem.Button, {
|
|
2927
|
+
onClick: handleEdit
|
|
2928
|
+
}, t("buttons.edit")), /*#__PURE__*/React.createElement(MenuItem.Button, {
|
|
2929
|
+
style: "danger",
|
|
2930
|
+
onClick: handleDelete
|
|
2931
|
+
}, t("buttons.delete"))));
|
|
2932
|
+
});
|
|
2933
|
+
|
|
2934
|
+
var isInPast = function isInPast(date) {
|
|
2935
|
+
return dayjs(date).isBefore(dayjs());
|
|
2936
|
+
};
|
|
2937
|
+
var partlyHideToken = function partlyHideToken(key) {
|
|
2938
|
+
return key.slice(-4).padStart(20, "*");
|
|
2939
|
+
};
|
|
2940
|
+
var formatExpiry = function formatExpiry(date) {
|
|
2941
|
+
return dayjs(date).diff(dayjs(), "day") <= 2 ? dateFormat.fromNow(date) : dateFormat.date(date);
|
|
2942
|
+
};
|
|
2943
|
+
var buildColumnData = function buildColumnData(_ref) {
|
|
2944
|
+
var _handleDelete = _ref.handleDelete,
|
|
2945
|
+
_handleEdit = _ref.handleEdit;
|
|
2946
|
+
return [{
|
|
2947
|
+
title: t$1("table.headers.label"),
|
|
2948
|
+
key: "label",
|
|
2949
|
+
dataIndex: "label",
|
|
2950
|
+
width: "20%"
|
|
2951
|
+
}, {
|
|
2952
|
+
title: t$1("table.headers.token"),
|
|
2953
|
+
key: "token",
|
|
2954
|
+
dataIndex: "token",
|
|
2955
|
+
width: "30%",
|
|
2956
|
+
render: function render(token) {
|
|
2957
|
+
return /*#__PURE__*/React.createElement("div", {
|
|
2958
|
+
className: "flex items-center justify-between gap-x-3"
|
|
2959
|
+
}, /*#__PURE__*/React.createElement(Typography, {
|
|
2960
|
+
style: "body2"
|
|
2961
|
+
}, partlyHideToken(token)), /*#__PURE__*/React.createElement(Button, {
|
|
2962
|
+
icon: Copy,
|
|
2963
|
+
iconsSize: 28,
|
|
2964
|
+
style: "text",
|
|
2965
|
+
tooltipProps: {
|
|
2966
|
+
content: t$1("tooltips.copyToClipboard", {
|
|
2967
|
+
token: token
|
|
2968
|
+
}),
|
|
2969
|
+
position: "top"
|
|
2970
|
+
},
|
|
2971
|
+
onClick: function onClick() {
|
|
2972
|
+
return copyToClipboard(token, {
|
|
2973
|
+
message: t$1("notifications.copiedToClipboard")
|
|
2974
|
+
});
|
|
2975
|
+
}
|
|
2976
|
+
}));
|
|
2977
|
+
}
|
|
2978
|
+
}, {
|
|
2979
|
+
title: t$1("table.headers.status"),
|
|
2980
|
+
key: "status",
|
|
2981
|
+
width: "15%",
|
|
2982
|
+
render: function render(_, _ref2) {
|
|
2983
|
+
var expiresAt = _ref2.expiresAt;
|
|
2984
|
+
return isPresent(expiresAt) && isInPast(expiresAt) ? /*#__PURE__*/React.createElement(Tag, {
|
|
2985
|
+
style: "warning"
|
|
2986
|
+
}, t$1("tags.expired")) : /*#__PURE__*/React.createElement(Tag, {
|
|
2987
|
+
style: "success"
|
|
2988
|
+
}, t$1("tags.active"));
|
|
2989
|
+
}
|
|
2990
|
+
}, {
|
|
2991
|
+
title: t$1("table.headers.expiresAt"),
|
|
2992
|
+
key: "expiresAt",
|
|
2993
|
+
dataIndex: "expiresAt",
|
|
2994
|
+
width: "15%",
|
|
2995
|
+
render: function render(expiresAt) {
|
|
2996
|
+
return isPresent(expiresAt) ? formatExpiry(expiresAt) : /*#__PURE__*/React.createElement(Typography, {
|
|
2997
|
+
style: "body2"
|
|
2998
|
+
}, t$1("common.never"));
|
|
2999
|
+
}
|
|
3000
|
+
}, {
|
|
3001
|
+
title: t$1("table.headers.createdAt"),
|
|
3002
|
+
key: "createdAt",
|
|
3003
|
+
dataIndex: "createdAt",
|
|
3004
|
+
width: "15%",
|
|
3005
|
+
render: function render(createdAt) {
|
|
3006
|
+
return isPresent(createdAt) ? dateFormat.dateTime(createdAt) : /*#__PURE__*/React.createElement(Typography, {
|
|
3007
|
+
style: "body2"
|
|
3008
|
+
}, t$1("common.never"));
|
|
3009
|
+
}
|
|
3010
|
+
}, {
|
|
3011
|
+
key: "opitons",
|
|
3012
|
+
render: function render(_, apiKey) {
|
|
3013
|
+
return /*#__PURE__*/React.createElement(ActionDropdown, {
|
|
3014
|
+
handleDelete: function handleDelete() {
|
|
3015
|
+
return _handleDelete(apiKey);
|
|
3016
|
+
},
|
|
3017
|
+
handleEdit: function handleEdit() {
|
|
3018
|
+
return _handleEdit(apiKey);
|
|
3019
|
+
}
|
|
3020
|
+
});
|
|
3021
|
+
},
|
|
3022
|
+
width: "40%"
|
|
3023
|
+
}];
|
|
3024
|
+
};
|
|
3025
|
+
var getStartOfTime = function getStartOfTime(time, unit) {
|
|
3026
|
+
return dayjs(time).startOf(unit);
|
|
3027
|
+
};
|
|
3028
|
+
|
|
3029
|
+
var DatePicker = function DatePicker(_ref) {
|
|
3030
|
+
var defaultValue = _ref.defaultValue,
|
|
3031
|
+
disabledDate = _ref.disabledDate,
|
|
3032
|
+
label = _ref.label,
|
|
3033
|
+
placeholder = _ref.placeholder,
|
|
3034
|
+
name = _ref.name,
|
|
3035
|
+
_ref$disabled = _ref.disabled,
|
|
3036
|
+
disabled = _ref$disabled === void 0 ? false : _ref$disabled;
|
|
3037
|
+
return /*#__PURE__*/React.createElement(Field, {
|
|
3038
|
+
name: name
|
|
3039
|
+
}, function (_ref2) {
|
|
3040
|
+
var _globalProps;
|
|
3041
|
+
var field = _ref2.field,
|
|
3042
|
+
meta = _ref2.meta,
|
|
3043
|
+
setFieldValue = _ref2.form.setFieldValue;
|
|
3044
|
+
return /*#__PURE__*/React.createElement(DatePicker$1, _extends({
|
|
3045
|
+
disabled: disabled,
|
|
3046
|
+
disabledDate: disabledDate,
|
|
3047
|
+
label: label,
|
|
3048
|
+
placeholder: placeholder,
|
|
3049
|
+
defaultValue: defaultValue,
|
|
3050
|
+
allowClear: false,
|
|
3051
|
+
className: "w-full",
|
|
3052
|
+
error: meta.touched && meta.error,
|
|
3053
|
+
format: (_globalProps = globalProps) === null || _globalProps === void 0 || (_globalProps = _globalProps.user) === null || _globalProps === void 0 ? void 0 : _globalProps.dateFormat,
|
|
3054
|
+
getPopupContainer: prop("parentNode"),
|
|
3055
|
+
size: "large"
|
|
3056
|
+
}, field, {
|
|
3057
|
+
onChange: function onChange(date) {
|
|
3058
|
+
setFieldValue(field.name, getStartOfTime(date, "day"));
|
|
3059
|
+
}
|
|
3060
|
+
}));
|
|
3061
|
+
});
|
|
3062
|
+
};
|
|
3063
|
+
|
|
3064
|
+
var INITIAL_VALUES = {
|
|
3065
|
+
expiresAt: null,
|
|
3066
|
+
label: "",
|
|
3067
|
+
hasNoExpiry: true
|
|
3068
|
+
};
|
|
3069
|
+
var NEXT_DAY = dayjs().add(1, "day").startOf("day");
|
|
3070
|
+
var VALIDATION_SCHEMA = yup.object({
|
|
3071
|
+
expiresAt: yup.date().when("hasNoExpiry", function (hasNoExpiry, field) {
|
|
3072
|
+
return hasNoExpiry ? field.nullable() : field.nullable().required(t$1("validations.required", {
|
|
3073
|
+
entity: t$1("fields.expiryDate")
|
|
3074
|
+
})).min(NEXT_DAY, t$1("validations.expiry", {
|
|
3075
|
+
date: dateFormat.date(NEXT_DAY)
|
|
3076
|
+
}));
|
|
3077
|
+
}),
|
|
3078
|
+
label: yup.string().required(t$1("validations.required", {
|
|
3079
|
+
entity: t$1("fields.label")
|
|
3080
|
+
}))
|
|
3081
|
+
});
|
|
3082
|
+
var DEFAULT_PAGE_SIZE = 15;
|
|
3083
|
+
|
|
3084
|
+
var Form = withT(function (_ref) {
|
|
3085
|
+
var t = _ref.t,
|
|
3086
|
+
_ref$initialValues = _ref.initialValues,
|
|
3087
|
+
initialValues = _ref$initialValues === void 0 ? INITIAL_VALUES : _ref$initialValues,
|
|
3088
|
+
isSubmitting = _ref.isSubmitting,
|
|
3089
|
+
onClose = _ref.onClose,
|
|
3090
|
+
onSubmit = _ref.onSubmit,
|
|
3091
|
+
initialFocusRef = _ref.initialFocusRef;
|
|
3092
|
+
return /*#__PURE__*/React.createElement(Form$1, {
|
|
3093
|
+
formikProps: {
|
|
3094
|
+
validationSchema: VALIDATION_SCHEMA,
|
|
3095
|
+
initialValues: initialValues,
|
|
3096
|
+
onSubmit: onSubmit
|
|
3097
|
+
}
|
|
3098
|
+
}, function (_ref2) {
|
|
3099
|
+
var setFieldValue = _ref2.setFieldValue,
|
|
3100
|
+
dirty = _ref2.dirty,
|
|
3101
|
+
_ref2$values = _ref2.values,
|
|
3102
|
+
_ref2$values2 = _ref2$values === void 0 ? {} : _ref2$values,
|
|
3103
|
+
hasNoExpiry = _ref2$values2.hasNoExpiry,
|
|
3104
|
+
expiresAt = _ref2$values2.expiresAt;
|
|
3105
|
+
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Pane.Body, null, /*#__PURE__*/React.createElement("div", {
|
|
3106
|
+
className: "w-full space-y-4"
|
|
3107
|
+
}, /*#__PURE__*/React.createElement(Input, {
|
|
3108
|
+
autoFocus: true,
|
|
3109
|
+
label: t("fields.label"),
|
|
3110
|
+
name: "label",
|
|
3111
|
+
placeholder: t("placeholders.label"),
|
|
3112
|
+
ref: initialFocusRef,
|
|
3113
|
+
size: "large"
|
|
3114
|
+
}), /*#__PURE__*/React.createElement("div", {
|
|
3115
|
+
className: "space-y-2"
|
|
3116
|
+
}, !hasNoExpiry && /*#__PURE__*/React.createElement(DatePicker, {
|
|
3117
|
+
defaultValue: expiresAt,
|
|
3118
|
+
disabledDate: function disabledDate(date) {
|
|
3119
|
+
return date < NEXT_DAY;
|
|
3120
|
+
},
|
|
3121
|
+
label: t("fields.expiryDate"),
|
|
3122
|
+
name: "expiresAt",
|
|
3123
|
+
placeholder: t("placeholders.selectExpiryDate")
|
|
3124
|
+
}), /*#__PURE__*/React.createElement(Checkbox, {
|
|
3125
|
+
checked: hasNoExpiry,
|
|
3126
|
+
label: t("fields.neverExpire"),
|
|
3127
|
+
name: "hasNoExpiry",
|
|
3128
|
+
onChange: function onChange() {
|
|
3129
|
+
setFieldValue("expiresAt", null);
|
|
3130
|
+
setFieldValue("hasNoExpiry", !hasNoExpiry);
|
|
3131
|
+
}
|
|
3132
|
+
})))), /*#__PURE__*/React.createElement(Pane.Footer, null, /*#__PURE__*/React.createElement(ActionBlock, {
|
|
3133
|
+
className: "space-x-2",
|
|
3134
|
+
cancelButtonProps: {
|
|
3135
|
+
onClick: onClose,
|
|
3136
|
+
label: t("buttons.cancel")
|
|
3137
|
+
},
|
|
3138
|
+
submitButtonProps: {
|
|
3139
|
+
disabled: isSubmitting || !dirty,
|
|
3140
|
+
loading: isSubmitting,
|
|
3141
|
+
label: t("buttons.submit")
|
|
3142
|
+
}
|
|
3143
|
+
})));
|
|
3144
|
+
});
|
|
3145
|
+
});
|
|
3146
|
+
|
|
3147
|
+
var Create = withT(function (_ref) {
|
|
3148
|
+
var t = _ref.t,
|
|
3149
|
+
onClose = _ref.onClose,
|
|
3150
|
+
isOpen = _ref.isOpen;
|
|
3151
|
+
var initialFocusRef = useRef(null);
|
|
3152
|
+
var _useCreateApiKey = useCreateApiKey(onClose),
|
|
3153
|
+
createApiKey = _useCreateApiKey.mutate,
|
|
3154
|
+
isCreating = _useCreateApiKey.isLoading;
|
|
3155
|
+
return /*#__PURE__*/React.createElement(Pane, {
|
|
3156
|
+
initialFocusRef: initialFocusRef,
|
|
3157
|
+
onClose: onClose,
|
|
3158
|
+
isOpen: isOpen
|
|
3159
|
+
}, /*#__PURE__*/React.createElement(Pane.Header, null, /*#__PURE__*/React.createElement(Typography, {
|
|
3160
|
+
style: "h2"
|
|
3161
|
+
}, t("headers.createApiKey"))), /*#__PURE__*/React.createElement(Form, {
|
|
3162
|
+
initialFocusRef: initialFocusRef,
|
|
3163
|
+
onClose: onClose,
|
|
3164
|
+
isSubmitting: isCreating,
|
|
3165
|
+
onSubmit: createApiKey
|
|
3166
|
+
}));
|
|
3167
|
+
});
|
|
3168
|
+
|
|
3169
|
+
function _typeof(obj) {
|
|
3170
|
+
"@babel/helpers - typeof";
|
|
3171
|
+
|
|
3172
|
+
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
|
|
3173
|
+
return typeof obj;
|
|
3174
|
+
} : function (obj) {
|
|
3175
|
+
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
|
|
3176
|
+
}, _typeof(obj);
|
|
3177
|
+
}
|
|
3178
|
+
|
|
3179
|
+
function _toPrimitive(input, hint) {
|
|
3180
|
+
if (_typeof(input) !== "object" || input === null) return input;
|
|
3181
|
+
var prim = input[Symbol.toPrimitive];
|
|
3182
|
+
if (prim !== undefined) {
|
|
3183
|
+
var res = prim.call(input, hint || "default");
|
|
3184
|
+
if (_typeof(res) !== "object") return res;
|
|
3185
|
+
throw new TypeError("@@toPrimitive must return a primitive value.");
|
|
3186
|
+
}
|
|
3187
|
+
return (hint === "string" ? String : Number)(input);
|
|
3188
|
+
}
|
|
3189
|
+
|
|
3190
|
+
function _toPropertyKey(arg) {
|
|
3191
|
+
var key = _toPrimitive(arg, "string");
|
|
3192
|
+
return _typeof(key) === "symbol" ? key : String(key);
|
|
3193
|
+
}
|
|
3194
|
+
|
|
3195
|
+
function _defineProperty(obj, key, value) {
|
|
3196
|
+
key = _toPropertyKey(key);
|
|
3197
|
+
if (key in obj) {
|
|
3198
|
+
Object.defineProperty(obj, key, {
|
|
3199
|
+
value: value,
|
|
3200
|
+
enumerable: true,
|
|
3201
|
+
configurable: true,
|
|
3202
|
+
writable: true
|
|
3203
|
+
});
|
|
3204
|
+
} else {
|
|
3205
|
+
obj[key] = value;
|
|
3206
|
+
}
|
|
3207
|
+
return obj;
|
|
3208
|
+
}
|
|
3209
|
+
|
|
3210
|
+
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; }
|
|
3211
|
+
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; }
|
|
3212
|
+
var Update = withT(function (_ref) {
|
|
3213
|
+
var t = _ref.t,
|
|
3214
|
+
onClose = _ref.onClose,
|
|
3215
|
+
apiKey = _ref.apiKey;
|
|
3216
|
+
var initialFocusRef = useRef(null);
|
|
3217
|
+
var _useUpdateApiKey = useUpdateApiKey(onClose),
|
|
3218
|
+
updateApiKey = _useUpdateApiKey.mutate,
|
|
3219
|
+
isUpdating = _useUpdateApiKey.isLoading;
|
|
3220
|
+
var handleUpdate = function handleUpdate(values) {
|
|
3221
|
+
updateApiKey({
|
|
3222
|
+
id: apiKey.id,
|
|
3223
|
+
payload: values
|
|
3224
|
+
});
|
|
3225
|
+
};
|
|
3226
|
+
var initialValues = _objectSpread(_objectSpread({}, apiKey), {}, {
|
|
3227
|
+
hasNoExpiry: isNotPresent(apiKey.expiresAt)
|
|
3228
|
+
});
|
|
3229
|
+
return /*#__PURE__*/React.createElement(Pane, {
|
|
3230
|
+
initialFocusRef: initialFocusRef,
|
|
3231
|
+
onClose: onClose,
|
|
3232
|
+
isOpen: isNotEmpty(apiKey)
|
|
3233
|
+
}, /*#__PURE__*/React.createElement(Pane.Header, null, /*#__PURE__*/React.createElement(Typography, {
|
|
3234
|
+
style: "h2"
|
|
3235
|
+
}, t("headers.updateApiKey"))), /*#__PURE__*/React.createElement(Form, {
|
|
3236
|
+
initialValues: initialValues,
|
|
3237
|
+
onClose: onClose,
|
|
3238
|
+
initialFocusRef: initialFocusRef,
|
|
3239
|
+
isSubmitting: isUpdating,
|
|
3240
|
+
onSubmit: handleUpdate
|
|
3241
|
+
}));
|
|
3242
|
+
});
|
|
3243
|
+
|
|
3244
|
+
var getPageFromSearchParams = function getPageFromSearchParams() {
|
|
3245
|
+
var _getQueryParams = getQueryParams(),
|
|
3246
|
+
page = _getQueryParams.page;
|
|
3247
|
+
return parseInt(page) || DEFAULT_PAGE_INDEX;
|
|
3248
|
+
};
|
|
3249
|
+
var setPageSearchParam = function setPageSearchParam(_ref) {
|
|
3250
|
+
var page = _ref.page,
|
|
3251
|
+
history = _ref.history;
|
|
3252
|
+
var searchParams = page !== DEFAULT_PAGE_INDEX && buildUrl("", {
|
|
3253
|
+
page: page
|
|
3254
|
+
});
|
|
3255
|
+
history.push({
|
|
3256
|
+
search: searchParams
|
|
3257
|
+
});
|
|
3258
|
+
};
|
|
3259
|
+
|
|
3260
|
+
var usePagination = function usePagination(_ref) {
|
|
3261
|
+
var searchTerm = _ref.searchTerm;
|
|
3262
|
+
var _useState = useState(getPageFromSearchParams),
|
|
3263
|
+
_useState2 = _slicedToArray(_useState, 2),
|
|
3264
|
+
currentPage = _useState2[0],
|
|
3265
|
+
setCurrentPage = _useState2[1];
|
|
3266
|
+
var history = useHistory();
|
|
3267
|
+
useEffect(function () {
|
|
3268
|
+
handlePageChange(getPageFromSearchParams());
|
|
3269
|
+
}, []);
|
|
3270
|
+
useEffect(function () {
|
|
3271
|
+
if (isNotEmpty(searchTerm) && currentPage !== DEFAULT_PAGE_INDEX) {
|
|
3272
|
+
handlePageChange(DEFAULT_PAGE_INDEX);
|
|
3273
|
+
}
|
|
3274
|
+
}, [searchTerm]);
|
|
3275
|
+
var handlePageChange = function handlePageChange(page) {
|
|
3276
|
+
setCurrentPage(page);
|
|
3277
|
+
setPageSearchParam({
|
|
3278
|
+
page: page,
|
|
3279
|
+
history: history
|
|
3280
|
+
});
|
|
3281
|
+
};
|
|
3282
|
+
var onFetchSuccess = function onFetchSuccess(_ref2) {
|
|
3283
|
+
var totalCount = _ref2.totalCount,
|
|
3284
|
+
apiKeys = _ref2.apiKeys;
|
|
3285
|
+
if (totalCount !== 0 && isEmpty(apiKeys)) {
|
|
3286
|
+
handlePageChange(DEFAULT_PAGE_INDEX);
|
|
3287
|
+
}
|
|
3288
|
+
};
|
|
3289
|
+
return {
|
|
3290
|
+
currentPage: currentPage,
|
|
3291
|
+
handlePageChange: handlePageChange,
|
|
3292
|
+
onFetchSuccess: onFetchSuccess
|
|
3293
|
+
};
|
|
3294
|
+
};
|
|
3295
|
+
|
|
3296
|
+
var Table = withT(function (_ref) {
|
|
3297
|
+
var t = _ref.t,
|
|
3298
|
+
handleDelete = _ref.handleDelete,
|
|
3299
|
+
handleEdit = _ref.handleEdit,
|
|
3300
|
+
searchTerm = _ref.searchTerm;
|
|
3301
|
+
var debouncedSearchTerm = useDebounce(searchTerm);
|
|
3302
|
+
var _usePagination = usePagination({
|
|
3303
|
+
searchTerm: debouncedSearchTerm
|
|
3304
|
+
}),
|
|
3305
|
+
currentPage = _usePagination.currentPage,
|
|
3306
|
+
handlePageChange = _usePagination.handlePageChange,
|
|
3307
|
+
onFetchSuccess = _usePagination.onFetchSuccess;
|
|
3308
|
+
var queryParams = {
|
|
3309
|
+
searchTerm: debouncedSearchTerm,
|
|
3310
|
+
page: currentPage,
|
|
3311
|
+
limit: DEFAULT_PAGE_SIZE
|
|
3312
|
+
};
|
|
3313
|
+
var _useFetchApiKeys = useFetchApiKeys({
|
|
3314
|
+
params: queryParams,
|
|
3315
|
+
options: {
|
|
3316
|
+
onSuccess: onFetchSuccess
|
|
3317
|
+
}
|
|
3318
|
+
}),
|
|
3319
|
+
_useFetchApiKeys$data = _useFetchApiKeys.data,
|
|
3320
|
+
_useFetchApiKeys$data2 = _useFetchApiKeys$data === void 0 ? {} : _useFetchApiKeys$data,
|
|
3321
|
+
_useFetchApiKeys$data3 = _useFetchApiKeys$data2.apiKeys,
|
|
3322
|
+
apiKeys = _useFetchApiKeys$data3 === void 0 ? [] : _useFetchApiKeys$data3,
|
|
3323
|
+
totalCount = _useFetchApiKeys$data2.totalCount,
|
|
3324
|
+
isLoading = _useFetchApiKeys.isLoading,
|
|
3325
|
+
isFetching = _useFetchApiKeys.isFetching;
|
|
3326
|
+
if (isLoading) return /*#__PURE__*/React.createElement(PageLoader, null);
|
|
3327
|
+
if (isEmpty(apiKeys)) {
|
|
3328
|
+
return /*#__PURE__*/React.createElement("div", {
|
|
3329
|
+
className: "flex h-full w-full items-center justify-center"
|
|
3330
|
+
}, /*#__PURE__*/React.createElement(NoData, {
|
|
3331
|
+
className: "w-full",
|
|
3332
|
+
title: t("noData.title")
|
|
3333
|
+
}), ";");
|
|
3334
|
+
}
|
|
3335
|
+
return /*#__PURE__*/React.createElement(TableWrapper, {
|
|
3336
|
+
hasPagination: totalCount > DEFAULT_PAGE_SIZE
|
|
3337
|
+
}, /*#__PURE__*/React.createElement(Table$1, {
|
|
3338
|
+
fixedHeight: true,
|
|
3339
|
+
columnData: buildColumnData({
|
|
3340
|
+
handleDelete: handleDelete,
|
|
3341
|
+
handleEdit: handleEdit
|
|
3342
|
+
}),
|
|
3343
|
+
currentPageNumber: currentPage,
|
|
3344
|
+
defaultPageSize: DEFAULT_PAGE_SIZE,
|
|
3345
|
+
handlePageChange: handlePageChange,
|
|
3346
|
+
loading: isFetching,
|
|
3347
|
+
rowData: apiKeys,
|
|
3348
|
+
totalCount: totalCount
|
|
3349
|
+
}));
|
|
3350
|
+
});
|
|
3351
|
+
|
|
3352
|
+
var ApiKeys = withT(function (_ref) {
|
|
3353
|
+
var t = _ref.t,
|
|
3354
|
+
_ref$breadcrumbs = _ref.breadcrumbs,
|
|
3355
|
+
breadcrumbs = _ref$breadcrumbs === void 0 ? [] : _ref$breadcrumbs;
|
|
3356
|
+
var _useState = useState(""),
|
|
3357
|
+
_useState2 = _slicedToArray(_useState, 2),
|
|
3358
|
+
searchTerm = _useState2[0],
|
|
3359
|
+
setSearchTerm = _useState2[1];
|
|
3360
|
+
var _useState3 = useState({}),
|
|
3361
|
+
_useState4 = _slicedToArray(_useState3, 2),
|
|
3362
|
+
apiKeyToBeDeleted = _useState4[0],
|
|
3363
|
+
setApiKeyToBeDeleted = _useState4[1];
|
|
3364
|
+
var _useState5 = useState({}),
|
|
3365
|
+
_useState6 = _slicedToArray(_useState5, 2),
|
|
3366
|
+
apiKeyToBeEdited = _useState6[0],
|
|
3367
|
+
setApiKeyToBeEdited = _useState6[1];
|
|
3368
|
+
var _useState7 = useState(false),
|
|
3369
|
+
_useState8 = _slicedToArray(_useState7, 2),
|
|
3370
|
+
isCreatePaneOpen = _useState8[0],
|
|
3371
|
+
setIsCreatePaneOpen = _useState8[1];
|
|
3372
|
+
var _useDeleteApiKey = useDeleteApiKey(function () {
|
|
3373
|
+
return setApiKeyToBeDeleted({});
|
|
3374
|
+
}),
|
|
3375
|
+
deleteApiKey = _useDeleteApiKey.mutate,
|
|
3376
|
+
isDeleting = _useDeleteApiKey.isLoading;
|
|
3377
|
+
return /*#__PURE__*/React.createElement(Container, null, /*#__PURE__*/React.createElement(Header, {
|
|
3378
|
+
breadcrumbs: breadcrumbs,
|
|
3379
|
+
title: t("common.apiKey", PLURAL),
|
|
3380
|
+
actionBlock: /*#__PURE__*/React.createElement(Button, {
|
|
3381
|
+
label: t("buttons.addApiKey"),
|
|
3382
|
+
onClick: function onClick() {
|
|
3383
|
+
return setIsCreatePaneOpen(true);
|
|
3384
|
+
}
|
|
3385
|
+
}),
|
|
3386
|
+
searchProps: {
|
|
3387
|
+
value: searchTerm,
|
|
3388
|
+
onChange: function onChange(_ref2) {
|
|
3389
|
+
var value = _ref2.target.value;
|
|
3390
|
+
return setSearchTerm(value);
|
|
3391
|
+
},
|
|
3392
|
+
placeholder: t("placeholders.search")
|
|
3393
|
+
}
|
|
3394
|
+
}), /*#__PURE__*/React.createElement(Table, {
|
|
3395
|
+
handleDelete: setApiKeyToBeDeleted,
|
|
3396
|
+
handleEdit: setApiKeyToBeEdited,
|
|
3397
|
+
searchTerm: searchTerm
|
|
3398
|
+
}), /*#__PURE__*/React.createElement(Alert, {
|
|
3399
|
+
isOpen: isNotEmpty(apiKeyToBeDeleted),
|
|
3400
|
+
isSubmitting: isDeleting,
|
|
3401
|
+
submitButtonLabel: t("buttons.delete"),
|
|
3402
|
+
title: t("alert.titles.deleteApiKey"),
|
|
3403
|
+
message: /*#__PURE__*/React.createElement(Trans, {
|
|
3404
|
+
components: {
|
|
3405
|
+
bold: /*#__PURE__*/React.createElement("strong", null)
|
|
3406
|
+
},
|
|
3407
|
+
i18nKey: "alert.descriptions.deleteApiKey",
|
|
3408
|
+
values: {
|
|
3409
|
+
name: apiKeyToBeDeleted.label
|
|
3410
|
+
}
|
|
3411
|
+
}),
|
|
3412
|
+
onClose: function onClose() {
|
|
3413
|
+
return setApiKeyToBeDeleted({});
|
|
3414
|
+
},
|
|
3415
|
+
onSubmit: function onSubmit() {
|
|
3416
|
+
return deleteApiKey(apiKeyToBeDeleted.id);
|
|
3417
|
+
}
|
|
3418
|
+
}), /*#__PURE__*/React.createElement(Create, {
|
|
3419
|
+
isOpen: isCreatePaneOpen,
|
|
3420
|
+
onClose: function onClose() {
|
|
3421
|
+
return setIsCreatePaneOpen(false);
|
|
3422
|
+
}
|
|
3423
|
+
}), /*#__PURE__*/React.createElement(Update, {
|
|
3424
|
+
apiKey: apiKeyToBeEdited,
|
|
3425
|
+
onClose: function onClose() {
|
|
3426
|
+
return setApiKeyToBeEdited({});
|
|
3427
|
+
}
|
|
3428
|
+
}));
|
|
3429
|
+
});
|
|
3430
|
+
|
|
3431
|
+
export { ApiKeys };
|
|
3432
|
+
//# sourceMappingURL=index.js.map
|