DevOps Pipeline Generator
Run ID: 69ccceb53e7fb09ff16a54882026-04-01Infrastructure
PantheraHive BOS
BOS Dashboard

DevOps Pipeline Generator: Comprehensive CI/CD Configurations

This deliverable provides detailed, production-ready CI/CD pipeline configurations for three leading platforms: GitHub Actions, GitLab CI, and Jenkins. Each configuration is designed to implement a robust workflow encompassing linting, testing, building, and deployment stages, ensuring code quality, reliability, and efficient delivery.

We will illustrate these pipelines using a common scenario: building a containerized application (e.g., a simple web service) and deploying it to a cloud-based container orchestration service.


1. Key Considerations for Robust CI/CD Pipelines

Before diving into specific configurations, it's crucial to understand the foundational principles that underpin effective CI/CD:

* Secrets Management: Never hardcode credentials. Utilize platform-specific secret management (e.g., GitHub Secrets, GitLab CI/CD Variables, Jenkins Credentials).

* Least Privilege: Grant pipelines and deployment agents only the minimum necessary permissions.

* Image Scanning: Integrate vulnerability scanning for Docker images.

* Static Application Security Testing (SAST): Scan source code for security vulnerabilities.


2. GitHub Actions CI/CD Pipeline Configuration

GitHub Actions provides a flexible and powerful way to automate workflows directly within your GitHub repository.

Scenario: A Node.js application that builds a Docker image, pushes it to a Container Registry (e.g., AWS ECR, Docker Hub), and deploys to a staging environment (e.g., Kubernetes, AWS ECS) on pushes to main, with a manual approval for production deployment.

File: .github/workflows/main.yml

text • 1,507 chars
**Explanation**:

*   **`on`**: Defines triggers for the workflow (push to `main`, pull requests to `main`, manual trigger).
*   **`env`**: Global environment variables for the workflow.
*   **`jobs`**:
    *   **`lint`**: Checks code style and quality.
    *   **`test`**: Runs unit and integration tests.
    *   **`build-and-push-image`**: Builds a Docker image and pushes it to a configured container registry. It uses `aws-actions/configure-aws-credentials` and `aws-actions/amazon-ecr-login` for AWS ECR integration.
    *   **`deploy-staging`**: Deploys the newly built image to a staging environment. This example uses AWS CLI to update an ECS service.
    *   **`deploy-production`**: Deploys the image to production. It uses GitHub Environments for manual approval and tracks the deployment status.
*   **`needs`**: Defines job dependencies, ensuring stages run in order.
*   **`if`**: Conditional execution of jobs (e.g., only build/deploy on `main` branch pushes).
*   **`secrets`**: Used to securely store sensitive information like AWS credentials or Docker Hub tokens.

---

### 3. GitLab CI/CD Pipeline Configuration

GitLab CI is deeply integrated into GitLab, offering a powerful and flexible platform for CI/CD.

**Scenario**: Same as GitHub Actions: A Node.js application that builds a Docker image, pushes it to GitLab's built-in Container Registry, and deploys to staging (e.g., Kubernetes) on `main` branch pushes, with a manual approval for production.

**File**: `.gitlab-ci.yml`

Sandboxed live preview

Step 1 of 3: Infrastructure Needs Analysis for DevOps Pipeline Generation

This document outlines a comprehensive analysis of the infrastructure requirements for generating robust CI/CD pipelines, covering common stages such as linting, testing, building, and deployment. Given the general request for a "DevOps Pipeline Generator," this analysis provides a foundational understanding and recommendations, which will be further refined based on specific project details in subsequent steps.

Understanding the Core Infrastructure Requirements for CI/CD

A well-architected CI/CD pipeline relies on specific infrastructure capabilities to support its various stages efficiently and securely.

Common CI/CD Stages and Their Infrastructure Demands:

  1. Linting/Static Analysis:

* Demand: Minimal compute resources, often executed within a containerized environment. Requires access to the codebase and linter tools.

