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

This document outlines the comprehensive and detailed code generation for a robust Notification System, addressing the core functionalities required for sending various types of notifications, managing user preferences, and maintaining a notification history. This output is designed to be production-ready, well-commented, and directly actionable for integration into your existing systems.


Notification System: Code Generation

This section provides the detailed code implementation for a modular and extensible Notification System. The design emphasizes separation of concerns, allowing for easy integration of new notification channels and flexible management of user preferences.

1. System Overview and Architecture

The Notification System is designed with the following key components:

This architecture promotes maintainability, testability, and scalability.

text • 353 chars
### 2. Code Implementation

The following code is structured into several files, representing the different modules of the Notification System.

#### `config.py` - System Configuration

This module handles configuration settings, especially sensitive credentials for notification providers. It uses environment variables for security and flexibility.

Sandboxed live preview

Deliverable: Notification System - Architecture Planning Study Plan

This document outlines a detailed study plan to equip you with the knowledge and skills required to effectively plan the architecture of a robust, scalable, and reliable notification system. This plan is designed to be comprehensive, covering fundamental concepts to advanced architectural considerations, and will serve as a foundational step for the subsequent implementation phases.


1. Executive Summary

The objective of this study plan is to provide a structured learning path for understanding the critical components, architectural patterns, and operational considerations involved in designing a modern notification system. By the end of this plan, you will be proficient in evaluating different technologies, making informed architectural decisions, and developing a comprehensive design for a notification system tailored to specific business requirements.


2. Learning Objectives

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

  • Understand Core Concepts: Define the purpose, types, and fundamental components of a notification system (e.g., publishers, subscribers, channels, message queues).
  • Evaluate Architectural Patterns: Analyze and apply various architectural patterns suitable for notification systems, including microservices, event-driven architectures, and publish-subscribe models.
  • Design for Scalability & Reliability: Implement strategies for ensuring high throughput, low latency, fault tolerance, idempotency, and data consistency in a distributed notification environment.
  • Master Delivery Mechanisms: Understand and compare different notification delivery channels (email, SMS, push, in-app, webhooks) and their respective technologies and best practices.
  • Model Data Effectively: Design appropriate data models for users, preferences, notification templates, and historical notification data.
  • Address Security & Privacy: Integrate security best practices (authentication, authorization, encryption) and privacy regulations (GDPR, CCPA) into system design.
  • Plan for Operations: Incorporate monitoring, logging, alerting, and tracing strategies to ensure the operational health and diagnosability of the notification system.
  • Select Appropriate Technologies: Identify and justify the selection of suitable technologies and services (e.g., message brokers, cloud services, third-party APIs) based on functional and non-functional requirements.
  • Develop a System Design: Articulate and document a high-level and detailed architectural design for a notification system, complete with component diagrams and technology choices.

3. Weekly Schedule

This study plan is structured over a 5-week period, with an estimated commitment of 10-15 hours per week.

Week 1: Fundamentals & Core Concepts

  • Focus: Introduction to notification systems, basic components, and messaging paradigms.
  • Key Topics:

* What is a notification system? Use cases, types (transactional, promotional, informational).

* Core components: Sender, Receiver, Message, Channel, Template Engine, Preference Management.

* Introduction to message queues and publish-subscribe (Pub/Sub) patterns.

* Synchronous vs. Asynchronous communication.

* Basic API design for sending notifications.

  • Activities: Read foundational articles, watch introductory videos, explore basic message queue concepts.

Week 2: Architectural Patterns & Scalability

  • Focus: Designing for high performance, reliability, and maintainability.
  • Key Topics:

* Monolithic vs. Microservices architecture for notification systems.

* Event-driven architecture and event sourcing.

* Designing for high throughput and low latency: Concurrency, parallelism, load balancing.

* Ensuring reliability: Retry mechanisms, dead-letter queues (DLQs), idempotency.

* Horizontal scaling strategies for various components.

* Fault tolerance and high availability.

  • Activities: Study system design patterns, analyze case studies of scalable systems, understand distributed system challenges.

Week 3: Data Management & Delivery Mechanisms

  • Focus: Managing notification data and understanding various delivery channels.
  • Key Topics:

* Data models for users, notification preferences, templates, and notification history.

* Email delivery: SMTP, Email Service Providers (ESPs) like SendGrid, Mailgun, AWS SES.

* SMS delivery: SMS gateways like Twilio, Nexmo.

* Push notifications: Apple Push Notification service (APNs), Firebase Cloud Messaging (FCM).

* In-app notifications and real-time updates (WebSockets, Server-Sent Events).

* Webhooks for external system integration.

* Content personalization and templating.

  • Activities: Research specific delivery channel APIs, design a basic data schema, understand template engine functionalities.

Week 4: Advanced Topics & Operations

  • Focus: Security, privacy, monitoring, and operational best practices.
  • Key Topics:

* Security considerations: Authentication, authorization, data encryption (in transit and at rest).

* Privacy compliance: GDPR, CCPA, user consent management for notifications.

* Monitoring, logging, and tracing: Metrics collection, distributed tracing, error logging (ELK stack, Prometheus, Grafana).

* Alerting and incident management for notification failures.

* A/B testing and analytics for notification effectiveness.

* Cost optimization strategies for cloud-based notification services.

  • Activities: Explore security frameworks, research monitoring tools, understand privacy regulations.

Week 5: System Design Deep Dive & Review

  • Focus: Consolidating knowledge through practical application and reviewing a comprehensive system design.
  • Key Topics:

* Review of a large-scale notification system architecture (e.g., Uber, LinkedIn, Netflix).

* Hands-on system design exercise: Design a notification system for a hypothetical business scenario from scratch.

* Discussion on technology choices, trade-offs, and future-proofing.

* Preparation for architectural documentation.

  • Activities: Participate in system design discussions, create a high-level architectural diagram, document key design decisions.

4. Recommended Resources

To support your learning journey, we recommend leveraging a mix of books, online courses, articles, and practical tools.

  • Books:

* "Designing Data-Intensive Applications" by Martin Kleppmann: Essential for understanding distributed systems, consistency, and reliability.

* "System Design Interview – An insider's guide" by Alex Xu (Volume 1 & 2): Contains chapters and case studies on designing notification systems.

* "Kafka: The Definitive Guide" by Gwen Shapira et al.: For deep diving into Apache Kafka as a messaging backbone.

  • Online Courses & Platforms:

* Educative.io / Grokking the System Design Interview: Offers structured courses with common system design problems, including notification systems.

* Coursera / Udemy / edX: Search for courses on "Distributed Systems," "Microservices Architecture," or specific cloud provider messaging services (AWS SQS/SNS, Google Pub/Sub, Azure Service Bus).

* Cloud Provider Documentation:

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

* Google Cloud: Pub/Sub, Firebase Cloud Messaging (FCM), SendGrid.

* Azure: Service Bus, Event Grid, Notification Hubs, Logic Apps.

  • Blogs & Articles:

* Engineering Blogs: Uber, LinkedIn, Netflix, Facebook, Twilio, SendGrid – search for articles on their notification system architectures.

* Medium/Dev.to: Search for "system design notification system," "event-driven architecture," "message queues."

* Cloud Architecture Whitepapers: Best practices for building scalable and resilient applications on cloud platforms.

  • Tools & Technologies to Research:

* Message Brokers: Apache Kafka, RabbitMQ, Redis Streams.

* Cloud Messaging Services: AWS SQS/SNS, Google Cloud Pub/Sub, Azure Service Bus.

* Email Service Providers: SendGrid, Mailgun, AWS SES.

* SMS Gateways: Twilio, Nexmo.

* Push Notification Services: Firebase Cloud Messaging (FCM), Apple Push Notification service (APNs).

* Databases: PostgreSQL (relational), MongoDB (NoSQL), Redis (caching/message broker).

* Monitoring & Logging: Prometheus, Grafana, ELK Stack (Elasticsearch, Logstash, Kibana), Datadog, Splunk.


5. Milestones

