repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/rewriters/base_spec.rb
spec/lib/rewriters/base_spec.rb
require 'lib/spec_helper' require 'support/rewriters_helper' require 'opal/rewriters/base' RSpec.describe Opal::Rewriters::Base do include RewritersHelper def body_ast_of(method_source) def_ast = parse_without_rewriting(method_source).children.first _, _, body_ast = *def_ast body_ast end let(:node) { ast_of('INJECTED') } # s(:const, nil, :INJECTED) let(:rewriter) { described_class.new } describe '#prepend_to_body' do context 'for empty body' do it 'replaces body with provided node' do body = body_ast_of('def m(a); end') rewritten = rewriter.prepend_to_body(body, node) expect(rewritten).to eq(body_ast_of('def m; INJECTED; end')) end end context 'for single-line body' do it 'prepends a node to the body and wraps it with begin; end' do body = body_ast_of('def m; 1; end') rewritten = rewriter.prepend_to_body(body, node) expect(rewritten).to eq(body_ast_of('def m; INJECTED; 1; end')) end end context 'for multi-line body' do it 'prepends a node to the body' do body = body_ast_of('def m(a); 1; 2; end') rewritten = rewriter.prepend_to_body(body, node) expect(rewritten).to eq(body_ast_of('def m; INJECTED; 1; 2; end')) end end end describe '#append_to_body' do context 'for empty body' do it 'replaces body with provided node' do body = body_ast_of('def m(a); end') rewritten = rewriter.append_to_body(body, node) expect(rewritten).to eq(body_ast_of('def m; INJECTED; end')) end end context 'for single-line body' do it 'appends a node to the body and wraps it with begin; end' do body = body_ast_of('def m(a); 1; end') rewritten = rewriter.append_to_body(body, node) expect(rewritten).to eq(body_ast_of('def m; 1; INJECTED; end')) end end context 'for multi-line body' do it 'appends a node to the body' do body = body_ast_of('def m(a); 1; 2; end') rewritten = rewriter.append_to_body(body, node) expect(rewritten).to eq(body_ast_of('def m; 1; 2; INJECTED; end')) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/rewriters/logical_operator_assignment_spec.rb
spec/lib/rewriters/logical_operator_assignment_spec.rb
require 'lib/spec_helper' require 'support/rewriters_helper' RSpec.describe Opal::Rewriters::LogicalOperatorAssignment do include RewritersHelper use_only_described_rewriter! before(:each) { Opal::Rewriters::LogicalOperatorAssignment.reset_tmp_counter! } let(:cache_tmp_name) { :$logical_op_recvr_tmp_1 } let(:cached) { s(:js_tmp, cache_tmp_name) } context 'rewriting or_asgn and and_asgn nodes' do context 'local variable' do include_examples 'it rewrites source-to-source', 'a = local; a ||= 1', 'a = local; a = a || 1' include_examples 'it rewrites source-to-source', 'a = local; a &&= 1', 'a = local; a = a && 1' end context 'instance variable' do include_examples 'it rewrites source-to-source', '@a ||= 1', '@a = @a || 1' include_examples 'it rewrites source-to-source', '@a &&= 1', '@a = @a && 1' end context 'constant' do include_examples 'it rewrites source-to-source', 'CONST ||= 1', 'CONST = defined?(CONST) ? (CONST || 1) : 1' include_examples 'it rewrites source-to-source', 'CONST &&= 1', 'CONST = CONST && 1' end context 'global variable' do include_examples 'it rewrites source-to-source', '$g ||= 1', '$g = $g || 1' include_examples 'it rewrites source-to-source', '$g &&= 1', '$g = $g && 1' end context 'class variable' do include_examples 'it rewrites source-to-source', '@@a ||= 1', '@@a = defined?(@@a) ? (@@a || 1) : 1' include_examples 'it rewrites source-to-source', '@@a &&= 1', '@@a = @@a && 1' end context 'simple method call' do include_examples 'it rewrites source-to-source', 'recvr = 1; recvr.meth ||= rhs', 'recvr = 1; recvr.meth || recvr.meth = rhs' include_examples 'it rewrites source-to-source', 'recvr = 1; recvr.meth &&= rhs', 'recvr = 1; recvr.meth && recvr.meth = rhs' end context '[] / []= method call' do include_examples 'it rewrites source-to-source', 'recvr = 1; recvr[idx] ||= rhs', 'recvr = 1; recvr[idx] || recvr[idx] = rhs' include_examples 'it rewrites source-to-source', 'recvr = 1; recvr[idx] &&= rhs', 'recvr = 1; recvr[idx] && recvr[idx] = rhs' end context '[] / []= method call with multiple arguments' do include_examples 'it rewrites source-to-source', 'recvr = 1; recvr[idx1, idx2] ||= rhs', 'recvr = 1; recvr[idx1, idx2] || recvr[idx1, idx2] = rhs' include_examples 'it rewrites source-to-source', 'recvr = 1; recvr[idx1, idx2] &&= rhs', 'recvr = 1; recvr[idx1, idx2] && recvr[idx1, idx2] = rhs' end context 'chain of method calls' do it 'rewrites ||= by caching receiver to a temporary local variable' do input = parse('recvr.a.b ||= rhs') rewritten = rewrite(input).children.first expected = s(:begin, s(:lvasgn, cache_tmp_name, ast_of('recvr.a')), # cached = recvr.a s(:or, s(:send, cached, :b), # cached.b || s(:send, cached, :b=, ast_of('rhs')))) # cached.b = rhs expect(rewritten).to eq(expected) end it 'rewrites &&= by caching receiver to a temporary local variable' do input = parse('recvr.a.b &&= rhs') rewritten = rewrite(input).children.first expected = s(:begin, s(:lvasgn, cache_tmp_name, ast_of('recvr.a')), # cached = recvr.a s(:and, s(:send, cached, :b), # cached.b || s(:send, cached, :b=, ast_of('rhs')))) # cached.b = rhs expect(rewritten).to eq(expected) end end context 'method call using safe nafigator' do it 'rewrites ||= by caching receiver and rewriting it to if and or_asgn' do input = parse('recvr&.meth ||= rhs') rewritten = rewrite(input).children.first expected = s(:begin, s(:lvasgn, cache_tmp_name, ast_of('recvr')), # cached = recvr s(:if, s(:send, cached, :nil?), # if cached.nil? s(:nil), # nil # else s(:or, s(:send, cached, :meth), # cached.meth || s(:send, cached, :meth=, ast_of('rhs'))) # cached.meth = rhs ) # end ) expect(rewritten).to eq(expected) end it 'rewrites &&= by caching receiver and rewriting it to if and or_asgn' do input = parse('recvr&.meth &&= rhs') rewritten = rewrite(input).children.first expected = s(:begin, s(:lvasgn, cache_tmp_name, ast_of('recvr')), # cached = recvr s(:if, s(:send, cached, :nil?), # if cached.nil? s(:nil), # nil # else s(:and, s(:send, cached, :meth), # cached.meth && s(:send, cached, :meth=, ast_of('rhs'))) # cached.meth = rhs ) # end ) expect(rewritten).to eq(expected) end end end context 'rewriting defined?(or_asgn) and defined?(and_asgn)' do context 'local variable' do include_examples 'it rewrites source-to-source', 'a = nil; defined?(a ||= 1)', 'a = nil; "assignment"' include_examples 'it rewrites source-to-source', 'a = nil; defined?(a &&= 1)', 'a = nil; "assignment"' end context 'instance variable' do include_examples 'it rewrites source-to-source', 'defined?(@a ||= 1)', %q("assignment") include_examples 'it rewrites source-to-source', 'defined?(@a &&= 1)', %q("assignment") end context 'constant' do include_examples 'it rewrites source-to-source', 'defined?(CONST ||= 1)', %q("assignment") include_examples 'it rewrites source-to-source', 'defined?(CONST &&= 1)', %q("assignment") end context 'global variable' do include_examples 'it rewrites source-to-source', 'defined?($g ||= 1)', %q("assignment") include_examples 'it rewrites source-to-source', 'defined?($g &&= 1)', %q("assignment") end context 'class variable' do include_examples 'it rewrites source-to-source', 'defined?(@@a ||= 1)', %q("assignment") include_examples 'it rewrites source-to-source', 'defined?(@@a &&= 1)', %q("assignment") end context 'simple method call' do include_examples 'it rewrites source-to-source', 'defined?(recvr.meth ||= rhs)', %q("assignment") include_examples 'it rewrites source-to-source', 'defined?(recvr.meth &&= rhs)', %q("assignment") end context '[] / []= method call' do include_examples 'it rewrites source-to-source', 'defined?(recvr[idx] ||= rhs)', %q("assignment") include_examples 'it rewrites source-to-source', 'defined?(recvr[idx] &&= rhs)', %q("assignment") end context '[] / []= method call with multiple arguments' do include_examples 'it rewrites source-to-source', 'defined?(recvr[idx1, idx2] ||= rhs)', %q("assignment") include_examples 'it rewrites source-to-source', 'defined?(recvr[idx1, idx2] &&= rhs)', %q("assignment") end context 'chain of method calls' do include_examples 'it rewrites source-to-source', 'defined?(recvr.a.b.c ||= rhs)', %q("assignment") include_examples 'it rewrites source-to-source', 'defined?(recvr.a.b.c &&= rhs)', %q("assignment") end context 'method call using safe nafigator' do include_examples 'it rewrites source-to-source', 'defined?(recvr&.meth ||= rhs)', %q("assignment") include_examples 'it rewrites source-to-source', 'defined?(recvr&.meth &&= rhs)', %q("assignment") end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/rewriters/hashes/key_duplicates_rewriter_spec.rb
spec/lib/rewriters/hashes/key_duplicates_rewriter_spec.rb
require 'lib/spec_helper' require 'support/rewriters_helper' require 'opal/rewriters/hashes/key_duplicates_rewriter' RSpec.describe Opal::Rewriters::Hashes::KeyDuplicatesRewriter do include RewritersHelper shared_examples 'it warns' do |code, key_to_warn| context "for #{code} code" do it "warns about #{key_to_warn.inspect} being overwritten" do expect(Kernel).to receive(:warn).with("warning: key #{key_to_warn.inspect} is duplicated and overwritten") { nil } ast = parse_without_rewriting(code) rewrite(ast) end end end include_examples 'it warns', '{ a: 1, a: 2 }', :a include_examples 'it warns', '{ a: 1, **{ a: 2 } }', :a include_examples 'it warns', '{ a: 1, **{ **{ a: 2 } } }', :a include_examples 'it warns', '{ "a" => 1, "a" => 2 }', 'a' include_examples 'it warns', '{ "a" => 1, **{ "a" => 2 } }', 'a' include_examples 'it warns', '{ "a" => 1, **{ **{ "a" => 2 } } }', 'a' shared_examples 'it does not warn' do |code| context "for #{code} code" do it "does not warn anything" do expect(Kernel).to_not receive(:warn).with(/is duplicated and overwritten/) ast = parse_without_rewriting(code) rewrite(ast) end end end include_examples 'it does not warn', '{ a: 1 }' include_examples 'it does not warn', '{ a: 1, "a" => 2 }' include_examples 'it does not warn', '{ "a" => 1, a: 2 }' include_examples 'it does not warn', '{ a: 1, **{ "a" => 2 } }' include_examples 'it does not warn', '{ "a" => 1, **{ a: 2 } }' include_examples 'it does not warn', '{ a: 1, nested: { a: 2 } }' include_examples 'it does not warn', 'key = "key"; { "#{key}" => 1, "#{key}" => 2 }' include_examples 'it does not warn', 'key = "key"; { :"#{key}" => 1, :"#{key}" => 2 }' end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/rewriters/rubyspec/filters_rewriter_spec.rb
spec/lib/rewriters/rubyspec/filters_rewriter_spec.rb
require 'lib/spec_helper' require 'opal/rewriters/rubyspec/filters_rewriter' require 'support/rewriters_helper' RSpec.describe Opal::Rubyspec::FiltersRewriter do include RewritersHelper let(:source) do <<-SOURCE describe 'User#email' do context 'when this' do it 'does that' it 'and does that' do 42 end end it 'also does something else' end SOURCE end let(:ast) { parse(source) } context 'when spec is filtered' do around(:each) do |e| Opal::Rubyspec::FiltersRewriter.filter 'User#email when this does that' Opal::Rubyspec::FiltersRewriter.filter 'User#email when this and does that' e.run Opal::Rubyspec::FiltersRewriter.clear_filters! end let(:rewritten_source) do <<-SOURCE describe 'User#email' do context 'when this' do nil # <- right here nil # <- and here end it 'also does something else' end SOURCE end let(:expected_ast) { parse(rewritten_source) } it 'replaces it with nil' do expect_rewritten(ast).to eq(expected_ast) end it 'disables cache' do expect(rewritten(ast).meta[:dynamic_cache_result]).to be_truthy end end context 'when spec is not filtered' do it 'does not rewrite it' do expect_no_rewriting_for(ast) end it 'disables cache' do expect(rewritten(ast).meta[:dynamic_cache_result]).to be_truthy end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/cli_runners/server_spec.rb
spec/lib/cli_runners/server_spec.rb
require 'lib/spec_helper' require 'opal/cli_runners' require 'rack/test' RSpec.describe Opal::CliRunners::Server do include Rack::Test::Methods def app @app end it 'starts a server for the given code' do expect(Rack::Server).to receive(:start) do |options| @app = options[:app] expect(options[:Port]).to eq(1234) end builder = -> { Opal::Builder.new.build_str("puts 123", "app.rb") } described_class.call(builder: builder, options: {port: 1234}) get '/assets/cli_runner.js' expect(last_response.body).to include(".$puts(123)") end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/builder/post_processor_spec.rb
spec/lib/builder/post_processor_spec.rb
require 'lib/spec_helper' require 'opal/os' require 'opal/builder' require 'opal/builder/scheduler/sequential' require 'opal/builder/scheduler/threaded' require 'opal/fragment' require 'tmpdir' RSpec.describe Opal::Builder::PostProcessor do subject(:builder) { Opal::Builder.new(options) } let(:options) { {compiler_options: {cache_fragments: true}} } let(:postprocessors) { body = postprocessor_body Class.new(described_class) { define_method(:call, &body) } } around(:example) do |example| described_class.with_postprocessors(postprocessors, &example) end context "with a capturing postprocessor" do scratchpad = nil let(:postprocessor_body) {-> { scratchpad << [processed, builder] processed }} it "has an access to both processed and builder" do scratchpad = [] builder.build_str("require 'opal'", "(sample)").to_s scratchpad.length.should be 1 first = scratchpad.first first[0].should be_a Array first[1].should be builder first[0].each { |i| i.should be_a Opal::Builder::Processor } end end context "with a replacing postprocessor" do let(:postprocessor_body) {-> { [ Opal::Builder::Processor::JsProcessor.new("Replaced!", "replaced.js") ] }} it "replaces everything in all result and source map" do b = builder.build_str("require 'opal'", "(sample)") b.to_s.should start_with "Replaced!" b.source_map.to_s.should include "Replaced!" end end context "with a fragment replacing postprocessor" do let(:postprocessor_body) {-> { processed.each do |file| if file.respond_to? :compiled compiler = file.compiled compiler.fragments = compiler.fragments.map do |frag| if frag.is_a? Opal::Fragment Opal::Fragment.new("Badger", frag.scope, frag.sexp) end end.compact end end }} it "replaces fragments correctly" do b = builder.build_str("require 'opal'", "(sample)") b.to_s.should include "Badger" * 1000 # TODO: Test the source map integrity? end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/builder/post_processor/dce_spec.rb
spec/lib/builder/post_processor/dce_spec.rb
require 'lib/spec_helper' require 'opal/builder' RSpec.describe Opal::Builder::PostProcessor::DCE do let(:builder) { Opal::Builder.new(compiler_options: {cache_fragments: true}, dce: dce_types) } def build(code) builder.build_str(code, 'input.rb').to_s end context "when dce removes unused instance methods" do let(:dce_types) { [:method] } it "strips methods that are never referenced" do output = build(<<~'RUBY') class Foo def used; 1; end def unused; 2; end end Foo.new.used RUBY expect(output).to include("$def(self, '$used'") expect(output).not_to include("$def(self, '$unused'") expect(output).to include("Removed by DCE: unused") end end context "when constant DCE is enabled" do let(:dce_types) { [:const] } it "strips unused constant definitions" do output = build(<<~'RUBY') module M VALUE = 123 end RUBY expect(output).to include("Removed by DCE: M") expect(output).not_to include("VALUE") end end context "when constant DCE is disabled" do let(:dce_types) { [:method] } it "keeps constants intact" do output = build(<<~'RUBY') module M VALUE = 123 end RUBY expect(output).to include("VALUE") expect(output).not_to include("Removed by DCE") end end context "when using attr_* helpers" do let(:dce_types) { [:method] } it "removes generated readers/writers when unused" do output = build(<<~'RUBY') class Foo attr_accessor :bar end RUBY expect(output).to include("Removed by DCE: [:bar, :bar=]") expect(output).not_to include("$def(self, '$bar'") end end context "with alias_method" do let(:dce_types) { [:method] } it "keeps aliased methods when the alias is used" do output = build(<<~'RUBY') class Foo def bar; 1; end alias_method :baz, :bar baz end RUBY expect(output).to include("$def(self, '$bar'") expect(output).to include("alias_method") expect(output).not_to include("Removed by DCE: bar") end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/source_location_test.rb
spec/lib/fixtures/source_location_test.rb
# Do not move this method # This file is used to test Method#source_location def m end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/sprockets_file.js.rb
spec/lib/fixtures/sprockets_file.js.rb
require 'opal' require 'native' puts 'sprockets!'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/no_requires.rb
spec/lib/fixtures/no_requires.rb
puts 'hi there'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/opal_file.rb
spec/lib/fixtures/opal_file.rb
require 'opal' puts 'hi from opal!'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/requires.rb
spec/lib/fixtures/requires.rb
require 'foo' puts 'hello' require 'bar' puts 'goodbye'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/build_order.rb
spec/lib/fixtures/build_order.rb
# This fixture tests build order of required JS files require 'fixtures/build_order/file1' require 'fixtures/build_order/file2' require 'fixtures/build_order/file3' require 'fixtures/build_order/file4' require 'fixtures/build_order/file5' require 'fixtures/build_order/file6' require 'fixtures/build_order/file7'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/sprockets_require_tree_test.rb
spec/lib/fixtures/sprockets_require_tree_test.rb
#=require_tree ./required_tree_test puts 5
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/source_map.rb
spec/lib/fixtures/source_map.rb
puts 'smap!'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/require_tree_test.rb
spec/lib/fixtures/require_tree_test.rb
require_tree '../fixtures/required_tree_test' puts 5
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/project/p1/test.rb
spec/lib/fixtures/project/p1/test.rb
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/project/p3/require_from_p3.rb
spec/lib/fixtures/project/p3/require_from_p3.rb
def require_from_p3_working? true end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/build_order/file63.rb
spec/lib/fixtures/build_order/file63.rb
# A circular require require_relative 'file62' FILE_63 = true
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/build_order/file61.rb
spec/lib/fixtures/build_order/file61.rb
FILE_61 = true
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/build_order/file64.rb
spec/lib/fixtures/build_order/file64.rb
FILE_64 = true
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/build_order/file6.rb
spec/lib/fixtures/build_order/file6.rb
require_relative 'file61' # There's a circular require between file63 and 62 # file62 should be in output file before 63 require 'fixtures/build_order/file63' require_relative './file62' require 'fixtures/build_order/file64.rb' FILE_6 = true
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/build_order/file7.rb
spec/lib/fixtures/build_order/file7.rb
FILE_7 = true
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/build_order/file62.rb
spec/lib/fixtures/build_order/file62.rb
# A circular require require_relative 'file63' FILE_62 = true
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/required_tree_test/required_file1.rb
spec/lib/fixtures/required_tree_test/required_file1.rb
p 1
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/required_tree_test/required_file2.rb
spec/lib/fixtures/required_tree_test/required_file2.rb
p 2
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/fixtures/source_map/subfolder/other_file.rb
spec/lib/fixtures/source_map/subfolder/other_file.rb
puts 'other!'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/source_map/file_spec.rb
spec/lib/source_map/file_spec.rb
require 'support/source_map_helper' RSpec.describe Opal::SourceMap::File do include SourceMapHelper specify '#as_json' do map = described_class.new([fragment(code: "foo")], 'foo.rb', "foo") expect(map.as_json).to be_a(Hash) expect(map.as_json(ignored: :options)).to be_a(Hash) end it 'correctly map generated code to original positions' do fragments = [ # It doesn't matter too much to keep these fragments updated in terms of generated code, # as long as it works as real-world usage. fragment(line: nil, column: nil, source_map_name: nil, code: "/* Generated by Opal 0.11.1.dev */", sexp_type: :top), fragment(line: nil, column: nil, source_map_name: nil, code: "\n", sexp_type: :top), fragment(line: nil, column: nil, source_map_name: nil, code: "(function(Opal) {", sexp_type: :top), fragment(line: nil, column: nil, source_map_name: nil, code: "\n ", sexp_type: :top), fragment(line: nil, column: nil, source_map_name: nil, code: "var self = Opal.top, $nesting = [], nil = Opal.nil, $$$ = Opal.$$$, $$ = Opal.$$, $breaker = Opal.breaker, $slice = Opal.slice;\n", sexp_type: :top), fragment(line: nil, column: nil, source_map_name: nil, code: "\n ", sexp_type: :top), fragment(line: nil, column: nil, source_map_name: nil, code: "Opal.add_stubs('puts');", sexp_type: :top), fragment(line: nil, column: nil, source_map_name: nil, code: "\n ", sexp_type: :top), fragment(line: 1, column: 0, source_map_name: nil, code: "\n ", sexp_type: :begin), fragment(line: nil, column: nil, source_map_name: "self", code: "self", sexp_type: :self), fragment(line: 1, column: 0, source_map_name: :puts, code: ".$puts", sexp_type: :send), fragment(line: 1, column: 0, source_map_name: :puts, code: "(", sexp_type: :send), fragment(line: 1, column: 5, source_map_name: "5", code: "5", sexp_type: :int), fragment(line: 1, column: 0, source_map_name: :puts, code: ")", sexp_type: :send), fragment(line: 1, column: 0, source_map_name: nil, code: ";", sexp_type: :begin), fragment(line: 1, column: 0, source_map_name: nil, code: "\n ", sexp_type: :begin), fragment(line: 3, column: 0, source_map_name: nil, code: "return ", sexp_type: :js_return), fragment(line: nil, column: nil, source_map_name: "self", code: "self", sexp_type: :self), fragment(line: 3, column: 0, source_map_name: :puts, code: ".$puts", sexp_type: :send), fragment(line: 3, column: 0, source_map_name: :puts, code: "(", sexp_type: :send), fragment(line: 3, column: 5, source_map_name: "6", code: "6", sexp_type: :int), fragment(line: 3, column: 0, source_map_name: :puts, code: ")", sexp_type: :send), fragment(line: 1, column: 0, source_map_name: nil, code: ";", sexp_type: :begin), fragment(line: nil, column: nil, source_map_name: nil, code: "\n", sexp_type: :top), fragment(line: nil, column: nil, source_map_name: nil, code: "})(Opal);\n", sexp_type: :top), fragment(line: nil, column: nil, source_map_name: nil, code: "\n", sexp_type: :newline), ] subject = described_class.new(fragments, 'foo.rb', "puts 5\n\nputs 6") generated_code = subject.generated_code expect(subject.map.merge(mappings: nil)).to eq( version: 3, sourceRoot: '', sources: ['foo.rb'], sourcesContent: ["puts 5\n\nputs 6"], names: ['self', 'puts', '5', '6'], mappings: nil, ) expect('$puts(5)').to be_at_line_and_column(6, 7, source: generated_code) expect('$puts(5)').to be_at_line_and_column(6, 7, source: generated_code) expect('5' ).to be_at_line_and_column(6, 13, source: generated_code) expect('$puts(6)').to be_at_line_and_column(7, 14, source: generated_code) expect('6' ).to be_at_line_and_column(7, 20, source: generated_code) expect('puts(5)').to be_mapped_to_line_and_column(0, 0, map: subject, source: generated_code, file: 'foo.rb') expect('5);' ).to be_mapped_to_line_and_column(0, 5, map: subject, source: generated_code, file: 'foo.rb') expect('puts(6)').to be_mapped_to_line_and_column(2, 0, map: subject, source: generated_code, file: 'foo.rb') expect('6);' ).to be_mapped_to_line_and_column(2, 5, map: subject, source: generated_code, file: 'foo.rb') end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/lib/source_map/index_spec.rb
spec/lib/source_map/index_spec.rb
require 'support/source_map_helper' RSpec.describe Opal::SourceMap::Index do include SourceMapHelper specify '#as_json' do builder = Opal::Builder.new builder.build_str('foo', 'bar.rb') map = builder.source_map expect(map.as_json).to be_a(Hash) expect(map.as_json(ignored: :options)).to be_a(Hash) end let(:builder) do builder = Opal::Builder.new builder.build_str( " jsline1();\n"+ " jsline2();\n"+ " jsline3();", 'js_file.js' ) builder.build_str( " rbline1\n"+ " rbline2\n"+ " rbline3", 'rb_file.rb' ) builder.build_str( "\n"+ "\n"+ "\n"+ " jsline4();\n"+ " jsline5();\n"+ " jsline6();", 'js2_file.js' ) builder.build_str( "\n"+ "\n"+ "\n"+ " rbline4\n"+ " rbline5\n"+ " rbline6", 'rb2_file.rb' ) builder end let(:compiled) { builder.to_s } let(:source_map) { builder.source_map } let(:mappings) { source_map.send(:mappings) } it 'points to the correct source line' do # To debug this stuff can be useful to print out all # the sources with #inspect_source: # # p :compiled # inspect_source compiled # # p :generated_code # source_map.source_maps.each do |sub_source_map| # p generated_code: sub_source_map.file # inspect_source sub_source_map.generated_code # end # expect('jsline1(').to be_mapped_to_line_and_column(0, 4, file: 'js_file.js', map: source_map, source: compiled) expect('jsline2(').to be_mapped_to_line_and_column(1, 4, file: 'js_file.js', map: source_map, source: compiled) expect('jsline3(').to be_mapped_to_line_and_column(2, 4, file: 'js_file.js', map: source_map, source: compiled) expect('$rbline1(').to be_mapped_to_line_and_column(0, 2, file: 'rb_file.rb', map: source_map, source: compiled) expect('$rbline2(').to be_mapped_to_line_and_column(1, 2, file: 'rb_file.rb', map: source_map, source: compiled) expect('$rbline3(').to be_mapped_to_line_and_column(2, 2, file: 'rb_file.rb', map: source_map, source: compiled) expect('jsline4(').to be_mapped_to_line_and_column(3, 4, file: 'js2_file.js', map: source_map, source: compiled) expect('jsline5(').to be_mapped_to_line_and_column(4, 4, file: 'js2_file.js', map: source_map, source: compiled) expect('jsline6(').to be_mapped_to_line_and_column(5, 4, file: 'js2_file.js', map: source_map, source: compiled) expect('$rbline4(').to be_mapped_to_line_and_column(3, 2, file: 'rb2_file.rb', map: source_map, source: compiled) expect('$rbline5(').to be_mapped_to_line_and_column(4, 2, file: 'rb2_file.rb', map: source_map, source: compiled) expect('$rbline6(').to be_mapped_to_line_and_column(5, 2, file: 'rb2_file.rb', map: source_map, source: compiled) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/examples/rack-esm/app/application.rb
examples/rack-esm/app/application.rb
require 'opal' require 'user' require 'opal/platform' module MyApp class Application def initialize @user = User.new('Bob') end def title "#{@user.name} is #{:not unless @user.authenticated?} authenticated" end end end $app = MyApp::Application.new require 'native' $$[:document][:title] = "#{$app.title}" bill = User.new('Bill') $$.alert "The user is named #{bill.name}." bill.authenticated?
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/examples/rack-esm/app/user.rb
examples/rack-esm/app/user.rb
class User def initialize(name) puts "wow" @name = name end attr_reader :name def authenticated? if admin? or special_permission? true else raise "not authenticated" end end def admin? @name == 'Bob' end def special_permission? false end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/examples/rack/app/application.rb
examples/rack/app/application.rb
require 'opal' require 'user' require 'opal/platform' module MyApp class Application def initialize @user = User.new('Bob') end def title "#{@user.name} is #{:not unless @user.authenticated?} authenticated" end end end $app = MyApp::Application.new require 'native' $$[:document][:title] = "#{$app.title}" bill = User.new('Bill') $$.alert "The user is named #{bill.name}." bill.authenticated?
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/examples/rack/app/user.rb
examples/rack/app/user.rb
class User def initialize(name) puts "wow" @name = name end attr_reader :name def authenticated? if admin? or special_permission? true else raise "not authenticated" end end def admin? @name == 'Bob' end def special_permission? false end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/examples/sinatra/app/application.rb
examples/sinatra/app/application.rb
require 'opal' def alert(msg) `alert(msg)` raise "an example exception with source-map powered backtrace" end alert "Hi there!"
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/examples/exe/simple.rb
examples/exe/simple.rb
puts "It works! Very cool app!"
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal.rb
lib/opal.rb
# frozen_string_literal: true require 'opal/requires'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/tilt/opal.rb
lib/tilt/opal.rb
# frozen_string_literal: true require 'tilt' require 'opal/builder' require 'opal/config' require 'opal/version' module Opal class TiltTemplate < Tilt::Template self.default_mime_type = 'application/javascript' def self.inherited(subclass) subclass.default_mime_type = 'application/javascript' end def self.engine_initialized? true end def self.version ::Opal::VERSION end def self.compiler_options Opal::Config.compiler_options.merge(requirable: true) end def initialize_engine require_template_library 'opal' end def prepare # stub end def evaluate(_scope, _locals) if builder = @options[:builder] builder.dup.build(file).to_s elsif @options[:build] Opal::Builder.build(file).to_s else compiler_options = (compiler_options || {}).merge!(file: file) compiler = Compiler.new(data, compiler_options) compiler.compile.to_s end end def compiler_options self.class.compiler_options end end end Tilt.register 'rb', Opal::TiltTemplate Tilt.register 'opal', Opal::TiltTemplate
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/path_reader.rb
lib/opal/path_reader.rb
# frozen_string_literal: true require 'opal/regexp_anchors' require 'opal/hike' module Opal class PathReader RELATIVE_PATH_REGEXP = /#{Opal::REGEXP_START}\.?\.#{Regexp.quote File::SEPARATOR}/.freeze DEFAULT_EXTENSIONS = ['.js', '.js.rb', '.rb', '.opalerb'].freeze def initialize(paths = Opal.paths, extensions = DEFAULT_EXTENSIONS) @file_finder = Hike::Trail.new @file_finder.append_paths(*paths) @file_finder.append_extensions(*extensions) end def read(path) full_path = expand(path) return nil if full_path.nil? File.open(full_path, 'rb:UTF-8', &:read) if File.exist?(full_path) end def expand(path) if Pathname.new(path).absolute? || path =~ RELATIVE_PATH_REGEXP path else find_path(path) end end def paths file_finder.paths end def extensions file_finder.extensions end def append_paths(*paths) file_finder.append_paths(*paths) end private def find_path(path) pathname = Pathname(path) return path if pathname.absolute? && pathname.exist? file_finder.find(path) end attr_reader :file_finder end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/regexp_anchors.rb
lib/opal/regexp_anchors.rb
# frozen_string_literal: true module Opal # rubocop:disable Style/MutableConstant self::REGEXP_START = '\A' self::REGEXP_END = '\z' # Unicode characters in ranges # \u0001 - \u002F (blank unicode characters + space + !"#$%&'()*+,-./ chars) # \u003A - \u0040 (:;<=>?@ chars) # \u005B - \u005E ([\]^ chars) # \u0060 (` char) # \u007B - \u007F ({|}~ chars}) # are not allowed to be used in identifier in the beggining or middle of its name self::FORBIDDEN_STARTING_IDENTIFIER_CHARS = '\u0001-\u002F\u003A-\u0040\u005B-\u005E\u0060\u007B-\u007F' # A map of some Ruby regexp patterns to their JS representations self::REGEXP_EQUIVALENTS = { '\h' => '[\dA-Fa-f]', '\H' => '[^\dA-Fa-f]', '\e' => '\x1b', # Invalid cases in JS Unicode mode '\_' => '_', '\~' => '~', '\#' => '#', '\\\'' => "'", '\"' => '"', '\ ' => ' ', '\=' => '=', '\!' => '!', '\%' => '%', '\&' => '&', '\<' => '<', '\>' => '>', '\@' => '@', '\:' => ':', '\`' => '`', # POSIX classes '[:alnum:]' => '\p{Alphabetic}\p{Number}', # Alphanumeric characters '[:alpha:]' => '\p{Alphabetic}', # Alphabetic characters '[:blank:]' => '\p{Space_Separator}\t', # Space and tab '[:cntrl:]' => '\p{Control}', # Control characters '[:digit:]' => '\d', # Digits '[:graph:]' => '\p{Alphabetic}\p{Number}\p{Punctuation}\p{Symbol}', # Visible characters '[:lower:]' => '\p{Lowercase_Letter}', # Lowercase letters '[:print:]' => '\p{Alphabetic}\p{Number}\p{Punctuation}\p{Symbol}\p{Space_Separator}', # Visible characters and spaces '[:punct:]' => '\p{Punctuation}', # Punctuation characters '[:space:]' => '\p{White_Space}', # Whitespace characters '[:upper:]' => '\p{Uppercase_Letter}', # Uppercase letters '[:xdigit:]' => '\dA-Fa-f', # Hexadecimal digits } # A map of some Ruby regexp patterns to their JS representations, but this set of # representations is only applied outside of `[` and `]`. self::REGEXP_EQUIVALENTS_OUTSIDE = { '\A' => '^', '\z' => '$', '\Z' => '(?:\n?$)', '\-' => '-', '\R' => '(?:\r|\n|\r\n|\f|\u0085|\u2028|\u2029)', } # Unicode characters in ranges # \u0001 - \u0020 (blank unicode characters + space) # \u0022 - \u002F ("#$%&'()*+,-./ chars) # \u003A - \u003E (:;<=> chars) # \u0040 (@ char) # \u005B - \u005E ([\]^ chars) # \u0060 (` char) # \u007B - \u007F ({|}~ chars}) # are not allowed to be used in identifier in the end of its name # In fact, FORBIDDEN_STARTING_IDENTIFIER_CHARS = FORBIDDEN_ENDING_IDENTIFIER_CHARS + \u0021 ('?') + \u003F ('!') self::FORBIDDEN_ENDING_IDENTIFIER_CHARS = '\u0001-\u0020\u0022-\u002F\u003A-\u003E\u0040\u005B-\u005E\u0060\u007B-\u007F' self::INLINE_IDENTIFIER_REGEXP = Regexp.new("[^#{self::FORBIDDEN_STARTING_IDENTIFIER_CHARS}]*[^#{self::FORBIDDEN_ENDING_IDENTIFIER_CHARS}]") # For constants rules are pretty much the same, but ':' is allowed and '?!' are not. # Plus it may start with a '::' which indicates that the constant comes from toplevel. self::FORBIDDEN_CONST_NAME_CHARS = '\u0001-\u0020\u0021-\u002F\u003B-\u003F\u0040\u005B-\u005E\u0060\u007B-\u007F' self::CONST_NAME_REGEXP = Regexp.new("#{self::REGEXP_START}(::)?[A-Z][^#{self::FORBIDDEN_CONST_NAME_CHARS}]*#{self::REGEXP_END}") # rubocop:enable Style/MutableConstant end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/version.rb
lib/opal/version.rb
# frozen_string_literal: true module Opal # WHEN RELEASING: # Remember to update RUBY_ENGINE_VERSION in opal/corelib/constants.rb too! VERSION = '2.0.0dev' # Only major and minor parts of version VERSION_MAJOR_MINOR = VERSION.split('.').first(2).join('.').freeze end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/project.rb
lib/opal/project.rb
# frozen_string_literal: true module Opal # Opal::Project is a representation of an Opal project. In particular # it's a directory containing Ruby files which is described by Opalfile. class Project # DSL for Opal::Project class Opalfile def initialize(project) @project = project yield self if block_given? end attr_reader :project def add_load_path(*load_paths) # Make relative paths absolute based on Opalfile's location load_paths = load_paths.map do |i| if File.absolute_path?(i) i else File.realpath(i, project.root_dir) end end project.collection.append_paths(*load_paths) end alias add_load_paths add_load_path def add_gem_dependency(name) project.collection.use_gem(name) end def method_missing(method, *, **) raise OpalfileUnknownDirective, "unknown directive #{method} in Opalfile" end def respond_to_missing?(_method, *) false end end # A mixin for methods that are used to extend either global (Opal) or local # (Opal::Builder instance) to contain a collection of projects. module Collection def all_projects if self == Opal projects else Opal.projects + projects end end def projects @projects ||= [] end def has_project?(root_dir) all_projects.any? { |i| i.root_dir == root_dir } end def project_of(root_dir) all_projects.find { |i| i.root_dir == root_dir } end def add_project(project) projects << project end def setup_project(file) Project.setup_project_for(self, file) end # Adds the "require_paths" (usually `lib/`) of gem with the given name to # Opal paths. By default will include the "require_paths" from all the # dependent gems. # # @param gem_name [String] the name of the gem # @param include_dependencies [Boolean] whether or not to add recursively # the gem's dependencies # @raise [Opal::GemNotFound] # if gem or any of its runtime dependencies not found def use_gem(gem_name, include_dependencies = true) if RUBY_ENGINE == 'opal' warn "Opal: paths for gems are not available in JavaScript. The directive `use_gem #{gem_name}` has been ignored." else append_paths(*require_paths_for_gem(gem_name, include_dependencies)) end end private def require_paths_for_gem(gem_name, include_dependencies) paths = [] spec = Gem::Specification.find_by_name(gem_name) raise GemNotFound, gem_name unless spec project = setup_project(spec.gem_dir) # If a project is found and it contains an Opalfile, use directives in # Opalfile. The dependencies will be resolved via Opalfile resolution. if project&.has_opalfile? [] else if include_dependencies spec.runtime_dependencies.each do |dependency| paths += require_paths_for_gem(dependency.name, include_dependencies) end end gem_dir = spec.gem_dir spec.require_paths.map do |path| if File.absolute_path? path paths << path else paths << File.join(gem_dir, path) end end paths end end end def initialize(root_dir, collection) @root_dir = root_dir @collection = collection collection.add_project(self) parse_opalfile end attr_reader :root_dir, :collection def has_opalfile? @has_opalfile end def parse_opalfile opalfile_path = "#{@root_dir}/Opalfile" if File.exist?(opalfile_path) opalfile = File.read(opalfile_path) Opalfile.new(self) do |dsl| dsl.instance_eval(opalfile, opalfile_path, 1) end @has_opalfile = true end end @loading = [] def self.setup_project_for(collection, file) root_dir = locate_root_dir(file) return collection.project_of(root_dir) if collection.has_project?(root_dir) return nil unless root_dir return nil if @loading.include? root_dir Project.new(root_dir, collection) end # Finds the project's root directory by searching for a project-defining file in # the given file's ancestor directories. # # A project-defining file is one of the files in the PROJECT_DEFINING_FILES constant. # # @param file [String] The starting file path for the search. # @return [String, nil] The path to the root directory, or nil if not found or # the file does not exist. def self.locate_root_dir(file) begin file = File.realpath(file) rescue Errno::ENOENT return nil end current_dir = file until dir_is_project_candidate? current_dir parent_dir = File.dirname(current_dir) # If no further parent, stop the search. # In addition, stop progressing if we hit a directory called "vendor". # This is a special case - some users are installing gem dependencies # inside a vendor directory in a standalone project. We don't want both # to be conflated, as then the gem's load paths may not be registered. break if current_dir == parent_dir || File.basename(current_dir) == 'vendor' current_dir = parent_dir end if dir_is_project_candidate? current_dir current_dir end end PROJECT_DEFINING_FILES = %w[Opalfile Gemfile *.gemspec].freeze @glob_cache = {} def self.dir_is_project_candidate?(current_dir) @glob_cache[current_dir] ||= Dir[File.join(current_dir, "{#{PROJECT_DEFINING_FILES.join(',')}}")] @glob_cache[current_dir].any? end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/compiler.rb
lib/opal/compiler.rb
# frozen_string_literal: true if RUBY_ENGINE == 'opal' require 'corelib/string/unpack' end require 'set' require 'opal/parser' require 'opal/fragment' require 'opal/nodes' require 'opal/eof_content' require 'opal/errors' require 'opal/magic_comments' require 'opal/nodes/closure' require 'opal/source_map' module Opal # Compile a string of ruby code into javascript. # # @example # # Opal.compile "ruby_code" # # => "string of javascript code" # # @see Opal::Compiler.new for compiler options # # @param source [String] ruby source # @param options [Hash] compiler options # @return [String] javascript code # def self.compile(source, options = {}) Compiler.new(source, options).compile end singleton_class.alias_method :opal_compile, :compile # {Opal::Compiler} is the main class used to compile ruby to javascript code. # This class uses {Opal::Parser} to gather the sexp syntax tree for the ruby # code, and then uses {Opal::Node} to step through the sexp to generate valid # javascript. # # @example # Opal::Compiler.new("ruby code").compile # # => "javascript code" # # @example Accessing result # compiler = Opal::Compiler.new("ruby_code") # compiler.compile # compiler.result # => "javascript code" # # @example Source Maps # compiler = Opal::Compiler.new("") # compiler.compile # compiler.source_map # => #<SourceMap:> # class Compiler include Nodes::Closure::CompilerSupport # Generated code gets indented with two spaces on each scope INDENT = ' ' # All compare method nodes - used to optimize performance of # math comparisons COMPARE = %w[< > <= >=].freeze def self.module_name(path) path = File.join(File.dirname(path), File.basename(path).split('.').first) Pathname(path).cleanpath.to_s end # Defines a compiler option. # @option as: [Symbol] uses a different method name, e.g. with a question mark for booleans # @option default: [Object] the default value for the option # @option magic_comment: [Bool] allows magic-comments to override the option value def self.compiler_option(name, config = {}) method_name = config.fetch(:as, name) define_method(method_name) { option_value(name, config) } end # Fetches and memoizes the value for an option. def option_value(name, config) return @option_values[name] if @option_values.key? name default_value = config[:default] valid_values = config[:valid_values] magic_comment = config[:magic_comment] value = @options.fetch(name, default_value) if magic_comment && @magic_comments.key?(name) value = @magic_comments.fetch(name) end if valid_values && !valid_values.include?(value) raise( ArgumentError, "invalid value #{value.inspect} for option #{name.inspect} " \ "(valid values: #{valid_values.inspect})" ) end @option_values[name] = value end # @!method file # # The filename to use for compiling this code. Used for __FILE__ directives # as well as finding relative require() # # @return [String] compiler_option :file, default: '(file)' # @!method method_missing? # # adds method stubs for all used methods in file # # @return [Boolean] compiler_option :method_missing, default: true, as: :method_missing? # @!method arity_check? # # adds an arity check to every method definition # # @return [Boolean] compiler_option :arity_check, default: false, as: :arity_check? # @deprecated # @!method freezing? # # stubs out #freeze and #frozen? # # @return [Boolean] compiler_option :freezing, default: true, as: :freezing? # @!method irb? # # compile top level local vars with support for irb style vars compiler_option :irb, default: false, as: :irb? # @!method dynamic_require_severity # # how to handle dynamic requires (:error, :warning, :ignore) compiler_option :dynamic_require_severity, default: :ignore, valid_values: %i[error warning ignore] # @!method requirable? # # Prepare the code for future requires compiler_option :requirable, default: false, as: :requirable? # @!method load? # # Instantly load a requirable module compiler_option :load, default: false, as: :load? # @!method esm? # # Encourage ESM semantics, eg. exporting run result compiler_option :esm, default: false, as: :esm? # @!method no_export? # # Don't export this compile, even if ESM mode is enabled. We use # this internally in CLI, so that even if ESM output is desired, # we would only have one default export. compiler_option :no_export, default: false, as: :no_export? # @!method inline_operators? # # are operators compiled inline compiler_option :inline_operators, default: true, as: :inline_operators? compiler_option :eval, default: false, as: :eval? # @!method enable_source_location? # # Adds source_location for every method definition compiler_option :enable_source_location, default: false, as: :enable_source_location? # @!method enable_file_source_embed? # # Embeds source code along compiled files compiler_option :enable_file_source_embed, default: false, as: :enable_file_source_embed? # @!method use_strict? # # Enables JavaScript's strict mode (i.e., adds 'use strict'; statement) compiler_option :use_strict, default: false, as: :use_strict?, magic_comment: true # @!method directory? # # Builds a JavaScript file that is aimed to reside as part of a directory # for an import map build or something similar. compiler_option :directory, default: false, as: :directory? # @!method parse_comments? # # Adds comments for every method definition compiler_option :parse_comments, default: false, as: :parse_comments? # @!method backtick_javascript? # # Allows use of a backtick operator (and `%x{}`) to embed verbatim JavaScript. # If false, backtick operator will compiler_option :backtick_javascript, default: nil, as: :backtick_javascript?, magic_comment: true # @!method runtime_mode? # # Generates code for runtime use, only suitable for early runtime functions. compiler_option :opal_runtime_mode, default: false, as: :runtime_mode?, magic_comment: true # @!method cache_fragments? # # Caches fragments. This enables postprocessing, but makes cache # a lot larger and slower for typical operation. This should be # enabled by builder. compiler_option :cache_fragments, default: false, as: :cache_fragments? # Warn about impending compatibility break def backtick_javascript_or_warn? case backtick_javascript? when true true when nil @backtick_javascript_warned ||= begin warning 'Backtick operator usage interpreted as intent to embed JavaScript; this code will ' \ 'break in Opal 2.0; add a magic comment: `# backtick_javascript: true`' true end true when false false end end compiler_option :scope_variables, default: [] # @!method async_await # # Enable async/await support and optionally enable auto-await. # # Use either true, false, an Array of Symbols, a String containing names # to auto-await separated by a comma or a Regexp. # # Auto-await awaits provided methods by default as if .__await__ was added to # them automatically. # # By default, the support is disabled (set to false). # # If the config value is not set to false, any calls to #__await__ will be # translated to ES8 await keyword which makes the scope return a Promise # and a containing scope will be async (instead of a value, it will return # a Promise). # # If the config value is an array, or a String separated by a comma, # auto-await is also enabled. # # A member of this collection can contain a wildcard character * in which # case all methods containing a given substring will be awaited. # # It can be used as a magic comment, examples: # ``` # # await: true # # await: *await* # # await: *await*, sleep, gets compiler_option :await, default: false, as: :async_await, magic_comment: true # Current scope attr_accessor :scope # Top scope attr_accessor :top_scope # Current case_stmt attr_reader :case_stmt # Any content in __END__ special construct attr_reader :eof_content # Comments from the source code attr_reader :comments # Method calls made in this file attr_reader :method_calls # Magic comment flags extracted from the leading comments attr_reader :magic_comments # Access the source code currently processed attr_reader :source # Set if some rewritter caused a dynamic cache result, meaning it's not # fit to be cached attr_accessor :dynamic_cache_result def initialize(source, options = {}) @source = source @indent = '' @unique = 0 @options = options @comments = Hash.new([]) @case_stmt = nil @method_calls = Set.new @option_values = {} @magic_comments = {} @dynamic_cache_result = false end def fragments return @fragments if @fragments unless @indent raise ArgumentError, <<~ERROR.tr("\n", ' ').strip This compiler arrived from cache and is unusable for postprocessing. Ensure you enable a compiler option "cache_fragments". ERROR end parse @fragments = re_raise_with_location { process(@sexp).flatten } @fragments << fragment("\n", nil, s(:newline)) unless @fragments.last.code.end_with?("\n") @fragments end # Method for postprocessors replacing fragments. # Uncache what we need. def fragments=(fragments) @result, @source_map = nil @fragments = fragments end # rubocop:disable Naming/MemoizedInstanceVariableName # Compile some ruby code to a string. # # @return [String] javascript code def compile @result ||= fragments.map(&:code).join('') end # rubocop:enable Naming/MemoizedInstanceVariableName alias result compile def parse @buffer = ::Opal::Parser::SourceBuffer.new(file, 1) @buffer.source = @source @parser = Opal::Parser.default_parser sexp, comments, tokens = re_raise_with_location { @parser.tokenize(@buffer) } kind = case when requirable? :require when eval? :eval else :main end @sexp = sexp.tap { |i| i.meta[:kind] = kind } first_node = sexp.children.first if sexp.children.first.location @comments = ::Parser::Source::Comment.associate_locations(first_node, comments) @magic_comments = MagicComments.parse(first_node, comments) @eof_content = EofContent.new(tokens, @source).eof end # Returns a source map that can be used in the browser to map back to # original ruby code. # # @param source_file [String] optional source_file to reference ruby source # @return [Opal::SourceMap] def source_map # We only use @source_map if compiler is cached. @source_map || ::Opal::SourceMap::File.new(fragments, file, @source, result) end # Any helpers required by this file. Used by {Opal::Nodes::Top} to reference # runtime helpers that are needed. These are used to minify resulting # javascript by keeping a reference to helpers used. # # @return [Set<Symbol>] def helpers @helpers ||= Set.new( magic_comments[:helpers].to_s.split(',').map { |h| h.strip.to_sym } ) end def record_method_call(mid) @method_calls << mid end alias async_await_before_typecasting async_await def async_await if defined? @async_await @async_await else original = async_await_before_typecasting @async_await = case original when String async_await_set_to_regexp(original.split(',').map { |h| h.strip.to_sym }) when Array, Set async_await_set_to_regexp(original.to_a.map(&:to_sym)) when Regexp, true, false original else raise 'A value of await compiler option can be either ' \ 'a Set, an Array, a String or a Boolean.' end end end def async_await_set_to_regexp(set) set = set.map { |name| Regexp.escape(name.to_s).gsub('\*', '.*?') } set = set.join('|') /^(#{set})$/ end # This is called when a parsing/processing error occurs. This # method simply appends the filename and curent line number onto # the message and raises it. def error(msg, line = nil) error = ::Opal::SyntaxError.new(msg) error.location = Opal::OpalBacktraceLocation.new(file, line) raise error end def re_raise_with_location yield rescue StandardError, ::Opal::SyntaxError => error opal_location = ::Opal.opal_location_from_error(error) opal_location.path = file opal_location.label ||= @source.lines[opal_location.line.to_i - 1].strip new_error = ::Opal::SyntaxError.new(error.message) new_error.set_backtrace error.backtrace ::Opal.add_opal_location_to_error(opal_location, new_error) raise new_error end # This is called when a parsing/processing warning occurs. This # method simply appends the filename and curent line number onto # the message and issues a warning. def warning(msg, line = nil) warn "warning: #{msg} -- #{file}:#{line}" end # Instances of `Scope` can use this to determine the current # scope indent. The indent is used to keep generated code easily # readable. def parser_indent @indent end # Create a new sexp using the given parts. def s(type, *children) ::Opal::AST::Node.new(type, children) end def fragment(str, scope, sexp = nil) Fragment.new(str, scope, sexp) end # Used to generate a unique id name per file. These are used # mainly to name method bodies for methods that use blocks. def unique_temp(name) name = name.to_s if name && !name.empty? name = name .to_s .gsub('<=>', '$lt_eq_gt') .gsub('===', '$eq_eq_eq') .gsub('==', '$eq_eq') .gsub('=~', '$eq_tilde') .gsub('!~', '$excl_tilde') .gsub('!=', '$not_eq') .gsub('<=', '$lt_eq') .gsub('>=', '$gt_eq') .gsub('=', '$eq') .gsub('?', '$ques') .gsub('!', '$excl') .gsub('/', '$slash') .gsub('%', '$percent') .gsub('+', '$plus') .gsub('-', '$minus') .gsub('<', '$lt') .gsub('>', '$gt') .gsub(/[^\w\$]/, '$') end unique = (@unique += 1) "#{'$' unless name.start_with?('$')}#{name}$#{unique}" end # Use the given helper def helper(name) helpers << name end # To keep code blocks nicely indented, this will yield a block after # adding an extra layer of indent, and then returning the resulting # code after reverting the indent. def indent indent = @indent @indent += INDENT @space = "\n#{@indent}" res = yield @indent = indent @space = "\n#{@indent}" res end # Temporary varibales will be needed from time to time in the # generated code, and this method will assign (or reuse) on # while the block is yielding, and queue it back up once it is # finished. Variables are queued once finished with to save the # numbers of variables needed at runtime. def with_temp tmp = @scope.new_temp res = yield tmp @scope.queue_temp tmp res end # Used when we enter a while statement. This pushes onto the current # scope's while stack so we know how to handle break, next etc. def in_while return unless block_given? @while_loop = @scope.push_while result = yield @scope.pop_while result end def in_case return unless block_given? old = @case_stmt @case_stmt = {} yield @case_stmt = old end # Returns true if the parser is curently handling a while sexp, # false otherwise. def in_while? @scope.in_while? end # Process the given sexp by creating a node instance, based on its type, # and compiling it to fragments. def process(sexp, level = :expr) return fragment('', scope) if sexp.nil? if handler = handlers[sexp.type] return handler.new(sexp, level, self).compile_to_fragments else error "Unsupported sexp: #{sexp.type}" end end def handlers @handlers ||= Opal::Nodes::Base.handlers end # An array of requires used in this file def requires @requires ||= [] end # An array of trees required in this file # (typically by calling #require_tree) def required_trees @required_trees ||= [] end # An array of things (requires, trees) which don't need to success in # loading compile-time. def autoloads @autoloads ||= [] end # The last sexps in method bodies, for example, need to be returned # in the compiled javascript. Due to syntax differences between # javascript any ruby, some sexps need to be handled specially. For # example, `if` statemented cannot be returned in javascript, so # instead the "truthy" and "falsy" parts of the if statement both # need to be returned instead. # # Sexps that need to be returned are passed to this method, and the # alterned/new sexps are returned and should be used instead. Most # sexps can just be added into a `s(:return) sexp`, so that is the # default action if no special case is required. def returns(sexp) return returns s(:nil) unless sexp case sexp.type when :undef # undef :method_name always returns nil returns sexp.updated(:begin, [sexp, s(:nil)]) when :break, :next, :redo, :retry sexp when :yield sexp.updated(:returnable_yield, nil) when :when *when_sexp, then_sexp = *sexp sexp.updated(nil, [*when_sexp, returns(then_sexp)]) when :rescue body_sexp, *resbodies, else_sexp = *sexp resbodies = resbodies.map do |resbody| returns(resbody) end if else_sexp else_sexp = returns(else_sexp) end sexp.updated( nil, [ returns(body_sexp), *resbodies, else_sexp ] ) when :resbody klass, lvar, body = *sexp sexp.updated(nil, [klass, lvar, returns(body)]) when :ensure rescue_sexp, ensure_body = *sexp sexp = sexp.updated(nil, [returns(rescue_sexp), ensure_body]) sexp.updated(:js_return, [sexp]) when :begin, :kwbegin # Wrapping last expression with s(:js_return, ...) *rest, last = *sexp sexp.updated(nil, [*rest, returns(last)]) when :while, :until, :while_post, :until_post sexp when :return, :js_return, :returnable_yield sexp when :xstr if backtick_javascript_or_warn? sexp.updated(nil, [s(:js_return, *sexp.children)]) else sexp end when :if cond, true_body, false_body = *sexp sexp.updated( nil, [ cond, returns(true_body), returns(false_body) ] ).tap { |s| s.meta[:returning] = true } else if sexp.type == :send && sexp.children[1] == :debugger # debugger is a statement, so it doesn't return a value # and returning it is invalid. Therefore we update it # to do `debugger; return nil`. sexp.updated(:begin, [sexp, s(:js_return, s(:nil))]) else sexp.updated(:js_return, [sexp]) end end end def handle_block_given_call(sexp) @scope.uses_block! if @scope.block_name fragment("(#{@scope.block_name} !== nil)", scope, sexp) elsif (scope = @scope.find_parent_def) && scope.block_name fragment("(#{scope.block_name} !== nil)", scope, sexp) else fragment('false', scope, sexp) end end # Track a module as required, so that builder will know to process it def track_require(mod) requires << mod end # Marshalling for cache shortpath def marshal_dump [@options, @option_values, @source_map ||= source_map.cache, @magic_comments, @result, @required_trees, @requires, @autoloads, (@fragments if cache_fragments?), (@source if cache_fragments?)] end def marshal_load(src) @options, @option_values, @source_map, @magic_comments, @result, @required_trees, @requires, @autoloads, @fragments, @source = src end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/errors.rb
lib/opal/errors.rb
# frozen_string_literal: true module Opal # Generic Opal error class Error < StandardError end # raised if Gem not found in Opal#use_gem class GemNotFound < Error # name of gem that not found attr_reader :gem_name # @param gem_name [String] name of gem that not found def initialize(gem_name) @gem_name = gem_name super("can't find gem #{gem_name}") end end class CompilationError < Error attr_accessor :location end class ParsingError < CompilationError end class RewritingError < ParsingError end class SyntaxError < ::SyntaxError attr_accessor :location end class OpalfileUnknownDirective < Error end def self.opal_location_from_error(error) opal_location = OpalBacktraceLocation.new opal_location.location = error.location if error.respond_to?(:location) opal_location.diagnostic = error.diagnostic if error.respond_to?(:diagnostic) opal_location end def self.add_opal_location_to_error(opal_location, error) backtrace = error.backtrace.to_a backtrace.unshift opal_location.to_s error.set_backtrace backtrace error end # Loosely compatible with Thread::Backtrace::Location class OpalBacktraceLocation attr_accessor :path, :lineno, :label def initialize(path = nil, lineno = nil, label = nil) @path, @lineno, @label = path, lineno, label end def to_s string = path string += ":#{lineno}" if lineno string += ':in ' if label string += "`#{label}'" else string += 'unknown' end string end alias line lineno def diagnostic=(diagnostic) return unless diagnostic self.location = diagnostic.location end def location=(location) return unless location self.lineno = location.line if location.respond_to?(:source_line) self.label = location.source_line elsif location.respond_to?(:expression) self.label = location.expression.source_line end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes.rb
lib/opal/nodes.rb
# frozen_string_literal: true require 'opal/nodes/closure' require 'opal/nodes/base' require 'opal/nodes/literal' require 'opal/nodes/variables' require 'opal/nodes/constants' require 'opal/nodes/call' require 'opal/nodes/call/eval' require 'opal/nodes/call/match3' require 'opal/nodes/call/js_property' require 'opal/nodes/call/reflection' require 'opal/nodes/call/require' require 'opal/nodes/call/dce' require 'opal/nodes/module' require 'opal/nodes/class' require 'opal/nodes/singleton_class' require 'opal/nodes/args' require 'opal/nodes/args/arity_check' require 'opal/nodes/iter' require 'opal/nodes/def' require 'opal/nodes/defs' require 'opal/nodes/if' require 'opal/nodes/logic' require 'opal/nodes/definitions' require 'opal/nodes/yield' require 'opal/nodes/rescue' require 'opal/nodes/super' require 'opal/nodes/top' require 'opal/nodes/while' require 'opal/nodes/hash' require 'opal/nodes/array' require 'opal/nodes/defined' require 'opal/nodes/masgn' require 'opal/nodes/arglist' require 'opal/nodes/x_string' require 'opal/nodes/lambda'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/simple_server.rb
lib/opal/simple_server.rb
# frozen_string_literal: true require 'opal/deprecations' # Opal::SimpleServer is a very basic Rack server for Opal assets, it relies on # Opal::Builder and Ruby corelib/stdlib. It's meant to be used just for local # development. # # For a more complete implementation see opal-sprockets (Rubygems) or # opal-webpack (NPM). # # @example (CLI) # rackup -ropal -ropal/simple_server -b 'Opal.append_path("app"); run Opal::SimpleServer.new' # ... or use the Server runner ... # opal -Rserver app.rb class Opal::SimpleServer require 'set' require 'erb' NotFound = Class.new(StandardError) def initialize(options = {}) @prefix = options.fetch(:prefix, 'assets').delete_prefix('/') @main = options.fetch(:main, 'application') @builder = options.fetch(:builder, nil) @transformations = [] @index_path = nil @builders = {} yield self if block_given? end attr_accessor :main, :index_path def append_path(path) @transformations << [:append_paths, path] end def call(env) case env['PATH_INFO'] when %r{\A/#{@prefix}/(.*?)\.m?js(/.*)?\z} path, rest = Regexp.last_match(1), Regexp.last_match(2)&.delete_prefix('/').to_s call_js(path, rest) else call_index end rescue NotFound => error [404, {}, [error.to_s]] end def call_js(path, rest) asset = fetch_asset(path, rest) [ 200, { 'content-type' => 'application/javascript' }, @directory ? [asset[:data]] : [asset[:data], "\n", asset[:map].to_data_uri_comment], ] end def builder(path) case @builder when Opal::Builder builder = @builder when Proc if @builder.arity == 0 builder = @builder.call else builder = @builder.call(path) end else builder = Opal::Builder.new builder = apply_builder_transformations(builder) builder.build(path.gsub(/(\.(?:rb|m?js|opal))*\z/, '')) end @esm = builder.compiler_options[:esm] @directory = builder.compiler_options[:directory] builder end # Only cache one builder at a time def cached_builder(path, uncache: false) @builders = {} if uncache || @builders.keys != [path] @builders[path] ||= builder(path) end def apply_builder_transformations(builder) @transformations.each do |type, *args| case type when :append_paths builder.append_paths(*args) end end builder end def fetch_asset(path, rest) builder = cached_builder(path) if @directory { data: builder.compile_to_directory(single_file: rest) } else { data: builder.to_s, map: builder.source_map } end end def javascript_include_tag(path) # Uncache previous builders and cache a new one cached_builder(path, uncache: true) path += ".#{js_ext}/index" if @directory if @esm %{<script src="/#{@prefix}/#{path}.#{js_ext}" type="module"></script>} else %{<script src="/#{@prefix}/#{path}.#{js_ext}"></script>} end end def call_index if @index_path contents = File.read(@index_path) html = ERB.new(contents).result binding else html = <<-HTML <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> #{javascript_include_tag(main)} </body> </html> HTML end [200, { 'content-type' => 'text/html', 'cache-control' => 'no-cache' }, [html]] end def js_ext @esm ? 'mjs' : 'js' end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/exe_compiler.rb
lib/opal/exe_compiler.rb
# frozen_string_literal: true require 'fileutils' require 'tmpdir' require 'opal/os' module Opal class ExeCompiler RUNTIMES = -> { types = %w[bun deno node quickjs] types << 'osascript' if OS.macos? types.freeze }.call def self.compile_exe(type, src_out) new(type, src_out).compile_exe end def initialize(type, src_out) raise "Cannot compile exe: unsupported runtime type '#{type}'" unless RUNTIMES.include?(type) if src_out.instance_of?(IO) @out_path = "opal_#{type}_exe" elsif src_out.is_a?(File) @out_path = src_out.path else raise 'Cannot compile exe: source must be a file.' end @type, @source = type, src_out end def compile_exe puts "Creating #{@out_path}:" res = true Dir.mktmpdir('opal-compile-exe-') do |dir| src_path = File.join(dir, "#{File.basename(@out_path)}.js") @source.flush @source.fsync @source.close File.write(src_path, File.read(@source.path)) File.unlink(@source.path) res = send("compile_#{@type}_exe".to_sym, src_path, dir) end puts 'Done.' res ? 0 : 1 end private def append_exe_to_out_path_on_windows if OS.windows? && !@out_path.downcase.end_with?('.exe') @out_path << '.exe' end end def compile_bun_exe(src_path, _dir) system('bun', 'build', src_path, '--compile', '--outfile', @out_path) end def compile_deno_exe(src_path, _dir) system('deno', 'compile', '--allow-env', '--allow-read', '--allow-sys', '--allow-write', '--output', @out_path, src_path ) end def compile_node_exe(src_path, dir) # Very new, experimental and complicated. # See https://nodejs.org/api/single-executable-applications.html Dir.chdir(dir) do # 1. Create a JavaScript file - already done above # 2. Create a configureation file File.write('sea-config.json', "{\"main\":\"#{src_path}\",\"output\":\"sea-prep.blob\"}") # 3. Generate the blob to be injected: system('node', '--experimental-sea-config', 'sea-config.json') # 4. Create a copy of the node executable # What could possibly go wrong? system('node', '-e', 'require("node:fs").copyFileSync(process.execPath, "node_copy.exe")') # 4.1. Adjust file permissions File.chmod(0o775, 'node_copy.exe') # 5. Remove the signature of the binary if OS.macos? system('codesign --remove-signature node_copy.exe') elsif OS.windows? system('signtool remove /s node_copy.exe') end # 6. Inject the blob into the copied binary if OS.macos? system('npx', 'postject', 'node_copy.exe', 'NODE_SEA_BLOB', 'sea-prep.blob', '--sentinel-fuse', 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2', '--macho-segment-name', 'NODE_SEA' # Thats not a 'macho', thats Mach-O, the Mach Object File Format ) else system('npx', 'postject', 'node_copy.exe', 'NODE_SEA_BLOB', 'sea-prep.blob', '--sentinel-fuse', 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2' ) end # 7. Sign the binary if OS.macos? system('codesign --sign - node_copy.exe') elsif OS.windows? system('signtool sign /fd SHA256 node_copy.exe') end end # 8. Copy binary to target append_exe_to_out_path_on_windows FileUtils.cp(File.join(dir, 'node_copy.exe'), @out_path) true end def compile_osascript_exe(src_path, _dir) @out_path << '.app' unless @out_path.end_with?('.app') system('osacompile', '-l', 'JavaScript', '-o', @out_path, '-s', src_path) end def compile_quickjs_exe(src_path, _dir) append_exe_to_out_path_on_windows # '-flto', '-fbignum' might be useful options, depending on quickjs version/build system('qjsc', '-o', @out_path, src_path) end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/deprecations.rb
lib/opal/deprecations.rb
# frozen_string_literal: true module Opal module Deprecations attr_accessor :raise_on_deprecation def deprecation(message) message = "DEPRECATION WARNING: #{message}" if defined?(@raise_on_deprecation) && @raise_on_deprecation raise message else warn message end end end extend Deprecations self.raise_on_deprecation = false end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners.rb
lib/opal/cli_runners.rb
# frozen_string_literal: true require 'opal/os' module Opal # `Opal::CliRunners` is the register in which JavaScript runners can be # defined for use by `Opal::CLI`. Runners will be called via the `#call` # method and passed a Hash containing the following keys: # # # - `options`: a hash of options for the runner # - `output`: an IO-like object responding to `#write` and `#puts` # - `argv`: is the arguments vector coming from the CLI that is being # forwarded to the program # - `builder`: a proc returning a new instance of Opal::Builder so it # can be re-created and pick up the most up-to-date sources # # Runners can be registered using `#register_runner(name, runner)`. # module CliRunners class RunnerError < StandardError end @runners = [] def self.registered_runners @runners end @register = {} def self.[](name) @register[name.to_sym]&.call end # @private def self.[]=(name, runner) warn "Overwriting Opal CLI runner: #{name}" if @register.key? name.to_sym @register[name.to_sym] = runner end private_class_method :[]= def self.to_h @register end # @param name [Symbol] the name at which the runner can be reached # @param runner [#call] a callable object that will act as the "runner" # @param runner [Symbol] a constant name that once autoloaded will point to # a callable. # @param path [nil,String] a path for setting up autoload on the constant def self.register_runner(name, runner, path = nil) autoload runner, path if path @runners.push(runner.to_s) if runner.respond_to? :call self[name] = -> { runner } else self[name] = -> { const_get(runner) } end nil end # Alias a runner name def self.alias_runner(new_name, old_name) self[new_name.to_sym] = -> { self[old_name.to_sym] } nil end # running on all OS register_runner :bun, :Bun, 'opal/cli_runners/bun' register_runner :chrome, :Chrome, 'opal/cli_runners/chrome' register_runner :compiler, :Compiler, 'opal/cli_runners/compiler' register_runner :deno, :Deno, 'opal/cli_runners/deno' register_runner :firefox, :Firefox, 'opal/cli_runners/firefox' register_runner :nodejs, :Nodejs, 'opal/cli_runners/nodejs' register_runner :quickjs, :Quickjs, 'opal/cli_runners/quickjs' register_runner :server, :Server, 'opal/cli_runners/server' alias_runner :node, :nodejs if !OS.windows? && !OS.macos? register_runner :gjs, :Gjs, 'opal/cli_runners/gjs' end unless OS.windows? register_runner :miniracer, :MiniRacer, 'opal/cli_runners/mini_racer' end if OS.macos? register_runner :applescript, :Applescript, 'opal/cli_runners/applescript' register_runner :safari, :Safari, 'opal/cli_runners/safari' alias_runner :osascript, :applescript end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/fragment.rb
lib/opal/fragment.rb
# frozen_string_literal: true module Opal # A fragment holds a string of generated javascript that will be written # to the destination. It also keeps hold of the original sexp from which # it was generated. Using this sexp, when writing fragments in order, a # mapping can be created of the original location => target location, # aka, source-maps! # # These are generated by nodes, so will not have to create directly. class Fragment # String of javascript this fragment holds # @return [String] attr_reader :code attr_reader :scope, :sexp # Create fragment with javascript code and optional original [Opal::Sexp]. # # @param code [String] javascript code # @param sexp [Opal::Sexp] sexp used for creating fragment def initialize(code, scope, sexp = nil) @code = code.to_s @sexp = sexp @scope = scope end # Inspect the contents of this fragment, f("fooo") def inspect "f(#{@code.inspect})" end def source_map_name_for(sexp) case sexp.type when :top case sexp.meta[:kind] when :require '<top (required)>' when :eval '(eval)' when :main '<main>' end when :begin, :newline, :js_return source_map_name_for(@scope.sexp) if @scope when :iter scope = @scope iters = 1 while scope if scope.class == Nodes::IterNode iters += 1 scope = scope.parent else break end end level = " (#{iters} levels)" if iters > 1 "block#{level} in #{source_map_name_for(scope.sexp)}" when :self 'self' when :module const, = *sexp "<module:#{source_map_name_for(const)}>" when :class const, = *sexp "<class:#{source_map_name_for(const)}>" when :const scope, name = *sexp if !scope || scope.type == :cbase name.to_s else "#{source_map_name_for(scope)}::#{name}" end when :int sexp.children.first when :def sexp.children.first when :defs sexp.children[1] when :send sexp.children[1] when :lvar, :lvasgn, :lvdeclare, :ivar, :ivasgn, :gvar, :cvar, :cvasgn, :gvars, :gvasgn, :arg sexp.children.first when :str, :xstr # Inside xstr - JS calls source_map_name_for(@scope.sexp) else # nil end end def source_map_name return nil unless @sexp source_map_name_for(@sexp) end def location case when !@sexp nil when @sexp.type == :send loc = @sexp.loc if loc.respond_to? :dot # a>.b || a>+b / >a / a>[b] loc.dot || loc.selector elsif loc.respond_to? :operator # a >|= b loc.operator else @sexp end when @sexp.type == :iter if loc.respond_to? :begin @sexp.loc.begin # [1,2].each >{ } else @sexp end else @sexp end end # Original line this fragment was created from # @return [Integer, nil] def line location&.line end # Original column this fragment was created from # @return [Integer, nil] def column location&.column end def skip_source_map? @sexp == false end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriter.rb
lib/opal/rewriter.rb
# frozen_string_literal: true require 'opal/rewriters/opal_engine_check' require 'opal/rewriters/targeted_patches' require 'opal/rewriters/for_rewriter' require 'opal/rewriters/js_reserved_words' require 'opal/rewriters/block_to_iter' require 'opal/rewriters/dot_js_syntax' require 'opal/rewriters/pattern_matching' require 'opal/rewriters/logical_operator_assignment' require 'opal/rewriters/binary_operator_assignment' require 'opal/rewriters/hashes/key_duplicates_rewriter' require 'opal/rewriters/dump_args' require 'opal/rewriters/deduplicate_arg_name' require 'opal/rewriters/mlhs_args' require 'opal/rewriters/inline_args' require 'opal/rewriters/numblocks' require 'opal/rewriters/returnable_logic' require 'opal/rewriters/forward_args' require 'opal/rewriters/thrower_finder' module Opal class Rewriter @disabled = false class << self def list @list ||= [] end def use(rewriter) list << rewriter end def delete(rewriter) list.delete(rewriter) end def disable(except: nil) old_disabled = @disabled @disabled = except || true yield ensure @disabled = old_disabled end def disabled? @disabled == true end def rewritter_disabled?(rewriter) return false if @disabled == false @disabled != rewriter end end use Rewriters::OpalEngineCheck use Rewriters::ForRewriter use Rewriters::Numblocks use Rewriters::ForwardArgs use Rewriters::BlockToIter use Rewriters::TargetedPatches use Rewriters::DotJsSyntax use Rewriters::PatternMatching use Rewriters::JsReservedWords use Rewriters::LogicalOperatorAssignment use Rewriters::BinaryOperatorAssignment use Rewriters::Hashes::KeyDuplicatesRewriter use Rewriters::ReturnableLogic use Rewriters::DeduplicateArgName use Rewriters::DumpArgs use Rewriters::MlhsArgs use Rewriters::InlineArgs use Rewriters::ThrowerFinder def initialize(sexp) @sexp = sexp end def process return @sexp if self.class.disabled? self.class.list.each do |rewriter_class| next if self.class.rewritter_disabled?(rewriter_class) rewriter = rewriter_class.new @sexp = rewriter.process(@sexp) end @sexp end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/os.rb
lib/opal/os.rb
# frozen_string_literal: true require 'shellwords' module Opal module OS module_function def windows? /bccwin|cygwin|djgpp|mingw|mswin|wince/.match?(RbConfig::CONFIG['host_os']) end def macos? /darwin|mac os/.match?(RbConfig::CONFIG['host_os']) end def shellescape(str) if windows? '"' + str.gsub('"', '""') + '"' else str.shellescape end end def env_sep windows? ? ';' : ':' end def path_sep windows? ? '\\' : '/' end def cmd_sep windows? ? ' & ' : ' ; ' end def dev_null windows? ? 'NUL' : '/dev/null' end def bash_c(*commands) cmd = if windows? [ 'bundle', 'exec', 'cmd', '/c', ] else [ 'bundle', 'exec', 'bash', '-c', ] end cmd << commands.join(cmd_sep) end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/parser.rb
lib/opal/parser.rb
# frozen_string_literal: true require 'opal/ast/builder' require 'opal/rewriter' require 'opal/parser/source_buffer' require 'opal/parser/default_config' require 'opal/parser/with_ruby_lexer' require 'opal/parser/patch'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/requires.rb
lib/opal/requires.rb
# frozen_string_literal: true require 'opal/config' require 'opal/compiler' require 'opal/builder' require 'opal/builder/processor' require 'opal/erb' require 'opal/paths' require 'opal/version' require 'opal/errors' require 'opal/source_map' require 'opal/deprecations' module Opal autoload :Server, 'opal/server' if RUBY_ENGINE != 'opal' autoload :SimpleServer, 'opal/simple_server' end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/repl.rb
lib/opal/repl.rb
# frozen_string_literal: true require 'opal' require 'securerandom' require 'stringio' require 'fileutils' require 'rbconfig' module Opal class REPL HISTORY_PATH = File.expand_path('~/.opal-repl-history') attr_accessor :colorize def initialize(runner_type = nil) @argv = [] @colorize = true @runner_type = runner_type || :nodejs begin require 'readline' rescue LoadError abort 'opal-repl depends on readline, which is not currently available' end begin FileUtils.touch(HISTORY_PATH) rescue nil end @history = File.exist?(HISTORY_PATH) end def run(argv = []) @argv = argv savepoint = save_tty load_opal load_history run_input_loop ensure dump_history restore_tty(savepoint) end def load_opal runner = @argv.reject { |i| i == '--repl' } runner += ['-R', @runner_type.to_s, '--await'] runner += ['-e', 'require "opal/repl_js"'] runner = [RbConfig.ruby, "#{__dir__}/../../exe/opal"] + runner # What I try to achieve here: let the runner ignore # interrupts. Those should be handled by a supervisor. @pipe = if RUBY_ENGINE == 'truffleruby' IO.popen(runner, 'r+', pgroup: true) else IO.popen(runner, 'r+', pgroup: true, new_pgroup: true) end end def run_input_loop while (line = readline) eval_ruby(line) end rescue Interrupt @incomplete = nil retry ensure finish end def finish @pipe.close rescue nil end def eval_ruby(code) builder = Opal::Builder.new silencer = Silencer.new code = "#{@incomplete}#{code}" if code.start_with? 'ls ' eval_code = code[3..-1] mode = :ls elsif code == 'ls' eval_code = 'self' mode = :ls elsif code.start_with? 'show ' eval_code = code[5..-1] mode = :show else eval_code = code mode = :inspect end begin silencer.silence do builder.build_str(eval_code, '(irb)', irb: true, const_missing: true, await: true) end @incomplete = nil rescue Opal::SyntaxError => e if LINEBREAKS.include?(e.message) @incomplete = "#{code}\n" else @incomplete = nil if silencer.warnings.empty? warn e.full_message else # Most likely a parser error warn silencer.warnings end end return end builder.processed[0...-1].each { |js_code| eval_js(:silent, js_code.to_s) } last_processed_file = builder.processed.last.to_s if mode == :show puts last_processed_file return end eval_js(mode, last_processed_file) rescue Interrupt, SystemExit => e raise e rescue Exception => e # rubocop:disable Lint/RescueException puts e.full_message(highlight: true) end private LINEBREAKS = [ 'unexpected token $end', 'unterminated string meets end of file' ].freeze class Silencer def initialize @stderr = $stderr end def silence @collector = StringIO.new $stderr = @collector yield ensure $stderr = @stderr end def warnings @collector.string end end def eval_js(mode, code) obj = { mode: mode, code: code, colors: colorize }.to_json @pipe.puts obj while (line = @pipe.readline) break if line.chomp == '<<<ready>>>' puts line end rescue Interrupt => e # A child stopped responding... let's create a new one warn "* Killing #{@pipe.pid}" Process.kill('-KILL', @pipe.pid) load_opal raise e rescue EOFError, Errno::EPIPE exit $?.nil? ? 0 : $?.exitstatus end def readline prompt = @incomplete ? '.. ' : '>> ' Readline.readline prompt, true end def load_history return unless @history File.read(HISTORY_PATH).lines.each { |line| Readline::HISTORY.push line.strip } end def dump_history return unless @history length = Readline::HISTORY.size > 1000 ? 1000 : Readline::HISTORY.size File.write(HISTORY_PATH, Readline::HISTORY.to_a[-length..-1].join("\n")) end # How do we support Win32? def save_tty %x{stty -g}.chomp rescue nil end def restore_tty(savepoint) system('stty', savepoint) rescue nil end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/hike.rb
lib/opal/hike.rb
# frozen_string_literal: true # Copyright (c) 2011 Sam Stephenson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require 'pathname' module Opal # Taken from hike v1.2.3 module Hike # `Index` is an internal cached variant of `Trail`. It assumes the # file system does not change between `find` calls. All `stat` and # `entries` calls are cached for the lifetime of the `Index` object. class Index # `Index#paths` is an immutable collection of `Pathname`s. attr_reader :paths # `Index#extensions` is an immutable collection of extensions. attr_reader :extensions # `Index.new` is an internal method. Instead of constructing it # directly, create a `Trail` and call `Trail#index`. def initialize(root, paths, extensions) @root = root # Freeze is used here so an error is throw if a mutator method # is called on the array. Mutating `@paths`, `@extensions` # would have unpredictable results. @paths = paths.dup.freeze @extensions = extensions.dup.freeze @pathnames = paths.map { |path| Pathname.new(path) } @stats = {} @entries = {} @patterns = {} end # `Index#root` returns root path as a `String`. This attribute is immutable. def root @root.to_s end # `Index#index` returns `self` to be compatable with the `Trail` interface. def index self end # The real implementation of `find`. `Trail#find` generates a one # time index and delegates here. # # See `Trail#find` for usage. def find(logical_path) base_path = Pathname.new(@root) logical_path = Pathname.new(logical_path.sub(/^\//, '')) if logical_path.to_s =~ %r{^\.\.?/} find_in_base_path(logical_path, base_path) { |path| return path } else find_in_paths(logical_path) { |path| return path } end nil end # A cached version of `Dir.entries` that filters out `.` files and # `~` swap files. Returns an empty `Array` if the directory does # not exist. def entries(path) @entries[path.to_s] ||= begin pathname = Pathname.new(path) if pathname.directory? pathname.entries.reject { |entry| entry.to_s =~ /^\.|~$|^\#.*\#$/ }.sort else [] end end end # A cached version of `File.stat`. Returns nil if the file does # not exist. def stat(path) key = path.to_s if @stats.key?(key) @stats[key] elsif File.exist?(path) @stats[key] = File.stat(path) else @stats[key] = nil end end protected def extract_options!(arguments) arguments.last.is_a?(Hash) ? arguments.pop.dup : {} end # Finds logical path across all `paths` def find_in_paths(logical_path, &block) dirname, basename = logical_path.split @pathnames.each do |base_path| match(base_path.join(dirname), basename, &block) end end # Finds relative logical path, `../test/test_trail`. Requires a # `base_path` for reference. def find_in_base_path(logical_path, base_path, &block) candidate = base_path.join(logical_path) dirname, basename = candidate.split match(dirname, basename, &block) if paths_contain?(dirname) end # Checks if the path is actually on the file system and performs # any syscalls if necessary. def match(dirname, basename) # Potential `entries` syscall matches = entries(dirname) pattern = pattern_for(basename) matches = matches.select { |m| m.to_s =~ pattern } sort_matches(matches, basename).each do |path| pathname = dirname.join(path) # Potential `stat` syscall stat = stat(pathname) # Exclude directories if stat && stat.file? yield pathname.to_s end end end # Returns true if `dirname` is a subdirectory of any of the `paths` def paths_contain?(dirname) paths.any? { |path| dirname.to_s[0, path.length] == path } end # Cache results of `build_pattern_for` def pattern_for(basename) @patterns[basename] ||= build_pattern_for(basename) end # Returns a `Regexp` that matches the allowed extensions. # # pattern_for("index.html") #=> /^index(.html|.htm)(.builder|.erb)*$/ def build_pattern_for(basename) extension_pattern = extensions.map { |e| Regexp.escape(e) }.join('|') /^#{basename}(?:#{extension_pattern})*$/ end # Sorts candidate matches by their extension # priority. Extensions in the front of the `extensions` carry # more weight. def sort_matches(matches, basename) matches.sort_by do |match| extnames = match.sub(basename.to_s, '').to_s.scan(/\.[^.]+/) extnames.inject(0) do |sum, ext| index = extensions.index(ext) if index sum + index + 1 else sum end end end end end # `Trail` is the public container class for holding paths and extensions. class Trail # `Trail#paths` is a mutable `Paths` collection. # # trail = Hike::Trail.new # trail.paths.push "~/Projects/hike/lib", "~/Projects/hike/test" # # The order of the paths is significant. Paths in the beginning of # the collection will be checked first. In the example above, # `~/Projects/hike/lib/hike.rb` would shadow the existent of # `~/Projects/hike/test/hike.rb`. attr_reader :paths # `Trail#extensions` is a mutable `Extensions` collection. # # trail = Hike::Trail.new # trail.paths.push "~/Projects/hike/lib" # trail.extensions.push ".rb" # # Extensions allow you to find files by just their name omitting # their extension. Is similar to Ruby's require mechanism that # allows you to require files with specifiying `foo.rb`. attr_reader :extensions # A Trail accepts an optional root path that defaults to your # current working directory. Any relative paths added to # `Trail#paths` will expanded relative to the root. def initialize(root = '.') @root = Pathname.new(root).expand_path @paths = [] @extensions = [] end # `Trail#root` returns root path as a `String`. This attribute is immutable. def root @root.to_s end # Append `path` to `Paths` collection def append_paths(*paths) @paths.concat(paths.map { |p| normalize_path(p) }) end # Append `extension` to `Extensions` collection def append_extensions(*extensions) @extensions.concat(extensions.map { |e| normalize_extension(e) }) end # `Trail#find` returns a the expand path for a logical path in the # path collection. # # trail = Hike::Trail.new "~/Projects/hike" # trail.extensions.push ".rb" # trail.paths.push "lib", "test" # # trail.find "hike/trail" # # => "~/Projects/hike/lib/hike/trail.rb" # # trail.find "test_trail" # # => "~/Projects/hike/test/test_trail.rb" # def find(*args, &block) index.find(*args, &block) end # `Trail#index` returns an `Index` object that has the same # interface as `Trail`. An `Index` is a cached `Trail` object that # does not update when the file system changes. If you are # confident that you are not making changes the paths you are # searching, `index` will avoid excess system calls. # # index = trail.index # index.find "hike/trail" # index.find "test_trail" # def index Index.new(root, paths, extensions) end # `Trail#entries` is equivalent to `Dir#entries`. It is not # recommend to use this method for general purposes. It exists for # parity with `Index#entries`. def entries(path) pathname = Pathname.new(path) if pathname.directory? pathname.entries.reject { |entry| entry.to_s =~ /^\.|~$|^\#.*\#$/ }.sort else [] end end # `Trail#stat` is equivalent to `File#stat`. It is not # recommend to use this method for general purposes. It exists for # parity with `Index#stat`. def stat(path) if File.exist?(path) File.stat(path.to_s) else # nil end end private def normalize_extension(ext) ext.start_with?('.') ? ext : ".#{ext}" end def normalize_path(path) path = Pathname.new(path) path = @root.join(path) if path.relative? path.expand_path.to_s end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_options.rb
lib/opal/cli_options.rb
# frozen_string_literal: true require 'optparse' require 'opal/cli_runners' require 'opal/exe_compiler' module Opal class CLIOptions < OptionParser def initialize super @options = {} self.banner = 'Usage: opal [options] -- [programfile]' separator '' on('--repl', 'Run the Opal REPL') do options[:repl] = true end on('--compile-to-exe RUNTIME', Opal::ExeCompiler::RUNTIMES, "Compiles and builds a standalone application with RUNTIME. The following RUNTIMEs are available: #{Opal::ExeCompiler::RUNTIMES.join(', ')}") do |type| options[:exe_type] = type options[:runner] = :compiler options[:output] = "opal_#{type}_exe" unless options[:output] end on('-v', '--verbose', 'print version number, then turn on verbose mode') do print_version exit if ARGV.empty? options[:verbose] = true end on('--verbose', 'turn on verbose mode (set $VERBOSE to true)') do options[:verbose] = true end on('-d', '--debug', 'turn on debug mode (set $DEBUG to true)') do options[:debug] = true end on('--version', 'Print the version') do print_version exit end on('-h', '--help', 'Show this message') do puts self exit end section 'Basic Options:' on('-e', '--eval SOURCE', String, 'One line of script. Several -e\'s allowed. Omit [programfile]' ) do |source| options[:evals] ||= [] options[:evals] << source end on('-r', '--require LIBRARY', String, 'Require the library before executing your script' ) do |library| options[:requires] ||= [] options[:requires] << library end on('-q', '--rbrequire LIBRARY', String, 'Require the library in Ruby context before compiling' ) do |library| options[:rbrequires] ||= [] options[:rbrequires] << library end on('-I', '--include DIR', 'Append a load path (may be used more than once)') do |i| options[:load_paths] ||= [] options[:load_paths] << i end on('-s', '--stub FILE', String, 'Stubbed files will be compiled as empty files') do |stub| options[:stubs] ||= [] options[:stubs] << stub end on('-p', '--preload FILE', String, 'Preloaded files will be prepared for dynamic requires') do |stub| options[:preload] ||= [] options[:preload] << stub end on('-g', '--gem GEM_NAME', String, 'Adds the specified GEM_NAME to Opal\'s load path.') do |g| options[:gems] ||= [] options[:gems] << g end section 'Running Options:' on('-R', '--runner RUNNER', Opal::CliRunners.to_h.keys, 'Choose the runner:', "nodejs (default), #{(Opal::CliRunners.to_h.keys - %i[nodejs compiler]).join(', ')}") do |runner| options[:runner] = runner.to_sym end on('--server-port PORT', 'Set the port for the server runner (default port: 3000)') do |port| options[:runner_options] ||= {} options[:runner_options][:port] = port.to_i end on('--runner-options JSON', 'Set options specific to the selected runner as a JSON string (e.g. port for server)') do |json_options| require 'json' runner_options = JSON.parse(json_options, symbolize_names: true) options[:runner_options] ||= {} options[:runner_options].merge!(runner_options) end section 'Builder Options:' on('-c', '--compile', 'Compile to JavaScript') do options[:runner] = :compiler end on('-o', '--output FILE', 'Output JavaScript to FILE (or directory if --directory enabled)') do |file| options[:output] = file end on('-P', '--map FILE', 'Output source map to FILE') do |file| options[:runner_options] ||= {} options[:runner_options][:map_file] = file end on('--no-source-map', "Don't append source map to a compiled file") do options[:runner_options] ||= {} options[:runner_options][:no_source_map] = true end on('--watch', 'Run the compiler in foreground, recompiling every filesystem change') do options[:runner_options] ||= {} options[:runner_options][:watch] = true end on('--no-cache', 'Disable filesystem cache') do options[:no_cache] = true end on('-L', '--library', 'Compile only required libraries. Omit [programfile] and [-e]. Assumed [-cOE].') do options[:lib_only] = true options[:no_exit] = true options[:compile] = true options[:skip_opal_require] = true end on('-O', '--no-opal', 'Disable implicit `require "opal"`') do options[:skip_opal_require] = true end on('-E', '--no-exit', 'Do not append a Kernel#exit at the end of file') do options[:no_exit] = true end on('--dce [OPTIONS]', 'EXPERIMENTAL: Enable dead code elimination to reduce bundle size.', 'You can select multiple optimizations separated with a comma (,):', 'method (default), const' ) do |dce| dce ||= 'method' options[:dce] = dce.split(',').map(&:to_sym) end section 'Compiler Options:' on('--use-strict', 'Enables JavaScript\'s strict mode (i.e., adds \'use strict\'; statement)') do options[:use_strict] = true end on('--esm', 'Wraps compiled bundle as ES6 module') do options[:esm] = true end on('--directory', 'Builds the program as a directory of JS files') do options[:directory] = true end on('-A', '--arity-check', 'Enable arity check') do options[:arity_check] = true end dynamic_require_levels = %w[error warning ignore] on('-D', '--dynamic-require LEVEL', dynamic_require_levels, 'Set level of dynamic require severity.', "(default: error, values: #{dynamic_require_levels.join(', ')})" ) do |level| options[:dynamic_require_severity] = level.to_sym end missing_require_levels = %w[error warning ignore] on('--missing-require LEVEL', missing_require_levels, 'Set level of missing require severity.', "(default: error, values: #{missing_require_levels.join(', ')})" ) do |level| options[:missing_require_severity] = level.to_sym end on('--enable-source-location', 'Compiles source location for each method definition.') do options[:enable_source_location] = true end on('--parse-comments', 'Compiles comments for each method definition.') do options[:parse_comments] = true end on('--enable-file-source-embed', 'Embeds file sources to be accessed by applications.') do options[:enable_file_source_embed] = true end on('--irb', 'Enable IRB var mode') do options[:irb] = true end on('--await', 'Enable async/await support') do options[:await] = true end on('-M', '--no-method-missing', 'Disable method missing') do options[:method_missing] = false end on('-F', '--file FILE', 'Set filename for compiled code') do |file| options[:file] = file end on('-V', '(deprecated; always enabled) Enable inline Operators') do warn '* -V is deprecated and has no effect' options[:inline_operators] = true end section 'Debug Options:' on('--sexp', 'Show Sexps') do options[:sexp] = true end on('--debug-source-map', 'Debug source map') do options[:debug_source_map] = true end separator '' end attr_reader :options private def print_version require 'opal/version' puts "Opal v#{Opal::VERSION}" end def section(title) separator '' separator title separator '' end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/paths.rb
lib/opal/paths.rb
# frozen_string_literal: true require 'opal/project' module Opal def self.gem_dir if defined? Opal::GEM_DIR # This is for the case of opalopal. __FILE__ and __dir__ are unreliable # in this case. Opal::GEM_DIR else File.expand_path('..', __dir__) end end # Add a file path to opals load path. Any gem containing ruby code that Opal # has access to should add a load path through this method. Load paths added # here should only be paths which contain code targeted at being compiled by # Opal. def self.append_path(path) append_paths(path) end # Same as #append_path but can take multiple paths. def self.append_paths(*paths) paths.each { |i| setup_project(i) } @paths.concat(paths) nil end # All files that Opal depends on while compiling (for cache keying and # watching) def self.dependent_files # We want to ensure the compiler and any Gemfile/gemspec (for development) # stays untouched opal_path = File.expand_path('..', Opal.gem_dir) files = Dir["#{opal_path}/{Opalfile,Gemfile*,*.gemspec,lib/**/*}"] # Also check if parser wasn't changed: files += $LOADED_FEATURES.grep(%r{lib/(parser|ast)}) files end extend Project::Collection def self.paths @paths.freeze end # Resets Opal.paths to the default value # (includes `corelib`, `stdlib`, `opal/lib`, `ast` gem and `parser` gem) def self.reset_paths! @paths = [] @projects = [] setup_project(gem_dir) nil end reset_paths! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/eof_content.rb
lib/opal/eof_content.rb
# frozen_string_literal: true module Opal class EofContent DATA_SEPARATOR = "__END__\n" def initialize(tokens, source) @tokens = tokens @source = source end def eof return nil if @tokens.empty? eof_content = @source[last_token_position..-1] return nil unless eof_content # On Windows token position is off a bit, because Parser does not seem to compensate for \r\n # The first eof_content line on Windows may be for example "end\r\n" # Must match for it and \r\n and \n eof_content = eof_content.lines.drop_while { |line| /\A.*\r?\n?\z/.match?(line) && !line.start_with?('__END__') } if /\A__END__\r?\n?\z/.match?(eof_content[0]) eof_content = eof_content[1..-1] || [] eof_content.join elsif eof_content == ['__END__'] '' end end private def last_token_position _, last_token_info = @tokens.last _, last_token_range = last_token_info last_token_range.end_pos end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/regexp_transpiler.rb
lib/opal/regexp_transpiler.rb
# frozen_string_literal: true # backtick_javascript: true # use_strict: true module Opal module RegexpTranspiler module_function # Transform a regular expression from Ruby syntax to JS syntax, as much # as possible. def transform_regexp(original_regexp, flags) flags ||= '' if include?(flags, 'm') ruby_multiline = true flags = remove_flag(flags, 'm') end flags = add_flag(flags, 'u') # always be unicode aware to handle surrogates correctly # First step - easy replacements regexp = transform_regexp_by_re_and_hash(original_regexp, ESCAPES_REGEXP, Opal::REGEXP_EQUIVALENTS) # Tokenize the regexp into tokens of `[]` and anything else. escaping = false str = '' depth = 0 inside = false curr_inside = false new_regexp = '' line_based_regexp = false string_based_regexp = false unicode_character_class = false quantifier = false apply_outside_transform = -> do unless curr_inside str = transform_regexp_by_re_and_hash(str, OUTSIDE_ESCAPES_REGEXP, Opal::REGEXP_EQUIVALENTS_OUTSIDE) end new_regexp += str end length = RUBY_ENGINE == 'opal' ? `regexp.length` : regexp.size i = 0 while i < length char = RUBY_ENGINE == 'opal' ? `regexp[i]` : regexp[i] capture = true if escaping escaping = false if char == 'A' || char == 'z' string_based_regexp = true elsif char == 'p' || char == 'P' unicode_character_class = 1 end elsif char == '\\' escaping = true elsif depth == 0 && char == '.' && ruby_multiline # If user has specified //m modifier, it means it's expected for '.' to match # any character, including newlines char = '[\s\S]' elsif depth == 0 && (char == '^' || char == '$') # Line based regexp line_based_regexp = true elsif char == '[' depth += 1 # Skip additional ['s. This is important for expressions, that are valid in Ruby # like [[[:alnum:]]_] capture = false if depth > 1 elsif char == ']' # Skip additional ]'s capture = false if depth > 1 if depth <= 0 # Re-add a [, since it is possible for that to happen. str = '[' + str depth = 0 end depth -= 1 elsif char == '{' # escape { to \\{ unless it belongs to # a unicode character class \p{...} or \P{...} or # a quantifier x{1}, x{1,} or x{1,2} if unicode_character_class == 1 # look behind prev_chars = RUBY_ENGINE == 'opal' ? `regexp.slice(i-2)` : regexp[i - 2..i - 1] if prev_chars == '\\p' || prev_chars == '\\P' unicode_character_class = 2 else unicode_character_class = false char = '\\{' end elsif i > 0 # look forward tail = RUBY_ENGINE == 'opal' ? `regexp.slice(i+1)` : regexp[i + 1..] if tail =~ /\A\d+(,|)\d*}/ quantifier = true else char = '\\{' end else unicode_character_class = false quantifier = false char = '\\{' end elsif char == '}' # escape } to \\} unless it belongs to # a unicode character class \p{...} or \P{...} or # a quantifier x{1}, x{1,} or x{1,2} if unicode_character_class == 2 unicode_character_class = false elsif quantifier quantifier = false else unicode_character_class = false quantifier = false char = '\\}' end end str += char if capture curr_inside = inside inside = depth > 0 # Switching a token if curr_inside != inside # Since we are outside, let's apply a transformation apply_outside_transform.call str = '' end i += 1 end apply_outside_transform.call # Set multiline flag to denote that ^ and $ should match both at borders of file # and at the borders of line. This will break if both \A and ^ are used in a single # regexp. flags = add_flag(flags, 'm') if line_based_regexp # Let's check for this case and warn appropriately if line_based_regexp && string_based_regexp warn "warning: Both \\A or \\z and ^ or $ used in a regexp #{original_regexp.inspect}. In Opal this will cause undefined behavior." end [new_regexp, flags] end if RUBY_ENGINE == 'opal' # rubocop: disable Lint/UnusedMethodArgument # Optimized version of helper functions, skipping the entire String#gsub shenanigans # and allowing to be used early in the bootstage. def transform_regexp_by_re_and_hash(regexp, transformer, hash) %x{ return regexp.replace(transformer, function(i) { return hash.get(i) || i; }); } end def add_flag(flags, flag) `flags.includes(flag) ? flags : flags + flag` end def remove_flag(flags, flag) `flags.replace(flag, '')` end # Are we sure the regexp is not using UTF-16 features? # This is a crude check. def simple_regexp?(regexp) `/^(\\[dnrtAzZ\\]|\(\?[:!]|[\w\s(){}|?+*@^$-])*$/.test(regexp)` end def include?(str, needle) `str.includes(needle)` end # rubocop:disable Style/MutableConstant ESCAPES_REGEXP = `/(\\.|\[:[a-z]*:\])/g` OUTSIDE_ESCAPES_REGEXP = `/(\\.)/g` # rubocop:enable Style/MutableConstant, Lint/UnusedMethodArgument else private def transform_regexp_by_re_and_hash(regexp, transformer, hash) regexp.gsub(transformer) do |i| hash[i] || i end end def add_flag(flags, flag) flags.include?(flag) ? flags : flags + flag end def remove_flag(flags, flag) flags.sub(flag, '') end # Are we sure the regexp is not using UTF-16 features? # TODO: This is a crude check. Revisit in the future. def simple_regexp?(regexp) /\A(\\[dnrtAzZ\\]|\(\?[:!]|[\w\s(){}|?+*@^$-])*\z/.match?(regexp) end def include?(str, needle) str.include?(needle) end ESCAPES_REGEXP = /(\\.|\[:[a-z]*:\])/ OUTSIDE_ESCAPES_REGEXP = /(\\.)/ end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli.rb
lib/opal/cli.rb
# frozen_string_literal: true require 'opal/requires' require 'opal/builder' require 'opal/cli_runners' require 'opal/exe_compiler' require 'stringio' module Opal class CLI attr_reader :options, :file, :compiler_options, :evals, :load_paths, :argv, :output, :requires, :rbrequires, :gems, :stubs, :verbose, :runner_options, :preload, :debug, :no_exit, :lib_only, :missing_require_severity, :filename, :stdin, :no_cache class << self attr_accessor :stdout end class Evals < StringIO def to_path '-e' end end def initialize(options = nil) options ||= {} # Runner @runner_type = options.delete(:runner) || :nodejs @runner_options = options.delete(:runner_options) || {} @options = options @sexp = options.delete(:sexp) @repl = options.delete(:repl) @no_exit = options.delete(:no_exit) @lib_only = options.delete(:lib_only) @argv = options.delete(:argv) { [] } @evals = options.delete(:evals) { [] } @load_paths = options.delete(:load_paths) { [] } @gems = options.delete(:gems) { [] } @stubs = options.delete(:stubs) { [] } @preload = options.delete(:preload) { [] } @output = options.delete(:output) { self.class.stdout || $stdout } @verbose = options.delete(:verbose) { false } @debug = options.delete(:debug) { false } @requires = options.delete(:requires) { [] } @rbrequires = options.delete(:rbrequires) { [] } @no_cache = options.delete(:no_cache) { false } @stdin = options.delete(:stdin) { $stdin } @dce = options.delete(:dce) { false } @exe_type = options.delete(:exe_type) @debug_source_map = options.delete(:debug_source_map) { false } @missing_require_severity = options.delete(:missing_require_severity) { Opal::Config.missing_require_severity } @requires.unshift('opal') unless options.delete(:skip_opal_require) @compiler_options = compiler_option_names.map do |option| key = option.to_sym next unless options.key? key value = options.delete(key) [key, value] end.compact.to_h # directory is both a runner and compiler option @directory = @compiler_options[:directory] @runner_options[:directory] = @directory @output = File.open(@output, 'w') if @output.is_a?(String) && !@directory @compiler_options[:cache_fragments] = true if @dce if @lib_only raise ArgumentError, 'no libraries to compile' if @requires.empty? raise ArgumentError, "can't accept evals, file, or extra arguments in `library only` mode" if @argv.any? || @evals.any? elsif @evals.any? @filename = '-e' @file = Evals.new(@evals.join("\n")) elsif @argv.first && @argv.first != '-' @filename = @argv.shift @file = File.open(@filename) else @filename = @argv.shift || '-' @file = @stdin end raise ArgumentError, "unknown options: #{options.inspect}" unless @options.empty? end def run return show_sexp if @sexp return debug_source_map if @debug_source_map return run_repl if @repl rbrequires.each { |file| require file } runner = self.runner # Some runners may need to use a dynamic builder, that is, # a builder that will try to build the entire package every time # a page is loaded - for example a Server runner that needs to # rerun if files are changed. builder = proc { create_builder } @exit_status = runner.call( options: runner_options, output: output, argv: argv, builder: builder, ) if @exe_type && exit_status == 0 @exit_status = Opal::ExeCompiler.compile_exe(@exe_type, output) end @exit_status end def runner CliRunners[@runner_type] || raise(ArgumentError, "unknown runner: #{@runner_type.inspect}") end def run_repl require 'opal/repl' repl = REPL.new(@runner_type) repl.run(argv) end attr_reader :exit_status def create_builder builder = Opal::Builder.new( stubs: stubs, compiler_options: compiler_options, missing_require_severity: missing_require_severity, dce: @dce, ) # --no-cache builder.cache = Opal::Cache::NullCache.new if no_cache # --include builder.append_paths(*load_paths) # --gem gems.each { |gem_name| builder.use_gem gem_name } # --require requires.each { |required| builder.build(required, requirable: true, load: true) } # --preload preload.each { |path| builder.build_require(path) } # --verbose builder.build_str '$VERBOSE = true', '(flags)', no_export: true if verbose # --debug builder.build_str '$DEBUG = true', '(flags)', no_export: true if debug # --eval / stdin / file source = evals_or_file_source builder.build_str(source, filename) if source # --no-exit builder.build_str '::Kernel.exit', '(exit)', no_export: true unless no_exit builder end def show_sexp source = evals_or_file_source or return # rubocop:disable Style/AndOr buffer = ::Opal::Parser::SourceBuffer.new(filename) buffer.source = source sexp = Opal::Parser.default_parser.parse(buffer) output.puts sexp.inspect end def debug_source_map source = evals_or_file_source or return # rubocop:disable Style/AndOr compiler = Opal::Compiler.new(source, file: filename, **compiler_options) compiler.compile b64 = [ compiler.result, compiler.source_map.to_json, evals_or_file_source, ].map { |i| Base64.strict_encode64(i) }.join(',') output.puts "https://sokra.github.io/source-map-visualization/#base64,#{b64}" end def compiler_option_names %w[ method_missing arity_check dynamic_require_severity source_map_enabled irb_enabled inline_operators enable_source_location enable_file_source_embed use_strict parse_comments esm directory await ] end # Internal: Yields a string of source code and the proper filename for either # evals, stdin or a filepath. def evals_or_file_source return if lib_only # --library return @cached_content if @cached_content unless file.tty? begin file.rewind can_read_again = true rescue Errno::ESPIPE # rubocop:disable Lint/HandleExceptions # noop end end if @cached_content.nil? || can_read_again if RUBY_ENGINE == 'truffleruby' # bug in truffleruby when calling: File.file?(file) # <internal:core> core/type.rb:280:in `convert_type': no implicit conversion of nil into String (TypeError) content = file.read else # On MacOS file.read is not enough to pick up changes, probably due to some # cache or buffer, unclear if coming from ruby or the OS. content = File.file?(file) ? File.read(file) : file.read end end @cached_content ||= content unless can_read_again content end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/config.rb
lib/opal/config.rb
# frozen_string_literal: true require 'set' module Opal module Config extend self private def config_options @config_options ||= {} end # Defines a new configuration option # # @param [String] name the option name # @param [Object] default_value the option's default value # @!macro [attach] property # @!attribute [rw] $1 def config_option(name, default_value, options = {}) compiler = options.fetch(:compiler_option, nil) valid_values = options.fetch(:valid_values, [true, false]) config_options[name] = { default: default_value, compiler: compiler } define_singleton_method(name) { config.fetch(name, default_value) } define_singleton_method("#{name}=") do |value| unless valid_values.any? { |valid_value| valid_value === value } raise ArgumentError, "Not a valid value for option #{self}.#{name}, provided #{value.inspect}. "\ "Must be #{valid_values.inspect} === #{value.inspect}" end config[name] = value end end public # @return [Hash] the default configuration def default_config default_config = {} config_options.each do |name, options| default_value = options.fetch(:default) default_value = Proc === default_value ? default_value.call : default_value default_config[name] = default_value end default_config end # @return [Hash] the configuration for Opal::Compiler def compiler_options compiler_options = {} config_options.each do |name, options| compiler_option_name = options.fetch(:compiler) compiler_options[compiler_option_name] = config.fetch(name) end compiler_options end # @return [Hash] the current configuration, defaults to #default_config def config @config ||= default_config end # Resets the config to its default value # # @return [void] def reset! @config = nil end # Enable method_missing support. # # @return [true, false] config_option :method_missing_enabled, true, compiler_option: :method_missing # Enable const_missing support. # # @return [true, false] config_option :const_missing_enabled, true, compiler_option: :const_missing # Enable arity check on the arguments passed to methods, procs and lambdas. # # @return [true, false] config_option :arity_check_enabled, false, compiler_option: :arity_check # Add stubs for methods related to freezing objects (for compatibility). # # @return [true, false] config_option :freezing_stubs_enabled, true, compiler_option: :freezing # Build ECMAScript modules, instead of legacy JS # # @return [true, false] config_option :esm, false, compiler_option: :esm # Build a program as a directory; don't bundle # # @return [true, false] config_option :directory, false, compiler_option: :directory # Set the error severity for when a require can't be parsed at compile time. # # @example # # Opal code # require "foo" + some_dynamic_value # # - `:error` will raise an error at compile time # - `:warning` will print a warning on stderr at compile time # - `:ignore` will skip the require silently at compile time # # @return [:error, :warning, :ignore] config_option :dynamic_require_severity, :warning, compiler_option: :dynamic_require_severity, valid_values: %i[error warning ignore] # Set the error severity for when a required file can't be found at build time. # # @example # # Opal code # require "some_non_existen_file" # # - `:error` will raise an error at compile time # - `:warning` will print a warning on stderr at compile time # - `:ignore` will skip the require silently at compile time # # @return [:error, :warning, :ignore] config_option :missing_require_severity, :error, valid_values: %i[error warning ignore] # Enable IRB support for making local variables across multiple compilations. # # @return [true, false] config_option :irb_enabled, false, compiler_option: :irb # Enable for inline operators optimizations. # # @return [true, false] config_option :inline_operators_enabled, true, compiler_option: :inline_operators # Enable source maps support. # # @return [true, false] config_option :source_map_enabled, true # Enable source location embedded for methods and procs. # # @return [true, false] config_option :enable_source_location, false, compiler_option: :enable_source_location # Enable embedding source code to be read by applications. # # @return [true, false] config_option :enable_file_source_embed, false, compiler_option: :enable_file_source_embed # A set of stubbed files that will be marked as loaded and skipped during # compilation. The value is expected to be mutated but it's ok to replace # it. # # @return [Set] config_option :stubbed_files, -> { Set.new }, valid_values: [Set] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/server.rb
lib/opal/server.rb
# frozen_string_literal: true Opal.deprecation "`require 'opal/server` and `Opal::Server` are deprecated in favor of `require 'opal/sprockets/server'` and `Opal::Sprockets::Server` (now part of the opal-sprockets gem)." require 'opal/sprockets/server' Opal::Server = Opal::Sprockets::Server
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/erb.rb
lib/opal/erb.rb
# frozen_string_literal: true require 'opal/compiler' module Opal module ERB # Compile ERB code into javascript. # # [Opal::ERB] can be used to compile [ERB] templates into javascript code. # This module uses the [Opal::Compiler] internally. # # Compiled templates, when run in a javascript environment, will appear # under the `Template` namespace, and can be accessed as: # # Template['template_name'] # => template instance # # @example # # source = "<div><%= @content %></div>" # # Opal::ERB.compile source, "my_template.erb" # # @param source [String] erb content # @param file_name [String] filename for reference in template # @return [String] javascript code # def self.compile(source, file_name = '(erb)') Compiler.new(source, file_name).compile end class Compiler BLOCK_EXPR = /\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/.freeze def initialize(source, file_name = '(erb)') @source, @file_name, @result = source, file_name, source end def prepared_source @prepared_source ||= begin source = @source source = fix_quotes(source) source = find_contents(source) source = find_code(source) source = wrap_compiled(source) source = require_erb(source) source end end def compile Opal.compile prepared_source end def fix_quotes(result) result.gsub '"', '\\"' end def require_erb(result) 'require "erb";' + result end def find_contents(result) result.gsub(/<%=([\s\S]+?)%>/) do inner = Regexp.last_match(1).gsub(/\\'/, "'").gsub(/\\"/, '"') if inner =~ BLOCK_EXPR "\")\noutput_buffer.append= #{inner}\noutput_buffer.append(\"" else "\")\noutput_buffer.append=(#{inner})\noutput_buffer.append(\"" end end end def find_code(result) result.gsub(/<%([\s\S]+?)%>/) do inner = Regexp.last_match(1).gsub(/\\"/, '"') "\")\n#{inner}\noutput_buffer.append(\"" end end def wrap_compiled(result) path = @file_name.sub(/\.opalerb#{REGEXP_END}/, '') "Template.new('#{path}') do |output_buffer|\noutput_buffer.append(\"#{result}\")\noutput_buffer.join\nend\n" end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/builder.rb
lib/opal/builder.rb
# frozen_string_literal: true require 'opal/path_reader' require 'opal/paths' require 'opal/config' require 'opal/cache' require 'opal/builder/scheduler' require 'opal/project' require 'opal/builder/directory' require 'opal/builder/post_processor' require 'set' module Opal class Builder # The registered processors def self.processors @processors ||= [] end # All the extensions supported by registered processors def self.extensions @extensions ||= [] end # @public # Register a builder processor and the supported extensions. # A processor will respond to: # # ## `#requires` # An array of string containing the logic paths of required assets # # ## `#required_trees` # An array of string containing the logic paths of required directories # # ## `#autoloads` # An array of entities that are autoloaded and their compile-time load failure can # be safely ignored # # ## `#to_s` # The processed source # # ## `#source_map` # An instance of `::Opal::SourceMap::File` representing the processd asset's source # map. # # ## `.new(source, filename, compiler_options)` # The processor will be instantiated passing: # - the unprocessed source # - the asset's filename # - Opal's compiler options # # ## `.match?(path)` # The processor is able to recognize paths suitable for its type of # processing. # def self.register_processor(processor, processor_extensions) return if processors.include?(processor) processors << processor processor_extensions.each { |ext| extensions << ext } end class MissingRequire < LoadError end class ProcessorNotFound < LoadError end def initialize(options = nil) (options || {}).each_pair do |k, v| public_send("#{k}=", v) end @stubs ||= [] @processors ||= ::Opal::Builder.processors @path_reader ||= PathReader.new(Opal.paths, extensions.map { |e| [".#{e}", ".js.#{e}"] }.flatten) @compiler_options ||= Opal::Config.compiler_options @missing_require_severity ||= Opal::Config.missing_require_severity @cache ||= Opal.cache @scheduler ||= Opal.builder_scheduler if @scheduler.respond_to? :new @scheduler = @scheduler.new(self) end @processed = [] end def self.build(*args, &block) new.build(*args, &block) end def build(path, options = {}) build_str(source_for(path), path, options) end # Retrieve the source for a given path the same way #build would do. def source_for(path) read(path, false) end def build_str(source, rel_path, options = {}) return if source.nil? abs_path = expand_path(rel_path) setup_project(abs_path) rel_path = expand_ext(rel_path) asset = processor_for(source, rel_path, abs_path, false, options) requires = asset.requires + tree_requires(asset, abs_path) # Don't automatically load modules required by the module process_requires(rel_path, requires, asset.autoloads, options.merge(load: false)) processed << asset self end def build_require(path, options = {}) process_require(path, [], options) end def initialize_copy(other) super @stubs = other.stubs.dup @processors = other.processors.dup @path_reader = other.path_reader.dup @projects = other.projects.dup @compiler_options = other.compiler_options.dup @missing_require_severity = other.missing_require_severity.to_sym @processed = other.processed.dup @scheduler = other.scheduler.dup.tap { |i| i.builder = self } end def to_s postprocessed.map(&:to_s).join("\n") end def source_map ::Opal::SourceMap::Index.new(postprocessed.map(&:source_map), join: "\n") end def append_paths(*paths) paths.each { |i| setup_project(i) } path_reader.append_paths(*paths) end def process_require_threadsafely(rel_path, autoloads, options) autoload = autoloads.include? rel_path source = stub?(rel_path) ? '' : read(rel_path, autoload) # The handling is delegated to the runtime return if source.nil? abs_path = expand_path(rel_path) rel_path = expand_ext(rel_path) asset = processor_for(source, rel_path, abs_path, autoload, options.merge(requirable: true)) process_requires( rel_path, asset.requires + tree_requires(asset, abs_path), asset.autoloads, options ) asset end def process_require(rel_path, autoloads, options) return if already_processed.include?(rel_path) already_processed << rel_path asset = process_require_threadsafely(rel_path, autoloads, options) processed << asset if asset end def already_processed @already_processed ||= Set.new end include Project::Collection include Builder::Directory attr_reader :processed def postprocessed @postprocessed ||= PostProcessor.call(processed, self) end attr_accessor :processors, :path_reader, :stubs, :dce, :compiler_options, :missing_require_severity, :cache, :scheduler alias dce? dce def esm? @compiler_options[:esm] end # Output extension, to be used by runners. At least Node.JS switches # to ESM mode only if the extension is "mjs" def output_extension if esm? 'mjs' else 'js' end end # Return a list of dependent files, for watching purposes def dependent_files processed.map(&:abs_path).compact.select { |fn| File.exist?(fn) } end def expand_ext(path) abs_path = path_reader.expand(path) if abs_path File.join( File.dirname(path), File.basename(abs_path) ) else path end end # Output method #compiled_source aims to replace #to_s def compiled_source(with_source_map: true) compiled_source = to_s compiled_source += "\n" + source_map.to_data_uri_comment if with_source_map compiled_source end private def process_requires(rel_path, requires, autoloads, options) @scheduler.process_requires(rel_path, requires, autoloads, options) end def tree_requires(asset, asset_path) dirname = asset_path.to_s.empty? ? Pathname.pwd : Pathname(asset_path).expand_path.dirname abs_base_paths = path_reader.paths.map { |p| File.expand_path(p) } asset.required_trees.flat_map do |tree| abs_tree_path = dirname.join(tree).expand_path.to_s abs_base_path = abs_base_paths.find { |p| abs_tree_path.start_with?(p) } if abs_base_path abs_base_path = Pathname(abs_base_path) entries_glob = Pathname(abs_tree_path).join('**', "*{.js,}.{#{extensions.join ','}}") Pathname.glob(entries_glob).map { |file| file.relative_path_from(abs_base_path).to_s } else [] # the tree is not part of any known base path end end end def processor_for(source, rel_path, abs_path, autoload, options) processor = processors.find { |p| p.match? abs_path } if !processor && !autoload raise(ProcessorNotFound, "can't find processor for rel_path: " \ "#{rel_path.inspect}, "\ "abs_path: #{abs_path.inspect}, "\ "source: #{source.inspect}, "\ "processors: #{processors.inspect}" ) end options = options.merge(cache: cache) processor.new(source, rel_path, abs_path, @compiler_options.merge(options)) end def read(path, autoload) path_reader.read(path) || begin print_list = ->(list) { "- #{list.join("\n- ")}\n" } message = "can't find file: #{path.inspect} in:\n" + print_list[path_reader.paths] + "\nWith the following projects loaded:\n" + print_list[all_projects.map(&:root_dir)] + "\nWith the following extensions:\n" + print_list[path_reader.extensions] + "\nAnd the following processors:\n" + print_list[processors] unless autoload case missing_require_severity when :error then raise MissingRequire, message when :warning then warn 'Warning: ' + message when :ignore then # noop end end nil end end def expand_path(path) return if stub?(path) (path_reader.expand(path) || File.expand_path(path)).to_s end def stub?(path) stubs.include?(path) end def extensions ::Opal::Builder.extensions end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/source_map.rb
lib/opal/source_map.rb
# frozen_string_literal: true module Opal # To generate the source map for a single file use Opal::SourceMap::File. # To combine multiple files the Opal::SourceMap::Index should be used. module SourceMap autoload :Map, 'opal/source_map/map' autoload :File, 'opal/source_map/file' autoload :Index, 'opal/source_map/index' autoload :VLQ, 'opal/source_map/vlq' end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cache.rb
lib/opal/cache.rb
# frozen_string_literal: true require 'opal/paths' require 'digest/sha2' unless RUBY_ENGINE == 'opal' if RUBY_ENGINE != 'opal' require 'opal/cache/file_cache' end module Opal # A Sprockets-compatible cache, for example an instance of # Opal::Cache::FileCache or Opal::Cache::NullCache. singleton_class.attr_writer :cache def self.cache @cache ||= if RUBY_ENGINE == 'opal' || ENV['OPAL_CACHE_DISABLE'] || !Cache::FileCache.find_dir Cache::NullCache.new else Cache::FileCache.new end end module Cache class NullCache def fetch(*) yield end end module_function def fetch(cache, key, &block) # Extension to the Sprockets API of Cache, if a cache responds # to #fetch, then we call it instead of using #get and #set. return cache.fetch(key, &block) if cache.respond_to? :fetch key = digest(key.join('/')) + '-' + runtime_key data = cache.get(key) data || begin compiler = yield cache.set(key, compiler) unless compiler.dynamic_cache_result compiler end end def runtime_key @runtime_key ||= begin files = Opal.dependent_files digest [ files.sort.map { |f| "#{f}:#{File.size(f)}:#{File.mtime(f).to_f}" }, RUBY_VERSION, RUBY_PATCHLEVEL ].join('/') end end def digest(string) ::Digest::SHA256.hexdigest(string)[-32..-1].to_i(16).to_s(36) end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/util.rb
lib/opal/util.rb
# frozen_string_literal: true require 'open3' module Opal module Util extend self ExitStatusError = Class.new(StandardError) # Used for uglifying source to minify. # # Opal::Util.uglify("javascript contents") # # @param str [String] string to minify # @return [String] def uglify(source, mangle: false) sh "#{'ruby ' if Gem.win_platform?}bin/yarn --silent run terser -c #{'-m' if mangle}", data: source end # Gzip code to check file size. def gzip(source) sh 'gzip -f', data: source end private def sh(command, data:) out, _err, status = Open3.capture3(command, stdin_data: data) raise ExitStatusError, "exited with status #{status.exitstatus}" unless status.success? out end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/magic_comments.rb
lib/opal/magic_comments.rb
# frozen_string_literal: true module Opal::MagicComments MAGIC_COMMENT_RE = /\A# *(\w+) *: *(\S+.*?) *\z/.freeze EMACS_MAGIC_COMMENT_RE = /\A# *-\*- *(\w+) *: *(\S+.*?) *-\*- *\z/.freeze def self.parse(sexp, comments) flags = {} # We have an upper limit at the first line of code if sexp first_line = sexp.loc.line comments = comments.take(first_line) end comments.each do |comment| next if first_line && comment.loc.line >= first_line if (parts = comment.text.scan(MAGIC_COMMENT_RE)).any? || (parts = comment.text.scan(EMACS_MAGIC_COMMENT_RE)).any? parts.each do |key, value| flags[key.to_sym] = case value when 'true' then true when 'false' then false else value end end end end flags end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/opal_engine_check.rb
lib/opal/rewriters/opal_engine_check.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters class OpalEngineCheck < Base def on_if(node) test, true_body, false_body = *node.children if (values = engine_check?(test)) if positive_engine_check?(*values) process(true_body || s(:nil)) else process(false_body || s(:nil)) end else super end end def engine_check?(test) # Engine check must look like this: s(:send, recvr, method, arg) return false unless test.type == :send && test.children.length == 3 recvr, method, arg = *test.children # Ensure that the recvr is present return false unless recvr # Enhance the check to: s(:send, s(:const, X, Y), :==/:!=, s(:str, Z)) return false unless recvr.type == :const return false unless arg.type == :str return false unless %i[== !=].include? method # Ensure that checked const is either RUBY_ENGINE or RUBY_PLATFORM const_name = recvr.children[1] return false unless %i[RUBY_ENGINE RUBY_PLATFORM].include? const_name # Return a truthy value [method, arg.children.first] end def positive_engine_check?(method, const_value) (method == :==) ^ (const_value != 'opal') end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/returnable_logic.rb
lib/opal/rewriters/returnable_logic.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters class ReturnableLogic < Base def next_tmp @counter ||= 0 @counter += 1 "$ret_or_#{@counter}" end def free_tmp @counter -= 1 end def reset_tmp_counter! @counter = nil end def on_if(node) test, = *node.children check_control_flow!(test) # The if_test metadata signifies that we don't care about the return value except if it's # truthy or falsy. And those tests will be carried out by the respective $truthy helper calls. test.meta[:if_test] = true if test super end def on_case(node) lhs, *whens, els = *node.children els ||= s(:nil) lhs_tmp = next_tmp if lhs out = build_if_from_when(node, lhs, lhs_tmp, whens, els) free_tmp if lhs out end # `a || b` / `a or b` def on_or(node) lhs, rhs = *node.children check_control_flow!(lhs) if node.meta[:if_test] # Let's forward the if_test to the lhs and rhs - since we don't care about the exact return # value of our or, we neither do care about a return value of our lhs or rhs. lhs.meta[:if_test] = rhs.meta[:if_test] = true out = process(node.updated(:if, [lhs, s(:true), rhs])) else lhs_tmp = next_tmp out = process(node.updated(:if, [s(:lvasgn, lhs_tmp, lhs), s(:js_tmp, lhs_tmp), rhs])) free_tmp end out end # `a && b` / `a and b` def on_and(node) lhs, rhs = *node.children check_control_flow!(lhs) if node.meta[:if_test] lhs.meta[:if_test] = rhs.meta[:if_test] = true out = process(node.updated(:if, [lhs, rhs, s(:false)])) else lhs_tmp = next_tmp out = process(node.updated(:if, [s(:lvasgn, lhs_tmp, lhs), rhs, s(:js_tmp, lhs_tmp)])) free_tmp end out end # Parser sometimes generates parentheses as a begin node. If it's a single node begin value, then # let's forward the if_test metadata. def on_begin(node) if node.meta[:if_test] && node.children.count == 1 node.children.first.meta[:if_test] = true end node.meta.delete(:if_test) super end private def check_control_flow!(node) case node.type when :break, :next, :redo, :retry, :return error 'void value expression' end end def build_if_from_when(node, lhs, lhs_tmp, whens, els) first_when, *next_whens = *whens *parts, expr = *first_when.children rule = build_rule_from_parts(node, lhs, lhs_tmp, parts) first_when.updated(:if, [rule, process(expr), next_whens.empty? ? process(els) : build_if_from_when(nil, nil, lhs_tmp, next_whens, els)]) end def build_rule_from_parts(node, lhs, lhs_tmp, parts) lhs = if node && lhs_tmp node.updated(:lvasgn, [lhs_tmp, process(lhs)]) else s(:js_tmp, lhs_tmp) end first_part, *next_parts = *parts subrule = if first_part.type == :splat splat_on = first_part.children.first iter_val = next_tmp block = s(:send, process(splat_on), :any?, s(:iter, s(:args, s(:arg, iter_val)), build_rule_from_parts(nil, nil, lhs_tmp, [s(:lvar, iter_val)]) ) ) if node && lhs_tmp s(:begin, lhs, block) else block end elsif lhs_tmp s(:send, process(first_part), :===, lhs) else process(first_part) end if next_parts.empty? subrule else s(:if, subrule, s(:true), build_rule_from_parts(nil, nil, lhs_tmp, next_parts)) end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/for_rewriter.rb
lib/opal/rewriters/for_rewriter.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters class ForRewriter < Base def self.reset_tmp_counter! @counter = 0 end def self.next_tmp @counter ||= 0 @counter += 1 :"$for_tmp#{@counter}" end # Handles # for i in 0..3; j = i + 1; end # # The problem here is that in Ruby for loop makes its # loop variable + all local variables available outside. # I.e. after this loop variable `i` is 3 and `j` is 4 # # This class rewrites it to the following code: # j = nil # i = nil # (0..3).each { |__jstmp| i = __jstmp; j = i + 1 } # # Complex stuff with multiple loop variables: # for i, j in [[1, 2], [3, 4]]; end # Becomes multiple left-hand assignment: # i = nil # j = nil # [[1, 2], [3, 4]].each { |__jstmp| i, j = __jstmp } # def on_for(node) loop_variable, loop_range, loop_body = *node # Declare local variables used in the loop and the loop body at the outer scope outer_assignments = generate_outer_assignments(loop_variable, loop_body) # Generate temporary loop variable tmp_loop_variable = self.class.next_tmp get_tmp_loop_variable = s(:js_tmp, tmp_loop_variable) # Assign the loop variables in the loop body loop_body = prepend_to_body(loop_body, assign_loop_variable(loop_variable, get_tmp_loop_variable)) # Transform the for-loop into each-loop with updated loop body node = transform_for_to_each_loop(node, loop_range, tmp_loop_variable, loop_body) node.updated(:begin, [*outer_assignments, node]) end private def generate_outer_assignments(loop_variable, loop_body) loop_local_vars = LocalVariableAssigns.find(loop_variable) body_local_vars = LocalVariableAssigns.find(loop_body) (loop_local_vars + body_local_vars).map { |lvar_name| s(:lvdeclare, lvar_name) } end def assign_loop_variable(loop_variable, tmp_loop_variable) case loop_variable.type when :mlhs # multiple left-hand statement like in "for i,j in [[1, 2], [3, 4]]" loop_variable.updated(:masgn, [loop_variable, tmp_loop_variable]) else # single argument like "for i in (0..3)" loop_variable << tmp_loop_variable end end # rubocop:disable Layout/MultilineMethodCallBraceLayout,Layout/MultilineArrayBraceLayout def transform_for_to_each_loop(node, loop_range, tmp_loop_variable, loop_body) node.updated(:send, [loop_range, :each, # (0..3).each { node.updated(:iter, [s(:args, s(:arg, tmp_loop_variable)), # |__jstmp| process(loop_body) # i = __jstmp; j = i + 1 } ])]) end # rubocop:enable Layout/MultilineMethodCallBraceLayout,Layout/MultilineArrayBraceLayout class LocalVariableAssigns < Base attr_reader :result def self.find(node) processor = new processor.process(node) processor.result.to_a end def initialize @result = Set.new end def on_lvasgn(node) name, _ = *node result << name super end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/logical_operator_assignment.rb
lib/opal/rewriters/logical_operator_assignment.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters class LogicalOperatorAssignment < Base def self.reset_tmp_counter! @@counter = 0 end def self.new_temp @@counter ||= 0 @@counter += 1 :"$logical_op_recvr_tmp_#{@@counter}" end GET_SET = ->(get_type, set_type) { ->(lhs, rhs, root_type) { get_node = lhs.updated(get_type) # lhs condition_node = s(root_type, get_node, rhs) # lhs || rhs if %i[const cvar].include?(get_type) && root_type == :or # defined?(lhs) defined_node = s(:defined?, get_node) # LHS = defined?(LHS) ? (LHS || rhs) : rhs condition_node = s(:if, defined_node, s(:begin, condition_node), rhs) end lhs.updated(set_type, [*lhs, condition_node]) # lhs = lhs || rhs } } # Takes `lhs ||= rhs` # Produces `lhs = lhs || rhs` LocalVariableHandler = GET_SET[:lvar, :lvasgn] # Takes `@lhs ||= rhs` # Produces `@lhs = @lhs || rhs` InstanceVariableHandler = GET_SET[:ivar, :ivasgn] # Takes `LHS ||= rhs` # Produces `LHS = defined?(LHS) ? (LHS || rhs) : rhs` # # Takes `LHS &&= rhs` # Produces `LHS = LHS && rhs` ConstantHandler = GET_SET[:const, :casgn] # Takes `$lhs ||= rhs` # Produces `$lhs = $lhs || rhs` GlobalVariableHandler = GET_SET[:gvar, :gvasgn] # Takes `@@lhs ||= rhs` # Produces `@@lhs = defined?(@@lhs) ? (@@lhs || rhs) : rhs` # # Takes `@@lhs &&= rhs` # Produces `@@lhs = @@lhs && rhs` ClassVariableHandler = GET_SET[:cvar, :cvasgn] # Takes `recvr.meth ||= rhs` # Produces `recvr.meth || recvr.meth = rhs` # (lhs is a recvr.meth) class SendHandler < self def self.call(lhs, rhs, root_type) recvr, reader_method, *args = *lhs # If recvr is a complex expression it must be cached. # MRI calls recvr in `recvr.meth ||= rhs` only once. if recvr && recvr.type == :send recvr_tmp = new_temp cache_recvr = s(:lvasgn, recvr_tmp, recvr) # $tmp = recvr recvr = s(:js_tmp, recvr_tmp) end writer_method = :"#{reader_method}=" call_reader = lhs.updated(:send, [recvr, reader_method, *args]) # $tmp.meth call_writer = lhs.updated(:send, [recvr, writer_method, *args, rhs]) # $tmp.meth = rhs get_or_set = s(root_type, call_reader, call_writer) if cache_recvr s(:begin, cache_recvr, get_or_set) else get_or_set end end end # Takes `recvr&.meth ||= rhs` # Produces `recvr.nil? ? nil : recvr.meth ||= rhs` # NOTE: Later output of this handler gets post-processed by this rewriter again # using SendHandler to `recvr.nil? ? nil : (recvr.meth || recvr.meth = rhs)` class ConditionalSendHandler < self def self.call(lhs, rhs, root_type) root_type = :"#{root_type}_asgn" recvr, meth, *args = *lhs recvr_tmp = new_temp cache_recvr = s(:lvasgn, recvr_tmp, recvr) # $tmp = recvr recvr = s(:js_tmp, recvr_tmp) recvr_is_nil = s(:send, recvr, :nil?) # recvr.nil? plain_send = lhs.updated(:send, [recvr, meth, *args]) # recvr.meth plain_or_asgn = s(root_type, plain_send, rhs) # recvr.meth ||= rhs s(:begin, cache_recvr, s(:if, recvr_is_nil, # if recvr.nil? s(:nil), # nil # else plain_or_asgn # recvr.meth ||= rhs ), ) # end end end HANDLERS = { lvasgn: LocalVariableHandler, ivasgn: InstanceVariableHandler, casgn: ConstantHandler, gvasgn: GlobalVariableHandler, cvasgn: ClassVariableHandler, send: SendHandler, csend: ConditionalSendHandler }.freeze # lhs ||= rhs def on_or_asgn(node) lhs, rhs = *node result = HANDLERS .fetch(lhs.type) { error "cannot handle LHS type: #{lhs.type}" } .call(lhs, rhs, :or) process(result) end # lhs &&= rhs def on_and_asgn(node) lhs, rhs = *node result = HANDLERS .fetch(lhs.type) { error "cannot handle LHS type: #{lhs.type}" } .call(lhs, rhs, :and) process(result) end ASSIGNMENT_STRING_NODE = s(:str, 'assignment') # Rewrites any or_asgn and and_asgn node like # `defined?(a ||= 1)` # and # `defined?(a &&= 1)` # to a static "assignment" string node def on_defined?(node) inner, _ = *node if %i[or_asgn and_asgn].include?(inner.type) ASSIGNMENT_STRING_NODE else super(node) end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/js_reserved_words.rb
lib/opal/rewriters/js_reserved_words.rb
# frozen_string_literal: true require 'opal/rewriters/base' require 'opal/regexp_anchors' module Opal module Rewriters class JsReservedWords < Base # Reserved javascript keywords - we cannot create variables with the # same name (ref: http://stackoverflow.com/a/9337272/601782) ES51_RESERVED_WORD = /#{REGEXP_START}(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)#{REGEXP_END}/.freeze # ES3 reserved words that aren’t ES5.1 reserved words ES3_RESERVED_WORD_EXCLUSIVE = /#{REGEXP_START}(?:int|byte|char|goto|long|final|float|short|double|native|throws|boolean|abstract|volatile|transient|synchronized)#{REGEXP_END}/.freeze # Prototype special properties. PROTO_SPECIAL_PROPS = /#{REGEXP_START}(?:constructor|displayName|__proto__|__parent__|__noSuchMethod__|__count__)#{REGEXP_END}/.freeze # Prototype special methods. PROTO_SPECIAL_METHODS = /#{REGEXP_START}(?:hasOwnProperty|valueOf)#{REGEXP_END}/.freeze # Immutable properties of the global object IMMUTABLE_PROPS = /#{REGEXP_START}(?:NaN|Infinity|undefined)#{REGEXP_END}/.freeze # Doesn't take in account utf8 BASIC_IDENTIFIER_RULES = /#{REGEXP_START}[$_a-z][$_a-z\d]*#{REGEXP_END}/i.freeze # Defining a local function like Array may break everything RESERVED_FUNCTION_NAMES = /#{REGEXP_START}(?:Array)#{REGEXP_END}/.freeze def self.valid_name?(name) BASIC_IDENTIFIER_RULES =~ name && !( ES51_RESERVED_WORD =~ name || ES3_RESERVED_WORD_EXCLUSIVE =~ name || IMMUTABLE_PROPS =~ name ) end def self.valid_ivar_name?(name) !(PROTO_SPECIAL_PROPS =~ name || PROTO_SPECIAL_METHODS =~ name) end def fix_var_name(name) self.class.valid_name?(name) ? name : "#{name}$".to_sym end def fix_ivar_name(name) self.class.valid_ivar_name?(name.to_s[1..-1]) ? name : "#{name}$".to_sym end def on_lvar(node) name, _ = *node node = node.updated(nil, [fix_var_name(name)]) super(node) end def on_lvasgn(node) name, value = *node node = if value node.updated(nil, [fix_var_name(name), value]) else node.updated(nil, [fix_var_name(name)]) end super(node) end def on_ivar(node) name, _ = *node node = node.updated(nil, [fix_ivar_name(name)]) super(node) end def on_ivasgn(node) name, value = *node node = if value node.updated(nil, [fix_ivar_name(name), value]) else node.updated(nil, [fix_ivar_name(name)]) end super(node) end # Restarg and kwrestarg are special cases # because they may have no name # def m(*, **); end def on_restarg(node) name, _ = *node if name node = node.updated(nil, [fix_var_name(name)], meta: { arg_name: name }) end node end alias on_kwrestarg on_restarg def on_argument(node) node = super(node) name, value = *node fixed_name = fix_var_name(name) new_children = value ? [fixed_name, value] : [fixed_name] node.updated(nil, new_children, meta: { arg_name: name }) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/arguments.rb
lib/opal/rewriters/arguments.rb
# frozen_string_literal: true module Opal module Rewriters class Arguments attr_reader :args, :optargs, :restarg, :postargs, :kwargs, :kwoptargs, :kwrestarg, :kwnilarg, :shadowargs, :blockarg def initialize(args) @args = [] @optargs = [] @restarg = nil @postargs = [] @kwargs = [] @kwoptargs = [] @kwrestarg = nil @kwnilarg = false @shadowargs = [] @blockarg = nil args.each do |arg| case arg.type when :arg, :mlhs (@restarg || @optargs.any? ? @postargs : @args) << arg when :optarg @optargs << arg when :restarg @restarg = arg when :kwarg @kwargs << arg when :kwoptarg @kwoptargs << arg when :kwnilarg @kwnilarg = true when :kwrestarg @kwrestarg = arg when :shadowarg @shadowargs << arg when :blockarg @blockarg = arg else raise "Unsupported arg type #{arg.type}" end end end def has_post_args? !@restarg.nil? || @postargs.any? || (has_any_kwargs? && !can_inline_kwargs?) end def has_any_kwargs? @kwargs.any? || @kwoptargs.any? || !@kwrestarg.nil? end def can_inline_kwargs? @optargs.empty? && @restarg.nil? && @postargs.empty? end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/binary_operator_assignment.rb
lib/opal/rewriters/binary_operator_assignment.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters class BinaryOperatorAssignment < Base def self.reset_tmp_counter! @@counter = 0 end def self.new_temp @@counter ||= 0 @@counter += 1 :"$binary_op_recvr_tmp_#{@@counter}" end GET_SET = ->(get_type, set_type) { ->(node, lhs, operation, rhs) { get_node = lhs.updated(get_type) # lhs set_node = node.updated(:send, [get_node, operation, rhs]) # lhs + rhs lhs.updated(set_type, [*lhs, set_node]) # lhs = lhs + rhs } } # Takes `lhs += rhs` # Produces `lhs = lhs + rhs` LocalVariableHandler = GET_SET[:lvar, :lvasgn] # Takes `@lhs += rhs` # Produces `@lhs = @lhs + rhs` InstanceVariableHandler = GET_SET[:ivar, :ivasgn] # Takes `LHS += rhs` # Produces `LHS = LHS + rhs` ConstantHandler = GET_SET[:const, :casgn] # Takes `$lhs += rhs` # Produces `$lhs = $lhs + rhs` GlobalVariableHandler = GET_SET[:gvar, :gvasgn] # Takes `@@lhs += rhs` # Produces `@@lhs = @@lhs + rhs` ClassVariableHandler = GET_SET[:cvar, :cvasgn] # Takes `recvr.meth += rhs` # Produces `recvr.meth = recvr.meth + rhs` # (lhs is a recvr.meth, op is :+) class SendHandler < self def self.call(node, lhs, operation, rhs) recvr, reader_method, *args = *lhs # If recvr is a complex expression it must be cached. # MRI calls recvr in `recvr.meth ||= rhs` only once. if recvr && recvr.type == :send recvr_tmp = new_temp cache_recvr = s(:lvasgn, recvr_tmp, recvr) # $tmp = recvr recvr = s(:js_tmp, recvr_tmp) end writer_method = :"#{reader_method}=" call_reader = lhs.updated(:send, [recvr, reader_method, *args]) # $tmp.meth call_op = node.updated(:send, [call_reader, operation, rhs]) # $tmp.meth + rhs call_writer = lhs.updated(:send, [recvr, writer_method, *args, call_op]) # $tmp.meth = $tmp.meth + rhs if cache_recvr node.updated(:begin, [cache_recvr, call_writer]) else call_writer end end end # Takes `recvr.meth += rhs` # Produces `recvr.nil? ? nil : recvr.meth += rhs` # NOTE: Later output of this handler gets post-processed by this rewriter again # using SendHandler to `recvr.nil? ? nil : (recvr.meth = recvr.meth + rhs)` class ConditionalSendHandler < self def self.call(node, lhs, operation, rhs) recvr, meth, *args = *lhs recvr_tmp = new_temp cache_recvr = s(:lvasgn, recvr_tmp, recvr) # $tmp = recvr recvr = s(:js_tmp, recvr_tmp) recvr_is_nil = s(:send, recvr, :nil?) # recvr.nil? plain_send = lhs.updated(:send, [recvr, meth, *args]) # recvr.meth plain_op_asgn = node.updated(:op_asgn, [plain_send, operation, rhs]) # recvr.meth += rhs s(:begin, cache_recvr, s(:if, recvr_is_nil, # if recvr.nil? s(:nil), # nil # else plain_op_asgn # recvr.meth ||= rhs ), ) # end end end HANDLERS = { lvasgn: LocalVariableHandler, ivasgn: InstanceVariableHandler, casgn: ConstantHandler, gvasgn: GlobalVariableHandler, cvasgn: ClassVariableHandler, send: SendHandler, csend: ConditionalSendHandler }.freeze # lhs += rhs def on_op_asgn(node) lhs, op, rhs = *node result = HANDLERS .fetch(lhs.type) { error "cannot handle LHS type: #{lhs.type}" } .call(node, lhs, op, rhs) process(result) end ASSIGNMENT_STRING_NODE = s(:str, 'assignment') # Rewrites any or_asgn and and_asgn node like # `defined?(a ||= 1)` # and # `defined?(a &&= 1)` # to a static "assignment" string node def on_defined?(node) inner, _ = *node if inner.type == :op_asgn ASSIGNMENT_STRING_NODE else super(node) end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/thrower_finder.rb
lib/opal/rewriters/thrower_finder.rb
# frozen_string_literal: true # rubocop:disable Layout/EmptyLineBetweenDefs, Style/SingleLineMethods module Opal module Rewriters # ThrowerFinder attempts to track the presence of throwers, like # break, redo, so we can make an informed guess in the early # compilation phase before traversing other nodes whether we # want to track a closure. Tracking a closure is often a deoptimizing # step, so we want to get that knowledge earlier. class ThrowerFinder < Opal::Rewriters::Base def initialize @break_stack = [] @redo_stack = [] @retry_stack = [] @rescue_else_stack = [] end def on_break(node) tracking(:break, @break_stack) super end def on_redo(node) tracking(:redo, @redo_stack) super end def on_retry(node) tracking(:retry, @retry_stack) super end def on_iter(node) pushing([@break_stack, node]) { super } end def on_loop(node, &block) pushing([@redo_stack, node], [@break_stack, nil], &block) end def on_for(node); on_loop(node) { super }; end def on_while(node); on_loop(node) { super }; end def on_while_post(node); on_loop(node) { super }; end def on_until(node); on_loop(node) { super }; end def on_until_post(node); on_loop(node) { super }; end # ignore throwers inside defined def on_defined(node) pushing( [@redo_stack, nil], [@break_stack, nil], [@retry_stack, nil] ) { super } end # In Opal we handle rescue-else either in ensure or in # rescue. If ensure is present, we handle it in ensure. # Otherwise we handle it in rescue. ensure is always # above a rescue. This logic is about tracking if a given # ensure node should expect a rescue-else inside a # rescue node. def on_ensure(node) pushing([@rescue_else_stack, node]) { super } end def on_rescue(node) if node.children[1..-1].detect { |sexp| sexp && sexp.type != :resbody } tracking(:rescue_else, @rescue_else_stack) end pushing([@rescue_else_stack, nil], [@retry_stack, node]) { super } end private def pushing(*stacks) stacks.each { |stack, node| stack.push(node) } result = yield stacks.map(&:first).each(&:pop) result end def tracking(breaker, stack) stack.last.meta[:"has_#{breaker}"] = true if stack.last end end end end # rubocop:enable Layout/EmptyLineBetweenDefs, Style/SingleLineMethods
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/inline_args.rb
lib/opal/rewriters/inline_args.rb
# frozen_string_literal: true require 'opal/rewriters/base' require 'opal/rewriters/arguments' module Opal module Rewriters # Converts # # def m( a, b = 1, *c, d, e:, f: 1, **g, &blk ) # end # # To something like # # def m( a, <fake b>, <fake c>, <fake d>, <fake kwargs>) # blk = <extract block> # $post_args = arguments[1..-1] # $kwargs = $post_args.pop # a = <enough args> ? $post_args.shift : 1 # c = <enough args> ? $post_args[0..-1] : [] # d = $post_args.last # e = $kwargs.delete(:e) # f = $kwargs.delete(:f) || 1 # g = $kwargs.except(:e, :f) # end # class InlineArgs < Base def on_def(node) node = super(node) mid, args, body = *node body ||= s(:nil) # prevent returning initialization statement initializer = Initializer.new(args, type: :def) inline_args = args.updated(nil, initializer.inline) body = prepend_to_body(body, initializer.initialization) node.updated(nil, [mid, inline_args, body]) end def on_defs(node) node = super(node) recv, mid, args, body = *node body ||= s(:nil) # prevent returning initialization statement initializer = Initializer.new(args, type: :defs) inline_args = args.updated(nil, initializer.inline) body = prepend_to_body(body, initializer.initialization) node.updated(nil, [recv, mid, inline_args, body]) end def on_iter(node) node = super(node) args, body = *node body ||= s(:nil) # prevent returning initialization statement initializer = Initializer.new(args, type: :iter) inline_args = args.updated(nil, initializer.inline) body = prepend_to_body(body, initializer.initialization) node.updated(nil, [inline_args, body]) end class Initializer < ::Opal::Rewriters::Base attr_reader :inline, :initialization STEPS = %i[ extract_blockarg initialize_shadowargs extract_args prepare_post_args prepare_kwargs extract_optargs extract_restarg extract_post_args extract_kwargs extract_kwoptargs extract_kwrestarg ].freeze def initialize(args, type:) @args = Arguments.new(args.children) @inline = [] @initialization = [] @type = type STEPS.each do |step| send(step) end if @initialization.any? @initialization = s(:begin, *@initialization) else @initialization = nil end end def extract_blockarg if (arg = @args.blockarg) @initialization << arg.updated(:extract_blockarg) end end def initialize_shadowargs @args.shadowargs.each do |arg| @initialization << arg.updated(:initialize_shadowarg) end end def extract_args @args.args.each do |arg| if @type == :iter # block args are not required, # so we need to tell compiler that required args # must be initialized with nil-s @initialization << arg.updated(:initialize_iter_arg) else # required inline def argument like 'def m(req)' # no initialization is required end @inline << arg end end def prepare_post_args if @args.has_post_args? @initialization << s(:prepare_post_args, @args.args.length) end end def prepare_kwargs return unless @args.has_any_kwargs? if @args.can_inline_kwargs? @inline << s(:arg, :'$kwargs') else @initialization << s(:extract_kwargs) @inline << s(:fake_arg) end @initialization << s(:ensure_kwargs_are_kwargs) end def extract_kwargs @args.kwargs.each do |arg| @initialization << arg.updated(:extract_kwarg) end end def extract_kwoptargs @args.kwoptargs.each do |arg| @initialization << arg.updated(:extract_kwoptarg) end end def extract_kwrestarg if (arg = @args.kwrestarg) @initialization << arg.updated(:extract_kwrestarg) end end def extract_post_args # post arguments must be extracted with an offset @args.postargs.each do |arg| @initialization << arg.updated(:extract_post_arg) @inline << s(:fake_arg) end end def extract_optargs has_post_args = @args.has_post_args? @args.optargs.each do |arg| if has_post_args # optional post argument like 'def m(opt = 1, a)' arg_name, default_value = *arg @initialization << arg.updated(:extract_post_optarg, [arg_name, default_value, args_to_keep]) @inline << s(:fake_arg) else # optional inline argument like 'def m(a, opt = 1)' @inline << arg.updated(:arg) @initialization << arg.updated(:extract_optarg) end end end def extract_restarg if (arg = @args.restarg) arg_name = arg.children[0] @initialization << arg.updated(:extract_restarg, [arg_name, args_to_keep]) @inline << s(:fake_arg) end end def args_to_keep @args.postargs.length end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/base.rb
lib/opal/rewriters/base.rb
# frozen_string_literal: true require 'parser' require 'opal/ast/node' module Opal module Rewriters class Base < ::Parser::AST::Processor class DummyLocation def node=(*) # stub end def expression self end def begin_pos 0 end def end_pos 0 end def source '' end def line 0 end def column 0 end def last_line Float::INFINITY end end DUMMY_LOCATION = DummyLocation.new def s(type, *children) loc = current_node ? current_node.loc : DUMMY_LOCATION ::Opal::AST::Node.new(type, children, location: loc) end def self.s(type, *children) ::Opal::AST::Node.new(type, children, location: DUMMY_LOCATION) end alias on_iter process_regular_node alias on_zsuper process_regular_node alias on_jscall on_send alias on_jsattr process_regular_node alias on_jsattrasgn process_regular_node alias on_kwsplat process_regular_node # Prepends given +node+ to +body+ node. # # Supports +body+ to be one of: # 1. nil - empty body # 2. s(:begin) / s(:kwbegin) - multiline body # 3. s(:anything_else) - singleline body # # Returns a new body with +node+ injected as a first statement. # def prepend_to_body(body, node) stmts = stmts_of(node) + stmts_of(body) begin_with_stmts(stmts) end # Appends given +node+ to +body+ node. # # Supports +body+ to be one of: # 1. nil - empty body # 2. s(:begin) / s(:kwbegin) - multiline body # 3. s(:anything_else) - singleline body # # Returns a new body with +node+ injected as a last statement. # def append_to_body(body, node) stmts = stmts_of(body) + stmts_of(node) begin_with_stmts(stmts) end def stmts_of(node) if node.nil? [] elsif %i[begin kwbegin].include?(node.type) node.children else [node] end end def begin_with_stmts(stmts) case stmts.length when 0 nil when 1 stmts[0] else s(:begin, *stmts) end end # Store the current node for reporting. attr_accessor :current_node # Intercept the main call and assign current node. def process(node) self.current_node = node super ensure self.current_node = nil end # This is called when a rewriting error occurs. def error(msg) error = ::Opal::RewritingError.new(msg) error.location = current_node.loc if current_node raise error end def on_top(node) node = process_regular_node(node) node.meta[:dynamic_cache_result] = true if @dynamic_cache_result node end # Called when a given transformation is deemed to be dynamic, so # that cache is conditionally disabled for a given file. def dynamic! @dynamic_cache_result = true end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/mlhs_args.rb
lib/opal/rewriters/mlhs_args.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters # Rewrites # # def m( (a, b), (c, d) ) # body # end # # To # # def m($mlhs_tmp1, $mlhs_tmp2) # (a, b) = $mlhs_tmp1 # (c, d) = $mlhs_tmp2 # body # end # class MlhsArgs < Base def on_def(node) node = super(node) mid, args, body = *node arguments = Arguments.new(args) args = args.updated(nil, arguments.rewritten) if arguments.initialization body ||= s(:nil) # prevent returning mlhs assignment body = prepend_to_body(body, arguments.initialization) end node.updated(nil, [mid, args, body]) end def on_defs(node) node = super(node) recv, mid, args, body = *node arguments = Arguments.new(args) args = args.updated(nil, arguments.rewritten) if arguments.initialization body ||= s(:nil) # prevent returning mlhs assignment body = prepend_to_body(body, arguments.initialization) end node.updated(nil, [recv, mid, args, body]) end def on_iter(node) node = super(node) args, body = *node arguments = Arguments.new(args) args = args.updated(nil, arguments.rewritten) if arguments.initialization body ||= s(:nil) # prevent returning mlhs assignment body = prepend_to_body(body, arguments.initialization) end node.updated(nil, [args, body]) end class Arguments < Base attr_reader :rewritten, :initialization def initialize(args) @args = args @rewritten = [] @initialization = [] @rewriter = MlhsRewriter.new split! end def reset_tmp_counter! @counter = 0 end def new_mlhs_tmp @counter ||= 0 @counter += 1 :"$mlhs_tmp#{@counter}" end def split! @args.children.each do |arg| if arg.type == :mlhs var_name = new_mlhs_tmp rhs = s(:lvar, var_name) mlhs = @rewriter.process(arg) @initialization << s(:masgn, mlhs, rhs) @rewritten << s(:arg, var_name).updated(nil, nil, meta: { arg_name: var_name }) else @rewritten << arg end end if @initialization.length == 1 @initialization = @initialization[0] elsif @initialization.empty? @initialization = nil else @initialization = s(:begin, *@initialization) end end end class MlhsRewriter < Base def on_arg(node) node.updated(:lvasgn) end def on_restarg(node) name = node.children[0] if name s(:splat, node.updated(:lvasgn)) else s(:splat) end end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/targeted_patches.rb
lib/opal/rewriters/targeted_patches.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters # This module attempts to run some optimizations or compatibility # improvements against some libraries used with Opal. # # This should be a last resort and must not break functionality in # existing applications. class TargetedPatches < Base def on_def(node) name, args, body = *node if body && body.type == :begin && body.children.length >= 2 # parser/rubyxx.rb - racc generated code often looks like: # # def _reduce_219(val, _values, result) # result = @builder.op_assign(val[0], val[1], val[2]) # result # end # # This converter transform this into just # # def _reduce_219(val, _values, result) # @builder.op_assign(val[0], val[1], val[2]) # end calls = body.children assignment, ret = calls.last(2) if assignment.type == :lvasgn && ret.type == :lvar && assignment.children.first == ret.children.first if calls.length == 2 node.updated(nil, [name, args, assignment.children[1]]) else calls = calls[0..-3] << assignment.children[1] node.updated(nil, [name, args, body.updated(nil, calls)]) end else super end else super end end def on_array(node) children = node.children # Optimize large arrays produced by lexer, but mainly we are interested # in improving compile times, by reducing the tree for the further # compilation efforts (also reducing the bundle size a bit) # # This particular patch reduces compile time of the following command # by 12.5%: # # OPAL_CACHE_DISABLE=true OPAL_PREFORK_DISABLE=true bin/opal \ # --no-source-map -ropal-parser -ropal/platform -ce \ # 'puts ::Opal.compile($stdin.read)' > _Cnow.js # # So, in short, an array of a kind: # # [1, 2, 3, nil, nil, :something, :abc, nil, ...] # # Becomes compiled to: # # Opal.large_array_unpack("1,2,3,,something,abc,,...") if children.length > 32 ssin_array = children.all? do |child| # Break for wrong types next false unless %i[str sym int nil].include?(child.type) # Break for strings that may conflict with our numbers, nils and separator next false if %i[str sym].include?(child.type) && child.children.first.to_s =~ /\A[0-9-]|\A\z|,/ # Break for too numbers out of range, as there may be decoding issues next false if child.type == :int && !(-1_000_000..1_000_000).cover?(child.children.first) true end if ssin_array str = children.map { |i| i.children.first.to_s }.join(',') node.updated(:jscall, [s(:js_tmp, :Opal), :large_array_unpack, s(:sym, str)]) else super end else super end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/block_to_iter.rb
lib/opal/rewriters/block_to_iter.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters class BlockToIter < Base def on_block(node) recvr, args, body = *node iter_node = s(:iter, args, body) process recvr.updated( nil, recvr.children + [iter_node], ) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/dump_args.rb
lib/opal/rewriters/dump_args.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters class DumpArgs < Base def on_def(node) node = super(node) _mid, args, _body = *node node.updated(nil, nil, meta: { original_args: args }) end def on_defs(node) node = super(node) _recv, _mid, args, _body = *node node.updated(nil, nil, meta: { original_args: args }) end def on_iter(node) node = super(node) args, _body = *node node.updated(nil, nil, meta: { original_args: args }) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/deduplicate_arg_name.rb
lib/opal/rewriters/deduplicate_arg_name.rb
# frozen_string_literal: true module Opal module Rewriters # Ruby allows for args with the same name, if the arg starts with a '_', like: # def funny_method_name(_, _) # puts _ # end # but JavaScript in strict mode does not allow for args with the same name # Ruby assigns the value of the first arg given # funny_method_name(1, 2) => 1 # leave the first appearance as it is and rename the other ones # compiler result: # function $$funny_method_name(_, __$2) class DeduplicateArgName < Base def on_args(node) @arg_name_count = Hash.new(0) children = node.children.map do |arg| rename_arg(arg) end super(node.updated(nil, children)) end def rename_arg(arg) case arg.type when :arg, :restarg, :kwarg, :kwrestarg, :blockarg name = arg.children[0] name ? arg.updated(nil, [unique_name(name)]) : arg when :optarg, :kwoptarg name, value = arg.children arg.updated(nil, [unique_name(name), value]) when :mlhs new_children = arg.children.map { |child| rename_arg(child) } arg.updated(nil, new_children) else arg end end def unique_name(name) count = (@arg_name_count[name] += 1) count > 1 ? :"#{name}_$#{count}" : name end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/dot_js_syntax.rb
lib/opal/rewriters/dot_js_syntax.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters class DotJsSyntax < Base def on_send(node) recv, meth, *args = *node if recv && recv.type == :send recv_of_recv, meth_of_recv, _ = *recv if meth_of_recv == :JS case meth when :[] if args.size != 1 error '.JS[:property] syntax supports only one argument' end property = args.first node = to_js_attr_call(recv_of_recv, property) when :[]= if args.size != 2 error '.JS[:property]= syntax supports only two arguments' end property, value = *args node = to_js_attr_assign_call(recv_of_recv, property, value) else node = to_native_js_call(recv_of_recv, meth, args) end super(node) else super end else super end end # @param recv [AST::Node] receiver of .JS. method # @param meth [Symbol] name of the JS method # @param args [Array<AST::Node>] list of the arguments passed to JS method def to_native_js_call(recv, meth, args) s(:jscall, recv, meth, *args) end # @param recv [AST::Node] receiver of .JS[] method # @param property [AST::Node] argument passed to .JS[] method def to_js_attr_call(recv, property) s(:jsattr, recv, property) end # @param recv [AST::Node] receiver of .JS[]= method # @param property [AST::Node] property passed to brackets # @param value [AST::Node] value of assignment def to_js_attr_assign_call(recv, property, value) s(:jsattrasgn, recv, property, value) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/forward_args.rb
lib/opal/rewriters/forward_args.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters class ForwardArgs < Base def on_forward_args(_node) process( s(:args, s(:forward_arg, :"$")) ) end def on_forwarded_restarg(_node) process( s(:splat, s(:lvar, '$fwd_rest')) ) end def on_forwarded_kwrestarg(_node) process( s(:kwsplat, s(:lvar, '$fwd_kwrest')) ) end def on_block_pass(node) if !node.children.first process( node.updated(nil, [s(:lvar, '$fwd_block')] ) ) else super end end def on_args(node) if node.children.last && node.children.last.type == :forward_arg prev_children = node.children[0..-2] super(node.updated(nil, [ *prev_children, s(:restarg, '$fwd_rest'), s(:blockarg, '$fwd_block') ] )) else super end end def on_restarg(node) if !node.children.first node.updated(nil, ['$fwd_rest']) else super end end def on_kwrestarg(node) if !node.children.first node.updated(nil, ['$fwd_kwrest']) else super end end def on_blockarg(node) if !node.children.first node.updated(nil, ['$fwd_block']) else super end end def on_send(node) if node.children.last && node.children.last.class != Symbol && node.children.last.type == :forwarded_args prev_children = node.children[0..-2] super(node.updated(nil, [ *prev_children, s(:splat, s(:lvar, '$fwd_rest') ), s(:block_pass, s(:lvar, '$fwd_block') ) ] )) else super end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/numblocks.rb
lib/opal/rewriters/numblocks.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters # This rewriter transforms the Ruby 2.7 numblocks to regular blocks: # # proc { _1 } # v # proc { |_1| _1 } class Numblocks < Base def on_numblock(node) left, arg_count, right = node.children s( :block, left, s(:args, *gen_args(arg_count)), right ) end def gen_args(arg_count) (1..arg_count).map do |i| s(:arg, :"_#{i}") end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/pattern_matching.rb
lib/opal/rewriters/pattern_matching.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rewriters class PatternMatching < Base def initialize @depth = 0 super end # a => b def on_match_pattern(node) from, pat = *node s(:begin, s(:lvasgn, :"$pmvar", from), s(:if, convert_full_pattern(from, pat), nil, raise_no_matching_pattern_error(:"$pmvar") ) ) end # a in b def on_match_pattern_p(node) from, pat = *node s(:if, convert_full_pattern(from, pat), s(:true), s(:false) ) end # case a; in b; end def on_case_match(node) @depth += 1 cmvar = :"$cmvar#{@depth}" from, *cases, els = *node if els process els else els = raise_no_matching_pattern_error(cmvar) end s(:begin, s(:lvasgn, cmvar, from), single_case_match(cmvar, *cases, els) ) end private # raise NoMatchingPatternError, from def raise_no_matching_pattern_error(from) s(:send, nil, :raise, s(:const, s(:cbase), :NoMatchingPatternError), s(:lvar, from) ) end # in b def single_case_match(from, *cases, els) cas = cases.shift pat, if_guard, body = *cas pat = convert_full_pattern(from, pat) if if_guard guard, = *if_guard case if_guard.type when :if_guard pat = s(:and, pat, guard) when :unless_guard pat = s(:and, pat, s(:send, guard, :!)) end end s(:if, pat, process(body), if !cases.empty? single_case_match(from, *cases, els) elsif els != s(:empty_else) els end ) end def convert_full_pattern(from, pat) if from.class == Symbol from = s(:lvar, from) end converter = PatternConverter.new(pat) converter.run! # a, b, c = ::PatternMatching.(from, [...]) s(:masgn, s(:mlhs, *converter.variables ), s(:send, s(:const, s(:cbase), :PatternMatching), :call, from, converter.pattern, ) ) end class PatternConverter < ::Opal::Rewriters::Base def initialize(pat) @pat = pat @variables = [] end def run! @outpat = process(@pat) end def pattern @outpat end def variables @variables.map { |i| s(:lvasgn, i) } end # a def on_match_var(node) var, = *node @variables << var s(:sym, :var) end # [...] => a def on_match_as(node) pat, save = *node process(save) array(s(:sym, :save), process(pat)) end def on_literal(node) array(s(:sym, :lit), node) end alias on_int on_literal alias on_float on_literal alias on_complex on_literal alias on_rational on_literal alias on_array on_literal alias on_str on_literal alias on_dstr on_literal alias on_xstr on_literal alias on_sym on_literal alias on_irange on_literal alias on_erange on_literal alias on_const on_literal alias on_regexp on_literal alias on_lambda on_literal alias on_begin on_literal # ^a def on_pin(node) on_literal(node.children.first) end # * def on_match_rest(node) if node.children.empty? array(s(:sym, :rest)) else array(s(:sym, :rest), process(node.children.first)) end end # {} | [] def on_match_alt(node) array(s(:sym, :any), *node.children.map(&method(:process))) end # MyStructName def on_const_pattern(node) array(s(:sym, :all), *node.children.map(&method(:process))) end # [0, 1, 2] or [*, 0, 1] or [0, 1, *] def on_array_pattern(node, tail = false) children = *node children << s(:match_rest) if tail fixed_size = true array_size = 0 children = children.each do |i| case i.type when :match_rest fixed_size = false else array_size += 1 end end array( s(:sym, :array), to_ast(fixed_size), to_ast(array_size), to_ast(children.map(&method(:process))) ) end # [0, 1, 2,] def on_array_pattern_with_tail(node) on_array_pattern(node, true) end # {a:, b:} def on_hash_pattern(node) children = *node any_size = children.empty? ? to_ast(false) : to_ast(true) children = children.map do |i| case i.type when :pair array(i.children[0], process(i.children[1])) when :match_var array(s(:sym, i.children[0]), process(i)) when :match_nil_pattern any_size = to_ast(false) nil when :match_rest # Capturing rest? if i.children.first any_size = process(i.children.first) else any_size = to_ast(true) end nil end end.compact array(s(:sym, :hash), any_size, array(*children)) end # [*, a, b, *] def on_find_pattern(node) children = *node children = children.map(&method(:process)) array(s(:sym, :find), array(*children)) end private def array(*args) to_ast(args) end def to_ast(val) case val when Array s(:array, *val) when Integer s(:int, val) when true s(:true) when false s(:false) when nil s(:nil) end end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/hashes/key_duplicates_rewriter.rb
lib/opal/rewriters/hashes/key_duplicates_rewriter.rb
# frozen_string_literal: true require 'opal/rewriters/base' require 'set' module Opal module Rewriters module Hashes class KeyDuplicatesRewriter < ::Opal::Rewriters::Base def initialize @keys = UniqKeysSet.new end def on_hash(node) previous_keys, @keys = @keys, UniqKeysSet.new super(node) ensure @keys = previous_keys end def on_pair(node) key, _value = *node if %i[str sym].include?(key.type) @keys << key end super(node) end def on_kwsplat(node) hash, _ = *node if hash.type == :hash hash = process_regular_node(hash) end node.updated(nil, [hash]) end class UniqKeysSet def initialize @set = Set.new end def <<(element) if @set.include?(element) key, _ = *element key = element.type == :str ? key.inspect : ":#{key}" Kernel.warn "warning: key #{key} is duplicated and overwritten" else @set << element end end end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/rewriters/rubyspec/filters_rewriter.rb
lib/opal/rewriters/rubyspec/filters_rewriter.rb
# frozen_string_literal: true require 'opal/rewriters/base' module Opal module Rubyspec class FiltersRewriter < Opal::Rewriters::Base class << self def filters @filters ||= [] end def filter(spec_name) filters << spec_name end alias fails filter alias fails_badly filter def filtered?(spec_name) filters.include?(spec_name) end def clear_filters! @filters = [] end end def initialize @specs_stack = [] end RUBYSPEC_DSL = %i[describe it context].freeze def on_send(node) _recvr, method_name, *args = *node if rubyspec_dsl?(method_name) dynamic! spec_name, _ = *args.first begin @specs_stack.push(spec_name) if skip? s(:nil) else super end ensure @specs_stack.pop end elsif method_name == :fixture # We want to expand the fixture paths before autoload happens. if args.all? { |i| i.type == :str } as = args.map { |i| i.children.first } s(:str, fixture(*as)) else super end else super end end def skip? self.class.filtered?(current_spec_name) end def rubyspec_dsl?(method_name) RUBYSPEC_DSL.include?(method_name) end def current_spec_name @specs_stack.join(' ') end # Adapted from: spec/mspec/lib/mspec/helpers/fixture.rb def fixture(file, *args) path = File.dirname(file) path = path[0..-7] if path[-7..-1] == '/shared' fixtures = path[-9..-1] == '/fixtures' ? '' : 'fixtures' File.join(path, fixtures, args) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/applescript.rb
lib/opal/cli_runners/applescript.rb
# frozen_string_literal: true require 'opal/cli_runners/system_runner' module Opal module CliRunners class Applescript def self.call(data) unless system('which osalang > /dev/null') raise MissingJavaScriptSupport, 'JavaScript Automation is only supported by OS X Yosemite and above.' end SystemRunner.call(data) do |tempfile| tempfile.puts "'';" # OSAScript will output the last thing ['osascript', '-l', 'JavaScript', tempfile.path, *data[:argv]] end rescue Errno::ENOENT raise MissingAppleScript, 'AppleScript is only available on Mac OS X.' end class MissingJavaScriptSupport < RunnerError end class MissingAppleScript < RunnerError end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/quickjs.rb
lib/opal/cli_runners/quickjs.rb
# frozen_string_literal: true require 'opal/paths' require 'opal/cli_runners/system_runner' require 'shellwords' module Opal module CliRunners # QuickJS is Fabrice Bellard's minimalistic JavaScript engine # https://github.com/bellard/quickjs class Quickjs def self.call(data) exe = ENV['QJS_PATH'] || 'qjs' opts = Shellwords.shellwords(ENV['QJS_OPTS'] || '') SystemRunner.call(data) do |tempfile| [exe, '--std', *opts, tempfile.path, *data[:argv]] end rescue Errno::ENOENT raise MissingQuickjs, 'Please install QuickJS to be able to run Opal scripts.' end class MissingQuickjs < RunnerError end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/mini_racer.rb
lib/opal/cli_runners/mini_racer.rb
# frozen_string_literal: true require 'mini_racer' require 'opal/paths' module Opal module CliRunners class MiniRacer 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.compiled_source 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 # A polyfill so that SecureRandom works in repl correctly. def self.random_bytes(bytes) ::SecureRandom.bytes(bytes).split('').map(&:ord) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/compiler.rb
lib/opal/cli_runners/compiler.rb
# frozen_string_literal: true require 'opal/paths' # The compiler runner will just output the compiled JavaScript class Opal::CliRunners::Compiler def self.call(data) new(data).start end def initialize(data) @options = data[:options] || {} @builder_factory = data.fetch(:builder) @map_file = @options[:map_file] @output = data.fetch(:output) @watch = @options[:watch] @directory = @options[:directory] end def compile builder = @builder_factory.call if @directory builder.compile_to_directory(@output, with_source_map: !@options[:no_source_map]) else compiled_source = builder.compiled_source(with_source_map: !@options[:no_source_map]) rewind_output if @watch @output.puts compiled_source @output.flush File.write(@map_file, builder.source_map.to_json) if @map_file end builder end def compile_noraise compile rescue StandardError, Opal::SyntaxError => e $stderr.puts "* Compilation failed: #{e.message}" nil end def rewind_output if !@output.is_a?(File) || @output.tty? fail_unrewindable! else begin @output.rewind @output.truncate(0) rescue Errno::ESPIPE fail_unrewindable! end end end def fail_unrewindable! abort <<~ERROR You have specified --watch, but for watch to work, you must specify an --output file. ERROR end def fail_no_listen! abort <<~ERROR --watch mode requires the `listen` gem present. Please try to run: gem install listen Or if you are using bundler, add listen to your Gemfile. ERROR end def watch_compile begin require 'listen' rescue LoadError fail_no_listen! end @opal_deps = Opal.dependent_files builder = compile code_deps = builder.dependent_files @files = @opal_deps + code_deps @code_listener = watch_files @code_listener.start $stderr.puts "* Opal v#{Opal::VERSION} successfully compiled your program in --watch mode" sleep rescue Interrupt $stderr.puts '* Stopping watcher...' @code_listener.stop end def reexec Process.kill('USR2', Process.pid) end def on_code_change(modified) if !(modified & @opal_deps).empty? $stderr.puts "* Modified core Opal files: #{modified.join(', ')}; reexecuting" reexec elsif !modified.all? { |file| @directories.any? { |dir| file.start_with?(dir + '/') } } $stderr.puts "* New unwatched files: #{modified.join(', ')}; reexecuting" reexec end $stderr.puts "* Modified code: #{modified.join(', ')}; rebuilding" builder = compile_noraise # Ignore the bad compilation if builder code_deps = builder.dependent_files @files = @opal_deps + code_deps end end def files_to_directories directories = @files.map { |file| File.dirname(file) }.uniq previous_dir = nil # Only get the topmost directories directories = directories.sort.map do |dir| if previous_dir && dir.start_with?(previous_dir + '/') nil else previous_dir = dir end end directories.compact end def watch_files @directories = files_to_directories Listen.to(*@directories, ignore!: []) do |modified, added, removed| our_modified = @files & (modified + added + removed) on_code_change(our_modified) unless our_modified.empty? end end def start if @watch watch_compile else compile end 0 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/chrome.rb
lib/opal/cli_runners/chrome.rb
# frozen_string_literal: true require 'shellwords' require 'socket' require 'timeout' require 'tmpdir' require 'rbconfig' require 'opal/os' module Opal module CliRunners class Chrome SCRIPT_PATH = File.expand_path('cdp_interface.rb', __dir__).freeze DEFAULT_CDP_HOST = 'localhost' DEFAULT_CDP_PORT = 9222 def self.call(data) runner = new(data) runner.run end def initialize(data) argv = data[:argv] if argv && argv.any? warn "warning: ARGV is not supported by the Chrome runner #{argv.inspect}" end options = data[:options] @output = options.fetch(:output, $stdout) @builder = data[:builder].call end attr_reader :output, :exit_status, :builder def run mktmpdir do |dir| with_chrome_server do prepare_files_in(dir) env = { 'OPAL_CDP_HOST' => chrome_host, 'OPAL_CDP_PORT' => chrome_port.to_s, 'NODE_PATH' => File.join(__dir__, 'node_modules'), 'OPAL_CDP_EXT' => builder.output_extension } cmd = [ RbConfig.ruby, "#{__dir__}/../../../exe/opal", '--no-exit', '-I', __dir__, '-r', 'source-map-support-node', SCRIPT_PATH, dir ] Kernel.exec(env, *cmd) end end end private def prepare_files_in(dir) js = builder.to_s map = builder.source_map.to_json stack = File.binread("#{__dir__}/source-map-support-browser.js") ext = builder.output_extension module_type = ' type="module"' if builder.esm? # Some maps may contain `</script>` fragment (eg. in strings) which would close our # `<script>` tag prematurely. For this case, we need to escape the `</script>` tag. map_json = map.to_json.gsub(/(<\/scr)(ipt>)/i, '\1"+"\2') # Chrome can't handle huge data passed to `addScriptToEvaluateOnLoad` # https://groups.google.com/a/chromium.org/forum/#!topic/chromium-discuss/U5qyeX_ydBo # The only way is to create temporary files and pass them to chrome. File.binwrite("#{dir}/index.#{ext}", js) File.binwrite("#{dir}/index.map", map) File.binwrite("#{dir}/source-map-support.js", stack) File.binwrite("#{dir}/index.html", <<~HTML) <html><head> <meta charset='utf-8'> <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon"> <script src='./source-map-support.js'></script> <script> window.opalheadlesschrome = true; sourceMapSupport.install({ retrieveSourceMap: function(path) { return path.endsWith('/index.#{ext}') ? { url: './index.map', map: #{map_json} } : null; } }); </script> </head><body> <script src='./index.#{ext}'#{module_type}></script> </body></html> HTML end def chrome_host ENV['CHROME_HOST'] || ENV['OPAL_CDP_HOST'] || DEFAULT_CDP_HOST end def chrome_port ENV['CHROME_PORT'] || ENV['OPAL_CDP_PORT'] || DEFAULT_CDP_PORT end def with_chrome_server if chrome_server_running? yield else run_chrome_server { yield } end end def run_chrome_server raise 'Chrome server can be started only on localhost' if chrome_host != DEFAULT_CDP_HOST profile = mktmpprofile # Disable web security with "--disable-web-security" flag to be able to do XMLHttpRequest (see test_openuri.rb) # For other options see https://github.com/puppeteer/puppeteer/blob/main/packages/puppeteer-core/src/node/ChromeLauncher.ts chrome_server_cmd = %{#{OS.shellescape(chrome_executable)} \ --allow-pre-commit-input \ --disable-background-networking \ --enable-features=NetworkServiceInProcess2 \ --disable-background-timer-throttling \ --disable-backgrounding-occluded-windows \ --disable-breakpad \ --disable-client-side-phishing-detection \ --disable-component-extensions-with-background-pages \ --disable-default-apps \ --disable-dev-shm-usage \ --disable-extensions \ --disable-features=Translate,BackForwardCache,AcceptCHFrame,AvoidUnnecessaryBeforeUnloadCheckSync \ --disable-hang-monitor \ --disable-ipc-flooding-protection \ --disable-popup-blocking \ --disable-prompt-on-repost \ --disable-renderer-backgrounding \ --disable-sync \ --force-color-profile=srgb \ --metrics-recording-only \ --no-first-run \ --enable-automation \ --password-store=basic \ --use-mock-keychain \ --enable-blink-features=IdleDetection \ --export-tagged-pdf \ --headless \ --user-data-dir=#{profile} \ --hide-scrollbars \ --mute-audio \ --disable-web-security \ --remote-debugging-port=#{chrome_port} \ #{ENV['CHROME_OPTS']}} chrome_pid = Process.spawn(chrome_server_cmd, in: OS.dev_null, out: OS.dev_null, err: OS.dev_null) Timeout.timeout(30) do loop do break if chrome_server_running? sleep 0.5 end end yield rescue Timeout::Error puts 'Failed to start chrome server' puts 'Make sure that you have it installed and that its version is > 59' exit(1) ensure if OS.windows? && chrome_pid Process.kill('KILL', chrome_pid) unless system("taskkill /f /t /pid #{chrome_pid} >NUL 2>NUL") elsif chrome_pid Process.kill('HUP', chrome_pid) end FileUtils.rm_rf(profile) if profile end def chrome_server_running? puts "Connecting to #{chrome_host}:#{chrome_port}..." TCPSocket.new(chrome_host, chrome_port).close true rescue Errno::ECONNREFUSED, Errno::EADDRNOTAVAIL false end def chrome_executable ENV['GOOGLE_CHROME_BINARY'] || if OS.windows? [ 'C:/Program Files/Google/Chrome Dev/Application/chrome.exe', 'C:/Program Files/Google/Chrome/Application/chrome.exe' ].each do |path| next unless File.exist? path return path end elsif OS.macos? [ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium' ].each do |path| next unless File.exist? path return path end else %w[ google-chrome-stable chromium chromium-freeworld chromium-browser ].each do |name| next unless system('sh', '-c', "command -v #{name.shellescape}", out: '/dev/null') return name end raise 'Cannot find chrome executable' end end def mktmpdir(&block) Dir.mktmpdir('chrome-opal-', &block) end def mktmpprofile Dir.mktmpdir('chrome-opal-profile-') end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/firefox.rb
lib/opal/cli_runners/firefox.rb
# frozen_string_literal: true require 'shellwords' require 'socket' require 'timeout' require 'tmpdir' require 'rbconfig' require 'opal/os' require 'json' require 'fileutils' require 'net/http' module Opal module CliRunners class Firefox SCRIPT_PATH = File.expand_path('cdp_interface.rb', __dir__).freeze DEFAULT_CDP_HOST = 'localhost' DEFAULT_CDP_PORT = 9333 # makes sure it doesn't accidentally connect to a lingering chrome def self.call(data) runner = new(data) runner.run end def initialize(data) builder = data[:builder].call options = data[:options] argv = data[:argv] if argv && argv.any? warn "warning: ARGV is not supported by the Firefox runner #{argv.inspect}" end @output = options.fetch(:output, $stdout) @builder = builder end attr_reader :output, :exit_status, :builder def run mktmpdir do |dir| with_firefox_server do prepare_files_in(dir) env = { 'OPAL_CDP_HOST' => chrome_host, 'OPAL_CDP_PORT' => chrome_port.to_s, 'NODE_PATH' => File.join(__dir__, 'node_modules') } env['OPAL_CDP_EXT'] = builder.output_extension cmd = [ RbConfig.ruby, "#{__dir__}/../../../exe/opal", '--no-exit', '-I', __dir__, '-r', 'source-map-support-node', SCRIPT_PATH, dir ] Kernel.exec(env, *cmd) end end end private def prepare_files_in(dir) js = builder.to_s map = builder.source_map.to_json ext = builder.output_extension module_type = ' type="module"' if builder.esm? # CDP can't handle huge data passed to `addScriptToEvaluateOnLoad` # https://groups.google.com/a/chromium.org/forum/#!topic/chromium-discuss/U5qyeX_ydBo # The only way is to create temporary files and pass them to the browser. File.binwrite("#{dir}/index.#{ext}", js) File.binwrite("#{dir}/index.#{ext}.map", map) File.binwrite("#{dir}/index.html", <<~HTML) <!DOCTYPE html> <html><head> <meta charset='utf-8'> <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon"> <script> window.opalheadlessfirefox = true; </script> </head><body> <script src='/index.#{ext}'#{module_type}></script> </body></html> HTML end def chrome_host ENV['FIREFOX_HOST'] || ENV['OPAL_CDP_HOST'] || DEFAULT_CDP_HOST end def chrome_port ENV['FIREFOX_PORT'] || ENV['OPAL_CDP_PORT'] || DEFAULT_CDP_PORT end def with_firefox_server if firefox_server_running? yield else run_firefox_server { yield } end end def run_firefox_server raise 'Firefox server can be started only on localhost' if chrome_host != DEFAULT_CDP_HOST profile = mktmpprofile # For options see https://github.com/puppeteer/puppeteer/blob/main/packages/puppeteer-core/src/node/FirefoxLauncher.ts firefox_server_cmd = %{#{OS.shellescape(firefox_executable)} \ --no-remote #{'--foreground' if OS.macos?} #{'--wait-for-browser' if OS.windows?} \ --profile #{profile} \ --headless \ --remote-debugging-port #{chrome_port} \ #{ENV['FIREFOX_OPTS']}} firefox_pid = Process.spawn(firefox_server_cmd, in: OS.dev_null, out: OS.dev_null, err: OS.dev_null) Timeout.timeout(30) do loop do break if firefox_server_running? sleep 0.5 end end yield rescue Timeout::Error puts 'Failed to start firefox server' puts 'Make sure that you have it installed and that its version is > 100' if !OS.windows? && !OS.macos? # The firefox executable within snap is in fact the snap executable which sets up paths and then calls the # real firefox executable. It also mistreats passed options and args and always tries to reuse a existing # instance. Thus firefox from snap, when called by this runner, will start with the wrong options, the # wrong profile and will fail to setup the remote debugging port puts 'When firefox is installed via snap, it cannot work correctly with this runner.' puts 'In that case, please uninstall firefox via snap and install firefox from a apt repo, see:' puts 'https://support.mozilla.org/en-US/kb/install-firefox-linux#w_install-firefox-deb-package-for-debian-based-distributions' end exit(1) ensure if OS.windows? && firefox_pid Process.kill('KILL', firefox_pid) unless system("taskkill /f /t /pid #{firefox_pid} >NUL 2>NUL") elsif firefox_pid Process.kill('HUP', firefox_pid) end FileUtils.rm_rf(profile) if profile end def firefox_server_running? puts "Connecting to #{chrome_host}:#{chrome_port}..." TCPSocket.new(chrome_host, chrome_port).close # Firefox CDP endpoints are initialized after the CDP port is ready # this causes first requests to fail # wait until the CDP endpoints are ready response = Net::HTTP.get_response('localhost', '/json/list', chrome_port) raise Errno::EADDRNOTAVAIL if response.code != '200' true rescue Errno::ECONNREFUSED, Errno::EADDRNOTAVAIL false end def firefox_executable ENV['MOZILLA_FIREFOX_BINARY'] || if OS.windows? [ 'C:/Program Files/Mozilla Firefox/firefox.exe' ].each do |path| next unless File.exist? path return path end elsif OS.macos? [ '/Applications/Firefox.app/Contents/MacOS/Firefox', '/Applications/Firefox.app/Contents/MacOS/firefox', ].each do |path| return path if File.exist? path end else %w[ firefox firefox-esr ].each do |name| next unless system('sh', '-c', "command -v #{name.shellescape}", out: '/dev/null') return name end raise 'Cannot find firefox executable' end end def mktmpdir(&block) Dir.mktmpdir('firefox-opal-', &block) end def mktmpprofile # for prefs see https://github.com/puppeteer/puppeteer/blob/main/packages/browsers/src/browser-data/firefox.ts # and https://github.com/puppeteer/puppeteer/blob/main/packages/puppeteer-core/src/node/FirefoxLauncher.ts profile = Dir.mktmpdir('firefox-opal-profile-') default_prefs = { # Make sure Shield doesn't hit the network. 'app.normandy.api_url': '', # Disable Firefox old build background check 'app.update.checkInstallTime': false, # Disable automatically upgrading Firefox 'app.update.disabledForTesting': true, # Increase the APZ content response timeout to 1 minute 'apz.content_response_timeout': 60_000, # Prevent various error message on the console 'browser.contentblocking.features.standard': '-tp,tpPrivate,cookieBehavior0,-cm,-fp', # Enable the dump function: which sends messages to the system console # https://bugzilla.mozilla.org/show_bug.cgi?id=1543115 'browser.dom.window.dump.enabled': true, # Disable topstories 'browser.newtabpage.activity-stream.feeds.system.topstories': false, # Always display a blank page 'browser.newtabpage.enabled': false, # Background thumbnails in particular cause grief: and disabling # thumbnails in general cannot hurt 'browser.pagethumbnails.capturing_disabled': true, # Disable safebrowsing components. 'browser.safebrowsing.blockedURIs.enabled': false, 'browser.safebrowsing.downloads.enabled': false, 'browser.safebrowsing.malware.enabled': false, 'browser.safebrowsing.passwords.enabled': false, 'browser.safebrowsing.phishing.enabled': false, # Disable updates to search engines. 'browser.search.update': false, # Do not restore the last open set of tabs if the browser has crashed 'browser.sessionstore.resume_from_crash': false, # Skip check for default browser on startup 'browser.shell.checkDefaultBrowser': false, # Disable newtabpage 'browser.startup.homepage': 'about:blank', # Do not redirect user when a milstone upgrade of Firefox is detected 'browser.startup.homepage_override.mstone': 'ignore', # Start with a blank page about:blank 'browser.startup.page': 0, # Do not close the window when the last tab gets closed 'browser.tabs.closeWindowWithLastTab': false, # Do not allow background tabs to be zombified on Android: otherwise for # tests that open additional tabs: the test harness tab itself might get unloaded 'browser.tabs.disableBackgroundZombification': false, # Do not warn when closing all other open tabs 'browser.tabs.warnOnCloseOtherTabs': false, # Do not warn when multiple tabs will be opened 'browser.tabs.warnOnOpen': false, # Do not automatically offer translations, as tests do not expect this. 'browser.translations.automaticallyPopup': false, # Disable the UI tour. 'browser.uitour.enabled': false, # Turn off search suggestions in the location bar so as not to trigger # network connections. 'browser.urlbar.suggest.searches': false, # Disable first run splash page on Windows 10 'browser.usedOnWindows10.introURL': '', # Do not warn on quitting Firefox 'browser.warnOnQuit': false, # Defensively disable data reporting systems 'datareporting.healthreport.documentServerURI': 'http://localhost/dummy/healthreport/', 'datareporting.healthreport.logging.consoleEnabled': false, 'datareporting.healthreport.service.enabled': false, 'datareporting.healthreport.service.firstRun': false, 'datareporting.healthreport.uploadEnabled': false, # Do not show datareporting policy notifications which can interfere with tests 'datareporting.policy.dataSubmissionEnabled': false, 'datareporting.policy.dataSubmissionPolicyBypassNotification': true, # DevTools JSONViewer sometimes fails to load dependencies with its require.js. # This doesn't affect Puppeteer but spams console (Bug 1424372) 'devtools.jsonview.enabled': false, # Disable popup-blocker 'dom.disable_open_during_load': false, # Enable the support for File object creation in the content process # Required for |Page.setFileInputFiles| protocol method. 'dom.file.createInChild': true, # Disable the ProcessHangMonitor 'dom.ipc.reportProcessHangs': false, # Disable slow script dialogues 'dom.max_chrome_script_run_time': 0, 'dom.max_script_run_time': 0, # Only load extensions from the application and user profile # AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION 'extensions.autoDisableScopes': 0, 'extensions.enabledScopes': 5, # Disable metadata caching for installed add-ons by default 'extensions.getAddons.cache.enabled': false, # Disable installing any distribution extensions or add-ons. 'extensions.installDistroAddons': false, # Disabled screenshots extension 'extensions.screenshots.disabled': true, # Turn off extension updates so they do not bother tests 'extensions.update.enabled': false, # Turn off extension updates so they do not bother tests 'extensions.update.notifyUser': false, # Make sure opening about:addons will not hit the network 'extensions.webservice.discoverURL': 'http://localhost/dummy/discoveryURL', # Temporarily force disable BFCache in parent (https://bit.ly/bug-1732263) 'fission.bfcacheInParent': false, # Force all web content to use a single content process 'fission.webContentIsolationStrategy': 0, # Allow the application to have focus even it runs in the background 'focusmanager.testmode': true, # Disable useragent updates 'general.useragent.updates.enabled': false, # Always use network provider for geolocation tests so we bypass the # macOS dialog raised by the corelocation provider 'geo.provider.testing': true, # Do not scan Wifi 'geo.wifi.scan': false, # No hang monitor 'hangmonitor.timeout': 0, # Show chrome errors and warnings in the error console 'javascript.options.showInConsole': true, # Disable download and usage of OpenH264: and Widevine plugins 'media.gmp-manager.updateEnabled': false, # Prevent various error message on the console 'network.cookie.cookieBehavior': 0, # Disable experimental feature that is only available in Nightly 'network.cookie.sameSite.laxByDefault': false, # Avoid cookie expiry date to be affected by server time, which can result in flaky tests. 'network.cookie.useServerTime': false, # Do not prompt for temporary redirects 'network.http.prompt-temp-redirect': false, # Disable speculative connections so they are not reported as leaking # when they are hanging around 'network.http.speculative-parallel-limit': 0, # Do not automatically switch between offline and online 'network.manage-offline-status': false, # Make sure SNTP requests do not hit the network 'network.sntp.pools': 'localhost', # Disable Flash. 'plugin.state.flash': 0, 'privacy.trackingprotection.enabled': false, # To enable remote protocols use: # const WEBDRIVER_BIDI_ACTIVE = 0x1; # const CDP_ACTIVE = 0x2; # Enable only CDP for now 'remote.active-protocols': 2, # Can be removed once Firefox 89 is no longer supported # https://bugzilla.mozilla.org/show_bug.cgi?id=1710839 'remote.enabled': true, # Don't do network connections for mitm priming 'security.certerrors.mitm.priming.enabled': false, # Local documents have access to all other local documents, # including directory listings 'security.fileuri.strict_origin_policy': false, # Do not wait for the notification button security delay 'security.notification_enable_delay': 0, # Ensure blocklist updates do not hit the network 'services.settings.server': 'http://localhost/dummy/blocklist/', # Do not automatically fill sign-in forms with known usernames and passwords 'signon.autofillForms': false, # Disable password capture, so that tests that include forms are not # influenced by the presence of the persistent doorhanger notification 'signon.rememberSignons': false, # Disable first-run welcome page 'startup.homepage_welcome_url': 'about:blank', # Disable first-run welcome page 'startup.homepage_welcome_url.additional': '', # Disable browser animations (tabs, fullscreen, sliding alerts) 'toolkit.cosmeticAnimations.enabled': false, # Prevent starting into safe mode after application crashes 'toolkit.startup.max_resumed_crashes': -1, } prefs = default_prefs.map { |key, value| "user_pref(\"#{key}\", #{JSON.dump(value)});" } # apparently firefox will read user.js an generate prefs.js from it File.binwrite(profile + '/user.js', prefs.join("\n")) profile end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/cdp_interface.rb
lib/opal/cli_runners/cdp_interface.rb
# backtick_javascript: true # frozen_string_literal: true # This script I converted into Opal, so that I don't have to write # buffer handling again. We have gets, Node has nothing close to it, # even async. # For CDP see docs/cdp_common.(md|json) require 'opal/platform' require 'nodejs/env' %x{ var CDP = require("chrome-remote-interface"); var fs = require("fs"); var http = require("http"); var dir = #{ARGV.last}; var ext = #{ENV['OPAL_CDP_EXT']}; var port_offset; // port offset for http server, depending on number of targets var script_id; // of script which is executed after page is initialized, before page scripts are executed var cdp_client; // CDP client var target_id; // the used Target var options = { host: #{ENV['OPAL_CDP_HOST'] || 'localhost'}, port: parseInt(#{ENV['OPAL_CDP_PORT'] || '9222'}) }; // shared secret function random_string() { let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let str = ''; for (let i = 0; i < 256; i++) { str += chars.charAt(Math.floor(Math.random() * chars.length)); } return str; }; var shared_secret = random_string(); // secret must be passed with POST requests // support functions function perror(error) { console.error(error); } var exiting = false; function shutdown(exit_code) { if (exiting) { return Promise.resolve(); } exiting = true; var promises = []; cdp_client.Page.removeScriptToEvaluateOnNewDocument(script_id).then(function(){}, perror); return Promise.all(promises).then(function () { target_id ? cdp_client.Target.closeTarget(target_id) : null; }).then(function() { server.close(); process.exit(exit_code); }, function(error) { perror(error); process.exit(1) }); }; // simple HTTP server to deliver page, scripts to, and trigger commands from browser function not_found(res) { res.writeHead(404, { "Content-Type": "text/plain" }); res.end("NOT FOUND"); } function response_ok(res) { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("OK"); } function handle_post(req, res, fun) { var data = ""; req.on('data', function(chunk) { data += chunk; }) req.on('end', function() { var obj = JSON.parse(data); if (obj.secret == shared_secret) { fun.call(this, obj); } else { not_found(res); } }); } var server = http.createServer(function(req, res) { if (req.method === "GET") { var path = dir + '/' + req.url.slice(1); if (path.includes('..') || !fs.existsSync(path)) { not_found(res); } else { var content_type; if (path.endsWith(".html")) { content_type = "text/html" } else if (path.endsWith(".map")) { content_type = "application/json" } else { content_type = "application/javascript" } res.writeHead(200, { "Content-Type": content_type }); res.end(fs.readFileSync(path)); } } else if (req.method === "POST") { if (req.url === "/File.write") { // totally insecure on purpose handle_post(req, res, function(obj) { fs.writeFileSync(obj.filename, obj.data); response_ok(res); }); } else { not_found(res); } } else { not_found(res); } }); // actual CDP code CDP.List(options, async function(err, targets) { // default CDP port is 9222, Firefox runner is at 9333 // Lets collect clients for // Chrome CDP starting at 9273 ... // Firefox CDP starting 9334 ... port_offset = targets ? targets.length + 51 : 51; // default CDP port is 9222, Node CDP port 9229, Firefox is at 9333 const {webSocketDebuggerUrl} = await CDP.Version(options); return await CDP({target: webSocketDebuggerUrl}, function(browser_client) { server.listen({ port: port_offset + options.port, host: options.host }); browser_client.Target.createTarget({url: "about:blank"}).then(function(target) { target_id = target; options.target = target_id.targetId; CDP(options, function(client) { cdp_client = client; var Log = client.Log, Page = client.Page, Runtime = client.Runtime; // enable used CDP domains Promise.all([ Log.enable(), Page.enable(), Runtime.enable() ]).then(function() { // add script to set the shared_secret in the browser return Page.addScriptToEvaluateOnNewDocument({source: "window.OPAL_CDP_SHARED_SECRET = '" + shared_secret + "';"}).then(function(scrid) { script_id = scrid; }, perror); }, perror).then(function() { // receive and handle all kinds of log and console messages Log.entryAdded(function(entry) { process.stdout.write(entry.entry.level + ': ' + entry.entry.text + "\n"); }); Runtime.consoleAPICalled(function(entry) { var args = entry.args; var stack = null; var i, arg, frame, value; // output actual message for(i = 0; i < args.length; i++) { arg = args[i]; if (arg.type === "string") { value = arg.value; } else { value = JSON.stringify(arg); } process.stdout.write(value); } if (entry.stackTrace && entry.stackTrace.callFrames) { stack = entry.stackTrace.callFrames; } if (entry.type === "error" && stack) { // print full stack for errors process.stdout.write("\n"); for(i = 0; i < stack.length; i++) { frame = stack[i]; if (frame) { value = frame.url + ':' + frame.lineNumer + ':' + frame.columnNumber + '\n'; process.stdout.write(value); } } } }); // react to exceptions Runtime.exceptionThrown(function(exception) { var ex = exception.exceptionDetails.exception.preview.properties; var stack = []; if (exception.exceptionDetails.stackTrace) { stack = exception.exceptionDetails.stackTrace.callFrames; } else { var d = exception.exceptionDetails; stack.push({ url: d.url, lineNumber: d.lineNumber, columnNumber: d.columnNumber, functionName: "(unknown)" }); } var fr; for (var i = 0; i < ex.length; i++) { fr = ex[i]; if (fr.name === "message") { perror(fr.value); } } for (var i = 0; i < stack.length; i++) { fr = stack[i]; perror(fr.url + ':' + fr.lineNumber + ':' + fr.columnNumber + ': in ' + fr.functionName); } return shutdown(1); }); // handle input Page.javascriptDialogOpening((dialog) => { #{ if `dialog.type` == 'prompt' message = gets&.chomp if message `Page.handleJavaScriptDialog({accept: true, promptText: #{message}})` else `Page.handleJavaScriptDialog({accept: false})` end elsif `dialog.type` == 'alert' && `dialog.message` == 'opalheadlessbrowserexit' # A special case of an alert with a magic string "opalheadlessbrowserexit". # This denotes that `Kernel#exit` has been called. We would have rather used # an exception here, but they don't bubble sometimes. %x{ Page.handleJavaScriptDialog({accept: true}); Runtime.evaluate({ expression: "window.OPAL_EXIT_CODE" }).then(function(output) { var exit_code = 0; if (typeof(output.result) !== "undefined" && output.result.type === "number") { exit_code = output.result.value; } return shutdown(exit_code); }); } end } }); // page has been loaded, all code has been executed Page.loadEventFired(() => { Runtime.evaluate({ expression: "window.OPAL_EXIT_CODE" }).then(function(output) { if (typeof(output.result) !== "undefined" && output.result.type === "number") { return shutdown(output.result.value); } else if (typeof(output.result) !== "undefined" && output.result.type === "string" && output.result.value === "noexit") { // do nothing, we have headless chrome support enabled and there are most probably async events awaiting } else { return shutdown(0); } }) }); // init page load Page.navigate({ url: "http://localhost:" + (port_offset + options.port).toString() + "/index.html" }) }, perror); }); }); }); }); } # end of code (marker to help see if brackets match above)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/nodejs.rb
lib/opal/cli_runners/nodejs.rb
# frozen_string_literal: true require 'shellwords' require 'opal/paths' require 'opal/cli_runners/system_runner' require 'opal/os' module Opal module CliRunners class Nodejs if RUBY_ENGINE == 'opal' # We can't rely on Opal.gem_dir for now... NODE_PATH = 'stdlib/nodejs/node_modules' DIR = './lib/opal/cli_runners' else NODE_PATH = File.expand_path('../stdlib/nodejs/node_modules', ::Opal.gem_dir) DIR = __dir__ end def self.call(data) (data[:options] ||= {})[:env] = { 'NODE_PATH' => node_modules } argv = data[:argv].dup.to_a argv.unshift('--') if argv.any? opts = Shellwords.shellwords(ENV['NODE_OPTS'] || '') flame = ENV['NODE_FLAME'] SystemRunner.call(data) do |tempfile| args = [ 'node', '--require', "#{DIR}/source-map-support-node", *opts, tempfile.path, *argv ] args.unshift('0x', '--') if flame args end rescue Errno::ENOENT raise MissingNodeJS, 'Please install Node.js to be able to run Opal scripts.' end # Ensure stdlib node_modules is among NODE_PATHs def self.node_modules ENV['NODE_PATH'].to_s.split(OS.env_sep).tap do |paths| paths << NODE_PATH unless paths.include? NODE_PATH end.join(OS.env_sep) end class MissingNodeJS < RunnerError end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/safari.rb
lib/opal/cli_runners/safari.rb
# frozen_string_literal: true require 'shellwords' require 'socket' require 'timeout' require 'tmpdir' require 'rbconfig' require 'opal/os' require 'net/http' require 'webrick' module Opal module CliRunners class Safari EXECUTION_TIMEOUT = 600 # seconds DEFAULT_SAFARI_DRIVER_HOST = 'localhost' DEFAULT_SAFARI_DRIVER_PORT = 9444 # in addition safari_driver_port + 1 is used for the http server def self.call(data) runner = new(data) runner.run end def initialize(data) argv = data[:argv] if argv && argv.any? warn "warning: ARGV is not supported by the Safari runner #{argv.inspect}" end options = data[:options] @output = options.fetch(:output, $stdout) @builder = data[:builder].call end attr_reader :output, :exit_status, :builder def run mktmpdir do |dir| with_http_server(dir) do |http_port, server_thread| with_safari_driver do prepare_files_in(dir) # Safaridriver commands are very limitied, for supported commands see: # https://developer.apple.com/documentation/webkit/macos_webdriver_commands_for_safari_12_and_later Net::HTTP.start(safari_driver_host, safari_driver_port) do |con| con.read_timeout = EXECUTION_TIMEOUT res = con.post('/session', { capabilities: { browserName: 'Safari' } }.to_json, 'Content-Type' => 'application/json') session_id = JSON.parse(res.body).dig('value', 'sessionId') if session_id session_path = "/session/#{session_id}" con.post("#{session_path}/url", { url: "http://#{safari_driver_host}:#{http_port}/index.html" }.to_json, 'Content-Type' => 'application/json') server_thread.join(EXECUTION_TIMEOUT) else STDERR.puts "Could not create session: #{res.body}" end end 0 end end end end private def prepare_files_in(dir) # The safaridriver is very limited in capabilities, basically it can trigger visiting sites # and interact a bit with the page. So this runner starts its own server, overwrites the # console log, warn, error functions of the browser and triggers a request after execution # to exit. Certain exceptions cannot be caught that way and everything may fail in between, # thats why execution is timed out after EXECUTION_TIMEOUT (10 minutes). # As a side effect, console messages may arrive out of order and timing anything may be inaccurate. builder.build_str <<~RUBY, '(exit)', no_export: true %x{ var req = new XMLHttpRequest(); req.open("GET", '/exit'); req.send(); } RUBY js = builder.to_s map = builder.source_map.to_json ext = builder.output_extension module_type = ' type="module"' if builder.esm? File.binwrite("#{dir}/index.#{ext}", js) File.binwrite("#{dir}/index.map", map) File.binwrite("#{dir}/index.html", <<~HTML) <html><head> <meta charset='utf-8'> <link rel="icon" href="data:;base64,="> </head><body> <script> var orig_log = console.log; var orig_err = console.error; var orig_warn = console.warn; function send_log_request(args) { var req = new XMLHttpRequest(); req.open("POST", '/log'); req.setRequestHeader("Content-Type", "application/json"); req.send(JSON.stringify(args)); } console.log = function() { orig_log.apply(null, arguments); send_log_request(arguments); } console.error = function() { orig_err.apply(null, arguments); send_log_request(arguments); } console.warn = function() { orig_warn.apply(null, arguments); send_log_request(arguments); } </script> <script src='./index.#{ext}'#{module_type}></script> </body></html> HTML # <script src='./index.#{ext}'#{module_type}></script> end def safari_driver_host ENV['SAFARI_DRIVER_HOST'] || DEFAULT_SAFARI_DRIVER_HOST end def safari_driver_port ENV['SAFARI_DRIVER_PORT'] || DEFAULT_SAFARI_DRIVER_PORT end def with_http_server(dir) port = safari_driver_port.to_i + 1 server_thread = Thread.new do server = WEBrick::HTTPServer.new(Port: port, DocumentRoot: dir, Logger: WEBrick::Log.new('/dev/null'), AccessLog: []) server.mount_proc('/log') do |req, res| if req.body par = JSON.parse(req.body) par.each_value do |value| print value.to_s end end res.header['Content-Type'] = 'text/plain' res.body = '' end server.mount_proc('/exit') do server_thread.kill end server.start end yield port, server_thread rescue exit(1) ensure server_thread.kill if server_thread end def with_safari_driver if safari_driver_running? yield else run_safari_driver { yield } end end def run_safari_driver raise 'Safari driver can be started only on localhost' if safari_driver_host != DEFAULT_SAFARI_DRIVER_HOST started = false safari_driver_cmd = %{/usr/bin/safaridriver \ -p #{safari_driver_port} \ #{ENV['SAFARI_DRIVER_OPTS']}} safari_driver_pid = Process.spawn(safari_driver_cmd, in: OS.dev_null, out: OS.dev_null, err: OS.dev_null) Timeout.timeout(30) do loop do break if safari_driver_running? sleep 0.5 end end started = true yield rescue Timeout::Error => e puts started ? 'Execution timed out' : 'Failed to start Safari driver' raise e ensure Process.kill('HUP', safari_driver_pid) if safari_driver_pid end def safari_driver_running? puts "Connecting to #{safari_driver_host}:#{safari_driver_port}..." TCPSocket.new(safari_driver_host, safari_driver_port).close true rescue Errno::ECONNREFUSED, Errno::EADDRNOTAVAIL false end def mktmpdir(&block) Dir.mktmpdir('safari-opal-', &block) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/bun.rb
lib/opal/cli_runners/bun.rb
# frozen_string_literal: true require 'shellwords' require 'opal/paths' require 'opal/cli_runners/system_runner' require 'opal/os' module Opal module CliRunners class Bun def self.call(data) argv = data[:argv].dup.to_a SystemRunner.call(data) do |tempfile| opts = Shellwords.shellwords(ENV['BUN_OPTS'] || '') [ 'bun', 'run', *opts, tempfile.path, *argv ] end rescue Errno::ENOENT raise MissingBun, 'Please install Bun to be able to run Opal scripts.' end class MissingBun < RunnerError end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/system_runner.rb
lib/opal/cli_runners/system_runner.rb
# frozen_string_literal: true require 'tempfile' require 'tmpdir' require 'fileutils' module Opal VirtualFileObject = Struct.new(:path, keyword_init: true) # Generic runner that will resort to calling an external program. # # @option :options [Hash,nil] :env a hash of options to be used as env in the # call to system. # @option :options [true,false] :debug enabling debug mode will write the # compiled JavaScript file in the current working directory. # @yield tempfile [File] Gives a file to the block, its #path can be used to # construct the command # @yieldreturn command [Array<String>] the command to be used in the system call SystemRunner = ->(data, &block) do options = data[:options] || {} builder = data.fetch(:builder).call output = data.fetch(:output) env = options.fetch(:env, {}) debug = options.fetch(:debug, false) || RUBY_ENGINE == 'opal' ext = builder.output_extension if options[:directory] tempdir = Dir.mktmpdir('opal-system-runner-') builder.compile_to_directory(tempdir, with_source_map: !options[:no_source_map]) cmd = block.call( VirtualFileObject.new(path: File.join(tempdir, "index.#{ext}")) ) else # Temporary issue with UTF-8, Base64, source maps and opalopal code = builder.compiled_source( with_source_map: !(options[:no_source_map] || RUBY_ENGINE == 'opal') ) tempfile = if debug File.new("opal-system-runner.#{ext}", 'wb') else Tempfile.new(['opal-system-runner', ".#{ext}"], mode: File::BINARY) end tempfile.write code cmd = block.call tempfile end if RUBY_PLATFORM == 'opal' # Opal doesn't support neither `out:` nor `IO.try_convert` nor `open3` system(env, *cmd) $?.exitstatus elsif IO.try_convert(output) system(env, *cmd, out: output) $?.exitstatus else require 'open3' captured_output, status = Open3.capture2(env, *cmd) output.write captured_output status.exitstatus end ensure tempfile.close if tempfile FileUtils.remove_entry(tempdir) if tempdir && !debug end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false