For AI agents: fetch /llms.txt first for the curated documentation index, then use same-host Markdown pages when available.

Reference

API Reference.

Generated from JSDoc in @nativefragments/core and @nativefragments/lit. Each symbol links back to the concept guide that explains it.

@nativefragments/core/server

Server HTML

Tagged-template HTML rendering that escapes by default, with helpers for attributes and embedded JSON. Source ↗

raw

raw(value?) → RawHtml

Mark a value as trusted HTML. Use this only for framework-generated markup or content that has already been validated. Ordinary interpolated values in html are escaped by default.

Parameters

  • value unknown optional = ""

    HTML to insert without escaping.

Returns

RawHtml — Trusted HTML wrapper.

html`<div>${userInput}</div>`        // escaped — safe
html`<div>${raw(userInput)}</div>`   // bypasses escaping — trusted HTML only

See also Agent-Friendly Apps

escapeHtml

escapeHtml(value) → string

Escape a value for safe insertion into HTML text or attribute context.

Parameters

  • value unknown

    Value to escape.

Returns

string — Escaped HTML string.

html

html(strings, ...values) → RawHtml

Server-side HTML template tag with escaped interpolation by default. Arrays are flattened, null, undefined, and false become empty strings, and trusted values returned by html, raw, or attrs are inserted as HTML without being re-escaped.

Parameters

  • strings TemplateStringsArray

    Template literal string parts.

  • values ...unknown

    Interpolated values.

Returns

RawHtml — Rendered HTML wrapper.

import { html, raw } from "@nativefragments/core/server";

// Interpolations are escaped by default — user input is safe.
const card = (post) => html`<article>
  <h2>${post.title}</h2>
  ${raw(post.bodyHtml)}
</article>`;

See also Components

jsonScript

jsonScript(value) → string

Serialize JSON for safe embedding inside an inline script tag. < characters are escaped so embedded JSON cannot accidentally terminate the script element.

Parameters

  • value unknown

    Value to serialize.

Returns

string — JSON string safe for script text.

import { html, jsonScript, raw } from "@nativefragments/core/server";

// Safe to embed in an inline script — "<" is escaped.
html`<script type="application/json">${raw(jsonScript(state))}</script>`;

attrs

attrs(attributes?) → RawHtml

Build escaped HTML attributes from an object. false, null, and undefined values are omitted. true values render as boolean attributes. Attribute names must be valid HTML-like names.

Parameters

  • attributes HtmlAttrs optional = {}

    Attribute map.

Returns

RawHtml — Trusted HTML attribute string.

import { attrs, html } from "@nativefragments/core/server";

// false / null / undefined are dropped; true renders a boolean attribute.
html`<button ${attrs({ disabled: post.locked, "data-id": post.id })}>Edit</button>`;

@nativefragments/core/server

Server Routing

Define routes, match requests, and render full pages or individual named fragments. Source ↗

fragment

fragment(name, definition) → FragmentDefinition

Create a named fragment definition. Use this when a route has a nested region with its own navigation. The returned object can be registered in route(..., { fragments: [item] }) and its attributes can be reused on links and target containers.

Parameters

  • name string

    Fragment slot name.

  • definition FragmentRenderer | Omit<FragmentDefinition, "name" | "attrs" | "prefetchAttrs">

    Fragment renderer or full fragment definition.

Returns

FragmentDefinition — Fragment definition.

  • name string

    Fragment slot name.

  • Fragment renderer.

  • loading FragmentLoadingRenderer optional

    Loading renderer used by deferred HTML streaming.

  • error FragmentErrorRenderer optional

    Error renderer used when a deferred fragment fails after its HTML response has started.

  • timeout number optional

    Maximum deferred render time in milliseconds.

  • attrs (attributes?: import("./html.js").HtmlAttrs) => import("./html.js").RawHtml

    Attributes for links and target containers using this fragment slot.

  • prefetchAttrs (mode?: "intent" | "visible" | "load" | "none", attributes?: import("./html.js").HtmlAttrs) => import("./html.js").RawHtml

    Attributes for links using this fragment slot with a prefetch mode.

