API Integration Builder
Run ID: 69ccf48f3e7fb09ff16a69502026-04-01Development
PantheraHive BOS
BOS Dashboard

Generate code to integrate with external APIs

API Integration Builder - Step 1 of 2: Code Generation

This deliverable provides a foundational, production-ready Python code template designed for robust and secure integration with external RESTful APIs. This code emphasizes best practices in API interaction, including secure authentication, comprehensive error handling, automatic retries, and clear modularity. It serves as a strong starting point that you can adapt and extend for your specific API integration needs.


1. Introduction and Purpose

The goal of this step is to furnish you with a versatile and well-structured API client. This client is built to handle common challenges in API integration, allowing you to focus on the business logic rather than the intricacies of HTTP requests, retries, and error parsing.

Key Features of the Generated Code:

  • Modularity: Encapsulated in a GenericAPIClient class for reusability.
  • Authentication: Flexible handling for API keys, Bearer tokens, or custom headers.
  • Robust Error Handling: Catches common HTTP errors and network issues, raising specific exceptions.
  • Automatic Retries: Implements exponential backoff for transient failures.
  • Configurability: Easy to set base URLs, timeouts, and retry parameters.
  • Production-Ready: Includes comments, type hints, and follows Python best practices.

2. Core Concepts for Robust API Integration

Before diving into the code, understanding these core concepts will help you leverage and customize the generated client effectively:

  • HTTP Client Library: A reliable library (e.g., requests in Python) simplifies making HTTP requests.
  • Authentication: Different APIs use various methods (API Keys, OAuth 2.0, Basic Auth, etc.). Securely manage and transmit credentials.
  • Error Handling: Anticipate and gracefully handle various HTTP status codes (4xx for client errors, 5xx for server errors) and network issues.
  • Retry Mechanisms: Implement logic to automatically retry failed requests, especially for transient network errors or temporary service unavailability, often with exponential backoff.
  • Rate Limiting: Respect the API provider's limits on the number of requests you can make within a certain timeframe to avoid being blocked.
  • Logging: Crucial for debugging, monitoring, and auditing API interactions in production.
  • Configuration Management: Externalize sensitive information (API keys, secrets) and changeable parameters (base URLs, timeouts) from your codebase.

3. Generated Code: GenericAPIClient (Python)

Below is the Python code for a GenericAPIClient class, built using the popular requests library.

Dependencies:

To run this code, you need to install the requests library:

pip install requests


import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import os
import json
from typing import Dict, Any, Optional, Union

# --- Custom Exception Classes ---
class APIClientError(Exception):
    """Base exception for API client errors."""
    def __init__(self, message: str, status_code: Optional[int] = None, response_data: Optional[Any] = None):
        super().__init__(message)
        self.status_code = status_code
        self.response_data = response_data

class APIAuthenticationError(APIClientError):
    """Raised for 401 Unauthorized or 403 Forbidden errors."""
    pass

class APIRateLimitError(APIClientError):
    """Raised for 429 Too Many Requests errors."""
    pass

class APIServerError(APIClientError):
    """Raised for 5xx server errors."""
    pass

class APIValidationError(APIClientError):
    """Raised for 400 Bad Request or 422 Unprocessable Entity errors."""
    pass

