Notification System
Run ID: 69cbba5061b1021a29a8bbd72026-03-31Development
PantheraHive BOS
BOS Dashboard

This document provides a comprehensive and detailed code implementation for a robust Notification System, designed for scalability, flexibility, and maintainability. This output is a direct deliverable for the customer, offering production-ready code along with thorough explanations.


Notification System: Code Implementation

This section delivers the core code components for your Notification System. The architecture is designed to be modular, allowing for easy integration with various communication channels and scalable processing.

1. Architectural Overview

The proposed Notification System follows a microservice-oriented design, leveraging asynchronous processing to ensure high performance and reliability.

text • 143 chars
### 3. Pydantic Schemas

Pydantic schemas are used for data validation and serialization/deserialization with FastAPI.

**`app/schemas.py`**

Sandboxed live preview

Study Plan: Designing a Robust Notification System

This document outlines a comprehensive study plan aimed at equipping you with the knowledge and skills necessary to design, implement, and maintain a scalable and reliable Notification System. This plan is structured to provide a deep dive into the core concepts, technologies, and best practices involved in creating a modern notification infrastructure.

Overall Goal: To develop a thorough understanding of the principles, components, and architectural patterns required to design a high-performance, fault-tolerant, and feature-rich notification system capable of delivering messages across multiple channels.


1. Weekly Schedule

This 5-week schedule provides a structured approach to learning, with each week focusing on a specific set of topics essential for notification system design.

Week 1: Fundamentals & System Design Overview

  • Focus: Introduction to notification systems, core concepts, system design principles, and basic architectural patterns.
  • Topics:

* What is a Notification System? Types (push, pull, real-time, batch).

* Key requirements: reliability, scalability, low latency, multi-channel support, personalization.

* High-level architectural components: sender, queue, processor, dispatcher, receiver.

* Introduction to distributed systems concepts: CAP theorem, consistency models.

* Basic system design interview frameworks (e.g., requirements gathering, estimation, API design, data model).

Week 2: Core Components - Message Queues & Data Storage

  • Focus: Deep dive into the backbone technologies for handling notifications: message queuing and appropriate data storage solutions.
  • Topics:

* Message Queues/Brokers:

* Concepts: producers, consumers, topics, queues, publish/subscribe (Pub/Sub).

* Technologies: Apache Kafka, RabbitMQ, AWS SQS/SNS, Google Cloud Pub/Sub, Azure Service Bus.

* Use cases in notification systems: decoupling, buffering, asynchronous processing, fan-out.

* Data Storage:

* Storing notification templates, user preferences, delivery logs, notification history.

* Database choices: SQL vs. NoSQL (e.g., PostgreSQL, MongoDB, Cassandra, Redis for caching).

* Considerations: write-heavy vs. read-heavy, data retention, indexing for fast lookups.

Week 3: Delivery Channels & External Integrations

  • Focus: Understanding the various channels through which notifications are delivered and how to integrate with external services.
  • Topics:

* Email: SMTP, transactional email services (SendGrid, Mailgun, AWS SES), templating engines.

* SMS: Twilio, Vonage (Nexmo), AWS SNS, local SMS gateways.

* Push Notifications (Mobile): APNs (Apple Push Notification Service), FCM (Firebase Cloud Messaging), SDK integration.

* In-App Notifications: WebSockets, SSE (Server-Sent Events), polling, real-time frameworks.

* Webhooks: Enabling other services to subscribe to notification events.

* Error Handling & Retries: Strategies for failed deliveries, exponential backoff.

Week 4: Advanced Topics - Scalability, Reliability & Monitoring

  • Focus: Designing for large-scale, fault-tolerant operation and ensuring system health.
  • Topics:

* Scalability: Horizontal scaling, load balancing, sharding, microservices architecture.

* Reliability & Fault Tolerance: Idempotency, dead-letter queues (DLQs), circuit breakers, retries, disaster recovery strategies.

* Security: Data encryption (at rest and in transit), authentication/authorization for APIs, rate limiting.

* Monitoring & Alerting: Metrics (delivery rates, latency, error rates), logging, tracing (e.g., OpenTelemetry, Prometheus, Grafana, ELK stack).

* Performance Optimization: Caching strategies, batching, efficient database queries.

Week 5: Best Practices, Case Studies & Architectural Design

  • Focus: Consolidating knowledge, reviewing real-world examples, and practicing architectural design.
  • Topics:

