Skip to content

Commit

Permalink
fix: babel-plugin-minify-mangle-names default parameter error (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
j4k0xb committed Dec 31, 2023
1 parent 40d3eb0 commit 9aca65a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
37 changes: 35 additions & 2 deletions packages/webcrack/src/transforms/mangle.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,37 @@
import traverse, { NodePath } from '@babel/traverse';
import { statement } from '@babel/template';
import traverse, { NodePath, Visitor, visitors } from '@babel/traverse';
import * as t from '@babel/types';
import mangle from 'babel-plugin-minify-mangle-names';
import { Transform } from '../ast-utils';

// See https://github.com/j4k0xb/webcrack/issues/41 and https://github.com/babel/minify/issues/1023
const fixDefaultParamError: Visitor = {
Function(path) {
const { params } = path.node;
for (let i = params.length - 1; i >= 0; i--) {
const param = params[i];
if (
!t.isAssignmentPattern(param) ||
!t.isIdentifier(param.left) ||
t.isLiteral(param.right)
)
continue;

if (
path.isArrowFunctionExpression() &&
!t.isBlockStatement(path.node.body)
) {
path.node.body = t.blockStatement([t.returnStatement(path.node.body)]);
}
(path.get('body') as NodePath<t.BlockStatement>).unshiftContainer(
'body',
statement`if (${param.left} !== undefined) ${param.left} = ${param.right}`(),
);
param.right = t.identifier('undefined');
}
},
};

export default {
name: 'mangle',
tags: ['safe'],
Expand All @@ -12,8 +41,12 @@ export default {
// eslint-disable-next-line @typescript-eslint/unbound-method
const { getSource } = NodePath.prototype;
NodePath.prototype.getSource = () => '';
const visitor = visitors.merge([
fixDefaultParamError,
mangle({ types: t, traverse }).visitor,
]);

traverse(ast, mangle({ types: t, traverse }).visitor, undefined, {
traverse(ast, visitor, undefined, {
opts: {
eval: true,
topLevel: true,
Expand Down
28 changes: 28 additions & 0 deletions packages/webcrack/test/mangle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { test } from 'vitest';
import { testTransform } from '.';
import mangle from '../src/transforms/mangle';

const expectJS = testTransform(mangle);

// https://github.com/j4k0xb/webcrack/issues/41
test('rename and extract non-literal default parameters', () => {
expectJS(`
function func(arg1, arg2 = 0, arg3 = arg1, arg4 = 30) {
return arg1;
}
`).toMatchInlineSnapshot(`
function a(a, b = 0, c = undefined, d = 30) {
if (c !== undefined) c = a;
return a;
}
`);

expectJS(`
const func = (arg1, arg2 = 0, arg3 = arg1, arg4 = 30) => arg1;
`).toMatchInlineSnapshot(`
const a = (a, b = 0, c = undefined, d = 30) => {
if (c !== undefined) c = a;
return a;
};
`);
});

0 comments on commit 9aca65a

Please sign in to comment.