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

This document outlines the comprehensive, detailed, and professional output for Step 2 of 3: gemini → generate_code for the "Notification System" workflow. The goal of this step is to provide production-ready, well-commented code that forms the foundational components of a robust notification system.


Notification System: Code Generation Deliverable

This deliverable provides the core code components for a flexible and extensible Notification System. The generated code focuses on modularity, clear separation of concerns, and includes mechanisms for different notification channels, user preferences, templating, and asynchronous processing.

1. System Overview and Architecture

The Notification System is designed with the following key architectural principles:

High-Level Architecture Diagram (Conceptual)

text • 2,929 chars
+---------------------+      +-----------------------------+
|    Your Application |      | Notification Trigger (API)  |
| (e.g., E-commerce,  +----->| - /notify                   |
|   CRM, Analytics)   |      | - /preferences              |
+---------------------+      +-------------+---------------+
                                           |
                                           | (Calls NotificationService)
                                           v
+-----------------------------------------------------------------------+
|                       Notification Service Layer                      |
|-----------------------------------------------------------------------|
| - create_notification()                                               |
| - schedule_notification()         +-----------------------+           |
| - get_user_preferences()          | Notification Templates|           |
| - render_template()               +-----------------------+           |
| - ...                             |                       |           |
+-----------------------------------+-----------------------+-----------+
                                    |
                                    | (Adds to Queue)
                                    v
+-----------------------------------------------------------------------+
|                       Message Queue (e.g., Redis, RabbitMQ)           |
|-----------------------------------------------------------------------|
| - Stores pending notification tasks                                   |
+-----------------------------------------------------------------------+
                                    |
                                    | (Worker Consumes)
                                    v
+-----------------------------------------------------------------------+
|                       Notification Worker(s)                          |
|-----------------------------------------------------------------------|
| - Dequeues tasks                                                      |
| - Processes notification (renders, selects provider)                  |
| - Updates notification status (sent, failed)                          |
+-----------------------------------------------------------------------+
        |                  |                  |                  |
        v                  v                  v                  v
+-------+--------+ +-------+--------+ +-------+--------+ +-------+--------+
| Email Provider | | SMS Provider   | | In-App Provider| | Push Provider  |
| (e.g., SendGrid)| | (e.g., Twilio) | | (DB, WebSockets)| | (e.g., FCM, APNS)|
+----------------+ +----------------+ +----------------+ +----------------+
        |                  |                  |                  |
        v                  v                  v                  v
  Actual Email       Actual SMS        In-App DB/UI    Mobile Device
Sandboxed live preview

python

models.py

import datetime

from typing import Dict, Any, List, Optional

from enum import Enum

--- Enums for clarity and consistency ---

class NotificationChannel(str, Enum):

"""Defines available notification channels."""

EMAIL = "email"

SMS = "sms"

IN_APP = "in_app"

PUSH = "push" # Placeholder for future expansion

class NotificationType(str, Enum):

"""Defines common types of notifications."""

ALERT = "alert"

REMINDER = "reminder"

PROMOTION = "promotion"

UPDATE = "update"

WELCOME = "welcome"

TRANSACTIONAL = "transactional" # e.g., order confirmation

class NotificationStatus(str, Enum):

"""Defines the lifecycle status of a notification."""

PENDING = "pending"

SENT = "sent"

FAILED = "failed"

CANCELLED = "cancelled"

QUEUED = "queued"

--- Core Data Models ---

class User:

"""Represents a user in the system."""

def __init__(self, user_id: str, email: str, phone_number: Optional[str] = None, name: Optional[str] = None):

self.user_id = user_id

self.email = email

self.phone_number = phone_number

self.name = name

def to_dict(self) -> Dict[str, Any]:

return {

"user_id": self.user_id,

"email": self.email,

"phone_number": self.phone_number,

"name": self.name

}

class NotificationPreference:

"""Stores user-specific preferences for receiving notifications."""

def __init__(self, user_id: str):

self.user_id = user_id

# Default to opt-in for all channels and types.

# Specific preferences can be stored as dictionaries mapping channel/type to boolean.

