kiln 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,71 +2,37 @@ module Kiln
2
2
  class Configuration
3
3
  # Output directory, relative to Rails.root unless absolute.
4
4
  attr_accessor :output
5
- # Public base URL ("https://davafons.com"). Used by the sitemap and absolute_urls processor.
5
+ # Public base URL ("https://davafons.com"). Sets the request host and enables sitemap.xml.
6
6
  attr_accessor :url
7
7
  # :directory ("/now" -> now/index.html) or :file ("/now" -> now.html).
8
8
  attr_accessor :paths
9
- # :referenced (only assets the output uses) or :all (everything under /assets).
10
- attr_accessor :assets
11
- # Writes a CNAME file with this domain when set.
9
+ # Writes a CNAME file with this domain when set. true takes the host from `url`.
12
10
  attr_accessor :cname
13
- # Removes `sourceMappingURL` comments from JS and CSS.
14
- attr_accessor :strip_source_maps
15
- # Extra HTML processors: objects responding to call(html, context) -> html.
16
- attr_accessor :processors
17
- # Built-in optional processors, off by default.
18
- attr_accessor :absolute_urls, :external_links
19
11
  # Path rendered to 404.html (expected to respond with 404 or 200), nil to skip.
20
12
  attr_accessor :not_found
21
- # :file (_redirects), :meta_refresh (HTML pages), :both, or false.
22
- attr_accessor :redirects
23
- # Writes sitemap.xml when true and `url` is set.
24
- attr_accessor :sitemap
25
- # Runs the verifier (links, anchors, importmap) after every build.
26
- attr_accessor :verify
27
13
  # CSS selectors for sample markup whose links the verifier ignores (for example component demos).
28
14
  attr_accessor :verify_skip
29
- # Copy public/ into the output (minus public/assets).
30
- attr_accessor :copy_public
31
15
  # Extra files that aren't routes: { "octicons-license.txt" => "vendor/octicons/LICENSE" }.
32
16
  # Sources are relative to Rails.root.
33
17
  attr_accessor :files
34
18
 
35
- attr_reader :before_build_hooks, :after_build_hooks
36
- attr_writer :host
37
-
38
19
  def initialize
39
20
  @output = "dist"
40
21
  @url = nil
41
- @host = nil
42
22
  @paths = :directory
43
- @assets = :referenced
44
23
  @cname = nil
45
- @strip_source_maps = true
46
- @processors = []
47
- @absolute_urls = false
48
- @external_links = false
49
24
  @not_found = nil
50
- @redirects = :file
51
- @sitemap = true
52
- @verify = true
53
25
  @verify_skip = []
54
- @copy_public = true
55
26
  @files = {}
56
- @before_build_hooks = []
57
- @after_build_hooks = []
58
27
  end
59
28
 
60
- # Host sent with every request. Derived from `url`, falls back to "localhost".
29
+ # Host sent with every request: the host of `url`, or "localhost".
61
30
  def host
62
- @host || (url && URI(url).host) || "localhost"
31
+ (url && URI(url).host) || "localhost"
63
32
  end
64
33
 
65
34
  def output_path(root = Rails.root)
66
35
  Pathname(output).absolute? ? Pathname(output) : Pathname(root).join(output)
67
36
  end
68
-
69
- def before_build(&block) = @before_build_hooks << block
70
- def after_build(&block) = @after_build_hooks << block
71
37
  end
72
38
  end
@@ -8,8 +8,9 @@ module Kiln
8
8
  def initialize(name, dir)
9
9
  @name, @dir = name.to_s, Pathname(dir)
10
10
  @stamp = stamp
11
- @entries = files.map { Entry.new(@name, it) }
12
- .sort_by { [ it.published_at&.in_time_zone || Time.at(0), it.slug ] }.reverse
11
+ translations, entries = files.map { Entry.new(@name, it) }.partition(&:locale)
12
+ @entries = entries.sort_by { [ it.published_at&.in_time_zone || Time.at(0), it.slug ] }.reverse
13
+ translations.each { attach(it) }
13
14
  end
