Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ gem "premailer", "~>1.10.3", :git => "git://github.com/cakemail/premailer.git",
gem "sinatra"
gem "json"
gem "hpricot"
gem "nokogiri"
gem "logger"
gem "syslog-logger"
64 changes: 55 additions & 9 deletions main.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,35 @@
eos
end

# Helper method to preserve application/ld+json scripts in the header
def preserve_ld_json_scripts(html, remove_script_tags)
return html unless remove_script_tags

require 'nokogiri'

doc = Nokogiri::HTML(html)

# Find all application/ld+json scripts in the head
ld_json_scripts = []
doc.css('head script[type="application/ld+json"]').each do |script|
ld_json_scripts << script.to_s
end

# Return original HTML if no ld+json scripts found
return html if ld_json_scripts.empty?

# Process with Premailer (which will remove all scripts)
processed_html = yield

# Re-insert the ld+json scripts into the head of the processed HTML
processed_doc = Nokogiri::HTML(processed_html)
ld_json_scripts.each do |script|
processed_doc.at('head').add_child(script)
end

processed_doc.to_html
end

post '/clean' do
error 400 if !params[:html]

Expand All @@ -36,16 +65,33 @@
remove_script_tags = params[:remove_script_tags] == '1' ? true : false
html = params[:html]

premailer = Premailer.new(html,
:warn_level => Premailer::Warnings::SAFE,
:with_html_string => true,
:preserve_styles => true,
:remove_comments => remove_comments,
:remove_script_tags => remove_script_tags
)
# Process HTML with special handling for application/ld+json scripts
processed_html = preserve_ld_json_scripts(html, remove_script_tags) do
premailer = Premailer.new(html,
:warn_level => Premailer::Warnings::SAFE,
:with_html_string => true,
:preserve_styles => true,
:remove_comments => remove_comments,
:remove_script_tags => remove_script_tags
)

premailer.to_inline_css
end

content_type :json
data = {:html => premailer.to_inline_css}
data[:warnings] = premailer.warnings if with_warnings
data = {:html => processed_html}

# Get warnings if needed
if with_warnings
premailer = Premailer.new(html,
:warn_level => Premailer::Warnings::SAFE,
:with_html_string => true,
:preserve_styles => true,
:remove_comments => remove_comments,
:remove_script_tags => remove_script_tags
)
data[:warnings] = premailer.warnings
end

data.to_json
end