@acala-network/chopsticks 0.9.1-2 → 0.9.1-3

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 (65) hide show
  1. package/dist/cjs/cli-options.js +30 -15
  2. package/dist/cjs/cli.js +69 -80
  3. package/dist/cjs/context.js +93 -64
  4. package/dist/cjs/index.js +32 -20
  5. package/dist/cjs/logger.js +18 -5
  6. package/dist/cjs/package.json +1 -0
  7. package/dist/cjs/plugins/decode-key/index.js +23 -20
  8. package/dist/cjs/plugins/dry-run/cli.js +46 -41
  9. package/dist/cjs/plugins/dry-run/dry-run-extrinsic.js +37 -21
  10. package/dist/cjs/plugins/dry-run/dry-run-preimage.js +101 -47
  11. package/dist/cjs/plugins/dry-run/index.js +18 -17
  12. package/dist/cjs/plugins/dry-run/rpc.js +48 -74
  13. package/dist/cjs/plugins/follow-chain/index.js +78 -46
  14. package/dist/cjs/plugins/index.js +76 -40
  15. package/dist/cjs/plugins/new-block/index.js +21 -53
  16. package/dist/cjs/plugins/run-block/index.js +145 -104
  17. package/dist/cjs/plugins/set-block-build-mode/index.js +17 -25
  18. package/dist/cjs/plugins/set-head/index.js +13 -23
  19. package/dist/cjs/plugins/set-runtime-log-level/index.js +16 -23
  20. package/dist/cjs/plugins/set-storage/index.js +16 -35
  21. package/dist/cjs/plugins/time-travel/index.js +13 -23
  22. package/dist/cjs/plugins/try-runtime/index.js +51 -42
  23. package/dist/cjs/plugins/types.js +43 -18
  24. package/dist/cjs/rpc/index.js +30 -21
  25. package/dist/cjs/schema/index.js +77 -48
  26. package/dist/cjs/server.js +89 -65
  27. package/dist/cjs/setup-with-server.js +19 -13
  28. package/dist/cjs/types.js +30 -18
  29. package/dist/cjs/utils/decoder.js +32 -16
  30. package/dist/cjs/utils/generate-html-diff.js +38 -19
  31. package/dist/cjs/utils/index.js +20 -19
  32. package/dist/cjs/utils/open-html.js +12 -6
  33. package/dist/cjs/utils/override.js +40 -27
  34. package/dist/cjs/utils/tunnel.js +11 -14
  35. package/dist/esm/cli-options.js +11 -11
  36. package/dist/esm/cli.js +45 -60
  37. package/dist/esm/context.js +20 -24
  38. package/dist/esm/plugins/decode-key/index.js +9 -12
  39. package/dist/esm/plugins/dry-run/cli.js +32 -33
  40. package/dist/esm/plugins/dry-run/dry-run-extrinsic.js +18 -8
  41. package/dist/esm/plugins/dry-run/dry-run-preimage.js +72 -24
  42. package/dist/esm/plugins/dry-run/rpc.js +14 -24
  43. package/dist/esm/plugins/follow-chain/index.js +52 -28
  44. package/dist/esm/plugins/index.js +8 -6
  45. package/dist/esm/plugins/new-block/index.js +8 -9
  46. package/dist/esm/plugins/run-block/index.js +97 -65
  47. package/dist/esm/plugins/set-block-build-mode/index.js +4 -3
  48. package/dist/esm/plugins/set-head/index.js +2 -4
  49. package/dist/esm/plugins/set-runtime-log-level/index.js +4 -3
  50. package/dist/esm/plugins/set-storage/index.js +3 -4
  51. package/dist/esm/plugins/time-travel/index.js +2 -4
  52. package/dist/esm/plugins/try-runtime/index.js +33 -30
  53. package/dist/esm/rpc/index.js +18 -15
  54. package/dist/esm/schema/index.js +31 -18
  55. package/dist/esm/server.js +70 -52
  56. package/dist/esm/setup-with-server.js +3 -3
  57. package/dist/esm/types.js +12 -1
  58. package/dist/esm/utils/decoder.js +12 -4
  59. package/dist/esm/utils/generate-html-diff.js +10 -6
  60. package/dist/esm/utils/open-html.js +1 -1
  61. package/dist/esm/utils/override.js +11 -13
  62. package/dist/esm/utils/tunnel.js +1 -8
  63. package/package.json +13 -17
  64. package/dist/esm/package.json +0 -1
  65. /package/{chopsticks.js → chopsticks.cjs} +0 -0
