Compare commits

..

9 Commits

Author SHA1 Message Date
Matthew Aaron Raymer
cf4375164f Adding router-links 2022-11-30 13:09:12 +08:00
Jose Olarte III
bdb9da2b87 Added back fontawesome icons 2022-11-28 21:04:26 +08:00
Matthew Aaron Raymer
6fc070b45d Chimney added to project view 2022-11-28 19:03:23 +08:00
Matthew Aaron Raymer
55ba4f0154 Updates with Font-Awesome 2022-11-28 18:31:38 +08:00
Matthew Aaron Raymer
38d04566a4 Merge branch 'tmp' of ssh://173.199.124.46:222/trent_larson/kick-starter-for-time-pwa into tmp 2022-11-28 17:52:19 +08:00
Matthew Aaron Raymer
4b8466fb04 First font-awesome icon 2022-11-28 17:50:51 +08:00
Jose Olarte III
f45a528f43 Fixes to input fields
Padding and border defaults not implicitly defaulted
2022-11-28 17:42:25 +08:00
Matthew Aaron Raymer
d25f8f45bd All the router endpoints to views initiated 2022-11-28 13:11:29 +08:00
Matthew Aaron Raymer
fee0c08f76 Review universal nav from boilerplate 2022-11-28 12:40:17 +08:00
508 changed files with 10687 additions and 137782 deletions

View File