* Infrastructure: Typically run on CI/CD runner agents (managed or self-hosted) with sufficient CPU/memory for quick analysis.

  1. Testing (Unit, Integration, End-to-End):

* Demand: Varies significantly. Unit tests are fast and light. Integration tests may require temporary database instances, message queues, or mocked services. End-to-end (E2E) tests often need fully deployed, ephemeral environments, potentially with browser automation tools (e.g., Selenium, Playwright).

* Infrastructure:

* Compute: CI/CD runners (CPU/memory intensive for parallel tests).

* Ephemeral Environments: Container orchestration (Kubernetes, Docker Compose) for spinning up test dependencies, or dedicated cloud services (e.g., AWS Fargate, Azure Container Instances).

* Storage: Temporary storage for test artifacts, logs.

  1. Building/Packaging:

* Demand: High CPU and memory for compiling code, building Docker images, packaging artifacts (JAR, WAR, NuGet, npm packages). Network bandwidth for pulling dependencies.

* Infrastructure:

* Compute: Powerful CI/CD runners (often multi-core CPUs, significant RAM).

* Container Registry: Docker Hub, Amazon ECR, Azure Container Registry, GitLab Container Registry for storing built images.

* Artifact Repository: Nexus, Artifactory, GitHub Packages, GitLab Package Registry for storing application packages and dependencies.

  1. Artifact Storage:

* Demand: Reliable, scalable, and secure storage for build artifacts, container images, and deployment packages. Versioning and access control are critical.

* Infrastructure: Object storage (AWS S3, Azure Blob Storage, Google Cloud Storage), dedicated artifact repositories (Nexus, Artifactory), or integrated CI/CD platform registries.

  1. Deployment:

* Demand: Secure network access to target environments, credentials management, and sufficient permissions to provision/update resources. Orchestration capabilities for complex deployments.

* Infrastructure:

* Target Environments: Cloud (IaaS, PaaS, Serverless), Kubernetes clusters, on-premise servers/VMs.

* Deployment Agents/Tools: CI/CD runners with deployment tools (Terraform, Ansible, Helm, kubectl, cloud CLIs).

* Secret Management: Vault, AWS Secrets Manager, Azure Key Vault, Kubernetes Secrets.

Key Infrastructure Considerations and Decision Factors

When planning CI/CD infrastructure, several factors influence the optimal choice:

  • Scalability & Elasticity: Can the infrastructure handle peak loads (e.g., multiple concurrent builds, large test suites) and scale down during idle periods to optimize costs?
  • Cost Optimization: Balancing performance requirements with budget. Managed services often have a higher per-unit cost but lower operational overhead.
  • Security & Compliance: Ensuring build environments are isolated, secrets are managed securely, and deployments adhere to regulatory requirements (e.g., SOC 2, HIPAA, GDPR).
  • Maintenance & Operational Overhead: The effort required to set up, maintain, and troubleshoot the CI/CD infrastructure. Managed services reduce this significantly.
  • Environment Consistency: Ensuring that build and test environments closely mirror production environments to prevent "it works on my machine" issues. Containerization is key here.
  • Technology Stack Compatibility: The infrastructure must support the specific languages, frameworks, databases, and deployment targets used by the application.

Data Insights & Current Trends in CI/CD Infrastructure

The landscape of CI/CD infrastructure is rapidly evolving, driven by cloud adoption, microservices, and automation.

  • Cloud-Native Dominance (70%+): A significant majority of organizations leverage cloud providers (AWS, Azure, GCP) for their CI/CD infrastructure due to scalability, global reach, and a rich ecosystem of managed services. This trend is expected to continue growing.

Insight:* Cloud-managed CI/CD services (e.g., GitHub Actions, GitLab CI, Azure DevOps Pipelines) are preferred for their ease of use and reduced operational burden.

  • Containerization & Orchestration (80%+ adoption for new projects): Docker and Kubernetes are de-facto standards for packaging applications and managing deployment environments. This extends to CI/CD, where builds and tests often run inside containers for consistency and isolation.

