Class: Condenser::RollupProcessor

Inherits:
NodeProcessor show all
Defined in:
lib/condenser/processors/rollup_processor.rb

Constant Summary collapse

ROLLUP_VERSION =
'0.56.1'

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from NodeProcessor

#binary, #exec_runtime_error, #exec_syntax_error, node_modules_path, #node_modules_path, setup

Constructor Details

#initialize(options = {}) ⇒ RollupProcessor

Returns a new instance of RollupProcessor.



12
13
14
# File 'lib/condenser/processors/rollup_processor.rb', line 12

def initialize(options = {})
  @options = options.merge({}).freeze
end

Class Method Details

.call(environment, input) ⇒ Object



8
9
10
# File 'lib/condenser/processors/rollup_processor.rb', line 8

def self.call(environment, input)
  new.call(environment, input)
end

Instance Method Details

#build_tree(renderStack, from, to, visited: nil) ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/condenser/processors/rollup_processor.rb', line 300

def build_tree(renderStack, from, to, visited: nil)
  visited ||= []
  return if visited.include?(from)
  visited << from
  
  if renderStack[from].nil? || renderStack[from].empty?
    nil
  elsif renderStack[from].include?(to)
    from
  else
    renderStack[from].each do |dep|
      if tree = build_tree(renderStack, dep, to, visited: visited)
        return "#{from}\n└ #{tree.lines.each_with_index.map{|l, i| "#{i == 0 ? '' : '    '}#{l}"}.join("")}"
      end
    end
    nil
  end
end

#call(environment, input) ⇒ Object



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
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
178
179
# File 'lib/condenser/processors/rollup_processor.rb', line 16

def call(environment, input)
  @environment = environment
  @input = input
  
  Dir.mktmpdir do |output_dir|
    @entry = File.join(output_dir, 'entry.js')
    input_options = {
      input: @entry
    }
    output_options = {
      file: File.join(output_dir, 'result.js'),
      format: 'iife',
      # output: { sourcemap: true, format: 'iife' },
      globals: [],
      sourcemap: true
    }
    if input[:source] =~ /export\s+{[^}]+};?\z/i
      output_options[:name] = File.basename(input[:filename], ".*").capitalize
      # output_options[:output][:name] = File.basename(input[:filename], ".*").capitalize
    end

    exec_runtime(<<-JS, @entry)
      const fs    = require('fs');
      const path  = require('path');
      const stdin = process.stdin;

      module.paths.push("#{File.expand_path('../node_modules', __FILE__)}")

      var buffer = '';
      stdin.resume();
      stdin.setEncoding('utf8');
      function emitMessages(buffer) {
        try {
          var message = JSON.parse(buffer);
          stdin.emit('message' + message.rid, message);
          return '';
        } catch(e) {
          if (e.name === "SyntaxError") {
            if (e.message.startsWith('Unexpected token { in JSON at position ')) {
              var pos = parseInt(e.message.slice(39));
              emitMessages(buffer.slice(0,pos));
              return emitMessages(buffer.slice(pos));
            } else {
              return buffer;
            }
          } else {
            console.log(JSON.stringify({method: 'error', args: [e.name, e.message]}) + "\\n");
            process.exit(1);
          }
        }
      }

      stdin.on('data', function (chunk) {
        buffer += chunk;
        buffer = emitMessages(buffer);
      });
      
      const rollup = require("#{File.expand_path('../node_modules', __FILE__)}/rollup");
      const commonjs = require('#{File.expand_path('../node_modules', __FILE__)}/rollup-plugin-commonjs');
      const nodeResolve = require('#{File.expand_path('../node_modules', __FILE__)}/rollup-plugin-node-resolve');
      var rid = 0;
      var renderStack = {};
      var nodeResolver = null;
      
      function request(method, args) {
        var trid = rid;
        rid += 1;
        var promise = new Promise(function(resolve, reject) {
          stdin.once('message' + trid, function(message) {
            resolve(message['return']);
          });
        });

        console.log(JSON.stringify({ rid: trid, method: method, args: args }) + "\\n");

        return promise;
      }

      if ('#{environment.npm_path}' !== '') {
        nodeResolver = nodeResolve({
          mainFields: ['module', 'main'],
          // modulesOnly: true,
          // preferBuiltins: false,
          customResolveOptions: {
            moduleDirectory: '#{environment.npm_path}'
          }
        });
      }

      const inputOptions = #{JSON.generate(input_options)};
      inputOptions.plugins = [];
      inputOptions.plugins.push({
        name: 'condenser',
        resolveId: function (importee, importer) {
          if (importee.startsWith('\\0') || (importer && importer.startsWith('\\0'))) {
            return;
          }

          if (!(importer in renderStack)) {
            renderStack[importer] = [];
          }

          return request('resolve', [importee, importer]).then((value) => {
            if (nodeResolver && (value === null || value === undefined)) {
              return nodeResolver.resolveId.call(this, importee, importer).then((value) => {
                if (!(value === null || value === undefined) && !renderStack[importer].includes(value.id)) {
                  renderStack[importer].push(value.id);
                }
                return value;
              });
            }

            if (!(value === null || value === undefined) && !renderStack[importer].includes(value)) {
              renderStack[importer].push(value);
            }
            return value;
          });
        },
        load: function(id) {
          if (id.startsWith('\\0')) {
            return;
          }

          return request('load', [id]).then(function(value) {
            return value;
          });
        }
      });
      inputOptions.plugins.push(nodeResolver);
      inputOptions.plugins.push(commonjs());
      
      inputOptions.plugins.push({
        name: 'nullHanlder',
        resolveId: function (importee, importer) {
          request('error', ["AssetNotFound", importee, importer, renderStack]).then(function(value) {
            process.exit(1);
          });
        }
      });

      const outputOptions = #{JSON.generate(output_options)};

      async function build() {
        try {
          // inputOptions.cache = await JSON.parse(request('get_cache', []));
          
          const bundle = await rollup.rollup(inputOptions);
          await bundle.write(outputOptions);
          // await request('set_cache', [JSON.stringify(bundle)]);
          process.exit(0);
        } catch(e) {
          await request('error', [e.name, e.message, e.stack]);
          process.exit(1);
        }
      }

      build();
    JS
    
    input[:source] = File.read(File.join(output_dir, 'result.js'))
    input[:source].delete_suffix!("//# sourceMappingURL=result.js.map\n")
    # asset.map = File.read(File.join(output_dir, 'result.js.map'))
  end