# --- Generic API Client Class ---
class GenericAPIClient:
    """
    A generic and robust API client for interacting with RESTful services.

    Handles authentication, retries with exponential backoff, and comprehensive
    error handling for common HTTP status codes.
    """

    def __init__(
        self,
        base_url: str,
        api_key: Optional[str] = None,
        auth_token: Optional[str] = None,
        headers: Optional[Dict[str, str]] = None,
        timeout: int = 30,
        retries: int = 3,
        backoff_factor: float = 0.3,
        status_forcelist: tuple = (429, 500, 502, 503, 504),
    ):
        """
        Initializes the GenericAPIClient.

        Args:
            base_url (str): The base URL of the API (e.g., "https://api.example.com/v1").
            api_key (str, optional): An API key for 'x-api-key' or similar header.
                                     If provided, overrides 'Authorization' header if both
                                     api_key and auth_token are given.
            auth_token (str, optional): A Bearer token for 'Authorization' header.
            headers (Dict[str, str], optional): Additional custom headers to send with requests.
            timeout (int): Default timeout for requests in seconds.
            retries (int): Number of times to retry failed requests.
            backoff_factor (float): Factor for exponential backoff between retries.
            status_forcelist (tuple): HTTP status codes that will trigger a retry.
        """
        if not base_url:
            raise ValueError("base_url cannot be empty.")

        self.base_url = base_url.rstrip('/') # Ensure no trailing slash for consistent path joining
        self.timeout = timeout

        self.session = requests.Session()
        self._configure_session_retries(retries, backoff_factor, status_forcelist)

        # Set default headers
        self.headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
        }
        if headers:
            self.headers.update(headers)

        # Handle authentication
        if api_key:
            self.headers["X-API-KEY"] = api_key # Common header for API keys
        elif auth_token:
            self.headers["Authorization"] = f"Bearer {auth_token}"

        self.session.headers.update(self.headers)


    def _configure_session_retries(self, retries: int, backoff_factor: float, status_forcelist: tuple):
        """Configures the requests session with retry logic."""
        retry_strategy = Retry(
            total=retries,
            read=retries,
            connect=retries,
            backoff_factor=backoff_factor,
            status_forcelist=status_forcelist,
            allowed_methods=frozenset(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']), # Retry all common methods
            raise_on_status=False # Don't raise on status, let our error handler do it
        )
        adapter = HTTPAdapter(max_retries=retry_strategy)
        self.session.mount("http://", adapter)
        self.session.mount("https://", adapter)

    def _send_request(
        self,
        method: str,
        endpoint: str,
        data: Optional[Union[Dict, str]] = None,
        params: Optional[Dict[str, Any]] = None,
        json_payload: Optional[Dict[str, Any]] = None,
        files: Optional[Dict[str, Any]] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> Any:
        """
        Sends an HTTP request to the API.

        Args:
            method (str): The HTTP method (GET, POST, PUT, DELETE).
            endpoint (str): The API endpoint (e.g., "/users", "/products/123").
            data (Union[Dict, str], optional): Dictionary or string of data to send in the request body.
                                                Used for `application/x-www-form-urlencoded` or raw body.
            params (Dict[str, Any], optional): Dictionary of query parameters.
            json_payload (Dict[str, Any], optional): Dictionary to be sent as JSON in the request body.
            files (Dict[str, Any], optional): Dictionary of files to upload.
            headers (Dict[str, str], optional): Additional headers for this specific request.

        Returns:
            Any: The JSON response from the API, or raw text if not JSON.

        Raises:
            APIClientError: For various API interaction failures.
        """
        url = f"{self.base_url}/{endpoint.lstrip('/')}"
        request_headers = self.session.headers.copy()
        if headers:
            request_headers.update(headers)

        try:
            response = self.session.request(
                method,
                url,
                params=params,
                data=data,
                json=json_payload,
                files=files,
                headers=request_headers,
                timeout=self.timeout
            )
            response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)

            # Attempt to parse JSON, fall back to text if not JSON
            try:
                return response.json()
            except json.JSONDecodeError:
                return response.text

        except requests.exceptions.HTTPError as e:
            status_code = e.response.status_code
            response_data = None
            try:
                response_data = e.response.json()
            except json.JSONDecodeError:
                response_data = e.response.text

            message = f"API request failed with status {status_code}: {e.response.reason}"
            if response_data and isinstance(response_data, dict) and 'message' in response_data:
                message = response_data['message']

            if status_code == 400:
                raise APIValidationError(message, status_code, response_data) from e
            elif status_code == 401 or status_code == 403:
                raise APIAuthenticationError(message, status_code, response_data) from e
            elif status_code == 404:
                raise APIClientError(f"Resource not found: {endpoint}", status_code, response_data) from e
            elif status_code == 422: # Unprocessable Entity
                raise APIValidationError(message, status_code, response_data) from e
            elif status_code == 429:
                raise APIRateLimitError(message, status_code, response_data) from e
            elif 500 <= status_code < 600:
                raise APIServerError(message, status_code, response_data) from e
            else:
                raise APIClientError(message, status_code, response_data) from e

        except requests.exceptions.ConnectionError as e:
            raise APIClientError(f"Network connection error: {e}", response_data=str(e)) from e
        except requests.exceptions.Timeout as e:
            raise APIClientError(f"Request timed out after {self.timeout} seconds: {e}", response_data=str(e)) from e
        except requests.exceptions.RequestException as e:
            raise APIClientError(f"An unexpected request error occurred: {e}", response_data=str(e)) from e
        except Exception as e:
            raise APIClientError(f"An unexpected
projectmanager Output

API Integration Builder: Project Creation Automation (Step 2 of 2)

Project Deliverable: Automated Project Setup via Integrated APIs


1. Introduction and Overview

This document serves as the comprehensive guide for leveraging the newly developed API integrations to streamline and automate your project creation process. The "API Integration Builder" workflow has successfully established robust connections with key external platforms, enabling a unified and efficient approach to setting up new projects.

This deliverable empowers Project Managers to initiate projects with pre-configured resources, standardizing the setup process, reducing manual effort, and ensuring consistency across all new initiatives.

2. Summary of Integrated APIs for Project Creation

The following external APIs have been successfully integrated and are now available to automate various aspects of project setup:

  • Project Management System (e.g., Jira, Asana, Monday.com):

* Integration Purpose: Automatic creation of a new project instance, including key metadata (name, description, lead, start/end dates).

* Key Functionality: Project board/space initialization.

  • Version Control System (e.g., GitHub, GitLab, Bitbucket):

* Integration Purpose: Automated repository creation for source code management.

* Key Functionality: Repository naming, initial README file, default branching strategy.

  • Communication Platform (e.g., Slack, Microsoft Teams):

* Integration Purpose: Creation of a dedicated communication channel for the project team.

* Key Functionality: Channel naming, basic introductory message, optional team member invitation.

  • Document Management System (e.g., Google Drive, SharePoint, Confluence):

* Integration Purpose: Automatic creation of a structured folder for project documentation.

* Key Functionality: Pre-defined folder structure (e.g., "Requirements," "Design," "Meeting Notes," "Deliverables"), shared access configuration.

3. Key Benefits for Project Managers

Leveraging these integrations for project creation offers significant advantages:

  • Accelerated Setup: Drastically reduce the time spent on manual setup across multiple platforms.
  • Standardization & Consistency: Ensure every new project adheres to predefined templates and configurations, minimizing errors and improving quality.
  • Reduced Manual Effort: Eliminate repetitive administrative tasks, allowing PMs to focus on strategic planning and execution.
  • Improved Compliance: Automatically apply required access controls and folder structures, aligning with organizational policies.
  • Enhanced Visibility: Centralized initiation ensures all relevant systems are updated simultaneously, providing a holistic view from day one.
  • Onboarding Efficiency: New team members can quickly access all project resources from a single point of reference.

4. Actionable Guide: How to Create a Project Using Integrated APIs

This section provides a step-by-step guide for Project Managers to utilize the API integrations for automated project creation.

4.1. Prerequisites and Access

Before initiating a new project, ensure the following:

  • Access Credentials: Confirm you have the necessary permissions and API keys (if applicable) for the integrated systems. These are typically managed centrally, but awareness is key.
  • Template Configuration: Review and understand the default project templates and configurations for each integrated system (e.g., Jira project type, GitHub default branch).
  • Required Input Data: Gather all necessary project details as outlined in Section 4.3.

4.2. Workflow for Automated Project Creation

The automated project creation process follows these steps:

  1. Initiation Point: Access the designated interface or script designed to trigger the automated project creation. This could be a custom web form, an internal tool, or a command-line script.

(Example: Navigate to [Your Internal Project Portal URL] or execute python create_project.py)*

  1. Input Project Details: Provide the required project information (see Section 4.3) into the interface.
  2. Review & Confirm: A summary of the project details and the actions to be taken across the integrated systems will be presented for your review.
  3. Execute Automation: Confirm the details to trigger the backend automation.
  4. Monitor Progress: The system will process the creation requests across all integrated APIs. You will receive real-time updates or a final status report.
  5. Verification: Upon completion, verify that all resources have been created correctly in their respective platforms.

4.3. Required Project Input Data

To successfully create a project using the integrated APIs, you will typically need to provide the following information:

  • Project Name: (e.g., "Website Redesign Phase 2," "Mobile App Feature X")

Used for:* Project Management System, Version Control, Communication Channel, Document Folder.

  • Project Code/Key (Optional but Recommended): A short, unique identifier.

Used for:* Project Management System (e.g., JIRA key).

  • Project Description: A brief overview of the project's goals and scope.

Used for:* Project Management System, Version Control (README), Communication Channel (intro).

  • Project Lead/Owner: The primary person responsible for the project.

Used for:* Project Management System (assignee), Communication Channel (initial admin).

  • Start Date:

Used for:* Project Management System.

  • Target End Date:

Used for:* Project Management System.

  • Team Members (Optional): List of individuals to be invited to the project.

Used for:* Communication Channel, Document Management (shared access).

  • Project Template (Optional, if multiple exist): Selection of a specific project template if different configurations are available.

4.4. Expected Outcomes and Verification Steps

Upon successful execution, you should observe the following:

  • Project Management System:

* A new project dashboard/space named [Project Name] with [Project Lead] assigned.

* Initial project settings (start/end dates, description) configured.

(Verification: Log into Jira/Asana/Monday.com and confirm the project exists.)*

  • Version Control System:

* A new repository named [project-name-slug] (or similar) under the designated organization/group.

* An initial README.md file with the project description.

(Verification: Log into GitHub/GitLab/Bitbucket and confirm the repository's existence and initial content.)*

  • Communication Platform:

* A new channel named #project-name-slug (or similar) created.

* An introductory message posted in the channel.

* Invited team members (if specified) added to the channel.

(Verification: Check Slack/Teams for the new channel and its members.)*

  • Document Management System:

* A new top-level folder [Project Name] created in the specified location.

* Pre-defined subfolders (e.g., "Requirements," "Design") within the main folder.

* Shared access permissions configured for specified team members.

(Verification: Navigate to Google Drive/SharePoint and confirm the folder structure and access rights.)*

5. Customization and Extension

The current API integrations provide a robust foundation. Future enhancements could include:

  • Conditional Logic: Implement rules for different project types (e.g., create a different set of repos for a software project vs. a marketing campaign).
  • Resource Provisioning: Integrate with cloud providers (AWS, Azure, GCP) to automatically provision development environments or databases.
  • Billing & ERP Integration: Register new projects in financial systems for cost tracking and invoicing.
  • Advanced Templating: Offer more granular control over templates for each integrated system directly from the project creation interface.
  • Webhook Notifications: Configure notifications to other systems or stakeholders upon successful project creation.

6. Support and Next Steps

  • Technical Support: For any issues or questions regarding the functionality or performance of the API integrations, please contact the IT/Development team at [Support Email/Channel].
  • Feedback & Enhancements: We encourage Project Managers to provide feedback on this automated process. Your input is invaluable for continuous improvement. Please submit suggestions via [Feedback Form/System].
  • Training & Documentation: Additional training sessions or detailed documentation on specific system configurations can be provided upon request.

This concludes the "API Integration Builder" workflow, providing you with a powerful tool for efficient project management. We are confident this automation will significantly enhance your operational efficiency and project consistency.

api_integration_builder.md
Download as Markdown
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);}});}