x2y SDK
Professional SDK for API monitoring and code refactoring
Overview
The x2y SDK is a comprehensive solution for modern software development, combining powerful API monitoring capabilities with intelligent code refactoring. It's designed for developers who want to improve their API integration practices and code quality through automated analysis and suggestions.
With support for both CommonJS and ES6 modules, the x2y SDK integrates seamlessly into any JavaScript or TypeScript project, providing real-time insights into API behavior and actionable code improvement recommendations.
Key Features
API Traffic Monitoring
Record and analyze API calls with detailed metrics
Predictive Issue Analysis
Anticipate API failures before they happen
Code Refactoring Suggestions
Get intelligent suggestions to improve code quality
Performance Optimization
Identify and fix performance bottlenecks
Async Pattern Improvements
Modernize your async code with best practices
Rate Limit Detection
Monitor and predict rate limit approaching
Installation
NPM (Project)
npm install x2y-dev-tools-sdkNPM Global
npm install -g x2y-dev-tools-sdkGitHub (Source)
git clone https://github.com/x2yDevs/x2y-sdk.git
cd x2y-sdk
npm install
npm run buildImport & Setup
Use either CommonJS or ES6 modules to import the SDK:
// ES6 modules
import { X2YSdk } from 'x2y-dev-tools-sdk';
// CommonJS (Node.js)
const { X2YSdk } = require('x2y-dev-tools-sdk');
// Initialize the SDK
const sdk = new X2YSdk();Basic Usage Example
import { X2YSdk } from 'x2y-dev-tools-sdk';
const sdk = new X2YSdk();
// Record API traffic
sdk.recordAPITraffic({
endpoint: '/api/users',
method: 'GET',
timestamp: Date.now(),
responseTime: 200,
statusCode: 200,
headers: { 'x-ratelimit-remaining': '85' }
});
// Predict issues
const prediction = await sdk.predictAPIIssues('/api/users');
console.log(prediction);
// Refactor code
const suggestions = await sdk.refactorCode(`
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
`);
console.log(suggestions);API Monitoring Features
1. Recording API Traffic
Build a dataset by recording API traffic data for predictions:
sdk.recordAPITraffic({
endpoint: '/api/users',
method: 'POST',
timestamp: Date.now(),
responseTime: 250,
statusCode: 201,
headers: {
'x-ratelimit-remaining': '45',
'x-ratelimit-limit': '100',
'content-type': 'application/json'
}
});2. Predicting API Issues
The SDK analyzes recorded traffic to predict potential problems:
const prediction = await sdk.predictAPIIssues('/api/users');
console.log(prediction);
/* Output:
{
endpoint: '/api/users',
riskLevel: 'medium',
predictedFailure: false,
rateLimitApproaching: true,
suggestedAlternatives: ['/api/v2/users', '/api/users?cached=true'],
confidence: 85
}
*/3. Configuration Options
Customize SDK behavior with configuration:
const sdk = new X2YSdk(
{
// API monitoring config
rateLimitThreshold: 80, // Percentage before warning
predictionWindow: 60000, // Time window in ms
apiUrl: 'https://api.example.com'
},
{
// Refactoring config
targetLanguage: 'typescript',
rules: ['performance', 'idiom', 'async']
}
);Code Refactoring Features
1. Refactoring Code Strings
Analyze and get improvement suggestions for code snippets:
const suggestions = await sdk.refactorCode(`
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
`);
console.log(suggestions);
/* Output:
[
{
type: 'idiom',
description: 'Use array methods like forEach() for better readability',
originalCode: 'for (let i = 0; i < arr.length; i++) { ... }',
suggestedCode: 'arr.forEach(item => console.log(item));',
line: 2,
severity: 'medium'
}
]
*/2. Refactoring Entire Files
Refactor complete JavaScript/TypeScript files:
const fileSuggestions = await sdk.refactorFile('./src/example.js');
console.log(`${fileSuggestions.length} suggestions found`);3. Performance Suggestions
Identify performance issues like DOM queries in loops:
const performanceCode = `
for (let i = 0; i < items.length; i++) {
document.getElementById('myElement').innerHTML += items[i];
}
`;
const suggestions = await sdk.refactorCode(performanceCode);
// Will suggest caching the DOM query outside the loop4. Idiom Suggestions
Get recommendations for modern JavaScript/TypeScript idioms:
const oldCode = `
var result = [];
for (var i = 0; i < items.length; i++) {
if (items[i].active) {
result.push(items[i].name);
}
}
`;
const suggestions = await sdk.refactorCode(oldCode);
// Will suggest: items.filter(item => item.active).map(item => item.name)5. Async Pattern Improvements
Modernize async code with async/await:
const oldAsyncCode = `
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
`;
const suggestions = await sdk.refactorCode(oldAsyncCode);
// Will suggest using async/await instead of promise chainsIntegration Examples
Fetch API Integration
Monitor and predict issues with Fetch API calls:
const originalFetch = window.fetch;
window.fetch = async (...args) => {
const start = Date.now();
const response = await originalFetch(...args);
const duration = Date.now() - start;
// Record the traffic
sdk.recordAPITraffic({
endpoint: args[0].toString(),
method: 'GET',
timestamp: Date.now(),
responseTime: duration,
statusCode: response.status,
headers: Object.fromEntries(response.headers.entries())
});
// Predict if next calls might fail
const prediction = await sdk.predictAPIIssues(args[0].toString());
if (prediction.riskLevel === 'high') {
console.warn('High risk detected for:', args[0]);
}
return response;
};Advanced Configuration
Custom Refactoring Rules
const sdk = new X2YSdk(
{}, // API config
{
targetLanguage: 'typescript',
rules: ['performance', 'idiom', 'async'] // Available rule sets
}
);Auto-Refactoring
Enable automatic refactoring by setting environment variable:
export X2Y_AUTO_REFACTOR=true
# This will automatically apply high-severity refactoring suggestions