index.js 13 KB

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