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

Notification System: Code Generation Deliverable

This document provides a comprehensive, detailed, and production-ready code implementation for a core Notification System. This deliverable focuses on modularity, extensibility, and clarity, enabling seamless integration into existing applications and future enhancements.


1. Introduction to the Notification System Code

This output delivers the foundational code for a robust Notification System. It encapsulates core functionalities such as defining notification types, managing different delivery channels (Email, SMS, Web Push), handling user preferences, and utilizing an asynchronous processing mechanism (message queue) for efficient and scalable notification delivery. The code is designed to be clean, well-commented, and easily adaptable to various application environments.

2. System Architecture Overview

The proposed Notification System follows a modular, event-driven architecture to ensure scalability, reliability, and maintainability.

Key Components:

  1. Notification Service: The central orchestrator responsible for creating, validating, and dispatching notifications. It interacts with other components to determine delivery channels and content.
  2. Notification Data Model: Defines the structure and attributes of a notification (e.g., recipient, type, content, channels).
  3. Notification Channels: Abstract interfaces and concrete implementations for various delivery methods (e.g., EmailSender, SMSSender, WebPushSender).
  4. Notification Template Manager: Manages and renders notification content using templates, allowing for dynamic and personalized messages.
  5. User Preference Manager: Stores and retrieves user-specific notification preferences, ensuring users only receive desired communications.
  6. Notification Queue: An asynchronous message queue (e.g., Redis Queue, RabbitMQ) to decouple notification generation from actual sending, preventing application bottlenecks.
  7. Notification Worker: A background process that consumes messages from the queue and dispatches them through the appropriate channels.

High-Level Flow:

  1. An application event triggers the need for a notification.
  2. The application calls the NotificationService with notification details.
  3. The NotificationService validates the request, retrieves user preferences via UserPreferenceManager, and renders content using NotificationTemplateManager.
  4. The NotificationService then enqueues the structured notification message into the NotificationQueue.
  5. A NotificationWorker continuously monitors the NotificationQueue.
  6. Upon receiving a message, the NotificationWorker retrieves the notification details.
  7. The NotificationWorker dispatches the notification through the specified NotificationChannels.
text • 451 chars
### 3. Core Components & Code Implementation

This section provides the Python code for each core component, along with detailed explanations and comments.

**Dependencies:**
To run this code, you will need `pydantic` for robust data modeling.
Install with: `pip install pydantic`

---

#### 3.1. `notification_models.py` - Notification Data Models

Defines the structure of notifications and related data using Pydantic for validation and clarity.

Sandboxed live preview

As part of the "Notification System" workflow, this document outlines a comprehensive and detailed study plan for understanding, designing, and implementing a robust notification system. This plan is designed to equip you with the necessary knowledge and practical skills, covering architectural considerations, core components, and operational best practices.


Notification System: Detailed Study Plan

1. Introduction and Purpose

This study plan provides a structured approach to learning about Notification Systems, from foundational concepts to advanced architectural patterns and operational aspects. The goal is to enable participants to confidently design, build, and maintain a scalable, reliable, and user-centric notification platform.

2. Overall Learning Objective

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

  • Articulate the key components and architectural considerations for a modern notification system.
  • Design a scalable and fault-tolerant notification architecture using appropriate technologies and patterns.
  • Understand and implement various notification channels (email, SMS, push, in-app).
  • Manage user preferences, notification history, and message templating effectively.
  • Address critical aspects such as scalability, reliability, security, and monitoring in a notification system.

3. Weekly Schedule

This 4-week study plan is structured to build knowledge progressively, starting with fundamentals and moving towards advanced topics and practical application.

Week 1: Fundamentals & Core Concepts

  • Focus: Understanding what a notification system is, its purpose, common types, and initial architectural considerations.
  • Key Topics:

* Introduction to Notification Systems: Definition, importance, use cases.

* Types of Notifications: In-app, push (mobile/web), email, SMS, voice.

* Core Components Overview: Sender, receiver, message store, preferences, channels.