@@ -1,58 +1,67 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.cli = void 0;
4
- const node_fs_1 = require("node:fs");
5
- const cli_options_1 = require("../../cli-options");
6
- const generate_html_diff_1 = require("../../utils/generate-html-diff");
7
- const open_html_1 = require("../../utils/open-html");
8
- const context_1 = require("../../context");
9
- const cli = (y) => {
10
- y.command('try-runtime', 'Runs runtime upgrade', (yargs) => yargs.options({
11
- ...cli_options_1.defaultOptions,
12
- 'wasm-override': {
13
- desc: 'Path to WASM built with feature `try-runtime` enabled',
14
- string: true,
15
- required: true,
16
- },
17
- 'output-path': {
18
- desc: 'File path to print output',
19
- string: true,
20
- },
21
- html: {
22
- desc: 'Generate html with storage diff',
23
- boolean: true,
24
- },
25
- open: {
26
- desc: 'Open generated html',
27
- boolean: true,
28
- },
29
- }), async (argv) => {
30
- const context = await (0, context_1.setupContext)(argv);
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "cli", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return cli;
9
+ }
10
+ });
11
+ const _nodefs = require("node:fs");
12
+ const _clioptions = require("../../cli-options");
13
+ const _generatehtmldiff = require("../../utils/generate-html-diff");
14
+ const _openhtml = require("../../utils/open-html");
15
+ const _context = require("../../context");
16
+ const cli = (y)=>{
17
+ y.command('try-runtime', 'Runs runtime upgrade', (yargs)=>yargs.options({
18
+ ..._clioptions.defaultOptions,
19
+ 'wasm-override': {
20
+ desc: 'Path to WASM built with feature `try-runtime` enabled',
21
+ string: true,
22
+ required: true
23
+ },
24
+ 'output-path': {
25
+ desc: 'File path to print output',
26
+ string: true
27
+ },
28
+ html: {
29
+ desc: 'Generate html with storage diff',
30
+ boolean: true
31
+ },
32
+ open: {
33
+ desc: 'Open generated html',
34
+ boolean: true
35
+ }
36
+ }), async (argv)=>{
37
+ const context = await (0, _context.setupContext)(argv);
31
38
  const block = context.chain.head;
32
39
  const registry = await block.registry;
33
40
  registry.register({
34
41
  UpgradeCheckSelect: {
35
42
  _enum: {
36
- None: null,
37
- },
38
- },
43
+ None: null
44
+ }
45
+ }
39
46
  });
40
47
  const select_none = registry.createType('UpgradeCheckSelect', 'None');
41
- const result = await block.call('TryRuntime_on_runtime_upgrade', [select_none.toHex()]);
48
+ const result = await block.call('TryRuntime_on_runtime_upgrade', [
49
+ select_none.toHex()
50
+ ]);
42
51
  if (argv.html) {
43
- const filePath = await (0, generate_html_diff_1.generateHtmlDiffPreviewFile)(block, result.storageDiff, block.hash);
52
+ const filePath = await (0, _generatehtmldiff.generateHtmlDiffPreviewFile)(block, result.storageDiff, block.hash);
44
53
  console.log(`Generated preview ${filePath}`);
45
54
  if (argv.open) {
46
- (0, open_html_1.openHtml)(filePath);
55
+ (0, _openhtml.openHtml)(filePath);
47
56
  }
48
- }
49
- else if (argv.outputPath) {
50
- (0, node_fs_1.writeFileSync)(argv.outputPath, JSON.stringify(result, null, 2));
51
- }
52
- else {
53
- console.dir(result, { depth: null, colors: false });
57
+ } else if (argv.outputPath) {
58
+ (0, _nodefs.writeFileSync)(argv.outputPath, JSON.stringify(result, null, 2));
59
+ } else {
60
+ console.dir(result, {
61
+ depth: null,
62
+ colors: false
63
+ });
54
64
  }
55
65
  process.exit(0);
56
66
  });