import { fragment, route } from "@nativefragments/core/server";

const panel = fragment("settings-panel", renderPanel);

route("/settings/profile", {
  render: settingsPage,
  fragments: [panel], // exposes the named slot for partial swaps
});

See also Fragments

route

route(path, definition) → Route

Create a normalized route definition.

Parameters

  • path string

    URL path for the route. Use :name segments for path params, for example /posts/:slug.

  • definition RouteDefinition

    Route metadata and render functions.

    • meta (context: RouteContext) => RouteMeta | Response | Promise<RouteMeta | Response> optional

      Function that returns metadata for the route.

    • status number optional = 200

      Status used for rendered HTML responses.

    • headers Record<string, string> | ((context: RouteContext) => Record<string, string> | Promise<Record<string, string>>) optional

      Headers merged into rendered HTML responses after adapter defaults.

    • action (context: RouteContext) => Response | Promise<Response> optional

      POST handler for no-JavaScript mutations. Must return a native Response, usually a 303 redirect.

    • render (context: RouteContext) => string | import("./html.js").RawHtml | Response | Promise<string | import("./html.js").RawHtml | Response>

      Function that renders route body HTML.

    • fragments Record<string, FragmentRenderer | FragmentDefinition> | FragmentDefinition[] optional

      Named fragment renderers used by nested fragment slots.

Returns

Route — Normalized route.

import { html, route } from "@nativefragments/core/server";

// :slug becomes ctx.params.slug
export const post = route("/blog/:slug", {
  meta: (ctx) => ({ title: ctx.params.slug }),
  render: (ctx) => html`<h1>${ctx.params.slug}</h1>`,
});

See also Routing

redirect

redirect(location, status?) → Response

Create a redirect response.

Parameters

  • location string | URL

    Redirect destination.

  • status number optional = 302

    Redirect status.

Returns

Response — Native redirect response.

readSearch

readSearch(searchParams, defaults) → T

Read string query parameters with defaults. Each returned key is searchParams.get(key) when it is a non-empty string, otherwise the default value.

Parameters

  • searchParams URLSearchParams

    Query parameters.

  • defaults T

    Default values.

Returns

T — Query values merged with defaults.

createRoutes

createRoutes(routes) → { all: Route[], match(pathname: string): Route | null }

Create a route manifest that can match normalized paths. Exact static routes win first, then parameterized routes are matched in declaration order.

Parameters

  • routes Route[]

    Route definitions.

Returns

{ all: Route[], match(pathname: string): Route | null } — Route manifest.

import { createRoutes } from "@nativefragments/core/server";

const manifest = createRoutes([home, post]);
manifest.match("/blog/hello"); // → the post route, params.slug = "hello"

See also Routing

fragmentMeta

fragmentMeta(meta) → import("./html.js").RawHtml

Render fragment metadata for the browser fragment router.

Parameters

  • meta RouteMeta

    Metadata to embed in the fragment response.

    • title string optional

      Document title.

    • description string optional

      Meta description.

    • canonical string optional

      Canonical URL.

    • alternates { hreflang: string, href: string }[] optional

      Alternate language URLs for <link rel="alternate" hreflang="...">.

Returns

import("./html.js").RawHtml — Script tag containing serialized metadata.

See also Fragments

renderRoute

renderRoute(options) → Promise<{ body: string, meta: Required<Pick<RouteMeta, "title" | "description" | "canonical">> & RouteMeta, deferred: unknown[], status: number, headers: Record<string, string> } | { response: Response }>

Render a matched route and normalize metadata defaults.

Parameters

  • options { match: Route, request: Request, slot?: string | null, deferredTimeout?: number | null }

    Render options. When slot matches a registered named fragment, only that fragment renderer is used. Calls to context.defer() always collect deferred work for the adapter to stream or inline.

