Skip to content

Latest commit

 

History

History
670 lines (570 loc) · 31.9 KB

render-cli.md

File metadata and controls

670 lines (570 loc) · 31.9 KB

Rendering static files with metaplate render

Static generation is the most portable way to deploy social images: render them during the build, publish them as ordinary .png or .jpg files, and no server ever runs Satori or Resvg (see the deployment guide). metaplate render is that build step. It loads a module you write, renders every page at every size its plates declare, writes each image where the plate's metadata says it lives, verifies every file on disk, and writes a manifest of what it wrote.

npx metaplate render og.render.mjs --out public

While designing a plate, metaplate preview serves the same module as a live gallery that reloads on every save, image files included.

A render module

The module's default export names the plates and the pages each one renders:

// og.render.mjs
import { fontsourceFontLoader } from "metaplate/fonts";
import { createNodeOg } from "metaplate/node";

const og = createNodeOg({
  alt: (copy) => copy.title,
  fonts: fontsourceFontLoader([{ font: "inter", weight: 700 }]),
  imagePath: "og-image.png",
  variants: { square: { size: { width: 1080, height: 1080 } } },
  component: (copy) => ({
    type: "div",
    props: {
      style: { width: "100%", height: "100%", display: "flex", fontFamily: "Inter", fontSize: 72 },
      children: copy.title,
    },
  }),
});

export default {
  plate: og,
  pages: [
    { copy: { title: "Home" } },
    { route: "/posts/hello", copy: { title: "Hello" } },
  ],
};

That writes four files and a manifest:

public/og-image.png
public/og-image-square.png
public/posts/hello/og-image.png
public/posts/hello/og-image-square.png
public/metaplate-manifest.json

The contract, in full:

  • The default export is a job, an array of jobs, or a function (sync or async) returning either. A function suits pages read from a CMS or the file system at build time. A module without a default export is refused.
  • A job is { plate, pages }. plate is a plate from createNodeOg (metaplate/node) or createEdgeOg (metaplate/edge); pages is a non-empty array.
  • A page is { route?, copy, version?, html?, page? }. copy is what the plate renders, exactly as plate.artifact(route, copy) takes it. route is the page's route as you pass it to plate.metadata(route, copy), and defaults to /. version is an optional cache-busting token for the page's image URLs (see Versioned URLs); an invalid token is refused before anything renders. html names a static HTML file to write the page's <meta> tags into, and page holds its page-level tags (see Writing tags into static HTML).
  • Sizes. A default plate renders each page at its default size and then at every declared variant, in declaration order. A variant view, og.variant("square"), renders only that size, so one job can add a single extra size for a few pages.
  • Several plates go in one array: export default [postJob, docsJob].

createSvgOg (metaplate/render) and createNextOg (metaplate/next) plates are refused with an error naming the supported factories: neither can produce the encoded bytes and metadata of an artifact. An edge plate renders once the module has supplied its Wasm modules, through createEdgeOg or initEdgeRenderer, exactly as in an edge function.

TypeScript modules can type the export with RenderJob, RenderPage, and RenderModule from metaplate/node, which check each page's copy against its plate:

import { createNodeOg, type RenderJob, type RenderModule } from "metaplate/node";

const posts = { plate: og, pages } satisfies RenderJob<Copy>;
export default [posts] satisfies RenderModule;

examples/api/render-module.ts type-checks a complete module against the sources.

Where files go

Each image is written at its plate's sitePath(route): the route joined with that size's imagePath, without basePath or origin. That is the path the metadata URL resolves to once --out is deployed under basePath. A plate with basePath: "/docs" and origin: "https://example.github.io" advertises https://example.github.io/docs/posts/hello/og-image.png and the file is written to public/posts/hello/og-image.png, which a GitHub Pages project site serves at exactly that URL. The manifest records both: path on disk and url as published.

sitePath is part of every plate's surface, so a hand-written build script can use the same rule:

og.sitePath("/posts/hello"); // "posts/hello/og-image.png"
og.variant("square").sitePath("/posts/hello"); // "posts/hello/og-image-square.png"

