index.node.mjs 34 KB

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