Returns

Promise<{ body: string, meta: Required<Pick<RouteMeta, "title" | "description" | "canonical">> & RouteMeta, deferred: unknown[], status: number, headers: Record<string, string> } | { response: Response }> — Rendered route.

renderFragment

renderFragment(rendered) → import("./html.js").RawHtml

Render a fragment response body with embedded metadata.

Parameters

  • rendered { body: string, meta: RouteMeta }

    Rendered route body and metadata.

Returns

import("./html.js").RawHtml — Fragment HTML.

errorRoute

errorRoute

Default 500 route used by adapters when a route render fails.

Type

{Route}

@nativefragments/core/server

Server API

Source ↗

apiRoute

apiRoute(method, path, handler) → ApiRoute

Create a normalized API route. Paths use the same :param and trailing :rest* segment syntax as page routes.

Parameters

  • method string

    Upper-case HTTP method.

  • path string

    API path pattern.

  • handler ApiHandler

    API handler.

Returns

ApiRoute — Normalized API route.

createApi

createApi(routes, options?) → { fetch(request: Request, env?: Record<string, unknown>, context?: unknown): Promise<Response> }

Create a Fetch-compatible API router.

Parameters

  • routes ApiRoute[]

    API route definitions.

    • method string

      Upper-case HTTP method.

    • path string

      Normalized API route path.

    • handler ApiHandler

      API route handler.

  • options { onError?: (event: { error: unknown, request: Request, route?: ApiRoute }) => void } optional = {}

    API options.

Returns

{ fetch(request: Request, env?: Record<string, unknown>, context?: unknown): Promise<Response> } — Fetch-compatible API router.

@nativefragments/core/cloudflare

Cloudflare Adapter

Turn a route manifest into a Cloudflare Worker that serves pages, fragments, static assets, and API routes. Source ↗

createCloudflareHandler

createCloudflareHandler(options) → { fetch(request: Request, env: Record<string, unknown>): Promise<Response> }

Create a Cloudflare Worker module for a Native Fragments app. Static assets are served from the configured assets binding. Normal document requests render the app shell. Requests with x-fragment: true return the route body plus fragment metadata, using framed HTML streaming when the route has deferred content. Requests under apiPrefix are delegated to the optional API router before app route matching.

Parameters

  • options CloudflareHandlerOptions

    Worker adapter options.

    • routes Route[]

      App route definitions.

    • shell (rendered: { body?: import("../server/html.js").RawHtml, meta: object, nonce?: string }) => string | import("../server/html.js").RawHtml | { before: string | import("../server/html.js").RawHtml, after: string | import("../server/html.js").RawHtml } | Promise<string | import("../server/html.js").RawHtml | { before: string | import("../server/html.js").RawHtml, after: string | import("../server/html.js").RawHtml }>

      Function that wraps a rendered route body in a full HTML document.

    • api { fetch(request: Request, env: Record<string, unknown>, context?: unknown): Promise<Response> | Response } | import("../server/api.js").ApiRoute[] optional

      Optional Web Standards API router or array of apiRoute() definitions. Hono apps work here because they expose a compatible fetch method.

    • apiPrefix string optional = "/api"

      URL prefix handled by api.

    • notFound Route optional

      Optional 404 route.

    • error Route optional

      Optional 500 route.

    • onError ({ error, request, phase }: { error: unknown, request: Request, phase: "route" | "error-route" | "api" }) => void optional

      Error hook for caught route, error-route, and API failures.

    • assetsBinding string optional = "ASSETS"

      Cloudflare assets binding name.

    • deferredTimeout number | null optional = 15000

      Default timeout in milliseconds for each deferred fragment renderer. Set null to disable.

    • contentSecurityPolicy string | false | ((options: { nonce: string, request: Request }) => string | false) optional

      Content Security Policy header. Defaults to frame-ancestors 'self'. Pass a function to build a nonce-based strict policy.

