Skip to content

Commit d87c4e5

Browse files
alexander-akaitclaude
authored andcommitted
fix(javascript): keep a call whose class reads new.target, and minify name caches through terser's tree
A class's heritage and computed keys run in the function defining it, so a call returning a class that reads that function's `new.target` stays a call. What only terser's tree reads (`nameCache`, `wrap`, property mangling and the rest) is minified through it rather than refused, and the cache suite's snapshots print the one pass. Claude-Session: https://claude.ai/code/session_01Tgxgyb4N35ndP6cC4KcrXC
1 parent fb2343c commit d87c4e5

6 files changed

Lines changed: 132 additions & 28 deletions

File tree

‎lib/javascript/jsMinify.js‎

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -160,11 +160,8 @@ const jsMinify = async (
160160

161161
const [[file, given]] = Object.entries(input);
162162
const code = typeof given === "string" ? given : given.toString("utf8");
163-
// One walk reads, mangles, compresses and prints it, as `cssMinify` runs
164-
// its stylesheet. Naming the input asks for the map the plugin chains.
165-
const result = new webpack.javascript.syntax.SourceProcessor().process(code, {
163+
const minifyOptions = {
166164
...options,
167-
mode: "minify",
168165
...(as === undefined ? undefined : { sourceType: as }),
169166
compress,
170167
mangle:
@@ -174,9 +171,41 @@ const jsMinify = async (
174171
? options.mangle
175172
: { ...options.mangle },
176173
parse: { ...options.parse },
177-
format,
178-
...(sourceMap ? { source: file, content: code } : undefined)
179-
});
174+
format
175+
};
176+
const { syntax } = webpack.javascript;
177+
/** @type {{ code: string, map?: SourceMap }} */
178+
let result;
179+
try {
180+
// One walk reads, mangles, compresses and prints it, as `cssMinify`
181+
// runs its stylesheet. Naming the input asks for the map the plugin chains.
182+
result = new syntax.SourceProcessor().process(code, {
183+
...minifyOptions,
184+
mode: "minify",
185+
...(sourceMap ? { source: file, content: code } : undefined)
186+
});
187+
} catch (err) {
188+
if (
189+
/** @type {Error & { code?: string }} */ (err).code !==
190+
syntax.printer.ONE_PASS_UNSUPPORTED
191+
) {
192+
throw err;
193+
}
194+
// What only terser's tree supports is minified through it.
195+
const minified = await (
196+
await syntax.printer.load()
197+
).minify(
198+
{ [file]: code },
199+
/** @type {MinifyOptions} */ ({
200+
...minifyOptions,
201+
sourceMap: sourceMap ? { asObject: true } : undefined
202+
})
203+
);
204+
result = {
205+
code: /** @type {string} */ (minified.code),
206+
map: /** @type {SourceMap | undefined} */ (minified.map || undefined)
207+
};
208+
}
180209

181210
return {
182211
// A handler printed as nothing (dropped whole, or no code asked for) is

‎lib/javascript/syntax-printer.js‎

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9969,9 +9969,13 @@ const installMinify = (modules) => {
99699969
preparing
99709970
);
99719971
if (preparing && treeSource === null) {
9972-
throw new Error(
9973-
"javascript syntax: the one-pass minify reads one source, without `wrap`, `enclose`, `nameCache`, `ie8`, `safari10`, property mangling or `keep_fnames`/`keep_classnames` as a function or pattern"
9972+
const error = /** @type {Error & { code: string }} */ (
9973+
new Error(
9974+
"javascript syntax: the one-pass minify reads one source, without `wrap`, `enclose`, `nameCache`, `ie8`, `safari10`, property mangling or `keep_fnames`/`keep_classnames` as a function or pattern"
9975+
)
99749976
);
9977+
error.code = ONE_PASS_UNSUPPORTED;
9978+
throw error;
99759979
}
99769980
/** @type {ParsedTree | null} */
99779981
let parsedTree = null;
@@ -18071,6 +18075,9 @@ const PARSE_FUNCTION_BODY = Symbol("a source read as a function body");
1807118075
// The option a minify is read and mangled under for the JavaScript
1807218076
// `SourceProcessor`, which compresses it as it prints.
1807318077
const PREPARES_NODE_PRINT = Symbol("a minify the SourceProcessor prints");
18078+
// The `code` of the error a one-pass minify throws for what only terser's
18079+
// tree supports.
18080+
const ONE_PASS_UNSUPPORTED = "WEBPACK_ONE_PASS_UNSUPPORTED";
1807418081

1807518082
/**
1807618083
* @param {NodeToken | number} first a node's token, or its number
@@ -64082,7 +64089,11 @@ const createNodePrinter = (modules) => {
6408264089
}
6408364090
const id = tree.field(0, Field.id, fn);
6408464091
const name = id === 0 ? "" : tree.name(id);
64085-
return findNode(value, (node) => {
64092+
/**
64093+
* @param {number} node a node of the value
64094+
* @returns {boolean | undefined} true where it reads the function itself, undefined to look inside
64095+
*/
64096+
const readsFunction = (node) => {
6408664097
switch (tree.type(node)) {
6408764098
case NodeType.ThisExpression:
6408864099
case NodeType.Super:
@@ -64098,10 +64109,13 @@ const createNodePrinter = (modules) => {
6409864109
case NodeType.ArrowFunctionExpression:
6409964110
// An arrow reads the function's `this` and `arguments`.
6410064111
return count !== 0 || undefined;
64101-
case NodeType.FunctionExpression:
64102-
case NodeType.FunctionDeclaration:
6410364112
case NodeType.ClassExpression:
6410464113
case NodeType.ClassDeclaration:
64114+
// Its heritage and computed keys run in the function.
64115+
if (count === 0 && classRunsIn(node, readsFunction)) return true;
64116+
// falls through
64117+
case NodeType.FunctionExpression:
64118+
case NodeType.FunctionDeclaration:
6410564119
// What it reads there is its own, but for a name.
6410664120
return Boolean(
6410764121
count !== 0 ||
@@ -64116,9 +64130,32 @@ const createNodePrinter = (modules) => {
6411664130
default:
6411764131
return undefined;
6411864132
}
64119-
})
64120-
? 0
64121-
: value;
64133+
};
64134+
return findNode(value, readsFunction) ? 0 : value;
64135+
};
64136+
64137+
/**
64138+
* Whether what a class runs where it is defined, its heritage and computed
64139+
* keys, holds a node a test finds.
64140+
* @param {number} node the class
64141+
* @param {(node: number) => boolean | undefined} test the test, as `findNode` runs it
64142+
* @returns {boolean} true where one does
64143+
*/
64144+
const classRunsIn = (node, test) => {
64145+
const heritage = childOf(Field.superClass, node);
64146+
if (heritage !== 0 && findNode(heritage, test)) return true;
64147+
const body = childOf(Field.body, node);
64148+
const count = tree.fieldCount(Field.body, body);
64149+
for (let i = 0; i < count; i++) {
64150+
const member = tree.field(i, Field.body, body);
64151+
if (
64152+
tree.flag(Flag.computed, member) &&
64153+
findNode(childOf(Field.key, member), test)
64154+
) {
64155+
return true;
64156+
}
64157+
}
64158+
return false;
6412264159
};
6412364160

6412464161
/**
@@ -69036,6 +69073,7 @@ const prepareMinify = (text, options) => {
6903669073

6903769074
module.exports = {
6903869075
NODE_KIND_ANCESTRY,
69076+
ONE_PASS_UNSUPPORTED,
6903969077
prepareMinify,
6904069078
plainIdentifier,
6904169079
load,
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
22

3-
exports[`ConfigCacheTestCases optimization minify-object-enumeration exported tests should enumerate a string's UTF-16 code units 1`] = `"function(){return[[\`0\`,\`1\`],[\`a\`,\`b\`],[[\`0\`,\`a\`]],[\`\\\\ud800\`],[],[],[]]}"`;
3+
exports[`ConfigCacheTestCases optimization minify-object-enumeration exported tests should enumerate a string's UTF-16 code units 1`] = `"function enumerate(){return[Object.keys(\\"\\\\u{1f600}\\"),Object.values(\\"ab\\"),Object.entries(\\"a\\"),Object.values(\\"\\\\ud800\\"),Object.keys(\\"\\"),Object.values(\\"\\"),Object.entries(\\"\\")]}"`;
44

5-
exports[`ConfigCacheTestCases optimization minify-object-enumeration exported tests should enumerate array literals without reading holes or length 1`] = `"function(){return[[\`0\`,\`2\`],[10,30],[[\`0\`,10],[\`2\`,30]],[],[],[]]}"`;
5+
exports[`ConfigCacheTestCases optimization minify-object-enumeration exported tests should enumerate array literals without reading holes or length 1`] = `"function enumerate(){return[Object.keys([10,,30]),Object.values([10,,30]),Object.entries([10,,30]),Object.keys([]),Object.values([,,]),Object.entries([])]}"`;
Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
11
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
22

3-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should keep repeated member reads before a later write 1`] = `"function read(object){var result=object.value+object.value+(object.value=5)+object.value;return object.value=9,result}"`;
3+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should keep repeated member reads before a later write 1`] = `"function read(object){var result=object.value+object.value+(object.value=5)+object.value;object.value=9;return result}"`;
44

5-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should keep repeated member reads before a later write 2`] = `"function e(e){var t=e.value+e.value+(e.value=5)+e.value;return e.value=9,t}"`;
5+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should keep repeated member reads before a later write 2`] = `"function e(e){var a=e.value+e.value+(e.value=5)+e.value;e.value=9;return a}"`;
66

7-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve assignments when joining bare declarations across blocks 1`] = `"function joined(flag,calls){flag&&(extra=calls.push(1)),calls.push(2);var extra,result=calls.push(3);return[calls.push(4),extra,result]}"`;
7+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve assignments when joining bare declarations across blocks 1`] = `"function joined(flag,calls){var value;if(flag){var extra;extra=calls.push(1)}value=calls.push(2);function inner(){var value;value=calls.push(3);return value}var result=inner();value=calls.push(4);return[value,extra,result]}"`;
88

9-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve assignments when joining bare declarations across blocks 2`] = `"function e(e,t){e&&(a=t.push(1)),t.push(2);var a,o=t.push(3);return[t.push(4),a,o]}"`;
9+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve assignments when joining bare declarations across blocks 2`] = `"function e(e,a){var t;if(e){var r;r=a.push(1)}t=a.push(2);var o=function(){var e;return e=a.push(3)}();return[t=a.push(4),r,o]}"`;
1010

11-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve captured values beside nested functions with their own variables 1`] = `"function capture(make){var source=make();return[function(){var copy=source;return copy.value+copy.value},function(){for(var source=make(),index=0;index<source.value;index++)var copy=index;return copy},()=>make().value]}"`;
11+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve captured values beside nested functions with their own variables 1`] = `"function capture(make){function nested(){var source=make();for(var index=0;index<source.value;index++)var copy=index;return copy}const arrow=()=>{var source=make();return source.value};var source=make();function read(){var copy=source;return copy.value+copy.value}return[read,nested,arrow]}"`;
1212

13-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve captured values beside nested functions with their own variables 2`] = `"function e(e){var t=e();return[function(){return t.value+t.value},function(){for(var t=e(),a=0;a<t.value;a++)var o=a;return o},()=>e().value]}"`;
13+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve captured values beside nested functions with their own variables 2`] = `"function e(e){var a=e();return[function(){var e=a;return e.value+e.value},function(){var a=e();for(var t=0;t<a.value;t++)var r=t;return r},()=>e().value]}"`;
1414

15-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve copies of variables initialized inside a loop 1`] = `"function capture(values){let readers=[];for(var index=0;index<values.length;index++){var source=values[index];(function(){var copy=source;readers.push(()=>copy.value+copy.value)})()}return readers}"`;
15+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve copies of variables initialized inside a loop 1`] = `"function capture(values){const readers=[];for(var index=0;index<values.length;index++){var source=values[index];(function(){var copy=source;readers.push(()=>copy.value+copy.value)})()}return readers}"`;
1616

17-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve copies of variables initialized inside a loop 2`] = `"function e(e){let t=[];for(var a=0;a<e.length;a++){var o=e[a];(function(){var e=o;t.push(()=>e.value+e.value)})()}return t}"`;
17+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve copies of variables initialized inside a loop 2`] = `"function e(e){let a=[];for(var t=0;t<e.length;t++){var r=e[t];(function(){var e=r;a.push(()=>e.value+e.value)})()}return a}"`;
1818

1919
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve copies when a generator resumes inside a loop 1`] = `"function*capture(values){for(var source of values)yield function(){var copy=source;return()=>copy.value+copy.value}()}"`;
2020

21-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve copies when a generator resumes inside a loop 2`] = `"function*e(e){for(var t of e)yield function(){var e=t;return()=>e.value+e.value}()}"`;
21+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve copies when a generator resumes inside a loop 2`] = `"function*e(e){for(var a of e)yield function(){var e=a;return()=>e.value+e.value}()}"`;
2222

23-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve getters and shadowed parameters during assignment folding 1`] = `"function read(object,other){var result=object.value+function(object){var value=object.value+object.value;return object.value=7,value+object.value}(other)+object.value;return result}"`;
23+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve getters and shadowed parameters during assignment folding 1`] = `"function read(object,other){var result=object.value+function(object){var value=object.value+object.value;object.value=7;return value+object.value}(other)+object.value;return result}"`;
2424

25-
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve getters and shadowed parameters during assignment folding 2`] = `"function e(e,t){var a=e.value+function(e){var t=e.value+e.value;return e.value=7,t+e.value}(t)+e.value;return a}"`;
25+
exports[`ConfigCacheTestCases optimization minify-traversal-work exported tests should preserve getters and shadowed parameters during assignment folding 2`] = `"function e(e,a){return e.value+function(e){var a=e.value+e.value;e.value=7;return a+e.value}(a)+e.value}"`;

‎test/unitCases/javascript/printer.unittest.js‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15725,6 +15725,29 @@ describe("JavaScript minifier printing a SyntaxTree", () => {
1572515725
);
1572615726
});
1572715727

15728+
it("should keep a call whose class reads the function's `new.target` where it is defined", () => {
15729+
const print = (/** @type {string} */ source) =>
15730+
minifyOnePass(source, { compress: {}, mangle: {}, module: true }).code;
15731+
expect(
15732+
print(
15733+
"it(function () { g((function () { return class { [new.target]() {} }; })()); });"
15734+
)
15735+
).toBe("it(function(){g(function(){return class{[new.target](){}}}())});");
15736+
expect(
15737+
print(
15738+
"it(function () { g((function () { return class extends (new.target || Object) {}; })()); });"
15739+
)
15740+
).toBe(
15741+
"it(function(){g(function(){return class extends(new.target||Object){}}())});"
15742+
);
15743+
// A method's `this` is its own: the class is the call's value.
15744+
expect(
15745+
print(
15746+
"it(function () { g((function () { return class { m() { return this.x } }; })()); });"
15747+
)
15748+
).toBe("it(function(){g(class{m(){return this.x}})});");
15749+
});
15750+
1572815751
it("should keep a `let` read before its declaration, from any function", () => {
1572915752
const print = (/** @type {string} */ source) =>
1573015753
minifyOnePass(source, { compress: {}, mangle: {} }).code;
@@ -17023,6 +17046,19 @@ describe("jsMinify", () => {
1702317046
await expect(jsMinify({ "broken.js": "function (" })).rejects.toThrow();
1702417047
});
1702517048

17049+
it("should minify through terser's tree what the one pass does not read", async () => {
17050+
const nameCache = {};
17051+
const result = await jsMinify(
17052+
{ "cached.js": "var longName = 1; sink(longName);" },
17053+
INPUT_MAP,
17054+
{ toplevel: true, nameCache },
17055+
false
17056+
);
17057+
expect(result.code).toBe("sink(1);");
17058+
expect(typeof result.map).toBe("object");
17059+
expect(nameCache).toEqual({ vars: { props: {} } });
17060+
});
17061+
1702617062
it("should read a Buffer input as UTF-8", async () => {
1702717063
const { code } = await jsMinify({
1702817064
"a.js": Buffer.from('console.log( "é" );', "utf8")

‎types.d.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37929,6 +37929,7 @@ declare namespace exports {
3792937929
}
3793037930
export namespace printer {
3793137931
export let NODE_KIND_ANCESTRY: Record<string, string[]>;
37932+
export let ONE_PASS_UNSUPPORTED: "WEBPACK_ONE_PASS_UNSUPPORTED";
3793237933
export let prepareMinify: (
3793337934
text: string,
3793437935
options: JavascriptProcessOptions

0 commit comments

Comments
 (0)