# Onairos NPM Package - Laravel Integration Context ## Laravel Integration Overview - **Package Version**: 2.2.1+ - **Laravel Support**: Laravel 9+ with Vite - **Integration Types**: Blade Templates, Vue.js, React, Mixed Approaches - **Build System**: Vite with custom plugins - **Mobile Support**: Auto-detection with responsive OAuth flows ## Key Laravel-Specific Features ✅ 1. **Blade Template Integration**: Direct PHP template support without React setup 2. **Vite Plugin System**: Custom plugins for Laravel, Vue, and React optimization 3. **Multi-Framework Support**: Seamless Vue.js and React integration within Laravel 4. **Mobile-First Design**: Automatic mobile detection with appropriate OAuth flows 5. **Laravel Backend Integration**: PHP controllers and route handlers 6. **Production Optimization**: Laravel-specific build and deployment strategies ## Laravel Integration Architecture ✅ ### Entry Points - **Main Package**: `onairos` (standard React components) - **Laravel Blade**: `onairos/blade` (vanilla JS helpers) - **Vite Plugin**: `onairos/vite-plugin` (build-time optimization) - **Vue Component**: `onairos/src/laravel/OnairosVue.vue` (Vue 3 SFC) ### Build Targets - **UMD Bundle**: `dist/onairos.bundle.js` (browser globals) - **ES Module**: `dist/onairos.esm.js` (modern imports) - **Laravel Specific**: `dist/onairos-laravel.js` (Blade helpers) ## Integration Approaches ✅ ### 1. Blade Templates (PHP-Focused) **Use Case**: Traditional Laravel apps with minimal JavaScript **Technology Stack**: PHP Blade + Vanilla JS + Tailwind CSS **Implementation**: ```javascript // Vite plugin handles build-time optimization onairosLaravelPlugin({ bladeSupport: true, // Watch .blade.php files injectGlobals: true, // Auto-inject helpers optimizeDeps: true, // Optimize for Laravel enableHMR: true // Hot module replacement }) ``` **Runtime Flow**: 1. `initializeOnairosForBlade()` sets up global configuration 2. `createOnairosButton()` generates DOM elements with event handlers 3. Mobile detection switches between popup/redirect OAuth flows 4. Custom events communicate with Laravel backend ### 2. Vue.js Integration **Use Case**: Laravel apps using Vue.js as primary frontend **Technology Stack**: PHP Blade + Vue 3 + Composition API + Vite **Implementation**: ```javascript // Specialized Vue plugin with auto-imports onairosVuePlugin({ autoImport: true, // Auto-import OnairosButton in .vue files optimizeDeps: true // Optimize Vue + Onairos dependencies }) ``` **Component Architecture**: - **OnairosVue.vue**: Complete Vue 3 component with Composition API - **Props System**: Vue-style props with validation and defaults - **Event System**: Vue custom events (@complete, @error, @loading) - **Reactive State**: Vue reactivity for loading, success, error states ### 3. React Integration **Use Case**: Laravel apps using React as primary frontend **Technology Stack**: PHP Blade + React 18 + JSX + Vite **Implementation**: ```javascript // React-specific optimizations onairosReactPlugin({ autoImport: true, // Auto-import in .jsx/.tsx files optimizeDeps: true // Optimize React + Onairos bundle }) ``` **Integration Pattern**: - Uses existing `OnairosButton` React component - Laravel Vite plugin handles React-specific builds - Automatic JSX transformation and optimization ## Technical Implementation Details ✅ ### Vite Plugin System **Core Plugin**: `onairosLaravelPlugin()` - **Development**: Injects initialization scripts, enables HMR - **Production**: Optimizes bundles, handles asset generation - **File Watching**: Watches .blade.php files for changes - **Dependency Optimization**: Pre-bundles Onairos for faster dev server **Specialized Plugins**: - `onairosVuePlugin()`: Vue-specific optimizations and auto-imports - `onairosReactPlugin()`: React-specific optimizations and auto-imports ### Mobile Detection & OAuth Flow ```javascript // Automatic mobile detection const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || (window.innerWidth <= 768); // OAuth flow selection if (isMobile) { // Redirect-based flow for mobile browsers window.location.href = authUrl; } else { // Popup-based flow for desktop window.open(authUrl, 'onairosAuth', 'width=450,height=700'); } ``` ### Laravel Backend Integration ```php // Example Laravel controller class OnairosController extends Controller { public function callback(Request $request) { $data = $request->validate([ 'user_hash' => 'required|string', 'connections' => 'required|array', 'data_types' => 'required|array' ]); auth()->user()->update([ 'onairos_hash' => $data['user_hash'], 'onairos_connections' => $data['connections'] ]); return response()->json(['success' => true]); } } ``` ## Differences from Standard Integration ✅ ### 1. Build System Integration **Standard**: Uses webpack UMD build for browser globals **Laravel**: Custom Vite plugins with Laravel-specific optimizations ### 2. Component Rendering **Standard**: React components mounted via ReactDOM **Laravel Blade**: Vanilla JS functions that generate DOM elements **Laravel Vue**: Native Vue 3 single-file components **Laravel React**: React components optimized for Laravel Vite ### 3. State Management **Standard**: React state hooks and context **Laravel Blade**: Global window objects and DOM manipulation **Laravel Vue**: Vue 3 Composition API with reactive refs **Laravel React**: React hooks within Laravel ecosystem ### 4. OAuth Flow Handling **Standard**: Hardcoded popup approach **Laravel**: Environment-aware with automatic mobile detection - Desktop: Popup windows - Mobile: Redirect-based flow with return URL handling ### 5. Styling Integration **Standard**: Inline styles and CSS-in-JS **Laravel**: - Tailwind CSS integration out of the box - Scoped Vue styles for Vue components - Laravel Mix/Vite asset compilation - Global CSS injection for Blade templates ### 6. Development Experience **Standard**: Create React App or manual webpack setup **Laravel**: - Vite HMR with Blade file watching - Automatic dependency optimization - Laravel-specific error handling and debugging - Integration with Laravel development tools ## Package Structure Changes ✅ ### New Files Added ``` src/laravel/ ├── blade-helpers.js # Vanilla JS helpers for Blade templates ├── vite-plugin.js # Custom Vite plugins for Laravel └── OnairosVue.vue # Vue 3 component for Laravel LARAVEL_INTEGRATION_GUIDE.md # Comprehensive integration guide laravel.txt # This context file ``` ### Package.json Exports ```json { "exports": { ".": { "import": "./dist/onairos.esm.js", "require": "./dist/onairos.bundle.js", "browser": "./dist/onairos.bundle.js" }, "./laravel": { "import": "./dist/onairos.laravel.js", "require": "./dist/onairos.laravel.js" }, "./blade": "./src/laravel/blade-helpers.js", "./vite-plugin": "./src/laravel/vite-plugin.js" } } ``` ### Webpack Configuration ```javascript // Laravel-specific build target { entry: { 'onairos-laravel': path.resolve(__dirname, 'src', 'laravel', 'blade-helpers.js') }, output: { filename: '[name].js', libraryTarget: 'umd', library: 'OnairosLaravel' } } ``` ## Developer Experience Improvements ✅ ### 1. Installation Simplicity ```bash # Single package for all Laravel integration types npm install onairos # Optional: Framework-specific plugins npm install --save-dev @vitejs/plugin-vue # For Vue npm install --save-dev @vitejs/plugin-react # For React ``` ### 2. Configuration Patterns **Blade Only**: ```javascript // Minimal setup onairosLaravelPlugin({ bladeSupport: true }) ``` **Vue Integration**: ```javascript // Vue + Laravel optimization plugins: [laravel(), vue(), onairosVuePlugin()] ``` **React Integration**: ```javascript // React + Laravel optimization plugins: [laravel(), react(), onairosReactPlugin()] ``` ### 3. Environment Configuration ```env # Laravel .env integration VITE_ONAIROS_API_KEY=your_api_key VITE_ONAIROS_TEST_MODE=true VITE_ONAIROS_BASE_URL=https://api2.onairos.uk ``` ### 4. Debug and Development ```javascript // Enhanced debugging for Laravel initializeOnairosForBlade({ debug: true, // Enable console logging testMode: import.meta.env.DEV, // Auto-detect dev environment autoDetectMobile: true // Mobile detection logging }); ``` ## Production Deployment ✅ ### 1. Build Process ```bash # Laravel standard build npm run build # Generates optimized bundles: # - dist/onairos.bundle.js (UMD) # - dist/onairos.esm.js (ES modules) # - dist/onairos-laravel.js (Laravel-specific) ``` ### 2. Laravel Optimization ```php // Laravel production commands php artisan optimize # Route/config caching php artisan view:cache # Blade template caching php artisan config:cache # Environment caching ``` ### 3. CDN Integration ```env # Laravel asset CDN ASSET_URL=https://your-cdn.com # Automatic asset URL prefixing # https://your-cdn.com/build/assets/onairos-laravel.abc123.js ``` ## Testing Strategy ✅ ### 1. Unit Tests - Laravel Blade helpers functionality - Vue component props and events - Vite plugin configuration - Mobile detection logic ### 2. Integration Tests - Laravel controller callbacks - OAuth flow completion - Database integration - Environment variable handling ### 3. End-to-End Tests - Full Laravel application flows - Mobile and desktop OAuth - Vue/React component integration - Production build verification ## Known Laravel-Specific Considerations ✅ ### 1. CSRF Protection Laravel CSRF tokens are automatically handled in AJAX requests when using Laravel's default Axios configuration. ### 2. Route Caching OAuth callback routes must be registered before route caching in production. ### 3. Session Management Laravel sessions are used for OAuth state management alongside Onairos user hashes. ### 4. Middleware Integration Custom Laravel middleware can be created to handle Onairos authentication states. ### 5. Queue Integration Heavy OAuth processing can be queued using Laravel's queue system for better performance. ## Migration from Standard Integration ✅ ### For Existing React Users - No changes needed to existing React components - Optional: Add Laravel Vite plugin for optimization - Optional: Use Laravel backend integration features ### For New Laravel Projects - Choose integration approach (Blade/Vue/React) - Install appropriate Vite plugins - Follow Laravel-specific setup guide - Configure environment variables ### For Hybrid Approaches - Mix Blade templates with Vue/React components - Use different integration methods in different parts of the app - Leverage Laravel's flexibility for gradual adoption ## Performance Considerations ✅ ### 1. Bundle Size Optimization - Vite plugins optimize bundle splitting - Laravel-specific builds exclude unnecessary dependencies - Tree-shaking removes unused code ### 2. Loading Performance - Lazy loading for Vue/React components - Preloading critical OAuth dependencies - Service worker integration for offline capability ### 3. Mobile Performance - Automatic redirect vs popup optimization - Touch-friendly UI components - Reduced JavaScript payload for mobile ## Troubleshooting Guide ✅ ### Common Issues 1. **Vite Plugin Not Working** - Clear Vite cache: `rm -rf node_modules/.vite` - Check plugin order in vite.config.js - Verify import paths 2. **Blade Helpers Unavailable** - Ensure `initializeOnairosForBlade()` is called - Check browser console for initialization errors - Verify script loading order 3. **Vue Component Not Rendering** - Confirm Vue 3 is properly installed - Check component registration - Verify Vite Vue plugin configuration 4. **Mobile OAuth Issues** - Test popup blockers disabled - Verify redirect URLs are whitelisted - Check mobile user agent detection ### Debug Commands ```javascript // Check initialization status console.log(typeof window.createOnairosButton); // Should be "function" console.log(typeof window.OnairosConfig); // Should be "object" // Test mobile detection console.log(window.OnairosUtils.isMobile); // Boolean // Verify Vite environment console.log(import.meta.env.DEV); // Development mode console.log(import.meta.env.VITE_ONAIROS_*); // Environment variables ``` ## Future Laravel Enhancements 🚀 ### Planned Features 1. **Artisan Commands**: CLI commands for setup and configuration 2. **Laravel Packages**: Composer package for PHP-side integration 3. **Blade Directives**: Custom `@onairos` Blade directive 4. **Middleware Package**: Pre-built authentication middleware 5. **Model Traits**: Eloquent traits for user Onairos data 6. **Testing Helpers**: Laravel testing utilities for Onairos ### Experimental Features 1. **Server-Side Rendering**: Laravel + Inertia.js SSR support 2. **API Resource Integration**: Laravel API resource transformers 3. **Livewire Components**: Native Livewire component integration 4. **Laravel Sail**: Docker development environment support