dsh-novel-game 0.1.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 0.2.0 — 2026-11-29
4
+
5
+ 新增 KiriKiri / NScripter 两个 Galgame 引擎、Wolf RPG 文本抢救、剧情路线图与摘录失效标记。
6
+
7
+ ### 新增
8
+
9
+ - **KiriKiri / KAG**:`.xp3` 归档(XP3 头、zlib/未压缩索引、File/info/data chunk;条目 zlib 解压)+ `.ks` 剧本(label、文本行、`@jump/@call`、标签剥离、说话人「名字「…」/名字:…」);散装 `.ks` 与归档内 `.ks` 都读。
10
+ - **NScripter / ONScripter**:`nscript.dat`(逐字节 XOR 0x84)与 `0.txt`/`*.nscript`;`*label`、`select` 选项、`goto/jumpf`、命令白名单(`bg/ld/play/…` 当演出指令跳过);`.nsa` 记为不支持容器(通常只放图片/音频)。
11
+ - **Wolf RPG Editor(文本抢救)**:检测 `Data/`、`Data.wolf`、`Game.exe`;从 `Data/*.dat`/`*.mps` 里扫描可读文本段(UTF-16LE/UTF-8),标为低置信场景;默认不进可见范围与导出,需 `settings.includeLowConfidence=true`。
12
+ - **剧情路线图**:`game_routes` 工具 + 面板「路线图」;场景为节点,选项/跳转为边,标签解析为场景;未解析边单独计数,候选结局 = 无出边的场景。
13
+ - **摘录失效标记**:`game_pick` 列表对找不到的 `lineId` 标 `stale`(结构变化不再静默丢引用)。
14
+ - **低置信开关**:`includeLowConfidence` 控制 Wolf 抢救文本是否参与浏览/导出。
15
+
16
+ ### 测试
17
+
18
+ - 18 项全过:新增 XP3 索引/条目、KiriKiri 解析、NScripter XOR 与选项、Wolf 抢救与低置信过滤、路线图、摘录 stale。
19
+
20
+ ### 已知限制
21
+
22
+ - Wolf 只做文本抢救(`Game.dat` 常见加密,不破解);`.nsa` 不解包。
23
+ - `.rpyc` 仍不反编译;KiriKiri 的 `[link]` 选项文本未单独建边(只做文本行与 jump)。
24
+ - 大 JSON 仍整文件解析(0.2.1 排流式 tokenizer)。
25
+
3
26
  ## 0.1.0 — 2026-11-29
4
27
 
5
28
  首个可用版本:本地合法游戏副本的剧情/文本/设定解包,右栏六页面板,三件套单向导出。
package/README.md CHANGED
@@ -19,7 +19,7 @@ DSH 插件:Host 工具 + 右侧栏六页面板。只处理你自己合法持
19
19
  ## 它不做什么
20
20
 
21
21
  - 不解析完整游戏代码、不反编译着色器/引擎运行时;只抽「玩家可见内容」。
22
- - 不解密图片/音频、不复制素材、不生成缩略图(0.1.0)。
22
+ - 不解密图片/音频、不复制素材、不生成缩略图(0.2.0)。
23
23
  - 不做盗版下载、不绕过 DRM/在线验证、不处理手游/联机/抽卡的服务端内容。
24
24
  - 不写其它 `.dsh-novel-*/` 目录;与 fanfic/kit 只做单向导出。
25
25
 
@@ -50,7 +50,9 @@ npm i dsh-novel-game
50
50
  | RPG Maker MV / MZ | 0.1.0 | 地图/公共/战斗事件的对白与选项、角色/物品/技能/敌人/系统词条、图片与 BGM 引用 |
51
51
  | Ren'Py | 0.1.0 | 明文 `.rpy` 的 label、Character、say、menu、jump/call、scene/show、voice;`.rpa` 内文本条目 |
52
52
  | 通用文本嗅探 | 0.1.0 | JSON/CSV/PO/Yarn/Ink/TXT/SRT 里的对话候选(低置信,需核对) |
53
- | KiriKiri / NScripter / Wolf RPG | 0.2.0 计划 | — |
53
+ | KiriKiri / KAG | 0.2.0 | `.xp3` 归档 + 散装 `.ks`:label、对白、`@jump/@call`、标签剥离 |
54
+ | NScripter / ONScripter | 0.2.0 | `nscript.dat`(XOR)/`0.txt`:对白、`select` 选项、`goto/jumpf`;`.nsa` 报不支持 |
55
+ | Wolf RPG Editor | 0.2.0(文本抢救) | `Data/*.dat` 里可读文本段;低置信,默认不显示/不导出 |
54
56
  | Godot / Unity / GameMaker | 0.3.0 计划 | — |
55
57
 
56
58
  `.rpyc` 编译脚本在 0.1.0 不解反编译:会出现在覆盖率报告里并提示用 `unrpyc` 或提供明文脚本。
@@ -80,6 +82,7 @@ npm i dsh-novel-game
80
82
  | `game_detect` | 只探测不写入 |
81
83
  | `game_import` / `game_job_status` / `game_cancel_job` | 后台导入与进度 |
82
84
  | `game_scenes` / `game_scene` | 场景列表 / 场景台词与选项 |
85
+ | `game_routes` | 剧情路线图(节点/边/候选结局) |
83
86
  | `game_search` | 台词与词条检索 |
84
87
  | `game_characters` / `game_glossary` | 人物卡草稿 / 词条 |
85
88
  | `game_pick` | 同人准备篮(add / list) |
@@ -94,12 +97,13 @@ npm run check
94
97
 
95
98
  零运行时依赖;纯 Node ESM。
96
99
 
97
- ## 已知限制(0.1.0)
100
+ ## 已知限制(0.2.0)
98
101
 
99
- - 大 JSON 目前整文件解析(有 32MB 上限),流式 tokenizer 排在 0.2.0。
102
+ - 大 JSON 目前整文件解析(有 32MB 上限),流式 tokenizer 排在 0.2.1。
100
103
  - `.rpyc` 不反编译;`.rpa` 只支持受限 pickle 子集(白名单外拒绝)。
101
104
  - 不模拟 RPG Maker 的开关/变量;条件页并列展示为候选剧情,不声称实际游玩顺序。
102
- - Unity / Godot / GameMaker 未支持。
105
+ - Wolf RPG 只做文本抢救(`Game.dat` 常见加密,不破解);NScripter 的 `.nsa` 不解包。
106
+ - KiriKiri 的 `[link]` 选项没有单独建边;Unity / Godot / GameMaker 未支持。
103
107
 
104
108
  ## 共同作者
105
109
 