Insight:* Using containers for CI/CD jobs ensures environment parity and simplifies dependency management.

  • Serverless for CI/CD Components (Growing): Functions-as-a-Service (FaaS) can be used for specific, event-driven CI/CD tasks (e.g., triggering a build on a code commit, custom notifications).

Insight:* While not suitable for all stages, serverless can reduce costs for intermittent tasks.

  • GitOps and Infrastructure as Code (IaC) (60%+): Managing infrastructure and deployments through Git repositories ensures version control, auditability, and automated reconciliation. Tools like Terraform, Ansible, and Helm are integral.

Insight:* IaC and GitOps principles are critical for reliable, repeatable, and transparent CI/CD deployments.

  • Hybrid/Multi-Cloud Strategies (20-30% of enterprises): Larger organizations often use a combination of cloud providers or a mix of on-premise and cloud infrastructure for resilience, compliance, or cost optimization.

Insight:* This adds complexity to CI/CD but can be managed with platform-agnostic tools and containerization.

  • Emphasis on Developer Experience (DX): Tools that are easy to use, integrate well with existing workflows, and provide fast feedback loops are highly valued.

Insight:* Self-service CI/CD, clear pipeline logs, and rapid iteration are paramount for developer productivity.

Recommendations for Infrastructure Strategy

Based on the general requirements and current trends, we recommend evaluating the following infrastructure strategies:

1. Fully Managed Cloud CI/CD Services (e.g., GitHub Actions, GitLab CI, Azure DevOps Pipelines, CircleCI)

  • Pros:

* Lowest Operational Overhead: No servers to manage, patch, or scale.

* Rapid Setup: Quick to get started with pre-built actions/templates.

* High Scalability & Reliability: Handled entirely by the cloud provider.

* Integrated Ecosystem: Deep integration with source control and other developer tools.

  • Cons:

* Vendor Lock-in: Pipelines are often specific to the platform.

* Cost: Pay-as-you-go model can be more expensive for very high usage compared to optimized self-hosted runners.

* Limited Customization: Less control over the underlying execution environment.

  • Best For: Most modern applications, startups, teams prioritizing speed, simplicity, and minimal infrastructure management. Ideal for cloud-native applications.

2. Self-Hosted Runners/Agents on Cloud IaaS (e.g., EC2, Azure VMs, GCE, or Kubernetes)

  • Pros:

* Greater Control: Full control over the runner environment, enabling specialized hardware/software.

* Cost Optimization: Potentially lower cost for high usage by optimizing instance types and utilization.

* Security: Can run within a private network for sensitive operations.

* Hybrid Cloud Integration: Easier to connect to private cloud resources.

  • Cons:

* Higher Operational Overhead: Requires managing VMs, OS updates, scaling, and security.

* Initial Setup Complexity: More involved setup and configuration.

* Maintenance: Responsibility for patching, upgrades, and troubleshooting.

  • Best For: Projects with specific hardware/software requirements, strict security/compliance needs, large organizations with existing cloud infrastructure teams, or those seeking to optimize costs for very high CI/CD usage.

3. On-Premise Self-Hosted Runners (e.g., Jenkins on dedicated servers)

  • Pros:

* Maximum Control & Security: Full control over physical hardware and network.

* Compliance: Essential for highly regulated industries with strict data residency or air-gapped environment requirements.

* Leverage Existing Hardware: Utilize existing data center investments.

  • Cons:

* Highest Operational Overhead: Requires significant IT resources for provisioning, maintenance, scaling, and disaster recovery.

* Limited Scalability: Scaling can be slow and expensive compared to cloud.

* Cost: High upfront investment in hardware and ongoing operational costs.

  • Best For: Highly regulated industries, projects with strict on-premise data residency requirements, or organizations with significant existing on-premise infrastructure and expertise.

