unicode-input-toolconverter 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/.babelrc.json +3 -0
  2. package/.editorconfig +16 -0
  3. package/.nojekyll +0 -0
  4. package/.nyc_output/out.json +173804 -0
  5. package/.nyc_output/processinfo/index.json +1 -0
  6. package/CHANGES.md +11 -0
  7. package/COPYING.LESSER.txt +180 -0
  8. package/COPYING.txt +687 -0
  9. package/README.md +65 -0
  10. package/_locales/en-US/messages.json +3126 -0
  11. package/_locales/hu-HU/messages.json +3126 -0
  12. package/_locales/pt-BR/messages.json +3126 -0
  13. package/_locales/sv-SE/messages.json +3126 -0
  14. package/babel.config.json +5 -0
  15. package/browser_action/characterSelection.js +91 -0
  16. package/browser_action/charrefConverters.js +389 -0
  17. package/browser_action/chartBuild.js +155 -0
  18. package/browser_action/encodingBehaviors.js +72 -0
  19. package/browser_action/encodings.js +97 -0
  20. package/browser_action/entities.js +12 -0
  21. package/browser_action/entityBehaviors.js +96 -0
  22. package/browser_action/index-es.html +15 -0
  23. package/browser_action/index-instrumented.html +16 -0
  24. package/browser_action/index-pages.html +16 -0
  25. package/browser_action/index.html +16 -0
  26. package/browser_action/index.iife.min.js +2 -0
  27. package/browser_action/index.iife.min.js.map +1 -0
  28. package/browser_action/index.instrumented.iife.min.js +2 -0
  29. package/browser_action/index.instrumented.iife.min.js.map +1 -0
  30. package/browser_action/index.js +95 -0
  31. package/browser_action/preferences/prefDefaults.js +52 -0
  32. package/browser_action/service-worker/sw-activateCallback.js +53 -0
  33. package/browser_action/service-worker/sw-locales.json +6 -0
  34. package/browser_action/service-worker/sw-resources.json +73 -0
  35. package/browser_action/service-worker/sw-unicode-data.json +3 -0
  36. package/browser_action/styles/unicode-dialog.css +391 -0
  37. package/browser_action/templateUtils/elements.js +12 -0
  38. package/browser_action/templateUtils/fill.js +3 -0
  39. package/browser_action/templateUtils/validation.js +6 -0
  40. package/browser_action/templates/chartBuild.js +185 -0
  41. package/browser_action/templates/index.js +1304 -0
  42. package/browser_action/templatesElementCustomization/widgets.js +56 -0
  43. package/browser_action/unicode/UnicodeConverter.js +793 -0
  44. package/browser_action/unicode/charrefunicodeDb.js +258 -0
  45. package/browser_action/unicode/getScriptInfoForCodePoint.js +646 -0
  46. package/browser_action/unicode/hangul.js +253 -0
  47. package/browser_action/unicode/lastScriptNames.json +5 -0
  48. package/browser_action/unicode/parseUnihanFromTextFileStrings.js +56 -0
  49. package/browser_action/unicode/unicodeFieldInfo.js +120 -0
  50. package/browser_action/unicode/unicodeScripts.js +4912 -0
  51. package/browser_action/unicode/unihan.js +129 -0
  52. package/browser_action/unicode/unihanDbPopulate.js +26 -0
  53. package/browser_action/unicodecharref.js +1480 -0
  54. package/browser_action/utils/DOMUtils.js +122 -0
  55. package/browser_action/utils/FetchUtils.js +19 -0
  56. package/browser_action/utils/TextUtils.js +28 -0
  57. package/browser_action/utils/TypedArrayUtils.js +21 -0
  58. package/browser_action/utils/semicolonSeparatedToArray.js +12 -0
  59. package/browser_action/utils/setupServiceWorker.js +193 -0
  60. package/cypress.config.js +21 -0
  61. package/download/entities/copyright-software-20021231.html +70 -0
  62. package/download/entities/html5-uppercase.ent +54 -0
  63. package/download/entities/htmlmathml-f.ent +2164 -0
  64. package/download/entities/isoamsa.ent +201 -0
  65. package/download/entities/isoamsb.ent +177 -0
  66. package/download/entities/isoamsc.ent +77 -0
  67. package/download/entities/isoamsn.ent +148 -0
  68. package/download/entities/isoamso.ent +107 -0
  69. package/download/entities/isoamsr.ent +238 -0
  70. package/download/entities/isobox.ent +95 -0
  71. package/download/entities/isocyr1.ent +122 -0
  72. package/download/entities/isocyr2.ent +81 -0
  73. package/download/entities/isodia.ent +69 -0
  74. package/download/entities/isogrk1.ent +104 -0
  75. package/download/entities/isogrk2.ent +75 -0
  76. package/download/entities/isogrk3.ent +98 -0
  77. package/download/entities/isogrk4.ent +98 -0
  78. package/download/entities/isolat1.ent +117 -0
  79. package/download/entities/isolat2.ent +176 -0
  80. package/download/entities/isomfrk.ent +107 -0
  81. package/download/entities/isomopf.ent +81 -0
  82. package/download/entities/isomscr.ent +107 -0
  83. package/download/entities/isonum.ent +131 -0
  84. package/download/entities/isopub.ent +140 -0
  85. package/download/entities/isotech.ent +216 -0
  86. package/download/entities/mmlalias.ent +598 -0
  87. package/download/entities/mmlextra.ent +154 -0
  88. package/download/entities/predefined.ent +52 -0
  89. package/download/entities/w3centities-f.ent +2276 -0
  90. package/download/entities/xhtml1-lat1.ent +143 -0
  91. package/download/entities/xhtml1-special.ent +78 -0
  92. package/download/entities/xhtml1-symbol.ent +171 -0
  93. package/eslint.config.js +66 -0
  94. package/icons/openWindow16.png +0 -0
  95. package/icons/openWindow24.png +0 -0
  96. package/lgtm.yml +5 -0
  97. package/lib/background.html +11 -0
  98. package/lib/background.js +13 -0
  99. package/lib/overlay.css +6 -0
  100. package/manifest.json +37 -0
  101. package/package.json +121 -0
  102. package/polyfills/browser-polyfill.min.js +8 -0
  103. package/polyfills/browser-polyfill.min.js.map +1 -0
  104. package/server.js +61 -0
  105. package/sw.js +259 -0
  106. package/tools/entities-import.js +62 -0
  107. package/tools/findEsResources.js +30 -0
  108. package/tools/list-locales.js +17 -0
  109. package/tools/parseUnicodeCharts.js +428 -0
  110. package/tools/ucd-import.js +24 -0
  111. package/tools/unicode-charts.html +596 -0
  112. package/tools/unihan-import.js +72 -0
  113. package/unicode_copyright.txt +46 -0
  114. package/vendor/camelcase/index.js +110 -0
  115. package/vendor/fflate/esm/browser.js +2665 -0
  116. package/vendor/intl-dom/dist/index.esm.js +2962 -0
  117. package/vendor/jamilih/dist/jml-es.js +2359 -0
  118. package/vendor/jquery/dist/jquery.js +10716 -0
  119. package/vendor/json-6/dist/index.mjs +1783 -0
  120. package/vendor/miller-columns/dist/index-es.min.js +1 -0
  121. package/vendor/miller-columns/miller-columns.css +75 -0
  122. package/vendor/simple-prefs/dist/index.esm.js +286 -0
  123. package/web-ext-config.cjs +13 -0
