Module: Jekyll::SimpleAssets

Defined in:
lib/jekyll-simple-assets.rb,
lib/jekyll-simple-assets/terser.rb,
lib/jekyll-simple-assets/esbuild.rb,
lib/jekyll-simple-assets/version.rb,
lib/jekyll-simple-assets/critical.rb,
lib/jekyll-simple-assets/content-hash.rb

Defined Under Namespace

Modules: SimpleAssetsFilters, UglifyFilter Classes: AssetTag, BundleRawTag, BundleTag, ContentHashTag, PathTag

Constant Summary collapse

VERSION =
"0.6.0"

Class Method Summary collapse

Class Method Details

.asset_contenthash_mapObject



19
20
21
# File 'lib/jekyll-simple-assets/content-hash.rb', line 19

def self.asset_contenthash_map
	@@asset_contenthash_map ||= {}
end

.asset_placeholder_mapObject



15
16
17
# File 'lib/jekyll-simple-assets/content-hash.rb', line 15

def self.asset_placeholder_map
	@@asset_placeholder_map ||= {}
end

.configObject



21
22
23
# File 'lib/jekyll-simple-assets.rb', line 21

def self.config
	@@config ||= @@site.config['simple_assets']
end

.critical_css_enabled?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/jekyll-simple-assets.rb', line 29

def self.critical_css_enabled?
	config.key?('critical_css')
end

.critical_css_source_filesObject



10
11
12
# File 'lib/jekyll-simple-assets/critical.rb', line 10

def self.critical_css_source_files ()
	@@critical_css_source_files ||= {}
end

.esbuild_bundle_file(page, payload, config_path) ⇒ Object



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
# File 'lib/jekyll-simple-assets/esbuild.rb', line 45

def self.esbuild_bundle_file (page, payload, config_path)
	if page.data['bundle'] == false
		return
	end

	bundle_cmd = "npx esbuild --bundle --tsconfig=#{ config_path }"

	if page.data['esbuild_flags']
		bundle_cmd += ' ' + page.data['esbuild_flags']
	end

	node_env = '--define:process.env.NODE_ENV="' + (ENV['JEKYLL_ENV'] != 'production' ? "'development'" : "'production'") + '"'

	bundle_cmd += ' ' + node_env + " --sourcefile=#{ page.path[/[^\/]*$/] }"

	if SimpleAssets::source_maps_enabled?
		bundle_cmd += ' ' + '--sourcemap=inline'
	end

	dir = File.dirname(page.path)

	Jekyll.logger.info("SimpleAssets:", 'bundling: ' + page.path)
	Jekyll.logger.debug("SimpleAssets:", 'running command: ' + bundle_cmd)

	Open3.popen3(bundle_cmd, :chdir => dir) do |stdin, stdout, stderr, wait_thr|
		stdin.write(page.output)
		stdin.close

		bundled = stdout.read

		if !wait_thr.value.success? || stderr.read != ''
			Jekyll.logger.error("SimpleAssets:", 'esbuild error:')
			stderr.each do |line|
				Jekyll.logger.error("", line)
			end
		elsif stderr.read != ''
			Jekyll.logger.error("SimpleAssets:", 'esbuild error:')
			stderr.each do |line|
				Jekyll.logger.error("", line)
			end
		end

		page.output = bundled
	end
end

.esbuild_config_file(file = nil) ⇒ Object



37
38
39
# File 'lib/jekyll-simple-assets.rb', line 37

def self.esbuild_config_file (file = nil)
	@@esbuild_config_file ||= file
end

.esbuild_enabled?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/jekyll-simple-assets.rb', line 33

def self.esbuild_enabled?
	config.key?('bundle') && config['bundle'] != false
end

.generate_critical_css(site) ⇒ Object



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
# File 'lib/jekyll-simple-assets/critical.rb', line 42

