source: frontend/node_modules/@babel/helper-define-polyfill-provider/esm/index.node.mjs

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 13 days ago

Fix frontend appearance

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