@@ -1,310 +0,0 @@
# Cursor Markdown Ruleset for TimeSafari Documentation
## Overview
This ruleset enforces consistent markdown formatting standards across all project
documentation, ensuring readability, maintainability, and compliance with
markdownlint best practices.
## General Formatting Standards
### Line Length
- **Maximum line length**: 80 characters
- **Exception**: Code blocks (JSON, shell, TypeScript, etc.) - no line length
enforcement
- **Rationale**: Ensures readability across different screen sizes and terminal
widths
### Blank Lines
- **Headings**: Must be surrounded by blank lines above and below
- **Lists**: Must be surrounded by blank lines above and below
- **Code blocks**: Must be surrounded by blank lines above and below
- **Maximum consecutive blank lines**: 1 (no multiple blank lines)
- **File start**: No blank lines at the beginning of the file
- **File end**: Single newline character at the end
### Whitespace
- **No trailing spaces**: Remove all trailing whitespace from lines
- **No tabs**: Use spaces for indentation
- **Consistent indentation**: 2 spaces for list items and nested content
## Heading Standards
### Format
- **Style**: ATX-style headings (`#`, `##`, `###`, etc.)
- **Case**: Title case for general headings
- **Code references**: Use backticks for file names and technical terms
-`### Current package.json Scripts`
-`### Current Package.json Scripts`
### Hierarchy
- **H1 (#)**: Document title only
- **H2 (##)**: Major sections
- **H3 (###)**: Subsections
- **H4 (####)**: Sub-subsections
- **H5+**: Avoid deeper nesting
## List Standards
### Unordered Lists
- **Marker**: Use `-` (hyphen) consistently
- **Indentation**: 2 spaces for nested items
- **Blank lines**: Surround lists with blank lines
### Ordered Lists
- **Format**: `1.`, `2.`, `3.` (sequential numbering)
- **Indentation**: 2 spaces for nested items
- **Blank lines**: Surround lists with blank lines
### Task Lists
- **Format**: `- [ ]` for incomplete, `- [x]` for complete
- **Use case**: Project planning, checklists, implementation tracking
## Code Block Standards
### Fenced Code Blocks
- **Syntax**: Triple backticks with language specification
- **Languages**: `json`, `bash`, `typescript`, `javascript`, `yaml`, `markdown`
- **Blank lines**: Must be surrounded by blank lines above and below
- **Line length**: No enforcement within code blocks
### Inline Code
- **Format**: Single backticks for inline code references
- **Use case**: File names, commands, variables, properties
## Special Content Standards
### JSON Examples
```json
{
"property": "value",
"nested": {
"property": "value"
}
}
```
### Shell Commands
```bash
# Command with comment
npm run build:web
# Multi-line command
VITE_GIT_HASH=`git log -1 --pretty=format:%h` \
vite build --config vite.config.web.mts
```
### TypeScript Examples
```typescript
// Function with JSDoc
/**
* Get environment configuration
* @param env - Environment name
* @returns Environment config object
*/
const getEnvironmentConfig = (env: string) => {
switch (env) {
case 'prod':
return { /* production settings */ };
default:
return { /* development settings */ };
}
};
```
## File Structure Standards
### Document Header
```markdown
# Document Title
**Author**: Matthew Raymer
**Date**: YYYY-MM-DD
**Status**: 🎯 **STATUS** - Brief description
## Overview
Brief description of the document's purpose and scope.
```
### Section Organization
1. **Overview/Introduction**
2. **Current State Analysis**
3. **Implementation Plan**
4. **Technical Details**
5. **Testing & Validation**
6. **Next Steps**
## Markdownlint Configuration
### Required Rules
```json
{
"MD013": { "code_blocks": false },
"MD012": true,
"MD022": true,
"MD031": true,
"MD032": true,
"MD047": true,
"MD009": true
}
```
### Rule Explanations
- **MD013**: Line length (disabled for code blocks)
- **MD012**: No multiple consecutive blank lines
- **MD022**: Headings should be surrounded by blank lines
- **MD031**: Fenced code blocks should be surrounded by blank lines
- **MD032**: Lists should be surrounded by blank lines
- **MD047**: Files should end with a single newline
- **MD009**: No trailing spaces
## Validation Commands
### Check Single File
```bash
npx markdownlint docs/filename.md
```
### Check All Documentation
```bash
npx markdownlint docs/
```
### Auto-fix Common Issues
```bash
# Remove trailing spaces
sed -i 's/[[:space:]]*$//' docs/filename.md
# Remove multiple blank lines
sed -i '/^$/N;/^\n$/D' docs/filename.md
# Add newline at end if missing
echo "" >> docs/filename.md
```
## Common Patterns
### Implementation Plans
```markdown
## Implementation Plan
### Phase 1: Foundation (Day 1)
#### 1.1 Component Setup
- [ ] Create new component file
- [ ] Add basic structure
- [ ] Implement core functionality
#### 1.2 Configuration
- [ ] Update configuration files
- [ ] Add environment variables
- [ ] Test configuration loading
```
### Status Tracking
```markdown
**Status**: ✅ **COMPLETE** - All phases finished
**Progress**: 75% (15/20 components)
**Next**: Ready for testing phase
```
### Performance Metrics
```markdown
#### 📊 Performance Metrics
- **Build Time**: 2.3 seconds (50% faster than baseline)
- **Bundle Size**: 1.2MB (30% reduction)
- **Success Rate**: 100% (no failures in 50 builds)
```
## Enforcement
### Pre-commit Hooks
- Run markdownlint on all changed markdown files
- Block commits with linting violations
- Auto-fix common issues when possible
### CI/CD Integration
- Include markdownlint in build pipeline
- Generate reports for documentation quality
- Fail builds with critical violations
### Team Guidelines
- All documentation PRs must pass markdownlint
- Use provided templates for new documents
- Follow established patterns for consistency
## Templates
### New Document Template
```markdown
# Document Title
**Author**: Matthew Raymer
**Date**: YYYY-MM-DD
**Status**: 🎯 **PLANNING** - Ready for Implementation
## Overview
Brief description of the document's purpose and scope.
## Current State
Description of current situation or problem.
## Implementation Plan
### Phase 1: Foundation
- [ ] Task 1
- [ ] Task 2
## Next Steps
1. **Review and approve plan**
2. **Begin implementation**
3. **Test and validate**
---
**Status**: Ready for implementation
**Priority**: Medium
**Estimated Effort**: X days
**Dependencies**: None
**Stakeholders**: Development team
```
---
**Last Updated**: 2025-07-09
**Version**: 1.0
**Maintainer**: Matthew Raymer

View File

@@ -1,153 +0,0 @@
---
description:
globs:
alwaysApply: true
---
# Absurd SQL - Cursor Development Guide
## Project Overview
Absurd SQL is a backend implementation for sql.js that enables persistent SQLite databases in the browser by using IndexedDB as a block storage system. This guide provides rules and best practices for developing with this project in Cursor.
## Project Structure
```
absurd-sql/
├── src/ # Source code
├── dist/ # Built files
├── package.json # Dependencies and scripts
├── rollup.config.js # Build configuration
└── jest.config.js # Test configuration
```
## Development Rules
### 1. Worker Thread Requirements
- All SQL operations MUST be performed in a worker thread
- Main thread should only handle worker initialization and communication
- Never block the main thread with database operations
### 2. Code Organization
- Keep worker code in separate files (e.g., `*.worker.js`)
- Use ES modules for imports/exports
- Follow the project's existing module structure
### 3. Required Headers
When developing locally or deploying, ensure these headers are set:
```
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```
### 4. Browser Compatibility
- Primary target: Modern browsers with SharedArrayBuffer support
- Fallback mode: Safari (with limitations)
- Always test in both modes
### 5. Database Configuration
Recommended database settings:
```sql
PRAGMA journal_mode=MEMORY;
PRAGMA page_size=8192; -- Optional, but recommended
```
### 6. Development Workflow
1. Install dependencies:
```bash
yarn add @jlongster/sql.js absurd-sql
```
2. Development commands:
- `yarn build` - Build the project
- `yarn jest` - Run tests
- `yarn serve` - Start development server
### 7. Testing Guidelines
- Write tests for both SharedArrayBuffer and fallback modes
- Use Jest for testing
- Include performance benchmarks for critical operations
### 8. Performance Considerations
- Use bulk operations when possible
- Monitor read/write performance
- Consider using transactions for multiple operations
- Avoid unnecessary database connections
### 9. Error Handling
- Implement proper error handling for:
- Worker initialization failures
- Database connection issues
- Concurrent access conflicts (in fallback mode)
- Storage quota exceeded scenarios
### 10. Security Best Practices
- Never expose database operations directly to the client
- Validate all SQL queries
- Implement proper access controls
- Handle sensitive data appropriately
### 11. Code Style
- Follow ESLint configuration
- Use async/await for asynchronous operations
- Document complex database operations
- Include comments for non-obvious optimizations
### 12. Debugging
- Use `jest-debug` for debugging tests
- Monitor IndexedDB usage in browser dev tools
- Check worker communication in console
- Use performance monitoring tools
## Common Patterns
### Worker Initialization
```javascript
// Main thread
import { initBackend } from 'absurd-sql/dist/indexeddb-main-thread';
function init() {
let worker = new Worker(new URL('./index.worker.js', import.meta.url));
initBackend(worker);
}
```
### Database Setup
```javascript
// Worker thread
import initSqlJs from '@jlongster/sql.js';
import { SQLiteFS } from 'absurd-sql';
import IndexedDBBackend from 'absurd-sql/dist/indexeddb-backend';
async function setupDatabase() {
let SQL = await initSqlJs({ locateFile: file => file });
let sqlFS = new SQLiteFS(SQL.FS, new IndexedDBBackend());
SQL.register_for_idb(sqlFS);
SQL.FS.mkdir('/sql');
SQL.FS.mount(sqlFS, {}, '/sql');
return new SQL.Database('/sql/db.sqlite', { filename: true });
}
```
## Troubleshooting
### Common Issues
1. SharedArrayBuffer not available
- Check COOP/COEP headers
- Verify browser support
- Test fallback mode
2. Worker initialization failures
- Check file paths
- Verify module imports
- Check browser console for errors
3. Performance issues
- Monitor IndexedDB usage
- Check for unnecessary operations
- Verify transaction usage
## Resources
- [Project Demo](https://priceless-keller-d097e5.netlify.app/)
- [Example Project](https://github.com/jlongster/absurd-example-project)
- [Blog Post](https://jlongster.com/future-sql-web)
- [SQL.js Documentation](https://github.com/sql-js/sql.js/)

View File

@@ -1,287 +0,0 @@
---
description:
globs:
alwaysApply: true
---
# TimeSafari Cross-Platform Architecture Guide
## 1. Platform Support Matrix
| Feature | Web (PWA) | Capacitor (Mobile) | Electron (Desktop) |
|---------|-----------|-------------------|-------------------|
| QR Code Scanning | WebInlineQRScanner | @capacitor-mlkit/barcode-scanning | Not Implemented |
| Deep Linking | URL Parameters | App URL Open Events | Not Implemented |
| File System | Limited (Browser API) | Capacitor Filesystem | Electron fs |
| Camera Access | MediaDevices API | Capacitor Camera | Not Implemented |
| Platform Detection | Web APIs | Capacitor.isNativePlatform() | process.env checks |
## 2. Project Structure
### 2.1 Core Directories
```
src/
├── components/ # Vue components
├── services/ # Platform services and business logic
├── views/ # Page components
├── router/ # Vue router configuration
├── types/ # TypeScript type definitions
├── utils/ # Utility functions
├── lib/ # Core libraries
├── platforms/ # Platform-specific implementations
├── electron/ # Electron-specific code
├── constants/ # Application constants
├── db/ # Database related code
├── interfaces/ # TypeScript interfaces and type definitions
└── assets/ # Static assets
```
### 2.2 Entry Points
```
src/
├── main.ts # Base entry
├── main.common.ts # Shared initialization
├── main.capacitor.ts # Mobile entry
├── main.electron.ts # Electron entry
└── main.web.ts # Web/PWA entry
```
### 2.3 Build Configurations
```
root/
├── vite.config.common.mts # Shared config
├── vite.config.capacitor.mts # Mobile build
├── vite.config.electron.mts # Electron build
└── vite.config.web.mts # Web/PWA build
```
## 3. Service Architecture
### 3.1 Service Organization
```
services/
├── QRScanner/ # QR code scanning service
│ ├── WebInlineQRScanner.ts
│ └── interfaces.ts
├── platforms/ # Platform-specific services
│ ├── WebPlatformService.ts
│ ├── CapacitorPlatformService.ts
│ └── ElectronPlatformService.ts
└── factory/ # Service factories
└── PlatformServiceFactory.ts
```
### 3.2 Service Factory Pattern
```typescript
// PlatformServiceFactory.ts
export class PlatformServiceFactory {
private static instance: PlatformService | null = null;
public static getInstance(): PlatformService {
if (!PlatformServiceFactory.instance) {
const platform = process.env.VITE_PLATFORM || "web";
PlatformServiceFactory.instance = createPlatformService(platform);
}
return PlatformServiceFactory.instance;
}
}
```
## 4. Feature Implementation Guidelines
### 4.1 QR Code Scanning
1. **Service Interface**
```typescript
interface QRScannerService {
checkPermissions(): Promise<boolean>;
requestPermissions(): Promise<boolean>;
isSupported(): Promise<boolean>;
startScan(): Promise<void>;
stopScan(): Promise<void>;
addListener(listener: ScanListener): void;
onStream(callback: (stream: MediaStream | null) => void): void;
cleanup(): Promise<void>;
}
```
2. **Platform-Specific Implementation**
```typescript
// WebInlineQRScanner.ts
export class WebInlineQRScanner implements QRScannerService {
private scanListener: ScanListener | null = null;
private isScanning = false;
private stream: MediaStream | null = null;
private events = new EventEmitter();
// Implementation of interface methods
}
```
### 4.2 Deep Linking
1. **URL Structure**
```typescript
// Format: timesafari://<route>[/<param>][?queryParam1=value1]
interface DeepLinkParams {
route: string;
params?: Record<string, string>;
query?: Record<string, string>;
}
```
2. **Platform Handlers**
```typescript
// Capacitor
App.addListener("appUrlOpen", handleDeepLink);
// Web
router.beforeEach((to, from, next) => {
handleWebDeepLink(to.query);
});
```
## 5. Build Process
### 5.1 Environment Configuration
```typescript
// vite.config.common.mts
export function createBuildConfig(mode: string) {
return {
define: {
'process.env.VITE_PLATFORM': JSON.stringify(mode),
// PWA is automatically enabled for web platforms via build configuration
__IS_MOBILE__: JSON.stringify(isCapacitor),
__USE_QR_READER__: JSON.stringify(!isCapacitor)
}
};
}
```
### 5.2 Platform-Specific Builds
```bash
# Build commands from package.json
"build:web": "vite build --config vite.config.web.mts",
"build:capacitor": "vite build --config vite.config.capacitor.mts",
"build:electron": "vite build --config vite.config.electron.mts"
```
## 6. Testing Strategy
### 6.1 Test Configuration
```typescript
// playwright.config-local.ts
const config: PlaywrightTestConfig = {
projects: [
{
name: 'web',
use: { browserName: 'chromium' }
},
{
name: 'mobile',
use: { ...devices['Pixel 5'] }
}
]
};
```
### 6.2 Platform-Specific Tests
```typescript
test('QR scanning works on mobile', async ({ page }) => {
test.skip(!process.env.MOBILE_TEST, 'Mobile-only test');
// Test implementation
});
```
## 7. Error Handling
### 7.1 Global Error Handler
```typescript
function setupGlobalErrorHandler(app: VueApp) {
app.config.errorHandler = (err, instance, info) => {
logger.error("[App Error]", {
error: err,
info,
component: instance?.$options.name
});
};
}
```
### 7.2 Platform-Specific Error Handling
```typescript
// API error handling for Capacitor
if (process.env.VITE_PLATFORM === 'capacitor') {
logger.error(`[Capacitor API Error] ${endpoint}:`, {
message: error.message,
status: error.response?.status
});
}
```
## 8. Best Practices
### 8.1 Code Organization
- Use platform-specific directories for unique implementations
- Share common code through service interfaces
- Implement feature detection before using platform capabilities
- Keep platform-specific code isolated in dedicated directories
- Use TypeScript interfaces for cross-platform compatibility
### 8.2 Platform Detection
```typescript
const platformService = PlatformServiceFactory.getInstance();
const capabilities = platformService.getCapabilities();
if (capabilities.hasCamera) {
// Implement camera features
}
```
### 8.3 Feature Implementation
1. Define platform-agnostic interface
2. Create platform-specific implementations
3. Use factory pattern for instantiation
4. Implement graceful fallbacks
5. Add comprehensive error handling
6. Use dependency injection for better testability
## 9. Dependency Management
### 9.1 Platform-Specific Dependencies
```json
{
"dependencies": {
"@capacitor/core": "^6.2.0",
"electron": "^33.2.1",
"vue": "^3.4.0"
}
}
```
### 9.2 Conditional Loading
```typescript
if (process.env.VITE_PLATFORM === 'capacitor') {
await import('@capacitor/core');
}
```
## 10. Security Considerations
### 10.1 Permission Handling
```typescript
async checkPermissions(): Promise<boolean> {
if (platformService.isCapacitor()) {
return await checkNativePermissions();
}
return await checkWebPermissions();
}
```
### 10.2 Data Storage
- Use secure storage mechanisms for sensitive data
- Implement proper encryption for stored data
- Follow platform-specific security guidelines
- Regular security audits and updates
This document should be updated as new features are added or platform-specific implementations change. Regular reviews ensure it remains current with the codebase.

View File

@@ -1,222 +0,0 @@
---
description:
globs:
alwaysApply: false
---
# Camera Implementation Documentation
## Overview
This document describes how camera functionality is implemented across the TimeSafari application. The application uses cameras for two main purposes:
1. QR Code scanning
2. Photo capture
## Components
### QRScannerDialog.vue
Primary component for QR code scanning in web browsers.
**Key Features:**
- Uses `qrcode-stream` for web-based QR scanning
- Supports both front and back cameras
- Provides real-time camera status feedback
- Implements error handling with user-friendly messages
- Includes camera switching functionality
**Camera Access Flow:**
1. Checks for camera API availability
2. Enumerates available video devices
3. Requests camera permissions
4. Initializes camera stream with preferred settings
5. Handles various error conditions with specific messages
### PhotoDialog.vue
Component for photo capture and selection.
**Key Features:**
- Cross-platform photo capture interface
- Image cropping capabilities
- File selection fallback
- Unified interface for different platforms
## Services
### QRScanner Services
#### WebDialogQRScanner
Web-based implementation of QR scanning.
**Key Methods:**
- `checkPermissions()`: Verifies camera permission status
- `requestPermissions()`: Requests camera access
- `isSupported()`: Checks for camera API support
- Handles various error conditions with specific messages
#### CapacitorQRScanner
Native implementation using Capacitor's MLKit.
**Key Features:**
- Uses `@capacitor-mlkit/barcode-scanning`
- Supports both front and back cameras
- Implements permission management
- Provides continuous scanning capability
### Platform Services
#### WebPlatformService
Web-specific implementation of platform features.
**Camera Capabilities:**
- Uses HTML5 file input with capture attribute
- Falls back to file selection if camera unavailable
- Processes captured images for consistent format
#### CapacitorPlatformService
Native implementation using Capacitor.
**Camera Features:**
- Uses `Camera.getPhoto()` for native camera access
- Supports image editing
- Configures high-quality image capture
- Handles base64 image processing
#### ElectronPlatformService
Desktop implementation (currently unimplemented).
**Status:**
- Camera functionality not yet implemented
- Planned to use Electron's media APIs
## Platform-Specific Considerations
### iOS
- Requires `NSCameraUsageDescription` in Info.plist
- Supports both front and back cameras
- Implements proper permission handling
### Android
- Requires camera permissions in manifest
- Supports both front and back cameras
- Handles permission requests through Capacitor
### Web
- Requires HTTPS for camera access
- Implements fallback mechanisms
- Handles browser compatibility issues
## Error Handling
### Common Error Scenarios
1. No camera found
2. Permission denied
3. Camera in use by another application
4. HTTPS required
5. Browser compatibility issues
### Error Response
- User-friendly error messages
- Troubleshooting tips
- Clear instructions for resolution
- Platform-specific guidance
## Security Considerations
### Permission Management
- Explicit permission requests
- Permission state tracking
- Graceful handling of denied permissions
### Data Handling
- Secure image processing
- Proper cleanup of camera resources
- No persistent storage of camera data
## Best Practices
### Camera Access
1. Always check for camera availability
2. Request permissions explicitly
3. Handle all error conditions
4. Provide clear user feedback
5. Implement proper cleanup
### Performance
1. Optimize camera resolution
2. Implement proper resource cleanup
3. Handle camera switching efficiently
4. Manage memory usage
### User Experience
1. Clear status indicators
2. Intuitive camera controls
3. Helpful error messages
4. Smooth camera switching
5. Responsive UI feedback
## Future Improvements
### Planned Enhancements
1. Implement Electron camera support
2. Add advanced camera features
3. Improve error handling
4. Enhance user feedback
5. Optimize performance
### Known Issues
1. Electron camera implementation pending
2. Some browser compatibility limitations
3. Platform-specific quirks to address
## Dependencies
### Key Packages
- `@capacitor-mlkit/barcode-scanning`
- `qrcode-stream`
- `vue-picture-cropper`
- Platform-specific camera APIs
## Testing
### Test Scenarios
1. Permission handling
2. Camera switching
3. Error conditions
4. Platform compatibility
5. Performance metrics
### Test Environment
- Multiple browsers
- iOS and Android devices
- Desktop platforms
- Various network conditions

View File

@@ -1,10 +0,0 @@
---
description: rules used while developing
globs:
alwaysApply: true
---
✅ use system date command to timestamp all interactions with accurate date and time
✅ python script files must always have a blank line at their end
✅ remove whitespace at the end of lines
✅ use npm run lint-fix to check for warnings
✅ do not use npm run dev let me handle running and supplying feedback

View File

@@ -1,14 +0,0 @@
---
alwaysApply: true
---
# Directive for Documentation Generation
1. Produce a **small, focused set of documents** rather than an overwhelming volume.
2. Ensure the content is **maintainable and worth preserving**, so that humans
are motivated to keep it up to date.
3. Prioritize **educational value**: the documents must clearly explain the
workings of the system.
4. Avoid **shallow, generic, or filler explanations** often found in
AI-generated documentation.
5. Aim for **clarity, depth, and usefulness**, so readers gain genuine understanding.
6. Always check the local system date to determine current date.

View File

@@ -1,6 +0,0 @@
---
description:
globs:
alwaysApply: true
---
All references in the codebase to Dexie apply only to migration from IndexedDb to Sqlite and will be deprecated in future versions.

View File

@@ -1,332 +0,0 @@
---
globs: *.md
alwaysApply: false
---
# Cursor Markdown Ruleset for TimeSafari Documentation
## Overview
This ruleset enforces consistent markdown formatting standards across all project
documentation, ensuring readability, maintainability, and compliance with
markdownlint best practices.
## General Formatting Standards
### Line Length
- **Maximum line length**: 80 characters
- **Exception**: Code blocks (JSON, shell, TypeScript, etc.) - no line length
enforcement
- **Rationale**: Ensures readability across different screen sizes and terminal
widths
### Blank Lines
- **Headings**: Must be surrounded by blank lines above and below
- **Lists**: Must be surrounded by blank lines above and below
- **Code blocks**: Must be surrounded by blank lines above and below
- **Maximum consecutive blank lines**: 1 (no multiple blank lines)
- **File start**: No blank lines at the beginning of the file
- **File end**: Single newline character at the end
### Whitespace
- **No trailing spaces**: Remove all trailing whitespace from lines
- **No tabs**: Use spaces for indentation
- **Consistent indentation**: 2 spaces for list items and nested content
## Heading Standards
### Format
- **Style**: ATX-style headings (`#`, `##`, `###`, etc.)
- **Case**: Title case for general headings
- **Code references**: Use backticks for file names and technical terms
- ✅ `### Current package.json Scripts`
- ❌ `### Current Package.json Scripts`
### Hierarchy
- **H1 (#)**: Document title only
- **H2 (##)**: Major sections
- **H3 (###)**: Subsections
- **H4 (####)**: Sub-subsections
- **H5+**: Avoid deeper nesting
## List Standards
### Unordered Lists
- **Marker**: Use `-` (hyphen) consistently
- **Indentation**: 2 spaces for nested items
- **Blank lines**: Surround lists with blank lines
### Ordered Lists
- **Format**: `1.`, `2.`, `3.` (sequential numbering)
- **Indentation**: 2 spaces for nested items
- **Blank lines**: Surround lists with blank lines
### Task Lists
- **Format**: `- [ ]` for incomplete, `- [x]` for complete
- **Use case**: Project planning, checklists, implementation tracking
## Code Block Standards
### Fenced Code Blocks
- **Syntax**: Triple backticks with language specification
- **Languages**: `json`, `bash`, `typescript`, `javascript`, `yaml`, `markdown`
- **Blank lines**: Must be surrounded by blank lines above and below
- **Line length**: No enforcement within code blocks
### Inline Code
- **Format**: Single backticks for inline code references
- **Use case**: File names, commands, variables, properties
## Special Content Standards
### JSON Examples
```json
{
"property": "value",
"nested": {
"property": "value"
}
}
```
### Shell Commands
```bash
# Command with comment
npm run build:web
# Multi-line command
VITE_GIT_HASH=`git log -1 --pretty=format:%h` \
vite build --config vite.config.web.mts
```
### TypeScript Examples
```typescript
// Function with JSDoc
/**
* Get environment configuration
* @param env - Environment name
* @returns Environment config object
*/
const getEnvironmentConfig = (env: string) => {
switch (env) {
case 'prod':
return { /* production settings */ };
default:
return { /* development settings */ };
}
};
```
## File Structure Standards
### Document Header
```markdown
# Document Title
**Author**: Matthew Raymer
**Date**: YYYY-MM-DD
**Status**: 🎯 **STATUS** - Brief description
## Overview
Brief description of the document's purpose and scope.
```
### Section Organization
1. **Overview/Introduction**
2. **Current State Analysis**
3. **Implementation Plan**
4. **Technical Details**
5. **Testing & Validation**
6. **Next Steps**
## Markdownlint Configuration
### Required Rules
```json
{
"MD013": { "code_blocks": false },
"MD012": true,
"MD022": true,
"MD031": true,
"MD032": true,
"MD047": true,
"MD009": true
}
```
### Rule Explanations
- **MD013**: Line length (disabled for code blocks)
- **MD012**: No multiple consecutive blank lines
- **MD022**: Headings should be surrounded by blank lines
- **MD031**: Fenced code blocks should be surrounded by blank lines
- **MD032**: Lists should be surrounded by blank lines
- **MD047**: Files should end with a single newline
- **MD009**: No trailing spaces
## Validation Commands
### Check Single File
```bash
npx markdownlint docs/filename.md
```
### Check All Documentation
```bash
npx markdownlint docs/
```
### Auto-fix Common Issues
```bash
# Remove trailing spaces
sed -i 's/[[:space:]]*$//' docs/filename.md
# Remove multiple blank lines
sed -i '/^$/N;/^\n$/D' docs/filename.md
# Add newline at end if missing
echo "" >> docs/filename.md
```
## Common Patterns
### Implementation Plans
```markdown
## Implementation Plan
### Phase 1: Foundation (Day 1)
#### 1.1 Component Setup
- [ ] Create new component file
- [ ] Add basic structure
- [ ] Implement core functionality
#### 1.2 Configuration
- [ ] Update configuration files
- [ ] Add environment variables
- [ ] Test configuration loading
```
### Status Tracking
```markdown
**Status**: ✅ **COMPLETE** - All phases finished
**Progress**: 75% (15/20 components)
**Next**: Ready for testing phase
```
### Performance Metrics
```markdown
#### 📊 Performance Metrics
- **Build Time**: 2.3 seconds (50% faster than baseline)
- **Bundle Size**: 1.2MB (30% reduction)
- **Success Rate**: 100% (no failures in 50 builds)
```
## Enforcement
### Pre-commit Hooks
- Run markdownlint on all changed markdown files
- Block commits with linting violations
- Auto-fix common issues when possible
### CI/CD Integration
- Include markdownlint in build pipeline
- Generate reports for documentation quality
- Fail builds with critical violations
### Team Guidelines
- All documentation PRs must pass markdownlint
- Use provided templates for new documents
- Follow established patterns for consistency
## Templates
### New Document Template
```markdown
# Document Title
**Author**: Matthew Raymer
**Date**: YYYY-MM-DD
**Status**: 🎯 **PLANNING** - Ready for Implementation
## Overview
Brief description of the document's purpose and scope.
## Current State
Description of current situation or problem.
## Implementation Plan
### Phase 1: Foundation
- [ ] Task 1
- [ ] Task 2
## Next Steps
1. **Review and approve plan**
2. **Begin implementation**
3. **Test and validate**
---
**Status**: Ready for implementation
**Priority**: Medium
**Estimated Effort**: X days
**Dependencies**: None
**Stakeholders**: Development team
```
---
**Last Updated**: 2025-07-09
**Version**: 1.0
**Maintainer**: Matthew Raymer
### Heading Uniqueness
- **Rule**: No duplicate heading content at the same level
- **Scope**: Within a single document
- **Rationale**: Maintains clear document structure and navigation
- **Example**:
```markdown
## Features ✅
### Authentication
### Authorization
## Features ❌ (Duplicate heading)
### Security
### Performance
```

View File

@@ -1,316 +0,0 @@
---
description:
globs:
alwaysApply: true
---
# Time Safari Context
## Project Overview
Time Safari is an application designed to foster community building through gifts,
gratitude, and collaborative projects. The app should make it extremely easy and
intuitive for users of any age and capability to recognize contributions, build
trust networks, and organize collective action. It is built on services that
preserve privacy and data sovereignty.
The ultimate goals of Time Safari are two-fold:
1. **Connect** Make it easy, rewarding, and non-threatening for people to
connect with others who have similar interests, and to initiate activities
together. This helps people accomplish and learn from other individuals in
less-structured environments; moreover, it helps them discover who they want
to continue to support and with whom they want to maintain relationships.
2. **Reveal** Widely advertise the great support and rewards that are being
given and accepted freely, especially non-monetary ones. Using visuals and text,
display the kind of impact that gifts are making in the lives of others. Also
show useful and engaging reports of project statistics and personal accomplishments.
## Core Approaches
Time Safari should help everyday users build meaningful connections and organize
collective efforts by:
1. **Recognizing Contributions**: Creating permanent, verifiable records of gifts
and contributions people give to each other and their communities.
2. **Facilitating Collaboration**: Making it ridiculously easy for people to ask
for or propose help on projects and interests that matter to them.
3. **Building Trust Networks**: Enabling users to maintain their network and activity
visibility. Developing reputation through verified contributions and references,
which can be selectively shown to others outside the network.
4. **Preserving Privacy**: Ensuring personal identifiers are only shared with
explicitly authorized contacts, allowing private individuals including children
to participate safely.
5. **Engaging Content**: Displaying people's records in compelling stories, and
highlighting those projects that are lifting people's lives long-term, both in
physical support and in emotional-spiritual-creative thriving.
## Technical Foundation
This application is built on a privacy-preserving claims architecture (via
endorser.ch) with these key characteristics:
- **Decentralized Identifiers (DIDs)**: User identities are based on public/private
key pairs stored on their devices
- **Cryptographic Verification**: All claims and confirmations are
cryptographically signed
- **User-Controlled Visibility**: Users explicitly control who can see their
identifiers and data
- **Merkle-Chained Claims**: Claims are cryptographically chained for verification
and integrity
- **Native and Web App**: Works on Capacitor (iOS, Android), Desktop (Electron
and CEFPython), and web browsers
## User Journey
The typical progression of usage follows these stages:
1. **Gratitude & Recognition**: Users begin by expressing and recording gratitude
for gifts received, building a foundation of acknowledgment.
2. **Project Proposals**: Users propose projects and ideas, reaching out to connect
with others who share similar interests.
3. **Action Triggers**: Offers of help serve as triggers and motivations to execute
proposed projects, moving from ideas to action.
## Context for LLM Development
When developing new functionality for Time Safari, consider these design principles:
1. **Accessibility First**: Features should be usable by non-technical users with
minimal learning curve.
2. **Privacy by Design**: All features must respect user privacy and data sovereignty.
3. **Progressive Enhancement**: Core functionality should work across all devices,
with richer experiences where supported.
4. **Voluntary Collaboration**: The system should enable but never coerce participation.
5. **Trust Building**: Features should help build verifiable trust between users.
6. **Network Effects**: Consider how features scale as more users join the platform.
7. **Low Resource Requirements**: The system should be lightweight enough to run
on inexpensive devices users already own.
## Use Cases to Support
LLM development should focus on enhancing these key use cases:
1. **Community Building**: Tools that help people find others with shared
interests and values.
2. **Project Coordination**: Features that make it easy to propose collaborative
projects and to submit suggestions and offers to existing ones.
3. **Reputation Building**: Methods for users to showcase their contributions
and reliability, in contexts where they explicitly reveal that information.
4. **Governance Experimentation**: Features that facilitate decision-making and
collective governance.
## Constraints
When developing new features, be mindful of these constraints:
1. **Privacy Preservation**: User identifiers must remain private except when
explicitly shared.
2. **Platform Limitations**: Features must work within the constraints of the target
app platforms, while aiming to leverage the best platform technology available.
3. **Endorser API Limitations**: Backend features are constrained by the endorser.ch
API capabilities.
4. **Performance on Low-End Devices**: The application should remain performant
on older/simpler devices.
5. **Offline-First When Possible**: Key functionality should work offline when feasible.
## Project Technologies
- Typescript using ES6 classes using vue-facing-decorator
- TailwindCSS
- Vite Build Tool
- Playwright E2E testing
- IndexDB
- Camera, Image uploads, QR Code reader, ...
## Mobile Features
- Deep Linking
- Local Notifications via a custom Capacitor plugin
## Project Architecture
- The application must work on web browser, PWA (Progressive Web Application),
desktop via Electron, and mobile via Capacitor
- Building for each platform is managed via Vite
## Core Development Principles
### DRY development
- **Code Reuse**
- Extract common functionality into utility functions
- Create reusable components for UI patterns
- Implement service classes for shared business logic
- Use mixins for cross-cutting concerns
- Leverage TypeScript interfaces for shared type definitions
- **Component Patterns**
- Create base components for common UI elements
- Implement higher-order components for shared behavior
- Use slot patterns for flexible component composition
- Create composable services for business logic
- Implement factory patterns for component creation
- **State Management**
- Centralize state in Pinia stores
- Use computed properties for derived state
- Implement shared state selectors
- Create reusable state mutations
- Use action creators for common operations
- **Error Handling**
- Implement centralized error handling
- Create reusable error components
- Use error boundary components
- Implement consistent error logging
- Create error type definitions
- **Type Definitions**
- Create shared interfaces for common data structures
- Use type aliases for complex types
- Implement generic types for reusable components
- Create utility types for common patterns
- Use discriminated unions for state management
- **API Integration**
- Create reusable API client classes
- Implement request/response interceptors
- Use consistent error handling patterns
- Create type-safe API endpoints
- Implement caching strategies
- **Platform Services**
- Abstract platform-specific code behind interfaces
- Create platform-agnostic service layers
- Implement feature detection
- Use dependency injection for services
- Create service factories
- **Testing**
- Create reusable test utilities
- Implement test factories
- Use shared test configurations
- Create reusable test helpers
- Implement consistent test patterns
- F.I.R.S.T. (for Unit Tests)
F Fast
I Independent
R Repeatable
S Self-validating
T Timely
### SOLID Principles
- **Single Responsibility**: Each class/component should have only one reason to
change
- Components should focus on one specific feature (e.g., QR scanning, DID management)
- Services should handle one type of functionality (e.g., platform services,
crypto services)
- Utilities should provide focused helper functions
- **Open/Closed**: Software entities should be open for extension but closed for
modification
- Use interfaces for service definitions
- Implement plugin architecture for platform-specific features
- Allow component behavior extension through props and events
- **Liskov Substitution**: Objects should be replaceable with their subtypes
- Platform services should work consistently across web/mobile
- Authentication providers should be interchangeable
- Storage implementations should be swappable
- **Interface Segregation**: Clients shouldn't depend on interfaces they don't use
- Break down large service interfaces into smaller, focused ones
- Component props should be minimal and purposeful
- Event emissions should be specific and targeted
- **Dependency Inversion**: High-level modules shouldn't depend on low-level modules
- Use dependency injection for services
- Abstract platform-specific code behind interfaces
- Implement factory patterns for component creation
### Law of Demeter
- Components should only communicate with immediate dependencies
- Avoid chaining method calls (e.g., `this.service.getUser().getProfile().getName()`)
- Use mediator patterns for complex component interactions
- Implement facade patterns for subsystem access
- Keep component communication through defined events and props
### Composition over Inheritance
- Prefer building components through composition
- Use mixins for shared functionality
- Implement feature toggles through props
- Create higher-order components for common patterns
- Use service composition for complex features
### Interface Segregation
- Define clear interfaces for services
- Keep component APIs minimal and focused
- Split large interfaces into smaller, specific ones
- Use TypeScript interfaces for type definitions
- Implement role-based interfaces for different use cases
### Fail Fast
- Validate inputs early in the process
- Use TypeScript strict mode
- Implement comprehensive error handling
- Add runtime checks for critical operations
- Use assertions for development-time validation
### Principle of Least Astonishment
- Follow Vue.js conventions consistently
- Use familiar naming patterns
- Implement predictable component behaviors
- Maintain consistent error handling
- Keep UI interactions intuitive
### Information Hiding
- Encapsulate implementation details
- Use private class members
- Implement proper access modifiers
- Hide complex logic behind simple interfaces
- Use TypeScript's access modifiers effectively
### Single Source of Truth
- Use Pinia for state management
- Maintain one source for user data
- Centralize configuration management
- Use computed properties for derived state
- Implement proper state synchronization
### Principle of Least Privilege
- Implement proper access control
- Use minimal required permissions
- Follow privacy-by-design principles
- Restrict component access to necessary data
- Implement proper authentication/authorization

View File

@@ -1,122 +0,0 @@
---
alwaysApply: true
---
# Directive: Peaceful Co-Existence with Developers
## 1) Version-Control Ownership
* **MUST NOT** run `git add`, `git commit`, or any write action.
* **MUST** leave staging/committing to the developer.
## 2) Source of Truth for Commit Text
* **MUST** derive messages **only** from:
* files **staged** for commit (primary), and
* files **awaiting staging** (context).
* **MUST** use the **diffs** to inform content.
* **MUST NOT** invent changes or imply work not present in diffs.
## 3) Mandatory Preview Flow
* **ALWAYS** present, before any real commit:
* file list + brief per-file notes,
* a **draft commit message** (copy-paste ready),
* nothing auto-applied.
---
# Commit Message Format (Normative)
## A. Subject Line (required)
```
<type>(<scope>)<!>: <summary>
```
* **type** (lowercase, Conventional Commits): `feat|fix|refactor|perf|docs|test|build|chore|ci|revert`
* **scope**: optional module/package/area (e.g., `api`, `ui/login`, `db`)
* **!**: include when a breaking change is introduced
* **summary**: imperative mood, ≤ 72 chars, no trailing period
**Examples**
* `fix(api): handle null token in refresh path`
* `feat(ui/login)!: require OTP after 3 failed attempts`
## B. Body (optional, when it adds non-obvious value)
* One blank line after subject.
* Wrap at \~72 chars.
* Explain **what** and **why**, not line-by-line “how”.
* Include brief notes like tests passing or TS/lint issues resolved **only if material**.
**Body checklist**
* [ ] Problem/symptom being addressed
* [ ] High-level approach or rationale
* [ ] Risks, tradeoffs, or follow-ups (if any)
## C. Footer (optional)
* Issue refs: `Closes #123`, `Refs #456`
* Breaking change (alternative to `!`):
`BREAKING CHANGE: <impact + migration note>`
* Authors: `Co-authored-by: Name <email>`
* Security: `CVE-XXXX-YYYY: <short note>` (if applicable)
---
## Content Guidance
### Include (when relevant)
* Specific fixes/features delivered
* Symptoms/problems fixed
* Brief note that tests passed or TS/lint errors resolved
### Avoid
* Vague: *improved, enhanced, better*
* Trivialities: tiny docs, one-liners, pure lint cleanups (separate, focused commits if needed)
* Redundancy: generic blurbs repeated across files
* Multi-purpose dumps: keep commits **narrow and focused**
* Long explanations that good inline code comments already cover
**Guiding Principle:** Let code and inline docs speak. Use commits to highlight what isnt obvious.
---
# Copy-Paste Templates
## Minimal (no body)
```text
<type>(<scope>): <summary>
```
## Standard (with body & footer)
```text
<type>(<scope>)<!>: <summary>
<why-this-change?>
<what-it-does?>
<risks-or-follow-ups?>
Closes #<id>
BREAKING CHANGE: <impact + migration>
Co-authored-by: <Name> <email>
```
---
# Assistant Output Checklist (before showing the draft)
* [ ] List changed files + 12 line notes per file
* [ ] Provide **one** focused draft message (subject/body/footer)
* [ ] Subject ≤ 72 chars, imperative mood, correct `type(scope)!` syntax
* [ ] Body only if it adds non-obvious value
* [ ] No invented changes; aligns strictly with diffs
* [ ] Render as a single copy-paste block for the developer

View File

@@ -1,171 +0,0 @@
# TimeSafari Docker Ignore File
# Author: Matthew Raymer
# Description: Excludes unnecessary files from Docker build context
#
# Benefits:
# - Faster build times
# - Smaller build context
# - Reduced image size
# - Better security (excludes sensitive files)
# Dependencies
node_modules
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Build outputs
# dist - Allow dist directory for Docker builds (contains pre-built assets)
dist-*
build
*.tsbuildinfo
# Development files
.git
.gitignore
README.md
CHANGELOG.md
CONTRIBUTING.md
BUILDING.md
LICENSE
# IDE and editor files
.vscode
.idea
*.swp
*.swo
*~
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Dependency directories
jspm_packages/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# Test files
test-playwright
test-playwright-results
test-results
test-scripts
# Documentation
doc
# Scripts (keep only what's needed for build)
scripts/test-*.sh
scripts/*.js
scripts/README.md
# Platform-specific files
android
ios
electron
# Docker files (avoid recursive copying)
Dockerfile*
docker-compose*
.dockerignore
# CI/CD files
.github
.gitlab-ci.yml
.travis.yml
.circleci
# Temporary files
tmp
temp
# Backup files
*.bak
*.backup
# Archive files
*.tar
*.tar.gz
*.zip
*.rar
# Certificate files
*.pem
*.key
*.crt
*.p12
# Configuration files that might contain secrets
*.secrets
secrets.json
config.local.json

View File

@@ -1,14 +0,0 @@
# Only the variables that start with VITE_ are seen in the application import.meta.env in Vue.
# iOS doesn't like spaces in the app title.
TIME_SAFARI_APP_TITLE="TimeSafari_Dev"
VITE_APP_SERVER=http://localhost:8080
# This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not production).
VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F
VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000
# Using shared server by default to ease setup, which works for shared test users.
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=http://localhost:3000
#VITE_DEFAULT_PUSH_SERVER... can't be set up with localhost domain
VITE_PASSKEYS_ENABLED=true

View File

@@ -1,12 +0,0 @@
# Only the variables that start with VITE_ are seen in the application import.meta.env in Vue.
VITE_APP_SERVER=https://timesafari.app
# This is the claim ID for actions in the BVC project.
VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01GXYPFF7FA03NXKPYY142PY4H
VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://timesafari.app

View File

@@ -1,13 +0,0 @@
# Only the variables that start with VITE_ are seen in the application import.meta.env in Vue.
# iOS doesn't like spaces in the app title.
TIME_SAFARI_APP_TITLE="TimeSafari_Test"
VITE_APP_SERVER=https://test.timesafari.app
# This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not production).
VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F
VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://test.timesafari.app
VITE_PASSKEYS_ENABLED=true

View File

@@ -2,37 +2,18 @@ module.exports = {
root: true,
env: {
node: true,
es2022: true,
},
ignorePatterns: [
'node_modules/',
'dist/',
'dist-electron/',
'*.d.ts'
],
extends: [
"plugin:vue/vue3-recommended",
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/typescript/recommended",
"plugin:prettier/recommended"
"plugin:prettier/recommended",
],
// parserOptions: {
// ecmaVersion: 2020,
// },
parserOptions: {
ecmaVersion: 2020,
},
rules: {
"max-len": ["warn", {
code: 100,
ignoreComments: true,
ignorePattern: '^\\s*class="[^"]*"$',
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreUrls: true,
}],
"no-console": process.env.NODE_ENV === "production" ? "error" : "warn",
"no-debugger": process.env.NODE_ENV === "production" ? "error" : "warn",
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-unnecessary-type-constraint": "off",
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }]
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
},
};

View File

@@ -1,27 +0,0 @@
name: Playwright Tests
on:
push:
branches: [ main, master ]
pull_request:
branches: [ main, master ]
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: lts/*
- name: Install dependencies
run: npm ci
- name: Install Playwright Browsers
run: npx playwright install --with-deps
- name: Run Playwright tests
run: npx playwright test
- uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: playwright-report/
retention-days: 30

112
.gitignore vendored
View File

@@ -1,22 +1,13 @@
squashfs-root
dist-electron
dist-electon-build
.DS_Store
node_modules
dist
signature.bin
# generated during `npm run build`
sw_scripts-combined.js
*.pem
verified.txt
myenv
/dist
*~
# local env files
.env.local
.env.*.local
# Log filesopenssl dgst -sha256 -verify public.pem -signature <(echo -n "$signature") "$signing_input"
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
@@ -30,102 +21,3 @@ pnpm-debug.log*
*.njsproj
*.sln
*.sw?
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
/dist-electron-build/
/dist-capacitor/
/test-playwright-results/
playwright-tests
dist-electron-packages
.ruby-version
+.env
# Test files generated by scripts test-ios.js & test-android.js
.generated/
.env.default
vendor/
# Build logs
build_logs/
# PWA icon files generated by capacitor-assets
icons
*.log
# Generated Android assets and resources (should be generated during build)
android/app/src/main/assets/public/
# Generated Android resources (icons, splash screens, etc.)
android/app/src/main/res/drawable*/
android/app/src/main/res/mipmap*/
android/app/src/main/res/values/ic_launcher_background.xml
# Keep these Android configuration files in version control:
# - android/app/src/main/assets/capacitor.plugins.json
# - android/app/src/main/res/values/strings.xml
# - android/app/src/main/res/values/styles.xml
# - android/app/src/main/res/layout/activity_main.xml
# - android/app/src/main/res/xml/config.xml
# - android/app/src/main/res/xml/file_paths.xml
sql-wasm.wasm
# Temporary and generated files
temp.*
*.tmp
*.temp
*.bak
*.cache
git.diff.*
*.har
# Development artifacts
dev-dist/
*.map
# OS generated files
Thumbs.db
ehthumbs.db
Desktop.ini
# Capacitor build outputs and generated files
android/app/build/
android/capacitor-cordova-android-plugins/build/
ios/App/App/public/assets/
ios/App/App/build/
ios/App/build/
# Capacitor build artifacts (covered by android/app/build/ above)
# Keep these Capacitor files in version control:
# - capacitor.config.json (root, electron, ios)
# - src/main.capacitor.ts
# - vite.config.capacitor.mts
# - android/capacitor.settings.gradle
# - android/app/capacitor.build.gradle
# - android/app/src/main/assets/capacitor.plugins.json
# Electron build outputs and generated files
electron/build/
electron/app/
electron/dist/
electron/out/
# Keep these Electron files in version control:
# - electron/src/preload.ts (source)
# - electron/src/index.ts (source)
# - electron/src/setup.ts (source)
# - electron/package.json
# - electron/electron-builder.config.json
# - electron/build-packages.sh
# - electron/live-runner.js
# - electron/resources/electron-publisher-custom.js
# Gradle cache files
android/.gradle/file-system.probe
android/.gradle/caches/
coverage

View File

@@ -1 +0,0 @@
{"MD013": {"code_blocks": false}}

1
.npmrc
View File

@@ -1 +0,0 @@
@jsr:registry=https://npm.jsr.io

File diff suppressed because it is too large Load Diff

View File

@@ -1,787 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.0.3] - 2025.07.12
### Changed
- Photo is pinned to profile mode
### Fixed
- Deep link URLs (and other prod settings)
- Error in BVC begin view
## [1.0.6] - 2025.08.09
### Fixed
- Deep link errors where none would validate
## [1.0.5] - 2025.07.24
### Fixed
- Export & import of contacts corrupted contact methods
## [1.0.4] - 2025.07.20 - 002f2407208d56cc59c0aa7c880535ae4cbace8b
### Fixed
- Deep link for invite-one-accept
## [1.0.3] - 2025.07.12 - a9a8ba217cd6015321911e98e6843e988dc2c4ae
### Changed
- Photo is pinned to profile mode
### Fixed
- Deep link URLs (and other prod settings)
- Error in BVC begin view
## [1.0.2] - 2025.06.20 - 276e0a741bc327de3380c4e508cccb7fee58c06d
### Added
- Version on feed title
## [1.0.1] - 2025.06.20
### Added
- Allow a user to block someone else's content from view
## [1.0.0] - 2025.06.20 - 5aa693de6337e5dbb278bfddc6bd39094bc14f73
### Added
- Web-oriented migration from IndexedDB to SQLite
## [0.5.8]
### Added
- /deep-link/ path for URLs that are shared with people
### Changed
- External links now go to /deep-link/...
- Feed visuals now have arrow imagery from giver to receiver
## [0.4.7]
### Fixed
- Cameras everywhere
### Changed
- IndexedDB -> SQLite
## [0.4.5] - 2025.02.23
### Added
- Total amounts of gives on project page
### Changed in DB or environment
- Requires Endorser.ch version 4.2.6+
## [0.4.4] - 2025.02.17
### Fixed in 0.4.4
- On production (due to data?) the search results would disappear after scrolling down. Now we don't show any results when going to the people map with a shortcut.
## [0.4.3] - 2025.02.17
### Added in 0.4.3
- Discover query parameter searchPeople to go directly to the people map
## [0.4.2] - 2025.02.17
### Added
- Capacitor on iOS and Android
### Fixed
- Path issues
## [0.4.1] - 2025.02.16
### Fixed in 0.4.1
- nostr build issue
- Linting
## [0.4.0] - 2025.02.14
### Changed
- Images in the home feed now take up the full width of the card.
- Clicking the image previously, would open the image in a new tab. Now, clicking the image opens the image in a lightbox view.
### Added in 0.4.0
- Clicking an image also now displays an in-app lightbox view of the image.
- The lightbox view includes a download button for the image in mobile view.
## [0.3.57] - 2025.02.11
### Added in 0.3.57
- Automatic user creation in onboarding meetings
## [0.3.55] - 2025.02.07
### Added in 0.3.55
- End time for projects
## [0.3.54] - 2025.02.06
### Added in 0.3.54
- Group onboarding meetings
## [0.3.53] - 2025.01.30
### Added in 0.3.53
- Hints for contacting the creator of a project
## [0.3.52] - 2025.01.22
### Fixed in 0.3.52
- User profile endpoint server for map was broken.
## [0.3.51] - 2025.01.22
### Fixed in 0.3.51
- User profile map jumped on first zoom.
## [0.3.50] - 2025.01.20 - b9fedcd3fd3e34c3fb0fc79150d1a81a76eaeb40
### Added in 0.3.50
- User public profiles
## [0.3.49] - 2025.01.09 - 36301ed238ff84df25bb11a8d44a295ee7eaf0f8
### Changed in 0.3.49
- Make all external contact links direct to the contact-import page.
- Handle all new-single-contact JWTs in the contacts page, and multiple-contact JWTs in the contacts-import page.
## [0.3.48] - 2025.01.08 - 398f3e64a376789f7eb1c400cd886f5a2cacd588 (but app shows 07c4e58)
### Added in 0.3.48
- More sanity-checks on contact-import JWT
## [0.3.47] - 2025.01.06 - 5bf6dd1ee32ca7cc46d39bd7afca58365b422f93
### Added in 0.3.47
- Notes on contacts page with new contact-edit page
- Contact methods (only on contact-edit page and under DID details)
- DID view with no DID shows user's info.
### Changed in 0.3.47
- URL for user's contact info is now URL to this app (not endorser.ch).
- Extended details (eg. full claim) is beneath details link on claim page.
## [0.3.46] - 2025.01.03 - 9e7056616b5e5acc51e5a8cf7354d408029fefb3
### Added in 0.3.46
- More action-oriented questions for the gift prompts
### Fixed in 0.3.46
- Contact-list import set visibility for all, even if not chosen.
## [0.3.45] - 2025.01.01 - 65402dc68ce69ccc6cb9aa8d2e7a9249bf4298e0
### Fixed in 0.3.45
- Previous project links stayed when following a link.
## [0.3.44] - 2024.12.31 - 694b22987b05482e4527c2478bbe15e6b6f3b532
### Added in 0.3.44
- Project counts on a map
## [0.3.42] - 2024.12.27 - 9751934bc24a1040415a8cfeacbae59ed91f92a5
### Added in 0.3.42
- Link from certificate page to the claim
### Changed in 0.3.42
- Contact data sharing is now a verified JWT.
- Feed pictures are larger.
## [0.3.41] - 2024.12.21 - ff6d14138f26daea6216b051562f0a04681f69fc
### Added in 0.3.41
- Link from certificate page to the claim
## [0.3.40] - 2024.12.20 - 77290d9fed3c364243793dc3e9bfe2e994a016b8
### Added in 0.3.40
- Only show issuer on certificate if it's not the agent.
## [0.3.39] - 2024.12.20 - d8819155e2acd2b57fdab523168fa5d1d09e80cc
### Added in 0.3.39
- Page for a framed claim certificate
## [0.3.38] - 2024.12.14 - f8cae5ad4fee1f114320dcce052299eab12108b2
### Fixed in 0.3.38
- Error on BVC confirmation screen (from IndexedDB refactor)
## [0.3.37] - 2024.12.13 - 4d805b43cd25eed73cdd6651f36ad1ec8c109555
### Added in 0.3.37
- Record a give from a project on the project page.
- New button on home page opens the gifted dialog.
- On confirmation buttons on the project page gives, mark when unavailable and explain why.
### Changed in 0.3.37
- Moved the secret into IndexedDB (and out of localStorage) for more reliability.
- New "invite" destination page helps troubleshoot when JWT link doesn't come through.
### Fixed in 0.3.37
- Problem showing claim issuer name
- Problem going "back" from a project page
## [0.3.36] - 2024.11.24 - c8d23647d165016f8a8f575e13d32583242e53ac
### Changed in 0.3.36
- More friendly default reminder message
- Blue borders around people to indicate clickability
## [0.3.35] - 2024.11.24 - bff7d0a6320b70349185e26bfac72e3bb17f76df
### Added in 0.3.35
- Daily reliable, hard-coded notification message
- Setting to change the partner API server
## [0.3.33] - 2024.11.07 - adb7b16ecf1343c39cba71a7d6bb0e7a973e1102
### Fixed in 0.3.33
- Affirm Delivery button on offer claim page didn't work.
- Plans were not showing by default on project page.
## [0.3.32] - 2024.11.06 - 9a3fa38a3fd28f977e06f0265fc39e635c9c5ccd
### Added in 0.3.32
- Highlight in green new offers to user & to user's projects on the front page.
## [0.3.31] - 2024.10.25 - 07c02ab98a09d293dd90d9289a7872e7d681d296
### Changed in 0.3.31
- Onboarding messages about offers
## [0.3.30]
### Added in 0.3.30
- Onboarding messages
## [0.3.29] - 2024.10.09 - babd3832bdfe0c40eaa3869de1b41399a51713c1
### Added in 0.3.29
- Invite for a contact to join immediately
### Changed in 0.3.29
- Send signed data to nostr endpoints to verify public key ownership.
- Enhanced help & help onboarding.
### Changed in DB or environment
- Uses Endorser.ch version 4.1.1
## [0.3.28] - 2024.09.30 - 84720b94049d29cc0ddd99c50cef2e7176130133
### Added in 0.3.28
- Posting to nostr apps Trustroots & TripHopping
- Display of providers on claim view page
### Changed in 0.3.28
- Switched BVC-meeting-ending gift to be a gift from the group.
### Changed in DB or environment in 0.3.28
- Requires Endorser.ch version 4.1.0
## [0.3.27] - 2024.09.22 - ee23e6f005e47f5bd6f04d804599f6395371b0e4
### Fixed in 0.3.27
- Error loading BVC claims to confirm
- Really allow visibility of bulk-imported contacts
## [0.3.26] - 2024.09.16 - 8263ed2b29947b3ccc6f3133bbc9454c222bce28
### Added in 0.3.26
- Separate 'isRegistered' flag for each account
### Fixed in 0.3.26
- Failure to assign offers to their project
- Alert when looking at one's own activity if not in contacts.
## [0.3.25] - 2024.08.30 - dcbe02d877aecb4cdef2643d90e6595d246a9f82
### Added in 0.3.25
- "Ideas" now jumps directly to giving prompt or contact list.
### Fixed in 0.3.25
- Empty giver name on gifted-details view
- Previously visited project would show up on the giving-details page.
### Removed in 0.3.25
- All unnecessary localStorage for project IDs
## [0.3.23] - 2024.08.30
### Added in 0.3.23
- Sections in Help for different kinds of users
- Discovery page parameters so that links with search text work
- Message when no projects are found
## [0.3.21] - 2024.08.24 - a7b89f4bb6da928d56daeffaae7741fa74cc80bf
### Added in 0.3.21
- Send list of contacts to someone, and move individual contact actions to detail page.
- Prompt for name in pop-up, and send to different contact-sharing screens.
### Changed in 0.3.21
- Moved contact actions from list onto detail page
## [0.3.20] - 2024.08.18 - 4064eb75a9743ca268bf00016fa0a5fc5dec4e30
### Fixed in 0.3.20
- Bad "give" verbiage on offer page
- Failing offer test
## [0.3.19] - 2024.08.18 - ee9c14942ceba993bf21a11249601f205158ec71
### Added in 0.3.19
- Update of an offer
- Recipient description in offer list
### Fixed in 0.3.19
- List of offers wasn't showing.
- Destination page after sharing photo was wrong.
## [0.3.17] - 2024.07.11 - cefa384ff1a2d922848c370640c096c529920fab
### Added in 0.3.17
- Photos on more screens
### Fixed in 0.3.17
- Share of a photo, including sharing a photo from webkit/Safari which never worked
### Changed in DB or environment in 0.3.17
- Nothing (though there's a new temp field in IndexedDB)
## [0.3.15] - 2024.08.04 - c8f0f2c2b16b9f0b4b47d40f7bf29058c7baa68e
### Added in 0.3.15
- Edit gives
- Page to edit claim JSON before submitting
- Update of imported contacts
- Improve messaging on give dialog
- Section for gives provided by plan
- Deletion of an identity
- UI for choosing a passkey creation (not enabled on prod)
- Cache signatures for reports for passkey-signed requests
- Refactor: consolidate alternative signing, eg. for passkeys & did:peer
- Playwright tests
### Changed in 0.3.15
- Linked projects display below description (instead of at bottom)
### Fixed in 0.3.15
- Visibility toggle appearance
### Changed in DB or environment in 0.3.15
- Nothing
## [0.3.14] - 2024.06.22 - 1611d22892f683f43856d2503eee7f391b6bbce8
### Added in 0.3.14
- Clearer give-confirmation screen
- BX currency <https://thebx.medium.com/>
- Deselection of project on gifted details page
### Fixed in 0.3.14
- Don't show registration pop-up for a new contact that is registered
### Changed in DB or environment in 0.3.14
- Nothing
## [0.3.13] - 2024.05.24 - 08b67984e443c58d9178ad3776013b0bce7afddc
### Added in 0.3.13
- Photos on projects
### Changed in DB or environment in 0.3.13
- Nothing
## [0.3.12] - 2024.05.19 - 141fb39ad19c44d82fe1a33bf85115beacf50870
### Fixed in 0.3.12
- Photo share (share_target) failed because requests were sent to server
### Changed in DB or environment in 0.3.12
- Nothing
## [0.3.11] - 2024.05.19 - 567bcad88dfb7e9ac8fea72530d1163985e4a7cc
### Added in 0.3.11
- Choose a file for gifts, and a URL for gifts & profiles
### Fixed in 0.3.11
- Multiple button pushes were required to switch camera
### Changed in DB or environment in 0.3.11
- Nothing
## [0.3.10] - 2024.05.11 - 03ac31d98110f7828cf9acb366db8d01b185f64c
### Added in 0.3.10
- Share an image
- Choose a file on the device for a profile image
### Changed in DB or environment in 0.3.10
- Nothing
## [0.3.9] - 2024.04.28 - 874e717e698b93a1ace9f588e675b8a3dccd7617
### Added in 0.3.9
- Offers on contacts page
- Checks on front page until they show as registered
### Changed in 0.3.9
- Scanned contacts now add immediately and prompt for registration.
- Better UI for gives on contact page
- Better UI for all confirmation messages
### Fixed in 0.3.9
- Repeated elements at top of main feed
### Changed in DB or environment in 0.3.9
- Nothing
## [0.3.8] - 2024.04.20 - 15c026c80ce03a26cae3ff80b0888934c101c7e2
### Added in 0.3.8
- Profile image for user
### Fixed in 0.3.8
- Slow loading of home page feed
### Changed in DB or environment in 0.3.8
- Nothing
## [0.3.7] - 2024.04.10 - cf18f1543a700d62a5f9e764905a4aafe1fb229b
### Added in 0.3.7
- Filter on home page feed
- Ability to set time of daily notification
- Jump to app on click of notification
### Changed in 0.3.7
- Built with vite
- Descriptions on home page to include projects
### Changed in DB or environment in 0.3.7
- Nothing
## [0.3.6] - 2024.03.24 - 3a07e31d6313ab95711265562d9023c42916e141
### Added in 0.3.6
- Button to mirror photo during video
- More detailed onboarding help screen
- Public-data blurb
### Changed in DB or environment in 0.3.6
- Nothing
## [0.3.5] - 2024.03.23 - 28754bdfb1e11aa221dd49a5dce4219b69cf6a9d
### Added in 0.3.5
- Photo on gift records
### Fixed in 0.3.5
- Environment variable for BVC meetings project
- Environment variables and build enhancements for test vs prod
### Changed in DB or environment in 0.3.5
- New environment variable for image API server
- Test that a new browser session will get the right default APIs.
- Test that a new browser session will send the right BVC meetings project.
## [0.2.17] - 2024.03.01 - 3612ea42240c5e1b7d7eff29a39ff18f1b869b36
### Added in 0.2.17
- Shortcut page for Bountiful Voluntaryist Community
### Changed in 0.2.17
- More readable, targeted summaries in home-page feed items
### Changed in DB
- Nothing
## [0.2.14] - 2024.02.14 - 5f9edea1167dbfb64e16648764eed8c09b24eaeb
### Changed in 0.2.14
- Combine all service worker scripts into a single file.
### Changed in DB in 0.2.14
- Nothing
## [0.2.13] - 2024.02.07
### Added in 0.2.13
- Display of user's offers
- Check for valid DIDs
### Fixed in 0.2.13
- Name display on give prompt
- Non-numbers on number input & autocapitalize on URL input
### Changed in DB in 0.2.13
- Nothing
## [0.2.12] - 2024.02.01
### Added in 0.2.12
- Prompts for gratitude
## [0.2.11] - 2024.01.28
### Added in 0.2.11
- Actions to share claim data with contacts
- Bulk CSV import from Endorser Mobile export
- Dates on give summaries
## [0.2.10] - 2024.01.18 - 667e1e8890b42de59cd939caca1a01c7a7a702be
### Added in 0.2.10
- Person identicons for contacts
- Confirmation & delivery directly from project page
- Offer dialog now allows units
- Links from claim detail page to the fulfilled project or offer
- Link to project from home feed
- Copy to clipboard in more places
### Fixed in 0.2.10
- "More Contacts" for give on project page now links correctly.
## [0.2.9] - 2024.01.15 - e5e702f8a5a53a6efbed48d35f0bc3cee63024a0
### Fixed in 0.2.9
- Set visibility for new contact.
## [0.2.8] - 2024.01.14
### Added in 0.2.8
- Automatic ID creation from home page
- Agent who can also edit a project
### Fixed in 0.2.8
- Cannot declare anonymous gift
## [0.2.7] - 2024.01.12
### Added in 0.2.7
- Give to fulfill a particular offer
- Give as part of a trade as opposed to a donation
- Error notifications on import
### Changed in 0.2.7
- Library security updates
- Visibility of actions & confirmations on claim page
### Fixed in 0.2.7
- Name of offerer
## [0.2.2] - 2024.01.05
### Added in 0.2.2
- Check for notification capability on front screen
- Contact next-public-key-hash in manual textual input
- Confirmation for contact visibility change
- YAML rendering of full claim details
- Hints for onboarding on the contact screen
## [0.2.0] - 2024.01.04
### Added in 0.2.0
- Contact next-public-key-hash
- Icon for Android
- More thorough messaging and testing for notifications
## [0.1.9] - 2024.01.01
### Added in 0.1.9
- Import for contacts and settings
- Second download button for DuckDuckGo
### Changed in 0.1.9
- Removed some keys from Dexie's IndexedDB declarations
## [0.1.8] - 2023.12.27- d26d1d360152a7d0e559b68486e85b72b88bd9ff
### Added in 0.1.8
- DB logging for service-worker events
- Help page for notifications
- Test notification & web-push triggers inside app
- Check that the app is installed
### Fixed in 0.1.8
- Project issuer display name
## [0.1.7] - 2023.12.19 - 91c6c7c11c71f96006cc876fc946f1f98a274ba2
### Changed in 0.1.7
- Icons
### Fixed in 0.1.7
- Notification switch now shows message
- Prod/test server warning message at top of page
## [0.1.6] - 2023.12.17 - b445b1234fbfcf6b37d695373f259aab0eda1118
### Added in 0.1.6
- Infinite scroll on home page
### Changed in 0.1.6
- UI improvements
- Show web-push subscription info
- Icon
## [0.1.5] - 2023.12.09 - 9c36bb509a9bae9bb3306d3bd9eeb144b67aa8ad
### Added in 0.1.5
- Web push notifications (though not finalized)
- Credentials details page
- See more data without an ID
- Change units of a give
## [0.1.4] - 2023.11.20 - 7311d36726f3667ec4c68f241f91d404273ad4db
### Added in 0.1.4
- Offer on a project
### Changed in 0.1.4
- Automatically set as visible when importing a contact
## [0.1.3] - 2023.11.08 - 910f57ec7d2e50803ae3d04f4b927e0f5219fbde
### Added in 0.1.3
- Contact name editing
### Changed in 0.1.3
- Don't show actions on front page if not registered.
### Removed in 0.1.3
- Home page Notiwind test buttons
## [0.1.2] - 2023.11.01 - 7f6c93802911a030a89fe3706e18b5c17151e5bb
### Added in 0.1.2
- Basics: create ID, record a give, declare a project, search, and get notifications.

View File

@@ -1,11 +0,0 @@
# Contributing
Welcome! We are happy to have your help with this project.
We expect contributions to include automated tests and pass linting. Run the `test-all` task.
Note that some previous features don't have tests and adding more will make you friends quick.
Note that all contributions will be under our [license, modeled after SQLite](https://github.com/trentlarson/endorser-ch/blob/master/LICENSE).
If you want to see a code of conduct, we're probably not the people you want to hang with.
Basically, we'll work together as long as we both enjoy it, and we'll stop when that stops.

View File

@@ -1,170 +0,0 @@
# TimeSafari Docker Build
# Author: Matthew Raymer
# Description: Multi-stage Docker build for TimeSafari web application
#
# Build Process:
# 1. Base stage: Node.js with build dependencies
# 2. Builder stage: Copy pre-built web assets from host
# 3. Production stage: Nginx server with optimized assets
#
# Note: Web assets are built on the host using npm scripts before Docker build
#
# Security Features:
# - Non-root user execution
# - Minimal attack surface with Alpine Linux
# - Multi-stage build to reduce image size
# - No build dependencies in final image
#
# Usage:
# IMPORTANT: Build web assets first, then build Docker image
#
# Using npm scripts (recommended):
# Production: npm run build:web:docker:prod
# Test: npm run build:web:docker:test
# Development: npm run build:web:docker
#
# Manual workflow:
# 1. Build web assets: npm run build:web:build -- --mode production
# 2. Build Docker: docker build -t timesafari:latest .
#
# Note: For development, use npm run build:web directly (no Docker needed)
#
# Build Arguments:
# BUILD_MODE: development, test, or production (default: production)
# NODE_ENV: node environment (default: production)
#
# Environment Variables:
# NODE_ENV: Build environment (development/production)
# BUILD_MODE: Build mode for asset selection (development/test/production)
#
# Build Context:
# This Dockerfile is designed to work when the build context is set to
# ./crowd-funder-for-time-pwa from the parent directory (where docker-compose.yml is located)
# =============================================================================
# BASE STAGE - Common dependencies and setup
# =============================================================================
FROM node:22-alpine3.20 AS base
# Install system dependencies for build process
RUN apk add --no-cache \
bash \
git \
python3 \
py3-pip \
py3-setuptools \
make \
g++ \
gcc \
&& rm -rf /var/cache/apk/*
# Create non-root user for security
RUN addgroup -g 1001 -S nodejs && \
adduser -S nextjs -u 1001
# Set working directory
WORKDIR /app
# Copy package files for dependency installation
# Note: These files are in the project root (crowd-funder-for-time-pwa directory)
COPY package*.json ./
# Install dependencies with security audit
RUN npm ci --only=production --audit --fund=false && \
npm audit fix --audit-level=moderate || true
# =============================================================================
# BUILDER STAGE - Copy pre-built assets
# =============================================================================
FROM base AS builder
# Define build arguments with defaults
ARG BUILD_MODE=production
ARG NODE_ENV=production
# Set environment variables from build arguments
ENV BUILD_MODE=${BUILD_MODE}
ENV NODE_ENV=${NODE_ENV}
# Copy pre-built assets from host
# Note: dist/ directory is in the project root (crowd-funder-for-time-pwa directory)
COPY dist/ ./dist/
# Verify build output exists
RUN ls -la dist/ || (echo "Build output not found in dist/ directory" && exit 1)
# =============================================================================
# PRODUCTION STAGE - Nginx server
# =============================================================================
FROM nginx:alpine AS production
# Define build arguments for production stage
ARG BUILD_MODE=production
ARG NODE_ENV=production
# Set environment variables
ENV BUILD_MODE=${BUILD_MODE}
ENV NODE_ENV=${NODE_ENV}
# Install security updates and clean cache
RUN apk update && \
apk upgrade && \
apk add --no-cache \
curl \
&& rm -rf /var/cache/apk/*
# Use existing nginx user from base image (nginx user and group already exist)
# No need to create new user as nginx:alpine already has nginx user
# Copy main nginx configuration
COPY docker/nginx.conf /etc/nginx/nginx.conf
# Copy production nginx configuration
COPY docker/default.conf /etc/nginx/conf.d/default.conf
# Copy built assets from builder stage
COPY --from=builder --chown=nginx:nginx /app/dist /usr/share/nginx/html
# Create necessary directories with proper permissions
RUN mkdir -p /var/cache/nginx /var/log/nginx /tmp && \
chown -R nginx:nginx /var/cache/nginx /var/log/nginx /tmp && \
chown -R nginx:nginx /usr/share/nginx/html
# Switch to non-root user
USER nginx
# Expose port 80
EXPOSE 80
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost/ || exit 1
# Start nginx with proper signal handling
CMD ["nginx", "-g", "daemon off;"]
# =============================================================================
# TEST STAGE - For test environment testing
# =============================================================================
FROM production AS test
# Define build arguments for test stage
ARG BUILD_MODE=test
ARG NODE_ENV=test
# Set environment variables
ENV BUILD_MODE=${BUILD_MODE}
ENV NODE_ENV=${NODE_ENV}
# Copy test-specific nginx configuration
COPY docker/staging.conf /etc/nginx/conf.d/default.conf
# Expose port 80
EXPOSE 80
# Health check for staging
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost/health || exit 1
# Start nginx
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -1,4 +0,0 @@
source "https://rubygems.org"
gem "cocoapods"

View File

@@ -1,134 +0,0 @@
GEM
remote: https://rubygems.org/
specs:
CFPropertyList (3.0.7)
base64
nkf
rexml
activesupport (7.2.2.1)
base64
benchmark (>= 0.3)
bigdecimal
concurrent-ruby (~> 1.0, >= 1.3.1)
connection_pool (>= 2.2.5)
drb
i18n (>= 1.6, < 2)
logger (>= 1.4.2)
minitest (>= 5.1)
securerandom (>= 0.3)
tzinfo (~> 2.0, >= 2.0.5)
addressable (2.8.7)
public_suffix (>= 2.0.2, < 7.0)
algoliasearch (1.27.5)
httpclient (~> 2.8, >= 2.8.3)
json (>= 1.5.1)
atomos (0.1.3)
base64 (0.2.0)
benchmark (0.4.0)
bigdecimal (3.1.9)
claide (1.1.0)
cocoapods (1.16.2)
addressable (~> 2.8)
claide (>= 1.0.2, < 2.0)
cocoapods-core (= 1.16.2)
cocoapods-deintegrate (>= 1.0.3, < 2.0)
cocoapods-downloader (>= 2.1, < 3.0)
cocoapods-plugins (>= 1.0.0, < 2.0)
cocoapods-search (>= 1.0.0, < 2.0)
cocoapods-trunk (>= 1.6.0, < 2.0)
cocoapods-try (>= 1.1.0, < 2.0)
colored2 (~> 3.1)
escape (~> 0.0.4)
fourflusher (>= 2.3.0, < 3.0)
gh_inspector (~> 1.0)
molinillo (~> 0.8.0)
nap (~> 1.0)
ruby-macho (>= 2.3.0, < 3.0)
xcodeproj (>= 1.27.0, < 2.0)
cocoapods-core (1.16.2)
activesupport (>= 5.0, < 8)
addressable (~> 2.8)
algoliasearch (~> 1.0)
concurrent-ruby (~> 1.1)
fuzzy_match (~> 2.0.4)
nap (~> 1.0)
netrc (~> 0.11)
public_suffix (~> 4.0)
typhoeus (~> 1.0)
cocoapods-deintegrate (1.0.5)
cocoapods-downloader (2.1)
cocoapods-plugins (1.0.0)
nap
cocoapods-search (1.0.1)
cocoapods-trunk (1.6.0)
nap (>= 0.8, < 2.0)
netrc (~> 0.11)
cocoapods-try (1.2.0)
colored2 (3.1.2)
concurrent-ruby (1.3.5)
connection_pool (2.5.0)
drb (2.2.1)
escape (0.0.4)
ethon (0.16.0)
ffi (>= 1.15.0)
ffi (1.17.1)
ffi (1.17.1-aarch64-linux-gnu)
ffi (1.17.1-aarch64-linux-musl)
ffi (1.17.1-arm-linux-gnu)
ffi (1.17.1-arm-linux-musl)
ffi (1.17.1-arm64-darwin)
ffi (1.17.1-x86-linux-gnu)
ffi (1.17.1-x86-linux-musl)
ffi (1.17.1-x86_64-darwin)
ffi (1.17.1-x86_64-linux-gnu)
ffi (1.17.1-x86_64-linux-musl)
fourflusher (2.3.1)
fuzzy_match (2.0.4)
gh_inspector (1.1.3)
httpclient (2.9.0)
mutex_m
i18n (1.14.7)
concurrent-ruby (~> 1.0)
json (2.10.2)
logger (1.6.6)
minitest (5.25.5)
molinillo (0.8.0)
mutex_m (0.3.0)
nanaimo (0.4.0)
nap (1.1.0)
netrc (0.11.0)
nkf (0.2.0)
public_suffix (4.0.7)
rexml (3.4.1)
ruby-macho (2.5.1)
securerandom (0.4.1)
typhoeus (1.4.1)
ethon (>= 0.9.0)
tzinfo (2.0.6)
concurrent-ruby (~> 1.0)
xcodeproj (1.27.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.4.0)
rexml (>= 3.3.6, < 4.0)
PLATFORMS
aarch64-linux-gnu
aarch64-linux-musl
arm-linux-gnu
arm-linux-musl
arm64-darwin
ruby
x86-linux-gnu
x86-linux-musl
x86_64-darwin
x86_64-linux-gnu
x86_64-linux-musl
DEPENDENCIES
cocoapods
BUNDLED WITH
2.6.5

View File

@@ -1,8 +0,0 @@
The author disclaims copyright to this source code. In place of a legal notice, here is a blessing:
May you do good and not evil.
May you find forgiveness for yourself and forgive others.
May you share freely, never taking more than you give.
________________________________________________________________
from https://www.sqlite.org/src/info/689401a6cfb4c234 and memorialized here https://spdx.org/licenses/blessing.html

179
README.md
View File

@@ -1,175 +1,24 @@
# TimeSafari.app - Crowd-Funder for Time - PWA
# kickstart-for-time-pwa
[Time Safari](https://timesafari.org/) allows people to ease into collaboration: start with expressions of gratitude
and expand to crowd-fund with time & money, then record and see the impact of contributions.
## Roadmap
See [ClickUp](https://sharing.clickup.com/9014278710/l/h/8cmnyhp-174/10573fec74e2ba0) for current priorities.
## Setup & Building
Quick start:
* For setup, we recommend [pkgx](https://pkgx.dev), which installs what you need (either automatically or with the `dev` command). Core dependencies are typescript & npm; when building for other platforms, you'll need other things such as those in the pkgx.yaml & BUILDING.md files.
```bash
## Project setup
```
npm install
npm run build:web:serve -- --test
```
To be able to make submissions: go to "profile" (bottom left), go to the bottom and expand "Show Advanced Settings", go to the bottom and to the "Test Page", and finally "Become User 0" to see all the functionality.
See [BUILDING.md](BUILDING.md) for comprehensive build instructions for all platforms (Web, Electron, iOS, Android, Docker).
## Development Database Clearing
TimeSafari provides a simple script-based approach to clear the local database (not the claim server) for development purposes.
### Quick Usage
```bash
# Run the database clearing script
./scripts/clear-database.sh
# Then restart your development server
npm run build:electron:dev # For Electron
npm run build:web:dev # For Web
### Compiles and hot-reloads for development
```
npm run serve
```
### What It Does
#### **Electron (Desktop App)**
- Automatically finds and clears the SQLite database files
- Works on Linux, macOS, and Windows
- Clears all data and forces fresh migrations on next startup
#### **Web Browser**
- Provides instructions for using custom browser data directories
- Shows manual clearing via browser DevTools
- Ensures reliable database clearing without browser complications
### Safety Features
-**Interactive Script**: Guides you through the process
-**Platform Detection**: Automatically detects your OS
-**Clear Instructions**: Step-by-step guidance for each platform
-**Safe Paths**: Only clears TimeSafari-specific data
### Manual Commands (if needed)
#### **Electron Database Location**
```bash
# Linux
rm -rf ~/.config/TimeSafari/*
# macOS
rm -rf ~/Library/Application\ Support/TimeSafari/*
# Windows
rmdir /s /q %APPDATA%\TimeSafari
### Compiles and minifies for production
```
npm run build
```
#### **Web Browser (Custom Data Directory)**
```bash
# Create isolated browser profile
mkdir ~/timesafari-dev-data
### Lints and fixes files
```
npm run lint
```
## Domain Configuration
TimeSafari uses a centralized domain configuration system to ensure consistent
URL generation across all environments. This prevents localhost URLs from
appearing in shared links during development.
### Key Features
-**Production URLs for Sharing**: All copy link buttons use production domain
-**Environment-Specific Internal URLs**: Internal operations use appropriate
environment URLs
-**Single Point of Control**: Change domain in one place for entire app
-**Type-Safe Configuration**: Full TypeScript support
### Quick Reference
```typescript
// For sharing functionality (environment-specific)
import { APP_SERVER } from "@/constants/app";
const shareLink = `${APP_SERVER}/deep-link/claim/123`;
// For internal operations (environment-specific)
import { APP_SERVER } from "@/constants/app";
const apiUrl = `${APP_SERVER}/api/claim/123`;
```
### Documentation
- [Constants and Configuration](src/constants/app.ts) - Core constants
## Tests
See [TESTING.md](test-playwright/TESTING.md) for detailed test instructions.
## Icons
Application icons are in the `assets` directory, processed by the `capacitor-assets` command.
To add a Font Awesome icon, add to fontawesome.ts and reference with `font-awesome` element and `icon` attribute with the hyphenated name.
## Other
### Reference Material
* Notifications can be type of `toast` (self-dismiss), `info`, `success`, `warning`, and `danger`.
They are done via [notiwind](https://www.npmjs.com/package/notiwind) and set up in App.vue.
* [Customize Vue configuration](https://cli.vuejs.org/config/).
* If you are deploying in a subdirectory, add it to `publicPath` in vue.config.js, eg: `publicPath: "/app/time-tracker/",`
### Code Organization
The project uses a centralized approach to type definitions and interfaces:
* `src/interfaces/` - Contains all TypeScript interfaces and type definitions
* `deepLinks.ts` - Deep linking type system and Zod validation schemas
* `give.ts` - Give-related interfaces and type definitions
* `claims.ts` - Claim-related interfaces and verifiable credentials
* `common.ts` - Shared interfaces and utility types
* Other domain-specific interface files
Key principles:
- All interfaces and types are defined in the interfaces folder
- Zod schemas are used for runtime validation and type generation
- Domain-specific interfaces are separated into their own files
- Common interfaces are shared through `common.ts`
- Type definitions are generated from Zod schemas where possible
### Database Architecture
The application uses a platform-agnostic database layer with Vue mixins for service access:
* `src/services/PlatformService.ts` - Database interface definition
* `src/services/PlatformServiceFactory.ts` - Platform-specific service factory
* `src/services/AbsurdSqlDatabaseService.ts` - SQLite implementation
* `src/utils/PlatformServiceMixin.ts` - Vue mixin for database access with caching
* `src/db/` - Legacy Dexie database (migration in progress)
**Development Guidelines**:
- Always use `PlatformServiceMixin` for database operations in components
- Test with PlatformServiceMixin for new features
- Use migration tools for data transfer between systems
- Leverage mixin's ultra-concise methods: `$db()`, `$exec()`, `$one()`, `$contacts()`, `$settings()`
**Architecture Decision**: The project uses Vue mixins over Composition API composables for platform service access. See [Architecture Decisions](doc/architecture-decisions.md) for detailed rationale.
### Kudos
Gifts make the world go 'round!
* [WebStorm by JetBrains](https://www.jetbrains.com/webstorm/) for the free open-source license
* [Máximo Fernández](https://medium.com/@maxfarenas) for the 3D [code](https://github.com/maxfer03/vue-three-ns) and [explanatory post](https://medium.com/nicasource/building-an-interactive-web-portfolio-with-vue-three-js-part-three-implementing-three-js-452cb375ef80)
* [Many tools & libraries](https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa/src/branch/master/package.json#L10) such as Nodejs.org, IntelliJ Idea, Veramo.io, Vuejs.org, threejs.org
* [Bush 3D model](https://sketchfab.com/3d-models/lupine-plant-bf30f1110c174d4baedda0ed63778439)
* [Forest floor image](https://www.goodfreephotos.com/albums/textures/leafy-autumn-forest-floor.jpg)
* Time Safari logo assisted by [DALL-E in ChatGPT](https://chat.openai.com/g/g-2fkFE8rbu-dall-e)
* [DiceBear](https://www.dicebear.com/licenses/) and [Avataaars](https://www.dicebear.com/styles/avataaars/#details) for human-looking identicons
* Some gratitude prompts thanks to [Develop Good Habits](https://www.developgoodhabits.com/gratitude-journal-prompts/)
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).

View File

@@ -1,84 +0,0 @@
# What to do about storage for native apps?
## Problem
We can't trust iOS IndexedDB to persist. I want to start delivering an app to people now, in preparation for presentations mid-June: Rotary on June 12 and Porcfest on June 17.
* Apple WebKit puts a [7-day cap on IndexedDB](https://webkit.org/blog/10218/full-third-party-cookie-blocking-and-more/).
* The web standards expose a `persist` method to mark memory as persistent, and [supposedly WebView supports it](https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/persisted), but too many other things indicate it's not reliable. I've talked with [ChatGPT](https://chatgpt.com/share/68322f40-84c8-8007-b213-855f7962989a) & Venice & Claude (in Cursor); [this answer from Perplexity](https://www.perplexity.ai/search/which-platforms-prompt-the-use-HUQLqy4qQD2cRbkmO4CgHg) says that most platforms don't prompt and Safari doesn't support it; I don't know if that means WebKit as well.
* Capacitor says [not to trust it on iOS](https://capacitorjs.com/docs/v6/guides/storage).
Also, with sensitive data, the accounts info should be encrypted.
# Options
* There is a community [SQLite plugin for Capacitor](https://github.com/capacitor-community/sqlite) with encryption by [SQLCipher](https://github.com/sqlcipher/sqlcipher).
* [This tutorial](https://jepiqueau.github.io/2023/09/05/Ionic7Vue-SQLite-CRUD-App.html#part-1---web---table-of-contents) shows how that plugin works for web as well as native.
* Capacitor abstracts [user preferences in an API](https://capacitorjs.com/docs/apis/preferences), which uses different underlying libraries on iOS & Android. Unfortunately, it won't do any filtering or searching, and is only meant for small amounts of data. (It could be used for settings and for identifiers, but contacts will grow and image blobs won't work.)
* There are hints that Capacitor offers another custom storage API but all I could find was that Preferences API.
* [Ionic Storage](https://ionic.io/docs/secure-storage) is an enterprise solution, which also supports encryption.
* Not an option yet: Dexie may support SQLite in [a future version](https://dexie.org/roadmap/dexie5.0).
# Current Plan
* Implement SQLite for Capacitor & web, with encryption. That will allow us to test quickly and keep the same interface for native & web, but we don't deal with migrations for current web users.
* After that is delivered, write a migration for current web users from IndexedDB to SQLite.
# Current method calls
... which is not 100% complete because the AI that generated thus claimed no usage of 'temp' DB.
### Secret Database (secretDB) - Used for storing the encryption key
secretDB.open() - Opens the database
secretDB.secret.get(MASTER_SECRET_KEY) - Retrieves the secret key
secretDB.secret.add({ id: MASTER_SECRET_KEY, secret }) - Adds a new secret key
### Accounts Database (accountsDB) - Used for storing sensitive account information
accountsDB.open() - Opens the database
accountsDB.accounts.count() - Counts number of accounts
accountsDB.accounts.toArray() - Gets all accounts
accountsDB.accounts.where("did").equals(did).first() - Gets a specific account by DID
accountsDB.accounts.add(account) - Adds a new account
### Non-sensitive Database (db) - Used for settings, contacts, logs, and temp data
Settings operations:
export all settings (Dexie format)
db.settings.get(MASTER_SETTINGS_KEY) - Gets default settings
db.settings.where("accountDid").equals(did).first() - Gets account-specific settings
db.settings.where("accountDid").equals(did).modify(settingsChanges) - Updates account settings
db.settings.add(settingsChanges) - Adds new settings
db.settings.count() - Counts number of settings
db.settings.update(key, changes) - Updates settings
Contacts operations:
export all contacts (Dexie format)
db.contacts.toArray() - Gets all contacts
db.contacts.add(contact) - Adds a new contact
db.contacts.update(did, contactData) - Updates a contact
db.contacts.delete(did) - Deletes a contact
db.contacts.where("did").equals(did).first() - Gets a specific contact by DID
Logs operations:
db.logs.get(todayKey) - Gets logs for a specific day
db.logs.update(todayKey, { message: fullMessage }) - Updates logs
db.logs.clear() - Clears all logs

101
android/.gitignore vendored
View File

@@ -1,101 +0,0 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
app/build/*
!app/build/.npmkeep
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
# secrets
app/gradle.properties.secrets
app/time-safari-upload-key-pkcs12.jks
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins

View File

@@ -1,119 +0,0 @@
apply plugin: 'com.android.application'
// These are sample values to set in gradle.properties.secrets
// MY_KEYSTORE_FILE=time-safari-upload-key-pkcs12.jks
// MY_KEYSTORE_PASSWORD=...
// MY_KEY_ALIAS=time-safari-key-alias
// MY_KEY_PASSWORD=...
// Try to load from environment variables first
project.ext.MY_KEYSTORE_FILE = System.getenv('ANDROID_KEYSTORE_FILE') ?: ""
project.ext.MY_KEYSTORE_PASSWORD = System.getenv('ANDROID_KEYSTORE_PASSWORD') ?: ""
project.ext.MY_KEY_ALIAS = System.getenv('ANDROID_KEY_ALIAS') ?: ""
project.ext.MY_KEY_PASSWORD = System.getenv('ANDROID_KEY_PASSWORD') ?: ""
// If no environment variables, try to load from secrets file
if (!project.ext.MY_KEYSTORE_FILE) {
def secretsPropertiesFile = rootProject.file("app/gradle.properties.secrets")
if (secretsPropertiesFile.exists()) {
Properties secretsProperties = new Properties()
secretsProperties.load(new FileInputStream(secretsPropertiesFile))
secretsProperties.each { name, value ->
project.ext[name] = value
}
}
}
android {
namespace 'app.timesafari'
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "app.timesafari.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 39
versionName "1.0.6"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
signingConfigs {
release {
if (project.ext.MY_KEYSTORE_FILE &&
project.ext.MY_KEYSTORE_PASSWORD &&
project.ext.MY_KEY_ALIAS &&
project.ext.MY_KEY_PASSWORD) {
storeFile file(project.ext.MY_KEYSTORE_FILE)
storePassword project.ext.MY_KEYSTORE_PASSWORD
keyAlias project.ext.MY_KEY_ALIAS
keyPassword project.ext.MY_KEY_PASSWORD
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
// Only sign if we have the signing config
if (signingConfigs.release.storeFile != null) {
signingConfig signingConfigs.release
}
}
}
packagingOptions {
jniLibs {
pickFirsts += ['**/lib/x86_64/libbarhopper_v3.so', '**/lib/x86_64/libimage_processing_util_jni.so', '**/lib/x86_64/libsqlcipher.so']
}
}
// Configure for 16 KB page size compatibility
// Enable bundle builds (without which it doesn't work right for bundleDebug vs bundleRelease)
bundle {
language {
enableSplit = true
}
density {
enableSplit = true
}
abi {
enableSplit = true
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
implementation project(':capacitor-community-sqlite')
implementation "androidx.biometric:biometric:1.2.0-alpha05"
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}

View File

@@ -1,25 +0,0 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-community-sqlite')
implementation project(':capacitor-mlkit-barcode-scanning')
implementation project(':capacitor-app')
implementation project(':capacitor-camera')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-share')
implementation project(':capawesome-capacitor-file-picker')
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}

View File

@@ -1,28 +0,0 @@
{
"project_info": {
"project_number": "123456789000",
"project_id": "timesafari-app",
"storage_bucket": "timesafari-app.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:123456789000:android:1234567890abcdef",
"android_client_info": {
"package_name": "app.timesafari.app"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyDummyKeyForBuildPurposesOnly12345"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
}
]
}

View File

@@ -1,21 +0,0 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -1,26 +0,0 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("app.timesafari.app", appContext.getPackageName());
}
}

View File

@@ -1,47 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
android:exported="true"
android:label="@string/title_activity_main"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBarLaunch">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="timesafari" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
</manifest>

View File

@@ -1,121 +0,0 @@
{
"appId": "app.timesafari",
"appName": "TimeSafari",
"webDir": "dist",
"server": {
"cleartext": true
},
"plugins": {
"App": {
"appUrlOpen": {
"handlers": [
{
"url": "timesafari://*",
"autoVerify": true
}
]
}
},
"SplashScreen": {
"launchShowDuration": 3000,
"launchAutoHide": true,
"backgroundColor": "#ffffff",
"androidSplashResourceName": "splash",
"androidScaleType": "CENTER_CROP",
"showSpinner": false,
"androidSpinnerStyle": "large",
"iosSpinnerStyle": "small",
"spinnerColor": "#999999",
"splashFullScreen": true,
"splashImmersive": true
},
"CapacitorSQLite": {
"iosDatabaseLocation": "Library/CapacitorDatabase",
"iosIsEncryption": false,
"iosBiometric": {
"biometricAuth": false,
"biometricTitle": "Biometric login for TimeSafari"
},
"androidIsEncryption": false,
"androidBiometric": {
"biometricAuth": false,
"biometricTitle": "Biometric login for TimeSafari"
},
"electronIsEncryption": false
}
},
"ios": {
"contentInset": "never",
"allowsLinkPreview": true,
"scrollEnabled": true,
"limitsNavigationsToAppBoundDomains": true,
"backgroundColor": "#ffffff",
"allowNavigation": [
"*.timesafari.app",
"*.jsdelivr.net",
"api.endorser.ch"
]
},
"android": {
"allowMixedContent": true,
"captureInput": true,
"webContentsDebuggingEnabled": false,
"allowNavigation": [
"*.timesafari.app",
"*.jsdelivr.net",
"api.endorser.ch",
"10.0.2.2:3000"
]
},
"electron": {
"deepLinking": {
"schemes": [
"timesafari"
]
},
"buildOptions": {
"appId": "app.timesafari",
"productName": "TimeSafari",
"directories": {
"output": "dist-electron-packages"
},
"files": [
"dist/**/*",
"electron/**/*"
],
"mac": {
"category": "public.app-category.productivity",
"target": [
{
"target": "dmg",
"arch": [
"x64",
"arm64"
]
}
]
},
"win": {
"target": [
{
"target": "nsis",
"arch": [
"x64"
]
}
]
},
"linux": {
"target": [
{
"target": "AppImage",
"arch": [
"x64"
]
}
],
"category": "Utility"
}
}
}
}

View File

@@ -1,30 +0,0 @@
[
{
"pkg": "@capacitor-community/sqlite",
"classpath": "com.getcapacitor.community.database.sqlite.CapacitorSQLitePlugin"
},
{
"pkg": "@capacitor-mlkit/barcode-scanning",
"classpath": "io.capawesome.capacitorjs.plugins.mlkit.barcodescanning.BarcodeScannerPlugin"
},
{
"pkg": "@capacitor/app",
"classpath": "com.capacitorjs.plugins.app.AppPlugin"
},
{
"pkg": "@capacitor/camera",
"classpath": "com.capacitorjs.plugins.camera.CameraPlugin"
},
{
"pkg": "@capacitor/filesystem",
"classpath": "com.capacitorjs.plugins.filesystem.FilesystemPlugin"
},
{
"pkg": "@capacitor/share",
"classpath": "com.capacitorjs.plugins.share.SharePlugin"
},
{
"pkg": "@capawesome/capacitor-file-picker",
"classpath": "io.capawesome.capacitorjs.plugins.filepicker.FilePickerPlugin"
}
]

View File

@@ -1,15 +0,0 @@
package app.timesafari;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
//import com.getcapacitor.community.sqlite.SQLite;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize SQLite
//registerPlugin(SQLite.class);
}
}

View File

@@ -1,12 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View File

@@ -1,7 +0,0 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">TimeSafari</string>
<string name="title_activity_main">TimeSafari</string>
<string name="package_name">timesafari.app</string>
<string name="custom_url_scheme">timesafari.app</string>
</resources>

View File

@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>

View File

@@ -1,6 +0,0 @@
<?xml version='1.0' encoding='utf-8'?>
<widget version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<access origin="*" />
</widget>

View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
<files-path name="my_files" path="." />
</paths>

View File

@@ -1,18 +0,0 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}

View File

@@ -1,29 +0,0 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.12.0'
classpath 'com.google.gms:google-services:4.4.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View File

@@ -1,59 +0,0 @@
ext {
androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.6.1'
cordovaAndroidVersion = project.hasProperty('cordovaAndroidVersion') ? rootProject.ext.cordovaAndroidVersion : '10.1.1'
}
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.2.1'
}
}
apply plugin: 'com.android.library'
android {
namespace "capacitor.cordova.android.plugins"
compileSdk project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 34
defaultConfig {
minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 22
targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 34
versionCode 1
versionName "1.0"
}
lintOptions {
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
}
repositories {
google()
mavenCentral()
flatDir{
dirs 'src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(dir: 'src/main/libs', include: ['*.jar'])
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "org.apache.cordova:framework:$cordovaAndroidVersion"
// SUB-PROJECT DEPENDENCIES START
// SUB-PROJECT DEPENDENCIES END
}
// PLUGIN GRADLE EXTENSIONS START
apply from: "cordova.variables.gradle"
// PLUGIN GRADLE EXTENSIONS END
for (def func : cdvPluginPostBuildExtras) {
func()
}

View File

@@ -1,7 +0,0 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
ext {
cdvMinSdkVersion = project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 22
// Plugin gradle extensions can append to this to have code run at the end.
cdvPluginPostBuildExtras = []
cordovaConfig = [:]
}

View File

@@ -1,8 +0,0 @@
<?xml version='1.0' encoding='utf-8'?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:amazon="http://schemas.amazon.com/apk/res/android">
<application android:usesCleartextTraffic="true">
</application>
</manifest>

View File

@@ -1,24 +0,0 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
include ':capacitor-community-sqlite'
project(':capacitor-community-sqlite').projectDir = new File('../node_modules/@capacitor-community/sqlite/android')
include ':capacitor-mlkit-barcode-scanning'
project(':capacitor-mlkit-barcode-scanning').projectDir = new File('../node_modules/@capacitor-mlkit/barcode-scanning/android')
include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
include ':capacitor-camera'
project(':capacitor-camera').projectDir = new File('../node_modules/@capacitor/camera/android')
include ':capacitor-filesystem'
project(':capacitor-filesystem').projectDir = new File('../node_modules/@capacitor/filesystem/android')
include ':capacitor-share'
project(':capacitor-share').projectDir = new File('../node_modules/@capacitor/share/android')
include ':capawesome-capacitor-file-picker'
project(':capawesome-capacitor-file-picker').projectDir = new File('../node_modules/@capawesome/capacitor-file-picker/android')

View File

@@ -1,23 +0,0 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
android.suppressUnsupportedCompileSdk=36

Binary file not shown.

View File

@@ -1,7 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
android/gradlew vendored
View File

@@ -1,248 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
android/gradlew.bat vendored
View File

@@ -1,92 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1,5 +0,0 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'

View File

@@ -1,16 +0,0 @@
ext {
minSdkVersion = 22
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.8.0'
androidxAppCompatVersion = '1.6.1'
androidxCoordinatorLayoutVersion = '1.2.0'
androidxCoreVersion = '1.12.0'
androidxFragmentVersion = '1.6.2'
coreSplashScreenVersion = '1.0.1'
androidxWebkitVersion = '1.9.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.1.5'
androidxEspressoCoreVersion = '3.5.1'
cordovaAndroidVersion = '10.1.1'
}

View File

@@ -1,2 +0,0 @@
Application icons are here. They are processed for android & ios by the `capacitor-assets` command, as indicated in the BUILDING.md file.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

3
babel.config.js Normal file
View File

@@ -0,0 +1,3 @@
module.exports = {
presets: ["@vue/cli-plugin-babel/preset"],
};

View File

@@ -1,4 +0,0 @@
#!/bin/bash
export IMAGENAME="$(basename $PWD):1.0"
docker build . --network=host -t $IMAGENAME --no-cache

View File

@@ -1,36 +0,0 @@
{
"icon": {
"ios": {
"source": "resources/ios/icon/icon.png",
"target": "ios/App/App/Assets.xcassets/AppIcon.appiconset"
},
"android": {
"source": "resources/android/icon/icon.png",
"target": "android/app/src/main/res"
},
"web": {
"source": "resources/web/icon/icon.png",
"target": "public/img/icons"
}
},
"splash": {
"ios": {
"source": "resources/ios/splash/splash.png",
"target": "ios/App/App/Assets.xcassets/Splash.imageset"
},
"android": {
"source": "resources/android/splash/splash.png",
"target": "android/app/src/main/res"
}
},
"splashDark": {
"ios": {
"source": "resources/ios/splash/splash_dark.png",
"target": "ios/App/App/Assets.xcassets/SplashDark.imageset"
},
"android": {
"source": "resources/android/splash/splash_dark.png",
"target": "android/app/src/main/res"
}
}
}

View File

@@ -1,112 +0,0 @@
{
"appId": "app.timesafari",
"appName": "TimeSafari",
"webDir": "dist",
"server": {
"cleartext": true
},
"plugins": {
"App": {
"appUrlOpen": {
"handlers": [
{
"url": "timesafari://*",
"autoVerify": true
}
]
}
},
"SplashScreen": {
"launchShowDuration": 3000,
"launchAutoHide": true,
"backgroundColor": "#ffffff",
"androidSplashResourceName": "splash",
"androidScaleType": "CENTER_CROP",
"showSpinner": false,
"androidSpinnerStyle": "large",
"iosSpinnerStyle": "small",
"spinnerColor": "#999999",
"splashFullScreen": true,
"splashImmersive": true
},
"CapacitorSQLite": {
"iosDatabaseLocation": "Library/CapacitorDatabase",
"iosIsEncryption": false,
"iosBiometric": {
"biometricAuth": false,
"biometricTitle": "Biometric login for TimeSafari"
},
"androidIsEncryption": false,
"androidBiometric": {
"biometricAuth": false,
"biometricTitle": "Biometric login for TimeSafari"
},
"electronIsEncryption": false
}
},
"ios": {
"contentInset": "never",
"allowsLinkPreview": true,
"scrollEnabled": true,
"limitsNavigationsToAppBoundDomains": true,
"backgroundColor": "#ffffff",
"allowNavigation": [
"*.timesafari.app",
"*.jsdelivr.net",
"api.endorser.ch"
]
},
"android": {
"allowMixedContent": true,
"captureInput": true,
"webContentsDebuggingEnabled": false,
"allowNavigation": [
"*.timesafari.app",
"*.jsdelivr.net",
"api.endorser.ch",
"10.0.2.2:3000"
]
},
"electron": {
"deepLinking": {
"schemes": ["timesafari"]
},
"buildOptions": {
"appId": "app.timesafari",
"productName": "TimeSafari",
"directories": {
"output": "dist-electron-packages"
},
"files": [
"dist/**/*",
"electron/**/*"
],
"mac": {
"category": "public.app-category.productivity",
"target": [
{
"target": "dmg",
"arch": ["x64", "arm64"]
}
]
},
"win": {
"target": [
{
"target": "nsis",
"arch": ["x64"]
}
]
},
"linux": {
"target": [
{
"target": "AppImage",
"arch": ["x64"]
}
],
"category": "Utility"
}
}
}
}

View File

@@ -1,166 +0,0 @@
# TimeSafari Deep Linking Documentation
## Type System Overview
The deep linking system uses a multi-layered type safety approach:
1. **Runtime Validation (Zod Schemas)**
- Validates URL structure
- Enforces parameter requirements
- Sanitizes input data
- Provides detailed validation errors
- Generates TypeScript types automatically
2. **TypeScript Types**
- Generated from Zod schemas using `z.infer`
- Ensures compile-time type safety
- Provides IDE autocompletion
- Catches type errors during development
- Maintains single source of truth for types
3. **Router Integration**
- Type-safe parameter passing
- Route-specific parameter validation
- Query parameter type checking
- Automatic type inference for route parameters
## Type System Implementation
### Zod Schema to TypeScript Type Generation
```typescript
// Define the schema
const claimSchema = z.object({
id: z.string(),
view: z.enum(["details", "certificate", "raw"]).optional()
});
// TypeScript type is automatically generated
type ClaimParams = z.infer<typeof claimSchema>;
// Equivalent to:
// type ClaimParams = {
// id: string;
// view?: "details" | "certificate" | "raw";
// }
```
### Type Safety Layers
1. **Schema Definition**
```typescript
// src/interfaces/deepLinks.ts
export const deepLinkSchemas = {
claim: z.object({
id: z.string(),
view: z.enum(["details", "certificate", "raw"]).optional()
}),
// Other route schemas...
};
```
2. **Type Generation**
```typescript
// Types are automatically generated from schemas
export type DeepLinkParams = {
[K in keyof typeof deepLinkSchemas]: z.infer<(typeof deepLinkSchemas)[K]>;
};
```
3. **Runtime Validation**
```typescript
// In DeepLinkHandler
const result = deepLinkSchemas.claim.safeParse(params);
if (!result.success) {
// Handle validation errors
console.error(result.error);
}
```
### Error Handling Types
```typescript
export interface DeepLinkError extends Error {
code: string;
details?: unknown;
}
// Usage in error handling
try {
await handler.handleDeepLink(url);
} catch (error) {
if (error instanceof DeepLinkError) {
// Type-safe error handling
console.error(error.code, error.message);
}
}
```
## Implementation Files
- `src/interfaces/deepLinks.ts`: Type definitions and validation schemas
- `src/services/deepLinks.ts`: Deep link processing service
- `src/main.capacitor.ts`: Capacitor integration
- `src/views/DeepLinkRedirectView.vue`: Page to handle links to both mobile and web
## Type Safety Examples
```typescript
// Parameter type safety
type ClaimParams = DeepLinkParams["claim"];
// TypeScript knows this has:
// - id: string
// - view?: "details" | "certificate" | "raw"
// Runtime validation
const result = deepLinkSchemas.claim.safeParse({
id: "123",
view: "details"
});
// Validates at runtime with detailed error messages
```
## Supported URL Schemes
All deep links follow the format: `timesafari://<route>/<param>?<query>`
### Claim Routes
- `timesafari://claim/:id`
- Query params:
- `view`: "details" | "certificate" | "raw"
- `timesafari://claim-cert/:id`
- `timesafari://claim-add-raw/:id`
- Query params:
- `claim`: JSON string of claim data
- `claimJwtId`: JWT ID for claim
### Contact Routes
- `timesafari://contact-edit/:did`
- `timesafari://contact-import/:jwt`
- Query params:
- `contacts`: JSON array of contacts
### Project Routes
- `timesafari://project/:id`
- Query params:
- `view`: "details" | "edit"
### Invite Routes
- `timesafari://invite-one-accept/:jwt`
- Query params:
- `type`: "one" | "many"
### Gift Routes
- `timesafari://confirm-gift/:id`
- Query params:
- `action`: "confirm" | "details"
### Offer Routes
- `timesafari://offer-details/:id`
- Query params:
- `view`: "details"

View File

@@ -1,76 +0,0 @@
# TimeSafari Docs
## Generating PDF from Markdown on OSx
This uses Pandoc and BasicTex (LaTeX) Installed through Homebrew.
### Set Up
```bash
brew install pandoc
brew install basictex
# Setting up LaTex packages
# First update tlmgr
sudo tlmgr update --self
# Then install LaTex packages
sudo tlmgr install bbding
sudo tlmgr install enumitem
sudo tlmgr install environ
sudo tlmgr install fancyhdr
sudo tlmgr install framed
sudo tlmgr install import
sudo tlmgr install lastpage # Enables Page X of Y
sudo tlmgr install mdframed
sudo tlmgr install multirow
sudo tlmgr install needspace
sudo tlmgr install ntheorem
sudo tlmgr install tabu
sudo tlmgr install tcolorbox
sudo tlmgr install textpos
sudo tlmgr install titlesec
sudo tlmgr install titling # Required for the fancy headers used
sudo tlmgr install threeparttable
sudo tlmgr install trimspaces
sudo tlmgr install tocloft # Required for \tableofcontents generation
sudo tlmgr install varwidth
sudo tlmgr install wrapfig
# Install fonts
sudo tlmgr install cmbright
sudo tlmgr install collection-fontsrecommended # And set up fonts
sudo tlmgr install fira
sudo tlmgr install fontaxes
sudo tlmgr install libertine # The main font the doc uses
sudo tlmgr install opensans
sudo tlmgr install sourceserifpro
```
#### References
The following guide was adapted to this project except that we install with Brew and have a few more packages.
Guide: https://daniel.feldroy.com/posts/setting-up-latex-on-mac-os-x
### Usage
Use the `pandoc` command to generate a PDF.
```bash
pandoc usage-guide.md -o usage-guide.pdf
```
And you can open the PDF with the `open` command.
```bash
open usage-guide.pdf
```
Or use this one-liner
```bash
pandoc usage-guide.md -o usage-guide.pdf && open usage-guide.pdf
```

View File

@@ -1,381 +0,0 @@
# Worker-Only Database Implementation for Web Platform
## Overview
This implementation fixes the double migration issue in the TimeSafari web platform by implementing worker-only database access, similar to the Capacitor platform architecture.
## Problem Solved
**Before:** Web platform had dual database contexts:
- Worker thread: `registerSQLWorker.js``AbsurdSqlDatabaseService.initialize()` → migrations run
- Main thread: `WebPlatformService.dbQuery()``databaseService.query()` → migrations run **AGAIN**
**After:** Single database context:
- Worker thread: Handles ALL database operations and initializes once
- Main thread: Sends messages to worker, no direct database access
## Architecture Changes
### 1. Message-Based Communication
```typescript
// Main Thread (WebPlatformService)
await this.sendWorkerMessage<QueryResult>({
type: "query",
sql: "SELECT * FROM users",
params: []
});
// Worker Thread (registerSQLWorker.js)
onmessage = async (event) => {
const { id, type, sql, params } = event.data;
if (type === "query") {
const result = await databaseService.query(sql, params);
postMessage({ id, type: "success", data: { result } });
}
};
```
### 2. Type-Safe Worker Messages
```typescript
// src/interfaces/worker-messages.ts
export interface QueryRequest extends BaseWorkerMessage {
type: "query";
sql: string;
params?: unknown[];
}
export type WorkerRequest =
| QueryRequest
| ExecRequest
| GetOneRowRequest
| InitRequest
| PingRequest;
```
### 3. Circular Dependency Resolution
#### 🔥 Critical Fix: Stack Overflow Prevention
**Problem**: Circular module dependency caused infinite recursion:
- `WebPlatformService` constructor → creates Worker
- Worker loads `registerSQLWorker.js` → imports `databaseService`
- Module resolution creates circular dependency → Stack Overflow
**Solution**: Lazy Loading in Worker
```javascript
// Before (caused stack overflow)
import databaseService from "./services/AbsurdSqlDatabaseService";
// After (fixed)
let databaseService = null;
async function getDatabaseService() {
if (!databaseService) {
// Dynamic import prevents circular dependency
const { default: service } = await import("./services/AbsurdSqlDatabaseService");
databaseService = service;
}
return databaseService;
}
```
**Key Changes for Stack Overflow Fix:**
- ✅ Removed top-level import of database service
- ✅ Added lazy loading with dynamic import
- ✅ Updated all handlers to use `await getDatabaseService()`
- ✅ Removed auto-initialization that triggered immediate loading
- ✅ Database service only loads when first database operation occurs
## Implementation Details
### 1. WebPlatformService Changes
- Removed direct database imports
- Added worker message handling
- Implemented timeout and error handling
- All database methods now proxy to worker
### 2. Worker Thread Changes
- Added message-based operation handling
- Implemented lazy loading for database service
- Added proper error handling and response formatting
- Fixed circular dependency with dynamic imports
### 3. Main Thread Changes
- Removed duplicate worker creation in `main.web.ts`
- WebPlatformService now manages single worker instance
- Added Safari compatibility with `initBackend()`
## Files Modified
1. **src/interfaces/worker-messages.ts** *(NEW)*
- Type definitions for worker communication
- Request and response message interfaces
2. **src/registerSQLWorker.js** *(MAJOR REWRITE)*
- Message-based operation handling
- **Fixed circular dependency with lazy loading**
- Proper error handling and response formatting
3. **src/services/platforms/WebPlatformService.ts** *(MAJOR REWRITE)*
- Worker-only database access
- Message sending and response handling
- Timeout and error management
4. **src/main.web.ts** *(SIMPLIFIED)*
- Removed duplicate worker creation
- Simplified initialization flow
5. **WORKER_ONLY_DATABASE_IMPLEMENTATION.md** *(NEW)*
- Complete documentation of changes
## Benefits
### ✅ Fixes Double Migration Issue
- Database migrations now run only once in worker thread
- No duplicate initialization between main thread and worker
### ✅ Prevents Stack Overflow
- Circular dependency resolved with lazy loading
- Worker loads immediately without triggering database import
- Database service loads on-demand when first operation occurs
### ✅ Improved Performance
- Single database connection
- No redundant operations
- Better resource utilization
### ✅ Better Error Handling
- Centralized error handling in worker
- Type-safe message communication
- Proper timeout handling
### ✅ Consistent Architecture
- Matches Capacitor platform pattern
- Single-threaded database access
- Clear separation of concerns
## Testing Verification
After implementation, you should see:
1. **Worker Loading**:
```text
[SQLWorker] Worker loaded, ready to receive messages
```
2. **Database Initialization** (only on first operation):
```text
[SQLWorker] Starting database initialization...
[SQLWorker] Database initialization completed successfully
```
3. **No Stack Overflow**: Application starts without infinite recursion
4. **Single Migration Run**: Database migrations execute only once
5. **Functional Database**: All queries, inserts, and updates work correctly
## Migration from Previous Implementation
If upgrading from the dual-context implementation:
1. **Remove Direct Database Imports**: No more `import databaseService` in main thread
2. **Update Database Calls**: Use platform service methods instead of direct database calls
3. **Handle Async Operations**: All database operations are now async message-based
4. **Error Handling**: Update error handling to work with worker responses
## Security Considerations
- Worker thread isolates database operations
- Message validation prevents malformed requests
- Timeout handling prevents hanging operations
- Type safety reduces runtime errors
## Performance Notes
- Initial worker creation has minimal overhead
- Database operations have message passing overhead (negligible)
- Single database connection is more efficient than dual connections
- Lazy loading reduces startup time
## Migration Execution Flow
### Before (Problematic)
```chart
┌────────────── ───┐ ┌─────────────────┐
│ Main Thread │ │ Worker Thread │
│ │ │ │
│ WebPlatformService│ │registerSQLWorker│
│ ↓ │ │ ↓ │
│ databaseService │ │ databaseService │
│ (Instance A) │ │ (Instance B) │
│ ↓ │ │ ↓ │
│ [Run Migrations] │ │[Run Migrations] │ ← DUPLICATE!
└─────────────── ──┘ └─────────────────┘
```
### After (Fixed)
```text
┌─────────────── ──┐ ┌─────────────────┐
│ Main Thread │ │ Worker Thread │
│ │ │ │
│ WebPlatformService │───→│registerSQLWorker│
│ │ │ ↓ │
│ [Send Messages] │ │ databaseService │
│ │ │(Single Instance)│
│ │ │ ↓ │
│ │ │[Run Migrations] │ ← ONCE ONLY!
└─────────────── ──┘ └─────────────────┘
```
## New Security Considerations
### 1. **Message Validation**
- All worker messages validated for required fields
- Unknown message types rejected with errors
- Proper error responses prevent information leakage
### 2. **Timeout Protection**
- 30-second timeout prevents hung operations
- Automatic cleanup of pending messages
- Worker health checks via ping/pong
### 3. **Error Sanitization**
- Error messages logged but not exposed raw to main thread
- Stack traces included only in development
- Graceful handling of worker failures
## Testing Considerations
### 1. **Unit Tests Needed**
- Worker message handling
- WebPlatformService worker communication
- Error handling and timeouts
- Migration execution (should run once only)
### 2. **Integration Tests**
- End-to-end database operations
- Worker lifecycle management
- Cross-browser compatibility (especially Safari)
### 3. **Performance Tests**
- Message passing overhead
- Database operation throughput
- Memory usage with worker communication
## Browser Compatibility
### 1. **Modern Browsers**
- Chrome/Edge: Full SharedArrayBuffer support
- Firefox: Full SharedArrayBuffer support (with headers)
- Safari: Uses IndexedDB fallback via `initBackend()`
### 2. **Required Headers**
```text
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```
## Deployment Notes
### 1. **Development**
- Enhanced logging shows worker message flow
- Clear separation between worker and main thread logs
- Easy debugging via browser DevTools
### 2. **Production**
- Reduced logging overhead
- Optimized message passing
- Proper error reporting without sensitive data
## Future Enhancements
### 1. **Potential Optimizations**
- Message batching for bulk operations
- Connection pooling simulation
- Persistent worker state management
### 2. **Additional Features**
- Database backup/restore via worker
- Schema introspection commands
- Performance monitoring hooks
## Rollback Plan
If issues arise, rollback involves:
1. Restore original `WebPlatformService.ts`
2. Restore original `registerSQLWorker.js`
3. Restore original `main.web.ts`
4. Remove `worker-messages.ts` interface
## Commit Messages
```bash
git add src/interfaces/worker-messages.ts
git commit -m "Add worker message interface for type-safe database communication
- Define TypeScript interfaces for worker request/response messages
- Include query, exec, getOneRow, init, and ping message types
- Provide type safety for web platform worker messaging"
git add src/registerSQLWorker.js
git commit -m "Implement message-based worker for single-point database access
- Replace simple auto-init with comprehensive message handler
- Add support for query, exec, getOneRow, init, ping operations
- Implement proper error handling and response management
- Ensure single database initialization point to prevent double migrations"
git add src/services/platforms/WebPlatformService.ts
git commit -m "Migrate WebPlatformService to worker-only database access
- Remove direct databaseService import to prevent dual context issue
- Implement worker-based messaging for all database operations
- Add worker lifecycle management with initialization tracking
- Include message timeout and error handling for reliability
- Add Safari compatibility with initBackend call"
git add src/main.web.ts
git commit -m "Remove duplicate worker creation from main.web.ts
- Worker initialization now handled by WebPlatformService
- Prevents duplicate worker creation and database contexts
- Simplifies main thread initialization"
git add WORKER_ONLY_DATABASE_IMPLEMENTATION.md
git commit -m "Document worker-only database implementation
- Comprehensive documentation of architecture changes
- Explain problem solved and benefits achieved
- Include security considerations and testing requirements"
```

View File

@@ -1,125 +0,0 @@
# Architecture Decisions
This document records key architectural decisions made during the development of TimeSafari.
## Platform Service Architecture: Mixins over Composables
**Date:** July 2, 2025
**Status:** Accepted
**Context:** Need for consistent platform service access across Vue components
### Decision
**Use Vue mixins for platform service access instead of Vue 3 Composition API composables.**
### Rationale
#### Why Mixins Were Chosen
1. **Existing Architecture Consistency**
- The entire codebase uses class-based components with `vue-facing-decorator`
- All components follow the established pattern of extending Vue class
- Mixins integrate seamlessly with the existing architecture
2. **Performance Benefits**
- **Caching Layer**: `PlatformServiceMixin` provides smart TTL-based caching
- **Ultra-Concise Methods**: Short methods like `$db()`, `$exec()`, `$one()` reduce boilerplate
- **Settings Shortcuts**: `$saveSettings()`, `$saveMySettings()` eliminate 90% of update boilerplate
- **Memory Management**: WeakMap-based caching prevents memory leaks
3. **Developer Experience**
- **Familiar Pattern**: Mixins are well-understood by the team
- **Type Safety**: Full TypeScript support with proper interfaces
- **Error Handling**: Centralized error handling across components
- **Code Reduction**: Reduces database code by up to 80%
4. **Production Readiness**
- **Mature Implementation**: `PlatformServiceMixin` is actively used and tested
- **Comprehensive Features**: Includes transaction support, cache management, settings shortcuts
- **Security**: Proper input validation and error handling
#### Why Composables Were Rejected
1. **Architecture Mismatch**
- Would require rewriting all components to use Composition API
- Breaks consistency with existing class-based component pattern
- Requires significant refactoring effort
2. **Limited Features**
- Basic platform service access without caching
- No settings management shortcuts
- No ultra-concise database methods
- Would require additional development to match mixin capabilities
3. **Performance Considerations**
- No built-in caching layer
- Would require manual implementation of performance optimizations
- More verbose for common operations
### Implementation
#### Current Usage
```typescript
// Component implementation
@Component({
mixins: [PlatformServiceMixin],
})
export default class HomeView extends Vue {
async mounted() {
// Ultra-concise cached settings loading
const settings = await this.$settings({
apiServer: "",
activeDid: "",
isRegistered: false,
});
// Cached contacts loading
this.allContacts = await this.$contacts();
// Settings update with automatic cache invalidation
await this.$saveMySettings({ isRegistered: true });
}
}
```
#### Key Features
- **Cached Database Operations**: `$contacts()`, `$settings()`, `$accountSettings()`
- **Settings Shortcuts**: `$saveSettings()`, `$saveMySettings()`, `$saveUserSettings()`
- **Ultra-Concise Methods**: `$db()`, `$exec()`, `$one()`, `$query()`, `$first()`
- **Cache Management**: `$refreshSettings()`, `$clearAllCaches()`
- **Transaction Support**: `$withTransaction()` with automatic rollback
### Consequences
#### Positive
- **Consistent Architecture**: All components follow the same pattern
- **High Performance**: Smart caching reduces database calls by 80%+
- **Developer Productivity**: Ultra-concise methods reduce boilerplate by 90%
- **Type Safety**: Full TypeScript support with proper interfaces
- **Memory Safety**: WeakMap-based caching prevents memory leaks
#### Negative
- **Vue 2 Pattern**: Uses older mixin pattern instead of modern Composition API
- **Tight Coupling**: Components are coupled to the mixin implementation
- **Testing Complexity**: Mixins can make unit testing more complex
### Future Considerations
1. **Migration Path**: If Vue 4 or future versions deprecate mixins, we may need to migrate
2. **Performance Monitoring**: Continue monitoring caching performance and adjust TTL values
3. **Feature Expansion**: Add new ultra-concise methods as needed
4. **Testing Strategy**: Develop comprehensive testing strategies for mixin-based components
### Related Documentation
- [PlatformServiceMixin Implementation](../src/utils/PlatformServiceMixin.ts)
- [TimeSafari Cross-Platform Architecture Guide](./build-modernization-context.md)
- [Database Migration Guide](./database-migration-guide.md)
---
*This decision was made based on the current codebase architecture and team expertise. The mixin approach provides the best balance of performance, developer experience, and architectural consistency for the TimeSafari application.*

View File

@@ -1,51 +0,0 @@
# TimeSafari Build Modernization Context
**Author:** Matthew Raymer
## Motivation
- Eliminate manual hacks and post-build scripts for Electron builds
- Ensure maintainability, reproducibility, and security of build outputs
- Unify build, test, and deployment scripts for developer experience and CI/CD
## Key Technical Decisions
- **Vite is the single source of truth for build output**
- All Electron build output (main process, preload, renderer HTML/CSS/JS) is managed by `vite.config.electron.mts`
- **CSS injection for Electron is handled by a Vite plugin**
- No more manual HTML/CSS edits or post-build scripts
- **Build scripts are unified and robust**
- Use `./scripts/build-electron.sh` for all Electron builds
- No more `fix-inject-css.js` or similar hacks
- **Output structure is deterministic and ASAR-friendly**
- Main process: `dist-electron/main.js`
- Preload: `dist-electron/preload.js`
- Renderer assets: `dist-electron/www/` (HTML, CSS, JS)
## Security & Maintenance Checklist
- [x] All scripts and configs are committed and documented
- [x] No manual file hacks remain
- [x] All build output is deterministic and reproducible
- [x] No sensitive data is exposed in the build process
- [x] Documentation (`BUILDING.md`) is up to date
## How to Build Electron
1. Run:
```bash
./scripts/build-electron.sh
```
2. Output will be in `dist-electron/`:
- `main.js`, `preload.js` in root
- `www/` contains all renderer assets
3. No manual post-processing is required
## Customization
- **Vite config:** All build output and asset handling is controlled in `vite.config.electron.mts`
- **CSS/HTML injection:** Use Vite plugins (see `electron-css-injection` in the config) for further customization
- **Build scripts:** All orchestration is in `scripts/` and documented in `BUILDING.md`
## For Future Developers
- Always use Vite plugins/config for build output changes
- Never manually edit built files or inject assets post-build
- Keep documentation and scripts in sync with the build process
---
This file documents the context and rationale for the build modernization and should be included in the repository for onboarding and future reference.

View File

@@ -1,163 +0,0 @@
# Circular Dependency Analysis
## Overview
This document analyzes the current state of circular dependencies in the TimeSafari codebase, particularly focusing on the migration from Dexie to SQLite and the PlatformServiceMixin implementation.
## Current Circular Dependency Status
### ✅ **EXCELLENT NEWS: All Circular Dependencies RESOLVED**
The codebase currently has **no active circular dependencies** that are causing runtime or compilation errors. All circular dependency issues have been successfully resolved.
### 🔍 **Resolved Dependency Patterns**
#### 1. **Logger → PlatformServiceFactory → Logger** (RESOLVED)
- **Status**: ✅ **RESOLVED**
- **Previous Issue**: Logger imported `logToDb` from databaseUtil, which imported logger
- **Solution**: Logger now uses direct database access via PlatformServiceFactory
- **Implementation**: Self-contained `logToDatabase()` function in logger.ts
#### 2. **PlatformServiceMixin → databaseUtil → logger → PlatformServiceMixin** (RESOLVED)
- **Status**: ✅ **RESOLVED**
- **Previous Issue**: PlatformServiceMixin imported `memoryLogs` from databaseUtil
- **Solution**: Created self-contained `_memoryLogs` array in PlatformServiceMixin
- **Implementation**: Self-contained memory logs implementation
#### 3. **databaseUtil → logger → PlatformServiceFactory → databaseUtil** (RESOLVED)
- **Status**: ✅ **RESOLVED**
- **Previous Issue**: databaseUtil imported logger, which could create loops
- **Solution**: Logger is now self-contained and doesn't import from databaseUtil
#### 4. **Utility Files → databaseUtil → PlatformServiceMixin** (RESOLVED)
- **Status**: ✅ **RESOLVED**
- **Previous Issue**: `src/libs/util.ts` and `src/services/deepLinks.ts` imported from databaseUtil
- **Solution**: Replaced with self-contained implementations and PlatformServiceFactory usage
- **Implementation**:
- Self-contained `parseJsonField()` and `mapQueryResultToValues()` functions
- Direct PlatformServiceFactory usage for database operations
- Console logging instead of databaseUtil logging functions
## Detailed Dependency Analysis
### ✅ **All Critical Dependencies Resolved**
#### PlatformServiceMixin Independence
- **Status**: ✅ **COMPLETE**
- **Achievement**: PlatformServiceMixin has no external dependencies on databaseUtil
- **Implementation**: Self-contained memory logs and utility functions
- **Impact**: Enables complete migration of databaseUtil functions to PlatformServiceMixin
#### Logger Independence
- **Status**: ✅ **COMPLETE**
- **Achievement**: Logger is completely self-contained
- **Implementation**: Direct database access via PlatformServiceFactory
- **Impact**: Eliminates all circular dependency risks
#### Utility Files Independence
- **Status**: ✅ **COMPLETE**
- **Achievement**: All utility files no longer depend on databaseUtil
- **Implementation**: Self-contained functions and direct platform service access
- **Impact**: Enables complete databaseUtil migration
### 🎯 **Migration Readiness Status**
#### Files Ready for Migration (52 files)
1. **Components** (15 files):
- `PhotoDialog.vue`
- `FeedFilters.vue`
- `UserNameDialog.vue`
- `ImageMethodDialog.vue`
- `OfferDialog.vue`
- `OnboardingDialog.vue`
- `PushNotificationPermission.vue`
- `GiftedPrompts.vue`
- `GiftedDialog.vue`
- `World/components/objects/landmarks.js`
- And 5 more...
2. **Views** (30+ files):
- `IdentitySwitcherView.vue`
- `ContactEditView.vue`
- `ContactGiftingView.vue`
- `ImportAccountView.vue`
- `OnboardMeetingMembersView.vue`
- `RecentOffersToUserProjectsView.vue`
- `ClaimCertificateView.vue`
- `NewActivityView.vue`
- `HelpView.vue`
- `NewEditProjectView.vue`
- And 20+ more...
3. **Services** (5 files):
- `deepLinks.ts`**MIGRATED**
- `endorserServer.ts`
- `libs/util.ts`**MIGRATED**
- `test/index.ts`
### 🟢 **Healthy Dependencies**
#### Logger Usage (80+ files)
- **Status**: ✅ **HEALTHY**
- **Pattern**: All files import logger from `@/utils/logger`
- **Impact**: No circular dependencies, logger is self-contained
- **Benefit**: Centralized logging with database integration
## Resolution Strategy - COMPLETED
### ✅ **Phase 1: Complete PlatformServiceMixin Independence (COMPLETE)**
1. **Removed memoryLogs import** from PlatformServiceMixin ✅
2. **Created self-contained memoryLogs** implementation ✅
3. **Added missing utility methods** to PlatformServiceMixin ✅
### ✅ **Phase 2: Utility Files Migration (COMPLETE)**
1. **Migrated deepLinks.ts** - Replaced databaseUtil logging with console logging ✅
2. **Migrated util.ts** - Replaced databaseUtil functions with self-contained implementations ✅
3. **Updated all PlatformServiceFactory calls** to use async pattern ✅
### 🎯 **Phase 3: File-by-File Migration (READY TO START)**
1. **High-usage files first** (views, core components)
2. **Replace databaseUtil imports** with PlatformServiceMixin
3. **Update function calls** to use mixin methods
### 🎯 **Phase 4: Cleanup (FUTURE)**
1. **Remove unused databaseUtil functions**
2. **Update TypeScript interfaces**
3. **Remove databaseUtil imports** from all files
## Current Status Summary
### ✅ **Resolved Issues**
1. **Logger circular dependency** - Fixed with self-contained implementation
2. **PlatformServiceMixin circular dependency** - Fixed with self-contained memoryLogs
3. **Utility files circular dependency** - Fixed with self-contained implementations
4. **TypeScript compilation** - No circular dependency errors
5. **Runtime stability** - No circular dependency crashes
### 🎯 **Ready for Next Phase**
1. **52 files** ready for databaseUtil migration
2. **PlatformServiceMixin** fully independent and functional
3. **Clear migration path** - Well-defined targets and strategy
## Benefits of Current State
### ✅ **Achieved**
1. **No runtime circular dependencies** - Application runs without crashes
2. **Self-contained logger** - No more logger/databaseUtil loops
3. **PlatformServiceMixin ready** - All methods implemented and independent
4. **Utility files independent** - No more databaseUtil dependencies
5. **Clear migration path** - Well-defined targets and strategy
### 🎯 **Expected After Migration**
1. **Complete databaseUtil migration** - Single source of truth
2. **Eliminated circular dependencies** - Clean architecture
3. **Improved performance** - Caching and optimization
4. **Better maintainability** - Centralized database operations
---
**Author**: Matthew Raymer
**Created**: 2025-07-05
**Status**: ✅ **COMPLETE - All Circular Dependencies Resolved**
**Last Updated**: 2025-01-06
**Note**: PlatformServiceMixin circular dependency completely resolved. Ready for Phase 2: File-by-File Migration

View File

@@ -1,314 +0,0 @@
# Component Communication Guide
## Overview
This guide establishes our preferred patterns for component communication in Vue.js applications, with a focus on maintainability, type safety, and developer experience.
## Core Principle: Function Props Over $emit
**Preference**: Use function props for business logic and data operations, reserve $emit for DOM-like events.
### Why Function Props?
1. **Better TypeScript Support**: Full type checking of parameters and return values
2. **Superior IDE Navigation**: Ctrl+click takes you directly to implementation
3. **Explicit Contracts**: Clear declaration of what functions a component needs
4. **Easier Testing**: Simple to mock and test in isolation
5. **Flexibility**: Can pass any function, not just event handlers
### When to Use $emit
1. **DOM-like Events**: `@click`, `@input`, `@submit`, `@change`
2. **Lifecycle Events**: `@mounted`, `@before-unmount`, `@updated`
3. **Form Validation**: `@validation-error`, `@validation-success`
4. **Event Bubbling**: When events need to bubble through multiple components
5. **Vue DevTools Integration**: When you want events visible in DevTools timeline
## Implementation Patterns
### Function Props Pattern
```typescript
// Child Component
@Component({
name: "MyComponent"
})
export default class MyComponent extends Vue {
@Prop({ required: true }) onSave!: (data: SaveData) => Promise<void>;
@Prop({ required: true }) onCancel!: () => void;
@Prop({ required: false }) onValidate?: (data: FormData) => boolean;
async handleSave() {
const data = this.collectFormData();
await this.onSave(data);
}
handleCancel() {
this.onCancel();
}
}
```
```vue
<!-- Parent Template -->
<MyComponent
:on-save="handleSave"
:on-cancel="handleCancel"
:on-validate="validateForm"
/>
```
### $emit Pattern (for DOM-like events)
```typescript
// Child Component
@Component({
name: "FormComponent"
})
export default class FormComponent extends Vue {
@Emit("submit")
handleSubmit() {
return this.formData;
}
@Emit("input")
handleInput(value: string) {
return value;
}
}
```
```vue
<!-- Parent Template -->
<FormComponent
@submit="handleFormSubmit"
@input="handleInputChange"
/>
```
## Automatic Code Generation Guidelines
### Component Template Generation
When generating component templates, follow these patterns:
#### Function Props Template
```vue
<template>
<div class="component-name">
<!-- Component content -->
<button @click="handleAction">
{{ buttonText }}
</button>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from "vue-facing-decorator";
@Component({
name: "ComponentName"
})
export default class ComponentName extends Vue {
@Prop({ required: true }) onAction!: () => void;
@Prop({ required: true }) buttonText!: string;
@Prop({ required: false }) disabled?: boolean;
handleAction() {
if (!this.disabled) {
this.onAction();
}
}
}
</script>
```
#### $emit Template (for DOM events)
```vue
<template>
<div class="component-name">
<!-- Component content -->
<button @click="handleClick">
{{ buttonText }}
</button>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Emit } from "vue-facing-decorator";
@Component({
name: "ComponentName"
})
export default class ComponentName extends Vue {
@Prop({ required: true }) buttonText!: string;
@Prop({ required: false }) disabled?: boolean;
@Emit("click")
handleClick() {
return { disabled: this.disabled };
}
}
</script>
```
### Code Generation Rules
#### 1. Function Props for Business Logic
- **Data operations**: Save, delete, update, validate
- **Navigation**: Route changes, modal opening/closing
- **State management**: Store actions, state updates
- **API calls**: Data fetching, form submissions
#### 2. $emit for User Interactions
- **Click events**: Button clicks, link navigation
- **Form events**: Input changes, form submissions
- **Lifecycle events**: Component mounting, unmounting
- **UI events**: Focus, blur, scroll, resize
#### 3. Naming Conventions
**Function Props:**
```typescript
// Action-oriented names
onSave: (data: SaveData) => Promise<void>
onDelete: (id: string) => Promise<void>
onUpdate: (item: Item) => void
onValidate: (data: FormData) => boolean
onNavigate: (route: string) => void
```
**$emit Events:**
```typescript
// Event-oriented names
@click: (event: MouseEvent) => void
@input: (value: string) => void
@submit: (data: FormData) => void
@focus: (event: FocusEvent) => void
@mounted: () => void
```
### TypeScript Integration
#### Function Prop Types
```typescript
// Define reusable function types
interface SaveHandler {
(data: SaveData): Promise<void>;
}
interface ValidationHandler {
(data: FormData): boolean;
}
// Use in components
@Prop({ required: true }) onSave!: SaveHandler;
@Prop({ required: true }) onValidate!: ValidationHandler;
```
#### Event Types
```typescript
// Define event payload types
interface ClickEvent {
target: HTMLElement;
timestamp: number;
}
@Emit("click")
handleClick(): ClickEvent {
return {
target: this.$el,
timestamp: Date.now()
};
}
```
## Testing Guidelines
### Function Props Testing
```typescript
// Easy to mock and test
const mockOnSave = jest.fn();
const wrapper = mount(MyComponent, {
propsData: {
onSave: mockOnSave
}
});
await wrapper.vm.handleSave();
expect(mockOnSave).toHaveBeenCalledWith(expectedData);
```
### $emit Testing
```typescript
// Requires event simulation
const wrapper = mount(MyComponent);
await wrapper.find('button').trigger('click');
expect(wrapper.emitted('click')).toBeTruthy();
```
## Migration Strategy
### From $emit to Function Props
1. **Identify business logic events** (not DOM events)
2. **Add function props** to component interface
3. **Update parent components** to pass functions
4. **Remove $emit decorators** and event handlers
5. **Update tests** to use function mocks
### Example Migration
**Before ($emit):**
```typescript
@Emit("save")
handleSave() {
return this.formData;
}
```
**After (Function Props):**
```typescript
@Prop({ required: true }) onSave!: (data: FormData) => void;
handleSave() {
this.onSave(this.formData);
}
```
## Best Practices Summary
1. **Use function props** for business logic, data operations, and complex interactions
2. **Use $emit** for DOM-like events, lifecycle events, and simple user interactions
3. **Be consistent** within your codebase
4. **Document your patterns** for team alignment
5. **Consider TypeScript** when choosing between approaches
6. **Test both patterns** appropriately
## Code Generation Templates
### Component Generator Input
```typescript
interface ComponentSpec {
name: string;
props: Array<{
name: string;
type: string;
required: boolean;
isFunction: boolean;
}>;
events: Array<{
name: string;
payloadType?: string;
}>;
template: string;
}
```
### Generated Output
```typescript
// Generator should automatically choose function props vs $emit
// based on the nature of the interaction (business logic vs DOM event)
```
This guide ensures consistent, maintainable component communication patterns across the application.

View File

@@ -1,116 +0,0 @@
# CORS Disabled for Universal Image Support
## Decision Summary
CORS headers have been **disabled** to support Time Safari's core mission: enabling users to share images from any domain without restrictions.
## What Changed
### ❌ Removed CORS Headers
- `Cross-Origin-Opener-Policy: same-origin`
- `Cross-Origin-Embedder-Policy: require-corp`
### ✅ Results
- Images from **any domain** now work in development and production
- No proxy configuration needed
- No whitelist of supported image hosts
- True community-driven image sharing
## Technical Tradeoffs
### 🔻 Lost: SharedArrayBuffer Performance
- **Before**: Fast SQLite operations via SharedArrayBuffer
- **After**: Slightly slower IndexedDB fallback mode
- **Impact**: Minimal for typical usage - absurd-sql automatically falls back
### 🔺 Gained: Universal Image Support
- **Before**: Only specific domains worked (TimeSafari, Flickr, Imgur, etc.)
- **After**: Any image URL works immediately
- **Impact**: Massive improvement for user experience
## Architecture Impact
### Database Operations
```typescript
// absurd-sql automatically detects SharedArrayBuffer availability
if (typeof SharedArrayBuffer === "undefined") {
// Uses IndexedDB backend (current state)
console.log("Using IndexedDB fallback mode");
} else {
// Uses SharedArrayBuffer (not available due to disabled CORS)
console.log("Using SharedArrayBuffer mode");
}
```
### Image Loading
```typescript
// All images load directly now
export function transformImageUrlForCors(imageUrl: string): string {
return imageUrl; // No transformation needed
}
```
## Why This Was The Right Choice
### Time Safari's Use Case
- **Community platform** where users share content from anywhere
- **User-generated content** includes images from arbitrary websites
- **Flexibility** is more important than marginal performance gains
### Alternative Would Require
- Pre-configuring proxies for every possible image hosting service
- Constantly updating proxy list as users find new sources
- Poor user experience when images fail to load
- Impossible to support the "any domain" requirement
## Performance Comparison
### Database Operations
- **SharedArrayBuffer**: ~2x faster for large operations
- **IndexedDB**: Still very fast for typical Time Safari usage
- **Real Impact**: Negligible for typical user operations
### Image Loading
- **With CORS**: Many images failed to load in development
- **Without CORS**: All images load immediately
- **Real Impact**: Massive improvement in user experience
## Browser Compatibility
| Browser | SharedArrayBuffer | IndexedDB | Image Loading |
|---------|------------------|-----------|---------------|
| Chrome | ❌ (CORS disabled) | ✅ Works | ✅ Any domain |
| Firefox | ❌ (CORS disabled) | ✅ Works | ✅ Any domain |
| Safari | ❌ (CORS disabled) | ✅ Works | ✅ Any domain |
| Edge | ❌ (CORS disabled) | ✅ Works | ✅ Any domain |
## Migration Notes
### For Developers
- No code changes needed
- `transformImageUrlForCors()` still exists but returns original URL
- All existing image references work without modification
### For Users
- Images from any website now work immediately
- No more "image failed to load" issues in development
- Consistent behavior between development and production
## Future Considerations
### If Performance Becomes Critical
1. **Selective CORS**: Enable only for specific operations
2. **Service Worker**: Handle image proxying at service worker level
3. **Build-time Processing**: Pre-process images during build
4. **User Education**: Guide users toward optimized image hosting
### Monitoring
- Track database operation performance
- Monitor for any user-reported slowness
- Consider re-enabling SharedArrayBuffer if usage patterns change
## Conclusion
This change prioritizes **user experience** and **community functionality** over marginal performance gains. The database still works efficiently via IndexedDB, while images now work universally without configuration.
For a community platform like Time Safari, the ability to share images from any domain is fundamental to the user experience and mission.

View File

@@ -1,240 +0,0 @@
# CORS Image Loading Solution
## Overview
This document describes the implementation of a comprehensive image loading solution that works in a cross-origin isolated environment (required for SharedArrayBuffer support) while accepting images from any domain.
## Problem Statement
When using SharedArrayBuffer (required for absurd-sql), browsers enforce a cross-origin isolated environment with these headers:
- `Cross-Origin-Opener-Policy: same-origin`
- `Cross-Origin-Embedder-Policy: require-corp`
This isolation prevents loading external resources (including images) unless they have proper CORS headers, which most image hosting services don't provide.
## Solution Architecture
### 1. Multi-Tier Proxy System
The solution uses a multi-tier approach to handle images from various sources:
#### Tier 1: Specific Domain Proxies (Development Only)
- **TimeSafari Images**: `/image-proxy/``https://image.timesafari.app/`
- **Flickr Images**: `/flickr-proxy/``https://live.staticflickr.com/`
- **Imgur Images**: `/imgur-proxy/``https://i.imgur.com/`
- **GitHub Raw**: `/github-proxy/``https://raw.githubusercontent.com/`
- **Unsplash**: `/unsplash-proxy/``https://images.unsplash.com/`
#### Tier 2: Universal CORS Proxy (Development Only)
- **Any External Domain**: Uses `https://api.allorigins.win/raw?url=` for arbitrary domains
#### Tier 3: Direct Loading (Production)
- **Production Mode**: All images load directly without proxying
### 2. Smart URL Transformation
The `transformImageUrlForCors` function automatically:
- Detects the image source domain
- Routes through appropriate proxy in development
- Preserves original URLs in production
- Handles edge cases (data URLs, relative paths, etc.)
## Implementation Details
### Configuration Files
#### `vite.config.common.mts`
```typescript
server: {
headers: {
// Required for SharedArrayBuffer support
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp'
},
proxy: {
// Specific domain proxies with CORS headers
'/image-proxy': { /* TimeSafari images */ },
'/flickr-proxy': { /* Flickr images */ },
'/imgur-proxy': { /* Imgur images */ },
'/github-proxy': { /* GitHub raw images */ },
'/unsplash-proxy': { /* Unsplash images */ }
}
}
```
#### `src/libs/util.ts`
```typescript
export function transformImageUrlForCors(imageUrl: string): string {
// Development mode: Transform URLs to use proxies
// Production mode: Return original URLs
// Handle specific domains with dedicated proxies
// Fall back to universal CORS proxy for arbitrary domains
}
```
### Usage in Components
All image loading in components uses the transformation function:
```typescript
// In Vue components
import { transformImageUrlForCors } from "../libs/util";
// Transform image URL before using
const imageUrl = transformImageUrlForCors(originalImageUrl);
```
```html
<!-- In templates -->
<img :src="transformImageUrlForCors(imageUrl)" alt="Description" />
```
## Benefits
### ✅ SharedArrayBuffer Support
- Maintains cross-origin isolation required for SharedArrayBuffer
- Enables fast SQLite database operations via absurd-sql
- Provides better performance than IndexedDB fallback
### ✅ Universal Image Support
- Handles images from any domain
- No need to pre-configure every possible image source
- Graceful fallback for unknown domains
### ✅ Development/Production Flexibility
- Proxy system only active in development
- Production uses direct URLs for maximum performance
- No proxy server required in production
### ✅ Automatic Detection
- Smart URL transformation based on domain patterns
- Preserves relative URLs and data URLs
- Handles edge cases gracefully
## Testing
### Automated Testing
Run the test suite to verify URL transformation:
```typescript
import { testCorsImageTransformation } from './libs/test-cors-images';
// Console output shows transformation results
testCorsImageTransformation();
```
### Visual Testing
Create test image elements to verify loading:
```typescript
import { createTestImageElements } from './libs/test-cors-images';
// Creates visual test panel in browser
createTestImageElements();
```
### Manual Testing
1. Start development server: `npm run dev`
2. Open browser console to see transformation logs
3. Check Network tab for proxy requests
4. Verify images load correctly from various domains
## Security Considerations
### Development Environment
- CORS proxies are only used in development
- External proxy services (allorigins.win) are used for testing
- No sensitive data is exposed through proxies
### Production Environment
- All images load directly without proxying
- No dependency on external proxy services
- Original security model maintained
### Privacy
- Image URLs are not logged or stored by proxy services
- Proxy requests are only made during development
- No tracking or analytics in proxy chain
## Performance Impact
### Development
- Slight latency from proxy requests
- Additional network hops for external domains
- More verbose logging for debugging
### Production
- No performance impact
- Direct image loading as before
- No proxy overhead
## Troubleshooting
### Common Issues
#### Images Not Loading in Development
1. Check console for proxy errors
2. Verify CORS headers are set
3. Test with different image URLs
4. Check network connectivity to proxy services
#### SharedArrayBuffer Not Available
1. Verify CORS headers are set in server configuration
2. Check that site is served over HTTPS (or localhost)
3. Ensure browser supports SharedArrayBuffer
#### Proxy Service Unavailable
1. Check if allorigins.win is accessible
2. Consider using alternative CORS proxy services
3. Temporarily disable CORS headers for testing
### Debug Commands
```bash
# Check if SharedArrayBuffer is available
console.log(typeof SharedArrayBuffer !== 'undefined');
# Test URL transformation
import { transformImageUrlForCors } from './libs/util';
console.log(transformImageUrlForCors('https://example.com/image.jpg'));
# Run comprehensive tests
import { testCorsImageTransformation } from './libs/test-cors-images';
testCorsImageTransformation();
```
## Migration Guide
### From Previous Implementation
1. CORS headers are now required for SharedArrayBuffer
2. Image URLs automatically transformed in development
3. No changes needed to existing image loading code
4. Test thoroughly in both development and production
### Adding New Image Sources
1. Add specific proxy for frequently used domains
2. Update `transformImageUrlForCors` function
3. Add CORS headers to proxy configuration
4. Test with sample images
## Future Enhancements
### Possible Improvements
1. **Local Proxy Server**: Run dedicated proxy server for development
2. **Caching**: Cache proxy responses for better performance
3. **Fallback Chain**: Multiple proxy services for reliability
4. **Image Optimization**: Compress/resize images through proxy
5. **Analytics**: Track image loading success/failure rates
### Alternative Approaches
1. **Service Worker**: Intercept image requests at service worker level
2. **Build-time Processing**: Pre-process images during build
3. **CDN Integration**: Use CDN with proper CORS headers
4. **Local Storage**: Cache images in browser storage
## Conclusion
This solution provides a robust, scalable approach to image loading in a cross-origin isolated environment while maintaining the benefits of SharedArrayBuffer support. The multi-tier proxy system ensures compatibility with any image source while optimizing for performance and security.
For questions or issues, refer to the troubleshooting section or consult the development team.

View File

@@ -1,304 +0,0 @@
# Database Migration Guide
## Overview
The Database Migration feature allows you to compare and migrate data between Dexie (IndexedDB) and SQLite databases in the TimeSafari application. This is particularly useful during the transition from the old Dexie-based storage system to the new SQLite-based system.
**⚠️ UPDATE**: The migration is now controlled through the **PlatformServiceMixin** rather than a `USE_DEXIE_DB` constant. This provides a cleaner, more maintainable approach to database access control.
## Features
### 1. Database Comparison
- Compare data between Dexie and SQLite databases
- View detailed differences in contacts and settings
- Identify added, modified, and missing records
- Export comparison results for analysis
### 2. Data Migration
- Migrate contacts from Dexie to SQLite
- Migrate settings from Dexie to SQLite
- Option to overwrite existing records or skip them
- Comprehensive error handling and reporting
### 3. User Interface
- Modern, responsive UI built with Tailwind CSS
- Real-time loading states and progress indicators
- Clear success and error messaging
- Export functionality for comparison data
## Prerequisites
### Enable Dexie Database Access
Before using the migration features, you must ensure the Dexie database is accessible for migration purposes. The migration tools will automatically handle database access through the PlatformServiceMixin.
**Note**: The migration tools are designed to work with both databases simultaneously during the migration process.
## Accessing the Migration Interface
1. Navigate to the **Account** page in the TimeSafari app
2. Scroll down to find the **Database Migration** link
3. Click the link to open the migration interface
## Using the Migration Interface
### Step 1: Compare Databases
1. Click the **"Compare Databases"** button
2. The system will retrieve data from both Dexie and SQLite databases
3. Review the comparison results showing:
- Summary counts for each database
- Detailed differences (added, modified, missing records)
- Specific records that need attention
### Step 2: Review Differences
The comparison results are displayed in several sections:
#### Summary Cards
- **Dexie Contacts**: Number of contacts in Dexie database
- **SQLite Contacts**: Number of contacts in SQLite database
- **Dexie Settings**: Number of settings in Dexie database
- **SQLite Settings**: Number of settings in SQLite database
#### Contact Differences
- **Added**: Contacts in Dexie but not in SQLite
- **Modified**: Contacts that differ between databases
- **Missing**: Contacts in SQLite but not in Dexie
#### Settings Differences
- **Added**: Settings in Dexie but not in SQLite
- **Modified**: Settings that differ between databases
- **Missing**: Settings in SQLite but not in Dexie
### Step 3: Configure Migration Options
Before migrating data, configure the migration options:
- **Overwrite existing records**: When enabled, existing records in SQLite will be updated with data from Dexie. When disabled, existing records will be skipped.
### Step 4: Migrate Data
#### Migrate Contacts
1. Click the **"Migrate Contacts"** button
2. The system will transfer contacts from Dexie to SQLite
3. Review the migration results showing:
- Number of contacts successfully migrated
- Any warnings or errors encountered
#### Migrate Settings
1. Click the **"Migrate Settings"** button
2. The system will transfer settings from Dexie to SQLite
3. Review the migration results showing:
- Number of settings successfully migrated
- Any warnings or errors encountered
### Step 5: Export Comparison (Optional)
1. Click the **"Export Comparison"** button
2. A JSON file will be downloaded containing the complete comparison data
3. This file can be used for analysis or backup purposes
## Migration Process Details
### Contact Migration
The contact migration process:
1. **Retrieves** all contacts from Dexie database
2. **Checks** for existing contacts in SQLite by DID
3. **Inserts** new contacts or **updates** existing ones (if overwrite is enabled)
4. **Handles** complex fields like `contactMethods` (JSON arrays)
5. **Reports** success/failure for each contact
### Settings Migration
The settings migration process:
1. **Retrieves** all settings from Dexie database
2. **Focuses** on key user-facing settings:
- `firstName`
- `isRegistered`
- `profileImageUrl`
- `showShortcutBvc`
- `searchBoxes`
3. **Preserves** other settings in SQLite
4. **Reports** success/failure for each setting
## Error Handling
### Common Issues
#### Database Connection Issues
**Error**: "Failed to retrieve Dexie contacts"
**Solution**: Check that the Dexie database is properly initialized and accessible
#### SQLite Query Errors
**Error**: "Failed to retrieve SQLite contacts"
**Solution**: Verify that the SQLite database is properly set up and the platform service is working
#### Migration Failures
**Error**: "Migration failed: [specific error]"
**Solution**: Review the error details and check data integrity in both databases
### Error Recovery
1. **Review** the error messages carefully
2. **Check** the browser console for additional details
3. **Verify** database connectivity and permissions
4. **Retry** the operation if appropriate
5. **Export** comparison data for manual review if needed
## Best Practices
### Before Migration
1. **Backup** your data if possible
2. **Test** the migration on a small dataset first
3. **Verify** that both databases are accessible
4. **Review** the comparison results before migrating
### During Migration
1. **Don't** interrupt the migration process
2. **Monitor** the progress and error messages
3. **Note** any warnings or skipped records
4. **Export** comparison data for reference
### After Migration
1. **Verify** that data was migrated correctly
2. **Test** the application functionality
3. **Use PlatformServiceMixin** for all new database operations
4. **Clean up** any temporary files or exports
## Technical Details
### Database Schema
The migration handles the following data structures:
#### Contacts Table
```typescript
interface Contact {
did: string; // Decentralized Identifier
name: string; // Contact name
contactMethods: ContactMethod[]; // Array of contact methods
nextPubKeyHashB64: string; // Next public key hash
notes: string; // Contact notes
profileImageUrl: string; // Profile image URL
publicKeyBase64: string; // Public key in base64
seesMe: boolean; // Visibility flag
registered: boolean; // Registration status
}
```
#### Settings Table
```typescript
interface Settings {
id: number; // Settings ID
accountDid: string; // Account DID
activeDid: string; // Active DID
firstName: string; // User's first name
isRegistered: boolean; // Registration status
profileImageUrl: string; // Profile image URL
showShortcutBvc: boolean; // UI preference
searchBoxes: any[]; // Search configuration
// ... other fields
}
```
### Migration Logic
The migration service uses sophisticated comparison logic:
1. **Primary Key Matching**: Uses DID for contacts, ID for settings
2. **Deep Comparison**: Compares all fields including complex objects
3. **JSON Handling**: Properly handles JSON fields like `contactMethods` and `searchBoxes`
4. **Conflict Resolution**: Provides options for handling existing records
### Performance Considerations
- **Batch Processing**: Processes records one by one for reliability
- **Error Isolation**: Individual record failures don't stop the entire migration
- **Memory Management**: Handles large datasets efficiently
- **Progress Reporting**: Provides real-time feedback during migration
## Troubleshooting
### Migration Stuck
If the migration appears to be stuck:
1. **Check** the browser console for errors
2. **Refresh** the page and try again
3. **Verify** database connectivity
4. **Check** for large datasets that might take time
### Incomplete Migration
If migration doesn't complete:
1. **Review** error messages
2. **Check** data integrity in both databases
3. **Export** comparison data for manual review
4. **Consider** migrating in smaller batches
### Data Inconsistencies
If you notice data inconsistencies:
1. **Export** comparison data
2. **Review** the differences carefully
3. **Manually** verify critical records
4. **Consider** selective migration of specific records
## Support
For issues with the Database Migration feature:
1. **Check** this documentation first
2. **Review** the browser console for error details
3. **Export** comparison data for analysis
4. **Contact** the development team with specific error details
## Security Considerations
- **Data Privacy**: Migration data is processed locally and not sent to external servers
- **Access Control**: Only users with access to the account can perform migration
- **Data Integrity**: Migration preserves data integrity and handles conflicts gracefully
- **Audit Trail**: Export functionality provides an audit trail of migration operations
## PlatformServiceMixin Integration
After migration, all database operations should use the PlatformServiceMixin:
```typescript
// Use mixin methods for database access
const contacts = await this.$contacts();
const settings = await this.$settings();
const result = await this.$db("SELECT * FROM contacts WHERE did = ?", [accountDid]);
```
This provides:
- **Caching**: Automatic caching for performance
- **Error Handling**: Consistent error handling
- **Type Safety**: Enhanced TypeScript integration
- **Code Reduction**: Up to 80% reduction in boilerplate
---
**Note**: This migration tool is designed for the transition period between database systems. Once migration is complete and verified, the Dexie database should be disabled to avoid confusion and potential data conflicts. All new development should use the PlatformServiceMixin for database operations.

View File

@@ -1,362 +0,0 @@
# DatabaseUtil to PlatformServiceMixin Migration Plan
## Migration Overview
This plan migrates database utility functions from `src/db/databaseUtil.ts` to `src/utils/PlatformServiceMixin.ts` to consolidate database operations and reduce boilerplate code across the application.
## Priority Levels
### 🔴 **PRIORITY 1 (Critical - Migrate First)**
Functions used in 50+ files that are core to application functionality
### 🟡 **PRIORITY 2 (High - Migrate Second)**
Functions used in 10-50 files that are important but not critical
### 🟢 **PRIORITY 3 (Medium - Migrate Third)**
Functions used in 5-10 files that provide utility but aren't frequently used
### 🔵 **PRIORITY 4 (Low - Migrate Last)**
Functions used in <5 files or specialized functions
## Detailed Migration Plan
### 🔴 **PRIORITY 1 - Critical Functions**
#### 1. `retrieveSettingsForActiveAccount()`
- **Usage**: 60+ files
- **Current**: `databaseUtil.retrieveSettingsForActiveAccount()`
- **Target**: `this.$settings()` (already exists in PlatformServiceMixin)
- **Migration**: Replace all calls with `this.$settings()`
- **Files to migrate**: All view files, components, and services
#### 2. `logConsoleAndDb()` and `logToDb()`
- **Usage**: 40+ files
- **Current**: `databaseUtil.logConsoleAndDb()` / `databaseUtil.logToDb()`
- **Target**: Add `$log()` and `$logError()` methods to PlatformServiceMixin
- **Migration**: Replace with `this.$log()` and `this.$logError()`
- **Files to migrate**: All error handling and logging code
#### 3. `mapQueryResultToValues()` and `mapColumnsToValues()`
- **Usage**: 30+ files
- **Current**: `databaseUtil.mapQueryResultToValues()` / `databaseUtil.mapColumnsToValues()`
- **Target**: `this.$mapResults()` (already exists in PlatformServiceMixin)
- **Migration**: Replace with `this.$mapResults()`
- **Files to migrate**: All data processing components
### 🟡 **PRIORITY 2 - High Priority Functions**
#### 4. `updateDefaultSettings()` and `updateDidSpecificSettings()`
- **Usage**: 20+ files
- **Current**: `databaseUtil.updateDefaultSettings()` / `databaseUtil.updateDidSpecificSettings()`
- **Target**: `this.$saveSettings()` and `this.$saveUserSettings()` (already exist)
- **Migration**: Replace with existing mixin methods
- **Files to migrate**: Settings management components
#### 5. `parseJsonField()`
- **Usage**: 15+ files
- **Current**: `databaseUtil.parseJsonField()` or direct import
- **Target**: Add `$parseJson()` method to PlatformServiceMixin
- **Migration**: Replace with `this.$parseJson()`
- **Files to migrate**: Data processing components
#### 6. `generateInsertStatement()` and `generateUpdateStatement()`
- **Usage**: 10+ files
- **Current**: `databaseUtil.generateInsertStatement()` / `databaseUtil.generateUpdateStatement()`
- **Target**: `this.$insertEntity()` and `this.$updateEntity()` (expand existing methods)
- **Migration**: Replace with high-level entity methods
- **Files to migrate**: Data manipulation components
### 🟢 **PRIORITY 3 - Medium Priority Functions**
#### 7. `insertDidSpecificSettings()`
- **Usage**: 8 files
- **Current**: `databaseUtil.insertDidSpecificSettings()`
- **Target**: `this.$insertUserSettings()` (new method)
- **Migration**: Replace with new mixin method
- **Files to migrate**: Account creation and import components
#### 8. `debugSettingsData()`
- **Usage**: 5 files
- **Current**: `databaseUtil.debugSettingsData()`
- **Target**: `this.$debugSettings()` (new method)
- **Migration**: Replace with new mixin method
- **Files to migrate**: Debug and testing components
### 🔵 **PRIORITY 4 - Low Priority Functions**
#### 9. `retrieveSettingsForDefaultAccount()`
- **Usage**: 3 files
- **Current**: `databaseUtil.retrieveSettingsForDefaultAccount()`
- **Target**: `this.$getDefaultSettings()` (new method)
- **Migration**: Replace with new mixin method
- **Files to migrate**: Settings management components
#### 10. Memory logs and cleanup functions
- **Usage**: 2 files
- **Current**: `databaseUtil.memoryLogs`, cleanup functions
- **Target**: `this.$memoryLogs` and `this.$cleanupLogs()` (new methods)
- **Migration**: Replace with new mixin methods
- **Files to migrate**: Log management components
## Implementation Strategy
### Phase 0: Untangle Logger and DatabaseUtil (Prerequisite)
**This must be done FIRST to eliminate circular dependencies before any mixin migration.**
1. **Create self-contained logger.ts**:
- Remove `import { logToDb } from "../db/databaseUtil"`
- Add direct database access via `PlatformServiceFactory.getInstance()`
- Implement `logger.toDb()` and `logger.toConsoleAndDb()` methods
2. **Remove databaseUtil imports from PlatformServiceMixin**:
- Remove `import { mapColumnsToValues, parseJsonField } from "@/db/databaseUtil"`
- Remove `import * as databaseUtil from "@/db/databaseUtil"`
- Add self-contained implementations of utility methods
3. **Test logger independence**:
- Verify logger works without databaseUtil
- Ensure no circular dependencies exist
- Test all logging functionality
### Phase 1: Add Missing Methods to PlatformServiceMixin
1. **Add logging methods** (now using independent logger):
```typescript
$log(message: string, level?: string): Promise<void>
$logError(message: string): Promise<void>
```
2. **Add JSON parsing method** (self-contained):
```typescript
$parseJson<T>(value: unknown, defaultValue: T): T
```
3. **Add entity update method**:
```typescript
$updateEntity(tableName: string, entity: Record<string, unknown>, whereClause: string, whereParams: unknown[]): Promise<boolean>
```
4. **Add user settings insertion**:
```typescript
$insertUserSettings(did: string, settings: Partial<Settings>): Promise<boolean>
```
### Phase 2: File-by-File Migration
#### Migration Order (by priority)
**Prerequisite**: Phase 0 (Logger/DatabaseUtil untangling) must be completed first.
1. **Start with most critical files**:
- `src/App.vue` (main application)
- `src/views/AccountViewView.vue` (core account management)
- `src/views/ContactsView.vue` (core contact management)
2. **Migrate high-usage components**:
- All view files in `src/views/`
- Core components in `src/components/`
3. **Migrate services and utilities**:
- `src/libs/util.ts`
- `src/services/` files
- `src/utils/logger.ts`
4. **Migrate remaining components**:
- Specialized components
- Test files
### Phase 3: Cleanup and Validation
1. **Remove databaseUtil imports** from migrated files
2. **Update TypeScript interfaces** to reflect new methods
3. **Run comprehensive tests** to ensure functionality
4. **Remove unused databaseUtil functions** after all migrations complete
## Migration Commands Template
For each file migration:
```bash
# 1. Update imports
# Remove: import * as databaseUtil from "../db/databaseUtil";
# Add: import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
# 2. Add mixin to component
# Add: mixins: [PlatformServiceMixin],
# 3. Replace function calls
# Replace: databaseUtil.retrieveSettingsForActiveAccount()
# With: this.$settings()
# 4. Test the migration
npm run test
# 5. Commit the change
git add .
git commit -m "Migrate [filename] from databaseUtil to PlatformServiceMixin"
```
## Benefits of Migration
1. **Reduced Boilerplate**: Eliminate repeated `PlatformServiceFactory.getInstance()` calls
2. **Better Caching**: Leverage existing caching in PlatformServiceMixin
3. **Consistent Error Handling**: Centralized error handling and logging
4. **Type Safety**: Better TypeScript integration with mixin methods
5. **Performance**: Cached platform service access and optimized database operations
6. **Maintainability**: Single source of truth for database operations
## Risk Mitigation
1. **Incremental Migration**: Migrate one file at a time to minimize risk
2. **Comprehensive Testing**: Test each migration thoroughly
3. **Rollback Plan**: Keep databaseUtil.ts until all migrations are complete
4. **Documentation**: Update documentation as methods are migrated
## Smart Logging Integration Strategy
### Current State Analysis
#### Current Logging Architecture
1. **`src/utils/logger.ts`** - Main logger with console + database logging
2. **`src/db/databaseUtil.ts`** - Database-specific logging (`logToDb`, `logConsoleAndDb`)
3. **Circular dependency** - logger.ts imports logToDb from databaseUtil.ts
#### Current Issues
- **Circular dependency** between logger and databaseUtil
- **Duplicate functionality** - both systems log to database
- **Inconsistent interfaces** - different method signatures
- **Scattered logging logic** - logging rules spread across multiple files
### Recommended Solution: Hybrid Approach (Option 3)
**Core Concept**: Enhanced logger + PlatformServiceMixin convenience methods with **zero circular dependencies**.
#### Implementation
```typescript
// 1. Enhanced logger.ts (single source of truth - NO databaseUtil imports)
export const logger = {
// Existing methods...
// New database-focused methods (self-contained)
toDb: async (message: string, level?: string) => {
// Direct database access without databaseUtil dependency
const platform = PlatformServiceFactory.getInstance();
await platform.dbExec("INSERT INTO logs (date, message) VALUES (?, ?)", [
new Date().toDateString(),
`[${level?.toUpperCase() || 'INFO'}] ${message}`
]);
},
toConsoleAndDb: async (message: string, isError?: boolean) => {
// Console output
if (isError) {
console.error(message);
} else {
console.log(message);
}
// Database output
await logger.toDb(message, isError ? 'error' : 'info');
},
// Component context methods
withContext: (componentName?: string) => ({
log: (message: string, level?: string) => logger.toDb(`[${componentName}] ${message}`, level),
error: (message: string) => logger.toDb(`[${componentName}] ${message}`, 'error')
})
};
// 2. PlatformServiceMixin convenience methods (NO databaseUtil imports)
methods: {
$log(message: string, level?: string): Promise<void> {
return logger.toDb(message, level);
},
$logError(message: string): Promise<void> {
return logger.toDb(message, 'error');
},
$logAndConsole(message: string, isError = false): Promise<void> {
return logger.toConsoleAndDb(message, isError);
},
// Self-contained utility methods (no databaseUtil dependency)
$mapResults<T>(results: QueryExecResult | undefined, mapper: (row: unknown[]) => T): T[] {
if (!results) return [];
return results.values.map(mapper);
},
$parseJson<T>(value: unknown, defaultValue: T): T {
if (typeof value === 'string') {
try {
return JSON.parse(value);
} catch {
return defaultValue;
}
}
return value as T || defaultValue;
}
}
```
#### Benefits
1. **Single source of truth** - logger.ts handles all database logging
2. **No circular dependencies** - logger.ts doesn't import from databaseUtil
3. **Component convenience** - PlatformServiceMixin provides easy access
4. **Backward compatibility** - existing code can be migrated gradually
5. **Context awareness** - logging can include component context
6. **Performance optimized** - caching and batching in logger
#### Migration Strategy
1. **Phase 1**: Create self-contained logger.ts with direct database access (no databaseUtil imports)
2. **Phase 2**: Add self-contained convenience methods to PlatformServiceMixin (no databaseUtil imports)
3. **Phase 3**: Migrate existing code to use new methods
4. **Phase 4**: Remove old logging methods from databaseUtil
5. **Phase 5**: Remove databaseUtil imports from PlatformServiceMixin
#### Key Features
- **Smart filtering** - prevent logging loops and initialization noise
- **Context tracking** - include component names in logs
- **Performance optimization** - batch database writes
- **Error handling** - graceful fallback when database unavailable
- **Platform awareness** - different behavior for web/mobile/desktop
### Integration with Migration Plan
This logging integration will be implemented as part of **Phase 1** of the migration plan, specifically:
1. **Add logging methods to PlatformServiceMixin** (Priority 1, Item 2)
2. **Migrate logConsoleAndDb and logToDb usage** across all files
3. **Consolidate logging logic** in logger.ts
4. **Remove circular dependencies** between logger and databaseUtil
---
**Author**: Matthew Raymer
**Created**: 2025-07-05
**Status**: Planning Phase
**Last Updated**: 2025-07-05

View File

@@ -1,418 +0,0 @@
# Dexie to absurd-sql Mapping Guide
## Schema Mapping
### Current Dexie Schema
```typescript
// Current Dexie schema
const db = new Dexie('TimeSafariDB');
db.version(1).stores({
accounts: 'did, publicKeyHex, createdAt, updatedAt',
settings: 'key, value, updatedAt',
contacts: 'id, did, name, createdAt, updatedAt'
});
```
### New SQLite Schema
```sql
-- New SQLite schema
CREATE TABLE accounts (
did TEXT PRIMARY KEY,
public_key_hex TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE contacts (
id TEXT PRIMARY KEY,
did TEXT NOT NULL,
name TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY (did) REFERENCES accounts(did)
);
-- Indexes for performance
CREATE INDEX idx_accounts_created_at ON accounts(created_at);
CREATE INDEX idx_contacts_did ON contacts(did);
CREATE INDEX idx_settings_updated_at ON settings(updated_at);
```
## Query Mapping
### 1. Account Operations
#### Get Account by DID
```typescript
// Dexie
const account = await db.accounts.get(did);
// absurd-sql
const result = await db.exec(`
SELECT * FROM accounts WHERE did = ?
`, [did]);
const account = result[0]?.values[0];
```
#### Get All Accounts
```typescript
// Dexie
const accounts = await db.accounts.toArray();
// absurd-sql
const result = await db.exec(`
SELECT * FROM accounts ORDER BY created_at DESC
`);
const accounts = result[0]?.values || [];
```
#### Add Account
```typescript
// Dexie
await db.accounts.add({
did,
publicKeyHex,
createdAt: Date.now(),
updatedAt: Date.now()
});
// absurd-sql
await db.run(`
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
VALUES (?, ?, ?, ?)
`, [did, publicKeyHex, Date.now(), Date.now()]);
```
#### Update Account
```typescript
// Dexie
await db.accounts.update(did, {
publicKeyHex,
updatedAt: Date.now()
});
// absurd-sql
await db.run(`
UPDATE accounts
SET public_key_hex = ?, updated_at = ?
WHERE did = ?
`, [publicKeyHex, Date.now(), did]);
```
### 2. Settings Operations
#### Get Setting
```typescript
// Dexie
const setting = await db.settings.get(key);
// absurd-sql
const result = await db.exec(`
SELECT * FROM settings WHERE key = ?
`, [key]);
const setting = result[0]?.values[0];
```
#### Set Setting
```typescript
// Dexie
await db.settings.put({
key,
value,
updatedAt: Date.now()
});
// absurd-sql
await db.run(`
INSERT INTO settings (key, value, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_at = excluded.updated_at
`, [key, value, Date.now()]);
```
### 3. Contact Operations
#### Get Contacts by Account
```typescript
// Dexie
const contacts = await db.contacts
.where('did')
.equals(accountDid)
.toArray();
// absurd-sql
const result = await db.exec(`
SELECT * FROM contacts
WHERE did = ?
ORDER BY created_at DESC
`, [accountDid]);
const contacts = result[0]?.values || [];
```
#### Add Contact
```typescript
// Dexie
await db.contacts.add({
id: generateId(),
did: accountDid,
name,
createdAt: Date.now(),
updatedAt: Date.now()
});
// absurd-sql
await db.run(`
INSERT INTO contacts (id, did, name, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
`, [generateId(), accountDid, name, Date.now(), Date.now()]);
```
## Transaction Mapping
### Batch Operations
```typescript
// Dexie
await db.transaction('rw', [db.accounts, db.contacts], async () => {
await db.accounts.add(account);
await db.contacts.bulkAdd(contacts);
});
// absurd-sql
await db.exec('BEGIN TRANSACTION;');
try {
await db.run(`
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
VALUES (?, ?, ?, ?)
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
for (const contact of contacts) {
await db.run(`
INSERT INTO contacts (id, did, name, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
`, [contact.id, contact.did, contact.name, contact.createdAt, contact.updatedAt]);
}
await db.exec('COMMIT;');
} catch (error) {
await db.exec('ROLLBACK;');
throw error;
}
```
## Migration Helper Functions
### 1. Data Export (Dexie to JSON)
```typescript
async function exportDexieData(): Promise<MigrationData> {
const db = new Dexie('TimeSafariDB');
return {
accounts: await db.accounts.toArray(),
settings: await db.settings.toArray(),
contacts: await db.contacts.toArray(),
metadata: {
version: '1.0.0',
timestamp: Date.now(),
dexieVersion: Dexie.version
}
};
}
```
### 2. Data Import (JSON to absurd-sql)
```typescript
async function importToAbsurdSql(data: MigrationData): Promise<void> {
await db.exec('BEGIN TRANSACTION;');
try {
// Import accounts
for (const account of data.accounts) {
await db.run(`
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
VALUES (?, ?, ?, ?)
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
}
// Import settings
for (const setting of data.settings) {
await db.run(`
INSERT INTO settings (key, value, updated_at)
VALUES (?, ?, ?)
`, [setting.key, setting.value, setting.updatedAt]);
}
// Import contacts
for (const contact of data.contacts) {
await db.run(`
INSERT INTO contacts (id, did, name, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
`, [contact.id, contact.did, contact.name, contact.createdAt, contact.updatedAt]);
}
await db.exec('COMMIT;');
} catch (error) {
await db.exec('ROLLBACK;');
throw error;
}
}
```
### 3. Verification
```typescript
async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
// Verify account count
const accountResult = await db.exec('SELECT COUNT(*) as count FROM accounts');
const accountCount = accountResult[0].values[0][0];
if (accountCount !== dexieData.accounts.length) {
return false;
}
// Verify settings count
const settingsResult = await db.exec('SELECT COUNT(*) as count FROM settings');
const settingsCount = settingsResult[0].values[0][0];
if (settingsCount !== dexieData.settings.length) {
return false;
}
// Verify contacts count
const contactsResult = await db.exec('SELECT COUNT(*) as count FROM contacts');
const contactsCount = contactsResult[0].values[0][0];
if (contactsCount !== dexieData.contacts.length) {
return false;
}
// Verify data integrity
for (const account of dexieData.accounts) {
const result = await db.exec(
'SELECT * FROM accounts WHERE did = ?',
[account.did]
);
const migratedAccount = result[0]?.values[0];
if (!migratedAccount ||
migratedAccount[1] !== account.publicKeyHex) { // public_key_hex is second column
return false;
}
}
return true;
}
```
## Performance Considerations
### 1. Indexing
- Dexie automatically creates indexes based on the schema
- absurd-sql requires explicit index creation
- Added indexes for frequently queried fields
- Use `PRAGMA journal_mode=MEMORY;` for better performance
### 2. Batch Operations
- Dexie has built-in bulk operations
- absurd-sql uses transactions for batch operations
- Consider chunking large datasets
- Use prepared statements for repeated queries
### 3. Query Optimization
- Dexie uses IndexedDB's native indexing
- absurd-sql requires explicit query optimization
- Use prepared statements for repeated queries
- Consider using `PRAGMA synchronous=NORMAL;` for better performance
## Error Handling
### 1. Common Errors
```typescript
// Dexie errors
try {
await db.accounts.add(account);
} catch (error) {
if (error instanceof Dexie.ConstraintError) {
// Handle duplicate key
}
}
// absurd-sql errors
try {
await db.run(`
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
VALUES (?, ?, ?, ?)
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
} catch (error) {
if (error.message.includes('UNIQUE constraint failed')) {
// Handle duplicate key
}
}
```
### 2. Transaction Recovery
```typescript
// Dexie transaction
try {
await db.transaction('rw', db.accounts, async () => {
// Operations
});
} catch (error) {
// Dexie automatically rolls back
}
// absurd-sql transaction
try {
await db.exec('BEGIN TRANSACTION;');
// Operations
await db.exec('COMMIT;');
} catch (error) {
await db.exec('ROLLBACK;');
throw error;
}
```
## Migration Strategy
1. **Preparation**
- Export all Dexie data
- Verify data integrity
- Create SQLite schema
- Setup indexes
2. **Migration**
- Import data in transactions
- Verify each batch
- Handle errors gracefully
- Maintain backup
3. **Verification**
- Compare record counts
- Verify data integrity
- Test common queries
- Validate relationships
4. **Cleanup**
- Remove Dexie database
- Clear IndexedDB storage
- Update application code
- Remove old dependencies

View File

@@ -1,304 +0,0 @@
# Electron Platform Cleanup Summary
## Overview
This document summarizes the comprehensive cleanup and improvements made to the TimeSafari Electron implementation. The changes resolve platform detection issues, improve build consistency, and provide a clear architecture for desktop development.
## Key Issues Resolved
### 1. Platform Detection Problems
- **Before**: `PlatformServiceFactory` only supported "capacitor" and "web" platforms
- **After**: Added proper "electron" platform support with dedicated `ElectronPlatformService`
### 2. Build Configuration Confusion
- **Before**: Electron builds used `VITE_PLATFORM=capacitor`, causing confusion
- **After**: Electron builds now properly use `VITE_PLATFORM=electron`
### 3. Missing Platform Service Methods
- **Before**: Platform services lacked proper `isElectron()`, `isCapacitor()`, `isWeb()` methods
- **After**: All platform services implement complete interface with proper detection
### 4. Inconsistent Build Scripts
- **Before**: Mixed platform settings in build scripts
- **After**: Clean, consistent electron-specific build process
## Architecture Changes
### Platform Service Factory Enhancement
```typescript
// src/services/PlatformServiceFactory.ts
export class PlatformServiceFactory {
public static getInstance(): PlatformService {
const platform = process.env.VITE_PLATFORM || "web";
switch (platform) {
case "capacitor":
return new CapacitorPlatformService();
case "electron":
return new ElectronPlatformService(); // NEW
case "web":
default:
return new WebPlatformService();
}
}
}
```
### New ElectronPlatformService
- Extends `CapacitorPlatformService` for SQLite compatibility
- Overrides capabilities for desktop-specific features
- Provides proper platform detection methods
```typescript
class ElectronPlatformService extends CapacitorPlatformService {
getCapabilities() {
return {
hasFileSystem: true,
hasCamera: false, // Desktop typically doesn't have integrated cameras
isMobile: false, // Electron is desktop, not mobile
isIOS: false,
hasFileDownload: true, // Desktop supports direct file downloads
needsFileHandlingInstructions: false, // Desktop users familiar with file handling
isNativeApp: true,
};
}
isElectron(): boolean { return true; }
isCapacitor(): boolean { return false; }
isWeb(): boolean { return false; }
}
```
### Enhanced Platform Service Interface
```typescript
// src/services/PlatformService.ts
export interface PlatformService {
// Platform detection methods
isCapacitor(): boolean;
isElectron(): boolean;
isWeb(): boolean;
// ... existing methods
}
```
## Build System Improvements
### New Electron Vite Configuration
- Created `vite.config.electron.mts` for electron-specific builds
- Proper platform environment variables
- Desktop-optimized build settings
- Electron-specific entry point handling
```bash
# Before
npm run build:capacitor # Used for electron builds (confusing)
# After
npm run build:electron # Dedicated electron build
```
### Updated Build Scripts
- `package.json`: Updated electron scripts to use proper electron build
- `scripts/common.sh`: Fixed electron environment setup
- `scripts/build-electron.sh`: Updated to use electron build instead of capacitor
- `scripts/electron-dev.sh`: Updated for proper electron development workflow
### Electron-Specific Entry Point
- Created `src/main.electron.ts` for electron-specific initialization
- Automatic entry point replacement in vite builds
- Electron-specific logging and error handling
## Configuration Updates
### Vite Configuration
```typescript
// vite.config.electron.mts
export default defineConfig(async () => {
const baseConfig = await createBuildConfig("electron");
return {
...baseConfig,
plugins: [
// Plugin to replace main entry point for electron builds
{
name: 'electron-entry-point',
transformIndexHtml(html) {
return html.replace('/src/main.web.ts', '/src/main.electron.ts');
}
}
],
define: {
'process.env.VITE_PLATFORM': JSON.stringify('electron'),
'__ELECTRON__': JSON.stringify(true),
'__IS_DESKTOP__': JSON.stringify(true),
// ... other electron-specific flags
}
};
});
```
### Common Configuration Updates
```typescript
// vite.config.common.mts
const isElectron = mode === "electron";
const isNative = isCapacitor || isElectron;
// Updated environment variables and build settings for electron support
```
## Usage Guide
### Development Workflow
```bash
# Setup electron environment (first time only)
npm run electron:setup
# Development build and run
npm run electron:dev
# Alternative development workflow
npm run electron:dev-full
```
### Production Builds
```bash
# Build web assets for electron
npm run build:electron
# Build and package electron app
npm run electron:build
# Build specific package types
npm run electron:build:appimage
npm run electron:build:deb
# Using the comprehensive build script
npm run build:electron:all
```
### Platform Detection in Code
```typescript
import { PlatformServiceFactory } from '@/services/PlatformServiceFactory';
const platformService = PlatformServiceFactory.getInstance();
if (platformService.isElectron()) {
// Desktop-specific logic
console.log('Running on Electron desktop');
} else if (platformService.isCapacitor()) {
// Mobile-specific logic
console.log('Running on mobile device');
} else if (platformService.isWeb()) {
// Web-specific logic
console.log('Running in web browser');
}
// Or check capabilities
const capabilities = platformService.getCapabilities();
if (capabilities.hasFileDownload) {
// Enable direct file downloads (available on desktop)
}
```
## File Structure Changes
### New Files
- `vite.config.electron.mts` - Electron-specific Vite configuration
- `src/main.electron.ts` - Electron main entry point
- `doc/electron-cleanup-summary.md` - This documentation
### Modified Files
- `src/services/PlatformServiceFactory.ts` - Added electron platform support
- `src/services/PlatformService.ts` - Added platform detection methods
- `src/services/platforms/CapacitorPlatformService.ts` - Added missing interface methods
- `vite.config.common.mts` - Enhanced electron support
- `package.json` - Updated electron build scripts
- `scripts/common.sh` - Fixed electron environment setup
- `scripts/build-electron.sh` - Updated for electron builds
- `scripts/electron-dev.sh` - Updated development workflow
- `experiment.sh` - Updated for electron builds
## Testing
### Platform Detection Testing
```bash
# Test web platform
npm run dev
# Test electron platform
npm run electron:dev
# Verify platform detection in console logs
```
### Build Testing
```bash
# Test electron build
npm run build:electron
# Test electron packaging
npm run electron:build:appimage
# Verify platform-specific features work correctly
```
## Benefits
1. **Clear Platform Separation**: Each platform has dedicated configuration and services
2. **Consistent Build Process**: No more mixing capacitor/electron configurations
3. **Better Developer Experience**: Clear commands and proper logging
4. **Type Safety**: Complete interface implementation across all platforms
5. **Desktop Optimization**: Electron builds optimized for desktop usage patterns
6. **Maintainability**: Clean architecture makes future updates easier
## Migration Guide
For developers working with the previous implementation:
1. **Update Build Commands**:
- Replace `npm run build:capacitor` with `npm run build:electron` for electron builds
- Use `npm run electron:dev` for development
2. **Platform Detection**:
- Use `platformService.isElectron()` instead of checking environment variables
- Leverage the `getCapabilities()` method for feature detection
3. **Configuration**:
- Electron-specific settings are now in `vite.config.electron.mts`
- Environment variables are automatically set correctly
## Security Considerations
- Platform detection is based on build-time environment variables
- No runtime platform detection that could be spoofed
- Electron-specific security settings in vite configuration
- Proper isolation between platform implementations
## Performance Improvements
- Electron builds exclude web-specific dependencies (PWA, service workers)
- Desktop-optimized chunk sizes and module bundling
- Faster build times due to reduced bundle size
- Better runtime performance on desktop
## Future Enhancements
- [ ] Add Electron-specific IPC communication helpers
- [ ] Implement desktop-specific UI components
- [ ] Add Electron auto-updater integration
- [ ] Create platform-specific testing utilities
- [ ] Add desktop notification system integration

View File

@@ -1,188 +0,0 @@
# Electron Console Cleanup Summary
## Overview
This document summarizes the comprehensive changes made to reduce excessive console logging in the TimeSafari Electron application. The cleanup focused on reducing database operation noise, API configuration issues, and platform-specific logging while maintaining error visibility.
## Issues Addressed
### 1. Excessive Database Logging (Major Issue - 90% Reduction)
**Problem:** Every database operation was logging detailed parameter information, creating hundreds of lines of console output.
**Solution:** Modified `src/services/platforms/CapacitorPlatformService.ts`:
- Changed `logger.warn` to `logger.debug` for routine SQL operations
- Reduced migration logging verbosity
- Made database integrity checks use debug-level logging
- Kept error and completion messages at appropriate log levels
### 2. Enhanced Logger Configuration
**Problem:** No platform-specific logging controls, causing noise in Electron.
**Solution:** Updated `src/utils/logger.ts`:
- Added platform detection for Electron vs Web
- Suppressed debug and verbose logs for Electron
- Filtered out routine database operations from database logging
- Maintained error and warning visibility
- Added intelligent filtering for CapacitorPlatformService messages
### 3. API Configuration Issues (Major Fix)
**Problem:** Electron was trying to use local development endpoints (localhost:3000) from saved user settings, which don't exist in desktop environment, causing:
- 400 status errors from missing local development servers
- JSON parsing errors (HTML error pages instead of JSON responses)
**Solution:**
- Updated `src/constants/app.ts` to provide Electron-specific API endpoints
- **Critical Fix:** Modified `src/db/databaseUtil.ts` in `retrieveSettingsForActiveAccount()` to force Electron to use production API endpoints regardless of saved user settings
- This ensures Electron never uses localhost development servers that users might have saved
### 4. SharedArrayBuffer Logging Noise
**Problem:** Web-specific SharedArrayBuffer detection was running in Electron, creating unnecessary debug output.
**Solution:** Modified `src/main.web.ts`:
- Made SharedArrayBuffer logging conditional on web platform only
- Converted console.log statements to logger.debug
- Only show in development mode for web platform
- Reduced platform detection noise
### 5. Missing Source Maps Warnings
**Problem:** Electron DevTools was complaining about missing source maps for external dependencies.
**Solution:** Updated `vite.config.electron.mts`:
- Disabled source maps for Electron builds (`sourcemap: false`)
- Added build configuration to suppress external dependency warnings
- Prevents DevTools from looking for non-existent source map files
## Files Modified
1. **src/services/platforms/CapacitorPlatformService.ts**
- Reduced database operation logging verbosity
- Changed routine operations from `logger.warn` to `logger.debug`
- Reduced migration and integrity check logging
2. **src/utils/logger.ts**
- Added platform-specific logging controls
- Suppressed verbose logging for Electron
- Filtered database operations from logs
- Enhanced log level management
3. **src/constants/app.ts**
- Fixed API endpoints for Electron platform
- Prevented localhost API connection errors
- Configured proper production endpoints
4. **src/db/databaseUtil.ts** (Critical Fix)
- Added Electron-specific logic in `retrieveSettingsForActiveAccount()`
- Forces Electron to use production API endpoints regardless of saved settings
- Prevents localhost development server connection attempts
5. **src/main.web.ts**
- Reduced SharedArrayBuffer logging noise
- Made logging conditional on platform
- Converted console statements to logger calls
6. **vite.config.electron.mts**
- Disabled source maps for Electron builds
- Added configuration to suppress external dependency warnings
- Configured build-time warning suppression
## Impact
### Before Cleanup:
- 500+ lines of console output per minute
- Detailed SQL parameter logging for every operation
- API connection errors every few seconds (400 status, JSON parsing errors)
- SharedArrayBuffer warnings on every startup
- DevTools source map warnings
### After Cleanup:
- **~95% reduction** in console output
- Only errors and important status messages visible
- **No API connection errors** - Electron uses proper production endpoints
- **No JSON parsing errors** - API returns valid JSON responses
- Minimal startup logging
- Clean DevTools console
- Preserved all error handling and functionality
## Technical Details
### API Configuration Fix
The most critical fix was in `src/db/databaseUtil.ts` where we added:
```typescript
// **ELECTRON-SPECIFIC FIX**: Force production API endpoints for Electron
if (process.env.VITE_PLATFORM === "electron") {
const { DEFAULT_ENDORSER_API_SERVER } = await import("../constants/app");
settings = {
...settings,
apiServer: DEFAULT_ENDORSER_API_SERVER,
};
}
```
This ensures that even if users have localhost development endpoints saved in their settings, Electron will override them with production endpoints.
### Logger Enhancement
Enhanced the logger with platform-specific behavior:
```typescript
const isElectron = process.env.VITE_PLATFORM === "electron";
// Suppress verbose logging for Electron while preserving errors
if (!isElectron || !message.includes("[CapacitorPlatformService]")) {
console.warn(message, ...args);
}
```
## Testing
The changes were tested with:
- `npm run lint-fix` - 0 errors, warnings only (pre-existing)
- Electron development environment
- Web platform (unchanged functionality)
- All platform detection working correctly
## Future Improvements
1. **Conditional Compilation**: Consider using build-time flags to completely remove debug statements in production builds
2. **Structured Logging**: Implement structured logging with log levels and categories
3. **Log Rotation**: Add log file rotation for long-running Electron sessions
4. **Performance Monitoring**: Add performance logging for database operations in debug builds only
## Backward Compatibility
All changes maintain backward compatibility:
- Web platform logging unchanged
- Capacitor platform logging unchanged
- Error handling preserved
- API functionality preserved
- Database operations unchanged
## Security Audit
**No security implications** - Changes only affect logging verbosity and API endpoint selection
**No data exposure** - Actually reduces data logging
**Improved security** - Forces production API endpoints instead of potentially insecure localhost
**No authentication changes** - Platform detection only
**No database changes** - Only logging changes
## Git Commit Message
```
feat: eliminate console noise in Electron builds
- Suppress excessive database operation logging (95% reduction)
- Fix API configuration to force production endpoints for Electron
- Prevent JSON parsing errors from localhost development servers
- Reduce SharedArrayBuffer detection noise
- Disable source maps for cleaner DevTools
- Add platform-specific logger configuration
Resolves database console spam, API connection errors, and JSON parsing issues
Tests: lint passes, Web/Capacitor functionality preserved
```
## Next Steps
1. **Test the fixes** - Run `npm run electron:dev` to verify console noise is eliminated
2. **Monitor for remaining issues** - Check for any other console noise sources
3. **Performance monitoring** - Verify the reduced logging doesn't impact functionality
4. **Documentation updates** - Update any development guides that reference the old logging behavior

View File

@@ -1,83 +0,0 @@
# Error Diagnostics Log
This file tracks console errors observed during development for future investigation.
## 2025-07-07 08:56 UTC - ProjectsView.vue Migration Session
### Migration Context
- **Current Work**: Completed ProjectsView.vue Triple Migration Pattern
- **Migration Status**: 21 complete, 4 appropriately incomplete components
- **Recent Changes**:
- ProjectsView.vue: databaseUtil → PlatformServiceMixin
- Added notification constants and literal string extraction
- Template logic streamlining with computed properties
### Observed Errors
#### 1. HomeView.vue API Rate Limit Errors
```
GET https://api.endorser.ch/api/report/rateLimits 400 (Bad Request)
Source: endorserServer.ts:1494, HomeView.vue:593, HomeView.vue:742
```
**Analysis**:
- API server returning 400 for rate limit checks
- Occurs during identity initialization and registration status checks
- **Migration Impact**: None - HomeView.vue was migrated and tested earlier
- **Likely Cause**: Server-side authentication or API configuration issue
**Action Items**:
- [ ] Check endorser.ch API documentation for rate limit endpoint changes
- [ ] Verify authentication headers being sent correctly
- [ ] Consider fallback handling for rate limit API failures
#### 2. ProjectViewView.vue Project Not Found Error
```
GET https://api.endorser.ch/api/claim/byHandle/...01JY2Q5D90E8P267ABB963S71D 404 (Not Found)
Source: ProjectViewView.vue:830 loadProject() method
```
**Analysis**:
- Attempting to load project ID: `01JY2Q5D90E8P267ABB963S71D`
- **Migration Impact**: None - error handling working correctly
- **Likely Cause**: User navigated to non-existent project or stale link
**Action Items**:
- [ ] Consider adding better user messaging for missing projects
- [ ] Investigate if project IDs are being generated/stored correctly
- [ ] Add breadcrumb or "return to projects" option on 404s
#### 3. Axios Request Stack Traces
Multiple stack traces showing Vue router navigation and component mounting cycles.
**Analysis**:
- Normal Vue.js lifecycle and routing behavior
- No obvious memory leaks or infinite loops
- **Migration Impact**: None - expected framework behavior
### System Health Indicators
#### ✅ Working Correctly
- Database migrations: `Migration process complete! Summary: 0 applied, 2 skipped`
- Platform service factory initialization: `Creating singleton instance for platform: development`
- SQL worker loading: `Worker loaded, ready to receive messages`
- Database connection: `Opened!`
#### 🔄 For Investigation
- API authentication/authorization with endorser.ch
- Project ID validation and error handling
- Rate limiting strategy
### Migration Validation
- **ProjectsView.vue**: Appropriately incomplete (3 helpers + 1 complex modal)
- **Error Handling**: Migrated components showing proper error handling
- **No Migration-Related Errors**: All errors appear to be infrastructure/data issues
### Next Steps
1. Continue migration slog with next component
2. Monitor these same error patterns in future sessions
3. Address API/server issues in separate debugging session
---
*Log Entry by: Migration Assistant*
*Session: ProjectsView.vue Triple Migration Pattern*

View File

@@ -1,180 +0,0 @@
# Image Hosting Guide for Cross-Origin Isolated Environment
## Quick Reference
### ✅ Supported Image Sources (Work in Development)
| Service | Proxy Endpoint | Example URL |
|---------|---------------|-------------|
| TimeSafari | `/image-proxy/` | `https://image.timesafari.app/abc123.jpg` |
| Flickr | `/flickr-proxy/` | `https://live.staticflickr.com/123/456.jpg` |
| Imgur | `/imgur-proxy/` | `https://i.imgur.com/example.jpg` |
| GitHub Raw | `/github-proxy/` | `https://raw.githubusercontent.com/user/repo/main/image.png` |
| Unsplash | `/unsplash-proxy/` | `https://images.unsplash.com/photo-123456` |
| Facebook | `/facebook-proxy/` | `https://www.facebook.com/images/groups/...` |
| Medium | `/medium-proxy/` | `https://miro.medium.com/v2/resize:fit:180/...` |
| Meetup | `/meetup-proxy/` | `https://secure.meetupstatic.com/photos/...` |
### ⚠️ Problematic Image Sources (May Not Work in Development)
- Random external websites without CORS headers
- WordPress uploads from arbitrary domains
- Custom CDNs without proper CORS configuration
- Any service that doesn't send `Cross-Origin-Resource-Policy: cross-origin`
## Why This Happens
In development mode, we enable SharedArrayBuffer for fast SQLite operations, which requires:
- `Cross-Origin-Opener-Policy: same-origin`
- `Cross-Origin-Embedder-Policy: require-corp`
These headers create a **cross-origin isolated environment** that blocks resources unless they have proper CORS headers.
## Solutions
### 1. Use Supported Image Hosting Services
**Recommended services that work well:**
- **Imgur**: Free, no registration required, direct links
- **GitHub**: If you have images in repositories
- **Unsplash**: For stock photos
- **TimeSafari Image Server**: For app-specific images
### 2. Add New Image Hosting Proxies
If you frequently use images from a specific domain, add a proxy:
#### Step 1: Add Proxy to `vite.config.common.mts`
```typescript
'/yourservice-proxy': {
target: 'https://yourservice.com',
changeOrigin: true,
secure: true,
followRedirects: true,
rewrite: (path) => path.replace(/^\/yourservice-proxy/, ''),
configure: (proxy) => {
proxy.on('proxyRes', (proxyRes, req, res) => {
proxyRes.headers['Access-Control-Allow-Origin'] = '*';
proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS';
proxyRes.headers['Cross-Origin-Resource-Policy'] = 'cross-origin';
});
}
}
```
#### Step 2: Update Transform Function in `src/libs/util.ts`
```typescript
// Transform YourService URLs to use proxy
if (imageUrl.startsWith("https://yourservice.com/")) {
const imagePath = imageUrl.replace("https://yourservice.com/", "");
return `/yourservice-proxy/${imagePath}`;
}
```
### 3. Use Alternative Image Sources
For frequently failing domains, consider:
- Upload images to Imgur or GitHub
- Use a CDN with proper CORS headers
- Host images on your own domain with CORS enabled
## Development vs Production
### Development Mode
- Images from supported services work through proxies
- Unsupported images may fail to load
- Console warnings show which images have issues
### Production Mode
- All images load directly without proxies
- No CORS restrictions in production
- Better performance without proxy overhead
## Testing Image Sources
### Check if an Image Source Works
```bash
# Test in browser console:
fetch('https://example.com/image.jpg', { mode: 'cors' })
.then(response => console.log('✅ Works:', response.status))
.catch(error => console.log('❌ Blocked:', error));
```
### Visual Testing
```typescript
import { createTestImageElements } from './libs/test-cors-images';
createTestImageElements(); // Creates visual test panel
```
## Common Error Messages
### `ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep`
**Cause**: Image source doesn't send required CORS headers
**Solution**: Use a supported image hosting service or add a proxy
### `ERR_NETWORK` or `ERR_INTERNET_DISCONNECTED`
**Cause**: Proxy service is unavailable
**Solution**: Check internet connection or use alternative image source
### Images Load in Production but Not Development
**Cause**: Normal behavior - development has stricter CORS requirements
**Solution**: Use supported image sources for development testing
## Best Practices
### For New Projects
1. Use supported image hosting services from the start
2. Upload user images to Imgur or similar service
3. Host critical images on your own domain with CORS enabled
### For Existing Projects
1. Identify frequently used image domains in console warnings
2. Add proxies for the most common domains
3. Gradually migrate to supported image hosting services
### For User-Generated Content
1. Provide upload functionality to supported services
2. Validate image URLs against supported domains
3. Show helpful error messages for unsupported sources
## Troubleshooting
### Image Not Loading?
1. Check browser console for error messages
2. Verify the domain is in the supported list
3. Test if the image loads in production mode
4. Consider adding a proxy for that domain
### Proxy Not Working?
1. Check if the target service allows proxying
2. Verify CORS headers are being set correctly
3. Test with a simpler image URL from the same domain
### Performance Issues?
1. Proxies add latency in development only
2. Production uses direct image loading
3. Consider using a local image cache for development
## Quick Fixes
### For Immediate Issues
```typescript
// Temporary fallback: disable CORS headers for testing
// In vite.config.common.mts, comment out:
// headers: {
// 'Cross-Origin-Opener-Policy': 'same-origin',
// 'Cross-Origin-Embedder-Policy': 'require-corp'
// },
```
**Note**: This disables SharedArrayBuffer performance benefits.
### For Long-term Solution
- Use supported image hosting services
- Add proxies for frequently used domains
- Migrate critical images to your own CORS-enabled CDN
## Summary
The cross-origin isolated environment is necessary for SharedArrayBuffer performance but requires careful image source management. Use the supported services, add proxies for common domains, and accept that some external images may not work in development mode.
This is a development-only limitation - production deployments work with any image source.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 140 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 463 KiB

View File

@@ -1,243 +0,0 @@
# Migration Fence Definition: Dexie to SQLite
## Overview
This document defines the **migration fence** - the boundary between the legacy Dexie (IndexedDB) storage system and the new SQLite-based storage system in TimeSafari. The fence ensures controlled migration while maintaining data integrity and application stability.
**⚠️ UPDATE**: The migration fence is now implemented through the **PlatformServiceMixin** rather than a `USE_DEXIE_DB` constant. This provides a cleaner, more maintainable approach to database access control.
## Current Migration Status
### ✅ Completed Components
- **SQLite Database Service**: Fully implemented with absurd-sql
- **Platform Service Layer**: Unified database interface across platforms
- **PlatformServiceMixin**: Centralized database access with caching and utilities
- **Migration Tools**: Data comparison and transfer utilities
- **Schema Migration**: Complete table structure migration
- **Data Export/Import**: Backup and restore functionality
### 🔄 Active Migration Components
- **Settings Migration**: Core user settings transferred
- **Account Migration**: Identity and key management
- **Contact Migration**: User contact data (via import interface)
- **DatabaseUtil Migration**: Moving functions to PlatformServiceMixin
### ❌ Legacy Components (Fence Boundary)
- **Dexie Database**: Legacy IndexedDB storage (disabled by default)
- **Dexie-Specific Code**: Direct database access patterns
- **Legacy Migration Paths**: Old data transfer methods
## Migration Fence Definition
### 1. PlatformServiceMixin Boundary
```typescript
// src/utils/PlatformServiceMixin.ts
export const PlatformServiceMixin = {
computed: {
platformService(): PlatformService {
// FENCE: All database operations go through platform service
// No direct Dexie access outside migration tools
return PlatformServiceFactory.getInstance();
}
}
}
```
**Fence Rule**: All database operations must use:
- `this.$db()` for read operations
- `this.$exec()` for write operations
- `this.$settings()` for settings access
- `this.$contacts()` for contact access
- No direct `db.` or `accountsDBPromise` access in application code
### 2. Service Layer Boundary
```typescript
// src/services/PlatformServiceFactory.ts
export class PlatformServiceFactory {
public static getInstance(): PlatformService {
// FENCE: All database operations go through platform service
// No direct Dexie access outside migration tools
}
}
```
**Fence Rule**: All database operations must use:
- `PlatformService.dbQuery()` for read operations
- `PlatformService.dbExec()` for write operations
- No direct `db.` or `accountsDBPromise` access in application code
### 3. Data Access Patterns
#### ✅ Allowed (Inside Fence)
```typescript
// Use PlatformServiceMixin for all database operations
const contacts = await this.$contacts();
const settings = await this.$settings();
const result = await this.$db("SELECT * FROM contacts WHERE did = ?", [accountDid]);
```
#### ❌ Forbidden (Outside Fence)
```typescript
// Direct Dexie access (legacy pattern)
const contacts = await db.contacts.where('did').equals(accountDid).toArray();
// Direct database reference
const result = await accountsDBPromise;
```
### 4. Migration Tool Boundary
```typescript
// src/services/indexedDBMigrationService.ts
// FENCE: Only migration tools can access both databases
export async function compareDatabases(): Promise<DataComparison> {
// This is the ONLY place where both databases are accessed
}
```
**Fence Rule**: Migration tools are the exclusive interface between:
- Legacy Dexie database
- New SQLite database
- Data comparison and transfer operations
## Migration Fence Guidelines
### 1. Code Development Rules
#### New Feature Development
- **Always** use `PlatformServiceMixin` for database operations
- **Never** import or reference Dexie directly
- **Always** use mixin methods like `this.$settings()`, `this.$contacts()`
#### Legacy Code Maintenance
- **Only** modify Dexie code for migration purposes
- **Always** add migration tests for schema changes
- **Never** add new Dexie-specific features
### 2. Data Integrity Rules
#### Migration Safety
- **Always** create backups before migration
- **Always** verify data integrity after migration
- **Never** delete legacy data until verified
#### Rollback Strategy
- **Always** maintain ability to rollback to Dexie
- **Always** preserve migration logs
- **Never** assume migration is irreversible
### 3. Testing Requirements
#### Migration Testing
```typescript
// Required test pattern for migration
describe('Database Migration', () => {
it('should migrate data without loss', async () => {
// 1. Create test data in Dexie
// 2. Run migration
// 3. Verify data integrity in SQLite
// 4. Verify PlatformServiceMixin access
});
});
```
#### Application Testing
```typescript
// Required test pattern for application features
describe('Feature with Database', () => {
it('should work with PlatformServiceMixin', async () => {
// Test with PlatformServiceMixin methods
// Verify all operations use mixin methods
});
});
```
## Migration Fence Enforcement
### 1. Static Analysis
#### ESLint Rules
```json
{
"rules": {
"no-restricted-imports": [
"error",
{
"patterns": [
{
"group": ["../db/index"],
"message": "Use PlatformServiceMixin instead of direct Dexie access"
}
]
}
]
}
}
```
#### TypeScript Rules
```json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true
}
}
```
### 2. Runtime Checks
#### Development Mode Validation
```typescript
// Development-only fence validation
if (import.meta.env.DEV) {
console.warn('⚠️ Using PlatformServiceMixin for all database operations');
}
```
#### Production Safety
```typescript
// Production fence enforcement
if (import.meta.env.PROD) {
// All database operations must go through PlatformServiceMixin
// Direct Dexie access is not allowed
}
```
## Migration Status Checklist
### ✅ Completed
- [x] PlatformServiceMixin implementation
- [x] SQLite database service
- [x] Migration tools
- [x] Settings migration
- [x] Account migration
- [x] ActiveDid migration
### 🔄 In Progress
- [ ] Contact migration
- [ ] DatabaseUtil to PlatformServiceMixin migration
- [ ] File-by-file migration
### ❌ Not Started
- [ ] Legacy Dexie removal
- [ ] Final cleanup and validation
## Benefits of PlatformServiceMixin Approach
1. **Centralized Access**: Single point of control for all database operations
2. **Caching**: Built-in caching for performance optimization
3. **Type Safety**: Enhanced TypeScript integration
4. **Error Handling**: Consistent error handling across components
5. **Code Reduction**: Up to 80% reduction in database boilerplate
6. **Maintainability**: Single source of truth for database patterns
---
**Author**: Matthew Raymer
**Created**: 2025-07-05
**Status**: Active Migration Phase
**Last Updated**: 2025-07-05
**Note**: Migration fence now implemented through PlatformServiceMixin instead of USE_DEXIE_DB constant

View File

@@ -1,424 +0,0 @@
# Migration Progress Tracker: PlatformServiceMixin & 52-File Migration
## Per-File Migration Workflow (MANDATORY)
For each file migrated:
1. **First**, migrate to PlatformServiceMixin (replace all databaseUtil usage, etc.).
2. **Immediately after**, standardize notify helper usage (property + created() pattern) and fix any related linter/type errors.
**This two-step process is to be followed for every file, not as a global sweep at the end.**
Anyone picking up this migration should follow this workflow for consistency and completeness.
---
## Overview
This document tracks the progress of the 2-day sprint to complete PlatformServiceMixin implementation and migrate all 52 files from databaseUtil imports to PlatformServiceMixin usage.
**Last Updated**: $(date)
**Current Phase**: ✅ **DAY 1 COMPLETE** - PlatformServiceMixin Circular Dependency Resolved
**Overall Progress**: 69% (64/92 components migrated)
---
## ✅ **DAY 1: PlatformServiceMixin Completion (COMPLETE)**
### **Phase 1: Remove Circular Dependency (COMPLETE)**
**Status**: ✅ **COMPLETE**
**Issue**: PlatformServiceMixin imports `memoryLogs` from databaseUtil
**Solution**: Create self-contained memoryLogs implementation
#### **Tasks**:
- [x] **Step 1.1**: Remove `memoryLogs` import from PlatformServiceMixin.ts ✅
- [x] **Step 1.2**: Add self-contained `_memoryLogs` array to PlatformServiceMixin ✅
- [x] **Step 1.3**: Add `$appendToMemoryLogs()` method to PlatformServiceMixin ✅
- [x] **Step 1.4**: Update logger.ts to use self-contained memoryLogs ✅
- [x] **Step 1.5**: Test memoryLogs functionality ✅
#### **Files Modified**:
- `src/utils/PlatformServiceMixin.ts`
- `src/utils/logger.ts`
#### **Validation**:
- [x] No circular dependency errors ✅
- [x] memoryLogs functionality works correctly ✅
- [x] Linting passes ✅
---
### **Phase 2: Add Missing Utility Functions (COMPLETE)**
**Status**: ✅ **COMPLETE**
**Missing Functions**: `generateInsertStatement`, `generateUpdateStatement`
#### **Tasks**:
- [x] **Step 2.1**: Add `_generateInsertStatement()` private method to PlatformServiceMixin ✅
- [x] **Step 2.2**: Add `_generateUpdateStatement()` private method to PlatformServiceMixin ✅
- [x] **Step 2.3**: Add `$generateInsertStatement()` public wrapper method ✅
- [x] **Step 2.4**: Add `$generateUpdateStatement()` public wrapper method ✅
- [x] **Step 2.5**: Test both utility functions ✅
#### **Files Modified**:
- `src/utils/PlatformServiceMixin.ts`
#### **Validation**:
- [x] Both functions generate correct SQL ✅
- [x] Parameter handling works correctly ✅
- [x] Type safety maintained ✅
---
### **Phase 3: Update Type Definitions (COMPLETE)**
**Status**: ✅ **COMPLETE**
**Goal**: Add new methods to TypeScript interfaces
#### **Tasks**:
- [x] **Step 3.1**: Add new methods to `IPlatformServiceMixin` interface ✅
- [x] **Step 3.2**: Add new methods to `ComponentCustomProperties` interface ✅
- [x] **Step 3.3**: Verify TypeScript compilation ✅
#### **Files Modified**:
- `src/utils/PlatformServiceMixin.ts` (interface definitions) ✅
#### **Validation**:
- [x] TypeScript compilation passes ✅
- [x] All new methods properly typed ✅
- [x] No type errors in existing code ✅
---
### **Phase 4: Testing & Validation (COMPLETE)**
**Status**: ✅ **COMPLETE**
**Goal**: Ensure PlatformServiceMixin is fully functional
#### **Tasks**:
- [x] **Step 4.1**: Create test component to verify all methods ✅
- [x] **Step 4.2**: Run comprehensive linting ✅
- [x] **Step 4.3**: Run TypeScript type checking ✅
- [x] **Step 4.4**: Test caching functionality ✅
- [x] **Step 4.5**: Test database operations ✅
#### **Validation**:
- [x] All tests pass ✅
- [x] No linting errors ✅
- [x] No TypeScript errors ✅
- [x] Caching works correctly ✅
- [x] Database operations work correctly ✅
---
### **Phase 5: Utility Files Migration (COMPLETE)**
**Status**: ✅ **COMPLETE**
**Goal**: Remove all remaining databaseUtil imports from utility files
#### **Tasks**:
- [x] **Step 5.1**: Migrate `src/services/deepLinks.ts`
- Replaced `logConsoleAndDb` with `console.error`
- Removed databaseUtil import
- [x] **Step 5.2**: Migrate `src/libs/util.ts`
- Added self-contained `parseJsonField()` and `mapQueryResultToValues()` functions
- Replaced all databaseUtil calls with PlatformServiceFactory usage
- Updated all async calls to use proper async pattern
- [x] **Step 5.3**: Verify no remaining databaseUtil imports ✅
#### **Validation**:
- [x] No databaseUtil imports in any TypeScript files ✅
- [x] No databaseUtil imports in any Vue files ✅
- [x] All functions work correctly ✅
---
## 🎯 **DAY 2: Migrate All 52 Files (READY TO START)**
### **Migration Strategy**
**Priority Order**:
1. **Views** (25 files) - User-facing components
2. **Components** (15 files) - Reusable UI components
3. **Services** (8 files) - Business logic
4. **Utils** (4 files) - Utility functions
### **Migration Pattern for Each File**
```typescript
// 1. Add PlatformServiceMixin
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
export default class ComponentName extends Vue {
mixins = [PlatformServiceMixin];
}
// 2. Replace databaseUtil imports
// Remove: import { ... } from "@/db/databaseUtil";
// Use mixin methods instead
// 3. Update method calls
// Before: generateInsertStatement(contact, 'contacts')
// After: this.$generateInsertStatement(contact, 'contacts')
```
### **Common Replacements**
- `generateInsertStatement``this.$generateInsertStatement`
- `generateUpdateStatement``this.$generateUpdateStatement`
- `parseJsonField``this._parseJsonField`
- `mapColumnsToValues``this._mapColumnsToValues`
- `logToDb``this.$log`
- `logConsoleAndDb``this.$logAndConsole`
- `memoryLogs``this.$memoryLogs`
---
## 📋 **File Migration Checklist**
### **Views (25 files) - Priority 1**
**Progress**: 6/25 (24%)
- [ ] QuickActionBvcEndView.vue
- [ ] ProjectsView.vue
- [x] ClaimCertificateView.vue ✅ **MIGRATED & HUMAN TESTED**
- [ ] NewEditAccountView.vue
- [ ] OnboardMeetingSetupView.vue
- [ ] SearchAreaView.vue
- [ ] TestView.vue
- [ ] InviteOneView.vue
- [ ] IdentitySwitcherView.vue
- [ ] HelpNotificationsView.vue
- [ ] StartView.vue
- [ ] OfferDetailsView.vue
- [ ] ContactEditView.vue
- [ ] SharedPhotoView.vue
- [x] ContactQRScanShowView.vue ✅ **MIGRATED & HUMAN TESTED**
- [ ] ContactGiftingView.vue
- [x] DiscoverView.vue ✅ **MIGRATED & HUMAN TESTED**
- [ ] ImportAccountView.vue
- [ ] ConfirmGiftView.vue
- [ ] SeedBackupView.vue
- [ ] ContactAmountsView.vue
- [x] ContactQRScanFullView.vue ✅ **MIGRATED & HUMAN TESTED**
- [ ] ContactsView.vue
- [ ] DIDView.vue
- [ ] GiftedDetailsView.vue
- [x] HelpView.vue ✅ **MIGRATED & HUMAN TESTED**
- [ ] ImportDerivedAccountView.vue
- [ ] InviteOneAcceptView.vue
- [ ] NewActivityView.vue
- [x] NewEditProjectView.vue ✅ **MIGRATED**
- [ ] OnboardMeetingListView.vue
- [ ] OnboardMeetingMembersView.vue
- [ ] ProjectViewView.vue
- [ ] QuickActionBvcBeginView.vue
- [ ] RecentOffersToUserProjectsView.vue
- [ ] RecentOffersToUserView.vue
- [ ] UserProfileView.vue
### **Components (15 files) - Priority 2**
**Progress**: 9/15 (60%)
- [x] UserNameDialog.vue ✅ **MIGRATED**
- [x] AmountInput.vue ✅ **REVIEWED (no migration needed)**
- Pure UI component, no databaseUtil or notification usage.
- [x] ImageMethodDialog.vue ✅ **MIGRATED & HUMAN TESTED**
- Completed 2025-07-09 07:04 AM UTC (19 minutes)
- All 4 phases completed: Database migration, SQL abstraction, notification standardization, template streamlining
- 20 long CSS classes extracted to computed properties
- [x] ChoiceButtonDialog.vue ✅ MIGRATED 2025-07-09 (7 min, all phases complete, template streamlined, no DB/SQL needed)
- [x] ContactNameDialog.vue ✅ MIGRATED 2025-07-09 (2 min, all phases complete, template streamlined, no DB/SQL needed)
- [x] DataExportSection.vue ✅ MIGRATED & HUMAN TESTED 2025-07-09 (3 min, all phases complete, template streamlined, already had DB/notifications)
- [x] EntityGrid.vue ✅ MIGRATED 2024-12-19 (3 min, Phase 4 only - template streamlined, no DB/SQL needed)
- [x] EntityIcon.vue ✅ MIGRATED & HUMAN TESTED 2024-12-19 (2 min, documentation enhancement, no DB/SQL needed)
- [x] EntitySelectionStep.vue ✅ MIGRATED & HUMAN TESTED 2024-12-19 (3 min, Phase 4 only - template streamlined, no DB/SQL needed)
- [x] EntitySummaryButton.vue ✅ MIGRATED & HUMAN TESTED 2024-12-19 (3 min, Phase 4 only - template streamlined, no DB/SQL needed)
- [x] FeedFilters.vue ✅ **MIGRATED**
- [x] GiftDetailsStep.vue ✅ MIGRATED & HUMAN TESTED 2024-12-19 (4 min, Phase 4 only - template streamlined, no DB/SQL needed)
- [x] GiftedDialog.vue ✅ **MIGRATED**
- [x] GiftedPrompts.vue ✅ MIGRATED & HUMAN TESTED 2024-12-19 (3 min, Phase 4 only - template streamlined, no DB/SQL needed)
- [x] HiddenDidDialog.vue ✅ MIGRATED & HUMAN TESTED 2024-12-19 (5 min, Phase 3 & 4 - notification modernized, template streamlined, no DB/SQL needed)
- [x] IconRenderer.vue ✅ MIGRATED & HUMAN TESTED 2024-12-19 (0 min, no migration needed - already compliant)
### **Services (8 files) - Priority 3**
**Progress**: 2/8 (25%)
- [x] api.ts ✅ MIGRATED 2024-12-19 (0 min, no migration needed - already compliant)
- [x] endorserServer.ts ✅ MIGRATED 2024-12-19 (35 min, all phases complete - database, SQL, notification migration)
- [ ] partnerServer.ts
- [ ] deepLinks.ts
### **Utils (4 files) - Priority 4**
**Progress**: 1/4 (25%)
- [ ] LogCollector.ts
- [x] util.ts ✅ MIGRATED 2024-12-19 (no migration needed, utility module decoupled from Vue, reviewed and confirmed)
- [x] test/index.ts ✅ MIGRATED 2024-12-19 (5 min, database migration with dynamic import pattern, enhanced documentation)
- [ ] PlatformServiceMixin.ts (remove circular dependency)
---
## 🛠️ **Migration Tools**
### **Migration Helper Script**
```bash
# Track progress
./scripts/migration-helper.sh progress
# Show remaining files
./scripts/migration-helper.sh files
# Show replacement patterns
./scripts/migration-helper.sh patterns
# Show migration template
./scripts/migration-helper.sh template
# Validate migration
./scripts/migration-helper.sh validate
# Show next steps
./scripts/migration-helper.sh next
# Run all checks
./scripts/migration-helper.sh all
```
### **Validation Commands**
```bash
# Check for remaining databaseUtil imports
find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil"
# Run linting
npm run lint
# Run type checking
npx tsc --noEmit
# Count remaining files
find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" | wc -l
```
---
## 📊 **Progress Tracking**
### **Day 1 Progress**
- [ ] Phase 1: Circular dependency resolved
- [ ] Phase 2: Utility functions added
- [ ] Phase 3: Type definitions updated
- [ ] Phase 4: Testing completed
### **Day 2 Progress**
- [ ] Views migrated (0/25)
- [ ] Components migrated (0/15)
- [ ] Services migrated (0/8)
- [ ] Utils migrated (0/4)
- [ ] Validation completed
### **Overall Progress**
- **Total files to migrate**: 52
- **Files migrated**: 3
- **Progress**: 6%
---
## 🎯 **Success Criteria**
### **Day 1 Success Criteria**
- [ ] PlatformServiceMixin has no circular dependencies
- [ ] All utility functions implemented and tested
- [ ] Type definitions complete and accurate
- [ ] Linting passes with no errors
- [ ] TypeScript compilation passes
### **Day 2 Success Criteria**
- [ ] 0 files importing databaseUtil
- [ ] All 52 files migrated to PlatformServiceMixin
- [ ] No runtime errors in migrated components
- [ ] All tests passing
- [ ] Performance maintained or improved
### **Overall Success Criteria**
- [ ] Complete elimination of databaseUtil dependency
- [ ] PlatformServiceMixin is the single source of truth for database operations
- [ ] Migration fence is fully implemented
- [ ] Ready for Phase 3: Cleanup and Optimization
---
## 🚀 **Post-Migration Benefits**
1. **80% reduction** in database boilerplate code
2. **Centralized caching** for improved performance
3. **Type-safe** database operations
4. **Eliminated circular dependencies**
5. **Simplified testing** with mockable mixin
6. **Consistent error handling** across all components
7. **Ready for SQLite-only mode**
---
## 📝 **Notes & Issues**
### **Current Issues**
- None identified yet
### **Decisions Made**
- PlatformServiceMixin approach chosen over USE_DEXIE_DB constant
- Self-contained utility functions preferred over imports
- Priority order: Views → Components → Services → Utils
### **Lessons Learned**
- To be filled as migration progresses
---
## 🔄 **Daily Updates**
### **Day 1 Updates**
- [ ] Start time: _____
- [ ] Phase 1 completion: _____
- [ ] Phase 2 completion: _____
- [ ] Phase 3 completion: _____
- [ ] Phase 4 completion: _____
- [ ] End time: _____
### **Day 2 Updates**
- [ ] Start time: _____
- [ ] Views migration completion: _____
- [ ] Components migration completion: _____
- [ ] Services migration completion: _____
- [ ] Utils migration completion: _____
- [ ] Final validation completion: _____
- [ ] End time: _____
---
## 🆘 **Contingency Plans**
### **If Day 1 Takes Longer**
- Focus on core functionality first
- Defer advanced utility functions to Day 2
- Prioritize circular dependency resolution
### **If Day 2 Takes Longer**
- Focus on high-impact views first
- Batch similar components together
- Use automated scripts for common patterns
### **If Issues Arise**
- Document specific problems in Notes section
- Create targeted fixes
- Maintain backward compatibility during transition
---
## 🎯 **Notification Best Practices and Nuances**
- **All user-facing notification messages must be defined as constants** in `src/constants/notifications.ts`. Do not hardcode notification strings in components.
- **All notification durations/timeouts must use the `TIMEOUTS` constants** from `src/utils/notify.ts`. Do not hardcode durations.
- **Notification helpers (`this.notify`) must be initialized as a property in `created()`** using `createNotifyHelpers(this.$notify)`.
- **Never hardcode notification strings or durations in components.**
- **When using `notifyWhyCannotConfirm` or similar utilities, pass a wrapper function** if the signature expects a raw notify function (e.g., `(msg, timeout) => this.notify.info(msg.text ?? '', timeout)`).
- **Declare `$notify` as a property on the class** to satisfy the type checker, since Vue injects it at runtime.
- **Use type guards or `as any` for unknown notification payloads** when necessary, but prefer type safety where possible.
These practices ensure maintainability, consistency, and type safety for all notification-related code during and after migration.
---
**Last Updated**: $(date)
**Next Review**: After each phase completion

Some files were not shown because too many files have changed in this diff Show More