This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Xget is a high-performance, security-focused acceleration engine for developer resources. It's a Cloudflare Workers application written in JavaScript that proxies and accelerates access to 40+ platforms including code repositories (GitHub, GitLab), package managers (npm, PyPI, Maven), container registries (Docker Hub, ghcr.io), AI inference providers (OpenAI, Anthropic), and Linux distributions.
Key characteristics:
- Runs on Cloudflare Workers (edge computing platform)
- Single-file architecture: all core logic in
src/index.js(~1500 lines) - Configuration-driven platform support via
src/config/platforms.js - No external dependencies in production (uses only Web APIs and Cloudflare Workers APIs)
- Supports HTTP/3, intelligent caching, retry logic, and performance monitoring
npm run dev # Start local development server with Wrangler
npm start # Alias for npm run devnpm test # Run all tests with Vitest (watch mode)
npm run test:run # Run tests once without watch mode
npm run test:coverage # Generate coverage report (requires 80% threshold)
npm run test:ui # Launch Vitest UI
npm run test:watch # Explicitly run in watch modeRun a single test file:
npx vitest run test/platforms.test.jsRun tests matching a pattern:
npm test -- --grep "GitHub"npm run lint # Run ESLint on src/ and test/
npm run lint:fix # Auto-fix ESLint issues
npm run format # Format code with Prettier
npm run format:check # Check formatting without modifying
npm run type-check # Run TypeScript type checking (no emit)npm run deploy # Deploy to Cloudflare WorkersNote: Deployment requires Cloudflare account and proper wrangler authentication (wrangler login).
-
Request Reception (
src/index.jsfetch handler)- Validates HTTP method (GET/HEAD by default, POST allowed for Git operations)
- Enforces path length limits (max 2048 characters)
- Creates
PerformanceMonitorinstance for timing metrics
-
Platform Detection & URL Transformation
- Extracts platform prefix from URL path (e.g.,
/gh/user/repo→ platform:gh) - Uses
transformPath()fromsrc/config/platforms.jsto convert Xget URL to upstream URL - Platform config in
PLATFORMSobject maps prefixes to base URLs
- Extracts platform prefix from URL path (e.g.,
-
Protocol Detection
- Git detection (
isGitRequest): checks for/info/refs,/git-upload-pack,/git-receive-pack, Git User-Agent - Docker detection (
isDockerRequest): checks for/v2/paths, Docker User-Agent, OCI manifest headers - Git LFS detection (
isGitLFSRequest): checks for.git/info/lfs,application/vnd.git-lfs+json - AI inference detection (
isAIInferenceRequest): checks forip-platform prefix
- Git detection (
-
Caching Layer
- Cache is skipped for Git, Git LFS, Docker, and AI inference requests
- Uses Cloudflare Cache API for HTTP GET/HEAD requests
- Default TTL: 1800 seconds (30 minutes)
- Supports HTTP Range requests with intelligent cache lookup
-
Upstream Fetch with Retry
- Retry logic: max 3 attempts with linear backoff (1000ms × retry count)
- Timeout: 30 seconds per request
- Request headers are proxied (User-Agent, Authorization, Range, etc.)
- Special handling for Git (
service=git-upload-packquery params) and Docker (authentication flow)
-
Response Processing
- Adds security headers (HSTS, CSP, X-Frame-Options, etc.)
- Adds performance metrics via
X-Performance-Metricsheader - Caches successful responses (200-299 status codes)
- Handles CORS for allowed origins
File: src/config/platforms.js
This file contains:
PLATFORMSobject: maps platform prefixes to base URLs (e.g.,gh: 'https://github.com')transformPath(effectivePath, platform)function: converts Xget paths to upstream paths- Handles special cases like container registries (
cr-*platforms) - Strips platform prefix and reconstructs correct upstream URL structure
- Handles special cases like container registries (
Adding a new platform:
- Add entry to
PLATFORMSobject with prefix and base URL - If URL transformation needs special logic, add case in
transformPath() - Add tests in
test/platforms.test.js - Update documentation (README.md)
File: src/config/index.js
The createConfig(env) function creates runtime configuration from environment variables:
TIMEOUT_SECONDS(default: 30)MAX_RETRIES(default: 3)RETRY_DELAY_MS(default: 1000)CACHE_DURATION(default: 1800)ALLOWED_METHODS(default: 'GET,HEAD')ALLOWED_ORIGINS(default: '*')MAX_PATH_LENGTH(default: 2048)
Environment variables are set via Cloudflare Workers dashboard or wrangler.toml.
Framework: Vitest with @cloudflare/vitest-pool-workers (simulates Cloudflare Workers environment)
Test Organization:
test/index.test.js- Core request handling logictest/platforms.test.js- Platform URL transformation logictest/integration.test.js- End-to-end integration teststest/security.test.js- Security validation (headers, input validation)test/performance.test.js- Performance monitoring teststest/range-cache.test.js- HTTP Range request cachingtest/container-registry.test.js- Docker/OCI registry supporttest/[platform].test.js- Platform-specific tests (npm, homebrew, jenkins, etc.)test/helpers/test-utils.js- Shared test utilities and mock helpers
Coverage requirements: 80% minimum (branches, functions, lines, statements)
Important testing notes:
- Tests run in a simulated Cloudflare Workers environment (not Node.js)
- Use
SELF.fetch()to test the worker (provided by vitest-pool-workers) - Mock external fetch calls using
vi.spyOn(globalThis, 'fetch') - Test fixtures in
test/fixtures/for sample responses
Enforced by ESLint + Prettier:
- 2-space indentation
- Single quotes for strings
- Semicolons required
- camelCase for variables/functions
- UPPER_SNAKE_CASE for constants
- PascalCase for classes
- Use JSDoc comments for all exported functions and classes
Example JSDoc:
/**
* Transforms incoming request path to upstream platform URL.
*
* @param {string} effectivePath - The path from the Xget URL
* @param {string} platform - Platform prefix (e.g., 'gh', 'npm')
* @returns {string} Transformed path for upstream request
*
* @example
* transformPath('/gh/user/repo/file.txt', 'gh')
* // Returns: '/user/repo/file.txt'
*/-
Add platform to
src/config/platforms.js:export const PLATFORMS = { // ... existing platforms 'newplatform': 'https://newplatform.com' };
-
If special URL transformation needed, update
transformPath()insrc/config/platforms.js -
Add tests in
test/platforms.test.jsor createtest/newplatform.test.js -
Update README.md with platform prefix and examples
- Wrangler provides local development server with hot reload
- Use
console.log()- output appears in terminal - Performance metrics available via
X-Performance-Metricsresponse header - Use
npm run devand test withcurlor browser
Docker registry protocol requires:
- Authentication flow handling (
/v2/authendpoint) - WWW-Authenticate header parsing
- Token fetching and proxying
- Special MIME types (
application/vnd.docker.distribution.manifest.v2+json)
See isDockerRequest() and Docker-specific logic in src/index.js:800-850.
Git protocol detection checks:
- URL paths:
/info/refs,/git-upload-pack,/git-receive-pack - Query params:
service=git-upload-pack - User-Agent:
git/prefix
Git requests bypass cache to ensure real-time data.
Never disable security headers - they protect against XSS, clickjacking, and MITM attacks.
Input validation:
- Always check path length before processing
- Validate platform prefix exists in
PLATFORMSconfig - Sanitize user input to prevent path traversal
Request method restrictions:
- Default: GET/HEAD only
- Git operations: also allow POST
- Enforce via
ALLOWED_METHODSconfiguration
CORS policy:
- Default allows all origins (
*) - Can be restricted via
ALLOWED_ORIGINSenvironment variable - Always set appropriate CORS headers
Cloudflare Workers (Primary):
- Run
npm run deployafterwrangler login - Configure environment variables in Cloudflare dashboard
- Uses
wrangler.tomlfor worker configuration
Self-hosted (Docker):
- Multi-stage Dockerfile builds worker with Wrangler
- Runs with
workerdruntime (Cloudflare's open-source Workers runtime) - Exposes port 8080
- Uses
config.capnpfor workerd configuration
EdgeOne Pages (Alternative edge platform):
- Similar to Cloudflare Workers
- See README.md for deployment instructions
Key performance features:
- HTTP/3 support (via Cloudflare)
- Brotli/gzip compression
- Connection keep-alive and pre-warming
- Edge caching with 30-minute default TTL
- Parallel retry logic with linear backoff
- Performance monitoring built-in (
PerformanceMonitorclass)
Monitoring metrics:
cache_hit- Successful cache retrievalattempt_N- Nth retry attempt timestampsuccess- Successful upstream fetch- Response includes
X-Performance-Metricswith timing data
Tests failing with "fetch is not defined":
- Ensure using
@cloudflare/vitest-pool-workerspool - Check
vitest.config.jshas correct pool configuration
Wrangler deployment fails:
- Run
wrangler loginfirst - Check
wrangler.tomlconfiguration - Verify Cloudflare account has Workers enabled
Cache not working:
- Ensure not testing Git/Docker/AI requests (cache bypassed)
- Check Cloudflare Workers cache API is available (not available in
wrangler dev) - Verify HTTP status is 2xx
Platform URL transformation incorrect:
- Check
transformPath()logic insrc/config/platforms.js - Add console.log to debug URL construction
- Verify platform prefix matches
PLATFORMSkey