// Build pipeline: config -> templates -> data -> scan -> collections -> render
// -> assets -> plugins -> cache.
//
// The pipeline knows nothing about individual formats or engines: data is parsed
// by a `FormatRegistry`, page bodies by a `ContentRegistry` and templates by a
// `TemplateEnv`. Adding one of those does not touch this file.

///|
/// Run the full build pipeline with the built-in formats and engines.
pub async fn build_site(options : BuildOptions) -> BuildResult {
  build_site_with(
    options,
    @formats.FormatRegistry::builtin(),
    @content.ContentRegistry::builtin(),
    None,
  )
}

///|
/// Run the build pipeline with explicit extension points.
///
/// `formats` parses configuration, `_data` files and front matter, `contents`
/// turns a templated body into HTML, and `engine_env` supplies the template
/// engines (created from the configuration when omitted). Pass prepared
/// registries to build a site that uses a custom data format, page format or
/// template engine.
pub async fn build_site_with(
  options : BuildOptions,
  formats : @formats.FormatRegistry,
  contents : @content.ContentRegistry,
  engine_env : @engine.TemplateEnv?,
) -> BuildResult {
  let started = @env.now()
  let cfg = @config.load_config_with(
    options.root,
    options.config,
    options.dest,
    options.force,
    formats,
    contents,
  )
  debug_step("config loaded")
  let config_path = @config.resolve_config_path(options.root, options.config)
  let source_root = cfg.source_path()
  let output_root = cfg.output_path()
  let theme = resolve_theme(cfg)
  let theme_root = theme_path(theme)
  let themed = match theme {
    NoTheme => false
    _ => true
  }
  @core.ensure_dir(output_root) |> ignore
  let prefixes = content_prefixes(cfg)
  let env = match engine_env {
    Some(ready) => ready
    None => @engine.TemplateEnv::with_engine(cfg.engine)
  }
  // Everything shared by all pages is hashed together: a change to a layout,
  // include or data file invalidates every page at once.
  let global_sources = StringBuilder(capacity=512)
  global_sources.write_string(config_path)
  // `raw` is the merged result of the site config and any theme defaults, so
  // editing theme.yaml invalidates the cache just like editing fus.config.yaml.
  global_sources.write_string(cfg.raw.stringify())
  // Layouts compiled into the binary are part of the cache key too: changing the
  // built-in theme has to invalidate pages that were rendered with it. The
  // templates themselves are not strings any more, so the package carries a
  // revision instead — `theme_test.mbt` fails when it was not bumped after an
  // edit to a `.mtpl`.
  if theme == BuiltinTheme {
    global_sources.write_string(theme_signature())
  }
  debug_step("loading layouts")
  load_templates(cfg, env, global_sources, theme_root)
  debug_step("loading data")
  let data = load_data(cfg, global_sources, formats, theme_root)
  let site_ctx = @core.merge(cfg.globals, cfg.site_data)
  let base_ctx = @core.set(site_ctx, "site", site_ctx)
  let base_ctx = @core.set(base_ctx, "data", data)
  let base_ctx = @core.set(base_ctx, "config", cfg.raw)
  let manifest = read_manifest(cfg.cache_path())
  let cached_files = @core.get(manifest, "files")
  let new_files : Map[String, Json] = Map([])
  let pages : Array[Page] = []
  let assets : Array[(String, String)] = []
  for
    rel in @core.collect_files(source_root, fn(p) {
      is_excluded(p, cfg, prefixes)
    }) {
    if rel == "" {
      continue
    }
    if is_page_file(rel, cfg) {
      match load_page(cfg, formats, options, source_root, base_ctx, rel) {
        Some(page) => pages.push(page)
        None => ()
      }
    } else {
      assets.push((source_root, rel))
    }
  }
  // Page bodies feed collections, pagination and language switchers, which
  // other pages render. Include every page in the global cache key so adding or
  // editing one page invalidates the pages that display it.
  for page in pages {
    global_sources.write_string(page.dest)
    global_sources.write_string(page.url)
    global_sources.write_string(page.body)
    global_sources.write_string(page.data.stringify())
  }
  debug_step("computing cache")
  let global_hash = @core.hash(global_sources.to_string())
  let cache_valid = !options.force &&
    @core.get(manifest, "global") == @core.jstr(global_hash)
  debug_step("rendering pages")
  // Minify before the file is written: the old post-pass re-read every page
  // from disk and rewrote it, which doubled both the writes and the I/O.
  let shrink = cfg.plugins.contains("minify")
  let collections = build_collections(pages)
  let lang_index = build_lang_index(pages)
  let generated : Array[Page] = []
  let mut skipped = 0
  let mut writes = 0
  // Pages that end up with no shell are counted, not printed per page: a site
  // that opted out of the theme would otherwise get one line per file. `check`
  // names the files.
  let shellless : Array[String] = []
  let missing_layouts : Array[String] = []
  for page in pages {
    let out_path = @core.join_path(output_root, page.dest)
    let fresh = page_hash_of(page, global_hash)
    new_files.set(page.dest, @core.jstr(fresh))
    let key = match @core.get(cached_files, page.dest) {
      Json::String(s) => s
      _ => ""
    }
    if cache_valid && key == fresh && @fs.exists(out_path) {
      skipped += 1
      continue
    }
    let ctx = page_context(page, collections, cfg, lang_index)
    let body_html = @content.render_body(
      page.body,
      page.src,
      ctx,
      env,
      contents,
    )
    match
      page_shell(
        body_html,
        ctx,
        cfg,
        fn(name) { layout_exists(name, env, theme) },
        themed,
      ) {
      Missing(_) => missing_layouts.push(page.src)
      NoLayout => shellless.push(page.src)
      _ => ()
    }
    let output = render_page(body_html, ctx, cfg, env, theme, 0)
    let output = if shrink { minify_html(output) } else { output }
    if @core.write_if_changed(out_path, output) {
      writes += 1
    }
  }
  debug_step("pagination")
  for page in pages {
    let page_size = @core.as_int(@core.get(page.data, "paginate"))
    if page_size <= 0 {
      continue
    }
    let collection_name = str_field(page.data, "collectionSrc", "all")
    let scoped = filter_collection(
      collections,
      str_field(page.data, "lang", ""),
    )
    let source_list = @core.as_array(@core.get(scoped, collection_name))
    if source_list.length() <= page_size {
      continue
    }
    let total_pages = (source_list.length() + page_size - 1) / page_size
    for p = 1; p < total_pages; p = p + 1 {
      let start = p * page_size
      let end = (start + page_size).min(source_list.length())
      let slice_items : Array[Json] = []
      for i = start; i < end; i = i + 1 {
        slice_items.push(source_list[i])
      }
      let pagination = make_pagination(
        slice_items,
        p + 1,
        page_size,
        source_list.length(),
        page.url,
        total_pages,
      )
      let ctx = @core.set(page.data, "collections", scoped)
      let ctx = @core.set(ctx, "page", page.data)
      let ctx = @core.set(ctx, "pagination", pagination)
      let ctx = attach_languages(ctx, cfg, lang_index)
      let body_html = @content.render_body(
        page.body,
        page.src,
        ctx,
        env,
        contents,
      )
      let url = "\{page.url}page/\{p + 1}/"
      let output = render_page(body_html, ctx, cfg, env, theme, 0)
      let output = if shrink { minify_html(output) } else { output }
      let dest_rel = url_to_dest(url)
      if @core.write_if_changed(@core.join_path(output_root, dest_rel), output) {
        writes += 1
      }
      generated.push(Page::{
        src: page.src,
        dest: dest_rel,
        url,
        data: ctx,
        body: page.body,
        html: page.html,
        output,
        paginated: true,
        skip: false,
      })
      new_files.set(
        dest_rel,
        @core.jstr(@core.hash("\{page.dest}\{p}\{global_hash}")),
      )
    }
  }
  debug_step("assets")
  // Theme assets are copied first; same-named site files win in `copy_assets`.
  if theme_root != "" {
    let theme_static = @core.join_path(theme_root, cfg.static_dir)
    for rel in @core.collect_files(theme_static, fn(_) { false }) {
      assets.push((theme_static, rel))
    }
  }
  let static_root = @core.join_path(cfg.root, cfg.static_dir)
  for rel in @core.collect_files(static_root, fn(_) { false }) {
    assets.push((static_root, rel))
  }
  let (asset_count, asset_skipped, asset_writes) = copy_assets(
    assets, output_root, cached_files, new_files, cache_valid,
  )
  skipped += asset_skipped
  writes += asset_writes
  let mut asset_total = asset_count
  // The built-in stylesheet is linked by the compiled `base`, so it is worth
  // writing only when that layout can still be used: a site that overrides
  // `base` links its own CSS. Whether a page was rendered is not a signal —
  // a fully cached build renders nothing and must still claim the file, or the
  // stale-output pass deletes a stylesheet the site uses.
  if theme == BuiltinTheme && !env.sources.contains("base") && !pages.is_empty() {
    let (count, extra_skipped, extra_writes) = write_embedded_assets(
      @theme.assets(),
      output_root,
      cached_files,
      new_files,
      cache_valid,
    )
    asset_total += count
    skipped += extra_skipped
    writes += extra_writes
  }
  debug_step("plugins")
  let all_outputs : Array[Page] = []
  for p in pages {
    all_outputs.push(p)
  }
  for p in generated {
    all_outputs.push(p)
  }
  for plugin in cfg.plugins {
    // Plugin outputs join the manifest so that disabling a plugin later removes
    // the file it used to write.
    for rel in run_plugin(plugin, cfg, all_outputs, site_ctx, env) {
      new_files.set(rel, @core.jstr(@core.hash("plugin:\{rel}:\{global_hash}")))
    }
  }
  debug_step("removing stale outputs")
  // Outputs from deleted pages, renamed permalinks, removed assets or disabled
  // plugins would otherwise stay on disk forever and remain publicly reachable.
  // Everything in the manifest is a file this build wrote once, so anything the
  // current build did not claim is stale.
  for key in @core.keys(cached_files) {
    match new_files.get(key) {
      None => {
        let stale = @core.join_path(output_root, key)
        if @fs.exists(stale) && @fs.kind(stale) == Regular {
          @fs.remove(stale, allow_missing=true) |> ignore
        }
      }
      Some(_) => ()
    }
  }
  debug_step("writing manifest")
  write_manifest(cfg.cache_path(), global_hash, new_files) |> ignore
  let warnings : Array[String] = []
  if !shellless.is_empty() {
    warnings.push(
      "\{shellless.length()} page(s) have no layout; the output is an HTML fragment. Add `layout:` in front matter, or a `_layouts/base.jinja`, or drop `theme: none`.",
    )
  }
  if !missing_layouts.is_empty() {
    warnings.push(
      "\{missing_layouts.length()} page(s) name a layout that does not exist; those pages were written without it.",
    )
  }
  BuildResult::{
    pages: pages.length(),
    generated: generated.length(),
    assets: asset_total,
    skipped,
    writes,
    warnings,
    // `@env.now()` is already in milliseconds; dividing by 1e6 reported 0 ms
    // for every build.
    elapsed_ms: (@env.now() - started).reinterpret_as_int64(),
  }
}

