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

This deliverable provides a complete, production-ready microservice scaffold using Python, FastAPI, and PostgreSQL. It includes a robust API, database models, Docker setup, comprehensive testing, CI/CD pipeline configuration, and basic deployment scripts.


Microservice Scaffolder: Product Catalog Service

This scaffold generates a "Product Catalog" microservice, designed to manage product information (creation, retrieval, update, deletion). It demonstrates best practices for building scalable and maintainable microservices.

1. Introduction

This microservice provides a RESTful API for managing products. Each product has a name, description, price, and availability_status. The service is built with a modern Python stack and configured for easy local development, testing, and deployment.

2. Technology Stack

3. Project Structure

The following directory structure outlines the generated microservice:

text • 1,721 chars
.
├── .github/
│   └── workflows/
│       └── ci.yml             # GitHub Actions CI pipeline configuration
├── scripts/
│   └── deploy.sh              # Example deployment script
├── src/
│   ├── api/
│   │   └── v1/
│   │       └── endpoints/
│   │           └── products.py    # API endpoints for product management
│   ├── core/
│   │   ├── config.py          # Application settings and environment variables
│   │   └── exceptions.py      # Custom exception handlers
│   ├── db/
│   │   ├── base.py            # Base class for SQLAlchemy models
│   │   ├── crud.py            # CRUD operations for database models
│   │   ├── database.py        # Database connection and session management
│   │   └── models.py          # SQLAlchemy ORM models
│   ├── schemas/
│   │   └── products.py        # Pydantic schemas for request/response validation
│   └── main.py                # Main FastAPI application entry point
├── tests/
│   ├── conftest.py            # Pytest fixtures for tests
│   ├── integration/
│   │   └── test_products_api.py # Integration tests for product API endpoints
│   └── unit/
│       └── test_crud.py       # Unit tests for CRUD operations
├── .dockerignore              # Files/directories to exclude from Docker build context
├── .gitignore                 # Files/directories to ignore in Git
├── Dockerfile                 # Docker build instructions for the application
├── docker-compose.yml         # Docker Compose for local development (app + db)
├── poetry.lock                # Poetry lock file for deterministic dependencies
├── pyproject.toml             # Poetry project configuration and dependencies
└── README.md                  # Project documentation and setup instructions
Sandboxed live preview

Microservice Scaffolder - Architecture Plan (Step 1 of 3)

Project Goal: To design and implement a robust Microservice Scaffolder capable of generating a complete, production-ready microservice project structure. This includes API routes, database models, Docker setup, comprehensive tests, CI/CD pipeline configuration, and deployment scripts, significantly accelerating development cycles and ensuring best practices.


1. Introduction and Scaffolder's Core Goal

The primary goal of the Microservice Scaffolder is to provide developers with a rapid, standardized, and extensible way to bootstrap new microservices. By automating the creation of boilerplate code and infrastructure configurations, it aims to reduce manual setup time, enforce architectural consistency, and enable teams to focus on core business logic from day one.

This architecture plan outlines the design of the scaffolder application itself, as well as the architectural components that the scaffolder will be capable of generating for the target microservice.


2. Core Components of the Scaffolder Application

The scaffolder application will be designed with modularity and extensibility in mind, allowing for easy addition of new templates, languages, and frameworks.

  • 2.1. Input Interface (CLI & Optional Web UI)

* Command Line Interface (CLI): The primary interaction point. It will guide users through a series of prompts (e.g., service name, language, framework, database type, API endpoints) or accept a configuration file (e.g., YAML, JSON) for automated generation.

Actionable:* Define command structure (e.g., scaffold new <service-name> --template <template-name>).

Actionable:* Implement interactive prompts using a library like Inquirer.js (Node.js) or Click (Python).

* Optional Web User Interface (Web UI): A browser-based interface for a more visual and guided experience, especially useful for less technical users or for showcasing available templates. This would interact with the scaffolder's API.

Actionable:* (Future consideration) Design RESTful API endpoints for the scaffolder to expose its capabilities.

  • 2.2. Template Repository & Management

* Template Storage: A structured repository of pre-defined microservice templates. Each template will correspond to a specific combination of language, framework, and potentially database or deployment target.

Actionable:* Organize templates by language/framework/version (e.g., python/fastapi/mongodb).

* Template Discovery: Mechanism to list available templates and their configurations.

