@prezly/theme-kit-intl 8.0.0 → 9.0.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 (82) hide show
  1. package/build/dictionary.cjs +33 -0
  2. package/build/dictionary.d.ts +3 -0
  3. package/build/dictionary.mjs +26 -0
  4. package/build/formatting/datetime/lib.cjs +4 -16
  5. package/build/formatting/datetime/lib.d.ts +2 -0
  6. package/build/formatting/datetime/lib.mjs +3 -16
  7. package/build/formatting/datetime/lib.test.cjs +14 -0
  8. package/build/formatting/datetime/lib.test.d.ts +1 -0
  9. package/build/formatting/datetime/lib.test.mjs +12 -0
  10. package/build/formatting/datetime/shared.test.cjs +15 -0
  11. package/build/formatting/datetime/shared.test.d.ts +1 -0
  12. package/build/formatting/datetime/shared.test.mjs +13 -0
  13. package/build/formatting/messages/lib.cjs +91 -63
  14. package/build/formatting/messages/lib.d.ts +7 -2
  15. package/build/formatting/messages/lib.mjs +89 -65
  16. package/build/formatting/messages/lib.test.cjs +141 -6
  17. package/build/formatting/messages/lib.test.mjs +142 -7
  18. package/build/formatting/messages/types.cjs +18 -1
  19. package/build/formatting/messages/types.d.ts +46 -3
  20. package/build/formatting/messages/types.mjs +12 -1
  21. package/build/i18n/af.json +87 -1
  22. package/build/i18n/ar.json +139 -2
  23. package/build/i18n/az.json +86 -0
  24. package/build/i18n/be.json +130 -0
  25. package/build/i18n/bg.json +130 -0
  26. package/build/i18n/ca.json +130 -0
  27. package/build/i18n/cs.json +134 -4
  28. package/build/i18n/da.json +130 -0
  29. package/build/i18n/de.json +86 -0
  30. package/build/i18n/el.json +86 -0
  31. package/build/i18n/en.json +130 -0
  32. package/build/i18n/es.json +131 -1
  33. package/build/i18n/et.json +86 -0
  34. package/build/i18n/fi.json +86 -0
  35. package/build/i18n/fil.json +87 -1
  36. package/build/i18n/fr.json +86 -0
  37. package/build/i18n/ga.json +130 -0
  38. package/build/i18n/he.json +108 -0
  39. package/build/i18n/hi.json +86 -0
  40. package/build/i18n/hr.json +108 -0
  41. package/build/i18n/hu.json +86 -0
  42. package/build/i18n/id.json +65 -1
  43. package/build/i18n/it.json +108 -0
  44. package/build/i18n/ja.json +64 -0
  45. package/build/i18n/kk.json +130 -0
  46. package/build/i18n/ko.json +64 -0
  47. package/build/i18n/lt.json +131 -1
  48. package/build/i18n/lv.json +87 -1
  49. package/build/i18n/mt.json +124 -0
  50. package/build/i18n/nl.json +131 -1
  51. package/build/i18n/no.json +86 -0
  52. package/build/i18n/pl.json +131 -1
  53. package/build/i18n/pt-BR.json +132 -2
  54. package/build/i18n/pt.json +133 -3
  55. package/build/i18n/ro.json +109 -1
  56. package/build/i18n/ru.json +130 -0
  57. package/build/i18n/sk.json +108 -0
  58. package/build/i18n/sl.json +131 -1
  59. package/build/i18n/sr.json +130 -0
  60. package/build/i18n/sv.json +130 -0
  61. package/build/i18n/sw.json +86 -0
  62. package/build/i18n/th.json +130 -0
  63. package/build/i18n/tr.json +130 -0
  64. package/build/i18n/uk.json +130 -0
  65. package/build/i18n/ur.json +86 -0
  66. package/build/i18n/uz.json +86 -0
  67. package/build/i18n/vi.json +64 -0
  68. package/build/i18n/zh-CN.json +130 -0
  69. package/build/i18n/zh-TW.json +64 -0
  70. package/build/index.cjs +12 -0
  71. package/build/index.d.ts +1 -0
  72. package/build/index.mjs +1 -0
  73. package/build/messages/content.cjs +12 -0
  74. package/build/messages/content.d.ts +12 -0
  75. package/build/messages/content.mjs +12 -0
  76. package/build/utils/index.cjs +12 -0
  77. package/build/utils/index.d.ts +1 -0
  78. package/build/utils/index.mjs +1 -0
  79. package/build/utils/withCache.cjs +20 -0
  80. package/build/utils/withCache.d.ts +1 -0
  81. package/build/utils/withCache.mjs +14 -0
  82. package/package.json +2 -2
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.importDictionary = importDictionary;
7
+ var _index = require("./locales/index.cjs");
8
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
9
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
10
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
11
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
12
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
13
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
14
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
15
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
16
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } /* eslint-disable @typescript-eslint/no-use-before-define */
17
+ function importDictionary(_x) {
18
+ return _importDictionary.apply(this, arguments);
19
+ }
20
+ function _importDictionary() {
21
+ _importDictionary = _asyncToGenerator(function* (localeCode) {
22
+ var isoCode = (0, _index.pickSupportedLocale)(localeCode);
23
+ var messages = yield (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))("@prezly/theme-kit-intl/i18n/".concat(isoCode, ".json"));
24
+ return _objectSpread({}, unwrapModule(messages));
25
+ });
26
+ return _importDictionary.apply(this, arguments);
27
+ }
28
+ function unwrapModule(module) {
29
+ if (module && typeof module === 'object' && 'default' in module) {
30
+ return module.default;
31
+ }
32
+ return module;
33
+ }
@@ -0,0 +1,3 @@
1
+ import type { IntlDictionary } from './formatting';
2
+ import { type Locale } from './locales';
3
+ export declare function importDictionary(localeCode: Locale.Code): Promise<IntlDictionary>;
@@ -0,0 +1,26 @@
1
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
3
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
4
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
5
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
6
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
7
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
8
+ /* eslint-disable @typescript-eslint/no-use-before-define */
9
+ import { pickSupportedLocale } from "./locales/index.mjs";
10
+ export function importDictionary(_x) {
11
+ return _importDictionary.apply(this, arguments);
12
+ }
13
+ function _importDictionary() {
14
+ _importDictionary = _asyncToGenerator(function* (localeCode) {
15
+ var isoCode = pickSupportedLocale(localeCode);
16
+ var messages = yield import("@prezly/theme-kit-intl/i18n/".concat(isoCode, ".json"));
17
+ return _objectSpread({}, unwrapModule(messages));
18
+ });
19
+ return _importDictionary.apply(this, arguments);
20
+ }
21
+ function unwrapModule(module) {
22
+ if (module && typeof module === 'object' && 'default' in module) {
23
+ return module.default;
24
+ }
25
+ return module;
26
+ }
@@ -5,28 +5,16 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.formatDate = formatDate;
7
7
  exports.formatTime = formatTime;
