API Documentation Generator
Run ID: 69caccb9eff1ba2b79624eb42026-03-30Development
PantheraHive BOS
BOS Dashboard

This document provides comprehensive, detailed, and professional API documentation for the Product Catalog Management API. It includes an overview, authentication guide, detailed endpoint descriptions with request/response examples, error handling, and SDK usage examples to help developers integrate seamlessly.


Product Catalog Management API Documentation

Welcome to the Product Catalog Management API documentation! This API allows developers to programmatically manage product listings, including creating, retrieving, updating, and deleting product information within a catalog.

1. Introduction

The Product Catalog Management API provides a robust and flexible interface for interacting with your product data. Whether you're building an e-commerce platform, an inventory management system, or a data analytics tool, this API offers the necessary endpoints to manage your product catalog efficiently.

Key Features:

Base URL:

All API requests should be prefixed with the following base URL:

https://api.yourcompany.com/v1

Data Format:

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

2. Authentication

The Product Catalog Management API uses API Key authentication. You must include your unique API key in the Authorization header of every request.

2.1 Obtaining Your API Key

  1. Log in to your developer dashboard at https://developer.yourcompany.com/dashboard.
  2. Navigate to the "API Keys" section.
  3. Generate a new API key or use an existing one.
  4. Keep your API key secure and do not expose it in client-side code or public repositories.

2.2 Authenticating Requests

Include your API key in the Authorization header with the Bearer scheme for all requests.

Header Example:

text • 2,443 chars
### 3. API Endpoints

This section details all available API endpoints, including their HTTP methods, paths, parameters, and example requests/responses.

#### 3.1 Product Object Schema

The core object manipulated by this API is a `Product`. Here's its typical structure:

| Field       | Type      | Description                                     | Required |
| :---------- | :-------- | :---------------------------------------------- | :------- |
| `id`        | `string`  | Unique identifier for the product. (Read-only)  | No       |
| `name`      | `string`  | Name of the product.                            | Yes      |
| `description` | `string`  | Detailed description of the product.            | Yes      |
| `price`     | `number`  | Price of the product.                           | Yes      |
| `currency`  | `string`  | Currency of the product price (e.g., "USD").    | Yes      |
| `stock`     | `integer` | Number of items in stock.                       | Yes      |
| `category`  | `string`  | Product category (e.g., "Electronics", "Books").| No       |
| `sku`       | `string`  | Stock Keeping Unit.                             | No       |
| `created_at` | `string`  | ISO 8601 timestamp of creation. (Read-only)     | No       |
| `updated_at` | `string`  | ISO 8601 timestamp of last update. (Read-only)  | No       |

---

#### 3.2 List All Products

Retrieve a list of all products in the catalog.

*   **HTTP Method:** `GET`
*   **Path:** `/products`

**Description:**
This endpoint fetches a paginated list of products. You can filter and sort the results using query parameters.

**Query Parameters:**

| Parameter | Type      | Description                                                               | Default |
| :-------- | :-------- | :------------------------------------------------------------------------ | :------ |
| `limit`   | `integer` | Maximum number of products to return per page. (Max: 100)                 | 10      |
| `offset`  | `integer` | The number of products to skip before starting to collect the result set. | 0       |
| `category`| `string`  | Filter products by category name.                                         | All     |
| `sort_by` | `string`  | Field to sort the results by (e.g., `name`, `price`, `created_at`).       | `id`    |
| `order`   | `string`  | Sort order: `asc` for ascending, `desc` for descending.                   | `asc`   |

**Example Request:**

Sandboxed live preview

API Documentation Generator: Architectural Plan

This document outlines the detailed architectural plan for the "API Documentation Generator." The goal is to create a robust, flexible, and extensible system capable of generating professional, comprehensive API documentation, including endpoint descriptions, request/response examples, authentication guides, and SDK usage examples.


1. Project Overview

Goal: To develop an automated system that ingests API definitions (e.g., OpenAPI/Swagger specifications) and produces high-quality, user-friendly, and maintainable documentation in various output formats.

Key Features:

  • Automated Content Generation: Generate documentation directly from API specifications.
  • Endpoint Details: Detailed descriptions for each API endpoint, including path, method, parameters (query, header, path, body), and responses.
  • Request/Response Examples: Automatically generated or user-provided examples for various scenarios.
  • Authentication Guides: Clear instructions and examples for different authentication schemes (e.g., API Key, OAuth2, Bearer Token).
  • SDK Usage Examples: Code snippets demonstrating how to interact with the API using various SDKs or programming languages.
  • Customizable Output: Support for multiple output formats (e.g., Markdown, HTML, PDF) and customizable templates.
  • Version Control Integration: Ability to integrate with source control for documentation history.
  • Extensibility: A modular architecture allowing for easy addition of new input formats, output formats, or content generation rules.

