Spaces:
Running
Running
Upload ef22-black.png
#519
by PetePatel - opened
This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50)
- .env.exampleDeleted-4
- .github/workflows/deploy-prod.ymlDeleted-77
- .gitignore+1-7
- Dockerfile+6-9
- MCP-SERVER.mdAdded+428
- README.md+11-8
- actions/mentions.tsDeleted-31
- actions/projects.tsDeleted-175
- app/(public)/layout.tsx+4-3
- app/(public)/page.tsx+3-23
- app/(public)/signin/page.tsxDeleted-21
- app/[namespace]/[repoId]/page.tsxAdded+28
- app/[owner]/[repoId]/page.tsxDeleted-35
- app/actions/auth.tsAdded+18
- app/actions/projects.tsAdded+47
- app/api/ask/route.ts+361-135
- app/api/auth/[...nextauth]/route.tsDeleted-6
- app/api/auth/login-url/route.tsAdded+21
- app/api/auth/logout/route.tsAdded+25
- app/api/auth/route.tsAdded+86
- app/api/healthcheck/route.tsDeleted-5
- app/api/mcp/route.tsAdded+435
- app/api/me/projects/[namespace]/[repoId]/commits/[commitId]/promote/route.tsAdded+230
- app/api/me/projects/[namespace]/[repoId]/commits/[commitId]/route.tsAdded+102
- app/api/me/projects/[namespace]/[repoId]/images/route.tsAdded+125
- app/api/me/projects/[namespace]/[repoId]/route.tsAdded+197
- app/api/me/projects/[namespace]/[repoId]/save/route.tsAdded+72
- app/api/me/projects/[namespace]/[repoId]/update/route.tsAdded+141
- app/api/me/projects/route.tsAdded+121
- app/api/me/route.tsAdded+46
- app/api/projects/[repoId]/[commitId]/route.tsDeleted-49
- app/api/projects/[repoId]/download/route.tsDeleted-76
- app/api/projects/[repoId]/medias/route.tsDeleted-87
- app/api/projects/[repoId]/rename/route.tsDeleted-92
- app/api/projects/[repoId]/route.tsDeleted-104
- app/api/projects/route.tsDeleted-145
- app/api/redesign/route.ts → app/api/re-design/route.tsRenamed+14-16
- app/auth/callback/page.tsxAdded+97
- app/auth/page.tsxAdded+28
- app/layout.tsx+69-32
- app/new/page.tsx+10-14
- app/not-found.tsxDeleted-17
- app/sitemap.tsAdded+28
- app/globals.css → assets/globals.cssRenamed+236-33
- assets/hf-logo.svgDeleted
- assets/logo.svgAdded
- assets/pro.svgDeleted
- chart/Chart.yamlDeleted-5
- chart/env/prod.yamlDeleted-59
- chart/templates/_helpers.tplDeleted-22
1234AUTH_HUGGINGFACE_ID=AUTH_HUGGINGFACE_SECRET=NEXTAUTH_URL=http://localhost:3001AUTH_SECRET=1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677name: Deploy to k8son: # run this workflow manually from the Actions tab workflow_dispatch:
jobs: build-and-publish: runs-on: group: cpu-high steps: - name: Checkout uses: actions/checkout@v4
- name: Login to Registry uses: docker/login-action@v3 with: registry: registry.internal.huggingface.tech username: ${{ secrets.DOCKER_INTERNAL_USERNAME }} password: ${{ secrets.DOCKER_INTERNAL_PASSWORD }}
- name: Docker metadata id: meta uses: docker/metadata-action@v5 with: images: | registry.internal.huggingface.tech/deepsite/deepsite tags: | type=raw,value=latest,enable={{is_default_branch}} type=sha,enable=true,prefix=sha-,format=short,sha-len=8
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Inject slug/short variables uses: rlespinasse/github-slug-action@v4
- name: Build and Publish image uses: docker/build-push-action@v5 with: context: . file: Dockerfile push: ${{ github.event_name != 'pull_request' }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} platforms: linux/amd64 cache-to: type=gha,mode=max,scope=amd64 cache-from: type=gha,scope=amd64 provenance: false
deploy: name: Deploy on prod runs-on: ubuntu-latest needs: ["build-and-publish"] steps: - name: Inject slug/short variables uses: rlespinasse/github-slug-action@v4
- name: Gen values run: | VALUES=$(cat <<-END image: tag: "sha-${{ env.GITHUB_SHA_SHORT }}" END ) echo "VALUES=$(echo "$VALUES" | yq -o=json | jq tostring)" >> $GITHUB_ENV
- name: Deploy on infra-deployments uses: the-actions-org/workflow-dispatch@v2 with: workflow: Update application single value repo: huggingface/infra-deployments wait-for-completion: true wait-for-completion-interval: 10s display-workflow-run-url-interval: 10s ref: refs/heads/main token: ${{ secrets.GIT_TOKEN_INFRA_DEPLOYMENT }} inputs: '{"path": "hub/deepsite/deepsite.yaml", "value": ${{ env.VALUES }}, "url": "${{ github.event.head_commit.url }}"}'30 unmodified lines313233343536371 unmodified line39404142434445464730 unmodified lines.pnpm-debug.log*# env files (can opt-in for committing if needed).env# vercel.vercel1 unmodified line# typescript*.tsbuildinfonext-env.d.ts.idea# binary assets (hosted on CDN)assets/assistant.jpg.gitattributes30 unmodified lines313233343536371 unmodified line39404130 unmodified lines.pnpm-debug.log*# env files (can opt-in for committing if needed).env*# vercel.vercel1 unmodified line# typescript*.tsbuildinfonext-env.d.ts
12345678910111213141516171819202122FROM node:20-alpineUSER root# Install pnpmRUN corepack enable && corepack prepare pnpm@latest --activateUSER 1000WORKDIR /usr/src/app# Copy package.json and pnpm-lock.yaml to the containerCOPY --chown=1000 package.json pnpm-lock.yaml ./# Copy the rest of the application files to the containerCOPY --chown=1000 . .RUN pnpm installRUN pnpm run build# Expose the application port (assuming your app runs on port 3000)EXPOSE 3001# Start the applicationCMD ["pnpm", "start"]12345678910111213141516171819FROM node:20-alpineUSER rootUSER 1000WORKDIR /usr/src/app# Copy package.json and package-lock.json to the containerCOPY --chown=1000 package.json package-lock.json ./# Copy the rest of the application files to the containerCOPY --chown=1000 . .RUN npm installRUN npm run build# Expose the application port (assuming your app runs on port 3000)EXPOSE 3000# Start the applicationCMD ["npm", "start"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428# DeepSite MCP Server
DeepSite is now available as an MCP (Model Context Protocol) server, enabling AI assistants like Claude to create websites directly using natural language.
## Two Ways to Use DeepSite MCP
**Quick Comparison:**
| Feature | Option 1: HTTP Server | Option 2: Local Server ||---------|----------------------|------------------------|| **Setup Difficulty** | ✅ Easy (just config) | ⚠️ Requires installation || **Authentication** | HF Token in config header | HF Token or session cookie in env || **Best For** | Most users | Developers, custom modifications || **Maintenance** | ✅ Always up-to-date | Need to rebuild for updates |
**Recommendation:** Use Option 1 (HTTP Server) unless you need to modify the MCP server code.
---
### 🌐 Option 1: HTTP Server (Recommended)
**No installation required!** Use DeepSite's hosted MCP server.
#### Setup for Claude Desktop
Add to your Claude Desktop configuration file:
**MacOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
```json{ "mcpServers": { "deepsite": { "url": "https://huggingface.co/deepsite/api/mcp", "transport": { "type": "sse" }, "headers": { "Authorization": "Bearer hf_your_token_here" } } }}```
**Getting Your Hugging Face Token:**
1. Go to https://huggingface.co/settings/tokens2. Create a new token with `write` access3. Copy the token4. Add it to the `Authorization` header in your config (recommended for security)5. Alternatively, you can pass it as the `hf_token` parameter when using the tool
**⚠️ Security Recommendation:** Use the `Authorization` header in your config instead of passing the token in chat. This keeps your token secure and out of conversation history.
#### Example Usage with Claude
> "Create a portfolio website using DeepSite. Include a hero section, about section, and contact form."
Claude will automatically:1. Use the `create_project` tool2. Authenticate using the token from your config3. Create the website on Hugging Face Spaces4. Return the URLs to access your new site
---
### 💻 Option 2: Local Server
Run the MCP server locally for more control or offline use.
> **Note:** Most users should use Option 1 (HTTP Server) instead. Option 2 is only needed if you want to run the MCP server locally or modify its behavior.
#### Installation
```bashcd mcp-servernpm installnpm run build```
#### Setup for Claude Desktop
**Method A: Using HF Token (Recommended)**
```json{ "mcpServers": { "deepsite-local": { "command": "node", "args": ["/absolute/path/to/deepsite-v3/mcp-server/dist/index.js"], "env": { "HF_TOKEN": "hf_your_token_here", "DEEPSITE_API_URL": "https://huggingface.co/deepsite" } } }}```
**Method B: Using Session Cookie (Alternative)**
```json{ "mcpServers": { "deepsite-local": { "command": "node", "args": ["/absolute/path/to/deepsite-v3/mcp-server/dist/index.js"], "env": { "DEEPSITE_AUTH_COOKIE": "your-session-cookie", "DEEPSITE_API_URL": "https://huggingface.co/deepsite" } } }}```
**Getting Your Session Cookie (Method B only):**
1. Log in to https://huggingface.co/deepsite2. Open Developer Tools (F12)3. Go to Application → Cookies4. Copy the session cookie value5. Set as `DEEPSITE_AUTH_COOKIE` in the config
---
## Available Tools
### `create_project`
Creates a new DeepSite project with HTML/CSS/JS files.
**Parameters:**
| Parameter | Type | Required | Description ||-----------|------|----------|-------------|| `title` | string | No | Project title (defaults to "DeepSite Project") || `pages` | array | Yes | Array of file objects with `path` and `html` || `prompt` | string | No | Commit message/description || `hf_token` | string | No* | Hugging Face API token (*optional if provided via Authorization header in config) |
**Page Object:**```typescript{ path: string; // e.g., "index.html", "styles.css", "script.js" html: string; // File content}```
**Returns:**```json{ "success": true, "message": "Project created successfully!", "projectUrl": "https://huggingface.co/deepsite/username/project-name", "spaceUrl": "https://huggingface.co/spaces/username/project-name", "liveUrl": "https://username-project-name.hf.space", "spaceId": "username/project-name", "projectId": "space-id", "files": ["index.html", "styles.css"]}```
---
## Example Prompts for Claude
### Simple Landing Page> "Create a modern landing page for my SaaS product using DeepSite. Include a hero section with CTA, features grid, and footer. Use gradient background."
### Portfolio Website> "Build a portfolio website with DeepSite. I need:> - Hero section with my name and photo> - Projects gallery with 3 sample projects> - Skills section with tech stack> - Contact form> Use dark mode with accent colors."
### Blog Homepage> "Create a blog homepage using DeepSite. Include:> - Header with navigation> - Featured post section> - Grid of recent posts (3 cards)> - Sidebar with categories> - Footer with social links> Clean, minimal design."
### Interactive Dashboard> "Make an analytics dashboard with DeepSite:> - Sidebar navigation> - 4 metric cards at top> - 2 chart placeholders> - Data table> - Modern, professional UI with charts.css"
---
## Direct API Usage
You can also call the HTTP endpoint directly:
### Using Authorization Header (Recommended)
```bashcurl -X POST https://huggingface.co/deepsite/api/mcp \ -H "Content-Type: application/json" \ -H "Authorization: Bearer hf_your_token_here" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "create_project", "arguments": { "title": "My Website", "pages": [ { "path": "index.html", "html": "<!DOCTYPE html><html><head><title>Hello</title></head><body><h1>Hello World!</h1></body></html>" } ] } } }'```
### Using Token Parameter (Fallback)
```bashcurl -X POST https://huggingface.co/deepsite/api/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "create_project", "arguments": { "title": "My Website", "pages": [ { "path": "index.html", "html": "<!DOCTYPE html><html><head><title>Hello</title></head><body><h1>Hello World!</h1></body></html>" } ], "hf_token": "hf_xxxxx" } } }'```
### List Available Tools
```bashcurl -X POST https://huggingface.co/deepsite/api/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} }'```
---
## Testing
### Test Local Server
```bashcd mcp-server./test.sh```
### Test HTTP Server
```bashcurl -X POST https://huggingface.co/deepsite/api/mcp \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'```
---
## Migration Guide: From Parameter to Header Auth
If you're currently passing the token as a parameter in your prompts, here's how to migrate to the more secure header-based authentication:
### Step 1: Update Your Config
Edit your Claude Desktop config file and add the `headers` section:
```json{ "mcpServers": { "deepsite": { "url": "https://huggingface.co/deepsite/api/mcp", "transport": { "type": "sse" }, "headers": { "Authorization": "Bearer hf_your_actual_token_here" } } }}```
### Step 2: Restart Claude Desktop
Completely quit and restart Claude Desktop for the changes to take effect.
### Step 3: Use Simpler Prompts
Now you can simply say:> "Create a portfolio website with DeepSite"
Instead of:> "Create a portfolio website with DeepSite using token `hf_xxxxx`"
Your token is automatically included in all requests via the header!
---
## Security Notes
### HTTP Server (Option 1)- **✅ Recommended:** Store your HF token in the `Authorization` header in your Claude Desktop config- The token is stored locally on your machine and never exposed in chat- The token is sent with each request but only used to authenticate with Hugging Face API- DeepSite does not store your token- Use tokens with minimal required permissions (write access to spaces)- You can revoke tokens anytime at https://huggingface.co/settings/tokens- **⚠️ Fallback:** You can still pass the token as a parameter, but this is less secure as it appears in conversation history
### Local Server (Option 2)- Use `HF_TOKEN` environment variable (same security as Option 1)- Or use `DEEPSITE_AUTH_COOKIE` if you prefer session-based auth- All authentication data stays on your local machine- Better for development and testing- No need for both HTTP Server and Local Server - choose one!
---
## Troubleshooting
### "Invalid Hugging Face token"- Verify your token at https://huggingface.co/settings/tokens- Ensure the token has write permissions- Check that you copied the full token (starts with `hf_`)
### "At least one page is required"- Make sure you're providing the `pages` array- Each page must have both `path` and `html` properties
### "Failed to create project"- Check your token permissions- Ensure the project title doesn't conflict with existing spaces- Verify your Hugging Face account is in good standing
### Claude doesn't see the tool- Restart Claude Desktop after modifying the config- Check that the JSON config is valid (no trailing commas)- For HTTP: verify the URL is correct- For local: check the absolute path to index.js
---
## Architecture
### HTTP Server Flow```Claude Desktop ↓ (HTTP Request) ↓huggingface.co/deepsite/api/mcp ↓Hugging Face API (with user's token) ↓New Space Created ↓URLs returned to Claude```
### Local Server Flow```Claude Desktop ↓ (stdio transport) ↓Local MCP Server ↓ (HTTP to DeepSite API) ↓huggingface.co/deepsite/api/me/projects ↓New Space Created```
---
## Contributing
The MCP server implementation lives in:- HTTP Server: `/app/api/mcp/route.ts`- Local Server: `/mcp-server/index.ts`
Both use the same core DeepSite logic for creating projects - no duplication!
---
## License
MIT
---
## Resources
- [Model Context Protocol Spec](https://modelcontextprotocol.io/)- [DeepSite Documentation](https://huggingface.co/deepsite)- [Hugging Face Spaces](https://huggingface.co/docs/hub/spaces)- [Claude Desktop](https://claude.ai/desktop)
123456789101112131415161718192021---title: DeepSite v4emoji: 🐳colorFrom: bluecolorTo: bluesdk: dockerpinned: trueapp_port: 3001license: mitfailure_strategy: rollbackshort_description: Generate any application by Vibe Coding itmodels:- deepseek-ai/DeepSeek-V3-0324- deepseek-ai/DeepSeek-V3.2- Qwen/Qwen3-Coder-30B-A3B-Instruct- moonshotai/Kimi-K2-Instruct-0905- zai-org/GLM-4.7- MiniMaxAI/MiniMax-M2.1---# DeepSite 🐳123456789101112131415161718192021222324---title: DeepSite v3emoji: 🐳colorFrom: bluecolorTo: bluesdk: dockerpinned: trueapp_port: 3000license: mitshort_description: Generate any application by Vibe Codingmodels:- deepseek-ai/DeepSeek-V3-0324- deepseek-ai/DeepSeek-R1-0528- deepseek-ai/DeepSeek-V3.1- deepseek-ai/DeepSeek-V3.1-Terminus- deepseek-ai/DeepSeek-V3.2-Exp- Qwen/Qwen3-Coder-480B-A35B-Instruct- moonshotai/Kimi-K2-Instruct- moonshotai/Kimi-K2-Instruct-0905- zai-org/GLM-4.6- MiniMaxAI/MiniMax-M2---# DeepSite 🐳
12345678910111213141516171819202122232425262728293031"use client";
import { File } from "@/lib/type";
export const searchMentions = async (query: string) => { const promises = [searchModels(query), searchDatasets(query)]; const results = await Promise.all(promises); return { models: results[0], datasets: results[1] };};
const searchModels = async (query: string) => { const response = await fetch( `https://huggingface.co/api/quicksearch?q=${query}&type=model&limit=3` ); const data = await response.json(); return data?.models ?? [];};
const searchDatasets = async (query: string) => { const response = await fetch( `https://huggingface.co/api/quicksearch?q=${query}&type=dataset&limit=3` ); const data = await response.json(); return data?.datasets ?? [];};
export const searchFilesMentions = async (query: string, files: File[]) => { if (!query) return files; const lowerQuery = query.toLowerCase(); return files.filter((file) => file.path.toLowerCase().includes(lowerQuery));};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175"use server";import { downloadFile, listCommits, listFiles, listSpaces, RepoDesignation, SpaceEntry, spaceInfo,} from "@huggingface/hub";
import { auth } from "@/lib/auth";import { Commit, File } from "@/lib/type";
export interface ProjectWithCommits extends SpaceEntry { commits?: Commit[]; medias?: string[];}
const IGNORED_PATHS = ["README.md", ".gitignore", ".gitattributes"];const IGNORED_FORMATS = [ ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".mp4", ".mp3", ".wav",];
export const getProjects = async () => { const projects: SpaceEntry[] = []; const session = await auth(); if (!session?.user) { return projects; } const token = session.accessToken; for await (const space of listSpaces({ accessToken: token, additionalFields: ["author", "cardData"], search: { owner: session.user.username, }, })) { if ( space.sdk === "static" && Array.isArray((space.cardData as { tags?: string[] })?.tags) && (space.cardData as { tags?: string[] })?.tags?.some((tag) => tag.includes("deepsite") ) ) { projects.push(space); } } return projects;};export const getProject = async (id: string, commitId?: string) => { const session = await auth(); if (!session?.user) { return null; } const token = session.accessToken; try { const project: ProjectWithCommits | null = await spaceInfo({ name: id, accessToken: token, additionalFields: ["author", "cardData"], }); const repo: RepoDesignation = { type: "space", name: id, }; const files: File[] = []; const medias: string[] = []; const params = { repo, accessToken: token }; if (commitId) { Object.assign(params, { revision: commitId }); } for await (const fileInfo of listFiles(params)) { if (IGNORED_PATHS.includes(fileInfo.path)) continue; if (IGNORED_FORMATS.some((format) => fileInfo.path.endsWith(format))) { medias.push( `https://huggingface.co/spaces/${id}/resolve/main/${fileInfo.path}` ); continue; }
if (fileInfo.type === "directory") { for await (const subFile of listFiles({ repo, accessToken: token, path: fileInfo.path, })) { if (IGNORED_FORMATS.some((format) => subFile.path.endsWith(format))) { medias.push( `https://huggingface.co/spaces/${id}/resolve/main/${subFile.path}` ); } const blob = await downloadFile({ repo, accessToken: token, path: subFile.path, raw: true, ...(commitId ? { revision: commitId } : {}), }).catch((_) => { return null; }); if (!blob) { continue; } const html = await blob?.text(); if (!html) { continue; } files[subFile.path === "index.html" ? "unshift" : "push"]({ path: subFile.path, content: html, }); } } else { const blob = await downloadFile({ repo, accessToken: token, path: fileInfo.path, raw: true, ...(commitId ? { revision: commitId } : {}), }).catch((_) => { return null; }); if (!blob) { continue; } const html = await blob?.text(); if (!html) { continue; } files[fileInfo.path === "index.html" ? "unshift" : "push"]({ path: fileInfo.path, content: html, }); } } const commits: Commit[] = []; const commitIterator = listCommits({ repo, accessToken: token }); for await (const commit of commitIterator) { if ( commit.title?.toLowerCase() === "initial commit" || commit.title ?.toLowerCase() ?.includes("upload media files through deepsite") ) continue; commits.push({ title: commit.title, oid: commit.oid, date: commit.date, }); if (commits.length >= 20) { break; } }
project.commits = commits; project.medias = medias;
return { project, files }; } catch (error) { return { project: null, files: [], }; }};123456789101112import { Navigation } from "@/components/public/navigation";export default function PublicLayout({children,}: Readonly<{children: React.ReactNode;}>) {return (<div className="min-h-screen font-sans"><Navigation />{children}</div>12345678910111213import Navigation from "@/components/public/navigation";export default async function PublicLayout({children,}: Readonly<{children: React.ReactNode;}>) {return (<div className="h-screen bg-neutral-950 z-1 relative overflow-auto scroll-smooth"><div className="background__noisy" /><Navigation />{children}</div>
12345678910111213141516171819202122232425import { AnimatedDotsBackground } from "@/components/public/animated-dots-background";import { HeroHeader } from "@/components/public/hero-header";import { UserProjects } from "@/components/projects/user-projects";import { AskAiLanding } from "@/components/ask-ai/ask-ai-landing";import { Bento } from "@/components/public/bento";export const dynamic = "force-dynamic";export default async function Homepage() {return (<><section className="container mx-auto relative z-10"><HeroHeader /><div className="absolute inset-0 -z-10"><AnimatedDotsBackground /></div><div className="max-w-xl mx-auto px-6"><AskAiLanding /></div></section><UserProjects /><Bento /></>);}12345import { MyProjects } from "@/components/my-projects";export default async function HomePage() {return <MyProjects />;}
123456789101112131415161718192021import { LoginButtons } from "@/components/login/login-buttons";
export default async function SignInPage({ searchParams,}: { searchParams: Promise<{ callbackUrl: string }>;}) { const { callbackUrl } = await searchParams; console.log(callbackUrl); return ( <section className="min-h-screen font-sans"> <div className="px-6 py-16 max-w-5xl mx-auto text-center"> <h1 className="text-5xl font-bold mb-5">You shall not pass 🧙</h1> <p className="text-lg text-muted-foreground mb-8"> You can't access this resource without being signed in. </p> <LoginButtons callbackUrl={callbackUrl ?? "/"} /> </div> </section> );}12345678910111213141516171819202122232425262728import { AppEditor } from "@/components/editor";import { generateSEO } from "@/lib/seo";import { Metadata } from "next";
export async function generateMetadata({ params,}: { params: Promise<{ namespace: string; repoId: string }>;}): Promise<Metadata> { const { namespace, repoId } = await params;
return generateSEO({ title: `${namespace}/${repoId} - DeepSite Editor`, description: `Edit and build ${namespace}/${repoId} with AI-powered tools on DeepSite. Create stunning websites with no code required.`, path: `/${namespace}/${repoId}`, // Prevent indexing of individual project editor pages if they contain sensitive content noIndex: false, // Set to true if you want to keep project pages private });}
export default async function ProjectNamespacePage({ params,}: { params: Promise<{ namespace: string; repoId: string }>;}) { const { namespace, repoId } = await params; return <AppEditor namespace={namespace} repoId={repoId} />;}1234567891011121314151617181920212223242526272829303132333435import { getProject } from "@/actions/projects";import { AppEditor } from "@/components/editor";import { auth } from "@/lib/auth";import { notFound, redirect } from "next/navigation";
export default async function ProjectPage({ params, searchParams,}: { params: Promise<{ owner: string; repoId: string }>; searchParams: Promise<{ commit?: string }>;}) { const session = await auth();
const { owner, repoId } = await params; const { commit } = await searchParams; if (!session) { redirect( `/api/auth/signin?callbackUrl=/${owner}/${repoId}${ commit ? `?commit=${commit}` : "" }` ); } const datas = await getProject(`${owner}/${repoId}`, commit); if (!datas?.project) { return notFound(); } return ( <AppEditor project={datas.project} files={datas.files ?? []} isHistoryView={!!commit} /> );}123456789101112131415161718"use server";
import { headers } from "next/headers";
export async function getAuth() { const authList = await headers(); const host = authList.get("host") ?? "localhost:3000"; const url = host.includes("/spaces/enzostvs") ? "enzostvs-deepsite.hf.space" : host; const redirect_uri = `${host.includes("localhost") ? "http://" : "https://"}` + url + "/deepsite/auth/callback";
const loginRedirectUrl = `https://huggingface.co/oauth/authorize?client_id=${process.env.OAUTH_CLIENT_ID}&redirect_uri=${redirect_uri}&response_type=code&scope=openid%20profile%20write-repos%20manage-repos%20inference-api&prompt=consent&state=1234567890`; return loginRedirectUrl;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"use server";
import { isAuthenticated } from "@/lib/auth";import { NextResponse } from "next/server";import { listSpaces } from "@huggingface/hub";import { ProjectType } from "@/types";
export async function getProjects(): Promise<{ ok: boolean; projects: ProjectType[]; isEmpty?: boolean;}> { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return { ok: false, projects: [], }; }
const projects = []; for await (const space of listSpaces({ accessToken: user.token as string, additionalFields: ["author", "cardData"], search: { owner: user.name, } })) { if ( !space.private && space.sdk === "static" && Array.isArray((space.cardData as { tags?: string[] })?.tags) && ( ((space.cardData as { tags?: string[] })?.tags?.includes("deepsite-v3")) || ((space.cardData as { tags?: string[] })?.tags?.includes("deepsite")) ) ) { projects.push(space); } }
return { ok: true, projects, };}123456789101112131415161718192021222324252627282930313233343536377 unmodified lines45464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183import { NextResponse } from "next/server";import { InferenceClient } from "@huggingface/inference";import { FOLLOW_UP_SYSTEM_PROMPT, INITIAL_SYSTEM_PROMPT } from "@/lib/prompts";import { auth } from "@/lib/auth";import { File, Message } from "@/lib/type";import { DEFAULT_MODEL, MODELS } from "@/lib/providers";export async function POST(request: Request) {const session = await auth();if (!session) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 });}const token = session.accessToken;const body = await request.json();const {prompt,previousMessages = [],files = [],provider,model,redesignMd,medias,} = body;if (!prompt) {return NextResponse.json({ error: "Prompt is required" }, { status: 400 });}if (!model || !MODELS.find((m: (typeof MODELS)[0]) => m.value === model)) {return NextResponse.json({ error: "Model is required" }, { status: 400 });}const client = new InferenceClient(token);try {const encoder = new TextEncoder();7 unmodified linesConnection: "keep-alive",},});(async () => {let hasRetried = false;let currentModel = model;const tryGeneration = async (): Promise<void> => {try {const chatCompletion = client.chatCompletionStream({model: currentModel + (provider !== "auto" ? `:${provider}` : ""),messages: [{role: "system",content:files.length > 0? FOLLOW_UP_SYSTEM_PROMPT: INITIAL_SYSTEM_PROMPT,},...previousMessages.map((message: Message) => ({role: message.role,content: message.content,})),...(files?.length > 0? [{role: "user",content: `Here are the files that the user has provider:${files.map((file: File) =>`File: ${file.path}\nContent: ${file.content}`).join("\n")}\n\n${prompt}`,},]: []),{role: "user",content: `${redesignMd?.url &&`Redesign the following website ${redesignMd.url}, try to use the same images and content, but you can still improve it if needed. Do the best version possibile. Here is the markdown:\n ${redesignMd.md} \n\n`}${prompt} ${medias && medias.length > 0? `\nHere is the list of my media files: ${medias.join(", ")}\n`: ""}`,}],stream: true,max_tokens: 16_000,});while (true) {const { done, value } = await chatCompletion.next();if (done) {break;}const chunk = value.choices[0]?.delta?.content;if (chunk) {await writer.write(encoder.encode(chunk));}}await writer.close();} catch (error) {const errorMessage =error instanceof Error? error.message: "An error occurred while processing your request";if (!hasRetried &&errorMessage?.includes("Failed to perform inference: Model not found")) {hasRetried = true;if (model === DEFAULT_MODEL) {const availableFallbackModels = MODELS.filter((m) => m.value !== model);const randomIndex = Math.floor(Math.random() * availableFallbackModels.length);currentModel = availableFallbackModels[randomIndex];} else {currentModel = DEFAULT_MODEL;}const switchMessage = `\n\n_Note: The selected model was not available. Switched to \`${currentModel}\`._\n\n`;await writer.write(encoder.encode(switchMessage));return tryGeneration();}try {let errorPayload = "";if (errorMessage?.includes("exceeded your monthly included credits") ||errorMessage?.includes("reached the free monthly usage limit")) {errorPayload = JSON.stringify({messageError: errorMessage,showProMessage: true,isError: true,});} else {errorPayload = JSON.stringify({messageError: errorMessage,isError: true,});}await writer.write(encoder.encode(`\n\n__ERROR__:${errorPayload}`));await writer.close();} catch (closeError) {console.error("Failed to send error message:", closeError);try {await writer.abort(error);} catch (abortError) {console.error("Failed to abort writer:", abortError);}}}};await tryGeneration();})();return response;} catch (error) {return NextResponse.json({error: error instanceof Error ? error.message : "Internal Server Error",},{ status: 500 });}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091927 unmodified lines100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409/* eslint-disable @typescript-eslint/no-explicit-any */import type { NextRequest } from "next/server";import { NextResponse } from "next/server";import { headers } from "next/headers";import { InferenceClient } from "@huggingface/inference";import { MODELS } from "@/lib/providers";import {FOLLOW_UP_SYSTEM_PROMPT,FOLLOW_UP_SYSTEM_PROMPT_LIGHT,INITIAL_SYSTEM_PROMPT,INITIAL_SYSTEM_PROMPT_LIGHT,MAX_REQUESTS_PER_IP,PROMPT_FOR_PROJECT_NAME,} from "@/lib/prompts";import MY_TOKEN_KEY from "@/lib/get-cookie-name";import { Page } from "@/types";import { isAuthenticated } from "@/lib/auth";import { getBestProvider } from "@/lib/best-provider";const ipAddresses = new Map();export async function POST(request: NextRequest) {const authHeaders = await headers();const tokenInHeaders = authHeaders.get("Authorization");const userToken = tokenInHeaders ? tokenInHeaders.replace("Bearer ", "") : request.cookies.get(MY_TOKEN_KEY())?.value;const body = await request.json();const { prompt, provider, model, redesignMarkdown, enhancedSettings, pages } = body;if (!model || (!prompt && !redesignMarkdown)) {return NextResponse.json({ ok: false, error: "Missing required fields" },{ status: 400 });}const selectedModel = MODELS.find((m) => m.value === model || m.label === model);if (!selectedModel) {return NextResponse.json({ ok: false, error: "Invalid model selected" },{ status: 400 });}let token: string | null = null;if (userToken) token = userToken;let billTo: string | null = null;/*** Handle local usage token, this bypass the need for a user token* and allows local testing without authentication.* This is useful for development and testing purposes.*/if (process.env.HF_TOKEN && process.env.HF_TOKEN.length > 0) {token = process.env.HF_TOKEN;}const ip = authHeaders.get("x-forwarded-for")?.includes(",")? authHeaders.get("x-forwarded-for")?.split(",")[1].trim(): authHeaders.get("x-forwarded-for");if (!token) {ipAddresses.set(ip, (ipAddresses.get(ip) || 0) + 1);if (ipAddresses.get(ip) > MAX_REQUESTS_PER_IP) {return NextResponse.json({ok: false,openLogin: true,message: "Log In to continue using the service",},{ status: 429 });}token = process.env.DEFAULT_HF_TOKEN as string;billTo = "huggingface";}const selectedProvider = await getBestProvider(selectedModel.value, provider)let rewrittenPrompt = redesignMarkdown ? `Here is my current design as a markdown:\n\n${redesignMarkdown}\n\nNow, please create a new design based on this markdown. Use the images in the markdown.` : prompt;if (enhancedSettings.isActive) {// rewrittenPrompt = await rewritePrompt(rewrittenPrompt, enhancedSettings, { token, billTo }, selectedModel.value, selectedProvider.provider);}try {const encoder = new TextEncoder();7 unmodified linesConnection: "keep-alive",},});(async () => {try {const client = new InferenceClient(token);// Use light prompt for MiniMax modelconst systemPrompt = selectedModel.value.includes('MiniMax')? INITIAL_SYSTEM_PROMPT_LIGHT: INITIAL_SYSTEM_PROMPT;const userPrompt = rewrittenPrompt;const chatCompletion = client.chatCompletionStream({model: selectedModel.value,provider: selectedProvider,messages: [{role: "system",content: systemPrompt,},{role: "user",content: userPrompt + (enhancedSettings.isActive ? `1. I want to use the following primary color: ${enhancedSettings.primaryColor} (eg: bg-${enhancedSettings.primaryColor}-500).2. I want to use the following secondary color: ${enhancedSettings.secondaryColor} (eg: bg-${enhancedSettings.secondaryColor}-500).3. I want to use the following theme: ${enhancedSettings.theme} mode.` : "")},],...(selectedModel.top_k ? { top_k: selectedModel.top_k } : {}),...(selectedModel.temperature ? { temperature: selectedModel.temperature } : {}),...(selectedModel.top_p ? { top_p: selectedModel.top_p } : {}),},billTo ? { billTo } : {});while (true) {const { done, value } = await chatCompletion.next()if (done) {break;}const chunk = value.choices[0]?.delta?.content;console.log(chunk);if (chunk) {await writer.write(encoder.encode(chunk));}}await writer.close();} catch (error: any) {if (error.message?.includes("exceeded your monthly included credits")) {await writer.write(encoder.encode(JSON.stringify({ok: false,openProModal: true,message: error.message,})));} else if (error?.message?.includes("inference provider information")) {await writer.write(encoder.encode(JSON.stringify({ok: false,openSelectProvider: true,message: error.message,})));}else {await writer.write(encoder.encode(JSON.stringify({ok: false,message:error.message ||"An error occurred while processing your request.",})));}} finally {try {await writer?.close();} catch {}}})();return response;} catch (error: any) {return NextResponse.json({ok: false,openSelectProvider: true,message:error?.message || "An error occurred while processing your request.",},{ status: 500 });}}export async function PUT(request: NextRequest) {const user = await isAuthenticated();if (user instanceof NextResponse || !user) {return NextResponse.json({ message: "Unauthorized" }, { status: 401 });}const authHeaders = await headers();const body = await request.json();const { prompt, provider, selectedElementHtml, model, pages, files, repoId, isNew } =body;if (!prompt || pages.length === 0) {return NextResponse.json({ ok: false, error: "Missing required fields" },{ status: 400 });}const selectedModel = MODELS.find((m) => m.value === model || m.label === model);if (!selectedModel) {return NextResponse.json({ ok: false, error: "Invalid model selected" },{ status: 400 });}let token = user.token as string;let billTo: string | null = null;/*** Handle local usage token, this bypass the need for a user token* and allows local testing without authentication.* This is useful for development and testing purposes.*/if (process.env.HF_TOKEN && process.env.HF_TOKEN.length > 0) {token = process.env.HF_TOKEN;}const ip = authHeaders.get("x-forwarded-for")?.includes(",")? authHeaders.get("x-forwarded-for")?.split(",")[1].trim(): authHeaders.get("x-forwarded-for");if (!token) {ipAddresses.set(ip, (ipAddresses.get(ip) || 0) + 1);if (ipAddresses.get(ip) > MAX_REQUESTS_PER_IP) {return NextResponse.json({ok: false,openLogin: true,message: "Log In to continue using the service",},{ status: 429 });}token = process.env.DEFAULT_HF_TOKEN as string;billTo = "huggingface";}const selectedProvider = await getBestProvider(selectedModel.value, provider);try {const encoder = new TextEncoder();const stream = new TransformStream();const writer = stream.writable.getWriter();const response = new NextResponse(stream.readable, {headers: {"Content-Type": "text/plain; charset=utf-8","Cache-Control": "no-cache",Connection: "keep-alive",},});(async () => {try {const client = new InferenceClient(token);const basePrompt = selectedModel.value.includes('MiniMax')? FOLLOW_UP_SYSTEM_PROMPT_LIGHT: FOLLOW_UP_SYSTEM_PROMPT;const systemPrompt = basePrompt + (isNew ? PROMPT_FOR_PROJECT_NAME : "");const userContext = "You are modifying the HTML file based on the user's request.";const allPages = pages || [];const pagesContext = allPages.map((p: Page) => `- ${p.path}\n${p.html}`).join("\n\n");const assistantContext = `${selectedElementHtml? `\n\nYou have to update ONLY the following element, NOTHING ELSE: \n\n\`\`\`html\n${selectedElementHtml}\n\`\`\` Could be in multiple pages, if so, update all the pages.`: ""}. Current pages (${allPages.length} total): ${pagesContext}. ${files?.length > 0 ? `Available images: ${files?.map((f: string) => f).join(', ')}.` : ""}`;const chatCompletion = client.chatCompletionStream({model: selectedModel.value,provider: selectedProvider,messages: [{role: "system",content: systemPrompt,},{role: "user",content: userContext,},{role: "assistant",content: assistantContext,},{role: "user",content: prompt,},],...(selectedModel.top_k ? { top_k: selectedModel.top_k } : {}),...(selectedModel.temperature ? { temperature: selectedModel.temperature } : {}),...(selectedModel.top_p ? { top_p: selectedModel.top_p } : {}),},billTo ? { billTo } : {});// Stream the response chunks to the clientwhile (true) {const { done, value } = await chatCompletion.next();if (done) {break;}const chunk = value.choices[0]?.delta?.content;if (chunk) {await writer.write(encoder.encode(chunk));}}await writer.write(encoder.encode(`\n___METADATA_START___\n${JSON.stringify({repoId,isNew,userName: user.name,})}\n___METADATA_END___\n`));await writer.close();} catch (error: any) {if (error.message?.includes("exceeded your monthly included credits")) {await writer.write(encoder.encode(JSON.stringify({ok: false,openProModal: true,message: error.message,})));} else if (error?.message?.includes("inference provider information")) {await writer.write(encoder.encode(JSON.stringify({ok: false,openSelectProvider: true,message: error.message,})));} else {await writer.write(encoder.encode(JSON.stringify({ok: false,message:error.message ||"An error occurred while processing your request.",})));}} finally {try {await writer?.close();} catch {// ignore}}})();return response;} catch (error: any) {return NextResponse.json({ok: false,openSelectProvider: true,message:error.message || "An error occurred while processing your request.",},{ status: 500 });}}
123456import NextAuth from "next-auth";import { authOptions } from "@/lib/auth";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };123456789101112131415161718192021import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest) { const host = req.headers.get("host") ?? "localhost:3000"; let url: string; if (host.includes("localhost")) { url = host; } else { url = "huggingface.co"; } const redirect_uri = `${host.includes("localhost") ? "http://" : "https://"}` + url + "/deepsite/auth/callback";
const loginRedirectUrl = `https://huggingface.co/oauth/authorize?client_id=${process.env.OAUTH_CLIENT_ID}&redirect_uri=${redirect_uri}&response_type=code&scope=openid%20profile%20write-repos%20manage-repos%20inference-api&prompt=consent&state=1234567890`; return NextResponse.json({ loginUrl: loginRedirectUrl });}12345678910111213141516171819202122232425import { NextResponse } from "next/server";import MY_TOKEN_KEY from "@/lib/get-cookie-name";
export async function POST() { const cookieName = MY_TOKEN_KEY(); const isProduction = process.env.NODE_ENV === "production"; const response = NextResponse.json( { message: "Logged out successfully" }, { status: 200 } ); // Clear the HTTP-only cookie const cookieOptions = [ `${cookieName}=`, "Max-Age=0", "Path=/", "HttpOnly", ...(isProduction ? ["Secure", "SameSite=None"] : ["SameSite=Lax"]) ].join("; "); response.headers.set("Set-Cookie", cookieOptions); return response;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) { const body = await req.json(); const { code } = body;
if (!code) { return NextResponse.json( { error: "Code is required" }, { status: 400, headers: { "Content-Type": "application/json", }, } ); }
const Authorization = `Basic ${Buffer.from( `${process.env.OAUTH_CLIENT_ID}:${process.env.OAUTH_CLIENT_SECRET}` ).toString("base64")}`;
const host = req.headers.get("host") ?? req.headers.get("origin") ?? "localhost:3000";
const url = host.includes("/spaces/enzostvs") ? "huggingface.co/deepsite" : host; const redirect_uri = `${host.includes("localhost") ? "http://" : "https://"}` + url + "/deepsite/auth/callback"; const request_auth = await fetch("https://huggingface.co/oauth/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization, }, body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri, }), });
const response = await request_auth.json(); if (!response.access_token) { return NextResponse.json( { error: "Failed to retrieve access token" }, { status: 400, headers: { "Content-Type": "application/json", }, } ); }
const userResponse = await fetch("https://huggingface.co/api/whoami-v2", { headers: { Authorization: `Bearer ${response.access_token}`, }, });
if (!userResponse.ok) { return NextResponse.json( { user: null, errCode: userResponse.status }, { status: userResponse.status } ); } const user = await userResponse.json();
return NextResponse.json( { access_token: response.access_token, expires_in: response.expires_in, user, }, { status: 200, headers: { "Content-Type": "application/json", }, } );}12345import { NextResponse } from "next/server";
export async function GET() { return NextResponse.json({ status: "ok" }, { status: 200 });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, createRepo, uploadFiles, spaceInfo, listCommits } from "@huggingface/hub";import { COLORS } from "@/lib/utils";import { injectDeepSiteBadge, isIndexPage } from "@/lib/inject-badge";import { Commit, Page } from "@/types";
// Timeout configuration (in milliseconds)const OPERATION_TIMEOUT = 120000; // 2 minutes for HF operations
// Extend the maximum execution time for this routeexport const maxDuration = 180; // 3 minutes
// Utility function to wrap promises with timeoutasync function withTimeout<T>( promise: Promise<T>, timeoutMs: number, errorMessage: string = "Operation timed out"): Promise<T> { let timeoutId: NodeJS.Timeout; const timeoutPromise = new Promise<never>((_, reject) => { timeoutId = setTimeout(() => { reject(new Error(errorMessage)); }, timeoutMs); });
try { const result = await Promise.race([promise, timeoutPromise]); clearTimeout(timeoutId!); return result; } catch (error) { clearTimeout(timeoutId!); throw error; }}
interface MCPRequest { jsonrpc: "2.0"; id: number | string; method: string; params?: any;}
interface MCPResponse { jsonrpc: "2.0"; id: number | string; result?: any; error?: { code: number; message: string; data?: any; };}
interface CreateProjectParams { title?: string; pages: Page[]; prompt?: string; hf_token?: string; // Optional - can come from header instead}
// MCP Server over HTTPexport async function POST(req: NextRequest) { try { const body: MCPRequest = await req.json(); const { jsonrpc, id, method, params } = body;
// Validate JSON-RPC 2.0 format if (jsonrpc !== "2.0") { return NextResponse.json({ jsonrpc: "2.0", id: id || null, error: { code: -32600, message: "Invalid Request: jsonrpc must be '2.0'", }, }); }
let response: MCPResponse;
switch (method) { case "initialize": response = { jsonrpc: "2.0", id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {}, }, serverInfo: { name: "deepsite-mcp-server", version: "1.0.0", }, }, }; break;
case "tools/list": response = { jsonrpc: "2.0", id, result: { tools: [ { name: "create_project", description: `Create a new DeepSite project. This will create a new Hugging Face Space with your HTML/CSS/JS files.
Example usage:- Create a simple website with HTML, CSS, and JavaScript files- Each page needs a 'path' (filename like "index.html", "styles.css", "script.js") and 'html' (the actual content)- The title will be formatted to a valid repository name- Returns the project URL and metadata`, inputSchema: { type: "object", properties: { title: { type: "string", description: "Project title (optional, defaults to 'DeepSite Project'). Will be formatted to a valid repo name.", }, pages: { type: "array", description: "Array of files to include in the project", items: { type: "object", properties: { path: { type: "string", description: "File path (e.g., 'index.html', 'styles.css', 'script.js')", }, html: { type: "string", description: "File content", }, }, required: ["path", "html"], }, }, prompt: { type: "string", description: "Optional prompt/description for the commit message", }, hf_token: { type: "string", description: "Hugging Face API token (optional if provided via Authorization header)", }, }, required: ["pages"], }, }, ], }, }; break;
case "tools/call": const { name, arguments: toolArgs } = params;
if (name === "create_project") { try { // Extract token from Authorization header if present const authHeader = req.headers.get("authorization"); let hf_token = toolArgs.hf_token; if (authHeader && authHeader.startsWith("Bearer ")) { hf_token = authHeader.substring(7); // Remove "Bearer " prefix } const result = await handleCreateProject({ ...toolArgs, hf_token, } as CreateProjectParams); response = { jsonrpc: "2.0", id, result, }; } catch (error: any) { response = { jsonrpc: "2.0", id, error: { code: -32000, message: error.message || "Failed to create project", data: error.data, }, }; } } else { response = { jsonrpc: "2.0", id, error: { code: -32601, message: `Unknown tool: ${name}`, }, }; } break;
default: response = { jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}`, }, }; }
return NextResponse.json(response); } catch (error: any) { return NextResponse.json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error", data: error.message, }, }); }}
// Handle OPTIONS for CORSexport async function OPTIONS() { return new NextResponse(null, { status: 200, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", }, });}
async function handleCreateProject(params: CreateProjectParams) { const { title: titleFromRequest, pages, prompt, hf_token } = params;
// Validate required parameters if (!hf_token || typeof hf_token !== "string") { throw new Error("hf_token is required and must be a string"); }
if (!pages || !Array.isArray(pages) || pages.length === 0) { throw new Error("At least one page is required"); }
// Validate that each page has required fields for (const page of pages) { if (!page.path || !page.html) { throw new Error("Each page must have 'path' and 'html' properties"); } }
// Get user info from HF token let username: string; try { const userResponse = await withTimeout( fetch("https://huggingface.co/api/whoami-v2", { headers: { Authorization: `Bearer ${hf_token}`, }, }), 30000, // 30 seconds for authentication "Authentication timeout: Unable to verify Hugging Face token" );
if (!userResponse.ok) { throw new Error("Invalid Hugging Face token"); }
const userData = await userResponse.json(); username = userData.name; } catch (error: any) { if (error.message?.includes('timeout')) { throw new Error(`Authentication timeout: ${error.message}`); } throw new Error(`Authentication failed: ${error.message}`); }
const title = titleFromRequest ?? "DeepSite Project";
const formattedTitle = title .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .split("-") .filter(Boolean) .join("-") .slice(0, 96);
const repo: RepoDesignation = { type: "space", name: `${username}/${formattedTitle}`, };
const colorFrom = COLORS[Math.floor(Math.random() * COLORS.length)]; const colorTo = COLORS[Math.floor(Math.random() * COLORS.length)]; const README = `---title: ${title}colorFrom: ${colorFrom}colorTo: ${colorTo}emoji: 🐳sdk: staticpinned: falsetags: - deepsite-v3---
# Welcome to your new DeepSite project!This project was created with [DeepSite](https://huggingface.co/deepsite).`;
const files: File[] = []; const readmeFile = new File([README], "README.md", { type: "text/markdown" }); files.push(readmeFile);
pages.forEach((page: Page) => { // Determine MIME type based on file extension let mimeType = "text/html"; if (page.path.endsWith(".css")) { mimeType = "text/css"; } else if (page.path.endsWith(".js")) { mimeType = "text/javascript"; } else if (page.path.endsWith(".json")) { mimeType = "application/json"; }
// Inject the DeepSite badge script into index pages only const content = mimeType === "text/html" && isIndexPage(page.path) ? injectDeepSiteBadge(page.html) : page.html; const file = new File([content], page.path, { type: mimeType }); files.push(file); });
try { const { repoUrl } = await withTimeout( createRepo({ repo, accessToken: hf_token, }), 60000, // 1 minute for repo creation "Timeout creating repository. Please try again." );
const commitTitle = !prompt || prompt.trim() === "" ? "Initial project creation via MCP" : prompt; await withTimeout( uploadFiles({ repo, files, accessToken: hf_token, commitTitle, }), OPERATION_TIMEOUT, "Timeout uploading files. The repository was created but files may not have been uploaded." );
const path = repoUrl.split("/").slice(-2).join("/");
const commits: Commit[] = []; const commitIterator = listCommits({ repo, accessToken: hf_token }); // Wrap the commit listing with a timeout const commitTimeout = new Promise<void>((_, reject) => { setTimeout(() => reject(new Error("Timeout listing commits")), 30000); }); try { await Promise.race([ (async () => { for await (const commit of commitIterator) { if (commit.title.includes("initial commit") || commit.title.includes("image(s)") || commit.title.includes("Promote version")) { continue; } commits.push({ title: commit.title, oid: commit.oid, date: commit.date, }); } })(), commitTimeout ]); } catch (error: any) { // If listing commits times out, continue with empty commits array console.error("Failed to list commits:", error.message); }
const space = await withTimeout( spaceInfo({ name: repo.name, accessToken: hf_token, }), 30000, // 30 seconds for space info "Timeout fetching space information" );
const projectUrl = `https://huggingface.co/deepsite/${path}`; const spaceUrl = `https://huggingface.co/spaces/${path}`; const liveUrl = `https://${username}-${formattedTitle}.hf.space`;
return { content: [ { type: "text", text: JSON.stringify( { success: true, message: "Project created successfully!", projectUrl, spaceUrl, liveUrl, spaceId: space.name, projectId: space.id, files: pages.map((p) => p.path), updatedAt: space.updatedAt, }, null, 2 ), }, ], }; } catch (err: any) { if (err.message?.includes('timeout') || err.message?.includes('Timeout')) { throw new Error(err.message || "Operation timed out. Please try again."); } throw new Error(err.message || "Failed to create project"); }}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, listFiles, spaceInfo, uploadFiles, deleteFiles, downloadFile } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";import { Page } from "@/types";
export async function POST( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string; commitId: string; }> }) { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const param = await params; const { namespace, repoId, commitId } = param;
try { const repo: RepoDesignation = { type: "space", name: `${namespace}/${repoId}`, };
const space = await spaceInfo({ name: `${namespace}/${repoId}`, accessToken: user.token as string, additionalFields: ["author"], });
if (!space || space.sdk !== "static") { return NextResponse.json( { ok: false, error: "Space is not a static space." }, { status: 404 } ); } if (space.author !== user.name) { return NextResponse.json( { ok: false, error: "Space does not belong to the authenticated user." }, { status: 403 } ); }
const files: File[] = []; const pages: Page[] = []; const mediaFiles: string[] = []; const allowedExtensions = ["html", "md", "css", "js", "json", "txt"]; const allowedFilesExtensions = ["jpg", "jpeg", "png", "gif", "svg", "webp", "avif", "heic", "heif", "ico", "bmp", "tiff", "tif", "mp4", "webm", "ogg", "avi", "mov", "mp3", "wav", "ogg", "aac", "m4a"]; const commitFilePaths: Set<string> = new Set(); for await (const fileInfo of listFiles({ repo, accessToken: user.token as string, revision: commitId, })) { const fileExtension = fileInfo.path.split('.').pop()?.toLowerCase(); if (fileInfo.path.endsWith(".html") || fileInfo.path.endsWith(".css") || fileInfo.path.endsWith(".js") || fileInfo.path.endsWith(".json")) { commitFilePaths.add(fileInfo.path); const blob = await downloadFile({ repo, accessToken: user.token as string, path: fileInfo.path, revision: commitId, raw: true }); const content = await blob?.text(); if (content) { let mimeType = "text/plain"; switch (fileExtension) { case "html": mimeType = "text/html"; break; case "css": mimeType = "text/css"; break; case "js": mimeType = "application/javascript"; break; case "json": mimeType = "application/json"; break; } if (fileInfo.path === "index.html") { pages.unshift({ path: fileInfo.path, html: content, }); } else { pages.push({ path: fileInfo.path, html: content, }); } const file = new File([content], fileInfo.path, { type: mimeType }); files.push(file); } } else if (fileInfo.type === "directory" && (["videos", "images", "audio"].includes(fileInfo.path) || fileInfo.path === "components")) { for await (const subFileInfo of listFiles({ repo, accessToken: user.token as string, revision: commitId, path: fileInfo.path, })) { if (subFileInfo.path.includes("components")) { commitFilePaths.add(subFileInfo.path); const blob = await downloadFile({ repo, accessToken: user.token as string, path: subFileInfo.path, revision: commitId, raw: true }); const content = await blob?.text(); if (content) { pages.push({ path: subFileInfo.path, html: content, }); const file = new File([content], subFileInfo.path, { type: "text/html" }); files.push(file); } } else if (allowedFilesExtensions.includes(subFileInfo.path.split(".").pop() || "")) { commitFilePaths.add(subFileInfo.path); mediaFiles.push(`https://huggingface.co/spaces/${namespace}/${repoId}/resolve/main/${subFileInfo.path}`); } } } else if (allowedExtensions.includes(fileExtension || "")) { commitFilePaths.add(fileInfo.path); } }
const mainBranchFilePaths: Set<string> = new Set(); for await (const fileInfo of listFiles({ repo, accessToken: user.token as string, revision: "main", })) { const fileExtension = fileInfo.path.split('.').pop()?.toLowerCase(); if (allowedExtensions.includes(fileExtension || "")) { mainBranchFilePaths.add(fileInfo.path); } }
const filesToDelete: string[] = []; for (const mainFilePath of mainBranchFilePaths) { if (!commitFilePaths.has(mainFilePath)) { filesToDelete.push(mainFilePath); } }
if (files.length === 0 && filesToDelete.length === 0) { return NextResponse.json( { ok: false, error: "No files found in the specified commit and no files to delete" }, { status: 404 } ); }
if (filesToDelete.length > 0) { await deleteFiles({ repo, paths: filesToDelete, accessToken: user.token as string, commitTitle: `Removed files from promoting ${commitId.slice(0, 7)}`, commitDescription: `Removed files that don't exist in commit ${commitId}:\n${filesToDelete.map(path => `- ${path}`).join('\n')}`, }); }
if (files.length > 0) { await uploadFiles({ repo, files, accessToken: user.token as string, commitTitle: `Promote version ${commitId.slice(0, 7)} to main`, commitDescription: `Promoted commit ${commitId} to main branch`, }); }
return NextResponse.json( { ok: true, message: "Version promoted successfully", promotedCommit: commitId, pages: pages, files: mediaFiles, }, { status: 200 } );
} catch (error: any) { // Handle specific HuggingFace API errors if (error.statusCode === 404) { return NextResponse.json( { ok: false, error: "Commit not found" }, { status: 404 } ); } if (error.statusCode === 403) { return NextResponse.json( { ok: false, error: "Access denied to repository" }, { status: 403 } ); }
return NextResponse.json( { ok: false, error: error.message || "Failed to promote version" }, { status: 500 } ); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, listFiles, spaceInfo, downloadFile } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";import { Page } from "@/types";
export async function GET( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string; commitId: string; }> }) { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const param = await params; const { namespace, repoId, commitId } = param;
try { const repo: RepoDesignation = { type: "space", name: `${namespace}/${repoId}`, };
const space = await spaceInfo({ name: `${namespace}/${repoId}`, accessToken: user.token as string, additionalFields: ["author"], });
if (!space || space.sdk !== "static") { return NextResponse.json( { ok: false, error: "Space is not a static space." }, { status: 404 } ); } if (space.author !== user.name) { return NextResponse.json( { ok: false, error: "Space does not belong to the authenticated user." }, { status: 403 } ); }
const pages: Page[] = []; for await (const fileInfo of listFiles({ repo, accessToken: user.token as string, revision: commitId, })) { const fileExtension = fileInfo.path.split('.').pop()?.toLowerCase(); if (fileInfo.path.endsWith(".html") || fileInfo.path.endsWith(".css") || fileInfo.path.endsWith(".js") || fileInfo.path.endsWith(".json")) { const blob = await downloadFile({ repo, accessToken: user.token as string, path: fileInfo.path, revision: commitId, raw: true }); const content = await blob?.text(); if (content) { if (fileInfo.path === "index.html") { pages.unshift({ path: fileInfo.path, html: content, }); } else { pages.push({ path: fileInfo.path, html: content, }); } } } } return NextResponse.json({ ok: true, pages, }); } catch (error: any) { console.error("Error fetching commit pages:", error); return NextResponse.json( { ok: false, error: error.message || "Failed to fetch commit pages", }, { status: 500 } ); }}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, spaceInfo, uploadFiles } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";import Project from "@/models/Project";import dbConnect from "@/lib/mongodb";
export async function POST( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string }> }) { try { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const param = await params; const { namespace, repoId } = param;
const space = await spaceInfo({ name: `${namespace}/${repoId}`, accessToken: user.token as string, additionalFields: ["author"], });
if (!space || space.sdk !== "static") { return NextResponse.json( { ok: false, error: "Space is not a static space." }, { status: 404 } ); } if (space.author !== user.name) { return NextResponse.json( { ok: false, error: "Space does not belong to the authenticated user." }, { status: 403 } ); }
// Parse the FormData to get the media files const formData = await req.formData(); const mediaFiles = formData.getAll("images") as File[];
if (!mediaFiles || mediaFiles.length === 0) { return NextResponse.json( { ok: false, error: "At least one media file is required under the 'images' key", }, { status: 400 } ); }
const files: File[] = []; for (const file of mediaFiles) { if (!(file instanceof File)) { return NextResponse.json( { ok: false, error: "Invalid file format - all items under 'images' key must be files", }, { status: 400 } ); }
// Check if file is a supported media type const isImage = file.type.startsWith('image/'); const isVideo = file.type.startsWith('video/'); const isAudio = file.type.startsWith('audio/'); if (!isImage && !isVideo && !isAudio) { return NextResponse.json( { ok: false, error: `File ${file.name} is not a supported media type (image, video, or audio)`, }, { status: 400 } ); }
// Create File object with appropriate folder prefix let folderPrefix = 'images/'; if (isVideo) { folderPrefix = 'videos/'; } else if (isAudio) { folderPrefix = 'audio/'; } const fileName = `${folderPrefix}${file.name}`; const processedFile = new File([file], fileName, { type: file.type }); files.push(processedFile); }
// Upload files to HuggingFace space const repo: RepoDesignation = { type: "space", name: `${namespace}/${repoId}`, };
await uploadFiles({ repo, files, accessToken: user.token as string, commitTitle: `Upload ${files.length} media file(s)`, });
return NextResponse.json({ ok: true, message: `Successfully uploaded ${files.length} media file(s) to ${namespace}/${repoId}/`, uploadedFiles: files.map((file) => `https://huggingface.co/spaces/${namespace}/${repoId}/resolve/main/${file.name}`), }, { status: 200 });
} catch (error) { console.error('Error uploading media files:', error); return NextResponse.json( { ok: false, error: "Failed to upload media files", }, { status: 500 } ); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, spaceInfo, listFiles, deleteRepo, listCommits, downloadFile } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";import { Commit, Page } from "@/types";
export async function DELETE( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string }> }) { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const param = await params; const { namespace, repoId } = param;
try { const space = await spaceInfo({ name: `${namespace}/${repoId}`, accessToken: user.token as string, additionalFields: ["author"], }); if (!space || space.sdk !== "static") { return NextResponse.json( { ok: false, error: "Space is not a static space." }, { status: 404 } ); } if (space.author !== user.name) { return NextResponse.json( { ok: false, error: "Space does not belong to the authenticated user." }, { status: 403 } ); } const repo: RepoDesignation = { type: "space", name: `${namespace}/${repoId}`, }; await deleteRepo({ repo, accessToken: user.token as string, });
return NextResponse.json({ ok: true }, { status: 200 }); } catch (error: any) { return NextResponse.json( { ok: false, error: error.message }, { status: 500 } ); }}
export async function GET( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string }> }) { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const param = await params; const { namespace, repoId } = param;
try { const space = await spaceInfo({ name: namespace + "/" + repoId, accessToken: user.token as string, additionalFields: ["author"], });
if (!space || space.sdk !== "static") { return NextResponse.json( { ok: false, error: "Space is not a static space", }, { status: 404 } ); } if (space.author !== user.name) { return NextResponse.json( { ok: false, error: "Space does not belong to the authenticated user", }, { status: 403 } ); }
const repo: RepoDesignation = { type: "space", name: `${namespace}/${repoId}`, };
const htmlFiles: Page[] = []; const files: string[] = [];
const allowedFilesExtensions = ["jpg", "jpeg", "png", "gif", "svg", "webp", "avif", "heic", "heif", "ico", "bmp", "tiff", "tif", "mp4", "webm", "ogg", "avi", "mov", "mp3", "wav", "ogg", "aac", "m4a"]; for await (const fileInfo of listFiles({repo, accessToken: user.token as string})) { if (fileInfo.path.endsWith(".html") || fileInfo.path.endsWith(".css") || fileInfo.path.endsWith(".js") || fileInfo.path.endsWith(".json")) { const blob = await downloadFile({ repo, accessToken: user.token as string, path: fileInfo.path, raw: true }); const html = await blob?.text(); if (!html) { continue; } if (fileInfo.path === "index.html") { htmlFiles.unshift({ path: fileInfo.path, html, }); } else { htmlFiles.push({ path: fileInfo.path, html, }); } } if (fileInfo.type === "directory" && (["videos", "images", "audio"].includes(fileInfo.path) || fileInfo.path === "components")) { for await (const subFileInfo of listFiles({repo, accessToken: user.token as string, path: fileInfo.path})) { if (subFileInfo.path.includes("components")) { const blob = await downloadFile({ repo, accessToken: user.token as string, path: subFileInfo.path, raw: true }); const html = await blob?.text(); if (!html) { continue; } htmlFiles.push({ path: subFileInfo.path, html, }); } else if (allowedFilesExtensions.includes(subFileInfo.path.split(".").pop() || "")) { files.push(`https://huggingface.co/spaces/${namespace}/${repoId}/resolve/main/${subFileInfo.path}`); } } } } const commits: Commit[] = []; for await (const commit of listCommits({ repo, accessToken: user.token as string })) { if (commit.title.includes("initial commit") || commit.title.includes("image(s)") || commit.title.includes("Removed files from promoting")) { continue; } commits.push({ title: commit.title, oid: commit.oid, date: commit.date, }); } if (htmlFiles.length === 0) { return NextResponse.json( { ok: false, error: "No HTML files found", }, { status: 404 } ); } return NextResponse.json( { project: { id: space.id, space_id: space.name, private: space.private, _updatedAt: space.updatedAt, }, pages: htmlFiles, files, commits, ok: true, }, { status: 200 } );
// eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { if (error.statusCode === 404) { return NextResponse.json( { error: "Space not found", ok: false }, { status: 404 } ); } return NextResponse.json( { error: error.message, ok: false }, { status: 500 } ); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import { NextRequest, NextResponse } from "next/server";import { uploadFiles } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";import { Page } from "@/types";
export async function PUT( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string }> }) { const user = await isAuthenticated(); if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const param = await params; const { namespace, repoId } = param; const { pages, commitTitle = "Manual changes saved" } = await req.json();
if (!pages || !Array.isArray(pages) || pages.length === 0) { return NextResponse.json( { ok: false, error: "Pages are required" }, { status: 400 } ); }
try { // Prepare files for upload const files: File[] = []; pages.forEach((page: Page) => { // Determine MIME type based on file extension let mimeType = "text/html"; if (page.path.endsWith(".css")) { mimeType = "text/css"; } else if (page.path.endsWith(".js")) { mimeType = "text/javascript"; } else if (page.path.endsWith(".json")) { mimeType = "application/json"; } const file = new File([page.html], page.path, { type: mimeType }); files.push(file); });
const response = await uploadFiles({ repo: { type: "space", name: `${namespace}/${repoId}`, }, files, commitTitle, accessToken: user.token as string, });
return NextResponse.json({ ok: true, pages, commit: { ...response.commit, title: commitTitle, } }); } catch (error: any) { console.error("Error saving manual changes:", error); return NextResponse.json( { ok: false, error: error.message || "Failed to save changes", }, { status: 500 } ); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import { NextRequest, NextResponse } from "next/server";import { createRepo, RepoDesignation, uploadFiles } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";import { Page } from "@/types";import { COLORS } from "@/lib/utils";import { injectDeepSiteBadge, isIndexPage } from "@/lib/inject-badge";import { pagesToFiles } from "@/lib/format-ai-response";
/** * UPDATE route - for updating existing projects or creating new ones after AI streaming * This route handles the HuggingFace upload after client-side AI response processing */export async function PUT( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string }> }) { const user = await isAuthenticated(); if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const param = await params; let { namespace, repoId } = param; const { pages, commitTitle = "AI-generated changes", isNew, projectName } = await req.json();
if (!pages || !Array.isArray(pages) || pages.length === 0) { return NextResponse.json( { ok: false, error: "Pages are required" }, { status: 400 } ); }
try { let files: File[]; if (isNew) { // Creating a new project const title = projectName || "DeepSite Project"; const formattedTitle = title .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .split("-") .filter(Boolean) .join("-") .slice(0, 96);
const repo: RepoDesignation = { type: "space", name: `${user.name}/${formattedTitle}`, };
try { const { repoUrl } = await createRepo({ repo, accessToken: user.token as string, }); namespace = user.name; repoId = repoUrl.split("/").slice(-2).join("/").split("/")[1]; } catch (createRepoError: any) { return NextResponse.json( { ok: false, error: `Failed to create repository: ${createRepoError.message || 'Unknown error'}`, }, { status: 500 } ); }
// Prepare files with badge injection for new projects files = []; pages.forEach((page: Page) => { let mimeType = "text/html"; if (page.path.endsWith(".css")) { mimeType = "text/css"; } else if (page.path.endsWith(".js")) { mimeType = "text/javascript"; } else if (page.path.endsWith(".json")) { mimeType = "application/json"; } const content = (mimeType === "text/html" && isIndexPage(page.path)) ? injectDeepSiteBadge(page.html) : page.html; const file = new File([content], page.path, { type: mimeType }); files.push(file); });
// Add README.md for new projects const colorFrom = COLORS[Math.floor(Math.random() * COLORS.length)]; const colorTo = COLORS[Math.floor(Math.random() * COLORS.length)]; const README = `---title: ${title}colorFrom: ${colorFrom}colorTo: ${colorTo}emoji: 🐳sdk: staticpinned: falsetags: - deepsite-v3---
# Welcome to your new DeepSite project!This project was created with [DeepSite](https://huggingface.co/deepsite).`; files.push(new File([README], "README.md", { type: "text/markdown" })); } else { // Updating existing project - no badge injection files = pagesToFiles(pages); }
const response = await uploadFiles({ repo: { type: "space", name: `${namespace}/${repoId}`, }, files, commitTitle, accessToken: user.token as string, });
return NextResponse.json({ ok: true, pages, repoId: `${namespace}/${repoId}`, commit: { ...response.commit, title: commitTitle, } }); } catch (error: any) { console.error("Error updating project:", error); return NextResponse.json( { ok: false, error: error.message || "Failed to update project", }, { status: 500 } ); }}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, createRepo, listCommits, spaceInfo, uploadFiles } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";import { Commit, Page } from "@/types";import { COLORS } from "@/lib/utils";import { injectDeepSiteBadge, isIndexPage } from "@/lib/inject-badge";
export async function POST( req: NextRequest,) { const user = await isAuthenticated(); if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const { title: titleFromRequest, pages, prompt } = await req.json();
const title = titleFromRequest ?? "DeepSite Project";
const formattedTitle = title .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .split("-") .filter(Boolean) .join("-") .slice(0, 96);
const repo: RepoDesignation = { type: "space", name: `${user.name}/${formattedTitle}`, }; const colorFrom = COLORS[Math.floor(Math.random() * COLORS.length)]; const colorTo = COLORS[Math.floor(Math.random() * COLORS.length)]; const README = `---title: ${title}colorFrom: ${colorFrom}colorTo: ${colorTo}emoji: 🐳sdk: staticpinned: falsetags: - deepsite-v3---
# Welcome to your new DeepSite project!This project was created with [DeepSite](https://huggingface.co/deepsite).`;
const files: File[] = []; const readmeFile = new File([README], "README.md", { type: "text/markdown" }); files.push(readmeFile); pages.forEach((page: Page) => { // Determine MIME type based on file extension let mimeType = "text/html"; if (page.path.endsWith(".css")) { mimeType = "text/css"; } else if (page.path.endsWith(".js")) { mimeType = "text/javascript"; } else if (page.path.endsWith(".json")) { mimeType = "application/json"; } // Inject the DeepSite badge script into index pages only (not components or other HTML files) const content = (mimeType === "text/html" && isIndexPage(page.path)) ? injectDeepSiteBadge(page.html) : page.html; const file = new File([content], page.path, { type: mimeType }); files.push(file); });
try { const { repoUrl} = await createRepo({ repo, accessToken: user.token as string, }); const commitTitle = !prompt || prompt.trim() === "" ? "Redesign my website" : prompt; await uploadFiles({ repo, files, accessToken: user.token as string, commitTitle });
const path = repoUrl.split("/").slice(-2).join("/");
const commits: Commit[] = []; for await (const commit of listCommits({ repo, accessToken: user.token as string })) { if (commit.title.includes("initial commit") || commit.title.includes("image(s)") || commit.title.includes("Promote version")) { continue; } commits.push({ title: commit.title, oid: commit.oid, date: commit.date, }); }
const space = await spaceInfo({ name: repo.name, accessToken: user.token as string, });
let newProject = { files, pages, commits, project: { id: space.id, space_id: space.name, _updatedAt: space.updatedAt, } } return NextResponse.json({ space: newProject, path, ok: true }, { status: 201 }); } catch (err: any) { return NextResponse.json( { error: err.message, ok: false }, { status: 500 } ); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546import { listSpaces } from "@huggingface/hub";import { headers } from "next/headers";import { NextResponse } from "next/server";
export async function GET() { const authHeaders = await headers(); const token = authHeaders.get("Authorization"); if (!token) { return NextResponse.json({ user: null, errCode: 401 }, { status: 401 }); }
const userResponse = await fetch("https://huggingface.co/api/whoami-v2", { headers: { Authorization: `${token}`, }, });
if (!userResponse.ok) { return NextResponse.json( { user: null, errCode: userResponse.status }, { status: userResponse.status } ); } const user = await userResponse.json(); const projects = []; for await (const space of listSpaces({ accessToken: token.replace("Bearer ", "") as string, additionalFields: ["author", "cardData"], search: { owner: user.name, } })) { if ( space.sdk === "static" && Array.isArray((space.cardData as { tags?: string[] })?.tags) && ( ((space.cardData as { tags?: string[] })?.tags?.includes("deepsite-v3")) || ((space.cardData as { tags?: string[] })?.tags?.includes("deepsite")) ) ) { projects.push(space); } }
return NextResponse.json({ user, projects, errCode: null }, { status: 200 });}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import { auth } from "@/lib/auth";import { createBranch, RepoDesignation } from "@huggingface/hub";import { format } from "date-fns";import { NextResponse } from "next/server";
export async function POST( request: Request, { params }: { params: Promise<{ repoId: string; commitId: string }> }) { const { repoId, commitId }: { repoId: string; commitId: string } = await params; const session = await auth(); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const token = session.accessToken;
const repo: RepoDesignation = { type: "space", name: session.user?.username + "/" + repoId, };
const commitTitle = `🔖 ${format(new Date(), "dd/MM")} - ${format( new Date(), "HH:mm" )} - Set commit ${commitId} as default.`;
await fetch( `https://huggingface.co/api/spaces/${session.user?.username}/${repoId}/branch/main`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, body: JSON.stringify({ startingPoint: commitId, overwrite: true, }), } ).catch((error) => { return NextResponse.json( { error: error ?? "Failed to create branch" }, { status: 500 } ); });
return NextResponse.json({ success: true }, { status: 200 });}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import { auth } from "@/lib/auth";import { downloadFile, listFiles, RepoDesignation } from "@huggingface/hub";import { NextResponse } from "next/server";import JSZip from "jszip";
export async function GET( request: Request, { params }: { params: Promise<{ repoId: string }> }) { const { repoId }: { repoId: string } = await params; const session = await auth(); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const token = session.accessToken; const repo: RepoDesignation = { type: "space", name: session.user?.username + "/" + repoId, };
try { const zip = new JSZip(); for await (const fileInfo of listFiles({ repo, accessToken: token as string, recursive: true, })) { if (fileInfo.type === "directory" || fileInfo.path.startsWith(".")) { continue; }
try { const blob = await downloadFile({ repo, accessToken: token as string, path: fileInfo.path, raw: true }).catch((error) => { return null; }); if (!blob) { continue; }
if (blob) { const arrayBuffer = await blob.arrayBuffer(); zip.file(fileInfo.path, arrayBuffer); } } catch (error) { console.error(`Error downloading file ${fileInfo.path}:`, error); } }
const zipBlob = await zip.generateAsync({ type: "blob", compression: "DEFLATE", compressionOptions: { level: 6 } });
const projectName = `${session.user?.username}-${repoId}`.replace(/[^a-zA-Z0-9-_]/g, '_'); const filename = `${projectName}.zip`;
return new NextResponse(zipBlob, { headers: { "Content-Type": "application/zip", "Content-Disposition": `attachment; filename="${filename}"`, "Content-Length": zipBlob.size.toString(), }, }); } catch (error) { console.error("Error downloading project:", error); return NextResponse.json({ error: "Failed to download project" }, { status: 500 }); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import { auth } from "@/lib/auth";import { RepoDesignation, uploadFiles } from "@huggingface/hub";import { NextResponse } from "next/server";
export async function POST( request: Request, { params }: { params: Promise<{ repoId: string }> }) { const { repoId }: { repoId: string } = await params; const session = await auth(); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const token = session.accessToken;
const repo: RepoDesignation = { type: "space", name: session.user?.username + "/" + repoId, };
const formData = await request.formData(); const newMedias = formData.getAll("images") as File[];
const filesToUpload: File[] = [];
if (!newMedias || newMedias.length === 0) { return NextResponse.json( { ok: false, error: "At least one media file is required under the 'images' key", }, { status: 400 } ); }
try { for (const media of newMedias) { const isImage = media.type.startsWith("image/"); const isVideo = media.type.startsWith("video/"); const isAudio = media.type.startsWith("audio/");
const folderPath = isImage ? "images/" : isVideo ? "videos/" : isAudio ? "audios/" : null;
if (!folderPath) { return NextResponse.json( { ok: false, error: "Unsupported media type: " + media.type }, { status: 400 } ); }
const mediaName = `${folderPath}${media.name}`; const processedFile = new File([media], mediaName, { type: media.type }); filesToUpload.push(processedFile); }
await uploadFiles({ repo, files: filesToUpload, accessToken: token, commitTitle: `📁 Upload media files through DeepSite`, });
return NextResponse.json( { success: true, medias: filesToUpload.map( (file) => `https://huggingface.co/spaces/${session.user?.username}/${repoId}/resolve/main/${file.name}` ), }, { status: 200 } ); } catch (error) { return NextResponse.json( { ok: false, error: error ?? "Failed to upload media files" }, { status: 500 } ); }
return NextResponse.json({ success: true }, { status: 200 });}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import { auth } from "@/lib/auth";import { downloadFile, RepoDesignation, uploadFile } from "@huggingface/hub";import { format } from "date-fns";import { NextResponse } from "next/server";
export async function PUT( request: Request, { params }: { params: Promise<{ repoId: string }> }) { const { repoId }: { repoId: string } = await params; const session = await auth(); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const token = session.accessToken;
const body = await request.json(); const { newTitle } = body;
if (!newTitle) { return NextResponse.json( { error: "newTitle is required" }, { status: 400 } ); }
const repo: RepoDesignation = { type: "space", name: session.user?.username + "/" + repoId, };
const blob = await downloadFile({ repo, accessToken: token, path: "README.md", raw: true, }).catch((_) => { return null; });
if (!blob) { return NextResponse.json( { error: "Could not fetch README.md" }, { status: 500 } ); }
const readmeFile = await blob?.text(); if (!readmeFile) { return NextResponse.json( { error: "Could not read README.md content" }, { status: 500 } ); }
// Escape YAML values to prevent injection attacks const escapeYamlValue = (value: string): string => { if (/[:|>]|^[-*#]|^\s|['"]/.test(value) || value.includes("\n")) { return `"${value.replace(/"/g, '\\"')}"`; } return value; };
// Escape commit message to prevent injection const escapeCommitMessage = (message: string): string => { return message.replace(/[\r\n]/g, " ").slice(0, 200); };
const updatedReadmeFile = readmeFile.replace( /^title:\s*(.*)$/m, `title: ${escapeYamlValue(newTitle)}` );
await uploadFile({ repo, accessToken: token, file: new File([updatedReadmeFile], "README.md", { type: "text/markdown" }), commitTitle: escapeCommitMessage( `🐳 ${format(new Date(), "dd/MM")} - ${format( new Date(), "HH:mm" )} - Rename project to "${newTitle}"` ), });
return NextResponse.json( { success: true, }, { status: 200 } );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import { auth } from "@/lib/auth";import { RepoDesignation, deleteRepo, uploadFiles } from "@huggingface/hub";import { format } from "date-fns";import { NextResponse } from "next/server";
export async function PUT( request: Request, { params }: { params: Promise<{ repoId: string }> }) { const { repoId }: { repoId: string } = await params; const session = await auth(); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const token = session.accessToken;
const body = await request.json(); const { files, prompt, isManualChanges } = body;
if (!files) { return NextResponse.json({ error: "Files are required" }, { status: 400 }); }
if (!prompt) { return NextResponse.json({ error: "Prompt is required" }, { status: 400 }); }
const repo: RepoDesignation = { type: "space", name: session.user?.username + "/" + repoId, };
const filesToUpload: File[] = []; for (const file of files) { let mimeType = "text/x-python"; if (file.path.endsWith(".txt")) { mimeType = "text/plain"; } else if (file.path.endsWith(".md")) { mimeType = "text/markdown"; } else if (file.path.endsWith(".json")) { mimeType = "application/json"; } filesToUpload.push(new File([file.content], file.path, { type: mimeType })); } // Escape commit title to prevent injection const escapeCommitTitle = (title: string): string => { return title.replace(/[\r\n]/g, " ").slice(0, 200); };
const baseTitle = isManualChanges ? "" : `🐳 ${format(new Date(), "dd/MM")} - ${format(new Date(), "HH:mm")} - `; const commitTitle = escapeCommitTitle( baseTitle + (prompt ?? "Follow-up DeepSite commit") ); const response = await uploadFiles({ repo, files: filesToUpload, accessToken: token, commitTitle, });
return NextResponse.json( { success: true, commit: { oid: response.commit, title: commitTitle, date: new Date(), }, }, { status: 200 } );}
export async function DELETE( request: Request, { params }: { params: Promise<{ repoId: string }> }) { const { repoId }: { repoId: string } = await params; const session = await auth(); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const token = session.accessToken;
const repo: RepoDesignation = { type: "space", name: session.user?.username + "/" + repoId, };
try { await deleteRepo({ repo, accessToken: token as string, });
return NextResponse.json({ success: true }, { status: 200 }); } catch (error) { const errMsg = error instanceof Error ? error.message : "Failed to delete project"; return NextResponse.json({ error: errMsg }, { status: 500 }); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import { NextResponse } from "next/server";import { RepoDesignation, createRepo, uploadFiles } from "@huggingface/hub";
import { auth } from "@/lib/auth";import { COLORS, EMOJIS_FOR_SPACE, injectDeepSiteBadge, isIndexPage,} from "@/lib/utils";
// todo: catch error while publishing project, and return the error to the user// if space has been created, but can't push, try again or catch well the error and return the error to the user
export async function POST(request: Request) { const session = await auth(); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const token = session.accessToken;
const body = await request.json(); const { projectTitle, files, prompt } = body;
if (!files) { return NextResponse.json( { error: "Project title and files are required" }, { status: 400 } ); }
const title = projectTitle || projectTitle !== "" ? projectTitle : "DeepSite Project";
let formattedTitle = title .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .split("-") .filter(Boolean) .join("-") .slice(0, 75);
formattedTitle = formattedTitle + "-" + Math.random().toString(36).substring(2, 7);
const repo: RepoDesignation = { type: "space", name: session.user?.username + "/" + formattedTitle, };
// Escape YAML values to prevent injection attacks const escapeYamlValue = (value: string): string => { if (/[:|>]|^[-*#]|^\s|['"]/.test(value) || value.includes("\n")) { return `"${value.replace(/"/g, '\\"')}"`; } return value; };
// Escape markdown headers to prevent injection const escapeMarkdownHeader = (value: string): string => { return value.replace(/^#+\s*/g, "").replace(/\n/g, " "); };
const colorFrom = COLORS[Math.floor(Math.random() * COLORS.length)]; const colorTo = COLORS[Math.floor(Math.random() * COLORS.length)]; const emoji = EMOJIS_FOR_SPACE[Math.floor(Math.random() * EMOJIS_FOR_SPACE.length)]; const README = `---title: ${escapeYamlValue(projectTitle)}colorFrom: ${colorFrom}colorTo: ${colorTo}sdk: staticemoji: ${emoji}tags: - deepsite-v4---
# ${escapeMarkdownHeader(title)}
This project has been created with [DeepSite](https://deepsite.hf.co) AI Vibe Coding.`;
const filesToUpload: File[] = [ new File([README], "README.md", { type: "text/markdown" }), ]; for (const file of files) { let mimeType = "text/html"; if (file.path.endsWith(".css")) { mimeType = "text/css"; } else if (file.path.endsWith(".js")) { mimeType = "text/javascript"; } const content = mimeType === "text/html" && isIndexPage(file.path) ? injectDeepSiteBadge(file.content) : file.content;
filesToUpload.push(new File([content], file.path, { type: mimeType })); }
let repoUrl: string | undefined; try { // Create the space first const createResult = await createRepo({ accessToken: token as string, repo: repo, sdk: "static", }); repoUrl = createResult.repoUrl;
// Escape commit message to prevent injection const escapeCommitMessage = (message: string): string => { return message.replace(/[\r\n]/g, " ").slice(0, 200); }; const commitMessage = escapeCommitMessage(prompt ?? "Initial DeepSite commit"); // Upload files to the created space await uploadFiles({ repo, files: filesToUpload, accessToken: token as string, commitTitle: commitMessage, });
const path = repoUrl.split("/").slice(-2).join("/");
return NextResponse.json({ repoUrl: path }, { status: 200 }); } catch (error) { const errMsg = error instanceof Error ? error.message : "Failed to create or upload to space"; // If space was created but upload failed, include the repo URL in the error if (repoUrl) { const path = repoUrl.split("/").slice(-2).join("/"); return NextResponse.json({ error: `${errMsg}. Space was created at ${path} but files could not be uploaded.`, repoUrl: path, partialSuccess: true }, { status: 500 }); } return NextResponse.json({ error: errMsg }, { status: 500 }); }}123456784 unmodified lines1314151617185 unmodified lines24252627282930313210 unmodified lines43444546474849505152535455565758596061626364656667/* eslint-disable @typescript-eslint/no-explicit-any */import { NextRequest, NextResponse } from "next/server";const FETCH_TIMEOUT = 30_000;export const maxDuration = 60;export async function PUT(request: NextRequest) {const body = await request.json();4 unmodified lines}try {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT);5 unmodified linessignal: controller.signal,});clearTimeout(timeoutId);if (!response.ok) {return NextResponse.json({ error: "Failed to fetch redesign" },10 unmodified lines);} catch (fetchError: any) {clearTimeout(timeoutId);if (fetchError.name === "AbortError") {return NextResponse.json({error:"Request timeout: The external service took too long to respond. Please try again.",},{ status: 504 });}throw fetchError;}} catch (error: any) {if (error.name === "AbortError" || error.message?.includes("timeout")) {return NextResponse.json({error:"Request timeout: The external service took too long to respond. Please try again.",},{ status: 504 });}123456789104 unmodified lines151617181920215 unmodified lines27282930313233343510 unmodified lines4647484950515253545556575859606162636465import { NextRequest, NextResponse } from "next/server";// Timeout configuration (in milliseconds)const FETCH_TIMEOUT = 30000; // 30 seconds for external fetch// Extend the maximum execution time for this routeexport const maxDuration = 60; // 1 minuteexport async function PUT(request: NextRequest) {const body = await request.json();4 unmodified lines}try {// Create an AbortController for timeoutconst controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT);5 unmodified linessignal: controller.signal,});clearTimeout(timeoutId);if (!response.ok) {return NextResponse.json({ error: "Failed to fetch redesign" },10 unmodified lines);} catch (fetchError: any) {clearTimeout(timeoutId);if (fetchError.name === 'AbortError') {return NextResponse.json({ error: "Request timeout: The external service took too long to respond. Please try again." },{ status: 504 });}throw fetchError;}// eslint-disable-next-line @typescript-eslint/no-explicit-any} catch (error: any) {if (error.name === 'AbortError' || error.message?.includes('timeout')) {return NextResponse.json({ error: "Request timeout: The external service took too long to respond. Please try again." },{ status: 504 });}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"use client";import Link from "next/link";import { useUser } from "@/hooks/useUser";import { use, useState } from "react";import { useMount, useTimeoutFn } from "react-use";
import { Button } from "@/components/ui/button";import { AnimatedBlobs } from "@/components/animated-blobs";import { useBroadcastChannel } from "@/lib/useBroadcastChannel";export default function AuthCallback({ searchParams,}: { searchParams: Promise<{ code: string }>;}) { const [showButton, setShowButton] = useState(false); const [isPopupAuth, setIsPopupAuth] = useState(false); const { code } = use(searchParams); const { loginFromCode } = useUser(); const { postMessage } = useBroadcastChannel("auth", () => {});
useMount(async () => { if (code) { const isPopup = window.opener || window.parent !== window; setIsPopupAuth(isPopup);
if (isPopup) { postMessage({ type: "user-oauth", code: code, });
setTimeout(() => { if (window.opener) { window.close(); } }, 1000); } else { await loginFromCode(code); } } });
useTimeoutFn(() => setShowButton(true), 7000);
return ( <div className="h-screen flex flex-col justify-center items-center bg-neutral-950 z-1 relative"> <div className="background__noisy" /> <div className="relative max-w-4xl py-10 flex items-center justify-center w-full"> <div className="max-w-lg mx-auto !rounded-2xl !p-0 !bg-white !border-neutral-100 min-w-xs text-center overflow-hidden ring-[8px] ring-white/20"> <header className="bg-neutral-50 p-6 border-b border-neutral-200/60"> <div className="flex items-center justify-center -space-x-4 mb-3"> <div className="size-9 rounded-full bg-pink-200 shadow-2xs flex items-center justify-center text-xl opacity-50"> 🚀 </div> <div className="size-11 rounded-full bg-amber-200 shadow-2xl flex items-center justify-center text-2xl z-2"> 👋 </div> <div className="size-9 rounded-full bg-sky-200 shadow-2xs flex items-center justify-center text-xl opacity-50"> 🙌 </div> </div> <p className="text-xl font-semibold text-neutral-950"> {isPopupAuth ? "Authentication Complete!" : "Login In Progress..."} </p> <p className="text-sm text-neutral-500 mt-1.5"> {isPopupAuth ? "You can now close this tab and return to the previous page." : "Wait a moment while we log you in with your code."} </p> </header> <main className="space-y-4 p-6"> <div> <p className="text-sm text-neutral-700 mb-4 max-w-xs"> If you are not redirected automatically in the next 5 seconds, please click the button below </p> {showButton ? ( <Link href="/"> <Button variant="black" className="relative"> Go to Home </Button> </Link> ) : ( <p className="text-xs text-neutral-500"> Please wait, we are logging you in... </p> )} </div> </main> </div> <AnimatedBlobs /> </div> </div> );}12345678910111213141516171819202122232425262728import { redirect } from "next/navigation";import { Metadata } from "next";
import { getAuth } from "@/app/actions/auth";
export const revalidate = 1;
export const metadata: Metadata = { robots: "noindex, nofollow",};
export default async function Auth() { const loginRedirectUrl = await getAuth(); if (loginRedirectUrl) { redirect(loginRedirectUrl); }
return ( <div className="p-4"> <div className="border bg-red-500/10 border-red-500/20 text-red-500 px-5 py-3 rounded-lg"> <h1 className="text-xl font-bold">Error</h1> <p className="text-sm"> An error occurred while trying to log in. Please try again later. </p> </div> </div> );}12345678910111213141516171819202122232421 unmodified lines4647484950515253545556575859606162636465666768697071727312 unmodified lines8687888990919293949596979899100101102103104105106107import type { Metadata, Viewport } from "next";import { Geist, Geist_Mono } from "next/font/google";import { NextStepProvider } from "nextstepjs";import Script from "next/script";import "@/app/globals.css";import { ThemeProvider } from "@/components/providers/theme";import { AuthProvider } from "@/components/providers/session";import { Toaster } from "@/components/ui/sonner";import { ReactQueryProvider } from "@/components/providers/react-query";import { generateSEO, generateStructuredData } from "@/lib/seo";import { NotAuthorizedDomain } from "@/components/not-authorized";const geistSans = Geist({variable: "--font-geist-sans",subsets: ["latin"],});const geistMono = Geist_Mono({variable: "--font-geist-mono",subsets: ["latin"],});export const metadata: Metadata = {21 unmodified linesexport const viewport: Viewport = {initialScale: 1,maximumScale: 1,themeColor: "#4f46e5",};export default async function RootLayout({children,}: Readonly<{children: React.ReactNode;}>) {const structuredData = generateStructuredData("WebApplication", {name: "DeepSite",description: "Build websites with AI, no code required",url: "https://deepsite.hf.co",});const organizationData = generateStructuredData("Organization", {name: "DeepSite",url: "https://deepsite.hf.co",});return (<html lang="en" suppressHydrationWarning><bodyclassName={`${geistSans.variable} ${geistMono.variable} antialiased`}><scripttype="application/ld+json"12 unmodified linesdata-domain="deepsite.hf.co"src="https://plausible.io/js/script.js"/><Toaster richColors /><AuthProvider><ReactQueryProvider><ThemeProviderattribute="class"defaultTheme="dark"enableSystemdisableTransitionOnChange><NextStepProvider>{children}<NotAuthorizedDomain /></NextStepProvider></ThemeProvider></ReactQueryProvider></AuthProvider></body></html>);1234567891011121314151617181920212223242526272821 unmodified lines505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611712 unmodified lines130131132133134135136137138139140141142143144/* eslint-disable @typescript-eslint/no-explicit-any */import type { Metadata, Viewport } from "next";import { Inter, PT_Sans } from "next/font/google";import Script from "next/script";import { headers } from "next/headers";import { redirect } from "next/navigation";import "@/assets/globals.css";import { Toaster } from "@/components/ui/sonner";import IframeDetector from "@/components/iframe-detector";import AppContext from "@/components/contexts/app-context";import TanstackContext from "@/components/contexts/tanstack-query-context";import { LoginProvider } from "@/components/contexts/login-context";import { ProProvider } from "@/components/contexts/pro-context";import { generateSEO, generateStructuredData } from "@/lib/seo";const inter = Inter({variable: "--font-inter-sans",subsets: ["latin"],});const ptSans = PT_Sans({variable: "--font-ptSans-mono",subsets: ["latin"],weight: ["400", "700"],});export const metadata: Metadata = {21 unmodified linesexport const viewport: Viewport = {initialScale: 1,maximumScale: 1,themeColor: "#000000",};// async function getMe() {// const cookieStore = await cookies();// const cookieName = MY_TOKEN_KEY();// const token = cookieStore.get(cookieName)?.value;// if (!token) return { user: null, projects: [], errCode: null };// try {// const res = await apiServer.get("/me", {// headers: {// Authorization: `Bearer ${token}`,// },// });// return { user: res.data.user, projects: res.data.projects, errCode: null };// } catch (err: any) {// return { user: null, projects: [], errCode: err.status };// }// }export default async function RootLayout({children,}: Readonly<{children: React.ReactNode;}>) {// Domain redirect checkconst headersList = await headers();const forwardedHost = headersList.get("x-forwarded-host");const host = headersList.get("host");const hostname = (forwardedHost || host || "").split(":")[0];const isLocalDev =hostname === "localhost" ||hostname === "127.0.0.1" ||hostname.startsWith("192.168.");const isHuggingFace =hostname === "huggingface.co" || hostname.endsWith(".huggingface.co");if (!isHuggingFace && !isLocalDev) {const pathname = headersList.get("x-invoke-path") || "/deepsite";redirect(`https://huggingface.co${pathname}`);}// const data = await getMe();// Generate structured dataconst structuredData = generateStructuredData("WebApplication", {name: "DeepSite",description: "Build websites with AI, no code required",url: "https://huggingface.co/deepsite",});const organizationData = generateStructuredData("Organization", {name: "DeepSite",url: "https://huggingface.co/deepsite",});return (<html lang="en"><bodyclassName={`${inter.variable} ${ptSans.variable} antialiased bg-black dark h-[100dvh] overflow-hidden`}><scripttype="application/ld+json"12 unmodified linesdata-domain="deepsite.hf.co"src="https://plausible.io/js/script.js"/><IframeDetector /><Toaster richColors position="bottom-center" /><TanstackContext><AppContext><LoginProvider><ProProvider>{children}</ProProvider></LoginProvider></AppContext></TanstackContext></body></html>);
123456789101112131415161718import { AppEditor } from "@/components/editor";import { auth } from "@/lib/auth";import { redirect } from "next/navigation";export default async function NewProjectPage({searchParams,}: {searchParams: Promise<{ prompt: string }>;}) {const session = await auth();if (!session) {redirect("/api/auth/signin?callbackUrl=/new");}const { prompt } = await searchParams;return <AppEditor isNew={true} initialPrompt={prompt} />;}1234567891011121314import { AppEditor } from "@/components/editor";import { Metadata } from "next";import { generateSEO } from "@/lib/seo";export const metadata: Metadata = generateSEO({title: "Create New Project - DeepSite",description:"Start building your next website with AI. Create a new project on DeepSite and experience the power of AI-driven web development.",path: "/new",});export default function NewProjectPage() {return <AppEditor isNew />;}
1234567891011121314151617import { NotFoundButtons } from "@/components/not-found/buttons";import { Navigation } from "@/components/public/navigation";
export default function NotFound() { return ( <div className="min-h-screen font-sans"> <Navigation /> <div className="px-6 py-16 max-w-5xl mx-auto text-center"> <h1 className="text-5xl font-bold mb-5">Oh no! Page not found.</h1> <p className="text-lg text-muted-foreground mb-8"> The page you are looking for does not exist. </p> <NotFoundButtons /> </div> </div> );}12345678910111213141516171819202122232425262728import { MetadataRoute } from 'next';
export default function sitemap(): MetadataRoute.Sitemap { const baseUrl = 'https://huggingface.co/deepsite'; return [ { url: baseUrl, lastModified: new Date(), changeFrequency: 'daily', priority: 1, }, { url: `${baseUrl}/new`, lastModified: new Date(), changeFrequency: 'weekly', priority: 0.8, }, { url: `${baseUrl}/auth`, lastModified: new Date(), changeFrequency: 'monthly', priority: 0.5, }, // Note: Dynamic project routes will be handled by Next.js automatically // but you can add specific high-priority project pages here if needed ];}5 unmodified lines67891011121330 unmodified lines4445464748495017 unmodified lines6869707172737438 unmodified lines1131141151161171181 unmodified line1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671685 unmodified lines@theme inline {--color-background: var(--background);--color-foreground: var(--foreground);--font-sans: var(--font-geist-sans);--font-mono: var(--font-geist-mono);--color-sidebar-ring: var(--sidebar-ring);--color-sidebar-border: var(--sidebar-border);--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);30 unmodified lines}:root {--radius: 0.65rem;--background: oklch(1 0 0);--foreground: oklch(0.145 0 0);--card: oklch(1 0 0);17 unmodified lines--chart-3: oklch(0.398 0.07 227.392);--chart-4: oklch(0.828 0.189 84.429);--chart-5: oklch(0.769 0.188 70.08);--radius: 0.625rem;--sidebar: oklch(0.985 0 0);--sidebar-foreground: oklch(0.145 0 0);--sidebar-primary: oklch(0.205 0 0);38 unmodified lines--sidebar-ring: oklch(0.556 0 0);}@layer base {* {@apply border-border outline-ring/50;1 unmodified linebody {@apply bg-background text-foreground;}}.monaco-editor .margin {@apply bg-background!;}.monaco-editor .monaco-editor-background {@apply bg-background!;}.monaco-editor .decorationsOverviewRuler {@apply opacity-0!;}.monaco-editor .view-line {/* @apply bg-primary/50!; */}.monaco-editor .scroll-decoration {@apply opacity-0!;}.monaco-editor .cursors-layer .cursor {@apply bg-primary!;}.content-placeholder::before {content: attr(data-placeholder);position: absolute;pointer-events: none;opacity: 0.5;@apply top-5 left-6;}.sp-layout.sp-file-explorer.sp-file-explorer-list.sp-explorer[data-active="true"] {@apply text-indigo-500!;}.sp-layout.sp-stack.sp-tabs.sp-tab-container[aria-selected="true"].sp-tab-button {@apply text-indigo-500!;}.sp-layout .sp-stack .sp-tabs .sp-tab-container:has(button:focus) {@apply outline-none! border-none!;}5 unmodified lines67891011121330 unmodified lines4445464748495017 unmodified lines68697071727338 unmodified lines1121131141151161171181191201211 unmodified line1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703715 unmodified lines@theme inline {--color-background: var(--background);--color-foreground: var(--foreground);--font-sans: var(--font-inter-sans);--font-mono: var(--font-ptSans-mono);--color-sidebar-ring: var(--sidebar-ring);--color-sidebar-border: var(--sidebar-border);--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);30 unmodified lines}:root {--radius: 0.625rem;--background: oklch(1 0 0);--foreground: oklch(0.145 0 0);--card: oklch(1 0 0);17 unmodified lines--chart-3: oklch(0.398 0.07 227.392);--chart-4: oklch(0.828 0.189 84.429);--chart-5: oklch(0.769 0.188 70.08);--sidebar: oklch(0.985 0 0);--sidebar-foreground: oklch(0.145 0 0);--sidebar-primary: oklch(0.205 0 0);38 unmodified lines--sidebar-ring: oklch(0.556 0 0);}body {@apply scroll-smooth}@layer base {* {@apply border-border outline-ring/50;1 unmodified linebody {@apply bg-background text-foreground;}html {@apply scroll-smooth;}}.background__noisy {@apply bg-blend-normal pointer-events-none opacity-90;background-size: 25ww auto;background-image: url("/deepsite/background_noisy.webp");@apply fixed w-screen h-screen -z-1 top-0 left-0;}.monaco-editor .margin {@apply !bg-neutral-900;}.monaco-editor .monaco-editor-background {@apply !bg-neutral-900;}.monaco-editor .line-numbers {@apply !text-neutral-500;}.matched-line {@apply bg-sky-500/30;}/* Fast liquid deformation animations */@keyframes liquidBlob1 {0%, 100% {border-radius: 40% 60% 50% 50%;transform: scaleX(1) scaleY(1) rotate(0deg);}12.5% {border-radius: 20% 80% 70% 30%;transform: scaleX(1.6) scaleY(0.4) rotate(25deg);}25% {border-radius: 80% 20% 30% 70%;transform: scaleX(0.5) scaleY(2.1) rotate(-15deg);}37.5% {border-radius: 30% 70% 80% 20%;transform: scaleX(1.8) scaleY(0.6) rotate(40deg);}50% {border-radius: 70% 30% 20% 80%;transform: scaleX(0.4) scaleY(1.9) rotate(-30deg);}62.5% {border-radius: 25% 75% 60% 40%;transform: scaleX(1.5) scaleY(0.7) rotate(55deg);}75% {border-radius: 75% 25% 40% 60%;transform: scaleX(0.6) scaleY(1.7) rotate(-10deg);}87.5% {border-radius: 50% 50% 75% 25%;transform: scaleX(1.3) scaleY(0.8) rotate(35deg);}}@keyframes liquidBlob2 {0%, 100% {border-radius: 60% 40% 50% 50%;transform: scaleX(1) scaleY(1) rotate(12deg);}16% {border-radius: 15% 85% 60% 40%;transform: scaleX(0.3) scaleY(2.3) rotate(50deg);}32% {border-radius: 85% 15% 25% 75%;transform: scaleX(2.0) scaleY(0.5) rotate(-20deg);}48% {border-radius: 30% 70% 85% 15%;transform: scaleX(0.4) scaleY(1.8) rotate(70deg);}64% {border-radius: 70% 30% 15% 85%;transform: scaleX(1.9) scaleY(0.6) rotate(-35deg);}80% {border-radius: 40% 60% 70% 30%;transform: scaleX(0.7) scaleY(1.6) rotate(45deg);}}@keyframes liquidBlob3 {0%, 100% {border-radius: 50% 50% 40% 60%;transform: scaleX(1) scaleY(1) rotate(0deg);}20% {border-radius: 10% 90% 75% 25%;transform: scaleX(2.2) scaleY(0.3) rotate(-45deg);}40% {border-radius: 90% 10% 20% 80%;transform: scaleX(0.4) scaleY(2.5) rotate(60deg);}60% {border-radius: 25% 75% 90% 10%;transform: scaleX(1.7) scaleY(0.5) rotate(-25deg);}80% {border-radius: 75% 25% 10% 90%;transform: scaleX(0.6) scaleY(2.0) rotate(80deg);}}@keyframes liquidBlob4 {0%, 100% {border-radius: 45% 55% 50% 50%;transform: scaleX(1) scaleY(1) rotate(-15deg);}14% {border-radius: 90% 10% 65% 35%;transform: scaleX(0.2) scaleY(2.8) rotate(35deg);}28% {border-radius: 10% 90% 20% 80%;transform: scaleX(2.4) scaleY(0.4) rotate(-50deg);}42% {border-radius: 35% 65% 90% 10%;transform: scaleX(0.3) scaleY(2.1) rotate(70deg);}56% {border-radius: 80% 20% 10% 90%;transform: scaleX(2.0) scaleY(0.5) rotate(-40deg);}70% {border-radius: 20% 80% 55% 45%;transform: scaleX(0.5) scaleY(1.9) rotate(55deg);}84% {border-radius: 65% 35% 80% 20%;transform: scaleX(1.6) scaleY(0.6) rotate(-25deg);}}/* Fast flowing movement animations */@keyframes liquidFlow1 {0%, 100% { transform: translate(0, 0); }16% { transform: translate(60px, -40px); }32% { transform: translate(-45px, -70px); }48% { transform: translate(80px, 25px); }64% { transform: translate(-30px, 60px); }80% { transform: translate(50px, -20px); }}@keyframes liquidFlow2 {0%, 100% { transform: translate(0, 0); }20% { transform: translate(-70px, 50px); }40% { transform: translate(90px, -30px); }60% { transform: translate(-40px, -55px); }80% { transform: translate(65px, 35px); }}@keyframes liquidFlow3 {0%, 100% { transform: translate(0, 0); }12% { transform: translate(-50px, -60px); }24% { transform: translate(40px, -20px); }36% { transform: translate(-30px, 70px); }48% { transform: translate(70px, 20px); }60% { transform: translate(-60px, -35px); }72% { transform: translate(35px, 55px); }84% { transform: translate(-25px, -45px); }}@keyframes liquidFlow4 {0%, 100% { transform: translate(0, 0); }14% { transform: translate(50px, 60px); }28% { transform: translate(-80px, -40px); }42% { transform: translate(30px, -90px); }56% { transform: translate(-55px, 45px); }70% { transform: translate(75px, -25px); }84% { transform: translate(-35px, 65px); }}/* Light sweep animation for buttons */@keyframes lightSweep {0% {transform: translateX(-150%);opacity: 0;}8% {opacity: 0.3;}25% {opacity: 0.8;}42% {opacity: 0.3;}50% {transform: translateX(150%);opacity: 0;}58% {opacity: 0.3;}75% {opacity: 0.8;}92% {opacity: 0.3;}100% {transform: translateX(-150%);opacity: 0;}}.light-sweep {position: relative;overflow: hidden;}.light-sweep::before {content: '';position: absolute;top: 0;left: 0;right: 0;bottom: 0;width: 300%;background: linear-gradient(90deg,transparent 0%,transparent 20%,rgba(56, 189, 248, 0.1) 35%,rgba(56, 189, 248, 0.2) 45%,rgba(255, 255, 255, 0.2) 50%,rgba(168, 85, 247, 0.2) 55%,rgba(168, 85, 247, 0.1) 65%,transparent 80%,transparent 100%);animation: lightSweep 7s cubic-bezier(0.4, 0, 0.2, 1) infinite;pointer-events: none;z-index: 1;filter: blur(1px);}
12345apiVersion: v2name: deepsiteversion: 0.0.0-latesttype: applicationicon: https://huggingface.co/front/assets/huggingface_logo-noborder.svg1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859nodeSelector: role-deepsite: "true"
tolerations: - key: "huggingface.co/deepsite" operator: "Equal" value: "true" effect: "NoSchedule"
serviceAccount: enabled: true create: true name: deepsite-prod
ingress: path: "/" annotations: alb.ingress.kubernetes.io/healthcheck-path: "/api/healthcheck" alb.ingress.kubernetes.io/listen-ports: "[{\"HTTP\": 80}, {\"HTTPS\": 443}]" alb.ingress.kubernetes.io/load-balancer-name: "hub-utils-prod-cloudfront" alb.ingress.kubernetes.io/group.name: "hub-utils-prod-cloudfront" alb.ingress.kubernetes.io/scheme: "internal" alb.ingress.kubernetes.io/ssl-redirect: "443" alb.ingress.kubernetes.io/tags: "Env=prod,Project=hub,Terraform=true" alb.ingress.kubernetes.io/target-group-attributes: deregistration_delay.timeout_seconds=30 alb.ingress.kubernetes.io/target-type: "ip" alb.ingress.kubernetes.io/certificate-arn: "arn:aws:acm:us-east-1:707930574880:certificate/5b25b145-75db-4837-b9f3-7f238ba8a9c7,arn:aws:acm:us-east-1:707930574880:certificate/bfdf509c-f44b-400f-b9e1-6f7a861abe91" kubernetes.io/ingress.class: "alb"
networkPolicy: enabled: true allowedBlocks: - 10.0.0.0/16
ingressInternal: enabled: false
envVars: NEXTAUTH_URL: https://deepsite.hf.co/api/auth
infisical: enabled: true env: "prod-us-east-1"
autoscaling: enabled: true minReplicas: 1 maxReplicas: 10 targetMemoryUtilizationPercentage: "50" targetCPUUtilizationPercentage: "50"
resources: requests: cpu: 2 memory: 4Gi limits: cpu: 4 memory: 8Gi12345678910111213141516171819202122{{- define "name" -}}{{- default $.Release.Name | trunc 63 | trimSuffix "-" -}}{{- end -}}
{{- define "app.name" -}}chat-ui{{- end -}}
{{- define "labels.standard" -}}release: {{ $.Release.Name | quote }}heritage: {{ $.Release.Service | quote }}chart: "{{ include "name" . }}"app: "{{ include "app.name" . }}"{{- end -}}
{{- define "labels.resolver" -}}release: {{ $.Release.Name | quote }}heritage: {{ $.Release.Service | quote }}chart: "{{ include "name" . }}"app: "{{ include "app.name" . }}-resolver"{{- end -}}
.env.exampleDeleted-4
.github/workflows/deploy-prod.ymlDeleted-77
.gitignore+1-7
Dockerfile+6-9
MCP-SERVER.mdAdded+428
README.md+11-8
actions/mentions.tsDeleted-31
actions/projects.tsDeleted-175
app/(public)/layout.tsx+4-3
app/(public)/page.tsx+3-23
app/(public)/signin/page.tsxDeleted-21
app/[namespace]/[repoId]/page.tsxAdded+28
app/[owner]/[repoId]/page.tsxDeleted-35
app/actions/auth.tsAdded+18
app/actions/projects.tsAdded+47
app/api/ask/route.ts+361-135
app/api/auth/[...nextauth]/route.tsDeleted-6
app/api/auth/login-url/route.tsAdded+21
app/api/auth/logout/route.tsAdded+25
app/api/auth/route.tsAdded+86
app/api/healthcheck/route.tsDeleted-5
app/api/mcp/route.tsAdded+435
app/api/me/projects/[namespace]/[repoId]/commits/[commitId]/promote/route.tsAdded+230
app/api/me/projects/[namespace]/[repoId]/commits/[commitId]/route.tsAdded+102
app/api/me/projects/[namespace]/[repoId]/images/route.tsAdded+125
app/api/me/projects/[namespace]/[repoId]/route.tsAdded+197
app/api/me/projects/[namespace]/[repoId]/save/route.tsAdded+72
app/api/me/projects/[namespace]/[repoId]/update/route.tsAdded+141
app/api/me/projects/route.tsAdded+121
app/api/me/route.tsAdded+46
app/api/projects/[repoId]/[commitId]/route.tsDeleted-49
app/api/projects/[repoId]/download/route.tsDeleted-76
app/api/projects/[repoId]/medias/route.tsDeleted-87
app/api/projects/[repoId]/rename/route.tsDeleted-92
app/api/projects/[repoId]/route.tsDeleted-104
app/api/projects/route.tsDeleted-145
app/api/redesign/route.ts → app/api/re-design/route.tsRenamed+14-16
app/auth/callback/page.tsxAdded+97
app/auth/page.tsxAdded+28
app/layout.tsx+69-32
app/new/page.tsx+10-14
app/not-found.tsxDeleted-17
app/sitemap.tsAdded+28
app/globals.css → assets/globals.cssRenamed+236-33
assets/hf-logo.svgDeleted
assets/logo.svgAdded
assets/pro.svgDeleted
chart/Chart.yamlDeleted-5
chart/env/prod.yamlDeleted-59
chart/templates/_helpers.tplDeleted-22