// Load layouts and includes into the template environment. Both the bare name
// (`post`) and the file name (`post.jinja`) are registered, so both `layout:
// post` and `include "note.jinja"` resolve. A theme on disk loads first, then
// the site; a later file with the same name replaces an earlier one. Sources
// are collected before registration so an override never leaves the overridden
// version inside the engine.
//
// The built-in theme is compiled (`@theme`), not registered here: it has no
// source to parse and needs no override path. A compiled layout is rendered by
// `render_page` only when no file of that name was registered here.

///|
async fn load_templates(
  cfg : @config.Config,
  env : @engine.TemplateEnv,
  sources : StringBuilder,
  theme_root : String,
) -> Unit {
  let layout_root = @core.join_path(cfg.root, cfg.layouts_dir)
  let include_root = @core.join_path(cfg.root, cfg.includes_dir)
  let roots : Array[String] = []
  if theme_root != "" {
    roots.push(@core.join_path(theme_root, cfg.layouts_dir))
    roots.push(@core.join_path(theme_root, cfg.includes_dir))
  }
  roots.push(layout_root)
  roots.push(include_root)
  let found : Map[String, String] = Map([])
  let kinds : Map[String, String] = Map([])
  for root in roots {
    for rel in @core.collect_files(root, fn(_) { false }) {
      if !is_page_file(rel, cfg) {
        continue
      }
      let text = @core.read_text_or(@core.join_path(root, rel), "")
      sources.write_string(text)
      let dotted = @core.extname(rel)
      let ext = if dotted.has_prefix(".") {
        @core.slice(dotted, 1, dotted.length())
      } else {
        dotted
      }
      found.set(@core.strip_ext(rel), text)
      found.set(rel, text)
      kinds.set(@core.strip_ext(rel), ext)
      kinds.set(rel, ext)
    }
  }
  for name, text in found {
    let ext = match kinds.get(name) {
      Some(kind) => kind
      None => ""
    }
    env.add_with(name, text, ext)
  }
}

