index.node.mjs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. import { declare } from '@babel/helper-plugin-utils';
  2. import _getTargets, { prettifyTargets, getInclusionReasons, isRequired } from '@babel/helper-compilation-targets';
  3. import * as babel from '@babel/core';
  4. import path from 'path';
  5. import debounce from 'lodash.debounce';
  6. import requireResolve from 'resolve';
  7. import { createRequire } from 'module';
  8. const {
  9. types: t$1,
  10. template
  11. } = babel.default || babel;
  12. function intersection(a, b) {
  13. const result = new Set();
  14. a.forEach(v => b.has(v) && result.add(v));
  15. return result;
  16. }
  17. function has$1(object, key) {
  18. return Object.prototype.hasOwnProperty.call(object, key);
  19. }
  20. function getType(target) {
  21. return Object.prototype.toString.call(target).slice(8, -1);
  22. }
  23. function resolveId(path) {
  24. if (path.isIdentifier() && !path.scope.hasBinding(path.node.name,
  25. /* noGlobals */
  26. true)) {
  27. return path.node.name;
  28. }
  29. const {
  30. deopt
  31. } = path.evaluate();
  32. if (deopt && deopt.isIdentifier()) {
  33. return deopt.node.name;
  34. }
  35. }
  36. function resolveKey(path, computed = false) {
  37. const {
  38. node,
  39. parent,
  40. scope
  41. } = path;
  42. if (path.isStringLiteral()) return node.value;
  43. const {
  44. name
  45. } = node;
  46. const isIdentifier = path.isIdentifier();
  47. if (isIdentifier && !(computed || parent.computed)) return name;
  48. if (computed && path.isMemberExpression() && path.get("object").isIdentifier({
  49. name: "Symbol"
  50. }) && !scope.hasBinding("Symbol",
  51. /* noGlobals */
  52. true)) {
  53. const sym = resolveKey(path.get("property"), path.node.computed);
  54. if (sym) return "Symbol." + sym;
  55. }
  56. if (!isIdentifier || scope.hasBinding(name,
  57. /* noGlobals */
  58. true)) {
  59. const {
  60. value
  61. } = path.evaluate();
  62. if (typeof value === "string") return value;
  63. }
  64. }
  65. function resolveSource(obj) {
  66. if (obj.isMemberExpression() && obj.get("property").isIdentifier({
  67. name: "prototype"
  68. })) {
  69. const id = resolveId(obj.get("object"));
  70. if (id) {
  71. return {
  72. id,
  73. placement: "prototype"
  74. };
  75. }
  76. return {
  77. id: null,
  78. placement: null
  79. };
  80. }
  81. const id = resolveId(obj);
  82. if (id) {
  83. return {
  84. id,
  85. placement: "static"
  86. };
  87. }
  88. const {
  89. value
  90. } = obj.evaluate();
  91. if (value !== undefined) {
  92. return {
  93. id: getType(value),
  94. placement: "prototype"
  95. };
  96. } else if (obj.isRegExpLiteral()) {
  97. return {
  98. id: "RegExp",
  99. placement: "prototype"
  100. };
  101. } else if (obj.isFunction()) {
  102. return {
  103. id: "Function",
  104. placement: "prototype"
  105. };
  106. }
  107. return {
  108. id: null,
  109. placement: null
  110. };
  111. }
  112. function getImportSource({
  113. node
  114. }) {
  115. if (node.specifiers.length === 0) return node.source.value;
  116. }
  117. function getRequireSource({
  118. node
  119. }) {
  120. if (!t$1.isExpressionStatement(node)) return;
  121. const {
  122. expression
  123. } = node;
  124. const isRequire = t$1.isCallExpression(expression) && t$1.isIdentifier(expression.callee) && expression.callee.name === "require" && expression.arguments.length === 1 && t$1.isStringLiteral(expression.arguments[0]);
  125. if (isRequire) return expression.arguments[0].value;
  126. }
  127. function hoist(node) {
  128. node._blockHoist = 3;
  129. return node;
  130. }
  131. function createUtilsGetter(cache) {
  132. return path => {
  133. const prog = path.findParent(p => p.isProgram());
  134. return {
  135. injectGlobalImport(url) {
  136. cache.storeAnonymous(prog, url, (isScript, source) => {
  137. return isScript ? template.statement.ast`require(${source})` : t$1.importDeclaration([], source);
  138. });
  139. },
  140. injectNamedImport(url, name, hint = name) {
  141. return cache.storeNamed(prog, url, name, (isScript, source, name) => {
  142. const id = prog.scope.generateUidIdentifier(hint);
  143. return {
  144. node: isScript ? hoist(template.statement.ast`
  145. var ${id} = require(${source}).${name}
  146. `) : t$1.importDeclaration([t$1.importSpecifier(id, name)], source),
  147. name: id.name
  148. };
  149. });
  150. },
  151. injectDefaultImport(url, hint = url) {
  152. return cache.storeNamed(prog, url, "default", (isScript, source) => {
  153. const id = prog.scope.generateUidIdentifier(hint);
  154. return {
  155. node: isScript ? hoist(template.statement.ast`var ${id} = require(${source})`) : t$1.importDeclaration([t$1.importDefaultSpecifier(id)], source),
  156. name: id.name
  157. };
  158. });
  159. }
  160. };
  161. };
  162. }
  163. const {
  164. types: t
  165. } = babel.default || babel;
  166. class ImportsCache {
  167. constructor(resolver) {
  168. this._imports = new WeakMap();
  169. this._anonymousImports = new WeakMap();
  170. this._lastImports = new WeakMap();
  171. this._resolver = resolver;
  172. }
  173. storeAnonymous(programPath, url, // eslint-disable-next-line no-undef
  174. getVal) {
  175. const key = this._normalizeKey(programPath, url);
  176. const imports = this._ensure(this._anonymousImports, programPath, Set);
  177. if (imports.has(key)) return;
  178. const node = getVal(programPath.node.sourceType === "script", t.stringLiteral(this._resolver(url)));
  179. imports.add(key);
  180. this._injectImport(programPath, node);
  181. }
  182. storeNamed(programPath, url, name, getVal) {
  183. const key = this._normalizeKey(programPath, url, name);
  184. const imports = this._ensure(this._imports, programPath, Map);
  185. if (!imports.has(key)) {
  186. const {
  187. node,
  188. name: id
  189. } = getVal(programPath.node.sourceType === "script", t.stringLiteral(this._resolver(url)), t.identifier(name));
  190. imports.set(key, id);
  191. this._injectImport(programPath, node);
  192. }
  193. return t.identifier(imports.get(key));
  194. }
  195. _injectImport(programPath, node) {
  196. let lastImport = this._lastImports.get(programPath);
  197. if (lastImport && lastImport.node && // Sometimes the AST is modified and the "last import"
  198. // we have has been replaced
  199. lastImport.parent === programPath.node && lastImport.container === programPath.node.body) {
  200. lastImport = lastImport.insertAfter(node);
  201. } else {
  202. lastImport = programPath.unshiftContainer("body", node);
  203. }
  204. lastImport = lastImport[lastImport.length - 1];
  205. this._lastImports.set(programPath, lastImport);
  206. /*
  207. let lastImport;
  208. programPath.get("body").forEach(path => {
  209. if (path.isImportDeclaration()) lastImport = path;
  210. if (
  211. path.isExpressionStatement() &&
  212. isRequireCall(path.get("expression"))
  213. ) {
  214. lastImport = path;
  215. }
  216. if (
  217. path.isVariableDeclaration() &&
  218. path.get("declarations").length === 1 &&
  219. (isRequireCall(path.get("declarations.0.init")) ||
  220. (path.get("declarations.0.init").isMemberExpression() &&
  221. isRequireCall(path.get("declarations.0.init.object"))))
  222. ) {
  223. lastImport = path;
  224. }
  225. });*/
  226. }
  227. _ensure(map, programPath, Collection) {
  228. let collection = map.get(programPath);
  229. if (!collection) {
  230. collection = new Collection();
  231. map.set(programPath, collection);
  232. }
  233. return collection;
  234. }
  235. _normalizeKey(programPath, url, name = "") {
  236. const {
  237. sourceType
  238. } = programPath.node; // If we rely on the imported binding (the "name" parameter), we also need to cache
  239. // based on the sourceType. This is because the module transforms change the names
  240. // of the import variables.
  241. return `${name && sourceType}::${url}::${name}`;
  242. }
  243. }
  244. const presetEnvSilentDebugHeader = "#__secret_key__@babel/preset-env__don't_log_debug_header_and_resolved_targets";
  245. function stringifyTargetsMultiline(targets) {
  246. return JSON.stringify(prettifyTargets(targets), null, 2);
  247. }
  248. function patternToRegExp(pattern) {
  249. if (pattern instanceof RegExp) return pattern;
  250. try {
  251. return new RegExp(`^${pattern}$`);
  252. } catch {
  253. return null;
  254. }
  255. }
  256. function buildUnusedError(label, unused) {
  257. if (!unused.length) return "";
  258. return ` - The following "${label}" patterns didn't match any polyfill:\n` + unused.map(original => ` ${String(original)}\n`).join("");
  259. }
  260. function buldDuplicatesError(duplicates) {
  261. if (!duplicates.size) return "";
  262. return ` - The following polyfills were matched both by "include" and "exclude" patterns:\n` + Array.from(duplicates, name => ` ${name}\n`).join("");
  263. }
  264. function validateIncludeExclude(provider, polyfills, includePatterns, excludePatterns) {
  265. let current;
  266. const filter = pattern => {
  267. const regexp = patternToRegExp(pattern);
  268. if (!regexp) return false;
  269. let matched = false;
  270. for (const polyfill of polyfills) {
  271. if (regexp.test(polyfill)) {
  272. matched = true;
  273. current.add(polyfill);
  274. }
  275. }
  276. return !matched;
  277. }; // prettier-ignore
  278. const include = current = new Set();
  279. const unusedInclude = Array.from(includePatterns).filter(filter); // prettier-ignore
  280. const exclude = current = new Set();
  281. const unusedExclude = Array.from(excludePatterns).filter(filter);
  282. const duplicates = intersection(include, exclude);
  283. if (duplicates.size > 0 || unusedInclude.length > 0 || unusedExclude.length > 0) {
  284. throw new Error(`Error while validating the "${provider}" provider options:\n` + buildUnusedError("include", unusedInclude) + buildUnusedError("exclude", unusedExclude) + buldDuplicatesError(duplicates));
  285. }
  286. return {
  287. include,
  288. exclude
  289. };
  290. }
  291. function applyMissingDependenciesDefaults(options, babelApi) {
  292. const {
  293. missingDependencies = {}
  294. } = options;
  295. if (missingDependencies === false) return false;
  296. const caller = babelApi.caller(caller => caller == null ? void 0 : caller.name);
  297. const {
  298. log = "deferred",
  299. inject = caller === "rollup-plugin-babel" ? "throw" : "import",
  300. all = false
  301. } = missingDependencies;
  302. return {
  303. log,
  304. inject,
  305. all
  306. };
  307. }
  308. var usage = (callProvider => {
  309. function property(object, key, placement, path) {
  310. return callProvider({
  311. kind: "property",
  312. object,
  313. key,
  314. placement
  315. }, path);
  316. }
  317. return {
  318. // Symbol(), new Promise
  319. ReferencedIdentifier(path) {
  320. const {
  321. node: {
  322. name
  323. },
  324. scope
  325. } = path;
  326. if (scope.getBindingIdentifier(name)) return;
  327. callProvider({
  328. kind: "global",
  329. name
  330. }, path);
  331. },
  332. MemberExpression(path) {
  333. const key = resolveKey(path.get("property"), path.node.computed);
  334. if (!key || key === "prototype") return;
  335. const object = path.get("object");
  336. const binding = object.scope.getBinding(object.node.name);
  337. if (binding && binding.path.isImportNamespaceSpecifier()) return;
  338. const source = resolveSource(object);
  339. return property(source.id, key, source.placement, path);
  340. },
  341. ObjectPattern(path) {
  342. const {
  343. parentPath,
  344. parent
  345. } = path;
  346. let obj; // const { keys, values } = Object
  347. if (parentPath.isVariableDeclarator()) {
  348. obj = parentPath.get("init"); // ({ keys, values } = Object)
  349. } else if (parentPath.isAssignmentExpression()) {
  350. obj = parentPath.get("right"); // !function ({ keys, values }) {...} (Object)
  351. // resolution does not work after properties transform :-(
  352. } else if (parentPath.isFunction()) {
  353. const grand = parentPath.parentPath;
  354. if (grand.isCallExpression() || grand.isNewExpression()) {
  355. if (grand.node.callee === parent) {
  356. obj = grand.get("arguments")[path.key];
  357. }
  358. }
  359. }
  360. let id = null;
  361. let placement = null;
  362. if (obj) ({
  363. id,
  364. placement
  365. } = resolveSource(obj));
  366. for (const prop of path.get("properties")) {
  367. if (prop.isObjectProperty()) {
  368. const key = resolveKey(prop.get("key"));
  369. if (key) property(id, key, placement, prop);
  370. }
  371. }
  372. },
  373. BinaryExpression(path) {
  374. if (path.node.operator !== "in") return;
  375. const source = resolveSource(path.get("right"));
  376. const key = resolveKey(path.get("left"), true);
  377. if (!key) return;
  378. callProvider({
  379. kind: "in",
  380. object: source.id,
  381. key,
  382. placement: source.placement
  383. }, path);
  384. }
  385. };
  386. });
  387. var entry = (callProvider => ({
  388. ImportDeclaration(path) {
  389. const source = getImportSource(path);
  390. if (!source) return;
  391. callProvider({
  392. kind: "import",
  393. source
  394. }, path);
  395. },
  396. Program(path) {
  397. path.get("body").forEach(bodyPath => {
  398. const source = getRequireSource(bodyPath);
  399. if (!source) return;
  400. callProvider({
  401. kind: "import",
  402. source
  403. }, bodyPath);
  404. });
  405. }
  406. }));
  407. const nativeRequireResolve = parseFloat(process.versions.node) >= 8.9; // $FlowIgnore
  408. const require = createRequire(import
  409. /*::(_)*/
  410. .meta.url); // eslint-disable-line
  411. function resolve(dirname, moduleName, absoluteImports) {
  412. if (absoluteImports === false) return moduleName;
  413. let basedir = dirname;
  414. if (typeof absoluteImports === "string") {
  415. basedir = path.resolve(basedir, absoluteImports);
  416. }
  417. try {
  418. if (nativeRequireResolve) {
  419. return require.resolve(moduleName, {
  420. paths: [basedir]
  421. });
  422. } else {
  423. return requireResolve.sync(moduleName, {
  424. basedir
  425. });
  426. }
  427. } catch (err) {
  428. if (err.code !== "MODULE_NOT_FOUND") throw err; // $FlowIgnore
  429. throw Object.assign(new Error(`Failed to resolve "${moduleName}" relative to "${dirname}"`), {
  430. code: "BABEL_POLYFILL_NOT_FOUND",
  431. polyfill: moduleName,
  432. dirname
  433. });
  434. }
  435. }
  436. function has(basedir, name) {
  437. try {
  438. if (nativeRequireResolve) {
  439. require.resolve(name, {
  440. paths: [basedir]
  441. });
  442. } else {
  443. requireResolve.sync(name, {
  444. basedir
  445. });
  446. }
  447. return true;
  448. } catch {
  449. return false;
  450. }
  451. }
  452. function logMissing(missingDeps) {
  453. if (missingDeps.size === 0) return;
  454. const deps = Array.from(missingDeps).sort().join(" ");
  455. console.warn("\nSome polyfills have been added but are not present in your dependencies.\n" + "Please run one of the following commands:\n" + `\tnpm install --save ${deps}\n` + `\tyarn add ${deps}\n`);
  456. process.exitCode = 1;
  457. }
  458. let allMissingDeps = new Set();
  459. const laterLogMissingDependencies = debounce(() => {
  460. logMissing(allMissingDeps);
  461. allMissingDeps = new Set();
  462. }, 100);
  463. function laterLogMissing(missingDeps) {
  464. if (missingDeps.size === 0) return;
  465. missingDeps.forEach(name => allMissingDeps.add(name));
  466. laterLogMissingDependencies();
  467. }
  468. const PossibleGlobalObjects = new Set(["global", "globalThis", "self", "window"]);
  469. function createMetaResolver(polyfills) {
  470. const {
  471. static: staticP,
  472. instance: instanceP,
  473. global: globalP
  474. } = polyfills;
  475. return meta => {
  476. if (meta.kind === "global" && globalP && has$1(globalP, meta.name)) {
  477. return {
  478. kind: "global",
  479. desc: globalP[meta.name],
  480. name: meta.name
  481. };
  482. }
  483. if (meta.kind === "property" || meta.kind === "in") {
  484. const {
  485. placement,
  486. object,
  487. key
  488. } = meta;
  489. if (object && placement === "static") {
  490. if (globalP && PossibleGlobalObjects.has(object) && has$1(globalP, key)) {
  491. return {
  492. kind: "global",
  493. desc: globalP[key],
  494. name: key
  495. };
  496. }
  497. if (staticP && has$1(staticP, object) && has$1(staticP[object], key)) {
  498. return {
  499. kind: "static",
  500. desc: staticP[object][key],
  501. name: `${object}$${key}`
  502. };
  503. }
  504. }
  505. if (instanceP && has$1(instanceP, key)) {
  506. return {
  507. kind: "instance",
  508. desc: instanceP[key],
  509. name: `${key}`
  510. };
  511. }
  512. }
  513. };
  514. }
  515. const getTargets = _getTargets.default || _getTargets;
  516. function resolveOptions(options, babelApi) {
  517. const {
  518. method,
  519. targets: targetsOption,
  520. ignoreBrowserslistConfig,
  521. configPath,
  522. debug,
  523. shouldInjectPolyfill,
  524. absoluteImports,
  525. ...providerOptions
  526. } = options;
  527. let methodName;
  528. 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") {
  529. throw new Error(".method must be a string");
  530. } else {
  531. throw new Error(`.method must be one of "entry-global", "usage-global"` + ` or "usage-pure" (received ${JSON.stringify(method)})`);
  532. }
  533. if (typeof shouldInjectPolyfill === "function") {
  534. if (options.include || options.exclude) {
  535. throw new Error(`.include and .exclude are not supported when using the` + ` .shouldInjectPolyfill function.`);
  536. }
  537. } else if (shouldInjectPolyfill != null) {
  538. throw new Error(`.shouldInjectPolyfill must be a function, or undefined` + ` (received ${JSON.stringify(shouldInjectPolyfill)})`);
  539. }
  540. if (absoluteImports != null && typeof absoluteImports !== "boolean" && typeof absoluteImports !== "string") {
  541. throw new Error(`.absoluteImports must be a boolean, a string, or undefined` + ` (received ${JSON.stringify(absoluteImports)})`);
  542. }
  543. let targets;
  544. if ( // If any browserslist-related option is specified, fallback to the old
  545. // behavior of not using the targets specified in the top-level options.
  546. targetsOption || configPath || ignoreBrowserslistConfig) {
  547. const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
  548. browsers: targetsOption
  549. } : targetsOption;
  550. targets = getTargets(targetsObj, {
  551. ignoreBrowserslistConfig,
  552. configPath
  553. });
  554. } else {
  555. targets = babelApi.targets();
  556. }
  557. return {
  558. method,
  559. methodName,
  560. targets,
  561. absoluteImports: absoluteImports != null ? absoluteImports : false,
  562. shouldInjectPolyfill,
  563. debug: !!debug,
  564. providerOptions: providerOptions
  565. };
  566. }
  567. function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
  568. const {
  569. method,
  570. methodName,
  571. targets,
  572. debug,
  573. shouldInjectPolyfill,
  574. providerOptions,
  575. absoluteImports
  576. } = resolveOptions(options, babelApi);
  577. const getUtils = createUtilsGetter(new ImportsCache(moduleName => resolve(dirname, moduleName, absoluteImports))); // eslint-disable-next-line prefer-const
  578. let include, exclude;
  579. let polyfillsSupport;
  580. let polyfillsNames;
  581. let filterPolyfills;
  582. const depsCache = new Map();
  583. const api = {
  584. babel: babelApi,
  585. getUtils,
  586. method: options.method,
  587. targets,
  588. createMetaResolver,
  589. shouldInjectPolyfill(name) {
  590. if (polyfillsNames === undefined) {
  591. throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
  592. }
  593. if (!polyfillsNames.has(name)) {
  594. console.warn(`Internal error in the ${provider.name} provider: ` + `unknown polyfill "${name}".`);
  595. }
  596. if (filterPolyfills && !filterPolyfills(name)) return false;
  597. let shouldInject = isRequired(name, targets, {
  598. compatData: polyfillsSupport,
  599. includes: include,
  600. excludes: exclude
  601. });
  602. if (shouldInjectPolyfill) {
  603. shouldInject = shouldInjectPolyfill(name, shouldInject);
  604. if (typeof shouldInject !== "boolean") {
  605. throw new Error(`.shouldInjectPolyfill must return a boolean.`);
  606. }
  607. }
  608. return shouldInject;
  609. },
  610. debug(name) {
  611. debugLog().found = true;
  612. if (!debug || !name) return;
  613. if (debugLog().polyfills.has(provider.name)) return;
  614. debugLog().polyfills.set(name, polyfillsSupport && name && polyfillsSupport[name]);
  615. },
  616. assertDependency(name, version = "*") {
  617. if (missingDependencies === false) return;
  618. if (absoluteImports) {
  619. // If absoluteImports is not false, we will try resolving
  620. // the dependency and throw if it's not possible. We can
  621. // skip the check here.
  622. return;
  623. }
  624. const dep = version === "*" ? name : `${name}@^${version}`;
  625. const found = missingDependencies.all ? false : mapGetOr(depsCache, `${name} :: ${dirname}`, () => has(dirname, name));
  626. if (!found) {
  627. debugLog().missingDeps.add(dep);
  628. }
  629. }
  630. };
  631. const provider = factory(api, providerOptions, dirname);
  632. if (typeof provider[methodName] !== "function") {
  633. throw new Error(`The "${provider.name || factory.name}" provider doesn't ` + `support the "${method}" polyfilling method.`);
  634. }
  635. if (Array.isArray(provider.polyfills)) {
  636. polyfillsNames = new Set(provider.polyfills);
  637. filterPolyfills = provider.filterPolyfills;
  638. } else if (provider.polyfills) {
  639. polyfillsNames = new Set(Object.keys(provider.polyfills));
  640. polyfillsSupport = provider.polyfills;
  641. filterPolyfills = provider.filterPolyfills;
  642. } else {
  643. polyfillsNames = new Set();
  644. }
  645. ({
  646. include,
  647. exclude
  648. } = validateIncludeExclude(provider.name || factory.name, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
  649. return {
  650. debug,
  651. method,
  652. targets,
  653. provider,
  654. callProvider(payload, path) {
  655. const utils = getUtils(path); // $FlowIgnore
  656. provider[methodName](payload, utils, path);
  657. }
  658. };
  659. }
  660. function definePolyfillProvider(factory) {
  661. return declare((babelApi, options, dirname) => {
  662. babelApi.assertVersion(7);
  663. const {
  664. traverse
  665. } = babelApi;
  666. let debugLog;
  667. const missingDependencies = applyMissingDependenciesDefaults(options, babelApi);
  668. const {
  669. debug,
  670. method,
  671. targets,
  672. provider,
  673. callProvider
  674. } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
  675. const createVisitor = method === "entry-global" ? entry : usage;
  676. const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
  677. if (debug && debug !== presetEnvSilentDebugHeader) {
  678. console.log(`${provider.name}: \`DEBUG\` option`);
  679. console.log(`\nUsing targets: ${stringifyTargetsMultiline(targets)}`);
  680. console.log(`\nUsing polyfills with \`${method}\` method:`);
  681. }
  682. return {
  683. name: "inject-polyfills",
  684. visitor,
  685. pre() {
  686. var _provider$pre;
  687. debugLog = {
  688. polyfills: new Map(),
  689. found: false,
  690. providers: new Set(),
  691. missingDeps: new Set()
  692. }; // $FlowIgnore - Flow doesn't support optional calls
  693. (_provider$pre = provider.pre) == null ? void 0 : _provider$pre.apply(this, arguments);
  694. },
  695. post() {
  696. var _provider$post;
  697. // $FlowIgnore - Flow doesn't support optional calls
  698. (_provider$post = provider.post) == null ? void 0 : _provider$post.apply(this, arguments);
  699. if (missingDependencies !== false) {
  700. if (missingDependencies.log === "per-file") {
  701. logMissing(debugLog.missingDeps);
  702. } else {
  703. laterLogMissing(debugLog.missingDeps);
  704. }
  705. }
  706. if (!debug) return;
  707. if (this.filename) console.log(`\n[${this.filename}]`);
  708. if (debugLog.polyfills.size === 0) {
  709. 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.`);
  710. return;
  711. }
  712. if (method === "entry-global") {
  713. console.log(`The ${provider.name} polyfill entry has been replaced with ` + `the following polyfills:`);
  714. } else {
  715. console.log(`The ${provider.name} polyfill added the following polyfills:`);
  716. }
  717. for (const [name, support] of debugLog.polyfills) {
  718. if (support) {
  719. const filteredTargets = getInclusionReasons(name, targets, support);
  720. const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
  721. console.log(` ${name} ${formattedTargets}`);
  722. } else {
  723. console.log(` ${name}`);
  724. }
  725. }
  726. }
  727. };
  728. });
  729. }
  730. function mapGetOr(map, key, getDefault) {
  731. let val = map.get(key);
  732. if (val === undefined) {
  733. val = getDefault();
  734. map.set(key, val);
  735. }
  736. return val;
  737. }
  738. export default definePolyfillProvider;
  739. //# sourceMappingURL=index.node.mjs.map