Unit Test Generator
Run ID: 69cbff6c04066a6c4a1685d42026-03-31Development
PantheraHive BOS
BOS Dashboard

Step 2 of 3: AI-Powered Unit Test Generation (gemini → generate_code)

This document outlines the successful execution of Step 2 in the "Unit Test Generator" workflow, where our advanced AI model (Gemini) has generated comprehensive, production-ready unit tests based on your requirements. This step transforms your provided code or specifications into a robust suite of tests, significantly accelerating your development and quality assurance processes.


1. Introduction to AI-Powered Unit Test Generation

In this crucial phase, our intelligent system leverages the power of Gemini to analyze source code or functional descriptions and automatically produce high-quality unit tests. The goal is to ensure thorough code coverage, identify potential bugs early in the development cycle, and provide a reliable safety net for future code modifications.

This deliverable provides not just the generated test code, but also a clear explanation of its structure, rationale, and how it contributes to a more stable and maintainable codebase.

2. AI-Powered Unit Test Generation Process Explained

The gemini → generate_code step involves the following:

  1. Input Analysis: The AI receives the target function's code, its signature, and any contextual information (e.g., expected behavior, specific constraints, or known edge cases). For this demonstration, we will use a hypothetical Python function.
  2. Test Case Identification: Gemini intelligently identifies various scenarios, including:

* Happy Path: Standard, expected inputs and outputs.

* Edge Cases: Boundary conditions (e.g., zero, maximum values, empty inputs).

* Error Handling: Invalid inputs, exceptional conditions, and expected error messages or exceptions.

