@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.
Files changed (57) hide show
  1. package/LICENSE +106 -0
  2. package/dist/src/chat.js +60 -0
  3. package/dist/src/commands-play.js +300 -0
  4. package/dist/src/commands.js +534 -0
  5. package/dist/src/coverage.js +208 -0
  6. package/dist/src/headless.js +109 -0
  7. package/dist/src/host.js +1 -0
  8. package/dist/src/index.js +15 -0
  9. package/dist/src/prefetch.js +80 -0
  10. package/dist/src/program.js +131 -0
  11. package/dist/src/project-options.js +84 -0
  12. package/dist/src/retranslate.js +44 -0
  13. package/dist/src/route.js +242 -0
  14. package/dist/src/runtime.js +1929 -0
  15. package/dist/src/save.js +51 -0
  16. package/dist/src/scenario-test.js +200 -0
  17. package/dist/src/state.js +62 -0
  18. package/dist/src/value.js +464 -0
  19. package/dist/src/voice-observe.js +82 -0
  20. package/package.json +33 -4
  21. package/src/chat.ts +109 -0
  22. package/src/commands-play.ts +280 -0
  23. package/src/commands.ts +457 -0
  24. package/src/coverage.ts +257 -0
  25. package/src/headless.ts +139 -0
  26. package/src/host.ts +116 -0
  27. package/src/index.ts +16 -0
  28. package/src/prefetch.ts +78 -0
  29. package/src/program.ts +186 -0
  30. package/src/project-options.ts +128 -0
  31. package/src/retranslate.ts +67 -0
  32. package/src/route.ts +365 -0
  33. package/src/runtime.ts +2143 -0
  34. package/src/save.ts +60 -0
  35. package/src/scenario-test.ts +218 -0
  36. package/src/state.ts +353 -0
  37. package/src/value.ts +443 -0
  38. package/src/voice-observe.ts +85 -0
  39. package/types/src/chat.d.ts +63 -0
  40. package/types/src/commands-play.d.ts +2 -0
  41. package/types/src/commands.d.ts +2 -0
  42. package/types/src/coverage.d.ts +100 -0
  43. package/types/src/headless.d.ts +77 -0
  44. package/types/src/host.d.ts +140 -0
  45. package/types/src/index.d.ts +16 -0
  46. package/types/src/prefetch.d.ts +18 -0
  47. package/types/src/program.d.ts +107 -0
  48. package/types/src/project-options.d.ts +103 -0
  49. package/types/src/retranslate.d.ts +39 -0
  50. package/types/src/route.d.ts +181 -0
  51. package/types/src/runtime.d.ts +553 -0
  52. package/types/src/save.d.ts +21 -0
  53. package/types/src/scenario-test.d.ts +43 -0
  54. package/types/src/state.d.ts +357 -0
  55. package/types/src/value.d.ts +61 -0
  56. package/types/src/voice-observe.d.ts +26 -0
  57. package/README.md +0 -3
