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

Deliverable: Notification System - Code Generation (Step 2 of 3)

This document provides a comprehensive, detailed, and production-ready code implementation for the core components of your Notification System. This deliverable is designed to be immediately actionable, offering a robust foundation built with modern, scalable technologies.


1. System Overview

The Notification System is designed to provide a flexible and extensible platform for sending various types of notifications (e.g., Email, SMS, In-App messages) to users. It decouples the notification sending logic from the application's core business logic, allowing for easy management, preference customization, and future expansion of notification channels.

Key Features Implemented:

2. Technology Stack Choices

To ensure a modern, efficient, and scalable solution, the following technologies have been chosen for this implementation:

* Why: FastAPI is a high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. It offers automatic interactive API documentation (Swagger UI/ReDoc), data validation, serialization, and excellent performance, making it ideal for microservices and APIs.

* Why: SQLAlchemy is a powerful and flexible Object Relational Mapper (ORM) that provides a full suite of well-known persistence patterns for Python. While SQLite is used for simplicity in this example, the SQLAlchemy setup is easily adaptable to production-grade databases like PostgreSQL or MySQL by changing the connection string and installing the respective database driver.

* Why: Pydantic is a data validation and settings management library using Python type hints. It's built into FastAPI, ensuring robust request/response data validation and clear error messages.

* Why: Standard practice for listing project dependencies, ensuring reproducibility across environments.

* Why: Securely manages configuration settings (e.g., API keys, database URLs) outside of the codebase.

3. Project Structure

The project is organized into logical directories and files to enhance readability, maintainability, and scalability.

text • 1,023 chars
notification_system/
├── .env                  # Environment variables (e.g., API keys, DB URL)
├── main.py               # FastAPI application entry point, API routes
├── config.py             # Configuration loading
├── database.py           # SQLAlchemy setup and session management
├── models.py             # SQLAlchemy ORM models (database schema)
├── schemas.py            # Pydantic models for API request/response validation
├── crud.py               # Database Create, Read, Update, Delete (CRUD) operations
├── services/
│   └── notification_service.py # Core notification orchestration logic
├── channels/
│   ├── __init__.py       # Initializes the channels package
│   ├── base_channel.py   # Abstract base class for all notification channels
│   ├── email_channel.py  # Implementation for Email notifications
│   ├── sms_channel.py    # Implementation for SMS notifications (Twilio example)
│   └── inapp_channel.py  # Implementation for In-App notifications
└── requirements.txt      # Project dependencies
Sandboxed live preview

This document outlines a comprehensive study plan for understanding and designing a robust Notification System architecture. This plan is specifically tailored to equip you with the knowledge and skills necessary to effectively complete the plan_architecture step of your workflow, ensuring a solid foundation for subsequent development phases.


Detailed Study Plan: Notification System Architecture

1. Introduction and Purpose

The goal of this study plan is to provide a structured learning path to master the architectural concepts, design patterns, and technical considerations for building a scalable, reliable, and efficient Notification System. By following this plan, you will gain the expertise to make informed decisions regarding technology choices, system components, and integration strategies, directly enabling the creation of a detailed architectural blueprint.

2. Learning Objectives

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

  • Understand Core Messaging Paradigms: Differentiate between various messaging patterns (e.g., Publish/Subscribe, Queueing) and their applications in a notification context.
  • Identify Key Architectural Components: Recognize and define the essential building blocks of a modern notification system, including ingestion APIs, message brokers, notification orchestrators, and channel-specific providers.
  • Evaluate Communication Channels: Analyze the technical requirements, benefits, and limitations of different notification channels (Email, SMS, Push Notifications, In-App, Webhooks).
  • Design for Scalability and Reliability: Propose architectural solutions to ensure high availability, fault tolerance, message durability, and horizontal scalability for high-volume notification traffic.
  • Implement Observability and Security Best Practices: Integrate logging, monitoring, alerting, and security measures (e.g., encryption, access control) into the notification system design.
  • Develop a Comprehensive Architectural Blueprint: Synthesize learned concepts to design a multi-channel notification system architecture, complete with component diagrams, data flows, and technology recommendations.

