import _ from "lodash" ; import OSCSched from "./OSCSched" ; import Server , { msg } from "@supercollider/server" ; import { Middleware , UpdateContext , Command , Context } from "dryadic" ; interface Properties { } interface ServerContext extends Context { oscSched ? : any ; epoch ? : number ; scserver : Server ; } interface ServerCommand extends Command { scserver ? : { msg ? : any ; bundle ? : any ; schedLoop ? : any ; callAndResponse ? : msg . CallAndResponse ; } ; } param { object } command export const scserver = async ( command , context , properties , updateContext ) : Promise < void > => { if ( command . scserver ) { const ctx = context as ServerContext ; const cmds = resolveFuncs ( command . scserver , ctx , properties ) ; if ( cmds . msg ) { ctx . scserver . send . bundle ( 0.05 , [ cmds . msg ] ) ; } if ( cmds . bundle ) { ctx . scserver . send . bundle ( cmds . bundle . time , cmds . bundle . packets ) ; } if ( cmds . schedLoop ) { let oscSched = ctx . oscSched ; if ( ! oscSched ) { const sendFn = ( time , packets ) => ctx . scserver . send . bundle ( time , packets ) ; oscSched = new OSCSched ( sendFn ) ; updateContext ( context , { oscSched } ) ; } oscSched . schedLoop ( cmds . schedLoop , ctx . epoch ) ; } if ( cmds . callAndResponse ) { await ctx . scserver . callAndResponse ( cmds . callAndResponse ) ; } } } ; export default scserver ; /**
 * Replace any functions in the command object's values with the result of
 * calling the function.
 *
 * eg. msg: (context) => { ... return ['/s_new', ...]; }
 * becomes msg: ['/s_new', ...]
 *
 * Non-functions are passed through.
 */ export function resolveFuncs ( command , context , properties ) { return _ . mapValues ( command , value => _callIfFn ( value , context , properties ) ) ; } private function _callIfFn < T = any > ( thing , context , properties ) { return _ . isFunction ( thing ) ? thing ( context , properties ) : thing ; }