json-renderer 0.0.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
- The MIT License (MIT)
1
+ MIT License
2
2
 
3
- Copyright (c) 2022 Dan Lynch <pyramation@gmail.com>
3
+ Copyright (c) 2026 Constructive
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1 +1,127 @@
1
- # json-renderer
1
+ # json-renderer
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/blocks/actions/workflows/ci.yml">
9
+ <img height="20" src="https://github.com/constructive-io/blocks/actions/workflows/ci.yml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/blocks/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/json-renderer"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/blocks?filename=packages%2Fjson-renderer%2Fpackage.json"/></a>
13
+ </p>
14
+
15
+ The framework-agnostic core of a declarative JSON UI document: the document
16
+ envelope and node tree, runtime validation, JSON Schema export, composition
17
+ (fragments, slots, per-node overrides, merge), binding resolution, and the
18
+ **adapter contract** a renderer implements.
19
+
20
+ No React, no component library, and no node vocabulary of its own — a document
21
+ names whatever node types its registry can satisfy. `blocks-schema` is the
22
+ Constructive vocabulary over this core, and `blocks-renderer` is its React
23
+ adapter.
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ pnpm add json-renderer
29
+ ```
30
+
31
+ Built with `makage` and published from `dist`, so every module is a root-level
32
+ entry point and deep imports need no exports map:
33
+
34
+ ```ts
35
+ import { createEnvelope, parseEnvelope } from 'json-renderer';
36
+ import { composeEnvelope } from 'json-renderer/compose';
37
+ import { resolveBinding } from 'json-renderer/bindings';
38
+ ```
39
+
40
+ ## Overview
41
+
42
+ | Layer | Purpose | File |
43
+ |-------|---------|------|
44
+ | **Envelope** | `DocumentEnvelope` container (`formatVersion`, `type`, `id`, `page`) | `envelope.ts` |
45
+ | **Nodes** | Recursive `DocumentNode` tree, traversal and mapping | `node.ts` |
46
+ | **Validation** | Zod schema factories for the envelope and node tree | `zod.ts` |
47
+ | **Constraints** | Framework-free field constraint checking | `constraints.ts` |
48
+ | **Fields** | Field name, default value, and constraint collection | `fields.ts` |
49
+ | **JSON Schema** | Exported JSON Schema of the format, for agents and tooling | `json-schema.ts` |
50
+ | **Compose** | Fragment expansion, slot filling, overrides, merge | `compose.ts` |
51
+ | **Bindings** | `{{ scope.path }}` resolution and scope layering | `bindings.ts` |
52
+ | **Registry** | Layered node type → handler resolution | `registry.ts` |
53
+ | **Adapter** | The interface a renderer implements | `adapter.ts` |
54
+
55
+ ## Document
56
+
57
+ ```json
58
+ {
59
+ "formatVersion": "1.0",
60
+ "type": "UISchema",
61
+ "id": "orders-form",
62
+ "meta": { "title": "Orders" },
63
+ "page": { "type": "Page", "key": "page", "props": {}, "children": [] }
64
+ }
65
+ ```
66
+
67
+ A node is `{ type, key, props, children, bindings?, actions? }`. `type` is any
68
+ string: unknown types are valid documents, because resolution happens at render
69
+ time and an adapter must render a visible fallback rather than throw.
70
+
71
+ `DocumentNode` and `DocumentEnvelope` are generic over the vocabulary, so a
72
+ format narrows them without redeclaring the tree:
73
+
74
+ ```ts
75
+ type UINode = DocumentNode<UINodeType, UINodeProps>;
76
+ type UIDocument = DocumentEnvelope<UINode, 'UISchema', '1.0'>;
77
+ ```
78
+
79
+ ## Composition
80
+
81
+ ```ts
82
+ const composed = composeEnvelope(document, {
83
+ fragments: { address: addressSubtree },
84
+ slots: { header: customHeaderNode },
85
+ overrides: { title: { props: { label: 'Headline' } }, legacy: { remove: true } },
86
+ });
87
+ ```
88
+
89
+ Composition is pure and never mutates its input. An unresolved fragment stays in
90
+ the tree so the renderer surfaces the gap. A vocabulary that spells its
91
+ indirection nodes differently configures `vocabulary` instead of forking
92
+ composition:
93
+
94
+ ```ts
95
+ composeEnvelope(document, { fragments, vocabulary: { fragmentNodeType: 'include' } });
96
+ ```
97
+
98
+ ## Adapter contract
99
+
100
+ A renderer is generic over the handler it resolves a node type to (`THandler`)
101
+ and the output it produces (`TOutput`), and owes three answers:
102
+
103
+ 1. **Registry resolution** — node type → handler, layered with `composeRegistry`
104
+ so a host adds or replaces node types without forking the renderer.
105
+ 2. **Binding scope access** — the scope a node's bindings resolve against.
106
+ 3. **Unknown-node handling** — `UnknownNodePolicy`; the default is a visible
107
+ placeholder, never a thrown render.
108
+
109
+ ```ts
110
+ import type { RendererAdapter } from 'json-renderer';
111
+
112
+ const stringAdapter: RendererAdapter<(props: NodeProps) => string, string> = {
113
+ name: 'example/string',
114
+ resolve: (type, context) => resolveNode(context.registry, type),
115
+ resolveProps: (node, context) => resolveNodeProps(node, context.scope),
116
+ renderNode: (node, context) => { /* ... */ },
117
+ renderUnknown: (node) => `<!-- unknown: ${node.type} -->`,
118
+ renderDocument: (document, context) => { /* ... */ },
119
+ };
120
+ ```
121
+
122
+ `blocks-renderer` is the reference implementation (React + shadcn); its
123
+ `reactAdapter` export states the contract its components satisfy.
124
+
125
+ ## License
126
+
127
+ MIT
package/adapter.d.ts ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The adapter contract.
3
+ *
4
+ * `json-renderer` never renders anything: it defines the document, and the
5
+ * interface a renderer implements to turn that document into output. An adapter
6
+ * is generic over two things — the handler it resolves a node type to
7
+ * (`THandler`: a React component, a string template, a serializer) and the output
8
+ * it produces (`TOutput`: a React element, a string, a DOM node).
9
+ *
10
+ * An adapter owes three answers:
11
+ *
12
+ * 1. **Registry resolution** — node type → handler, layered (see
13
+ * {@link composeRegistry}).
14
+ * 2. **Binding scope access** — the scope a node's bindings resolve against, and
15
+ * how scope is layered for nested content.
16
+ * 3. **Unknown-node handling** — what happens when no layer satisfies a type.
17
+ * A document may name nodes a given host has not installed, so the default is
18
+ * a visible placeholder, never a thrown render.
19
+ *
20
+ * `blocks-renderer` is the reference implementation (React + shadcn).
21
+ */
22
+ import type { BindingScope } from './bindings';
23
+ import type { AnyDocumentEnvelope } from './envelope';
24
+ import type { AnyDocumentNode, NodeAction, NodeProps } from './node';
25
+ import type { NodeRegistry } from './registry';
26
+ /** How an adapter treats a node type no registry layer satisfies. */
27
+ export type UnknownNodePolicy = 'fallback' | 'omit' | 'throw';
28
+ /** Resolution outcome for one node type. */
29
+ export type NodeResolution<THandler> = {
30
+ status: 'resolved';
31
+ type: string;
32
+ handler: THandler;
33
+ } | {
34
+ status: 'unknown';
35
+ type: string;
36
+ };
37
+ export declare function resolveNode<THandler>(registry: NodeRegistry<THandler>, type: string): NodeResolution<THandler>;
38
+ /**
39
+ * Everything an adapter needs while walking one document. A React adapter puts
40
+ * this in context; a string adapter threads it through its recursion.
41
+ */
42
+ export interface RenderContextBase<THandler, TDocument extends AnyDocumentEnvelope = AnyDocumentEnvelope> {
43
+ document: TDocument;
44
+ registry: NodeRegistry<THandler>;
45
+ /** Scope for binding expressions (`{{ row.title }}`). */
46
+ scope: BindingScope;
47
+ unknownNodePolicy?: UnknownNodePolicy;
48
+ }
49
+ /**
50
+ * The context plus action dispatch. `TAction` lets a vocabulary narrow its
51
+ * action union (`blocks-schema`'s `UIAction`) without restating the context.
52
+ */
53
+ export interface RenderContext<THandler, TDocument extends AnyDocumentEnvelope = AnyDocumentEnvelope, TAction extends NodeAction = NodeAction> extends RenderContextBase<THandler, TDocument> {
54
+ /** Declarative actions are dispatched to the host, never executed here. */
55
+ onAction?: (action: TAction, event: string) => void;
56
+ }
57
+ /** Props an adapter hands a resolved handler: the node plus its resolved props. */
58
+ export interface NodeRenderInput<TOutput> {
59
+ node: AnyDocumentNode;
60
+ props: NodeProps;
61
+ children?: TOutput;
62
+ }
63
+ /**
64
+ * The interface a renderer implements. Methods are the contract, not a base
65
+ * class: adapters are free to be a single function, a class, or a React tree.
66
+ */
67
+ export interface RendererAdapter<THandler, TOutput, TDocument extends AnyDocumentEnvelope = AnyDocumentEnvelope, TContext extends RenderContextBase<THandler, TDocument> = RenderContext<THandler, TDocument>> {
68
+ /** Adapter identity, for diagnostics: e.g. `blocks-renderer/react`. */
69
+ readonly name: string;
70
+ /** Node type → handler, after layering. */
71
+ resolve(type: string, context: TContext): NodeResolution<THandler>;
72
+ /** Resolve a node's bindings against the context scope. */
73
+ resolveProps(node: AnyDocumentNode, context: TContext): NodeProps;
74
+ /** Render one node (and, recursively, its children). */
75
+ renderNode(node: AnyDocumentNode, context: TContext): TOutput;
76
+ /** Render the placeholder for an unsatisfied node type. */
77
+ renderUnknown(node: AnyDocumentNode, context: TContext): TOutput;
78
+ /** Render a whole document. */
79
+ renderDocument(document: TDocument, context: TContext): TOutput;
80
+ }
81
+ /**
82
+ * A field-value store an adapter exposes to interactive nodes. Kept in the core
83
+ * so form semantics (value, error, validate-on-change) are one contract across
84
+ * adapters instead of per-framework inventions.
85
+ */
86
+ export interface FieldStateAccess {
87
+ getValue(name: string): unknown;
88
+ setValue(name: string, value: unknown): void;
89
+ getError(name: string): string | undefined;
90
+ setError(name: string, error: string | null): void;
91
+ }
package/adapter.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveNode = resolveNode;
4
+ function resolveNode(registry, type) {
5
+ const handler = registry[type];
6
+ return handler === undefined ? { status: 'unknown', type } : { status: 'resolved', type, handler };
7
+ }
package/bindings.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Binding and scope resolution. A binding is a template expression over a scope
3
+ * object; resolution is pure string/object work, so it runs in a renderer, in an
4
+ * SSR pass, or in a validator with no framework present.
5
+ */
6
+ import type { AnyDocumentNode, NodeProps } from './node';
7
+ /** The data a document's expressions read from, e.g. `{ row, user, values }`. */
8
+ export interface BindingScope {
9
+ [key: string]: unknown;
10
+ }
11
+ /** Read a dotted path (`row.author.name`) out of a scope object. */
12
+ export declare function readPath(scope: BindingScope, path: string): unknown;
13
+ /**
14
+ * Resolve a binding expression. A template that is exactly one placeholder
15
+ * yields the raw value (so a boolean or an object survives); a template mixed
16
+ * with text is interpolated as a string.
17
+ */
18
+ export declare function resolveBinding(expression: string, scope: BindingScope): unknown;
19
+ /** Apply a node's `bindings` over its static props. */
20
+ export declare function resolveNodeProps<TProps extends NodeProps = NodeProps>(node: AnyDocumentNode, scope: BindingScope): TProps;
21
+ /**
22
+ * Layer scopes left-to-right, later layers winning. Scope layering is how a
23
+ * renderer adds row/item context inside a repeating node without rebuilding the
24
+ * document's scope.
25
+ */
26
+ export declare function composeScope(...layers: (BindingScope | undefined)[]): BindingScope;
package/bindings.js ADDED
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readPath = readPath;
4
+ exports.resolveBinding = resolveBinding;
5
+ exports.resolveNodeProps = resolveNodeProps;
6
+ exports.composeScope = composeScope;
7
+ const TEMPLATE = /\{\{\s*([^}\s]+)\s*\}\}/g;
8
+ /** Read a dotted path (`row.author.name`) out of a scope object. */
9
+ function readPath(scope, path) {
10
+ let current = scope;
11
+ for (const segment of path.split('.')) {
12
+ if (current == null || typeof current !== 'object')
13
+ return undefined;
14
+ current = current[segment];
15
+ }
16
+ return current;
17
+ }
18
+ /**
19
+ * Resolve a binding expression. A template that is exactly one placeholder
20
+ * yields the raw value (so a boolean or an object survives); a template mixed
21
+ * with text is interpolated as a string.
22
+ */
23
+ function resolveBinding(expression, scope) {
24
+ const single = expression.match(/^\{\{\s*([^}\s]+)\s*\}\}$/);
25
+ if (single) {
26
+ return readPath(scope, single[1]);
27
+ }
28
+ return expression.replace(TEMPLATE, (_match, path) => {
29
+ const value = readPath(scope, path);
30
+ return value == null ? '' : String(value);
31
+ });
32
+ }
33
+ /** Apply a node's `bindings` over its static props. */
34
+ function resolveNodeProps(node, scope) {
35
+ if (!node.bindings)
36
+ return (node.props ?? {});
37
+ const resolved = { ...(node.props ?? {}) };
38
+ for (const [prop, expression] of Object.entries(node.bindings)) {
39
+ resolved[prop] = resolveBinding(expression, scope);
40
+ }
41
+ return resolved;
42
+ }
43
+ /**
44
+ * Layer scopes left-to-right, later layers winning. Scope layering is how a
45
+ * renderer adds row/item context inside a repeating node without rebuilding the
46
+ * document's scope.
47
+ */
48
+ function composeScope(...layers) {
49
+ const composed = {};
50
+ for (const layer of layers) {
51
+ if (!layer)
52
+ continue;
53
+ Object.assign(composed, layer);
54
+ }
55
+ return composed;
56
+ }
package/compose.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Composition ops: fragment expansion, slot filling, per-node overrides, and
3
+ * document merge. Pure JSON in, pure JSON out — nothing here needs a renderer,
4
+ * so a generated document can be customized on a server before it ships.
5
+ */
6
+ import type { AnyDocumentEnvelope } from './envelope';
7
+ import type { AnyDocumentNode, NodeActions, NodeBindings, NodeProps } from './node';
8
+ /**
9
+ * A patch applied to the node with a given `key`. Composition is per node, not
10
+ * per document, so a generated default can be customized in a few places
11
+ * without giving up generation.
12
+ */
13
+ export interface NodeOverride<TType extends string = string, TProps extends NodeProps = NodeProps> {
14
+ type?: TType;
15
+ props?: TProps;
16
+ bindings?: NodeBindings;
17
+ actions?: NodeActions;
18
+ /** Drop the node (and its subtree) from the composed document. */
19
+ remove?: boolean;
20
+ }
21
+ export type NodeOverrides<TType extends string = string, TProps extends NodeProps = NodeProps> = Record<string, NodeOverride<TType, TProps>>;
22
+ /** Reusable subtrees addressed by fragment nodes. */
23
+ export type FragmentMap<TNode extends AnyDocumentNode = AnyDocumentNode> = Record<string, TNode>;
24
+ /** Subtrees that fill slot nodes, addressed by slot name. */
25
+ export type SlotMap<TNode extends AnyDocumentNode = AnyDocumentNode> = Record<string, TNode | TNode[]>;
26
+ /**
27
+ * Which node types and props carry composition. A vocabulary that spells its
28
+ * indirection nodes differently (`include`/`outlet`) configures them here rather
29
+ * than forking composition.
30
+ */
31
+ export interface ComposeVocabulary {
32
+ fragmentNodeType: string;
33
+ slotNodeType: string;
34
+ /** Prop on a fragment node naming the fragment to expand. */
35
+ fragmentRefProp: string;
36
+ /** Prop on a slot node naming the slot to fill. */
37
+ slotNameProp: string;
38
+ }
39
+ export declare const DEFAULT_COMPOSE_VOCABULARY: ComposeVocabulary;
40
+ export interface ComposeOptions<TNode extends AnyDocumentNode = AnyDocumentNode> {
41
+ fragments?: FragmentMap<TNode>;
42
+ slots?: SlotMap<TNode>;
43
+ overrides?: NodeOverrides<string, NodeProps>;
44
+ vocabulary?: Partial<ComposeVocabulary>;
45
+ }
46
+ /**
47
+ * Compose a document: expand fragment references, fill slots, then apply
48
+ * per-node overrides. Pure — the input document is never mutated.
49
+ */
50
+ export declare function composeEnvelope<TEnvelope extends AnyDocumentEnvelope>(document: TEnvelope, options?: ComposeOptions<TEnvelope['page']>): TEnvelope;
51
+ export declare function composeNodeTree<TNode extends AnyDocumentNode>(node: TNode, options?: ComposeOptions<TNode>): TNode;
52
+ /**
53
+ * Merge an overlay tree onto a base tree by node `key`: matching nodes have
54
+ * their props, bindings, and actions shallow-merged (overlay wins) and their
55
+ * children merged recursively; overlay children with no match are appended.
56
+ * This is the "hand-authored beats generated, at the node level" rule.
57
+ */
58
+ export declare function mergeNodeTrees<TNode extends AnyDocumentNode>(base: TNode, overlay: TNode): TNode;
59
+ /**
60
+ * Merge an overlay document onto a base document: envelope identity comes from
61
+ * the overlay when set, `meta` is shallow-merged, `registries` and `dataSources`
62
+ * are merged by name, and the page trees are merged by node key.
63
+ */
64
+ export declare function mergeEnvelopes<TEnvelope extends AnyDocumentEnvelope>(base: TEnvelope, overlay: Partial<Omit<TEnvelope, 'page'>> & {
65
+ page?: TEnvelope['page'];
66
+ }): TEnvelope;
package/compose.js ADDED
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_COMPOSE_VOCABULARY = void 0;
4
+ exports.composeEnvelope = composeEnvelope;
5
+ exports.composeNodeTree = composeNodeTree;
6
+ exports.mergeNodeTrees = mergeNodeTrees;
7
+ exports.mergeEnvelopes = mergeEnvelopes;
8
+ exports.DEFAULT_COMPOSE_VOCABULARY = {
9
+ fragmentNodeType: 'Fragment',
10
+ slotNodeType: 'Slot',
11
+ fragmentRefProp: 'ref',
12
+ slotNameProp: 'name',
13
+ };
14
+ function vocabularyOf(options) {
15
+ return { ...exports.DEFAULT_COMPOSE_VOCABULARY, ...options.vocabulary };
16
+ }
17
+ function applyOverride(node, override) {
18
+ return {
19
+ ...node,
20
+ ...(override.type ? { type: override.type } : {}),
21
+ props: { ...node.props, ...override.props },
22
+ ...(override.bindings ? { bindings: { ...node.bindings, ...override.bindings } } : {}),
23
+ ...(override.actions ? { actions: { ...node.actions, ...override.actions } } : {}),
24
+ };
25
+ }
26
+ function expandChild(node, options, vocabulary) {
27
+ if (node.type === vocabulary.fragmentNodeType) {
28
+ const ref = node.props?.[vocabulary.fragmentRefProp];
29
+ const fragment = typeof ref === 'string' ? options.fragments?.[ref] : undefined;
30
+ // An unresolved reference stays in the tree so the renderer surfaces it
31
+ // rather than silently dropping content.
32
+ return fragment
33
+ ? [composeNode(fragment, options, vocabulary)]
34
+ : [composeNode({ ...node, children: [] }, options, vocabulary)];
35
+ }
36
+ if (node.type === vocabulary.slotNodeType) {
37
+ const name = node.props?.[vocabulary.slotNameProp];
38
+ const filler = typeof name === 'string' ? options.slots?.[name] : undefined;
39
+ if (filler === undefined) {
40
+ // No filler: fall back to the slot's own children (its default content).
41
+ return (node.children ?? []).flatMap((child) => expandChild(child, options, vocabulary));
42
+ }
43
+ const nodes = Array.isArray(filler) ? filler : [filler];
44
+ return nodes.map((filled) => composeNode(filled, options, vocabulary));
45
+ }
46
+ return [composeNode(node, options, vocabulary)];
47
+ }
48
+ function composeNode(node, options, vocabulary) {
49
+ const override = options.overrides?.[node.key];
50
+ const base = override ? applyOverride(node, override) : node;
51
+ const children = (base.children ?? [])
52
+ .filter((child) => !options.overrides?.[child.key]?.remove)
53
+ .flatMap((child) => expandChild(child, options, vocabulary));
54
+ return { ...base, children };
55
+ }
56
+ /**
57
+ * Compose a document: expand fragment references, fill slots, then apply
58
+ * per-node overrides. Pure — the input document is never mutated.
59
+ */
60
+ function composeEnvelope(document, options = {}) {
61
+ return { ...document, page: composeNode(document.page, options, vocabularyOf(options)) };
62
+ }
63
+ function composeNodeTree(node, options = {}) {
64
+ return composeNode(node, options, vocabularyOf(options));
65
+ }
66
+ /**
67
+ * Merge an overlay tree onto a base tree by node `key`: matching nodes have
68
+ * their props, bindings, and actions shallow-merged (overlay wins) and their
69
+ * children merged recursively; overlay children with no match are appended.
70
+ * This is the "hand-authored beats generated, at the node level" rule.
71
+ */
72
+ function mergeNodeTrees(base, overlay) {
73
+ const merged = {
74
+ ...base,
75
+ ...(overlay.type ? { type: overlay.type } : {}),
76
+ props: { ...base.props, ...overlay.props },
77
+ ...(base.bindings || overlay.bindings ? { bindings: { ...base.bindings, ...overlay.bindings } } : {}),
78
+ ...(base.actions || overlay.actions ? { actions: { ...base.actions, ...overlay.actions } } : {}),
79
+ };
80
+ const overlayChildren = (overlay.children ?? []);
81
+ const byKey = new Map(overlayChildren.map((child) => [child.key, child]));
82
+ const consumed = new Set();
83
+ const children = (base.children ?? []).map((child) => {
84
+ const patch = byKey.get(child.key);
85
+ if (!patch)
86
+ return child;
87
+ consumed.add(child.key);
88
+ return mergeNodeTrees(child, patch);
89
+ });
90
+ for (const child of overlayChildren) {
91
+ if (!consumed.has(child.key))
92
+ children.push(child);
93
+ }
94
+ return { ...merged, children };
95
+ }
96
+ function mergeNamed(base, overlay) {
97
+ if (!base && !overlay)
98
+ return undefined;
99
+ const merged = new Map((base ?? []).map((entry) => [entry.name, entry]));
100
+ for (const entry of overlay ?? [])
101
+ merged.set(entry.name, entry);
102
+ return [...merged.values()];
103
+ }
104
+ /**
105
+ * Merge an overlay document onto a base document: envelope identity comes from
106
+ * the overlay when set, `meta` is shallow-merged, `registries` and `dataSources`
107
+ * are merged by name, and the page trees are merged by node key.
108
+ */
109
+ function mergeEnvelopes(base, overlay) {
110
+ const registries = mergeNamed(base.registries, overlay.registries);
111
+ const dataSources = mergeNamed(base.dataSources, overlay.dataSources);
112
+ return {
113
+ ...base,
114
+ ...overlay,
115
+ ...(base.meta || overlay.meta ? { meta: { ...base.meta, ...overlay.meta } } : {}),
116
+ ...(registries ? { registries } : {}),
117
+ ...(dataSources ? { dataSources } : {}),
118
+ page: overlay.page ? mergeNodeTrees(base.page, overlay.page) : base.page,
119
+ };
120
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Value constraints a node can declare, and the pure check over them. Documents
3
+ * are authored elsewhere (a JSON Schema, a database constraint, an agent), so
4
+ * this layer never throws on malformed input.
5
+ */
6
+ export interface NodeConstraints {
7
+ minLength?: number;
8
+ maxLength?: number;
9
+ minValue?: number;
10
+ maxValue?: number;
11
+ pattern?: string;
12
+ precision?: number;
13
+ scale?: number;
14
+ }
15
+ /**
16
+ * Validate a single value against the constraints declared on its node.
17
+ * Returns a human-readable message, or `null` when the value is acceptable.
18
+ */
19
+ export declare function validateValue(value: unknown, constraints?: NodeConstraints, required?: boolean): string | null;
package/constraints.js ADDED
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ /**
3
+ * Value constraints a node can declare, and the pure check over them. Documents
4
+ * are authored elsewhere (a JSON Schema, a database constraint, an agent), so
5
+ * this layer never throws on malformed input.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.validateValue = validateValue;
9
+ /**
10
+ * Validate a single value against the constraints declared on its node.
11
+ * Returns a human-readable message, or `null` when the value is acceptable.
12
+ */
13
+ function validateValue(value, constraints, required) {
14
+ const stringValue = value == null ? '' : String(value);
15
+ const isEmpty = stringValue.trim() === '';
16
+ if (required && isEmpty) {
17
+ return 'This field is required';
18
+ }
19
+ if (isEmpty)
20
+ return null;
21
+ if (constraints?.minLength != null && stringValue.length < constraints.minLength) {
22
+ return `Minimum ${constraints.minLength} characters required`;
23
+ }
24
+ if (constraints?.maxLength != null && stringValue.length > constraints.maxLength) {
25
+ return `Maximum ${constraints.maxLength} characters allowed`;
26
+ }
27
+ if (constraints?.minValue != null && typeof value === 'number' && value < constraints.minValue) {
28
+ return `Minimum value is ${constraints.minValue}`;
29
+ }
30
+ if (constraints?.maxValue != null && typeof value === 'number' && value > constraints.maxValue) {
31
+ return `Maximum value is ${constraints.maxValue}`;
32
+ }
33
+ if (constraints?.pattern) {
34
+ const regex = compilePattern(constraints.pattern);
35
+ if (regex && !regex.test(stringValue)) {
36
+ return 'Invalid format';
37
+ }
38
+ }
39
+ return null;
40
+ }
41
+ /**
42
+ * An uncompilable pattern must not take the document down — it is reported as
43
+ * unconstrained rather than as a failed value.
44
+ */
45
+ function compilePattern(pattern) {
46
+ try {
47
+ return new RegExp(pattern);
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ }
package/envelope.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The document envelope: a versioned container around one node tree, plus the
3
+ * resolution sources and named data the tree binds against.
4
+ */
5
+ import type { AnyDocumentNode } from './node';
6
+ export declare const DOCUMENT_FORMAT_VERSION = "1.0";
7
+ export interface DocumentMetadata {
8
+ title?: string;
9
+ description?: string;
10
+ [key: string]: unknown;
11
+ }
12
+ /**
13
+ * A resolution source for node types: a registry name and a URL template, e.g.
14
+ * `https://example.com/r/{name}.json`.
15
+ */
16
+ export interface RegistrySource {
17
+ name: string;
18
+ url: string;
19
+ }
20
+ /** A named, read-only query a document's nodes can bind against. */
21
+ export interface DocumentDataSource {
22
+ name: string;
23
+ query?: string;
24
+ variables?: Record<string, unknown>;
25
+ [key: string]: unknown;
26
+ }
27
+ /**
28
+ * The generic envelope. `TNode` is the node tree, `TKind` the envelope's `type`
29
+ * discriminator, and `TVersion` its format version — a concrete format pins
30
+ * those as literal types (see `blocks-schema`'s `UIDocument`).
31
+ */
32
+ export interface DocumentEnvelope<TNode extends AnyDocumentNode = AnyDocumentNode, TKind extends string = string, TVersion extends string = string> {
33
+ formatVersion: TVersion;
34
+ type: TKind;
35
+ id: string;
36
+ meta?: DocumentMetadata;
37
+ registries?: RegistrySource[];
38
+ dataSources?: DocumentDataSource[];
39
+ page: TNode;
40
+ }
41
+ /** Any envelope, whatever its kind and vocabulary. */
42
+ export type AnyDocumentEnvelope = DocumentEnvelope<AnyDocumentNode, string, string>;
43
+ export interface EnvelopeKind<TKind extends string = string, TVersion extends string = string> {
44
+ /** The envelope's `type` discriminator, e.g. `UISchema`. */
45
+ documentType: TKind;
46
+ formatVersion: TVersion;
47
+ }
48
+ /**
49
+ * Structural check against one envelope kind. Deliberately shallow: a full
50
+ * check is `parseDocument` (zod), this is the cheap discriminator a router or a
51
+ * content-kind switch needs.
52
+ */
53
+ export declare function isDocumentEnvelope<TKind extends string, TVersion extends string>(value: unknown, kind: EnvelopeKind<TKind, TVersion>): value is DocumentEnvelope<AnyDocumentNode, TKind, TVersion>;
54
+ export declare function createEnvelope<TNode extends AnyDocumentNode, TKind extends string, TVersion extends string>(kind: EnvelopeKind<TKind, TVersion>, page: TNode, options?: {
55
+ id?: string;
56
+ meta?: DocumentMetadata;
57
+ registries?: RegistrySource[];
58
+ dataSources?: DocumentDataSource[];
59
+ }): DocumentEnvelope<TNode, TKind, TVersion>;
package/envelope.js ADDED
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DOCUMENT_FORMAT_VERSION = void 0;
4
+ exports.isDocumentEnvelope = isDocumentEnvelope;
5
+ exports.createEnvelope = createEnvelope;
6
+ exports.DOCUMENT_FORMAT_VERSION = '1.0';
7
+ /**
8
+ * Structural check against one envelope kind. Deliberately shallow: a full
9
+ * check is `parseDocument` (zod), this is the cheap discriminator a router or a
10
+ * content-kind switch needs.
11
+ */
12
+ function isDocumentEnvelope(value, kind) {
13
+ if (!value || typeof value !== 'object')
14
+ return false;
15
+ const candidate = value;
16
+ return (candidate.type === kind.documentType && candidate.formatVersion === kind.formatVersion && !!candidate.page);
17
+ }
18
+ function createEnvelope(kind, page, options = {}) {
19
+ return {
20
+ formatVersion: kind.formatVersion,
21
+ type: kind.documentType,
22
+ id: options.id ?? 'document',
23
+ ...(options.meta ? { meta: options.meta } : {}),
24
+ ...(options.registries ? { registries: options.registries } : {}),
25
+ ...(options.dataSources ? { dataSources: options.dataSources } : {}),
26
+ page,
27
+ };
28
+ }