General Best Practices:

  • Containerization for Builds: Always run build and test jobs within Docker containers to ensure environment consistency and isolate dependencies.
  • Ephemeral Environments: Provision temporary environments for integration and E2E testing that are automatically torn down after use.
  • Centralized Artifact Management: Use dedicated artifact repositories (e.g., Nexus, Artifactory) or cloud object storage for managing build outputs and dependencies.
  • Robust Secret Management: Integrate with a dedicated secret management solution (e.g., HashiCorp Vault, cloud-native secret managers) to handle credentials securely.
  • Observability: Implement logging, monitoring, and alerting for the CI/CD pipeline and its underlying infrastructure to quickly identify and resolve issues.

Next Steps & Required Information

To generate a precise and highly effective CI/CD pipeline configuration, we require further specific details about your project. Please provide the following information:

  1. Target CI/CD Platform Preference: Which CI/CD platform do you intend to use? (e.g., GitHub Actions, GitLab CI, Jenkins, Azure DevOps, CircleCI, Travis CI, etc.)
  2. Application Type(s) and Primary Language(s)/Frameworks:

Example:* Microservices (Java Spring Boot, Python FastAPI), Frontend (React/Next.js), Mobile (iOS/Swift, Android/Kotlin), Data Science (Python/Jupyter).

  1. Deployment Target(s): Where will the application be deployed?

Example:* Kubernetes (AWS EKS, Azure AKS, GCP GKE, On-prem), Cloud PaaS (AWS App Runner, Azure App Service, GCP Cloud Run), Serverless (AWS Lambda, Azure Functions), Virtual Machines (AWS EC2, Azure VMs), On-premise Servers.

  1. Existing Infrastructure/Cloud Provider Preference: Do you have an existing cloud provider (AWS, Azure, GCP) or on-premise infrastructure you plan to leverage?
  2. Specific Testing Frameworks/Tools:

Example:* Jest, JUnit, Pytest, Cypress, Selenium, Playwright.

  1. Specific Linting/Static Analysis Tools:

Example:* ESLint, SonarQube, Black, Flake8, Checkstyle.

  1. Artifact Management Needs: Do you have specific requirements for storing build artifacts or container images? (e.g., existing private registry, specific naming conventions).
  2. Security & Compliance Requirements: Are there any specific industry regulations or security standards that the pipeline and infrastructure must adhere to?
  3. Scalability & Performance Expectations: What are your anticipated build frequencies, average build times, and concurrent job requirements?
  4. Budgetary Constraints / Operational Overhead Tolerance: What is your team's capacity for managing infrastructure vs. preference for managed services?

Once this information is provided, we can proceed to Step 2: Define Pipeline Stages and Logic, where we will design the specific workflow for your CI/CD pipeline.

gemini Output

This document provides comprehensive, detailed, and professional CI/CD pipeline configurations for GitHub Actions, GitLab CI, and Jenkins. It covers essential stages including linting, testing, building, and deployment, designed to ensure a robust and automated software delivery process.


1. Introduction: The Power of Automated CI/CD

Continuous Integration (CI) and Continuous Delivery/Deployment (CD) pipelines are fundamental to modern software development. They automate the processes of building, testing, and deploying applications, leading to faster release cycles, improved code quality, and reduced manual errors.

This deliverable provides detailed templates and guidelines for implementing a full-featured CI/CD pipeline across three popular platforms: GitHub Actions, GitLab CI, and Jenkins. These configurations are designed to be adaptable to various programming languages, frameworks, and deployment targets.

Key Benefits of an Automated CI/CD Pipeline:

  • Faster Release Cycles: Automate repetitive tasks, enabling quicker delivery of new features and bug fixes.
  • Improved Code Quality: Early detection of issues through automated linting and testing.
  • Reduced Risk: Consistent, repeatable processes minimize human error during deployment.
  • Enhanced Collaboration: Developers can integrate their changes frequently and confidently.
  • Scalability: Pipelines can be scaled to handle growing projects and teams.

2. Universal CI/CD Pipeline Stages

Regardless of the platform, a robust CI/CD pipeline typically consists of the following core stages:

2.1. Stage 1: Linting & Static Analysis

