Microservice Scaffolder
Run ID: 69cb056158b35c7ea758c1fd2026-03-30Development
PantheraHive BOS
BOS Dashboard

This document provides the complete, detailed, and production-ready code scaffold for a new microservice. This output is designed to be a foundational template, ready for immediate development and deployment.


Microservice Scaffolder: Code Generation Deliverable

This deliverable provides a comprehensive scaffold for a new microservice, encompassing core application logic, API definitions, database interactions, Dockerization, testing infrastructure, CI/CD pipeline configuration, and basic deployment scripts.

1. Technology Stack Chosen

To provide a robust and widely applicable example, we have chosen the following technology stack:

This stack offers excellent developer experience, performance, and scalability for modern microservices.

2. Project Structure

The generated microservice follows a standard and organized project structure:

text • 2,560 chars
.
├── .github/                       # GitHub specific configurations
│   └── workflows/                 # CI/CD workflows
│       └── main.yml               # Main CI/CD pipeline for build, test, deploy
├── app/                           # Main application source code
│   ├── api/                       # API endpoints definitions
│   │   └── v1/
│   │       └── endpoints.py       # API routes for version 1
│   ├── crud/                      # Create, Read, Update, Delete operations
│   │   └── __init__.py
│   │   └── item.py                # CRUD operations for Item model
│   ├── core/                      # Core application utilities and configurations
│   │   ├── config.py              # Application settings
│   │   ├── database.py            # Database connection and session management
│   │   └── security.py            # (Placeholder for security utilities)
│   ├── db/                        # Database related scripts and migrations
│   │   └── alembic/               # Alembic migration environment
│   │       └── versions/          # Migration scripts
│   │       └── env.py
│   │       └── script.py.mako
│   │   └── alembic.ini            # Alembic configuration
│   │   └── base_class.py          # Base for SQLModel models
│   ├── models/                    # Database models
│   │   └── item.py                # Item model definition
│   │   └── __init__.py
│   ├── schemas/                   # Pydantic schemas for request/response validation
│   │   └── item.py                # Item schemas (create, update, read)
│   │   └── __init__.py
│   ├── services/                  # Business logic services
│   │   └── item_service.py        # Business logic for items
│   │   └── __init__.py
│   └── main.py                    # FastAPI application entry point
├── tests/                         # Unit and integration tests
│   └── conftest.py                # Pytest fixtures
│   └── test_api_items.py          # Tests for Item API endpoints
├── .dockerignore                  # Files/directories to ignore when building Docker image
├── .env.example                   # Example environment variables
├── Dockerfile                     # Docker image definition
├── docker-compose.yml             # Docker Compose for local development environment
├── Makefile                       # Common development commands
├── pyproject.toml                 # Poetry/PEP 621 project configuration
├── README.md                      # Project documentation
├── requirements.txt               # Python dependencies (generated from pyproject.toml)
Sandboxed live preview

Step 1 of 3: Microservice Architecture Plan

Workflow Description: Generate a complete microservice with Docker setup, API routes, database models, tests, CI/CD pipeline config, and deployment scripts.

Current Step: gemini → plan_architecture

This document outlines the comprehensive architectural plan for the microservice to be scaffolded. This plan will serve as the blueprint for subsequent steps, ensuring a robust, scalable, maintainable, and deployable service.


1. Project Overview & Guiding Principles

Project Goal: To establish a foundational architecture for a new microservice, enabling rapid development, consistent quality, and streamlined deployment.

Architectural Principles:

  • Modularity: Clear separation of concerns for easy maintenance and independent evolution.
  • Scalability: Designed to handle increasing load horizontally.
  • Resilience: Ability to recover gracefully from failures.
  • Observability: Built-in mechanisms for monitoring, logging, and tracing.
  • Security: Adherence to best practices for data protection and access control.
  • Automation: Maximizing automation in development, testing, and deployment processes.
  • Cloud-Native: Leveraging cloud capabilities for efficiency and elasticity.

2. Core Microservice Architecture

This section details the internal structure and key components of the microservice.

2.1. Technology Stack Recommendation

To provide a concrete and modern scaffold, we recommend the following default stack. This can be customized in subsequent steps.

  • Language & Framework: Python 3.10+ with FastAPI

* Rationale: High performance (ASGI), excellent developer experience, automatic OpenAPI (Swagger) documentation generation, strong type hinting support.

  • Asynchronous Tasks: Celery (if background tasks are required)
  • Database: PostgreSQL

