index.browser.mjs 33 KB

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