3. Weekly Schedule

This 6-week schedule provides a structured approach to cover the breadth and depth required for architectural planning. Each week includes core topics and suggested activities.

Week 1: Fundamentals of Messaging & Distributed Systems

  • Topics:

* Introduction to Distributed Systems concepts (consistency, availability, partition tolerance).

* Messaging patterns: Publish/Subscribe vs. Point-to-Point queues.

* Message brokers: Concepts, benefits, and comparison (e.g., Kafka, RabbitMQ, AWS SQS/SNS, GCP Pub/Sub, Azure Service Bus).

* Message delivery guarantees: At-least-once, At-most-once, Exactly-once (semantics and challenges).

* Idempotency and message deduplication strategies.

  • Activities:

* Read foundational articles on message queues and pub/sub.

* Explore documentation for at least two different message broker technologies.

* Draw basic data flow diagrams for a simple message producer-consumer system.

Week 2: Core Notification System Components

  • Topics:

* High-level architecture overview: Ingestion layer (API), Notification Service/Orchestrator, User Preference Management, Template Engine.

* Data models for notifications: payload structure, metadata, recipient information.

* User preference management: Storing and retrieving user notification settings (channels, frequency, topics).

* Notification templating: Dynamic content generation, localization, A/B testing considerations.

* Service-Oriented Architecture (SOA) / Microservices patterns for notification systems.

  • Activities:

* Outline the logical components of a notification system.

* Design a basic data schema for user preferences and notification templates.

* Consider different approaches for managing notification templates (e.g., database, file system, external service).

Week 3: Channel-Specific Integrations & Providers

  • Topics:

* Email Notifications: SMTP, transactional email services (SendGrid, Mailgun, AWS SES), email deliverability, bounce handling.

* SMS Notifications: SMS gateways (Twilio, Vonage), short codes vs. long codes, delivery reports, compliance (e.g., TCPA).

* Push Notifications (Mobile): FCM (Firebase Cloud Messaging) for Android, APNs (Apple Push Notification service) for iOS, token management, topic-based vs. device-specific pushes.

* Push Notifications (Web): Web Push API, Service Workers.

* In-App Notifications: Real-time updates, feed-based notifications.

* Webhooks: Outbound notifications to external systems.

* Provider abstraction layer design.

  • Activities:

* Research API documentation for at least one provider for Email, SMS, and Mobile Push.

* Map out the integration points and data flows for each channel.

* Identify common challenges for each channel (e.g., rate limits, delivery failures).

Week 4: Scalability, Reliability & High Availability

  • Topics:

* Horizontal scaling strategies for notification services and message brokers.

* Retry mechanisms: Exponential backoff, dead-letter queues (DLQ), circuit breakers.

* Fault tolerance and redundancy: Active-passive vs. Active-active setups.

* Load balancing and traffic management.

* Handling peak loads and traffic spikes.

* Data consistency and eventual consistency in distributed notification systems.

* Disaster recovery planning.

  • Activities:

* Propose scaling strategies for a notification system processing millions of messages daily.

* Design a retry and DLQ mechanism for a critical notification flow.

* Consider how to handle database failures for user preferences.

Week 5: Observability, Security & Advanced Features

  • Topics:

* Observability: Logging (structured logs, log aggregation), Monitoring (metrics, dashboards, Prometheus/Grafana), Alerting, Distributed Tracing (OpenTelemetry, Jaeger).

* Security: Data encryption (at rest and in transit), access control (authentication, authorization), API security (API keys, OAuth), compliance (GDPR, CCPA).

* Advanced Features:

* Batching and throttling notifications.

* Notification prioritization.

* A/B testing for notification content/delivery.

* Analytics and reporting for notification effectiveness.

* User segmentation for targeted notifications.

  • Activities:

* Define key metrics for monitoring a notification system's health and performance.

* Outline security considerations for handling sensitive user data within notifications.

