Skip to content

Commit

Permalink
fix: escape defaultMessage properly, fixes #1158 (#1345)
Browse files Browse the repository at this point in the history
  • Loading branch information
longlho authored Jul 3, 2019
1 parent 493d6dd commit 96e9bae
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@
"watchify": "^3.7.0"
},
"scripts": {
"benchmark": "TS_NODE_PROJECT='test/perf/tsconfig.json' ts-node test/perf/index.tsx",
"benchmark": "NODE_ENV=production TS_NODE_PROJECT='test/perf/tsconfig.json' ts-node test/perf/index.tsx",
"build:dist:dev": "cross-env NODE_ENV=development rollup -c rollup.config.dist.js",
"build:dist:prod": "cross-env NODE_ENV=production rollup -c rollup.config.dist.js",
"build:dist": "npm run build:dist:dev && npm run build:dist:prod",
Expand Down
15 changes: 14 additions & 1 deletion src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,19 @@ function getNamedFormat<T extends keyof CustomFormats>(
onError(createError(`No ${type} format named: ${name}`));
}

/**
* Escape a raw msg when we run in prod mode
* https://github.com/formatjs/formatjs/blob/master/packages/intl-messageformat-parser/src/parser.pegjs#L155
*/
function escapeUnformattedMessage(msg: string): string {
return msg
.replace(/\\u([\da-fA-F]{4})/g, (_, digits) =>
String.fromCharCode(parseInt(digits, 16))
)
.replace(/\\\{/g, '\u007B')
.replace(/\\\}/g, '\u007D');
}

export function formatDate(
{
locale,
Expand Down Expand Up @@ -266,7 +279,7 @@ export function formatMessage(
if (!hasValues && process.env.NODE_ENV === 'production') {
const val = message || defaultMessage || id;
if (typeof val === 'string') {
return val;
return escapeUnformattedMessage(val);
}
invariant(
val.elements.length === 1 &&
Expand Down
15 changes: 15 additions & 0 deletions test/unit/format.js
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,21 @@ RangeError: Invalid unit argument`
formatMessage = f.formatMessage.bind(null, config, state);
});

['Hello, World!\\{foo\\}', '\\ud83d\\udc04'].forEach(msg =>
it(`should render escaped msg ${msg} properly in production`, () => {
process.env.NODE_ENV = 'production';

const descriptor = {
id: 'hello',
defaultMessage: msg,
};

const mf = new IntlMessageFormat(msg, 'en');

expect(formatMessage(descriptor)).toBe(mf.format());
})
);

it('throws when no Message Descriptor is provided', () => {
expect(() => formatMessage()).toThrow(
'[React Intl] An `id` must be provided to format a message.'
Expand Down

0 comments on commit 96e9bae

Please sign in to comment.