@blocklet/cli 1.16.33 → 1.16.34-beta-20241120-080738-bbbe036c

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.
Files changed (87) hide show
  1. package/README.md +32 -25
  2. package/bin/blocklet.js +292 -1
  3. package/config.example.yml +33 -0
  4. package/lib/arcblock.js +53 -0
  5. package/lib/commands/blocklet/add.js +124 -0
  6. package/lib/commands/blocklet/assets/git-ignore +28 -0
  7. package/lib/commands/blocklet/assets/index.html +9 -0
  8. package/lib/commands/blocklet/assets/index.js +14 -0
  9. package/lib/commands/blocklet/assets/logo.png +0 -0
  10. package/lib/commands/blocklet/bundle/bundle.js +184 -0
  11. package/lib/commands/blocklet/bundle/bundlers/blocklet.js +138 -0
  12. package/lib/commands/blocklet/bundle/bundlers/changelog.js +100 -0
  13. package/lib/commands/blocklet/bundle/bundlers/logo.js +56 -0
  14. package/lib/commands/blocklet/bundle/bundlers/markdown.js +241 -0
  15. package/lib/commands/blocklet/bundle/bundlers/preference.js +50 -0
  16. package/lib/commands/blocklet/bundle/bundlers/readme.js +43 -0
  17. package/lib/commands/blocklet/bundle/bundlers/screenshots.js +94 -0
  18. package/lib/commands/blocklet/bundle/bundlers/simple.js +70 -0
  19. package/lib/commands/blocklet/bundle/compact/bundle-compact-file.js +48 -0
  20. package/lib/commands/blocklet/bundle/compact/bundle-merge-extra.js +66 -0
  21. package/lib/commands/blocklet/bundle/compact/default-external.js +5 -0
  22. package/lib/commands/blocklet/bundle/compact/index.js +88 -0
  23. package/lib/commands/blocklet/bundle/index.js +139 -0
  24. package/lib/commands/blocklet/bundle/pack.js +8 -0
  25. package/lib/commands/blocklet/bundle/parse-external-dependencies.js +97 -0
  26. package/lib/commands/blocklet/bundle/simple/index.js +62 -0
  27. package/lib/commands/blocklet/bundle/zip/archive.js +35 -0
  28. package/lib/commands/blocklet/bundle/zip/dependencies.js +333 -0
  29. package/lib/commands/blocklet/bundle/zip/index.js +165 -0
  30. package/lib/commands/blocklet/bundle/zip/main.js +124 -0
  31. package/lib/commands/blocklet/bundle/zip/node.js +59 -0
  32. package/lib/commands/blocklet/bundle/zip/resolve.js +93 -0
  33. package/lib/commands/blocklet/cleanup.js +52 -0
  34. package/lib/commands/blocklet/config.js +108 -0
  35. package/lib/commands/blocklet/connect.js +87 -0
  36. package/lib/commands/blocklet/create.js +38 -0
  37. package/lib/commands/blocklet/deploy.js +435 -0
  38. package/lib/commands/blocklet/dev.js +1000 -0
  39. package/lib/commands/blocklet/document.js +39 -0
  40. package/lib/commands/blocklet/exec.js +106 -0
  41. package/lib/commands/blocklet/init.js +300 -0
  42. package/lib/commands/blocklet/meta.js +22 -0
  43. package/lib/commands/blocklet/remove.js +35 -0
  44. package/lib/commands/blocklet/test.js +201 -0
  45. package/lib/commands/blocklet/upload.js +105 -0
  46. package/lib/commands/blocklet/version.js +81 -0
  47. package/lib/commands/server/cleanup.js +32 -0
  48. package/lib/commands/server/command.js +131 -0
  49. package/lib/commands/server/info.js +92 -0
  50. package/lib/commands/server/init.js +433 -0
  51. package/lib/commands/server/logs.js +99 -0
  52. package/lib/commands/server/rescue.js +71 -0
  53. package/lib/commands/server/start.js +821 -0
  54. package/lib/commands/server/status.js +107 -0
  55. package/lib/commands/server/stop.js +163 -0
  56. package/lib/commands/server/upgrade.js +123 -0
  57. package/lib/constant.js +21 -2
  58. package/lib/debug.js +20 -0
  59. package/lib/manager/config.js +122 -0
  60. package/lib/manager/deploy.js +75 -0
  61. package/lib/manager/index.js +23 -0
  62. package/lib/manager/process.js +47 -0
  63. package/lib/node.js +214 -0
  64. package/lib/port.js +19 -0
  65. package/lib/postinstall.js +3 -0
  66. package/lib/process/daemon.js +196 -0
  67. package/lib/process/service.js +86 -0
  68. package/lib/ui.js +137 -0
  69. package/lib/util/blocklet/config.js +78 -0
  70. package/lib/util/blocklet/env.js +172 -0
  71. package/lib/util/blocklet/meta.js +36 -0
  72. package/lib/util/blocklet/payment.js +88 -0
  73. package/lib/util/blocklet/sign.js +21 -0
  74. package/lib/util/blocklet/tar.js +119 -0
  75. package/lib/util/convert-to-nosources-sourcemap.js +37 -0
  76. package/lib/util/docker-status-log.js +17 -0
  77. package/lib/util/exit-when-server-stopped.js +44 -0
  78. package/lib/util/get-cli-binary-name.js +8 -0
  79. package/lib/util/get-download-bundle-step.js +36 -0
  80. package/lib/util/get-service-instance-number.js +12 -0
  81. package/lib/util/index.js +626 -0
  82. package/lib/util/print-error.js +11 -0
  83. package/lib/util/print.js +9 -0
  84. package/lib/util/what-uri.js +40 -0
  85. package/package.json +123 -27
  86. package/lib/run.d.ts +0 -2
  87. package/lib/run.js +0 -73
