Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export function extractValueReferencesFromMessage(message, messageId) {
// Skip validation if message doesn't use ICU.
if (!message.includes('{')) {
return [];
}
let messageAST;
try {
messageAST = parser.parse(message);
} catch (error) {
if (error.name === 'SyntaxError') {
const errorWithContext = createParserErrorMessage(message, {
loc: {
line: error.location.start.line,
column: error.location.start.column - 1,
},
message: error.message,
});
throw createFailError(
`Couldn't parse default message ("${messageId}"):\n${errorWithContext}`
);
}
throw error;
// `id` is a required field of a Message Descriptor.
invariant(id, '[React Intl] An `id` must be provided to format a message.');
const message = messages && messages[id];
const hasValues = Object.keys(values).length > 0;
// Avoid expensive message formatting for simple messages without values. In
// development messages will always be formatted in case of missing values.
if (!hasValues && process.env.NODE_ENV === 'production') {
const val = message || defaultMessage || id;
if (typeof val === 'string') {
return escapeUnformattedMessage(val);
}
invariant(
val.length === 1 && val[0].type === TYPE.literal,
'Message has placeholders but no values was provided'
);
return (val[0] as LiteralElement).value;
}
let formattedMessageParts: Array = [];
if (message) {
try {
let formatter = state.getMessageFormat(message, locale, formats, {
formatters: state,
});
formattedMessageParts = formatter.formatHTMLMessage(values);
} catch (e) {
onError(
many {{var0, number} message}
other {{var0, number} messages}
}`;
formattedMessages.push(
);
}
ReactDOMServer.renderToString(
{formattedMessages}
);
});
const cachedAst = parse(
`{var0, plural,
zero {{var0, number} message}
one {{var0, number} message}
few {{var0, number} message}
many {{var0, number} message}
other {{var0, number} messages}
}`
);
suite.add(
'100 x with placeholder, cached in AST form',
function() {
let messages: Record = {};
let formattedMessages = [];
for (let i = 0, len = 100; i < len; i += 1) {
messages[i] = cachedAst;
formattedMessages.push(
config = {
locale: 'en',
messages: {
no_args: 'Hello, World!',
with_arg: 'Hello, {name}!',
with_named_format: 'It is {now, date, year-only}',
with_html: 'Hello, <b>{name}</b>!',
missing: undefined,
empty: '',
invalid: 'invalid {}',
missing_value: 'missing {arg_missing}',
missing_named_format: 'missing {now, date, format_missing}',
ast_simple: parse('hello world'),
ast_var: parse('hello there, {name}'),
},
formats: {
date: {
'year-only': {
year: 'numeric',
},
missing: undefined,
},
time: {
'hour-only': {
hour: '2-digit',
hour12: false,
},
missing: undefined,
translate(message) {
let ast = parse(message);
let translated = this.transform(ast);
return print(translated);
}
translate(message) {
const ast = parse(message);
const translated = this.transform(ast);
return print(translated);
}