2. Architectural Style: Modular Monolith with Plugin Capabilities

The proposed architectural style is a Modular Monolith with strong emphasis on plugin-based extensibility. This approach offers the benefits of a single deployment unit (simplicity, reduced overhead) while enforcing clear separation of concerns through modules. Plugins will allow for easy integration of new input sources, output renderers, and content transformers without altering the core system.

Rationale:

  • Simplicity: Easier to develop, deploy, and manage initially compared to a distributed microservices architecture.
  • Performance: Direct function calls between modules reduce latency.
  • Extensibility: Well-defined interfaces for modules and plugins enable future expansion.
  • Maintainability: Clear module boundaries improve code organization and maintainability.

3. Core Components & Modules

The system will be composed of several distinct modules, each with a specific responsibility:

3.1. Input Processing Module

  • Responsibility: Ingesting API definitions from various sources and formats.
  • Sub-components:

* API Spec Loaders: Adapters for different API specification formats (e.g., OpenAPI/Swagger YAML/JSON, Postman Collections, RAML). Each loader will parse its specific format into a standardized internal representation.

* Validation Engine: Validates the loaded API specification against its schema to ensure correctness and completeness.

* Source Integration: Mechanisms to fetch specifications from local files, URLs, or version control systems (e.g., Git repositories).

3.2. Internal Data Model (IDM)

  • Responsibility: A standardized, technology-agnostic, and comprehensive intermediate representation of the API. This acts as the central data structure for all subsequent processing.
  • Key Entities: API (name, version, description), Endpoints (path, method, summary, description), Parameters (name, type, location, required), Request Bodies, Responses (status code, description, schema), Schemas (data models), Security Schemes (type, description), Tags, External Docs.
  • Benefits: Decouples input formats from output formats, simplifying the core generation logic.

3.3. Content Generation Engine

  • Responsibility: Transforming the IDM into human-readable content blocks. This module contains the core logic for generating descriptions, examples, and structured data.
  • Sub-components:

* Description Generator: Logic to compose clear and concise descriptions for endpoints, parameters, and models, potentially enriching them with inferred details.

* Example Generator:

* Static Examples: Processes user-provided examples from the API spec.

* Dynamic Example Generation: Logic to generate realistic request/response body examples based on defined schemas (e.g., using Faker libraries for data types).

* Authentication Guide Generator: Creates structured content for various authentication methods based on securitySchemes defined in the IDM.

* Error Handling Guide Generator: Extracts and formats error responses.

3.4. Templating & Rendering Module

  • Responsibility: Taking the generated content blocks and structuring them into final documentation using templates.
  • Sub-components:

* Templating Engine: A robust templating library (e.g., Jinja2 for Python, Handlebars for Node.js) that allows for dynamic content injection.

* Template Management: System for managing default and custom documentation templates.

* Renderer Adapters: Converts rendered templates into specific output formats (e.g., Markdown, HTML, PDF).

3.5. Output & Publishing Module

  • Responsibility: Delivering the generated documentation in the desired format and location.
  • Sub-components:

* File System Publisher: Writes documentation to specified local directories.

* Static Site Generator Integration: Integrates with popular static site generators (e.g., MkDocs, Docusaurus, Next.js) for HTML output.

* Deployment Adapters (Future): Potentially publish directly to cloud storage (S3, Azure Blob) or content delivery networks.

3.6. Authentication & Security Module (for Documented APIs)

  • Responsibility: Focuses on documenting different authentication methods for the API itself, not securing the generator.
  • Features:

* Detailed explanations of OAuth2 flows (Client Credentials, Authorization Code, Implicit).

* API Key usage instructions (header, query).

* Bearer Token examples.

* Code snippets for obtaining and using tokens/keys.

3.7. SDK Snippet Generator (Optional, but requested)

  • Responsibility: Generating code examples for interacting with the API in various programming languages.
  • Sub-components:

* Language Adapters: Modules for generating snippets in Python, JavaScript, Java, Go, cURL, etc.

* Client Code Generation: Uses the IDM to construct accurate API calls including parameters, headers, and body.

* SDK Awareness: Ability to generate snippets that leverage existing SDKs where available, or raw HTTP requests otherwise.

