joycraft 0.7.17 → 1.0.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/README.md +148 -140
- package/dist/cli.js +1593 -373
- package/dist/cli.js.map +1 -1
- package/dist/joycraft-release.json +1 -1
- package/package.json +9 -3
- package/payload/.agents/skills/joycraft-context/SKILL.md +36 -0
- package/payload/.agents/skills/joycraft-decompose/SKILL.md +68 -0
- package/payload/.agents/skills/joycraft-entry/SKILL.md +109 -0
- package/payload/.agents/skills/joycraft-implement/SKILL.md +118 -0
- package/payload/.agents/skills/joycraft-retro/SKILL.md +54 -0
- package/payload/.agents/skills/joycraft-retro/agents/openai.yaml +5 -0
- package/payload/.agents/skills/joycraft-session-end/SKILL.md +82 -0
- package/payload/.agents/skills/joycraft-testing/SKILL.md +60 -0
- package/payload/.agents/skills/joycraft-ui-slice/SKILL.md +59 -0
- package/payload/.agents/skills/joycraft-ui-slice/scripts/serve.mjs +97 -0
- package/payload/.agents/skills/joycraft-verify/SKILL.md +103 -0
- package/payload/.claude/agents/joycraft-implementer.md +36 -0
- package/payload/.claude/agents/joycraft-reviewer.md +35 -0
- package/payload/.joycraft/assets/artifacts/kit.css +102 -0
- package/payload/.joycraft/assets/artifacts/kit.js +301 -0
- package/payload/.joycraft/assets/artifacts/transports.js +236 -0
- package/payload/.joycraft/contracts/types.d.ts +185 -0
- package/payload/.joycraft/references/architecture.md +90 -0
- package/payload/.joycraft/references/archive.md +211 -0
- package/payload/.joycraft/references/artifacts.md +176 -0
- package/payload/.joycraft/references/completion.md +109 -0
- package/payload/.joycraft/references/context.md +85 -0
- package/payload/.joycraft/references/delivery.md +32 -0
- package/payload/.joycraft/references/dispatch.md +231 -0
- package/payload/.joycraft/references/recurring-failures.md +33 -0
- package/payload/.joycraft/references/retro.md +94 -0
- package/payload/.joycraft/references/setup.md +295 -0
- package/payload/.joycraft/references/testing.md +120 -0
- package/payload/.joycraft/references/update.md +44 -0
- package/payload/.joycraft/references/workflow.md +113 -0
- package/payload/.joycraft/references/worktrees.md +174 -0
- package/payload/.joycraft/runtime/archive.mjs +463 -0
- package/payload/.joycraft/runtime/artifacts/cli.mjs +61 -0
- package/payload/.joycraft/runtime/artifacts/decisions.mjs +214 -0
- package/payload/.joycraft/runtime/artifacts/model.mjs +161 -0
- package/payload/.joycraft/runtime/artifacts/preferences.mjs +127 -0
- package/payload/.joycraft/runtime/artifacts/render.mjs +21 -0
- package/payload/.joycraft/runtime/artifacts/server.mjs +40 -0
- package/payload/.joycraft/runtime/completion.mjs +300 -0
- package/payload/.joycraft/runtime/context/cli.mjs +75 -0
- package/payload/.joycraft/runtime/context/index.mjs +29 -0
- package/payload/.joycraft/runtime/context/search.mjs +149 -0
- package/payload/.joycraft/runtime/coordinator.mjs +169 -0
- package/payload/.joycraft/runtime/delivery.mjs +142 -0
- package/payload/.joycraft/runtime/dispatch-preflight.mjs +535 -0
- package/payload/.joycraft/runtime/dispatch-start.mjs +106 -0
- package/payload/.joycraft/runtime/evidence.mjs +137 -0
- package/payload/.joycraft/runtime/identity.mjs +486 -0
- package/payload/.joycraft/runtime/kickoff.mjs +174 -0
- package/payload/.joycraft/runtime/redact.mjs +9 -0
- package/payload/.joycraft/runtime/retro.mjs +151 -0
- package/payload/.joycraft/runtime/review-tools.json +34 -0
- package/payload/.joycraft/runtime/review-tools.mjs +331 -0
- package/payload/.joycraft/runtime/scope.mjs +129 -0
- package/payload/.joycraft/runtime/status.mjs +96 -0
- package/payload/.joycraft/runtime/update-check.mjs +142 -0
- package/payload/.joycraft/runtime/worktrees.mjs +201 -0
- package/payload/.joycraft/templates/README.md +7 -0
- package/payload/.joycraft/templates/artifact.json +33 -0
- package/payload/.joycraft/templates/brief.md +35 -0
- package/payload/.joycraft/templates/decisions.md +13 -0
- package/payload/.joycraft/templates/project-context.md +36 -0
- package/payload/.joycraft/templates/queue.json +27 -0
- package/payload/.joycraft/templates/spec.md +39 -0
- package/payload/.joycraft/templates/ui-slice.html +71 -0
- package/payload/PIN +77 -0
- package/payload/scripts/export.mjs +301 -0
- package/payload/scripts/hook-paths.mjs +35 -0
- package/payload/scripts/legacy-hooks.mjs +128 -0
- package/payload/scripts/legacy-inventory.json +117 -0
- package/dist/chunk-35RQLGKM.js +0 -2167
- package/dist/chunk-35RQLGKM.js.map +0 -1
- package/dist/chunk-7BPB2IKY.js +0 -255
- package/dist/chunk-7BPB2IKY.js.map +0 -1
- package/dist/chunk-B73DPYYC.js +0 -377
- package/dist/chunk-B73DPYYC.js.map +0 -1
- package/dist/chunk-K4AI6FKB.js +0 -417
- package/dist/chunk-K4AI6FKB.js.map +0 -1
- package/dist/chunk-KKDKC4FM.js +0 -115
- package/dist/chunk-KKDKC4FM.js.map +0 -1
- package/dist/chunk-OMFGDJW4.js +0 -97
- package/dist/chunk-OMFGDJW4.js.map +0 -1
- package/dist/chunk-YLWBDXF4.js +0 -3999
- package/dist/chunk-YLWBDXF4.js.map +0 -1
- package/dist/chunk-Z5JFEGWG.js +0 -563
- package/dist/chunk-Z5JFEGWG.js.map +0 -1
- package/dist/init-O2QC5X57.js +0 -60
- package/dist/init-O2QC5X57.js.map +0 -1
- package/dist/init-autofix-2DMBO4QN.js +0 -122
- package/dist/init-autofix-2DMBO4QN.js.map +0 -1
- package/dist/install-manifest-EQHT4474.js +0 -37
- package/dist/install-manifest-EQHT4474.js.map +0 -1
- package/dist/release-artifact-4TL5L2ZY.js +0 -14
- package/dist/release-artifact-4TL5L2ZY.js.map +0 -1
- package/dist/release-resolver-P2H46QTU.js +0 -293
- package/dist/release-resolver-P2H46QTU.js.map +0 -1
- package/dist/telemetry-store-IBO5GRTA.js +0 -14
- package/dist/telemetry-store-IBO5GRTA.js.map +0 -1
- package/dist/update-LYHS4FBH.js +0 -21
- package/dist/update-LYHS4FBH.js.map +0 -1
- package/dist/update-check-YT765NE7.js +0 -36
- package/dist/update-check-YT765NE7.js.map +0 -1
- package/dist/upgrade-GMP6JQ52.js +0 -28
- package/dist/upgrade-GMP6JQ52.js.map +0 -1
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const states = new Set(['open', 'clarified', 'backlogged', 'discarded', 'assigned']);
|
|
4
|
+
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
5
|
+
const nonempty = value => typeof value === 'string' && value.trim().length > 0;
|
|
6
|
+
|
|
7
|
+
/** Maximum UTF-16 code units accepted for a human decision note. */
|
|
8
|
+
export const MAX_NOTE_LENGTH = 4_000;
|
|
9
|
+
|
|
10
|
+
function readValueEnd(text, start, limit) {
|
|
11
|
+
let quoted = false, escaped = false, depth = 0;
|
|
12
|
+
for (let index = start; index < limit; index += 1) {
|
|
13
|
+
const char = text[index];
|
|
14
|
+
if (quoted) {
|
|
15
|
+
if (escaped) escaped = false;
|
|
16
|
+
else if (char === '\\') escaped = true;
|
|
17
|
+
else if (char === '"') quoted = false;
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (char === '"') quoted = true;
|
|
21
|
+
else if (char === '{' || char === '[') depth += 1;
|
|
22
|
+
else if (char === '}' || char === ']') {
|
|
23
|
+
depth -= 1;
|
|
24
|
+
if (depth === 0) return index + 1;
|
|
25
|
+
} else if (depth === 0 && (char === ',' || /\s/.test(char))) return index;
|
|
26
|
+
}
|
|
27
|
+
return limit;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function decisionSpans(text, start, end) {
|
|
31
|
+
const spans = [];
|
|
32
|
+
let index = start + 1;
|
|
33
|
+
while (index < end - 1) {
|
|
34
|
+
while (/\s/.test(text[index])) index += 1;
|
|
35
|
+
if (text[index] === ']') break;
|
|
36
|
+
const valueStart = index;
|
|
37
|
+
const valueEnd = readValueEnd(text, valueStart, end);
|
|
38
|
+
spans.push({ start: valueStart, end: valueEnd });
|
|
39
|
+
index = valueEnd;
|
|
40
|
+
while (/\s/.test(text[index])) index += 1;
|
|
41
|
+
if (text[index] === ',') index += 1;
|
|
42
|
+
else if (text[index] !== ']') throw new Error('Malformed decisions array');
|
|
43
|
+
}
|
|
44
|
+
return spans;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Read the documented JSON flow array without interpreting/reformatting other YAML. */
|
|
48
|
+
export function readBrief(text) {
|
|
49
|
+
if (typeof text !== 'string') throw new Error('Brief text must be a string');
|
|
50
|
+
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
|
51
|
+
if (!frontmatter) throw new Error('Brief needs YAML frontmatter');
|
|
52
|
+
const body = frontmatter[1];
|
|
53
|
+
const keys = [...body.matchAll(/^decisions:[ \t]*/gm)];
|
|
54
|
+
if (keys.length !== 1) throw new Error('Expected one top-level decisions: JSON flow array');
|
|
55
|
+
const start = frontmatter[0].indexOf(body) + keys[0].index + keys[0][0].length;
|
|
56
|
+
if (text[start] !== '[') throw new Error('decisions: must use the documented JSON flow array');
|
|
57
|
+
let depth = 0, quoted = false, escaped = false, end = -1;
|
|
58
|
+
for (let index = start; index < frontmatter[0].length; index += 1) {
|
|
59
|
+
const char = text[index];
|
|
60
|
+
if (quoted) {
|
|
61
|
+
if (escaped) escaped = false;
|
|
62
|
+
else if (char === '\\') escaped = true;
|
|
63
|
+
else if (char === '"') quoted = false;
|
|
64
|
+
} else if (char === '"') quoted = true;
|
|
65
|
+
else if (char === '[') depth += 1;
|
|
66
|
+
else if (char === ']' && --depth === 0) { end = index + 1; break; }
|
|
67
|
+
}
|
|
68
|
+
if (end < 0 || !/^[ \t]*(?:\r?\n|$)/.test(text.slice(end))) throw new Error('Malformed decisions array');
|
|
69
|
+
let decisions;
|
|
70
|
+
try { decisions = JSON.parse(text.slice(start, end)); }
|
|
71
|
+
catch { throw new Error('Malformed decisions JSON'); }
|
|
72
|
+
if (!Array.isArray(decisions)) throw new Error('decisions: must be a JSON array');
|
|
73
|
+
const spans = decisionSpans(text, start, end);
|
|
74
|
+
if (spans.length !== decisions.length) throw new Error('Malformed decisions array');
|
|
75
|
+
const ids = new Set();
|
|
76
|
+
for (const decision of decisions) {
|
|
77
|
+
if (!decision || typeof decision !== 'object' || Array.isArray(decision) || !nonempty(decision.id) || ids.has(decision.id) || !states.has(decision.status)) {
|
|
78
|
+
throw new Error('Invalid or duplicate decision ID/status');
|
|
79
|
+
}
|
|
80
|
+
ids.add(decision.id);
|
|
81
|
+
}
|
|
82
|
+
return { text, decisions, start, end, spans, revision: digest(text) };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function validateOptionalString(value, name) {
|
|
86
|
+
if (value !== undefined && typeof value !== 'string') throw new Error(`${name} must be a string`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function displayedDecision(brief, id) {
|
|
90
|
+
const index = brief.decisions.findIndex(item => item.id === id);
|
|
91
|
+
const decision = brief.decisions[index];
|
|
92
|
+
if (!decision || !nonempty(decision.question) || !Array.isArray(decision.options) || decision.options.length < 2 ||
|
|
93
|
+
!Array.isArray(decision.affected) || !decision.affected.every(nonempty)) {
|
|
94
|
+
throw new Error('Displayed decision needs question, options and affected references');
|
|
95
|
+
}
|
|
96
|
+
for (const field of ['why', 'context', 'details']) validateOptionalString(decision[field], `Decision ${field}`);
|
|
97
|
+
const values = new Set();
|
|
98
|
+
for (const option of decision.options) {
|
|
99
|
+
if (!option || typeof option !== 'object' || Array.isArray(option) || !nonempty(option.value) || !nonempty(option.label) || values.has(option.value)) {
|
|
100
|
+
throw new Error('Invalid decision options');
|
|
101
|
+
}
|
|
102
|
+
validateOptionalString(option.description, 'Option description');
|
|
103
|
+
if (option.requiresNote !== undefined && typeof option.requiresNote !== 'boolean') throw new Error('Option requiresNote must be boolean');
|
|
104
|
+
values.add(option.value);
|
|
105
|
+
}
|
|
106
|
+
if (!(decision.answer === null || values.has(decision.answer)) || (decision.status === 'clarified' && decision.answer === null)) {
|
|
107
|
+
throw new Error('Invalid decision answer');
|
|
108
|
+
}
|
|
109
|
+
validateOptionalString(decision.note, 'Decision note');
|
|
110
|
+
if (decision.note !== undefined && decision.note.length > MAX_NOTE_LENGTH) throw new Error('Decision note is too long');
|
|
111
|
+
return { decision, index };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function publicQuestion(decision) {
|
|
115
|
+
const question = {
|
|
116
|
+
id: decision.id,
|
|
117
|
+
question: decision.question,
|
|
118
|
+
options: decision.options.map(option => {
|
|
119
|
+
const result = { value: option.value, label: option.label };
|
|
120
|
+
if (option.description !== undefined) result.description = option.description;
|
|
121
|
+
if (option.requiresNote !== undefined) result.requiresNote = option.requiresNote;
|
|
122
|
+
return result;
|
|
123
|
+
}),
|
|
124
|
+
affected: [...decision.affected],
|
|
125
|
+
status: decision.status,
|
|
126
|
+
answer: decision.answer
|
|
127
|
+
};
|
|
128
|
+
for (const field of ['why', 'context', 'details']) if (decision[field] !== undefined) question[field] = decision[field];
|
|
129
|
+
if (decision.note !== undefined) question.note = decision.note;
|
|
130
|
+
return question;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Return a render-safe view of requested decisions, including settled choices. */
|
|
134
|
+
export function questionsFromBrief(text, ids) {
|
|
135
|
+
const brief = readBrief(text);
|
|
136
|
+
if (ids !== undefined && (!Array.isArray(ids) || ids.some(id => !nonempty(id)) || new Set(ids).size !== ids.length)) {
|
|
137
|
+
throw new Error('Question IDs must be unique non-empty strings');
|
|
138
|
+
}
|
|
139
|
+
const requested = ids === undefined ? brief.decisions.map(decision => decision.id) : ids;
|
|
140
|
+
const questions = requested.map(id => publicQuestion(displayedDecision(brief, id).decision));
|
|
141
|
+
return { revision: brief.revision, questions };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Select an explicitly requested decision, or the first unanswered choice. */
|
|
145
|
+
export function selectPreviewDecision(brief, id) {
|
|
146
|
+
if (!brief || !Array.isArray(brief.decisions)) throw new Error('Invalid brief');
|
|
147
|
+
if (id) return displayedDecision(brief, id).decision;
|
|
148
|
+
const decision = brief.decisions.find(item => ['open', 'assigned'].includes(item.status) && item.answer === null);
|
|
149
|
+
return decision ? displayedDecision(brief, decision.id).decision : null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function responseNote(response) {
|
|
153
|
+
if (!Object.hasOwn(response, 'note') || response.note === undefined) return undefined;
|
|
154
|
+
if (typeof response.note !== 'string') throw new Error('Decision note must be a string');
|
|
155
|
+
if (response.note.length > MAX_NOTE_LENGTH) throw new Error('Decision note is too long');
|
|
156
|
+
return response.note;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function sameAnswer(decision, answer, note) {
|
|
160
|
+
return decision.answer === answer && decision.note === note;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Atomically save one or more canonical decision answers. Every response is
|
|
165
|
+
* validated before the JSON spans are replaced, so failures leave `text` intact.
|
|
166
|
+
*/
|
|
167
|
+
export function saveAnswers(text, request) {
|
|
168
|
+
const brief = readBrief(text);
|
|
169
|
+
if (!request || typeof request !== 'object' || Array.isArray(request) || request.revision !== brief.revision || !Array.isArray(request.answers) || request.answers.length === 0) {
|
|
170
|
+
throw new Error(request?.revision !== brief.revision ? 'Brief changed. Reload before choosing.' : 'Answers must be a non-empty array');
|
|
171
|
+
}
|
|
172
|
+
const ids = new Set();
|
|
173
|
+
const changes = [];
|
|
174
|
+
for (const response of request.answers) {
|
|
175
|
+
if (!response || typeof response !== 'object' || Array.isArray(response) || !nonempty(response.id) || !nonempty(response.answer) || ids.has(response.id)) {
|
|
176
|
+
throw new Error('Responses need unique decision IDs and choices');
|
|
177
|
+
}
|
|
178
|
+
ids.add(response.id);
|
|
179
|
+
const { decision, index } = displayedDecision(brief, response.id);
|
|
180
|
+
const option = decision.options.find(item => item.value === response.answer);
|
|
181
|
+
if (!option) throw new Error('Unknown choice');
|
|
182
|
+
const note = responseNote(response);
|
|
183
|
+
if (option.requiresNote && !nonempty(note)) throw new Error('This choice requires a note');
|
|
184
|
+
if (sameAnswer(decision, response.answer, note)) continue;
|
|
185
|
+
if (!['open', 'assigned'].includes(decision.status)) throw new Error('Reopen the decision explicitly before changing its answer.');
|
|
186
|
+
const updated = { ...decision, answer: response.answer, status: 'clarified' };
|
|
187
|
+
if (note === undefined) delete updated.note;
|
|
188
|
+
else updated.note = note;
|
|
189
|
+
changes.push({ index, updated });
|
|
190
|
+
}
|
|
191
|
+
if (changes.length === 0) return text;
|
|
192
|
+
const newline = text.includes('\r\n') ? '\r\n' : '\n';
|
|
193
|
+
let updatedText = text;
|
|
194
|
+
for (const change of changes.sort((left, right) => right.index - left.index)) {
|
|
195
|
+
const span = brief.spans[change.index];
|
|
196
|
+
const json = JSON.stringify(change.updated, null, 2).replaceAll('\n', newline);
|
|
197
|
+
updatedText = updatedText.slice(0, span.start) + json + updatedText.slice(span.end);
|
|
198
|
+
}
|
|
199
|
+
return updatedText;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Legacy single-answer convenience API. */
|
|
203
|
+
export function saveAnswer(text, { id, answer, revision, note } = {}) {
|
|
204
|
+
const response = { id, answer };
|
|
205
|
+
if (note !== undefined) response.note = note;
|
|
206
|
+
const updated = saveAnswers(text, { revision, answers: [response] });
|
|
207
|
+
if (updated === text) return text;
|
|
208
|
+
// Preserve the established preview writer's stable, whole-array formatting.
|
|
209
|
+
// New batch callers use saveAnswers and retain every untouched decision span.
|
|
210
|
+
const brief = readBrief(updated);
|
|
211
|
+
const newline = updated.includes('\r\n') ? '\r\n' : '\n';
|
|
212
|
+
const json = JSON.stringify(brief.decisions, null, 2).replaceAll('\n', newline);
|
|
213
|
+
return updated.slice(0, brief.start) + json + updated.slice(brief.end);
|
|
214
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { lstat, mkdir, open, readFile, realpath, rename, unlink } from 'node:fs/promises';
|
|
3
|
+
import { dirname, extname, join, resolve, sep } from 'node:path';
|
|
4
|
+
import { questionsFromBrief, saveAnswers } from './decisions.mjs';
|
|
5
|
+
import { artifactTheme, checkedTheme, artifactColors } from './preferences.mjs';
|
|
6
|
+
|
|
7
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
8
|
+
const string = value => typeof value === 'string' && value.trim().length > 0;
|
|
9
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
10
|
+
const imageTypes = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
|
|
11
|
+
|
|
12
|
+
export function projectPath(value) {
|
|
13
|
+
if (!string(value) || value.startsWith('/') || value.includes('\\') || value.split('/').some(part => !part || part === '.' || part === '..') || /[\x00-\x1f]/.test(value)) {
|
|
14
|
+
throw new Error('Use a path relative to the project root, without dot segments.');
|
|
15
|
+
}
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Deliberately read only explicitly named, plain project files. */
|
|
20
|
+
export async function checkedPath(root, path, { output = false } = {}) {
|
|
21
|
+
projectPath(path);
|
|
22
|
+
const base = await realpath(root);
|
|
23
|
+
let current = base;
|
|
24
|
+
const parts = path.split('/');
|
|
25
|
+
for (let i = 0; i < parts.length; i += 1) {
|
|
26
|
+
current = join(current, parts[i]);
|
|
27
|
+
let stat;
|
|
28
|
+
try { stat = await lstat(current); }
|
|
29
|
+
catch (error) { if (output && error.code === 'ENOENT') continue; throw error; }
|
|
30
|
+
if (stat.isSymbolicLink() || (i < parts.length - 1 ? !stat.isDirectory() : !stat.isFile())) throw new Error(`Expected a plain project file: ${path}`);
|
|
31
|
+
}
|
|
32
|
+
if (!current.startsWith(base + sep)) throw new Error('Path escaped project root');
|
|
33
|
+
return current;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function readProjectFile(root, path, limit = 1_000_000) {
|
|
37
|
+
const absolute = await checkedPath(root, path);
|
|
38
|
+
const stat = await lstat(absolute);
|
|
39
|
+
if (stat.size > limit) throw new Error(`File exceeds artifact limit: ${path}`);
|
|
40
|
+
return readFile(absolute);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function parseJSON(bytes, path) {
|
|
44
|
+
try { return JSON.parse(bytes.toString('utf8')); }
|
|
45
|
+
catch { throw new Error(`Invalid JSON: ${path}`); }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function loadArtifact({ root = process.cwd(), brief, view, mode = 'local', theme: themeOverride }) {
|
|
49
|
+
projectPath(brief);
|
|
50
|
+
if (!['local', 'claude', 'portable'].includes(mode)) throw new Error('Artifact mode must be local, claude or portable');
|
|
51
|
+
const text = (await readProjectFile(root, brief)).toString('utf8');
|
|
52
|
+
const definition = view ? parseJSON(await readProjectFile(root, view), view) : { schemaVersion: 1, title: 'Your decisions' };
|
|
53
|
+
if (!object(definition) || definition.schemaVersion !== 1 || !string(definition.title)) throw new Error('View needs schemaVersion: 1 and a title');
|
|
54
|
+
for (const field of ['title', 'summary']) if (definition[field] !== undefined && (typeof definition[field] !== 'string' || definition[field].length > 8_000)) throw new Error(`Invalid view ${field}`);
|
|
55
|
+
if (definition.theme !== undefined) checkedTheme(definition.theme, 'View theme');
|
|
56
|
+
if (themeOverride !== undefined) checkedTheme(themeOverride, 'Theme');
|
|
57
|
+
const artifactId = definition.artifactId ?? `decisions-${hash(brief).slice(0, 16)}`;
|
|
58
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/.test(artifactId)) throw new Error('artifactId must be a short alphanumeric slug');
|
|
59
|
+
const { revision, questions } = questionsFromBrief(text, definition.decisionIds);
|
|
60
|
+
if (questions.length > 100) throw new Error('Select at most 100 decision IDs for one artifact');
|
|
61
|
+
const comparisons = [], reviews = [], inputs = [];
|
|
62
|
+
let imageBytes = 0;
|
|
63
|
+
if (definition.comparisons !== undefined && !Array.isArray(definition.comparisons)) throw new Error('comparisons must be an array');
|
|
64
|
+
for (const comparison of definition.comparisons ?? []) {
|
|
65
|
+
if (!object(comparison) || !string(comparison.title) || !Array.isArray(comparison.images) || comparison.images.length < 1 || comparison.images.length > 4) throw new Error('Each comparison needs a title and one to four images');
|
|
66
|
+
if (comparison.decisionId !== undefined && !questions.some(q => q.id === comparison.decisionId)) throw new Error('Comparison refers to a decision outside this view');
|
|
67
|
+
const images = [];
|
|
68
|
+
for (const input of comparison.images) {
|
|
69
|
+
if (!object(input) || !string(input.label) || !string(input.alt) || (input.caption !== undefined && typeof input.caption !== 'string')) throw new Error('Images need a project path, label and descriptive alt text');
|
|
70
|
+
const type = imageTypes[extname(projectPath(input.path)).toLowerCase()];
|
|
71
|
+
if (!type) throw new Error('Use a PNG, JPEG, WebP or GIF screenshot');
|
|
72
|
+
const bytes = await readProjectFile(root, input.path, 8_000_000);
|
|
73
|
+
inputs.push({ path: input.path, sha256: hash(bytes) });
|
|
74
|
+
imageBytes += bytes.length;
|
|
75
|
+
if (imageBytes > 16_000_000) throw new Error('Artifact screenshots exceed 16 MB; select smaller images');
|
|
76
|
+
images.push({ src: `data:${type};base64,${bytes.toString('base64')}`, label: input.label, alt: input.alt, ...(input.caption === undefined ? {} : { caption: input.caption }) });
|
|
77
|
+
}
|
|
78
|
+
comparisons.push({ title: comparison.title, ...(comparison.decisionId ? { decisionId: comparison.decisionId } : {}), images });
|
|
79
|
+
}
|
|
80
|
+
if (definition.reviews !== undefined && !Array.isArray(definition.reviews)) throw new Error('reviews must be an array');
|
|
81
|
+
for (const input of definition.reviews ?? []) {
|
|
82
|
+
if (!object(input) || (input.title !== undefined && !string(input.title))) throw new Error('Review needs a report path and optional title');
|
|
83
|
+
const bytes = await readProjectFile(root, input.path);
|
|
84
|
+
inputs.push({ path: input.path, sha256: hash(bytes) });
|
|
85
|
+
const report = parseJSON(bytes, input.path);
|
|
86
|
+
if (!object(report) || report.schemaVersion !== 1 || !['PASS', 'FAIL', 'UNVERIFIED'].includes(report.verdict) || !Array.isArray(report.flows) || !Array.isArray(report.unresolved) || !report.unresolved.every(item => typeof item === 'string')) throw new Error(`Not a verification report: ${input.path}`);
|
|
87
|
+
const details = [...report.unresolved];
|
|
88
|
+
for (const flow of report.flows) {
|
|
89
|
+
if (!object(flow) || !string(flow.id) || !Array.isArray(flow.limits) || !flow.limits.every(item => typeof item === 'string')) throw new Error(`Invalid report flow: ${input.path}`);
|
|
90
|
+
details.push(...flow.limits.map(limit => `${flow.id}: ${limit}`));
|
|
91
|
+
}
|
|
92
|
+
reviews.push({ title: input.title ?? 'Independent review', result: report.verdict, summary: `${report.flows.length} recorded flows; ${report.unresolved.length} unresolved findings. This view does not revalidate the report against current files.`, details, source: input.path });
|
|
93
|
+
}
|
|
94
|
+
// Theme is display-only. Retain the legacy hash bytes when a view has no theme.
|
|
95
|
+
const { theme: _theme, ...semanticDefinition } = definition;
|
|
96
|
+
const viewRevision = hash(JSON.stringify({ definition: semanticDefinition, inputs }));
|
|
97
|
+
const theme = themeOverride ?? definition.theme ?? await artifactTheme(root) ?? 'light';
|
|
98
|
+
// Colors are display-only too: they stay out of the view revision.
|
|
99
|
+
const colors = (await artifactColors(root))?.[theme];
|
|
100
|
+
return { model: { schemaVersion: 1, artifactId, title: definition.title, summary: definition.summary ?? '', theme, ...(colors ? { colors } : {}), source: { path: brief, revision, viewRevision }, questions, comparisons, reviews, mode }, text };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function localState(model) {
|
|
104
|
+
return { model, responses: model.questions.filter(q => q.answer !== null).map(q => ({ id: q.id, answer: q.answer, ...(q.note === undefined ? {} : { note: q.note }) })), writable: true, storage: 'brief', message: 'Answers save directly to your brief.' };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function validateEnvelope(envelope, model) {
|
|
108
|
+
if (!object(envelope) || envelope.schemaVersion !== 1 || envelope.kind !== 'joycraft-artifact-responses' || envelope.artifactId !== model.artifactId || !object(envelope.source) || envelope.source.path !== model.source.path || envelope.source.revision !== model.source.revision || envelope.source.viewRevision !== model.source.viewRevision) throw new Error('Responses do not match this artifact and current brief revision or view. Refresh the artifact and review the answers.');
|
|
109
|
+
if (!Array.isArray(envelope.answers) || envelope.answers.length === 0 || envelope.answers.some(answer => !model.questions.some(q => q.id === answer?.id))) throw new Error('Responses must name only decisions displayed in this artifact');
|
|
110
|
+
return { revision: model.source.revision, answers: envelope.answers };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Cooperative lock + compare before atomic replacement; no silent stale write. */
|
|
114
|
+
async function replaceBrief(root, path, before, after) {
|
|
115
|
+
if (before === after) return;
|
|
116
|
+
const absolute = await checkedPath(root, path);
|
|
117
|
+
const lock = `${absolute}.joycraft-answer-lock`;
|
|
118
|
+
let handle;
|
|
119
|
+
try { handle = await open(lock, 'wx', 0o600); }
|
|
120
|
+
catch (error) { if (error.code === 'EEXIST') throw new Error('Another answer writer is active. Retry after it finishes; inspect a leftover .joycraft-answer-lock before removing it.'); throw error; }
|
|
121
|
+
const temporary = `${absolute}.answers-${randomBytes(8).toString('hex')}`;
|
|
122
|
+
try {
|
|
123
|
+
await checkedPath(root, path);
|
|
124
|
+
if ((await readFile(absolute, 'utf8')) !== before) throw new Error('Brief changed. Refresh before saving.');
|
|
125
|
+
const mode = (await lstat(absolute)).mode;
|
|
126
|
+
const output = await open(temporary, 'wx', mode);
|
|
127
|
+
try { await output.writeFile(after); await output.sync(); } finally { await output.close(); }
|
|
128
|
+
if ((await readFile(absolute, 'utf8')) !== before) throw new Error('Brief changed. Refresh before saving.');
|
|
129
|
+
await rename(temporary, absolute);
|
|
130
|
+
} finally {
|
|
131
|
+
await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
132
|
+
await handle.close();
|
|
133
|
+
await unlink(lock);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function persistResponses({ root = process.cwd(), brief, view, envelope, apply = false }) {
|
|
138
|
+
const { model, text } = await loadArtifact({ root, brief, view });
|
|
139
|
+
const request = validateEnvelope(envelope, model);
|
|
140
|
+
const updated = saveAnswers(text, request);
|
|
141
|
+
if (apply) await replaceBrief(root, brief, text, updated);
|
|
142
|
+
return { applied: apply, changed: updated !== text, source: model.source, answers: request.answers };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export async function saveLocal({ root = process.cwd(), brief, view, theme, request }) {
|
|
146
|
+
const { model, text } = await loadArtifact({ root, brief, view, theme });
|
|
147
|
+
if (request?.viewRevision !== model.source.viewRevision) throw new Error('Artifact view changed. Refresh the screenshots and questions before saving.');
|
|
148
|
+
if (!request || !Array.isArray(request.answers) || request.answers.some(answer => !model.questions.some(q => q.id === answer?.id))) throw new Error('Responses must name only decisions displayed in this artifact');
|
|
149
|
+
const updated = saveAnswers(text, request);
|
|
150
|
+
await replaceBrief(root, brief, text, updated);
|
|
151
|
+
return localState((await loadArtifact({ root, brief, view, theme })).model);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function writeArtifact({ root = process.cwd(), path, html }) {
|
|
155
|
+
const target = await checkedPath(root, path, { output: true });
|
|
156
|
+
await mkdir(dirname(target), { recursive: true });
|
|
157
|
+
await checkedPath(root, path, { output: true });
|
|
158
|
+
const file = await open(target, 'wx', 0o600);
|
|
159
|
+
try { await file.writeFile(html); } finally { await file.close(); }
|
|
160
|
+
return resolve(target);
|
|
161
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { lstat, mkdir, open, readFile, realpath, rename, unlink } from 'node:fs/promises';
|
|
3
|
+
import { join, sep } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const preferencePath = '.joycraft/preferences.json';
|
|
6
|
+
const themes = new Set(['light', 'dark']);
|
|
7
|
+
export const colorTokens = Object.freeze(['canvas', 'paper', 'surface', 'ink', 'muted', 'line', 'control-line', 'accent', 'accent-hover', 'accent-text', 'accent-soft', 'focus', 'error', 'error-bg', 'caution', 'input']);
|
|
8
|
+
const textPairs = [['ink', 'paper'], ['ink', 'surface'], ['ink', 'input'], ['ink', 'accent-soft'], ['muted', 'paper'], ['muted', 'surface'], ['muted', 'input'], ['muted', 'accent-soft'], ['accent', 'paper'], ['accent', 'accent-soft'], ['accent-text', 'accent'], ['accent-text', 'accent-hover'], ['error', 'error-bg']];
|
|
9
|
+
const controlPairs = [['control-line', 'paper'], ['control-line', 'input'], ['focus', 'paper'], ['focus', 'accent-soft']];
|
|
10
|
+
|
|
11
|
+
export function checkedTheme(value, source = 'theme') {
|
|
12
|
+
if (!themes.has(value)) throw new Error(`${source} must be light or dark`);
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function luminance(hex) {
|
|
17
|
+
const rgb = hex.slice(1).match(/../g).map(value => parseInt(value, 16) / 255).map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4);
|
|
18
|
+
return rgb[0] * .2126 + rgb[1] * .7152 + rgb[2] * .0722;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function contrast(a, b) {
|
|
22
|
+
const values = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
|
23
|
+
return (values[0] + .05) / (values[1] + .05);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The kit's built-in palettes, read from kit.css so there is one source. */
|
|
27
|
+
export async function defaultPalettes() {
|
|
28
|
+
const css = await readFile(new URL('../../assets/artifacts/kit.css', import.meta.url), 'utf8');
|
|
29
|
+
const tokens = block => Object.fromEntries([...block.matchAll(/--([\w-]+):\s*(#[\da-f]{6})/gi)].map(match => [match[1], match[2]]));
|
|
30
|
+
const light = tokens(css.split('}')[0]);
|
|
31
|
+
const dark = { ...light, ...tokens(css.slice(css.indexOf('[data-jca-theme="dark"]')).split('}')[0]) };
|
|
32
|
+
return { light, dark };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Override shape is { light?: { token: "#rrggbb" }, dark?: { ... } }; each merged palette keeps the kit's contrast floor. */
|
|
36
|
+
export async function checkedColors(colors, source = 'Artifact colors') {
|
|
37
|
+
if (!colors || typeof colors !== 'object' || Array.isArray(colors)) throw new Error(`${source} must be an object with light and/or dark palettes`);
|
|
38
|
+
const defaults = await defaultPalettes();
|
|
39
|
+
const result = {};
|
|
40
|
+
for (const [theme, palette] of Object.entries(colors)) {
|
|
41
|
+
if (!themes.has(theme)) throw new Error(`${source} theme must be light or dark: ${theme}`);
|
|
42
|
+
if (!palette || typeof palette !== 'object' || Array.isArray(palette)) throw new Error(`${source} ${theme} must be an object of colors`);
|
|
43
|
+
const checked = {};
|
|
44
|
+
for (const [token, value] of Object.entries(palette)) {
|
|
45
|
+
if (!colorTokens.includes(token)) throw new Error(`${source} ${theme} has an unknown color: ${token}. Use: ${colorTokens.join(', ')}`);
|
|
46
|
+
if (typeof value !== 'string' || !/^#[\da-f]{6}$/i.test(value)) throw new Error(`${source} ${theme}.${token} must be a #rrggbb color`);
|
|
47
|
+
checked[token] = value.toLowerCase();
|
|
48
|
+
}
|
|
49
|
+
const merged = { ...defaults[theme], ...checked };
|
|
50
|
+
const low = [...textPairs.map(pair => [...pair, 4.5]), ...controlPairs.map(pair => [...pair, 3])]
|
|
51
|
+
.filter(([fg, bg, floor]) => contrast(merged[fg], merged[bg]) < floor)
|
|
52
|
+
.map(([fg, bg, floor]) => `${fg} on ${bg} is ${contrast(merged[fg], merged[bg]).toFixed(2)}:1 (needs ${floor}:1)`);
|
|
53
|
+
if (low.length) throw new Error(`${source} ${theme} is hard to read: ${low.join('; ')}`);
|
|
54
|
+
if (Object.keys(checked).length) result[theme] = checked;
|
|
55
|
+
}
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function checkedPreferencePath(root, { output = false } = {}) {
|
|
60
|
+
const base = await realpath(root);
|
|
61
|
+
let current = base;
|
|
62
|
+
for (const part of preferencePath.split('/')) {
|
|
63
|
+
current = join(current, part);
|
|
64
|
+
let stat;
|
|
65
|
+
try { stat = await lstat(current); }
|
|
66
|
+
catch (error) { if (output && error.code === 'ENOENT') continue; throw error; }
|
|
67
|
+
if (stat.isSymbolicLink() || (part === 'preferences.json' ? !stat.isFile() : !stat.isDirectory())) throw new Error(`Expected a plain project file: ${preferencePath}`);
|
|
68
|
+
}
|
|
69
|
+
if (!current.startsWith(base + sep)) throw new Error('Path escaped project root');
|
|
70
|
+
return current;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function parsePreferences(bytes) {
|
|
74
|
+
let preferences;
|
|
75
|
+
try { preferences = JSON.parse(bytes.toString('utf8')); }
|
|
76
|
+
catch { throw new Error(`Invalid JSON: ${preferencePath}`); }
|
|
77
|
+
if (!preferences || typeof preferences !== 'object' || Array.isArray(preferences)) throw new Error(`${preferencePath} must contain an object`);
|
|
78
|
+
if (preferences.artifacts !== undefined && (!preferences.artifacts || typeof preferences.artifacts !== 'object' || Array.isArray(preferences.artifacts))) throw new Error(`${preferencePath} artifacts must be an object`);
|
|
79
|
+
return preferences;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function artifactTheme(root) {
|
|
83
|
+
let path;
|
|
84
|
+
try { path = await checkedPreferencePath(root); }
|
|
85
|
+
catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
|
|
86
|
+
const preferences = parsePreferences(await readFile(path));
|
|
87
|
+
return preferences.artifacts?.theme === undefined ? undefined : checkedTheme(preferences.artifacts.theme, 'Artifact preference theme');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function updatePreferences(root, change) {
|
|
91
|
+
const base = await realpath(root);
|
|
92
|
+
const directory = join(base, '.joycraft');
|
|
93
|
+
await mkdir(directory, { recursive: true });
|
|
94
|
+
let path;
|
|
95
|
+
try { path = await checkedPreferencePath(root); }
|
|
96
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; path = await checkedPreferencePath(root, { output: true }); }
|
|
97
|
+
let preferences;
|
|
98
|
+
try { preferences = parsePreferences(await readFile(path)); }
|
|
99
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; preferences = { schemaVersion: 1 }; }
|
|
100
|
+
const updated = { ...preferences, artifacts: change({ ...(preferences.artifacts ?? {}) }) };
|
|
101
|
+
const temporary = `${path}.prefs-${randomBytes(8).toString('hex')}`;
|
|
102
|
+
const file = await open(temporary, 'wx', 0o600);
|
|
103
|
+
try { await file.writeFile(`${JSON.stringify(updated, null, 2)}\n`); await file.sync(); }
|
|
104
|
+
finally { await file.close(); }
|
|
105
|
+
try { await checkedPreferencePath(root, { output: true }); await rename(temporary, path); }
|
|
106
|
+
finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
|
|
107
|
+
return updated;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function setArtifactTheme(root, theme) {
|
|
111
|
+
checkedTheme(theme, 'Theme');
|
|
112
|
+
return updatePreferences(root, artifacts => ({ ...artifacts, theme }));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function artifactColors(root) {
|
|
116
|
+
let path;
|
|
117
|
+
try { path = await checkedPreferencePath(root); }
|
|
118
|
+
catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
|
|
119
|
+
const preferences = parsePreferences(await readFile(path));
|
|
120
|
+
return preferences.artifacts?.colors === undefined ? undefined : checkedColors(preferences.artifacts.colors, 'Artifact preference colors');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Replace the project's color overrides; null removes them and restores the kit palettes. */
|
|
124
|
+
export async function setArtifactColors(root, colors) {
|
|
125
|
+
const checked = colors === null ? null : await checkedColors(colors);
|
|
126
|
+
return updatePreferences(root, ({ colors: _colors, ...artifacts }) => checked && Object.keys(checked).length ? { ...artifacts, colors: checked } : artifacts);
|
|
127
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { colorTokens } from './preferences.mjs';
|
|
3
|
+
|
|
4
|
+
const asset = name => readFile(new URL(`../../assets/artifacts/${name}`, import.meta.url), 'utf8');
|
|
5
|
+
const escape = text => String(text).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"');
|
|
6
|
+
const embeddedJSON = value => JSON.stringify(value).replaceAll('<', '\\u003c').replaceAll('\u2028', '\\u2028').replaceAll('\u2029', '\\u2029');
|
|
7
|
+
|
|
8
|
+
/** Assembly copies runtime bytes; the author only supplies the small view data. */
|
|
9
|
+
export async function renderArtifact(model, { token } = {}) {
|
|
10
|
+
if (!['local', 'claude', 'portable'].includes(model.mode)) throw new Error('Unknown artifact mode');
|
|
11
|
+
if (model.mode === 'local' && !/^[a-f0-9]{48}$/.test(token ?? '')) throw new Error('Local artifact needs a request token');
|
|
12
|
+
const theme = model.theme ?? 'light';
|
|
13
|
+
if (!['light', 'dark'].includes(theme)) throw new Error('Artifact theme must be light or dark');
|
|
14
|
+
const colors = Object.entries(model.colors ?? {});
|
|
15
|
+
for (const [token, value] of colors) if (!colorTokens.includes(token) || !/^#[\da-f]{6}$/i.test(value)) throw new Error('Artifact colors must be known tokens with #rrggbb values');
|
|
16
|
+
const palette = colors.length ? `[data-jca-theme="${theme}"]{${colors.map(([token, value]) => `--${token}:${value}`).join(';')}}` : '';
|
|
17
|
+
const [css, kit, transports] = await Promise.all([asset('kit.css'), asset('kit.js'), asset('transports.js')]);
|
|
18
|
+
const nonce = token ? ` nonce="${token}"` : '';
|
|
19
|
+
const init = `const model = JSON.parse(document.getElementById('artifact-data').textContent);\nconst transport = JoycraftArtifactTransports.${model.mode}(model, ${model.mode === 'local' ? `{token:${JSON.stringify(token)}}` : '{}'});\nJoycraftArtifacts.mount({element:document.getElementById('artifact'),model,transport});`;
|
|
20
|
+
return `<!doctype html>\n<html lang="en" data-jca-theme="${theme}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(model.title)}</title><style>${css}${palette}</style></head><body><main id="artifact"></main><noscript>This interactive page needs JavaScript. Read the source brief for current decisions.</noscript><script type="application/json" id="artifact-data"${nonce}>${embeddedJSON(model)}</script><script${nonce}>${kit}</script><script${nonce}>${transports}</script><script${nonce}>${init}</script></body></html>\n`;
|
|
21
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { loadArtifact, localState, saveLocal } from './model.mjs';
|
|
4
|
+
import { renderArtifact } from './render.mjs';
|
|
5
|
+
|
|
6
|
+
export async function startArtifact({ root = process.cwd(), brief, view, theme, port = 0 }) {
|
|
7
|
+
const args = { root, brief, view, theme };
|
|
8
|
+
await loadArtifact(args);
|
|
9
|
+
const token = randomBytes(24).toString('hex');
|
|
10
|
+
let url;
|
|
11
|
+
const server = createServer(async (request, response) => {
|
|
12
|
+
const send = (status, data, type = 'application/json') => {
|
|
13
|
+
response.writeHead(status, { 'Content-Type': `${type}; charset=utf-8`, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' });
|
|
14
|
+
response.end(type === 'application/json' ? JSON.stringify(data) : data);
|
|
15
|
+
};
|
|
16
|
+
try {
|
|
17
|
+
if (request.headers.host !== new URL(url).host) return send(403, { error: 'Invalid host' });
|
|
18
|
+
const path = new URL(request.url, url).pathname;
|
|
19
|
+
if (request.method === 'GET' && path === '/') {
|
|
20
|
+
response.setHeader('Content-Security-Policy', `default-src 'none'; script-src 'nonce-${token}'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; frame-ancestors 'none'; form-action 'none'`);
|
|
21
|
+
return send(200, await renderArtifact((await loadArtifact(args)).model, { token }), 'text/html');
|
|
22
|
+
}
|
|
23
|
+
if (request.method === 'GET' && path === '/state') return send(200, localState((await loadArtifact(args)).model));
|
|
24
|
+
if (request.method === 'POST' && path === '/answers') {
|
|
25
|
+
if (request.headers.origin !== url || request.headers['x-artifact-token'] !== token) return send(403, { error: 'Invalid origin or token' });
|
|
26
|
+
if (!/^application\/json(?:;|$)/i.test(request.headers['content-type'] ?? '')) return send(415, { error: 'Send application/json' });
|
|
27
|
+
let body = '';
|
|
28
|
+
for await (const part of request) {
|
|
29
|
+
body += part;
|
|
30
|
+
if (Buffer.byteLength(body) > 500_000) return send(413, { error: 'Answer request too large' });
|
|
31
|
+
}
|
|
32
|
+
return send(200, await saveLocal({ ...args, request: JSON.parse(body) }));
|
|
33
|
+
}
|
|
34
|
+
return send(404, { error: 'Not found' });
|
|
35
|
+
} catch (error) { return send(409, { error: error.message }); }
|
|
36
|
+
});
|
|
37
|
+
await new Promise((accept, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', accept); });
|
|
38
|
+
url = `http://127.0.0.1:${server.address().port}`;
|
|
39
|
+
return { server, url, close: () => new Promise((accept, reject) => server.close(error => error ? reject(error) : accept())) };
|
|
40
|
+
}
|