Unit Test Generator
Run ID: 69cac9faeff1ba2b79624d0d2026-03-30Development
PantheraHive BOS
BOS Dashboard

Unit Test Generator: Code Generation Deliverable

This document presents the comprehensive, detailed, and professional unit test code generated as part of the "Unit Test Generator" workflow. This output is designed to be directly actionable, providing clean, well-commented, and production-ready code along with thorough explanations.


1. Introduction

This step focuses on generating robust unit tests for a specified piece of code. Based on the analysis performed in the previous workflow step (Gemini's code understanding), we have identified critical functionalities and potential edge cases within the target code. The output below delivers a complete unit test suite designed to ensure the reliability, correctness, and maintainability of the target application.

For this demonstration, we will generate unit tests for a hypothetical Calculator class, which serves as a representative example of a common utility class found in many applications.


2. Core Deliverable: Generated Unit Tests

2.1. Target Code Under Test: calculator.py

Below is the Python code for a Calculator class that our generated unit tests will validate. This code has been identified and analyzed by the previous Gemini step as the component requiring test coverage.

text • 710 chars
**Explanation of Target Code:**

The `Calculator` class provides four fundamental arithmetic methods: `add`, `subtract`, `multiply`, and `divide`. Each method is type-hinted for clarity and includes a docstring explaining its purpose, arguments, and return value. Notably, the `divide` method includes error handling to prevent division by zero, raising a `ValueError` in such cases. This robust error handling is a key aspect that our unit tests will verify.

#### 2.2. Generated Unit Test Code: `test_calculator.py`

This section presents the generated unit tests for the `Calculator` class using Python's built-in `unittest` framework. The tests cover normal operations, edge cases, and error conditions.

Sandboxed live preview

Detailed Study Plan: Mastering Unit Test Generator Development

This document outlines a comprehensive, structured study plan designed to equip you with the knowledge and skills necessary to understand, design, and potentially develop a robust Unit Test Generator. This plan is tailored for professionals seeking to deepen their expertise in automated testing, code analysis, and software engineering principles.


1. Overall Goal

The primary goal of this study plan is to enable the learner to conceptually architect, understand the underlying technologies, and apply design principles for building an effective Unit Test Generator. Upon completion, you will be proficient in the core concepts of automated unit testing, code analysis, test case generation strategies, and the architectural considerations for such a system.

2. Target Audience

This plan is ideal for software engineers, quality assurance professionals, technical leads, and architects who:

  • Have a foundational understanding of at least one programming language (e.g., Java, Python, C#, JavaScript).
  • Are familiar with basic software development principles.
  • Are interested in test automation, static analysis, and enhancing software quality through intelligent tooling.

3. Recommended Time Commitment

To maximize learning and retention, we recommend dedicating 10-15 hours per week to this study plan. This includes time for reading, watching lectures, hands-on coding exercises, and project work.


4. Weekly Schedule & Learning Objectives

This 10-week schedule is designed to progressively build your expertise, starting from foundational concepts and moving towards advanced architectural and implementation details.

Week 1: Foundations of Unit Testing & Software Quality

  • Learning Objectives:

* Understand the purpose and benefits of unit testing, TDD (Test-Driven Development), and BDD (Behavior-Driven Development).

* Differentiate between various types of software testing (unit, integration, system, acceptance).

* Identify qualities of good unit tests (FAST: Fast, Autonomous, Repeatable, Self-Validating, Timely).

* Grasp core concepts like code coverage metrics (statement, branch, path coverage).

  • Activities: Read foundational articles/chapters, review existing unit tests in a codebase, write simple unit tests manually.

Week 2: Introduction to Code Analysis & ASTs (Abstract Syntax Trees)

  • Learning Objectives:

* Understand how compilers and interpreters process code (lexing, parsing, semantic analysis).

* Learn about Abstract Syntax Trees (ASTs) as a representation of source code structure.

* Explore tools and libraries for parsing code into ASTs in a chosen language (e.g., JavaParser, Python's ast module, Roslyn for C#, Babel for JavaScript).

* Understand the basics of static code analysis.

  • Activities: Experiment with an AST visualization tool, write a simple program to parse a code snippet and print its AST.

Week 3: Code Instrumentation & Reflection

  • Learning Objectives:

* Understand the concept of reflection and its use in inspecting and modifying code at runtime.

* Explore how to dynamically load classes/modules and invoke methods.

* Learn about bytecode manipulation (for JVM languages) or similar techniques for dynamic code modification.

* Grasp how these techniques enable runtime analysis and test generation.

  • Activities: Write code using reflection to inspect class members, experiment with a bytecode manipulation library (e.g., ASM, ByteBuddy for Java) or dynamic module loading (e.g., importlib in Python).

Week 4: Test Frameworks & Assertion Libraries

  • Learning Objectives:

* Deep dive into popular unit testing frameworks (e.g., JUnit/TestNG for Java, Pytest/unittest for Python, NUnit/xUnit for C#, Jest/Mocha for JavaScript).

* Understand the structure of a test suite, test cases, and test fixtures.

* Become proficient with various assertion libraries and their usage.

* Learn about test runners and how they execute tests and report results.

  • Activities: Implement a comprehensive test suite for a small application using your chosen framework, explore advanced features like parameterized tests.

Week 5: Mocking, Stubbing, and Dependency Injection

  • Learning Objectives:

* Understand the importance of test doubles (mocks, stubs, spies, fakes, dummies) for isolating units under test.

* Learn how to use popular mocking frameworks (e.g., Mockito for Java, unittest.mock for Python, NSubstitute for C#, Jest mocks for JavaScript).

* Grasp the principles of Dependency Injection (DI) and how it facilitates testability.

* Identify scenarios where mocking is appropriate versus when it introduces brittle tests.

  • Activities: Refactor existing code to use DI, write unit tests for classes with complex dependencies using mocking frameworks.

Week 6: Test Case Generation Strategies (Rule-based)

  • Learning Objectives:

* Explore systematic techniques for generating test inputs:

* Boundary Value Analysis: Testing values at the edges of valid ranges.

* Equivalence Partitioning: Dividing input data into partitions that are expected to behave similarly.

* State-Based Testing: Generating tests based on object states and transitions.

* Combinatorial Testing: Generating tests for combinations of inputs.

* Understand challenges in generating expected outputs.

  • Activities: Design and manually generate test cases for a given function using BVA and Equivalence Partitioning, implement a simple function that generates a set of boundary values for a given type/range.

Week 7: Property-Based Testing & Fuzzing

  • Learning Objectives:

* Understand the principles of Property-Based Testing (PBT) as a powerful approach for testing invariants.

* Learn to use PBT frameworks (e.g., Hypothesis for Python, QuickCheck for Haskell/F#, JUnit-Quickcheck for Java).

* Explore basic fuzzing techniques for finding unexpected bugs by providing invalid or random inputs.

* Differentiate between example-based and property-based testing.

  • Activities: Implement property-based tests for a data structure or algorithm, experiment with a basic fuzzer against a simple parser.

Week 8: Designing the Unit Test Generator Architecture

  • Learning Objectives:

* Conceptualize the main components of a Unit Test Generator (e.g., Code Parser, Static Analyzer, Test Case Generator Core, Test Framework Adapter, Code Formatter, Output Manager).

* Identify key architectural patterns and design principles applicable to building such a tool.

* Understand the data flow and interactions between different modules.

* Consider scalability, extensibility, and configurability.

  • Activities: Draft a high-level architectural diagram for a UTG, document the responsibilities of each component, identify potential integration points (e.g., IDEs, CI/CD).

Week 9: Implementation & Integration Considerations

  • Learning Objectives:

* Understand practical aspects of building the generator: language choice, tooling, build systems.

* Explore strategies for integrating the generator into existing development workflows (e.g., CLI tools, IDE plugins, CI/CD pipelines).

* Consider performance optimization and error handling within the generator.

* Learn about code generation best practices (e.g., template engines, code formatting).

  • Activities: Develop a Proof-of-Concept (POC) for a core component of your UTG (e.g., a module that takes an AST and generates a basic test shell), research existing open-source test generators.

Week 10: Advanced Topics & AI/ML for Test Generation (Optional)

  • Learning Objectives:

* Explore advanced techniques such as mutation testing for assessing test suite effectiveness.

* Understand the potential role of Artificial Intelligence (AI) and Machine Learning (ML), particularly Large Language Models (LLMs), in more intelligent test case generation (e.g., inferring test scenarios, generating complex mocks).

* Research current trends and academic papers in automated test generation.

  • Activities: Investigate a mutation testing tool, explore how LLMs are being used for code generation, read a research paper on AI-driven test generation.

5. Recommended Resources

  • Books:

* "Working Effectively with Legacy Code" by Michael C. Feathers (for understanding testability)

* "Test Driven Development: By Example" by Kent Beck

* "Clean Code: A Handbook of Agile Software Craftsmanship" by Robert C. Martin (Chapter on Unit Tests)

* "The Art of Unit Testing" by Roy Osherove

* "Software Testing: A Craftsman's Approach" by Paul C. Jorgensen (for test case generation strategies)

* "Compiler Design: Principles, Techniques, and Tools" by Aho, Lam, Sethi, Ullman (the "Dragon Book" - for ASTs, parsing)

  • Online Courses (e.g., Coursera, Udemy, edX, Pluralsight):

* Courses on specific programming language unit testing frameworks.

* Courses on Static Program Analysis or Compiler Design.

* Courses on Software Design and Architecture.

  • Documentation:

* Official documentation for chosen unit testing frameworks (JUnit, Pytest, NUnit, Jest, Mocha).

* Official documentation for chosen mocking frameworks (Mockito, unittest.mock, NSubstitute, Jest).

* Documentation for AST parsing libraries (e.g., JavaParser, Python ast module, Roslyn SDK).

* Documentation for Property-Based Testing libraries (e.g., Hypothesis).

  • Research Papers & Articles:

* Google Scholar, ACM Digital Library, IEEE Xplore for "Automated Test Generation," "Mutation Testing," "Property-Based Testing," "Fuzz Testing."

* Blogs and articles from leading software engineering companies on their testing practices.

  • Open Source Projects:

* Explore existing open-source unit test frameworks and code analysis tools to understand their internal workings.

* Look for smaller open-source projects that generate code or tests for inspiration.


6. Milestones

  • End of Week 2: Successfully parse a simple code file into an AST

Explanation of Generated Unit Test Code:

  1. import unittest: Imports Python's standard library module for unit testing.
  2. from calculator import Calculator: Imports the Calculator class, assuming calculator.py is in the same directory.
  3. class TestCalculator(unittest.TestCase): Defines a test class that inherits from unittest.TestCase. This inheritance provides access to various assertion methods and test runner functionalities.
  4. setUp(self): This method is called before each test method execution. It's used to set up the test environment, in this case, creating a new Calculator instance. This ensures that each test is isolated and doesn't affect subsequent tests.
  5. Test Methods (test_add_positive_numbers, test_divide_by_zero_raises_error, etc.):

* Each method prefixed with test_ is automatically discovered and run by the unittest test runner.

* Descriptive Naming: Test method names clearly indicate what scenario or functionality they are testing (e.g., test_add_positive_numbers, test_divide_by_zero_raises_error). This enhances readability and maintainability.

* Assertions:

* self.assertEqual(a, b): Asserts that a is equal to b. Used for exact comparisons of integers and strings.

* self.assertAlmostEqual(a, b): Asserts that a is approximately equal to b. This is crucial for comparing floating-point numbers, which can have precision issues.

* self.assertRaises(ExceptionType): This context manager is used to verify that a specific exception is raised when expected. It's vital for testing error handling logic, such as division by zero.

* self.assertTrue(condition), self.assertFalse(condition): Can be used for boolean conditions. (Not explicitly used here but good to know).

  1. Comprehensive Coverage: The tests cover a wide range of scenarios for each arithmetic operation:

* Positive and negative numbers.

* Zero inputs.

* Floating-point numbers.

* Edge cases (e.g., subtracting a larger number from a smaller one, division by one).

* Error conditions (e.g., division by zero).

  1. Docstrings: Each test method includes a docstring explaining its specific purpose, making the test suite self-documenting.
  2. if __name__ == '__main__': unittest.main(): This block allows the test file to be run directly from the command line, executing all tests within the TestCalculator
gemini Output

Unit Test Generation: Review & Documentation Deliverable

This document provides a comprehensive review and detailed documentation of the unit tests generated for your specified codebase. This output marks the completion of Step 3 of 3 in the "Unit Test Generator" workflow, ensuring you have clear, actionable insights into the generated tests and how to effectively utilize them.


1. Introduction

We are pleased to present the review and documentation for the unit tests generated by our system. The primary goal of this step is to ensure that the generated tests are not only accurate and comprehensive but also well-understood, maintainable, and easily integrable into your development workflow. This document covers the structure, coverage, usage instructions, and recommendations for maximizing the value of the provided unit test suite.


2. Summary of Generated Unit Tests

The Unit Test Generator has successfully produced a suite of unit tests designed to validate the core functionality of your specified component(s). The generated tests focus on isolating individual units of code (e.g., functions, methods, classes) and verifying their behavior against expected outcomes, covering typical use cases, edge cases, and error conditions where applicable.

Key Highlights:

  • Targeted Components: The tests specifically target the following component(s): [Placeholder: e.g., CalculatorService class, data_processor.py module, UserAuthentication module]
  • Framework Used: The tests are generated using the [Placeholder: e.g., unittest (Python), JUnit 5 (Java), Jest (JavaScript), xUnit.net (C#)] testing framework.
  • Output Format: The generated tests are provided as [Placeholder: e.g., .py files, .java files, .js files, .cs files] ready for execution.

3. Detailed Review of Generated Tests

3.1. Targeted Component(s) and Scope

The generated unit tests are specifically designed for the [Placeholder: e.g., Calculator class in calculator.py] component. The scope of these tests includes:

  • add(a, b): Verification of correct addition for various integer and float inputs.
  • subtract(a, b): Validation of subtraction logic.
  • multiply(a, b): Testing multiplication, including by zero and negative numbers.
  • divide(a, b): Comprehensive testing of division, including division by zero error handling.
  • [Add more specific functions/methods targeted if applicable]

3.2. Test Suite Structure and Organization

The generated tests are organized into a clear and logical structure to enhance readability and maintainability.

  • File Structure:

* A dedicated test file, e.g., test_calculator.py, has been created.

* This file is typically placed in a tests/ directory at the project root or alongside the source code.

  • Test Classes:

* Tests for a specific component (e.g., Calculator) are encapsulated within a test class, e.g., TestCalculator(unittest.TestCase).

  • Test Methods:

* Each distinct test case is implemented as a separate method within the test class, following standard naming conventions (e.g., test_add_positive_numbers, test_divide_by_zero_raises_error).

3.3. Key Test Cases Generated (Illustrative Examples)

The generator focused on creating a balanced set of test cases to ensure robust validation. Below are illustrative examples of the types of tests generated:

  • Basic Functionality / Happy Path:

* test_add_positive_numbers(): self.assertEqual(calculator.add(2, 3), 5)

* test_subtract_positive_numbers(): self.assertEqual(calculator.subtract(5, 2), 3)

* test_multiply_by_one(): self.assertEqual(calculator.multiply(7, 1), 7)

  • Edge Cases:

* test_add_zero(): self.assertEqual(calculator.add(5, 0), 5)

* test_subtract_to_zero(): self.assertEqual(calculator.subtract(5, 5), 0)

* test_multiply_by_zero(): self.assertEqual(calculator.multiply(10, 0), 0)

  • Negative Scenarios / Error Handling:

* test_divide_by_zero_raises_error(): with self.assertRaises(ValueError): calculator.divide(10, 0)

* test_add_negative_numbers(): self.assertEqual(calculator.add(-2, -3), -5)

* test_subtract_negative_from_positive(): self.assertEqual(calculator.subtract(5, -2), 7)

  • Data Type Variations (if applicable):

* test_add_floats(): self.assertAlmostEqual(calculator.add(2.5, 3.5), 6.0)

3.4. Test Assertions Used

The generator utilized standard assertion methods provided by the chosen testing framework to verify expected outcomes. Common assertions include:

  • assertEqual(expected, actual)
  • assertNotEqual(expected, actual)
  • assertTrue(condition)
  • assertFalse(condition)
  • assertIsNone(obj)
  • assertIsNotNone(obj)
  • assertRaises(ExceptionType, callable, args, *kwargs)
  • assertAlmostEqual(expected, actual, places=N) (for floating-point comparisons)

3.5. Readability and Maintainability

The generated tests prioritize readability and maintainability:

  • Clear Naming Conventions: Test methods are named descriptively to indicate their purpose.
  • Minimal Setup: Tests are designed to have minimal setup, focusing on the unit under test.
  • Isolated Tests: Each test case is independent, ensuring that failures in one test do not cascade to others.
  • Comments: Relevant comments are added where complex logic or specific assumptions are made.

4. How to Use and Integrate the Tests

4.1. Prerequisites and Dependencies

To run the generated tests, ensure you have the following:

  • Python Environment: Python 3.x installed.
  • Testing Framework: The unittest module is built into Python's standard library, so no additional installation is typically required.

(If another framework was used, e.g., pytest, specify installation: pip install pytest)*

  • Source Code: The original source code of the component(s) being tested must be accessible (e.g., calculator.py in the same directory or accessible via Python path).

4.2. Setup Instructions

  1. Locate Test Files: Place the generated test file(s) (e.g., test_calculator.py) in a tests/ directory within your project structure, or alongside the source file if preferred for smaller projects.

    my_project/
    ├── src/
    │   └── calculator.py
    └── tests/
        └── test_calculator.py
  1. Ensure Pathing: Verify that your sys.path or project structure allows the test files to import the source code correctly. You might need to add sys.path.append('../src') or similar relative imports in your test files if the structure differs.

4.3. Running the Tests

You can execute the unit tests using your terminal:

  1. Navigate to Project Root: Open your terminal and navigate to the root directory of your project (e.g., my_project/).
  2. Run unittest Discover:

    python -m unittest discover tests

* Replace tests with the actual path to your test directory if it's named differently.

* To run a specific test file: python -m unittest tests.test_calculator

* To run a specific test method: python -m unittest tests.test_calculator.TestCalculator.test_add_positive_numbers

4.4. Integration with CI/CD Pipelines (Recommendation)

We highly recommend integrating these unit tests into your Continuous Integration/Continuous Deployment (CI/CD) pipeline. This will ensure that all code changes are automatically validated against the test suite, catching regressions early in the development cycle.

  • Example for GitHub Actions:

    name: Run Unit Tests

    on: [push, pull_request]

    jobs:
      build:
        runs-on: ubuntu-latest
        steps:
        - uses: actions/checkout@v3
        - name: Set up Python
          uses: actions/setup-python@v4
          with:
            python-version: '3.x'
        - name: Install dependencies (if any)
          run: |
            # pip install -r requirements.txt # Uncomment if you have dependencies
        - name: Run unit tests
          run: |
            python -m unittest discover tests

5. Assumptions and Limitations

5.1. Assumptions Made During Generation

  • Isolated Units: The generator assumed that the provided code units (functions, methods) could be tested in isolation without complex external dependencies (e.g., databases, external APIs, UI components).
  • Deterministic Behavior: It's assumed that the unit under test exhibits deterministic behavior given the same inputs.
  • Standard Library Usage: Assumed usage of standard Python data types and libraries unless specific external dependencies were explicitly declared in the input.

5.2. Known Limitations

  • External Dependencies: Tests involving complex external systems (databases, network calls, file I/O) are typically mocked or stubbed. The generated tests provide basic mocking where feasible, but extensive mocking might require manual refinement.
  • UI/Integration Tests: This generator focuses solely on unit tests. It does not produce integration, end-to-end, or UI tests.
  • Business Logic Complexity: While a good range of test cases is generated, highly intricate or domain-specific business logic might require additional, manually crafted tests to cover all permutations.
  • Performance Testing: No performance-related assertions or benchmarks are included in these unit tests.
  • Security Testing: Unit tests primarily focus on functional correctness, not security vulnerabilities.

6. Recommendations for Further Enhancement

To further strengthen your testing strategy and codebase quality, consider the following enhancements:

  • Expand Test Coverage:

* Boundary Conditions: Manually review and add more tests for specific boundary values that might be critical to your application's domain.

* Error Paths: Explore all possible error conditions and ensure robust error handling is tested.

* Complex Scenarios: For highly complex functions, consider using property-based testing (e.g., Hypothesis for Python) to explore a wider range of inputs automatically.

  • Refactor and Optimize Tests:

* Test Data Management: For tests requiring complex setup data, consider using fixtures or factories to simplify test data creation.

* Parameterization: If many tests follow similar patterns with different inputs/outputs, consider test parameterization to reduce duplication.

  • Introduce Other Test Types:

* Integration Tests: Develop tests that verify the interaction between multiple components or with external services.

* End-to-End (E2E) Tests: Create tests that simulate user workflows through the entire application.

* Performance Tests: Use tools to measure and monitor the performance of critical components.

* Code Coverage Tools: Integrate tools like coverage.py to get a precise report on lines, branches, and statements covered by your tests, helping identify untested areas.

  • Documentation: Maintain clear documentation for your test suite, explaining its purpose, structure, and any specific testing strategies employed.

7. Next Steps

  1. Review Generated Code: Carefully examine the actual generated unit test files provided alongside this documentation.
  2. Integrate into Project: Place the test files into your project structure as described in Section 4.2.
  3. Execute Tests: Run the tests locally to ensure they pass and integrate them into your CI/CD pipeline.
  4. Customize and Extend: Use the generated tests as a strong foundation, and extend them with additional test cases or refactor them to better suit your project's specific needs and conventions.
  5. Feedback: Provide us with any feedback on the generated tests or this documentation to help us improve our services.

8. Support and Contact

Should you have any questions, require further assistance, or wish to discuss custom test generation requirements, please do not hesitate to contact our support team at [Placeholder: support@pantherahive.com] or through your dedicated account manager.


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