57
67
  };
58
- exports.cli = cli;
@@ -1,19 +1,44 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.runBlock = exports.timeTravel = exports.setStorage = exports.setRuntimeLogLevel = exports.setHead = exports.setBlockBuildMode = exports.dryRun = exports.newBlock = void 0;
4
- var new_block_1 = require("./new-block");
5
- Object.defineProperty(exports, "newBlock", { enumerable: true, get: function () { return new_block_1.rpc; } });
6
- var dry_run_1 = require("./dry-run");
7
- Object.defineProperty(exports, "dryRun", { enumerable: true, get: function () { return dry_run_1.rpc; } });
8
- var set_block_build_mode_1 = require("./set-block-build-mode");
9
- Object.defineProperty(exports, "setBlockBuildMode", { enumerable: true, get: function () { return set_block_build_mode_1.rpc; } });
10
- var set_head_1 = require("./set-head");
11
- Object.defineProperty(exports, "setHead", { enumerable: true, get: function () { return set_head_1.rpc; } });
12
- var set_runtime_log_level_1 = require("./set-runtime-log-level");
13
- Object.defineProperty(exports, "setRuntimeLogLevel", { enumerable: true, get: function () { return set_runtime_log_level_1.rpc; } });
14
- var set_storage_1 = require("./set-storage");
15
- Object.defineProperty(exports, "setStorage", { enumerable: true, get: function () { return set_storage_1.rpc; } });
16
- var time_travel_1 = require("./time-travel");
17
- Object.defineProperty(exports, "timeTravel", { enumerable: true, get: function () { return time_travel_1.rpc; } });
18
- var run_block_1 = require("./run-block");
19
- Object.defineProperty(exports, "runBlock", { enumerable: true, get: function () { return run_block_1.rpc; } });
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ dryRun: function() {
13
+ return _dryrun.rpc;
14
+ },
15
+ newBlock: function() {
16
+ return _newblock.rpc;
17
+ },
18
+ runBlock: function() {
19
+ return _runblock.rpc;
20
+ },
21
+ setBlockBuildMode: function() {
22
+ return _setblockbuildmode.rpc;
23
+ },
24
+ setHead: function() {
25
+ return _sethead.rpc;
26
+ },
27
+ setRuntimeLogLevel: function() {
28
+ return _setruntimeloglevel.rpc;
29
+ },
30
+ setStorage: function() {
31
+ return _setstorage.rpc;
32
+ },
33
+ timeTravel: function() {
34
+ return _timetravel.rpc;
35
+ }
36
+ });
37
+ const _newblock = require("./new-block");
38
+ const _dryrun = require("./dry-run");
39
+ const _setblockbuildmode = require("./set-block-build-mode");
40
+ const _sethead = require("./set-head");
41
+ const _setruntimeloglevel = require("./set-runtime-log-level");
42
+ const _setstorage = require("./set-storage");
43
+ const _timetravel = require("./time-travel");
44
+ const _runblock = require("./run-block");
@@ -1,30 +1,39 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.handler = void 0;
4
- const chopsticks_core_1 = require("@acala-network/chopsticks-core");
5
- const plugins_1 = require("../plugins");
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "handler", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return handler;
9
+ }
10
+ });
11
+ const _chopstickscore = require("@acala-network/chopsticks-core");
12
+ const _plugins = require("../plugins");
6
13
  const allHandlers = {
7
- ...chopsticks_core_1.substrate,
8
- rpc_methods: async () => Promise.resolve({
9
- version: 1,
10
- methods: [...Object.keys(allHandlers), ...Object.keys(plugins_1.pluginHandlers)],
11
- }),
14
+ ..._chopstickscore.substrate,
15
+ rpc_methods: async ()=>Promise.resolve({
16
+ version: 1,
17
+ methods: [
18
+ ...Object.keys(allHandlers),
19
+ ...Object.keys(_plugins.pluginHandlers)
20
+ ]
21
+ })
12
22
  };
