index.node.mjs 28 KB

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