Sha256: 6fff4b8d7fc2f91e41f15bc085234bc77f40ef8b1c37f72cfe6f84097404b2ef

Contents?: true

Size: 1.99 KB

Versions: 12

Compression:

Stored size: 1.99 KB

Contents

# frozen_string_literal: true

require "json"
require "forwardable"
require "pathname"

require "source_map"

module Pakyow
  module Assets
    class SourceMap
      class << self
        def mapping_url(path:, type:)
          case type.to_sym
          when :css
            "\n/*# sourceMappingURL=#{path}.map */\n"
          when :javascript
            "\n//# sourceMappingURL=#{path}.map\n"
          end
        end
      end

      extend Forwardable
      def_delegators :@internal, :mappings

      attr_reader :file, :sources, :sources_content

      def initialize(content = nil, file:)
        @file = file

        @raw = content

        if content.is_a?(String)
          content = JSON.parse(content)
        end

        @sources = if content
          content["sources"].dup
        else
          []
        end

        @sources_content = if content
          content["sourcesContent"].to_a
        else
          []
        end

        @internal = if content.nil?
          ::SourceMap.new
        else
          ::SourceMap.from_json(content)
        end
      end

      def merge(other)
        tap do
          other.mappings.each do |mapping|
            @internal.add_mapping(mapping)
          end

          @sources.concat(other.sources)
          @sources_content.concat(other.sources_content)
        end
      end

      def mime_type
        "application/octet-stream"
      end

      def bytesize
        read.bytesize
      end

      def read
        root = "/"
        map = @internal.as_json
        map["file"] = @file
        map["sourceRoot"] = root

        # The source_map gem reorders sources, so make sure that the sources content matches.
        #
        map["sourcesContent"] = map["sources"].map { |source|
          @sources_content[@sources.index(source)]
        }

        map["sources"].map! do |source|
          File.join(root, source)
        end

        map.to_json
      end

      def each(&block)
        StringIO.new(read).each(&block)
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
pakyow-assets-1.0.6 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.5 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.4 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.3 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.2 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.1 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.0 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.0.rc5 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.0.rc4 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.0.rc3 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.0.rc2 lib/pakyow/assets/source_map.rb
pakyow-assets-1.0.0.rc1 lib/pakyow/assets/source_map.rb