@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.
@@ -0,0 +1,128 @@
1
+ // 最小 RFC 6455 服务端实现,避免为本地预览引入外部依赖。
2
+ // 只支持文本帧、ping/pong 与关闭帧;单帧与总消息大小都有上限。
3
+
4
+ import { createHash } from 'node:crypto';
5
+
6
+ const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
7
+
8
+ export class WsConnection {
9
+ constructor(socket, { maxFrameBytes = 65536, onMessage, onClose }) {
10
+ this.socket = socket;
11
+ this.maxFrameBytes = maxFrameBytes;
12
+ this.onMessage = onMessage;
13
+ this.onClose = onClose;
14
+ this.buffer = Buffer.alloc(0);
15
+ this.closed = false;
16
+ socket.on('data', (chunk) => this.receive(chunk));
17
+ socket.on('close', () => this.close(false));
18
+ socket.on('error', () => this.close(false));
19
+ }
20
+
21
+ receive(chunk) {
22
+ this.buffer = Buffer.concat([this.buffer, chunk]);
23
+ while (this.buffer.length >= 2) {
24
+ const first = this.buffer[0];
25
+ const second = this.buffer[1];
26
+ const fin = (first & 0x80) !== 0;
27
+ const opcode = first & 0x0f;
28
+ const masked = (second & 0x80) !== 0;
29
+ let length = second & 0x7f;
30
+ let offset = 2;
31
+ if (length === 126) {
32
+ if (this.buffer.length < 4) return;
33
+ length = this.buffer.readUInt16BE(2);
34
+ offset = 4;
35
+ } else if (length === 127) {
36
+ // 超大帧直接关闭,本地预览不需要。
37
+ this.close(true);
38
+ return;
39
+ }
40
+ if (length > this.maxFrameBytes) {
41
+ this.close(true);
42
+ return;
43
+ }
44
+ const maskBytes = masked ? 4 : 0;
45
+ if (this.buffer.length < offset + maskBytes + length) return;
46
+ let payload;
47
+ if (masked) {
48
+ const mask = this.buffer.subarray(offset, offset + 4);
49
+ payload = Buffer.from(this.buffer.subarray(offset + 4, offset + 4 + length));
50
+ for (let index = 0; index < payload.length; index += 1) payload[index] ^= mask[index % 4];
51
+ } else {
52
+ payload = this.buffer.subarray(offset, offset + length);
53
+ }
54
+ this.buffer = this.buffer.subarray(offset + maskBytes + length);
55
+
56
+ if (opcode === 0x8) {
57
+ this.close(true);
58
+ return;
59
+ }
60
+ if (opcode === 0x9) {
61
+ this.sendFrame(payload, 0x0a);
62
+ continue;
63
+ }
64
+ if (opcode === 0x1) {
65
+ let text;
66
+ try {
67
+ text = payload.toString('utf8');
68
+ } catch {
69
+ continue;
70
+ }
71
+ if (!fin) {
72
+ // 分片消息在本服务不需要支持。
73
+ continue;
74
+ }
75
+ this.onMessage?.(text);
76
+ }
77
+ }
78
+ }
79
+
80
+ sendFrame(payload, opcode = 0x1) {
81
+ if (this.closed || this.socket.destroyed) return;
82
+ const data = Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload), 'utf8');
83
+ const header = [];
84
+ header.push(0x80 | opcode);
85
+ if (data.length < 126) {
86
+ header.push(data.length);
87
+ } else if (data.length < 65536) {
88
+ header.push(126, data.length >> 8, data.length & 0xff);
89
+ } else {
90
+ this.close(true);
91
+ return;
92
+ }
93
+ this.socket.write(Buffer.concat([Buffer.from(header), data]));
94
+ }
95
+
96
+ sendJson(value) {
97
+ this.sendFrame(JSON.stringify(value));
98
+ }
99
+
100
+ close(handshake = true) {
101
+ if (this.closed) return;
102
+ this.closed = true;
103
+ try {
104
+ if (handshake) this.sendFrame(Buffer.alloc(0), 0x8);
105
+ this.socket.end();
106
+ } catch {
107
+ // 忽略关闭期间的写入错误。
108
+ }
109
+ this.onClose?.();
110
+ }
111
+ }
112
+
113
+ export function acceptUpgrade(request, socket, { maxFrameBytes = 65536, onMessage, onClose } = {}) {
114
+ const key = request.headers['sec-websocket-key'];
115
+ if (!key) {
116
+ socket.destroy();
117
+ return null;
118
+ }
119
+ const accept = createHash('sha1').update(`${key}${GUID}`).digest('base64');
120
+ socket.write(
121
+ 'HTTP/1.1 101 Switching Protocols\r\n' +
122
+ 'Upgrade: websocket\r\n' +
123
+ 'Connection: Upgrade\r\n' +
124
+ `Sec-WebSocket-Accept: ${accept}\r\n\r\n`,
125
+ );
126
+ socket.setNoDelay(true);
127
+ return new WsConnection(socket, { maxFrameBytes, onMessage, onClose });
128
+ }
@@ -0,0 +1,48 @@
1
+ // 课件模板:初始化与场景骨架。模板只使用自带资源,不依赖外网。
2
+
3
+ export function coursewareTemplate({ id, title, subject = '信息科技', grade = '七年级', durationMin = 45, objectives = [], aspectRatio = '16:9' }) {
4
+ return {
5
+ specVersion: '1.1',
6
+ id,
7
+ version: '1.0.0',
8
+ title,
9
+ subject,
10
+ grade,
11
+ durationMin,
12
+ locale: 'zh-CN',
13
+ runtime: '>=1.1 <2.0',
14
+ aspectRatio,
15
+ authors: ['LumeSync Studio'],
16
+ source: { kind: 'agent-generated', ref: 'studio-template' },
17
+ objectives: objectives.length > 0
18
+ ? objectives
19
+ : [{ id: 'o1', text: '能说明本课的核心概念并完成一次课堂练习', bloom: 'understand' }],
20
+ scenes: [],
21
+ interactions: [],
22
+ compliance: { studentDataCollected: ['answer', 'component_state'], requiresNetwork: false },
23
+ };
24
+ }
25
+
26
+ export const SCENE_CONTENT_REQUIREMENTS = {
27
+ engage: { heading: '问题导入', bullets: ['先观察现象', '提出一个可验证的问题'] },
28
+ explain: { heading: '概念讲解', bullets: ['给出定义与关键特征', '用一个例子说明'] },
29
+ demo: { heading: '演示', bullets: ['按步骤演示一次', '指出容易出错的位置'] },
30
+ practice: { heading: '课堂练习', bullets: ['独立完成一次操作', '和同伴对比结果'] },
31
+ assess: { heading: '当堂检测', bullets: ['完成一道客观题', '查看解析'] },
32
+ summary: { heading: '课堂小结', bullets: ['回顾今天的目标', '布置课后延伸'] },
33
+ };
34
+
35
+ export function defaultContent(phase, title) {
36
+ const base = SCENE_CONTENT_REQUIREMENTS[phase] ?? SCENE_CONTENT_REQUIREMENTS.explain;
37
+ return { heading: title ?? base.heading, body: '', bullets: base.bullets };
38
+ }
39
+
40
+ export function phaseDefaults(index, total) {
41
+ const ratio = total <= 1 ? 0.5 : index / (total - 1);
42
+ if (ratio < 0.2) return 'engage';
43
+ if (ratio < 0.45) return 'explain';
44
+ if (ratio < 0.6) return 'demo';
45
+ if (ratio < 0.8) return 'practice';
46
+ if (ratio < 0.95) return 'assess';
47
+ return 'summary';
48
+ }
@@ -0,0 +1,374 @@
1
+ // 初始化:从模板生成一个可校验、可预览的最小课件。
2
+ // 场景 1 为导入,场景 2 为带单选题的练习,场景 3 为小结。
3
+
4
+ import fs from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { StudioError, ERROR_CODES } from '../core/errors.js';
8
+ import { createSalt, answerHash, resolveInside, writeJsonAtomic, writeFileAtomic } from '../core/storage.js';
9
+ import { normalizeAnswer, ASPECT_RATIOS, DEFAULT_ASPECT_RATIO, isGrade, isPackageId, charLen } from '../core/rules.js';
10
+ import { SUBJECT_VALUES } from '../core/model.js';
11
+ import { coursewareTemplate } from './courseware.js';
12
+ import { renderSceneTemplate, escapeHtml } from '../editing/operations.js';
13
+
14
+ let quizViewSourcePromise = null;
15
+ // 通用题目组件与 Studio 编辑器共用同一份源码(ui/shared/quiz-view.js)。
16
+ function loadQuizViewSource() {
17
+ if (!quizViewSourcePromise) {
18
+ quizViewSourcePromise = fs.readFile(new URL('../../ui/shared/quiz-view.js', import.meta.url), 'utf8');
19
+ }
20
+ return quizViewSourcePromise;
21
+ }
22
+
23
+ export async function initializeCourseware(root, options = {}) {
24
+ const title = options.title ?? '新建互动课件';
25
+ if (charLen(title) < 2 || charLen(title) > 60) {
26
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '标题长度必须是 2-60 个字符', { title }, 400);
27
+ }
28
+ const id = options.id ?? defaultId(title);
29
+ if (!isPackageId(id)) {
30
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '课件 id 必须是 6-96 位小写字母/数字的点分层级', { id }, 400);
31
+ }
32
+ const aspectRatio = normalizeAspectRatio(options.aspectRatio);
33
+ const requestedDuration = options.durationMin;
34
+ const durationMin = requestedDuration ?? 45;
35
+ if (!Number.isInteger(durationMin) || durationMin < 10 || durationMin > 90) {
36
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '课时长度必须是 10-90 分钟', { durationMin }, 400);
37
+ }
38
+ const subject = options.subject ?? '信息科技';
39
+ if (!SUBJECT_VALUES.includes(subject)) {
40
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, `学科必须是 ${SUBJECT_VALUES.join(' / ')}`, { subject }, 400);
41
+ }
42
+ const grade = options.grade ?? '七年级';
43
+ if (!isGrade(grade)) {
44
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '年级格式不合法,示例:七年级 / 小学四年级 / 高二', { grade }, 400);
45
+ }
46
+ const template = coursewareTemplate({
47
+ id,
48
+ title,
49
+ subject,
50
+ grade,
51
+ durationMin,
52
+ aspectRatio,
53
+ });
54
+
55
+ const scenes = [];
56
+ const files = [];
57
+
58
+ const intro = {
59
+ id: 's1', file: 'scenes/01-engage.html', title: '导入:从一个问题开始',
60
+ phase: 'engage', minutes: 8,
61
+ components: [{ cid: 'intro1', type: 'lume-sim', collect: 'onDemand', role: 'primary' }],
62
+ notes: '先让学生描述现象,再引出本课概念。',
63
+ };
64
+ scenes.push(intro);
65
+ files.push([intro.file, renderSceneTemplate(intro, {
66
+ heading: '你遇到过这种情况吗?',
67
+ body: '观察下面的现象,想一想它为什么会重复发生。',
68
+ bullets: ['先自己写下猜测', '再和同伴比较一次'],
69
+ })]);
70
+
71
+ const practice = {
72
+ id: 's2', file: 'scenes/02-practice.html', title: '练习:判断关键特征',
73
+ phase: 'practice', minutes: 15,
74
+ components: [{ cid: 'quiz1', type: 'lume-quiz', collect: 'onSubmit', role: 'primary' }],
75
+ notes: '提示:注意题干中的限定词。',
76
+ };
77
+ scenes.push(practice);
78
+ files.push([practice.file, renderQuizScene({
79
+ heading: '练习:识别核心特征',
80
+ ref: 'quiz1',
81
+ })]);
82
+
83
+ const summary = {
84
+ id: 's3', file: 'scenes/03-summary.html', title: '小结:把方法带走',
85
+ phase: 'summary', minutes: 7,
86
+ components: [{ cid: 'reflect1', type: 'lume-vars', collect: 'onDemand', role: 'support' }],
87
+ notes: '用一句话复述本课方法。',
88
+ };
89
+ scenes.push(summary);
90
+ files.push([summary.file, renderSceneTemplate(summary, {
91
+ heading: '今天带走的三个要点',
92
+ bullets: ['识别条件', '说明执行过程', '用例子验证结论'],
93
+ })]);
94
+
95
+ template.scenes = scenes;
96
+ const baseTotal = scenes.reduce((sum, scene) => sum + scene.minutes, 0);
97
+ if (requestedDuration !== undefined && requestedDuration !== baseTotal) {
98
+ // 显式传入 --duration 时按目标课时等比缩放模板场景。
99
+ const ratio = requestedDuration / baseTotal;
100
+ for (const scene of scenes) {
101
+ scene.minutes = Math.min(30, Math.max(0.5, Math.round(scene.minutes * ratio * 2) / 2));
102
+ }
103
+ }
104
+ template.durationMin = scenes.reduce((sum, scene) => sum + scene.minutes, 0);
105
+
106
+ const interaction = {
107
+ id: 'quiz1',
108
+ type: 'single-choice',
109
+ stem: '哪一项符合本课的核心特征?',
110
+ options: [
111
+ { key: 'A', text: '只在特定条件下重复执行' },
112
+ { key: 'B', text: '每次都执行固定的次数' },
113
+ { key: 'C', text: '与条件无关地顺序执行' },
114
+ ],
115
+ explain: '条件成立时才重复执行,是该结构的核心特征。',
116
+ policy: { maxAttempts: 2, lockAfterSubmit: false, showAnswerAfterSubmit: true, showResultAfterSubmit: true, shuffleOptions: false, timeLimitSec: 0 },
117
+ grading: { enabled: false, rubric: [], feedbackLanguage: 'zh-CN' },
118
+ };
119
+ const salt = createSalt();
120
+ // 明文答案只用于生成材料,落盘前必须移除:Rust 侧 deny_unknown_fields 会拒绝 `answer`。
121
+ const answer = { choice: 'A' };
122
+ interaction.answerHash = answerHash(salt, normalizeAnswer('single-choice', answer));
123
+ interaction.answerSalt = salt;
124
+
125
+ template.interactions = [{ id: interaction.id, file: `interactions/${interaction.id}.json`, scene: 's2', points: 2, graded: true }];
126
+
127
+ await fs.mkdir(path.join(root, 'scenes'), { recursive: true });
128
+ await fs.mkdir(path.join(root, 'interactions'), { recursive: true });
129
+ await fs.mkdir(path.join(root, 'assets'), { recursive: true });
130
+ await writeJsonAtomic(resolveInside(root, 'manifest.json'), template);
131
+ for (const [file, content] of files) await writeFileAtomic(resolveInside(root, file), content);
132
+ await writeJsonAtomic(resolveInside(root, `interactions/${interaction.id}.json`), interaction);
133
+ // 通用题目组件的源码只有一份,随运行时 SDK 一起写进课件包,
134
+ // 让学生端与 Studio 预览渲染出完全相同的题目。
135
+ await writeFileAtomic(
136
+ resolveInside(root, 'assets/lume-courseware.js'),
137
+ `${COURSEWARE_SDK}\n\n${await loadQuizViewSource()}`,
138
+ );
139
+ await writeJsonAtomic(resolveInside(root, 'checksums.json'), await computeChecksumsFor(root));
140
+ await fs.mkdir(resolveInside(root, '.studio'), { recursive: true }).catch(() => {});
141
+
142
+ return { id: template.id, scenes: template.scenes.length, interactions: 1, root };
143
+ }
144
+
145
+ // 题目场景只声明“用哪个题目”,题干、选项与答案统一由交互数据驱动。
146
+ // <lume-quiz> 的数据由宿主注入(Studio 预览 / 学生端运行时),
147
+ // 组件代码随 assets/lume-courseware.js 一起发布。
148
+ export function renderQuizScene({ heading, ref = 'quiz1' }) {
149
+ return `<!doctype html>
150
+ <html lang="zh-CN">
151
+ <head>
152
+ <meta charset="utf-8">
153
+ <meta name="viewport" content="width=device-width,initial-scale=1">
154
+ <title>${escapeHtml(heading)}</title>
155
+ <style>
156
+ *{box-sizing:border-box}
157
+ body{margin:0;padding:6%;min-height:100vh;font-family:system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;background:#0f172a;color:#e2e8f0}
158
+ main{max-width:920px;margin:auto}
159
+ h1{font-size:clamp(24px,3.4vw,42px);margin:0 0 24px;line-height:1.25}
160
+ </style>
161
+ </head>
162
+ <body>
163
+ <main>
164
+ <h1>${escapeHtml(heading)}</h1>
165
+ <lume-quiz ref="${escapeHtml(ref)}"></lume-quiz>
166
+ </main>
167
+ <script src="../assets/lume-courseware.js"></script>
168
+ </body>
169
+ </html>
170
+ `;
171
+ }
172
+
173
+ export const COURSEWARE_SDK = `(() => {
174
+ const stores = new Map();
175
+ let host = { role: 'preview', playbackMode: 'free', sceneId: '', revision: null };
176
+ let hostRevision = null;
177
+ let ackTimer = null;
178
+ const clone = (value) => JSON.parse(JSON.stringify(value));
179
+ const post = (message) => parent.postMessage({ source: 'lume-courseware', ...message }, '*');
180
+ // 无 DOM 的宿主(例如 Node 单测)里也能安全加载:只保留状态同步能力。
181
+ const hasDom = typeof document !== 'undefined' && !!document.documentElement;
182
+ const defer = (fn, ms) => {
183
+ if (typeof setTimeout === 'function') return setTimeout(fn, ms);
184
+ if (typeof queueMicrotask === 'function') { queueMicrotask(fn); return -1; }
185
+ fn();
186
+ return -1;
187
+ };
188
+ const cancelDefer = (id) => { if (id >= 0 && typeof clearTimeout === 'function') clearTimeout(id); };
189
+ function scheduleRenderAck() {
190
+ if (ackTimer !== null) cancelDefer(ackTimer);
191
+ ackTimer = defer(() => {
192
+ ackTimer = null;
193
+ post({ type: 'render-ack', sceneId: host.sceneId ?? null, revision: hostRevision });
194
+ }, 60);
195
+ }
196
+ function createStore(cid, initialState, render) {
197
+ if (!/^[a-zA-Z0-9._-]{1,64}$/.test(cid)) throw new Error('Invalid store cid');
198
+ const listeners = new Set();
199
+ let raw = clone(initialState);
200
+ let seq = 0;
201
+ if (typeof render === 'function') listeners.add(render);
202
+ const notify = () => { for (const listener of listeners) listener(clone(raw)); };
203
+ const api = {
204
+ get: () => clone(raw),
205
+ seq: () => seq,
206
+ set(next) { raw = clone(typeof next === 'function' ? next(clone(raw)) : next); seq += 1; notify(); },
207
+ patch(partial) { api.set((current) => ({ ...current, ...partial })); },
208
+ subscribe(listener) { listeners.add(listener); listener(clone(raw)); return () => listeners.delete(listener); },
209
+ apply(snapshot) {
210
+ if (snapshot && Number.isFinite(snapshot.seq) && snapshot.seq >= seq) {
211
+ seq = snapshot.seq;
212
+ raw = clone(snapshot.state);
213
+ notify();
214
+ }
215
+ },
216
+ };
217
+ stores.set(cid, api);
218
+ notify();
219
+ return api;
220
+ }
221
+ function postAllStates() {
222
+ for (const [cid, store] of stores) post({ type: 'state', cid, state: store.get(), seq: store.seq() });
223
+ }
224
+
225
+ // 场景自适配:把可见内容整体等比缩放到画布可用区域,课件不需要额外代码。
226
+ // 只做缩放与居中,不改变场景内部布局;<html data-lume-fit="off"> 可关闭。
227
+ let fitTimer = null;
228
+ let fitScale = 1;
229
+ function contentBox() {
230
+ if (!hasDom) return null;
231
+ const body = document.body;
232
+ if (!body) return null;
233
+ let left = Infinity, top = Infinity, right = -Infinity, bottom = -Infinity;
234
+ for (const node of body.children) {
235
+ const tag = node.tagName;
236
+ if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'LINK' || tag === 'TEMPLATE') continue;
237
+ const rect = node.getBoundingClientRect();
238
+ if (rect.width <= 1 || rect.height <= 1) continue;
239
+ left = Math.min(left, rect.left);
240
+ top = Math.min(top, rect.top);
241
+ right = Math.max(right, rect.right);
242
+ bottom = Math.max(bottom, rect.bottom);
243
+ }
244
+ return Number.isFinite(left) ? { left, top, width: right - left, height: bottom - top } : null;
245
+ }
246
+ function applyFit() {
247
+ fitTimer = null;
248
+ if (!hasDom) return;
249
+ const html = document.documentElement;
250
+ const body = document.body;
251
+ if (!body || html.dataset.lumeFit === 'off' || body.dataset.lumeFit === 'off') return;
252
+ // 演示画布不允许自身滚动:内容由 fit 缩放,溢出时裁切而不是出现滚动条。
253
+ html.style.overflow = 'hidden';
254
+ body.style.overflow = 'hidden';
255
+ // 先还原,保证测量到的是未缩放的内容尺寸。
256
+ body.style.transform = 'none';
257
+ const box = contentBox();
258
+ if (!box) return;
259
+ const vw = html.clientWidth || 1280;
260
+ const vh = html.clientHeight || 720;
261
+ let scale = Math.min((vw * 0.96) / box.width, (vh * 0.96) / box.height);
262
+ scale = Math.max(0.35, Math.min(1.8, scale));
263
+ if (Math.abs(scale - 1) < 0.04) scale = 1;
264
+ const dx = (vw - box.width * scale) / 2 - box.left * scale;
265
+ const dy = (vh - box.height * scale) / 2 - box.top * scale;
266
+ fitScale = scale;
267
+ body.style.transformOrigin = '0 0';
268
+ body.style.transform = 'translate(' + dx.toFixed(2) + 'px, ' + dy.toFixed(2) + 'px) scale(' + scale.toFixed(4) + ')';
269
+ const background = getComputedStyle(body).backgroundColor;
270
+ if (background && background !== 'rgba(0, 0, 0, 0)') html.style.backgroundColor = background;
271
+ }
272
+ function scheduleFit(delay = 80) {
273
+ if (fitTimer !== null) cancelDefer(fitTimer);
274
+ fitTimer = defer(applyFit, delay);
275
+ }
276
+ if (hasDom) {
277
+ let fitObserver = null;
278
+ if (typeof ResizeObserver === 'function') fitObserver = new ResizeObserver(() => scheduleFit(140));
279
+ const watchFitChildren = () => {
280
+ if (!fitObserver || !document.body) return;
281
+ fitObserver.disconnect();
282
+ for (const node of document.body.children) {
283
+ if (node.tagName !== 'SCRIPT' && node.tagName !== 'STYLE') fitObserver.observe(node);
284
+ }
285
+ };
286
+ if (typeof MutationObserver === 'function' && document.body) {
287
+ new MutationObserver(() => { watchFitChildren(); scheduleFit(160); })
288
+ .observe(document.body, { childList: true, subtree: true, characterData: true });
289
+ }
290
+ window.addEventListener('resize', () => scheduleFit(120));
291
+ if (document.fonts && document.fonts.ready) document.fonts.ready.then(() => scheduleFit(0)).catch(() => {});
292
+ if (document.readyState === 'loading') {
293
+ document.addEventListener('DOMContentLoaded', () => { watchFitChildren(); scheduleFit(0); });
294
+ } else {
295
+ watchFitChildren();
296
+ scheduleFit(0);
297
+ }
298
+ }
299
+ window.addEventListener('message', (event) => {
300
+ const data = event.data;
301
+ if (!data || data.source !== 'lume-host') return;
302
+ if (data.type === 'sync') {
303
+ host = { ...host, ...data };
304
+ hostRevision = Number.isInteger(data.revision) ? data.revision : hostRevision;
305
+ scheduleRenderAck();
306
+ scheduleFit(60);
307
+ return;
308
+ }
309
+ if (data.type === 'scene-state' && data.states) {
310
+ for (const [cid, snapshot] of Object.entries(data.states)) stores.get(cid)?.apply(snapshot);
311
+ scheduleRenderAck();
312
+ scheduleFit(60);
313
+ return;
314
+ }
315
+ if (data.type === 'state-request') { postAllStates(); return; }
316
+ });
317
+ window.LumeCourseware = {
318
+ createStore,
319
+ fit() { scheduleFit(0); },
320
+ share(cid, initialState, render) { return createStore(cid, initialState, render).get; },
321
+ event(action, cid, payload = {}) { post({ type: 'event', action, cid, payload }); },
322
+ navigate(target) { post({ type: 'navigate', ...target }); },
323
+ };
324
+ post({ type: 'ready', sceneId: null, revision: null });
325
+ })();
326
+ `;
327
+
328
+ export async function computeChecksumsFor(root) {
329
+ const { computeChecksums } = await import('../core/storage.js');
330
+ return computeChecksums(root);
331
+ }
332
+
333
+ // 比例白名单校验:非法值直接拒绝,避免写入后课件无法被运行时加载。
334
+ function normalizeAspectRatio(value) {
335
+ if (value === undefined || value === null || value === '') return DEFAULT_ASPECT_RATIO;
336
+ const text = String(value).trim();
337
+ if (!ASPECT_RATIOS.includes(text)) {
338
+ throw new StudioError(
339
+ ERROR_CODES.OPERATION_INVALID,
340
+ `不支持的比例 ${text},可用:${ASPECT_RATIOS.join(' / ')}`,
341
+ { available: ASPECT_RATIOS },
342
+ 400,
343
+ );
344
+ }
345
+ return text;
346
+ }
347
+
348
+ function defaultId(title) {
349
+ const ascii = String(title).toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 24) || 'courseware';
350
+ return `studio.${ascii}.${randomUUID().slice(0, 6)}`;
351
+ }
352
+
353
+ export async function ensureEmptyOrCourseware(root) {
354
+ let entries;
355
+ try {
356
+ entries = await fs.readdir(root);
357
+ } catch {
358
+ return { empty: true, exists: false };
359
+ }
360
+ const meaningful = entries.filter((name) => !name.startsWith('.'));
361
+ if (meaningful.length === 0) return { empty: true, exists: true };
362
+ const manifestPath = path.join(root, 'manifest.json');
363
+ try {
364
+ await fs.stat(manifestPath);
365
+ return { empty: false, exists: true, courseware: true };
366
+ } catch {
367
+ throw new StudioError(
368
+ ERROR_CODES.COURSEWARE_INVALID,
369
+ `目录非空且没有 manifest.json,拒绝覆盖:${root}`,
370
+ { root },
371
+ 422,
372
+ );
373
+ }
374
+ }