@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,305 @@
1
+ // Manifest 与题目的规范化、严格校验和默认值。行为对齐 crates/lume-courseware。
2
+ // Studio 的 answer 明文只用于编辑输入;落盘前由解释器转换为 answerHash + answerSalt。
3
+ // Node 与 Rust 的字段白名单、整数边界和未知字段处理必须一致。
4
+
5
+ import { normalizeAnswer } from '../core/rules.js';
6
+
7
+ export const SUBJECT_VALUES = ['信息科技', '信息技术', '人工智能', '通用技术', '跨学科'];
8
+ export const PHASE_VALUES = ['engage', 'explain', 'demo', 'practice', 'assess', 'summary'];
9
+ export const LAYOUT_VALUES = ['full', 'split', 'compare', 'code-focus', 'media', 'canvas'];
10
+ export const RUN_MODE_VALUES = ['broadcast', 'explore', 'converge'];
11
+ export const BLOOM_VALUES = ['remember', 'understand', 'apply', 'analyze', 'evaluate', 'create'];
12
+ export const COMPONENT_VALUES = [
13
+ 'lume-code', 'lume-run', 'lume-blocks', 'lume-vars', 'lume-sheet', 'lume-doc',
14
+ 'lume-board', 'lume-chart', 'lume-graph', 'lume-3d', 'lume-sim', 'lume-quiz',
15
+ 'lume-hotspot', 'lume-terminal', 'lume-timer', 'lume-ai',
16
+ ];
17
+ export const COLLECT_VALUES = ['none', 'onDemand', 'onSubmit', 'periodic'];
18
+ export const INTERACTION_KIND_VALUES = ['single-choice', 'multi-choice', 'fill-blank', 'code', 'open'];
19
+ export const OBJECTIVE_KIND_VALUES = ['single-choice', 'multi-choice', 'fill-blank'];
20
+
21
+ export const POLICY_FIELDS = [
22
+ 'maxAttempts', 'lockAfterSubmit', 'showAnswerAfterSubmit', 'showResultAfterSubmit',
23
+ 'shuffleOptions', 'timeLimitSec', 'deadline',
24
+ ];
25
+ export const INTERACTION_FIELDS = [
26
+ 'id', 'type', 'kind', 'stem', 'options', 'answerHash', 'answerSalt', 'explain', 'policy',
27
+ 'answerKeys', 'partialCredit', 'grading', 'deadline', 'shuffleOptions', 'allowResubmit',
28
+ 'timeLimitSec', 'language', 'starter', 'tests', 'timeLimitMs', 'memoryLimitMb', 'answer',
29
+ ];
30
+ export const GRADING_FIELDS = ['enabled', 'rubric', 'referenceAnswer', 'feedbackLanguage'];
31
+ export const RUBRIC_FIELDS = ['id', 'points', 'criteria'];
32
+
33
+ export function isObjective(kind) {
34
+ return OBJECTIVE_KIND_VALUES.includes(kind);
35
+ }
36
+
37
+ export function defaultPolicy(policy = {}) {
38
+ return {
39
+ maxAttempts: policy.maxAttempts ?? 1,
40
+ lockAfterSubmit: policy.lockAfterSubmit ?? true,
41
+ showAnswerAfterSubmit: policy.showAnswerAfterSubmit ?? true,
42
+ showResultAfterSubmit: policy.showResultAfterSubmit ?? true,
43
+ shuffleOptions: policy.shuffleOptions ?? false,
44
+ timeLimitSec: policy.timeLimitSec ?? 0,
45
+ ...(policy.deadline === undefined ? {} : { deadline: policy.deadline }),
46
+ };
47
+ }
48
+
49
+ function isPlainObject(value) {
50
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
51
+ }
52
+
53
+ export function unknownFields(value, allowed, path = '') {
54
+ if (!isPlainObject(value)) return [];
55
+ return Object.keys(value)
56
+ .filter((key) => !allowed.includes(key))
57
+ .map((key) => `${path ? `${path}.` : ''}${key} 不是受支持字段`);
58
+ }
59
+
60
+ // 截止时间统一成毫秒时间戳;非法写法返回 null。
61
+ export function normalizeDeadline(value) {
62
+ if (typeof value === 'number') {
63
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) return null;
64
+ return value > 0 && value < 100_000_000_000 ? value * 1000 : value;
65
+ }
66
+ if (typeof value !== 'string' || value.trim() === '') return null;
67
+ const raw = value.trim();
68
+ if (/^\d+$/.test(raw)) {
69
+ const number = Number(raw);
70
+ if (!Number.isSafeInteger(number) || number < 0) return null;
71
+ return number > 0 && number < 100_000_000_000 ? number * 1000 : number;
72
+ }
73
+ const millis = Date.parse(raw);
74
+ return Number.isFinite(millis) && millis >= 0 ? millis : null;
75
+ }
76
+
77
+ // 严格校验提交策略:字段白名单、整数、有限数和边界。
78
+ export function policyIssues(policy, path = 'policy') {
79
+ if (policy === undefined) return [];
80
+ if (!isPlainObject(policy)) return [`${path} 必须是对象`];
81
+ const issues = unknownFields(policy, POLICY_FIELDS, path);
82
+ if (policy.maxAttempts !== undefined) {
83
+ if (!Number.isInteger(policy.maxAttempts) || policy.maxAttempts < 1 || policy.maxAttempts > 10) {
84
+ issues.push(`${path}.maxAttempts 必须是 1-10 的整数`);
85
+ }
86
+ }
87
+ if (policy.timeLimitSec !== undefined) {
88
+ if (!Number.isInteger(policy.timeLimitSec) || policy.timeLimitSec < 0 || policy.timeLimitSec > 7200) {
89
+ issues.push(`${path}.timeLimitSec 必须是 0-7200 的整数`);
90
+ }
91
+ }
92
+ for (const key of ['lockAfterSubmit', 'showAnswerAfterSubmit', 'showResultAfterSubmit', 'shuffleOptions']) {
93
+ if (policy[key] !== undefined && typeof policy[key] !== 'boolean') issues.push(`${path}.${key} 必须是布尔值`);
94
+ }
95
+ if (policy.deadline !== undefined && normalizeDeadline(policy.deadline) === null) {
96
+ issues.push(`${path}.deadline 必须是毫秒时间戳或 RFC 3339 字符串`);
97
+ }
98
+ return issues;
99
+ }
100
+
101
+ export function normalizePolicy(input = {}) {
102
+ const policy = defaultPolicy(input);
103
+ if (policy.deadline !== undefined) {
104
+ const normalized = normalizeDeadline(policy.deadline);
105
+ if (normalized !== null) policy.deadline = normalized;
106
+ }
107
+ return policy;
108
+ }
109
+
110
+ export function answerShapeIssues(kind, answer) {
111
+ if (answer === undefined) return [];
112
+ if (!isPlainObject(answer)) return ['answer 必须是对象'];
113
+ const allowed = kind === 'single-choice' ? ['choice']
114
+ : kind === 'multi-choice' ? ['choices']
115
+ : kind === 'fill-blank' ? ['blanks']
116
+ : kind === 'code' ? ['code']
117
+ : ['text'];
118
+ return unknownFields(answer, allowed, 'answer');
119
+ }
120
+
121
+ // 校验编辑态题目的输入结构:未知字段、策略边界、评分配置和选项字段。
122
+ export function interactionInputIssues(input) {
123
+ if (!isPlainObject(input)) return ['题目 value 必须是对象'];
124
+ const issues = unknownFields(input, INTERACTION_FIELDS, 'value');
125
+ const kind = input.type ?? input.kind;
126
+ if (kind !== undefined && !INTERACTION_KIND_VALUES.includes(kind)) issues.push(`未知题目类型 ${kind}`);
127
+ if (input.stem !== undefined && typeof input.stem !== 'string') issues.push('题干必须是字符串');
128
+ if (input.options !== undefined) {
129
+ if (!Array.isArray(input.options)) issues.push('options 必须是数组');
130
+ else {
131
+ for (const [index, option] of input.options.entries()) {
132
+ if (!isPlainObject(option)) {
133
+ issues.push(`options[${index}] 必须是对象`);
134
+ continue;
135
+ }
136
+ issues.push(...unknownFields(option, ['key', 'text'], `options[${index}]`));
137
+ if (typeof option.key !== 'string' || option.key.trim() === '') issues.push(`options[${index}].key 必须是非空字符串`);
138
+ if (typeof option.text !== 'string') issues.push(`options[${index}].text 必须是字符串`);
139
+ }
140
+ }
141
+ }
142
+ issues.push(...policyIssues(input.policy));
143
+ if (input.deadline !== undefined && normalizeDeadline(input.deadline) === null) {
144
+ issues.push('deadline 必须是毫秒时间戳或 RFC 3339 字符串');
145
+ }
146
+ for (const key of ['shuffleOptions', 'allowResubmit']) {
147
+ if (input[key] !== undefined && typeof input[key] !== 'boolean') issues.push(`${key} 必须是布尔值`);
148
+ }
149
+ if (input.timeLimitSec !== undefined && (!Number.isInteger(input.timeLimitSec) || input.timeLimitSec < 0 || input.timeLimitSec > 7200)) {
150
+ issues.push('timeLimitSec 必须是 0-7200 的整数');
151
+ }
152
+ if (input.timeLimitMs !== undefined && (!Number.isInteger(input.timeLimitMs) || input.timeLimitMs < 0 || input.timeLimitMs > 600000)) {
153
+ issues.push('timeLimitMs 必须是 0-600000 的整数');
154
+ }
155
+ if (input.memoryLimitMb !== undefined && (!Number.isInteger(input.memoryLimitMb) || input.memoryLimitMb < 0 || input.memoryLimitMb > 4096)) {
156
+ issues.push('memoryLimitMb 必须是 0-4096 的整数');
157
+ }
158
+ if (input.partialCredit !== undefined && typeof input.partialCredit !== 'boolean') issues.push('partialCredit 必须是布尔值');
159
+ if (input.answerKeys !== undefined) {
160
+ if (!Array.isArray(input.answerKeys) || input.answerKeys.some((key) => typeof key !== 'string')) {
161
+ issues.push('answerKeys 必须是字符串数组');
162
+ }
163
+ }
164
+ if (input.answer !== undefined && !isPlainObject(input.answer)) issues.push('answer 必须是对象');
165
+ if (input.grading !== undefined) {
166
+ if (!isPlainObject(input.grading)) issues.push('grading 必须是对象');
167
+ else {
168
+ issues.push(...unknownFields(input.grading, GRADING_FIELDS, 'grading'));
169
+ if (input.grading.enabled !== undefined && typeof input.grading.enabled !== 'boolean') issues.push('grading.enabled 必须是布尔值');
170
+ if (input.grading.referenceAnswer !== undefined && typeof input.grading.referenceAnswer !== 'string') issues.push('grading.referenceAnswer 必须是字符串');
171
+ if (input.grading.feedbackLanguage !== undefined && typeof input.grading.feedbackLanguage !== 'string') issues.push('grading.feedbackLanguage 必须是字符串');
172
+ if (input.grading.rubric !== undefined) {
173
+ if (!Array.isArray(input.grading.rubric)) issues.push('grading.rubric 必须是数组');
174
+ else {
175
+ const ids = new Set();
176
+ for (const [index, point] of input.grading.rubric.entries()) {
177
+ if (!isPlainObject(point)) {
178
+ issues.push(`grading.rubric[${index}] 必须是对象`);
179
+ continue;
180
+ }
181
+ issues.push(...unknownFields(point, RUBRIC_FIELDS, `grading.rubric[${index}]`));
182
+ if (typeof point.id !== 'string' || point.id.trim() === '') issues.push(`grading.rubric[${index}].id 必须是非空字符串`);
183
+ else if (ids.has(point.id)) issues.push(`grading.rubric[${index}].id 重复`);
184
+ else ids.add(point.id);
185
+ if (typeof point.points !== 'number' || !Number.isFinite(point.points) || point.points < 0) {
186
+ issues.push(`grading.rubric[${index}].points 必须是非负有限数`);
187
+ }
188
+ if (typeof point.criteria !== 'string' || point.criteria.trim() === '') issues.push(`grading.rubric[${index}].criteria 必须是非空字符串`);
189
+ }
190
+ }
191
+ }
192
+ }
193
+ }
194
+ return issues;
195
+ }
196
+
197
+ // 规范化编辑态题目:保留 answer 明文,分离服务端材料。
198
+ // 缺省字段保持 undefined,由 interaction.upsert 与已有正文合并,避免替换造成配置丢失。
199
+ export function normalizeInteractionInput(input, { keepAnswerMaterial = true } = {}) {
200
+ const kind = input.type ?? input.kind;
201
+ const interaction = {
202
+ id: input.id,
203
+ type: kind,
204
+ stem: String(input.stem ?? '').trim(),
205
+ options: Array.isArray(input.options)
206
+ ? input.options.map((option) => ({ key: String(option.key ?? '').trim(), text: String(option.text ?? '') }))
207
+ : [],
208
+ policy: normalizePolicy(input.policy ?? {}),
209
+ };
210
+ if (input.explain !== undefined) interaction.explain = String(input.explain);
211
+ if (input.answer !== undefined) interaction.answer = input.answer;
212
+ if (Array.isArray(input.answerKeys)) interaction.answerKeys = input.answerKeys.map((key) => String(key).trim());
213
+ if (input.partialCredit !== undefined) interaction.partialCredit = Boolean(input.partialCredit);
214
+ if (input.grading !== undefined) interaction.grading = input.grading;
215
+ if (input.language !== undefined) interaction.language = input.language;
216
+ if (input.starter !== undefined) interaction.starter = input.starter;
217
+ if (input.tests !== undefined) interaction.tests = input.tests;
218
+ if (input.timeLimitMs !== undefined) interaction.timeLimitMs = input.timeLimitMs;
219
+ if (input.memoryLimitMb !== undefined) interaction.memoryLimitMb = input.memoryLimitMb;
220
+ if (input.deadline !== undefined) interaction.deadline = normalizeDeadline(input.deadline) ?? input.deadline;
221
+ if (input.answerHash !== undefined) interaction.answerHash = input.answerHash;
222
+ if (input.answerSalt !== undefined) interaction.answerSalt = input.answerSalt;
223
+ if (!keepAnswerMaterial) {
224
+ delete interaction.answer;
225
+ delete interaction.grading;
226
+ }
227
+ return interaction;
228
+ }
229
+
230
+ // 校验题目结构,返回诊断列表。规则对齐 Interaction::structural_issues。
231
+ export function interactionIssues(interaction) {
232
+ const issues = [];
233
+ if (!interaction || typeof interaction !== 'object') return ['题目正文不是对象'];
234
+ if (!interaction.stem || !String(interaction.stem).trim()) issues.push('题干为空');
235
+ const kind = interaction.type;
236
+ const options = Array.isArray(interaction.options) ? interaction.options : [];
237
+ if (!INTERACTION_KIND_VALUES.includes(kind)) {
238
+ issues.push(`未知题目类型 ${kind}`);
239
+ return issues;
240
+ }
241
+ if (kind === 'single-choice' || kind === 'multi-choice') {
242
+ if (options.length < 2) issues.push('选择题至少需要 2 个选项');
243
+ const seen = new Set();
244
+ for (const option of options) {
245
+ if (!option.key) issues.push('选项 key 为空');
246
+ if (seen.has(option.key)) issues.push(`选项 key \`${option.key}\` 重复`);
247
+ seen.add(option.key);
248
+ }
249
+ }
250
+ issues.push(...policyIssues(interaction.policy));
251
+ if (interaction.partialCredit === true) {
252
+ if (kind !== 'multi-choice') issues.push('仅多选题支持部分给分');
253
+ if (!Array.isArray(interaction.answerKeys) || interaction.answerKeys.length === 0) issues.push('启用部分给分需要提供 answerKeys');
254
+ }
255
+ if (Array.isArray(interaction.answerKeys)) {
256
+ for (const key of interaction.answerKeys) {
257
+ if (!options.some((option) => option.key === key)) issues.push(`answerKeys 中的 \`${key}\` 不在选项里`);
258
+ }
259
+ }
260
+ if (kind === 'multi-choice' && Array.isArray(interaction.answerKeys) && interaction.answerKeys.length === 0) {
261
+ issues.push('多选题答案不能为空');
262
+ }
263
+ if (isObjective(kind)) {
264
+ if (!interaction.answerHash) issues.push('客观题缺少 answerHash');
265
+ if (!interaction.answerSalt) issues.push('客观题缺少 answerSalt');
266
+ if (interaction.answerHash && !/^[a-f0-9]{64}$/.test(interaction.answerHash)) issues.push('answerHash 不是 64 位小写十六进制 sha256');
267
+ }
268
+ return issues;
269
+ }
270
+
271
+ // 编辑态答案是否可转为哈希:仅客观题需要 answer。
272
+ export function answerMaterialIssues(interaction) {
273
+ const issues = [];
274
+ if (!isObjective(interaction.type)) return issues;
275
+ if (interaction.answer === undefined || interaction.answer === null) {
276
+ issues.push('客观题缺少答案');
277
+ return issues;
278
+ }
279
+ if (interaction.type === 'single-choice') {
280
+ if (typeof interaction.answer.choice !== 'string') issues.push('单选答案必须是 choice');
281
+ else if (!interaction.options.some((option) => option.key === interaction.answer.choice.trim())) {
282
+ issues.push(`正确答案 \`${interaction.answer.choice}\` 不在选项中`);
283
+ }
284
+ }
285
+ if (interaction.type === 'multi-choice') {
286
+ if (!Array.isArray(interaction.answer.choices)) issues.push('多选答案必须是 choices 数组');
287
+ else {
288
+ if (interaction.answer.choices.length === 0) issues.push('多选答案至少需要一个选项');
289
+ const unique = new Set();
290
+ for (const key of interaction.answer.choices) {
291
+ if (typeof key !== 'string' || !key.trim()) issues.push('多选答案包含空 key');
292
+ const normalized = String(key).trim();
293
+ if (unique.has(normalized)) issues.push(`多选答案重复:${normalized}`);
294
+ unique.add(normalized);
295
+ if (!interaction.options.some((option) => option.key === normalized)) issues.push(`正确答案 \`${key}\` 不在选项中`);
296
+ }
297
+ }
298
+ }
299
+ if (interaction.type === 'fill-blank') {
300
+ if (!Array.isArray(interaction.answer.blanks)) issues.push('填空答案必须是 blanks 数组');
301
+ else if (interaction.answer.blanks.length === 0) issues.push('填空答案至少需要一个空');
302
+ }
303
+ if (!normalizeAnswer(interaction.type, interaction.answer)) issues.push('答案结构无法规范化');
304
+ return issues;
305
+ }
@@ -0,0 +1,288 @@
1
+ // 与 crates/lume-courseware 保持一致的标识符、路径和内容规则。
2
+ // 修改本文件时必须同步 spec/manifest.schema.json 与 Rust 侧实现。
3
+
4
+ export const SPEC_VERSION = '1.1';
5
+ export const RUNTIME_VERSION = '1.1.0';
6
+ // 与 crates/lume-courseware 的 AspectRatio 枚举保持一致。
7
+ export const ASPECT_RATIOS = ['16:9', '4:3', '16:10', '21:9', '1:1'];
8
+ export const DEFAULT_ASPECT_RATIO = '16:9';
9
+ export const MAX_BODY_CHARS = 6000;
10
+ export const MAX_SCENE_PROSE = 60;
11
+ export const MAX_STATE_BYTES = 4096;
12
+ export const MAX_HTML_BYTES = 1024 * 1024;
13
+
14
+ // HTML 场景安全基线:沙箱内也不允许主动外联、读取宿主存储或嵌入可执行对象。
15
+ export function htmlSafetyIssues(text) {
16
+ const source = String(text ?? '');
17
+ const issues = [];
18
+ if (Buffer.byteLength(source, 'utf8') > MAX_HTML_BYTES) issues.push(`HTML 超过 ${MAX_HTML_BYTES} 字节上限`);
19
+ const patterns = [
20
+ [/<script[^>]+src\s*=\s*["'](?:https?:)?\/\//i, '禁止引用外部脚本'],
21
+ [/\bfetch\s*\(/, '禁止发起网络请求'],
22
+ [/\bXMLHttpRequest\b/, '禁止使用 XMLHttpRequest'],
23
+ [/\bnew\s+WebSocket\b/, '禁止在场景内建立 WebSocket'],
24
+ [/\bwindow\.open\s*\(/, '禁止打开新窗口'],
25
+ [/\bdocument\.cookie\b/, '禁止读取 Cookie'],
26
+ [/\b(?:local|session)Storage\b/, '禁止访问浏览器存储'],
27
+ [/<iframe\b/i, '禁止嵌套 iframe'],
28
+ [/<object\b|<embed\b/i, '禁止嵌入对象'],
29
+ [/<form\b/i, '禁止表单提交'],
30
+ [/<base\b/i, '禁止改写基准地址'],
31
+ ];
32
+ for (const [pattern, message] of patterns) {
33
+ if (pattern.test(source)) issues.push(message);
34
+ }
35
+ return issues;
36
+ }
37
+
38
+ export const SUBJECTS = ['信息科技', '信息技术', '人工智能', '通用技术', '跨学科'];
39
+ export const PHASES = ['engage', 'explain', 'demo', 'practice', 'assess', 'summary'];
40
+ export const LAYOUTS = ['full', 'split', 'compare', 'code-focus', 'media', 'canvas'];
41
+ export const RUN_MODES = ['broadcast', 'explore', 'converge'];
42
+ export const BLOOM = ['remember', 'understand', 'apply', 'analyze', 'evaluate', 'create'];
43
+ export const COMPONENT_KINDS = [
44
+ 'lume-code', 'lume-run', 'lume-blocks', 'lume-vars', 'lume-sheet', 'lume-doc',
45
+ 'lume-board', 'lume-chart', 'lume-graph', 'lume-3d', 'lume-sim', 'lume-quiz',
46
+ 'lume-hotspot', 'lume-terminal', 'lume-timer', 'lume-ai',
47
+ ];
48
+ export const COLLECT = ['none', 'onDemand', 'onSubmit', 'periodic'];
49
+ export const INTERACTION_KINDS = ['single-choice', 'multi-choice', 'fill-blank', 'code', 'open'];
50
+
51
+ export function charLen(value) {
52
+ return [...String(value)].length;
53
+ }
54
+
55
+ export function isPackageId(value) {
56
+ if (typeof value !== 'string') return false;
57
+ if (value.length < 6 || value.length > 96) return false;
58
+ return value.split('.').every((segment) => segment.length > 0 && /^[a-z0-9]+$/.test(segment));
59
+ }
60
+
61
+ export function isSemver(value) {
62
+ return typeof value === 'string' && /^\d+\.\d+\.\d+$/.test(value);
63
+ }
64
+
65
+ export function isSceneId(value) {
66
+ return typeof value === 'string' && /^s\d{1,3}$/.test(value);
67
+ }
68
+
69
+ export function isObjectiveId(value) {
70
+ return typeof value === 'string' && /^o\d{1,2}$/.test(value);
71
+ }
72
+
73
+ export function isComponentCid(value) {
74
+ return typeof value === 'string' && /^[a-z][a-z0-9]{0,15}$/.test(value);
75
+ }
76
+
77
+ export function isInteractionId(value) {
78
+ if (typeof value !== 'string') return false;
79
+ const length = charLen(value);
80
+ return length >= 3 && length <= 40 && /^[a-z0-9][a-z0-9\-_]*$/.test(value);
81
+ }
82
+
83
+ export function isSha256(value) {
84
+ return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
85
+ }
86
+
87
+ export function isGrade(value) {
88
+ if (typeof value !== 'string') return false;
89
+ if (['高一', '高二', '高三'].includes(value)) return true;
90
+ if (!value.endsWith('年级')) return false;
91
+ let rest = value.slice(0, -2);
92
+ for (const school of ['小学', '初中', '高中']) {
93
+ if (rest.startsWith(school)) {
94
+ rest = rest.slice(school.length);
95
+ break;
96
+ }
97
+ }
98
+ return charLen(rest) <= 1 && /^[一二三四五六七八九]?$/.test(rest);
99
+ }
100
+
101
+ export function isSceneFile(value) {
102
+ if (typeof value !== 'string' || !value.startsWith('scenes/')) return false;
103
+ const name = value.slice('scenes/'.length);
104
+ const stripped = name.endsWith('.html') ? name.slice(0, -5) : name.endsWith('.md') ? name.slice(0, -3) : null;
105
+ return stripped !== null && stripped.length > 0 && /^[a-z0-9\-_]+$/.test(stripped);
106
+ }
107
+
108
+ export function isInteractionFile(value) {
109
+ if (typeof value !== 'string' || !value.startsWith('interactions/')) return false;
110
+ const name = value.slice('interactions/'.length);
111
+ if (!name.endsWith('.json')) return false;
112
+ const stripped = name.slice(0, -5);
113
+ return stripped.length > 0 && /^[a-z0-9\-_]+$/.test(stripped);
114
+ }
115
+
116
+ export function isVersionRange(value) {
117
+ return typeof value === 'string' && value.length > 0 && /^[><=~^ \d.,]+$/.test(value);
118
+ }
119
+
120
+ export function isSafeRelative(path) { if (typeof path !== 'string' || path.length === 0) return false;
121
+ if (path.startsWith('/') || path.startsWith('\\')) return false;
122
+ if (path.includes('\\') || path.includes(':')) return false;
123
+ return path.split('/').every((segment) => segment.length > 0 && segment !== '.' && segment !== '..');
124
+ }
125
+
126
+ export function satisfiesRange(range, version) {
127
+ const actual = version.split('.').map(Number);
128
+ const parts = String(range).trim().split(/\s+/).filter(Boolean);
129
+ return parts.every((part) => {
130
+ // 兼容 >=1.1 这类省略 patch 的写法。
131
+ const match = /^(>=|<=|>|<|=|\^|~)?(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(part);
132
+ if (!match) return false;
133
+ const [, operator = '=', rawMajor, rawMinor = '0', rawPatch = '0'] = match;
134
+ const target = [Number(rawMajor), Number(rawMinor), Number(rawPatch)];
135
+ let result = 0;
136
+ for (let index = 0; index < 3; index += 1) {
137
+ if (actual[index] !== target[index]) {
138
+ result = actual[index] < target[index] ? -1 : 1;
139
+ break;
140
+ }
141
+ }
142
+ switch (operator) {
143
+ case '>=': return result >= 0;
144
+ case '<=': return result <= 0;
145
+ case '>': return result > 0;
146
+ case '<': return result < 0;
147
+ case '=': return result === 0;
148
+ case '^': return actual[0] === target[0] && result >= 0;
149
+ case '~': return actual[0] === target[0] && actual[1] === target[1] && result >= 0;
150
+ default: return false;
151
+ }
152
+ });
153
+ }
154
+
155
+ const ALNUM = /[\p{L}\p{N}]/u;
156
+
157
+ // 统计 HTML 可见正文:忽略标签、注释、script 与 style 内容。
158
+ export function htmlProseChars(text) {
159
+ const source = String(text);
160
+ const length = source.length;
161
+ let index = 0;
162
+ let count = 0;
163
+ let hiddenTag = null;
164
+
165
+ const isBoundary = (offset, needle) => {
166
+ if (!source.startsWith(needle, offset) && !source.slice(offset, offset + needle.length).toLowerCase() === needle) return false;
167
+ const next = source[offset + needle.length];
168
+ return next === undefined ? false : next === '>' || next === '/' || next === ' ' || next === '\t' || next === '\r' || next === '\n';
169
+ };
170
+
171
+ const startsTag = (offset, tag) => {
172
+ if (offset + tag.length >= length) return false;
173
+ if (source.slice(offset, offset + tag.length).toLowerCase() !== tag) return false;
174
+ const next = source[offset + tag.length];
175
+ return next === '>' || next === '/' || next === ' ' || next === '\t' || next === '\r' || next === '\n';
176
+ };
177
+
178
+ const findTagEnd = (start) => {
179
+ let quote = null;
180
+ for (let offset = start; offset < length; offset += 1) {
181
+ const character = source[offset];
182
+ if (quote === null && (character === '"' || character === "'")) quote = character;
183
+ else if (quote !== null && character === quote) quote = null;
184
+ else if (character === '>' && quote === null) return offset;
185
+ }
186
+ return null;
187
+ };
188
+
189
+ while (index < length) {
190
+ const character = source[index];
191
+ if (hiddenTag) {
192
+ if (startsTag(index, `</${hiddenTag}`) || (source.startsWith('</', index) && source.slice(index + 2, index + 2 + hiddenTag.length).toLowerCase() === hiddenTag)) {
193
+ const end = findTagEnd(index + 2);
194
+ index = end === null ? length : end + 1;
195
+ hiddenTag = null;
196
+ } else {
197
+ index += 1;
198
+ }
199
+ continue;
200
+ }
201
+ if (character !== '<') {
202
+ if (ALNUM.test(character)) count += 1;
203
+ index += 1;
204
+ continue;
205
+ }
206
+ if (source.startsWith('<!--', index)) {
207
+ const offset = source.indexOf('-->', index + 4);
208
+ index = offset === -1 ? length : offset + 3;
209
+ continue;
210
+ }
211
+ const end = findTagEnd(index + 1);
212
+ if (end === null) break;
213
+ if (startsTag(index, '<script')) hiddenTag = 'script';
214
+ else if (startsTag(index, '<style')) hiddenTag = 'style';
215
+ index = end + 1;
216
+ }
217
+ return count;
218
+ }
219
+
220
+ export function proseChars(text) {
221
+ const body = stripFrontmatter(String(text));
222
+ let inCode = false;
223
+ let count = 0;
224
+ for (const line of body.split(/\r?\n/)) {
225
+ const trimmed = line.trim();
226
+ if (trimmed.startsWith('```')) {
227
+ inCode = !inCode;
228
+ continue;
229
+ }
230
+ if (inCode || trimmed.startsWith(':::')) continue;
231
+ for (const character of trimmed) {
232
+ if (ALNUM.test(character)) count += 1;
233
+ }
234
+ }
235
+ return count;
236
+ }
237
+
238
+ export function stripFrontmatter(text) {
239
+ const source = String(text);
240
+ if (!source.startsWith('---')) return source;
241
+ const rest = source.slice(3);
242
+ const offset = rest.indexOf('\n---');
243
+ if (offset === -1) return source;
244
+ return rest.slice(offset + 4).replace(/^\n+/, '');
245
+ }
246
+
247
+ export function frontmatterId(text) {
248
+ const source = String(text);
249
+ if (!source.startsWith('---')) return null;
250
+ const rest = source.slice(3);
251
+ const end = rest.indexOf('\n---');
252
+ if (end === -1) return null;
253
+ for (const line of rest.slice(0, end).split(/\r?\n/)) {
254
+ const trimmed = line.trim();
255
+ if (trimmed.startsWith('id:')) return trimmed.slice(3).trim().replace(/^["']|["']$/g, '');
256
+ }
257
+ return null;
258
+ }
259
+
260
+ // 判定用规范化,与 interaction.rs 完全一致。
261
+ export function normalizeAnswer(kind, answer) {
262
+ if (!answer || typeof answer !== 'object') return null;
263
+ switch (kind) {
264
+ case 'single-choice': {
265
+ if (typeof answer.choice !== 'string') return null;
266
+ return `choice:${answer.choice.trim()}`;
267
+ }
268
+ case 'multi-choice': {
269
+ if (!Array.isArray(answer.choices)) return null;
270
+ const keys = answer.choices
271
+ .filter((value) => typeof value === 'string')
272
+ .map((value) => value.trim())
273
+ .sort();
274
+ return `choices:${keys.join(',')}`;
275
+ }
276
+ case 'fill-blank': {
277
+ if (!Array.isArray(answer.blanks)) return null;
278
+ const items = answer.blanks.map((value) => (typeof value === 'string' ? value.trim() : ''));
279
+ return `blanks:${items.join('\u001f')}`;
280
+ }
281
+ case 'code':
282
+ return typeof answer.code === 'string' ? `code:${answer.code.trim()}` : null;
283
+ case 'open':
284
+ return typeof answer.text === 'string' ? `text:${answer.text.trim()}` : null;
285
+ default:
286
+ return null;
287
+ }
288
+ }