Skip to content

@ogygia/rewrite

Custom elements

rewrite({ match, render }) sends the custom elements match picks to your render function, one batch per chunk of the page and one per region answer, and puts each result in the element's place with the stylesheets it needs.

On this page

rewrite({ match, render }) from @ogygia/rewrite makes a Kit handle that sends the custom elements match picks to your render function, and puts what it returns in their place. List it before ogygia.handle() in sequence().

In the example, a handle renders every my-* element in one batch through a design system’s server renderer.

import { rewrite } from '@ogygia/rewrite';
import { renderBatch } from '$lib/server/renderer';

export const components = rewrite({
  match: 'my-',
  async render(elements, ctx) {
    const rendered = await renderBatch(
      elements.map((el) => el.html),
      { signal: ctx.signal }
    );
    return rendered.map((r) => ({
      html: r.html,
      sheets: r.sheets
    }));
  }
});
import { sequence } from '@sveltejs/kit/hooks';
import * as ogygia from 'ogygia/server';
import { components } from '$lib/server/components';

export const handle = sequence(
  components,
  ogygia.handle()
);

Matching

match picks the elements:

  • a tag prefix, such as 'my-';
  • a list of tag names, such as ['my-card', 'my-nav'];
  • a function that takes the lower-case tag name and returns true or false.

Only custom elements in the <body> are candidates (a name with a hyphen), so match never sees a div. Names are compared in lower case. Only the outermost match is sent; a match inside it goes along inside its html. A chunk of the page with no match goes out byte for byte, and render isn’t called.

import { rewrite } from '@ogygia/rewrite';
import { renderElement } from '$lib/server/renderer';

const KNOWN = new Set(['my-card', 'my-nav', 'my-button']);

export const components = rewrite({
  match: (name) => KNOWN.has(name),
  render: (elements) =>
    elements.map((el) => renderElement(el.html))
});

Render function

render(elements, ctx) is called once per chunk of a streamed page with every match in that chunk, and once per region answer. It may be async.

  • Each element has name (the tag, lower case), html (its outer HTML) and restored (whether ogygia puts it back for Svelte; see Restored elements).
  • Return one result per element, in order: { html, sheets }, or the HTML string alone.
  • ctx has kind ('document' for a page, 'region' for a region answer), csr (Kit hydrates the whole page; always false for a region answer), url, event (Kit’s RequestEvent), and signal, which aborts when the request is cancelled.

Each element’s html has ogygia’s marks numbered from 0, so the same element has the same bytes on every page, and a cache can key on it. Elements with equal html in one call are sent once. ogygia has no cache of its own, so the example keeps one.

import { rewrite, type RewriteResult } from '@ogygia/rewrite';
import { renderElement } from '$lib/server/renderer';

const cache = new Map<string, RewriteResult>();

export const components = rewrite({
  match: 'my-',
  render: (elements) =>
    elements.map((el) => {
      let hit = cache.get(el.html);
      if (hit === undefined)
        cache.set(el.html, (hit = renderElement(el.html)));
      return hit;
    })
});

Stylesheets

A result’s sheets is a list of { key, css, scope, attrs? }:

  • scope: 'page' becomes a <style> the document applies.
  • scope: 'shadow' becomes a <template> the document doesn’t apply.

A restored element names the sheets for its root by key in og-shadow, whatever their scope. Each one is built once and adopted by every shadow root that names its key, so one sheet can serve the page and the shadow roots alike. A restored element that names a key the page carries no sheet for paints without it, and the browser warns restore_sheet_missing.

Each key goes out once per response, and the first sheet with that key wins. While the <head> is still open, a sheet goes there. After that, it goes inline right before the first element that needs it. In a region answer it goes inline, and the runtime moves it into the head.

Sheet attributes

attrs (optional) are written on the sheet’s tag after its key, with values escaped: a media, or a library’s own marker. A shadow root that names the sheet adopts its CSS and its media with it, so a print sheet doesn’t paint on screen there either. The other attributes are on the tag only.

A name must be a plain attribute name. It can’t be an on… handler, one of ogygia’s marks (og-…, data-og-…, data-ogygia-…, ogygia-…), is, a name that starts with xmlns, or shadowroot…. A render that asks for one fails like any invalid result (rewrite_element_failed).

A nonce in attrs is the nonce of the request that rendered the sheet, so it only matches the page’s policy for a document response’s own sheets. A region answer or an incoming page is another request: its sheets go into the page’s head, where the page’s policy checks them against the page’s nonce, so a nonce-based style-src blocks them. Don’t rely on a sheet nonce outside the document response.

import { rewrite } from '@ogygia/rewrite';
import {
  renderElement,
  shadowCss,
  pageCss
} from '$lib/server/renderer';

export const components = rewrite({
  match: 'my-',
  render: (elements) =>
    elements.map((el) => ({
      html: renderElement(el.html),
      sheets: [
        { key: 'my.page', css: pageCss, scope: 'page' },
         {
          key: `${el.name}.shadow`,
          css: shadowCss(el.name),
          scope: 'shadow'
        } 
      ]
    }))
});
import { rewrite } from '@ogygia/rewrite';
import { renderElement, printCss } from '$lib/server/renderer';

export const components = rewrite({
  match: 'my-',
  render: (elements) =>
    elements.map((el) => ({
      html: renderElement(el.html),
      sheets: [
        {
          key: 'print',
          css: printCss,
          scope: 'page',
          attrs: { media: 'print' }
        }
      ]
    }))
});

Streaming

A streamed page goes out chunk by chunk, and each chunk’s matches are rendered in one call and sent with that chunk. An element that starts in one chunk and ends in a later one (an {#await} inside it) goes out as ogygia rendered it and renders in the browser. Dev says rewrite_element_split, once per response and element name. Keep streamed blocks out of matched elements, or put the element inside the streamed block.

Failures

A failed render never breaks the page:

  • If the batch throws or returns the wrong number of results, each element is tried again on its own.
  • An element that still fails goes out as ogygia rendered it and renders in the browser. Only that element is affected. ogygia warns rewrite_element_failed once per response and element name, in every build.
  • A result whose HTML doesn’t close what it opens fails too, since it would swallow the rest of the page.
  • A result that drops og-h from an element ogygia restores goes out the same way, with rewrite_marks_lost. A serializer that keeps only the attributes it knows, or a sanitizer, does this.
  • When the request was cancelled, nothing is retried and nothing is said.

Testing shows how to catch each of these in a unit test with .check().