14
15
 
15
16
  # Visible entries, newest first.
@@ -19,11 +20,7 @@ module Kiln
19
20
 
20
21
  def each(&) = all.each(&)
21
22
 
22
- def find(slug, preview_token: nil)
23
- entry = @entries.find { it.slug == slug.to_s }
24
- return entry if entry && (Content.show_drafts || entry.published? || preview?(entry, preview_token))
25
- raise NotFound, "no #{name} entry with slug #{slug.inspect}"
26
- end
23
+ def find(slug) = find_by(slug:) || raise(NotFound, "no #{name} entry with slug #{slug.inspect}")
27
24
 
28
25
  def find_by(slug:) = all.find { it.slug == slug.to_s }
29
26
 
@@ -33,11 +30,14 @@ module Kiln
33
30
  private
34
31
  def files = Dir[@dir.join("*.md")].sort
35
32
 
36
- def stamp = files.map { [ it, File.mtime(it) ] }
33
+ def attach(translation)
34
+ entry = @entries.find { it.slug == translation.slug }
35
+ raise ArgumentError, "#{translation.path} is a translation, but no entry has the slug #{translation.slug.inspect}" unless entry
37
36
 
38
- def preview?(entry, token)
39
- token.present? && ActiveSupport::SecurityUtils.secure_compare(entry.preview_token, token.to_s)
37
+ entry.add_translation(translation)
40
38
  end
39
+
40
+ def stamp = files.map { [ it, File.mtime(it) ] }
41
41
  end
42
42
  end
43
43
  end
@@ -1,20 +1,36 @@
1
1
  module Kiln
2
2
  module Content
3
3
  class Entry
4
- FILENAME = /\A(?:(?<date>\d{4}-\d{2}-\d{2})-)?(?<slug>.+?)\.md\z/
4
+ # SLUG.md, or SLUG.LOCALE.md for a translation. A locale is two lowercase letters, optionally
5
+ # followed by a dash and two uppercase letters: es, ja, pt-BR.
6
+ FILENAME = /\A(?<name>.+?)(?:\.(?<locale>[a-z]{2}(?:-[A-Z]{2})?))?\.md\z/
7
+ # A leading YYYY-MM-DD or YYYY-MM date. The slug is the rest of the name, or the whole name when
8
+ # it is only a date. A month-only date means the 1st of that month.
9
+ DATED = /\A(?<date>\d{4}-\d{2}(?:-\d{2})?)(?:-(?<slug>.+))?\z/
5
10
 
6
- attr_reader :collection, :path, :slug, :attributes, :body, :published_at
11
+ attr_reader :collection, :path, :slug, :locale, :attributes, :body, :published_at
7
12
 
8
13
  def initialize(collection, path)
9
- @collection, @path = collection.to_s, Pathname(path)
10
- match = FILENAME.match(@path.basename.to_s)
11
- @slug = match[:slug]
14
+ @collection, @path = collection&.to_s, Pathname(path)
15
+ match = FILENAME.match(@path.basename.to_s) or raise ArgumentError, "#{@path} is not a Markdown file: its name must end in .md"
16
+ @locale = match[:locale]
17
+ dated = DATED.match(match[:name])
18
+ @slug = (dated && dated[:slug]) || match[:name]
12
19
  text = @path.read
13
20
  @attributes, @body = Frontmatter.parse(text)
14
21
  @frontmatter_lines = text.delete_suffix(body).count("\n")
15
- @published_at = attributes["published_at"] || (Date.iso8601(match[:date]) if match[:date])
22
+ @published_at = attributes["published_at"] || (filename_date(dated[:date]) if dated)
23
+ @translations = {}
16
24
  end
17
25
 
26
+ # The visible translation from SLUG.LOCALE.md, or nil.
27
+ def translation(locale)
28
+ entry = @translations[locale.to_s]
29
+ entry if entry && (Content.show_drafts || entry.published?)
30
+ end
31
+
32
+ def add_translation(entry) = @translations[entry.locale] = entry
33
+
18
34
  def title = attributes["title"] || slug.titleize
