Microservice Scaffolder
Run ID: 69cb67e261b1021a29a88be32026-03-31Development
PantheraHive BOS
BOS Dashboard

This deliverable outlines the complete microservice scaffolding generated for your project, focusing on a robust, scalable, and maintainable architecture. We have chosen Python with FastAPI as the core framework, leveraging its modern asynchronous capabilities, built-in data validation (Pydantic), and automatic OpenAPI documentation. PostgreSQL is selected as the database, integrated via SQLAlchemy 2.0+ for asynchronous operations.


Microservice Scaffolding Output

1. Introduction

We have successfully generated a comprehensive microservice, complete with a structured project layout, API endpoints, database models, CRUD operations, Docker setup for containerization, a robust testing suite, CI/CD pipeline configuration, and example deployment scripts. This scaffolding provides a solid foundation for developing your specific business logic.

Chosen Stack:

2. Project Overview and Structure

The generated microservice follows a modular and layered architecture, promoting separation of concerns and ease of maintenance.

text • 2,177 chars
.
├── .github/                       # GitHub Actions CI/CD workflows
│   └── workflows/
│       └── main.yml               # CI/CD pipeline definition
├── app/                           # Main application source code
│   ├── api/                       # API endpoints definitions
│   │   └── v1/
│   │       ├── endpoints/
│   │       │   └── items.py       # Specific API endpoints for 'Item' resource
│   │       └── routers.py         # Aggregation of API routers
│   ├── crud/                      # Create, Read, Update, Delete operations
│   │   └── item.py                # CRUD functions for 'Item' model
│   ├── core/                      # Core configurations and utilities
│   │   └── config.py              # Application settings and environment variables
│   ├── database.py                # Database connection and session management
│   ├── models/                    # Database (SQLAlchemy) and Pydantic models
│   │   ├── __init__.py
│   │   ├── item.py                # Pydantic models for request/response
│   │   └── sql.py                 # SQLAlchemy ORM models for database tables
│   └── main.py                    # FastAPI application entry point
├── tests/                         # Unit and integration tests
│   ├── __init__.py
│   ├── conftest.py                # Pytest fixtures for testing
│   ├── test_api.py                # API integration tests
│   └── test_main.py               # Basic application tests
├── deploy/                        # Deployment scripts and configurations
│   ├── deploy.sh                  # Generic shell script for server deployment
│   └── kubernetes/
│       ├── deployment.yaml        # Kubernetes Deployment manifest
│       └── service.yaml           # Kubernetes Service manifest
├── Dockerfile                     # Docker build instructions
├── docker-compose.yml             # Docker Compose for local development (app + db)
├── .env.example                   # Example environment variables
├── requirements.txt               # Python dependencies
├── README.md                      # Project documentation and setup instructions
└── .gitignore                     # Files/directories to ignore in Git
Sandboxed live preview

This document outlines the architectural plan for your new microservice, providing a foundational blueprint for its development. This plan addresses the core components, technology stack, infrastructure considerations, and best practices to ensure a robust, scalable, and maintainable service.

Note: The request for a "detailed study plan" appears to be a separate, unrelated request. This deliverable focuses solely on the architectural plan for the microservice as per the "Microservice Scaffolder" workflow step description.


Microservice Architecture Plan: Core Blueprint

1. Introduction & Purpose

The objective of this plan_architecture step is to define the high-level design and technology stack for the microservice. This blueprint will guide the subsequent development phases, including scaffolding generation, implementation, testing, and deployment, ensuring consistency, scalability, and adherence to modern best practices.

2. Core Microservice Design

This section details the internal structure and external interfaces of the microservice.

2.1. Service Definition

  • Primary Function: To be defined based on the specific business domain (e.g., "Manages user profiles and authentication," "Processes product orders," "Handles inventory management"). For this general plan, we assume a standard CRUD (Create, Read, Update, Delete) microservice with business logic.
  • API Interface:

* Protocol: RESTful API using JSON over HTTP/S. This offers broad compatibility and ease of use.

* Authentication: JWT (JSON Web Tokens) for stateless authentication. This assumes an external Identity Provider (IdP) service (e.g., Auth0, Keycloak, or another microservice) responsible for issuing and validating tokens.

* Authorization: Role-Based Access Control (RBAC) implemented via middleware, leveraging claims within the JWT to determine user permissions.

