react-intl
Version:
Internationalize React apps. This library provides React components and an API to format dates, numbers, and strings, including pluralization and handling translations.
1,319 lines (1,271 loc) • 90.5 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactIntl = {}, global.React));
}(this, (function (exports, React) { 'use strict';
function _interopNamespace(e) {
if (e && e.__esModule) { return e; } else {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () {
return e[k];
}
});
}
});
}
n['default'] = e;
return Object.freeze(n);
}
}
var React__namespace = /*#__PURE__*/_interopNamespace(React);
/**
* Cannot do Math.log(x) / Math.log(10) bc if IEEE floating point issue
* @param x number
*/
function invariant(condition, message, Err) {
if (Err === void 0) { Err = Error; }
if (!condition) {
throw new Err(message);
}
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var types = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNumberElement = exports.createLiteralElement = exports.isDateTimeSkeleton = exports.isNumberSkeleton = exports.isTagElement = exports.isPoundElement = exports.isPluralElement = exports.isSelectElement = exports.isTimeElement = exports.isDateElement = exports.isNumberElement = exports.isArgumentElement = exports.isLiteralElement = exports.SKELETON_TYPE = exports.TYPE = void 0;
var TYPE;
(function (TYPE) {
/**
* Raw text
*/
TYPE[TYPE["literal"] = 0] = "literal";
/**
* Variable w/o any format, e.g `var` in `this is a {var}`
*/
TYPE[TYPE["argument"] = 1] = "argument";
/**
* Variable w/ number format
*/
TYPE[TYPE["number"] = 2] = "number";
/**
* Variable w/ date format
*/
TYPE[TYPE["date"] = 3] = "date";
/**
* Variable w/ time format
*/
TYPE[TYPE["time"] = 4] = "time";
/**
* Variable w/ select format
*/
TYPE[TYPE["select"] = 5] = "select";
/**
* Variable w/ plural format
*/
TYPE[TYPE["plural"] = 6] = "plural";
/**
* Only possible within plural argument.
* This is the `#` symbol that will be substituted with the count.
*/
TYPE[TYPE["pound"] = 7] = "pound";
/**
* XML-like tag
*/
TYPE[TYPE["tag"] = 8] = "tag";
})(TYPE = exports.TYPE || (exports.TYPE = {}));
var SKELETON_TYPE;
(function (SKELETON_TYPE) {
SKELETON_TYPE[SKELETON_TYPE["number"] = 0] = "number";
SKELETON_TYPE[SKELETON_TYPE["dateTime"] = 1] = "dateTime";
})(SKELETON_TYPE = exports.SKELETON_TYPE || (exports.SKELETON_TYPE = {}));
/**
* Type Guards
*/
function isLiteralElement(el) {
return el.type === TYPE.literal;
}
exports.isLiteralElement = isLiteralElement;
function isArgumentElement(el) {
return el.type === TYPE.argument;
}
exports.isArgumentElement = isArgumentElement;
function isNumberElement(el) {
return el.type === TYPE.number;
}
exports.isNumberElement = isNumberElement;
function isDateElement(el) {
return el.type === TYPE.date;
}
exports.isDateElement = isDateElement;
function isTimeElement(el) {
return el.type === TYPE.time;
}
exports.isTimeElement = isTimeElement;
function isSelectElement(el) {
return el.type === TYPE.select;
}
exports.isSelectElement = isSelectElement;
function isPluralElement(el) {
return el.type === TYPE.plural;
}
exports.isPluralElement = isPluralElement;
function isPoundElement(el) {
return el.type === TYPE.pound;
}
exports.isPoundElement = isPoundElement;
function isTagElement(el) {
return el.type === TYPE.tag;
}
exports.isTagElement = isTagElement;
function isNumberSkeleton(el) {
return !!(el && typeof el === 'object' && el.type === 0 /* number */);
}
exports.isNumberSkeleton = isNumberSkeleton;
function isDateTimeSkeleton(el) {
return !!(el && typeof el === 'object' && el.type === 1 /* dateTime */);
}
exports.isDateTimeSkeleton = isDateTimeSkeleton;
function createLiteralElement(value) {
return {
type: TYPE.literal,
value: value,
};
}
exports.createLiteralElement = createLiteralElement;
function createNumberElement(value, style) {
return {
type: TYPE.number,
value: value,
style: style,
};
}
exports.createNumberElement = createNumberElement;
});
var dummy = createCommonjsModule(function (module, exports) {
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = void 0;
__exportStar(types, exports);
function parse() {
throw new Error("You're trying to format an uncompiled message with react-intl without parser, please import from 'react-int' instead");
}
exports.parse = parse;
});
//
// Main
//
function memoize (fn, options) {
var cache = options && options.cache
? options.cache
: cacheDefault;
var serializer = options && options.serializer
? options.serializer
: serializerDefault;
var strategy = options && options.strategy
? options.strategy
: strategyDefault;
return strategy(fn, {
cache: cache,
serializer: serializer
})
}
//
// Strategy
//
function isPrimitive (value) {
return value == null || typeof value === 'number' || typeof value === 'boolean' // || typeof value === "string" 'unsafe' primitive for our needs
}
function monadic (fn, cache, serializer, arg) {
var cacheKey = isPrimitive(arg) ? arg : serializer(arg);
var computedValue = cache.get(cacheKey);
if (typeof computedValue === 'undefined') {
computedValue = fn.call(this, arg);
cache.set(cacheKey, computedValue);
}
return computedValue
}
function variadic (fn, cache, serializer) {
var args = Array.prototype.slice.call(arguments, 3);
var cacheKey = serializer(args);
var computedValue = cache.get(cacheKey);
if (typeof computedValue === 'undefined') {
computedValue = fn.apply(this, args);
cache.set(cacheKey, computedValue);
}
return computedValue
}
function assemble (fn, context, strategy, cache, serialize) {
return strategy.bind(
context,
fn,
cache,
serialize
)
}
function strategyDefault (fn, options) {
var strategy = fn.length === 1 ? monadic : variadic;
return assemble(
fn,
this,
strategy,
options.cache.create(),
options.serializer
)
}
function strategyVariadic (fn, options) {
var strategy = variadic;
return assemble(
fn,
this,
strategy,
options.cache.create(),
options.serializer
)
}
function strategyMonadic (fn, options) {
var strategy = monadic;
return assemble(
fn,
this,
strategy,
options.cache.create(),
options.serializer
)
}
//
// Serializer
//
function serializerDefault () {
return JSON.stringify(arguments)
}
//
// Cache
//
function ObjectWithoutPrototypeCache () {
this.cache = Object.create(null);
}
ObjectWithoutPrototypeCache.prototype.has = function (key) {
return (key in this.cache)
};
ObjectWithoutPrototypeCache.prototype.get = function (key) {
return this.cache[key]
};
ObjectWithoutPrototypeCache.prototype.set = function (key, value) {
this.cache[key] = value;
};
var cacheDefault = {
create: function create () {
return new ObjectWithoutPrototypeCache()
}
};
//
// API
//
var src = memoize;
var strategies = {
variadic: strategyVariadic,
monadic: strategyMonadic
};
src.strategies = strategies;
var memoize$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), src, {
'default': src,
strategies: strategies
}));
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var ErrorCode;
(function (ErrorCode) {
// When we have a placeholder but no value to format
ErrorCode["MISSING_VALUE"] = "MISSING_VALUE";
// When value supplied is invalid
ErrorCode["INVALID_VALUE"] = "INVALID_VALUE";
// When we need specific Intl API but it's not available
ErrorCode["MISSING_INTL_API"] = "MISSING_INTL_API";
})(ErrorCode || (ErrorCode = {}));
var FormatError = /** @class */ (function (_super) {
__extends(FormatError, _super);
function FormatError(msg, code, originalMessage) {
var _this = _super.call(this, msg) || this;
_this.code = code;
_this.originalMessage = originalMessage;
return _this;
}
FormatError.prototype.toString = function () {
return "[formatjs Error: " + this.code + "] " + this.message;
};
return FormatError;
}(Error));
var InvalidValueError = /** @class */ (function (_super) {
__extends(InvalidValueError, _super);
function InvalidValueError(variableId, value, options, originalMessage) {
return _super.call(this, "Invalid values for \"" + variableId + "\": \"" + value + "\". Options are \"" + Object.keys(options).join('", "') + "\"", "INVALID_VALUE" /* INVALID_VALUE */, originalMessage) || this;
}
return InvalidValueError;
}(FormatError));
var InvalidValueTypeError = /** @class */ (function (_super) {
__extends(InvalidValueTypeError, _super);
function InvalidValueTypeError(value, type, originalMessage) {
return _super.call(this, "Value for \"" + value + "\" must be of type " + type, "INVALID_VALUE" /* INVALID_VALUE */, originalMessage) || this;
}
return InvalidValueTypeError;
}(FormatError));
var MissingValueError = /** @class */ (function (_super) {
__extends(MissingValueError, _super);
function MissingValueError(variableId, originalMessage) {
return _super.call(this, "The intl string context variable \"" + variableId + "\" was not provided to the string \"" + originalMessage + "\"", "MISSING_VALUE" /* MISSING_VALUE */, originalMessage) || this;
}
return MissingValueError;
}(FormatError));
var PART_TYPE;
(function (PART_TYPE) {
PART_TYPE[PART_TYPE["literal"] = 0] = "literal";
PART_TYPE[PART_TYPE["object"] = 1] = "object";
})(PART_TYPE || (PART_TYPE = {}));
function mergeLiteral(parts) {
if (parts.length < 2) {
return parts;
}
return parts.reduce(function (all, part) {
var lastPart = all[all.length - 1];
if (!lastPart ||
lastPart.type !== 0 /* literal */ ||
part.type !== 0 /* literal */) {
all.push(part);
}
else {
lastPart.value += part.value;
}
return all;
}, []);
}
function isFormatXMLElementFn(el) {
return typeof el === 'function';
}
// TODO(skeleton): add skeleton support
function formatToParts(els, locales, formatters, formats, values, currentPluralValue,
// For debugging
originalMessage) {
// Hot path for straight simple msg translations
if (els.length === 1 && dummy.isLiteralElement(els[0])) {
return [
{
type: 0 /* literal */,
value: els[0].value,
},
];
}
var result = [];
for (var _i = 0, els_1 = els; _i < els_1.length; _i++) {
var el = els_1[_i];
// Exit early for string parts.
if (dummy.isLiteralElement(el)) {
result.push({
type: 0 /* literal */,
value: el.value,
});
continue;
}
// TODO: should this part be literal type?
// Replace `#` in plural rules with the actual numeric value.
if (dummy.isPoundElement(el)) {
if (typeof currentPluralValue === 'number') {
result.push({
type: 0 /* literal */,
value: formatters.getNumberFormat(locales).format(currentPluralValue),
});
}
continue;
}
var varName = el.value;
// Enforce that all required values are provided by the caller.
if (!(values && varName in values)) {
throw new MissingValueError(varName, originalMessage);
}
var value = values[varName];
if (dummy.isArgumentElement(el)) {
if (!value || typeof value === 'string' || typeof value === 'number') {
value =
typeof value === 'string' || typeof value === 'number'
? String(value)
: '';
}
result.push({
type: typeof value === 'string' ? 0 /* literal */ : 1 /* object */,
value: value,
});
continue;
}
// Recursively format plural and select parts' option — which can be a
// nested pattern structure. The choosing of the option to use is
// abstracted-by and delegated-to the part helper object.
if (dummy.isDateElement(el)) {
var style = typeof el.style === 'string'
? formats.date[el.style]
: dummy.isDateTimeSkeleton(el.style)
? el.style.parsedOptions
: undefined;
result.push({
type: 0 /* literal */,
value: formatters
.getDateTimeFormat(locales, style)
.format(value),
});
continue;
}
if (dummy.isTimeElement(el)) {
var style = typeof el.style === 'string'
? formats.time[el.style]
: dummy.isDateTimeSkeleton(el.style)
? el.style.parsedOptions
: undefined;
result.push({
type: 0 /* literal */,
value: formatters
.getDateTimeFormat(locales, style)
.format(value),
});
continue;
}
if (dummy.isNumberElement(el)) {
var style = typeof el.style === 'string'
? formats.number[el.style]
: dummy.isNumberSkeleton(el.style)
? el.style.parsedOptions
: undefined;
result.push({
type: 0 /* literal */,
value: formatters
.getNumberFormat(locales, style)
.format(value),
});
continue;
}
if (dummy.isTagElement(el)) {
var children = el.children, value_1 = el.value;
var formatFn = values[value_1];
if (!isFormatXMLElementFn(formatFn)) {
throw new InvalidValueTypeError(value_1, 'function', originalMessage);
}
var parts = formatToParts(children, locales, formatters, formats, values, currentPluralValue);
var chunks = formatFn(parts.map(function (p) { return p.value; }));
if (!Array.isArray(chunks)) {
chunks = [chunks];
}
result.push.apply(result, chunks.map(function (c) {
return {
type: typeof c === 'string' ? 0 /* literal */ : 1 /* object */,
value: c,
};
}));
}
if (dummy.isSelectElement(el)) {
var opt = el.options[value] || el.options.other;
if (!opt) {
throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);
}
result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values));
continue;
}
if (dummy.isPluralElement(el)) {
var opt = el.options["=" + value];
if (!opt) {
if (!Intl.PluralRules) {
throw new FormatError("Intl.PluralRules is not available in this environment.\nTry polyfilling it using \"@formatjs/intl-pluralrules\"\n", "MISSING_INTL_API" /* MISSING_INTL_API */, originalMessage);
}
var rule = formatters
.getPluralRules(locales, { type: el.pluralType })
.select(value - (el.offset || 0));
opt = el.options[rule] || el.options.other;
}
if (!opt) {
throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);
}
result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values, value - (el.offset || 0)));
continue;
}
}
return mergeLiteral(result);
}
/*
Copyright (c) 2014, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/
var __assign = (undefined && undefined.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __spreadArrays = (undefined && undefined.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
// -- MessageFormat --------------------------------------------------------
function mergeConfig(c1, c2) {
if (!c2) {
return c1;
}
return __assign(__assign(__assign({}, (c1 || {})), (c2 || {})), Object.keys(c1).reduce(function (all, k) {
all[k] = __assign(__assign({}, c1[k]), (c2[k] || {}));
return all;
}, {}));
}
function mergeConfigs(defaultConfig, configs) {
if (!configs) {
return defaultConfig;
}
return Object.keys(defaultConfig).reduce(function (all, k) {
all[k] = mergeConfig(defaultConfig[k], configs[k]);
return all;
}, __assign({}, defaultConfig));
}
function createFastMemoizeCache(store) {
return {
create: function () {
return {
has: function (key) {
return key in store;
},
get: function (key) {
return store[key];
},
set: function (key, value) {
store[key] = value;
},
};
},
};
}
// @ts-ignore this is to deal with rollup's default import shenanigans
var _memoizeIntl = src || memoize$1;
var memoizeIntl = _memoizeIntl;
function createDefaultFormatters(cache) {
if (cache === void 0) { cache = {
number: {},
dateTime: {},
pluralRules: {},
}; }
return {
getNumberFormat: memoizeIntl(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.NumberFormat).bind.apply(_a, __spreadArrays([void 0], args)))();
}, {
cache: createFastMemoizeCache(cache.number),
strategy: memoizeIntl.strategies.variadic,
}),
getDateTimeFormat: memoizeIntl(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.DateTimeFormat).bind.apply(_a, __spreadArrays([void 0], args)))();
}, {
cache: createFastMemoizeCache(cache.dateTime),
strategy: memoizeIntl.strategies.variadic,
}),
getPluralRules: memoizeIntl(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.PluralRules).bind.apply(_a, __spreadArrays([void 0], args)))();
}, {
cache: createFastMemoizeCache(cache.pluralRules),
strategy: memoizeIntl.strategies.variadic,
}),
};
}
var IntlMessageFormat = /** @class */ (function () {
function IntlMessageFormat(message, locales, overrideFormats, opts) {
var _this = this;
if (locales === void 0) { locales = IntlMessageFormat.defaultLocale; }
this.formatterCache = {
number: {},
dateTime: {},
pluralRules: {},
};
this.format = function (values) {
var parts = _this.formatToParts(values);
// Hot path for straight simple msg translations
if (parts.length === 1) {
return parts[0].value;
}
var result = parts.reduce(function (all, part) {
if (!all.length ||
part.type !== 0 /* literal */ ||
typeof all[all.length - 1] !== 'string') {
all.push(part.value);
}
else {
all[all.length - 1] += part.value;
}
return all;
}, []);
if (result.length <= 1) {
return result[0] || '';
}
return result;
};
this.formatToParts = function (values) {
return formatToParts(_this.ast, _this.locales, _this.formatters, _this.formats, values, undefined, _this.message);
};
this.resolvedOptions = function () { return ({
locale: Intl.NumberFormat.supportedLocalesOf(_this.locales)[0],
}); };
this.getAst = function () { return _this.ast; };
if (typeof message === 'string') {
this.message = message;
if (!IntlMessageFormat.__parse) {
throw new TypeError('IntlMessageFormat.__parse must be set to process `message` of type `string`');
}
// Parse string messages into an AST.
this.ast = IntlMessageFormat.__parse(message, {
normalizeHashtagInPlural: false,
ignoreTag: opts === null || opts === void 0 ? void 0 : opts.ignoreTag,
});
}
else {
this.ast = message;
}
if (!Array.isArray(this.ast)) {
throw new TypeError('A message must be provided as a String or AST.');
}
// Creates a new object with the specified `formats` merged with the default
// formats.
this.formats = mergeConfigs(IntlMessageFormat.formats, overrideFormats);
// Defined first because it's used to build the format pattern.
this.locales = locales;
this.formatters =
(opts && opts.formatters) || createDefaultFormatters(this.formatterCache);
}
Object.defineProperty(IntlMessageFormat, "defaultLocale", {
get: function () {
if (!IntlMessageFormat.memoizedDefaultLocale) {
IntlMessageFormat.memoizedDefaultLocale = new Intl.NumberFormat().resolvedOptions().locale;
}
return IntlMessageFormat.memoizedDefaultLocale;
},
enumerable: false,
configurable: true
});
IntlMessageFormat.memoizedDefaultLocale = null;
IntlMessageFormat.__parse = dummy.parse;
// Default format options used as the prototype of the `formats` provided to the
// constructor. These are used when constructing the internal Intl.NumberFormat
// and Intl.DateTimeFormat instances.
IntlMessageFormat.formats = {
number: {
currency: {
style: 'currency',
},
percent: {
style: 'percent',
},
},
date: {
short: {
month: 'numeric',
day: 'numeric',
year: '2-digit',
},
medium: {
month: 'short',
day: 'numeric',
year: 'numeric',
},
long: {
month: 'long',
day: 'numeric',
year: 'numeric',
},
full: {
weekday: 'long',
month: 'long',
day: 'numeric',
year: 'numeric',
},
},
time: {
short: {
hour: 'numeric',
minute: 'numeric',
},
medium: {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
},
long: {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
},
full: {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
},
},
};
return IntlMessageFormat;
}());
var __extends$1 = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
(function (IntlErrorCode) {
IntlErrorCode["FORMAT_ERROR"] = "FORMAT_ERROR";
IntlErrorCode["UNSUPPORTED_FORMATTER"] = "UNSUPPORTED_FORMATTER";
IntlErrorCode["INVALID_CONFIG"] = "INVALID_CONFIG";
IntlErrorCode["MISSING_DATA"] = "MISSING_DATA";
IntlErrorCode["MISSING_TRANSLATION"] = "MISSING_TRANSLATION";
})(exports.ReactIntlErrorCode || (exports.ReactIntlErrorCode = {}));
var IntlError = /** @class */ (function (_super) {
__extends$1(IntlError, _super);
function IntlError(code, message, exception) {
var _this = _super.call(this, "[@formatjs/intl Error " + code + "] " + message + " \n" + (exception ? "\n" + exception.message + "\n" + exception.stack : '')) || this;
_this.code = code;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(_this, IntlError);
}
return _this;
}
return IntlError;
}(Error));
var UnsupportedFormatterError = /** @class */ (function (_super) {
__extends$1(UnsupportedFormatterError, _super);
function UnsupportedFormatterError(message, exception) {
return _super.call(this, "UNSUPPORTED_FORMATTER" /* UNSUPPORTED_FORMATTER */, message, exception) || this;
}
return UnsupportedFormatterError;
}(IntlError));
var InvalidConfigError = /** @class */ (function (_super) {
__extends$1(InvalidConfigError, _super);
function InvalidConfigError(message, exception) {
return _super.call(this, "INVALID_CONFIG" /* INVALID_CONFIG */, message, exception) || this;
}
return InvalidConfigError;
}(IntlError));
var MissingDataError = /** @class */ (function (_super) {
__extends$1(MissingDataError, _super);
function MissingDataError(message, exception) {
return _super.call(this, "MISSING_DATA" /* MISSING_DATA */, message, exception) || this;
}
return MissingDataError;
}(IntlError));
var MessageFormatError = /** @class */ (function (_super) {
__extends$1(MessageFormatError, _super);
function MessageFormatError(message, locale, descriptor, exception) {
var _this = _super.call(this, "FORMAT_ERROR" /* FORMAT_ERROR */, message + " \nLocale: " + locale + "\nMessageID: " + (descriptor === null || descriptor === void 0 ? void 0 : descriptor.id) + "\nDefault Message: " + (descriptor === null || descriptor === void 0 ? void 0 : descriptor.defaultMessage) + "\nDescription: " + (descriptor === null || descriptor === void 0 ? void 0 : descriptor.description) + " \n", exception) || this;
_this.descriptor = descriptor;
return _this;
}
return MessageFormatError;
}(IntlError));
var MissingTranslationError = /** @class */ (function (_super) {
__extends$1(MissingTranslationError, _super);
function MissingTranslationError(descriptor, locale) {
var _this = _super.call(this, "MISSING_TRANSLATION" /* MISSING_TRANSLATION */, "Missing message: \"" + descriptor.id + "\" for locale \"" + locale + "\", using " + (descriptor.defaultMessage ? 'default message' : 'id') + " as fallback.") || this;
_this.descriptor = descriptor;
return _this;
}
return MissingTranslationError;
}(IntlError));
var __assign$1 = (undefined && undefined.__assign) || function () {
__assign$1 = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign$1.apply(this, arguments);
};
var __spreadArrays$1 = (undefined && undefined.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function filterProps(props, whitelist, defaults) {
if (defaults === void 0) { defaults = {}; }
return whitelist.reduce(function (filtered, name) {
if (name in props) {
filtered[name] = props[name];
}
else if (name in defaults) {
filtered[name] = defaults[name];
}
return filtered;
}, {});
}
var defaultErrorHandler = function (error) {
};
var DEFAULT_INTL_CONFIG = {
formats: {},
messages: {},
timeZone: undefined,
defaultLocale: 'en',
defaultFormats: {},
onError: defaultErrorHandler,
};
function createIntlCache() {
return {
dateTime: {},
number: {},
message: {},
relativeTime: {},
pluralRules: {},
list: {},
displayNames: {},
};
}
function createFastMemoizeCache$1(store) {
return {
create: function () {
return {
has: function (key) {
return key in store;
},
get: function (key) {
return store[key];
},
set: function (key, value) {
store[key] = value;
},
};
},
};
}
// @ts-ignore this is to deal with rollup's default import shenanigans
var _memoizeIntl$1 = src || memoize$1;
var memoizeIntl$1 = _memoizeIntl$1;
/**
* Create intl formatters and populate cache
* @param cache explicit cache to prevent leaking memory
*/
function createFormatters(cache) {
if (cache === void 0) { cache = createIntlCache(); }
var RelativeTimeFormat = Intl.RelativeTimeFormat;
var ListFormat = Intl.ListFormat;
var DisplayNames = Intl.DisplayNames;
var getDateTimeFormat = memoizeIntl$1(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.DateTimeFormat).bind.apply(_a, __spreadArrays$1([void 0], args)))();
}, {
cache: createFastMemoizeCache$1(cache.dateTime),
strategy: memoizeIntl$1.strategies.variadic,
});
var getNumberFormat = memoizeIntl$1(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.NumberFormat).bind.apply(_a, __spreadArrays$1([void 0], args)))();
}, {
cache: createFastMemoizeCache$1(cache.number),
strategy: memoizeIntl$1.strategies.variadic,
});
var getPluralRules = memoizeIntl$1(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.PluralRules).bind.apply(_a, __spreadArrays$1([void 0], args)))();
}, {
cache: createFastMemoizeCache$1(cache.pluralRules),
strategy: memoizeIntl$1.strategies.variadic,
});
return {
getDateTimeFormat: getDateTimeFormat,
getNumberFormat: getNumberFormat,
getMessageFormat: memoizeIntl$1(function (message, locales, overrideFormats, opts) {
return new IntlMessageFormat(message, locales, overrideFormats, __assign$1({ formatters: {
getNumberFormat: getNumberFormat,
getDateTimeFormat: getDateTimeFormat,
getPluralRules: getPluralRules,
} }, (opts || {})));
}, {
cache: createFastMemoizeCache$1(cache.message),
strategy: memoizeIntl$1.strategies.variadic,
}),
getRelativeTimeFormat: memoizeIntl$1(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new (RelativeTimeFormat.bind.apply(RelativeTimeFormat, __spreadArrays$1([void 0], args)))();
}, {
cache: createFastMemoizeCache$1(cache.relativeTime),
strategy: memoizeIntl$1.strategies.variadic,
}),
getPluralRules: getPluralRules,
getListFormat: memoizeIntl$1(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new (ListFormat.bind.apply(ListFormat, __spreadArrays$1([void 0], args)))();
}, {
cache: createFastMemoizeCache$1(cache.list),
strategy: memoizeIntl$1.strategies.variadic,
}),
getDisplayNames: memoizeIntl$1(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new (DisplayNames.bind.apply(DisplayNames, __spreadArrays$1([void 0], args)))();
}, {
cache: createFastMemoizeCache$1(cache.displayNames),
strategy: memoizeIntl$1.strategies.variadic,
}),
};
}
function getNamedFormat(formats, type, name, onError) {
var formatType = formats && formats[type];
var format;
if (formatType) {
format = formatType[name];
}
if (format) {
return format;
}
onError(new UnsupportedFormatterError("No " + type + " format named: " + name));
}
var __assign$2 = (undefined && undefined.__assign) || function () {
__assign$2 = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign$2.apply(this, arguments);
};
function setTimeZoneInOptions(opts, timeZone) {
return Object.keys(opts).reduce(function (all, k) {
all[k] = __assign$2({ timeZone: timeZone }, opts[k]);
return all;
}, {});
}
function deepMergeOptions(opts1, opts2) {
var keys = Object.keys(__assign$2(__assign$2({}, opts1), opts2));
return keys.reduce(function (all, k) {
all[k] = __assign$2(__assign$2({}, (opts1[k] || {})), (opts2[k] || {}));
return all;
}, {});
}
function deepMergeFormatsAndSetTimeZone(f1, timeZone) {
if (!timeZone) {
return f1;
}
var mfFormats = IntlMessageFormat.formats;
return __assign$2(__assign$2(__assign$2({}, mfFormats), f1), { date: deepMergeOptions(setTimeZoneInOptions(mfFormats.date, timeZone), setTimeZoneInOptions(f1.date || {}, timeZone)), time: deepMergeOptions(setTimeZoneInOptions(mfFormats.time, timeZone), setTimeZoneInOptions(f1.time || {}, timeZone)) });
}
function formatMessage(_a, state, messageDescriptor, values) {
var locale = _a.locale, formats = _a.formats, messages = _a.messages, defaultLocale = _a.defaultLocale, defaultFormats = _a.defaultFormats, onError = _a.onError, timeZone = _a.timeZone, defaultRichTextElements = _a.defaultRichTextElements;
if (messageDescriptor === void 0) { messageDescriptor = { id: '' }; }
var msgId = messageDescriptor.id, defaultMessage = messageDescriptor.defaultMessage;
// `id` is a required field of a Message Descriptor.
invariant(!!msgId, '[@formatjs/intl] An `id` must be provided to format a message.');
var id = String(msgId);
var message =
// In case messages is Object.create(null)
// e.g import('foo.json') from webpack)
// See https://github.com/formatjs/formatjs/issues/1914
messages &&
Object.prototype.hasOwnProperty.call(messages, id) &&
messages[id];
// IMPORTANT: Hot path if `message` is AST with a single literal node
if (Array.isArray(message) &&
message.length === 1 &&
message[0].type === dummy.TYPE.literal) {
return message[0].value;
}
if (!values &&
message &&
typeof message === 'string' &&
defaultRichTextElements) {
console.error("[@formatjs/intl] \"defaultRichTextElements\" was specified but \"message\" was not pre-compiled. \nPlease consider using \"@formatjs/cli\" to pre-compile your messages for performance.\nFor more details see https://formatjs.io/docs/getting-started/message-distribution");
}
// IMPORTANT: Hot path straight lookup for performance
if (!values &&
message &&
typeof message === 'string' &&
!defaultRichTextElements) {
return message.replace(/'\{(.*?)\}'/gi, "{$1}");
}
values = __assign$2(__assign$2({}, defaultRichTextElements), (values || {}));
formats = deepMergeFormatsAndSetTimeZone(formats, timeZone);
defaultFormats = deepMergeFormatsAndSetTimeZone(defaultFormats, timeZone);
if (!message) {
if (!defaultMessage ||
(locale && locale.toLowerCase() !== defaultLocale.toLowerCase())) {
// This prevents warnings from littering the console in development
// when no `messages` are passed into the <IntlProvider> for the
// default locale.
onError(new MissingTranslationError(messageDescriptor, locale));
}
if (defaultMessage) {
try {
var formatter = state.getMessageFormat(defaultMessage, defaultLocale, defaultFormats);
return formatter.format(values);
}
catch (e) {
onError(new MessageFormatError("Error formatting default message for: \"" + id + "\", rendering default message verbatim", locale, messageDescriptor, e));
return typeof defaultMessage === 'string' ? defaultMessage : id;
}
}
return id;
}
// We have the translated message
try {
var formatter = state.getMessageFormat(message, locale, formats, {
formatters: state,
});
return formatter.format(values);
}
catch (e) {
onError(new MessageFormatError("Error formatting message: \"" + id + "\", using " + (defaultMessage ? 'default message' : 'id') + " as fallback.", locale, messageDescriptor, e));
}
if (defaultMessage) {
try {
var formatter = state.getMessageFormat(defaultMessage, defaultLocale, defaultFormats);
return formatter.format(values);
}
catch (e) {
onError(new MessageFormatError("Error formatting the default message for: \"" + id + "\", rendering message verbatim", locale, messageDescriptor, e));
}
}
if (typeof message === 'string') {
return message;
}
if (typeof defaultMessage === 'string') {
return defaultMessage;
}
return id;
}
var __assign$3 = (undefined && undefined.__assign) || function () {
__assign$3 = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign$3.apply(this, arguments);
};
var DATE_TIME_FORMAT_OPTIONS = [
'localeMatcher',
'formatMatcher',
'timeZone',
'hour12',
'weekday',
'era',
'year',
'month',
'day',
'hour',
'minute',
'second',
'timeZoneName',
'hourCycle',
'dateStyle',
'timeStyle',
'fractionalSecondDigits',
'calendar',
// 'dayPeriod',
'numberingSystem',
];
function getFormatter(_a, type, getDateTimeFormat, options) {
var locale = _a.locale, formats = _a.formats, onError = _a.onError, timeZone = _a.timeZone;
if (options === void 0) { options = {}; }
var format = options.format;
var defaults = __assign$3(__assign$3({}, (timeZone && { timeZone: timeZone })), (format && getNamedFormat(formats, type, format, onError)));
var filteredOptions = filterProps(options, DATE_TIME_FORMAT_OPTIONS, defaults);
if (type === 'time' &&
!filteredOptions.hour &&
!filteredOptions.minute &&
!filteredOptions.second) {
// Add default formatting options if hour, minute, or second isn't defined.
filteredOptions = __assign$3(__assign$3({}, filteredOptions), { hour: 'numeric', minute: 'numeric' });
}
return getDateTimeFormat(locale, filteredOptions);
}
function formatDate(config, getDateTimeFormat, value, options) {
if (options === void 0) { options = {}; }
var date = typeof value === 'string' ? new Date(value || 0) : value;
try {
return getFormatter(config, 'date', getDateTimeFormat, options).format(date);
}
catch (e) {
config.onError(new IntlError("FORMAT_ERROR" /* FORMAT_ERROR */, 'Error formatting date.', e));
}
return String(date);
}
function formatTime(config, getDateTimeFormat, value, options) {
if (options === void 0) { options = {}; }
var date = typeof value === 'string' ? new Date(value || 0) : value;
try {
return getFormatter(config, 'time', getDateTimeFormat, options).format(date);
}
catch (e) {
config.onError(new IntlError("FORMAT_ERROR" /* FORMAT_ERROR */, 'Error formatting time.', e));
}
return String(date);
}
function formatDateToParts(config, getDateTimeFormat, value, options) {
if (options === void 0) { options = {}; }
var date = typeof value === 'string' ? new Date(value || 0) : value;
try {
return getFormatter(config, 'date', getDateTimeFormat, options).formatToParts(date);
}
catch (e) {
config.onError(new IntlError("FORMAT_ERROR" /* FORMAT_ERROR */, 'Error formatting date.', e));
}
return [];
}
function formatTimeToParts(config, getDateTimeFormat, value, options) {
if (options === void 0) { options = {}; }
var date = typeof value === 'string' ? new Date(value || 0) : value;
try {
return getFormatter(config, 'time', getDateTimeFormat, options).formatToParts(date);
}
catch (e) {
config.onError(new IntlError("FORMAT_ERROR" /* FORMAT_ERROR */, 'Error formatting time.', e));
}
return [];
}
var DISPLAY_NAMES_OPTONS = [
'localeMatcher',
'style',
'type',
'fallback',
];
function formatDisplayName(_a, getDisplayNames, value, options) {
var locale = _a.locale, onError = _a.onError;
if (options === void 0) { options = {}; }
var DisplayNames = Intl.DisplayNames;
if (!DisplayNames) {
onError(new FormatError("Intl.DisplayNames is not available in this environment.\nTry polyfilling it using \"@formatjs/intl-displaynames\"\n", "MISSING_INTL_API" /* MISSING_INTL_API */));
}
var filteredOptions = filterProps(options, DISPLAY_NAMES_OPTONS);
try {
return getDisplayNames(locale, filteredOptions).of(value);
}
catch (e) {
onError(new IntlError("FORMAT_ERROR" /* FORMAT_ERROR */, 'Error formatting display name.', e));
}
}
var LIST_FORMAT_OPTIONS = [
'localeMatcher',
'type',
'style',
];
var now = Date.now();
function generateToken(i) {
return now + "_" + i + "_" + now;
}
function formatList(_a, getListFormat, values, options) {
var locale = _a.locale, onError = _a.onError;
if (options === void 0) { options = {}; }
var ListFormat = Intl.ListFormat;
if (!ListFormat) {
onError(new FormatError("Intl.ListFormat is not available in this environment.\nTry polyfilling it using \"@formatjs/intl-listformat\"\n", "MISSING_INTL_API" /* MISSING_INTL_API */));
}
var filteredOptions = filterProps(options, LIST_FORMAT_OPTIONS);
try {
var richValues_1 = {};
var serializedValues = values.map(function (v, i) {
if (typeof v === 'object') {
var id = generateToken(i);
richValues_1[id] = v;
return id;
}
return String(v);
});
if (!Object.keys(richValues_1).length) {
return getListFormat(locale, filteredOptions).format(serializedValues);
}
var parts = getListFormat(locale, filteredOptions).formatToParts(serializedValues);
return parts.reduce(function (all, el) {
var val = el.value;
if (richValues_1[val]) {
all.push(richValues_1[val]);
}
else if (typeof all[all.length - 1] === 'string') {
all[all.length