package/src/program.ts ADDED
@@ -0,0 +1,186 @@
1
+ import { pageKeys, voiceLines, type Argument, type ChoiceOption, type Expr, type Inline, type Param, type Script, type Statement, type Target } from "@liminalia/lang";
2
+
3
+ /**
4
+ * 実行単位。ファイル本体と、各 @define の本体がそれぞれ一つの Unit になる。
5
+ * 制御構文は条件ジャンプに展開してあり、実行位置は (unit, index) の二つの値で表せる。
6
+ * そのためセーブデータに実行位置をそのまま書ける。
7
+ */
8
+ export interface Unit {
9
+ /** "chapter1" または "chapter1::title-card"。 */
10
+ id: string;
11
+ file: string;
12
+ instructions: Instruction[];
13
+ /** ラベル名 → 位置(ファイル本体の Unit だけが持つ)。 */
14
+ labels: Record<string, number>;
15
+ /** @if の中にあるラベル(飛び込めない。検査ではエラー)。 */
16
+ nestedLabels?: Set<string>;
17
+ /** @define の Unit だけが持つ。 */
18
+ params?: Param[];
19
+ }
20
+
21
+ export type Instruction =
22
+ /** name はこの行だけ名前欄に出す名前(話者{name …})。id は行末の固定の行 ID(#line:ID。訳の鍵)。 */
23
+ | { op: "say"; speaker: string | null; name?: Inline[]; content: Inline[]; line: number; id?: string }
24
+ /** body は @end までの行をそのまま持つ命令(@html)の中身。content は @with で渡す中身の実行単位の id。 */
25
+ | { op: "command"; name: string; args: Argument[]; body?: string; content?: string; line: number }
26
+ | { op: "branch"; condition: Expr; /** 偽のときの飛び先 */ otherwise: number; line: number }
27
+ | { op: "goto"; to: number; line: number }
28
+ | { op: "choice"; options: ChoiceOption[]; args?: Argument[]; line: number }
29
+ | { op: "set"; target: Expr; operator: "=" | "+=" | "-=" | "*=" | "/="; value: Expr; line: number }
30
+ | { op: "let"; name: string; value: Expr; line: number }
31
+ | { op: "jump" | "call"; target: Target; line: number }
32
+ /** value はマクロの戻り値(@return (式))。 */
33
+ | { op: "return"; value?: Expr; line: number }
34
+ /** @with で渡された中身を実行する(@define の中の @content)。 */
35
+ | { op: "content"; line: number }
36
+ | { op: "script"; code: string; line: number }
37
+ | { op: "label"; name: string; line: number };
38
+
39
+ export interface Program {
40
+ file: string;
41
+ main: Unit;
42
+ defines: Map<string, Unit>;
43
+ /** @use したファイル(ここにある @define を呼べる)。 */
44
+ uses: string[];
45
+ /** 台詞の行 → ボイスの番号の固定の鍵(voice-lock.json)。 */
46
+ voiceKeys: Map<number, string>;
47
+ /** 本文の行 → ページの鍵(既読を覚えるのに使う。@liminalia/lang の pageKeys)。 */
48
+ pageKeys: Map<number, string>;
49
+ /** @function で作った式の関数(名前 → 引数と中身)。 */
50
+ functions: Map<string, UserFunction>;
51
+ }
52
+
53
+ /** @function で作った式の関数。file は書いたファイル(中から呼ぶ関数はそのファイルから探す)。 */
54
+ export interface UserFunction {
55
+ file: string;
56
+ params: string[];
57
+ body: Expr;
58
+ }
59
+
60
+ export function buildProgram(script: Script): Program {
61
+ const main: Unit = { id: script.file, file: script.file, instructions: [], labels: {} };
62
+ const defines = new Map<string, Unit>();
63
+ emitBlock(script.body, main, defines, false, { withs: 0, loops: 0 });
64
+ const uses = script.body.flatMap((s) => (s.kind === "use" ? [s.file] : []));
65
+ const functions = new Map<string, UserFunction>();
66
+ for (const s of script.body) if (s.kind === "function" && !functions.has(s.name)) functions.set(s.name, { file: script.file, params: s.params, body: s.body });
67
+ return { file: script.file, main, defines, uses, voiceKeys: new Map(voiceLines(script).map((l) => [l.line, l.key])), pageKeys: pageKeys(script), functions };
68
+ }
69
+
70
+ /**
71
+ * withs は @with の中身に振る番号(ファイルの中で書いた順。中身の実行単位は `ファイル::@with:番号` で、defines に置く)。
72
+ */
73
+ function emitBlock(body: Statement[], unit: Unit, defines: Map<string, Unit>, inIf: boolean, counter: { withs: number; loops: number }): void {
74
+ const out = unit.instructions;
75
+ for (const s of body) {
76
+ switch (s.kind) {
77
+ case "prose":
78
+ out.push({ op: "say", speaker: null, content: s.content, line: s.line, ...(s.id ? { id: s.id } : {}) });
79
+ break;
80
+ case "say":
81
+ out.push({ op: "say", speaker: s.speaker, ...(s.name ? { name: s.name } : {}), content: s.content, line: s.line, ...(s.id ? { id: s.id } : {}) });
82
+ break;
83
+ case "label":
84
+ unit.labels[s.name] ??= out.length;
85
+ if (inIf) (unit.nestedLabels ??= new Set()).add(s.name);
86
+ out.push({ op: "label", name: s.name, line: s.line });
87
+ break;
88
+ case "command":
89
+ out.push({ op: "command", name: s.name, args: s.args, ...(s.body ? { body: s.body.text } : {}), line: s.line });
90
+ break;
91
+ case "if": {
92
+ if (s.with) {
93
+ // @with: 中身を別の実行単位にして、マクロの呼び出しに渡す(マクロの中の @content がそこへ入る)
94
+ const key = `@with:${++counter.withs}`;
95
+ const child: Unit = { id: `${unit.file}::${key}`, file: unit.file, instructions: [], labels: {} };
96
+ emitBlock(s.branches[0]?.body ?? [], child, defines, true, counter);
97
+ child.instructions.push({ op: "return", line: s.line });
98
+ defines.set(key, child);
99
+ out.push({ op: "command", name: s.with.name, args: s.with.args, content: child.id, line: s.line });
100
+ break;
101
+ }
102
+ if (s.each) {
103
+ // @for 名前 in 式: 配列(辞書ならキーの並び)を一度だけ求めて隠れた局所変数に置き、番号を進めながら要素を名前に入れてくり返す。
104
+ // 隠れた名前は @ で始まるので、式からは書けない(台本の変数とぶつからない)
105
+ const b = s.branches[0]!;
106
+ const n = ++counter.loops;
107
+ const list: Expr = { kind: "name", name: `@for${n}:list` };
108
+ const index: Expr = { kind: "name", name: `@for${n}:i` };
109
+ out.push({ op: "let", name: `@for${n}:list`, value: { kind: "call", callee: EACH_FUNCTION, args: [s.each.list] }, line: s.line });
110
+ out.push({ op: "let", name: `@for${n}:i`, value: { kind: "literal", value: 0 }, line: s.line });
111
+ const start = out.length;
112
+ const branch: Extract<Instruction, { op: "branch" }> = { op: "branch", condition: { kind: "binary", op: "<", left: index, right: { kind: "call", callee: "len", args: [list] } }, otherwise: -1, line: s.line };
113
+ out.push(branch);
114
+ out.push({ op: "let", name: s.each.name, value: { kind: "index", object: list, index }, line: s.line });
115
+ out.push({ op: "let", name: `@for${n}:i`, value: { kind: "binary", op: "+", left: index, right: { kind: "literal", value: 1 } }, line: s.line });
116
+ emitBlock(b.body, unit, defines, true, counter);
117
+ out.push({ op: "goto", to: start, line: s.line });
118
+ branch.otherwise = out.length;
119
+ break;
120
+ }
121
+ if (s.loop) {
122
+ // @while: 条件が偽なら @end の後ろへ。中を終えたら条件へ戻る
123
+ const start = out.length;
124
+ const b = s.branches[0]!;
125
+ const branch: Extract<Instruction, { op: "branch" }> = { op: "branch", condition: b.condition!, otherwise: -1, line: b.line };
126
+ out.push(branch);
127
+ emitBlock(b.body, unit, defines, true, counter);
128
+ out.push({ op: "goto", to: start, line: b.line });
129
+ branch.otherwise = out.length;
130
+ break;
131
+ }
132
+ const exits: { op: "goto"; to: number; line: number }[] = [];
133
+ for (const b of s.branches) {
134
+ let branch: Extract<Instruction, { op: "branch" }> | null = null;
135
+ if (b.condition) {
136
+ branch = { op: "branch", condition: b.condition, otherwise: -1, line: b.line };
137
+ out.push(branch);
138
+ }
139
+ emitBlock(b.body, unit, defines, true, counter);
140
+ const exit = { op: "goto" as const, to: -1, line: b.line };
141
+ out.push(exit);
142
+ exits.push(exit);
143
+ if (branch) branch.otherwise = out.length;
144
+ }
145
+ for (const e of exits) e.to = out.length;
146
+ break;
147
+ }
148
+ case "choice":
149
+ out.push({ op: "choice", options: s.options, ...(s.args ? { args: s.args } : {}), line: s.line });
150
+ break;
151
+ case "define": {
152
+ const id = `${unit.file}::${s.name}`;
153
+ const child: Unit = { id, file: unit.file, instructions: [], labels: {}, params: s.params };
154
+ emitBlock(s.body, child, defines, false, counter);
155
+ child.instructions.push({ op: "return", line: s.line });
156
+ defines.set(s.name, child);
157
+ break;
158
+ }
159
+ case "script":
160
+ out.push({ op: "script", code: s.code, line: s.line });
161
+ break;
162
+ case "set":
163
+ out.push({ op: "set", target: s.target, operator: s.op, value: s.value, line: s.line });
164
+ break;
165
+ case "let":
166
+ out.push({ op: "let", name: s.name, value: s.value, line: s.line });
167
+ break;
168
+ case "jump":
169
+ case "call":
170
+ out.push({ op: s.kind, target: s.target, line: s.line });
171
+ break;
172
+ case "return":
173
+ out.push({ op: "return", ...(s.value ? { value: s.value } : {}), line: s.line });
174
+ break;
175
+ case "content":
176
+ out.push({ op: "content", line: s.line });
177
+ break;
178
+ case "use":
179
+ case "function":
180
+ break;
181
+ }
182
+ }
183
+ }
184
+
185
+ /** @for が回すものを配列にする式の関数(実行器だけが呼ぶ。名前は式からは書けない。value.ts)。 */
186
+ export const EACH_FUNCTION = "@each";
@@ -0,0 +1,128 @@
1
+ import { achievementGoals, autoLayoutRules, cgMatcher, chatDialogueOption, endingAchievements, uiForLanguage, type CastEntry, type ChapterInfo, type CommandDefaults, type ExtraConfig, type UiConfig, type VoiceLock } from "@liminalia/lang";
2
+ import type { CommandImpl, RuntimeOptions, Translator } from "./runtime.ts";
3
+ import type { Value } from "./value.ts";
4
+
5
+ /**
6
+ * 作品の設定から実行器の設定(RuntimeOptions)を作る。遊ぶ側(packages/web)と、画面なしで流すもの(lim trace、lim test、lim coverage、
7
+ * lim reach、lim build --seed、lim voice-lock、制作画面の現在地と全ルートテスト、VS Code の「ここからテストプレイ」)は、どれもこれで作り、
8
+ * 流し方で変えるもの(RUNTIME_OPTION_OWNERS で caller にしたもの)だけを呼ぶ側が足す。片方にだけ作品の設定を渡して、
9
+ * 同じ台本を流した結果が食い違う(自動配置が外れる、言語や章や版で分かれる先が違う、台詞の括弧やボイスの番号が違う)ことを防ぐ。
10
+ */
11
+
12
+ /**
13
+ * 実行器の設定の一つ一つを、だれが決めるか。
14
+ * - "project": projectRuntimeOptions が作品の設定から埋める
15
+ * - { caller }: 呼ぶ側が決める(その理由)
16
+ * 実行器の設定を足したら、ここで分けるまで型の確かめが通らない(project-options.test.ts は、関数が埋める項目がここの "project" と
17
+ * ちょうど同じことを見る)。
18
+ */
19
+ export const RUNTIME_OPTION_OWNERS = {
20
+ speakers: "project",
21
+ commands: "project",
22
+ commandDefaults: "project",
23
+ variables: "project",
24
+ afterLoad: "project",
25
+ gameVersion: "project",
26
+ chapters: "project",
27
+ achievementGoals: "project",
28
+ endingAchievements: "project",
29
+ endingKinds: "project",
30
+ cast: "project",
31
+ autoLayout: "project",
32
+ voiceLock: "project",
33
+ cg: "project",
34
+ chatDialogue: "project",
35
+ // 選択肢を本文の流れに出す(ui.choice.position: inline。@nvl の間、選んだものを本文の一部として残す)
36
+ inlineChoices: "project",
37
+ stripQuotes: "project",
38
+ language: "project",
39
+ translator: "project",
40
+ loadData: "project",
41
+ seed: { caller: "乱数の種。遊ぶ側は決めず、台本のテストと網羅は回ごとに決める" },
42
+ maxSteps: { caller: "命令の数の上限。流し方ごとに、終わらない繰り返しで止める所が違う" },
43
+ onError: { caller: "実行時のエラーで止めるか。遊ぶ側と画面なしの流しは続けて知らせる(continue)が、実行器の既定は止める" },
44
+ returnWithoutCall: { caller: "呼ばれていない @return の扱い。網羅のファイルごとの流しだけが、@call で呼ぶだけのファイルを先頭から流すので続ける" },
45
+ onAssign: { caller: "変数を入れたときの知らせ。制作画面が値を決めた行を控えるためのもので、流し方が使う" },
46
+ onStep: { caller: "命令の前の知らせ。網羅と台本のテストが通った行を数えるためのもので、流し方が使う" },
47
+ beforeStep: { caller: "命令の前で待つ。遊ぶ側の作品の画面とブレークポイントだけが使う" },
48
+ programCache: { caller: "読んだ台本の控え。遊ぶ側が一回のプレイを作り直しても読み解き直さないためのもので、流し方が持つ" },
49
+ platform: { caller: "遊んでいる機種。遊ぶ側は調べて入れ、画面なしの流しは省いてパソコンのブラウザとする" },
50
+ } as const satisfies { readonly [K in keyof Required<RuntimeOptions>]: "project" | { readonly caller: string } };
51
+
52
+ type ProjectKey = { [K in keyof typeof RUNTIME_OPTION_OWNERS]: (typeof RUNTIME_OPTION_OWNERS)[K] extends "project" ? K : never }[keyof typeof RUNTIME_OPTION_OWNERS];
53
+
54
+ /** projectRuntimeOptions が埋める実行器の設定。 */
55
+ export type ProjectRuntimeOptions = Pick<RuntimeOptions, ProjectKey>;
56
+
57
+ /** 作品の設定(liminalia.json)の、実行器に効く項目。読んだ JSON のままでよい(形の違う値は使わない。lim check が知らせる)。 */
58
+ export interface ProjectRuntimeConfig {
59
+ version?: unknown;
60
+ variables?: unknown;
61
+ afterLoad?: unknown;
62
+ commandDefaults?: unknown;
63
+ chapters?: unknown;
64
+ extra?: unknown;
65
+ endingKinds?: unknown;
66
+ autoLayout?: unknown;
67
+ ui?: unknown;
68
+ languages?: unknown;
69
+ }
70
+
71
+ /** 実行器の設定を作る元。ファイルを読むのは呼ぶ側(ブラウザでも Node でも使うため)。 */
72
+ export interface ProjectRuntimeSource {
73
+ config: ProjectRuntimeConfig;
74
+ /** 話者(cast.json の speakers)。 */
75
+ speakers: Iterable<string>;
76
+ /** 組み込みの外の命令(標準の命令と、作品のプラグインの命令)。 */
77
+ commands: readonly CommandImpl[];
78
+ /** キャストの定義(cast.json の cast)。 */
79
+ cast: Readonly<Record<string, CastEntry>> | Readonly<Record<string, unknown>>;
80
+ /** 連番のボイスの番号の固定(voice-lock.json。無い・読めなければ null)。 */
81
+ voiceLock?: VoiceLock | null;
82
+ /** 作品のデータを読む(画面なしで流すとき。遊ぶ側は描画側が読むので渡さない)。 */
83
+ loadData?(name: string): unknown;
84
+ /** 遊ぶ言語。省けば原文の言語(languages の先頭。無ければ ""。遊ぶ側が言語を選ばないときと同じ)。 */
85
+ language?: string;
86
+ /** その言語の訳。省けば訳さない(原文の言語で流すとき)。 */
87
+ translator?: Translator | null;
88
+ }
89
+
90
+ const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
91
+
92
+ /** 作品の設定から実行器の設定を作る(RUNTIME_OPTION_OWNERS で "project" にしたもの)。 */
93
+ export function projectRuntimeOptions(src: ProjectRuntimeSource): ProjectRuntimeOptions {
94
+ const c = src.config;
95
+ const extra = isRecord(c.extra) ? (c.extra as ExtraConfig) : undefined;
96
+ const ui = isRecord(c.ui) ? (c.ui as UiConfig) : undefined;
97
+ const languages = Array.isArray(c.languages) ? c.languages : [];
98
+ const language = src.language ?? (typeof languages[0] === "string" ? languages[0] : "");
99
+ const autoLayout = autoLayoutRules(c.autoLayout);
100
+ const cg = cgMatcher(extra);
101
+ const chatDialogue = chatDialogueOption(ui);
102
+ const strip = uiForLanguage(ui, language)?.text?.quotes === "strip";
103
+ return {
104
+ speakers: [...src.speakers],
105
+ commands: [...src.commands],
106
+ cast: src.cast as Readonly<Record<string, CastEntry>>,
107
+ ...(isRecord(c.variables) ? { variables: c.variables as Record<string, Value> } : {}),
108
+ ...(typeof c.afterLoad === "string" && c.afterLoad !== "" ? { afterLoad: c.afterLoad } : {}),
109
+ // 作品の版(セーブに入り、式の save.version で読める。書き出したゲームは project/build.json の版)
110
+ ...(typeof c.version === "string" && c.version !== "" ? { gameVersion: c.version } : {}),
111
+ ...(isRecord(c.commandDefaults) ? { commandDefaults: c.commandDefaults as CommandDefaults } : {}),
112
+ ...(Array.isArray(c.chapters) ? { chapters: c.chapters as ChapterInfo[] } : {}),
113
+ achievementGoals: achievementGoals(extra),
114
+ endingAchievements: endingAchievements(extra),
115
+ ...(isRecord(c.endingKinds) ? { endingKinds: c.endingKinds } : {}),
116
+ ...(autoLayout ? { autoLayout } : {}),
117
+ voiceLock: src.voiceLock ?? null,
118
+ ...(cg ? { cg } : {}),
119
+ ...(chatDialogue ? { chatDialogue } : {}),
120
+ // 選択肢を本文の流れに出す(ui.choice.position: inline。@nvl の間、選んだものを本文の一部として残す。遊ぶ言語の ui.languages を重ねたもの)
121
+ ...(uiForLanguage(ui, language)?.choice?.position === "inline" ? { inlineChoices: true } : {}),
122
+ // 台詞の外側の括弧(ui.text.quotes。遊ぶ言語の ui.languages を重ねたもの)
123
+ stripQuotes: () => strip,
124
+ language,
125
+ translator: src.translator ?? null,
126
+ ...(src.loadData ? { loadData: src.loadData } : {}),
127
+ };
128
+ }
@@ -0,0 +1,67 @@
1
+ import type { Args } from "./runtime.ts";
2
+ import type { Value } from "./value.ts";
3
+
4
+ /**
5
+ * 置いたままの文字(@layer-text の文字、チャットの吹き出しなど、状態の stage.extra に残る文字)を、言語を替えたときと
6
+ * 別の言語でロードしたときに、今の言語で出し直すための元。
7
+ *
8
+ * 文字を持つものは、その横に `i18n: { 名前: TextOrigin }` を置く(名前はその文字を入れておく欄。text・title・label など)。
9
+ * Runtime.retranslate が stage.extra をたどり、i18n を持つものの欄を今の言語の訳に書き換える。
10
+ * - arg: コマンドの文字(仕様で translate: "text" の引数に字面で書いたもの)
11
+ * - line: 本文の行(チャットの吹き出し。欄の文字と、ルビや装飾つきの一片 parts を作り直す)
12
+ * - option: 選択肢の文
13
+ * - speaker: 話者名と表示名(欄が label で、訳が話者と同じなら label を外す)
14
+ */
15
+ export interface TextOrigin {
16
+ kind: "arg" | "line" | "option" | "speaker";
17
+ /** 書いたファイル(speaker は無い)。 */
18
+ file?: string;
19
+ /** 原文(本文の行と選択肢は printInline で書き直したもの)。 */
20
+ source: string;
21
+ /** 場面(直前のラベル。訳のファイルの contexts)。 */
22
+ context?: string;
23
+ /** 行末の固定の行 ID(#line:ID。本文の行と選択肢。あれば ID で訳を引く)。 */
24
+ id?: string;
25
+ }
26
+
27
+ export const I18N_FIELD = "i18n";
28
+
29
+ /** 引数を読んだときの、訳す印のある文字の元(resolveArgs が付ける)。 */
30
+ const origins = new WeakMap<Args, Record<string, TextOrigin>>();
31
+
32
+ /** 引数の文字の元を控える(実行器の resolveArgs だけが使う)。 */
33
+ export function noteArgOrigin(args: Args, name: string, origin: TextOrigin): void {
34
+ let o = origins.get(args);
35
+ if (!o) origins.set(args, (o = {}));
36
+ o[name] = origin;
37
+ }
38
+
39
+ /**
40
+ * 命令の引数の、訳す印(translate: "text")のある文字の元。字面で書いた文字だけにあり、式で書いた文字には無い。
41
+ * 置いた文字を状態に残す命令は、これを i18n に入れておくと、言語を替えたときに出し直される。
42
+ */
43
+ export function argOrigin(args: Args, name: string): TextOrigin | undefined {
44
+ return origins.get(args)?.[name];
45
+ }
46
+
47
+ /** i18n を一つ作る(元の無い欄は入れない。どれも無ければ undefined)。 */
48
+ export function textOrigins(fields: Record<string, TextOrigin | undefined>): Record<string, TextOrigin> | undefined {
49
+ const out: Record<string, TextOrigin> = {};
50
+ for (const [k, v] of Object.entries(fields)) if (v) out[k] = v;
51
+ return Object.keys(out).length > 0 ? out : undefined;
52
+ }
53
+
54
+ const isRecord = (v: unknown): v is Record<string, Value> => !!v && typeof v === "object" && !Array.isArray(v);
55
+
56
+ /** stage.extra などの中で、i18n を持つものを順に渡す。 */
57
+ export function* withOrigins(value: unknown, depth = 0): Generator<{ target: Record<string, Value>; origins: Record<string, TextOrigin> }> {
58
+ if (depth > 12) return;
59
+ if (Array.isArray(value)) {
60
+ for (const v of value) yield* withOrigins(v, depth + 1);
61
+ return;
62
+ }
63
+ if (!isRecord(value)) return;
64
+ const own = value[I18N_FIELD];
65
+ if (isRecord(own)) yield { target: value, origins: own as unknown as Record<string, TextOrigin> };
66
+ for (const [k, v] of Object.entries(value)) if (k !== I18N_FIELD && v && typeof v === "object") yield* withOrigins(v, depth + 1);
67
+ }