* API Versioning: URI versioning (e.g., /v1/resource) to manage API evolution gracefully.

  • Internal Logic: Structured into layers:

* Controller/Handler Layer: Handles incoming HTTP requests, validates input, delegates to service layer.

* Service/Business Logic Layer: Contains the core business rules and orchestrates interactions with the data layer.

* Repository/Data Access Layer: Abstracts database interactions, providing a clean interface for the service layer.

* Domain Layer: Defines core entities and value objects.

2.2. Technology Stack Recommendation

Choosing a modern, efficient, and well-supported stack is crucial.

  • Backend Language/Framework: Python 3.10+ with FastAPI.

* Justification: FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. It offers automatic interactive API documentation (Swagger UI, ReDoc), excellent developer experience, and performance comparable to Node.js and Go for I/O-bound tasks.

  • Database: PostgreSQL.

* Justification: A powerful, open-source, object-relational database system known for its reliability, feature robustness, and strong support for complex queries and data integrity. It's suitable for a wide range of microservice data storage needs.

  • ORM (Object-Relational Mapper): SQLAlchemy.

* Justification: A comprehensive and powerful ORM for Python, providing a flexible and expressive way to interact with relational databases. It supports both ORM and SQL Expression Language patterns.

  • Messaging (for Inter-Service Communication): RabbitMQ.

* Justification: A popular open-source message broker that implements the Advanced Message Queuing Protocol (AMQP). It provides reliable asynchronous communication, enabling loose coupling between microservices, supporting event-driven architectures, and handling background tasks.

2.3. Data Model Overview

  • Schema Design: Each microservice should own its data schema. Initial design will involve identifying core entities (e.g., User, Product, Order, Transaction) and their relationships.
  • Migrations: Database schema changes will be managed using migration tools (e.g., Alembic for SQLAlchemy) to ensure version control and smooth deployments.

3. Infrastructure & DevOps Blueprint

This section outlines the infrastructure and tools required to build, deploy, and operate the microservice.

3.1. Containerization (Docker)

  • Dockerfile: A lean and optimized Dockerfile will be created for the microservice, ensuring a consistent build environment and efficient image size. It will include dependencies, application code, and entrypoint configuration.
  • Docker Compose: Used for local development and testing. A docker-compose.yml file will orchestrate the microservice, its database (PostgreSQL), and message queue (RabbitMQ) for a complete local environment.

3.2. CI/CD Pipeline

A robust Continuous Integration/Continuous Deployment (CI/CD) pipeline is essential for automated testing and deployment.

  • Recommended Tool: GitHub Actions.

* Justification: Tightly integrated with GitHub repositories, easy to configure with YAML, and provides a wide range of community actions for various tasks.

  • Pipeline Phases:

1. Build & Lint:

* Trigger: Push to any branch, Pull Request.

* Actions: Code linting (e.g., Black, Flake8, Pylint), dependency installation.

2. Test:

* Trigger: Successful Build & Lint.

* Actions: Run unit tests, integration tests (against an ephemeral database/mocked services).

3. Container Image Build & Scan:

* Trigger: Successful Test, Push to main branch.

* Actions: Build Docker image, scan for vulnerabilities (e.g., Trivy, Snyk), tag image with commit SHA/version.

4. Container Image Push:

* Trigger: Successful Image Build & Scan.

* Actions: Push Docker image to a container registry (e.g., AWS ECR, Docker Hub, GitHub Container Registry).

5. Deployment to Staging:

* Trigger: Successful Image Push, Push to main branch.

* Actions: Deploy the new image to a staging environment (e.g., Kubernetes cluster).

6. End-to-End (E2E) Tests:

* Trigger: Successful Deployment to Staging.

* Actions: Run E2E tests against the deployed staging environment.

7. Manual Approval / Automated Promotion to Production:

* Trigger: Successful E2E Tests.

* Actions: Manual approval step for production deployment, or automated promotion based on confidence.

* Actions: Deploy to production environment.

3.3. Deployment Strategy

  • Orchestration: Kubernetes (K8s).

* Justification: The industry standard for container orchestration, providing automated deployment, scaling, and management of containerized applications.

  • Cloud Provider (Example): AWS EKS (Elastic Kubernetes Service).

* Justification: A managed Kubernetes service by AWS, simplifying the operation of Kubernetes control plane.

  • Configuration Management: Helm.

