rpg-engine 0.11.0 → 0.13.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.
Files changed (102) hide show
  1. package/README.md +1 -1
  2. package/dist/commands/effect.d.ts +1 -1
  3. package/dist/commands/shared/inputs.d.ts +2 -2
  4. package/dist/commands/shared/inputs.js +15 -2
  5. package/dist/commands/shared/page-words.d.ts +4 -0
  6. package/dist/commands/shared/page-words.js +7 -7
  7. package/dist/commands/shared/system-texts.d.ts +11 -0
  8. package/dist/commands/shared/system-texts.js +203 -0
  9. package/dist/commands/shared/world.d.ts +2 -0
  10. package/dist/commands/shared/world.js +13 -3
  11. package/dist/commands/view/view.d.ts +4 -0
  12. package/dist/commands/view/view.js +14 -3
  13. package/dist/commands/write/write.d.ts +3 -3
  14. package/dist/core/context.d.ts +16 -0
  15. package/dist/core/files.js +2 -3
  16. package/dist/core/language.d.ts +2 -0
  17. package/dist/core/language.js +8 -0
  18. package/dist/core/text.d.ts +2 -0
  19. package/dist/core/text.js +5 -0
  20. package/dist/dashboard/app.js +10 -9
  21. package/dist/dashboard/asked.js +2 -2
  22. package/dist/dashboard/dice/throw.js +2 -1
  23. package/dist/dashboard/dice/tray.js +1 -1
  24. package/dist/dashboard/guide/ar.md +2 -2
  25. package/dist/dashboard/guide/cs.md +2 -2
  26. package/dist/dashboard/guide/da.md +2 -2
  27. package/dist/dashboard/guide/de.md +2 -2
  28. package/dist/dashboard/guide/el.md +2 -2
  29. package/dist/dashboard/guide/en.md +1 -1
  30. package/dist/dashboard/guide/es.md +2 -2
  31. package/dist/dashboard/guide/fi.md +2 -2
  32. package/dist/dashboard/guide/fr.md +2 -2
  33. package/dist/dashboard/guide/he.md +2 -2
  34. package/dist/dashboard/guide/hi.md +2 -2
  35. package/dist/dashboard/guide/hu.md +2 -2
  36. package/dist/dashboard/guide/is.md +2 -2
  37. package/dist/dashboard/guide/it.md +2 -2
  38. package/dist/dashboard/guide/ja.md +2 -2
  39. package/dist/dashboard/guide/ko.md +2 -2
  40. package/dist/dashboard/guide/nb.md +2 -2
  41. package/dist/dashboard/guide/nl.md +2 -2
  42. package/dist/dashboard/guide/pl.md +2 -2
  43. package/dist/dashboard/guide/pt.md +2 -2
  44. package/dist/dashboard/guide/ro.md +2 -2
  45. package/dist/dashboard/guide/ru.md +2 -2
  46. package/dist/dashboard/guide/sv.md +2 -2
  47. package/dist/dashboard/guide/tr.md +2 -2
  48. package/dist/dashboard/guide/uk.md +2 -2
  49. package/dist/dashboard/guide/zh.md +2 -2
  50. package/dist/dashboard/i18n/ar.json +2 -1
  51. package/dist/dashboard/i18n/cs.json +2 -1
  52. package/dist/dashboard/i18n/da.json +2 -1
  53. package/dist/dashboard/i18n/de.json +2 -1
  54. package/dist/dashboard/i18n/el.json +2 -1
  55. package/dist/dashboard/i18n/es.json +2 -1
  56. package/dist/dashboard/i18n/fi.json +2 -1
  57. package/dist/dashboard/i18n/fr.json +2 -1
  58. package/dist/dashboard/i18n/he.json +2 -1
  59. package/dist/dashboard/i18n/hi.json +2 -1
  60. package/dist/dashboard/i18n/hu.json +2 -1
  61. package/dist/dashboard/i18n/is.json +2 -1
  62. package/dist/dashboard/i18n/it.json +2 -1
  63. package/dist/dashboard/i18n/ja.json +2 -1
  64. package/dist/dashboard/i18n/ko.json +2 -1
  65. package/dist/dashboard/i18n/nb.json +2 -1
  66. package/dist/dashboard/i18n/nl.json +2 -1
  67. package/dist/dashboard/i18n/pl.json +2 -1
  68. package/dist/dashboard/i18n/pt.json +2 -1
  69. package/dist/dashboard/i18n/ro.json +2 -1
  70. package/dist/dashboard/i18n/ru.json +2 -1
  71. package/dist/dashboard/i18n/sv.json +2 -1
  72. package/dist/dashboard/i18n/tr.json +2 -1
  73. package/dist/dashboard/i18n/uk.json +2 -1
  74. package/dist/dashboard/i18n/zh.json +2 -1
  75. package/dist/dashboard/journal.js +1 -1
  76. package/dist/dashboard/notices.js +9 -2
  77. package/dist/dashboard/packages/packages.js +5 -5
  78. package/dist/dashboard/packages/widgets.js +1 -1
  79. package/dist/dashboard/saves.js +1 -1
  80. package/dist/dashboard/settings.js +2 -2
  81. package/dist/dashboard/setup.js +1 -1
  82. package/dist/dashboard/text.js +7 -2
  83. package/dist/dashboard/world/lore.js +1 -1
  84. package/dist/dashboard/world/world.js +1 -1
  85. package/dist/documents/png.d.ts +2 -3
  86. package/dist/documents/png.js +6 -6
  87. package/dist/documents/read.js +2 -1
  88. package/dist/extensions/words.js +2 -1
  89. package/dist/languages/language-pack.js +2 -2
  90. package/dist/pages/index.d.ts +1 -1
  91. package/dist/pages/index.js +1 -1
  92. package/dist/pages/world.d.ts +5 -0
  93. package/dist/pages/world.js +22 -11
  94. package/dist/server/dashboard/files.js +6 -5
  95. package/dist/server/dashboard/index.d.ts +3 -1
  96. package/dist/server/dashboard/index.js +3 -1
  97. package/dist/server/mcp.js +3 -1
  98. package/dist/systems/game-system.js +2 -1
  99. package/dist/systems/words.js +2 -1
  100. package/dist/testing/index.js +1 -1
  101. package/instructions/play.md +1 -1
  102. package/package.json +12 -12