13
- const getHandler = (method) => {
23
+ const getHandler = (method)=>{
14
24
  const handler = allHandlers[method];
15
25
  if (!handler) {
16
26
  // no handler for this method, check if it's a plugin
17
- return plugins_1.pluginHandlers[method];
27
+ return _plugins.pluginHandlers[method];
18
28
  }
19
29
  return handler;
20
30
  };
21
- const handler = (context) => ({ method, params }, subscriptionManager) => {
22
- chopsticks_core_1.logger.trace('Handling %s', method);
23
- const handler = getHandler(method);
24
- if (!handler) {
25
- chopsticks_core_1.logger.warn('Method not found %s', method);
26
- throw new chopsticks_core_1.ResponseError(-32601, `Method not found: ${method}`);
27
- }
28
- return handler(context, params, subscriptionManager);
29
- };
30
- exports.handler = handler;
31
+ const handler = (context)=>({ method, params }, subscriptionManager)=>{
32
+ _chopstickscore.logger.trace('Handling %s', method);
33
+ const handler = getHandler(method);
34
+ if (!handler) {
35
+ _chopstickscore.logger.warn('Method not found %s', method);
36
+ throw new _chopstickscore.ResponseError(-32601, `Method not found: ${method}`);
37
+ }
38
+ return handler(context, params, subscriptionManager);
39
+ };
@@ -1,60 +1,89 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.fetchConfig = exports.configSchema = void 0;
7
- const chopsticks_core_1 = require("@acala-network/chopsticks-core");
8
- const node_path_1 = require("node:path");
9
- const node_fs_1 = require("node:fs");
10
- const zod_1 = require("zod");
11
- const lodash_1 = __importDefault(require("lodash"));
12
- const axios_1 = __importDefault(require("axios"));
13
- const js_yaml_1 = __importDefault(require("js-yaml"));
14
- exports.configSchema = zod_1.z
15
- .object({
16
- port: zod_1.z.number().optional(),
17
- endpoint: zod_1.z.string().optional(),
18
- block: zod_1.z.union([zod_1.z.string().length(66).startsWith('0x'), zod_1.z.number(), zod_1.z.null()]).optional(),
19
- 'build-block-mode': zod_1.z.nativeEnum(chopsticks_core_1.BuildBlockMode).optional(),
20
- 'import-storage': zod_1.z.any().optional(),
21
- 'mock-signature-host': zod_1.z.boolean().optional(),
22
- 'max-memory-block-count': zod_1.z.number().optional(),
23
- db: zod_1.z.string().optional(),
24
- 'wasm-override': zod_1.z.string().optional(),
25
- genesis: zod_1.z.union([zod_1.z.string(), chopsticks_core_1.genesisSchema]).optional(),
26
- timestamp: zod_1.z.number().optional(),
27
- 'registered-types': zod_1.z.any().optional(),
28
- 'runtime-log-level': zod_1.z.number().min(0).max(5).optional(),
29
- 'offchain-worker': zod_1.z.boolean().optional(),
30
- resume: zod_1.z.union([zod_1.z.string().length(66).startsWith('0x'), zod_1.z.number(), zod_1.z.boolean()]).optional(),
31
- })
32
- .strict();
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ configSchema: function() {
13
+ return configSchema;
14
+ },
15
+ fetchConfig: function() {
16
+ return fetchConfig;
17
+ }
18
+ });
19
+ const _chopstickscore = require("@acala-network/chopsticks-core");
20
+ const _nodepath = require("node:path");
21
+ const _nodefs = require("node:fs");
22
+ const _zod = require("zod");
23
+ const _lodash = /*#__PURE__*/ _interop_require_default(require("lodash"));
24
+ const _axios = /*#__PURE__*/ _interop_require_default(require("axios"));
25
+ const _jsyaml = /*#__PURE__*/ _interop_require_default(require("js-yaml"));
26
+ function _interop_require_default(obj) {
27
+ return obj && obj.__esModule ? obj : {
28
+ default: obj
29
+ };
30
+ }
31
+ const configSchema = _zod.z.object({
32
+ port: _zod.z.number().optional(),
33
+ endpoint: _zod.z.string().optional(),
34
+ block: _zod.z.union([
35
+ _zod.z.string().length(66).startsWith('0x'),
36
+ _zod.z.number(),
37
+ _zod.z.null()
38
+ ]).optional(),
39
+ 'build-block-mode': _zod.z.nativeEnum(_chopstickscore.BuildBlockMode).optional(),
40
+ 'import-storage': _zod.z.any().optional(),
41
+ 'mock-signature-host': _zod.z.boolean().optional(),
42
+ 'max-memory-block-count': _zod.z.number().optional(),
43
+ db: _zod.z.string().optional(),
44
+ 'wasm-override': _zod.z.string().optional(),
45
+ genesis: _zod.z.union([
46
+ _zod.z.string(),
47
+ _chopstickscore.genesisSchema
48
+ ]).optional(),
49
+ timestamp: _zod.z.number().optional(),
50
+ 'registered-types': _zod.z.any().optional(),
51
+ 'runtime-log-level': _zod.z.number().min(0).max(5).optional(),
52
+ 'offchain-worker': _zod.z.boolean().optional(),
53
+ resume: _zod.z.union([
54
+ _zod.z.string().length(66).startsWith('0x'),
55
+ _zod.z.number(),
56
+ _zod.z.boolean()
57
+ ]).optional()
58
+ }).strict();
33
59
  const CONFIGS_BASE_URL = 'https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/';