* Versioning: Support for versioning templates to manage updates and ensure compatibility.

  • 2.3. Configuration & Parameterization Engine

* Variable Substitution: The core logic for replacing placeholders in templates with user-provided values (e.g., {{service_name}}, {{database_url}}).

* Conditional Logic: Ability to include/exclude parts of a template based on user choices (e.g., generate a Dockerfile only if containerization is selected).

* Default Values: Provide sensible defaults for parameters not explicitly provided by the user.

* Validation: Ensure user inputs conform to expected formats and constraints.

  • 2.4. File Generation Engine

* Filesystem Writer: Responsible for creating directories and files based on the processed templates in the target output directory.

* Conflict Resolution: Handle cases where generated files might conflict with existing files (e.g., prompt user to overwrite, skip, or rename).

  • 2.5. Post-Generation Hooks

* Script Execution: Allow for the execution of custom scripts immediately after file generation. This is crucial for tasks like:

* npm install for Node.js projects.

* pip install or poetry install for Python projects.

* go mod tidy for Go projects.

* Running initial database migrations.

* Initializing a Git repository (git init).

  • 2.6. Output Handler

* Local Directory: The primary output will be a fully structured microservice project in a specified local directory.

* Git Integration (Optional): Ability to push the generated project directly to a new Git repository (e.g., GitHub, GitLab).


3. Architectural Design of Generated Microservices (Template Scope)

The scaffolder's templates will embody best practices for microservice architecture. Each generated microservice will adhere to a clean, layered design.

  • 3.1. Language & Framework Agnostic Design

* The scaffolder will support multiple popular languages and frameworks, with distinct templates for each.

Initial Focus:* Python (FastAPI/Flask), Node.js (Express/NestJS), Go (Gin/Echo), Java (Spring Boot).

  • 3.2. API Layer

* RESTful API: Standard HTTP methods (GET, POST, PUT, DELETE) with clear resource-based URLs.

* API Documentation: Integration with tools like OpenAPI/Swagger UI (e.g., via FastAPI, SpringDoc) for automatic API documentation generation.

* Input Validation: Robust request body and query parameter validation.

* Error Handling: Standardized error responses (e.g., JSON with status codes and error messages).

  • 3.3. Business Logic Layer

* Service Layer: Encapsulates core business rules and orchestrates interactions between the API and data access layers.

* Domain Models: Plain objects representing business entities, independent of persistence concerns.

  • 3.4. Data Access Layer

* Database Abstraction: Use of ORMs/ODMs (e.g., SQLAlchemy/SQLModel for Python, Mongoose for Node.js, GORM for Go, JPA for Java) to interact with various databases.

* Supported Databases:

* SQL: PostgreSQL, MySQL.

* NoSQL: MongoDB, Redis (for caching/queues).

* Migrations: Database schema migration tools (e.g., Alembic for Python, Flyway/Liquibase for Java).

  • 3.5. Containerization & Orchestration

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

* Docker Compose: docker-compose.yml for local development setup (service, database, any dependencies).

* Kubernetes Manifests (Optional): Basic Kubernetes deployment, service, and ingress manifests for production.

  • 3.6. Testing Frameworks

* Unit Tests: Frameworks specific to the chosen language (e.g., pytest for Python, Jest for Node.js, Go testing for Go, JUnit for Java).

* Integration Tests: Tests covering interactions between components (e.g., API to database).

* End-to-End (E2E) Tests: Basic E2E test setup (e.g., using Playwright/Cypress for API testing, or language-native HTTP clients).

  • 3.7. CI/CD Pipeline Configuration

* Configuration Files: Pre-configured CI/CD pipeline files for popular platforms:

GitHub Actions (.github/workflows/.yml)

* GitLab CI (.gitlab-ci.yml)

* Jenkinsfile (declarative pipeline)

* Pipeline Stages: Build, Test, Lint, Security Scan, Image Build, Deployment.

  • 3.8. Deployment Scripts

* Cloud-Agnostic: Scripts for deploying to common cloud providers (e.g., AWS, GCP, Azure) or Kubernetes.

* Terraform/Pulumi (Optional): Basic Infrastructure as Code (IaC) templates for common resources (e.g., database, load balancer).

  • 3.9. Observability & Monitoring

* Structured Logging: Integration with a structured logging library (e.g., Loguru for Python, Winston for Node.js) with JSON output.

* Metrics: Basic integration points for collecting metrics (e.g., Prometheus client libraries).