// Read `_data` files into one tree. Markdown data files contribute their front
// matter; every format registered in `formats` is accepted. Theme data is the
// base and site data is merged on top, so a partial override keeps the theme's
// other keys.

///|
async fn load_data(
  cfg : @config.Config,
  sources : StringBuilder,
  formats : @formats.FormatRegistry,
  theme_root : String,
) -> Json {
  let from_theme = if theme_root == "" {
    Json::object(Map([]))
  } else {
    read_data_dir(@core.join_path(theme_root, cfg.data_dir), sources, formats)
  }
  let from_site = read_data_dir(
    @core.join_path(cfg.root, cfg.data_dir),
    sources,
    formats,
  )
  @core.merge(from_theme, from_site)
}

// Parse every supported data file of one directory into a flat tree.

///|
async fn read_data_dir(
  data_root : String,
  sources : StringBuilder,
  formats : @formats.FormatRegistry,
) -> Json {
  let data = Json::object(Map([]))
  for rel in @core.collect_files(data_root, fn(_) { false }) {
    let kind = @formats.format_of_path(rel)
    let text = @core.read_text_or(@core.join_path(data_root, rel), "")
    let parsed = if formats.supports(kind) {
      sources.write_string(text)
      formats.parse(text, kind)
    } else if kind == "md" || kind == "markdown" {
      sources.write_string(text)
      let (meta, _) = @formats.split_front_matter(text)
      meta
    } else {
      continue
    }
    set_path(data, @core.strip_ext(rel), parsed)
  }
  data
}