* Justification: A package manager for Kubernetes, allowing for defining, installing, and upgrading even the most complex Kubernetes applications.

  • Infrastructure as Code (IaC): Terraform.

* Justification: Used to provision and manage cloud resources (e.g., EKS cluster, databases, networking) in a declarative and version-controlled manner.

3.4. Observability

Comprehensive observability is critical for understanding microservice behavior and diagnosing issues.

  • Logging:

* Strategy: Structured logging (JSON format) to stdout/stderr from the application.

* Centralized System: ELK Stack (Elasticsearch, Logstash, Kibana) or Grafana Loki.

* Justification: Collects, aggregates, and visualizes logs from all services for easy searching and analysis.

  • Monitoring:

* Metrics Collection: Prometheus for time-series data collection.

* Visualization & Alerting: Grafana for creating dashboards and configuring alerts based on Prometheus metrics.

* Justification: Provides real-time insights into service health, performance, and resource utilization.

  • Tracing:

* Tool: OpenTelemetry.

* Justification: A vendor-agnostic set of APIs, SDKs, and tools for instrumenting, generating, collecting, and exporting telemetry data (traces, metrics, logs). It allows for distributed tracing across microservices to understand request flows and latency.

4. Architectural Principles

Adhering to these principles ensures a robust and maintainable microservice architecture:

  • Single Responsibility Principle (SRP): Each microservice should encapsulate a single, well-defined business capability or bounded context.
  • Loose Coupling: Services should be designed to be independent of each other, minimizing direct dependencies. Communication primarily via APIs or message queues.
  • High Cohesion: Related functionality and data should be grouped together within the same microservice.
  • Resilience: Services must be designed to handle failures gracefully (e.g., retries, circuit breakers, bulkheads, timeouts).
  • Scalability: Design for horizontal scaling by making services stateless where possible and utilizing container orchestration.
  • Security: Implement security at all layers: network, application (authentication, authorization, input validation), and data storage (encryption at rest and in transit).
  • Automation: Automate all aspects of the development lifecycle, from testing to deployment.

5. Summary of Recommended Technologies

This table summarizes the key technology choices for the microservice:

| Component | Recommended Technology |

| :---------------------- | :---------------------------------- |

| Backend Framework | Python 3.10+ with FastAPI |

| Database | PostgreSQL |

| ORM | SQLAlchemy |

| Messaging Queue | RabbitMQ |

| Containerization | Docker |

| Local Orchestration | Docker Compose |

| CI/CD Platform | GitHub Actions |

| Production Orchestration | Kubernetes (e.g., AWS EKS) |

| IaC (Cloud Resources) | Terraform |

| Logging | ELK Stack (Elasticsearch, Logstash, Kibana) or Grafana Loki |

| Monitoring | Prometheus & Graf

python

app/crud/item.py

import uuid

from typing import List, Optional

from sqlalchemy.future import select

from sqlalchemy.ext.asyncio import AsyncSession

from app.models.sql import Item as DBItem

from app.models.item import ItemCreate, ItemUpdate

class CRUDItem:

"""

CRUD operations for the Item model.

"""

