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

Generate code to integrate with external APIs

API Integration Builder: Code Generation Deliverable (Step 1 of 2)

Workflow Description: Generate code to integrate with external APIs.

Step: collab → generate_code


1. Introduction

This deliverable provides comprehensive, production-ready code for integrating with an external API. As part of the "API Integration Builder" workflow, this step focuses on generating a robust, well-structured, and easily customizable API client in Python.

For demonstration purposes, we've designed this code to interact with a hypothetical "Product Management API." This allows us to showcase common API integration patterns such as GET (fetching data), POST (creating data), PUT (updating data), and DELETE (removing data), along with essential features like authentication, error handling, and logging.

The generated code is designed to be a strong foundation that you can adapt to your specific API and business logic.

2. Key Considerations for API Integration

Before diving into the code, it's important to understand the fundamental principles guiding robust API integration:

  • Authentication & Authorization: Securely access the API using appropriate credentials (API keys, OAuth tokens, etc.).
  • Error Handling: Gracefully manage network issues, invalid requests, server errors, and API-specific error responses.
  • Rate Limiting & Throttling: Respect API usage limits to prevent being blocked and ensure fair usage. (While not explicitly coded in this generic example, it's a critical consideration for production systems.)
  • Retry Mechanisms: Implement logic to re-attempt failed requests, especially for transient network issues.
  • Logging: Record API requests, responses, and errors for debugging, monitoring, and auditing.
  • Configuration Management: Separate sensitive credentials and changeable parameters from the core code.
  • Scalability & Performance: Design the integration to handle expected load and process data efficiently.
  • Data Validation: Ensure data sent to the API conforms to its requirements and validate responses where necessary.

3. Example Scenario: Product Management API

To provide a concrete example, we've structured the generated code around a hypothetical RESTful API for managing products.

Hypothetical API Details:

  • Base URL: https://api.example.com/v1 (configurable)
  • Authentication: API Key passed in the X-API-KEY header.
  • Data Format: JSON for both requests and responses.

Key Endpoints & Operations:

| Operation | HTTP Method | Endpoint | Description | Request Body (Example) | Response Body (Example) |

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

| Get All Products | GET | /products | Retrieves a list of all products. | None | [{"id": "prod_123", "name": "Laptop", "price": 1200.00, "category": "Electronics"}, ...] |

| Get Product by ID | GET | /products/{id} | Retrieves a single product by its ID. | None | {"id": "prod_123", "name": "Laptop", "price": 1200.00, "category": "Electronics"} |

| Create Product | POST | /products | Creates a new product. | {"name": "New Product", "price": 99.99, "category": "General"} | {"id": "prod_456", "name": "New Product", "price": 99.99, "category": "General"} |

| Update Product | PUT | /products/{id} | Updates an existing product. | {"name": "Updated Product Name", "price": 109.99} | {"id": "prod_123", "name": "Updated Product Name", "price": 109.99, "category": "Electronics"} |

| Delete Product | DELETE | /products/{id} | Deletes a product by its ID. | None | {"message": "Product prod_123 deleted successfully"} (or HTTP 204 No Content) |

| Error Response | N/A | N/A | Generic error structure. | N/A | {"status": 404, "error": "Not Found", "message": "Product with ID prod_xyz not found."} or {"status": 400, "error": "Bad Request", "message": "Invalid input data."} (Note: This is a common pattern, but actual API error structures vary.) |

4. Generated Code (Python)

Below is the Python code for a ProductAPIClient class, which encapsulates the logic for interacting with our hypothetical Product Management API.


import requests
import json
import logging
import os
from typing import Dict, Any, List, Optional

# --- Configuration ---
# It's recommended to manage sensitive information like API keys via environment variables
# or a secure configuration management system (e.g., AWS Secrets Manager, HashiCorp Vault).
# For demonstration, we'll try to load from environment or use a placeholder.
API_BASE_URL = os.getenv("PRODUCT_API_BASE_URL", "https://api.example.com/v1")
API_KEY = os.getenv("PRODUCT_API_KEY", "YOUR_SECRET_API_KEY") # REPLACE WITH YOUR ACTUAL API KEY

# --- Logging Setup ---
# Configure logging for better visibility into API interactions and potential issues.
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# --- Custom Exception for API Errors ---
class APIIntegrationError(Exception):
    """Custom exception for API-related errors."""
    def __init__(self, message: str, status_code: Optional[int] = None, api_response: Optional[Dict] = None):
        super().__init__(message)
        self.status_code = status_code
        self.api_response = api_response

    def __str__(self):
        details = f"Status Code: {self.status_code}" if self.status_code else "N/A"
        if self.api_response:
            details += f", API Response: {json.dumps(self.api_response)}"
        return f"APIIntegrationError: {self.args[0]} ({details})"

# --- API Client Class ---
class ProductAPIClient:
    """
    A client for interacting with the Product Management API.

    Handles API requests, responses, authentication, and error handling.
    """

    def __init__(self, base_url: str, api_key: str, timeout: int = 30):
        """
        Initializes the ProductAPIClient.

        Args:
            base_url (str): The base URL of the Product Management API (e.g., "https://api.example.com/v1").
            api_key (str): The API key for authentication.
            timeout (int): Default timeout for API requests in seconds.
        """
        if not base_url or not api_key:
            raise ValueError("Base URL and API Key must be provided.")

        self.base_url = base_url
        self.api_key = api_key
        self.timeout = timeout
        self.headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "X-API-KEY": self.api_key  # Example: API Key in a custom header
        }
        logger.info(f"ProductAPIClient initialized with base_url: {self.base_url}")

    def _make_request(self, method: str, endpoint: str, params: Optional[Dict] = None, data: Optional[Dict] = None) -> Any:
        """
        Internal helper method to make an HTTP request to the API.

        Args:
            method (str): HTTP method (GET, POST, PUT, DELETE).
            endpoint (str): The API endpoint relative to the base URL (e.g., "/products").
            params (Optional[Dict]): Dictionary of query parameters.
            data (Optional[Dict]): Dictionary of request body data (for POST/PUT).

        Returns:
            Any: Parsed JSON response from the API.

        Raises:
            APIIntegrationError: If the API request fails or returns an error status.
        """
        url = f"{self.base_url}{endpoint}"
        logger.debug(f"Making {method} request to: {url}")
        logger.debug(f"Headers: {self.headers}")
        if params:
            logger.debug(f"Params: {params}")
        if data:
            logger.debug(f"Payload: {json.dumps(data)}")

        try:
            response = requests.request(
                method,
                url,
                headers=self.headers,
                params=params,
                json=data, # Use 'json' parameter for automatic JSON serialization
                timeout=self.timeout
            )
            response.raise_for_status()  # Raises HTTPError for bad responses (4xx or 5xx)

            # Attempt to parse JSON, even for successful responses that might be empty or non-JSON
            try:
                if response.content: # Check if there's content before trying to parse JSON
                    return response.json()
                else:
                    return None # No content, e.g., for 204 No Content
            except json.JSONDecodeError:
                logger.warning(f"Response content is not valid JSON for {url}. Content: {response.text}")
                return response.text # Return raw text if not JSON

        except requests.exceptions.HTTPError as e:
            error_details = {"status": e.response.status_code, "error": str(e)}
            try:
                api_response_json = e.response.json()
                error_details.update(api_response_json) # Merge API's error details
                error_message = api_response_json.get("message", f"API error for {endpoint}")
            except json.JSONDecodeError:
                error_message = f"API error for {endpoint}: {e.response.text}"
            logger.error(f"HTTP Error {e.response.status_code} for {url}: {error_message}")
            raise APIIntegrationError(
                message=error_message,
                status_code=e.response.status_code,
                api_response=error_details
            ) from e
        except requests.exceptions.ConnectionError as e:
            logger.error(f"Connection Error to {url}: {e}")
            raise APIIntegrationError(f"Network connection error: {e}") from e
        except requests.exceptions.Timeout as e:
            logger.error(f"Timeout Error for {url}: {e}")
            raise APIIntegrationError(f"Request timed out after {self.timeout} seconds: {e}") from e
        except requests.exceptions.RequestException as e:
            logger.error(f"An unexpected request error occurred for {url}: {e}")
            raise APIIntegrationError(f"An unexpected request error occurred: {e}") from e
        except Exception as e:
            logger.critical(f"An unhandled error occurred during API request for {url}: {e}", exc_info=True)
            raise APIIntegrationError(f"An unhandled internal error occurred: {e}") from e

    # --- Product-specific API Methods ---

    def get_all_products(self, limit: Optional[int] = None, offset: Optional[int] = None) -> List[Dict]:
        """
        Retrieves a list of all products.

        Args:
            limit (Optional[int]): Max number of products to return.
            offset (Optional[int]): Number of products to skip.

        Returns:
            List[Dict]: A list of product dictionaries.
        """
        endpoint = "/products"
        params = {}
        if limit is not None:
            params["limit"] = limit
        if offset is not None:
            params["offset"] = offset

        logger.info("Fetching all products...")
        response = self._make_request("GET", endpoint, params=params)
        return response if isinstance(response, list) else [] # Ensure it's a list

    def get_product_by_id(self, product_id: str) -> Dict:
        """
        Retrieves a single product by its ID.

        Args:
            product_id (str): The ID of the product to retrieve.

        Returns:
            Dict: A dictionary representing the product.

        Raises:
            APIIntegrationError: If the product is not found or another API error occurs.
        """
        endpoint = f"/products/{product_id}"
        logger.info(f"Fetching product with ID: {product_id}")
        response = self._make_request("GET", endpoint)
        return response if isinstance(response, dict) else {} # Ensure it's a dict

    def create_product(self, product_data: Dict) -> Dict:
        """
        Creates a new product.

        Args:
            product_data (Dict): A dictionary containing the product's details
                                 (e.g., {"name": "Laptop", "price": 1200.00, "category": "Electronics"}).

        Returns:
            Dict: A dictionary representing the newly created product, including its ID.
        """
        endpoint = "/products"
        logger.info(f"Creating product: {product_data.get('name', 'N/A')}")
        response = self._make_request("POST", endpoint, data=product_data)
        return response if isinstance(response, dict) else {}

    def update_product(self, product_id: str, product_data: Dict) -> Dict:
        """
        Updates an existing product.

        Args:
            product_id (str): The ID of the product to update.
            product_data (Dict): A dictionary containing the updated product details.
                                 Only fields to be updated need to be included.

        Returns:
            Dict: A dictionary representing the updated product.
        """
        endpoint = f"/products/{product_id}"
        logger.info(f"Updating product ID {product_id} with data: {product_data}")
        response = self._make_request("PUT", endpoint, data=product_data)
        return response if isinstance(response, dict) else {}

    def delete_product(self, product_id: str) -> None:
        """
        Deletes a product by its ID.

        Args:
            product_id (str): The ID of the
projectmanager Output

API Integration Project: Initiation Confirmation & Next Steps

Project Status: Initiated

Workflow Step: projectmanager → create_project

Description: API Integration Project Setup


We are pleased to confirm that your API Integration Project has been successfully initiated. This foundational step marks the beginning of leveraging external APIs to enhance your systems, automate workflows, and unlock new capabilities.

This document outlines the scope of this project, the immediate next steps required from your end, and how we will proceed to generate the specific code for your desired API integration.

1. Project Overview: API Integration Builder

The "API Integration Builder" project is designed to provide you with robust, scalable, and maintainable code for integrating with various external APIs. Our goal is to streamline the development process, minimize manual effort, and ensure a secure and efficient connection between your applications and third-party services.

Key Benefits of this Project:

  • Accelerated Development: Rapid generation of API client code.
  • Reduced Complexity: Abstracting away the intricacies of API communication.
  • Consistency & Maintainability: Standardized, well-documented code structure.
  • Enhanced Functionality: Seamlessly connect to external services for data exchange, automation, and extended features.

2. General Phases of API Integration

While your specific integration will have unique requirements, the overall process typically follows these structured phases:

  1. Requirements Gathering & API Discovery:

* Identify the target API (e.g., Salesforce, Stripe, Shopify, custom REST API).

* Define specific integration goals (e.g., create a customer, fetch order details, sync product inventory).

* Understand the API's authentication, rate limits, and data structures.

  1. Design & Planning:

* Architectural considerations (e.g., direct integration, middleware, event-driven).

* Error handling strategies, logging, and monitoring.

* Security best practices.

  1. Code Generation & Development:

* Generate API client code based on specified requirements.

* Implement logic for data transformation, request/response handling, and error management.

* Integrate with your existing application codebase.

  1. Testing & Validation:

* Unit tests for individual API calls.

* Integration tests to ensure end-to-end functionality.

* Performance and load testing (if applicable).

  1. Deployment & Monitoring:

* Deployment to development, staging, and production environments.

* Implement monitoring tools for API health, performance, and error tracking.

  1. Maintenance & Updates:

* Handle API version changes, deprecations, and new features.

* Ongoing support and enhancements.

3. Immediate Next Steps: Your Input Required for Code Generation

To move forward from project initiation to generating the specific integration code, we require detailed information about your target API and integration objectives. Please provide the following:

3.1. Target API Details

  • API Name: The name of the external API you wish to integrate with (e.g., "Stripe API," "Salesforce REST API," "YourCompany's Internal Microservice API").
  • API Documentation: A direct link to the official API documentation (e.g., OpenAPI/Swagger specification, developer portal URL). This is crucial for accurate code generation.
  • Base URL(s): The base URL for the API's development/staging and production environments (e.g., https://api.example.com/v1).

3.2. Integration Goals & Functionality

  • Specific Endpoints/Operations: List the exact API endpoints and operations you need to interact with. Be as precise as possible.

Example 1:* "Create a new customer (POST /customers)"

Example 2:* "Retrieve an order by ID (GET /orders/{id})"

Example 3:* "Update product inventory (PUT /products/{id}/inventory)"

Example 4:* "Listen for webhook events (POST /webhooks/stripe)"

  • Data Fields: For each operation, specify the key data fields you expect to send or receive. If integrating with an existing system, provide mapping details.
  • Use Cases: Describe the business use cases driving this integration. This helps us understand the context and optimize the solution.

3.3. Technical Preferences

  • Programming Language: Your preferred programming language for the integration code (e.g., Python, Node.js, Java, C#, Go, PHP, Ruby).
  • Framework/Library (Optional): If you have a specific framework or library preference (e.g., Express.js for Node.js, Spring Boot for Java, Django/Flask for Python).
  • Authentication Method: How does the API authenticate requests? (e.g., API Key, OAuth 2.0, Bearer Token, Basic Authentication, JWT). Please specify the grant type if using OAuth.
  • Error Handling: Any specific requirements for error handling, logging, or retry mechanisms.
  • Idempotency: Are there any operations that require idempotency handling?
  • Rate Limiting: Any specific requirements or strategies for managing API rate limits.

4. Deliverables from this Step

At this stage, we have successfully:

  • Initiated your API Integration Project.
  • Established the framework for detailed requirements gathering.
  • Prepared to generate tailored integration code once your inputs are received.

5. Call to Action

To proceed with the development of your API integration code, please compile and submit the information requested in Section 3: Immediate Next Steps.

You can reply to this message with the details, or if you prefer a more interactive session, please let us know your availability to schedule a dedicated requirements gathering call.

6. Support & Assistance

Should you have any questions or require clarification on any of the requested information, please do not hesitate to reach out to your dedicated project manager or our support team. We are here to assist you every step of the way.


We look forward to receiving your input and moving to the next exciting phase of building your API integration!

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