* Rationale: Robust, open-source, ACID-compliant relational database, widely supported.

  • ORM/ODM: SQLAlchemy with Alembic for migrations

* Rationale: Powerful and flexible ORM for Python, robust migration tool.

  • Dependency Management: Poetry or PDM

* Rationale: Modern dependency managers for Python, offering isolated environments and reproducible builds.

2.2. API Design & Structure

  • API Style: RESTful API principles (stateless, resource-oriented).
  • Data Format: JSON for request and response bodies.
  • Versioning: URI-based versioning (e.g., /api/v1/resource).
  • Endpoint Structure:

* /api/v1/[resource]: Collection resources (e.g., /api/v1/users).

* /api/v1/[resource]/{id}: Specific resource instance (e.g., /api/v1/users/123).

  • HTTP Methods:

* GET: Retrieve resources.

* POST: Create new resources.

* PUT/PATCH: Update existing resources.

* DELETE: Remove resources.

  • Error Handling: Standardized JSON error responses with HTTP status codes (e.g., 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Internal Server Error).
  • Documentation: Automatic OpenAPI/Swagger UI generation via FastAPI.

2.3. Data Persistence

  • Database: PostgreSQL instance.
  • Connection Management: SQLAlchemy connection pool managed by the application.
  • Migrations: Alembic for managing database schema changes, ensuring smooth upgrades and downgrades.
  • Data Models: Python classes mapped to database tables using SQLAlchemy ORM.
  • Transactions: Proper transaction management to ensure data integrity.

2.4. Security Considerations

  • Authentication: JWT (JSON Web Tokens) for stateless authentication.

* Flow: User authenticates with an identity provider (or directly with the service), receives a JWT, and includes it in subsequent requests via the Authorization: Bearer <token> header.

  • Authorization: Role-Based Access Control (RBAC) or Attribute-Based Access Control (ABAC) implemented via middleware/decorators.
  • Input Validation: Strict validation of all incoming API requests using Pydantic models (integrated with FastAPI).
  • Secrets Management: Environment variables for development, cloud-native secret management services (e.g., AWS Secrets Manager, GCP Secret Manager) for production.
  • HTTPS: Enforce SSL/TLS for all communication.
  • CORS: Configurable Cross-Origin Resource Sharing policies.

2.5. Observability

  • Logging: Structured logging (JSON format) using Python's logging module, directed to stdout/stderr for collection by container orchestration logs.

* Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.

  • Monitoring:

* Metrics: Prometheus-compatible metrics exposed via an /metrics endpoint (e.g., request count, latency, error rates, resource utilization).

* Health Checks: /health and /ready endpoints for liveness and readiness probes in container orchestration.

  • Tracing: OpenTelemetry integration for distributed tracing across microservices (optional, but recommended for complex systems).

2.6. Configuration Management

  • Environment Variables: Primary mechanism for external configuration (database URLs, API keys, service ports, etc.).
  • Settings Class: Pydantic BaseSettings for loading and validating environment variables into a structured configuration object.
  • Defaults: Sensible default values where possible, overridden by environment variables.

3. Development & Operations (DevOps) Architecture

This section details the infrastructure, build, test, and deployment strategies.

3.1. Containerization

  • Dockerfile: Optimized Dockerfile for building a lean production-ready container image.

* Multi-stage builds for smaller image sizes and improved security.

* Utilizes a lightweight base image (e.g., Alpine Linux).

  • Docker Compose: docker-compose.yml for local development setup, including:

* The microservice itself.

* A PostgreSQL database container.

* (Optional) A local Redis instance for caching/Celery broker.

* (Optional) Adminer/pgAdmin for database management.

3.2. CI/CD Pipeline

A robust CI/CD pipeline ensures automated testing, building, and deployment.

  • Platform: GitHub Actions (or GitLab CI/CD, AWS CodePipeline, etc.)
  • Trigger: On push to main branch, and pull requests to main.
  • Stages:

1. Build: Install dependencies, compile (if applicable), lint, format.

2. Test: Run unit, integration, and (optionally) end-to-end tests.

3. Security Scan: Static Application Security Testing (SAST) tools (e.g., Bandit for Python).

4. Container Build & Push: Build Docker image, tag with commit SHA/version, push to Container Registry (e.g., Docker Hub, AWS ECR, GCP Container Registry).

5. Deployment (Optional for CI, part of CD): Trigger deployment to staging/production environments.

