Class: Opal::SourceMap

Inherits:
Object show all
Defined in:
opal/lib/opal/source_map.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fragments, file) ⇒ SourceMap

Returns a new instance of SourceMap



9
10
11
12
# File 'opal/lib/opal/source_map.rb', line 9

def initialize(fragments, file)
  @fragments = fragments
  @file = file
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file



7
8
9
# File 'opal/lib/opal/source_map.rb', line 7

def file
  @file
end

#fragmentsObject (readonly)

Returns the value of attribute fragments



6
7
8
# File 'opal/lib/opal/source_map.rb', line 6

def fragments
  @fragments
end

Instance Method Details

#as_jsonObject



58
59
60
# File 'opal/lib/opal/source_map.rb', line 58

def as_json
  map.as_json
end

#magic_comment(map_path) ⇒ Object



66
67
68
# File 'opal/lib/opal/source_map.rb', line 66

def magic_comment map_path
  "\n//# sourceMappingURL=file://#{map_path}"
end

#mapObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
# File 'opal/lib/opal/source_map.rb', line 14

def map
  @map ||= begin
    source_file = file+'.rb'
    generated_line, generated_column = 1, 0

    mappings = @fragments.map do |fragment|
      mapping = nil
      source_line   = fragment.line
      source_column = fragment.column
      source_code   = fragment.code

      if source_line and source_column
        source_offset    = ::SourceMap::Offset.new(source_line, source_column)
        generated_offset = ::SourceMap::Offset.new(generated_line, generated_column)

        mapping = ::SourceMap::Mapping.new(
          source_file,
          generated_offset,
          source_offset
        )
      end

      new_lines = source_code.count "\n"
      generated_line += new_lines

      if new_lines > 0
        generated_column = source_code.size - (source_code.rindex("\n") + 1)
      else
        generated_column += source_code.size
      end

      mapping
    end

    # Ensure mappings isn't empty: https://github.com/maccman/sourcemap/issues/11
    unless mappings.any?
      zero_offset = ::SourceMap::Offset.new(0,0)
      mappings = [::SourceMap::Mapping.new(source_file,zero_offset,zero_offset)]
    end

    ::SourceMap::Map.new(mappings.compact)
  end
end

#to_sObject



62
63
64
# File 'opal/lib/opal/source_map.rb', line 62

def to_s
  map.to_s
end