package/README.md CHANGED
@@ -42,7 +42,7 @@ A game comes as a game system, a package the master installs when you set up a c
42
42
 
43
43
  ## What you need
44
44
 
45
- **Node.js 22.4** or newer, a web browser, and an AI agent to be the master: an AI app that can work with the files on your computer, such as Claude Code or Codex. A plain chat such as claude.ai or ChatGPT, or a phone app, is not enough: the master needs to reach the campaign's files on your computer.
45
+ **Node.js 24** or newer, a web browser, and an AI agent to be the master: an AI app that can work with the files on your computer, such as Claude Code or Codex. A plain chat such as claude.ai or ChatGPT, or a phone app, is not enough: the master needs to reach the campaign's files on your computer.
46
46
 
47
47
  RPG Engine is tied to no AI company: any agent that supports MCP tools can be the master, local ones included. We play and test it with **Claude Code**; **Codex** is connected and checked, but no whole campaign has been played with it yet; [the guide](https://github.com/stefanocaronia/rpg-engine/blob/main/src/dashboard/guide/en.md#24-connect-your-ai) says how to connect any other agent. Give the master the largest model you have: a small one is easier to talk into revealing secrets or bending the rules.
48
48
 
@@ -21,7 +21,7 @@ export declare const effect: import("../core/registry.ts").Command<z.ZodObject<{
21
21
  for: z.ZodOptional<z.ZodString>;
22
22
  until: z.ZodOptional<z.ZodString>;
23
23
  by: z.ZodOptional<z.ZodString>;
24
- set: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>;
24
+ set: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodRecord<z.ZodString, z.ZodUnknown>, z.ZodPipe<z.ZodString, z.ZodTransform<string[] | Record<string, unknown>, string>>]>>;
25
25
  why: z.ZodOptional<z.ZodString>;
26
26
  }, z.core.$strip>, EffectResult>;
27
27
  export {};
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
  export declare const textList: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
4
4
  /** A whole number, as text from a command line or as a number through MCP. */
5
5
  export declare const wholeNumber: z.ZodPreprocess<z.ZodNumber, unknown>;
6
- /** Fields and their values, as field=value strings from a command line or as an object through MCP. */
7
- export declare const fieldValues: z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodRecord<z.ZodString, z.ZodUnknown>]>;
6
+ /** Fields and their values, as field=value strings from a command line or as an object through MCP; one field=value, or an object sent as JSON text, is read too. */
7
+ export declare const fieldValues: z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodRecord<z.ZodString, z.ZodUnknown>, z.ZodPipe<z.ZodString, z.ZodTransform<string[] | Record<string, unknown>, string>>]>;
8
8
  /** The texts of a textList: one text as a list of one, blank ones left out. */
9
9
  export declare function textsOf(value: string | string[] | undefined): string[];
@@ -4,9 +4,22 @@ import { z } from "zod";
4
4
  export const textList = z.union([z.string(), z.array(z.string())]);
5
5
  /** A whole number, as text from a command line or as a number through MCP. */
6
6
  export const wholeNumber = z.preprocess((value) => (typeof value === "string" && /^[+-]?\d+$/.test(value.trim()) ? Number(value) : value), z.number().int());
7
- /** Fields and their values, as field=value strings from a command line or as an object through MCP. */
8
- export const fieldValues = z.union([z.array(z.string()), z.record(z.string(), z.unknown())]);
7
+ /** Fields and their values, as field=value strings from a command line or as an object through MCP; one field=value, or an object sent as JSON text, is read too. */
8
+ export const fieldValues = z.union([z.array(z.string()), z.record(z.string(), z.unknown()), z.string().transform((text) => objectInText(text) ?? [text])]);
9
9
  /** The texts of a textList: one text as a list of one, blank ones left out. */
10
10
  export function textsOf(value) {
11
11
  return (value === undefined ? [] : typeof value === "string" ? [value] : value).filter((text) => text.trim() !== "");
12
12
  }
