import type {NPConfig, NPField, NPValue, NPRun} from './contract.ts'; // script_id is the shared identity; display names are not a registration match. // 转换工具登记的 script_id 是内容哈希,生成器段名在登记 id 的“<根>/<段名>”里(整段相等,不认后缀); // 看某一批时只认这一批的根:同一配置跑两批,段名相同。 export function matchRegistered(segments: S[], registered: R[], root?: string): (R | null)[] { const pool = root ? registered.filter(row => row.root === root) : registered; return segments.map(segment => pool.find(row => row.script_id === segment.script_id || (row.root != null && row.id === row.root + '/' + segment.script_id)) ?? null); } export function filterByReason}>(segments: S[], reasonId: string): S[] | null { if (!segments.length || segments.some(segment => segment.reasons == null)) return null; return segments.filter(segment => (segment.reasons?.[reasonId] ?? 0) > 0); } export function runFinished(run: Pick): boolean { return run.status !== 'running'; } /** 页面上的时刻一律中文格式,不随浏览器语言变。 */ export const localTime = (iso: string) => new Date(iso).toLocaleString('zh-CN', {hour12: false}); /** 段长档位的中文名。 */ export const lengthLabel = (length: string) => ({short: '短段', long: '长段'} as Record)[length] || length; /** 结果屏顶部的批次状态(设计 R-1):完成与否、开始时间和各阶段用时之和、和哪一批比。 */ export function runSummary(run: Pick, previous?: Pick) { const state = run.status === 'completed' ? '完成' : run.status === 'completed_with_failures' ? '完成(有失败段)' : run.status === 'failed' ? '失败' : '进行中'; const seconds = Math.round(run.stages.reduce((n, stage) => n + stage.seconds, 0)); return {state, ok: run.status === 'completed', time: `${localTime(run.created_at)} 开始 · 用时 ${seconds} s`, compare: previous ? `和上一批比:${previous.label}(${localTime(previous.created_at)})` : '没有更早的批次,不比'}; } /** 生成那一步被拒的段按拒因分项(run.stages 里 generate 的 rejected;中文名来自 np/planning.py GENERATOR_REJECT_LABELS,接入-6)。 */ export function generatorRejects(run: Pick) { return run.stages.find(stage => stage.id === 'generate')?.rejected?.filter(row => row.count > 0) ?? []; } export function schemaDefaults(field: NPField): NPValue { if (field.type === 'object' && field.properties) return Object.fromEntries(Object.entries(field.properties).map(([key, spec]) => [key, schemaDefaults(spec)])); return field.default ?? field.const ?? (field.type === 'object' ? {} : field.type === 'array' ? [] : field.type === 'boolean' ? false : ['integer', 'number'].includes(field.type || '') ? 0 : ''); } export function setConfigPath(config: NPConfig, path: string[], value: NPValue): NPConfig { const copy = structuredClone(config); let parent = copy; for (const key of path.slice(0, -1)) { if (!parent[key] || typeof parent[key] !== 'object' || Array.isArray(parent[key])) parent[key] = {}; parent = parent[key] as NPConfig; } parent[path[path.length - 1]] = value; return copy; } const errors: Record = {GENERATION_BUSY: '已经有一批在跑', BATCH_REPEATS: '这批的设定和种子与以前的一批完全相同,会生成同样的剧本;已换了新种子,再点一次开始', NP_RUNS_NOT_CONFIGURED: '服务没配生成器,只能规划', GENERATOR_COMMIT_MISMATCH: '生成器版本和登记的不符'}; export function generationError(error: unknown): string { const message = error instanceof Error ? error.message : String(error); const code = Object.keys(errors).find(code => message.startsWith(code)); return code ? errors[code] : message.replace(/^[A-Z][A-Z0-9_]+:/, ''); } export async function postNP(url: string, body: unknown, signal?: AbortSignal): Promise { const response = await fetch(url, {method: 'POST', headers: {'Content-Type': 'application/json'}, credentials: 'same-origin', body: JSON.stringify(body), signal}); const value = await response.json(); if (!response.ok) throw Error(`${value.error?.code || response.status}:${value.error?.message || '请求失败'}`); return value as T; }