@vvedantb/server 0.5.0 → 0.6.0
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/CHANGELOG.md +18 -0
- package/README.md +7 -4
- package/dist/artifacts/debounce.d.ts +16 -0
- package/dist/artifacts/debounce.js +49 -0
- package/dist/artifacts/document.d.ts +26 -0
- package/dist/artifacts/document.js +61 -0
- package/dist/artifacts/index.d.ts +8 -0
- package/dist/artifacts/index.js +8 -0
- package/dist/artifacts/limits.d.ts +21 -0
- package/dist/artifacts/limits.js +23 -0
- package/dist/artifacts/protocol.d.ts +45 -0
- package/dist/artifacts/protocol.js +243 -0
- package/dist/artifacts/schemas.d.ts +80 -0
- package/dist/artifacts/schemas.js +103 -0
- package/dist/artifacts/stateOps.d.ts +39 -0
- package/dist/artifacts/stateOps.js +92 -0
- package/dist/artifacts/storageShim.d.ts +9 -0
- package/dist/artifacts/storageShim.js +32 -0
- package/dist/artifacts/templates.d.ts +33 -0
- package/dist/artifacts/templates.js +496 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/docs/artifacts.md +116 -0
- package/package.json +3 -2
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
import { embedJsonInScript } from "./protocol.js";
|
|
2
|
+
function isPlainObject(value) {
|
|
3
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
function parseJsonRoot(raw) {
|
|
6
|
+
const trimmed = raw.trim();
|
|
7
|
+
if (!trimmed.startsWith("{") && !trimmed.startsWith("["))
|
|
8
|
+
return undefined;
|
|
9
|
+
try {
|
|
10
|
+
const value = JSON.parse(trimmed);
|
|
11
|
+
if (Array.isArray(value)) {
|
|
12
|
+
const items = [];
|
|
13
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
14
|
+
const item = value[i];
|
|
15
|
+
if (!isPlainObject(item))
|
|
16
|
+
return undefined;
|
|
17
|
+
items.push(item);
|
|
18
|
+
}
|
|
19
|
+
return { kind: "array", items };
|
|
20
|
+
}
|
|
21
|
+
if (isPlainObject(value))
|
|
22
|
+
return { kind: "object", value };
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function stringField(obj, key) {
|
|
30
|
+
if (!Object.prototype.hasOwnProperty.call(obj, key))
|
|
31
|
+
return undefined;
|
|
32
|
+
const desc = Object.getOwnPropertyDescriptor(obj, key);
|
|
33
|
+
if (!desc || typeof desc.value !== "string")
|
|
34
|
+
return undefined;
|
|
35
|
+
const text = desc.value.trim();
|
|
36
|
+
return text.length > 0 ? text : undefined;
|
|
37
|
+
}
|
|
38
|
+
function numberField(obj, key) {
|
|
39
|
+
if (!Object.prototype.hasOwnProperty.call(obj, key))
|
|
40
|
+
return undefined;
|
|
41
|
+
const desc = Object.getOwnPropertyDescriptor(obj, key);
|
|
42
|
+
if (!desc || typeof desc.value !== "number" || !Number.isFinite(desc.value)) {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
return desc.value;
|
|
46
|
+
}
|
|
47
|
+
function arrayField(obj, key) {
|
|
48
|
+
if (!Object.prototype.hasOwnProperty.call(obj, key))
|
|
49
|
+
return undefined;
|
|
50
|
+
const desc = Object.getOwnPropertyDescriptor(obj, key);
|
|
51
|
+
if (!desc || !Array.isArray(desc.value))
|
|
52
|
+
return undefined;
|
|
53
|
+
const list = [];
|
|
54
|
+
const raw = desc.value;
|
|
55
|
+
for (let i = 0; i < raw.length; i += 1) {
|
|
56
|
+
const item = raw[i];
|
|
57
|
+
list.push(item);
|
|
58
|
+
}
|
|
59
|
+
return list;
|
|
60
|
+
}
|
|
61
|
+
function parseCard(obj, index) {
|
|
62
|
+
const front = stringField(obj, "front");
|
|
63
|
+
const back = stringField(obj, "back");
|
|
64
|
+
if (!front || !back)
|
|
65
|
+
return undefined;
|
|
66
|
+
return { id: stringField(obj, "id") ?? String(index), front, back };
|
|
67
|
+
}
|
|
68
|
+
function parseCardList(items) {
|
|
69
|
+
const cards = [];
|
|
70
|
+
for (let i = 0; i < items.length; i += 1) {
|
|
71
|
+
const item = items[i];
|
|
72
|
+
if (!item)
|
|
73
|
+
return undefined;
|
|
74
|
+
const card = parseCard(item, i);
|
|
75
|
+
if (!card)
|
|
76
|
+
return undefined;
|
|
77
|
+
cards.push(card);
|
|
78
|
+
}
|
|
79
|
+
return cards.length > 0 ? cards : undefined;
|
|
80
|
+
}
|
|
81
|
+
function parseQuestion(obj, index) {
|
|
82
|
+
const prompt = stringField(obj, "prompt") ?? stringField(obj, "question");
|
|
83
|
+
const correctIndex = numberField(obj, "correctIndex");
|
|
84
|
+
const optionsRaw = arrayField(obj, "options");
|
|
85
|
+
if (!prompt || correctIndex === undefined || !optionsRaw)
|
|
86
|
+
return undefined;
|
|
87
|
+
const options = [];
|
|
88
|
+
for (const option of optionsRaw) {
|
|
89
|
+
if (typeof option !== "string" || option.trim().length === 0)
|
|
90
|
+
return undefined;
|
|
91
|
+
options.push(option.trim());
|
|
92
|
+
}
|
|
93
|
+
if (options.length < 2 || options.length > 5)
|
|
94
|
+
return undefined;
|
|
95
|
+
if (!Number.isInteger(correctIndex) ||
|
|
96
|
+
correctIndex < 0 ||
|
|
97
|
+
correctIndex >= options.length) {
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
id: stringField(obj, "id") ?? String(index),
|
|
102
|
+
prompt,
|
|
103
|
+
options,
|
|
104
|
+
correctIndex,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function parseQuestionList(items) {
|
|
108
|
+
const questions = [];
|
|
109
|
+
for (let i = 0; i < items.length; i += 1) {
|
|
110
|
+
const item = items[i];
|
|
111
|
+
if (!item)
|
|
112
|
+
return undefined;
|
|
113
|
+
const question = parseQuestion(item, i);
|
|
114
|
+
if (!question)
|
|
115
|
+
return undefined;
|
|
116
|
+
questions.push(question);
|
|
117
|
+
}
|
|
118
|
+
return questions.length > 0 ? questions : undefined;
|
|
119
|
+
}
|
|
120
|
+
export function parseFlashcardsTemplate(raw) {
|
|
121
|
+
const root = parseJsonRoot(raw);
|
|
122
|
+
if (!root)
|
|
123
|
+
return undefined;
|
|
124
|
+
if (root.kind === "array") {
|
|
125
|
+
const cards = parseCardList(root.items);
|
|
126
|
+
if (!cards)
|
|
127
|
+
return undefined;
|
|
128
|
+
return { cards };
|
|
129
|
+
}
|
|
130
|
+
const cardsRaw = arrayField(root.value, "cards");
|
|
131
|
+
if (!cardsRaw)
|
|
132
|
+
return undefined;
|
|
133
|
+
const items = [];
|
|
134
|
+
for (const item of cardsRaw) {
|
|
135
|
+
if (!isPlainObject(item))
|
|
136
|
+
return undefined;
|
|
137
|
+
items.push(item);
|
|
138
|
+
}
|
|
139
|
+
const cards = parseCardList(items);
|
|
140
|
+
if (!cards)
|
|
141
|
+
return undefined;
|
|
142
|
+
return { title: stringField(root.value, "title"), cards };
|
|
143
|
+
}
|
|
144
|
+
export function parseQuizTemplate(raw) {
|
|
145
|
+
const root = parseJsonRoot(raw);
|
|
146
|
+
if (!root)
|
|
147
|
+
return undefined;
|
|
148
|
+
if (root.kind === "array") {
|
|
149
|
+
const questions = parseQuestionList(root.items);
|
|
150
|
+
if (!questions)
|
|
151
|
+
return undefined;
|
|
152
|
+
return { questions };
|
|
153
|
+
}
|
|
154
|
+
const questionsRaw = arrayField(root.value, "questions");
|
|
155
|
+
if (!questionsRaw)
|
|
156
|
+
return undefined;
|
|
157
|
+
const items = [];
|
|
158
|
+
for (const item of questionsRaw) {
|
|
159
|
+
if (!isPlainObject(item))
|
|
160
|
+
return undefined;
|
|
161
|
+
items.push(item);
|
|
162
|
+
}
|
|
163
|
+
const questions = parseQuestionList(items);
|
|
164
|
+
if (!questions)
|
|
165
|
+
return undefined;
|
|
166
|
+
return { title: stringField(root.value, "title"), questions };
|
|
167
|
+
}
|
|
168
|
+
export function htmlFromArtifactTemplate(args) {
|
|
169
|
+
if (args.template === "flashcards" || args.template === undefined) {
|
|
170
|
+
const parsed = parseFlashcardsTemplate(args.content);
|
|
171
|
+
if (parsed) {
|
|
172
|
+
return buildFlashcardsHtml({
|
|
173
|
+
title: parsed.title ?? args.title,
|
|
174
|
+
cards: parsed.cards,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
if (args.template === "flashcards")
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
if (args.template === "quiz" || args.template === undefined) {
|
|
181
|
+
const parsed = parseQuizTemplate(args.content);
|
|
182
|
+
if (parsed) {
|
|
183
|
+
return buildQuizHtml({
|
|
184
|
+
title: parsed.title ?? args.title,
|
|
185
|
+
questions: parsed.questions,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
function escapeHtml(value) {
|
|
192
|
+
return value
|
|
193
|
+
.replace(/&/g, "&")
|
|
194
|
+
.replace(/</g, "<")
|
|
195
|
+
.replace(/>/g, ">")
|
|
196
|
+
.replace(/"/g, """);
|
|
197
|
+
}
|
|
198
|
+
const SHARED_CSS = `:root{--bg:#f7f7f5;--fg:#1a1a1a;--muted:#5c5c57;--card:#fff;--line:#d9d9d4;--accent:#2f2f2a}
|
|
199
|
+
@media(prefers-color-scheme:dark){:root{--bg:#121212;--fg:#f2f2f2;--muted:#b3b3b3;--card:#1c1c1c;--line:#333;--accent:#ececec}}
|
|
200
|
+
*{box-sizing:border-box}html,body{margin:0;padding:0;background:var(--bg);color:var(--fg);font-family:"Instrument Sans",system-ui,sans-serif}
|
|
201
|
+
button{font:inherit;color:inherit;background:var(--card);border:1px solid var(--line);border-radius:12px;min-height:44px;min-width:44px;padding:0 14px;cursor:pointer}
|
|
202
|
+
button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}`;
|
|
203
|
+
export function buildFlashcardsHtml(args) {
|
|
204
|
+
const payload = embedJsonInScript(args.cards);
|
|
205
|
+
const title = escapeHtml(args.title);
|
|
206
|
+
return `<!DOCTYPE html>
|
|
207
|
+
<html lang="en">
|
|
208
|
+
<head>
|
|
209
|
+
<meta charset="utf-8"/>
|
|
210
|
+
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
|
211
|
+
<title>${title} flashcards</title>
|
|
212
|
+
<style>
|
|
213
|
+
${SHARED_CSS}
|
|
214
|
+
.wrap{max-width:40rem;margin:0 auto;padding:1.25rem 1rem 2.5rem}
|
|
215
|
+
h1{font-size:1.25rem;font-weight:600;margin:0 0 .25rem}
|
|
216
|
+
.sub{color:var(--muted);margin:0 0 1rem;font-size:.9rem}
|
|
217
|
+
.stage{perspective:1200px;min-height:14rem;margin:1rem 0}
|
|
218
|
+
.card{position:relative;min-height:14rem;transform-style:preserve-3d;transition:transform .35s ease;background:transparent;border:0;width:100%;padding:0;border-radius:16px}
|
|
219
|
+
.card.flipped{transform:rotateY(180deg)}
|
|
220
|
+
.face{position:absolute;inset:0;backface-visibility:hidden;background:var(--card);border:1px solid var(--line);border-radius:16px;padding:1.25rem;display:flex;align-items:center;justify-content:center;text-align:center;font-size:1.05rem;line-height:1.45}
|
|
221
|
+
.back{transform:rotateY(180deg)}
|
|
222
|
+
.row{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center}
|
|
223
|
+
#status{color:var(--muted)}
|
|
224
|
+
</style>
|
|
225
|
+
</head>
|
|
226
|
+
<body>
|
|
227
|
+
<div class="wrap">
|
|
228
|
+
<h1>${title} flashcards</h1>
|
|
229
|
+
<p class="sub">Progress is saved so chat can see which cards you know.</p>
|
|
230
|
+
<p id="status" aria-live="polite"></p>
|
|
231
|
+
<div class="stage">
|
|
232
|
+
<button type="button" class="card" id="card" aria-pressed="false">
|
|
233
|
+
<span class="face front" id="front"></span>
|
|
234
|
+
<span class="face back" id="back"></span>
|
|
235
|
+
</button>
|
|
236
|
+
</div>
|
|
237
|
+
<div class="row">
|
|
238
|
+
<button type="button" id="prev">Previous</button>
|
|
239
|
+
<button type="button" id="flip">Flip</button>
|
|
240
|
+
<button type="button" id="next">Next</button>
|
|
241
|
+
<button type="button" id="shuffle">Shuffle</button>
|
|
242
|
+
<button type="button" id="known">Mark known</button>
|
|
243
|
+
</div>
|
|
244
|
+
</div>
|
|
245
|
+
<script type="application/json" id="data">${payload}</script>
|
|
246
|
+
<script>
|
|
247
|
+
(function(){
|
|
248
|
+
var dataEl=document.getElementById("data");
|
|
249
|
+
var cards=dataEl?JSON.parse(dataEl.textContent||"[]"):[];
|
|
250
|
+
if(!cards.length){
|
|
251
|
+
var s=document.getElementById("status");
|
|
252
|
+
if(s)s.textContent="No cards";
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
var i=0,flipped=false,known=[],seen=0;
|
|
256
|
+
var card=document.getElementById("card");
|
|
257
|
+
var front=document.getElementById("front");
|
|
258
|
+
var back=document.getElementById("back");
|
|
259
|
+
var status=document.getElementById("status");
|
|
260
|
+
function decode(raw,fallback){
|
|
261
|
+
if(raw==null||raw==="")return fallback;
|
|
262
|
+
try{return JSON.parse(raw);}catch(e){return fallback;}
|
|
263
|
+
}
|
|
264
|
+
function persist(){
|
|
265
|
+
var st=window.artifactState;
|
|
266
|
+
if(!st)return;
|
|
267
|
+
st.set("index",i);
|
|
268
|
+
st.set("known",known);
|
|
269
|
+
st.set("seen",seen);
|
|
270
|
+
}
|
|
271
|
+
function show(){
|
|
272
|
+
var c=cards[i];
|
|
273
|
+
if(!c||!front||!back||!card||!status)return;
|
|
274
|
+
front.textContent=c.front;
|
|
275
|
+
back.textContent=c.back;
|
|
276
|
+
flipped=false;
|
|
277
|
+
card.classList.remove("flipped");
|
|
278
|
+
card.setAttribute("aria-pressed","false");
|
|
279
|
+
var mark=known.indexOf(c.id)>=0?" · known":"";
|
|
280
|
+
status.textContent=(i+1)+" / "+cards.length+" · seen "+seen+mark;
|
|
281
|
+
}
|
|
282
|
+
function flip(){
|
|
283
|
+
if(!card)return;
|
|
284
|
+
flipped=!flipped;
|
|
285
|
+
card.classList.toggle("flipped",flipped);
|
|
286
|
+
card.setAttribute("aria-pressed",flipped?"true":"false");
|
|
287
|
+
}
|
|
288
|
+
function go(d){
|
|
289
|
+
i=(i+d+cards.length)%cards.length;
|
|
290
|
+
seen+=1;
|
|
291
|
+
persist();
|
|
292
|
+
show();
|
|
293
|
+
}
|
|
294
|
+
function shuffle(){
|
|
295
|
+
for(var n=cards.length-1;n>0;n--){
|
|
296
|
+
var j=Math.floor(Math.random()*(n+1));
|
|
297
|
+
var t=cards[n];
|
|
298
|
+
cards[n]=cards[j];
|
|
299
|
+
cards[j]=t;
|
|
300
|
+
}
|
|
301
|
+
i=0;
|
|
302
|
+
persist();
|
|
303
|
+
show();
|
|
304
|
+
}
|
|
305
|
+
function markKnown(){
|
|
306
|
+
var c=cards[i];
|
|
307
|
+
if(!c)return;
|
|
308
|
+
if(known.indexOf(c.id)<0)known.push(c.id);
|
|
309
|
+
persist();
|
|
310
|
+
show();
|
|
311
|
+
}
|
|
312
|
+
var prev=document.getElementById("prev");
|
|
313
|
+
var next=document.getElementById("next");
|
|
314
|
+
var flipBtn=document.getElementById("flip");
|
|
315
|
+
var shuffleBtn=document.getElementById("shuffle");
|
|
316
|
+
var knownBtn=document.getElementById("known");
|
|
317
|
+
if(card)card.addEventListener("click",flip);
|
|
318
|
+
if(flipBtn)flipBtn.addEventListener("click",function(e){e.stopPropagation();flip();});
|
|
319
|
+
if(prev)prev.addEventListener("click",function(){go(-1);});
|
|
320
|
+
if(next)next.addEventListener("click",function(){go(1);});
|
|
321
|
+
if(shuffleBtn)shuffleBtn.addEventListener("click",shuffle);
|
|
322
|
+
if(knownBtn)knownBtn.addEventListener("click",markKnown);
|
|
323
|
+
document.addEventListener("keydown",function(e){
|
|
324
|
+
if(e.key==="ArrowLeft")go(-1);
|
|
325
|
+
else if(e.key==="ArrowRight")go(1);
|
|
326
|
+
else if(e.key===" "||e.key==="Enter"){e.preventDefault();flip();}
|
|
327
|
+
});
|
|
328
|
+
async function boot(){
|
|
329
|
+
var st=window.artifactState;
|
|
330
|
+
if(st){
|
|
331
|
+
var all=await st.getAll();
|
|
332
|
+
var idx=decode(all&&all.index,0);
|
|
333
|
+
if(typeof idx==="number"&&idx>=0&&idx<cards.length)i=idx;
|
|
334
|
+
var kn=decode(all&&all.known,[]);
|
|
335
|
+
if(Array.isArray(kn))known=kn.filter(function(id){return typeof id==="string";});
|
|
336
|
+
var se=decode(all&&all.seen,0);
|
|
337
|
+
if(typeof se==="number")seen=se;
|
|
338
|
+
}
|
|
339
|
+
show();
|
|
340
|
+
}
|
|
341
|
+
boot();
|
|
342
|
+
})();
|
|
343
|
+
</script>
|
|
344
|
+
</body>
|
|
345
|
+
</html>`;
|
|
346
|
+
}
|
|
347
|
+
export function buildQuizHtml(args) {
|
|
348
|
+
const payload = embedJsonInScript(args.questions);
|
|
349
|
+
const title = escapeHtml(args.title);
|
|
350
|
+
return `<!DOCTYPE html>
|
|
351
|
+
<html lang="en">
|
|
352
|
+
<head>
|
|
353
|
+
<meta charset="utf-8"/>
|
|
354
|
+
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
|
355
|
+
<title>${title} quiz</title>
|
|
356
|
+
<style>
|
|
357
|
+
${SHARED_CSS}
|
|
358
|
+
.wrap{max-width:40rem;margin:0 auto;padding:1.25rem 1rem 2.5rem}
|
|
359
|
+
h1{font-size:1.25rem;font-weight:600;margin:0 0 .25rem}
|
|
360
|
+
.sub{color:var(--muted);margin:0 0 1rem;font-size:.9rem}
|
|
361
|
+
#prompt{font-size:1.05rem;line-height:1.45;margin:0 0 1rem}
|
|
362
|
+
.options{display:flex;flex-direction:column;gap:.5rem;margin:0 0 1rem}
|
|
363
|
+
.options button{text-align:left;width:100%}
|
|
364
|
+
.options button[aria-pressed="true"]{background:var(--accent);color:var(--bg)}
|
|
365
|
+
.options button.correct{outline:2px solid var(--accent)}
|
|
366
|
+
.options button.wrong{opacity:.6}
|
|
367
|
+
.row{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center}
|
|
368
|
+
#status{color:var(--muted);margin:0 0 .75rem}
|
|
369
|
+
#score{font-weight:600;margin:0 0 1rem}
|
|
370
|
+
</style>
|
|
371
|
+
</head>
|
|
372
|
+
<body>
|
|
373
|
+
<div class="wrap">
|
|
374
|
+
<h1>${title} quiz</h1>
|
|
375
|
+
<p class="sub">Answers are saved so chat can tell you how you did.</p>
|
|
376
|
+
<p id="status" aria-live="polite"></p>
|
|
377
|
+
<p id="score" aria-live="polite"></p>
|
|
378
|
+
<p id="prompt"></p>
|
|
379
|
+
<div class="options" id="options" role="group"></div>
|
|
380
|
+
<div class="row">
|
|
381
|
+
<button type="button" id="prev">Previous</button>
|
|
382
|
+
<button type="button" id="next">Next</button>
|
|
383
|
+
<button type="button" id="submit">Submit</button>
|
|
384
|
+
<button type="button" id="retry">Retry</button>
|
|
385
|
+
</div>
|
|
386
|
+
</div>
|
|
387
|
+
<script type="application/json" id="data">${payload}</script>
|
|
388
|
+
<script>
|
|
389
|
+
(function(){
|
|
390
|
+
var dataEl=document.getElementById("data");
|
|
391
|
+
var questions=dataEl?JSON.parse(dataEl.textContent||"[]"):[];
|
|
392
|
+
if(!questions.length){
|
|
393
|
+
var s=document.getElementById("status");
|
|
394
|
+
if(s)s.textContent="No questions";
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
var i=0,answers={},submitted=false,score=0;
|
|
398
|
+
var promptEl=document.getElementById("prompt");
|
|
399
|
+
var optionsEl=document.getElementById("options");
|
|
400
|
+
var status=document.getElementById("status");
|
|
401
|
+
var scoreEl=document.getElementById("score");
|
|
402
|
+
function decode(raw,fallback){
|
|
403
|
+
if(raw==null||raw==="")return fallback;
|
|
404
|
+
try{return JSON.parse(raw);}catch(e){return fallback;}
|
|
405
|
+
}
|
|
406
|
+
function persist(){
|
|
407
|
+
var st=window.artifactState;
|
|
408
|
+
if(!st)return;
|
|
409
|
+
st.set("answers",answers);
|
|
410
|
+
st.set("currentIndex",i);
|
|
411
|
+
st.set("submitted",submitted);
|
|
412
|
+
st.set("score",score);
|
|
413
|
+
st.set("total",questions.length);
|
|
414
|
+
}
|
|
415
|
+
function tally(){
|
|
416
|
+
var n=0;
|
|
417
|
+
for(var q=0;q<questions.length;q++){
|
|
418
|
+
var item=questions[q];
|
|
419
|
+
if(item&&answers[item.id]===item.correctIndex)n+=1;
|
|
420
|
+
}
|
|
421
|
+
return n;
|
|
422
|
+
}
|
|
423
|
+
function render(){
|
|
424
|
+
var q=questions[i];
|
|
425
|
+
if(!q||!promptEl||!optionsEl||!status||!scoreEl)return;
|
|
426
|
+
promptEl.textContent=q.prompt;
|
|
427
|
+
status.textContent=(i+1)+" / "+questions.length;
|
|
428
|
+
scoreEl.textContent=submitted?("Score "+score+" / "+questions.length):"";
|
|
429
|
+
optionsEl.innerHTML="";
|
|
430
|
+
for(var n=0;n<q.options.length;n++){
|
|
431
|
+
var btn=document.createElement("button");
|
|
432
|
+
btn.type="button";
|
|
433
|
+
btn.textContent=q.options[n];
|
|
434
|
+
var chosen=answers[q.id];
|
|
435
|
+
btn.setAttribute("aria-pressed",chosen===n?"true":"false");
|
|
436
|
+
if(submitted){
|
|
437
|
+
if(n===q.correctIndex)btn.className="correct";
|
|
438
|
+
else if(chosen===n)btn.className="wrong";
|
|
439
|
+
}
|
|
440
|
+
btn.addEventListener("click",(function(idx){
|
|
441
|
+
return function(){
|
|
442
|
+
if(submitted)return;
|
|
443
|
+
answers[q.id]=idx;
|
|
444
|
+
persist();
|
|
445
|
+
render();
|
|
446
|
+
};
|
|
447
|
+
})(n));
|
|
448
|
+
optionsEl.appendChild(btn);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
function go(d){
|
|
452
|
+
i=Math.max(0,Math.min(questions.length-1,i+d));
|
|
453
|
+
persist();
|
|
454
|
+
render();
|
|
455
|
+
}
|
|
456
|
+
var prev=document.getElementById("prev");
|
|
457
|
+
var next=document.getElementById("next");
|
|
458
|
+
var submitBtn=document.getElementById("submit");
|
|
459
|
+
var retryBtn=document.getElementById("retry");
|
|
460
|
+
if(prev)prev.addEventListener("click",function(){go(-1);});
|
|
461
|
+
if(next)next.addEventListener("click",function(){go(1);});
|
|
462
|
+
if(submitBtn)submitBtn.addEventListener("click",function(){
|
|
463
|
+
submitted=true;
|
|
464
|
+
score=tally();
|
|
465
|
+
persist();
|
|
466
|
+
render();
|
|
467
|
+
});
|
|
468
|
+
if(retryBtn)retryBtn.addEventListener("click",function(){
|
|
469
|
+
answers={};
|
|
470
|
+
submitted=false;
|
|
471
|
+
score=0;
|
|
472
|
+
i=0;
|
|
473
|
+
persist();
|
|
474
|
+
render();
|
|
475
|
+
});
|
|
476
|
+
async function boot(){
|
|
477
|
+
var st=window.artifactState;
|
|
478
|
+
if(st){
|
|
479
|
+
var all=await st.getAll();
|
|
480
|
+
var idx=decode(all&&all.currentIndex,0);
|
|
481
|
+
if(typeof idx==="number"&&idx>=0&&idx<questions.length)i=idx;
|
|
482
|
+
var ans=decode(all&&all.answers,{});
|
|
483
|
+
if(ans&&typeof ans==="object")answers=ans;
|
|
484
|
+
submitted=!!decode(all&&all.submitted,false);
|
|
485
|
+
var sc=decode(all&&all.score,0);
|
|
486
|
+
if(typeof sc==="number")score=sc;
|
|
487
|
+
else score=tally();
|
|
488
|
+
}
|
|
489
|
+
render();
|
|
490
|
+
}
|
|
491
|
+
boot();
|
|
492
|
+
})();
|
|
493
|
+
</script>
|
|
494
|
+
</body>
|
|
495
|
+
</html>`;
|
|
496
|
+
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# Artifacts core (`@vvedantb/server`)
|
|
2
|
+
|
|
3
|
+
The backend-safe core for artifacts: standalone documents (HTML, Markdown, SVG, code, or typed JSON such as a quiz) that run offline in a sandboxed iframe or WebView and keep per-user state through a small bridge. Everything here is plain strings and data. There is no DOM, no React, and no Convex import, so the same code runs in a Convex V8 function, a Node server, a browser and React Native.
|
|
4
|
+
|
|
5
|
+
- **Contract**: Zod schemas for the artifact type and format, the state spec, typed bodies (`quizBodyV1`, `flashcardsBodyV1`), and list/detail rows. Built with your `z`.
|
|
6
|
+
- **State**: limits, the pure ops the host and the server both apply, storage-shim prefixes, and the host's save debounce.
|
|
7
|
+
- **Rendering**: the built-in quiz and flashcards pages, the document wrapper with its CSP, and the guest bootstrap.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { createArtifactSchemas, wrapArtifactDocument } from "@vvedantb/server";
|
|
12
|
+
|
|
13
|
+
const artifacts = createArtifactSchemas(z);
|
|
14
|
+
|
|
15
|
+
// Server: check a body before saving it.
|
|
16
|
+
const checked = artifacts.validateArtifactBody("quiz", "json", body, 1);
|
|
17
|
+
if (!checked.ok) throw new Error(checked.error);
|
|
18
|
+
|
|
19
|
+
// Client: build the iframe srcdoc from the row, its body and the user's state.
|
|
20
|
+
iframe.srcdoc = wrapArtifactDocument(body, row.format, state.data, {
|
|
21
|
+
title: row.title,
|
|
22
|
+
template: row.stateSpec?.template,
|
|
23
|
+
stateGlobalAliases: ["app"], // optional: window.app.state works as well as window.artifactState
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Contract
|
|
28
|
+
|
|
29
|
+
`createArtifactSchemas(z)` takes zod 3.25+ or 4 (zod is an optional peer and the package never imports it) and returns:
|
|
30
|
+
|
|
31
|
+
| Schema | Shape |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| `artifactType` | `ARTIFACT_TYPES`: `document`, `report`, `slides`, `infographic`, `mindmap`, `quiz`, `flashcards`, `diagram`, `code`. What the artifact is, for filters and icons. |
|
|
34
|
+
| `artifactFormat` | `ARTIFACT_FORMATS`: `html`, `markdown`, `svg`, `code`, `json`. How the body renders. |
|
|
35
|
+
| `stateSpec` | `{ stateVersion: int ≥ 1, keys: string[] (≤ 32, each 1–64 chars), template?: "quiz" \| "flashcards" }` |
|
|
36
|
+
| `quizBodyV1` | `{ title, questions: [{ id, prompt, options: 2–5 strings, correctIndex }] }` (≥ 1 question; `correctIndex` must point at an option) |
|
|
37
|
+
| `flashcardsBodyV1` | `{ title, cards: [{ id, front, back }] }` (≥ 1 card) |
|
|
38
|
+
| `listRow` | `ArtifactListRow`: `id`, `title` (1–200 chars), `description?` (≤ 280), `type`, `format`, `language?`, `schemaVersion`, `stateSpec?`, `currentVersion`, `size` (bytes), `origin: { client, externalId? }`, `createdAt`, `updatedAt`, `teamId?`. Metadata only. |
|
|
39
|
+
| `detailRow` | `ArtifactDetailRow`: a list row plus `body` (≤ 400,000 chars). |
|
|
40
|
+
|
|
41
|
+
Strings in the typed bodies are trimmed and must not be empty. Objects strip unknown keys. Ids are strings, so the rows work for any store and any client. `origin.client` is a free string naming the writer, not an enum.
|
|
42
|
+
|
|
43
|
+
`validateArtifactBody(type, format, body, schemaVersion = 1)` returns `{ ok: true, json? }` or `{ ok: false, error }`:
|
|
44
|
+
|
|
45
|
+
- Any body over `ARTIFACT_BODY_MAX_CHARS` (400,000 characters) fails.
|
|
46
|
+
- `json` is only valid for the types in `ARTIFACT_JSON_TYPES` (`quiz` and `flashcards`, version 1). The body must parse and match the typed schema; `json` is the parsed body.
|
|
47
|
+
- Other formats are strings and pass once under the cap.
|
|
48
|
+
|
|
49
|
+
## State
|
|
50
|
+
|
|
51
|
+
State is a `Record<string, string>` per user, per artifact. The guest JSON-encodes values. The host keeps a copy, answers the guest from it, and saves it through its own store. The server applies the same ops and limits, so a write the host accepted is never refused for size.
|
|
52
|
+
|
|
53
|
+
| Limit | Value |
|
|
54
|
+
| --- | --- |
|
|
55
|
+
| `ARTIFACT_STATE_MAX_KEYS` | 32 keys |
|
|
56
|
+
| `ARTIFACT_STATE_MAX_KEY_LENGTH` | 64 characters (after trimming) |
|
|
57
|
+
| `ARTIFACT_STATE_MAX_VALUE_BYTES` | 16 KiB per value (UTF-8) |
|
|
58
|
+
| `ARTIFACT_STATE_MAX_TOTAL_BYTES` | 64 KiB in total, keys included (UTF-8) |
|
|
59
|
+
| `ARTIFACT_STATE_MIN_WRITE_INTERVAL_MS` | 1 s between server writes for one artifact and user |
|
|
60
|
+
| `ARTIFACT_STATE_DAILY_WRITES` | `{ free: 400, pro: 4000 }` writes per user per UTC day (`utcDayKey(now)`, for example `20261022`) |
|
|
61
|
+
| `ARTIFACT_STATE_DEBOUNCE_MS`, `ARTIFACT_STATE_MAX_WAIT_MS` | the host saves 5 s after the last change, and at least every 30 s while changes keep coming |
|
|
62
|
+
| `ARTIFACT_VERSION_KEEP` | 10 versions kept per artifact |
|
|
63
|
+
|
|
64
|
+
The package holds the numbers only. Enforcing the write interval and daily caps is the server's job, since it holds the counters.
|
|
65
|
+
|
|
66
|
+
- `applyArtifactStateOp(current, op)`: one guest op (`get`, `set`, `getAll`, `remove`, `reset`). Returns `{ data, value, error? }`. On an error, `data` is `current`.
|
|
67
|
+
- `applyArtifactStatePatch(current, { sets?, removes?, reset? })`: a batched write, applied as reset, then sets, then removes. All or nothing: on an error, `data` is `current`.
|
|
68
|
+
- `validateArtifactStateMap(data)`: the first limit broken, or `undefined`.
|
|
69
|
+
- `parseArtifactStateOp(message)`: the op in a guest message, or `undefined` when it is malformed.
|
|
70
|
+
- `createTrailingMaxDebounce(flush, trailingMs?, maxMs?, timers?)`: `{ schedule, flushNow, cancel, isPending }`. Call `flushNow()` on `pagehide` and when the frame unmounts.
|
|
71
|
+
- Storage shims: the guest's `localStorage` and `sessionStorage` live in the same map under `ARTIFACT_LOCAL_STORAGE_PREFIX` (`ls:`) and `ARTIFACT_SESSION_STORAGE_PREFIX` (`ss:`). `storageView`, `clearPrefixedKeys`, `prefixedStorageKey` and `unprefixStorageKey` read and edit them.
|
|
72
|
+
|
|
73
|
+
## Rendering
|
|
74
|
+
|
|
75
|
+
`wrapArtifactDocument(body, format, snapshot?, options?)` returns the `srcdoc`:
|
|
76
|
+
|
|
77
|
+
| Format | Document |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| `html` | The page as is when it has `<html`; otherwise wrapped in a minimal page. |
|
|
80
|
+
| `svg` | Centred on a white page. |
|
|
81
|
+
| `markdown`, `code` | Escaped text in a `<pre>`. Render Markdown in the host when you want formatting. |
|
|
82
|
+
| `json` | The built-in quiz or flashcards page; escaped text when the body does not parse. |
|
|
83
|
+
|
|
84
|
+
`options.template` (from `stateSpec.template`) is tried first for any format, so an older HTML-format body that holds quiz JSON still renders. `options.title` is the heading when the body has none (default "Artifact"). `options.stateGlobalAliases` is passed to the guest (see below).
|
|
85
|
+
|
|
86
|
+
The CSP meta tag and the guest script go at the start of `<head>`. `ARTIFACT_CSP` allows inline scripts and styles, and `data:`/`blob:` images, fonts and media. It blocks every network request, frames, objects, forms and `<base>`. Render the document in an iframe with `sandbox="allow-scripts"` and **no** `allow-same-origin`, or in a WebView with the same isolation.
|
|
87
|
+
|
|
88
|
+
`wrapArtifactHtml(html, snapshot?, options?)` does the injection step only, for a document you built yourself. `artifactGuestScript(snapshot?, options?)` is the inline script alone (snapshot, aliases, then `GUEST_BOOTSTRAP_SCRIPT`), for a React Native WebView's `injectedJavaScriptBeforeContentLoaded`.
|
|
89
|
+
|
|
90
|
+
`buildQuizHtml({ title, questions })` and `buildFlashcardsHtml({ title, cards })` build the offline pages. They keep progress in `window.artifactState` (quiz: `answers`, `currentIndex`, `submitted`, `score`, `total`; flashcards: `index`, `known`, `seen`). `htmlFromArtifactTemplate({ title, content, template? })` parses `content` and builds the page, or returns `undefined`. Its parsers (`parseQuizTemplate`, `parseFlashcardsTemplate`) are lenient so older bodies still render without zod: they also take a bare array, `question` for `prompt`, and missing ids. Use `validateArtifactBody` for writes.
|
|
91
|
+
|
|
92
|
+
Download helpers: `ARTIFACT_FORMAT_FILES[format]` gives `{ extension, mime }`, and `artifactFileName(title, format)` a safe file name. `formatFromLanguage(language)` maps a code-fence language to a format (`html`/`htm`, `svg`, `md`/`markdown`, otherwise `code`).
|
|
93
|
+
|
|
94
|
+
## Bridge protocol
|
|
95
|
+
|
|
96
|
+
1. The guest bootstrap runs first. It reads `window.__ARTIFACT_SNAPSHOT__` and `window.__ARTIFACT_ALIASES__` (set by `artifactGuestScript`), deletes them, and posts `{ type: "artifact:ready" }` to the parent.
|
|
97
|
+
2. The host checks `event.source` is its frame, creates a `MessageChannel`, and posts `{ type: "artifact:port" }` with `port2`.
|
|
98
|
+
3. The guest sends `{ type: "artifact:state", requestId, op, key?, value? }` on the port. The host parses it with `parseArtifactStateOp`, applies it with `applyArtifactStateOp`, schedules a save after `set`, `remove` or `reset`, and answers `{ type: "artifact:state-result", requestId, ok, value?, error? }`.
|
|
99
|
+
|
|
100
|
+
In a React Native WebView the guest sends through `window.ReactNativeWebView.postMessage` (JSON strings) and the host answers with `artifact:state-result` window messages. The constants are `ARTIFACT_READY_TYPE`, `ARTIFACT_PORT_TYPE`, `ARTIFACT_STATE_TYPE` and `ARTIFACT_STATE_RESULT_TYPE`.
|
|
101
|
+
|
|
102
|
+
The guest API, with promises and JSON values:
|
|
103
|
+
|
|
104
|
+
```js
|
|
105
|
+
await window.artifactState.set("score", 3);
|
|
106
|
+
const all = await window.artifactState.getAll(); // { score: "3", ... } raw strings
|
|
107
|
+
await window.artifactState.get("score"); // "3"
|
|
108
|
+
await window.artifactState.remove("score");
|
|
109
|
+
await window.artifactState.reset();
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The guest checks the limits before sending, so an over-quota `set` rejects (and `localStorage.setItem` throws `QuotaExceededError`) without reaching the host.
|
|
113
|
+
|
|
114
|
+
### Aliases
|
|
115
|
+
|
|
116
|
+
An app whose existing artifacts call another global (for example `window.app.state`) passes `stateGlobalAliases: ["app"]`. Each alias becomes `window[alias] = { state }`, with the same `state` object as `window.artifactState`. Aliases must be JavaScript identifiers and must not name a global the page or the bootstrap needs (`window`, `document`, `localStorage`, `artifactState`, …). `assertStateGlobalAliases` throws on a bad one, and the wrappers call it.
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vvedantb/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"license": "MIT",
|
|
5
|
-
"description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP OAuth client helpers from one root import: query-limit errors, Clerk auth and token verification, Clerk-user lookups and ensure-user for Convex functions, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools, WebCrypto primitives, Convex optimistic-update helpers, MCP OAuth client helpers (provider, sign-in, refresh, revocation, loopback redirect server) for desktop apps,
|
|
5
|
+
"description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP OAuth client helpers from one root import: query-limit errors, Clerk auth and token verification, Clerk-user lookups and ensure-user for Convex functions, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools, WebCrypto primitives, Convex optimistic-update helpers, MCP OAuth client helpers (provider, sign-in, refresh, revocation, loopback redirect server) for desktop apps, a QuickJS code sandbox that bridges script tool calls to host handlers, and a pure artifacts core (Zod contract, state limits and ops, quiz and flashcards pages, a sandboxed document wrapper with CSP and a guest state bridge).",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"publishConfig": {
|
|
8
8
|
"access": "public"
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
},
|
|
22
22
|
"files": [
|
|
23
23
|
"dist",
|
|
24
|
+
"docs/artifacts.md",
|
|
24
25
|
"docs/convex.md",
|
|
25
26
|
"docs/crypto.md",
|
|
26
27
|
"docs/mcp.md",
|