index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 _importsCache = _interopRequireDefault(require("./imports-cache"));
  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. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  15. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }
  16. 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; }
  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, ["method", "targets", "ignoreBrowserslistConfig", "configPath", "debug", "shouldInjectPolyfill", "absoluteImports"]);
  29. let methodName;
  30. 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") {
  31. throw new Error(".method must be a string");
  32. } else {
  33. throw new Error(`.method must be one of "entry-global", "usage-global"` + ` or "usage-pure" (received ${JSON.stringify(method)})`);
  34. }
  35. if (typeof shouldInjectPolyfill === "function") {
  36. if (options.include || options.exclude) {
  37. throw new Error(`.include and .exclude are not supported when using the` + ` .shouldInjectPolyfill function.`);
  38. }
  39. } else if (shouldInjectPolyfill != null) {
  40. throw new Error(`.shouldInjectPolyfill must be a function, or undefined` + ` (received ${JSON.stringify(shouldInjectPolyfill)})`);
  41. }
  42. if (absoluteImports != null && typeof absoluteImports !== "boolean" && typeof absoluteImports !== "string") {
  43. throw new Error(`.absoluteImports must be a boolean, a string, or undefined` + ` (received ${JSON.stringify(absoluteImports)})`);
  44. }
  45. let targets;
  46. if ( // If any browserslist-related option is specified, fallback to the old
  47. // behavior of not using the targets specified in the top-level options.
  48. targetsOption || configPath || ignoreBrowserslistConfig) {
  49. const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
  50. browsers: targetsOption
  51. } : targetsOption;
  52. targets = getTargets(targetsObj, {
  53. ignoreBrowserslistConfig,
  54. configPath
  55. });
  56. } else {
  57. targets = babelApi.targets();
  58. }
  59. return {
  60. method,
  61. methodName,
  62. targets,
  63. absoluteImports: absoluteImports != null ? absoluteImports : false,
  64. shouldInjectPolyfill,
  65. debug: !!debug,
  66. providerOptions: providerOptions
  67. };
  68. }
  69. function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
  70. const {
  71. method,
  72. methodName,
  73. targets,
  74. debug,
  75. shouldInjectPolyfill,
  76. providerOptions,
  77. absoluteImports
  78. } = resolveOptions(options, babelApi);
  79. const getUtils = (0, _utils.createUtilsGetter)(new _importsCache.default(moduleName => deps.resolve(dirname, moduleName, absoluteImports))); // eslint-disable-next-line prefer-const
  80. let include, exclude;
  81. let polyfillsSupport;
  82. let polyfillsNames;
  83. let filterPolyfills;
  84. const depsCache = new Map();
  85. const api = {
  86. babel: babelApi,
  87. getUtils,
  88. method: options.method,
  89. targets,
  90. createMetaResolver: _metaResolver.default,
  91. shouldInjectPolyfill(name) {
  92. if (polyfillsNames === undefined) {
  93. throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
  94. }
  95. if (!polyfillsNames.has(name)) {
  96. console.warn(`Internal error in the ${provider.name} provider: ` + `unknown polyfill "${name}".`);
  97. }
  98. if (filterPolyfills && !filterPolyfills(name)) return false;
  99. let shouldInject = (0, _helperCompilationTargets.isRequired)(name, targets, {
  100. compatData: polyfillsSupport,
  101. includes: include,
  102. excludes: exclude
  103. });
  104. if (shouldInjectPolyfill) {
  105. shouldInject = shouldInjectPolyfill(name, shouldInject);
  106. if (typeof shouldInject !== "boolean") {
  107. throw new Error(`.shouldInjectPolyfill must return a boolean.`);
  108. }
  109. }
  110. return shouldInject;
  111. },
  112. debug(name) {
  113. debugLog().found = true;
  114. if (!debug || !name) return;
  115. if (debugLog().polyfills.has(provider.name)) return;
  116. debugLog().polyfills.set(name, polyfillsSupport && name && polyfillsSupport[name]);
  117. },
  118. assertDependency(name, version = "*") {
  119. if (missingDependencies === false) return;
  120. if (absoluteImports) {
  121. // If absoluteImports is not false, we will try resolving
  122. // the dependency and throw if it's not possible. We can
  123. // skip the check here.
  124. return;
  125. }
  126. const dep = version === "*" ? name : `${name}@^${version}`;
  127. const found = missingDependencies.all ? false : mapGetOr(depsCache, `${name} :: ${dirname}`, () => deps.has(dirname, name));
  128. if (!found) {
  129. debugLog().missingDeps.add(dep);
  130. }
  131. }
  132. };
  133. const provider = factory(api, providerOptions, dirname);
  134. if (typeof provider[methodName] !== "function") {
  135. throw new Error(`The "${provider.name || factory.name}" provider doesn't ` + `support the "${method}" polyfilling method.`);
  136. }
  137. if (Array.isArray(provider.polyfills)) {
  138. polyfillsNames = new Set(provider.polyfills);
  139. filterPolyfills = provider.filterPolyfills;
  140. } else if (provider.polyfills) {
  141. polyfillsNames = new Set(Object.keys(provider.polyfills));
  142. polyfillsSupport = provider.polyfills;
  143. filterPolyfills = provider.filterPolyfills;
  144. } else {
  145. polyfillsNames = new Set();
  146. }
  147. ({
  148. include,
  149. exclude
  150. } = (0, _normalizeOptions.validateIncludeExclude)(provider.name || factory.name, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
  151. return {
  152. debug,
  153. method,
  154. targets,
  155. provider,
  156. callProvider(payload, path) {
  157. const utils = getUtils(path); // $FlowIgnore
  158. provider[methodName](payload, utils, path);
  159. }
  160. };
  161. }
  162. function definePolyfillProvider(factory) {
  163. return (0, _helperPluginUtils.declare)((babelApi, options, dirname) => {
  164. babelApi.assertVersion(7);
  165. const {
  166. traverse
  167. } = babelApi;
  168. let debugLog;
  169. const missingDependencies = (0, _normalizeOptions.applyMissingDependenciesDefaults)(options, babelApi);
  170. const {
  171. debug,
  172. method,
  173. targets,
  174. provider,
  175. callProvider
  176. } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
  177. const createVisitor = method === "entry-global" ? v.entry : v.usage;
  178. const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
  179. if (debug && debug !== _debugUtils.presetEnvSilentDebugHeader) {
  180. console.log(`${provider.name}: \`DEBUG\` option`);
  181. console.log(`\nUsing targets: ${(0, _debugUtils.stringifyTargetsMultiline)(targets)}`);
  182. console.log(`\nUsing polyfills with \`${method}\` method:`);
  183. }
  184. return {
  185. name: "inject-polyfills",
  186. visitor,
  187. pre() {
  188. var _provider$pre;
  189. debugLog = {
  190. polyfills: new Map(),
  191. found: false,
  192. providers: new Set(),
  193. missingDeps: new Set()
  194. }; // $FlowIgnore - Flow doesn't support optional calls
  195. (_provider$pre = provider.pre) == null ? void 0 : _provider$pre.apply(this, arguments);
  196. },
  197. post() {
  198. var _provider$post;
  199. // $FlowIgnore - Flow doesn't support optional calls
  200. (_provider$post = provider.post) == null ? void 0 : _provider$post.apply(this, arguments);
  201. if (missingDependencies !== false) {
  202. if (missingDependencies.log === "per-file") {
  203. deps.logMissing(debugLog.missingDeps);
  204. } else {
  205. deps.laterLogMissing(debugLog.missingDeps);
  206. }
  207. }
  208. if (!debug) return;
  209. if (this.filename) console.log(`\n[${this.filename}]`);
  210. if (debugLog.polyfills.size === 0) {
  211. console.log(method === "entry-global" ? debugLog.found ? `Based on your targets, the ${provider.name} polyfill did not add any polyfill.` : `The entry point for the ${provider.name} polyfill has not been found.` : `Based on your code and targets, the ${provider.name} polyfill did not add any polyfill.`);
  212. return;
  213. }
  214. if (method === "entry-global") {
  215. console.log(`The ${provider.name} polyfill entry has been replaced with ` + `the following polyfills:`);
  216. } else {
  217. console.log(`The ${provider.name} polyfill added the following polyfills:`);
  218. }
  219. for (const [name, support] of debugLog.polyfills) {
  220. if (support) {
  221. const filteredTargets = (0, _helperCompilationTargets.getInclusionReasons)(name, targets, support);
  222. const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
  223. console.log(` ${name} ${formattedTargets}`);
  224. } else {
  225. console.log(` ${name}`);
  226. }
  227. }
  228. }
  229. };
  230. });
  231. }
  232. function mapGetOr(map, key, getDefault) {
  233. let val = map.get(key);
  234. if (val === undefined) {
  235. val = getDefault();
  236. map.set(key, val);
  237. }
  238. return val;
  239. }