13
14
15
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
|
# File 'lib/svelte/handler.rb', line 13
def call(template, source)
digest = Digest::SHA256.base64digest(source)
<<-RUBY
Dir.mktmpdir("svelte", Rails.root.join('tmp')) do |dir|
template = OpenStruct.new(JSON.parse('#{template.to_json}').deep_symbolize_keys)
Svelte.props.merge!(
instance_values.reject { |k,v|
k.start_with?("_") || Svelte::DISCARD_PROPS.include?(k)
}
) { |key,old,new| old }
Svelte.props.deep_symbolize_keys!
if local_assigns.dig(:svelte) == nil
local_assigns[:svelte] = {}
end
assembler = nil
assembler = Tempfile.new(['assembler', ".mjs"], dir)
assembler.write(ERB.new(File.read('#{Svelte.gem_dir}/lib/svelte/templates/assembler.js.erb')).result_with_hash({
path: '#{Rails.root.join template.identifier}',
digest: '#{digest}',
locals: local_assigns,
compiled_client: j(Rails.cache.read('svelte/template/client' + '#{digest}')),
compiled_server: j(Rails.cache.read('svelte/template/server' + '#{digest}')),
ssr: Svelte.precedence(local_assigns.dig(:svelte, :ssr), template.variant.nil? ? nil : (template.variant == "server"), Svelte.ssr)
}))
assembler.rewind
result = JSON.parse(`NODE_PATH=#{Rails.root.join("node_modules")} NODE_NO_WARNINGS=1 node --experimental-vm-modules \#{assembler.path}`).deep_symbolize_keys
if result[:error]
e = Svelte::Errors::CompilerError.new(result.dig(:error))
raise Svelte::Errors::TemplateError.new(template, e)
end
assembler&.close
assembler&.unlink
Rails.cache.write("svelte/template/client/" + '#{digest}', result[:compiled][:client], expires_in: 14.days)
Rails.cache.write("svelte/template/server/" + '#{digest}', result[:compiled][:server], expires_in: 14.days)
content_for(:head, (result.dig(:server, :head) || "").html_safe)
ERB.new(File.read("#{Svelte.gem_dir}/lib/svelte/templates/island.html.erb")).result_with_hash({ result:, locals: local_assigns, digest: "#{digest}", bind: binding }).html_safe
end
RUBY
end
|