* Sketch out an architecture for implementing notification prioritization.

Week 6: Architectural Design & Case Studies

  • Topics:

* Synthesizing all learned concepts into a cohesive architectural design.

* Technology selection criteria: open-source vs. managed services, cost, operational overhead, expertise.

* Reviewing existing notification system architectures (e.g., Netflix, Uber, LinkedIn, Stripe).

* Documenting architectural decisions (ADRs - Architectural Decision Records).

* Capacity planning and cost estimation.

  • Activities:

* Major Deliverable: Draft a high-level architectural diagram for a multi-channel notification system, including key components, data flows, and technology choices.

* Prepare a short presentation summarizing your proposed architecture and design rationale.

* Analyze a case study of a real-world notification system and identify its strengths and weaknesses.

4. Recommended Resources

  • Books:

* "Designing Data-Intensive Applications" by Martin Kleppmann (essential for distributed systems foundations).

* "Building Microservices" by Sam Newman.

* Specific books on Kafka, RabbitMQ, or cloud messaging services if deep dives are needed.

  • Online Courses:

* Coursera, Udemy, Pluralsight courses on distributed systems, microservices architecture, cloud computing (AWS, Azure, GCP messaging services).

* System Design Interview courses often cover notification system design.

  • Documentation:

* Official documentation for AWS SQS/SNS, GCP Pub/Sub, Azure Service Bus.

* Apache Kafka, RabbitMQ official documentation.

* API documentation for Twilio, SendGrid, Mailgun, Firebase Cloud Messaging (FCM), Apple Push Notification service (APNs).

  • Articles & Blogs:

* Engineering blogs of companies like Netflix, Uber, LinkedIn, Stripe, Meta, etc. (search for "notification system architecture").

* Medium articles and industry whitepapers on system design.

  • Open Source Projects:

* Explore notification libraries or microservice examples on GitHub to understand practical implementations.

5. Milestones

  • Milestone 1 (End of Week 1): Solid understanding of core messaging patterns and the role of message brokers. Ability to describe basic message delivery guarantees.
  • Milestone 2 (End of Week 2): Clear conceptual model of a notification system's logical components and data flows. Initial design for user preferences and template management.
  • Milestone 3 (End of Week 3): Familiarity with the integration complexities and specific considerations for at least three different notification channels.
  • Milestone 4 (End of Week 4): Ability to articulate strategies for ensuring scalability, reliability, and high availability in a high-throughput notification environment.
  • Milestone 5 (End of Week 5): Competence in incorporating observability tools and security measures into the system design, along with understanding advanced notification features.
  • Milestone 6 (End of Week 6): Completion of a high-level architectural design for a multi-channel notification system, ready for detailed review and discussion.

6. Assessment Strategies

  • Self-Assessment Quizzes/Exercises: Regular checks against learning objectives, challenging your understanding of concepts and trade-offs.
  • Design Exercises: Actively drawing architectural diagrams, data flow charts, and component breakdowns for various notification scenarios.
  • Case Study Analysis: Applying

python

from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text

from sqlalchemy.orm import relationship

from sqlalchemy.sql import func

from database import Base

class User(Base):

"""

Represents a user in the system.

Simplified for notification purposes; can be integrated with an existing user service.

"""

__tablename__ = "users"

id = Column(Integer, primary_key=True, index=True)

email = Column(String, unique=True, index=True, nullable=False)

phone_number = Column(String, unique=True, nullable=True) # Optional

name = Column(String, nullable=True)

preferences = relationship("UserPreference", back_populates="user")

notifications = relationship("Notification", back_populates="recipient_user")

class NotificationTemplate(Base):

"""

Stores templates for different types of notifications.

Templates can be simple strings or more complex structures (e.g., HTML for email).

"""

__tablename__ = "notification_templates"

id = Column(Integer, primary_key=True, index=True)

name = Column(String, unique=True, index=True, nullable=False) # e.g., "welcome_email", "order_confirmation_sms"

subject = Column(String, nullable=True) # For email

