@nainudhin/video-meeting-sdk 1.7.1 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/meet-sdk.mjs CHANGED
@@ -6617,7 +6617,9 @@ class Zr {
6617
6617
  }
6618
6618
  t && (e.enabled ? this.setPresentingPeer(t) : this.presentingPeerId === t && this.setPresentingPeer(null));
6619
6619
  }), this.socketManager.on("youJoined", (e) => {
6620
- if (this.myRole = e && e.role ? e.role : "candidate", e && e.hostId) {
6620
+ if (this.myRole = e && e.role ? e.role : "candidate", console.log(
6621
+ `MeetSDK: joined as ${this.myRole}` + (e && e.hostId ? ` (host is ${e.hostName || e.hostId})` : "")
6622
+ ), e && e.hostId) {
6621
6623
  for (const [n] of this.peerLabels.entries())
6622
6624
  if (n.endsWith(`-${e.hostId}`)) {
6623
6625
  this.hostPeerId = n;
@@ -6630,6 +6632,18 @@ class Zr {
6630
6632
  this.refreshParticipantsPanel();
6631
6633
  });
6632
6634
  }
6635
+ async hydrateIceServers() {
6636
+ try {
6637
+ const e = await fetch(`${this.config.apiUrl}/rt-config`, { headers: this.buildHeaders() });
6638
+ if (!e.ok) return;
6639
+ const t = await e.json();
6640
+ if (!t || !Array.isArray(t.iceServers) || t.iceServers.length === 0) return;
6641
+ const n = Array.isArray(this.config.iceServers) ? this.config.iceServers : [];
6642
+ this.config.iceServers = [...n, ...t.iceServers];
6643
+ } catch (e) {
6644
+ console.warn("rt-config fetch failed, using STUN defaults:", e && e.message);
6645
+ }
6646
+ }
6633
6647
  labelForPeer(e, t) {
6634
6648
  return t ? this.currentUser && this.currentUser.name ? this.currentUser.name : "You" : this.peerLabels && this.peerLabels.has(e) ? this.peerLabels.get(e) : e;
6635
6649
  }
@@ -6665,7 +6679,7 @@ class Zr {
6665
6679
  async mount(e) {
6666
6680
  if (!this.isInitialized)
6667
6681
  throw new Error("SDK not initialized. Call init() first.");
6668
- this.uiManager.mount(e);
6682
+ this.uiManager.mount(e), await this.hydrateIceServers();
6669
6683
  const t = `${this.config.workspace}-${this.currentRoom}-${this.currentUser.id}`;
6670
6684
  await this.peerManager.initialize(t);
6671
6685
  const n = await this.peerManager.getLocalStream();
@@ -186,4 +186,4 @@ a=extmap-allow-mixed`)!==-1){const i=s.sdp.split(`
186
186
  <canvas id="wb-canvas" class="wb-canvas"></canvas>
187
187
  </div>
188
188
  <div class="wb-note" id="wb-note"></div>
189
- `,this.canvas=this.container.querySelector("#wb-canvas"),this.wrap=this.container.querySelector("#wb-wrap"),this.ctx=this.canvas.getContext("2d"),this.note=this.container.querySelector("#wb-note"),this._resize=this._resize.bind(this),requestAnimationFrame(()=>{this._resize(),this._replay()}),window.addEventListener("resize",this._resize),this._resizeObserver=null,typeof ResizeObserver<"u"&&(this._resizeObserver=new ResizeObserver(()=>this._resize()),this._resizeObserver.observe(this.wrap)),this.container.querySelectorAll(".wb-tool").forEach(e=>{e.addEventListener("click",()=>{this.tool=e.getAttribute("data-tool"),this.container.querySelectorAll(".wb-tool").forEach(t=>t.classList.toggle("active",t===e))})}),this.container.querySelectorAll(".wb-swatch").forEach(e=>{e.addEventListener("click",()=>{this.color=e.getAttribute("data-color"),this.container.querySelectorAll(".wb-swatch").forEach(t=>t.classList.toggle("active",t===e)),this.tool="pen",this.container.querySelectorAll(".wb-tool").forEach(t=>t.classList.toggle("active",t.getAttribute("data-tool")==="pen"))})}),this.container.querySelector("#wb-size").addEventListener("input",e=>{this.size=parseInt(e.target.value,10)||3}),this.container.querySelector("#wb-clear").addEventListener("click",()=>{this.canDraw()&&(this.emit("whiteboard-clear",{}),this._clearLocal())}),this.canvas.addEventListener("pointerdown",e=>this._onDown(e)),this.canvas.addEventListener("pointermove",e=>this._onMove(e)),this.canvas.addEventListener("pointerup",()=>this._onUp()),this.canvas.addEventListener("pointerleave",()=>this._onUp()),this.refreshPermissionUI()}refreshPermissionUI(){const e=this.canDraw();this.canvas.style.pointerEvents=e?"auto":"none",this.note.textContent=e?"":"View-only — request draw access from the host"}_resize(){if(!this.canvas||!this.wrap)return;const e=this.wrap.getBoundingClientRect(),t=window.devicePixelRatio||1;this.canvas.width=Math.max(300,Math.floor(e.width*t)),this.canvas.height=Math.max(200,Math.floor(e.height*t)),this.ctx.setTransform(t,0,0,t,0,0),this._replay()}_pointerCoords(e){const t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width,y:(e.clientY-t.top)/t.height}}_drawSegment(e,t,n,s,i){const o=this.canvas.getBoundingClientRect().width,a=this.canvas.getBoundingClientRect().height;this.ctx.lineWidth=i,this.ctx.lineCap="round",this.ctx.lineJoin="round",this.ctx.globalCompositeOperation=n==="eraser"?"destination-out":"source-over",this.ctx.strokeStyle=n==="eraser"?"rgba(0,0,0,1)":s,this.ctx.beginPath(),this.ctx.moveTo(e.x*o,e.y*a),this.ctx.lineTo(t.x*o,t.y*a),this.ctx.stroke()}_onDown(e){if(!this.canDraw())return;e.preventDefault(),this.canvas.setPointerCapture(e.pointerId);const t=this._pointerCoords(e);this.currentStroke={tool:this.tool,color:this.color,size:this.size,points:[t]}}_onMove(e){if(!this.currentStroke)return;const t=this._pointerCoords(e),n=this.currentStroke.points[this.currentStroke.points.length-1];this._drawSegment(n,t,this.currentStroke.tool,this.currentStroke.color,this.currentStroke.size),this.currentStroke.points.push(t)}_onUp(){if(!this.currentStroke||this.currentStroke.points.length<2){this.currentStroke=null;return}const e=this.currentStroke;this.currentStroke=null,this.remoteStrokes.push(e),this.emit("whiteboard-draw",{drawing:e})}_clearLocal(){this.remoteStrokes=[],this.imageData=null,this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}_replay(){if(this.ctx){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.imageData&&this._drawBackground();for(const e of this.remoteStrokes){const t=e.points||[];for(let n=1;n<t.length;n++)this._drawSegment(t[n-1],t[n],e.tool,e.color,e.size)}}}_drawBackground(){if(!this.imageData)return;const e=new Image;e.onload=()=>{const t=this.canvas.getBoundingClientRect().width,n=this.canvas.getBoundingClientRect().height;this.ctx.globalCompositeOperation="source-over",this.ctx.drawImage(e,0,0,t,n)},e.src=this.imageData}handleDrawing(e){if(e.userId&&e.userId===this.userId||!e.drawing)return;this.remoteStrokes.push(e.drawing);const t=e.drawing.points||[];for(let n=1;n<t.length;n++)this._drawSegment(t[n-1],t[n],e.drawing.tool,e.drawing.color,e.drawing.size)}handleCleared(){this._clearLocal()}handleImageUploaded(e){this.imageData=e.imageData||null,this._replay()}handleStateSync(e){e&&(this.imageData=e.imageData||null,this.remoteStrokes=Array.isArray(e.drawings)?e.drawings.slice():[],this._replay(),this.refreshPermissionUI())}destroy(){window.removeEventListener("resize",this._resize),this._resizeObserver&&this._resizeObserver.disconnect()}}const Hr=new Set(["auto","manual","off"]),Kr=new Set(["local","composite"]),Jr="https://preproduction.tentoro.in/videocall";function Wr(r){const e=new URL(r),t=e.protocol==="https:",n=e.pathname.replace(/\/+$/,"");return{host:e.hostname,port:e.port?parseInt(e.port,10):t?443:80,path:`${n}/peerjs`,secure:t}}class hn{constructor(){this.config=null,this.peerManager=null,this.socketManager=null,this.mediaManager=null,this.uiManager=null,this.isInitialized=!1,this.currentRoom=null,this.currentUser=null}init(e){if(!e||!e.workspace||!e.roomId||!e.user)throw new Error("workspace, roomId, and user are required");const t=e.host||Jr,n=Hr.has(e.recording)?e.recording:"off",s=n!=="off"&&!!e.transcribe,i=s&&!!e.summarize,o=e.recordOnlyIfHost!==!1,a=Kr.has(e.recordingMode)?e.recordingMode:"local",c=Number.isFinite(e.compositeWidth)?e.compositeWidth:1280,h=Number.isFinite(e.compositeHeight)?e.compositeHeight:720,l=Number.isFinite(e.compositeFps)?e.compositeFps:30,d=Number.isFinite(e.recordingVideoBps)?e.recordingVideoBps:1e6,u=Number.isFinite(e.recordingAudioBps)?e.recordingAudioBps:64e3,p=["chat","code","whiteboard"],m=Array.isArray(e.panels)&&e.panels.length?e.panels.filter(_=>p.includes(_)):["chat"];m.includes("chat")||m.unshift("chat"),this.config={...e,host:t,apiUrl:e.apiUrl||`${t}/api`,socketUrl:e.socketUrl||t,peerServer:e.peerServer||Wr(t),ai:{...e.ai||{}},recording:n,transcribe:s,summarize:i,recordOnlyIfHost:o,recordingMode:a,compositeWidth:c,compositeHeight:h,compositeFps:l,recordingVideoBps:d,recordingAudioBps:u,panels:m},this.myRole=null,this.roleResolvers=[],this.currentRoom=this.config.roomId,this.currentUser=this.config.user,this.peerManager=new Fn(this.config),this.socketManager=new Lr(this.config),this.mediaManager=new $r,this.uiManager=new jr({recording:n,screenShare:e.screenShare!==!1,panels:m}),this.recorder=n==="off"?null:new ze,this.compositor=null,this.setupEventHandlers(),this.isInitialized=!0,console.log("MeetSDK initialized")}setupEventHandlers(){this.peerManager.on("stream",(e,t,n)=>{const s=this.labelForPeer(e,n);this.mediaManager.addRemoteStream(e,t),this.uiManager.addVideoStream(e,t,n,s),this.compositor&&this.compositor.addStream(e,t,{isLocal:n,label:s}),this.refreshParticipantsPanel()}),this.peerManager.on("peerLeft",e=>{this.mediaManager.removeRemoteStream(e),this.uiManager.removeVideoStream(e),this.compositor&&this.compositor.removeStream(e),this.refreshParticipantsPanel()}),this.socketManager.on("message",e=>{this.uiManager.addChatMessage(e)}),this.peerLabels=new Map,this.socketManager.on("existingPeers",e=>{e.forEach(t=>{this.peerLabels.set(t.peerId,t.userName||t.userId),this.peerManager.callPeer(t.peerId)})}),this.socketManager.on("userJoined",e=>{this.peerLabels.set(e.peerId,e.userName||e.userId),this.uiManager.updateVideoStreamLabel(e.peerId,e.userName||e.userId),this.peerManager.callPeer(e.peerId),this.refreshParticipantsPanel()}),this.socketManager.on("userLeft",e=>{const t=e.peerId||e.userId;this.mediaManager.removeRemoteStream(t),this.uiManager.removeVideoStream(t),this.compositor&&t&&this.compositor.removeStream(t),e.peerId&&this.peerLabels.delete(e.peerId),this.refreshParticipantsPanel()}),this.socketManager.on("peerMediaStateChange",e=>{if(!e||!e.userId||e.type!=="screen")return;let t=null;for(const[n]of this.peerLabels.entries())if(n.endsWith(`-${e.userId}`)){t=n;break}t&&(e.enabled?this.setPresentingPeer(t):this.presentingPeerId===t&&this.setPresentingPeer(null))}),this.socketManager.on("youJoined",e=>{if(this.myRole=e&&e.role?e.role:"candidate",e&&e.hostId){for(const[n]of this.peerLabels.entries())if(n.endsWith(`-${e.hostId}`)){this.hostPeerId=n;break}}const t=this.roleResolvers;this.roleResolvers=[];for(const n of t)n(this.myRole);this.refreshParticipantsPanel()})}labelForPeer(e,t){return t?this.currentUser&&this.currentUser.name?this.currentUser.name:"You":this.peerLabels&&this.peerLabels.has(e)?this.peerLabels.get(e):e}setPresentingPeer(e){this.presentingPeerId=e||null,this.uiManager&&this.uiManager.setPresentingPeer&&this.uiManager.setPresentingPeer(this.presentingPeerId),this.refreshParticipantsPanel()}refreshParticipantsPanel(){if(!this.uiManager)return;const e=[];if(this.currentUser&&e.push({label:this.currentUser.name||"You",isYou:!0,isHost:this.myRole==="organizer",isSharing:this.peerManager&&this.peerManager.isScreenSharing&&this.peerManager.isScreenSharing()}),this.peerLabels)for(const[t,n]of this.peerLabels.entries())e.push({label:n,isYou:!1,isHost:this.hostPeerId===t,isSharing:this.presentingPeerId===t});this.uiManager.setParticipants(e)}waitForRole(e=3e3){return this.myRole?Promise.resolve(this.myRole):new Promise(t=>{const n=setTimeout(()=>t(this.myRole||"candidate"),e);this.roleResolvers.push(s=>{clearTimeout(n),t(s)})})}async mount(e){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");this.uiManager.mount(e);const t=`${this.config.workspace}-${this.currentRoom}-${this.currentUser.id}`;await this.peerManager.initialize(t);const n=await this.peerManager.getLocalStream();if(this.uiManager.addVideoStream("local",n,!0),this.config.recordingMode==="composite"&&this.recorder)try{this.compositor=new Fe({width:this.config.compositeWidth,height:this.config.compositeHeight,fps:this.config.compositeFps}),await this.compositor.start(),this.compositor.addStream("local",n,{isLocal:!0,label:this.labelForPeer("local",!0)})}catch(s){console.warn("Composite recording unavailable, falling back to local:",s.message),this.compositor=null}this.socketManager.connect(this.config.workspace),setTimeout(()=>{this.socketManager.joinRoom(this.currentRoom,this.currentUser.id,this.currentUser.name,t)},500),this.setupUIControls(),this.setupRecording(n).catch(s=>console.error("setupRecording failed:",s)),this.setupCollabPanels(),this.fetchChatHistory().then(s=>{s&&s.messages&&this.uiManager.setChatHistory(s.messages)}).catch(s=>console.warn("Chat history fetch failed:",s&&s.message)),console.log("MeetSDK mounted")}setupCollabPanels(){if(this.uiManager&&!this.uiManager._panelWired&&(this.uiManager.wirePanelTabs(),this.uiManager._panelWired=!0),this.config.panels.includes("code")){const e=this.uiManager.getPanelSlot("code");e&&(this.codeSandbox=new qr({container:e,userId:this.currentUser.id,canEdit:()=>this._canEditCode(),canRun:()=>this._canEditCode(),emit:(t,n)=>{this.socketManager.emit(t,{roomId:this.currentRoom,userId:this.currentUser.id,userName:this.currentUser.name,...n})}}),this.socketManager.onRaw("code-changed",t=>this.codeSandbox.handleCodeChanged(t)),this.socketManager.onRaw("code-language-changed",t=>this.codeSandbox.handleLanguageChanged(t)),this.socketManager.onRaw("code-executing",t=>this.codeSandbox.handleExecuting(t)),this.socketManager.onRaw("code-execution-result",t=>this.codeSandbox.handleExecutionResult(t)),this.socketManager.onRaw("code-state-sync",t=>{if(t&&Array.isArray(t.editPermissions)){const n=t.editPermissions.find(s=>s.userId===this.currentUser.id);this._codeEditPermission=!!(n&&n.canEdit)}this.codeSandbox.handleStateSync(t)}),this.socketManager.onRaw("code-permission-changed",t=>{if(t&&t.targetUserId===this.currentUser.id&&(this._codeEditPermission=!!t.canEdit),Array.isArray(t&&t.editPermissions)){const n=t.editPermissions.find(s=>s.userId===this.currentUser.id);n&&(this._codeEditPermission=!!n.canEdit)}this.codeSandbox.refreshPermissionUI()}),this.socketManager.emit("code-state-request",{roomId:this.currentRoom}))}if(this.config.panels.includes("whiteboard")){const e=this.uiManager.getPanelSlot("whiteboard");e&&(this.whiteboard=new Vr({container:e,userId:this.currentUser.id,canDraw:()=>this._canDrawWhiteboard(),emit:(t,n)=>{this.socketManager.emit(t,{roomId:this.currentRoom,userId:this.currentUser.id,userName:this.currentUser.name,...n})}}),this.socketManager.onRaw("whiteboard-drawing",t=>this.whiteboard.handleDrawing(t)),this.socketManager.onRaw("whiteboard-cleared",()=>this.whiteboard.handleCleared()),this.socketManager.onRaw("whiteboard-image-uploaded",t=>this.whiteboard.handleImageUploaded(t)),this.socketManager.onRaw("whiteboard-state-sync",t=>{if(t&&Array.isArray(t.drawPermissions)){const n=t.drawPermissions.find(s=>s.userId===this.currentUser.id);this._whiteboardDrawPermission=!!(n&&n.canDraw)}this.whiteboard.handleStateSync(t)}),this.socketManager.onRaw("whiteboard-permission-changed",t=>{if(t&&t.targetUserId===this.currentUser.id&&(this._whiteboardDrawPermission=!!t.canDraw),Array.isArray(t&&t.drawPermissions)){const n=t.drawPermissions.find(s=>s.userId===this.currentUser.id);n&&(this._whiteboardDrawPermission=!!n.canDraw)}this.whiteboard.refreshPermissionUI()}),this.socketManager.emit("whiteboard-state-request",{roomId:this.currentRoom}))}}_canEditCode(){return this.myRole==="organizer"?!0:!!this._codeEditPermission}_canDrawWhiteboard(){return this.myRole==="organizer"?!0:!!this._whiteboardDrawPermission}async fetchChatHistory(e={}){if(!this.isInitialized)throw new Error("SDK not initialized");const t=new URLSearchParams;e.limit&&t.set("limit",String(e.limit)),e.before&&t.set("before",e.before),e.after&&t.set("after",e.after);const n=t.toString(),s=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/chat/messages${n?"?"+n:""}`,{headers:this.buildHeaders()});if(!s.ok)throw new Error(`chat/messages: HTTP ${s.status}`);return s.json()}async uploadChatAttachment(e){if(!this.isInitialized)throw new Error("SDK not initialized");const t=new FormData;t.append("file",e,e.name),t.append("userId",this.currentUser.id),t.append("userName",this.currentUser.name);const n=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/chat/attachments`,{method:"POST",headers:this.buildHeaders(),body:t});if(!n.ok){const s=await n.json().catch(()=>({}));throw new Error(s.error||`Upload failed: HTTP ${n.status}`)}return n.json()}async setupRecording(e){if(this.recorder){if(this.recorder.on("stateChange",t=>{this.uiManager.updateRecordingIndicator(t),this.uiManager.setPauseButtonVisible(t==="recording"||t==="paused"),this.uiManager.setPauseButtonState(t==="paused")}),this.uiManager.onControlClick("toggle-pause",()=>{this.recorder.isPaused()?this.recorder.resume():this.recorder.pause()}),this.config.recordOnlyIfHost&&await this.waitForRole()!=="organizer"){console.log("MeetSDK: not the host — skipping recording");return}this.config.recording==="auto"&&this.startRecording().catch(t=>console.error("Auto-record failed:",t)),this.config.recording==="manual"&&this.uiManager.onControlClick("toggle-record",async()=>{this.recorder.isRecording()?await this.stopRecording():await this.startRecording()})}}async startRecording(){if(!this.recorder)throw new Error("recording is disabled in SDK config");let e;if(this.config.recordingMode==="composite"&&this.compositor){if(e=this.compositor.getStream(),!e)throw new Error("composite stream not ready")}else if(e=this.peerManager.localStream,!e)throw new Error("local stream not ready");const t=this.readStoredSession();let n=null,s=0;if(t){const i=await this.probeSessionStatus(t.sessionId).catch(()=>null);i&&i.active?(n={sessionId:t.sessionId},s=(i.lastSeq||-1)+1,console.log(`MeetSDK: resuming recording session ${t.sessionId} at seq=${s}`)):this.clearStoredSession()}n||(n=await this.startRecordingSession(),this.persistStoredSession(n)),this.recordingSession=n,this.chunkQueue=[],this.chunkDrainerRunning=!1,this.recorder.start(e,{timesliceMs:15e3,startSeq:s,videoBitsPerSecond:this.config.recordingVideoBps,audioBitsPerSecond:this.config.recordingAudioBps,onChunk:(i,o)=>(this.enqueueChunk(n.sessionId,i,o),Promise.resolve())})}storedSessionKey(){return`meetSdk.session.${this.config.workspace}.${this.currentRoom}`}readStoredSession(){try{const e=window.localStorage.getItem(this.storedSessionKey());if(!e)return null;const t=JSON.parse(e);return Date.now()-(t.at||0)>24*60*60*1e3?null:t}catch{return null}}persistStoredSession(e){try{window.localStorage.setItem(this.storedSessionKey(),JSON.stringify({sessionId:e.sessionId,at:Date.now()}))}catch{}}clearStoredSession(){try{window.localStorage.removeItem(this.storedSessionKey())}catch{}}async probeSessionStatus(e){const t=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/status`,{headers:this.buildHeaders()});return t.ok?t.json():null}enqueueChunk(e,t,n){this.chunkQueue=this.chunkQueue||[],this.chunkQueue.push({sessionId:e,blob:t,seq:n}),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length),this.runChunkDrainer().catch(s=>console.warn("Chunk drainer error:",s&&s.message))}async runChunkDrainer(){if(!this.chunkDrainerRunning){this.chunkDrainerRunning=!0;try{for(;this.chunkQueue&&this.chunkQueue.length>0;){const e=this.chunkQueue[0];try{await this.uploadRecordingChunk(e.sessionId,e.blob,e.seq),this.chunkQueue.shift(),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length)}catch(t){if(/HTTP 404|HTTP 409/.test(String(t&&t.message))){console.warn(`Dropping chunk seq=${e.seq}: ${t.message}`),this.chunkQueue.shift(),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length);continue}const n=Math.min(3e4,1e3*Math.pow(2,this._chunkFailStreak||0));this._chunkFailStreak=(this._chunkFailStreak||0)+1,console.warn(`Chunk seq=${e.seq} failed, retrying in ${n}ms`),await new Promise(s=>setTimeout(s,n))}}this._chunkFailStreak=0}finally{this.chunkDrainerRunning=!1}}}async waitForChunkQueueEmpty(){for(;this.chunkQueue&&this.chunkQueue.length>0||this.chunkDrainerRunning;)await new Promise(e=>setTimeout(e,200))}async stopRecording(){if(!this.recorder)return null;const e=await this.recorder.stop();if(!e||!this.recordingSession)return null;const t=this.recordingSession.sessionId;this.recordingSession=null,await this.waitForChunkQueueEmpty();try{return await this.finalizeRecordingSession(t,e)}catch(n){throw console.error("Recording finalize failed:",n),n}}async startRecordingSession(){const e={recordedBy:this.currentUser.id,contentType:this.recorder.mimeType||"video/webm",transcribe:this.config.transcribe,summarize:this.config.summarize},t=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/start`,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`session/start failed: HTTP ${t.status}`);return t.json()}async uploadRecordingChunk(e,t,n){const s=new FormData;s.append("chunk",t,`chunk-${n}.webm`);const i=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/chunk?seq=${n}`,{method:"POST",headers:this.buildHeaders(),body:s});if(!i.ok)throw new Error(`chunk seq=${n}: HTTP ${i.status}`)}async finalizeRecordingSession(e,t){const n=Math.max(0,Math.round((t.endedAt-t.startedAt)/1e3)),s=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/finalize`,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify({durationSec:n,startedAt:t.startedAt.toISOString(),endedAt:t.endedAt.toISOString()})});if(!s.ok)throw new Error(`session/finalize failed: HTTP ${s.status}`);const i=await s.json();return this.clearStoredSession(),i}async listRecordings(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings`,{headers:this.buildHeaders()})).json()}async getRecording(e){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/${encodeURIComponent(e)}`,{headers:this.buildHeaders()})).json()}setupUIControls(){let e=!0,t=!0;this.uiManager.onControlClick("toggle-video",()=>{e=this.peerManager.toggleVideo(),this.uiManager.updateButtonState("toggle-video",e?"Video On":"Video Off")}),this.uiManager.onControlClick("toggle-audio",()=>{t=this.peerManager.toggleAudio(),this.uiManager.updateButtonState("toggle-audio",t?"Mic On":"Mic Off")}),this.uiManager.onControlClick("leave-meeting",()=>{this.leave()}),this.uiManager.onControlClick("toggle-screenshare",async()=>{try{if(this.peerManager.isScreenSharing())await this.peerManager.stopScreenShare(),this.uiManager.setScreenSharingState(!1),this.socketManager.emitMediaState(this.currentRoom,this.currentUser.id,"screen",!1),this.setPresentingPeer(null);else{await this.peerManager.startScreenShare(),this.uiManager.setScreenSharingState(!0),this.socketManager.emitMediaState(this.currentRoom,this.currentUser.id,"screen",!0);const n=`${this.config.workspace}-${this.currentRoom}-${this.currentUser.id}`;this.setPresentingPeer(n)}}catch(n){console.warn("Screen share toggle failed:",n&&n.message)}}),this.uiManager.onChatSend((n,s)=>{this.socketManager.sendMessage(this.currentRoom,this.currentUser.id,this.currentUser.name,n,s)}),this.uiManager.onAttachFile(async n=>this.uploadChatAttachment(n))}buildHeaders(e={}){const t=this.config.ai||{},n={workspace:this.config.workspace,...e};return t.whisperKey&&(n["x-whisper-key"]=t.whisperKey),t.whisperUrl&&(n["x-whisper-url"]=t.whisperUrl),t.llmKey&&(n["x-llm-key"]=t.llmKey),t.llmUrl&&(n["x-llm-url"]=t.llmUrl),t.llmModel&&(n["x-llm-model"]=t.llmModel),n}setAiConfig(e={}){if(!this.config)throw new Error("SDK not initialized");this.config.ai={...this.config.ai||{},...e}}async getSummary(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/summary`,{headers:this.buildHeaders()})).json()}async generateSummary(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/summary/generate`,{method:"POST",headers:this.buildHeaders()})).json()}async transcribeAudio(e,t="audio.webm"){if(!this.isInitialized)throw new Error("SDK not initialized");const n=new FormData;return n.append("audio",e,t),(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/transcribe`,{method:"POST",headers:this.buildHeaders(),body:n})).json()}grantCodeEdit(e,t,n=!0){this.socketManager.emit("code-permission-change",{roomId:this.currentRoom,userId:this.currentUser.id,targetUserId:e,targetUserName:t||e,canEdit:!!n})}grantWhiteboardDraw(e,t,n=!0){this.socketManager.emit("whiteboard-permission-change",{roomId:this.currentRoom,userId:this.currentUser.id,targetUserId:e,targetUserName:t||e,canDraw:!!n})}async leave(){if(this.recorder&&this.recorder.isRecording())try{this.uiManager.setUploadingIndicator(!0),await this.stopRecording()}catch(e){console.warn("Recording upload on leave failed:",e)}finally{this.uiManager.setUploadingIndicator(!1)}if(this.socketManager.leaveRoom(),this.socketManager.disconnect(),this.peerManager.disconnect(),this.mediaManager.cleanup(),this.uiManager.destroy(),this.compositor){try{this.compositor.stop()}catch{}this.compositor=null}this.isInitialized=!1,console.log("Left meeting")}}typeof window<"u"&&(window.MeetSDK=new hn),x.default=hn,Object.defineProperties(x,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
189
+ `,this.canvas=this.container.querySelector("#wb-canvas"),this.wrap=this.container.querySelector("#wb-wrap"),this.ctx=this.canvas.getContext("2d"),this.note=this.container.querySelector("#wb-note"),this._resize=this._resize.bind(this),requestAnimationFrame(()=>{this._resize(),this._replay()}),window.addEventListener("resize",this._resize),this._resizeObserver=null,typeof ResizeObserver<"u"&&(this._resizeObserver=new ResizeObserver(()=>this._resize()),this._resizeObserver.observe(this.wrap)),this.container.querySelectorAll(".wb-tool").forEach(e=>{e.addEventListener("click",()=>{this.tool=e.getAttribute("data-tool"),this.container.querySelectorAll(".wb-tool").forEach(t=>t.classList.toggle("active",t===e))})}),this.container.querySelectorAll(".wb-swatch").forEach(e=>{e.addEventListener("click",()=>{this.color=e.getAttribute("data-color"),this.container.querySelectorAll(".wb-swatch").forEach(t=>t.classList.toggle("active",t===e)),this.tool="pen",this.container.querySelectorAll(".wb-tool").forEach(t=>t.classList.toggle("active",t.getAttribute("data-tool")==="pen"))})}),this.container.querySelector("#wb-size").addEventListener("input",e=>{this.size=parseInt(e.target.value,10)||3}),this.container.querySelector("#wb-clear").addEventListener("click",()=>{this.canDraw()&&(this.emit("whiteboard-clear",{}),this._clearLocal())}),this.canvas.addEventListener("pointerdown",e=>this._onDown(e)),this.canvas.addEventListener("pointermove",e=>this._onMove(e)),this.canvas.addEventListener("pointerup",()=>this._onUp()),this.canvas.addEventListener("pointerleave",()=>this._onUp()),this.refreshPermissionUI()}refreshPermissionUI(){const e=this.canDraw();this.canvas.style.pointerEvents=e?"auto":"none",this.note.textContent=e?"":"View-only — request draw access from the host"}_resize(){if(!this.canvas||!this.wrap)return;const e=this.wrap.getBoundingClientRect(),t=window.devicePixelRatio||1;this.canvas.width=Math.max(300,Math.floor(e.width*t)),this.canvas.height=Math.max(200,Math.floor(e.height*t)),this.ctx.setTransform(t,0,0,t,0,0),this._replay()}_pointerCoords(e){const t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width,y:(e.clientY-t.top)/t.height}}_drawSegment(e,t,n,s,i){const o=this.canvas.getBoundingClientRect().width,a=this.canvas.getBoundingClientRect().height;this.ctx.lineWidth=i,this.ctx.lineCap="round",this.ctx.lineJoin="round",this.ctx.globalCompositeOperation=n==="eraser"?"destination-out":"source-over",this.ctx.strokeStyle=n==="eraser"?"rgba(0,0,0,1)":s,this.ctx.beginPath(),this.ctx.moveTo(e.x*o,e.y*a),this.ctx.lineTo(t.x*o,t.y*a),this.ctx.stroke()}_onDown(e){if(!this.canDraw())return;e.preventDefault(),this.canvas.setPointerCapture(e.pointerId);const t=this._pointerCoords(e);this.currentStroke={tool:this.tool,color:this.color,size:this.size,points:[t]}}_onMove(e){if(!this.currentStroke)return;const t=this._pointerCoords(e),n=this.currentStroke.points[this.currentStroke.points.length-1];this._drawSegment(n,t,this.currentStroke.tool,this.currentStroke.color,this.currentStroke.size),this.currentStroke.points.push(t)}_onUp(){if(!this.currentStroke||this.currentStroke.points.length<2){this.currentStroke=null;return}const e=this.currentStroke;this.currentStroke=null,this.remoteStrokes.push(e),this.emit("whiteboard-draw",{drawing:e})}_clearLocal(){this.remoteStrokes=[],this.imageData=null,this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}_replay(){if(this.ctx){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.imageData&&this._drawBackground();for(const e of this.remoteStrokes){const t=e.points||[];for(let n=1;n<t.length;n++)this._drawSegment(t[n-1],t[n],e.tool,e.color,e.size)}}}_drawBackground(){if(!this.imageData)return;const e=new Image;e.onload=()=>{const t=this.canvas.getBoundingClientRect().width,n=this.canvas.getBoundingClientRect().height;this.ctx.globalCompositeOperation="source-over",this.ctx.drawImage(e,0,0,t,n)},e.src=this.imageData}handleDrawing(e){if(e.userId&&e.userId===this.userId||!e.drawing)return;this.remoteStrokes.push(e.drawing);const t=e.drawing.points||[];for(let n=1;n<t.length;n++)this._drawSegment(t[n-1],t[n],e.drawing.tool,e.drawing.color,e.drawing.size)}handleCleared(){this._clearLocal()}handleImageUploaded(e){this.imageData=e.imageData||null,this._replay()}handleStateSync(e){e&&(this.imageData=e.imageData||null,this.remoteStrokes=Array.isArray(e.drawings)?e.drawings.slice():[],this._replay(),this.refreshPermissionUI())}destroy(){window.removeEventListener("resize",this._resize),this._resizeObserver&&this._resizeObserver.disconnect()}}const Hr=new Set(["auto","manual","off"]),Kr=new Set(["local","composite"]),Jr="https://preproduction.tentoro.in/videocall";function Wr(r){const e=new URL(r),t=e.protocol==="https:",n=e.pathname.replace(/\/+$/,"");return{host:e.hostname,port:e.port?parseInt(e.port,10):t?443:80,path:`${n}/peerjs`,secure:t}}class hn{constructor(){this.config=null,this.peerManager=null,this.socketManager=null,this.mediaManager=null,this.uiManager=null,this.isInitialized=!1,this.currentRoom=null,this.currentUser=null}init(e){if(!e||!e.workspace||!e.roomId||!e.user)throw new Error("workspace, roomId, and user are required");const t=e.host||Jr,n=Hr.has(e.recording)?e.recording:"off",s=n!=="off"&&!!e.transcribe,i=s&&!!e.summarize,o=e.recordOnlyIfHost!==!1,a=Kr.has(e.recordingMode)?e.recordingMode:"local",c=Number.isFinite(e.compositeWidth)?e.compositeWidth:1280,h=Number.isFinite(e.compositeHeight)?e.compositeHeight:720,l=Number.isFinite(e.compositeFps)?e.compositeFps:30,d=Number.isFinite(e.recordingVideoBps)?e.recordingVideoBps:1e6,u=Number.isFinite(e.recordingAudioBps)?e.recordingAudioBps:64e3,p=["chat","code","whiteboard"],m=Array.isArray(e.panels)&&e.panels.length?e.panels.filter(_=>p.includes(_)):["chat"];m.includes("chat")||m.unshift("chat"),this.config={...e,host:t,apiUrl:e.apiUrl||`${t}/api`,socketUrl:e.socketUrl||t,peerServer:e.peerServer||Wr(t),ai:{...e.ai||{}},recording:n,transcribe:s,summarize:i,recordOnlyIfHost:o,recordingMode:a,compositeWidth:c,compositeHeight:h,compositeFps:l,recordingVideoBps:d,recordingAudioBps:u,panels:m},this.myRole=null,this.roleResolvers=[],this.currentRoom=this.config.roomId,this.currentUser=this.config.user,this.peerManager=new Fn(this.config),this.socketManager=new Lr(this.config),this.mediaManager=new $r,this.uiManager=new jr({recording:n,screenShare:e.screenShare!==!1,panels:m}),this.recorder=n==="off"?null:new ze,this.compositor=null,this.setupEventHandlers(),this.isInitialized=!0,console.log("MeetSDK initialized")}setupEventHandlers(){this.peerManager.on("stream",(e,t,n)=>{const s=this.labelForPeer(e,n);this.mediaManager.addRemoteStream(e,t),this.uiManager.addVideoStream(e,t,n,s),this.compositor&&this.compositor.addStream(e,t,{isLocal:n,label:s}),this.refreshParticipantsPanel()}),this.peerManager.on("peerLeft",e=>{this.mediaManager.removeRemoteStream(e),this.uiManager.removeVideoStream(e),this.compositor&&this.compositor.removeStream(e),this.refreshParticipantsPanel()}),this.socketManager.on("message",e=>{this.uiManager.addChatMessage(e)}),this.peerLabels=new Map,this.socketManager.on("existingPeers",e=>{e.forEach(t=>{this.peerLabels.set(t.peerId,t.userName||t.userId),this.peerManager.callPeer(t.peerId)})}),this.socketManager.on("userJoined",e=>{this.peerLabels.set(e.peerId,e.userName||e.userId),this.uiManager.updateVideoStreamLabel(e.peerId,e.userName||e.userId),this.peerManager.callPeer(e.peerId),this.refreshParticipantsPanel()}),this.socketManager.on("userLeft",e=>{const t=e.peerId||e.userId;this.mediaManager.removeRemoteStream(t),this.uiManager.removeVideoStream(t),this.compositor&&t&&this.compositor.removeStream(t),e.peerId&&this.peerLabels.delete(e.peerId),this.refreshParticipantsPanel()}),this.socketManager.on("peerMediaStateChange",e=>{if(!e||!e.userId||e.type!=="screen")return;let t=null;for(const[n]of this.peerLabels.entries())if(n.endsWith(`-${e.userId}`)){t=n;break}t&&(e.enabled?this.setPresentingPeer(t):this.presentingPeerId===t&&this.setPresentingPeer(null))}),this.socketManager.on("youJoined",e=>{if(this.myRole=e&&e.role?e.role:"candidate",console.log(`MeetSDK: joined as ${this.myRole}`+(e&&e.hostId?` (host is ${e.hostName||e.hostId})`:"")),e&&e.hostId){for(const[n]of this.peerLabels.entries())if(n.endsWith(`-${e.hostId}`)){this.hostPeerId=n;break}}const t=this.roleResolvers;this.roleResolvers=[];for(const n of t)n(this.myRole);this.refreshParticipantsPanel()})}async hydrateIceServers(){try{const e=await fetch(`${this.config.apiUrl}/rt-config`,{headers:this.buildHeaders()});if(!e.ok)return;const t=await e.json();if(!t||!Array.isArray(t.iceServers)||t.iceServers.length===0)return;const n=Array.isArray(this.config.iceServers)?this.config.iceServers:[];this.config.iceServers=[...n,...t.iceServers]}catch(e){console.warn("rt-config fetch failed, using STUN defaults:",e&&e.message)}}labelForPeer(e,t){return t?this.currentUser&&this.currentUser.name?this.currentUser.name:"You":this.peerLabels&&this.peerLabels.has(e)?this.peerLabels.get(e):e}setPresentingPeer(e){this.presentingPeerId=e||null,this.uiManager&&this.uiManager.setPresentingPeer&&this.uiManager.setPresentingPeer(this.presentingPeerId),this.refreshParticipantsPanel()}refreshParticipantsPanel(){if(!this.uiManager)return;const e=[];if(this.currentUser&&e.push({label:this.currentUser.name||"You",isYou:!0,isHost:this.myRole==="organizer",isSharing:this.peerManager&&this.peerManager.isScreenSharing&&this.peerManager.isScreenSharing()}),this.peerLabels)for(const[t,n]of this.peerLabels.entries())e.push({label:n,isYou:!1,isHost:this.hostPeerId===t,isSharing:this.presentingPeerId===t});this.uiManager.setParticipants(e)}waitForRole(e=3e3){return this.myRole?Promise.resolve(this.myRole):new Promise(t=>{const n=setTimeout(()=>t(this.myRole||"candidate"),e);this.roleResolvers.push(s=>{clearTimeout(n),t(s)})})}async mount(e){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");this.uiManager.mount(e),await this.hydrateIceServers();const t=`${this.config.workspace}-${this.currentRoom}-${this.currentUser.id}`;await this.peerManager.initialize(t);const n=await this.peerManager.getLocalStream();if(this.uiManager.addVideoStream("local",n,!0),this.config.recordingMode==="composite"&&this.recorder)try{this.compositor=new Fe({width:this.config.compositeWidth,height:this.config.compositeHeight,fps:this.config.compositeFps}),await this.compositor.start(),this.compositor.addStream("local",n,{isLocal:!0,label:this.labelForPeer("local",!0)})}catch(s){console.warn("Composite recording unavailable, falling back to local:",s.message),this.compositor=null}this.socketManager.connect(this.config.workspace),setTimeout(()=>{this.socketManager.joinRoom(this.currentRoom,this.currentUser.id,this.currentUser.name,t)},500),this.setupUIControls(),this.setupRecording(n).catch(s=>console.error("setupRecording failed:",s)),this.setupCollabPanels(),this.fetchChatHistory().then(s=>{s&&s.messages&&this.uiManager.setChatHistory(s.messages)}).catch(s=>console.warn("Chat history fetch failed:",s&&s.message)),console.log("MeetSDK mounted")}setupCollabPanels(){if(this.uiManager&&!this.uiManager._panelWired&&(this.uiManager.wirePanelTabs(),this.uiManager._panelWired=!0),this.config.panels.includes("code")){const e=this.uiManager.getPanelSlot("code");e&&(this.codeSandbox=new qr({container:e,userId:this.currentUser.id,canEdit:()=>this._canEditCode(),canRun:()=>this._canEditCode(),emit:(t,n)=>{this.socketManager.emit(t,{roomId:this.currentRoom,userId:this.currentUser.id,userName:this.currentUser.name,...n})}}),this.socketManager.onRaw("code-changed",t=>this.codeSandbox.handleCodeChanged(t)),this.socketManager.onRaw("code-language-changed",t=>this.codeSandbox.handleLanguageChanged(t)),this.socketManager.onRaw("code-executing",t=>this.codeSandbox.handleExecuting(t)),this.socketManager.onRaw("code-execution-result",t=>this.codeSandbox.handleExecutionResult(t)),this.socketManager.onRaw("code-state-sync",t=>{if(t&&Array.isArray(t.editPermissions)){const n=t.editPermissions.find(s=>s.userId===this.currentUser.id);this._codeEditPermission=!!(n&&n.canEdit)}this.codeSandbox.handleStateSync(t)}),this.socketManager.onRaw("code-permission-changed",t=>{if(t&&t.targetUserId===this.currentUser.id&&(this._codeEditPermission=!!t.canEdit),Array.isArray(t&&t.editPermissions)){const n=t.editPermissions.find(s=>s.userId===this.currentUser.id);n&&(this._codeEditPermission=!!n.canEdit)}this.codeSandbox.refreshPermissionUI()}),this.socketManager.emit("code-state-request",{roomId:this.currentRoom}))}if(this.config.panels.includes("whiteboard")){const e=this.uiManager.getPanelSlot("whiteboard");e&&(this.whiteboard=new Vr({container:e,userId:this.currentUser.id,canDraw:()=>this._canDrawWhiteboard(),emit:(t,n)=>{this.socketManager.emit(t,{roomId:this.currentRoom,userId:this.currentUser.id,userName:this.currentUser.name,...n})}}),this.socketManager.onRaw("whiteboard-drawing",t=>this.whiteboard.handleDrawing(t)),this.socketManager.onRaw("whiteboard-cleared",()=>this.whiteboard.handleCleared()),this.socketManager.onRaw("whiteboard-image-uploaded",t=>this.whiteboard.handleImageUploaded(t)),this.socketManager.onRaw("whiteboard-state-sync",t=>{if(t&&Array.isArray(t.drawPermissions)){const n=t.drawPermissions.find(s=>s.userId===this.currentUser.id);this._whiteboardDrawPermission=!!(n&&n.canDraw)}this.whiteboard.handleStateSync(t)}),this.socketManager.onRaw("whiteboard-permission-changed",t=>{if(t&&t.targetUserId===this.currentUser.id&&(this._whiteboardDrawPermission=!!t.canDraw),Array.isArray(t&&t.drawPermissions)){const n=t.drawPermissions.find(s=>s.userId===this.currentUser.id);n&&(this._whiteboardDrawPermission=!!n.canDraw)}this.whiteboard.refreshPermissionUI()}),this.socketManager.emit("whiteboard-state-request",{roomId:this.currentRoom}))}}_canEditCode(){return this.myRole==="organizer"?!0:!!this._codeEditPermission}_canDrawWhiteboard(){return this.myRole==="organizer"?!0:!!this._whiteboardDrawPermission}async fetchChatHistory(e={}){if(!this.isInitialized)throw new Error("SDK not initialized");const t=new URLSearchParams;e.limit&&t.set("limit",String(e.limit)),e.before&&t.set("before",e.before),e.after&&t.set("after",e.after);const n=t.toString(),s=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/chat/messages${n?"?"+n:""}`,{headers:this.buildHeaders()});if(!s.ok)throw new Error(`chat/messages: HTTP ${s.status}`);return s.json()}async uploadChatAttachment(e){if(!this.isInitialized)throw new Error("SDK not initialized");const t=new FormData;t.append("file",e,e.name),t.append("userId",this.currentUser.id),t.append("userName",this.currentUser.name);const n=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/chat/attachments`,{method:"POST",headers:this.buildHeaders(),body:t});if(!n.ok){const s=await n.json().catch(()=>({}));throw new Error(s.error||`Upload failed: HTTP ${n.status}`)}return n.json()}async setupRecording(e){if(this.recorder){if(this.recorder.on("stateChange",t=>{this.uiManager.updateRecordingIndicator(t),this.uiManager.setPauseButtonVisible(t==="recording"||t==="paused"),this.uiManager.setPauseButtonState(t==="paused")}),this.uiManager.onControlClick("toggle-pause",()=>{this.recorder.isPaused()?this.recorder.resume():this.recorder.pause()}),this.config.recordOnlyIfHost&&await this.waitForRole()!=="organizer"){console.log("MeetSDK: not the host — skipping recording");return}this.config.recording==="auto"&&this.startRecording().catch(t=>console.error("Auto-record failed:",t)),this.config.recording==="manual"&&this.uiManager.onControlClick("toggle-record",async()=>{this.recorder.isRecording()?await this.stopRecording():await this.startRecording()})}}async startRecording(){if(!this.recorder)throw new Error("recording is disabled in SDK config");let e;if(this.config.recordingMode==="composite"&&this.compositor){if(e=this.compositor.getStream(),!e)throw new Error("composite stream not ready")}else if(e=this.peerManager.localStream,!e)throw new Error("local stream not ready");const t=this.readStoredSession();let n=null,s=0;if(t){const i=await this.probeSessionStatus(t.sessionId).catch(()=>null);i&&i.active?(n={sessionId:t.sessionId},s=(i.lastSeq||-1)+1,console.log(`MeetSDK: resuming recording session ${t.sessionId} at seq=${s}`)):this.clearStoredSession()}n||(n=await this.startRecordingSession(),this.persistStoredSession(n)),this.recordingSession=n,this.chunkQueue=[],this.chunkDrainerRunning=!1,this.recorder.start(e,{timesliceMs:15e3,startSeq:s,videoBitsPerSecond:this.config.recordingVideoBps,audioBitsPerSecond:this.config.recordingAudioBps,onChunk:(i,o)=>(this.enqueueChunk(n.sessionId,i,o),Promise.resolve())})}storedSessionKey(){return`meetSdk.session.${this.config.workspace}.${this.currentRoom}`}readStoredSession(){try{const e=window.localStorage.getItem(this.storedSessionKey());if(!e)return null;const t=JSON.parse(e);return Date.now()-(t.at||0)>24*60*60*1e3?null:t}catch{return null}}persistStoredSession(e){try{window.localStorage.setItem(this.storedSessionKey(),JSON.stringify({sessionId:e.sessionId,at:Date.now()}))}catch{}}clearStoredSession(){try{window.localStorage.removeItem(this.storedSessionKey())}catch{}}async probeSessionStatus(e){const t=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/status`,{headers:this.buildHeaders()});return t.ok?t.json():null}enqueueChunk(e,t,n){this.chunkQueue=this.chunkQueue||[],this.chunkQueue.push({sessionId:e,blob:t,seq:n}),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length),this.runChunkDrainer().catch(s=>console.warn("Chunk drainer error:",s&&s.message))}async runChunkDrainer(){if(!this.chunkDrainerRunning){this.chunkDrainerRunning=!0;try{for(;this.chunkQueue&&this.chunkQueue.length>0;){const e=this.chunkQueue[0];try{await this.uploadRecordingChunk(e.sessionId,e.blob,e.seq),this.chunkQueue.shift(),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length)}catch(t){if(/HTTP 404|HTTP 409/.test(String(t&&t.message))){console.warn(`Dropping chunk seq=${e.seq}: ${t.message}`),this.chunkQueue.shift(),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length);continue}const n=Math.min(3e4,1e3*Math.pow(2,this._chunkFailStreak||0));this._chunkFailStreak=(this._chunkFailStreak||0)+1,console.warn(`Chunk seq=${e.seq} failed, retrying in ${n}ms`),await new Promise(s=>setTimeout(s,n))}}this._chunkFailStreak=0}finally{this.chunkDrainerRunning=!1}}}async waitForChunkQueueEmpty(){for(;this.chunkQueue&&this.chunkQueue.length>0||this.chunkDrainerRunning;)await new Promise(e=>setTimeout(e,200))}async stopRecording(){if(!this.recorder)return null;const e=await this.recorder.stop();if(!e||!this.recordingSession)return null;const t=this.recordingSession.sessionId;this.recordingSession=null,await this.waitForChunkQueueEmpty();try{return await this.finalizeRecordingSession(t,e)}catch(n){throw console.error("Recording finalize failed:",n),n}}async startRecordingSession(){const e={recordedBy:this.currentUser.id,contentType:this.recorder.mimeType||"video/webm",transcribe:this.config.transcribe,summarize:this.config.summarize},t=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/start`,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`session/start failed: HTTP ${t.status}`);return t.json()}async uploadRecordingChunk(e,t,n){const s=new FormData;s.append("chunk",t,`chunk-${n}.webm`);const i=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/chunk?seq=${n}`,{method:"POST",headers:this.buildHeaders(),body:s});if(!i.ok)throw new Error(`chunk seq=${n}: HTTP ${i.status}`)}async finalizeRecordingSession(e,t){const n=Math.max(0,Math.round((t.endedAt-t.startedAt)/1e3)),s=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/finalize`,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify({durationSec:n,startedAt:t.startedAt.toISOString(),endedAt:t.endedAt.toISOString()})});if(!s.ok)throw new Error(`session/finalize failed: HTTP ${s.status}`);const i=await s.json();return this.clearStoredSession(),i}async listRecordings(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings`,{headers:this.buildHeaders()})).json()}async getRecording(e){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/${encodeURIComponent(e)}`,{headers:this.buildHeaders()})).json()}setupUIControls(){let e=!0,t=!0;this.uiManager.onControlClick("toggle-video",()=>{e=this.peerManager.toggleVideo(),this.uiManager.updateButtonState("toggle-video",e?"Video On":"Video Off")}),this.uiManager.onControlClick("toggle-audio",()=>{t=this.peerManager.toggleAudio(),this.uiManager.updateButtonState("toggle-audio",t?"Mic On":"Mic Off")}),this.uiManager.onControlClick("leave-meeting",()=>{this.leave()}),this.uiManager.onControlClick("toggle-screenshare",async()=>{try{if(this.peerManager.isScreenSharing())await this.peerManager.stopScreenShare(),this.uiManager.setScreenSharingState(!1),this.socketManager.emitMediaState(this.currentRoom,this.currentUser.id,"screen",!1),this.setPresentingPeer(null);else{await this.peerManager.startScreenShare(),this.uiManager.setScreenSharingState(!0),this.socketManager.emitMediaState(this.currentRoom,this.currentUser.id,"screen",!0);const n=`${this.config.workspace}-${this.currentRoom}-${this.currentUser.id}`;this.setPresentingPeer(n)}}catch(n){console.warn("Screen share toggle failed:",n&&n.message)}}),this.uiManager.onChatSend((n,s)=>{this.socketManager.sendMessage(this.currentRoom,this.currentUser.id,this.currentUser.name,n,s)}),this.uiManager.onAttachFile(async n=>this.uploadChatAttachment(n))}buildHeaders(e={}){const t=this.config.ai||{},n={workspace:this.config.workspace,...e};return t.whisperKey&&(n["x-whisper-key"]=t.whisperKey),t.whisperUrl&&(n["x-whisper-url"]=t.whisperUrl),t.llmKey&&(n["x-llm-key"]=t.llmKey),t.llmUrl&&(n["x-llm-url"]=t.llmUrl),t.llmModel&&(n["x-llm-model"]=t.llmModel),n}setAiConfig(e={}){if(!this.config)throw new Error("SDK not initialized");this.config.ai={...this.config.ai||{},...e}}async getSummary(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/summary`,{headers:this.buildHeaders()})).json()}async generateSummary(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/summary/generate`,{method:"POST",headers:this.buildHeaders()})).json()}async transcribeAudio(e,t="audio.webm"){if(!this.isInitialized)throw new Error("SDK not initialized");const n=new FormData;return n.append("audio",e,t),(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/transcribe`,{method:"POST",headers:this.buildHeaders(),body:n})).json()}grantCodeEdit(e,t,n=!0){this.socketManager.emit("code-permission-change",{roomId:this.currentRoom,userId:this.currentUser.id,targetUserId:e,targetUserName:t||e,canEdit:!!n})}grantWhiteboardDraw(e,t,n=!0){this.socketManager.emit("whiteboard-permission-change",{roomId:this.currentRoom,userId:this.currentUser.id,targetUserId:e,targetUserName:t||e,canDraw:!!n})}async leave(){if(this.recorder&&this.recorder.isRecording())try{this.uiManager.setUploadingIndicator(!0),await this.stopRecording()}catch(e){console.warn("Recording upload on leave failed:",e)}finally{this.uiManager.setUploadingIndicator(!1)}if(this.socketManager.leaveRoom(),this.socketManager.disconnect(),this.peerManager.disconnect(),this.mediaManager.cleanup(),this.uiManager.destroy(),this.compositor){try{this.compositor.stop()}catch{}this.compositor=null}this.isInitialized=!1,console.log("Left meeting")}}typeof window<"u"&&(window.MeetSDK=new hn),x.default=hn,Object.defineProperties(x,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nainudhin/video-meeting-sdk",
3
- "version": "1.7.1",
3
+ "version": "1.8.1",
4
4
  "description": "Embeddable multi-tenant video meeting SDK (PeerJS + Socket.IO)",
5
5
  "type": "module",
6
6
  "main": "./dist/meet-sdk.umd.js",