import {gmAccessPolicy} from '../audio/gm-host.mjs'; import {validateIceServers} from '../audio/peer-audio.mjs'; import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs'; const messages={ 'saved-connection-unavailable':'This token could not unlock the saved connection. Enter the server address and a valid token to save a new connection.', 'saved-connection-write-failed':'Connected, but Foundry could not save the connection for this account.', 'private-credential-write-failed':'Connected, but the browser could not remember the credential on this device.', 'receiver-storage-write-failed':'The browser could not update the remembered receiver. Check site storage before reconnecting.', 'private-credential-corrupt':'The device credential could not be unlocked. Use Forget Credentials and enter a valid token.', 'ice-config-invalid':'Enter a valid existing STUN/TURN URL. TURN also needs a username, credential and UTC expiry within one hour. No network setting was applied.', 'token-required':'Enter a Music Assistant access token for this server.', 'token-invalid':'Remove line breaks from the access token and try again.', 'receiver-name-invalid':'Use at most 120 characters for the receiver name, without line breaks.', 'automation-disabled':'Enable automation before applying a manual playlist override.', 'address-invalid':'Enter the MA server origin, such as https://ma.example.test, without a path or query.', 'ws-upgrade-failed':'The browser could not open the API WebSocket. Run Check browser connection below. If it works from MA’s page only, compare this browser’s local-network permission, private DNS and site restrictions.', 'ws-auth-timeout':'The API socket opened, but authentication did not finish. Check that /ws reaches MA rather than a login portal.', 'ws-auth-denied':'MA rejected the token. Enter a replacement and select Connect again; the receiver is remembered.', 'ws-disconnected':'The API socket closed. Your private inputs remain in this tab. Retry after checking the private route.', 'ws-command-timeout':'MA did not answer a command before its deadline. Catalog reads have a 10-second limit; stream startup has a 60-second limit. Unconfirmed queue writes stop automation for review.', 'ws-command-failed':'MA rejected a command. The account needs music-provider access and permission to control and pair its dedicated web receiver.', 'sendspin-auth-failed':'The receiver socket opened, but Sendspin authentication failed. Verify the authenticated /sendspin route, separate from /ws.', 'sendspin-sync-failed':'Sendspin did not complete pairing and clock synchronization. Retry the remembered receiver; transport HTTP 101 alone does not prove a working audio receiver.', 'audio-context-unavailable':'This browser could not start Web Audio. Check the browser’s audio output and whether another device is using it exclusively.', 'insecure-context':'Open Foundry over trusted HTTPS to use secure browser audio APIs.', 'mixed-content':'HTTPS Foundry requires a trusted HTTPS MA address. Browser security cannot permit an HTTP/ws downgrade.', 'reconcile-required':'This dedicated receiver has an existing queue. Playback was left untouched. Resume the remembered receiver after reviewing its queue in MA, or use a new dedicated receiver.', 'catalog-empty':'No available music providers were returned. Check the dedicated MA account’s music-provider access.', 'unsupported':'This queue or browser feature is unsupported. Use a standalone receiver with a static queue, shuffle and autoplay off, and a browser with Web Locks, Web Audio and WebRTC.', 'campaign-paused':'Select Play all music to resume campaign playback.', 'private-storage-unavailable':'This browser denied private storage. Allow site storage for this Foundry address and retry.', 'private-storage-corrupt':'The remembered receiver could not be decrypted. Use Forget remembered receiver below to create a replacement. Existing MA queues are left untouched.', 'identity-mismatch':'The remembered receiver identity does not match this connection. Forget that receiver to create a new campaign receiver.', 'dedicated-target-required':'The receiver did not match the identity and name created for this campaign. No unrelated player was selected.', 'receiver-queue-unavailable':'MA did not make this receiver’s queue available after connection. Retry connecting the remembered receiver.', 'receiver-access-lost':'Music Assistant withdrew this receiver’s queue access. If another MA browser player uses this token, give the two players separate tokens. Review the dedicated receiver before reconnecting.', 'denied':'The dedicated receiver, account permission or active GM check failed. Keep one active GM and verify that this account can control its campaign receiver.', 'stale':'GM authority or the connection changed during setup. Keep one active GM, then retry.', 'uncertain':'MA did not confirm a queue write. Automation stopped to avoid duplicate playback. Review this dedicated queue before reconnecting.', 'unavailable':'The operation failed. Your private inputs are retained. Run the browser connection check to separate transport failures from receiver and audio setup.' }; const connectionStages=new Set(['API authentication','Sendspin authentication','Noise handshake','receiver pairing', 'clock synchronization','dedicated receiver verification','catalog retrieval','dedicated queue verification']); function diagnosticFailure(error){ return {code:Object.hasOwn(messages,error?.code)?error.code:'unavailable', ...(connectionStages.has(error?.stage)&&{stage:error.stage})}; } export function connectionMessage(error){ if(error?.code==='ws-upgrade-failed'&&error.stage==='Sendspin authentication')return 'The browser could not open the receiver’s /sendspin WebSocket. Check both routes from this Foundry page.'; if(error?.upstreamCode===2&&['player_queues/play_media','player_queues/play_index'].includes(error.command))return 'MA could not find playable media for this playlist (MA error 2). Check its content/provider in MA or choose another playlist. Automation stopped after an unconfirmed queue write.'; return messages[error?.code]??messages.unavailable; } function failureStage(error) { if(error?.code==='audio-context-unavailable')return 'Browser audio unavailable'; if(error?.stage==='Sendspin authentication'&&error.code==='ws-upgrade-failed')return 'Receiver connection failed'; if (['ws-upgrade-failed', 'ws-disconnected', 'mixed-content', 'insecure-context'].includes(error?.code)) return 'Connection failed'; if (['ws-auth-denied', 'ws-auth-timeout'].includes(error?.code) || error?.stage === 'API authentication') return 'Authentication failed'; if (['receiver pairing','dedicated receiver verification','dedicated queue verification','Noise handshake'].includes(error?.stage) || error?.code === 'sendspin-sync-failed') return 'Receiver setup failed'; if (error?.stage === 'Sendspin authentication' || error?.code === 'sendspin-auth-failed') return 'Receiver connection failed'; if (error?.stage === 'catalog retrieval' || error?.code === 'catalog-empty') return 'Playlist catalog unavailable'; return 'Setup failed'; } function iceConfiguration(fields) { const {url, username, credential, expires} = fields; if (!url && !username && !credential && !expires) return undefined; const scheme = url.match(/^(stun|stuns|turn|turns):/i)?.[1].toLowerCase(); const target = scheme && URL.canParse(`https://${url.slice(scheme.length + 1)}`) && new URL(`https://${url.slice(scheme.length + 1)}`); const turn = scheme?.startsWith('turn'); if (!target || !target.hostname || target.username || target.password || target.pathname !== '/' || target.hash || /[\s/]/.test(url) || (target.search && !(turn && /^\?transport=(udp|tcp)$/.test(target.search))) || (!turn && (username || credential || expires))) throw {code:'ice-config-invalid'}; const server = {urls:url, ...(turn ? {username, credential, expires:Date.parse(expires + 'Z')} : {})}; try{validateIceServers([server]);} catch{throw {code:'ice-config-invalid'};} return {iceServers:[server]}; } export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{},next,advancedContent}) { const dom=container.ownerDocument; const make=(tag,text,parent=container)=>{ const node=dom.createElement(tag); if(text)node.textContent=text; parent.append(node); return node; }; const input=(parent,label,type='text')=>{ const wrapper=make('label',label,parent),field=make('input',null,wrapper); field.type=type;field.autocomplete='off';field.spellcheck=false; return field; }; const initial=connection.draftFields??{}; make('h2','Connect Music Assistant'); make('p','Enter your Music Assistant address and access token. Adaptive Music creates or reconnects your campaign receiver and loads your playlists.'); if(initial.savedConnection&&!initial.deviceCredential)make('p','This Foundry account has a saved connection. Enter its access token to unlock the address, or enter a different address to replace it.'); const fields=make('div');fields.className='adaptive-fields'; const address=input(fields,'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=initial.maUrl??''; const token=input(fields,'Private GM access token','password'); const remember=input(fields,'Remember credentials and reconnect on this trusted device','checkbox');remember.checked=initial.deviceCredential===true; make('p','Use a revocable Music Assistant token. Remembered credentials belong to this browser profile. Enable this only on a device and Foundry site you trust.'); const retainError=make('p');retainError.setAttribute('role','alert');retainError.hidden=true; const actions=make('div');actions.className='adaptive-actions'; const state=make('p');state.className='adaptive-state'; const status=make('p');status.setAttribute('role','status'); const automaticFailure=make('p');automaticFailure.hidden=true; const advanced=make('details');make('summary','Advanced',advanced); const advancedFields=make('div',null,advanced);advancedFields.className='adaptive-fields'; const name=input(advancedFields,'Dedicated receiver name');name.value=initial.targetName??'';name.placeholder='Adaptive Music '+(game.world?.title??'campaign'); const iceURL=input(advancedFields,'ICE server URL');iceURL.placeholder='stun:stun.example.test:3478'; const iceUsername=input(advancedFields,'TURN username'),iceCredential=input(advancedFields,'TURN credential','password'); const iceExpiry=input(advancedFields,'TURN credential expiry (UTC)','datetime-local'); const diagnosticsActions=make('div');diagnosticsActions.className='adaptive-actions'; const report=make('div');report.setAttribute('aria-live','polite'); let transportResults=[],transportCheckAt,lastConnectFailure,busy=false,hadDeviceCredential=initial.deviceCredential; const run=async(action,label,onFailure)=>{ if(busy||!game.user.isGM)return; busy=true;retainError.hidden=true;render(); try{await action();} catch(error){ onFailure?.(error); busy=false;render();error.field?.focus?.(); retainError.textContent=`${typeof label==='function'?label(error):label}. ${connectionMessage(error)}`;retainError.hidden=false;onError(error); }finally{busy=false;render();} }; const button=(parent,label,action)=>{ const b=make('button',label,parent);b.type='button';b.addEventListener('click',action);return b; }; const pageUrl=()=>dom.location?.href??globalThis.location?.href??'https://foundry.invalid'; function validatedAddress(){ try{return gmAccessPolicy(address.value.trim(),pageUrl()).origin;} catch(error){if(error.code==='denied')throw {code:'address-invalid'};throw error;} } function retainedToken(){ const draft=connection.draftFields??{}; try{return draft.retainedToken===true&&new URL(draft.maUrl).origin===validatedAddress();} catch{return false;} } const connect=button(actions,'Connect',()=>run(async()=>{ lastConnectFailure=undefined; let maUrl; const useSaved=!address.value.trim()&&connection.draftFields?.savedConnection; if(!useSaved)try{maUrl=validatedAddress();}catch(error){throw {code:error.code,field:address};} const draft=connection.draftFields??{}; const usingDevice=draft.deviceCredential&&draft.maUrl===maUrl; if(!token.value.trim()&&!usingDevice&&(useSaved||!retainedToken()))throw {code:'token-required',field:token}; if(/[\r\n]/.test(token.value))throw {code:'token-invalid',field:token}; const targetName=name.value.trim(); if(targetName.length>120||/[\x00-\x1f\x7f]/.test(name.value)){advanced.open=true;throw {code:'receiver-name-invalid',field:name};} let listenerNetwork; try{listenerNetwork=iceConfiguration({url:iceURL.value.trim(),username:iceUsername.value.trim(),credential:iceCredential.value,expires:iceExpiry.value});} catch{advanced.open=true;throw {code:'ice-config-invalid',field:iceURL};} status.textContent='Contacting Music Assistant…'; let result; try{result=await connection.open({maUrl,token:token.value.trim(),remember:remember.checked,...(targetName&&{targetName}),...(listenerNetwork&&{listenerNetwork})});} finally{if(connection.status.hasPrivateDraft){token.value='';iceCredential.value='';}} address.value=connection.draftFields?.maUrl??address.value; await onCatalog(); status.textContent=result?.attachedExistingQueue?'Connected. The existing queue is preserved. Enable automation from Playback when you’re ready.':'Campaign audio connected. Choose playlists for your scene.'; },error=>['address-invalid','token-invalid','token-required','receiver-name-invalid','ice-config-invalid'].includes(error.code)?'Check your settings':failureStage(error), error=>{lastConnectFailure={at:new Date().toISOString(),...diagnosticFailure(error)};})); connect.className='adaptive-primary'; const nextButton=button(actions,'Choose scene music',()=>next?.()); const disconnect=button(actions,'Disconnect',()=>run(async()=>{ await connection.disconnect();token.value='';iceCredential.value='';status.textContent='Disconnected. Automatic reconnection is paused until you connect again.';await onCatalog(); },'Disconnect failed')); const forgetCredentials=button(actions,'Forget Credentials',()=>run(async()=>{ await connection.forgetCredentials();remember.checked=false;token.value='';status.textContent='Credentials removed from this device.';await onCatalog(); },'Could not forget credentials')); button(diagnosticsActions,'Check browser connection',()=>run(async()=>{ report.replaceChildren();transportResults=[];transportCheckAt=undefined; transportResults=await probeWebSockets(validatedAddress()); transportCheckAt=new Date().toISOString(); for(const result of transportResults)make('p',`${result.path} — ${diagnosticMessage(result)}`,report); status.textContent='Browser checks complete.'; },'Browser connection check failed')); button(diagnosticsActions,'Copy connection diagnostics',()=>run(async()=>{ const d=connection.status; const details={ state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext, decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames, droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,bufferedMs:d.bufferedMs, underruns:d.underruns,bufferOverruns:d.bufferOverruns, sourceGaps:d.sourceGaps,sourceOverlaps:d.sourceOverlaps,gapMs:d.gapMs,overlapMs:d.overlapMs, muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS, listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics, transport:transportResults,transportCheckAt,lastConnectFailure, automaticConnectFailure:d.deviceError?diagnosticFailure({code:d.deviceError}):undefined, secureContext:globalThis.isSecureContext, }; await navigator.clipboard.writeText(JSON.stringify(details,null,2)); status.textContent='Connection diagnostics copied.'; },'Could not copy diagnostics')); const advancedActions=make('div',null,advanced);advancedActions.className='adaptive-actions'; const refresh=button(advancedActions,'Refresh playlists',()=>run(async()=>{await connection.refresh();await onCatalog();status.textContent='Playlists refreshed.';},'Catalog refresh failed')); const forget=button(advancedActions,'Forget saved connection',()=>run(async()=>{ await connection.forgetReceiver();address.value='';token.value='';iceCredential.value='';name.value='';status.textContent='Saved connection removed from this account.';await onCatalog(); },'Could not forget the connection')); if(advancedContent)advanced.append(advancedContent); function render(){ const d=connection.status,connected=d.state==='connected'; const connecting=busy||d.deviceReconnect; const label=connected?'Connected':connecting?'Working':d.state==='connection-lost'?'Connection lost':d.deviceError?'Automatic connection failed':'Disconnected'; const summary=connected?`${label} · ${d.catalog??0} catalog choices`: busy&&d.stage&&d.stage!=='idle'?`${label} · ${d.stage}`:label; if(state.textContent!==summary)state.textContent=summary; state.dataset.connected=String(connected); automaticFailure.hidden=connected||connecting||!d.deviceError; if(!automaticFailure.hidden)automaticFailure.textContent=connectionMessage({code:d.deviceError}); connect.hidden=connected;connect.disabled=connecting;connect.textContent=connecting?'Connecting…':'Connect'; disconnect.hidden=!connected;disconnect.disabled=busy; nextButton.hidden=!connected||!next;nextButton.disabled=busy;refresh.hidden=!connected; forget.disabled=busy||(!d.hasPrivateDraft&&!connection.draftFields?.savedConnection); const draft=connection.draftFields; forgetCredentials.hidden=!draft?.deviceCredential&&d.deviceError!=='private-credential-corrupt';forgetCredentials.disabled=connecting; if(!address.value&&draft?.deviceCredential&&!hadDeviceCredential)address.value=draft.maUrl; if(draft?.deviceCredential&&!hadDeviceCredential)remember.checked=true; hadDeviceCredential=draft?.deviceCredential; for(const field of [address,token,name,iceURL,iceUsername,iceCredential,iceExpiry,remember])field.disabled=connected||connecting; token.placeholder=retainedToken()||connection.draftFields?.deviceCredential?'Retained for this address':'Paste your access token'; } address.addEventListener('input',render); render(); return render; }