Class: ThemeJavascriptCompiler

Inherits:
Object
  • Object
show all
Defined in:
lib/theme_javascript_compiler.rb

Defined Under Namespace

Classes: CompileError

Constant Summary collapse

COLOCATED_CONNECTOR_REGEX =
%r{\A(?<prefix>.*/?)connectors/(?<outlet>[^/]+)/(?<name>[^/\.]+)\.(?<extension>.+)\z}
@@terser_disabled =
false

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(theme_id, theme_name, minify: true) ⇒ ThemeJavascriptCompiler

Returns a new instance of ThemeJavascriptCompiler.



21
22
23
24
25
26
# File 'lib/theme_javascript_compiler.rb', line 21

def initialize(theme_id, theme_name, minify: true)
  @theme_id = theme_id
  @output_tree = []
  @theme_name = theme_name
  @minify = minify
end

Class Method Details

.disable_terser!Object



11
12
13
14
# File 'lib/theme_javascript_compiler.rb', line 11

def self.disable_terser!
  raise "Tests only" if !Rails.env.test?
  @@terser_disabled = true
end

.enable_terser!Object



16
17
18
19
# File 'lib/theme_javascript_compiler.rb', line 16

def self.enable_terser!
  raise "Tests only" if !Rails.env.test?
  @@terser_disabled = false
end

Instance Method Details

#append_ember_template(name, hbs_template) ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/theme_javascript_compiler.rb', line 189

