recoder-shared
Version:
Shared types, utilities, and configurations for Recoder
394 lines • 12.7 kB
JavaScript
"use strict";
/**
* Recoder.xyz Unified SDK
* Cross-platform SDK for all Recoder platforms
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecoderSDK = void 0;
exports.createWebSDK = createWebSDK;
exports.createCLISDK = createCLISDK;
exports.createMobileSDK = createMobileSDK;
exports.createDesktopSDK = createDesktopSDK;
exports.createExtensionSDK = createExtensionSDK;
const tslib_1 = require("tslib");
const events_1 = require("events");
const auth_client_1 = require("./auth-client");
const websocket_client_1 = require("./websocket-client");
const sync_client_1 = require("./sync-client");
const ai_client_1 = require("./ai-client");
const axios_1 = tslib_1.__importDefault(require("axios"));
class RecoderSDK extends events_1.EventEmitter {
constructor(config) {
super();
this.config = {
baseURL: config.baseURL || 'http://localhost:3001',
webSocketURL: config.webSocketURL || 'http://localhost:3001',
platform: config.platform,
deviceName: config.deviceName || `${config.platform}-${Date.now()}`,
enableWebSocket: config.enableWebSocket ?? true,
enableAutoSync: config.enableAutoSync ?? true,
apiKey: config.apiKey || '',
debug: config.debug || false
};
// Initialize API client
this.api = axios_1.default.create({
baseURL: `${this.config.baseURL}/api`,
timeout: 10000,
headers: {
'User-Agent': `Recoder-${config.platform}/${this.getVersion()}`
}
});
// Initialize auth client
this.auth = new auth_client_1.AuthClient(this.config.baseURL);
// Initialize AI client
this.ai = new ai_client_1.AIClient(this.auth, {
platform: this.config.platform,
baseURL: this.config.baseURL,
routingStrategy: 'balanced'
});
// Setup API interceptors
this.setupAPIInterceptors();
// Initialize other clients
this.initializeClients();
// Setup event forwarding
this.setupEventForwarding();
if (this.config.debug) {
console.log('Recoder SDK initialized for platform:', this.config.platform);
}
}
setupAPIInterceptors() {
this.api.interceptors.request.use((config) => {
const tokens = this.auth.getTokens();
if (tokens?.accessToken) {
config.headers.Authorization = `Bearer ${tokens.accessToken}`;
}
return config;
});
this.api.interceptors.response.use((response) => response, (error) => {
if (this.config.debug) {
console.error('API Error:', error.response?.data || error.message);
}
return Promise.reject(error);
});
}
initializeClients() {
// Initialize WebSocket client
if (this.config.enableWebSocket) {
this.websocket = new websocket_client_1.WebSocketClient({
url: this.config.webSocketURL,
authClient: this.auth,
platform: this.config.platform
});
}
// Initialize sync client
this.sync = new sync_client_1.SyncClient({
authClient: this.auth,
webSocketClient: this.websocket,
baseURL: this.config.baseURL,
enableRealTimeSync: this.config.enableWebSocket
});
}
setupEventForwarding() {
// Forward auth events
this.auth.on('authenticated', (data) => {
this.emit('authenticated', data);
this.onAuthenticated();
});
this.auth.on('logout', () => {
this.emit('logout');
this.onLogout();
});
// Forward WebSocket events
if (this.websocket) {
this.websocket.on('connected', () => {
this.emit('websocketConnected');
});
this.websocket.on('disconnected', () => {
this.emit('websocketDisconnected');
});
this.websocket.on('notificationReceived', (notification) => {
this.emit('notification', notification);
});
this.websocket.on('syncUpdated', (data) => {
this.emit('syncUpdate', data);
});
}
// Forward sync events
if (this.sync) {
this.sync.on('syncCompleted', (data) => {
this.emit('syncCompleted', data);
});
this.sync.on('syncError', (data) => {
this.emit('syncError', data);
});
}
// Forward AI events
this.ai.on('requestStarted', (data) => {
this.emit('aiRequestStarted', data);
});
this.ai.on('responseReceived', (data) => {
this.emit('aiResponseReceived', data);
});
this.ai.on('requestFailed', (data) => {
this.emit('aiRequestFailed', data);
});
this.ai.on('providerError', (data) => {
this.emit('aiProviderError', data);
});
}
async onAuthenticated() {
try {
// Register device
await this.auth.registerDevice({
name: this.config.deviceName,
deviceType: this.config.platform,
platform: this.getPlatformDetails()
});
// Connect WebSocket
if (this.websocket) {
await this.websocket.connect();
}
// Start auto sync
if (this.sync && this.config.enableAutoSync) {
await this.sync.startAutoSync();
}
this.emit('ready');
if (this.config.debug) {
console.log('Recoder SDK ready for platform:', this.config.platform);
}
}
catch (error) {
console.error('SDK initialization after auth failed:', error);
this.emit('initError', error);
}
}
onLogout() {
// Disconnect WebSocket
if (this.websocket) {
this.websocket.disconnect();
}
// Stop auto sync
if (this.sync) {
this.sync.stopAutoSync();
}
}
// Public API Methods
async initialize() {
if (this.auth.isAuthenticated()) {
await this.onAuthenticated();
}
}
async connect() {
if (this.websocket && !this.websocket.connected) {
await this.websocket.connect();
}
}
disconnect() {
if (this.websocket) {
this.websocket.disconnect();
}
}
// AI Provider Methods
async getAIProviderStatus() {
try {
const response = await this.api.get('/ai-providers/status');
return response.data.data;
}
catch (error) {
throw this.handleError(error);
}
}
async healthCheckAIProviders() {
try {
const response = await this.api.post('/ai-providers/health-check');
return response.data.data;
}
catch (error) {
throw this.handleError(error);
}
}
async getAIProviderRecommendation(taskType, priority = 'quality') {
try {
const response = await this.api.post('/ai-providers/recommend', {
taskType,
priority
});
return response.data.data;
}
catch (error) {
throw this.handleError(error);
}
}
async getAIProviderCosts(timeframe = 'day') {
try {
const response = await this.api.get('/ai-providers/costs', {
params: { timeframe }
});
return response.data.data;
}
catch (error) {
throw this.handleError(error);
}
}
// Analytics Methods
async trackAnalytics(data) {
try {
await this.api.post('/analytics/track', {
...data,
platform: this.config.platform
});
}
catch (error) {
if (this.config.debug) {
console.error('Analytics tracking failed:', error);
}
// Don't throw - analytics failures shouldn't break the app
}
}
async getAnalyticsDashboard(timeframe = 'day') {
try {
const response = await this.api.get('/analytics/dashboard', {
params: { timeframe, platform: this.config.platform }
});
return response.data.data;
}
catch (error) {
throw this.handleError(error);
}
}
async getPerformanceMetrics() {
try {
const response = await this.api.get('/analytics/performance');
return response.data.data;
}
catch (error) {
throw this.handleError(error);
}
}
async getRealTimeAnalytics() {
try {
const response = await this.api.get('/analytics/realtime');
return response.data.data;
}
catch (error) {
throw this.handleError(error);
}
}
// Notification Methods
async sendNotification(type, title, message, data) {
try {
await this.api.post('/notifications/send', {
type,
title,
message,
data
});
}
catch (error) {
throw this.handleError(error);
}
}
async broadcastNotification(channel, event, type, title, message, data) {
try {
await this.api.post('/notifications/broadcast', {
channel,
event,
type,
title,
message,
data
});
}
catch (error) {
throw this.handleError(error);
}
}
// Utility Methods
isReady() {
return this.auth.isAuthenticated() &&
(!this.config.enableWebSocket || this.websocket?.connected || false);
}
getStatus() {
return {
authenticated: this.auth.isAuthenticated(),
websocketConnected: this.websocket?.connected || false,
autoSyncEnabled: this.sync?.autoSyncEnabled || false,
platform: this.config.platform,
user: this.auth.getUser(),
device: this.auth.getDeviceInfo(),
ai: this.ai.getStatus()
};
}
// Platform Integration Helpers
async switchToPlatform(targetPlatform, context) {
if (this.websocket) {
await this.websocket.notifyPlatformSwitch(this.config.platform, targetPlatform, context);
}
}
async startCollaboration(projectId) {
if (this.websocket) {
await this.websocket.joinCollaboration(projectId);
}
}
async stopCollaboration(projectId) {
if (this.websocket) {
await this.websocket.leaveCollaboration(projectId);
}
}
// Private helpers
getVersion() {
return '2.0.0'; // SDK version
}
getPlatformDetails() {
if (typeof window !== 'undefined' && window && typeof navigator !== 'undefined' && navigator) {
return navigator.userAgent;
}
else if (typeof process !== 'undefined' && process) {
return `${process.platform} ${process.arch}`;
}
return 'unknown';
}
handleError(error) {
const message = error.response?.data?.error?.message || error.message || 'SDK operation failed';
return new Error(message);
}
}
exports.RecoderSDK = RecoderSDK;
// Convenience factory functions for different platforms
function createWebSDK(config = {}) {
return new RecoderSDK({
platform: 'web',
deviceName: 'Web Browser',
...config
});
}
function createCLISDK(config = {}) {
return new RecoderSDK({
platform: 'cli',
deviceName: `CLI - ${require('os').hostname()}`,
...config
});
}
function createMobileSDK(config = {}) {
return new RecoderSDK({
platform: 'mobile',
deviceName: 'Mobile Device',
...config
});
}
function createDesktopSDK(config = {}) {
return new RecoderSDK({
platform: 'desktop',
deviceName: 'Desktop App',
...config
});
}
function createExtensionSDK(config = {}) {
return new RecoderSDK({
platform: 'extension',
deviceName: 'VS Code Extension',
...config
});
}
exports.default = RecoderSDK;
//# sourceMappingURL=recoder-sdk.js.map