Browse Source

Merge branch 'master' into profile_include_location

profile_include_location
Matthew Raymer 2 days ago
parent
commit
95a8f5ebe1
  1. 10
      .cursor/rules/adr_template.mdc
  2. 282
      .cursor/rules/app/architectural_decision_record.mdc
  3. 413
      .cursor/rules/app/timesafari.mdc
  4. 49
      .cursor/rules/asset_configuration.mdc
  5. 96
      .cursor/rules/base_context.mdc
  6. 47
      .cursor/rules/database/absurd-sql.mdc
  7. 5
      .cursor/rules/database/legacy_dexie.mdc
  8. 47
      .cursor/rules/development/type_safety_guide.mdc
  9. 8
      .cursor/rules/features/camera-implementation.mdc
  10. 81
      .cursor/rules/investigation_report_example.mdc
  11. 222
      .cursor/rules/logging_standards.mdc
  12. 4
      .cursor/rules/research_diagnostic.mdc
  13. 209
      .cursor/rules/software_development.mdc
  14. 329
      .cursor/rules/time.mdc
  15. 321
      .cursor/rules/workflow/version_control.mdc
  16. 2
      .env.test
  17. 75
      BUILDING.md
  18. 8
      CHANGELOG.md
  19. 27
      README.md
  20. 4
      android/app/build.gradle
  21. 2
      android/build.gradle
  22. 182
      doc/debug-hook-guide.md
  23. 2
      index.html
  24. 8
      ios/App/App.xcodeproj/project.pbxproj
  25. 3247
      package-lock.json
  26. 14
      package.json
  27. 34
      scripts/build-android.sh
  28. 8
      scripts/build-ios.sh
  29. 110
      scripts/check-dependencies.sh
  30. 62
      scripts/clean-android.sh
  31. 103
      scripts/git-hooks/README.md
  32. 86
      scripts/git-hooks/debug-checker.config
  33. 252
      scripts/git-hooks/pre-commit
  34. 171
      scripts/install-debug-hook.sh
  35. 117
      scripts/test-debug-hook.sh
  36. 24
      src/components/FeedFilters.vue
  37. 6
      src/interfaces/common.ts
  38. 28
      src/interfaces/deepLinks.ts
  39. 120
      src/main.capacitor.ts
  40. 26
      src/main.ts
  41. 72
      src/router/index.ts
  42. 80
      src/services/ProfileService.ts
  43. 352
      src/services/deepLinks.ts
  44. 67
      src/views/AccountViewView.vue
  45. 4
      src/views/DeepLinkErrorView.vue
  46. 110
      src/views/HomeView.vue
  47. 2
      src/views/OnboardMeetingMembersView.vue
  48. 21
      vite.config.common.mts
  49. 6
      vite.config.optimized.mts
  50. 24
      vite.config.utils.mts
  51. 99
      vite.config.web.mts

10
.cursor/rules/adr_template.mdc

@ -2,14 +2,16 @@
## ADR-XXXX-YY-ZZ: [Short Title] ## ADR-XXXX-YY-ZZ: [Short Title]
**Date:** YYYY-MM-DD **Date:** YYYY-MM-DD
**Status:** [PROPOSED | ACCEPTED | REJECTED | DEPRECATED | SUPERSEDED] **Status:** [PROPOSED | ACCEPTED | REJECTED | DEPRECATED | SUPERSEDED]
**Deciders:** [List of decision makers] **Deciders:** [List of decision makers]
**Technical Story:** [Link to issue/PR if applicable] **Technical Story:** [Link to issue/PR if applicable]
## Context ## 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.] [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 ## Decision

282
.cursor/rules/app/architectural_decision_record.mdc

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

413
.cursor/rules/app/timesafari.mdc

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

49
.cursor/rules/asset_configuration.mdc

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

96
.cursor/rules/base_context.mdc

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

47
.cursor/rules/database/absurd-sql.mdc