* Design Patterns: Observer pattern, publish-subscribe, fan-out, saga pattern for distributed transactions.

* User Preferences & Personalization: Managing opt-ins/opt-outs, notification preferences, segmentation.

* Throttling & Rate Limiting: Preventing abuse and managing external API quotas.

* Cost Optimization: Efficient use of cloud resources, choosing cost-effective external services.

* Case Studies: Analyze architectures of popular notification systems (e.g., WhatsApp, Slack, Twitter).

* Hands-on Architecture Design: Design a notification system for a hypothetical scenario from scratch, applying learned principles.


2. Learning Objectives

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

  • Comprehend Fundamentals: Articulate the core requirements, challenges, and benefits of a robust notification system.
  • Architectural Design: Design a scalable, reliable, and fault-tolerant notification system architecture from scratch, justifying technology choices.
  • Component Selection: Evaluate and select appropriate message queues, databases, and third-party delivery services based on specific use cases and constraints.
  • Multi-Channel Integration: Understand and implement strategies for delivering notifications across email, SMS, mobile push, and in-app channels.
  • Scalability & Performance: Apply techniques for scaling notification delivery to millions of users, optimizing for low latency and high throughput.
  • Reliability & Resiliency: Implement error handling, retry mechanisms, and fault-tolerant patterns to ensure high delivery rates and system uptime.
  • Monitoring & Security: Define key metrics for monitoring system health and implement security best practices for notification data.
  • User Experience: Design for user preferences, opt-outs, and personalization to enhance the user experience.
  • Problem-Solving: Analyze and troubleshoot common issues in distributed notification systems.

3. Recommended Resources

This list includes a mix of books, online courses, documentation, and articles to support your learning journey.

Books:

  • "Designing Data-Intensive Applications" by Martin Kleppmann: Essential for understanding distributed systems, databases, and message queues.
  • "System Design Interview – An Insider's Guide" by Alex Xu: Provides frameworks and examples for various system designs, including notification systems.
  • "Building Microservices" by Sam Newman: Relevant for understanding how to structure complex systems.

Online Courses & Platforms:

  • Educative.io / Grokking the System Design Interview: Excellent for practical system design problems, often includes notification system examples.
  • Udemy / Coursera / Pluralsight: Search for courses on "Distributed Systems," "Kafka," "RabbitMQ," "AWS SQS/SNS," "System Design."
  • Cloud Provider Documentation (AWS, Azure, GCP):

* AWS: SQS, SNS, Lambda, SES, Pinpoint, DynamoDB.

* Azure: Service Bus, Event Hubs, Notification Hubs, Cosmos DB.

* GCP: Pub/Sub, Cloud Functions, Firebase Cloud Messaging, Firestore.

  • Specific Technologies Documentation:

* Apache Kafka Official Documentation

* RabbitMQ Official Documentation

* Twilio / SendGrid / Mailgun API Documentation

Articles & Blogs:

  • High Scalability Blog: Case studies and architectural insights from major tech companies.
  • Medium / Dev.to: Search for "Notification System Architecture," "Scaling Push Notifications," "Building a Real-time Notification Service."
  • Company Engineering Blogs: Uber, LinkedIn, Facebook, Netflix, Slack often publish articles on their notification infrastructure.

Example Search Terms:* "Uber notification system," "Slack notification architecture," "LinkedIn notification service design."

Practical Tools:

  • Docker: For setting up local environments with Kafka, RabbitMQ, PostgreSQL, etc.
  • Postman/Insomnia: For API testing.
  • Diagramming Tools: Draw.io, Lucidchart, Miro for architectural diagrams.

4. Milestones

Achieving these milestones will mark significant progress through the study plan.

  • Milestone 1 (End of Week 1):

* Successfully articulate the core components and high-level flow of a basic notification system.

* Draw a simple architectural diagram for a single-channel notification system.

  • Milestone 2 (End of Week 2):

* Demonstrate understanding of message queue concepts (Pub/Sub, queues) and their role in a notification system.

* Justify database choices for storing notification data (templates, preferences, logs).

* (Optional but Recommended) Set up a local Kafka/RabbitMQ instance and send/receive a test message.

  • Milestone 3 (End of Week 3):

* Outline the integration points and challenges for at least three different delivery channels (e.g., Email, SMS, Push).

* Design a basic retry mechanism for failed notification deliveries.

  • Milestone 4 (End of Week 4):