@@ -0,0 +1,2962 @@
1
+ function _iterableToArrayLimit(arr, i) {
2
+ var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
3
+ if (null != _i) {
4
+ var _s,
5
+ _e,
6
+ _x,
7
+ _r,
8
+ _arr = [],
9
+ _n = !0,
10
+ _d = !1;
11
+ try {
12
+ if (_x = (_i = _i.call(arr)).next, 0 === i) {
13
+ if (Object(_i) !== _i) return;
14
+ _n = !1;
15
+ } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
16
+ } catch (err) {
17
+ _d = !0, _e = err;
18
+ } finally {
19
+ try {
20
+ if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
21
+ } finally {
22
+ if (_d) throw _e;
23
+ }
24
+ }
25
+ return _arr;
26
+ }
27
+ }
28
+ function ownKeys(object, enumerableOnly) {
29
+ var keys = Object.keys(object);
30
+ if (Object.getOwnPropertySymbols) {
31
+ var symbols = Object.getOwnPropertySymbols(object);
32
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
33
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
34
+ })), keys.push.apply(keys, symbols);
35
+ }
36
+ return keys;
37
+ }
38
+ function _objectSpread2(target) {
39
+ for (var i = 1; i < arguments.length; i++) {
40
+ var source = null != arguments[i] ? arguments[i] : {};
41
+ i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
42
+ _defineProperty(target, key, source[key]);
43
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
44
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
45
+ });
46
+ }
47
+ return target;
48
+ }
49
+ function _typeof(obj) {
50
+ "@babel/helpers - typeof";
51
+
52
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
53
+ return typeof obj;
54
+ } : function (obj) {
55
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
56
+ }, _typeof(obj);
57
+ }
58
+ function _wrapRegExp() {
59
+ _wrapRegExp = function (re, groups) {
60
+ return new BabelRegExp(re, void 0, groups);
61
+ };
62
+ var _super = RegExp.prototype,
63
+ _groups = new WeakMap();
64
+ function BabelRegExp(re, flags, groups) {
65
+ var _this = new RegExp(re, flags);
66
+ return _groups.set(_this, groups || _groups.get(re)), _setPrototypeOf(_this, BabelRegExp.prototype);
67
+ }
68
+ function buildGroups(result, re) {
69
+ var g = _groups.get(re);
70
+ return Object.keys(g).reduce(function (groups, name) {
71
+ var i = g[name];
72
+ if ("number" == typeof i) groups[name] = result[i];else {
73
+ for (var k = 0; void 0 === result[i[k]] && k + 1 < i.length;) k++;
74
+ groups[name] = result[i[k]];
75
+ }
76
+ return groups;
77
+ }, Object.create(null));
78
+ }
79
+ return _inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) {
80
+ var result = _super.exec.call(this, str);
81
+ if (result) {
82
+ result.groups = buildGroups(result, this);
83
+ var indices = result.indices;
84
+ indices && (indices.groups = buildGroups(indices, this));
85
+ }
86
+ return result;
87
+ }, BabelRegExp.prototype[Symbol.replace] = function (str, substitution) {
88
+ if ("string" == typeof substitution) {
89
+ var groups = _groups.get(this);
90
+ return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) {
91
+ var group = groups[name];
92
+ return "$" + (Array.isArray(group) ? group.join("$") : group);
93
+ }));
94
+ }
95
+ if ("function" == typeof substitution) {
96
+ var _this = this;
97
+ return _super[Symbol.replace].call(this, str, function () {
98
+ var args = arguments;
99
+ return "object" != typeof args[args.length - 1] && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args);
100
+ });
101
+ }
102
+ return _super[Symbol.replace].call(this, str, substitution);
103
+ }, _wrapRegExp.apply(this, arguments);
104
+ }
105
+ function _classCallCheck(instance, Constructor) {
106
+ if (!(instance instanceof Constructor)) {
107
+ throw new TypeError("Cannot call a class as a function");
108
+ }
109
+ }
110
+ function _defineProperties(target, props) {
111
+ for (var i = 0; i < props.length; i++) {
112
+ var descriptor = props[i];
113
+ descriptor.enumerable = descriptor.enumerable || false;
114
+ descriptor.configurable = true;
115
+ if ("value" in descriptor) descriptor.writable = true;
116
+ Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
117
+ }
118
+ }
119
+ function _createClass(Constructor, protoProps, staticProps) {
120
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
121
+ if (staticProps) _defineProperties(Constructor, staticProps);
122
+ Object.defineProperty(Constructor, "prototype", {
123
+ writable: false
124
+ });
125
+ return Constructor;
126
+ }
127
+ function _defineProperty(obj, key, value) {
128
+ key = _toPropertyKey(key);
129
+ if (key in obj) {
130
+ Object.defineProperty(obj, key, {
131
+ value: value,
132
+ enumerable: true,
133
+ configurable: true,
134
+ writable: true
135
+ });
136
+ } else {
137
+ obj[key] = value;
138
+ }
139
+ return obj;
140
+ }
141
+ function _inherits(subClass, superClass) {
142
+ if (typeof superClass !== "function" && superClass !== null) {
143
+ throw new TypeError("Super expression must either be null or a function");
144
+ }
145
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
146
+ constructor: {
147
+ value: subClass,
148
+ writable: true,
149
+ configurable: true
150
+ }
151
+ });
152
+ Object.defineProperty(subClass, "prototype", {
153
+ writable: false
154
+ });
155
+ if (superClass) _setPrototypeOf(subClass, superClass);
156
+ }
157
+ function _getPrototypeOf(o) {
158
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
159
+ return o.__proto__ || Object.getPrototypeOf(o);
160
+ };
161
+ return _getPrototypeOf(o);
162
+ }
163
+ function _setPrototypeOf(o, p) {
164
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
165
+ o.__proto__ = p;
166
+ return o;
167
+ };
168
+ return _setPrototypeOf(o, p);
169
+ }
170
+ function _isNativeReflectConstruct() {
171
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
172
+ if (Reflect.construct.sham) return false;
173
+ if (typeof Proxy === "function") return true;
174
+ try {
175
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
176
+ return true;
177
+ } catch (e) {
178
+ return false;
179
+ }
180
+ }
181
+ function _assertThisInitialized(self) {
182
+ if (self === void 0) {
183
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
184
+ }
185
+ return self;
186
+ }
187
+ function _possibleConstructorReturn(self, call) {
188
+ if (call && (typeof call === "object" || typeof call === "function")) {
189
+ return call;
190
+ } else if (call !== void 0) {
191
+ throw new TypeError("Derived constructors may only return object or undefined");
192
+ }
193
+ return _assertThisInitialized(self);
194
+ }
195
+ function _createSuper(Derived) {
196
+ var hasNativeReflectConstruct = _isNativeReflectConstruct();
197
+ return function _createSuperInternal() {
198
+ var Super = _getPrototypeOf(Derived),
199
+ result;
200
+ if (hasNativeReflectConstruct) {
201
+ var NewTarget = _getPrototypeOf(this).constructor;
202
+ result = Reflect.construct(Super, arguments, NewTarget);
203
+ } else {
204
+ result = Super.apply(this, arguments);
205
+ }
206
+ return _possibleConstructorReturn(this, result);
207
+ };
208
+ }
209
+ function _slicedToArray(arr, i) {
210
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
211
+ }
212
+ function _toConsumableArray(arr) {
213
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
214
+ }
215
+ function _arrayWithoutHoles(arr) {
216
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
217
+ }
218
+ function _arrayWithHoles(arr) {
219
+ if (Array.isArray(arr)) return arr;
220
+ }
221
+ function _iterableToArray(iter) {
222
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
223
+ }
224
+ function _unsupportedIterableToArray(o, minLen) {
225
+ if (!o) return;
226
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
227
+ var n = Object.prototype.toString.call(o).slice(8, -1);
228
+ if (n === "Object" && o.constructor) n = o.constructor.name;
229
+ if (n === "Map" || n === "Set") return Array.from(o);
230
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
231
+ }
232
+ function _arrayLikeToArray(arr, len) {
233
+ if (len == null || len > arr.length) len = arr.length;
234
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
235
+ return arr2;
236
+ }
237
+ function _nonIterableSpread() {
238
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
239
+ }
240
+ function _nonIterableRest() {
241
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
242
+ }
243
+ function _toPrimitive(input, hint) {
244
+ if (typeof input !== "object" || input === null) return input;
245
+ var prim = input[Symbol.toPrimitive];
246
+ if (prim !== undefined) {
247
+ var res = prim.call(input, hint || "default");
248
+ if (typeof res !== "object") return res;
249
+ throw new TypeError("@@toPrimitive must return a primitive value.");
250
+ }
251
+ return (hint === "string" ? String : Number)(input);
252
+ }
253
+ function _toPropertyKey(arg) {
254
+ var key = _toPrimitive(arg, "string");
255
+ return typeof key === "symbol" ? key : String(key);
256
+ }
257
+
258
+ // We want it to work in the browser, so commenting out
259
+ // import jsonExtra from 'json5';
260
+ // import jsonExtra from 'json-6';
261
+
262
+ /**
263
+ * @typedef {any} JSON6
264
+ */
265
+
266
+ // @ts-expect-error Need typing for JSON6
267
+ var _jsonExtra = globalThis.jsonExtra;
268
+
269
+ /**
270
+ * @param {JSON6} __jsonExtra
271
+ */
272
+ var setJSONExtra = function setJSONExtra(__jsonExtra) {
273
+ _jsonExtra = __jsonExtra;
274
+ };
275
+
276
+ /**
277
+ * @param {string} str
278
+ * @returns {string}
279
+ */
280
+ var unescapeBackslashes = function unescapeBackslashes(str) {
281
+ return str.replace(/\\+/g, function (esc) {
282
+ return esc.slice(0, esc.length / 2);
283
+ });
284
+ };
285
+
286
+ /**
287
+ * @typedef {any} AnyValue
288
+ */
289
+
290
+ /**
291
+ * @param {string} args
292
+ * @returns {AnyValue}
293
+ */
294
+ var parseJSONExtra = function parseJSONExtra(args) {
295
+ return _jsonExtra.parse(
296
+ // Doesn't actually currently allow explicit brackets,
297
+ // but in case we change our regex to allow inner brackets
298
+ '{' + (args || '').replace(/^\{/, '').replace(/\}$/, '') + '}');
299
+ };
300
+
301
+ // Todo: Extract to own library (RegExtras?)
302
+
303
+ /**
304
+ * @callback BetweenMatches
305
+ * @param {string} str
306
+ * @returns {void}
307
+ */
308
+
309
+ /**
310
+ * @callback AfterMatch
311
+ * @param {string} str
312
+ * @returns {void}
313
+ */
314
+
315
+ /**
316
+ * @callback EscapeAtOne
317
+ * @param {string} str
318
+ * @returns {void}
319
+ */
320
+
321
+ /**
322
+ * @param {RegExp} regex
323
+ * @param {string} str
324
+ * @param {{
325
+ * onMatch: (...arg0: string[]) => void,
326
+ * extra?: BetweenMatches|AfterMatch|EscapeAtOne
327
+ * betweenMatches?: BetweenMatches,
328
+ * afterMatch?: AfterMatch,
329
+ * escapeAtOne?: EscapeAtOne
330
+ * }} cfg
331
+ */
332
+ var processRegex = function processRegex(regex, str, _ref) {
333
+ var onMatch = _ref.onMatch,
334
+ extra = _ref.extra,
335
+ betweenMatches = _ref.betweenMatches,
336
+ afterMatch = _ref.afterMatch,
337
+ escapeAtOne = _ref.escapeAtOne;
338
+ var match;
339
+ var previousIndex = 0;
340
+ if (extra) {
341
+ betweenMatches = extra;
342
+ afterMatch = extra;
343
+ escapeAtOne = extra;
344
+ }
345
+ if (!betweenMatches || !afterMatch) {
346
+ throw new Error('You must have `extra` or `betweenMatches` and `afterMatch` arguments.');
347
+ }
348
+ while ((match = regex.exec(str)) !== null) {
349
+ var _match = match,
350
+ _match2 = _slicedToArray(_match, 2),
351
+ _ = _match2[0],
352
+ esc = _match2[1];
353
+ var lastIndex = regex.lastIndex;
354
+ var startMatchPos = lastIndex - _.length;
355
+ if (startMatchPos > previousIndex) {
356
+ betweenMatches(str.slice(previousIndex, startMatchPos));
357
+ }
358
+ if (escapeAtOne && esc.length % 2) {
359
+ previousIndex = lastIndex;
360
+ escapeAtOne(_);
361
+ continue;
362
+ }
363
+ onMatch.apply(void 0, _toConsumableArray(match));
364
+ previousIndex = lastIndex;
365
+ }
366
+ if (previousIndex !== str.length) {
367
+ // Get text at end
368
+ afterMatch(str.slice(previousIndex));
369
+ }
370
+ };
371
+
372
+ /* globals fetch, document */
373
+
374
+ /**
375
+ * @typedef {(
376
+ * input: RequestInfo|URL, init?: RequestInit
377
+ * ) => Promise<Response>} Fetch
378
+ */
379
+ /**
380
+ * @type {null|Fetch}
381
+ */
382
+ var _fetch = typeof fetch !== 'undefined' ? fetch
383
+ /* c8 ignore next */ : null;
384
+
385
+ /**
386
+ * @param {Fetch} f
387
+ * @returns {void}
388
+ */
389
+ var setFetch = function setFetch(f) {
390
+ _fetch = f;
391
+ };
392
+
393
+ /**
394
+ * @returns {Fetch|null}
395
+ */
396
+ var getFetch = function getFetch() {
397
+ return _fetch;
398
+ };
399
+
400
+ /** @type {Document|null} */
401
+ var _doc = typeof document !== 'undefined'
402
+ /* c8 ignore next */ ? document : null;
403
+
404
+ /**
405
+ * @param {Document} doc
406
+ * @returns {void}
407
+ */
408
+ var setDocument = function setDocument(doc) {
409
+ _doc = doc;
410
+ };
411
+
412
+ /**
413
+ * @returns {Document|null}
414
+ */
415
+ var getDocument = function getDocument() {
416
+ return _doc;
417
+ };
418
+
419
+ /**
420
+ *
421
+ * @returns {string}
422
+ */
423
+ function generateUUID() {
424
+ // Adapted from original: public domain/MIT: http://stackoverflow.com/a/8809472/271577
425
+ var d = Date.now();
426
+ /* c8 ignore next 5 */
427
+ if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
428
+ d += performance.now(); // use high-precision timer if available
429
+ }
430
+
431
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
432
+ /* eslint-disable no-bitwise */
433
+ var r = Math.trunc((d + Math.random() * 16) % 16);
434
+ d = Math.floor(d / 16);
435
+ return (c === 'x' ? r : r & 0x3 | 0x8).toString(16);
436
+ /* eslint-enable no-bitwise */
437
+ });
438
+ }
439
+
440
+ /**
441
+ *
442
+ * @param {string} locale
443
+ * @param {string[]} arrayOfItems
444
+ * @param {Intl.CollatorOptions|undefined} options
445
+ * @returns {string[]}
446
+ */
447
+ var sort = function sort(locale, arrayOfItems, options) {
448
+ return arrayOfItems.sort(new Intl.Collator(locale, options).compare);
449
+ };
450
+
451
+ /**
452
+ *
453
+ * @param {string} locale
454
+ * @param {string[]} arrayOfItems
455
+ * @param {Intl.ListFormatOptions|undefined} [options]
456
+ * @returns {string}
457
+ */
458
+ var list = function list(locale, arrayOfItems, options) {
459
+ return new Intl.ListFormat(locale, options).format(arrayOfItems);
460
+ };
461
+
462
+ /**
463
+ *
464
+ * @param {string} locale
465
+ * @param {string[]} arrayOfItems
466
+ * @param {Intl.ListFormatOptions|undefined} [listOptions]
467
+ * @param {Intl.CollatorOptions|undefined} [collationOptions]
468
+ * @returns {string}
469
+ */
470
+ var sortListSimple = function sortListSimple(locale, arrayOfItems, listOptions, collationOptions) {
471
+ sort(locale, arrayOfItems, collationOptions);
472
+ return list(locale, arrayOfItems, listOptions);
473
+ };
474
+
475
+ /**
476
+ * @typedef {number} Integer
477
+ */
478
+
479
+ /**
480
+ *
481
+ * @param {string} locale
482
+ * @param {string[]} arrayOfItems
483
+ * @param {((str: string, idx: Integer) => any)|
484
+ * Intl.ListFormatOptions|undefined} map
485
+ * @param {Intl.ListFormatOptions|undefined} [listOptions]
486
+ * @param {Intl.CollatorOptions|undefined} [collationOptions]
487
+ * @returns {DocumentFragment|string}
488
+ */
489
+ var sortList = function sortList(locale, arrayOfItems, map, listOptions, collationOptions) {
490
+ if (typeof map !== 'function') {
491
+ return sortListSimple(locale, /** @type {string[]} */arrayOfItems, map, listOptions);
492
+ }
493
+ sort(locale, arrayOfItems, collationOptions);
494
+ var randomId = generateUUID();
495
+ var placeholderArray = _toConsumableArray(arrayOfItems).map(function (_, i) {
496
+ return "<<".concat(randomId).concat(i, ">>");
497
+ });
498
+
499
+ /** @type {(string|Node)[]} */
500
+ var nodes = [];
501
+
502
+ /**
503
+ * @param {string} arg
504
+ * @returns {void}
505
+ */
506
+ var push = function push(arg) {
507
+ nodes.push(arg);
508
+ };
509
+ processRegex(
510
+ // // eslint-disable-next-line prefer-named-capture-group
511
+ new RegExp("<<".concat(randomId, "(\\d)>>"), 'gu'), list(locale, placeholderArray, listOptions), {
512
+ betweenMatches: push,
513
+ afterMatch: push,
514
+ onMatch: function onMatch(_, idx) {
515
+ push(map(arrayOfItems[Number(idx)], Number(idx)));
516
+ }
517
+ });
518
+ var _doc = /** @type {Document} */getDocument();
519
+ var container = _doc.createDocumentFragment();
520
+ container.append.apply(container, nodes);
521
+ return container;
522
+ };
523
+
524
+ /**
525
+ * @typedef {number} Integer
526
+ */
527
+
528
+ /**
529
+ * @param {{
530
+ * object: import('./defaultLocaleResolver.js').DateRangeValueArray|
531
+ * import('./defaultLocaleResolver.js').ListValueArray|
532
+ * import('./defaultLocaleResolver.js').RelativeValueArray|
533
+ * import('./defaultLocaleResolver.js').ValueArray
534
+ * }} cfg
535
+ * @returns {{
536
+ * value: number|string|string[]|Date,
537
+ * options?: Intl.NumberFormatOptions|Intl.PluralRulesOptions|
538
+ * string|Date|number,
539
+ * extraOpts?: object,
540
+ * callback?: (item: string, i: Integer) => Element
541
+ * }}
542
+ */
543
+ var getFormatterInfo = function getFormatterInfo(_ref) {
544
+ var object = _ref.object;
545
+ if (Array.isArray(object)) {
546
+ if (typeof object[1] === 'function') {
547
+ var _object = _slicedToArray(
548
+ /**
549
+ * @type {[
550
+ * string[], (item: string, i: Integer) => Element, object, object
551
+ * ]}
552
+ */
553
+ object, 4),
554
+ _value = _object[0],
555
+ callback = _object[1],
556
+ _options = _object[2],
557
+ _extraOpts = _object[3];
558
+ return {
559
+ value: _value,
560
+ callback: callback,
561
+ options: _options,
562
+ extraOpts: _extraOpts
563
+ };
564
+ }
565
+ var _object2 = _slicedToArray(object, 3),
566
+ value = _object2[0],
567
+ options = _object2[1],
568
+ extraOpts = _object2[2];
569
+ return {
570
+ value: value,
571
+ options: options,
572
+ extraOpts: extraOpts
573
+ };
574
+ }
575
+ return {
576
+ value: object
577
+ };
578
+ };
579
+
580
+ /**
581
+ * Callback to give replacement text based on a substitution value.
582
+ *
583
+ * `value` - contains the value returned by the individual substitution.
584
+ * `arg` - See `cfg.arg` of {@link SubstitutionCallback}.
585
+ * `key` - The substitution key Not currently in use
586
+ * `locale` - The locale.
587
+ * @typedef {(info: {
588
+ * value: import('./defaultLocaleResolver.js').SubstitutionObjectValue
589
+ * arg?: string,
590
+ * key?: string,
591
+ * locale?: string
592
+ * }) => string|Node} AllSubstitutionCallback
593
+ */
594
+
595
+ /**
596
+ * @type {AllSubstitutionCallback}
597
+ */
598
+ var defaultAllSubstitutions = function defaultAllSubstitutions(_ref2) {
599
+ var value = _ref2.value,
600
+ arg = _ref2.arg;
601
+ _ref2.key;
602
+ var locale = _ref2.locale;
603
+ // Strings or DOM Nodes
604
+ if (typeof value === 'string' || value && _typeof(value) === 'object' && 'nodeType' in value) {
605
+ return value;
606
+ }
607
+
608
+ /** @type {object|string|Date|number|undefined} */
609
+ var opts;
610
+
611
+ /**
612
+ * @param {{
613
+ * type: string,
614
+ * options?: object,
615
+ * checkArgOptions?: boolean;
616
+ * }} cfg
617
+ * @returns {object|undefined}
618
+ */
619
+ var applyArgs = function applyArgs(_ref3) {
620
+ var type = _ref3.type,
621
+ _ref3$options = _ref3.options,
622
+ options = _ref3$options === void 0 ? /** @type {object|undefined} */
623
+ opts : _ref3$options,
624
+ _ref3$checkArgOptions = _ref3.checkArgOptions,
625
+ checkArgOptions = _ref3$checkArgOptions === void 0 ? false : _ref3$checkArgOptions;
626
+ if (typeof arg === 'string') {
627
+ var _arg$split = arg.split('|'),
628
+ _arg$split2 = _slicedToArray(_arg$split, 3),
629
+ userType = _arg$split2[0],
630
+ extraArgs = _arg$split2[1],
631
+ argOptions = _arg$split2[2];
632
+ // Alias
633
+ if (userType === 'DATE') {
634
+ userType = 'DATETIME';
635
+ }
636
+ if (userType === type) {
637
+ if (!extraArgs) {
638
+ options = {};
639
+ } else if (!checkArgOptions || argOptions) {
640
+ // Todo: Allow escaping and restoring of pipe symbol
641
+ options = _objectSpread2(_objectSpread2({}, options), parseJSONExtra(checkArgOptions && argOptions ? argOptions : extraArgs));
642
+ }
643
+ }
644
+ }
645
+ return options;
646
+ };
647
+ var expectsDatetime = false;
648
+ if (value && _typeof(value) === 'object' && !Array.isArray(value)) {
649
+ var singleKey = Object.keys(value)[0];
650
+ if (['number', 'date', 'datetime', 'dateRange', 'datetimeRange', 'relative', 'region', 'language', 'script', 'currency', 'list', 'plural'].includes(singleKey)) {
651
+ var extraOpts, callback;
652
+ /**
653
+ * @typedef {any} AnyValue
654
+ */
655
+
656
+ var obj = /** @type {unknown} */
657
+ /** @type {AnyValue} */
658
+ value[
659
+ /**
660
+ * @type {"number"|"date"|"datetime"|"dateRange"|
661
+ * "datetimeRange"|"relative"|"region"|"language"|
662
+ * "script"|"currency"|"list"|"plural"}
663
+ */
664
+ singleKey];
665
+ var _getFormatterInfo = getFormatterInfo({
666
+ object:
667
+ /**
668
+ * @type {import('./defaultLocaleResolver.js').DateRangeValueArray|
669
+ * import('./defaultLocaleResolver.js').ListValueArray|
670
+ * import('./defaultLocaleResolver.js').RelativeValueArray|
671
+ * import('./defaultLocaleResolver.js').ValueArray
672
+ * }
673
+ */
674
+ obj
675
+ });
676
+ value = _getFormatterInfo.value;
677
+ opts = _getFormatterInfo.options;
678
+ extraOpts = _getFormatterInfo.extraOpts;
679
+ callback = _getFormatterInfo.callback;
680
+ switch (singleKey) {
681
+ case 'date':
682
+ case 'datetime':
683
+ expectsDatetime = true;
684
+ break;
685
+ case 'dateRange':
686
+ case 'datetimeRange':
687
+ {
688
+ var dtf = new Intl.DateTimeFormat(locale, applyArgs({
689
+ type: 'DATERANGE',
690
+ options: extraOpts
691
+ }));
692
+ return dtf.formatRange.apply(dtf, _toConsumableArray( /** @type {[Date, Date]} */
693
+ [/** @type {number|Date} */
694
+ value, /** @type {Date} */
695
+ opts].map(function (val) {
696
+ return typeof val === 'number' ? new Date(val) : val;
697
+ })));
698
+ }
699
+ case 'region':
700
+ case 'language':
701
+ case 'script':
702
+ case 'currency':
703
+ return (/** @type {string} */new Intl.DisplayNames(locale, _objectSpread2(_objectSpread2({}, applyArgs({
704
+ type: singleKey.toUpperCase()
705
+ })), {}, {
706
+ type: singleKey
707
+ })).of( /** @type {string} */value)
708
+ );
709
+ case 'relative':
710
+ // The second argument actually contains the primary options, so swap
711
+ // eslint-disable-next-line max-len -- Long
712
+ var _ref4 = /** @type {[Intl.RelativeTimeFormatUnit, object?]} */
713
+ [opts, extraOpts];
714
+ extraOpts = _ref4[0];
715
+ opts = _ref4[1];
716
+ return new Intl.RelativeTimeFormat(locale, applyArgs({
717
+ type: 'RELATIVE'
718
+ })).format( /** @type {number} */value, extraOpts);
719
+
720
+ // ListFormat (with Collator)
721
+ case 'list':
722
+ if (callback) {
723
+ return sortList( /** @type {string} */locale, /** @type {string[]} */
724
+ value, callback, applyArgs({
725
+ type: 'LIST'
726
+ }), applyArgs({
727
+ type: 'LIST',
728
+ options: extraOpts,
729
+ checkArgOptions: true
730
+ }));
731
+ }
732
+ return sortList( /** @type {string} */locale, /** @type {string[]} */
733
+ value, applyArgs({
734
+ type: 'LIST'
735
+ }), applyArgs({
736
+ type: 'LIST',
737
+ options: extraOpts,
738
+ checkArgOptions: true
739
+ }));
740
+ }
741
+ }
742
+ }
743
+
744
+ // Dates
745
+ if (value) {
746
+ if (typeof value === 'number' && (expectsDatetime || /^DATE(?:TIME)(?:\||$)/.test( /** @type {string} */arg))) {
747
+ value = new Date(value);
748
+ }
749
+ if (_typeof(value) === 'object' && 'getTime' in value && typeof value.getTime === 'function') {
750
+ return new Intl.DateTimeFormat(locale, applyArgs({
751
+ type: 'DATETIME'
752
+ })).format(value);
753
+ }
754
+ }
755
+
756
+ // Date range
757
+ if (Array.isArray(value)) {
758
+ var _Intl$DateTimeFormat;
759
+ var _extraOpts2 = /** @type {Intl.DateTimeFormatOptions|undefined} */
760
+ value[2];
761
+ return (_Intl$DateTimeFormat = new Intl.DateTimeFormat(locale, applyArgs({
762
+ type: 'DATERANGE',
763
+ options: _extraOpts2
764
+ }))).formatRange.apply(_Intl$DateTimeFormat, _toConsumableArray( /** @type {[Date, Date]} */
765
+ value.slice(0, 2).map(function (val) {
766
+ return typeof val === 'number' ? new Date(val) : val;
767
+ })));
768
+ }
769
+
770
+ // Numbers
771
+ if (typeof value === 'number') {
772
+ return new Intl.NumberFormat(locale, applyArgs({
773
+ type: 'NUMBER'
774
+ })).format(value);
775
+ }
776
+
777
+ // console.log('value', value);
778
+ throw new TypeError('Unknown formatter');
779
+ };
780
+
781
+ /**
782
+ * Base class for formatting.
783
+ */
784
+ var Formatter = /*#__PURE__*/_createClass(function Formatter() {
785
+ _classCallCheck(this, Formatter);
786
+ });
787
+
788
+ /**
789
+ * @param {object} cfg
790
+ * @param {string} cfg.key
791
+ * @param {import('./getMessageForKeyByStyle.js').LocaleBody} cfg.body
792
+ * @param {string} cfg.type
793
+ * @param {"richNested"|"rich"|"plain"|
794
+ * "plainNested"|import('./getMessageForKeyByStyle.js').
795
+ * MessageStyleCallback} [cfg.messageStyle="richNested"]
796
+ * @returns {string}
797
+ */
798
+ var _getSubstitution = function getSubstitution(_ref) {
799
+ var key = _ref.key,
800
+ body = _ref.body,
801
+ type = _ref.type,
802
+ _ref$messageStyle = _ref.messageStyle,
803
+ messageStyle = _ref$messageStyle === void 0 ? 'richNested' : _ref$messageStyle;
804
+ var messageForKey = getMessageForKeyByStyle({
805
+ messageStyle: messageStyle
806
+ });
807
+ var substitution = messageForKey({
808
+ body: body
809
+ }, key);
810
+ if (!substitution) {
811
+ throw new Error("Key value not found for ".concat(type, " key: (").concat(key, ")"));
812
+ }
813
+ // We don't allow a substitution function here or below as comes
814
+ // from locale and locale content should not pose security concerns
815
+ return substitution.value;
816
+ };
817
+
818
+ /**
819
+ * Formatter for local variables.
820
+ */
821
+ var LocalFormatter = /*#__PURE__*/function (_Formatter) {
822
+ _inherits(LocalFormatter, _Formatter);
823
+ var _super = _createSuper(LocalFormatter);
824
+ /**
825
+ * @param {import('./getMessageForKeyByStyle.js').LocalObject} locals
826
+ */
827
+ function LocalFormatter(locals) {
828
+ var _this;
829
+ _classCallCheck(this, LocalFormatter);
830
+ _this = _super.call(this);
831
+ _this.locals = locals;
832
+ return _this;
833
+ }
834
+ /**
835
+ * @param {string} key
836
+ * @returns {string|Element}
837
+ */
838
+ _createClass(LocalFormatter, [{
839
+ key: "getSubstitution",
840
+ value: function getSubstitution(key) {
841
+ return _getSubstitution({
842
+ key: key.slice(1),
843
+ body: this.locals,
844
+ type: 'local'
845
+ });
846
+ }
847
+ /**
848
+ * @param {string} key
849
+ * @returns {boolean}
850
+ */
851
+ }, {
852
+ key: "isMatch",
853
+ value: function isMatch(key) {
854
+ var components = key.slice(1).split('.');
855
+ /** @type {import('./getMessageForKeyByStyle.js').LocaleBody} */
856
+ var parent = this.locals;
857
+ return (/** @type {typeof LocalFormatter} */this.constructor.isMatchingKey(key) && components.every(function (cmpt) {
858
+ var result = (cmpt in parent);
859
+ parent =
860
+ /**
861
+ * @type {import('./defaultLocaleResolver.js').
862
+ * RichNestedLocaleStringBodyObject|
863
+ * import('./defaultLocaleResolver.js').
864
+ * PlainNestedLocaleStringBodyObject|
865
+ * import('./defaultLocaleResolver.js').RichLocaleStringSubObject
866
+ * }
867
+ */
868
+ /**
869
+ * @type {import('./defaultLocaleResolver.js').
870
+ * RichNestedLocaleStringBodyObject|
871
+ * import('./defaultLocaleResolver.js').
872
+ * PlainNestedLocaleStringBodyObject
873
+ * }
874
+ */
875
+ parent[cmpt];
876
+ return result;
877
+ })
878
+ );
879
+ }
880
+ /**
881
+ * @param {string} key
882
+ * @returns {boolean}
883
+ */
884
+ }], [{
885
+ key: "isMatchingKey",
886
+ value: function isMatchingKey(key) {
887
+ return key.startsWith('-');
888
+ }
889
+ }]);
890
+ return LocalFormatter;
891
+ }(Formatter);
892
+
893
+ /**
894
+ * Formatter for regular variables.
895
+ */
896
+ var RegularFormatter = /*#__PURE__*/function (_Formatter2) {
897
+ _inherits(RegularFormatter, _Formatter2);
898
+ var _super2 = _createSuper(RegularFormatter);
899
+ /**
900
+ * @param {import('./defaultLocaleResolver.js').SubstitutionObject
901
+ * } substitutions
902
+ */
903
+ function RegularFormatter(substitutions) {
904
+ var _this2;
905
+ _classCallCheck(this, RegularFormatter);
906
+ _this2 = _super2.call(this);
907
+ _this2.substitutions = substitutions;
908
+ return _this2;
909
+ }
910
+ /**
911
+ * @param {string} key
912
+ * @returns {boolean}
913
+ */
914
+ _createClass(RegularFormatter, [{
915
+ key: "isMatch",
916
+ value: function isMatch(key) {
917
+ return (/** @type {typeof RegularFormatter} */this.constructor.isMatchingKey(key) && key in this.substitutions
918
+ );
919
+ }
920
+ /**
921
+ * @param {string} key
922
+ * @returns {boolean}
923
+ */
924
+ }], [{
925
+ key: "isMatchingKey",
926
+ value: function isMatchingKey(key) {
927
+ return /^[0-9A-Z_a-z]/.test(key);
928
+ }
929
+ }]);
930
+ return RegularFormatter;
931
+ }(Formatter);
932
+
933
+ /**
934
+ * Formatter for switch variables.
935
+ */
936
+ var SwitchFormatter = /*#__PURE__*/function (_Formatter3) {
937
+ _inherits(SwitchFormatter, _Formatter3);
938
+ var _super3 = _createSuper(SwitchFormatter);
939
+ /**
940
+ * @param {import('./defaultLocaleResolver.js').Switches} switches
941
+ * @param {object} cfg
942
+ * @param {import('./defaultLocaleResolver.js').
943
+ * SubstitutionObject} cfg.substitutions
944
+ */
945
+ function SwitchFormatter(switches, _ref2) {
946
+ var _this3;
947
+ var substitutions = _ref2.substitutions;
948
+ _classCallCheck(this, SwitchFormatter);
949
+ _this3 = _super3.call(this);
950
+ _this3.switches = switches;
951
+ _this3.substitutions = substitutions;
952
+ return _this3;
953
+ }
954
+
955
+ /**
956
+ * @param {string} key
957
+ * @param {object} cfg
958
+ * @param {string} cfg.locale
959
+ * @param {(string|undefined)[]} cfg.usedKeys
960
+ * @param {string} cfg.arg
961
+ * @param {import('./getDOMForLocaleString.js').
962
+ * MissingSuppliedFormattersCallback} cfg.missingSuppliedFormatters
963
+ * @returns {string}
964
+ */
965
+ _createClass(SwitchFormatter, [{
966
+ key: "getSubstitution",
967
+ value: function getSubstitution(key, _ref3) {
968
+ var locale = _ref3.locale,
969
+ usedKeys = _ref3.usedKeys,
970
+ arg = _ref3.arg,
971
+ missingSuppliedFormatters = _ref3.missingSuppliedFormatters;
972
+ var ky = /** @type {typeof SwitchFormatter} */this.constructor.getKey(key).slice(1);
973
+ // Expression might not actually use formatter, e.g., for singular,
974
+ // the conditional might just write out "one"
975
+
976
+ var _this$getMatch = this.getMatch(ky),
977
+ _this$getMatch2 = _slicedToArray(_this$getMatch, 3),
978
+ objKey = _this$getMatch2[0],
979
+ body = _this$getMatch2[1],
980
+ keySegment = _this$getMatch2[2];
981
+ usedKeys.push(keySegment);
982
+ var type;
983
+ /** @type {string} */
984
+ var opts;
985
+ if (objKey && objKey.includes('|')) {
986
+ var _objKey$split = objKey.split('|');
987
+ var _objKey$split2 = _slicedToArray(_objKey$split, 3);
988
+ type = _objKey$split2[1];
989
+ opts = _objKey$split2[2];
990
+ }
991
+ if (!body) {
992
+ missingSuppliedFormatters({
993
+ key: key,
994
+ formatter: this
995
+ });
996
+ return '\\{' + key + '}';
997
+ }
998
+
999
+ /*
1000
+ if (!(ky in this.substitutions)) {
1001
+ throw new Error(`Switch expecting formatter: ${ky}`);
1002
+ }
1003
+ */
1004
+
1005
+ /**
1006
+ * @param {number} value
1007
+ * @param {Intl.NumberFormatOptions|undefined} [defaultOptions]
1008
+ * @returns {string}
1009
+ */
1010
+ var getNumberFormat = function getNumberFormat(value, defaultOptions) {
1011
+ var numberOpts = parseJSONExtra(opts);
1012
+ return new Intl.NumberFormat(locale, _objectSpread2(_objectSpread2({}, defaultOptions), numberOpts)).format(value);
1013
+ };
1014
+
1015
+ /**
1016
+ * @param {number} value
1017
+ * @param {Intl.PluralRulesOptions|undefined} [defaultOptions]
1018
+ * @returns {Intl.LDMLPluralRule}
1019
+ */
1020
+ var getPluralFormat = function getPluralFormat(value, defaultOptions) {
1021
+ var pluralOpts = parseJSONExtra(opts);
1022
+ return new Intl.PluralRules(locale, _objectSpread2(_objectSpread2({}, defaultOptions), pluralOpts)).select(value);
1023
+ };
1024
+ var formatterValue = this.substitutions[/** @type {string} */keySegment];
1025
+ var match = formatterValue;
1026
+ if (typeof formatterValue === 'number') {
1027
+ switch (type) {
1028
+ case 'NUMBER':
1029
+ match = getNumberFormat(formatterValue);
1030
+ break;
1031
+ case 'PLURAL':
1032
+ match = getPluralFormat(formatterValue);
1033
+ break;
1034
+ default:
1035
+ match = new Intl.PluralRules(locale).select(formatterValue);
1036
+ break;
1037
+ }
1038
+ } else if (formatterValue && _typeof(formatterValue) === 'object') {
1039
+ var singleKey = Object.keys(formatterValue)[0];
1040
+ if (['number', 'plural'].includes(singleKey)) {
1041
+ var _getFormatterInfo = getFormatterInfo({
1042
+ object:
1043
+ /**
1044
+ * @type {import('./defaultLocaleResolver.js').NumberInfo|
1045
+ * import('./defaultLocaleResolver.js').PluralInfo}
1046
+ */
1047
+ // @ts-expect-error Ok
1048
+ formatterValue[/** @type {"number"|"plural"} */singleKey]
1049
+ }),
1050
+ value = _getFormatterInfo.value,
1051
+ options = _getFormatterInfo.options;
1052
+ if (!type) {
1053
+ type = singleKey.toUpperCase();
1054
+ }
1055
+ var typeMatches = singleKey.toUpperCase() === type;
1056
+ if (!typeMatches) {
1057
+ throw new TypeError("Expecting type \"".concat(type.toLowerCase(), "\"; instead found \"").concat(singleKey, "\"."));
1058
+ }
1059
+ // eslint-disable-next-line default-case
1060
+ switch (type) {
1061
+ case 'NUMBER':
1062
+ match = getNumberFormat( /** @type {number} */value, /** @type {Intl.NumberFormatOptions} */
1063
+ options);
1064
+ break;
1065
+ case 'PLURAL':
1066
+ match = getPluralFormat( /** @type {number} */value, /** @type {Intl.PluralRulesOptions} */
1067
+ options);
1068
+ break;
1069
+ }
1070
+ }
1071
+ }
1072
+
1073
+ // We do not want the default `richNested` here as that will split
1074
+ // up the likes of `0.0`
1075
+ var messageStyle = 'richNested';
1076
+
1077
+ /**
1078
+ * @param {string} s
1079
+ * @returns {string}
1080
+ */
1081
+ var preventNesting = function preventNesting(s) {
1082
+ return s.replace(/\\/g, '\\\\').replace(/\./g, '\\.');
1083
+ };
1084
+ try {
1085
+ return _getSubstitution({
1086
+ messageStyle: messageStyle,
1087
+ key: match ? preventNesting( /** @type {string} */match) : arg,
1088
+ body: body,
1089
+ type: 'switch'
1090
+ });
1091
+ } catch (err) {
1092
+ try {
1093
+ return _getSubstitution({
1094
+ messageStyle: messageStyle,
1095
+ key: '*' + preventNesting( /** @type {string} */match),
1096
+ body: body,
1097
+ type: 'switch'
1098
+ });
1099
+ } catch (error) {
1100
+ var k = Object.keys(body).find(function (switchKey) {
1101
+ return switchKey.startsWith('*');
1102
+ });
1103
+ if (!k) {
1104
+ throw new Error("No defaults found for switch ".concat(ky));
1105
+ }
1106
+ return _getSubstitution({
1107
+ messageStyle: messageStyle,
1108
+ key: preventNesting(k),
1109
+ body: body,
1110
+ type: 'switch'
1111
+ });
1112
+ }
1113
+ }
1114
+ }
1115
+
1116
+ /**
1117
+ * @param {string} key
1118
+ * @returns {boolean}
1119
+ */
1120
+ }, {
1121
+ key: "isMatch",
1122
+ value: function isMatch(key) {
1123
+ return Boolean(key && /** @type {typeof SwitchFormatter} */this.constructor.isMatchingKey(key) && this.getMatch(key.slice(1)).length);
1124
+ }
1125
+
1126
+ /**
1127
+ * @typedef {[
1128
+ * objKey?: string,
1129
+ * body?: import('./getMessageForKeyByStyle.js').LocaleBody,
1130
+ * keySegment?: string
1131
+ * ]} SwitchMatch
1132
+ */
1133
+
1134
+ /**
1135
+ * @typedef {number} Integer
1136
+ */
1137
+
1138
+ /**
1139
+ * @param {string} ky
1140
+ * @returns {SwitchMatch}
1141
+ */
1142
+ }, {
1143
+ key: "getMatch",
1144
+ value: function getMatch(ky) {
1145
+ var _this4 = this;
1146
+ var ks = ky.split('.');
1147
+ var returnValue = /** @type {unknown} */ks.reduce(
1148
+ /**
1149
+ * @param {import('./defaultLocaleResolver.js').SwitchArrays|
1150
+ * import('./defaultLocaleResolver.js').SwitchArray} obj
1151
+ * @param {string} k
1152
+ * @param {Integer} i
1153
+ * @throws {Error}
1154
+ * @returns {SwitchMatch|
1155
+ * import('./defaultLocaleResolver.js').SwitchCaseArray|
1156
+ * import('./defaultLocaleResolver.js').SwitchArray}
1157
+ */
1158
+ // @ts-expect-error It works
1159
+ function (obj, k, i) {
1160
+ if (i < ks.length - 1) {
1161
+ if (!(k in obj)) {
1162
+ throw new Error("Switch key \"".concat(k, "\" not found (from \"~").concat(ky, "\")"));
1163
+ }
1164
+ return obj[k];
1165
+ }
1166
+ // Todo: Should throw on encountering duplicate fundamental keys (even
1167
+ // if there are different arguments, that should not be allowed)
1168
+ var ret = Object.entries(obj).find(function (_ref4) {
1169
+ var _ref5 = _slicedToArray(_ref4, 1),
1170
+ switchKey = _ref5[0];
1171
+ return k === /** @type {typeof SwitchFormatter} */_this4.constructor.getKey(switchKey);
1172
+ });
1173
+ return ret ? [].concat(_toConsumableArray(ret), [k]) : [];
1174
+ }, this.switches);
1175
+ return (/** @type {SwitchMatch} */returnValue
1176
+ );
1177
+ }
1178
+
1179
+ /**
1180
+ * @param {string} key
1181
+ * @returns {boolean}
1182
+ */
1183
+ }], [{
1184
+ key: "isMatchingKey",
1185
+ value: function isMatchingKey(key) {
1186
+ return key.startsWith('~');
1187
+ }
1188
+ /**
1189
+ * @param {string} key
1190
+ * @returns {string}
1191
+ */
1192
+ }, {
1193
+ key: "getKey",
1194
+ value: function getKey(key) {
1195
+ var match = key.match(/^(?:[\0-\{\}-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*/);
1196
+ return (/** @type {string} */match && match[0]
1197
+ );
1198
+ }
1199
+ }]);
1200
+ return SwitchFormatter;
1201
+ }(Formatter);
1202
+
1203
+ /**
1204
+ * @typedef {(value: any) => Promise<any>|any} PromiseChainErrback
1205
+ */
1206
+
1207
+ /**
1208
+ * The given array will have its items processed in series; if the supplied
1209
+ * `errBack` (which is guaranteed to run at least once), when passed the
1210
+ * current item, returns a `Promise` or value that resolves, that value will
1211
+ * be used for the return result of this function and no other items in
1212
+ * the array will continue to be processed; if it rejects, however, the
1213
+ * next item will be processed with `errBack`.
1214
+ * Accept an array of values to pass to an errback which should return
1215
+ * a promise (or final result value) which resolves to a result or which
1216
+ * rejects so that the next item in the array can be checked in series.
1217
+ * @param {Array<any>} values Array of values
1218
+ * @param {PromiseChainErrback} errBack Accepts an item of the array as its
1219
+ * single argument
1220
+ * @param {string} [errorMessage="Reached end of values array."]
1221
+ * @returns {Promise<any>} Either resolves to a value derived from an item in
1222
+ * the array or rejects if all items reject
1223
+ * @example
1224
+ promiseChainForValues(['a', 'b', 'c'], (val) => {
1225
+ return new Promise(function (resolve, reject) {
1226
+ if (val === 'a') {
1227
+ reject(new Error('missing'));
1228
+ }
1229
+ setTimeout(() => {
1230
+ resolve(val);
1231
+ }, 100);
1232
+ });
1233
+ });
1234
+ */
1235
+
1236
+ function _await$2(value, then, direct) {
1237
+ if (direct) {
1238
+ return then ? then(value) : value;
1239
+ }
1240
+ if (!value || !value.then) {
1241
+ value = Promise.resolve(value);
1242
+ }
1243
+ return then ? value.then(then) : value;
1244
+ }
1245
+ function _catch$1(body, recover) {
1246
+ try {
1247
+ var result = body();
1248
+ } catch (e) {
1249
+ return recover(e);
1250
+ }
1251
+ if (result && result.then) {
1252
+ return result.then(void 0, recover);
1253
+ }
1254
+ return result;
1255
+ }
1256
+ function _settle(pact, state, value) {
1257
+ if (!pact.s) {
1258
+ if (value instanceof _Pact) {
1259
+ if (value.s) {
1260
+ if (state & 1) {
1261
+ state = value.s;
1262
+ }
1263
+ value = value.v;
1264
+ } else {
1265
+ value.o = _settle.bind(null, pact, state);
1266
+ return;
1267
+ }
1268
+ }
1269
+ if (value && value.then) {
1270
+ value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2));
1271
+ return;
1272
+ }
1273
+ pact.s = state;
1274
+ pact.v = value;
1275
+ var observer = pact.o;
1276
+ if (observer) {
1277
+ observer(pact);
1278
+ }
1279
+ }
1280
+ }
1281
+ var _Pact = /*#__PURE__*/function () {
1282
+ function _Pact() {}
1283
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
1284
+ var result = new _Pact();
1285
+ var state = this.s;
1286
+ if (state) {
1287
+ var callback = state & 1 ? onFulfilled : onRejected;
1288
+ if (callback) {
1289
+ try {
1290
+ _settle(result, 1, callback(this.v));
1291
+ } catch (e) {
1292
+ _settle(result, 2, e);
1293
+ }
1294
+ return result;
1295
+ } else {
1296
+ return this;
1297
+ }
1298
+ }
1299
+ this.o = function (_this) {
1300
+ try {
1301
+ var value = _this.v;
1302
+ if (_this.s & 1) {
1303
+ _settle(result, 1, onFulfilled ? onFulfilled(value) : value);
1304
+ } else if (onRejected) {
1305
+ _settle(result, 1, onRejected(value));
1306
+ } else {
1307
+ _settle(result, 2, value);
1308
+ }
1309
+ } catch (e) {
1310
+ _settle(result, 2, e);
1311
+ }
1312
+ };
1313
+ return result;
1314
+ };
1315
+ return _Pact;
1316
+ }();
1317
+ function _isSettledPact(thenable) {
1318
+ return thenable instanceof _Pact && thenable.s & 1;
1319
+ }
1320
+ function _for(test, update, body) {
1321
+ var stage;
1322
+ for (;;) {
1323
+ var shouldContinue = test();
1324
+ if (_isSettledPact(shouldContinue)) {
1325
+ shouldContinue = shouldContinue.v;
1326
+ }
1327
+ if (!shouldContinue) {
1328
+ return result;
1329
+ }
1330
+ if (shouldContinue.then) {
1331
+ stage = 0;
1332
+ break;
1333
+ }
1334
+ var result = body();
1335
+ if (result && result.then) {
1336
+ if (_isSettledPact(result)) {
1337
+ result = result.s;
1338
+ } else {
1339
+ stage = 1;
1340
+ break;
1341
+ }
1342
+ }
1343
+ if (update) {
1344
+ var updateValue = update();
1345
+ if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
1346
+ stage = 2;
1347
+ break;
1348
+ }
1349
+ }
1350
+ }
1351
+ var pact = new _Pact();
1352
+ var reject = _settle.bind(null, pact, 2);
1353
+ (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
1354
+ return pact;
1355
+ function _resumeAfterBody(value) {
1356
+ result = value;
1357
+ do {
1358
+ if (update) {
1359
+ updateValue = update();
1360
+ if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
1361
+ updateValue.then(_resumeAfterUpdate).then(void 0, reject);
1362
+ return;
1363
+ }
1364
+ }
1365
+ shouldContinue = test();
1366
+ if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) {
1367
+ _settle(pact, 1, result);
1368
+ return;
1369
+ }
1370
+ if (shouldContinue.then) {
1371
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
1372
+ return;
1373
+ }
1374
+ result = body();
1375
+ if (_isSettledPact(result)) {
1376
+ result = result.v;
1377
+ }
1378
+ } while (!result || !result.then);
1379
+ result.then(_resumeAfterBody).then(void 0, reject);
1380
+ }
1381
+ function _resumeAfterTest(shouldContinue) {
1382
+ if (shouldContinue) {
1383
+ result = body();
1384
+ if (result && result.then) {
1385
+ result.then(_resumeAfterBody).then(void 0, reject);
1386
+ } else {
1387
+ _resumeAfterBody(result);
1388
+ }
1389
+ } else {
1390
+ _settle(pact, 1, result);
1391
+ }
1392
+ }
1393
+ function _resumeAfterUpdate() {
1394
+ if (shouldContinue = test()) {
1395
+ if (shouldContinue.then) {
1396
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
1397
+ } else {
1398
+ _resumeAfterTest(shouldContinue);
1399
+ }
1400
+ } else {
1401
+ _settle(pact, 1, result);
1402
+ }
1403
+ }
1404
+ }
1405
+ function _continue(value, then) {
1406
+ return value && value.then ? value.then(then) : then(value);
1407
+ }
1408
+ function _async$1(f) {
1409
+ return function () {
1410
+ for (var args = [], i = 0; i < arguments.length; i++) {
1411
+ args[i] = arguments[i];
1412
+ }
1413
+ try {
1414
+ return Promise.resolve(f.apply(this, args));
1415
+ } catch (e) {
1416
+ return Promise.reject(e);
1417
+ }
1418
+ };
1419
+ }
1420
+ var promiseChainForValues = function promiseChainForValues(values, errBack) {
1421
+ var errorMessage = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'Reached end of values array.';
1422
+ if (!Array.isArray(values)) {
1423
+ throw new TypeError('The `values` argument to `promiseChainForValues` must be an array.');
1424
+ }
1425
+ if (typeof errBack !== 'function') {
1426
+ throw new TypeError('The `errBack` argument to `promiseChainForValues` must be a function.');
1427
+ }
1428
+ return _async$1(function () {
1429
+ var _exit = false,
1430
+ _interrupt = false;
1431
+ var ret;
1432
+ var p = Promise.reject(new Error('Intentionally reject so as to begin checking chain'));
1433
+ var breaking;
1434
+ return _continue(_for(function () {
1435
+ return !(_interrupt || _exit);
1436
+ }, void 0, function () {
1437
+ var value = values.shift();
1438
+ return _catch$1(function () {
1439
+ // eslint-disable-next-line no-await-in-loop
1440
+ return _await$2(p, function (_p) {
1441
+ ret = _p;
1442
+ _interrupt = true;
1443
+ });
1444
+ }, function () {
1445
+ if (breaking) {
1446
+ throw new Error(errorMessage);
1447
+ }
1448
+ // We allow one more try
1449
+ if (!values.length) {
1450
+ breaking = true;
1451
+ }
1452
+ // // eslint-disable-next-line no-await-in-loop
1453
+ p = errBack(value);
1454
+ });
1455
+ }), function (_result2) {
1456
+ return ret;
1457
+ });
1458
+ })();
1459
+ };
1460
+
1461
+ /**
1462
+ * `arg` - By default, accepts the third portion of the
1463
+ * `formattingRegex` within `insertNodes`, i.e., to allow the locale to
1464
+ * supply arguments back to the calling script.
1465
+ * `key` - The substitution key.
1466
+ * @callback SubstitutionCallback
1467
+ * @param {{
1468
+ * arg: string,
1469
+ * key: string
1470
+ * }} cfg
1471
+ * @returns {string|Element} The replacement text or element
1472
+ */
1473
+
1474
+ /**
1475
+ * May have additional properties if supplying options to an underlying
1476
+ * formatter.
1477
+ * The first value is the main value.
1478
+ * The second are the options related to the main value.
1479
+ * The third are any additional options.
1480
+ * @typedef {[string|number|Date, object?, object?]} ValueArray
1481
+ */
1482
+
1483
+ /**
1484
+ * @typedef {number} Integer
1485
+ */
1486
+
1487
+ /**
1488
+ * @typedef {[
1489
+ * string[],
1490
+ * (((item: string, i: Integer) => Element)|object)?,
1491
+ * object?,
1492
+ * object?
1493
+ * ]} ListValueArray
1494
+ */
1495
+
1496
+ /**
1497
+ * @typedef {[
1498
+ * Date|number, Date|number, Intl.DateTimeFormatOptions|undefined
1499
+ * ]} DateRangeValueArray
1500
+ */
1501
+
1502
+ /**
1503
+ * @typedef {[number, Intl.RelativeTimeFormatUnit, object?]} RelativeValueArray
1504
+ */
1505
+
1506
+ /**
1507
+ * @typedef {object} RelativeTimeInfo
1508
+ * @property {RelativeValueArray} relative
1509
+ */
1510
+
1511
+ /**
1512
+ * @typedef {object} ListInfo
1513
+ * @property {ListValueArray} list
1514
+ */
1515
+
1516
+ /**
1517
+ * @typedef {object} NumberInfo
1518
+ * @property {ValueArray|number} number
1519
+ */
1520
+
1521
+ /**
1522
+ * @typedef {object} DateInfo
1523
+ * @property {ValueArray} date
1524
+ */
1525
+
1526
+ /**
1527
+ * @typedef {object} DateTimeInfo
1528
+ * @property {ValueArray} datetime
1529
+ */
1530
+
1531
+ /**
1532
+ * @typedef {object} DateRangeInfo
1533
+ * @property {DateRangeValueArray} dateRange
1534
+ */
1535
+
1536
+ /**
1537
+ * @typedef {object} DatetimeRangeInfo
1538
+ * @property {DateRangeValueArray} datetimeRange
1539
+ */
1540
+
1541
+ /**
1542
+ * @typedef {object} RegionInfo
1543
+ * @property {ValueArray} region
1544
+ */
1545
+
1546
+ /**
1547
+ * @typedef {object} LanguageInfo
1548
+ * @property {ValueArray} language
1549
+ */
1550
+
1551
+ /**
1552
+ * @typedef {object} ScriptInfo
1553
+ * @property {ValueArray} script
1554
+ */
1555
+
1556
+ /**
1557
+ * @typedef {object} CurrencyInfo
1558
+ * @property {ValueArray} currency
1559
+ */
1560
+
1561
+ /**
1562
+ * @typedef {object} PluralInfo
1563
+ * @property {ValueArray} plural
1564
+ */
1565
+
1566
+ /**
1567
+ * @typedef {{[key: string]: string}} PlainLocaleStringBodyObject
1568
+ */
1569
+
1570
+ /**
1571
+ * @typedef {{
1572
+ * [key: string]: string|PlainNestedLocaleStringBodyObject
1573
+ * }} PlainNestedLocaleStringBodyObject
1574
+ */
1575
+
1576
+ /**
1577
+ * @typedef {object} SwitchCaseInfo
1578
+ * @property {boolean} [default=false] Whether this conditional is the default
1579
+ */
1580
+
1581
+ /**
1582
+ * Contains the type, the message, and optional info about the switch case.
1583
+ * @typedef {[string, string, SwitchCaseInfo?]} SwitchCaseArray
1584
+ */
1585
+
1586
+ /**
1587
+ * @typedef {Object<string, SwitchCaseArray>} SwitchArray
1588
+ */
1589
+
1590
+ /**
1591
+ * @typedef {Object<string, SwitchArray>} SwitchArrays
1592
+ */
1593
+
1594
+ /**
1595
+ * @typedef {object} SwitchCase
1596
+ * @property {string} message The locale message with any formatting
1597
+ * place-holders; defaults to use of any single conditional
1598
+ * @property {string} [description] A description to add for translators
1599
+ */
1600
+
1601
+ /**
1602
+ * @typedef {Object<string, SwitchCase>} Switch
1603
+ */
1604
+
1605
+ /**
1606
+ * @typedef {Object<string, Switch>} Switches
1607
+ */
1608
+
1609
+ /**
1610
+ * @typedef {object} RichLocaleStringSubObject
1611
+ * @property {string} message The locale message with any formatting
1612
+ * place-holders; defaults to use of any single conditional
1613
+ * @property {string} [description] A description to add for translators
1614
+ * @property {Switches} [switches] Conditionals
1615
+ */
1616
+
1617
+ /**
1618
+ * @typedef {{
1619
+ * [key: string]: RichLocaleStringSubObject
1620
+ * }} RichLocaleStringBodyObject
1621
+ */
1622
+
1623
+ /**
1624
+ * @typedef {{
1625
+ * [key: string]: RichLocaleStringSubObject|RichNestedLocaleStringBodyObject
1626
+ * }} RichNestedLocaleStringBodyObject
1627
+ */
1628
+
1629
+ /**
1630
+ * Takes a base path and locale and gives a URL.
1631
+ * @callback LocaleResolver
1632
+ * @param {string} localesBasePath (Trailing slash optional)
1633
+ * @param {string} locale BCP-47 language string
1634
+ * @returns {string|false} URL of the locale file to be fetched
1635
+ */
1636
+
1637
+ /**
1638
+ * @typedef {[
1639
+ * Date|number, Date|number, (Intl.DateTimeFormatOptions|undefined)?
1640
+ * ]} DateRange
1641
+ */
1642
+
1643
+ /**
1644
+ * @typedef {string|string[]|number|Date|DateRange|
1645
+ * Element|Node|SubstitutionCallback|
1646
+ * NumberInfo|PluralInfo|CurrencyInfo|LanguageInfo|ScriptInfo|
1647
+ * DatetimeRangeInfo|DateRangeInfo|RegionInfo|DateTimeInfo|DateInfo|
1648
+ * ListInfo|RelativeTimeInfo
1649
+ * } SubstitutionObjectValue
1650
+ */
1651
+
1652
+ /**
1653
+ * @typedef {{
1654
+ * [key: string]: SubstitutionObjectValue
1655
+ * }} SubstitutionObject
1656
+ */
1657
+
1658
+ /**
1659
+ * @type {LocaleResolver}
1660
+ */
1661
+ var defaultLocaleResolver = function defaultLocaleResolver(localesBasePath, locale) {
1662
+ if (typeof localesBasePath !== 'string') {
1663
+ throw new TypeError('`defaultLocaleResolver` expects a string `localesBasePath`.');
1664
+ }
1665
+ if (typeof locale !== 'string') {
1666
+ throw new TypeError('`defaultLocaleResolver` expects a string `locale`.');
1667
+ }
1668
+ if (/[\.\/\\]/.test(locale)) {
1669
+ throw new TypeError('Locales cannot use file-reserved characters, `.`, `/` or `\\`');
1670
+ }
1671
+ return "".concat(localesBasePath.replace(/\/$/, ''), "/_locales/").concat(locale, "/messages.json");
1672
+ };
1673
+
1674
+ /**
1675
+ * @typedef {number} Integer
1676
+ */
1677
+
1678
+ /**
1679
+ * @callback Replace
1680
+ * @param {{
1681
+ * str: string,
1682
+ * substs?: import('./defaultLocaleResolver.js').SubstitutionObject,
1683
+ * formatter?: import('./Formatter.js').RegularFormatter|
1684
+ * import('./Formatter.js').LocalFormatter|
1685
+ * import('./Formatter.js').SwitchFormatter
1686
+ * }} cfg
1687
+ * @returns {string}
1688
+ */
1689
+
1690
+ /**
1691
+ * @callback ProcessSubstitutions
1692
+ * @param {{
1693
+ * str: string,
1694
+ * substs?: import('./defaultLocaleResolver.js').SubstitutionObject,
1695
+ * formatter?: import('./Formatter.js').RegularFormatter|
1696
+ * import('./Formatter.js').LocalFormatter|
1697
+ * import('./Formatter.js').SwitchFormatter
1698
+ * }} cfg
1699
+ * @returns {(string|Node)[]}
1700
+ */
1701
+
1702
+ /**
1703
+ * Callback to return a string or array of nodes and strings based on
1704
+ * a localized string, substitutions object, and other metadata.
1705
+ *
1706
+ * `string` - The localized string.
1707
+ * `dom` - If substitutions known to contain DOM, can be set
1708
+ * to `true` to optimize.
1709
+ * `usedKeys` - Array for tracking which keys have been used. Defaults
1710
+ * to empty array.
1711
+ * `substitutions` - The formatting substitutions object.
1712
+ * `allSubstitutions` - The
1713
+ * callback or array composed thereof for applying to each substitution.
1714
+ * `locale` - The successfully resolved locale
1715
+ * `locals` - The local section.
1716
+ * `switches` - The switch section.
1717
+ * `maximumLocalNestingDepth` - Depth of local variable resolution to
1718
+ * check before reporting a recursion error. Defaults to 3.
1719
+ * `missingSuppliedFormatters` - Callback
1720
+ * supplied key to throw if the supplied key is present (if
1721
+ * `throwOnMissingSuppliedFormatters` is enabled). Defaults to no-op.
1722
+ * `checkExtraSuppliedFormatters` - No
1723
+ * argument callback to check if any formatters are not present in `string`
1724
+ * (if `throwOnExtraSuppliedFormatters` is enabled). Defaults to no-op.
1725
+ * @typedef {(cfg: {
1726
+ * string: string,
1727
+ * dom?: boolean,
1728
+ * usedKeys: string[],
1729
+ * substitutions: import('./defaultLocaleResolver.js').SubstitutionObject,
1730
+ * allSubstitutions?: ?(
1731
+ * import('./defaultAllSubstitutions.js').AllSubstitutionCallback|
1732
+ * import('./defaultAllSubstitutions.js').AllSubstitutionCallback[]
1733
+ * )
1734
+ * locale: string|undefined,
1735
+ * locals?: import('./getMessageForKeyByStyle.js').LocalObject|undefined,
1736
+ * switches: import('./defaultLocaleResolver.js').Switches|undefined,
1737
+ * maximumLocalNestingDepth?: Integer,
1738
+ * missingSuppliedFormatters: import('./getDOMForLocaleString.js').
1739
+ * MissingSuppliedFormattersCallback,
1740
+ * checkExtraSuppliedFormatters: import('./getDOMForLocaleString.js').
1741
+ * CheckExtraSuppliedFormattersCallback
1742
+ * }) => string|(Node|string)[]} InsertNodesCallback
1743
+ */
1744
+
1745
+ /**
1746
+ * @type {InsertNodesCallback}
1747
+ */
1748
+ var defaultInsertNodes = function defaultInsertNodes(_ref) {
1749
+ var string = _ref.string,
1750
+ dom = _ref.dom,
1751
+ usedKeys = _ref.usedKeys,
1752
+ substitutions = _ref.substitutions,
1753
+ allSubstitutions = _ref.allSubstitutions,
1754
+ locale = _ref.locale,
1755
+ locals = _ref.locals,
1756
+ switches = _ref.switches,
1757
+ _ref$maximumLocalNest = _ref.maximumLocalNestingDepth,
1758
+ maximumLocalNestingDepth = _ref$maximumLocalNest === void 0 ? 3 : _ref$maximumLocalNest,
1759
+ missingSuppliedFormatters = _ref.missingSuppliedFormatters,
1760
+ checkExtraSuppliedFormatters = _ref.checkExtraSuppliedFormatters;
1761
+ if (typeof maximumLocalNestingDepth !== 'number') {
1762
+ throw new TypeError('`maximumLocalNestingDepth` must be a number.');
1763
+ }
1764
+ var addFunctionKeys = function addFunctionKeys() {
1765
+ Object.entries(substitutions).forEach(function (_ref2) {
1766
+ var _ref3 = _slicedToArray(_ref2, 2),
1767
+ key = _ref3[0],
1768
+ value = _ref3[1];
1769
+ if (typeof value === 'function') {
1770
+ usedKeys.push(key);
1771
+ }
1772
+ });
1773
+ };
1774
+ addFunctionKeys();
1775
+ var localFormatter = new LocalFormatter( /** @type {import('./getMessageForKeyByStyle.js').LocalObject} */locals);
1776
+ var regularFormatter = new RegularFormatter(substitutions);
1777
+ var switchFormatter = new SwitchFormatter( /** @type {import('./defaultLocaleResolver.js').Switches} */
1778
+ switches, {
1779
+ substitutions: substitutions
1780
+ });
1781
+
1782
+ // eslint-disable-next-line max-len
1783
+ // eslint-disable-next-line prefer-named-capture-group, unicorn/no-unsafe-regex
1784
+ var formattingRegex = /(\\*)\{((?:(?:[\0-\|~-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])|\\\})*?)(?:(\|)((?:[\0-\|~-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*))?\}/g;
1785
+ if (allSubstitutions) {
1786
+ allSubstitutions = Array.isArray(allSubstitutions) ? allSubstitutions : [allSubstitutions];
1787
+ }
1788
+
1789
+ /**
1790
+ * @param {{
1791
+ * key: string,
1792
+ * arg: string,
1793
+ * substs: import('./defaultLocaleResolver.js').SubstitutionObject
1794
+ * }} cfg
1795
+ * @returns {string|Node}
1796
+ */
1797
+ var getSubstitution = function getSubstitution(_ref4) {
1798
+ var key = _ref4.key,
1799
+ arg = _ref4.arg,
1800
+ substs = _ref4.substs;
1801
+ /** @type {import('./defaultLocaleResolver.js').SubstitutionObjectValue} */
1802
+ var substitution;
1803
+ var isLocalKey =
1804
+ /**
1805
+ * @type {typeof import('./Formatter.js').LocalFormatter}
1806
+ */
1807
+ localFormatter.constructor.isMatchingKey(key);
1808
+ if (isLocalKey) {
1809
+ substitution = localFormatter.getSubstitution(key);
1810
+ } else if (
1811
+ /**
1812
+ * @type {typeof import('./Formatter.js').SwitchFormatter}
1813
+ */
1814
+ switchFormatter.constructor.isMatchingKey(key)) {
1815
+ substitution = switchFormatter.getSubstitution(key, {
1816
+ // eslint-disable-next-line object-shorthand -- TS casting
1817
+ locale: /** @type {string} */locale,
1818
+ usedKeys: usedKeys,
1819
+ arg: arg,
1820
+ missingSuppliedFormatters: missingSuppliedFormatters
1821
+ });
1822
+ } else {
1823
+ substitution = substs[key];
1824
+ if (typeof substitution === 'function') {
1825
+ substitution = substitution({
1826
+ arg: arg,
1827
+ key: key
1828
+ });
1829
+ }
1830
+ }
1831
+ // Todo: Could support resolving locals within arguments
1832
+ // Todo: Even for `null` `allSubstitutions`, we could have
1833
+ // a mode to throw for non-string/non-DOM (non-numbers?),
1834
+ // or whatever is not likely intended as a target for `toString()`.
1835
+ if (allSubstitutions) {
1836
+ substitution = /** @type {string|Node} */
1837
+ /**
1838
+ * @type {import('./defaultAllSubstitutions.js').
1839
+ * AllSubstitutionCallback[]
1840
+ * }
1841
+ */allSubstitutions.reduce(
1842
+ /**
1843
+ * @param {import('./defaultLocaleResolver.js').
1844
+ * SubstitutionObjectValue} subst
1845
+ * @param {import('./defaultAllSubstitutions.js').
1846
+ * AllSubstitutionCallback} allSubst
1847
+ * @returns {string|Node}
1848
+ */
1849
+ function (subst, allSubst) {
1850
+ return allSubst({
1851
+ value: subst,
1852
+ arg: arg,
1853
+ key: key,
1854
+ locale: locale
1855
+ });
1856
+ }, substitution);
1857
+ } else if (arg && /^(?:NUMBER|DATE(?:TIME|RANGE|TIMERANGE)?|REGION|LANGUAGE|SCRIPT|CURRENCY|RELATIVE|LIST)(?:\||$)/.test(arg)) {
1858
+ substitution = defaultAllSubstitutions({
1859
+ value: substitution,
1860
+ arg: arg,
1861
+ key: key,
1862
+ locale: locale
1863
+ });
1864
+ }
1865
+
1866
+ // Change this and return type if other substitutions possible
1867
+ return (/** @type {string|Node} */substitution
1868
+ );
1869
+ };
1870
+ var recursiveLocalCount = 1;
1871
+ /**
1872
+ * @param {{
1873
+ * substitution: string|Node,
1874
+ * ky: string,
1875
+ * arg: string,
1876
+ * processSubsts: Replace|ProcessSubstitutions
1877
+ * }} cfg
1878
+ * @returns {number|string|Node|(string|Node)[]}
1879
+ */
1880
+ var checkLocalVars = function checkLocalVars(_ref5) {
1881
+ var substitution = _ref5.substitution,
1882
+ ky = _ref5.ky,
1883
+ arg = _ref5.arg,
1884
+ processSubsts = _ref5.processSubsts;
1885
+ /** @type {number|string|Node|(string|Node)[]} */
1886
+ var subst = substitution;
1887
+ if (typeof substitution === 'string' && substitution.includes('{')) {
1888
+ if (recursiveLocalCount++ > maximumLocalNestingDepth) {
1889
+ throw new TypeError('Too much recursion in local variables.');
1890
+ }
1891
+ if ( /** @type {typeof import('./Formatter.js').LocalFormatter} */localFormatter.constructor.isMatchingKey(ky)) {
1892
+ var extraSubsts = substitutions;
1893
+ var localFormatters;
1894
+ if (arg) {
1895
+ localFormatters = parseJSONExtra(arg);
1896
+ extraSubsts = _objectSpread2(_objectSpread2({}, substitutions), localFormatters);
1897
+ }
1898
+ subst = processSubsts({
1899
+ str: substitution,
1900
+ substs: extraSubsts,
1901
+ formatter: localFormatter
1902
+ });
1903
+ if (localFormatters) {
1904
+ checkExtraSuppliedFormatters({
1905
+ substitutions: localFormatters
1906
+ });
1907
+ }
1908
+ } else if ( /** @type {typeof import('./Formatter.js').SwitchFormatter} */
1909
+ switchFormatter.constructor.isMatchingKey(ky)) {
1910
+ subst = processSubsts({
1911
+ str: substitution
1912
+ });
1913
+ }
1914
+ }
1915
+ return subst;
1916
+ };
1917
+
1918
+ // Give chance to avoid this block when known to contain DOM
1919
+ if (!dom) {
1920
+ // Run this block to optimize non-DOM substitutions
1921
+ var returnsDOM = false;
1922
+
1923
+ /** @type {Replace} */
1924
+ var replace = function replace(_ref6) {
1925
+ var str = _ref6.str,
1926
+ _ref6$substs = _ref6.substs,
1927
+ substs = _ref6$substs === void 0 ? substitutions : _ref6$substs,
1928
+ _ref6$formatter = _ref6.formatter,
1929
+ formatter = _ref6$formatter === void 0 ? regularFormatter : _ref6$formatter;
1930
+ return str.replace(formattingRegex,
1931
+ /**
1932
+ * @param {string} _
1933
+ * @param {string} esc
1934
+ * @param {string} ky
1935
+ * @param {string} pipe
1936
+ * @param {string} arg
1937
+ * @returns {string}
1938
+ */
1939
+ function (_, esc, ky, pipe, arg) {
1940
+ if (esc.length % 2) {
1941
+ return _;
1942
+ }
1943
+ if (missingSuppliedFormatters({
1944
+ key: ky,
1945
+ formatter: formatter
1946
+ })) {
1947
+ return _;
1948
+ }
1949
+ /** @type {string|number|Node|(string|Node)[]} */
1950
+ var substitution = getSubstitution({
1951
+ key: ky,
1952
+ arg: arg,
1953
+ substs: substs
1954
+ });
1955
+ substitution = checkLocalVars({
1956
+ substitution: substitution,
1957
+ ky: ky,
1958
+ arg: arg,
1959
+ processSubsts: replace
1960
+ });
1961
+ returnsDOM = returnsDOM || substitution !== null && _typeof(substitution) === 'object' && 'nodeType' in substitution;
1962
+ usedKeys.push(ky);
1963
+ return esc + substitution;
1964
+ });
1965
+ };
1966
+ var ret = replace({
1967
+ str: string
1968
+ });
1969
+ if (!returnsDOM) {
1970
+ checkExtraSuppliedFormatters({
1971
+ substitutions: substitutions
1972
+ });
1973
+ usedKeys.length = 0;
1974
+ addFunctionKeys();
1975
+ return unescapeBackslashes(ret);
1976
+ }
1977
+ usedKeys.length = 0;
1978
+ addFunctionKeys();
1979
+ }
1980
+ recursiveLocalCount = 1;
1981
+
1982
+ /** @type {ProcessSubstitutions} */
1983
+ var processSubstitutions = function processSubstitutions(_ref7) {
1984
+ var str = _ref7.str,
1985
+ _ref7$substs = _ref7.substs,
1986
+ substs = _ref7$substs === void 0 ? substitutions : _ref7$substs,
1987
+ _ref7$formatter = _ref7.formatter,
1988
+ formatter = _ref7$formatter === void 0 ? regularFormatter : _ref7$formatter;
1989
+ /** @type {(string|Node)[]} */
1990
+ var nodes = [];
1991
+
1992
+ // Copy to ensure we are resetting index on each instance (manually
1993
+ // resetting on `formattingRegex` is problematic with recursion that
1994
+ // uses the same regex copy)
1995
+ var regex = new RegExp(formattingRegex, 'gu');
1996
+
1997
+ /**
1998
+ * @param {...(string|Node)} args
1999
+ */
2000
+ var push = function push() {
2001
+ nodes.push.apply(nodes, arguments);
2002
+ };
2003
+ processRegex(regex, str, {
2004
+ extra: push,
2005
+ onMatch: function onMatch(_, esc, ky, pipe, arg) {
2006
+ if (missingSuppliedFormatters({
2007
+ key: ky,
2008
+ formatter: formatter
2009
+ })) {
2010
+ push(_);
2011
+ } else {
2012
+ if (esc.length) {
2013
+ push(esc);
2014
+ }
2015
+
2016
+ /** @type {string|number|Node|(string|Node)[]} */
2017
+ var substitution = getSubstitution({
2018
+ key: ky,
2019
+ arg: arg,
2020
+ substs: substs
2021
+ });
2022
+ substitution = checkLocalVars({
2023
+ substitution: substitution,
2024
+ ky: ky,
2025
+ arg: arg,
2026
+ processSubsts: processSubstitutions
2027
+ });
2028
+ if (Array.isArray(substitution)) {
2029
+ push.apply(void 0, _toConsumableArray(substitution));
2030
+ } else if (
2031
+ // Clone so that multiple instances may be added (and no
2032
+ // side effects to user code)
2033
+ substitution && _typeof(substitution) === 'object' && 'nodeType' in substitution) {
2034
+ push(substitution.cloneNode(true));
2035
+ } else {
2036
+ // Why no number here?
2037
+ push( /** @type {string} */substitution);
2038
+ }
2039
+ }
2040
+ usedKeys.push(ky);
2041
+ }
2042
+ });
2043
+ return nodes;
2044
+ };
2045
+ var nodes = processSubstitutions({
2046
+ str: string
2047
+ });
2048
+ checkExtraSuppliedFormatters({
2049
+ substitutions: substitutions
2050
+ });
2051
+ usedKeys.length = 0;
2052
+ return nodes.map(function (node) {
2053
+ if (typeof node === 'string') {
2054
+ return unescapeBackslashes(node);
2055
+ }
2056
+ return node;
2057
+ });
2058
+ };
2059
+
2060
+ /**
2061
+ * @callback KeyCheckerConverterCallback
2062
+ * @param {string|string[]} key By default may be an array (if the type ends
2063
+ * with "Nested") or a string, but a non-default validator may do otherwise.
2064
+ * @param {"plain"|"plainNested"|"rich"|
2065
+ * "richNested"|
2066
+ * import('./getMessageForKeyByStyle.js').MessageStyleCallback
2067
+ * } messageStyle
2068
+ * @throws {TypeError}
2069
+ * @returns {string} The converted (or unconverted) key
2070
+ */
2071
+
2072
+ /**
2073
+ * @type {KeyCheckerConverterCallback}
2074
+ */
2075
+ function defaultKeyCheckerConverter(key, messageStyle) {
2076
+ if (Array.isArray(key) && key.every(function (k) {
2077
+ return typeof k === 'string';
2078
+ }) && typeof messageStyle === 'string' && messageStyle.endsWith('Nested')) {
2079
+ return key.map(function (k) {
2080
+ return k.replace( /*#__PURE__*/_wrapRegExp(/(\\+)/g, {
2081
+ backslashes: 1
2082
+ }), '\\$<backslashes>').replace(/\./g, '\\.');
2083
+ }).join('.');
2084
+ }
2085
+ if (typeof key !== 'string') {
2086
+ throw new TypeError('`key` is expected to be a string (or array of strings for nested style)');
2087
+ }
2088
+ return key;
2089
+ }
2090
+
2091
+ /**
2092
+ * @typedef {LocaleBody} LocalObject
2093
+ */
2094
+
2095
+ /**
2096
+ * May also contain language code and direction, translator name and
2097
+ * contact, etc., but no defaults currently apply besides reserving `locals`
2098
+ * @typedef {object} LocaleHead
2099
+ * @property {LocalObject} [locals]
2100
+ * @property {import('./defaultLocaleResolver.js').Switches} [switches]
2101
+ */
2102
+
2103
+ /**
2104
+ * @typedef {import('./defaultLocaleResolver.js').
2105
+ * RichNestedLocaleStringBodyObject|
2106
+ * import('./defaultLocaleResolver.js').RichLocaleStringBodyObject|
2107
+ * import('./defaultLocaleResolver.js').PlainLocaleStringBodyObject|
2108
+ * import('./defaultLocaleResolver.js').PlainNestedLocaleStringBodyObject|
2109
+ * object
2110
+ * } LocaleBody
2111
+ */
2112
+
2113
+ /**
2114
+ * @typedef {object} LocaleObject
2115
+ * @property {LocaleHead} [head]
2116
+ * @property {LocaleBody} body
2117
+ */
2118
+
2119
+ /**
2120
+ * @typedef {object} MessageStyleCallbackResult
2121
+ * @property {string} value Regardless of message style, will contain
2122
+ * the string result
2123
+ * @property {import(
2124
+ * './defaultLocaleResolver.js'
2125
+ * ).RichLocaleStringSubObject} [info] Full info on the localized item
2126
+ * (for rich message styles only)
2127
+ */
2128
+
2129
+ /**
2130
+ * @callback MessageStyleCallback
2131
+ * @param {LocaleObject} obj The exact
2132
+ * format depends on the `cfg.defaults` of `i18n`
2133
+ * @param {string} key
2134
+ * @returns {false|MessageStyleCallbackResult} If `false`, will resort to default
2135
+ */
2136
+
2137
+ /* eslint-disable max-len */
2138
+ /**
2139
+ * @param {object} [cfg]
2140
+ * @param {"richNested"|"rich"|"plain"|"plainNested"|MessageStyleCallback} [cfg.messageStyle="richNested"]
2141
+ * @returns {MessageStyleCallback}
2142
+ */
2143
+ var getMessageForKeyByStyle = function getMessageForKeyByStyle() {
2144
+ var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
2145
+ _ref$messageStyle = _ref.messageStyle,
2146
+ messageStyle = _ref$messageStyle === void 0 ? 'richNested' : _ref$messageStyle;
2147
+ return typeof messageStyle === 'function' ? messageStyle : messageStyle === 'richNested' ? function (mainObj, key) {
2148
+ var obj =
2149
+ /**
2150
+ * @type {import('./defaultLocaleResolver.js').
2151
+ * RichNestedLocaleStringBodyObject
2152
+ * }
2153
+ */
2154
+ mainObj && _typeof(mainObj) === 'object' && mainObj.body;
2155
+
2156
+ /**
2157
+ * @type {string[]}
2158
+ */
2159
+ var keys = [];
2160
+ // eslint-disable-next-line prefer-named-capture-group
2161
+ var possiblyEscapedCharPattern = /(\\*)\./g;
2162
+
2163
+ /**
2164
+ * @param {string} val
2165
+ * @returns {void}
2166
+ */
2167
+ var mergeWithPreviousOrStart = function mergeWithPreviousOrStart(val) {
2168
+ if (!keys.length) {
2169
+ keys[0] = '';
2170
+ }
2171
+ keys[keys.length - 1] += val;
2172
+ };
2173
+ processRegex(possiblyEscapedCharPattern, key, {
2174
+ // If odd, this is just an escaped dot, so merge content with
2175
+ // any previous
2176
+ extra: mergeWithPreviousOrStart,
2177
+ onMatch: function onMatch(_, esc) {
2178
+ // If even, there are no backslashes, or they are just escaped
2179
+ // backslashes and not an escaped dot, so start anew, though
2180
+ // first merge any backslashes
2181
+ mergeWithPreviousOrStart(esc);
2182
+ keys.push('');
2183
+ }
2184
+ });
2185
+ var keysUnescaped = keys.map(function (ky) {
2186
+ return unescapeBackslashes(ky);
2187
+ });
2188
+
2189
+ /**
2190
+ * @type {false|{
2191
+ * value: string|undefined,
2192
+ * info: import('./defaultLocaleResolver.js').
2193
+ * RichLocaleStringSubObject
2194
+ * }}
2195
+ */
2196
+ var ret = false;
2197
+ var currObj = obj;
2198
+ keysUnescaped.some(function (ky, i, kys) {
2199
+ if (!currObj || _typeof(currObj) !== 'object') {
2200
+ return true;
2201
+ }
2202
+ if (
2203
+ // If specified key is too deep, we should fail
2204
+ i === kys.length - 1 && ky in currObj && currObj[ky] && _typeof(currObj[ky]) === 'object' && 'message' in currObj[ky] &&
2205
+ // NECESSARY FOR SECURITY ON UNTRUSTED LOCALES
2206
+ typeof currObj[ky].message === 'string') {
2207
+ ret = {
2208
+ value: /** @type {string} */currObj[ky].message,
2209
+ info:
2210
+ /**
2211
+ * @type {import('./defaultLocaleResolver.js').
2212
+ * RichLocaleStringSubObject}
2213
+ */
2214
+ currObj[ky]
2215
+ };
2216
+ }
2217
+ currObj =
2218
+ /**
2219
+ * @type {import('./defaultLocaleResolver.js').
2220
+ * RichNestedLocaleStringBodyObject
2221
+ * }
2222
+ */
2223
+ currObj[ky];
2224
+ return false;
2225
+ });
2226
+ return ret;
2227
+ } : messageStyle === 'rich' ? function (mainObj, key) {
2228
+ var obj =
2229
+ /**
2230
+ * @type {import('./defaultLocaleResolver.js').
2231
+ * RichLocaleStringBodyObject
2232
+ * }
2233
+ */
2234
+ mainObj && _typeof(mainObj) === 'object' && mainObj.body;
2235
+ if (obj && _typeof(obj) === 'object' && key in obj && obj[key] && _typeof(obj[key]) === 'object' && 'message' in obj[key] &&
2236
+ // NECESSARY FOR SECURITY ON UNTRUSTED LOCALES
2237
+ typeof obj[key].message === 'string') {
2238
+ return {
2239
+ value: obj[key].message,
2240
+ info: obj[key]
2241
+ };
2242
+ }
2243
+ return false;
2244
+ } : messageStyle === 'plain' ? function (mainObj, key) {
2245
+ var obj =
2246
+ /**
2247
+ * @type {import('./defaultLocaleResolver.js').
2248
+ * PlainLocaleStringBodyObject
2249
+ * }
2250
+ */
2251
+ mainObj && _typeof(mainObj) === 'object' && mainObj.body;
2252
+ if (obj && _typeof(obj) === 'object' && key in obj && obj[key] && typeof obj[key] === 'string') {
2253
+ return {
2254
+ value: obj[key]
2255
+ };
2256
+ }
2257
+ return false;
2258
+ } : messageStyle === 'plainNested' ? function (mainObj, key) {
2259
+ var obj =
2260
+ /**
2261
+ * @type {import('./defaultLocaleResolver.js').
2262
+ * PlainNestedLocaleStringBodyObject
2263
+ * }
2264
+ */
2265
+ mainObj && _typeof(mainObj) === 'object' && mainObj.body;
2266
+ if (obj && _typeof(obj) === 'object') {
2267
+ // Should really be counting that it is an odd number
2268
+ // of backslashes only
2269
+ var keys = key.split(/(?<!\\)\./);
2270
+ var value = keys.reduce(
2271
+ /**
2272
+ * @param {null|string|import('./defaultLocaleResolver.js').
2273
+ * PlainNestedLocaleStringBodyObject} o
2274
+ * @param {string} k
2275
+ * @returns {null|string|import('./defaultLocaleResolver.js').
2276
+ * PlainNestedLocaleStringBodyObject}
2277
+ */
2278
+ function (o, k) {
2279
+ if (o && _typeof(o) === 'object' && o[k]) {
2280
+ return o[k];
2281
+ }
2282
+ return null;
2283
+ }, obj);
2284
+ if (value && typeof value === 'string') {
2285
+ return {
2286
+ value: value
2287
+ };
2288
+ }
2289
+ }
2290
+ return false;
2291
+ } : function () {
2292
+ throw new TypeError("Unknown `messageStyle` ".concat(messageStyle));
2293
+ }();
2294
+ };
2295
+
2296
+ /**
2297
+ * @param {object} cfg
2298
+ * @param {string|false} [cfg.message] If present, this string will be
2299
+ * the return value.
2300
+ * @param {false|null|undefined|
2301
+ * import('./getMessageForKeyByStyle.js').LocaleObject
2302
+ * } [cfg.defaults]
2303
+ * @param {"richNested"|"rich"|"plain"|"plainNested"|
2304
+ * import('./getMessageForKeyByStyle.js').MessageStyleCallback
2305
+ * } [cfg.messageStyle="richNested"]
2306
+ * @param {import('./getMessageForKeyByStyle.js').
2307
+ * MessageStyleCallback
2308
+ * } [cfg.messageForKey] Defaults to getting `MessageStyleCallback` based
2309
+ * on `messageStyle`
2310
+ * @param {string} cfg.key Key to check against object of strings;
2311
+ * used to find a default if no string `message` is provided.
2312
+ * @returns {string}
2313
+ */
2314
+ var getStringFromMessageAndDefaults = function getStringFromMessageAndDefaults(_ref) {
2315
+ var message = _ref.message,
2316
+ defaults = _ref.defaults,
2317
+ messageStyle = _ref.messageStyle,
2318
+ _ref$messageForKey = _ref.messageForKey,
2319
+ messageForKey = _ref$messageForKey === void 0 ? getMessageForKeyByStyle({
2320
+ messageStyle: messageStyle
2321
+ }) : _ref$messageForKey,
2322
+ key = _ref.key;
2323
+ // NECESSARY CHECK FOR SECURITY ON UNTRUSTED LOCALES
2324
+ /** @type {string|false} */
2325
+ var str;
2326
+ if (typeof message === 'string') {
2327
+ str = message;
2328
+ } else if (defaults === false || defaults === undefined || defaults === null) {
2329
+ str = false;
2330
+ } else if (defaults && _typeof(defaults) === 'object') {
2331
+ var msg = messageForKey(defaults, key);
2332
+ str = msg ? msg.value : msg;
2333
+ } else {
2334
+ throw new TypeError("Default locale strings must resolve to `false`, " + "nullish, or an object!");
2335
+ }
2336
+ if (str === false) {
2337
+ throw new Error("Key value not found for key: (".concat(key, ")"));
2338
+ }
2339
+ return str;
2340
+ };
2341
+
2342
+ /**
2343
+ * @typedef {number} Integer
2344
+ */
2345
+
2346
+ /**
2347
+ * @callback CheckExtraSuppliedFormattersCallback
2348
+ * @param {import('./defaultLocaleResolver.js').SubstitutionObject|{
2349
+ * substitutions: import('./defaultLocaleResolver.js').SubstitutionObject
2350
+ * }} substs (Why is an arg. of `substitutions` being passed in?)
2351
+ * @throws {Error} Upon an extra formatting key being found
2352
+ * @returns {void}
2353
+ */
2354
+
2355
+ /**
2356
+ * @typedef {(
2357
+ * cfg: {
2358
+ * key: string,
2359
+ * formatter: import('./Formatter.js').LocalFormatter|
2360
+ * import('./Formatter.js').RegularFormatter|
2361
+ * import('./Formatter.js').SwitchFormatter
2362
+ * }
2363
+ * ) => boolean} MissingSuppliedFormattersCallback
2364
+ */
2365
+
2366
+ /**
2367
+ *
2368
+ * @param {object} cfg
2369
+ * @param {string} cfg.string
2370
+ * @param {string} [cfg.locale] The (possibly already resolved) locale
2371
+ * for use by configuring formatters
2372
+ * @param {import('./getMessageForKeyByStyle.js').LocalObject} [cfg.locals]
2373
+ * @param {import('./defaultLocaleResolver.js').Switches} [cfg.switches]
2374
+ * @param {Integer} [cfg.maximumLocalNestingDepth=3]
2375
+ * @param {?(import('./defaultAllSubstitutions.js').AllSubstitutionCallback|
2376
+ * import('./defaultAllSubstitutions.js').AllSubstitutionCallback[])
2377
+ * } [cfg.allSubstitutions=[defaultAllSubstitutions]]
2378
+ * @param {import('./defaultInsertNodes.js').InsertNodesCallback
2379
+ * } [cfg.insertNodes=defaultInsertNodes]
2380
+ * @param {false|import('./defaultLocaleResolver.js').SubstitutionObject
2381
+ * } [cfg.substitutions=false]
2382
+ * @param {boolean} [cfg.dom=false]
2383
+ * @param {boolean} [cfg.forceNodeReturn=false]
2384
+ * @param {boolean} [cfg.throwOnMissingSuppliedFormatters=true]
2385
+ * @param {boolean} [cfg.throwOnExtraSuppliedFormatters=true]
2386
+ * @returns {string|Text|DocumentFragment}
2387
+ */
2388
+ var getDOMForLocaleString = function getDOMForLocaleString(_ref) {
2389
+ var string = _ref.string,
2390
+ locale = _ref.locale,
2391
+ locals = _ref.locals,
2392
+ switches = _ref.switches;
2393
+ _ref.maximumLocalNestingDepth;
2394
+ var _ref$allSubstitutions = _ref.allSubstitutions,
2395
+ allSubstitutions = _ref$allSubstitutions === void 0 ? [defaultAllSubstitutions] : _ref$allSubstitutions,
2396
+ _ref$insertNodes = _ref.insertNodes,
2397
+ insertNodes = _ref$insertNodes === void 0 ? defaultInsertNodes : _ref$insertNodes,
2398
+ _ref$substitutions = _ref.substitutions,
2399
+ substitutions = _ref$substitutions === void 0 ? false : _ref$substitutions,
2400
+ _ref$dom = _ref.dom,
2401
+ dom = _ref$dom === void 0 ? false : _ref$dom,
2402
+ _ref$forceNodeReturn = _ref.forceNodeReturn,
2403
+ forceNodeReturn = _ref$forceNodeReturn === void 0 ? false : _ref$forceNodeReturn,
2404
+ _ref$throwOnMissingSu = _ref.throwOnMissingSuppliedFormatters,
2405
+ throwOnMissingSuppliedFormatters = _ref$throwOnMissingSu === void 0 ? true : _ref$throwOnMissingSu,
2406
+ _ref$throwOnExtraSupp = _ref.throwOnExtraSuppliedFormatters,
2407
+ throwOnExtraSuppliedFormatters = _ref$throwOnExtraSupp === void 0 ? true : _ref$throwOnExtraSupp;
2408
+ if (typeof string !== 'string') {
2409
+ throw new TypeError('An options object with a `string` property set to a string must ' + 'be provided for `getDOMForLocaleString`.');
2410
+ }
2411
+
2412
+ /**
2413
+ * @param {string} str
2414
+ * @returns {Text|string}
2415
+ */
2416
+ var stringOrTextNode = function stringOrTextNode(str) {
2417
+ var _doc = getDocument();
2418
+ return forceNodeReturn ? /** @type {Document} */_doc.createTextNode(str) : str;
2419
+ };
2420
+
2421
+ /** @type {string[]} */
2422
+ var usedKeys = [];
2423
+
2424
+ /**
2425
+ * @type {CheckExtraSuppliedFormattersCallback}
2426
+ */
2427
+ var checkExtraSuppliedFormatters = function checkExtraSuppliedFormatters(_ref2) {
2428
+ var substs = _ref2.substitutions;
2429
+ if (throwOnExtraSuppliedFormatters) {
2430
+ Object.keys(substs).forEach(function (key) {
2431
+ if (!usedKeys.includes(key)) {
2432
+ throw new Error("Extra formatting key: ".concat(key));
2433
+ }
2434
+ });
2435
+ }
2436
+ };
2437
+
2438
+ /**
2439
+ * @type {MissingSuppliedFormattersCallback}
2440
+ */
2441
+ var missingSuppliedFormatters = function missingSuppliedFormatters(_ref3) {
2442
+ var key = _ref3.key,
2443
+ formatter = _ref3.formatter;
2444
+ var matching = formatter.isMatch(key);
2445
+ if (
2446
+ /**
2447
+ * @type {typeof import('./Formatter.js').LocalFormatter|
2448
+ * typeof import('./Formatter.js').RegularFormatter|
2449
+ * typeof import('./Formatter.js').SwitchFormatter}
2450
+ */
2451
+ formatter.constructor.isMatchingKey(key) && !matching) {
2452
+ if (throwOnMissingSuppliedFormatters) {
2453
+ throw new Error("Missing formatting key: ".concat(key));
2454
+ }
2455
+ return true;
2456
+ }
2457
+ return false;
2458
+ };
2459
+ if (!substitutions && !allSubstitutions && !throwOnMissingSuppliedFormatters) {
2460
+ return stringOrTextNode(string);
2461
+ }
2462
+ if (!substitutions) {
2463
+ substitutions = {};
2464
+ }
2465
+ var nodes = insertNodes({
2466
+ string: string,
2467
+ dom: dom,
2468
+ usedKeys: usedKeys,
2469
+ substitutions: substitutions,
2470
+ allSubstitutions: allSubstitutions,
2471
+ locale: locale,
2472
+ locals: locals,
2473
+ switches: switches,
2474
+ missingSuppliedFormatters: missingSuppliedFormatters,
2475
+ checkExtraSuppliedFormatters: checkExtraSuppliedFormatters
2476
+ });
2477
+ if (typeof nodes === 'string') {
2478
+ return stringOrTextNode(nodes);
2479
+ }
2480
+ var _doc = getDocument();
2481
+ var container = /** @type {Document} */_doc.createDocumentFragment();
2482
+ container.append.apply(container, _toConsumableArray(nodes));
2483
+ return container;
2484
+ };
2485
+
2486
+ function _await$1(value, then, direct) {
2487
+ if (direct) {
2488
+ return then ? then(value) : value;
2489
+ }
2490
+ if (!value || !value.then) {
2491
+ value = Promise.resolve(value);
2492
+ }
2493
+ return then ? value.then(then) : value;
2494
+ } /**
2495
+ * Takes a locale and returns a new locale to check.
2496
+ * @callback LocaleMatcher
2497
+ * @param {string} locale The failed locale
2498
+ * @throws {Error} If there are no further hyphens left to check
2499
+ * @returns {string|Promise<string>} The new locale to check
2500
+ */
2501
+
2502
+ /**
2503
+ * @type {LocaleMatcher}
2504
+ */
2505
+
2506
+ function _async(f) {
2507
+ return function () {
2508
+ for (var args = [], i = 0; i < arguments.length; i++) {
2509
+ args[i] = arguments[i];
2510
+ }
2511
+ try {
2512
+ return Promise.resolve(f.apply(this, args));
2513
+ } catch (e) {
2514
+ return Promise.reject(e);
2515
+ }
2516
+ };
2517
+ }
2518
+ function _catch(body, recover) {
2519
+ try {
2520
+ var result = body();
2521
+ } catch (e) {
2522
+ return recover(e);
2523
+ }
2524
+ if (result && result.then) {
2525
+ return result.then(void 0, recover);
2526
+ }
2527
+ return result;
2528
+ }
2529
+ var defaultLocaleMatcher = function defaultLocaleMatcher(locale) {
2530
+ if (!locale.includes('-')) {
2531
+ throw new Error('Locale not available');
2532
+ }
2533
+ // Try without hyphen, i.e., the "lookup" algorithm:
2534
+ // See https://tools.ietf.org/html/rfc4647#section-3.4 and
2535
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
2536
+ return locale.replace(/\x2D(?:[\0-,\.-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*$/, '');
2537
+ };
2538
+
2539
+ /**
2540
+ * @param {object} cfg
2541
+ * @param {string} cfg.locale
2542
+ * @param {string[]} cfg.locales
2543
+ * @param {LocaleMatcher} [cfg.localeMatcher=defaultLocaleMatcher]
2544
+ * @returns {string|false}
2545
+ */
2546
+ var getMatchingLocale = function getMatchingLocale(_ref) {
2547
+ var locale = _ref.locale,
2548
+ locales = _ref.locales,
2549
+ _ref$localeMatcher = _ref.localeMatcher,
2550
+ localeMatcher = _ref$localeMatcher === void 0 ? defaultLocaleMatcher : _ref$localeMatcher;
2551
+ try {
2552
+ while (!locales.includes(locale)) {
2553
+ // Catch as `defaultLocaleMatcher` will throw if no hyphen found
2554
+ locale = localeMatcher(locale);
2555
+ }
2556
+ } catch (err) {
2557
+ return false;
2558
+ }
2559
+ return locale;
2560
+ };
2561
+
2562
+ /**
2563
+ * @typedef {object} LocaleObjectInfo
2564
+ * @property {import('./getMessageForKeyByStyle.js').
2565
+ * LocaleObject} strings The successfully retrieved locale strings
2566
+ * @property {string} locale The successfully resolved locale
2567
+ */
2568
+
2569
+ /**
2570
+ * @typedef {{
2571
+ * locales?: string[],
2572
+ * defaultLocales?: string[],
2573
+ * localesBasePath?: string,
2574
+ * localeResolver?: import('./defaultLocaleResolver.js').LocaleResolver,
2575
+ * localeMatcher?: "lookup"|LocaleMatcher
2576
+ * }} LocaleStringArgs
2577
+ */
2578
+
2579
+ /**
2580
+ * `locales` - BCP-47 language strings. Defaults to `navigator.languages`.
2581
+ * `defaultLocales` - Defaults to ["en-US"].
2582
+ * `localesBasePath` - Defaults to `.`.
2583
+ * `localeResolver` - Defaults to `defaultLocaleResolver`.
2584
+ * @typedef {(
2585
+ * cfg?: LocaleStringArgs
2586
+ * ) => Promise<LocaleObjectInfo>} LocaleStringFinder
2587
+ */
2588
+
2589
+ /**
2590
+ *
2591
+ * @type {LocaleStringFinder}
2592
+ */
2593
+ var findLocaleStrings = function findLocaleStrings() {
2594
+ var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
2595
+ locales = _ref2.locales,
2596
+ defaultLocales = _ref2.defaultLocales,
2597
+ localeResolver = _ref2.localeResolver,
2598
+ localesBasePath = _ref2.localesBasePath,
2599
+ localeMatcher = _ref2.localeMatcher;
2600
+ return (/** @type {Promise<LocaleObjectInfo>} */_findLocale({
2601
+ locales: locales,
2602
+ defaultLocales: defaultLocales,
2603
+ localeResolver: localeResolver,
2604
+ localesBasePath: localesBasePath,
2605
+ localeMatcher: localeMatcher
2606
+ })
2607
+ );
2608
+ };
2609
+
2610
+ /**
2611
+ * Resolves to the successfully resolved locale.
2612
+ * `locales` - BCP-47 language strings. Defaults to `navigator.languages`.
2613
+ * `defaultLocales` - Defaults to ["en-US"].
2614
+ * `localesBasePath` - Defaults to `.`.
2615
+ * `localeResolver` - Defaults to `defaultLocaleResolver`.
2616
+ * `localeMatcher`.
2617
+ * @typedef {(cfg?: LocaleStringArgs) => Promise<string>} LocaleFinder
2618
+ */
2619
+
2620
+ /**
2621
+ *
2622
+ * @type {LocaleFinder}
2623
+ */
2624
+ var findLocale = function findLocale() {
2625
+ var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
2626
+ locales = _ref3.locales,
2627
+ defaultLocales = _ref3.defaultLocales,
2628
+ localeResolver = _ref3.localeResolver,
2629
+ localesBasePath = _ref3.localesBasePath,
2630
+ localeMatcher = _ref3.localeMatcher;
2631
+ return (/** @type {Promise<string>} */_findLocale({
2632
+ locales: locales,
2633
+ defaultLocales: defaultLocales,
2634
+ localeResolver: localeResolver,
2635
+ localesBasePath: localesBasePath,
2636
+ localeMatcher: localeMatcher,
2637
+ headOnly: true
2638
+ })
2639
+ );
2640
+ };
2641
+
2642
+ /**
2643
+ * @type {(
2644
+ * cfg: LocaleStringArgs & {
2645
+ * headOnly?: boolean
2646
+ * }
2647
+ * ) => Promise<string|LocaleObjectInfo>} Also has a `headOnly` boolean
2648
+ * property to determine whether to make a simple HEAD and resolve to
2649
+ * the locale rather than locale and contents
2650
+ */
2651
+ var _findLocale = _async(function (_ref4) {
2652
+ /**
2653
+ * @callback getLocale
2654
+ * @throws {SyntaxError|TypeError|Error}
2655
+ * @param {string} locale
2656
+ * @returns {Promise<LocaleObjectInfo|string>}
2657
+ */
2658
+ var getLocale = _async(function (locale) {
2659
+ if (typeof locale !== 'string') {
2660
+ throw new TypeError('Non-string locale type');
2661
+ }
2662
+ var url = localeResolver(localesBasePath, locale);
2663
+ if (typeof url !== 'string') {
2664
+ throw new TypeError('`localeResolver` expected to resolve to (URL) string.');
2665
+ }
2666
+ return _catch(function () {
2667
+ var _fetch = /** @type {import('./shared.js').Fetch} */getFetch();
2668
+ return _await$1(headOnly ? _fetch(url, {
2669
+ method: 'HEAD'
2670
+ }) : _fetch(url), function (resp) {
2671
+ if (resp.status === 404) {
2672
+ // Don't allow browser (tested in Firefox) to continue
2673
+ // and give `SyntaxError` with missing file or we won't be
2674
+ // able to try without the hyphen
2675
+ throw new Error('Trying again');
2676
+ }
2677
+ return headOnly ? locale : _await$1(resp.json(), function (strings) {
2678
+ return {
2679
+ locale: locale,
2680
+ strings: strings
2681
+ };
2682
+ });
2683
+ });
2684
+ }, function (err) {
2685
+ if ( /** @type {Error} */err.name === 'SyntaxError') {
2686
+ throw err;
2687
+ }
2688
+ return _await$1( /** @type {LocaleMatcher} */localeMatcher(locale), getLocale);
2689
+ });
2690
+ });
2691
+ var _ref4$locales = _ref4.locales,
2692
+ locales = _ref4$locales === void 0 ? typeof intlDomLocale !== 'undefined' ? [intlDomLocale] : typeof navigator === 'undefined' ? [] : navigator.languages : _ref4$locales,
2693
+ _ref4$defaultLocales = _ref4.defaultLocales,
2694
+ defaultLocales = _ref4$defaultLocales === void 0 ? ['en-US'] : _ref4$defaultLocales,
2695
+ _ref4$localeResolver = _ref4.localeResolver,
2696
+ localeResolver = _ref4$localeResolver === void 0 ? defaultLocaleResolver : _ref4$localeResolver,
2697
+ _ref4$localesBasePath = _ref4.localesBasePath,
2698
+ localesBasePath = _ref4$localesBasePath === void 0 ? '.' : _ref4$localesBasePath,
2699
+ _ref4$localeMatcher = _ref4.localeMatcher,
2700
+ localeMatcher = _ref4$localeMatcher === void 0 ? 'lookup' : _ref4$localeMatcher,
2701
+ _ref4$headOnly = _ref4.headOnly,
2702
+ headOnly = _ref4$headOnly === void 0 ? false : _ref4$headOnly;
2703
+ if (localeMatcher === 'lookup') {
2704
+ localeMatcher = defaultLocaleMatcher;
2705
+ } else if (typeof localeMatcher !== 'function') {
2706
+ throw new TypeError('`localeMatcher` must be "lookup" or a function!');
2707
+ }
2708
+ return promiseChainForValues([].concat(_toConsumableArray(locales), _toConsumableArray(defaultLocales)), getLocale, 'No matching locale found for ' + [].concat(_toConsumableArray(locales), _toConsumableArray(defaultLocales)).join(', '));
2709
+ });
2710
+
2711
+ /**
2712
+ * @typedef {import('./index.js').Sort} Sort
2713
+ */
2714
+ /**
2715
+ * @typedef {import('./index.js').SortList} SortList
2716
+ */
2717
+ /**
2718
+ * @typedef {import('./index.js').List} List
2719
+ */
2720
+
2721
+ /**
2722
+ * @typedef {import('./index.js').I18NCallback} I18NCallback
2723
+ */
2724
+
2725
+ /**
2726
+ * @param {object} cfg
2727
+ * @param {import('./getMessageForKeyByStyle.js').LocaleObject} cfg.strings
2728
+ * @param {string} cfg.resolvedLocale
2729
+ * @param {"richNested"|"rich"|"plain"|"plainNested"|
2730
+ * import('./getMessageForKeyByStyle.js').
2731
+ * MessageStyleCallback} [cfg.messageStyle="richNested"]
2732
+ * @param {?import('./defaultAllSubstitutions.js').AllSubstitutionCallback|
2733
+ * import('./defaultAllSubstitutions.js').
2734
+ * AllSubstitutionCallback[]} [cfg.allSubstitutions]
2735
+ * @param {import('./defaultInsertNodes.js').
2736
+ * InsertNodesCallback} [cfg.insertNodes=defaultInsertNodes]
2737
+ * @param {import('./defaultKeyCheckerConverter.js').
2738
+ * KeyCheckerConverterCallback} [cfg.keyCheckerConverter]
2739
+ * @param {false|null|undefined|
2740
+ * import('./getMessageForKeyByStyle.js').LocaleObject} [cfg.defaults]
2741
+ * @param {false|import('./defaultLocaleResolver.js').
2742
+ * SubstitutionObject} [cfg.substitutions={}]
2743
+ * @param {Integer} [cfg.maximumLocalNestingDepth=3]
2744
+ * @param {boolean} [cfg.dom=false]
2745
+ * @param {boolean} [cfg.forceNodeReturn=false]
2746
+ * @param {boolean} [cfg.throwOnMissingSuppliedFormatters=true]
2747
+ * @param {boolean} [cfg.throwOnExtraSuppliedFormatters=true]
2748
+ * @returns {I18NCallback} Rejects if no suitable locale is found.
2749
+ */
2750
+
2751
+ function _await(value, then, direct) {
2752
+ if (direct) {
2753
+ return then ? then(value) : value;
2754
+ }
2755
+ if (!value || !value.then) {
2756
+ value = Promise.resolve(value);
2757
+ }
2758
+ return then ? value.then(then) : value;
2759
+ }
2760
+
2761
+ /**
2762
+ * @typedef {number} Integer
2763
+ */
2764
+
2765
+ /**
2766
+ * @param {object} [cfg={}]
2767
+ * @param {string[]} [cfg.locales=navigator.languages] BCP-47 language strings
2768
+ * @param {string[]} [cfg.defaultLocales=["en-US"]]
2769
+ * @param {import('./findLocaleStrings.js').
2770
+ * LocaleStringFinder} [cfg.localeStringFinder=findLocaleStrings]
2771
+ * @param {string} [cfg.localesBasePath="."]
2772
+ * @param {import('./defaultLocaleResolver.js').
2773
+ * LocaleResolver} [cfg.localeResolver=defaultLocaleResolver]
2774
+ * @param {"lookup"|import('./findLocaleStrings.js').
2775
+ * LocaleMatcher} [cfg.localeMatcher="lookup"]
2776
+ * @param {"richNested"|"rich"|"plain"|"plainNested"|
2777
+ * import('./getMessageForKeyByStyle.js').
2778
+ * MessageStyleCallback} [cfg.messageStyle="richNested"]
2779
+ * @param {?(import('./defaultAllSubstitutions.js').AllSubstitutionCallback|
2780
+ * import('./defaultAllSubstitutions.js').
2781
+ * AllSubstitutionCallback[])} [cfg.allSubstitutions]
2782
+ * @param {import('./defaultInsertNodes.js').
2783
+ * InsertNodesCallback} [cfg.insertNodes=defaultInsertNodes]
2784
+ * @param {import('./defaultKeyCheckerConverter.js').
2785
+ * KeyCheckerConverterCallback} [cfg.keyCheckerConverter]
2786
+ * @param {false|null|undefined|
2787
+ * import('./getMessageForKeyByStyle.js').LocaleObject} [cfg.defaults]
2788
+ * @param {false|
2789
+ * import('./defaultLocaleResolver.js').
2790
+ * SubstitutionObject} [cfg.substitutions={}]
2791
+ * @param {Integer} [cfg.maximumLocalNestingDepth=3]
2792
+ * @param {boolean} [cfg.dom=false]
2793
+ * @param {boolean} [cfg.forceNodeReturn=false]
2794
+ * @param {boolean} [cfg.throwOnMissingSuppliedFormatters=true]
2795
+ * @param {boolean} [cfg.throwOnExtraSuppliedFormatters=true]
2796
+ * @returns {Promise<I18NCallback>} Rejects if no suitable locale is found.
2797
+ */
2798
+
2799
+ function _invoke(body, then) {
2800
+ var result = body();
2801
+ if (result && result.then) {
2802
+ return result.then(then);
2803
+ }
2804
+ return then(result);
2805
+ }
2806
+ var i18nServer = function i18nServer(_ref) {
2807
+ var strings = _ref.strings,
2808
+ resolvedLocale = _ref.resolvedLocale,
2809
+ _ref$messageStyle = _ref.messageStyle,
2810
+ messageStyle = _ref$messageStyle === void 0 ? 'richNested' : _ref$messageStyle,
2811
+ defaultAllSubstitutionsValue = _ref.allSubstitutions,
2812
+ insertNodes = _ref.insertNodes,
2813
+ _ref$keyCheckerConver = _ref.keyCheckerConverter,
2814
+ keyCheckerConverter = _ref$keyCheckerConver === void 0 ? defaultKeyCheckerConverter : _ref$keyCheckerConver,
2815
+ defaultDefaults = _ref.defaults,
2816
+ defaultSubstitutions = _ref.substitutions,
2817
+ maximumLocalNestingDepth = _ref.maximumLocalNestingDepth,
2818
+ _ref$dom = _ref.dom,
2819
+ domDefaults = _ref$dom === void 0 ? false : _ref$dom,
2820
+ _ref$forceNodeReturn = _ref.forceNodeReturn,
2821
+ forceNodeReturnDefault = _ref$forceNodeReturn === void 0 ? false : _ref$forceNodeReturn,
2822
+ _ref$throwOnMissingSu = _ref.throwOnMissingSuppliedFormatters,
2823
+ throwOnMissingSuppliedFormattersDefault = _ref$throwOnMissingSu === void 0 ? true : _ref$throwOnMissingSu,
2824
+ _ref$throwOnExtraSupp = _ref.throwOnExtraSuppliedFormatters,
2825
+ throwOnExtraSuppliedFormattersDefault = _ref$throwOnExtraSupp === void 0 ? true : _ref$throwOnExtraSupp;
2826
+ if (!strings || _typeof(strings) !== 'object') {
2827
+ throw new TypeError("Locale strings must be an object!");
2828
+ }
2829
+ var messageForKey = getMessageForKeyByStyle({
2830
+ messageStyle: messageStyle
2831
+ });
2832
+
2833
+ /**
2834
+ * @type {I18NCallback}
2835
+ */
2836
+ var formatter = function formatter(key, substitutions) {
2837
+ var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
2838
+ _ref2$allSubstitution = _ref2.allSubstitutions,
2839
+ allSubstitutions = _ref2$allSubstitution === void 0 ? defaultAllSubstitutionsValue : _ref2$allSubstitution,
2840
+ _ref2$defaults = _ref2.defaults,
2841
+ defaults = _ref2$defaults === void 0 ? defaultDefaults : _ref2$defaults,
2842
+ _ref2$dom = _ref2.dom,
2843
+ dom = _ref2$dom === void 0 ? domDefaults : _ref2$dom,
2844
+ _ref2$forceNodeReturn = _ref2.forceNodeReturn,
2845
+ forceNodeReturn = _ref2$forceNodeReturn === void 0 ? forceNodeReturnDefault : _ref2$forceNodeReturn,
2846
+ _ref2$throwOnMissingS = _ref2.throwOnMissingSuppliedFormatters,
2847
+ throwOnMissingSuppliedFormatters = _ref2$throwOnMissingS === void 0 ? throwOnMissingSuppliedFormattersDefault : _ref2$throwOnMissingS,
2848
+ _ref2$throwOnExtraSup = _ref2.throwOnExtraSuppliedFormatters,
2849
+ throwOnExtraSuppliedFormatters = _ref2$throwOnExtraSup === void 0 ? throwOnExtraSuppliedFormattersDefault : _ref2$throwOnExtraSup;
2850
+ key = /** @type {string} */keyCheckerConverter(key, messageStyle);
2851
+ var message = messageForKey(strings, key);
2852
+ var string = getStringFromMessageAndDefaults({
2853
+ message: message && typeof message.value === 'string' ? message.value : false,
2854
+ defaults: defaults,
2855
+ messageForKey: messageForKey,
2856
+ key: key
2857
+ });
2858
+ return getDOMForLocaleString({
2859
+ string: string,
2860
+ locals: strings.head && strings.head.locals,
2861
+ switches: strings.head && strings.head.switches,
2862
+ locale: resolvedLocale,
2863
+ maximumLocalNestingDepth: maximumLocalNestingDepth,
2864
+ allSubstitutions: allSubstitutions,
2865
+ insertNodes: insertNodes,
2866
+ substitutions: _objectSpread2(_objectSpread2({}, defaultSubstitutions), substitutions),
2867
+ dom: dom,
2868
+ forceNodeReturn: forceNodeReturn,
2869
+ throwOnMissingSuppliedFormatters: throwOnMissingSuppliedFormatters,
2870
+ throwOnExtraSuppliedFormatters: throwOnExtraSuppliedFormatters
2871
+ });
2872
+ };
2873
+ formatter.resolvedLocale = resolvedLocale;
2874
+ formatter.strings = strings;
2875
+
2876
+ /** @type {Sort} */
2877
+ formatter.sort = function (arrayOfItems, options) {
2878
+ return sort(resolvedLocale, arrayOfItems, options);
2879
+ };
2880
+
2881
+ /** @type {SortList} */
2882
+ formatter.sortList = function (arrayOfItems, map, listOptions, collationOptions) {
2883
+ return sortList(resolvedLocale, arrayOfItems, map, listOptions, collationOptions);
2884
+ };
2885
+
2886
+ /** @type {List} */
2887
+ formatter.list = function (arrayOfItems, options) {
2888
+ return list(resolvedLocale, arrayOfItems, options);
2889
+ };
2890
+ return formatter;
2891
+ };
2892
+ var i18n = function i18n() {
2893
+ var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
2894
+ locales = _ref3.locales,
2895
+ defaultLocales = _ref3.defaultLocales,
2896
+ _ref3$localeStringFin = _ref3.localeStringFinder,
2897
+ localeStringFinder = _ref3$localeStringFin === void 0 ? findLocaleStrings : _ref3$localeStringFin,
2898
+ localesBasePath = _ref3.localesBasePath,
2899
+ localeResolver = _ref3.localeResolver,
2900
+ localeMatcher = _ref3.localeMatcher,
2901
+ messageStyle = _ref3.messageStyle,
2902
+ allSubstitutions = _ref3.allSubstitutions,
2903
+ insertNodes = _ref3.insertNodes,
2904
+ keyCheckerConverter = _ref3.keyCheckerConverter,
2905
+ defaults = _ref3.defaults,
2906
+ substitutions = _ref3.substitutions,
2907
+ maximumLocalNestingDepth = _ref3.maximumLocalNestingDepth,
2908
+ dom = _ref3.dom,
2909
+ forceNodeReturn = _ref3.forceNodeReturn,
2910
+ throwOnMissingSuppliedFormatters = _ref3.throwOnMissingSuppliedFormatters,
2911
+ throwOnExtraSuppliedFormatters = _ref3.throwOnExtraSuppliedFormatters;
2912
+ try {
2913
+ return _await(localeStringFinder({
2914
+ locales: locales,
2915
+ defaultLocales: defaultLocales,
2916
+ localeResolver: localeResolver,
2917
+ localesBasePath: localesBasePath,
2918
+ localeMatcher: localeMatcher
2919
+ }), function (_ref4) {
2920
+ var strings = _ref4.strings,
2921
+ resolvedLocale = _ref4.locale;
2922
+ return _invoke(function () {
2923
+ if (!defaults && defaultLocales) {
2924
+ var defaultLocale;
2925
+ return _await(localeStringFinder({
2926
+ locales: defaultLocales,
2927
+ defaultLocales: [],
2928
+ localeResolver: localeResolver,
2929
+ localesBasePath: localesBasePath,
2930
+ localeMatcher: localeMatcher
2931
+ }), function (_localeStringFinder) {
2932
+ defaults = _localeStringFinder.strings;
2933
+ defaultLocale = _localeStringFinder.locale;
2934
+ if (defaultLocale === resolvedLocale) {
2935
+ defaults = null; // No need to fall back
2936
+ }
2937
+ });
2938
+ }
2939
+ }, function () {
2940
+ return i18nServer({
2941
+ strings: strings,
2942
+ resolvedLocale: resolvedLocale,
2943
+ messageStyle: messageStyle,
2944
+ allSubstitutions: allSubstitutions,
2945
+ insertNodes: insertNodes,
2946
+ keyCheckerConverter: keyCheckerConverter,
2947
+ defaults: defaults,
2948
+ substitutions: substitutions,
2949
+ maximumLocalNestingDepth: maximumLocalNestingDepth,
2950
+ dom: dom,
2951
+ forceNodeReturn: forceNodeReturn,
2952
+ throwOnMissingSuppliedFormatters: throwOnMissingSuppliedFormatters,
2953
+ throwOnExtraSuppliedFormatters: throwOnExtraSuppliedFormatters
2954
+ });
2955
+ });
2956
+ });
2957
+ } catch (e) {
2958
+ return Promise.reject(e);
2959
+ }
2960
+ };
2961
+
2962
+ export { Formatter, LocalFormatter, RegularFormatter, SwitchFormatter, defaultAllSubstitutions, defaultInsertNodes, defaultKeyCheckerConverter, defaultLocaleMatcher, defaultLocaleResolver, findLocale, findLocaleStrings, getDOMForLocaleString, getDocument, getFetch, getMatchingLocale, getMessageForKeyByStyle, getStringFromMessageAndDefaults, i18n, i18nServer, parseJSONExtra, processRegex, promiseChainForValues, setDocument, setFetch, setJSONExtra, unescapeBackslashes };