3.8. User Interface / Command Line Interface (CLI)

  • Responsibility: Providing a means for users to interact with the generator.
  • CLI: Primary interface for configuration, triggering generation, and specifying input/output paths.
  • Web UI (Future consideration): A simple web interface for uploading specs, selecting templates, and previewing output.

4. Data Flow & Interactions

  1. Input: User provides API specification path (local file, URL, Git repo) and desired output configuration via CLI/UI.
  2. Load & Validate: The Input Processing Module loads the specification and validates it.
  3. IDM Creation: The validated specification is transformed into the Internal Data Model (IDM).
  4. Content Generation: The Content Generation Engine processes the IDM to produce raw documentation content (descriptions, examples, auth guides, SDK snippets).
  5. Templating & Rendering: The Templating & Rendering Module takes the raw content and the IDM, applies the selected templates, and renders it into an intermediate format (e.g., Markdown document string).
  6. Output & Publishing: The Output & Publishing Module takes the rendered content and saves it to the specified output format and location (e.g., HTML files, Markdown files).

5. Proposed Technology Stack

  • Primary Language: Python

* Rationale: Rich ecosystem for text processing, data manipulation, and strong libraries for YAML/JSON parsing. Excellent for CLI applications and static site generation integration.

  • API Specification Parsing:

* PyYAML: For YAML parsing.

* json: For JSON parsing.

* openapi-spec-validator: For OpenAPI schema validation.

* pydantic (or similar): For defining the Internal Data Model with strong typing.

  • Templating Engine: Jinja2

* Rationale: Powerful, widely used, and flexible templating engine in Python.

  • Dynamic Example Generation: Faker, jsonschema-faker (if available for Python)
  • CLI Framework: Click or Typer

* Rationale: Robust and easy-to-use frameworks for building command-line interfaces.

  • Output Formats:

* Markdown (default)

* HTML (via Markdown-to-HTML conversion, e.g., Markdown library, integration with MkDocs, Docusaurus or custom templates)

* PDF (via WeasyPrint or similar for HTML-to-PDF conversion)

  • Static Site Generator Integration: MkDocs (with Material for MkDocs theme)

* Rationale: Excellent for generating clean, navigable API documentation sites from Markdown.

  • SDK Snippet Generation: Custom logic or leveraging libraries like requests for Python examples, axios for JavaScript, etc.

6. Scalability, Performance & Security Considerations

  • Scalability:

* Modular Design: Allows for individual components to be optimized or replaced without affecting the entire system.

* Stateless Processing: The generation process will be largely stateless, making it easy to run in parallel if deployed as a service.

* Caching (Future): Caching parsed API specs or generated content for frequently requested documentation.

  • Performance:

* Efficient Parsing: Use optimized libraries for parsing large YAML/JSON files.

* Optimized Templating: Design templates to minimize complex logic within the template itself, pushing logic into the Python code.

* Asynchronous I/O (if applicable): For fetching specs from multiple remote URLs.

  • Security:

* Input Validation: Thorough validation of all input API specifications to prevent malformed data from causing issues or injecting malicious content.

* Template Sandboxing: If custom templates are allowed from untrusted sources, ensure the templating engine runs in a sandbox to prevent arbitrary code execution.

* Dependency Security: Regularly update dependencies to mitigate known vulnerabilities.

Sensitive Data Handling: Ensure no sensitive API keys or credentials used by the generator* are hardcoded or exposed.


7. Deployment Strategy

  • Containerization (Docker): The entire application will be containerized using Docker. This ensures consistent environments across development, testing, and production.
  • CLI Tool: Primarily distributed as a Docker image or a Python package (pip install).
  • CI/CD Pipeline: Implement a Continuous Integration/Continuous Deployment pipeline (e.g., GitHub Actions, GitLab CI) for automated testing, building Docker images, and publishing new versions.
  • Output Hosting: Generated static HTML documentation can be hosted on any web server, cloud storage (S3, Azure Blob Storage), or dedicated static site hosting services (Netlify, Vercel).

8. Project Roadmap & Milestones

This roadmap outlines a phased approach for the development of the API Documentation Generator.

Phase 1: Foundation & Core Generation (Weeks 1-4)

  • Milestones:

* Week 1: Initial project setup, core CLI with basic command structure, OpenAPI 3.x YAML/JSON loader.

* Week 2: Internal Data Model (IDM) definition, basic transformation from OpenAPI to IDM.

* Week 3: Basic content generation engine for endpoints (path, method, summary, description). Jinja2 templating integration.

* Week 4: Output to Markdown files. End-to-end generation for a simple API spec.

  • Deliverables: Functional CLI for basic documentation generation, core IDM, initial Markdown templates.