self.channel_preferences: Dict[NotificationChannel, bool] = {

NotificationChannel.EMAIL: True,

NotificationChannel.SMS: True,

NotificationChannel.IN_APP: True,

NotificationChannel.PUSH: True,

}

self.type_preferences: Dict[NotificationType, bool] = {

NotificationType.ALERT: True,

NotificationType.REMINDER: True,

NotificationType.PROMOTION: True,

NotificationType.UPDATE: True,

NotificationType.WELCOME: True,

NotificationType.TRANSACTIONAL: True,

}

def can_receive(self, channel: NotificationChannel, notification_type: NotificationType) -> bool:

"""Checks if the user has opted in for a given channel and type."""

return self.channel_preferences.get(channel, False) and self.type_preferences.get(notification_type, False)

def to_dict(self) -> Dict[str, Any]:

return {

"user_id": self.user_id,

"channel_preferences": {k.value: v for k, v in self.channel_preferences.items()},

"type_preferences": {k.value: v for k, v in self.type_preferences.items()},

}

class NotificationTemplate:

"""Defines a reusable template for specific notification types and channels."""

def __init__(self, template_id: str, name: str, notification_type: NotificationType,

channel: NotificationChannel, subject_template: Optional[str] = None,

body_template: str = "", metadata: Optional[Dict[str, Any]] = None):

self.template_id = template_id

self.name = name

self.notification_type = notification_type

self.channel = channel

self.subject_template = subject_template # Primarily for email

self.body_template = body_template

self.metadata = metadata if metadata is not None else {} # e.g., 'sender_name' for email

def to_dict(self) -> Dict[str, Any]:

return {

"template_id": self.template_id,

"name": self.name,

"notification_type": self.notification_type.value,

"channel": self.channel.value,

"subject_template": self.subject_template,

"body_template": self.body_template,

"metadata": self.metadata

}

class Notification:

"""Represents a single instance of a notification to be sent or already sent."""

def __init__(self, notification_id: str, user_id: str, notification_type: NotificationType,

channel: NotificationChannel, template_id: str,

rendered_subject: Optional[str] = None, rendered_body: str = "",

status: NotificationStatus = NotificationStatus.PENDING,

created_at: datetime.datetime = None, sent_at: Optional[datetime.datetime] = None,

error_message: Optional[str] = None, retry_count: int = 0,

metadata: Optional[Dict[str, Any]] = None):

self.notification_id = notification_id

self.user_id = user_id

self.notification_type = notification_type

self.channel = channel

self.template_id = template_id

self.rendered_subject = rendered_subject

self.rendered_body = rendered_body

self.status = status

self.created_at = created_at if created_at else datetime.datetime.now(datetime.timezone.utc)

self.sent_at = sent_at

self.error_message = error_message

self.retry_count = retry_count

self.metadata = metadata if metadata is not None else {} # Additional data for the notification instance

def to_dict(self) -> Dict[str, Any]:

return {

"notification_id": self.notification_id,

"user_id": self.user_id,

"notification_type": self.notification_type.value,

"channel": self.channel.value,

"template_id": self.template_id,

"rendered_subject": self.rendered_subject,

"rendered_body": self.rendered_body,

"status": self.status.value,

"created_at": self.created_at.isoformat(),

"sent_at": self.sent_at.isoformat() if self.sent_at else None,

"error_message": self.error_message,

"retry_count": self.retry_count,

"metadata": self.metadata

}

--- In-memory "Database" for demonstration ---

class InMemoryDB:

"""A simple in-memory database substitute for demonstration purposes."""

def __init__(self):

self.users: Dict[str, User] = {}

self.preferences: Dict[str, NotificationPreference] = {}

self.templates: Dict[str, NotificationTemplate] = {}

self.notifications: Dict[str, Notification] = {}

def add_user(self, user: User):

self.users[user.user_id] = user

# Initialize preferences for new users if they don't exist

if user.user_id not in self.preferences:

self.preferences[user.user_id] = NotificationPreference(user.user_id)

def get_user(self, user_id: str) -> Optional[User]:

return self.users.get(user_id)

def add_preference(self, preference: NotificationPreference):

self.preferences[preference.user_id] = preference

