@derushly/editor 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +15 -0
- package/README.md +6 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/server.d.ts +42 -0
- package/dist/server.js +756 -0
- package/package.json +56 -4
- package/ui-dist/THIRD_PARTY_NOTICES.md +2201 -0
- package/ui-dist/assets/dist-DDQ9WcrZ.js +58 -0
- package/ui-dist/assets/index-B1Lor06r.css +1 -0
- package/ui-dist/assets/index-BefJOHLE.js +852 -0
- package/ui-dist/assets/parent-audio-333CSKNZ-x-ixkhjk.js +500 -0
- package/ui-dist/assets/pausedVideoDecoder-3C25UMTR-DnYIc3M4.js +1 -0
- package/ui-dist/assets/previewOffCanvas-CTOQIFXK-DoXeJSRI.js +1 -0
- package/ui-dist/assets/runtime-inline-BT7nvEOP.js +1 -0
- package/ui-dist/assets/src-CYmap0el.js +36 -0
- package/ui-dist/hyperframe.runtime.iife.js +1146 -0
- package/ui-dist/index.html +13 -0
- package/ui-dist/third-party.json +1 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
1
|
+
// The local editor: a page on 127.0.0.1 that reads and writes one project folder, with the same
|
|
2
|
+
// operations as the CLI and the MCP server (all changes go through @derushly/core, so they land in
|
|
3
|
+
// the history and the journal like any other).
|
|
4
|
+
//
|
|
5
|
+
// Security (spec 9.2):
|
|
6
|
+
// - bound to 127.0.0.1 only; requests whose Host is not this address are refused (DNS rebinding);
|
|
7
|
+
// - a one-time launch token in the URL opens a session (HttpOnly, SameSite=Strict cookie);
|
|
8
|
+
// - every change is a POST with a JSON body, the session cookie, the page's CSRF token and a
|
|
9
|
+
// same-origin Origin header;
|
|
10
|
+
// - the project's files are served to the preview from a second address (another port: another
|
|
11
|
+
// origin, so the composition's code cannot reach the editor page, its cookie or its token),
|
|
12
|
+
// under an unguessable path, read-only, without .env files, history or Derushly's own state.
|
|
13
|
+
import { createReadStream, createWriteStream, existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, watch } from "node:fs";
|
|
14
|
+
import { tmpdir } from "node:os";
|
|
15
|
+
import { createServer } from "node:http";
|
|
16
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
17
|
+
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
import * as core from "@derushly/core";
|
|
20
|
+
import { DerushlyError } from "@derushly/core";
|
|
21
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
/** The built page: next to the package (dist/ -> ../ui-dist) or next to the plugin's bundle (editor-ui/). */
|
|
23
|
+
const UI_DIRS = [resolve(HERE, "..", "ui-dist"), join(HERE, "editor-ui")];
|
|
24
|
+
const MAX_BODY = 1024 * 1024;
|
|
25
|
+
const token = () => randomBytes(24).toString("base64url");
|
|
26
|
+
const same = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
27
|
+
/** Never served to the preview, wherever they are in the project. */
|
|
28
|
+
const DENY = new Set([".history", ".derushly", ".mvi", ".notes", ".git", "node_modules", ".hyperframes"]);
|
|
29
|
+
const denied = (rel) => rel.split(/[\\/]/).some((part) => DENY.has(part) || part.startsWith(".env"));
|
|
30
|
+
const TYPES = {
|
|
31
|
+
".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8",
|
|
32
|
+
".css": "text/css; charset=utf-8", ".json": "application/json; charset=utf-8", ".svg": "image/svg+xml",
|
|
33
|
+
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif", ".avif": "image/avif",
|
|
34
|
+
".mp3": "audio/mpeg", ".wav": "audio/wav", ".m4a": "audio/mp4", ".aac": "audio/aac", ".ogg": "audio/ogg", ".opus": "audio/ogg",
|
|
35
|
+
".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime",
|
|
36
|
+
".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".otf": "font/otf", ".txt": "text/plain; charset=utf-8",
|
|
37
|
+
".ico": "image/x-icon", ".map": "application/json",
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* The preview runs the composition's own code: it may use the CDNs HyperFrames compositions use
|
|
41
|
+
* (scripts, styles, fonts) and nothing else; it cannot send data anywhere but this server.
|
|
42
|
+
*/
|
|
43
|
+
const PREVIEW_CSP = [
|
|
44
|
+
"default-src 'self' data: blob:",
|
|
45
|
+
"script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com",
|
|
46
|
+
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net",
|
|
47
|
+
"font-src 'self' data: https://fonts.gstatic.com https://cdn.jsdelivr.net",
|
|
48
|
+
"img-src 'self' data: blob:",
|
|
49
|
+
"media-src 'self' data: blob:",
|
|
50
|
+
"connect-src 'self' data: blob:",
|
|
51
|
+
"form-action 'none'",
|
|
52
|
+
"base-uri 'self'",
|
|
53
|
+
].join("; ");
|
|
54
|
+
/** The editor page: its own code only; the preview, snapshots and renders come from the preview origin. */
|
|
55
|
+
const pageCsp = (preview) => [
|
|
56
|
+
"default-src 'self'",
|
|
57
|
+
"script-src 'self'",
|
|
58
|
+
"style-src 'self' 'unsafe-inline'",
|
|
59
|
+
`img-src 'self' data: blob: ${preview}`,
|
|
60
|
+
`media-src 'self' data: blob: ${preview}`,
|
|
61
|
+
"font-src 'self' data:",
|
|
62
|
+
`connect-src 'self' ${preview}`,
|
|
63
|
+
`frame-src ${preview}`,
|
|
64
|
+
"worker-src 'self' blob:",
|
|
65
|
+
"form-action 'none'",
|
|
66
|
+
"frame-ancestors 'none'",
|
|
67
|
+
"base-uri 'none'",
|
|
68
|
+
].join("; ");
|
|
69
|
+
/** The HyperFrames runtime the preview adds to the composition (shipped with the Player). */
|
|
70
|
+
const RUNTIME = "hyperframe.runtime.iife.js";
|
|
71
|
+
class HttpError extends Error {
|
|
72
|
+
status;
|
|
73
|
+
constructor(status, message) {
|
|
74
|
+
super(message);
|
|
75
|
+
this.status = status;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
export async function startEditor(opts) {
|
|
79
|
+
const dir = resolve(opts.project);
|
|
80
|
+
core.openProject(dir); // refuses a folder that is not a project, migrates an old one
|
|
81
|
+
core.setActor("editor");
|
|
82
|
+
const log = opts.log ?? (() => { });
|
|
83
|
+
const uiDir = opts.uiDir ?? UI_DIRS.find((d) => existsSync(join(d, "index.html")));
|
|
84
|
+
if (!uiDir || !existsSync(join(uiDir, "index.html")))
|
|
85
|
+
throw new DerushlyError("internal", "the editor page is not built: run `npm run build:ui -w @derushly/editor`");
|
|
86
|
+
const launch = new Set([token()]);
|
|
87
|
+
const sessions = new Set();
|
|
88
|
+
const csrf = token();
|
|
89
|
+
const filesToken = token();
|
|
90
|
+
const filesBase = `/p/${filesToken}/`;
|
|
91
|
+
let port = 0;
|
|
92
|
+
let previewPort = 0;
|
|
93
|
+
const previewOrigin = () => `http://127.0.0.1:${previewPort}`;
|
|
94
|
+
// ---- jobs: one engine job at a time (each takes a browser) ----------------------------------
|
|
95
|
+
let job = null;
|
|
96
|
+
let jobSeq = 0;
|
|
97
|
+
const events = new Set();
|
|
98
|
+
const send = (type, data) => {
|
|
99
|
+
const msg = `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
100
|
+
for (const res of events)
|
|
101
|
+
res.write(msg);
|
|
102
|
+
};
|
|
103
|
+
function startJob(kind, args, run) {
|
|
104
|
+
if (job?.state === "running")
|
|
105
|
+
throw new DerushlyError("exists", `the engine is busy (${job.kind}): wait for it to finish`);
|
|
106
|
+
const running = core.renderStatus(dir);
|
|
107
|
+
if (running?.state === "running")
|
|
108
|
+
throw new DerushlyError("exists", `a render of this project is already running (${running.progress}%), started elsewhere`);
|
|
109
|
+
const j = { id: ++jobSeq, kind, state: "running", progress: 0, started: new Date().toISOString(), args, lines: [] };
|
|
110
|
+
job = j;
|
|
111
|
+
send("job", j);
|
|
112
|
+
log(`job ${j.id} ${kind} started`);
|
|
113
|
+
let lastSent = 0;
|
|
114
|
+
const tick = () => {
|
|
115
|
+
if (Date.now() - lastSent > 400) {
|
|
116
|
+
lastSent = Date.now();
|
|
117
|
+
send("job", j);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
j.tick = tick;
|
|
121
|
+
run(j)
|
|
122
|
+
.then((r) => Object.assign(j, { state: "done", progress: 100, result: r }))
|
|
123
|
+
.catch((e) => {
|
|
124
|
+
const err = e instanceof DerushlyError ? e : null;
|
|
125
|
+
Object.assign(j, { state: "failed", error: { code: err?.code ?? "internal", message: e.message, ...(err?.errors ? { errors: err.errors } : {}) } });
|
|
126
|
+
})
|
|
127
|
+
.finally(() => {
|
|
128
|
+
j.finished = new Date().toISOString();
|
|
129
|
+
log(`job ${j.id} ${kind} ${j.state}`);
|
|
130
|
+
send("job", j);
|
|
131
|
+
send("change", { why: kind });
|
|
132
|
+
});
|
|
133
|
+
return j;
|
|
134
|
+
}
|
|
135
|
+
const onLine = (j) => (line) => {
|
|
136
|
+
j.lines.push(line.slice(0, 300));
|
|
137
|
+
if (j.lines.length > 30)
|
|
138
|
+
j.lines.shift();
|
|
139
|
+
j.tick();
|
|
140
|
+
};
|
|
141
|
+
const engine = (j, variant) => ({
|
|
142
|
+
...(opts.mode ? { mode: opts.mode } : {}),
|
|
143
|
+
...(typeof variant === "string" && variant ? { variant } : {}),
|
|
144
|
+
onLine: onLine(j),
|
|
145
|
+
});
|
|
146
|
+
/** Image of a note's moment, rendered by the engine and attached to the note. */
|
|
147
|
+
function noteSnapshot(id, at, variant) {
|
|
148
|
+
return startJob("note-snapshot", { id, at, ...(variant ? { variant } : {}) }, async (j) => {
|
|
149
|
+
const r = await core.snapshot(dir, [at], engine(j, variant));
|
|
150
|
+
const file = r.files[0]?.path;
|
|
151
|
+
if (!file)
|
|
152
|
+
throw new DerushlyError("engine", "the engine returned no image");
|
|
153
|
+
core.setNoteSnapshot(dir, id, file);
|
|
154
|
+
return { note: id, snapshot: file };
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
const str = (a, k, required = true) => {
|
|
158
|
+
const v = a[k];
|
|
159
|
+
if (v === undefined && !required)
|
|
160
|
+
return undefined;
|
|
161
|
+
if (typeof v !== "string" || !v.length || v.length > 5000)
|
|
162
|
+
throw new DerushlyError("usage", `${k}: expected a text`);
|
|
163
|
+
return v;
|
|
164
|
+
};
|
|
165
|
+
const num = (a, k, required = false) => {
|
|
166
|
+
const v = a[k];
|
|
167
|
+
if (v === undefined && !required)
|
|
168
|
+
return undefined;
|
|
169
|
+
if (typeof v !== "number" || !Number.isFinite(v))
|
|
170
|
+
throw new DerushlyError("usage", `${k}: expected a number`);
|
|
171
|
+
return v;
|
|
172
|
+
};
|
|
173
|
+
const pick = (a, keys) => {
|
|
174
|
+
const out = {};
|
|
175
|
+
for (const k of keys) {
|
|
176
|
+
const v = num(a, k);
|
|
177
|
+
if (v !== undefined)
|
|
178
|
+
out[k] = Math.round(v * 1000) / 1000;
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
};
|
|
182
|
+
const transitionOf = (v) => {
|
|
183
|
+
if (v === undefined)
|
|
184
|
+
return undefined;
|
|
185
|
+
if (v === null)
|
|
186
|
+
return null;
|
|
187
|
+
const t = v;
|
|
188
|
+
const type = str(t, "type");
|
|
189
|
+
if (!core.TRANSITION_TYPES.includes(type))
|
|
190
|
+
throw new DerushlyError("usage", `transition "${type}": ${core.TRANSITION_TYPES.join(", ")}`);
|
|
191
|
+
return { type: type, ...pick(t, ["duration"]) };
|
|
192
|
+
};
|
|
193
|
+
/** Free placement: numbers, a null field to reset it, null to reset everything. */
|
|
194
|
+
const transformOf = (v) => {
|
|
195
|
+
if (v === null)
|
|
196
|
+
return null;
|
|
197
|
+
const t = v;
|
|
198
|
+
const out = {};
|
|
199
|
+
for (const k of ["x", "y", "scale", "rotation", "opacity"])
|
|
200
|
+
if (t[k] === null)
|
|
201
|
+
out[k] = null;
|
|
202
|
+
else if (t[k] !== undefined)
|
|
203
|
+
out[k] = num(t, k);
|
|
204
|
+
return out;
|
|
205
|
+
};
|
|
206
|
+
/** Transitions, clip fields, placement and extend of scene.add / scene.update. */
|
|
207
|
+
const sceneExtras = (a) => {
|
|
208
|
+
const out = {};
|
|
209
|
+
const tin = transitionOf(a.transitionIn);
|
|
210
|
+
const tout = transitionOf(a.transitionOut);
|
|
211
|
+
if (tin !== undefined)
|
|
212
|
+
out.transitionIn = tin;
|
|
213
|
+
if (tout !== undefined)
|
|
214
|
+
out.transitionOut = tout;
|
|
215
|
+
if (a.mediaPatch && typeof a.mediaPatch === "object")
|
|
216
|
+
out.media = mediaFields(a.mediaPatch, true);
|
|
217
|
+
if (a.transform !== undefined)
|
|
218
|
+
out.transform = transformOf(a.transform);
|
|
219
|
+
if (a.extend === true)
|
|
220
|
+
out.extend = true;
|
|
221
|
+
return out;
|
|
222
|
+
};
|
|
223
|
+
const mediaFields = (m, patch = false) => {
|
|
224
|
+
const out = {};
|
|
225
|
+
for (const k of ["mediaStart", "volume"])
|
|
226
|
+
if (m[k] === null && patch)
|
|
227
|
+
out[k] = null;
|
|
228
|
+
else if (m[k] !== undefined)
|
|
229
|
+
out[k] = num(m, k);
|
|
230
|
+
if (m.fit === "cover" || m.fit === "contain" || (patch && m.fit === null))
|
|
231
|
+
out.fit = m.fit;
|
|
232
|
+
if (m.motion === "zoom-in" || m.motion === "zoom-out" || (patch && m.motion === null))
|
|
233
|
+
out.motion = m.motion;
|
|
234
|
+
if (typeof m.muted === "boolean" || (patch && m.muted === null))
|
|
235
|
+
out.muted = m.muted;
|
|
236
|
+
if (patch && m.src)
|
|
237
|
+
out.src = str(m, "src");
|
|
238
|
+
return out;
|
|
239
|
+
};
|
|
240
|
+
const ops = {
|
|
241
|
+
"variables.set": (a) => {
|
|
242
|
+
const list = a.assignments;
|
|
243
|
+
if (!Array.isArray(list) || !list.length || list.length > 200)
|
|
244
|
+
throw new DerushlyError("usage", "assignments: expected a list");
|
|
245
|
+
// target: a variable id, a list's element id, or `list[n]` (1-based).
|
|
246
|
+
return core.setVariables(dir, list.map((x) => ({
|
|
247
|
+
scene: str(x, "scene"),
|
|
248
|
+
target: str(x, "target"),
|
|
249
|
+
value: Array.isArray(x.value) ? x.value.map(String) : typeof x.value === "string" ? x.value : "",
|
|
250
|
+
})));
|
|
251
|
+
},
|
|
252
|
+
"scene.update": (a) => core.updateScene(dir, str(a, "id"), { ...pick(a, ["start", "duration", "track"]), ...sceneExtras(a) }, { ripple: a.ripple === true }),
|
|
253
|
+
"scene.add": (a) => {
|
|
254
|
+
const params = a.params && typeof a.params === "object" && !Array.isArray(a.params) ? a.params : undefined;
|
|
255
|
+
const media = a.media;
|
|
256
|
+
return core.addScene(dir, {
|
|
257
|
+
id: str(a, "id"), start: num(a, "start", true),
|
|
258
|
+
...pick(a, ["duration", "track"]),
|
|
259
|
+
...(a.component ? { component: str(a, "component") } : {}),
|
|
260
|
+
...(a.from ? { from: str(a, "from") } : {}),
|
|
261
|
+
...(media ? { media: { src: str(media, "src"), ...mediaFields(media) } } : {}),
|
|
262
|
+
...(params ? { params } : {}),
|
|
263
|
+
...sceneExtras(a),
|
|
264
|
+
}, { ripple: a.ripple === true });
|
|
265
|
+
},
|
|
266
|
+
"clip.split": (a) => core.splitClip(dir, str(a, "id"), num(a, "at", true)),
|
|
267
|
+
"clip.trim": (a) => core.trimClip(dir, str(a, "id"), pick(a, ["in", "out"]), { ripple: a.ripple === true }),
|
|
268
|
+
"clip.duplicate": (a) => core.duplicateClip(dir, str(a, "id"), { ...pick(a, ["at", "track"]), extend: a.extend === true }),
|
|
269
|
+
"clip.crossfade": (a) => core.crossfade(dir, str(a, "id"), num(a, "duration")),
|
|
270
|
+
"layering.set": (a) => core.setLayering(dir, a.layering === "default" ? "default" : "tracks"),
|
|
271
|
+
"audio.add": (a) => core.addAudio(dir, {
|
|
272
|
+
src: str(a, "src"), start: num(a, "start", true),
|
|
273
|
+
...pick(a, ["duration", "mediaStart", "volume", "fadeIn", "fadeOut", "track"]),
|
|
274
|
+
...(a.role ? { role: str(a, "role") } : {}), ...(a.id ? { id: str(a, "id") } : {}), ...(a.extend === true ? { extend: true } : {}),
|
|
275
|
+
}),
|
|
276
|
+
"duration.set": (a) => core.setDuration(dir, num(a, "duration", true)),
|
|
277
|
+
"brand.set": (a) => {
|
|
278
|
+
const map = (k) => {
|
|
279
|
+
const v = a[k];
|
|
280
|
+
if (v === undefined)
|
|
281
|
+
return undefined;
|
|
282
|
+
if (!v || typeof v !== "object" || Array.isArray(v))
|
|
283
|
+
throw new DerushlyError("usage", `${k}: expected { name: value }`);
|
|
284
|
+
return Object.fromEntries(Object.entries(v).map(([n, x]) => [n, x === null ? null : String(x)]));
|
|
285
|
+
};
|
|
286
|
+
const colors = map("colors");
|
|
287
|
+
// Files come from the upload endpoint; here only removals (null) and files already in the project.
|
|
288
|
+
const logos = map("logos");
|
|
289
|
+
const captions = a.captions === null ? null : a.captions && typeof a.captions === "object" ? a.captions : undefined;
|
|
290
|
+
return core.setBrand(dir, {
|
|
291
|
+
id: str(a, "id"), ...(a.name ? { name: str(a, "name") } : {}),
|
|
292
|
+
...(colors ? { colors } : {}), ...(logos ? { logos } : {}), ...(captions !== undefined ? { captions } : {}),
|
|
293
|
+
...(typeof a.apply === "boolean" ? { apply: a.apply } : {}),
|
|
294
|
+
});
|
|
295
|
+
},
|
|
296
|
+
"brand.apply": (a) => core.applyBrand(dir, a.id === null ? null : str(a, "id")),
|
|
297
|
+
"brand.remove": (a) => core.removeBrand(dir, str(a, "id")),
|
|
298
|
+
// The user asked for it in this page (remote adapters: the page asked them to confirm first).
|
|
299
|
+
"voice.generate": (a) => core.generateVoice(dir, {
|
|
300
|
+
text: str(a, "text"), ...(a.adapter ? { adapter: str(a, "adapter") } : {}), ...(a.voice ? { voice: str(a, "voice") } : {}),
|
|
301
|
+
...(a.language ? { language: str(a, "language") } : {}), ...pick(a, ["start", "volume", "speed"]), ...(a.extend === true ? { extend: true } : {}),
|
|
302
|
+
}),
|
|
303
|
+
"captions.transcribe": (a) => core.transcribeCaptions(dir, {
|
|
304
|
+
...(a.adapter ? { adapter: str(a, "adapter") } : {}), ...(a.language ? { language: str(a, "language") } : {}),
|
|
305
|
+
...(Array.isArray(a.clips) ? { clips: a.clips.map(String) } : {}),
|
|
306
|
+
...(Array.isArray(a.text) ? { text: a.text.map(String) } : typeof a.text === "string" && a.text.trim() ? { text: a.text } : {}),
|
|
307
|
+
}),
|
|
308
|
+
"scene.move": (a) => core.moveScene(dir, str(a, "id"), { ...(a.before ? { before: str(a, "before") } : {}), ...(a.after ? { after: str(a, "after") } : {}) }),
|
|
309
|
+
"scene.remove": (a) => core.removeScene(dir, str(a, "id"), { ripple: a.ripple === true }),
|
|
310
|
+
"audio.update": (a) => {
|
|
311
|
+
const patch = pick(a, ["start", "duration", "mediaStart", "volume", "fadeIn", "fadeOut", "track"]);
|
|
312
|
+
return core.updateAudio(dir, { id: str(a, "id") }, patch);
|
|
313
|
+
},
|
|
314
|
+
"audio.remove": (a) => core.removeAudio(dir, str(a, "id")),
|
|
315
|
+
"caption.update": (a) => core.updateCaption(dir, str(a, "id"), {
|
|
316
|
+
...pick(a, ["start", "duration"]),
|
|
317
|
+
...(a.text !== undefined ? { text: str(a, "text") } : {}),
|
|
318
|
+
}),
|
|
319
|
+
"caption.add": (a) => core.addCaption(dir, { text: str(a, "text"), start: num(a, "start", true), duration: num(a, "duration", true) }),
|
|
320
|
+
"caption.remove": (a) => core.removeCaption(dir, str(a, "id")),
|
|
321
|
+
"note.add": (a) => {
|
|
322
|
+
const from = num(a, "from", true);
|
|
323
|
+
const to = num(a, "to", true);
|
|
324
|
+
const region = a.region;
|
|
325
|
+
const r = core.addNote(dir, {
|
|
326
|
+
from, to, text: str(a, "text"),
|
|
327
|
+
...(typeof a.format === "string" && a.format ? { format: a.format } : {}),
|
|
328
|
+
...(region ? { region: { x: num(region, "x", true), y: num(region, "y", true), w: num(region, "w", true), h: num(region, "h", true) } } : {}),
|
|
329
|
+
});
|
|
330
|
+
// The image of the moment, as the user saw it: taken in the background when the engine is free.
|
|
331
|
+
let snapshotJob;
|
|
332
|
+
try {
|
|
333
|
+
const at = typeof a.at === "number" ? a.at : from;
|
|
334
|
+
snapshotJob = noteSnapshot(r.result.id, Math.min(Math.max(at, 0), Math.max(0, core.describe(dir).composition.duration - 0.01)), typeof a.format === "string" ? a.format : undefined).id;
|
|
335
|
+
}
|
|
336
|
+
catch (e) {
|
|
337
|
+
log(`note ${r.result.id}: no snapshot (${e.message})`);
|
|
338
|
+
}
|
|
339
|
+
return { ...r, ...(snapshotJob ? { snapshotJob } : {}) };
|
|
340
|
+
},
|
|
341
|
+
"note.validate": (a) => core.validateNote(dir, str(a, "id")),
|
|
342
|
+
"note.reopen": (a) => core.reopenNote(dir, str(a, "id"), str(a, "why", false)),
|
|
343
|
+
"history.undo": () => core.undo(dir),
|
|
344
|
+
"history.redo": () => core.redo(dir),
|
|
345
|
+
"variant.set": (a) => core.setVariant(dir, {
|
|
346
|
+
id: str(a, "id"),
|
|
347
|
+
...(a.preset ? { preset: str(a, "preset") } : {}),
|
|
348
|
+
...pick(a, ["width", "height"]),
|
|
349
|
+
...(a.fit === "contain" || a.fit === "cover" ? { fit: a.fit } : {}),
|
|
350
|
+
...(a.background === null ? { background: null } : a.background !== undefined ? { background: str(a, "background") } : {}),
|
|
351
|
+
...(a.safeZone === null ? { safeZone: null } : a.safeZone !== undefined ? { safeZone: str(a, "safeZone") } : {}),
|
|
352
|
+
}),
|
|
353
|
+
"variant.remove": (a) => core.removeVariant(dir, str(a, "id")),
|
|
354
|
+
/** Keep the edits made to the generated files elsewhere. */
|
|
355
|
+
"sync.keep": () => core.sync(dir),
|
|
356
|
+
/** Discard them: rebuild the generated files from the project. */
|
|
357
|
+
"sync.discard": () => core.rebuild(dir, { force: true }),
|
|
358
|
+
"job.check": (a) => startJob("check", { format: a.format }, (j) => core.check(dir, engine(j, a.format))),
|
|
359
|
+
"job.snapshot": (a) => {
|
|
360
|
+
const at = Array.isArray(a.at) ? a.at.filter((x) => typeof x === "number").slice(0, 8) : [];
|
|
361
|
+
if (!at.length)
|
|
362
|
+
throw new DerushlyError("usage", "at: give one or more times");
|
|
363
|
+
return startJob("snapshot", { at, format: a.format }, (j) => core.snapshot(dir, at, engine(j, a.format)));
|
|
364
|
+
},
|
|
365
|
+
"job.render": (a) => {
|
|
366
|
+
const quality = a.quality === "draft" || a.quality === "high" ? a.quality : "standard";
|
|
367
|
+
const range = pick(a, ["start", "end"]);
|
|
368
|
+
return startJob("render", { quality, format: a.format, ...range }, (j) => core.render(dir, {
|
|
369
|
+
...engine(j, a.format), quality, ...range,
|
|
370
|
+
onProgress: (pct) => {
|
|
371
|
+
j.progress = Math.round(pct);
|
|
372
|
+
j.tick();
|
|
373
|
+
},
|
|
374
|
+
}));
|
|
375
|
+
},
|
|
376
|
+
"job.note-snapshot": (a) => noteSnapshot(str(a, "id"), num(a, "at", true), typeof a.format === "string" ? a.format : undefined),
|
|
377
|
+
};
|
|
378
|
+
const library = core.listLibrary();
|
|
379
|
+
/** Media files of the project (assets/), for the clip, audio and image pickers. */
|
|
380
|
+
function assets() {
|
|
381
|
+
const root = join(dir, "assets");
|
|
382
|
+
const out = [];
|
|
383
|
+
const media = core.openProject(dir).project.media ?? {};
|
|
384
|
+
const walk = (d, depth) => {
|
|
385
|
+
if (depth > 4 || !existsSync(d) || out.length > 500)
|
|
386
|
+
return;
|
|
387
|
+
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
388
|
+
if (e.name.startsWith("."))
|
|
389
|
+
continue;
|
|
390
|
+
const full = join(d, e.name);
|
|
391
|
+
if (e.isDirectory())
|
|
392
|
+
walk(full, depth + 1);
|
|
393
|
+
else {
|
|
394
|
+
const kind = core.mediaKind(full);
|
|
395
|
+
const rel = relative(dir, full).split(sep).join("/");
|
|
396
|
+
if (kind !== "other")
|
|
397
|
+
out.push({ path: rel, kind, ...(media[rel] ? { origin: media[rel].origin } : {}) });
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
walk(root, 0);
|
|
402
|
+
return out.sort((a, b) => a.path.localeCompare(b.path));
|
|
403
|
+
}
|
|
404
|
+
// ---- upload: a file chosen in the page, streamed to a temporary file, then checked and copied in
|
|
405
|
+
async function upload(req, url) {
|
|
406
|
+
const name = basename(url.searchParams.get("name") ?? "");
|
|
407
|
+
if (!name || name.length > 200 || name.startsWith("."))
|
|
408
|
+
throw new HttpError(400, "name: the file's name");
|
|
409
|
+
const purpose = url.searchParams.get("purpose") ?? "media";
|
|
410
|
+
if (!["media", "logo", "font"].includes(purpose))
|
|
411
|
+
throw new HttpError(400, "purpose: media, logo or font");
|
|
412
|
+
const limit = core.DEFAULT_LIMITS.maxBytes;
|
|
413
|
+
const declared = Number(req.headers["content-length"] ?? NaN);
|
|
414
|
+
if (declared > limit)
|
|
415
|
+
throw new HttpError(413, `file over the ${Math.round(limit / 1024 ** 2)} MB limit`);
|
|
416
|
+
const tmp = mkdtempSync(join(tmpdir(), "derushly-upload-"));
|
|
417
|
+
const file = join(tmp, name);
|
|
418
|
+
try {
|
|
419
|
+
let size = 0;
|
|
420
|
+
const out = createWriteStream(file);
|
|
421
|
+
for await (const c of req) {
|
|
422
|
+
size += c.length;
|
|
423
|
+
if (size > limit) {
|
|
424
|
+
out.destroy();
|
|
425
|
+
throw new HttpError(413, `file over the ${Math.round(limit / 1024 ** 2)} MB limit`);
|
|
426
|
+
}
|
|
427
|
+
if (!out.write(c))
|
|
428
|
+
await new Promise((r) => out.once("drain", () => r()));
|
|
429
|
+
}
|
|
430
|
+
await new Promise((done, failed) => out.end((e) => (e ? failed(e) : done())));
|
|
431
|
+
if (purpose === "media") {
|
|
432
|
+
const folder = url.searchParams.get("folder") ?? undefined;
|
|
433
|
+
const license = url.searchParams.get("license") ?? undefined;
|
|
434
|
+
return core.importMedia(dir, [file], { ...(folder ? { folder } : {}), ...(license ? { license } : {}) });
|
|
435
|
+
}
|
|
436
|
+
const kit = url.searchParams.get("kit") ?? "";
|
|
437
|
+
const key = url.searchParams.get("key") ?? "";
|
|
438
|
+
if (!/^[a-z][a-z0-9-]{0,31}$/.test(key))
|
|
439
|
+
throw new HttpError(400, "key: the logo name or font role (lowercase letters, digits, dashes)");
|
|
440
|
+
return core.setBrand(dir, { id: kit, ...(purpose === "logo" ? { logos: { [key]: file } } : { fonts: { [key]: { file, ...(url.searchParams.get("family") ? { family: url.searchParams.get("family") } : {}) } } }) });
|
|
441
|
+
}
|
|
442
|
+
finally {
|
|
443
|
+
try {
|
|
444
|
+
rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
// a temporary file still held by the system: the OS cleans its temp folder
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
function state() {
|
|
452
|
+
const s = core.openProject(dir);
|
|
453
|
+
const exportsDir = join(dir, core.EXPORTS_DIR);
|
|
454
|
+
const exportsList = existsSync(exportsDir)
|
|
455
|
+
? readdirSync(exportsDir).filter((f) => f.toLowerCase().endsWith(".mp4")).map((f) => {
|
|
456
|
+
const st = statSync(join(exportsDir, f));
|
|
457
|
+
return { file: `${core.EXPORTS_DIR}/${f}`, bytes: st.size, time: st.mtime.toISOString() };
|
|
458
|
+
}).sort((a, b) => b.time.localeCompare(a.time)).slice(0, 30)
|
|
459
|
+
: [];
|
|
460
|
+
return {
|
|
461
|
+
project: s.project,
|
|
462
|
+
version: s.version,
|
|
463
|
+
captions: s.captions ? { scene: s.captions.scene, cues: s.captions.cues } : null,
|
|
464
|
+
variables: core.listVariables(dir),
|
|
465
|
+
notes: core.listNotes(dir),
|
|
466
|
+
formats: core.listFormats(dir),
|
|
467
|
+
history: core.history(dir, 30),
|
|
468
|
+
drift: core.detectDrift(dir),
|
|
469
|
+
render: core.renderStatus(dir),
|
|
470
|
+
exports: exportsList,
|
|
471
|
+
job,
|
|
472
|
+
files: previewOrigin() + filesBase,
|
|
473
|
+
folder: basename(dir),
|
|
474
|
+
brands: core.listBrands(dir),
|
|
475
|
+
adapters: core.listAdapters(dir),
|
|
476
|
+
library,
|
|
477
|
+
assets: assets(),
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
// ---- file watching: changes made elsewhere (the agent, the CLI) reach the page ---------------
|
|
481
|
+
let watcher;
|
|
482
|
+
let changeTimer;
|
|
483
|
+
try {
|
|
484
|
+
watcher = watch(dir, { recursive: true }, (_e, name) => {
|
|
485
|
+
const f = String(name ?? "");
|
|
486
|
+
if (!f || f.startsWith(core.EXPORTS_DIR + sep + ".rendering") || f.includes("node_modules"))
|
|
487
|
+
return;
|
|
488
|
+
if (!/^(project\.json|captions\.json|notes\.json|index\.html|compositions|\.history|\.derushly[\\/]render\.json|exports)/.test(f))
|
|
489
|
+
return;
|
|
490
|
+
clearTimeout(changeTimer);
|
|
491
|
+
changeTimer = setTimeout(() => send("change", { file: f.replaceAll("\\", "/") }), 150);
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
catch (e) {
|
|
495
|
+
log(`file watching unavailable: ${e.message}`);
|
|
496
|
+
}
|
|
497
|
+
// ---- HTTP -----------------------------------------------------------------------------------
|
|
498
|
+
const cookieOf = (req) => {
|
|
499
|
+
const m = (req.headers.cookie ?? "").match(/(?:^|;\s*)derushly_session=([A-Za-z0-9_-]+)/);
|
|
500
|
+
return m?.[1];
|
|
501
|
+
};
|
|
502
|
+
const authed = (req) => {
|
|
503
|
+
const c = cookieOf(req);
|
|
504
|
+
return !!c && [...sessions].some((s) => same(s, c));
|
|
505
|
+
};
|
|
506
|
+
const hostOk = (req) => [`127.0.0.1:${port}`, `localhost:${port}`].includes(req.headers.host ?? "");
|
|
507
|
+
function json(res, status, body) {
|
|
508
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
509
|
+
res.end(JSON.stringify(body));
|
|
510
|
+
}
|
|
511
|
+
function errorBody(e) {
|
|
512
|
+
const err = e instanceof DerushlyError ? e : null;
|
|
513
|
+
return { ok: false, code: err?.code ?? "internal", error: e.message, ...(err?.errors ? { errors: err.errors } : {}), ...(err?.drift ? { drift: err.drift } : {}) };
|
|
514
|
+
}
|
|
515
|
+
const statusOf = (code) => ({ usage: 400, invalid: 422, not_found: 404, exists: 409, drift: 409 }[code] ?? 500);
|
|
516
|
+
async function body(req) {
|
|
517
|
+
if (!(req.headers["content-type"] ?? "").startsWith("application/json"))
|
|
518
|
+
throw new HttpError(415, "expected application/json");
|
|
519
|
+
const chunks = [];
|
|
520
|
+
let size = 0;
|
|
521
|
+
for await (const c of req) {
|
|
522
|
+
size += c.length;
|
|
523
|
+
if (size > MAX_BODY)
|
|
524
|
+
throw new HttpError(413, "request too large");
|
|
525
|
+
chunks.push(c);
|
|
526
|
+
}
|
|
527
|
+
try {
|
|
528
|
+
const v = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
|
|
529
|
+
if (!v || typeof v !== "object" || Array.isArray(v))
|
|
530
|
+
throw new Error();
|
|
531
|
+
return v;
|
|
532
|
+
}
|
|
533
|
+
catch {
|
|
534
|
+
throw new HttpError(400, "invalid JSON");
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
function serveFile(req, res, file, headers) {
|
|
538
|
+
const st = statSync(file);
|
|
539
|
+
const type = TYPES[extname(file).toLowerCase()] ?? "application/octet-stream";
|
|
540
|
+
const base = { "content-type": type, "x-content-type-options": "nosniff", "accept-ranges": "bytes", "cache-control": "no-cache", ...headers };
|
|
541
|
+
const range = req.headers.range?.match(/^bytes=(\d*)-(\d*)$/);
|
|
542
|
+
if (range && st.size > 0) {
|
|
543
|
+
let start = range[1] ? Number(range[1]) : st.size - Number(range[2]);
|
|
544
|
+
let end = range[1] && range[2] ? Number(range[2]) : st.size - 1;
|
|
545
|
+
start = Math.max(0, start);
|
|
546
|
+
end = Math.min(end, st.size - 1);
|
|
547
|
+
if (start > end) {
|
|
548
|
+
res.writeHead(416, { "content-range": `bytes */${st.size}` });
|
|
549
|
+
return res.end();
|
|
550
|
+
}
|
|
551
|
+
res.writeHead(206, { ...base, "content-range": `bytes ${start}-${end}/${st.size}`, "content-length": String(end - start + 1) });
|
|
552
|
+
if (req.method === "HEAD")
|
|
553
|
+
return res.end();
|
|
554
|
+
return createReadStream(file, { start, end }).pipe(res);
|
|
555
|
+
}
|
|
556
|
+
res.writeHead(200, { ...base, "content-length": String(st.size) });
|
|
557
|
+
if (req.method === "HEAD")
|
|
558
|
+
return res.end();
|
|
559
|
+
createReadStream(file).pipe(res);
|
|
560
|
+
}
|
|
561
|
+
/** Project files for the preview (and snapshots, exports): read-only, no secrets, no history. */
|
|
562
|
+
function serveProject(req, res, rel, query) {
|
|
563
|
+
const cors = { "access-control-allow-origin": "*", "cross-origin-resource-policy": "cross-origin" };
|
|
564
|
+
if (req.method === "OPTIONS") {
|
|
565
|
+
res.writeHead(204, { ...cors, "access-control-allow-methods": "GET, HEAD", "access-control-allow-headers": "range" });
|
|
566
|
+
return res.end();
|
|
567
|
+
}
|
|
568
|
+
if (req.method !== "GET" && req.method !== "HEAD")
|
|
569
|
+
throw new HttpError(405, "read-only");
|
|
570
|
+
const clean = decodeURIComponent(rel || "index.html");
|
|
571
|
+
if (denied(clean))
|
|
572
|
+
throw new HttpError(404, "not found");
|
|
573
|
+
const file = resolve(dir, clean);
|
|
574
|
+
const r = relative(dir, file);
|
|
575
|
+
if (r.startsWith("..") || resolve(dir, r) !== file || r === "" || !core.staysInside(dir, file))
|
|
576
|
+
throw new HttpError(404, "not found");
|
|
577
|
+
const html = { ...cors, "content-security-policy": PREVIEW_CSP, "content-type": TYPES[".html"], "cache-control": "no-store", "x-content-type-options": "nosniff" };
|
|
578
|
+
if (r === RUNTIME)
|
|
579
|
+
return serveFile(req, res, join(uiDir, RUNTIME), cors);
|
|
580
|
+
if (r === "index.html") {
|
|
581
|
+
// A format variant: its generated index.html (same scenes, scaled into the variant's frame).
|
|
582
|
+
const p = core.openProject(dir).project;
|
|
583
|
+
const v = core.resolveVariant(p, query.get("format") ?? undefined);
|
|
584
|
+
const out = (v ? core.variantHtml(dir, p, v) : readFileSync(file, "utf8"))
|
|
585
|
+
.replace(/<\/body>/i, ` <script src="${RUNTIME}" data-derushly-preview></script>\n </body>`);
|
|
586
|
+
res.writeHead(200, html);
|
|
587
|
+
return res.end(req.method === "HEAD" ? undefined : out);
|
|
588
|
+
}
|
|
589
|
+
const fmt = r.replace(/\\/g, "/").match(/^compositions\/[^/]+@([a-z0-9][a-z0-9-]*)\.html$/);
|
|
590
|
+
if (fmt && !existsSync(file)) {
|
|
591
|
+
// A scene laid out again for a format variant (library blocks, captions).
|
|
592
|
+
const p = core.openProject(dir).project;
|
|
593
|
+
const v = core.resolveVariant(p, fmt[1]);
|
|
594
|
+
const out = v ? core.variantOverlay(dir, p, v)[r.replace(/\\/g, "/")] : undefined;
|
|
595
|
+
if (out === undefined)
|
|
596
|
+
throw new HttpError(404, "not found");
|
|
597
|
+
res.writeHead(200, html);
|
|
598
|
+
return res.end(req.method === "HEAD" ? undefined : out);
|
|
599
|
+
}
|
|
600
|
+
if (!existsSync(file) || !statSync(file).isFile())
|
|
601
|
+
throw new HttpError(404, "not found");
|
|
602
|
+
if (extname(file).toLowerCase() === ".html") {
|
|
603
|
+
res.writeHead(200, html);
|
|
604
|
+
return res.end(req.method === "HEAD" ? undefined : readFileSync(file));
|
|
605
|
+
}
|
|
606
|
+
serveFile(req, res, file, cors);
|
|
607
|
+
}
|
|
608
|
+
function servePage(res) {
|
|
609
|
+
const page = readFileSync(join(uiDir, "index.html"), "utf8")
|
|
610
|
+
.replace("</head>", ` <meta name="derushly-csrf" content="${csrf}">\n <meta name="derushly-files" content="${previewOrigin()}${filesBase}">\n </head>`);
|
|
611
|
+
res.writeHead(200, {
|
|
612
|
+
"content-type": TYPES[".html"], "cache-control": "no-store", "content-security-policy": pageCsp(previewOrigin()),
|
|
613
|
+
"x-content-type-options": "nosniff", "referrer-policy": "no-referrer", "x-frame-options": "DENY",
|
|
614
|
+
});
|
|
615
|
+
res.end(page);
|
|
616
|
+
}
|
|
617
|
+
async function handle(req, res) {
|
|
618
|
+
if (!hostOk(req))
|
|
619
|
+
throw new HttpError(421, "wrong host");
|
|
620
|
+
const url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
|
|
621
|
+
const path = url.pathname;
|
|
622
|
+
// Launch: the one-time token becomes a session cookie, then the token leaves the address bar.
|
|
623
|
+
const t = url.searchParams.get("t");
|
|
624
|
+
if (path === "/" && t) {
|
|
625
|
+
const known = [...launch].find((x) => same(x, t));
|
|
626
|
+
if (!known) {
|
|
627
|
+
res.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
|
|
628
|
+
return res.end("This link was already used. Run `derushly studio` again, or ask the agent for a new link.");
|
|
629
|
+
}
|
|
630
|
+
launch.delete(known);
|
|
631
|
+
const sid = token();
|
|
632
|
+
sessions.add(sid);
|
|
633
|
+
res.writeHead(303, { location: "/", "set-cookie": `derushly_session=${sid}; HttpOnly; SameSite=Strict; Path=/`, "cache-control": "no-store", "referrer-policy": "no-referrer" });
|
|
634
|
+
return res.end();
|
|
635
|
+
}
|
|
636
|
+
if (!authed(req)) {
|
|
637
|
+
res.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
|
|
638
|
+
return res.end("Open the link printed by `derushly studio` (it can be used once).");
|
|
639
|
+
}
|
|
640
|
+
if (req.method === "GET" && path === "/")
|
|
641
|
+
return servePage(res);
|
|
642
|
+
if (req.method === "GET" && path === "/api/state")
|
|
643
|
+
return json(res, 200, state());
|
|
644
|
+
if (req.method === "GET" && path === "/api/events") {
|
|
645
|
+
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
|
|
646
|
+
res.write(`event: hello\ndata: {}\n\n`);
|
|
647
|
+
events.add(res);
|
|
648
|
+
const ping = setInterval(() => res.write(": ping\n\n"), 20_000);
|
|
649
|
+
req.on("close", () => {
|
|
650
|
+
clearInterval(ping);
|
|
651
|
+
events.delete(res);
|
|
652
|
+
});
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
if (req.method === "POST" && (path === "/api/op" || path === "/api/upload")) {
|
|
656
|
+
const origin = req.headers.origin;
|
|
657
|
+
if (origin !== `http://127.0.0.1:${port}` && origin !== `http://localhost:${port}`)
|
|
658
|
+
throw new HttpError(403, "cross-origin request refused");
|
|
659
|
+
const h = req.headers["x-derushly-csrf"];
|
|
660
|
+
if (typeof h !== "string" || !same(h, csrf))
|
|
661
|
+
throw new HttpError(403, "missing or wrong CSRF token");
|
|
662
|
+
if (path === "/api/upload") {
|
|
663
|
+
if (!(req.headers["content-type"] ?? "").startsWith("application/octet-stream"))
|
|
664
|
+
throw new HttpError(415, "expected application/octet-stream");
|
|
665
|
+
try {
|
|
666
|
+
const out = await upload(req, url);
|
|
667
|
+
log(`upload ${url.searchParams.get("purpose") ?? "media"}`);
|
|
668
|
+
send("change", { op: "upload" });
|
|
669
|
+
return json(res, 200, { ok: true, ...out });
|
|
670
|
+
}
|
|
671
|
+
catch (e) {
|
|
672
|
+
if (e instanceof HttpError)
|
|
673
|
+
throw e;
|
|
674
|
+
return json(res, statusOf(e.code), errorBody(e));
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
const b = await body(req);
|
|
678
|
+
const name = typeof b.op === "string" ? b.op : "";
|
|
679
|
+
const op = Object.hasOwn(ops, name) ? ops[name] : undefined;
|
|
680
|
+
if (!op)
|
|
681
|
+
throw new HttpError(400, `unknown operation "${name}"`);
|
|
682
|
+
try {
|
|
683
|
+
const out = (await op((b.args ?? {})));
|
|
684
|
+
log(`op ${name}`);
|
|
685
|
+
send("change", { op: name });
|
|
686
|
+
return json(res, 200, { ok: true, ...(out && "kind" in out ? { job: out } : out) });
|
|
687
|
+
}
|
|
688
|
+
catch (e) {
|
|
689
|
+
return json(res, statusOf(e.code), errorBody(e));
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
if (req.method === "GET" && !path.startsWith("/api/")) {
|
|
693
|
+
// The page's own files (scripts, styles).
|
|
694
|
+
const file = resolve(uiDir, "." + decodeURIComponent(path));
|
|
695
|
+
const r = relative(uiDir, file);
|
|
696
|
+
if (!r.startsWith("..") && existsSync(file) && statSync(file).isFile()) {
|
|
697
|
+
return serveFile(req, res, file, { "cache-control": path.startsWith("/assets/") ? "public, max-age=31536000, immutable" : "no-cache" });
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
throw new HttpError(404, "not found");
|
|
701
|
+
}
|
|
702
|
+
const fail = (req, res) => (e) => {
|
|
703
|
+
const status = e instanceof HttpError ? e.status : e instanceof DerushlyError ? statusOf(e.code) : 500;
|
|
704
|
+
if (status >= 500)
|
|
705
|
+
log(`error ${req.method} ${req.url}: ${e.stack}`);
|
|
706
|
+
else
|
|
707
|
+
log(`refused ${req.method} ${(req.url ?? "").replace(/t=[^&]+/, "t=…")}: ${e.message}`);
|
|
708
|
+
if (!res.headersSent)
|
|
709
|
+
json(res, status, { ok: false, code: status === 403 ? "forbidden" : "http", error: e.message });
|
|
710
|
+
else
|
|
711
|
+
res.end();
|
|
712
|
+
};
|
|
713
|
+
const server = createServer((req, res) => void handle(req, res).catch(fail(req, res)));
|
|
714
|
+
// The preview origin: project files only, under the unguessable path.
|
|
715
|
+
const preview = createServer((req, res) => {
|
|
716
|
+
try {
|
|
717
|
+
if (req.headers.host !== `127.0.0.1:${previewPort}`)
|
|
718
|
+
throw new HttpError(421, "wrong host");
|
|
719
|
+
const url = new URL(req.url ?? "/", previewOrigin());
|
|
720
|
+
if (!url.pathname.startsWith(filesBase))
|
|
721
|
+
throw new HttpError(404, "not found");
|
|
722
|
+
serveProject(req, res, url.pathname.slice(filesBase.length), url.searchParams);
|
|
723
|
+
}
|
|
724
|
+
catch (e) {
|
|
725
|
+
fail(req, res)(e);
|
|
726
|
+
}
|
|
727
|
+
});
|
|
728
|
+
const listen = (s, p) => new Promise((done, failed) => {
|
|
729
|
+
s.once("error", failed);
|
|
730
|
+
s.listen(p, "127.0.0.1", () => done(s.address().port));
|
|
731
|
+
});
|
|
732
|
+
port = await listen(server, opts.port ?? 0);
|
|
733
|
+
previewPort = await listen(preview, 0);
|
|
734
|
+
const link = (t) => `http://127.0.0.1:${port}/?t=${t}`;
|
|
735
|
+
return {
|
|
736
|
+
url: link([...launch][0]),
|
|
737
|
+
port,
|
|
738
|
+
previewUrl: previewOrigin() + filesBase,
|
|
739
|
+
newLink() {
|
|
740
|
+
const t = token();
|
|
741
|
+
launch.add(t);
|
|
742
|
+
return link(t);
|
|
743
|
+
},
|
|
744
|
+
close: () => new Promise((done) => {
|
|
745
|
+
watcher?.close();
|
|
746
|
+
clearTimeout(changeTimer);
|
|
747
|
+
for (const res of events)
|
|
748
|
+
res.end();
|
|
749
|
+
server.closeAllConnections();
|
|
750
|
+
preview.closeAllConnections();
|
|
751
|
+
preview.close();
|
|
752
|
+
server.close(() => done());
|
|
753
|
+
}),
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
//# sourceMappingURL=server.js.map
|