@abtnode/util 1.16.11-beta-0ae58a71 → 1.16.11-beta-f9719c31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,7 +18,7 @@ const getDID = (address) => {
18
18
  return `did:abt:${address}`;
19
19
  };
20
20
 
21
- const update = async ({ id, services, didRegistryUrl, wallet, alsoKnownAs = [] }) => {
21
+ const update = ({ id, services, didRegistryUrl, wallet, alsoKnownAs = [] }) => {
22
22
  debug('update did document', { didRegistryUrl });
23
23
 
24
24
  const did = getDID(wallet.address);
@@ -55,7 +55,7 @@ const update = async ({ id, services, didRegistryUrl, wallet, alsoKnownAs = [] }
55
55
  return axios.post(joinUrl(didRegistryUrl, '/.well-known/did-resolver/registries'), document, { timeout: 10 * 1000 });
56
56
  };
57
57
 
58
- const updateWithRetry = async (...args) => pRetry(() => update(...args), { retries: 3 });
58
+ const updateWithRetry = (...args) => pRetry(() => update(...args), { retries: 3 });
59
59
 
60
60
  const getServerServices = ({ ips, wallet, domain }) => {
61
61
  const records = ips.map((ip) => ({
@@ -93,6 +93,7 @@ const getBlockletServices = ({ appPid, daemonDidDomain, domain }) => {
93
93
  ];
94
94
  };
95
95
 
96
+ // eslint-disable-next-line require-await
96
97
  const updateServerDocument = async ({ ips, wallet, didRegistryUrl, domain }) => {
97
98
  const filteredIps = (ips || []).filter(Boolean);
98
99
  if (filteredIps.length === 0) {
@@ -104,14 +105,7 @@ const updateServerDocument = async ({ ips, wallet, didRegistryUrl, domain }) =>
104
105
  return updateWithRetry({ id: getDID(wallet.address), services, didRegistryUrl, wallet });
105
106
  };
106
107
 
107
- const updateBlockletDocument = async ({
108
- wallet,
109
- didRegistryUrl,
110
- domain,
111
- daemonDidDomain,
112
- appPid,
113
- alsoKnownAs = [],
114
- }) => {
108
+ const updateBlockletDocument = ({ wallet, didRegistryUrl, domain, daemonDidDomain, appPid, alsoKnownAs = [] }) => {
115
109
  const services = getBlockletServices({ appPid, daemonDidDomain, domain });
116
110
  return updateWithRetry({ id: appPid, services, didRegistryUrl, alsoKnownAs, wallet });
117
111
  };
@@ -63,6 +63,7 @@ module.exports = async ({
63
63
  port,
64
64
  timeout = 10 * ONE_SECOND,
65
65
  minConsecutiveTime = (+process.env.ENDPOINT_CONSECUTIVE_TIME || 5) * ONE_SECOND,
66
+ // eslint-disable-next-line require-await
66
67
  }) => {
67
68
  debug('ensure endpoint healthy', { port, minConsecutiveTime });
68
69
 
@@ -3,10 +3,6 @@ const get = require('lodash/get');
3
3
 
4
4
  // Format context: https://github.com/graphql/express-graphql
5
5
  module.exports = (ctx = {}) => {
6
- // 不要更改入参的值,base case
7
- // if (ctx && ctx.user) {
8
- // delete ctx.user.avatar;
9
- // }
10
6
  const contextUser = omit(ctx?.user || {}, 'avatar');
11
7
 
12
8
  const safeGet = (key, _default = '') =>
@@ -0,0 +1,28 @@
1
+ const formatError = (err) => {
2
+ const { details, errors, response } = err;
3
+
4
+ // graphql error
5
+ if (Array.isArray(errors)) {
6
+ return errors.map((x) => x.message).join('\n');
7
+ }
8
+
9
+ // joi validate error
10
+ if (Array.isArray(details)) {
11
+ const formatted = details.map((e) => {
12
+ const errorMessage = e.message.replace(/["]/g, "'");
13
+ const errorPath = e.path.join('.');
14
+ return `${errorPath}: ${errorMessage}`;
15
+ });
16
+
17
+ return `Validate failed: ${formatted.join(';')}`;
18
+ }
19
+
20
+ // axios error
21
+ if (response) {
22
+ return `Request failed: ${response.status} ${response.statusText}: ${JSON.stringify(response.data)}`;
23
+ }
24
+
25
+ return err.message;
26
+ };
27
+
28
+ module.exports = formatError;
@@ -2,8 +2,14 @@ const joinUrl = require('url-join');
2
2
  const Client = require('@ocap/client');
3
3
 
4
4
  // cache ocap clients for smaller memory consumption
5
+ /** @type {Map<string, import('@ocap/client')>} */
5
6
  const clients = new Map();
6
7
 
8
+ /**
9
+ * @description
10
+ * @param {string} chainHost
11
+ * @return {import('@ocap/client')}
12
+ */
7
13
  const getChainClient = (chainHost) => {
8
14
  const endpoint = joinUrl(chainHost, '/');
9
15
  if (!clients.has(endpoint)) {
@@ -5,7 +5,7 @@ const noop = () => {};
5
5
 
6
6
  const getPm2ProcessInfo = (processId, { printError = noop, throwOnNotExist = true } = {}) =>
7
7
  new Promise((resolve, reject) => {
8
- pm2.describe(processId, async (err, [info]) => {
8
+ pm2.describe(processId, (err, [info]) => {
9
9
  if (err) {
10
10
  printError('Failed to get blocklet status from pm2', { error: err });
11
11
  return reject(err);
package/lib/log.js CHANGED
@@ -20,7 +20,7 @@ class StreamLog {
20
20
  * @param {Object} files Object { <level>: <filePath> }
21
21
  * @return {Boolean} if files change
22
22
  */
23
- async setFiles(files) {
23
+ setFiles(files) {
24
24
  if (!isEqual(this._files, files)) {
25
25
  this.clearTails();
26
26
  this._files = files;
@@ -253,7 +253,7 @@ const getDownloadLogFilesFromServer = async ({ dates, nodeInfo, node } = {}) =>
253
253
  return glob(list);
254
254
  };
255
255
 
256
- const getDownloadLogFilesFromBlocklet = async ({ dates, blocklet } = {}) => {
256
+ const getDownloadLogFilesFromBlocklet = ({ dates, blocklet } = {}) => {
257
257
  const logDir = path.join(blocklet.env.logsDir);
258
258
 
259
259
  const list = [];
@@ -11,7 +11,7 @@ const logger = require('@abtnode/logger')('@abtnode/util:logo-middleware');
11
11
  * @param {import('express').NextFunction} next
12
12
  * @returns
13
13
  */
14
- const ensureBlockletExist = async (req, res, next) => {
14
+ const ensureBlockletExist = (req, res, next) => {
15
15
  const { blocklet } = req;
16
16
 
17
17
  if (!blocklet || !get(blocklet, 'env.appDir')) {
@@ -29,7 +29,7 @@ const ensureBlockletExist = async (req, res, next) => {
29
29
  * @param {import('express').NextFunction} next
30
30
  * @returns
31
31
  */
32
- const ensureCustomSquareLogo = async (req, res, next) => {
32
+ const ensureCustomSquareLogo = (req, res, next) => {
33
33
  const { blocklet, sendOptions } = req;
34
34
 
35
35
  /** @type {string} */
@@ -58,7 +58,7 @@ const ensureCustomSquareLogo = async (req, res, next) => {
58
58
  * @param {import('express').NextFunction} next
59
59
  * @returns
60
60
  */
61
- const ensureBundleLogo = async (req, res, next) => {
61
+ const ensureBundleLogo = (req, res, next) => {
62
62
  /**
63
63
  * @type {{
64
64
  * blocklet: import('@abtnode/client').BlockletState, // 目前肯定是不准确的,但是有些属性是通用的,无伤大雅
@@ -85,12 +85,12 @@ const ensureBundleLogo = async (req, res, next) => {
85
85
  * @param {import('express').Response & {sendFallbackLogo: Function} } res
86
86
  * @returns
87
87
  */
88
- const fallbackLogo = async (_req, res) => {
88
+ const fallbackLogo = (_req, res) => {
89
89
  res.sendFallbackLogo();
90
90
  };
91
91
 
92
92
  // eslint-disable-next-line no-unused-vars
93
- const cacheError = async (err, req, res, next) => {
93
+ const cacheError = (err, req, res, next) => {
94
94
  logger.error('failed to send blocklet logo', { url: req.url, error: err });
95
95
  res.sendFallbackLogo();
96
96
  };
@@ -102,7 +102,7 @@ const cacheError = async (err, req, res, next) => {
102
102
  * @param {import('express').NextFunction} next
103
103
  * @returns
104
104
  */
105
- const ensureDefaultLogo = async (req, res, next) => {
105
+ const ensureDefaultLogo = (req, res, next) => {
106
106
  /**
107
107
  * @type {{
108
108
  * blocklet: import('@abtnode/client').BlockletState, // 目前肯定是不准确的,但是有些属性是通用的,无伤大雅
@@ -137,7 +137,7 @@ const ensureDefaultLogo = async (req, res, next) => {
137
137
  * @param {import('express').NextFunction} next
138
138
  * @returns
139
139
  */
140
- const ensureCustomFavicon = async (req, res, next) => {
140
+ const ensureCustomFavicon = (req, res, next) => {
141
141
  /**
142
142
  * @type {{
143
143
  * blocklet: import('@abtnode/client').BlockletState, // 目前肯定是不准确的,但是有些属性是通用的,无伤大雅
package/lib/user.js CHANGED
@@ -5,6 +5,7 @@ const cloneDeep = require('lodash/cloneDeep');
5
5
  const { USER_AVATAR_DIR, USER_AVATAR_URL_PREFIX } = require('@abtnode/constant');
6
6
 
7
7
  const md5 = require('./md5');
8
+ const axios = require('./axios');
8
9
 
9
10
  const getAvatarFile = (dataDir, fileName) =>
10
11
  path.join(dataDir, USER_AVATAR_DIR, fileName.substring(0, 2), fileName.substring(2));
@@ -90,9 +91,40 @@ function updateConnectedAccount(connectedAccounts = [], connectedAccount = {}) {
90
91
  return updated;
91
92
  }
92
93
 
94
+ const getAvatarByUrl = async (url) => {
95
+ try {
96
+ const { data } = await axios.get(url, {
97
+ responseType: 'arraybuffer',
98
+ });
99
+ const base64Content = Buffer.from(data, 'binary').toString('base64');
100
+
101
+ return `data:image/png;base64,${base64Content}`;
102
+ } catch (error) {
103
+ console.error(`Fetch avatar failed: ${url}`, error);
104
+ throw error;
105
+ }
106
+ };
107
+
108
+ const getEmailHash = (email) => md5(email.trim().toLowerCase());
109
+
110
+ const getAvatarByEmail = async (email) => {
111
+ try {
112
+ const emailHash = getEmailHash(email);
113
+ const gravatarUrl = `https://www.gravatar.com/avatar/${emailHash}`;
114
+ const avatarBase64 = await getAvatarByUrl(gravatarUrl);
115
+ return avatarBase64;
116
+ } catch (error) {
117
+ console.error(`Fetch gravatar failed: ${email}`, error);
118
+ return null;
119
+ }
120
+ };
121
+
93
122
  module.exports = {
94
123
  extractUserAvatar,
95
124
  parseUserAvatar,
96
125
  getAvatarFile,
97
126
  updateConnectedAccount,
127
+ getAvatarByUrl,
128
+ getAvatarByEmail,
129
+ getEmailHash,
98
130
  };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.16.11-beta-0ae58a71",
6
+ "version": "1.16.11-beta-f9719c31",
7
7
  "description": "ArcBlock's JavaScript utility",
8
8
  "main": "lib/index.js",
9
9
  "files": [
@@ -18,13 +18,13 @@
18
18
  "author": "polunzh <polunzh@gmail.com> (http://github.com/polunzh)",
19
19
  "license": "Apache-2.0",
20
20
  "dependencies": {
21
- "@abtnode/constant": "1.16.11-beta-0ae58a71",
22
- "@abtnode/logger": "1.16.11-beta-0ae58a71",
23
- "@blocklet/constant": "1.16.11-beta-0ae58a71",
24
- "@ocap/client": "1.18.80",
25
- "@ocap/mcrypto": "1.18.80",
26
- "@ocap/util": "1.18.80",
27
- "@ocap/wallet": "1.18.80",
21
+ "@abtnode/constant": "1.16.11-beta-f9719c31",
22
+ "@abtnode/logger": "1.16.11-beta-f9719c31",
23
+ "@blocklet/constant": "1.16.11-beta-f9719c31",
24
+ "@ocap/client": "1.18.84",
25
+ "@ocap/mcrypto": "1.18.84",
26
+ "@ocap/util": "1.18.84",
27
+ "@ocap/wallet": "1.18.84",
28
28
  "archiver": "^5.3.1",
29
29
  "axios": "^0.27.2",
30
30
  "axios-mock-adapter": "^1.21.2",
@@ -71,5 +71,5 @@
71
71
  "jest": "^27.5.1",
72
72
  "unzipper": "^0.10.11"
73
73
  },
74
- "gitHead": "5d044a08b4399eb855563e670af7cbd0d3851e94"
74
+ "gitHead": "2d88c5df1a414e5b6a8d575984e1940de7573976"
75
75
  }