Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit cd77ad1

Browse files
minify helpers-generated.ts (#13837)
Co-authored-by: Nicolò Ribaudo <[email protected]>
1 parent d30308f commit cd77ad1

File tree

17 files changed

+101
-132
lines changed

17 files changed

+101
-132
lines changed

packages/babel-helpers/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020
"@babel/types": "workspace:^"
2121
},
2222
"devDependencies": {
23-
"@babel/helper-plugin-test-runner": "workspace:^"
23+
"@babel/helper-plugin-test-runner": "workspace:^",
24+
"terser": "^5.9.0"
2425
},
2526
"engines": {
2627
"node": ">=6.9.0"
Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,34 @@
11
import fs from "fs";
22
import { join } from "path";
33
import { URL, fileURLToPath } from "url";
4+
import { minify } from "terser"; // eslint-disable-line
45

56
const HELPERS_FOLDER = new URL("../src/helpers", import.meta.url);
67
const IGNORED_FILES = new Set(["package.json"]);
78

89
export default async function generateHelpers() {
910
let output = `/*
1011
* This file is auto-generated! Do not modify it directly.
11-
* To re-generate run 'make build'
12+
* To re-generate run 'yarn gulp generate-runtime-helpers'
1213
*/
1314
1415
import template from "@babel/template";
1516
17+
function helper(minVersion, source) {
18+
return Object.freeze({
19+
minVersion,
20+
ast: () => template.program.ast(source),
21+
})
22+
}
23+
24+
export default Object.freeze({
1625
`;
1726

1827
for (const file of (await fs.promises.readdir(HELPERS_FOLDER)).sort()) {
1928
if (IGNORED_FILES.has(file)) continue;
2029
if (file.startsWith(".")) continue; // ignore e.g. vim swap files
2130

2231
const [helperName] = file.split(".");
23-
const isValidId = isValidBindingIdentifier(helperName);
24-
const varName = isValidId ? helperName : `_${helperName}`;
2532

2633
const filePath = join(fileURLToPath(HELPERS_FOLDER), file);
2734
if (!file.endsWith(".js")) {
@@ -38,31 +45,20 @@ import template from "@babel/template";
3845
}
3946
const { minVersion } = minVersionMatch.groups;
4047

41-
// TODO: We can minify the helpers in production
42-
const source = fileContents
43-
// Remove comments
44-
.replace(/\/\*[^]*?\*\/|\/\/.*/g, "")
45-
// Remove multiple newlines
46-
.replace(/\n{2,}/g, "\n");
48+
const source = await minify(fileContents, {
49+
mangle: false,
50+
// The _typeof helper has a custom directive that we must keep
51+
compress: { directives: false },
52+
});
4753

48-
const intro = isValidId
49-
? "export "
50-
: `export { ${varName} as ${helperName} }\n`;
51-
52-
output += `\n${intro}const ${varName} = {
53-
minVersion: ${JSON.stringify(minVersion)},
54-
ast: () => template.program.ast(${JSON.stringify(source)})
55-
};\n`;
54+
output += `\
55+
${JSON.stringify(helperName)}: helper(
56+
${JSON.stringify(minVersion)},
57+
${JSON.stringify(source.code)},
58+
),
59+
`;
5660
}
5761

62+
output += "});";
5863
return output;
5964
}
60-
61-
function isValidBindingIdentifier(name) {
62-
try {
63-
Function(`var ${name}`);
64-
return true;
65-
} catch {
66-
return false;
67-
}
68-
}
Lines changed: 29 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,36 @@
11
/*
22
* This file is auto-generated! Do not modify it directly.
3-
* To re-generate run 'make build'
3+
* To re-generate run 'yarn gulp generate-runtime-helpers'
44
*/
55

66
import template from "@babel/template";
77

8-
export const asyncIterator = {
9-
minVersion: "7.15.9",
10-
ast: () =>
11-
template.program.ast(
12-
'\nexport default function _asyncIterator(iterable) {\n var method,\n async,\n sync,\n retry = 2;\n if (typeof Symbol !== "undefined") {\n async = Symbol.asyncIterator;\n sync = Symbol.iterator;\n }\n while (retry--) {\n if (async && (method = iterable[async]) != null) {\n return method.call(iterable);\n }\n if (sync && (method = iterable[sync]) != null) {\n return new AsyncFromSyncIterator(method.call(iterable));\n }\n async = "@@asyncIterator";\n sync = "@@iterator";\n }\n throw new TypeError("Object is not async iterable");\n}\nfunction AsyncFromSyncIterator(s) {\n AsyncFromSyncIterator = function (s) {\n this.s = s;\n this.n = s.next;\n };\n AsyncFromSyncIterator.prototype = {\n s: null,\n n: null,\n next: function () {\n return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));\n },\n return: function (value) {\n var ret = this.s.return;\n if (ret === undefined) {\n return Promise.resolve({ value: value, done: true });\n }\n return AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments));\n },\n throw: function (value) {\n var thr = this.s.return;\n if (thr === undefined) return Promise.reject(value);\n return AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments));\n },\n };\n function AsyncFromSyncIteratorContinuation(r) {\n \n if (Object(r) !== r) {\n return Promise.reject(new TypeError(r + " is not an object."));\n }\n var done = r.done;\n return Promise.resolve(r.value).then(function (value) {\n return { value: value, done: done };\n });\n }\n return new AsyncFromSyncIterator(s);\n}\n',
13-
),
14-
};
8+
function helper(minVersion, source) {
9+
return Object.freeze({
10+
minVersion,
11+
ast: () => template.program.ast(source),
12+
});
13+
}
1514

16-
export const jsx = {
17-
minVersion: "7.0.0-beta.0",
18-
ast: () =>
19-
template.program.ast(
20-
'\nvar REACT_ELEMENT_TYPE;\nexport default function _createRawReactElement(type, props, key, children) {\n if (!REACT_ELEMENT_TYPE) {\n REACT_ELEMENT_TYPE =\n (typeof Symbol === "function" &&\n \n Symbol["for"] &&\n Symbol["for"]("react.element")) ||\n 0xeac7;\n }\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n if (!props && childrenLength !== 0) {\n \n \n props = { children: void 0 };\n }\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = new Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n props.children = childArray;\n }\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : "" + key,\n ref: null,\n props: props,\n _owner: null,\n };\n}\n',
21-
),
22-
};
23-
24-
export const objectSpread2 = {
25-
minVersion: "7.5.0",
26-
ast: () =>
27-
template.program.ast(
28-
'\nimport defineProperty from "defineProperty";\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) {\n symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n }\n keys.push.apply(keys, symbols);\n }\n return keys;\n}\nexport default function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(\n target,\n key,\n Object.getOwnPropertyDescriptor(source, key)\n );\n });\n }\n }\n return target;\n}\n',
29-
),
30-
};
31-
32-
export { _typeof as typeof };
33-
const _typeof = {
34-
minVersion: "7.0.0-beta.0",
35-
ast: () =>
36-
template.program.ast(
37-
'\nexport default function _typeof(obj) {\n "@babel/helpers - typeof";\n if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj &&\n typeof Symbol === "function" &&\n obj.constructor === Symbol &&\n obj !== Symbol.prototype\n ? "symbol"\n : typeof obj;\n };\n }\n return _typeof(obj);\n}\n',
38-
),
39-
};
40-
41-
export const wrapRegExp = {
42-
minVersion: "7.2.6",
43-
ast: () =>
44-
template.program.ast(
45-
'\nimport setPrototypeOf from "setPrototypeOf";\nimport inherits from "inherits";\nexport default function _wrapRegExp() {\n _wrapRegExp = function (re, groups) {\n return new BabelRegExp(re, undefined, groups);\n };\n var _super = RegExp.prototype;\n var _groups = new WeakMap();\n function BabelRegExp(re, flags, groups) {\n var _this = new RegExp(re, flags);\n \n _groups.set(_this, groups || _groups.get(re));\n return setPrototypeOf(_this, BabelRegExp.prototype);\n }\n inherits(BabelRegExp, RegExp);\n BabelRegExp.prototype.exec = function (str) {\n var result = _super.exec.call(this, str);\n if (result) result.groups = buildGroups(result, this);\n return result;\n };\n BabelRegExp.prototype[Symbol.replace] = function (str, substitution) {\n if (typeof substitution === "string") {\n var groups = _groups.get(this);\n return _super[Symbol.replace].call(\n this,\n str,\n substitution.replace(/\\$<([^>]+)>/g, function (_, name) {\n return "$" + groups[name];\n })\n );\n } else if (typeof substitution === "function") {\n var _this = this;\n return _super[Symbol.replace].call(this, str, function () {\n var args = arguments;\n \n if (typeof args[args.length - 1] !== "object") {\n args = [].slice.call(args);\n args.push(buildGroups(args, _this));\n }\n return substitution.apply(this, args);\n });\n } else {\n return _super[Symbol.replace].call(this, str, substitution);\n }\n };\n function buildGroups(result, re) {\n \n \n var g = _groups.get(re);\n return Object.keys(g).reduce(function (groups, name) {\n groups[name] = result[g[name]];\n return groups;\n }, Object.create(null));\n }\n return _wrapRegExp.apply(this, arguments);\n}\n',
46-
),
47-
};
15+
export default Object.freeze({
16+
asyncIterator: helper(
17+
"7.15.9",
18+
'export default function _asyncIterator(iterable){var method,async,sync,retry=2;for("undefined"!=typeof Symbol&&(async=Symbol.asyncIterator,sync=Symbol.iterator);retry--;){if(async&&null!=(method=iterable[async]))return method.call(iterable);if(sync&&null!=(method=iterable[sync]))return new AsyncFromSyncIterator(method.call(iterable));async="@@asyncIterator",sync="@@iterator"}throw new TypeError("Object is not async iterable")}function AsyncFromSyncIterator(s){function AsyncFromSyncIteratorContinuation(r){if(Object(r)!==r)return Promise.reject(new TypeError(r+" is not an object."));var done=r.done;return Promise.resolve(r.value).then((function(value){return{value:value,done:done}}))}return AsyncFromSyncIterator=function(s){this.s=s,this.n=s.next},AsyncFromSyncIterator.prototype={s:null,n:null,next:function(){return AsyncFromSyncIteratorContinuation(this.n.apply(this.s,arguments))},return:function(value){var ret=this.s.return;return void 0===ret?Promise.resolve({value:value,done:!0}):AsyncFromSyncIteratorContinuation(ret.apply(this.s,arguments))},throw:function(value){var thr=this.s.return;return void 0===thr?Promise.reject(value):AsyncFromSyncIteratorContinuation(thr.apply(this.s,arguments))}},new AsyncFromSyncIterator(s)}',
19+
),
20+
jsx: helper(
21+
"7.0.0-beta.0",
22+
'var REACT_ELEMENT_TYPE;export default function _createRawReactElement(type,props,key,children){REACT_ELEMENT_TYPE||(REACT_ELEMENT_TYPE="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103);var defaultProps=type&&type.defaultProps,childrenLength=arguments.length-3;if(props||0===childrenLength||(props={children:void 0}),1===childrenLength)props.children=children;else if(childrenLength>1){for(var childArray=new Array(childrenLength),i=0;i<childrenLength;i++)childArray[i]=arguments[i+3];props.children=childArray}if(props&&defaultProps)for(var propName in defaultProps)void 0===props[propName]&&(props[propName]=defaultProps[propName]);else props||(props=defaultProps||{});return{$$typeof:REACT_ELEMENT_TYPE,type:type,key:void 0===key?null:""+key,ref:null,props:props,_owner:null}}',
23+
),
24+
objectSpread2: helper(
25+
"7.5.0",
26+
'import defineProperty from"defineProperty";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}export default function _objectSpread2(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys(Object(source),!0).forEach((function(key){defineProperty(target,key,source[key])})):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach((function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))}))}return target}',
27+
),
28+
typeof: helper(
29+
"7.0.0-beta.0",
30+
'export default function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}',
31+
),
32+
wrapRegExp: helper(
33+
"7.2.6",
34+
'import setPrototypeOf from"setPrototypeOf";import inherits from"inherits";export default function _wrapRegExp(){_wrapRegExp=function(re,groups){return new BabelRegExp(re,void 0,groups)};var _super=RegExp.prototype,_groups=new WeakMap;function BabelRegExp(re,flags,groups){var _this=new RegExp(re,flags);return _groups.set(_this,groups||_groups.get(re)),setPrototypeOf(_this,BabelRegExp.prototype)}function buildGroups(result,re){var g=_groups.get(re);return Object.keys(g).reduce((function(groups,name){return groups[name]=result[g[name]],groups}),Object.create(null))}return inherits(BabelRegExp,RegExp),BabelRegExp.prototype.exec=function(str){var result=_super.exec.call(this,str);return result&&(result.groups=buildGroups(result,this)),result},BabelRegExp.prototype[Symbol.replace]=function(str,substitution){if("string"==typeof substitution){var groups=_groups.get(this);return _super[Symbol.replace].call(this,str,substitution.replace(/\\$<([^>]+)>/g,(function(_,name){return"$"+groups[name]})))}if("function"==typeof substitution){var _this=this;return _super[Symbol.replace].call(this,str,(function(){var args=arguments;return"object"!=typeof args[args.length-1]&&(args=[].slice.call(args)).push(buildGroups(args,_this)),substitution.apply(this,args)}))}return _super[Symbol.replace].call(this,str,substitution)},_wrapRegExp.apply(this,arguments)}',
35+
),
36+
});

packages/babel-helpers/src/helpers.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import template from "@babel/template";
22
import type * as t from "@babel/types";
33

4-
import * as generated from "./helpers-generated";
4+
import generated from "./helpers-generated";
55

66
interface Helper {
77
minVersion: string;

packages/babel-plugin-proposal-async-generator-functions/test/fixtures/regression/13801/output.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
function _asyncIterator(iterable) { var method, async, sync, retry = 2; if (typeof Symbol !== "undefined") { async = Symbol.asyncIterator; sync = Symbol.iterator; } while (retry--) { if (async && (method = iterable[async]) != null) { return method.call(iterable); } if (sync && (method = iterable[sync]) != null) { return new AsyncFromSyncIterator(method.call(iterable)); } async = "@@asyncIterator"; sync = "@@iterator"; } throw new TypeError("Object is not async iterable"); }
1+
function _asyncIterator(iterable) { var method, async, sync, retry = 2; for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { if (async && null != (method = iterable[async])) return method.call(iterable); if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable)); async = "@@asyncIterator", sync = "@@iterator"; } throw new TypeError("Object is not async iterable"); }
22

