### Setup Development Environment Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Executes a script to set up the local development environment for DeepLX. This may involve configuration or initial setup tasks. ```bash npm run test:setup ``` -------------------------------- ### Start Development Server Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Starts the local development server for DeepLX, allowing for real-time testing and development. This command is typically used during the development phase. ```bash npm run dev ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/xixu-me/deeplx/blob/main/README.md Installs the necessary Node.js dependencies for the DeepLX project using npm. This command should be run after cloning the repository. ```bash npm install ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Installs all necessary Node.js packages for the DeepLX project using npm. This command should be run after cloning the repository. ```bash npm install ``` -------------------------------- ### Environment Configuration Example Source: https://github.com/xixu-me/deeplx/blob/main/SECURITY.md An example JSON configuration for deploying DeepLX, specifying environment variables such as DEBUG_MODE and PROXY_URLS. This configuration is crucial for setting up the API in different environments. ```jsonc { "vars": { "DEBUG_MODE": "false", // Always false in production "PROXY_URLS": "https://your-secure-endpoints.com/jsonrpc" } } ``` -------------------------------- ### Debug Endpoint Usage (curl) Source: https://github.com/xixu-me/deeplx/blob/main/README.md Example of how to send a POST request to the debug endpoint using curl. This demonstrates sending translation text and language codes to the service for debugging purposes. ```curl curl -X POST https://your-domain.workers.dev/debug \ -H "Content-Type: application/json" \ -d '{"text": "test", "source_lang": "EN", "target_lang": "ZH"}' ``` -------------------------------- ### DeepLX Test Writing Structure Source: https://github.com/xixu-me/deeplx/blob/main/tests/README.md A standard template for writing new tests in TypeScript for the DeepLX project, using Jest. It includes setup for mock environments and clearing mocks between tests. ```typescript describe('Module Name', () => { let mockEnv: Env; beforeEach(() => { mockEnv = createMockEnv(); }); afterEach(() => { jest.clearAllMocks(); }); describe('function name', () => { it('should handle normal case', () => { // Test implementation }); it('should handle error case', () => { // Error test implementation }); }); }); ``` -------------------------------- ### Run Tests in Watch Mode Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Starts the test runner in watch mode, which automatically re-runs tests when code changes are detected. This enhances the development workflow. ```bash npm run test:watch ``` -------------------------------- ### DeepLX Enhanced Rate Limiting Configuration Source: https://github.com/xixu-me/deeplx/blob/main/SECURITY.md This TypeScript snippet demonstrates an example of defining enhanced rate limiting constants. It specifies limits per IP per minute, per IP per hour, and global limits per second, which can be used to implement stricter access controls and prevent abuse. ```typescript // Example: Additional rate limiting layers const ENHANCED_RATE_LIMITS = { PER_IP_PER_MINUTE: 60, PER_IP_PER_HOUR: 1000, GLOBAL_PER_SECOND: 100 }; ``` -------------------------------- ### DeepLX Translation Request Validation Function Source: https://github.com/xixu-me/deeplx/blob/main/SECURITY.md This TypeScript example shows a function for validating translation requests. It checks for the presence and type of the 'text' parameter, enforces a maximum text length, and includes a placeholder for checking against suspicious patterns, contributing to input sanitization. ```typescript // Example: Enhanced input validation function validateTranslationRequest(params: any): boolean { return ( params.text && typeof params.text === 'string' && params.text.length <= MAX_TEXT_LENGTH && !containsSuspiciousPatterns(params.text) ); } ``` -------------------------------- ### Run Tests (npm) Source: https://github.com/xixu-me/deeplx/blob/main/README.md Commands to execute various test suites for the project using npm. Includes running all tests, unit tests, integration tests, performance tests, and generating coverage reports. ```bash # Run all tests npm test # Run unit tests npm run test:unit # Run integration tests npm run test:integration # Run performance tests npm run test:performance # Generate coverage report npm run test:coverage ``` -------------------------------- ### Clone DeepLX Repository Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Instructions to clone the DeepLX project repository locally. This is the first step in setting up the development environment. ```bash git clone https://github.com/YOUR_USERNAME/DeepLX.git cd DeepLX ``` -------------------------------- ### Clone DeepLX Repository Source: https://github.com/xixu-me/deeplx/blob/main/README.md Clones the DeepLX project repository from GitHub and navigates into the project directory. This is the first step for self-deployment. ```bash git clone https://github.com/xixu-me/DeepLX.git cd DeepLX ``` -------------------------------- ### Running DeepLX Tests with npm Source: https://github.com/xixu-me/deeplx/blob/main/tests/README.md Commands for executing the DeepLX test suite using npm. Includes options for running all tests, specific categories, coverage reports, CI mode, and development/debugging modes. ```bash npm test # Test Categories # Unit tests only npm run test:unit # Integration tests only npm run test:integration # Performance tests only npm run test:performance # With coverage report npm run test:coverage # Continuous integration mode npm run test:ci # Development Mode # Watch mode for development npm run test:watch # Verbose output for debugging npm run test:verbose # Debug mode with detailed output npm run test:debug ``` -------------------------------- ### Test Environment Utilities Source: https://github.com/xixu-me/deeplx/blob/main/tests/README.md Imports essential utilities for setting up test environments and creating mock data. These helpers streamline the creation of mock translation and error responses for testing. ```typescript import { createMockTranslationResponse, createMockErrorResponse, createTestEnvironment, expectValidTranslationResponse } from './utils/testHelpers'; ``` -------------------------------- ### Run All Tests Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Executes the entire test suite for the DeepLX project. This is a crucial step before submitting changes to ensure code quality. ```bash npm test ``` -------------------------------- ### File Organization Guidelines Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Best practices for structuring files and directories within the DeepLX project to promote modularity and maintainability. ```APIDOC Keep files focused on a single responsibility. Use consistent file naming (kebab-case). Export types and interfaces from dedicated files. Group related functionality in modules. ``` -------------------------------- ### Debugging Test Commands Source: https://github.com/xixu-me/deeplx/blob/main/tests/README.md Provides essential command-line interface (CLI) commands for debugging the test suite. These commands allow running specific test files, enabling debug output, or executing single tests by name. ```bash # Run specific test file npm test -- query.test.ts # Run with debug output npm run test:debug # Run single test npm test -- --testNamePattern="should handle successful translation" ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Runs all tests and generates a code coverage report, indicating which parts of the codebase are covered by tests. ```bash npm run test:coverage ``` -------------------------------- ### Security Guidelines Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Essential security practices to follow when contributing to DeepLX, including handling sensitive information and input validation. ```APIDOC Never commit sensitive information. Use environment variables for configuration. Validate all user inputs. Implement proper error handling. Follow security best practices for APIs. ``` -------------------------------- ### Code Documentation Standards Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Guidelines for documenting code within the DeepLX project, focusing on clarity, completeness, and maintainability. ```APIDOC Add JSDoc comments for public APIs. Document complex algorithms and business logic. Include usage examples in documentation. Keep documentation up to date with code changes. ``` -------------------------------- ### Performance Considerations Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Key considerations for optimizing the performance of the DeepLX project, particularly within the Cloudflare Workers environment. ```APIDOC Optimize for Cloudflare Workers environment. Minimize memory allocations. Use efficient algorithms and data structures. Cache frequently accessed data. Monitor and test performance impact. ``` -------------------------------- ### Code Style Guidelines Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Defines the preferred code formatting and style conventions for the DeepLX project to ensure consistency across the codebase. ```APIDOC Use 2 spaces for indentation. Use single quotes for strings. Add trailing commas in multiline structures. Keep lines under 100 characters. Use meaningful comments for complex logic. ``` -------------------------------- ### Deploy DeepLX to Cloudflare Workers Source: https://github.com/xixu-me/deeplx/blob/main/README.md Deploys the DeepLX application to Cloudflare Workers. 'wrangler dev' is used for local development and testing, while 'wrangler deploy' pushes the application to production. ```bash # Development environment npx wrangler dev # Production deployment npx wrangler deploy ``` -------------------------------- ### TypeScript Guidelines Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Recommendations for writing TypeScript code within the DeepLX project, emphasizing type safety and code clarity. ```APIDOC Use strict TypeScript configuration. Define explicit types for function parameters and returns. Avoid `any` type unless absolutely necessary. Use meaningful variable and function names. Follow consistent naming conventions. ``` -------------------------------- ### Translate Text via JavaScript Fetch API Source: https://github.com/xixu-me/deeplx/blob/main/README.md Shows how to use the JavaScript `fetch` API to call the `/translate` endpoint. It includes setting headers, sending a JSON body, and handling the response. The function supports optional source and target languages. ```javascript async function translate(text, sourceLang = 'auto', targetLang = 'zh') { const response = await fetch('https://dplx.xi-xu.me/translate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ text: text, source_lang: sourceLang, target_lang: targetLang }) }); const result = await response.json(); return result.data; } // Usage example translate('Hello, world!', 'en', 'zh') .then(result => console.log(result)) .catch(error => console.error(error)); ``` -------------------------------- ### Translate Text via cURL Source: https://github.com/xixu-me/deeplx/blob/main/README.md Demonstrates how to send a POST request to the `/translate` endpoint using cURL. It specifies the content type and provides a JSON payload with text, source, and target languages. ```bash curl -X POST https://dplx.xi-xu.me/translate \ -H "Content-Type: application/json" \ -d '{ "text": "Hello, world!", "source_lang": "EN", "target_lang": "ZH" }' ``` -------------------------------- ### Enable Debug Mode Configuration Source: https://github.com/xixu-me/deeplx/blob/main/README.md Configuration snippet to enable debug mode by setting the DEBUG_MODE environment variable. This is typically used for enhanced logging and troubleshooting. ```jsonc { "vars": { "DEBUG_MODE": "true" } } ``` -------------------------------- ### Create Cloudflare KV Namespaces Source: https://github.com/xixu-me/deeplx/blob/main/README.md Creates the 'CACHE_KV' and 'RATE_LIMIT_KV' namespaces required by the Cloudflare Worker. These namespaces are used for caching and rate limiting. After creation, update the 'kv_namespaces' in 'wrangler.jsonc' with the returned IDs. ```bash # Create cache KV namespace npx wrangler kv namespace create "CACHE_KV" # Create rate limit KV namespace npx wrangler kv namespace create "RATE_LIMIT_KV" ``` -------------------------------- ### DeepLX API Endpoint Documentation Source: https://github.com/xixu-me/deeplx/blob/main/README.zh.md Documentation for the DeepLX translation API endpoints, detailing the available methods, request parameters, and expected responses. This section covers the primary translation functionality. ```APIDOC POST /translate Description: Translates text from a source language to a target language. Parameters: - text (string, required): The text content to translate. - source_lang (string, optional, default: 'auto'): The source language code (e.g., 'EN', 'ZH'). 'auto' enables automatic detection. - target_lang (string, required): The target language code (e.g., 'EN', 'ZH'). Request Body: { "text": "string", "source_lang": "string", "target_lang": "string" } Responses: - 200 OK: Content-Type: application/json Body: { "code": 200, "data": "translated text" } - 400 Bad Request: Content-Type: application/json Body: { "code": 400, "message": "Invalid input parameters" } - 500 Internal Server Error: Content-Type: application/json Body: { "code": 500, "message": "Internal server error" } Example: Request: POST /translate Content-Type: application/json Body: { "text": "Hello, world!", "source_lang": "EN", "target_lang": "ZH" } Response (200 OK): Content-Type: application/json Body: { "code": 200, "data": "你好,世界!" } POST /debug Description: Provides debugging information about the service, potentially useful for diagnosing issues. Parameters: None Request Body: None Responses: - 200 OK: Content-Type: application/json Body: (Details of service status and configuration) ``` -------------------------------- ### Run Specific Test Types Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Commands to run specific categories of tests, such as unit, integration, or performance tests, for targeted testing. ```bash npm run test:unit npm run test:integration npm run test:performance ``` -------------------------------- ### DeepLX Configuration - Environment Variables Source: https://github.com/xixu-me/deeplx/blob/main/README.md Details the environment variables that can be configured for the DeepLX service. These variables control aspects like debug mode and proxy endpoint usage. ```APIDOC Environment Variables: DEBUG_MODE: Debug mode switch (Default: false) PROXY_URLS: Proxy endpoint list, comma-separated (Default: None) ``` -------------------------------- ### DeepLX Performance Configuration Source: https://github.com/xixu-me/deeplx/blob/main/README.md Shows performance-related configuration constants defined in src/lib/config.ts. These include request timeouts, retry settings, rate limiting parameters, and payload size limits. ```typescript // Request timeout export const REQUEST_TIMEOUT = 10000; // 10 seconds // Retry configuration export const DEFAULT_RETRY_CONFIG = { maxRetries: 3, // Maximum retry attempts initialDelay: 1000, // Initial delay backoffFactor: 2, // Backoff factor }; // Rate limit configuration export const RATE_LIMIT_CONFIG = { PROXY_TOKENS_PER_SECOND: 8, // Tokens per proxy per second PROXY_MAX_TOKENS: 16, // Maximum tokens per proxy BASE_TOKENS_PER_MINUTE: 480, // Base tokens per minute }; // Payload limits export const PAYLOAD_LIMITS = { MAX_TEXT_LENGTH: 5000, // Maximum text length MAX_REQUEST_SIZE: 32768, // Maximum request size }; ``` -------------------------------- ### Configure Proxy Endpoints for DeepLX Source: https://github.com/xixu-me/deeplx/blob/main/README.md Updates the PROXY_URLS environment variable in wrangler.jsonc to include multiple XDPL proxy endpoints. This enhances performance and stability by distributing the translation load across several deployed instances. ```jsonc { "vars": { "PROXY_URLS": "https://your-xdpl-1.vercel.app/jsonrpc,https://your-xdpl-2.vercel.app/jsonrpc,https://your-xdpl-3.vercel.app/jsonrpc,https://your-xdpl-n.vercel.app/jsonrpc" } } ``` -------------------------------- ### DeepLX API Reference (/translate) Source: https://github.com/xixu-me/deeplx/blob/main/README.md Provides details for the /translate API endpoint, including request method, headers, parameters, response structure, and supported language codes. This endpoint is used to perform text translations. ```APIDOC /translate Request Method: POST Request Headers: Content-Type: application/json Request Parameters: - text (string, Yes): Text to translate - source_lang (string, No, default 'AUTO'): Source language code - target_lang (string, No, default 'EN'): Target language code Response: { "code": 200, "data": "Translation result", "id": "Random identifier", "source_lang": "Detected source language code", "target_lang": "Target language code" } Supported Language Codes: AUTO - Auto-detect (source language only) AR - Arabic BG - Bulgarian CS - Czech DA - Danish DE - German EL - Greek EN - English ES - Spanish ET - Estonian FI - Finnish FR - French HE - Hebrew HU - Hungarian ID - Indonesian IT - Italian JA - Japanese KO - Korean LT - Lithuanian LV - Latvian NB - Norwegian Bokmål NL - Dutch PL - Polish PT - Portuguese RO - Romanian RU - Russian SK - Slovak SL - Slovenian SV - Swedish TH - Thai TR - Turkish UK - Ukrainian VI - Vietnamese ZH - Chinese ``` -------------------------------- ### Lint Code Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Checks the code against predefined style and quality rules using a linter. This command helps maintain code consistency and identify potential issues. ```bash npm run lint ``` -------------------------------- ### Translate Text via cURL Source: https://github.com/xixu-me/deeplx/blob/main/README.zh.md Demonstrates how to send a POST request to the DeepLX translation endpoint using cURL. It specifies the text, source language, and target language in JSON format. ```bash curl -X POST https://dplx.xi-xu.me/translate \ -H "Content-Type: application/json" \ -d '{ "text": "Hello, world!", "source_lang": "EN", "target_lang": "ZH" }' ``` -------------------------------- ### Translate Text via Python Requests Library Source: https://github.com/xixu-me/deeplx/blob/main/README.md Illustrates translating text using the Python `requests` library. It defines a function to send a POST request with a JSON payload to the `/translate` endpoint and handles potential API errors. ```python import requests import json def translate(text, source_lang='auto', target_lang='zh'): url = 'https://dplx.xi-xu.me/translate' data = { 'text': text, 'source_lang': source_lang, 'target_lang': target_lang } response = requests.post(url, json=data) result = response.json() if result['code'] == 200: return result['data'] else: raise Exception(f"Translation failed: {result.get('message', 'Unknown error')}") # Usage example try: result = translate('Hello, world!', 'en', 'zh') print(result) except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Configure Cloudflare Worker Environment Source: https://github.com/xixu-me/deeplx/blob/main/README.md Configures the Cloudflare Worker environment by specifying account ID, worker name, and custom variables like DEBUG_MODE and PROXY_URLS in the wrangler.jsonc file. Ensure YOUR_CLOUDFLARE_ACCOUNT_ID and YOUR_WORKER_NAME are replaced with actual values. ```jsonc { "account_id": "YOUR_CLOUDFLARE_ACCOUNT_ID", "name": "YOUR_WORKER_NAME", "vars": { "DEBUG_MODE": "false", "PROXY_URLS": "your_proxy_endpoint_list,comma_separated" } } ``` -------------------------------- ### DeepLX API: Translate Endpoint Source: https://github.com/xixu-me/deeplx/blob/main/README.md Details the POST `/translate` endpoint for text translation. It accepts JSON payload with text, source language, and target language. The response includes a status code, translated data, and an optional message. ```APIDOC POST /translate Description: Translates text from a source language to a target language. Request Body: Content-Type: application/json Schema: type: object properties: text: (string, required) The text to translate. source_lang: (string, optional, default: 'auto') The source language code (e.g., 'EN', 'ZH'). 'auto' for auto-detection. target_lang: (string, required) The target language code (e.g., 'EN', 'ZH'). Response Body: Content-Type: application/json Schema: type: object properties: code: (integer) HTTP status code (e.g., 200 for success). data: (string) The translated text. message: (string, optional) An error message if code is not 200. Example Request: { "text": "Hello, world!", "source_lang": "EN", "target_lang": "ZH" } Example Success Response: { "code": 200, "data": "你好,世界!" } Example Error Response: { "code": 400, "message": "Invalid target language" } Related Endpoints: POST /debug: For debugging purposes. ``` -------------------------------- ### Custom Logging for Security Events Source: https://github.com/xixu-me/deeplx/blob/main/SECURITY.md Illustrates a JavaScript code snippet for implementing custom logging of security-related events, such as rate limit violations. This helps in monitoring and auditing security incidents. ```javascript // Example: Custom logging for security events if (rateLimitExceeded) { console.log(`Rate limit exceeded for IP: ${hashedIP}`); } ``` -------------------------------- ### Conventional Commits Format Source: https://github.com/xixu-me/deeplx/blob/main/CONTRIBUTING.md Specifies the required format for commit messages, following the Conventional Commits specification. This aids in automated changelog generation and semantic versioning. ```APIDOC type(scope): description [optional body] [optional footer] Types: - feat: A new feature - fix: A bug fix - docs: Documentation only changes - style: Changes that do not affect the meaning of the code - refactor: A code change that neither fixes a bug nor adds a feature - test: Adding missing tests or correcting existing tests - chore: Changes to the build process or auxiliary tools Example: feat(api): add new translation feature Implement new endpoint that accepts multiple text inputs for translation to improve performance for bulk operations. Closes #123 ``` -------------------------------- ### DeepLX API Error Codes Source: https://github.com/xixu-me/deeplx/blob/main/README.md Lists the possible HTTP status codes and their corresponding descriptions for the DeepLX API. These codes indicate the outcome of a translation request. ```APIDOC Error Codes: 200: Translation successful 400: Request parameter error 429: Request rate too high 500: Internal server error 503: Service temporarily unavailable ``` -------------------------------- ### Translate Text with JavaScript Fetch API Source: https://github.com/xixu-me/deeplx/blob/main/README.zh.md Provides a JavaScript function to translate text using the Fetch API. It handles sending the translation request and parsing the JSON response, including error handling. ```javascript async function translate(text, sourceLang = 'auto', targetLang = 'zh') { const response = await fetch('https://dplx.xi-xu.me/translate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ text: text, source_lang: sourceLang, target_lang: targetLang }) }); const result = await response.json(); return result.data; } // 使用示例 translate('Hello, world!', 'en', 'zh') .then(result => console.log(result)) .catch(error => console.error(error)); ``` -------------------------------- ### Custom Jest Matchers for Response Validation Source: https://github.com/xixu-me/deeplx/blob/main/tests/README.md Illustrates custom Jest matchers used within the test suite for asserting the validity of translation and error responses. These matchers simplify the process of checking response structures. ```typescript expect(response).toBeValidTranslationResponse(); expect(response).toBeValidErrorResponse(); ``` -------------------------------- ### Translate Text with Python Requests Source: https://github.com/xixu-me/deeplx/blob/main/README.zh.md A Python function utilizing the requests library to perform translations. It sends a POST request with JSON data and processes the response, raising an exception for translation failures. ```python import requests import json def translate(text, source_lang='auto', target_lang='zh'): url = 'https://dplx.xi-xu.me/translate' data = { 'text': text, 'source_lang': source_lang, 'target_lang': target_lang } response = requests.post(url, json=data) result = response.json() if result['code'] == 200: return result['data'] else: raise Exception(f"翻译失败: {result.get('message', '未知错误')}") # 使用示例 try: result = translate('Hello, world!', 'en', 'zh') print(result) except Exception as e: print(f"错误: {e}") ``` -------------------------------- ### HTTP Security Headers Source: https://github.com/xixu-me/deeplx/blob/main/SECURITY.md Defines essential HTTP security headers returned by the DeepLX API to enhance client-side security. These headers help mitigate common web vulnerabilities like cross-site scripting (XSS) and clickjacking. ```http X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block Referrer-Policy: strict-origin-when-cross-origin Permissions-Policy: geolocation=(), microphone=(), camera=() Content-Security-Policy: default-src 'self'; script-src 'none'; object-src 'none'; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.