diff --git a/Index.html b/Index.html new file mode 100644 index 0000000000000000000000000000000000000000..2b4b665b0abe4985b470d46a5b10772e94a4b08f --- /dev/null +++ b/Index.html @@ -0,0 +1,27 @@ + + + + + Mon site + + + + +

Bienvenue sur mon site πŸš€

+

Ce site a Γ©tΓ© dΓ©ployΓ© avec Hugging Face Spaces.

+ + \ No newline at end of file diff --git a/MCP-SERVER.md b/MCP-SERVER.md deleted file mode 100644 index 675acdbb77beeb3bdc3e0b7b49a2e01d39df1b58..0000000000000000000000000000000000000000 --- a/MCP-SERVER.md +++ /dev/null @@ -1,428 +0,0 @@ -# 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/tokens -2. Create a new token with `write` access -3. Copy the token -4. 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` tool -2. Authenticate using the token from your config -3. Create the website on Hugging Face Spaces -4. 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 - -```bash -cd mcp-server -npm install -npm 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/deepsite -2. Open Developer Tools (F12) -3. Go to Application β†’ Cookies -4. Copy the session cookie value -5. 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) - -```bash -curl -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": "Hello

Hello World!

" - } - ] - } - } - }' -``` - -### Using Token Parameter (Fallback) - -```bash -curl -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": "Hello

Hello World!

