diff --git a/build-worker/server.js b/build-worker/server.js index e3730fe..c19bb83 100644 --- a/build-worker/server.js +++ b/build-worker/server.js @@ -81,97 +81,96 @@ async function runBuild({ buildId, files, appName, packageName, version }) { } fs.mkdirSync(projectDir, { recursive: true }); - // Write all project files + // ── Template-based build: start from golden template, merge LLM additions ── + const TEMPLATE_DIR = path.join(__dirname, "template"); + const CONFIG_FILES = ["package.json", "app.json", "babel.config.js", "tsconfig.json"]; + + // 1. Copy template files as the base + for (const cf of CONFIG_FILES) { + const src = path.join(TEMPLATE_DIR, cf); + const dst = path.join(projectDir, cf); + if (fs.existsSync(src)) { + fs.copyFileSync(src, dst); + } + } + + // 2. Parse LLM-generated package.json for extra deps (if any) + const pkgPath = path.join(projectDir, "package.json"); + const templatePkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + const coreDeps = new Set(Object.keys(templatePkg.dependencies)); + const coreDevDeps = new Set(Object.keys(templatePkg.devDependencies || {})); + + if (files["package.json"]) { + try { + const llmPkg = JSON.parse(files["package.json"]); + // Add extra deps that aren't in the template (never override core) + for (const [dep, ver] of Object.entries(llmPkg.dependencies || {})) { + if (!coreDeps.has(dep)) { + templatePkg.dependencies[dep] = ver; + } + } + for (const [dep, ver] of Object.entries(llmPkg.devDependencies || {})) { + if (!coreDevDeps.has(dep)) { + templatePkg.devDependencies[dep] = ver; + } + } + } catch (e) { + log(buildId, "warn", "Could not parse LLM package.json, using template only"); + } + } + // Update package name + templatePkg.name = (packageName || "apk-forge-app").replace(/[^a-z0-9-]/g, "-"); + fs.writeFileSync(pkgPath, JSON.stringify(templatePkg, null, 2)); + + // 3. Merge app.json — take name/slug/colors from LLM, keep template structure + const appJsonPath = path.join(projectDir, "app.json"); + const templateAppJson = JSON.parse(fs.readFileSync(appJsonPath, "utf-8")); + if (files["app.json"]) { + try { + const llmAppJson = JSON.parse(files["app.json"]); + const llmExpo = llmAppJson.expo || {}; + // Merge cosmetic fields from LLM + if (llmExpo.name) templateAppJson.expo.name = llmExpo.name; + if (llmExpo.slug) templateAppJson.expo.slug = llmExpo.slug; + if (llmExpo.icon) templateAppJson.expo.icon = llmExpo.icon; + if (llmExpo.splash?.backgroundColor) templateAppJson.expo.splash.backgroundColor = llmExpo.splash.backgroundColor; + if (llmExpo.android?.adaptiveIcon?.backgroundColor) { + templateAppJson.expo.android.adaptiveIcon.backgroundColor = llmExpo.android.adaptiveIcon.backgroundColor; + } + if (llmExpo.android?.package) templateAppJson.expo.android.package = llmExpo.android.package; + // Merge extra plugins from LLM + if (llmExpo.plugins) { + const existingPlugins = new Set(templateAppJson.expo.plugins.map(p => typeof p === "string" ? p : p[0])); + for (const plugin of llmExpo.plugins) { + const pluginName = typeof plugin === "string" ? plugin : plugin[0]; + if (!existingPlugins.has(pluginName)) { + templateAppJson.expo.plugins.push(plugin); + } + } + } + } catch (e) { + log(buildId, "warn", "Could not parse LLM app.json, using template only"); + } + } + // Apply defaults + const safeName = (appName || templateAppJson.expo.name || "APK Forge App").replace(/[^a-zA-Z0-9 ]/g, ""); + const safeSlug = safeName.toLowerCase().replace(/\s+/g, "-"); + templateAppJson.expo.name = safeName; + if (!templateAppJson.expo.slug || templateAppJson.expo.slug === "my-app") templateAppJson.expo.slug = safeSlug; + if (!templateAppJson.expo.android.package) { + templateAppJson.expo.android.package = packageName || `com.apkforge.${safeSlug.replace(/-/g, "")}`; + } + fs.writeFileSync(appJsonPath, JSON.stringify(templateAppJson, null, 2)); + + // 4. Write only LLM-generated source files (skip config files handled by template) + const skipFiles = new Set(CONFIG_FILES); for (const [filePath, content] of Object.entries(files)) { + if (skipFiles.has(filePath)) continue; const fullPath = path.join(projectDir, filePath); fs.mkdirSync(path.dirname(fullPath), { recursive: true }); fs.writeFileSync(fullPath, content); } - // Force correct package.json with compatible Expo deps (LLM often generates ancient versions) - const pkgPath = path.join(projectDir, "package.json"); - const REQUIRED_DEPS = { - "expo": "~52.0.0", - "expo-status-bar": "~2.0.0", - "react": "18.3.1", - "react-native": "0.76.3", - "react-native-screens": "~4.1.0", - "react-native-safe-area-context": "~5.0.0", - "@expo/vector-icons": "^14.0.0" - }; - const REQUIRED_DEV_DEPS = { - "@babel/core": "^7.24.0", - "typescript": "~5.3.3", - "@types/react": "~18.2.45" - }; - let pkg; - if (fs.existsSync(pkgPath)) { - pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); - // Force main entry point - pkg.main = "expo/AppEntry.js"; - // Override core deps with known-working versions - pkg.dependencies = { ...(pkg.dependencies || {}), ...REQUIRED_DEPS }; - // Fix navigation deps if present (force v7 compatible with Expo 52) - if (pkg.dependencies["@react-navigation/native"]) pkg.dependencies["@react-navigation/native"] = "^7.0.0"; - if (pkg.dependencies["@react-navigation/native-stack"]) pkg.dependencies["@react-navigation/native-stack"] = "^7.0.0"; - if (pkg.dependencies["react-native-reanimated"]) pkg.dependencies["react-native-reanimated"] = "~3.16.0"; - if (pkg.dependencies["react-native-gesture-handler"]) pkg.dependencies["react-native-gesture-handler"] = "~2.20.0"; - pkg.devDependencies = { ...(pkg.devDependencies || {}), ...REQUIRED_DEV_DEPS }; - // Remove old expo config from package.json (use app.json instead) - delete pkg.expo; - } else { - pkg = { - name: (packageName || "apk-forge-app").replace(/[^a-z0-9-]/g, "-"), - version: "1.0.0", - main: "expo/AppEntry.js", - scripts: { - start: "expo start", - android: "expo start --android", - ios: "expo start --ios", - web: "expo start --web" - }, - dependencies: { - ...REQUIRED_DEPS, - "@react-navigation/native": "^7.0.0", - "@react-navigation/native-stack": "^7.0.0", - }, - devDependencies: REQUIRED_DEV_DEPS - }; - } - fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2)); - - // Ensure app.json exists - const appJsonPath = path.join(projectDir, "app.json"); - if (!fs.existsSync(appJsonPath)) { - const safeName = (appName || "APK Forge App").replace(/[^a-zA-Z0-9 ]/g, ""); - const safeSlug = safeName.toLowerCase().replace(/\s+/g, "-"); - const appJson = { - expo: { - name: safeName, - slug: safeSlug, - version: "1.0.0", - orientation: "portrait", - icon: "./assets/icon.png", - userInterfaceStyle: "automatic", - newArchEnabled: true, - splash: { - image: "./assets/splash-icon.png", - resizeMode: "contain", - backgroundColor: "#1a1a2e" - }, - android: { - adaptiveIcon: { - foregroundImage: "./assets/adaptive-icon.png", - backgroundColor: "#1a1a2e" - }, - package: packageName || `com.apkforge.${safeSlug.replace(/-/g, "")}` - }, - plugins: ["expo-router"] - } - }; - fs.writeFileSync(appJsonPath, JSON.stringify(appJson, null, 2)); - } - // Create placeholder assets if missing const assetsDir = path.join(projectDir, "assets"); fs.mkdirSync(assetsDir, { recursive: true }); diff --git a/build-worker/template/App.tsx b/build-worker/template/App.tsx new file mode 100644 index 0000000..48fa6f6 --- /dev/null +++ b/build-worker/template/App.tsx @@ -0,0 +1,32 @@ +import React from 'react'; +import { View, Text, StyleSheet } from 'react-native'; +import { StatusBar } from 'expo-status-bar'; + +export default function App() { + return ( + + Welcome to My App + Built with APK Forge + + + ); +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: '#1a1a2e', + alignItems: 'center', + justifyContent: 'center', + }, + title: { + fontSize: 28, + fontWeight: 'bold', + color: '#ffffff', + marginBottom: 8, + }, + subtitle: { + fontSize: 16, + color: '#a0a0b0', + }, +}); diff --git a/build-worker/template/app.json b/build-worker/template/app.json new file mode 100644 index 0000000..290c8a5 --- /dev/null +++ b/build-worker/template/app.json @@ -0,0 +1,24 @@ +{ + "expo": { + "name": "My App", + "slug": "my-app", + "version": "1.0.0", + "orientation": "portrait", + "icon": "./assets/icon.png", + "userInterfaceStyle": "automatic", + "newArchEnabled": true, + "splash": { + "image": "./assets/splash-icon.png", + "resizeMode": "contain", + "backgroundColor": "#1a1a2e" + }, + "android": { + "adaptiveIcon": { + "foregroundImage": "./assets/adaptive-icon.png", + "backgroundColor": "#1a1a2e" + }, + "package": "com.apkforge.myapp" + }, + "plugins": ["expo-font", "expo-haptics"] + } +} diff --git a/build-worker/template/babel.config.js b/build-worker/template/babel.config.js new file mode 100644 index 0000000..9e4d4b7 --- /dev/null +++ b/build-worker/template/babel.config.js @@ -0,0 +1,4 @@ +module.exports = function (api) { + api.cache(true); + return { presets: ['babel-preset-expo'] }; +}; diff --git a/build-worker/template/package.json b/build-worker/template/package.json new file mode 100644 index 0000000..e24f24d --- /dev/null +++ b/build-worker/template/package.json @@ -0,0 +1,31 @@ +{ + "name": "apk-forge-app", + "version": "1.0.0", + "main": "expo/AppEntry.js", + "scripts": { + "start": "expo start", + "android": "expo start --android" + }, + "dependencies": { + "expo": "~52.0.0", + "expo-status-bar": "~2.0.0", + "react": "18.3.1", + "react-native": "0.76.3", + "@react-navigation/native": "^7.0.0", + "@react-navigation/native-stack": "^7.0.0", + "react-native-screens": "~4.1.0", + "react-native-safe-area-context": "~5.0.0", + "react-native-reanimated": "~3.16.0", + "react-native-gesture-handler": "~2.20.0", + "@expo/vector-icons": "^14.0.0", + "expo-linear-gradient": "~14.0.0", + "expo-haptics": "~14.0.0", + "expo-font": "~13.0.0", + "@react-native-async-storage/async-storage": "2.1.0" + }, + "devDependencies": { + "@babel/core": "^7.24.0", + "typescript": "~5.3.3", + "@types/react": "~18.2.45" + } +} diff --git a/build-worker/template/tsconfig.json b/build-worker/template/tsconfig.json new file mode 100644 index 0000000..b9567f6 --- /dev/null +++ b/build-worker/template/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "expo/tsconfig.base", + "compilerOptions": { + "strict": true + } +} diff --git a/src/app/api/build/route.ts b/src/app/api/build/route.ts index 95fb3f7..12744a5 100644 --- a/src/app/api/build/route.ts +++ b/src/app/api/build/route.ts @@ -76,7 +76,13 @@ export async function POST(req: NextRequest) { // Check build limit const buildCheck = await checkBuildLimit(session.userId); if (!buildCheck.allowed) { - return NextResponse.json({ error: "Build limit reached. Upgrade your plan." }, { status: 403 }); + // Fetch user to give plan-specific message + const db2 = await getDb(); + const buildUser = await db2.collection("users").findOne({ _id: new ObjectId(session.userId) }); + const errorMsg = buildUser?.plan === "free" + ? "Free plan allows 3 APK builds per month. Upgrade to continue." + : "Build limit reached. Upgrade your plan."; + return NextResponse.json({ error: errorMsg }, { status: 403 }); } // Determine version diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.ts index e8ce701..823c7e4 100644 --- a/src/app/api/chat/route.ts +++ b/src/app/api/chat/route.ts @@ -1,6 +1,6 @@ // @ts-nocheck import { NextRequest, NextResponse } from "next/server"; -import { getSession, incrementUsage, checkBuildLimit } from "@/lib/auth"; +import { getSession, incrementUsage, checkBuildLimit, checkLlmLimit } from "@/lib/auth"; import { checkRateLimit } from "@/lib/rate-limit"; import { getDb } from "@/lib/db"; import { callLLM } from "@/lib/llm"; @@ -67,6 +67,15 @@ export async function POST(req: NextRequest) { ); } + // Check LLM usage limit (free plan) + const llmCheck = await checkLlmLimit(session.userId); + if (!llmCheck.allowed) { + return NextResponse.json( + { error: "Free plan allows 50 AI messages per month. Upgrade to continue." }, + { status: 403 } + ); + } + const { projectId, message, questionAnswers, markFormSubmitted } = await req.json(); // Handle marking a form as submitted (no LLM call needed) @@ -168,8 +177,8 @@ export async function POST(req: NextRequest) { projectName: project.name, }); - // Track usage - await incrementUsage(session.userId, "totalPrompts"); + // Track usage (increments both promptsThisMonth and totalPrompts) + await incrementUsage(session.userId, "promptsThisMonth"); // If build is ready, check limits and increment if (aiResponse.buildReady) { diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsx index 5acf4cf..c262c69 100644 --- a/src/app/dashboard/page.tsx +++ b/src/app/dashboard/page.tsx @@ -24,6 +24,13 @@ interface UserInfo { username: string; role: string; plan: string; + usage?: { + buildsThisMonth: number; + promptsThisMonth: number; + totalBuilds: number; + totalPrompts: number; + monthResetAt: string; + }; } const templates = [ @@ -146,6 +153,11 @@ export default function DashboardPage() { {user?.username} {user?.plan} + {user?.usage && ( + + {user.usage.promptsThisMonth || 0}/{user.plan === "free" ? "50" : "∞"} AI messages · {user.usage.buildsThisMonth || 0}/{user.plan === "free" ? "3" : user.plan === "starter" ? "10" : user.plan === "pro" ? "50" : "∞"} builds + + )} diff --git a/src/app/page.tsx b/src/app/page.tsx index cc51642..4666853 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -17,9 +17,14 @@ const steps = [ ]; const plans = [ + { + name: "Free", price: "$0", period: "/month", + features: ["3 builds per month", "50 AI messages per month", "Source code download", "Community support"], + cta: "Get Started", highlight: false, + }, { name: "Starter", price: "$12", period: "/month", - features: ["10 builds per month", "AI-powered code generation", "Source code download", "APK builds", "Build history"], + features: ["10 builds per month", "Unlimited AI messages", "Source code download", "APK builds", "Build history"], cta: "Get Started", highlight: false, }, { @@ -195,7 +200,7 @@ export default function Home() {