async def get(self, db: AsyncSession, item_id: uuid

gemini Output

Microservice Scaffolder: Comprehensive Deliverable

This document provides a detailed overview and access to the complete microservice scaffold generated for your project. This deliverable includes all necessary components for a production-ready microservice, encompassing development, testing, deployment, and operational aspects.


1. Introduction & Project Overview

We have successfully generated a robust microservice scaffold, designed for high performance, scalability, and maintainability. This scaffold provides a strong foundation for your specific business logic, significantly accelerating your development timeline.

Key Features of the Generated Microservice:

  • Language & Framework: Python 3.10+ (FastAPI)
  • Database: PostgreSQL (SQLAlchemy ORM)
  • Containerization: Docker & Docker Compose
  • Testing: Pytest (Unit & Integration)
  • CI/CD: GitHub Actions (configurable for other platforms)
  • Deployment: Kubernetes-ready manifests and basic deployment scripts
  • API Documentation: OpenAPI/Swagger UI (built-in with FastAPI)

The generated microservice is named [YourServiceName] (e.g., user-management-service) and is designed to handle common microservice patterns such as CRUD operations, authentication placeholders, and robust error handling.


2. Project Structure

The generated project adheres to a standard, modular structure for clarity and ease of maintenance. Below is a high-level representation of the directory structure:


[YourServiceName]/
├── src/
│   ├── api/                  # API endpoints and route definitions
│   │   ├── v1/
│   │   │   └── endpoints/    # Specific resource endpoints (e.g., users.py)
│   │   └── __init__.py
│   ├── core/                 # Core configurations, settings, and utilities
│   │   ├── config.py         # Environment-based configurations
│   │   ├── exceptions.py     # Custom exception handling
│   │   └── __init__.py
│   ├── db/                   # Database-related components
│   │   ├── models/           # SQLAlchemy ORM models
│   │   ├── repositories/     # Data access layer (CRUD operations)
│   │   ├── database.py       # Database session management
│   │   └── __init__.py
│   ├── services/             # Business logic and service layer
│   │   └── __init__.py
│   ├── schemas/              # Pydantic schemas for request/response validation
│   └── main.py               # FastAPI application entry point
├── tests/
│   ├── unit/                 # Unit tests for individual components
│   ├── integration/          # Integration tests for API endpoints and DB interaction
│   └── conftest.py           # Pytest fixtures
├── scripts/                  # Helper scripts (e.g., local setup, migration)
├── deployment/
│   ├── kubernetes/           # Kubernetes manifests (Deployment, Service, Ingress, etc.)
│   └── docker-compose/       # Docker Compose for local development (if separate)
├── .github/
│   └── workflows/            # GitHub Actions CI/CD pipeline definitions
│       └── main.yml
├── .env.example              # Example environment variables
├── Dockerfile                # Docker image definition for the microservice
├── docker-compose.yml        # Docker Compose for local development (app + db)
├── Makefile                  # Common development commands
├── requirements.txt          # Python dependencies
├── README.md                 # Project README with setup and usage instructions
└── tox.ini                   # Tox configuration for testing environments

3. Core Microservice Components

3.1. API Routes & Endpoints

The src/api/v1/endpoints/ directory contains the definition of your RESTful API endpoints, built using FastAPI. Each resource (e.g., users.py, items.py) has its own file, promoting modularity.

  • Example: src/api/v1/endpoints/users.py

    from fastapi import APIRouter, Depends, HTTPException, status
    from typing import List
    from sqlalchemy.orm import Session

    from src.db.database import get_db
    from src.db.repositories.user_repository import UserRepository
    from src.schemas.user_schema import UserCreate, UserResponse, UserUpdate

    router = APIRouter(prefix="/users", tags=["Users"])

    @router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
    async def create_user(user: UserCreate, db: Session = Depends(get_db)):
        repo = UserRepository(db)
        db_user = await repo.get_by_email(user.email)
        if db_user:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered")
        return await repo.create(user)

    @router.get("/", response_model=List[UserResponse])
    async def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
        repo = UserRepository(db)
        return await repo.get_all(skip=skip, limit=limit)

    @router.get("/{user_id}", response_model=UserResponse)
    async def read_user(user_id: int, db: Session = Depends(get_db)):
        repo = UserRepository(db)
        db_user = await repo.get_by_id(user_id)
        if db_user is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
        return db_user

    # ... (PUT, DELETE endpoints)
  • Key Features:

* Pydantic Schemas: Used for request body validation and response serialization, ensuring strict data contracts.

* Dependency Injection: Depends(get_db) automatically manages database sessions for each request.

* OpenAPI/Swagger UI: All defined endpoints are automatically documented and accessible at /docs (interactive) and /redoc (static) when running the service.

3.2. Database Models & ORM Setup

The src/db/models/ directory contains SQLAlchemy ORM models representing your database tables. The src/db/database.py handles database connection and session management.

  • Example: src/db/models/user_model.py

    from sqlalchemy import Column, Integer, String, Boolean
    from sqlalchemy.ext.declarative import declarative_base

    Base = declarative_base()

    class User(Base):
        __tablename__ = "users"

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

        # Add relationships or other fields as needed
  • Database Migrations: While not explicitly generated as part of the initial scaffold for simplicity, the project is set up to easily integrate with Alembic for database migrations. A scripts/init_db.py is provided for initial table creation.

3.3. Business Logic / Services

The src/services/ directory is where your core business logic resides. These services interact with repositories (data access layer) and encapsulate complex operations, keeping your API endpoints clean and focused on request/response handling.

  • Example: src/services/user_service.py

    from sqlalchemy.orm import Session
    from src.db.repositories.user_repository import UserRepository
    from src.schemas.user_schema import UserCreate, UserUpdate
    # ... other imports for hashing passwords, etc.

    class UserService:
        def __init__(self, db: Session):
            self.user_repo = UserRepository(db)

        async def create_new_user(self, user_data: UserCreate):
            # Example: Hash password before passing to repository
            hashed_password = "hashed_" + user_data.password # Placeholder for actual hashing
            user_data.password = hashed_password
            return await self.user_repo.create(user_data)

        async def get_user_profile(self, user_id: int):
            return await self.user_repo.get_by_id(user_id)

        # ... other business logic methods

4. Containerization (Docker)

The microservice is fully containerized using Docker, ensuring consistent environments across development, testing, and production.

4.1. Dockerfile

Located at the project root, the Dockerfile defines how to build the Docker image for your microservice.


# Use an official Python runtime as a parent image
FROM python:3.10-slim-buster

# Set the working directory in the container
WORKDIR /app

# Install system dependencies (if any, e.g., for psycopg2)
# RUN apt-get update && apt-get install -y --no-install-recommends \
#     build-essential libpq-dev \
#     && rm -rf /var/lib/apt/lists/*

# Copy the requirements file into the container
COPY requirements.txt .

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Copy the rest of the application code into the container
COPY . .

# Expose the port the app runs on
EXPOSE 8000

# Run the application using Uvicorn (ASGI server for FastAPI)
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]