19
35
  def draft? = attributes["draft"] == true
20
36
  def scheduled? = published_at.present? && published_at.in_time_zone.future?
@@ -29,15 +45,18 @@ module Kiln
29
45
  def [](key) = attributes[key.to_s]
30
46
  def to_h = attributes
31
47
 
32
- def preview_token
33
- OpenSSL::HMAC.hexdigest("SHA256", Content.preview_secret, "#{collection}/#{slug}")
34
- end
35
-
36
48
  def respond_to_missing?(name, include_private = false) = attributes.key?(name.to_s) || super
37
49
 
38
50
  def method_missing(name, *args)
39
51
  attributes.key?(name.to_s) && args.empty? ? attributes[name.to_s] : super
40
52
  end
53
+
54
+ private
55
+ def filename_date(date)
56
+ Date.iso8601(date.length == 7 ? "#{date}-01" : date)
57
+ rescue Date::Error
58
+ raise ArgumentError, "#{path} starts with an invalid date: #{date}"
59
+ end
41
60
  end
42
61
  end
43
62
  end
@@ -20,20 +20,34 @@ module Kiln
20
20
  path ? SourcePosition.rewrite(html, path, line_offset) : html
21
21
  end
22
22
 
23
+ # Renders text that is a single paragraph without the wrapping <p>, for titles and captions.
24
+ # Text with any other block structure renders as with render.
25
+ def self.render_inline(text)
26
+ html = render(text)
27
+ block = Commonmarker.parse(text.to_s, options: OPTIONS).first_child
28
+ return html unless block&.type == :paragraph && block.next_sibling.nil?
29
+
30
+ html.delete_prefix("<p>").delete_suffix("</p>\n")
31
+ end
32
+
23
33
  # Swaps a code block for raw HTML highlighted by Rouge, with CSS classes and no inline styles.
34
+ # data-language keeps the fence's language as written, also when Rouge has no lexer for it.
24
35
  def self.highlight(node, sourcepos:)
25
36
  code = node.string_content
