API Documentation Generator
Run ID: 69cc798f3e7fb09ff16a23b82026-04-01Development
PantheraHive BOS
BOS Dashboard

Architecture Plan: API Documentation Generator

This document outlines the architectural plan for a robust and professional API Documentation Generator. The goal is to create a system that can ingest various API definitions, process them, and generate comprehensive, user-friendly, and interactive documentation, suitable for both developers and business stakeholders.


1. Introduction and Architectural Goals

The API Documentation Generator aims to streamline the process of creating and maintaining high-quality API documentation. Key architectural goals include:


2. High-Level Architecture Overview

The system will be structured into three primary layers: Input Layer, Core Processing Layer, and Output Layer, orchestrated by a Command-Line Interface (CLI) or Web-based UI.

mermaid • 690 chars
graph TD
    A[User/CLI/Web UI] --> B(Configuration & Orchestration)
    B --> C(Input Layer)
    C --> D(Core Processing Layer)
    D --> E(Output Layer)
    E --> F[Generated Documentation]

    subgraph Input Layer
        C1[API Definition Parsers]
        C2[Schema Validators]
    end

    subgraph Core Processing Layer
        D1[Internal Data Model]
        D2[Content Enrichment Modules]
        D3[Templating Engine]
    end

    subgraph Output Layer
        E1[Output Format Renderers]
        E2[Theming & Styling]
        E3[Navigation & Search Indexers]
    end

    C --> C1
    C1 --> C2
    C2 --> D1
    D1 --> D2
    D2 --> D3
    D3 --> E1
    E1 --> E2
    E2 --> E3
Sandboxed live preview

3. Detailed Component Breakdown

3.1. Input Layer: API Definition Ingestion

This layer is responsible for consuming API definitions from various sources and converting them into a standardized internal data model.

  • API Definition Parsers:

* Purpose: Read and parse different API definition formats.

* Supported Formats (Initial Focus):

* OpenAPI/Swagger (v2.0, v3.0, v3.1): JSON and YAML formats.

* Postman Collections (v2.1): For broader compatibility and existing definitions.

* Extensibility: Designed with an interface to easily add new parsers for formats like RAML, API Blueprint, etc.

* Error Handling: Robust error reporting for malformed or invalid input files.

  • Schema Validators:

* Purpose: Validate the parsed API definition against its respective schema (e.g., OpenAPI Schema).

* Benefits: Ensures the input is syntactically correct and adheres to the standard, preventing downstream processing errors.

* Feedback: Provide clear validation errors to the user.

3.2. Core Processing Layer: Data Model & Transformation

This layer sits at the heart of the generator, holding the canonical representation of the API and applying transformations and enrichments.

  • Internal Data Model (IDM):

* Purpose: A unified, language-agnostic, and technology-agnostic representation of the API definition. This decouples the input format from the output generation.

* Structure: Hierarchical model representing APIs, endpoints, methods, parameters, request bodies, responses, schemas, authentication schemes, tags, etc.

* Normalization: All input formats are normalized into this IDM.

  • Content Enrichment Modules:

* Purpose: Add, modify, or enhance information within the IDM that might not be explicitly present in the raw API definition.

* Key Modules:

* Example Generator: Automatically generate realistic request/response examples based on defined schemas (e.g., using Faker libraries or example fields in OpenAPI).

* SDK Usage Example Integrator:

* Option A (Static): Pull pre-written SDK code snippets from a specified repository or configuration.

* Option B (Dynamic - advanced): If an SDK generation step is part of a broader workflow, this module could integrate directly with generated SDKs to fetch or create usage examples.

* Markdown/Rich Text Renderer: Convert any embedded Markdown in descriptions (e.g., in OpenAPI description fields) into the appropriate internal representation.

* Authentication Guide Builder: Generate standardized explanations and code examples for various authentication methods (API Key, OAuth2, Bearer Token) based on the security schemes defined in the IDM.

  • Templating Engine:

* Purpose: Provide a mechanism to render the IDM into various output formats using predefined templates.

* Technology Consideration: Liquid, Handlebars, Jinja2, or a similar logic-less or minimalistic templating engine.