Phase 2: Advanced Content & Customization (Weeks 5-8)

  • Milestones:

* Week 5: Parameter (path, query, header, body) documentation, request

gemini Output

The following output provides a comprehensive, detailed, and professional representation of API documentation, generated in a machine-readable format (OpenAPI 3.1.0 YAML) suitable for automated documentation tools, alongside human-readable explanations and example code snippets. This output serves as the core deliverable for the "API Documentation Generator" workflow, demonstrating how a sophisticated API's documentation can be structured and presented.


API Documentation Generator Output: User Management API

This section presents the detailed API documentation for a hypothetical "User Management API." The primary output format is OpenAPI 3.1.0 YAML, which is the industry standard for describing RESTful APIs. This YAML can be consumed by various tools (e.g., Swagger UI, Redoc) to generate interactive and visually appealing documentation portals.

Alongside the OpenAPI YAML, we provide explanations and illustrative examples for key documentation components, including endpoint descriptions, request/response examples, authentication guides, and SDK usage examples.


1. OpenAPI 3.1.0 YAML Definition

This YAML file describes a complete API, including its endpoints, data models, security schemes, and example requests/responses.


# api-documentation.yaml
openapi: 3.1.0
info:
  title: User Management API
  description: |
    Welcome to the User Management API documentation! This API allows you to manage user accounts, including creating, retrieving, updating, and deleting users.
    
    All API requests must be made over HTTPS.
  version: 1.0.0
  contact:
    name: API Support
    url: https://yourcompany.com/support
    email: support@yourcompany.com
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0.html

servers:
  - url: https://api.yourcompany.com/v1
    description: Production Server
  - url: https://dev.api.yourcompany.com/v1
    description: Development Server

tags:
  - name: Users
    description: Operations related to user management

security:
  - BearerAuth: [] # Apply BearerAuth globally by default

paths:
  /users:
    get:
      tags:
        - Users
      summary: Retrieve a list of users
      description: |
        Fetches a paginated list of all registered users.
        
        **Note:** Requires `admin` scope for full user details.
      operationId: listUsers
      parameters:
        - name: limit
          in: query
          description: Maximum number of users to return
          required: false
          schema:
            type: integer
            format: int32
            minimum: 1
            maximum: 100
            default: 10
        - name: offset
          in: query
          description: Number of users to skip before starting to collect the result set
          required: false
          schema:
            type: integer
            format: int32
            minimum: 0
            default: 0
      responses:
        '200':
          description: A list of users
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
              examples:
                SuccessResponse:
                  summary: Example successful response
                  value:
                    - id: "usr_12345"
                      username: "john.doe"
                      email: "john.doe@example.com"
                      firstName: "John"
                      lastName: "Doe"
                      createdAt: "2023-01-01T10:00:00Z"
                      updatedAt: "2023-01-01T10:00:00Z"
                    - id: "usr_67890"
                      username: "jane.smith"
                      email: "jane.smith@example.com"
                      firstName: "Jane"
                      lastName: "Smith"
                      createdAt: "2023-01-05T15:30:00Z"
                      updatedAt: "2023-01-05T15:30:00Z"
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '500':
          $ref: '#/components/responses/InternalServerError'
    post:
      tags:
        - Users
      summary: Create a new user
      description: Registers a new user account with the provided details.
      operationId: createUser
      requestBody:
        description: User object to be created
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewUser'
            examples:
              NewUserRequest:
                summary: Example request to create a user
                value:
                  username: "alice.wonder"
                  email: "alice.wonder@example.com"
                  password: "SecurePassword123!"
                  firstName: "Alice"
                  lastName: "Wonderland"
      responses:
        '201':
          description: User created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
              examples:
                UserCreatedResponse:
                  summary: Example successful creation response
                  value:
                    id: "usr_abcde"
                    username: "alice.wonder"
                    email: "alice.wonder@example.com"
                    firstName: "Alice"
                    lastName: "Wonderland"
                    createdAt: "2023-03-10T11:22:33Z"
                    updatedAt: "2023-03-10T11:22:33Z"
        '400':
          $ref: '#/components/responses/BadRequestError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '409':
          description: Conflict, user with that email or username already exists
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                ConflictError:
                  value:
                    code: "USER_EXISTS"
                    message: "User with email 'alice.wonder@example.com' already exists."
        '500':
          $ref: '#/components/responses/InternalServerError'

  /users/{userId}:
    parameters:
      - name: userId
        in: path
        description: The ID of the user to retrieve or modify.
        required: true
        schema:
          type: string
          pattern: '^usr_[a-zA-Z0-9]{5}$' # Example pattern for user IDs
    get:
      tags:
        - Users
      summary: Retrieve a single user by ID
      description: Fetches details for a specific user using their unique ID.
      operationId: getUserById
      responses:
        '200':
          description: User details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
              examples:
                UserDetailResponse:
                  summary: Example successful user detail response
                  value:
                    id: "usr_12345"
                    username: "john.doe"
                    email: "john.doe@example.com"
                    firstName: "John"
                    lastName: "Doe"
                    createdAt: "2023-01-01T10:00:00Z"
                    updatedAt: "2023-01-01T10:00:00Z"
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '500':
          $ref: '#/components/responses/InternalServerError'
    put:
      tags:
        - Users
      summary: Update an existing user
      description: Updates the details of an existing user identified by their ID.
      operationId: updateUser
      requestBody:
        description: User object with updated fields
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateUser'
            examples:
              UpdateUserRequest:
                summary: Example request to update a user'                
                value:
                  firstName: "Jonathan"
                  lastName: "Doe-Smith"
                  email: "jonathan.doe@example.com" # Email can be updated
      responses:
        '200':
          description: User updated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
              examples:
                UserUpdatedResponse:
                  summary: Example successful update response
                  value:
                    id: "usr_12345"
                    username: "john.doe"
                    email: "jonathan.doe@example.com"
                    firstName: "Jonathan"
                    lastName: "Doe-Smith"
                    createdAt: "2023-01-01T10:00:00Z"
                    updatedAt: "2023-03-15T09:45:00Z"
        '400':
          $ref: '#/components/responses/BadRequestError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '500':
          $ref: '#/components/responses/InternalServerError'
    delete:
      tags:
        - Users
      summary: Delete a user
      description: Deletes a user account permanently.
      operationId: deleteUser
      responses:
        '204':
          description: User deleted successfully (No Content)
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '403':
          description: Forbidden, user does not have permission to delete this account
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                ForbiddenError:
                  value:
                    code: "PERMISSION_DENIED"
                    message: "You do not have sufficient permissions to delete this user."
        '404':
          $ref: '#/components/responses/NotFoundError'
        '500':
          $ref: '#/components/responses/InternalServerError'