def get_preference(self, user_id: str) -> Optional[NotificationPreference]:

return self.preferences.get(user_id)

def add_template(self, template: NotificationTemplate):

self.templates[template.template_id] = template

def get_template(self, template_id: str) -> Optional[NotificationTemplate]:

return self.templates.get(template_id)

def

gemini Output

Comprehensive Review and Documentation: Notification System

This document provides a detailed overview and documentation of the proposed Notification System, outlining its core functionalities, architectural considerations, integration points, and strategic benefits. This system is designed to provide a robust, scalable, and highly configurable platform for managing all outbound communications, ensuring timely and relevant interactions with your users and stakeholders.


1. Executive Summary

The Notification System is a critical component designed to centralize, standardize, and optimize all communication touchpoints across your digital ecosystem. By offering a unified platform for multi-channel message delivery, advanced templating, personalization, and comprehensive analytics, this system empowers your organization to deliver highly effective and engaging notifications. This document details the system's capabilities, high-level architecture, and strategic advantages, laying the groundwork for its successful implementation and operation.


2. Introduction to the Notification System

2.1. Purpose and Objectives

The primary purpose of the Notification System is to enable efficient, reliable, and personalized communication across various channels. Its core objectives include:

  • Centralization: Provide a single source for managing all notification types and channels.
  • Consistency: Ensure brand voice and message consistency across all communications.
  • Personalization: Deliver highly relevant and tailored messages to individual users.
  • Reliability: Guarantee high deliverability rates with robust retry mechanisms and fallbacks.
  • Scalability: Support growing communication volumes and new channels without performance degradation.
  • Actionability: Provide insights into notification performance and user engagement.
  • Compliance: Adhere to regulatory requirements (e.g., GDPR, CAN-SPAM) for user privacy and communication preferences.

2.2. Core Value Proposition

This Notification System offers significant value by:

  • Enhancing User Experience: Delivering timely and relevant information improves user satisfaction and trust.
  • Driving Engagement: Personalized and targeted communications increase user interaction with your products/services.
  • Improving Operational Efficiency: Automating and centralizing notifications reduces manual effort and potential errors.
  • Enabling Data-Driven Decisions: Analytics on notification performance provide insights for continuous optimization.
  • Accelerating Time-to-Market: Standardized templates and APIs allow for quicker deployment of new communication campaigns.

3. Key Features and Capabilities

The Notification System is engineered with a comprehensive set of features to meet diverse communication needs:

  • 3.1. Multi-Channel Delivery:

* Email: Rich HTML and plain-text support, attachment capabilities.

* SMS/MMS: Text messages, multimedia messages, and short-code support.

* Push Notifications: Mobile (iOS, Android) and Web push notifications.

* In-App Notifications: Messages displayed directly within your application interface.

* Webhooks: Programmatic notifications to external systems or custom endpoints.

* Voice/IVR: (Optional, configurable module) Automated voice calls or interactive voice response.

  • 3.2. Advanced Templating Engine:

* Dynamic Templates: Support for variables and conditional logic to personalize content.

* Version Control: Manage different versions of templates for A/B testing or historical tracking.

* Localization: Support for multiple languages and regional formats.

* Drag-and-Drop Editor: (If applicable) User-friendly interface for non-technical users to create and modify templates.

  • 3.3. Personalization and Segmentation:

* Dynamic Content Insertion: Inject user-specific data (e.g., name, order details) into messages.

* Audience Segmentation: Target specific user groups based on demographics, behavior, or preferences.

* Contextual Delivery: Deliver messages based on user activity, time of day, or location.

  • 3.4. Scheduling and Throttling:

* Scheduled Delivery: Send notifications at specific future dates/times.

* Recurring Notifications: Set up repeating messages (e.g., daily digests).

* Rate Limiting/Throttling: Control the volume of messages sent per period to prevent overwhelming users or external services.

* Quiet Hours: Define periods during which non-critical notifications should be suppressed.

  • 3.5. Retry Mechanisms and Fallbacks:

* Automatic Retries: Configure retry logic for failed deliveries with exponential backoff.