// Read one source file into a page, or `None` when it is skipped.

///|
async fn load_page(
  cfg : @config.Config,
  formats : @formats.FormatRegistry,
  options : BuildOptions,
  source_root : String,
  base_ctx : Json,
  rel : String,
) -> Page? {
  let text = @core.read_text_or(@core.join_path(source_root, rel), "")
  let (front, body) = @formats.split_front_matter_with(text, formats)
  let (lang, page_rel) = split_language(rel, cfg)
  let no_ext = @core.strip_ext(page_rel)
  let url = page_url(cfg, front, rel)
  if url == "" {
    return None
  }
  let draft = bool_field(front, "draft")
  if draft && !options.drafts {
    return None
  }
  let mut data = @core.merge(base_ctx, front)
  // `paginate` in the site config is the default page size for archive pages.
  // Only pages that opt into a collection get the default; applying it to every
  // page would also remove regular posts from their own collections.
  if cfg.paginate_size > 0 && str_field(front, "collectionSrc", "") != "" {
    match @core.get(front, "paginate") {
      Json::Null =>
        data = @core.set(
          data,
          "paginate",
          @core.jnum(cfg.paginate_size.to_double()),
        )
      _ => ()
    }
  }
  data = set_str(data, "url", url)
  data = set_str(data, "src", rel)
  data = set_str(data, "file", @core.basename(rel))
  data = set_str(data, "slug", str_field(front, "slug", @core.basename(no_ext)))
  data = set_str(data, "path", no_ext)
  data = set_str(data, "dir", page_rel)
  data = set_str(data, "lang", lang)
  data = set_str(data, "base", cfg.lang_prefix(lang))
  data = set_str(data, "root", cfg.base_path)
  data = @core.set(
    data,
    "strings",
    @i18n.catalog(@core.get(base_ctx, "data"), lang, cfg.default_lang),
  )
  data = set_str(data, "date", str_field(front, "date", date_from_name(no_ext)))
  data = set_str(
    data,
    "collection",
    str_field(front, "collection", @core.dirname(no_ext)),
  )
  data = set_str(
    data,
    "category",
    str_field(front, "category", str_field(front, "collection", "posts")),
  )
  data = @core.set(data, "draft", @core.jbool(draft))
  data = @core.set(
    data,
    "tags",
    @core.jarr(list_field(front, "tags").map(fn(t) { @core.jstr(t) })),
  )
  Some(Page::{
    src: rel,
    dest: url_to_dest(url),
    url,
    data,
    body,
    html: body,
    output: body,
    paginated: false,
    skip: false,
  })
}

// The cache key of a page: its merged context (front matter included), its raw
// body, the shared hash and the layout it uses.

///|
fn page_hash_of(page : Page, global_hash : String) -> String {
  @core.hash(
    "\{page.data.stringify()}\{page.body}\{global_hash}\{str_field(page.data, "layout", "")}",
  )
}