* Template Sets: Manage different sets of templates for various output styles or formats.

3.3. Output Layer: Documentation Generation & Publishing

This layer is responsible for transforming the processed IDM into the final documentation artifacts.

  • Output Format Renderers:

* Purpose: Generate documentation in different formats.

* Supported Formats (Initial Focus):

* Static HTML: Highly optimized for web browsers, including responsiveness.

* Markdown: For easy integration into developer portals, wikis, or other Markdown-based systems.

* PDF: For print-friendly versions or offline distribution.

* Extensibility: Interface for adding new renderers (e.g., Confluence Wiki Markup, custom XML).

  • Theming & Styling Engine:

* Purpose: Apply visual themes and styles to the generated documentation.

* Features:

* Default Themes: A set of professional, responsive themes.

* Custom Theming: Allow users to provide custom CSS, JavaScript, and even override specific template partials.

* Branding: Options for logo, color schemes, and fonts.

  • Navigation & Search Indexers:

* Purpose: Create a navigable structure and enable efficient search within the generated documentation.

* Features:

* Table of Contents (TOC): Dynamically generated based on API structure.

* Search Index: Generate a client-side search index (e.g., using Lunr.js or similar) for static HTML output.

* Categorization: Group endpoints by tags, paths, or custom categories.

  • Publishing/Deployment Integrations:

* Purpose: Facilitate the deployment of generated documentation.

* Features:

* Local File System: Output to a specified directory.

* Static Site Hosting: Integration/instructions for deploying to platforms like Netlify, GitHub Pages, AWS S3, etc.

* CI/CD Hooks: Designed to be easily integrated into automated build pipelines.

3.4. User Interface / Orchestration Layer

This layer provides the entry point for users to interact with the generator.

  • Command-Line Interface (CLI):

* Purpose: Primary interface for developers and CI/CD pipelines.

* Features:

* Configuration Management: Load configuration from files (YAML, JSON), environment variables, or CLI arguments.

* Generation Commands: generate, validate, init (for project setup).

* Verbose Logging: Detailed output for debugging.

  • Configuration Management:

* Purpose: Define generation parameters, input files, output paths, theme settings, and content enrichment options.

* Format: YAML or JSON files for easy human readability and version control.


4. Key Features Mapping to Architecture

  • Endpoint Descriptions: Directly sourced from the IDM (parsed from description fields in OpenAPI) and rendered via the Templating Engine.
  • Request/Response Examples: Generated by the "Example Generator" module within the Core Processing Layer, then injected into the IDM and rendered.
  • Authentication Guides: Created by the "Authentication Guide Builder" module, providing dynamic explanations and examples based on the security schemes in the IDM.
  • SDK Usage Examples: Integrated by the "SDK Usage Example Integrator" module, either by fetching static snippets or by interacting with a dynamic SDK generation process.
  • Interactive "Try-it-out" Functionality (for HTML output):

* Architecture Implication: The Output Layer's HTML Renderer will include client-side JavaScript that leverages the API definition (potentially embedded or fetched) to construct HTTP requests and display responses directly in the browser. This requires careful handling of CORS and authentication.

  • Version Control Integration: The CLI and configuration files are designed to be managed and tracked within Git or other VCS. The generated output can also be committed back if desired.

5. Technology Stack Considerations

  • Primary Programming Language: Python or TypeScript/Node.js are strong candidates due to their rich ecosystems for parsing, templating, and static site generation.

* Python: Excellent for data processing, YAML/JSON handling, and has libraries like PyYAML, jsonschema, Jinja2.

* TypeScript/Node.js: Strong for web-based outputs, client-side interactivity, and has libraries like yaml, json-schema, Handlebars.js, react-static or next.js for advanced output.

  • Parsing Libraries:

* For OpenAPI: swagger-parser (JS), openapi-spec-validator (Python), pyyaml.

  • Templating Engine: Jinja2 (Python) or Handlebars.js (JS/TS) for flexible and powerful rendering.
  • Static Site Generation (for HTML output): Potentially integrate with or build upon frameworks like Jekyll, Hugo, Docusaurus, or Sphinx for robust static site features, though a custom renderer offers maximum control.
  • Front-end Libraries (for interactive HTML): React, Vue, or vanilla JavaScript for "Try-it-out" functionality and dynamic navigation.
  • CLI Framework: Click (Python) or Commander.js (JS/TS) for building a user-friendly CLI.

