Skip to content

Commit

Permalink
Console logs updated + Classic & XMLHttp
Browse files Browse the repository at this point in the history
interceptors now headers are shown
  • Loading branch information
RNEvok committed Jun 17, 2023
1 parent c3a77ab commit bb035f1
Show file tree
Hide file tree
Showing 11 changed files with 81 additions and 49 deletions.
31 changes: 15 additions & 16 deletions Connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { EventHandleError, ScenarioHandleError } from './Errors';
import { api, SOCKET_EVENTS_LISTEN, SOCKET_EVENTS_EMIT } from './api/api';
import { SPECIAL_INSTRUCTIONS_TABLE, SPECIAL_INSTRUCTIONS } from './constants/events';
import { io, Socket } from "socket.io-client";
import { stringifyIfNotString } from './helperFunctions';
import { codebudConsoleLog, codebudConsoleWarn, stringifyIfNotString } from './helperFunctions';
import moment from 'moment';

export class Connector {
Expand Down Expand Up @@ -97,7 +97,7 @@ export class Connector {
};

private async _innerHandleEvent(event: RemoteEvent, isPartOfScenario: boolean = false) {
console.log('On event:', event);
codebudConsoleLog('On event:', event);

try {
const correspondingInstructionsTable = event.eventType === "default" ? this._instructionsTable: SPECIAL_INSTRUCTIONS_TABLE;
Expand Down Expand Up @@ -153,7 +153,7 @@ export class Connector {

return eventLog;
} catch (error) {
console.log(`Error while trying to handle event.`, error);
codebudConsoleLog(`Error while trying to handle event.`, error);

// If current event was part of scenario then throw error so it would be processed inside _innerHandleScenario's catch block
if (isPartOfScenario)
Expand All @@ -164,7 +164,7 @@ export class Connector {
}

private async _innerHandleScenario(scenario: RemoteScenario) {
console.log('On scenario:', scenario);
// codebudConsoleLog('On scenario:', scenario);

var eventIndex = 0;
this._lastEventLog = undefined;
Expand Down Expand Up @@ -199,7 +199,7 @@ export class Connector {
};
this._socket.emit(SOCKET_EVENTS_EMIT.SAVE_SCENARIO_LOG, scenarioLog);
} catch (error) {
console.log(`Error while trying to handle scenario.`, error);
codebudConsoleLog(`Error while trying to handle scenario.`, error);
const scenarioError = new ScenarioHandleError(scenario, scenario.events[eventIndex], "Scenario execution failed.");
this._socket.emit(SOCKET_EVENTS_EMIT.SAVE_SCENARIO_LOG, {scenario, ok: false, error: scenarioError});
}
Expand All @@ -219,20 +219,20 @@ export class Connector {
Connector._remoteSettings = remoteSettings;
callbackFn && callbackFn(remoteSettings);
} catch (e) {
console.warn("Error while trying to fetch remote settings", e);
codebudConsoleWarn("Error while trying to fetch remote settings", e);
}
}

private async _setupNetworkMonitor(config: PackageConfig) {
this._networkInterceptor = new config.Interceptor({
onRequest: ({ request, requestId }: NetworkInterceptorOnRequestPayload) => {
// console.log(`Intercepted request ${requestId}`, request);
// codebudConsoleLog(`Intercepted request ${requestId}`, request);
const timestamp = moment().valueOf();
const encryptedData = this._encryptData({request, requestId, timestamp});
this._socket?.emit(SOCKET_EVENTS_EMIT.SAVE_INTERCEPTED_REQUEST, encryptedData);
},
onResponse: ({ response, request, requestId }: NetworkInterceptorOnResponsePayload) => {
// console.log(`Intercepted response ${requestId}`, response);
// codebudConsoleLog(`Intercepted response ${requestId}`, response);
const timestamp = moment().valueOf();
const encryptedData = this._encryptData({response, request, requestId, timestamp});
this._socket?.emit(SOCKET_EVENTS_EMIT.SAVE_INTERCEPTED_RESPONSE, encryptedData);
Expand Down Expand Up @@ -283,14 +283,13 @@ export class Connector {
this.refreshRemoteSettings();

this._socket.on(SOCKET_EVENTS_LISTEN.CONNECT, () => {
console.log('Socket connected:', this._socket.connected);
codebudConsoleLog('Socket connected:', this._socket.connected);
this._socket.emit(SOCKET_EVENTS_EMIT.SET_CONNECTION_INFO, this._connectionInfoPacket);
});

this._socket.on(SOCKET_EVENTS_LISTEN.ADMIN_CONNECTED, (data: AdminConnectedData) => {
console.log("AdminConnected", data)
codebudConsoleLog("AdminConnected");
if (!data.isAdmin) {
console.warn('Warning: client connected');
return;
}

Expand All @@ -303,7 +302,7 @@ export class Connector {
this._socket.on(SOCKET_EVENTS_LISTEN.SCENARIO, (scenario: RemoteScenario) => this._innerHandleScenario(scenario));

this._socket.on(SOCKET_EVENTS_LISTEN.STOP_SCENARIO_EXECUTION, () => {
console.log("Stopping scenario manually...");
codebudConsoleLog("Stopping scenario manually...");
this._shouldStopScenarioExecution = true;
});

Expand All @@ -314,15 +313,15 @@ export class Connector {
});

this._socket.on(SOCKET_EVENTS_LISTEN.CONNECT_ERROR, (err) => {
console.warn(`Socket connect_error: ${err.message}`);
codebudConsoleWarn(`Socket connect_error: ${err.message}`);
});

this._socket.on(SOCKET_EVENTS_LISTEN.ERROR, (error) => {
console.log('Socket send error:', error);
codebudConsoleLog('Socket send error:', error);
});

this._socket.on(SOCKET_EVENTS_LISTEN.DISCONNECT, async () => {
console.log('Socket disconnected.');
codebudConsoleLog('Socket disconnected.');
setTimeout(() => {
this._socket.connect();
}, CONFIG.SOCKET_RECONNECTION_DELAY);
Expand All @@ -346,7 +345,7 @@ export class Connector {
}
}
} catch (e) {
console.warn(`Error while trying to create ReduxStoreChangeHandler`, e);
codebudConsoleWarn(`Error while trying to create ReduxStoreChangeHandler`, e);
return () => {};
}
}
Expand Down
16 changes: 10 additions & 6 deletions Network/NetworkInterceptorClassic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest';
import { NetworkInterceptorApi } from './AbstractInterceptor';
import { NetworkInterceptorCallbacksTable } from '../types';
import { shouldProceedIntercepted } from './helpers';
import { codebudConsoleLog } from '../helperFunctions';

class NetworkInterceptorClassic extends NetworkInterceptorApi {
private _interceptor: ClientRequestInterceptor | null = null;

protected async formatRequest(request: any) {
console.log('DEBUG', Object.fromEntries(request.headers));
let body: any;
const isJsonContentType = request.headers.get("content-type")?.includes("application/json");

Expand All @@ -17,13 +19,14 @@ class NetworkInterceptorClassic extends NetworkInterceptorApi {
body = await request.clone().text();
}
} catch (e) {
console.log('Request transfrom error');
codebudConsoleLog('Request transfrom error');
}

const formattedRequest = {
method: request.method,
body,
url: request.url
url: request.url,
requestHeaders: Object.fromEntries(request.headers)
};

return formattedRequest;
Expand All @@ -40,13 +43,14 @@ class NetworkInterceptorClassic extends NetworkInterceptorApi {
data = await response.clone().text();
}
} catch (e) {
console.log('Response transfrom error');
codebudConsoleLog('Response transfrom error');
}

const formattedResponse = {
status: response.status,
statusText: response.statusText,
data
data,
responseHeaders: Object.fromEntries(response.headers)
};

return formattedResponse;
Expand All @@ -68,7 +72,7 @@ class NetworkInterceptorClassic extends NetworkInterceptorApi {
requestId
});
} catch (e) {
console.log(e);
codebudConsoleLog(e);
}
}
});
Expand All @@ -84,7 +88,7 @@ class NetworkInterceptorClassic extends NetworkInterceptorApi {
requestId
});
} catch (e) {
console.log(e);
codebudConsoleLog(e);
}
}
});
Expand Down
3 changes: 2 additions & 1 deletion Network/NetworkInterceptorRN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { NetworkInterceptorApi } from './AbstractInterceptor';
import { startNetworkLogging, stopNetworkLogging, clearRequests } from "./../rn";
import { NetworkInterceptorCallbacksTable } from '../types';
import { CONFIG } from './../config';
import { codebudConsoleLog } from '../helperFunctions';

