biz-a-cli 2.3.61 → 2.3.63

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.
@@ -1,6 +1,7 @@
1
1
  import { apiRequestListener, RECONNECT_SOCKET_DELAY } from './hubEvent.js'
2
2
  import { deploymentListenerForVSCode } from './deployEvent.js'
3
3
  import { Tunnel as QuickTunnel } from 'cloudflared'
4
+ import { Server as ioServer } from 'socket.io'
4
5
 
5
6
  export const CLIENT_ROOM = 'clientRoom'
6
7
 
@@ -46,25 +47,40 @@ export async function localhostTunnel(port, notifier){
46
47
 
47
48
  export function directHubEvent(serverSocket, argv){
48
49
  serverSocket.on('connection', (clientSocket) => {
50
+
51
+ const setConnectListeners = (sock)=>{
52
+ // shall not log in production mode
53
+ if (process.env.NODE_ENV !== 'production') {
54
+ const id = `<${sock.handshake?.query?.isClient ? `Client` : sock.handshake?.query?.isDeploy ? 'Deployer' : 'Anonymous'}> ${sock.id}`;
55
+ console.log(id, `connected`)
56
+ sock.on('disconnect', (reason)=>{
57
+ console.log(id, `disconnected. Reason : ${reason}`)
58
+ })
59
+ };
60
+ };
61
+
49
62
  if (clientSocket.handshake.query.isClient) {
50
- clientSocket.join(CLIENT_ROOM);
63
+ setConnectListeners(clientSocket);
51
64
  apiRequestListener(clientSocket, argv);
65
+ clientSocket.join(CLIENT_ROOM);
52
66
  }
53
67
  else if (clientSocket.handshake.query.isDeploy) {
68
+ setConnectListeners(clientSocket);
54
69
  deploymentListenerForVSCode(clientSocket, argv)
70
+ } else {
71
+ clientSocket.disconnect();
55
72
  }
56
-
57
- // shall not log in production mode
58
- if (process.env.NODE_ENV !== 'production') {
59
- const id = `<${clientSocket.handshake?.query?.isClient ? `Client` : clientSocket.handshake?.query?.isDeploy ? 'Deployer' : 'Anonymous'}> ${clientSocket.id}`;
60
- console.log(id, `connected`)
61
- clientSocket.on('disconnect', (reason)=>{
62
- console.log(id, `disconnected. Reason : ${reason}`)
63
- })
64
- };
65
73
  })
66
74
  }
67
75
 
68
- export function getSocketCORSOrigin(cliIpAddress){
69
- return ['https://biz-a.id', 'https://test.biz-a.id', /\.biz-a\.id$/, 'vscode-file://vscode-app', /\.vscode-cdn\.net$/].concat((process.env.NODE_ENV === 'production') ? [] : [`http://${cliIpAddress}:4200`, 'http://localhost:4200'])
70
- }
76
+ export function createSocketServer(httpServer, cliIpAddress='127.0.0.1'){
77
+ return new ioServer(
78
+ httpServer,
79
+ {
80
+ cors: {origin: ['https://biz-a.id', 'https://test.biz-a.id', /\.biz-a\.id$/, 'vscode-file://vscode-app', /\.vscode-cdn\.net$/].concat((process.env.NODE_ENV === 'production') ? [] : [`http://${cliIpAddress}:4200`, 'http://localhost:4200'])},
81
+ maxHttpBufferSize: 1e8, // 100 MB
82
+ pingInterval: 35000, // default = 25000
83
+ pingTimeout: 30000 // default = 20000
84
+ }
85
+ );
86
+ };
package/bin/hub.js CHANGED
@@ -8,9 +8,8 @@ import yargs from 'yargs';
8
8
  import { io as ioClient } from "socket.io-client";
9
9
  import { streamEvent, hubEvent, RECONNECT_SOCKET_DELAY } from './hubEvent.js'
10
10
  import { createLogger, transports, format } from "winston";
11
- import { Server as ioServer } from 'socket.io'
12
11
  import os from 'node:os'
13
- import { directHubEvent, localhostTunnel, getSocketCORSOrigin }from './directHubEvent.js'
12
+ import { directHubEvent, localhostTunnel, createSocketServer }from './directHubEvent.js'
14
13
  import { env } from "../envs/env.js"
15
14
 
16
15
  const logger = createLogger({
@@ -132,7 +131,11 @@ app.use(express.json({ limit: '100mb' }));
132
131
 
133
132
  app.set('args', argv);
134
133
 
135
- app.use('/cb', runCliScript);
134
+ let socket = null
135
+ app.use('/cb', (req, res)=>{
136
+ req.socket = socket
137
+ runCliScript(req, res)
138
+ });
136
139
 
137
140
  app.use('/status', (req, res)=>{
138
141
  res.status(200).json(argv.cliAddress());
@@ -158,7 +161,7 @@ await streamEvent(ioClient(argv['server'], {query: {isSockStream: true }}), argv
158
161
 
159
162
  // as socket client to BizA HUB
160
163
  if (argv.hubServer) {
161
- hubEvent(ioClient(argv['hubServer'], { reconnectionDelay: RECONNECT_SOCKET_DELAY, reconnectionDelayMax: RECONNECT_SOCKET_DELAY, query: {isCLI: true, room: argv['subdomain']} }), argv, (url)=>{
164
+ socket = hubEvent(ioClient(argv['hubServer'], { reconnectionDelay: RECONNECT_SOCKET_DELAY, reconnectionDelayMax: RECONNECT_SOCKET_DELAY, query: {isCLI: true, room: argv['subdomain']} }), argv, (url)=>{
162
165
  if (url!==argv.connectedHubUrl) {
163
166
  argv.connectedHubUrl = url
164
167
  }
@@ -166,7 +169,8 @@ if (argv.hubServer) {
166
169
  }
167
170
 
168
171
  // as socket server for BizA Client and BizA devTools
169
- directHubEvent(new ioServer(server, {cors: {origin: getSocketCORSOrigin(argv.cliAddress().ip)}}), argv);
172
+ directHubEvent(createSocketServer(server, argv.cliAddress().ip), argv);
173
+
170
174
  if (argv.publish==true) {
171
175
  localhostTunnel(argv.serverport, (url)=>{ // publish CLI
172
176
  if (url!==argv.connectedPublicUrl) {
package/bin/hubEvent.js CHANGED
@@ -128,6 +128,7 @@ export const streamEvent = async (socket, argv) => new Promise((resolve, reject)
128
128
  socket.io.on('reconnect', ()=>{
129
129
  console.log(`${new Date()}: ${getIdText(id)}reconnecting to BizA Server`)
130
130
  })
131
+ return socket
131
132
  })
132
133
 
133
134
  export const hubEvent = (socket, argv, notifier)=>{
@@ -160,11 +161,11 @@ export const hubEvent = (socket, argv, notifier)=>{
160
161
  })
161
162
  apiRequestListener(socket, argv);
162
163
  deploymentListenerForHubServer(socket, argv);
164
+ return socket
163
165
  }
164
166
 
165
167
  export const apiRequestListener = (socket, argv)=>{
166
168
  socket.on('apiRequest', (reqData, resCB)=>{
167
-
168
169
  let apiAddress = `${argv['secure']==true ? 'https://' : 'http://'}${argv['hostname']}:${argv['port']}`
169
170
  let reqBody = reqData.body
170
171
  try{
@@ -176,14 +177,23 @@ export const apiRequestListener = (socket, argv)=>{
176
177
  }
177
178
  } catch (error) {}
178
179
 
179
- const socketResponse = (resp)=>{return {
180
- status: resp.status,
181
- statusText: resp.statusText,
182
- headers: resp.headers,
183
- body: resp.data,
184
- url: apiAddress + resp.config.url
185
- }}
186
-
180
+ const socketResponse = (resp)=>{
181
+ const cliAddress = argv.cliAddress();
182
+ let cliAddressHeaders = {};
183
+ if (cliAddress.publicUrl) {
184
+ cliAddressHeaders['biza-cli-address'] = cliAddress.publicUrl;
185
+ };
186
+ if (cliAddress.hubUrl) {
187
+ cliAddressHeaders['biza-hub-address'] = cliAddress.hubUrl;
188
+ };
189
+ return {
190
+ status: resp.status,
191
+ statusText: resp.statusText,
192
+ headers: {...resp.headers, ...cliAddressHeaders},
193
+ body: resp.data,
194
+ url: apiAddress + resp.config.url
195
+ };
196
+ };
187
197
  if (argv['subdomain'].localeCompare(reqData.subDomain)==0) {
188
198
  axios.request({
189
199
  timeout : (reqData.timeout || IDLE_SOCKET_TIMEOUT_MILLISECONDS),
@@ -26,7 +26,7 @@ export async function runCliScript(req, res) {
26
26
  let script = await loadCliScript(selectedConfig, 'ID', req.body.query.scriptid);
27
27
  let functions = await extractFunctionScript(selectedConfig, script);
28
28
  if (functions) {
29
- let respon = await functions.onInit(data);
29
+ let respon = await functions.onInit(data, req.socket);
30
30
  res.send(respon);
31
31
 
32
32
  console.log(`Run Callback Successfully!`);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "biz-a-cli",
3
3
  "nameDev": "biz-a-cli-dev",
4
- "version": "2.3.61",
4
+ "version": "2.3.63",
5
5
  "versionDev": "0.0.34",
6
6
  "description": "",
7
7
  "main": "bin/index.js",
@@ -167,7 +167,8 @@ export async function extractFunctionScript(selectedConfig, data) {
167
167
  axios: axios.default,
168
168
  dayjs: dayjs.default,
169
169
  crypto: crypto,
170
- log: logger
170
+ log: logger,
171
+ data: {sendModel, queryData, crudData, genId, getUrlAndParam}
171
172
  }
172
173
 
173
174
  if (scriptFn().functions.useLibrary) {
@@ -3,7 +3,7 @@ import { getAppData, onScriptChangeFromVsCode, onScriptChangeFromHubServer} from
3
3
  import { io as ioClient, Socket, Manager } from "socket.io-client";
4
4
  import { expect, jest } from '@jest/globals';
5
5
  import axios from "axios";
6
- import { directHubEvent, getSocketCORSOrigin, CLIENT_ROOM } from '../bin/directHubEvent.js'
6
+ import { directHubEvent, CLIENT_ROOM } from '../bin/directHubEvent.js'
7
7
  import { createDecipheriv } from 'node:crypto'
8
8
  import { hubEvent } from '../bin/hubEvent.js';
9
9
 
@@ -38,18 +38,6 @@ describe('Deployment', () => {
38
38
  jest.restoreAllMocks()
39
39
  })
40
40
 
41
- it('shall allow origins', ()=>{
42
- expect(getSocketCORSOrigin(hostname)).toStrictEqual([
43
- 'https://biz-a.id',
44
- 'https://test.biz-a.id',
45
- /\.biz-a\.id$/,
46
- 'vscode-file://vscode-app',
47
- /\.vscode-cdn\.net$/,
48
- `http://${hostname}:4200`,
49
- 'http://localhost:4200'
50
- ])
51
- })
52
-
53
41
  it('shall get app list from database', async ()=>{
54
42
  // Failed : check for error message
55
43
  const requestSpy = jest.spyOn(axios, 'request').mockResolvedValueOnce({
@@ -174,7 +162,7 @@ describe('Deployment', () => {
174
162
  jest.spyOn(console, 'log').mockImplementation()
175
163
 
176
164
  vsCodeToCLISock = await toPromise((resolve)=>{
177
- const sock = ioClient(`http://${hostname}:${port}`).on('connect', async ()=>{
165
+ const sock = ioClient(`http://${hostname}:${port}`, {query: {isDeploy: true}}).on('connect', async ()=>{
178
166
  serverSideSock = (await cliSocketServer.fetchSockets()).find((s)=>s.id==sock.id)
179
167
 
180
168
  // if using socket.broadcast.emit()
package/tests/hub.test.js CHANGED
@@ -9,7 +9,7 @@ import tls from 'node:tls'
9
9
  import ss from 'socket.io-stream'
10
10
  import { Writable, pipeline } from 'node:stream'
11
11
  import { text } from 'node:stream/consumers'
12
- import { directHubEvent } from '../bin/directHubEvent.js'
12
+ import { directHubEvent, createSocketServer } from '../bin/directHubEvent.js'
13
13
 
14
14
  let socketsBySubdomain = {};
15
15
 
@@ -234,8 +234,7 @@ describe('Hub event tests', () => {
234
234
 
235
235
  beforeAll(()=>{
236
236
  cliSocketServer = new ioServer(9999)// mocking of CLI socket server
237
- directHubEvent(cliSocketServer, {subdomain, hostname: apiAddress, port, secure: false})
238
-
237
+ directHubEvent(cliSocketServer, {subdomain, hostname: apiAddress, port, secure: false, cliAddress: ()=>{return {ip: '59.60.1.22', port: '3002', address: `59.60.1.22:3002`, publicUrl: 'https://some.public.url', hubUrl: 'https://some.hub.url'}}});
239
238
  clientToCliSocket = ioClient('http://localhost:9999', {query: {isClient:true}})
240
239
  })
241
240
 
@@ -260,14 +259,16 @@ describe('Hub event tests', () => {
260
259
  clientToCliSocket.emit(
261
260
  'apiRequest'
262
261
  , {subDomain: subdomain, method: 'POST', path: '/test', headers: {'req-header': 'aa'}, body: 'body of request', responseType: 'json'}
263
- , (err, res)=>{resolve([err, res])}
262
+ , (err, res)=>{
263
+ resolve([err, res])
264
+ }
264
265
  )
265
266
  })
266
267
 
267
268
  expect(response).toStrictEqual({
268
269
  status: 200,
269
270
  statusText: 'Success',
270
- headers: {'res-header': 'aa'},
271
+ headers: {'res-header': 'aa', "biza-cli-address": "https://some.public.url", "biza-hub-address": "https://some.hub.url"},
271
272
  body: 'body of response',
272
273
  url: `http://${apiAddress}:${port}/test`
273
274
  })
@@ -398,7 +399,7 @@ describe('Hub event tests', () => {
398
399
  expect(result.response).toStrictEqual({
399
400
  status: 200,
400
401
  statusText: 'Success',
401
- headers: {'res-header': 'aa'},
402
+ headers: {'res-header': 'aa', "biza-cli-address": "https://some.tunnel.url"},
402
403
  body: 'body of response',
403
404
  url: `http://127.0.0.1:${port}/test`
404
405
  })
@@ -420,7 +421,7 @@ describe('Hub event tests', () => {
420
421
  expect(result.response).toStrictEqual({
421
422
  status: 200,
422
423
  statusText: 'Success',
423
- headers: {'res-header': 'aa'},
424
+ headers: {'res-header': 'aa', 'biza-cli-address': 'https://some.tunnel.url'},
424
425
  body: 'body of response',
425
426
  url: 'http://apiHost:apiPort/test'
426
427
  })
@@ -442,7 +443,7 @@ describe('Hub event tests', () => {
442
443
  expect(result.response).toStrictEqual({
443
444
  status: 200,
444
445
  statusText: 'Success',
445
- headers: {'res-header': 'aa'},
446
+ headers: {'res-header': 'aa', 'biza-cli-address': 'https://some.tunnel.url'},
446
447
  body: 'body of response',
447
448
  url: 'http://apiHost:apiPort/test'
448
449
  })
@@ -467,4 +468,27 @@ describe('Hub event tests', () => {
467
468
  }
468
469
  })
469
470
 
471
+ test('shall create socket server with correct options', ()=>{
472
+ const sockHttpServer = createServer();
473
+ const sockServer = createSocketServer(sockHttpServer, '1.2.3.4');
474
+ try {
475
+ const opts = sockServer.opts;
476
+ expect(opts.cors.origin).toStrictEqual([
477
+ 'https://biz-a.id',
478
+ 'https://test.biz-a.id',
479
+ /\.biz-a\.id$/,
480
+ 'vscode-file://vscode-app',
481
+ /\.vscode-cdn\.net$/,
482
+ 'http://1.2.3.4:4200',
483
+ 'http://localhost:4200'
484
+ ]);
485
+ expect(opts.maxHttpBufferSize).toBe(1e8);
486
+ expect(opts.pingInterval).toBe(35000);
487
+ expect(opts.pingTimeout).toBe(30000);
488
+ } finally {
489
+ sockServer.close();
490
+ sockHttpServer.close();
491
+ };
492
+ });
493
+
470
494
  })
package/constanta.js DELETED
@@ -1,8 +0,0 @@
1
- export const ECODE = {
2
- API: 'EAPI',
3
- FULL: 'full'
4
- }
5
- export const MSG = {
6
- E_USER_PASS_IN_API: 'Username or password is not valid. Check database no:1 in API',
7
- E_LICENSE_FULL: 'The license is full.',
8
- }