* Basic Architectural Patterns: Monolithic vs. Microservices approach for notifications.

* User Preference Management: Opt-in/out, channel preferences, frequency limits.

* Message Templating: Dynamic content generation, localization.

Week 2: Backend Services & Data Management

  • Focus: Deep dive into the server-side logic, data persistence, and asynchronous processing required for a robust notification system.
  • Key Topics:

* API Design for Notifications: RESTful APIs for sending, fetching history, managing preferences.

* Message Queuing Systems: Role of queues (e.g., Kafka, RabbitMQ, AWS SQS) for asynchronous processing, reliability, and decoupling.

* Data Persistence: Choosing databases for notification history, user preferences, templates (SQL vs. NoSQL considerations).

* Notification Service Logic: Routing, rate limiting, retry mechanisms, idempotency.

* Scheduling Mechanisms: For delayed or recurring notifications.

* Audit Trails and Logging: Tracking notification lifecycle.

Week 3: Channel Integrations & Real-time Aspects

  • Focus: Exploring the specifics of integrating with various notification channels and implementing real-time delivery.
  • Key Topics:

* Email Integration: SMTP, Email Service Providers (ESPs) like SendGrid, Mailgun, AWS SES. Best practices for deliverability.

* SMS Integration: SMS Gateways (e.g., Twilio, Nexmo), short codes vs. long codes, country-specific regulations.

* Push Notifications: Mobile (FCM for Android, APNS for iOS), Web Push APIs, third-party services (OneSignal).

* In-app Notifications: WebSockets, Server-Sent Events (SSE), long polling for real-time updates.

* Error Handling & Fallbacks: Strategies for dealing with failed deliveries across channels.

Week 4: Advanced Topics & Operations

  • Focus: Addressing critical operational aspects, advanced architectural patterns, and ensuring the system's reliability, scalability, and security.
  • Key Topics:

* Scalability & High Availability: Load balancing, horizontal scaling, fault tolerance, disaster recovery.

* Monitoring, Logging, & Alerting: Key metrics, dashboards, incident response for notification failures.

* Security Considerations: Data privacy (GDPR, CCPA), authentication/authorization, secure handling of sensitive user data.

* Advanced Patterns: Event-driven architecture, Pub/Sub models for notification events.

* A/B Testing & Analytics: Measuring notification effectiveness, user engagement.

* Cost Optimization: Managing third-party service costs, infrastructure efficiency.

4. Recommended Resources

Books & E-books:

  • "Designing Data-Intensive Applications" by Martin Kleppmann: Essential for understanding distributed systems, data storage, and reliability. (Chapters on messaging, replication, fault tolerance are highly relevant).
  • "System Design Interview – An insider's guide" by Alex Xu: Provides excellent frameworks for approaching system design problems, including notification systems.
  • Online Documentation: Official documentation for AWS SQS/SNS, Kafka, RabbitMQ, Firebase Cloud Messaging, Apple Push Notification Service, Twilio, SendGrid.

Online Courses & Tutorials:

  • "Grokking the System Design Interview" (Educative.io): Contains a dedicated section on designing a notification system.
  • Udemy/Coursera Courses on Microservices Architecture: Essential for understanding how notification services fit into larger ecosystems.
  • YouTube Channels: "ByteByteGo," "System Design Interview," "Hussein Nasser" for deep dives into specific technologies (queues, databases).

Articles & Blogs:

  • Medium/Dev.to: Search for "designing notification system," "scalable notifications," "microservices notifications."
  • Company Engineering Blogs: Uber, Netflix, LinkedIn, Facebook often publish articles on how they handle notifications at scale.

Example:* "Building a Scalable Notification System at Uber" (or similar posts from major tech companies).

  • Cloud Provider Blogs: AWS, Azure, GCP blogs often feature reference architectures for notification systems.