Returns

{ fetch(request: Request, env: Record<string, unknown>): Promise<Response> } — Cloudflare Worker module.

// worker.js
import { createCloudflareHandler } from "@nativefragments/core/cloudflare";
import { routes } from "./site/routes.js";
import { shell } from "./site/shell.js";

export default createCloudflareHandler({ routes, shell });

See also API Routes · Getting Started

@nativefragments/core/client/router.js

Browser Router

Upgrade same-origin links into streamed fragment navigation with explicit control, caching, and lifecycle events. Source ↗

startRouter

startRouter(options?) → Readonly<FragmentRouter>

Start document navigation and return a small imperative controller. Links and opted-in GET forms retain their native behavior when JavaScript is unavailable. While active, same-origin navigation is upgraded with streamed HTML fragments, history, metadata, focus, scrolling, and prefetching.

Parameters

  • options FragmentRouterOptions optional = {}

    Router options.

    • target string | Element optional = "#content-slot"

      Primary navigation target.

    • cacheTtl number optional = 30000

      Completed fragment cache lifetime.

    • prefetch PrefetchMode | boolean optional = "intent"

      Default automatic prefetch policy.

    • viewTransitions boolean optional = true

      Use View Transitions when available.

    • signal AbortSignal optional

      Aborting this signal tears down the router.

Returns

Readonly<FragmentRouter> — Router controller.

  • navigate (href: string | URL, options?: NavigateOptions) => Promise<void>

    Navigate to a route or named fragment.

  • prefetch (href: string | URL, options?: FragmentRequestOptions) => Promise<void>

    Warm a completed fragment in the shared cache.

  • invalidate (href?: string | URL, options?: InvalidateOptions) => void

    Drop matching cached and in-flight fragments, or all fragments when omitted.

import { startRouter } from "@nativefragments/core/client/router.js";

const router = startRouter({ prefetch: "intent" });
await router.navigate("/blog/hello");
router.invalidate("/blog/hello");

See also Fragments

@nativefragments/core/client/worker.js

Web Workers

A tiny RPC layer over Web Workers for moving expensive work off the main thread. Source ↗

transferResult

transferResult(payload, transfer?) → { payload: T, transfer: Transferable[], [transferMarker]: true }

Wrap a worker response with Transferable objects.

Parameters

  • payload T

    Response payload.

  • transfer Transferable[] optional = []

    Transferable objects to move.

Returns

{ payload: T, transfer: Transferable[], [transferMarker]: true }

import { exposeWorker, transferResult } from "@nativefragments/core/client/worker.js";

exposeWorker({
  // Move the buffer instead of copying it.
  bytes: (buffer) => transferResult(buffer, [buffer]),
});

See also Workers

workerClient

workerClient(worker, options?) → NativeWorkerClient

Create a tiny RPC client for a dedicated Web Worker.

Parameters

  • worker Worker

    Worker instance.

  • options WorkerClientOptions & { owned?: boolean } optional = {}

    Client options.

    • timeout number optional = 30000

      Request timeout in milliseconds.

    • owned boolean optional

Returns

NativeWorkerClient — Worker client.

  • call (type: string, payload?: unknown, transfer?: Transferable[]) => Promise<unknown>

    Call a named worker handler.

  • dispose () => void

    Reject pending calls, remove listeners, and terminate workers constructed by createWorkerClient.

  • worker Worker

    The wrapped Worker instance.

See also Workers

createWorkerClient

createWorkerClient(workerOrUrl, options?) → NativeWorkerClient

Create a module worker and wrap it with workerClient.

Parameters

  • workerOrUrl string | URL | Worker

    Existing Worker or worker module URL.

  • options WorkerClientOptions & { workerOptions?: WorkerOptions } optional = {}

    Client and Worker constructor options.

    • timeout number optional = 30000

      Request timeout in milliseconds.

    • workerOptions WorkerOptions optional

Returns

NativeWorkerClient — Worker client.

