@liminalia/runtime 0.0.0-stage → 0.8.4
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/LICENSE +106 -0
- package/dist/src/chat.js +60 -0
- package/dist/src/commands-play.js +300 -0
- package/dist/src/commands.js +534 -0
- package/dist/src/coverage.js +208 -0
- package/dist/src/headless.js +109 -0
- package/dist/src/host.js +1 -0
- package/dist/src/index.js +15 -0
- package/dist/src/prefetch.js +80 -0
- package/dist/src/program.js +131 -0
- package/dist/src/project-options.js +84 -0
- package/dist/src/retranslate.js +44 -0
- package/dist/src/route.js +242 -0
- package/dist/src/runtime.js +1929 -0
- package/dist/src/save.js +51 -0
- package/dist/src/scenario-test.js +200 -0
- package/dist/src/state.js +62 -0
- package/dist/src/value.js +464 -0
- package/dist/src/voice-observe.js +82 -0
- package/package.json +33 -4
- package/src/chat.ts +109 -0
- package/src/commands-play.ts +280 -0
- package/src/commands.ts +457 -0
- package/src/coverage.ts +257 -0
- package/src/headless.ts +139 -0
- package/src/host.ts +116 -0
- package/src/index.ts +16 -0
- package/src/prefetch.ts +78 -0
- package/src/program.ts +186 -0
- package/src/project-options.ts +128 -0
- package/src/retranslate.ts +67 -0
- package/src/route.ts +365 -0
- package/src/runtime.ts +2143 -0
- package/src/save.ts +60 -0
- package/src/scenario-test.ts +218 -0
- package/src/state.ts +353 -0
- package/src/value.ts +443 -0
- package/src/voice-observe.ts +85 -0
- package/types/src/chat.d.ts +63 -0
- package/types/src/commands-play.d.ts +2 -0
- package/types/src/commands.d.ts +2 -0
- package/types/src/coverage.d.ts +100 -0
- package/types/src/headless.d.ts +77 -0
- package/types/src/host.d.ts +140 -0
- package/types/src/index.d.ts +16 -0
- package/types/src/prefetch.d.ts +18 -0
- package/types/src/program.d.ts +107 -0
- package/types/src/project-options.d.ts +103 -0
- package/types/src/retranslate.d.ts +39 -0
- package/types/src/route.d.ts +181 -0
- package/types/src/runtime.d.ts +553 -0
- package/types/src/save.d.ts +21 -0
- package/types/src/scenario-test.d.ts +43 -0
- package/types/src/state.d.ts +357 -0
- package/types/src/value.d.ts +61 -0
- package/types/src/voice-observe.d.ts +26 -0
- package/README.md +0 -3
package/src/coverage.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { parse, type Diagnostic, type Statement } from "@liminalia/lang";
|
|
2
|
+
import type { RunResult, RuntimeOptions } from "./runtime.ts";
|
|
3
|
+
import { explore } from "./route.ts";
|
|
4
|
+
|
|
5
|
+
/** ファイルごとに流す回数の上限の既定(lim coverage --runs、制作画面の全ルートテスト)。選び方を試し終えれば、上限より前に止める。 */
|
|
6
|
+
export const DEFAULT_COVERAGE_RUNS = 8;
|
|
7
|
+
|
|
8
|
+
export interface CoverageOptions {
|
|
9
|
+
/** 流すファイル(拡張子なし)。 */
|
|
10
|
+
files: readonly string[];
|
|
11
|
+
loadSource(file: string): Promise<string>;
|
|
12
|
+
/** 実行器の設定。onAssign は使わない(流し方が使う)。onStep は通った命令ごとに呼ぶ。 */
|
|
13
|
+
runtime?: RuntimeOptions;
|
|
14
|
+
/** ファイルごとに流す回数の上限。既定 DEFAULT_COVERAGE_RUNS。選び方をすべて試し終えたら、上限より前に止める。 */
|
|
15
|
+
runs?: number;
|
|
16
|
+
/** 乱数の種(random の結果)。種ごとに runs 回まで流す。既定 [1]。 */
|
|
17
|
+
seeds?: readonly number[];
|
|
18
|
+
/**
|
|
19
|
+
* プラグインの命令が教えた行き先("ファイル:行" → 飛び先。@liminalia/lang の promisedTargets)。
|
|
20
|
+
* 通った命令の行き先のうち、画面なしで一度も選択肢(ctx.choose・ctx.pick)に出なかったものを警告にする。
|
|
21
|
+
*/
|
|
22
|
+
promised?: ReadonlyMap<string, readonly string[]>;
|
|
23
|
+
/** 一回流し終えるたびに呼ぶ(done は流し終えた回数、total は全部の回数、file はいま流したファイル)。制作画面の経過の表示。 */
|
|
24
|
+
onProgress?(p: { done: number; total: number; file: string }): void;
|
|
25
|
+
/** 止める合図(止めたら、そこまでの分を返す)。 */
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface CoverageReport {
|
|
30
|
+
/** complete は、そのファイルの選び方をすべて試したか(false なら runs の上限か止める合図で打ち切った)。 */
|
|
31
|
+
files: { file: string; /** 本文の行。 */ lines: number[]; /** 通った本文の行。 */ reached: Set<number>; complete: boolean }[];
|
|
32
|
+
/** 実行時の診断(同じものはまとめて、出た回数を数える)。 */
|
|
33
|
+
diagnostics: { diagnostic: Diagnostic; count: number }[];
|
|
34
|
+
/** 実行の終わり方("end"・"error"・"別ファイルへ" など)→ 回数。前に通った状態に合流して止めた回は数えない。 */
|
|
35
|
+
endings: Map<string, number>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 実行器の設定から、流し方が使うもの(onStep・onAssign)を外す。 */
|
|
39
|
+
function runtimeFor(o: RuntimeOptions | undefined, seed: number, defaults: Partial<RuntimeOptions>): Omit<RuntimeOptions, "onAssign" | "onStep"> {
|
|
40
|
+
const { onStep: _onStep, onAssign: _onAssign, ...rest } = o ?? {};
|
|
41
|
+
return { onError: "continue", ...defaults, ...rest, seed };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 一回分の診断を、同じものをまとめて数える控えに足す。 */
|
|
45
|
+
function addDiagnostics(into: Map<string, { diagnostic: Diagnostic; count: number }>, found: readonly Diagnostic[]): void {
|
|
46
|
+
for (const d of found) {
|
|
47
|
+
const key = `${d.code} ${d.file}:${d.line} ${d.message}`;
|
|
48
|
+
const seen = into.get(key);
|
|
49
|
+
if (seen) seen.count++;
|
|
50
|
+
else into.set(key, { diagnostic: d, count: 1 });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 全ファイルを画面なしで、選択肢の選び方を変えながら何通りか流し、本文の網羅と実行時の診断を集める(lim coverage・制作画面の全ルートテスト)。
|
|
56
|
+
* ファイルごとに先頭から、まだ試していない選び方へ広げながら(route.ts の explore)runs 回まで流す。選び方をすべて試し終えたら、そこで止める。
|
|
57
|
+
* 別のファイルへ移ったら、そのファイルの網羅はそのファイル自身の実行に任せて打ち切る。
|
|
58
|
+
* random は種で決まるので、種を変えないと同じ分かれ方しか通らない。seeds を複数渡すと種ごとに流し直す。
|
|
59
|
+
* promised があれば、通った命令が教えた行き先のうち選択肢に一度も出なかったものを "target-never-offered" の警告にする
|
|
60
|
+
* (画面なしの選び方に入れ忘れた行き先は、網羅でも道筋の探索でも通れないため)。
|
|
61
|
+
*/
|
|
62
|
+
export async function coverage(o: CoverageOptions): Promise<CoverageReport> {
|
|
63
|
+
const runs = o.runs ?? DEFAULT_COVERAGE_RUNS;
|
|
64
|
+
const seeds = o.seeds?.length ? o.seeds : [1];
|
|
65
|
+
const speakers = o.runtime?.speakers ?? [];
|
|
66
|
+
const files: CoverageReport["files"] = [];
|
|
67
|
+
for (const f of o.files) {
|
|
68
|
+
const lines = new Set<number>();
|
|
69
|
+
const walk = (body: Statement[]) => {
|
|
70
|
+
for (const s of body) {
|
|
71
|
+
if (s.kind === "say" || s.kind === "prose") lines.add(s.line);
|
|
72
|
+
if (s.kind === "if") for (const b of s.branches) walk(b.body);
|
|
73
|
+
if (s.kind === "define") walk(s.body);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const script = parse(await o.loadSource(f), f, { speakers });
|
|
77
|
+
// 下書き(// lim: draft)は遊ぶ人に届かないので、流さず、網羅率にも数えない
|
|
78
|
+
if (script.draft) continue;
|
|
79
|
+
walk(script.body);
|
|
80
|
+
files.push({ file: f, lines: [...lines].sort((a, b) => a - b), reached: new Set(), complete: true });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const diagnostics = new Map<string, { diagnostic: Diagnostic; count: number }>();
|
|
84
|
+
const endings = new Map<string, number>();
|
|
85
|
+
/** 通った命令の行("ファイル:行")と、そこで選択肢に出た飛び先。 */
|
|
86
|
+
const visited = new Set<string>();
|
|
87
|
+
const offered = new Map<string, Set<string>>();
|
|
88
|
+
const total = files.length * seeds.length * runs;
|
|
89
|
+
let done = 0;
|
|
90
|
+
const onStep = o.runtime?.onStep;
|
|
91
|
+
for (const entry of files) {
|
|
92
|
+
const f = entry.file;
|
|
93
|
+
for (const seed of seeds) {
|
|
94
|
+
if (o.signal?.aborted) break;
|
|
95
|
+
let left = false;
|
|
96
|
+
let found: Diagnostic[] = [];
|
|
97
|
+
const explored = await explore({
|
|
98
|
+
start: f,
|
|
99
|
+
runs,
|
|
100
|
+
...(o.signal ? { signal: o.signal } : {}),
|
|
101
|
+
loadSource: (file) => o.loadSource(file),
|
|
102
|
+
// @call で呼ぶだけのファイルも先頭から流すので、呼ばれていない @return は誤りにせずに次の行へ進む(ラベルごとの続きも網羅に数える)
|
|
103
|
+
runtime: { ...runtimeFor(o.runtime, seed, { maxSteps: 200_000 }), returnWithoutCall: "continue" },
|
|
104
|
+
...(o.promised || onStep
|
|
105
|
+
? {
|
|
106
|
+
step: (at: { file: string; line: number }) => {
|
|
107
|
+
visited.add(`${at.file}:${at.line}`);
|
|
108
|
+
onStep?.(at);
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
: {}),
|
|
112
|
+
present: (e, w) => {
|
|
113
|
+
if (e.type !== "page") return;
|
|
114
|
+
if (e.at.file !== f) {
|
|
115
|
+
left = true;
|
|
116
|
+
w.runtime.stop();
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
entry.reached.add(e.at.line);
|
|
120
|
+
},
|
|
121
|
+
choice: (at, _options, _w, targets) => {
|
|
122
|
+
const site = `${at.file}:${at.line}`;
|
|
123
|
+
if (!o.promised?.has(site)) return;
|
|
124
|
+
const seen = offered.get(site) ?? new Set<string>();
|
|
125
|
+
for (const t of targets ?? []) if (t) seen.add(t);
|
|
126
|
+
offered.set(site, seen);
|
|
127
|
+
},
|
|
128
|
+
onDiagnostic: (d) => found.push(d),
|
|
129
|
+
begin: () => {
|
|
130
|
+
left = false;
|
|
131
|
+
found = [];
|
|
132
|
+
},
|
|
133
|
+
ran: async ({ result, merged }: { result: RunResult; merged: boolean }) => {
|
|
134
|
+
if (!merged) {
|
|
135
|
+
const ending = left ? "別ファイルへ" : result.reason;
|
|
136
|
+
endings.set(ending, (endings.get(ending) ?? 0) + 1);
|
|
137
|
+
}
|
|
138
|
+
addDiagnostics(diagnostics, found);
|
|
139
|
+
if (o.onProgress) {
|
|
140
|
+
o.onProgress({ done: ++done, total, file: f });
|
|
141
|
+
// 経過を画面へ流し、ほかの頼みにも答えられるよう、一回ごとに手を離す
|
|
142
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
if (!explored.complete) entry.complete = false;
|
|
147
|
+
// 早く試し終えた分も、経過は上限の回数まで進める
|
|
148
|
+
done += runs - explored.runs;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
for (const [site, targets] of o.promised ?? []) {
|
|
152
|
+
if (!visited.has(site)) continue;
|
|
153
|
+
const seen = offered.get(site);
|
|
154
|
+
const missing = targets.filter((t) => !seen?.has(t));
|
|
155
|
+
if (missing.length === 0) continue;
|
|
156
|
+
const at = site.lastIndexOf(":");
|
|
157
|
+
const diagnostic: Diagnostic = {
|
|
158
|
+
severity: "warning",
|
|
159
|
+
code: "target-never-offered",
|
|
160
|
+
message: `命令が教えた行き先 ${missing.join("・")} が、画面なしで流したとき一度も選択肢に出ませんでした(全ルートテストでもルートの探索でも通れません)`,
|
|
161
|
+
file: site.slice(0, at),
|
|
162
|
+
line: Number(site.slice(at + 1)),
|
|
163
|
+
hint: "この命令の run で、描画側が答えを返さないときに選ぶ一覧(ctx.pick か ctx.choose)にこの行き先を入れてください。targets と同じ一覧から作ると漏れません",
|
|
164
|
+
};
|
|
165
|
+
diagnostics.set(`${diagnostic.code} ${site}`, { diagnostic, count: 1 });
|
|
166
|
+
}
|
|
167
|
+
return { files, diagnostics: [...diagnostics.values()], endings };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export interface RouteCoverageOptions {
|
|
171
|
+
/** 「はじめから」の位置(`ファイル` か `ファイル#ラベル`。liminalia.json の entry)。 */
|
|
172
|
+
entry: string;
|
|
173
|
+
loadSource(file: string): Promise<string>;
|
|
174
|
+
/** 実行器の設定。onAssign は使わない(流し方が使う)。onStep は通った命令ごとに呼ぶ。 */
|
|
175
|
+
runtime?: RuntimeOptions;
|
|
176
|
+
/** 流す回数の上限。既定 8。選び方をすべて試し終えたら、上限より前に止める。 */
|
|
177
|
+
runs?: number;
|
|
178
|
+
seeds?: readonly number[];
|
|
179
|
+
/**
|
|
180
|
+
* プレイを終える命令の行("ファイル:行" → エンディングの名前。@title-screen ending= など)。そこに来たら、その実行はそのエンディングに届いたとして止める。
|
|
181
|
+
*/
|
|
182
|
+
endings?: ReadonlyMap<string, string>;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export interface RouteCoverageReport {
|
|
186
|
+
/** ファイル → 通った本文の行(ファイルをまたいで流したもの)。 */
|
|
187
|
+
reached: Map<string, Set<number>>;
|
|
188
|
+
/** 届いた終わり方(名前 → 回数)。プレイを終える命令で止まらなかったものは "ファイルの終わり(file:行)" などの名前。 */
|
|
189
|
+
endings: Map<string, number>;
|
|
190
|
+
/**
|
|
191
|
+
* 実行ごとの終わり方と、選んだ選択肢の数。merged は、前に通ったのと同じ状態の選択肢に来たので、その先を流さずに止めた回
|
|
192
|
+
* (ending は止めた場所の名前で、endings には数えない)。
|
|
193
|
+
*/
|
|
194
|
+
runs: { seed: number; run: number; ending: string; choices: number; at: { file: string; line: number } | null; merged?: true }[];
|
|
195
|
+
/** 選び方をすべて試したか(false なら runs の上限で打ち切った。種のどれかで打ち切れば false)。 */
|
|
196
|
+
complete: boolean;
|
|
197
|
+
diagnostics: { diagnostic: Diagnostic; count: number }[];
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* 「はじめから」の位置から、ファイルをまたいで最後まで流す(lim coverage のルートの網羅)。ほかのファイルで決めた変数を引き継いだまま進むので、
|
|
202
|
+
* 前の章の選択で分かれる先も通る。選び方は、まだ試していないものへ広げていく(coverage と同じ。route.ts の explore)。
|
|
203
|
+
* プレイを終える命令(endings)に来たら、そのエンディングに届いたとして止める。
|
|
204
|
+
*/
|
|
205
|
+
export async function routeCoverage(o: RouteCoverageOptions): Promise<RouteCoverageReport> {
|
|
206
|
+
const runs = o.runs ?? 8;
|
|
207
|
+
const seeds = o.seeds?.length ? o.seeds : [1];
|
|
208
|
+
const reached = new Map<string, Set<number>>();
|
|
209
|
+
const endings = new Map<string, number>();
|
|
210
|
+
const diagnostics = new Map<string, { diagnostic: Diagnostic; count: number }>();
|
|
211
|
+
const out: RouteCoverageReport["runs"] = [];
|
|
212
|
+
let complete = true;
|
|
213
|
+
const onStep = o.runtime?.onStep;
|
|
214
|
+
for (const seed of seeds) {
|
|
215
|
+
let ending: string | null = null;
|
|
216
|
+
let last: { file: string; line: number } | null = null;
|
|
217
|
+
let found: Diagnostic[] = [];
|
|
218
|
+
const explored = await explore({
|
|
219
|
+
start: o.entry,
|
|
220
|
+
runs,
|
|
221
|
+
loadSource: (file) => o.loadSource(file),
|
|
222
|
+
runtime: runtimeFor(o.runtime, seed, { maxSteps: 400_000 }),
|
|
223
|
+
step: (at, w) => {
|
|
224
|
+
last = at;
|
|
225
|
+
const name = o.endings?.get(`${at.file}:${at.line}`);
|
|
226
|
+
if (name !== undefined && ending === null) {
|
|
227
|
+
ending = name;
|
|
228
|
+
w.runtime.stop();
|
|
229
|
+
}
|
|
230
|
+
onStep?.(at);
|
|
231
|
+
},
|
|
232
|
+
present: (e) => {
|
|
233
|
+
if (e.type !== "page") return;
|
|
234
|
+
const set = reached.get(e.at.file) ?? new Set<number>();
|
|
235
|
+
set.add(e.at.line);
|
|
236
|
+
reached.set(e.at.file, set);
|
|
237
|
+
},
|
|
238
|
+
onDiagnostic: (d) => found.push(d),
|
|
239
|
+
begin: () => {
|
|
240
|
+
ending = null;
|
|
241
|
+
last = null;
|
|
242
|
+
found = [];
|
|
243
|
+
},
|
|
244
|
+
ran: ({ index, result, walk, merged }) => {
|
|
245
|
+
const at = last as { file: string; line: number } | null;
|
|
246
|
+
const where = at ? `${at.file}:${at.line}` : o.entry;
|
|
247
|
+
const reason = ending as string | null;
|
|
248
|
+
const name = reason ?? (result.reason === "end" ? `ファイルの終わり(${where})` : result.reason === "max-steps" ? `終わらない(${where} で手数の上限)` : result.reason === "error" ? `エラーで止まった(${where})` : `止まった(${where})`);
|
|
249
|
+
if (!merged) endings.set(name, (endings.get(name) ?? 0) + 1);
|
|
250
|
+
out.push({ seed, run: index, ending: name, choices: walk.choices.length, at, ...(merged ? { merged: true as const } : {}) });
|
|
251
|
+
addDiagnostics(diagnostics, found);
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
if (!explored.complete) complete = false;
|
|
255
|
+
}
|
|
256
|
+
return { reached, endings, runs: out, complete, diagnostics: [...diagnostics.values()] };
|
|
257
|
+
}
|
package/src/headless.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { Diagnostic } from "@liminalia/lang";
|
|
2
|
+
import type { ChoiceLook, Host, PresentEvent } from "./host.ts";
|
|
3
|
+
import type { Value } from "./value.ts";
|
|
4
|
+
|
|
5
|
+
export type TraceEntry =
|
|
6
|
+
/** label は名前欄に出す名前(訳か表示名の上書き。話者と同じなら無い)。 */
|
|
7
|
+
| { type: "page"; file: string; line: number; speaker: string | null; label?: string; text: string; voice?: string }
|
|
8
|
+
| { type: "command"; name: string; args: Record<string, Value> }
|
|
9
|
+
| { type: "choice"; options: string[]; selected: number | null }
|
|
10
|
+
| { type: "diagnostic"; diagnostic: Diagnostic };
|
|
11
|
+
|
|
12
|
+
export interface HeadlessOptions {
|
|
13
|
+
loadSource(file: string): Promise<string>;
|
|
14
|
+
/** 作品のデータ(paths.data の .json)を読む(命令の ctx.data)。無ければ命令はデータを読めない。 */
|
|
15
|
+
loadData?(name: string): Promise<unknown>;
|
|
16
|
+
/**
|
|
17
|
+
* 選択肢で選ぶものを順に。数は番号(0 始まり)、文字は選択肢の文(同じ文か、その文を含む選択肢)。使い切ったら policy に従う。
|
|
18
|
+
* 文に当たる選択肢が無ければ診断(unknown-option)を残して policy に従う。
|
|
19
|
+
*/
|
|
20
|
+
choices?: (number | string)[];
|
|
21
|
+
/** 選ぶ番号を使い切ったとき。既定は "first"(最初の選択肢)。 */
|
|
22
|
+
/**
|
|
23
|
+
* 選ぶ番号を使い切ったとき。既定は "rotate"(同じ選択肢に戻ってくるたびに次の選択肢を選ぶ。
|
|
24
|
+
* 外れを選ぶと選択肢に戻る作りでも、いずれ全部を試して先へ進める)。
|
|
25
|
+
*/
|
|
26
|
+
whenChoicesRunOut?: "rotate" | "first" | "stop";
|
|
27
|
+
/** このページ数に達したら止める。 */
|
|
28
|
+
maxPages?: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 画面なしで実行する Host。待ちはすべて即座に終わり、出来事を trace に記録する。
|
|
33
|
+
* テスト・CLI の trace・AI による動作確認に使う。
|
|
34
|
+
*/
|
|
35
|
+
export class HeadlessHost implements Host {
|
|
36
|
+
/**
|
|
37
|
+
* 人が操作せずに流すので、命令の autoplay の答えで進める(Host.automated)。描画側の代わりに答えを返すテスト
|
|
38
|
+
* (present を差し替えて、遊ぶ人の操作を真似る)は false にする。
|
|
39
|
+
*/
|
|
40
|
+
automated = true;
|
|
41
|
+
readonly trace: TraceEntry[] = [];
|
|
42
|
+
private page: Extract<TraceEntry, { type: "page" }> | null = null;
|
|
43
|
+
private pages = 0;
|
|
44
|
+
private readonly choices: (number | string)[];
|
|
45
|
+
private readonly seenChoices = new Map<string, number>();
|
|
46
|
+
/** 選択肢(場所と文)ごとの、前に出たときのページの数と、ページを挟まずに続けて出た回数(選択肢だけの輪を見つける)。 */
|
|
47
|
+
private readonly choiceLoops = new Map<string, { pages: number; repeats: number }>();
|
|
48
|
+
onLimit: (() => void) | null = null;
|
|
49
|
+
/** 今の場所(実行器の at)。選択肢の輪と、選ぶ選択肢が無いときの診断に、選択肢のある行を入れる(無ければ場所なし)。 */
|
|
50
|
+
where: (() => { file: string; line: number } | null) | null = null;
|
|
51
|
+
|
|
52
|
+
constructor(private readonly options: HeadlessOptions) {
|
|
53
|
+
this.choices = [...(options.choices ?? [])];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
loadSource(file: string): Promise<string> {
|
|
57
|
+
return this.options.loadSource(file);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
loadData(name: string): Promise<unknown> {
|
|
61
|
+
return this.options.loadData ? this.options.loadData(name) : Promise.resolve(undefined);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async present(event: PresentEvent): Promise<Value | void> {
|
|
65
|
+
switch (event.type) {
|
|
66
|
+
case "page":
|
|
67
|
+
this.page = { type: "page", file: event.at.file, line: event.at.line, speaker: event.speaker, ...(event.label ? { label: event.label } : {}), text: "", ...(event.voice ? { voice: `${event.voice.folder}/${event.voice.file}` } : {}) };
|
|
68
|
+
this.trace.push(this.page);
|
|
69
|
+
if (++this.pages >= (this.options.maxPages ?? Infinity)) this.onLimit?.();
|
|
70
|
+
break;
|
|
71
|
+
case "text":
|
|
72
|
+
if (this.page) this.page.text += event.text;
|
|
73
|
+
break;
|
|
74
|
+
case "br":
|
|
75
|
+
if (this.page) this.page.text += "\n";
|
|
76
|
+
break;
|
|
77
|
+
case "command":
|
|
78
|
+
this.trace.push({ type: "command", name: event.name, args: event.args });
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async waitClick(): Promise<void> {}
|
|
84
|
+
|
|
85
|
+
/** 診断の場所(where が無ければ場所なし)。 */
|
|
86
|
+
private place(): { file: string; line: number } {
|
|
87
|
+
const at = this.where?.() ?? null;
|
|
88
|
+
return at ? { file: at.file, line: at.line } : { file: "", line: 0 };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async choose(texts: string[], _signal?: AbortSignal, looks?: (ChoiceLook | null)[]): Promise<number | null> {
|
|
92
|
+
// 画像のボタン・押せる範囲で文のないものは、画像の名前で記録する。
|
|
93
|
+
const options = texts.map((t, i) => t || looks?.[i]?.image || t);
|
|
94
|
+
const key = options.join("\u0000");
|
|
95
|
+
// 本文を出さずに同じ選択肢へ戻り続ける輪(どれを選んでも本文の無い選択肢へ戻る)。選び方を一巡しても抜けなければ止める
|
|
96
|
+
// (止めないと実行器の手数の上限まで記録が膨らむ)
|
|
97
|
+
// 同じ文でも台本の別の場所の選択肢は別に数える(「次へ」だけのメニューを続けて並べた作りを輪と見ない)
|
|
98
|
+
const at = this.where?.();
|
|
99
|
+
const loopKey = at ? `${at.file}:${at.line}\u0000${key}` : key;
|
|
100
|
+
const loop = this.choiceLoops.get(loopKey);
|
|
101
|
+
const repeats = loop && loop.pages === this.pages ? loop.repeats + 1 : 0;
|
|
102
|
+
this.choiceLoops.set(loopKey, { pages: this.pages, repeats });
|
|
103
|
+
if (repeats > Math.max(2, options.length * 2)) {
|
|
104
|
+
this.trace.push({ type: "choice", options, selected: null });
|
|
105
|
+
this.trace.push({
|
|
106
|
+
type: "diagnostic",
|
|
107
|
+
diagnostic: { severity: "warning", code: "choice-loop", message: `選択肢「${options.join(" / ")}」に、本文を挟まずに ${repeats} 回続けて戻ったため止めました(どれを選んでも本文の無い選択肢へ戻ります)`, ...this.place(), hint: "抜ける選択肢を足すか、--choose で選ぶものを決めます" },
|
|
108
|
+
});
|
|
109
|
+
this.onLimit?.();
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
let next = this.choices.shift();
|
|
113
|
+
if (typeof next === "string") {
|
|
114
|
+
const text = next;
|
|
115
|
+
const exact = options.indexOf(text);
|
|
116
|
+
next = exact >= 0 ? exact : options.findIndex((o) => o.includes(text));
|
|
117
|
+
if (next < 0) {
|
|
118
|
+
this.trace.push({ type: "diagnostic", diagnostic: { severity: "warning", code: "unknown-option", message: `選ぶ選択肢「${text}」がありません(${options.join(" / ")})`, ...this.place() } });
|
|
119
|
+
next = undefined;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const policy = this.options.whenChoicesRunOut ?? "rotate";
|
|
123
|
+
let selected: number | null;
|
|
124
|
+
if (next !== undefined) selected = next;
|
|
125
|
+
else if (policy === "stop") selected = null;
|
|
126
|
+
else if (policy === "first") selected = 0;
|
|
127
|
+
else {
|
|
128
|
+
const seen = this.seenChoices.get(key) ?? 0;
|
|
129
|
+
this.seenChoices.set(key, seen + 1);
|
|
130
|
+
selected = seen % options.length;
|
|
131
|
+
}
|
|
132
|
+
this.trace.push({ type: "choice", options, selected });
|
|
133
|
+
return selected;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
onDiagnostic(diagnostic: Diagnostic): void {
|
|
137
|
+
this.trace.push({ type: "diagnostic", diagnostic });
|
|
138
|
+
}
|
|
139
|
+
}
|
package/src/host.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import type { Diagnostic } from "@liminalia/lang";
|
|
2
|
+
import type { Position, StageState, VoiceCue } from "./state.ts";
|
|
3
|
+
import type { PrefetchItem } from "./prefetch.ts";
|
|
4
|
+
import type { Value } from "./value.ts";
|
|
5
|
+
|
|
6
|
+
export interface TextStyle {
|
|
7
|
+
bold: boolean;
|
|
8
|
+
italic: boolean;
|
|
9
|
+
color: string | null;
|
|
10
|
+
/** 一文字あたりのミリ秒。null はそのときの既定の速さ。 */
|
|
11
|
+
perChar: number | null;
|
|
12
|
+
/** 文字の大きさ(px)。null は既定の大きさ。 */
|
|
13
|
+
size: number | null;
|
|
14
|
+
/** 背景に引く色(蛍光ペン)。 */
|
|
15
|
+
mark: string | null;
|
|
16
|
+
/** 文字の動き({fx …}。shake・wave・pop・fade・glow)。 */
|
|
17
|
+
fx?: string | null;
|
|
18
|
+
/** 文字の動きの大きさと速さの倍率({fx … strength= speed=}。書かなければ無い)。 */
|
|
19
|
+
fxStrength?: number;
|
|
20
|
+
fxSpeed?: number;
|
|
21
|
+
/** 傍点({dot …})。 */
|
|
22
|
+
emphasis?: boolean;
|
|
23
|
+
/** 本文の中の画像({img …}。image フォルダからのパス)。このときの text は "\uFFFC"。imageHeight は高さ(px)。 */
|
|
24
|
+
image?: string;
|
|
25
|
+
imageHeight?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 選択肢の見た目(@choice の選択肢の行の image= x= など)。書かなかったものは入らない。 */
|
|
29
|
+
export interface ChoiceLook {
|
|
30
|
+
/** 押せない状態で見せる(locked= が真)。 */
|
|
31
|
+
locked?: boolean;
|
|
32
|
+
image?: string;
|
|
33
|
+
hover?: string;
|
|
34
|
+
x?: number;
|
|
35
|
+
y?: number;
|
|
36
|
+
width?: number;
|
|
37
|
+
height?: number;
|
|
38
|
+
/** 上に乗せたときのカーソルの画像と、出す短い説明(調べる場所)。 */
|
|
39
|
+
cursor?: string;
|
|
40
|
+
tip?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 同じページで同時に話すほかの話者(PresentEvent の page の with)。 */
|
|
44
|
+
export interface CoSpeaker {
|
|
45
|
+
speaker: string;
|
|
46
|
+
/** 名前欄に出す名前(@name、訳)。話者名と同じなら省く。 */
|
|
47
|
+
label?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 描画側へ渡す出来事。描画側は表示し終えたら(または待たない指定なら即座に)Promise を解決する。 */
|
|
51
|
+
export type PresentEvent =
|
|
52
|
+
/**
|
|
53
|
+
* 新しいページ。メッセージ枠を空にして話者名を出す(null は地の文)。voice はこのページで鳴らすボイス(@voice・@voice-auto)。
|
|
54
|
+
* label は話者名の訳(多言語)。出すのは label、話者ごとの処理(ボイスの音量・口パク)は speaker で見る。
|
|
55
|
+
* key はページの鍵(@liminalia/lang の pageKeys。行を足しても変わらない。既読を覚えるのに使う)。
|
|
56
|
+
* with は同じページで同時に話すほかの話者(二つ目のボイスの who。話者と同じ人は入れない)。label はその人の名前欄の名前(話者名と違うときだけ)。
|
|
57
|
+
*/
|
|
58
|
+
| { type: "page"; speaker: string | null; label?: string; at: { file: string; line: number }; key?: string; voice?: VoiceCue; with?: CoSpeaker[] }
|
|
59
|
+
| { type: "text"; text: string; ruby: string | null; style: TextStyle }
|
|
60
|
+
| { type: "br" }
|
|
61
|
+
/**
|
|
62
|
+
* 命令を実行した。stage は実行後の状態。wait が true なら演出が終わるまで解決しない。
|
|
63
|
+
* skip は演出の命令に付く。true ならクリックで演出を終わりまで早送りでき、false なら早送りしない(命令の skip=false)。
|
|
64
|
+
* 演出でない命令(音、入力を待つ画面など)には付かない。
|
|
65
|
+
* autoplay は自動確認(Host.automated)で命令の autoplay が答えを出すときに付く。描画側は描かずにすぐ返す(画面なしの記録には残す)。
|
|
66
|
+
* interactive は autoplay を持つ命令(遊ぶ人の操作を待つ画面や動画)を、自動確認でないので描かせるときに付く。描画側は描いている間、
|
|
67
|
+
* 操作待ちの画面を出していると撮影(lim shot)に知らせる。
|
|
68
|
+
* afterPage は、メッセージ枠のページをクリックで送ってから最初に渡す命令に付く(TyranoScript の [p] の改ページと同じく、
|
|
69
|
+
* 描画側はここで前のページの名前と本文を消し、枠は残す。ui.message.keepText か、@bg の keep-text=true なら消さない)。
|
|
70
|
+
*/
|
|
71
|
+
| { type: "command"; name: string; args: Record<string, Value>; wait: boolean; stage: StageState; skip?: boolean; autoplay?: boolean; interactive?: boolean; afterPage?: boolean };
|
|
72
|
+
|
|
73
|
+
export interface Host {
|
|
74
|
+
/** ファイル名(拡張子なし)から .lim の中身を返す。 */
|
|
75
|
+
loadSource(file: string): Promise<string>;
|
|
76
|
+
/**
|
|
77
|
+
* 作品のデータ(paths.data の .json。name はそこからのパスで `.json` を省ける)を JSON として読む。無ければ undefined。
|
|
78
|
+
* 命令は ctx.data で読む(図鑑・調べる場所など、作品のデータで動く標準の命令が使う)。省略可。
|
|
79
|
+
*/
|
|
80
|
+
loadData?(name: string): Promise<unknown>;
|
|
81
|
+
/** 命令によっては結果(選ばれた行き先など)を返す。 */
|
|
82
|
+
present(event: PresentEvent, signal: AbortSignal): Promise<Value | void>;
|
|
83
|
+
/** クリック(本文の送り)を待つ。 */
|
|
84
|
+
waitClick(signal: AbortSignal): Promise<void>;
|
|
85
|
+
/**
|
|
86
|
+
* 選択肢から一つ選ぶ。null なら実行を終える。
|
|
87
|
+
* looks は選択肢ごとの見た目(文字のボタンなら null)。画像のボタンや押せる範囲のときだけ渡る。
|
|
88
|
+
* targets は選択肢ごとの飛び先("ファイル" か "ファイル#ラベル"。式の飛び先などで分からなければ null)。
|
|
89
|
+
* 描画側は使わない。画面なしで流す道筋の探索が、目標に近い選択肢から試すのに使う。
|
|
90
|
+
*/
|
|
91
|
+
choose(options: string[], signal: AbortSignal, looks?: (ChoiceLook | null)[], targets?: (string | null)[]): Promise<number | null>;
|
|
92
|
+
/**
|
|
93
|
+
* @choice の選択肢を選んだ(時間切れで default を選んだときも。call=true の選択肢は除く)。text は選んだ選択肢の文(訳したもの。
|
|
94
|
+
* 画像のボタンなどで文が無ければ空)、index は出した選択肢の中の番号。履歴に残すのに使う。省略可。
|
|
95
|
+
*/
|
|
96
|
+
chosen?(option: { text: string; index: number }): void;
|
|
97
|
+
/**
|
|
98
|
+
* 選択肢の制限時間(@choice timeout=)を計り、ms だけ経ったら解決する。描画側は、システム画面を開いている間などは
|
|
99
|
+
* 時間を止めておける。signal で打ち切ったら解決しなくてよい。省略すると実時間で計る(画面なしで流すときなど)。
|
|
100
|
+
*/
|
|
101
|
+
countdown?(ms: number, signal: AbortSignal): Promise<void>;
|
|
102
|
+
/**
|
|
103
|
+
* この先で使う素材を先に読んでおく(ページを出すたびに呼ぶ)。待たずに返す。省略可。
|
|
104
|
+
* 同じものが何度も来るので、描画側で重複を除く。
|
|
105
|
+
*/
|
|
106
|
+
prefetch?(items: PrefetchItem[]): void;
|
|
107
|
+
/** @script を実行する。省略時は実行せず診断を出す。 */
|
|
108
|
+
runScript?(code: string, at: Position): Promise<void>;
|
|
109
|
+
onDiagnostic?(diagnostic: Diagnostic): void;
|
|
110
|
+
/**
|
|
111
|
+
* 自動確認(lim playtest・lim shot・全ルートテストなど、人が操作せずに流す)で動いているか。true なら、autoplay を持つ命令
|
|
112
|
+
* (遊ぶ人の操作を待つ画面や動画)は描かずに、命令の autoplay の答えで進める。画面なしの Host(HeadlessHost)は常に true。
|
|
113
|
+
* 実行器は命令ごとに読み直すので、途中で変えてよい(lim shot は撮る所に着いたら false にして、その画面を描かせる)。
|
|
114
|
+
*/
|
|
115
|
+
readonly automated?: boolean;
|
|
116
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { Runtime, type Args, type CommandContext, type CommandImpl, type PickOutcome, type Platform, type ProgramCache, type RunResult, type RuntimeOptions, type StartOptions, type Translator } from "./runtime.ts";
|
|
2
|
+
export type { ChoiceLook, CoSpeaker, Host, PresentEvent, TextStyle } from "./host.ts";
|
|
3
|
+
export { buildProgram, type Instruction, type Program, type Unit } from "./program.ts";
|
|
4
|
+
export { createState, initialStage, toSaveData, voiceFile, type NvlPage, type NvlPart, type VoiceAuto, type VoiceCue, type GameState, type Position, type SaveData, type Snapshot, type Sprite, type StageState, type Balloon, type SceneWait, type SoundOptions, type SoundFilterState } from "./state.ts";
|
|
5
|
+
export { CHAT_KEEP, CHAT_KEY, chatDialogueActive, chatPartsText, chatQuoteStripper, clearChatMessages, pushChatMessage, readChat, type Chat, type ChatDialogue, type ChatMessage } from "./chat.ts";
|
|
6
|
+
export { argOrigin, textOrigins, I18N_FIELD, type TextOrigin } from "./retranslate.ts";
|
|
7
|
+
export { display, equals, evaluate, EvalError, setPluginFunctionImpls, truthy, type Scope, type Value } from "./value.ts";
|
|
8
|
+
export { CORE_IMPLEMENTATIONS } from "./commands.ts";
|
|
9
|
+
export { HeadlessHost, type HeadlessOptions, type TraceEntry } from "./headless.ts";
|
|
10
|
+
export { collectPrefetch, type PrefetchItem } from "./prefetch.ts";
|
|
11
|
+
export { capture, explore, findRoute, walk, type Assignments, type ChoiceMade, type Exploration, type ExploreOptions, type FindRouteOptions, type Reached, type Walk, type WalkOptions } from "./route.ts";
|
|
12
|
+
export { coverage, DEFAULT_COVERAGE_RUNS, routeCoverage, type CoverageOptions, type CoverageReport, type RouteCoverageOptions, type RouteCoverageReport } from "./coverage.ts";
|
|
13
|
+
export { observeVoiceNumbers } from "./voice-observe.ts";
|
|
14
|
+
export { projectRuntimeOptions, RUNTIME_OPTION_OWNERS, type ProjectRuntimeConfig, type ProjectRuntimeOptions, type ProjectRuntimeSource } from "./project-options.ts";
|
|
15
|
+
export { DEFAULT_TEST_LIMIT, runScenarioTest, type ScenarioTestOptions, type ScenarioTestResult, type TestFailure } from "./scenario-test.ts";
|
|
16
|
+
export { migrateSave, migrateWith, saveProblem, SAVE_VERSION, SaveVersionError, type SaveProblem } from "./save.ts";
|
package/src/prefetch.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { CHOICE_OPTION, normalizeBooleanArgs, type Argument, type CommandSpec, type Inline, type Registry } from "@liminalia/lang";
|
|
2
|
+
import type { Instruction, Unit } from "./program.ts";
|
|
3
|
+
|
|
4
|
+
/** 先読みしてほしい素材。立ち絵はキャストの定義から画像を求めるので、名前の組で渡す。 */
|
|
5
|
+
export type PrefetchItem =
|
|
6
|
+
| { kind: "asset"; folder: string; path: string }
|
|
7
|
+
| { kind: "sprite"; who: string; appearance: string; variant: string };
|
|
8
|
+
|
|
9
|
+
/** 画像のフォルダ。命令が folder 引数を持つときは、それで探し先が替わる。 */
|
|
10
|
+
const IMAGE_FOLDERS = new Set(["bgimage", "fgimage", "image"]);
|
|
11
|
+
/** ボイスを探せるフォルダ(@voice の folder=)。 */
|
|
12
|
+
const VOICE_FOLDERS = new Set(["voice", "sound"]);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* index から先の limit 個の命令(本文中の命令と、選択肢の画像も含む)が使う素材を集める。
|
|
16
|
+
* 分岐は両方とも見る(どちらへ進んでも間に合うように)。式で書いた引数は評価せずに飛ばす(副作用を起こさないため)。
|
|
17
|
+
*/
|
|
18
|
+
export function collectPrefetch(unit: Unit, index: number, registry: Registry, limit = 40): PrefetchItem[] {
|
|
19
|
+
const out: PrefetchItem[] = [];
|
|
20
|
+
const seen = new Set<string>();
|
|
21
|
+
const push = (item: PrefetchItem) => {
|
|
22
|
+
const key = JSON.stringify(item);
|
|
23
|
+
if (seen.has(key)) return;
|
|
24
|
+
seen.add(key);
|
|
25
|
+
out.push(item);
|
|
26
|
+
};
|
|
27
|
+
const end = Math.min(unit.instructions.length, index + limit);
|
|
28
|
+
for (let i = index; i < end; i++) {
|
|
29
|
+
const ins: Instruction = unit.instructions[i]!;
|
|
30
|
+
if (ins.op === "command") fromCommand(ins.name, ins.args, registry, push);
|
|
31
|
+
else if (ins.op === "say") fromInline(ins.content, registry, push);
|
|
32
|
+
else if (ins.op === "choice") for (const o of ins.options) fromSpec(CHOICE_OPTION, o.args, push);
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function fromInline(nodes: Inline[], registry: Registry, push: (item: PrefetchItem) => void): void {
|
|
38
|
+
for (const n of nodes) {
|
|
39
|
+
if (n.kind === "command") fromCommand(n.name, n.args, registry, push);
|
|
40
|
+
else if ("children" in n) fromInline(n.children, registry, push);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function fromCommand(name: string, args: Argument[], registry: Registry, push: (item: PrefetchItem) => void): void {
|
|
45
|
+
const spec = registry.get(name);
|
|
46
|
+
if (spec) fromSpec(spec, args, push);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function fromSpec(spec: CommandSpec, args: Argument[], push: (item: PrefetchItem) => void): void {
|
|
50
|
+
const values = literalArgs(spec, args);
|
|
51
|
+
let who: string | null = null;
|
|
52
|
+
let variant: string | null = null;
|
|
53
|
+
let appearance = "";
|
|
54
|
+
for (const [param, value] of Object.entries(values)) {
|
|
55
|
+
const type = spec.params[param]?.type;
|
|
56
|
+
if (!type) continue;
|
|
57
|
+
if (type.kind === "asset" && value !== "") {
|
|
58
|
+
const given = typeof values.folder === "string" ? values.folder : null;
|
|
59
|
+
const folder = given !== null && ((IMAGE_FOLDERS.has(type.folder) && IMAGE_FOLDERS.has(given)) || (VOICE_FOLDERS.has(type.folder) && VOICE_FOLDERS.has(given))) ? given : type.folder;
|
|
60
|
+
push({ kind: "asset", folder, path: value });
|
|
61
|
+
}
|
|
62
|
+
if (type.kind === "cast") who = value;
|
|
63
|
+
if (type.kind === "variant") variant = value;
|
|
64
|
+
if (type.kind === "appearance") appearance = value;
|
|
65
|
+
}
|
|
66
|
+
if (who !== null && variant !== null) push({ kind: "sprite", who, appearance, variant });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 文字列で書かれた引数だけを、引数名ごとに取り出す。 */
|
|
70
|
+
function literalArgs(spec: CommandSpec, args: Argument[]): Record<string, string> {
|
|
71
|
+
const out: Record<string, string> = {};
|
|
72
|
+
let position = 0;
|
|
73
|
+
for (const a of normalizeBooleanArgs(spec, args)) {
|
|
74
|
+
const name = a.key ?? spec.positional[position++];
|
|
75
|
+
if (name !== undefined && a.value.kind === "string") out[name] = a.value.value;
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|