// Build the template context of one page: front matter stays available as flat
// keys, and the same values are nested under `page` so bodies and layouts can
// use one spelling. Page 1 of the page's own pagination is added when the page
// drives a paginated collection.

///|
fn page_context(
  page : Page,
  collections : Json,
  cfg : @config.Config,
  index : Map[String, Map[String, String]],
) -> Json {
  let lang = str_field(page.data, "lang", "")
  let scoped = filter_collection(collections, lang)
  let ctx = @core.set(page.data, "collections", scoped)
  let ctx = @core.set(ctx, "page", page.data)
  let page_size = @core.as_int(@core.get(page.data, "paginate"))
  if page_size <= 0 {
    return attach_languages(ctx, cfg, index)
  }
  let list = @core.as_array(
    @core.get(scoped, str_field(page.data, "collectionSrc", "all")),
  )
  let total_pages = (list.length() + page_size - 1) / page_size
  let first : Array[Json] = []
  for i = 0; i < list.length().min(page_size); i = i + 1 {
    first.push(list[i])
  }
  let ctx = @core.set(
    ctx,
    "pagination",
    make_pagination(first, 1, page_size, list.length(), page.url, total_pages),
  )
  attach_languages(ctx, cfg, index)
}

// Map a page path (without the language prefix) to the URL of every language
// that has a page at that path, so a switcher can link to real translations.

///|
fn build_lang_index(pages : Array[Page]) -> Map[String, Map[String, String]] {
  let index : Map[String, Map[String, String]] = Map([])
  for page in pages {
    let lang = str_field(page.data, "lang", "")
    if lang == "" {
      continue
    }
    let path = str_field(page.data, "path", "")
    let entry = match index.get(path) {
      Some(existing) => existing
      None => {
        let created : Map[String, String] = Map([])
        index.set(path, created)
        created
      }
    }
    entry.set(lang, page.url)
  }
  index
}

// Expose `page.langs` and `page.translations`: one entry per configured
// language, with `active` marking the current one and `url` pointing at the
// translation, or at that language's home page when the page is not translated.

///|
fn attach_languages(
  ctx : Json,
  cfg : @config.Config,
  index : Map[String, Map[String, String]],
) -> Json {
  if !cfg.is_multilingual() {
    return ctx
  }
  let page_data = @core.get(ctx, "page")
  let path = str_field(page_data, "path", "")
  let lang = str_field(page_data, "lang", "")
  let siblings = index.get(path)
  let list : Array[Json] = []
  for item in cfg.languages {
    let url = match siblings {
      Some(translations) =>
        match translations.get(item.code) {
          Some(found) => found
          None => ""
        }
      None => ""
    }
    let target = if url != "" { url } else { "\{cfg.lang_prefix(item.code)}/" }
    list.push(
      @core.jobj([
        ("code", @core.jstr(item.code)),
        ("name", @core.jstr(item.name)),
        ("url", @core.jstr(target)),
        ("active", @core.jbool(item.code == lang)),
      ]),
    )
  }
  let page = @core.set(page_data, "langs", @core.jarr(list))
  let page = @core.set(page, "translations", @core.jarr(list))
  // Layouts receive the whole context as `page`, page bodies receive the page
  // data as `page`; expose the switcher in both shapes.
  let ctx = @core.set(ctx, "langs", @core.jarr(list))
  let ctx = @core.set(ctx, "translations", @core.jarr(list))
  @core.set(ctx, "page", page)
}

// Copy static assets, returning `(copied, skipped, written)`.