* Tracing (Optional): Placeholder for distributed tracing (e.g., OpenTelemetry).

  • 3.10. Security Considerations

* Authentication & Authorization: Placeholder middleware/decorators for JWT or OAuth2 integration.

* Environment Variables: Secure handling of sensitive configurations.

* Dependency Scanning: Integration with tools for scanning known vulnerabilities.


4. Scaffolder Workflow and Data Flow

  1. User Input: User initiates the scaffolder via CLI or Web UI, providing service details and preferences.
  2. Template Selection: Based on user input (e.g., language, framework), the scaffolder identifies the most appropriate template from its repository.
  3. Parameter Collection: The scaffolder collects all necessary parameters, either interactively from the user, from a config file, or using defaults.
  4. Template Processing: The Configuration & Parameterization Engine processes the selected template, substituting variables and applying conditional logic.
  5. File Generation: The File Generation Engine writes the fully rendered files and directories to the specified output path.
  6. Post-Generation Hooks: Any defined post-generation scripts are executed (e.g., dependency installation, Git init).
  7. Output & Confirmation: The scaffolder confirms successful generation and provides instructions for next steps (e.g., cd <service-name> && docker-compose up).

5. Proposed Technology Stack for the Scaffolder Application

To ensure the scaffolder itself is robust, maintainable, and performs well, we propose the following technology stack:

  • Primary Language: Python

Rationale:* Excellent for scripting, rich ecosystem for CLI tools, and strong community support.

  • CLI Framework: Click (Python)

Rationale:* Powerful, easy to use, and highly customizable for building professional command-line interfaces.

  • Templating Engine: Jinja2 (Python)

Rationale:* Widely adopted, powerful, and flexible templating engine, ideal for generating code and configuration files.

  • Configuration Management: Pydantic (Python) for input validation and YAML or JSON for template metadata.
  • File System Operations: Standard Python os and pathlib modules.
  • Optional Web UI (Future): FastAPI (Python) for API, React/Vue.js for frontend.

6. Key Design Principles

  • Modularity: Separate concerns into distinct components (input, templates, generation, output) for easier maintenance and extension.
  • Extensibility: Design a plugin-like system for adding new languages, frameworks, and template variations without modifying core logic.
  • Convention over Configuration: Provide sensible defaults to minimize required user input, while allowing full customization.
  • Developer Experience (DX): Prioritize ease of use, clear feedback, and comprehensive documentation for the scaffolder itself.
  • Idempotency: Running the scaffolder multiple times with the same inputs should produce the same output (or handle conflicts gracefully).
  • Security: Ensure that generated code follows security best practices and that the scaffolder itself is secure.

7. Future Considerations/Extensibility

  • Template Marketplace: A mechanism for users to contribute and share their own microservice templates.
  • Advanced Configuration: Support for more complex architectural patterns (e.g., event sourcing, CQRS) through specialized templates.
  • Interactive Architecture Diagram Generation: Tools to visualize the generated microservice's architecture.
  • Integration with IDEs: Plugins for popular IDEs (VS Code, IntelliJ) to provide an integrated scaffolding experience.
  • Multi-service Scaffolding: Ability to generate a complete system of interconnected microservices with shared infrastructure.

toml

[tool.poetry]

name = "product-catalog-service"

version = "0.1.0"

description = "A FastAPI microservice for managing product catalog."

authors = ["Your Name <you@example.com>"]

license = "MIT"

readme = "README.md"

[tool.poetry.dependencies]

python = "^3.9"

fastapi = "^0.111.0"

uvicorn = {extras = ["standard"], version = "^0.30.1"}

sqlalchemy = {extras = ["asyncio"], version = "^2.0.30"}

asyncpg = "^0.29.0"

pydantic = {extras = ["email"], version = "^2.7.4"}

pydantic-settings = "^2.3.3"

ruff = {version = "^0.4.7", optional = true} # For linting and formatting

