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/tree`

The website editor's page tree. Framework-free, with zod and @shadestack/expressions as its only dependencies, and not a site package itself: the expressions, styles, the rendering core and the four renderers, interactions, the accessibility checker and the editor build on its types. The website module keeps a page's tree in a json field and checks it itself (website:tree: readTree with the site's languages, its component library, its embed permission, the editor roles and the media types each place takes), and the content API gives it to sites as page.tree. asNodeTree(stored) reads a stored value as a tree for showing it (an older version migrated, anything else an empty tree), and isNodeTree says whether a value has a tree's shape.

A stored tree is { version, nodes }. Eight node types; the first seven match what a developer writes in code:

NodeIsIn code
elementan allow-listed tag with allow-listed attributes, style classes and children<section class="…">
textplain text, per language, escaped when renderedWelcome
componentan instance of a component (a library's card, a module's shop.offer, or one of SHADE's widgets, shade:dialog): its properties and its slots' nodes<Card title="…"><p>…</p></Card>
ifa condition with a then and an else branch{#if}…{:else}…{/if}
eacha loop over a list or a data source, with an item name, an optional index name and a key{#each items as product (product.id)}
slotwhere an instance's content goes, in a component's own tree<slot name="…">
islandrendered per visitor on the server (server), or hydrated with state (client)server:defer, client:load
embedraw HTML, behind its own permission, sanitised into elements by the rendering core{@html …}
import { insertNode, readTree, validateTree, diffTrees, type NodeTree } from '@shadestack/tree'

const tree: NodeTree = {
  version: 2,
  nodes: [{
    id: 'intro', type: 'element', tag: 'section',
    children: [
      { id: 'title', type: 'element', tag: 'h1', children: [
        { id: 'title-text', type: 'text', value: { kind: 'binding', expression: { type: 'path', root: 'entry', keys: ['title'] } } }
      ] },
      { id: 'lead', type: 'element', tag: 'p', children: [
        { id: 'lead-text', type: 'text', value: { kind: 'literal', value: { nl: 'Welkom', en: 'Welcome' } } }
      ] }
    ]
  }]
}

const result = validateTree(tree, {
  languages: { default: 'nl', others: ['en'] },
  components: name => library[name], // what an instance is checked against
  expressions: createExpressionChecker({ entry: entryType, site: siteType }), // types every name in scope
  embeds: user.mayEmbed // the permission to save raw HTML embeds
})
if (!result.ok) console.log(result.issues) // [{ code, path, nodeId, message }]
  • Values are tagged: { kind: 'literal', value } or { kind: 'binding', expression }. Text, and every translatable attribute or property, is per language: { nl: '…', en: '…' }. An image's src is a media library image, { mediaId }, which the renderer resolves to its address (or an address on the site). A link's href is an address or a page by id, { kind: 'entry', collection, id, anchor? } (EntryLink, a url attribute with entries in html.ts), which the renderer resolves to that page's address in the page's language through links, as navigation links are; one without an address there is left out and reported. Ids, names, enums and tokens are literal only, except an enum marked bindable (aria-current, isBindable, bindingType), whose binding gives text held to its values when rendered, and the name of an input, select or textarea, so a form's controls can be drawn from data (the forms module's Form starter names each by its field's key). A bound control name is checked when rendered (isBoundNameAllowed): lowercase letters, digits and dashes (BOUND_NAME) and never a property of the page or a form, such as action or submit (DOM clobbering); any other leaves the name out, so the control sends nothing, and is reported. A form's, a fieldset's and an output's name, and every type and id, stay literal. The only roles a tree sets are a live region's, role="status" or role="alert", on a div, p, span or section.
  • Expressions are @shadestack/expressions' AST. validateTree decides where a binding may stand, what type it must give there and which names are in scope (entry and site everywhere, visitor only inside a server island, state only inside a client island, props only in a component's own tree, event only in an event's actions, and each enclosing Each's item and index), and passes that to the expressions checker. createExpressionChecker(environment) is that checker: give it the types of the entry, the site, the visitor's projection, a component's properties (propertyTypes(interface.props)), the data sources' items (sources) and the site's translation keys; what it has no type for can't be read. Each place accepts what EXPECTED says (a text shows nothing for an empty value, a condition must decide; a text node may show rich text, content; a URL place takes a link or a media library image too, resolved to its address when rendered), and an issue's path points into the expression (nodes.0.value.expression.args.0). A checker is told the place (ExpressionPlace): what it expects, the scope, for a URL its schemes, and for setState the state's exact type. A bound URL's texts that are known when the tree is saved (a literal, a ternary's or a ??'s literal branch, a literal start such as 'javascript:' + x) go through the attribute's allow-list then (knownUrlProblem; more than 64 such texts and the binding is refused, never checked in part); the rest is checked when it is shown (the runtime's url). Each loop's item is typed once, where its Each stands (ScopeItem.scope), so checking is linear in the tree's size, and a tree's expressions may hold at most maxExpressionParts parts together (default 50,000). Without a checker every binding is refused; without components every component instance is; without embeds: true every embed is.
  • Events and actions: an element inside a client island may answer events (click, submit, change, input, keydown narrowed to a key, load), each with actions run in order: setState, toggleState, navigate (the link scheme allow-list), submitForm (a form of the island, by id), callRoute (a module's public or account route, through callAccountRoute at SHADE's account API (accountApiBase, the page's shade-account-api address), with values in its body and its address and maybe a form of the island, its answer kept in an answer state of that route and how it went in a text state; challenge solves the module's proof of work first and sends it as altcha), playInteraction, and account (a step of SHADE's own account routes, ACCOUNT_STEPS: how it went in a text state, ACCOUNT_STATUSES, and who is signed in in an account state of name and email; only session runs on load; a step with a form sends its fields by the names ACCOUNT_FIELDS gives). A password field (type="password") stands only in a form of a client island, takes no events, and its form goes only to account, never callRoute; the renderer writes that form with method="post". Text, number and on/off state may be kept in the visitor's browser, shared by every island of the site with a kept state of that name. A text state may have a fixed set of options (2–16 lower-case names such as site or all-plugins) and a number a range ({ min, max }); styles read them through the island's wrapper (see Expressions and styles), so neither may be kept, the first value is one of the options or inside the range, and a setState with a literal outside the options is refused when saving (a computed one at run time, like a value of another type). The runtime writes the options' values as data-shade-state="picked:site" on <shade-island>, already in the first view, and each number kept to its range as --shade-value-<name> once the island runs, at most once a frame. Events stand only inside client islands and on elements that answer them, in validateTree and the operations alike; validateTree checks actions against the island's state and forms, visitorRoutes(plugin, method, route) and interactions(id), and refuses every route call and interaction without those lookups. setState takes exactly the state's type (never nothing, a list's items of its type, never a data source); a bound navigate target is never nothing, its known texts are checked when saved and the islands' runtime checks what it gives with url before going. load runs without the visitor doing anything, so it takes only LOAD_ACTIONS: set or toggle state, play an interaction, or a GET route call; never navigate, submitForm or a route call that changes something.
  • Loops over data sources: an Each's source is a data source written in the tree ({ kind: 'literal', value: { source: 'collection:posts', parameters: { order: 'newest', limit: 6 } } }), whose items the renderer fetches on the server, or a binding that gives a list or a source. A component property of type source holds a data source, so an Each in the component's tree can loop over props.feed: a source counts as a list (acceptsValue).
  • What validateTree refuses: tags off the allow-list (script, style, iframe, svg, object, template…), attributes a tag doesn't take, every on* attribute, style, a form's action, URLs outside the scheme allow-lists (urls.ts: links http, https, mailto, tel; audio, video, tracks and posters https; relative paths; whitespace, control characters and backslashes refused), images from another host, ids and form names that are a property of the document, a form or the window (submit, action, cookie, name…: DOM clobbering), names such as constructor or toString, an interactive element inside another (also in a summary), flow content where only phrasing may stand, misplaced list items, table rows (only in thead, tbody, tfoot), table cells, dt and dd, and options, islands where only some tags or only text may stand, children in void elements, duplicate ids, locks on fields a node doesn't have, oversized or too deep input (checked before parsing) and __proto__ keys.
  • Components are seen through, both ways. An instance counts as the tag it renders as, with the tags, the interactive content, the islands and the embeds it holds (a card holding a link can't stand in a link, a component holding an island not in an island, one holding an embed not in a form), and the nodes in one of its slots are checked where that slot stands in the component's own tree (no link in a link component's slot). describeComponent(componentTree, { components }) computes that part of a component's interface (root, phrasing, interactive, tags, islands, embeds, and per slot content, parentTag, forbidden, noInteractive, island); the library stores it with the component, a code component declares it.
  • A component as data is a ComponentDefinition (its tree, properties, slots, variants, default variant and defaults), whoever keeps it; validateComponent(definition, { name, languages, components, types, visitorRoutes, forms }) checks one without a database (properties, defaults, variants' classes, its tree as a component's, its slots placed once, no instance of itself), and instancesIn and placedSlots read a tree. The website module's library and its SDK's checkComponent (@shadestack/module-website/sdk/testing) use it; @shadestack/render's LibraryComponent is made from it. @shadestack/tree/build builds trees in code (el, words, show, when, each, slot, use).
  • Embeds hold raw HTML: at most 20,000 characters, refused when they contain <script, an on…= attribute, a javascript:/vbscript: URL (also with a tab or newline in the scheme, or written with character references such as &#x61;) or srcdoc (a first check, not a sanitiser), and every renderer sanitises them before output. They stand only where flow content may, outside links, buttons and forms.
  • Locks (for the editor's roles): any node may carry locks: { structure, properties, styles }, the properties by the field names diffTrees reports (tag, attributes.href, props.title, value). The tree checks their shape; the website module's content check enforces them when saving: editProblems(before, after, role) in rights.ts says what a builder or content editor changed beyond their role or past a lock, each problem with a code (RIGHTS_PROBLEMS), and mayChangeField, mayAddTo and mayMoveOrRemove answer an editor's questions per node. The website module's roles are website.pages.design and website.pages.build.
  • Renderers check bound URLs again when they are known, with the runtime's url(value, schemes) (or the same safeUrl(value, schemes), from @shadestack/expressions): the rules are @shadestack/expressions' (urls.ts), and the tree re-exports the scheme lists and urlProblem.
  • Schema versions: readTree(stored, options) migrates a tree of any earlier version (migrateTree, MIGRATIONS) and validates it. Raising SCHEMA_VERSION without a migration fails the package's tests. Version 2 stores expressions as their AST, parsed from version 1's { expr } placeholders; one that doesn't parse, or isn't exactly { expr: '<formula>' }, stops the migration with its reason and where.
  • Operations: insertNode, moveNode, removeNode, duplicateNode, updateNode return a new tree and share untouched subtrees; they throw TreeOperationError with a code for what the nesting rules refuse, the same rules validateTree applies (nesting.ts). A node they are given is checked for size before its schema reads it (too-large, structure), and maxNodes/maxDepth in their rules refuse an insert, move or duplicate past them. Every walk is iterative, so no tree is too deep for them. A position is { parentId, list, index }, where list is children, then, else, empty, fallback or slot:<name>.
  • Comparison: diffTrees(before, after) lists nodes added, removed, moved and changed, with the changed fields (attributes.href, props.title, value.nl, locks.structure). summarizeChanges(before, after, locale?) is that for a person: a removed or added subtree once, each node with its tag or component and first words, at most 200 changes (more counts the rest).

Code, in shade-frontend: packages/tree/src/. Tests: packages/tree/test/*.test.ts.