Goal: To analyze source code without executing it, identifying potential bugs, style violations, and security vulnerabilities early in the development cycle. This ensures code quality and adherence to coding standards.

  • Purpose: Enforce coding standards, detect common errors, and improve code readability.
  • Common Tools:

* JavaScript/TypeScript: ESLint, Prettier, TSLint (deprecated, use ESLint).

* Python: Flake8, Black, Pylint.

* Java: Checkstyle, SpotBugs, SonarQube (also for other languages).

* Go: GolangCI-Lint.

* Security: SAST tools like Bandit (Python), Semgrep, Snyk, SonarQube.

  • Example Commands:

* npm run lint (for JavaScript/TypeScript)

* flake8 . (for Python)

* golangci-lint run ./... (for Go)

2.2. Stage 2: Testing

Goal: To verify the functionality and correctness of the application through automated tests. This stage catches regressions and validates new features.

  • Purpose: Ensure the application behaves as expected under various conditions.
  • Types of Tests:

* Unit Tests: Test individual components or functions in isolation.

* Integration Tests: Verify that different modules or services work together correctly.

* End-to-End (E2E) Tests: Simulate real user scenarios across the entire application stack.

* Performance Tests: Assess application responsiveness, stability, and scalability under load (often in a separate stage or pipeline).

* Security Tests (DAST/Penetration): Test applications in their running state for vulnerabilities (often in a separate stage or pipeline).

  • Example Commands:

* npm test (for JavaScript/TypeScript)

* pytest (for Python)

* mvn test (for Java with Maven)

* go test ./... (for Go)

2.3. Stage 3: Building & Artifact Creation

Goal: To compile the source code, resolve dependencies, and package the application into a deployable artifact. For modern applications, this often involves creating Docker images.

  • Purpose: Create a consistent, immutable package ready for deployment.
  • Common Tasks:

* Dependency Installation: Fetching libraries (e.g., npm install, pip install, mvn clean install).

* Compilation: Converting source code into executable binaries or bytecode.

* Packaging: Creating JARs, WARs, ZIP files, or executable bundles.

* Containerization: Building Docker images and pushing them to a container registry (e.g., Docker Hub, AWS ECR, GitLab Container Registry).

* Artifact Upload: Storing build artifacts (e.g., test reports, compiled binaries, Docker image manifests) for later use or auditing.

  • Example Commands:

* npm run build (for frontend JavaScript)

* docker build -t your-registry/your-app:$(GIT_COMMIT) .

* docker push your-registry/your-app:$(GIT_COMMIT)

* mvn package (for Java)

2.4. Stage 4: Deployment

Goal: To release the built artifact to various environments (development, staging, production). This stage often involves environment-specific configurations and approval gates.

  • Purpose: Make the application available to users.
  • Environments:

* Development (Dev): For internal team testing and feature validation.

* Staging (Stage/Pre-Prod): A production-like environment for final testing and stakeholder review.

* Production (Prod): The live environment accessible to end-users.

  • Deployment Strategies:

* Rolling Updates: Gradually replace old instances with new ones.

* Blue/Green Deployment: Run two identical environments (blue and green); switch traffic to the new "green" version after validation.

* Canary Deployment: Gradually roll out new versions to a small subset of users before a full rollout.

  • Common Tools:

* Kubernetes: kubectl apply -f your-manifest.yaml

* Cloud Providers (AWS, Azure, GCP): AWS CLI, Azure CLI, gcloud CLI, Terraform, CloudFormation.

* Serverless: Serverless Framework, AWS SAM.

* PaaS: Heroku CLI, Vercel CLI.

  • Example Commands:

* kubectl apply -f k8s/dev-deployment.yaml

* aws ecs update-service --cluster your-cluster --service your-service --force-new-deployment

* ssh user@your-server "sudo systemctl restart your-app"


3. Platform-Specific CI/CD Pipeline Configurations

Below are detailed, generic pipeline templates for a typical containerized web application (e.g., Node.js, Python, Go) that builds a Docker image and deploys it to a Kubernetes cluster or a cloud service. These templates use placeholders (YOUR_...) that you will need to replace with your specific project details.