26
- lexer = Rouge::Lexer.find_fancy(node.fence_info.split.first.to_s, code) || Rouge::Lexers::PlainText.new
27
- position = node.source_position.values_at(:start_line, :start_column, :end_line, :end_column)
28
- attribute = %( data-sourcepos="%d:%d-%d:%d") % position if sourcepos
29
- html = %(<pre class="highlight #{lexer.tag}"#{attribute}><code>#{Rouge::Formatters::HTML.new.format(lexer.lex(code))}</code></pre>\n)
37
+ language = node.fence_info.split.first.to_s
38
+ lexer = Rouge::Lexer.find_fancy(language, code) || Rouge::Lexers::PlainText.new
39
+ attributes = +""
40
+ attributes << %( data-language="#{ERB::Util.html_escape(language)}") unless language.empty?
41
+ attributes << %( data-sourcepos="%d:%d-%d:%d") % node.source_position.values_at(:start_line, :start_column, :end_line, :end_column) if sourcepos
42
+ html = %(<pre class="highlight #{lexer.tag}"#{attributes}><code>#{Rouge::Formatters::HTML.new.format(lexer.lex(code))}</code></pre>\n)
30
43
  node.replace(Commonmarker::Node.new(:html_block, literal: html))
31
44
  end
32
45
  end
33
46
 
34
- # Editor markup for Tensaku: data-tensaku-md="path:startLine:startCol-endLine:endCol", with the
35
- # path relative to Rails.root. Only block elements carry it; commonmarker's positions on inline
36
- # elements are dropped. The format is a draft, and this is the one place that writes it.
47
+ # Editor markup: data-md-source="path:startLine:startCol-endLine:endCol", with the path relative
48
+ # to Rails.root, 1-based lines and commonmarker byte columns with an inclusive end. Only the
49
+ # elements in BLOCKS carry it; commonmarker's positions on inline elements are dropped. This is
50
+ # the one place that writes it.
37
51
  module SourcePosition
38
52
  BLOCKS = %w[p h1 h2 h3 h4 h5 h6 ul ol li blockquote pre table hr].to_set.freeze
39
53
  ATTRIBUTE = /<(\w+)([^>]*?) data-sourcepos="(\d+):(\d+)-(\d+):(\d+)"/
@@ -44,7 +58,7 @@ module Kiln
44
58
  tag, rest = $1, $2
45
59
  next "<#{tag}#{rest}" unless BLOCKS.include?(tag)
46
60
 
47
- %(<#{tag}#{rest} data-tensaku-md="#{relative}:#{$3.to_i + line_offset}:#{$4}-#{$5.to_i + line_offset}:#{$6}")
61
+ %(<#{tag}#{rest} data-md-source="#{relative}:#{$3.to_i + line_offset}:#{$4}-#{$5.to_i + line_offset}:#{$6}")
48
62
  end
49
63
  end
50
64
  end
data/lib/kiln/content.rb CHANGED
@@ -1,47 +1,8 @@
1
- # Kiln content layer: Markdown views and Markdown collections with YAML frontmatter.
2
- # Optional and independent of the exporter, so server-rendered Rails apps can use it too.
3
- #
4
- # # Gemfile
5
- # gem "commonmarker"
6
- # gem "rouge"
7
- #
8
- # # config/initializers/kiln.rb
9
- # require "kiln/content"
10
- #
11
- # Markdown views. app/views/pages/about.html.md renders through the layout like any view.
12
- # about.html.md.erb runs ERB first, then Markdown. commonmarker renders GitHub Flavored Markdown
13
- # (tables, strikethrough, autolinks, heading ids). Code blocks are highlighted by Rouge with CSS
14
- # classes, so add a Rouge theme to your stylesheet (`rougify style github`).
15
- #
16
- # Collections. content/blog/2024-05-01-hello.md:
17
- #
18
- # ---
19
- # title: Hello
20
- # tags: [rails]
21
- # ---
22
- # # Hello
23
- #
24
- # posts = Kiln::Content.collection("blog")
25
- # posts.all # visible entries, newest first
26
- # posts.find("hello") # raises Kiln::Content::NotFound (a 404 in Rails)
27
- # posts.find_by(slug: "hello") # or nil
28
- # post.slug, post.title, post.published_at, post.draft?, post.body, post.html, post[:tags], post.tags
29
- #
30
- # # config/kiln.rb
31
- # params :post, -> { Kiln::Content.collection("blog").map { { slug: it.slug } } }
32
- #
33
- # Publishing. Entries with `draft: true` or a future `published_at` (frontmatter or filename date)
34
- # are hidden. They show in development unless Kiln is building; set Kiln::Content.show_drafts to
35
- # override. A server-rendered app can share a hidden entry with
36
- # `posts.find(params[:slug], preview_token: params[:token])`, where the token is `post.preview_token`.
37
- #
38
- # Source positions. With Kiln::Content.source_positions on, each rendered block of a .md view or
39
- # collection entry carries data-tensaku-md="path:startLine:startCol-endLine:endCol" for the Tensaku
40
- # editor. .md.erb views get none. It defaults to on in development when Tensaku is loaded, and is
41
- # always off while Kiln is building.
42
- #
43
- # Settings: Kiln::Content.root (default Rails.root/content), Kiln::Content.show_drafts,
44
- # Kiln::Content.preview_secret (default secret_key_base), Kiln::Content.source_positions.
1
+ # Kiln content layer: Markdown views (.html.md, .html.md.erb), collections of Markdown files with
2
+ # YAML frontmatter, and single Markdown files. Optional and independent of the exporter, so
3
+ # server-rendered Rails apps can use it too. Load it with `require "kiln/content"` after adding the
4
+ # commonmarker and rouge gems. The content page of the docs (docs/app/views/pages/content.html.md)
5
+ # describes every feature; comments here cover only what the code does not show.
45
6
  begin
46
7
  require "commonmarker"
47
8
  require "rouge"
@@ -63,7 +24,7 @@ module Kiln
63
24
  class NotFound < Kiln::Error; end
64
25
 
65
26
  class << self
66
- attr_writer :root, :show_drafts, :preview_secret, :source_positions
27
+ attr_writer :root, :show_drafts, :source_positions
67
28
 
68
29
  def root
69
30
  Pathname(@root || Rails.root.join("content"))
@@ -76,12 +37,7 @@ module Kiln
76
37
 
77
38
  def source_positions
78
39
  return false if Kiln.building?
79
- return @source_positions unless @source_positions.nil?
80
- Rails.env.development? && !defined?(::Tensaku).nil?
81
- end
82
-
83
- def preview_secret
84
- @preview_secret || Rails.application.secret_key_base
40
+ @source_positions == true
85
41
  end
86
42
 
87
43
  def collection(name)
@@ -94,15 +50,33 @@ module Kiln
94
50
  end
95
51
  end
96
52
 
53
+ # One Markdown file anywhere, such as a README or CONTRIBUTING.md, as an entry with
54
+ # frontmatter, html and source positions. Read again when the file changes, once per build.
55
+ def file(path)
56
+ path = Pathname(path).expand_path
57
+ if Kiln.building?
58
+ Kiln.build_cache.fetch("kiln/content/file/#{path}") { Entry.new(nil, path) }
59
+ else
60
+ mtime = path.mtime
61
+ cached = files[path]
62
+ cached && cached[0] == mtime ? cached[1] : (files[path] = [ mtime, Entry.new(nil, path) ])[1]
63
+ end
64
+ end
65
+
97
66
  def reset!
98
- @root = @show_drafts = @preview_secret = @source_positions = nil
67
+ @root = @show_drafts = @source_positions = nil
99
68
  @collections = {}
69
+ @files = {}
100
70
  end
101
71
 
102
72
  private
103
73
  def collections
104
74
  @collections ||= {}
105
75
  end
76
+
77
+ def files
78
+ @files ||= {}
79
+ end
106
80
  end
107
81
  end
108
82
  end
data/lib/kiln/pages.rb CHANGED
@@ -9,27 +9,33 @@ module Kiln
9
9
  end
10
10
 
11
11
  # params :post, -> { Post.all.map { { slug: it.slug } } }
12
- def params(route_name, source)
13
- raise ArgumentError, "params :#{route_name} needs a callable source" unless source.respond_to?(:call)
14
- @sources[route_name.to_sym] = source
12
+ # params :health, locale: [ nil, "es", "ja" ]
13
+ # params :archive, -> { Archive.all.map { { year: it.year } } }, locale: [ nil, "es" ]
14
+ #
15
+ # Value lists build every combination of their values. A nil value leaves the key out, for
16
+ # optional segments such as "(:locale)". A list may be a lambda, called at build time. With both a
17
+ # source and value lists, every hash from the source is combined with every combination.
18
+ def params(route_name, source = nil, **values)
19
+ raise ArgumentError, "params :#{route_name} needs a callable source" unless source.nil? || source.respond_to?(:call)
20
+ raise ArgumentError, "params :#{route_name} needs a source or value lists" if source.nil? && values.empty?
21
+
22
+ @sources[route_name.to_sym] =
23
+ if values.empty? then source
24
+ elsif source.nil? then -> { combinations(values) }
25
+ else -> { source.call.to_a.product(combinations(values)).map { |params, extra| params.merge(extra) } }
26
+ end
15
27
  end
16
28
 
17
29
  def skip(route_name, reason: nil)
18
30
  @skips[route_name.to_sym] = reason
19
31
  end
20
32
 
21
- # paginate :posts_page, per: 10, total: -> { Post.count }
22
- # Builds pages start..last, where last is ceil(total / per). The start page is always built, so an
23
- # empty list still gets its first page. Use start: 2 when page 1 lives at another route.
24
- def paginate(route_name, per:, total:, param: :page, start: 1)
25
- raise ArgumentError, "paginate :#{route_name} needs a positive per:" unless per.is_a?(Integer) && per.positive?
33
+ def declared_names = (sources.keys + skips.keys).uniq
26
34
 
27
- params route_name, -> do
28
- last = Integer(total.call).fdiv(per).ceil
29
- (start..[ start, last ].max).map { { param => it } }
35
+ private
36
+ def combinations(values)
37
+ lists = values.map { |key, list| (list.respond_to?(:call) ? list.call : list).to_a.map { { key => it } } }
38
+ lists.first.product(*lists.drop(1)).map { it.reduce(:merge).compact }
30
39
  end
31
- end
32
-
33
- def declared_names = (sources.keys + skips.keys).uniq
34
40
  end
35
41
  end
@@ -7,7 +7,7 @@ module Kiln
7
7
  # The newline csrf_meta_tags puts between its two tags goes with the first one.
8
8
  META_TAG = /<meta\b(?=[^>]*\sname="csrf-(?:param|token)")[^>]*>(?:\n(?=<meta\b[^>]*\sname="csrf-))?/
9
9
 
10
- def self.call(html, _context = nil)
10
+ def self.call(html)
11
11
  html.gsub(TOKEN_INPUT, "").gsub(META_TAG, "")
12
12
  end
13
13
  end
data/lib/kiln/railtie.rb CHANGED
@@ -15,6 +15,15 @@ module Kiln
15
15
  hosts << Kiln.config.host if hosts.any? && !hosts.include?(Kiln.config.host)
16
16
  end
17
17
 
18
+ # In :directory mode "/now" is written as now/index.html, which static hosts serve at "/now/" and
19
+ # reach from "/now" with a redirect. Route helpers add the trailing slash so links point at the
20
+ # served URL. Paths with a dot (feed.xml) are left alone, and an app that sets trailing_slash in
21
+ # default_url_options keeps its own value.
22
+ config.after_initialize do |app|
23
+ options = app.routes.default_url_options
24
+ options[:trailing_slash] = true if Kiln.config.paths == :directory && !options.key?(:trailing_slash)
25
+ end
26
+
18
27
  rake_tasks do
19
28
  Dir[File.expand_path("../tasks/kiln/*.rake", __dir__)].sort.each { load it }
20
29
  end
@@ -1,8 +1,5 @@
1
- require "erb"
2
-
3
1
  module Kiln
4
- # Writes redirect responses as a _redirects file (Cloudflare Pages, Netlify) and/or meta refresh pages
5
- # (GitHub Pages).
2
+ # Writes redirect responses as a _redirects file (Cloudflare Pages, Netlify).
6
3
  class Redirects
7
4
  Entry = Data.define(:from, :to, :status)
8
5
 
@@ -20,52 +17,19 @@ module Kiln
20
17
  end
21
18
  end
22
19
 
23
- def initialize(entries, mode:, writer:, host:, url: nil)
20
+ def initialize(entries, host:)
24
21
  @entries = entries.map { it.with(to: relativize(it.to, host)) }
25
- @mode = mode
26
- @writer = writer
27
- @url = url
28
22
  end
29
23
 
24
+ # Rules from a copied public/_redirects come first, so hand-written rules win. Returns the filename.
30
25
  def write(output)
31
- files = []
32
- files << write_file(output) if %i[file both].include?(@mode)
33
- files.concat(write_pages) if %i[meta_refresh both].include?(@mode)
34
- files
26
+ file = Pathname(output).join(FILENAME)
27
+ existing = file.exist? ? file.read.chomp.then { it.empty? ? "" : "#{it}\n" } : ""
28
+ File.write(file, existing + @entries.map { "#{it.from} #{it.to} #{it.status}\n" }.join)
29
+ FILENAME
35
30
  end
36
31
 
37
32
  private
38
- # Rules from a copied public/_redirects come first, so hand-written rules win.
39
- def write_file(output)
40
- file = Pathname(output).join(FILENAME)
41
- existing = file.exist? ? file.read.chomp.then { it.empty? ? "" : "#{it}\n" } : ""
42
- File.write(file, existing + @entries.map { "#{it.from} #{it.to} #{it.status}\n" }.join)
43
- FILENAME
44
- end
45
-
46
- def write_pages
47
- @entries.map do |entry|
48
- @writer.write_file(@writer.file_for(entry.from, "text/html"), page(entry.to))
49
- end
50
- end
51
-
52
- def page(to)
53
- canonical = ERB::Util.html_escape(@url && to.start_with?("/") ? "#{@url.chomp("/")}#{to}" : to)
54
- to = ERB::Util.html_escape(to)
55
- <<~HTML
56
- <!DOCTYPE html>
57
- <html>
58
- <head>
59
- <meta charset="utf-8">
60
- <title>Redirecting</title>
61
- <meta http-equiv="refresh" content="0; url=#{to}">
62
- <link rel="canonical" href="#{canonical}">
63
- </head>
64
- <body><a href="#{to}">#{to}</a></body>
65
- </html>
66
- HTML
67
- end
68
-
69
33
  def relativize(location, host)
70
34
  uri = URI.parse(location)
71
35
  return location unless uri.is_a?(URI::HTTP) && uri.host&.casecmp?(host)
data/lib/kiln/report.rb CHANGED
@@ -3,7 +3,7 @@ module Kiln
3
3
  class Report
4
4
  Entry = Data.define(:kind, :message, :path)
5
5
 
6
- KINDS = %i[uncovered_route render editor_markup asset broken_link missing_anchor importmap redirect write hook other].freeze
6
+ KINDS = %i[uncovered_route render editor_markup asset broken_link missing_anchor importmap redirect write other].freeze
7
7
 
8
8
  attr_reader :errors, :warnings, :written
9
9
 
data/lib/kiln/sitemap.rb CHANGED
@@ -24,7 +24,7 @@ module Kiln
24
24
  urls = @manifest.entries.filter_map do |path, entry|
25
25
  next if entry[:noindex] || entry[:content_type] != "text/html"
26
26
 
27
- " <url><loc>#{ERB::Util.html_escape(@url + path)}</loc></url>\n"
27
+ " <url><loc>#{ERB::Util.html_escape(@url + served_path(path, entry[:file]))}</loc></url>\n"
28
28
  end
29
29
 
30
30
  File.write(Pathname(output).join(FILENAME), <<~XML)
@@ -34,5 +34,10 @@ module Kiln
34
34
  XML
35
35
  FILENAME
36
36
  end
37
+
38
+ private
39
+ def served_path(path, file)
40
+ File.basename(file.to_s) == "index.html" ? "/#{file.to_s.delete_suffix("index.html")}" : path
41
+ end
37
42
  end
38
43
  end
@@ -10,43 +10,39 @@ module Kiln
10
10
  # class StaticSiteTest < ActiveSupport::TestCase
11
11
  # include Kiln::TestHelper
12
12
  #
13
- # test("builds the same output twice") { assert_repeatable_build }
13
+ # test("builds repeatably") { kiln_build(repeatable: true) { assert it.join("index.html").file? } }
14
14
  # test("home page") { assert_page "/", selector: "h1", text: "Home" }
15
15
  # end
16
16
  module TestHelper
17
17
  # Builds into a temp dir, fails with the report on any error, and yields the output path.
18
18
  # Returns the Build when no block is given (the temp dir is then left for the caller).
19
- def kiln_build(app: Rails.application, config: Kiln.config)
20
- dir = Dir.mktmpdir("kiln-build")
19
+ # With repeatable: true it builds a second time and fails with the diff when the two outputs
20
+ # differ, then yields the first output.
21
+ def kiln_build(app: Rails.application, config: Kiln.config, repeatable: false)
22
+ dir = Pathname(Dir.mktmpdir("kiln-build"))
21
23
  build = Build.new(app:, config:, output: dir)
22
24
  assert build.run.success?, build.report.to_s
23
- return build unless block_given?
24
-
25
- begin
26
- yield Pathname(dir)
27
- ensure
28
- FileUtils.rm_rf(dir)
29
- end
30
- end
31
-
32
- # Builds twice and asserts both outputs are byte-identical.
33
- def assert_repeatable_build(app: Rails.application, config: Kiln.config)
34
- kiln_build(app:, config:) do |first|
25
+ if repeatable
35
26
  kiln_build(app:, config:) do |second|
36
- diff = TreeDiff.call(first, second)
27
+ diff = TreeDiff.call(dir, second)
37
28
  assert diff.empty?, "Kiln output differs between two builds:\n#{diff}"
38
29
  end
39
30
  end
31
+ return build unless block_given?
32
+
33
+ yield dir
34
+ ensure
35
+ FileUtils.rm_rf(dir) if dir && block_given?
40
36
  end
41
37
 
42
- # Renders one path the way a build does (processors included) and asserts it succeeds.
38
+ # Renders one path the way a build does (CSRF tokens stripped) and asserts it succeeds.
43
39
  # Optional `selector` must match, and contain `text` when given. Returns the processed body.
44
40
  def assert_page(path, status: 200, selector: nil, text: nil, app: Rails.application, config: Kiln.config)
45
41
  response = Kiln.building! { Renderer.new(app, host: config.host).get(path) }
46
42
  assert_equal status, response.status, "Expected #{path} to respond with #{status}"
47
43
 
48
44
  body = response.body
49
- body = Processors.apply(body, Processors::Context.new(path:, config:, response:)) if response.html?
45
+ body = Processors::StripCSRF.call(body) if response.html?
50
46
 
51
47
  if selector
52
48
  nodes = Nokogiri::HTML5(body).css(selector)
data/lib/kiln/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Kiln
2
- VERSION = "0.1.1"
2
+ VERSION = "0.1.3"
3
3
  end
data/lib/kiln.rb CHANGED
@@ -35,16 +35,50 @@ module Kiln
35
35
  @building == true
36
36
  end
37
37
 
38
- def building!
39
- previous = @building
38
+ def building!(renderer: nil)
39
+ previous = [ @building, @renderer ]
40
40
  @building = true
41
+ @renderer = renderer
41
42
  build_cache.clear
42
43
  yield
43
44
  ensure
44
- @building = previous
45
+ @building, @renderer = previous
45
46
  build_cache.clear
46
47
  end
47
48
 
49
+ # Another page's body as a build writes it (CSRF tokens stripped), for pages built from other
50
+ # pages, such as a search index. Raises Kiln::Error unless the page responds with 2xx.
51
+ #
52
+ # pages = Docs::PAGES.map { { url: page_path(it), html: Kiln.render(page_path(it)) } }
53
+ #
54
+ # During a build the response is shared: the build writes the same response, so every page is
55
+ # rendered once whichever asks for it first. Outside a build it renders on every call.
56
+ def render(path)
57
+ response = response_for(path)
58
+ raise Error, "Kiln.render(#{path.inspect}) got a #{response.status} response" unless response.success?
59
+
60
+ response.html? ? Processors::StripCSRF.call(response.body) : response.body
61
+ end
62
+
63
+ # The app's response for a path, cached for the build so the build and Kiln.render share it.
64
+ # "/now" and "/now/" are the same page. A page that renders itself, directly or through other
65
+ # pages, raises Kiln::Error.
66
+ def response_for(path)
67
+ path = path.to_s
68
+ path = path.chomp("/") unless path == "/"
69
+ build_cache.fetch([ :kiln_response, path ]) do
70
+ rendering = Thread.current[:kiln_rendering] ||= []
71
+ raise Error, "Kiln.render loops: #{[ *rendering, path ].join(" -> ")}" if rendering.include?(path)
72
+
73
+ rendering.push(path)
74
+ begin
75
+ (@renderer || Renderer.new(Rails.application, host: config.host)).get(path)
76
+ ensure
77
+ rendering.pop
78
+ end
79
+ end
80
+ end
81
+
48
82
  # Memoization store that lives for one build. Cleared before and after every build.
49
83
  def build_cache
50
84
  @build_cache ||= BuildCache.new
@@ -55,6 +89,7 @@ module Kiln
55
89
  @pages = nil
56
90
  @building = nil
57
91
  @build_cache = nil
92
+ @renderer = nil
58
93
  end
59
94
  end
60
95
  end