33 Callback ,
44 Storage ,
55 Methods as ConsoleMethods ,
6- Message
6+ Message ,
77} from '../definitions/Console'
88import Methods from '../definitions/Methods'
99
@@ -12,6 +12,17 @@ import Unhook from '../Unhook'
1212import { Encode } from '../Transform'
1313// import Construct from './construct'
1414
15+ export interface HookOptions {
16+ encode ?: boolean
17+ async ?: boolean
18+ }
19+
20+ const optionsDefault : HookOptions = { encode : true , async : true }
21+
22+ function runImmediately ( f : ( ) => void ) : void {
23+ f ( )
24+ }
25+
1526/**
1627 * Hook a console constructor and forward messages to a callback
1728 * @argument console The Console constructor to Hook
@@ -20,35 +31,46 @@ import { Encode } from '../Transform'
2031export default function Hook (
2132 console : Console ,
2233 callback : Callback ,
23- encode = true
34+ optionsIn : boolean | HookOptions = true
2435) {
36+ const options : HookOptions = ( ( ) => {
37+ // Support old call style, where third argument is just `encode`
38+ if ( typeof optionsIn === 'boolean' ) {
39+ optionsIn = { encode : optionsIn }
40+ }
41+ // Set defaults
42+ optionsIn = Object . assign ( { } , optionsDefault , optionsIn )
43+ return optionsIn
44+ } ) ( )
45+
2546 const TargetConsole = console as HookedConsole
2647 const Storage : Storage = {
2748 pointers : { } ,
2849 src : {
2950 npm : 'https://npmjs.com/package/console-feed' ,
30- github : 'https://github.com/samdenty99/console-feed'
31- }
51+ github : 'https://github.com/samdenty99/console-feed' ,
52+ } ,
3253 }
3354
3455 // Override console methods
3556 for ( let method of Methods ) {
3657 const NativeMethod = TargetConsole [ method ]
3758
3859 // Override
39- TargetConsole [ method ] = function ( ) {
60+ TargetConsole [ method ] = function ( ) {
4061 // Pass back to native method
4162 NativeMethod . apply ( this , arguments )
4263
4364 // Parse arguments and send to transport
4465 const args = [ ] . slice . call ( arguments )
4566
46- // setTimeout to prevent lag
47- setTimeout ( ( ) => {
67+ // setTimeout to prevent lag, unless disabled
68+ const maybeSetTimeout = options . async ? setTimeout : runImmediately
69+ maybeSetTimeout ( ( ) => {
4870 const parsed = Parse ( method as ConsoleMethods , args )
4971 if ( parsed ) {
5072 let encoded : Message = parsed as Message
51- if ( encode ) {
73+ if ( options . encode ) {
5274 encoded = Encode ( parsed ) as Message
5375 }
5476 callback ( encoded , parsed )
0 commit comments