* Identify key metrics for monitoring a notification system and propose a monitoring stack.

* Describe strategies for scaling a notification system to handle 10x increased load.

* Explain how to ensure idempotency in notification delivery.

  • Milestone 5 (End of Week 5):

* Final Project: Design a comprehensive notification system architecture for a given set of requirements (e.g., an e-commerce platform, a social media app). This includes drawing detailed diagrams, defining API contracts, choosing technologies, and discussing scalability/reliability aspects.

* Present and defend your architectural design, incorporating best practices and lessons learned.


5. Assessment Strategies

Regular assessment will help solidify understanding and track progress.

  • Weekly Self-Assessments:

* Concept Quizzes: Create short quizzes for yourself based on the week's learning objectives.

* Whiteboard Sessions: Practice drawing architectural diagrams and explaining concepts out loud.

* "Teach Back" Method: Explain complex topics to a peer or even just to yourself as if you were teaching it.

  • Practical Exercises:

* API Integration: Write simple code (e.g., Python, Node.js) to send an email via SendGrid, an SMS via Twilio, or a push notification via FCM.

* Local Setup: Experiment with setting up and configuring message brokers (Kafka, RabbitMQ) and databases (PostgreSQL, MongoDB) locally.

* Data Modeling: Design a data schema for storing user notification preferences and delivery logs.

  • System Design Case Studies:

* Work through various notification system design problems (e.g., from system design interview books or online platforms) to apply learned principles.

* Critique existing notification system architectures and propose improvements.

  • Final Project Presentation:

* The capstone project (Milestone 5) will be the primary assessment, requiring a detailed architectural design, justification of choices, and a presentation. This will demonstrate comprehensive understanding and practical application of the entire study plan.

  • Peer Review (Optional): If possible, collaborate with a study partner to review each other's designs and provide feedback.

This detailed study plan provides a roadmap for mastering the complexities of Notification System design. Consistent effort, hands-on practice, and engagement with the recommended resources will be key to your success.

python

from pydantic import BaseModel, EmailStr, Field

from typing import Optional, Dict, Any

from datetime import datetime

--- Base Schemas ---

class TimestampMixin(BaseModel):

created_at: datetime

updated_at: datetime

class IDMixin(BaseModel):

id: int

--- User Schemas ---

class UserBase(BaseModel):

email: Optional[EmailStr] = None

phone_number: Optional[str] = None

device_token: Optional[str] = None

class UserCreate(UserBase):

# In a real system, user creation might be handled by an auth service.

# Here, we allow creating users with basic notification info.

pass

class UserUpdate(UserBase):

pass

class User(UserBase, IDMixin, TimestampMixin):

class Config:

from_attributes = True # Allows Pydantic to read ORM models

--- Notification Template Schemas ---

class NotificationTemplateBase(BaseModel):

name: str = Field(..., description="Unique name for the notification template (e.g., 'welcome_email')")

channel: str = Field(..., description="Communication channel (e.g., 'email', 'sms', 'push')")

body_template: str = Field(..., description="Template string for the notification body (supports Jinja2-like placeholders)")

subject_template: Optional[str] = Field(None, description="Template string for the notification subject (for email, supports placeholders)")

is_active: bool = True

class NotificationTemplateCreate(NotificationTemplateBase):

pass

class NotificationTemplateUpdate(NotificationTemplateBase):

name: Optional[str] = None

channel: Optional[str] = None

body_template: Optional[str] = None

class NotificationTemplate(NotificationTemplateBase, IDMixin, TimestampMixin):

class Config:

from_attributes = True

--- Notification Schemas ---

class NotificationBase(BaseModel):

user_id: int

channel: str

status: str = "pending" # Initial status

send_at: datetime = Field(default_factory=datetime.utcnow)

subject: Optional[str] = None

body: str

metadata_json: Optional[Dict[str, Any]] = None

class NotificationCreate(BaseModel):

user_id: int = Field(..., description="ID of the recipient user.")

template_name: Optional[str] = Field(None, description="Name of the notification template to use.")

channel: Optional[str] = Field(None, description="Communication channel. Required if template_name is not provided.")

context: Dict[str, Any] = Field({}, description="Key-value pairs for template rendering.")

# For ad-hoc notifications not using a template

ad_hoc_subject: Optional[str] = Field(None, description="Ad-hoc subject. Used if template_name is null.")

ad_hoc_body: Optional[str] = Field(None, description="Ad-hoc body. Used if template_name is null.")