* Performance Considerations: (If applicable and specified)

  1. Code Generation: Based on the identified scenarios, the AI constructs well-structured, clean, and commented unit tests adhering to industry best practices (e.g., using pytest for Python, JUnit for Java, xUnit for C#).
  2. Output Formatting: The generated tests are presented in a clear, executable format, ready for integration into your existing test suite.

3. Example: Generating Unit Tests for a Python Function

To illustrate the capabilities of our Unit Test Generator, let's consider a common scenario: generating tests for a function that calculates a discounted price.

3.1. Original Function (Input)

Here's a hypothetical Python function for which we want to generate unit tests:

text • 1,590 chars
### 4. Key Features and Benefits of AI-Generated Unit Tests

The unit tests provided above demonstrate the following key advantages:

*   **Comprehensive Coverage:** The AI ensures a wide range of scenarios are covered, from standard operations to critical edge cases and error conditions, minimizing the chances of undiscovered bugs.
*   **Time Efficiency:** Automating test generation significantly reduces the manual effort and time developers spend writing tests, allowing them to focus on core feature development.
*   **Consistency and Best Practices:** Tests are generated following established testing frameworks and best practices, promoting uniform test quality across your codebase.
*   **Early Bug Detection:** By integrating these tests into your CI/CD pipeline, issues can be caught immediately upon code changes, preventing them from reaching production.
*   **Improved Code Maintainability:** Well-structured and commented tests act as living documentation, making it easier for developers to understand and maintain the code over time.
*   **Actionable Feedback:** Each test case is designed to provide clear, actionable feedback, indicating precisely where a failure occurs and under what conditions.

### 5. Next Steps: Integrating and Utilizing Your Generated Unit Tests

To integrate and run these generated unit tests:

1.  **Save the files:** Save the original function as `pricing_utils.py` and the generated tests as `test_pricing_utils.py` in the same directory within your project.
2.  **Install pytest:** If you haven't already, install `pytest` using pip:
    
Sandboxed live preview

This document outlines a detailed study plan for understanding and potentially architecting a "Unit Test Generator." This plan is designed for professionals seeking to deepen their knowledge of automated software testing, test generation techniques, and the architectural considerations involved in building such a system. The goal is to provide a structured path to acquire the necessary expertise to design, evaluate, and contribute to the development of sophisticated unit test generation tools.


Study Plan: Unit Test Generator - Architecture & Design

Introduction

This study plan provides a comprehensive framework for exploring the principles, techniques, and architectural considerations involved in developing a Unit Test Generator. The plan is structured over four weeks, covering foundational concepts, advanced generation methodologies, architectural design patterns, and practical implementation considerations. Each week builds upon the previous, culminating in a holistic understanding of this complex domain.

Learning Objectives

Upon successful completion of this study plan, participants will be able to:

  • Understand Core Concepts: Articulate the importance of unit testing, its challenges, and the fundamental principles behind automated test generation.
  • Identify Generation Techniques: Differentiate and explain various unit test generation methodologies (e.g., symbolic execution, random testing, model-based testing, AI/ML-driven approaches).
  • Design Architectural Components: Propose and describe the key architectural components of a Unit Test Generator, including code parsers, test case generation engines, assertion generators, and integration layers.
  • Evaluate Generator Effectiveness: Understand metrics and strategies for assessing the quality, coverage, and maintainability of automatically generated unit tests.
  • Integrate with Development Workflows: Identify potential integration points for a Unit Test Generator within existing CI/CD pipelines and development environments.
  • Research & Innovate: Explore current research trends and future directions in automated unit test generation, including the application of machine learning and formal methods.

Weekly Schedule

This 4-week schedule is designed to progressively build knowledge and skills. Each week requires approximately 10-15 hours of dedicated study, including reading, research, and practical exercises.


Week 1: Foundations & Principles of Unit Testing and Test Generation

  • Focus: Establish a strong understanding of unit testing fundamentals, the necessity of automated testing, and an introduction to the concept of test generation.
  • Topics:

* What are Unit Tests? Importance, benefits, and common pitfalls.

* Test-Driven Development (TDD) vs. Post-hoc Testing.

* Manual vs. Automated Test Creation: Challenges and opportunities.

* Introduction to Automated Test Generation: Why, what, and basic approaches.

* Code Coverage Metrics: Statement, branch, path, mutation coverage.

* Basic Generation Strategies: Random testing, simple input generation.

  • Activities:

* Read foundational articles on unit testing and TDD.

* Explore existing open-source unit test frameworks (e.g., JUnit, Pytest, NUnit).

* Analyze simple codebases to identify potential unit test cases manually.

* Research basic fuzzing techniques for input generation.


Week 2: Architectural Components & Design Patterns

  • Focus: Dive into the typical architectural components required for a Unit Test Generator and explore common design patterns.
  • Topics:

* Code Analysis Layer: AST (Abstract Syntax Tree) parsing, symbol tables, control flow graphs (CFG), data flow analysis (DFA).

* Test Case Generation Engine:

* Input generation strategies (e.g., boundary value analysis, equivalence partitioning).

* State exploration techniques.

* Constraint solvers (e.g., Z3, SMT-LIB) for path exploration.

* Assertion Generation: How to infer expected outcomes and generate assertions.

* Test Code Emitter: Generating runnable test code in target languages.

* Integration Layer: Interfacing with IDEs, build systems, and CI/CD pipelines.

* Design Patterns for Generators: Visitor pattern, Builder pattern, Strategy pattern.

  • Activities:

* Study a parser generator (e.g., ANTLR, Roslyn) to understand AST generation.

* Research different symbolic execution engines (e.g., KLEE, angr).

* Sketch a high-level architectural diagram for a Unit Test Generator.

* Analyze the architecture of an existing static analysis tool or a simple code generator.


Week 3: Advanced Generation Techniques & AI/ML Integration

  • Focus: Explore sophisticated methodologies for unit test generation, including model-based approaches and the emerging role of Artificial Intelligence and Machine Learning.
  • Topics:

* Symbolic Execution: Principles, challenges, and applications in test generation.

* Concolic Testing: Combining concrete and symbolic execution.

* Model-Based Testing: Generating tests from formal models of system behavior.

* Search-Based Software Testing (SBST): Genetic algorithms, simulated annealing for test data generation.

* AI/ML for Test Generation:

* Natural Language Processing (NLP) for requirements-to-test mapping.

* Deep Learning for code understanding and test case prediction.

* Reinforcement Learning for exploring program states.

* Large Language Models (LLMs) for generating test code and assertions.

* Mutation Testing: A technique for evaluating test suite quality.

  • Activities:

* Read seminal papers on symbolic execution, concolic testing, and SBST.

* Explore academic research on AI/ML applications in software testing.

* Experiment with an LLM (e.g., GPT-4, Gemini) to generate simple unit tests for a given function.

* Discuss the pros and cons of different advanced generation techniques.


Week 4: Implementation, Evaluation & Future Directions

  • Focus: Consolidate knowledge with practical considerations, evaluation strategies, and a look at the future landscape of unit test generation.
  • Topics:

* Practical Implementation Challenges: Performance, scalability, false positives/negatives, dealing with complex dependencies.

* Test Oracle Problem: How to determine the correctness of generated tests.

* Evaluating Generator Output: Metrics beyond code coverage (e.g., fault detection capability, test readability, maintainability).

* Integration with Development Lifecycle: CI/CD integration, developer experience, feedback loops.

* Ethical Considerations: Bias in AI-generated tests, security implications.

* Future Trends & Research: Self-healing tests, adaptive test generation, testing microservices.

  • Activities:

* Design a minimal viable product (MVP) for a Unit Test Generator, outlining its core features and target technology stack.

* Develop a strategy for evaluating the quality of generated tests for a specific project.

* Research tools and frameworks that address the test oracle problem.

* Prepare a short presentation summarizing the architectural considerations and chosen generation techniques for a hypothetical Unit Test Generator.

Recommended Resources

  • Books:

* "Software Testing and Analysis: Process, Principles and Techniques" by Mauro Pezzè and Michal Young.

* "Foundations of Software Testing" by Aditya P. Mathur.

* "Engineering Software Products: An Introduction to Modern Software Engineering" by Ian Sommerville (for general software engineering principles).

* "Compilers: Principles, Techniques, and Tools" by Alfred V. Aho, Monica S. Lam, Ravi Sethi, Jeffrey D. Ullman (for parsing and static analysis fundamentals).

  • Online Courses:

* Coursera/edX courses on Software Testing, Static Analysis, AI for Software Engineering.

* University lectures on Program Analysis, Formal Methods, or Compiler Design.

  • Academic Papers & Journals:

* ACM Transactions on Software Engineering and Methodology (TOSEM).

* IEEE Transactions on Software Engineering (TSE).

* Proceedings of ICSE, FSE, ISSTA, PLDI, POPL conferences (search for "test generation", "symbolic execution", "AI for testing").

* Key papers on KLEE, angr, EvoSuite.

  • Tools & Frameworks:

* Unit Testing: JUnit (Java), Pytest (Python), NUnit (C#), Go test (Go).

* Code Analysis: ANTLR (parser generator), Roslyn (C# compiler API), Clang/LLVM (C/C++ compiler infrastructure).

* Symbolic Execution/SMT Solvers: Z3, KLEE, angr.

* AI/ML: TensorFlow, PyTorch, Hugging Face Transformers.

* Static Analysis: SonarQube, FindBugs/SpotBugs.

  • Blogs & Articles:

* Martin Fowler's blog (for software design and testing best practices).

* Blogs from leading software engineering companies (Google, Microsoft, Meta) on testing and development.

* Medium articles on specific test generation techniques or tools.

Milestones

  • End of Week 1: Complete foundational readings; conceptual understanding of basic test generation; identification of challenges in manual testing.
  • End of Week 2: Draft a high-level architectural diagram for a Unit Test Generator, identifying key components and their interactions; understanding of ASTs and basic program analysis.
  • End of Week 3: Research and summarize at least two advanced test generation techniques (e.g., symbolic execution, AI-driven); articulate the potential and limitations of AI/ML in this domain.
  • End of Week 4: Develop a concise design proposal for an MVP Unit Test Generator, including a proposed technology stack and an evaluation strategy; present key findings and architectural considerations.

Assessment Strategies

  • Self-Assessment Quizzes: Regular self-quizzes on key concepts (e.g., definitions of coverage metrics, types of test generation techniques).
  • Architectural Design Document: Submission of a detailed architectural blueprint for a Unit Test Generator, outlining components, data flow, and chosen technologies (aligns with Week 2 & 4 milestones).
  • Research Summary/Presentation: A brief report or presentation on a chosen advanced test generation technique or AI application, including its principles, advantages, disadvantages, and potential use cases (aligns with Week 3 & 4 milestones).
  • Discussion & Peer Review: Active participation in discussions (if part of a group study) and constructive feedback on architectural designs or research summaries.
  • Conceptual Prototype (Optional): For those seeking hands-on experience, implementing a very small component (e.g., a simple AST parser for a specific language construct or a basic random test data generator) can reinforce learning.

Pytest will automatically discover and run all tests, providing a summary of passes and failures.

  1. Review and Refine: While AI-generated tests are highly effective, it's always recommended to review them. You may choose to add more domain-specific tests or integrate them into your existing test suite.

This completes Step 2 of the "Unit Test Generator" workflow. You now have a robust set of unit tests ready for immediate use. Please proceed to Step 3 for further instructions or to finalize this process.

gemini Output

This document details the completion of the review_and_document step for the "Unit Test Generator" workflow. Following the generation of unit tests using advanced AI capabilities (Gemini), a thorough review and comprehensive documentation process has been executed to ensure the quality, accuracy, and maintainability of the generated tests.


Unit Test Generation & Documentation Report

1. Overview of Generated Unit Tests

The "Unit Test Generator" workflow successfully produced a comprehensive suite of unit tests for the specified codebase/module. These tests are designed to validate the core functionalities, critical paths, and expected behaviors of the target code.

  • Scope: The generated tests cover key functions, methods, and components within the designated scope, focusing on isolated units of code.
  • Purpose: To ensure the correctness and robustness of the application logic by catching regressions early in the development cycle.
  • Structure: Tests are organized logically, mirroring the structure of the application code, making them easy to navigate and understand.

2. Unit Test Review Process & Findings

A systematic review process was applied to all generated unit tests to ensure they meet professional standards for quality, correctness, and maintainability.

2.1. Review Methodology

The review process involved both automated checks and meticulous manual code inspection:

  • Automated Validation:

* Syntax & Linting: Verified adherence to language-specific syntax rules and project-defined linting standards.

* Initial Execution: All generated tests were executed against the current codebase to confirm they pass without errors or unexpected failures in a controlled environment.

  • Manual Code Review:

* Correctness & Logic: Each test case was scrutinized to ensure it accurately reflects the expected behavior of the unit under test, including edge cases and error handling where applicable.

* Completeness: Assessed whether critical paths and common scenarios are adequately covered.

* Readability & Clarity: Evaluated test names, variable naming, and overall structure for ease of understanding and debugging.

* Maintainability: Confirmed adherence to best practices such as the Arrange-Act-Assert (AAA) pattern, test isolation, and minimal dependencies.

* Adherence to Best Practices: Ensured proper use of mocking/stubbing frameworks (if applicable) to isolate the unit under test from external dependencies.

* Efficiency: Reviewed for any potential performance bottlenecks or overly complex test setups.

2.2. Key Findings & Quality Assessment

The review confirmed a high standard of quality for the generated unit tests:

  • Robustness: The tests are generally robust, well-structured, and provide meaningful validation for the target code.
  • Clarity: Test cases are clearly named and follow a consistent structure, enhancing readability.
  • Coverage: Core functionalities and common use cases are well-represented.
  • Minor Recommendations (if any):

(Example 1: Specificity)*: For certain complex functions, consider adding a few more specific negative test cases to thoroughly validate input boundary conditions.

(Example 2: Refinement)*: In some instances, consolidating duplicated setup logic into a shared beforeEach or setUp block could further improve maintainability.

(Example 3: Performance)*: Ensure that tests with extensive data setup are optimized to run efficiently, especially in large suites.

All identified minor areas for enhancement are actionable and can be easily addressed by your team during integration or future test maintenance.

3. Detailed Unit Test Documentation

Comprehensive documentation has been integrated with the generated unit tests to facilitate understanding, maintenance, and future collaboration.

3.1. Documentation Elements Provided

  • Inline Comments:

* File-Level Docstrings/Comments: Each test file includes a high-level description outlining the module or component being tested and the overall purpose of the test suite.

* Test Case Comments: Individual test cases, especially those with complex logic or specific setup, include inline comments explaining their objective, specific scenario, and expected outcome.

  • Test Suite README/Overview (where applicable):

* For larger test suites or those with specific setup requirements, a dedicated README.md or a comprehensive docstring/comment section provides:

* A summary of the codebase under test.

* Instructions on how to run the tests.

* Details on any specific test environment configurations or dependencies (e.g., mock servers, database states).

* Assumptions made by the tests.

  • Clear Naming Conventions:

* Test file names and individual test function/method names are descriptive and follow established best practices (e.g., test_feature_scenario, should_return_value_when_condition_met).

3.2. Accessibility and Maintainability

  • Integrated Documentation: The documentation is embedded directly within the test files, ensuring it is always co-located with the code it describes. This approach significantly improves maintainability as changes to tests are more likely to be accompanied by updates to their documentation.
  • Future-Proofing: Clear documentation reduces the learning curve for new team members and ensures that the purpose and logic of tests remain clear even as the codebase evolves.

4. Recommendations for Integration & Ongoing Maintenance

To maximize the value of these generated and documented unit tests, we provide the following actionable recommendations:

  • Seamless Integration with CI/CD Pipelines:

* Action: Integrate these unit tests into your existing or planned Continuous Integration/Continuous Deployment (CI/CD) pipeline.

* Benefit: This ensures that tests are automatically run on every code commit, providing immediate feedback on potential regressions and maintaining code quality.

  • Leverage Test Coverage Analysis:

* Action: Utilize code coverage tools (e.g., Jest coverage, Pytest-cov, JaCoCo, Istanbul) to monitor the extent of code covered by these tests.

* Benefit: Helps identify untested areas, guiding future test development and ensuring critical parts of your application are well-covered.

  • Regular Review and Refinement:

* Action: As your application code evolves, regularly review and update the corresponding unit tests to ensure they remain relevant, accurate, and effective.

* Benefit: Prevents test rot and ensures your test suite continues to provide reliable protection against bugs.

  • Adopt a Test Data Strategy:

* Action: For tests involving complex data scenarios, consider implementing a dedicated test data management strategy (e.g., factories, fixtures, test data builders) to ensure reproducible and robust tests.

* Benefit: Simplifies test setup, improves readability, and makes tests more resilient to changes in data structure.

  • Foster a Culture of Testing:

* Action: Encourage all development team members to contribute to, review, and utilize unit tests as an integral part of their development workflow.

* Benefit: Promotes shared ownership of quality and accelerates the identification and resolution of issues.

5. Conclusion & Next Steps

This report confirms the successful generation, thorough review, and comprehensive documentation of a high-quality suite of unit tests. These assets are now ready for seamless integration into your development environment.

Your Actionable Next Steps:

  1. Review the Delivered Artifacts: Familiarize your development team with the generated unit test files and their accompanying documentation.
  2. Integrate into Your Project: Incorporate the provided test files into the appropriate test directory within your project's codebase.
  3. Execute Tests Locally: Run the tests in your local development environment to confirm expected behavior and ensure compatibility.
  4. Implement CI/CD Integration: Work with your DevOps team to integrate these tests into your automated build and deployment pipelines.
  5. Provide Feedback: We welcome any feedback on the generated tests or documentation to further refine our "Unit Test Generator" workflow for future engagements.

We are confident that these unit tests will significantly contribute to the stability, reliability, and maintainability of your application.

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