import Alpine from 'alpinejs'; import { ConnectionState, Room, RoomEvent, Track } from 'livekit-client'; function meetRoom() { // LiveKit Room must stay outside Alpine's reactive proxy — wrapping it breaks // structuredClone inside the SDK during connect and media setup. let room = null; let connectPromise = null; let initialized = false; return { isMuted: true, isVideoOff: true, isScreenSharing: false, isRecording: false, isLocked: false, isHost: false, watermark: false, liveCaptions: false, captionText: '', displayName: '', canPublish: true, isWebinar: false, qaItems: [], activePolls: [], breakoutBroadcast: '', featuresOpen: false, whiteboardOpen: false, qaInput: '', chatOpen: false, chatInput: '', shareOpen: false, shareCopied: false, joinUrl: '', passcode: '', roomTitle: '', connectionStatus: 'Connecting…', participants: [], floatingReactions: [], pollTimer: null, config: {}, init() { if (initialized) return; initialized = true; const el = document.getElementById('meet-config'); if (!el) return; this.config = { token: el.dataset.token, url: el.dataset.url, configured: el.dataset.configured === '1', pollUrl: el.dataset.pollUrl, chatUrl: el.dataset.chatUrl, reactionUrl: el.dataset.reactionUrl, raiseHandUrl: el.dataset.raiseHandUrl, recordingStartUrl: el.dataset.recordingStartUrl, recordingStopUrl: el.dataset.recordingStopUrl, lockUrl: el.dataset.lockUrl, unlockUrl: el.dataset.unlockUrl, captionUrl: el.dataset.captionUrl, qaUrl: el.dataset.qaUrl, pollsCreateUrl: el.dataset.pollsCreateUrl, breakoutsCreateUrl: el.dataset.breakoutsCreateUrl, breakoutsCloseUrl: el.dataset.breakoutsCloseUrl, breakoutsBroadcastUrl: el.dataset.breakoutsBroadcastUrl, filesUploadUrl: el.dataset.filesUploadUrl, whiteboardUrl: el.dataset.whiteboardUrl, whiteboardSaveUrl: el.dataset.whiteboardSaveUrl, csrf: el.dataset.csrf, }; this.joinUrl = el.dataset.joinUrl || ''; this.passcode = el.dataset.passcode || ''; this.roomTitle = el.dataset.roomTitle || ''; this.isHost = el.dataset.isHost === '1'; this.canPublish = el.dataset.canPublish !== '0'; this.isWebinar = el.dataset.isWebinar === '1'; this.isRecording = el.dataset.recordingActive === '1'; this.isLocked = el.dataset.locked === '1'; this.watermark = el.dataset.watermark === '1'; this.liveCaptions = el.dataset.liveCaptions === '1'; this.displayName = el.dataset.displayName || ''; if (this.config.configured && this.config.token) { this.connectLiveKit(); } else { this.connectionStatus = 'Video unavailable — configure LiveKit'; } this.pollTimer = setInterval(() => this.poll(), 3000); }, connectionErrorMessage(error) { const name = error?.name || ''; const message = error?.message || ''; if (name === 'NotAllowedError' || message.includes('Permission denied')) { return 'Connected — allow camera and microphone in your browser'; } if (name === 'NotFoundError' || message.includes('Requested device not found')) { return 'Connected — no camera or microphone found'; } if (message.includes('401') || message.toLowerCase().includes('unauthorized')) { return 'LiveKit rejected the session token'; } if (message.includes('engine not connected within timeout')) { return 'In call — camera/mic timed out. Use the mic/camera buttons to retry.'; } if (message) { return `Connection failed — ${message}`; } return 'Connection failed'; }, async connectLiveKit() { if (connectPromise) { return connectPromise; } connectPromise = this.startLiveKitSession(); try { await connectPromise; } catch (e) { connectPromise = null; throw e; } }, async startLiveKitSession() { try { room = new Room({ adaptiveStream: true, dynacast: true, disconnectOnPageLeave: true, }); room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => { this.attachTrack(track, publication, participant); }); room.on(RoomEvent.TrackUnsubscribed, (track, publication, participant) => { track.detach(); if (track.kind === Track.Kind.Video && publication.source !== Track.Source.ScreenShare) { this.updateParticipantTile(participant); } }); room.on(RoomEvent.TrackMuted, (publication, participant) => { if (publication.kind === Track.Kind.Video && publication.source !== Track.Source.ScreenShare) { publication.track?.detach(); this.updateParticipantTile(participant); } if (publication.kind === Track.Kind.Audio) { this.updateParticipantTile(participant); } if (participant === room.localParticipant) { this.syncLocalMediaState(); } }); room.on(RoomEvent.TrackUnmuted, (publication, participant) => { if (publication.kind === Track.Kind.Video && publication.track) { this.attachTrack(publication.track, publication, participant); } if (publication.kind === Track.Kind.Audio) { this.updateParticipantTile(participant); } if (participant === room.localParticipant) { this.syncLocalMediaState(); } }); room.on(RoomEvent.LocalTrackPublished, (publication, participant) => { if (publication.track?.kind === Track.Kind.Video) { this.attachTrack(publication.track, publication, participant); } this.updateParticipantTile(participant); this.syncLocalMediaState(); }); room.on(RoomEvent.LocalTrackUnpublished, (publication, participant) => { if (publication.kind === Track.Kind.Video) { this.updateParticipantTile(participant); } this.syncLocalMediaState(); }); room.on(RoomEvent.ParticipantConnected, () => this.syncParticipants()); room.on(RoomEvent.ParticipantDisconnected, () => this.syncParticipants()); room.on(RoomEvent.Disconnected, () => { this.connectionStatus = 'Disconnected'; }); await room.prepareConnection(this.config.url, this.config.token); await room.connect(this.config.url, this.config.token, { autoSubscribe: true, peerConnectionTimeout: 20_000, websocketTimeout: 20_000, }); await this.waitForRoomConnected(room); this.connectionStatus = 'Connected'; this.syncParticipants(); if (this.canPublish) { await this.enableLocalMedia(room); } else { this.connectionStatus = 'View-only audience mode'; this.isMuted = true; this.isVideoOff = true; } this.setupCaptionPipeline(); this.updateParticipantTile(room.localParticipant); room.localParticipant.videoTrackPublications.forEach((pub) => { if (pub.track && !pub.isMuted && pub.source !== Track.Source.ScreenShare) { this.attachTrack(pub.track, pub, room.localParticipant); } }); } catch (e) { console.error(e); this.connectionStatus = this.connectionErrorMessage(e); } }, waitForRoomConnected(activeRoom) { if (activeRoom.state === ConnectionState.Connected) { return Promise.resolve(); } return new Promise((resolve, reject) => { const timeout = setTimeout(() => { activeRoom.off(RoomEvent.Connected, onConnected); reject(new Error('Timed out waiting for LiveKit room connection')); }, 20_000); const onConnected = () => { clearTimeout(timeout); resolve(); }; activeRoom.once(RoomEvent.Connected, onConnected); }); }, async enableLocalMedia(activeRoom, attempts = 3) { for (let attempt = 1; attempt <= attempts; attempt += 1) { try { await activeRoom.localParticipant.setMicrophoneEnabled(true); await activeRoom.localParticipant.setCameraEnabled(false); this.syncLocalMediaState(); this.updateParticipantTile(activeRoom.localParticipant); this.connectionStatus = 'Connected'; return; } catch (mediaError) { console.error(mediaError); const retryable = mediaError?.message?.includes('engine not connected within timeout'); if (!retryable || attempt === attempts) { this.syncLocalMediaState(); this.updateParticipantTile(activeRoom.localParticipant); this.connectionStatus = this.connectionErrorMessage(mediaError); return; } await new Promise((resolve) => setTimeout(resolve, 1000 * attempt)); } } }, syncLocalMediaState() { if (!room) return; const local = room.localParticipant; this.isMuted = !local.isMicrophoneEnabled; this.isVideoOff = !local.isCameraEnabled; }, participantInitials(name) { const parts = (name || '?').trim().split(/\s+/).filter(Boolean); if (parts.length === 0) return '?'; if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase(); return `${parts[0][0]}${parts[parts.length - 1][0]}`.toUpperCase(); }, avatarHue(name) { let hash = 0; const value = name || 'guest'; for (let i = 0; i < value.length; i += 1) { hash = value.charCodeAt(i) + ((hash << 5) - hash); } return Math.abs(hash) % 360; }, getOrCreateParticipantTile(participant) { const grid = document.getElementById('video-grid'); if (!grid) return null; const identity = participant.identity; let tile = grid.querySelector(`[data-participant-tile="${identity}"]`); if (!tile) { tile = document.createElement('div'); tile.dataset.participantTile = identity; tile.className = 'relative aspect-video w-full overflow-hidden rounded-xl bg-slate-900 ring-1 ring-white/10'; tile.innerHTML = `
${this.escape(message.body)}
`; container.appendChild(div); container.scrollTop = container.scrollHeight; }, showFloatingReaction(kind) { const id = Date.now(); this.floatingReactions.push({ id, kind }); setTimeout(() => { this.floatingReactions = this.floatingReactions.filter((r) => r.id !== id); }, 2000); }, headers() { return { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': this.config.csrf, 'X-Requested-With': 'XMLHttpRequest', }; }, escape(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; }, }; } window.meetRoom = meetRoom; Alpine.data('meetRoom', meetRoom); Alpine.start();