8
+ exports.getTimeFormat = exports.getDateFormat = void 0;
8
9
  var _index = require("../../locales/index.cjs");
10
+ var _index2 = require("../../utils/index.cjs");
9
11
  var _shared = require("./shared.cjs");
10
12
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
11
13
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
12
14
  function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
13
15
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
14
16
  function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
15
- function withCache(fn) {
16
- var CACHE = new Map();
17
- return function () {
18
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
19
- args[_key] = arguments[_key];
20
- }
21
- var key = JSON.stringify(args);
22
- var cached = CACHE.get(key);
23
- if (cached) return cached;
24
- var value = fn(...args);
25
- CACHE.set(key, value);
26
- return value;
27
- };
28
- }
29
- var getDateFormat = withCache(function (locale, timeZone) {
17
+ var getDateFormat = exports.getDateFormat = (0, _index2.withCache)(function (locale, timeZone) {
30
18
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
31
19
  return new Intl.DateTimeFormat(_index.Locale.from(locale).isoCode, _objectSpread({
32
20
  year: 'numeric',
@@ -35,7 +23,7 @@ var getDateFormat = withCache(function (locale, timeZone) {
35
23
  timeZone
36
24
  }, options));
37
25
  });
38
- var getTimeFormat = withCache(function (locale, timeZone) {
26
+ var getTimeFormat = exports.getTimeFormat = (0, _index2.withCache)(function (locale, timeZone) {
39
27
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
40
28
  return new Intl.DateTimeFormat(_index.Locale.from(locale).isoCode, _objectSpread({
41
29
  hour: 'numeric',
@@ -1,5 +1,7 @@
1
1
  import { Locale } from '../../locales';
2
2
  import type { Iso8601Date, Timezone, UnixTimestampInSeconds } from './types';
3
+ export declare const getDateFormat: (locale: Locale.Code, timeZone: string, options?: Intl.DateTimeFormatOptions | undefined) => Intl.DateTimeFormat;
4
+ export declare const getTimeFormat: (locale: Locale.Code, timeZone: string, options?: Intl.DateTimeFormatOptions | undefined) => Intl.DateTimeFormat;
3
5
  export declare function formatDate(input: Date | Iso8601Date | UnixTimestampInSeconds, context: {
4
6
  locale: Locale.Code;
5
7
  timezone: Timezone;
@@ -4,22 +4,9 @@ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key i
4
4
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
5
5
  function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
6
6
  import { Locale } from "../../locales/index.mjs";
7
+ import { withCache } from "../../utils/index.mjs";
7
8
  import { toDate } from "./shared.mjs";
8
- function withCache(fn) {
9
- var CACHE = new Map();
10
- return function () {
11
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
12
- args[_key] = arguments[_key];
13
- }
14
- var key = JSON.stringify(args);
15
- var cached = CACHE.get(key);
16
- if (cached) return cached;
17
- var value = fn(...args);
18
- CACHE.set(key, value);
19
- return value;
20
- };
21
- }
22
- var getDateFormat = withCache(function (locale, timeZone) {
9
+ export var getDateFormat = withCache(function (locale, timeZone) {
23
10
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
24
11
  return new Intl.DateTimeFormat(Locale.from(locale).isoCode, _objectSpread({
25
12
  year: 'numeric',
@@ -28,7 +15,7 @@ var getDateFormat = withCache(function (locale, timeZone) {
28
15
  timeZone
29
16
  }, options));
30
17
  });
31
- var getTimeFormat = withCache(function (locale, timeZone) {
18
+ export var getTimeFormat = withCache(function (locale, timeZone) {
32
19
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
33
20
  return new Intl.DateTimeFormat(Locale.from(locale).isoCode, _objectSpread({
34
21
  hour: 'numeric',
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+
3
+ var _index = require("../../locales/index.cjs");
4
+ var _lib = require("./lib.cjs");
5
+ describe('getDateFormat', () => {
6
+ test.each(_index.supportedLocales)('should be safe to use with any of the supported locales: %s', locale => {
7
+ expect((0, _lib.getDateFormat)(_index.Locale.from(locale).code, 'Europe/London')).toBeInstanceOf(Intl.DateTimeFormat);
8
+ });
9
+ });
10
+ describe('getTimeFormat', () => {
11
+ test.each(_index.supportedLocales)('should be safe to use with any of the supported locales: %s', locale => {
12
+ expect((0, _lib.getTimeFormat)(_index.Locale.from(locale).code, 'Europe/London')).toBeInstanceOf(Intl.DateTimeFormat);
13
+ });
14
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ import { Locale, supportedLocales } from "../../locales/index.mjs";
2
+ import { getDateFormat, getTimeFormat } from "./lib.mjs";
3
+ describe('getDateFormat', () => {
4
+ test.each(supportedLocales)('should be safe to use with any of the supported locales: %s', locale => {
5
+ expect(getDateFormat(Locale.from(locale).code, 'Europe/London')).toBeInstanceOf(Intl.DateTimeFormat);
6
+ });
7
+ });
8
+ describe('getTimeFormat', () => {
9
+ test.each(supportedLocales)('should be safe to use with any of the supported locales: %s', locale => {
10
+ expect(getTimeFormat(Locale.from(locale).code, 'Europe/London')).toBeInstanceOf(Intl.DateTimeFormat);
11
+ });
12
+ });
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+
3
+ var _shared = require("./shared.cjs");
4
+ describe('toDate', () => {
5
+ it('should keep Date object as is', () => {
6
+ var now = new Date();
7
+ expect((0, _shared.toDate)(now)).toBe(now);
8
+ });
9
+ it('should convert string values to date', () => {
10
+ expect((0, _shared.toDate)('2000-01-01T00:00:00Z')).toEqual(new Date('2000-01-01T00:00:00Z'));
11
+ });
12
+ it('should treat numeric values as UNIX timestamp in seconds', () => {
13
+ expect((0, _shared.toDate)(946684865)).toEqual(new Date('2000-01-01T00:01:05Z'));
14
+ });
15
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import { toDate } from "./shared.mjs";
2
+ describe('toDate', () => {
3
+ it('should keep Date object as is', () => {
4
+ var now = new Date();
5
+ expect(toDate(now)).toBe(now);
6
+ });
7
+ it('should convert string values to date', () => {
8
+ expect(toDate('2000-01-01T00:00:00Z')).toEqual(new Date('2000-01-01T00:00:00Z'));
9
+ });
10
+ it('should treat numeric values as UNIX timestamp in seconds', () => {
11
+ expect(toDate(946684865)).toEqual(new Date('2000-01-01T00:01:05Z'));
12
+ });
13
+ });
@@ -5,64 +5,65 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.formatMessageFragment = formatMessageFragment;
7
7
  exports.formatMessageString = formatMessageString;
8
+ exports.getPluralRules = void 0;
9
+ exports.parseMessage = parseMessage;
10
+ exports.tokenizeMessage = tokenizeMessage;
11
+ var _index = require("../../locales/index.cjs");
12
+ var _index2 = require("../../utils/index.cjs");
13
+ var _types = require("./types.cjs");
8
14
  /* eslint-disable @typescript-eslint/no-use-before-define */
9
15
 
10
- function formatMessageFragment(_ref, dictionary) {
16
+ var getPluralRules = exports.getPluralRules = (0, _index2.withCache)(locale => new Intl.PluralRules(_index.Locale.from(locale).isoCode));
17
+ function formatMessageFragment(locale, _ref, dictionary) {
11
18
  var _ref2, _dictionary$id;
12
19
  var {
13
20
  id,
14
21
  defaultMessage
15
22
  } = _ref;
16
- var values = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
23
+ var values = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
17
24
  var format = (_ref2 = (_dictionary$id = dictionary[id]) !== null && _dictionary$id !== void 0 ? _dictionary$id : prepareMessage(defaultMessage)) !== null && _ref2 !== void 0 ? _ref2 : [{
18
25
  type: 0,
19
26
  value: "[".concat(id, "]")
20
27
  }];
21
- return format.map(_ref3 => {
22
- var _values$value;
23
- var {
24
- type,
25
- value
26
- } = _ref3;
27
- if (type === 0) {
28
- return value;
29
- }
30
- return (_values$value = values[value]) !== null && _values$value !== void 0 ? _values$value : "{".concat(value, "}");
31
- });
28
+ return format.flatMap(token => formatToken(locale, token, values));
32
29
  }
33
- function formatMessageString(_ref4, dictionary) {
34
- var _ref5, _dictionary$id2;
30
+ function formatMessageString(locale, _ref3, dictionary) {
31
+ var _ref4, _dictionary$id2;
35
32
  var {
36
33
  id,
37
34
  defaultMessage
38
- } = _ref4;
39
- var values = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
40
- var format = (_ref5 = (_dictionary$id2 = dictionary[id]) !== null && _dictionary$id2 !== void 0 ? _dictionary$id2 : prepareMessage(defaultMessage)) !== null && _ref5 !== void 0 ? _ref5 : [{
41
- type: 0,
35
+ } = _ref3;
36
+ var values = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
37
+ var format = (_ref4 = (_dictionary$id2 = dictionary[id]) !== null && _dictionary$id2 !== void 0 ? _dictionary$id2 : prepareMessage(defaultMessage)) !== null && _ref4 !== void 0 ? _ref4 : [{
38
+ type: _types.IntlMessageFormat.Type.LITERAL,
42
39
  value: "[".concat(id, "]")
43
40
  }];
44
- return format.map(_ref6 => {
45
- var _values$value2;
46
- var {
47
- type,
48
- value
49
- } = _ref6;
50
- if (type === 0) {
51
- return value;
52
- }
53
- return String((_values$value2 = values[value]) !== null && _values$value2 !== void 0 ? _values$value2 : "{".concat(value, "}"));
54
- }).join('');
41
+ return format.flatMap(token => formatToken(locale, token, values)).join('');
55
42
  }
56
- var CACHE = new Map();
57
- function prepareMessage(message) {
58
- if (typeof message === 'undefined') {
59
- return undefined;
43
+ var prepareMessage = (0, _index2.withCache)(message => typeof message !== 'undefined' ? parseMessage(message) : undefined);
44
+ function formatToken(locale, token) {
45
+ var values = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
46
+ var poundValue = arguments.length > 3 ? arguments[3] : undefined;
47
+ if (token.type === _types.IntlMessageFormat.Type.LITERAL) {
48
+ return [token.value];
60
49
  }
61
- var cached = CACHE.get(message);
62
- if (cached) return cached;
63
- var parsed = parseMessage(message);
64
- CACHE.set(message, parsed);
65
- return parsed;
50
+ if (token.type === _types.IntlMessageFormat.Type.ARGUMENT) {
51
+ var _values$token$value;
52
+ return [(_values$token$value = values[token.value]) !== null && _values$token$value !== void 0 ? _values$token$value : "{".concat(token.value, "}")];
53
+ }
54
+ if (token.type === _types.IntlMessageFormat.Type.PLURAL) {
55
+ var _ref5, _token$options;
56
+ var value = values[token.value];
57
+ if (typeof value !== 'number') {
58
+ throw new Error("Invalid message parameters given. {".concat(token.value, "} param is required to be a number."));
59
+ }
60
+ var option = (_ref5 = (_token$options = token.options["=".concat(value)]) !== null && _token$options !== void 0 ? _token$options : token.options[getPluralRules(locale).select(value)]) !== null && _ref5 !== void 0 ? _ref5 : token.options.other;
61
+ return option.value.flatMap(x => formatToken(locale, x, values, value));
62
+ }
63
+ if (token.type === _types.IntlMessageFormat.Type.POUND) {
64
+ return [String(poundValue !== null && poundValue !== void 0 ? poundValue : '#')];
65
+ }
66
+ throw new Error("Unsupported token: ".concat(JSON.stringify(token)));
66
67
  }
67
68
  function parseMessage(message) {
68
69
  if (message.length === 0) {
@@ -71,38 +72,65 @@ function parseMessage(message) {
71
72
  value: message
72
73
  }];
73
74
  }
74
- var remaining = message;
75
75
  var format = [];
76
- while (remaining.length > 0) {
77
- var start = remaining.indexOf('{');
78
- var end = remaining.indexOf('}');
79
- if (start === -1 || end === -1) {
76
+ tokenizeMessage(message).forEach(token => {
77
+ // literal: "hello"
78
+ if (!token.startsWith('{') || !token.endsWith('}')) {
80
79
  format.push({
81
80
  type: 0,
82
- value: remaining
81
+ value: token
83
82
  });
84
- break;
83
+ return;
85
84
  }
86
- var prefix = remaining.substring(0, start);
87
- var placeholder = remaining.substring(start + 1, end);
88
- if (prefix) {
89
- format.push({
90
- type: 0,
91
- value: prefix
92
- });
93
- }
94
- if (placeholder) {
85
+
86
+ // plural placeholder: "{var, plural, ...}"
87
+ if (token.indexOf(',') >= 0) {
88
+ var _token$split$;
89
+ var name = ((_token$split$ = token.split(/[{,}]/)[1]) !== null && _token$split$ !== void 0 ? _token$split$ : '').trim();
95
90
  format.push({
96
91
  type: 1,
97
- value: placeholder
92
+ value: name
98
93
  });
99
- } else {
100
- format.push({
101
- type: 0,
102
- value: '{}'
103
- }); // false-positive?
94
+ return;
104
95
  }
105
- remaining = remaining.substring(end + 1);
106
- }
96
+
97
+ // (assuming) argument: "{var}"
98
+ format.push({
99
+ type: 1,
100
+ value: token.substring(1, token.length - 1)
101
+ });
102
+ });
107
103
  return format;
104
+ }
105
+ function tokenizeMessage(message) {
106
+ var tokens = message.split(/([{}])/);
107
+ var nesting = 0;
108
+ var result = [];
109
+ var buffer = '';
110
+ tokens.forEach(token => {
111
+ switch (token) {
112
+ case '{':
113
+ if (nesting === 0 && buffer.length > 0) {
114
+ result = [...result, buffer];
115
+ buffer = '';
116
+ }
117
+ buffer += token;
118
+ nesting += 1;
119
+ break;
120
+ case '}':
121
+ buffer += token;
122
+ nesting -= 1;
123
+ if (nesting === 0) {
124
+ result = [...result, buffer];
125
+ buffer = '';
126
+ }
127
+ break;
128
+ default:
129
+ buffer += token;
130
+ }
131
+ });
132
+ if (buffer.length > 0) {
133
+ return [...result, buffer];
134
+ }
135
+ return result;
108
136
  }
@@ -1,3 +1,8 @@
1
+ import { Locale } from '../../locales';
2
+ import { IntlMessageFormat } from './types';
1
3
  import type { IntlDictionary, IntlMessageDescriptor, IntlMessageValues } from './types';
2
- export declare function formatMessageFragment<T>({ id, defaultMessage }: IntlMessageDescriptor, dictionary: IntlDictionary, values?: IntlMessageValues<T>): (T | string)[];
3
- export declare function formatMessageString({ id, defaultMessage }: IntlMessageDescriptor, dictionary: IntlDictionary, values?: IntlMessageValues<string | number>): string;
4
+ export declare const getPluralRules: (locale: string) => Intl.PluralRules;
5
+ export declare function formatMessageFragment<T>(locale: Locale.Code, { id, defaultMessage }: IntlMessageDescriptor, dictionary: IntlDictionary, values?: IntlMessageValues<T>): (T | string)[];
6
+ export declare function formatMessageString(locale: Locale.Code, { id, defaultMessage }: IntlMessageDescriptor, dictionary: IntlDictionary, values?: IntlMessageValues<string | number>): string;
7
+ export declare function parseMessage(message: string): IntlMessageFormat;
8
+ export declare function tokenizeMessage(message: string): string[];
@@ -1,101 +1,125 @@
1
1
  /* eslint-disable @typescript-eslint/no-use-before-define */
2
-
3
- export function formatMessageFragment(_ref, dictionary) {
2
+ import { Locale } from "../../locales/index.mjs";
3
+ import { withCache } from "../../utils/index.mjs";
4
+ import { IntlMessageFormat } from "./types.mjs";
5
+ export var getPluralRules = withCache(locale => new Intl.PluralRules(Locale.from(locale).isoCode));
6
+ export function formatMessageFragment(locale, _ref, dictionary) {
4
7
  var _ref2, _dictionary$id;
5
8
  var {
6
9
  id,
7
10
  defaultMessage
8
11
  } = _ref;
9
- var values = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
12
+ var values = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
10
13
  var format = (_ref2 = (_dictionary$id = dictionary[id]) !== null && _dictionary$id !== void 0 ? _dictionary$id : prepareMessage(defaultMessage)) !== null && _ref2 !== void 0 ? _ref2 : [{
11
14
  type: 0,
12
15
  value: "[".concat(id, "]")
13
16
  }];
14
- return format.map(_ref3 => {
15
- var _values$value;
16
- var {
17
- type,
18
- value
19
- } = _ref3;
20
- if (type === 0) {
21
- return value;
22
- }
23
- return (_values$value = values[value]) !== null && _values$value !== void 0 ? _values$value : "{".concat(value, "}");
24
- });
17
+ return format.flatMap(token => formatToken(locale, token, values));
25
18
  }
26
- export function formatMessageString(_ref4, dictionary) {
27
- var _ref5, _dictionary$id2;
19
+ export function formatMessageString(locale, _ref3, dictionary) {
20
+ var _ref4, _dictionary$id2;
28
21
  var {
29
22
  id,
30
23
  defaultMessage
31
- } = _ref4;
32
- var values = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
33
- var format = (_ref5 = (_dictionary$id2 = dictionary[id]) !== null && _dictionary$id2 !== void 0 ? _dictionary$id2 : prepareMessage(defaultMessage)) !== null && _ref5 !== void 0 ? _ref5 : [{
34
- type: 0,
24
+ } = _ref3;
25
+ var values = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
26
+ var format = (_ref4 = (_dictionary$id2 = dictionary[id]) !== null && _dictionary$id2 !== void 0 ? _dictionary$id2 : prepareMessage(defaultMessage)) !== null && _ref4 !== void 0 ? _ref4 : [{
27
+ type: IntlMessageFormat.Type.LITERAL,
35
28
  value: "[".concat(id, "]")
36
29
  }];
37
- return format.map(_ref6 => {
38
- var _values$value2;
39
- var {
40
- type,
41
- value
42
- } = _ref6;
43
- if (type === 0) {
44
- return value;
45
- }
46
- return String((_values$value2 = values[value]) !== null && _values$value2 !== void 0 ? _values$value2 : "{".concat(value, "}"));
47
- }).join('');
30
+ return format.flatMap(token => formatToken(locale, token, values)).join('');
48
31
  }
49
- var CACHE = new Map();
50
- function prepareMessage(message) {
51
- if (typeof message === 'undefined') {
52
- return undefined;
32
+ var prepareMessage = withCache(message => typeof message !== 'undefined' ? parseMessage(message) : undefined);
33
+ function formatToken(locale, token) {
34
+ var values = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
35
+ var poundValue = arguments.length > 3 ? arguments[3] : undefined;
36
+ if (token.type === IntlMessageFormat.Type.LITERAL) {
37
+ return [token.value];
38
+ }
39
+ if (token.type === IntlMessageFormat.Type.ARGUMENT) {
40
+ var _values$token$value;
41
+ return [(_values$token$value = values[token.value]) !== null && _values$token$value !== void 0 ? _values$token$value : "{".concat(token.value, "}")];
42
+ }
43
+ if (token.type === IntlMessageFormat.Type.PLURAL) {
44
+ var _ref5, _token$options;
45
+ var value = values[token.value];
46
+ if (typeof value !== 'number') {
47
+ throw new Error("Invalid message parameters given. {".concat(token.value, "} param is required to be a number."));
48
+ }
49
+ var option = (_ref5 = (_token$options = token.options["=".concat(value)]) !== null && _token$options !== void 0 ? _token$options : token.options[getPluralRules(locale).select(value)]) !== null && _ref5 !== void 0 ? _ref5 : token.options.other;
50
+ return option.value.flatMap(x => formatToken(locale, x, values, value));
51
+ }
52
+ if (token.type === IntlMessageFormat.Type.POUND) {
53
+ return [String(poundValue !== null && poundValue !== void 0 ? poundValue : '#')];
53
54
  }
54
- var cached = CACHE.get(message);
55
- if (cached) return cached;
56
- var parsed = parseMessage(message);
57
- CACHE.set(message, parsed);
58
- return parsed;
55
+ throw new Error("Unsupported token: ".concat(JSON.stringify(token)));
59
56
  }
60
- function parseMessage(message) {
57
+ export function parseMessage(message) {
61
58
  if (message.length === 0) {
62
59
  return [{
63
60
  type: 0,
64
61
  value: message
65
62
  }];
66
63
  }
67
- var remaining = message;
68
64
  var format = [];
69
- while (remaining.length > 0) {
70
- var start = remaining.indexOf('{');
71
- var end = remaining.indexOf('}');
72
- if (start === -1 || end === -1) {
73
- format.push({
74
- type: 0,
75
- value: remaining
76
- });
77
- break;
78
- }
79
- var prefix = remaining.substring(0, start);
80
- var placeholder = remaining.substring(start + 1, end);
81
- if (prefix) {
65
+ tokenizeMessage(message).forEach(token => {
66
+ // literal: "hello"
67
+ if (!token.startsWith('{') || !token.endsWith('}')) {
82
68
  format.push({
83
69
  type: 0,
84
- value: prefix
70
+ value: token
85
71
  });
72
+ return;
86
73
  }
87
- if (placeholder) {
74
+
75
+ // plural placeholder: "{var, plural, ...}"
76
+ if (token.indexOf(',') >= 0) {
77
+ var _token$split$;
78
+ var name = ((_token$split$ = token.split(/[{,}]/)[1]) !== null && _token$split$ !== void 0 ? _token$split$ : '').trim();
88
79
  format.push({
89
80
  type: 1,
90
- value: placeholder
81
+ value: name
91
82
  });
92
- } else {
93
- format.push({
94
- type: 0,
95
- value: '{}'
96
- }); // false-positive?
83
+ return;
97
84
  }
98
- remaining = remaining.substring(end + 1);
99
- }
85
+
86
+ // (assuming) argument: "{var}"
87
+ format.push({
88
+ type: 1,
89
+ value: token.substring(1, token.length - 1)
90
+ });
91
+ });
100
92
  return format;
93
+ }
94
+ export function tokenizeMessage(message) {
95
+ var tokens = message.split(/([{}])/);
96
+ var nesting = 0;
97
+ var result = [];
98
+ var buffer = '';
99
+ tokens.forEach(token => {
100
+ switch (token) {
101
+ case '{':
102
+ if (nesting === 0 && buffer.length > 0) {
103
+ result = [...result, buffer];
104
+ buffer = '';
105
+ }
106
+ buffer += token;
107
+ nesting += 1;
108
+ break;
109
+ case '}':
110
+ buffer += token;
111
+ nesting -= 1;
112
+ if (nesting === 0) {
113
+ result = [...result, buffer];
114
+ buffer = '';
115
+ }
116
+ break;
117
+ default:
118
+ buffer += token;
119
+ }
120
+ });
121
+ if (buffer.length > 0) {
122
+ return [...result, buffer];
123
+ }
124
+ return result;
101
125
  }