Upload 7 files
Browse filesFiles changed (7)
- DockerfileAdded+8
- install.pyAdded+752
- next.config.jsAdded+7
- package.jsonAdded+30
- postcss.config.jsAdded+6
- tailwind.config.tsAdded+13
- tsconfig.jsonAdded+21
12345678FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
EXPOSE 7860
CMD ["npm", "start", "--", "-p", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752import osimport json
# Define the project structure and file contentsfiles = { "package.json": """{ "name": "rpg-companion-ultimate", "version": "1.0.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start" }, "dependencies": { "next": "14.1.0", "react": "^18", "react-dom": "^18", "better-sqlite3": "^9.4.0", "swr": "^2.2.5", "@huggingface/inference": "^2.6.4", "lucide-react": "^0.330.0", "clsx": "^2.1.0", "tailwind-merge": "^2.2.1" }, "devDependencies": { "@types/node": "^20", "@types/react": "^18", "@types/better-sqlite3": "^7.6.9", "autoprefixer": "^10.0.1", "postcss": "^8", "tailwindcss": "^3.3.0", "typescript": "^5" }}""",
"Dockerfile": """FROM node:18-alpineWORKDIR /appCOPY package*.json ./RUN npm installCOPY . .RUN npm run buildEXPOSE 7860CMD ["npm", "start", "--", "-p", "7860"]""",
"next.config.js": """/** @type {import('next').NextConfig} */const nextConfig = { typescript: { ignoreBuildErrors: true }, eslint: { ignoreDuringBuilds: true }, output: 'standalone',};module.exports = nextConfig;""",
"tsconfig.json": """{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [{"name": "next"}], "paths": {"@/*": ["./*"]} }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"]}""",
"postcss.config.js": """module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, },}""",
"tailwind.config.ts": """import type { Config } from "tailwindcss";const config: Config = { content: [ "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: {}, }, plugins: [],};export default config;""",
"lib/db.ts": """import Database from 'better-sqlite3';import fs from 'fs';import path from 'path';
const DATA_DIR = '/data';const DB_PATH = path.join(DATA_DIR, 'campaign.db');const IMG_DIR = path.join(DATA_DIR, 'images');
if (!fs.existsSync(DATA_DIR)) { if (!fs.existsSync('./data')) fs.mkdirSync('./data');} else { if (!fs.existsSync(IMG_DIR)) fs.mkdirSync(IMG_DIR);}
const finalDbPath = fs.existsSync(DATA_DIR) ? DB_PATH : './data/campaign.db';const db = new Database(finalDbPath);db.pragma('journal_mode = WAL');
db.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, password TEXT, role TEXT DEFAULT 'player', avatar_url TEXT ); CREATE TABLE IF NOT EXISTS logs ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, content TEXT, is_secret INTEGER DEFAULT 0, game_date TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS tech_tree ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, status TEXT DEFAULT 'locked', progress INTEGER DEFAULT 0 ); CREATE TABLE IF NOT EXISTS characters ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, name TEXT, class_type TEXT, inventory TEXT, image_url TEXT, FOREIGN KEY(user_id) REFERENCES users(id) ); CREATE TABLE IF NOT EXISTS journal ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, title TEXT, content TEXT, is_public INTEGER DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY(user_id) REFERENCES users(id) );`);
export default db;""",
"app/globals.css": """@tailwind base;@tailwind components;@tailwind utilities;
:root { --foreground-rgb: 255, 255, 255; --background-start-rgb: 0, 0, 0; --background-end-rgb: 0, 0, 0;}
body { color: rgb(var(--foreground-rgb)); background: linear-gradient(to bottom, transparent, rgb(var(--background-end-rgb))) rgb(var(--background-start-rgb));}""",
"app/layout.tsx": """import type { Metadata } from "next";import "./globals.css";
export const metadata: Metadata = { title: "RPG Companion", description: "Campaign Manager & AI Tool",};
export default function RootLayout({ children,}: Readonly<{ children: React.ReactNode;}>) { return ( <html lang="en"> <body className="bg-slate-950 text-white min-h-screen">{children}</body> </html> );}""",
"app/api/auth/route.ts": """import { NextResponse } from 'next/server';import db from '@/lib/db';
export async function POST(req: Request) { const { action, username, password } = await req.json();
if (action === 'SIGNUP') { try { const userCount = db.prepare('SELECT COUNT(*) as count FROM users').get() as any; const role = userCount.count === 0 ? 'admin' : 'player'; const stmt = db.prepare('INSERT INTO users (username, password, role) VALUES (?, ?, ?)'); const info = stmt.run(username, password, role); return NextResponse.json({ success: true, userId: info.lastInsertRowid, role, username }); } catch (err) { return NextResponse.json({ success: false, error: "Username taken" }); } }
if (action === 'LOGIN') { const user = db.prepare('SELECT id, username, role FROM users WHERE username = ? AND password = ?').get(username, password); if (user) { return NextResponse.json({ success: true, user }); } return NextResponse.json({ success: false, error: "Invalid credentials" }); } return NextResponse.json({ success: false });}""",
"app/api/game-data/route.ts": """import { NextResponse } from 'next/server';import db from '@/lib/db';
export async function GET(req: Request) { const { searchParams } = new URL(req.url); const userId = searchParams.get('userId');
let isAdmin = false; if (userId) { const user = db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as any; if (user && user.role === 'admin') isAdmin = true; }
let logsQuery = 'SELECT * FROM logs ORDER BY created_at DESC'; if (!isAdmin) { logsQuery = 'SELECT * FROM logs WHERE is_secret = 0 ORDER BY created_at DESC'; } const logs = db.prepare(logsQuery).all(); const tech = db.prepare('SELECT * FROM tech_tree').all();
return NextResponse.json({ logs, tech, isAdmin });}
export async function POST(req: Request) { const body = await req.json(); const user = db.prepare('SELECT role FROM users WHERE id = ?').get(body.userId) as any; if (!user || user.role !== 'admin') { return NextResponse.json({ error: "Unauthorized" }, { status: 403 }); }
if (body.type === 'LOG') { db.prepare('INSERT INTO logs (title, content, is_secret, game_date) VALUES (?, ?, ?, ?)').run( body.title, body.content, body.is_secret ? 1 : 0, body.game_date ); } if (body.type === 'TECH') { const exists = db.prepare('SELECT id FROM tech_tree WHERE name = ?').get(body.name); if (exists) { db.prepare('UPDATE tech_tree SET progress = ?, status = ? WHERE name = ?').run(body.progress, body.status, body.name); } else { db.prepare('INSERT INTO tech_tree (name, progress, status) VALUES (?, ?, ?)').run(body.name, body.progress, body.status); } }
return NextResponse.json({ success: true });}""",
"app/api/character/route.ts": """import { NextResponse } from 'next/server';import db from '@/lib/db';
export async function GET(req: Request) { const { searchParams } = new URL(req.url); const userId = searchParams.get('userId');
if (!userId) return NextResponse.json({ error: "Missing User ID" });
const character = db.prepare('SELECT * FROM characters WHERE user_id = ?').get(userId); const journals = db.prepare(` SELECT j.*, u.username FROM journal j JOIN users u ON j.user_id = u.id WHERE j.user_id = ? OR j.is_public = 1 ORDER BY j.created_at DESC `).all(userId);
return NextResponse.json({ character, journals });}
export async function POST(req: Request) { const body = await req.json(); const { userId, type } = body;
if (type === 'UPDATE_CHAR') { const exists = db.prepare('SELECT id FROM characters WHERE user_id = ?').get(userId); if (exists) { db.prepare('UPDATE characters SET name=?, class_type=?, inventory=? WHERE user_id=?') .run(body.name, body.class_type, body.inventory, userId); } else { db.prepare('INSERT INTO characters (user_id, name, class_type, inventory) VALUES (?, ?, ?, ?)') .run(userId, body.name, body.class_type, body.inventory); } }
if (type === 'ADD_JOURNAL') { db.prepare('INSERT INTO journal (user_id, title, content, is_public) VALUES (?, ?, ?, ?)') .run(userId, body.title, body.content, body.is_public ? 1 : 0); }
return NextResponse.json({ success: true });}""",
"app/api/ai/route.ts": """import { NextResponse } from 'next/server';import { HfInference } from '@huggingface/inference';import db from '@/lib/db';
const hf = new HfInference(process.env.NEXT_PUBLIC_HF_TOKEN);
export async function POST(req: Request) { const body = await req.json();
if (body.type === 'IMAGE') { try { const prompt = `Fantasy character portrait, ${body.prompt}, anime style, 8k, detailed`; const blob = await hf.textToImage({ model: 'black-forest-labs/FLUX.1-dev', inputs: prompt, }); const arrayBuffer = await blob.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); const base64 = `data:image/png;base64,${buffer.toString('base64')}`; db.prepare('UPDATE characters SET image_url = ? WHERE user_id = ?').run(base64, body.userId); return NextResponse.json({ success: true, url: base64 }); } catch (e) { console.error(e); return NextResponse.json({ error: "AI Failed" }, { status: 500 }); } }
if (body.type === 'CHAT') { const { userId, message, history } = body; const char = db.prepare('SELECT * FROM characters WHERE user_id = ?').get(userId) as any; const systemPrompt = `You are a helper AI inside the inventory of ${char?.name || 'the adventurer'}. Inventory: ${char?.inventory || 'Empty'}. Class: ${char?.class_type || 'Unknown'}. Keep answers short, helpful, and immersive.`;
const stream = await hf.chatCompletionStream({ model: "meta-llama/Meta-Llama-3-8B-Instruct", messages: [{ role: "system", content: systemPrompt }, ...history, { role: "user", content: message }], max_tokens: 200 });
const encoder = new TextEncoder(); const customStream = new ReadableStream({ async start(controller) { for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content || ""; controller.enqueue(encoder.encode(content)); } controller.close(); }, });
return new Response(customStream, { headers: { 'Content-Type': 'text/plain' } }); }
return NextResponse.json({ error: "Invalid Type" });}""",
"components/AICompanion.tsx": """'use client';import { useState, useRef, useEffect } from 'react';import { Send, MessageSquare, X, Sparkles } from 'lucide-react';
export default function AICompanion({ userId }: { userId: number }) { const [isOpen, setIsOpen] = useState(false); const [input, setInput] = useState(""); const [messages, setMessages] = useState<any[]>([]); const [loading, setLoading] = useState(false); const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => { scrollRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]);
async function sendMessage() { if (!input) return; const newMsg = { role: 'user', content: input }; setMessages(prev => [...prev, newMsg]); setInput(""); setLoading(true);
try { const res = await fetch('/api/ai', { method: 'POST', body: JSON.stringify({ type: 'CHAT', userId, message: newMsg.content, history: messages.slice(-4) }) }); if (!res.body) return; const reader = res.body.getReader(); const decoder = new TextDecoder(); let aiText = ""; setMessages(prev => [...prev, { role: 'assistant', content: "" }]);
while (true) { const { done, value } = await reader.read(); if (done) break; aiText += decoder.decode(value); setMessages(prev => { const arr = [...prev]; arr[arr.length - 1].content = aiText; return arr; }); } } catch (e) { console.error(e); } setLoading(false); }
return ( <div className="fixed bottom-4 right-4 z-50"> {isOpen ? ( <div className="bg-slate-900 border border-indigo-500 w-80 h-96 rounded-lg flex flex-col shadow-2xl"> <div className="bg-indigo-900/50 p-3 flex justify-between items-center border-b border-indigo-500/30"> <span className="flex items-center gap-2 text-indigo-200 font-bold text-sm"><Sparkles size={14}/> Companion</span> <button onClick={() => setIsOpen(false)}><X size={16} className="text-indigo-300"/></button> </div> <div className="flex-1 overflow-y-auto p-3 space-y-3"> {messages.map((m, i) => ( <div key={i} className={`text-xs p-2 rounded max-w-[85%] ${m.role === 'user' ? 'bg-indigo-600 ml-auto' : 'bg-slate-800 border border-slate-700'}`}> {m.content} </div> ))} <div ref={scrollRef} /> </div> <div className="p-2 border-t border-slate-700 flex gap-2"> <input className="flex-1 bg-slate-950 border border-slate-700 rounded px-2 text-xs text-white h-8" value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && sendMessage()} placeholder="Ask about inventory..." /> <button onClick={sendMessage} disabled={loading} className="bg-indigo-600 p-2 rounded hover:bg-indigo-500"><Send size={14}/></button> </div> </div> ) : ( <button onClick={() => setIsOpen(true)} className="bg-indigo-600 p-4 rounded-full shadow-lg hover:scale-110 transition"> <MessageSquare className="text-white" /> </button> )} </div> );}""",
"app/page.tsx": """'use client';import { useState, useEffect } from 'react';import useSWR from 'swr';import Link from 'next/link';import { Shield, Hammer, Eye, EyeOff } from 'lucide-react';
const fetcher = (url: string) => fetch(url).then(r => r.json());
export default function Dashboard() { const [user, setUser] = useState<any>(null); const { data, mutate } = useSWR(user ? `/api/game-data?userId=${user.id}` : null, fetcher, { refreshInterval: 2000 });
useEffect(() => { const u = localStorage.getItem('rpg_user'); if (u) setUser(JSON.parse(u)); }, []);
async function addLog() { const title = prompt("Event Title:"); const content = prompt("Description:"); const isSecret = confirm("Is this secret?"); if (title && content) { await fetch('/api/game-data', { method: 'POST', body: JSON.stringify({ type: 'LOG', userId: user.id, title, content, is_secret: isSecret, game_date: 'Present Day' }) }); mutate(); } }
async function updateTech(name: string, currentProg: number) { const newProg = prompt(`Update progress for ${name} (0-100):`, currentProg.toString()); if (newProg) { await fetch('/api/game-data', { method: 'POST', body: JSON.stringify({ type: 'TECH', userId: user.id, name, progress: parseInt(newProg), status: 'Researching' }) }); mutate(); } }
if (!user) return <div className="h-screen flex items-center justify-center bg-slate-950 text-white"><Link href="/login" className="text-blue-400 underline">Please Login</Link></div>;
return ( <div className="min-h-screen bg-slate-950 text-slate-200 p-6 font-mono"> <div className="flex justify-between items-center mb-10 border-b border-slate-800 pb-4"> <h1 className="text-3xl font-bold bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">CAMPAIGN DASHBOARD</h1> <div className="flex gap-4 items-center"> <Link href="/profile" className="hover:text-white text-slate-400">My Character</Link> <span className={`text-xs px-2 py-1 rounded ${data?.isAdmin ? 'bg-red-900 text-red-200' : 'bg-green-900 text-green-200'}`}> {data?.isAdmin ? 'DM OVERRIDE ACTIVE' : 'PLAYER VIEW'} </span> </div> </div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8"> <div className="col-span-2 space-y-4"> <div className="flex justify-between"> <h2 className="text-xl font-bold text-blue-400 flex gap-2"><Shield /> TIMELINE</h2> {data?.isAdmin && <button onClick={addLog} className="bg-slate-800 text-xs px-2 py-1 hover:bg-slate-700">+ Add Event</button>} </div> <div className="space-y-4 h-[600px] overflow-y-auto pr-2"> {data?.logs?.map((log: any) => ( <div key={log.id} className={`p-4 rounded border-l-4 ${log.is_secret ? 'border-red-500 bg-red-950/20' : 'border-blue-500 bg-slate-900'}`}> <div className="flex justify-between text-xs text-slate-500 mb-1"> <span>{log.game_date}</span> {log.is_secret && <span className="text-red-500 flex items-center gap-1"><EyeOff size={10}/> HIDDEN</span>} </div> <h3 className="font-bold text-lg">{log.title}</h3> <p className="text-sm text-slate-400 mt-2">{log.content}</p> </div> ))} </div> </div>
<div className="space-y-4"> <div className="flex justify-between"> <h2 className="text-xl font-bold text-green-400 flex gap-2"><Hammer /> BASE UPGRADES</h2> {data?.isAdmin && <button onClick={() => updateTech(prompt("Tech Name:") || "New Tech", 0)} className="bg-slate-800 text-xs px-2 py-1">+ Add Tech</button>} </div> <div className="bg-slate-900 p-4 rounded border border-slate-800 space-y-6"> {data?.tech?.map((t: any) => ( <div key={t.id} onClick={() => data.isAdmin && updateTech(t.name, t.progress)} className={data.isAdmin ? "cursor-pointer hover:bg-slate-800 p-2 rounded" : ""}> <div className="flex justify-between mb-1"> <span className="font-bold text-sm">{t.name}</span> <span className="text-xs uppercase">{t.status}</span> </div> <div className="w-full bg-slate-800 h-2 rounded-full overflow-hidden"> <div className="bg-green-500 h-full transition-all duration-1000" style={{ width: `${t.progress}%` }}></div> </div> </div> ))} {data?.tech?.length === 0 && <div className="text-slate-600 text-sm">No active research.</div>} </div> </div> </div> </div> );}""",
"app/profile/page.tsx": """'use client';import { useState, useEffect } from 'react';import useSWR from 'swr';import Link from 'next/link';import AICompanion from '@/components/AICompanion';
const fetcher = (url: string) => fetch(url).then(r => r.json());
export default function Profile() { const [user, setUser] = useState<any>(null); const [isGenerating, setIsGenerating] = useState(false); useEffect(() => { const u = localStorage.getItem('rpg_user'); if (u) setUser(JSON.parse(u)); }, []);
const { data, mutate } = useSWR(user ? `/api/character?userId=${user.id}` : null, fetcher);
const [formData, setFormData] = useState({ name: '', class_type: '', inventory: '' }); const [journal, setJournal] = useState({ title: '', content: '', is_public: false });
useEffect(() => { if (data?.character) { setFormData({ name: data.character.name || '', class_type: data.character.class_type || '', inventory: data.character.inventory || '' }); } }, [data]);
async function saveChar() { await fetch('/api/character', { method: 'POST', body: JSON.stringify({ type: 'UPDATE_CHAR', userId: user.id, ...formData }) }); mutate(); }
async function generateAI() { setIsGenerating(true); await fetch('/api/ai', { method: 'POST', body: JSON.stringify({ type: 'IMAGE', userId: user.id, prompt: `A ${formData.class_type} named ${formData.name} wearing ${formData.inventory}` }) }); setIsGenerating(false); mutate(); }
async function saveJournal() { await fetch('/api/character', { method: 'POST', body: JSON.stringify({ type: 'ADD_JOURNAL', userId: user.id, ...journal }) }); setJournal({ title: '', content: '', is_public: false }); mutate(); }
if (!user) return <div>Loading...</div>;
return ( <div className="min-h-screen bg-slate-950 text-slate-100 p-6"> <Link href="/" className="mb-6 block text-slate-500 hover:text-white">← Back to Dashboard</Link> <div className="grid grid-cols-1 md:grid-cols-2 gap-8"> <div className="bg-slate-900 p-6 rounded border border-slate-800"> <h2 className="text-2xl font-bold text-purple-400 mb-4">Character Identity</h2> <div className="flex gap-4 mb-6"> <div className="w-1/2 aspect-square bg-black rounded overflow-hidden border border-slate-700 relative"> {data?.character?.image_url ? ( <img src={data.character.image_url} className="w-full h-full object-cover" /> ) : ( <div className="flex items-center justify-center h-full text-xs text-slate-600">No Image</div> )} {isGenerating && <div className="absolute inset-0 bg-black/80 flex items-center justify-center text-purple-400 animate-pulse">Scanning...</div>} </div> <div className="w-1/2 space-y-2"> <input className="w-full bg-slate-950 p-2 rounded border border-slate-700" placeholder="Name" value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} /> <input className="w-full bg-slate-950 p-2 rounded border border-slate-700" placeholder="Class" value={formData.class_type} onChange={e => setFormData({...formData, class_type: e.target.value})} /> <button onClick={generateAI} disabled={isGenerating} className="w-full bg-purple-600 py-2 rounded font-bold text-xs mt-2 hover:bg-purple-500"> {isGenerating ? 'GENERATING...' : 'AI VISUALIZE'} </button> </div> </div>
<textarea className="w-full h-32 bg-slate-950 p-2 rounded border border-slate-700 mb-2" placeholder="Inventory (AI reads this!)" value={formData.inventory} onChange={e => setFormData({...formData, inventory: e.target.value})} /> <button onClick={saveChar} className="bg-slate-800 w-full py-2 rounded hover:bg-slate-700">Save Stats</button> </div>
<div className="space-y-6"> <div className="bg-slate-900 p-6 rounded border border-slate-800"> <h2 className="text-xl font-bold text-yellow-400 mb-2">Adventure Log</h2> <input className="w-full bg-slate-950 p-2 mb-2 rounded" placeholder="Title" value={journal.title} onChange={e => setJournal({...journal, title: e.target.value})} /> <textarea className="w-full bg-slate-950 p-2 mb-2 h-24 rounded" placeholder="What happened?" value={journal.content} onChange={e => setJournal({...journal, content: e.target.value})} /> <div className="flex justify-between items-center"> <label className="flex gap-2 items-center text-sm"><input type="checkbox" checked={journal.is_public} onChange={e => setJournal({...journal, is_public: e.target.checked})}/> Make Public?</label> <button onClick={saveJournal} className="bg-yellow-700 px-4 py-1 rounded text-sm">Log It</button> </div> </div>
<div className="h-[300px] overflow-y-auto space-y-2"> {data?.journals?.map((j: any) => ( <div key={j.id} className="bg-slate-900 p-3 rounded border border-slate-800"> <div className="flex justify-between text-xs text-slate-500"> <span className="font-bold text-slate-300">{j.username}</span> <span>{new Date(j.created_at).toLocaleDateString()}</span> </div> <div className="font-bold">{j.title}</div> <div className="text-sm text-slate-400">{j.content}</div> {j.is_public === 1 && <span className="text-[10px] bg-green-900 text-green-300 px-1 rounded">PUBLIC</span>} </div> ))} </div> </div> </div> <AICompanion userId={user.id} /> </div> );}""",
"app/login/page.tsx": """'use client';import { useState } from 'react';import { useRouter } from 'next/navigation';
export default function Login() { const [form, setForm] = useState({ username: '', password: '' }); const router = useRouter();
async function handleAuth(action: 'LOGIN' | 'SIGNUP') { const res = await fetch('/api/auth', { method: 'POST', body: JSON.stringify({ action, ...form }) }); const data = await res.json(); if (data.success) { if (action === 'SIGNUP') { alert("Account created! Please log in."); } else { localStorage.setItem('rpg_user', JSON.stringify(data.user)); router.push('/'); } } else { alert(data.error); } }
return ( <div className="h-screen flex items-center justify-center bg-slate-950 text-white"> <div className="bg-slate-900 p-8 rounded border border-slate-800 w-96 space-y-4"> <h1 className="text-2xl font-bold text-center">RPG COMPANION</h1> <input className="w-full bg-slate-950 p-3 rounded border border-slate-700" placeholder="Username" onChange={e => setForm({...form, username: e.target.value})} /> <input className="w-full bg-slate-950 p-3 rounded border border-slate-700" type="password" placeholder="Password" onChange={e => setForm({...form, password: e.target.value})} /> <div className="flex gap-2"> <button onClick={() => handleAuth('LOGIN')} className="flex-1 bg-blue-600 py-2 rounded">Login</button> <button onClick={() => handleAuth('SIGNUP')} className="flex-1 bg-slate-700 py-2 rounded">Sign Up</button> </div> <p className="text-xs text-center text-slate-500">Note: The first user created becomes the Admin (DM).</p> </div> </div> );}"""}
# Create filesfor path, content in files.items(): # Create directory if needed if '/' in path: os.makedirs(os.path.dirname(path), exist_ok=True) # Write file with open(path, 'w', encoding='utf-8') as f: f.write(content) print(f"Created: {path}")
print("\n--- DONE! Project generated. ---")print("1. If running locally, type: npm install")print("2. Then type: npm run dev")print("3. If on Hugging Face, just hit 'Restart Space'.")1234567/** @type {import('next').NextConfig} */
const nextConfig = {
typescript: { ignoreBuildErrors: true },
eslint: { ignoreDuringBuilds: true },
output: 'standalone',
};
module.exports = nextConfig;123456789101112131415161718192021222324252627282930{
"name": "rpg-companion-ultimate",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "14.1.0",
"react": "^18",
"react-dom": "^18",
"better-sqlite3": "^9.4.0",
"swr": "^2.2.5",
"@huggingface/inference": "^2.6.4",
"lucide-react": "^0.330.0",
"clsx": "^2.1.0",
"tailwind-merge": "^2.2.1"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/better-sqlite3": "^7.6.9",
"autoprefixer": "^10.0.1",
"postcss": "^8",
"tailwindcss": "^3.3.0",
"typescript": "^5"
}
}123456module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}12345678910111213import type { Config } from "tailwindcss";
const config: Config = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {},
},
plugins: [],
};
export default config;123456789101112131415161718192021{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [{"name": "next"}],
"paths": {"@/*": ["./*"]}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}DockerfileAdded+8
install.pyAdded+752
next.config.jsAdded+7
package.jsonAdded+30
postcss.config.jsAdded+6
tailwind.config.tsAdded+13
tsconfig.jsonAdded+21