<commit_before>require 'stringio'
require 'volt'
require 'volt/server/rack/component_code'

module Volt
  class ComponentHandler
    def initialize(component_paths)
      @component_paths = component_paths
    end

    def call(env)
      req            = Rack::Request.new(env)

      # TODO: Sanatize template path
      component_name = req.path.strip.gsub(/^\/components\//, '').gsub(/[.]js$/, '')

      javascript_code = compile_for_component(component_name)

      [200, { 'Content-Type' => 'application/javascript; charset=utf-8' }, StringIO.new(javascript_code)]
    end

    def compile_for_component(component_name)
      code = ComponentCode.new(component_name, @component_paths).code

      # Compile the code
      # javascript_code = Opal.compile(code)
      javascript_code = Opal::Builder.new.build_str(code, 'app.rb').to_s

      javascript_code
    end
  end
end<commit_msg>Working on moving to Opal::Builder<commit_after>require 'stringio'
require 'volt'
require 'volt/server/rack/component_code'

module Volt
  class ComponentHandler
    def initialize(component_paths)
      @component_paths = component_paths
    end

    def call(env)
      req            = Rack::Request.new(env)

      path = req.path.strip

      request_source_map = (File.extname(path) == '.map')

      # TODO: Sanatize template path
      component_name = path.gsub(/^\/components\//, '').gsub(/[.](js|map)$/, '')

      javascript_code = compile_for_component(component_name, request_source_map)

      [200, { 'Content-Type' => 'application/javascript; charset=utf-8' }, StringIO.new(javascript_code)]
    end

    def compile_for_component(component_name, map=false)
      code = ComponentCode.new(component_name, @component_paths).code

      # Compile the code
      # javascript_code = Opal.compile(code)
      builder = Opal::Builder.new.build_str(code, 'app.rb')

      if map
        js_code = builder.source_map
      else
        js_code = builder.to_s + "\n//# sourceMappingURL=#{component_name}.map"
      end

      js_code
    end
  end
end
{'fraction_non_alphanumeric': 0.11836337067705796, 'fraction_numerical': 0.003896736483195324, 'mean_word_length': 3.1578947368421053, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5307866', 'n_tokens_mistral': 669, 'n_tokens_neox': 629, 'n_words': 122}