From 3f60e44b71702c69ae09ca426466933a72a7ad2c Mon Sep 17 00:00:00 2001 From: Kang Seonghoon Date: Sat, 14 Aug 2021 04:41:43 +0900 Subject: [PATCH] Fix an invalid code when exactly 1--2 abbreviations are in use --- index.js | 2 +- test.js | 27 ++++++++++++++++++++++----- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index f0732ed..16e3a75 100644 --- a/index.js +++ b/index.js @@ -930,7 +930,7 @@ export class Packer { outputVar = `c=w=String.fromCharCode(...z)`; } else if (this.preparedJs.abbrs.length < 3) { secondLine += `c=w=String.fromCharCode(...z);`; - for (const [, abbr] in this.preparedJs.abbrs) { + for (const [, abbr] of this.preparedJs.abbrs) { secondLine += `with(c.split(\`${escapeCharInTemplate(abbr)}\`))c=join(shift());`; } } else { diff --git a/test.js b/test.js index 00f75f4..2f01162 100644 --- a/test.js +++ b/test.js @@ -229,14 +229,31 @@ test('prepareJs without abbrs', t => { //------------------------------------------------------------------------------ -test('Packer', t => { - const packer = new Packer([{ type: 'js', action: 'eval', data: 'okay = 12345;' }], { maxMemoryMB: 10 }); +function packAndEval(data) { + const packer = new Packer([{ type: 'js', action: 'eval', data }], { maxMemoryMB: 10 }); const { firstLine, secondLine } = packer.makeDecoder(); // XXX this is only okay-ish because we know the decoder internals const possibleVars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$'; - let okay = false; - eval(`let ${[...possibleVars].join(',')};${firstLine};${secondLine}`); - t.is(okay, 12345); + // Function doesn't inherit the strictness, which is required for Roadroller outputs + return Function('code', 'return eval(code)')(`let ${[...possibleVars].join(',')};${firstLine};${secondLine}`); +} + +test('Packer', t => { + t.is(packAndEval('3 + 4 * 5'), 23); + + // abbreviation tests + t.is(packAndEval(` + const alpha = 42; + alpha + alpha + alpha + alpha + alpha + `), 42 * 5); + t.is(packAndEval(` + const alpha = 42, beta = 54; + (alpha + alpha + alpha + alpha + alpha) * (beta + beta + beta + beta) + `), 42 * 5 * 54 * 4); + t.is(packAndEval(` + const alpha = 42, beta = 54, gamma = 13; + (alpha + alpha + alpha + alpha + alpha) * (beta + beta + beta + beta) * (gamma + gamma + gamma) + `), 42 * 5 * 54 * 4 * 13 * 3); });