Paths are checked before anything renders, and a bad one fails the run:

  • Never outside --out. Routes are already held to the plate's pathname rules (no . or .. segments, literal or percent-encoded, no backslashes). Percent-escapes are then decoded the way a static host maps a URL onto a file (/caf%C3%A9 is written to café/), and a decoded segment that is empty, a dot segment, or contains / or \ is refused. Every target must resolve inside --out; before each write the directory's real path must still be inside it, so a symbolic link or junction inside --out cannot carry a write elsewhere, and an existing symbolic link is never written through.
  • Portable names only. A segment containing < > : " | ? * or a control character, a Windows device name such as con or nul, or a name ending in a dot or a space is refused on every platform, so one module produces one tree on Windows, macOS, and Linux.
  • One image per file. Two pages or sizes that would write the same file are refused, including two paths differing only in case, which collide on the default Windows and macOS filesystems.

--out is not emptied first; files the run does not write are left alone.

Versioned URLs

Crawlers cache images by URL, so a card that changes needs a new URL (see Versioned image URLs). A plate created with version: "copy" (and optionally a design revision) publishes each page's image URL with ?v=<token> derived from its copy, and a page's own version overrides that token for the page:

const og = createNodeOg({ /* ... */ imagePath: "og-image.png", version: "copy", revision: "2" });

export default {
  plate: og,
  pages: [
    { route: "/posts/hello", copy: { title: "Hello" } },
    { route: "/about", copy: { title: "About" }, version: "release-12" },
  ],
};

The token changes only the manifest url, which is the URL the page's metadata publishes. The file is written at the same unversioned path, because a static host serves posts/hello/og-image.png for any query on that path:

{
  "path": "posts/hello/og-image.png",
  "url": "/posts/hello/og-image.png?v=1e52226d"
}

Render the module with the same plate your pages use for their metadata, so the manifest and the pages agree on every token. For a hand-written HTML page, let the command write the tags itself, as the next section shows.

Writing tags into static HTML

A framework page gets its tags from the framework, but a hand-written page in public/ (a landing page or a concept board served beside the app) needs them written into the file. Name the file in the page's html and its page-level tags in page:

// og.render.mjs
export default {
  plate: og,
  pages: [
    {
      route: "/rebrand/",
      copy: { title: "Our new look" },
      html: "public/rebrand/index.html",
      page: {
        title: "Our new look",
        description: "What changed, and why.",
        url: "https://example.com/rebrand/",
        siteName: "Example",
      },
    },
  ],
};
<!-- public/rebrand/index.html, before -->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Our new look</title>
  </head>
  <body>...</body>
</html>

After metaplate render og.render.mjs --out public, with a plate whose origin is https://example.com and with version: "copy":

  <head>
    <meta charset="utf-8">
    <title>Our new look</title>
    <!-- metaplate:social -->
    <meta property="og:image" content="https://example.com/rebrand/og-image.png?v=1e52226d">
    <meta property="og:image:width" content="1200">
    <meta property="og:image:height" content="630">
    <meta property="og:image:type" content="image/png">
    <meta property="og:image:alt" content="Our new look">
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:image" content="https://example.com/rebrand/og-image.png?v=1e52226d">
    <meta name="twitter:image:alt" content="Our new look">
    <meta property="og:title" content="Our new look">
    <meta property="og:description" content="What changed, and why.">
    <meta property="og:url" content="https://example.com/rebrand/">
    <meta property="og:site_name" content="Example">
    <meta property="og:type" content="website">
    <!-- /metaplate:social -->
  </head>

The command prints ✓ public/rebrand/index.html social tags written, or social tags unchanged when the file already holds exactly these tags.

Where the tags come from. The image tags are the plate's own metadata(route, copy), with the page's version token, so og:image is the URL in the manifest, ?v= included; a plate with variants lists every size. The page-level tags are socialMetaHtml's, so page takes the fields of SocialMetaOptions: title, description, url, siteName, type, locale, alternateLocales, article, pubdate, and themeColor, validated and escaped the same way (an unknown field is refused). <title> and <link rel="canonical"> stay yours.

og:url is page.url, exactly as given. Nothing is derived from the route or the plate's origin, and no slash is added or removed, because only you know whether the host serves /rebrand/ or /rebrand: use the URL your canonical link names. Without page.url no og:url is written. page.url is also the base that relative image URLs resolve against, so a plate with no origin needs it (the run fails without it, since crawlers ignore relative og:image URLs).

