Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,509 changes: 3,382 additions & 127 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"wasm-pack": "^0.13.1"
},
"dependencies": {
"@innerworks-me/iw-auth-sdk": "^1.8.2",
"@telegram-apps/sdk": "^1.1.0",
"@tonconnect/ui": "2.0.5",
"http-server": "14.1.1"
Expand Down
58 changes: 50 additions & 8 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { AnalyticsController } from './controllers/Analytics.controller'
import { NetworkController } from './controllers/Network.controller'
import { SessionController } from './controllers/Session.controller'
import { AnalyticsController } from './controllers/Analytics.controller';
import { NetworkController } from './controllers/Network.controller';
import { SessionController } from './controllers/Session.controller';
import { BatchService } from './services/Batch.service';
import {InvoicePayload} from './declarations/invoice-payload.interface';
import {Events} from './constants';
import { InnerworksSessionService } from './services/InnerworksSession.service';
import { InvoicePayload } from './declarations/invoice-payload.interface';
import { Events } from './constants';

export class App {
private sessionController: SessionController;
private networkController: NetworkController;
private analyticsController: AnalyticsController;
private batchService: BatchService;
private innerworksSessionService: InnerworksSessionService;

private readonly apiToken: string;
private readonly appName: string;
Expand All @@ -25,25 +27,48 @@ export class App {
this.networkController = new NetworkController(this);
this.analyticsController = new AnalyticsController(this);
this.batchService = new BatchService(this);
this.innerworksSessionService = new InnerworksSessionService(env);
}

public async init() {
this.sessionController.init();
await this.analyticsController.init();
this.networkController.init();
this.batchService.init();

if (this.innerworksSessionService) {
await this.innerworksSessionService.initialize();
}
}

public assembleEventSession() {
return this.sessionController.assembleEventSession();
}

public recordEvent(
public async recordEvent(
event_name: string,
data?: Record<string, any>,
attributes?: Record<string, any>,
userId?: string,
) {
return this.networkController.recordEvent(event_name, data, attributes);
let innerworksRequestId: string | undefined;

if (this.innerworksSessionService && this.innerworksSessionService.isServiceEnabled() && userId) {
try {
innerworksRequestId = await this.innerworksSessionService.collectForSession(userId);
} catch (error) {
if (this.env === 'STG') {
console.warn('[Analytics] Failed to collect Innerworks session metrics:', error);
}
}
}

const enrichedData = {
...data,
innerworks_request_id: innerworksRequestId,
};

return this.networkController.recordEvent(event_name, enrichedData, attributes);
}

public recordEvents(
Expand All @@ -52,10 +77,23 @@ export class App {
return this.networkController.recordEvents(data);
}

public collectEvent(event_name: string, requestBody?: Record<string, any>){
public async collectEvent(event_name: string, requestBody?: Record<string, any>, userId?: string){
let innerworksRequestId: string | undefined;

if (this.innerworksSessionService && this.innerworksSessionService.isServiceEnabled() && userId) {
try {
innerworksRequestId = await this.innerworksSessionService.collectForSession(userId);
} catch (error) {
if (this.env === 'STG') {
console.warn('[Analytics] Failed to collect Innerworks session metrics:', error);
}
}
}

this.batchService.collect(event_name, {
...requestBody,
...this.assembleEventSession(),
innerworks_request_id: innerworksRequestId,
});
}

Expand All @@ -73,4 +111,8 @@ export class App {
public getAppName() {
return this.appName;
}

public getInnerworksSessionService(): InnerworksSessionService | undefined {
return this.innerworksSessionService;
}
}
8 changes: 4 additions & 4 deletions src/controllers/Analytics.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,16 @@ export class AnalyticsController {
}
}

public recordEvent(event_name: string, data?: Record<string, any>) {
this.appModule.recordEvent(event_name, data).catch(e => console.error(e));
public recordEvent(event_name: string, data?: Record<string, any>, userId?: string) {
this.appModule.recordEvent(event_name, data, undefined, userId).catch(e => console.error(e));
}

public collectEvent(event_name: string, data?: Record<string, any>) {
public async collectEvent(event_name: string, data?: Record<string, any>, userId?: string) {
if (this.eventsThreshold[event_name] === 0) {
return;
}

this.appModule.collectEvent(event_name, data);
await this.appModule.collectEvent(event_name, data, userId);

if (this.eventsThreshold[event_name]) {
this.eventsThreshold[event_name]--;
Expand Down
14 changes: 14 additions & 0 deletions src/declarations/analytics-event.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export interface AnalyticsEvent {
event_name: string;
data?: Record<string, any>;
attributes?: Record<string, any>;
innerworks_request_id?: string;
timestamp?: number;
session_id?: string;
user_id?: string;
}

export interface BatchedAnalyticsEvent extends AnalyticsEvent {
batch_id?: string;
retry_count?: number;
}
9 changes: 8 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { App } from './app'
import { InvoicePayload } from "./declarations/invoice-payload.interface";
import { AnalyticsEvent, BatchedAnalyticsEvent } from "./declarations/analytics-event.interface";
import { InnerworksSessionService } from "./services/InnerworksSession.service";
import {validateInvoicePayload} from "./validators/invoice-payload.validator";

let __registerInvoice: (invoicePayload: InvoicePayload) => void;
Expand All @@ -22,4 +24,9 @@ async function init({ token, appName, env = 'PROD'}: {
export default {
init,
registerInvoice: (invoicePayload: InvoicePayload) => __registerInvoice(invoicePayload),
};
};

export { App };
export { InvoicePayload };
export { AnalyticsEvent, BatchedAnalyticsEvent };
export { InnerworksSessionService };
109 changes: 109 additions & 0 deletions src/services/Innerworks.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { InnerworksMetrics, InnerworksResponse } from "@innerworks-me/iw-auth-sdk";

export interface InnerworksConfig {
appId: string;
enabled?: boolean;
}

export interface InnerworksResult {
requestId?: string;
success: boolean;
error?: string;
}

export class InnerworksService {
private innerworksMetrics: InnerworksMetrics | null = null;
private config: InnerworksConfig;
private isInitialized: boolean = false;
private env: 'STG' | 'PROD';

constructor(config: InnerworksConfig, env: 'STG' | 'PROD') {
this.config = config;
this.env = env;
}

private log(message: string, ...args: any[]): void {
if (this.env === 'STG') {
console.log(message, ...args);
}
}

private warn(message: string, ...args: any[]): void {
if (this.env === 'STG') {
console.warn(message, ...args);
}
}

private error(message: string, ...args: any[]): void {
if (this.env === 'STG') {
console.error(message, ...args);
}
}

public async initialize(): Promise<void> {
if (this.config.enabled === false) {
this.log('[Innerworks] Service disabled by configuration');
return;
}

if (!this.config.appId) {
this.warn('[Innerworks] App ID not provided, service will not be initialized');
return;
}

try {
this.innerworksMetrics = new InnerworksMetrics({
appId: this.config.appId
});
this.isInitialized = true;
this.log('[Innerworks] Service initialized successfully');
} catch (error) {
this.error('[Innerworks] Failed to initialize:', error);
}
}

public async collectMetrics(userId: string): Promise<InnerworksResult> {
if (!this.isInitialized || !this.innerworksMetrics) {
return {
success: false,
error: 'Innerworks service not initialized'
};
}

try {
const response: InnerworksResponse = await this.innerworksMetrics.send(userId);

if (response.result === 'success') {
const result: InnerworksResult = {
success: true
};

// Extract request ID for fingerprinting
if (response.requestId) {
result.requestId = response.requestId;
}

return result;
} else {
return {
success: false,
error: `Innerworks collection failed: ${response.result}`
};
}
} catch (error) {
this.error('[Innerworks] Error collecting metrics:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
};
}
}

public isServiceEnabled(): boolean {
return this.isInitialized && this.config.enabled !== false;
}

public getConfig(): InnerworksConfig {
return { ...this.config };
}
}
Loading