send_at: datetime = Field(default_factory=datetime.utcnow, description="Scheduled send time.")

# Validation logic for ad-hoc vs template-based

@classmethod

def

gemini Output

Notification System: Comprehensive Overview and Documentation Summary

This document provides a comprehensive overview of the proposed Notification System, outlining its core components, key features, integration capabilities, and operational considerations. This deliverable serves as a detailed summary following the design and review phases, intended to provide a clear understanding of the system's architecture and functionality.


1. Executive Summary

The PantheraHive Notification System is designed to provide a robust, reliable, and highly configurable platform for delivering timely and relevant communications to users across various channels. By centralizing notification logic and delivery, it aims to enhance user engagement, streamline operational alerts, and improve overall system responsiveness. This document details the system's capabilities, ensuring alignment with your strategic objectives for communication and user experience.


2. Core Components of the Notification System

The Notification System is built upon a modular architecture, comprising several key components that work in concert to manage the entire notification lifecycle:

  • Notification Service API: A RESTful API that serves as the primary interface for other applications to trigger notifications. It handles request validation, routing, and persistence.
  • Template Management Module: Stores and manages notification templates (e.g., email, SMS, push) with support for dynamic content injection.
  • User Preference Management Module: Allows users to configure their preferred notification channels, frequency, and types, ensuring personalized communication.
  • Channel Adapters: Dedicated modules for integrating with various communication channels (e.g., Email Sender, SMS Gateway, Push Notification Service).
  • Queueing System: Decouples notification requests from delivery, ensuring high throughput, reliability, and resilience against channel outages.
  • Notification History & Logging: Stores records of all sent notifications, their status, and relevant metadata for auditing, debugging, and analytics.
  • Monitoring & Alerting: Provides real-time insights into system health, delivery rates, and error conditions.

3. Key Features and Capabilities

The Notification System offers a rich set of features designed to meet diverse communication needs:

  • Multi-Channel Delivery:

* Email: Rich HTML and plain-text emails, supporting custom branding and attachments.

* SMS: Short Message Service for critical alerts and time-sensitive information.

* Push Notifications: Mobile and web push notifications for real-time engagement.

* In-App Notifications: Direct notifications within the application interface.

* (Optional) Webhooks: For integrating with third-party systems or custom endpoints.

  • Dynamic Templating:

* Support for handlebars, Jinja2, or similar templating engines to personalize messages with user-specific data.

* Version control for templates to manage changes effectively.

  • User Preference Management:

* Granular control for users to opt-in/out of specific notification types or channels.

* Ability to set notification frequency (e.g., daily digests vs. immediate alerts).

  • Prioritization and Throttling:

* Assign priority levels to notifications to ensure critical messages are delivered promptly.

* Implement throttling mechanisms to prevent spamming users or overloading channel providers.

  • Delivery Status Tracking:

* Real-time status updates (e.g., sent, delivered, failed, opened) for each notification.

* Retry mechanisms for failed deliveries with configurable back-off strategies.

  • Auditing and Reporting:

* Comprehensive logs for all notification events, including sender, recipient, content, and delivery status.

* Reporting dashboards for key metrics such as delivery rates, open rates, and channel performance.

  • Scheduled Notifications:

* Ability to schedule notifications for future delivery at specific times or intervals.


4. Integration Points

The Notification System is designed for seamless integration with your existing and future applications:

  • API Integration:

* Exposes a well-documented RESTful API for triggering notifications from any internal or external service.

* Authentication and authorization mechanisms (e.g., API keys, OAuth 2.0) to secure access.

  • Event-Driven Architecture:

* Can subscribe to events from other systems (e.g., "Order Placed," "Password Reset") to automatically trigger relevant notifications.

* Publishes notification delivery status events for other systems to consume.

  • CRM/User Management Systems:

* Integration with your existing CRM or user database to fetch user profiles, contact information, and preferences.

  • External Communication Providers:

* Pre-built or easily extensible adapters for popular email services (e.g., SendGrid, Mailgun), SMS gateways (e.g., Twilio, Nexmo), and push notification services (e.g., Firebase Cloud Messaging, Apple Push Notification Service).


5. Scalability and Reliability

