fus

    A general-purpose high-performance static site generator for MoonBit

    static-site
    generator
    ssg
    cli
    Download zip
    Author
    Version
    0.1.4
    License
    MIT
    Last updated
    1 hour ago
    Downloads
    35

    #Fus

    A native static site generator for MoonBit. One executable turns Markdown, templates and data into plain HTML — no Node.js runtime in the loop.

    fus.justjavac.com — installation, the full manual, and the project site, built with Fus itself.

    #Highlights

    • Fast — single-pass builds, content-hash cache, zero writes when nothing changed.
    • Complete — CommonMark + GFM, Jinja2 and Liquid, layouts, includes, data, collections, pagination.
    • AI-ready — llms.txt / llms-full.txt, structured metadata, plain static output.
    • Themes and i18n — themes provide defaults the site overrides; languages and translation tables come from config.
    • Embeddable — the core is a library, the CLI is a thin wrapper.

    #Quick start

    moon install justjavac/fus/fus # install the CLI fus init my-site # scaffold a site fus run --root my-site --port 8000 # build, serve and watch fus build --root my-site # output: my-site/_site/

    A page is a Markdown file with front matter:

    --- title: Hello layout: base --- # Hello Fus

    #Use as a library

    // moon.pkg import { "justjavac/fus", }

    // main.mbt
    async fn main {
    let opts = @fus.make_options("my-site", None, None, false, false, true)
    let result = @fus.build_site(opts)
    println("built \{result.pages} pages")
    }

    Every subpackage is re-exported through @fus; build_site_with accepts custom format, page-format and template-engine registries.

    #Commands

    CommandWhat it does
    fus init [dir]Scaffold a new site.
    fus buildRender the site into _site/.
    fus checkValidate config, content and templates without writing.
    fus runBuild, serve and rebuild on change.
    fus serveSame as run, for scripts that name the server.
    fus cleanRemove the output directory and cache.
    fus versionPrint the version.
    fus helpPrint the command list.

    #justjavac/fus

    The facade package: one import re-exports every subpackage.

    ///|
    // moon.pkg
    import {
    "justjavac/fus",
    }

    ///|
    async fn main {
    let opts = @fus.make_options("my-site", None, None, false, false, true)
    let result = @fus.build_site(opts)
    println("built \{result.pages} pages")
    }

    @fus.* covers core, formats, markdown, i18n, highlight, engine, content, config, build, check and cli. Hosts that need one layer only can import that subpackage directly.

    To swap the extension points, pass registries to build_site_with:

    ///|
    let result = @fus.build_site_with(
    opts,
    @fus.FormatRegistry::builtin(),
    @fus.ContentRegistry::builtin(),
    None,
    )

    Fus targets the native backend only; a module that depends on it must declare supported_targets = "native" in its moon.pkg.

    BuildOptions

    The build pipeline.

    BuildResult

    The build pipeline.

    CheckIssue

    Read-only validation.

    CheckReport

    Read-only validation.

    CleanScope

    The command table behind the executable.

    Command

    The command table behind the executable.

    Config

    Site configuration.

    ContentFormat

    Page formats and the body pipeline.

    ContentRegistry

    Page formats and the body pipeline.

    EngineKind

    Template engines.

    FormatRegistry

    Data formats and front matter.

    IssueLevel

    Read-only validation.

    Outcome

    The command table behind the executable.

    Page

    using @justjavac/fus/build { type Page }

    The build pipeline.

    PageShell

    The build pipeline.

    TemplateEngine

    Template engines.

    TemplateEnv

    Template engines.

    ThemeSource

    The build pipeline.

    as_array

    Return the array inside a JSON value, or an empty array.

    as_bool

    fn as_bool(value :
    Json
    ) -> Bool

    Interpret a JSON value with template-style truthiness.

    as_int

    fn as_int(value :
    Json
    ) -> Int

    Convert a JSON number or numeric string to an integer, or zero.

    as_str

    fn as_str(value :
    Json
    ) -> String

    Convert a JSON value to a plain string, using its representation for scalars.

    attr_escape

    fn attr_escape(s : StringView) -> String

    Escape text for use inside a quoted HTML attribute.

    basename

    fn basename(path : StringView) -> String

    Return the final component of a path.

    bool_field

    fn bool_field(value :
    Json
    , key : StringView) -> Bool

    Read a boolean field, defaulting to false.

    build_collections

    Derive all, named and tag collections from the page set.

    Pages that drive pagination are excluded, and a page with skipCollection: true opts out of every collection.

    build_command

    async fn build_command(options :
    BuildOptions
    ) -> Unit

    Build a site and print the summary unless quiet mode is requested.

    build_site

    Run the full build pipeline with the built-in formats and engines.

    build_site_with

    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.

    builtin_assets

    fn builtin_assets() -> Array[(String, String)]

    Static assets of the built-in theme, as (file name, contents).

    builtin_layout

    fn builtin_layout(layout : StringView) -> Bool

    Whether the built-in theme provides layout, compiled.

    The build and check both answer "does this layout exist" through one function, so a name the build can render is never reported as missing.

    catalog

    fn catalog(data :
    Json
    , lang : StringView, default_lang : StringView) ->
    Json

    The translation catalogue a page in lang should see.

    data is the whole _data tree, so i18n.<default> and i18n.<lang> are merged, with the current language winning. Missing keys fall back to the default language, then to nothing (the template prints an empty string).

    char_at

    fn char_at(s : StringView, index : Int) -> Char

    Return the character at a UTF-16 code-unit index.

    Indexes are code units, the same unit String::length() counts, so char_at(s, i) and s[a:b] agree on non-ASCII text. The lookup is O(1); the previous implementation called to_array() on every access, which made any per-character loop quadratic (a 30-page site spent 12 s in minify).

    An index past the end panics, like ordinary indexing. An index that lands on the second half of a surrogate pair (only possible when a caller steps through an emoji one code unit at a time) returns U+FFFD instead, so a blind scan cannot crash a build.

    check_command

    async fn check_command(options :
    BuildOptions
    ) -> Bool

    Validate a site and print every finding.

    Returns true when no errors were found. Warnings do not fail the check, so this suits a CI gate while leaving room for non-fatal notes.

    check_site

    Validate a site without writing any output, using the built-in formats.

    check_site_with

    Validate a site with an explicit format registry.

    Checks the configuration file, the content and layout directories, front matter delimiters, layout chains, include targets, duplicate permalinks, unknown plugins and skipped drafts. Only reads files: _site and .fus-cache are never modified, so this is safe to run in CI.

    clean_site

    Remove generated output, the incremental cache, or both.

    Paths come from the loaded configuration, so --root alone is enough even when the site writes to a custom dest. Content files are never touched. Returns false, without deleting anything, when the output resolves to the site root: dest: . or a .. segment would otherwise erase the sources.

    collect_files

    async fn collect_files(base : String, exclude : (String) -> Bool) -> Array[String]

    Walk a directory tree and return every regular file, relative to base.

    Results are sorted so build output is deterministic. exclude receives a full path (normalized to forward slashes) and prunes whole subtrees as well as single files: a site whose srcDir is the site root keeps its config file and static folder next to its pages, and both must stay out of the content scan.

    default_options

    Return options for building the current directory with defaults.

    The defaults are: root ., no config/dest override, cache enabled, drafts excluded and summary printed.

    dirname

    fn dirname(path : StringView) -> String

    Return the parent directory portion of a path.

    dispatch

    async fn dispatch(args : Array[String]) ->
    Outcome

    Run one command from the process arguments.

    This is the single place that knows how a command maps to an action, so the main only has to start the server when this returns Serve.

    display

    fn display(value :
    Json
    ) -> String

    Render a JSON value as human-readable template text.

    display_name

    fn display_name(lang : StringView) -> String

    The heading of a language in its own words, used by switchers.

    Unknown codes are returned uppercased so a new language still renders.

    engine_kind

    fn engine_kind(name : StringView) ->
    EngineKind

    Parse a templateEngine configuration value.

    ensure_dir

    async fn ensure_dir(path : StringView) -> Unit

    Ensure a directory (and all parents) exists. Handles Windows drive prefixes.

    extname

    fn extname(path : StringView) -> String

    Return the dotted extension of a path, or an empty string.

    format_date

    fn format_date(value : StringView, format : StringView) -> String

    Human-readable timestamp, using only lexical parsing so the builder stays locale-independent.

    format_of_path

    fn format_of_path(path : StringView) -> String

    Lowercase extension of path without the leading dot, ready for parse.

    get

    Read a key from a JSON object, returning null for other kinds.

    Use get_path for dotted and indexed paths.

    get_path

    fn get_path(value :
    Json
    , path : StringView) ->
    Json

    Read a dotted JSON path such as site.author.name or posts.0.title.

    Numeric segments index arrays. Any missing segment returns null, which keeps template lookups total.

    has_any

    fn has_any(s : StringView, chars : StringView) -> Bool

    Check whether any character of a set occurs in the input.

    has_prefix

    fn has_prefix(s : String, prefix : StringView) -> Bool

    Check whether a string starts with a prefix.

    has_suffix

    fn has_suffix(s : String, suffix : StringView) -> Bool

    Check whether a string ends with a suffix.

    has_unclosed_front_matter

    fn has_unclosed_front_matter(text : StringView) -> Bool

    Detect a front matter block that opens but never closes.

    hash

    fn hash(s : StringView) -> String

    64-bit FNV-1a, used for content hashes in the incremental cache.

    help

    fn help(topic? : String?) -> Unit

    Print the command list, or the usage of one command when topic is set.

    highlight_code

    fn highlight_code(code : StringView, lang : StringView) -> String

    Highlight a code block and return HTML with hl-* spans.

    The input is plain code (not escaped). Unknown languages are escaped and returned without spans, so callers can always inject the result.

    highlight_html

    fn highlight_html(html : String) -> String

    Add syntax highlighting to the fenced code blocks of an HTML document.

    Only blocks that carry a language- (or lang-) class are touched; plain code blocks and inline code are left exactly as they were.

    html_escape

    fn html_escape(s : StringView) -> String

    Escape text for use in HTML element content.

    init_site

    async fn init_site(root : String) -> Unit

    Scaffold a complete example site at root.

    is_document

    fn is_document(body : StringView) -> Bool

    Whether a body already is a whole HTML document.

    A page that opens with <!doctype> or <html> brought its own shell; wrapping it in base would nest two documents. Templates that emit a full page are common enough that the check is worth the two string comparisons.

    is_excluded

    fn is_excluded(path : StringView, cfg :
    Config
    , prefixes : Array[String]) -> Bool

    Check whether a path is ignored or inside an excluded prefix.

    is_page_file

    fn is_page_file(path : StringView, cfg :
    Config
    ) -> Bool

    Check whether a path has a configured page extension.

    jarr

    Build a JSON array from values.

    jbool

    fn jbool(b : Bool) ->
    Json

    Build a JSON boolean value.

    jnum

    fn jnum(n : Double) ->
    Json

    Build a JSON number value.

    jobj

    Build a JSON object from key/value pairs, retaining insertion order.

    join_path

    fn join_path(base : String, name : StringView) -> String

    Join a base path and a relative name using forward slashes.

    jstr

    fn jstr(s : StringView) ->
    Json

    Build a JSON string value.

    keys

    fn keys(value :
    Json
    ) -> Array[String]

    List the keys of a JSON object in insertion order.

    lines

    fn lines(text : StringView) -> Array[String]

    Split text into lines without keeping the trailing empty line of a newline-terminated document.

    list_field

    fn list_field(value :
    Json
    , key : StringView) -> Array[String]

    Read an array-of-strings field, defaulting to empty.

    load_config

    async fn load_config(root : String, config_path : String?, dest_override : String?, force : Bool) ->
    Config

    Load and normalize a site configuration with the built-in registries.

    root is the site directory. config_path overrides the default file, dest_override overrides the configured output directory and force disables reading the cache manifest. Formats follow the file extension.

    load_config_with

    async fn load_config_with(root : String, config_path : String?, dest_override : String?, force : Bool, formats :
    FormatRegistry
    , contents :
    ContentRegistry
    ) ->
    Config

    Load configuration with explicit registries.

    Use this to add data formats or page formats: the configuration file is parsed by formats, and the default pageExtensions come from contents.

    make_options

    fn make_options(root : String, config : String?, dest : String?, force : Bool, drafts : Bool, quiet : Bool) ->
    BuildOptions

    Create build options from explicit values.

    Use this when embedding Fus in another tool. config and dest are optional overrides; force bypasses the incremental cache, drafts includes draft pages and quiet suppresses the build summary.

    make_pagination

    fn make_pagination(items : Array[
    Json
    ], number : Int, page_size : Int, total : Int, base_url : String, page_count : Int) ->
    Json

    Build the pagination object exposed to one page of a sliced collection.

    merge

    Deep merge used for layout data, global data and page front matter. Values from extra win; objects are merged recursively.

    minify_html

    fn minify_html(input : StringView) -> String

    Remove redundant whitespace from generated HTML.

    Scans for < and copies whole runs instead of walking character by character: page text is UTF-16, so per-character scanning both costs a transition per character and can split a surrogate pair.

    normalize_slashes

    fn normalize_slashes(path : StringView) -> String

    Convert Windows separators to forward slashes.

    page_shell

    fn page_shell(body : String, front :
    Json
    , cfg :
    Config
    , has_layout : (StringView) -> Bool, themed : Bool) ->
    PageShell

    Decide the shell for a page.

    One decision, used by the build and by the validator, so a page can never be reported as shellless by one and wrapped by the other. has_layout answers whether a layout name is registered; themed says whether a theme is in charge, which is what allows the base fallback.

    parse_command

    fn parse_command(args : Array[String]) ->
    Command

    Parse argv into a command for the caller to execute.

    argv[0] is the program name, as in @env.args(); the subcommand is argv[1]. An argv with no subcommand builds the current directory, so parse_command(["fus"]) is the same as parse_command(["fus", "build"]). Passing subcommand arguments without the program name (["check"]) builds instead, because check lands in the program-name slot.

    parse_double

    fn parse_double(s : StringView) -> Double?

    Parse a decimal or floating point number, rejecting trailing junk.

    parse_format

    fn parse_format(text : StringView, format : StringView) ->
    Json

    Parse text as the named format using the built-in registry.

    parse_ini

    fn parse_ini(text : StringView) ->
    Json

    Parse a small INI document: [section] headers and key = value pairs.

    Top-level keys stay at the root, section keys become nested objects, and scalars are typed so port = 8000 works without a schema.

    parse_int

    fn parse_int(s : StringView) -> Int?

    Parse an optionally signed decimal integer.

    parse_json

    fn parse_json(text : StringView) ->
    Json

    Parse JSON with the core parser.

    parse_options

    Parse global options after the command name.

    Returns the resulting build options and the requested HTTP port. Unknown tokens are ignored so that subcommands can grow without breaking callers.

    parse_toml

    fn parse_toml(text : StringView) ->
    Json

    Parse TOML with moonbit-community/toml.

    parse_yaml

    fn parse_yaml(text : StringView) ->
    Json

    Parse YAML with moonbit-community/yaml, taking the first document.

    prefix_for

    fn prefix_for(lang : StringView, default_lang : StringView) -> String

    The URL prefix of a language: empty for the default one.

    prefix_for("zh", "en") is /zh, while prefix_for("en", "en") is empty, so callers can concatenate without special cases.
    fn print_version() -> Unit

    Print the tool version line.

    read_text_or

    async fn read_text_or(path : StringView, fallback : String) -> String

    Read a UTF-8 file, returning a fallback when it cannot be read.

    render_body

    fn render_body(body : String, src : StringView, ctx :
    Json
    , env :
    TemplateEnv
    , registry :
    ContentRegistry
    ) -> String

    Render a page body: template first, then the format transform.

    Templating runs before Markdown so that a {% for %} loop can generate list items or table rows that Markdown then parses as real blocks.

    render_builtin

    fn render_builtin(layout : StringView, page :
    Json
    , body : String, slot : (StringView) -> String) -> (String, String)?

    Render a compiled layout, returning its HTML and the layout that wraps it.

    None means the name is not compiled and the caller should look for a file in _layouts instead. base returns "" as its parent: it is the shell.

    slot resolves one fragment of the shell (head, header, menu, footer, pagination): a file in the site wins, the compiled fragment is the fallback, and an empty string means "nothing here".

    render_layout

    fn render_layout(name : StringView, ctx :
    Json
    , body_html : StringView, env :
    TemplateEnv
    ) -> String

    Render a layout with body and content bound to trusted HTML.

    render_markdown

    fn render_markdown(text : StringView) -> String

    Render a Markdown document to HTML.

    CommonMark plus GFM tables, task lists and strikethrough, with an id attribute added to every heading so anchors keep working, and hl-* spans added to fenced code blocks that name a language. Raw HTML is passed through: page bodies are trusted content.

    render_source

    fn render_source(source : StringView, ctx :
    Json
    , env :
    TemplateEnv
    ) -> String

    Render an inline template source, used for page bodies.

    render_source_of

    fn render_source_of(source : StringView, path : StringView, ctx :
    Json
    , env :
    TemplateEnv
    ) -> String

    Render an inline template source with the engine of path.

    Page bodies use this: a post.liquid body is Liquid even when Jinja is the default, and a post.jinja body stays Jinja even when templateEngine is liquid. Extensions no engine owns (.md, .html) fall back to the default.

    render_template

    fn render_template(name : StringView, ctx :
    Json
    , env :
    TemplateEnv
    ) -> String

    Render a registered template by name.

    resolve_config_path

    async fn resolve_config_path(root : String, config_path : String?) -> String

    Path of the configuration file a build would read.

    config_path wins when given. Otherwise the first existing file of fus.config.yaml, .yml, .json, .toml, .ini is used, and finally the YAML path so that callers always have something to create or report.
    fn resolve_permalink(cfg :
    Config
    , front :
    Json
    , no_ext : String) -> String

    Expand permalink placeholders into a final URL.

    Supported placeholders: :path, :slug, :collection, :title, :date, :year, :month, :day. A template of false or none skips the page.

    resolve_theme

    Pick the theme for a loaded configuration.

    A directory on disk always wins over the built-in theme of the same name, so theme: fus keeps working for a site that vendored and edited that theme.

    rfind

    fn rfind(s : StringView, needle : StringView) -> Int?

    Last occurrence of a substring, implemented with StringView::find so it also works for multi-byte Unicode separators.

    safe_html

    fn safe_html(s : StringView) ->
    Json

    Mark a string as trusted HTML for templates that need it explicitly.

    scalar

    fn scalar(raw : StringView) ->
    Json

    Parse a scalar from YAML/front matter, keeping dates and versions as strings.

    set

    Return a copy of an object with one key replaced or added.

    Non-object inputs are converted to a fresh object so context building never needs a mutable binding.

    set_path

    fn set_path(root :
    Json
    , path : StringView, value :
    Json
    ) -> Unit

    Assign a value at a slash-separated path, creating objects along the way.

    Data files use this so _data/nav/links.yaml lands at data.nav.links.

    set_str

    fn set_str(value :
    Json
    , key : String, s : StringView) ->
    Json

    Set a string field on a JSON object.

    slice

    fn slice(s : StringView, start : Int, end : Int) -> String

    Return a substring using character indices, clamped to the input bounds.

    slugify

    fn slugify(s : StringView) -> String

    Stable heading slugs. ASCII words are lower-cased; non-ASCII characters are kept so Chinese and other headings do not all collapse to section-N.

    split_front_matter

    fn split_front_matter(text : StringView) -> (
    Json
    , String)

    Split front matter using the built-in format registry.

    split_front_matter_with

    fn split_front_matter_with(text : StringView, formats :
    FormatRegistry
    ) -> (
    Json
    , String)

    Split a source file into front matter data and the remaining body.

    --- opens YAML, ;;; opens JSON and +++ opens TOML front matter; the block ends at the next line holding the same delimiter. Anything else is body text and the data is an empty object.

    split_language

    fn split_language(path : StringView, cfg :
    Config
    ) -> (String, String)

    Split a source path into its language and the path inside that language.

    zh/about.md belongs to zh when zh is configured; every other path belongs to the default language and is returned unchanged. A site without an i18n block returns ("", path), so nothing changes for single-language sites.

    split_once

    fn split_once(s : StringView, delimiter : Char) -> (String, String)?

    Split at the first delimiter outside quotes, returning both halves.

    split_top_level

    fn split_top_level(s : StringView, delimiter : Char) -> Array[String]

    Split on a delimiter that is not nested in quotes or brackets.

    str_field

    fn str_field(value :
    Json
    , key : StringView, fallback : String) -> String

    Read a string field with a fallback.

    strip_ext

    fn strip_ext(path : StringView) -> String

    Remove the final extension from a path.

    strip_trailing_slash

    fn strip_trailing_slash(text : StringView) -> String

    Remove trailing slashes, keeping a lone /.

    Site URLs are joined with page URLs, and every page URL starts with /: a site.url of https://example.com/ would otherwise produce https://example.com//about/ in the sitemap, the feed and canonical.

    theme_path

    fn theme_path(source :
    ThemeSource
    ) -> String

    The theme's absolute directory, or "" when there is no directory to read.

    theme_signature

    fn theme_signature() -> String

    Revision of the compiled theme, for the build cache key.

    theme_slot

    fn theme_slot(name : StringView, page :
    Json
    , env :
    TemplateEnv
    ) -> String

    Resolve one shell slot, preferring the site over the compiled fragment.

    head has no compiled default: it is the injection point for extra <meta>, fonts or analytics, and renders nothing until the site provides it.

    to_int

    fn to_int(s : StringView) -> Int

    Parse an integer, returning zero when the input is not numeric.

    to_url

    fn to_url(path : StringView) -> String

    Turn a relative source path into a canonical site URL.

    The final segment decides the shape: index.html becomes the directory URL (blog/index.html → /blog/), a file such as assets/logo.png keeps its extension and gets no trailing slash, and anything else is treated as a directory and ends in /. Leading ./ segments are ignored.

    trim

    fn trim(s : StringView) -> String

    Trim ASCII whitespace from both ends and return an owned string.

    trim_quotes

    fn trim_quotes(s : StringView) -> String

    Remove one pair of matching single or double quotes.

    truthy

    fn truthy(value :
    Json
    ) -> Bool

    Apply template truthiness, treating "false" and "0" strings as false.

    url_to_dest

    fn url_to_dest(url : StringView) -> String

    Translate a site URL into an output-relative file path.

    version

    let version : String

    The Fus version, without a leading v.

    write_if_changed

    async fn write_if_changed(path : StringView, content : String) -> Bool

    Write a file only when its content actually changed. Returns true when a write happened.

    Source Files