def self.generate_critical_css (site)
	css_files_str = ''

	SimpleAssets::critical_css_source_files.each do |_, f|
		css_files_str += "--css #{ f['file'].path } "

		f['css'] = CssParser::Parser.new
		f['css'].load_string! f['page'].output
	end

	SimpleAssets::config['critical_css']['files'].each do |file|
		css_path = File.join(site.config['destination'], file['output_file'])

		html = file['html']

		critical_cmd = "npx critical #{ css_files_str }"

		Jekyll.logger.debug("SimpleAssets:", "Running command: #{ critical_cmd }")

		Open3.popen3(critical_cmd) do |stdin, stdout, stderr, wait_thr|
			stdin.write(html)
			stdin.close

			if !wait_thr.value.success? || stderr.read != ''
				Jekyll.logger.error("SimpleAssets:", 'Critical (css) error:')
				stderr.each do |line|
					Jekyll.logger.error("", line)
				end
			elsif stderr.read != ''
				Jekyll.logger.error("SimpleAssets:", 'Critical (css) error:')
				stderr.each do |line|
					Jekyll.logger.error("", line)
				end
			end

			critical_css_str = stdout.read

			asset_path = file['output_file'].sub(/^\//, '')

			base64hash = Digest::MD5.base64digest(critical_css_str)

			hash = base64hash[0, SimpleAssets::hash_length].gsub(/[+\/]/, '_')

			SimpleAssets::asset_contenthash_map[asset_path] = hash

			IO.write(css_path, critical_css_str)

			site.keep_files << asset_path

			if file['extract']
				critical_css = CssParser::Parser.new

				critical_css.load_string! critical_css_str

				SimpleAssets::critical_css_source_files.each do |_, f|
					f['css'].each_rule_set do |source_rule_set, source_media_type|
						critical_css.each_rule_set do |critical_rule_set, critical_media_type|
							if critical_rule_set.selectors.join(',') == source_rule_set.selectors.join(',')
								f['css'].remove_rule_set! source_rule_set, source_media_type
								f['extract'] = true

								break
							end
						end
					end
				end
			end
		end
	end

	SimpleAssets::critical_css_source_files.each do |_, f|
		leftover_css = f['css'].to_s if f['extract']

		# css_parser leaves blank keyframes so fix them
		keyframes = f['page'].output.scan(/@keyframes\s+(?:.*?)\s*{(?:\s*\S*?\s*{.*?}\s*)+}/m)
		keyframes.each { |keyframe| leftover_css += keyframe }

		f['page'].output
	end
end

.generate_esbuild_config_fileObject



4
5
6
7
8
9
10
11
12
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
# File 'lib/jekyll-simple-assets/esbuild.rb', line 4

def self.generate_esbuild_config_file ()
	source_path = Jekyll::SimpleAssets::site.config['source']

	tsconfig_path = File.join(source_path, 'jsconfig.json')
	jsconfig_path = File.join(source_path, 'tsconfig.json')

	config = {}

	if File.file?(tsconfig_path)
		config = JSON.parse(File.read(tsconfig_path))
	elsif File.file?(jsconfig_path)
		config = JSON.parse(File.read(jsconfig_path))
	end

	f = Tempfile.new([ 'jsconfig.esbuild.', '.json' ])

	config['compilerOptions'] = {} unless config['compilerOptions']

	base_url = source_path
	if config['compilerOptions']['baseUrl']
		base_url = File.join(source_path, config['compilerOptions']['baseUrl'])
	end
	config['compilerOptions']['baseUrl'] = Pathname.new(base_url).relative_path_from(Pathname.new(f.path))

	config['compilerOptions']['paths'] = {} unless config['compilerOptions']['paths']

	relative_path = Pathname.new(source_path).relative_path_from(Pathname.new(base_url))

	config['compilerOptions']['paths']['@simple-assets/*'] = [
		File.join(relative_path, '_js/*'),
		File.join(relative_path, '_ts/*'),
	]

	f.write config.to_json
	f.close

	Jekyll::SimpleAssets::esbuild_config_file(f)

	Jekyll.logger.debug("SimpleAssets:", "esbuild: using tsconfig #{ f.path }")
end

.get_html_input_for_critical(doc, site) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/jekyll-simple-assets/critical.rb', line 28

def self.get_html_input_for_critical (doc, site)
	return unless doc.respond_to? '[]'

	SimpleAssets::config['critical_css']['files'].each do |file|
		next if file['html']

		page_path = doc.path.sub("#{ site.config['source'] }/", '')

		next unless page_path == file['input_page_path'] || file['layout'] == doc['layout']

		file['html'] = doc.output
	end
end

.get_placeholder(asset_path) ⇒ Object



23
24
25
# File 'lib/jekyll-simple-assets/content-hash.rb', line 23

def self.get_placeholder (asset_path)
	asset_placeholder_map[asset_path] ||= Digest::MD5.base64digest(asset_path)
end

.hash_lengthObject



7
8
9
# File 'lib/jekyll-simple-assets/content-hash.rb', line 7

def self.hash_length
	config['hash_length'] || 16
end

.hashing_enabled?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/jekyll-simple-assets.rb', line 25

def self.hashing_enabled?
	config['hashing_enabled'] || ENV['JEKYLL_ENV'] == 'production'
end

.make_temp_css_files_for_critical(asset) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/jekyll-simple-assets/critical.rb', line 14

def self.make_temp_css_files_for_critical (asset)
	SimpleAssets::config['critical_css']['css_files'].each do |path|
		next unless asset.path == path || asset.path == path.sub(/\.css$/, '.scss')

		f = Tempfile.new([ 'css-source', '.css' ])
		f.write asset.output
		f.close

		Jekyll.logger.debug("SimpleAssets:", "Created new temp file for css: #{ asset.path } at: #{ f.path }")

		SimpleAssets::critical_css_source_files[path] = { 'file' => f, 'page' => asset }
	end
end

.merge_recursively(a, b) ⇒ Object



31
32
33
# File 'lib/jekyll-simple-assets/terser.rb', line 31

def self.merge_recursively(a, b)
	a.merge(b) {|key, a_item, b_item| SimpleAssets::merge_recursively(a_item, b_item) }
end

.minify_file(page) ⇒ Object



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
# File 'lib/jekyll-simple-assets/terser.rb', line 42

def self.minify_file (page)
	return unless SimpleAssets::should_minify_file?(page)

	site_config = symbolize_keys(SimpleAssets::site.config['simple_assets']['terser'])
	page_config = symbolize_keys(page.data['terser'])

	config = SimpleAssets::merge_recursively(site_config || {}, page_config || {})

	map_path = page.path + '.map'
	if SimpleAssets::source_maps_enabled?
		config = SimpleAssets::merge_recursively(config, {
			:source_map => { :filename => page.path[/[^\/]*$/], :url => true },
		})

		minified, source_map = Terser.new(config).compile_with_map(page.output)
	else
		minified = Terser.new(config).compile(page.output)
	end

	min_path = page.path.sub(/\.(j|t)s$/i, '.min.js')
	Jekyll.logger.info("SimpleAssets:", 'minified: ' + min_path)

	if source_map
		File.write(File.join(SimpleAssets::site.config['destination'], map_path), source_map)
		minified = minified.gsub(/^\/\/#\s*?source(Mapping)?URL=.*$/, '')
		minified += "\n//# sourceMappingURL=#{ SimpleAssets::relative_url(map_path) }"

		Jekyll.logger.debug("SimpleAssets:", 'created source map: ' + map_path)

		SimpleAssets::site.config['keep_files'] << map_path
	end

	if SimpleAssets::page_assets_map[page.path]
		SimpleAssets::page_assets_map[min_path] = SimpleAssets::page_assets_map[page.path]
	end

	SimpleAssets::site.config['keep_files'] << min_path

	return min_path, minified
end

.page_assets_mapObject



11
12
13
# File 'lib/jekyll-simple-assets/content-hash.rb', line 11

def self.page_assets_map
	@@page_assets_map ||= {}
end

.relative_url(path) ⇒ Object



27
28
29
# File 'lib/jekyll-simple-assets/content-hash.rb', line 27

def self.relative_url (path)
	"#{ @@site.config['baseurl'] || '' }/#{ path }".gsub(%r{/{2,}}, '/')
end

.replace_placeholders_for_path(page_path, input) ⇒ Object



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
# File 'lib/jekyll-simple-assets/content-hash.rb', line 143

def self.replace_placeholders_for_path (page_path, input)
	output = input

	SimpleAssets::page_assets_map[page_path].each do |asset_path, types|
		types.each do |type, placeholders|
			placeholders.each do |placeholder_hash|
				unless SimpleAssets::asset_contenthash_map[asset_path]
					Jekyll.logger.warn "SimpleAssets:", "No contenthash for: #{ asset_path } not found"

					next
				end

				replacement = SimpleAssets::asset_contenthash_map[asset_path]

				if type == 'path'
					min_path = asset_path.sub(/\.([^\.]*?)$/, '.min.\1')
					url = (File.file? File.join(SimpleAssets::site.config['destination'], min_path)) ? min_path : asset_path

					replacement = "#{ url }?v=#{ replacement }"

					replacement = SimpleAssets::relative_url(replacement)
				end

				placeholder = "#{ type }::#{ SimpleAssets::asset_placeholder_map[asset_path] }"

				output = output.gsub(placeholder, replacement)
			end
		end
	end

	output
end

.resolve_asset_content_hashes(asset, site) ⇒ Object



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
# File 'lib/jekyll-simple-assets/content-hash.rb', line 105

def self.resolve_asset_content_hashes (asset, site)
	asset_path = asset.path.sub("#{ site.config['source'] }/", '')

	if File.extname(asset_path) == '.scss'
		asset_path = Pathname.new(asset_path).sub_ext('.css').to_path()
	elsif File.extname(asset_path) == '.ts'
		asset_path = Pathname.new(asset_path).sub_ext('.js').to_path()
	end

	return unless SimpleAssets::asset_placeholder_map[asset_path]
	return if SimpleAssets::asset_contenthash_map[asset_path]

	content = ""

	# Prefer reading from output if available, because in theory should
	# be faster than from disk, but fall back to reading from disk for
	# static assets.
	if asset.respond_to? :output
		content = asset.output
	elsif File.file? asset_path
		content = File.read asset_path
	elsif File.file? asset.path
		content = File.read asset.path
	else
		Jekyll.logger.warn "SimpleAssets:", "File: #{ asset_path } not found"
	end

	if content.nil?
		Jekyll.logger.warn "SimpleAssets:", "#{ asset_path } has no content"
	end

	base64hash = Digest::MD5.base64digest(content)

	hash = base64hash[0, SimpleAssets::hash_length].gsub(/[+\/]/, '_')

	SimpleAssets::asset_contenthash_map[asset_path] = hash
end

.resolve_critical_css_content_hashes(site) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/jekyll-simple-assets/critical.rb', line 123

def self.resolve_critical_css_content_hashes (site)
	SimpleAssets::critical_css_source_files.each do |_, source_file|
		page = source_file['page']
		page_path = page.path.sub("#{ site.config['source'] }/", '')

		SimpleAssets::config['critical_css']['files'].each do |file|
			css_path  = File.join(site.config['destination'], file['output_file'])
			content = IO.read(css_path)

			critical = SimpleAssets::replace_placeholders_for_path(page_path, content)

			IO.write(css_path, critical)
		end
	end
end

.should_minify_file?(page) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
38
39
40
# File 'lib/jekyll-simple-assets/terser.rb', line 35

def self.should_minify_file? (page)
	return false unless page.respond_to? :output
	return false unless SimpleAssets::terser_enabled?
	return false if page.data['do_not_compress'] == true
	return true
end

.site(site = nil) ⇒ Object



15
16
17
18
19
# File 'lib/jekyll-simple-assets.rb', line 15

def self.site (site = nil)
	@@site = site if site

	@@site
end

.source_maps_enabled?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/jekyll-simple-assets.rb', line 45

def self.source_maps_enabled?
	config['source_maps_enabled']
end

.symbolize_keys(hash) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/jekyll-simple-assets/terser.rb', line 7

def self.symbolize_keys (hash)
	return {} if hash.nil?

	hash.inject({}) do |result, (key, value)|

		new_key = case key
			when String then key.to_sym
			else key
		end
		new_value = case value
			when Hash then symbolize_keys(value)
			else value
		end

		if new_value.is_a?(String) and new_value.match(/^\/.*\/$/)
			new_value = /#{ Regexp.quote(new_value[1..-2]) }/
		end

		result[new_key] = new_value

		result
	end
end

.terser_enabled?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/jekyll-simple-assets.rb', line 41

def self.terser_enabled?
	config['terser_enabled'] || ENV['JEKYLL_ENV'] == 'production'
end