index.mjs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import corejs2Polyfills from '@babel/compat-data/corejs2-built-ins';
  2. import semver from 'semver';
  3. import defineProvider from '@babel/helper-define-polyfill-provider';
  4. import * as babel from '@babel/core';
  5. const define = (name, pure, global = [], meta) => {
  6. return {
  7. name,
  8. pure,
  9. global,
  10. meta
  11. };
  12. };
  13. const pureAndGlobal = (pure, global, minRuntimeVersion = null) => define(global[0], pure, global, {
  14. minRuntimeVersion
  15. });
  16. const globalOnly = global => define(global[0], null, global);
  17. const pureOnly = (pure, name) => define(name, pure, []);
  18. const ArrayNatureIterators = ["es6.object.to-string", "es6.array.iterator", "web.dom.iterable"];
  19. const CommonIterators = ["es6.string.iterator", ...ArrayNatureIterators];
  20. const PromiseDependencies = ["es6.object.to-string", "es6.promise"];
  21. const BuiltIns = {
  22. DataView: globalOnly(["es6.typed.data-view"]),
  23. Float32Array: globalOnly(["es6.typed.float32-array"]),
  24. Float64Array: globalOnly(["es6.typed.float64-array"]),
  25. Int8Array: globalOnly(["es6.typed.int8-array"]),
  26. Int16Array: globalOnly(["es6.typed.int16-array"]),
  27. Int32Array: globalOnly(["es6.typed.int32-array"]),
  28. Map: pureAndGlobal("map", ["es6.map", ...CommonIterators]),
  29. Number: globalOnly(["es6.number.constructor"]),
  30. Promise: pureAndGlobal("promise", PromiseDependencies),
  31. RegExp: globalOnly(["es6.regexp.constructor"]),
  32. Set: pureAndGlobal("set", ["es6.set", ...CommonIterators]),
  33. Symbol: pureAndGlobal("symbol", ["es6.symbol"]),
  34. Uint8Array: globalOnly(["es6.typed.uint8-array"]),
  35. Uint8ClampedArray: globalOnly(["es6.typed.uint8-clamped-array"]),
  36. Uint16Array: globalOnly(["es6.typed.uint16-array"]),
  37. Uint32Array: globalOnly(["es6.typed.uint32-array"]),
  38. WeakMap: pureAndGlobal("weak-map", ["es6.weak-map", ...CommonIterators]),
  39. WeakSet: pureAndGlobal("weak-set", ["es6.weak-set", ...CommonIterators]),
  40. setImmediate: pureOnly("set-immediate", "web.immediate"),
  41. clearImmediate: pureOnly("clear-immediate", "web.immediate"),
  42. parseFloat: pureOnly("parse-float", "es6.parse-float"),
  43. parseInt: pureOnly("parse-int", "es6.parse-int")
  44. };
  45. const InstanceProperties = {
  46. __defineGetter__: globalOnly(["es7.object.define-getter"]),
  47. __defineSetter__: globalOnly(["es7.object.define-setter"]),
  48. __lookupGetter__: globalOnly(["es7.object.lookup-getter"]),
  49. __lookupSetter__: globalOnly(["es7.object.lookup-setter"]),
  50. anchor: globalOnly(["es6.string.anchor"]),
  51. big: globalOnly(["es6.string.big"]),
  52. bind: globalOnly(["es6.function.bind"]),
  53. blink: globalOnly(["es6.string.blink"]),
  54. bold: globalOnly(["es6.string.bold"]),
  55. codePointAt: globalOnly(["es6.string.code-point-at"]),
  56. copyWithin: globalOnly(["es6.array.copy-within"]),
  57. endsWith: globalOnly(["es6.string.ends-with"]),
  58. entries: globalOnly(ArrayNatureIterators),
  59. every: globalOnly(["es6.array.every"]),
  60. fill: globalOnly(["es6.array.fill"]),
  61. filter: globalOnly(["es6.array.filter"]),
  62. finally: globalOnly(["es7.promise.finally", ...PromiseDependencies]),
  63. find: globalOnly(["es6.array.find"]),
  64. findIndex: globalOnly(["es6.array.find-index"]),
  65. fixed: globalOnly(["es6.string.fixed"]),
  66. flags: globalOnly(["es6.regexp.flags"]),
  67. flatMap: globalOnly(["es7.array.flat-map"]),
  68. fontcolor: globalOnly(["es6.string.fontcolor"]),
  69. fontsize: globalOnly(["es6.string.fontsize"]),
  70. forEach: globalOnly(["es6.array.for-each"]),
  71. includes: globalOnly(["es6.string.includes", "es7.array.includes"]),
  72. indexOf: globalOnly(["es6.array.index-of"]),
  73. italics: globalOnly(["es6.string.italics"]),
  74. keys: globalOnly(ArrayNatureIterators),
  75. lastIndexOf: globalOnly(["es6.array.last-index-of"]),
  76. link: globalOnly(["es6.string.link"]),
  77. map: globalOnly(["es6.array.map"]),
  78. match: globalOnly(["es6.regexp.match"]),
  79. name: globalOnly(["es6.function.name"]),
  80. padStart: globalOnly(["es7.string.pad-start"]),
  81. padEnd: globalOnly(["es7.string.pad-end"]),
  82. reduce: globalOnly(["es6.array.reduce"]),
  83. reduceRight: globalOnly(["es6.array.reduce-right"]),
  84. repeat: globalOnly(["es6.string.repeat"]),
  85. replace: globalOnly(["es6.regexp.replace"]),
  86. search: globalOnly(["es6.regexp.search"]),
  87. small: globalOnly(["es6.string.small"]),
  88. some: globalOnly(["es6.array.some"]),
  89. sort: globalOnly(["es6.array.sort"]),
  90. split: globalOnly(["es6.regexp.split"]),
  91. startsWith: globalOnly(["es6.string.starts-with"]),
  92. strike: globalOnly(["es6.string.strike"]),
  93. sub: globalOnly(["es6.string.sub"]),
  94. sup: globalOnly(["es6.string.sup"]),
  95. toISOString: globalOnly(["es6.date.to-iso-string"]),
  96. toJSON: globalOnly(["es6.date.to-json"]),
  97. toString: globalOnly(["es6.object.to-string", "es6.date.to-string", "es6.regexp.to-string"]),
  98. trim: globalOnly(["es6.string.trim"]),
  99. trimEnd: globalOnly(["es7.string.trim-right"]),
  100. trimLeft: globalOnly(["es7.string.trim-left"]),
  101. trimRight: globalOnly(["es7.string.trim-right"]),
  102. trimStart: globalOnly(["es7.string.trim-left"]),
  103. values: globalOnly(ArrayNatureIterators)
  104. }; // This isn't present in older @babel/compat-data versions
  105. if ("es6.array.slice" in corejs2Polyfills) {
  106. InstanceProperties.slice = globalOnly(["es6.array.slice"]);
  107. }
  108. const StaticProperties = {
  109. Array: {
  110. from: pureAndGlobal("array/from", ["es6.symbol", "es6.array.from", ...CommonIterators]),
  111. isArray: pureAndGlobal("array/is-array", ["es6.array.is-array"]),
  112. of: pureAndGlobal("array/of", ["es6.array.of"])
  113. },
  114. Date: {
  115. now: pureAndGlobal("date/now", ["es6.date.now"])
  116. },
  117. JSON: {
  118. stringify: pureOnly("json/stringify", "es6.symbol")
  119. },
  120. Math: {
  121. // 'Math' was not included in the 7.0.0
  122. // release of '@babel/runtime'. See issue https://github.com/babel/babel/pull/8616.
  123. acosh: pureAndGlobal("math/acosh", ["es6.math.acosh"], "7.0.1"),
  124. asinh: pureAndGlobal("math/asinh", ["es6.math.asinh"], "7.0.1"),
  125. atanh: pureAndGlobal("math/atanh", ["es6.math.atanh"], "7.0.1"),
  126. cbrt: pureAndGlobal("math/cbrt", ["es6.math.cbrt"], "7.0.1"),
  127. clz32: pureAndGlobal("math/clz32", ["es6.math.clz32"], "7.0.1"),
  128. cosh: pureAndGlobal("math/cosh", ["es6.math.cosh"], "7.0.1"),
  129. expm1: pureAndGlobal("math/expm1", ["es6.math.expm1"], "7.0.1"),
  130. fround: pureAndGlobal("math/fround", ["es6.math.fround"], "7.0.1"),
  131. hypot: pureAndGlobal("math/hypot", ["es6.math.hypot"], "7.0.1"),
  132. imul: pureAndGlobal("math/imul", ["es6.math.imul"], "7.0.1"),
  133. log1p: pureAndGlobal("math/log1p", ["es6.math.log1p"], "7.0.1"),
  134. log10: pureAndGlobal("math/log10", ["es6.math.log10"], "7.0.1"),
  135. log2: pureAndGlobal("math/log2", ["es6.math.log2"], "7.0.1"),
  136. sign: pureAndGlobal("math/sign", ["es6.math.sign"], "7.0.1"),
  137. sinh: pureAndGlobal("math/sinh", ["es6.math.sinh"], "7.0.1"),
  138. tanh: pureAndGlobal("math/tanh", ["es6.math.tanh"], "7.0.1"),
  139. trunc: pureAndGlobal("math/trunc", ["es6.math.trunc"], "7.0.1")
  140. },
  141. Number: {
  142. EPSILON: pureAndGlobal("number/epsilon", ["es6.number.epsilon"]),
  143. MIN_SAFE_INTEGER: pureAndGlobal("number/min-safe-integer", ["es6.number.min-safe-integer"]),
  144. MAX_SAFE_INTEGER: pureAndGlobal("number/max-safe-integer", ["es6.number.max-safe-integer"]),
  145. isFinite: pureAndGlobal("number/is-finite", ["es6.number.is-finite"]),
  146. isInteger: pureAndGlobal("number/is-integer", ["es6.number.is-integer"]),
  147. isSafeInteger: pureAndGlobal("number/is-safe-integer", ["es6.number.is-safe-integer"]),
  148. isNaN: pureAndGlobal("number/is-nan", ["es6.number.is-nan"]),
  149. parseFloat: pureAndGlobal("number/parse-float", ["es6.number.parse-float"]),
  150. parseInt: pureAndGlobal("number/parse-int", ["es6.number.parse-int"])
  151. },
  152. Object: {
  153. assign: pureAndGlobal("object/assign", ["es6.object.assign"]),
  154. create: pureAndGlobal("object/create", ["es6.object.create"]),
  155. defineProperties: pureAndGlobal("object/define-properties", ["es6.object.define-properties"]),
  156. defineProperty: pureAndGlobal("object/define-property", ["es6.object.define-property"]),
  157. entries: pureAndGlobal("object/entries", ["es7.object.entries"]),
  158. freeze: pureAndGlobal("object/freeze", ["es6.object.freeze"]),
  159. getOwnPropertyDescriptor: pureAndGlobal("object/get-own-property-descriptor", ["es6.object.get-own-property-descriptor"]),
  160. getOwnPropertyDescriptors: pureAndGlobal("object/get-own-property-descriptors", ["es7.object.get-own-property-descriptors"]),
  161. getOwnPropertyNames: pureAndGlobal("object/get-own-property-names", ["es6.object.get-own-property-names"]),
  162. getOwnPropertySymbols: pureAndGlobal("object/get-own-property-symbols", ["es6.symbol"]),
  163. getPrototypeOf: pureAndGlobal("object/get-prototype-of", ["es6.object.get-prototype-of"]),
  164. is: pureAndGlobal("object/is", ["es6.object.is"]),
  165. isExtensible: pureAndGlobal("object/is-extensible", ["es6.object.is-extensible"]),
  166. isFrozen: pureAndGlobal("object/is-frozen", ["es6.object.is-frozen"]),
  167. isSealed: pureAndGlobal("object/is-sealed", ["es6.object.is-sealed"]),
  168. keys: pureAndGlobal("object/keys", ["es6.object.keys"]),
  169. preventExtensions: pureAndGlobal("object/prevent-extensions", ["es6.object.prevent-extensions"]),
  170. seal: pureAndGlobal("object/seal", ["es6.object.seal"]),
  171. setPrototypeOf: pureAndGlobal("object/set-prototype-of", ["es6.object.set-prototype-of"]),
  172. values: pureAndGlobal("object/values", ["es7.object.values"])
  173. },
  174. Promise: {
  175. all: globalOnly(CommonIterators),
  176. race: globalOnly(CommonIterators)
  177. },
  178. Reflect: {
  179. apply: pureAndGlobal("reflect/apply", ["es6.reflect.apply"]),
  180. construct: pureAndGlobal("reflect/construct", ["es6.reflect.construct"]),
  181. defineProperty: pureAndGlobal("reflect/define-property", ["es6.reflect.define-property"]),
  182. deleteProperty: pureAndGlobal("reflect/delete-property", ["es6.reflect.delete-property"]),
  183. get: pureAndGlobal("reflect/get", ["es6.reflect.get"]),
  184. getOwnPropertyDescriptor: pureAndGlobal("reflect/get-own-property-descriptor", ["es6.reflect.get-own-property-descriptor"]),
  185. getPrototypeOf: pureAndGlobal("reflect/get-prototype-of", ["es6.reflect.get-prototype-of"]),
  186. has: pureAndGlobal("reflect/has", ["es6.reflect.has"]),
  187. isExtensible: pureAndGlobal("reflect/is-extensible", ["es6.reflect.is-extensible"]),
  188. ownKeys: pureAndGlobal("reflect/own-keys", ["es6.reflect.own-keys"]),
  189. preventExtensions: pureAndGlobal("reflect/prevent-extensions", ["es6.reflect.prevent-extensions"]),
  190. set: pureAndGlobal("reflect/set", ["es6.reflect.set"]),
  191. setPrototypeOf: pureAndGlobal("reflect/set-prototype-of", ["es6.reflect.set-prototype-of"])
  192. },
  193. String: {
  194. at: pureOnly("string/at", "es7.string.at"),
  195. fromCodePoint: pureAndGlobal("string/from-code-point", ["es6.string.from-code-point"]),
  196. raw: pureAndGlobal("string/raw", ["es6.string.raw"])
  197. },
  198. Symbol: {
  199. // FIXME: Pure disabled to work around zloirock/core-js#262.
  200. asyncIterator: globalOnly(["es6.symbol", "es7.symbol.async-iterator"]),
  201. for: pureOnly("symbol/for", "es6.symbol"),
  202. hasInstance: pureOnly("symbol/has-instance", "es6.symbol"),
  203. isConcatSpreadable: pureOnly("symbol/is-concat-spreadable", "es6.symbol"),
  204. iterator: define("es6.symbol", "symbol/iterator", CommonIterators),
  205. keyFor: pureOnly("symbol/key-for", "es6.symbol"),
  206. match: pureAndGlobal("symbol/match", ["es6.regexp.match"]),
  207. replace: pureOnly("symbol/replace", "es6.symbol"),
  208. search: pureOnly("symbol/search", "es6.symbol"),
  209. species: pureOnly("symbol/species", "es6.symbol"),
  210. split: pureOnly("symbol/split", "es6.symbol"),
  211. toPrimitive: pureOnly("symbol/to-primitive", "es6.symbol"),
  212. toStringTag: pureOnly("symbol/to-string-tag", "es6.symbol"),
  213. unscopables: pureOnly("symbol/unscopables", "es6.symbol")
  214. }
  215. };
  216. const webPolyfills = {
  217. "web.timers": {},
  218. "web.immediate": {},
  219. "web.dom.iterable": {}
  220. };
  221. const purePolyfills = {
  222. "es6.parse-float": {},
  223. "es6.parse-int": {},
  224. "es7.string.at": {}
  225. };
  226. function addPlatformSpecificPolyfills (targets, method, polyfills) {
  227. const targetNames = Object.keys(targets);
  228. const isAnyTarget = !targetNames.length;
  229. const isWebTarget = targetNames.some(name => name !== "node");
  230. return { ...polyfills,
  231. ...(method === "usage-pure" ? purePolyfills : null),
  232. ...(isAnyTarget || isWebTarget ? webPolyfills : null)
  233. };
  234. }
  235. function hasMinVersion(minVersion, runtimeVersion) {
  236. // If the range is unavailable, we're running the script during Babel's
  237. // build process, and we want to assume that all versions are satisfied so
  238. // that the built output will include all definitions.
  239. if (!runtimeVersion || !minVersion) return true; // semver.intersects() has some surprising behavior with comparing ranges
  240. // with preprelease versions. We add '^' to ensure that we are always
  241. // comparing ranges with ranges, which sidesteps this logic.
  242. // For example:
  243. //
  244. // semver.intersects(`<7.0.1`, "7.0.0-beta.0") // false - surprising
  245. // semver.intersects(`<7.0.1`, "^7.0.0-beta.0") // true - expected
  246. //
  247. // This is because the first falls back to
  248. //
  249. // semver.satisfies("7.0.0-beta.0", `<7.0.1`) // false - surprising
  250. //
  251. // and this fails because a prerelease version can only satisfy a range
  252. // if it is a prerelease within the same major/minor/patch range.
  253. //
  254. // Note: If this is found to have issues, please also revist the logic in
  255. // babel-core's availableHelper() API.
  256. if (semver.valid(runtimeVersion)) runtimeVersion = `^${runtimeVersion}`;
  257. return !semver.intersects(`<${minVersion}`, runtimeVersion) && !semver.intersects(`>=8.0.0`, runtimeVersion);
  258. }
  259. const {
  260. types: t
  261. } = babel.default || babel;
  262. const presetEnvCompat = "#__secret_key__@babel/preset-env__compatibility";
  263. const runtimeCompat = "#__secret_key__@babel/runtime__compatibility"; // $FlowIgnore
  264. const has = Function.call.bind(Object.hasOwnProperty);
  265. var index = defineProvider(function (api, {
  266. [presetEnvCompat]: {
  267. entryInjectRegenerator
  268. } = {},
  269. [runtimeCompat]: {
  270. useBabelRuntime,
  271. runtimeVersion,
  272. ext = ".js"
  273. } = {}
  274. }) {
  275. const resolve = api.createMetaResolver({
  276. global: BuiltIns,
  277. static: StaticProperties,
  278. instance: InstanceProperties
  279. });
  280. const {
  281. debug,
  282. shouldInjectPolyfill,
  283. method
  284. } = api;
  285. const polyfills = addPlatformSpecificPolyfills(api.targets, method, corejs2Polyfills);
  286. const coreJSBase = useBabelRuntime ? `${useBabelRuntime}/core-js` : method === "usage-pure" ? "core-js/library/fn" : "core-js/modules";
  287. function inject(name, utils) {
  288. if (typeof name === "string") {
  289. // Some polyfills aren't always available, for example
  290. // web.dom.iterable when targeting node
  291. if (has(polyfills, name) && shouldInjectPolyfill(name)) {
  292. debug(name);
  293. utils.injectGlobalImport(`${coreJSBase}/${name}.js`);
  294. }
  295. return;
  296. }
  297. name.forEach(name => inject(name, utils));
  298. }
  299. function maybeInjectPure(desc, hint, utils) {
  300. const {
  301. pure,
  302. meta,
  303. name
  304. } = desc;
  305. if (!pure || !shouldInjectPolyfill(name)) return;
  306. if (runtimeVersion && meta && meta.minRuntimeVersion && !hasMinVersion(meta && meta.minRuntimeVersion, runtimeVersion)) {
  307. return;
  308. }
  309. return utils.injectDefaultImport(`${coreJSBase}/${pure}${ext}`, hint);
  310. }
  311. return {
  312. name: "corejs2",
  313. polyfills,
  314. entryGlobal(meta, utils, path) {
  315. if (meta.kind === "import" && meta.source === "core-js") {
  316. debug(null);
  317. inject(Object.keys(polyfills), utils);
  318. if (entryInjectRegenerator) {
  319. utils.injectGlobalImport("regenerator-runtime/runtime.js");
  320. }
  321. path.remove();
  322. }
  323. },
  324. usageGlobal(meta, utils) {
  325. const resolved = resolve(meta);
  326. if (!resolved) return;
  327. let deps = resolved.desc.global;
  328. if (resolved.kind !== "global" && meta.object && meta.placement === "prototype") {
  329. const low = meta.object.toLowerCase();
  330. deps = deps.filter(m => m.includes(low));
  331. }
  332. inject(deps, utils);
  333. },
  334. usagePure(meta, utils, path) {
  335. if (meta.kind === "in") {
  336. if (meta.key === "Symbol.iterator") {
  337. path.replaceWith(t.callExpression(utils.injectDefaultImport(`${coreJSBase}/is-iterable${ext}`, "isIterable"), [path.node.right]));
  338. }
  339. return;
  340. }
  341. if (path.parentPath.isUnaryExpression({
  342. operator: "delete"
  343. })) return;
  344. if (meta.kind === "property") {
  345. // We can't compile destructuring.
  346. if (!path.isMemberExpression()) return;
  347. if (!path.isReferenced()) return;
  348. if (meta.key === "Symbol.iterator" && shouldInjectPolyfill("es6.symbol") && path.parentPath.isCallExpression({
  349. callee: path.node
  350. }) && path.parent.arguments.length === 0) {
  351. path.parentPath.replaceWith(t.callExpression(utils.injectDefaultImport(`${coreJSBase}/get-iterator${ext}`, "getIterator"), [path.node.object]));
  352. path.skip();
  353. return;
  354. }
  355. }
  356. const resolved = resolve(meta);
  357. if (!resolved) return;
  358. const id = maybeInjectPure(resolved.desc, resolved.name, utils);
  359. if (id) path.replaceWith(id);
  360. },
  361. visitor: method === "usage-global" && {
  362. // yield*
  363. YieldExpression(path) {
  364. if (path.node.delegate) {
  365. inject("web.dom.iterable", api.getUtils(path));
  366. }
  367. },
  368. // for-of, [a, b] = c
  369. "ForOfStatement|ArrayPattern"(path) {
  370. CommonIterators.forEach(name => inject(name, api.getUtils(path)));
  371. }
  372. }
  373. };
  374. });
  375. export default index;
  376. //# sourceMappingURL=index.mjs.map