* Channel Fallbacks: Define alternative channels if a primary channel fails (e.g., SMS if push fails).

* Error Handling: Robust logging and alerting for delivery failures.

  • 3.6. Analytics and Reporting:

* Delivery Status: Track sent, delivered, opened, clicked, and failed notifications.

* Engagement Metrics: Monitor user interactions, conversion rates, and unsubscribe rates.

* Performance Dashboards: Visual representations of key metrics.

* Export Capabilities: Download raw data for further analysis.

  • 3.7. User Preference Management:

* Subscription Center: Allow users to manage their notification preferences (e.g., opt-in/out of specific types, choose preferred channels).

* Global Opt-out: Support for complete unsubscribe functionality.

* Preference API: Programmatic access for internal systems to manage user preferences.

  • 3.8. Prioritization:

* Critical vs. Marketing: Assign priority levels to notifications to ensure urgent messages are delivered promptly.

* Queue Management: Prioritize messages within the sending queue.


4. High-Level System Architecture

The Notification System is designed with a modular and scalable architecture, typically comprising the following key components:


graph TD
    A[Triggering System/Application] --> B(Notification API Gateway);
    B --> C{Notification Service};
    C --> D(Template Store);
    C --> E(User Preference Service);
    C --> F(Notification Queue/Broker);
    F --> G{Channel Adapters};
    G -- Email --> H(Email Service Provider);
    G -- SMS --> I(SMS Gateway);
    G -- Push --> J(Mobile/Web Push Provider);
    G -- In-App --> K(Application Backend);
    G -- Webhook --> L(External System);
    C --> M(Analytics & Reporting DB);
    M --> N[Monitoring & Alerting];
    E --> O(User Interface for Preferences);

Key Components:

  • Triggering System/Application: Any internal or external system (e.g., CRM, e-commerce platform, backend service) that initiates a notification request.
  • Notification API Gateway: A secure and robust entry point for all notification requests, handling authentication, authorization, and initial validation.
  • Notification Service: The core brain of the system, responsible for:

* Receiving notification requests.

* Retrieving and rendering templates from the Template Store.

* Fetching user preferences from the User Preference Service.

* Applying personalization, segmentation, and throttling rules.

* Logging notification events for analytics.

* Enqueuing messages into the Notification Queue/Broker.

  • Template Store: A repository for all notification templates (e.g., email HTML, SMS text, push notification payloads).
  • User Preference Service: Manages and stores individual user communication preferences (opt-in/out, preferred channels).
  • Notification Queue/Broker: A message queue (e.g., Kafka, RabbitMQ, SQS) to decouple the sending process, ensuring reliability and scalability.
  • Channel Adapters: Dedicated modules for each communication channel, responsible for:

* Consuming messages from the queue.

* Translating generic notification data into channel-specific formats.

* Interacting with external Service Providers (e.g., Email Service Provider, SMS Gateway, Push Notification Provider).

* Handling delivery status callbacks and retries.

  • Analytics & Reporting DB: Stores all notification event data for reporting and analysis.
  • Monitoring & Alerting: Tools to track system health, delivery rates, and alert on anomalies.
  • User Interface for Preferences: A customer-facing portal or section within your application for users to manage their notification settings.

5. Integration Points

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

  • API-Driven Integration:

* RESTful API: Primary interface for triggering notifications, managing templates, and fetching delivery status.

* Event-Driven Integration: Support for consuming events from other systems (e.g., order created, user registered) to trigger notifications.

  • Data Sources:

* User Management Systems (UMS): Integration to retrieve user profiles and contact information.

* CRM/ERP Systems: To fetch transactional data, customer segments, and business logic.

* Product Catalogs: For dynamic content related to products or services.

  • External Service Providers:

* Email Service Providers (ESPs): SendGrid, Mailgun, AWS SES, etc.

* SMS Gateways: Twilio, Nexmo, Sinch, etc.

* Mobile Push Providers: Firebase Cloud Messaging (FCM), Apple Push Notification Service (APNS).

* Webhook Endpoints: For custom integrations with partner systems or internal services.

  • Analytics Platforms:

* Integration with existing BI tools or data warehouses for advanced reporting and cross-system analysis.