3.1. GitHub Actions

Overview & Key Features:

GitHub Actions provides powerful and flexible CI/CD directly within your GitHub repository. Workflows are defined in YAML files (.github/workflows/*.yml) and run on GitHub-hosted runners or self-hosted runners.

Generic Pipeline Template: .github/workflows/main.yml


name: CI/CD Pipeline

on:
  push:
    branches:
      - main
      - develop
    tags:
      - 'v*' # Run on tags like v1.0.0
  pull_request:
    branches:
      - main
      - develop
  workflow_dispatch: # Allows manual trigger from GitHub UI

env:
  # Define common environment variables
  DOCKER_IMAGE_NAME: your-app-name
  DOCKER_REGISTRY: ghcr.io/${{ github.repository_owner }} # Or docker.io/your-docker-id, your-aws-account-id.dkr.ecr.your-aws-region.amazonaws.com

jobs:
  lint:
    name: Lint Code
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Node.js (Example for Node.js app)
        uses: actions/setup-node@v4
        with:
          node-version: '20' # Specify your Node.js version

      - name: Install dependencies
        run: npm ci # Use npm ci for clean installs in CI

      - name: Run ESLint
        run: npm run lint # Or your specific lint command (e.g., flake8, golangci-lint)

  test:
    name: Run Tests
    runs-on: ubuntu-latest
    needs: lint # This job depends on the lint job completing successfully
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Node.js (Example for Node.js app)
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install dependencies
        run: npm ci

      - name: Run Unit and Integration Tests
        run: npm test # Or your specific test command (e.g., pytest, go test ./...)

      - name: Upload test results (optional)
        uses: actions/upload-artifact@v4
        if: always() # Upload even if tests fail
        with:
          name: test-results
          path: ./test-results.xml # Path to your test report file (e.g., JUnit XML)

  build_and_push_image:
    name: Build & Push Docker Image
    runs-on: ubuntu-latest
    needs: test # This job depends on the test job completing successfully
    if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' # Only build/push on push or manual trigger
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name

yaml

stages:

- lint

- test

- build

- deploy-staging

- deploy-production

variables:

DOCKER_IMAGE_NAME: $CI_REGISTRY_IMAGE # Uses GitLab's built-in registry variable

DOCKER_TAG: $CI_COMMIT_SHORT_SHA

# AWS_REGION: us-east-1 # Uncomment and configure if deploying to AWS

lint_job:

stage: lint

image: node:20-alpine

script:

- npm ci

- npm run lint # Assumes 'lint' script in package.json

rules:

- if: $CI_COMMIT_BRANCH

exists:

- package.json

test_job:

stage: test

image: node:20-alpine

script:

- npm ci

- npm test # Assumes 'test' script in package.json

# - npm run test:integration

rules:

- if: $CI_COMMIT_BRANCH

exists:

- package.json

build_and_push_image_job:

stage: build

image: docker:latest

services:

- docker:dind # Docker-in-Docker for building images

variables:

DOCKER_HOST: tcp://docker:23

devops_pipeline_generator.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
"); 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' import ReactDOM from 'react-dom/client' import App from './App' import './index.css' ReactDOM.createRoot(document.getElementById('root')!).render( ) "); 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' import './App.css' function App(){ return(

"+slugTitle(pn)+"

Built with PantheraHive BOS

) } export default App "); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e} .app{min-height:100vh;display:flex;flex-direction:column} .app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px} h1{font-size:2.5rem;font-weight:700} "); 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)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` ## Open in IDE Open the project folder in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- 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",'{ "name": "'+pn+'", "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vue-tsc -b && vite build", "preview": "vite preview" }, "dependencies": { "vue": "^3.5.13", "vue-router": "^4.4.5", "pinia": "^2.3.0", "axios": "^1.7.9" }, "devDependencies": { "@vitejs/plugin-vue": "^5.2.1", "typescript": "~5.7.3", "vite": "^6.0.5", "vue-tsc": "^2.2.0" } } '); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': resolve(__dirname,'src') } } }) "); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]} '); zip.file(folder+"tsconfig.app.json",'{ "compilerOptions":{ "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"], "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true, "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue", "strict":true,"paths":{"@/*":["./src/*"]} }, "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"] } '); zip.file(folder+"env.d.ts","/// "); zip.file(folder+"index.html"," "+slugTitle(pn)+"
"); 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' import { createPinia } from 'pinia' import App from './App.vue' import './assets/main.css' const app = createApp(App) app.use(createPinia()) app.mount('#app') "); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue"," "); 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} "); 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)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` Open in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- 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",'{ "name": "'+pn+'", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test" }, "dependencies": { "@angular/animations": "^19.0.0", "@angular/common": "^19.0.0", "@angular/compiler": "^19.0.0", "@angular/core": "^19.0.0", "@angular/forms": "^19.0.0", "@angular/platform-browser": "^19.0.0", "@angular/platform-browser-dynamic": "^19.0.0", "@angular/router": "^19.0.0", "rxjs": "~7.8.0", "tslib": "^2.3.0", "zone.js": "~0.15.0" }, "devDependencies": { "@angular-devkit/build-angular": "^19.0.0", "@angular/cli": "^19.0.0", "@angular/compiler-cli": "^19.0.0", "typescript": "~5.6.0" } } '); zip.file(folder+"angular.json",'{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "'+pn+'": { "projectType": "application", "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/'+pn+'", "index": "src/index.html", "browser": "src/main.ts", "tsConfig": "tsconfig.app.json", "styles": ["src/styles.css"], "scripts": [] } }, "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"} } } } } '); zip.file(folder+"tsconfig.json",'{ "compileOnSave": false, "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"]}, "references":[{"path":"./tsconfig.app.json"}] } '); zip.file(folder+"tsconfig.app.json",'{ "extends":"./tsconfig.json", "compilerOptions":{"outDir":"./dist/out-tsc","types":[]}, "files":["src/main.ts"], "include":["src/**/*.d.ts"] } '); zip.file(folder+"src/index.html"," "+slugTitle(pn)+" "); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from './app/app.config'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent, appConfig) .catch(err => console.error(err)); "); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; } "); 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'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = '"+pn+"'; } "); zip.file(folder+"src/app/app.component.html","

"+slugTitle(pn)+"

Built with PantheraHive BOS

"); 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} "); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes) ] }; "); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router'; export const routes: Routes = []; "); 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)+" Generated by PantheraHive BOS. ## Setup ```bash npm install ng serve # or: npm start ``` ## Build ```bash ng build ``` Open in VS Code with Angular Language Service extension. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local .angular/ "); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/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(" "):"# add dependencies here "; zip.file(folder+"main.py",src||"# "+title+" # Generated by PantheraHive BOS print(title+" loaded") "); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` ## Run ```bash python main.py ``` "); zip.file(folder+".gitignore",".venv/ __pycache__/ *.pyc .env .DS_Store "); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/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)+" "; zip.file(folder+"package.json",pkgJson); var fallback="const express=require("express"); const app=express(); app.use(express.json()); app.get("/",(req,res)=>{ res.json({message:""+title+" API"}); }); const PORT=process.env.PORT||3000; app.listen(PORT,()=>console.log("Server on port "+PORT)); "; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000 "); zip.file(folder+".gitignore","node_modules/ .env .DS_Store "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash npm install ``` ## Run ```bash npm run dev ``` "); } /* --- 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:" "+title+" "+code+" "; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */ *{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e} "); zip.file(folder+"script.js","/* "+title+" — scripts */ "); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Open Double-click `index.html` in your browser. Or serve locally: ```bash npx serve . # or python3 -m http.server 3000 ``` "); zip.file(folder+".gitignore",".DS_Store node_modules/ .env "); } /* ===== 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(/ {2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. Files: - "+app+".md (Markdown) - "+app+".html (styled HTML) "); } 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);}});}