Class: Condenser::DartSassTransformer

Inherits:
NodeProcessor show all
Defined in:
lib/condenser/transformers/dart_sass_transformer.rb

Direct Known Subclasses

DartScssTransformer

Constant Summary collapse

ACCEPT =
['text/css', 'text/scss', 'text/sass']
@@helper_methods =
Set.new

Instance Attribute Summary collapse

Attributes inherited from NodeProcessor

#npm_path

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from NodeProcessor

#binary, call, #exec_runtime_error, #exec_syntax_error, #name, #npm_install, #npm_module_path, setup

Constructor Details

#initialize(dir, options = {}) ⇒ DartSassTransformer

Returns a new instance of DartSassTransformer.



26
27
28
29
30
31
32
33
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 26

def initialize(dir, options = {})
  super(dir)
  npm_install('sass')
  
  @options = options.merge({
    indentedSyntax: self.class.syntax == :sass
  }).freeze
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



7
8
9
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 7

def options
  @options
end

Class Method Details

.add_helper_methods(module_to_add = nil, &block) ⇒ Object

Use this function to append Modules that contain functions to expose to dart-sass



11
12
13
14
15
16
17
18
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 11

def self.add_helper_methods(module_to_add = nil, &block)
  old_methods = self.instance_methods
  
  self.include(module_to_add) if module_to_add
  self.class_eval(&block) if block_given?
  
  @@helper_methods.merge(self.instance_methods - old_methods)
end

.syntaxObject



22
23
24
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 22

def self.syntax
  :sass
end

Instance Method Details

#call(environment, input) ⇒ Object



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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 57

def call(environment, input)
  @context = environment.new_context_class#.new(environment)
  
  options = {
    verbose: true,
    file: File.join('/', input[:filename])
  }.merge(@options)
  @environment = environment
  @input = input

  result = exec_runtime(<<-JS)
    const fs    = require('fs');
    const sass = require("#{npm_module_path('sass')}");
    const stdin = process.stdin;
    stdin.resume();
    stdin.setEncoding('utf8');
    
    // SET STDOUT to sync so that we don't get in an infinte looping waiting
    // for Ruby to response when we haven't even sent the entire request.
    if (process.stdout._handle) process.stdout._handle.setBlocking(true)
      
    const source = #{JSON.generate(input[:source])};
    const options = #{JSON.generate(options)};

    var rid = 0;
    function request(method, ...args) {
      var trid = rid;
      rid += 1;
      console.log(JSON.stringify({ rid: trid, method: method, args: args }) + "\\n");
      

      var readBuffer = '';
      var response = null;
      let chunk = new Buffer(1024);
      let bytesRead;
      
      while (response === null) {
        try {
          bytesRead = fs.readSync(stdin.fd, chunk, 0, 1024);
          if (bytesRead === null) { exit(1); }
          readBuffer += chunk.toString('utf8', 0, bytesRead);
          [readBuffer, response] = readResponse(readBuffer);
        } catch (e) {
           if (e.code !== 'EAGAIN') { throw e; }
        }
      }
      return response['return'];
    }
    
    function readResponse(buffer) {
      try {
        var message = JSON.parse(buffer);
        return ['', message];
      } catch(e) {
        if (e.name === "SyntaxError") {
          if (e.message.startsWith('Unexpected non-whitespace character after JSON at position ')) {
            let pos = parseInt(e.message.slice(59));
            let [b, r] = readResponse(buffer.slice(0,pos));
            return [b + buffer.slice(pos), r];
          } else if (e.message.startsWith('Unexpected token { in JSON at position ')) {
            // This can be removed, once dropping support for node <= v18
            var pos = parseInt(e.message.slice(39));
            let [b, r] = readResponse(buffer.slice(0,pos));
            return [b + buffer.slice(pos), r];
          } else {
            return [buffer, null];
          }
        } else {
          console.log(JSON.stringify({method: 'error', args: [e.name, e.message]}) + "\\n");
          process.exit(1);
        }
      }
    }
    
    
    options.importer = function(url, prev) { return request('load', url, prev); };
    
    const call_fn = function(name, types, args) {
      const transformedArgs = [];
      request('log', '==================')
      args.forEach((a, i) => {
        if (types[i] === 'Map') {
          // Don't know how to go from SassMap to hash yet
          transformedArgs.push({});
        } else if (types[i] === 'List') {
          // Don't know how to go from SassList to hash yet
          transformedArgs.push([]);
        } else if (!(a instanceof sass.types[types[i]])) {
          throw "$url: Expected a string."; 
        } else {
          transformedArgs.push(a.getValue());
        }
         

        // if (types[i] === 'List') { a = a.contents(); }
      });
      request('log', name, transformedArgs, types)
      return new sass.types.String(request('call', name, transformedArgs));
    }
    options.functions = {};
    #{JSON.generate(helper_method_signatures)}.forEach( (f) => {
      let name = f[0].replace(/-/g, '_').replace(/(^[^\\(]+)\\(.*\\)$/, '$1');
      options.functions[f[0]] = (...a) => call_fn(name, f[1], a);
    })
    
    try {
      options.data = source;
      const result = sass.renderSync(options);
      request('result', result.css.toString());
      process.exit(0);
    } catch(e) {
      request('error', e.name, e.message);
      process.exit(1);
    }
  JS
  
  input[:source] = result
  # input[:map] = map.to_json({})
  input[:linked_assets]         += @context.links
  input[:process_dependencies]  += @context.dependencies