Tools & Platforms (for hands-on practice):

  • Messaging Queues: Kafka, RabbitMQ, AWS SQS/SNS, Google Cloud Pub/Sub.
  • Databases: PostgreSQL, MongoDB, Redis.
  • Email Service Providers: SendGrid, Mailgun, AWS SES.
  • SMS Gateways: Twilio, Nexmo.
  • Push Notification Services: Firebase Cloud Messaging (FCM), OneSignal.
  • Containerization: Docker, Kubernetes.
  • Cloud Platforms: AWS, Azure, GCP (for deploying and experimenting).

5. Milestones

  • End of Week 1:

* Milestone: Conceptual understanding of notification system components and user preference flows.

* Deliverable: High-level architectural diagram of a notification system, identifying key modules and their interactions.

  • End of Week 2:

* Milestone: Understanding of data flow, persistence, and asynchronous processing.

* Deliverable: Detailed component diagram focusing on the backend services (API, queue, database) and their responsibilities.

  • End of Week 3:

* Milestone: Knowledge of integrating various notification channels and real-time delivery mechanisms.

* Deliverable: A design document outlining channel integration strategies, including error handling and fallbacks for each.

  • End of Week 4:

* Milestone: Comprehensive understanding of a production-ready notification system, including advanced topics.

* Deliverable: A complete system design proposal for a scalable and reliable notification system, including monitoring, security, and scalability considerations. This should ideally include a simple Proof-of-Concept (PoC) demonstrating a basic notification flow (e.g., sending an email via an API endpoint).

6. Assessment Strategies

  • Weekly Quizzes/Self-Assessments: Short quizzes to test understanding of key concepts and terminology from the week's topics.
  • Design Exercises: Presenting a specific notification system requirement (e.g., "Design a system for sending order updates for an e-commerce platform") and asking participants to outline the architecture.
  • Peer Reviews: Reviewing and providing feedback on architectural diagrams and design documents created by peers.
  • Code Walkthroughs (Optional but Recommended): Analyzing open-source notification system components or example implementations to understand practical coding patterns.
  • Final Project/System Design Presentation: Presenting the comprehensive system design proposal and PoC, followed by a Q&A session to validate understanding and critical thinking. This presentation should cover:

* Problem statement and requirements.

* Proposed architecture and technology stack.

* Scalability, reliability, and security considerations.

* Monitoring and operational aspects.

* Trade-offs and future enhancements.


This detailed study plan provides a robust framework for mastering the intricacies of notification system design and implementation. Consistent engagement with the recommended resources and active participation in the assessment strategies will ensure a thorough understanding and practical readiness.

python

notification_channels.py

import abc

import smtplib

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

from typing import Dict, Any, Optional

from notification_models import Notification, NotificationChannel

--- Abstract Base Class for Notification Channels ---

class BaseNotificationChannel(abc.ABC):

"""

Abstract base class for all notification channels.

Defines the interface for sending notifications.

"""

@abc.abstractmethod

def send(self, notification: Notification, rendered_content: Dict[str, str]) -> bool:

"""

Sends a notification through this channel.

:param notification: The Notification object containing recipient details.

:param rendered_content: A dictionary containing rendered subject/body for the notification.

e.g., {'subject': '...', 'body_html': '...', 'body_plain': '...'}

or {'message': '...', 'title': '...'} for push.

:return: True if successful, False otherwise.

"""

pass

@property

@abc.abstractmethod

def channel_type(self) -> NotificationChannel:

"""

Returns the type of this notification channel.

"""

pass

--- Concrete Channel Implementations ---

class EmailSender(BaseNotificationChannel):

"""

Sends notifications via email.

In a real-world scenario, this would integrate with an email service provider

like SendGrid, Mailgun, AWS SES, or a local SMTP server.

"""

def __init__(self, smtp_server: str = "localhost", smtp_port: int = 1025,

smtp_username: Optional[str] = None, smtp_password: Optional[str] = None,

sender_email: str = "noreply@example.com"):

self.smtp_server = smtp_server

self.smtp_port = smtp_port

self.smtp_username = smtp_username

self.smtp_password = smtp_password

self.sender_email = sender_email