class NetworkInterceptorRN extends NetworkInterceptorApi {
protected async formatRequest(data: any) {
Expand Down Expand Up @@ -60,7 +61,7 @@ class NetworkInterceptorRN extends NetworkInterceptorApi {
requestId: data.id
});
} catch (e) {
console.log(e);
codebudConsoleLog(e);
}
}
});
Expand Down
15 changes: 9 additions & 6 deletions Network/NetworkInterceptorXMLHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest';
import { NetworkInterceptorApi } from './AbstractInterceptor';
import { NetworkInterceptorCallbacksTable } from '../types';
import { shouldProceedIntercepted } from './helpers';
import { codebudConsoleLog } from '../helperFunctions';

class NetworkInterceptorXMLHttp extends NetworkInterceptorApi {
private _interceptor: XMLHttpRequestInterceptor | null = null;
Expand All @@ -17,13 +18,14 @@ class NetworkInterceptorXMLHttp extends NetworkInterceptorApi {
body = await request.clone().text();
}
} catch (e) {
console.log('Request transfrom error');
codebudConsoleLog('Request transfrom error');
}

const formattedRequest = {
method: request.method,
body,
url: request.url
url: request.url,
requestHeaders: Object.fromEntries(request.headers)
};

return formattedRequest;
Expand All @@ -40,13 +42,14 @@ class NetworkInterceptorXMLHttp extends NetworkInterceptorApi {
data = await response.clone().text();
}
} catch (e) {
console.log('Response transfrom error');
codebudConsoleLog(e);
}