end

#exec_runtime(script) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 197

def exec_runtime(script)
  io = IO.popen([binary, '-e', script], 'r+')
  buffer = ''
  result = nil
  
  begin
    while IO.select([io]) && io_read = io.read_nonblock(1_024)
      buffer << io_read
      messages = buffer.split("\n\n")
      buffer = buffer.end_with?("\n\n") ? '' : messages.pop
      
      messages.each do |message|
        message = JSON.parse(message)

        ret = case message['method']
        when 'result'
          result = message['args'][0]
          nil
        when 'load'
          importee = message['args'][0]
          importer = message['args'][1]
          
          if importee.end_with?('*')
            @context.depend_on(importee)
            code = ""
            resolve(importee, importer).each do |f, i|
              code << "@import '#{f.filename}';\n"
            end
            { contents: code, map: nil }
          else
            if asset = find(importee)
              @context.depend_on(asset.filename)
              { contents: asset.source, map: asset.sourcemap }
            else
              @context.depend_on(importee)
              nil
            end
          end
        when 'error'
          io.write(JSON.generate({rid: message['rid'], return: nil}))
          
          case message['args'][0]
          when 'AssetNotFound'
            error_message = "Could not find import \"#{message['args'][1]}\" for \"#{message['args'][2]}\".\n\n"
            error_message << build_tree(message['args'][3], input, message['args'][2])
            raise exec_runtime_error(error_message)
          else
            raise exec_runtime_error(message['args'][0] + ': ' + message['args'][1])
          end
        when 'call'
          if respond_to?(message['args'][0])
            send(message['args'][0], *message['args'][1])
          else
            puts '!!!'
          end
        end

        io.write(JSON.generate({rid: message['rid'], return: ret}))
      end
    end
  rescue Errno::EPIPE, EOFError
  end
  
  io.close
  if $?.success?
    result
  else
    raise exec_runtime_error(buffer)
  end
end

#expand_path(path, base = nil) ⇒ Object



189
190
191
192
193
194
195
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 189

def expand_path(path, base=nil)
  if path.start_with?('.')
    File.expand_path(path, File.dirname(base)).delete_prefix(File.expand_path('.') + '/')
  else
    File.expand_path(path).delete_prefix(File.expand_path('.') + '/')
  end
end

#find(importee, importer = nil) ⇒ Object



179
180
181
182
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 179

def find(importee, importer = nil)
  # importer ||= @input[:source_file]
  @environment.find(expand_path(importee, importer), nil, accept: ACCEPT)
end

#helper_method_signaturesObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 35

def helper_method_signatures
  x = @@helper_methods.map do |name|
    arity = self.method(name).arity
    signature = []
    types = []
    if respond_to?(:"#{name}_signature")
      send(:"#{name}_signature").each do |arg, type|
        signature << arg
        types << type
      end
    elsif arity >= 0
      arity.times.with_index do |a|
        signature << "$arg#{a}"
        types << 'String'
      end
    end
    
    ["#{name}(#{signature.join(', ')})", types]
  end
  x
end

#resolve(importee, importer = nil) ⇒ Object



184
185
186
187
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 184

def resolve(importee, importer = nil)
  # importer ||= @input[:source_file]
  @environment.resolve(expand_path(importee, importer), accept: ACCEPT)
end