SHADE is young: 0.1.0-next.2 is a pre-release, and 0.1.0 isn't out yet.

SHADE
Sites in other frameworks

`@shadestack/render`

The website editor's rendering core. Framework-free, on @shadestack/tree, @shadestack/expressions and @shadestack/styles; the four framework packages render what it gives with their own components (ShadeTree in each, below). Everything is decided on the server; the frameworks only write it.

import { headData, pageSources, resolvePage, sourceKey } from '@shadestack/render'

// The data sources the tree and its components name, fetched first (rendering is synchronous).
const sources = new Map(await Promise.all(pageSources(tree, library).map(async source => [sourceKey(source), await fetchItems(source)] as const)))

const result = resolvePage({
  tree, // the page's tree, as stored (any schema version)
  treeId: page.id, // what its local styles are keyed by
  components: library, // { card: { tree, interface, defaults, variants, treeId } }
  entry, site, // plain data
  visitor, // the account's allow-listed projection, made on the server; read only in server islands, with `signedIn` added
  sources: source => sources.get(sourceKey(source)),
  locale: 'nl', defaultLocale: 'nl', timeZone: 'Europe/Amsterdam', translations,
  media: id => media[id], // { url, width, height, alt, variants }
  localStyles: styles.local, // which nodes get data-s
  edit: false // true: every element gets data-shade-node (and data-shade-instance) and its data-s key
})
result.nodes // the resolved tree: elements, texts and islands
result.classes // the style classes used (the CSS is compileStyles', linked once)
result.issues // what wasn't rendered and where: codes and paths, never the data's values (every ShadeTree tells them on the server)
const head = headData({ title, description, canonical, alternates, language: 'nl', image })
  • The resolved tree (resolved.ts) is plain elements with checked attribute values and texts (never HTML: every framework escapes them, and toHtml, the core's own writer, does too), and islands. Bindings are evaluated with the expressions' interpreter; every URL place (links, quotations, media, a media library image and its srcset, a menu item, navigate) goes through the runtime's url with its own schemes, literal or bound, also for a tree that skipped the save gate; a link value or a media library image there is its address (an entry's through links). If keeps only the branch that holds; Each repeats per item of a list or a data source, with its empty branch; component instances render their tree with their properties (literal, bound or the component's defaults), their slots' content in the scope it was written in and their variant's classes on the top elements. A bound property is held to its declared type (boundProperty: a choice one of its choices, a number finite…), or gets its empty value and an issue. A failure shows nothing in its place and is reported.
  • Rich text bound to a text node renders from its schema's nodes and marks only (richTextNodes; headings are h2, h3 or h4, a level rounded and held to them, h2 for one that is no number), as much as may stand there: blocks in a div, texts and marks with line breaks in a p, its text in an option.
  • Images from the media library get srcset (the original among the sizes), the tree's sizes (default 100vw), dimensions, loading="lazy", the library's alt text, and a <picture> with a source per other format (a variant's type, image/avif before image/webp). An image without alt text is written with alt="" and reported; alt="" in the tree marks it decorative.
  • Server islands read visitor; outside them it is not in scope. They render with the visitor by default (pass it on a dynamic route); the page is then the visitor's (result.personal) and each package sends it with Cache-Control: private, no-store (cacheHeaders(result); in Astro applyCacheHeaders(Astro, result) in the page's frontmatter). serverIslands: 'defer' makes placeholders for Astro's server:defer, rendered per request by renderServerIsland(serverIslandPayload(result, key), { visitor }), which reads only the visitor fields the payload names. A payload holds what only some visitors may see, so it is never part of the result's data: a result sent as a framework's page data, copied or cloned has none. Next, Nuxt and SvelteKit seal it instead (Deferred server islands, below).
  • Client islands carry ClientIslandData: their state's first values and types and a template with everything decided but what depends on the state, an event or a live loop's item. Each live expression carries only the fields it reads of the entry, the site, the props and the loops around it, never the visitor. createIsland(data, { callRoute, navigate, onError }) is the islands' runtime all four use: view() for the nodes to show (elements answering events marked data-shade-on), dispatch and start for the actions (navigate checked with url before it goes, callRoute through callAccountRoute, its answer and status kept, an idempotent call's key kept until it is done, a repeating call made again through schedule (by default setTimeout), playInteraction dispatching shade:interaction, account through account (by default accountStep at accountApiBase(), which reads an email link's #confirm= or #reset= once with accountLink, takes it off the address bar and gives it only to its step, and empties the step's password fields after it); kept state read from storage, by default local storage (sessionStorage for kept: 'session', by default session storage), once the island starts, so the first view stays the server's), and connectIsland(island, wrapper, onChange) to run it there: subscribed, its events caught on the wrapper (listenIsland) and started, with what stops it all. Islands stand in a <shade-island> wrapper. On a server the default onError reports nothing (a throw there would stop the server): what fails in an island's first view is an issue of resolvePage's, with the island's key. In the browser the packages load @shadestack/render/island, the islands' runtime alone (no resolver, sanitiser or schemas; island-entry.test.ts holds what they load to a budget). Two parts are chunks of their own, fetched only on a page that uses them: callAccountRoute (@shadestack/client/account) on an island's first route call, solveChallenge (@shadestack/client/challenge, the island host's solveChallenge option) on a callRoute with challenge, and the account action's code when an island shows or runs an account step. A chunk that doesn't load fails its action like any other error: it is reported and the actions after it don't run.
  • Embeds are sanitised into elements (sanitizeEmbed): a strict allow-list with its own tokenizer; scripts, styles, iframe, object, svg, math, forms and the like go with their content; no on…, style, srcset; URLs through the scheme allow-lists; ids that would clobber the DOM and shade-/site- classes dropped. It applies the tree's nesting rules from where the embed stands, as a browser does (a link in a link unwrapped, a p closed before a block, a table's tbody and tr added), so a browser builds exactly what it gives.
  • Limits (RENDER_LIMITS): components 16 deep (one inside itself refused at once), 1,000 items per loop, 20,000 nodes and 2,000,000 characters per render, counting texts, attribute values, an embed's attributes and what client islands carry. The client islands' first views (what the server renders of them) share the page's budget: together they get what the page left of its nodes and characters. Past the depth or a loop's limit, that component or loop gives nothing; past the nodes or the characters, the whole render gives nothing (islands included) and a too-large issue.
  • Widgets a tree names by a reserved id (WIDGETS, in @shadestack/tree so a check knows them without the renderer, holds their interfaces for the tree's ComponentLookup): shade:disclosure and shade:accordion (<details>, no script), shade:dialog (a modal <dialog> with its button), shade:tabs with shade:tab, shade:menu with shade:menu-item (links), each with ARIA's pattern (until the script runs, every tab panel shows and a menu's links are a plain list, so nothing is out of reach without it), and shade:skip-link (to #main, shown when it has focus) for the top of the header part; shade:navigation, a labelled <nav> (its items slot) with a Menu button below 48rem that Escape and a click outside close, or below one of the site's breakpoints when its foldAt names it, or never with foldAt: "none" (NO_FOLD of @shadestack/styles, which no breakpoint may be called). It is written as data-shade-fold on the element; the rules are in the site's styles.css, which the website module writes with navigationFoldCss of @shadestack/render/navigation-fold for the breakpoints its live navigations name. render.css stands a navigation with data-shade-fold in a row (its button hidden) at every width, and the fold rules, more specific, fold it below its breakpoint and stack its menu there; so one set to none, or whose breakpoint has no rules, never folds and stays in a row. @shadestack/a11y warns of the second (navigation-fold); and shade:icon, a Lucide icon by name (@iconify-json/lucide), hidden from screen readers unless it has a label, in a client island only with a fixed name (its SVG travels in the island's template); and shade:year, this year as the render's (in timeZone, at now), which the visitor's browser sets to its own; shade:mode-switch, a button showing the page's light or dark mode and switching it; shade:code, a code sample (code, language) highlighted on the server with Prism's tokenizer into spans classed by kind, never in a client island; and shade:pause-motion, a button (its pauseMotion word by default) hidden until its script shows it, pressed while the page's animations are paused: a press keeps the choice (localStorage['shade-motion']) and sends shade:motion on document, which the interactions runtime follows; never in a client island; and shade:embed (category, url, title, ratio), an outside player or map behind the visitor's consent: give the render consent (the site data's categories, renderInputFor does) and it renders a notice from one of the category's hosts, which the consent runtime turns into the frame once allowed (The consent banner). The words a widget says when the editor gave none (a dialog's close button, the skip link, the navigation's name and Menu button, the mode switch, the pause control, an embed's notice) are the render's words: the site data's, in the page's language, which renderInputFor gives (The site's words). Without them such a widget is left out, with an issue. Their behaviour is defineWidgets() of @shadestack/render/dom: custom elements shade-dialog, shade-tabs, shade-menu, shade-mode-switch, shade-navigation, shade-pause-motion and shade-year, the same for every framework (each package loads it). An instance's classes go on its widget's outermost element, after the widget's own (a tab's on its tab, a menu item's on its list item). A widget names the inner elements a site may style (ComponentInterface.parts, in WIDGETS): shade:tabs list, tab, panel; shade:menu button, list, item; shade:navigation toggle, nav, content; shade:disclosure summary, content; shade:dialog button, dialog, title, close, body; shade:mode-switch and shade:pause-motion button. An instance's parts ({ tab: ['pill'] }) puts those classes on them, after the widget's own class, and the styles' states selected, expanded and current (experimental) match their aria-selected, aria-expanded and aria-current. Their buttons are 24px high at least (render.css). shade:menu takes an icon (a Lucide name) before its label, and its items may come from an Each; a shade:menu-item's language writes its link's hreflang and lang, and current its aria-current="page". The accessibility check sees a widget's own classes, its parts' classes and the labels an instance gives it, so their contrast is checked in every state. Their ids are shade:<idScope>:<n>, the scope the render's treeId unless idScope names one: resolve each part of a page (header, page, footer) with its own.
  • Code components: components a frontend registers in its own code, by name. Give their names to resolvePage as codeComponents and the components to the package's ShadeTree as code. An instance naming one resolves to a code node: its properties now (a binding evaluated), its slots' content resolved like the rest; the package renders the frontend's component there (Astro gives it node, code and context, the page's context passed along; React node and its rendered slots; Vue node and Vue slots; Svelte node, with ShadeNode for the slots). In edit mode it stands in a <shade-code> wrapper with its markers. Code components render on the server only (never in an island or a live part); a name the library has too is refused; they take no classes and their properties are plain data.
  • Head data (headData): title, description, canonical, hreflang with x-default, Open Graph and structuredData (JSON-LD objects, written by scriptJson as jsonLd, which nothing can end); absolute http(s) addresses only (an image https). Each package writes it through its framework's head API, and each JSON-LD writer (Next's ShadeJsonLd, Astro's and Svelte's ShadeHead, Nuxt's shadeHead) leaves out an entry that isScriptJson (@shadestack/render/island) refuses: one with a <, > or &, which didn't come from scriptJson.
  • Sitemap (sitemapXml(entries)): the sitemap protocol's XML with each page's other languages, every address checked, for a route of the site's own (an Astro endpoint, Next's app/sitemap.xml/route.ts, a Nuxt server route, a SvelteKit +server.ts).
  • @shadestack/render/render.css: the islands' wrappers and the widgets' few styles, in the theme's variables. Link it once.
  • @shadestack/render/dom: the browser side without a framework: defineWidgets(), mountIsland and defineIslands() (a client island patched in place, used by Astro). A renderer that writes the <shade-island> wrapper by hand writes its data after it with islandDataScript(island) from @shadestack/render, never by hand: it is scriptJson's output in the script element defineIslands reads.
  • @shadestack/render/server-islands: loadServerIslands({ base }), which fills a static page's deferred server islands in Next, Nuxt and SvelteKit from <base>/shade-island (its own chunk, loaded only by a page that has some).
  • @shadestack/render/conformance: FIXTURES (trees with the HTML every renderer must give, XSS and URL fixtures among them), fixtureResult and normalizeHtml. A renderer passes when every fixture's result (fixtureResult: its resolvePage result, or that result tampered with, for what a renderer must check again), rendered, normalises to the fixture's HTML; the core, Astro, Next, Nuxt and SvelteKit are all held to it.

Each framework package's ShadeTree renders a resolvePage result:

PackageComponentClient islandsHeadA visitor's page
@shadestack/astro/tree<ShadeTree result accountApi>their first view, their data as JSON after it, patched by <shade-island> (@shadestack/render/dom); deferred server islands with server:defer (accountApi: the site's SHADE_API_URL and SHADE_ACCOUNT_URL)<ShadeHead head> in <head>applyCacheHeaders(Astro, result) in the page's frontmatter
@shadestack/next<ShadeTree result> (a server component)ShadeClientIsland, a client component on useSyncExternalStoreshadeMetadata(head) from generateMetadata (robots as it says; meta it has no field for in other), <ShadeJsonLd head>await shadeNoStore(result) (ShadeTree warns once of a personal result it never saw)
@shadestack/nuxt<ShadeTree :result> (registered by the module)ShadeClientIsland, state in a ref, hydrated with the pageuseHead(shadeHead(head))ShadeTree sends the HTML with no-store; shadeNoStore(event, result) in the server route sends its JSON so
@shadestack/sveltekit<ShadeTree {result}>ShadeClientIsland, state in runes<ShadeHead {head} />shadeNoStore(result, setHeaders) in load (ShadeTree warns once of a personal result it never saw)

The same in every package (review rendering 7):

  • What it renders: the input of @shadestack/client/render (above), on the server.
  • code: the frontend's code components (above), as each framework writes components (Astro's get node, code and context; React's node and their slots rendered; Vue's and Svelte's node).
  • interactions: a page's interactions. Astro writes them as the page's JSON script (pageInteractionsJson) and loads the runtime in a script of its own; Next, Nuxt and SvelteKit load the runtime once the page is mounted, only for a page that has some (hasPageInteractions, @shadestack/interactions/present), and give it the interactions as data, again with the next page's when the framework keeps the page's component. All four start it the same way (bootPageInteractions), which also plays what an island's playInteraction asks for: the island's shade:interaction event, with its tree and the element whose action ran, reaches the runtime's play().
  • Islands: each runs its client islands through connectIsland (@shadestack/render/island).
  • Issues: each tells a result's issues on the server, once per issue (reportRenderIssues, issueText).
  • A page by its path: findPage(client, …) and shadeFromEnv(env) (@shadestack/client/render's; SvelteKit takes the rest route's path as one string).
  • Deferred server islands: Astro's are server:defer's; Next, Nuxt and SvelteKit seal them into their placeholders and fill them from the site's island route (below). On a page rendered per request, all four can instead give the visitor to resolvePage.

None of them sets HTML from a string but an icon's SVG, and only once isIconSvg says it is the icon set's own (its start tag and Lucide's shapes, nothing that links, runs or styles); structured data, scriptJson's output, is a script's text as it is. Each checks every tag and attribute name again (isWritableTag, which also refuses script, style, iframe, object and embed, and writableAttributes) and leaves out what fails, an icon that isn't the set's too, and keys each client island by its key, so new data (the next page of a route, a refresh) makes a new island. The conformance suite holds them to it with a result tampered with (fixtureResult).

Code, in shade-frontend: packages/render/src/ (resolve.ts, properties.ts, richtext.ts, template.ts, island.ts and island-entry.ts, sanitize.ts and tokenize.ts, attributes.ts, names.ts, widgets.ts, head.ts, sitemap.ts, defer.ts and seal.ts, dom/, conformance/), and each package's tree files. Tests: packages/render/test/*.test.ts, the conformance suite in each package (packages/next/test/tree.test.tsx, packages/nuxt/test/tree.test.ts, packages/sveltekit/test/tree.test.ts, packages/astro/test/tree/tree.test.ts), the widgets and the DOM runtime in a real browser (e2e/tests/render-dom.spec.ts), and one island page hydrated by React, Vue, Svelte and the DOM runtime in a real browser (e2e/tests/render-frameworks.spec.ts, built from the packages' sources by e2e/render-bundles.ts). These browser tests need no SHADE instance: they are in shade-frontend's e2e/, with its own Playwright.

Deferred server islands

A statically built page shows its server islands ("Welcome back, Sam", a cart count, "My bookings") per visitor in every framework. Astro renders them with server:defer (ShadeTree with accountApi). Next, Nuxt and SvelteKit do the same in three steps:

  1. Resolve the page with serverIslands: 'defer' (renderPublishedPage(page, context, { deferIslands: true })), then seal it on the server: await deferServerIslands(result) (SvelteKit: deferServerIslands(result, env)). Each island becomes an empty <shade-island data-shade-defer="…"> holding its payload sealed with the site's secret. Render that result with ShadeTree; it may go through the framework's page data.
  2. Add the island route, GET /shade-island on the site's own origin, under its base path if it has one (the setup per framework is in the frameworks' pages).
  3. ShadeTree loads @shadestack/render/server-islands once the page is mounted, on a page that has deferred islands. It asks the route once per island, with the visitor's sign-in cookie, and puts the answer in the island.

A site under a base path has its island route there too: ShadeTree tells the loader the base, and it asks <base>/shade-island. Nuxt (app.baseURL) and SvelteKit (paths.base) give it on their own; in Next, pass the basePath of next.config to ShadeTree (<ShadeTree result={result} basePath="/docs" />; default none).

Set SHADE_ISLAND_SECRET (at least 32 characters, made with openssl rand -base64 48) in the build's environment and the server's, the same in both. SHADE_API_URL (or SHADE_ACCOUNT_URL when the account API has its own address) tells the route where to ask who is signed in. The account API must be on the site's origin for the cookie to come along, as for every visitor route (accounts).

How it holds:

  • Sealed, not signed. A payload holds both branches of a condition on the visitor (what a signed-in visitor sees, and what nobody does), so it is encrypted with AES-256-GCM (Web Crypto; the key derived from the secret with HKDF-SHA-256). Nobody can read it in the page or change it: the route refuses a payload that doesn't open. Changing the secret refuses every earlier page's islands until the next build.
  • Bounded. A sealed payload is at most 8,000 characters (SERVER_ISLAND_TOKEN_LIMIT), since it travels in the address. A larger island stays empty, for nobody, with a too-large issue in the build's log.
  • Deny by default. The route answers GET only (405 otherwise), refuses a request whose Sec-Fetch-Site is not same-origin (403) and a payload missing, too long or changed (400), always with an empty body. Its answer is the island's HTML (the core's toHtml) with Cache-Control: private, no-store. A render that fails answers an empty 500; the reason is only in the server's log.
  • Same origin. The base path comes from the framework's own setting, never from the page or its tree. The loader refuses, before asking anything, a base that isn't empty or a path starting with / (no //, \, scheme, query or fragment).
  • For a year. A seal carries when it was made, and the route refuses one older than a year (SERVER_ISLAND_MAX_AGE), so a token copied from a page stops working in time. Build a static page again within a year, or its islands stay empty, for nobody.
  • Only what it reads. The visitor is the account API's session for the request's shade_account.* cookies (the site's others stay with the site), projected to the fields the island reads (name, email, signedIn); nobody without a session, or when the API can't say within 3 seconds.
  • Accessible. Until it is filled, and when the request fails, the island is an empty wrapper, as Astro's fallback: nothing is announced, and filling it announces nothing either. Calling loadServerIslands again asks again for an island whose request failed.

The functions are sealServerIslands(result, secret) and openServerIsland(token, secret, maxAge?) (@shadestack/render), answerServerIsland(request, options) and serverIslandRoute(env) (@shadestack/client/render), and loadServerIslands({ base }). The conformance suite's DEFERRED_FIXTURES hold the core and the three packages to the same placeholders and the same answers for a signed-in visitor and for nobody, and to refusing a changed payload; e2e/tests/render-deferred.spec.ts fills an island with React, Vue and Svelte in a real browser, at the root and under a base path.

The website editor's canvas

The website editor edits a page over the frontend itself. A frontend that supports it has two routes:

  • The edit route (/preview/canvas?token=… on SHADE's site): reads the draft with the preview token (shade.canvas(token), the website module's /api/v1/content/website/canvas: the page and its stored node tree), renders the tree with resolvePage({ …, edit: true }) in the site's layout, sends canvasHeaders(adminOrigin) (no-store, noindex, no-referrer, so the address with its token goes nowhere, and frame-ancestors for the admin) and starts connectCanvas in the browser.
  • The render route (POST /preview/canvas/render): readCanvasRequest(request) (same host, at most 2 MB, a token and a tree; else the response to answer with), then the same render without the layout: what goes inside <main>.
import { connectCanvas } from '@shadestack/client/canvas'

connectCanvas({
  adminOrigin, // the only origin the canvas listens to and answers (of an address, only its origin counts)
  async render(body) { // { token, tree }: the editor's draft
    const response = await fetch('/preview/canvas/render', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
    if (response.status === 401) return { error: 'expired' }
    return response.ok ? { html: await response.text() } : { error: 'failed' }
  }
})

The admin owns the tree: it sends the whole draft once (tree), then each change as tree operations (patch) on the revision the canvas has; the canvas applies them with @shadestack/tree's operations (applyEditorMessage in @shadestack/client/canvas), asks for the tree again when it can't (resync), renders one draft at a time (the newest wins) and swaps in the top-level nodes that changed. It outlines the selected and hovered nodes (a display: contents wrapper is measured by its children), selects the outermost component instance around a click, asks for the element menu on a right-click (contextmenu with the point; Shift keeps the browser's menu), stops links and forms, sets the colour mode (data-shade-mode on <html>) and scrolls to a node on request. The messages are EditorToCanvasMessage and CanvasToEditorMessage (@shadestack/tree/canvas, with CANVAS_PROTOCOL_VERSION; core and the module SDK don't have them), version 2 of the canvas protocol, with its origin rules. The theme screen uses the canvas too: it sends the home page's tree and, as styles, the theme with the site's styles.

The canvas writes no inline styles: its outlines' CSS and the editor's styles go into constructed style sheets (CSSStyleSheet with replaceSync, in document.adoptedStyleSheets), which a Content-Security-Policy's style-src doesn't restrict. Nor does it need 'unsafe-eval': @shadestack/client/canvas first imports @shadestack/tree/jitless, which runs zod without compiled parsers in the browser, so the tree's schemas never try new Function, in every framework. The edit route's policy can name its <style> blocks by hash and leave out 'unsafe-inline' (SHADE's site: previewPolicy). The page's own <style data-shade-styles> draws the first paint; the first styles message removes it once the adopted sheet holds the styles. Adopted sheets come after the page's own style sheets, so the editor's styles come after the saved theme.

SHADE's site: src/pages/preview/canvas.astro, src/pages/preview/canvas/render.astro, src/lib/canvas.ts, src/scripts/canvas.ts. Code, in shade-frontend: packages/client/src/canvas.ts, packages/tree/src/canvas.ts (@shadestack/tree/canvas). Tests: packages/client/test/canvas.test.ts, and the website module's e2e/site/canvas.spec.ts on the built site.

Details

  • A formula that can't give its value when a page is rendered shows nothing in its place, and the problem is reported without the data in it (the report never carries the page's or visitor's values).