4.2. docker-compose.yml

This file facilitates local development by orchestrating the microservice and its dependencies (e.g., PostgreSQL database).


version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8000:8000"
    volumes:
      - .:/app  # Mount current directory for live code changes (dev only)
    env_file:
      - .env
    depends_on:
      - db
    networks:
      - app-network

  db:
    image: postgres:13
    ports:
      - "5432:5432"
    env_file:
      - .env
    volumes:
      - db_data:/var/lib/postgresql/data
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

volumes:
  db_data:

4.3. Docker Instructions

  • Build the image: docker build -t your-service-name:latest .
  • Run locally with Docker Compose: docker-compose up --build

* This will start both the FastAPI application and a PostgreSQL database.

* The service will be accessible at http://localhost:8000.


5. Testing Framework

The project includes a comprehensive testing setup using pytest, covering both unit and integration tests.

5.1. Test Structure

  • tests/unit/: Contains tests for individual functions, classes, and components in isolation (e.g., test_user_service.py). Mocking is extensively used here.
  • tests/integration/: Contains tests that verify the interaction between multiple components, often involving API endpoints and actual database operations (e.g., test_user_api.py).
  • tests/conftest.py: Defines reusable fixtures (e.g., database session, test client) to simplify test writing and ensure consistent test environments.

5.2. Example: tests/integration/test_user_api.py


import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from src.main import app
from src.db.database import Base, get_db
from src.db.models.user_model import User # Import your actual User model

# Use an in-memory SQLite database for integration tests for speed
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

@pytest.fixture(scope="module")
def setup_db():
    Base.metadata.create_all(bind=engine) # Create tables
    yield
    Base.metadata.drop_all(bind=engine)   # Drop tables after tests

@pytest.fixture(scope="function")
def db_session(setup_db):
    connection = engine.connect()
    transaction = connection.begin()
    session = TestingSessionLocal(bind=connection)
    yield session
    session.close()
    transaction.rollback()
    connection.close()

@pytest.fixture(scope="function")
def client(db_session):
    def override_get_db():
        yield db_session
    app.dependency_overrides[get_db] = override_get_db
    with TestClient(app) as c:
        yield c
    app.dependency_overrides.clear()

def test_create_user(client):
    response = client.post(
        "/api/v1/users/",
        json={"email": "test@example.com", "password": "password123"},
    )
    assert response.status_code == 201
    assert response.json()["email"] == "test@example.com"
    assert "id" in response.json()

def test_read_users(client):
    # Create a user first
    client.post("/api/v1/users/", json={"email": "another@example.com", "password": "pass"})
    response = client.get("/api/v1/users/")
    assert response.status_code == 200
    assert len(response.json()) > 0
    assert any(user["email"] == "another@example.com" for user in response.json())

5.3. Running Tests

  • Install dependencies: pip install -r requirements.txt (or make install)
  • Run all tests: pytest
  • Run specific tests: pytest tests/unit/test_some_module.py
  • Run tests with coverage: pytest --cov=src
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);}});}