13
+ /** The object an MCP client sent as JSON text, such as {"bonus-ac": 5}; undefined when the text is not one. */
14
+ function objectInText(text) {
15
+ if (!text.trim().startsWith("{")) {
16
+ return undefined;
17
+ }
18
+ try {
19
+ const value = JSON.parse(text);
20
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
@@ -50,3 +50,7 @@ export declare function keepChatAnswer(home: string, page: string, language: str
50
50
  export declare function languageName(language: string): string;
51
51
  /** The game system's words in a language translated on the fly, in the player's data folder; none where it has none there. */
52
52
  export declare function homeSystemWords(home: string | undefined, system: WordsSystem, language: string): SystemWords | undefined;
53
+ /** Whether a translation is garbled: it has what a misread encoding leaves, and what it translates has not. */
54
+ export declare function isGarbled(text: string, source: string): boolean;
55
+ /** The JSON object in a writer's answer, whatever came around it; none when there is none. */
56
+ export declare function answerOf(text: string | undefined): Record<string, unknown>;
@@ -4,6 +4,7 @@
4
4
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { dirname, join } from "node:path";
6
6
  import { stringify } from "yaml";
7
+ import { codeAndBase } from "../../core/language.js";
7
8
  import { files } from "../../core/store.js";
8
9
  import { languagePackFor, packPhrases } from "../../languages/index.js";
9
10
  import { layeredSystemWords, systemContentFolders, systemWords } from "../../systems/index.js";
@@ -74,8 +75,8 @@ export function pageTranslator(context, page, notify) {
74
75
  const chatBatchSize = 160;
75
76
  /** Whether the built page in `page` ships a language: its own file, its base language's (pt-BR, pt), or English. */
76
77
  export function shipsLanguage(page, language) {
77
- const base = language.toLowerCase().split("-")[0];
78
- return base === "en" || [language.toLowerCase(), base, base === "no" ? "nb" : ""].some((code) => code !== "" && existsSync(join(page, "i18n", `${code}.json`)));
78
+ const codes = codeAndBase(language);
79
+ return codes.at(-1) === "en" || [...codes, codes.at(-1) === "no" ? "nb" : ""].some((code) => code !== "" && existsSync(join(page, "i18n", `${code}.json`)));
79
80
  }
80
81
  /** A phrase of the page in a language: a language package's, then the page's own file, by its code or its base language, then this computer's; English when none has it. */
81
82
  export function pagePhrase(context, language, phrase) {
@@ -83,10 +84,9 @@ export function pagePhrase(context, language, phrase) {
83
84
  return phrase;
84
85
  }
85
86
  const page = context.pageFolder;
86
- const code = language.toLowerCase();
87
- const base = code.split("-")[0];
87
+ const codes = codeAndBase(language);
88
88
  const pack = languagePackFor(context.extensionFolders ?? [], language);
89
- const shipped = [code, base, base === "no" ? "nb" : ""].filter((candidate) => candidate !== "").map((candidate) => readJson(join(page, "i18n", `${candidate}.json`)));
89
+ const shipped = [...codes, codes.at(-1) === "no" ? "nb" : ""].filter((candidate) => candidate !== "").map((candidate) => readJson(join(page, "i18n", `${candidate}.json`)));
90
90
  const own = context.home === undefined ? {} : readJson(join(context.home, "i18n", `${language}.json`));
91
91
  return [pack === undefined ? {} : packPhrases(pack), ...shipped, own].map((phrases) => phrases[phrase]).find((said) => typeof said === "string" && said !== "") ?? phrase;
92
92
  }
@@ -212,11 +212,11 @@ function keptOf(answer, entries) {
212
212
  // à and  before a sign of Latin-1 ("é" for "é").
213
213
  const garbledMarks = /[√∫∞∑≈∂Ω¬ƒ†∆]|·ª|[ÃÂ][ -¿]/;
214
214
  /** Whether a translation is garbled: it has what a misread encoding leaves, and what it translates has not. */
215
- function isGarbled(text, source) {
215
+ export function isGarbled(text, source) {
216
216
  return garbledMarks.test(text) && !garbledMarks.test(source);
217
217
  }
218
218
  /** The JSON object in a writer's answer, whatever came around it; none when there is none. */
219
- function answerOf(text) {
219
+ export function answerOf(text) {
220
220
  try {
221
221
  return text === undefined ? {} : JSON.parse(text.slice(text.indexOf("{"), text.lastIndexOf("}") + 1));
222
222
  }
@@ -0,0 +1,11 @@
1
+ import type { Context, SystemTexts } from "../../core/context.ts";
2
+ import { type Page, type World } from "../../pages/index.ts";
3
+ /**
4
+ * Asks for the game system's pages that these pages show the player in the campaign's language: themselves and their bases, and for a character the pages
5
+ * its fields link, as its class, its spells and its items (D-539); nothing where the system has its own translation, or nothing translates.
6
+ */
7
+ export declare function wantTexts(root: string, context: Context, world: World, shown: Page[]): void;
8
+ /** The campaign's language, when this computer is translating the game system's pages into it (D-539). */
9
+ export declare function translatingTexts(context: Context, world: World): string | undefined;
10
+ /** The game system's pages translated in the background with the player's writer (D-539); `notify` tells the pages when some have come, and when the work ends. */
11
+ export declare function systemTexts(context: Context, notify: () => void): SystemTexts;
@@ -0,0 +1,203 @@
1
+ // A game system's pages in the campaign's language where the system has no translation of its own (D-539): translated in the background on this computer,
2
+ // as the player first reads them, and kept in the player's data folder with the print of the text they come from, so that a page the system changes is
3
+ // translated again.
4
+ import { join } from "node:path";
5
+ import { stringify } from "yaml";
6
+ import { translationFolder } from "../../core/files.js";
7
+ import { codeAndBase } from "../../core/language.js";
8
+ import { files } from "../../core/store.js";
9
+ import { textPrint } from "../../core/text.js";
10
+ import { baseChain, findPage, linksIn, versionTranslations } from "../../pages/index.js";
11
+ import { answerOf, isGarbled, languageName } from "./page-words.js";
12
+ import { campaignSystem, ownTranslationFolder } from "./world.js";
13
+ // How much of the system's text goes in one request, in characters, and at most how many pages.
14
+ const batchLetters = 12_000;
15
+ const batchPages = 12;
16
+ // How long a language whose translation brought nothing waits before it is tried again, so that a writer that fails is not called at every reading.
17
+ const pause = 10 * 60 * 1000;
18
+ // How many times a page whose translation is refused is asked for in a process.
19
+ const mostTries = 2;
20
+ /**
21
+ * Asks for the game system's pages that these pages show the player in the campaign's language: themselves and their bases, and for a character the pages
22
+ * its fields link, as its class, its spells and its items (D-539); nothing where the system has its own translation, or nothing translates.
23
+ */
24
+ export function wantTexts(root, context, world, shown) {
25
+ const texts = context.texts;
26
+ const language = world.language?.trim().toLowerCase();
27
+ const system = world.system;
28
+ if (texts === undefined || system === undefined || language === undefined || codeAndBase(language).includes(system.language.toLowerCase())) {
29
+ return;
30
+ }
31
+ const found = campaignSystem(root, context);
32
+ if (found === undefined) {
33
+ return;
34
+ }
35
+ const wanted = new Map();
36
+ const add = (page) => {
37
+ for (const one of page === undefined ? [] : [page, ...baseChain(world, page)]) {
38
+ // A page of the version of the system's rules is the version's, with a translation of its own (VER-3).
39
+ const version = found.version !== undefined && files().exists(join(found.version.folder, one.path)) ? found.version : undefined;
40
+ const path = version === undefined ? one.path : join(versionTranslations(version.name), one.path);
41
+ if (one.system !== undefined && one.translated === undefined && translationFolder(version?.folder ?? found.folder, language) === undefined) {
42
+ wanted.set(path, { path, name: one.name, body: one.body });
43
+ }
44
+ }
45
+ };
46
+ for (const page of shown) {
47
+ add(page);
48
+ if (page.type === "character") {
49
+ Object.values(page.fields).flatMap(linksIn).forEach((name) => add(pageOrNone(world, name)));
50
+ }
51
+ }
52
+ if (wanted.size > 0) {
53
+ texts.want(language, { name: system.name, title: system.title }, [...wanted.values()], world.words ?? {});
54
+ }
55
+ }
56
+ /** The campaign's language, when this computer is translating the game system's pages into it (D-539). */
57
+ export function translatingTexts(context, world) {
58
+ const language = world.language?.trim().toLowerCase();
59
+ return language !== undefined && context.texts?.translating(language) === true ? language : undefined;
60
+ }
61
+ /** The game system's pages translated in the background with the player's writer (D-539); `notify` tells the pages when some have come, and when the work ends. */
62
+ export function systemTexts(context, notify) {
63
+ const waiting = new Map();
64
+ const running = new Set();
65
+ const sent = new Set();
66
+ const tries = new Map();
67
+ const stopped = new Map();
68
+ const run = async (language, write) => {
69
+ const queue = waiting.get(language) ?? new Map();
70
+ for (;;) {
71
+ const batch = nextBatch([...queue.values()]);
72
+ const writer = context.writer;
73
+ if (batch.length === 0 || writer === undefined) {
74
+ return true;
75
+ }
76
+ batch.forEach((one) => {
77
+ queue.delete(one.file);
78
+ sent.add(one.file);
79
+ });
80
+ try {
81
+ const said = await writer.write(textsBrief(language, batch));
82
+ // A writer that failed, as offline, answers nothing: no try counts, and the pages wait for the next time.
83
+ if (said === undefined) {
84
+ queue.clear();
85
+ return false;
86
+ }
87
+ const answer = answerOf(said);
88
+ batch.forEach((one) => tries.set(one.file, (tries.get(one.file) ?? 0) + 1));
89
+ const kept = batch.flatMap((one, index) => {
90
+ const translation = keptTranslation(answer[`p${index + 1}`], one.page.body);
91
+ return translation === undefined ? [] : [{ one, translation }];
92
+ });
93
+ kept.forEach(({ one, translation }) => write(one.file, translatedFile(translation, one.page.body)));
94
+ // A request that brings nothing ends the work for a while: the pages stay in the system's language.
95
+ if (kept.length === 0) {
96
+ queue.clear();
97
+ return false;
98
+ }
99
+ notify();
100
+ }
101
+ finally {
102
+ batch.forEach((one) => sent.delete(one.file));
103
+ }
104
+ }
105
+ };
106
+ return {
107
+ want: (language, system, pages, glossary) => {
108
+ const folder = ownTranslationFolder(context, system.name, language);
109
+ if (context.writer?.ready() !== true || folder === undefined) {
110
+ return;
111
+ }
112
+ const queue = waiting.get(language) ?? new Map();
113
+ waiting.set(language, queue);
114
+ for (const page of pages) {
115
+ const file = join(folder, page.path);
116
+ if (!sent.has(file) && (tries.get(file) ?? 0) < mostTries) {
117
+ queue.set(file, { file, page, system, glossary });
118
+ }
119
+ }
120
+ const resting = context.now().getTime() - (stopped.get(language) ?? -pause) < pause;
121
+ if (queue.size === 0 || running.has(language) || resting) {
122
+ return;
123
+ }
124
+ running.add(language);
125
+ // Through the store the pages are read with, so that the world reads them as they come.
126
+ const store = files();
127
+ void run(language, (file, text) => store.write(file, text))
128
+ .then((finished) => finished || stopped.set(language, context.now().getTime()), () => stopped.set(language, context.now().getTime()))
129
+ .finally(() => {
130
+ running.delete(language);
131
+ notify();
132
+ });
133
+ },
134
+ translating: (language) => running.has(language),
135
+ };
136
+ }
137
+ /** The pages of the next request, in the order they were asked: up to the letters of a batch, and always one, however long. */
138
+ function nextBatch(queue) {
139
+ const batch = [];
140
+ let letters = 0;
141
+ for (const one of queue) {
142
+ if (batch.length === batchPages || (batch.length > 0 && letters + one.page.body.length > batchLetters)) {
143
+ break;
144
+ }
145
+ batch.push(one);
146
+ letters += one.page.body.length;
147
+ }
148
+ return batch;
149
+ }
150
+ /** The request for some of a system's pages in a language, with the words of the system there that their texts use. */
151
+ function textsBrief(language, batch) {
152
+ const name = languageName(language);
153
+ const texts = batch.map((one) => one.page.body).join("\n");
154
+ const glossary = Object.fromEntries(Object.entries(batch[0].glossary).filter(([english]) => english.length > 2 && texts.includes(english)));
155
+ return [
156
+ `Translate pages of the rules of a tabletop role-playing game, the game system ${batch[0].system.title}, into ${name} (${language}), for a player who reads them while playing.`,
157
+ "- Each page is markdown: keep it as it is, its headings, lists, tables, bold and italics, and secret blocks (> [!secret]); translate the words.",
158
+ "- Keep each link [[Target]] to the same Target, untouched; you may add the words to show after a bar, as [[Target|words]].",
159
+ `- Keep numbers and dice such as 2d6+3 as they are; never convert a unit (feet stay feet), but write its name in ${name}.`,
160
+ `- Where the game has an official translation in ${name}, use its terms; else the words its players use. The glossary gives the terms the game already uses in ${name}: keep to them.`,
161
+ `- name: the page's name in ${name}, as the game's translation would call it.`,
162
+ 'Answer with a JSON object alone, from each id exactly as given to an object {"name": "…", "text": "…"}.',
163
+ "",
164
+ `Glossary: ${JSON.stringify(glossary)}`,
165
+ "",
166
+ JSON.stringify(batch.map((one, index) => ({ id: `p${index + 1}`, name: one.page.name, text: one.page.body }))),
167
+ ].join("\n");
168
+ }
169
+ /** A translation kept: a name and a text that keep the page's headings, secrets and links, and are not garbled; undefined otherwise. */
170
+ function keptTranslation(given, body) {
171
+ if (given === null || typeof given !== "object") {
172
+ return undefined;
173
+ }
174
+ const { name, text } = given;
175
+ if (typeof name !== "string" || typeof text !== "string" || name.trim() === "" || name.includes("\n") || text.trim() === "") {
176
+ return undefined;
177
+ }
178
+ const same = (pattern) => count(text, pattern) === count(body, pattern);
179
+ const kept = same(/^#{1,6}\s/gm) && same(/^>\s*\[!secret\]/gim) && linkTargets(text) === linkTargets(body) && !isGarbled(text, body);
180
+ return kept ? { name: name.trim(), text: text.trim() } : undefined;
181
+ }
182
+ // What a page translated on this computer says of itself: the system's licence goes with its text, and a translation made by an AI is no official one.
183
+ const note = "An unofficial translation made on this computer by the player's AI, from the game system's text, under that text's licence and with its attribution; the system's own text prevails.";
184
+ /** The file of a page translated on this computer: its name in the language, the print of the text it comes from, and its text. */
185
+ function translatedFile(translation, body) {
186
+ return `---\n${stringify({ name: translation.name, source: textPrint(body), note }, { lineWidth: 0 })}---\n\n${translation.text}\n`;
187
+ }
188
+ /** The pages a text links to, each once, in order of name. */
189
+ function linkTargets(text) {
190
+ return [...new Set([...text.matchAll(/\[\[([^\]|#]+)/g)].map((match) => match[1].trim()))].sort().join("|");
191
+ }
192
+ function count(text, pattern) {
193
+ return text.match(pattern)?.length ?? 0;
194
+ }
195
+ /** The page with this name, the campaign's or the system's; none where there is none, or where two of the campaign's have it. */
196
+ function pageOrNone(world, name) {
197
+ try {
198
+ return findPage(world, name);
199
+ }
200
+ catch {
201
+ return undefined;
202
+ }
203
+ }
@@ -5,6 +5,8 @@ import { type PageType, type World } from "../../pages/index.ts";
5
5
  import { type CampaignData, type GameSystem, type SystemLayer, type SystemSetting, type SystemWords } from "../../systems/index.ts";
6
6
  /** The world of the campaign in `root`, with the pages of its game system when campaign.yaml names one that is installed (SYS-1, SYS-3). */
7
7
  export declare function campaignWorld(root: string, context: Context): World;
8
+ /** The folder of a game system's pages translated on this computer into a language (D-539), in the player's data folder; none without one. */
9
+ export declare function ownTranslationFolder(context: Context, system: string, language: string): string | undefined;
8
10
  /**
9
11
  * The game system's words in the campaign's language (D-403): its own, else those translated on the fly on this computer (D-406); with the names of the
10
12
  * fields the campaign's extensions add, from their words, layered as their additions are (CAM-2, D-505).
@@ -12,15 +12,19 @@ import { campaignExtensions, extensionSources, layeredParts } from "./packages/e
12
12
  import { homeSystemWords } from "./page-words.js";
13
13
  /** The world of the campaign in `root`, with the pages of its game system when campaign.yaml names one that is installed (SYS-1, SYS-3). */
14
14
  export function campaignWorld(root, context) {
15
- // The same world until one of its pages or campaign.yaml changes: in a session, across calls (D-137). A game system does not change while the server runs.
16
- const from = [join(root, worldFolderName), join(root, campaignFileName)].map((path) => resolve(path));
15
+ // The same world until one of its pages, campaign.yaml or the system's pages translated on this computer change: in a session, across calls (D-137). A
16
+ // game system does not change while the server runs.
17
+ const from = [join(root, worldFolderName), join(root, campaignFileName), ...(context.home === undefined ? [] : [join(context.home, "systems")])].map((path) => resolve(path));
17
18
  const dependsOn = (path) => from.some((source) => source === path || isInside(source, path) || isInside(path, source));
18
19
  return files().remember(`world ${resolve(root)}`, dependsOn, () => {
19
20
  const named = readTextSetting(root, "system");
20
21
  const system = campaignSystem(root, context);
22
+ const language = readTextSetting(root, "language");
23
+ const own = system === undefined || language === undefined ? undefined : ownTranslationFolder(context, system.name, language);
21
24
  return loadWorld(root, {
22
25
  system,
23
- language: readTextSetting(root, "language"),
26
+ language,
27
+ ...(own === undefined ? {} : { ownTranslations: own }),
24
28
  words: campaignSystemWords(root, context),
25
29
  missingSystem: system === undefined ? named : undefined,
26
30
  noSystem: named === undefined,
@@ -29,6 +33,12 @@ export function campaignWorld(root, context) {
29
33
  });
30
34
  });
31
35
  }
36
+ /** The folder of a game system's pages translated on this computer into a language (D-539), in the player's data folder; none without one. */
37
+ export function ownTranslationFolder(context, system, language) {
38
+ const code = language.trim().toLowerCase();
39
+ // A language campaign.yaml writes by hand is a code, never a path out of the folder.
40
+ return context.home === undefined || !/^[a-z]{2,3}(-[a-z0-9]{2,8})*$/.test(code) ? undefined : join(context.home, "systems", system, "translations", code);
41
+ }
32
42
  /**
33
43
  * The game system's words in the campaign's language (D-403): its own, else those translated on the fly on this computer (D-406); with the names of the
34
44
  * fields the campaign's extensions add, from their words, layered as their additions are (CAM-2, D-505).
@@ -119,6 +119,8 @@ export type ViewResult = {
119
119
  problems: number;
120
120
  /** An import under way, which the dashboard tells the player (D-491 (11)). */
121
121
  importing?: ShownImport;
122
+ /** The campaign's language, when this computer is translating the game system's pages into it, which the dashboard tells the player (D-539). */
123
+ textsTranslating?: string;
122
124
  } | {
123
125
  kind: "page";
124
126
  title: string;
@@ -277,6 +279,8 @@ export declare const view: import("../../core/registry.ts").Command<z.ZodObject<
277
279
  problems: number;
278
280
  /** An import under way, which the dashboard tells the player (D-491 (11)). */
279
281
  importing?: ShownImport;
282
+ /** The campaign's language, when this computer is translating the game system's pages into it, which the dashboard tells the player (D-539). */
283
+ textsTranslating?: string;
280
284
  } | {
281
285
  kind: "page";
282
286
  title: string;
@@ -26,6 +26,7 @@ import { measuresOf } from "../shared/roads.js";
26
26
  import { campaignSaves, loadRefusal, loadRule, mayGoBack, resetPoints, resetSave, saveMode, savesWhy, wentBackTo } from "../shared/saves.js";
27
27
  import { readOpenScene } from "../shared/scene.js";
28
28
  import { counterOf, experienceNeed, experienceProgress, sheetData, sheetGroup, sheetHeadline, sheetText, statBlock, tokenIcon } from "../shared/sheet.js";
29
+ import { translatingTexts, wantTexts } from "../shared/system-texts.js";
29
30
  import { thoughtsIn, thoughtsRule, thoughtsShown } from "../shared/thoughts.js";
30
31
  import { calendarDayOf, readPresent } from "../shared/time.js";
31
32
  import { fuelLeft } from "../shared/upkeep.js";
@@ -173,6 +174,8 @@ export const view = defineCommand({
173
174
  const knownBy = part === undefined ? undefined : secret === undefined ? pageKnownBy(knowledge, page) : secretKnownBy(knowledge, page, secret);
174
175
  return { kind: "section", title: `${page.name}#${group?.name ?? reference.section}`, lines: group?.lines ?? [], text: part ?? "", ...(knownBy === undefined ? {} : { knownBy }) };
175
176
  }
177
+ // The system's pages it shows, in the campaign's language where the system has no translation (D-539).
178
+ wantTexts(root, context, world, [page]);
176
179
  return shownPage(root, context, world, knowledge, page, party);
177
180
  }
178
181
  const { coins } = campaignCoins(root, context);
@@ -238,11 +241,15 @@ export const view = defineCommand({
238
241
  const settings = readSettings(root);
239
242
  const today = now === undefined ? undefined : calendarDayOf(root, context, now.day);
240
243
  const words = system === undefined || settings.language === undefined ? undefined : systemWordsOf(root, system, settings.language, context);
244
+ const titled = withPageTitles(words, world);
245
+ // The system's pages of the party's sheets, in the campaign's language where the system has no translation (D-539).
246
+ wantTexts(root, context, world, [...players, ...companions]);
247
+ const textsTranslating = translatingTexts(context, world);
241
248
  return {
242
249
  kind: "overview",
243
250
  campaign: settings.name,
244
251
  ...(settings.language === undefined ? {} : { language: settings.language }),
245
- ...(words === undefined ? {} : { words: withPageTitles(words, world) }),
252
+ ...(titled === undefined ? {} : { words: titled }),
246
253
  ...(system === undefined || Object.keys(system.sheetVerbs).length === 0 ? {} : { verbs: system.sheetVerbs }),
247
254
  ...(system === undefined ? {} : { system: { name: system.name, title: system.title, ...(system.attribution === undefined ? {} : { attribution: system.attribution }) } }),
248
255
  ...(now === undefined ? {} : { now: formatGameDate(now) }),
@@ -261,6 +268,7 @@ export const view = defineCommand({
261
268
  rollsTotal: shownRolls.length,
262
269
  problems: campaignProblems(root, world, context).length,
263
270
  ...(importing === undefined ? {} : { importing }),
271
+ ...(textsTranslating === undefined ? {} : { textsTranslating }),
264
272
  };
265
273
  },
266
274
  format(result) {
@@ -349,10 +357,13 @@ function shownPage(root, context, world, knowledge, page, party) {
349
357
  ...(story === undefined ? {} : { story }),
350
358
  };
351
359
  }
352
- /** The system's words for the page, with the names its translation gives its pages, as Palla di fuoco for Fireball, where its words do not name them (D-542). */
360
+ /**
361
+ * The system's words for the page, with the names its translation gives its pages, as Palla di fuoco for Fireball, where its words do not name them (D-542):
362
+ * those translated on this computer too, where the system has no words in the language (D-539).
363
+ */
353
364
  function withPageTitles(words, world) {
354
365
  const titles = Object.fromEntries((world.system?.pages ?? []).flatMap((page) => (page.title === undefined ? [] : [[page.name, page.title]])));
355
- return Object.keys(titles).length === 0 ? words : { ...words, words: { ...titles, ...words.words } };
366
+ return Object.keys(titles).length === 0 ? words : { groups: {}, fields: {}, ...words, words: { ...titles, ...words?.words } };
356
367
  }
357
368
  /** "Known to Bruna alone: Ettore plays as not knowing it, though all at the screen may read it.": who knows a page, and how the others are played (VIEW-12). */
358
369
  function whoKnowsText(who, unaware) {
@@ -39,10 +39,10 @@ export declare const write: import("../../core/registry.ts").Command<z.ZodObject
39
39
  event: "event";
40
40
  topic: "topic";
41
41
  }>>;
42
- set: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>;
42
+ set: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodRecord<z.ZodString, z.ZodUnknown>, z.ZodPipe<z.ZodString, z.ZodTransform<string[] | Record<string, unknown>, string>>]>>;
43
43
  unset: z.ZodOptional<z.ZodArray<z.ZodString>>;
44
- add: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>;
45
- remove: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>;
44
+ add: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodRecord<z.ZodString, z.ZodUnknown>, z.ZodPipe<z.ZodString, z.ZodTransform<string[] | Record<string, unknown>, string>>]>>;
45
+ remove: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodRecord<z.ZodString, z.ZodUnknown>, z.ZodPipe<z.ZodString, z.ZodTransform<string[] | Record<string, unknown>, string>>]>>;
46
46
  text: z.ZodOptional<z.ZodString>;
47
47
  section: z.ZodOptional<z.ZodString>;
48
48
  append: z.ZodOptional<z.ZodBoolean>;
@@ -75,6 +75,8 @@ export interface Context {
75
75
  pictures?: PictureMaker;
76
76
  /** What writes text from a brief on this computer, outside the chat, as Codex or Claude Code with the player's login (D-406); missing where none can. */
77
77
  writer?: TextWriter;
78
+ /** A game system's pages translated on this computer as a player first reads them, where the system has no translation of its own (D-539); missing elsewhere. */
79
+ texts?: SystemTexts;
78
80
  /** What reads the player's documents outside the chat (D-489 (1)): none where no helper is ready, and in tests. */
79
81
  reader?: DocumentReader;
80
82
  /** The OCR of the player's system, which reads pages of a PDF without readable text from their pictures (LIB-4): by page number, those it read; none where there is none. */
@@ -95,6 +97,20 @@ export interface Context {
95
97
  /** Codex and Claude Code on this computer, installed and signed in with the player's yes (D-424); missing outside the MCP server, as in tests. */
96
98
  helpers?: Helpers;
97
99
  }
100
+ /** A game system's pages a player reads, translated into the campaign's language in the background where they lack it (D-539). */
101
+ export interface SystemTexts {
102
+ /** Asks for these pages of a system in a language, with the system's words there as a glossary; those translated or on their way are left. */
103
+ want(language: string, system: {
104
+ name: string;
105
+ title: string;
106
+ }, pages: {
107
+ path: string;
108
+ name: string;
109
+ body: string;
110
+ }[], glossary: Record<string, string>): void;
111
+ /** Whether pages are being translated into a language now. */
112
+ translating(language: string): boolean;
113
+ }
98
114
  /** A package for rpg-engine as npm or its folder describes it (D-439): its name, version and kind, and what it is. */
99
115
  export interface PackageInfo {
100
116
  name: string;
@@ -1,6 +1,7 @@
1
1
  // The files of a folder and of the folders inside it, listed one folder at a time: listing a whole tree at once looks at every file again on Windows (D-194).
2
2
  import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
3
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
+ import { codeAndBase } from "./language.js";
4
5
  /** The full paths of `folder` and of the folders inside it, however deep; none when there is no such folder. */
5
6
  export function foldersIn(folder) {
6
7
  const folders = existsSync(folder) && statSync(folder).isDirectory() ? [folder] : [];
@@ -36,9 +37,7 @@ export function fileOrder(first, second) {
36
37
  }
37
38
  /** Where a game system keeps its text in a language, translations/it, by the language's code or its base one (D-542); undefined when it has none. */
38
39
  export function translationFolder(folder, language) {
39
- const code = language?.trim().toLowerCase();
40
- const codes = code === undefined || code === "" ? [] : [...new Set([code, code.split("-")[0]])];
41
- return codes.map((one) => join(folder, "translations", one)).find((path) => existsSync(path) && statSync(path).isDirectory());
40
+ return codeAndBase(language ?? "").map((one) => join(folder, "translations", one)).find((path) => existsSync(path) && statSync(path).isDirectory());
42
41
  }
43
42
  /**
44
43
  * The folders of the packages in these folders of npm's, in their scopes' folders too (@rpgengine/weather), links to folders included, as npm links a package
@@ -0,0 +1,2 @@
1
+ /** A language's code, then its base's where the base is written in the same script, both in lower case: pt-br and pt; zh-tw alone, as zh is simplified. */
2
+ export declare function codeAndBase(code: string): string[];
@@ -0,0 +1,8 @@
1
+ // Chinese in traditional characters, whose base zh is the simplified.
2
+ const traditionalChinese = /^zh-(hant|tw|hk|mo)(-|$)/;
3
+ /** A language's code, then its base's where the base is written in the same script, both in lower case: pt-br and pt; zh-tw alone, as zh is simplified. */
4
+ export function codeAndBase(code) {
5
+ const own = code.trim().toLowerCase();
6
+ const base = own.split("-")[0];
7
+ return own === "" ? [] : traditionalChinese.test(own) || base === own ? [own] : [own, base];
8
+ }
@@ -4,6 +4,8 @@ export declare function comparableText(text: string): string;
4
4
  export declare function wordCount(text: string): number;
5
5
  /** How long a text is, in words: a Chinese, Japanese or Korean letter counts as one, as a model reads it; else about six letters a word. */
6
6
  export declare function textSize(text: string): number;
7
+ /** A short print of a text, which changes when the text does: a translation keeps the print of the text it was made from. */
8
+ export declare function textPrint(text: string): string;
7
9
  /** The first sentence of a text, up to its first ". ", as the help and the commands' reference give a command's description. */
8
10
  export declare function firstSentence(text: string): string;
9
11
  /** A noun with its article, as messages write it: "a character", "an item". */
package/dist/core/text.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { rememberedByText } from "./memo.js";
2
3
  /** A name as it is compared: any case, accents written either way (NFC) and a curly apostrophe as a straight one (SYS-5), so that "Città" from any system matches "città". */
3
4
  export function comparableText(text) {
@@ -14,6 +15,10 @@ export function textSize(text) {
14
15
  const letters = text.match(/[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]/gu)?.length ?? 0;
15
16
  return Math.max(wordCount(text) + letters, Math.ceil(text.length / 6));
16
17
  }
18
+ /** A short print of a text, which changes when the text does: a translation keeps the print of the text it was made from. */
19
+ export function textPrint(text) {
20
+ return createHash("sha256").update(text, "utf8").digest("hex").slice(0, 16);
21
+ }
17
22
  /** The first sentence of a text, up to its first ". ", as the help and the commands' reference give a command's description. */
18
23
  export function firstSentence(text) {
19
24
  const end = text.indexOf(". ");
@@ -60,11 +60,11 @@ function App() {
60
60
  const [address, setAddress] = useState(() => readAddress(window.location.hash));
61
61
  const reading = useRef(0);
62
62
  // Whose sheet the Party section opened by itself, kept until the address changes.
63
- const opened = useRef();
63
+ const opened = useRef(undefined);
64
64
  // Whose card the player chose at hand in a fight, with more than one player character (D-480 (7)): kept through that turn alone.
65
- const handed = useRef();
65
+ const handed = useRef(undefined);
66
66
  // The rolls already read, from the first reading on: a check rolled after it is thrown on the page; the rolls new since come into the list as new.
67
- const seen = useRef();
67
+ const seen = useRef(undefined);
68
68
  const [thrown, setThrown] = useState();
69
69
  // The roll whose dice are in the air: its line comes into the rolls only as they go (D-300).
70
70
  const [held, setHeld] = useState();
@@ -73,13 +73,13 @@ function App() {
73
73
  const rollsAsked = useRef(firstRolls);
74
74
  // The robot's face for a moment (D-305): the master's last moment once it is new, or a new roll's reaction, whichever came last.
75
75
  const [moment, setMoment] = useState();
76
- const toldMoment = useRef();
76
+ const toldMoment = useRef(undefined);
77
77
  // A number of the sheet rolled for fun, from its explanation (D-280): each a throw of its own, even of the same number.
78
78
  const [sheetThrow, setSheetThrow] = useState();
79
79
  // The question answered from the sheet or the tray, while the engine rolls it (D-330); the free rolls, in this browser alone.
80
80
  const [answering, setAnswering] = useState();
81
81
  // The roll that answers a card, or a die of a rest, while its dice fly: what it changes of the sheet waits for them (D-461).
82
- const holding = useRef();
82
+ const holding = useRef(undefined);
83
83
  const [free, setFree] = useState([]);
84
84
  // On a wide screen the table stands beside the page, unless the player folded it; folded, or under that width, the turns and the followed quest go back to
85
85
  // the page.
@@ -110,13 +110,13 @@ function App() {
110
110
  const widgetReading = useRef({ asked: 0, shown: 0 });
111
111
  const moduleReading = useRef({ asked: 0, shown: 0 });
112
112
  // The card of a package's question as last read, even while the dice that changed it fly; the attempts the player let go, with the question then (D-507).
113
- const packNow = useRef();
113
+ const packNow = useRef(undefined);
114
114
  const packsGone = useRef(new Map());
115
115
  // In the card of a rest's dice, how many dice were rolled as the player pressed one, until its roll lands.
116
- const restSent = useRef();
116
+ const restSent = useRef(undefined);
117
117
  // The widgets as read while a card's dice fly, which show only once they land, as the rest of what the roll changed: a panel on the party never tells the
118
118
  // outcome of a death save before its die (D-461).
119
- const widgetsHeld = useRef();
119
+ const widgetsHeld = useRef(undefined);
120
120
  // Reads view again for whom the address names, or the player character the master calls, and what the master asks; an answer that comes after a newer one
121
121
  // is left out.
122
122
  const read = async () => {
@@ -259,6 +259,7 @@ function App() {
259
259
  noCharacter: overview.kind === "none",
260
260
  problems: overview.kind === "overview" ? overview.problems : undefined,
261
261
  importing: overview.kind === "overview" || overview.kind === "none" ? overview.importing : undefined,
262
+ textsTranslating: overview.kind === "overview" ? overview.textsTranslating : undefined,
262
263
  }, holding.current !== undefined));
263
264
  }
264
265
  }
@@ -592,7 +593,7 @@ function App() {
592
593
  ? [{ kind: "away", text: t("Not connected: the sheet as of {time}. It comes back when the game does.", { time: shown.readAt.toLocaleTimeString(pageLocale(), { hour: "2-digit", minute: "2-digit" }) }) }]
593
594
  : []),
594
595
  ...(shown.noCharacter && !inSetup ? [{ kind: "info", text: t("There is no player character yet: the sheet comes when the master writes one.") }] : []),
595
- ...gameNotices(shown.problems),
596
+ ...gameNotices(shown.problems, shown.textsTranslating),
596
597
  // In the setup an import under way is with the page's other notices, in the column of its card (D-491 (11)).
597
598
  ...(inSetup ? importNotices(shown.importing) : []),
598
599
  ];