end

#exec_runtime(script, input) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/condenser/processors/rollup_processor.rb', line 181

def exec_runtime(script, input)
  io = IO.popen([binary, '-e', script], 'r+')
  buffer = ''
  
  begin
    
    while IO.select([io]) && io_read = io.read_nonblock(1_024)
      buffer << io_read
      messages = buffer.split("\n\n")
      
      buffer = if buffer.end_with?("\n\n")
        ''
      else
        messages.pop
      end
      
      messages.each do |message|
        message = JSON.parse(message)
        
        ret = case message['method']
        when 'resolve'
          importee, importer = message['args']

          asset = if importer.nil? && importee == @entry
            @entry
          elsif importee.start_with?('@babel/runtime') || importee.start_with?('core-js-pure') || importee.start_with?('regenerator-runtime')
            x = File.expand_path('../node_modules/' + importee.gsub(/^\.\//, File.dirname(importer) + '/'), __FILE__).sub('/node_modules/regenerator-runtime', '/node_modules/regenerator-runtime/runtime.js')
            x = "#{x}.js" if !x.end_with?('.js')
            File.file?(x) ? x : (x.delete_suffix('.js') + "/index.js")
          elsif importer.start_with?(File.expand_path('../node_modules/', __FILE__))
            x = File.expand_path(importee, File.dirname(importer))
            x = x.end_with?('.js') ? x : "#{x}.js"
            File.file?(x) ? x : (x.delete_suffix('.js') + "/index.js")
          elsif @environment.npm_path &&
                importer.start_with?(@environment.npm_path) #&&
            #     File.file?(File.expand_path(importee, File.dirname(importer))) &&
            #     File.file?(File.expand_path(importee, File.dirname(importer)) + '.js')
            # x = File.expand_path(importee, File.dirname(importer))
            # x.end_with?('.js') ? x : "#{x}.js"
            nil
          else
            if importee.end_with?('*')
              File.join(File.dirname(importee), '*')
            else
              @environment.find(importee, importer ? File.dirname(@entry == importer ? @input[:source_file] : importer) : nil, accept: @input[:content_types].last)&.source_file
            end
          end

          # begin
            asset
          # rescue Errno::EPIPE
            # puts io.read
            # raise
          # end
        when 'load'
          importee = message['args'].first
          if importee == @entry
            { code: @input[:source], map: @input[:map] }
          elsif importee.start_with?(File.expand_path('../node_modules/', __FILE__))
            { code: File.read(importee), map: nil }
          elsif importee.end_with?('*')
            importees = @environment.resolve(importee, importer ? File.dirname(@entry == importer ? @input[:source_file] : importer) : nil, accept: @input[:content_types].last)
            code = ""
            code_imports = [];
            importees.each_with_index.map do |f, i|
              if f.has_default_export?
                code << "import _#{i} from '#{f.source_file}';\n"
                code_imports << "_#{i}"
              elsif f.has_exports?
                code << "import * as _#{i} from '#{f.source_file}';\n"
                code_imports << "_#{i}"
              else
                code << "import '#{f.source_file}';\n"
              end
            end
            
            code += "export default [#{code_imports.join(', ')}];"

            { code: code, map: nil }
          else
            asset = @environment.find(importee, accept: @input[:content_types].last)
            if asset
              { code: asset.source, map: asset.sourcemap }
            else
              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 'set_cache'
        #   @environment.cache.set('rollup', message['args'][0])
        #   io.write(JSON.generate({rid: message['rid'], return: true}))
        # when 'get_cache'
        #   io.write(JSON.generate({rid: message['rid'], return: [(@environment.cache.get('rollup') || '{}')] }))
        end

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