3.3. Testing Strategy

  • Unit Tests: Focus on individual functions, methods, and components in isolation.

* Framework: pytest with pytest-asyncio for asynchronous code.

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

  • Integration Tests: Verify interactions between different components (e.g., API endpoints with database).

* Framework: pytest using FastAPI's TestClient.

* Database: Use a dedicated test database or in-memory database for faster execution.

  • End-to-End (E2E) Tests (Optional but Recommended): Simulate user scenarios against the deployed service.

* Framework: Playwright, Cypress, or similar.

  • Linting & Formatting: Enforce code style and catch common errors.

* Tools: Black, Flake8, isort.

3.4. Deployment Strategy

  • Target Environment: Cloud-native container orchestration.

* Recommended: Kubernetes (EKS/GKE/AKS) or AWS ECS/Fargate.

  • Deployment Method:

* Kubernetes: Helm charts for packaging and deploying the microservice.

* ECS/Fargate: AWS CloudFormation or Terraform for infrastructure as code, defining task definitions and services.

  • Infrastructure as Code (IaC): Terraform or CloudFormation for provisioning and managing cloud resources (database, load balancers, networking, etc.).
  • Environments:

* Development: Local Docker Compose.

* Staging/UAT: A pre-production environment for testing and user acceptance.

* Production: The live environment.

  • Rollback Strategy: Automated rollback to previous stable version in case of deployment failures.

4. Deliverables for Next Steps

This architectural plan provides the foundation for the following deliverables in the subsequent scaffolding steps:

  • Project Structure: Directory layout for source code, tests, and configurations.
  • Core Application Code: FastAPI application setup, basic routes, Pydantic models, SQLAlchemy models.
  • Database Migrations: Initial Alembic setup and a sample migration.
  • Docker Files: Dockerfile and docker-compose.yml.
  • CI/CD Configuration: GitHub Actions workflow file.
  • Testing Suite: Basic unit and integration tests.
  • Readme & Documentation: Initial README.md with setup instructions and API documentation via OpenAPI.
  • IaC Templates: Placeholder templates for cloud deployment (e.g., basic Kubernetes manifest or ECS task definition).

5. Actionable Recommendations

  • Choose a Cloud Provider: Decide on AWS, GCP, or Azure early to tailor IaC and deployment scripts.
  • Define Initial Data Models: Provide specific entities and their attributes to generate the first set of database models and API endpoints.
  • Security Audit: Conduct regular security audits and vulnerability scans throughout the development lifecycle.

Clarification Regarding "Study Plan" Request

It appears your request included a query for a "detailed study plan." Please note that the current workflow, "Microservice Scaffolder," is designed to generate microservice components and related infrastructure, not educational study plans.

For this current step, I have focused entirely on delivering the comprehensive microservice architecture plan as requested. If you require a study plan, please initiate a new, separate workflow specifically for that purpose.

python

app/crud/item.py

from typing import List, Optional

from sqlmodel import Session, select

from app.models.item import Item

from app.schemas.item import ItemCreate, ItemUpdate

def create_item(session: Session, item_in: ItemCreate) -> Item:

"""

Creates a new item in the database.

"""

item = Item.model_validate(item_in) # Converts Pydantic schema to SQLModel instance

session.add(item)

session.commit()

session.refresh(item) # Refresh to get auto-generated ID and timestamps

return item

def get_item(session: Session, item_id: int) -> Optional[Item]:

"""

Retrieves a single item by its ID.

"""

return session.get(Item, item_id)

def get_items(session: Session, skip: int = 0, limit: int = 100) -> List[Item]:

"""

Retrieves a list of items from the database.

"""

statement = select(Item).offset(skip).limit(limit)

return session.exec(statement).all()

def update_item(session: Session, item_id: int, item_in: ItemUpdate) -> Optional[Item]:

"""

Updates an existing item in the database.

"""

item = session.get(Item, item_id)

if not item:

return None

# Update fields from the input schema

# Use .model_dump(exclude_unset=True) to only update fields that were provided

update_data = item_in.model_dump(exclude_unset=True)

for key, value

gemini Output

Microservice Scaffolding: Professional Output & Documentation

This document provides a comprehensive overview and detailed documentation for the newly generated microservice. This output is the result of the "Microservice Scaffolder" workflow, successfully completing the review_and_document step.