body = Column(Text, nullable=False)

channel_type = Column(String, nullable=False) # e.g., "email", "sms", "in-app"

created_at = Column(DateTime(timezone=True), server_default=func.now())

updated_at = Column(DateTime(timezone=True), onupdate=func.now())

class Notification(Base):

"""

Records a sent notification for history and auditing.

"""

__tablename__ = "notifications"

id = Column(Integer, primary_key=True, index=True)

recipient_id = Column(Integer, ForeignKey("users.id"), nullable=False)

template_id = Column(Integer, ForeignKey("notification_templates.id"), nullable=True) # Optional, if not using template

channel_type = Column(String, nullable=False) # e.g., "email", "sms", "in-app"

subject = Column(String, nullable=True) # Actual subject used

body = Column(Text, nullable=False) # Actual body sent

status = Column(String, default="pending", nullable=False) # e.g., "pending", "sent", "failed"

sent_at = Column(DateTime(timezone=True), server_default=func.now())

failed_reason = Column(Text, nullable=True)

recipient_user = relationship("User", back_populates="notifications")

template = relationship("NotificationTemplate")

class UserPreference(Base):

"""

Defines a user's preference for receiving certain notification types via specific channels.

"""

__tablename__ = "user_preferences"

id = Column(Integer, primary_key=True, index=True)

user_id = Column(Integer, ForeignKey("users.id"), nullable=False)

notification_type = Column(String, nullable=False) # e.g., "marketing", "transactional", "security"

channel_type = Column(String, nullable=False) # e.g., "email", "sms", "in-app"

enabled = Column(Boolean, default=True, nullable=False)

