import { createPlugin } from "@prodo/core" ; import { Event } from "@prodo/core/lib/types" ; import DevTools , { DevMessage } from "@prodo/devtools-core" ; import { original } from "immer" ; import * as _ from "lodash" ; export interface DevToolsConfig { devtools ? : boolean ; devtoolsServer ? : { port : number ; buttons : { [ key ] : string ; } ; } ; } export interface DevToolsUniverse { } const serialize = ( data ) => { return JSON . stringify ( data ) ; } ; const postMessage = ( message ) => { window . parent . postMessage ( serialize ( message ) , "*" ) ; } ; const plugin = createPlugin < DevToolsConfig , DevToolsUniverse , { } , { } > ( "devtools" ) ; if ( process . env . NODE_ENV !== "test" ) { const onCompleteEventFn = ( { event } ) => { const message = { destination : "devtools" , type : "completedEvent" , contents : { event } , } ; postMessage ( message ) ; } ; const updateStateAction = plugin . action ( ctx => ( { path , newValue } ) => _ . set ( ( ctx as any ) . state as any , path , newValue ) , "updateState" ) ; const initFn = ( config , universe , store ) => { if ( config . devtools ) { plugin . setProvider ( DevTools ) ; plugin . onCompleteEvent ( onCompleteEventFn ) ; const exposedUniverse = original ( universe ) ; ( store . exposedUniverseVars || [ ] ) . forEach ( ( exposedUniverseVar ) => ( exposedUniverse [ exposedUniverseVar ] = universe [ exposedUniverseVar ] ) ) ; if ( config . devtoolsServer ) { ( window as any ) . devtoolsServer = config . devtoolsServer ; } const message = { destination : "devtools" , type : "universe" , contents : { universe : exposedUniverse } , } ; postMessage ( message ) ; window . addEventListener ( "message" , event => { if ( event . data . destination === "app" ) { if ( event . data . type === "updateState" ) { store . dispatch ( updateStateAction ) ( event . data . contents ) ; } else { console . warn ( "Devtools got message with unimplemented type" , event . data ) ; } } } ) ; } } ; plugin . init ( initFn ) ; } export default plugin ;