6. Configuration and Management

The system provides robust tools for administration and content management:

  • 6.1. Admin Interface (Dashboard):

* Centralized Control Panel: A web-based interface for administrators to manage all aspects of the system.

* Template Management: Create, edit, preview, and publish templates across channels.

* Channel Configuration: Configure credentials and settings for various email, SMS, and push providers.

* User Management: Manage roles and permissions for system administrators.

* System Health Monitoring: View real-time status of queues, delivery rates, and error logs.

  • 6.2. Template Versioning and A/B Testing:

* Maintain multiple versions of templates for iterative improvements and A/B testing campaigns.

* Rollback to previous template versions if needed.

  • 6.3. Audit Logs:

* Comprehensive logging of all administrative actions and notification events for compliance and troubleshooting.


7. Security, Scalability, and Reliability Considerations

  • 7.1. Security:

* Data Encryption: All sensitive data (e.g., PII in messages, API keys) will be encrypted at rest and in transit (TLS/SSL).

* Access Control: Role-Based Access Control (RBAC) for the admin interface and API.

* API Security: OAuth2/API Key authentication for external systems integrating with the Notification API.

* Compliance: Designed to comply with relevant data privacy regulations (e.g., GDPR, CCPA).

  • 7.2. Scalability:

* Microservices Architecture: Modular components allow for independent scaling.

* Stateless Services: Designed to be stateless where possible to facilitate horizontal scaling.

* Message Queues: Decouple components, handle spikes in traffic, and ensure reliable message processing.

* Cloud-Native Design: Leverages cloud services (e.g., auto-scaling groups, managed databases) for elasticity.

  • 7.3. Reliability and High Availability:

* Redundancy: All critical components will be deployed with redundancy across multiple availability zones.

* Automatic Failover: Mechanisms for automatic failover for databases and core services.

* Disaster Recovery: Defined RTO/RPO objectives with backup and recovery strategies.

* Circuit Breakers & Retries: Implement patterns to prevent cascading failures and ensure message delivery.


8. Use Cases & Applications

The Notification System supports a wide array of communication scenarios:

  • 8.1. Transactional Notifications:

* Order confirmations, shipping updates

* Password resets, account verifications

* Payment receipts, subscription renewals

* System alerts (e.g., low stock, service degradation)

  • 8.2. Marketing and Promotional Communications:

* New product announcements

* Special offers and discounts

* Event invitations

* Newsletter subscriptions

  • 8.3. User Engagement and Lifecycle Communications:

* Welcome emails/onboarding sequences

* Activity summaries, progress reports

* Reminder notifications (e.g., abandoned cart, upcoming appointments)

* Re-engagement campaigns for inactive users

  • 8.4. Operational and Support Communications:

* Customer support ticket updates

* Service outage notifications

* Internal team alerts (e.g., critical system errors)


9. Benefits of Implementing This System

Implementing the proposed Notification System will yield significant advantages:

  • Enhanced Customer Experience: Consistent, timely, and personalized communications foster trust and satisfaction.
  • Increased Engagement & Retention: Targeted messaging drives user interaction and reduces churn.
  • Operational Efficiency: Automation and centralization streamline communication workflows, reducing manual effort and errors.
  • Improved Decision Making: Comprehensive analytics provide actionable insights into communication effectiveness.
  • Scalability for Growth: The system is built to handle increasing volumes and new communication channels as your business expands.
  • Reduced Development Overhead: Developers can integrate with a single API instead of managing multiple vendor-specific integrations.
  • Regulatory Compliance: Built-in features for preference management and audit trails support compliance with privacy regulations.

10. Next Steps and Recommendations

To proceed with the successful implementation of this Notification System, we recommend the following actionable steps:

  1. Detailed Technical Design Session (Week 1-2):

* Conduct deep-dive workshops with your technical team to finalize specific technology choices (e.g., queueing system, database, specific ESP/SMS providers).

* Map out detailed API specifications and data models.

* Define integration strategies for all identified triggering systems.

  1. Define Initial Use Cases & Prioritization (Week 2):

* Identify 2-3 critical notification types (e.g., password reset, order

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