The system is engineered for high availability and performance:

  • Horizontal Scalability: Designed to scale horizontally by adding more instances of stateless components.
  • Fault Tolerance: Utilizes redundant components and resilient queuing mechanisms to ensure service continuity even during component failures.
  • Asynchronous Processing: Leverages message queues to process notification requests asynchronously, preventing bottlenecks and ensuring responsiveness.
  • Disaster Recovery: Includes strategies for data backup and recovery to minimize data loss and downtime in catastrophic events.

6. Security Considerations

Security is paramount and has been integrated throughout the system's design:

  • Data Encryption:

* Encryption of sensitive data (e.g., API keys, user contact details) at rest and in transit (TLS/SSL).

  • Access Control:

* Role-Based Access Control (RBAC) for managing who can configure, trigger, or view notification data.

* API authentication and authorization for all external interactions.

  • Input Validation:

* Strict input validation on all API endpoints to prevent injection attacks and malformed requests.

  • Auditing:

* Comprehensive audit trails for all critical actions and configuration changes.

  • Compliance:

* Designed with considerations for data privacy regulations (e.g., GDPR, CCPA) regarding user consent and data handling.


7. Customization and Extensibility

The Notification System is built to be adaptable to evolving needs:

  • Configurable Rules Engine: Allows for defining complex rules for notification delivery based on user attributes, event data, and business logic.
  • Extensible Channel Adapters: New communication channels can be integrated by developing new adapters without modifying core system logic.
  • API-First Design: Facilitates custom integrations and extensions by exposing all core functionalities via APIs.

8. Management and Monitoring

Operational excellence is supported by robust management and monitoring tools:

  • Admin Dashboard: A user-friendly interface for managing templates, user preferences, viewing delivery logs, and configuring system settings.
  • Real-time Metrics: Integration with monitoring platforms (e.g., Prometheus, Grafana, Datadog) to track key performance indicators (KPIs) like message throughput, latency, and error rates.
  • Automated Alerts: Configurable alerts for critical issues such as delivery failures, service outages, or performance degradation.
  • Logging: Centralized logging of all system activities for debugging, auditing, and performance analysis.

9. Proposed Implementation Phases (High-Level)

To ensure a structured and efficient deployment, we propose the following high-level implementation phases:

  1. Phase 1: Foundation & Core Services (Weeks 1-4)

* Set up core Notification Service API.

* Implement Queueing System.

* Integrate initial channel (e.g., Email).

* Develop basic Template Management and User Preference modules.

* Establish initial monitoring and logging.

  1. Phase 2: Channel Expansion & Advanced Features (Weeks 5-8)

* Integrate additional channels (e.g., SMS, Push Notifications).

* Enhance Template Management with versioning.

* Implement Prioritization and Throttling.

* Develop Admin Dashboard for basic management.

  1. Phase 3: Integration & Optimization (Weeks 9-12)

* Integrate with primary client applications.

* Refine User Preference Management.

* Implement comprehensive reporting and analytics.

* Conduct extensive testing (performance, security, UAT).

* Finalize documentation and training materials.

  1. Phase 4: Go-Live & Post-Launch Support (Week 13 onwards)

* Production deployment.

* Continuous monitoring and optimization.

* Dedicated support and maintenance.

Note: Specific timelines are estimates and subject to detailed planning and resource allocation.


10. Next Steps

To move forward with the implementation of the Notification System, we recommend the following actions:

  1. Review and Feedback: Please review this comprehensive overview and provide any feedback, questions, or requests for clarification.
  2. Detailed Requirements Workshop: Schedule a workshop to finalize specific notification types, content requirements, and user preference configurations.
  3. Integration Planning: Identify the primary applications that will integrate with the Notification System and define their integration points and data exchange requirements.
  4. Resource Allocation: Confirm the necessary resources (technical, operational) for successful implementation and ongoing management.

11. Documentation Summary

The following documentation will be provided and maintained throughout the project lifecycle:

  • System Architecture Document: Detailed technical design of the Notification System components and their interactions.
  • API Reference Guide: Comprehensive documentation for all Notification Service API endpoints, including request/response formats, authentication, and error codes.
  • User Guide (Admin Dashboard): Instructions for managing templates, preferences, and viewing reports via the admin interface.
  • Integration Guides: Step-by-step instructions for integrating client applications with the Notification System.
  • Deployment and Operations Guide: Information on deploying, monitoring, and maintaining the system in a production environment.
  • Security Documentation: Overview of security measures and compliance considerations.

We are confident that this Notification System will significantly enhance your communication capabilities and user experience. We look forward to collaborating closely with your team to bring this solution to fruition.

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