The generated microservice is designed for rapid development, robust operation, and seamless integration into a modern cloud-native environment. It includes a complete set of components, from API routes and database models to Dockerization, testing, and CI/CD pipeline configurations.


1. Generated Microservice Overview

Your new microservice is built with a modern, asynchronous Python stack, optimized for performance and developer experience.

Technology Stack:

  • Language: Python 3.9+
  • Web Framework: FastAPI (for high performance and automatic API documentation)
  • Database: PostgreSQL (configured for local development via Docker Compose)
  • ORM: SQLAlchemy with Alembic for database migrations
  • Data Validation: Pydantic
  • Testing: Pytest
  • Containerization: Docker
  • CI/CD: GitHub Actions (example configuration provided)

Key Features:

  • RESTful API: Clearly defined routes with Pydantic for request/response validation.
  • Database Integration: Robust ORM with migration capabilities.
  • Dockerized Environment: Ready for local development and production deployment.
  • Comprehensive Testing: Unit and integration tests structure.
  • Automated Workflows: CI/CD pipeline configurations for build, test, and linting.
  • Deployment Readiness: Basic deployment scripts and Kubernetes manifests for common cloud environments.
  • Built-in API Documentation: Swagger UI and ReDoc automatically generated by FastAPI.

2. Project Structure Breakdown

The scaffolded project follows a modular and organized structure to enhance readability, maintainability, and scalability.


.
├── .github/                     # GitHub Actions CI/CD workflows
│   └── workflows/
│       ├── ci.yml               # Continuous Integration (build, test, lint)
│       └── cd.yml               # Continuous Deployment (placeholder)
├── deploy/                      # Deployment configurations and scripts
│   ├── kubernetes/              # Kubernetes manifests
│   │   ├── deployment.yaml
│   │   └── service.yaml
│   └── scripts/                 # Utility deployment scripts
│       └── deploy_to_cloud.sh   # Example cloud deployment script
├── src/                         # Core microservice source code
│   ├── api/                     # API routes and endpoint definitions
│   │   └── v1/
│   │       ├── __init__.py
│   │       ├── items.py         # Example CRUD for 'items'
│   │       └── users.py         # Example CRUD for 'users'
│   ├── core/                    # Core configurations and utilities
│   │   ├── config.py            # Application settings
│   │   └── security.py          # Security utilities (e.g., password hashing)
│   ├── database/                # Database connection and ORM setup
│   │   ├── migrations/          # Alembic migration scripts
│   │   │   ├── versions/        # Generated migration files
│   │   │   └── env.py
│   │   ├��─ __init__.py
│   │   ├── base.py              # Base for SQLAlchemy declarative models
│   │   └── session.py           # Database session management
│   ├── models/                  # SQLAlchemy ORM models
│   │   ├── __init__.py
│   │   ├── item.py
│   │   └── user.py
│   ├── schemas/                 # Pydantic schemas for request/response validation
│   │   ├── __init__.py
│   │   ├── item.py
│   │   └── user.py
│   ├── services/                # Business logic and service layer
│   │   ├── __init__.py
│   │   ├── item.py
│   │   └── user.py
│   └── main.py                  # FastAPI application entry point
├── tests/                       # Unit and integration tests
│   ├── conftest.py              # Pytest fixtures
│   ├── unit/
│   │   ├── test_models.py
│   │   └── test_services.py
│   └── integration/
│       └── test_api.py
├── .dockerignore                # Files to ignore when building Docker image
├── .env.example                 # Example environment variables
├── .gitignore                   # Git ignore file
├── Dockerfile                   # Docker image definition
├── docker-compose.yml           # Local development environment with Docker
├── README.md                    # Project README
├── requirements.txt             # Python dependencies
└── alembic.ini                  # Alembic configuration for migrations

3. Detailed Component Documentation