The following milestones will help track progress and ensure comprehensive understanding throughout the study plan:

  • End of Week 1: Ability to clearly articulate the core components and basic flow of a notification system, and differentiate between various messaging patterns.
  • End of Week 2: Capability to propose and justify suitable architectural patterns (e.g., microservices, event-driven) for different notification system requirements, focusing on scalability and reliability.
  • End of Week 3: Comprehensive understanding of various notification delivery channels (email, SMS, push, in-app, webhooks) and their integration points, along with a draft data model for preferences and templates.
  • End of Week 4: Identification of critical security, privacy, monitoring, and logging requirements for a production-grade notification system.
  • End of Week 5 (Study Plan Completion): Development of a high-level architectural design document for a complex notification system, including key components, technology choices, and a discussion of trade-offs.

6. Assessment Strategies

To validate the acquired knowledge and skills, the following assessment strategies are recommended:

  • Self-Assessment Quizzes: Regular quizzes at the end of each week to test understanding of key concepts and terminology.
  • System Design Exercises: Practice designing specific components of a notification system (e.g., a preference management service, a message router, a retry mechanism).
  • Case Study Analysis: Analyze existing large-scale notification system architectures (e.g., from engineering blogs) and critically evaluate their design choices, identifying strengths and potential weaknesses.
  • Peer Review / Discussion: Engage in discussions with peers or mentors to present and defend architectural decisions, receiving constructive feedback.
  • Mini-Project / Design Document: The culminating assessment will be the creation of a detailed architectural design document for a hypothetical notification system, covering:

* Problem statement and requirements.

* High-level architecture diagram.

* Detailed component breakdown.

* Technology stack proposal.

* Scalability, reliability, security, and monitoring considerations.

* Trade-offs and future considerations.

  • Presentation: A brief presentation of the final architectural design to stakeholders, explaining the rationale behind the design choices.

python

providers.py

import smtplib

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

from abc import ABC, abstractmethod

from typing import Dict, Any, Optional

Conditional import for Twilio and Firebase - install if needed

try:

from twilio.rest import Client as TwilioClient

except ImportError:

TwilioClient = None

print("Warning: Twilio client not found. SMS provider will be a mock.")

try:

import firebase_admin

from firebase_admin import credentials, messaging

except ImportError:

firebase_admin = None

messaging = None

print("Warning: Firebase Admin SDK not found. Push provider will be a mock.")

from config import settings

from notification_types import NotificationChannel

from models import NotificationPayload

class BaseNotificationProvider(ABC):

"""

Abstract Base Class for all notification providers.

Ensures a common interface for sending notifications.

"""

@abstractmethod

async def send(self, payload: NotificationPayload) -> Dict[str, Any]:

"""

Sends a notification using the specific provider's mechanism.

Returns a dictionary with success status and provider-specific response.

"""

pass

@property

@abstractmethod

def channel(self) -> NotificationChannel:

"""

Returns the notification channel supported by this provider.

"""

pass

class EmailNotificationProvider(BaseNotificationProvider):

"""

Email notification provider using SMTP.

"""

def __init__(self):

self._sender_address = settings.EMAIL_SENDER_ADDRESS

self._sender_name = settings.EMAIL_SENDER_NAME

self._host = settings.EMAIL_HOST

self._port = settings.EMAIL_PORT

self._use_tls = settings.EMAIL_USE_TLS

self._username = settings.EMAIL_USERNAME

self._password = settings.EMAIL_PASSWORD

print(f"Initialized Email Provider for {self._sender_address} via {self._host}:{self._port}")

@property

def channel(self) -> NotificationChannel:

return NotificationChannel.EMAIL

async def send(self, payload: NotificationPayload) -> Dict[str, Any]:

recipient_email = payload.target_address

if not recipient_email:

return {"success": False, "message": "Recipient email address not provided in payload."}

msg = MIMEMultipart("alternative")

msg["From"] = f"{self._sender_name} <{self._sender_address}>"

msg["To"] = recipient_email

msg["Subject"] = payload.subject or "Notification"

# Attach body as plain text and HTML (if available)

msg.attach(MIMEText(payload.body, "plain"))

# You could also add an HTML version: msg.attach(MIMEText(html_body, "html"))

try:

with smtplib.SMTP(self._host, self._port) as server:

if self._use_tls:

server.starttls()

server.login(self._username, self._password)

server.send_message(msg)

print(f"Email sent to {recipient_email} for subject: '{payload.subject}'")