user = relationship("User

gemini Output

As part of the "Notification System" workflow, this document provides a comprehensive review and detailed documentation of the proposed notification system. This output serves as a foundational deliverable, outlining the system's purpose, architecture, features, and operational considerations.


1. Executive Summary

This document details the design and capabilities of a robust, scalable, and flexible Notification System. The system is engineered to centralize and standardize how our services communicate with users and internal stakeholders across multiple channels. By providing a unified API, dynamic templating, and comprehensive preference management, this system will significantly enhance user engagement, improve critical information dissemination, and streamline developer integration efforts. This deliverable consolidates the strategic vision and technical blueprint, setting the stage for subsequent development phases.

2. System Overview and Objectives

The Notification System is designed to be the single source for all outbound communications, ensuring consistency, reliability, and user control.

2.1. Core Purpose

To provide a highly available, asynchronous, and extensible platform for sending timely and relevant notifications to users and system administrators via their preferred channels.

2.2. Key Objectives

  • Enhance User Engagement: Deliver personalized and timely communications that keep users informed and connected.
  • Improve Information Dissemination: Ensure critical alerts and transactional information reach recipients reliably and promptly.
  • Streamline Development: Offer a simple, unified API for internal services to trigger notifications, reducing integration complexity and boilerplate code.
  • Provide User Control: Empower users to manage their notification preferences (channels, frequency, categories).
  • Ensure Scalability & Reliability: Design a system capable of handling high volumes of notifications with built-in fault tolerance and retry mechanisms.
  • Maintain Compliance & Security: Adhere to data privacy regulations (e.g., GDPR, CCPA) and security best practices.

3. Core Capabilities and Features

The Notification System will offer a rich set of features to meet diverse communication needs:

  • Multi-Channel Delivery: Support for various communication channels including Email, SMS, Push Notifications (mobile/web), and In-App notifications.
  • Dynamic Templating Engine: Allows for the creation and management of notification templates with dynamic content insertion, enabling personalization and consistent branding.
  • User Preference Management: A dedicated service for storing and applying user-defined preferences for notification types, channels, and frequency.
  • Notification Prioritization: Ability to assign priority levels (e.g., critical, high, medium, low) to notifications, influencing delivery speed and retry logic.
  • Asynchronous Processing: All notification requests are processed asynchronously via message queues to ensure non-blocking operations and system resilience.
  • Retry Mechanisms & Fallbacks: Configurable retry policies for transient delivery failures, with potential fallback channels or escalation paths.
  • Auditing and Logging: Comprehensive logging of notification requests, processing status, and delivery outcomes for traceability, debugging, and compliance.
  • API-Driven Integration: A well-documented RESTful API for internal services to trigger notifications with minimal effort.
  • Idempotency: Mechanisms to prevent duplicate notifications from being sent if a request is received multiple times.

4. Architectural Design (High-Level)

The system will follow a microservices-oriented architecture, leveraging message queues for decoupling and scalability.

4.1. Key Components

  • Notification Service API Gateway: The primary entry point for all internal services to request notifications. Handles authentication, authorization, and initial request validation.
  • Message Queue (e.g., Kafka/RabbitMQ): A high-throughput, fault-tolerant message broker used to decouple the API gateway from the processing logic. It ensures asynchronous processing and buffers requests during peak loads.
  • Notification Processor Service: Consumes messages from the queue, fetches user preferences, resolves notification templates with dynamic data, and determines the appropriate delivery channels.
  • Template Management Service/Repository: Stores and manages all notification templates, allowing for versioning and dynamic updates without code deployments.
  • User Preference Service/Database: Dedicated storage for user-specific notification settings, including opt-ins/outs, preferred channels, and frequency caps.
  • Channel Adapters (Email, SMS, Push, In-App): Specialized microservices or modules responsible for integrating with external third-party providers (e.g., SendGrid, Twilio, Firebase Cloud Messaging) for actual message delivery. Each adapter handles provider-specific APIs and error handling.
  • Reporting & Analytics Service: Aggregates delivery data, success/failure rates, and user engagement metrics for dashboards and insights.
  • Monitoring & Alerting: Integrated with existing observability tools (e.g., Prometheus, Grafana, ELK stack) for real-time system health, performance, and error alerting.

4.2. Notification Flow

  1. Trigger: An internal service (e.g., Order Service, User Service) calls the Notification Service API Gateway with a notification request (template ID, recipient info, dynamic data).
  2. Queueing: The API Gateway validates the request and publishes it as a message to the Message Queue.
  3. Processing: The Notification Processor Service consumes the message from the queue.
  4. Lookup & Resolution:

* It queries the User Preference Service to retrieve the recipient's preferences.

* It fetches the relevant template from the Template Management Service.

* It renders the template with the provided dynamic data, applying personalization and channel-specific content.

  1. Delivery: Based on preferences and template configuration, the Processor forwards the prepared message to the appropriate Channel Adapter(s).
  2. External Delivery: The Channel Adapter interacts with the external provider (e.g., SendGrid for email, Twilio for SMS) to send the notification.
  3. Status & Logging: Delivery status is reported back to the Notification Processor and logged for auditing and analytics.

5. Notification Types and Use Cases

The system will support various categories of notifications:

  • Account & Security: Password reset links, login alerts, multi-factor authentication codes, account activity warnings.
  • Transactional: Order confirmations, shipping updates, payment receipts, subscription renewals, service status changes.
  • System Alerts: Critical system outages, maintenance windows, administrative warnings.
  • User Interaction: Mentions, comments, direct messages, friend requests, activity feed updates.
  • Marketing & Promotional: Product updates, special offers, newsletters (strictly opt-in/opt-out compliant).
  • Reminders: Appointment reminders, task due dates, incomplete profile prompts.

6. User Experience & Preference Management

A key aspect of the system is empowering users to control their notification experience.

  • Dedicated UI: Users will have a clear, intuitive section within their profile settings to manage all notification preferences.
  • Granular Control: Users can opt in/out of specific notification categories (e.g., marketing, transactional, security) and select preferred channels for each category.
  • Channel Prioritization: Users can define a preferred channel order (e.g., "try push first, then email if offline, never SMS").
  • Frequency Caps: Options to limit the number of non-critical notifications received within a given timeframe.
  • Default Settings: Sensible default preferences will be pre-configured, allowing users to easily customize them.
  • Unsubscribe Mechanisms: All marketing and non-essential emails will include clear unsubscribe links, adhering to legal requirements.

7. Reliability, Scalability, and Performance

The system is designed for high availability and performance under varying loads.

  • Asynchronous Processing: Message queues inherently provide resilience against spikes in traffic and ensure that notification delivery doesn't block critical business logic.
  • Horizontal Scaling: All processing services (Notification Processor, Channel Adapters) will be designed to be stateless, allowing for easy horizontal scaling based on demand.
  • Rate Limiting: Implemented at Channel Adapters to prevent exceeding external provider API limits and to manage outgoing traffic effectively.
  • Circuit Breakers: To isolate failures in external communication channels, preventing cascading failures within the system.
  • Dead-Letter Queues (DLQs): For messages that cannot be processed successfully after multiple retries, allowing for manual inspection and re-processing.
  • Prioritization Queues: Critical notifications can be routed through dedicated, higher-priority queues to ensure faster processing.

8. Security and Compliance

Security and data privacy are paramount to the Notification System.

  • Data Encryption: All sensitive data (e.g., user contact information, notification content) will be encrypted in transit (TLS/SSL) and at rest (disk encryption, database encryption).
  • Access Control: Strict authentication (e.g., API keys, OAuth tokens) and authorization mechanisms will be enforced for all API endpoints.
  • Input Validation: Rigorous validation of all incoming notification requests to prevent injection attacks (e.g., XSS in email templates).
  • Privacy by Design: The system will be designed to comply with data privacy regulations (e.g., GDPR, CCPA) by:

* Obtaining explicit consent for marketing communications.

* Providing mechanisms for users to access, modify, or delete their notification data.

* Implementing strict data retention policies.

* Minimizing the collection of personally identifiable information (PII) where possible.

  • Audit Trails: Comprehensive logs will record who sent what notification, when, and to whom, for accountability and compliance purposes.

9. Monitoring, Logging, and Alerting

Robust observability is crucial for maintaining a healthy and performant notification system.

  • Key Metrics: Track notification send rates, delivery success/failure rates per channel, latency, queue depths, error rates per external provider, and user engagement metrics.
  • Centralized Logging: All system logs will be aggregated into a centralized logging platform (e.g., ELK stack, Splunk) for easy searching, analysis, and debugging.
  • Real-time Dashboards: Visual dashboards (e.g., Grafana) will provide real-time insights into system health, performance trends, and operational status.
  • Automated Alerting: Configured alerts for critical events such as high error rates, prolonged queue backlogs, external provider outages, or degraded performance.
  • Distributed Tracing: Implementation of tracing (e.g., OpenTelemetry, Jaeger) to track the full lifecycle of a notification request across multiple services.

10. Future Enhancements and Roadmap

While the initial build focuses on core functionality, the system is designed for future expansion:

  • Localization & Internationalization: Support for multiple languages and region-specific content.
  • A/B Testing Framework: Ability to test different notification contents, timings, and channels to optimize engagement.
  • Advanced Analytics: Deeper insights into user interaction, conversion rates, and the impact of notifications on key business metrics.
  • Machine Learning Integration: Potential for smart scheduling, personalized content recommendations, and anomaly detection in notification patterns.
  • Webhooks: Provide webhooks for external systems to subscribe to notification events (e.g., delivery status).
  • Developer Self-Service Portal: A dedicated portal for developers to manage templates, view API documentation, and monitor their notification usage.

11. Recommendations and Next Steps

To move forward with the implementation of this Notification System, we recommend the following immediate next steps:

  1. Stakeholder Review & Feedback: Schedule a dedicated session with all relevant stakeholders to review this detailed documentation, gather feedback, and ensure alignment on scope and priorities.
  2. Detailed Design & Technology Stack Selection: Initiate a deep-dive design phase for each core component, including specific technology choices (e.g., message broker, database, templating engine, external providers) and API specifications.
  3. Proof of Concept (POC): Develop a small-scale, end
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);}});}