refactor: improve build configuration and code organization

- Add build scripts for Android and iOS platforms
- Remove duplicate web implementation (src/web.ts)
- Add proper TypeScript configuration
- Add module documentation to index.ts
- Clean up package.json scripts

This commit improves the project structure and build process by:
1. Adding dedicated build scripts for native platforms
2. Removing redundant web implementation
3. Adding proper TypeScript configuration with strict mode
4. Improving code documentation
5. Organizing package.json scripts

The changes maintain backward compatibility while improving
the development experience and code quality.
This commit is contained in:
Matthew Raymer
2025-03-25 13:13:55 +00:00
parent e946767cba
commit 71e0f297ff
92 changed files with 11523 additions and 69 deletions
+259
View File
@@ -0,0 +1,259 @@
/**
* Advanced usage examples for the Daily Notification plugin
* Demonstrates complex scenarios and best practices
*/
import { registerPlugin } from '@capacitor/core';
import { DailyNotificationPlugin, NotificationOptions, NotificationSettings } from '../src/definitions';
const DailyNotification = registerPlugin<DailyNotificationPlugin>('DailyNotification');
/**
* Example of handling multiple notification schedules
*/
async function handleMultipleSchedules() {
try {
// Morning notification
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/morning-content',
time: '08:00',
title: 'Morning Briefing',
body: 'Your morning briefing is ready',
priority: 'high'
});
// Evening notification
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/evening-content',
time: '20:00',
title: 'Evening Summary',
body: 'Your daily summary is ready',
priority: 'normal'
});
console.log('Multiple schedules set up successfully');
} catch (error) {
console.error('Failed to setup multiple schedules:', error);
}
}
/**
* Example of handling timezone changes
*/
async function handleTimezoneChanges() {
try {
// Get user's timezone
const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
// Schedule notification with timezone consideration
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/timezone-aware-content',
time: '09:00',
title: 'Timezone-Aware Update',
body: 'Your timezone-aware content is ready',
timezone: userTimezone
});
// Listen for timezone changes
window.addEventListener('timezonechange', async () => {
const newTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
await DailyNotification.updateSettings({
timezone: newTimezone
});
});
} catch (error) {
console.error('Failed to handle timezone changes:', error);
}
}
/**
* Example of implementing retry logic with exponential backoff
*/
async function implementRetryLogic() {
const maxRetries = 3;
const baseDelay = 1000; // 1 second
async function fetchWithRetry(url: string, retryCount = 0): Promise<Response> {
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Network response was not ok');
return response;
} catch (error) {
if (retryCount >= maxRetries) throw error;
const delay = baseDelay * Math.pow(2, retryCount);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, retryCount + 1);
}
}
try {
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/unstable-content',
time: '10:00',
title: 'Retry-Enabled Update',
body: 'Your content with retry logic is ready',
retryCount: maxRetries,
retryInterval: baseDelay / 1000, // Convert to seconds
contentHandler: async (response) => {
const data = await response.json();
return {
title: data.title,
body: data.content,
data: data.metadata
};
}
});
} catch (error) {
console.error('Failed to implement retry logic:', error);
}
}
/**
* Example of implementing offline support
*/
async function implementOfflineSupport() {
try {
// Check if we're online
const isOnline = navigator.onLine;
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/offline-aware-content',
time: '11:00',
title: 'Offline-Aware Update',
body: 'Your offline-aware content is ready',
offlineFallback: true,
cacheDuration: 24, // Cache for 24 hours
contentHandler: async (response) => {
const data = await response.json();
// Store in IndexedDB for offline access
if ('indexedDB' in window) {
const db = await openDB('notificationCache', 1, {
upgrade(db) {
db.createObjectStore('content');
}
});
await db.put('content', data, 'latest');
}
return {
title: data.title,
body: data.content,
data: data.metadata
};
}
});
// Listen for online/offline events
window.addEventListener('online', () => {
console.log('Back online, syncing content...');
// Trigger content sync
});
window.addEventListener('offline', () => {
console.log('Offline, using cached content...');
// Use cached content
});
} catch (error) {
console.error('Failed to implement offline support:', error);
}
}
/**
* Example of implementing user preferences
*/
async function implementUserPreferences() {
try {
// Get user preferences from storage
const preferences = {
notificationTime: '12:00',
soundEnabled: true,
priority: 'high' as const,
categories: ['news', 'weather', 'tasks']
};
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/personalized-content',
time: preferences.notificationTime,
title: 'Personalized Update',
body: 'Your personalized content is ready',
sound: preferences.soundEnabled,
priority: preferences.priority,
headers: {
'X-User-Categories': preferences.categories.join(',')
}
});
// Listen for preference changes
window.addEventListener('storage', (event) => {
if (event.key === 'notificationPreferences') {
const newPreferences = JSON.parse(event.newValue || '{}');
DailyNotification.updateSettings({
time: newPreferences.notificationTime,
sound: newPreferences.soundEnabled,
priority: newPreferences.priority
});
}
});
} catch (error) {
console.error('Failed to implement user preferences:', error);
}
}
/**
* Example of implementing analytics and monitoring
*/
async function implementAnalytics() {
try {
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/analytics-enabled-content',
time: '13:00',
title: 'Analytics-Enabled Update',
body: 'Your analytics-enabled content is ready',
contentHandler: async (response) => {
const data = await response.json();
// Track notification delivery
await trackEvent('notification_delivered', {
timestamp: new Date().toISOString(),
contentId: data.id,
contentType: data.type
});
return {
title: data.title,
body: data.content,
data: data.metadata
};
}
});
// Track notification interactions
document.addEventListener('notification_clicked', async (event) => {
await trackEvent('notification_clicked', {
timestamp: new Date().toISOString(),
notificationId: event.detail.id,
action: event.detail.action
});
});
} catch (error) {
console.error('Failed to implement analytics:', error);
}
}
// Helper function for analytics
async function trackEvent(eventName: string, properties: Record<string, any>) {
// Implement your analytics tracking logic here
console.log(`Tracking event: ${eventName}`, properties);
}
// Export all advanced example functions
export {
handleMultipleSchedules,
handleTimezoneChanges,
implementRetryLogic,
implementOfflineSupport,
implementUserPreferences,
implementAnalytics
};
+262
View File
@@ -0,0 +1,262 @@
/**
* Enterprise-level usage examples for the Daily Notification plugin
* Demonstrates advanced features and best practices for large-scale applications
*/
import { DailyNotification } from '@timesafari/daily-notification-plugin';
import { NotificationOptions, NotificationSettings } from '../src/definitions';
/**
* Example of implementing a notification queue system
*/
async function implementNotificationQueue() {
const plugin = new DailyNotification();
const queue: NotificationOptions[] = [];
let isProcessing = false;
async function processQueue() {
if (isProcessing || queue.length === 0) return;
isProcessing = true;
try {
const notification = queue.shift();
if (notification) {
await plugin.scheduleDailyNotification(notification);
}
} catch (error) {
console.error('Failed to process notification:', error);
// Retry logic here
} finally {
isProcessing = false;
}
}
// Add to queue
queue.push({
url: 'https://api.example.com/enterprise/updates',
time: '09:00',
title: 'Enterprise Update',
priority: 'high',
retryCount: 3,
retryInterval: 5000,
});
// Process queue
await processQueue();
}
/**
* Example of implementing A/B testing for notifications
*/
async function implementABTesting() {
const plugin = new DailyNotification();
async function scheduleABTest() {
const variants = [
{
title: 'Version A: Direct Call-to-Action',
body: 'Click here to view your daily report',
priority: 'high',
},
{
title: 'Version B: Value Proposition',
body: 'Your daily insights are ready to help you succeed',
priority: 'normal',
},
];
// Randomly select a variant
const variant = variants[Math.floor(Math.random() * variants.length)];
await plugin.scheduleDailyNotification({
url: 'https://api.example.com/ab-test-content',
time: '10:00',
...variant,
data: {
variant: variant === variants[0] ? 'A' : 'B',
timestamp: new Date().toISOString(),
},
});
}
await scheduleABTest();
}
/**
* Example of implementing notification analytics and tracking
*/
async function implementAnalyticsTracking() {
const plugin = new DailyNotification();
// Track notification delivery
plugin.on('notification', async (event) => {
await trackAnalytics({
event: 'notification_delivered',
notificationId: event.detail.id,
timestamp: new Date().toISOString(),
platform: navigator.platform,
userAgent: navigator.userAgent,
});
});
// Track notification interactions
document.addEventListener('notification_clicked', async (event) => {
await trackAnalytics({
event: 'notification_clicked',
notificationId: event.detail.id,
timestamp: new Date().toISOString(),
action: event.detail.action,
data: event.detail.data,
});
});
async function trackAnalytics(data: Record<string, any>) {
// Implement your analytics tracking logic here
console.log('Analytics Event:', data);
}
}
/**
* Example of implementing notification preferences management
*/
async function implementPreferencesManagement() {
const plugin = new DailyNotification();
interface UserPreferences {
notificationTimes: string[];
categories: string[];
priority: 'low' | 'normal' | 'high';
sound: boolean;
timezone: string;
}
async function updateUserPreferences(preferences: UserPreferences) {
// Update all scheduled notifications
for (const time of preferences.notificationTimes) {
await plugin.updateSettings({
time,
priority: preferences.priority,
sound: preferences.sound,
timezone: preferences.timezone,
});
}
// Schedule new notifications for each category
for (const category of preferences.categories) {
await plugin.scheduleDailyNotification({
url: `https://api.example.com/categories/${category}`,
time: preferences.notificationTimes[0],
title: `${category} Update`,
priority: preferences.priority,
sound: preferences.sound,
timezone: preferences.timezone,
});
}
}
// Example usage
await updateUserPreferences({
notificationTimes: ['09:00', '12:00', '18:00'],
categories: ['news', 'tasks', 'updates'],
priority: 'high',
sound: true,
timezone: 'America/New_York',
});
}
/**
* Example of implementing notification content personalization
*/
async function implementContentPersonalization() {
const plugin = new DailyNotification();
interface UserProfile {
id: string;
name: string;
preferences: {
language: string;
timezone: string;
categories: string[];
};
}
async function schedulePersonalizedNotification(profile: UserProfile) {
await plugin.scheduleDailyNotification({
url: 'https://api.example.com/personalized-content',
time: '09:00',
title: `Good morning, ${profile.name}!`,
priority: 'high',
timezone: profile.preferences.timezone,
headers: {
'X-User-ID': profile.id,
'X-Language': profile.preferences.language,
'X-Categories': profile.preferences.categories.join(','),
},
contentHandler: async (response) => {
const data = await response.json();
return {
title: data.title,
body: data.content,
data: {
...data.metadata,
userId: profile.id,
timestamp: new Date().toISOString(),
},
};
},
});
}
// Example usage
await schedulePersonalizedNotification({
id: 'user123',
name: 'John Doe',
preferences: {
language: 'en-US',
timezone: 'America/New_York',
categories: ['news', 'weather', 'tasks'],
},
});
}
/**
* Example of implementing notification rate limiting
*/
async function implementRateLimiting() {
const plugin = new DailyNotification();
class RateLimiter {
private lastNotificationTime: number = 0;
private minInterval: number = 60000; // 1 minute
async scheduleWithRateLimit(options: NotificationOptions): Promise<void> {
const now = Date.now();
if (now - this.lastNotificationTime < this.minInterval) {
throw new Error('Rate limit exceeded. Please wait before scheduling another notification.');
}
await plugin.scheduleDailyNotification(options);
this.lastNotificationTime = now;
}
}
const rateLimiter = new RateLimiter();
// Example usage
await rateLimiter.scheduleWithRateLimit({
url: 'https://api.example.com/rate-limited-content',
time: '11:00',
title: 'Rate Limited Update',
priority: 'normal',
});
}
// Export all enterprise example functions
export {
implementNotificationQueue,
implementABTesting,
implementAnalyticsTracking,
implementPreferencesManagement,
implementContentPersonalization,
implementRateLimiting,
};
+165
View File
@@ -0,0 +1,165 @@
/**
* Example usage of the Daily Notification plugin
* Demonstrates various features and best practices
*/
import { registerPlugin } from '@capacitor/core';
import { DailyNotificationPlugin } from '../src/definitions';
const DailyNotification = registerPlugin<DailyNotificationPlugin>('DailyNotification');
/**
* Basic setup for daily notifications
*/
async function setupBasicNotifications() {
try {
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/daily-content',
time: '08:00', // 8 AM
title: 'Daily Update',
body: 'Your daily content is ready!'
});
console.log('Daily notifications scheduled successfully');
} catch (error) {
console.error('Failed to schedule notifications:', error);
}
}
/**
* Advanced setup with custom options
*/
async function setupAdvancedNotifications() {
try {
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/daily-content',
time: '09:00', // 9 AM
title: 'Daily Digest',
body: 'Your personalized daily digest is ready',
sound: true,
vibrate: true,
priority: 'high',
retryCount: 3,
retryInterval: 15, // minutes
cacheDuration: 24, // hours
headers: {
'Authorization': 'Bearer your-token'
}
});
console.log('Advanced notification setup completed');
} catch (error) {
console.error('Failed to setup advanced notifications:', error);
}
}
/**
* Handle notification response
*/
async function handleNotificationResponse() {
try {
const response = await DailyNotification.getLastNotification();
if (response) {
console.log('Last notification:', response);
// Handle the notification data
}
} catch (error) {
console.error('Failed to get last notification:', error);
}
}
/**
* Cancel all scheduled notifications
*/
async function cancelNotifications() {
try {
await DailyNotification.cancelAllNotifications();
console.log('All notifications cancelled');
} catch (error) {
console.error('Failed to cancel notifications:', error);
}
}
/**
* Check notification status
*/
async function checkNotificationStatus() {
try {
const status = await DailyNotification.getNotificationStatus();
console.log('Notification status:', status);
return status;
} catch (error) {
console.error('Failed to get notification status:', error);
return null;
}
}
/**
* Update notification settings
*/
async function updateNotificationSettings() {
try {
await DailyNotification.updateSettings({
time: '10:00', // Change to 10 AM
sound: false, // Disable sound
priority: 'normal'
});
console.log('Notification settings updated');
} catch (error) {
console.error('Failed to update settings:', error);
}
}
/**
* Example of handling network errors
*/
async function handleNetworkErrors() {
try {
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/daily-content',
time: '08:00',
retryCount: 3,
retryInterval: 15,
offlineFallback: true
});
} catch (error) {
if (error.code === 'NETWORK_ERROR') {
console.log('Network error, will retry later');
} else {
console.error('Unexpected error:', error);
}
}
}
/**
* Example of using custom content handlers
*/
async function useCustomContentHandler() {
try {
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/daily-content',
time: '08:00',
contentHandler: async (response) => {
// Custom processing of the API response
const data = await response.json();
return {
title: data.title,
body: data.summary,
data: data.details
};
}
});
} catch (error) {
console.error('Failed to setup custom content handler:', error);
}
}
// Export all example functions
export {
setupBasicNotifications,
setupAdvancedNotifications,
handleNotificationResponse,
cancelNotifications,
checkNotificationStatus,
updateNotificationSettings,
handleNetworkErrors,
useCustomContentHandler
};