index.node.mjs 27 KB

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