Convert Cloudflare Worker to Cloudflare Pages

This commit converts the entire Xget application from a Cloudflare Worker
to a Cloudflare Page, enabling static asset hosting while maintaining all
existing functionality.

Changes:
- Add functions/[[path]].js: Catch-all Pages Function handler
- Add public/index.html: Landing page with Xget information
- Update src/index.js: Export handleRequest for Pages Function import
- Update wrangler.toml: Configure for Pages deployment
- Update package.json: Change scripts to use Pages commands
- Update vitest.config.js: Include functions/ in coverage
- Update .github/workflows/depoly.yml: Deploy to Pages
- Update documentation: CLAUDE.md, README.md, README.en.md

The conversion maintains full backward compatibility with existing tests
and functionality. All caching strategies, security headers, and protocol
handling remain unchanged.
This commit is contained in:
Claude committed 2025-11-16 15:18:34 +00:00
1 parent f74850e5a2
commit eabf0782d4
10 files changed
+240 -35

No files matched your search

+3 -2
View File
@@ -1,4 +1,4 @@
name: Deploy Worker
name: Deploy to Cloudflare Pages
permissions:
contents: read
@@ -25,8 +25,9 @@ jobs:
timeout-minutes: 60
steps:
- uses: actions/checkout@v5
- name: Deploy Worker
- name: Deploy to Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy
+20 -7
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview
Xget is a high-performance acceleration engine for developer resources built on Cloudflare Workers. It provides unified acceleration for code repositories, package managers, container registries, AI inference providers, and more. The application proxies requests to various platforms, applies intelligent caching, and implements security measures while maintaining protocol compliance (Git, Docker/OCI, AI APIs).
Xget is a high-performance acceleration engine for developer resources built on Cloudflare Pages. It provides unified acceleration for code repositories, package managers, container registries, AI inference providers, and more. The application proxies requests to various platforms, applies intelligent caching, and implements security measures while maintaining protocol compliance (Git, Docker/OCI, AI APIs).
**Key Features:**
@@ -65,12 +65,12 @@ npm run format:check
### Deployment
```bash
# Deploy to Cloudflare Workers
# Deploy to Cloudflare Pages
npm run deploy
# or
wrangler deploy
wrangler pages deploy
# Start production preview
# Start local development server
npm start
```
@@ -115,6 +115,19 @@ podman run -p 8080:8080 xget
- Container registries: `cr-docker`, `cr-ghcr`, `cr-gcr`, etc. (prefix: `cr-`)
- `transformPath()` - Converts prefixed URLs to actual platform URLs
**`functions/[[path]].js`** - Cloudflare Pages Function handler
- `onRequest()` - Pages Function entry point that wraps handleRequest
- Catch-all route handler that processes all incoming requests
- Converts Pages Function context to Workers-compatible format
- Delegates to handleRequest for actual processing
**`public/index.html`** - Landing page
- Static HTML page served at the root URL
- Provides information about Xget features and usage examples
- Only served when accessing the root path directly
### Request Flow
```
@@ -186,7 +199,7 @@ podman run -p 8080:8080 xget
## Environment Variables
Configure via Cloudflare Workers environment or `.dev.vars`:
Configure via Cloudflare Pages environment variables or `.dev.vars`:
- `TIMEOUT_SECONDS` - Request timeout (default: 30)
- `MAX_RETRIES` - Max retry attempts (default: 3)
@@ -241,9 +254,9 @@ Configure via Cloudflare Workers environment or `.dev.vars`:
## Deployment Targets
1. **Cloudflare Workers** (primary): Zero-config deployment with global edge network
1. **Cloudflare Pages** (primary): Zero-config deployment with global edge network and built-in static asset hosting
2. **Docker/Podman**: Self-hosted with workerd runtime (see Dockerfile)
3. **Local development**: Wrangler dev server on localhost
3. **Local development**: Wrangler Pages dev server on localhost
## License
+6 -6
View File
@@ -4,7 +4,7 @@
<a href="https://trendshift.io/repositories/14768" target="_blank"><img src="https://trendshift.io/api/badge/repositories/14768" alt="xixu-me%2FXget | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
[![Cloudflare Workers](https://img.shields.io/badge/Cloudflare%20Workers-F38020?&logo=cloudflare&logoColor=white)](#deploy-to-cloudflare-workers)
[![Cloudflare Pages](https://img.shields.io/badge/Cloudflare%20Pages-F38020?&logo=cloudflare&logoColor=white)](#deploy-to-cloudflare-pages)
[![Docker](https://img.shields.io/badge/Docker-2496ED?&logo=docker&logoColor=white)](#self-hosted-deployment)
[![Podman](https://img.shields.io/badge/Podman-892CA0?&logo=podman&logoColor=white)](#self-hosted-deployment)
[![Chromium](https://img.shields.io/badge/Chromium-4285F4?logo=googlechrome&logoColor=white)](#-ecosystem-integration)
@@ -65,7 +65,7 @@ In-depth technical analysis article published: ***[Deep Dive into Xget: A High-P
### ⚡ Extreme Performance - Breaking Through Traditional Accelerator Bottlenecks
- **⚡ Millisecond Response**: Cloudflare's global 330+ edge nodes, average response time < 50ms
- **⚡ Millisecond Response**: Cloudflare Pages' global 330+ edge nodes, average response time < 50ms
- **🌐 HTTP/3 Ultra-Fast Protocol**: Latest HTTP/3 protocol enabled, 40% reduction in connection latency, 30% increase in transmission speed
- **📦 Intelligent Multi-Compression**: Triple compression algorithms (gzip, deflate, brotli), 60% improvement in transmission efficiency
- **🔗 Zero-Latency Pre-Connection**: Connection warm-up and keep-alive, eliminating handshake overhead for second-level responses
@@ -2351,7 +2351,7 @@ client = OpenAI(
## 🚀 Deployment
### Deploy to Cloudflare Workers
### Deploy to Cloudflare Pages
#### Deployment Steps
@@ -2372,16 +2372,16 @@ client = OpenAI(
- Modifying only documentation files (`.md`), `LICENSE`, `.gitignore`, etc. will not trigger deployment
- You can also manually trigger deployment in the GitHub Actions page
5. **Bind custom domain** (optional): Bind your custom domain in the Cloudflare Workers console
5. **Bind custom domain** (optional): Bind your custom domain in the Cloudflare Pages console
After deployment completes, your Xget service will be available at:
- Worker domain: `your-worker-name.your-subdomain.workers.dev`
- Pages domain: `your-project-name.pages.dev`
- Custom domain: `your-domain.com` (if bound)
#### Environment Variable Configuration
You can set the following environment variables in the Cloudflare Workers console to customize configuration:
You can set the following environment variables in the Cloudflare Pages console (Settings → Environment variables) to customize configuration:
- `TIMEOUT_SECONDS`: Request timeout (default: 30)
- `MAX_RETRIES`: Maximum retry count (default: 3)
+7 -7
View File
@@ -4,7 +4,7 @@
<a href="https://trendshift.io/repositories/14768" target="_blank"><img src="https://trendshift.io/api/badge/repositories/14768" alt="xixu-me%2FXget | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
[![Cloudflare Workers](https://img.shields.io/badge/Cloudflare%20Workers-F38020?&logo=cloudflare&logoColor=white)](#部署到-cloudflare-workers)
[![Cloudflare Pages](https://img.shields.io/badge/Cloudflare%20Pages-F38020?&logo=cloudflare&logoColor=white)](#部署到-cloudflare-pages)
[![Docker](https://img.shields.io/badge/Docker-2496ED?&logo=docker&logoColor=white)](#自托管部署)
[![Podman](https://img.shields.io/badge/Podman-892CA0?&logo=podman&logoColor=white)](#自托管部署)
[![Chromium](https://img.shields.io/badge/Chromium-4285F4?logo=googlechrome&logoColor=white)](#-生态系统集成)
@@ -74,7 +74,7 @@
### ⚡ 极速性能 - 突破传统加速器瓶颈
- **⚡ 毫秒级响应**:Cloudflare 全球 330+ 边缘节点,平均响应时间 < 50ms
- **⚡ 毫秒级响应**:Cloudflare Pages 全球 330+ 边缘节点,平均响应时间 < 50ms
- **🌐 HTTP/3 极速协议**:启用最新 HTTP/3 协议,连接延迟降低 40%,传输速度提升 30%
- **📦 智能多重压缩**:gzip、deflate、brotli 三重压缩算法,传输效率提升 60%
- **🔗 零延迟预连接**:连接预热和保持活跃,消除握手开销,实现秒级响应
@@ -2361,14 +2361,14 @@ client = OpenAI(
## 🚀 部署
### 部署到 Cloudflare Workers
### 部署到 Cloudflare Pages
#### 部署步骤
1. **fork 本存储库**:[Fork xixu-me/Xget](https://github.com/xixu-me/Xget/fork)
2. **获取 Cloudflare 凭证**:
- 访问[帐户 API 令牌](https://dash.cloudflare.com/?to=/:account/api-tokens)创建并记录 API 令牌,使用“编辑 Cloudflare Workers”模板
- 访问[帐户 API 令牌](https://dash.cloudflare.com/?to=/:account/api-tokens)创建并记录 API 令牌,使用"编辑 Cloudflare Workers"模板
- 访问 [Workers 和 Pages](https://dash.cloudflare.com/?to=/:account/workers-and-pages) 记录 Account ID
3. **配置 GitHub Secrets**:
@@ -2382,16 +2382,16 @@ client = OpenAI(
- 仅修改文档文件(`.md`)、`LICENSE`、`.gitignore` 等不会触发部署
- 也可以在 GitHub Actions 页面手动触发部署
5. **绑定自定义域名**(可选):在 Cloudflare Workers 控制台中绑定你的自定义域名
5. **绑定自定义域名**(可选):在 Cloudflare Pages 控制台中绑定你的自定义域名
部署完成后,你的 Xget 服务将在以下地址可用:
- Worker 域名:`your-worker-name.your-subdomain.workers.dev`
- Pages 域名:`your-project-name.pages.dev`
- 自定义域名:`your-domain.com`(如果已绑定)
#### 环境变量配置
你可以在 Cloudflare Workers 控制台中设置以下环境变量来自定义配置:
你可以在 Cloudflare Pages 控制台(Settings → Environment variables)中设置以下环境变量来自定义配置:
- `TIMEOUT_SECONDS`:请求超时时间(默认:30)
- `MAX_RETRIES`:最大重试次数(默认:3)
+69
View File
@@ -0,0 +1,69 @@
/**
* Xget - High-performance acceleration engine for developer resources
* Copyright (C) 2025 Xi Xu
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { handleRequest } from '../src/index.js';
/**
* Cloudflare Pages Function handler for all routes.
*
* This catch-all route handler processes all incoming requests to the Xget
* acceleration engine. It delegates request processing to the main handleRequest
* function from the Worker code, maintaining full compatibility with the
* existing implementation.
*
* The [[path]] syntax in the filename creates a catch-all route that matches
* any path, allowing this single function to handle all requests to the Pages
* application.
*
* @param {Object} context - Cloudflare Pages Function context
* @param {Request} context.request - The incoming HTTP request
* @param {Object} context.env - Environment variables and bindings (KV, secrets, etc.)
* @param {Object} context.params - Route parameters (path segments from [[path]])
* @param {Function} context.waitUntil - Extend function execution for background tasks
* @param {Function} context.next - Call next middleware in chain (not used here)
* @param {Object} context.data - Shared data between functions
* @returns {Promise<Response>} The HTTP response to return to the client
*
* @example
* // This is called automatically by Cloudflare Pages
* // User requests: https://xget.pages.dev/npm/lodash
* // Runtime invokes: onRequest(context)
* // Returns: Response with package data
*
* @example
* // Environment variables usage
* // wrangler.toml: [vars] TIMEOUT_SECONDS = "60"
* // context.env contains: { TIMEOUT_SECONDS: "60" }
* // handleRequest uses createConfig(env) to override defaults
*/
export async function onRequest(context) {
// Extract request, env, and create an execution context compatible with Workers
const { request, env, waitUntil } = context;
// Create a minimal ExecutionContext-like object for compatibility
const ctx = {
waitUntil: waitUntil,
passThroughOnException: () => {
// Pages doesn't support passThroughOnException, so this is a no-op
console.warn('passThroughOnException is not supported in Pages Functions');
}
};
// Delegate to the main request handler
return handleRequest(request, env, ctx);
}
+7 -7
View File
@@ -15,13 +15,13 @@
"name": "xget",
"private": false,
"scripts": {
"deploy": "wrangler deploy",
"dev": "wrangler dev",
"format": "prettier --write src/ test/ *.js *.json",
"format:check": "prettier --check src/ test/ *.js *.json",
"lint": "eslint src/ test/",
"lint:fix": "eslint src/ test/ --fix",
"start": "wrangler dev",
"deploy": "wrangler pages deploy",
"dev": "wrangler pages dev public --compatibility-flags=nodejs_compat",
"format": "prettier --write src/ test/ functions/ *.js *.json",
"format:check": "prettier --check src/ test/ functions/ *.js *.json",
"lint": "eslint src/ test/ functions/",
"lint:fix": "eslint src/ test/ functions/ --fix",
"start": "wrangler pages dev public --compatibility-flags=nodejs_compat",
"test": "vitest",
"test:coverage": "vitest run --coverage",
"test:run": "vitest run",
+122
View File
@@ -0,0 +1,122 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Xget - High-performance acceleration engine</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
line-height: 1.6;
color: #333;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.container {
background: white;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
padding: 40px;
max-width: 800px;
width: 100%;
}
h1 {
color: #667eea;
margin-bottom: 20px;
font-size: 2.5em;
}
p {
margin-bottom: 15px;
color: #666;
}
.features {
margin: 30px 0;
}
.features h2 {
color: #764ba2;
margin-bottom: 15px;
font-size: 1.5em;
}
.features ul {
list-style: none;
padding-left: 0;
}
.features li {
padding: 10px 0;
border-bottom: 1px solid #eee;
}
.features li:before {
content: "✓ ";
color: #667eea;
font-weight: bold;
margin-right: 10px;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 3px;
font-family: "Courier New", monospace;
color: #e83e8c;
}
.example {
background: #f8f9fa;
border-left: 4px solid #667eea;
padding: 15px;
margin: 20px 0;
border-radius: 4px;
}
.example h3 {
color: #667eea;
margin-bottom: 10px;
}
.footer {
margin-top: 30px;
padding-top: 20px;
border-top: 2px solid #eee;
text-align: center;
color: #999;
font-size: 0.9em;
}
</style>
</head>
<body>
<div class="container">
<h1>Xget</h1>
<p>High-performance acceleration engine for developer resources built on Cloudflare Pages.</p>
<div class="features">
<h2>Features</h2>
<ul>
<li>Multi-platform support (40+ platforms: GitHub, npm, PyPI, Docker Hub, etc.)</li>
<li>Smart caching with protocol-aware strategies</li>
<li>HTTP Range request support for partial downloads</li>
<li>Container registry authentication proxy</li>
<li>Retry logic with exponential backoff</li>
<li>Comprehensive security headers</li>
</ul>
</div>
<div class="example">
<h3>Usage Examples</h3>
<p><strong>GitHub:</strong> <code>https://your-domain.pages.dev/gh/user/repo/file.txt</code></p>
<p><strong>npm:</strong> <code>https://your-domain.pages.dev/npm/package-name</code></p>
<p><strong>PyPI:</strong> <code>https://your-domain.pages.dev/pypi/package-name</code></p>
<p><strong>Docker:</strong> <code>docker pull your-domain.pages.dev/cr-docker/library/nginx</code></p>
</div>
<div class="footer">
<p>Xget is free software licensed under GPLv3</p>
<p>Powered by Cloudflare Pages Functions</p>
</div>
</div>
</body>
</html>
+1 -1
View File
@@ -739,7 +739,7 @@ function responseUnauthorized(url) {
* const response = await handleRequest(request, env, ctx);
* // Uses 60s timeout and 1-hour cache instead of defaults
*/
async function handleRequest(request, env, ctx) {
export async function handleRequest(request, env, ctx) {
try {
// Create config with environment variable overrides
const config = env ? createConfig(env) : CONFIG;
+1 -1
View File
@@ -19,7 +19,7 @@ export default defineWorkersConfig({
'*.config.js',
'*.config.ts'
],
include: ['src/**/*.js', 'src/**/*.ts'],
include: ['src/**/*.js', 'src/**/*.ts', 'functions/**/*.js', 'functions/**/*.ts'],
thresholds: {
global: {
branches: 80,
+4 -4
View File
@@ -1,12 +1,12 @@
#:schema node_modules/wrangler/config-schema.json
name = "xget"
main = "src/index.js"
pages_build_output_dir = "public"
compatibility_date = "2024-10-22"
compatibility_flags = ["nodejs_compat"]
workers_dev = false
[placement]
mode = "smart"
# Pages-specific configuration
# Functions are automatically loaded from the functions/ directory
# Static assets are served from the public/ directory
[observability]
enabled = false