components:
  schemas:
    User:
      type: object
      required:
        - id
        - username
        - email
        - firstName
        - lastName
        - createdAt
        - updatedAt
      properties:
        id:
          type: string
          description: Unique identifier for the user.
          example: "usr_12345"
        username:
          type: string
          description: Unique username for the user.
          example: "john.doe"
        email:
          type: string
          format: email
          description: Email address of the user.
          example: "john.doe@example.com"
        firstName:
          type: string
          description: First name of the user.
          example: "John"
        lastName:
          type: string
          description: Last name of the user.
          example: "Doe"
        createdAt:
          type: string
          format: date-time
          description: Timestamp when the user was created.
          example: "2023-01-01T10:00:00Z"
        updatedAt:
          type: string
          format: date-time
          description: Timestamp when the user was last updated.
          example: "2023-01-01T10:00:00Z"
      example: # Example for the schema itself, not for a specific response
        id: "usr_example"
        username: "user.example"
        email: "user@example.com"
        firstName: "Example"
        lastName: "User"
        createdAt: "2023-01-01T00:00:00Z"
        updatedAt: "2023-01-01T00:00:00Z"

    NewUser:
      type: object
      required:
        - username
        - email
        - password
      properties:
        username:
          type: string
          description: Unique username for the new user.
          minLength: 3
          maxLength: 30
          pattern: "^[a-zA-Z0-9._-]+$"
          example: "new.user"
        email:
          type: string
          format: email
          description: Email address of the new user. Must be unique.
          example: "new.user@example.com"
        password:
          type: string
          format: password
          description: Password for the new user.
          minLength: 8
          maxLength: 64
          example: "StrongP@ssw0rd!"
        firstName:
          type: string
          description: First name of the user.
          nullable: true
          example: "New"
        lastName:
          type: string
          description: Last name of the user.
          nullable: true
          example: "User"
      example:
        username: "test.user"
        email: "test.user@example.com"
        password: "MySecurePassword123"
        firstName: "Test"
        lastName: "User"

    UpdateUser:
      type: object
      properties:
        username:
          type: string
          description: New unique username for the user.
          minLength: 3
          maxLength

json

