From 2fbc92fd2e8c36f506f2c777f12e7cb20d7b5c08 Mon Sep 17 00:00:00 2001 From: Tobias Bosch Date: Fri, 18 Aug 2017 15:02:10 -0700 Subject: [PATCH] fix(compiler): quote non identifiers in map keys. (#18788) PR Close #18788 --- packages/compiler-cli/src/transformers/node_emitter.ts | 5 ++++- packages/compiler-cli/test/transformers/node_emitter_spec.ts | 5 +++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/compiler-cli/src/transformers/node_emitter.ts b/packages/compiler-cli/src/transformers/node_emitter.ts index 29cd86863c..e6a2ca7056 100644 --- a/packages/compiler-cli/src/transformers/node_emitter.ts +++ b/packages/compiler-cli/src/transformers/node_emitter.ts @@ -14,6 +14,7 @@ export interface Node { sourceSpan: ParseSourceSpan|null; } const METHOD_THIS_NAME = 'this'; const CATCH_ERROR_NAME = 'error'; const CATCH_STACK_NAME = 'stack'; +const _VALID_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i; export class TypeScriptNodeEmitter { updateSourceFile(sourceFile: ts.SourceFile, stmts: Statement[], preamble?: string): @@ -421,7 +422,9 @@ class _NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { return this.record( expr, ts.createObjectLiteral(expr.entries.map( entry => ts.createPropertyAssignment( - entry.quoted ? ts.createLiteral(entry.key) : entry.key, + entry.quoted || !_VALID_IDENTIFIER_RE.test(entry.key) ? + ts.createLiteral(entry.key) : + entry.key, entry.value.visitExpression(this, null))))); } diff --git a/packages/compiler-cli/test/transformers/node_emitter_spec.ts b/packages/compiler-cli/test/transformers/node_emitter_spec.ts index f7b169c2a7..050f2621ca 100644 --- a/packages/compiler-cli/test/transformers/node_emitter_spec.ts +++ b/packages/compiler-cli/test/transformers/node_emitter_spec.ts @@ -169,10 +169,11 @@ describe('TypeScriptNodeEmitter', () => { expect(emitStmt(o.literalMap([ {key: 'someKey', value: o.literal(1), quoted: false}, {key: 'a', value: o.literal('a'), quoted: false}, - {key: '*', value: o.literal('star'), quoted: true}, + {key: 'b', value: o.literal('b'), quoted: true}, + {key: '*', value: o.literal('star'), quoted: false}, ]).toStmt()) .replace(/\s+/gm, '')) - .toEqual(`({someKey:1,a:"a","*":"star"});`); + .toEqual(`({someKey:1,a:"a","b":"b","*":"star"});`); }); it('should support blank literals', () => {