@@ -0,0 +1,78 @@
1
+ /* eslint-disable no-underscore-dangle */
2
+ const fs = require('fs-extra');
3
+ const ini = require('ini');
4
+ const get = require('lodash/get');
5
+
6
+ class Config {
7
+ constructor({ configFile, section } = {}) {
8
+ if (!configFile) {
9
+ throw new Error('configFile argument is required');
10
+ }
11
+
12
+ fs.ensureFileSync(configFile);
13
+ this.configFile = configFile;
14
+
15
+ this.config = ini.parse(fs.readFileSync(configFile).toString());
16
+ this.section = section;
17
+ }
18
+
19
+ set(key, value) {
20
+ if (this.section) {
21
+ this.config[this.section] = this.config[this.section] === undefined ? {} : this.config[this.section];
22
+ this.config[this.section][key] = value;
23
+ } else {
24
+ this.config[key] = value;
25
+ }
26
+
27
+ this._write();
28
+ }
29
+
30
+ unset(key) {
31
+ if (this.section) {
32
+ delete this.config[this.section][key];
33
+ } else {
34
+ delete this.config[key];
35
+ }
36
+ this._write();
37
+ }
38
+
39
+ get(key, defaultValue) {
40
+ // TODO: 是否需要保护一些关键信息(例如 secretKey)
41
+ return this._get(key, defaultValue);
42
+ }
43
+
44
+ setSection(section) {
45
+ this.section = section;
46
+ }
47
+
48
+ _write() {
49
+ fs.writeFileSync(this.configFile, ini.stringify(this.config));
50
+ }
51
+
52
+ _get(key, defaultValue) {
53
+ let result = this.config;
54
+ if (this.section) {
55
+ result = result[this.section];
56
+ }
57
+
58
+ if (!key) {
59
+ return result;
60
+ }
61
+
62
+ return get(result, key, defaultValue);
63
+ }
64
+ }
65
+
66
+ Config.stringify = (value) => {
67
+ if (typeof value === 'string') {
68
+ return value;
69
+ }
70
+
71
+ if (typeof value === 'undefined') {
72
+ return undefined;
73
+ }
74
+
75
+ return ini.stringify(value);
76
+ };
77
+
78
+ module.exports = Config;
@@ -0,0 +1,172 @@
1
+ const fs = require('fs');
2
+ const chalk = require('chalk');
3
+ const inquirer = require('inquirer');
4
+ const dotenv = require('dotenv-flow');
5
+ const mask = require('maskdata');
6
+ const uniqBy = require('lodash/uniqBy');
7
+ const { CHAIN_INFO_CONFIG } = require('@blocklet/meta/lib/constants');
8
+ const { forEachBlockletSync, getComponentName, getComponentMissingConfigs } = require('@blocklet/meta/lib/util');
9
+
10
+ const { print, printInfo } = require('../index');
11
+
12
+ const askQuestions = (requiredEnvs) => {
13
+ const questions = requiredEnvs.map((env) => ({
14
+ type: 'text',
15
+ name: env.name,
16
+ message: `Please input ${env.name}`,
17
+ validate: (v) => (v ? true : `${env.name} is required`),
18
+ }));
19
+
20
+ return inquirer.prompt(questions);
21
+ };
22
+
23
+ const mergeBlockletConfigEntry = (blocklet, key, value, result, id, ancestors, skipUnknown = true) => {
24
+ let configEntry;
25
+ const envConfig = (blocklet.meta.environments || []).find((x) => x.name === key);
26
+ if (envConfig) {
27
+ configEntry = { ...envConfig, key, value };
28
+ delete configEntry.name;
29
+ } else if (skipUnknown === false) {
30
+ configEntry = { key, value, required: false, shared: true, custom: true };
31
+ }
32
+
33
+ if (configEntry) {
34
+ if (!result[id]) {
35
+ result[id] = {
36
+ name: getComponentName(blocklet, ancestors),
37
+ did: [...ancestors.map((y) => y.meta.did), blocklet.meta.did],
38
+ configs: [configEntry],
39
+ };
40
+ } else {
41
+ const index = result[id].configs.findIndex((x) => x.key === key);
42
+ if (index >= 0) {
43
+ result[id].configs[index].value = value;
44
+ } else {
45
+ result[id].configs.push(configEntry);
46
+ }
47
+ }
48
+ }
49
+ };
50
+
51
+ const getMetaDefinedEnv = (blocklet) => {
52
+ const env = {};
53
+
54
+ // only read env in blocklet.meta.environments.
55
+ const environments = blocklet && blocklet.meta && blocklet.meta.environments;
56
+ if (Array.isArray(environments)) {
57
+ environments.forEach((item) => {
58
+ if (process.env[item.name]) {
59
+ env[item.name] = process.env[item.name];
60
+ }
61
+ });
62
+ }
63
+
64
+ return env;
65
+ };
66
+
67
+ const ensureBlockletEnv = async (node, blocklet, dir) => {
68
+ const envFiles = dotenv.listFiles(dir, { node_env: 'development' });
69
+ let env = {};
70
+ envFiles.forEach((x) => {
71
+ if (fs.existsSync(x)) {
72
+ env = Object.assign(env, dotenv.parse(x));
73
+ }
74
+ });
75
+
76
+ Object.assign(env, getMetaDefinedEnv(blocklet));
77
+
78
+ // merge blocklet.yml config from dotenv files
79
+ const pickedEnvs = Object.entries(env).reduce((obj, [key, value]) => {
80
+ forEachBlockletSync(blocklet, (b, { id, ancestors }) => {
81
+ mergeBlockletConfigEntry(b, key, value, obj, id, ancestors, true);
82
+ });
83
+ return obj;
84
+ }, {});
85
+
86
+ // merge chainInfo config from dotenv files
87
+ Object.entries(CHAIN_INFO_CONFIG).forEach(([key, [, value]]) => {
88
+ if (typeof env[key] === 'undefined') return;
89
+ mergeBlockletConfigEntry(blocklet, key, env[key] || value, pickedEnvs, blocklet.meta.did, [], false);
90
+ });
91
+
92
+ if (Object.keys(pickedEnvs).length) {
93
+ print('');
94
+ printInfo(`Use the values from ${chalk.cyan('.env[.development][.local]')} as environment variables\n`);
95
+ for (const { name, configs } of Object.values(pickedEnvs)) {
96
+ print(`${name}:`);
97
+ configs.forEach((f) => print(`- ${f.key}: ${chalk.cyan(f.secure ? mask.maskPassword(f.value) : f.value)}`));
98
+ print('\n');
99
+ }
100
+
101
+ for (const { did, configs } of Object.values(pickedEnvs)) {
102
+ // eslint-disable-next-line no-await-in-loop
103
+ await node.configBlocklet({ did, configs });
104
+ }
105
+ }
106
+
107
+ const requiredEnvs = {};
108
+ forEachBlockletSync(blocklet, (b, { id, ancestors }) => {
109
+ const envs = getComponentMissingConfigs(b, ancestors[0])
110
+ .map((x) => {
111
+ const o = (b.meta.environments || []).find((y) => y.name === x.key);
112
+ return o;
113
+ })
114
+ .filter(Boolean)
115
+ .filter((d) => !Object.prototype.hasOwnProperty.call(env, d.name));
116
+ if (envs.length) {
117
+ requiredEnvs[id] = {
118
+ name: getComponentName(b, ancestors),
119
+ did: [...ancestors.map((y) => y.meta.did), b.meta.did],
120
+ envs,
121
+ };
122
+ }
123
+ });
124
+
125
+ if (Object.keys(requiredEnvs).length) {
126
+ const questions = uniqBy(
127
+ Object.values(requiredEnvs)
128
+ .map((x) => x.envs)
129
+ .flat(),
130
+ 'name'
131
+ );
132
+ printInfo('Missing following required configuration to continue\n');
133
+ questions.forEach((f) => print('-', f.name));
134
+ print('');
135
+ const answers = await askQuestions(questions);
136
+
137
+ if (Object.entries(requiredEnvs).length) {
138
+ print('');
139
+ printInfo('Use the values as environment variables\n');
140
+ }
141
+ for (const [, { name, did, envs }] of Object.entries(requiredEnvs)) {
142
+ const configs = Object.entries(answers)
143
+ .map(([key, value]) => {
144
+ const envConfig = envs.find((x) => x.name === key);
145
+ if (!envConfig) {
146
+ return null;
147
+ }
148
+ const config = {
149
+ ...envConfig,
150
+ key,
151
+ value,
152
+ };
153
+ delete config.name;
154
+ return config;
155
+ })
156
+ .filter(Boolean);
157
+
158
+ print(`${name}:`);
159
+ configs.forEach((f) => print(`- ${f.key}: ${chalk.cyan(f.value)}`));
160
+ print('\n');
161
+
162
+ // eslint-disable-next-line no-await-in-loop
163
+ await node.configBlocklet({
164
+ did,
165
+ configs,
166
+ });
167
+ }
168
+ }
169
+ };
170
+
171
+ module.exports = ensureBlockletEnv;
172
+ module.exports.mergeBlockletConfigEntry = mergeBlockletConfigEntry;
@@ -0,0 +1,36 @@
1
+ const chalk = require('chalk');
2
+ const cloneDeep = require('lodash/cloneDeep');
3
+ const { parseComponents } = require('@blocklet/resolver');
4
+ const formatError = require('@abtnode/util/lib/format-error');
5
+
6
+ const { printSuccess, printError, printInfo } = require('../index');
7
+
8
+ const fixComponents = (meta) => {
9
+ if (meta.children) {
10
+ meta.components = meta.children;
11
+ delete meta.children;
12
+ }
13
+ };
14
+
15
+ const checkCircularDependencies = async (meta) => {
16
+ try {
17
+ const cloneMeta = cloneDeep(meta);
18
+ await parseComponents(
19
+ { meta: cloneMeta },
20
+ { didKey: 'did', ancestors: [{ meta: cloneMeta }] },
21
+ { logger: { error: printError, info: printInfo } }
22
+ );
23
+ printSuccess('Blocklet components verify success!');
24
+ } catch (err) {
25
+ printError(`Blocklet components verify failed: ${chalk.red(formatError(err))}`);
26
+ if (process.env.DEBUG) {
27
+ console.error(err);
28
+ }
29
+ process.exit(1);
30
+ }
31
+ };
32
+
33
+ module.exports = {
34
+ fixComponents,
35
+ checkCircularDependencies,
36
+ };
@@ -0,0 +1,88 @@
1
+ /* eslint-disable no-await-in-loop */
2
+ const { joinURL } = require('ufo');
3
+ const cloneDeep = require('lodash/cloneDeep');
4
+ const get = require('lodash/get');
5
+ const Client = require('@ocap/client');
6
+ const axios = require('@abtnode/util/lib/axios');
7
+ const { BLOCKLET_STORE_META_PATH } = require('@abtnode/constant');
8
+ const { BLOCKLET_FACTORY_SHARES } = require('@blocklet/constant');
9
+ const { createNftFactoryItx } = require('@blocklet/meta/lib/payment/v2');
10
+
11
+ const debug = require('debug')('@blocklet/cli');
12
+
13
+ const getStoreInfo = async (url) => {
14
+ const { data } = await axios.get(joinURL(url, BLOCKLET_STORE_META_PATH), { timeout: 20 * 1000 });
15
+ return data;
16
+ };
17
+
18
+ const isValidChainEndpoint = async (endpoint) => {
19
+ if (!endpoint) {
20
+ return false;
21
+ }
22
+
23
+ const client = new Client(endpoint);
24
+ try {
25
+ const { info } = await client.getChainInfo();
26
+ if (info.consensusVersion.split(' ').length === 2) {
27
+ return client;
28
+ }
29
+
30
+ return false;
31
+ } catch (err) {
32
+ return false;
33
+ }
34
+ };
35
+
36
+ const getShare = async ({ meta, storeUrl, developerDid }) => {
37
+ const info = await getStoreInfo(storeUrl);
38
+
39
+ const shares = cloneDeep(get(meta, 'payment.share', []));
40
+ if (shares.length === 0) {
41
+ shares.push({
42
+ name: 'developer',
43
+ address: developerDid,
44
+ value: BLOCKLET_FACTORY_SHARES.developer,
45
+ });
46
+ }
47
+ if (!shares.find((x) => x.address === info.id)) {
48
+ shares.push({
49
+ name: 'store',
50
+ address: info.id,
51
+ value: BLOCKLET_FACTORY_SHARES.store,
52
+ });
53
+ }
54
+
55
+ return shares;
56
+ };
57
+
58
+ /**
59
+ * Ensure NFT factory exists for paid blocklets, the process must be deterministic.
60
+ * If user changed the name/title of the blocklet, then a new factory will be created
61
+ */
62
+ const ensureBlockletNftFactory = async ({ meta, storeUrl }) => {
63
+ const info = await getStoreInfo(storeUrl);
64
+ const endpoint = info.chainHost;
65
+
66
+ const ocapClient = await isValidChainEndpoint(endpoint);
67
+ if (ocapClient === false) {
68
+ throw new Error('Invalid chain endpoint fetched from store, please contact store administrator to fix');
69
+ }
70
+
71
+ // create factory nft itx
72
+ const { itx } = await createNftFactoryItx({
73
+ blockletMeta: meta,
74
+ ocapClient,
75
+ issuers: [info.id],
76
+ storeUrl,
77
+ });
78
+
79
+ debug('factory itx', itx);
80
+
81
+ return itx.address;
82
+ };
83
+
84
+ module.exports = {
85
+ isValidChainEndpoint,
86
+ ensureBlockletNftFactory,
87
+ getShare,
88
+ };
@@ -0,0 +1,21 @@
1
+ const { toBase58 } = require('@ocap/util');
2
+ const stableStringify = require('json-stable-stringify');
3
+
4
+ const sign = (blockletMeta, wallet) => {
5
+ const walletJSON = wallet.toJSON();
6
+
7
+ const signatureData = {
8
+ type: walletJSON.type.pk,
9
+ name: blockletMeta.name,
10
+ signer: walletJSON.address,
11
+ pk: toBase58(walletJSON.pk),
12
+ created: new Date().toISOString(),
13
+ };
14
+
15
+ const signature = wallet.sign(stableStringify({ ...blockletMeta, signatures: [signatureData] }));
16
+ signatureData.sig = toBase58(signature);
17
+
18
+ return signatureData;
19
+ };
20
+
21
+ module.exports = { sign };
@@ -0,0 +1,119 @@
1
+ const fs = require('fs-extra');
2
+ const tar = require('tar');
3
+ const byteSize = require('byte-size');
4
+ const columnify = require('columnify');
5
+
6
+ // eslint-disable-next-line no-console
7
+ const logger = { notice: console.log };
8
+
9
+ const logTar = (tarball, opts = {}) => {
10
+ const { unicode = true, log = logger } = opts;
11
+ log.notice('');
12
+ log.notice(`${unicode ? '📦 ' : 'bundle:'} ${tarball.name}@${tarball.version}`);
13
+ log.notice('=== Tarball Contents ===');
14
+ if (tarball.files.length) {
15
+ log.notice(
16
+ columnify(
17
+ tarball.files
18
+ .map((f) => {
19
+ const bytes = byteSize(f.size);
20
+ return /^node_modules\//.test(f.path) ? null : { path: f.path, size: `${bytes.value}${bytes.unit}` };
21
+ })
22
+ .filter((f) => f),
23
+ {
24
+ include: ['size', 'path'],
25
+ showHeaders: false,
26
+ }
27
+ )
28
+ );
29
+ }
30
+ if (tarball.bundled.length) {
31
+ log.notice('=== Bundled Dependencies ===');
32
+ tarball.bundled.forEach((name) => log.notice('', name));
33
+ }
34
+ log.notice('=== Tarball Details ===');
35
+ log.notice(
36
+ columnify(
37
+ [
38
+ { name: 'name:', value: tarball.name },
39
+ { name: 'version:', value: tarball.version },
40
+ tarball.filename && { name: 'filename:', value: tarball.filename },
41
+ { name: 'bundle size:', value: byteSize(tarball.size) },
42
+ { name: 'unpacked size:', value: byteSize(tarball.unpackedSize) },
43
+ { name: 'shasum:', value: tarball.shasum },
44
+ {
45
+ name: 'integrity:',
46
+ value: `${tarball.integrity.toString().substr(0, 20)}[...]${tarball.integrity.toString().substr(80)}`,
47
+ },
48
+ tarball.bundled.length && { name: 'bundled deps:', value: tarball.bundled.length },
49
+ tarball.bundled.length && { name: 'bundled files:', value: tarball.entryCount - tarball.files.length },
50
+ tarball.bundled.length && { name: 'own files:', value: tarball.files.length },
51
+ { name: 'total files:', value: tarball.entryCount },
52
+ ].filter((x) => x),
53
+ {
54
+ include: ['name', 'value'],
55
+ showHeaders: false,
56
+ }
57
+ )
58
+ );
59
+ log.notice('');
60
+ };
61
+
62
+ const getContents = async (meta, tarball) => {
63
+ const files = [];
64
+ const bundled = new Set();
65
+ let totalEntries = 0;
66
+ let totalEntrySize = 0;
67
+
68
+ await tar.list({
69
+ file: tarball,
70
+ sync: true,
71
+ onentry: (entry) => {
72
+ totalEntries++;
73
+ totalEntrySize += entry.size;
74
+ const p = entry.path;
75
+ if (p.startsWith('package/node_modules/')) {
76
+ const name = p.match(/^package\/node_modules\/((?:@[^/]+\/)?[^/]+)/)[1];
77
+ bundled.add(name);
78
+ }
79
+ files.push({
80
+ path: entry.path.replace(/^package\//, ''),
81
+ size: entry.size,
82
+ mode: entry.mode,
83
+ });
84
+ },
85
+ });
86
+
87
+ const comparator = (a, b) =>
88
+ a.path.localeCompare(b.path, undefined, {
89
+ sensitivity: 'case',
90
+ numeric: true,
91
+ });
92
+
93
+ const isUpper = (str) => {
94
+ const ch = str.charAt(0);
95
+ return ch >= 'A' && ch <= 'Z';
96
+ };
97
+
98
+ const uppers = files.filter((file) => isUpper(file.path));
99
+ const others = files.filter((file) => !isUpper(file.path));
100
+
101
+ uppers.sort(comparator);
102
+ others.sort(comparator);
103
+
104
+ return {
105
+ id: `${meta.name}@${meta.version}`,
106
+ name: meta.name,
107
+ version: meta.version,
108
+ size: fs.statSync(tarball).size,
109
+ unpackedSize: totalEntrySize,
110
+ shasum: meta.dist.shasum,
111
+ integrity: meta.dist.integrity,
112
+ filename: meta.dist.tarball,
113
+ files: uppers.concat(others),
114
+ entryCount: totalEntries,
115
+ bundled: Array.from(bundled),
116
+ };
117
+ };
118
+
119
+ module.exports = { logTar, getContents };
@@ -0,0 +1,37 @@
1
+ const fs = require('fs');
2
+ const { SourceMapConsumer, SourceMapGenerator } = require('source-map');
3
+
4
+ async function convertToNoSourcesSourceMap(inputMapPath, outputMapPath) {
5
+ if (!fs.existsSync(inputMapPath)) {
6
+ return;
7
+ }
8
+ const rawSourceMap = JSON.parse(fs.readFileSync(inputMapPath, 'utf8'));
9
+
10
+ const consumer = await new SourceMapConsumer(rawSourceMap);
11
+
12
+ const generator = new SourceMapGenerator({
13
+ file: rawSourceMap.file,
14
+ sourceRoot: rawSourceMap.sourceRoot,
15
+ });
16
+
17
+ consumer.eachMapping((mapping) => {
18
+ generator.addMapping({
19
+ generated: {
20
+ line: mapping.generatedLine,
21
+ column: mapping.generatedColumn,
22
+ },
23
+ source: mapping.source,
24
+ original: mapping.source
25
+ ? {
26
+ line: mapping.originalLine,
27
+ column: mapping.originalColumn,
28
+ }
29
+ : null,
30
+ name: mapping.name,
31
+ });
32
+ });
33
+
34
+ fs.writeFileSync(outputMapPath, JSON.stringify(generator.toJSON()));
35
+ }
36
+
37
+ module.exports = convertToNoSourcesSourceMap;
@@ -0,0 +1,17 @@
1
+ const chalk = require('chalk');
2
+
3
+ function getDockerStatusLog(printInfo, nodeInfo) {
4
+ const { enableDocker, isDockerInstalled } = nodeInfo;
5
+ const unsupportedDockerMsg =
6
+ process.platform === 'darwin'
7
+ ? 'On MacOS, you need to install https://orbstack.dev/ and ensure you have sufficient permissions to run Docker.'
8
+ : 'You need to install Docker and ensure you have sufficient permissions to run it.';
9
+
10
+ printInfo('Docker enabled for running blocklets:', enableDocker ? chalk.green('on') : chalk.green('off'));
11
+ printInfo('Docker installed:', isDockerInstalled ? chalk.green('on') : chalk.green('off'));
12
+ if (!isDockerInstalled) {
13
+ printInfo('Docker installation:', chalk.yellow(unsupportedDockerMsg));
14
+ }
15
+ }
16
+
17
+ module.exports = getDockerStatusLog;
@@ -0,0 +1,44 @@
1
+ const pm2 = require('@abtnode/util/lib/async-pm2');
2
+ const { PROCESS_NAME_DAEMON } = require('@abtnode/constant');
3
+
4
+ const exitWhenServerStopped = () => {
5
+ const isRunning = (name) =>
6
+ new Promise((resolve) => {
7
+ pm2.connect((err) => {
8
+ if (err) {
9
+ pm2.disconnect();
10
+ resolve(false);
11
+ return;
12
+ }
13
+ // eslint-disable-next-line no-shadow
14
+ pm2.describe(name, (err, [info]) => {
15
+ pm2.disconnect();
16
+ if (err) {
17
+ return resolve(false);
18
+ }
19
+ return resolve(!!info);
20
+ });
21
+ });
22
+ });
23
+ const MAX_RETRY = 3;
24
+ const time = 5 * 1000;
25
+ let retry = 0;
26
+ setInterval(async () => {
27
+ let running = false;
28
+ try {
29
+ running = await isRunning(PROCESS_NAME_DAEMON);
30
+ } catch (err) {
31
+ console.error(err);
32
+ }
33
+ if (!running) {
34
+ retry++;
35
+ } else {
36
+ retry = 0;
37
+ }
38
+ if (retry >= MAX_RETRY) {
39
+ process.exit(0);
40
+ }
41
+ }, time);
42
+ };
43
+
44
+ module.exports = exitWhenServerStopped;
@@ -0,0 +1,8 @@
1
+ const path = require('path');
2
+
3
+ const getCLIBinaryName = () => {
4
+ const [, binaryPath] = process.argv;
5
+ return path.basename(binaryPath, path.extname(binaryPath));
6
+ };
7
+
8
+ module.exports = getCLIBinaryName;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @param {Array<{
3
+ * status: 'extracting' | 'downloading';
4
+ * total: number;
5
+ * current: number;
6
+ * name: string; // for extracting
7
+ * component: {
8
+ * title: string
9
+ * }
10
+ * }>} progresses
11
+ * @param {{
12
+ * paddingStart: string
13
+ * }} param1
14
+ * @returns {string}
15
+ */
16
+ const getDownloadBundleStep = (progresses, { paddingStart = '' } = {}) => {
17
+ const lines = (progresses || []).map((progress) => {
18
+ const title = `${progress.status === 'extracting' ? 'Extracting' : 'Downloading'} ${
19
+ progress.component?.title || ''
20
+ }`;
21
+
22
+ const percent =
23
+ progress.total && progress.current ? `: ${Math.floor((progress.current / progress.total) * 100)}%` : '';
24
+
25
+ let name = progress.name ? `: ${progress.name}` : '';
26
+ if (!percent) {
27
+ name += '...';
28
+ }
29
+
30
+ return `${title}${percent}${name}`;
31
+ });
32
+
33
+ return lines.join(`\n${paddingStart}`);
34
+ };
35
+
36
+ module.exports = getDownloadBundleStep;
@@ -0,0 +1,12 @@
1
+ const os = require('os');
2
+
3
+ module.exports = () => {
4
+ // unit: GB
5
+ const memorySize = Math.floor(os.totalmem() / 1024 / 1024 / 1024) || 1;
6
+
7
+ const cpuLength = os.cpus().length || 1;
8
+
9
+ const customConfig = +process.env.ABT_NODE_MAX_CLUSTER_SIZE || Number.MAX_SAFE_INTEGER;
10
+
11
+ return Math.max(Math.min(memorySize, cpuLength, customConfig), 1);
12
+ };