UNPKG

2.87 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.detectPackage = void 0;
4const x_global_1 = require("@polkadot/x-global");
5const function_js_1 = require("./is/function.js");
6const DEDUPE = 'Either remove and explicitly install matching versions or dedupe using your package manager.\nThe following conflicting packages were found:';
7/** @internal */
8function getEntry(name) {
9 const _global = x_global_1.xglobal;
10 if (!_global.__polkadotjs) {
11 _global.__polkadotjs = {};
12 }
13 if (!_global.__polkadotjs[name]) {
14 _global.__polkadotjs[name] = [];
15 }
16 return _global.__polkadotjs[name];
17}
18/** @internal */
19function formatDisplay(all, fmt) {
20 let max = 0;
21 for (let i = 0, count = all.length; i < count; i++) {
22 max = Math.max(max, all[i].version.length);
23 }
24 return all
25 .map((d) => `\t${fmt(d.version.padEnd(max), d).join('\t')}`)
26 .join('\n');
27}
28/** @internal */
29function formatInfo(version, { name }) {
30 return [
31 version,
32 name
33 ];
34}
35/** @internal */
36function formatVersion(version, { path, type }) {
37 let extracted;
38 if (path && path.length >= 5) {
39 const nmIndex = path.indexOf('node_modules');
40 extracted = nmIndex === -1
41 ? path
42 : path.substring(nmIndex);
43 }
44 else {
45 extracted = '<unknown>';
46 }
47 return [
48 `${`${type || ''}`.padStart(3)} ${version}`,
49 extracted
50 ];
51}
52/** @internal */
53function getPath(infoPath, pathOrFn) {
54 if (infoPath) {
55 return infoPath;
56 }
57 else if ((0, function_js_1.isFunction)(pathOrFn)) {
58 try {
59 return pathOrFn() || '';
60 }
61 catch {
62 return '';
63 }
64 }
65 return pathOrFn || '';
66}
67/** @internal */
68function warn(pre, all, fmt) {
69 console.warn(`${pre}\n${DEDUPE}\n${formatDisplay(all, fmt)}`);
70}
71/**
72 * @name detectPackage
73 * @summary Checks that a specific package is only imported once
74 * @description A `@polkadot/*` version detection utility, checking for one occurence of a package in addition to checking for ddependency versions.
75 */
76function detectPackage({ name, path, type, version }, pathOrFn, deps = []) {
77 if (!name.startsWith('@polkadot')) {
78 throw new Error(`Invalid package descriptor ${name}`);
79 }
80 const entry = getEntry(name);
81 entry.push({ path: getPath(path, pathOrFn), type, version });
82 if (entry.length !== 1) {
83 warn(`${name} has multiple versions, ensure that there is only one installed.`, entry, formatVersion);
84 }
85 else {
86 const mismatches = deps.filter((d) => d && d.version !== version);
87 if (mismatches.length) {
88 warn(`${name} requires direct dependencies exactly matching version ${version}.`, mismatches, formatInfo);
89 }
90 }
91}
92exports.detectPackage = detectPackage;