3.1. Core Application (src/)

  • src/main.py: The main entry point for your FastAPI application. It initializes the FastAPI app, includes API routers, and sets up event handlers (e.g., database connection lifecycle).

    # Example src/main.py snippet
    from fastapi import FastAPI
    from src.api.v1 import users, items
    from src.core.config import settings
    from src.database.session import engine, Base

    app = FastAPI(
        title=settings.PROJECT_NAME,
        version=settings.API_VERSION,
        openapi_url=f"{settings.API_V1_STR}/openapi.json"
    )

    # Include API routers
    app.include_router(users.router, prefix=settings.API_V1_STR, tags=["users"])
    app.include_router(items.router, prefix=settings.API_V1_STR, tags=["items"])

    @app.on_event("startup")
    async def startup_event():
        # Optional: Create all database tables if they don't exist
        # Base.metadata.create_all(bind=engine)
        print("Application startup")

    @app.on_event("shutdown")
    async def shutdown_event():
        print("Application shutdown")

    # Access API docs at /docs or /redoc
  • src/api/v1/: Contains endpoint definitions for version 1 of your API. Each file (e.g., items.py, users.py) defines a APIRouter with specific routes, dependencies, and response models.

    # Example src/api/v1/users.py snippet
    from fastapi import APIRouter, Depends, HTTPException, status
    from sqlalchemy.orm import Session
    from typing import List

    from src.schemas import user as user_schemas
    from src.services import user as user_services
    from src.database.session import get_db

    router = APIRouter()

    @router.post("/", response_model=user_schemas.User, status_code=status.HTTP_201_CREATED)
    def create_user(user: user_schemas.UserCreate, db: Session = Depends(get_db)):
        db_user = user_services.get_user_by_email(db, email=user.email)
        if db_user:
            raise HTTPException(status_code=400, detail="Email already registered")
        return user_services.create_user(db=db, user=user)

    @router.get("/", response_model=List[user_schemas.User])
    def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
        users = user_services.get_users(db, skip=skip, limit=limit)
        return users
  • src/models/: Defines your SQLAlchemy ORM models, representing database tables.

    # Example src/models/user.py snippet
    from sqlalchemy import Column, Integer, String, Boolean
    from sqlalchemy.orm import relationship

    from src.database.base import Base

    class User(Base):
        __tablename__ = "users"

        id = Column(Integer, primary_key=True, index=True)
        email = Column(String, unique=True, index=True, nullable=False)
        hashed_password = Column(String, nullable=False)
        is_active = Column(Boolean, default=True)

        items = relationship("Item", back_populates="owner")
  • src/schemas/: Contains Pydantic models used for validating request bodies, structuring response data, and defining data shapes throughout the application.

    # Example src/schemas/user.py snippet
    from pydantic import BaseModel, EmailStr
    from typing import List, Optional

    class UserBase(BaseModel):
        email: EmailStr

    class UserCreate(UserBase):
        password: str

    class User(UserBase):
        id: int
        is_active: bool
        # items: List[Item] = [] # Uncomment if you want to embed items in user response

        class Config:
            orm_mode = True # Enable ORM mode for SQLAlchemy integration
  • src/services/: Encapsulates the business logic, interacting with the database through the ORM models. This separation keeps your API routes clean and focused on request/response handling.

    # Example src/services/user.py snippet
    from sqlalchemy.orm import Session
    from src.models import user as user_model
    from src.schemas import user as user_schemas
    from src.core.security import get_password_hash

    def get_user(db: Session, user_id: int):
        return db.query(user_model.User).filter(user_model.User.id == user_id).first()

    def get_user_by_email(db: Session, email: str):
        return db.query(user_model.User).filter(user_model.User.email == email).first()

    def get_users(db: Session, skip: int = 0, limit: int = 100):
        return db.query(user_model.User).offset(skip).limit(limit).all()

    def create_user(db: Session, user: user_schemas.UserCreate):
        hashed_password = get_password_hash(user.password)
        db_user = user_model.User(email=user.email, hashed_password=hashed_password)
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
        return db_user
  • src/core/config.py: Manages application settings, typically loaded from environment variables.

    # Example src/core/config.py snippet
    from pydantic import BaseSettings, Field

    class Settings(BaseSettings):
        PROJECT_NAME: str = "MyMicroservice"
        API_VERSION: str = "0.1.0"
        API_V1_STR: str = "/api/v1"
        DATABASE_URL: str = Field(..., env="DATABASE_URL")
        SECRET_KEY: str = Field(..., env="SECRET_KEY")
        ALGORITHM: str = "HS256"
        ACCESS_TOKEN_EXPIRE_MINUTES: int = 30

        class Config:
            env_file = ".env"
            env_file_encoding = 'utf-8'

    settings = Settings()

3.2. Database Setup & Migrations (src/database/)

  • src/database/session.py: Configures the SQLAlchemy engine and provides a dependency for obtaining a database session within your API routes.
  • src/database/base.py: Defines the Base class for your SQLAlchemy declarative models.
  • src/database/migrations/: This directory is managed by Alembic.

*`alembic.ini

microservice_scaffolder.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);}});}