///|
async fn copy_assets(
  assets : Array[(String, String)],
  output_root : String,
  cached_files : Json,
  new_files : Map[String, Json],
  cache_valid : Bool,
) -> (Int32, Int32, Int32) {
  // A site asset replaces a same-named theme asset. Resolve that before
  // checking the cache; otherwise the theme copy can be written first and the
  // site copy skipped as "cached", leaving the theme version in the output.
  let selected : Map[String, String] = Map([])
  for (asset_root, rel) in assets {
    selected.set(rel, asset_root)
  }
  let mut count = 0
  let mut skipped = 0
  let mut writes = 0
  for rel, asset_root in selected {
    let source = @core.join_path(asset_root, rel)
    let target = @core.join_path(output_root, rel)
    let size = @fs.file_size(source) catch { _ => 0 }
    // Seconds alone miss an edit that keeps the size and lands in the same
    // second, which is exactly what the watcher produces when a file is saved
    // twice in a row.
    let modified = asset_stamp(source) catch { _ => "0" }
    let asset_hash = @core.hash("asset:\{rel}:\{size}:\{modified}")
    new_files.set(rel, @core.jstr(asset_hash))
    let cached = match @core.get(cached_files, rel) {
      Json::String(s) => s
      _ => ""
    }
    if cache_valid && cached == asset_hash && @fs.exists(target) {
      skipped += 1
      continue
    }
    // A file can disappear between the scan and the copy (the watcher rebuilds
    // while the user is editing); skipping it beats aborting the build.
    let content = @fs.read_binary(source) catch { _ => continue }
    let old = if @fs.exists(target) {
      @fs.read_binary(target) catch {
        _ => b""
      }
    } else {
      b""
    }
    if old != content {
      @core.ensure_dir(@core.dirname(target)) |> ignore
      @fs.write_binary(target, content)
      writes += 1
    }
    count += 1
  }
  (count, skipped, writes)
}

// Write assets that live in the binary rather than on disk. The manifest key is
// derived from the contents, so editing the built-in stylesheet invalidates it.

///|
async fn write_embedded_assets(
  files : Array[(String, String)],
  output_root : String,
  cached_files : Json,
  new_files : Map[String, Json],
  cache_valid : Bool,
) -> (Int32, Int32, Int32) {
  let mut count = 0
  let mut skipped = 0
  let mut writes = 0
  for (rel, text) in files {
    // A site file of the same name was copied already and owns the manifest
    // entry; writing the built-in copy would overwrite it.
    let claimed = match new_files.get(rel) {
      Some(_) => true
      None => false
    }
    if claimed {
      continue
    }
    let digest = @core.hash("builtin:\{rel}:\{text}")
    new_files.set(rel, @core.jstr(digest))
    let cached = match @core.get(cached_files, rel) {
      Json::String(s) => s
      _ => ""
    }
    let target = @core.join_path(output_root, rel)
    if cache_valid && cached == digest && @fs.exists(target) {
      skipped += 1
      continue
    }
    if @core.write_if_changed(target, text) {
      writes += 1
    }
    count += 1
  }
  (count, skipped, writes)
}

// Modification time with sub-second precision, as text for the asset hash.

///|
async fn asset_stamp(path : String) -> String {
  let stamp = @fs.mtime(path)
  "\{stamp.sec()}.\{stamp.subsec_nanos()}"
}

// Apply a layout chain to a rendered page body.
//
// A name resolves to a file in `_layouts` first and to a compiled layout of the
// built-in theme second, so a site overrides one layout without giving up the
// rest of the theme.

///|
fn layout_exists(
  name : StringView,
  env : @engine.TemplateEnv,
  theme : ThemeSource,
) -> Bool {
  env.sources.contains(name.to_owned()) ||
  (theme == BuiltinTheme && @theme.has_layout(name))
}

///|
fn render_page(
  body : String,
  ctx : Json,
  cfg : @config.Config,
  env : @engine.TemplateEnv,
  theme : ThemeSource,
  depth : Int32,
) -> String {
  if depth > 8 {
    return body
  }
  let themed = match theme {
    NoTheme => false
    _ => true
  }
  let layout_name = match
    page_shell(
      body,
      ctx,
      cfg,
      fn(name) { layout_exists(name, env, theme) },
      themed,
    ) {
    Applied(name) => name
    _ => return body
  }
  match env.sources.get(layout_name) {
    Some(source) => {
      let (front, _template) = @formats.split_front_matter(source)
      let scope = @core.merge(ctx, front)
      let scope = @core.set(scope, "page", ctx)
      // `body` and `content` are injected as trusted HTML by the engine.
      let rendered = @engine.render_layout(layout_name, scope, body, env)
      let parent = str_field(front, "layout", "")
      if parent == "" || parent == layout_name {
        rendered
      } else {
        let parent_ctx = @core.set(scope, "layout", @core.jstr(parent))
        render_page(rendered, parent_ctx, cfg, env, theme, depth + 1)
      }
    }
    None =>
      match
        render_builtin(layout_name, ctx, body, fn(name) {
          theme_slot(name, ctx, env)
        }) {
        Some((rendered, "")) => rendered
        Some((rendered, parent)) => {
          let parent_ctx = @core.set(ctx, "layout", @core.jstr(parent))
          render_page(rendered, parent_ctx, cfg, env, theme, depth + 1)
        }
        None => body
      }
  }
}