The block. The tags go between <!-- metaplate:social --> and <!-- /metaplate:social -->. On the first run the block is inserted on its own lines just before </head> (matched in any case), indented like the line above it; a </head> inside a comment, <script>, <style>, or <template> is skipped, as a browser skips it. After that the block is replaced in place and nothing outside it changes, so a second run writes the same bytes and an unchanged page is not written at all. To put the tags somewhere else in <head>, add the two markers there yourself. CRLF files keep CRLF, and a file that starts with a UTF-8 byte order mark keeps it.

What fails. These stop the run before anything renders or is written, with the earlier manifest kept, as a refused image path does:

  • an html path outside the directory the command runs in, not ending in .html or .htm, missing, a symbolic link, or the same file as an image, the manifest, or another page's html (case-insensitively);
  • a file that is not UTF-8;
  • no </head> and no markers (the command does not guess where <head> ends), a head that ends before its </head> (at body text or a tag such as <div>) with no markers, a start marker without an end marker or the reverse, more than one of either, markers out of order, or a block after </head>;
  • a block a crawler would not read, such as one inside a comment or <script>, and an og:image or twitter:image outside the block, which would leave a crawler with two cards;
  • a page field socialMetaHtml refuses, such as the locale en-US.

When it writes. html is resolved against the directory the command runs in, like --manifest, not against --out, so the page can live anywhere in the project. A page is written only after every image of that page has rendered and verified: if one fails, the file is left exactly as it was, the run exits 1, and no manifest is written. The new text is staged beside the file, read back, and renamed over it, as images are. With --incremental, a reused image counts as rendered, and the page is rewritten only if its tags changed. --json adds an html array to the report, one { path, route, valid, changed, issues } entry per page, only when the module names a page.

Formats and verification

The plate decides the format. A plate with no output writes PNG; a plate with an output encoder writes what that encoder produces, at the plate's imagePath.

Static hosts choose the Content-Type from the file extension, so the imagePath must end in the format's extension: .png, .jpg or .jpeg, .webp, .gif, .avif, or .svg, in any case. An image whose file name has no extension (such as the default og-image) or another format's fails before it is written, because the host would serve it as the wrong type and crawlers and verify-url would reject it.

Every image is checked before it replaces anything. The rendered bytes must pass verifyImage (the format and the exact dimensions the size advertises) and any --target rules first; then they are written to a temporary file beside the target, read back, and checked again (the SHA-256 must match and verifyImage must pass), and only then renamed over the target. An image that fails any check leaves the previous file exactly as it was, with no temporary file behind. This always runs, with no flag to turn it off: it walks the image's chunk structure without decoding pixels, which costs little next to rendering, and a static build has no later point at which a truncated or mis-sized file would be caught before a crawler sees it. The one exception is an encoder declared with checkSignature: false (a format Metaplate cannot recognize, such as AVIF): its file is still written and hashed, but recorded with "format": null and "verified": false.

To hold every file to a platform's published rules as well, pass --target, once per platform, and --max-file-size for a limit of your own:

npx metaplate render og.render.mjs --out public --target whatsapp --target linkedin

These are the checks metaplate verify --target makes, such as WhatsApp's 600 KB limit or LinkedIn's minimum size, so the render step needs no second command with the sizes repeated. A file that fails one counts as a failed image: it is reported, the command exits 1, and no manifest is written. The image URL is checked only when it is absolute HTTPS. A root-relative URL is resolved by the page that publishes it, as Next.js does with metadataBase, and an http://localhost origin belongs to a local or CI build that is never crawled, so either would fail every card for no fault of the card. An image reused by --incremental is checked again, because the targets are not part of its input hash.

Command line