34
- const fetchConfig = async (path) => {
60
+ const fetchConfig = async (path)=>{
35
61
  let file;
36
- if ((0, chopsticks_core_1.isUrl)(path)) {
37
- file = await axios_1.default.get(path).then((x) => x.data);
38
- }
39
- else {
62
+ if ((0, _chopstickscore.isUrl)(path)) {
63
+ file = await _axios.default.get(path).then((x)=>x.data);
64
+ } else {
40
65
  try {
41
- file = (0, node_fs_1.readFileSync)(path, 'utf8');
42
- }
43
- catch (err) {
44
- if ((0, node_path_1.basename)(path) === path && ['', '.yml', '.yaml', '.json'].includes((0, node_path_1.extname)(path))) {
45
- if ((0, node_path_1.extname)(path) === '') {
66
+ file = (0, _nodefs.readFileSync)(path, 'utf8');
67
+ } catch (err) {
68
+ if ((0, _nodepath.basename)(path) === path && [
69
+ '',
70
+ '.yml',
71
+ '.yaml',
72
+ '.json'
73
+ ].includes((0, _nodepath.extname)(path))) {
74
+ if ((0, _nodepath.extname)(path) === '') {
46
75
  path += '.yml';
47
76
  }
48
77
  const url = CONFIGS_BASE_URL + path;
49
- chopsticks_core_1.defaultLogger.info(`Loading config file ${url}`);
50
- file = await axios_1.default.get(url).then((x) => x.data);
51
- }
52
- else {
78
+ _chopstickscore.defaultLogger.info(`Loading config file ${url}`);
79
+ file = await _axios.default.get(url).then((x)=>x.data);
80
+ } else {
53
81
  throw err;
54
82
  }
55
83
  }
56
84
  }
57
- const config = js_yaml_1.default.load(lodash_1.default.template(file, { variable: 'env' })(process.env));
58
- return exports.configSchema.parse(config);
85
+ const config = _jsyaml.default.load(_lodash.default.template(file, {
86
+ variable: 'env'
87
+ })(process.env));
88
+ return configSchema.parse(config);
59
89
  };
60
- exports.fetchConfig = fetchConfig;
@@ -1,43 +1,60 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createServer = void 0;
4
- const ws_1 = require("ws");
5
- const chopsticks_core_1 = require("@acala-network/chopsticks-core");
6
- const zod_1 = require("zod");
7
- const logger_1 = require("./logger");
8
- const logger = logger_1.defaultLogger.child({ name: 'ws' });
9
- const singleRequest = zod_1.z.object({
10
- id: zod_1.z.number(),
11
- jsonrpc: zod_1.z.literal('2.0'),
12
- method: zod_1.z.string(),
13
- params: zod_1.z.array(zod_1.z.any()).default([]),
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
14
4
  });
15
- const batchRequest = zod_1.z.array(singleRequest);
16
- const requestSchema = zod_1.z.union([singleRequest, batchRequest]);
17
- const parseRequest = (request) => {
5
+ Object.defineProperty(exports, "createServer", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return createServer;
9
+ }
10
+ });
11
+ const _ws = require("ws");
12
+ const _chopstickscore = require("@acala-network/chopsticks-core");
13
+ const _zod = require("zod");
14
+ const _logger = require("./logger");
15
+ const logger = _logger.defaultLogger.child({
16
+ name: 'ws'
17
+ });
18
+ const singleRequest = _zod.z.object({
19
+ id: _zod.z.number(),
20
+ jsonrpc: _zod.z.literal('2.0'),
21
+ method: _zod.z.string(),
22
+ params: _zod.z.array(_zod.z.any()).default([])
23
+ });
24
+ const batchRequest = _zod.z.array(singleRequest);
25
+ const requestSchema = _zod.z.union([
26
+ singleRequest,
27
+ batchRequest
28
+ ]);
29
+ const parseRequest = (request)=>{
18
30
  try {
19
31
  return JSON.parse(request);
20
- }
21
- catch (e) {
32
+ } catch (e) {
22
33
  return undefined;
23
34
  }
24
35
  };
25
- const createWS = async (port) => {
26
- const wss = new ws_1.WebSocketServer({ port, maxPayload: 1024 * 1024 * 100 });
27
- const promise = new Promise((resolve) => {
28
- wss.on('listening', () => {
29
- resolve([wss, wss.address().port]);
36
+ const createWS = async (port)=>{
37
+ const wss = new _ws.WebSocketServer({
38
+ port,
39
+ maxPayload: 1024 * 1024 * 100
40
+ });
41
+ const promise = new Promise((resolve)=>{
42
+ wss.on('listening', ()=>{
43
+ resolve([
44
+ wss,
45
+ wss.address().port
46
+ ]);
30
47
  });
31
- wss.on('error', (_) => {
48
+ wss.on('error', (_)=>{
32
49
  resolve([]);
33
50
  });
34
51
  });
35
52
  return promise;
36
53
  };
37
- const createServer = async (handler, port) => {
54
+ const createServer = async (handler, port)=>{
38
55
  let wss;
39
56
  let listenPort;
40
- for (let i = 0; i < 10; i++) {
57
+ for(let i = 0; i < 10; i++){
41
58
  const preferPort = (port ?? 0) > 0 ? (port ?? 0) + i : 0;
42
59
  logger.debug('Try starting on port %d', preferPort);
43
60
  const [maybeWss, maybeListenPort] = await createWS(preferPort);
@@ -50,80 +67,86 @@ const createServer = async (handler, port) => {
50
67
  if (!wss || !listenPort) {
51
68
  throw new Error(`Failed to create WebsocketServer at port ${port}`);
52
69
  }
53
- wss.on('connection', (ws) => {
70
+ wss.on('connection', (ws)=>{
54
71
  logger.debug('New connection');
55
- const send = (data) => {
56
- if (ws.readyState === ws_1.WebSocket.OPEN) {
72
+ const send = (data)=>{
73
+ if (ws.readyState === _ws.WebSocket.OPEN) {
57
74
  ws.send(JSON.stringify(data));
58
75
  }
59
76
  };
60
77
  const subscriptions = {};
61
78
  const subscriptionManager = {
62
- subscribe: (method, subid, onCancel = () => { }) => {
79
+ subscribe: (method, subid, onCancel = ()=>{})=>{
63
80
  subscriptions[subid] = onCancel;
64
- return (data) => {
81
+ return (data)=>{
65
82
  if (subscriptions[subid]) {
66
- logger.trace({ method, subid, data: (0, logger_1.truncate)(data) }, 'Subscription notification');
83
+ logger.trace({
84
+ method,
85
+ subid,
86
+ data: (0, _logger.truncate)(data)
87
+ }, 'Subscription notification');
67
88
  send({
68
89
  jsonrpc: '2.0',
69
90
  method,
70
91
  params: {
71
92
  result: data,
72
- subscription: subid,
73
- },
93
+ subscription: subid
94
+ }
74
95
  });
75
96
  }
76
97
  };
77
98
  },
78
- unsubscribe: (subid) => {
99
+ unsubscribe: (subid)=>{
79
100
  if (subscriptions[subid]) {
80
101
  subscriptions[subid](subid);
81
102
  delete subscriptions[subid];
82
103
  }
83
- },
104
+ }
84
105
  };
85
- const processRequest = async (req) => {
106
+ const processRequest = async (req)=>{
86
107
  logger.trace({
87
108
  id: req.id,
88
- method: req.method,
109
+ method: req.method
89
110
  }, 'Received message');
90
111
  try {
91
112
  const resp = await handler(req, subscriptionManager);
92
113
  logger.trace({
93
114
  id: req.id,
94
115
  method: req.method,
95
- result: (0, logger_1.truncate)(resp),
116
+ result: (0, _logger.truncate)(resp)
96
117
  }, 'Response for request');
97
118
  return {
98
119
  id: req.id,
99
120
  jsonrpc: '2.0',
100
- result: resp ?? null,
121
+ result: resp ?? null
101
122
  };
102
- }
103
- catch (e) {
123
+ } catch (e) {
104
124
  logger.info('Error handling request: %s %o', e, e.stack);
105
125
  return {
106
126
  id: req.id,
107
127
  jsonrpc: '2.0',
108
- error: e instanceof chopsticks_core_1.ResponseError ? e : { code: -32603, message: `Internal ${e}` },
128
+ error: e instanceof _chopstickscore.ResponseError ? e : {
129
+ code: -32603,
130
+ message: `Internal ${e}`
131
+ }
109
132
  };
110
133
  }
111
134
  };
112
- ws.on('close', () => {
135
+ ws.on('close', ()=>{
113
136
  logger.debug('Connection closed');
114
- for (const [subid, onCancel] of Object.entries(subscriptions)) {
137
+ for (const [subid, onCancel] of Object.entries(subscriptions)){
115
138
  onCancel(subid);
116
139
  }
117
140
  ws.removeAllListeners();
118
141
  });
119
- ws.on('error', () => {
142
+ ws.on('error', ()=>{
120
143
  logger.debug('Connection error');
121
- for (const [subid, onCancel] of Object.entries(subscriptions)) {
144
+ for (const [subid, onCancel] of Object.entries(subscriptions)){
122
145
  onCancel(subid);
123
146
  }
124
147
  ws.removeAllListeners();
125
148
  });
126
- ws.on('message', async (message) => {
149
+ ws.on('message', async (message)=>{
127
150
  const parsed = await requestSchema.safeParseAsync(parseRequest(message.toString()));
128
151
  if (!parsed.success) {
129
152
  logger.info('Invalid request: %s', message);
@@ -132,19 +155,22 @@ const createServer = async (handler, port) => {
132
155
  jsonrpc: '2.0',
133
156
  error: {
134
157
  code: -32600,
135
- message: 'Invalid JSON Request',
136
- },
158
+ message: 'Invalid JSON Request'
159
+ }
137
160
  });
138
161
  return;
139
162
  }
140
163
  const { data: req } = parsed;
141
164
  if (Array.isArray(req)) {
142
- logger.trace({ req }, 'Received batch request');
165
+ logger.trace({
166
+ req
167
+ }, 'Received batch request');
143
168
  const resp = await Promise.all(req.map(processRequest));
144
169
  send(resp);
145
- }
146
- else {
147
- logger.trace({ req }, 'Received single request');
170
+ } else {
171
+ logger.trace({
172
+ req
173
+ }, 'Received single request');
148
174
  const resp = await processRequest(req);
149
175
  send(resp);
150
176
  }
@@ -152,17 +178,15 @@ const createServer = async (handler, port) => {
152
178
  });
153
179
  return {
154
180
  port: listenPort,
155
- close: () => new Promise((resolve, reject) => {
156
- wss?.clients.forEach((socket) => socket.close());
157
- wss?.close((err) => {
158
- if (err) {
159
- reject(err);
160
- }
161
- else {
162
- resolve();
163
- }
164
- });
165
- }),
181
+ close: ()=>new Promise((resolve, reject)=>{
182
+ wss?.clients.forEach((socket)=>socket.close());
183
+ wss?.close((err)=>{
184
+ if (err) {
185
+ reject(err);
186
+ } else {
187
+ resolve();
188
+ }
189
+ });
190
+ })
166
191
  };
167
192
  };
168
- exports.createServer = createServer;