Skip to content

Commit bc9b441

Browse files
committed
Fix #91
1 parent 5013a4f commit bc9b441

File tree

3 files changed

+44
-2
lines changed

3 files changed

+44
-2
lines changed

src/templates/functionLength.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import Template from "./template";
2+
3+
/**
4+
* Helper function to set `function.length` property.
5+
*/
6+
export const FunctionLengthTemplate = Template(`
7+
function {name}(functionObject, functionLength){
8+
Object["defineProperty"](functionObject, "length", {
9+
"value": functionLength,
10+
"configurable": true
11+
});
12+
return functionObject;
13+
}
14+
`);

src/transforms/minify.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
isForInitialize,
2323
append,
2424
isVarContext,
25+
computeFunctionLength,
2526
} from "../util/insert";
2627
import { isValidIdentifier, isEquivalent } from "../util/compare";
2728
import { walk, isBlock } from "../traverse";
@@ -258,8 +259,15 @@ export default class Minify extends Transform {
258259
append(
259260
parents[parents.length - 1] || object,
260261
Template(`
261-
function ${this.arrowFunctionName}(arrowFn){
262-
return function(){ return arrowFn(...arguments) }
262+
function ${this.arrowFunctionName}(arrowFn, functionLength){
263+
var functionObject = function(){ return arrowFn(...arguments) };
264+
265+
Object["defineProperty"](functionObject, "length", {
266+
"value": functionLength,
267+
"configurable": true
268+
});
269+
270+
return functionObject;
263271
}
264272
`).single()
265273
);
@@ -268,6 +276,7 @@ export default class Minify extends Transform {
268276
const wrap = (object: Node) => {
269277
return CallExpression(Identifier(this.arrowFunctionName), [
270278
clone(object),
279+
Literal(computeFunctionLength(object.params)),
271280
]);
272281
};
273282

test/transforms/minify.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,3 +517,22 @@ test("Variant #26: Don't break nested redefined function declaration", async ()
517517

518518
expect(TEST_OUTPUT).toStrictEqual(1);
519519
});
520+
521+
// https://github.com/MichaelXF/js-confuser/issues/91
522+
test("Variant #27: Preserve function.length property", async () => {
523+
var output = await JsConfuser(
524+
`
525+
function oneParameter(a){};
526+
var twoParameters = function({a},{b,c},...d){};
527+
function threeParameters(a,b,c,d = 1,{e},...f){};
528+
529+
TEST_OUTPUT = oneParameter.length + twoParameters.length + threeParameters.length;
530+
`,
531+
{ target: "node", minify: true }
532+
);
533+
534+
var TEST_OUTPUT;
535+
eval(output);
536+
537+
expect(TEST_OUTPUT).toStrictEqual(6);
538+
});

0 commit comments

Comments
 (0)