index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  143. if (_i == null) return;
  144. var _arr = [];
  145. var _n = true;
  146. var _d = false;
  147. var _s, _e;
  148. try {
  149. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  150. _arr.push(_s.value);
  151. if (i && _arr.length === i) break;
  152. }
  153. } catch (err) {
  154. _d = true;
  155. _e = err;
  156. } finally {
  157. try {
  158. if (!_n && _i["return"] != null) _i["return"]();
  159. } finally {
  160. if (_d) throw _e;
  161. }
  162. }
  163. return _arr;
  164. }
  165. function _unsupportedIterableToArray(o, minLen) {
  166. if (!o) return;
  167. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  168. var n = Object.prototype.toString.call(o).slice(8, -1);
  169. if (n === "Object" && o.constructor) n = o.constructor.name;
  170. if (n === "Map" || n === "Set") return Array.from(o);
  171. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  172. }
  173. function _arrayLikeToArray(arr, len) {
  174. if (len == null || len > arr.length) len = arr.length;
  175. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  176. return arr2;
  177. }
  178. function _nonIterableRest() {
  179. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  180. }
  181. function _await$2(value, then, direct) {
  182. if (direct) {
  183. return then ? then(value) : value;
  184. }
  185. if (!value || !value.then) {
  186. value = Promise.resolve(value);
  187. }
  188. return then ? value.then(then) : value;
  189. }
  190. var FETCH_TIMEOUT = 3000;
  191. function _catch(body, recover) {
  192. try {
  193. var result = body();
  194. } catch (e) {
  195. return recover(e);
  196. }
  197. if (result && result.then) {
  198. return result.then(void 0, recover);
  199. }
  200. return result;
  201. }
  202. var fetchJson = _async$2(function (url) {
  203. return _catch(function () {
  204. return _await$2(global.fetch("".concat(url, ".json"), {
  205. timeout: FETCH_TIMEOUT
  206. }), function (_global$fetch) {
  207. return _global$fetch.json();
  208. });
  209. }, function (e) {
  210. report(e);
  211. reportAndThrowError("Could not fetch ".concat(url, ".json"));
  212. });
  213. });
  214. function _async$2(f) {
  215. return function () {
  216. for (var args = [], i = 0; i < arguments.length; i++) {
  217. args[i] = arguments[i];
  218. }
  219. try {
  220. return Promise.resolve(f.apply(this, args));
  221. } catch (e) {
  222. return Promise.reject(e);
  223. }
  224. };
  225. }
  226. var fetchStats = _async$2(function (collectiveUrl) {
  227. return _catch(function () {
  228. return _await$2(fetchJson(collectiveUrl));
  229. }, function (e) {
  230. report(e);
  231. report("Could not load the stats for ".concat(collectiveSlugFromUrl(collectiveUrl)));
  232. });
  233. });
  234. var fetchLogo = _async$2(function (logoUrl) {
  235. if (!logoUrl) {
  236. // Silent return if no logo has been provided
  237. return;
  238. }
  239. if (!logoUrl.match(/^https?:\/\//)) {
  240. reportAndThrowError("Your logo URL isn't well-formatted - ".concat(logoUrl));
  241. }
  242. return _catch(function () {
  243. return _await$2(global.fetch(logoUrl, {
  244. timeout: FETCH_TIMEOUT
  245. }), function (res) {
  246. if (isLogoResponseWellFormatted(res)) {
  247. return res.text();
  248. }
  249. report("Error while fetching logo from ".concat(logoUrl, ". The response wasn't well-formatted"));
  250. });
  251. }, function () {
  252. report("Error while fetching logo from ".concat(logoUrl));
  253. });
  254. });
  255. var isLogoResponseWellFormatted = function isLogoResponseWellFormatted(res) {
  256. return res.status === 200 && res.headers.get('content-type').match(/^text\/plain/);
  257. };
  258. var fetchPkg = function fetchPkg(pathToPkg) {
  259. var fullPathToPkg = path__default["default"].resolve("".concat(pathToPkg, "/package.json"));
  260. try {
  261. return JSON.parse(fs__default["default"].readFileSync(fullPathToPkg, 'utf8'));
  262. } catch (e) {
  263. reportAndThrowError("Could not find package.json at ".concat(fullPathToPkg));
  264. }
  265. };
  266. function _await$1(value, then, direct) {
  267. if (direct) {
  268. return then ? then(value) : value;
  269. }
  270. if (!value || !value.then) {
  271. value = Promise.resolve(value);
  272. }
  273. return then ? value.then(then) : value;
  274. }
  275. function _async$1(f) {
  276. return function () {
  277. for (var args = [], i = 0; i < arguments.length; i++) {
  278. args[i] = arguments[i];
  279. }
  280. try {
  281. return Promise.resolve(f.apply(this, args));
  282. } catch (e) {
  283. return Promise.reject(e);
  284. }
  285. };
  286. }
  287. var collectiveSlugFromUrl = function collectiveSlugFromUrl(url) {
  288. return url.substr(url.lastIndexOf('/') + 1).toLowerCase().replace(/\.json/g, '');
  289. };
  290. var collectiveUrl = function collectiveUrl(pkg) {
  291. var url = pkg.collective && pkg.collective.url;
  292. if (!url) {
  293. reportAndThrowError('No collective URL set!');
  294. }
  295. return stripTrailingSlash(url);
  296. }; // use pkg.collective.logo for "legacy"/compatibility reasons
  297. var collectiveLogoUrl = function collectiveLogoUrl(pkg) {
  298. return pkg.collective.logo || pkg.collective.logoUrl || false;
  299. };
  300. var collectiveDonationText = function collectiveDonationText(pkg) {
  301. return pkg.collective.donation && pkg.collective.donation.text || 'Donate:';
  302. };
  303. var getCollective = _async$1(function (pkgPath) {
  304. var pkg = fetchPkg(pkgPath);
  305. var url = collectiveUrl(pkg);
  306. var baseCollective = {
  307. url: url,
  308. slug: collectiveSlugFromUrl(url),
  309. logoUrl: collectiveLogoUrl(pkg),
  310. donationUrl: collectiveDonationUrl(pkg),
  311. donationText: collectiveDonationText(pkg)
  312. };
  313. var logoUrl = baseCollective.logoUrl;
  314. var promises = [fetchStats(url)].concat(logoUrl ? fetchLogo(logoUrl) : []);
  315. return _await$1(Promise.all(promises), function (_ref) {
  316. var _ref2 = _slicedToArray(_ref, 2),
  317. stats = _ref2[0],
  318. logo = _ref2[1];
  319. return Object.assign(baseCollective, {
  320. stats: stats,
  321. logo: logo
  322. });
  323. });
  324. });
  325. var collectiveDonationUrl = function collectiveDonationUrl(pkg) {
  326. var defaultDonationAmount = pkg.collective.donation && pkg.collective.donation.amount;
  327. var donateUrl = "".concat(collectiveUrl(pkg), "/").concat(retrieveDonationSlug(pkg));
  328. if (defaultDonationAmount) {
  329. return "".concat(donateUrl, "/").concat(defaultDonationAmount);
  330. }
  331. return donateUrl;
  332. };
  333. var retrieveDonationSlug = function retrieveDonationSlug(pkg) {
  334. var rawDonationSlug = pkg.collective.donation && pkg.collective.donation.slug;
  335. if (!rawDonationSlug) {
  336. return 'donate';
  337. }
  338. return stripLeadingSlash(rawDonationSlug);
  339. };
  340. function _await(value, then, direct) {
  341. if (direct) {
  342. return then ? then(value) : value;
  343. }
  344. if (!value || !value.then) {
  345. value = Promise.resolve(value);
  346. }
  347. return then ? value.then(then) : value;
  348. }
  349. function _async(f) {
  350. return function () {
  351. for (var args = [], i = 0; i < arguments.length; i++) {
  352. args[i] = arguments[i];
  353. }
  354. try {
  355. return Promise.resolve(f.apply(this, args));
  356. } catch (e) {
  357. return Promise.reject(e);
  358. }
  359. };
  360. }
  361. var init = _async(function (path, hide) {
  362. if (hide === undefined) hide = hideMessage();
  363. if (hide) {
  364. return;
  365. }
  366. global.fetch = global.fetch || fetch__default["default"];
  367. return _await(getCollective(path), function (collective) {
  368. printLogo(collective.logo);
  369. printFooter(collective);
  370. });
  371. });
  372. exports.init = init;