index.browser.mjs 26 KB

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