6. Scalability and Extensibility

  • Plugin Architecture: Design core components (parsers, enrichers, renderers) as pluggable modules. This allows users to extend the generator without modifying its core codebase.

* Hooks: Provide well-defined extension points for custom logic.

  • Configuration-driven: Most behaviors should be configurable through external files rather than requiring code changes.
  • Modular Codebase: Adhere to SOLID principles and clear separation of concerns to facilitate future expansion.

7. Security Considerations

  • Input Validation: Strictly validate all input API definitions to prevent injection vulnerabilities or processing of malicious content.
  • Output Sanitization: Ensure any user-provided content (e.g., descriptions) is properly sanitized before being embedded in the generated HTML to prevent XSS attacks.
  • Dependency Management: Regularly update and audit third-party libraries for known vulnerabilities.

8. Deployment and Operations

  • Containerization: Provide Docker images for easy deployment and consistent execution across different environments.
  • CI/CD Integration: Design the CLI to be easily callable within automated build and deployment pipelines (e.g., GitHub Actions, GitLab CI, Jenkins).
  • Configuration as Code: Encourage storing generator configurations alongside API definitions in version control.

This architectural plan provides a solid foundation for developing a powerful and flexible API Documentation Generator, capable of meeting the demands of modern API development workflows.

gemini Output

This deliverable provides the core code for an API Documentation Generator. This generator is designed to take structured definitions of your API endpoints and automatically produce comprehensive, well-formatted documentation in Markdown. This output can then be easily converted to HTML, PDF, or used directly in your documentation portal.

The code is written in Python, focusing on clarity, modularity, and extensibility, making it suitable for production environments.


1. Project Overview

This step (gemini → generate_code) focuses on providing a robust, production-ready Python codebase that acts as the engine for generating API documentation. It defines a set of classes to model different components of an API (endpoints, parameters, responses) and a central APIDocumentationGenerator class that orchestrates the conversion of these definitions into a structured Markdown document.

Key Features:

  • Structured API Definitions: Define your API using Python classes, making it easy to manage and update.
  • Detailed Endpoint Information: Capture method, path, summary, detailed description, parameters (query, path, header, body), request bodies (schema and examples), and responses (status codes, descriptions, schemas, and examples).
  • Authentication & SDK Guidance: Dedicated sections for authentication methods and SDK usage examples.
  • Markdown Output: Generates clean, human-readable Markdown, which is universally compatible and easily transformable into various formats.
  • Endpoint Grouping: Automatically groups endpoints by tags for better navigation.

2. Core Components: Python Code & Explanations

Here's the complete Python code for the API Documentation Generator, followed by detailed explanations of each component.


import json
from typing import List, Dict, Any, Optional

# --- Data Models for API Components ---

class Parameter:
    """
    Represents a single API parameter (e.g., query, header, path, or body parameter).
    """
    def __init__(self, name: str, type: str, location: str, required: bool, description: str, example: Optional[Any] = None):
        """
        Initializes a Parameter object.

        Args:
            name (str): The name of the parameter.
            type (str): The data type of the parameter (e.g., 'string', 'integer', 'boolean').
            location (str): Where the parameter is located ('query', 'header', 'path', 'body').
            required (bool): True if the parameter is mandatory, False otherwise.
            description (str): A brief explanation of the parameter.
            example (Optional[Any]): An example value for the parameter.
        """
        self.name = name
        self.type = type
        self.location = location
        self.required = required
        self.description = description
        self.example = example

    def to_markdown(self) -> str:
        """
        Converts the parameter details into a Markdown formatted string.
        """
        required_str = "Yes" if self.required else "No"
        example_str = f" (Example: `{self.example}`)" if self.example is not None else ""
        return f"- `{self.name}` ({self.location}, {self.type}, Required: {required_str}): {self.description}{example_str}"