Simple Pricing

No hidden fees. Cancel anytime.

-
+
{plans.map((plan) => (
{plan.highlight &&
Most popular
} diff --git a/src/lib/auth.ts b/src/lib/auth.ts index 7d48877..088ad38 100644 --- a/src/lib/auth.ts +++ b/src/lib/auth.ts @@ -76,11 +76,12 @@ export async function createUser( email: email.toLowerCase().trim(), passwordHash, role: "user", - plan: "starter" as PlanTier, + plan: "free" as PlanTier, emailVerified: false, emailVerificationToken: generateToken(), usage: { buildsThisMonth: 0, + promptsThisMonth: 0, totalBuilds: 0, totalPrompts: 0, monthResetAt: getNextMonthReset(), @@ -119,32 +120,41 @@ export async function updateUser(id: string, update: Partial): Promise { const db = await getDb(); const user = await findUserById(userId); if (!user) return; - // Reset monthly counter if needed + const isMonthlyField = field === "buildsThisMonth" || field === "promptsThisMonth"; + + // Reset monthly counters if needed if (new Date() >= user.usage.monthResetAt) { + const setFields: Record = { + "usage.buildsThisMonth": field === "buildsThisMonth" ? 1 : 0, + "usage.promptsThisMonth": field === "promptsThisMonth" ? 1 : 0, + "usage.monthResetAt": getNextMonthReset(), + updatedAt: new Date(), + }; + const incFields: Record = {}; + if (field === "buildsThisMonth") incFields["usage.totalBuilds"] = 1; + else if (field === "promptsThisMonth") incFields["usage.totalPrompts"] = 1; + else incFields[`usage.${field}`] = 1; + await db.collection("users").updateOne( { _id: new ObjectId(userId) }, - { - $set: { - "usage.buildsThisMonth": field === "buildsThisMonth" ? 1 : 0, - "usage.monthResetAt": getNextMonthReset(), - updatedAt: new Date(), - }, - $inc: { - [`usage.${field === "buildsThisMonth" ? "totalBuilds" : field}`]: 1, - }, - } + { $set: setFields, $inc: incFields } ); } else { + const incFields: Record = { [`usage.${field}`]: 1 }; + // Also increment the total counter for monthly fields + if (field === "buildsThisMonth") incFields["usage.totalBuilds"] = 1; + else if (field === "promptsThisMonth") incFields["usage.totalPrompts"] = 1; + await db.collection("users").updateOne( { _id: new ObjectId(userId) }, { - $inc: { [`usage.${field}`]: 1 }, + $inc: incFields, $set: { updatedAt: new Date() }, } ); @@ -169,6 +179,24 @@ export async function checkBuildLimit(userId: string): Promise<{ allowed: boolea return { allowed: remaining > 0, remaining }; } +export async function checkLlmLimit(userId: string): Promise<{ allowed: boolean; remaining: number }> { + const user = await findUserById(userId); + if (!user) return { allowed: false, remaining: 0 }; + + const { plan, usage } = user; + const allLimits = (await import("@/types")).PLAN_LIMITS; + const limits = allLimits[plan] || allLimits["free"] || { llmRequestsPerMonth: 50 }; + + if (limits.llmRequestsPerMonth === -1) return { allowed: true, remaining: -1 }; + + // Reset if month passed + let currentPrompts = usage.promptsThisMonth || 0; + if (new Date() >= usage.monthResetAt) currentPrompts = 0; + + const remaining = limits.llmRequestsPerMonth - currentPrompts; + return { allowed: remaining > 0, remaining }; +} + // ─── Helpers ──────────────────────────────────────────────────── function generateToken(): string { return crypto.randomBytes(32).toString('hex'); diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.ts index f0f6117..a43d8b2 100644 --- a/src/lib/rate-limit.ts +++ b/src/lib/rate-limit.ts @@ -8,6 +8,7 @@ interface RateLimitEntry { } const RATE_LIMITS: Record = { + free: 5, starter: 10, pro: 30, unlimited: 60, diff --git a/src/lib/system-prompt.ts b/src/lib/system-prompt.ts index 1f5b965..7efbf83 100644 --- a/src/lib/system-prompt.ts +++ b/src/lib/system-prompt.ts @@ -65,6 +65,18 @@ When the user describes an app for the first time: 6. Set \`buildReady\` to true — the project MUST be complete and buildable 7. The \`questions\` array MUST be empty when generating files +### Available Packages +The project uses Expo SDK 52 with React Native 0.76. The following packages are pre-installed and available: +- expo, expo-status-bar, expo-linear-gradient, expo-haptics, expo-font +- @react-navigation/native, @react-navigation/native-stack +- react-native-screens, react-native-safe-area-context +- react-native-reanimated, react-native-gesture-handler +- @expo/vector-icons (MaterialIcons, Ionicons, FontAwesome, etc.) +- @react-native-async-storage/async-storage + +Use these packages freely. If you need additional packages, include them in package.json dependencies. +Do NOT specify version numbers for expo, react, or react-native in package.json — the build system handles versions. + ### Code Style - Use TypeScript for all React Native code - Follow Material Design 3 patterns diff --git a/src/types/index.ts b/src/types/index.ts index 4f0e22a..0bebd2f 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1,30 +1,41 @@ import { ObjectId } from "mongodb"; // ─── Subscription & Plans ─────────────────────────────────────── -export type PlanTier = "starter" | "pro" | "unlimited"; +export type PlanTier = "free" | "starter" | "pro" | "unlimited"; export interface PlanLimits { buildsPerMonth: number; // -1 = unlimited + llmRequestsPerMonth: number; // -1 = unlimited models: string[]; priorityBuild: boolean; customBranding: boolean; } export const PLAN_LIMITS: Record = { + free: { + buildsPerMonth: 3, + llmRequestsPerMonth: 50, + models: ["gpt-4.1-mini"], + priorityBuild: false, + customBranding: false, + }, starter: { buildsPerMonth: 10, + llmRequestsPerMonth: -1, models: ["claude-sonnet-4-6", "gpt-4.1-mini"], priorityBuild: false, customBranding: false, }, pro: { buildsPerMonth: 50, + llmRequestsPerMonth: -1, models: ["claude-sonnet-4-6", "gpt-4.1-mini", "claude-opus-4-6", "gpt-5-mini", "deepseek-chat"], priorityBuild: true, customBranding: false, }, unlimited: { buildsPerMonth: -1, + llmRequestsPerMonth: -1, models: ["claude-sonnet-4-6", "gpt-4.1-mini", "claude-opus-4-6", "gpt-5-mini", "gpt-5.4", "o3", "deepseek-chat"], priorityBuild: true, customBranding: true, @@ -32,12 +43,14 @@ export const PLAN_LIMITS: Record = { }; export const PLAN_PRICES: Record = { + free: 0, starter: 12, pro: 29, unlimited: 59, }; export const PLAN_NAMES: Record = { + free: "Free", starter: "Starter", pro: "Pro", unlimited: "Unlimited", @@ -60,6 +73,7 @@ export interface User { passwordResetExpires?: Date; usage: { buildsThisMonth: number; + promptsThisMonth: number; totalBuilds: number; totalPrompts: number; monthResetAt: Date; diff --git a/tsconfig.json b/tsconfig.json index cf9c65d..c9aa20f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -30,5 +30,5 @@ ".next/dev/types/**/*.ts", "**/*.mts" ], - "exclude": ["node_modules"] + "exclude": ["node_modules", "build-worker"] }