metaplate render [--json] [--incremental] [--out DIR] [--manifest FILE] [--concurrency N] [--target TARGET] [--max-file-size BYTES] <module>
Option Meaning
<module> The render module: .mjs, .js, .cjs, or, where Node strips types, .ts, .mts, .cts (see Loading TypeScript and JSX). Relative to the current directory.
--out DIR The directory the site is published from. Default public. Created if missing.
--manifest FILE Where to write the manifest. Default DIR/metaplate-manifest.json. Pass a path outside DIR to keep the manifest out of the published site.
--concurrency N Render at most N images at once, 1 to 256. Default 4.
--incremental Reuse each image whose inputs and file are unchanged since the previous manifest; see Incremental builds.
--target TARGET Fail any file that breaks this platform's rules. Repeat for several. The names are the compatibility profiles.
--max-file-size BYTES Fail any file larger than this.
--json Print one JSON report instead of a line per image.

Without --json, each image prints ✓ <path> <width>x<height> <format> (<bytes> bytes) as it is written (<bytes> bytes, unchanged when --incremental reused it), each failure prints ✗ <path> render failed: <reason> to stderr, and a summary line follows.

Concurrency. Satori's layout and Resvg's rasterization both run on the main JavaScript thread (Metaplate calls Resvg's synchronous render), so within one process they run one at a time whatever the limit. The limit bounds how many renders are in flight, and so how much image memory is held at once, while font loading, asynchronous output encoders (sharp runs on its own thread pool), and file writes overlap. Raise it for modules whose encoders do real work off the main thread; lower it to cap memory on a small build machine. The manifest and the JSON report list images in declaration order whatever order renders finish in; the per-image lines print as each one finishes.

Exit codes

Code Meaning
0 Every image rendered, was written inside --out, matched its hash and dimensions on disk, every html page holds its tags, and the manifest was written.
1 Anything else: an argument error (printed with the usage line), a module that cannot be loaded or breaks the contract, a refused path, collision, or malformed html page (nothing is rendered), at least one image that failed to render, write, or verify, or one html page that could not be written.

These match metaplate verify, verify-url, and verify-page, which also exit 1 for every failure. When some images fail, the rest are still rendered and written, every failure is reported, and no manifest is left behind, so a deploy step that publishes only when the manifest exists never publishes half a build. That includes the manifest of an earlier run: once the module loads and every path passes its checks, the existing manifest is deleted before the first image is written, because the files it lists are about to change. A run that fails before that point (an argument error, a module that cannot load, a refused path) touches nothing, so the earlier manifest still describes the earlier files. A successful run writes the manifest to a temporary file beside it and renames it into place, so no reader ever sees a partial manifest.

Each image is replaced atomically, but a run is not a transaction. In a run where some images fail, those keep their previous files, and the ones that passed are already replaced, so --out holds a mix of old and new cards. The missing manifest is the signal not to publish it. To publish all or nothing, render into a scratch directory and swap it in on success, as One card per record shows.

Format, size, and structure checks cannot tell a blank card from a drawn one. Give the module's plate render guards set to "error" and a card with text off the canvas, text no font covers, or a single-color image fails its render here, exits 1, and keeps the manifest unwritten.

Manifest

One entry of the manifest written for examples/api/render-module.ts:

{
  "schemaVersion": 1,
  "images": [
    {
      "path": "posts/hello-world/og-image-square.png",
      "url": "https://example.github.io/docs/posts/hello-world/og-image-square.png",
      "route": "/posts/hello-world",
      "variant": "square",
      "size": { "width": 1080, "height": 1080 },
      "format": "png",
      "contentType": "image/png",
      "bytes": 14853,
      "sha256": "9c30c52b62d368f585ef08665d49a9a3c6c3ab8791c731b1d8e178f514bdaf3a",
      "verified": true,
      "inputHash": "7eed8a15e1d9154e163bde353b53893b7aead494f9d12ab83db8f9d4acdeb282",
      "inputs": []
    }
  ]
}
Field Meaning
schemaVersion 1. Fields may be added within a version; removing or changing one bumps it.
path The file, relative to --out, with / separators on every platform.
url The image URL the plate's metadata publishes for it, with basePath, origin, and any ?v= version token.
route The page route, as given (default /).
variant The variant name, or null for the default size.
size The width and height the file was verified at.
format png, jpeg, webp, gif, or null for an unrecognizable encoder format.
contentType The media type the plate serves the image as.
bytes, sha256 Length and lowercase hex SHA-256 of the file as read back from disk.
verified Whether verifyImage checked the file (false only when format is null).
inputHash Lowercase hex SHA-256 of everything known to determine the bytes (see Incremental builds), or null when the plate has no fingerprint() or the copy cannot be serialized. Added within schema version 1.
inputs The files the image read while it rendered, sorted by path, each with the lowercase hex SHA-256 of its contents (see Files a card reads). A path is relative to the directory the command ran in, with / separators and ../ for a file outside it; a file that shares no root with it (another Windows drive, or a UNC path) keeps its absolute path. The manifest is published with the site unless --manifest points outside DIR, so these paths are too. Added within schema version 1.

Images appear in declaration order: jobs, then pages, then the default size before each variant.

JSON report

--json prints { "schemaVersion": 1, "out", "manifest", "images" }, where out and manifest are paths relative to the current directory, manifest is null when none was written, and each images entry is a manifest entry plus "valid": true, an empty issues array, and "reused" (true when --incremental kept the existing file). A failed image has only its identity and its issues:

{
  "path": "posts/hello/og-image.png",
  "route": "/posts/hello",
  "variant": null,
  "valid": false,
  "issues": [{ "severity": "error", "message": "Expected 1200x630, received 1080x1080" }]
}

When the module names html pages, the report also has an html array, one { "path", "route", "valid", "changed", "issues" } entry per page; see Writing tags into static HTML.

A module that cannot be loaded or breaks the contract prints its error to stderr instead of a report.

Incremental builds

A site with hundreds of pages re-renders every card on every build, though a typical change touches a few. --incremental renders only what changed. Each manifest entry records an inputHash: the SHA-256 of

  • the Metaplate version, and the installed satori, @resvg/resvg-js, @resvg/resvg-wasm, and takumi-js versions, resolved from the render module's location;
  • the image's path, route, and variant;
  • the plate's fingerprint() for that size: its renderer (node, edge, or takumi), revision, size, output format, guard levels, the bytes of every font fonts() returns, the source text of component and of the other functions in the definition (such as an output encoder), and its satori, emoji, and resvg options;
  • the page's copy, with object keys in insertion order at every depth, because a component can read that order (Object.values(copy)), so a reordered copy renders again rather than reusing the file.

With --incremental, an image is reused, not rendered, only when its inputHash equals the one in the previous manifest and every file in its inputs still has the SHA-256 that manifest recorded and the file on disk still has the byte length and SHA-256 that manifest recorded and it still passes verifyImage. Anything else renders: a new or edited page, a changed plate, an image file the card draws that was edited or deleted, an output file edited or deleted since the last build, an entry from before inputHash or inputs existed, or a manifest that cannot be read (which prints a warning and renders everything). A reused entry is recorded with the plate's current URL, versioned as the page's version or the plate's version: "copy" says, so changing origin, basePath, or a version token does not force a render. Without the flag, every image renders, as before.

Files a card reads

Copy and code are not the only inputs: a card can draw an artwork file or a product photo that changes while its path stays the same. metaplate render records the files each card reads, with the SHA-256 of their contents, in that card's inputs, and --incremental renders the card again when one of them changes or disappears:

  • Through metaplate/assets. Every readImageAsset and fileImageLoader call made while a card renders records the file for that card, including a fileImageLoader call answered from memory. A file read while the render module loads, such as a logo read at its top level, is recorded for every card. Each card has to make the call: a promise the plate caches itself, such as logo ??= readImageAsset("logo.svg") inside the component, records the file only for the card that created it. Share a file between cards with fileImageLoader, read it at the module's top level, or list it in inputs. A file read outside any card counts for every render running in the process, and for later ones: a second runCli render in the same process finds the module already loaded, so its top-level reads are not made again but still count.
  • With plain fs. List the files in the plate's inputs option, which receives the card's copy. Relative paths resolve against the directory the command runs in; a file: URL is read as is. A listed file that cannot be read fails that card.
const og = createNodeOg({
  // The component reads public/<copy.image> itself.
  inputs: (copy) => [`public/${copy.image}`],
  // ...
});

Fonts are covered already: the plate's fingerprint hashes the bytes fonts() returns.

The manifest names each file by its path, so a file whose name or location should stay private needs --manifest outside the published DIR.

A render repeated in one process, such as runCli called twice by a watch script, reuses the loaded module and whatever its loaders hold in memory: a card whose image file changed renders again, but draws the bytes loaded the first time, and records that it did, so the next build in a fresh process renders it once more with the new file. Files read outside any card also count for every later render in that process, even of another render module, so its cards can render again when the other module's files change. Run each build in its own process when files change between them.

What the hash cannot see

A function's source text does not include what it imports or closes over: a component that calls a helper from another file, or reads a theme object defined elsewhere, renders differently when that helper changes while its own text stays the same. Images fetched at render time (an <img src> URL, a remoteImageLoader or fetchImageLoader image, an emoji loader's network source), files read with plain fs that inputs does not list, and the files of installed packages that emoji and languageFonts loaders read are not hashed either. Set the plate's revision to name the version of everything outside the component, and change it when any of that changes:

const og = createNodeOg({
  // Any string works: a release number, or a hash of the plate's files.
  revision: "2026-11-01",
  // ...
});

Copy that is not plain data (a class instance other than Date, URL, or a byte array, a symbol, a cycle, or a function, whose captured values its source text cannot show) gets inputHash: null and always renders. A clean build, without --incremental or after deleting --out, is the reference whenever in doubt; CI release builds should use one.

Loading modules

The CLI runs on Node and loads the module with a dynamic import() of the file's file: URL, built with url.pathToFileURL as the Node documentation recommends for importing a path (a Windows drive path is not a valid specifier). The module is an ordinary ES module: top-level await works, and its own imports, such as metaplate/node, resolve from its location, so keep it inside the project that installs Metaplate. Font loaders such as fontsourceFontLoader resolve packages from the current directory, so run the command from the project root.

A .js module is an ES module when the nearest package.json has "type": "module"; otherwise Node decides by syntax detection, which is on by default from Node 20.19 and 22.7. .mjs is always an ES module and avoids the question. A CommonJS module (.cjs) works too: its module.exports is the default export.

Loading TypeScript and JSX

Metaplate adds no TypeScript or JSX compiler. A .ts module loads only where Node itself strips types, which depends on the Node version running the CLI:

Node .ts, .mts, .cts
20 Not supported: compile the module to .js.
22.6 to 22.17 With NODE_OPTIONS=--experimental-strip-types.
22.18+, 23.6+, 24, and later By default (disabled by --no-strip-types).