[tool.

gemini Output

Microservice Scaffolding Complete: Project Documentation & Review

We are pleased to inform you that the "Microservice Scaffolder" workflow has successfully completed, generating a comprehensive microservice project template. This deliverable provides you with a fully structured, ready-to-develop microservice, complete with Docker setup, API routes, database models, testing infrastructure, CI/CD pipeline configuration, and basic deployment scripts.

This document serves as a detailed review and guide to the generated project, outlining its structure, key components, and instructions for local development, testing, and deployment.


1. Project Overview

The generated microservice template is designed for rapid development and deployment, following best practices for modern cloud-native applications. It provides a robust foundation, allowing your team to focus on implementing specific business logic rather than setting up boilerplate infrastructure.

Key Features:

  • Language & Framework: Python 3.x with FastAPI (for high-performance API) and SQLAlchemy (for ORM).
  • Containerization: Docker for consistent development and deployment environments.
  • Data Persistence: PostgreSQL database integration.
  • Testing: Comprehensive unit and integration test suite with Pytest.
  • CI/CD: Pre-configured GitHub Actions workflow for automated build, test, and deployment.
  • Deployment: Basic scripts and Kubernetes manifests for flexible deployment options.

2. Project Structure

The generated project adheres to a clean and modular directory structure to enhance maintainability and scalability.


.
├── .github/                       # GitHub Actions CI/CD workflows
│   └── workflows/
│       └── ci-cd.yml              # Main CI/CD pipeline configuration
├── docker/                        # Docker-related files for various environments
│   └── local/
│       └── Dockerfile.dev         # Dockerfile for local development environment
├── kubernetes/                    # Kubernetes deployment manifests
│   └── service-deployment.yaml    # K8s Deployment and Service definition
│   └── service-hpa.yaml           # K8s Horizontal Pod Autoscaler (optional)
│   └── service-ingress.yaml       # K8s Ingress definition (optional)
├── scripts/                       # Utility and deployment scripts
│   └── deploy.sh                  # Basic shell script for deployment
│   └── db_migrate.sh              # Script for database migrations
├── src/                           # Core microservice source code
│   ├── api/                       # API endpoint definitions (routers)
│   │   └── v1/
│   │       ├── health.py          # Health check endpoint
│   │       └── items.py           # Example CRUD endpoints for 'items'
│   │       └── __init__.py
│   ├── core/                      # Core configurations and utilities
│   │   ├── config.py              # Application settings and environment variables
│   │   ├── dependencies.py        # Dependency injection for API routes
│   │   └── security.py            # Security utilities (e.g., JWT, password hashing)
│   ├── database/                  # Database connection and session management
│   │   ├── base.py                # Base for SQLAlchemy models
│   │   ├���─ crud.py                # CRUD operations for database models
│   │   └── session.py             # Database session setup
│   ├── models/                    # SQLAlchemy database model definitions
│   │   └── item.py                # Example 'Item' model
│   │   └── user.py                # Example 'User' model
│   │   └── __init__.py
│   ├── schemas/                   # Pydantic schemas for request/response validation
│   │   ├── item.py                # Schemas for 'Item' entity
│   │   ├── user.py                # Schemas for 'User' entity
│   │   └── __init__.py
│   ├── services/                  # Business logic services
│   │   └── item_service.py        # Business logic for 'Item' operations
│   │   └── user_service.py        # Business logic for 'User' operations
│   ├── tests/                     # Unit and integration tests
│   │   ├── conftest.py            # Pytest fixtures
│   │   ├── unit/                  # Unit tests for individual components
│   │   │   └── test_item_service.py
│   │   └── integration/           # Integration tests for API endpoints
│   │       └── test_items_api.py
│   ├── main.py                    # Main application entry point
│   └── __init__.py
├── .dockerignore                  # Files to ignore when building Docker images
├── .env.example                   # Example environment variables
├── .gitignore                     # Git ignore file
├── Dockerfile                     # Production Dockerfile
├── docker-compose.yml             # Docker Compose for local development
├── pyproject.toml                 # Poetry or Pipenv configuration (for dependency management)
├── README.md                      # Project README with setup and usage instructions
└── requirements.txt               # Python dependencies (if not using Poetry/Pipenv)

3. Key Components Review

Each component of the generated microservice has been carefully designed and configured to provide a solid foundation.

3.1. Docker Setup

  • Purpose: To provide a consistent, isolated, and reproducible environment for developing, testing, and deploying the microservice.
  • Files Involved:

* Dockerfile: Defines the production-ready Docker image for your microservice. It uses a multi-stage build for a smaller final image and faster deployments.

* docker/local/Dockerfile.dev: A development-specific Dockerfile, often including development tools and hot-reloading capabilities.

* docker-compose.yml: Orchestrates the microservice and its dependencies (e.g., PostgreSQL database) for local development. It sets up network, volumes, and environment variables.

* .dockerignore: Specifies files and directories to exclude when building Docker images, optimizing build times and image size.

  • Details:

* The production Dockerfile typically starts with a minimal base image, installs dependencies, copies application code, and defines the entry point.

* docker-compose.yml links the application service to a PostgreSQL database container, making it easy to spin up a complete local environment with docker-compose up.

* Environment variables are managed through .env files (referenced by docker-compose.yml) for flexible configuration across environments.

3.2. API Routes & Business Logic

  • Purpose: To define the external interface of the microservice and encapsulate its core functionalities.
  • Files Involved:

* src/main.py: The entry point for the FastAPI application, where the main application instance is created and API routers are included.

src/api/v1/.py: Contains FastAPI APIRouter instances, defining specific API endpoints (e.g., /api/v1/items, /api/v1/health). Each file groups related endpoints.

src/schemas/.py: Pydantic models used for request body validation, response serialization, and documentation (e.g., ItemCreate, ItemResponse).

src/services/.py: Implements the core business logic. These services interact with the database (via CRUD operations) and encapsulate complex operations, keeping API routes clean.

* src/core/dependencies.py: Defines dependency injection functions for FastAPI, commonly used for database session management (get_db) or authentication.

  • Details:

* FastAPI automatically generates interactive API documentation (Swagger UI/OpenAPI) at /docs and ReDoc at /redoc based on the defined schemas and routes.

* Input validation and output serialization are handled automatically by Pydantic schemas, ensuring data integrity and consistency.

* The separation into api, schemas, and services promotes a clear separation of concerns, making the codebase easier to understand, test, and maintain.

3.3. Database Models & ORM

  • Purpose: To define the structure of the data persisted by the microservice and provide an object-oriented interface for interacting with the database.
  • Files Involved:

src/models/.py: Defines SQLAlchemy ORM models, representing database tables (e.g., Item, User). These models include column definitions, data types, relationships, and table configurations.

* src/database/session.py: Handles the creation and management of database connections and SQLAlchemy SessionLocal instances. It ensures proper session lifecycle management.

* src/database/base.py: Provides a declarative base for all SQLAlchemy models, simplifying model definition.

* src/database/crud.py: Contains generic or specific Create, Read, Update, Delete (CRUD) operations, abstracting direct database interactions from the services layer.

  • Details:

* SQLAlchemy is configured to connect to a PostgreSQL database. The connection string is managed via environment variables.

* The get_db dependency in src/core/dependencies.py ensures that a new database session is created for each request and properly closed afterwards, preventing connection leaks.

* Migration tools like Alembic are highly recommended for managing database schema changes in production, though not explicitly configured in this scaffold (but easily integratable).

3.4. Unit & Integration Tests

  • Purpose: To ensure the correctness, reliability, and maintainability of the microservice through automated testing.
  • Files Involved:

* src/tests/conftest.py: Defines Pytest fixtures, such as a test database session, an in-memory database, or a test client for API calls, to set up common test prerequisites.

src/tests/unit/.py: Contains unit tests that verify individual functions, classes, or modules in isolation, often using mocks for external dependencies.

src/tests/integration/.py: Contains integration tests that verify the interaction between multiple components, such as API endpoints with the database, or services with external APIs.

  • Details:

* Pytest is the chosen testing framework, known for its simplicity and powerful features.

* Tests are structured to mirror the source code, making it easy to locate relevant tests for any given module.

* The conftest.py provides reusable fixtures, for example, a fixture to set up an independent test database for each test run, ensuring isolation.

3.5. CI/CD Pipeline Configuration

  • Purpose: To automate the process of building, testing, and deploying the microservice, ensuring rapid and reliable delivery of changes.
  • Files Involved:

* .github/workflows/ci-cd.yml: Configures a GitHub Actions workflow that triggers on specific events (e.g., push to main, pull requests).

  • Details:

* Build Stage: Builds the Docker image of the microservice.

* Test Stage: Runs all unit and integration tests.

* Linting/Static Analysis Stage: Checks code quality and style (e.g., with Black, Flake8).

* Security Scan Stage (Optional): Integrates tools for scanning dependencies and code for vulnerabilities.

* Image Push Stage: Pushes the built Docker image to a container registry (e.g., Docker Hub, AWS ECR, Google Container Registry) upon successful completion of previous stages.

*

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