Class: Mbeditor::JsSyntaxCheckService

Inherits:
Object
  • Object
show all
Defined in:
app/services/mbeditor/js_syntax_check_service.rb

Overview

Save-time JS/JSX syntax check using the HOST app's own toolchain: runs babel-standalone inside a MiniRacer (V8) context — the same transform that sprockets/react-rails will apply — so code that would break the host's asset pipeline is caught in the editor instead of at page load.

Zero new dependencies (ADR-0001): active only when the host already has mini_racer loaded AND a babel-standalone asset can be found. Degrades to a no-op otherwise.

Constant Summary collapse

EVAL_TIMEOUT_MS =
2_000
MAX_CHECKS_PER_CONTEXT =

V8 heap grows across transforms; recreate the context periodically.

50
BABEL_ASSET_CANDIDATES =
%w[babel.min.js babel.js babel-standalone.js babel-standalone.min.js].freeze

Class Method Summary collapse

Class Method Details

.available?Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
# File 'app/services/mbeditor/js_syntax_check_service.rb', line 22

def available?
  return false if Mbeditor.configuration.js_syntax_check == false
  return false unless defined?(::MiniRacer)

  !babel_source_path.nil?
end

.check(source) ⇒ Object

Returns nil when the source parses cleanly (or the checker is unavailable/broken), else { "message" =>, "line" =>, "column" => }.



31
32
33
34
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
# File 'app/services/mbeditor/js_syntax_check_service.rb', line 31

def check(source)
  return nil unless available?

  MUTEX.synchronize do
    begin
      ctx = context
      return nil unless ctx

      result = ctx.eval(<<~JS)
        (function () {
          try {
            Babel.transform(#{source.to_json}, { presets: ["react"], code: false });
            return null;
          } catch (e) {
            return {
              message: String((e && e.message) || e).split("\\n")[0],
              line: (e && e.loc && e.loc.line) || null,
              column: (e && e.loc && e.loc.column) || null
            };
          }
        })()
      JS

      @checks_run = (@checks_run || 0) + 1
      reset_context! if @checks_run >= MAX_CHECKS_PER_CONTEXT
      result
    rescue StandardError
      # Timeout / V8 OOM / eval failure: recreate on next use, report clean.
      reset_context!
      nil
    end
  end
end

.reset!Object

Exposed for tests.



66
67
68
69
70
71
# File 'app/services/mbeditor/js_syntax_check_service.rb', line 66

def reset!
  MUTEX.synchronize do
    reset_context!
    @babel_path = :unresolved
  end
end