From 72f119345f3ce8fd479501e7081dcc54ee5e3d49 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Tue, 13 Jul 2021 11:30:55 +0200 Subject: [PATCH] fix(async-rewriter2): fix 'use strict' handling MONGOSH-890 - Fix dumb bug where I forgot to check whether the program actually contains a body before assuming that the presence of a single directive would indicate that the program consisted only of that - Make sure that 'use strict' actually gets propagated into the transpiled result --- .../src/async-writer-babel.spec.ts | 26 +++++++++++++++++++ .../src/stages/wrap-as-iife.ts | 26 +++++++++++-------- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/packages/async-rewriter2/src/async-writer-babel.spec.ts b/packages/async-rewriter2/src/async-writer-babel.spec.ts index d7263d81f9..5aea31235c 100644 --- a/packages/async-rewriter2/src/async-writer-babel.spec.ts +++ b/packages/async-rewriter2/src/async-writer-babel.spec.ts @@ -96,6 +96,32 @@ describe('AsyncWriter', () => { }); }); + context('use strict', () => { + it('parses a plain "use strict"; as a string literal', () => { + expect(runTranspiledCode('"use strict"')).to.equal('use strict'); + expect(runTranspiledCode('"use strict";')).to.equal('use strict'); + expect(runTranspiledCode("'use strict'")).to.equal('use strict'); + expect(runTranspiledCode("'use strict';")).to.equal('use strict'); + }); + + it('runs code that starts with "use strict"', () => { + expect(runTranspiledCode("'use strict'; 144 + 233;")).to.equal(377); + }); + + it('fails to run invalid strict-mode code', () => { + try { + runTranspiledCode("'use strict'; delete Object.prototype"); + expect.fail('missed exception'); + } catch (err) { + expect(err.name).to.equal('TypeError'); + } + }); + + it('runs code in sloppy mode by default', () => { + expect(runTranspiledCode('delete Object.prototype')).to.equal(false); + }); + }); + context('scoping', () => { it('adds functions to the global scope as expected', () => { const f = runTranspiledCode('function f() {}'); diff --git a/packages/async-rewriter2/src/stages/wrap-as-iife.ts b/packages/async-rewriter2/src/stages/wrap-as-iife.ts index 5a2a26f181..e8b1d2b095 100644 --- a/packages/async-rewriter2/src/stages/wrap-as-iife.ts +++ b/packages/async-rewriter2/src/stages/wrap-as-iife.ts @@ -128,10 +128,11 @@ export default ({ types: t }: { types: typeof BabelTypes }): babel.PluginObj t.variableDeclaration('var', [t.variableDeclarator(t.identifier(v))])), - ...this.functionDeclarations, - t.expressionStatement(t.callExpression( - t.arrowFunctionExpression( - [], - t.blockStatement(this.movedStatements) - ), []))])); + path.replaceWith(t.program( + [ + ...this.variables.map( + v => t.variableDeclaration('var', [t.variableDeclarator(t.identifier(v))])), + ...this.functionDeclarations, + t.expressionStatement(t.callExpression( + t.arrowFunctionExpression( + [], + t.blockStatement(this.movedStatements) + ), [])) + ], + path.node.directives)); } }, BlockStatement: {