index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. "use strict";
  2. exports.__esModule = true;
  3. exports.default = definePolyfillProvider;
  4. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  5. var _helperCompilationTargets = _interopRequireWildcard(require("@babel/helper-compilation-targets"));
  6. var _utils = require("./utils");
  7. var _importsInjector = _interopRequireDefault(require("./imports-injector"));
  8. var _debugUtils = require("./debug-utils");
  9. var _normalizeOptions = require("./normalize-options");
  10. var v = _interopRequireWildcard(require("./visitors"));
  11. var deps = _interopRequireWildcard(require("./node/dependencies"));
  12. var _metaResolver = _interopRequireDefault(require("./meta-resolver"));
  13. const _excluded = ["method", "targets", "ignoreBrowserslistConfig", "configPath", "debug", "shouldInjectPolyfill", "absoluteImports"];
  14. function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
  15. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
  16. function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
  17. const getTargets = _helperCompilationTargets.default.default || _helperCompilationTargets.default;
  18. function resolveOptions(options, babelApi) {
  19. const {
  20. method,
  21. targets: targetsOption,
  22. ignoreBrowserslistConfig,
  23. configPath,
  24. debug,
  25. shouldInjectPolyfill,
  26. absoluteImports
  27. } = options,
  28. providerOptions = _objectWithoutPropertiesLoose(options, _excluded);
  29. if (isEmpty(options)) {
  30. throw new Error(`\
  31. This plugin requires options, for example:
  32. {
  33. "plugins": [
  34. ["<plugin name>", { method: "usage-pure" }]
  35. ]
  36. }
  37. See more options at https://github.com/babel/babel-polyfills/blob/main/docs/usage.md`);
  38. }
  39. let methodName;
  40. if (method === "usage-global") methodName = "usageGlobal";else if (method === "entry-global") methodName = "entryGlobal";else if (method === "usage-pure") methodName = "usagePure";else if (typeof method !== "string") {
  41. throw new Error(".method must be a string");
  42. } else {
  43. throw new Error(`.method must be one of "entry-global", "usage-global"` + ` or "usage-pure" (received ${JSON.stringify(method)})`);
  44. }
  45. if (typeof shouldInjectPolyfill === "function") {
  46. if (options.include || options.exclude) {
  47. throw new Error(`.include and .exclude are not supported when using the` + ` .shouldInjectPolyfill function.`);
  48. }
  49. } else if (shouldInjectPolyfill != null) {
  50. throw new Error(`.shouldInjectPolyfill must be a function, or undefined` + ` (received ${JSON.stringify(shouldInjectPolyfill)})`);
  51. }
  52. if (absoluteImports != null && typeof absoluteImports !== "boolean" && typeof absoluteImports !== "string") {
  53. throw new Error(`.absoluteImports must be a boolean, a string, or undefined` + ` (received ${JSON.stringify(absoluteImports)})`);
  54. }
  55. let targets;
  56. if (
  57. // If any browserslist-related option is specified, fallback to the old
  58. // behavior of not using the targets specified in the top-level options.
  59. targetsOption || configPath || ignoreBrowserslistConfig) {
  60. const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
  61. browsers: targetsOption
  62. } : targetsOption;
  63. targets = getTargets(targetsObj, {
  64. ignoreBrowserslistConfig,
  65. configPath
  66. });
  67. } else {
  68. targets = babelApi.targets();
  69. }
  70. return {
  71. method,
  72. methodName,
  73. targets,
  74. absoluteImports: absoluteImports != null ? absoluteImports : false,
  75. shouldInjectPolyfill,
  76. debug: !!debug,
  77. providerOptions: providerOptions
  78. };
  79. }
  80. function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
  81. const {
  82. method,
  83. methodName,
  84. targets,
  85. debug,
  86. shouldInjectPolyfill,
  87. providerOptions,
  88. absoluteImports
  89. } = resolveOptions(options, babelApi);
  90. // eslint-disable-next-line prefer-const
  91. let include, exclude;
  92. let polyfillsSupport;
  93. let polyfillsNames;
  94. let filterPolyfills;
  95. const getUtils = (0, _utils.createUtilsGetter)(new _importsInjector.default(moduleName => deps.resolve(dirname, moduleName, absoluteImports), name => {
  96. var _polyfillsNames$get, _polyfillsNames;
  97. return (_polyfillsNames$get = (_polyfillsNames = polyfillsNames) == null ? void 0 : _polyfillsNames.get(name)) != null ? _polyfillsNames$get : Infinity;
  98. }));
  99. const depsCache = new Map();
  100. const api = {
  101. babel: babelApi,
  102. getUtils,
  103. method: options.method,
  104. targets,
  105. createMetaResolver: _metaResolver.default,
  106. shouldInjectPolyfill(name) {
  107. if (polyfillsNames === undefined) {
  108. throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
  109. }
  110. if (!polyfillsNames.has(name)) {
  111. console.warn(`Internal error in the ${providerName} provider: ` + `unknown polyfill "${name}".`);
  112. }
  113. if (filterPolyfills && !filterPolyfills(name)) return false;
  114. let shouldInject = (0, _helperCompilationTargets.isRequired)(name, targets, {
  115. compatData: polyfillsSupport,
  116. includes: include,
  117. excludes: exclude
  118. });
  119. if (shouldInjectPolyfill) {
  120. shouldInject = shouldInjectPolyfill(name, shouldInject);
  121. if (typeof shouldInject !== "boolean") {
  122. throw new Error(`.shouldInjectPolyfill must return a boolean.`);
  123. }
  124. }
  125. return shouldInject;
  126. },
  127. debug(name) {
  128. var _debugLog, _debugLog$polyfillsSu;
  129. debugLog().found = true;
  130. if (!debug || !name) return;
  131. if (debugLog().polyfills.has(providerName)) return;
  132. debugLog().polyfills.add(name);
  133. (_debugLog$polyfillsSu = (_debugLog = debugLog()).polyfillsSupport) != null ? _debugLog$polyfillsSu : _debugLog.polyfillsSupport = polyfillsSupport;
  134. },
  135. assertDependency(name, version = "*") {
  136. if (missingDependencies === false) return;
  137. if (absoluteImports) {
  138. // If absoluteImports is not false, we will try resolving
  139. // the dependency and throw if it's not possible. We can
  140. // skip the check here.
  141. return;
  142. }
  143. const dep = version === "*" ? name : `${name}@^${version}`;
  144. const found = missingDependencies.all ? false : mapGetOr(depsCache, `${name} :: ${dirname}`, () => deps.has(dirname, name));
  145. if (!found) {
  146. debugLog().missingDeps.add(dep);
  147. }
  148. }
  149. };
  150. const provider = factory(api, providerOptions, dirname);
  151. const providerName = provider.name || factory.name;
  152. if (typeof provider[methodName] !== "function") {
  153. throw new Error(`The "${providerName}" provider doesn't support the "${method}" polyfilling method.`);
  154. }
  155. if (Array.isArray(provider.polyfills)) {
  156. polyfillsNames = new Map(provider.polyfills.map((name, index) => [name, index]));
  157. filterPolyfills = provider.filterPolyfills;
  158. } else if (provider.polyfills) {
  159. polyfillsNames = new Map(Object.keys(provider.polyfills).map((name, index) => [name, index]));
  160. polyfillsSupport = provider.polyfills;
  161. filterPolyfills = provider.filterPolyfills;
  162. } else {
  163. polyfillsNames = new Map();
  164. }
  165. ({
  166. include,
  167. exclude
  168. } = (0, _normalizeOptions.validateIncludeExclude)(providerName, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
  169. let callProvider;
  170. if (methodName === "usageGlobal") {
  171. callProvider = (payload, path) => {
  172. var _ref;
  173. const utils = getUtils(path);
  174. return (_ref = provider[methodName](payload, utils, path)) != null ? _ref : false;
  175. };
  176. } else {
  177. callProvider = (payload, path) => {
  178. const utils = getUtils(path);
  179. provider[methodName](payload, utils, path);
  180. return false;
  181. };
  182. }
  183. return {
  184. debug,
  185. method,
  186. targets,
  187. provider,
  188. providerName,
  189. callProvider
  190. };
  191. }
  192. function definePolyfillProvider(factory) {
  193. return (0, _helperPluginUtils.declare)((babelApi, options, dirname) => {
  194. babelApi.assertVersion("^7.0.0 || ^8.0.0-alpha.0");
  195. const {
  196. traverse
  197. } = babelApi;
  198. let debugLog;
  199. const missingDependencies = (0, _normalizeOptions.applyMissingDependenciesDefaults)(options, babelApi);
  200. const {
  201. debug,
  202. method,
  203. targets,
  204. provider,
  205. providerName,
  206. callProvider
  207. } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
  208. const createVisitor = method === "entry-global" ? v.entry : v.usage;
  209. const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
  210. if (debug && debug !== _debugUtils.presetEnvSilentDebugHeader) {
  211. console.log(`${providerName}: \`DEBUG\` option`);
  212. console.log(`\nUsing targets: ${(0, _debugUtils.stringifyTargetsMultiline)(targets)}`);
  213. console.log(`\nUsing polyfills with \`${method}\` method:`);
  214. }
  215. const {
  216. runtimeName
  217. } = provider;
  218. return {
  219. name: "inject-polyfills",
  220. visitor,
  221. pre(file) {
  222. var _provider$pre;
  223. if (runtimeName) {
  224. if (file.get("runtimeHelpersModuleName") && file.get("runtimeHelpersModuleName") !== runtimeName) {
  225. console.warn(`Two different polyfill providers` + ` (${file.get("runtimeHelpersModuleProvider")}` + ` and ${providerName}) are trying to define two` + ` conflicting @babel/runtime alternatives:` + ` ${file.get("runtimeHelpersModuleName")} and ${runtimeName}.` + ` The second one will be ignored.`);
  226. } else {
  227. file.set("runtimeHelpersModuleName", runtimeName);
  228. file.set("runtimeHelpersModuleProvider", providerName);
  229. }
  230. }
  231. debugLog = {
  232. polyfills: new Set(),
  233. polyfillsSupport: undefined,
  234. found: false,
  235. providers: new Set(),
  236. missingDeps: new Set()
  237. };
  238. (_provider$pre = provider.pre) == null || _provider$pre.apply(this, arguments);
  239. },
  240. post() {
  241. var _provider$post;
  242. (_provider$post = provider.post) == null || _provider$post.apply(this, arguments);
  243. if (missingDependencies !== false) {
  244. if (missingDependencies.log === "per-file") {
  245. deps.logMissing(debugLog.missingDeps);
  246. } else {
  247. deps.laterLogMissing(debugLog.missingDeps);
  248. }
  249. }
  250. if (!debug) return;
  251. if (this.filename) console.log(`\n[${this.filename}]`);
  252. if (debugLog.polyfills.size === 0) {
  253. console.log(method === "entry-global" ? debugLog.found ? `Based on your targets, the ${providerName} polyfill did not add any polyfill.` : `The entry point for the ${providerName} polyfill has not been found.` : `Based on your code and targets, the ${providerName} polyfill did not add any polyfill.`);
  254. return;
  255. }
  256. if (method === "entry-global") {
  257. console.log(`The ${providerName} polyfill entry has been replaced with ` + `the following polyfills:`);
  258. } else {
  259. console.log(`The ${providerName} polyfill added the following polyfills:`);
  260. }
  261. for (const name of debugLog.polyfills) {
  262. var _debugLog$polyfillsSu2;
  263. if ((_debugLog$polyfillsSu2 = debugLog.polyfillsSupport) != null && _debugLog$polyfillsSu2[name]) {
  264. const filteredTargets = (0, _helperCompilationTargets.getInclusionReasons)(name, targets, debugLog.polyfillsSupport);
  265. const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
  266. console.log(` ${name} ${formattedTargets}`);
  267. } else {
  268. console.log(` ${name}`);
  269. }
  270. }
  271. }
  272. };
  273. });
  274. }
  275. function mapGetOr(map, key, getDefault) {
  276. let val = map.get(key);
  277. if (val === undefined) {
  278. val = getDefault();
  279. map.set(key, val);
  280. }
  281. return val;
  282. }
  283. function isEmpty(obj) {
  284. return Object.keys(obj).length === 0;
  285. }