class Response:
    """
    Represents a single API response for a specific HTTP status code.
    """
    def __init__(self, status_code: int, description: str, schema: Optional[Dict[str, Any]] = None, example: Optional[Dict[str, Any]] = None):
        """
        Initializes a Response object.

        Args:
            status_code (int): The HTTP status code (e.g., 200, 201, 400).
            description (str): A description of the response.
            schema (Optional[Dict[str, Any]]): A JSON schema defining the structure of the response body.
            example (Optional[Dict[str, Any]]): An example JSON response body.
        """
        self.status_code = status_code
        self.description = description
        self.schema = schema
        self.example = example

    def to_markdown(self) -> str:
        """
        Converts the response details into a Markdown formatted string.
        Includes schema and example if provided.
        """
        md = f"- **{self.status_code}**: {self.description}\n"
        if self.schema:
            md += "  ```json\n"
            md += json.dumps(self.schema, indent=2) + "\n"
            md += "  ```\n"
        if self.example:
            md += "  Example:\n"
            md += "  ```json\n"
            md += json.dumps(self.example, indent=2) + "\n"
            md += "  ```\n"
        return md

class Endpoint:
    """
    Represents a single API endpoint, encapsulating all its details.
    """
    def __init__(self,
                 path: str,
                 method: str,
                 summary: str,
                 description: str,
                 parameters: Optional[List[Parameter]] = None,
                 request_body_schema: Optional[Dict[str, Any]] = None,
                 request_body_example: Optional[Dict[str, Any]] = None,
                 responses: Optional[List[Response]] = None,
                 authentication_required: bool = False,
                 tags: Optional[List[str]] = None):
        """
        Initializes an Endpoint object.

        Args:
            path (str): The URL path for the endpoint (e.g., '/users/{id}').
            method (str): The HTTP method (e.g., 'GET', 'POST', 'PUT', 'DELETE').
            summary (str): A short, summary description of the endpoint.
            description (str): A detailed description of what the endpoint does.
            parameters (Optional[List[Parameter]]): A list of Parameter objects for this endpoint.
            request_body_schema (Optional[Dict[
gemini Output

API Documentation: PantheraHive User Management API

Welcome to the PantheraHive User Management API documentation! This guide provides comprehensive information on how to integrate with our API, manage users, handle authentication, and utilize our SDKs for seamless development.


Table of Contents

  1. [Introduction](#1-introduction)

* [API Overview](#api-overview)

* [Base URL](#base-url)

* [Data Formats](#data-formats)

  1. [Authentication](#2-authentication)

* [API Key Authentication](#api-key-authentication)

* [Bearer Token Authentication (OAuth 2.0)](#bearer-token-authentication-oauth-20)

  1. [Error Handling](#3-error-handling)

* [Common Error Codes](#common-error-codes)

* [Error Response Structure](#error-response-structure)

  1. [Rate Limiting](#4-rate-limiting)

* [Rate Limit Headers](#rate-limit-headers)

  1. [Endpoints](#5-endpoints)

* [User Management](#user-management)

* [List All Users (GET /users)](#list-all-users-get-users)

* [Retrieve a Specific User (GET /users/{user_id})](#retrieve-a-specific-user-get-usersuser_id)

* [Create a New User (POST /users)](#create-a-new-user-post-users)

* [Update an Existing User (PUT /users/{user_id})](#update-an-existing-user-put-usersuser_id)

* [Delete a User (DELETE /users/{user_id})](#delete-a-user-delete-usersuser_id)

  1. [SDK Usage Examples](#6-sdk-usage-examples)

* [Python SDK](#python-sdk)

* [JavaScript SDK](#javascript-sdk)

  1. [Webhooks (Optional)](#7-webhooks-optional)

* [Setting Up Webhooks](#setting-up-webhooks)

* [Webhook Event Types](#webhook-event-types)

* [Verifying Webhook Signatures](#verifying-webhook-signatures)

  1. [Support and Feedback](#8-support-and-feedback)
  2. [Changelog](#9-changelog)

1. Introduction

API Overview

The PantheraHive User Management API allows you to programmatically manage users within your PantheraHive ecosystem. You can perform actions such as creating, retrieving, updating, and deleting user records, enabling seamless integration with your applications and services.

Base URL

All API requests should be made to the following base URL:

https://api.pantherahive.com/v1

Data Formats

All requests and responses use JSON (JavaScript Object Notation) format.

  • Request Header: Content-Type: application/json
  • Response Header: Content-Type: application/json

2. Authentication

All requests to the PantheraHive API must be authenticated. We support two primary authentication methods: API Key and Bearer Token (OAuth 2.0).

API Key Authentication

For simpler integrations and server-to-server communication, you can use an API Key.

  • How to obtain: Your API Key can be generated and managed in your PantheraHive Developer Dashboard.
  • How to use: Include your API Key in the X-API-Key header for every request.

Example Request Header:


X-API-Key: YOUR_API_KEY_HERE

Bearer Token Authentication (OAuth 2.0)

For client-side applications or scenarios requiring more granular control and user consent, we recommend using Bearer Token authentication via OAuth 2.0.

  1. Obtain an Access Token:

* Direct your users to the PantheraHive authorization URL:

https://auth.pantherahive.com/oauth/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&scope=read:users write:users

* Upon successful authorization, the user will be redirected to YOUR_REDIRECT_URI with an authorization code.

* Exchange the code for an access_token by making a POST request to our token endpoint:

Request:


    POST https://auth.pantherahive.com/oauth/token
    Content-Type: application/json

    {
        "grant_type": "authorization_code",
        "client_id": "YOUR_CLIENT_ID",
        "client_secret": "YOUR_CLIENT_SECRET",
        "code": "AUTHORIZATION_CODE_FROM_REDIRECT",
        "redirect_uri": "YOUR_REDIRECT_URI"
    }

Response (Success):


    {
        "access_token": "YOUR_ACCESS_TOKEN",
        "token_type": "Bearer",
        "expires_in": 3600,
        "refresh_token": "YOUR_REFRESH_TOKEN",
        "scope": "read:users write:users"
    }
  1. Use the Access Token:

Include the access_token in the Authorization header with the Bearer scheme for every API request.

Example Request Header:


Authorization: Bearer YOUR_ACCESS_TOKEN

3. Error Handling

The API uses standard HTTP status codes to indicate the success or failure of an API request. In case of an error, the response body will contain a JSON object with more details.

Common Error Codes

  • 200 OK: The request was successful.
  • 201 Created: The resource was successfully created.
  • 204 No Content: The request was successful, but there is no content to return (e.g., DELETE requests).
  • 400 Bad Request: The request was malformed or invalid.
  • 401 Unauthorized: Authentication is required or has failed (e.g., missing or invalid API key/token).
  • 403 Forbidden: The authenticated user does not have permission to access the resource.
  • 404 Not Found: The requested resource does not exist.
  • 405 Method Not Allowed: The HTTP method used is not supported for the resource.
  • 429 Too Many Requests: Rate limit exceeded.
  • 500 Internal Server Error: An unexpected error occurred on the server.

Error Response Structure


{
    "status": "error",
    "code": "error_code_string",
    "message": "A human-readable description of the error.",
    "details": {
        "field_name": "Specific reason for the field error"
    }
}

Example Error Response:


{
    "status": "error",
    "code": "invalid_input",
    "message": "Validation failed for one or more fields.",
    "details": {
        "email": "Email address is already in use.",
        "password": "Password must be at least 8 characters long."
    }
}

4. Rate Limiting

To ensure fair usage and stability, our API enforces rate limits on requests. If you exceed the allocated rate limits, you will receive a 429 Too Many Requests HTTP status code.

Rate Limit Headers

The following headers are included in every response to help you manage your request rate:

  • X-RateLimit-Limit: The maximum number of requests you can make in the current window.
  • X-RateLimit-Remaining: The number of requests remaining in the current window.
  • X-RateLimit-Reset: The time (in UTC epoch seconds) when the current rate limit window resets.

Example Headers:


X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 995
X-RateLimit-Reset: 1678886400

Our default rate limit is 1000 requests per minute per IP address/API Key.


5. Endpoints

User Management

This section details the endpoints for managing user resources. A user resource typically includes properties like id, email, first_name, last_name, status, created_at, and updated_at.

##### List All Users (GET /users)

Retrieves a list of all users in your organization. Supports pagination and filtering.

  • Description: Fetches an array of user objects.
  • Authentication: Required (API Key or Bearer Token with read:users scope).
  • Query Parameters:

* limit (integer, optional): Maximum number of users to return. Default is 20, max is 100.

* offset (integer, optional): Number of users to skip for pagination. Default is 0.

* status (string, optional): Filter by user status (active, inactive, pending).

* email (string, optional): Filter by exact email address.

  • Response (Success - 200 OK):

    {
        "status": "success",
        "data": [
            {
                "id": "user_12345",
                "email": "john.doe@example.com",
                "first_name": "John",
                "last_name": "Doe",
                "status": "active",
                "created_at": "2023-01-15T10:00:00Z",
                "updated_at": "2023-01-15T10:00:00Z"
            },
            {
                "id": "user_67890",
                "email": "jane.smith@example.com",
                "first_name": "Jane",
                "last_name": "Smith",
                "status": "active",
                "created_at": "2023-01-20T11:30:00Z",
                "updated_at": "2023-01-20T11:30:00Z"
            }
        ],
        "meta": {
            "total": 2,
            "limit": 20,
            "offset": 0
        }
    }
  • Response (Error - 401 Unauthorized): See [Error Handling](#3-error-handling).

##### Retrieve a Specific User (GET /users/{user_id})

Retrieves details for a single user by their unique ID.

  • Description: Fetches a single user object.
  • Authentication: Required (API Key or Bearer Token with read:users scope).
  • Path Parameters:

* user_id (string, required): The unique identifier of the user.

  • Response (Success - 200 OK):

    {
        "status": "success",
        "data": {
            "id": "user_12345",
            "email": "john.doe@example.com",
            "first_name": "John",
            "last_name": "Doe",
            "status": "active",
            "created_at": "2023-01-15T10:00:00Z",
            "updated_at": "2023-01-15T10:00:00Z"
        }
    }
  • Response (Error - 404 Not Found):

    {
        "status": "error",
        "code": "user_not_found",
        "message": "The user with ID 'user_nonexistent' was not found."
    }

##### Create a New User (POST /users)

Creates a new user record in the system.

  • Description: Adds a new user.
  • Authentication: Required (API Key or Bearer Token with write:users scope).
  • Request Body:

    {
        "email": "new.user@example.com",
        "password": "securepassword123",
        "first_name": "New",
        "last_name": "User",
        "status": "pending"
    }

* email (string, required): The user's email address. Must be unique.

* password (string, required): The user's password.

* first_name (string, optional): The user's first name.

* last_name (string, optional): The user's last name.

* status (string, optional): Initial status of the user (active, inactive, pending). Default is pending.

  • Response (Success - 201 Created):

    {
        "status": "success",
        "data": {
            "id": "user_abcde",
            "email": "new.user@example.com",
            "first_name": "New",
            "last_name": "User",
            "status": "pending",
            "created_at": "2023-03-15T14:30:00Z",
            "updated_at": "2023-03-15T14:30:00Z"
        }
    }
  • Response (Error - 400 Bad Request): See [Error Handling](#3-error-handling).

##### Update an Existing User (PUT /users/{user_id})

Updates an existing user's information. Only provided fields will be updated.

  • Description: Modifies an existing user's details.
  • Authentication: Required (API Key or Bearer Token with write:users scope).
  • Path Parameters:

* user_id (string, required): The unique identifier of the user to update.

  • Request Body:

    {
        "first_name": "Jonathan",
        "status": "active"
    }

* email (string, optional): New email address.

* password (string, optional): New password.

* first_name (string, optional): New first name.

* last_name (string, optional): New last name.

* status (string, optional): New status (active, inactive, pending).

  • Response (Success - 200 OK):

    {
        "status": "success",
        "data": {
            "id": "user_12345",
            "email": "john.doe@example.com",
            "first_name": "Jonathan",
            "last_name": "Doe",
            "status": "active",
            "created_at": "2023-01-15T10:00
api_documentation_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);}});}