@lumesync/studio 0.0.0-stage → 1.0.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/README.md +229 -2
- package/bin/lumesync-studio.js +7 -0
- package/package.json +33 -4
- package/skills/courseware-authoring/SKILL.md +226 -0
- package/skills/courseware-authoring/references/tools.md +133 -0
- package/src/chat/mailbox.js +307 -0
- package/src/cli/main.js +669 -0
- package/src/core/document.js +349 -0
- package/src/core/errors.js +44 -0
- package/src/core/exporter.js +272 -0
- package/src/core/model.js +305 -0
- package/src/core/rules.js +288 -0
- package/src/core/storage.js +616 -0
- package/src/core/transaction.js +250 -0
- package/src/core/validate.js +503 -0
- package/src/core/zip.js +251 -0
- package/src/editing/operations.js +671 -0
- package/src/editing/session.js +838 -0
- package/src/server/http.js +944 -0
- package/src/server/ws.js +128 -0
- package/src/templates/courseware.js +48 -0
- package/src/templates/init.js +374 -0
- package/src/tools/registry.js +487 -0
- package/ui/app.js +2671 -0
- package/ui/home.html +32 -0
- package/ui/home.js +148 -0
- package/ui/index.html +210 -0
- package/ui/shared/edit-model.js +105 -0
- package/ui/shared/quiz-view.js +455 -0
- package/ui/style.css +1161 -0
|
@@ -0,0 +1,944 @@
|
|
|
1
|
+
// 本地 HTTP + WS 服务:静态 UI、工具 API、课件资源、实时事件。
|
|
2
|
+
// 只监听回环地址;所有文件访问经过真实路径白名单;浏览器用同源 Cookie 鉴权。
|
|
3
|
+
|
|
4
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import fsp from 'node:fs/promises';
|
|
7
|
+
import http from 'node:http';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { ChatMailbox } from '../chat/mailbox.js';
|
|
12
|
+
import { ERROR_CODES, StudioError } from '../core/errors.js';
|
|
13
|
+
import {
|
|
14
|
+
COURSEWARE_CSP, contentType, listPackageFiles, resolveRealFile,
|
|
15
|
+
readSessionFile, removeSessionFile, writeSessionFile,
|
|
16
|
+
} from '../core/storage.js';
|
|
17
|
+
import { exportCourseware, packageCourseware } from '../core/exporter.js';
|
|
18
|
+
import { deriveAnswer } from '../core/document.js';
|
|
19
|
+
import { acceptUpgrade } from './ws.js';
|
|
20
|
+
|
|
21
|
+
const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
|
|
22
|
+
const DEFAULT_MAX_BODY = 8 * 1024 * 1024;
|
|
23
|
+
|
|
24
|
+
export async function startServer({ root, document, session, tools, options = {}, chat }) {
|
|
25
|
+
const host = options.host ?? '127.0.0.1';
|
|
26
|
+
const urlHost = host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host;
|
|
27
|
+
const preferredPort = Number(options.port ?? 4173);
|
|
28
|
+
const token = options.token ?? randomBytes(18).toString('base64url');
|
|
29
|
+
const maxBody = Number.isFinite(Number(options.maxBody)) ? Number(options.maxBody) : DEFAULT_MAX_BODY;
|
|
30
|
+
let mailbox = chat ?? new ChatMailbox({ root });
|
|
31
|
+
const clients = new Map();
|
|
32
|
+
const ackHistory = new Map();
|
|
33
|
+
const waiters = new Set();
|
|
34
|
+
const startedAt = new Date().toISOString();
|
|
35
|
+
let listeningPort = 0;
|
|
36
|
+
let sequence = 0;
|
|
37
|
+
|
|
38
|
+
const broadcast = (event) => {
|
|
39
|
+
const payload = { ...event, seq: sequence += 1, ts: Date.now() };
|
|
40
|
+
let receivers = 0;
|
|
41
|
+
for (const [clientId, client] of clients) {
|
|
42
|
+
try {
|
|
43
|
+
client.sendJson({ ...payload, clientId });
|
|
44
|
+
receivers += 1;
|
|
45
|
+
} catch {
|
|
46
|
+
clients.delete(clientId);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return receivers;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// 课件库:以当前课件所在目录为范围,列出同级或下一级的已编辑课件。
|
|
53
|
+
// “已编辑”以 .studio/document.json 为准,未打开过的模板不会被列出。
|
|
54
|
+
async function libraryItems() {
|
|
55
|
+
const items = [];
|
|
56
|
+
for (const dir of await discoverCoursewareRoots(root)) {
|
|
57
|
+
items.push(await describeCoursewareRoot(dir));
|
|
58
|
+
}
|
|
59
|
+
return items.sort((a, b) => {
|
|
60
|
+
if (a.current !== b.current) return a.current ? -1 : 1;
|
|
61
|
+
return String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? ''));
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function describeCoursewareRoot(dir) {
|
|
66
|
+
const current = dir === root;
|
|
67
|
+
let manifest = null;
|
|
68
|
+
let revision = null;
|
|
69
|
+
let updatedAt = null;
|
|
70
|
+
try {
|
|
71
|
+
manifest = JSON.parse(await fsp.readFile(path.join(dir, 'manifest.json'), 'utf8'));
|
|
72
|
+
} catch {
|
|
73
|
+
manifest = null;
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
const documentFile = path.join(dir, '.studio', 'document.json');
|
|
77
|
+
const [text, stat] = await Promise.all([
|
|
78
|
+
fsp.readFile(documentFile, 'utf8'),
|
|
79
|
+
fsp.stat(documentFile),
|
|
80
|
+
]);
|
|
81
|
+
const value = JSON.parse(text);
|
|
82
|
+
revision = Number.isInteger(value?.revision) ? value.revision : null;
|
|
83
|
+
updatedAt = stat.mtime.toISOString();
|
|
84
|
+
} catch {
|
|
85
|
+
// 缺少编辑记录时仍展示课件,只是没有 revision 与更新时间。
|
|
86
|
+
}
|
|
87
|
+
const live = current
|
|
88
|
+
? { previewUrl: `http://${urlHost}:${listeningPort}/` }
|
|
89
|
+
: await liveSessionOf(dir);
|
|
90
|
+
return {
|
|
91
|
+
root: dir,
|
|
92
|
+
name: path.basename(dir),
|
|
93
|
+
title: typeof manifest?.title === 'string' ? manifest.title : path.basename(dir),
|
|
94
|
+
subject: typeof manifest?.subject === 'string' ? manifest.subject : null,
|
|
95
|
+
grade: typeof manifest?.grade === 'string' ? manifest.grade : null,
|
|
96
|
+
scenes: Array.isArray(manifest?.scenes) ? manifest.scenes.length : 0,
|
|
97
|
+
durationMin: Number.isInteger(manifest?.durationMin) ? manifest.durationMin : null,
|
|
98
|
+
revision,
|
|
99
|
+
updatedAt,
|
|
100
|
+
current,
|
|
101
|
+
running: Boolean(live?.previewUrl),
|
|
102
|
+
previewUrl: live?.previewUrl ?? null,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function liveSessionOf(dir) {
|
|
107
|
+
const value = await readSessionFile(dir);
|
|
108
|
+
if (!value || !Number.isInteger(value.pid) || typeof value.previewUrl !== 'string') return null;
|
|
109
|
+
return pidAlive(value.pid) ? value : null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// 原地切换当前课件:重建文档、编辑会话、工具与信箱,并同步 session.json。
|
|
113
|
+
async function switchCourseware(nextRoot) {
|
|
114
|
+
if (typeof options.activateRoot !== 'function') {
|
|
115
|
+
throw new StudioError(ERROR_CODES.PREVIEW_UNAVAILABLE, '当前 Studio 不支持切换课件', undefined, 501);
|
|
116
|
+
}
|
|
117
|
+
const previousRoot = root;
|
|
118
|
+
const next = await options.activateRoot(nextRoot);
|
|
119
|
+
root = next.root ?? nextRoot;
|
|
120
|
+
document = next.document;
|
|
121
|
+
session = next.session;
|
|
122
|
+
tools = next.tools;
|
|
123
|
+
mailbox = next.chat ?? new ChatMailbox({ root });
|
|
124
|
+
await writeSessionFile(root, { ...describe(), startedAt }).catch(() => {});
|
|
125
|
+
await removeSessionFile(previousRoot, (value) => value?.pid === process.pid && value?.token === token).catch(() => {});
|
|
126
|
+
broadcast({ type: 'studio.switched', root });
|
|
127
|
+
return describe();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const server = http.createServer(async (request, response) => {
|
|
131
|
+
const url = new URL(request.url, `http://${request.headers.host ?? '127.0.0.1'}`);
|
|
132
|
+
try {
|
|
133
|
+
if (options.logLevel === 'debug') {
|
|
134
|
+
process.stderr.write(`[studio] ${request.method} ${url.pathname}\n`);
|
|
135
|
+
}
|
|
136
|
+
if (url.pathname === '/healthz') {
|
|
137
|
+
return sendJson(response, 200, {
|
|
138
|
+
status: document.report.valid ? 'ok' : 'degraded',
|
|
139
|
+
protocolVersion: 1,
|
|
140
|
+
packageVersion: packageVersion(),
|
|
141
|
+
skillVersion: skillVersion(),
|
|
142
|
+
revision: document.revision,
|
|
143
|
+
previewKey: document.previewKey,
|
|
144
|
+
coursewareRoot: root,
|
|
145
|
+
valid: document.report.valid,
|
|
146
|
+
errors: document.report.errors,
|
|
147
|
+
startedAt,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
if (url.pathname.startsWith('/api/')) {
|
|
151
|
+
return await handleApi(request, response, url);
|
|
152
|
+
}
|
|
153
|
+
if (url.pathname.startsWith('/lessons/')) {
|
|
154
|
+
return await serveLessonFile(request, response, url);
|
|
155
|
+
}
|
|
156
|
+
if (url.pathname.startsWith('/ui/') || url.pathname === '/' || url.pathname === '/index.html' || url.pathname === '/home') {
|
|
157
|
+
return await serveUi(request, response, url);
|
|
158
|
+
}
|
|
159
|
+
if (url.pathname === '/favicon.ico') {
|
|
160
|
+
response.writeHead(204).end();
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
sendJson(response, 404, { error: { code: ERROR_CODES.BAD_REQUEST, message: '未找到资源' } });
|
|
164
|
+
} catch (error) {
|
|
165
|
+
const studio = error instanceof StudioError ? error : new StudioError(ERROR_CODES.INTERNAL, error.message, undefined, 500);
|
|
166
|
+
if (!response.headersSent) sendJson(response, studio.status ?? 500, studio.toJSON());
|
|
167
|
+
else response.end();
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
server.on('upgrade', (request, socket) => {
|
|
172
|
+
const url = new URL(request.url, `http://${request.headers.host ?? '127.0.0.1'}`);
|
|
173
|
+
if (url.pathname !== '/ws') {
|
|
174
|
+
socket.destroy();
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (!authorizeWsRequest(request)) {
|
|
178
|
+
socket.write('HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n');
|
|
179
|
+
socket.destroy();
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const clientId = `c_${randomBytes(6).toString('base64url')}`;
|
|
183
|
+
const client = acceptUpgrade(request, socket, {
|
|
184
|
+
maxFrameBytes: 65536,
|
|
185
|
+
onClose: () => clients.delete(clientId),
|
|
186
|
+
onMessage: (text) => {
|
|
187
|
+
let message;
|
|
188
|
+
try {
|
|
189
|
+
message = JSON.parse(text);
|
|
190
|
+
} catch {
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
if (message?.type === 'ping') client.sendJson({ type: 'pong', ts: Date.now() });
|
|
194
|
+
if (message?.type === 'renderAck') handleRenderAck(clientId, message);
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
if (!client) return;
|
|
198
|
+
clients.set(clientId, client);
|
|
199
|
+
client.sendJson({
|
|
200
|
+
type: 'studio.hello',
|
|
201
|
+
protocolVersion: 1,
|
|
202
|
+
packageVersion: packageVersion(),
|
|
203
|
+
skillVersion: skillVersion(),
|
|
204
|
+
clientId,
|
|
205
|
+
revision: document.revision,
|
|
206
|
+
coursewareId: document.manifest?.id ?? null,
|
|
207
|
+
previewKey: document.previewKey,
|
|
208
|
+
exists: document.exists,
|
|
209
|
+
report: document.report,
|
|
210
|
+
});
|
|
211
|
+
if (document.exists) {
|
|
212
|
+
client.sendJson({
|
|
213
|
+
type: 'courseware.snapshot',
|
|
214
|
+
revision: document.revision,
|
|
215
|
+
document: document.toAuthorView(),
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
function handleRenderAck(clientId, message) {
|
|
221
|
+
if (!Number.isInteger(message.revision) || message.revision !== document.revision) return;
|
|
222
|
+
if (!document.exists) return;
|
|
223
|
+
const coursewareId = document.manifest?.id ?? null;
|
|
224
|
+
if (message.coursewareId !== undefined && message.coursewareId !== coursewareId) return;
|
|
225
|
+
if (message.sceneId !== undefined && !document.sceneById(message.sceneId)) return;
|
|
226
|
+
const ack = { revision: message.revision, sceneId: message.sceneId ?? null, clientId, ts: Date.now() };
|
|
227
|
+
if (!ackHistory.has(message.revision)) ackHistory.set(message.revision, new Map());
|
|
228
|
+
ackHistory.get(message.revision).set(clientId, ack);
|
|
229
|
+
broadcast({ type: 'preview.ack', revision: ack.revision, sceneId: ack.sceneId, ackedClientId: clientId });
|
|
230
|
+
for (const waiter of [...waiters]) {
|
|
231
|
+
if (waiter.revision !== ack.revision) continue;
|
|
232
|
+
if (waiter.sceneId && waiter.sceneId !== ack.sceneId) continue;
|
|
233
|
+
waiters.delete(waiter);
|
|
234
|
+
clearTimeout(waiter.timer);
|
|
235
|
+
waiter.resolve({ acknowledged: true, ack, clients: clients.size });
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function waitForAck({ revision, sceneId = null, timeoutMs = 1200 } = {}) {
|
|
240
|
+
const existing = ackHistory.get(revision);
|
|
241
|
+
const matched = existing ? [...existing.values()].find((ack) => !sceneId || ack.sceneId === sceneId) : null;
|
|
242
|
+
if (matched) return Promise.resolve({ acknowledged: true, ack: matched, clients: clients.size });
|
|
243
|
+
if (clients.size === 0) {
|
|
244
|
+
return Promise.resolve({ acknowledged: false, reason: 'NO_PREVIEW_CLIENT', clients: 0 });
|
|
245
|
+
}
|
|
246
|
+
return new Promise((resolve) => {
|
|
247
|
+
const waiter = {
|
|
248
|
+
revision,
|
|
249
|
+
sceneId,
|
|
250
|
+
resolve,
|
|
251
|
+
timer: setTimeout(() => {
|
|
252
|
+
waiters.delete(waiter);
|
|
253
|
+
resolve({ acknowledged: false, reason: 'ACK_TIMEOUT', clients: clients.size, timeoutMs });
|
|
254
|
+
}, Math.min(Math.max(Number(timeoutMs) || 1200, 100), 10000)),
|
|
255
|
+
};
|
|
256
|
+
waiters.add(waiter);
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function handleApi(request, response, url) {
|
|
261
|
+
if (request.method === 'OPTIONS') {
|
|
262
|
+
response.writeHead(204).end();
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
const route = url.pathname.slice('/api/'.length);
|
|
266
|
+
const authenticated = authorizeRequest(request);
|
|
267
|
+
// 未鉴权的会话接口只返回浏览器启动所需的最小信息,且永远不含 token。
|
|
268
|
+
if (route === 'session' && request.method === 'GET') {
|
|
269
|
+
const base = publicSession(authenticated);
|
|
270
|
+
return sendJson(response, 200, base);
|
|
271
|
+
}
|
|
272
|
+
if (!authenticated) {
|
|
273
|
+
throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, '本地编辑会话凭证无效', undefined, 401);
|
|
274
|
+
}
|
|
275
|
+
if (route === 'library' && request.method === 'GET') {
|
|
276
|
+
return sendJson(response, 200, { currentRoot: root, items: await libraryItems() });
|
|
277
|
+
}
|
|
278
|
+
if (route === 'library/open' && request.method === 'POST') {
|
|
279
|
+
const body = await readBody(request);
|
|
280
|
+
const target = typeof body?.root === 'string' ? path.resolve(body.root) : '';
|
|
281
|
+
const item = (await libraryItems()).find((entry) => entry.root === target);
|
|
282
|
+
if (!item) {
|
|
283
|
+
throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, '该课件不在课件库中', { root: target }, 403);
|
|
284
|
+
}
|
|
285
|
+
if (item.current) return sendJson(response, 200, { status: 'ready', current: true, ...describe() });
|
|
286
|
+
// 该课件已有独立进程在服务时直接跳转,避免两个服务同时写同一目录。
|
|
287
|
+
if (item.running && item.previewUrl) {
|
|
288
|
+
return sendJson(response, 200, { status: 'running', root: item.root, previewUrl: item.previewUrl });
|
|
289
|
+
}
|
|
290
|
+
const info = await switchCourseware(item.root);
|
|
291
|
+
return sendJson(response, 200, { status: 'ready', ...info });
|
|
292
|
+
}
|
|
293
|
+
if (route === 'document') {
|
|
294
|
+
const snapshot = await session.readDocument();
|
|
295
|
+
return sendJson(response, 200, snapshot);
|
|
296
|
+
}
|
|
297
|
+
if (route === 'tools') {
|
|
298
|
+
return sendJson(response, 200, { tools: tools.list().map((tool) => ({ name: tool.name, description: tool.description, highImpact: tool.highImpact, input: tool.input })) });
|
|
299
|
+
}
|
|
300
|
+
if (route === 'invoke') {
|
|
301
|
+
const body = await readBody(request);
|
|
302
|
+
const name = body?.tool;
|
|
303
|
+
if (typeof name !== 'string') throw new StudioError(ERROR_CODES.OPERATION_INVALID, '缺少 tool 字段', undefined, 400);
|
|
304
|
+
const result = await tools.invoke(name, body.args ?? {});
|
|
305
|
+
return sendJson(response, 200, result);
|
|
306
|
+
}
|
|
307
|
+
if (route === 'undo') {
|
|
308
|
+
const body = await readBody(request);
|
|
309
|
+
const result = await tools.invoke('courseware.undo', { revision: body?.revision, confirm: body?.confirm });
|
|
310
|
+
return sendJson(response, 200, result);
|
|
311
|
+
}
|
|
312
|
+
if (route === 'export' && request.method === 'GET') {
|
|
313
|
+
return await sendExport(response);
|
|
314
|
+
}
|
|
315
|
+
// 界面对话:浏览器写入用户消息,启动 Studio 的 Agent 通过 chat.pull 拉取。
|
|
316
|
+
if (route === 'chat' && request.method === 'GET') {
|
|
317
|
+
const since = Number(url.searchParams.get('since') ?? 0);
|
|
318
|
+
const limit = Number(url.searchParams.get('limit') ?? 120);
|
|
319
|
+
const snapshot = await mailbox.list({ since, limit });
|
|
320
|
+
const pending = await mailbox.pending({ limit: 50 });
|
|
321
|
+
return sendJson(response, 200, {
|
|
322
|
+
...snapshot,
|
|
323
|
+
pending: pending.length,
|
|
324
|
+
claimed: await mailbox.claimedIds(),
|
|
325
|
+
revision: document.revision,
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
if (route === 'chat/pending' && request.method === 'GET') {
|
|
329
|
+
const limit = Number(url.searchParams.get('limit') ?? 20);
|
|
330
|
+
return sendJson(response, 200, {
|
|
331
|
+
messages: await mailbox.pending({ limit }),
|
|
332
|
+
revision: document.revision,
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
if (route === 'chat/claim' && request.method === 'POST') {
|
|
336
|
+
const body = await readBody(request);
|
|
337
|
+
const result = await mailbox.claim({
|
|
338
|
+
id: body?.id,
|
|
339
|
+
by: body?.by,
|
|
340
|
+
ttlMs: body?.ttlMs,
|
|
341
|
+
});
|
|
342
|
+
if (!result.claimed) {
|
|
343
|
+
throw new StudioError(
|
|
344
|
+
ERROR_CODES.OPERATION_CONFLICT,
|
|
345
|
+
'消息已被其他监听器认领',
|
|
346
|
+
{ id: body?.id, by: result.by, expiresAt: result.expiresAt },
|
|
347
|
+
409,
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
return sendJson(response, 200, { ...result, revision: document.revision });
|
|
351
|
+
}
|
|
352
|
+
if (route === 'chat' && request.method === 'POST') {
|
|
353
|
+
const body = await readBody(request);
|
|
354
|
+
const message = await mailbox.append({
|
|
355
|
+
role: 'user',
|
|
356
|
+
text: body?.text,
|
|
357
|
+
selection: body?.selection,
|
|
358
|
+
revision: Number.isInteger(body?.revision) ? body.revision : document.revision,
|
|
359
|
+
});
|
|
360
|
+
broadcast({ type: 'chat.message', message });
|
|
361
|
+
return sendJson(response, 200, { message, cursor: message.seq, revision: document.revision });
|
|
362
|
+
}
|
|
363
|
+
if (route === 'chat/reply' && request.method === 'POST') {
|
|
364
|
+
const body = await readBody(request);
|
|
365
|
+
const message = await mailbox.append({
|
|
366
|
+
role: 'agent',
|
|
367
|
+
text: body?.text,
|
|
368
|
+
inReplyTo: typeof body?.inReplyTo === 'string' ? body.inReplyTo : null,
|
|
369
|
+
revision: Number.isInteger(body?.revision) ? body.revision : document.revision,
|
|
370
|
+
});
|
|
371
|
+
broadcast({ type: 'chat.message', message });
|
|
372
|
+
return sendJson(response, 200, { message, cursor: message.seq, revision: document.revision });
|
|
373
|
+
}
|
|
374
|
+
if (route === 'import' && request.method === 'POST') {
|
|
375
|
+
// .lume 是二进制 ZIP,允许比 JSON API 更大的请求体。
|
|
376
|
+
const buffer = await readBinaryBody(request, Math.max(maxBody, 64 * 1024 * 1024));
|
|
377
|
+
const result = await session.importCourseware(buffer);
|
|
378
|
+
return sendJson(response, 200, result);
|
|
379
|
+
}
|
|
380
|
+
throw new StudioError(ERROR_CODES.BAD_REQUEST, `未知接口 /api/${route}`, undefined, 404);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// 课件资源:只允许当前 manifest 声明的场景、assets/ 与场景引用资源。
|
|
384
|
+
async function serveLessonFile(request, response, url) {
|
|
385
|
+
if (!document.exists) throw new StudioError(ERROR_CODES.COURSEWARE_INVALID, '当前没有可预览课件', undefined, 422);
|
|
386
|
+
const rest = url.pathname.slice('/lessons/'.length);
|
|
387
|
+
const slash = rest.indexOf('/content/');
|
|
388
|
+
if (slash === -1) throw new StudioError(ERROR_CODES.BAD_REQUEST, '资源路径不合法', undefined, 400);
|
|
389
|
+
const previewKey = decodeURIComponent(rest.slice(0, slash));
|
|
390
|
+
const relative = decodeURIComponent(rest.slice(slash + '/content/'.length));
|
|
391
|
+
if (previewKey !== document.previewKey) throw new StudioError(ERROR_CODES.BAD_REQUEST, '课程不匹配', undefined, 404);
|
|
392
|
+
const allowed = allowedLessonFiles(document.manifest, root);
|
|
393
|
+
if (!allowed.has(relative)) throw new StudioError(ERROR_CODES.ASSET_FORBIDDEN, '资源未在课件清单中声明', { path: relative }, 403);
|
|
394
|
+
let absolute;
|
|
395
|
+
try {
|
|
396
|
+
absolute = resolveRealFile(root, relative, { code: ERROR_CODES.ASSET_FORBIDDEN });
|
|
397
|
+
} catch {
|
|
398
|
+
throw new StudioError(ERROR_CODES.ASSET_FORBIDDEN, '资源不可安全读取', { path: relative }, 403);
|
|
399
|
+
}
|
|
400
|
+
let content;
|
|
401
|
+
try {
|
|
402
|
+
content = await fsp.readFile(absolute);
|
|
403
|
+
} catch {
|
|
404
|
+
throw new StudioError(ERROR_CODES.BAD_REQUEST, '资源不存在', { path: relative }, 404);
|
|
405
|
+
}
|
|
406
|
+
// 预览(主画面与缩略图)注入题目数据与通用题目组件;
|
|
407
|
+
// 源码读取不带 pick/thumb 参数,保持原始内容不被改写。
|
|
408
|
+
const upper = relative.toLowerCase();
|
|
409
|
+
if (upper.endsWith('.html')) {
|
|
410
|
+
const isMain = url.searchParams.get('pick') === '1';
|
|
411
|
+
const isThumb = url.searchParams.get('thumb') === '1';
|
|
412
|
+
if (isMain || isThumb) {
|
|
413
|
+
let text = content.toString('utf8');
|
|
414
|
+
if (isMain) text = injectPreviewBridge(text);
|
|
415
|
+
const scene = (document.manifest?.scenes ?? []).find((item) => item.file === relative);
|
|
416
|
+
if (scene) {
|
|
417
|
+
const quizzes = quizzesForScene(scene);
|
|
418
|
+
if (Object.keys(quizzes).length > 0) text = await injectQuizRuntime(text, quizzes);
|
|
419
|
+
}
|
|
420
|
+
content = Buffer.from(text, 'utf8');
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
response.writeHead(200, {
|
|
424
|
+
'content-type': contentType(relative),
|
|
425
|
+
'cache-control': 'no-store',
|
|
426
|
+
'x-content-type-options': 'nosniff',
|
|
427
|
+
'content-security-policy': COURSEWARE_CSP,
|
|
428
|
+
}).end(content);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// 预览用题目表:以交互 id 为键,包含作者视图里的答案,
|
|
432
|
+
// 让组件在预览里能立即判分;学生端由 Rust 服务端注入脱敏数据。
|
|
433
|
+
function quizzesForScene(scene) {
|
|
434
|
+
const map = {};
|
|
435
|
+
for (const record of document.interactions ?? []) {
|
|
436
|
+
const entry = record.entry ?? {};
|
|
437
|
+
const body = record.body;
|
|
438
|
+
if (!body || entry.scene !== scene.id) continue;
|
|
439
|
+
map[entry.id] = {
|
|
440
|
+
id: entry.id,
|
|
441
|
+
type: body.type,
|
|
442
|
+
stem: body.stem,
|
|
443
|
+
options: body.options,
|
|
444
|
+
explain: body.explain,
|
|
445
|
+
points: entry.points ?? 1,
|
|
446
|
+
graded: entry.graded !== false,
|
|
447
|
+
partialCredit: body.partialCredit === true,
|
|
448
|
+
policy: body.policy,
|
|
449
|
+
answer: deriveAnswer(body) ?? null,
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
return map;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function allowedLessonFiles(manifest, packageRoot) {
|
|
456
|
+
const allowed = new Set();
|
|
457
|
+
for (const scene of manifest.scenes ?? []) {
|
|
458
|
+
if (typeof scene.file === 'string') allowed.add(scene.file);
|
|
459
|
+
}
|
|
460
|
+
for (const asset of manifest.assets ?? []) {
|
|
461
|
+
if (typeof asset.path === 'string') allowed.add(asset.path);
|
|
462
|
+
}
|
|
463
|
+
// assets/ 下由场景引用但未逐一声明的文件(如 lume-courseware.js)也要可用;
|
|
464
|
+
// listPackageFiles 已排除符号链接与点文件。
|
|
465
|
+
for (const relative of listPackageFiles(packageRoot)) {
|
|
466
|
+
if (relative.startsWith('assets/')) allowed.add(relative);
|
|
467
|
+
}
|
|
468
|
+
return allowed;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async function serveUi(request, response, url) {
|
|
472
|
+
const relative = url.pathname === '/' || url.pathname === '/index.html'
|
|
473
|
+
? 'index.html'
|
|
474
|
+
: url.pathname === '/home'
|
|
475
|
+
? 'home.html'
|
|
476
|
+
: url.pathname.slice('/ui/'.length);
|
|
477
|
+
if (!/^[a-z0-9\-_/.]+$/i.test(relative) || relative.includes('..')) {
|
|
478
|
+
throw new StudioError(ERROR_CODES.BAD_REQUEST, 'UI 路径不合法', undefined, 400);
|
|
479
|
+
}
|
|
480
|
+
const uiRoot = path.join(PACKAGE_ROOT, 'ui');
|
|
481
|
+
const absolute = path.resolve(uiRoot, relative);
|
|
482
|
+
const relativeCheck = path.relative(uiRoot, absolute);
|
|
483
|
+
if (relativeCheck.startsWith('..') || path.isAbsolute(relativeCheck)) {
|
|
484
|
+
throw new StudioError(ERROR_CODES.BAD_REQUEST, 'UI 路径不合法', undefined, 400);
|
|
485
|
+
}
|
|
486
|
+
let content;
|
|
487
|
+
try {
|
|
488
|
+
content = await fsp.readFile(absolute);
|
|
489
|
+
} catch {
|
|
490
|
+
throw new StudioError(ERROR_CODES.BAD_REQUEST, '未找到界面资源', { path: relative }, 404);
|
|
491
|
+
}
|
|
492
|
+
const isHtml = relative.endsWith('.html');
|
|
493
|
+
response.writeHead(200, {
|
|
494
|
+
'content-type': contentType(relative),
|
|
495
|
+
'cache-control': 'no-store',
|
|
496
|
+
'x-content-type-options': 'nosniff',
|
|
497
|
+
...(isHtml ? {
|
|
498
|
+
'set-cookie': `studio_session=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Strict`,
|
|
499
|
+
'content-security-policy': uiCsp(),
|
|
500
|
+
} : {}),
|
|
501
|
+
}).end(content);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function publicSession(authenticated) {
|
|
505
|
+
return {
|
|
506
|
+
status: document.report.valid ? 'ready' : 'degraded',
|
|
507
|
+
protocolVersion: 1,
|
|
508
|
+
packageVersion: packageVersion(),
|
|
509
|
+
skillVersion: skillVersion(),
|
|
510
|
+
previewUrl: `http://${urlHost}:${listeningPort}/`,
|
|
511
|
+
previewKey: document.previewKey,
|
|
512
|
+
coursewareId: document.manifest?.id ?? null,
|
|
513
|
+
revision: document.revision,
|
|
514
|
+
valid: document.report.valid,
|
|
515
|
+
authenticated,
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function describe() {
|
|
520
|
+
return {
|
|
521
|
+
status: document.report.valid ? 'ready' : 'degraded',
|
|
522
|
+
protocolVersion: 1,
|
|
523
|
+
packageVersion: packageVersion(),
|
|
524
|
+
skillVersion: skillVersion(),
|
|
525
|
+
previewUrl: `http://${urlHost}:${listeningPort}/`,
|
|
526
|
+
healthUrl: `http://${urlHost}:${listeningPort}/healthz`,
|
|
527
|
+
wsUrl: `ws://${urlHost}:${listeningPort}/ws`,
|
|
528
|
+
toolApiUrl: `http://${urlHost}:${listeningPort}/api/invoke`,
|
|
529
|
+
coursewareRoot: root,
|
|
530
|
+
previewKey: document.previewKey,
|
|
531
|
+
coursewareId: document.manifest?.id ?? null,
|
|
532
|
+
revision: document.revision,
|
|
533
|
+
token,
|
|
534
|
+
pid: process.pid,
|
|
535
|
+
valid: document.report.valid,
|
|
536
|
+
errors: document.report.errors,
|
|
537
|
+
warnings: document.report.warnings,
|
|
538
|
+
startedAt,
|
|
539
|
+
previewClients: clients.size,
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
async function exportCoursewareTo(outDirectory, options = {}) {
|
|
544
|
+
return exportCourseware({
|
|
545
|
+
root,
|
|
546
|
+
out: outDirectory,
|
|
547
|
+
revision: options.revision ?? document.revision,
|
|
548
|
+
force: options.force === true,
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
async function packageCoursewareTo(outFile, options = {}) {
|
|
553
|
+
return packageCourseware({
|
|
554
|
+
root,
|
|
555
|
+
out: outFile,
|
|
556
|
+
revision: options.revision ?? document.revision,
|
|
557
|
+
force: options.force === true,
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
async function sendExport(response) {
|
|
562
|
+
const temporary = await fsp.mkdtemp(path.join(os.tmpdir(), 'lume-studio-package-'));
|
|
563
|
+
const id = String(document.manifest?.id ?? 'courseware').replace(/[^a-zA-Z0-9._-]/g, '-');
|
|
564
|
+
const file = path.join(temporary, `${id}.lume`);
|
|
565
|
+
try {
|
|
566
|
+
const meta = await packageCoursewareTo(file, { revision: document.revision, force: true });
|
|
567
|
+
const data = await fsp.readFile(file);
|
|
568
|
+
response.writeHead(200, {
|
|
569
|
+
'content-type': 'application/zip',
|
|
570
|
+
'content-length': data.length,
|
|
571
|
+
'content-disposition': `attachment; filename="${id}.lume"`,
|
|
572
|
+
'cache-control': 'no-store',
|
|
573
|
+
});
|
|
574
|
+
response.end(data);
|
|
575
|
+
return meta;
|
|
576
|
+
} finally {
|
|
577
|
+
await fsp.rm(temporary, { recursive: true, force: true }).catch(() => {});
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function close() {
|
|
582
|
+
for (const client of clients.values()) {
|
|
583
|
+
try {
|
|
584
|
+
client.close(true);
|
|
585
|
+
} catch {
|
|
586
|
+
// 忽略关闭错误。
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
clients.clear();
|
|
590
|
+
for (const waiter of waiters) {
|
|
591
|
+
clearTimeout(waiter.timer);
|
|
592
|
+
waiter.resolve({ acknowledged: false, reason: 'SERVER_CLOSED', clients: 0 });
|
|
593
|
+
}
|
|
594
|
+
waiters.clear();
|
|
595
|
+
return new Promise((resolve) => {
|
|
596
|
+
server.close(() => resolve());
|
|
597
|
+
setTimeout(() => {
|
|
598
|
+
server.closeAllConnections?.();
|
|
599
|
+
resolve();
|
|
600
|
+
}, 500).unref?.();
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function authorizeRequest(request) {
|
|
605
|
+
return tokenMatches(providedToken(request));
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function authorizeWsRequest(request) {
|
|
609
|
+
const origin = request.headers.origin;
|
|
610
|
+
const cookieToken = readCookie(request, 'studio_session');
|
|
611
|
+
if (cookieToken) {
|
|
612
|
+
if (!originAllowed(request)) return false;
|
|
613
|
+
return tokenMatches(cookieToken);
|
|
614
|
+
}
|
|
615
|
+
return tokenMatches(providedToken(request));
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
function providedToken(request) {
|
|
619
|
+
const header = request.headers['x-studio-token'];
|
|
620
|
+
if (typeof header === 'string') return header;
|
|
621
|
+
return readCookie(request, 'studio_session');
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function tokenMatches(provided) {
|
|
625
|
+
if (!provided || typeof provided !== 'string') return false;
|
|
626
|
+
const expected = Buffer.from(token);
|
|
627
|
+
const actual = Buffer.from(provided);
|
|
628
|
+
if (expected.length !== actual.length) return false;
|
|
629
|
+
return timingSafeEqual(expected, actual);
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
function originAllowed(request) {
|
|
633
|
+
const origin = request.headers.origin;
|
|
634
|
+
if (typeof origin !== 'string' || origin === '') return false;
|
|
635
|
+
try {
|
|
636
|
+
const parsed = new URL(origin);
|
|
637
|
+
// 同源比较:浏览器 Origin 必须与 Host 一致;兼容本地回环别名。
|
|
638
|
+
if (request.headers.host && parsed.host === request.headers.host) return true;
|
|
639
|
+
const allowedHosts = new Set(['127.0.0.1', 'localhost', '[::1]', urlHost]);
|
|
640
|
+
return allowedHosts.has(parsed.hostname) && Number(parsed.port || 80) === Number(listeningPort);
|
|
641
|
+
} catch {
|
|
642
|
+
return false;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
async function readBody(request) {
|
|
647
|
+
if (request.method !== 'POST') throw new StudioError(ERROR_CODES.BAD_REQUEST, '只接受 POST', undefined, 405);
|
|
648
|
+
const chunks = [];
|
|
649
|
+
let size = 0;
|
|
650
|
+
for await (const chunk of request) {
|
|
651
|
+
size += chunk.length;
|
|
652
|
+
if (size > maxBody) throw new StudioError(ERROR_CODES.PAYLOAD_TOO_LARGE, '请求体过大', { limit: maxBody }, 413);
|
|
653
|
+
chunks.push(chunk);
|
|
654
|
+
}
|
|
655
|
+
if (chunks.length === 0) return {};
|
|
656
|
+
try {
|
|
657
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
658
|
+
} catch {
|
|
659
|
+
throw new StudioError(ERROR_CODES.BAD_REQUEST, '请求体不是合法 JSON', undefined, 400);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
async function readBinaryBody(request, limit) {
|
|
664
|
+
if (request.method !== 'POST') throw new StudioError(ERROR_CODES.BAD_REQUEST, '只接受 POST', undefined, 405);
|
|
665
|
+
const chunks = [];
|
|
666
|
+
let size = 0;
|
|
667
|
+
for await (const chunk of request) {
|
|
668
|
+
size += chunk.length;
|
|
669
|
+
if (size > limit) throw new StudioError(ERROR_CODES.PAYLOAD_TOO_LARGE, '导入文件过大', { limit }, 413);
|
|
670
|
+
chunks.push(chunk);
|
|
671
|
+
}
|
|
672
|
+
if (size === 0) throw new StudioError(ERROR_CODES.BAD_REQUEST, '导入文件为空', undefined, 400);
|
|
673
|
+
return Buffer.concat(chunks);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
await listen(server, host, preferredPort, options.strictPort);
|
|
677
|
+
listeningPort = server.address().port;
|
|
678
|
+
|
|
679
|
+
return {
|
|
680
|
+
port: listeningPort,
|
|
681
|
+
host,
|
|
682
|
+
token,
|
|
683
|
+
broadcast,
|
|
684
|
+
waitForAck,
|
|
685
|
+
describe,
|
|
686
|
+
publicSession: () => publicSession(true),
|
|
687
|
+
exportCourseware: exportCoursewareTo,
|
|
688
|
+
packageCourseware: packageCoursewareTo,
|
|
689
|
+
close,
|
|
690
|
+
get previewClients() {
|
|
691
|
+
return clients.size;
|
|
692
|
+
},
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
function readCookie(request, name) {
|
|
697
|
+
const raw = request.headers.cookie;
|
|
698
|
+
if (typeof raw !== 'string') return null;
|
|
699
|
+
for (const part of raw.split(';')) {
|
|
700
|
+
const [key, ...rest] = part.trim().split('=');
|
|
701
|
+
if (key === name) return decodeURIComponent(rest.join('='));
|
|
702
|
+
}
|
|
703
|
+
return null;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function sendJson(response, status, value) {
|
|
707
|
+
const body = JSON.stringify(value);
|
|
708
|
+
response.writeHead(status, {
|
|
709
|
+
'content-type': 'application/json; charset=utf-8',
|
|
710
|
+
'cache-control': 'no-store',
|
|
711
|
+
'x-content-type-options': 'nosniff',
|
|
712
|
+
}).end(body);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
const LIBRARY_SKIP = new Set(['node_modules', '.git', '.studio', 'dist', 'target', 'build', 'coverage']);
|
|
716
|
+
|
|
717
|
+
// 仅收录由 Studio 创建或打开过的课件(存在 .studio 目录),未初始化的普通目录不会误入。
|
|
718
|
+
async function discoverCoursewareRoots(currentRoot) {
|
|
719
|
+
const roots = new Set([currentRoot]);
|
|
720
|
+
const parent = path.dirname(currentRoot);
|
|
721
|
+
if (parent === currentRoot) return [...roots];
|
|
722
|
+
const siblings = await fsp.readdir(parent, { withFileTypes: true }).catch(() => []);
|
|
723
|
+
let budget = 80;
|
|
724
|
+
for (const entry of siblings) {
|
|
725
|
+
if (budget <= 0) break;
|
|
726
|
+
if (!entry.isDirectory() || LIBRARY_SKIP.has(entry.name) || entry.name.startsWith('.')) continue;
|
|
727
|
+
const dir = path.join(parent, entry.name);
|
|
728
|
+
if (dir === currentRoot) continue;
|
|
729
|
+
budget -= 1;
|
|
730
|
+
if (await isEditedCourseware(dir)) roots.add(dir);
|
|
731
|
+
const children = await fsp.readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
732
|
+
for (const child of children) {
|
|
733
|
+
if (budget <= 0) break;
|
|
734
|
+
if (!child.isDirectory() || LIBRARY_SKIP.has(child.name) || child.name.startsWith('.')) continue;
|
|
735
|
+
budget -= 1;
|
|
736
|
+
const nested = path.join(dir, child.name);
|
|
737
|
+
if (await isEditedCourseware(nested)) roots.add(nested);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
return [...roots];
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
async function isEditedCourseware(dir) {
|
|
744
|
+
try {
|
|
745
|
+
const stat = await fsp.stat(dir);
|
|
746
|
+
if (!stat.isDirectory()) return false;
|
|
747
|
+
await Promise.all([
|
|
748
|
+
fsp.access(path.join(dir, 'manifest.json')),
|
|
749
|
+
fsp.access(path.join(dir, '.studio')),
|
|
750
|
+
]);
|
|
751
|
+
return true;
|
|
752
|
+
} catch {
|
|
753
|
+
return false;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
function pidAlive(pid) {
|
|
758
|
+
try {
|
|
759
|
+
process.kill(pid, 0);
|
|
760
|
+
return true;
|
|
761
|
+
} catch (error) {
|
|
762
|
+
return error.code === 'EPERM';
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function uiCsp() {
|
|
767
|
+
return "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; " +
|
|
768
|
+
"img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ws://127.0.0.1:* ws://localhost:*; " +
|
|
769
|
+
"frame-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'";
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// 预览场景里的元素选择桥:父窗口发送 pick-mode,用户点击后回传选择器与元素片段。
|
|
773
|
+
// iframe 保持 allow-scripts 的最小沙箱,因此只能通过 postMessage 通信。
|
|
774
|
+
const PREVIEW_BRIDGE_SCRIPT = [
|
|
775
|
+
'(function () {',
|
|
776
|
+
' if (window.__lumePreviewBridge) return;',
|
|
777
|
+
' window.__lumePreviewBridge = true;',
|
|
778
|
+
' var enabled = false;',
|
|
779
|
+
' var hovered = null;',
|
|
780
|
+
' var sceneId = null;',
|
|
781
|
+
" var style = document.createElement('style');",
|
|
782
|
+
" style.textContent = '.lume-pick-on,.lume-pick-on *{cursor:crosshair !important}' +",
|
|
783
|
+
" '.lume-pick-hover{outline:2px solid #3b5bfd !important;outline-offset:2px !important;' +",
|
|
784
|
+
" 'box-shadow:inset 0 0 0 9999px rgba(59,91,253,.08) !important}';",
|
|
785
|
+
' document.documentElement.appendChild(style);',
|
|
786
|
+
' function selectorOf(node) {',
|
|
787
|
+
' var parts = [];',
|
|
788
|
+
' var depth = 0;',
|
|
789
|
+
' while (node && node.nodeType === 1 && depth < 4) {',
|
|
790
|
+
' var part = node.tagName.toLowerCase();',
|
|
791
|
+
' if (node.id) { parts.unshift(part + "#" + node.id); break; }',
|
|
792
|
+
" var classes = typeof node.className === 'string' ? node.className.trim().split(/\\s+/).filter(Boolean).slice(0, 2) : [];",
|
|
793
|
+
" if (classes.length > 0) part += '.' + classes.join('.');",
|
|
794
|
+
' var parent = node.parentElement;',
|
|
795
|
+
' if (parent) {',
|
|
796
|
+
' var same = Array.prototype.filter.call(parent.children, function (child) { return child.tagName === node.tagName; });',
|
|
797
|
+
" if (same.length > 1) part += ':nth-of-type(' + (same.indexOf(node) + 1) + ')';",
|
|
798
|
+
' }',
|
|
799
|
+
' parts.unshift(part);',
|
|
800
|
+
' node = parent;',
|
|
801
|
+
' depth += 1;',
|
|
802
|
+
' }',
|
|
803
|
+
" return parts.join(' > ');",
|
|
804
|
+
' }',
|
|
805
|
+
' function clearHover() {',
|
|
806
|
+
' if (!hovered) return;',
|
|
807
|
+
" hovered.classList.remove('lume-pick-hover');",
|
|
808
|
+
' hovered = null;',
|
|
809
|
+
' }',
|
|
810
|
+
' function disable() {',
|
|
811
|
+
' enabled = false;',
|
|
812
|
+
" document.documentElement.classList.remove('lume-pick-on');",
|
|
813
|
+
' clearHover();',
|
|
814
|
+
' }',
|
|
815
|
+
' function pick(target) {',
|
|
816
|
+
' if (!target || target === document.documentElement || target === document.body) return;',
|
|
817
|
+
' var rect = target.getBoundingClientRect();',
|
|
818
|
+
' var text = (target.textContent || "").replace(/\\s+/g, " ").trim().slice(0, 200);',
|
|
819
|
+
' var selection = {',
|
|
820
|
+
' sceneId: sceneId,',
|
|
821
|
+
' selector: selectorOf(target),',
|
|
822
|
+
' tag: target.tagName.toLowerCase(),',
|
|
823
|
+
' id: target.id || null,',
|
|
824
|
+
" classes: typeof target.className === 'string' ? target.className.slice(0, 200) : '',",
|
|
825
|
+
' text: text,',
|
|
826
|
+
' outerHTML: (target.outerHTML || "").slice(0, 1200),',
|
|
827
|
+
' rect: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) }',
|
|
828
|
+
' };',
|
|
829
|
+
" parent.postMessage({ source: 'lume-picker', type: 'picked', selection: selection }, '*');",
|
|
830
|
+
' disable();',
|
|
831
|
+
' }',
|
|
832
|
+
" document.addEventListener('mousemove', function (event) {",
|
|
833
|
+
' if (!enabled) return;',
|
|
834
|
+
' var target = event.target;',
|
|
835
|
+
' if (!target || target === hovered) return;',
|
|
836
|
+
' clearHover();',
|
|
837
|
+
' if (target === document.body || target === document.documentElement) return;',
|
|
838
|
+
' hovered = target;',
|
|
839
|
+
" target.classList.add('lume-pick-hover');",
|
|
840
|
+
' }, true);',
|
|
841
|
+
" document.addEventListener('click', function (event) {",
|
|
842
|
+
' if (!enabled) return;',
|
|
843
|
+
' event.preventDefault();',
|
|
844
|
+
' event.stopPropagation();',
|
|
845
|
+
' pick(event.target);',
|
|
846
|
+
' }, true);',
|
|
847
|
+
" document.addEventListener('keydown', function (event) {",
|
|
848
|
+
' if (!enabled || event.key !== "Escape") return;',
|
|
849
|
+
' event.preventDefault();',
|
|
850
|
+
' disable();',
|
|
851
|
+
" parent.postMessage({ source: 'lume-picker', type: 'cancelled' }, '*');",
|
|
852
|
+
' }, true);',
|
|
853
|
+
" window.addEventListener('message', function (event) {",
|
|
854
|
+
' var data = event.data;',
|
|
855
|
+
" if (!data || data.source !== 'lume-host') return;",
|
|
856
|
+
" if (data.type === 'sync' && data.sceneId) sceneId = data.sceneId;",
|
|
857
|
+
" if (data.type !== 'pick-mode') return;",
|
|
858
|
+
' if (data.enabled) {',
|
|
859
|
+
' enabled = true;',
|
|
860
|
+
" document.documentElement.classList.add('lume-pick-on');",
|
|
861
|
+
' } else {',
|
|
862
|
+
' disable();',
|
|
863
|
+
' }',
|
|
864
|
+
' });',
|
|
865
|
+
'})();',
|
|
866
|
+
].join('\n');
|
|
867
|
+
|
|
868
|
+
function injectPreviewBridge(html) {
|
|
869
|
+
if (typeof html !== 'string' || html.includes('__lumePreviewBridge')) return html;
|
|
870
|
+
const tag = `<script>${PREVIEW_BRIDGE_SCRIPT}</` + 'script>';
|
|
871
|
+
if (/<\/body\s*>(?![\s\S]*<\/body\s*>)/i.test(html)) {
|
|
872
|
+
return html.replace(/<\/body\s*>(?![\s\S]*<\/body\s*>)/i, `${tag}</body>`);
|
|
873
|
+
}
|
|
874
|
+
return `${html}\n${tag}`;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
// 通用题目组件的渲染代码只有一份(ui/shared/quiz-view.js),
|
|
878
|
+
// 预览时直接注入,保证不同课件的旧运行时也能渲染 <lume-quiz>。
|
|
879
|
+
let quizViewSource = null;
|
|
880
|
+
async function loadQuizViewSource() {
|
|
881
|
+
if (quizViewSource === null) {
|
|
882
|
+
quizViewSource = await fsp.readFile(new URL('../../ui/shared/quiz-view.js', import.meta.url), 'utf8');
|
|
883
|
+
}
|
|
884
|
+
return quizViewSource;
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
function injectAfterBodyOpen(html, tag) {
|
|
888
|
+
const match = /<body[^>]*>/i.exec(html);
|
|
889
|
+
if (!match) return `${tag}\n${html}`;
|
|
890
|
+
const index = match.index + match[0].length;
|
|
891
|
+
return `${html.slice(0, index)}${tag}${html.slice(index)}`;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// 预览里注入当前场景的题目数据。Studio 预览是本地沙盒 iframe,
|
|
895
|
+
// 带着作者视图(含答案)便于即时试答;学生端走脱敏的 student view。
|
|
896
|
+
async function injectQuizRuntime(html, quizzes) {
|
|
897
|
+
const source = await loadQuizViewSource();
|
|
898
|
+
const payload = JSON.stringify(quizzes).replace(/</g, '\\u003c');
|
|
899
|
+
const tag = `<script>window.__lumeQuizzes = ${payload};</script>\n`
|
|
900
|
+
+ `<script>${source.replace(/<\/script/gi, '<\\/script')}</script>`;
|
|
901
|
+
return injectAfterBodyOpen(html, tag);
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
function listen(server, host, port, strictPort) {
|
|
905
|
+
return new Promise((resolve, reject) => {
|
|
906
|
+
const attempt = (candidate, remaining) => {
|
|
907
|
+
const onError = (error) => {
|
|
908
|
+
server.off('error', onError);
|
|
909
|
+
if (error.code === 'EADDRINUSE' && !strictPort && remaining > 0) {
|
|
910
|
+
attempt(candidate + 1, remaining - 1);
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
reject(new StudioError(ERROR_CODES.PREVIEW_UNAVAILABLE, `无法监听 ${host}:${candidate}(${error.code})`, { host, port: candidate }, 500));
|
|
914
|
+
};
|
|
915
|
+
server.once('error', onError);
|
|
916
|
+
server.listen(candidate, host, () => {
|
|
917
|
+
server.off('error', onError);
|
|
918
|
+
resolve();
|
|
919
|
+
});
|
|
920
|
+
};
|
|
921
|
+
attempt(port, 40);
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
function packageVersion() {
|
|
926
|
+
try {
|
|
927
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
|
|
928
|
+
return manifest.version ?? '0.0.0';
|
|
929
|
+
} catch {
|
|
930
|
+
return '0.0.0';
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
function skillVersion() {
|
|
935
|
+
try {
|
|
936
|
+
const text = fs.readFileSync(path.join(PACKAGE_ROOT, 'skills/courseware-authoring/SKILL.md'), 'utf8');
|
|
937
|
+
const match = /^---[\s\S]*?^version:\s*(.+)$/m.exec(text);
|
|
938
|
+
return match ? match[1].trim() : packageVersion();
|
|
939
|
+
} catch {
|
|
940
|
+
return packageVersion();
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
export { packageVersion, skillVersion };
|