const formattedResponse = {
status: response.status,
statusText: response.statusText,
data
data,
responseHeaders: Object.fromEntries(response.headers)
};

return formattedResponse;
Expand All @@ -68,7 +71,7 @@ class NetworkInterceptorXMLHttp extends NetworkInterceptorApi {
requestId
});
} catch (e) {
console.log(e);
codebudConsoleLog(e);
}
}
});
Expand All @@ -84,7 +87,7 @@ class NetworkInterceptorXMLHttp extends NetworkInterceptorApi {
requestId
});
} catch (e) {
console.log(e);
codebudConsoleLog(e);
}
}
});
Expand Down
1 change: 1 addition & 0 deletions config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const DEV_MODE: DevMode = "PRODUCTION";

const CONFIG_INNER = {
PRODUCT_NAME: "CodeBud",
MAX_IDENTICAL_CONSOLE_WARNINGS_IN_A_ROW: 3,
DOMAIN: "unitap.online",
MAIN_URL: "https://unitap.online",
BASE_URL: 'https://unitap.online/api',
Expand Down
6 changes: 3 additions & 3 deletions encryption/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { box, randomBytes } from 'tweetnacl';
import { decodeUTF8, encodeBase64 } from 'tweetnacl-util';
import { codebudConsoleLog, codebudConsoleWarn } from '../helperFunctions';

export class EncryptionPlugin {
private _keyPair: nacl.BoxKeyPair | null = null;
Expand Down Expand Up @@ -27,7 +28,7 @@ export class EncryptionPlugin {
const base64FullMessage = encodeBase64(fullMessage);
return base64FullMessage;
} catch (e) {
console.log(e);
codebudConsoleLog(e);
return JSON.stringify({msg: "Data encryption error"});
}
};
Expand All @@ -44,9 +45,8 @@ export class EncryptionPlugin {
if (this._keyPair) {
this._adminPanelPublicKey = new Uint8Array(data);
this._sharedKey = box.before(this._adminPanelPublicKey, this._keyPair.secretKey);
console.log('this._sharedKey',this._sharedKey)
} else {
console.warn("No keypair generated!");
codebudConsoleWarn("No keypair generated!");
}
}
};
26 changes: 26 additions & 0 deletions helperFunctions.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { CONFIG } from "./config";

export function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Expand All @@ -9,4 +11,28 @@ export const stringifyIfNotString = (data: any) => {
}

return JSON.stringify(data);
}

const memo = {
warn: {
data: "",
identicalInARow: 0
}
}

export const codebudConsoleWarn = (...data: any[]) => {
const dataStr = JSON.stringify(data);

if (dataStr === memo.warn.data) {
if (memo.warn.identicalInARow++ < CONFIG.MAX_IDENTICAL_CONSOLE_WARNINGS_IN_A_ROW)
console.warn(`${CONFIG.PRODUCT_NAME}:`, ...data);
} else {
memo.warn.data = dataStr;
memo.warn.identicalInARow = 1;
console.warn(`${CONFIG.PRODUCT_NAME}:`, ...data);
}
}

export const codebudConsoleLog = (...data: any[]) => {
console.log(`${CONFIG.PRODUCT_NAME}:`, ...data);
}
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ declare module '@appklaar/codebud' {

type InstructionPrototype = "login" | "logout";

type ParamType = "number" | "string" | "object" | "array";
type ParamType = "number" | "string" | "object" | "array" | "boolean";

type InstructionPublicFields = {
id: string;
Expand Down
Loading

0 comments on commit bb035f1

Please sign in to comment.