{

"id": "prod_def456",

"name": "Ergonomic Office Chair (Deluxe Edition)",

"description": "High-back mesh office chair with adjustable lumbar support and headrest.",

"price": 399.99,

"currency": "USD",

"stock": 60,

"category": "Office Furniture",

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
\n\n\n"); var hasSrcMain=Object.keys(extracted).some(function(k){return k.indexOf("src/main")>=0;}); if(!hasSrcMain) zip.file(folder+"src/main."+ext,"import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport './index.css'\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n \n \n \n)\n"); var hasSrcApp=Object.keys(extracted).some(function(k){return k==="src/App."+ext||k==="App."+ext;}); if(!hasSrcApp) zip.file(folder+"src/App."+ext,"import React from 'react'\nimport './App.css'\n\nfunction App(){\n return(\n
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n
\n )\n}\nexport default App\n"); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e}\n.app{min-height:100vh;display:flex;flex-direction:column}\n.app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px}\nh1{font-size:2.5rem;font-weight:700}\n"); zip.file(folder+"src/App.css",""); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/pages/.gitkeep",""); zip.file(folder+"src/hooks/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\n## Open in IDE\nOpen the project folder in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Vue (Vite + Composition API + TypeScript) --- */ function buildVue(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "type": "module",\n "scripts": {\n "dev": "vite",\n "build": "vue-tsc -b && vite build",\n "preview": "vite preview"\n },\n "dependencies": {\n "vue": "^3.5.13",\n "vue-router": "^4.4.5",\n "pinia": "^2.3.0",\n "axios": "^1.7.9"\n },\n "devDependencies": {\n "@vitejs/plugin-vue": "^5.2.1",\n "typescript": "~5.7.3",\n "vite": "^6.0.5",\n "vue-tsc": "^2.2.0"\n }\n}\n'); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { resolve } from 'path'\n\nexport default defineConfig({\n plugins: [vue()],\n resolve: { alias: { '@': resolve(__dirname,'src') } }\n})\n"); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]}\n'); zip.file(folder+"tsconfig.app.json",'{\n "compilerOptions":{\n "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"],\n "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true,\n "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue",\n "strict":true,"paths":{"@/*":["./src/*"]}\n },\n "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"]\n}\n'); zip.file(folder+"env.d.ts","/// \n"); zip.file(folder+"index.html","\n\n\n \n \n "+slugTitle(pn)+"\n\n\n
\n \n\n\n"); var hasMain=Object.keys(extracted).some(function(k){return k==="src/main.ts"||k==="main.ts";}); if(!hasMain) zip.file(folder+"src/main.ts","import { createApp } from 'vue'\nimport { createPinia } from 'pinia'\nimport App from './App.vue'\nimport './assets/main.css'\n\nconst app = createApp(App)\napp.use(createPinia())\napp.mount('#app')\n"); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue","\n\n\n\n\n"); zip.file(folder+"src/assets/main.css","*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#fff;color:#213547}\n"); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/views/.gitkeep",""); zip.file(folder+"src/stores/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\nOpen in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Angular (v19 standalone) --- */ function buildAngular(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var sel=pn.replace(/_/g,"-"); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "scripts": {\n "ng": "ng",\n "start": "ng serve",\n "build": "ng build",\n "test": "ng test"\n },\n "dependencies": {\n "@angular/animations": "^19.0.0",\n "@angular/common": "^19.0.0",\n "@angular/compiler": "^19.0.0",\n "@angular/core": "^19.0.0",\n "@angular/forms": "^19.0.0",\n "@angular/platform-browser": "^19.0.0",\n "@angular/platform-browser-dynamic": "^19.0.0",\n "@angular/router": "^19.0.0",\n "rxjs": "~7.8.0",\n "tslib": "^2.3.0",\n "zone.js": "~0.15.0"\n },\n "devDependencies": {\n "@angular-devkit/build-angular": "^19.0.0",\n "@angular/cli": "^19.0.0",\n "@angular/compiler-cli": "^19.0.0",\n "typescript": "~5.6.0"\n }\n}\n'); zip.file(folder+"angular.json",'{\n "$schema": "./node_modules/@angular/cli/lib/config/schema.json",\n "version": 1,\n "newProjectRoot": "projects",\n "projects": {\n "'+pn+'": {\n "projectType": "application",\n "root": "",\n "sourceRoot": "src",\n "prefix": "app",\n "architect": {\n "build": {\n "builder": "@angular-devkit/build-angular:application",\n "options": {\n "outputPath": "dist/'+pn+'",\n "index": "src/index.html",\n "browser": "src/main.ts",\n "tsConfig": "tsconfig.app.json",\n "styles": ["src/styles.css"],\n "scripts": []\n }\n },\n "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"}\n }\n }\n }\n}\n'); zip.file(folder+"tsconfig.json",'{\n "compileOnSave": false,\n "compilerOptions": {"baseUrl":"./","outDir":"./dist/out-tsc","forceConsistentCasingInFileNames":true,"strict":true,"noImplicitOverride":true,"noPropertyAccessFromIndexSignature":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true,"paths":{"@/*":["src/*"]},"skipLibCheck":true,"esModuleInterop":true,"sourceMap":true,"declaration":false,"experimentalDecorators":true,"moduleResolution":"bundler","importHelpers":true,"target":"ES2022","module":"ES2022","useDefineForClassFields":false,"lib":["ES2022","dom"]},\n "references":[{"path":"./tsconfig.app.json"}]\n}\n'); zip.file(folder+"tsconfig.app.json",'{\n "extends":"./tsconfig.json",\n "compilerOptions":{"outDir":"./dist/out-tsc","types":[]},\n "files":["src/main.ts"],\n "include":["src/**/*.d.ts"]\n}\n'); zip.file(folder+"src/index.html","\n\n\n \n "+slugTitle(pn)+"\n \n \n \n\n\n \n\n\n"); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser';\nimport { appConfig } from './app/app.config';\nimport { AppComponent } from './app/app.component';\n\nbootstrapApplication(AppComponent, appConfig)\n .catch(err => console.error(err));\n"); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; }\nbody { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; }\n"); var hasComp=Object.keys(extracted).some(function(k){return k.indexOf("app.component")>=0;}); if(!hasComp){ zip.file(folder+"src/app/app.component.ts","import { Component } from '@angular/core';\nimport { RouterOutlet } from '@angular/router';\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [RouterOutlet],\n templateUrl: './app.component.html',\n styleUrl: './app.component.css'\n})\nexport class AppComponent {\n title = '"+pn+"';\n}\n"); zip.file(folder+"src/app/app.component.html","
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n \n
\n"); zip.file(folder+"src/app/app.component.css",".app-header{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;gap:16px}h1{font-size:2.5rem;font-weight:700;color:#6366f1}\n"); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\nimport { provideRouter } from '@angular/router';\nimport { routes } from './app.routes';\n\nexport const appConfig: ApplicationConfig = {\n providers: [\n provideZoneChangeDetection({ eventCoalescing: true }),\n provideRouter(routes)\n ]\n};\n"); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router';\n\nexport const routes: Routes = [];\n"); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nng serve\n# or: npm start\n\`\`\`\n\n## Build\n\`\`\`bash\nng build\n\`\`\`\n\nOpen in VS Code with Angular Language Service extension.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n.angular/\n"); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var reqMap={"numpy":"numpy","pandas":"pandas","sklearn":"scikit-learn","tensorflow":"tensorflow","torch":"torch","flask":"flask","fastapi":"fastapi","uvicorn":"uvicorn","requests":"requests","sqlalchemy":"sqlalchemy","pydantic":"pydantic","dotenv":"python-dotenv","PIL":"Pillow","cv2":"opencv-python","matplotlib":"matplotlib","seaborn":"seaborn","scipy":"scipy"}; var reqs=[]; Object.keys(reqMap).forEach(function(k){if(src.indexOf("import "+k)>=0||src.indexOf("from "+k)>=0)reqs.push(reqMap[k]);}); var reqsTxt=reqs.length?reqs.join("\n"):"# add dependencies here\n"; zip.file(folder+"main.py",src||"# "+title+"\n# Generated by PantheraHive BOS\n\nprint(title+\" loaded\")\n"); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\npython3 -m venv .venv\nsource .venv/bin/activate\npip install -r requirements.txt\n\`\`\`\n\n## Run\n\`\`\`bash\npython main.py\n\`\`\`\n"); zip.file(folder+".gitignore",".venv/\n__pycache__/\n*.pyc\n.env\n.DS_Store\n"); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var depMap={"mongoose":"^8.0.0","dotenv":"^16.4.5","axios":"^1.7.9","cors":"^2.8.5","bcryptjs":"^2.4.3","jsonwebtoken":"^9.0.2","socket.io":"^4.7.4","uuid":"^9.0.1","zod":"^3.22.4","express":"^4.18.2"}; var deps={}; Object.keys(depMap).forEach(function(k){if(src.indexOf(k)>=0)deps[k]=depMap[k];}); if(!deps["express"])deps["express"]="^4.18.2"; var pkgJson=JSON.stringify({"name":pn,"version":"1.0.0","main":"src/index.js","scripts":{"start":"node src/index.js","dev":"nodemon src/index.js"},"dependencies":deps,"devDependencies":{"nodemon":"^3.0.3"}},null,2)+"\n"; zip.file(folder+"package.json",pkgJson); var fallback="const express=require(\"express\");\nconst app=express();\napp.use(express.json());\n\napp.get(\"/\",(req,res)=>{\n res.json({message:\""+title+" API\"});\n});\n\nconst PORT=process.env.PORT||3000;\napp.listen(PORT,()=>console.log(\"Server on port \"+PORT));\n"; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000\n"); zip.file(folder+".gitignore","node_modules/\n.env\n.DS_Store\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\n\`\`\`\n\n## Run\n\`\`\`bash\nnpm run dev\n\`\`\`\n"); } /* --- Vanilla HTML --- */ function buildVanillaHtml(zip,folder,app,code){ var title=slugTitle(app); var isFullDoc=code.trim().toLowerCase().indexOf("=0||code.trim().toLowerCase().indexOf("=0; var indexHtml=isFullDoc?code:"\n\n\n\n\n"+title+"\n\n\n\n"+code+"\n\n\n\n"; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */\n*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e}\n"); zip.file(folder+"script.js","/* "+title+" — scripts */\n"); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Open\nDouble-click \`index.html\` in your browser.\n\nOr serve locally:\n\`\`\`bash\nnpx serve .\n# or\npython3 -m http.server 3000\n\`\`\`\n"); zip.file(folder+".gitignore",".DS_Store\nnode_modules/\n.env\n"); } /* ===== MAIN ===== */ var sc=document.createElement("script"); sc.src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"; sc.onerror=function(){ if(lbl)lbl.textContent="Download ZIP"; alert("JSZip load failed — check connection."); }; sc.onload=function(){ var zip=new JSZip(); var base=(_phFname||"output").replace(/\.[^.]+$/,""); var app=base.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; var folder=app+"/"; var vc=document.getElementById("panel-content"); var panelTxt=vc?(vc.innerText||vc.textContent||""):""; var lang=detectLang(_phCode,panelTxt); if(_phIsHtml){ buildVanillaHtml(zip,folder,app,_phCode); } else if(lang==="flutter"){ buildFlutter(zip,folder,app,_phCode,panelTxt); } else if(lang==="react-native"){ buildReactNative(zip,folder,app,_phCode,panelTxt); } else if(lang==="swift"){ buildSwift(zip,folder,app,_phCode,panelTxt); } else if(lang==="kotlin"){ buildKotlin(zip,folder,app,_phCode,panelTxt); } else if(lang==="react"){ buildReact(zip,folder,app,_phCode,panelTxt); } else if(lang==="vue"){ buildVue(zip,folder,app,_phCode,panelTxt); } else if(lang==="angular"){ buildAngular(zip,folder,app,_phCode,panelTxt); } else if(lang==="python"){ buildPython(zip,folder,app,_phCode); } else if(lang==="node"){ buildNode(zip,folder,app,_phCode); } else { /* Document/content workflow */ var title=app.replace(/_/g," "); var md=_phAll||_phCode||panelTxt||"No content"; zip.file(folder+app+".md",md); var h=""+title+""; h+="

"+title+"

"; var hc=md.replace(/&/g,"&").replace(//g,">"); hc=hc.replace(/^### (.+)$/gm,"

$1

"); hc=hc.replace(/^## (.+)$/gm,"

$1

"); hc=hc.replace(/^# (.+)$/gm,"

$1

"); hc=hc.replace(/\*\*(.+?)\*\*/g,"$1"); hc=hc.replace(/\n{2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\nFiles:\n- "+app+".md (Markdown)\n- "+app+".html (styled HTML)\n"); } zip.generateAsync({type:"blob"}).then(function(blob){ var a=document.createElement("a"); a.href=URL.createObjectURL(blob); a.download=app+".zip"; a.click(); URL.revokeObjectURL(a.href); if(lbl)lbl.textContent="Download ZIP"; }); }; document.head.appendChild(sc); } function phShare(){navigator.clipboard.writeText(window.location.href).then(function(){var el=document.getElementById("ph-share-lbl");if(el){el.textContent="Link copied!";setTimeout(function(){el.textContent="Copy share link";},2500);}});}function phEmbed(){var runId=window.location.pathname.split("/").pop().replace(".html","");var embedUrl="https://pantherahive.com/embed/"+runId;var code='';navigator.clipboard.writeText(code).then(function(){var el=document.getElementById("ph-embed-lbl");if(el){el.textContent="Embed code copied!";setTimeout(function(){el.textContent="Get Embed Code";},2500);}});}