@ -1,13 +1,23 @@
--- ---
globs: **/db/databaseUtil.ts, **/interfaces/absurd-sql.d.ts, **/src/registerSQLWorker.js, **/services/AbsurdSqlDatabaseService.ts globs: **/db/databaseUtil.ts, **/interfaces/absurd-sql.d.ts, **/src/registerSQLWorker.js, **/
services/AbsurdSqlDatabaseService.ts
alwaysApply: false 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
@ -20,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
``` ```
@ -60,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
@ -78,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
@ -98,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';
@ -109,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';
@ -130,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
@ -146,7 +174,20 @@ 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)
- [SQL.js Documentation](https://github.com/sql-js/sql.js/) - [SQL.js Documentation](https://github.com/sql-js/sql.js/)

5
.cursor/rules/database/legacy_dexie.mdc

@ -2,4 +2,7 @@
globs: **/databaseUtil.ts,**/AccountViewView.vue,**/ContactsView.vue,**/DatabaseMigration.vue,**/NewIdentifierView.vue globs: **/databaseUtil.ts,**/AccountViewView.vue,**/ContactsView.vue,**/DatabaseMigration.vue,**/NewIdentifierView.vue
alwaysApply: false alwaysApply: false
--- ---
All references in the codebase to Dexie apply only to migration from IndexedDb to Sqlite and will be deprecated in future versions. # 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.

47
.cursor/rules/development/type_safety_guide.mdc

@ -1,5 +1,5 @@
--- ---
globs: **/src/**/*,**/scripts/**/*,**/electron/**/* description: when dealing with types and Typesript
alwaysApply: false alwaysApply: false
--- ---
```json ```json
@ -15,8 +15,8 @@ alwaysApply: false
# TypeScript Type Safety Guidelines # TypeScript Type Safety Guidelines
**Author**: Matthew Raymer **Author**: Matthew Raymer
**Date**: 2025-08-16 **Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** **Status**: 🎯 **ACTIVE** - Type safety enforcement
## Overview ## Overview
@ -28,7 +28,8 @@ Practical rules to keep TypeScript strict and predictable. Minimize exceptions.
- Use explicit types. If unknown, use `unknown` and **narrow** via guards. - Use explicit types. If unknown, use `unknown` and **narrow** via guards.
2. **Error handling uses guards** 2. **Error handling uses guards**
- Reuse guards from `src/interfaces/**` (e.g., `isDatabaseError`, `isApiError`). - Reuse guards from `src/interfaces/**` (e.g., `isDatabaseError`,
`isApiError`).
- Catch with `unknown`; never cast to `any`. - Catch with `unknown`; never cast to `any`.
3. **Dynamic property access is type‑safe** 3. **Dynamic property access is type‑safe**
@ -40,12 +41,30 @@ Practical rules to keep TypeScript strict and predictable. Minimize exceptions.
- Avoid `(obj as any)[k]`. - 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) ## Minimal Special Cases (document in PR when used)
- **Vue refs / instances**: Use `ComponentPublicInstance` or specific component - **Vue refs / instances**: Use `ComponentPublicInstance` or specific
types for dynamic refs. component types for dynamic refs.
- **3rd‑party libs without types**: Narrow immediately to a **known interface**; - **3rd‑party libs without types**: Narrow immediately to a **known
do not leave `any` hanging. interface**; do not leave `any` hanging.
## Patterns (short) ## Patterns (short)
@ -106,3 +125,15 @@ const keys = Object.keys(newSettings).filter(
- TS Handbook — https://www.typescriptlang.org/docs/ - TS Handbook — https://www.typescriptlang.org/docs/
- TS‑ESLint — https://typescript-eslint.io/rules/ - TS‑ESLint — https://typescript-eslint.io/rules/
- Vue 3 + TS — https://vuejs.org/guide/typescript/ - 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/

8
.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
@ -219,4 +219,4 @@ Desktop implementation (currently unimplemented).
- Multiple browsers - Multiple browsers
- iOS and Android devices - iOS and Android devices
- Desktop platforms - Desktop platforms
- Various network conditions - Various network conditions

81
.cursor/rules/investigation_report_example.mdc

@ -1,76 +1,117 @@
# Investigation Report Example # Investigation Report Example
**Author**: Matthew Raymer
**Date**: 2025-08-19
**Status**: 🎯 **ACTIVE** - Investigation methodology example
## Investigation — Registration Dialog Test Flakiness ## Investigation — Registration Dialog Test Flakiness
## Objective ## Objective
Identify root cause of flaky tests related to registration dialogs in contact import scenarios.
Identify root cause of flaky tests related to registration dialogs in contact
import scenarios.
## System Map ## System Map
- User action → ContactInputForm → ContactsView.addContact() → handleRegistrationPrompt()
- User action → ContactInputForm → ContactsView.addContact() →
handleRegistrationPrompt()
- setTimeout(1000ms) → Modal dialog → User response → Registration API call - setTimeout(1000ms) → Modal dialog → User response → Registration API call
- Test execution → Wait for dialog → Assert dialog content → Click response button - Test execution → Wait for dialog → Assert dialog content → Click response
button
## Findings (Evidence) ## 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() - **1-second timeout causes flakiness** — evidence:
- **Dialog only appears in direct add flow** — evidence: `src/views/ContactsView.vue:774-800`; addContact() calls handleRegistrationPrompt() after database insert `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 ## 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 - 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 ## 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" - 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) ## Diagnostics (Next Checks)
- [ ] Repro on CI environment vs local - [ ] Repro on CI environment vs local
- [ ] Measure actual dialog appearance timing - [ ] Measure actual dialog appearance timing
- [ ] Test with setTimeout removed - [ ] Test with setTimeout removed
- [ ] Verify import flow doesn't call handleRegistrationPrompt - [ ] Verify import flow doesn't call handleRegistrationPrompt
## Risks & Scope ## Risks & Scope
- Impacted: Contact addition tests, registration workflow tests; Data: None; Users: Test suite reliability
- Impacted: Contact addition tests, registration workflow tests; Data: None;
Users: Test suite reliability
## Decision / Next Steps ## Decision / Next Steps
- Owner: Development Team; By: 2025-01-28 - Owner: Development Team; By: 2025-01-28
- Action: Remove 1-second timeout + add test mode flag; Exit criteria: Tests pass consistently - Action: Remove 1-second timeout + add test mode flag; Exit criteria: Tests
pass consistently
## References ## References
- `src/views/ContactsView.vue:971-1000` - `src/views/ContactsView.vue:971-1000`
- `src/views/ContactImportView.vue:500-520` - `src/views/ContactImportView.vue:500-520`
- `src/views/ContactsView.vue:774-800` - `src/views/ContactsView.vue:774-800`
## Competence Hooks ## 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?"
--- - 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 ## Key Learning Points
### Evidence-First Approach ### Evidence-First Approach
This investigation demonstrates the importance of: This investigation demonstrates the importance of:
1. **Tracing actual code execution** rather than making assumptions 1. **Tracing actual code execution** rather than making assumptions
2. **Citing specific evidence** with file:line references 2. **Citing specific evidence** with file:line references
3. **Validating problem scope** before proposing solutions 3. **Validating problem scope** before proposing solutions
4. **Considering simpler alternatives** before complex architectural changes 4. **Considering simpler alternatives** before complex architectural changes
### Code Path Tracing Value ### Code Path Tracing Value
By tracing the execution paths, we discovered: By tracing the execution paths, we discovered:
- Import flow and direct add flow are completely separate - Import flow and direct add flow are completely separate
- The "multiple dialog interference" problem didn't exist - The "multiple dialog interference" problem didn't exist
- A simple timeout removal would solve the actual issue - A simple timeout removal would solve the actual issue
### Prevention of Over-Engineering ### Prevention of Over-Engineering
The investigation prevented: The investigation prevented:
- Unnecessary database schema changes - Unnecessary database schema changes
- Complex batch registration systems - Complex batch registration systems
- Migration scripts for non-existent problems - Migration scripts for non-existent problems
- Architectural changes based on assumptions - Architectural changes based on assumptions
description:
globs:
alwaysApply: false
--- ---
**Status**: Active investigation methodology
**Priority**: High
**Estimated Effort**: Ongoing reference
**Dependencies**: software_development.mdc
**Stakeholders**: Development team, QA team

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

4
.cursor/rules/research_diagnostic.mdc

@ -31,6 +31,7 @@ steps—**not** code changes.
## Enhanced with Software Development Ruleset ## Enhanced with Software Development Ruleset
When investigating software issues, also apply: When investigating software issues, also apply:
- **Code Path Tracing**: Required for technical investigations - **Code Path Tracing**: Required for technical investigations
- **Evidence Validation**: Ensure claims are code-backed - **Evidence Validation**: Ensure claims are code-backed
- **Solution Complexity Assessment**: Justify architectural changes - **Solution Complexity Assessment**: Justify architectural changes
@ -117,6 +118,7 @@ Copy/paste and fill:
## Code Path Tracing (Required for Software Investigations) ## Code Path Tracing (Required for Software Investigations)
Before proposing solutions, trace the actual execution path: Before proposing solutions, trace the actual execution path:
- [ ] **Entry Points**: Identify where the flow begins (user action, API call, etc.) - [ ] **Entry Points**: Identify where the flow begins (user action, API call, etc.)
- [ ] **Component Flow**: Map which components/methods are involved - [ ] **Component Flow**: Map which components/methods are involved
- [ ] **Data Path**: Track how data moves through the system - [ ] **Data Path**: Track how data moves through the system
@ -136,11 +138,13 @@ Before proposing solutions, trace the actual execution path:
## Integration with Other Rulesets ## Integration with Other Rulesets
### With software_development.mdc ### With software_development.mdc
- **Enhanced Evidence Validation**: Use code path tracing for technical investigations - **Enhanced Evidence Validation**: Use code path tracing for technical investigations
- **Architecture Assessment**: Apply complexity justification to proposed solutions - **Architecture Assessment**: Apply complexity justification to proposed solutions
- **Impact Analysis**: Assess effects on existing systems before recommendations - **Impact Analysis**: Assess effects on existing systems before recommendations
### With base_context.mdc ### With base_context.mdc
- **Competence Building**: Focus on technical investigation skills - **Competence Building**: Focus on technical investigation skills
- **Collaboration**: Structure outputs for team review and discussion - **Collaboration**: Structure outputs for team review and discussion

209
.cursor/rules/software_development.mdc

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

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

321
.cursor/rules/workflow/version_control.mdc

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

2
.env.test

@ -7,7 +7,7 @@ VITE_LOG_LEVEL=info
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

75
BUILDING.md

@ -1017,47 +1017,27 @@ If you need to build manually or want to understand the individual steps:
export GEM_PATH=$shortened_path export GEM_PATH=$shortened_path
``` ```
1. Build the web assets & update ios: 1. Bump the version in package.json, then here.
```bash
rm -rf dist
npm run build:web
npm run build:capacitor
npx cap sync ios
```
- If that fails with "Could not find..." then look at the "gem_path" instructions above.
3. Copy the assets:
```bash
# It makes no sense why capacitor-assets will not run without these but it actually changes the contents.
mkdir -p ios/App/App/Assets.xcassets/AppIcon.appiconset
echo '{"images":[]}' > ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json
mkdir -p ios/App/App/Assets.xcassets/Splash.imageset
echo '{"images":[]}' > ios/App/App/Assets.xcassets/Splash.imageset/Contents.json
npx capacitor-assets generate --ios
``` ```
cd ios/App && xcrun agvtool new-version 40 && perl -p -i -e "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 1.0.7;/g" App.xcodeproj/project.pbxproj && cd -
4. Bump the version to match Android & package.json:
```
cd ios/App && xcrun agvtool new-version 39 && perl -p -i -e "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 1.0.6;/g" App.xcodeproj/project.pbxproj && cd -
# Unfortunately this edits Info.plist directly. # Unfortunately this edits Info.plist directly.
#xcrun agvtool new-marketing-version 0.4.5 #xcrun agvtool new-marketing-version 0.4.5
``` ```
5. Open the project in Xcode: 2. Build.
```bash Here's prod. Also available: test, dev
npx cap open ios
``` ```bash
npm run build:ios:prod
```
6. Use Xcode to build and run on simulator or device. 3.1. Use Xcode to build and run on simulator or device.
* Select Product -> Destination with some Simulator version. Then click the run arrow. * Select Product -> Destination with some Simulator version. Then click the run arrow.
7. Release 3.2. Use Xcode to release.
* Someday: Under "General" we want to rename a bunch of things to "Time Safari" * Someday: Under "General" we want to rename a bunch of things to "Time Safari"
* Choose Product -> Destination -> Any iOS Device * Choose Product -> Destination -> Any iOS Device
@ -1125,35 +1105,28 @@ The recommended way to build for Android is using the automated build script:
#### Manual Build Process #### Manual Build Process
1. Build the web assets: 1. Bump the version in package.json, then here: android/app/build.gradle
```bash
rm -rf dist
npm run build:web
npm run build:capacitor
```
2. Update Android project with latest build:
```bash ```bash
npx cap sync android perl -p -i -e 's/versionCode .*/versionCode 40/g' android/app/build.gradle
``` perl -p -i -e 's/versionName .*/versionName "1.0.7"/g' android/app/build.gradle
```
3. Copy the assets 2. Build.
```bash Here's prod. Also available: test, dev
npx capacitor-assets generate --android
```
4. Bump version to match iOS & package.json: android/app/build.gradle ```bash
npm run build:android:prod
```
5. Open the project in Android Studio: 3. Open the project in Android Studio:
```bash ```bash
npx cap open android npx cap open android
``` ```
6. Use Android Studio to build and run on emulator or device. 4. Use Android Studio to build and run on emulator or device.
## Android Build from the console ## Android Build from the console
@ -1186,9 +1159,9 @@ cd -
At play.google.com/console: At play.google.com/console:
- Go to the Testing Track (eg. Closed). - Go to Production or the Closed Testing and either Create Track or Manage Track.
- Click "Create new release". - Click "Create new release".
- Upload the `aab` file. - Upload the `aab` file from: app/build/outputs/bundle/release/app-release.aab
- Hit "Next". - Hit "Next".
- Save, go to "Publishing Overview" as prompted, and click "Send changes for review". - Save, go to "Publishing Overview" as prompted, and click "Send changes for review".

8
CHANGELOG.md

@ -5,12 +5,10 @@ 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) - Deep link for onboard-meeting-members
- Error in BVC begin view
## [1.0.6] - 2025.08.09 ## [1.0.6] - 2025.08.09
### Fixed ### Fixed

27
README.md

@ -170,6 +170,33 @@ npm run assets:clean
npm run build:native npm run build:native
``` ```
### Environment Setup & Dependencies
Before building the application, ensure your development environment is properly
configured:
```bash
# Install all dependencies (required first time and after updates)
npm install
# Validate your development environment
npm run check:dependencies
# Check prerequisites for testing
npm run test:prerequisites
```
**Common Issues & Solutions**:
- **"tsx: command not found"**: Run `npm install` to install devDependencies
- **"capacitor-assets: command not found"**: Ensure `@capacitor/assets` is installed
- **Build failures**: Run `npm run check:dependencies` to diagnose environment issues
**Required Versions**:
- Node.js: 18+ (LTS recommended)
- npm: 8+ (comes with Node.js)
- Platform-specific tools: Android Studio, Xcode (for mobile builds)
### Platform Support ### Platform Support
- **Android**: Adaptive icons with foreground/background, monochrome support - **Android**: Adaptive icons with foreground/background, monochrome support

4
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 39 versionCode 40
versionName "1.0.6" 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.

2
android/build.gradle

@ -7,7 +7,7 @@ buildscript {
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:8.12.0' 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

182
doc/debug-hook-guide.md

@ -0,0 +1,182 @@
# 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

2
index.html

@ -11,6 +11,6 @@
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
<script type="module" src="/src/main.web.ts"></script> <script type="module" src="/src/main.ts"></script>
</body> </body>
</html> </html>

8
ios/App/App.xcodeproj/project.pbxproj

@ -403,7 +403,7 @@
buildSettings = { buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 39; CURRENT_PROJECT_VERSION = 40;
DEVELOPMENT_TEAM = GM3FS5JQPH; DEVELOPMENT_TEAM = GM3FS5JQPH;
ENABLE_APP_SANDBOX = NO; ENABLE_APP_SANDBOX = NO;
ENABLE_USER_SCRIPT_SANDBOXING = NO; ENABLE_USER_SCRIPT_SANDBOXING = NO;
@ -413,7 +413,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 1.0.6; MARKETING_VERSION = 1.0.7;
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\""; OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari; PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
@ -430,7 +430,7 @@
buildSettings = { buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 39; CURRENT_PROJECT_VERSION = 40;
DEVELOPMENT_TEAM = GM3FS5JQPH; DEVELOPMENT_TEAM = GM3FS5JQPH;
ENABLE_APP_SANDBOX = NO; ENABLE_APP_SANDBOX = NO;
ENABLE_USER_SCRIPT_SANDBOXING = NO; ENABLE_USER_SCRIPT_SANDBOXING = NO;
@ -440,7 +440,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 1.0.6; MARKETING_VERSION = 1.0.7;
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari; PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = ""; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";

3247
package-lock.json

File diff suppressed because it is too large

14
package.json

@ -1,6 +1,6 @@
{ {
"name": "timesafari", "name": "timesafari",
"version": "1.0.7-beta", "version": "1.0.8-beta",
"description": "Time Safari Application", "description": "Time Safari Application",
"author": { "author": {
"name": "Time Safari Team" "name": "Time Safari Team"
@ -12,6 +12,8 @@
"type-check": "tsc --noEmit", "type-check": "tsc --noEmit",
"prebuild": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src && node sw_combine.js && node scripts/copy-wasm.js", "prebuild": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src && node sw_combine.js && node scripts/copy-wasm.js",
"test:prerequisites": "node scripts/check-prerequisites.js", "test:prerequisites": "node scripts/check-prerequisites.js",
"check:dependencies": "./scripts/check-dependencies.sh",
"test:all": "npm run lint && tsc && npm run test:web && npm run test:mobile && ./scripts/test-safety-check.sh && echo '\n\n\nGotta add the performance tests'",
"test:web": "npx playwright test -c playwright.config-local.ts --trace on", "test:web": "npx playwright test -c playwright.config-local.ts --trace on",
"test:mobile": "./scripts/test-mobile.sh", "test:mobile": "./scripts/test-mobile.sh",
"test:android": "node scripts/test-android.js", "test:android": "node scripts/test-android.js",
@ -27,8 +29,8 @@
"build:capacitor": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --mode capacitor --config vite.config.capacitor.mts", "build:capacitor": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --mode capacitor --config vite.config.capacitor.mts",
"build:capacitor:sync": "npm run build:capacitor && npx cap sync", "build:capacitor:sync": "npm run build:capacitor && npx cap sync",
"build:native": "vite build && npx cap sync && npx capacitor-assets generate", "build:native": "vite build && npx cap sync && npx capacitor-assets generate",
"assets:config": "tsx scripts/assets-config.ts", "assets:config": "npx tsx scripts/assets-config.ts",
"assets:validate": "tsx scripts/assets-validator.ts", "assets:validate": "npx tsx scripts/assets-validator.ts",
"assets:clean": "rimraf android/app/src/main/res/mipmap-* ios/App/App/Assets.xcassets/**/AppIcon*.png ios/App/App/Assets.xcassets/**/Splash*.png || true", "assets:clean": "rimraf android/app/src/main/res/mipmap-* ios/App/App/Assets.xcassets/**/AppIcon*.png ios/App/App/Assets.xcassets/**/Splash*.png || true",
"build:ios": "./scripts/build-ios.sh", "build:ios": "./scripts/build-ios.sh",
"build:ios:dev": "./scripts/build-ios.sh --dev", "build:ios:dev": "./scripts/build-ios.sh --dev",
@ -96,7 +98,7 @@
"build:electron:dmg:dev": "./scripts/build-electron.sh --dev --dmg", "build:electron:dmg:dev": "./scripts/build-electron.sh --dev --dmg",
"build:electron:dmg:test": "./scripts/build-electron.sh --test --dmg", "build:electron:dmg:test": "./scripts/build-electron.sh --test --dmg",
"build:electron:dmg:prod": "./scripts/build-electron.sh --prod --dmg", "build:electron:dmg:prod": "./scripts/build-electron.sh --prod --dmg",
"clean:android": "adb uninstall app.timesafari.app || true", "clean:android": "./scripts/clean-android.sh",
"clean:ios": "rm -rf ios/App/build ios/App/Pods ios/App/output ios/App/App/public ios/DerivedData ios/capacitor-cordova-ios-plugins ios/App/App/capacitor.config.json ios/App/App/config.xml || true", "clean:ios": "rm -rf ios/App/build ios/App/Pods ios/App/output ios/App/App/public ios/DerivedData ios/capacitor-cordova-ios-plugins ios/App/App/capacitor.config.json ios/App/App/config.xml || true",
"clean:electron": "./scripts/build-electron.sh --clean", "clean:electron": "./scripts/build-electron.sh --clean",
"clean:all": "npm run clean:ios && npm run clean:android && npm run clean:electron", "clean:all": "npm run clean:ios && npm run clean:android && npm run clean:electron",
@ -200,9 +202,9 @@
"three": "^0.156.1", "three": "^0.156.1",
"ua-parser-js": "^1.0.37", "ua-parser-js": "^1.0.37",
"uint8arrays": "^5.0.0", "uint8arrays": "^5.0.0",
"vue": "^3.5.13", "vue": "3.5.13",
"vue-axios": "^3.5.2", "vue-axios": "^3.5.2",
"vue-facing-decorator": "^3.0.4", "vue-facing-decorator": "3.0.4",
"vue-picture-cropper": "^0.7.0", "vue-picture-cropper": "^0.7.0",
"vue-qrcode-reader": "^5.5.3", "vue-qrcode-reader": "^5.5.3",
"vue-router": "^4.5.0", "vue-router": "^4.5.0",

34
scripts/build-android.sh

@ -49,6 +49,31 @@ set -e
# Source common utilities # Source common utilities
source "$(dirname "$0")/common.sh" source "$(dirname "$0")/common.sh"
# Function to validate critical dependencies
validate_dependencies() {
log_info "Validating critical dependencies..."
# Check if node_modules exists
if [ ! -d "node_modules" ]; then
log_error "node_modules directory not found. Please run 'npm install' first."
exit 1
fi
# Check if tsx is available
if [ ! -f "node_modules/.bin/tsx" ]; then
log_error "tsx dependency not found. Please run 'npm install' first."
exit 1
fi
# Check if capacitor-assets is available
if [ ! -f "node_modules/.bin/capacitor-assets" ]; then
log_error "capacitor-assets dependency not found. Please run 'npm install' first."
exit 1
fi
log_success "All critical dependencies validated successfully"
}
# Default values # Default values
BUILD_MODE="development" BUILD_MODE="development"
BUILD_TYPE="debug" BUILD_TYPE="debug"
@ -179,6 +204,11 @@ parse_android_args "$@"
# Print build header # Print build header
print_header "TimeSafari Android Build Process" print_header "TimeSafari Android Build Process"
# Validate dependencies before proceeding
validate_dependencies
# Log build start
log_info "Starting Android build process at $(date)" log_info "Starting Android build process at $(date)"
log_info "Build mode: $BUILD_MODE" log_info "Build mode: $BUILD_MODE"
log_info "Build type: $BUILD_TYPE" log_info "Build type: $BUILD_TYPE"
@ -257,6 +287,7 @@ fi
# Step 1: Validate asset configuration # Step 1: Validate asset configuration
safe_execute "Validating asset configuration" "npm run assets:validate" || { safe_execute "Validating asset configuration" "npm run assets:validate" || {
log_warn "Asset validation found issues, but continuing with build..." log_warn "Asset validation found issues, but continuing with build..."
log_info "If you encounter build failures, please run 'npm install' first to ensure all dependencies are available."
} }
# Step 2: Clean Android app # Step 2: Clean Android app
@ -337,6 +368,9 @@ if [ "$OPEN_STUDIO" = true ]; then
log_info "Android Studio: opened" log_info "Android Studio: opened"
fi fi
# Reminder about dependency management
log_info "💡 Tip: If you encounter dependency issues, run 'npm install' to ensure all packages are up to date."
print_footer "Android Build" print_footer "Android Build"
# Exit with success # Exit with success

8
scripts/build-ios.sh

@ -173,20 +173,20 @@ check_ios_resources() {
# Check for required assets # Check for required assets
if [ ! -f "assets/icon.png" ]; then if [ ! -f "assets/icon.png" ]; then
log_warning "App icon not found at assets/icon.png" log_warn "App icon not found at assets/icon.png"
fi fi
if [ ! -f "assets/splash.png" ]; then if [ ! -f "assets/splash.png" ]; then
log_warning "Splash screen not found at assets/splash.png" log_warn "Splash screen not found at assets/splash.png"
fi fi
# Check for iOS-specific files # Check for iOS-specific files
if [ ! -f "ios/App/App/Info.plist" ]; then if [ ! -f "ios/App/App/Info.plist" ]; then
log_warning "Info.plist not found" log_warn "Info.plist not found"
fi fi
if [ ! -f "ios/App/App/AppDelegate.swift" ]; then if [ ! -f "ios/App/App/AppDelegate.swift" ]; then
log_warning "AppDelegate.swift not found" log_warn "AppDelegate.swift not found"
fi fi
log_success "iOS resource check completed" log_success "iOS resource check completed"

110
scripts/check-dependencies.sh

@ -0,0 +1,110 @@
#!/bin/bash
# check-dependencies.sh
# Author: Matthew Raymer
# Date: 2025-08-19
# Description: Dependency validation script for TimeSafari development environment
# This script checks for critical dependencies required for building the application.
# Exit on any error
set -e
# Source common utilities
source "$(dirname "$0")/common.sh"
print_header "TimeSafari Dependency Validation"
log_info "Checking development environment dependencies..."
# Check Node.js version
if command -v node &> /dev/null; then
NODE_VERSION=$(node --version)
log_info "Node.js version: $NODE_VERSION"
# Extract major version number
MAJOR_VERSION=$(echo $NODE_VERSION | sed 's/v\([0-9]*\)\..*/\1/')
if [ "$MAJOR_VERSION" -lt 18 ]; then
log_error "Node.js version $NODE_VERSION is too old. Please upgrade to Node.js 18 or later."
exit 1
fi
else
log_error "Node.js is not installed. Please install Node.js 18 or later."
exit 1
fi
# Check npm version
if command -v npm &> /dev/null; then
NPM_VERSION=$(npm --version)
log_info "npm version: $NPM_VERSION"
else
log_error "npm is not installed. Please install npm."
exit 1
fi
# Check if node_modules exists
if [ ! -d "node_modules" ]; then
log_error "node_modules directory not found."
log_info "Please run: npm install"
exit 1
fi
# Check critical dependencies
log_info "Validating critical packages..."
CRITICAL_DEPS=("tsx" "capacitor-assets" "vite")
for dep in "${CRITICAL_DEPS[@]}"; do
if [ -f "node_modules/.bin/$dep" ]; then
log_success "$dep found"
else
log_error "$dep not found in node_modules/.bin"
log_info "This usually means the package wasn't installed properly."
log_info "Try running: npm install"
exit 1
fi
done
# Check TypeScript via npx
if npx tsc --version &> /dev/null; then
TSC_VERSION=$(npx tsc --version)
log_success "✓ TypeScript found: $TSC_VERSION"
else
log_error "✗ TypeScript not accessible via npx"
log_info "Try running: npm install"
exit 1
fi
# Check Capacitor CLI
if command -v npx &> /dev/null; then
if npx cap --version &> /dev/null; then
CAP_VERSION=$(npx cap --version)
log_success "✓ Capacitor CLI version: $CAP_VERSION"
else
log_error "✗ Capacitor CLI not accessible via npx"
log_info "Try running: npm install @capacitor/cli"
exit 1
fi
else
log_error "npx is not available. Please ensure npm is properly installed."
exit 1
fi
# Check Android development tools
if command -v adb &> /dev/null; then
log_success "✓ Android Debug Bridge (adb) found"
else
log_warn "⚠ Android Debug Bridge (adb) not found"
log_info "This is only needed for Android development and testing."
fi
if command -v gradle &> /dev/null; then
GRADLE_VERSION=$(gradle --version | head -n 1)
log_success "✓ Gradle found: $GRADLE_VERSION"
else
log_warn "⚠ Gradle not found in PATH"
log_info "This is only needed if building outside of Android Studio."
fi
log_success "Dependency validation completed successfully!"
log_info "Your development environment is ready for TimeSafari development."
print_footer "Dependency Validation"

62
scripts/clean-android.sh

@ -0,0 +1,62 @@
#!/bin/bash
# clean-android.sh
# Author: Matthew Raymer
# Date: 2025-08-19
# Description: Clean Android app with timeout protection to prevent hanging
# This script safely uninstalls the TimeSafari app from connected Android devices
# with a 30-second timeout to prevent indefinite hanging.
# Exit on any error
set -e
# Source common utilities
source "$(dirname "$0")/common.sh"
# Function to implement timeout for systems without timeout command
timeout_command() {
local timeout_seconds="$1"
shift
# Check if timeout command exists
if command -v timeout &> /dev/null; then
timeout "$timeout_seconds" "$@"
else
# Fallback for systems without timeout (like macOS)
# Use perl to implement timeout
perl -e '
eval {
local $SIG{ALRM} = sub { die "timeout" };
alarm shift;
system @ARGV;
alarm 0;
};
if ($@) { exit 1; }
' "$timeout_seconds" "$@"
fi
}
log_info "Starting Android cleanup process..."
# Check if adb is available
if ! command -v adb &> /dev/null; then
log_error "adb command not found. Please install Android SDK Platform Tools."
exit 1
fi
# Check for connected devices
log_info "Checking for connected Android devices..."
if adb devices | grep -q 'device$'; then
log_info "Android device(s) found. Attempting to uninstall app..."
# Try to uninstall with timeout
if timeout_command 30 adb uninstall app.timesafari.app; then
log_success "Successfully uninstalled TimeSafari app"
else
log_warn "Uninstall failed or timed out after 30 seconds"
log_info "This is normal if the app wasn't installed or device is unresponsive"
fi
else
log_info "No Android devices connected. Skipping uninstall."
fi
log_success "Android cleanup process completed"

103
scripts/git-hooks/README.md

@ -0,0 +1,103 @@
# TimeSafari Git Hooks
This directory contains custom Git hooks for the TimeSafari project.
## Debug Code Checker Hook
### Overview
The `pre-commit` hook automatically checks for debug code when committing to protected branches (master, main, production, release). This prevents debug statements from accidentally reaching production code.
### How It Works
1. **Branch Detection**: Only runs on protected branches (configurable)
2. **File Filtering**: Automatically skips test files, scripts, and documentation
3. **Pattern Matching**: Detects common debug patterns using regex
4. **Commit Prevention**: Blocks commits containing debug code
### Protected Branches (Default)
- `master`
- `main`
- `production`
- `release`
- `stable`
### 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
### Configuration
Edit `.git/hooks/debug-checker.config` to customize:
- Protected branches
- Debug patterns
- Skip patterns
- Logging level
### Testing the Hook
Run the test script to verify the hook works:
```bash
./scripts/test-debug-hook.sh
```
### Manual Testing
1. Make changes to a file with debug code
2. Stage the file: `git add <filename>`
3. Try to commit: `git commit -m 'test'`
4. Hook should prevent commit if debug code is found
### Bypassing the Hook (Emergency)
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 and only in emergencies.
### Troubleshooting
#### Hook not running
- Ensure the hook is executable: `chmod +x .git/hooks/pre-commit`
- Check if you're on a protected branch
- Verify the hook file exists and has correct permissions
#### False positives
- Add legitimate debug patterns to skip patterns in config
- Use proper logging levels (`logger.info`, `logger.debug`) instead of console
- Move debug code to feature branches first
#### Hook too strict
- Modify debug patterns in config file
- Add more file types to skip patterns
- Adjust protected branch list
### Best Practices
1. **Use feature branches** for development with debug code
2. **Use proper logging** instead of console statements
3. **Test thoroughly** before merging to protected branches
4. **Review commits** to ensure no debug code slips through
5. **Keep config updated** as project needs change
### Integration with CI/CD
This hook works locally. For CI/CD pipelines, consider:
- Running the same checks in your build process
- Adding ESLint rules for console statements
- Using TypeScript strict mode
- Adding debug code detection to PR checks
### Support
If you encounter issues:
1. Check the hook output for specific error messages
2. Verify your branch is in the protected list
3. Review the configuration file
4. Test with the provided test script
5. Check file permissions and git setup

86
scripts/git-hooks/debug-checker.config

@ -0,0 +1,86 @@
# TimeSafari Debug Checker Configuration
# Edit this file to customize protected branches and debug patterns
# Protected branches where debug code checking is enforced
# Add or remove branches as needed
PROTECTED_BRANCHES=(
"master"
"main"
"production"
"release"
"stable"
)
# Debug patterns to detect (regex patterns)
# Add or remove patterns as needed
DEBUG_PATTERNS=(
# Console statements
"console\."
# Template debug text
"Debug:"
"debug:"
# Debug constants and variables
"DEBUG_"
"debug_"
# HTML debug comments
"<!-- debug"
# Debug attributes
"debug.*="
# Vue debug patterns
"v-if.*debug"
"v-show.*debug"
# Common debug text
"TODO.*debug"
"FIXME.*debug"
# Debug imports (uncomment if you want to catch these)
# "import.*debug"
# "require.*debug"
)
# Files and directories to skip during checking
# Add patterns to exclude from debug checking
SKIP_PATTERNS=(
"\.(test|spec)\.(js|ts|vue)$" # Test files (must have .test. or .spec.)
"^scripts/" # Scripts directory
"^test-.*/" # Test directories (must end with /)
"^\.git/" # Git directory
"^node_modules/" # Dependencies
"^docs/" # Documentation
"^\.cursor/" # Cursor IDE files
"\.md$" # Markdown files
"\.txt$" # Text files
"\.json$" # JSON config files
"\.yml$" # YAML config files
"\.yaml$" # YAML config files
)
# Files that are whitelisted for console statements
# These files may contain intentional console.log statements that are
# properly whitelisted with eslint-disable-next-line no-console comments
WHITELIST_FILES=(
"src/services/platforms/WebPlatformService.ts" # Worker context logging
"src/services/platforms/CapacitorPlatformService.ts" # Platform-specific logging
"src/services/platforms/ElectronPlatformService.ts" # Electron-specific logging
"src/services/QRScanner/.*" # QR Scanner services
"src/utils/logger.ts" # Logger utility itself
"src/utils/LogCollector.ts" # Log collection utilities
"scripts/.*" # Build and utility scripts
"test-.*/.*" # Test directories
".*\.test\..*" # Test files
".*\.spec\..*" # Spec files
)
# Logging level (debug, info, warn, error)
LOG_LEVEL="info"
# Exit codes
EXIT_SUCCESS=0
EXIT_DEBUG_FOUND=1
EXIT_ERROR=2

252
scripts/git-hooks/pre-commit

@ -0,0 +1,252 @@
#!/bin/bash
# TimeSafari Pre-commit Hook - Debug Code Checker
# Only runs on master or specified branches to catch debug code before it reaches production
# Hook directory
HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="$HOOK_DIR/debug-checker.config"
# Default configuration (fallback if config file is missing)
DEFAULT_PROTECTED_BRANCHES=("master" "main" "production" "release")
DEFAULT_DEBUG_PATTERNS=(
"console\."
"Debug:"
"debug:"
"DEBUG_"
"debug_"
"<!-- debug"
"debug.*="
)
DEFAULT_WHITELIST_FILES=(
"src/services/platforms/WebPlatformService.ts"
"src/services/platforms/CapacitorPlatformService.ts"
"src/services/platforms/ElectronPlatformService.ts"
)
# Load configuration from file if it exists
load_config() {
if [[ -f "$CONFIG_FILE" ]]; then
# Source the config file to load variables
# We'll use a safer approach by reading and parsing
PROTECTED_BRANCHES=()
DEBUG_PATTERNS=()
SKIP_PATTERNS=()
WHITELIST_FILES=()
# Read protected branches
while IFS= read -r line; do
if [[ "$line" =~ ^PROTECTED_BRANCHES=\( ]]; then
# Start reading array
while IFS= read -r line; do
if [[ "$line" =~ ^\)$ ]]; then
break
fi
if [[ "$line" =~ \"([^\"]+)\" ]]; then
PROTECTED_BRANCHES+=("${BASH_REMATCH[1]}")
fi
done
fi
done < "$CONFIG_FILE"
# Read debug patterns
while IFS= read -r line; do
if [[ "$line" =~ ^DEBUG_PATTERNS=\( ]]; then
while IFS= read -r line; do
if [[ "$line" =~ ^\)$ ]]; then
break
fi
if [[ "$line" =~ \"([^\"]+)\" ]]; then
DEBUG_PATTERNS+=("${BASH_REMATCH[1]}")
fi
done
fi
done < "$CONFIG_FILE"
# Read skip patterns
while IFS= read -r line; do
if [[ "$line" =~ ^SKIP_PATTERNS=\( ]]; then
while IFS= read -r line; do
if [[ "$line" =~ ^\)$ ]]; then
break
fi
if [[ "$line" =~ \"([^\"]+)\" ]]; then
SKIP_PATTERNS+=("${BASH_REMATCH[1]}")
fi
done
fi
done < "$CONFIG_FILE"
# Read whitelist files
while IFS= read -r line; do
if [[ "$line" =~ ^WHITELIST_FILES=\( ]]; then
while IFS= read -r line; do
if [[ "$line" =~ ^\)$ ]]; then
break
fi
if [[ "$line" =~ \"([^\"]+)\" ]]; then
WHITELIST_FILES+=("${BASH_REMATCH[1]}")
fi
done
fi
done < "$CONFIG_FILE"
fi
# Use defaults if config loading failed
if [[ ${#PROTECTED_BRANCHES[@]} -eq 0 ]]; then
PROTECTED_BRANCHES=("${DEFAULT_PROTECTED_BRANCHES[@]}")
fi
if [[ ${#DEBUG_PATTERNS[@]} -eq 0 ]]; then
DEBUG_PATTERNS=("${DEFAULT_DEBUG_PATTERNS[@]}")
fi
if [[ ${#SKIP_PATTERNS[@]} -eq 0 ]]; then
SKIP_PATTERNS=("${DEFAULT_SKIP_PATTERNS[@]}")
fi
if [[ ${#WHITELIST_FILES[@]} -eq 0 ]]; then
WHITELIST_FILES=("${DEFAULT_WHITELIST_FILES[@]}")
fi
}
# Check if current branch is protected
is_protected_branch() {
local branch="$1"
for protected in "${PROTECTED_BRANCHES[@]}"; do
if [[ "$branch" == "$protected" ]]; then
return 0
fi
done
return 1
}
# Check if file should be skipped
should_skip_file() {
local file="$1"
for pattern in "${SKIP_PATTERNS[@]}"; do
if [[ "$file" =~ $pattern ]]; then
return 0
fi
done
return 1
}
# Check if file is whitelisted for console statements
is_whitelisted_file() {
local file="$1"
for whitelisted in "${WHITELIST_FILES[@]}"; do
if [[ "$file" =~ $whitelisted ]]; then
return 0
fi
done
return 1
}
# Main execution
main() {
# Load configuration
load_config
# Get current branch name
CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null)
if [[ -z "$CURRENT_BRANCH" ]]; then
echo "⚠️ Could not determine current branch, skipping debug check"
exit 0
fi
# Check if we should run the hook
if ! is_protected_branch "$CURRENT_BRANCH"; then
echo "🔒 Pre-commit hook skipped - not on protected branch ($CURRENT_BRANCH)"
echo " Protected branches: ${PROTECTED_BRANCHES[*]}"
exit 0
fi
echo "🔍 Running debug code check on protected branch: $CURRENT_BRANCH"
echo " Using config: $CONFIG_FILE"
# Get all staged files (modified, added, copied, merged)
ALL_STAGED_FILES=$(git diff --cached --name-only)
if [ -z "$ALL_STAGED_FILES" ]; then
echo "✅ No staged files to check"
exit 0
fi
# Initialize error tracking
ERRORS_FOUND=0
ERROR_MESSAGES=()
FILES_CHECKED=0
# Check each staged file for debug patterns
for file in $ALL_STAGED_FILES; do
# Skip files that should be ignored
if should_skip_file "$file"; then
continue
fi
FILES_CHECKED=$((FILES_CHECKED + 1))
# Check for debug patterns in the file
for pattern in "${DEBUG_PATTERNS[@]}"; do
# Skip console pattern checks for whitelisted files
if [[ "$pattern" == "console\." ]] && is_whitelisted_file "$file"; then
continue
fi
# For new files, check the file content directly
# For modified files, check the staged diff
if [[ -f "$file" ]]; then
# New file - check content directly
if grep -E "$pattern" "$file" > /dev/null; then
ERRORS_FOUND=$((ERRORS_FOUND + 1))
ERROR_MESSAGES+=("🚨 $file: Found debug pattern '$pattern'")
fi
else
# Modified file - check staged diff
if git diff --cached "$file" | grep -E "$pattern" > /dev/null; then
ERRORS_FOUND=$((ERRORS_FOUND + 1))
ERROR_MESSAGES+=("🚨 $file: Found debug pattern '$pattern'")
fi
fi
done
done
# Report results
if [ $ERRORS_FOUND -gt 0 ]; then
echo ""
echo "❌ Debug code detected in staged files!"
echo " Branch: $CURRENT_BRANCH"
echo " Files checked: $FILES_CHECKED"
echo " Errors found: $ERRORS_FOUND"
echo ""
for msg in "${ERROR_MESSAGES[@]}"; do
echo " $msg"
done
echo ""
echo "💡 Please remove debug code before committing to $CURRENT_BRANCH"
echo " Common debug patterns to check:"
echo " - console.log, console.debug, console.error"
echo " - Debug: or debug: in templates"
echo " - DEBUG_ constants"
echo " - HTML comments with debug"
echo ""
echo " If debug code is intentional, consider:"
echo " - Moving to a feature branch first"
echo " - Using proper logging levels (logger.info, logger.debug)"
echo " - Adding debug code to .gitignore or .debugignore"
echo ""
echo " Configuration file: $CONFIG_FILE"
exit 1
else
echo "✅ No debug code found in $FILES_CHECKED staged files"
exit 0
fi
}
# Run main function
main "$@"

171
scripts/install-debug-hook.sh

@ -0,0 +1,171 @@
#!/bin/bash
# TimeSafari Debug Hook Installer
# Run this script in any repository to install the debug pre-commit hook
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo -e "${BLUE}🔧 TimeSafari Debug Hook Installer${NC}"
echo "============================================="
# Check if we're in a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
echo -e "${RED}❌ Error: Not in a git repository${NC}"
echo "Please run this script from within a git repository"
exit 1
fi
# Get repository root
REPO_ROOT=$(git rev-parse --show-toplevel)
HOOKS_DIR="$REPO_ROOT/.git/hooks"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo -e "${BLUE}Repository:${NC} $REPO_ROOT"
echo -e "${BLUE}Hooks directory:${NC} $HOOKS_DIR"
echo -e "${BLUE}Script directory:${NC} $SCRIPT_DIR"
# Check if hooks directory exists
if [[ ! -d "$HOOKS_DIR" ]]; then
echo -e "${RED}❌ Error: Hooks directory not found${NC}"
echo "This repository may not be properly initialized"
exit 1
fi
# Check if we have the hook files in the repository
HOOK_SCRIPT="$SCRIPT_DIR/git-hooks/pre-commit"
CONFIG_FILE="$SCRIPT_DIR/git-hooks/debug-checker.config"
if [[ ! -f "$HOOK_SCRIPT" ]]; then
echo -e "${RED}❌ Error: Pre-commit hook script not found${NC}"
echo "Expected location: $HOOK_SCRIPT"
echo "Make sure you're running this from the TimeSafari repository"
exit 1
fi
if [[ ! -f "$CONFIG_FILE" ]]; then
echo -e "${RED}❌ Error: Debug checker config not found${NC}"
echo "Expected location: $CONFIG_FILE"
echo "Make sure you're running this from the TimeSafari repository"
exit 1
fi
# Check if already installed
if [[ -f "$HOOKS_DIR/pre-commit" && -f "$HOOKS_DIR/debug-checker.config" ]]; then
echo -e "${YELLOW}⚠️ Debug hook already appears to be installed${NC}"
echo -e " Checking if update is needed..."
# Check if files are different
if diff "$HOOK_SCRIPT" "$HOOKS_DIR/pre-commit" > /dev/null 2>&1; then
echo -e " ${GREEN}${NC} Hook script is up to date"
HOOK_UP_TO_DATE=true
else
echo -e " ${YELLOW}⚠️ Hook script differs - will update${NC}"
HOOK_UP_TO_DATE=false
fi
if diff "$CONFIG_FILE" "$HOOKS_DIR/debug-checker.config" > /dev/null 2>&1; then
echo -e " ${GREEN}${NC} Config file is up to date"
CONFIG_UP_TO_DATE=true
else
echo -e " ${YELLOW}⚠️ Config file differs - will update${NC}"
CONFIG_UP_TO_DATE=false
fi
if [[ "$HOOK_UP_TO_DATE" == true && "$CONFIG_UP_TO_DATE" == true ]]; then
echo -e "\n${GREEN}✅ Debug hook is already up to date!${NC}"
echo -e " No installation needed"
else
echo -e "\n${BLUE}Updating existing installation...${NC}"
fi
else
echo -e "\n${BLUE}Installing debug hook...${NC}"
fi
# Copy/update the hook script if needed
if [[ "$HOOK_UP_TO_DATE" != true ]]; then
cp "$HOOK_SCRIPT" "$HOOKS_DIR/pre-commit"
chmod +x "$HOOKS_DIR/pre-commit"
echo -e " ${GREEN}${NC} Pre-commit hook installed/updated"
fi
# Copy/update the config file if needed
if [[ "$CONFIG_UP_TO_DATE" != true ]]; then
cp "$CONFIG_FILE" "$HOOKS_DIR/debug-checker.config"
echo -e " ${GREEN}${NC} Configuration file installed/updated"
fi
# Copy/update the README if needed
README_FILE="$SCRIPT_DIR/git-hooks/README.md"
if [[ -f "$README_FILE" ]]; then
if [[ ! -f "$HOOKS_DIR/README.md" ]] || ! diff "$README_FILE" "$HOOKS_DIR/README.md" > /dev/null 2>&1; then
cp "$README_FILE" "$HOOKS_DIR/README.md"
echo -e " ${GREEN}${NC} Documentation installed/updated"
else
echo -e " ${GREEN}${NC} Documentation is up to date"
fi
fi
echo -e "\n${GREEN}🎉 Debug hook installation complete!${NC}"
# Test the installation
echo -e "\n${BLUE}Testing installation...${NC}"
if [[ -x "$HOOKS_DIR/pre-commit" ]]; then
echo -e " ${GREEN}${NC} Hook is executable"
else
echo -e " ${RED}${NC} Hook is not executable"
fi
if [[ -f "$HOOKS_DIR/debug-checker.config" ]]; then
echo -e " ${GREEN}${NC} Config file exists"
else
echo -e " ${RED}${NC} Config file missing"
fi
# Show current branch status
CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || echo "detached")
echo -e "\n${BLUE}Current branch:${NC} $CURRENT_BRANCH"
# Check if this is a protected branch
PROTECTED_BRANCHES=("master" "main" "production" "release" "stable")
IS_PROTECTED=false
for branch in "${PROTECTED_BRANCHES[@]}"; do
if [[ "$CURRENT_BRANCH" == "$branch" ]]; then
IS_PROTECTED=true
break
fi
done
if [[ "$IS_PROTECTED" == true ]]; then
echo -e "${YELLOW}⚠️ You're on a protected branch ($CURRENT_BRANCH)${NC}"
echo -e " The debug hook will now run on all commits to this branch"
echo -e " Consider switching to a feature branch for development"
else
echo -e "${GREEN}✅ You're on a feature branch ($CURRENT_BRANCH)${NC}"
echo -e " The debug hook will be skipped on this branch"
echo -e " You can develop with debug code freely"
fi
echo -e "\n${BLUE}Next steps:${NC}"
echo "1. The hook will now run automatically on protected branches"
echo "2. Test it by trying to commit a file with debug code"
echo "3. Use feature branches for development with debug code"
echo "4. Check the README.md in .git/hooks/ for more information"
echo -e "\n${BLUE}To test the hook:${NC}"
echo "1. Create a test file with debug code (e.g., console.log('test'))"
echo "2. Stage it: git add <filename>"
echo "3. Try to commit: git commit -m 'test'"
echo "4. The hook should prevent the commit if debug code is found"
echo -e "\n${BLUE}To uninstall:${NC}"
echo "rm $HOOKS_DIR/pre-commit"
echo "rm $HOOKS_DIR/debug-checker.config"
echo "rm $HOOKS_DIR/README.md"

117
scripts/test-debug-hook.sh

@ -0,0 +1,117 @@
#!/bin/bash
# Test script for the debug pre-commit hook
# This script helps verify that the hook is working correctly
set -e
echo "🧪 Testing TimeSafari Debug Pre-commit Hook"
echo "============================================="
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Test directory
TEST_DIR="$(mktemp -d)"
echo -e "${BLUE}Created test directory: $TEST_DIR${NC}"
# Function to cleanup
cleanup() {
echo -e "${YELLOW}Cleaning up test directory...${NC}"
rm -rf "$TEST_DIR"
}
# Set trap to cleanup on exit
trap cleanup EXIT
# Function to run test
run_test() {
local test_name="$1"
local test_file="$2"
local expected_exit="$3"
echo -e "\n${BLUE}Running test: $test_name${NC}"
# Create test file
echo "$test_file" > "$TEST_DIR/test.vue"
# Stage the file
cd "$TEST_DIR"
git init > /dev/null 2>&1
git add test.vue > /dev/null 2>&1
# Run the hook
if bash ../../.git/hooks/pre-commit > hook_output.txt 2>&1; then
exit_code=0
else
exit_code=$?
fi
# Check result
if [[ $exit_code -eq $expected_exit ]]; then
echo -e " ${GREEN}✅ PASS${NC} - Exit code: $exit_code (expected: $expected_exit)"
else
echo -e " ${RED}❌ FAIL${NC} - Exit code: $exit_code (expected: $expected_exit)"
echo -e " ${YELLOW}Hook output:${NC}"
cat hook_output.txt
fi
# Cleanup git
rm -rf .git
rm -f hook_output.txt
}
# Test cases
echo -e "\n${BLUE}Test Case 1: Clean file (should pass)${NC}"
run_test "Clean file" "// No debug code here" 0
echo -e "\n${BLUE}Test Case 2: Console statement (should fail)${NC}"
run_test "Console statement" "console.log('debug info')" 1
echo -e "\n${BLUE}Test Case 3: Debug template (should fail)${NC}"
run_test "Debug template" "Debug: {{ isMapReady ? 'Map Ready' : 'Map Loading' }}" 1
echo -e "\n${BLUE}Test Case 4: Debug constant (should fail)${NC}"
run_test "Debug constant" "const DEBUG_MODE = true" 1
echo -e "\n${BLUE}Test Case 5: Mixed content (should fail)${NC}"
run_test "Mixed content" "// Some normal code\nconsole.debug('test')\n// More normal code" 1
echo -e "\n${BLUE}Test Case 6: HTML debug comment (should fail)${NC}"
run_test "HTML debug comment" "<!-- debug: this is debug info -->" 1
echo -e "\n${BLUE}Test Case 7: Debug attribute (should fail)${NC}"
run_test "Debug attribute" "<div debug='true'>content</div>" 1
echo -e "\n${BLUE}Test Case 8: Test file (should be skipped)${NC}"
run_test "Test file" "console.log('this should be skipped')" 0
# Test branch detection
echo -e "\n${BLUE}Testing branch detection...${NC}"
cd "$TEST_DIR"
git init > /dev/null 2>&1
git checkout -b feature-branch > /dev/null 2>&1
echo "console.log('debug')" > test.vue
git add test.vue > /dev/null 2>&1
if bash ../../.git/hooks/pre-commit > hook_output.txt 2>&1; then
echo -e " ${GREEN}✅ PASS${NC} - Hook skipped on feature branch"
else
echo -e " ${RED}❌ FAIL${NC} - Hook should have been skipped on feature branch"
echo -e " ${YELLOW}Hook output:${NC}"
cat hook_output.txt
fi
rm -rf .git
rm -f hook_output.txt
echo -e "\n${GREEN}🎉 All tests completed!${NC}"
echo -e "\n${BLUE}To test manually:${NC}"
echo "1. Make changes to a file with debug code"
echo "2. Stage the file: git add <filename>"
echo "3. Try to commit: git commit -m 'test'"
echo "4. The hook should prevent the commit if debug code is found"

24
src/components/FeedFilters.vue

@ -101,6 +101,7 @@ import {
import { Router } from "vue-router"; import { Router } from "vue-router";
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin"; import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
import { logger } from "@/utils/logger";
@Component({ @Component({
components: { components: {
@ -119,11 +120,13 @@ export default class FeedFilters extends Vue {
isNearby = false; isNearby = false;
settingChanged = false; settingChanged = false;
visible = false; visible = false;
activeDid = "";
async open(onCloseIfChanged: () => void) { async open(onCloseIfChanged: () => void, activeDid: string) {
this.onCloseIfChanged = onCloseIfChanged; this.onCloseIfChanged = onCloseIfChanged;
this.activeDid = activeDid;
const settings = await this.$settings(); const settings = await this.$accountSettings(activeDid);
this.hasVisibleDid = !!settings.filterFeedByVisible; this.hasVisibleDid = !!settings.filterFeedByVisible;
this.isNearby = !!settings.filterFeedByNearby; this.isNearby = !!settings.filterFeedByNearby;
if (settings.searchBoxes && settings.searchBoxes.length > 0) { if (settings.searchBoxes && settings.searchBoxes.length > 0) {
@ -137,6 +140,7 @@ export default class FeedFilters extends Vue {
async toggleHasVisibleDid() { async toggleHasVisibleDid() {
this.settingChanged = true; this.settingChanged = true;
this.hasVisibleDid = !this.hasVisibleDid; this.hasVisibleDid = !this.hasVisibleDid;
await this.$updateSettings({ await this.$updateSettings({
filterFeedByVisible: this.hasVisibleDid, filterFeedByVisible: this.hasVisibleDid,
}); });
@ -145,9 +149,18 @@ export default class FeedFilters extends Vue {
async toggleNearby() { async toggleNearby() {
this.settingChanged = true; this.settingChanged = true;
this.isNearby = !this.isNearby; this.isNearby = !this.isNearby;
logger.debug("[FeedFilters] 🔄 Toggling nearby filter:", {
newValue: this.isNearby,
settingChanged: this.settingChanged,
activeDid: this.activeDid,
});
await this.$updateSettings({ await this.$updateSettings({
filterFeedByNearby: this.isNearby, filterFeedByNearby: this.isNearby,
}); });
logger.debug("[FeedFilters] ✅ Nearby filter updated in settings");
} }
async clearAll() { async clearAll() {
@ -179,13 +192,20 @@ export default class FeedFilters extends Vue {
} }
close() { close() {
logger.debug("[FeedFilters] 🚪 Closing dialog:", {
settingChanged: this.settingChanged,
hasCallback: !!this.onCloseIfChanged,
});
if (this.settingChanged) { if (this.settingChanged) {
logger.debug("[FeedFilters] 🔄 Settings changed, calling callback");
this.onCloseIfChanged(); this.onCloseIfChanged();
} }
this.visible = false; this.visible = false;
} }
done() { done() {
logger.debug("[FeedFilters] ✅ Done button clicked");
this.close(); this.close();
} }
} }

6
src/interfaces/common.ts

@ -60,9 +60,13 @@ export interface AxiosErrorResponse {
[key: string]: unknown; [key: string]: unknown;
}; };
status?: number; status?: number;
statusText?: string;
config?: unknown; config?: unknown;
}; };
config?: unknown; config?: {
url?: string;
[key: string]: unknown;
};
[key: string]: unknown; [key: string]: unknown;
} }

28
src/interfaces/deepLinks.ts

@ -28,7 +28,7 @@
import { z } from "zod"; import { z } from "zod";
// Parameter validation schemas for each route type // Parameter validation schemas for each route type
export const deepLinkSchemas = { export const deepLinkPathSchemas = {
claim: z.object({ claim: z.object({
id: z.string(), id: z.string(),
}), }),
@ -60,7 +60,7 @@ export const deepLinkSchemas = {
jwt: z.string().optional(), jwt: z.string().optional(),
}), }),
"onboard-meeting-members": z.object({ "onboard-meeting-members": z.object({
id: z.string(), groupId: z.string(),
}), }),
project: z.object({ project: z.object({
id: z.string(), id: z.string(),
@ -70,6 +70,17 @@ export const deepLinkSchemas = {
}), }),
}; };
export const deepLinkQuerySchemas = {
"onboard-meeting-members": z.object({
password: z.string(),
}),
};
// Add a union type of all valid route paths
export const VALID_DEEP_LINK_ROUTES = Object.keys(
deepLinkPathSchemas,
) as readonly (keyof typeof deepLinkPathSchemas)[];
// Create a type from the array // Create a type from the array
export type DeepLinkRoute = (typeof VALID_DEEP_LINK_ROUTES)[number]; export type DeepLinkRoute = (typeof VALID_DEEP_LINK_ROUTES)[number];
@ -80,14 +91,13 @@ export const baseUrlSchema = z.object({
queryParams: z.record(z.string()).optional(), queryParams: z.record(z.string()).optional(),
}); });
// Add a union type of all valid route paths // export type DeepLinkPathParams = {
export const VALID_DEEP_LINK_ROUTES = Object.keys( // [K in keyof typeof deepLinkPathSchemas]: z.infer<(typeof deepLinkPathSchemas)[K]>;
deepLinkSchemas, // };
) as readonly (keyof typeof deepLinkSchemas)[];
export type DeepLinkParams = { // export type DeepLinkQueryParams = {
[K in keyof typeof deepLinkSchemas]: z.infer<(typeof deepLinkSchemas)[K]>; // [K in keyof typeof deepLinkQuerySchemas]: z.infer<(typeof deepLinkQuerySchemas)[K]>;
}; // };
export interface DeepLinkError extends Error { export interface DeepLinkError extends Error {
code: string; code: string;

120
src/main.capacitor.ts

@ -29,14 +29,14 @@
*/ */
import { initializeApp } from "./main.common"; import { initializeApp } from "./main.common";
import { App } from "./libs/capacitor/app"; import { App as CapacitorApp } from "@capacitor/app";
import router from "./router"; import router from "./router";
import { handleApiError } from "./services/api"; import { handleApiError } from "./services/api";
import { AxiosError } from "axios"; import { AxiosError } from "axios";
import { DeepLinkHandler } from "./services/deepLinks"; import { DeepLinkHandler } from "./services/deepLinks";
import { logger, safeStringify } from "./utils/logger"; import { logger, safeStringify } from "./utils/logger";
logger.log("[Capacitor] Starting initialization"); logger.log("[Capacitor] 🚀 Starting initialization");
logger.log("[Capacitor] Platform:", process.env.VITE_PLATFORM); logger.log("[Capacitor] Platform:", process.env.VITE_PLATFORM);
const app = initializeApp(); const app = initializeApp();
@ -67,23 +67,123 @@ const deepLinkHandler = new DeepLinkHandler(router);
* @throws {Error} If URL format is invalid * @throws {Error} If URL format is invalid
*/ */
const handleDeepLink = async (data: { url: string }) => { const handleDeepLink = async (data: { url: string }) => {
const { url } = data;
logger.info(`[Main] 🌐 Deeplink received from Capacitor: ${url}`);
try { try {
// Wait for router to be ready
logger.info(`[Main] ⏳ Waiting for router to be ready...`);
await router.isReady(); await router.isReady();
await deepLinkHandler.handleDeepLink(data.url); logger.info(`[Main] ✅ Router is ready, processing deeplink`);
// Process the deeplink
logger.info(`[Main] 🚀 Starting deeplink processing`);
await deepLinkHandler.handleDeepLink(url);
logger.info(`[Main] ✅ Deeplink processed successfully`);
} catch (error) { } catch (error) {
logger.error("[DeepLink] Error handling deep link: ", error); logger.error(`[Main] ❌ Deeplink processing failed:`, {
url,
error: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
timestamp: new Date().toISOString(),
});
// Log additional context for debugging
logger.error(`[Main] 🔍 Debug context:`, {
routerReady: router.isReady(),
currentRoute: router.currentRoute.value,
appMounted: app._instance?.isMounted,
timestamp: new Date().toISOString(),
});
// Fallback to original error handling
let message: string = let message: string =
error instanceof Error ? error.message : safeStringify(error); error instanceof Error ? error.message : safeStringify(error);
if (data.url) { if (url) {
message += `\nURL: ${data.url}`; message += `\nURL: ${url}`;
} }
handleApiError({ message } as AxiosError, "deep-link"); handleApiError({ message } as AxiosError, "deep-link");
} }
}; };
// Register deep link handler with Capacitor // Function to register the deeplink listener
App.addListener("appUrlOpen", handleDeepLink); const registerDeepLinkListener = async () => {
try {
logger.info(
`[Main] 🔗 Attempting to register deeplink handler with Capacitor`,
);
// Check if Capacitor App plugin is available
logger.info(`[Main] 🔍 Checking Capacitor App plugin availability...`);
if (!CapacitorApp) {
throw new Error("Capacitor App plugin not available");
}
logger.info(`[Main] ✅ Capacitor App plugin is available`);
// Check available methods on CapacitorApp
logger.info(
`[Main] 🔍 Capacitor App plugin methods:`,
Object.getOwnPropertyNames(CapacitorApp),
);
logger.info(
`[Main] 🔍 Capacitor App plugin addListener method:`,
typeof CapacitorApp.addListener,
);
// Wait for router to be ready first
await router.isReady();
logger.info(
`[Main] ✅ Router is ready, proceeding with listener registration`,
);
// Try to register the listener
logger.info(`[Main] 🧪 Attempting to register appUrlOpen listener...`);
const listenerHandle = await CapacitorApp.addListener(
"appUrlOpen",
handleDeepLink,
);
logger.info(
`[Main] ✅ appUrlOpen listener registered successfully with handle:`,
listenerHandle,
);
logger.log("[Capacitor] Mounting app"); // Test the listener registration by checking if it's actually registered
logger.info(`[Main] 🧪 Verifying listener registration...`);
return listenerHandle;
} catch (error) {
logger.error(`[Main] ❌ Failed to register deeplink listener:`, {
error: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
timestamp: new Date().toISOString(),
});
throw error;
}
};
logger.log("[Capacitor] 🚀 Mounting app");
app.mount("#app"); app.mount("#app");
logger.log("[Capacitor] App mounted"); logger.info(`[Main] ✅ App mounted successfully`);
// Register deeplink listener after app is mounted
setTimeout(async () => {
try {
logger.info(
`[Main] ⏳ Delaying listener registration to ensure Capacitor is ready...`,
);
await registerDeepLinkListener();
logger.info(`[Main] 🎉 Deep link system fully initialized!`);
} catch (error) {
logger.error(`[Main] ❌ Deep link system initialization failed:`, error);
}
}, 2000); // 2 second delay to ensure Capacitor is fully ready
// Log app initialization status
setTimeout(() => {
logger.info(`[Main] 📊 App initialization status:`, {
routerReady: router.isReady(),
currentRoute: router.currentRoute.value,
appMounted: app._instance?.isMounted,
timestamp: new Date().toISOString(),
});
}, 1000);

26
src/main.ts

@ -0,0 +1,26 @@
/**
* @file Dynamic Main Entry Point
* @author Matthew Raymer
*
* This file dynamically loads the appropriate platform-specific main entry point
* based on the current environment and build configuration.
*/
import { logger } from "./utils/logger";
// Check the platform from environment variables
const platform = process.env.VITE_PLATFORM || "web";
logger.info(`[Main] 🚀 Loading TimeSafari for platform: ${platform}`);
// Dynamically import the appropriate main entry point
if (platform === "capacitor") {
logger.info(`[Main] 📱 Loading Capacitor-specific entry point`);
import("./main.capacitor");
} else if (platform === "electron") {
logger.info(`[Main] 💻 Loading Electron-specific entry point`);
import("./main.electron");
} else {
logger.info(`[Main] 🌐 Loading Web-specific entry point`);
import("./main.web");
}

72
src/router/index.ts

@ -321,24 +321,21 @@ const errorHandler = (
router.onError(errorHandler); // Assign the error handler to the router instance router.onError(errorHandler); // Assign the error handler to the router instance
/** /**
* Global navigation guard to ensure user identity exists * Navigation guard to ensure user has an identity before accessing protected routes
*
* This guard checks if the user has any identities before navigating to most routes.
* If no identity exists, it automatically creates one using the default seed-based method.
*
* Routes that are excluded from this check:
* - /start - Manual identity creation selection
* - /new-identifier - Manual seed-based creation
* - /import-account - Manual import flow
* - /import-derive - Manual derivation flow
* - /database-migration - Migration utilities
* - /deep-link-error - Error page
*
* @param to - Target route * @param to - Target route
* @param from - Source route * @param _from - Source route (unused)
* @param next - Navigation function * @param next - Navigation function
*/ */
router.beforeEach(async (to, _from, next) => { router.beforeEach(async (to, _from, next) => {
logger.info(`[Router] 🧭 Navigation guard triggered:`, {
from: _from?.path || "none",
to: to.path,
name: to.name,
params: to.params,
query: to.query,
timestamp: new Date().toISOString(),
});
try { try {
// Skip identity check for routes that handle identity creation manually // Skip identity check for routes that handle identity creation manually
const skipIdentityRoutes = [ const skipIdentityRoutes = [
@ -351,32 +348,67 @@ router.beforeEach(async (to, _from, next) => {
]; ];
if (skipIdentityRoutes.includes(to.path)) { if (skipIdentityRoutes.includes(to.path)) {
logger.debug(`[Router] ⏭️ Skipping identity check for route: ${to.path}`);
return next(); return next();
} }
logger.info(`[Router] 🔍 Checking user identity for route: ${to.path}`);
// Check if user has any identities // Check if user has any identities
const allMyDids = await retrieveAccountDids(); const allMyDids = await retrieveAccountDids();
logger.info(`[Router] 📋 Found ${allMyDids.length} user identities`);
if (allMyDids.length === 0) { if (allMyDids.length === 0) {
logger.info("[Router] No identities found, creating default identity"); logger.info("[Router] ⚠️ No identities found, creating default identity");
// Create identity automatically using seed-based method // Create identity automatically using seed-based method
await generateSaveAndActivateIdentity(); await generateSaveAndActivateIdentity();
logger.info("[Router] Default identity created successfully"); logger.info("[Router] ✅ Default identity created successfully");
} else {
logger.info(
`[Router] ✅ User has ${allMyDids.length} identities, proceeding`,
);
} }
logger.info(`[Router] ✅ Navigation guard passed for: ${to.path}`);
next(); next();
} catch (error) { } catch (error) {
logger.error( logger.error("[Router] ❌ Identity creation failed in navigation guard:", {
"[Router] Identity creation failed in navigation guard:", error: error instanceof Error ? error.message : String(error),
error, stack: error instanceof Error ? error.stack : undefined,
); route: to.path,
timestamp: new Date().toISOString(),
});
// Redirect to start page if identity creation fails // Redirect to start page if identity creation fails
// This allows users to manually create an identity or troubleshoot // This allows users to manually create an identity or troubleshoot
logger.info(
`[Router] 🔄 Redirecting to /start due to identity creation failure`,
);
next("/start"); next("/start");
} }
}); });
// Add navigation success logging
router.afterEach((to, from) => {
logger.info(`[Router] ✅ Navigation completed:`, {
from: from?.path || "none",
to: to.path,
name: to.name,
params: to.params,
query: to.query,
timestamp: new Date().toISOString(),
});
});
// Add error logging
router.onError((error) => {
logger.error(`[Router] ❌ Navigation error:`, {
error: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
timestamp: new Date().toISOString(),
});
});
export default router; export default router;

80
src/services/ProfileService.ts

@ -124,31 +124,32 @@ export class ProfileService {
async deleteProfile(activeDid: string): Promise<boolean> { async deleteProfile(activeDid: string): Promise<boolean> {
try { try {
const headers = await getHeaders(activeDid); const headers = await getHeaders(activeDid);
const response = await this.axios.delete( const url = `${this.partnerApiServer}/api/partner/userProfile`;
`${this.partnerApiServer}/api/partner/userProfile`, const response = await this.axios.delete(url, { headers });
{ headers },
);
if (response.status === 200 || response.status === 204) { if (response.status === 204 || response.status === 200) {
logger.info("Profile deleted successfully");
return true; return true;
} else { } else {
logger.error("Unexpected response status when deleting profile:", { logger.error("Unexpected response status when deleting profile:", {
status: response.status, status: response.status,
statusText: response.statusText, statusText: response.statusText,
data: response.data data: response.data,
}); });
throw new Error(`Profile not deleted - HTTP ${response.status}: ${response.statusText}`); throw new Error(
`Profile not deleted - HTTP ${response.status}: ${response.statusText}`,
);
} }
} catch (error) { } catch (error) {
if (this.isApiError(error) && error.response) { if (this.isApiError(error) && error.response) {
const response = error.response as any; // Type assertion for error response const response = error.response;
logger.error("API error deleting profile:", { logger.error("API error deleting profile:", {
status: response.status, status: response.status,
statusText: response.statusText, statusText: response.statusText,
data: response.data, data: response.data,
url: (error as any).config?.url url: this.getErrorUrl(error),
}); });
// Handle specific HTTP status codes // Handle specific HTTP status codes
if (response.status === 204) { if (response.status === 204) {
return true; // 204 is success for DELETE operations return true; // 204 is success for DELETE operations
@ -157,7 +158,11 @@ export class ProfileService {
return true; // Consider this a success if profile doesn't exist return true; // Consider this a success if profile doesn't exist
} else if (response.status === 400) { } else if (response.status === 400) {
logger.error("Bad request when deleting profile:", response.data); logger.error("Bad request when deleting profile:", response.data);
throw new Error(`Profile deletion failed: ${response.data?.message || 'Bad request'}`); const errorMessage =
typeof response.data === "string"
? response.data
: response.data?.message || "Bad request";
throw new Error(`Profile deletion failed: ${errorMessage}`);
} else if (response.status === 401) { } else if (response.status === 401) {
logger.error("Unauthorized to delete profile"); logger.error("Unauthorized to delete profile");
throw new Error("You are not authorized to delete this profile"); throw new Error("You are not authorized to delete this profile");
@ -166,7 +171,7 @@ export class ProfileService {
throw new Error("You are not allowed to delete this profile"); throw new Error("You are not allowed to delete this profile");
} }
} }
logger.error("Error deleting profile:", errorStringForLog(error)); logger.error("Error deleting profile:", errorStringForLog(error));
handleApiError(error as AxiosError, "/api/partner/userProfile"); handleApiError(error as AxiosError, "/api/partner/userProfile");
return false; return false;
@ -236,13 +241,56 @@ export class ProfileService {
} }
/** /**
* Type guard for API errors * Type guard for API errors with proper typing
*/ */
private isApiError( private isApiError(error: unknown): error is {
error: unknown, response?: {
): error is { response?: { status?: number } } { status?: number;
statusText?: string;
data?: { message?: string } | string;
};
} {
return typeof error === "object" && error !== null && "response" in error; return typeof error === "object" && error !== null && "response" in error;
} }
/**
* Extract error URL safely from error object
*/
private getErrorUrl(error: unknown): string | undefined {
if (this.isAxiosError(error)) {
return error.config?.url;
}
if (this.isApiError(error) && this.hasConfigProperty(error)) {
const config = this.getConfigProperty(error);
return config?.url;
}
return undefined;
}
/**
* Type guard to check if error has config property
*/
private hasConfigProperty(
error: unknown,
): error is { config?: { url?: string } } {
return typeof error === "object" && error !== null && "config" in error;
}
/**
* Safely extract config property from error
*/
private getConfigProperty(error: {
config?: { url?: string };
}): { url?: string } | undefined {
return error.config;
}
/**
* Type guard for AxiosError
*/
private isAxiosError(error: unknown): error is AxiosError {
return error instanceof AxiosError;
}
} }
/** /**

352
src/services/deepLinks.ts

@ -1,56 +1,22 @@
/** /**
* @file Deep Link Handler Service * DeepLinks Service
* @author Matthew Raymer
*
* This service handles the processing and routing of deep links in the TimeSafari app.
* It provides a type-safe interface between the raw deep links and the application router.
*
* Architecture:
* 1. DeepLinkHandler class encapsulates all deep link processing logic
* 2. Uses Zod schemas from interfaces/deepLinks for parameter validation
* 3. Provides consistent error handling and logging
* 4. Maps validated parameters to Vue router calls
*
* Error Handling Strategy:
* - All errors are wrapped in DeepLinkError interface
* - Errors include error codes for systematic handling
* - Detailed error information is logged for debugging
* - Errors are propagated to the global error handler
*
* Validation Strategy:
* - URL structure validation
* - Route-specific parameter validation using Zod schemas
* - Query parameter validation and sanitization
* - Type-safe parameter passing to router
* *
* Deep Link Format: * Handles deep link processing and routing for the TimeSafari application.
* timesafari://<route>[/<param>][?queryParam1=value1&queryParam2=value2] * Supports both path parameters and query parameters with comprehensive validation.
* *
* Supported Routes: * @author Matthew Raymer
* - claim: View claim * @version 2.0.0
* - claim-add-raw: Add raw claim * @since 2025-01-25
* - claim-cert: View claim certificate
* - confirm-gift
* - contact-import: Import contacts
* - did: View DID
* - invite-one-accept: Accept invitation
* - onboard-meeting-members
* - project: View project details
* - user-profile: View user profile
*
* @example
* const handler = new DeepLinkHandler(router);
* await handler.handleDeepLink("timesafari://claim/123?view=details");
*/ */
import { Router } from "vue-router"; import { Router } from "vue-router";
import { z } from "zod"; import { z } from "zod";
import { import {
deepLinkSchemas, deepLinkPathSchemas,
baseUrlSchema,
routeSchema, routeSchema,
DeepLinkRoute, DeepLinkRoute,
deepLinkQuerySchemas,
} from "../interfaces/deepLinks"; } from "../interfaces/deepLinks";
import type { DeepLinkError } from "../interfaces/deepLinks"; import type { DeepLinkError } from "../interfaces/deepLinks";
import { logger } from "../utils/logger"; import { logger } from "../utils/logger";
@ -74,7 +40,7 @@ function getFirstKeyFromZodObject(
* because "router.replace" expects the right parameter name for the route. * because "router.replace" expects the right parameter name for the route.
*/ */
export const ROUTE_MAP: Record<string, { name: string; paramKey?: string }> = export const ROUTE_MAP: Record<string, { name: string; paramKey?: string }> =
Object.entries(deepLinkSchemas).reduce( Object.entries(deepLinkPathSchemas).reduce(
(acc, [routeName, schema]) => { (acc, [routeName, schema]) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const paramKey = getFirstKeyFromZodObject(schema as z.ZodObject<any>); const paramKey = getFirstKeyFromZodObject(schema as z.ZodObject<any>);
@ -103,83 +69,152 @@ export class DeepLinkHandler {
} }
/** /**
* Main entry point for processing deep links
* Parses deep link URL into path, params and query components. * @param url - The deep link URL to process
* Validates URL structure using Zod schemas. * @throws {DeepLinkError} If validation fails or route is invalid
*
* @param url - The deep link URL to parse (format: scheme://path[?query])
* @throws {DeepLinkError} If URL format is invalid
* @returns Parsed URL components (path: string, params: {KEY: string}, query: {KEY: string})
*/ */
private parseDeepLink(url: string) { async handleDeepLink(url: string): Promise<void> {
const parts = url.split("://"); logger.info(`[DeepLink] 🚀 Starting deeplink processing for URL: ${url}`);
if (parts.length !== 2) {
throw { code: "INVALID_URL", message: "Invalid URL format" };
}
// Validate base URL structure try {
baseUrlSchema.parse({ logger.info(`[DeepLink] 📍 Parsing URL: ${url}`);
scheme: parts[0], const { path, params, query } = this.parseDeepLink(url);
path: parts[1],
queryParams: {}, // Will be populated below
});
const [path, queryString] = parts[1].split("?"); logger.info(`[DeepLink] ✅ URL parsed successfully:`, {
const [routePath, ...pathParams] = path.split("/"); path,
params: Object.keys(params),
query: Object.keys(query),
fullParams: params,
fullQuery: query,
});
// Validate route exists before proceeding // Sanitize parameters (remove undefined values)
if (!ROUTE_MAP[routePath]) { const sanitizedParams = Object.fromEntries(
throw { Object.entries(params).map(([key, value]) => [key, value ?? ""]),
code: "INVALID_ROUTE", );
message: `Invalid route path: ${routePath}`,
details: { routePath }, logger.info(`[DeepLink] 🧹 Parameters sanitized:`, sanitizedParams);
};
}
const query: Record<string, string> = {}; await this.validateAndRoute(path, sanitizedParams, query);
if (queryString) { logger.info(`[DeepLink] 🎯 Deeplink processing completed successfully`);
new URLSearchParams(queryString).forEach((value, key) => { } catch (error) {
query[key] = value; logger.error(`[DeepLink] ❌ Deeplink processing failed:`, {
url,
error: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
}); });
}
const params: Record<string, string> = {}; const deepLinkError = error as DeepLinkError;
if (pathParams) { throw deepLinkError;
// Now we know routePath exists in ROUTE_MAP
const routeConfig = ROUTE_MAP[routePath];
params[routeConfig.paramKey ?? "id"] = pathParams.join("/");
} }
}
/**
* Parse a deep link URL into its components
* @param url - The deep link URL
* @returns Parsed components
*/
private parseDeepLink(url: string): {
path: string;
params: Record<string, string>;
query: Record<string, string>;
} {
logger.debug(`[DeepLink] 🔍 Parsing deep link: ${url}`);
// logConsoleAndDb( try {
// `[DeepLink] Debug: Route Path: ${routePath} Path Params: ${JSON.stringify(params)} Query String: ${JSON.stringify(query)}`, const parts = url.split("://");
// false, if (parts.length !== 2) {
// ); throw new Error("Invalid URL format");
return { path: routePath, params, query }; }
const [path, queryString] = parts[1].split("?");
const [routePath, ...pathParams] = path.split("/");
// Parse path parameters using route-specific configuration
const params: Record<string, string> = {};
if (pathParams.length > 0) {
// Get the correct parameter key for this route
const routeConfig = ROUTE_MAP[routePath];
if (routeConfig?.paramKey) {
params[routeConfig.paramKey] = pathParams[0];
logger.debug(
`[DeepLink] 📍 Path parameter extracted: ${routeConfig.paramKey}=${pathParams[0]}`,
);
} else {
// Fallback to 'id' for backward compatibility
params.id = pathParams[0];
logger.debug(
`[DeepLink] 📍 Path parameter extracted: id=${pathParams[0]} (fallback)`,
);
}
}
// Parse query parameters
const query: Record<string, string> = {};
if (queryString) {
const queryParams = new URLSearchParams(queryString);
for (const [key, value] of queryParams.entries()) {
query[key] = value;
}
logger.debug(`[DeepLink] 🔗 Query parameters extracted:`, query);
}
logger.info(`[DeepLink] ✅ Parse completed:`, {
routePath,
pathParams: pathParams.length,
queryParams: Object.keys(query).length,
});
return { path: routePath, params, query };
} catch (error) {
logger.error(`[DeepLink] ❌ Parse failed:`, {
url,
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
} }
/** /**
* Routes the deep link to appropriate view with validated parameters. * Validate and route the deep link
* Validates route and parameters using Zod schemas before routing. * @param path - The route path
* * @param params - Path parameters
* @param path - The route path from the deep link * @param query - Query parameters
* @param params - URL parameters
* @param query - Query string parameters
* @throws {DeepLinkError} If validation fails or route is invalid
*/ */
private async validateAndRoute( private async validateAndRoute(
path: string, path: string,
params: Record<string, string>, params: Record<string, string>,
query: Record<string, string>, query: Record<string, string>,
): Promise<void> { ): Promise<void> {
logger.info(
`[DeepLink] 🎯 Starting validation and routing for path: ${path}`,
);
// First try to validate the route path // First try to validate the route path
let routeName: string; let routeName: string;
try { try {
logger.debug(`[DeepLink] 🔍 Validating route path: ${path}`);
// Validate route exists // Validate route exists
const validRoute = routeSchema.parse(path) as DeepLinkRoute; const validRoute = routeSchema.parse(path) as DeepLinkRoute;
routeName = ROUTE_MAP[validRoute].name; logger.info(`[DeepLink] ✅ Route validation passed: ${validRoute}`);
// Get route configuration
const routeConfig = ROUTE_MAP[validRoute];
logger.info(`[DeepLink] 📋 Route config retrieved:`, routeConfig);
if (!routeConfig) {
logger.error(`[DeepLink] ❌ No route config found for: ${validRoute}`);
throw new Error(`Route configuration missing for: ${validRoute}`);
}
routeName = routeConfig.name;
logger.info(`[DeepLink] 🎯 Route name resolved: ${routeName}`);
} catch (error) { } catch (error) {
logger.error(`[DeepLink] Invalid route path: ${path}`); logger.error(`[DeepLink] ❌ Route validation failed:`, {
path,
error: error instanceof Error ? error.message : String(error),
});
// Redirect to error page with information about the invalid link // Redirect to error page with information about the invalid link
await this.router.replace({ await this.router.replace({
@ -193,21 +228,66 @@ export class DeepLinkHandler {
}, },
}); });
// This previously threw an error but we're redirecting so there's no need. logger.info(
`[DeepLink] 🔄 Redirected to error page for invalid route: ${path}`,
);
return; return;
} }
// Continue with parameter validation as before... // Continue with parameter validation
const schema = deepLinkSchemas[path as keyof typeof deepLinkSchemas]; logger.info(
`[DeepLink] 🔍 Starting parameter validation for route: ${routeName}`,
);
const pathSchema =
deepLinkPathSchemas[path as keyof typeof deepLinkPathSchemas];
const querySchema =
deepLinkQuerySchemas[path as keyof typeof deepLinkQuerySchemas];
logger.debug(`[DeepLink] 📋 Schemas found:`, {
hasPathSchema: !!pathSchema,
hasQuerySchema: !!querySchema,
pathSchemaType: pathSchema ? typeof pathSchema : "none",
querySchemaType: querySchema ? typeof querySchema : "none",
});
let validatedPathParams: Record<string, string> = {};
let validatedQueryParams: Record<string, string> = {};
let validatedParams;
try { try {
validatedParams = await schema.parseAsync(params); if (pathSchema) {
logger.debug(`[DeepLink] 🔍 Validating path parameters:`, params);
validatedPathParams = await pathSchema.parseAsync(params);
logger.info(
`[DeepLink] ✅ Path parameters validated:`,
validatedPathParams,
);
} else {
logger.debug(`[DeepLink] ⚠️ No path schema found for: ${path}`);
validatedPathParams = params;
}
if (querySchema) {
logger.debug(`[DeepLink] 🔍 Validating query parameters:`, query);
validatedQueryParams = await querySchema.parseAsync(query);
logger.info(
`[DeepLink] ✅ Query parameters validated:`,
validatedQueryParams,
);
} else {
logger.debug(`[DeepLink] ⚠️ No query schema found for: ${path}`);
validatedQueryParams = query;
}
} catch (error) { } catch (error) {
// For parameter validation errors, provide specific error feedback logger.error(`[DeepLink] ❌ Parameter validation failed:`, {
logger.error( routeName,
`[DeepLink] Invalid parameters for route name ${routeName} for path: ${path}: ${JSON.stringify(error)} ... with params: ${JSON.stringify(params)} ... and query: ${JSON.stringify(query)}`, path,
); params,
query,
error: error instanceof Error ? error.message : String(error),
errorDetails: JSON.stringify(error),
});
await this.router.replace({ await this.router.replace({
name: "deep-link-error", name: "deep-link-error",
params, params,
@ -219,58 +299,52 @@ export class DeepLinkHandler {
}, },
}); });
// This previously threw an error but we're redirecting so there's no need. logger.info(
`[DeepLink] 🔄 Redirected to error page for invalid parameters`,
);
return; return;
} }
// Attempt navigation
try { try {
logger.info(`[DeepLink] 🚀 Attempting navigation:`, {
routeName,
pathParams: validatedPathParams,
queryParams: validatedQueryParams,
});
await this.router.replace({ await this.router.replace({
name: routeName, name: routeName,
params: validatedParams, params: validatedPathParams,
query: validatedQueryParams,
}); });
logger.info(`[DeepLink] ✅ Navigation successful to: ${routeName}`);
} catch (error) { } catch (error) {
logger.error( logger.error(`[DeepLink] ❌ Navigation failed:`, {
`[DeepLink] Error routing to route name ${routeName} for path: ${path}: ${JSON.stringify(error)} ... with validated params: ${JSON.stringify(validatedParams)}`, routeName,
); path,
// For parameter validation errors, provide specific error feedback validatedPathParams,
validatedQueryParams,
error: error instanceof Error ? error.message : String(error),
errorDetails: JSON.stringify(error),
});
// Redirect to error page for navigation failures
await this.router.replace({ await this.router.replace({
name: "deep-link-error", name: "deep-link-error",
params: validatedParams, params: validatedPathParams,
query: { query: {
originalPath: path, originalPath: path,
errorCode: "ROUTING_ERROR", errorCode: "ROUTING_ERROR",
errorMessage: `Error routing to ${routeName}: ${JSON.stringify(error)}`, errorMessage: `Error routing to ${routeName}: ${(error as Error).message}`,
...validatedQueryParams,
}, },
}); });
}
}
/** logger.info(
* Processes incoming deep links and routes them appropriately. `[DeepLink] 🔄 Redirected to error page for navigation failure`,
* Handles validation, error handling, and routing to the correct view.
*
* @param url - The deep link URL to process
* @throws {DeepLinkError} If URL processing fails
*/
async handleDeepLink(url: string): Promise<void> {
try {
const { path, params, query } = this.parseDeepLink(url);
// Ensure params is always a Record<string,string> by converting undefined to empty string
const sanitizedParams = Object.fromEntries(
Object.entries(params).map(([key, value]) => [key, value ?? ""]),
); );
await this.validateAndRoute(path, sanitizedParams, query);
} catch (error) {
const deepLinkError = error as DeepLinkError;
logger.error(
`[DeepLink] Error (${deepLinkError.code}): ${deepLinkError.details}`,
);
throw {
code: deepLinkError.code || "UNKNOWN_ERROR",
message: deepLinkError.message,
details: deepLinkError.details,
};
} }
} }
} }

67
src/views/AccountViewView.vue

@ -174,15 +174,15 @@
:aria-busy="loadingProfile || savingProfile" :aria-busy="loadingProfile || savingProfile"
></textarea> ></textarea>
<div class="flex items-center mb-4"> <div class="flex items-center mb-4">
<input <input
v-model="includeUserProfileLocation" v-model="includeUserProfileLocation"
type="checkbox" type="checkbox"
class="mr-2" class="mr-2"
@change="onLocationCheckboxChange" @change="onLocationCheckboxChange"
/> />
<label for="includeUserProfileLocation">Include Location</label> <label for="includeUserProfileLocation">Include Location</label>
</div> </div>
<div v-if="includeUserProfileLocation" class="mb-4 aspect-video"> <div v-if="includeUserProfileLocation" class="mb-4 aspect-video">
<p class="text-sm mb-2 text-slate-500"> <p class="text-sm mb-2 text-slate-500">
The location you choose will be shared with the world until you remove The location you choose will be shared with the world until you remove
@ -917,15 +917,21 @@ export default class AccountViewView extends Vue {
created() { created() {
this.notify = createNotifyHelpers(this.$notify); this.notify = createNotifyHelpers(this.$notify);
// Fix Leaflet icon issues in modern bundlers // Fix Leaflet icon issues in modern bundlers
// This prevents the "Cannot read properties of undefined (reading 'Default')" error // This prevents the "Cannot read properties of undefined (reading 'Default')" error
if (L.Icon.Default) { if (L.Icon.Default) {
delete (L.Icon.Default.prototype as any)._getIconUrl; // Type-safe way to handle Leaflet icon prototype
const iconDefault = L.Icon.Default.prototype as Record<string, unknown>;
if ("_getIconUrl" in iconDefault) {
delete iconDefault._getIconUrl;
}
L.Icon.Default.mergeOptions({ L.Icon.Default.mergeOptions({
iconRetinaUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon-2x.png', iconRetinaUrl:
iconUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon.png', "https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon-2x.png",
shadowUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-shadow.png', iconUrl: "https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon.png",
shadowUrl:
"https://unpkg.com/leaflet@1.7.1/dist/images/marker-shadow.png",
}); });
} }
} }
@ -954,7 +960,7 @@ export default class AccountViewView extends Vue {
this.userProfileLatitude = profile.latitude; this.userProfileLatitude = profile.latitude;
this.userProfileLongitude = profile.longitude; this.userProfileLongitude = profile.longitude;
this.includeUserProfileLocation = profile.includeLocation; this.includeUserProfileLocation = profile.includeLocation;
// Initialize map ready state if location is included // Initialize map ready state if location is included
if (profile.includeLocation) { if (profile.includeLocation) {
this.isMapReady = false; // Will be set to true when map is ready this.isMapReady = false; // Will be set to true when map is ready
@ -1541,11 +1547,18 @@ export default class AccountViewView extends Vue {
onMapReady(map: L.Map): void { onMapReady(map: L.Map): void {
try { try {
// doing this here instead of on the l-map element avoids a recentering after a drag then zoom at startup // doing this here instead of on the l-map element avoids a recentering after a drag then zoom at startup
const zoom = this.userProfileLatitude && this.userProfileLongitude ? 12 : 2; const zoom =
this.userProfileLatitude && this.userProfileLongitude ? 12 : 2;
const lat = this.userProfileLatitude || 0; const lat = this.userProfileLatitude || 0;
const lng = this.userProfileLongitude || 0; const lng = this.userProfileLongitude || 0;
map.setView([lat, lng], zoom); map.setView([lat, lng], zoom);
this.isMapReady = true; this.isMapReady = true;
logger.debug(
"Map ready state set to true, coordinates:",
[lat, lng],
"zoom:",
zoom,
);
} catch (error) { } catch (error) {
logger.error("Error in onMapReady:", error); logger.error("Error in onMapReady:", error);
this.isMapReady = true; // Set to true even on error to prevent infinite loading this.isMapReady = true; // Set to true even on error to prevent infinite loading
@ -1553,6 +1566,11 @@ export default class AccountViewView extends Vue {
} }
onMapMounted(): void { onMapMounted(): void {
logger.debug("Map component mounted");
// Check if map ref is available
const mapRef = this.$refs.profileMap;
logger.debug("Map ref:", mapRef);
// Try to set map ready after component is mounted // Try to set map ready after component is mounted
setTimeout(() => { setTimeout(() => {
this.isMapReady = true; this.isMapReady = true;
@ -1585,7 +1603,9 @@ export default class AccountViewView extends Vue {
longitude: this.userProfileLongitude, longitude: this.userProfileLongitude,
includeLocation: this.includeUserProfileLocation, includeLocation: this.includeUserProfileLocation,
}; };
logger.debug("Saving profile data:", profileData);
const success = await this.profileService.saveProfile( const success = await this.profileService.saveProfile(
this.activeDid, this.activeDid,
profileData, profileData,
@ -1614,7 +1634,7 @@ export default class AccountViewView extends Vue {
this.userProfileLatitude = updated.latitude; this.userProfileLatitude = updated.latitude;
this.userProfileLongitude = updated.longitude; this.userProfileLongitude = updated.longitude;
this.includeUserProfileLocation = updated.includeLocation; this.includeUserProfileLocation = updated.includeLocation;
// Reset map ready state when toggling location // Reset map ready state when toggling location
if (!updated.includeLocation) { if (!updated.includeLocation) {
this.isMapReady = false; this.isMapReady = false;
@ -1663,7 +1683,7 @@ export default class AccountViewView extends Vue {
} }
} catch (error) { } catch (error) {
logger.error("Error in deleteProfile component method:", error); logger.error("Error in deleteProfile component method:", error);
// Show more specific error message if available // Show more specific error message if available
if (error instanceof Error) { if (error instanceof Error) {
this.notify.error(error.message); this.notify.error(error.message);
@ -1694,6 +1714,10 @@ export default class AccountViewView extends Vue {
onLocationCheckboxChange(): void { onLocationCheckboxChange(): void {
try { try {
logger.debug(
"Location checkbox changed, new value:",
this.includeUserProfileLocation,
);
if (!this.includeUserProfileLocation) { if (!this.includeUserProfileLocation) {
// Location checkbox was unchecked, clean up map state // Location checkbox was unchecked, clean up map state
this.isMapReady = false; this.isMapReady = false;
@ -1702,14 +1726,15 @@ export default class AccountViewView extends Vue {
} else { } else {
// Location checkbox was checked, start map initialization timeout // Location checkbox was checked, start map initialization timeout
this.isMapReady = false; this.isMapReady = false;
logger.debug("Location checked, starting map initialization timeout");
// Try to set map ready after a short delay to allow Vue to render // Try to set map ready after a short delay to allow Vue to render
setTimeout(() => { setTimeout(() => {
if (!this.isMapReady) { if (!this.isMapReady) {
this.isMapReady = true; this.isMapReady = true;
} }
}, 1000); // 1 second delay }, 1000); // 1 second delay
this.handleMapInitFailure(); this.handleMapInitFailure();
} }
} catch (error) { } catch (error) {

4
src/views/DeepLinkErrorView.vue

@ -47,7 +47,7 @@ import { computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router"; import { useRoute, useRouter } from "vue-router";
import { import {
VALID_DEEP_LINK_ROUTES, VALID_DEEP_LINK_ROUTES,
deepLinkSchemas, deepLinkPathSchemas,
} from "../interfaces/deepLinks"; } from "../interfaces/deepLinks";
import { logConsoleAndDb } from "../db/databaseUtil"; import { logConsoleAndDb } from "../db/databaseUtil";
import { logger } from "../utils/logger"; import { logger } from "../utils/logger";
@ -56,7 +56,7 @@ const route = useRoute();
const router = useRouter(); const router = useRouter();
// an object with the route as the key and the first param name as the value // an object with the route as the key and the first param name as the value
const deepLinkSchemaKeys = Object.fromEntries( const deepLinkSchemaKeys = Object.fromEntries(
Object.entries(deepLinkSchemas).map(([route, schema]) => { Object.entries(deepLinkPathSchemas).map(([route, schema]) => {
const param = Object.keys(schema.shape)[0]; const param = Object.keys(schema.shape)[0];
return [route, param]; return [route, param];
}), }),

110
src/views/HomeView.vue

@ -476,7 +476,7 @@ export default class HomeView extends Vue {
// Re-initialize identity with new settings (loads settings internally) // Re-initialize identity with new settings (loads settings internally)
await this.initializeIdentity(); await this.initializeIdentity();
} else { } else {
logger.info( logger.debug(
"[HomeView Settings Trace] 📍 DID unchanged, skipping re-initialization", "[HomeView Settings Trace] 📍 DID unchanged, skipping re-initialization",
); );
} }
@ -756,17 +756,34 @@ export default class HomeView extends Vue {
* Called by FeedFilters component when filters change * Called by FeedFilters component when filters change
*/ */
async reloadFeedOnChange() { async reloadFeedOnChange() {
const settings = await this.$accountSettings(this.activeDid, { logger.debug("[HomeView] 🔄 reloadFeedOnChange() called - refreshing feed");
filterFeedByVisible: false,
filterFeedByNearby: false, // Get current settings without overriding with defaults
const settings = await this.$accountSettings(this.activeDid);
logger.debug("[HomeView] 📊 Current filter settings:", {
filterFeedByVisible: settings.filterFeedByVisible,
filterFeedByNearby: settings.filterFeedByNearby,
searchBoxes: settings.searchBoxes?.length || 0,
}); });
this.isFeedFilteredByVisible = !!settings.filterFeedByVisible; this.isFeedFilteredByVisible = !!settings.filterFeedByVisible;
this.isFeedFilteredByNearby = !!settings.filterFeedByNearby; this.isFeedFilteredByNearby = !!settings.filterFeedByNearby;
this.isAnyFeedFilterOn = checkIsAnyFeedFilterOn(settings); this.isAnyFeedFilterOn = checkIsAnyFeedFilterOn(settings);
logger.debug("[HomeView] 🎯 Updated filter states:", {
isFeedFilteredByVisible: this.isFeedFilteredByVisible,
isFeedFilteredByNearby: this.isFeedFilteredByNearby,
isAnyFeedFilterOn: this.isAnyFeedFilterOn,
});
this.feedData = []; this.feedData = [];
this.feedPreviousOldestId = undefined; this.feedPreviousOldestId = undefined;
logger.debug("[HomeView] 🧹 Cleared feed data, calling updateAllFeed()");
await this.updateAllFeed(); await this.updateAllFeed();
logger.debug("[HomeView] ✅ Feed refresh completed");
} }
/** /**
@ -845,6 +862,14 @@ export default class HomeView extends Vue {
* - this.feedLastViewedClaimId (via updateFeedLastViewedId) * - this.feedLastViewedClaimId (via updateFeedLastViewedId)
*/ */
async updateAllFeed() { async updateAllFeed() {
logger.debug("[HomeView] 🚀 updateAllFeed() called", {
isFeedLoading: this.isFeedLoading,
currentFeedDataLength: this.feedData.length,
isAnyFeedFilterOn: this.isAnyFeedFilterOn,
isFeedFilteredByVisible: this.isFeedFilteredByVisible,
isFeedFilteredByNearby: this.isFeedFilteredByNearby,
});
this.isFeedLoading = true; this.isFeedLoading = true;
let endOfResults = true; let endOfResults = true;
@ -853,21 +878,37 @@ export default class HomeView extends Vue {
this.apiServer, this.apiServer,
this.feedPreviousOldestId, this.feedPreviousOldestId,
); );
logger.debug("[HomeView] 📡 Retrieved gives from API", {
resultsCount: results.data.length,
endOfResults,
});
if (results.data.length > 0) { if (results.data.length > 0) {
endOfResults = false; endOfResults = false;
// gather any contacts that user has blocked from view // gather any contacts that user has blocked from view
await this.processFeedResults(results.data); await this.processFeedResults(results.data);
await this.updateFeedLastViewedId(results.data); await this.updateFeedLastViewedId(results.data);
logger.debug("[HomeView] 📝 Processed feed results", {
processedCount: this.feedData.length,
});
} }
} catch (e) { } catch (e) {
logger.error("[HomeView] ❌ Error in updateAllFeed:", e);
this.handleFeedError(e); this.handleFeedError(e);
} }
if (this.feedData.length === 0 && !endOfResults) { if (this.feedData.length === 0 && !endOfResults) {
logger.debug("[HomeView] 🔄 No results after filtering, retrying...");
await this.updateAllFeed(); await this.updateAllFeed();
} }
this.isFeedLoading = false; this.isFeedLoading = false;
logger.debug("[HomeView] ✅ updateAllFeed() completed", {
finalFeedDataLength: this.feedData.length,
isFeedLoading: this.isFeedLoading,
});
} }
/** /**
@ -892,12 +933,35 @@ export default class HomeView extends Vue {
* @param records Array of feed records to process * @param records Array of feed records to process
*/ */
private async processFeedResults(records: GiveSummaryRecord[]) { private async processFeedResults(records: GiveSummaryRecord[]) {
logger.debug("[HomeView] 📝 Processing feed results:", {
inputRecords: records.length,
currentFilters: {
isAnyFeedFilterOn: this.isAnyFeedFilterOn,
isFeedFilteredByVisible: this.isFeedFilteredByVisible,
isFeedFilteredByNearby: this.isFeedFilteredByNearby,
},
});
let processedCount = 0;
let filteredCount = 0;
for (const record of records) { for (const record of records) {
const processedRecord = await this.processRecord(record); const processedRecord = await this.processRecord(record);
if (processedRecord) { if (processedRecord) {
this.feedData.push(processedRecord); this.feedData.push(processedRecord);
processedCount++;
} else {
filteredCount++;
} }
} }
logger.debug("[HomeView] 📊 Feed processing results:", {
processed: processedCount,
filtered: filteredCount,
total: records.length,
finalFeedLength: this.feedData.length,
});
this.feedPreviousOldestId = records[records.length - 1].jwtId; this.feedPreviousOldestId = records[records.length - 1].jwtId;
} }
@ -931,7 +995,7 @@ export default class HomeView extends Vue {
* - this.feedData (via createFeedRecord) * - this.feedData (via createFeedRecord)
* *
* @param record The record to process * @param record The record to process
* @returns Processed record with contact info if it passes filters, null otherwise * @returns Processed record if it passes filters, null otherwise
*/ */
private async processRecord( private async processRecord(
record: GiveSummaryRecord, record: GiveSummaryRecord,
@ -941,13 +1005,28 @@ export default class HomeView extends Vue {
const recipientDid = this.extractRecipientDid(claim); const recipientDid = this.extractRecipientDid(claim);
const fulfillsPlan = await this.getFulfillsPlan(record); const fulfillsPlan = await this.getFulfillsPlan(record);
// Log record details for debugging
logger.debug("[HomeView] 🔍 Processing record:", {
recordId: record.jwtId,
hasFulfillsPlan: !!fulfillsPlan,
fulfillsPlanHandleId: record.fulfillsPlanHandleId,
filters: {
isAnyFeedFilterOn: this.isAnyFeedFilterOn,
isFeedFilteredByVisible: this.isFeedFilteredByNearby,
isFeedFilteredByNearby: this.isFeedFilteredByNearby,
},
});
if (!this.shouldIncludeRecord(record, fulfillsPlan)) { if (!this.shouldIncludeRecord(record, fulfillsPlan)) {
logger.debug("[HomeView] ❌ Record filtered out:", record.jwtId);
return null; return null;
} }
const provider = this.extractProvider(claim); const provider = this.extractProvider(claim);
const providedByPlan = await this.getProvidedByPlan(provider); const providedByPlan = await this.getProvidedByPlan(provider);
logger.debug("[HomeView] ✅ Record included:", record.jwtId);
return this.createFeedRecord( return this.createFeedRecord(
record, record,
claim, claim,
@ -1096,6 +1175,22 @@ export default class HomeView extends Vue {
} }
} }
// Add debug logging for nearby filter
if (this.isFeedFilteredByNearby && record.fulfillsPlanHandleId) {
logger.debug("[HomeView] 🔍 Nearby filter check:", {
recordId: record.jwtId,
hasFulfillsPlan: !!fulfillsPlan,
hasLocation: !!(fulfillsPlan?.locLat && fulfillsPlan?.locLon),
location: fulfillsPlan
? { lat: fulfillsPlan.locLat, lon: fulfillsPlan.locLon }
: null,
inSearchBox: fulfillsPlan
? this.latLongInAnySearchBox(fulfillsPlan.locLat, fulfillsPlan.locLon)
: null,
finalResult: anyMatch,
});
}
return anyMatch; return anyMatch;
} }
@ -1531,7 +1626,10 @@ export default class HomeView extends Vue {
* Called by template click handler * Called by template click handler
*/ */
openFeedFilters() { openFeedFilters() {
(this.$refs.feedFilters as FeedFilters).open(this.reloadFeedOnChange); (this.$refs.feedFilters as FeedFilters).open(
this.reloadFeedOnChange,
this.activeDid,
);
} }
/** /**

2
src/views/OnboardMeetingMembersView.vue

@ -113,7 +113,7 @@ export default class OnboardMeetingMembersView extends Vue {
try { try {
// Identity creation should be handled by router guard, but keep as fallback for meeting setup // Identity creation should be handled by router guard, but keep as fallback for meeting setup
if (!this.activeDid) { if (!this.activeDid) {
logger.info( this.$logAndConsole(
"[OnboardMeetingMembersView] No active DID found, creating identity as fallback for meeting setup", "[OnboardMeetingMembersView] No active DID found, creating identity as fallback for meeting setup",
); );
this.activeDid = await generateSaveAndActivateIdentity(); this.activeDid = await generateSaveAndActivateIdentity();

21
vite.config.common.mts

@ -6,10 +6,8 @@ import path from "path";
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
// Load environment variables // Load environment variables
console.log('NODE_ENV:', process.env.NODE_ENV)
dotenv.config({ path: `.env.${process.env.NODE_ENV}` }) dotenv.config({ path: `.env.${process.env.NODE_ENV}` })
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
@ -37,9 +35,6 @@ export async function createBuildConfig(platform: string): Promise<UserConfig> {
assetsDir: 'assets', assetsDir: 'assets',
chunkSizeWarningLimit: 1000, chunkSizeWarningLimit: 1000,
rollupOptions: { rollupOptions: {
external: isNative
? ['@capacitor/app']
: [],
output: { output: {
format: 'esm', format: 'esm',
generatedCode: { generatedCode: {
@ -53,6 +48,22 @@ export async function createBuildConfig(platform: string): Promise<UserConfig> {
format: 'es', format: 'es',
plugins: () => [] plugins: () => []
}, },
// ESBuild configuration to fail on errors - TEMPORARILY DISABLED
// esbuild: {
// target: 'es2015',
// supported: {
// 'bigint': true
// },
// // Fail on any ESBuild errors
// logLevel: 'error',
// // Ensure build fails on syntax errors and other critical issues
// logOverride: {
// 'duplicate-export': 'error',
// 'duplicate-member': 'error',
// 'syntax-error': 'error',
// 'invalid-identifier': 'error'
// }
// },
define: { define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),

6
vite.config.optimized.mts

@ -135,7 +135,11 @@ export async function createOptimizedBuildConfig(mode: string): Promise<UserConf
target: 'es2015', target: 'es2015',
supported: { supported: {
'bigint': true 'bigint': true
} },
// Fail on any ESBuild errors
logLevel: 'error',
// Ensure build fails on syntax errors
logOverride: { 'duplicate-export': 'error' }
} }
}; };
} }

24
vite.config.utils.mts

@ -112,4 +112,28 @@ export async function loadAppConfig(): Promise<AppConfig> {
"dexie-export-import/dist/import/index.js", "dexie-export-import/dist/import/index.js",
}, },
}; };
}
/**
* Shared ESBuild configuration that ensures builds fail on errors
*/
export function getStrictESBuildConfig() {
return {
target: 'es2015',
supported: {
'bigint': true
},
// Fail on any ESBuild errors
logLevel: 'error' as const,
// Ensure build fails on syntax errors and other critical issues
logOverride: {
'duplicate-export': 'error',
'duplicate-member': 'error',
'syntax-error': 'error',
'invalid-identifier': 'error'
},
// Additional strict settings
keepNames: false,
minifyIdentifiers: false
};
} }

99
vite.config.web.mts

@ -1,99 +1,4 @@
import { defineConfig, mergeConfig } from "vite"; import { defineConfig } from "vite";
import { createBuildConfig } from "./vite.config.common.mts"; import { createBuildConfig } from "./vite.config.common.mts";
import { loadAppConfig } from "./vite.config.utils.mts";
export default defineConfig(async ({ mode }) => { export default defineConfig(async () => createBuildConfig('web'));
const baseConfig = await createBuildConfig('web');
const appConfig = await loadAppConfig();
// Environment-specific configuration based on mode
const getEnvironmentConfig = (mode: string) => {
switch (mode) {
case 'production':
return {
// Production optimizations
build: {
minify: 'terser',
sourcemap: false,
rollupOptions: {
output: {
manualChunks: {
vendor: ['vue', 'vue-router', 'pinia'],
utils: ['luxon', 'ramda', 'zod'],
crypto: ['@ethersproject/wallet', '@ethersproject/hdnode', 'ethereum-cryptography'],
sql: ['@jlongster/sql.js', 'absurd-sql']
}
}
}
},
define: {
__DEV__: false,
__TEST__: false,
__PROD__: true
}
};
case 'test':
return {
// Test environment configuration
build: {
minify: false,
sourcemap: true,
rollupOptions: {
output: {
manualChunks: undefined
}
}
},
define: {
__DEV__: false,
__TEST__: true,
__PROD__: false
}
};
default: // development
return {
// Development configuration
build: {
minify: false,
sourcemap: true,
rollupOptions: {
output: {
manualChunks: undefined
}
}
},
define: {
__DEV__: true,
__TEST__: false,
__PROD__: false
}
};
}
};
const environmentConfig = getEnvironmentConfig(mode);
return mergeConfig(baseConfig, {
...environmentConfig,
// Ensure source maps are enabled for development and test modes
// This affects both dev server and build output
sourcemap: mode === 'development' || mode === 'test',
// Server configuration inherited from base config
// CORS headers removed to allow images from any domain
plugins: [],
// Worker configuration for SQL worker
worker: {
format: 'es',
plugins: () => []
},
// Optimize dependencies for SQL worker
optimizeDeps: {
include: [
'@jlongster/sql.js',
'absurd-sql',
'absurd-sql/dist/indexeddb-main-thread',
'absurd-sql/dist/indexeddb-backend'
]
}
});
});

Loading…
Cancel
Save