Class: Condenser::DartSassTransformer
- Inherits:
-
NodeProcessor
- Object
- NodeProcessor
- Condenser::DartSassTransformer
- Defined in:
- lib/condenser/transformers/dart_sass_transformer.rb
Direct Known Subclasses
Constant Summary collapse
- ACCEPT =
['text/css', 'text/scss', 'text/sass']
- @@helper_methods =
Set.new
Instance Attribute Summary collapse
-
#options ⇒ Object
Returns the value of attribute options.
Attributes inherited from NodeProcessor
Class Method Summary collapse
-
.add_helper_methods(module_to_add = nil, &block) ⇒ Object
Use this function to append Modules that contain functions to expose to dart-sass.
- .syntax ⇒ Object
Instance Method Summary collapse
- #call(environment, input) ⇒ Object
- #exec_runtime(script) ⇒ Object
- #expand_path(path, base = nil) ⇒ Object
- #find(importee, importer = nil) ⇒ Object
- #helper_method_signatures ⇒ Object
-
#initialize(dir, options = {}) ⇒ DartSassTransformer
constructor
A new instance of DartSassTransformer.
- #resolve(importee, importer = nil) ⇒ Object
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, = {}) super(dir) npm_install('sass') @options = .merge({ indentedSyntax: self.class.syntax == :sass }).freeze end |
Instance Attribute Details
#options ⇒ Object
Returns the value of attribute options.
7 8 9 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 7 def @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 |
.syntax ⇒ Object
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) = { 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()}; 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 = buffer.split("\n\n") buffer = buffer.end_with?("\n\n") ? '' : .pop .each do || = JSON.parse() ret = case ['method'] when 'result' result = ['args'][0] nil when 'load' importee = ['args'][0] importer = ['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: ['rid'], return: nil})) case ['args'][0] when 'AssetNotFound' = "Could not find import \"#{['args'][1]}\" for \"#{['args'][2]}\".\n\n" << build_tree(['args'][3], input, ['args'][2]) raise exec_runtime_error() else raise exec_runtime_error(['args'][0] + ': ' + ['args'][1]) end when 'call' if respond_to?(['args'][0]) send(['args'][0], *['args'][1]) else puts '!!!' end end io.write(JSON.generate({rid: ['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 (path, base=nil) if path.start_with?('.') File.(path, File.dirname(base)).delete_prefix(File.('.') + '/') else File.(path).delete_prefix(File.('.') + '/') 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((importee, importer), nil, accept: ACCEPT) end |
#helper_method_signatures ⇒ Object
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((importee, importer), accept: ACCEPT) end |