import { createWorkerClient } from "@nativefragments/core/client/worker.js";

const search = createWorkerClient("/build/search-worker.js");
const hits = await search.call("search", { rows, query: "native" });

See also Workers

exposeWorker

exposeWorker(handlers, scope?) → () => void

Expose named handlers inside a dedicated Web Worker.

Parameters

  • handlers Record<string, (payload: unknown, context: { event: MessageEvent, type: string }) => unknown | Promise<unknown>>

    Worker handlers keyed by message type.

  • scope NativeWorkerScope optional = globalThis

    Worker global scope.

    • postMessage (message: unknown, transfer?: Transferable[]) => void

      Post a message to the paired thread.

    • addEventListener (type: "message", listener: (event: MessageEvent) => void) => void

      Register a message listener.

    • removeEventListener (type: "message", listener: (event: MessageEvent) => void) => void

      Remove a message listener.

Returns

() => void — Cleanup function.

// client/search-worker.js
import { exposeWorker } from "@nativefragments/core/client/worker.js";

exposeWorker({
  search: ({ rows, query }) =>
    rows.filter((row) => row.title.toLowerCase().includes(query.toLowerCase())),
});

See also Workers

@nativefragments/lit/server

Lit SSR

Render Lit templates and custom elements as hydratable server HTML. Source ↗

renderLit

renderLit(value) → Promise<import("@nativefragments/core/server").RawHtml>

Render a Lit template or component tree to trusted server HTML. Component modules must be imported by the Worker so their custom element definitions are registered in Lit's server DOM shim.

Parameters

  • value unknown

    Lit template value to render.

Returns

Promise<import("@nativefragments/core/server").RawHtml>

import { renderLit } from "@nativefragments/lit/server";
import { html } from "lit";
import "../../client/components/app-card.js";

export const card = () =>
  renderLit(html`<app-card>Ready</app-card>`);

See also Lit Components

Types

Shared object shapes referenced by the functions above.

RawHtml

{ [RAW]: true, value: string, toString(): string }

HtmlAttrs

Record<string, string | number | boolean | null | undefined>

RouteContext

object

Properties

  • request Request

    Original request.

  • signal AbortSignal

    Request cancellation signal.

  • url URL

    Parsed request URL.

  • query URLSearchParams

    Parsed query parameters from url.searchParams.

  • params Record<string, string>

    Path parameters captured from a route pattern like /posts/:slug.

  • defer (fragment: FragmentDefinition | string, attributes?: import("./html.js").HtmlAttrs) => import("./html.js").RawHtml

    Render a stable loading boundary and collect a named fragment for deferred HTML streaming during document loads and browser fragment navigation.

FragmentRenderer

(context: RouteContext) => string | import("./html.js").RawHtml | Response | Promise<string | import("./html.js").RawHtml | Response>

FragmentLoadingRenderer

(context: RouteContext) => string | import("./html.js").RawHtml

FragmentErrorRenderer

(error: unknown, context: RouteContext) => string | import("./html.js").RawHtml | Promise<string | import("./html.js").RawHtml>

Route

RouteDefinition & { path: string, params?: Record<string, string> }

ApiContext

object

Properties

  • request Request

    Original request.

  • env Record<string, unknown>

    Runtime environment bindings.

  • context unknown

    Runtime execution context.

  • url URL

    Parsed request URL.

  • query URLSearchParams

    Parsed query parameters from url.searchParams.

  • params Record<string, string>

    Path parameters captured from the API route.

  • signal AbortSignal

    Request cancellation signal.

ApiHandler

(context: ApiContext) => unknown | Response | Promise<unknown | Response>

PrefetchMode

"none" | "intent" | "visible" | "load"

FragmentRequestOptions

object

Properties

  • slot string optional

    Named fragment target.

  • signal AbortSignal optional

    Abort this request consumer.

InvalidateOptions

object

Properties

  • slot string optional

    Limit invalidation to one named fragment target.