index.browser.mjs 27 KB

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