index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var fetch = require('node-fetch');
  4. var child_process = require('child_process');
  5. var chalk = require('chalk');
  6. var consola = require('consola');
  7. var path = require('path');
  8. var fs = require('fs');
  9. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  10. var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
  11. var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
  12. var consola__default = /*#__PURE__*/_interopDefaultLegacy(consola);
  13. var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  14. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
  15. var reportAndThrowError = function reportAndThrowError(msg) {
  16. report(msg);
  17. throw new Error(msg);
  18. };
  19. var report = function report(message) {
  20. consola__default['default'].debug({
  21. message: String(message),
  22. tag: 'opencollective'
  23. });
  24. };
  25. var hideMessage = function hideMessage() {
  26. var env = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : process.env;
  27. // Show message if it is forced
  28. if (env.OPENCOLLECTIVE_FORCE) {
  29. return false;
  30. } // Don't show after oracle postinstall
  31. if (env.OC_POSTINSTALL_TEST) {
  32. return true;
  33. } // Don't show if opted-out
  34. if (env.OPENCOLLECTIVE_HIDE) {
  35. return true;
  36. } // Compatability with opencollective-postinstall
  37. if (!!env.DISABLE_OPENCOLLECTIVE && env.DISABLE_OPENCOLLECTIVE !== '0' && env.DISABLE_OPENCOLLECTIVE !== 'false') {
  38. return true;
  39. } // Don't show if on CI
  40. if (env.CI || env.CONTINUOUS_INTEGRATION) {
  41. return true;
  42. } // Only show in dev environment
  43. return Boolean(env.NODE_ENV) && !['dev', 'development'].includes(env.NODE_ENV);
  44. };
  45. var formatMoney = function formatMoney(currency) {
  46. return function (amount) {
  47. amount = amount / 100; // converting cents
  48. var precision = 0;
  49. return amount.toLocaleString(currency, {
  50. style: 'currency',
  51. currency: currency,
  52. minimumFractionDigits: precision,
  53. maximumFractionDigits: precision
  54. });
  55. };
  56. };
  57. var isWin32 = process.platform === 'win32';
  58. var stripLeadingSlash = function stripLeadingSlash(s) {
  59. return s.startsWith('/') ? s.substring(1) : s;
  60. };
  61. var stripTrailingSlash = function stripTrailingSlash(s) {
  62. return s.endsWith('/') ? s.slice(0, -1) : s;
  63. };
  64. /* eslint-disable no-console */
  65. var print = function print() {
  66. var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
  67. return function () {
  68. var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  69. var terminalCols = retrieveCols();
  70. var strLength = str.replace(/\u001B\[[0-9]{2}m/g, '').length;
  71. var leftPaddingLength = Math.floor((terminalCols - strLength) / 2);
  72. var leftPadding = ' '.repeat(Math.max(leftPaddingLength, 0));
  73. if (color) {
  74. str = chalk__default['default'][color](str);
  75. }
  76. console.log(leftPadding, str);
  77. };
  78. };
  79. var retrieveCols = function () {
  80. var result = false;
  81. return function () {
  82. if (result) {
  83. return result;
  84. }
  85. var defaultCols = 80;
  86. try {
  87. var terminalCols = child_process.execSync('tput cols', {
  88. stdio: ['pipe', 'pipe', 'ignore']
  89. });
  90. result = parseInt(terminalCols.toString()) || defaultCols;
  91. } catch (e) {
  92. result = defaultCols;
  93. }
  94. return result;
  95. };
  96. }();
  97. var printStats = function printStats(stats, color) {
  98. if (!stats) {
  99. return;
  100. }
  101. var colored = print(color);
  102. var bold = print('bold');
  103. var formatWithCurrency = formatMoney(stats.currency);
  104. colored("Number of contributors: ".concat(stats.contributorsCount));
  105. colored("Number of backers: ".concat(stats.backersCount));
  106. colored("Annual budget: ".concat(formatWithCurrency(stats.yearlyIncome)));
  107. bold("Current balance: ".concat(formatWithCurrency(stats.balance)), 'bold');
  108. };
  109. var printLogo = function printLogo(logoText) {
  110. if (!logoText) {
  111. return;
  112. }
  113. logoText.split('\n').forEach(print('blue'));
  114. };
  115. /**
  116. * Only show emoji on OSx (Windows shell doesn't like them that much ¯\_(ツ)_/¯ )
  117. * @param {*} emoji
  118. */
  119. var emoji = function emoji(_emoji) {
  120. return process.stdout.isTTY && !isWin32 ? _emoji : '';
  121. };
  122. function printFooter(collective) {
  123. var dim = print('dim');
  124. var yellow = print('yellow');
  125. var emptyLine = print();
  126. yellow("Thanks for installing ".concat(collective.slug, " ").concat(emoji('🙏')));
  127. dim('Please consider donating to our open collective');
  128. dim('to help us maintain this package.');
  129. emptyLine();
  130. printStats(collective.stats);
  131. emptyLine();
  132. print()("".concat(chalk__default['default'].bold("".concat(emoji('👉 '), " ").concat(collective.donationText)), " ").concat(chalk__default['default'].underline(collective.donationUrl)));
  133. emptyLine();
  134. }
  135. function _slicedToArray(arr, i) {
  136. return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
  137. }
  138. function _arrayWithHoles(arr) {
  139. if (Array.isArray(arr)) return arr;
  140. }
  141. function _iterableToArrayLimit(arr, i) {
  142. if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
  143. var _arr = [];
  144. var _n = true;
  145. var _d = false;
  146. var _e = undefined;
  147. try {
  148. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  149. _arr.push(_s.value);
  150. if (i && _arr.length === i) break;
  151. }
  152. } catch (err) {
  153. _d = true;
  154. _e = err;
  155. } finally {
  156. try {
  157. if (!_n && _i["return"] != null) _i["return"]();
  158. } finally {
  159. if (_d) throw _e;
  160. }
  161. }
  162. return _arr;
  163. }
  164. function _unsupportedIterableToArray(o, minLen) {
  165. if (!o) return;
  166. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  167. var n = Object.prototype.toString.call(o).slice(8, -1);
  168. if (n === "Object" && o.constructor) n = o.constructor.name;
  169. if (n === "Map" || n === "Set") return Array.from(o);
  170. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  171. }
  172. function _arrayLikeToArray(arr, len) {
  173. if (len == null || len > arr.length) len = arr.length;
  174. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  175. return arr2;
  176. }
  177. function _nonIterableRest() {
  178. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  179. }
  180. function _await(value, then, direct) {
  181. if (direct) {
  182. return then ? then(value) : value;
  183. }
  184. if (!value || !value.then) {
  185. value = Promise.resolve(value);
  186. }
  187. return then ? value.then(then) : value;
  188. }
  189. var FETCH_TIMEOUT = 3000;
  190. function _catch(body, recover) {
  191. try {
  192. var result = body();
  193. } catch (e) {
  194. return recover(e);
  195. }
  196. if (result && result.then) {
  197. return result.then(void 0, recover);
  198. }
  199. return result;
  200. }
  201. var fetchJson = _async(function (url) {
  202. return _catch(function () {
  203. return _await(global.fetch("".concat(url, ".json"), {
  204. timeout: FETCH_TIMEOUT
  205. }), function (_global$fetch) {
  206. return _global$fetch.json();
  207. });
  208. }, function (e) {
  209. report(e);
  210. reportAndThrowError("Could not fetch ".concat(url, ".json"));
  211. });
  212. });
  213. function _async(f) {
  214. return function () {
  215. for (var args = [], i = 0; i < arguments.length; i++) {
  216. args[i] = arguments[i];
  217. }
  218. try {
  219. return Promise.resolve(f.apply(this, args));
  220. } catch (e) {
  221. return Promise.reject(e);
  222. }
  223. };
  224. }
  225. var fetchStats = _async(function (collectiveUrl) {
  226. return _catch(function () {
  227. return _await(fetchJson(collectiveUrl));
  228. }, function (e) {
  229. report(e);
  230. report("Could not load the stats for ".concat(collectiveSlugFromUrl(collectiveUrl)));
  231. });
  232. });
  233. var fetchLogo = _async(function (logoUrl) {
  234. if (!logoUrl) {
  235. // Silent return if no logo has been provided
  236. return;
  237. }
  238. if (!logoUrl.match(/^https?:\/\//)) {
  239. reportAndThrowError("Your logo URL isn't well-formatted - ".concat(logoUrl));
  240. }
  241. return _catch(function () {
  242. return _await(global.fetch(logoUrl, {
  243. timeout: FETCH_TIMEOUT
  244. }), function (res) {
  245. if (isLogoResponseWellFormatted(res)) {
  246. return res.text();
  247. }
  248. report("Error while fetching logo from ".concat(logoUrl, ". The response wasn't well-formatted"));
  249. });
  250. }, function () {
  251. report("Error while fetching logo from ".concat(logoUrl));
  252. });
  253. });
  254. var isLogoResponseWellFormatted = function isLogoResponseWellFormatted(res) {
  255. return res.status === 200 && res.headers.get('content-type').match(/^text\/plain/);
  256. };
  257. var fetchPkg = function fetchPkg(pathToPkg) {
  258. var fullPathToPkg = path__default['default'].resolve("".concat(pathToPkg, "/package.json"));
  259. try {
  260. return JSON.parse(fs__default['default'].readFileSync(fullPathToPkg, 'utf8'));
  261. } catch (e) {
  262. reportAndThrowError("Could not find package.json at ".concat(fullPathToPkg));
  263. }
  264. };
  265. function _await$1(value, then, direct) {
  266. if (direct) {
  267. return then ? then(value) : value;
  268. }
  269. if (!value || !value.then) {
  270. value = Promise.resolve(value);
  271. }
  272. return then ? value.then(then) : value;
  273. }
  274. function _async$1(f) {
  275. return function () {
  276. for (var args = [], i = 0; i < arguments.length; i++) {
  277. args[i] = arguments[i];
  278. }
  279. try {
  280. return Promise.resolve(f.apply(this, args));
  281. } catch (e) {
  282. return Promise.reject(e);
  283. }
  284. };
  285. }
  286. var collectiveSlugFromUrl = function collectiveSlugFromUrl(url) {
  287. return url.substr(url.lastIndexOf('/') + 1).toLowerCase().replace(/\.json/g, '');
  288. };
  289. var collectiveUrl = function collectiveUrl(pkg) {
  290. var url = pkg.collective && pkg.collective.url;
  291. if (!url) {
  292. reportAndThrowError('No collective URL set!');
  293. }
  294. return stripTrailingSlash(url);
  295. }; // use pkg.collective.logo for "legacy"/compatibility reasons
  296. var collectiveLogoUrl = function collectiveLogoUrl(pkg) {
  297. return pkg.collective.logo || pkg.collective.logoUrl || false;
  298. };
  299. var collectiveDonationText = function collectiveDonationText(pkg) {
  300. return pkg.collective.donation && pkg.collective.donation.text || 'Donate:';
  301. };
  302. var getCollective = _async$1(function (pkgPath) {
  303. var pkg = fetchPkg(pkgPath);
  304. var url = collectiveUrl(pkg);
  305. var baseCollective = {
  306. url: url,
  307. slug: collectiveSlugFromUrl(url),
  308. logoUrl: collectiveLogoUrl(pkg),
  309. donationUrl: collectiveDonationUrl(pkg),
  310. donationText: collectiveDonationText(pkg)
  311. };
  312. var logoUrl = baseCollective.logoUrl;
  313. var promises = [fetchStats(url)].concat(logoUrl ? fetchLogo(logoUrl) : []);
  314. return _await$1(Promise.all(promises), function (_ref) {
  315. var _ref2 = _slicedToArray(_ref, 2),
  316. stats = _ref2[0],
  317. logo = _ref2[1];
  318. return Object.assign(baseCollective, {
  319. stats: stats,
  320. logo: logo
  321. });
  322. });
  323. });
  324. var collectiveDonationUrl = function collectiveDonationUrl(pkg) {
  325. var defaultDonationAmount = pkg.collective.donation && pkg.collective.donation.amount;
  326. var donateUrl = "".concat(collectiveUrl(pkg), "/").concat(retrieveDonationSlug(pkg));
  327. if (defaultDonationAmount) {
  328. return "".concat(donateUrl, "/").concat(defaultDonationAmount);
  329. }
  330. return donateUrl;
  331. };
  332. var retrieveDonationSlug = function retrieveDonationSlug(pkg) {
  333. var rawDonationSlug = pkg.collective.donation && pkg.collective.donation.slug;
  334. if (!rawDonationSlug) {
  335. return 'donate';
  336. }
  337. return stripLeadingSlash(rawDonationSlug);
  338. };
  339. function _await$2(value, then, direct) {
  340. if (direct) {
  341. return then ? then(value) : value;
  342. }
  343. if (!value || !value.then) {
  344. value = Promise.resolve(value);
  345. }
  346. return then ? value.then(then) : value;
  347. }
  348. function _async$2(f) {
  349. return function () {
  350. for (var args = [], i = 0; i < arguments.length; i++) {
  351. args[i] = arguments[i];
  352. }
  353. try {
  354. return Promise.resolve(f.apply(this, args));
  355. } catch (e) {
  356. return Promise.reject(e);
  357. }
  358. };
  359. }
  360. var init = _async$2(function (path, hide) {
  361. if (hide === undefined) hide = hideMessage();
  362. if (hide) {
  363. return;
  364. }
  365. global.fetch = global.fetch || fetch__default['default'];
  366. return _await$2(getCollective(path), function (collective) {
  367. printLogo(collective.logo);
  368. printFooter(collective);
  369. });
  370. });
  371. exports.init = init;