Class: Opal::CliRunners::MiniRacer

Inherits:
Object
  • Object
show all
Defined in:
lib/opal/cli_runners/mini_racer.rb

Class Method Summary collapse

Class Method Details

.call(data) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/opal/cli_runners/mini_racer.rb', line 9

def self.call(data)
  ::MiniRacer::Platform.set_flags! :harmony

  builder = data.fetch(:builder).call
  output = data.fetch(:output)
  # TODO: pass it
  argv = data.fetch(:argv)

  # MiniRacer doesn't like to fork. Let's build Opal first
  # in a forked environment.
  code = builder.to_s + "\n" + builder.source_map.to_data_uri_comment

  v8 = ::MiniRacer::Context.new
  v8.attach('prompt', ->(_msg = '') { $stdin.gets&.chomp })
  v8.attach('console.log', ->(i) { output.print(i); output.flush })
  v8.attach('console.warn', ->(i) { $stderr.print(i); $stderr.flush })
  v8.attach('crypto.randomBytes', method(:random_bytes).to_proc)
  v8.attach('opalminiracer.exit', ->(status) { Kernel.exit(status) })
  v8.attach('opalminiracer.argv', argv)

  v8.eval(code)
end

.random_bytes(bytes) ⇒ Object

A polyfill so that SecureRandom works in repl correctly.



33
34
35
# File 'lib/opal/cli_runners/mini_racer.rb', line 33

def self.random_bytes(bytes)
  ::SecureRandom.bytes(bytes).split('').map(&:ord)
end