print(f"Initialized EmailSender for {sender_email} via {smtp_server}:{smtp_port}")

@property

def channel_type(self) -> NotificationChannel:

return NotificationChannel.EMAIL

def send(self, notification: Notification, rendered_content: Dict[str, str]) -> bool:

if not notification.recipient.email:

print(f"EmailSender: No email address for user {notification.recipient.user_id}. Skipping.")

return False

subject = rendered_content.get('subject', 'No Subject')

body_html = rendered_content.get('body_html')

body_plain = rendered_content.get('body_plain', body_html) # Fallback to HTML if plain not provided

msg = MIMEMultipart("alternative")

msg['From'] = self.sender_email

msg['To'] = notification.recipient.email

msg['Subject'] = subject

if body_plain:

msg.attach(MIMEText(body_plain, 'plain'))

if body_html:

msg.attach(MIMEText(body_html, 'html'))

try:

with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:

# server.set_debuglevel(1) # Uncomment for debugging SMTP

if self.smtp_username and self.smtp_password:

server.starttls() # Use TLS for secure connection

server.login(self.smtp_username, self.smtp_password)

server.send_message(msg)

print(f"EmailSender: Successfully sent email to {notification.recipient.email} (Type: {notification.type})")

return True

except Exception as e:

print(f"EmailSender: Failed to send email to {notification.recipient.email}. Error: {e}")

return False

class SMSSender(BaseNotificationChannel):

"""

Sends notifications via SMS.

In a real-world scenario, this would integrate with an SMS gateway

like Twilio, Nexmo (Vonage), or MessageBird.

"""

def __init__(self, api_key: str = "mock_sms_key", api_secret: str = "mock_sms_secret",

from_number: str = "+15017122661"):

self.api_key = api_key

self.api_secret = api_secret

self.from_number = from_number

print(f"Initialized SMSSender from {from_number}")

@property

def channel_type

gemini Output

This document outlines the comprehensive design and proposed implementation strategy for your new Notification System. This deliverable is the culmination of our "Notification System" workflow, moving from initial conceptualization to a detailed actionable plan.


Notification System: Comprehensive Deliverable

1. Executive Summary

We are pleased to present the detailed design and strategic roadmap for your dedicated Notification System. This system is engineered to provide a robust, scalable, and highly flexible communication platform, enabling your organization to deliver timely and relevant messages across multiple channels. By centralizing notification logic and delivery, this system will significantly enhance user engagement, streamline operational alerts, and improve overall communication efficiency.

This deliverable covers the system's core features, conceptual architecture, technical considerations, and a phased implementation roadmap, ensuring a clear path from design to deployment.

2. System Overview and Objectives

The Notification System is designed to act as a central hub for all outbound communications, decoupling message generation from message delivery. Its primary objectives are:

  • Reliable Delivery: Ensure messages reach their intended recipients consistently and without failure.
  • Multi-Channel Support: Facilitate communication through various preferred channels (e.g., email, SMS, push notifications, in-app messages).
  • Personalization & Relevance: Deliver highly targeted and personalized content based on user preferences and behavior.
  • Scalability: Handle high volumes of notifications with minimal latency, adapting to future growth.
  • Flexibility: Provide an easy-to-use interface and API for integrating with existing and future applications.
  • Actionable Insights: Offer tracking and analytics to monitor notification performance and user engagement.

3. Key Features and Capabilities

The proposed Notification System will include the following core features:

  • Multi-Channel Delivery:

* Email: Integration with professional email service providers (ESPs) for high deliverability.

* SMS: Reliable text message delivery via SMS gateways.

* Push Notifications: Support for mobile (iOS/Android) and web push notifications.

* In-App Notifications: Display messages directly within your applications.

* Webhooks: Enable real-time data push to external systems or custom integrations.

  • Dynamic Templating Engine:

* Centralized management of reusable notification templates.

* Support for dynamic content insertion (e.g., user names, order details) to ensure personalization.

* Consistent branding and messaging across all channels.

  • User Preference & Subscription Management:

* Allow users to manage their preferred communication channels and opt-in/opt-out of specific notification types.

* Robust mechanisms for handling unsubscribe requests and compliance (e.g., GDPR, CAN-SPAM).

  • Scheduling & Recurrence:

* Ability to schedule one-time, recurring, or delayed notifications.

* Support for time-zone aware delivery.

  • Prioritization & Throttling:

* Define priority levels for different notification types (e.g., critical alerts vs. promotional messages).

* Implement throttling mechanisms to prevent message overload and maintain compliance with provider limits.

  • Delivery Tracking & Analytics:

* Track the status of each notification (sent, delivered, opened, clicked, failed).

* Provide dashboards and reports on key metrics (e.g., delivery rates, open rates, click-through rates).

  • Auditing & Logging:

* Comprehensive logs for all notification events, crucial for debugging, compliance, and auditing.

  • API-Driven Integration:

* A well-documented RESTful API for seamless integration with your existing applications and services.

  • Error Handling & Retries:

* Automated retry mechanisms for transient delivery failures.

* Configurable fallback strategies for persistent issues.

4. Conceptual Architecture & Components

The Notification System will adopt a modular, microservices-oriented architecture to ensure scalability, resilience, and maintainability.

  • API Gateway:

* Serves as the single entry point for all external services to interact with the Notification System.

* Handles authentication, authorization, rate limiting, and request routing.

  • Notification Service Core:

* The central brain of the system, responsible for processing incoming notification requests.

* Manages business logic, template rendering, and message queueing.

* Interacts with the User Preference Database to determine delivery channels.

  • Message Queue (e.g., Apache Kafka, RabbitMQ, AWS SQS):

* Decouples the Notification Service Core from the actual delivery mechanisms.

* Buffers messages, handles bursts of traffic, and ensures reliable message processing even during high load.

  • Template Management Module:

* Stores and manages notification templates, supporting various formats (e.g., HTML for email, plain text for SMS).

* Provides an interface for creating, editing, and previewing templates.

  • Channel Adapters/Providers:

* Dedicated services or modules for integrating with specific third-party communication providers.

* Examples:

* Email Adapter: Integrates with SendGrid, Mailgun, AWS SES.

* SMS Adapter: Integrates with Twilio, Vonage.

* Push Notification Adapter: Integrates with Firebase Cloud Messaging (FCM), Apple Push Notification Service (APNS).

* In-App Adapter: Integrates with your application's UI components.

* Webhook Adapter: Manages and dispatches custom HTTP POST requests.

  • User Preference Database:

* Stores user contact information, preferred channels, and subscription status for various notification types.

* Ensures compliance with user opt-in/opt-out choices.

  • Delivery Tracking & Analytics Database:

* Stores logs of all notification attempts and their statuses.

* Feeds data into monitoring and reporting dashboards.

  • Logging & Monitoring System:

* Centralized logging for all system components (e.g., ELK Stack, Splunk, Datadog).

* Real-time monitoring and alerting for system health, performance, and delivery success rates.

5. Technical Considerations & Recommendations

To ensure the system meets its objectives, we recommend focusing on the following technical aspects:

  • Scalability:

* Cloud-Native Design: Leverage cloud services (AWS, Azure, GCP) for managed queues, databases, and compute.

* Stateless Services: Design services to be stateless for easy horizontal scaling.

* Auto-Scaling: Implement auto-scaling groups for compute resources based on load metrics.

  • Reliability & Resilience:

* Redundancy: Deploy components across multiple availability zones.

* Fault Tolerance: Implement circuit breakers and bulkheads to isolate failures.

* Idempotency: Design notification requests to be idempotent where possible to prevent duplicate processing on retries.

  • Security:

* API Security: OAuth2/JWT for API authentication and authorization.

* Data Encryption: Encrypt sensitive data both in transit (TLS/SSL) and at rest (database encryption).

* Access Control: Implement granular role-based access control (RBAC) for system management.

* Secrets Management: Use secure secrets management solutions (e.g., AWS Secrets Manager, HashiCorp Vault).

  • Observability:

* Distributed Tracing: Implement tracing (e.g., OpenTelemetry) to track requests across services.

* Metrics & Dashboards: Comprehensive metrics collection and visualization for real-time operational insights.

* Alerting: Proactive alerts for critical issues (e.g., delivery failures, high error rates, queue backlogs).

  • Technology Stack (Recommended Examples):

* Backend Language/Framework: Python (Django/Flask), Node.js (Express), Java (Spring Boot), or Go.

* Database: PostgreSQL (for relational data like templates, user preferences), MongoDB/DynamoDB (for high-volume logging/tracking).

* Message Queue: Apache Kafka (for high throughput, durable messaging), AWS SQS/Azure Service Bus (for managed queues).

* Cloud Platform: AWS, Azure, or Google Cloud Platform, depending on existing infrastructure and preferences.

6. Proposed Implementation Roadmap

We propose a phased approach to implementing the Notification System to ensure controlled development, early value delivery, and continuous feedback.

Phase 1: Discovery & Detailed Design (Weeks 1-4)

  • Objective: Define comprehensive requirements and finalize architectural blueprints.
  • Activities:

* In-depth requirements gathering and use case definition with stakeholders.

* Detailed API contract definition for internal and external integrations.

* Finalize technology stack and cloud service providers.

* Security and compliance review.

* Establish development and testing environments.

Phase 2: Core Service Development & Initial Channel Integration (Weeks 5-12)

  • Objective: Build the foundational notification platform and integrate primary communication channels.
  • Activities:

* Develop Notification Service Core and API Gateway.

* Implement Message Queue integration.

* Build basic Template Management Module.

* Integrate 1-2 primary channels (e.g., Email, In-App Messaging).

* Develop basic User Preference Management (opt-in/out).

* Initial unit and integration testing.

Phase 3: Advanced Features & Additional Channels (Weeks 13-20)

  • Objective: Expand system capabilities with advanced features and integrate remaining channels.
  • Activities:

* Implement personalization logic and dynamic content insertion.

* Develop scheduling, recurrence, prioritization, and throttling mechanisms.

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

* Develop comprehensive Delivery Tracking & Analytics module.

* Enhance error handling and retry mechanisms.

* Further integration and system testing.

Phase 4: Testing, Deployment & Optimization (Weeks 21-26)

  • Objective: Ensure system quality, performance, and successful production deployment.
  • Activities:

* Comprehensive testing: unit, integration, end-to-end, load, and security penetration testing.

* User Acceptance Testing (UAT) with key business users.

* Production environment setup and configuration.

* Deployment to production, cutover strategy.

* Establish continuous monitoring, alerting, and incident response procedures.

* Performance tuning and optimization.

Phase 5: Iteration & Continuous Improvement (Ongoing)

  • Objective: Gather feedback, implement enhancements, and ensure long-term system health.
  • Activities:

* Regular review of analytics and user feedback.

* Prioritize and implement new features and enhancements.

* Maintain and update system documentation.

* Ongoing security audits and patching.

7. Future Enhancements & Scalability Considerations

The proposed architecture is designed with future growth in mind. Potential future enhancements include:

  • AI-Powered Personalization: Leverage machine learning to optimize notification timing, content, and channel based on user behavior.
  • A/B Testing Framework: Integrate tools to A/B test notification content, subject lines, and calls-to-action to optimize engagement.
  • Localization & Internationalization: Support multiple languages, regional templates, and advanced time-zone management.
  • Rich Media Notifications: Enable embedding images, videos, and interactive elements within notifications.
  • Advanced Analytics & Reporting: Deeper insights into user journeys, conversion attribution, and notification ROI.
  • Self-Service Portal: A dedicated portal for business users to create, manage, and schedule notifications without developer intervention.

8. Documentation & Support

As part of this deliverable, comprehensive documentation will be provided:

  • API Documentation: Detailed Swagger/OpenAPI specifications for all API endpoints, including request/response examples and authentication methods.
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);}});}