Type stripping removes type annotations and does nothing else, so a module must use only erasable syntax:

  • Type-only imports need type: import { createNodeOg, type RenderJob } from "metaplate/node". Without it Node treats the import as a value and fails at run time (details). TypeScript's verbatimModuleSyntax enforces this.
  • No syntax that needs code generation: enum, namespaces with runtime code, parameter properties, and import x = require() aliases (details) fail with a message naming them; TypeScript's erasableSyntaxOnly flags them.
  • Relative imports name the real file, extension included (./plates.ts), and tsconfig.json (including paths) is not read.
  • No .tsx or .jsx. Node does not transform JSX in any version.

So a TypeScript module authors its plate with plain { type, props } objects, as examples/api/render-module.ts does (see also Authoring without a JSX toolchain). For a plate written in JSX, run the command in-process under tsx. The command's import() then goes through the loader tsx registered, and this works the same on Windows, macOS, and Linux:

// scripts/render-cards.mts
import { runCli } from "metaplate/cli";

process.exit(await runCli(["render", "--out", "public", "src/lib/og/cards.render.tsx"]));
{ "scripts": { "cards": "tsx scripts/render-cards.mts" } }

Keep the .mts extension: in a package without "type": "module", tsx compiles a .ts script to CommonJS and rejects its top-level await. tsconfig.json needs "jsx": "react-jsx" and an include that covers the plate, or the render fails with React is not defined. Static Next.js sites shows the whole setup.

Two other routes work. Compile the module first (with tsc, your bundler, or your framework's build) and pass the compiled .js. Or register the loader for the CLI's process, as in NODE_OPTIONS="--import tsx" npx metaplate render og.render.tsx, which is POSIX shell syntax: an npm script on Windows runs through cmd.exe, where it fails with 'NODE_OPTIONS' is not recognized, unless you add a package such as cross-env. Node never type checks a module on any of these routes, so keep tsc --noEmit in the build.