class ViteRuby::DevServerProxy

Public: Allows to relay asset requests to the Vite development server.

Constants

HOST_WITH_PORT_REGEX
VITE_DEPENDENCY_PREFIX

Public Class Methods

new(app = nil, options = {}) click to toggle source
Calls superclass method
# File lib/vite_ruby/dev_server_proxy.rb, line 10
def initialize(app = nil, options = {})
  @vite_ruby = options.delete(:vite_ruby) || ViteRuby.instance
  options[:streaming] = false if config.mode == 'test' && !options.key?(:streaming)
  super
end

Public Instance Methods

perform_request(env) click to toggle source

Rack: Intercept asset requests and send them to the Vite server.

Calls superclass method
# File lib/vite_ruby/dev_server_proxy.rb, line 17
def perform_request(env)
  if vite_should_handle?(env) && dev_server_running?
    forward_to_vite_dev_server(env)
    super(env)
  else
    @app.call(env)
  end
end

Private Instance Methods

file_in_vite_root?(path) click to toggle source
# File lib/vite_ruby/dev_server_proxy.rb, line 58
def file_in_vite_root?(path)
  path.include?('.') && # Check for extension, avoid filesystem if possible.
    config.vite_root_dir.join(path.start_with?('/') ? path[1..-1] : path).file?
end
forward_to_vite_dev_server(env) click to toggle source
# File lib/vite_ruby/dev_server_proxy.rb, line 40
def forward_to_vite_dev_server(env)
  rewrite_uri_for_vite(env)
  env['QUERY_STRING'] ||= ''
  env['HTTP_HOST'] = env['HTTP_X_FORWARDED_HOST'] = config.host
  env['HTTP_X_FORWARDED_SERVER'] = config.host_with_port
  env['HTTP_PORT'] = env['HTTP_X_FORWARDED_PORT'] = config.port.to_s
  env['HTTP_X_FORWARDED_PROTO'] = env['HTTP_X_FORWARDED_SCHEME'] = config.protocol
  env['HTTPS'] = env['HTTP_X_FORWARDED_SSL'] = 'off' unless config.https
  env['SCRIPT_NAME'] = ''
end
rewrite_uri_for_vite(env) click to toggle source
# File lib/vite_ruby/dev_server_proxy.rb, line 32
def rewrite_uri_for_vite(env)
  uri = env.fetch('REQUEST_URI') { [env['PATH_INFO'], env['QUERY_STRING']].reject { |str| str.to_s.strip.empty? }.join('?') }
    .sub(HOST_WITH_PORT_REGEX, '/') # Hanami adds the host and port.
    .sub('.ts.js', '.ts') # Hanami's javascript helper always adds the extension.
    .sub(/(\.(?!min|module)\w+)\.css$/, '\1') # Rails' stylesheet_link_tag always adds the extension.
  env['PATH_INFO'], env['QUERY_STRING'] = (env['REQUEST_URI'] = uri).split('?')
end
vite_asset_url_prefix() click to toggle source
# File lib/vite_ruby/dev_server_proxy.rb, line 63
def vite_asset_url_prefix
  @vite_asset_url_prefix ||= "/#{ config.public_output_dir }/"
end
vite_should_handle?(env) click to toggle source
# File lib/vite_ruby/dev_server_proxy.rb, line 51
def vite_should_handle?(env)
  path = env['PATH_INFO']
  return true if path.start_with?(vite_asset_url_prefix) # Vite asset
  return true if path.start_with?(VITE_DEPENDENCY_PREFIX) # Packages and imports
  return true if file_in_vite_root?(path) # Fallback if Vite can serve the file
end