Browse Source

Merge branch 'master' into units-mocking

pull/153/head
Matthew Raymer 22 hours ago
parent
commit
552002b9a2
  1. 65
      .cursor/rules/adr_template.mdc
  2. 352
      .cursor/rules/app/architectural_decision_record.mdc
  3. 181
      .cursor/rules/app/timesafari.mdc
  4. 287
      .cursor/rules/architectural_decision_record.mdc
  5. 75
      .cursor/rules/architecture/README.md
  6. 295
      .cursor/rules/architecture/build_architecture_guard.mdc
  7. 61
      .cursor/rules/asset_configuration.mdc
  8. 154
      .cursor/rules/base_context.mdc
  9. 48
      .cursor/rules/database/absurd-sql.mdc
  10. 8
      .cursor/rules/database/legacy_dexie.mdc
  11. 9
      .cursor/rules/development/development_guide.mdc
  12. 139
      .cursor/rules/development/type_safety_guide.mdc
  13. 35
      .cursor/rules/development_guide.mdc
  14. 14
      .cursor/rules/docs/documentation.mdc
  15. 79
      .cursor/rules/docs/markdown-automation.mdc
  16. 54
      .cursor/rules/docs/markdown.mdc
  17. 6
      .cursor/rules/features/camera-implementation.mdc
  18. 206
      .cursor/rules/harbor_pilot_universal.mdc
  19. 236
      .cursor/rules/historical_comment_management.mdc
  20. 117
      .cursor/rules/investigation_report_example.mdc
  21. 6
      .cursor/rules/legacy_dexie.mdc
  22. 222
      .cursor/rules/logging_standards.mdc
  23. 348
      .cursor/rules/realistic_time_estimation.mdc
  24. 174
      .cursor/rules/research_diagnostic.mdc
  25. 225
      .cursor/rules/software_development.mdc
  26. 329
      .cursor/rules/time.mdc
  27. 276
      .cursor/rules/timesafari.mdc
  28. 335
      .cursor/rules/workflow/version_control.mdc
  29. 2
      .dockerignore
  30. 8
      .env.development
  31. 3
      .env.production
  32. 5
      .env.test
  33. 2
      .eslintrc.js
  34. 27
      .github/workflows/playwright.yml
  35. 12
      .gitignore
  36. 40
      .husky/_/husky.sh
  37. 10
      .husky/commit-msg
  38. 15
      .husky/pre-commit
  39. 27
      .husky/pre-push
  40. 1
      .node-version
  41. 1
      .nvmrc
  42. 1145
      BUILDING.md
  43. 59
      CHANGELOG.md
  44. 290
      README-BUILD-GUARD.md
  45. 82
      README-PR-TEMPLATE.md
  46. 237
      README.md
  47. 8
      TASK_storage.md
  48. 12
      android/app/build.gradle
  49. 7
      android/app/src/main/assets/capacitor.config.json
  50. 7
      android/app/src/main/res/values/colors.xml
  51. 2
      android/build.gradle
  52. 2
      android/gradle.properties
  53. 4
      android/variables.gradle
  54. 2
      assets/README.md
  55. 34
      capacitor-assets.config.json
  56. 5
      capacitor.config.json
  57. 116
      capacitor.config.ts
  58. 32
      config/assets/capacitor-assets.config.json
  59. 119
      config/assets/schema.json
  60. 3
      doc/DEEP_LINKS.md
  61. 3
      doc/README.md
  62. 215
      doc/asset-migration-plan.md
  63. 8
      doc/build-modernization-context.md
  64. 17
      doc/circular-dependency-analysis.md
  65. 14
      doc/component-communication-guide.md
  66. 14
      doc/cors-disabled-for-universal-images.md
  67. 26
      doc/cors-image-loading-solution.md
  68. 1
      doc/database-migration-guide.md
  69. 187
      doc/debug-hook-guide.md
  70. 6
      doc/electron-cleanup-summary.md
  71. 21
      doc/electron-console-cleanup.md
  72. 13
      doc/error-diagnostics-log.md
  73. 21
      doc/image-hosting-guide.md
  74. 119
      doc/logging-configuration.md
  75. 21
      doc/migration-fence-definition.md
  76. 69
      doc/migration-progress-tracker.md
  77. 1
      doc/migration-quick-reference.md
  78. 31
      doc/migration-readiness-summary.md
  79. 31
      doc/migration-roadmap-next-steps.md
  80. 29
      doc/migration-to-wa-sqlite.md
  81. 29
      doc/platformservicemixin-completion-plan.md
  82. 28
      doc/qr-code-implementation-guide.md
  83. 9
      doc/secure-storage-implementation.md
  84. 14
      doc/sharebufferarray_spectre_security.md
  85. 29
      doc/storage-implementation-checklist.md
  86. 11
      doc/usage-guide.md
  87. 32
      docker/README.md
  88. 115
      docs/README.md
  89. 405
      docs/build-system/automation/auto-run-guide.md
  90. 379
      docs/build-system/automation/cefpython-implementation-guide.md
  91. 616
      docs/build-system/core/build-pattern-conversion-plan.md
  92. 470
      docs/build-system/core/build-systems-overview.md
  93. 722
      docs/build-system/core/build-troubleshooting.md
  94. 363
      docs/build-system/core/build-web-script-integration.md
  95. 594
      docs/build-system/core/electron-build-patterns.md
  96. 422
      docs/build-system/platforms/android-build-scripts.md
  97. 146
      docs/build-system/platforms/database-clearing.md
  98. 174
      docs/build-system/platforms/electron-auto-updates.md
  99. 181
      docs/build-system/platforms/electron-build-scripts.md
  100. 436
      docs/build-system/platforms/ios-build-scripts.md

65
.cursor/rules/adr_template.mdc

@ -0,0 +1,65 @@
# ADR Template
## ADR-XXXX-YY-ZZ: [Short Title]
**Date:** YYYY-MM-DD
**Status:** [PROPOSED | ACCEPTED | REJECTED | DEPRECATED | SUPERSEDED]
**Deciders:** [List of decision makers]
**Technical Story:** [Link to issue/PR if applicable]
## Context
[Describe the forces at play, including technological, political, social, and
project local. These forces are probably in tension, and should be called out as
such. The language in this section is value-neutral. It is simply describing facts.]
## Decision
[Describe our response to these forces. We will use the past tense ("We will...").]
## Consequences
### Positive
- [List positive consequences]
### Negative
- [List negative consequences or trade-offs]
### Neutral
- [List neutral consequences or notes]
## Alternatives Considered
- **Alternative 1:** [Description] - [Why rejected]
- **Alternative 2:** [Description] - [Why rejected]
- **Alternative 3:** [Description] - [Why rejected]
## Implementation Notes
[Any specific implementation details, migration steps, or technical considerations]
## References
- [Link to relevant documentation]
- [Link to related ADRs]
- [Link to external resources]
## Related Decisions
- [List related ADRs or decisions]
---
## Usage Guidelines
1. **Copy this template** for new ADRs
2. **Number sequentially** (ADR-001, ADR-002, etc.)
3. **Use descriptive titles** that clearly indicate the decision
4. **Include all stakeholders** in the deciders list
5. **Link to related issues** and documentation
6. **Update status** as decisions evolve
7. **Store in** `doc/architecture-decisions/` directory
description:
globs:
alwaysApply: false
---

352
.cursor/rules/app/architectural_decision_record.mdc

@ -0,0 +1,352 @@
---
description: when you need to understand the system architecture or make changes that impact the system architecture
alwaysApply: false
---
# TimeSafari Cross-Platform Architecture Guide
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Architecture guidelines
## 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
### 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
└── assets/ # Static assets
```
### Entry Points
- `main.ts` → Base entry
- `main.common.ts` → Shared init
- `main.capacitor.ts` → Mobile entry
- `main.electron.ts` → Electron entry
- `main.web.ts` → Web entry
## 3. Service Architecture
### Service Organization
```tree
services/
├── QRScanner/
│ ├── WebInlineQRScanner.ts
│ └── interfaces.ts
├── platforms/
│ ├── WebPlatformService.ts
│ ├── CapacitorPlatformService.ts
│ └── ElectronPlatformService.ts
└── factory/
└── PlatformServiceFactory.ts
```
### Factory Pattern
Use a **singleton factory** to select platform services via
`process.env.VITE_PLATFORM`.
## 4. Feature Guidelines
### QR Code Scanning
- Define `QRScannerService` interface.
- Implement platform-specific classes (`WebInlineQRScanner`, Capacitor,
etc).
- Provide `addListener` and `onStream` hooks for composability.
### Deep Linking
- URL format: `timesafari://<route>[/<param>][?query=value]`
- Web: `router.beforeEach` → parse query
- Capacitor: `App.addListener("appUrlOpen", …)`
## 5. Build Process
- `vite.config.common.mts` → shared config
- Platform configs: `vite.config.web.mts`, `.capacitor.mts`,
`.electron.mts`
- Use `process.env.VITE_PLATFORM` for conditional loading.
```bash
npm run build:web
npm run build:capacitor
npm run build:electron
```
## 6. Testing Strategy
- **Unit tests** for services.
- **Playwright** for Web + Capacitor:
- `playwright.config-local.ts` includes web + Pixel 5.
- **Electron tests**: add `spectron` or Playwright-Electron.
- Mark tests with platform tags:
```ts
test.skip(!process.env.MOBILE_TEST, "Mobile-only test");
```
> 🔗 **Human Hook:** Before merging new tests, hold a short sync (≤15
> min) with QA to align on coverage and flaky test risks.
## 7. Error Handling
- Global Vue error handler → logs with component name.
- Platform-specific wrappers log API errors with platform prefix
(`[Capacitor API Error]`, etc).
- Use structured logging (not `console.log`).
## 8. Best Practices
- Keep platform code **isolated** in `platforms/`.
- Always define a **shared interface** first.
- Use feature detection, not platform detection, when possible.
- Dependency injection for services → improves testability.
- Maintain **Competence Hooks** in PRs (2–3 prompts for dev
discussion).
## 9. Dependency Management
- Key deps: `@capacitor/core`, `electron`, `vue`.
- Use conditional `import()` for platform-specific libs.
## 10. Security Considerations
- **Permissions**: Always check + request gracefully.
- **Storage**: Secure storage for sensitive data; encrypt when possible.
- **Audits**: Schedule quarterly security reviews.
## 11. ADR Process
- All major architecture choices → log in `doc/adr/`.
- Use ADR template with Context, Decision, Consequences, Status.
- Link related ADRs in PR descriptions.
> 🔗 **Human Hook:** When proposing a new ADR, schedule a 30-min
> design sync for discussion, not just async review.
## 12. Collaboration Hooks
- **QR features**: Sync with Security before merging → permissions &
privacy.
- **New platform builds**: Demo in team meeting → confirm UX
differences.
- **Critical ADRs**: Present in guild or architecture review.
## Self-Check
- [ ] Does this feature implement a shared interface?
- [ ] Are fallbacks + errors handled gracefully?
- [ ] Have relevant ADRs been updated/linked?
- [ ] Did I add competence hooks or prompts for the team?
- [ ] Was human interaction (sync/review/demo) scheduled?
---
**Status**: Active architecture guidelines
**Priority**: High
**Estimated Effort**: Ongoing reference
**Dependencies**: Vue 3, Capacitor, Electron, Vite
**Stakeholders**: Development team, Architecture team
- [ ] Are fallbacks + errors handled gracefully?
- [ ] Have relevant ADRs been updated/linked?
- [ ] Did I add competence hooks or prompts for the team?
- [ ] Was human interaction (sync/review/demo) scheduled?
# TimeSafari Cross-Platform Architecture Guide
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Architecture guidelines
## 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
### 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
└── assets/ # Static assets
```
### Entry Points
- `main.ts` → Base entry
- `main.common.ts` → Shared init
- `main.capacitor.ts` → Mobile entry
- `main.electron.ts` → Electron entry
- `main.web.ts` → Web entry
## 3. Service Architecture
### Service Organization
```tree
services/
├── QRScanner/
│ ├── WebInlineQRScanner.ts
│ └── interfaces.ts
├── platforms/
│ ├── WebPlatformService.ts
│ ├── CapacitorPlatformService.ts
│ └── ElectronPlatformService.ts
└── factory/
└── PlatformServiceFactory.ts
```
### Factory Pattern
Use a **singleton factory** to select platform services via
`process.env.VITE_PLATFORM`.
## 4. Feature Guidelines
### QR Code Scanning
- Define `QRScannerService` interface.
- Implement platform-specific classes (`WebInlineQRScanner`, Capacitor,
etc).
- Provide `addListener` and `onStream` hooks for composability.
### Deep Linking
- URL format: `timesafari://<route>[/<param>][?query=value]`
- Web: `router.beforeEach` → parse query
- Capacitor: `App.addListener("appUrlOpen", …)`
## 5. Build Process
- `vite.config.common.mts` → shared config
- Platform configs: `vite.config.web.mts`, `.capacitor.mts`,
`.electron.mts`
- Use `process.env.VITE_PLATFORM` for conditional loading.
```bash
npm run build:web
npm run build:capacitor
npm run build:electron
```
## 6. Testing Strategy
- **Unit tests** for services.
- **Playwright** for Web + Capacitor:
- `playwright.config-local.ts` includes web + Pixel 5.
- **Electron tests**: add `spectron` or Playwright-Electron.
- Mark tests with platform tags:
```ts
test.skip(!process.env.MOBILE_TEST, "Mobile-only test");
```
> 🔗 **Human Hook:** Before merging new tests, hold a short sync (≤15
> min) with QA to align on coverage and flaky test risks.
## 7. Error Handling
- Global Vue error handler → logs with component name.
- Platform-specific wrappers log API errors with platform prefix
(`[Capacitor API Error]`, etc).
- Use structured logging (not `console.log`).
## 8. Best Practices
- Keep platform code **isolated** in `platforms/`.
- Always define a **shared interface** first.
- Use feature detection, not platform detection, when possible.
- Dependency injection for services → improves testability.
- Maintain **Competence Hooks** in PRs (2–3 prompts for dev
discussion).
## 9. Dependency Management
- Key deps: `@capacitor/core`, `electron`, `vue`.
- Use conditional `import()` for platform-specific libs.
## 10. Security Considerations
- **Permissions**: Always check + request gracefully.
- **Storage**: Secure storage for sensitive data; encrypt when possible.
- **Audits**: Schedule quarterly security reviews.
## 11. ADR Process
- All major architecture choices → log in `doc/adr/`.
- Use ADR template with Context, Decision, Consequences, Status.
- Link related ADRs in PR descriptions.
> 🔗 **Human Hook:** When proposing a new ADR, schedule a 30-min
> design sync for discussion, not just async review.
## 12. Collaboration Hooks
- **QR features**: Sync with Security before merging → permissions &
privacy.
- **New platform builds**: Demo in team meeting → confirm UX
differences.
- **Critical ADRs**: Present in guild or architecture review.
## Self-Check
- [ ] Does this feature implement a shared interface?
- [ ] Are fallbacks + errors handled gracefully?
- [ ] Have relevant ADRs been updated/linked?
- [ ] Did I add competence hooks or prompts for the team?
- [ ] Was human interaction (sync/review/demo) scheduled?
---
**Status**: Active architecture guidelines
**Priority**: High
**Estimated Effort**: Ongoing reference
**Dependencies**: Vue 3, Capacitor, Electron, Vite
**Stakeholders**: Development team, Architecture team
- [ ] Are fallbacks + errors handled gracefully?
- [ ] Have relevant ADRs been updated/linked?
- [ ] Did I add competence hooks or prompts for the team?
- [ ] Was human interaction (sync/review/demo) scheduled?

181
.cursor/rules/app/timesafari.mdc

@ -0,0 +1,181 @@
# Time Safari Context
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Core application context
## Project Overview
Time Safari is an application designed to foster community building through
gifts, gratitude, and collaborative projects. The app makes it 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.
## Core Goals
1. **Connect**: Make it easy, rewarding, and non-threatening for people to
connect with others who have similar interests, and to initiate activities
together.
2. **Reveal**: Widely advertise the great support and rewards that are being
given and accepted freely, especially non-monetary ones, showing the impact
gifts make in people's lives.
## Technical Foundation
### Architecture
- **Privacy-preserving claims architecture** via endorser.ch
- **Decentralized Identifiers (DIDs)**: User identities based on
public/private key pairs stored on devices
- **Cryptographic Verification**: All claims and confirmations are
cryptographically signed
- **User-Controlled Visibility**: Users explicitly control who can see their
identifiers and data
- **Cross-Platform**: Web (PWA), Mobile (Capacitor), Desktop (Electron)
### Current Database State
- **Database**: SQLite via Absurd SQL (browser) and native SQLite
(mobile/desktop)
- **Legacy Support**: IndexedDB (Dexie) for backward compatibility
- **Status**: Modern database architecture fully implemented
### Core Technologies
- **Frontend**: Vue 3 + TypeScript + vue-facing-decorator
- **Styling**: TailwindCSS
- **Build**: Vite with platform-specific configs
- **Testing**: Playwright E2E, Jest unit tests
- **Database**: SQLite (Absurd SQL in browser), IndexedDB (legacy)
- **State**: Pinia stores
- **Platform Services**: Abstracted behind interfaces with factory pattern
## Development Principles
### Code Organization
- **Platform Services**: Abstract platform-specific code behind interfaces
- **Service Factory**: Use `PlatformServiceFactory` for platform selection
- **Type Safety**: Strict TypeScript, no `any` types, use type guards
- **Modern Architecture**: Use current platform service patterns
### Architecture Patterns
- **Dependency Injection**: Services injected via mixins and factory pattern
- **Interface Segregation**: Small, focused interfaces over large ones
- **Composition over Inheritance**: Prefer mixins and composition
- **Single Responsibility**: Each component/service has one clear purpose
### Testing Strategy
- **E2E**: Playwright for critical user journeys
- **Unit**: Jest with F.I.R.S.T. principles
- **Platform Coverage**: Web + Capacitor (Pixel 5) in CI
- **Quality Assurance**: Comprehensive testing and validation
## Current Development Focus
### Active Development
- **Feature Development**: Build new functionality using modern platform
services
- **Performance Optimization**: Improve app performance and user experience
- **Platform Enhancement**: Leverage platform-specific capabilities
- **Code Quality**: Maintain high standards and best practices
### Development Metrics
- **Code Quality**: High standards maintained across all platforms
- **Performance**: Optimized for all target devices
- **Testing**: Comprehensive coverage maintained
- **User Experience**: Focus on intuitive, accessible interfaces
## Platform-Specific Considerations
### Web (PWA)
- **QR Scanning**: WebInlineQRScanner
- **Deep Linking**: URL parameters
- **File System**: Limited browser APIs
- **Build**: `npm run build:web` (development build)
### Mobile (Capacitor)
- **QR Scanning**: @capacitor-mlkit/barcode-scanning
- **Deep Linking**: App URL open events
- **File System**: Capacitor Filesystem
- **Build**: `npm run build:capacitor`
### Desktop (Electron)
- **File System**: Node.js fs
- **Build**: `npm run build:electron`
- **Distribution**: AppImage, DEB, DMG packages
## Development Workflow
### Build Commands
```bash
# Web (development)
npm run build:web
# Mobile
npm run build:capacitor
npm run build:native
# Desktop
npm run build:electron
npm run build:electron:appimage
npm run build:electron:deb
npm run build:electron:dmg
```
### Testing Commands
```bash
# Web E2E
npm run test:web
# Mobile
npm run test:mobile
npm run test:android
npm run test:ios
# Type checking
npm run type-check
npm run lint-fix
```
## Key Constraints
1. **Privacy First**: User identifiers remain private except when explicitly
shared
2. **Platform Compatibility**: Features must work across all target platforms
3. **Performance**: Must remain performant on older/simpler devices
4. **Modern Architecture**: New features should use current platform services
5. **Offline Capability**: Key functionality should work offline when feasible
## Use Cases to Support
1. **Community Building**: Tools for finding others with shared interests
2. **Project Coordination**: Easy proposal and collaboration on projects
3. **Reputation Building**: Showcasing contributions and reliability
4. **Governance**: Facilitating decision-making and collective governance
## Resources
- **Testing**: `docs/migration-testing/`
- **Architecture**: `docs/architecture-decisions.md`
- **Build Context**: `docs/build-modernization-context.md`
---
## Status: Active application context
- **Priority**: Critical
- **Estimated Effort**: Ongoing reference
- **Dependencies**: Vue 3, TypeScript, SQLite, Capacitor, Electron
- **Stakeholders**: Development team, Product team

287
.cursor/rules/architectural_decision_record.mdc

@ -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.

75
.cursor/rules/architecture/README.md

@ -0,0 +1,75 @@
# Architecture Rules Directory
**Author**: Matthew Raymer
**Date**: 2025-08-20
**Status**: 🎯 **ACTIVE** - Architecture protection guidelines
## Overview
This directory contains MDC (Model Directive Configuration) rules that protect
critical architectural components of the TimeSafari project. These rules ensure
that changes to system architecture follow proper review, testing, and
documentation procedures.
## Available Rules
### Build Architecture Guard (`build_architecture_guard.mdc`)
Protects the multi-platform build system including:
- Vite configuration files
- Build scripts and automation
- Platform-specific configurations (iOS, Android, Electron, Web)
- Docker and deployment infrastructure
- CI/CD pipeline components
**When to use**: Any time you're modifying build scripts, configuration files,
or deployment processes.
**Authorization levels**:
- **Level 1**: Minor changes (review required)
- **Level 2**: Moderate changes (testing required)
- **Level 3**: Major changes (ADR required)
## Usage Guidelines
### For Developers
1. **Check the rule**: Before making architectural changes, review the relevant
rule
2. **Follow the process**: Use the appropriate authorization level
3. **Complete validation**: Run through the required checklist
4. **Update documentation**: Keep BUILDING.md and related docs current
### For Reviewers
1. **Verify authorization**: Ensure changes match the required level
2. **Check testing**: Confirm appropriate testing has been completed
3. **Validate documentation**: Ensure BUILDING.md reflects changes
4. **Assess risk**: Consider impact on other platforms and systems
## Integration with Other Rules
- **Version Control**: Works with `workflow/version_control.mdc`
- **Research & Diagnostic**: Supports `research_diagnostic.mdc` for
investigations
- **Software Development**: Aligns with development best practices
- **Markdown Automation**: Integrates with `docs/markdown-automation.mdc` for
consistent documentation formatting
## Emergency Procedures
If architectural changes cause system failures:
1. **Immediate rollback** to last known working state
2. **Document the failure** with full error details
3. **Investigate root cause** using diagnostic workflows
4. **Update procedures** to prevent future failures
---
**Status**: Active architecture protection
**Priority**: Critical
**Maintainer**: Development team
**Next Review**: 2025-09-20

295
.cursor/rules/architecture/build_architecture_guard.mdc

@ -0,0 +1,295 @@
---
description: Guards against unauthorized changes to the TimeSafari building
architecture
alwaysApply: false
---
# Build Architecture Guard Directive
**Author**: Matthew Raymer
**Date**: 2025-08-20
**Status**: 🎯 **ACTIVE** - Build system protection guidelines
## Purpose
Protect the TimeSafari building architecture from unauthorized changes that
could break the multi-platform build pipeline, deployment processes, or
development workflow. This directive ensures all build system modifications
follow proper review, testing, and documentation procedures.
## Protected Architecture Components
### Core Build Infrastructure
- **Vite Configuration Files**: `vite.config.*.mts` files
- **Build Scripts**: All scripts in `scripts/` directory
- **Package Scripts**: `package.json` build-related scripts
- **Platform Configs**: `capacitor.config.ts`, `electron/`, `android/`,
`ios/`
- **Docker Configuration**: `Dockerfile`, `docker-compose.yml`
- **Environment Files**: `.env.*`, `.nvmrc`, `.node-version`
### Critical Build Dependencies
- **Build Tools**: Vite, Capacitor, Electron, Android SDK, Xcode
- **Asset Management**: `capacitor-assets.config.json`, asset scripts
- **Testing Infrastructure**: Playwright, Jest, mobile test scripts
- **CI/CD Pipeline**: GitHub Actions, build validation scripts
- **Service Worker Assembly**: `sw_scripts/`, `sw_combine.js`, WASM copy steps
## Change Authorization Requirements
### Level 1: Minor Changes (Requires Review)
- Documentation updates to `BUILDING.md`
- Non-breaking script improvements
- Test additions or improvements
- Asset configuration updates
**Process**: Code review + basic testing
### Level 2: Moderate Changes (Requires Testing)
- New build script additions
- Environment variable changes
- Dependency version updates
- Platform-specific optimizations
**Process**: Code review + platform testing + documentation update
### Level 3: Major Changes (Requires ADR)
- Build system architecture changes
- New platform support
- Breaking changes to build scripts
- Major dependency migrations
**Process**: ADR creation + comprehensive testing + team review
## Prohibited Actions
### ❌ Never Allow Without ADR
- **Delete or rename** core build scripts
- **Modify** `package.json` build script names
- **Change** Vite configuration structure
- **Remove** platform-specific build targets
- **Alter** Docker build process
- **Modify** CI/CD pipeline without testing
### ❌ Never Allow Without Testing
- **Update** build dependencies
- **Change** environment configurations
- **Modify** asset generation scripts
- **Alter** test infrastructure
- **Update** platform SDK versions
## Required Validation Checklist
### Before Any Build System Change
- [ ] **Impact Assessment**: Which platforms are affected?
- [ ] **Testing Plan**: How will this be tested across platforms?
- [ ] **Rollback Plan**: How can this be reverted if it breaks?
- [ ] **Documentation**: Will `BUILDING.md` need updates?
- [ ] **Dependencies**: Are all required tools available?
### After Build System Change
- [ ] **Web Platform**: Does `npm run build:web:dev` work?
- [ ] **Mobile Platforms**: Do iOS/Android builds succeed?
- [ ] **Desktop Platform**: Does Electron build and run?
- [ ] **Tests Pass**: Do all build-related tests pass?
- [ ] **Documentation Updated**: Is `BUILDING.md` current?
## Specific Test Commands (Minimum Required)
### Web Platform
- **Development**: `npm run build:web:dev` - serve and load app
- **Production**: `npm run build:web:prod` - verify SW and WASM present
### Mobile Platforms
- **Android**: `npm run build:android:test` or `:prod` - confirm assets copied
- **iOS**: `npm run build:ios:test` or `:prod` - verify build succeeds
### Desktop Platform
- **Electron**: `npm run build:electron:dev` and packaging for target OS
- **Verify**: Single-instance behavior and app boot
### Auto-run (if affected)
- **Test Mode**: `npm run auto-run:test` and platform variants
- **Production Mode**: `npm run auto-run:prod` and platform variants
### Clean and Rebuild
- Run relevant `clean:*` scripts and ensure re-build works
## Emergency Procedures
### Build System Broken
1. **Immediate**: Revert to last known working commit
2. **Investigation**: Create issue with full error details
3. **Testing**: Verify all platforms work after revert
4. **Documentation**: Update `BUILDING.md` with failure notes
### Platform-Specific Failure
1. **Isolate**: Identify which platform is affected
2. **Test Others**: Verify other platforms still work
3. **Rollback**: Revert platform-specific changes
4. **Investigation**: Debug in isolated environment
## Integration Points
### With Version Control
- **Branch Protection**: Require reviews for build script changes
- **Commit Messages**: Must reference ADR for major changes
- **Testing**: All build changes must pass CI/CD pipeline
### With Documentation
- **BUILDING.md**: Must be updated for any script changes
- **README.md**: Must reflect new build requirements
- **CHANGELOG.md**: Must document breaking build changes
### With Testing
- **Pre-commit**: Run basic build validation
- **CI/CD**: Full platform build testing
- **Manual Testing**: Human verification of critical paths
## Risk Matrix & Required Validation
### Environment Handling
- **Trigger**: Change to `.env.*` loading / variable names
- **Validation**: Prove `dev/test/prod` builds; show environment echo in logs
### Script Flow
- **Trigger**: Reorder steps (prebuild → build → package), new flags
- **Validation**: Dry-run + normal run, show exit codes & timing
### Platform Packaging
- **Trigger**: Electron NSIS/DMG/AppImage, Android/iOS bundle
- **Validation**: Produce installer/artifact and open it; verify single-instance,
icons, signing
### Service Worker / WASM
- **Trigger**: `sw_combine.js`, WASM copy path
- **Validation**: Verify combined SW exists and is injected; page loads offline;
WASM present
### Docker
- **Trigger**: New base image, build args
- **Validation**: Build image locally; run container; list produced `/dist`
### Signing/Notarization
- **Trigger**: Cert path/profiles
- **Validation**: Show signing logs + verify on target OS
## PR Template (Paste into Description)
- [ ] **Level**: L1 / L2 / L3 + justification
- [ ] **Files & platforms touched**:
- [ ] **Risk triggers & mitigations**:
- [ ] **Commands run (paste logs)**:
- [ ] **Artifacts (names + sha256)**:
- [ ] **Docs updated (sections/links)**:
- [ ] **Rollback steps verified**:
- [ ] **CI**: Jobs passing and artifacts uploaded
## Rollback Playbook
### Immediate Rollback
1. `git revert` or `git reset --hard <prev>`; restore prior `scripts/` or config
files
2. Rebuild affected targets; verify old behavior returns
3. Post-mortem notes → update this guard and `BUILDING.md` if gaps found
### Rollback Verification
- **Web**: `npm run build:web:dev` and `npm run build:web:prod`
- **Mobile**: `npm run build:android:test` and `npm run build:ios:test`
- **Desktop**: `npm run build:electron:dev` and packaging commands
- **Clean**: Run relevant `clean:*` scripts and verify re-build works
## ADR Trigger List
Raise an ADR when you propose any of:
- **New build stage** or reorder of canonical stages
- **Replacement of packager** / packaging format
- **New environment model** or secure secret handling scheme
- **New service worker assembly** strategy or cache policy
- **New Docker base** or multi-stage pipeline
- **Relocation of build outputs** or directory conventions
**ADR must include**: motivation, alternatives, risks, validation plan, rollback,
doc diffs.
## Competence Hooks
### Why This Works
- **Prevents Build Failures**: Catches issues before they reach production
- **Maintains Consistency**: Ensures all platforms build identically
- **Reduces Debugging Time**: Prevents build system regressions
### Common Pitfalls
- **Silent Failures**: Changes that work on one platform but break others
- **Dependency Conflicts**: Updates that create version incompatibilities
- **Documentation Drift**: Build scripts that don't match documentation
### Next Skill Unlock
- Learn to test build changes across all platforms simultaneously
### Teach-back
- "What three platforms must I test before committing a build script change?"
## Collaboration Hooks
### Team Review Requirements
- **Platform Owners**: iOS, Android, Electron, Web specialists
- **DevOps**: CI/CD pipeline maintainers
- **QA**: Testing infrastructure owners
### Discussion Prompts
- "Which platforms will be affected by this build change?"
- "How can we test this change without breaking existing builds?"
- "What's our rollback plan if this change fails?"
## Self-Check (Before Allowing Changes)
- [ ] **Authorization Level**: Is this change appropriate for the level?
- [ ] **Testing Plan**: Is there a comprehensive testing strategy?
- [ ] **Documentation**: Will BUILDING.md be updated?
- [ ] **Rollback**: Is there a safe rollback mechanism?
- [ ] **Team Review**: Have appropriate stakeholders been consulted?
- [ ] **CI/CD**: Will this pass the build pipeline?
---
**Status**: Active build system protection
**Priority**: Critical
**Estimated Effort**: Ongoing vigilance
**Dependencies**: All build system components
**Stakeholders**: Development team, DevOps, Platform owners
**Next Review**: 2025-09-20

61
.cursor/rules/asset_configuration.mdc

@ -0,0 +1,61 @@
---
description: when doing anything with capacitor assets
alwaysApply: false
---
# Asset Configuration Directive
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Asset management guidelines
*Scope: Assets Only (icons, splashes, image pipelines) — not overall build
orchestration*
## Intent
- Version **asset configuration files** (optionally dev-time generated).
- **Do not** version platform asset outputs (Android/iOS/Electron); generate
them **at build-time** with standard tools.
- Keep existing per-platform build scripts unchanged.
## Source of Truth
- **Preferred (Capacitor default):** `resources/` as the single master source.
- **Alternative:** `assets/` is acceptable **only** if `capacitor-assets` is
explicitly configured to read from it.
- **Never** maintain both `resources/` and `assets/` as parallel sources.
Migrate and delete the redundant folder.
## Config Files
- Live under: `config/assets/` (committed).
- Examples:
- `config/assets/capacitor-assets.config.json` (or the path the tool
expects)
- `config/assets/android.assets.json`
- `config/assets/ios.assets.json`
- `config/assets/common.assets.yaml` (optional shared layer)
- **Dev-time generation allowed** for these configs; **build-time
generation is forbidden**.
## Build-Time Behavior
- Build generates platform assets (not configs) using the standard chain:
```bash
npm run build:capacitor # web build via Vite (.mts)
npx cap sync
npx capacitor-assets generate # produces platform assets; not committed
# then platform-specific build steps
```
---
**Status**: Active asset management directive
**Priority**: Medium
**Estimated Effort**: Ongoing reference
**Dependencies**: capacitor-assets toolchain
**Stakeholders**: Development team, Build team
npx capacitor-assets generate # produces platform assets; not committed
# then platform-specific build steps

154
.cursor/rules/base_context.mdc

@ -0,0 +1,154 @@
---
alwaysApply: true
---
```json
{
"coaching_level": "standard",
"socratic_max_questions": 7,
"verbosity": "normal",
"timebox_minutes": null,
"format_enforcement": "strict"
}
```
# Base Context — Human Competence First
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Core interaction guidelines
## Purpose
All interactions must *increase the human's competence over time* while
completing the task efficiently. The model may handle menial work and memory
extension, but must also promote learning, autonomy, and healthy work habits.
The model should also **encourage human interaction and collaboration** rather
than replacing it — outputs should be designed to **facilitate human discussion,
decision-making, and creativity**, not to atomize tasks into isolated, purely
machine-driven steps.
## Principles
1. Competence over convenience: finish the task *and* leave the human more
capable next time.
2. Mentorship, not lectures: be concise, concrete, and immediately applicable.
3. Transparency: show assumptions, limits, and uncertainty; cite when
non-obvious.
4. Optional scaffolding: include small, skimmable learning hooks that do not
bloat output.
5. Time respect: default to **lean output**; offer opt-in depth via toggles.
6. Psychological safety: encourage, never condescend; no medical/clinical
advice. No censorship!
7. Reusability: structure outputs so they can be saved, searched, reused, and
repurposed.
8. **Collaborative Bias**: Favor solutions that invite human review,
discussion, and iteration. When in doubt, ask "Who should this be shown
to?" or "Which human input would improve this?"
## Toggle Definitions
### coaching_level
Determines the depth of learning support: `light` (short hooks),
`standard` (balanced), `deep` (detailed).
### socratic_max_questions
The number of clarifying questions the model may ask before proceeding.
If >0, questions should be targeted, minimal, and followed by reasonable
assumptions if unanswered.
### verbosity
'terse' (just a sentence), `concise` (minimum commentary), `normal`
(balanced explanation), or other project-defined levels.
### timebox_minutes
*integer or null* — When set to a positive integer (e.g., `5`), this acts
as a **time budget** guiding the model to prioritize delivering the most
essential parts of the task within that constraint.
Behavior when set:
1. **Prioritize Core Output** — Deliver the minimum viable solution or
result first.
2. **Limit Commentary** — Competence Hooks and Collaboration Hooks must be
shorter than normal.
3. **Signal Skipped Depth** — Omitted details should be listed under
*Deferred for depth*.
4. **Order by Value** — Start with blocking or high-value items, then
proceed to nice-to-haves if budget allows.
If `null`, there is no timebox — the model can produce full-depth
responses.
### format_enforcement
`strict` (reject outputs with format drift) or `relaxed` (minor deviations
acceptable).
## Modes (select or combine)
- **Doer**: produce the artifact fast, minimal commentary.
- **Mentor**: add short "why/how" notes + next-step pointers.
- **Socratic**: ask up to N targeted questions when requirements are
ambiguous.
- **Pair-Programmer/Pair-Writer**: explain tradeoffs as you implement.
- **Facilitator**: structure output to be reviewable, commentable, and
ready for group discussion.
Default: Doer + short Mentor notes.
## Competence & Collaboration Levers (keep lightweight)
- "Why this works" (≤3 bullets)
- "Common pitfalls" (≤3 bullets)
- "Next skill unlock" (1 tiny action or reading)
- "Teach-back" (1 sentence prompt the human can answer to self-check)
- "Discussion prompts" (≤2 short questions for peers/stakeholders)
## Output Contract (apply to every deliverable)
- Clear **Objective** (1 line)
- **Result** (artifact/code/answer)
- **Use/Run** (how to apply/test)
- **Competence Hooks** (the 4 learning levers above, kept terse)
- **Collaboration Hooks** (discussion prompts or group review steps)
- **Assumptions & Limits**
- **References** (if used; links or titles)
## Do-Not
- No filler, hedging, or moralizing.
- No medical/mental-health advice; keep "healthy habits" to general work
practices.
- No invented facts; mark uncertainty plainly.
- No censorship.
- Avoid outputs that bypass human review when such review is valuable.
## Related Rulesets
- **software_development.mdc**: For software-specific development practices
- **research_diagnostic.mdc**: For investigation and research workflows
## Self-Check (model, before responding)
- [ ] Task done *and* at least one competence lever included (≤120 words
total).
- [ ] At least one collaboration/discussion hook present.
- [ ] Output follows the **Output Contract** sections.
- [ ] Toggles respected; verbosity remains concise.
- [ ] Uncertainties/assumptions surfaced.
- [ ] No disallowed content.
---
**Status**: Active core guidelines
**Priority**: Critical
**Estimated Effort**: Ongoing reference
**Dependencies**: None (base ruleset)
**Stakeholders**: All AI interactions
- [ ] Uncertainties/assumptions surfaced.
- [ ] No disallowed content.

48
.cursor/rules/absurd-sql.mdc → .cursor/rules/database/absurd-sql.mdc

@ -1,14 +1,23 @@
--- ---
description: globs: **/db/databaseUtil.ts, **/interfaces/absurd-sql.d.ts, **/src/registerSQLWorker.js, **/
globs: services/AbsurdSqlDatabaseService.ts
alwaysApply: true alwaysApply: false
--- ---
# Absurd SQL - Cursor Development Guide # Absurd SQL - Cursor Development Guide
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Database development guidelines
## Project Overview ## 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.
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 ## Project Structure
``` ```
absurd-sql/ absurd-sql/
├── src/ # Source code ├── src/ # Source code
@ -21,36 +30,45 @@ absurd-sql/
## Development Rules ## Development Rules
### 1. Worker Thread Requirements ### 1. Worker Thread Requirements
- All SQL operations MUST be performed in a worker thread - All SQL operations MUST be performed in a worker thread
- Main thread should only handle worker initialization and communication - Main thread should only handle worker initialization and communication
- Never block the main thread with database operations - Never block the main thread with database operations
### 2. Code Organization ### 2. Code Organization
- Keep worker code in separate files (e.g., `*.worker.js`) - Keep worker code in separate files (e.g., `*.worker.js`)
- Use ES modules for imports/exports - Use ES modules for imports/exports
- Follow the project's existing module structure - Follow the project's existing module structure
### 3. Required Headers ### 3. Required Headers
When developing locally or deploying, ensure these headers are set: When developing locally or deploying, ensure these headers are set:
``` ```
Cross-Origin-Opener-Policy: same-origin Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp Cross-Origin-Embedder-Policy: require-corp
``` ```
### 4. Browser Compatibility ### 4. Browser Compatibility
- Primary target: Modern browsers with SharedArrayBuffer support - Primary target: Modern browsers with SharedArrayBuffer support
- Fallback mode: Safari (with limitations) - Fallback mode: Safari (with limitations)
- Always test in both modes - Always test in both modes
### 5. Database Configuration ### 5. Database Configuration
Recommended database settings: Recommended database settings:
```sql ```sql
PRAGMA journal_mode=MEMORY; PRAGMA journal_mode=MEMORY;
PRAGMA page_size=8192; -- Optional, but recommended PRAGMA page_size=8192; -- Optional, but recommended
``` ```
### 6. Development Workflow ### 6. Development Workflow
1. Install dependencies: 1. Install dependencies:
```bash ```bash
yarn add @jlongster/sql.js absurd-sql yarn add @jlongster/sql.js absurd-sql
``` ```
@ -61,17 +79,20 @@ PRAGMA page_size=8192; -- Optional, but recommended
- `yarn serve` - Start development server - `yarn serve` - Start development server
### 7. Testing Guidelines ### 7. Testing Guidelines
- Write tests for both SharedArrayBuffer and fallback modes - Write tests for both SharedArrayBuffer and fallback modes
- Use Jest for testing - Use Jest for testing
- Include performance benchmarks for critical operations - Include performance benchmarks for critical operations
### 8. Performance Considerations ### 8. Performance Considerations
- Use bulk operations when possible - Use bulk operations when possible
- Monitor read/write performance - Monitor read/write performance
- Consider using transactions for multiple operations - Consider using transactions for multiple operations
- Avoid unnecessary database connections - Avoid unnecessary database connections
### 9. Error Handling ### 9. Error Handling
- Implement proper error handling for: - Implement proper error handling for:
- Worker initialization failures - Worker initialization failures
- Database connection issues - Database connection issues
@ -79,18 +100,21 @@ PRAGMA page_size=8192; -- Optional, but recommended
- Storage quota exceeded scenarios - Storage quota exceeded scenarios
### 10. Security Best Practices ### 10. Security Best Practices
- Never expose database operations directly to the client - Never expose database operations directly to the client
- Validate all SQL queries - Validate all SQL queries
- Implement proper access controls - Implement proper access controls
- Handle sensitive data appropriately - Handle sensitive data appropriately
### 11. Code Style ### 11. Code Style
- Follow ESLint configuration - Follow ESLint configuration
- Use async/await for asynchronous operations - Use async/await for asynchronous operations
- Document complex database operations - Document complex database operations
- Include comments for non-obvious optimizations - Include comments for non-obvious optimizations
### 12. Debugging ### 12. Debugging
- Use `jest-debug` for debugging tests - Use `jest-debug` for debugging tests
- Monitor IndexedDB usage in browser dev tools - Monitor IndexedDB usage in browser dev tools
- Check worker communication in console - Check worker communication in console
@ -99,6 +123,7 @@ PRAGMA page_size=8192; -- Optional, but recommended
## Common Patterns ## Common Patterns
### Worker Initialization ### Worker Initialization
```javascript ```javascript
// Main thread // Main thread
import { initBackend } from 'absurd-sql/dist/indexeddb-main-thread'; import { initBackend } from 'absurd-sql/dist/indexeddb-main-thread';
@ -110,6 +135,7 @@ function init() {
``` ```
### Database Setup ### Database Setup
```javascript ```javascript
// Worker thread // Worker thread
import initSqlJs from '@jlongster/sql.js'; import initSqlJs from '@jlongster/sql.js';
@ -131,6 +157,7 @@ async function setupDatabase() {
## Troubleshooting ## Troubleshooting
### Common Issues ### Common Issues
1. SharedArrayBuffer not available 1. SharedArrayBuffer not available
- Check COOP/COEP headers - Check COOP/COEP headers
- Verify browser support - Verify browser support
@ -147,6 +174,19 @@ async function setupDatabase() {
- Verify transaction usage - Verify transaction usage
## Resources ## 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/)
---
**Status**: Active database development guidelines
**Priority**: High
**Estimated Effort**: Ongoing reference
**Dependencies**: Absurd SQL, SQL.js, IndexedDB
**Stakeholders**: Development team, Database team
- [Project Demo](https://priceless-keller-d097e5.netlify.app/) - [Project Demo](https://priceless-keller-d097e5.netlify.app/)
- [Example Project](https://github.com/jlongster/absurd-example-project) - [Example Project](https://github.com/jlongster/absurd-example-project)
- [Blog Post](https://jlongster.com/future-sql-web) - [Blog Post](https://jlongster.com/future-sql-web)

8
.cursor/rules/database/legacy_dexie.mdc

@ -0,0 +1,8 @@
---
globs: **/databaseUtil.ts,**/AccountViewView.vue,**/ContactsView.vue,**/DatabaseMigration.vue,**/NewIdentifierView.vue
alwaysApply: false
---
# What to do with Dexie
All references in the codebase to Dexie apply only to migration from IndexedDb to
Sqlite and will be deprecated in future versions.

9
.cursor/rules/development/development_guide.mdc

@ -0,0 +1,9 @@
---
globs: **/src/**/*
alwaysApply: false
---
✅ 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

139
.cursor/rules/development/type_safety_guide.mdc

@ -0,0 +1,139 @@
---
description: when dealing with types and Typesript
alwaysApply: false
---
```json
{
"coaching_level": "light",
"socratic_max_questions": 7,
"verbosity": "concise",
"timebox_minutes": null,
"format_enforcement": "strict"
}
```
# TypeScript Type Safety Guidelines
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Type safety enforcement
## Overview
Practical rules to keep TypeScript strict and predictable. Minimize exceptions.
## Core Rules
1. **No `any`**
- Use explicit types. If unknown, use `unknown` and **narrow** via guards.
2. **Error handling uses guards**
- Reuse guards from `src/interfaces/**` (e.g., `isDatabaseError`,
`isApiError`).
- Catch with `unknown`; never cast to `any`.
3. **Dynamic property access is type‑safe**
- Use `keyof` + `in` checks:
```ts
obj[k as keyof typeof obj]
```
- Avoid `(obj as any)[k]`.
## Type Safety Enforcement
### Core Type Safety Rules
- **No `any` Types**: Use explicit types or `unknown` with proper type guards
- **Error Handling Uses Guards**: Implement and reuse type guards from `src/interfaces/**`
- **Dynamic Property Access**: Use `keyof` + `in` checks for type-safe property access
### Type Guard Patterns
- **API Errors**: Use `isApiError(error)` guards for API error handling
- **Database Errors**: Use `isDatabaseError(error)` guards for database operations
- **Axios Errors**: Implement `isAxiosError(error)` guards for HTTP error handling
### Implementation Guidelines
- **Avoid Type Assertions**: Replace `as any` with proper type guards and interfaces
- **Narrow Types Properly**: Use type guards to narrow `unknown` types safely
- **Document Type Decisions**: Explain complex type structures and their purpose
## Minimal Special Cases (document in PR when used)
- **Vue refs / instances**: Use `ComponentPublicInstance` or specific
component types for dynamic refs.
- **3rd‑party libs without types**: Narrow immediately to a **known
interface**; do not leave `any` hanging.
## Patterns (short)
### Database errors
```ts
try { await this.$addContact(contact); }
catch (e: unknown) {
if (isDatabaseError(e) && e.message.includes("Key already exists")) {
/* handle duplicate */
}
}
```
### API errors
```ts
try { await apiCall(); }
catch (e: unknown) {
if (isApiError(e)) {
const msg = e.response?.data?.error?.message;
}
}
```
### Dynamic keys
```ts
const keys = Object.keys(newSettings).filter(
k => k in newSettings && newSettings[k as keyof typeof newSettings] !== undefined
);
```
## Checklists
**Before commit**
- [ ] No `any` (except documented, justified cases)
- [ ] Errors handled via guards
- [ ] Dynamic access uses `keyof`/`in`
- [ ] Imports point to correct interfaces/types
**Code review**
- [ ] Hunt hidden `as any`
- [ ] Guard‑based error paths verified
- [ ] Dynamic ops are type‑safe
- [ ] Prefer existing types over re‑inventing
## Tools
- `npm run lint-fix` — lint & auto‑fix
- `npm run type-check` — strict type compilation (CI + pre‑release)
- IDE: enable strict TS, ESLint/TS ESLint, Volar (Vue 3)
## References
- TS Handbook — https://www.typescriptlang.org/docs/
- TS‑ESLint — https://typescript-eslint.io/rules/
- Vue 3 + TS — https://vuejs.org/guide/typescript/
---
**Status**: Active type safety guidelines
**Priority**: High
**Estimated Effort**: Ongoing reference
**Dependencies**: TypeScript, ESLint, Vue 3
**Stakeholders**: Development team
- TS Handbook — https://www.typescriptlang.org/docs/
- TS‑ESLint — https://typescript-eslint.io/rules/
- Vue 3 + TS — https://vuejs.org/guide/typescript/

35
.cursor/rules/development_guide.mdc

@ -1,35 +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
✅ do not add or commit for the user; let him control that process
always preview changes and commit message to use and allow me to copy and paste
✅ Preferred Commit Message Format
Short summary in the first line (concise and high-level).
Avoid long commit bodies unless truly necessary.
✅ Valued Content in Commit Messages
Specific fixes or features.
Symptoms or problems that were fixed.
Notes about tests passing or TS/linting errors being resolved (briefly).
❌ Avoid in Commit Messages
Vague terms: “improved”, “enhanced”, “better” — especially from AI.
Minor changes: small doc tweaks, one-liners, cleanup, or lint fixes.
Redundant blurbs: repeated across files or too generic.
Multiple overlapping purposes in a single commit — prefer narrow, focused commits.
Long explanations of what can be deduced from good in-line code comments.
Guiding Principle
Let code and inline documentation speak for themselves. Use commits to highlight what isn't obvious from reading the code.

14
.cursor/rules/docs/documentation.mdc

@ -0,0 +1,14 @@
---
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.

79
.cursor/rules/docs/markdown-automation.mdc

@ -0,0 +1,79 @@
---
alwaysApply: true
---
# Markdown Automation System
**Author**: Matthew Raymer
**Date**: 2025-08-20
**Status**: 🎯 **ACTIVE** - Markdown formatting automation
## Overview
The Markdown Automation System ensures your markdown formatting standards are
followed **during content generation** by AI agents, not just applied after the
fact.
## AI-First Approach
### **Primary Method**: AI Agent Compliance
- **AI agents follow markdown rules** while generating content
- **No post-generation fixes needed** - content is compliant from creation
- **Consistent formatting** across all generated documentation
### **Secondary Method**: Automated Validation
- **Pre-commit hooks** catch any remaining issues
- **GitHub Actions** validate formatting before merge
- **Manual tools** for bulk fixes when needed
## How It Works
### 1. **AI Agent Compliance** (Primary)
- **When**: Every time AI generates markdown content
- **What**: AI follows markdown rules during generation
- **Result**: Content is properly formatted from creation
### 2. **Pre-commit Hooks** (Backup)
- **When**: Every time you commit
- **What**: Catches any remaining formatting issues
- **Result**: Clean, properly formatted markdown files
### 3. **GitHub Actions** (Pre-merge)
- **When**: Every pull request
- **What**: Validates markdown formatting across all files
- **Result**: Blocks merge if formatting issues exist
## AI Agent Rules Integration
The AI agent follows markdown rules defined in `.cursor/rules/docs/markdown.mdc`:
- **alwaysApply: true** - Rules are enforced during generation
- **Line Length**: AI never generates lines > 80 characters
- **Blank Lines**: AI adds proper spacing around all elements
- **Structure**: AI uses established templates and patterns
## Available Commands
### NPM Scripts
- **`npm run markdown:setup`** - Install the automation system
- **`npm run markdown:fix`** - Fix formatting in all markdown files
- **`npm run markdown:check`** - Validate formatting without fixing
## Benefits
- **No more manual fixes** - AI generates compliant content from start
- **Consistent style** - All files follow same standards
- **Faster development** - No need to fix formatting manually
---
**Status**: Active automation system
**Priority**: High
**Maintainer**: Development team
**Next Review**: 2025-09-20

54
.cursor/rules/markdown.mdc → .cursor/rules/docs/markdown.mdc

@ -1,5 +1,5 @@
--- ---
globs: *.md globs: ["*.md", "*.mdc"]
alwaysApply: false alwaysApply: false
--- ---
# Cursor Markdown Ruleset for TimeSafari Documentation # Cursor Markdown Ruleset for TimeSafari Documentation
@ -10,6 +10,36 @@ This ruleset enforces consistent markdown formatting standards across all projec
documentation, ensuring readability, maintainability, and compliance with documentation, ensuring readability, maintainability, and compliance with
markdownlint best practices. markdownlint best practices.
**⚠️ CRITICAL FOR AI AGENTS**: These rules must be followed DURING content
generation, not applied after the fact. Always generate markdown that complies
with these standards from the start.
## AI Generation Guidelines
### **MANDATORY**: Follow These Rules While Writing
When generating markdown content, you MUST:
1. **Line Length**: Never exceed 80 characters per line
2. **Blank Lines**: Always add blank lines around headings, lists, and code
blocks
3. **Structure**: Use proper heading hierarchy and document templates
4. **Formatting**: Apply consistent formatting patterns immediately
### **DO NOT**: Generate content that violates these rules
- ❌ Generate long lines that need breaking
- ❌ Create content without proper blank line spacing
- ❌ Use inconsistent formatting patterns
- ❌ Assume post-processing will fix violations
### **DO**: Generate compliant content from the start
- ✅ Write within 80-character limits
- ✅ Add blank lines around all structural elements
- ✅ Use established templates and patterns
- ✅ Apply formatting standards immediately
## General Formatting Standards ## General Formatting Standards
### Line Length ### Line Length
@ -312,3 +342,25 @@ Description of current situation or problem.
**Last Updated**: 2025-07-09 **Last Updated**: 2025-07-09
**Version**: 1.0 **Version**: 1.0
**Maintainer**: Matthew Raymer **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
```
## Features ❌ (Duplicate heading)
### Security
### Performance
```

6
.cursor/rules/camera-implementation.mdc → .cursor/rules/features/camera-implementation.mdc

@ -1,13 +1,13 @@
--- ---
description: description: when dealing with cameras in the application
globs:
alwaysApply: false alwaysApply: false
--- ---
# Camera Implementation Documentation # Camera Implementation Documentation
## Overview ## Overview
This document describes how camera functionality is implemented across the TimeSafari application. The application uses cameras for two main purposes: This document describes how camera functionality is implemented across the
TimeSafari application. The application uses cameras for two main purposes:
1. QR Code scanning 1. QR Code scanning
2. Photo capture 2. Photo capture

206
.cursor/rules/harbor_pilot_universal.mdc

@ -0,0 +1,206 @@
---
alwaysApply: true
inherits: base_context.mdc
---
```json
{
"coaching_level": "standard",
"socratic_max_questions": 2,
"verbosity": "concise",
"timebox_minutes": 10,
"format_enforcement": "strict"
}
```
# Harbor Pilot — Universal Directive for Human-Facing Technical Guides
**Author**: System/Shared
**Date**: 2025-08-21 (UTC)
**Status**: 🚢 ACTIVE — General ruleset extending *Base Context — Human Competence First*
> **Alignment with Base Context**
> - **Purpose fit**: Prioritizes human competence and collaboration while delivering reproducible artifacts.
> - **Output Contract**: This directive **adds universal constraints** for any technical topic while **inheriting** the Base Context contract sections.
> - **Toggles honored**: Uses the same toggle semantics; defaults above can be overridden by the caller.
---
## Objective
Produce a **developer-grade, reproducible guide** for any technical topic that onboards a competent practitioner **without meta narration** and **with evidence-backed steps**.
## Scope & Constraints
- **One Markdown document** as the deliverable.
- Use **absolute dates** in **UTC** (e.g., `2025-08-21T14:22Z`) — avoid “today/yesterday”.
- Include at least **one diagram** (Mermaid preferred). Choose the most fitting type:
- `sequenceDiagram` (protocols/flows), `flowchart`, `stateDiagram`, `gantt` (timelines), or `classDiagram` (schemas).
- Provide runnable examples where applicable:
- **APIs**: `curl` + one client library (e.g., `httpx` for Python).
- **CLIs**: literal command blocks and expected output snippets.
- **Code**: minimal, self-contained samples (language appropriate).
- Cite **evidence** for *Works/Doesn’t* items (timestamps, filenames, line numbers, IDs/status codes, or logs).
- If something is unknown, output `TODO:<missing>` — **never invent**.
## Required Sections (extends Base Output Contract)
Follow this exact order **after** the Base Contract’s **Objective → Result → Use/Run** headers:
1. **Context & Scope**
- Problem statement, audience, in/out-of-scope bullets.
2. **Artifacts & Links**
- Repos/PRs, design docs, datasets/HARs/pcaps, scripts/tools, dashboards.
3. **Environment & Preconditions**
- OS/runtime, versions/build IDs, services/endpoints/URLs, credentials/auth mode (describe acquisition, do not expose secrets).
4. **Architecture / Process Overview**
- Short prose + **one diagram** selected from the list above.
5. **Interfaces & Contracts (choose one)**
- **API-based**: Endpoint table (*Step, Method, Path/URL, Auth, Key Headers/Params, Sample Req/Resp ref*).
- **Data/Files**: I/O contract table (*Source, Format, Schema/Columns, Size, Validation rules*).
- **Systems/Hardware**: Interfaces table (*Port/Bus, Protocol, Voltage/Timing, Constraints*).
6. **Repro: End-to-End Procedure**
- Minimal copy-paste steps with code/commands and **expected outputs**.
7. **What Works (with Evidence)**
- Each item: **Time (UTC)** • **Artifact/Req IDs** • **Status/Result** • **Where to verify**.
8. **What Doesn’t (Evidence & Hypotheses)**
- Each failure: locus (file/endpoint/module), evidence snippet; short hypothesis and **next probe**.
9. **Risks, Limits, Assumptions**
- SLOs/limits, rate/size caps, security boundaries (CORS/CSRF/ACLs), retries/backoff/idempotency patterns.
10. **Next Steps (Owner • Exit Criteria • Target Date)**
- Actionable, assigned, and time-bound.
11. **References**
- Canonical docs, specs, tickets, prior analyses.
> **Competence Hooks (per Base Context; keep lightweight):**
> - *Why this works* (≤3 bullets) — core invariants or guarantees.
> - *Common pitfalls* (≤3 bullets) — the traps we saw in evidence.
> - *Next skill unlock* (1 line) — the next capability to implement/learn.
> - *Teach-back* (1 line) — prompt the reader to restate the flow/architecture.
> **Collaboration Hooks (per Base Context):**
> - Name reviewers for **Interfaces & Contracts** and the **diagram**.
> - Short **sign-off checklist** before merging/publishing the guide.
## Do / Don’t (Base-aligned)
- **Do** quantify progress only against a defined scope with acceptance criteria.
- **Do** include minimal sample payloads/headers or I/O schemas; redact sensitive values.
- **Do** keep commentary lean; if timeboxed, move depth to **Deferred for depth**.
- **Don’t** use marketing language or meta narration (“Perfect!”, “tool called”, “new chat”).
- **Don’t** include IDE-specific chatter or internal rules unrelated to the task.
## Validation Checklist (self-check before returning)
- [ ] All Required Sections present and ordered.
- [ ] Diagram compiles (basic Mermaid syntax) and fits the problem.
- [ ] If API-based, **Auth** and **Key Headers/Params** are listed for each endpoint.
- [ ] Repro section includes commands/code **and expected outputs**.
- [ ] Every Works/Doesn’t item has **UTC timestamp**, **status/result**, and **verifiable evidence**.
- [ ] Next Steps include **Owner**, **Exit Criteria**, **Target Date**.
- [ ] Unknowns are `TODO:<missing>` — no fabrication.
- [ ] Base **Output Contract** sections satisfied (Objective/Result/Use/Run/Competence/Collaboration/Assumptions/References).
## Universal Template (fill-in)
```markdown
# <Title> — Working Notes (As of YYYY-MM-DDTHH:MMZ)
## Objective
<one line>
## Result
<link to the produced guide file or say “this document”>
## Use/Run
<how to apply/test and where to run samples>
## Context & Scope
- Audience: <role(s)>
- In scope: <bullets>
- Out of scope: <bullets>
## Artifacts & Links
- Repo/PR: <link>
- Data/Logs: <paths or links>
- Scripts/Tools: <paths>
- Dashboards: <links>
## Environment & Preconditions
- OS/Runtime: <details>
- Versions/Builds: <list>
- Services/Endpoints: <list>
- Auth mode: <Bearer/Session/Keys + how acquired>
## Architecture / Process Overview
<short prose>
```mermaid
<one suitable diagram: sequenceDiagram | flowchart | stateDiagram | gantt | classDiagram>
```
## Interfaces & Contracts
### If API-based
| Step | Method | Path/URL | Auth | Key Headers/Params | Sample |
|---|---|---|---|---|---|
| <…> | <…> | <…> | <…> | <…> | below |
### If Data/Files
| Source | Format | Schema/Columns | Size | Validation |
|---|---|---|---|---|
| <…> | <…> | <…> | <…> | <…> |
### If Systems/Hardware
| Interface | Protocol | Timing/Voltage | Constraints | Notes |
|---|---|---|---|---|
| <…> | <…> | <…> | <…> | <…> |
## Repro: End-to-End Procedure
```bash
# commands / curl examples (redacted where necessary)
```
```python
# minimal client library example (language appropriate)
```
> Expected output: <snippet/checks>
## What Works (Evidence)
- ✅ <short statement>
- **Time**: <YYYY-MM-DDTHH:MMZ>
- **Evidence**: file/line/log or request id/status
- **Verify at**: <where>
## What Doesn’t (Evidence & Hypotheses)
- ❌ <short failure> at `<component/endpoint/file>`
- **Time**: <YYYY-MM-DDTHH:MMZ>
- **Evidence**: <snippet/id/status>
- **Hypothesis**: <short>
- **Next probe**: <short>
## Risks, Limits, Assumptions
<bullets: limits, security boundaries, retries/backoff, idempotency, SLOs>
## Next Steps
| Owner | Task | Exit Criteria | Target Date (UTC) |
|---|---|---|---|
| <name> | <action> | <measurable outcome> | <YYYY-MM-DD> |
## References
<links/titles>
## Competence Hooks
- *Why this works*: <≤3 bullets>
- *Common pitfalls*: <≤3 bullets>
- *Next skill unlock*: <1 line>
- *Teach-back*: <1 line>
## Collaboration Hooks
- Reviewers: <names/roles>
- Sign-off checklist: <≤5 checks>
## Assumptions & Limits
<bullets>
## Deferred for depth
<park deeper material here to respect timeboxing>
```
---
**Notes for Implementers:**
- Respect Base *Do-Not* (no filler, no invented facts, no censorship).
- Prefer clarity over completeness when timeboxed; capture unknowns explicitly.
- Apply historical comment management rules (see `.cursor/rules/historical_comment_management.mdc`)
- Apply realistic time estimation rules (see `.cursor/rules/realistic_time_estimation.mdc`)

236
.cursor/rules/historical_comment_management.mdc

@ -0,0 +1,236 @@
---
description: when comments are generated by the model
alwaysApply: false
---
# Historical Comment Management — Harbor Pilot Directive
> **Agent role**: When encountering historical comments about removed methods, deprecated patterns, or architectural changes, apply these guidelines to maintain code clarity and developer guidance.
## 🎯 Purpose
Historical comments should either be **removed entirely** or **transformed into actionable guidance** for future developers. Avoid keeping comments that merely state what was removed without explaining why or what to do instead.
## 📋 Decision Framework
### Remove Historical Comments When:
- **Obsolete Information**: Comment describes functionality that no longer exists
- **No Action Required**: Comment doesn't help future developers make decisions
- **Outdated Context**: Comment refers to old patterns that are no longer relevant
- **Self-Evident**: The current code clearly shows the current approach
### Transform Historical Comments When:
- **Architectural Context**: The change represents a significant pattern shift
- **Migration Guidance**: Future developers might need to understand the evolution
- **Decision Rationale**: The "why" behind the change is still relevant
- **Alternative Approaches**: The comment can guide future implementation choices
## 🔄 Transformation Patterns
### 1. From Removal Notice to Migration Note
```typescript
// ❌ REMOVE THIS
// turnOffNotifyingFlags method removed - notification state is now managed by NotificationSection component
// ✅ TRANSFORM TO THIS
// Note: Notification state management has been migrated to NotificationSection component
// which handles its own lifecycle and persistence via PlatformServiceMixin
```
### 2. From Deprecation Notice to Implementation Guide
```typescript
// ❌ REMOVE THIS
// This will be handled by the NewComponent now
// No need to call oldMethod() as it's no longer needed
// ✅ TRANSFORM TO THIS
// Note: This functionality has been migrated to NewComponent
// which provides better separation of concerns and testability
```
### 3. From Historical Note to Architectural Context
```typescript
// ❌ REMOVE THIS
// Old approach: used direct database calls
// New approach: uses service layer
// ✅ TRANSFORM TO THIS
// Note: Database access has been abstracted through service layer
// for better testability and platform independence
```
## 🚫 Anti-Patterns to Remove
- Comments that only state what was removed
- Comments that don't explain the current approach
- Comments that reference non-existent methods
- Comments that are self-evident from the code
- Comments that don't help future decision-making
## ✅ Best Practices
### When Keeping Historical Context:
1. **Explain the "Why"**: Why was the change made?
2. **Describe the "What"**: What is the current approach?
3. **Provide Context**: When might this information be useful?
4. **Use Actionable Language**: Guide future decisions, not just document history
### When Removing Historical Context:
1. **Verify Obsoleteness**: Ensure the information is truly outdated
2. **Check for Dependencies**: Ensure no other code references the old approach
3. **Update Related Docs**: If removing from code, consider adding to documentation
4. **Preserve in Git History**: The change is preserved in version control
## 🔍 Implementation Checklist
- [ ] Identify historical comments about removed/deprecated functionality
- [ ] Determine if comment provides actionable guidance
- [ ] Transform useful comments into migration notes or architectural context
- [ ] Remove comments that are purely historical without guidance value
- [ ] Ensure remaining comments explain current approach and rationale
- [ ] Update related documentation if significant context is removed
## 📚 Examples
### Good Historical Comment (Keep & Transform)
```typescript
// Note: Database access has been migrated from direct IndexedDB calls to PlatformServiceMixin
// This provides better platform abstraction and consistent error handling across web/mobile/desktop
// When adding new database operations, use this.$getContact(), this.$saveSettings(), etc.
```
### Bad Historical Comment (Remove)
```typescript
// Old method getContactFromDB() removed - now handled by PlatformServiceMixin
// No need to call the old method anymore
```
## 🎯 Integration with Harbor Pilot
This rule works in conjunction with:
- **Component Creation Ideals**: Maintains architectural consistency
- **Migration Patterns**: Documents evolution of patterns
- **Code Review Guidelines**: Ensures comments provide value
## 📝 Version History
### v1.0.0 (2025-08-21)
- Initial creation based on notification system cleanup
- Established decision framework for historical comment management
- Added transformation patterns and anti-patterns
- Integrated with existing Harbor Pilot architecture rules
# Historical Comment Management — Harbor Pilot Directive
> **Agent role**: When encountering historical comments about removed methods, deprecated patterns, or architectural changes, apply these guidelines to maintain code clarity and developer guidance.
## 🎯 Purpose
Historical comments should either be **removed entirely** or **transformed into actionable guidance** for future developers. Avoid keeping comments that merely state what was removed without explaining why or what to do instead.
## 📋 Decision Framework
### Remove Historical Comments When:
- **Obsolete Information**: Comment describes functionality that no longer exists
- **No Action Required**: Comment doesn't help future developers make decisions
- **Outdated Context**: Comment refers to old patterns that are no longer relevant
- **Self-Evident**: The current code clearly shows the current approach
### Transform Historical Comments When:
- **Architectural Context**: The change represents a significant pattern shift
- **Migration Guidance**: Future developers might need to understand the evolution
- **Decision Rationale**: The "why" behind the change is still relevant
- **Alternative Approaches**: The comment can guide future implementation choices
## 🔄 Transformation Patterns
### 1. From Removal Notice to Migration Note
```typescript
// ❌ REMOVE THIS
// turnOffNotifyingFlags method removed - notification state is now managed by NotificationSection component
// ✅ TRANSFORM TO THIS
// Note: Notification state management has been migrated to NotificationSection component
// which handles its own lifecycle and persistence via PlatformServiceMixin
```
### 2. From Deprecation Notice to Implementation Guide
```typescript
// ❌ REMOVE THIS
// This will be handled by the NewComponent now
// No need to call oldMethod() as it's no longer needed
// ✅ TRANSFORM TO THIS
// Note: This functionality has been migrated to NewComponent
// which provides better separation of concerns and testability
```
### 3. From Historical Note to Architectural Context
```typescript
// ❌ REMOVE THIS
// Old approach: used direct database calls
// New approach: uses service layer
// ✅ TRANSFORM TO THIS
// Note: Database access has been abstracted through service layer
// for better testability and platform independence
```
## 🚫 Anti-Patterns to Remove
- Comments that only state what was removed
- Comments that don't explain the current approach
- Comments that reference non-existent methods
- Comments that are self-evident from the code
- Comments that don't help future decision-making
## ✅ Best Practices
### When Keeping Historical Context:
1. **Explain the "Why"**: Why was the change made?
2. **Describe the "What"**: What is the current approach?
3. **Provide Context**: When might this information be useful?
4. **Use Actionable Language**: Guide future decisions, not just document history
### When Removing Historical Context:
1. **Verify Obsoleteness**: Ensure the information is truly outdated
2. **Check for Dependencies**: Ensure no other code references the old approach
3. **Update Related Docs**: If removing from code, consider adding to documentation
4. **Preserve in Git History**: The change is preserved in version control
## 🔍 Implementation Checklist
- [ ] Identify historical comments about removed/deprecated functionality
- [ ] Determine if comment provides actionable guidance
- [ ] Transform useful comments into migration notes or architectural context
- [ ] Remove comments that are purely historical without guidance value
- [ ] Ensure remaining comments explain current approach and rationale
- [ ] Update related documentation if significant context is removed
## 📚 Examples
### Good Historical Comment (Keep & Transform)
```typescript
// Note: Database access has been migrated from direct IndexedDB calls to PlatformServiceMixin
// This provides better platform abstraction and consistent error handling across web/mobile/desktop
// When adding new database operations, use this.$getContact(), this.$saveSettings(), etc.
```
### Bad Historical Comment (Remove)
```typescript
// Old method getContactFromDB() removed - now handled by PlatformServiceMixin
// No need to call the old method anymore
```
## 🎯 Integration with Harbor Pilot
This rule works in conjunction with:
- **Component Creation Ideals**: Maintains architectural consistency
- **Migration Patterns**: Documents evolution of patterns
- **Code Review Guidelines**: Ensures comments provide value
## 📝 Version History
### v1.0.0 (2025-08-21)
- Initial creation based on notification system cleanup
- Established decision framework for historical comment management
- Added transformation patterns and anti-patterns
- Integrated with existing Harbor Pilot architecture rules

117
.cursor/rules/investigation_report_example.mdc

@ -0,0 +1,117 @@
# Investigation Report Example
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Investigation methodology example
## Investigation — Registration Dialog Test Flakiness
## Objective
Identify root cause of flaky tests related to registration dialogs in contact
import scenarios.
## System Map
- User action → ContactInputForm → ContactsView.addContact() →
handleRegistrationPrompt()
- setTimeout(1000ms) → Modal dialog → User response → Registration API call
- Test execution → Wait for dialog → Assert dialog content → Click response
button
## Findings (Evidence)
- **1-second timeout causes flakiness** — evidence:
`src/views/ContactsView.vue:971-1000`; setTimeout(..., 1000) in
handleRegistrationPrompt()
- **Import flow bypasses dialogs** — evidence:
`src/views/ContactImportView.vue:500-520`; importContacts() calls
$insertContact() directly, no handleRegistrationPrompt()
- **Dialog only appears in direct add flow** — evidence:
`src/views/ContactsView.vue:774-800`; addContact() calls
handleRegistrationPrompt() after database insert
## Hypotheses & Failure Modes
- H1: 1-second timeout makes dialog appearance unpredictable; would fail when
tests run faster than 1000ms
- H2: Test environment timing differs from development; watch for CI vs local
test differences
## Corrections
- Updated: "Multiple dialogs interfere with imports" → "Import flow never
triggers dialogs - they only appear in direct contact addition"
- Updated: "Complex batch registration needed" → "Simple timeout removal and
test mode flag sufficient"
## Diagnostics (Next Checks)
- [ ] Repro on CI environment vs local
- [ ] Measure actual dialog appearance timing
- [ ] Test with setTimeout removed
- [ ] Verify import flow doesn't call handleRegistrationPrompt
## Risks & Scope
- Impacted: Contact addition tests, registration workflow tests; Data: None;
Users: Test suite reliability
## Decision / Next Steps
- Owner: Development Team; By: 2025-01-28
- Action: Remove 1-second timeout + add test mode flag; Exit criteria: Tests
pass consistently
## References
- `src/views/ContactsView.vue:971-1000`
- `src/views/ContactImportView.vue:500-520`
- `src/views/ContactsView.vue:774-800`
## Competence Hooks
- Why this works: Code path tracing revealed separate execution flows,
evidence disproved initial assumptions
- Common pitfalls: Assuming related functionality without tracing execution
paths, over-engineering solutions to imaginary problems
- Next skill: Learn to trace code execution before proposing architectural
changes
- Teach-back: "What evidence shows that contact imports bypass registration
dialogs?"
## Key Learning Points
### Evidence-First Approach
This investigation demonstrates the importance of:
1. **Tracing actual code execution** rather than making assumptions
2. **Citing specific evidence** with file:line references
3. **Validating problem scope** before proposing solutions
4. **Considering simpler alternatives** before complex architectural changes
### Code Path Tracing Value
By tracing the execution paths, we discovered:
- Import flow and direct add flow are completely separate
- The "multiple dialog interference" problem didn't exist
- A simple timeout removal would solve the actual issue
### Prevention of Over-Engineering
The investigation prevented:
- Unnecessary database schema changes
- Complex batch registration systems
- Migration scripts for non-existent problems
- Architectural changes based on assumptions
---
**Status**: Active investigation methodology
**Priority**: High
**Estimated Effort**: Ongoing reference
**Dependencies**: software_development.mdc
**Stakeholders**: Development team, QA team

6
.cursor/rules/legacy_dexie.mdc

@ -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.

222
.cursor/rules/logging_standards.mdc

@ -0,0 +1,222 @@
# Agent Contract — TimeSafari Logging (Unified, MANDATORY)
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Mandatory logging standards
## Overview
This document defines unified logging standards for the TimeSafari project,
ensuring consistent, rest-parameter logging style using the project logger.
No `console.*` methods are allowed in production code.
## Scope and Goals
**Scope**: Applies to all diffs and generated code in this workspace unless
explicitly exempted below.
**Goal**: One consistent, rest-parameter logging style using the project
logger; no `console.*` in production code.
## Non‑Negotiables (DO THIS)
- You **MUST** use the project logger; **DO NOT** use any `console.*`
methods.
- Import exactly as:
- `import { logger } from '@/utils/logger'`
- If `@` alias is unavailable, compute the correct relative path (do not
fail).
- Call signatures use **rest parameters**: `logger.info(message, ...args)`
- Prefer primitives/IDs and small objects in `...args`; **never build a
throwaway object** just to "wrap context".
- Production defaults: Web = `warn+`, Electron = `error`, Dev/Capacitor =
`info+` (override via `VITE_LOG_LEVEL`).
- **Database persistence**: `info|warn|error` are persisted; `debug` is not.
Use `logger.toDb(msg, level?)` for DB-only.
## Available Logger API (Authoritative)
- `logger.debug(message, ...args)` — verbose internals, timings, input/output
shapes
- `logger.log(message, ...args)` — synonym of `info` for general info
- `logger.info(message, ...args)` — lifecycle, state changes, success paths
- `logger.warn(message, ...args)` — recoverable issues, retries, degraded mode
- `logger.error(message, ...args)` — failures, thrown exceptions, aborts
- `logger.toDb(message, level?)` — DB-only entry (default level = `info`)
- `logger.toConsoleAndDb(message, isError)` — console + DB (use sparingly)
- `logger.withContext(componentName)` — returns a scoped logger
## Level Guidelines (Use These Heuristics)
### DEBUG
Use for method entry/exit, computed values, filters, loops, retries, and
external call payload sizes.
```typescript
logger.debug('[HomeView] reloadFeedOnChange() called');
logger.debug('[HomeView] Current filter settings',
settings.filterFeedByVisible,
settings.filterFeedByNearby,
settings.searchBoxes?.length ?? 0);
logger.debug('[FeedFilters] Toggling nearby filter',
this.isNearby, this.settingChanged, this.activeDid);
```
**Avoid**: Vague messages (`'Processing data'`).
### INFO
Use for user-visible lifecycle and completed operations.
```typescript
logger.info('[StartView] Component mounted', process.env.VITE_PLATFORM);
logger.info('[StartView] User selected new seed generation');
logger.info('[SearchAreaView] Search box stored',
searchBox.name, searchBox.bbox);
logger.info('[ContactQRScanShowView] Contact registration OK',
contact.did);
```
**Avoid**: Diagnostic details that belong in `debug`.
### WARN
Use for recoverable issues, fallbacks, unexpected-but-handled conditions.
```typescript
logger.warn('[ContactQRScanShowView] Invalid scan result – no value',
resultType);
logger.warn('[ContactQRScanShowView] Invalid QR format – no JWT in URL');
logger.warn('[ContactQRScanShowView] JWT missing "own" field');
```
**Avoid**: Hard failures (those are `error`).
### ERROR
Use for unrecoverable failures, data integrity issues, and thrown
exceptions.
```typescript
logger.error('[HomeView Settings] initializeIdentity() failed', err);
logger.error('[StartView] Failed to load initialization data', error);
logger.error('[ContactQRScanShowView] Error processing contact QR',
error, rawValue);
```
**Avoid**: Expected user cancels (use `info`/`debug`).
## Context Hygiene (Consistent, Minimal, Helpful)
- **Component context**: Prefer scoped logger.
```typescript
const log = logger.withContext('UserService');
log.info('User created', userId);
log.error('Failed to create user', error);
```
If not using `withContext`, prefix message with `[ComponentName]`.
- **Emojis**: Optional and minimal for visual scanning. Recommended set:
- Start/finish: 🚀 / ✅
- Retry/loop: 🔄
- External call: 📡
- Data/metrics: 📊
- Inspection: 🔍
- **Sensitive data**: Never log secrets (tokens, keys, passwords) or
payloads >10KB. Prefer IDs over objects; redact/hash when needed.
## Migration — Auto‑Rewrites (Apply Every Time)
- Exact transforms:
- `console.debug(...)` → `logger.debug(...)`
- `console.log(...)` → `logger.log(...)` (or `logger.info(...)` when
clearly stateful)
- `console.info(...)` → `logger.info(...)`
- `console.warn(...)` → `logger.warn(...)`
- `console.error(...)` → `logger.error(...)`
- Multi-arg handling:
- First arg becomes `message` (stringify safely if non-string).
- Remaining args map 1:1 to `...args`:
`console.info(msg, a, b)` → `logger.info(String(msg), a, b)`
- Sole `Error`:
- `console.error(err)` → `logger.error(err.message, err)`
- **Object-wrapping cleanup**: Replace `{{ userId, meta }}` wrappers with
separate args:
`logger.info('User signed in', userId, meta)`
## DB Logging Rules
- `debug` **never** persists automatically.
- `info|warn|error` persist automatically.
- For DB-only events (no console), call `logger.toDb('Message',
'info'|'warn'|'error')`.
## Exceptions (Tightly Scoped)
Allowed paths (still prefer logger):
- `**/*.test.*`, `**/*.spec.*`
- `scripts/dev/**`, `scripts/migrate/**`
To intentionally keep `console.*`, add a pragma on the previous line:
```typescript
// cursor:allow-console reason="short justification"
console.log('temporary output');
```
Without the pragma, rewrite to `logger.*`.
## CI & Diff Enforcement
- Do not introduce `console.*` anywhere outside allowed, pragma'd spots.
- If an import is missing, insert it and resolve alias/relative path
correctly.
- Enforce rest-parameter call shape in reviews; replace object-wrapped
context.
- Ensure environment log level rules remain intact (`VITE_LOG_LEVEL`
respected).
## Quick Before/After
### **Before**
```typescript
console.log('User signed in', user.id, meta);
console.error('Failed to update profile', err);
console.info('Filter toggled', this.hasVisibleDid);
```
### **After**
```typescript
import { logger } from '@/utils/logger';
logger.info('User signed in', user.id, meta);
logger.error('Failed to update profile', err);
logger.debug('[FeedFilters] Filter toggled', this.hasVisibleDid);
```
## Checklist (for every PR)
- [ ] No `console.*` (or properly pragma'd in the allowed locations)
- [ ] Correct import path for `logger`
- [ ] Rest-parameter call shape (`message, ...args`)
- [ ] Right level chosen (debug/info/warn/error)
- [ ] No secrets / oversized payloads / throwaway context objects
- [ ] Component context provided (scoped logger or `[Component]` prefix)
---
**Status**: Active and enforced
**Priority**: Critical
**Estimated Effort**: Ongoing reference
**Dependencies**: TimeSafari logger utility
**Stakeholders**: Development team, Code review team

348
.cursor/rules/realistic_time_estimation.mdc

@ -0,0 +1,348 @@
---
description: when generating text that has project task work estimates
alwaysApply: false
---
# No Time Estimates — Harbor Pilot Directive
> **Agent role**: **DO NOT MAKE TIME ESTIMATES**. Instead, use phases, milestones, and complexity levels. Time estimates are consistently wrong and create unrealistic expectations.
## 🎯 Purpose
Development time estimates are consistently wrong and create unrealistic expectations. This rule ensures we focus on phases, milestones, and complexity rather than trying to predict specific timeframes.
## 🚨 Critical Rule
**DO NOT MAKE TIME ESTIMATES**
- **Never provide specific time estimates** - they are always wrong
- **Use phases and milestones** instead of days/weeks
- **Focus on complexity and dependencies** rather than time
- **Set expectations based on progress, not deadlines**
## 📊 Planning Framework (Not Time Estimates)
### **Complexity Categories**
- **Simple**: Text changes, styling updates, minor bug fixes
- **Medium**: New features, refactoring, component updates
- **Complex**: Architecture changes, integrations, cross-platform work
- **Unknown**: New technologies, APIs, or approaches
### **Platform Complexity**
- **Single platform**: Web-only or mobile-only changes
- **Two platforms**: Web + mobile or web + desktop
- **Three platforms**: Web + mobile + desktop
- **Cross-platform consistency**: Ensuring behavior matches across all platforms
### **Testing Complexity**
- **Basic**: Unit tests for new functionality
- **Comprehensive**: Integration tests, cross-platform testing
- **User acceptance**: User testing, feedback integration
## 🔍 Planning Process (No Time Estimates)
### **Step 1: Break Down the Work**
- Identify all subtasks and dependencies
- Group related work into logical phases
- Identify critical path and blockers
### **Step 2: Define Phases and Milestones**
- **Phase 1**: Foundation work (basic fixes, core functionality)
- **Phase 2**: Enhancement work (new features, integrations)
- **Phase 3**: Polish work (testing, user experience, edge cases)
### **Step 3: Identify Dependencies**
- **Technical dependencies**: What must be built first
- **Platform dependencies**: What works on which platforms
- **Testing dependencies**: What can be tested when
### **Step 4: Set Progress Milestones**
- **Milestone 1**: Basic functionality working
- **Milestone 2**: All platforms supported
- **Milestone 3**: Fully tested and polished
## 📋 Planning Checklist (No Time Estimates)
- [ ] Work broken down into logical phases
- [ ] Dependencies identified and mapped
- [ ] Milestones defined with clear criteria
- [ ] Complexity levels assigned to each phase
- [ ] Platform requirements identified
- [ ] Testing strategy planned
- [ ] Risk factors identified
- [ ] Success criteria defined
## 🎯 Example Planning (No Time Estimates)
### **Example 1: Simple Feature**
```
Phase 1: Core implementation
- Basic functionality
- Single platform support
- Unit tests
Phase 2: Platform expansion
- Multi-platform support
- Integration tests
Phase 3: Polish
- User testing
- Edge case handling
```
### **Example 2: Complex Cross-Platform Feature**
```
Phase 1: Foundation
- Architecture design
- Core service implementation
- Basic web platform support
Phase 2: Platform Integration
- Mobile platform support
- Desktop platform support
- Cross-platform consistency
Phase 3: Testing & Polish
- Comprehensive testing
- Error handling
- User experience refinement
```
## 🚫 Anti-Patterns to Avoid
- **"This should take X days"** - Red flag for time estimation
- **"Just a few hours"** - Ignores complexity and testing
- **"Similar to X"** - Without considering differences
- **"Quick fix"** - Nothing is ever quick in software
- **"No testing needed"** - Testing always takes effort
## ✅ Best Practices
### **When Planning:**
1. **Break down everything** - no work is too small to plan
2. **Consider all platforms** - web, mobile, desktop differences
3. **Include testing strategy** - unit, integration, and user testing
4. **Account for unknowns** - there are always surprises
5. **Focus on dependencies** - what blocks what
### **When Presenting Plans:**
1. **Show the phases** - explain the logical progression
2. **Highlight dependencies** - what could block progress
3. **Define milestones** - clear success criteria
4. **Identify risks** - what could go wrong
5. **Suggest alternatives** - ways to reduce scope or complexity
## 🔄 Continuous Improvement
### **Track Progress**
- Record planned vs. actual phases completed
- Identify what took longer than expected
- Learn from complexity misjudgments
- Adjust planning process based on experience
### **Learn from Experience**
- **Underestimated complexity**: Increase complexity categories
- **Missed dependencies**: Improve dependency mapping
- **Platform surprises**: Better platform research upfront
## 🎯 Integration with Harbor Pilot
This rule works in conjunction with:
- **Project Planning**: Focuses on phases and milestones
- **Resource Allocation**: Based on complexity, not time
- **Risk Management**: Identifies blockers and dependencies
- **Stakeholder Communication**: Sets progress-based expectations
## 📝 Version History
### v2.0.0 (2025-08-21)
- **Major Change**: Completely removed time estimation approach
- **New Focus**: Phases, milestones, and complexity-based planning
- **Eliminated**: All time multipliers, estimates, and calculations
- **Added**: Dependency mapping and progress milestone framework
### v1.0.0 (2025-08-21)
- Initial creation based on user feedback about estimation accuracy
- ~~Established realistic estimation multipliers and process~~
- ~~Added comprehensive estimation checklist and examples~~
- Integrated with Harbor Pilot planning and risk management
---
## 🚨 Remember
**DO NOT MAKE TIME ESTIMATES. Use phases, milestones, and complexity instead. Focus on progress, not deadlines.**
## 🚨 Remember
**Your first estimate is wrong. Your second estimate is probably still wrong. Focus on progress, not deadlines.**
# No Time Estimates — Harbor Pilot Directive
> **Agent role**: **DO NOT MAKE TIME ESTIMATES**. Instead, use phases, milestones, and complexity levels. Time estimates are consistently wrong and create unrealistic expectations.
## 🎯 Purpose
Development time estimates are consistently wrong and create unrealistic expectations. This rule ensures we focus on phases, milestones, and complexity rather than trying to predict specific timeframes.
## 🚨 Critical Rule
**DO NOT MAKE TIME ESTIMATES**
- **Never provide specific time estimates** - they are always wrong
- **Use phases and milestones** instead of days/weeks
- **Focus on complexity and dependencies** rather than time
- **Set expectations based on progress, not deadlines**
## 📊 Planning Framework (Not Time Estimates)
### **Complexity Categories**
- **Simple**: Text changes, styling updates, minor bug fixes
- **Medium**: New features, refactoring, component updates
- **Complex**: Architecture changes, integrations, cross-platform work
- **Unknown**: New technologies, APIs, or approaches
### **Platform Complexity**
- **Single platform**: Web-only or mobile-only changes
- **Two platforms**: Web + mobile or web + desktop
- **Three platforms**: Web + mobile + desktop
- **Cross-platform consistency**: Ensuring behavior matches across all platforms
### **Testing Complexity**
- **Basic**: Unit tests for new functionality
- **Comprehensive**: Integration tests, cross-platform testing
- **User acceptance**: User testing, feedback integration
## 🔍 Planning Process (No Time Estimates)
### **Step 1: Break Down the Work**
- Identify all subtasks and dependencies
- Group related work into logical phases
- Identify critical path and blockers
### **Step 2: Define Phases and Milestones**
- **Phase 1**: Foundation work (basic fixes, core functionality)
- **Phase 2**: Enhancement work (new features, integrations)
- **Phase 3**: Polish work (testing, user experience, edge cases)
### **Step 3: Identify Dependencies**
- **Technical dependencies**: What must be built first
- **Platform dependencies**: What works on which platforms
- **Testing dependencies**: What can be tested when
### **Step 4: Set Progress Milestones**
- **Milestone 1**: Basic functionality working
- **Milestone 2**: All platforms supported
- **Milestone 3**: Fully tested and polished
## 📋 Planning Checklist (No Time Estimates)
- [ ] Work broken down into logical phases
- [ ] Dependencies identified and mapped
- [ ] Milestones defined with clear criteria
- [ ] Complexity levels assigned to each phase
- [ ] Platform requirements identified
- [ ] Testing strategy planned
- [ ] Risk factors identified
- [ ] Success criteria defined
## 🎯 Example Planning (No Time Estimates)
### **Example 1: Simple Feature**
```
Phase 1: Core implementation
- Basic functionality
- Single platform support
- Unit tests
Phase 2: Platform expansion
- Multi-platform support
- Integration tests
Phase 3: Polish
- User testing
- Edge case handling
```
### **Example 2: Complex Cross-Platform Feature**
```
Phase 1: Foundation
- Architecture design
- Core service implementation
- Basic web platform support
Phase 2: Platform Integration
- Mobile platform support
- Desktop platform support
- Cross-platform consistency
Phase 3: Testing & Polish
- Comprehensive testing
- Error handling
- User experience refinement
```
## 🚫 Anti-Patterns to Avoid
- **"This should take X days"** - Red flag for time estimation
- **"Just a few hours"** - Ignores complexity and testing
- **"Similar to X"** - Without considering differences
- **"Quick fix"** - Nothing is ever quick in software
- **"No testing needed"** - Testing always takes effort
## ✅ Best Practices
### **When Planning:**
1. **Break down everything** - no work is too small to plan
2. **Consider all platforms** - web, mobile, desktop differences
3. **Include testing strategy** - unit, integration, and user testing
4. **Account for unknowns** - there are always surprises
5. **Focus on dependencies** - what blocks what
### **When Presenting Plans:**
1. **Show the phases** - explain the logical progression
2. **Highlight dependencies** - what could block progress
3. **Define milestones** - clear success criteria
4. **Identify risks** - what could go wrong
5. **Suggest alternatives** - ways to reduce scope or complexity
## 🔄 Continuous Improvement
### **Track Progress**
- Record planned vs. actual phases completed
- Identify what took longer than expected
- Learn from complexity misjudgments
- Adjust planning process based on experience
### **Learn from Experience**
- **Underestimated complexity**: Increase complexity categories
- **Missed dependencies**: Improve dependency mapping
- **Platform surprises**: Better platform research upfront
## 🎯 Integration with Harbor Pilot
This rule works in conjunction with:
- **Project Planning**: Focuses on phases and milestones
- **Resource Allocation**: Based on complexity, not time
- **Risk Management**: Identifies blockers and dependencies
- **Stakeholder Communication**: Sets progress-based expectations
## 📝 Version History
### v2.0.0 (2025-08-21)
- **Major Change**: Completely removed time estimation approach
- **New Focus**: Phases, milestones, and complexity-based planning
- **Eliminated**: All time multipliers, estimates, and calculations
- **Added**: Dependency mapping and progress milestone framework
### v1.0.0 (2025-08-21)
- Initial creation based on user feedback about estimation accuracy
- ~~Established realistic estimation multipliers and process~~
- ~~Added comprehensive estimation checklist and examples~~
- Integrated with Harbor Pilot planning and risk management
---
## 🚨 Remember
**DO NOT MAKE TIME ESTIMATES. Use phases, milestones, and complexity instead. Focus on progress, not deadlines.**
## 🚨 Remember
**Your first estimate is wrong. Your second estimate is probably still wrong. Focus on progress, not deadlines.**

174
.cursor/rules/research_diagnostic.mdc

@ -0,0 +1,174 @@
---
description: Use this workflow when doing **pre-implementation research, defect investigations with uncertain repros, or clarifying system architecture and behaviors**.
alwaysApply: false
---
```json
{
"coaching_level": "light",
"socratic_max_questions": 2,
"verbosity": "concise",
"timebox_minutes": null,
"format_enforcement": "strict"
}
```
# Research & Diagnostic Workflow (R&D)
## Purpose
Provide a **repeatable, evidence-first** workflow to investigate features and
defects **before coding**. Outputs are concise reports, hypotheses, and next
steps—**not** code changes.
## When to Use
- Pre-implementation research for new features
- Defect investigations (repros uncertain, user-specific failures)
- Architecture/behavior clarifications (e.g., auth flows, merges, migrations)
---
## Enhanced with Software Development Ruleset
When investigating software issues, also apply:
- **Code Path Tracing**: Required for technical investigations
- **Evidence Validation**: Ensure claims are code-backed
- **Solution Complexity Assessment**: Justify architectural changes
---
## Output Contract (strict)
1) **Objective** — 1–2 lines
2) **System Map (if helpful)** — short diagram or bullet flow (≤8 bullets)
3) **Findings (Evidence-linked)** — bullets; each with file/function refs
4) **Hypotheses & Failure Modes** — short list, each testable
5) **Corrections** — explicit deltas from earlier assumptions (if any)
6) **Diagnostics** — what to check next (logs, DB, env, repro steps)
7) **Risks & Scope** — what could break; affected components
8) **Decision/Next Steps** — what we'll do, who's involved, by when
9) **References** — code paths, ADRs, docs
10) **Competence & Collaboration Hooks** — brief, skimmable
> Keep total length lean. Prefer links and bullets over prose.
---
## Quickstart Template
Copy/paste and fill:
```md
# Investigation — <short title>
## Objective
<one or two lines>
## System Map
- <module> → <function> → <downstream>
- <data path> → <db table> → <api>
## Findings (Evidence)
- <claim> — evidence: `src/path/file.ts:function` (lines X–Y); log snippet/trace id
- <claim> — evidence: `...`
## Hypotheses & Failure Modes
- H1: <hypothesis>; would fail when <condition>
- H2: <hypothesis>; watch for <signal>
## Corrections
- Updated: <old statement> → <new statement with evidence>
## Diagnostics (Next Checks)
- [ ] Repro on <platform/version>
- [ ] Inspect <table/store> for <record>
- [ ] Capture <log/trace>
## Risks & Scope
- Impacted: <areas/components>; Data: <tables/keys>; Users: <segments>
## Decision / Next Steps
- Owner: <name>; By: <date> (YYYY-MM-DD)
- Action: <spike/bugfix/ADR>; Exit criteria: <binary checks>
## References
- `src/...`
- ADR: `docs/adr/xxxx-yy-zz-something.md`
- Design: `docs/...`
## Competence Hooks
- Why this works: <≤3 bullets>
- Common pitfalls: <≤3 bullets>
- Next skill: <≤1 item>
- Teach-back: "<one question>"
```
---
## Evidence Quality Bar
- **Cite the source** (file:func, line range if possible).
- **Prefer primary evidence** (code, logs) over inference.
- **Disambiguate platform** (Web/Capacitor/Electron) and **state** (migration, auth).
- **Note uncertainty** explicitly.
---
## Code Path Tracing (Required for Software Investigations)
Before proposing solutions, trace the actual execution path:
- [ ] **Entry Points**: Identify where the flow begins (user action, API call, etc.)
- [ ] **Component Flow**: Map which components/methods are involved
- [ ] **Data Path**: Track how data moves through the system
- [ ] **Exit Points**: Confirm where the flow ends and what results
- [ ] **Evidence Collection**: Gather specific code citations for each step
---
## Collaboration Hooks
- **Syncs:** 10–15m with QA/Security/Platform owners for high-risk areas.
- **ADR:** Record major decisions; link here.
- **Review:** Share repro + diagnostics checklist in PR/issue.
---
## Integration with Other Rulesets
### With software_development.mdc
- **Enhanced Evidence Validation**: Use code path tracing for technical investigations
- **Architecture Assessment**: Apply complexity justification to proposed solutions
- **Impact Analysis**: Assess effects on existing systems before recommendations
### With base_context.mdc
- **Competence Building**: Focus on technical investigation skills
- **Collaboration**: Structure outputs for team review and discussion
---
## Self-Check (model, before responding)
- [ ] Output matches the **Output Contract** sections.
- [ ] Each claim has **evidence** or **uncertainty** is flagged.
- [ ] Hypotheses are testable; diagnostics are actionable.
- [ ] Competence + collaboration hooks present (≤120 words total).
- [ ] Respect toggles; keep it concise.
- [ ] **Code path traced** (for software investigations).
- [ ] **Evidence validated** against actual code execution.
---
## Optional Globs (examples)
> Uncomment `globs` in the header if you want auto-attach behavior.
- `src/platforms/**`, `src/services/**` — attach during service/feature investigations
- `docs/adr/**` — attach when editing ADRs
## Referenced Files
- Consider including templates as context: `@adr_template.mdc`, `@investigation_report_example.mdc`

225
.cursor/rules/software_development.mdc

@ -0,0 +1,225 @@
# Software Development Ruleset
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Core development guidelines
## Purpose
Specialized guidelines for software development tasks including code review,
debugging, architecture decisions, and testing.
## Core Principles
### 1. Evidence-First Development
- **Code Citations Required**: Always cite specific file:line references when
making claims
- **Execution Path Tracing**: Trace actual code execution before proposing
architectural changes
- **Assumption Validation**: Flag assumptions as "assumed" vs "evidence-based"
### 2. Code Review Standards
- **Trace Before Proposing**: Always trace execution paths before suggesting
changes
- **Evidence Over Inference**: Prefer code citations over logical deductions
- **Scope Validation**: Confirm the actual scope of problems before proposing
solutions
### 3. Problem-Solution Validation
- **Problem Scope**: Does the solution address the actual problem?
- **Evidence Alignment**: Does the solution match the evidence?
- **Complexity Justification**: Is added complexity justified by real needs?
- **Alternative Analysis**: What simpler solutions were considered?
### 4. Dependency Management & Environment Validation
- **Pre-build Validation**: Always validate critical dependencies before executing
build scripts
- **Environment Consistency**: Ensure team members have identical development
environments
- **Dependency Verification**: Check that required packages are installed and
accessible
- **Path Resolution**: Use `npx` for local dependencies to avoid PATH issues
## Required Workflows
### Before Proposing Changes
- [ ] **Code Path Tracing**: Map execution flow from entry to exit
- [ ] **Evidence Collection**: Gather specific code citations and logs
- [ ] **Assumption Surfacing**: Identify what's proven vs. inferred
- [ ] **Scope Validation**: Confirm the actual extent of the problem
- [ ] **Dependency Validation**: Verify all required dependencies are available
and accessible
### During Solution Design
- [ ] **Evidence Alignment**: Ensure solution addresses proven problems
- [ ] **Complexity Assessment**: Justify any added complexity
- [ ] **Alternative Evaluation**: Consider simpler approaches first
- [ ] **Impact Analysis**: Assess effects on existing systems
- [ ] **Environment Impact**: Assess how changes affect team member setups
## Software-Specific Competence Hooks
### Evidence Validation
- **"What code path proves this claim?"**
- **"How does data actually flow through the system?"**
- **"What am I assuming vs. what can I prove?"**
### Code Tracing
- **"What's the execution path from user action to system response?"**
- **"Which components actually interact in this scenario?"**
- **"Where does the data originate and where does it end up?"**
### Architecture Decisions
- **"What evidence shows this change is necessary?"**
- **"What simpler solution could achieve the same goal?"**
- **"How does this change affect the existing system architecture?"**
### Dependency & Environment Management
- **"What dependencies does this feature require and are they properly
declared?"**
- **"How will this change affect team member development environments?"**
- **"What validation can we add to catch dependency issues early?"**
## Dependency Management Best Practices
### Pre-build Validation
- **Check Critical Dependencies**: Validate essential tools before executing build
scripts
- **Use npx for Local Dependencies**: Prefer `npx tsx` over direct `tsx` to
avoid PATH issues
- **Environment Consistency**: Ensure all team members have identical dependency
versions
### Common Pitfalls
- **Missing npm install**: Team members cloning without running `npm install`
- **PATH Issues**: Direct command execution vs. npm script execution differences
- **Version Mismatches**: Different Node.js/npm versions across team members
### Validation Strategies
- **Dependency Check Scripts**: Implement pre-build validation for critical
dependencies
- **Environment Requirements**: Document and enforce minimum Node.js/npm versions
- **Onboarding Checklist**: Standardize team member setup procedures
### Error Messages and Guidance
- **Specific Error Context**: Provide clear guidance when dependency issues occur
- **Actionable Solutions**: Direct users to specific commands (`npm install`,
`npm run check:dependencies`)
- **Environment Diagnostics**: Implement comprehensive environment validation
tools
### Build Script Enhancements
- **Early Validation**: Check dependencies before starting build processes
- **Graceful Degradation**: Continue builds when possible but warn about issues
- **Helpful Tips**: Remind users about dependency management best practices
## Integration with Other Rulesets
### With base_context.mdc
- Inherits generic competence principles
- Adds software-specific evidence requirements
- Maintains collaboration and learning focus
### With research_diagnostic.mdc
- Enhances investigation with code path tracing
- Adds evidence validation to diagnostic workflow
- Strengthens problem identification accuracy
## Usage Guidelines
### When to Use This Ruleset
- Code reviews and architectural decisions
- Bug investigation and debugging
- Performance optimization
- Feature implementation planning
- Testing strategy development
### When to Combine with Others
- **base_context + software_development**: General development tasks
- **research_diagnostic + software_development**: Technical investigations
- **All three**: Complex architectural decisions or major refactoring
## Self-Check (model, before responding)
- [ ] Code path traced and documented
- [ ] Evidence cited with specific file:line references
- [ ] Assumptions clearly flagged as proven vs. inferred
- [ ] Solution complexity justified by evidence
- [ ] Simpler alternatives considered and documented
- [ ] Impact on existing systems assessed
- [ ] Dependencies validated and accessible
- [ ] Environment impact assessed for team members
- [ ] Pre-build validation implemented where appropriate
## Additional Core Principles
### 4. Dependency Management & Environment Validation
- **Pre-build Validation**: Always validate critical dependencies before executing build scripts
- **Environment Consistency**: Ensure team members have identical development environments
- **Dependency Verification**: Check that required packages are installed and accessible
- **Path Resolution**: Use `npx` for local dependencies to avoid PATH issues
## Additional Required Workflows
### Dependency Validation (Before Proposing Changes)
- [ ] **Dependency Validation**: Verify all required dependencies are available and accessible
### Environment Impact Assessment (During Solution Design)
- [ ] **Environment Impact**: Assess how changes affect team member setups
## Additional Competence Hooks
### Dependency & Environment Management
- **"What dependencies does this feature require and are they properly declared?"**
- **"How will this change affect team member development environments?"**
- **"What validation can we add to catch dependency issues early?"**
## Dependency Management Best Practices
### Pre-build Validation
- **Check Critical Dependencies**: Validate essential tools before executing build scripts
- **Use npx for Local Dependencies**: Prefer `npx tsx` over direct `tsx` to avoid PATH issues
- **Environment Consistency**: Ensure all team members have identical dependency versions
### Common Pitfalls
- **Missing npm install**: Team members cloning without running `npm install`
- **PATH Issues**: Direct command execution vs. npm script execution differences
- **Version Mismatches**: Different Node.js/npm versions across team members
### Validation Strategies
- **Dependency Check Scripts**: Implement pre-build validation for critical dependencies
- **Environment Requirements**: Document and enforce minimum Node.js/npm versions
- **Onboarding Checklist**: Standardize team member setup procedures
### Error Messages and Guidance
- **Specific Error Context**: Provide clear guidance when dependency issues occur
- **Actionable Solutions**: Direct users to specific commands (`npm install`, `npm run check:dependencies`)
- **Environment Diagnostics**: Implement comprehensive environment validation tools
### Build Script Enhancements
- **Early Validation**: Check dependencies before starting build processes
- **Graceful Degradation**: Continue builds when possible but warn about issues
- **Helpful Tips**: Remind users about dependency management best practices
- **Narrow Types Properly**: Use type guards to narrow `unknown` types safely
- **Document Type Decisions**: Explain complex type structures and their purpose

329
.cursor/rules/time.mdc

@ -0,0 +1,329 @@
---
alwaysApply: true
---
# Time Handling in Development Workflow
**Author**: Matthew Raymer
**Date**: 2025-08-17
**Status**: 🎯 **ACTIVE** - Production Ready
## Overview
This guide establishes **how time should be referenced and used** across the
development workflow. It is not tied to any one project, but applies to **all
feature development, issue investigations, ADRs, and documentation**.
## General Principles
- **Explicit over relative**: Always prefer absolute dates (`2025-08-17`) over
relative references like "last week."
- **ISO 8601 Standard**: Use `YYYY-MM-DD` format for all date references in
docs, issues, ADRs, and commits.
- **Time zones**: Default to **UTC** unless explicitly tied to user-facing
behavior.
- **Precision**: Only specify as much precision as needed (date vs. datetime vs.
timestamp).
- **Consistency**: Align time references across ADRs, commits, and investigation
reports.
## In Documentation & ADRs
- Record decision dates using **absolute ISO dates**.
- For ongoing timelines, state start and end explicitly (e.g., `2025-08-01` →
`2025-08-17`).
- Avoid ambiguous terms like *recently*, *last month*, or *soon*.
- For time-based experiments (e.g., A/B tests), always include:
- Start date
- Expected duration
- Review date checkpoint
## In Code & Commits
- Use **UTC timestamps** in logs, DB migrations, and serialized formats.
- In commits, link changes to **date-bound ADRs or investigation docs**.
- For migrations, include both **applied date** and **intended version window**.
- Use constants for known fixed dates; avoid hardcoding arbitrary strings.
## In Investigations & Research
- Capture **when** an issue occurred (absolute time or version tag).
- When describing failures: note whether they are **time-sensitive** (e.g., after
migrations, cache expirations).
- Record diagnostic timelines in ISO format (not relative).
- For performance regressions, annotate both **baseline timeframe** and
**measurement timeframe**.
## Collaboration Hooks
- During reviews, verify **time references are clear, absolute, and
standardized**.
- In syncs, reframe relative terms ("this week") into shared absolute
references.
- Tag ADRs with both **date created** and **review by** checkpoints.
## Self-Check Before Submitting
- [ ] Did I check the time using the **developer's actual system time and
timezone**?
- [ ] Am I using absolute ISO dates?
- [ ] Is UTC assumed unless specified otherwise?
- [ ] Did I avoid ambiguous relative terms?
- [ ] If duration matters, did I specify both start and end?
- [ ] For future work, did I include a review/revisit date?
## Real-Time Context in Developer Interactions
- The model must always resolve **"current time"** using the **developer's
actual system time and timezone**.
- When generating timestamps (e.g., in investigation logs, ADRs, or examples),
the model should:
- Use the **developer's current local time** by default.
- Indicate the timezone explicitly (e.g., `2025-08-17T10:32-05:00`).
- Optionally provide UTC alongside if context requires cross-team clarity.
- When interpreting relative terms like *now*, *today*, *last week*:
- Resolve them against the **developer's current time**.
- Convert them into **absolute ISO-8601 values** in the output.
## LLM Time Checking Instructions
**CRITICAL**: The LLM must actively query the system for current time rather
than assuming or inventing times.
### How to Check Current Time
#### 1. **Query System Time (Required)**
- **Always start** by querying the current system time using available tools
- **Never assume** what the current time is
- **Never use** placeholder values like "current time" or "now"
#### 2. **Available Time Query Methods**
- **System Clock**: Use `date` command or equivalent system time function
- **Programming Language**: Use language-specific time functions (e.g.,
`Date.now()`, `datetime.now()`)
- **Environment Variables**: Check for time-related environment variables
- **API Calls**: Use time service APIs if available
#### 3. **Required Time Information**
When querying time, always obtain:
- **Current Date**: YYYY-MM-DD format
- **Current Time**: HH:MM:SS format (24-hour)
- **Timezone**: Current system timezone or UTC offset
- **UTC Equivalent**: Convert local time to UTC for cross-team clarity
#### 4. **Time Query Examples**
```bash
# Example: Query system time
$ date
# Expected output: Mon Aug 17 10:32:45 EDT 2025
# Example: Query UTC time
$ date -u
# Expected output: Mon Aug 17 14:32:45 UTC 2025
```
```python
# Example: Python time query
import datetime
current_time = datetime.datetime.now()
utc_time = datetime.datetime.utcnow()
print(f"Local: {current_time}")
print(f"UTC: {utc_time}")
```
```javascript
// Example: JavaScript time query
const now = new Date();
const utc = new Date().toISOString();
console.log(`Local: ${now}`);
console.log(`UTC: ${utc}`);
```
#### 5. **LLM Time Checking Workflow**
1. **Query**: Actively query system for current time
2. **Validate**: Confirm time data is reasonable and current
3. **Format**: Convert to ISO 8601 format
4. **Context**: Provide both local and UTC times when helpful
5. **Document**: Show the source of time information
#### 6. **Error Handling for Time Queries**
- **If time query fails**: Ask user for current time or use "unknown time"
with explanation
- **If timezone unclear**: Default to UTC and ask for clarification
- **If time seems wrong**: Verify with user before proceeding
- **Always log**: Record when and how time was obtained
#### 7. **Time Query Verification**
Before using queried time, verify:
- [ ] Time is recent (within last few minutes)
- [ ] Timezone information is available
- [ ] UTC conversion is accurate
- [ ] Format follows ISO 8601 standard
## Model Behavior Rules
- **Never invent a "fake now"**: All "current time" references must come from
the real system clock available at runtime.
- **Check developer time zone**: If ambiguous, ask for clarification (e.g.,
"Should I use UTC or your local timezone?").
- **Format for clarity**:
- Local time: `YYYY-MM-DDTHH:mm±hh:mm`
- UTC equivalent (if needed): `YYYY-MM-DDTHH:mmZ`
## Examples
### Good
- "Feature flag rollout started on `2025-08-01` and will be reviewed on
`2025-08-21`."
- "Migration applied on `2025-07-15T14:00Z`."
- "Issue reproduced on `2025-08-17T09:00-05:00 (local)` /
`2025-08-17T14:00Z (UTC)`."
### Bad
- "Feature flag rolled out last week."
- "Migration applied recently."
- "Now is August, so we assume this was last month."
### More Examples
#### Issue Reports
- ✅ **Good**: "User reported login failure at `2025-08-17T14:30:00Z`. Issue
persisted until `2025-08-17T15:45:00Z`."
- ❌ **Bad**: "User reported login failure earlier today. Issue lasted for a
while."
#### Release Planning
- ✅ **Good**: "Feature X scheduled for release on `2025-08-25`. Testing
window: `2025-08-20` to `2025-08-24`."
- ❌ **Bad**: "Feature X will be released next week after testing."
#### Performance Monitoring
- ✅ **Good**: "Baseline performance measured on `2025-08-10T09:00:00Z`.
Regression detected on `2025-08-15T14:00:00Z`."
- ❌ **Bad**: "Performance was good last week but got worse this week."
## Technical Implementation Notes
### UTC Storage Principle
- **Store all timestamps in UTC** in databases, logs, and serialized formats
- **Convert to local time only for user display**
- **Use ISO 8601 format** for all storage: `YYYY-MM-DDTHH:mm:ss.sssZ`
### Common Implementation Patterns
#### Database Storage
```sql
-- ✅ Good: Store in UTC
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
-- ❌ Bad: Store in local time
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
```
#### API Responses
```json
// ✅ Good: Include both UTC and local time
{
"eventTime": "2025-08-17T14:00:00Z",
"localTime": "2025-08-17T10:00:00-04:00",
"timezone": "America/New_York"
}
// ❌ Bad: Only local time
{
"eventTime": "2025-08-17T10:00:00-04:00"
}
```
#### Logging
```python
# ✅ Good: Log in UTC with timezone info
logger.info(f"User action at {datetime.utcnow().isoformat()}Z (UTC)")
# ❌ Bad: Log in local time
logger.info(f"User action at {datetime.now()}")
```
### Timezone Handling Best Practices
#### 1. Always Store Timezone Information
- Include IANA timezone identifier (e.g., `America/New_York`)
- Store UTC offset at time of creation
- Handle daylight saving time transitions automatically
#### 2. User Display Considerations
- Convert UTC to user's preferred timezone
- Show timezone abbreviation when helpful
- Use relative time for recent events ("2 hours ago")
#### 3. Edge Case Handling
- **Daylight Saving Time**: Use timezone-aware libraries
- **Leap Seconds**: Handle gracefully (rare but important)
- **Invalid Times**: Validate before processing
### Common Mistakes to Avoid
#### 1. Timezone Confusion
- ❌ **Don't**: Assume server timezone is user timezone
- ✅ **Do**: Always convert UTC to user's local time for display
#### 2. Format Inconsistency
- ❌ **Don't**: Mix different time formats in the same system
- ✅ **Do**: Standardize on ISO 8601 for all storage
#### 3. Relative Time References
- ❌ **Don't**: Use relative terms in persistent storage
- ✅ **Do**: Convert relative terms to absolute timestamps immediately
## References
- [ISO 8601 Date and Time Standard](https://en.wikipedia.org/wiki/ISO_8601)
- [IANA Timezone Database](https://www.iana.org/time-zones)
- [ADR Template](./adr_template.md)
- [Research & Diagnostic Workflow](./research_diagnostic.mdc)
---
**Rule of Thumb**: Every time reference in development artifacts should be
**clear in 6 months without context**, and aligned to the **developer's actual
current time**.
**Technical Rule of Thumb**: **Store in UTC, display in local time, always
include timezone context.**
---
**Status**: Active
**Version**: 1.0
**Maintainer**: Matthew Raymer
**Next Review**: 2025-09-17

276
.cursor/rules/timesafari.mdc

@ -1,276 +0,0 @@
---
description:
globs:
alwaysApply: true
---
---
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
### 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
### Continuous Integration/Continuous Deployment (CI/CD)
- Automated testing on every commit
- Consistent build process across platforms
- Automated deployment pipelines
- Quality gates for code merging
- Environment-specific configurations
This expanded documentation provides:
1. Clear principles for development
2. Practical implementation guidelines
3. Real-world examples
4. TypeScript integration
5. Best practices for Time Safari

335
.cursor/rules/workflow/version_control.mdc

@ -0,0 +1,335 @@
---
description: interacting with git
alwaysApply: false
---
# Directive: Peaceful Co-Existence with Developers
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Version control guidelines
## 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.
## 4) Version Synchronization Requirements
- **MUST** check for version changes in `package.json` before committing
- **MUST** ensure `CHANGELOG.md` is updated when `package.json` version
changes
- **MUST** validate version format consistency between both files
- **MUST** include version bump commits in changelog with proper semantic
versioning
### Version Sync Checklist (Before Commit)
- [ ] `package.json` version matches latest `CHANGELOG.md` entry
- [ ] New version follows semantic versioning
(MAJOR.MINOR.PATCH[-PRERELEASE])
- [ ] Changelog entry includes all significant changes since last version
- [ ] Version bump commit message follows `build(version): bump to X.Y.Z`
format
- [ ] Breaking changes properly documented with migration notes
- [ ] Alert developer in chat message that version has been updated
### Version Change Detection
- **Check for version changes** in staged/unstaged `package.json`
- **Alert developer** if version changed but changelog not updated
- **Suggest changelog update** with proper format and content
- **Validate semantic versioning** compliance
### Implementation Notes
- **Version Detection**: Compare `package.json` version field with latest
changelog entry
- **Semantic Validation**: Ensure version follows `X.Y.Z[-PRERELEASE]`
format
- **Changelog Format**: Follow [Keep a Changelog](https://keepachangelog.com/)
standards
- **Breaking Changes**: Use `!` in commit message and `BREAKING CHANGE:`
in changelog
- **Pre-release Versions**: Include beta/alpha/rc suffixes in both files
consistently
## 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 isn't 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 + 1–2 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
---
**Status**: Active version control guidelines
**Priority**: High
**Estimated Effort**: Ongoing reference
**Dependencies**: git, package.json, CHANGELOG.md
**Stakeholders**: Development team, AI assistants
- [ ] No invented changes; aligns strictly with diffs
- [ ] Render as a single copy-paste block for the developer
## 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.
## 4) Version Synchronization Requirements
- **MUST** check for version changes in `package.json` before committing
- **MUST** ensure `CHANGELOG.md` is updated when `package.json` version
changes
- **MUST** validate version format consistency between both files
- **MUST** include version bump commits in changelog with proper semantic
versioning
### Version Sync Checklist (Before Commit)
- [ ] `package.json` version matches latest `CHANGELOG.md` entry
- [ ] New version follows semantic versioning
(MAJOR.MINOR.PATCH[-PRERELEASE])
- [ ] Changelog entry includes all significant changes since last version
- [ ] Version bump commit message follows `build(version): bump to X.Y.Z`
format
- [ ] Breaking changes properly documented with migration notes
- [ ] Alert developer in chat message that version has been updated
### Version Change Detection
- **Check for version changes** in staged/unstaged `package.json`
- **Alert developer** if version changed but changelog not updated
- **Suggest changelog update** with proper format and content
- **Validate semantic versioning** compliance
### Implementation Notes
- **Version Detection**: Compare `package.json` version field with latest
changelog entry
- **Semantic Validation**: Ensure version follows `X.Y.Z[-PRERELEASE]`
format
- **Changelog Format**: Follow [Keep a Changelog](https://keepachangelog.com/)
standards
- **Breaking Changes**: Use `!` in commit message and `BREAKING CHANGE:`
in changelog
- **Pre-release Versions**: Include beta/alpha/rc suffixes in both files
consistently
## 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 isn't 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 + 1–2 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
---
**Status**: Active version control guidelines
**Priority**: High
**Estimated Effort**: Ongoing reference
**Dependencies**: git, package.json, CHANGELOG.md
**Stakeholders**: Development team, AI assistants
* [ ] No invented changes; aligns strictly with diffs
* [ ] Render as a single copy-paste block for the developer

2
.dockerignore

@ -140,7 +140,7 @@ docker-compose*
.dockerignore .dockerignore
# CI/CD files # CI/CD files
.github
.gitlab-ci.yml .gitlab-ci.yml
.travis.yml .travis.yml
.circleci .circleci

8
.env.development

@ -1,10 +1,14 @@
# Only the variables that start with VITE_ are seen in the application import.meta.env in Vue. # Only the variables that start with VITE_ are seen in the application import.meta.env in Vue.
# Logging Configuration - Development environment gets maximum visibility
VITE_LOG_LEVEL=debug
# iOS doesn't like spaces in the app title. # iOS doesn't like spaces in the app title.
TIME_SAFARI_APP_TITLE="TimeSafari_Dev" TIME_SAFARI_APP_TITLE="TimeSafari_Dev"
VITE_APP_SERVER=http://localhost:8080 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). # This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not
VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F
VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000 VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000
# Using shared server by default to ease setup, which works for shared test users. # Using shared server by default to ease setup, which works for shared test users.

3
.env.production

@ -1,6 +1,7 @@
# Only the variables that start with VITE_ are seen in the application import.meta.env in Vue. # Only the variables that start with VITE_ are seen in the application import.meta.env in Vue.
# Logging Configuration - Production environment gets minimal logging for performance
VITE_LOG_LEVEL=warn
VITE_APP_SERVER=https://timesafari.app VITE_APP_SERVER=https://timesafari.app
# This is the claim ID for actions in the BVC project. # This is the claim ID for actions in the BVC project.

5
.env.test

@ -1,9 +1,14 @@
# Only the variables that start with VITE_ are seen in the application import.meta.env in Vue. # Only the variables that start with VITE_ are seen in the application import.meta.env in Vue.
# Logging Configuration - Test environment gets balanced logging for debugging
VITE_LOG_LEVEL=info
# iOS doesn't like spaces in the app title. # iOS doesn't like spaces in the app title.
TIME_SAFARI_APP_TITLE="TimeSafari_Test" TIME_SAFARI_APP_TITLE="TimeSafari_Test"
VITE_APP_SERVER=https://test.timesafari.app 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
# This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not production). # 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_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F
VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch

2
.eslintrc.js

@ -30,7 +30,7 @@ module.exports = {
}], }],
"no-console": process.env.NODE_ENV === "production" ? "error" : "warn", "no-console": process.env.NODE_ENV === "production" ? "error" : "warn",
"no-debugger": process.env.NODE_ENV === "production" ? "error" : "warn", "no-debugger": process.env.NODE_ENV === "production" ? "error" : "warn",
"@typescript-eslint/no-explicit-any": "warn", "@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/explicit-function-return-type": "off", "@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-unnecessary-type-constraint": "off", "@typescript-eslint/no-unnecessary-type-constraint": "off",
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }] "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }]

27
.github/workflows/playwright.yml

@ -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

12
.gitignore

@ -56,6 +56,10 @@ icons
*.log *.log
# Build outputs
dist/
build/
# Generated Android assets and resources (should be generated during build) # Generated Android assets and resources (should be generated during build)
android/app/src/main/assets/public/ android/app/src/main/assets/public/
@ -64,6 +68,14 @@ android/app/src/main/res/drawable*/
android/app/src/main/res/mipmap*/ android/app/src/main/res/mipmap*/
android/app/src/main/res/values/ic_launcher_background.xml android/app/src/main/res/values/ic_launcher_background.xml
# Android generated assets (deny-listed in CI)
android/app/src/main/res/mipmap-*/ic_launcher*.png
android/app/src/main/res/drawable*/splash*.png
# iOS generated assets (deny-listed in CI)
ios/App/App/Assets.xcassets/**/AppIcon*.png
ios/App/App/Assets.xcassets/**/Splash*.png
# Keep these Android configuration files in version control: # Keep these Android configuration files in version control:
# - android/app/src/main/assets/capacitor.plugins.json # - android/app/src/main/assets/capacitor.plugins.json
# - android/app/src/main/res/values/strings.xml # - android/app/src/main/res/values/strings.xml

40
.husky/_/husky.sh

@ -0,0 +1,40 @@
#!/usr/bin/env sh
#
# Husky Helper Script
# This file is sourced by all Husky hooks
#
if [ -z "$husky_skip_init" ]; then
debug () {
if [ "$HUSKY_DEBUG" = "1" ]; then
echo "husky (debug) - $1"
fi
}
readonly hook_name="$(basename -- "$0")"
debug "starting $hook_name..."
if [ "$HUSKY" = "0" ]; then
debug "HUSKY env variable is set to 0, skipping hook"
exit 0
fi
if [ -f ~/.huskyrc ]; then
debug "sourcing ~/.huskyrc"
. ~/.huskyrc
fi
readonly husky_skip_init=1
export husky_skip_init
sh -e "$0" "$@"
exitCode="$?"
if [ $exitCode != 0 ]; then
echo "husky - $hook_name hook exited with code $exitCode (error)"
fi
if [ $exitCode = 127 ]; then
echo "husky - command not found in PATH=$PATH"
fi
exit $exitCode
fi

10
.husky/commit-msg

@ -0,0 +1,10 @@
#!/usr/bin/env bash
#
# Husky Commit Message Hook
# Validates commit message format using commitlint
#
. "$(dirname -- "$0")/_/husky.sh"
# Run commitlint but don't fail the commit (|| true)
# This provides helpful feedback without blocking commits
npx commitlint --edit "$1" || true

15
.husky/pre-commit

@ -0,0 +1,15 @@
#!/usr/bin/env bash
#
# Husky Pre-commit Hook
# Runs Build Architecture Guard to check staged files
#
. "$(dirname -- "$0")/_/husky.sh"
echo "🔍 Running Build Architecture Guard (pre-commit)..."
bash ./scripts/build-arch-guard.sh --staged || {
echo
echo "💡 To bypass this check for emergency commits, use:"
echo " git commit --no-verify"
echo
exit 1
}

27
.husky/pre-push

@ -0,0 +1,27 @@
#!/usr/bin/env bash
#
# Husky Pre-push Hook
# Runs Build Architecture Guard to check commits being pushed
#
. "$(dirname -- "$0")/_/husky.sh"
echo "🔍 Running Build Architecture Guard (pre-push)..."
# Get the remote branch we're pushing to
REMOTE_BRANCH="origin/$(git rev-parse --abbrev-ref HEAD)"
# Check if remote branch exists
if git show-ref --verify --quiet "refs/remotes/$REMOTE_BRANCH"; then
RANGE="$REMOTE_BRANCH...HEAD"
else
# If remote branch doesn't exist, check last commit
RANGE="HEAD~1..HEAD"
fi
bash ./scripts/build-arch-guard.sh --range "$RANGE" || {
echo
echo "💡 To bypass this check for emergency pushes, use:"
echo " git push --no-verify"
echo
exit 1
}

1
.node-version

@ -0,0 +1 @@
18.19.0

1
.nvmrc

@ -0,0 +1 @@
18.19.0

1145
BUILDING.md

File diff suppressed because it is too large

59
CHANGELOG.md

@ -5,54 +5,89 @@ 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/), 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). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.0.3] - 2025.07.12 ## [1.0.7] - 2025.08.18
### Changed
- Photo is pinned to profile mode
### Fixed ### Fixed
- Deep link URLs (and other prod settings)
- Error in BVC begin view
## [Unreleased] - Deep link for onboard-meeting-members
## [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 ### Changed
- Photo is pinned to profile mode - 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 ## [1.0.2] - 2025.06.20 - 276e0a741bc327de3380c4e508cccb7fee58c06d
### Added ### Added
- Version on feed title
- Version on feed title
## [1.0.1] - 2025.06.20 ## [1.0.1] - 2025.06.20
### Added ### Added
- Allow a user to block someone else's content from view
- Allow a user to block someone else's content from view
## [1.0.0] - 2025.06.20 - 5aa693de6337e5dbb278bfddc6bd39094bc14f73 ## [1.0.0] - 2025.06.20 - 5aa693de6337e5dbb278bfddc6bd39094bc14f73
### Added ### Added
- Web-oriented migration from IndexedDB to SQLite
- Web-oriented migration from IndexedDB to SQLite
## [0.5.8] ## [0.5.8]
### Added ### Added
- /deep-link/ path for URLs that are shared with people - /deep-link/ path for URLs that are shared with people
### Changed ### Changed
- External links now go to /deep-link/... - External links now go to /deep-link/...
- Feed visuals now have arrow imagery from giver to receiver - Feed visuals now have arrow imagery from giver to receiver
## [0.4.7] ## [0.4.7]
### Fixed ### Fixed
- Cameras everywhere - Cameras everywhere
### Changed ### Changed
- IndexedDB -> SQLite
- IndexedDB -> SQLite
## [0.4.5] - 2025.02.23 ## [0.4.5] - 2025.02.23
### Added ### Added
- Total amounts of gives on project page - Total amounts of gives on project page
### Changed in DB or environment ### Changed in DB or environment
- Requires Endorser.ch version 4.2.6+
- Requires Endorser.ch version 4.2.6+
## [0.4.4] - 2025.02.17 ## [0.4.4] - 2025.02.17

290
README-BUILD-GUARD.md

@ -0,0 +1,290 @@
# Build Architecture Guard - Husky Implementation
## Overview
The Build Architecture Guard protects your build system by enforcing
documentation requirements through **Git hooks**. When you modify
build-critical files, the system automatically blocks commits/pushes
until you update `BUILDING.md`.
## 🎯 **Why Husky-Only?**
**Advantages:**
- ✅ **Immediate feedback** - Hooks run before commit/push
- ✅ **Works everywhere** - No server-side CI/CD required
- ✅ **Simple setup** - One tool, one configuration
- ✅ **Fast execution** - No network delays or server queues
- ✅ **Offline support** - Works without internet connection
**Trade-offs:**
- ⚠️ **Can be bypassed** - `git commit --no-verify` or `git push --no-verify`
- ⚠️ **Developer discipline** - Relies on team following the rules
## 🏗️ **Architecture**
```bash
Developer Workflow:
1. Modify build files (scripts/, vite.config.*, etc.)
2. Try to commit → Husky pre-commit hook runs
3. Guard script checks if BUILDING.md was updated
4. ✅ Commit succeeds if docs updated
5. ❌ Commit blocked if docs missing
```
## 🚀 **Quick Start**
### 1. Install Dependencies
```bash
npm install
npm run prepare # Sets up Husky hooks
```
### 2. Test the System
```bash
# Modify a build file without updating BUILDING.md
echo "# test" >> scripts/test.sh
# Try to commit (should be blocked)
git add scripts/test.sh
git commit -m "test: add build script"
# ❌ Hook blocks commit with helpful message
```
### 3. Fix and Retry
```bash
# Update BUILDING.md with your changes
echo "## New Build Script" >> BUILDING.md
echo "Added test.sh for testing purposes" >> BUILDING.md
# Now commit should succeed
git add BUILDING.md
git commit -m "feat: add test build script with docs"
# ✅ Commit succeeds
```
## 🔧 **How It Works**
### Pre-commit Hook (`.husky/pre-commit`)
- **When**: Every `git commit`
- **What**: Runs `./scripts/build-arch-guard.sh --staged`
- **Result**: Blocks commit if build files changed without BUILDING.md update
### Pre-push Hook (`.husky/pre-push`)
- **When**: Every `git push`
- **What**: Runs `./scripts/build-arch-guard.sh --range`
- **Result**: Blocks push if commits contain undocumented build changes
### Guard Script (`scripts/build-arch-guard.sh`)
- **Detects**: Changes to build-sensitive file patterns
- **Validates**: BUILDING.md was updated alongside changes
- **Reports**: Clear error messages with guidance
## 📁 **Protected File Patterns**
The guard script monitors these paths for changes:
```text
Build Configuration:
├── vite.config.* # Vite configuration
├── capacitor.config.ts # Capacitor configuration
├── package.json # Package configuration
├── package-lock.json # Lock files
├── yarn.lock
└── pnpm-lock.yaml
Build Scripts:
├── scripts/** # All build and automation scripts
├── electron/** # Electron build files
├── android/** # Android build configuration
├── ios/** # iOS build configuration
├── sw_scripts/** # Service worker scripts
└── sw_combine.js # Service worker combination
Deployment:
├── Dockerfile # Docker configuration
└── docker/** # Docker services
```
## 🎭 **Usage Scenarios**
### Scenario 1: Adding a New Build Script
```bash
# ❌ This will be blocked
echo '#!/bin/bash' > scripts/new-build.sh
git add scripts/new-build.sh
git commit -m "feat: add new build script"
# Hook blocks: "Build-sensitive files changed but BUILDING.md not updated"
# ✅ This will succeed
echo '#!/bin/bash' > scripts/new-build.sh
echo '## New Build Script' >> BUILDING.md
echo 'Added new-build.sh for feature X' >> BUILDING.md
git add scripts/new-build.sh BUILDING.md
git commit -m "feat: add new build script with docs"
# ✅ Commit succeeds
```
### Scenario 2: Updating Vite Configuration
```bash
# ❌ This will be blocked
echo 'export default { newOption: true }' >> vite.config.ts
git add vite.config.ts
git commit -m "config: add new vite option"
# Hook blocks: "Build-sensitive files changed but BUILDING.md not updated"
# ✅ This will succeed
echo 'export default { newOption: true }' >> vite.config.ts
echo '### New Vite Option' >> BUILDING.md
echo 'Added newOption for improved performance' >> BUILDING.md
git add vite.config.ts BUILDING.md
git commit -m "config: add new vite option with docs"
# ✅ Commit succeeds
```
## 🚨 **Emergency Bypass**
**⚠️ Use sparingly and only for emergencies:**
```bash
# Skip pre-commit hook
git commit -m "emergency: critical fix" --no-verify
# Skip pre-push hook
git push --no-verify
# Remember to update BUILDING.md later!
```
## 🔍 **Troubleshooting**
### Hooks Not Running
```bash
# Reinstall hooks
npm run prepare
# Check hook files exist and are executable
ls -la .husky/
chmod +x .husky/*
# Verify Git hooks path
git config core.hooksPath
# Should show: .husky
```
### Guard Script Issues
```bash
# Test guard script manually
./scripts/build-arch-guard.sh --help
# Check script permissions
chmod +x scripts/build-arch-guard.sh
# Test with specific files
./scripts/build-arch-guard.sh --staged
```
### False Positives
```bash
# If guard blocks legitimate changes, check:
# 1. Are you modifying a protected file pattern?
# 2. Did you update BUILDING.md?
# 3. Is BUILDING.md staged for commit?
# View what the guard sees
git diff --name-only --cached
```
## 📋 **Best Practices**
### For Developers
1. **Update BUILDING.md first** - Document changes before implementing
2. **Test locally** - Run `./scripts/build-arch-guard.sh --staged` before committing
3. **Use descriptive commits** - Include context about build changes
4. **Don't bypass lightly** - Only use `--no-verify` for true emergencies
### For Teams
1. **Document the system** - Ensure everyone understands the guard
2. **Review BUILDING.md updates** - Verify documentation quality
3. **Monitor bypass usage** - Track when hooks are skipped
4. **Regular audits** - Check that BUILDING.md stays current
### For Maintainers
1. **Update protected patterns** - Modify `scripts/build-arch-guard.sh` as needed
2. **Monitor effectiveness** - Track how often the guard catches issues
3. **Team training** - Help developers understand the system
4. **Continuous improvement** - Refine patterns and error messages
## 🔄 **Customization**
### Adding New Protected Paths
Edit `scripts/build-arch-guard.sh`:
```bash
SENSITIVE=(
# ... existing patterns ...
"new-pattern/**" # Add your new pattern
"*.config.js" # Add file extensions
)
```
### Modifying Error Messages
Edit the guard script to customize:
- Error message content
- File pattern matching
- Documentation requirements
- Bypass instructions
### Adding New Validation Rules
Extend the guard script to check for:
- Specific file content patterns
- Required documentation sections
- Commit message formats
- Branch naming conventions
## 📚 **Integration with PR Template**
The `pull_request_template.md` works with this system by:
- **Guiding developers** through required documentation
- **Ensuring consistency** across all build changes
- **Providing checklist** for comprehensive updates
- **Supporting L1/L2/L3** change classification
## 🎯 **Success Metrics**
Track the effectiveness of your Build Architecture Guard:
- **Hook execution rate** - How often hooks run successfully
- **Bypass frequency** - How often `--no-verify` is used
- **Documentation quality** - BUILDING.md stays current
- **Build failures** - Fewer issues from undocumented changes
- **Team adoption** - Developers follow the process
---
**Status**: Active protection system
**Architecture**: Client-side Git hooks only
**Dependencies**: Husky, Git, Bash
**Maintainer**: Development team
**Related**: `pull_request_template.md`, `scripts/build-arch-guard.sh`

82
README-PR-TEMPLATE.md

@ -0,0 +1,82 @@
# Pull Request Template
## Location
The Build Architecture Guard PR template is located at:
- **`pull_request_template.md`** (root directory)
## Usage
When creating a pull request in Gitea, this template will automatically populate the PR description with the required checklist.
## Template Features
### Change Level Classification
- **L1**: Minor changes, documentation updates
- **L2**: Moderate changes, new features, environment changes
- **L3**: Major changes, architecture changes, new platforms
### Required Fields for All Levels
- Change level selection
- Scope and impact description
- Commands executed and their output
- Documentation updates (BUILDING.md)
- Rollback verification steps
### Additional Requirements for L3
- **ADR link**: Must provide URL to Architectural Decision Record
- **Artifacts with SHA256**: Must list artifacts with cryptographic hashes
## Integration
This template works with:
- **Gitea Actions**: `.gitea/workflows/build-guard.yml`
- **Client-side hooks**: `.husky/` pre-commit and pre-push hooks
- **Guard script**: `scripts/build-arch-guard.sh`
## Example Usage
```markdown
### Change Level
- [x] Level: **L2**
**Why:** Adding new build script for Docker deployment
### Scope & Impact
- [x] Files & platforms touched: scripts/build-docker.sh,
BUILDING.md
- [x] Risk triggers: Docker build process changes
- [x] Mitigations/validation done: Tested on local Docker environment
### Commands Run
- [x] Web: `npm run build:web:docker`
- [x] Docker: `docker build -t test-image .`
### Artifacts
- [x] Names + **sha256** of artifacts/installers:
Artifacts:
```text
test-image.tar a1b2c3d4e5f6...
```
### Docs
- [x] **BUILDING.md** updated (sections): Docker deployment
- [x] Troubleshooting updated: Added Docker troubleshooting section
### Rollback
- [x] Verified steps to restore previous behavior:
1. `git revert HEAD`
2. `docker rmi test-image`
3. Restore previous BUILDING.md
```
---
**Note**: This template is enforced by the Build Architecture Guard
system. Complete all required fields to ensure your PR can be merged.

237
README.md

@ -1,199 +1,118 @@
# TimeSafari.app - Crowd-Funder for Time - PWA # Time Safari Application
[Time Safari](https://timesafari.org/) allows people to ease into collaboration: start with expressions of gratitude **Author**: Matthew Raymer
and expand to crowd-fund with time & money, then record and see the impact of contributions. **Version**: 1.0.8-beta
**Description**: Time Safari Application
## Database Migration Status ## 🛡️ Build Architecture Guard
**Current Status**: The application is undergoing a migration from Dexie (IndexedDB) to SQLite using absurd-sql. This migration is in **Phase 2** with a well-defined migration fence in place. This project uses **Husky Git hooks** to protect the build system
architecture. When you modify build-critical files, the system
automatically blocks commits until you update `BUILDING.md`.
### Migration Progress ### Quick Setup
- ✅ **SQLite Database Service**: Fully implemented with absurd-sql
- ✅ **Platform Service Layer**: Unified database interface across platforms
- ✅ **Settings Migration**: Core user settings transferred
- ✅ **Account Migration**: Identity and key management
- 🔄 **Contact Migration**: User contact data (via import interface)
- 📋 **Code Cleanup**: Remove unused Dexie imports
### Migration Fence
The migration is controlled by a **migration fence** that separates legacy Dexie code from the new SQLite implementation. See [Migration Fence Definition](doc/migration-fence-definition.md) for complete details.
**Key Points**:
- Legacy Dexie database is disabled by default
- All database operations go through `PlatformServiceMixin`
- Migration tools provide controlled access to both databases
- Clear separation between legacy and new code
### Migration Documentation
- [Migration Guide](doc/migration-to-wa-sqlite.md) - Complete migration process
- [Migration Fence Definition](doc/migration-fence-definition.md) - Fence boundaries and rules
- [Database Migration Guide](doc/database-migration-guide.md) - User-facing migration tools
## Roadmap
See [project.task.yaml](project.task.yaml) for current priorities.
(Numbers at the beginning of lines are estimated hours. See [taskyaml.org](https://taskyaml.org/) for details.)
## 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 ```bash
npm install npm run guard:setup # Install and activate the guard
npm run dev
``` ```
See [BUILDING.md](BUILDING.md) for comprehensive build instructions for all platforms (Web, Electron, iOS, Android, Docker). ### How It Works
## Development Database Clearing - **Pre-commit**: Blocks commits if build files changed without
BUILDING.md updates
- **Pre-push**: Blocks pushes if commits contain undocumented build
changes
- **Protected paths**: `scripts/`, `vite.config.*`, `electron/`,
`android/`, `ios/`, etc.
TimeSafari provides a simple script-based approach to clear the database for development purposes. ### Usage
### Quick Usage
```bash ```bash
# Run the database clearing script # Test the guard manually
./scripts/clear-database.sh npm run guard:test
# Then restart your development server # Emergency bypass (use sparingly)
npm run build:electron:dev # For Electron git commit --no-verify
npm run build:web:dev # For Web git push --no-verify
``` ```
### What It Does **📚 Full documentation**: See `README-BUILD-GUARD.md`
#### **Electron (Desktop App)** ## 🚀 Quick Start
- 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** ### Prerequisites
- Provides instructions for using custom browser data directories
- Shows manual clearing via browser DevTools
- Ensures reliable database clearing without browser complications
### Safety Features - Node.js 18+
- ✅ **Interactive Script**: Guides you through the process - npm, yarn, or pnpm
- ✅ **Platform Detection**: Automatically detects your OS - Git
- ✅ **Clear Instructions**: Step-by-step guidance for each platform
- ✅ **Safe Paths**: Only clears TimeSafari-specific data
### Manual Commands (if needed) ### Installation
#### **Electron Database Location**
```bash ```bash
# Linux npm install
rm -rf ~/.config/TimeSafari/* npm run guard:setup # Sets up Build Architecture Guard
# macOS
rm -rf ~/Library/Application\ Support/TimeSafari/*
# Windows
rmdir /s /q %APPDATA%\TimeSafari
``` ```
#### **Web Browser (Custom Data Directory)** ### Development
```bash ```bash
# Create isolated browser profile npm run build:web:dev # Build web version
mkdir ~/timesafari-dev-data npm run build:ios:test # Build iOS test version
npm run build:android:test # Build Android test version
npm run build:electron:dev # Build Electron dev version
``` ```
## Domain Configuration ### Testing
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 ```bash
```typescript npm run test:web # Run web tests
// For sharing functionality (always production) npm run test:mobile # Run mobile tests
import { PROD_SHARE_DOMAIN } from "@/constants/app"; npm run test:all # Run all tests
const shareLink = `${PROD_SHARE_DOMAIN}/deep-link/claim/123`;
// For internal operations (environment-specific)
import { APP_SERVER } from "@/constants/app";
const apiUrl = `${APP_SERVER}/api/claim/123`;
``` ```
### Documentation ## 📁 Project Structure
- [Domain Configuration System](docs/domain-configuration.md) - Complete guide
- [Constants and Configuration](src/constants/app.ts) - Core constants ```text
timesafari/
## Tests ├── 📁 src/ # Source code
├── 📁 scripts/ # Build and automation scripts
See [TESTING.md](test-playwright/TESTING.md) for detailed test instructions. ├── 📁 electron/ # Electron configuration
├── 📁 android/ # Android configuration
## Icons ├── 📁 ios/ # iOS configuration
├── 📁 .husky/ # Git hooks (Build Architecture Guard)
Application icons are in the `assets` directory, processed by the `capacitor-assets` command. ├── 📄 BUILDING.md # Build system documentation
├── 📄 pull_request_template.md # PR template
To add a Font Awesome icon, add to main.ts and reference with `font-awesome` element and `icon` attribute with the hyphenated name. └── 📄 README-BUILD-GUARD.md # Guard system documentation
```
## 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 ## 🔧 Build System
* `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: This project supports multiple platforms:
- 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 - **Web**: Vite-based build with service worker support
- **Mobile**: Capacitor-based iOS and Android builds
- **Desktop**: Electron-based cross-platform desktop app
- **Docker**: Containerized deployment options
The application uses a platform-agnostic database layer with Vue mixins for service access: ## 📚 Documentation
* `src/services/PlatformService.ts` - Database interface definition - **`BUILDING.md`** - Complete build system guide
* `src/services/PlatformServiceFactory.ts` - Platform-specific service factory - **`README-BUILD-GUARD.md`** - Build Architecture Guard documentation
* `src/services/AbsurdSqlDatabaseService.ts` - SQLite implementation - **`pull_request_template.md`** - PR template for build changes
* `src/utils/PlatformServiceMixin.ts` - Vue mixin for database access with caching
* `src/db/` - Legacy Dexie database (migration in progress)
**Development Guidelines**: ## 🤝 Contributing
- Always use `PlatformServiceMixin` for database operations in components 1. **Follow the Build Architecture Guard** - Update BUILDING.md when modifying build files
- Test with PlatformServiceMixin for new features 2. **Use the PR template** - Complete the checklist for build-related changes
- Use migration tools for data transfer between systems 3. **Test your changes** - Ensure builds work on affected platforms
- Leverage mixin's ultra-concise methods: `$db()`, `$exec()`, `$one()`, `$contacts()`, `$settings()` 4. **Document updates** - Keep BUILDING.md current and accurate
**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. ## 📄 License
### Kudos [Add your license information here]
Gifts make the world go 'round! ---
* [WebStorm by JetBrains](https://www.jetbrains.com/webstorm/) for the free open-source license **Note**: The Build Architecture Guard is active and will block
* [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) commits/pushes that modify build files without proper documentation
* [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 updates. See `README-BUILD-GUARD.md` for complete details.
* [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/)

8
TASK_storage.md

@ -1,7 +1,6 @@
# What to do about storage for native apps? # What to do about storage for native apps?
## Problem ## 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. 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.
@ -14,7 +13,6 @@ We can't trust iOS IndexedDB to persist. I want to start delivering an app to pe
Also, with sensitive data, the accounts info should be encrypted. Also, with sensitive data, the accounts info should be encrypted.
# Options # Options
* There is a community [SQLite plugin for Capacitor](https://github.com/capacitor-community/sqlite) with encryption by [SQLCipher](https://github.com/sqlcipher/sqlcipher). * There is a community [SQLite plugin for Capacitor](https://github.com/capacitor-community/sqlite) with encryption by [SQLCipher](https://github.com/sqlcipher/sqlcipher).
@ -29,16 +27,12 @@ Also, with sensitive data, the accounts info should be encrypted.
* Not an option yet: Dexie may support SQLite in [a future version](https://dexie.org/roadmap/dexie5.0). * Not an option yet: Dexie may support SQLite in [a future version](https://dexie.org/roadmap/dexie5.0).
# Current Plan # 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. * 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. * After that is delivered, write a migration for current web users from IndexedDB to SQLite.
# Current method calls # Current method calls
... which is not 100% complete because the AI that generated thus claimed no usage of 'temp' DB. ... which is not 100% complete because the AI that generated thus claimed no usage of 'temp' DB.
@ -80,5 +74,3 @@ Logs operations:
db.logs.get(todayKey) - Gets logs for a specific day db.logs.get(todayKey) - Gets logs for a specific day
db.logs.update(todayKey, { message: fullMessage }) - Updates logs db.logs.update(todayKey, { message: fullMessage }) - Updates logs
db.logs.clear() - Clears all logs db.logs.clear() - Clears all logs

12
android/app/build.gradle

@ -31,8 +31,8 @@ android {
applicationId "app.timesafari.app" applicationId "app.timesafari.app"
minSdkVersion rootProject.ext.minSdkVersion minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 35 versionCode 40
versionName "1.0.2" versionName "1.0.7"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions { aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
@ -64,6 +64,14 @@ android {
} }
} }
} }
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) // Enable bundle builds (without which it doesn't work right for bundleDebug vs bundleRelease)
bundle { bundle {

7
android/app/src/main/assets/capacitor.config.json

@ -29,7 +29,7 @@
"splashFullScreen": true, "splashFullScreen": true,
"splashImmersive": true "splashImmersive": true
}, },
"CapacitorSQLite": { "CapSQLite": {
"iosDatabaseLocation": "Library/CapacitorDatabase", "iosDatabaseLocation": "Library/CapacitorDatabase",
"iosIsEncryption": false, "iosIsEncryption": false,
"iosBiometric": { "iosBiometric": {
@ -57,13 +57,14 @@
] ]
}, },
"android": { "android": {
"allowMixedContent": false, "allowMixedContent": true,
"captureInput": true, "captureInput": true,
"webContentsDebuggingEnabled": false, "webContentsDebuggingEnabled": false,
"allowNavigation": [ "allowNavigation": [
"*.timesafari.app", "*.timesafari.app",
"*.jsdelivr.net", "*.jsdelivr.net",
"api.endorser.ch" "api.endorser.ch",
"10.0.2.2:3000"
] ]
}, },
"electron": { "electron": {

7
android/app/src/main/res/values/colors.xml

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>

2
android/build.gradle

@ -7,7 +7,7 @@ buildscript {
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:8.11.1' classpath 'com.android.tools.build:gradle:8.12.1'
classpath 'com.google.gms:google-services:4.4.0' classpath 'com.google.gms:google-services:4.4.0'
// NOTE: Do not place your application dependencies here; they belong // NOTE: Do not place your application dependencies here; they belong

2
android/gradle.properties

@ -20,4 +20,4 @@ org.gradle.jvmargs=-Xmx1536m
# Android operating system, and which are packaged with your app's APK # Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn # https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true android.useAndroidX=true
android.suppressUnsupportedCompileSdk=34 android.suppressUnsupportedCompileSdk=36

4
android/variables.gradle

@ -1,7 +1,7 @@
ext { ext {
minSdkVersion = 22 minSdkVersion = 22
compileSdkVersion = 34 compileSdkVersion = 36
targetSdkVersion = 34 targetSdkVersion = 36
androidxActivityVersion = '1.8.0' androidxActivityVersion = '1.8.0'
androidxAppCompatVersion = '1.6.1' androidxAppCompatVersion = '1.6.1'
androidxCoordinatorLayoutVersion = '1.2.0' androidxCoordinatorLayoutVersion = '1.2.0'

2
assets/README.md

@ -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.

34
capacitor-assets.config.json

@ -1,36 +1,32 @@
{ {
"icon": { "icon": {
"ios": {
"source": "resources/ios/icon/icon.png",
"target": "ios/App/App/Assets.xcassets/AppIcon.appiconset"
},
"android": { "android": {
"source": "resources/android/icon/icon.png", "adaptive": {
"background": "#121212",
"foreground": "resources/icon.png",
"monochrome": "resources/icon.png"
},
"target": "android/app/src/main/res" "target": "android/app/src/main/res"
}, },
"ios": {
"padding": 0,
"target": "ios/App/App/Assets.xcassets/AppIcon.appiconset"
},
"source": "resources/icon.png",
"web": { "web": {
"source": "resources/web/icon/icon.png",
"target": "public/img/icons" "target": "public/img/icons"
} }
}, },
"splash": { "splash": {
"ios": {
"source": "resources/ios/splash/splash.png",
"target": "ios/App/App/Assets.xcassets/Splash.imageset"
},
"android": { "android": {
"source": "resources/android/splash/splash.png", "scale": "cover",
"target": "android/app/src/main/res" "target": "android/app/src/main/res"
}
}, },
"splashDark": { "darkSource": "resources/splash_dark.png",
"ios": { "ios": {
"source": "resources/ios/splash/splash_dark.png", "target": "ios/App/App/Assets.xcassets",
"target": "ios/App/App/Assets.xcassets/SplashDark.imageset" "useStoryBoard": true
}, },
"android": { "source": "resources/splash.png"
"source": "resources/android/splash/splash_dark.png",
"target": "android/app/src/main/res"
}
} }
} }

5
capacitor.config.json

@ -57,13 +57,14 @@
] ]
}, },
"android": { "android": {
"allowMixedContent": false, "allowMixedContent": true,
"captureInput": true, "captureInput": true,
"webContentsDebuggingEnabled": false, "webContentsDebuggingEnabled": false,
"allowNavigation": [ "allowNavigation": [
"*.timesafari.app", "*.timesafari.app",
"*.jsdelivr.net", "*.jsdelivr.net",
"api.endorser.ch" "api.endorser.ch",
"10.0.2.2:3000"
] ]
}, },
"electron": { "electron": {

116
capacitor.config.ts

@ -0,0 +1,116 @@
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
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
},
CapSQLite: {
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'
}
}
}
};
export default config;

32
config/assets/capacitor-assets.config.json

@ -0,0 +1,32 @@
{
"icon": {
"android": {
"adaptive": {
"background": "#121212",
"foreground": "resources/icon.png",
"monochrome": "resources/icon.png"
},
"target": "android/app/src/main/res"
},
"ios": {
"padding": 0,
"target": "ios/App/App/Assets.xcassets/AppIcon.appiconset"
},
"source": "resources/icon.png",
"web": {
"target": "public/img/icons"
}
},
"splash": {
"android": {
"scale": "cover",
"target": "android/app/src/main/res"
},
"darkSource": "resources/splash_dark.png",
"ios": {
"target": "ios/App/App/Assets.xcassets",
"useStoryBoard": true
},
"source": "resources/splash.png"
}
}

119
config/assets/schema.json

@ -0,0 +1,119 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Capacitor Assets Configuration Schema",
"description": "Schema for validating capacitor-assets configuration files",
"type": "object",
"properties": {
"icon": {
"type": "object",
"properties": {
"source": {
"type": "string",
"pattern": "^resources/.*\\.(png|svg)$",
"description": "Source icon file path relative to project root"
},
"android": {
"type": "object",
"properties": {
"adaptive": {
"type": "object",
"properties": {
"foreground": {
"type": "string",
"pattern": "^resources/.*\\.(png|svg)$",
"description": "Foreground icon for Android adaptive icons"
},
"background": {
"type": ["string", "object"],
"description": "Background color or image for adaptive icons"
},
"monochrome": {
"type": "string",
"pattern": "^resources/.*\\.(png|svg)$",
"description": "Monochrome icon for Android 13+"
}
},
"required": ["foreground", "background"]
},
"target": {
"type": "string",
"description": "Android target directory for generated icons"
}
}
},
"ios": {
"type": "object",
"properties": {
"padding": {
"type": "number",
"minimum": 0,
"maximum": 1,
"description": "Padding ratio for iOS icons"
},
"target": {
"type": "string",
"description": "iOS target directory for generated icons"
}
}
},
"web": {
"type": "object",
"properties": {
"target": {
"type": "string",
"description": "Web target directory for generated icons"
}
}
}
},
"required": ["source"],
"additionalProperties": false
},
"splash": {
"type": "object",
"properties": {
"source": {
"type": "string",
"pattern": "^resources/.*\\.(png|svg)$",
"description": "Source splash screen file"
},
"darkSource": {
"type": "string",
"pattern": "^resources/.*\\.(png|svg)$",
"description": "Dark mode splash screen file"
},
"android": {
"type": "object",
"properties": {
"scale": {
"type": "string",
"enum": ["cover", "contain", "fill"],
"description": "Android splash screen scaling mode"
},
"target": {
"type": "string",
"description": "Android target directory for splash screens"
}
}
},
"ios": {
"type": "object",
"properties": {
"useStoryBoard": {
"type": "boolean",
"description": "Use LaunchScreen storyboard instead of splash assets"
},
"target": {
"type": "string",
"description": "iOS target directory for splash screens"
}
}
}
},
"required": ["source"],
"additionalProperties": false
}
},
"required": ["icon", "splash"],
"additionalProperties": false
}

3
doc/DEEP_LINKS.md

@ -47,6 +47,7 @@ type ClaimParams = z.infer<typeof claimSchema>;
### Type Safety Layers ### Type Safety Layers
1. **Schema Definition** 1. **Schema Definition**
```typescript ```typescript
// src/interfaces/deepLinks.ts // src/interfaces/deepLinks.ts
export const deepLinkSchemas = { export const deepLinkSchemas = {
@ -59,6 +60,7 @@ type ClaimParams = z.infer<typeof claimSchema>;
``` ```
2. **Type Generation** 2. **Type Generation**
```typescript ```typescript
// Types are automatically generated from schemas // Types are automatically generated from schemas
export type DeepLinkParams = { export type DeepLinkParams = {
@ -67,6 +69,7 @@ type ClaimParams = z.infer<typeof claimSchema>;
``` ```
3. **Runtime Validation** 3. **Runtime Validation**
```typescript ```typescript
// In DeepLinkHandler // In DeepLinkHandler
const result = deepLinkSchemas.claim.safeParse(params); const result = deepLinkSchemas.claim.safeParse(params);

3
doc/README.md

@ -54,7 +54,7 @@ sudo tlmgr install sourceserifpro
The following guide was adapted to this project except that we install with Brew and have a few more packages. 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 Guide: <https://daniel.feldroy.com/posts/setting-up-latex-on-mac-os-x>
### Usage ### Usage
@ -71,6 +71,7 @@ open usage-guide.pdf
``` ```
Or use this one-liner Or use this one-liner
```bash ```bash
pandoc usage-guide.md -o usage-guide.pdf && open usage-guide.pdf pandoc usage-guide.md -o usage-guide.pdf && open usage-guide.pdf
``` ```

215
doc/asset-migration-plan.md

@ -0,0 +1,215 @@
# TimeSafari Asset Configuration Migration Plan
**Author**: Matthew Raymer
**Date**: 2025-08-14
**Status**: 🎯 **IMPLEMENTATION** - Ready for Execution
## Overview
This document outlines the migration from the current mixed asset management
system to a standardized, single-source asset configuration approach using
`capacitor-assets` as the standard generator.
## Current State Analysis
### Asset Sources (Duplicated)
- **`assets/` directory**: Contains `icon.png`, `splash.png`, `splash_dark.png`
- **`resources/` directory**: Contains identical files in platform-specific subdirectories
- **Result**: Duplicate storage, confusion about source of truth
### Asset Generation (Manual)
- **Custom scripts**: `generate-icons.sh`, `generate-ios-assets.sh`, `generate-android-icons.sh`
- **Bypass capacitor-assets**: Manual ImageMagick-based generation
- **Inconsistent outputs**: Different generation methods for each platform
### Configuration (Scattered)
- **`capacitor-assets.config.json`**: Basic configuration at root
- **Platform-specific configs**: Mixed in various build scripts
- **No validation**: No schema or consistency checks
## Target State
### Single Source of Truth
- **`resources/` directory**: Capacitor default location for source assets
- **Eliminate duplication**: Remove `assets/` directory after migration
- **Standardized paths**: All tools read from `resources/`
### Standardized Generation
- **`capacitor-assets`**: Single tool for all platform asset generation
- **Build-time generation**: Assets generated during build, not committed
- **Deterministic outputs**: Same inputs → same outputs every time
### Centralized Configuration
- **`config/assets/`**: All asset-related configuration files
- **Schema validation**: JSON schema for configuration validation
- **CI safeguards**: Automated validation and compliance checks
## Migration Steps
### Phase 1: Foundation Setup ✅
- [x] Create `config/assets/` directory structure
- [x] Create asset configuration schema (`schema.json`)
- [x] Create enhanced capacitor-assets configuration
- [x] Convert `capacitor.config.json` to `capacitor.config.ts`
- [x] Pin Node.js version (`.nvmrc`, `.node-version`)
- [x] Create dev-time asset configuration generator
- [x] Create asset configuration validator
- [x] Add npm scripts for asset management
- [x] Update `.gitignore` with proper asset exclusions
- [x] Create CI workflow for asset validation
### Phase 2: Validation & Testing
- [ ] Run `npm run assets:config` to generate new configuration
- [ ] Run `npm run assets:validate` to verify configuration
- [ ] Test `npm run build:native` workflow
- [ ] Verify CI workflow passes all checks
- [ ] Confirm no platform assets are committed to VCS
### Phase 3: Cleanup & Removal
- [ ] Remove `assets/` directory (after validation)
- [ ] Remove manual asset generation scripts
- [ ] Remove asset checking scripts
- [ ] Update documentation references
- [ ] Final validation of clean state
## Implementation Details
### File Structure
```
resources/ # Image sources ONLY
icon.png
splash.png
splash_dark.png
config/assets/ # Versioned config & schema
capacitor-assets.config.json
schema.json
scripts/
assets-config.js # Dev-time config generator
assets-validator.js # Schema validator
```
### Configuration Schema
The schema enforces:
- Source files must be in `resources/` directory
- Required fields for icon and splash sections
- Android adaptive icon support (foreground/background/monochrome)
- iOS LaunchScreen preferences
- Target directory validation
### CI Safeguards
- **Schema validation**: Configuration must comply with schema
- **Source file validation**: All referenced files must exist
- **Platform asset denial**: Reject commits with generated assets
- **Clean tree enforcement**: Build must not modify committed configs
## Testing Strategy
### Local Validation
```bash
# Generate configuration
npm run assets:config
# Validate configuration
npm run assets:validate
# Test build workflow
npm run build:native
# Clean generated assets
npm run assets:clean
```
### CI Validation
- **Asset validation workflow**: Runs on asset-related changes
- **Schema compliance**: Ensures configuration follows schema
- **Source file existence**: Verifies all referenced files exist
- **Platform asset detection**: Prevents committed generated assets
- **Build tree verification**: Ensures clean tree after build
## Risk Mitigation
### Data Loss Prevention
- **Backup branch**: Create backup before removing `assets/`
- **Validation checks**: Multiple validation steps before removal
- **Gradual migration**: Phase-by-phase approach with rollback capability
### Build Continuity
- **Per-platform scripts unchanged**: All existing build orchestration preserved
- **Standard toolchain**: Uses capacitor-assets, not custom scripts
- **Fallback support**: Manual scripts remain until migration complete
### Configuration Consistency
- **Schema enforcement**: JSON schema prevents invalid configurations
- **CI validation**: Automated checks catch configuration issues
- **Documentation updates**: Clear guidance for future changes
## Success Criteria
### Technical Requirements
- [ ] Single source of truth in `resources/` directory
- [ ] All platform assets generated via `capacitor-assets`
- [ ] No manual asset generation scripts
- [ ] Configuration validation passes all checks
- [ ] CI workflow enforces asset policies
### Quality Metrics
- [ ] Zero duplicate asset sources
- [ ] 100% configuration schema compliance
- [ ] No platform assets committed to VCS
- [ ] Clean build tree after asset generation
- [ ] Deterministic asset outputs
### User Experience
- [ ] Clear asset management documentation
- [ ] Simple development commands
- [ ] Consistent asset generation across platforms
- [ ] Reduced confusion about asset sources
## Next Steps
1. **Execute Phase 2**: Run validation and testing steps
2. **Verify CI workflow**: Ensure all checks pass
3. **Execute Phase 3**: Remove duplicate assets and scripts
4. **Update documentation**: Finalize README and BUILDING.md
5. **Team training**: Ensure all developers understand new workflow
## Rollback Plan
If issues arise during migration:
1. **Restore backup branch**: `git checkout backup-before-asset-migration`
2. **Revert configuration changes**: Remove new config files
3. **Restore manual scripts**: Re-enable previous asset generation
4. **Investigate issues**: Identify and resolve root causes
5. **Plan revised migration**: Adjust approach based on lessons learned
---
**Status**: Ready for Phase 2 execution
**Priority**: High
**Estimated Effort**: 2-3 hours
**Dependencies**: CI workflow validation
**Stakeholders**: Development team

8
doc/build-modernization-context.md

@ -3,11 +3,13 @@
**Author:** Matthew Raymer **Author:** Matthew Raymer
## Motivation ## Motivation
- Eliminate manual hacks and post-build scripts for Electron builds - Eliminate manual hacks and post-build scripts for Electron builds
- Ensure maintainability, reproducibility, and security of build outputs - Ensure maintainability, reproducibility, and security of build outputs
- Unify build, test, and deployment scripts for developer experience and CI/CD - Unify build, test, and deployment scripts for developer experience and CI/CD
## Key Technical Decisions ## Key Technical Decisions
- **Vite is the single source of truth for build output** - **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` - 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** - **CSS injection for Electron is handled by a Vite plugin**
@ -21,6 +23,7 @@
- Renderer assets: `dist-electron/www/` (HTML, CSS, JS) - Renderer assets: `dist-electron/www/` (HTML, CSS, JS)
## Security & Maintenance Checklist ## Security & Maintenance Checklist
- [x] All scripts and configs are committed and documented - [x] All scripts and configs are committed and documented
- [x] No manual file hacks remain - [x] No manual file hacks remain
- [x] All build output is deterministic and reproducible - [x] All build output is deterministic and reproducible
@ -28,21 +31,26 @@
- [x] Documentation (`BUILDING.md`) is up to date - [x] Documentation (`BUILDING.md`) is up to date
## How to Build Electron ## How to Build Electron
1. Run: 1. Run:
```bash ```bash
./scripts/build-electron.sh ./scripts/build-electron.sh
``` ```
2. Output will be in `dist-electron/`: 2. Output will be in `dist-electron/`:
- `main.js`, `preload.js` in root - `main.js`, `preload.js` in root
- `www/` contains all renderer assets - `www/` contains all renderer assets
3. No manual post-processing is required 3. No manual post-processing is required
## Customization ## Customization
- **Vite config:** All build output and asset handling is controlled in `vite.config.electron.mts` - **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 - **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` - **Build scripts:** All orchestration is in `scripts/` and documented in `BUILDING.md`
## For Future Developers ## For Future Developers
- Always use Vite plugins/config for build output changes - Always use Vite plugins/config for build output changes
- Never manually edit built files or inject assets post-build - Never manually edit built files or inject assets post-build
- Keep documentation and scripts in sync with the build process - Keep documentation and scripts in sync with the build process

17
doc/circular-dependency-analysis.md

@ -13,23 +13,27 @@ The codebase currently has **no active circular dependencies** that are causing
### 🔍 **Resolved Dependency Patterns** ### 🔍 **Resolved Dependency Patterns**
#### 1. **Logger → PlatformServiceFactory → Logger** (RESOLVED) #### 1. **Logger → PlatformServiceFactory → Logger** (RESOLVED)
- **Status**: ✅ **RESOLVED** - **Status**: ✅ **RESOLVED**
- **Previous Issue**: Logger imported `logToDb` from databaseUtil, which imported logger - **Previous Issue**: Logger imported `logToDb` from databaseUtil, which imported logger
- **Solution**: Logger now uses direct database access via PlatformServiceFactory - **Solution**: Logger now uses direct database access via PlatformServiceFactory
- **Implementation**: Self-contained `logToDatabase()` function in logger.ts - **Implementation**: Self-contained `logToDatabase()` function in logger.ts
#### 2. **PlatformServiceMixin → databaseUtil → logger → PlatformServiceMixin** (RESOLVED) #### 2. **PlatformServiceMixin → databaseUtil → logger → PlatformServiceMixin** (RESOLVED)
- **Status**: ✅ **RESOLVED** - **Status**: ✅ **RESOLVED**
- **Previous Issue**: PlatformServiceMixin imported `memoryLogs` from databaseUtil - **Previous Issue**: PlatformServiceMixin imported `memoryLogs` from databaseUtil
- **Solution**: Created self-contained `_memoryLogs` array in PlatformServiceMixin - **Solution**: Created self-contained `_memoryLogs` array in PlatformServiceMixin
- **Implementation**: Self-contained memory logs implementation - **Implementation**: Self-contained memory logs implementation
#### 3. **databaseUtil → logger → PlatformServiceFactory → databaseUtil** (RESOLVED) #### 3. **databaseUtil → logger → PlatformServiceFactory → databaseUtil** (RESOLVED)
- **Status**: ✅ **RESOLVED** - **Status**: ✅ **RESOLVED**
- **Previous Issue**: databaseUtil imported logger, which could create loops - **Previous Issue**: databaseUtil imported logger, which could create loops
- **Solution**: Logger is now self-contained and doesn't import from databaseUtil - **Solution**: Logger is now self-contained and doesn't import from databaseUtil
#### 4. **Utility Files → databaseUtil → PlatformServiceMixin** (RESOLVED) #### 4. **Utility Files → databaseUtil → PlatformServiceMixin** (RESOLVED)
- **Status**: ✅ **RESOLVED** - **Status**: ✅ **RESOLVED**
- **Previous Issue**: `src/libs/util.ts` and `src/services/deepLinks.ts` imported from databaseUtil - **Previous Issue**: `src/libs/util.ts` and `src/services/deepLinks.ts` imported from databaseUtil
- **Solution**: Replaced with self-contained implementations and PlatformServiceFactory usage - **Solution**: Replaced with self-contained implementations and PlatformServiceFactory usage
@ -43,18 +47,21 @@ The codebase currently has **no active circular dependencies** that are causing
### ✅ **All Critical Dependencies Resolved** ### ✅ **All Critical Dependencies Resolved**
#### PlatformServiceMixin Independence #### PlatformServiceMixin Independence
- **Status**: ✅ **COMPLETE** - **Status**: ✅ **COMPLETE**
- **Achievement**: PlatformServiceMixin has no external dependencies on databaseUtil - **Achievement**: PlatformServiceMixin has no external dependencies on databaseUtil
- **Implementation**: Self-contained memory logs and utility functions - **Implementation**: Self-contained memory logs and utility functions
- **Impact**: Enables complete migration of databaseUtil functions to PlatformServiceMixin - **Impact**: Enables complete migration of databaseUtil functions to PlatformServiceMixin
#### Logger Independence #### Logger Independence
- **Status**: ✅ **COMPLETE** - **Status**: ✅ **COMPLETE**
- **Achievement**: Logger is completely self-contained - **Achievement**: Logger is completely self-contained
- **Implementation**: Direct database access via PlatformServiceFactory - **Implementation**: Direct database access via PlatformServiceFactory
- **Impact**: Eliminates all circular dependency risks - **Impact**: Eliminates all circular dependency risks
#### Utility Files Independence #### Utility Files Independence
- **Status**: ✅ **COMPLETE** - **Status**: ✅ **COMPLETE**
- **Achievement**: All utility files no longer depend on databaseUtil - **Achievement**: All utility files no longer depend on databaseUtil
- **Implementation**: Self-contained functions and direct platform service access - **Implementation**: Self-contained functions and direct platform service access
@ -63,6 +70,7 @@ The codebase currently has **no active circular dependencies** that are causing
### 🎯 **Migration Readiness Status** ### 🎯 **Migration Readiness Status**
#### Files Ready for Migration (52 files) #### Files Ready for Migration (52 files)
1. **Components** (15 files): 1. **Components** (15 files):
- `PhotoDialog.vue` - `PhotoDialog.vue`
- `FeedFilters.vue` - `FeedFilters.vue`
@ -98,6 +106,7 @@ The codebase currently has **no active circular dependencies** that are causing
### 🟢 **Healthy Dependencies** ### 🟢 **Healthy Dependencies**
#### Logger Usage (80+ files) #### Logger Usage (80+ files)
- **Status**: ✅ **HEALTHY** - **Status**: ✅ **HEALTHY**
- **Pattern**: All files import logger from `@/utils/logger` - **Pattern**: All files import logger from `@/utils/logger`
- **Impact**: No circular dependencies, logger is self-contained - **Impact**: No circular dependencies, logger is self-contained
@ -106,21 +115,25 @@ The codebase currently has **no active circular dependencies** that are causing
## Resolution Strategy - COMPLETED ## Resolution Strategy - COMPLETED
### ✅ **Phase 1: Complete PlatformServiceMixin Independence (COMPLETE)** ### ✅ **Phase 1: Complete PlatformServiceMixin Independence (COMPLETE)**
1. **Removed memoryLogs import** from PlatformServiceMixin ✅ 1. **Removed memoryLogs import** from PlatformServiceMixin ✅
2. **Created self-contained memoryLogs** implementation ✅ 2. **Created self-contained memoryLogs** implementation ✅
3. **Added missing utility methods** to PlatformServiceMixin ✅ 3. **Added missing utility methods** to PlatformServiceMixin ✅
### ✅ **Phase 2: Utility Files Migration (COMPLETE)** ### ✅ **Phase 2: Utility Files Migration (COMPLETE)**
1. **Migrated deepLinks.ts** - Replaced databaseUtil logging with console logging ✅ 1. **Migrated deepLinks.ts** - Replaced databaseUtil logging with console logging ✅
2. **Migrated util.ts** - Replaced databaseUtil functions with self-contained implementations ✅ 2. **Migrated util.ts** - Replaced databaseUtil functions with self-contained implementations ✅
3. **Updated all PlatformServiceFactory calls** to use async pattern ✅ 3. **Updated all PlatformServiceFactory calls** to use async pattern ✅
### 🎯 **Phase 3: File-by-File Migration (READY TO START)** ### 🎯 **Phase 3: File-by-File Migration (READY TO START)**
1. **High-usage files first** (views, core components) 1. **High-usage files first** (views, core components)
2. **Replace databaseUtil imports** with PlatformServiceMixin 2. **Replace databaseUtil imports** with PlatformServiceMixin
3. **Update function calls** to use mixin methods 3. **Update function calls** to use mixin methods
### 🎯 **Phase 4: Cleanup (FUTURE)** ### 🎯 **Phase 4: Cleanup (FUTURE)**
1. **Remove unused databaseUtil functions** 1. **Remove unused databaseUtil functions**
2. **Update TypeScript interfaces** 2. **Update TypeScript interfaces**
3. **Remove databaseUtil imports** from all files 3. **Remove databaseUtil imports** from all files
@ -128,6 +141,7 @@ The codebase currently has **no active circular dependencies** that are causing
## Current Status Summary ## Current Status Summary
### ✅ **Resolved Issues** ### ✅ **Resolved Issues**
1. **Logger circular dependency** - Fixed with self-contained implementation 1. **Logger circular dependency** - Fixed with self-contained implementation
2. **PlatformServiceMixin circular dependency** - Fixed with self-contained memoryLogs 2. **PlatformServiceMixin circular dependency** - Fixed with self-contained memoryLogs
3. **Utility files circular dependency** - Fixed with self-contained implementations 3. **Utility files circular dependency** - Fixed with self-contained implementations
@ -135,6 +149,7 @@ The codebase currently has **no active circular dependencies** that are causing
5. **Runtime stability** - No circular dependency crashes 5. **Runtime stability** - No circular dependency crashes
### 🎯 **Ready for Next Phase** ### 🎯 **Ready for Next Phase**
1. **52 files** ready for databaseUtil migration 1. **52 files** ready for databaseUtil migration
2. **PlatformServiceMixin** fully independent and functional 2. **PlatformServiceMixin** fully independent and functional
3. **Clear migration path** - Well-defined targets and strategy 3. **Clear migration path** - Well-defined targets and strategy
@ -142,6 +157,7 @@ The codebase currently has **no active circular dependencies** that are causing
## Benefits of Current State ## Benefits of Current State
### ✅ **Achieved** ### ✅ **Achieved**
1. **No runtime circular dependencies** - Application runs without crashes 1. **No runtime circular dependencies** - Application runs without crashes
2. **Self-contained logger** - No more logger/databaseUtil loops 2. **Self-contained logger** - No more logger/databaseUtil loops
3. **PlatformServiceMixin ready** - All methods implemented and independent 3. **PlatformServiceMixin ready** - All methods implemented and independent
@ -149,6 +165,7 @@ The codebase currently has **no active circular dependencies** that are causing
5. **Clear migration path** - Well-defined targets and strategy 5. **Clear migration path** - Well-defined targets and strategy
### 🎯 **Expected After Migration** ### 🎯 **Expected After Migration**
1. **Complete databaseUtil migration** - Single source of truth 1. **Complete databaseUtil migration** - Single source of truth
2. **Eliminated circular dependencies** - Clean architecture 2. **Eliminated circular dependencies** - Clean architecture
3. **Improved performance** - Caching and optimization 3. **Improved performance** - Caching and optimization

14
doc/component-communication-guide.md

@ -93,6 +93,7 @@ export default class FormComponent extends Vue {
When generating component templates, follow these patterns: When generating component templates, follow these patterns:
#### Function Props Template #### Function Props Template
```vue ```vue
<template> <template>
<div class="component-name"> <div class="component-name">
@ -124,6 +125,7 @@ export default class ComponentName extends Vue {
``` ```
#### $emit Template (for DOM events) #### $emit Template (for DOM events)
```vue ```vue
<template> <template>
<div class="component-name"> <div class="component-name">
@ -155,12 +157,14 @@ export default class ComponentName extends Vue {
### Code Generation Rules ### Code Generation Rules
#### 1. Function Props for Business Logic #### 1. Function Props for Business Logic
- **Data operations**: Save, delete, update, validate - **Data operations**: Save, delete, update, validate
- **Navigation**: Route changes, modal opening/closing - **Navigation**: Route changes, modal opening/closing
- **State management**: Store actions, state updates - **State management**: Store actions, state updates
- **API calls**: Data fetching, form submissions - **API calls**: Data fetching, form submissions
#### 2. $emit for User Interactions #### 2. $emit for User Interactions
- **Click events**: Button clicks, link navigation - **Click events**: Button clicks, link navigation
- **Form events**: Input changes, form submissions - **Form events**: Input changes, form submissions
- **Lifecycle events**: Component mounting, unmounting - **Lifecycle events**: Component mounting, unmounting
@ -169,6 +173,7 @@ export default class ComponentName extends Vue {
#### 3. Naming Conventions #### 3. Naming Conventions
**Function Props:** **Function Props:**
```typescript ```typescript
// Action-oriented names // Action-oriented names
onSave: (data: SaveData) => Promise<void> onSave: (data: SaveData) => Promise<void>
@ -179,6 +184,7 @@ onNavigate: (route: string) => void
``` ```
**$emit Events:** **$emit Events:**
```typescript ```typescript
// Event-oriented names // Event-oriented names
@click: (event: MouseEvent) => void @click: (event: MouseEvent) => void
@ -191,6 +197,7 @@ onNavigate: (route: string) => void
### TypeScript Integration ### TypeScript Integration
#### Function Prop Types #### Function Prop Types
```typescript ```typescript
// Define reusable function types // Define reusable function types
interface SaveHandler { interface SaveHandler {
@ -207,6 +214,7 @@ interface ValidationHandler {
``` ```
#### Event Types #### Event Types
```typescript ```typescript
// Define event payload types // Define event payload types
interface ClickEvent { interface ClickEvent {
@ -226,6 +234,7 @@ handleClick(): ClickEvent {
## Testing Guidelines ## Testing Guidelines
### Function Props Testing ### Function Props Testing
```typescript ```typescript
// Easy to mock and test // Easy to mock and test
const mockOnSave = jest.fn(); const mockOnSave = jest.fn();
@ -240,6 +249,7 @@ expect(mockOnSave).toHaveBeenCalledWith(expectedData);
``` ```
### $emit Testing ### $emit Testing
```typescript ```typescript
// Requires event simulation // Requires event simulation
const wrapper = mount(MyComponent); const wrapper = mount(MyComponent);
@ -260,6 +270,7 @@ expect(wrapper.emitted('click')).toBeTruthy();
### Example Migration ### Example Migration
**Before ($emit):** **Before ($emit):**
```typescript ```typescript
@Emit("save") @Emit("save")
handleSave() { handleSave() {
@ -268,6 +279,7 @@ handleSave() {
``` ```
**After (Function Props):** **After (Function Props):**
```typescript ```typescript
@Prop({ required: true }) onSave!: (data: FormData) => void; @Prop({ required: true }) onSave!: (data: FormData) => void;
@ -288,6 +300,7 @@ handleSave() {
## Code Generation Templates ## Code Generation Templates
### Component Generator Input ### Component Generator Input
```typescript ```typescript
interface ComponentSpec { interface ComponentSpec {
name: string; name: string;
@ -306,6 +319,7 @@ interface ComponentSpec {
``` ```
### Generated Output ### Generated Output
```typescript ```typescript
// Generator should automatically choose function props vs $emit // Generator should automatically choose function props vs $emit
// based on the nature of the interaction (business logic vs DOM event) // based on the nature of the interaction (business logic vs DOM event)

14
doc/cors-disabled-for-universal-images.md

@ -7,10 +7,12 @@ CORS headers have been **disabled** to support Time Safari's core mission: enabl
## What Changed ## What Changed
### ❌ Removed CORS Headers ### ❌ Removed CORS Headers
- `Cross-Origin-Opener-Policy: same-origin` - `Cross-Origin-Opener-Policy: same-origin`
- `Cross-Origin-Embedder-Policy: require-corp` - `Cross-Origin-Embedder-Policy: require-corp`
### ✅ Results ### ✅ Results
- Images from **any domain** now work in development and production - Images from **any domain** now work in development and production
- No proxy configuration needed - No proxy configuration needed
- No whitelist of supported image hosts - No whitelist of supported image hosts
@ -19,11 +21,13 @@ CORS headers have been **disabled** to support Time Safari's core mission: enabl
## Technical Tradeoffs ## Technical Tradeoffs
### 🔻 Lost: SharedArrayBuffer Performance ### 🔻 Lost: SharedArrayBuffer Performance
- **Before**: Fast SQLite operations via SharedArrayBuffer - **Before**: Fast SQLite operations via SharedArrayBuffer
- **After**: Slightly slower IndexedDB fallback mode - **After**: Slightly slower IndexedDB fallback mode
- **Impact**: Minimal for typical usage - absurd-sql automatically falls back - **Impact**: Minimal for typical usage - absurd-sql automatically falls back
### 🔺 Gained: Universal Image Support ### 🔺 Gained: Universal Image Support
- **Before**: Only specific domains worked (TimeSafari, Flickr, Imgur, etc.) - **Before**: Only specific domains worked (TimeSafari, Flickr, Imgur, etc.)
- **After**: Any image URL works immediately - **After**: Any image URL works immediately
- **Impact**: Massive improvement for user experience - **Impact**: Massive improvement for user experience
@ -31,6 +35,7 @@ CORS headers have been **disabled** to support Time Safari's core mission: enabl
## Architecture Impact ## Architecture Impact
### Database Operations ### Database Operations
```typescript ```typescript
// absurd-sql automatically detects SharedArrayBuffer availability // absurd-sql automatically detects SharedArrayBuffer availability
if (typeof SharedArrayBuffer === "undefined") { if (typeof SharedArrayBuffer === "undefined") {
@ -43,6 +48,7 @@ if (typeof SharedArrayBuffer === "undefined") {
``` ```
### Image Loading ### Image Loading
```typescript ```typescript
// All images load directly now // All images load directly now
export function transformImageUrlForCors(imageUrl: string): string { export function transformImageUrlForCors(imageUrl: string): string {
@ -53,11 +59,13 @@ export function transformImageUrlForCors(imageUrl: string): string {
## Why This Was The Right Choice ## Why This Was The Right Choice
### Time Safari's Use Case ### Time Safari's Use Case
- **Community platform** where users share content from anywhere - **Community platform** where users share content from anywhere
- **User-generated content** includes images from arbitrary websites - **User-generated content** includes images from arbitrary websites
- **Flexibility** is more important than marginal performance gains - **Flexibility** is more important than marginal performance gains
### Alternative Would Require ### Alternative Would Require
- Pre-configuring proxies for every possible image hosting service - Pre-configuring proxies for every possible image hosting service
- Constantly updating proxy list as users find new sources - Constantly updating proxy list as users find new sources
- Poor user experience when images fail to load - Poor user experience when images fail to load
@ -66,11 +74,13 @@ export function transformImageUrlForCors(imageUrl: string): string {
## Performance Comparison ## Performance Comparison
### Database Operations ### Database Operations
- **SharedArrayBuffer**: ~2x faster for large operations - **SharedArrayBuffer**: ~2x faster for large operations
- **IndexedDB**: Still very fast for typical Time Safari usage - **IndexedDB**: Still very fast for typical Time Safari usage
- **Real Impact**: Negligible for typical user operations - **Real Impact**: Negligible for typical user operations
### Image Loading ### Image Loading
- **With CORS**: Many images failed to load in development - **With CORS**: Many images failed to load in development
- **Without CORS**: All images load immediately - **Without CORS**: All images load immediately
- **Real Impact**: Massive improvement in user experience - **Real Impact**: Massive improvement in user experience
@ -87,11 +97,13 @@ export function transformImageUrlForCors(imageUrl: string): string {
## Migration Notes ## Migration Notes
### For Developers ### For Developers
- No code changes needed - No code changes needed
- `transformImageUrlForCors()` still exists but returns original URL - `transformImageUrlForCors()` still exists but returns original URL
- All existing image references work without modification - All existing image references work without modification
### For Users ### For Users
- Images from any website now work immediately - Images from any website now work immediately
- No more "image failed to load" issues in development - No more "image failed to load" issues in development
- Consistent behavior between development and production - Consistent behavior between development and production
@ -99,12 +111,14 @@ export function transformImageUrlForCors(imageUrl: string): string {
## Future Considerations ## Future Considerations
### If Performance Becomes Critical ### If Performance Becomes Critical
1. **Selective CORS**: Enable only for specific operations 1. **Selective CORS**: Enable only for specific operations
2. **Service Worker**: Handle image proxying at service worker level 2. **Service Worker**: Handle image proxying at service worker level
3. **Build-time Processing**: Pre-process images during build 3. **Build-time Processing**: Pre-process images during build
4. **User Education**: Guide users toward optimized image hosting 4. **User Education**: Guide users toward optimized image hosting
### Monitoring ### Monitoring
- Track database operation performance - Track database operation performance
- Monitor for any user-reported slowness - Monitor for any user-reported slowness
- Consider re-enabling SharedArrayBuffer if usage patterns change - Consider re-enabling SharedArrayBuffer if usage patterns change

26
doc/cors-image-loading-solution.md

@ -7,6 +7,7 @@ This document describes the implementation of a comprehensive image loading solu
## Problem Statement ## Problem Statement
When using SharedArrayBuffer (required for absurd-sql), browsers enforce a cross-origin isolated environment with these headers: 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-Opener-Policy: same-origin`
- `Cross-Origin-Embedder-Policy: require-corp` - `Cross-Origin-Embedder-Policy: require-corp`
@ -19,6 +20,7 @@ This isolation prevents loading external resources (including images) unless the
The solution uses a multi-tier approach to handle images from various sources: The solution uses a multi-tier approach to handle images from various sources:
#### Tier 1: Specific Domain Proxies (Development Only) #### Tier 1: Specific Domain Proxies (Development Only)
- **TimeSafari Images**: `/image-proxy/``https://image.timesafari.app/` - **TimeSafari Images**: `/image-proxy/``https://image.timesafari.app/`
- **Flickr Images**: `/flickr-proxy/``https://live.staticflickr.com/` - **Flickr Images**: `/flickr-proxy/``https://live.staticflickr.com/`
- **Imgur Images**: `/imgur-proxy/``https://i.imgur.com/` - **Imgur Images**: `/imgur-proxy/``https://i.imgur.com/`
@ -26,14 +28,17 @@ The solution uses a multi-tier approach to handle images from various sources:
- **Unsplash**: `/unsplash-proxy/``https://images.unsplash.com/` - **Unsplash**: `/unsplash-proxy/``https://images.unsplash.com/`
#### Tier 2: Universal CORS Proxy (Development Only) #### Tier 2: Universal CORS Proxy (Development Only)
- **Any External Domain**: Uses `https://api.allorigins.win/raw?url=` for arbitrary domains - **Any External Domain**: Uses `https://api.allorigins.win/raw?url=` for arbitrary domains
#### Tier 3: Direct Loading (Production) #### Tier 3: Direct Loading (Production)
- **Production Mode**: All images load directly without proxying - **Production Mode**: All images load directly without proxying
### 2. Smart URL Transformation ### 2. Smart URL Transformation
The `transformImageUrlForCors` function automatically: The `transformImageUrlForCors` function automatically:
- Detects the image source domain - Detects the image source domain
- Routes through appropriate proxy in development - Routes through appropriate proxy in development
- Preserves original URLs in production - Preserves original URLs in production
@ -44,6 +49,7 @@ The `transformImageUrlForCors` function automatically:
### Configuration Files ### Configuration Files
#### `vite.config.common.mts` #### `vite.config.common.mts`
```typescript ```typescript
server: { server: {
headers: { headers: {
@ -63,6 +69,7 @@ server: {
``` ```
#### `src/libs/util.ts` #### `src/libs/util.ts`
```typescript ```typescript
export function transformImageUrlForCors(imageUrl: string): string { export function transformImageUrlForCors(imageUrl: string): string {
// Development mode: Transform URLs to use proxies // Development mode: Transform URLs to use proxies
@ -93,21 +100,25 @@ const imageUrl = transformImageUrlForCors(originalImageUrl);
## Benefits ## Benefits
### ✅ SharedArrayBuffer Support ### ✅ SharedArrayBuffer Support
- Maintains cross-origin isolation required for SharedArrayBuffer - Maintains cross-origin isolation required for SharedArrayBuffer
- Enables fast SQLite database operations via absurd-sql - Enables fast SQLite database operations via absurd-sql
- Provides better performance than IndexedDB fallback - Provides better performance than IndexedDB fallback
### ✅ Universal Image Support ### ✅ Universal Image Support
- Handles images from any domain - Handles images from any domain
- No need to pre-configure every possible image source - No need to pre-configure every possible image source
- Graceful fallback for unknown domains - Graceful fallback for unknown domains
### ✅ Development/Production Flexibility ### ✅ Development/Production Flexibility
- Proxy system only active in development - Proxy system only active in development
- Production uses direct URLs for maximum performance - Production uses direct URLs for maximum performance
- No proxy server required in production - No proxy server required in production
### ✅ Automatic Detection ### ✅ Automatic Detection
- Smart URL transformation based on domain patterns - Smart URL transformation based on domain patterns
- Preserves relative URLs and data URLs - Preserves relative URLs and data URLs
- Handles edge cases gracefully - Handles edge cases gracefully
@ -115,6 +126,7 @@ const imageUrl = transformImageUrlForCors(originalImageUrl);
## Testing ## Testing
### Automated Testing ### Automated Testing
Run the test suite to verify URL transformation: Run the test suite to verify URL transformation:
```typescript ```typescript
@ -125,6 +137,7 @@ testCorsImageTransformation();
``` ```
### Visual Testing ### Visual Testing
Create test image elements to verify loading: Create test image elements to verify loading:
```typescript ```typescript
@ -135,6 +148,7 @@ createTestImageElements();
``` ```
### Manual Testing ### Manual Testing
1. Start development server: `npm run dev` 1. Start development server: `npm run dev`
2. Open browser console to see transformation logs 2. Open browser console to see transformation logs
3. Check Network tab for proxy requests 3. Check Network tab for proxy requests
@ -143,16 +157,19 @@ createTestImageElements();
## Security Considerations ## Security Considerations
### Development Environment ### Development Environment
- CORS proxies are only used in development - CORS proxies are only used in development
- External proxy services (allorigins.win) are used for testing - External proxy services (allorigins.win) are used for testing
- No sensitive data is exposed through proxies - No sensitive data is exposed through proxies
### Production Environment ### Production Environment
- All images load directly without proxying - All images load directly without proxying
- No dependency on external proxy services - No dependency on external proxy services
- Original security model maintained - Original security model maintained
### Privacy ### Privacy
- Image URLs are not logged or stored by proxy services - Image URLs are not logged or stored by proxy services
- Proxy requests are only made during development - Proxy requests are only made during development
- No tracking or analytics in proxy chain - No tracking or analytics in proxy chain
@ -160,11 +177,13 @@ createTestImageElements();
## Performance Impact ## Performance Impact
### Development ### Development
- Slight latency from proxy requests - Slight latency from proxy requests
- Additional network hops for external domains - Additional network hops for external domains
- More verbose logging for debugging - More verbose logging for debugging
### Production ### Production
- No performance impact - No performance impact
- Direct image loading as before - Direct image loading as before
- No proxy overhead - No proxy overhead
@ -174,17 +193,20 @@ createTestImageElements();
### Common Issues ### Common Issues
#### Images Not Loading in Development #### Images Not Loading in Development
1. Check console for proxy errors 1. Check console for proxy errors
2. Verify CORS headers are set 2. Verify CORS headers are set
3. Test with different image URLs 3. Test with different image URLs
4. Check network connectivity to proxy services 4. Check network connectivity to proxy services
#### SharedArrayBuffer Not Available #### SharedArrayBuffer Not Available
1. Verify CORS headers are set in server configuration 1. Verify CORS headers are set in server configuration
2. Check that site is served over HTTPS (or localhost) 2. Check that site is served over HTTPS (or localhost)
3. Ensure browser supports SharedArrayBuffer 3. Ensure browser supports SharedArrayBuffer
#### Proxy Service Unavailable #### Proxy Service Unavailable
1. Check if allorigins.win is accessible 1. Check if allorigins.win is accessible
2. Consider using alternative CORS proxy services 2. Consider using alternative CORS proxy services
3. Temporarily disable CORS headers for testing 3. Temporarily disable CORS headers for testing
@ -207,12 +229,14 @@ testCorsImageTransformation();
## Migration Guide ## Migration Guide
### From Previous Implementation ### From Previous Implementation
1. CORS headers are now required for SharedArrayBuffer 1. CORS headers are now required for SharedArrayBuffer
2. Image URLs automatically transformed in development 2. Image URLs automatically transformed in development
3. No changes needed to existing image loading code 3. No changes needed to existing image loading code
4. Test thoroughly in both development and production 4. Test thoroughly in both development and production
### Adding New Image Sources ### Adding New Image Sources
1. Add specific proxy for frequently used domains 1. Add specific proxy for frequently used domains
2. Update `transformImageUrlForCors` function 2. Update `transformImageUrlForCors` function
3. Add CORS headers to proxy configuration 3. Add CORS headers to proxy configuration
@ -221,6 +245,7 @@ testCorsImageTransformation();
## Future Enhancements ## Future Enhancements
### Possible Improvements ### Possible Improvements
1. **Local Proxy Server**: Run dedicated proxy server for development 1. **Local Proxy Server**: Run dedicated proxy server for development
2. **Caching**: Cache proxy responses for better performance 2. **Caching**: Cache proxy responses for better performance
3. **Fallback Chain**: Multiple proxy services for reliability 3. **Fallback Chain**: Multiple proxy services for reliability
@ -228,6 +253,7 @@ testCorsImageTransformation();
5. **Analytics**: Track image loading success/failure rates 5. **Analytics**: Track image loading success/failure rates
### Alternative Approaches ### Alternative Approaches
1. **Service Worker**: Intercept image requests at service worker level 1. **Service Worker**: Intercept image requests at service worker level
2. **Build-time Processing**: Pre-process images during build 2. **Build-time Processing**: Pre-process images during build
3. **CDN Integration**: Use CDN with proper CORS headers 3. **CDN Integration**: Use CDN with proper CORS headers

1
doc/database-migration-guide.md

@ -294,6 +294,7 @@ const result = await this.$db("SELECT * FROM contacts WHERE did = ?", [accountDi
``` ```
This provides: This provides:
- **Caching**: Automatic caching for performance - **Caching**: Automatic caching for performance
- **Error Handling**: Consistent error handling - **Error Handling**: Consistent error handling
- **Type Safety**: Enhanced TypeScript integration - **Type Safety**: Enhanced TypeScript integration

187
doc/debug-hook-guide.md

@ -0,0 +1,187 @@
# TimeSafari Debug Hook Guide
**Complete Guide for Team Members**
**Date**: 2025-01-27
**Author**: Matthew Raymer
**Status**: ✅ **ACTIVE** - Ready for production use
## 🎯 Overview
A pre-commit hook that automatically detects and prevents debug code from reaching protected branches (master, main, production, release, stable). This ensures production code remains clean while allowing free development on feature branches.
## 🚀 Quick Installation
**From within the TimeSafari repository:**
```bash
./scripts/install-debug-hook.sh
```
This automatically installs, updates, and verifies the hook in your current
repository. **Note**: Hooks are not automatically installed - you must run this
script deliberately to enable debug code checking.
## 🔧 Manual Installation
**Copy files manually:**
```bash
cp scripts/git-hooks/pre-commit /path/to/your/repo/.git/hooks/
cp scripts/git-hooks/debug-checker.config /path/to/your/repo/.git/hooks/
chmod +x /path/to/your/repo/.git/hooks/pre-commit
```
## 📋 What Gets Installed
- **`pre-commit`** - Main hook script (executable)
- **`debug-checker.config`** - Configuration file
- **`README.md`** - Documentation and troubleshooting
**Note**: Hooks are stored in `scripts/git-hooks/` and must be deliberately
installed by each developer. They are not automatically active.
## 🎯 How It Works
1. **Deliberate Installation**: Hooks must be explicitly installed by each
developer
2. **Branch Detection**: Only runs on protected branches
3. **File Filtering**: Automatically skips tests, scripts, and documentation
4. **Pattern Matching**: Detects debug code using regex patterns
5. **Commit Prevention**: Blocks commits containing debug code
## 🔒 Installation Philosophy
**Why deliberate installation?**
- **Developer choice**: Each developer decides whether to use the hook
- **No forced behavior**: Hooks don't interfere with existing workflows
- **Local control**: Hooks are installed locally, not globally
- **Easy removal**: Can be uninstalled at any time
- **Team flexibility**: Some developers may prefer different tools
## 🌿 Branch Behavior
- **Protected branches** (master, main, production, release, stable): Hook runs automatically
- **Feature branches**: Hook is skipped, allowing free development with debug code
## 🔍 Debug Patterns Detected
- **Console statements**: `console.log`, `console.debug`, `console.error`
- **Template debug**: `Debug:`, `debug:` in Vue templates
- **Debug constants**: `DEBUG_`, `debug_` variables
- **HTML debug**: `<!-- debug` comments
- **Debug attributes**: `debug="true"` attributes
- **Vue debug**: `v-if="debug"`, `v-show="debug"`
- **Debug TODOs**: `TODO debug`, `FIXME debug`
## 📁 Files Automatically Skipped
- Test files: `*.test.js`, `*.spec.ts`, `*.test.vue`
- Scripts: `scripts/` directory
- Test directories: `test-*` directories
- Documentation: `docs/`, `*.md`, `*.txt`
- Config files: `*.json`, `*.yml`, `*.yaml`
- IDE files: `.cursor/` directory
## ✅ Verification
**After installation, verify it's working:**
```bash
# Check if files exist
ls -la .git/hooks/pre-commit
ls -la .git/hooks/debug-checker.config
# Test the hook manually
.git/hooks/pre-commit
# Test with actual commit
echo "console.log('test')" > test.vue
git add test.vue
git commit -m "test" # Should be blocked
```
## 📊 Example Output
```
❌ Debug code detected in staged files!
Branch: master
Files checked: 1
Errors found: 3
🚨 AccountViewView.vue: Found debug pattern 'console\.'
🚨 AccountViewView.vue: Found debug pattern 'Debug:'
🚨 AccountViewView.vue: Found debug pattern 'DEBUG_'
💡 Please remove debug code before committing to master
```
## ⚙️ Configuration
Edit `.git/hooks/debug-checker.config` to customize:
- **Protected branches**: Add/remove branches as needed
- **Debug patterns**: Customize what gets detected
- **Skip patterns**: Adjust file filtering rules
## 🚨 Emergency Bypass
If you absolutely need to commit debug code to a protected branch:
```bash
git commit --no-verify -m "emergency: debug code needed"
```
⚠️ **Warning**: This bypasses all pre-commit hooks. Use sparingly.
## 🔄 Updates
When the hook is updated in the main repository:
```bash
./scripts/install-debug-hook.sh
```
## 🚨 Troubleshooting
| Issue | Solution |
|-------|----------|
| Hook not running | Check if on protected branch, verify permissions |
| Permission denied | Run `chmod +x .git/hooks/pre-commit` |
| Files not found | Ensure you're copying from TimeSafari repo |
| False positives | Edit `debug-checker.config` to customize patterns |
## 🧪 Testing
A test script is available at `scripts/test-debug-hook.sh` to verify the hook works correctly.
## 💡 Best Practices
1. **Use feature branches** for development with debug code
2. **Use proper logging** instead of console statements (`logger.info`, `logger.debug`)
3. **Test thoroughly** before merging to protected branches
4. **Review commits** to ensure no debug code slips through
5. **Keep hooks updated** across all repositories
## 📚 Additional Resources
- **Hook documentation**: `scripts/git-hooks/README.md`
- **Configuration**: `scripts/git-hooks/debug-checker.config`
- **Test script**: `scripts/test-debug-hook.sh`
- **Installation script**: `scripts/install-debug-hook.sh`
## 🎯 Team Workflow
**Recommended setup:**
1. **Repository setup**: Include hook files in `.githooks/` directory
2. **Team onboarding**: Run installation script in each repo
3. **Updates**: Re-run installation script when hooks are updated
4. **Documentation**: Keep this guide updated
---
**Status**: Active and enforced
**Last Updated**: 2025-01-27
**Maintainer**: Matthew Raymer

6
doc/electron-cleanup-summary.md

@ -7,18 +7,22 @@ This document summarizes the comprehensive cleanup and improvements made to the
## Key Issues Resolved ## Key Issues Resolved
### 1. Platform Detection Problems ### 1. Platform Detection Problems
- **Before**: `PlatformServiceFactory` only supported "capacitor" and "web" platforms - **Before**: `PlatformServiceFactory` only supported "capacitor" and "web" platforms
- **After**: Added proper "electron" platform support with dedicated `ElectronPlatformService` - **After**: Added proper "electron" platform support with dedicated `ElectronPlatformService`
### 2. Build Configuration Confusion ### 2. Build Configuration Confusion
- **Before**: Electron builds used `VITE_PLATFORM=capacitor`, causing confusion - **Before**: Electron builds used `VITE_PLATFORM=capacitor`, causing confusion
- **After**: Electron builds now properly use `VITE_PLATFORM=electron` - **After**: Electron builds now properly use `VITE_PLATFORM=electron`
### 3. Missing Platform Service Methods ### 3. Missing Platform Service Methods
- **Before**: Platform services lacked proper `isElectron()`, `isCapacitor()`, `isWeb()` methods - **Before**: Platform services lacked proper `isElectron()`, `isCapacitor()`, `isWeb()` methods
- **After**: All platform services implement complete interface with proper detection - **After**: All platform services implement complete interface with proper detection
### 4. Inconsistent Build Scripts ### 4. Inconsistent Build Scripts
- **Before**: Mixed platform settings in build scripts - **Before**: Mixed platform settings in build scripts
- **After**: Clean, consistent electron-specific build process - **After**: Clean, consistent electron-specific build process
@ -215,11 +219,13 @@ if (capabilities.hasFileDownload) {
## File Structure Changes ## File Structure Changes
### New Files ### New Files
- `vite.config.electron.mts` - Electron-specific Vite configuration - `vite.config.electron.mts` - Electron-specific Vite configuration
- `src/main.electron.ts` - Electron main entry point - `src/main.electron.ts` - Electron main entry point
- `doc/electron-cleanup-summary.md` - This documentation - `doc/electron-cleanup-summary.md` - This documentation
### Modified Files ### Modified Files
- `src/services/PlatformServiceFactory.ts` - Added electron platform support - `src/services/PlatformServiceFactory.ts` - Added electron platform support
- `src/services/PlatformService.ts` - Added platform detection methods - `src/services/PlatformService.ts` - Added platform detection methods
- `src/services/platforms/CapacitorPlatformService.ts` - Added missing interface methods - `src/services/platforms/CapacitorPlatformService.ts` - Added missing interface methods

21
doc/electron-console-cleanup.md

@ -7,18 +7,22 @@ This document summarizes the comprehensive changes made to reduce excessive cons
## Issues Addressed ## Issues Addressed
### 1. Excessive Database Logging (Major Issue - 90% Reduction) ### 1. Excessive Database Logging (Major Issue - 90% Reduction)
**Problem:** Every database operation was logging detailed parameter information, creating hundreds of lines of console output. **Problem:** Every database operation was logging detailed parameter information, creating hundreds of lines of console output.
**Solution:** Modified `src/services/platforms/CapacitorPlatformService.ts`: **Solution:** Modified `src/services/platforms/CapacitorPlatformService.ts`:
- Changed `logger.warn` to `logger.debug` for routine SQL operations - Changed `logger.warn` to `logger.debug` for routine SQL operations
- Reduced migration logging verbosity - Reduced migration logging verbosity
- Made database integrity checks use debug-level logging - Made database integrity checks use debug-level logging
- Kept error and completion messages at appropriate log levels - Kept error and completion messages at appropriate log levels
### 2. Enhanced Logger Configuration ### 2. Enhanced Logger Configuration
**Problem:** No platform-specific logging controls, causing noise in Electron. **Problem:** No platform-specific logging controls, causing noise in Electron.
**Solution:** Updated `src/utils/logger.ts`: **Solution:** Updated `src/utils/logger.ts`:
- Added platform detection for Electron vs Web - Added platform detection for Electron vs Web
- Suppressed debug and verbose logs for Electron - Suppressed debug and verbose logs for Electron
- Filtered out routine database operations from database logging - Filtered out routine database operations from database logging
@ -26,28 +30,35 @@ This document summarizes the comprehensive changes made to reduce excessive cons
- Added intelligent filtering for CapacitorPlatformService messages - Added intelligent filtering for CapacitorPlatformService messages
### 3. API Configuration Issues (Major Fix) ### 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: **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 - 400 status errors from missing local development servers
- JSON parsing errors (HTML error pages instead of JSON responses) - JSON parsing errors (HTML error pages instead of JSON responses)
**Solution:** **Solution:**
- Updated `src/constants/app.ts` to provide Electron-specific API endpoints - 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 - **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 - This ensures Electron never uses localhost development servers that users might have saved
### 4. SharedArrayBuffer Logging Noise ### 4. SharedArrayBuffer Logging Noise
**Problem:** Web-specific SharedArrayBuffer detection was running in Electron, creating unnecessary debug output. **Problem:** Web-specific SharedArrayBuffer detection was running in Electron, creating unnecessary debug output.
**Solution:** Modified `src/main.web.ts`: **Solution:** Modified `src/main.web.ts`:
- Made SharedArrayBuffer logging conditional on web platform only - Made SharedArrayBuffer logging conditional on web platform only
- Converted console.log statements to logger.debug - Converted console.log statements to logger.debug
- Only show in development mode for web platform - Only show in development mode for web platform
- Reduced platform detection noise - Reduced platform detection noise
### 5. Missing Source Maps Warnings ### 5. Missing Source Maps Warnings
**Problem:** Electron DevTools was complaining about missing source maps for external dependencies. **Problem:** Electron DevTools was complaining about missing source maps for external dependencies.
**Solution:** Updated `vite.config.electron.mts`: **Solution:** Updated `vite.config.electron.mts`:
- Disabled source maps for Electron builds (`sourcemap: false`) - Disabled source maps for Electron builds (`sourcemap: false`)
- Added build configuration to suppress external dependency warnings - Added build configuration to suppress external dependency warnings
- Prevents DevTools from looking for non-existent source map files - Prevents DevTools from looking for non-existent source map files
@ -87,14 +98,16 @@ This document summarizes the comprehensive changes made to reduce excessive cons
## Impact ## Impact
### Before Cleanup: ### Before Cleanup
- 500+ lines of console output per minute - 500+ lines of console output per minute
- Detailed SQL parameter logging for every operation - Detailed SQL parameter logging for every operation
- API connection errors every few seconds (400 status, JSON parsing errors) - API connection errors every few seconds (400 status, JSON parsing errors)
- SharedArrayBuffer warnings on every startup - SharedArrayBuffer warnings on every startup
- DevTools source map warnings - DevTools source map warnings
### After Cleanup: ### After Cleanup
- **~95% reduction** in console output - **~95% reduction** in console output
- Only errors and important status messages visible - Only errors and important status messages visible
- **No API connection errors** - Electron uses proper production endpoints - **No API connection errors** - Electron uses proper production endpoints
@ -106,6 +119,7 @@ This document summarizes the comprehensive changes made to reduce excessive cons
## Technical Details ## Technical Details
### API Configuration Fix ### API Configuration Fix
The most critical fix was in `src/db/databaseUtil.ts` where we added: The most critical fix was in `src/db/databaseUtil.ts` where we added:
```typescript ```typescript
@ -122,6 +136,7 @@ if (process.env.VITE_PLATFORM === "electron") {
This ensures that even if users have localhost development endpoints saved in their settings, Electron will override them with production endpoints. This ensures that even if users have localhost development endpoints saved in their settings, Electron will override them with production endpoints.
### Logger Enhancement ### Logger Enhancement
Enhanced the logger with platform-specific behavior: Enhanced the logger with platform-specific behavior:
```typescript ```typescript
@ -135,6 +150,7 @@ if (!isElectron || !message.includes("[CapacitorPlatformService]")) {
## Testing ## Testing
The changes were tested with: The changes were tested with:
- `npm run lint-fix` - 0 errors, warnings only (pre-existing) - `npm run lint-fix` - 0 errors, warnings only (pre-existing)
- Electron development environment - Electron development environment
- Web platform (unchanged functionality) - Web platform (unchanged functionality)
@ -150,6 +166,7 @@ The changes were tested with:
## Backward Compatibility ## Backward Compatibility
All changes maintain backward compatibility: All changes maintain backward compatibility:
- Web platform logging unchanged - Web platform logging unchanged
- Capacitor platform logging unchanged - Capacitor platform logging unchanged
- Error handling preserved - Error handling preserved

13
doc/error-diagnostics-log.md

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

21
doc/image-hosting-guide.md

@ -25,6 +25,7 @@
## Why This Happens ## Why This Happens
In development mode, we enable SharedArrayBuffer for fast SQLite operations, which requires: In development mode, we enable SharedArrayBuffer for fast SQLite operations, which requires:
- `Cross-Origin-Opener-Policy: same-origin` - `Cross-Origin-Opener-Policy: same-origin`
- `Cross-Origin-Embedder-Policy: require-corp` - `Cross-Origin-Embedder-Policy: require-corp`
@ -35,6 +36,7 @@ These headers create a **cross-origin isolated environment** that blocks resourc
### 1. Use Supported Image Hosting Services ### 1. Use Supported Image Hosting Services
**Recommended services that work well:** **Recommended services that work well:**
- **Imgur**: Free, no registration required, direct links - **Imgur**: Free, no registration required, direct links
- **GitHub**: If you have images in repositories - **GitHub**: If you have images in repositories
- **Unsplash**: For stock photos - **Unsplash**: For stock photos
@ -45,6 +47,7 @@ These headers create a **cross-origin isolated environment** that blocks resourc
If you frequently use images from a specific domain, add a proxy: If you frequently use images from a specific domain, add a proxy:
#### Step 1: Add Proxy to `vite.config.common.mts` #### Step 1: Add Proxy to `vite.config.common.mts`
```typescript ```typescript
'/yourservice-proxy': { '/yourservice-proxy': {
target: 'https://yourservice.com', target: 'https://yourservice.com',
@ -63,6 +66,7 @@ If you frequently use images from a specific domain, add a proxy:
``` ```
#### Step 2: Update Transform Function in `src/libs/util.ts` #### Step 2: Update Transform Function in `src/libs/util.ts`
```typescript ```typescript
// Transform YourService URLs to use proxy // Transform YourService URLs to use proxy
if (imageUrl.startsWith("https://yourservice.com/")) { if (imageUrl.startsWith("https://yourservice.com/")) {
@ -74,6 +78,7 @@ if (imageUrl.startsWith("https://yourservice.com/")) {
### 3. Use Alternative Image Sources ### 3. Use Alternative Image Sources
For frequently failing domains, consider: For frequently failing domains, consider:
- Upload images to Imgur or GitHub - Upload images to Imgur or GitHub
- Use a CDN with proper CORS headers - Use a CDN with proper CORS headers
- Host images on your own domain with CORS enabled - Host images on your own domain with CORS enabled
@ -81,11 +86,13 @@ For frequently failing domains, consider:
## Development vs Production ## Development vs Production
### Development Mode ### Development Mode
- Images from supported services work through proxies - Images from supported services work through proxies
- Unsupported images may fail to load - Unsupported images may fail to load
- Console warnings show which images have issues - Console warnings show which images have issues
### Production Mode ### Production Mode
- All images load directly without proxies - All images load directly without proxies
- No CORS restrictions in production - No CORS restrictions in production
- Better performance without proxy overhead - Better performance without proxy overhead
@ -93,6 +100,7 @@ For frequently failing domains, consider:
## Testing Image Sources ## Testing Image Sources
### Check if an Image Source Works ### Check if an Image Source Works
```bash ```bash
# Test in browser console: # Test in browser console:
fetch('https://example.com/image.jpg', { mode: 'cors' }) fetch('https://example.com/image.jpg', { mode: 'cors' })
@ -101,6 +109,7 @@ fetch('https://example.com/image.jpg', { mode: 'cors' })
``` ```
### Visual Testing ### Visual Testing
```typescript ```typescript
import { createTestImageElements } from './libs/test-cors-images'; import { createTestImageElements } from './libs/test-cors-images';
createTestImageElements(); // Creates visual test panel createTestImageElements(); // Creates visual test panel
@ -109,30 +118,36 @@ createTestImageElements(); // Creates visual test panel
## Common Error Messages ## Common Error Messages
### `ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep` ### `ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep`
**Cause**: Image source doesn't send required CORS headers **Cause**: Image source doesn't send required CORS headers
**Solution**: Use a supported image hosting service or add a proxy **Solution**: Use a supported image hosting service or add a proxy
### `ERR_NETWORK` or `ERR_INTERNET_DISCONNECTED` ### `ERR_NETWORK` or `ERR_INTERNET_DISCONNECTED`
**Cause**: Proxy service is unavailable **Cause**: Proxy service is unavailable
**Solution**: Check internet connection or use alternative image source **Solution**: Check internet connection or use alternative image source
### Images Load in Production but Not Development ### Images Load in Production but Not Development
**Cause**: Normal behavior - development has stricter CORS requirements **Cause**: Normal behavior - development has stricter CORS requirements
**Solution**: Use supported image sources for development testing **Solution**: Use supported image sources for development testing
## Best Practices ## Best Practices
### For New Projects ### For New Projects
1. Use supported image hosting services from the start 1. Use supported image hosting services from the start
2. Upload user images to Imgur or similar service 2. Upload user images to Imgur or similar service
3. Host critical images on your own domain with CORS enabled 3. Host critical images on your own domain with CORS enabled
### For Existing Projects ### For Existing Projects
1. Identify frequently used image domains in console warnings 1. Identify frequently used image domains in console warnings
2. Add proxies for the most common domains 2. Add proxies for the most common domains
3. Gradually migrate to supported image hosting services 3. Gradually migrate to supported image hosting services
### For User-Generated Content ### For User-Generated Content
1. Provide upload functionality to supported services 1. Provide upload functionality to supported services
2. Validate image URLs against supported domains 2. Validate image URLs against supported domains
3. Show helpful error messages for unsupported sources 3. Show helpful error messages for unsupported sources
@ -140,17 +155,20 @@ createTestImageElements(); // Creates visual test panel
## Troubleshooting ## Troubleshooting
### Image Not Loading? ### Image Not Loading?
1. Check browser console for error messages 1. Check browser console for error messages
2. Verify the domain is in the supported list 2. Verify the domain is in the supported list
3. Test if the image loads in production mode 3. Test if the image loads in production mode
4. Consider adding a proxy for that domain 4. Consider adding a proxy for that domain
### Proxy Not Working? ### Proxy Not Working?
1. Check if the target service allows proxying 1. Check if the target service allows proxying
2. Verify CORS headers are being set correctly 2. Verify CORS headers are being set correctly
3. Test with a simpler image URL from the same domain 3. Test with a simpler image URL from the same domain
### Performance Issues? ### Performance Issues?
1. Proxies add latency in development only 1. Proxies add latency in development only
2. Production uses direct image loading 2. Production uses direct image loading
3. Consider using a local image cache for development 3. Consider using a local image cache for development
@ -158,6 +176,7 @@ createTestImageElements(); // Creates visual test panel
## Quick Fixes ## Quick Fixes
### For Immediate Issues ### For Immediate Issues
```typescript ```typescript
// Temporary fallback: disable CORS headers for testing // Temporary fallback: disable CORS headers for testing
// In vite.config.common.mts, comment out: // In vite.config.common.mts, comment out:
@ -166,9 +185,11 @@ createTestImageElements(); // Creates visual test panel
// 'Cross-Origin-Embedder-Policy': 'require-corp' // 'Cross-Origin-Embedder-Policy': 'require-corp'
// }, // },
``` ```
**Note**: This disables SharedArrayBuffer performance benefits. **Note**: This disables SharedArrayBuffer performance benefits.
### For Long-term Solution ### For Long-term Solution
- Use supported image hosting services - Use supported image hosting services
- Add proxies for frequently used domains - Add proxies for frequently used domains
- Migrate critical images to your own CORS-enabled CDN - Migrate critical images to your own CORS-enabled CDN

119
doc/logging-configuration.md

@ -0,0 +1,119 @@
# Logging Configuration Guide
## Overview
TimeSafari now supports configurable logging levels via the `VITE_LOG_LEVEL` environment variable. This allows developers to control the verbosity of console output without modifying code.
## Available Log Levels
| Level | Value | Description | Console Output |
|-------|-------|-------------|----------------|
| `error` | 0 | Errors only | Critical errors only |
| `warn` | 1 | Warnings and errors | Warnings and errors |
| `info` | 2 | Info, warnings, and errors | General information, warnings, and errors |
| `debug` | 3 | All log levels | Verbose debugging information |
## Environment Variable
Set the `VITE_LOG_LEVEL` environment variable to control logging:
```bash
# Show only errors
VITE_LOG_LEVEL=error
# Show warnings and errors (default for production web)
VITE_LOG_LEVEL=warn
# Show info, warnings, and errors (default for development/capacitor)
VITE_LOG_LEVEL=info
# Show all log levels including debug
VITE_LOG_LEVEL=debug
```
## Default Behavior by Platform
The logger automatically selects appropriate default log levels based on your platform and environment:
- **Production Web**: `warn` (warnings and errors only)
- **Electron**: `error` (errors only - very quiet)
- **Development/Capacitor**: `info` (info and above)
## Usage Examples
### Setting Log Level in Development
```bash
# In your terminal before running the app
export VITE_LOG_LEVEL=debug
npm run dev
# Or inline
VITE_LOG_LEVEL=debug npm run dev
```
### Setting Log Level in Production
```bash
# For verbose production logging
VITE_LOG_LEVEL=info npm run build:web
# For minimal production logging
VITE_LOG_LEVEL=warn npm run build:web
```
### Programmatic Access
The logger provides methods to check current configuration:
```typescript
import { logger } from '@/utils/logger';
// Get current log level
const currentLevel = logger.getCurrentLevel(); // 'info'
// Check if a level is enabled
const debugEnabled = logger.isLevelEnabled('debug'); // false if level < debug
// Get available levels
const levels = logger.getAvailableLevels(); // ['error', 'warn', 'info', 'debug']
```
## Database Logging
Database logging continues to work regardless of console log level settings. All log messages are still stored in the database for debugging and audit purposes.
## Migration Notes
- **Existing code**: No changes required - logging behavior remains the same
- **New feature**: Use `VITE_LOG_LEVEL` to override default behavior
- **Backward compatible**: All existing logging calls work as before
## Best Practices
1. **Development**: Use `VITE_LOG_LEVEL=debug` for maximum visibility
2. **Testing**: Use `VITE_LOG_LEVEL=info` for balanced output
3. **Production**: Use `VITE_LOG_LEVEL=warn` for minimal noise
4. **Debugging**: Temporarily set `VITE_LOG_LEVEL=debug` to troubleshoot issues
## Troubleshooting
### No Logs Appearing
Check your `VITE_LOG_LEVEL` setting:
```bash
echo $VITE_LOG_LEVEL
```
### Too Many Logs
Reduce verbosity by setting a lower log level:
```bash
VITE_LOG_LEVEL=warn
```
### Platform-Specific Issues
Remember that Electron is very quiet by default. Use `VITE_LOG_LEVEL=info` to see more output in Electron builds.

21
doc/migration-fence-definition.md

@ -9,6 +9,7 @@ This document defines the **migration fence** - the boundary between the legacy
## Current Migration Status ## Current Migration Status
### ✅ Completed Components ### ✅ Completed Components
- **SQLite Database Service**: Fully implemented with absurd-sql - **SQLite Database Service**: Fully implemented with absurd-sql
- **Platform Service Layer**: Unified database interface across platforms - **Platform Service Layer**: Unified database interface across platforms
- **PlatformServiceMixin**: Centralized database access with caching and utilities - **PlatformServiceMixin**: Centralized database access with caching and utilities
@ -17,12 +18,14 @@ This document defines the **migration fence** - the boundary between the legacy
- **Data Export/Import**: Backup and restore functionality - **Data Export/Import**: Backup and restore functionality
### 🔄 Active Migration Components ### 🔄 Active Migration Components
- **Settings Migration**: Core user settings transferred - **Settings Migration**: Core user settings transferred
- **Account Migration**: Identity and key management - **Account Migration**: Identity and key management
- **Contact Migration**: User contact data (via import interface) - **Contact Migration**: User contact data (via import interface)
- **DatabaseUtil Migration**: Moving functions to PlatformServiceMixin - **DatabaseUtil Migration**: Moving functions to PlatformServiceMixin
### ❌ Legacy Components (Fence Boundary) ### ❌ Legacy Components (Fence Boundary)
- **Dexie Database**: Legacy IndexedDB storage (disabled by default) - **Dexie Database**: Legacy IndexedDB storage (disabled by default)
- **Dexie-Specific Code**: Direct database access patterns - **Dexie-Specific Code**: Direct database access patterns
- **Legacy Migration Paths**: Old data transfer methods - **Legacy Migration Paths**: Old data transfer methods
@ -45,6 +48,7 @@ export const PlatformServiceMixin = {
``` ```
**Fence Rule**: All database operations must use: **Fence Rule**: All database operations must use:
- `this.$db()` for read operations - `this.$db()` for read operations
- `this.$exec()` for write operations - `this.$exec()` for write operations
- `this.$settings()` for settings access - `this.$settings()` for settings access
@ -64,6 +68,7 @@ export class PlatformServiceFactory {
``` ```
**Fence Rule**: All database operations must use: **Fence Rule**: All database operations must use:
- `PlatformService.dbQuery()` for read operations - `PlatformService.dbQuery()` for read operations
- `PlatformService.dbExec()` for write operations - `PlatformService.dbExec()` for write operations
- No direct `db.` or `accountsDBPromise` access in application code - No direct `db.` or `accountsDBPromise` access in application code
@ -71,6 +76,7 @@ export class PlatformServiceFactory {
### 3. Data Access Patterns ### 3. Data Access Patterns
#### ✅ Allowed (Inside Fence) #### ✅ Allowed (Inside Fence)
```typescript ```typescript
// Use PlatformServiceMixin for all database operations // Use PlatformServiceMixin for all database operations
const contacts = await this.$contacts(); const contacts = await this.$contacts();
@ -79,6 +85,7 @@ const result = await this.$db("SELECT * FROM contacts WHERE did = ?", [accountDi
``` ```
#### ❌ Forbidden (Outside Fence) #### ❌ Forbidden (Outside Fence)
```typescript ```typescript
// Direct Dexie access (legacy pattern) // Direct Dexie access (legacy pattern)
const contacts = await db.contacts.where('did').equals(accountDid).toArray(); const contacts = await db.contacts.where('did').equals(accountDid).toArray();
@ -98,6 +105,7 @@ export async function compareDatabases(): Promise<DataComparison> {
``` ```
**Fence Rule**: Migration tools are the exclusive interface between: **Fence Rule**: Migration tools are the exclusive interface between:
- Legacy Dexie database - Legacy Dexie database
- New SQLite database - New SQLite database
- Data comparison and transfer operations - Data comparison and transfer operations
@ -107,11 +115,13 @@ export async function compareDatabases(): Promise<DataComparison> {
### 1. Code Development Rules ### 1. Code Development Rules
#### New Feature Development #### New Feature Development
- **Always** use `PlatformServiceMixin` for database operations - **Always** use `PlatformServiceMixin` for database operations
- **Never** import or reference Dexie directly - **Never** import or reference Dexie directly
- **Always** use mixin methods like `this.$settings()`, `this.$contacts()` - **Always** use mixin methods like `this.$settings()`, `this.$contacts()`
#### Legacy Code Maintenance #### Legacy Code Maintenance
- **Only** modify Dexie code for migration purposes - **Only** modify Dexie code for migration purposes
- **Always** add migration tests for schema changes - **Always** add migration tests for schema changes
- **Never** add new Dexie-specific features - **Never** add new Dexie-specific features
@ -119,11 +129,13 @@ export async function compareDatabases(): Promise<DataComparison> {
### 2. Data Integrity Rules ### 2. Data Integrity Rules
#### Migration Safety #### Migration Safety
- **Always** create backups before migration - **Always** create backups before migration
- **Always** verify data integrity after migration - **Always** verify data integrity after migration
- **Never** delete legacy data until verified - **Never** delete legacy data until verified
#### Rollback Strategy #### Rollback Strategy
- **Always** maintain ability to rollback to Dexie - **Always** maintain ability to rollback to Dexie
- **Always** preserve migration logs - **Always** preserve migration logs
- **Never** assume migration is irreversible - **Never** assume migration is irreversible
@ -131,6 +143,7 @@ export async function compareDatabases(): Promise<DataComparison> {
### 3. Testing Requirements ### 3. Testing Requirements
#### Migration Testing #### Migration Testing
```typescript ```typescript
// Required test pattern for migration // Required test pattern for migration
describe('Database Migration', () => { describe('Database Migration', () => {
@ -144,6 +157,7 @@ describe('Database Migration', () => {
``` ```
#### Application Testing #### Application Testing
```typescript ```typescript
// Required test pattern for application features // Required test pattern for application features
describe('Feature with Database', () => { describe('Feature with Database', () => {
@ -159,6 +173,7 @@ describe('Feature with Database', () => {
### 1. Static Analysis ### 1. Static Analysis
#### ESLint Rules #### ESLint Rules
```json ```json
{ {
"rules": { "rules": {
@ -178,6 +193,7 @@ describe('Feature with Database', () => {
``` ```
#### TypeScript Rules #### TypeScript Rules
```json ```json
{ {
"compilerOptions": { "compilerOptions": {
@ -190,6 +206,7 @@ describe('Feature with Database', () => {
### 2. Runtime Checks ### 2. Runtime Checks
#### Development Mode Validation #### Development Mode Validation
```typescript ```typescript
// Development-only fence validation // Development-only fence validation
if (import.meta.env.DEV) { if (import.meta.env.DEV) {
@ -198,6 +215,7 @@ if (import.meta.env.DEV) {
``` ```
#### Production Safety #### Production Safety
```typescript ```typescript
// Production fence enforcement // Production fence enforcement
if (import.meta.env.PROD) { if (import.meta.env.PROD) {
@ -209,6 +227,7 @@ if (import.meta.env.PROD) {
## Migration Status Checklist ## Migration Status Checklist
### ✅ Completed ### ✅ Completed
- [x] PlatformServiceMixin implementation - [x] PlatformServiceMixin implementation
- [x] SQLite database service - [x] SQLite database service
- [x] Migration tools - [x] Migration tools
@ -217,11 +236,13 @@ if (import.meta.env.PROD) {
- [x] ActiveDid migration - [x] ActiveDid migration
### 🔄 In Progress ### 🔄 In Progress
- [ ] Contact migration - [ ] Contact migration
- [ ] DatabaseUtil to PlatformServiceMixin migration - [ ] DatabaseUtil to PlatformServiceMixin migration
- [ ] File-by-file migration - [ ] File-by-file migration
### ❌ Not Started ### ❌ Not Started
- [ ] Legacy Dexie removal - [ ] Legacy Dexie removal
- [ ] Final cleanup and validation - [ ] Final cleanup and validation

69
doc/migration-progress-tracker.md

@ -3,6 +3,7 @@
## Per-File Migration Workflow (MANDATORY) ## Per-File Migration Workflow (MANDATORY)
For each file migrated: For each file migrated:
1. **First**, migrate to PlatformServiceMixin (replace all databaseUtil usage, etc.). 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. 2. **Immediately after**, standardize notify helper usage (property + created() pattern) and fix any related linter/type errors.
@ -25,22 +26,26 @@ This document tracks the progress of the 2-day sprint to complete PlatformServic
## ✅ **DAY 1: PlatformServiceMixin Completion (COMPLETE)** ## ✅ **DAY 1: PlatformServiceMixin Completion (COMPLETE)**
### **Phase 1: Remove Circular Dependency (COMPLETE)** ### **Phase 1: Remove Circular Dependency (COMPLETE)**
**Status**: ✅ **COMPLETE** **Status**: ✅ **COMPLETE**
**Issue**: PlatformServiceMixin imports `memoryLogs` from databaseUtil **Issue**: PlatformServiceMixin imports `memoryLogs` from databaseUtil
**Solution**: Create self-contained memoryLogs implementation **Solution**: Create self-contained memoryLogs implementation
#### **Tasks**: #### **Tasks**
- [x] **Step 1.1**: Remove `memoryLogs` import from PlatformServiceMixin.ts ✅ - [x] **Step 1.1**: Remove `memoryLogs` import from PlatformServiceMixin.ts ✅
- [x] **Step 1.2**: Add self-contained `_memoryLogs` array to PlatformServiceMixin ✅ - [x] **Step 1.2**: Add self-contained `_memoryLogs` array to PlatformServiceMixin ✅
- [x] **Step 1.3**: Add `$appendToMemoryLogs()` method 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.4**: Update logger.ts to use self-contained memoryLogs ✅
- [x] **Step 1.5**: Test memoryLogs functionality ✅ - [x] **Step 1.5**: Test memoryLogs functionality ✅
#### **Files Modified**: #### **Files Modified**
- `src/utils/PlatformServiceMixin.ts` - `src/utils/PlatformServiceMixin.ts`
- `src/utils/logger.ts` - `src/utils/logger.ts`
#### **Validation**: #### **Validation**
- [x] No circular dependency errors ✅ - [x] No circular dependency errors ✅
- [x] memoryLogs functionality works correctly ✅ - [x] memoryLogs functionality works correctly ✅
- [x] Linting passes ✅ - [x] Linting passes ✅
@ -48,20 +53,24 @@ This document tracks the progress of the 2-day sprint to complete PlatformServic
--- ---
### **Phase 2: Add Missing Utility Functions (COMPLETE)** ### **Phase 2: Add Missing Utility Functions (COMPLETE)**
**Status**: ✅ **COMPLETE** **Status**: ✅ **COMPLETE**
**Missing Functions**: `generateInsertStatement`, `generateUpdateStatement` **Missing Functions**: `generateInsertStatement`, `generateUpdateStatement`
#### **Tasks**: #### **Tasks**
- [x] **Step 2.1**: Add `_generateInsertStatement()` private method to PlatformServiceMixin ✅ - [x] **Step 2.1**: Add `_generateInsertStatement()` private method to PlatformServiceMixin ✅
- [x] **Step 2.2**: Add `_generateUpdateStatement()` 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.3**: Add `$generateInsertStatement()` public wrapper method ✅
- [x] **Step 2.4**: Add `$generateUpdateStatement()` public wrapper method ✅ - [x] **Step 2.4**: Add `$generateUpdateStatement()` public wrapper method ✅
- [x] **Step 2.5**: Test both utility functions ✅ - [x] **Step 2.5**: Test both utility functions ✅
#### **Files Modified**: #### **Files Modified**
- `src/utils/PlatformServiceMixin.ts` - `src/utils/PlatformServiceMixin.ts`
#### **Validation**: #### **Validation**
- [x] Both functions generate correct SQL ✅ - [x] Both functions generate correct SQL ✅
- [x] Parameter handling works correctly ✅ - [x] Parameter handling works correctly ✅
- [x] Type safety maintained ✅ - [x] Type safety maintained ✅
@ -69,18 +78,22 @@ This document tracks the progress of the 2-day sprint to complete PlatformServic
--- ---
### **Phase 3: Update Type Definitions (COMPLETE)** ### **Phase 3: Update Type Definitions (COMPLETE)**
**Status**: ✅ **COMPLETE** **Status**: ✅ **COMPLETE**
**Goal**: Add new methods to TypeScript interfaces **Goal**: Add new methods to TypeScript interfaces
#### **Tasks**: #### **Tasks**
- [x] **Step 3.1**: Add new methods to `IPlatformServiceMixin` interface ✅ - [x] **Step 3.1**: Add new methods to `IPlatformServiceMixin` interface ✅
- [x] **Step 3.2**: Add new methods to `ComponentCustomProperties` interface ✅ - [x] **Step 3.2**: Add new methods to `ComponentCustomProperties` interface ✅
- [x] **Step 3.3**: Verify TypeScript compilation ✅ - [x] **Step 3.3**: Verify TypeScript compilation ✅
#### **Files Modified**: #### **Files Modified**
- `src/utils/PlatformServiceMixin.ts` (interface definitions) ✅ - `src/utils/PlatformServiceMixin.ts` (interface definitions) ✅
#### **Validation**: #### **Validation**
- [x] TypeScript compilation passes ✅ - [x] TypeScript compilation passes ✅
- [x] All new methods properly typed ✅ - [x] All new methods properly typed ✅
- [x] No type errors in existing code ✅ - [x] No type errors in existing code ✅
@ -88,17 +101,20 @@ This document tracks the progress of the 2-day sprint to complete PlatformServic
--- ---
### **Phase 4: Testing & Validation (COMPLETE)** ### **Phase 4: Testing & Validation (COMPLETE)**
**Status**: ✅ **COMPLETE** **Status**: ✅ **COMPLETE**
**Goal**: Ensure PlatformServiceMixin is fully functional **Goal**: Ensure PlatformServiceMixin is fully functional
#### **Tasks**: #### **Tasks**
- [x] **Step 4.1**: Create test component to verify all methods ✅ - [x] **Step 4.1**: Create test component to verify all methods ✅
- [x] **Step 4.2**: Run comprehensive linting ✅ - [x] **Step 4.2**: Run comprehensive linting ✅
- [x] **Step 4.3**: Run TypeScript type checking ✅ - [x] **Step 4.3**: Run TypeScript type checking ✅
- [x] **Step 4.4**: Test caching functionality ✅ - [x] **Step 4.4**: Test caching functionality ✅
- [x] **Step 4.5**: Test database operations ✅ - [x] **Step 4.5**: Test database operations ✅
#### **Validation**: #### **Validation**
- [x] All tests pass ✅ - [x] All tests pass ✅
- [x] No linting errors ✅ - [x] No linting errors ✅
- [x] No TypeScript errors ✅ - [x] No TypeScript errors ✅
@ -108,10 +124,12 @@ This document tracks the progress of the 2-day sprint to complete PlatformServic
--- ---
### **Phase 5: Utility Files Migration (COMPLETE)** ### **Phase 5: Utility Files Migration (COMPLETE)**
**Status**: ✅ **COMPLETE** **Status**: ✅ **COMPLETE**
**Goal**: Remove all remaining databaseUtil imports from utility files **Goal**: Remove all remaining databaseUtil imports from utility files
#### **Tasks**: #### **Tasks**
- [x] **Step 5.1**: Migrate `src/services/deepLinks.ts` - [x] **Step 5.1**: Migrate `src/services/deepLinks.ts`
- Replaced `logConsoleAndDb` with `console.error` - Replaced `logConsoleAndDb` with `console.error`
- Removed databaseUtil import - Removed databaseUtil import
@ -121,7 +139,8 @@ This document tracks the progress of the 2-day sprint to complete PlatformServic
- Updated all async calls to use proper async pattern - Updated all async calls to use proper async pattern
- [x] **Step 5.3**: Verify no remaining databaseUtil imports ✅ - [x] **Step 5.3**: Verify no remaining databaseUtil imports ✅
#### **Validation**: #### **Validation**
- [x] No databaseUtil imports in any TypeScript files ✅ - [x] No databaseUtil imports in any TypeScript files ✅
- [x] No databaseUtil imports in any Vue files ✅ - [x] No databaseUtil imports in any Vue files ✅
- [x] All functions work correctly ✅ - [x] All functions work correctly ✅
@ -131,13 +150,16 @@ This document tracks the progress of the 2-day sprint to complete PlatformServic
## 🎯 **DAY 2: Migrate All 52 Files (READY TO START)** ## 🎯 **DAY 2: Migrate All 52 Files (READY TO START)**
### **Migration Strategy** ### **Migration Strategy**
**Priority Order**: **Priority Order**:
1. **Views** (25 files) - User-facing components 1. **Views** (25 files) - User-facing components
2. **Components** (15 files) - Reusable UI components 2. **Components** (15 files) - Reusable UI components
3. **Services** (8 files) - Business logic 3. **Services** (8 files) - Business logic
4. **Utils** (4 files) - Utility functions 4. **Utils** (4 files) - Utility functions
### **Migration Pattern for Each File** ### **Migration Pattern for Each File**
```typescript ```typescript
// 1. Add PlatformServiceMixin // 1. Add PlatformServiceMixin
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin"; import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
@ -155,6 +177,7 @@ export default class ComponentName extends Vue {
``` ```
### **Common Replacements** ### **Common Replacements**
- `generateInsertStatement``this.$generateInsertStatement` - `generateInsertStatement``this.$generateInsertStatement`
- `generateUpdateStatement``this.$generateUpdateStatement` - `generateUpdateStatement``this.$generateUpdateStatement`
- `parseJsonField``this._parseJsonField` - `parseJsonField``this._parseJsonField`
@ -168,6 +191,7 @@ export default class ComponentName extends Vue {
## 📋 **File Migration Checklist** ## 📋 **File Migration Checklist**
### **Views (25 files) - Priority 1** ### **Views (25 files) - Priority 1**
**Progress**: 6/25 (24%) **Progress**: 6/25 (24%)
- [ ] QuickActionBvcEndView.vue - [ ] QuickActionBvcEndView.vue
@ -209,6 +233,7 @@ export default class ComponentName extends Vue {
- [ ] UserProfileView.vue - [ ] UserProfileView.vue
### **Components (15 files) - Priority 2** ### **Components (15 files) - Priority 2**
**Progress**: 9/15 (60%) **Progress**: 9/15 (60%)
- [x] UserNameDialog.vue ✅ **MIGRATED** - [x] UserNameDialog.vue ✅ **MIGRATED**
@ -233,6 +258,7 @@ export default class ComponentName extends Vue {
- [x] IconRenderer.vue ✅ MIGRATED & HUMAN TESTED 2024-12-19 (0 min, no migration needed - already compliant) - [x] IconRenderer.vue ✅ MIGRATED & HUMAN TESTED 2024-12-19 (0 min, no migration needed - already compliant)
### **Services (8 files) - Priority 3** ### **Services (8 files) - Priority 3**
**Progress**: 2/8 (25%) **Progress**: 2/8 (25%)
- [x] api.ts ✅ MIGRATED 2024-12-19 (0 min, no migration needed - already compliant) - [x] api.ts ✅ MIGRATED 2024-12-19 (0 min, no migration needed - already compliant)
@ -241,6 +267,7 @@ export default class ComponentName extends Vue {
- [ ] deepLinks.ts - [ ] deepLinks.ts
### **Utils (4 files) - Priority 4** ### **Utils (4 files) - Priority 4**
**Progress**: 1/4 (25%) **Progress**: 1/4 (25%)
- [ ] LogCollector.ts - [ ] LogCollector.ts
@ -253,6 +280,7 @@ export default class ComponentName extends Vue {
## 🛠️ **Migration Tools** ## 🛠️ **Migration Tools**
### **Migration Helper Script** ### **Migration Helper Script**
```bash ```bash
# Track progress # Track progress
./scripts/migration-helper.sh progress ./scripts/migration-helper.sh progress
@ -277,6 +305,7 @@ export default class ComponentName extends Vue {
``` ```
### **Validation Commands** ### **Validation Commands**
```bash ```bash
# Check for remaining databaseUtil imports # Check for remaining databaseUtil imports
find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil"
@ -296,12 +325,14 @@ find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" |
## 📊 **Progress Tracking** ## 📊 **Progress Tracking**
### **Day 1 Progress** ### **Day 1 Progress**
- [ ] Phase 1: Circular dependency resolved - [ ] Phase 1: Circular dependency resolved
- [ ] Phase 2: Utility functions added - [ ] Phase 2: Utility functions added
- [ ] Phase 3: Type definitions updated - [ ] Phase 3: Type definitions updated
- [ ] Phase 4: Testing completed - [ ] Phase 4: Testing completed
### **Day 2 Progress** ### **Day 2 Progress**
- [ ] Views migrated (0/25) - [ ] Views migrated (0/25)
- [ ] Components migrated (0/15) - [ ] Components migrated (0/15)
- [ ] Services migrated (0/8) - [ ] Services migrated (0/8)
@ -309,6 +340,7 @@ find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" |
- [ ] Validation completed - [ ] Validation completed
### **Overall Progress** ### **Overall Progress**
- **Total files to migrate**: 52 - **Total files to migrate**: 52
- **Files migrated**: 3 - **Files migrated**: 3
- **Progress**: 6% - **Progress**: 6%
@ -318,6 +350,7 @@ find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" |
## 🎯 **Success Criteria** ## 🎯 **Success Criteria**
### **Day 1 Success Criteria** ### **Day 1 Success Criteria**
- [ ] PlatformServiceMixin has no circular dependencies - [ ] PlatformServiceMixin has no circular dependencies
- [ ] All utility functions implemented and tested - [ ] All utility functions implemented and tested
- [ ] Type definitions complete and accurate - [ ] Type definitions complete and accurate
@ -325,6 +358,7 @@ find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" |
- [ ] TypeScript compilation passes - [ ] TypeScript compilation passes
### **Day 2 Success Criteria** ### **Day 2 Success Criteria**
- [ ] 0 files importing databaseUtil - [ ] 0 files importing databaseUtil
- [ ] All 52 files migrated to PlatformServiceMixin - [ ] All 52 files migrated to PlatformServiceMixin
- [ ] No runtime errors in migrated components - [ ] No runtime errors in migrated components
@ -332,6 +366,7 @@ find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" |
- [ ] Performance maintained or improved - [ ] Performance maintained or improved
### **Overall Success Criteria** ### **Overall Success Criteria**
- [ ] Complete elimination of databaseUtil dependency - [ ] Complete elimination of databaseUtil dependency
- [ ] PlatformServiceMixin is the single source of truth for database operations - [ ] PlatformServiceMixin is the single source of truth for database operations
- [ ] Migration fence is fully implemented - [ ] Migration fence is fully implemented
@ -354,14 +389,17 @@ find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" |
## 📝 **Notes & Issues** ## 📝 **Notes & Issues**
### **Current Issues** ### **Current Issues**
- None identified yet - None identified yet
### **Decisions Made** ### **Decisions Made**
- PlatformServiceMixin approach chosen over USE_DEXIE_DB constant - PlatformServiceMixin approach chosen over USE_DEXIE_DB constant
- Self-contained utility functions preferred over imports - Self-contained utility functions preferred over imports
- Priority order: Views → Components → Services → Utils - Priority order: Views → Components → Services → Utils
### **Lessons Learned** ### **Lessons Learned**
- To be filled as migration progresses - To be filled as migration progresses
--- ---
@ -369,6 +407,7 @@ find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" |
## 🔄 **Daily Updates** ## 🔄 **Daily Updates**
### **Day 1 Updates** ### **Day 1 Updates**
- [ ] Start time: _____ - [ ] Start time: _____
- [ ] Phase 1 completion: _____ - [ ] Phase 1 completion: _____
- [ ] Phase 2 completion: _____ - [ ] Phase 2 completion: _____
@ -377,6 +416,7 @@ find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" |
- [ ] End time: _____ - [ ] End time: _____
### **Day 2 Updates** ### **Day 2 Updates**
- [ ] Start time: _____ - [ ] Start time: _____
- [ ] Views migration completion: _____ - [ ] Views migration completion: _____
- [ ] Components migration completion: _____ - [ ] Components migration completion: _____
@ -390,16 +430,19 @@ find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" |
## 🆘 **Contingency Plans** ## 🆘 **Contingency Plans**
### **If Day 1 Takes Longer** ### **If Day 1 Takes Longer**
- Focus on core functionality first - Focus on core functionality first
- Defer advanced utility functions to Day 2 - Defer advanced utility functions to Day 2
- Prioritize circular dependency resolution - Prioritize circular dependency resolution
### **If Day 2 Takes Longer** ### **If Day 2 Takes Longer**
- Focus on high-impact views first - Focus on high-impact views first
- Batch similar components together - Batch similar components together
- Use automated scripts for common patterns - Use automated scripts for common patterns
### **If Issues Arise** ### **If Issues Arise**
- Document specific problems in Notes section - Document specific problems in Notes section
- Create targeted fixes - Create targeted fixes
- Maintain backward compatibility during transition - Maintain backward compatibility during transition

1
doc/migration-quick-reference.md

@ -63,6 +63,7 @@ export default class ComponentName extends Vue {
## ✅ **Validation Checklist** ## ✅ **Validation Checklist**
After each file migration: After each file migration:
- [ ] No databaseUtil imports - [ ] No databaseUtil imports
- [ ] PlatformServiceMixin added - [ ] PlatformServiceMixin added
- [ ] Method calls updated - [ ] Method calls updated

31
doc/migration-readiness-summary.md

@ -11,11 +11,14 @@
## 🎯 **Migration Overview** ## 🎯 **Migration Overview**
### **Goal** ### **Goal**
Complete the TimeSafari database migration from Dexie to SQLite by: Complete the TimeSafari database migration from Dexie to SQLite by:
1. **Day 1**: Finish PlatformServiceMixin implementation (4-6 hours) 1. **Day 1**: Finish PlatformServiceMixin implementation (4-6 hours)
2. **Day 2**: Migrate all 52 files to PlatformServiceMixin (6-8 hours) 2. **Day 2**: Migrate all 52 files to PlatformServiceMixin (6-8 hours)
### **Current Status** ### **Current Status**
- ✅ **PlatformServiceMixin**: 95% complete (1,301 lines) - ✅ **PlatformServiceMixin**: 95% complete (1,301 lines)
- ✅ **Migration Tools**: Ready and tested - ✅ **Migration Tools**: Ready and tested
- ✅ **Documentation**: Complete and cross-machine accessible - ✅ **Documentation**: Complete and cross-machine accessible
@ -27,22 +30,30 @@ Complete the TimeSafari database migration from Dexie to SQLite by:
## 📊 **File Breakdown** ## 📊 **File Breakdown**
### **Views (42 files) - Priority 1** ### **Views (42 files) - Priority 1**
User-facing components that need immediate attention: User-facing components that need immediate attention:
- 25 files from original list - 25 files from original list
- 17 additional files identified by migration helper - 17 additional files identified by migration helper
### **Components (9 files) - Priority 2** ### **Components (9 files) - Priority 2**
Reusable UI components: Reusable UI components:
- FeedFilters.vue, GiftedDialog.vue, GiftedPrompts.vue - FeedFilters.vue, GiftedDialog.vue, GiftedPrompts.vue
- ImageMethodDialog.vue, OfferDialog.vue, OnboardingDialog.vue - ImageMethodDialog.vue, OfferDialog.vue, OnboardingDialog.vue
- PhotoDialog.vue, PushNotificationPermission.vue, UserNameDialog.vue - PhotoDialog.vue, PushNotificationPermission.vue, UserNameDialog.vue
### **Services (1 file) - Priority 3** ### **Services (1 file) - Priority 3**
Business logic: Business logic:
- deepLinks.ts - deepLinks.ts
### **Utils (3 files) - Priority 4** ### **Utils (3 files) - Priority 4**
Utility functions: Utility functions:
- util.ts, test/index.ts, PlatformServiceMixin.ts (circular dependency fix) - util.ts, test/index.ts, PlatformServiceMixin.ts (circular dependency fix)
--- ---
@ -50,17 +61,21 @@ Utility functions:
## 🛠️ **Available Tools** ## 🛠️ **Available Tools**
### **Migration Helper Script** ### **Migration Helper Script**
```bash ```bash
./scripts/migration-helper.sh [command] ./scripts/migration-helper.sh [command]
``` ```
**Commands**: progress, files, patterns, template, validate, next, all **Commands**: progress, files, patterns, template, validate, next, all
### **Progress Tracking** ### **Progress Tracking**
- **Main Tracker**: `doc/migration-progress-tracker.md` - **Main Tracker**: `doc/migration-progress-tracker.md`
- **Quick Reference**: `doc/migration-quick-reference.md` - **Quick Reference**: `doc/migration-quick-reference.md`
- **Completion Plan**: `doc/platformservicemixin-completion-plan.md` - **Completion Plan**: `doc/platformservicemixin-completion-plan.md`
### **Validation Commands** ### **Validation Commands**
```bash ```bash
# Check progress # Check progress
./scripts/migration-helper.sh progress ./scripts/migration-helper.sh progress
@ -77,6 +92,7 @@ find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" |
## 🔄 **Migration Pattern** ## 🔄 **Migration Pattern**
### **Standard Template** ### **Standard Template**
```typescript ```typescript
// 1. Add import // 1. Add import
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin"; import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
@ -94,6 +110,7 @@ export default class ComponentName extends Vue {
``` ```
### **Common Replacements** ### **Common Replacements**
| Old | New | | Old | New |
|-----|-----| |-----|-----|
| `generateInsertStatement` | `this.$generateInsertStatement` | | `generateInsertStatement` | `this.$generateInsertStatement` |
@ -109,19 +126,23 @@ export default class ComponentName extends Vue {
## 🎯 **Day 1 Plan: PlatformServiceMixin Completion** ## 🎯 **Day 1 Plan: PlatformServiceMixin Completion**
### **Phase 1: Remove Circular Dependency (30 min)** ### **Phase 1: Remove Circular Dependency (30 min)**
- Remove `memoryLogs` import from PlatformServiceMixin - Remove `memoryLogs` import from PlatformServiceMixin
- Add self-contained memoryLogs implementation - Add self-contained memoryLogs implementation
- Update logger.ts - Update logger.ts
### **Phase 2: Add Missing Functions (1 hour)** ### **Phase 2: Add Missing Functions (1 hour)**
- Add `generateInsertStatement` and `generateUpdateStatement` - Add `generateInsertStatement` and `generateUpdateStatement`
- Test both utility functions - Test both utility functions
### **Phase 3: Update Types (30 min)** ### **Phase 3: Update Types (30 min)**
- Add new methods to TypeScript interfaces - Add new methods to TypeScript interfaces
- Verify compilation - Verify compilation
### **Phase 4: Testing (1 hour)** ### **Phase 4: Testing (1 hour)**
- Comprehensive testing and validation - Comprehensive testing and validation
- Ensure no circular dependencies - Ensure no circular dependencies
@ -130,17 +151,20 @@ export default class ComponentName extends Vue {
## 🎯 **Day 2 Plan: File Migration** ## 🎯 **Day 2 Plan: File Migration**
### **Strategy** ### **Strategy**
1. **Views First** (42 files) - High impact, user-facing 1. **Views First** (42 files) - High impact, user-facing
2. **Components** (9 files) - Reusable UI elements 2. **Components** (9 files) - Reusable UI elements
3. **Services** (1 file) - Business logic 3. **Services** (1 file) - Business logic
4. **Utils** (3 files) - Utility functions 4. **Utils** (3 files) - Utility functions
### **Batch Processing** ### **Batch Processing**
- Process similar files together - Process similar files together
- Use automated scripts for common patterns - Use automated scripts for common patterns
- Validate after each batch - Validate after each batch
### **Success Criteria** ### **Success Criteria**
- 0 files importing databaseUtil - 0 files importing databaseUtil
- All tests passing - All tests passing
- No runtime errors - No runtime errors
@ -151,12 +175,14 @@ export default class ComponentName extends Vue {
## 🚀 **Expected Benefits** ## 🚀 **Expected Benefits**
### **Immediate Benefits** ### **Immediate Benefits**
- **80% reduction** in database boilerplate code - **80% reduction** in database boilerplate code
- **Eliminated circular dependencies** - **Eliminated circular dependencies**
- **Centralized caching** for performance - **Centralized caching** for performance
- **Type-safe** database operations - **Type-safe** database operations
### **Long-term Benefits** ### **Long-term Benefits**
- **Simplified testing** with mockable mixin - **Simplified testing** with mockable mixin
- **Consistent error handling** across components - **Consistent error handling** across components
- **Ready for SQLite-only mode** - **Ready for SQLite-only mode**
@ -167,18 +193,21 @@ export default class ComponentName extends Vue {
## 📋 **Pre-Migration Checklist** ## 📋 **Pre-Migration Checklist**
### **Environment Ready** ### **Environment Ready**
- [x] Migration helper script tested and working - [x] Migration helper script tested and working
- [x] Progress tracking system operational - [x] Progress tracking system operational
- [x] Documentation complete and accessible - [x] Documentation complete and accessible
- [x] Validation commands working - [x] Validation commands working
### **Tools Available** ### **Tools Available**
- [x] Automated progress tracking - [x] Automated progress tracking
- [x] Migration pattern templates - [x] Migration pattern templates
- [x] Validation scripts - [x] Validation scripts
- [x] Cross-machine documentation - [x] Cross-machine documentation
### **Knowledge Base** ### **Knowledge Base**
- [x] Common replacement patterns documented - [x] Common replacement patterns documented
- [x] Migration templates ready - [x] Migration templates ready
- [x] Troubleshooting guides available - [x] Troubleshooting guides available
@ -191,12 +220,14 @@ export default class ComponentName extends Vue {
**All systems are ready for the 2-day migration sprint.** **All systems are ready for the 2-day migration sprint.**
### **Next Steps** ### **Next Steps**
1. **Start Day 1**: Complete PlatformServiceMixin 1. **Start Day 1**: Complete PlatformServiceMixin
2. **Use tracking tools**: Monitor progress with helper script 2. **Use tracking tools**: Monitor progress with helper script
3. **Follow documentation**: Use provided templates and patterns 3. **Follow documentation**: Use provided templates and patterns
4. **Validate frequently**: Run checks after each phase 4. **Validate frequently**: Run checks after each phase
### **Success Metrics** ### **Success Metrics**
- **Day 1**: PlatformServiceMixin 100% complete, no circular dependencies - **Day 1**: PlatformServiceMixin 100% complete, no circular dependencies
- **Day 2**: 0 files importing databaseUtil, all tests passing - **Day 2**: 0 files importing databaseUtil, all tests passing
- **Overall**: Ready for Phase 3 cleanup and optimization - **Overall**: Ready for Phase 3 cleanup and optimization

31
doc/migration-roadmap-next-steps.md

@ -7,6 +7,7 @@ This document outlines the immediate next steps for completing the TimeSafari da
## Current Status Summary ## Current Status Summary
### ✅ **Completed Achievements** ### ✅ **Completed Achievements**
1. **Circular Dependencies Resolved** - No active circular dependencies blocking development 1. **Circular Dependencies Resolved** - No active circular dependencies blocking development
2. **PlatformServiceMixin Implemented** - Core functionality with caching and utilities 2. **PlatformServiceMixin Implemented** - Core functionality with caching and utilities
3. **Migration Tools Ready** - Data comparison and transfer utilities functional 3. **Migration Tools Ready** - Data comparison and transfer utilities functional
@ -14,6 +15,7 @@ This document outlines the immediate next steps for completing the TimeSafari da
5. **Documentation Updated** - All docs reflect current PlatformServiceMixin approach 5. **Documentation Updated** - All docs reflect current PlatformServiceMixin approach
### 🔄 **Current Phase: Phase 2 - Active Migration** ### 🔄 **Current Phase: Phase 2 - Active Migration**
- **DatabaseUtil Migration**: 52 files still importing databaseUtil - **DatabaseUtil Migration**: 52 files still importing databaseUtil
- **Contact Migration**: Framework ready, implementation in progress - **Contact Migration**: Framework ready, implementation in progress
- **File-by-File Migration**: Ready to begin systematic migration - **File-by-File Migration**: Ready to begin systematic migration
@ -23,6 +25,7 @@ This document outlines the immediate next steps for completing the TimeSafari da
### 🔴 **Priority 1: Complete PlatformServiceMixin Independence** ### 🔴 **Priority 1: Complete PlatformServiceMixin Independence**
#### **Step 1.1: Remove memoryLogs Dependency** #### **Step 1.1: Remove memoryLogs Dependency**
```typescript ```typescript
// Current: PlatformServiceMixin imports from databaseUtil // Current: PlatformServiceMixin imports from databaseUtil
import { memoryLogs } from "@/db/databaseUtil"; import { memoryLogs } from "@/db/databaseUtil";
@ -32,12 +35,15 @@ const memoryLogs: string[] = [];
``` ```
**Files to modify**: **Files to modify**:
- `src/utils/PlatformServiceMixin.ts` - Remove import, add self-contained implementation - `src/utils/PlatformServiceMixin.ts` - Remove import, add self-contained implementation
**Estimated time**: 30 minutes **Estimated time**: 30 minutes
#### **Step 1.2: Add Missing Utility Methods** #### **Step 1.2: Add Missing Utility Methods**
Add these methods to PlatformServiceMixin: Add these methods to PlatformServiceMixin:
- `$parseJson()` - Self-contained JSON parsing - `$parseJson()` - Self-contained JSON parsing
- `$generateInsertStatement()` - SQL generation - `$generateInsertStatement()` - SQL generation
- `$generateUpdateStatement()` - SQL generation - `$generateUpdateStatement()` - SQL generation
@ -48,6 +54,7 @@ Add these methods to PlatformServiceMixin:
### 🟡 **Priority 2: Start File-by-File Migration** ### 🟡 **Priority 2: Start File-by-File Migration**
#### **Step 2.1: Migrate Critical Files First** #### **Step 2.1: Migrate Critical Files First**
Based on the migration plan, start with these high-priority files: Based on the migration plan, start with these high-priority files:
1. **`src/App.vue`** - Main application (highest impact) 1. **`src/App.vue`** - Main application (highest impact)
@ -57,6 +64,7 @@ Based on the migration plan, start with these high-priority files:
5. **`src/services/deepLinks.ts`** - Service layer 5. **`src/services/deepLinks.ts`** - Service layer
**Migration pattern for each file**: **Migration pattern for each file**:
```typescript ```typescript
// 1. Remove databaseUtil import // 1. Remove databaseUtil import
// Remove: import * as databaseUtil from "../db/databaseUtil"; // Remove: import * as databaseUtil from "../db/databaseUtil";
@ -82,7 +90,9 @@ Based on the migration plan, start with these high-priority files:
### 🟡 **Priority 3: Systematic File Migration** ### 🟡 **Priority 3: Systematic File Migration**
#### **Step 3.1: Migrate High-Usage Components (15 files)** #### **Step 3.1: Migrate High-Usage Components (15 files)**
Target components with databaseUtil imports: Target components with databaseUtil imports:
- `PhotoDialog.vue` - `PhotoDialog.vue`
- `FeedFilters.vue` - `FeedFilters.vue`
- `UserNameDialog.vue` - `UserNameDialog.vue`
@ -97,7 +107,9 @@ Target components with databaseUtil imports:
**Estimated time**: 15-30 hours **Estimated time**: 15-30 hours
#### **Step 3.2: Migrate High-Usage Views (20 files)** #### **Step 3.2: Migrate High-Usage Views (20 files)**
Target views with databaseUtil imports: Target views with databaseUtil imports:
- `IdentitySwitcherView.vue` - `IdentitySwitcherView.vue`
- `ContactEditView.vue` - `ContactEditView.vue`
- `ContactGiftingView.vue` - `ContactGiftingView.vue`
@ -113,6 +125,7 @@ Target views with databaseUtil imports:
**Estimated time**: 20-40 hours **Estimated time**: 20-40 hours
#### **Step 3.3: Migrate Remaining Files (27 files)** #### **Step 3.3: Migrate Remaining Files (27 files)**
Complete migration of all remaining files with databaseUtil imports. Complete migration of all remaining files with databaseUtil imports.
**Estimated time**: 27-54 hours **Estimated time**: 27-54 hours
@ -120,6 +133,7 @@ Complete migration of all remaining files with databaseUtil imports.
### 🟢 **Priority 4: Contact Migration Completion** ### 🟢 **Priority 4: Contact Migration Completion**
#### **Step 4.1: Complete Contact Migration Framework** #### **Step 4.1: Complete Contact Migration Framework**
- Implement contact import/export functionality - Implement contact import/export functionality
- Add contact validation and error handling - Add contact validation and error handling
- Test contact migration with real data - Test contact migration with real data
@ -127,6 +141,7 @@ Complete migration of all remaining files with databaseUtil imports.
**Estimated time**: 4-8 hours **Estimated time**: 4-8 hours
#### **Step 4.2: User Testing and Validation** #### **Step 4.2: User Testing and Validation**
- Test migration with various data scenarios - Test migration with various data scenarios
- Validate data integrity after migration - Validate data integrity after migration
- Performance testing with large datasets - Performance testing with large datasets
@ -138,7 +153,9 @@ Complete migration of all remaining files with databaseUtil imports.
### 🔵 **Priority 5: Cleanup and Optimization** ### 🔵 **Priority 5: Cleanup and Optimization**
#### **Step 5.1: Remove Unused databaseUtil Functions** #### **Step 5.1: Remove Unused databaseUtil Functions**
After all files are migrated: After all files are migrated:
- Remove unused functions from databaseUtil.ts - Remove unused functions from databaseUtil.ts
- Update TypeScript interfaces - Update TypeScript interfaces
- Clean up legacy code - Clean up legacy code
@ -146,6 +163,7 @@ After all files are migrated:
**Estimated time**: 4-8 hours **Estimated time**: 4-8 hours
#### **Step 5.2: Performance Optimization** #### **Step 5.2: Performance Optimization**
- Optimize PlatformServiceMixin caching - Optimize PlatformServiceMixin caching
- Add performance monitoring - Add performance monitoring
- Implement database query optimization - Implement database query optimization
@ -153,6 +171,7 @@ After all files are migrated:
**Estimated time**: 8-16 hours **Estimated time**: 8-16 hours
#### **Step 5.3: Legacy Dexie Removal** #### **Step 5.3: Legacy Dexie Removal**
- Remove Dexie dependencies - Remove Dexie dependencies
- Clean up migration tools - Clean up migration tools
- Update build configurations - Update build configurations
@ -162,6 +181,7 @@ After all files are migrated:
## Migration Commands and Tools ## Migration Commands and Tools
### **Automated Migration Script** ### **Automated Migration Script**
Create a script to help with bulk migrations: Create a script to help with bulk migrations:
```bash ```bash
@ -193,6 +213,7 @@ echo "Please review and test the changes"
``` ```
### **Migration Testing Commands** ### **Migration Testing Commands**
```bash ```bash
# Test individual file migration # Test individual file migration
npm run test -- --grep "ComponentName" npm run test -- --grep "ComponentName"
@ -213,18 +234,21 @@ npx tsc --noEmit
## Risk Mitigation ## Risk Mitigation
### **Incremental Migration Strategy** ### **Incremental Migration Strategy**
1. **One file at a time** - Minimize risk of breaking changes 1. **One file at a time** - Minimize risk of breaking changes
2. **Comprehensive testing** - Test each migration thoroughly 2. **Comprehensive testing** - Test each migration thoroughly
3. **Rollback capability** - Keep databaseUtil.ts until migration complete 3. **Rollback capability** - Keep databaseUtil.ts until migration complete
4. **Documentation updates** - Update docs as methods are migrated 4. **Documentation updates** - Update docs as methods are migrated
### **Testing Strategy** ### **Testing Strategy**
1. **Unit tests** - Test individual component functionality 1. **Unit tests** - Test individual component functionality
2. **Integration tests** - Test database operations 2. **Integration tests** - Test database operations
3. **End-to-end tests** - Test complete user workflows 3. **End-to-end tests** - Test complete user workflows
4. **Performance tests** - Ensure no performance regression 4. **Performance tests** - Ensure no performance regression
### **Rollback Plan** ### **Rollback Plan**
1. **Git branches** - Each migration in separate branch 1. **Git branches** - Each migration in separate branch
2. **Backup files** - Keep original files until migration verified 2. **Backup files** - Keep original files until migration verified
3. **Feature flags** - Ability to switch back to databaseUtil if needed 3. **Feature flags** - Ability to switch back to databaseUtil if needed
@ -233,18 +257,21 @@ npx tsc --noEmit
## Success Metrics ## Success Metrics
### **Short-Term (This Week)** ### **Short-Term (This Week)**
- [ ] PlatformServiceMixin completely independent - [ ] PlatformServiceMixin completely independent
- [ ] 5 critical files migrated - [ ] 5 critical files migrated
- [ ] No new circular dependencies - [ ] No new circular dependencies
- [ ] All tests passing - [ ] All tests passing
### **Medium-Term (Next 2 Weeks)** ### **Medium-Term (Next 2 Weeks)**
- [ ] 35+ files migrated (70% completion) - [ ] 35+ files migrated (70% completion)
- [ ] Contact migration framework complete - [ ] Contact migration framework complete
- [ ] Performance maintained or improved - [ ] Performance maintained or improved
- [ ] User testing completed - [ ] User testing completed
### **Long-Term (Next Month)** ### **Long-Term (Next Month)**
- [ ] All 52 files migrated (100% completion) - [ ] All 52 files migrated (100% completion)
- [ ] databaseUtil.ts removed or minimal - [ ] databaseUtil.ts removed or minimal
- [ ] Legacy Dexie code removed - [ ] Legacy Dexie code removed
@ -253,12 +280,14 @@ npx tsc --noEmit
## Resource Requirements ## Resource Requirements
### **Development Time** ### **Development Time**
- **Immediate (This Week)**: 8-12 hours - **Immediate (This Week)**: 8-12 hours
- **Medium-Term (Next 2 Weeks)**: 35-70 hours - **Medium-Term (Next 2 Weeks)**: 35-70 hours
- **Long-Term (Next Month)**: 16-32 hours - **Long-Term (Next Month)**: 16-32 hours
- **Total Estimated**: 59-114 hours - **Total Estimated**: 59-114 hours
### **Testing Time** ### **Testing Time**
- **Unit Testing**: 20-30 hours - **Unit Testing**: 20-30 hours
- **Integration Testing**: 10-15 hours - **Integration Testing**: 10-15 hours
- **User Testing**: 8-12 hours - **User Testing**: 8-12 hours
@ -266,6 +295,7 @@ npx tsc --noEmit
- **Total Testing**: 43-65 hours - **Total Testing**: 43-65 hours
### **Total Project Time** ### **Total Project Time**
- **Development**: 59-114 hours - **Development**: 59-114 hours
- **Testing**: 43-65 hours - **Testing**: 43-65 hours
- **Documentation**: 5-10 hours - **Documentation**: 5-10 hours
@ -274,6 +304,7 @@ npx tsc --noEmit
## Conclusion ## Conclusion
The migration is well-positioned for completion with: The migration is well-positioned for completion with:
- ✅ **No blocking circular dependencies** - ✅ **No blocking circular dependencies**
- ✅ **PlatformServiceMixin mostly complete** - ✅ **PlatformServiceMixin mostly complete**
- ✅ **Clear migration path defined** - ✅ **Clear migration path defined**

29
doc/migration-to-wa-sqlite.md

@ -29,12 +29,15 @@ This document outlines the migration process from Dexie.js to absurd-sql for the
## Migration Architecture ## Migration Architecture
### Migration Fence ### Migration Fence
The migration fence is now defined by the **PlatformServiceMixin** in `src/utils/PlatformServiceMixin.ts`: The migration fence is now defined by the **PlatformServiceMixin** in `src/utils/PlatformServiceMixin.ts`:
- **PlatformServiceMixin**: Centralized database access with caching and utilities - **PlatformServiceMixin**: Centralized database access with caching and utilities
- **Migration Tools**: Exclusive interface between legacy and new databases - **Migration Tools**: Exclusive interface between legacy and new databases
- **Service Layer**: All database operations go through PlatformService - **Service Layer**: All database operations go through PlatformService
### Migration Order ### Migration Order
The migration follows a specific order to maintain data integrity: The migration follows a specific order to maintain data integrity:
1. **Accounts** (foundational - contains DIDs) 1. **Accounts** (foundational - contains DIDs)
@ -45,9 +48,11 @@ The migration follows a specific order to maintain data integrity:
## ActiveDid Migration ⭐ **NEW FEATURE** ## ActiveDid Migration ⭐ **NEW FEATURE**
### Problem Solved ### Problem Solved
Previously, the `activeDid` setting was not migrated from Dexie to SQLite, causing users to lose their active identity after migration. Previously, the `activeDid` setting was not migrated from Dexie to SQLite, causing users to lose their active identity after migration.
### Solution Implemented ### Solution Implemented
The migration now includes a dedicated step for migrating the `activeDid`: The migration now includes a dedicated step for migrating the `activeDid`:
1. **Detection**: Identifies the `activeDid` from Dexie master settings 1. **Detection**: Identifies the `activeDid` from Dexie master settings
@ -58,6 +63,7 @@ The migration now includes a dedicated step for migrating the `activeDid`:
### Implementation Details ### Implementation Details
#### New Function: `migrateActiveDid()` #### New Function: `migrateActiveDid()`
```typescript ```typescript
export async function migrateActiveDid(): Promise<MigrationResult> { export async function migrateActiveDid(): Promise<MigrationResult> {
// 1. Get Dexie settings to find the activeDid // 1. Get Dexie settings to find the activeDid
@ -76,13 +82,17 @@ export async function migrateActiveDid(): Promise<MigrationResult> {
``` ```
#### Enhanced `migrateSettings()` Function #### Enhanced `migrateSettings()` Function
The settings migration now includes activeDid handling: The settings migration now includes activeDid handling:
- Extracts `activeDid` from Dexie master settings - Extracts `activeDid` from Dexie master settings
- Validates account existence in SQLite - Validates account existence in SQLite
- Updates SQLite master settings with the `activeDid` - Updates SQLite master settings with the `activeDid`
#### Updated `migrateAll()` Function #### Updated `migrateAll()` Function
The complete migration now includes a dedicated step for activeDid: The complete migration now includes a dedicated step for activeDid:
```typescript ```typescript
// Step 3: Migrate ActiveDid (depends on accounts and settings) // Step 3: Migrate ActiveDid (depends on accounts and settings)
logger.info("[MigrationService] Step 3: Migrating activeDid..."); logger.info("[MigrationService] Step 3: Migrating activeDid...");
@ -90,6 +100,7 @@ const activeDidResult = await migrateActiveDid();
``` ```
### Benefits ### Benefits
- ✅ **User Identity Preservation**: Users maintain their active identity - ✅ **User Identity Preservation**: Users maintain their active identity
- ✅ **Seamless Experience**: No need to manually select identity after migration - ✅ **Seamless Experience**: No need to manually select identity after migration
- ✅ **Data Consistency**: Ensures all identity-related settings are preserved - ✅ **Data Consistency**: Ensures all identity-related settings are preserved
@ -98,17 +109,20 @@ const activeDidResult = await migrateActiveDid();
## Migration Process ## Migration Process
### Phase 1: Preparation ✅ ### Phase 1: Preparation ✅
- [x] PlatformServiceMixin implementation - [x] PlatformServiceMixin implementation
- [x] Implement data comparison tools - [x] Implement data comparison tools
- [x] Create migration service structure - [x] Create migration service structure
### Phase 2: Core Migration ✅ ### Phase 2: Core Migration ✅
- [x] Account migration with `importFromMnemonic` - [x] Account migration with `importFromMnemonic`
- [x] Settings migration (excluding activeDid) - [x] Settings migration (excluding activeDid)
- [x] **ActiveDid migration** ⭐ **COMPLETED** - [x] **ActiveDid migration** ⭐ **COMPLETED**
- [x] Contact migration framework - [x] Contact migration framework
### Phase 3: Validation and Cleanup 🔄 ### Phase 3: Validation and Cleanup 🔄
- [ ] Comprehensive data validation - [ ] Comprehensive data validation
- [ ] Performance testing - [ ] Performance testing
- [ ] User acceptance testing - [ ] User acceptance testing
@ -117,6 +131,7 @@ const activeDidResult = await migrateActiveDid();
## Usage ## Usage
### Manual Migration ### Manual Migration
```typescript ```typescript
import { migrateAll, migrateActiveDid } from '../services/indexedDBMigrationService'; import { migrateAll, migrateActiveDid } from '../services/indexedDBMigrationService';
@ -128,6 +143,7 @@ const activeDidResult = await migrateActiveDid();
``` ```
### Migration Verification ### Migration Verification
```typescript ```typescript
import { compareDatabases } from '../services/indexedDBMigrationService'; import { compareDatabases } from '../services/indexedDBMigrationService';
@ -136,7 +152,9 @@ console.log('Migration differences:', comparison.differences);
``` ```
### PlatformServiceMixin Integration ### PlatformServiceMixin Integration
After migration, use the mixin for all database operations: After migration, use the mixin for all database operations:
```typescript ```typescript
// Use mixin methods for database access // Use mixin methods for database access
const contacts = await this.$contacts(); const contacts = await this.$contacts();
@ -147,11 +165,13 @@ const result = await this.$db("SELECT * FROM contacts WHERE did = ?", [accountDi
## Error Handling ## Error Handling
### ActiveDid Migration Errors ### ActiveDid Migration Errors
- **Missing Account**: If the `activeDid` from Dexie doesn't exist in SQLite accounts - **Missing Account**: If the `activeDid` from Dexie doesn't exist in SQLite accounts
- **Database Errors**: Connection or query failures - **Database Errors**: Connection or query failures
- **Settings Update Failures**: Issues updating SQLite master settings - **Settings Update Failures**: Issues updating SQLite master settings
### Recovery Strategies ### Recovery Strategies
1. **Automatic Recovery**: Migration continues even if activeDid migration fails 1. **Automatic Recovery**: Migration continues even if activeDid migration fails
2. **Manual Recovery**: Users can manually select their identity after migration 2. **Manual Recovery**: Users can manually select their identity after migration
3. **Fallback**: System creates new identity if none exists 3. **Fallback**: System creates new identity if none exists
@ -159,11 +179,13 @@ const result = await this.$db("SELECT * FROM contacts WHERE did = ?", [accountDi
## Security Considerations ## Security Considerations
### Data Protection ### Data Protection
- All sensitive data (mnemonics, private keys) are encrypted - All sensitive data (mnemonics, private keys) are encrypted
- Migration preserves encryption standards - Migration preserves encryption standards
- No plaintext data exposure during migration - No plaintext data exposure during migration
### Identity Verification ### Identity Verification
- ActiveDid migration validates account existence - ActiveDid migration validates account existence
- Prevents setting non-existent identities as active - Prevents setting non-existent identities as active
- Maintains cryptographic integrity - Maintains cryptographic integrity
@ -171,6 +193,7 @@ const result = await this.$db("SELECT * FROM contacts WHERE did = ?", [accountDi
## Testing ## Testing
### Migration Testing ### Migration Testing
```bash ```bash
# Run migration # Run migration
npm run migrate npm run migrate
@ -180,6 +203,7 @@ npm run test:migration
``` ```
### ActiveDid Testing ### ActiveDid Testing
```typescript ```typescript
// Test activeDid migration specifically // Test activeDid migration specifically
const result = await migrateActiveDid(); const result = await migrateActiveDid();
@ -188,6 +212,7 @@ expect(result.warnings).toContain('Successfully migrated activeDid');
``` ```
### PlatformServiceMixin Testing ### PlatformServiceMixin Testing
```typescript ```typescript
// Test mixin integration // Test mixin integration
describe('PlatformServiceMixin', () => { describe('PlatformServiceMixin', () => {
@ -224,6 +249,7 @@ describe('PlatformServiceMixin', () => {
- Verify caching and error handling work correctly - Verify caching and error handling work correctly
### Debugging ### Debugging
```typescript ```typescript
// Debug migration process // Debug migration process
import { logger } from '../utils/logger'; import { logger } from '../utils/logger';
@ -245,6 +271,7 @@ logger.debug('[Migration] Migration completed:', result);
## Migration Status Checklist ## Migration Status Checklist
### ✅ Completed ### ✅ Completed
- [x] PlatformServiceMixin implementation - [x] PlatformServiceMixin implementation
- [x] SQLite database service - [x] SQLite database service
- [x] Migration tools - [x] Migration tools
@ -253,11 +280,13 @@ logger.debug('[Migration] Migration completed:', result);
- [x] ActiveDid migration - [x] ActiveDid migration
### 🔄 In Progress ### 🔄 In Progress
- [ ] Contact migration - [ ] Contact migration
- [ ] DatabaseUtil to PlatformServiceMixin migration - [ ] DatabaseUtil to PlatformServiceMixin migration
- [ ] File-by-file migration - [ ] File-by-file migration
### ❌ Not Started ### ❌ Not Started
- [ ] Legacy Dexie removal - [ ] Legacy Dexie removal
- [ ] Final cleanup and validation - [ ] Final cleanup and validation

29
doc/platformservicemixin-completion-plan.md

@ -7,6 +7,7 @@ This document outlines the complete plan to finish PlatformServiceMixin implemen
## Current Status ## Current Status
### ✅ **PlatformServiceMixin - 95% Complete** ### ✅ **PlatformServiceMixin - 95% Complete**
- **Core functionality**: ✅ Implemented - **Core functionality**: ✅ Implemented
- **Caching system**: ✅ Implemented - **Caching system**: ✅ Implemented
- **Database methods**: ✅ Implemented - **Database methods**: ✅ Implemented
@ -14,6 +15,7 @@ This document outlines the complete plan to finish PlatformServiceMixin implemen
- **Type definitions**: ✅ Implemented - **Type definitions**: ✅ Implemented
### ⚠️ **Remaining Issues** ### ⚠️ **Remaining Issues**
1. **Single circular dependency**: `memoryLogs` import from databaseUtil 1. **Single circular dependency**: `memoryLogs` import from databaseUtil
2. **Missing utility functions**: `generateInsertStatement`, `generateUpdateStatement` 2. **Missing utility functions**: `generateInsertStatement`, `generateUpdateStatement`
3. **52 files** still importing databaseUtil 3. **52 files** still importing databaseUtil
@ -25,6 +27,7 @@ This document outlines the complete plan to finish PlatformServiceMixin implemen
### **Phase 1: Remove Circular Dependency (30 minutes)** ### **Phase 1: Remove Circular Dependency (30 minutes)**
#### **Step 1.1: Create Self-Contained memoryLogs** #### **Step 1.1: Create Self-Contained memoryLogs**
```typescript ```typescript
// In PlatformServiceMixin.ts - Replace line 50: // In PlatformServiceMixin.ts - Replace line 50:
// Remove: import { memoryLogs } from "@/db/databaseUtil"; // Remove: import { memoryLogs } from "@/db/databaseUtil";
@ -48,6 +51,7 @@ $appendToMemoryLogs(message: string): void {
``` ```
#### **Step 1.2: Update logger.ts** #### **Step 1.2: Update logger.ts**
```typescript ```typescript
// In logger.ts - Replace memoryLogs usage: // In logger.ts - Replace memoryLogs usage:
// Remove: import { memoryLogs } from "@/db/databaseUtil"; // Remove: import { memoryLogs } from "@/db/databaseUtil";
@ -70,6 +74,7 @@ export function getMemoryLogs(): string[] {
### **Phase 2: Add Missing Utility Functions (1 hour)** ### **Phase 2: Add Missing Utility Functions (1 hour)**
#### **Step 2.1: Add generateInsertStatement to PlatformServiceMixin** #### **Step 2.1: Add generateInsertStatement to PlatformServiceMixin**
```typescript ```typescript
// Add to PlatformServiceMixin methods: // Add to PlatformServiceMixin methods:
_generateInsertStatement( _generateInsertStatement(
@ -95,6 +100,7 @@ _generateInsertStatement(
``` ```
#### **Step 2.2: Add generateUpdateStatement to PlatformServiceMixin** #### **Step 2.2: Add generateUpdateStatement to PlatformServiceMixin**
```typescript ```typescript
// Add to PlatformServiceMixin methods: // Add to PlatformServiceMixin methods:
_generateUpdateStatement( _generateUpdateStatement(
@ -129,6 +135,7 @@ _generateUpdateStatement(
``` ```
#### **Step 2.3: Add Public Wrapper Methods** #### **Step 2.3: Add Public Wrapper Methods**
```typescript ```typescript
// Add to PlatformServiceMixin methods: // Add to PlatformServiceMixin methods:
$generateInsertStatement( $generateInsertStatement(
@ -151,6 +158,7 @@ $generateUpdateStatement(
### **Phase 3: Update Type Definitions (30 minutes)** ### **Phase 3: Update Type Definitions (30 minutes)**
#### **Step 3.1: Update IPlatformServiceMixin Interface** #### **Step 3.1: Update IPlatformServiceMixin Interface**
```typescript ```typescript
// Add to IPlatformServiceMixin interface: // Add to IPlatformServiceMixin interface:
$generateInsertStatement( $generateInsertStatement(
@ -167,6 +175,7 @@ $appendToMemoryLogs(message: string): void;
``` ```
#### **Step 3.2: Update ComponentCustomProperties** #### **Step 3.2: Update ComponentCustomProperties**
```typescript ```typescript
// Add to ComponentCustomProperties interface: // Add to ComponentCustomProperties interface:
$generateInsertStatement( $generateInsertStatement(
@ -185,12 +194,14 @@ $appendToMemoryLogs(message: string): void;
### **Phase 4: Test PlatformServiceMixin (1 hour)** ### **Phase 4: Test PlatformServiceMixin (1 hour)**
#### **Step 4.1: Create Test Component** #### **Step 4.1: Create Test Component**
```typescript ```typescript
// Create test file: src/test/PlatformServiceMixin.test.ts // Create test file: src/test/PlatformServiceMixin.test.ts
// Test all methods including new utility functions // Test all methods including new utility functions
``` ```
#### **Step 4.2: Run Linting and Type Checking** #### **Step 4.2: Run Linting and Type Checking**
```bash ```bash
npm run lint npm run lint
npx tsc --noEmit npx tsc --noEmit
@ -203,6 +214,7 @@ npx tsc --noEmit
### **Migration Strategy** ### **Migration Strategy**
#### **Priority Order:** #### **Priority Order:**
1. **Views** (25 files) - User-facing components 1. **Views** (25 files) - User-facing components
2. **Components** (15 files) - Reusable UI components 2. **Components** (15 files) - Reusable UI components
3. **Services** (8 files) - Business logic 3. **Services** (8 files) - Business logic
@ -211,6 +223,7 @@ npx tsc --noEmit
#### **Migration Pattern for Each File:** #### **Migration Pattern for Each File:**
**Step 1: Add PlatformServiceMixin** **Step 1: Add PlatformServiceMixin**
```typescript ```typescript
// Add to component imports: // Add to component imports:
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin"; import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
@ -223,6 +236,7 @@ export default class ComponentName extends Vue {
``` ```
**Step 2: Replace databaseUtil Imports** **Step 2: Replace databaseUtil Imports**
```typescript ```typescript
// Remove: // Remove:
import { import {
@ -244,6 +258,7 @@ import {
``` ```
**Step 3: Update Method Calls** **Step 3: Update Method Calls**
```typescript ```typescript
// Before: // Before:
const { sql, params } = generateInsertStatement(contact, 'contacts'); const { sql, params } = generateInsertStatement(contact, 'contacts');
@ -255,6 +270,7 @@ const { sql, params } = this.$generateInsertStatement(contact, 'contacts');
### **File Migration Checklist** ### **File Migration Checklist**
#### **Views (25 files) - Priority 1** #### **Views (25 files) - Priority 1**
- [ ] QuickActionBvcEndView.vue - [ ] QuickActionBvcEndView.vue
- [ ] ProjectsView.vue - [ ] ProjectsView.vue
- [ ] ClaimReportCertificateView.vue - [ ] ClaimReportCertificateView.vue
@ -278,6 +294,7 @@ const { sql, params } = this.$generateInsertStatement(contact, 'contacts');
- [ ] [5 more view files] - [ ] [5 more view files]
#### **Components (15 files) - Priority 2** #### **Components (15 files) - Priority 2**
- [ ] ActivityListItem.vue - [ ] ActivityListItem.vue
- [ ] AmountInput.vue - [ ] AmountInput.vue
- [ ] ChoiceButtonDialog.vue - [ ] ChoiceButtonDialog.vue
@ -295,18 +312,21 @@ const { sql, params } = this.$generateInsertStatement(contact, 'contacts');
- [ ] IconRenderer.vue - [ ] IconRenderer.vue
#### **Services (8 files) - Priority 3** #### **Services (8 files) - Priority 3**
- [ ] api.ts - [ ] api.ts
- [ ] endorserServer.ts - [ ] endorserServer.ts
- [ ] partnerServer.ts - [ ] partnerServer.ts
- [ ] [5 more service files] - [ ] [5 more service files]
#### **Utils (4 files) - Priority 4** #### **Utils (4 files) - Priority 4**
- [ ] LogCollector.ts - [ ] LogCollector.ts
- [ ] [3 more util files] - [ ] [3 more util files]
### **Migration Tools** ### **Migration Tools**
#### **Automated Script for Common Patterns** #### **Automated Script for Common Patterns**
```bash ```bash
#!/bin/bash #!/bin/bash
# migration-helper.sh # migration-helper.sh
@ -326,6 +346,7 @@ echo "logConsoleAndDb → this.\$logAndConsole"
``` ```
#### **Validation Script** #### **Validation Script**
```bash ```bash
#!/bin/bash #!/bin/bash
# validate-migration.sh # validate-migration.sh
@ -350,6 +371,7 @@ echo "Migration validation complete!"
## 🎯 **Success Criteria** ## 🎯 **Success Criteria**
### **Day 1 Success Criteria:** ### **Day 1 Success Criteria:**
- [ ] PlatformServiceMixin has no circular dependencies - [ ] PlatformServiceMixin has no circular dependencies
- [ ] All utility functions implemented and tested - [ ] All utility functions implemented and tested
- [ ] Type definitions complete and accurate - [ ] Type definitions complete and accurate
@ -357,6 +379,7 @@ echo "Migration validation complete!"
- [ ] TypeScript compilation passes - [ ] TypeScript compilation passes
### **Day 2 Success Criteria:** ### **Day 2 Success Criteria:**
- [ ] 0 files importing databaseUtil - [ ] 0 files importing databaseUtil
- [ ] All 52 files migrated to PlatformServiceMixin - [ ] All 52 files migrated to PlatformServiceMixin
- [ ] No runtime errors in migrated components - [ ] No runtime errors in migrated components
@ -364,6 +387,7 @@ echo "Migration validation complete!"
- [ ] Performance maintained or improved - [ ] Performance maintained or improved
### **Overall Success Criteria:** ### **Overall Success Criteria:**
- [ ] Complete elimination of databaseUtil dependency - [ ] Complete elimination of databaseUtil dependency
- [ ] PlatformServiceMixin is the single source of truth for database operations - [ ] PlatformServiceMixin is the single source of truth for database operations
- [ ] Migration fence is fully implemented - [ ] Migration fence is fully implemented
@ -386,12 +410,14 @@ echo "Migration validation complete!"
## 📋 **Daily Progress Tracking** ## 📋 **Daily Progress Tracking**
### **Day 1 Progress:** ### **Day 1 Progress:**
- [ ] Phase 1: Circular dependency resolved - [ ] Phase 1: Circular dependency resolved
- [ ] Phase 2: Utility functions added - [ ] Phase 2: Utility functions added
- [ ] Phase 3: Type definitions updated - [ ] Phase 3: Type definitions updated
- [ ] Phase 4: Testing completed - [ ] Phase 4: Testing completed
### **Day 2 Progress:** ### **Day 2 Progress:**
- [ ] Views migrated (0/25) - [ ] Views migrated (0/25)
- [ ] Components migrated (0/15) - [ ] Components migrated (0/15)
- [ ] Services migrated (0/8) - [ ] Services migrated (0/8)
@ -403,16 +429,19 @@ echo "Migration validation complete!"
## 🆘 **Contingency Plans** ## 🆘 **Contingency Plans**
### **If Day 1 Takes Longer:** ### **If Day 1 Takes Longer:**
- Focus on core functionality first - Focus on core functionality first
- Defer advanced utility functions to Day 2 - Defer advanced utility functions to Day 2
- Prioritize circular dependency resolution - Prioritize circular dependency resolution
### **If Day 2 Takes Longer:** ### **If Day 2 Takes Longer:**
- Focus on high-impact views first - Focus on high-impact views first
- Batch similar components together - Batch similar components together
- Use automated scripts for common patterns - Use automated scripts for common patterns
### **If Issues Arise:** ### **If Issues Arise:**
- Document specific problems - Document specific problems
- Create targeted fixes - Create targeted fixes
- Maintain backward compatibility during transition - Maintain backward compatibility during transition

28
doc/qr-code-implementation-guide.md

@ -7,6 +7,7 @@ This document describes the QR code scanning and generation implementation in th
## Architecture ## Architecture
### Directory Structure ### Directory Structure
``` ```
src/ src/
├── services/ ├── services/
@ -74,6 +75,7 @@ interface QRScannerOptions {
### Platform-Specific Implementations ### Platform-Specific Implementations
#### Mobile (Capacitor) #### Mobile (Capacitor)
- Uses `@capacitor-mlkit/barcode-scanning` - Uses `@capacitor-mlkit/barcode-scanning`
- Native camera access through platform APIs - Native camera access through platform APIs
- Optimized for mobile performance - Optimized for mobile performance
@ -82,6 +84,7 @@ interface QRScannerOptions {
- Back camera preferred for scanning - Back camera preferred for scanning
Configuration: Configuration:
```typescript ```typescript
// capacitor.config.ts // capacitor.config.ts
const config: CapacitorConfig = { const config: CapacitorConfig = {
@ -105,6 +108,7 @@ const config: CapacitorConfig = {
``` ```
#### Web #### Web
- Uses browser's MediaDevices API - Uses browser's MediaDevices API
- Vue.js components for UI - Vue.js components for UI
- EventEmitter for stream management - EventEmitter for stream management
@ -116,6 +120,7 @@ const config: CapacitorConfig = {
### View Components ### View Components
#### ContactQRScanView #### ContactQRScanView
- Dedicated view for scanning QR codes - Dedicated view for scanning QR codes
- Full-screen camera interface - Full-screen camera interface
- Simple UI focused on scanning - Simple UI focused on scanning
@ -123,6 +128,7 @@ const config: CapacitorConfig = {
- Streamlined scanning experience - Streamlined scanning experience
#### ContactQRScanShowView #### ContactQRScanShowView
- Combined view for QR code display and scanning - Combined view for QR code display and scanning
- Shows user's own QR code - Shows user's own QR code
- Handles user registration status - Handles user registration status
@ -160,6 +166,7 @@ const config: CapacitorConfig = {
## Build Configuration ## Build Configuration
### Common Vite Configuration ### Common Vite Configuration
```typescript ```typescript
// vite.config.common.mts // vite.config.common.mts
export async function createBuildConfig(mode: string) { export async function createBuildConfig(mode: string) {
@ -183,6 +190,7 @@ export async function createBuildConfig(mode: string) {
``` ```
### Platform-Specific Builds ### Platform-Specific Builds
```json ```json
{ {
"scripts": { "scripts": {
@ -196,6 +204,7 @@ export async function createBuildConfig(mode: string) {
## Error Handling ## Error Handling
### Common Error Scenarios ### Common Error Scenarios
1. No camera found 1. No camera found
2. Permission denied 2. Permission denied
3. Camera in use by another application 3. Camera in use by another application
@ -207,6 +216,7 @@ export async function createBuildConfig(mode: string) {
9. Network connectivity issues 9. Network connectivity issues
### Error Response ### Error Response
- User-friendly error messages - User-friendly error messages
- Troubleshooting tips - Troubleshooting tips
- Clear instructions for resolution - Clear instructions for resolution
@ -215,6 +225,7 @@ export async function createBuildConfig(mode: string) {
## Security Considerations ## Security Considerations
### QR Code Security ### QR Code Security
- Encryption of contact data - Encryption of contact data
- Timestamp validation - Timestamp validation
- Version checking - Version checking
@ -222,6 +233,7 @@ export async function createBuildConfig(mode: string) {
- Rate limiting for scans - Rate limiting for scans
### Data Protection ### Data Protection
- Secure transmission of contact data - Secure transmission of contact data
- Validation of QR code authenticity - Validation of QR code authenticity
- Prevention of duplicate scans - Prevention of duplicate scans
@ -231,6 +243,7 @@ export async function createBuildConfig(mode: string) {
## Best Practices ## Best Practices
### Camera Access ### Camera Access
1. Always check for camera availability 1. Always check for camera availability
2. Request permissions explicitly 2. Request permissions explicitly
3. Handle all error conditions 3. Handle all error conditions
@ -238,6 +251,7 @@ export async function createBuildConfig(mode: string) {
5. Implement proper cleanup 5. Implement proper cleanup
### Performance ### Performance
1. Optimize camera resolution 1. Optimize camera resolution
2. Implement proper resource cleanup 2. Implement proper resource cleanup
3. Handle camera switching efficiently 3. Handle camera switching efficiently
@ -245,6 +259,7 @@ export async function createBuildConfig(mode: string) {
5. Battery usage optimization 5. Battery usage optimization
### User Experience ### User Experience
1. Clear visual feedback 1. Clear visual feedback
2. Camera preview 2. Camera preview
3. Scanning status indicators 3. Scanning status indicators
@ -257,6 +272,7 @@ export async function createBuildConfig(mode: string) {
## Testing ## Testing
### Test Scenarios ### Test Scenarios
1. Permission handling 1. Permission handling
2. Camera switching 2. Camera switching
3. Error conditions 3. Error conditions
@ -267,6 +283,7 @@ export async function createBuildConfig(mode: string) {
8. Security validation 8. Security validation
### Test Environment ### Test Environment
- Multiple browsers - Multiple browsers
- iOS and Android devices - iOS and Android devices
- Various network conditions - Various network conditions
@ -275,6 +292,7 @@ export async function createBuildConfig(mode: string) {
## Dependencies ## Dependencies
### Key Packages ### Key Packages
- `@capacitor-mlkit/barcode-scanning` - `@capacitor-mlkit/barcode-scanning`
- `qrcode-stream` - `qrcode-stream`
- `vue-qrcode-reader` - `vue-qrcode-reader`
@ -283,12 +301,14 @@ export async function createBuildConfig(mode: string) {
## Maintenance ## Maintenance
### Regular Updates ### Regular Updates
- Keep dependencies updated - Keep dependencies updated
- Monitor platform changes - Monitor platform changes
- Update documentation - Update documentation
- Review security patches - Review security patches
### Performance Monitoring ### Performance Monitoring
- Track memory usage - Track memory usage
- Monitor camera performance - Monitor camera performance
- Check error rates - Check error rates
@ -436,6 +456,7 @@ The camera switching implementation includes comprehensive error handling:
- Camera switch timeout - Camera switch timeout
2. **Error Response** 2. **Error Response**
```typescript ```typescript
private async handleCameraSwitch(deviceId: string): Promise<void> { private async handleCameraSwitch(deviceId: string): Promise<void> {
try { try {
@ -460,6 +481,7 @@ The camera switching implementation includes comprehensive error handling:
The camera system maintains several states: The camera system maintains several states:
1. **Camera States** 1. **Camera States**
```typescript ```typescript
type CameraState = type CameraState =
| "initializing" // Camera is being initialized | "initializing" // Camera is being initialized
@ -529,6 +551,7 @@ The camera system maintains several states:
#### MLKit Barcode Scanner Configuration #### MLKit Barcode Scanner Configuration
1. **Plugin Setup** 1. **Plugin Setup**
```typescript ```typescript
// capacitor.config.ts // capacitor.config.ts
const config: CapacitorConfig = { const config: CapacitorConfig = {
@ -552,6 +575,7 @@ The camera system maintains several states:
``` ```
2. **Camera Management** 2. **Camera Management**
```typescript ```typescript
// CapacitorQRScanner.ts // CapacitorQRScanner.ts
export class CapacitorQRScanner implements QRScannerService { export class CapacitorQRScanner implements QRScannerService {
@ -603,6 +627,7 @@ The camera system maintains several states:
``` ```
3. **Camera State Management** 3. **Camera State Management**
```typescript ```typescript
// CapacitorQRScanner.ts // CapacitorQRScanner.ts
private async handleCameraState(): Promise<void> { private async handleCameraState(): Promise<void> {
@ -645,6 +670,7 @@ The camera system maintains several states:
``` ```
4. **Error Handling** 4. **Error Handling**
```typescript ```typescript
// CapacitorQRScanner.ts // CapacitorQRScanner.ts
private async handleCameraError(error: Error): Promise<void> { private async handleCameraError(error: Error): Promise<void> {
@ -737,6 +763,7 @@ The camera system maintains several states:
#### Performance Optimization #### Performance Optimization
1. **Battery Usage** 1. **Battery Usage**
```typescript ```typescript
// CapacitorQRScanner.ts // CapacitorQRScanner.ts
private optimizeBatteryUsage(): void { private optimizeBatteryUsage(): void {
@ -759,6 +786,7 @@ The camera system maintains several states:
``` ```
2. **Memory Management** 2. **Memory Management**
```typescript ```typescript
// CapacitorQRScanner.ts // CapacitorQRScanner.ts
private async cleanupResources(): Promise<void> { private async cleanupResources(): Promise<void> {

9
doc/secure-storage-implementation.md

@ -111,6 +111,7 @@ export class AbsurdSqlDatabaseService implements PlatformService {
``` ```
Key features: Key features:
- Uses absurd-sql for SQLite in the browser - Uses absurd-sql for SQLite in the browser
- Implements operation queuing for thread safety - Implements operation queuing for thread safety
- Handles initialization and connection management - Handles initialization and connection management
@ -143,6 +144,7 @@ async function getAccount(did: string): Promise<Account | undefined> {
When converting from Dexie.js to SQL-based implementation, follow these patterns: When converting from Dexie.js to SQL-based implementation, follow these patterns:
1. **Database Access Pattern** 1. **Database Access Pattern**
```typescript ```typescript
// Before (Dexie) // Before (Dexie)
const result = await db.table.where("field").equals(value).first(); const result = await db.table.where("field").equals(value).first();
@ -161,6 +163,7 @@ When converting from Dexie.js to SQL-based implementation, follow these patterns
``` ```
2. **Update Operations** 2. **Update Operations**
```typescript ```typescript
// Before (Dexie) // Before (Dexie)
await db.table.where("id").equals(id).modify(changes); await db.table.where("id").equals(id).modify(changes);
@ -184,6 +187,7 @@ When converting from Dexie.js to SQL-based implementation, follow these patterns
``` ```
3. **Insert Operations** 3. **Insert Operations**
```typescript ```typescript
// Before (Dexie) // Before (Dexie)
await db.table.add(item); await db.table.add(item);
@ -202,6 +206,7 @@ When converting from Dexie.js to SQL-based implementation, follow these patterns
``` ```
4. **Delete Operations** 4. **Delete Operations**
```typescript ```typescript
// Before (Dexie) // Before (Dexie)
await db.table.where("id").equals(id).delete(); await db.table.where("id").equals(id).delete();
@ -216,6 +221,7 @@ When converting from Dexie.js to SQL-based implementation, follow these patterns
``` ```
5. **Result Processing** 5. **Result Processing**
```typescript ```typescript
// Before (Dexie) // Before (Dexie)
const items = await db.table.toArray(); const items = await db.table.toArray();
@ -247,6 +253,7 @@ await databaseUtil.logConsoleAndDb(message, showInConsole);
``` ```
Key Considerations: Key Considerations:
- Always use `databaseUtil.mapQueryResultToValues()` to process SQL query results - Always use `databaseUtil.mapQueryResultToValues()` to process SQL query results
- Use utility methods from `db/index.ts` when available instead of direct SQL - Use utility methods from `db/index.ts` when available instead of direct SQL
- Keep Dexie fallbacks wrapped in migration period checks - Keep Dexie fallbacks wrapped in migration period checks
@ -254,6 +261,7 @@ Key Considerations:
- For updates/inserts/deletes, execute both SQL and Dexie operations during migration period - For updates/inserts/deletes, execute both SQL and Dexie operations during migration period
Example Migration: Example Migration:
```typescript ```typescript
// Before (Dexie) // Before (Dexie)
export async function updateSettings(settings: Settings): Promise<void> { export async function updateSettings(settings: Settings): Promise<void> {
@ -274,6 +282,7 @@ export async function updateSettings(settings: Settings): Promise<void> {
``` ```
Remember to: Remember to:
- Create database access code to use the platform service, putting it in front of the Dexie version - Create database access code to use the platform service, putting it in front of the Dexie version
- Instead of removing Dexie-specific code, keep it. - Instead of removing Dexie-specific code, keep it.

14
doc/sharebufferarray_spectre_security.md

@ -4,11 +4,13 @@
## 1. Introduction to SharedArrayBuffer ## 1. Introduction to SharedArrayBuffer
### Overview ### Overview
- `SharedArrayBuffer` is a JavaScript object that enables **shared memory** access between the main thread and Web Workers. - `SharedArrayBuffer` is a JavaScript object that enables **shared memory** access between the main thread and Web Workers.
- Unlike `ArrayBuffer`, the memory is **not copied** between threads—allowing **true parallelism**. - Unlike `ArrayBuffer`, the memory is **not copied** between threads—allowing **true parallelism**.
- Paired with `Atomics`, it allows low-level memory synchronization (e.g., locks, waits). - Paired with `Atomics`, it allows low-level memory synchronization (e.g., locks, waits).
### Example Use ### Example Use
```js ```js
const sab = new SharedArrayBuffer(1024); const sab = new SharedArrayBuffer(1024);
const sharedArray = new Uint8Array(sab); const sharedArray = new Uint8Array(sab);
@ -18,6 +20,7 @@ sharedArray[0] = 42;
## 2. Browser Security Requirements ## 2. Browser Security Requirements
### Security Headers Required to Use SharedArrayBuffer ### Security Headers Required to Use SharedArrayBuffer
Modern browsers **restrict access** to `SharedArrayBuffer` due to Spectre-class vulnerabilities. Modern browsers **restrict access** to `SharedArrayBuffer` due to Spectre-class vulnerabilities.
The following **HTTP headers must be set** to enable it: The following **HTTP headers must be set** to enable it:
@ -28,23 +31,28 @@ Cross-Origin-Embedder-Policy: require-corp
``` ```
### HTTPS Requirement ### HTTPS Requirement
- Must be served over **HTTPS** (except `localhost` for dev). - Must be served over **HTTPS** (except `localhost` for dev).
- These headers enforce **cross-origin isolation**. - These headers enforce **cross-origin isolation**.
### Role of CORS ### Role of CORS
- CORS **alone is not sufficient**. - CORS **alone is not sufficient**.
- However, embedded resources (like scripts and iframes) must still include proper CORS headers if they are to be loaded in a cross-origin isolated context. - However, embedded resources (like scripts and iframes) must still include proper CORS headers if they are to be loaded in a cross-origin isolated context.
## 3. Spectre Vulnerability ## 3. Spectre Vulnerability
### What is Spectre? ### What is Spectre?
- A class of **side-channel attacks** exploiting **speculative execution** in CPUs. - A class of **side-channel attacks** exploiting **speculative execution** in CPUs.
- Allows an attacker to read arbitrary memory from the same address space. - Allows an attacker to read arbitrary memory from the same address space.
### Affected Architectures ### Affected Architectures
- Intel, AMD, ARM — essentially **all modern processors**. - Intel, AMD, ARM — essentially **all modern processors**.
### Why It's Still a Concern ### Why It's Still a Concern
- It's a **hardware flaw**, not just a software bug. - It's a **hardware flaw**, not just a software bug.
- Can't be fully fixed in software without performance penalties. - Can't be fully fixed in software without performance penalties.
- New Spectre **variants** (e.g., v2, RSB, BranchScope) continue to emerge. - New Spectre **variants** (e.g., v2, RSB, BranchScope) continue to emerge.
@ -52,16 +60,19 @@ Cross-Origin-Embedder-Policy: require-corp
## 4. Mitigations and Current Limitations ## 4. Mitigations and Current Limitations
### Browser Mitigations ### Browser Mitigations
- **Restricted precision** for `performance.now()`. - **Restricted precision** for `performance.now()`.
- **Disabled or gated** access to `SharedArrayBuffer`. - **Disabled or gated** access to `SharedArrayBuffer`.
- **Reduced or removed** fine-grained timers. - **Reduced or removed** fine-grained timers.
### OS/Hardware Mitigations ### OS/Hardware Mitigations
- **Kernel Page Table Isolation (KPTI)** - **Kernel Page Table Isolation (KPTI)**
- **Microcode updates** - **Microcode updates**
- **Retpoline** compiler mitigations - **Retpoline** compiler mitigations
### Developer Responsibilities ### Developer Responsibilities
- Avoid sharing sensitive data across threads unless necessary. - Avoid sharing sensitive data across threads unless necessary.
- Use **constant-time cryptographic functions**. - Use **constant-time cryptographic functions**.
- Assume timing attacks are **still possible**. - Assume timing attacks are **still possible**.
@ -70,10 +81,12 @@ Cross-Origin-Embedder-Policy: require-corp
## 5. Practical Development Notes ## 5. Practical Development Notes
### Using SharedArrayBuffer Safely ### Using SharedArrayBuffer Safely
- Ensure the site is **cross-origin isolated**: - Ensure the site is **cross-origin isolated**:
- Serve all resources with appropriate **CORS policies** (`Cross-Origin-Resource-Policy`, `Access-Control-Allow-Origin`) - Serve all resources with appropriate **CORS policies** (`Cross-Origin-Resource-Policy`, `Access-Control-Allow-Origin`)
- Set the required **COOP/COEP headers** - Set the required **COOP/COEP headers**
- Validate support using: - Validate support using:
```js ```js
if (window.crossOriginIsolated) { if (window.crossOriginIsolated) {
// Safe to use SharedArrayBuffer // Safe to use SharedArrayBuffer
@ -81,6 +94,7 @@ if (window.crossOriginIsolated) {
``` ```
### Testing and Fallback ### Testing and Fallback
- Provide fallbacks to `ArrayBuffer` if isolation is not available. - Provide fallbacks to `ArrayBuffer` if isolation is not available.
- Document use cases clearly (e.g., high-performance WebAssembly applications or real-time audio/video processing). - Document use cases clearly (e.g., high-performance WebAssembly applications or real-time audio/video processing).

29
doc/storage-implementation-checklist.md

@ -3,6 +3,7 @@
## Core Services ## Core Services
### 1. Storage Service Layer ### 1. Storage Service Layer
- [x] Create base `PlatformService` interface - [x] Create base `PlatformService` interface
- [x] Define common methods for all platforms - [x] Define common methods for all platforms
- [x] Add platform-specific method signatures - [x] Add platform-specific method signatures
@ -25,6 +26,7 @@
- [ ] File system access - [ ] File system access
### 2. Migration Services ### 2. Migration Services
- [x] Implement basic migration support - [x] Implement basic migration support
- [x] Dual-storage pattern (SQLite + Dexie) - [x] Dual-storage pattern (SQLite + Dexie)
- [x] Basic data verification - [x] Basic data verification
@ -37,6 +39,7 @@
- [ ] Manual triggers - [ ] Manual triggers
### 3. Security Layer ### 3. Security Layer
- [x] Basic data integrity - [x] Basic data integrity
- [ ] Implement `EncryptionService` (planned) - [ ] Implement `EncryptionService` (planned)
- [ ] Key management - [ ] Key management
@ -50,14 +53,17 @@
## Platform-Specific Implementation ## Platform-Specific Implementation
### Web Platform ### Web Platform
- [x] Setup absurd-sql - [x] Setup absurd-sql
- [x] Install dependencies - [x] Install dependencies
```json ```json
{ {
"@jlongster/sql.js": "^1.8.0", "@jlongster/sql.js": "^1.8.0",
"absurd-sql": "^1.8.0" "absurd-sql": "^1.8.0"
} }
``` ```
- [x] Configure VFS with IndexedDB backend - [x] Configure VFS with IndexedDB backend
- [x] Setup worker threads - [x] Setup worker threads
- [x] Implement operation queuing - [x] Implement operation queuing
@ -83,6 +89,7 @@
- [x] Implement atomic operations - [x] Implement atomic operations
### iOS Platform (Planned) ### iOS Platform (Planned)
- [ ] Setup SQLCipher - [ ] Setup SQLCipher
- [ ] Install pod dependencies - [ ] Install pod dependencies
- [ ] Configure encryption - [ ] Configure encryption
@ -96,6 +103,7 @@
- [ ] Setup app groups - [ ] Setup app groups
### Android Platform (Planned) ### Android Platform (Planned)
- [ ] Setup SQLCipher - [ ] Setup SQLCipher
- [ ] Add Gradle dependencies - [ ] Add Gradle dependencies
- [ ] Configure encryption - [ ] Configure encryption
@ -109,6 +117,7 @@
- [ ] Setup file provider - [ ] Setup file provider
### Electron Platform (Planned) ### Electron Platform (Planned)
- [ ] Setup Node SQLite - [ ] Setup Node SQLite
- [ ] Install dependencies - [ ] Install dependencies
- [ ] Configure IPC - [ ] Configure IPC
@ -124,6 +133,7 @@
## Data Models and Types ## Data Models and Types
### 1. Database Schema ### 1. Database Schema
- [x] Define tables - [x] Define tables
```sql ```sql
@ -166,6 +176,7 @@
### 2. Type Definitions ### 2. Type Definitions
- [x] Create interfaces - [x] Create interfaces
```typescript ```typescript
interface Account { interface Account {
did: string; did: string;
@ -197,6 +208,7 @@
## UI Components ## UI Components
### 1. Migration UI (Planned) ### 1. Migration UI (Planned)
- [ ] Create components - [ ] Create components
- [ ] `MigrationProgress.vue` - [ ] `MigrationProgress.vue`
- [ ] `MigrationError.vue` - [ ] `MigrationError.vue`
@ -204,6 +216,7 @@
- [ ] `MigrationStatus.vue` - [ ] `MigrationStatus.vue`
### 2. Settings UI (Planned) ### 2. Settings UI (Planned)
- [ ] Update components - [ ] Update components
- [ ] Add storage settings - [ ] Add storage settings
- [ ] Add migration controls - [ ] Add migration controls
@ -211,6 +224,7 @@
- [ ] Add security settings - [ ] Add security settings
### 3. Error Handling UI (Planned) ### 3. Error Handling UI (Planned)
- [ ] Create components - [ ] Create components
- [ ] `StorageError.vue` - [ ] `StorageError.vue`
- [ ] `QuotaExceeded.vue` - [ ] `QuotaExceeded.vue`
@ -220,6 +234,7 @@
## Testing ## Testing
### 1. Unit Tests ### 1. Unit Tests
- [x] Basic service tests - [x] Basic service tests
- [x] Platform service tests - [x] Platform service tests
- [x] Database operation tests - [x] Database operation tests
@ -227,6 +242,7 @@
- [ ] Platform detection tests (planned) - [ ] Platform detection tests (planned)
### 2. Integration Tests (Planned) ### 2. Integration Tests (Planned)
- [ ] Test migrations - [ ] Test migrations
- [ ] Web platform tests - [ ] Web platform tests
- [ ] iOS platform tests - [ ] iOS platform tests
@ -234,6 +250,7 @@
- [ ] Electron platform tests - [ ] Electron platform tests
### 3. E2E Tests (Planned) ### 3. E2E Tests (Planned)
- [ ] Test workflows - [ ] Test workflows
- [ ] Account management - [ ] Account management
- [ ] Settings management - [ ] Settings management
@ -243,12 +260,14 @@
## Documentation ## Documentation
### 1. Technical Documentation ### 1. Technical Documentation
- [x] Update architecture docs - [x] Update architecture docs
- [x] Add API documentation - [x] Add API documentation
- [ ] Create migration guides (planned) - [ ] Create migration guides (planned)
- [ ] Document security measures (planned) - [ ] Document security measures (planned)
### 2. User Documentation (Planned) ### 2. User Documentation (Planned)
- [ ] Update user guides - [ ] Update user guides
- [ ] Add troubleshooting guides - [ ] Add troubleshooting guides
- [ ] Create FAQ - [ ] Create FAQ
@ -257,12 +276,14 @@
## Deployment ## Deployment
### 1. Build Process ### 1. Build Process
- [x] Update build scripts - [x] Update build scripts
- [x] Add platform-specific builds - [x] Add platform-specific builds
- [ ] Configure CI/CD (planned) - [ ] Configure CI/CD (planned)
- [ ] Setup automated testing (planned) - [ ] Setup automated testing (planned)
### 2. Release Process (Planned) ### 2. Release Process (Planned)
- [ ] Create release checklist - [ ] Create release checklist
- [ ] Add version management - [ ] Add version management
- [ ] Setup rollback procedures - [ ] Setup rollback procedures
@ -271,12 +292,14 @@
## Monitoring and Analytics (Planned) ## Monitoring and Analytics (Planned)
### 1. Error Tracking ### 1. Error Tracking
- [ ] Setup error logging - [ ] Setup error logging
- [ ] Add performance monitoring - [ ] Add performance monitoring
- [ ] Configure alerts - [ ] Configure alerts
- [ ] Create dashboards - [ ] Create dashboards
### 2. Usage Analytics ### 2. Usage Analytics
- [ ] Add storage metrics - [ ] Add storage metrics
- [ ] Track migration success - [ ] Track migration success
- [ ] Monitor performance - [ ] Monitor performance
@ -285,12 +308,14 @@
## Security Audit (Planned) ## Security Audit (Planned)
### 1. Code Review ### 1. Code Review
- [ ] Review encryption - [ ] Review encryption
- [ ] Check access controls - [ ] Check access controls
- [ ] Verify data handling - [ ] Verify data handling
- [ ] Audit dependencies - [ ] Audit dependencies
### 2. Penetration Testing ### 2. Penetration Testing
- [ ] Test data access - [ ] Test data access
- [ ] Verify encryption - [ ] Verify encryption
- [ ] Check authentication - [ ] Check authentication
@ -299,6 +324,7 @@
## Success Criteria ## Success Criteria
### 1. Performance ### 1. Performance
- [x] Query response time < 100ms - [x] Query response time < 100ms
- [x] Operation queuing for thread safety - [x] Operation queuing for thread safety
- [x] Proper initialization handling - [x] Proper initialization handling
@ -307,6 +333,7 @@
- [ ] Memory usage < 50MB (planned) - [ ] Memory usage < 50MB (planned)
### 2. Reliability ### 2. Reliability
- [x] Basic data integrity - [x] Basic data integrity
- [x] Operation queuing - [x] Operation queuing
- [ ] Automatic recovery (planned) - [ ] Automatic recovery (planned)
@ -315,6 +342,7 @@
- [ ] Data consistency (planned) - [ ] Data consistency (planned)
### 3. Security ### 3. Security
- [x] Basic data integrity - [x] Basic data integrity
- [ ] AES-256 encryption (planned) - [ ] AES-256 encryption (planned)
- [ ] Secure key storage (planned) - [ ] Secure key storage (planned)
@ -322,6 +350,7 @@
- [ ] Audit logging (planned) - [ ] Audit logging (planned)
### 4. User Experience ### 4. User Experience
- [x] Basic database operations - [x] Basic database operations
- [ ] Smooth migration (planned) - [ ] Smooth migration (planned)
- [ ] Clear error messages (planned) - [ ] Clear error messages (planned)

11
doc/usage-guide.md

@ -53,7 +53,6 @@ header-includes:
\clearpage \clearpage
# Purpose of Document # Purpose of Document
Both end-users and development team members need to know how to use TimeSafari. Both end-users and development team members need to know how to use TimeSafari.
@ -90,6 +89,7 @@ development environment. This section will guide you through the process.
## Prerequisites ## Prerequisites
1. Have the following installed on your local machine: 1. Have the following installed on your local machine:
- Node.js and NPM - Node.js and NPM
- A web browser. For this guide, we will use Google Chrome. - A web browser. For this guide, we will use Google Chrome.
- Git - Git
@ -97,6 +97,7 @@ development environment. This section will guide you through the process.
2. Create an API key on Infura. This is necessary for the Endorser API to connect to the Ethereum 2. Create an API key on Infura. This is necessary for the Endorser API to connect to the Ethereum
blockchain. blockchain.
- You can create an account on Infura [here](https://infura.io/).\ - You can create an account on Infura [here](https://infura.io/).\
Click "CREATE NEW API KEY" and label the key. Then click "API Keys" in the top menu bar to Click "CREATE NEW API KEY" and label the key. Then click "API Keys" in the top menu bar to
be taken back to the list of keys. be taken back to the list of keys.
@ -117,10 +118,10 @@ development environment. This section will guide you through the process.
- Save this for later during the Endorser API setup. This will go in your `INFURA_PROJECT_ID` - Save this for later during the Endorser API setup. This will go in your `INFURA_PROJECT_ID`
environment variable. environment variable.
## Setup steps ## Setup steps
### 1. Clone the following repositories from their respective Git hosts: ### 1. Clone the following repositories from their respective Git hosts
- [TimeSafari Frontend](https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa)\ - [TimeSafari Frontend](https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa)\
This is a Progressive Web App (PWA) built with VueJS and TypeScript. This is a Progressive Web App (PWA) built with VueJS and TypeScript.
Note that the clone command here is different from the one you would use for GitHub. Note that the clone command here is different from the one you would use for GitHub.
@ -157,21 +158,25 @@ second user to the app.
1. Install dependencies and environment variables.\ 1. Install dependencies and environment variables.\
In endorser-ch install dependencies and set up environment variables to allow starting it up in In endorser-ch install dependencies and set up environment variables to allow starting it up in
development mode. development mode.
```bash ```bash
cd endorser-ch cd endorser-ch
npm clean install # or npm ci npm clean install # or npm ci
cp .env.local .env cp .env.local .env
``` ```
Edit the .env file's INFURA_PROJECT_ID with the value you saved earlier in the Edit the .env file's INFURA_PROJECT_ID with the value you saved earlier in the
prerequisites.\ prerequisites.\
Then create the SQLite database by running `npm run flyway migrate` with environment variables Then create the SQLite database by running `npm run flyway migrate` with environment variables
set correctly to select the default SQLite development user as follows. set correctly to select the default SQLite development user as follows.
```bash ```bash
export NODE_ENV=dev export NODE_ENV=dev
export DBUSER=sa export DBUSER=sa
export DBPASS=sasa export DBPASS=sasa
npm run flyway migrate npm run flyway migrate
``` ```
The first run of flyway migrate may take some time to complete because the entire Flyway The first run of flyway migrate may take some time to complete because the entire Flyway
distribution must be downloaded prior to executing migrations. distribution must be downloaded prior to executing migrations.

32
docker/README.md

@ -155,6 +155,7 @@ VITE_PASSKEYS_ENABLED=true
## Build Modes ## Build Modes
### Development Mode ### Development Mode
- **Target**: `development` - **Target**: `development`
- **Features**: Hot reloading, development server - **Features**: Hot reloading, development server
- **Port**: 5173 - **Port**: 5173
@ -168,6 +169,7 @@ docker build --target development -t timesafari:dev .
``` ```
### Staging Mode ### Staging Mode
- **Target**: `staging` - **Target**: `staging`
- **Features**: Production build with relaxed caching - **Features**: Production build with relaxed caching
- **Port**: 8080 (mapped from 80) - **Port**: 8080 (mapped from 80)
@ -181,6 +183,7 @@ docker build --build-arg BUILD_MODE=staging -t timesafari:staging .
``` ```
### Production Mode ### Production Mode
- **Target**: `production` - **Target**: `production`
- **Features**: Optimized production build - **Features**: Optimized production build
- **Port**: 80 - **Port**: 80
@ -194,6 +197,7 @@ docker build -t timesafari:latest .
``` ```
### Custom Mode ### Custom Mode
- **Target**: Configurable via `BUILD_TARGET` - **Target**: Configurable via `BUILD_TARGET`
- **Features**: Fully configurable - **Features**: Fully configurable
- **Port**: Configurable via `CUSTOM_PORT` - **Port**: Configurable via `CUSTOM_PORT`
@ -250,6 +254,7 @@ docker-compose up staging
## Security Features ## Security Features
### Built-in Security ### Built-in Security
- **Non-root user execution**: All containers run as non-root users - **Non-root user execution**: All containers run as non-root users
- **Security headers**: XSS protection, content type options, frame options - **Security headers**: XSS protection, content type options, frame options
- **Rate limiting**: API request rate limiting - **Rate limiting**: API request rate limiting
@ -257,6 +262,7 @@ docker-compose up staging
- **Minimal attack surface**: Alpine Linux base images - **Minimal attack surface**: Alpine Linux base images
### Security Headers ### Security Headers
- `X-Frame-Options: SAMEORIGIN` - `X-Frame-Options: SAMEORIGIN`
- `X-Content-Type-Options: nosniff` - `X-Content-Type-Options: nosniff`
- `X-XSS-Protection: 1; mode=block` - `X-XSS-Protection: 1; mode=block`
@ -266,17 +272,20 @@ docker-compose up staging
## Performance Optimizations ## Performance Optimizations
### Caching Strategy ### Caching Strategy
- **Static assets**: 1 year cache with immutable flag (production) - **Static assets**: 1 year cache with immutable flag (production)
- **HTML files**: 1 hour cache (production) / no cache (staging) - **HTML files**: 1 hour cache (production) / no cache (staging)
- **Service worker**: No cache - **Service worker**: No cache
- **Manifest**: 1 day cache (production) / 1 hour cache (staging) - **Manifest**: 1 day cache (production) / 1 hour cache (staging)
### Compression ### Compression
- **Gzip compression**: Enabled for text-based files - **Gzip compression**: Enabled for text-based files
- **Compression level**: 6 (balanced) - **Compression level**: 6 (balanced)
- **Minimum size**: 1024 bytes - **Minimum size**: 1024 bytes
### Nginx Optimizations ### Nginx Optimizations
- **Sendfile**: Enabled for efficient file serving - **Sendfile**: Enabled for efficient file serving
- **TCP optimizations**: nopush and nodelay enabled - **TCP optimizations**: nopush and nodelay enabled
- **Keepalive**: 65 second timeout - **Keepalive**: 65 second timeout
@ -285,19 +294,23 @@ docker-compose up staging
## Health Checks ## Health Checks
### Built-in Health Checks ### Built-in Health Checks
All services include health checks that: All services include health checks that:
- Check every 30 seconds - Check every 30 seconds
- Timeout after 10 seconds - Timeout after 10 seconds
- Retry 3 times before marking unhealthy - Retry 3 times before marking unhealthy
- Start checking after 40 seconds - Start checking after 40 seconds
### Health Check Endpoints ### Health Check Endpoints
- **Production/Staging**: `http://localhost/health` - **Production/Staging**: `http://localhost/health`
- **Development**: `http://localhost:5173` - **Development**: `http://localhost:5173`
## SSL/HTTPS Setup ## SSL/HTTPS Setup
### SSL Certificates ### SSL Certificates
For SSL deployment, create an `ssl` directory with certificates: For SSL deployment, create an `ssl` directory with certificates:
```bash ```bash
@ -308,6 +321,7 @@ cp your-key.pem ssl/
``` ```
### SSL Configuration ### SSL Configuration
Use the `production-ssl` service in docker-compose: Use the `production-ssl` service in docker-compose:
```bash ```bash
@ -317,10 +331,12 @@ docker-compose up production-ssl
## Monitoring and Logging ## Monitoring and Logging
### Log Locations ### Log Locations
- **Access logs**: `/var/log/nginx/access.log` - **Access logs**: `/var/log/nginx/access.log`
- **Error logs**: `/var/log/nginx/error.log` - **Error logs**: `/var/log/nginx/error.log`
### Log Format ### Log Format
``` ```
$remote_addr - $remote_user [$time_local] "$request" $remote_addr - $remote_user [$time_local] "$request"
$status $body_bytes_sent "$http_referer" $status $body_bytes_sent "$http_referer"
@ -328,6 +344,7 @@ $status $body_bytes_sent "$http_referer"
``` ```
### Log Levels ### Log Levels
- **Production**: `warn` level - **Production**: `warn` level
- **Staging**: `debug` level - **Staging**: `debug` level
- **Development**: Full logging - **Development**: Full logging
@ -337,6 +354,7 @@ $status $body_bytes_sent "$http_referer"
### Common Issues ### Common Issues
#### Build Failures #### Build Failures
```bash ```bash
# Check build logs # Check build logs
docker build -t timesafari:latest . 2>&1 | tee build.log docker build -t timesafari:latest . 2>&1 | tee build.log
@ -349,6 +367,7 @@ docker run --rm timesafari:latest npm list --depth=0
``` ```
#### Container Won't Start #### Container Won't Start
```bash ```bash
# Check container logs # Check container logs
docker logs <container_id> docker logs <container_id>
@ -361,6 +380,7 @@ netstat -tulpn | grep :80
``` ```
#### Environment Variables Not Set #### Environment Variables Not Set
```bash ```bash
# Check environment in container # Check environment in container
docker exec <container_id> env | grep VITE_ docker exec <container_id> env | grep VITE_
@ -373,6 +393,7 @@ cat .env.production
``` ```
#### Performance Issues #### Performance Issues
```bash ```bash
# Check container resources # Check container resources
docker stats <container_id> docker stats <container_id>
@ -387,6 +408,7 @@ docker exec <container_id> tail -f /var/log/nginx/access.log
### Debug Commands ### Debug Commands
#### Container Debugging #### Container Debugging
```bash ```bash
# Enter running container # Enter running container
docker exec -it <container_id> /bin/sh docker exec -it <container_id> /bin/sh
@ -399,6 +421,7 @@ docker exec <container_id> ls -la /usr/share/nginx/html
``` ```
#### Network Debugging #### Network Debugging
```bash ```bash
# Check container network # Check container network
docker network inspect bridge docker network inspect bridge
@ -413,6 +436,7 @@ docker exec <container_id> nslookup google.com
## Production Deployment ## Production Deployment
### Recommended Production Setup ### Recommended Production Setup
1. **Use specific version tags**: `timesafari:1.0.0` 1. **Use specific version tags**: `timesafari:1.0.0`
2. **Implement health checks**: Already included 2. **Implement health checks**: Already included
3. **Configure proper logging**: Use external log aggregation 3. **Configure proper logging**: Use external log aggregation
@ -420,6 +444,7 @@ docker exec <container_id> nslookup google.com
5. **Use Docker secrets**: For sensitive data 5. **Use Docker secrets**: For sensitive data
### Production Commands ### Production Commands
```bash ```bash
# Build with specific version # Build with specific version
docker build -t timesafari:1.0.0 . docker build -t timesafari:1.0.0 .
@ -442,6 +467,7 @@ docker run -d --name timesafari -p 80:80 --restart unless-stopped --env-file .en
## Development Workflow ## Development Workflow
### Local Development ### Local Development
```bash ```bash
# Start development environment # Start development environment
./docker/run.sh dev ./docker/run.sh dev
@ -454,6 +480,7 @@ docker-compose down dev
``` ```
### Testing Changes ### Testing Changes
```bash ```bash
# Build and test staging # Build and test staging
./docker/run.sh staging ./docker/run.sh staging
@ -463,6 +490,7 @@ docker-compose down dev
``` ```
### Continuous Integration ### Continuous Integration
```bash ```bash
# Build and test in CI # Build and test in CI
docker build -t timesafari:test . docker build -t timesafari:test .
@ -479,6 +507,7 @@ docker rm timesafari-test
## Best Practices ## Best Practices
### Security ### Security
- Always use non-root users - Always use non-root users
- Keep base images updated - Keep base images updated
- Scan images for vulnerabilities - Scan images for vulnerabilities
@ -486,6 +515,7 @@ docker rm timesafari-test
- Implement proper access controls - Implement proper access controls
### Performance ### Performance
- Use multi-stage builds - Use multi-stage builds
- Optimize layer caching - Optimize layer caching
- Minimize image size - Minimize image size
@ -493,6 +523,7 @@ docker rm timesafari-test
- Implement proper caching - Implement proper caching
### Monitoring ### Monitoring
- Use health checks - Use health checks
- Monitor resource usage - Monitor resource usage
- Set up log aggregation - Set up log aggregation
@ -500,6 +531,7 @@ docker rm timesafari-test
- Use proper error handling - Use proper error handling
### Maintenance ### Maintenance
- Regular security updates - Regular security updates
- Monitor for vulnerabilities - Monitor for vulnerabilities
- Keep dependencies updated - Keep dependencies updated

115
docs/README.md

@ -1,115 +0,0 @@
# TimeSafari Documentation
**Author**: Matthew Raymer
**Date**: 2025-01-27
**Status**: 🎯 **COMPLETE** - Documentation organized and structured
## Documentation Structure
This documentation is organized into logical categories to ensure easy navigation and maintenance. Each folder contains no more than 7 items to maintain clarity and usability.
### 📚 User Guides (`user-guides/`)
Documentation for end users and potential users of TimeSafari:
- User Guide - Comprehensive explanation of TimeSafari's purpose and features
- Quick Start Guide - Immediate actionable steps for new users
- Real-World Examples - Concrete stories of community transformation
### 🔧 Build System (`build-system/`)
Documentation for building and deploying TimeSafari across platforms:
- Build Systems Overview - Complete architecture of build processes
- Build Troubleshooting - Common issues and solutions
- Platform-specific build scripts and configurations
- Auto-run and automation guides
### 🔄 Migration (`migration/`)
Documentation for the database migration from Dexie to SQLite:
- Migration progress tracking and assessments
- Migration templates and best practices
- Component migration testing and validation
- Migration tools and utilities
### 💻 Development (`development/`)
Documentation for developers working on TimeSafari:
- Domain configuration and setup
- Development tools and utilities
- Code standards and templates
- Testing frameworks and practices
### 🏗️ Architecture (`architecture/`)
High-level system design and architectural decisions:
- System architecture overview
- Design patterns and principles
- Integration guides
- Performance considerations
### 🧪 Testing (`testing/`)
Testing documentation and procedures:
- Test frameworks and tools
- Testing strategies and methodologies
- Quality assurance processes
- Performance testing guidelines
### 📖 Examples (`examples/`)
Code examples and implementation patterns:
- Implementation examples
- Best practice demonstrations
- Integration examples
- Troubleshooting examples
## Documentation Standards
### File Organization
- **Maximum 7 items per folder**: Ensures easy navigation and maintenance
- **Logical grouping**: Related documents are grouped together
- **Clear naming**: File names clearly indicate content and purpose
- **Version control**: All changes are tracked in git with proper commit messages
### Documentation Quality
- **Rich documentation**: Comprehensive coverage at file, class, and method levels
- **Consistent formatting**: Follows established markdown standards
- **Regular updates**: Documentation is updated as code changes
- **User-focused**: Content is written for the intended audience
### Maintenance
- **Regular reviews**: Documentation is reviewed and updated regularly
- **Feedback integration**: User feedback is incorporated into documentation
- **Cross-references**: Related documents are properly linked
- **Searchability**: Content is organized for easy discovery
## Getting Started
### For Users
1. Start with the [Quick Start Guide](user-guides/quick-start-guide.md)
2. Read the [User Guide](user-guides/user-guide.md) for comprehensive understanding
3. Explore [Real-World Examples](user-guides/real-world-examples.md) for inspiration
### For Developers
1. Review the [Build System Overview](build-system/build-systems-overview.md)
2. Check [Development Setup](development/) for environment configuration
3. Understand the [Migration Process](migration/) if working on database changes
### For Contributors
1. Read the [Development Guidelines](development/)
2. Review [Testing Procedures](testing/)
3. Check [Architecture Decisions](architecture/)
## Contributing to Documentation
When adding or updating documentation:
1. **Choose the right folder**: Place documents in the most appropriate category
2. **Follow naming conventions**: Use clear, descriptive file names
3. **Maintain folder limits**: Create sub-folders if a folder exceeds 7 items
4. **Update this README**: Add new categories or reorganize as needed
5. **Version in git**: Commit documentation changes with clear messages
## Documentation Tools
- **Markdown**: All documentation uses markdown format
- **Git**: Version control for all documentation changes
- **Linting**: Markdown linting ensures consistent formatting
- **Validation**: Regular checks ensure documentation accuracy
---
*This documentation structure is designed to scale with the project while maintaining clarity and usability.*

405
docs/build-system/automation/auto-run-guide.md

@ -1,405 +0,0 @@
# Auto-Run Guide
**Author**: Matthew Raymer
**Date**: 2025-07-12
**Status**: 🎯 **ACTIVE** - In Use
## Overview
The TimeSafari auto-run system intelligently detects available devices and
automatically builds and launches the app on the best available target. It
supports Android devices/emulators, iOS devices/simulators, and Electron
desktop apps.
## Features
### Smart Device Detection
- **Android**: Detects real devices vs emulators using ADB
- **iOS**: Detects real devices vs simulators using xcrun
- **Electron**: Checks for Electron availability
- **Priority**: Real devices preferred over simulators/emulators
### Build Mode Support
- **Development**: Default mode for daily development
- **Test**: Optimized for testing with test data
- **Production**: Production-ready builds
### Platform Targeting
- **All platforms**: Automatically detects and runs on all available
- **Specific platform**: Target only iOS, Android, or Electron
- **Cross-platform**: Works on macOS, Linux, and Windows
### Auto-Run Options
- **Build + Auto-Run**: Single command to build and launch
- **Smart Detection**: Automatically chooses best available target
- **Error Handling**: Graceful fallbacks when devices unavailable
## Usage
### Auto-Run Script (Recommended)
```bash
# Auto-detect and run on all available platforms (development mode)
npm run auto-run
# Run in test mode
npm run auto-run:test
# Run in production mode
npm run auto-run:prod
# Target specific platforms
npm run auto-run:ios
npm run auto-run:android
npm run auto-run:electron
```
### Build Script Auto-Run
#### iOS Auto-Run Commands
```bash
# Test build + auto-run
npm run build:ios:test:run
# Production build + auto-run
npm run build:ios:prod:run
# Debug build + auto-run
npm run build:ios:debug:run
# Release build + auto-run
npm run build:ios:release:run
```
#### Android Auto-Run Commands
```bash
# Test build + auto-run
npm run build:android:test:run
# Production build + auto-run
npm run build:android:prod:run
# Debug build + auto-run
npm run build:android:debug:run
# Release build + auto-run
npm run build:android:release:run
```
#### Electron Auto-Run Commands
```bash
# Development build + auto-run
npm run build:electron:dev:run
# Test build + auto-run
npm run build:electron:test:run
# Production build + auto-run
npm run build:electron:prod:run
```
### Advanced Usage
```bash
# Direct script usage with options
./scripts/auto-run.sh --test --platform=ios
./scripts/auto-run.sh --prod --platform=android
./scripts/auto-run.sh --auto # Skip confirmation prompts
# Build script with auto-run flag
./scripts/build-ios.sh --test --auto-run
./scripts/build-android.sh --prod --auto-run
./scripts/build-electron.sh --test --auto-run
# Combine options
./scripts/auto-run.sh --test --platform=all --auto
```
### Command Line Options
| Option | Description | Example |
|--------|-------------|---------|
| `--test` | Build and run in test mode | `--test` |
| `--prod` | Build and run in production mode | `--prod` |
| `--platform=PLATFORM` | Target specific platform | `--platform=ios` |
| `--auto` | Skip confirmation prompts | `--auto` |
| `--auto-run` | Auto-run after build | `--auto-run` |
| `--help` | Show help message | `--help` |
**Platform Options:**
- `ios` - iOS devices/simulators only
- `android` - Android devices/emulators only
- `electron` - Electron desktop app only
- `all` - All available platforms (default)
## How It Works
### 1. Device Detection
**Android Detection:**
```bash
# Uses ADB to list devices
adb devices
# Parses output to distinguish:
# - Real devices: Physical Android phones/tablets
# - Emulators: Android emulator instances
```
**iOS Detection:**
```bash
# Uses xcrun to list devices
xcrun xctrace list devices
# Parses output to distinguish:
# - Real devices: Physical iPhones/iPads
# - Simulators: iOS Simulator instances
```
### 2. Build Process
The script automatically calls the appropriate build commands:
```bash
# Development mode
npm run build:ios:dev
npm run build:android:dev
npm run build:electron:dev
# Test mode
npm run build:ios:test
npm run build:android:test
npm run build:electron:test
# Production mode
npm run build:ios:prod
npm run build:android:prod
npm run build:electron:prod
```
### 3. Launch Process
**Android:**
- Real devices: Install APK and launch via ADB
- Emulators: Use `npx cap run android`
**iOS:**
- Real devices: Build release version (requires Xcode setup)
- Simulators: Use `npx cap run ios`
**Electron:**
- Launch via `npm run electron:start`
## Examples
### Development Workflow
```bash
# Quick development run
npm run auto-run
# Output:
# ✅ Found 1 real Android device: ABC123DEF456
# ✅ Found 1 iOS simulator: iPhone 15 Pro
# ✅ Electron: available
#
# Available targets:
# Android: real:ABC123DEF456
# iOS: simulator:iPhone 15 Pro
# Electron: available
#
# Continue with auto-run? (y/N): y
#
# 🔄 Building and running Android (real: ABC123DEF456)...
# 🔄 Building and running iOS (simulator: iPhone 15 Pro)...
# 🔄 Building and running Electron...
#
# ✅ Auto-run completed successfully! 3 platform(s) launched.
```
### Test Mode with Build Scripts
```bash
# iOS test build + auto-run
npm run build:ios:test:run
# Android test build + auto-run
npm run build:android:test:run
# Electron test build + auto-run
npm run build:electron:test:run
# Output:
# === TimeSafari iOS Build Process ===
# 🔄 Building Capacitor version (test)...
# 🔄 Syncing with Capacitor...
# 🔄 Building iOS app...
# 🔄 Auto-running iOS app...
# ✅ iOS app launched successfully!
# ✅ iOS build completed successfully!
```
### Production Mode
```bash
# Production build and run
npm run auto-run:prod
# Output:
# 🔄 Building Android (production)...
# 🔄 Building iOS (production)...
# 🔄 Building Electron (production)...
#
# ✅ Auto-run completed successfully! 3 platform(s) launched.
```
## Comparison: Auto-Run Script vs Build Scripts
### Auto-Run Script (`auto-run.sh`)
**Best for:**
- Multi-platform development
- Quick testing across devices
- Automated workflows
- CI/CD integration
**Features:**
- Smart device detection
- Multi-platform support
- Interactive confirmation
- Error recovery
### Build Scripts with `--auto-run`
**Best for:**
- Single platform development
- Specific build configurations
- Non-interactive workflows
- Build customization
**Features:**
- Platform-specific optimization
- Build customization options
- Direct control over build process
- Integration with existing workflows
## Troubleshooting
### Common Issues
**No devices detected:**
```bash
# Check Android devices
adb devices
# Check iOS devices (macOS only)
xcrun xctrace list devices
# Check Electron availability
which electron
```
**Build failures:**
```bash
# Clean and rebuild
npm run clean:android
npm run clean:ios
npm run clean:electron
# Then retry auto-run
npm run auto-run
```
**Permission issues:**
```bash
# Make script executable
chmod +x scripts/auto-run.sh
# Check ADB permissions (Android)
adb kill-server
adb start-server
```
### Platform-Specific Issues
**Android:**
- Ensure ADB is in PATH
- Enable USB debugging on device
- Accept device authorization prompt
- Check device is in "device" state (not "unauthorized")
**iOS:**
- Requires macOS with Xcode
- Ensure Xcode command line tools installed
- Check iOS Simulator is available
- For real devices: Requires proper certificates
**Electron:**
- Ensure Electron is installed globally or locally
- Check Node.js version compatibility
- Verify build dependencies are installed
### Debug Mode
Enable verbose logging by modifying the script:
```bash
# Add debug logging to auto-run.sh
set -x # Enable debug mode
```
## Integration with CI/CD
The auto-run script can be integrated into CI/CD pipelines:
```yaml
# Example GitHub Actions workflow
- name: Auto-run tests
run: |
npm run auto-run:test --auto
env:
# Set environment variables for CI
CI: true
```
## Best Practices
### Development Workflow
1. **Daily development**: Use `npm run auto-run` for quick testing
2. **Testing**: Use `npm run auto-run:test` before commits
3. **Production**: Use `npm run auto-run:prod` for final testing
4. **Single platform**: Use `npm run build:ios:test:run` for focused work
### Device Management
1. **Keep devices connected**: Reduces detection time
2. **Use consistent device names**: Helps with identification
3. **Regular cleanup**: Clear old builds and caches
### Performance Tips
1. **Use --auto flag**: Skip prompts in automated workflows
2. **Target specific platforms**: Use `--platform=ios` for faster runs
3. **Parallel execution**: Script runs platforms in sequence (can be optimized)
## Future Enhancements
### Planned Features
- **Parallel execution**: Run multiple platforms simultaneously
- **Device selection**: Choose specific devices when multiple available
- **Custom build configurations**: Support for custom build modes
- **Integration with IDEs**: VS Code and other IDE integration
- **Performance monitoring**: Track build and launch times
### Contributing
To add new features or fix issues:
1. Modify `scripts/auto-run.sh`
2. Update this documentation
3. Test on multiple platforms
4. Submit pull request
## Related Documentation
- [iOS Simulator Build and Icons](./ios-simulator-build-and-icons.md)
- [Android Build Guide](./android-build-guide.md)
- [Electron Build Guide](./electron-build-guide.md)
- [Testing Guide](./testing-guide.md)

379
docs/build-system/automation/cefpython-implementation-guide.md

@ -1,379 +0,0 @@
# CEFPython Implementation Guide (Revised)
**Author**: Matthew Raymer
**Date**: 2025-07-12
**Status**: ✨ **PLANNING** - Ready for Implementation
## Overview
This guide outlines the implementation of CEFPython to deliver the TimeSafari Vue.js application as a native desktop experience. It details the integration of Chromium Embedded Framework (CEF) with a Python backend for desktop-specific operations.
## Architecture
### High-Level Diagram
```
TimeSafari CEFPython Architecture
├── Python Backend (CEFPython)
│ ├── CEF Browser Window
│ ├── SQLite Database Access
│ ├── File System Operations
│ └── Native OS Integration
├── Vue.js Frontend (Unchanged)
│ ├── Existing Components
│ ├── Platform Service Integration
│ └── Database Operations
└── Platform Service Bridge
├── CEFPython Platform Service
├── IPC Communication
└── Native API Exposure
```
### Platform Service
A TypeScript class will act as the interface between the Vue frontend and the Python backend:
```typescript
export class CEFPythonPlatformService implements PlatformService {
async dbQuery(sql: string, params?: any[]): Promise<any[]> {
// Call Python backend via IPC
}
async exportData(fileName: string, data: string): Promise<ExportResult> {
// Call file export via IPC
}
async getPlatformInfo(): Promise<PlatformInfo> {
return {
platform: 'cefpython',
capabilities: ['sqlite', 'filesystem', 'native-ui']
};
}
}
```
## Implementation Plan
### Phase 1: Foundation Setup (Week 1)
- [ ] Install CEFPython dependencies
- [ ] Create Python virtual environment
- [ ] Set up development and build tools
- [ ] Create and test minimal CEFPython app
- [ ] Create IPC and platform service skeleton
### Phase 2: SQLite Database (Week 2)
- [ ] Implement Python SQLite wrapper
- [ ] Setup schema initialization
- [ ] Bridge database ops over IPC
- [ ] Test queries and data integrity
### Phase 3: Native OS Integration (Week 3)
- [ ] Implement file import/export
- [ ] Add system tray and notifications
- [ ] Test native menu hooks and permissions
### Phase 4: Build & Packaging (Week 4)
- [ ] Create packaging and build scripts
- [ ] Integrate with existing npm build
- [ ] Automate cross-platform distribution
## Backend Implementation
### Main Entry
```python
# main.py
import cefpython3.cefpython as cef
from platform_service import CEFPythonPlatformService
from ipc_bridge import IPCBridge
class TimeSafariApp:
def __init__(self):
self.platform_service = CEFPythonPlatformService()
self.cef_settings = {
"debug": False,
"log_severity": cef.LOGSEVERITY_ERROR,
"log_file": "cef.log",
"multi_threaded_message_loop": True,
}
def initialize(self):
cef.Initialize(settings=self.cef_settings)
self.browser = cef.CreateBrowserSync(
url=f"file://{os.path.abspath('dist/index.html')}"
)
self.ipc = IPCBridge(self.browser, self.platform_service)
def run(self):
cef.MessageLoop()
cef.Shutdown()
```
### Platform Service (Python)
Handles local database and file system access:
```python
class CEFPythonPlatformService:
def __init__(self):
self.db_path = self._get_db_path()
self._init_schema()
def db_query(self, sql, params=None):
with sqlite3.connect(self.db_path, check_same_thread=False) as conn:
conn.row_factory = sqlite3.Row
return [dict(row) for row in conn.execute(sql, params or [])]
def db_exec(self, sql, params=None):
with sqlite3.connect(self.db_path, check_same_thread=False) as conn:
cur = conn.execute(sql, params or [])
conn.commit()
return {"changes": cur.rowcount, "lastId": cur.lastrowid}
def export_data(self, file_name, data):
try:
path = os.path.join(self._get_downloads(), file_name)
with open(path, 'w') as f:
f.write(data)
return {"success": True, "path": path}
except Exception as e:
return {"success": False, "error": str(e)}
```
### IPC Bridge
Handles communication from JavaScript:
```python
class IPCBridge:
def __init__(self, browser, platform_service):
self.browser = browser
self.platform_service = platform_service
bindings = cef.JavascriptBindings()
bindings.SetFunction("callPython", self.call)
self.browser.SetJavascriptBindings(bindings)
def call(self, name, args):
handlers = {
"dbQuery": self.platform_service.db_query,
"dbExec": self.platform_service.db_exec,
"exportData": self.platform_service.export_data
}
try:
return {"success": True, "data": handlers[name](*args)}
except Exception as e:
return {"success": False, "error": str(e)}
```
## Build & Packaging
Shell script with build modes:
```bash
npm run build:web:dev
./scripts/build-cefpython.sh --dev
```
Includes PyInstaller packaging:
```bash
pyinstaller --onefile --windowed --name TimeSafari main.py
```
## Package.json Integration
### CEFPython Build Scripts
```json
{
"scripts": {
// CEFPython builds
"build:cefpython": "./scripts/build-cefpython.sh",
"build:cefpython:dev": "./scripts/build-cefpython.sh --dev",
"build:cefpython:test": "./scripts/build-cefpython.sh --test",
"build:cefpython:prod": "./scripts/build-cefpython.sh --prod",
"build:cefpython:package": "./scripts/build-cefpython.sh --prod --package",
// Legacy aliases
"build:desktop:cef": "npm run build:cefpython",
"build:desktop:cef:dev": "npm run build:cefpython:dev",
"build:desktop:cef:prod": "npm run build:cefpython:prod"
}
}
```
## Platform Service Factory Integration
### Update PlatformServiceFactory
```typescript
// src/services/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";
switch (platform) {
case "cefpython":
PlatformServiceFactory.instance = new CEFPythonPlatformService();
break;
case "electron":
PlatformServiceFactory.instance = new ElectronPlatformService();
break;
case "capacitor":
PlatformServiceFactory.instance = new CapacitorPlatformService();
break;
default:
PlatformServiceFactory.instance = new WebPlatformService();
}
}
return PlatformServiceFactory.instance;
}
}
```
## Development Workflow
```bash
cd cefpython
pip install -r requirements.txt
npm run build:cefpython:dev
```
## Platform Considerations
### Windows
- VC++ Redistributable
- Registry for settings
### macOS
- macOS 10.14+
- Handle App Sandbox
### Linux
- GTK dependencies
- Provide `.desktop` launcher
## Security Considerations
- CEF sandboxing
- File and IPC validation
- Data encryption & key management
- Code signing & integrity checks
## Performance Optimization
### 1. Memory Management
- Implement proper cleanup
- Monitor memory usage
- Optimize database queries
- Handle large datasets
### 2. Startup Time
- Optimize application startup
- Implement lazy loading
- Cache frequently used data
- Minimize initialization overhead
### 3. Resource Usage
- Monitor CPU usage
- Optimize rendering
- Handle background tasks
- Implement resource limits
## Testing
- Unit tests for each service
- Integration for IPC and file access
- End-to-end for user workflows
## Issues & Suggestions for Improvement
### 1. IPC Registration Missing in Initial Version
You must explicitly bind Python functions to JS:
```python
bindings.SetFunction("callPython", self.call)
```
### 2. Incorrect `IPCBridge` Constructor in Early Draft
Original:
```python
def __init__(self, browser):
```
Fixed:
```python
def __init__(self, browser, platform_service):
```
### 3. SQLite Threading Caveat
Add `check_same_thread=False` or use a threading queue to avoid crashes from multi-threaded access.
### 4. No Vue IPC Access Description
Specify the frontend JS API for calling Python:
```javascript
window.callPython('dbQuery', ['SELECT * FROM accounts'])
```
### 5. Missing Cleanup in Unit Tests
Add teardown for exported files to avoid clutter and permissions issues.
### 6. Logging
Add `logging` or `structlog` to the Python service and bridge for auditability.
## Troubleshooting
### Common Issues
#### 1. CEF Initialization Failures
```bash
# Check CEF installation
python -c "import cefpython3; print('CEF installed')"
# Verify dependencies
pip list | grep cefpython3
```
#### 2. Database Access Issues
```bash
# Check database permissions
ls -la ~/.local/share/timesafari/
# Verify SQLite installation
python -c "import sqlite3; print('SQLite available')"
```
#### 3. Build Failures
```bash
# Clean and rebuild
rm -rf cefpython/dist/
rm -rf cefpython/build/
npm run build:cefpython:dev
```
### Debug Mode
```python
# Enable debug logging
cef_settings = {
"debug": True,
"log_severity": cef.LOGSEVERITY_VERBOSE,
"log_file": "cef_debug.log",
}
```
## Conclusion
This guide offers a clear and technically complete roadmap for integrating CEFPython with TimeSafari. By implementing the suggestions above, the solution will be production-ready with complete platform service integration, desktop capability, and a stable build process.
**Effort**: 4 weeks
**Priority**: Medium
**Dependencies**: Python 3.8+, CEFPython
**Stakeholders**: Desktop development team, users

616
docs/build-system/core/build-pattern-conversion-plan.md

@ -1,616 +0,0 @@
# Build Pattern Conversion Plan
**Author**: Matthew Raymer
**Date**: 2025-07-09
**Status**: **PLANNING** - Ready for Implementation
## Overview
Convert TimeSafari's build instruction pattern from the current script-based
approach to a new Vite `mode`-based pattern that provides better environment
management and consistency across all build targets.
## Why Vite Mode Instead of NODE_ENV?
### Vite's Native Mode System
Vite is designed to work with `mode`, which:
- Determines the `.env` file to load (e.g. `.env.production`, `.env.test`, etc.)
- Is passed to `defineConfig(({ mode }) => {...})` in `vite.config.ts`
- Is used to set behavior for dev/prod/test at config level
- Provides better integration with Vite's build system
### NODE_ENV Limitations
`NODE_ENV` is legacy from Webpack-era tooling:
- You can't change `NODE_ENV` manually and expect Vite to adapt
- Vite does not map `NODE_ENV` back to `mode`
- It's redundant with `mode` and might conflict with assumptions
- Limited integration with Vite's environment loading system
### Usage Pattern
```bash
# Correct: Use Vite's mode system
vite build --mode production
vite build --mode development
vite build --mode test
# Only if third-party libraries require NODE_ENV
NODE_ENV=production vite build --mode production
```
### Development vs Build Environments
**Development Environment:**
- **Build with defaults**: `npm run build:*` - Uses `--mode development` by default
- **Purpose**: Development builds for testing and debugging
- **Output**: Bundled files with development optimizations
**Testing/Production Environments:**
- **Build with explicit mode**: `npm run build:* -- --mode test/production`
- **Purpose**: Validate and deploy the bundled application
- **Output**: Optimized, bundled files for specific environment
### Mode Override Behavior
**How `--mode` Override Works:**
```bash
# Base script (no hardcoded mode)
"build:electron": "vite build --config vite.config.electron.mts"
# Development (uses Vite's default: --mode development)
npm run build:electron
# Executes: vite build --config vite.config.electron.mts
# Testing (explicitly overrides with --mode test)
npm run build:electron -- --mode test
# Executes: vite build --config vite.config.electron.mts --mode test
# Production (explicitly overrides with --mode production)
npm run build:electron -- --mode production
# Executes: vite build --config vite.config.electron.mts --mode production
```
**Key Points:**
- Base scripts have **no hardcoded `--mode`** to allow override
- `npm run build:electron` defaults to `--mode development`
- `npm run build:electron -- --mode test` overrides to `--mode test`
- Vite uses the **last `--mode` argument** if multiple are provided
### Capacitor Platform-Specific Commands
Capacitor requires platform-specific sync commands after building:
```bash
# General sync (copies web assets to all platforms)
npm run build:capacitor && npx cap sync
# Platform-specific sync
npm run build:capacitor && npx cap sync android
npm run build:capacitor && npx cap sync ios
# Environment-specific with platform sync
npm run build:capacitor -- --mode production && npx cap sync android
npm run build:capacitor -- --mode development && npx cap sync ios
```
### Docker Build Commands
Docker builds include both Vite asset generation and Docker image creation:
```bash
# General Docker build (Vite build + Docker image)
npm run build:web:docker
# Environment-specific Docker builds
npm run build:web:docker:test # Test environment + Docker image
npm run build:web:docker:prod # Production environment + Docker image
# Manual mode overrides for Docker builds
npm run build:web:docker -- --mode test
npm run build:web:docker -- --mode production
```
**Docker Build Process:**
1. **Vite Build**: Creates optimized web assets with environment-specific variables
2. **Docker Build**: Creates Docker image using `Dockerfile` in project root
3. **Image Tagging**: Images are tagged as `timesafari-web` for consistent management
**Key Features:**
- Complete end-to-end Docker workflow in single command
- Environment-aware builds (test/production configurations)
- Consistent image tagging for deployment
- Mode override flexibility for custom environments
### Electron Platform-Specific Commands
Electron requires platform-specific build commands after the Vite build:
```bash
# General Electron build (Vite build only)
npm run build:electron
# Platform-specific builds
npm run build:electron:windows # Windows executable
npm run build:electron:mac # macOS app bundle
npm run build:electron:linux # Linux executable
# Package-specific builds
npm run build:electron:appimage # Linux AppImage
npm run build:electron:dmg # macOS DMG installer
# Environment-specific builds
npm run build:electron -- --mode development
npm run build:electron -- --mode test
npm run build:electron -- --mode production
# Environment-specific with platform builds
npm run build:electron:windows -- --mode development
npm run build:electron:windows -- --mode test
npm run build:electron:windows -- --mode production
npm run build:electron:mac -- --mode development
npm run build:electron:mac -- --mode test
npm run build:electron:mac -- --mode production
npm run build:electron:linux -- --mode development
npm run build:electron:linux -- --mode test
npm run build:electron:linux -- --mode production
# Environment-specific with package builds
npm run build:electron:appimage -- --mode development
npm run build:electron:appimage -- --mode test
npm run build:electron:appimage -- --mode production
npm run build:electron:dmg -- --mode development
npm run build:electron:dmg -- --mode test
npm run build:electron:dmg -- --mode production
```
## Current State Analysis
### Existing Build Scripts
- **Web**: `build:web` - Uses vite.config.web.mts
- **Capacitor**: `build:capacitor` - Uses vite.config.capacitor.mts
- **Android**: `build:android` - Shell script wrapper
- **iOS**: `build:ios` - Shell script wrapper
- **Electron**: `build:electron` - Uses vite.config.electron.mts
- **Windows**: `build:electron:windows` - Windows executable
- **macOS**: `build:electron:mac` - macOS app bundle
- **Linux**: `build:electron:linux` - Linux executable
- **AppImage**: `build:electron:appimage` - Linux AppImage
- **DMG**: `build:electron:dmg` - macOS DMG installer
### Current `package.json` Scripts
```json
{
"build:capacitor": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --mode capacitor --config vite.config.capacitor.mts",
"build:web": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.web.mts",
"build:electron": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --mode electron --config vite.config.electron.mts"
}
```
## Target Pattern
### New Vite Mode-Based Pattern
```bash
# Development builds (defaults to --mode development)
npm run build:web-dev
npm run build:capacitor-dev
npm run build:electron-dev
# Testing builds (bundle required)
npm run build:web -- --mode test
npm run build:capacitor -- --mode test && npx cap sync
npm run build:electron -- --mode test
# Production builds (bundle required)
npm run build:web -- --mode production
npm run build:capacitor -- --mode production && npx cap sync
npm run build:electron -- --mode production
# Docker builds
npm run build:web:docker -- --mode test
npm run build:web:docker -- --mode production
# Docker environment-specific builds
npm run build:web:docker:test
npm run build:web:docker:prod
# Capacitor platform-specific builds
npm run build:capacitor:android -- --mode test
npm run build:capacitor:android -- --mode production
npm run build:capacitor:ios -- --mode test
npm run build:capacitor:ios -- --mode production
# Electron platform-specific builds
npm run build:electron:windows -- --mode test
npm run build:electron:windows -- --mode production
npm run build:electron:mac -- --mode test
npm run build:electron:mac -- --mode production
npm run build:electron:linux -- --mode test
npm run build:electron:linux -- --mode production
# Electron package-specific builds
npm run build:electron:appimage -- --mode test
npm run build:electron:appimage -- --mode production
npm run build:electron:dmg -- --mode test
npm run build:electron:dmg -- --mode production
```
### New `package.json` Scripts Structure
```json
{
"build:web": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite --mode development --config vite.config.web.mts",
"build:web:dev": "npm run build:web",
"build:web:build": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --mode development --config vite.config.web.mts",
"build:web:test": "npm run build:web:build -- --mode test",
"build:web:prod": "npm run build:web:build -- --mode production",
"build:web:docker": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.web.mts && docker build -t timesafari-web .",
"build:web:docker:test": "npm run build:web:docker -- --mode test",
"build:web:docker:prod": "npm run build:web:docker -- --mode production",
"build:capacitor": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --mode capacitor --config vite.config.capacitor.mts",
"build:capacitor-dev": "npm run build:capacitor",
"build:capacitor:sync": "npm run build:capacitor && npx cap sync",
"build:capacitor:android": "npm run build:capacitor:sync && npx cap sync android",
"build:capacitor:ios": "npm run build:capacitor:sync && npx cap sync ios",
"build:electron": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.electron.mts",
"build:electron:dev": "npm run build:electron && cd electron && npm run electron:start",
"build:electron:windows": "npm run build:electron && cd electron && npm run build:windows",
"build:electron:mac": "npm run build:electron && cd electron && npm run build:mac",
"build:electron:linux": "npm run build:electron && cd electron && npm run build:linux",
"build:electron:appimage": "npm run build:electron:linux && cd electron && npm run build:appimage",
"build:electron:dmg": "npm run build:electron:mac && cd electron && npm run build:dmg"
}
```
## Implementation Plan
### Phase 1: Environment Configuration (Day 1)
#### 1.1 Update Vite Configurations
- [ ] **vite.config.web.mts**: Add mode-based configuration
- [ ] **vite.config.capacitor.mts**: Add mode-based configuration
- [ ] **vite.config.electron.mts**: Add mode-based configuration
- [ ] **vite.config.common.mts**: Add environment-specific variables
#### 1.2 Environment Variables Setup
- [ ] Create `.env.development` file for development settings
- [ ] Create `.env.test` file for testing settings
- [ ] Create `.env.production` file for production settings
- [ ] Update `.env.example` with new pattern
#### 1.3 Environment Detection Logic
```typescript
// vite.config.common.mts
export default defineConfig(({ mode }) => {
const getEnvironmentConfig = (mode: string) => {
switch (mode) {
case 'production':
return { /* production settings */ };
case 'test':
return { /* testing settings */ };
default:
return { /* development settings */ };
}
};
return {
define: {
__DEV__: mode === 'development',
__TEST__: mode === 'test',
__PROD__: mode === 'production'
},
// ... other config
};
});
```
### Phase 2: Package.json Scripts Update (Day 1)
#### 2.1 Web Build Scripts
```json
{
"build:web": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.web.mts",
"build:web-dev": "npm run build:web",
"build:web-test": "npm run build:web -- --mode test",
"build:web-prod": "npm run build:web -- --mode production"
}
```
#### 2.2 Capacitor Build Scripts
```json
{
"build:capacitor": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --mode capacitor --config vite.config.capacitor.mts",
"build:capacitor-dev": "npm run build:capacitor",
"build:capacitor:sync": "npm run build:capacitor && npx cap sync",
"build:capacitor:android": "npm run build:capacitor:sync && npx cap sync android",
"build:capacitor:ios": "npm run build:capacitor:sync && npx cap sync ios",
"build:capacitor-test": "npm run build:capacitor -- --mode test && npx cap sync",
"build:capacitor-prod": "npm run build:capacitor -- --mode production && npx cap sync",
"build:capacitor:android-test": "npm run build:capacitor -- --mode test && npx cap sync android",
"build:capacitor:android-prod": "npm run build:capacitor -- --mode production && npx cap sync android",
"build:capacitor:ios-test": "npm run build:capacitor -- --mode test && npx cap sync ios",
"build:capacitor:ios-prod": "npm run build:capacitor -- --mode production && npx cap sync ios"
}
```
#### 2.3 Electron Build Scripts
```json
{
"build:electron": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.electron.mts",
"build:electron-dev": "npm run build:electron",
"build:electron:windows": "npm run build:electron && cd electron && npm run build:windows",
"build:electron:mac": "npm run build:electron && cd electron && npm run build:mac",
"build:electron:linux": "npm run build:electron && cd electron && npm run build:linux",
"build:electron:appimage": "npm run build:electron:linux && cd electron && npm run build:appimage",
"build:electron:dmg": "npm run build:electron:mac && cd electron && npm run build:dmg",
"build:electron-test": "npm run build:electron -- --mode test",
"build:electron-prod": "npm run build:electron -- --mode production",
"build:electron:windows-test": "npm run build:electron -- --mode test && cd electron && npm run build:windows",
"build:electron:windows-prod": "npm run build:electron -- --mode production && cd electron && npm run build:windows",
"build:electron:mac-dev": "npm run build:electron -- --mode development && cd electron && npm run build:mac",
"build:electron:mac-test": "npm run build:electron -- --mode test && cd electron && npm run build:mac",
"build:electron:mac-prod": "npm run build:electron -- --mode production && cd electron && npm run build:mac",
"build:electron:linux-test": "npm run build:electron -- --mode test && cd electron && npm run build:linux",
"build:electron:linux-prod": "npm run build:electron -- --mode production && cd electron && npm run build:linux"
}
```
#### 2.4 Docker Build Scripts
```json
{
"build:web:docker": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.web.mts && docker build -t timesafari-web .",
"build:web:docker:test": "npm run build:web:docker -- --mode test",
"build:web:docker:prod": "npm run build:web:docker -- --mode production"
}
```
**Docker Build Features:**
- Complete Vite build + Docker image creation workflow
- Environment-specific configurations (test/production)
- Consistent image tagging (`timesafari-web`)
- Mode override flexibility for custom environments
### Phase 3: Shell Script Updates (Day 2)
#### 3.1 Update build-electron.sh
- [ ] Add mode-based environment support
- [ ] Update environment loading logic
- [ ] Add environment-specific build paths
- [ ] Update logging to show environment
#### 3.2 Update build-android.sh
- [ ] Add mode-based environment support
- [ ] Update environment detection
- [ ] Add environment-specific configurations
#### 3.3 Update build-ios.sh
- [ ] Add mode-based environment support
- [ ] Update environment detection
- [ ] Add environment-specific configurations
### Phase 4: Documentation Updates (Day 2)
#### 4.1 Update BUILDING.md
- [ ] Document new Vite mode-based pattern
- [ ] Update build instructions
- [ ] Add environment-specific examples
- [ ] Update troubleshooting section
#### 4.2 Update scripts/README.md
- [ ] Document new Vite mode-based build patterns
- [ ] Update usage examples
- [ ] Add environment configuration guide
#### 4.3 Update CI/CD Documentation
- [ ] Update GitHub Actions workflows
- [ ] Update Docker build instructions
- [ ] Update deployment guides
### Phase 5: Testing & Validation (Day 3)
#### 5.1 Environment Testing
- [ ] Test dev environment builds
- [ ] Test test environment builds
- [ ] Test prod environment builds
- [ ] Validate environment variables
#### 5.2 Platform Testing
- [ ] Test web builds across environments
- [ ] Test capacitor builds across environments
- [ ] Test capacitor android sync across environments
- [ ] Test capacitor ios sync across environments
- [ ] Test electron builds across environments
- [ ] Test electron windows builds across environments
- [ ] Test electron mac builds across environments
- [ ] Test electron linux builds across environments
- [ ] Test electron appimage builds across environments
- [ ] Test electron dmg builds across environments
- [ ] Test docker builds across environments
- [ ] Test docker image creation and tagging
- [ ] Test docker environment-specific configurations
#### 5.3 Integration Testing
- [ ] Test with existing CI/CD pipelines
- [ ] Test with existing deployment scripts
- [ ] Test with existing development workflows
## Environment-Specific Configurations
### Development Environment (--mode development)
```typescript
{
VITE_API_URL: 'http://localhost:3000',
VITE_DEBUG: 'true',
VITE_LOG_LEVEL: 'debug',
VITE_ENABLE_DEV_TOOLS: 'true'
}
```
### Testing Environment (--mode test)
```typescript
{
VITE_API_URL: 'https://test-api.timesafari.com',
VITE_DEBUG: 'false',
VITE_LOG_LEVEL: 'info',
VITE_ENABLE_DEV_TOOLS: 'false'
}
```
### Production Environment (--mode production)
```typescript
{
VITE_API_URL: 'https://api.timesafari.com',
VITE_DEBUG: 'false',
VITE_LOG_LEVEL: 'warn',
VITE_ENABLE_DEV_TOOLS: 'false'
}
```
## Migration Strategy
### Backward Compatibility
- [ ] Keep existing script names as aliases
- [ ] Add deprecation warnings for old scripts
- [ ] Maintain existing CI/CD compatibility
- [ ] Provide migration guide for users
### Gradual Rollout
1. **Week 1**: Implement new scripts alongside existing ones
2. **Week 2**: Update CI/CD to use new pattern
3. **Week 3**: Update documentation and guides
4. **Week 4**: Deprecate old scripts with warnings
## Success Metrics
### Technical Metrics
- [ ] All builds work with Vite mode-based pattern
- [ ] Environment variables properly loaded
- [ ] Build artifacts correctly generated
- [ ] No regression in existing functionality
### Process Metrics
- [ ] Reduced build script complexity
- [ ] Improved environment management
- [ ] Better developer experience
- [ ] Consistent build patterns
## Risk Assessment
### Low Risk
- [ ] Environment variable changes
- [ ] Package.json script updates
- [ ] Documentation updates
### Medium Risk
- [ ] Vite configuration changes (mode-based)
- [ ] Shell script modifications
- [ ] CI/CD pipeline updates
### High Risk
- [ ] Breaking existing build processes
- [ ] Environment-specific bugs
- [ ] Deployment failures
## Rollback Plan
### Immediate Rollback
- [ ] Revert package.json changes
- [ ] Restore original vite configs
- [ ] Restore original shell scripts
### Gradual Rollback
- [ ] Keep old scripts as primary
- [ ] Use new scripts as experimental
- [ ] Gather feedback before full migration
## Timeline
### Day 1: Foundation
- [ ] Environment configuration setup
- [ ] Package.json script updates
- [ ] Basic testing
### Day 2: Integration
- [ ] Shell script updates
- [ ] Documentation updates
- [ ] Integration testing
### Day 3: Validation
- [ ] Comprehensive testing
- [ ] Performance validation
- [ ] Documentation review
### Day 4: Deployment
- [ ] CI/CD updates
- [ ] Production validation
- [ ] User communication
## Next Steps
1. **Review and approve plan**
2. **Set up development environment**
3. **Begin Phase 1 implementation**
4. **Create test cases**
5. **Start implementation**
---
**Status**: Ready for implementation
**Priority**: Medium
**Estimated Effort**: 3-4 days
**Dependencies**: None
**Stakeholders**: Development team, DevOps team

470
docs/build-system/core/build-systems-overview.md

@ -1,470 +0,0 @@
# TimeSafari Build Systems Overview
**Author**: Matthew Raymer
**Date**: 2025-07-11
**Status**: ✅ **COMPLETE** - All build systems documented and integrated
## Overview
TimeSafari supports multiple platforms and build targets through a unified build system architecture. This document provides a comprehensive overview of all build systems, their purposes, and how they work together.
## Build System Architecture
### Platform Support Matrix
| Platform | Build Script | Development | Testing | Production | Package Types |
|----------|--------------|-------------|---------|------------|---------------|
| **Web** | `build-web.sh` | ✅ Dev Server | ✅ Test Build | ✅ Prod Build | Docker Images |
| **Android** | `build-android.sh` | ✅ Debug APK | ✅ Test APK | ✅ Release APK/AAB | APK, AAB |
| **iOS** | `build-ios.sh` | ✅ Debug App | ✅ Test App | ✅ Release App | IPA |
| **Electron** | `build-electron.sh` | ✅ Dev App | ✅ Test App | ✅ Prod App | AppImage, DEB, DMG, EXE |
### Build Script Locations
```bash
scripts/
├── build-web.sh # Web/PWA builds
├── build-android.sh # Android mobile builds
├── build-ios.sh # iOS mobile builds (future)
├── build-electron.sh # Desktop builds
└── common.sh # Shared build utilities
```
## Unified Build Pattern
All build scripts follow a consistent pattern:
### 1. **Environment Setup**
```bash
# Set platform-specific environment variables
VITE_PLATFORM=<platform>
PWA: automatically enabled for web platforms
VITE_GIT_HASH=<git-commit-hash>
```
### 2. **Argument Parsing**
```bash
# Consistent command-line interface
./scripts/build-<platform>.sh [--dev|--test|--prod] [options]
```
### 3. **Build Process**
```bash
# Standard build flow
1. Validate environment
2. Clean build artifacts
3. Build web assets (Vite)
4. Platform-specific build
5. Generate assets
6. Create packages (if requested)
```
### 4. **Error Handling**
```bash
# Consistent exit codes
1: Cleanup failed
2: Web build failed
3: Platform build failed
4: Asset generation failed
5: Package creation failed
```
## Web Build System
### Purpose
Builds the web application for browser and PWA deployment.
### Key Features
- **Development Server**: Hot reload with Vite
- **PWA Support**: Service workers and manifest generation
- **Docker Integration**: Containerized deployment
- **Environment Modes**: Development, test, production
### Usage Examples
```bash
# Development (starts dev server)
npm run build:web:dev
# Production build
npm run build:web:prod
# Docker deployment
npm run build:web:docker:prod
```
### Output
- **Development**: Vite dev server at http://localhost:8080
- **Production**: Static files in `dist/` directory
- **Docker**: Containerized application image
**Documentation**: [Web Build Scripts Guide](build-web-script-integration.md)
## Android Build System
### Purpose
Builds Android mobile applications using Capacitor and Gradle.
### Key Features
- **Capacitor Integration**: Web-to-native bridge
- **Gradle Builds**: APK and AAB generation
- **Asset Generation**: Icons and splash screens
- **Device Deployment**: Direct APK installation
### Usage Examples
```bash
# Development build
npm run build:android:dev
# Production APK
npm run build:android:prod
# Deploy to device
npm run build:android:deploy
```
### Output
- **Debug APK**: `android/app/build/outputs/apk/debug/app-debug.apk`
- **Release APK**: `android/app/build/outputs/apk/release/app-release.apk`
- **AAB Bundle**: `android/app/build/outputs/bundle/release/app-release.aab`
### Device Deployment
```bash
# Automatic deployment to connected device
npm run build:android:deploy
# Manual deployment
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
```
**Documentation**: [Android Build Scripts Guide](android-build-scripts.md)
## iOS Build System
### Purpose
Builds iOS mobile applications using Capacitor and Xcode.
### Key Features
- **Capacitor Integration**: Web-to-native bridge
- **Xcode Integration**: Native iOS builds
- **Asset Generation**: Icons and splash screens
- **Simulator Support**: iOS simulator testing
### Usage Examples
```bash
# Development build
npm run build:ios:dev
# Production build
npm run build:ios:prod
# Open Xcode
npm run build:ios:studio
```
### Output
- **Debug App**: `ios/App/build/Debug-iphonesimulator/App.app`
- **Release App**: `ios/App/build/Release-iphoneos/App.app`
- **IPA Package**: `ios/App/build/Release-iphoneos/App.ipa`
**Documentation**: [iOS Build Scripts Guide](ios-build-scripts.md) *(Future)*
## Electron Build System
### Purpose
Builds desktop applications for Windows, macOS, and Linux.
### Key Features
- **Cross-Platform**: Windows, macOS, Linux support
- **Package Formats**: AppImage, DEB, DMG, EXE
- **Development Mode**: Direct app execution
- **Single Instance**: Prevents multiple app instances
### Usage Examples
```bash
# Development (runs app directly)
npm run build:electron:dev
# Production AppImage
npm run build:electron:appimage:prod
# Production DMG
npm run build:electron:dmg:prod
```
### Output
- **Development**: App runs directly (no files created)
- **Packages**: Executables in `electron/dist/` directory
- **AppImage**: `TimeSafari-1.0.3-beta.AppImage`
- **DEB**: `TimeSafari_1.0.3-beta_amd64.deb`
- **DMG**: `TimeSafari-1.0.3-beta.dmg`
- **EXE**: `TimeSafari Setup 1.0.3-beta.exe`
**Documentation**: [Electron Build Scripts Guide](electron-build-scripts.md)
## Environment Management
### Environment Variables
All build systems use consistent environment variable patterns:
```bash
# Platform identification
VITE_PLATFORM=web|capacitor|electron
# PWA configuration
PWA: automatically enabled for web platforms
# Build information
VITE_GIT_HASH=<git-commit-hash>
DEBUG_MIGRATIONS=0|1
```
### Environment Files
```bash
.env.development # Development environment
.env.test # Testing environment
.env.production # Production environment
```
### Mode-Specific Configuration
Each build mode loads appropriate environment configuration:
- **Development**: Local development settings
- **Test**: Testing environment with test APIs
- **Production**: Production environment with live APIs
## Package.json Integration
### Script Organization
All build scripts are integrated into `package.json` with consistent naming:
```json
{
"scripts": {
// Web builds
"build:web": "./scripts/build-web.sh",
"build:web:dev": "./scripts/build-web.sh --dev",
"build:web:test": "./scripts/build-web.sh --test",
"build:web:prod": "./scripts/build-web.sh --prod",
// Android builds
"build:android": "./scripts/build-android.sh",
"build:android:dev": "./scripts/build-android.sh --dev",
"build:android:test": "./scripts/build-android.sh --test",
"build:android:prod": "./scripts/build-android.sh --prod",
// iOS builds
"build:ios": "./scripts/build-ios.sh",
"build:ios:dev": "./scripts/build-ios.sh --dev",
"build:ios:test": "./scripts/build-ios.sh --test",
"build:ios:prod": "./scripts/build-ios.sh --prod",
// Electron builds
"build:electron:dev": "./scripts/build-electron.sh --dev",
"build:electron:test": "./scripts/build-electron.sh --test",
"build:electron:prod": "./scripts/build-electron.sh --prod"
}
}
```
### Legacy Compatibility
Legacy scripts are maintained as aliases for backward compatibility:
```json
{
"scripts": {
// Legacy Android scripts (aliases)
"build:capacitor:android": "npm run build:android",
"build:capacitor:android:dev": "npm run build:android:dev",
"build:capacitor:android:test": "npm run build:android:test",
"build:capacitor:android:prod": "npm run build:android:prod"
}
}
```
## Build Artifacts
### Common Artifacts
All build systems generate consistent artifacts:
```bash
dist/ # Web build output
├── index.html # Main HTML file
├── assets/ # Compiled assets
├── manifest.webmanifest # PWA manifest
└── sw.js # Service worker
android/app/build/ # Android build output
├── outputs/apk/debug/ # Debug APKs
├── outputs/apk/release/ # Release APKs
└── outputs/bundle/release/ # AAB bundles
ios/App/build/ # iOS build output
├── Debug-iphonesimulator/ # Debug builds
└── Release-iphoneos/ # Release builds
electron/dist/ # Electron packages
├── *.AppImage # Linux AppImages
├── *.deb # Linux DEB packages
├── *.dmg # macOS DMG packages
└── *.exe # Windows installers
```
### Asset Generation
All platforms generate platform-specific assets:
```bash
# Icons and splash screens
npx capacitor-assets generate --android
npx capacitor-assets generate --ios
# PWA assets
npx vite build --config vite.config.web.mts
```
## Development Workflow
### Daily Development
```bash
# Web development
npm run build:web:dev # Starts dev server
# Android development
npm run build:android:dev # Builds debug APK
npm run build:android:deploy # Deploy to device
# Electron development
npm run build:electron:dev # Runs app directly
```
### Testing Workflow
```bash
# Test all platforms
npm run build:web:test
npm run build:android:test
npm run build:ios:test
npm run build:electron:test
```
### Production Workflow
```bash
# Build all platforms for production
npm run build:web:prod
npm run build:android:prod
npm run build:ios:prod
npm run build:electron:prod
# Create distribution packages
npm run build:electron:appimage:prod
npm run build:electron:dmg:prod
npm run build:electron:deb:prod
```
## Troubleshooting
### Common Issues
#### Build Failures
```bash
# Clean all build artifacts
npm run clean:all
# Rebuild from scratch
npm run build:<platform>:dev
```
#### Device Connection Issues
```bash
# Check Android device connection
adb devices
# Check iOS device connection
xcrun devicectl list devices
```
#### Environment Issues
```bash
# Verify environment variables
echo $VITE_PLATFORM
echo "PWA: automatically enabled for web platforms"
# Check environment files
ls -la .env*
```
### Debug Mode
Enable verbose logging for all build scripts:
```bash
# Verbose mode
./scripts/build-<platform>.sh --verbose
# Debug environment
DEBUG_MIGRATIONS=1 npm run build:<platform>:dev
```
## Performance Metrics
### Build Times (Typical)
| Platform | Development | Production | Package |
|----------|-------------|------------|---------|
| **Web** | 350ms | 8s | 12s |
| **Android** | 45s | 60s | 75s |
| **iOS** | 60s | 90s | 120s |
| **Electron** | 15s | 25s | 45s |
### Optimization Features
- **Incremental Builds**: Only rebuild changed files
- **Parallel Processing**: Multi-core build optimization
- **Caching**: Build artifact caching
- **Asset Optimization**: Image and code minification
## Security Considerations
### Build Security
- **Environment Isolation**: Separate dev/test/prod environments
- **Secret Management**: Secure handling of API keys
- **Code Signing**: Digital signatures for packages
- **Dependency Scanning**: Regular security audits
### Distribution Security
- **Package Verification**: Checksum validation
- **Code Signing**: Digital certificates for packages
- **Update Security**: Secure update mechanisms
- **Sandboxing**: Platform-specific security isolation
## Future Enhancements
### Planned Improvements
- **CI/CD Integration**: Automated build pipelines
- **Cross-Platform Testing**: Unified test framework
- **Performance Monitoring**: Build performance tracking
- **Asset Optimization**: Advanced image and code optimization
### Platform Expansion
- **Windows Store**: Microsoft Store packages
- **Mac App Store**: App Store distribution
- **Google Play**: Play Store optimization
- **App Store**: iOS App Store distribution
---
**Last Updated**: 2025-07-11
**Version**: 1.0.3-beta
**Status**: Production Ready

722
docs/build-system/core/build-troubleshooting.md

@ -1,722 +0,0 @@
# Build Systems Troubleshooting Guide
**Author**: Matthew Raymer
**Date**: 2025-07-11
**Status**: ✅ **COMPLETE** - Comprehensive troubleshooting for all build systems
## Overview
This guide provides comprehensive troubleshooting for all TimeSafari build systems, including common issues, solutions, and debugging techniques for web, Android, iOS, and Electron builds.
## Quick Diagnostic Commands
### Environment Check
```bash
# Check Node.js and npm versions
node --version
npm --version
# Check platform-specific tools
npx cap --version
npx vite --version
# Check environment variables
echo $VITE_PLATFORM
echo "PWA: automatically enabled for web platforms"
```
### Build System Status
```bash
# Check all build scripts exist
ls -la scripts/build-*.sh
# Check package.json scripts
npm run | grep build:
# Check build artifacts
ls -la dist/
ls -la android/app/build/
ls -la electron/dist/
```
## Web Build Issues
### Development Server Problems
#### Port Already in Use
```bash
# Check what's using port 8080
lsof -i :8080
# Kill the process
kill -9 <PID>
# Or use different port
npm run build:web:dev -- --port 8081
```
#### Hot Reload Not Working
```bash
# Clear browser cache
# DevTools > Application > Storage > Clear site data
# Restart dev server
npm run build:web:dev
# Check file watching
# Ensure no file system watcher limits
```
#### PWA Issues in Development
```bash
# Clear service worker
# DevTools > Application > Service Workers > Unregister
# Clear browser cache
# DevTools > Application > Storage > Clear site data
# Restart development server
npm run build:web:dev
```
### Production Build Issues
#### Build Fails with Errors
```bash
# Clean build artifacts
rm -rf dist/
# Clear npm cache
npm cache clean --force
# Reinstall dependencies
rm -rf node_modules/
npm install
# Rebuild
npm run build:web:prod
```
#### Large Bundle Size
```bash
# Analyze bundle
npm run build:web:prod
# Check dist/assets/ for large files
# Enable bundle analysis
npm install --save-dev vite-bundle-analyzer
# Add to vite.config.web.mts
```
#### PWA Not Working in Production
```bash
# Check manifest generation
ls -la dist/manifest.webmanifest
# Check service worker
ls -la dist/sw.js
# Verify HTTPS (required for PWA)
# Ensure site is served over HTTPS
```
### Docker Build Issues
#### Docker Build Fails
```bash
# Check Docker is running
docker --version
docker ps
# Clean Docker cache
docker system prune -a
# Rebuild without cache
docker build --no-cache -t timesafari-web:production .
```
#### Docker Image Too Large
```bash
# Use multi-stage builds
# Optimize base images
# Remove unnecessary files
# Analyze image layers
docker history timesafari-web:production
```
## Android Build Issues
### Build Process Failures
#### Gradle Build Fails
```bash
# Clean Gradle cache
cd android && ./gradlew clean && cd ..
# Clear Android build cache
rm -rf android/app/build/
rm -rf android/.gradle/
# Rebuild
npm run build:android:dev
```
#### Capacitor Sync Issues
```bash
# Clean Capacitor
npx cap clean android
# Reinstall Android platform
npx cap remove android
npx cap add android
# Sync manually
npx cap sync android
```
#### Resource Generation Fails
```bash
# Check source assets
ls -la assets/icon.png
ls -la assets/splash.png
# Regenerate assets
npx capacitor-assets generate --android
# Check generated resources
ls -la android/app/src/main/res/
```
### Device Deployment Issues
#### No Device Connected
```bash
# Check device connection
adb devices
# Enable USB debugging
# Settings > Developer options > USB debugging
# Install ADB drivers (Windows)
# Download from Google USB drivers
```
#### Device Unauthorized
```bash
# Check device for authorization dialog
# Tap "Allow USB debugging"
# Reset ADB
adb kill-server
adb start-server
# Check device again
adb devices
```
#### APK Installation Fails
```bash
# Uninstall existing app
adb uninstall app.timesafari.app
# Install fresh APK
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
# Check installation
adb shell pm list packages | grep timesafari
```
### Performance Issues
#### Slow Build Times
```bash
# Enable Gradle daemon
# Add to ~/.gradle/gradle.properties:
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.configureondemand=true
# Use incremental builds
# Only rebuild changed files
```
#### Large APK Size
```bash
# Enable APK splitting
# Add to android/app/build.gradle:
android {
splits {
abi {
enable true
reset()
include 'x86', 'x86_64', 'arm64-v8a', 'armeabi-v7a'
}
}
}
```
## Electron Build Issues
### Development Issues
#### App Won't Start
```bash
# Check Electron installation
npm list electron
# Clear Electron cache
rm -rf ~/.config/TimeSafari/
rm -rf ~/Library/Application\ Support/TimeSafari/
rm -rf %APPDATA%\TimeSafari
# Reinstall Electron
npm install electron
```
#### Single Instance Lock Issues
```bash
# Check lock file
ls -la ~/.timesafari-lock
# Remove lock file manually
rm -f ~/.timesafari-lock
# Restart app
npm run build:electron:dev
```
#### Database Issues
```bash
# Clear database
./scripts/clear-database.sh
# Check database files
ls -la ~/.config/TimeSafari/
ls -la ~/Library/Application\ Support/TimeSafari/
# Rebuild database
npm run build:electron:dev
```
### Package Build Issues
#### Package Creation Fails
```bash
# Check electron-builder
npm list electron-builder
# Clean package cache
rm -rf electron/dist/
rm -rf electron/node_modules/
# Reinstall dependencies
cd electron && npm install && cd ..
# Rebuild package
npm run build:electron:appimage:prod
```
#### Code Signing Issues
```bash
# Check certificates
# macOS: Keychain Access
# Windows: Certificate Manager
# Linux: Check certificate files
# Skip code signing for testing
# Add to electron-builder.config.json:
"forceCodeSigning": false
```
#### Platform-Specific Issues
##### Linux AppImage Issues
```bash
# Check AppImage creation
file electron/dist/*.AppImage
# Make executable
chmod +x electron/dist/*.AppImage
# Test AppImage
./electron/dist/*.AppImage
```
##### macOS DMG Issues
```bash
# Check DMG creation
file electron/dist/*.dmg
# Mount DMG
hdiutil attach electron/dist/*.dmg
# Check contents
ls -la /Volumes/TimeSafari/
```
##### Windows EXE Issues
```bash
# Check EXE creation
file electron/dist/*.exe
# Test installer
# Run the EXE file
# Check installation directory
```
## iOS Build Issues (Future)
### Xcode Issues
```bash
# Check Xcode installation
xcode-select --print-path
# Install command line tools
xcode-select --install
# Accept Xcode license
sudo xcodebuild -license accept
```
### Simulator Issues
```bash
# List available simulators
xcrun simctl list devices
# Boot simulator
xcrun simctl boot "iPhone 15 Pro"
# Reset simulator
xcrun simctl erase all
```
### Code Signing Issues
```bash
# Check certificates
security find-identity -v -p codesigning
# Check provisioning profiles
ls ~/Library/MobileDevice/Provisioning\ Profiles/
# Install certificate
# Use Keychain Access or Xcode
```
## Environment Issues
### Environment Variables
#### Missing Environment Variables
```bash
# Check environment files
ls -la .env*
# Set required variables
export VITE_PLATFORM=web
# Check in build script
echo $VITE_PLATFORM
echo "PWA: automatically enabled for web platforms"
```
#### Wrong Environment Loaded
```bash
# Check current environment
echo $NODE_ENV
# Force environment
NODE_ENV=production npm run build:web:prod
# Check environment file loading
# Verify .env.production exists
```
### Dependency Issues
#### Missing Dependencies
```bash
# Check package.json
cat package.json | grep -A 10 "dependencies"
# Install missing dependencies
npm install
# Check for peer dependencies
npm ls
```
#### Version Conflicts
```bash
# Check for conflicts
npm ls
# Update dependencies
npm update
# Force resolution
npm install --force
```
#### Platform-Specific Dependencies
```bash
# Check Capacitor plugins
npx cap ls
# Install missing plugins
npm install @capacitor/core @capacitor/cli
# Sync plugins
npx cap sync
```
## Performance Issues
### Build Performance
#### Slow Build Times
```bash
# Enable parallel processing
# Add to package.json scripts:
"build:parallel": "npm run build:web:prod & npm run build:android:prod & wait"
# Use incremental builds
# Only rebuild changed files
# Optimize file watching
# Increase file watcher limits
```
#### Memory Issues
```bash
# Increase Node.js memory
NODE_OPTIONS="--max-old-space-size=4096" npm run build:web:prod
# Check memory usage
top -p $(pgrep node)
# Optimize build process
# Use streaming builds
# Minimize memory usage
```
### Runtime Performance
#### App Performance Issues
```bash
# Profile application
# Use browser DevTools > Performance
# Use React/Vue DevTools
# Check bundle size
npm run build:web:prod
# Analyze dist/assets/
# Optimize code splitting
# Implement lazy loading
```
## Debugging Techniques
### Verbose Logging
#### Enable Verbose Mode
```bash
# Web builds
./scripts/build-web.sh --verbose
# Android builds
./scripts/build-android.sh --verbose
# Electron builds
./scripts/build-electron.sh --verbose
```
#### Debug Environment
```bash
# Enable debug logging
DEBUG_MIGRATIONS=1 npm run build:web:dev
# Check debug output
# Look for detailed error messages
# Check console output
```
### Log Analysis
#### Build Logs
```bash
# Capture build logs
npm run build:web:prod > build.log 2>&1
# Analyze logs
grep -i error build.log
grep -i warning build.log
# Check for specific issues
grep -i "failed\|error\|exception" build.log
```
#### Runtime Logs
##### Web Browser
```bash
# Open DevTools
# Console tab for JavaScript errors
# Network tab for API issues
# Application tab for storage issues
```
##### Android
```bash
# View Android logs
adb logcat | grep -i timesafari
# Filter by app
adb logcat | grep -i "app.timesafari.app"
```
##### Electron
```bash
# View Electron logs
# Check console output
# Check DevTools console
# Check main process logs
```
## Common Error Messages
### Web Build Errors
#### "Module not found"
```bash
# Check import paths
# Verify file exists
# Check case sensitivity
# Update import statements
```
#### "Port already in use"
```bash
# Kill existing process
lsof -i :8080
kill -9 <PID>
# Use different port
npm run build:web:dev -- --port 8081
```
### Android Build Errors
#### "Gradle build failed"
```bash
# Clean Gradle cache
cd android && ./gradlew clean && cd ..
# Check Gradle version
./android/gradlew --version
# Update Gradle wrapper
cd android && ./gradlew wrapper --gradle-version 8.13 && cd ..
```
#### "Device not found"
```bash
# Check device connection
adb devices
# Enable USB debugging
# Settings > Developer options > USB debugging
# Install drivers (Windows)
# Download Google USB drivers
```
### Electron Build Errors
#### "App already running"
```bash
# Remove lock file
rm -f ~/.timesafari-lock
# Kill existing processes
pkill -f "TimeSafari"
# Restart app
npm run build:electron:dev
```
#### "Code signing failed"
```bash
# Check certificates
# macOS: Keychain Access
# Windows: Certificate Manager
# Skip code signing for testing
# Add to electron-builder.config.json:
"forceCodeSigning": false
```
## Prevention Strategies
### Best Practices
#### Regular Maintenance
```bash
# Update dependencies regularly
npm update
# Clean build artifacts
npm run clean:all
# Check for security vulnerabilities
npm audit
# Update build tools
npm update -g @capacitor/cli
npm update -g electron-builder
```
#### Environment Management
```bash
# Use consistent environments
# Separate dev/test/prod configurations
# Version control environment files
# Document environment requirements
```
#### Testing
```bash
# Test builds regularly
npm run build:web:prod
npm run build:android:prod
npm run build:electron:prod
# Test on different platforms
# Verify all features work
# Check performance metrics
```
### Monitoring
#### Build Monitoring
```bash
# Track build times
# Monitor build success rates
# Check for performance regressions
# Monitor bundle sizes
```
#### Runtime Monitoring
```bash
# Monitor app performance
# Track error rates
# Monitor user experience
# Check platform-specific issues
```
---
**Last Updated**: 2025-07-11
**Version**: 1.0.3-beta
**Status**: Production Ready

363
docs/build-system/core/build-web-script-integration.md

@ -1,363 +0,0 @@
# Build Web Script Integration
**Author**: Matthew Raymer
**Date**: 2025-07-11
**Status**: ✅ **COMPLETE** - Successfully implemented and tested
## Overview
The `build-web.sh` script has been successfully integrated into the TimeSafari build system, providing a unified approach to web builds that eliminates the need for multiple commands with flags in npm scripts.
## Problem Solved
### Previous Issue: Multiple Commands with Flags
The original package.json scripts had complex command chains that made debugging and maintenance difficult:
```json
// OLD PATTERN - Multiple commands with flags
"build:web:test": "npm run build:web:build -- --mode test",
"build:web:prod": "npm run build:web:build -- --mode production",
"build:web:docker:test": "npm run build:web:docker -- --mode test",
"build:web:docker:prod": "npm run build:web:docker -- --mode production"
```
### New Solution: Single Script with Arguments
The new approach uses a single shell script that handles all build modes and options:
```json
// NEW PATTERN - Single script calls
"build:web": "./scripts/build-web.sh",
"build:web:dev": "./scripts/build-web.sh --dev",
"build:web:test": "./scripts/build-web.sh --test",
"build:web:prod": "./scripts/build-web.sh --prod",
"build:web:docker": "./scripts/build-web.sh --docker",
"build:web:docker:test": "./scripts/build-web.sh --docker:test",
"build:web:docker:prod": "./scripts/build-web.sh --docker:prod",
"build:web:serve": "./scripts/build-web.sh --serve"
```
## Script Architecture
### Design Principles
1. **Single Responsibility**: Each npm script calls exactly one command
2. **Argument Parsing**: All complexity handled within the shell script
3. **Consistent Interface**: Follows the same pattern as other build scripts
4. **Environment Management**: Proper environment variable handling
5. **Error Handling**: Comprehensive error checking and reporting
6. **Development-First**: Development mode starts dev server instead of building
### Script Structure
```bash
#!/bin/bash
# build-web.sh
# Author: Matthew Raymer
# Description: Web build script for TimeSafari application
# Exit on any error
set -e
# Source common utilities
source "$(dirname "$0")/common.sh"
# Parse arguments and set build mode
parse_web_args "$@"
# Validate environment
validate_web_environment
# Setup environment
setup_build_env "web"
setup_web_environment
# Execute build steps
clean_build_artifacts "dist"
execute_vite_build "$BUILD_MODE"
# Optional steps
if [ "$DOCKER_BUILD" = true ]; then
execute_docker_build "$BUILD_MODE"
fi
if [ "$SERVE_BUILD" = true ]; then
serve_build
fi
```
## Build Modes Supported
### Development Mode (Default)
```bash
./scripts/build-web.sh
./scripts/build-web.sh --dev
```
- Starts Vite development server with hot reload
- No build step - runs development server directly
- Fast startup with live reload capabilities
- Available at http://localhost:8080
- **Source maps enabled** for debugging
- **PWA enabled** for development testing
### Test Mode
```bash
./scripts/build-web.sh --test
```
- Test environment configuration
- Minimal minification
- Source maps enabled
- Uses `.env.test` file
- **PWA enabled** for testing
### Production Mode
```bash
./scripts/build-web.sh --prod
```
- Full production optimizations
- Maximum minification
- Source maps disabled
- Uses `.env.production` file
- **PWA enabled** with full caching strategies
## Docker Integration
### Docker Build Options
```bash
# Development + Docker
./scripts/build-web.sh --docker
# Test + Docker
./scripts/build-web.sh --docker:test
# Production + Docker
./scripts/build-web.sh --docker:prod
```
### Docker Features
- Automatic image tagging (`timesafari-web:mode`)
- Build argument passing
- Environment-specific configurations
- Consistent image naming
## Local Development
### Development Server
```bash
./scripts/build-web.sh
./scripts/build-web.sh --dev
```
- Starts Vite development server with hot reload
- No build step required
- Fast startup (~350ms)
- Available at http://localhost:8080
- Supports live reload and HMR
- **Source maps enabled** for debugging
### Serve Build Locally
```bash
./scripts/build-web.sh --serve
```
- Builds the application first
- Starts a local HTTP server to serve the built files
- Supports Python HTTP server or npx serve
- Runs on port 8080
## PWA Configuration
### PWA Best Practices Implementation
The TimeSafari web build follows PWA best practices by enabling PWA functionality across all environments:
#### ✅ **Development Mode**
- PWA enabled for development testing
- Service worker registration active
- Manifest generation enabled
- Hot reload compatible
#### ✅ **Test Mode**
- PWA enabled for QA testing
- Service worker registration active
- Manifest generation enabled
- Full PWA feature testing
#### ✅ **Production Mode**
- PWA enabled with full caching strategies
- Service worker registration active
- Manifest generation enabled
- Runtime caching for API calls
- Optimized for production performance
### PWA Features Generated
- `manifest.webmanifest` - PWA manifest with app metadata
- `sw.js` - Service worker for offline functionality
- `workbox-*.js` - Workbox library for caching strategies
- Share target support for image sharing
- Offline-first architecture
### Visual Confirmations of PWA Installation
#### ✅ **Automatic Browser Prompts**
- **Chrome**: Install banner in address bar with install button
- **Safari**: "Add to Home Screen" prompt
- **Edge**: Install button in toolbar
- **Firefox**: Install button in address bar
#### ✅ **Custom Install Prompt**
- **PWAInstallPrompt Component**: Shows when PWA can be installed
- **Install Button**: Prominent blue "Install" button
- **Dismiss Options**: "Later" button and close button
- **Success Notification**: Confirms successful installation
#### ✅ **Post-Installation Indicators**
- **App Icon**: Appears on device home screen/start menu
- **Standalone Window**: Opens without browser UI
- **Native Experience**: Full-screen app-like behavior
- **Offline Capability**: Works without internet connection
#### ✅ **Installation Status Detection**
- **Display Mode Detection**: Checks for standalone/fullscreen modes
- **Service Worker Status**: Monitors service worker registration
- **Install Event Handling**: Listens for successful installation
- **Environment Awareness**: Only shows when PWA is enabled
### Environment Variables Set
- `VITE_PLATFORM=web`
- `VITE_PWA_ENABLED=true`
- `VITE_DISABLE_PWA=false`
- `NODE_ENV` (based on build mode)
- `VITE_GIT_HASH` (from git)
## Environment Management
### Environment File Loading
The script automatically loads environment files based on build mode:
1. `.env.{mode}` (e.g., `.env.test`, `.env.production`)
2. `.env` (fallback)
## Integration with Existing System
### Common Utilities
The script leverages the existing `common.sh` utilities:
- `log_info`, `log_success`, `log_error` - Consistent logging
- `measure_time` - Performance tracking
- `safe_execute` - Error handling
- `setup_build_env` - Environment setup
- `clean_build_artifacts` - Cleanup operations
### Consistent Patterns
Follows the same patterns as other build scripts:
- `build-electron.sh` - Electron builds
- `build-android.sh` - Android builds
- `build-ios.sh` - iOS builds
## Usage Examples
### Basic Builds
```bash
# Development server (starts dev server)
npm run build:web
# Test environment build
npm run build:web:test
# Production build
npm run build:web:prod
```
### Docker Builds
```bash
# Development + Docker
npm run build:web:docker
# Test + Docker
npm run build:web:docker:test
# Production + Docker
npm run build:web:docker:prod
```
### Direct Script Usage
```bash
# Show help
./scripts/build-web.sh --help
# Show environment variables
./scripts/build-web.sh --env
# Verbose logging
./scripts/build-web.sh --test --verbose
```
## Benefits Achieved
### 1. Simplified NPM Scripts
- No more complex command chains
- Single command per script
- Easy to understand and maintain
### 2. Better Error Handling
- Comprehensive error checking
- Clear error messages
- Proper exit codes
### 3. Consistent Logging
- Structured log output
- Performance timing
- Build step tracking
### 4. Environment Management
- Automatic environment file loading
- Platform-specific configurations
- Git hash integration
### 5. Docker Integration
- Seamless Docker builds
- Environment-aware containerization
- Consistent image tagging
## Testing Results
### Build Performance
- **Development Mode**: ~350ms startup time (dev server)
- **Test Mode**: ~11 seconds build time
- **Production Mode**: ~12 seconds build time
### Environment Loading
- Successfully loads `.env.test` for test builds
- Properly sets `NODE_ENV` based on build mode
- Correctly applies Vite mode configurations
### Docker Integration
- Docker builds complete successfully
- Images tagged correctly (`timesafari-web:test`, etc.)
- Build arguments passed properly
## Future Enhancements
### Potential Improvements
1. **Parallel Builds**: Support for parallel asset processing
2. **Build Caching**: Implement build caching for faster rebuilds
3. **Custom Ports**: Allow custom port specification for serve mode
4. **Build Profiles**: Support for custom build profiles
5. **Watch Mode**: Add development watch mode support
### Integration Opportunities
1. **CI/CD Integration**: Easy integration with GitHub Actions
2. **Multi-Platform Builds**: Extend to support other platforms
3. **Build Analytics**: Add build performance analytics
4. **Dependency Checking**: Automatic dependency validation
## Conclusion
The `build-web.sh` script successfully addresses the requirement to prevent scripts from having multiple commands with flags while providing a robust, maintainable, and feature-rich build system for the TimeSafari web application.
The implementation follows established patterns in the codebase, leverages existing utilities, and provides a consistent developer experience across all build modes and platforms.
---
**Status**: ✅ **COMPLETE** - Ready for production use
**Test Coverage**: 100% - All build modes tested and working
**Documentation**: Complete with usage examples and integration guide

594
docs/build-system/core/electron-build-patterns.md

@ -1,594 +0,0 @@
# Electron Build Patterns
**Author**: Matthew Raymer
**Date**: 2025-01-27
**Status**: 🎯 **ACTIVE** - Current Implementation
## Overview
TimeSafari's Electron build system provides comprehensive packaging and
distribution capabilities across Windows, macOS, and Linux platforms. The
system supports multiple build modes, environment configurations, and
package formats for different deployment scenarios.
## Build Architecture
### Multi-Stage Build Process
```
1. Web Build (Vite) → 2. Capacitor Sync → 3. TypeScript Compile → 4. Package
```
**Stage 1: Web Build**
- Vite builds web assets with Electron-specific configuration
- Environment variables loaded based on build mode
- Assets optimized for desktop application
**Stage 2: Capacitor Sync**
- Copies web assets to Electron app directory
- Syncs Capacitor configuration and plugins
- Prepares native module bindings
**Stage 3: TypeScript Compile**
- Compiles Electron main process TypeScript
- Rebuilds native modules for target platform
- Generates production-ready JavaScript
**Stage 4: Package Creation**
- Creates platform-specific installers
- Generates distribution packages
- Signs applications (when configured)
## Build Modes
### Development Mode (--mode development)
**Purpose**: Local development and testing
**Configuration**: Development environment variables
**Output**: Unpacked application for testing
```bash
# Development build (runs app)
npm run build:electron:dev
# Development build with explicit mode
npm run build:electron -- --mode development
```
**Features**:
- Hot reload enabled
- Debug tools available
- Development logging
- Unoptimized assets
### Testing Mode (--mode test)
**Purpose**: Staging and testing environments
**Configuration**: Test environment variables
**Output**: Packaged application for testing
```bash
# Test build
npm run build:electron -- --mode test
# Test build with specific platform
npm run build:electron:windows -- --mode test
npm run build:electron:mac -- --mode test
npm run build:electron:linux -- --mode test
```
**Features**:
- Test API endpoints
- Staging configurations
- Optimized for testing
- Debug information available
### Production Mode (--mode production)
**Purpose**: Production deployment
**Configuration**: Production environment variables
**Output**: Optimized distribution packages
```bash
# Production build
npm run build:electron -- --mode production
# Production build with specific platform
npm run build:electron:windows -- --mode production
npm run build:electron:mac -- --mode production
npm run build:electron:linux -- --mode production
```
**Features**:
- Production optimizations
- Code minification
- Security hardening
- Performance optimizations
## Platform-Specific Builds
### Windows Builds
**Target Platforms**: Windows 10/11 (x64)
**Package Formats**: NSIS installer, portable executable
```bash
# Windows development build
npm run build:electron:windows -- --mode development
# Windows test build
npm run build:electron:windows -- --mode test
# Windows production build
npm run build:electron:windows -- --mode production
```
**Configuration**:
- NSIS installer with custom options
- Desktop and Start Menu shortcuts
- Elevation permissions for installation
- Custom installation directory support
### macOS Builds
**Target Platforms**: macOS 10.15+ (x64, arm64)
**Package Formats**: DMG installer, app bundle
```bash
# macOS development build
npm run build:electron:mac -- --mode development
# macOS test build
npm run build:electron:mac -- --mode test
# macOS production build
npm run build:electron:mac -- --mode production
```
**Configuration**:
- Universal binary (x64 + arm64)
- DMG installer with custom branding
- App Store compliance (when configured)
- Code signing support
### Linux Builds
**Target Platforms**: Ubuntu 18.04+, Debian 10+, Arch Linux
**Package Formats**: AppImage, DEB, RPM
```bash
# Linux development build
npm run build:electron:linux -- --mode development
# Linux test build
npm run build:electron:linux -- --mode test
# Linux production build
npm run build:electron:linux -- --mode production
```
**Configuration**:
- AppImage for universal distribution
- DEB package for Debian-based systems
- RPM package for Red Hat-based systems
- Desktop integration
## Package-Specific Builds
### AppImage Package
**Format**: Self-contained Linux executable
**Distribution**: Universal Linux distribution
```bash
# AppImage development build
npm run build:electron:appimage -- --mode development
# AppImage test build
npm run build:electron:appimage -- --mode test
# AppImage production build
npm run build:electron:appimage -- --mode production
```
**Features**:
- Single file distribution
- No installation required
- Portable across Linux distributions
- Automatic updates support
### DEB Package
**Format**: Debian package installer
**Distribution**: Debian-based Linux systems
```bash
# DEB development build
npm run build:electron:deb -- --mode development
# DEB test build
npm run build:electron:deb -- --mode test
# DEB production build
npm run build:electron:deb -- --mode production
```
**Features**:
- Native package management
- Dependency resolution
- System integration
- Easy installation/uninstallation
### DMG Package
**Format**: macOS disk image
**Distribution**: macOS systems
```bash
# DMG development build
npm run build:electron:dmg -- --mode development
# DMG test build
npm run build:electron:dmg -- --mode test
# DMG production build
npm run build:electron:dmg -- --mode production
```
**Features**:
- Native macOS installer
- Custom branding and layout
- Drag-and-drop installation
- Code signing support
## Environment Configuration
### Environment Variables
**Development Environment**:
```bash
VITE_API_URL=http://localhost:3000
VITE_DEBUG=true
VITE_LOG_LEVEL=debug
VITE_ENABLE_DEV_TOOLS=true
```
**Testing Environment**:
```bash
VITE_API_URL=https://test-api.timesafari.com
VITE_DEBUG=false
VITE_LOG_LEVEL=info
VITE_ENABLE_DEV_TOOLS=false
```
**Production Environment**:
```bash
VITE_API_URL=https://api.timesafari.com
VITE_DEBUG=false
VITE_LOG_LEVEL=warn
VITE_ENABLE_DEV_TOOLS=false
```
### Build Configuration
**Vite Configuration** (`vite.config.electron.mts`):
```typescript
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
return {
mode,
build: {
outDir: 'dist',
emptyOutDir: true,
sourcemap: mode === 'development',
minify: mode === 'production'
},
define: {
__DEV__: mode === 'development',
__TEST__: mode === 'test',
__PROD__: mode === 'production'
}
};
});
```
**Electron Builder Configuration** (`electron-builder.config.json`):
```json
{
"appId": "app.timesafari.desktop",
"productName": "TimeSafari",
"directories": {
"buildResources": "resources",
"output": "dist"
},
"files": [
"assets/**/*",
"build/**/*",
"capacitor.config.*",
"app/**/*"
]
}
```
## Build Scripts Reference
### Main Build Scripts
```bash
# Development builds
npm run build:electron:dev # Development build and run
npm run build:electron --dev # Development build only
# Testing builds
npm run build:electron:test # Test environment build
# Production builds
npm run build:electron:prod # Production environment build
```
### Platform-Specific Scripts
```bash
# Windows builds
npm run build:electron:windows # Windows production build
npm run build:electron:windows:dev # Windows development build
npm run build:electron:windows:test # Windows test build
npm run build:electron:windows:prod # Windows production build
# macOS builds
npm run build:electron:mac # macOS production build
npm run build:electron:mac:dev # macOS development build
npm run build:electron:mac:test # macOS test build
npm run build:electron:mac:prod # macOS production build
# Linux builds
npm run build:electron:linux # Linux production build
npm run build:electron:linux:dev # Linux development build
npm run build:electron:linux:test # Linux test build
npm run build:electron:linux:prod # Linux production build
```
### Package-Specific Scripts
```bash
# AppImage builds
npm run build:electron:appimage # Linux AppImage production build
npm run build:electron:appimage:dev # AppImage development build
npm run build:electron:appimage:test # AppImage test build
npm run build:electron:appimage:prod # AppImage production build
# DEB builds
npm run build:electron:deb # Debian package production build
npm run build:electron:deb:dev # DEB development build
npm run build:electron:deb:test # DEB test build
npm run build:electron:deb:prod # DEB production build
# DMG builds
npm run build:electron:dmg # macOS DMG production build
npm run build:electron:dmg:dev # DMG development build
npm run build:electron:dmg:test # DMG test build
npm run build:electron:dmg:prod # DMG production build
```
### Direct Script Usage
All npm scripts use the underlying `./scripts/build-electron.sh` script:
```bash
# Direct script usage examples
./scripts/build-electron.sh --dev # Development build
./scripts/build-electron.sh --test # Test build
./scripts/build-electron.sh --prod # Production build
./scripts/build-electron.sh --prod --windows # Windows production
./scripts/build-electron.sh --test --appimage # Linux AppImage test
./scripts/build-electron.sh --dev --mac # macOS development
./scripts/build-electron.sh --prod --dmg # macOS DMG production
```
### Utility Scripts
```bash
# Cleanup scripts
npm run clean:electron # Clean Electron build artifacts
# Development scripts
npm run electron:dev # Start development server
npm run electron:dev-full # Full development workflow
```
## Build Output Structure
### Development Build
```
electron/
├── app/ # Web assets
├── build/ # Compiled TypeScript
├── dist/ # Build artifacts (empty in dev)
└── node_modules/ # Dependencies
```
### Production Build
```
electron/
├── app/ # Web assets
├── build/ # Compiled TypeScript
├── dist/ # Distribution packages
│ ├── TimeSafari.exe # Windows executable
│ ├── TimeSafari.dmg # macOS installer
│ ├── TimeSafari.AppImage # Linux AppImage
│ └── TimeSafari.deb # Debian package
└── node_modules/ # Dependencies
```
## Troubleshooting
### Common Build Issues
**TypeScript Compilation Errors**:
```bash
# Clean and rebuild
npm run clean:electron
cd electron && npm run build
```
**Native Module Issues**:
```bash
# Rebuild native modules
cd electron && npm run build
```
**Asset Copy Issues**:
```bash
# Verify Capacitor sync
npx cap sync electron
```
**Package Creation Failures**:
```bash
# Check electron-builder configuration
# Verify platform-specific requirements
# Check signing certificates (macOS/Windows)
```
### Platform-Specific Issues
**Windows**:
- Ensure Windows Build Tools installed
- Check NSIS installation
- Verify code signing certificates
**macOS**:
- Install Xcode Command Line Tools
- Configure code signing certificates
- Check app notarization requirements
**Linux**:
- Install required packages (rpm-tools, etc.)
- Check AppImage dependencies
- Verify desktop integration
## Performance Optimization
### Build Performance
**Parallel Builds**:
- Use concurrent TypeScript compilation
- Optimize asset copying
- Minimize file system operations
**Caching Strategies**:
- Cache node_modules between builds
- Cache compiled TypeScript
- Cache web assets when unchanged
### Runtime Performance
**Application Startup**:
- Optimize main process initialization
- Minimize startup dependencies
- Use lazy loading for features
**Memory Management**:
- Monitor memory usage
- Implement proper cleanup
- Optimize asset loading
## Security Considerations
### Code Signing
**Windows**:
- Authenticode code signing
- EV certificate for SmartScreen
- Timestamp server configuration
**macOS**:
- Developer ID code signing
- App notarization
- Hardened runtime
**Linux**:
- GPG signing for packages
- AppImage signing
- Package verification
### Security Hardening
**Production Builds**:
- Disable developer tools
- Remove debug information
- Enable security policies
- Implement sandboxing
**Update Security**:
- Secure update channels
- Package integrity verification
- Rollback capabilities
## CI/CD Integration
### GitHub Actions
```yaml
# Example workflow for Electron builds
- name: Build Electron
run: |
npm run build:electron -- --mode production
npm run build:electron:windows -- --mode production
npm run build:electron:mac -- --mode production
npm run build:electron:linux -- --mode production
```
### Automated Testing
```yaml
# Test Electron builds
- name: Test Electron
run: |
npm run build:electron -- --mode test
# Run automated tests
```
### Release Management
```yaml
# Create releases with assets
- name: Create Release
run: |
# Upload built packages
# Create GitHub release
# Publish to distribution channels
```
## Best Practices
### Development Workflow
1. **Use development mode for local testing**
2. **Test builds in all environments**
3. **Validate packages before distribution**
4. **Maintain consistent versioning**
### Build Optimization
1. **Minimize build dependencies**
2. **Use efficient asset processing**
3. **Implement proper caching**
4. **Optimize for target platforms**
### Quality Assurance
1. **Test on all target platforms**
2. **Validate installation processes**
3. **Check update mechanisms**
4. **Verify security configurations**
---
**Status**: Active implementation
**Last Updated**: 2025-01-27
**Version**: 1.0
**Maintainer**: Matthew Raymer

422
docs/build-system/platforms/android-build-scripts.md

@ -1,422 +0,0 @@
# Android Build Scripts Documentation
**Author**: Matthew Raymer
**Date**: 2025-07-11
**Status**: ✅ **COMPLETE** - Full Android build system integration
## Overview
The Android build system for TimeSafari has been integrated with the Vite
mode-based pattern, providing consistent environment management and flexible
build options across development, testing, and production environments.
**Note:** All Android builds should be invoked via `npm run build:android*` scripts for consistency. The legacy `build:capacitor:android*` scripts are now aliases for the corresponding `build:android*` scripts.
## Build Script Integration
### Package.json Scripts
The Android build system is fully integrated into `package.json` with the
following scripts:
#### Basic Build Commands
```bash
# Development builds (defaults to --mode development)
npm run build:android:dev # Development build
npm run build:android:test # Testing build
npm run build:android:prod # Production build
```
#### Build Type Commands
```bash
# Debug builds
npm run build:android:debug # Debug APK build
# Release builds
npm run build:android:release # Release APK build
```
#### Specialized Commands
```bash
# Android Studio integration
npm run build:android:studio # Build + open Android Studio
# Package builds
npm run build:android:apk # Build APK file
npm run build:android:aab # Build AAB (Android App Bundle)
# Utility commands
npm run build:android:clean # Clean build artifacts only
npm run build:android:sync # Sync Capacitor only
npm run build:android:assets # Generate assets only
```
#### Legacy Command
```bash
# Original script (maintains backward compatibility)
npm run build:android # Full build process
```
## Script Usage
### Direct Script Usage
The `build-android.sh` script supports comprehensive command-line options:
```bash
# Basic usage
./scripts/build-android.sh [options]
# Environment-specific builds
./scripts/build-android.sh --dev --studio # Development + open studio
./scripts/build-android.sh --test --apk # Testing APK build
./scripts/build-android.sh --prod --aab # Production AAB build
# Utility operations
./scripts/build-android.sh --clean # Clean only
./scripts/build-android.sh --sync # Sync only
./scripts/build-android.sh --assets # Assets only
```
### Command-Line Options
| Option | Description | Default |
|--------|-------------|---------|
| `--dev`, `--development` | Build for development environment | ✅ |
| `--test` | Build for testing environment | |
| `--prod`, `--production` | Build for production environment | |
| `--debug` | Build debug APK | ✅ |
| `--release` | Build release APK | |
| `--studio` | Open Android Studio after build | |
| `--apk` | Build APK file | |
| `--aab` | Build AAB (Android App Bundle) | |
| `--clean` | Clean build artifacts only | |
| `--sync` | Sync Capacitor only | |
| `--assets` | Generate assets only | |
| `-h`, `--help` | Show help message | |
| `-v`, `--verbose` | Enable verbose logging | |
## Build Process
### Complete Build Flow
1. **Resource Check**: Validate Android resources
2. **Cleanup**: Clean Android app and build artifacts
3. **Capacitor Build**: Build web assets with environment-specific mode
4. **Gradle Clean**: Clean Gradle build cache
5. **Gradle Build**: Assemble debug/release APK
6. **Capacitor Sync**: Sync web assets to Android platform
7. **Asset Generation**: Generate Android-specific assets
8. **Package Build**: Build APK/AAB if requested
9. **Studio Launch**: Open Android Studio if requested
### Environment-Specific Builds
#### Development Environment (`--dev`)
```bash
# Uses --mode development
npm run build:capacitor
# Builds with development optimizations and debugging enabled
```
#### Testing Environment (`--test`)
```bash
# Uses --mode test
npm run build:capacitor -- --mode test
# Builds with testing configurations and test API endpoints
```
#### Production Environment (`--prod`)
```bash
# Uses --mode production
npm run build:capacitor -- --mode production
# Builds with production optimizations and live API endpoints
```
## Build Artifacts
### APK Files
- **Debug APK**: `android/app/build/outputs/apk/debug/app-debug.apk`
- **Release APK**: `android/app/build/outputs/apk/release/app-release.apk`
### AAB Files
- **Release AAB**: `android/app/build/outputs/bundle/release/app-release.aab`
### Build Locations
```bash
# APK files
android/app/build/outputs/apk/debug/
android/app/build/outputs/apk/release/
# AAB files
android/app/build/outputs/bundle/release/
# Gradle build cache
android/app/build/
android/.gradle/
```
## Environment Variables
The build system automatically sets environment variables based on the build
type:
### Capacitor Environment
```bash
VITE_PLATFORM=capacitor
VITE_PWA_ENABLED=false
VITE_DISABLE_PWA=true
DEBUG_MIGRATIONS=0
```
### Git Integration
```bash
VITE_GIT_HASH=<git-commit-hash>
# Automatically set from current git commit
```
## Error Handling
### Exit Codes
| Code | Description |
|------|-------------|
| 1 | Android cleanup failed |
| 2 | Web build failed |
| 3 | Capacitor build failed |
| 4 | Gradle clean failed |
| 5 | Gradle assemble failed |
| 6 | Capacitor sync failed |
| 7 | Asset generation failed |
| 8 | Android Studio launch failed |
| 9 | Resource check failed |
### Common Issues
#### Resource Check Failures
```bash
# Resource check may find issues but continues build
log_warning "Resource check found issues, but continuing with build..."
```
#### Gradle Build Failures
```bash
# Check Android SDK and build tools
./android/gradlew --version
# Verify JAVA_HOME is set correctly
echo $JAVA_HOME
```
## Integration with Capacitor
### Capacitor Sync Process
```bash
# Full sync (all platforms)
npx cap sync
# Android-specific sync
npx cap sync android
```
### Asset Generation
```bash
# Generate Android-specific assets
npx capacitor-assets generate --android
```
### Android Studio Integration
```bash
# Open Android Studio with project
npx cap open android
```
## Development Workflow
### Typical Development Cycle
```bash
# 1. Make code changes
# 2. Build for development
npm run build:android:dev
# 3. Open Android Studio for debugging
npm run build:android:studio
# 4. Test on device/emulator
# 5. Iterate and repeat
```
### Testing Workflow
```bash
# 1. Build for testing environment
npm run build:android:test
# 2. Build test APK
npm run build:android:test -- --apk
# 3. Install and test on device
adb install android/app/build/outputs/apk/debug/app-debug.apk
```
### Production Workflow
```bash
# 1. Build for production environment
npm run build:android:prod
# 2. Build release AAB for Play Store
npm run build:android:prod -- --aab
# 3. Sign and upload to Play Console
```
## Performance Optimization
### Build Time Optimization
- **Incremental Builds**: Gradle caches build artifacts
- **Parallel Execution**: Multiple build steps run in parallel
- **Resource Optimization**: Assets are optimized for Android
### Memory Management
- **Gradle Daemon**: Reuses JVM for faster builds
- **Build Cache**: Caches compiled resources
- **Clean Builds**: Full cleanup when needed
## Troubleshooting
### Common Build Issues
#### Gradle Build Failures
```bash
# Clean Gradle cache
cd android && ./gradlew clean && cd ..
# Check Java version
java -version
# Verify Android SDK
echo $ANDROID_HOME
```
#### Capacitor Sync Issues
```bash
# Force full sync
npx cap sync android --force
# Check Capacitor configuration
cat capacitor.config.json
```
#### Asset Generation Issues
```bash
# Regenerate assets
npx capacitor-assets generate --android --force
# Check asset source files
ls -la src/assets/
```
### Debug Mode
```bash
# Enable verbose logging
./scripts/build-android.sh --verbose
# Show environment variables
./scripts/build-android.sh --env
```
## Best Practices
### Build Optimization
1. **Use Appropriate Environment**: Always specify the correct environment
2. **Clean When Needed**: Use `--clean` for troubleshooting
3. **Incremental Builds**: Avoid unnecessary full rebuilds
4. **Asset Management**: Keep assets optimized for mobile
### Development Workflow
1. **Development Builds**: Use `--dev` for daily development
2. **Testing Builds**: Use `--test` for QA testing
3. **Production Builds**: Use `--prod` for release builds
4. **Studio Integration**: Use `--studio` for debugging
### Error Prevention
1. **Resource Validation**: Always run resource checks
2. **Environment Consistency**: Use consistent environment variables
3. **Build Verification**: Test builds on actual devices
4. **Version Control**: Keep build scripts in version control
## Migration from Legacy System
### Backward Compatibility
The new system maintains full backward compatibility:
```bash
# Old command still works (now an alias)
npm run build:capacitor:android
# New commands provide more flexibility
npm run build:android:dev
npm run build:android:test
npm run build:android:prod
```
**Note:** All Android builds should use the `build:android*` pattern. The `build:capacitor:android*` scripts are provided as aliases for compatibility but will be deprecated in the future.
### Migration Checklist
- [ ] Update CI/CD pipelines to use new commands
- [ ] Update documentation references
- [ ] Train team on new build options
- [ ] Test all build environments
- [ ] Verify artifact locations
## Future Enhancements
### Planned Features
1. **Build Profiles**: Custom build configurations
2. **Automated Testing**: Integration with test suites
3. **Build Analytics**: Performance metrics and reporting
4. **Cloud Builds**: Remote build capabilities
### Integration Opportunities
1. **Fastlane Integration**: Automated deployment
2. **CI/CD Enhancement**: Pipeline optimization
3. **Monitoring**: Build performance tracking
4. **Documentation**: Auto-generated build reports
---
**Status**: Complete and ready for production use
**Last Updated**: 2025-07-11
**Version**: 1.0
**Maintainer**: Matthew Raymer

146
docs/build-system/platforms/database-clearing.md

@ -1,146 +0,0 @@
# Database Clearing for Development
**Author**: Matthew Raymer
**Date**: 2025-07-11
**Status**: **ACTIVE** - Production Ready
## Overview
TimeSafari provides a simple script-based approach to clear the database for development purposes. This avoids the complexity of programmatic database clearing and provides reliable, platform-specific solutions.
## Quick Start
```bash
# Run the interactive 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
```
## Platform-Specific Approaches
### Electron (Desktop App)
The script automatically detects your platform and clears the SQLite database files:
- **Linux**: `~/.config/TimeSafari/`
- **macOS**: `~/Library/Application Support/TimeSafari/`
- **Windows**: `%APPDATA%\TimeSafari`
### Web Browser
For web browsers, the script provides two approaches:
#### 1. Custom Data Directory (Recommended)
Create an isolated browser profile for development:
```bash
# Create isolated profile
mkdir ~/timesafari-dev-data
# Start browser with custom profile
google-chrome --user-data-dir=~/timesafari-dev-data
# Clear when needed
rm -rf ~/timesafari-dev-data
```
#### 2. Manual Browser Clearing
Use browser DevTools to clear IndexedDB:
1. Open Developer Tools (F12)
2. Go to Application/Storage tab
3. Find 'IndexedDB' section
4. Delete 'TimeSafari' database
5. Refresh the page
## Why Script-Based Approach?
### **Simplicity**
- No complex programmatic database clearing
- No browser storage complications
- No race conditions or permission issues
### **Reliability**
- Direct file system access for Electron
- Isolated browser profiles for web
- Clear, predictable behavior
### **Safety**
- Interactive script guides users
- Platform-specific instructions
- Only clears TimeSafari data
## Manual Commands
If you prefer manual commands:
### Electron
```bash
# Linux
rm -rf ~/.config/TimeSafari/*
# macOS
rm -rf ~/Library/Application\ Support/TimeSafari/*
# Windows
rmdir /s /q %APPDATA%\TimeSafari
```
### Web Browser
```bash
# Create and use isolated profile
mkdir ~/timesafari-dev-data
google-chrome --user-data-dir=~/timesafari-dev-data
# Clear when needed
rm -rf ~/timesafari-dev-data
```
## Best Practices
1. **Stop the development server** before clearing
2. **Use isolated browser profiles** for web development
3. **Restart the development server** after clearing
4. **Backup important data** before clearing
5. **Use the script** for consistent behavior
## Troubleshooting
### Script Not Found
```bash
# Make sure script is executable
chmod +x scripts/clear-database.sh
# Run from project root
./scripts/clear-database.sh
```
### Permission Errors
```bash
# Check file permissions
ls -la ~/.config/TimeSafari/
# Use sudo if needed (rare)
sudo rm -rf ~/.config/TimeSafari/*
```
### Browser Profile Issues
```bash
# Ensure browser is completely closed
pkill -f chrome
pkill -f firefox
# Then clear profile
rm -rf ~/timesafari-dev-data
```
---
**Last Updated**: 2025-07-11
**Version**: 1.0.3-beta
**Status**: Production Ready

174
docs/build-system/platforms/electron-auto-updates.md

@ -1,174 +0,0 @@
# Electron Auto-Updates Configuration
**Author**: Matthew Raymer
**Date**: 2025-07-12
**Status**: **DISABLED** - Manual Updates Only
## Overview
TimeSafari's Electron application currently has auto-updates disabled due to hosting on Gitea instead of GitHub. This document explains the current configuration and provides guidance for future update mechanisms.
## Current Status
### Auto-Updates Disabled
Auto-updates are currently disabled for the following reasons:
1. **Repository Hosting**: The project is hosted on Gitea (`https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa`) rather than GitHub
2. **Provider Limitations**: `electron-updater` primarily supports GitHub, S3, and other major cloud providers
3. **404 Errors**: Attempting to use GitHub auto-updates with a Gitea repository causes 404 errors
### Configuration Changes Made
1. **Repository URL Updated**: Changed from `https://github.com/trentlarson/crowd-master` to the correct Gitea URL
2. **Publish Configuration Removed**: Removed GitHub provider from `electron-builder.config.json`
3. **Auto-Updater Disabled**: Commented out auto-updater code in `electron/src/index.ts`
## Error Resolution
The original error:
```
HttpError: 404
"method: GET url: https://github.com/trentlarson/crowd-master/releases.atom"
```
This occurred because:
- The app was trying to check for updates on GitHub
- The repository doesn't exist on GitHub
- The auto-updater was configured for GitHub releases
## Future Update Options
### Option 1: Manual Distribution
- Build and distribute packages manually
- Users download and install new versions manually
- No automatic update checking
### Option 2: Custom Update Server
- Implement a custom update server compatible with `electron-updater`
- Host update files on a web server
- Configure custom update endpoints
### Option 3: GitHub Migration
- Move repository to GitHub
- Set up GitHub releases
- Re-enable auto-updates
### Option 4: Alternative Update Providers
- Use S3 or other supported providers
- Implement custom update mechanism
- Use third-party update services
## Current Build Process
### Development Builds
```bash
npm run build:electron:dev
```
### Production Builds
```bash
npm run build:electron:prod
```
### Package Distribution
```bash
# Windows
npm run build:electron:windows:prod
# macOS
npm run build:electron:mac:prod
# Linux
npm run build:electron:linux:prod
```
## Manual Update Process
1. **Build New Version**: Use appropriate build script
2. **Test Package**: Verify the built package works correctly
3. **Distribute**: Share the package with users
4. **User Installation**: Users manually download and install
## Security Considerations
### Disabled Auto-Updates
- No automatic security updates
- Users must manually update for security patches
- Consider implementing update notifications
### Package Verification
- Verify package integrity before distribution
- Use code signing for packages
- Implement checksum verification
## Monitoring and Maintenance
### Version Tracking
- Track application versions manually
- Document changes between versions
- Maintain changelog for users
### User Communication
- Notify users of available updates
- Provide clear update instructions
- Document breaking changes
## Recommendations
### Short Term
1. Continue with manual distribution
2. Implement update notifications in-app
3. Provide clear update instructions
### Long Term
1. Evaluate hosting platform options
2. Consider implementing custom update server
3. Plan for automated update mechanism
## Configuration Files
### electron-builder.config.json
```json
{
"appId": "app.timesafari.desktop",
"productName": "TimeSafari",
// publish configuration removed
}
```
### electron/src/index.ts
```typescript
// Auto-updater disabled
// import { autoUpdater } from 'electron-updater';
// Auto-updates disabled - not supported on Gitea hosting
// if (!electronIsDev && !process.env.APPIMAGE) {
// try {
// autoUpdater.checkForUpdatesAndNotify();
// } catch (error) {
// console.log('Update check failed (suppressed):', error);
// }
// }
```
## Troubleshooting
### Common Issues
1. **404 Errors**: Ensure repository URL is correct
2. **Build Failures**: Check build configuration
3. **Package Issues**: Verify package contents
### Debug Mode
```bash
# Enable debug logging
DEBUG=* npm run build:electron:dev
```
---
**Status**: Auto-updates disabled
**Last Updated**: 2025-07-12
**Version**: 1.0
**Maintainer**: Matthew Raymer

181
docs/build-system/platforms/electron-build-scripts.md

@ -1,181 +0,0 @@
# Electron Build Scripts Guide
**Author**: Matthew Raymer
**Date**: 2025-07-11
**Status**: **ACTIVE** - Production Ready
## Overview
This document clarifies the difference between Electron build scripts that create executable packages versus those that run the app directly.
## Script Categories
### 🚀 **Development Scripts (Run App Directly)**
These scripts build the app and then run it immediately for development:
```bash
# Development mode - runs app directly
npm run build:electron:dev
# Test mode - runs app directly
npm run build:electron:test
# Production mode - runs app directly
npm run build:electron:prod
```
### 📦 **Package Build Scripts (Create Executables)**
These scripts build executable packages that can be distributed and run by users:
#### **Platform-Specific Executables**
```bash
# Windows executable (.exe)
npm run build:electron:windows
npm run build:electron:windows:dev
npm run build:electron:windows:test
npm run build:electron:windows:prod
# macOS app bundle (.app)
npm run build:electron:mac
npm run build:electron:mac:dev
npm run build:electron:mac:test
npm run build:electron:mac:prod
# Linux executable
npm run build:electron:linux
npm run build:electron:linux:dev
npm run build:electron:linux:test
npm run build:electron:linux:prod
```
#### **Package Formats**
```bash
# Linux AppImage (portable executable)
npm run build:electron:appimage
npm run build:electron:appimage:dev
npm run build:electron:appimage:test
npm run build:electron:appimage:prod
# Linux DEB package (installable)
npm run build:electron:deb
npm run build:electron:deb:dev
npm run build:electron:deb:test
npm run build:electron:deb:prod
# macOS DMG package (installable)
npm run build:electron:dmg
npm run build:electron:dmg:dev
npm run build:electron:dmg:test
npm run build:electron:dmg:prod
```
## Output Locations
### **Development Scripts**
- Run the app directly in development mode
- No files created for distribution
- App runs immediately after build
### **Package Scripts**
- Create executable files in `electron/dist/`
- Files can be distributed to users
- Users can run the executables by hand
#### **Package Output Examples**
```bash
# AppImage
electron/dist/TimeSafari-1.0.3-beta.AppImage
# DEB package
electron/dist/TimeSafari_1.0.3-beta_amd64.deb
# DMG package
electron/dist/TimeSafari-1.0.3-beta.dmg
# Windows executable
electron/dist/TimeSafari Setup 1.0.3-beta.exe
```
## Usage Examples
### **Development Workflow**
```bash
# Start development (runs app directly)
npm run build:electron:dev
# Test with production build (runs app directly)
npm run build:electron:test
```
### **Distribution Workflow**
```bash
# Build AppImage for Linux distribution
npm run build:electron:appimage:prod
# Build DMG for macOS distribution
npm run build:electron:dmg:prod
# Build Windows installer
npm run build:electron:windows:prod
```
### **Testing Packages**
```bash
# Build test version of AppImage
npm run build:electron:appimage:test
# Test the generated executable
./electron/dist/TimeSafari-1.0.3-beta.AppImage
```
## Key Differences
| Script Type | Purpose | Output | User Action |
|-------------|---------|--------|-------------|
| Development | Run app directly | None | App starts automatically |
| Package | Create executable | `electron/dist/` | User runs executable by hand |
## Best Practices
### **For Development**
- Use `npm run build:electron:dev` for daily development
- Use `npm run build:electron:test` for testing production builds
- App runs immediately after build
### **For Distribution**
- Use `npm run build:electron:*:prod` for production packages
- Test packages before distribution
- Users install/run the generated executables
### **For Testing**
- Use `npm run build:electron:*:test` for test packages
- Verify executables work on target platforms
- Test installation and uninstallation
## Troubleshooting
### **Package Build Issues**
```bash
# Check if package was created
ls -la electron/dist/
# Verify package integrity
file electron/dist/*.AppImage
file electron/dist/*.deb
file electron/dist/*.dmg
```
### **Development Issues**
```bash
# Clean and rebuild
npm run clean:electron
npm run build:electron:dev
```
---
**Last Updated**: 2025-07-11
**Version**: 1.0.3-beta
**Status**: Production Ready

436
docs/build-system/platforms/ios-build-scripts.md

@ -1,436 +0,0 @@
# iOS Build Scripts Documentation
**Author**: Matthew Raymer
**Date**: 2025-07-11
**Status**: ✅ **COMPLETE** - Full iOS build system integration
## Overview
The iOS build system for TimeSafari will provide comprehensive support for iOS mobile application development using Capacitor and Xcode. This system will support development, testing, and production environments with optimized builds for each use case.
**Note:** The iOS build system is now fully implemented and follows the same patterns as the Android and Electron build systems for consistency and maintainability.
## Build Script Integration
### Package.json Scripts
The iOS build system is fully integrated into `package.json` with the following scripts:
#### Basic Build Commands
```bash
# Development builds (defaults to --mode development)
npm run build:ios:dev # Development build
npm run build:ios:test # Testing build
npm run build:ios:prod # Production build
```
#### Build Type Commands
```bash
# Debug builds
npm run build:ios:debug # Debug app build
# Release builds
npm run build:ios:release # Release app build
```
#### Specialized Commands
```bash
# Xcode integration
npm run build:ios:studio # Build + open Xcode
# Package builds
npm run build:ios:ipa # Build IPA file
npm run build:ios:app # Build app bundle
# Utility commands
npm run build:ios:clean # Clean build artifacts only
npm run build:ios:sync # Sync Capacitor only
npm run build:ios:assets # Generate assets only
```
#### Legacy Command
```bash
# Original script (maintains backward compatibility)
npm run build:ios # Full build process
```
## Script Usage
### Direct Script Usage
The `build-ios.sh` script supports comprehensive command-line options:
```bash
# Basic usage
./scripts/build-ios.sh [options]
# Environment-specific builds
./scripts/build-ios.sh --dev --studio # Development + open Xcode
./scripts/build-ios.sh --test --ipa # Testing IPA build
./scripts/build-ios.sh --prod --app # Production app build
# Utility operations
./scripts/build-ios.sh --clean # Clean only
./scripts/build-ios.sh --sync # Sync only
./scripts/build-ios.sh --assets # Assets only
```
### Command-Line Options
| Option | Description | Default |
|--------|-------------|---------|
| `--dev`, `--development` | Build for development environment | ✅ |
| `--test` | Build for testing environment | |
| `--prod`, `--production` | Build for production environment | |
| `--debug` | Build debug app | ✅ |
| `--release` | Build release app | |
| `--studio` | Open Xcode after build | |
| `--ipa` | Build IPA file | |
| `--app` | Build app bundle | |
| `--clean` | Clean build artifacts only | |
| `--sync` | Sync Capacitor only | |
| `--assets` | Generate assets only | |
| `-h`, `--help` | Show help message | |
| `-v`, `--verbose` | Enable verbose logging | |
## Build Process
### Complete Build Flow
1. **Resource Check**: Validate iOS resources
2. **Cleanup**: Clean iOS app and build artifacts
3. **Capacitor Build**: Build web assets with environment-specific mode
4. **Xcode Clean**: Clean Xcode build cache
5. **Xcode Build**: Build debug/release app
6. **Capacitor Sync**: Sync web assets to iOS platform
7. **Asset Generation**: Generate iOS-specific assets
8. **Package Build**: Build IPA if requested
9. **Xcode Launch**: Open Xcode if requested
### Environment-Specific Builds
#### Development Environment (`--dev`)
```bash
# Uses --mode development
npm run build:capacitor
# Builds with development optimizations and debugging enabled
```
#### Testing Environment (`--test`)
```bash
# Uses --mode test
npm run build:capacitor -- --mode test
# Builds with testing configurations and test API endpoints
```
#### Production Environment (`--prod`)
```bash
# Uses --mode production
npm run build:capacitor -- --mode production
# Builds with production optimizations and live API endpoints
```
## Build Artifacts
### App Files
- **Debug App**: `ios/App/build/Debug-iphonesimulator/App.app`
- **Release App**: `ios/App/build/Release-iphoneos/App.app`
### IPA Files
- **Release IPA**: `ios/App/build/Release-iphoneos/App.ipa`
### Build Locations
```bash
# App files
ios/App/build/Debug-iphonesimulator/
ios/App/build/Release-iphoneos/
# IPA files
ios/App/build/Release-iphoneos/
# Xcode build cache
ios/App/build/
ios/App/DerivedData/
```
## Environment Variables
The build system will automatically set environment variables based on the build type:
### Capacitor Environment
```bash
VITE_PLATFORM=capacitor
VITE_PWA_ENABLED=false
VITE_DISABLE_PWA=true
DEBUG_MIGRATIONS=0
```
### Git Integration
```bash
VITE_GIT_HASH=<git-commit-hash>
# Automatically set from current git commit
```
## Error Handling
### Exit Codes
| Code | Description |
|------|-------------|
| 1 | iOS cleanup failed |
| 2 | Web build failed |
| 3 | Capacitor build failed |
| 4 | Xcode clean failed |
| 5 | Xcode build failed |
| 6 | Capacitor sync failed |
| 7 | Asset generation failed |
| 8 | Xcode open failed |
## iOS-Specific Features
### Simulator Support
```bash
# Build for iOS Simulator
npm run build:ios:dev --simulator
# Run on specific simulator
xcrun simctl boot "iPhone 15 Pro"
xcrun simctl install booted ios/App/build/Debug-iphonesimulator/App.app
```
### Device Deployment
```bash
# Build for physical device
npm run build:ios:dev --device
# Install on connected device
xcrun devicectl device install app --device <device-id> ios/App/build/Debug-iphoneos/App.app
```
### Code Signing
```bash
# Development signing
npm run build:ios:dev --development-team <team-id>
# Distribution signing
npm run build:ios:prod --distribution-certificate <cert-id>
```
## Asset Generation
### iOS-Specific Assets
```bash
# Generate iOS assets
npx capacitor-assets generate --ios
# Assets generated
ios/App/App/Assets.xcassets/
├── AppIcon.appiconset/
├── Splash.imageset/
└── SplashDark.imageset/
```
### Asset Requirements
- **App Icon**: 1024x1024 PNG (App Store requirement)
- **Splash Screens**: Multiple sizes for different devices
- **Launch Images**: Optimized for fast app startup
## Xcode Integration
### Xcode Project Structure
```bash
ios/App/
├── App.xcodeproj/ # Xcode project file
├── App.xcworkspace/ # Xcode workspace
├── App/ # iOS app source
│ ├── AppDelegate.swift # App delegate
│ ├── Info.plist # App configuration
│ └── Assets.xcassets/ # App assets
└── Podfile # CocoaPods dependencies
```
### Xcode Build Configurations
- **Debug**: Development with debugging enabled
- **Release**: Production with optimizations
- **Ad Hoc**: Testing distribution
- **App Store**: App Store distribution
## Development Workflow
### Daily Development
```bash
# Development build
npm run build:ios:dev
# Open in Xcode
npm run build:ios:studio
# Run on simulator
xcrun simctl launch booted app.timesafari.app
```
### Testing Workflow
```bash
# Test build
npm run build:ios:test
# Run tests
cd ios/App && xcodebuild test -workspace App.xcworkspace -scheme App -destination 'platform=iOS Simulator,name=iPhone 15 Pro'
```
### Production Workflow
```bash
# Production build
npm run build:ios:prod
# Create IPA for distribution
npm run build:ios:ipa:prod
# Upload to App Store Connect
xcrun altool --upload-app -f ios/App/build/Release-iphoneos/App.ipa -t ios -u <apple-id> -p <app-specific-password>
```
## Troubleshooting
### Common Issues
#### Build Failures
```bash
# Clean Xcode build
cd ios/App && xcodebuild clean -workspace App.xcworkspace -scheme App
# Clean Capacitor
npx cap clean ios
# Rebuild
npm run build:ios:dev
```
#### Simulator Issues
```bash
# Reset simulator
xcrun simctl erase all
# List available simulators
xcrun simctl list devices
# Boot specific simulator
xcrun simctl boot "iPhone 15 Pro"
```
#### Code Signing Issues
```bash
# Check certificates
security find-identity -v -p codesigning
# Check provisioning profiles
ls ~/Library/MobileDevice/Provisioning\ Profiles/
```
### Debug Mode
Enable verbose logging for iOS builds:
```bash
# Verbose mode
./scripts/build-ios.sh --verbose
# Xcode verbose build
cd ios/App && xcodebuild -workspace App.xcworkspace -scheme App -configuration Debug -verbose
```
## Performance Considerations
### Build Performance
- **Incremental Builds**: Only rebuild changed files
- **Parallel Processing**: Multi-core build optimization
- **Caching**: Xcode build cache utilization
- **Asset Optimization**: Image compression and optimization
### Runtime Performance
- **App Launch Time**: Optimized splash screens and assets
- **Memory Usage**: Efficient image loading and caching
- **Battery Life**: Background task optimization
- **Network Performance**: Efficient API communication
## Security Considerations
### iOS Security Features
- **App Sandboxing**: Isolated app environment
- **Code Signing**: Digital signature verification
- **Entitlements**: Controlled access to system resources
- **App Transport Security**: Secure network communication
### Build Security
- **Environment Isolation**: Separate dev/test/prod environments
- **Secret Management**: Secure handling of API keys
- **Dependency Scanning**: Regular security audits
- **Code Signing**: Secure certificate management
## Future Enhancements
### Planned Features
- **CI/CD Integration**: Automated build pipelines
- **Test Automation**: Automated testing framework
- **Performance Monitoring**: Build and runtime performance tracking
- **Asset Optimization**: Advanced image and code optimization
### Platform Expansion
- **App Store**: App Store distribution optimization
- **TestFlight**: Beta testing integration
- **Enterprise Distribution**: Enterprise app distribution
- **Universal Links**: Deep linking support
## Current Status
### ✅ Phase 1: Foundation (Complete)
- [x] Create `build-ios.sh` script
- [x] Implement basic build functionality
- [x] Add environment management
- [x] Integrate with package.json
### ✅ Phase 2: Advanced Features (Complete)
- [x] Add Xcode integration
- [x] Implement asset generation
- [x] Add simulator support
- [x] Add device deployment
### ✅ Phase 3: Optimization (Complete)
- [x] Performance optimization
- [x] Error handling improvements
- [x] Documentation completion
- [x] Testing and validation
---
**Last Updated**: 2025-07-11
**Version**: 1.0.3-beta
**Status**: Production Ready

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

Loading…
Cancel
Save