github.com/kosmosJS/engine-node@v0.0.0-20220426040216-d53e2a72192e/console/module.go (about)

     1  package console
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/kosmosJS/engine"
     7  	"github.com/kosmosJS/engine-node/require"
     8  	_ "github.com/kosmosJS/engine-node/util"
     9  )
    10  
    11  type Console struct {
    12  	runtime *engine.Runtime
    13  	util    *engine.Object
    14  	printer Printer
    15  }
    16  
    17  type Printer interface {
    18  	Log(string)
    19  	Warn(string)
    20  	Error(string)
    21  }
    22  
    23  type PrinterFunc func(s string)
    24  
    25  func (p PrinterFunc) Log(s string) { p(s) }
    26  
    27  func (p PrinterFunc) Warn(s string) { p(s) }
    28  
    29  func (p PrinterFunc) Error(s string) { p(s) }
    30  
    31  var defaultPrinter Printer = PrinterFunc(func(s string) { fmt.Println(s) })
    32  
    33  func (c *Console) log(p func(string)) func(engine.FunctionCall) engine.Value {
    34  	return func(call engine.FunctionCall) engine.Value {
    35  		if format, ok := engine.AssertFunction(c.util.Get("format")); ok {
    36  			ret, err := format(c.util, call.Arguments...)
    37  			if err != nil {
    38  				panic(err)
    39  			}
    40  
    41  			p(ret.String())
    42  		} else {
    43  			panic(c.runtime.NewTypeError("util.format is not a function"))
    44  		}
    45  
    46  		return nil
    47  	}
    48  }
    49  
    50  func Require(runtime *engine.Runtime, module *engine.Object) {
    51  	requireWithPrinter(defaultPrinter)(runtime, module)
    52  }
    53  
    54  func RequireWithPrinter(printer Printer) require.ModuleLoader {
    55  	return requireWithPrinter(printer)
    56  }
    57  
    58  func requireWithPrinter(printer Printer) require.ModuleLoader {
    59  	return func(runtime *engine.Runtime, module *engine.Object) {
    60  		c := &Console{
    61  			runtime: runtime,
    62  			printer: printer,
    63  		}
    64  
    65  		c.util = require.Require(runtime, "util").(*engine.Object)
    66  
    67  		o := module.Get("exports").(*engine.Object)
    68  		o.Set("log", c.log(c.printer.Log))
    69  		o.Set("error", c.log(c.printer.Error))
    70  		o.Set("warn", c.log(c.printer.Warn))
    71  	}
    72  }
    73  
    74  func Enable(runtime *engine.Runtime) {
    75  	runtime.Set("console", require.Require(runtime, "console"))
    76  }
    77  
    78  func init() {
    79  	require.RegisterNativeModule("console", Require)
    80  }