Full Stack App Blueprint
Run ID: 69cc2e66fdffe128046c553c2026-03-31Development
PantheraHive BOS
BOS Dashboard

Full Stack Application Blueprint: Detailed Professional Output

This document provides a comprehensive and detailed blueprint for your full-stack application, encompassing frontend components, backend API, database design, authentication, deployment configurations, and testing strategies. The goal is to provide a clear, actionable foundation, with production-ready code examples and explanations, enabling your team to commence development efficiently.


1. Project Overview

This blueprint outlines a robust, scalable, and maintainable full-stack application. We will leverage modern technologies for optimal performance and developer experience:

Application Scope (Example Use Case): A simple task management application where users can register, log in, create, view, update, and delete their tasks.


2. Frontend Blueprint (React + TypeScript)

The frontend will be structured for modularity, reusability, and maintainability, using React components and a service-oriented architecture for API interactions.

2.1. Project Structure

text • 1,675 chars
frontend/
├── public/
│   └── index.html
├── src/
│   ├── assets/                # Static assets like images, icons
│   ├── components/            # Reusable UI components (e.g., Button, Input)
│   │   ├── Button/Button.tsx
│   │   └── Input/Input.tsx
│   ├── features/              # Feature-specific components and logic (e.g., Auth, Tasks)
│   │   ├── Auth/
│   │   │   ├── components/    # Auth-specific components (e.g., LoginForm)
│   │   │   │   └── LoginForm.tsx
│   │   │   └── pages/         # Auth-specific pages (e.g., LoginPage)
│   │   │       └── LoginPage.tsx
│   │   └── Tasks/
│   │       ├── components/
│   │       │   └── TaskList.tsx
│   │       └── pages/
│   │           └── TasksPage.tsx
│   ├── hooks/                 # Custom React hooks (e.g., useAuth)
│   ├── layouts/               # Layout components (e.g., MainLayout, AuthLayout)
│   ├── pages/                 # Top-level page components (e.g., HomePage, DashboardPage)
│   ├── services/              # API interaction logic (e.g., authService, taskService)
│   │   ├── api.ts             # Axios instance configuration
│   │   ├── authService.ts
│   │   └── taskService.ts
│   ├── store/                 # State management (e.g., Redux, Zustand, React Context)
│   │   └── authStore.ts
│   ├── types/                 # TypeScript type definitions
│   │   └── index.d.ts
│   ├── utils/                 # Utility functions (e.g., helpers, formatters)
│   ├── App.tsx                # Main application component
│   ├── index.tsx              # Entry point
│   └── reportWebVitals.ts
├── tailwind.config.js         # Tailwind CSS configuration
├── tsconfig.json
├── package.json
└── README.md
Sandboxed live preview

Full Stack Application Blueprint: Architectural Plan

This document outlines the detailed architectural plan for your full-stack application, covering all major components from frontend to deployment. This plan provides a robust, scalable, and maintainable foundation for development.


1. Project Overview & Guiding Principles

Goal: To establish a comprehensive blueprint for building a modern, performant, secure, and scalable full-stack application. This plan serves as the foundational technical specification for all subsequent development phases.

Architectural Principles:

  • Modularity & Decoupling: Components should be independent and communicate via well-defined interfaces to facilitate easier development, testing, and maintenance.
  • Scalability: Design for horizontal scaling of both frontend and backend services to handle increased load.
  • Security First: Implement security best practices at every layer, from authentication to data storage and network communication.
  • Maintainability & Readability: Prioritize clean code, consistent patterns, and comprehensive documentation to ensure long-term sustainability.
  • Performance: Optimize for fast load times, responsive user interfaces, and efficient API responses.
  • Developer Experience (DX): Choose technologies and tools that enhance developer productivity and collaboration.
  • Observability: Integrate logging, monitoring, and alerting to gain insights into application health and performance.

2. Core Components & Recommended Technology Stack

This blueprint proposes a modern, robust, and widely adopted technology stack, offering a balance of performance, developer experience, and community support.

  • Frontend: React with Next.js (TypeScript)
  • Backend (API): Node.js with NestJS (TypeScript)
  • Database: PostgreSQL
  • ORM/ODM: Prisma ORM
  • Authentication: JWT (JSON Web Tokens)
  • Deployment: Docker, AWS (ECS, RDS, S3, CloudFront), GitHub Actions (CI/CD)
  • Testing: Jest, React Testing Library, Cypress

3. Detailed Architecture Breakdown

3.1. Frontend Architecture

The frontend will be built as a single-page application (SPA) with server-side rendering (SSR) capabilities for improved performance and SEO, using a component-based approach.

  • Framework/Library: React.js