" - } - ], - "hf_token": "hf_xxxxx" - } - } - }' -``` - -### List Available Tools - -```bash -curl -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 - -```bash -cd mcp-server -./test.sh -``` - -### Test HTTP Server - -```bash -curl -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) - diff --git a/README.md b/README.md index 7ccf31d982730ec847528e80004330ab71f11539..f33f84d940c051642f6c1d0b829c4db5f52f40b4 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ --- -title: DeepSite v3 +title: DeepSite v2 emoji: 🐳 colorFrom: blue colorTo: blue @@ -7,23 +7,19 @@ sdk: docker pinned: true app_port: 3000 license: mit -short_description: Generate any application by Vibe Coding +short_description: Generate any application with DeepSeek models: - 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 --- # DeepSite 🐳 -DeepSite is a Vibe Coding Platform designed to make coding smarter and more efficient. Tailored for developers, data scientists, and AI engineers, it integrates generative AI into your coding projects to enhance creativity and productivity. +DeepSite is a coding platform powered by DeepSeek AI, designed to make coding smarter and more efficient. Tailored for developers, data scientists, and AI engineers, it integrates generative AI into your coding projects to enhance creativity and productivity. ## How to use it locally -Follow [this discussion](https://huggingface.co/spaces/enzostvs/deepsite/discussions/74) \ No newline at end of file +Follow [this discussion](https://huggingface.co/spaces/enzostvs/deepsite/discussions/74) diff --git a/app/(public)/layout.tsx b/app/(public)/layout.tsx index 4c640fb83ccfced8842764d029c87a2d85718d65..4a4ec57d2609c783602beb6c06c8dca6a1e6192d 100644 --- a/app/(public)/layout.tsx +++ b/app/(public)/layout.tsx @@ -6,7 +6,7 @@ export default async function PublicLayout({ children: React.ReactNode; }>) { return ( -
+
{children} diff --git a/app/(public)/page.tsx b/app/(public)/page.tsx index e2d5c88a4977801d6acabd904535b00ad622a267..c0849e72cf29027524ec9ebc3818e80a8aee5ef3 100644 --- a/app/(public)/page.tsx +++ b/app/(public)/page.tsx @@ -1,5 +1,44 @@ -import { MyProjects } from "@/components/my-projects"; - -export default async function HomePage() { - return ; +import { AskAi } from "@/components/space/ask-ai"; +import { redirect } from "next/navigation"; +export default function Home() { + redirect("/projects/new"); + return ( + <> +
+
+ ✨ DeepSite Public Beta +
+

+ Code your website with AI in seconds +

+

+ Vibe Coding has never been so easy. +

+
+ +
+
+
+
+
+
+
+
+
+

+ Community Driven +

+
+
+

+ Deploy your website in seconds +

+
+
+

+ Features that make you smile +

+
+ + ); } diff --git a/app/(public)/projects/page.tsx b/app/(public)/projects/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..374dc6b1194256c5b142a62168ce0f414f6098be --- /dev/null +++ b/app/(public)/projects/page.tsx @@ -0,0 +1,13 @@ +import { redirect } from "next/navigation"; + +import { MyProjects } from "@/components/my-projects"; +import { getProjects } from "@/app/actions/projects"; + +export default async function ProjectsPage() { + const { ok, projects } = await getProjects(); + if (!ok) { + redirect("/"); + } + + return ; +} diff --git a/app/[namespace]/[repoId]/page.tsx b/app/[namespace]/[repoId]/page.tsx deleted file mode 100644 index 19a09d72477dd437fa8a786601cbc584676609ee..0000000000000000000000000000000000000000 --- a/app/[namespace]/[repoId]/page.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { 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 { - 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 ; -} diff --git a/app/actions/auth.ts b/app/actions/auth.ts index b0028105705dde5ace29f4484398edbd0e9c9dc0..a343e65e6726b35b32f022c117d3f3b5187d78e6 100644 --- a/app/actions/auth.ts +++ b/app/actions/auth.ts @@ -11,7 +11,7 @@ export async function getAuth() { const redirect_uri = `${host.includes("localhost") ? "http://" : "https://"}` + url + - "/deepsite/auth/callback"; + "/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; diff --git a/app/actions/projects.ts b/app/actions/projects.ts index 5f99d85273352e21e22efb85b03bced1cf210897..209b16d9d9960eeafb9e0b02d7b1b3eda638338d 100644 --- a/app/actions/projects.ts +++ b/app/actions/projects.ts @@ -2,13 +2,13 @@ import { isAuthenticated } from "@/lib/auth"; import { NextResponse } from "next/server"; -import { listSpaces } from "@huggingface/hub"; -import { ProjectType } from "@/types"; +import dbConnect from "@/lib/mongodb"; +import Project from "@/models/Project"; +import { Project as ProjectType } from "@/types"; export async function getProjects(): Promise<{ ok: boolean; projects: ProjectType[]; - isEmpty?: boolean; }> { const user = await isAuthenticated(); @@ -19,29 +19,45 @@ export async function getProjects(): Promise<{ }; } - 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); - } + await dbConnect(); + const projects = await Project.find({ + user_id: user?.id, + }) + .sort({ _createdAt: -1 }) + .limit(100) + .lean(); + if (!projects) { + return { + ok: false, + projects: [], + }; } - return { ok: true, - projects, + projects: JSON.parse(JSON.stringify(projects)) as ProjectType[], }; } + +export async function getProject( + namespace: string, + repoId: string +): Promise { + const user = await isAuthenticated(); + + if (user instanceof NextResponse || !user) { + return null; + } + + await dbConnect(); + const project = await Project.findOne({ + user_id: user.id, + namespace, + repoId, + }).lean(); + + if (!project) { + return null; + } + + return JSON.parse(JSON.stringify(project)) as ProjectType; +} diff --git a/app/api/ask-ai/route.ts b/app/api/ask-ai/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac076fe255c99ff9e33417e5cde007e291ece123 --- /dev/null +++ b/app/api/ask-ai/route.ts @@ -0,0 +1,419 @@ +/* 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, PROVIDERS } from "@/lib/providers"; +import { + DIVIDER, + FOLLOW_UP_SYSTEM_PROMPT, + INITIAL_SYSTEM_PROMPT, + MAX_REQUESTS_PER_IP, + REPLACE_END, + SEARCH_START, +} from "@/lib/prompts"; +import MY_TOKEN_KEY from "@/lib/get-cookie-name"; + +const ipAddresses = new Map(); + +export async function POST(request: NextRequest) { + const authHeaders = await headers(); + const userToken = request.cookies.get(MY_TOKEN_KEY())?.value; + + const body = await request.json(); + const { prompt, provider, model, redesignMarkdown, html } = 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 } + ); + } + + if (!selectedModel.providers.includes(provider) && provider !== "auto") { + return NextResponse.json( + { + ok: false, + error: `The selected model does not support the ${provider} provider.`, + openSelectProvider: true, + }, + { status: 400 } + ); + } + + let 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 DEFAULT_PROVIDER = PROVIDERS.novita; + const selectedProvider = + provider === "auto" + ? PROVIDERS[selectedModel.autoProvider as keyof typeof PROVIDERS] + : PROVIDERS[provider as keyof typeof PROVIDERS] ?? DEFAULT_PROVIDER; + + try { + // Create a stream response + const encoder = new TextEncoder(); + const stream = new TransformStream(); + const writer = stream.writable.getWriter(); + + // Start the response + const response = new NextResponse(stream.readable, { + headers: { + "Content-Type": "text/plain; charset=utf-8", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }, + }); + + (async () => { + let completeResponse = ""; + try { + const client = new InferenceClient(token); + const chatCompletion = client.chatCompletionStream( + { + model: selectedModel.value, + provider: selectedProvider.id as any, + messages: [ + { + role: "system", + content: INITIAL_SYSTEM_PROMPT, + }, + { + role: "user", + content: redesignMarkdown + ? `Here is my current design as a markdown:\n\n${redesignMarkdown}\n\nNow, please create a new design based on this markdown.` + : html + ? `Here is my current HTML code:\n\n\`\`\`html\n${html}\n\`\`\`\n\nNow, please create a new design based on this HTML.` + : prompt, + }, + ], + max_tokens: selectedProvider.max_tokens, + }, + billTo ? { billTo } : {} + ); + + while (true) { + const { done, value } = await chatCompletion.next(); + if (done) { + break; + } + + const chunk = value.choices[0]?.delta?.content; + if (chunk) { + let newChunk = chunk; + if (!selectedModel?.isThinker) { + if (provider !== "sambanova") { + await writer.write(encoder.encode(chunk)); + completeResponse += chunk; + + if (completeResponse.includes("")) { + break; + } + } else { + if (chunk.includes("")) { + newChunk = newChunk.replace(/<\/html>[\s\S]*/, ""); + } + completeResponse += newChunk; + await writer.write(encoder.encode(newChunk)); + if (newChunk.includes("")) { + break; + } + } + } else { + const lastThinkTagIndex = + completeResponse.lastIndexOf(""); + completeResponse += newChunk; + await writer.write(encoder.encode(newChunk)); + if (lastThinkTagIndex !== -1) { + const afterLastThinkTag = completeResponse.slice( + lastThinkTagIndex + "".length + ); + if (afterLastThinkTag.includes("")) { + break; + } + } + } + } + } + } 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 { + await writer.write( + encoder.encode( + JSON.stringify({ + ok: false, + message: + error.message || + "An error occurred while processing your request.", + }) + ) + ); + } + } finally { + await writer?.close(); + } + })(); + + 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 authHeaders = await headers(); + const userToken = request.cookies.get(MY_TOKEN_KEY())?.value; + + const body = await request.json(); + const { prompt, html, previousPrompt, provider, selectedElementHtml, model } = + body; + + if (!prompt || !html) { + 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 = 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 client = new InferenceClient(token); + + const DEFAULT_PROVIDER = PROVIDERS.novita; + const selectedProvider = + provider === "auto" + ? PROVIDERS[selectedModel.autoProvider as keyof typeof PROVIDERS] + : PROVIDERS[provider as keyof typeof PROVIDERS] ?? DEFAULT_PROVIDER; + + try { + const response = await client.chatCompletion( + { + model: selectedModel.value, + provider: selectedProvider.id as any, + messages: [ + { + role: "system", + content: FOLLOW_UP_SYSTEM_PROMPT, + }, + { + role: "user", + content: previousPrompt + ? previousPrompt + : "You are modifying the HTML file based on the user's request.", + }, + { + role: "assistant", + + content: `The current code is: \n\`\`\`html\n${html}\n\`\`\` ${ + selectedElementHtml + ? `\n\nYou have to update ONLY the following element, NOTHING ELSE: \n\n\`\`\`html\n${selectedElementHtml}\n\`\`\`` + : "" + }`, + }, + { + role: "user", + content: prompt, + }, + ], + ...(selectedProvider.id !== "sambanova" + ? { + max_tokens: selectedProvider.max_tokens, + } + : {}), + }, + billTo ? { billTo } : {} + ); + + const chunk = response.choices[0]?.message?.content; + if (!chunk) { + return NextResponse.json( + { ok: false, message: "No content returned from the model" }, + { status: 400 } + ); + } + + if (chunk) { + const updatedLines: number[][] = []; + let newHtml = html; + let position = 0; + let moreBlocks = true; + + while (moreBlocks) { + const searchStartIndex = chunk.indexOf(SEARCH_START, position); + if (searchStartIndex === -1) { + moreBlocks = false; + continue; + } + + const dividerIndex = chunk.indexOf(DIVIDER, searchStartIndex); + if (dividerIndex === -1) { + moreBlocks = false; + continue; + } + + const replaceEndIndex = chunk.indexOf(REPLACE_END, dividerIndex); + if (replaceEndIndex === -1) { + moreBlocks = false; + continue; + } + + const searchBlock = chunk.substring( + searchStartIndex + SEARCH_START.length, + dividerIndex + ); + const replaceBlock = chunk.substring( + dividerIndex + DIVIDER.length, + replaceEndIndex + ); + + if (searchBlock.trim() === "") { + newHtml = `${replaceBlock}\n${newHtml}`; + updatedLines.push([1, replaceBlock.split("\n").length]); + } else { + const blockPosition = newHtml.indexOf(searchBlock); + if (blockPosition !== -1) { + const beforeText = newHtml.substring(0, blockPosition); + const startLineNumber = beforeText.split("\n").length; + const replaceLines = replaceBlock.split("\n").length; + const endLineNumber = startLineNumber + replaceLines - 1; + + updatedLines.push([startLineNumber, endLineNumber]); + newHtml = newHtml.replace(searchBlock, replaceBlock); + } + } + + position = replaceEndIndex + REPLACE_END.length; + } + + return NextResponse.json({ + ok: true, + html: newHtml, + updatedLines, + }); + } else { + return NextResponse.json( + { ok: false, message: "No content returned from the model" }, + { status: 400 } + ); + } + } catch (error: any) { + if (error.message?.includes("exceeded your monthly included credits")) { + return NextResponse.json( + { + ok: false, + openProModal: true, + message: error.message, + }, + { status: 402 } + ); + } + return NextResponse.json( + { + ok: false, + openSelectProvider: true, + message: + error.message || "An error occurred while processing your request.", + }, + { status: 500 } + ); + } +} diff --git a/app/api/ask/route.ts b/app/api/ask/route.ts deleted file mode 100644 index d7e3d3aa77287b113448240d784008beefba945a..0000000000000000000000000000000000000000 --- a/app/api/ask/route.ts +++ /dev/null @@ -1,404 +0,0 @@ -/* 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, - INITIAL_SYSTEM_PROMPT, - MAX_REQUESTS_PER_IP, - PROMPT_FOR_PROJECT_NAME, -} from "@/lib/prompts"; -import { calculateMaxTokens, estimateInputTokens, getProviderSpecificConfig } from "@/lib/max-tokens"; -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 userToken = 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(); - 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 () => { - // let completeResponse = ""; - try { - const client = new InferenceClient(token); - - const systemPrompt = INITIAL_SYSTEM_PROMPT; - - const userPrompt = rewrittenPrompt; - const estimatedInputTokens = estimateInputTokens(systemPrompt, userPrompt); - const dynamicMaxTokens = calculateMaxTokens(selectedProvider, estimatedInputTokens, true); - const providerConfig = getProviderSpecificConfig(selectedProvider, dynamicMaxTokens); - - const chatCompletion = client.chatCompletionStream( - { - model: selectedModel.value, - provider: selectedProvider.provider, - 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.` : "") - }, - ], - ...providerConfig, - }, - billTo ? { billTo } : {} - ); - - 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: 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 systemPrompt = FOLLOW_UP_SYSTEM_PROMPT + (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 estimatedInputTokens = estimateInputTokens(systemPrompt, prompt, userContext + assistantContext); - const dynamicMaxTokens = calculateMaxTokens(selectedProvider, estimatedInputTokens, false); - const providerConfig = getProviderSpecificConfig(selectedProvider, dynamicMaxTokens); - - const chatCompletion = client.chatCompletionStream( - { - model: selectedModel.value, - provider: selectedProvider.provider, - messages: [ - { - role: "system", - content: systemPrompt, - }, - { - role: "user", - content: userContext, - }, - { - role: "assistant", - content: assistantContext, - }, - { - role: "user", - content: prompt, - }, - ], - ...providerConfig, - }, - billTo ? { billTo } : {} - ); - - // Stream the response chunks to the client - 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.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 } - ); - } -} - diff --git a/app/api/auth/login-url/route.ts b/app/api/auth/login-url/route.ts deleted file mode 100644 index e46df350e48e088ad278dec248f55651cdefd027..0000000000000000000000000000000000000000 --- a/app/api/auth/login-url/route.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { 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 }); -} diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.ts deleted file mode 100644 index 01feb588119d8472e23d61fffbc6f43d8f5a508c..0000000000000000000000000000000000000000 --- a/app/api/auth/logout/route.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { 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; -} diff --git a/app/api/auth/route.ts b/app/api/auth/route.ts index f826af35fa35c5767a318d1e146e77fb6fc07592..221e0c266bd2e6673779b9e81caf333243147f60 100644 --- a/app/api/auth/route.ts +++ b/app/api/auth/route.ts @@ -24,12 +24,12 @@ export async function POST(req: NextRequest) { req.headers.get("host") ?? req.headers.get("origin") ?? "localhost:3000"; const url = host.includes("/spaces/enzostvs") - ? "huggingface.co/deepsite" + ? "enzostvs-deepsite.hf.space" : host; const redirect_uri = `${host.includes("localhost") ? "http://" : "https://"}` + url + - "/deepsite/auth/callback"; + "/auth/callback"; const request_auth = await fetch("https://huggingface.co/oauth/token", { method: "POST", headers: { diff --git a/app/api/mcp/route.ts b/app/api/mcp/route.ts deleted file mode 100644 index be92c97380e2ad66379edede9fe07b96f697ff49..0000000000000000000000000000000000000000 --- a/app/api/mcp/route.ts +++ /dev/null @@ -1,435 +0,0 @@ -import { 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 route -export const maxDuration = 180; // 3 minutes - -// Utility function to wrap promises with timeout -async function withTimeout( - promise: Promise, - timeoutMs: number, - errorMessage: string = "Operation timed out" -): Promise { - let timeoutId: NodeJS.Timeout; - - const timeoutPromise = new Promise((_, 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 HTTP -export 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 CORS -export 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: static -pinned: false -tags: - - 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((_, 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"); - } -} - diff --git a/app/api/me/projects/[namespace]/[repoId]/commits/[commitId]/promote/route.ts b/app/api/me/projects/[namespace]/[repoId]/commits/[commitId]/promote/route.ts deleted file mode 100644 index 1e070e50ad1654ddd200786d4feac6d6919c8502..0000000000000000000000000000000000000000 --- a/app/api/me/projects/[namespace]/[repoId]/commits/[commitId]/promote/route.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { NextRequest, NextResponse } from "next/server"; -import { RepoDesignation, listFiles, spaceInfo, uploadFiles, deleteFiles } 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 } - ); - } - - // Fetch files from the specific commit - const files: File[] = []; - const pages: Page[] = []; - const allowedExtensions = ["html", "md", "css", "js", "json", "txt"]; - const commitFilePaths: Set = new Set(); - - // Get all files from the specific commit - for await (const fileInfo of listFiles({ - repo, - accessToken: user.token as string, - revision: commitId, - })) { - const fileExtension = fileInfo.path.split('.').pop()?.toLowerCase(); - - if (allowedExtensions.includes(fileExtension || "")) { - commitFilePaths.add(fileInfo.path); - - // Fetch the file content from the specific commit - const response = await fetch( - `https://huggingface.co/spaces/${namespace}/${repoId}/raw/${commitId}/${fileInfo.path}` - ); - - if (response.ok) { - const content = await response.text(); - let mimeType = "text/plain"; - - switch (fileExtension) { - case "html": - mimeType = "text/html"; - // Add HTML files to pages array for client-side setPages - pages.push({ - path: fileInfo.path, - html: content, - }); - break; - case "css": - mimeType = "text/css"; - break; - case "js": - mimeType = "application/javascript"; - break; - case "json": - mimeType = "application/json"; - break; - case "md": - mimeType = "text/markdown"; - break; - } - - const file = new File([content], fileInfo.path, { type: mimeType }); - files.push(file); - } - } - } - - // Get files currently in main branch to identify files to delete - const mainBranchFilePaths: Set = 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); - } - } - - // Identify files to delete (exist in main but not in commit) - 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 } - ); - } - - // Delete files that exist in main but not in the commit being promoted - 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')}`, - }); - } - - // Upload the files to the main branch with a promotion commit message - 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, - }, - { 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 } - ); - } -} diff --git a/app/api/me/projects/[namespace]/[repoId]/images/route.ts b/app/api/me/projects/[namespace]/[repoId]/images/route.ts deleted file mode 100644 index 6ac05307e5bc176942f949d69bbe945da7a70323..0000000000000000000000000000000000000000 --- a/app/api/me/projects/[namespace]/[repoId]/images/route.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { 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 } - ); - } -} diff --git a/app/api/me/projects/[namespace]/[repoId]/route.ts b/app/api/me/projects/[namespace]/[repoId]/route.ts index 7b415ad866247b536526bf9f758e8f35ab8138da..5b5bb19a9fe7a91d48b8b8cbcf340f1508032baf 100644 --- a/app/api/me/projects/[namespace]/[repoId]/route.ts +++ b/app/api/me/projects/[namespace]/[repoId]/route.ts @@ -1,10 +1,12 @@ import { NextRequest, NextResponse } from "next/server"; -import { RepoDesignation, spaceInfo, listFiles, deleteRepo, listCommits, downloadFile } from "@huggingface/hub"; +import { RepoDesignation, spaceInfo, uploadFile } from "@huggingface/hub"; import { isAuthenticated } from "@/lib/auth"; -import { Commit, Page } from "@/types"; +import Project from "@/models/Project"; +import dbConnect from "@/lib/mongodb"; +import { getPTag } from "@/lib/utils"; -export async function DELETE( +export async function GET( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string }> } ) { @@ -14,63 +16,24 @@ export async function DELETE( return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); } + await dbConnect(); 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) { + const project = await Project.findOne({ + user_id: user.id, + space_id: `${namespace}/${repoId}`, + }).lean(); + if (!project) { return NextResponse.json( - { ok: false, error: error.message }, - { status: 500 } + { + ok: false, + error: "Project not found", + }, + { status: 404 } ); } -} - -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; - + const space_url = `https://huggingface.co/spaces/${namespace}/${repoId}/raw/main/index.html`; try { const space = await spaceInfo({ name: namespace + "/" + repoId, @@ -97,85 +60,26 @@ export async function GET( ); } - 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")) { - 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) { + const response = await fetch(space_url); + if (!response.ok) { return NextResponse.json( { ok: false, - error: "No HTML files found", + error: "Failed to fetch space HTML", }, { status: 404 } ); } + let html = await response.text(); + // remove the last p tag including this url https://enzostvs-deepsite.hf.space + html = html.replace(getPTag(namespace + "/" + repoId), ""); + return NextResponse.json( { project: { - id: space.id, - space_id: space.name, - private: space.private, - _updatedAt: space.updatedAt, + ...project, + html, }, - pages: htmlFiles, - files, - commits, ok: true, }, { status: 200 } @@ -184,6 +88,10 @@ export async function GET( // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { if (error.statusCode === 404) { + await Project.deleteOne({ + user_id: user.id, + space_id: `${namespace}/${repoId}`, + }); return NextResponse.json( { error: "Space not found", ok: false }, { status: 404 } @@ -195,3 +103,135 @@ export async function GET( ); } } + +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 }); + } + + await dbConnect(); + const param = await params; + const { namespace, repoId } = param; + const { html, prompts } = await req.json(); + + const project = await Project.findOne({ + user_id: user.id, + space_id: `${namespace}/${repoId}`, + }).lean(); + if (!project) { + return NextResponse.json( + { + ok: false, + error: "Project not found", + }, + { status: 404 } + ); + } + + const repo: RepoDesignation = { + type: "space", + name: `${namespace}/${repoId}`, + }; + + const newHtml = html.replace(/<\/body>/, `${getPTag(repo.name)}`); + const file = new File([newHtml], "index.html", { type: "text/html" }); + await uploadFile({ + repo, + file, + accessToken: user.token as string, + commitTitle: `${prompts[prompts.length - 1]} - Follow Up Deployment`, + }); + + await Project.updateOne( + { user_id: user.id, space_id: `${namespace}/${repoId}` }, + { + $set: { + prompts: [ + ...(project && "prompts" in project ? project.prompts : []), + ...prompts, + ], + }, + } + ); + return NextResponse.json({ ok: true }, { status: 200 }); +} + +export async function POST( + 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 }); + } + + await dbConnect(); + 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 } + ); + } + + const project = await Project.findOne({ + user_id: user.id, + space_id: `${namespace}/${repoId}`, + }).lean(); + if (project) { + // redirect to the project page if it already exists + return NextResponse.json( + { + ok: false, + error: "Project already exists", + redirect: `/projects/${namespace}/${repoId}`, + }, + { status: 400 } + ); + } + + const newProject = new Project({ + user_id: user.id, + space_id: `${namespace}/${repoId}`, + prompts: [], + }); + + await newProject.save(); + return NextResponse.json( + { + ok: true, + project: { + id: newProject._id, + space_id: newProject.space_id, + prompts: newProject.prompts, + }, + }, + { status: 201 } + ); +} diff --git a/app/api/me/projects/[namespace]/[repoId]/save/route.ts b/app/api/me/projects/[namespace]/[repoId]/save/route.ts deleted file mode 100644 index d0a99d0c14b299872f4f9c8c874769bd198894ee..0000000000000000000000000000000000000000 --- a/app/api/me/projects/[namespace]/[repoId]/save/route.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { 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 } - ); - } -} diff --git a/app/api/me/projects/[namespace]/[repoId]/update/route.ts b/app/api/me/projects/[namespace]/[repoId]/update/route.ts deleted file mode 100644 index dad31b4e988a5ce815ba90ce76186a0ec4f00b1c..0000000000000000000000000000000000000000 --- a/app/api/me/projects/[namespace]/[repoId]/update/route.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { 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: static -pinned: false -tags: - - 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 } - ); - } -} - diff --git a/app/api/me/projects/route.ts b/app/api/me/projects/route.ts index dec5b655708390a0779bb2917defee6ab1bb02b2..9899bc2533a40a28b9e35cfe123b9868c318e19d 100644 --- a/app/api/me/projects/route.ts +++ b/app/api/me/projects/route.ts @@ -1,121 +1,126 @@ import { NextRequest, NextResponse } from "next/server"; -import { RepoDesignation, createRepo, listCommits, spaceInfo, uploadFiles } from "@huggingface/hub"; +import { createRepo, RepoDesignation, 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"; +import Project from "@/models/Project"; +import dbConnect from "@/lib/mongodb"; +import { COLORS, getPTag } from "@/lib/utils"; +// import type user +export async function GET() { + const user = await isAuthenticated(); + + if (user instanceof NextResponse || !user) { + return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); + } -export async function POST( - req: NextRequest, -) { + await dbConnect(); + + const projects = await Project.find({ + user_id: user?.id, + }) + .sort({ _createdAt: -1 }) + .limit(100) + .lean(); + if (!projects) { + return NextResponse.json( + { + ok: false, + projects: [], + }, + { status: 404 } + ); + } + return NextResponse.json( + { + ok: true, + projects, + }, + { status: 200 } + ); +} + +/** + * This API route creates a new project in Hugging Face Spaces. + * It requires an Authorization header with a valid token and a JSON body with the project details. + */ +export async function POST(request: 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, html, prompts } = await request.json(); + + if (!title || !html) { + return NextResponse.json( + { message: "Title and HTML content are required.", ok: false }, + { status: 400 } + ); + } + + await dbConnect(); - const title = titleFromRequest ?? "DeepSite Project"; + try { + let readme = ""; + let newHtml = html; - const formattedTitle = title - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .split("-") - .filter(Boolean) - .join("-") - .slice(0, 96); + const newTitle = 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} + const repo: RepoDesignation = { + type: "space", + name: `${user.name}/${newTitle}`, + }; + + const { repoUrl } = await createRepo({ + repo, + accessToken: user.token as string, + }); + const colorFrom = COLORS[Math.floor(Math.random() * COLORS.length)]; + const colorTo = COLORS[Math.floor(Math.random() * COLORS.length)]; + readme = `--- +title: ${newTitle} +emoji: 🐳 colorFrom: ${colorFrom} colorTo: ${colorTo} -emoji: 🐳 sdk: static pinned: false tags: - - deepsite-v3 + - deepsite --- -# Welcome to your new DeepSite project! -This project was created with [DeepSite](https://huggingface.co/deepsite). -`; +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference`; - 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, + newHtml = html.replace(/<\/body>/, `${getPTag(repo.name)}`); + const file = new File([newHtml], "index.html", { type: "text/html" }); + const readmeFile = new File([readme], "README.md", { + type: "text/markdown", }); - const commitTitle = !prompt || prompt.trim() === "" ? "Redesign my website" : prompt; + const files = [file, readmeFile]; await uploadFiles({ repo, files, accessToken: user.token as string, - commitTitle + commitTitle: `${prompts[prompts.length - 1]} - Initial Deployment`, }); - 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, + const project = await Project.create({ + user_id: user.id, + space_id: path, + prompts, }); - - 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 }); + return NextResponse.json({ project, path, ok: true }, { status: 201 }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (err: any) { return NextResponse.json( { error: err.message, ok: false }, { status: 500 } ); } -} \ No newline at end of file +} diff --git a/app/api/me/route.ts b/app/api/me/route.ts index 25bc6c81aa826d65cac703e43c5d4647ae5cd141..c4164daba5c58bb2fe7f4f7508de7165f32ca443 100644 --- a/app/api/me/route.ts +++ b/app/api/me/route.ts @@ -1,4 +1,3 @@ -import { listSpaces } from "@huggingface/hub"; import { headers } from "next/headers"; import { NextResponse } from "next/server"; @@ -22,25 +21,5 @@ export async function GET() { ); } 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 }); + return NextResponse.json({ user, errCode: null }, { status: 200 }); } diff --git a/app/api/re-design/route.ts b/app/api/re-design/route.ts index aeff09fbc04f8b398a312b8db6f66f4a74113d2b..777c2cbd18f95592080c0fe1ad2cab23a5264397 100644 --- a/app/api/re-design/route.ts +++ b/app/api/re-design/route.ts @@ -1,11 +1,5 @@ import { 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 route -export const maxDuration = 60; // 1 minute - export async function PUT(request: NextRequest) { const body = await request.json(); const { url } = body; @@ -15,54 +9,28 @@ export async function PUT(request: NextRequest) { } try { - // Create an AbortController for timeout - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT); - - try { - const response = await fetch( - `https://r.jina.ai/${encodeURIComponent(url)}`, - { - method: "POST", - signal: controller.signal, - } - ); - - clearTimeout(timeoutId); - - if (!response.ok) { - return NextResponse.json( - { error: "Failed to fetch redesign" }, - { status: 500 } - ); + const response = await fetch( + `https://r.jina.ai/${encodeURIComponent(url)}`, + { + method: "POST", } - const markdown = await response.text(); + ); + if (!response.ok) { return NextResponse.json( - { - ok: true, - markdown, - }, - { status: 200 } + { error: "Failed to fetch redesign" }, + { status: 500 } ); - } 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; } + const markdown = await response.text(); + return NextResponse.json( + { + ok: true, + markdown, + }, + { status: 200 } + ); // 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 } - ); - } return NextResponse.json( { error: error.message || "An error occurred" }, { status: 500 } diff --git a/app/auth/callback/page.tsx b/app/auth/callback/page.tsx index 6cf420cea009bbe322d10d7fc9a9d7badee467f6..ac44f365b707908d6003a4266db1269d297a4336 100644 --- a/app/auth/callback/page.tsx +++ b/app/auth/callback/page.tsx @@ -5,92 +5,67 @@ 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); - } + await loginFromCode(code); } }); - useTimeoutFn(() => setShowButton(true), 7000); + useTimeoutFn( + () => setShowButton(true), + 7000 // Show button after 5 seconds + ); return ( -
-
-
-
-
-
-
- πŸš€ -
-
- πŸ‘‹ -
-
- πŸ™Œ -
+
+
+
+
+
+ πŸš€
-

- {isPopupAuth - ? "Authentication Complete!" - : "Login In Progress..."} -

-

- {isPopupAuth - ? "You can now close this tab and return to the previous page." - : "Wait a moment while we log you in with your code."} +

+ πŸ‘‹ +
+
+ πŸ™Œ +
+
+

+ Login In Progress... +

+

+ Wait a moment while we log you in with your code. +

+
+
+
+

+ If you are not redirected automatically in the next 5 seconds, + please click the button below

-
-
-
-

- If you are not redirected automatically in the next 5 seconds, - please click the button below + {showButton ? ( + + + + ) : ( +

+ Please wait, we are logging you in...

- {showButton ? ( - - - - ) : ( -

- Please wait, we are logging you in... -

- )} -
-
-
- + )} +
+
); diff --git a/app/layout.tsx b/app/layout.tsx index 711a8b4c579a592546e1bc355ae6132f939fc0a1..09fe16906a16a6a8bff4a21d55004968eff2b163 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -2,19 +2,14 @@ import type { Metadata, Viewport } from "next"; import { Inter, PT_Sans } from "next/font/google"; import { cookies } from "next/headers"; -import Script from "next/script"; +import TanstackProvider from "@/components/providers/tanstack-query-provider"; import "@/assets/globals.css"; import { Toaster } from "@/components/ui/sonner"; import MY_TOKEN_KEY from "@/lib/get-cookie-name"; import { apiServer } from "@/lib/api"; -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"; -import DomainRedirect from "@/components/domain-redirect"; +import Script from "next/script"; const inter = Inter({ variable: "--font-inter-sans", @@ -28,12 +23,31 @@ const ptSans = PT_Sans({ }); export const metadata: Metadata = { - ...generateSEO({ + title: "DeepSite | Build with AI ✨", + description: + "DeepSite is a web development tool that helps you build websites with AI, no code required. Let's deploy your website with DeepSite and enjoy the magic of AI.", + openGraph: { title: "DeepSite | Build with AI ✨", description: "DeepSite is a web development tool that helps you build websites with AI, no code required. Let's deploy your website with DeepSite and enjoy the magic of AI.", - path: "/", - }), + url: "https://deepsite.hf.co", + siteName: "DeepSite", + images: [ + { + url: "https://deepsite.hf.co/banner.png", + width: 1200, + height: 630, + alt: "DeepSite Open Graph Image", + }, + ], + }, + twitter: { + card: "summary_large_image", + title: "DeepSite | Build with AI ✨", + description: + "DeepSite is a web development tool that helps you build websites with AI, no code required. Let's deploy your website with DeepSite and enjoy the magic of AI.", + images: ["https://deepsite.hf.co/banner.png"], + }, appleWebApp: { capable: true, title: "DeepSite", @@ -44,9 +58,6 @@ export const metadata: Metadata = { shortcut: "/logo.svg", apple: "/logo.svg", }, - verification: { - google: process.env.GOOGLE_SITE_VERIFICATION, - }, }; export const viewport: Viewport = { @@ -55,75 +66,42 @@ export const viewport: Viewport = { 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 }; -// } -// } +async function getMe() { + const cookieStore = await cookies(); + const token = cookieStore.get(MY_TOKEN_KEY())?.value; + if (!token) return { user: null, errCode: null }; + try { + const res = await apiServer.get("/me", { + headers: { + Authorization: `Bearer ${token}`, + }, + }); + return { user: res.data.user, errCode: null }; + } catch (err: any) { + return { user: null, errCode: err.status }; + } +} export default async function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { - // const data = await getMe(); - - // Generate structured data - const 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", - }); - + const data = await getMe(); return ( + - ` - ) - .join("\n"); - - if (modifiedHtml.includes("")) { - modifiedHtml = modifiedHtml.replace( - "", - `${allJsContent}\n` - ); - } else if (modifiedHtml.includes("")) { - modifiedHtml = modifiedHtml + allJsContent; - } else { - modifiedHtml = modifiedHtml + "\n" + allJsContent; - } - - jsFiles.forEach((file) => { - const escapedPath = file.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - modifiedHtml = modifiedHtml.replace( - new RegExp( - `]*src=["'][\\.\/]*${escapedPath}["'][^>]*><\\/script>`, - "gi" - ), - "" - ); - }); - } - - return modifiedHtml; - }, - [pages, previewPageData?.path] +export const Preview = ({ + html, + isResizing, + isAiWorking, + ref, + device, + currentTab, + iframeRef, + isEditableModeEnabled, + onClickElement, +}: { + html: string; + isResizing: boolean; + isAiWorking: boolean; + ref: React.RefObject; + iframeRef?: React.RefObject; + device: "desktop" | "mobile"; + currentTab: string; + isEditableModeEnabled?: boolean; + onClickElement?: (element: HTMLElement) => void; +}) => { + const [hoveredElement, setHoveredElement] = useState( + null ); - useEffect(() => { - if (isNew && previewPageData?.html) { - const now = Date.now(); - const timeSinceLastUpdate = now - lastUpdateTimeRef.current; - - if (lastUpdateTimeRef.current === 0 || timeSinceLastUpdate >= 3000) { - const processedHtml = injectAssetsIntoHtml(previewPageData.html); - setThrottledHtml(processedHtml); - lastUpdateTimeRef.current = now; - } else { - const timeUntilNextUpdate = 3000 - timeSinceLastUpdate; - const timer = setTimeout(() => { - const processedHtml = injectAssetsIntoHtml(previewPageData.html); - setThrottledHtml(processedHtml); - lastUpdateTimeRef.current = Date.now(); - }, timeUntilNextUpdate); - return () => clearTimeout(timer); - } - } - }, [isNew, previewPageData?.html, injectAssetsIntoHtml]); - - useEffect(() => { - if (!isAiWorking && !globalAiLoading && previewPageData?.html) { - const processedHtml = injectAssetsIntoHtml(previewPageData.html); - setStableHtml(processedHtml); - } - }, [ - isAiWorking, - globalAiLoading, - previewPageData?.html, - injectAssetsIntoHtml, - previewPage, - ]); - - useEffect(() => { - if ( - previewPageData?.html && - !stableHtml && - !isAiWorking && - !globalAiLoading - ) { - const processedHtml = injectAssetsIntoHtml(previewPageData.html); - setStableHtml(processedHtml); - } - }, [ - previewPageData?.html, - stableHtml, - isAiWorking, - globalAiLoading, - injectAssetsIntoHtml, - ]); - - const setupIframeListeners = () => { - if (iframeRef?.current?.contentDocument) { - const iframeDocument = iframeRef.current.contentDocument; - - iframeDocument.addEventListener( - "click", - handleCustomNavigation as any, - true - ); - - if (isEditableModeEnabled) { - iframeDocument.addEventListener("mouseover", handleMouseOver); - iframeDocument.addEventListener("mouseout", handleMouseOut); - iframeDocument.addEventListener("click", handleClick); - } - } - }; - - useEffect(() => { - const cleanupListeners = () => { - if (iframeRef?.current?.contentDocument) { - const iframeDocument = iframeRef.current.contentDocument; - iframeDocument.removeEventListener( - "click", - handleCustomNavigation as any, - true - ); - iframeDocument.removeEventListener("mouseover", handleMouseOver); - iframeDocument.removeEventListener("mouseout", handleMouseOut); - iframeDocument.removeEventListener("click", handleClick); - } - }; - - const timer = setTimeout(() => { - if (iframeRef?.current?.contentDocument) { - cleanupListeners(); - setupIframeListeners(); - } - }, 50); - - return () => { - clearTimeout(timer); - cleanupListeners(); - }; - }, [isEditableModeEnabled, stableHtml, throttledHtml, previewPage]); - - const promoteVersion = async () => { - setIsPromotingVersion(true); - await api - .post( - `/me/projects/${project?.space_id}/commits/${currentCommit}/promote` - ) - .then((res) => { - if (res.data.ok) { - setCurrentCommit(null); - setPages(res.data.pages); - setCurrentPage(res.data.pages[0].path); - setPreviewPage(res.data.pages[0].path); - toast.success("Version promoted successfully"); - } - }) - .catch((err) => { - toast.error(err.response.data.error); - }); - setIsPromotingVersion(false); - }; - + // add event listener to the iframe to track hovered elements const handleMouseOver = (event: MouseEvent) => { if (iframeRef?.current) { const iframeDocument = iframeRef.current.contentDocument; if (iframeDocument) { const targetElement = event.target as HTMLElement; if ( - hoveredElement?.tagName !== targetElement.tagName || - hoveredElement?.rect.top !== - targetElement.getBoundingClientRect().top || - hoveredElement?.rect.left !== - targetElement.getBoundingClientRect().left || - hoveredElement?.rect.width !== - targetElement.getBoundingClientRect().width || - hoveredElement?.rect.height !== - targetElement.getBoundingClientRect().height + hoveredElement !== targetElement && + targetElement !== iframeDocument.body ) { - if (targetElement !== iframeDocument.body) { - const rect = targetElement.getBoundingClientRect(); - setHoveredElement({ - tagName: targetElement.tagName, - rect: { - top: rect.top, - left: rect.left, - width: rect.width, - height: rect.height, - }, - }); - targetElement.classList.add("hovered-element"); - } else { - return setHoveredElement(null); - } + setHoveredElement(targetElement); + targetElement.classList.add("hovered-element"); + } else { + return setHoveredElement(null); } } } @@ -313,257 +58,119 @@ export const Preview = ({ isNew }: { isNew: boolean }) => { if (iframeRef?.current) { const iframeDocument = iframeRef.current.contentDocument; if (iframeDocument) { - const path = event.composedPath(); - const targetElement = path[0] as HTMLElement; - - const findClosestAnchor = ( - element: HTMLElement - ): HTMLAnchorElement | null => { - let current: HTMLElement | null = element; - while (current) { - if (current.tagName?.toUpperCase() === "A") { - return current as HTMLAnchorElement; - } - if (current === iframeDocument.body) { - break; - } - const parent: Node | null = current.parentNode; - if (parent && parent.nodeType === 11) { - current = (parent as ShadowRoot).host as HTMLElement; - } else if (parent && parent.nodeType === 1) { - current = parent as HTMLElement; - } else { - break; - } - } - return null; - }; - - const anchorElement = findClosestAnchor(targetElement); - - if (anchorElement) { - return; - } - + const targetElement = event.target as HTMLElement; if (targetElement !== iframeDocument.body) { - setSelectedElement(targetElement); + onClickElement?.(targetElement); } } } }; - const handleCustomNavigation = (event: MouseEvent) => { + useUpdateEffect(() => { + const cleanupListeners = () => { + if (iframeRef?.current?.contentDocument) { + const iframeDocument = iframeRef.current.contentDocument; + iframeDocument.removeEventListener("mouseover", handleMouseOver); + iframeDocument.removeEventListener("mouseout", handleMouseOut); + iframeDocument.removeEventListener("click", handleClick); + } + }; + if (iframeRef?.current) { const iframeDocument = iframeRef.current.contentDocument; if (iframeDocument) { - const path = event.composedPath(); - const actualTarget = path[0] as HTMLElement; - - const findClosestAnchor = ( - element: HTMLElement - ): HTMLAnchorElement | null => { - let current: HTMLElement | null = element; - while (current) { - if (current.tagName?.toUpperCase() === "A") { - return current as HTMLAnchorElement; - } - if (current === iframeDocument.body) { - break; - } - const parent: Node | null = current.parentNode; - if (parent && parent.nodeType === 11) { - current = (parent as ShadowRoot).host as HTMLElement; - } else if (parent && parent.nodeType === 1) { - current = parent as HTMLElement; - } else { - break; - } - } - return null; - }; - - const anchorElement = findClosestAnchor(actualTarget); - if (anchorElement) { - let href = anchorElement.getAttribute("href"); - if (href) { - event.stopPropagation(); - event.preventDefault(); - - if (href.startsWith("#")) { - let targetElement = iframeDocument.querySelector(href); - - if (!targetElement) { - const searchInShadows = ( - root: Document | ShadowRoot - ): Element | null => { - const elements = root.querySelectorAll("*"); - for (const el of elements) { - if (el.shadowRoot) { - const found = el.shadowRoot.querySelector(href); - if (found) return found; - const nested = searchInShadows(el.shadowRoot); - if (nested) return nested; - } - } - return null; - }; - targetElement = searchInShadows(iframeDocument); - } - - if (targetElement) { - targetElement.scrollIntoView({ behavior: "smooth" }); - } - return; - } - - let normalizedHref = href.replace(/^\.?\//, ""); - - if (normalizedHref === "" || normalizedHref === "/") { - normalizedHref = "index.html"; - } - - const hashIndex = normalizedHref.indexOf("#"); - if (hashIndex !== -1) { - normalizedHref = normalizedHref.substring(0, hashIndex); - } - - if (!normalizedHref.includes(".")) { - normalizedHref = normalizedHref + ".html"; - } - - const isPageExist = pages.some((page) => { - const pagePath = page.path.replace(/^\.?\//, ""); - return pagePath === normalizedHref; - }); + // Clean up existing listeners first + cleanupListeners(); - if (isPageExist) { - setPreviewPage(normalizedHref); - } - } + if (isEditableModeEnabled) { + iframeDocument.addEventListener("mouseover", handleMouseOver); + iframeDocument.addEventListener("mouseout", handleMouseOut); + iframeDocument.addEventListener("click", handleClick); } } } - }; + + // Clean up when component unmounts or dependencies change + return cleanupListeners; + }, [iframeRef, isEditableModeEnabled]); + + const selectedElement = useMemo(() => { + if (!isEditableModeEnabled) return null; + if (!hoveredElement) return null; + return hoveredElement; + }, [hoveredElement, isEditableModeEnabled]); return (
{ + if (isAiWorking) { + e.preventDefault(); + e.stopPropagation(); + toast.warning("Please wait for the AI to finish working."); + } + }} > - {/* Preview page indicator */} - {!isAiWorking && hoveredElement && isEditableModeEnabled && ( + {!isAiWorking && hoveredElement && selectedElement && (
- {htmlTagToText(hoveredElement.tagName.toLowerCase())} + {htmlTagToText(selectedElement.tagName.toLowerCase())}
)} - {isLoadingProject ? ( -
-
- - - -
-
- ) : ( - <> - - ) : user ? ( + {user ? ( ) : ( <> - + )}
diff --git a/components/space/ask-ai/index.tsx b/components/space/ask-ai/index.tsx new file mode 100644 index 0000000000000000000000000000000000000000..46202ffe6f8d82f29eab068db97573985eaf9cca --- /dev/null +++ b/components/space/ask-ai/index.tsx @@ -0,0 +1,43 @@ +"use client"; + +import { ArrowUp } from "lucide-react"; +import { PiGearSixFill } from "react-icons/pi"; +import { TiUserAdd } from "react-icons/ti"; + +import { Button } from "@/components/ui/button"; + +export const AskAi = () => { + return ( + <> +
+