Class: AutoreloadServer::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/autoreload_server/server.rb

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Server

Returns a new instance of Server.



12
13
14
15
16
# File 'lib/autoreload_server/server.rb', line 12

def initialize(opts)
  @opts = opts
  @directory = File.expand_path(opts[:directory])
  @watcher = nil
end

Instance Method Details

#create_sinatra_appObject

rubocop:disable Metrics/AbcSize, Metrics/MethodLength



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/autoreload_server/server.rb', line 35

def create_sinatra_app # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
  opts = @opts
  directory = @directory
  server = self

  app = Sinatra.new do # rubocop:disable Metrics/BlockLength
    set :server, :webrick
    set :bind, opts[:host]
    set :port, opts[:port]
    set :static, false
    set :logging, false
    set :pending_reload, false
    set :connections, []

    get '/autoreload-events' do
      content_type 'text/event-stream'
      headers['Cache-Control'] = 'no-cache'
      headers['Access-Control-Allow-Origin'] = '*'
      headers['Connection'] = 'keep-alive'

      # Create a new EventSource connection
      stream do |out|
        # Send initial connection message
        out << "data: #{JSON.generate({ type: 'connected' })}\n\n"

        # Keep connection alive with periodic heartbeat
        heartbeat_thread = Thread.new do
          loop do
            sleep 30
            begin
              out << "data: #{JSON.generate({ type: 'heartbeat' })}\n\n"
            rescue StandardError
              # Connection closed
              break
            end
          end
        end

        # Monitor for reload events
        loop do
          if settings.pending_reload
            puts '[autoreload-server] Sending reload event to client'
            settings.pending_reload = false
            out << "data: #{JSON.generate({ type: 'update', reload: true })}\n\n"
            break
          end
          sleep 1
        end

        heartbeat_thread.kill if heartbeat_thread&.alive?
      end
    end

    get '/*' do
      requested_path = params['splat'].first || ''
      requested_path = 'index.html' if requested_path.empty?
      file_path = File.join(directory, requested_path)

      if File.directory?(file_path)
        index_file = File.join(file_path, 'index.html')
        file_path = index_file if File.exist?(index_file)
      end

      if File.exist?(file_path) && file_path.end_with?('.html')
        content = File.read(file_path)
        server.inject_client_script(content)
      elsif File.exist?(file_path)
        send_file file_path
      end
    end
  end

  @app = app
  app
end

#inject_client_script(html) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
# File 'lib/autoreload_server/server.rb', line 111

def inject_client_script(html)
  doc = Nokogiri::HTML::Document.parse(html)

  if (head = doc.at('head'))
    head.add_child(client_script)
  else
    doc.at('html').add_child("<head>#{client_script}</head>")
  end

  doc.to_html
end

#startObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/autoreload_server/server.rb', line 18

def start
  puts '[autoreload-server] Initializing server...'
  start_file_watcher

  puts '[autoreload-server] Starting server...'
  puts "[autoreload-server] Directory: #{@directory}"
  puts "[autoreload-server] Server: http://#{@opts[:host]}:#{@opts[:port]}"

  Rackup::Handler::WEBrick.run(
    create_sinatra_app,
    Host: @opts[:host],
    Port: @opts[:port],
    Logger: WEBrick::Log.new(IO::NULL),
    AccessLog: []
  )
end