def append_ember_template(name, hbs_template)
  module_name = name
  module_name = "/#{module_name}" if !module_name.start_with?("/")
  module_name = "discourse/theme-#{@theme_id}#{module_name}"

  # Mimics the ember-cli implementation
  # https://github.com/ember-cli/ember-cli-htmlbars/blob/d5aa14b3/lib/template-compiler-plugin.js#L18-L26
  script = <<~JS
    import { hbs } from 'ember-cli-htmlbars';
    export default hbs(#{hbs_template.to_json}, { moduleName: #{module_name.to_json} });
  JS

  template_module = DiscourseJsProcessor.transpile(script, "", module_name, theme_id: @theme_id)
  @output_tree << ["#{name}.js", <<~JS]
    if ('define' in window) {
    #{template_module}
    }
  JS
rescue MiniRacer::RuntimeError, DiscourseJsProcessor::TranspileError => ex
  raise CompileError.new ex.message
end

#append_js_error(filename, message) ⇒ Object



265
266
267
268
# File 'lib/theme_javascript_compiler.rb', line 265

def append_js_error(filename, message)
  message = "[THEME #{@theme_id} '#{@theme_name}'] Compile error: #{message}"
  append_raw_script filename, "console.error(#{message.to_json});"
end

#append_module(script, name, extension, include_variables: true) ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/theme_javascript_compiler.rb', line 249

def append_module(script, name, extension, include_variables: true)
  original_filename = name
  name = "discourse/theme-#{@theme_id}/#{name}"

  script = "#{theme_settings}#{script}" if include_variables
  transpiler = DiscourseJsProcessor::Transpiler.new

  @output_tree << ["#{original_filename}.#{extension}", <<~JS]
    if ('define' in window) {
    #{transpiler.perform(script, "", name, theme_id: @theme_id, extension: extension).strip}
    }
  JS
rescue MiniRacer::RuntimeError, DiscourseJsProcessor::TranspileError => ex
  raise CompileError.new ex.message
end

#append_raw_script(filename, script) ⇒ Object



245
246
247
# File 'lib/theme_javascript_compiler.rb', line 245

def append_raw_script(filename, script)
  @output_tree << [filename, script + "\n"]
end

#append_raw_template(name, hbs_template) ⇒ Object



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
# File 'lib/theme_javascript_compiler.rb', line 215

def append_raw_template(name, hbs_template)
  compiled =
    DiscourseJsProcessor::Transpiler.new.compile_raw_template(hbs_template, theme_id: @theme_id)
  source_for_comment = hbs_template.gsub("*/", '*\/').indent(4, " ")
  modern_replacement_marker = hbs_template.include?("{{!-- has-modern-replacement --}}")

  source = <<~JS
    /*
    #{source_for_comment}
    */

    import { template as compiler } from "discourse-common/lib/raw-handlebars";
    import { addRawTemplate } from "discourse-common/lib/raw-templates";

    let template = compiler(#{compiled});

    addRawTemplate(#{raw_template_name(name).to_json}, template, {
      themeId: #{@theme_id},
      themeName: #{@theme_name.to_json},
      hasModernReplacement: #{modern_replacement_marker}
    });

    export default template;
  JS

  append_module source, "raw-templates/#{raw_template_name(name)}", "js", include_variables: false
rescue MiniRacer::RuntimeError, DiscourseJsProcessor::TranspileError => ex
  raise CompileError.new ex.message
end

#append_tree(tree, include_variables: true) ⇒ Object



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
180
181
182
183
184
185
186
187
# File 'lib/theme_javascript_compiler.rb', line 98

def append_tree(tree, include_variables: true)
  # Replace legacy extensions
  tree.transform_keys! do |filename|
    if filename.ends_with? ".js.es6"
      filename.sub(/\.js\.es6\z/, ".js")
    elsif filename.include? "/templates/"
      filename = filename.sub(/\.raw\.hbs\z/, ".hbr") if filename.ends_with? ".raw.hbs"

      if filename.ends_with? ".hbr"
        filename.sub(%r{/templates/}, "/raw-templates/")
      else
        filename
      end
    else
      filename
    end
  end

  # Some themes are colocating connector JS under `/connectors`. Move template to /templates to avoid module name clash
  tree.transform_keys! do |filename|
    match = COLOCATED_CONNECTOR_REGEX.match(filename)
    next filename if !match

    is_template = match[:extension] == "hbs"
    is_in_templates_directory = match[:prefix].split("/").last == "templates"

    if is_template && !is_in_templates_directory
      "#{match[:prefix]}templates/connectors/#{match[:outlet]}/#{match[:name]}.#{match[:extension]}"
    elsif !is_template && is_in_templates_directory
      "#{match[:prefix].chomp("templates/")}connectors/#{match[:outlet]}/#{match[:name]}.#{match[:extension]}"
    else
      filename
    end
  end

  # Handle colocated components
  tree.dup.each_pair do |filename, content|
    is_component_template =
      filename.end_with?(".hbs") &&
        filename.start_with?("discourse/components/", "admin/components/")
    next if !is_component_template
    template_contents = content

    hbs_invocation_options = { moduleName: filename, parseOptions: { srcName: filename } }
    hbs_invocation = "hbs(#{template_contents.to_json}, #{hbs_invocation_options.to_json})"

    prefix = <<~JS
      import { hbs } from 'ember-cli-htmlbars';
      const __COLOCATED_TEMPLATE__ = #{hbs_invocation};
    JS

    js_filename = filename.sub(/\.hbs\z/, ".js")
    js_contents = tree[js_filename] # May be nil for template-only component
    if js_contents && !js_contents.include?("export default")
      message =
        "#{filename} does not contain a `default export`. Did you forget to export the component class?"
      js_contents += "throw new Error(#{message.to_json});"
    end

    if js_contents.nil?
      # No backing class, use template-only
      js_contents = <<~JS
        import templateOnly from '@ember/component/template-only';
        export default templateOnly();
      JS
    end

    js_contents = prefix + js_contents

    tree[js_filename] = js_contents
    tree.delete(filename)
  end

  # Transpile and write to output
  tree.each_pair do |filename, content|
    module_name, extension = filename.split(".", 2)

    if extension == "js" || extension == "gjs"
      append_module(content, module_name, extension, include_variables:)
    elsif extension == "hbs"
      append_ember_template(module_name, content)
    elsif extension == "hbr"
      append_raw_template(module_name.sub("discourse/raw-templates/", ""), content)
    else
      append_js_error(filename, "unknown file extension '#{extension}' (#{filename})")
    end
  rescue CompileError => e
    append_js_error filename, "#{e.message} (#{filename})"
  end
end

#compile!Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/theme_javascript_compiler.rb', line 28

def compile!
  if !@compiled
    @compiled = true
    @output_tree.freeze

    output =
      if !has_content?
        { "code" => "" }
      elsif @@terser_disabled || !@minify
        { "code" => raw_content }
      else
        DiscourseJsProcessor::Transpiler.new.terser(@output_tree.to_h, terser_config)
      end

    @content = output["code"]
    @source_map = output["map"]
  end
  [@content, @source_map]
rescue DiscourseJsProcessor::TranspileError => e
  message = "[THEME #{@theme_id} '#{@theme_name}'] Compile error: #{e.message}"
  @content = "console.error(#{message.to_json});\n"
  [@content, @source_map]
end

#contentObject



70
71
72
73
# File 'lib/theme_javascript_compiler.rb', line 70

def content
  compile!
  @content
end

#has_content?Boolean

Returns:

  • (Boolean)


84
85
86
# File 'lib/theme_javascript_compiler.rb', line 84

def has_content?
  @output_tree.present?
end

#prepend_settings(settings_hash) ⇒ Object



88
89
90
91
92
93
94
95
96
# File 'lib/theme_javascript_compiler.rb', line 88

def prepend_settings(settings_hash)
  @output_tree.prepend ["settings.js", <<~JS]
    (function() {
      if ('require' in window) {
        require("discourse/lib/theme-settings-store").registerSettings(#{@theme_id}, #{settings_hash.to_json});
      }
    })();
  JS
end

#raw_contentObject



80
81
82
# File 'lib/theme_javascript_compiler.rb', line 80

def raw_content
  @output_tree.map { |filename, source| source }.join("")
end

#raw_template_name(name) ⇒ Object



211
212
213
# File 'lib/theme_javascript_compiler.rb', line 211

def raw_template_name(name)
  name.sub(/\.(raw|hbr)\z/, "")
end

#source_mapObject



75
76
77
78
# File 'lib/theme_javascript_compiler.rb', line 75

def source_map
  compile!
  @source_map
end

#terser_configObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/theme_javascript_compiler.rb', line 52

def terser_config
  # Based on https://github.com/ember-cli/ember-cli-terser/blob/28df3d90a5/index.js#L12-L26
  {
    sourceMap: {
      includeSources: true,
      root: "theme-#{@theme_id}/",
    },
    compress: {
      negate_iife: false,
      sequences: 30,
      drop_debugger: false,
    },
    output: {
      semicolons: false,
    },
  }
end