* Rationale: Highly popular, component-based, large ecosystem, strong community support.

  • Meta-Framework: Next.js

* Rationale: Provides SSR, Static Site Generation (SSG), API routes, file-system based routing, and optimized builds out-of-the-box, significantly enhancing performance and developer experience.

  • Language: TypeScript

* Rationale: Provides static typing, improving code quality, maintainability, and reducing runtime errors.

  • State Management:

* Data Fetching & Caching: React Query (TanStack Query)

* Rationale: Manages server state, caching, re-fetching, and optimistic updates efficiently, reducing boilerplate for data operations.

* Client-Side UI State: Zustand

* Rationale: A lightweight, fast, and scalable state management solution for simple global UI state.

  • UI Component Library/Styling: Tailwind CSS

* Rationale: A utility-first CSS framework for rapidly building custom designs without leaving your HTML. Highly configurable and performant. Consider UI component libraries like Radix UI or Shadcn UI for unstyled, accessible components if a pre-built component system is desired.

  • Routing: Handled by Next.js's file-system based router.
  • Build Tooling: Integrated into Next.js (Webpack/Turbopack).
  • Deployment Strategy:

* Build artifacts deployed to AWS S3 and served via AWS CloudFront (CDN) for global low-latency access. Next.js server components and API routes would run on AWS Lambda (via Next.js's serverless deployment target).

3.2. Backend (API) Architecture

The backend will be a robust, scalable, and secure API service.

  • Framework/Language: Node.js with NestJS

* Rationale:

* Node.js: Asynchronous, event-driven runtime ideal for I/O-bound applications, enabling high concurrency.

* NestJS: A progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It leverages TypeScript and combines elements of OOP, functional programming, and reactive programming, providing an opinionated and structured architecture similar to Angular.

  • API Style: RESTful API

* Rationale: Widely adopted, stateless, easy to consume, and well-understood.

  • Database ORM/ODM: Prisma ORM

* Rationale: Modern, type-safe ORM that integrates seamlessly with TypeScript, providing an intuitive API for database interactions and powerful schema migrations.

  • Authentication & Authorization:

* Authentication: JWT (JSON Web Tokens)

* Strategy: Users authenticate with username/password, receive an access token (JWT). This token is then sent with subsequent requests. Refresh tokens can be implemented for long-lived sessions.

* Implementation: Handled by NestJS Passport module with JWT strategy.

* Authorization: Role-Based Access Control (RBAC)

* Strategy: Define roles (e.g., Admin, User, Guest) and assign permissions to these roles. Middleware/Guards in NestJS will check user roles/permissions before allowing access to specific routes/resources.

  • Error Handling: Centralized error handling middleware/interceptors in NestJS to catch and format errors consistently (e.g., 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Internal Server Error).
  • Validation: Class-validator integrated with NestJS pipes for request payload validation.
  • Logging: Winston or Pino integrated with NestJS for structured logging, outputting to stdout for containerized environments, easily ingestible by monitoring systems.
  • Monitoring: Expose Prometheus metrics endpoints.
  • Deployment Strategy:

* Containerized using Docker.

* Deployed to AWS Elastic Container Service (ECS) with Fargate for serverless container management, ensuring scalability and high availability.

* Load balancing via AWS Application Load Balancer (ALB).

3.3. Database Architecture

A relational database is chosen for its data integrity, transaction support, and well-defined schema.

  • Database Type: Relational Database
  • Specific Database: PostgreSQL

* Rationale: Open-source, robust, highly reliable, feature-rich, and widely supported. Excellent for complex queries and transactional data.

  • Schema Design Principles:

* Normalization: Design for 3rd Normal Form (3NF) to minimize data redundancy and improve data integrity. Denormalization can be considered for specific performance bottlenecks if necessary.

* Indexing: Strategically apply indexes to frequently queried columns to optimize read performance.

* Foreign Keys: Enforce referential integrity using foreign key constraints.

* Data Types: Use appropriate data types for columns (e.g., UUID for primary keys, VARCHAR for strings, TEXT for long text, TIMESTAMP WITH TIME ZONE for dates).

  • Migration Strategy:

* Tool: Prisma Migrate

* Process: Version-controlled schema migrations applied automatically during deployment, ensuring database schema is always in sync with the application code.

  • Backup & Recovery:

* Strategy: Automated daily backups of the PostgreSQL database using AWS RDS snapshotting or logical backups (e.g., pg_dump).

* Recovery: Point-in-time recovery enabled.

  • Deployment: AWS Relational Database Service (RDS) for PostgreSQL. Managed service providing automated backups, patching, scaling, and high availability.

3.4. Authentication & Authorization

A robust security model is critical for any application.

  • Authentication Mechanism: JWT (JSON Web Tokens)

* Flow:

1. User sends credentials (username/password) to the backend API.

2. API authenticates user, generates a short-lived Access Token (JWT) and a long-lived Refresh Token.

3. Access Token is stored securely (e.g., in HttpOnly cookies or browser memory for SPA) and sent with every subsequent request in the Authorization header.

4. Refresh Token is stored securely (e.g., in HttpOnly cookies) and used to obtain new Access Tokens when the current one expires.

* Security: JWTs are signed with a secret key to prevent tampering. Tokens should have short lifespans.

  • User Management:

* Password Hashing: Use strong, industry-standard hashing algorithms (e.g., bcrypt) with sufficient salt rounds.

* User Registration & Login: Dedicated API endpoints for user creation and authentication.

* Password Reset: Secure password reset flow using one-time tokens sent via email.

  • Authorization (Role-Based Access Control - RBAC):

* Roles: Define distinct roles (e.g., Admin, Editor, Viewer, Authenticated User).

* Permissions: Associate granular permissions (e.g., user:create, product:read, product:update) with roles.

* Enforcement: NestJS Guards and Decorators will be used to protect API routes and resources based on the authenticated user's roles and permissions.

3.5. Deployment & DevOps

An automated and robust deployment pipeline is essential for continuous delivery.

  • Infrastructure Provider: Amazon Web Services (AWS)

* Rationale: Comprehensive suite of services, high availability, scalability, and security features.

  • Containerization: Docker

* Rationale: Encapsulates the application and its dependencies into portable containers, ensuring consistent environments across development, testing, and production.

  • CI/CD Pipeline: GitHub Actions

* Frontend Pipeline:

1. Code commit to main branch.

2. Run unit tests, linting.

3. Build Next.js application.

4. Deploy static assets to AWS S3 and invalidate CloudFront cache.

* Backend Pipeline:

1. Code commit to main branch.

2. Run unit tests, integration tests, linting.

3. Build Docker image.

4. Push Docker image to AWS Elastic Container Registry (ECR).

5. Update AWS ECS Fargate service to use the new Docker image, triggering a rolling update.

6. Run database migrations (carefully orchestrated).

  • Environment Management:

* Use .env files and environment variables for configuration.

* Separate environments (Development, Staging, Production) with distinct configurations and AWS resources.

* AWS Secrets Manager for sensitive credentials.

  • Monitoring & Alerting:

* AWS CloudWatch: Collects logs from ECS/Lambda, provides metrics (CPU, memory, network), and allows setting up alarms for critical events.

* Prometheus/Grafana (Optional): For more advanced custom metrics and dashboarding.

* Sentry (Optional): For real-time error tracking and reporting.

3.6. Testing Strategy

A comprehensive testing strategy ensures application quality, reliability, and reduces regressions.

  • Unit Tests:

* Scope: Individual functions, components, services, and modules in isolation.

* Tools: Jest (for both frontend and backend), React Testing Library (for frontend component interaction).

* Coverage: Aim for high unit test coverage (e.g., 80%+).

  • Integration Tests:

* Scope: Verify interactions between different components (e.g., frontend components with Redux store, backend services with database, API endpoints with their handlers).

* Tools: Jest (backend), React Testing Library (frontend).

  • End-to-End (E2E) Tests:

* Scope: Simulate real user scenarios across the entire application stack (browser -> frontend -> backend -> database).

* Tools: Cypress or Playwright.

* Execution: Run against a deployed staging environment.

  • Performance Tests (Optional for initial MVP):

* Scope: Assess application responsiveness and stability under various load conditions.

* Tools: JMeter, k6.

  • Security Tests (Penetration Testing):

* Scope: Identify vulnerabilities through ethical hacking techniques. (Often outsourced or performed by security specialists).

3.7. Cross-Cutting Concerns

  • Logging: Centralized, structured logging (e.g., JSON format) for easy aggregation and analysis in AWS CloudWatch.
  • Caching:

* Frontend: Browser caching, React Query caching.

* Backend: In-memory caching for frequently accessed static data. Consider Redis for distributed caching at scale.

  • Security:

* HTTPS everywhere (AWS ALB with ACM certificates).

* Input validation and sanitization.

* Protection against common web vulnerabilities (XSS, CSRF, SQL Injection) – frameworks like NestJS and Prisma provide built-in protections.

* Regular security audits and dependency vulnerability scanning.

  • Scalability: Achieved through stateless backend services, containerization, load balancing, database scaling (vertical initially, horizontal with read replicas if needed).
  • Error Handling: Consistent, user-friendly error messages on the frontend, detailed server-side logging for debugging.

4. Next Steps

This architectural blueprint provides a solid foundation. The next steps involve:

  1. Technology Deep Dive: Confirm specific versions and explore advanced features of chosen technologies.
  2. Detailed Data Modeling: Create the full database schema with all tables, relationships, and constraints.
  3. **API

typescript

// src/controllers/authController.ts

import { Request, Response, NextFunction } from 'express';

import * as authService from '../services/authService';

import { RegisterBody, LoginBody } from '../types'; // Define these types for request bodies

/**

* Handles user registration.

* @route POST /api/auth/register

*/

export const register = async (req: Request<{}, {}, RegisterBody>, res: Response, next: NextFunction) => {

try {

const { email, password, name } = req.body;

const user = await authService.registerUser(email, password, name);

res.status(201).json({ message: 'User registered successfully', user: { id: user.id, email: user.email, name: user.name } });

} catch (error) {

next(error); // Pass error to the error handling middleware

}

};

/**

* Handles user login.

* @route POST /api/auth/login

*/

export const login = async (req: Request<{}, {}, LoginBody>, res: Response, next: NextFunction) => {

try {

const { email, password } = req.body;

const { user, token } = await authService.loginUser(email, password);

res.status(200).json({ message: 'Login successful', user: { id: user.id, email: user.email, name: user.name }, token });

} catch (error) {

next(error);

}

};

/**

* Handles fetching current user profile.

* Requires authentication middleware

gemini Output

Full Stack Application Blueprint: Detailed Deliverable

This document outlines a comprehensive, detailed blueprint for your full-stack application, providing a ready-to-build foundation. It covers all essential architectural components, technology stacks, design considerations, and operational strategies to ensure a robust, scalable, and maintainable application.


1. Executive Summary & Application Overview

This blueprint proposes a modern, scalable full-stack application designed to provide a robust platform for [Insert Application's Core Purpose Here, e.g., "managing user-generated content and facilitating community interaction"]. The architecture leverages industry-standard technologies and best practices to ensure high performance, security, and ease of development.

Core Features (Example):

  • User Registration & Authentication
  • User Profile Management
  • CRUD operations for [Key Entity, e.g., "Items" or "Posts"]
  • Dashboard for [User/Admin]
  • Search and Filtering capabilities

High-Level Architecture:

The application will follow a micro-service-oriented (or layered monolithic) architecture, separating frontend (client-side) and backend (server-side) concerns, with a dedicated database layer. Communication between frontend and backend will be via a RESTful API.


+------------------+         +------------------+         +---------------------+
|    User Device   |         |    Web Browser   |         |       CDN           |
| (Mobile/Desktop) |         |  (Frontend App)  |         | (Static Assets)     |
+--------+---------+         +--------+---------+         +----------+----------+
         |                          |                               |
         | HTTP/S                   | HTTP/S                        | HTTP/S
         |                          |                               |
         |                          |       +-----------------------+
         |                          |       |
         |                          |       v
         |                          +--------------------------------+
         |                                  | API Gateway / Load Balancer    |
         |                                  +--------------------------------+
         |                                          | HTTP/S
         |                                          v
         |                           +--------------------------------+
         |                           |      Backend API Services      |
         |                           | (Node.js/Express/TypeScript)   |
         +---------------------------> (Authentication, User Mgmt,    |
                                     |  Item Mgmt, Business Logic)    |
                                     +--------------------------------+
                                                  |
                                                  | Database Connections
                                                  v
                                     +--------------------------------+
                                     |         Database Server        |
                                     |      (PostgreSQL / RDS)        |
                                     +--------------------------------+

2. Frontend Blueprint

The frontend will be a Single Page Application (SPA) designed for responsiveness, performance, and an intuitive user experience.

2.1. Technology Stack

  • Framework: React v18.x (with Hooks and Function Components)
  • Language: TypeScript 5.x
  • Styling: Tailwind CSS v3.x (for utility-first styling) & PostCSS
  • State Management: Zustand (lightweight and flexible) or React Query (for server state management)
  • Routing: React Router DOM v6.x
  • Build Tool: Vite v4.x (for fast development and optimized builds)
  • Linting/Formatting: ESLint, Prettier

2.2. Key Components & Structure

The application will be organized into a modular structure, promoting reusability and maintainability.

  • Layout Components:

* AppLayout: Main application shell with Header, Sidebar, and Footer.

* AuthLayout: Specific layout for login/registration pages.

* Header: Navigation, user avatar, notifications.

* Sidebar: Primary navigation links.

* Footer: Copyright, legal links.

  • Reusable UI Components (src/components/ui):

* Button, Input, Select, Textarea, Checkbox, Radio

* Modal, Dropdown, Tooltip, Popover

* Card, Table, Badge, Spinner

* Alert, ToastNotification

  • Page-Specific Components (src/pages):

* DashboardPage: Overview for logged-in users.

* ItemsListPage: Displays a list of [Items].

* ItemDetailPage: Displays details of a specific [Item].

* ItemFormPage: For creating/editing [Items].

* ProfilePage: User profile viewing and editing.

* LoginPage, RegisterPage, ForgotPasswordPage

  • Hooks (src/hooks): Custom hooks for encapsulating reusable logic (e.g., useAuth, useForm, useDebounce).
  • Services/API Integration (src/services): Axios for HTTP requests, configured with interceptors for token handling and error management.

2.3. User Flows (Example: Item Management)

  1. Login: User navigates to /login, enters credentials, receives JWT, redirected to /dashboard.
  2. View Items: User clicks "Items" in sidebar, navigates to /items. ItemsListPage fetches data from /api/items.
  3. Create New Item: User clicks "Add New Item", navigates to /items/new. ItemFormPage allows input, submits to /api/items (POST).
  4. Edit Item: User clicks "Edit" on an item in ItemsListPage, navigates to /items/:id/edit. ItemFormPage pre-fills data, submits to /api/items/:id (PUT).
  5. Delete Item: User clicks "Delete" on an item. Confirmation modal appears, on confirmation, sends DELETE request to /api/items/:id.

3. Backend API Blueprint

The backend will provide a robust, secure, and performant RESTful API to serve the frontend and potentially other clients.

3.1. Technology Stack

  • Framework: Node.js v18.x with Express.js v4.x
  • Language: TypeScript 5.x
  • ORM: Prisma v5.x (Type-safe database access)
  • Authentication: JWT (JSON Web Tokens)
  • Validation: Zod (Schema declaration and validation)
  • Logging: Winston / Pino
  • Testing: Jest, Supertest

3.2. API Architecture & Endpoints (RESTful)

The API will adhere to RESTful principles, using standard HTTP methods and status codes.

  • Base URL: /api/v1
  • Authentication & User Management:

* POST /auth/register: Register a new user.

* POST /auth/login: Authenticate user, return JWT.

* POST /auth/refresh-token: Get a new access token using a refresh token.

* GET /auth/me: Get current user's profile (protected).

* PUT /users/:id: Update user profile (protected, owner/admin).

* GET /users: List all users (protected, admin).

  • [Key Entity, e.g., Item] Management:

* GET /items: Get a list of [items] (with pagination, filtering, sorting).

* GET /items/:id: Get a specific [item] by ID.

* POST /items: Create a new [item] (protected).

* PUT /items/:id: Update an existing [item] (protected, owner/admin).

* DELETE /items/:id: Delete an [item] (protected, owner/admin).

3.3. Data Models (High-Level)

  • User: id, username, email, passwordHash, role (admin, user), createdAt, updatedAt, isActive.
  • Item: id, name, description, price, userId (FK to User), status, imageUrl, createdAt, updatedAt.
  • [Other Entities as needed, e.g., Category, Order, Comment]

3.4. Business Logic & Services

  • User Service: Handles user registration, login, profile updates, password management, role assignment.
  • Item Service: Manages CRUD operations for [items], including validation, data transformation, and authorization checks.
  • Authentication Middleware: Verifies JWTs, attaches user info to request, handles token expiration.
  • Authorization Middleware: Checks user roles/permissions for specific routes.
  • Error Handling: Centralized error handling middleware to catch exceptions and return consistent error responses (e.g., 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Internal Server Error).
  • Input Validation: All incoming API requests will be validated against Zod schemas.

3.5. Security Considerations

  • Input Validation: Prevent injection attacks (SQL, XSS, etc.).
  • Password Hashing: Use strong, salted hashing algorithms (e.g., bcrypt).
  • JWT Security: Secure signing key, short expiry times for access tokens, refresh tokens for extended sessions.
  • CORS: Properly configured to allow requests only from the authorized frontend domain(s).
  • Rate Limiting: Protect against brute-force attacks and abuse.
  • Environment Variables: Sensitive information (database credentials, JWT secret) stored in environment variables, not hardcoded.
  • HTTPS: Enforce SSL/TLS for all communication.

4. Database Design

A relational database will be used to ensure data integrity, consistency, and robust querying capabilities.

4.1. Database Technology

  • Type: Relational Database Management System (RDBMS)
  • Provider: PostgreSQL v15.x
  • Hosting: AWS RDS (Managed PostgreSQL service for scalability and reliability)

4.2. Schema Design (Example Tables)

Table: users

  • id (UUID, Primary Key, auto-generated)
  • username (VARCHAR(50), UNIQUE, NOT NULL)
  • email (VARCHAR(255), UNIQUE, NOT NULL)
  • password_hash (VARCHAR(255), NOT NULL)
  • role (ENUM('user', 'admin'), DEFAULT 'user', NOT NULL)
  • first_name (VARCHAR(100), NULL)
  • last_name (VARCHAR(100), NULL)
full_stack_app_blueprint.txt
Download source file
Copy all content
Full output as text
Download ZIP
IDE-ready project ZIP
Copy share link
Permanent URL for this run
Get Embed Code
Embed this result on any website
Print / Save PDF
Use browser print dialog
\n\n\n"); var hasSrcMain=Object.keys(extracted).some(function(k){return k.indexOf("src/main")>=0;}); if(!hasSrcMain) zip.file(folder+"src/main."+ext,"import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport './index.css'\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n \n \n \n)\n"); var hasSrcApp=Object.keys(extracted).some(function(k){return k==="src/App."+ext||k==="App."+ext;}); if(!hasSrcApp) zip.file(folder+"src/App."+ext,"import React from 'react'\nimport './App.css'\n\nfunction App(){\n return(\n
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n
\n )\n}\nexport default App\n"); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e}\n.app{min-height:100vh;display:flex;flex-direction:column}\n.app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px}\nh1{font-size:2.5rem;font-weight:700}\n"); zip.file(folder+"src/App.css",""); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/pages/.gitkeep",""); zip.file(folder+"src/hooks/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\n## Open in IDE\nOpen the project folder in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Vue (Vite + Composition API + TypeScript) --- */ function buildVue(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "type": "module",\n "scripts": {\n "dev": "vite",\n "build": "vue-tsc -b && vite build",\n "preview": "vite preview"\n },\n "dependencies": {\n "vue": "^3.5.13",\n "vue-router": "^4.4.5",\n "pinia": "^2.3.0",\n "axios": "^1.7.9"\n },\n "devDependencies": {\n "@vitejs/plugin-vue": "^5.2.1",\n "typescript": "~5.7.3",\n "vite": "^6.0.5",\n "vue-tsc": "^2.2.0"\n }\n}\n'); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { resolve } from 'path'\n\nexport default defineConfig({\n plugins: [vue()],\n resolve: { alias: { '@': resolve(__dirname,'src') } }\n})\n"); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]}\n'); zip.file(folder+"tsconfig.app.json",'{\n "compilerOptions":{\n "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"],\n "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true,\n "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue",\n "strict":true,"paths":{"@/*":["./src/*"]}\n },\n "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"]\n}\n'); zip.file(folder+"env.d.ts","/// \n"); zip.file(folder+"index.html","\n\n\n \n \n "+slugTitle(pn)+"\n\n\n
\n \n\n\n"); var hasMain=Object.keys(extracted).some(function(k){return k==="src/main.ts"||k==="main.ts";}); if(!hasMain) zip.file(folder+"src/main.ts","import { createApp } from 'vue'\nimport { createPinia } from 'pinia'\nimport App from './App.vue'\nimport './assets/main.css'\n\nconst app = createApp(App)\napp.use(createPinia())\napp.mount('#app')\n"); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue","\n\n\n\n\n"); zip.file(folder+"src/assets/main.css","*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#fff;color:#213547}\n"); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/views/.gitkeep",""); zip.file(folder+"src/stores/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\nOpen in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Angular (v19 standalone) --- */ function buildAngular(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var sel=pn.replace(/_/g,"-"); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "scripts": {\n "ng": "ng",\n "start": "ng serve",\n "build": "ng build",\n "test": "ng test"\n },\n "dependencies": {\n "@angular/animations": "^19.0.0",\n "@angular/common": "^19.0.0",\n "@angular/compiler": "^19.0.0",\n "@angular/core": "^19.0.0",\n "@angular/forms": "^19.0.0",\n "@angular/platform-browser": "^19.0.0",\n "@angular/platform-browser-dynamic": "^19.0.0",\n "@angular/router": "^19.0.0",\n "rxjs": "~7.8.0",\n "tslib": "^2.3.0",\n "zone.js": "~0.15.0"\n },\n "devDependencies": {\n "@angular-devkit/build-angular": "^19.0.0",\n "@angular/cli": "^19.0.0",\n "@angular/compiler-cli": "^19.0.0",\n "typescript": "~5.6.0"\n }\n}\n'); zip.file(folder+"angular.json",'{\n "$schema": "./node_modules/@angular/cli/lib/config/schema.json",\n "version": 1,\n "newProjectRoot": "projects",\n "projects": {\n "'+pn+'": {\n "projectType": "application",\n "root": "",\n "sourceRoot": "src",\n "prefix": "app",\n "architect": {\n "build": {\n "builder": "@angular-devkit/build-angular:application",\n "options": {\n "outputPath": "dist/'+pn+'",\n "index": "src/index.html",\n "browser": "src/main.ts",\n "tsConfig": "tsconfig.app.json",\n "styles": ["src/styles.css"],\n "scripts": []\n }\n },\n "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"}\n }\n }\n }\n}\n'); zip.file(folder+"tsconfig.json",'{\n "compileOnSave": false,\n "compilerOptions": {"baseUrl":"./","outDir":"./dist/out-tsc","forceConsistentCasingInFileNames":true,"strict":true,"noImplicitOverride":true,"noPropertyAccessFromIndexSignature":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true,"paths":{"@/*":["src/*"]},"skipLibCheck":true,"esModuleInterop":true,"sourceMap":true,"declaration":false,"experimentalDecorators":true,"moduleResolution":"bundler","importHelpers":true,"target":"ES2022","module":"ES2022","useDefineForClassFields":false,"lib":["ES2022","dom"]},\n "references":[{"path":"./tsconfig.app.json"}]\n}\n'); zip.file(folder+"tsconfig.app.json",'{\n "extends":"./tsconfig.json",\n "compilerOptions":{"outDir":"./dist/out-tsc","types":[]},\n "files":["src/main.ts"],\n "include":["src/**/*.d.ts"]\n}\n'); zip.file(folder+"src/index.html","\n\n\n \n "+slugTitle(pn)+"\n \n \n \n\n\n \n\n\n"); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser';\nimport { appConfig } from './app/app.config';\nimport { AppComponent } from './app/app.component';\n\nbootstrapApplication(AppComponent, appConfig)\n .catch(err => console.error(err));\n"); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; }\nbody { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; }\n"); var hasComp=Object.keys(extracted).some(function(k){return k.indexOf("app.component")>=0;}); if(!hasComp){ zip.file(folder+"src/app/app.component.ts","import { Component } from '@angular/core';\nimport { RouterOutlet } from '@angular/router';\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [RouterOutlet],\n templateUrl: './app.component.html',\n styleUrl: './app.component.css'\n})\nexport class AppComponent {\n title = '"+pn+"';\n}\n"); zip.file(folder+"src/app/app.component.html","
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n \n
\n"); zip.file(folder+"src/app/app.component.css",".app-header{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;gap:16px}h1{font-size:2.5rem;font-weight:700;color:#6366f1}\n"); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\nimport { provideRouter } from '@angular/router';\nimport { routes } from './app.routes';\n\nexport const appConfig: ApplicationConfig = {\n providers: [\n provideZoneChangeDetection({ eventCoalescing: true }),\n provideRouter(routes)\n ]\n};\n"); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router';\n\nexport const routes: Routes = [];\n"); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nng serve\n# or: npm start\n\`\`\`\n\n## Build\n\`\`\`bash\nng build\n\`\`\`\n\nOpen in VS Code with Angular Language Service extension.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n.angular/\n"); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var reqMap={"numpy":"numpy","pandas":"pandas","sklearn":"scikit-learn","tensorflow":"tensorflow","torch":"torch","flask":"flask","fastapi":"fastapi","uvicorn":"uvicorn","requests":"requests","sqlalchemy":"sqlalchemy","pydantic":"pydantic","dotenv":"python-dotenv","PIL":"Pillow","cv2":"opencv-python","matplotlib":"matplotlib","seaborn":"seaborn","scipy":"scipy"}; var reqs=[]; Object.keys(reqMap).forEach(function(k){if(src.indexOf("import "+k)>=0||src.indexOf("from "+k)>=0)reqs.push(reqMap[k]);}); var reqsTxt=reqs.length?reqs.join("\n"):"# add dependencies here\n"; zip.file(folder+"main.py",src||"# "+title+"\n# Generated by PantheraHive BOS\n\nprint(title+\" loaded\")\n"); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\npython3 -m venv .venv\nsource .venv/bin/activate\npip install -r requirements.txt\n\`\`\`\n\n## Run\n\`\`\`bash\npython main.py\n\`\`\`\n"); zip.file(folder+".gitignore",".venv/\n__pycache__/\n*.pyc\n.env\n.DS_Store\n"); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var depMap={"mongoose":"^8.0.0","dotenv":"^16.4.5","axios":"^1.7.9","cors":"^2.8.5","bcryptjs":"^2.4.3","jsonwebtoken":"^9.0.2","socket.io":"^4.7.4","uuid":"^9.0.1","zod":"^3.22.4","express":"^4.18.2"}; var deps={}; Object.keys(depMap).forEach(function(k){if(src.indexOf(k)>=0)deps[k]=depMap[k];}); if(!deps["express"])deps["express"]="^4.18.2"; var pkgJson=JSON.stringify({"name":pn,"version":"1.0.0","main":"src/index.js","scripts":{"start":"node src/index.js","dev":"nodemon src/index.js"},"dependencies":deps,"devDependencies":{"nodemon":"^3.0.3"}},null,2)+"\n"; zip.file(folder+"package.json",pkgJson); var fallback="const express=require(\"express\");\nconst app=express();\napp.use(express.json());\n\napp.get(\"/\",(req,res)=>{\n res.json({message:\""+title+" API\"});\n});\n\nconst PORT=process.env.PORT||3000;\napp.listen(PORT,()=>console.log(\"Server on port \"+PORT));\n"; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000\n"); zip.file(folder+".gitignore","node_modules/\n.env\n.DS_Store\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\n\`\`\`\n\n## Run\n\`\`\`bash\nnpm run dev\n\`\`\`\n"); } /* --- Vanilla HTML --- */ function buildVanillaHtml(zip,folder,app,code){ var title=slugTitle(app); var isFullDoc=code.trim().toLowerCase().indexOf("=0||code.trim().toLowerCase().indexOf("=0; var indexHtml=isFullDoc?code:"\n\n\n\n\n"+title+"\n\n\n\n"+code+"\n\n\n\n"; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */\n*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e}\n"); zip.file(folder+"script.js","/* "+title+" — scripts */\n"); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Open\nDouble-click \`index.html\` in your browser.\n\nOr serve locally:\n\`\`\`bash\nnpx serve .\n# or\npython3 -m http.server 3000\n\`\`\`\n"); zip.file(folder+".gitignore",".DS_Store\nnode_modules/\n.env\n"); } /* ===== MAIN ===== */ var sc=document.createElement("script"); sc.src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"; sc.onerror=function(){ if(lbl)lbl.textContent="Download ZIP"; alert("JSZip load failed — check connection."); }; sc.onload=function(){ var zip=new JSZip(); var base=(_phFname||"output").replace(/\.[^.]+$/,""); var app=base.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; var folder=app+"/"; var vc=document.getElementById("panel-content"); var panelTxt=vc?(vc.innerText||vc.textContent||""):""; var lang=detectLang(_phCode,panelTxt); if(_phIsHtml){ buildVanillaHtml(zip,folder,app,_phCode); } else if(lang==="flutter"){ buildFlutter(zip,folder,app,_phCode,panelTxt); } else if(lang==="react-native"){ buildReactNative(zip,folder,app,_phCode,panelTxt); } else if(lang==="swift"){ buildSwift(zip,folder,app,_phCode,panelTxt); } else if(lang==="kotlin"){ buildKotlin(zip,folder,app,_phCode,panelTxt); } else if(lang==="react"){ buildReact(zip,folder,app,_phCode,panelTxt); } else if(lang==="vue"){ buildVue(zip,folder,app,_phCode,panelTxt); } else if(lang==="angular"){ buildAngular(zip,folder,app,_phCode,panelTxt); } else if(lang==="python"){ buildPython(zip,folder,app,_phCode); } else if(lang==="node"){ buildNode(zip,folder,app,_phCode); } else { /* Document/content workflow */ var title=app.replace(/_/g," "); var md=_phAll||_phCode||panelTxt||"No content"; zip.file(folder+app+".md",md); var h=""+title+""; h+="

"+title+"

"; var hc=md.replace(/&/g,"&").replace(//g,">"); hc=hc.replace(/^### (.+)$/gm,"

$1

"); hc=hc.replace(/^## (.+)$/gm,"

$1

"); hc=hc.replace(/^# (.+)$/gm,"

$1

"); hc=hc.replace(/\*\*(.+?)\*\*/g,"$1"); hc=hc.replace(/\n{2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\nFiles:\n- "+app+".md (Markdown)\n- "+app+".html (styled HTML)\n"); } zip.generateAsync({type:"blob"}).then(function(blob){ var a=document.createElement("a"); a.href=URL.createObjectURL(blob); a.download=app+".zip"; a.click(); URL.revokeObjectURL(a.href); if(lbl)lbl.textContent="Download ZIP"; }); }; document.head.appendChild(sc); } function phShare(){navigator.clipboard.writeText(window.location.href).then(function(){var el=document.getElementById("ph-share-lbl");if(el){el.textContent="Link copied!";setTimeout(function(){el.textContent="Copy share link";},2500);}});}function phEmbed(){var runId=window.location.pathname.split("/").pop().replace(".html","");var embedUrl="https://pantherahive.com/embed/"+runId;var code='';navigator.clipboard.writeText(code).then(function(){var el=document.getElementById("ph-embed-lbl");if(el){el.textContent="Embed code copied!";setTimeout(function(){el.textContent="Get Embed Code";},2500);}});}