package/client.js CHANGED
@@ -35,6 +35,7 @@ window.__ModuleLoader__.load({
35
35
  invoke("scenes", [param("options", obj)]),
36
36
  invoke("scene", [param("options", obj)]),
37
37
  invoke("search", [param("options", obj)]),
38
+ invoke("routes", [param("options", obj)]),
38
39
  invoke("characters", [param("options", obj)]),
39
40
  invoke("glossary", [param("options", obj)]),
40
41
  invoke("picks", [param("options", obj)]),
@@ -111,6 +112,7 @@ window.__ModuleLoader__.load({
111
112
  const [query, setQuery] = React.useState("");
112
113
  const [results, setResults] = React.useState(null);
113
114
  const [cast, setCast] = React.useState(null);
115
+ const [routes, setRoutes] = React.useState(null);
114
116
  const [terms, setTerms] = React.useState(null);
115
117
  const [picks, setPicks] = React.useState(null);
116
118
  const [exported, setExported] = React.useState(null);
@@ -220,6 +222,11 @@ window.__ModuleLoader__.load({
220
222
  if (value) setPicks(value);
221
223
  }
222
224
 
225
+ async function loadRoutes() {
226
+ const value = await run(async () => unwrap(await remote.routes(sessionId, { gameId })));
227
+ if (value) setRoutes(value);
228
+ }
229
+
223
230
  async function addPick(line) {
224
231
  const value = await run(async () => unwrap(await remote.addPick(sessionId, { gameId, kind: "line", refId: line.lineId })));
225
232
  if (value) flash("已收进同人准备篮");
@@ -302,6 +309,19 @@ window.__ModuleLoader__.load({
302
309
  }
303
310
 
304
311
  function renderStory() {
312
+ if (routes) {
313
+ const titleOf = (id) => routes.nodes.find((node) => node.sceneId === id)?.title ?? id;
314
+ return h("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
315
+ h("div", { style: S.row }, h(Btn, { onClick: () => setRoutes(null) }, "← 场景列表"), h("b", null, "路线图")),
316
+ h("div", { style: S.sub }, `节点 ${routes.nodes.length} · 边 ${routes.edges.length} · 未解析 ${routes.unresolved}`),
317
+ ...routes.edges.filter((edge) => edge.resolved).slice(0, 80).map((edge, index) => h("div", { key: index, style: S.sub },
318
+ `${titleOf(edge.from)} → ${titleOf(edge.to)}(${edge.kind === "choice" ? "选项" : "跳转"}:${edge.label})`,
319
+ )),
320
+ h("div", { style: { ...S.row, marginTop: 6 } }, h("b", null, "候选结局")),
321
+ ...routes.endings.slice(0, 40).map((id) => h("div", { key: id, style: S.sub }, titleOf(id))),
322
+ h("div", { style: { ...S.sub, marginTop: 6 } }, routes.note ?? ""),
323
+ );
324
+ }
305
325
  if (detail) {
306
326
  return h("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
307
327
  h("div", { style: S.row },
@@ -327,6 +347,7 @@ window.__ModuleLoader__.load({
327
347
  }
328
348
  const items = scenes?.items ?? [];
329
349
  return h("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
350
+ h("div", { style: S.row }, h("span", { style: S.sub }, `共 ${scenes?.total ?? 0} 场`), h(Btn, { onClick: loadRoutes, disabled: busy || !gameId }, "路线图")),
330
351
  items.length === 0 ? h("div", { style: S.empty }, "这个游戏还没有可浏览的场景。") : null,
331
352
  ...items.map((scene) => h("div", {
332
353
  key: scene.sceneId, style: { ...S.card, cursor: "pointer" },
package/docs/ENGINES.md CHANGED
@@ -43,9 +43,33 @@
43
43
  - SRT:按 cue 合并文本行。
44
44
  - 编码:BOM 优先;否则 UTF-8 / GB18030 / Shift-JIS / Big5 里选坏字符最少者。
45
45
 
46
- ## 0.2.0 计划
46
+ ## KiriKiri / KAG(0.2.0)
47
47
 
48
- - KiriKiri:`.xp3` 索引 + `.ks` 的 KAG 标签。
49
- - NScripter:`nscript.dat`(XOR 0x84)/ `0.txt`、`arc.nsa`。
50
- - Wolf RPG:`.wolf` 归档、`Game.dat`、地图/公共事件数据库。
51
- - 参考:[morkt/GARbro](https://github.com/morkt/GARbro)、[stmkza/xp3.js](https://github.com/stmkza/xp3.js)、[Sinflower/UberWolf](https://github.com/Sinflower/UberWolf)、[danmig06/nscript.dat-tool](https://github.com/danmig06/nscript.dat-tool)。
48
+ - 归档:`.xp3` 头 11 字节 `XP3\r\n \x1a\x8b\x67\x01`,其后 u64 索引偏移;索引多数为 zlib 压缩,少数未压缩(读取时先试 inflate,失败按原文解析)。
49
+ - 索引为 chunk 流:`File`(0x656C6946)chunk 内含 `info`(u16 名称长度 + UTF-16LE 名称 + 文件大小)与 `data`(offset / packedSize / unpackedSize 三个 u64)。
50
+ - 条目:`packedSize === unpackedSize` 视为未压缩,否则 zlib 解压;有 64MB 上限。
51
+ - 剧本:`.ks` 的 `*label`、文本行、`[tag]` 剥离、`@jump/@call target=...`;`@bg` 等演出指令计入未解析。
52
+ - 参考:[stmkza/xp3.js](https://github.com/stmkza/xp3.js)、[morkt/GARbro](https://github.com/morkt/GARbro)。
53
+ - 已知缺口:`[link]` 选项未建边;加密/定制 xp3 只报错。
54
+
55
+ ## NScripter / ONScripter(0.2.0)
56
+
57
+ - `nscript.dat` 为逐字节 XOR 0x84 的脚本(`*` 0x2A → 0xAE 可作签名);`0.txt`/`*.nscript` 为明文。
58
+ - 语法:`*label`、`select "文本",*标签,...`、`goto/jumpf`、命令白名单(`bg/ld/play/stop/wait/…`)跳过;文本行剥离 `\n` 等转义。
59
+ - `.nsa` 不解包(通常只放图片/音频),在覆盖率里标「不支持」。
60
+ - 参考:[danmig06/nscript.dat-tool](https://github.com/danmig06/nscript.dat-tool)。
61
+
62
+ ## Wolf RPG Editor(0.2.0,文本抢救)
63
+
64
+ - 检测:`Data/`、`Data.wolf`、`Game.exe`。
65
+ - `Game.dat` 常见加密,**不破解**;对 `Data/*.dat`、`MapData/*.mps` 做 UTF-16LE / UTF-8 可读文本段扫描(含 CJK 或句末标点/长英文句),去重后作为低置信旁白。
66
+ - 低置信场景默认不参与浏览与导出;`settings.includeLowConfidence=true` 才显示。
67
+ - 参考:[Sinflower/UberWolf](https://github.com/Sinflower/UberWolf)(加密与归档的权威实现;本插件不集成)。
68
+ - 0.2.1 计划:`.wolf` 归档读取与明文 `Game.dat` 的结构化抽取。
69
+
70
+ ## 0.3.0 计划
71
+
72
+ - Godot:`.pck` + `.tscn/.tres` + 翻译表。
73
+ - Unity:`StreamingAssets` 本地化表、`TextAsset` 内嵌对话。
74
+ - GameMaker:`data.win` 的 `STRG` 字符串表。
75
+ - 参考:[Not-Parker/godot-pck-reader](https://github.com/Not-Parker/godot-pck-reader)、[AssetRipper/AssetRipper](https://github.com/AssetRipper/AssetRipper)、[UnderminersTeam/UndertaleModTool](https://github.com/UnderminersTeam/UndertaleModTool)。
package/index.js CHANGED
@@ -269,6 +269,21 @@ const tools = [
269
269
  });
270
270
  }),
271
271
  },
272
+ {
273
+ name: 'game_routes',
274
+ description: '剧情路线图:场景节点、选项/跳转边、候选结局;未解析边单独标出。',
275
+ parameters: {
276
+ type: 'object',
277
+ properties: { dir: dirParam, gameId: gameIdParam },
278
+ required: ['dir', 'gameId'],
279
+ additionalProperties: false,
280
+ },
281
+ output,
282
+ execute: guarded(async (args, exec) => {
283
+ const service = await serviceFor(await requireDir(args, exec));
284
+ return service.routes(args.gameId);
285
+ }),
286
+ },
272
287
  {
273
288
  name: 'game_export',
274
289
  description: '导出三件套到 .dsh-novel-game/exports/:story.md(可给 fanfic /fic import)、canon.json、brief.md。',
@@ -0,0 +1,197 @@
1
+ import path from 'node:path';
2
+ import { isXp3, readXp3Entry, readXp3Index } from '../archive/xp3.mjs';
3
+
4
+ /**
5
+ * KAG 剧本解析(KiriKiri .ks)。
6
+ * 只做静态解析:标签、文本行、跳转;不解释表达式、不执行。
7
+ */
8
+ export function* parseKagScript(text, { relPath }) {
9
+ const lines = String(text).split(/\r?\n/);
10
+ let sceneKey = null;
11
+ let sceneOrder = 0;
12
+ let lineOrder = 0;
13
+ let label = null;
14
+
15
+ const ensureScene = function* () {
16
+ if (sceneKey) return;
17
+ sceneKey = `${relPath}#top`;
18
+ yield { type: 'scene', key: sceneKey, title: '开场', container: relPath, order: sceneOrder++, conditions: null, src: { relPath, path: 'top' } };
19
+ };
20
+
21
+ for (let index = 0; index < lines.length; index += 1) {
22
+ const raw = lines[index];
23
+ const trimmed = raw.trim();
24
+ if (!trimmed) continue;
25
+ if (trimmed.startsWith(';') || trimmed.startsWith('//')) continue;
26
+ const src = { relPath, path: `line:${index + 1}`, index };
27
+
28
+ const labelMatch = /^\*([A-Za-z_][\w.-]*)\s*$/.exec(trimmed);
29
+ if (labelMatch) {
30
+ label = labelMatch[1];
31
+ sceneKey = `${relPath}#label:${label}`;
32
+ lineOrder = 0;
33
+ yield { type: 'scene', key: sceneKey, title: label, container: relPath, order: sceneOrder++, conditions: null, src };
34
+ continue;
35
+ }
36
+
37
+ // 命令:@jump / @call / [jump ...] / [link ...]
38
+ const jump = /^@(?:jump|call)\s+(?:target|storage)=["']?([^"'\s]+)/.exec(trimmed)
39
+ ?? /^\[(?:jump|call)\s+(?:target|storage)=["']?([^"'\s]+)/.exec(trimmed);
40
+ if (jump) {
41
+ yield* ensureScene();
42
+ yield { type: 'jump', sceneKey, label: jump[1].replace(/^\*/, ''), src };
43
+ continue;
44
+ }
45
+ if (/^@|^\[(?:cm|er|hr|r|p|l|delay|wait|locate|position|image|bg|music|sound|se|voice|trans|quake|flash|fadein|fadeout|graph|move|anim|stop|play|call|jump|if|elsif|else|endif|end|link|endlink|macro|endmacro|ignore|endignore)\b/.test(trimmed)) {
46
+ yield* ensureScene();
47
+ yield { type: 'skip', sceneKey, reason: 'kag-tag', src };
48
+ continue;
49
+ }
50
+
51
+ // 文本行:去掉 [tag]
52
+ const plain = trimmed.replace(/\[[^\]]*\]/g, '').trim();
53
+ if (!plain) continue;
54
+ const speaker = /^([^「」::]{1,16})[「::]\s*[「]?(.+?)[」]?$/.exec(plain);
55
+ yield* ensureScene();
56
+ yield {
57
+ type: 'line',
58
+ sceneKey,
59
+ order: lineOrder++,
60
+ kind: speaker ? 'dialogue' : 'narration',
61
+ speakerId: speaker ? `name:${speaker[1]}` : null,
62
+ speakerName: speaker ? speaker[1].trim() : null,
63
+ text: speaker ? speaker[2].trim() : plain,
64
+ refs: {},
65
+ src,
66
+ };
67
+ }
68
+ }
69
+
70
+ async function walk(ctx, dir, extensions, depth = 2, level = 0, out = []) {
71
+ if (level > depth) return out;
72
+ for (const entry of await ctx.list(dir)) {
73
+ if (entry.dir) await walk(ctx, entry.rel, extensions, depth, level + 1, out);
74
+ else if (extensions.some((ext) => entry.name.toLowerCase().endsWith(ext))) out.push(entry.rel);
75
+ }
76
+ return out;
77
+ }
78
+
79
+ export const kirikiri = {
80
+ id: 'kirikiri',
81
+ label: 'KiriKiri / KAG',
82
+
83
+ async detect(ctx) {
84
+ const evidence = [];
85
+ let score = 0;
86
+ const archives = [];
87
+ for (const dir of ['', 'game', 'data']) {
88
+ for (const entry of await ctx.list(dir || '.')) {
89
+ if (!entry.dir && entry.name.toLowerCase().endsWith('.xp3')) archives.push(entry.rel);
90
+ }
91
+ }
92
+ if (archives.length) {
93
+ score = 0.9;
94
+ evidence.push(`${archives.length} 个 .xp3`);
95
+ }
96
+ const scripts = await walk(ctx, '.', ['.ks'], 2);
97
+ if (scripts.length) {
98
+ score = Math.max(score, 0.86);
99
+ evidence.push(`${scripts.length} 个 .ks`);
100
+ }
101
+ if (await ctx.exists('krkr.exe') || await ctx.exists('TVP(KIRIKIRI) Z.exe') || (await ctx.list('.')).some((entry) => /tvp|kirikiri/i.test(entry.name))) {
102
+ score = Math.max(score, 0.78);
103
+ evidence.push('KiriKiri 可执行文件');
104
+ }
105
+ if (score === 0) return null;
106
+ return {
107
+ engineId: 'kirikiri',
108
+ label: 'KiriKiri / KAG',
109
+ confidence: score,
110
+ variant: 'kag',
111
+ evidence,
112
+ title: path.basename(ctx.root),
113
+ archives,
114
+ scripts,
115
+ };
116
+ },
117
+
118
+ async open(ctx, detection) {
119
+ const archives = detection.archives ?? [];
120
+ const scripts = detection.scripts ?? (await walk(ctx, '.', ['.ks'], 2));
121
+ const containers = [
122
+ ...archives.map((rel) => ({ rel, kind: 'archive', textBearing: true, note: 'XP3' })),
123
+ ...scripts.map((rel) => ({ rel, kind: 'script', textBearing: true, note: '' })),
124
+ ];
125
+
126
+ return {
127
+ id: 'kirikiri',
128
+ meta() {
129
+ return {
130
+ title: detection.title || path.basename(ctx.root),
131
+ engine: 'KiriKiri / KAG',
132
+ variant: 'kag',
133
+ encrypted: false,
134
+ dataDir: '.',
135
+ archiveCount: archives.length,
136
+ scriptCount: scripts.length,
137
+ };
138
+ },
139
+ containers() {
140
+ return containers;
141
+ },
142
+ fingerprintFiles() {
143
+ return [...archives, ...scripts].slice(0, 3);
144
+ },
145
+
146
+ async *extract(options = {}) {
147
+ const shouldRead = typeof options.shouldRead === 'function' ? options.shouldRead : () => true;
148
+
149
+ for (const rel of scripts) {
150
+ if (!shouldRead(rel)) continue;
151
+ try {
152
+ const { text } = await ctx.readText(rel, 8 * 1024 * 1024);
153
+ yield* parseKagScript(text, { relPath: rel });
154
+ } catch (error) {
155
+ yield { type: 'error', relPath: rel, message: error.message };
156
+ }
157
+ }
158
+
159
+ for (const rel of archives) {
160
+ if (!shouldRead(rel)) continue;
161
+ let buffer;
162
+ try {
163
+ buffer = await ctx.readBuffer(rel, 1024 * 1024 * 1024);
164
+ } catch (error) {
165
+ yield { type: 'error', relPath: rel, message: error.message };
166
+ continue;
167
+ }
168
+ if (!isXp3(buffer)) {
169
+ yield { type: 'error', relPath: rel, message: '不是 XP3 归档(可能加密/定制)' };
170
+ continue;
171
+ }
172
+ let entries;
173
+ try {
174
+ entries = readXp3Index(buffer);
175
+ } catch (error) {
176
+ yield { type: 'error', relPath: rel, message: error.message };
177
+ continue;
178
+ }
179
+ for (const entry of entries) {
180
+ if (!/\.ks$/i.test(entry.name)) continue;
181
+ let content;
182
+ try {
183
+ content = readXp3Entry(buffer, entry);
184
+ } catch (error) {
185
+ yield { type: 'error', relPath: `${rel}!${entry.name}`, message: error.message };
186
+ continue;
187
+ }
188
+ const virtual = `${rel}!${entry.name}`;
189
+ yield* parseKagScript(content.toString('utf8'), { relPath: virtual });
190
+ }
191
+ }
192
+ },
193
+ };
194
+ },
195
+ };
196
+
197
+ export default kirikiri;
@@ -0,0 +1,219 @@
1
+ import path from 'node:path';
2
+
3
+ /** NScripter 常用命令白名单:命中则不当正文。 */
4
+ const COMMANDS = new Set([
5
+ 'game', 'mode', 'bg', 'ld', 'cl', 'csp', 'cell', 'print', 'ruby', 'textwindow', 'setwindow',
6
+ 'caption', 'monocro', 'dwave', 'play', 'stop', 'se', 'bgm', 'wait', 'click', 'delay',
7
+ 'erasetextwindow', 'line', 'br', 'windoweffect', 'quake', 'flash', 'trans', 'effect',
8
+ 'select', 'goto', 'jumpf', 'gosub', 'return', 'if', 'notif', 'for', 'next', 'break',
9
+ 'mov', 'add', 'sub', 'mul', 'div', 'mod', 'inc', 'dec', 'random', 'numalias', 'stralias',
10
+ 'defsub', 'getparam', 'itoa', 'atoi', 'itoa2', 'atoi2', 'skip', 'autosave', 'save', 'load',
11
+ 'resettimer', 'gettimer', 'fileexist', 'getversion', 'systemcall', 'nsa', 'arc', 'resume',
12
+ 'automode', 'btnwait', 'btndef', 'btntime', 'menuset', 'lookback', 'humanz', 'isskip',
13
+ 'isvolume', 'english', 'japanese', 'chinese', 'korean', 'setlayer', 'spriteset',
14
+ 'effect', 'blt', 'tablegoto', 'getspmode', 'spmode', 'bgmvol', 'sevol', 'voicevol',
15
+ 'movie', 'avi', 'mp3', 'wav', 'dll', 'nscom', 'rubyon', 'rubyoff', 'luasub',
16
+ ]);
17
+
18
+ /** nscript.dat 是逐字节 XOR 0x84 的 Shift-JIS 文本。 */
19
+ export function decodeNscript(buffer) {
20
+ const bytes = Buffer.from(buffer);
21
+ if (bytes.length === 0) return { text: '', encoding: 'utf-8' };
22
+ if (bytes[0] === (0x2a ^ 0x84)) {
23
+ for (let i = 0; i < bytes.length; i += 1) bytes[i] ^= 0x84;
24
+ return { text: bytes.toString('utf8'), encoding: 'ns-xor' };
25
+ }
26
+ return { text: bytes.toString('utf8'), encoding: 'plain' };
27
+ }
28
+
29
+ function isCommand(trimmed) {
30
+ const word = /^\\?([A-Za-z_]\w*)/.exec(trimmed)?.[1]?.toLowerCase();
31
+ if (!word) return false;
32
+ return COMMANDS.has(word);
33
+ }
34
+
35
+ function parseSelectOptions(raw) {
36
+ const parts = [];
37
+ let current = '';
38
+ let quoted = false;
39
+ for (const ch of raw) {
40
+ if (ch === '"') quoted = !quoted;
41
+ else if (ch === ',' && !quoted) {
42
+ parts.push(current.trim());
43
+ current = '';
44
+ continue;
45
+ }
46
+ if (ch !== '"') current += ch;
47
+ }
48
+ parts.push(current.trim());
49
+ const options = [];
50
+ for (let i = 0; i + 1 < parts.length; i += 2) {
51
+ const text = parts[i];
52
+ const target = parts[i + 1]?.replace(/^\*/, '') ?? null;
53
+ if (text) options.push({ id: options.length, text, targetLabel: target });
54
+ }
55
+ return options;
56
+ }
57
+
58
+ /** 解析 NScripter 脚本(nscript.dat / 0.txt)。 */
59
+ export function* parseNscripter(text, { relPath }) {
60
+ const lines = String(text).split(/\r?\n/);
61
+ let sceneKey = null;
62
+ let sceneOrder = 0;
63
+ let lineOrder = 0;
64
+
65
+ const ensureScene = function* () {
66
+ if (sceneKey) return;
67
+ sceneKey = `${relPath}#top`;
68
+ yield { type: 'scene', key: sceneKey, title: '开场', container: relPath, order: sceneOrder++, conditions: null, src: { relPath, path: 'top' } };
69
+ };
70
+
71
+ for (let index = 0; index < lines.length; index += 1) {
72
+ const raw = lines[index];
73
+ const trimmed = raw.trim();
74
+ if (!trimmed) continue;
75
+ if (trimmed.startsWith(';')) continue;
76
+ const src = { relPath, path: `line:${index + 1}`, index };
77
+
78
+ const label = /^\*([A-Za-z_][\w.-]*)\s*$/.exec(trimmed);
79
+ if (label) {
80
+ if (label[1].toLowerCase() === 'define') continue;
81
+ sceneKey = `${relPath}#label:${label[1]}`;
82
+ lineOrder = 0;
83
+ yield { type: 'scene', key: sceneKey, title: label[1], container: relPath, order: sceneOrder++, conditions: null, src };
84
+ continue;
85
+ }
86
+
87
+ const select = /^select\s+(.+)$/i.exec(trimmed);
88
+ if (select) {
89
+ yield* ensureScene();
90
+ yield { type: 'choice', sceneKey, order: lineOrder++, prompt: '', options: parseSelectOptions(select[1]), src };
91
+ continue;
92
+ }
93
+
94
+ const jump = /^(?:goto|jumpf)\s+\*?([A-Za-z_][\w.-]*)/i.exec(trimmed);
95
+ if (jump) {
96
+ yield* ensureScene();
97
+ yield { type: 'jump', sceneKey, label: jump[1], src };
98
+ continue;
99
+ }
100
+
101
+ if (isCommand(trimmed) || trimmed.startsWith('\\')) {
102
+ yield* ensureScene();
103
+ yield { type: 'skip', sceneKey, reason: 'ns-command', src };
104
+ continue;
105
+ }
106
+
107
+ const plain = trimmed
108
+ .replace(/\\n/g, ' ')
109
+ .replace(/\\[a-zA-Z~|!]/g, '')
110
+ .replace(/\\@[a-zA-Z0-9]+/g, '')
111
+ .trim();
112
+ if (!plain) continue;
113
+ const speaker = /^([^「」::]{1,16})[「::]\s*[「]?(.+?)[」]?$/.exec(plain);
114
+ yield* ensureScene();
115
+ yield {
116
+ type: 'line',
117
+ sceneKey,
118
+ order: lineOrder++,
119
+ kind: speaker ? 'dialogue' : 'narration',
120
+ speakerId: speaker ? `name:${speaker[1]}` : null,
121
+ speakerName: speaker ? speaker[1].trim() : null,
122
+ text: speaker ? speaker[2].trim() : plain,
123
+ refs: {},
124
+ src,
125
+ };
126
+ }
127
+ }
128
+
129
+ async function listScripts(ctx) {
130
+ const entries = await ctx.list('.');
131
+ const names = entries.filter((entry) => !entry.dir).map((entry) => entry.name);
132
+ const scripts = [];
133
+ if (names.includes('nscript.dat')) scripts.push('nscript.dat');
134
+ else {
135
+ for (const name of names) {
136
+ if (/^\d+\.txt$/i.test(name) || /\.nscript$/i.test(name)) scripts.push(name);
137
+ }
138
+ }
139
+ const archives = names.filter((name) => /\.nsa$/i.test(name));
140
+ return { scripts, archives };
141
+ }
142
+
143
+ export const nscripter = {
144
+ id: 'nscripter',
145
+ label: 'NScripter / ONScripter',
146
+
147
+ async detect(ctx) {
148
+ const { scripts, archives } = await listScripts(ctx);
149
+ const evidence = [];
150
+ let score = 0;
151
+ if (scripts.length) {
152
+ score = 0.9;
153
+ evidence.push(scripts.slice(0, 3).join(', '));
154
+ }
155
+ if (archives.length) {
156
+ score = Math.max(score, scripts.length ? score : 0.7);
157
+ evidence.push(`${archives.length} 个 .nsa`);
158
+ }
159
+ const entries = await ctx.list('.');
160
+ if (entries.some((entry) => /^(nscr|onscripter)/i.test(entry.name))) {
161
+ score = Math.max(score, 0.78);
162
+ evidence.push('NScripter 可执行文件');
163
+ }
164
+ if (score === 0) return null;
165
+ return {
166
+ engineId: 'nscripter',
167
+ label: 'NScripter / ONScripter',
168
+ confidence: score,
169
+ variant: 'ns',
170
+ evidence,
171
+ title: path.basename(ctx.root),
172
+ scripts,
173
+ archives,
174
+ };
175
+ },
176
+
177
+ async open(ctx, detection) {
178
+ const { scripts = [], archives = [] } = detection;
179
+ return {
180
+ id: 'nscripter',
181
+ meta() {
182
+ return {
183
+ title: detection.title || path.basename(ctx.root),
184
+ engine: 'NScripter',
185
+ variant: 'ns',
186
+ encrypted: false,
187
+ dataDir: '.',
188
+ scriptCount: scripts.length,
189
+ archiveCount: archives.length,
190
+ };
191
+ },
192
+ containers() {
193
+ return [
194
+ ...scripts.map((rel) => ({ rel, kind: 'script', textBearing: true, note: '' })),
195
+ ...archives.map((rel) => ({ rel, kind: 'archive', textBearing: false, note: '0.2.0 不解包 .nsa(通常为图片/音频)' })),
196
+ ];
197
+ },
198
+ fingerprintFiles() {
199
+ return scripts.slice(0, 2);
200
+ },
201
+
202
+ async *extract(options = {}) {
203
+ const shouldRead = typeof options.shouldRead === 'function' ? options.shouldRead : () => true;
204
+ for (const rel of scripts) {
205
+ if (!shouldRead(rel)) continue;
206
+ try {
207
+ const buffer = await ctx.readBuffer(rel, 64 * 1024 * 1024);
208
+ const { text } = decodeNscript(buffer);
209
+ yield* parseNscripter(text, { relPath: rel });
210
+ } catch (error) {
211
+ yield { type: 'error', relPath: rel, message: error.message };
212
+ }
213
+ }
214
+ },
215
+ };
216
+ },
217
+ };
218
+
219
+ export default nscripter;
@@ -1,8 +1,11 @@
1
1
  import { rpgmaker } from './rpgmaker.mjs';
2
2
  import { renpy } from './renpy.mjs';
3
3
  import { generic } from './generic.mjs';
4
+ import { kirikiri } from './kirikiri.mjs';
5
+ import { nscripter } from './nscripter.mjs';
6
+ import { wolf } from './wolf.mjs';
4
7
 
5
- export const ADAPTERS = [rpgmaker, renpy, generic];
8
+ export const ADAPTERS = [rpgmaker, renpy, kirikiri, nscripter, wolf, generic];
6
9
 
7
10
  export function getAdapter(id) {
8
11
  return ADAPTERS.find((adapter) => adapter.id === id) ?? null;
@@ -0,0 +1,155 @@
1
+ import path from 'node:path';
2
+
3
+ /**
4
+ * Wolf RPG Editor:0.2.0 做「检测 + 文本抢救」。
5
+ * Game.dat 常见加密(需 UberWolf 之类外部工具),本插件不破解;
6
+ * 这里只从 Data/*.dat、MapData/*.mps 里扫描可读文本段(UTF-16LE / UTF-8),
7
+ * 标为低置信,不进 canon 的默认导出范围。
8
+ */
9
+ function hasCjk(text) {
10
+ return /[\u3400-\u9fff\u3040-\u30ff\uac00-\ud7af]/.test(text);
11
+ }
12
+
13
+ function looksLikeText(value) {
14
+ const text = value.trim();
15
+ if (text.length < 4 || text.length > 200) return false;
16
+ const control = [...text].filter((ch) => {
17
+ const code = ch.codePointAt(0);
18
+ return code < 0x20 || (code > 0x7e && code < 0xa0);
19
+ }).length;
20
+ if (control / text.length > 0.1) return false;
21
+ if (hasCjk(text)) return true;
22
+ if (/[。!?…—「」『』]/.test(text)) return true;
23
+ return /^[A-Za-z][A-Za-z0-9 .,!?'"()\-]{10,}$/.test(text);
24
+ }
25
+
26
+ /** 从二进制里抢救可读文本段。 */
27
+ export function salvageText(buffer, { limit = 2000 } = {}) {
28
+ const found = [];
29
+ const seen = new Set();
30
+ const push = (value) => {
31
+ const text = value.replace(/\s+/g, ' ').trim();
32
+ if (!looksLikeText(text) || seen.has(text)) return;
33
+ seen.add(text);
34
+ found.push(text);
35
+ };
36
+
37
+ for (const raw of buffer.toString('utf16le').split(/[\u0000-\u001f]+/u)) push(raw);
38
+ for (const raw of buffer.toString('utf8').split(/[\u0000-\u0008\u000b-\u001f]+/u)) push(raw);
39
+
40
+ return found.slice(0, limit);
41
+ }
42
+
43
+ async function listDataFiles(ctx) {
44
+ const files = [];
45
+ const entries = await ctx.list('Data');
46
+ for (const entry of entries) {
47
+ if (entry.dir) {
48
+ for (const child of await ctx.list(entry.rel)) {
49
+ if (!child.dir && /\.(dat|mps|txt|json)$/i.test(child.name)) files.push(child.rel);
50
+ }
51
+ } else if (/\.(dat|mps|txt|json)$/i.test(entry.name)) {
52
+ files.push(entry.rel);
53
+ }
54
+ }
55
+ return files;
56
+ }
57
+
58
+ export const wolf = {
59
+ id: 'wolf',
60
+ label: 'Wolf RPG Editor',
61
+
62
+ async detect(ctx) {
63
+ const evidence = [];
64
+ let score = 0;
65
+ if (await ctx.exists('Data')) {
66
+ const files = await listDataFiles(ctx);
67
+ if (files.length) {
68
+ score = 0.74;
69
+ evidence.push(`Data/ 下 ${files.length} 个数据文件`);
70
+ }
71
+ }
72
+ for (const name of ['Data.wolf', 'Game.exe', 'WolfRPG.exe']) {
73
+ if (await ctx.exists(name)) {
74
+ score = Math.max(score, score ? score : 0.7);
75
+ evidence.push(name);
76
+ }
77
+ }
78
+ if (score === 0) return null;
79
+ return {
80
+ engineId: 'wolf',
81
+ label: 'Wolf RPG Editor',
82
+ confidence: score,
83
+ variant: 'wolf',
84
+ evidence,
85
+ title: path.basename(ctx.root),
86
+ salvage: true,
87
+ };
88
+ },
89
+
90
+ async open(ctx, detection) {
91
+ const files = await listDataFiles(ctx);
92
+ return {
93
+ id: 'wolf',
94
+ meta() {
95
+ return {
96
+ title: detection.title || path.basename(ctx.root),
97
+ engine: 'Wolf RPG Editor',
98
+ variant: 'wolf-salvage',
99
+ encrypted: false,
100
+ dataDir: 'Data',
101
+ fileCount: files.length,
102
+ };
103
+ },
104
+ containers() {
105
+ return files.map((rel) => ({ rel, kind: 'binary', textBearing: true, note: '文本抢救(低置信)' }));
106
+ },
107
+ fingerprintFiles() {
108
+ return files.slice(0, 3);
109
+ },
110
+
111
+ async *extract(options = {}) {
112
+ const shouldRead = typeof options.shouldRead === 'function' ? options.shouldRead : () => true;
113
+ let sceneOrder = 0;
114
+ for (const rel of files) {
115
+ if (!shouldRead(rel)) continue;
116
+ let buffer;
117
+ try {
118
+ buffer = await ctx.readBuffer(rel, 256 * 1024 * 1024);
119
+ } catch (error) {
120
+ yield { type: 'error', relPath: rel, message: error.message };
121
+ continue;
122
+ }
123
+ const texts = salvageText(buffer);
124
+ if (texts.length === 0) continue;
125
+ const sceneKey = `${rel}#salvage`;
126
+ yield {
127
+ type: 'scene',
128
+ key: sceneKey,
129
+ title: `${path.basename(rel)}(文本抢救)`,
130
+ container: rel,
131
+ order: sceneOrder++,
132
+ conditions: null,
133
+ lowConfidence: true,
134
+ src: { relPath: rel, path: 'salvage' },
135
+ };
136
+ for (let index = 0; index < texts.length; index += 1) {
137
+ yield {
138
+ type: 'line',
139
+ sceneKey,
140
+ order: index,
141
+ kind: 'narration',
142
+ speakerId: null,
143
+ speakerName: null,
144
+ text: texts[index],
145
+ refs: {},
146
+ src: { relPath: rel, path: `salvage:${index}`, index },
147
+ };
148
+ }
149
+ }
150
+ },
151
+ };
152
+ },
153
+ };
154
+
155
+ export default wolf;
@@ -0,0 +1,106 @@
1
+ import zlib from 'node:zlib';
2
+ import { GameError, ErrorCode } from '../core/errors.mjs';
3
+
4
+ export const XP3_MAGIC = Buffer.from([0x58, 0x50, 0x33, 0x0d, 0x0a, 0x20, 0x1a, 0x8b, 0x67, 0x01]);
5
+ const MAX_INDEX = 64 * 1024 * 1024;
6
+ const MAX_ENTRY = 64 * 1024 * 1024;
7
+
8
+ function readU64LE(buffer, offset) {
9
+ return Number(buffer.readBigUInt64LE(offset));
10
+ }
11
+
12
+ /** 判断是否 XP3 归档(KiriKiri / TVP)。 */
13
+ export function isXp3(buffer) {
14
+ return buffer.length >= XP3_MAGIC.length + 8 && buffer.subarray(0, XP3_MAGIC.length).equals(XP3_MAGIC);
15
+ }
16
+
17
+ /**
18
+ * 读取 XP3 索引。
19
+ * 索引在 header 之后由 u64 偏移指出;多数游戏是 zlib 压缩的 chunk 流,也有未压缩的。
20
+ * 返回 [{ name, offset, packedSize, unpackedSize }]。
21
+ */
22
+ export function readXp3Index(buffer, { maxEntries = 50000 } = {}) {
23
+ if (!isXp3(buffer)) throw new GameError(ErrorCode.PARSE_ERROR, '不是 XP3 归档');
24
+ const indexOffset = readU64LE(buffer, XP3_MAGIC.length);
25
+ if (indexOffset <= 0 || indexOffset >= buffer.length) {
26
+ throw new GameError(ErrorCode.PARSE_ERROR, `XP3 索引偏移非法:${indexOffset}`);
27
+ }
28
+ const raw = buffer.subarray(indexOffset);
29
+ let data;
30
+ try {
31
+ data = zlib.inflateSync(raw, { maxOutputLength: MAX_INDEX });
32
+ } catch {
33
+ data = raw; // 部分归档索引未压缩
34
+ }
35
+
36
+ const entries = [];
37
+ let pos = 0;
38
+ const CHUNK_HEADER = 12;
39
+ while (pos + CHUNK_HEADER <= data.length) {
40
+ const magic = data.readUInt32LE(pos);
41
+ const size = readU64LE(data, pos + 4);
42
+ pos += CHUNK_HEADER;
43
+ if (size < 0 || pos + size > data.length) break;
44
+ const payload = data.subarray(pos, pos + size);
45
+ pos += size;
46
+ if (magic !== 0x656c6946) continue; // 'File'
47
+ const entry = parseFileChunk(payload);
48
+ if (entry) {
49
+ entries.push(entry);
50
+ if (entries.length > maxEntries) throw new GameError(ErrorCode.PARSE_ERROR, 'XP3 条目超过上限');
51
+ }
52
+ }
53
+ return entries;
54
+ }
55
+
56
+ function parseFileChunk(payload) {
57
+ if (payload.length < 4) return null;
58
+ let cursor = 4; // flags
59
+ let name = null;
60
+ let offset = null;
61
+ let packedSize = null;
62
+ let unpackedSize = null;
63
+ while (cursor + 12 <= payload.length) {
64
+ const magic = payload.readUInt32LE(cursor);
65
+ const size = readU64LE(payload, cursor + 4);
66
+ cursor += 12;
67
+ if (size < 0 || cursor + size > payload.length) break;
68
+ const seg = payload.subarray(cursor, cursor + size);
69
+ cursor += size;
70
+ if (magic === 0x6f666e69) {
71
+ // 'info':u16 名称长度(字符)+ UTF-16LE 名称 + 文件大小
72
+ if (seg.length < 2) continue;
73
+ const nameLen = seg.readUInt16LE(0);
74
+ const byteLen = nameLen * 2;
75
+ if (2 + byteLen <= seg.length) {
76
+ name = seg.subarray(2, 2 + byteLen).toString('utf16le');
77
+ const rest = seg.subarray(2 + byteLen);
78
+ if (rest.length >= 8) unpackedSize = readU64LE(rest, 0);
79
+ else if (rest.length >= 4) unpackedSize = rest.readUInt32LE(0);
80
+ }
81
+ } else if (magic === 0x64617461) {
82
+ // 'data':offset u64 + packed u64 + unpacked u64
83
+ if (seg.length >= 24) {
84
+ offset = readU64LE(seg, 0);
85
+ packedSize = readU64LE(seg, 8);
86
+ unpackedSize = readU64LE(seg, 16);
87
+ }
88
+ }
89
+ }
90
+ if (!name || offset === null || packedSize === null) return null;
91
+ return { name, offset, packedSize, unpackedSize: unpackedSize ?? packedSize };
92
+ }
93
+
94
+ /** 读取并解压一个条目。packedSize === unpackedSize 时视为未压缩。 */
95
+ export function readXp3Entry(buffer, entry, { maxBytes = MAX_ENTRY } = {}) {
96
+ const begin = entry.offset;
97
+ const end = begin + entry.packedSize;
98
+ if (begin < 0 || end > buffer.length) throw new GameError(ErrorCode.PARSE_ERROR, `XP3 条目越界:${entry.name}`);
99
+ const slice = buffer.subarray(begin, end);
100
+ if (entry.packedSize === entry.unpackedSize) return slice;
101
+ try {
102
+ return zlib.inflateSync(slice, { maxOutputLength: maxBytes });
103
+ } catch (error) {
104
+ throw new GameError(ErrorCode.PARSE_ERROR, `XP3 条目解压失败:${entry.name}(${error.message})`);
105
+ }
106
+ }
package/lib/ingest.mjs CHANGED
@@ -152,6 +152,7 @@ export async function importGame({
152
152
  container: unit.container || path.basename(srcRel),
153
153
  order: unit.order ?? scenes.length,
154
154
  conditions: unit.conditions ?? null,
155
+ lowConfidence: unit.lowConfidence === true,
155
156
  src: unit.src,
156
157
  };
157
158
  scenes.push(scene);
@@ -49,6 +49,7 @@ export const DESCRIPTORS = [
49
49
  invocation('scenes', [param('options', jsonObjectSchema)]),
50
50
  invocation('scene', [param('options', jsonObjectSchema)]),
51
51
  invocation('search', [param('options', jsonObjectSchema)]),
52
+ invocation('routes', [param('options', jsonObjectSchema)]),
52
53
  invocation('characters', [param('options', jsonObjectSchema)]),
53
54
  invocation('glossary', [param('options', jsonObjectSchema)]),
54
55
  invocation('picks', [param('options', jsonObjectSchema)]),
package/lib/remote.js CHANGED
@@ -108,6 +108,10 @@ class GamePanelRemote extends TypertRemoteService {
108
108
  return (await this.service(id)).characters(String(options.gameId ?? ''));
109
109
  }
110
110
 
111
+ async routes(id, options = {}) {
112
+ return (await this.service(id)).routes(String(options.gameId ?? ''));
113
+ }
114
+
111
115
  async glossary(id, options = {}) {
112
116
  return (await this.service(id)).glossary(String(options.gameId ?? ''), {
113
117
  kind: options.kind ? String(options.kind) : undefined,
package/lib/service.mjs CHANGED
@@ -146,11 +146,15 @@ export class GameService {
146
146
 
147
147
  visibleScenes(scenes, settings) {
148
148
  const spoiler = settings?.spoiler ?? {};
149
+ let visible = scenes;
150
+ if (!settings?.includeLowConfidence) {
151
+ visible = visible.filter((scene) => scene.lowConfidence !== true);
152
+ }
149
153
  if (spoiler.mode === 'scene' && Number.isFinite(Number(spoiler.maxSceneOrder))) {
150
154
  const max = Number(spoiler.maxSceneOrder);
151
- return scenes.filter((scene) => (scene.seq ?? 0) <= max);
155
+ visible = visible.filter((scene) => (scene.seq ?? 0) <= max);
152
156
  }
153
- return scenes;
157
+ return visible;
154
158
  }
155
159
 
156
160
  async sceneCounts(gameId, genId) {
@@ -346,7 +350,70 @@ export class GameService {
346
350
 
347
351
  async picks(gameId) {
348
352
  const rows = await this.store.readPicks(gameId);
349
- return { gameId, total: rows.length, items: rows };
353
+ const { genId } = await this.active(gameId);
354
+ const lineIds = new Set();
355
+ for await (const row of this.store.iterateShards(gameId, genId)) {
356
+ if (row.t === 'line') lineIds.add(row.lineId);
357
+ }
358
+ const items = rows.map((row) => ({
359
+ ...row,
360
+ stale: row.kind === 'line' ? !lineIds.has(row.refId) : false,
361
+ }));
362
+ return { gameId, total: items.length, items, staleCount: items.filter((row) => row.stale).length };
363
+ }
364
+
365
+ /**
366
+ * 剧情路线图:场景为节点,选项/跳转为边,标签解析为场景;未解析的边保留 resolved=false。
367
+ * 注意:这是静态可达图,不是实际游玩顺序(不模拟开关/变量)。
368
+ */
369
+ async routes(gameId) {
370
+ const { manifest, genId, scenes, choices } = await this.active(gameId);
371
+ const settings = await this.store.readSettings();
372
+ const visible = this.visibleScenes(scenes, settings);
373
+ const visibleIds = new Set(visible.map((scene) => scene.sceneId));
374
+ const labels = new Map();
375
+ const jumps = [];
376
+ for await (const row of this.store.iterateShards(gameId, genId)) {
377
+ if (row.t === 'label' && visibleIds.has(row.sceneId)) labels.set(row.label, row.sceneId);
378
+ if (row.t === 'jump' && visibleIds.has(row.sceneId)) jumps.push(row);
379
+ }
380
+ const counts = await this.sceneCounts(gameId, genId);
381
+ const nodes = visible.map((scene) => ({
382
+ sceneId: scene.sceneId,
383
+ seq: scene.seq ?? 0,
384
+ title: scene.title,
385
+ lowConfidence: scene.lowConfidence === true,
386
+ lineCount: counts.get(scene.sceneId)?.lines ?? 0,
387
+ }));
388
+ const edges = [];
389
+ for (const choice of choices) {
390
+ if (!visibleIds.has(choice.sceneId)) continue;
391
+ for (const option of choice.options ?? []) {
392
+ const target = option.targetLabel ? labels.get(option.targetLabel) ?? null : null;
393
+ edges.push({
394
+ from: choice.sceneId,
395
+ to: target,
396
+ kind: 'choice',
397
+ label: option.text,
398
+ targetLabel: option.targetLabel ?? null,
399
+ resolved: Boolean(target),
400
+ });
401
+ }
402
+ }
403
+ for (const jump of jumps) {
404
+ const target = labels.get(jump.label) ?? null;
405
+ edges.push({ from: jump.sceneId, to: target, kind: 'jump', label: jump.label, targetLabel: jump.label, resolved: Boolean(target) });
406
+ }
407
+ const outgoing = new Set(edges.filter((edge) => edge.resolved).map((edge) => edge.from));
408
+ return {
409
+ gameId,
410
+ generation: manifest.activeGeneration,
411
+ nodes,
412
+ edges,
413
+ endings: nodes.filter((node) => !outgoing.has(node.sceneId)).map((node) => node.sceneId),
414
+ unresolved: edges.filter((edge) => !edge.resolved).length,
415
+ note: '静态可达图,不模拟开关/变量;未解析边不代表没有后续。',
416
+ };
350
417
  }
351
418
 
352
419
  async export(gameId, { formats = ['story', 'canon', 'brief'] } = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-novel-game",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "DSH 小说插件·游戏剧情:解包本地合法游戏副本中玩家可见的剧情/文本/设定,整理成可浏览、可检索、可摘录的 canon,供同人创作参考;只写 .dsh-novel-game/,游戏目录只读。",
5
5
  "type": "module",
6
6
  "main": "index.js",