@mastra/json-render 0.0.0-color-ramp-20261124000035
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.md +32 -0
- package/README.md +96 -0
- package/dist/index.cjs +371 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +369 -0
- package/dist/processor.d.ts +33 -0
- package/dist/state-BJ97_AE8.cjs +9 -0
- package/dist/state-Bl6NZlzO.js +4 -0
- package/dist/state.d.ts +3 -0
- package/dist/studio/catalog.d.ts +236 -0
- package/dist/studio/index.cjs +193 -0
- package/dist/studio/index.d.ts +4 -0
- package/dist/studio/index.js +191 -0
- package/package.json +93 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Portions of this software are licensed as follows:
|
|
2
|
+
|
|
3
|
+
- All content that resides under any directory named `ee/` within this
|
|
4
|
+
repository, including but not limited to:
|
|
5
|
+
- `@mastra/core/auth/ee`
|
|
6
|
+
- `@mastra/core/agent-builder/ee`
|
|
7
|
+
- `@mastra/editor/ee`
|
|
8
|
+
|
|
9
|
+
is licensed under the license defined in [`ee/LICENSE`](https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE).
|
|
10
|
+
|
|
11
|
+
- All third-party components incorporated into the Mastra Software are
|
|
12
|
+
licensed under the original license provided by the owner of the
|
|
13
|
+
applicable component.
|
|
14
|
+
|
|
15
|
+
- Content outside of the above-mentioned directories or restrictions is
|
|
16
|
+
available under the "Apache License 2.0" as defined below.
|
|
17
|
+
|
|
18
|
+
# Apache License 2.0
|
|
19
|
+
|
|
20
|
+
Copyright (c) 2025 Kepler Software, Inc.
|
|
21
|
+
|
|
22
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
23
|
+
you may not use this file except in compliance with the License.
|
|
24
|
+
You may obtain a copy of the License at
|
|
25
|
+
|
|
26
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
27
|
+
|
|
28
|
+
Unless required by applicable law or agreed to in writing, software
|
|
29
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
30
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
31
|
+
See the License for the specific language governing permissions and
|
|
32
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# @mastra/json-render
|
|
2
|
+
|
|
3
|
+
Let Mastra agents compose [json-render](https://json-render.dev) interfaces from your component catalog. The interfaces stream to the client, are saved with the message, and can be edited in later turns.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @mastra/json-render
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
It needs `@json-render/core` on the server and `@json-render/react` to render on the client:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install @json-render/core @json-render/react
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
Register the processor as both an input and an output processor, and build the instructions from your catalog:
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import { Agent } from '@mastra/core/agent';
|
|
23
|
+
import { JsonRenderProcessor } from '@mastra/json-render';
|
|
24
|
+
import { Memory } from '@mastra/memory';
|
|
25
|
+
import { catalog } from './catalog';
|
|
26
|
+
|
|
27
|
+
const ui = new JsonRenderProcessor({ catalog });
|
|
28
|
+
|
|
29
|
+
export const uiAgent = new Agent({
|
|
30
|
+
id: 'ui-agent',
|
|
31
|
+
name: 'UI Agent',
|
|
32
|
+
model: 'openai/gpt-6.1-sol',
|
|
33
|
+
instructions: catalog.prompt({
|
|
34
|
+
mode: 'inline',
|
|
35
|
+
editModes: ['patch'],
|
|
36
|
+
system: 'You are a travel assistant. Prefer showing an interface over describing it.',
|
|
37
|
+
}),
|
|
38
|
+
inputProcessors: [ui],
|
|
39
|
+
outputProcessors: [ui],
|
|
40
|
+
maxProcessorRetries: 2,
|
|
41
|
+
memory: new Memory(),
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
On the client, render each message's `data-spec` parts with `useJsonRenderMessage()` from `@json-render/react`. Send the interface's state under the `JSON_RENDER_STATE` request context key so the model sees what the user set.
|
|
46
|
+
|
|
47
|
+
json-render 0.22's `buildSpecFromParts()` writes patch values into the spec by reference, so building the same parts again (on every streamed chunk) repeats list items. Pass `useJsonRenderMessage()` a copy of the parts:
|
|
48
|
+
|
|
49
|
+
```tsx
|
|
50
|
+
import { useJsonRenderMessage } from '@json-render/react';
|
|
51
|
+
import { useMemo } from 'react';
|
|
52
|
+
|
|
53
|
+
function Reply({ message }) {
|
|
54
|
+
const parts = useMemo(() => structuredClone(message.content.parts), [message.content.parts]);
|
|
55
|
+
const { spec } = useJsonRenderMessage(parts);
|
|
56
|
+
// Render `spec` with your registry.
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Render interfaces in Studio
|
|
61
|
+
|
|
62
|
+
Studio draws interfaces composed from `studioCatalog`, using its own components. The `/studio` entry reads its component schema from `@json-render/react`, so install it alongside the processor. Give an agent this catalog to see its interfaces in Studio's chat, with no client code:
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
import { JsonRenderProcessor } from '@mastra/json-render';
|
|
66
|
+
import { studioCatalog } from '@mastra/json-render/studio';
|
|
67
|
+
|
|
68
|
+
const ui = new JsonRenderProcessor({ catalog: studioCatalog });
|
|
69
|
+
|
|
70
|
+
export const uiAgent = new Agent({
|
|
71
|
+
id: 'ui-agent',
|
|
72
|
+
name: 'UI Agent',
|
|
73
|
+
model: 'openai/gpt-6.1-sol',
|
|
74
|
+
instructions: studioCatalog.prompt({ mode: 'inline', editModes: ['patch'] }),
|
|
75
|
+
inputProcessors: [ui],
|
|
76
|
+
outputProcessors: [ui],
|
|
77
|
+
memory: new Memory(),
|
|
78
|
+
});
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The catalog has layout (`Stack`, `Grid`, `Card`, `Separator`), content (`Heading`, `Text`, `Badge`, `Stat`, `Table`, `List`, `Progress`, `Notice`), and form controls (`Button`, `Input`, `Select`, `Checkbox`). Its `sendMessage` action sends a message as the user, along with the values entered in the interface. Controls are disabled while the reply streams, and in places where nothing can answer them, such as traces.
|
|
82
|
+
|
|
83
|
+
`@mastra/json-render/studio` doesn't depend on React, so the same catalog can back your own registry.
|
|
84
|
+
|
|
85
|
+
## Documentation
|
|
86
|
+
|
|
87
|
+
- [Processors](https://mastra.ai/docs/agents/processors)
|
|
88
|
+
- [json-render](https://json-render.dev)
|
|
89
|
+
|
|
90
|
+
## Changelog
|
|
91
|
+
|
|
92
|
+
See the [package changelog](https://github.com/mastra-ai/mastra/blob/main/integrations/json-render/CHANGELOG.md) for version history and release notes.
|
|
93
|
+
|
|
94
|
+
## Support
|
|
95
|
+
|
|
96
|
+
We have an [open community Discord](https://discord.gg/mastra-ai). Come and say hello and let us know if you have any questions or need any help getting things running.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_state = require("./state-BJ97_AE8.cjs");
|
|
3
|
+
let _json_render_core = require("@json-render/core");
|
|
4
|
+
let _mastra_core_processors = require("@mastra/core/processors");
|
|
5
|
+
// src/processor.ts
|
|
6
|
+
const FENCE_OPEN = "```spec";
|
|
7
|
+
const FENCE_CLOSE = "```";
|
|
8
|
+
/** Where a patch can write in a spec. Outside a ```spec block, only patches here are taken as interface edits. */
|
|
9
|
+
const SPEC_PATH = /^\/(root|elements|state)(\/|$)/;
|
|
10
|
+
/** A part that empties an interface the client has already rendered. */
|
|
11
|
+
const CLEARED = {
|
|
12
|
+
type: "flat",
|
|
13
|
+
spec: {
|
|
14
|
+
root: "",
|
|
15
|
+
elements: {}
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/** The code block a line opens, as CommonMark reads it. */
|
|
19
|
+
function fenceOpenedBy(line) {
|
|
20
|
+
const [, marker, info] = /^(`{3,}|~{3,})(.*)$/.exec(line) ?? [];
|
|
21
|
+
if (!marker || marker.startsWith("`") && info.includes("`")) return;
|
|
22
|
+
return {
|
|
23
|
+
marker,
|
|
24
|
+
spec: info.trim().split(/\s/)[0] === "spec"
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Whether a line closes a code block: the fence's character, at least as many times, and nothing else. */
|
|
28
|
+
function closes(fence, line) {
|
|
29
|
+
const [, marker] = /^(`+|~+)$/.exec(line) ?? [];
|
|
30
|
+
return !!marker && marker[0] === fence.marker[0] && marker.length >= fence.marker.length;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Whether a line held back may still turn out to be a code fence or a patch
|
|
34
|
+
* (`{"op": …}`). Lines that cannot are released as prose right away, so
|
|
35
|
+
* only a reply cut off inside a patch line ends with text held back.
|
|
36
|
+
*/
|
|
37
|
+
function couldOpenSpecLine(line) {
|
|
38
|
+
if (line.startsWith("`") || line.startsWith("~")) {
|
|
39
|
+
const fence = line[0].repeat(3);
|
|
40
|
+
return fence.startsWith(line) || line.startsWith(fence);
|
|
41
|
+
}
|
|
42
|
+
return /^\{\s*("|$)/.test(line);
|
|
43
|
+
}
|
|
44
|
+
function uiStateIn(requestContext) {
|
|
45
|
+
return requestContext?.get(require_state.JSON_RENDER_STATE);
|
|
46
|
+
}
|
|
47
|
+
/** The spec the latest message with one builds, which a block not starting at `/root` edits. */
|
|
48
|
+
function latestSpec(messages) {
|
|
49
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
50
|
+
const spec = specOf(messages[i].content.parts ?? []);
|
|
51
|
+
if (spec) return spec;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Turns the ```spec blocks a model writes (json-render's text format) into
|
|
56
|
+
* `data-spec` parts, so the interface streams to the client and is saved with
|
|
57
|
+
* the message while the text keeps only the prose.
|
|
58
|
+
*
|
|
59
|
+
* A block that does not start by setting `/root` edits the latest interface in
|
|
60
|
+
* the thread: the reply saves that spec first, then the patches, so every
|
|
61
|
+
* message rebuilds its own interface and earlier ones stay as they were.
|
|
62
|
+
*/
|
|
63
|
+
var JsonRenderProcessor = class {
|
|
64
|
+
options;
|
|
65
|
+
id = "json-render";
|
|
66
|
+
name = "json-render";
|
|
67
|
+
constructor(options) {
|
|
68
|
+
this.options = options;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Shows the model the latest interface it wrote, which Mastra leaves out of the
|
|
72
|
+
* prompt with every `data-*` part: the ```spec block goes back into the reply
|
|
73
|
+
* that wrote it, as the spec is now, holding the state the user set in it.
|
|
74
|
+
* Only this call's prompt changes, not the thread.
|
|
75
|
+
*/
|
|
76
|
+
async processLLMRequest({ prompt, messageList, requestContext }) {
|
|
77
|
+
const messages = messageList?.get.all.db() ?? [];
|
|
78
|
+
const reply = messages.findLast((message) => specOf(message.content.parts ?? []));
|
|
79
|
+
if (!reply) return;
|
|
80
|
+
const spec = specOf(reply.content.parts);
|
|
81
|
+
const uiState = uiStateIn(requestContext);
|
|
82
|
+
const text = specBlock(uiState ? {
|
|
83
|
+
...spec,
|
|
84
|
+
state: uiState
|
|
85
|
+
} : spec);
|
|
86
|
+
const written = new Set(reply.content.parts.map((part) => part.createdAt));
|
|
87
|
+
const wrote = (message) => !!message && message.role !== "user" && writtenAt(message).some((createdAt) => written.has(createdAt));
|
|
88
|
+
let at = prompt.findIndex(wrote);
|
|
89
|
+
if (at < 0) {
|
|
90
|
+
const later = messages.slice(messages.indexOf(reply) + 1).filter((message) => message.role === "user").length;
|
|
91
|
+
const users = prompt.flatMap((message, index) => message.role === "user" ? [index] : []);
|
|
92
|
+
const after = later > 0 ? users.at(-later) : void 0;
|
|
93
|
+
if (after === void 0) return;
|
|
94
|
+
return { prompt: prompt.toSpliced(after, 0, {
|
|
95
|
+
role: "assistant",
|
|
96
|
+
content: [{
|
|
97
|
+
type: "text",
|
|
98
|
+
text
|
|
99
|
+
}]
|
|
100
|
+
}) };
|
|
101
|
+
}
|
|
102
|
+
while (wrote(prompt[at + 1])) at++;
|
|
103
|
+
const message = prompt[at];
|
|
104
|
+
if (message.role === "assistant" && !message.content.some((part) => part.type === "tool-call")) {
|
|
105
|
+
const prose = message.content.findLast((part) => part.type === "text")?.text ?? "";
|
|
106
|
+
const block = {
|
|
107
|
+
type: "text",
|
|
108
|
+
text: prose && !prose.endsWith("\n") ? `\n${text}` : text
|
|
109
|
+
};
|
|
110
|
+
return { prompt: prompt.with(at, {
|
|
111
|
+
...message,
|
|
112
|
+
content: [...message.content, block]
|
|
113
|
+
}) };
|
|
114
|
+
}
|
|
115
|
+
return { prompt: prompt.toSpliced(at + 1, 0, {
|
|
116
|
+
role: "assistant",
|
|
117
|
+
content: [{
|
|
118
|
+
type: "text",
|
|
119
|
+
text
|
|
120
|
+
}]
|
|
121
|
+
}) };
|
|
122
|
+
}
|
|
123
|
+
async processOutputStream({ part, state, writer, messageList, requestContext }) {
|
|
124
|
+
if (part.type !== "text-delta" && part.type !== "text-end") return part;
|
|
125
|
+
const split = state.split ??= {
|
|
126
|
+
line: "",
|
|
127
|
+
holding: false,
|
|
128
|
+
midLine: false,
|
|
129
|
+
indent: 0,
|
|
130
|
+
started: false
|
|
131
|
+
};
|
|
132
|
+
const live = state.live ??= { rejected: [] };
|
|
133
|
+
const parts = [];
|
|
134
|
+
let text = "";
|
|
135
|
+
/** `last`: the text block ended on this line, so no newline follows it. */
|
|
136
|
+
const endLine = (last = false) => {
|
|
137
|
+
const line = split.line;
|
|
138
|
+
const trimmed = line.trim();
|
|
139
|
+
split.line = "";
|
|
140
|
+
split.holding = false;
|
|
141
|
+
const keep = () => void (text += last ? line : `${line}\n`);
|
|
142
|
+
const fence = split.fence;
|
|
143
|
+
if (fence && closes(fence, trimmed)) {
|
|
144
|
+
split.fence = void 0;
|
|
145
|
+
return fence.spec ? void 0 : keep();
|
|
146
|
+
}
|
|
147
|
+
if (fence && !fence.spec) return keep();
|
|
148
|
+
const opened = !fence && fenceOpenedBy(trimmed);
|
|
149
|
+
if (opened) {
|
|
150
|
+
split.fence = opened;
|
|
151
|
+
split.started = false;
|
|
152
|
+
return opened.spec ? void 0 : keep();
|
|
153
|
+
}
|
|
154
|
+
const parsed = (0, _json_render_core.parseSpecStreamLine)(trimmed);
|
|
155
|
+
const patch = parsed && (fence || SPEC_PATH.test(parsed.path)) ? parsed : null;
|
|
156
|
+
if (!patch) return void (!fence && keep());
|
|
157
|
+
if (!split.started) {
|
|
158
|
+
split.started = true;
|
|
159
|
+
const latest = patch.path !== "/root" && messageList && latestSpec(messageList.get.all.db());
|
|
160
|
+
const uiState = uiStateIn(requestContext);
|
|
161
|
+
const edited = latest && (uiState ? {
|
|
162
|
+
...latest,
|
|
163
|
+
state: uiState
|
|
164
|
+
} : latest);
|
|
165
|
+
if (edited) {
|
|
166
|
+
live.spec = structuredClone(edited);
|
|
167
|
+
parts.push({
|
|
168
|
+
type: "flat",
|
|
169
|
+
spec: edited
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
applyPatch(live.spec ??= {
|
|
175
|
+
root: "",
|
|
176
|
+
elements: {}
|
|
177
|
+
}, patch);
|
|
178
|
+
parts.push({
|
|
179
|
+
type: "patch",
|
|
180
|
+
patch
|
|
181
|
+
});
|
|
182
|
+
} catch (error) {
|
|
183
|
+
live.rejected.push(error.message);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
if (part.type === "text-end") {
|
|
187
|
+
if (split.holding) endLine(true);
|
|
188
|
+
state.split = void 0;
|
|
189
|
+
} else for (const char of part.payload.text) {
|
|
190
|
+
const inSpec = !!split.fence?.spec;
|
|
191
|
+
if (char === "\n") {
|
|
192
|
+
if (split.holding) endLine();
|
|
193
|
+
else if (!inSpec) text += char;
|
|
194
|
+
split.midLine = false;
|
|
195
|
+
split.indent = 0;
|
|
196
|
+
} else if (split.holding) {
|
|
197
|
+
split.line += char;
|
|
198
|
+
if (!inSpec && !couldOpenSpecLine(split.line)) {
|
|
199
|
+
text += split.line;
|
|
200
|
+
split.line = "";
|
|
201
|
+
split.holding = false;
|
|
202
|
+
split.midLine = true;
|
|
203
|
+
}
|
|
204
|
+
} else if (inSpec || !split.midLine && split.indent < 4 && (char === "{" || char === "`" || char === "~")) {
|
|
205
|
+
split.holding = true;
|
|
206
|
+
split.line = char;
|
|
207
|
+
} else {
|
|
208
|
+
text += char;
|
|
209
|
+
if (!/\s/.test(char)) split.midLine = true;
|
|
210
|
+
else if (!split.midLine) split.indent += char === " " ? 4 : 1;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
for (const data of parts) await writer?.custom({
|
|
214
|
+
type: _json_render_core.SPEC_DATA_PART_TYPE,
|
|
215
|
+
data
|
|
216
|
+
});
|
|
217
|
+
if (part.type !== "text-end") return text ? {
|
|
218
|
+
...part,
|
|
219
|
+
payload: {
|
|
220
|
+
...part.payload,
|
|
221
|
+
text
|
|
222
|
+
}
|
|
223
|
+
} : null;
|
|
224
|
+
if (!text) return part;
|
|
225
|
+
state[_mastra_core_processors.REPROCESS_PART_KEY] = part;
|
|
226
|
+
return {
|
|
227
|
+
type: "text-delta",
|
|
228
|
+
runId: part.runId,
|
|
229
|
+
from: part.from,
|
|
230
|
+
payload: {
|
|
231
|
+
id: part.payload.id,
|
|
232
|
+
text
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
/** Sends a reply whose interface cannot render back to the model, with what is wrong. */
|
|
237
|
+
async processOutputStep({ messages, abort, state, writer }) {
|
|
238
|
+
const live = state.live;
|
|
239
|
+
const rejected = live?.rejected.splice(0) ?? [];
|
|
240
|
+
const reply = messages.at(-1);
|
|
241
|
+
if (reply?.role !== "assistant") return messages;
|
|
242
|
+
let problems = rejected.join("\n") || void 0;
|
|
243
|
+
try {
|
|
244
|
+
const spec = buildSpec(reply.content.parts);
|
|
245
|
+
problems ??= spec && problemsIn(spec, this.options.catalog);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
problems ??= error.message;
|
|
248
|
+
}
|
|
249
|
+
if (problems) {
|
|
250
|
+
if (live?.spec) {
|
|
251
|
+
live.spec = void 0;
|
|
252
|
+
await writer?.custom({
|
|
253
|
+
type: _json_render_core.SPEC_DATA_PART_TYPE,
|
|
254
|
+
data: CLEARED,
|
|
255
|
+
transient: true
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
abort(`The interface in your \`\`\`spec block cannot be shown. Write it again without these problems:\n${problems}`, { retry: true });
|
|
259
|
+
}
|
|
260
|
+
return messages;
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
/** The ```spec block json-render's prompt asks for, writing `spec` from nothing. */
|
|
264
|
+
function specBlock({ root, state, elements }) {
|
|
265
|
+
const patches = (0, _json_render_core.diffToPatches)({ elements: {} }, {
|
|
266
|
+
root,
|
|
267
|
+
...state && { state },
|
|
268
|
+
elements
|
|
269
|
+
});
|
|
270
|
+
return [
|
|
271
|
+
FENCE_OPEN,
|
|
272
|
+
...patches.map((patch) => JSON.stringify(patch)),
|
|
273
|
+
FENCE_CLOSE
|
|
274
|
+
].join("\n");
|
|
275
|
+
}
|
|
276
|
+
/** When the parts of a prompt message were written, as Mastra records it on each part. */
|
|
277
|
+
function writtenAt(message) {
|
|
278
|
+
if (typeof message.content === "string") return [];
|
|
279
|
+
return message.content.flatMap((part) => {
|
|
280
|
+
const at = part.providerOptions?.mastra?.createdAt;
|
|
281
|
+
return typeof at === "number" ? [at] : [];
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* The spec a message's `data-spec` parts build, the way the client renders it,
|
|
286
|
+
* leaving the parts as they are. Throws when a patch cannot be applied, naming it.
|
|
287
|
+
*/
|
|
288
|
+
function buildSpec(parts) {
|
|
289
|
+
let spec;
|
|
290
|
+
for (const part of parts) {
|
|
291
|
+
if (part.type !== _json_render_core.SPEC_DATA_PART_TYPE) continue;
|
|
292
|
+
const data = part.data;
|
|
293
|
+
if (data.type === "flat") spec = structuredClone(data.spec);
|
|
294
|
+
else if (data.type === "patch") applyPatch(spec ??= {
|
|
295
|
+
root: "",
|
|
296
|
+
elements: {}
|
|
297
|
+
}, data.patch);
|
|
298
|
+
}
|
|
299
|
+
return spec;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Applies a copy of `patch` to `spec`: `applySpecPatch` inserts the values a
|
|
303
|
+
* patch holds, so applying the patch itself would let later patches change it.
|
|
304
|
+
* Throws when it cannot be applied, naming it.
|
|
305
|
+
*/
|
|
306
|
+
function applyPatch(spec, patch) {
|
|
307
|
+
try {
|
|
308
|
+
if (typeof patch.path !== "string") throw new Error("its path is not a string");
|
|
309
|
+
(0, _json_render_core.applySpecPatch)(spec, structuredClone(patch));
|
|
310
|
+
} catch (error) {
|
|
311
|
+
throw new Error(`- ${JSON.stringify(patch)} cannot be applied: ${error.message}`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/** The spec a message's `data-spec` parts build, or none when they cannot build one. */
|
|
315
|
+
function specOf(parts) {
|
|
316
|
+
try {
|
|
317
|
+
return buildSpec(parts);
|
|
318
|
+
} catch {
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/** What keeps a spec from rendering: broken structure, unknown components, or props a component does not take. */
|
|
323
|
+
function problemsIn(spec, catalog) {
|
|
324
|
+
const problems = (0, _json_render_core.validateSpec)(spec).issues.filter((issue) => issue.severity === "error");
|
|
325
|
+
const lines = problems.length ? [(0, _json_render_core.formatSpecIssues)(problems)] : [];
|
|
326
|
+
const components = catalog.data.components ?? {};
|
|
327
|
+
const stateModel = spec.state ?? {};
|
|
328
|
+
const seen = /* @__PURE__ */ new Set();
|
|
329
|
+
const report = (line) => {
|
|
330
|
+
if (seen.has(line)) return;
|
|
331
|
+
seen.add(line);
|
|
332
|
+
lines.push(line);
|
|
333
|
+
};
|
|
334
|
+
const visit = (key, scope, path) => {
|
|
335
|
+
const element = spec.elements[key];
|
|
336
|
+
if (!element || path.has(key)) return;
|
|
337
|
+
const component = components[element.type];
|
|
338
|
+
if (!component) report(`- "${key}" uses "${element.type}", which is not in the catalog`);
|
|
339
|
+
else {
|
|
340
|
+
const result = component.props.safeParse((0, _json_render_core.resolveElementProps)(element.props ?? {}, {
|
|
341
|
+
stateModel,
|
|
342
|
+
...scope
|
|
343
|
+
}));
|
|
344
|
+
for (const issue of result.success ? [] : result.error.issues) report(`- "${key}" (${element.type}) prop "${issue.path.join(".")}": ${issue.message}`);
|
|
345
|
+
}
|
|
346
|
+
const inner = new Set(path).add(key);
|
|
347
|
+
const children = [...element.children ?? [], ...Object.values(element.slots ?? {}).flat()];
|
|
348
|
+
if (!element.repeat) return children.forEach((child) => visit(child, scope, inner));
|
|
349
|
+
const statePath = (0, _json_render_core.resolveRepeatStatePath)(element.repeat.statePath, scope.repeatBasePath);
|
|
350
|
+
const items = statePath === void 0 ? [] : (0, _json_render_core.getByPath)(stateModel, statePath);
|
|
351
|
+
if (!Array.isArray(items)) return;
|
|
352
|
+
const keyField = element.repeat.key;
|
|
353
|
+
if (keyField) {
|
|
354
|
+
const keys = items.map((item, index) => String(item?.[keyField] ?? index));
|
|
355
|
+
const repeated = keys.find((itemKey, index) => keys.indexOf(itemKey) !== index);
|
|
356
|
+
if (repeated !== void 0) report(`- "${key}" repeats ${statePath} keyed by "${keyField}", but "${repeated}" appears more than once; each item needs its own key`);
|
|
357
|
+
}
|
|
358
|
+
items.forEach((repeatItem, repeatIndex) => {
|
|
359
|
+
const itemScope = {
|
|
360
|
+
repeatItem,
|
|
361
|
+
repeatIndex,
|
|
362
|
+
repeatBasePath: (0, _json_render_core.resolveRepeatItemStatePath)(statePath, repeatIndex)
|
|
363
|
+
};
|
|
364
|
+
children.forEach((child) => visit(child, itemScope, inner));
|
|
365
|
+
});
|
|
366
|
+
};
|
|
367
|
+
visit(spec.root, {}, /* @__PURE__ */ new Set());
|
|
368
|
+
return lines.length ? lines.join("\n") : void 0;
|
|
369
|
+
}
|
|
370
|
+
exports.JSON_RENDER_STATE = require_state.JSON_RENDER_STATE;
|
|
371
|
+
exports.JsonRenderProcessor = JsonRenderProcessor;
|
package/dist/index.d.ts
ADDED