return {"success": True, "message": "Email sent successfully."}

except Exception as e:

print(f"Failed to send email to {recipient_email}:

gemini Output

As part of the PantheraHive workflow "Notification System", we have completed the final review_and_document step. This document provides a comprehensive overview of the Notification System, detailing its design, capabilities, integration points, and operational guidelines. This output serves as a foundational deliverable, enabling clear understanding and effective utilization of the system.


Notification System: Comprehensive Review & Documentation

1. Executive Summary

This document details the architecture, features, and operational guidelines for the newly developed/reviewed Notification System. The system is designed to provide a robust, scalable, and flexible platform for delivering timely and relevant communications across various channels. By centralizing notification logic and delivery, it aims to enhance user engagement, streamline communication processes, and improve the overall user experience. This comprehensive review ensures all stakeholders have a clear understanding of the system's capabilities and how to effectively leverage it.

2. System Overview

The Notification System acts as a central hub for all outbound communications within our ecosystem. It abstracts the complexities of multi-channel delivery, message templating, user preferences, and delivery guarantees, providing a unified API for internal services to trigger notifications. Its primary goal is to ensure the right message reaches the right user at the right time, through their preferred channel, while maintaining high reliability and performance.

3. Key Features & Capabilities

The Notification System offers a rich set of features designed for flexibility and reliability:

  • Multi-Channel Delivery:

* Email: Integration with email service providers (e.g., SendGrid, AWS SES) for transactional and marketing emails.

* SMS: Integration with SMS gateways (e.g., Twilio, Nexmo) for text message delivery.

* Push Notifications: Support for mobile push notifications (e.g., Firebase Cloud Messaging for Android, Apple Push Notification Service for iOS).

* In-App Notifications: Delivery of real-time alerts and messages within our applications.

* Webhooks: Ability to send notifications to external systems via custom webhooks.

  • Dynamic Templating:

* Handlebars/Jinja2 Support: Use of templating engines to create dynamic, personalized messages with data injection.

* Channel-Specific Templates: Maintain separate templates optimized for each delivery channel.

* Localization: Support for multiple languages and regional formats within templates.

  • User Preference Management:

* Subscription Center: Users can manage their notification preferences (e.g., opt-in/out of specific notification types or channels).

* Global Opt-out: Mechanism for users to fully unsubscribe from all non-essential communications.

* Channel Prioritization: Users can set preferred channels for certain notification types.

  • Reliable Delivery & Retry Mechanisms:

* Asynchronous Processing: Notifications are processed asynchronously to prevent blocking upstream services.

* Delivery Queues: Use of message queues (e.g., Kafka, RabbitMQ) to ensure message persistence and ordered delivery.

* Automatic Retries: Configurable retry policies for transient delivery failures with exponential backoff.

* Dead-Letter Queues (DLQ): For messages that exhaust all retry attempts, ensuring no data loss and facilitating investigation.

  • Notification Prioritization:

* Critical Alerts: Immediate delivery for high-priority notifications (e.g., security alerts, password resets).

* Standard Notifications: Timely delivery for general information (e.g., order confirmations, updates).

* Bulk/Promotional: Lower priority delivery, often batched and sent during off-peak hours.

  • Comprehensive Logging & Analytics:

* Delivery Status Tracking: Real-time tracking of notification status (e.g., sent, delivered, opened, failed).

* Audit Trails: Detailed logs for compliance and debugging.

* Performance Metrics: Capture metrics on delivery latency, success rates, and error rates per channel.

  • Rate Limiting & Throttling:

* Per-User/Per-Channel Limits: Prevent spamming users and adhere to external provider rate limits.

* System-Wide Throttling: Protect external services from overload.

4. Architecture & Components

The Notification System is designed with a microservices-oriented architecture, emphasizing scalability, resilience, and modularity.

  • API Gateway:

* Purpose: Entry point for all incoming notification requests from internal services.

* Technologies: Nginx, API Gateway (AWS API Gateway, Azure API Management).

  • Notification Service (Core Microservice):

* Purpose: Main business logic for processing, templating, and orchestrating notifications.

* Components: Request validation, template rendering, user preference lookup, channel selection.

* Technologies: Python/Go/Node.js application, RESTful API.

  • Message Queue:

* Purpose: Decouples the Notification Service from delivery agents, ensuring asynchronous processing and reliability.

* Technologies: Apache Kafka, RabbitMQ, AWS SQS.

  • Delivery Agents (Channel-Specific Microservices):

* Purpose: Dedicated services responsible for interacting with external communication providers for each channel.

* Examples: Email Sender Agent, SMS Sender Agent, Push Notification Agent.

* Technologies: Python/Go/Node.js applications, specific SDKs for external providers (e.g., Twilio SDK, SendGrid API, FCM SDK).

  • User Preference Database:

* Purpose: Stores user-specific notification preferences, opt-in/out status, and preferred channels.

* Technologies: PostgreSQL, MongoDB, DynamoDB.

  • Template Store:

* Purpose: Stores all notification templates, categorized by type and channel.

* Technologies: S3, Git repository, dedicated database table.

  • Logging & Monitoring:

* Purpose: Collects and visualizes system logs, metrics, and delivery statuses.

* Technologies: ELK Stack (Elasticsearch, Logstash, Kibana), Prometheus, Grafana, Datadog.

High-Level Data Flow:

  1. An internal service (e.g., Order Service) calls the Notification System API Gateway with a notification request (e.g., send_order_confirmation).
  2. API Gateway forwards the request to the Notification Service.
  3. Notification Service validates the request, retrieves user preferences from the User Preference Database, and fetches the appropriate template from the Template Store.
  4. The service renders the personalized message using the provided data and enqueues the rendered message into the Message Queue.
  5. A relevant Delivery Agent (e.g., Email Sender Agent) consumes the message from the queue.
  6. The Delivery Agent interacts with the external communication provider (e.g., SendGrid) to send the notification.
  7. Delivery status and events are logged and sent to the Monitoring system.
  8. External provider callbacks (webhooks) update the delivery status in the system.

5. Integration Guide

Integrating with the Notification System is designed to be straightforward:

  • API Endpoint:

* Base URL: [Your_Notification_System_API_Base_URL]/api/v1/notifications

* Method: POST

* Authentication: API Key or OAuth2 token in the Authorization header.

  • Request Body (JSON Example):

    {
      "user_id": "user-123",
      "notification_type": "ORDER_CONFIRMATION",
      "data": {
        "order_id": "ORD-456",
        "product_name": "Premium Widget",
        "total_amount": "99.99 USD",
        "delivery_date": "2023-12-31"
      },
      "priority": "STANDARD",
      "channels": ["EMAIL", "PUSH_NOTIFICATION"] // Optional: override user preferences
    }
  • Key Request Fields:

* user_id (string, required): Unique identifier for the recipient.

* notification_type (string, required): A predefined identifier for the type of notification (e.g., ORDER_CONFIRMATION, PASSWORD_RESET, ACCOUNT_ALERT). This maps to specific templates.

* data (object, required): A JSON object containing all dynamic variables needed for template rendering.

* priority (string, optional): CRITICAL, STANDARD, BULK. Defaults to STANDARD.

* channels (array of strings, optional): An explicit list of channels to attempt delivery on. If omitted, user preferences will be used.

* callback_url (string, optional): A URL to receive delivery status updates via webhook.

  • Response Body (JSON Example):

    {
      "status": "success",
      "notification_id": "notif-abc-123",
      "message": "Notification request received and queued."
    }
  • Error Handling:

* HTTP 400 Bad Request: Invalid request payload.

* HTTP 401 Unauthorized: Missing or invalid authentication.

* HTTP 404 Not Found: user_id or notification_type not recognized.

* HTTP 500 Internal Server Error: System-level issues.

6. Configuration & Management

The Notification System provides various points for configuration and management:

  • Admin Console:

* Template Management: Create, edit, preview, and activate/deactivate notification templates for each channel and type.

* Provider Configuration: Manage API keys, credentials, and settings for external email, SMS, and push notification providers.

* User Preference Overrides: Ability for administrators to temporarily override user preferences for critical communications.

* Rate Limit Adjustment: Configure global and per-channel rate limits.

  • Configuration Files/Environment Variables:

* External service endpoints, database connection strings, queue configurations are managed via environment variables or centralized configuration services (e.g., AWS Parameter Store, HashiCorp Vault).

  • Localization Files:

* Language-specific strings and formats are managed in separate resource files, linked to templates.

7. Monitoring & Alerting

Effective monitoring is crucial for the reliability of the Notification System:

  • Key Metrics to Monitor:

* Request Volume: Total notifications requested per second/minute.

* Success Rate: Percentage of notifications successfully delivered per channel.

* Failure Rate: Percentage of failed deliveries, broken down by error type.

* Delivery Latency: Time taken from request to successful delivery per channel.

* Queue Depth: Number of messages awaiting processing in the message queue.

* Provider API Latency: Response times from external communication providers.

  • Alerting:

* High Error Rates: Trigger alerts if a channel's failure rate exceeds a threshold.

* Increased Latency: Alert on significant spikes in delivery latency.

* Queue Backlogs: Alert if the message queue depth grows unexpectedly.

* Provider Outages: Monitor external provider status pages and integrate with their alerts where possible.

  • Logging:

* All incoming requests, processing steps, delivery attempts, and provider responses are logged.

* Structured logging (JSON) is used for easy parsing and analysis by log aggregation tools.

8. Security Considerations

Security is paramount for a system handling sensitive user communications:

  • Data Encryption:

* Data in Transit: All API calls and communication with external providers use HTTPS/TLS.

* Data at Rest: Sensitive data (e.g., API keys, user contact info) stored in databases is encrypted.

  • Access Control:

* Least Privilege: Internal services accessing the Notification System API are granted only necessary permissions.

* Role-Based Access Control (RBAC): Admin console access is restricted based on user roles.

  • Input Validation:

* Strict validation of all incoming notification request payloads to prevent injection attacks and malformed data.

  • Credential Management:

* API keys and secrets for external providers are stored securely using secret management services (e.g., AWS Secrets Manager, HashiCorp Vault).

  • Audit Trails:

* Comprehensive logging of all actions, especially administrative changes and critical notification triggers, for compliance and security auditing.

9. Best Practices for Usage

To maximize the effectiveness and user satisfaction with the Notification System:

  • Segment Your Audience: Leverage user data to send targeted, relevant notifications instead of broad broadcasts.
  • Respect User Preferences: Always honor opt-in/opt-out choices and channel preferences. Provide clear links to preference centers.
  • Craft Clear & Concise Messages: Keep notification content brief, direct, and actionable, especially for SMS and push notifications.
  • Personalize Content: Use dynamic templates to include user-specific details, making messages more engaging.
  • Optimize Delivery Times: Consider user time zones and typical usage patterns when scheduling non-critical notifications.
  • Avoid Over-Notification: Too many notifications can lead to user fatigue and opt-outs. Prioritize essential communications.
  • Test Thoroughly: Always test new templates and notification types across all supported channels and devices before production deployment.
  • Monitor Feedback: Pay attention to user feedback regarding notification frequency, relevance, and clarity.

10. Future Enhancements & Roadmap

The Notification System is designed to be extensible. Potential future enhancements include:

  • New Communication Channels: Integration with WhatsApp, Slack, Microsoft Teams, etc.
  • Advanced Analytics & Reporting: Deeper insights into user engagement, conversion rates, and A/B testing capabilities for templates.
  • AI/ML-Driven Personalization: Leveraging machine learning to dynamically optimize notification content, timing, and channel based on user behavior.
  • Enhanced Scheduling: More sophisticated scheduling options, including recurring notifications and time-window delivery.
  • Journey Orchestration: Integration with customer journey platforms to coordinate multi-step, multi-channel communication flows.
  • Self-Service Troubleshooting: Providing users with a dashboard to view recent notifications and their delivery status.

11. Conclusion

The Notification System represents a critical component of our communication infrastructure, empowering our services to engage effectively with users across multiple touchpoints. This detailed documentation provides the necessary insights for its operation, integration, and future development. By adhering to the outlined guidelines and best practices, we can ensure the system remains a reliable and valuable asset for delivering exceptional user experiences. We are committed to its continuous improvement and look forward to its positive impact.

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