3-
function AsyncFromSyncIterator(s) { AsyncFromSyncIterator = function (s) { this.s = s; this.n = s.next; }; AsyncFromSyncIterator.prototype = { s: null, n: null, next: function () { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, return: function (value) { var ret = this.s.return; if (ret === undefined) { return Promise.resolve({ value: value, done: true }); } return AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); }, throw: function (value) { var thr = this.s.return; if (thr === undefined) return Promise.reject(value); return AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); } }; function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) { return Promise.reject(new TypeError(r + " is not an object.")); } var done = r.done; return Promise.resolve(r.value).then(function (value) { return { value: value, done: done }; }); } return new AsyncFromSyncIterator(s); }
3+
function AsyncFromSyncIterator(s) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var done = r.done; return Promise.resolve(r.value).then(function (value) { return { value: value, done: done }; }); } return AsyncFromSyncIterator = function (s) { this.s = s, this.n = s.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function () { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, return: function (value) { var ret = this.s.return; return void 0 === ret ? Promise.resolve({ value: value, done: !0 }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); }, throw: function (value) { var thr = this.s.return; return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(s); }
44

55
function main() {
66
var one;

packages/babel-plugin-transform-runtime/scripts/build-dist.js

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -302,14 +302,24 @@ function buildRuntimeRewritePlugin(runtimeName, helperName) {
302302
}
303303

304304
function addDefaultCJSExport({ template }) {
305+
const transformed = new WeakSet();
306+
305307
return {
306308
visitor: {
307309
AssignmentExpression: {
308310
exit(path) {
309311
if (path.get("left").matchesPattern("module.exports")) {
310-
path.insertAfter(template.expression.ast`
311-
module.exports.default = module.exports,
312-
module.exports.__esModule = true
312+
if (transformed.has(path.node)) return;
313+
transformed.add(path.node);
314+
315+
// Ensure that the completion value is still `module.exports`.
316+
// This would be guaranteed by `insertAfter`, but by using `replaceWith`
317+
// we can do it by putting `module.exports` last so that we don't need
318+
// to inject temporary variables.
319+
path.replaceWith(template.expression.ast`
320+
${path.node},
321+
module.exports.__esModule = true,
322+
module.exports.default = module.exports
313323
`);
314324
}
315325
},

0 commit comments

Comments
 (0)