index.browser.mjs 24 KB

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