rpg-engine 0.21.0 → 0.22.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 (117) hide show
  1. package/dist/campaign/host-files.js +4 -1
  2. package/dist/campaign/index.d.ts +2 -1
  3. package/dist/campaign/index.js +2 -1
  4. package/dist/campaign/port.d.ts +6 -0
  5. package/dist/campaign/port.js +24 -0
  6. package/dist/campaign/settings.d.ts +17 -0
  7. package/dist/campaign/settings.js +24 -1
  8. package/dist/cli/cli.js +15 -0
  9. package/dist/commands/config/config.js +15 -1
  10. package/dist/commands/config/dashboard.d.ts +4 -0
  11. package/dist/commands/config/dashboard.js +37 -6
  12. package/dist/commands/config/shown.js +4 -0
  13. package/dist/commands/config/words.d.ts +3 -1
  14. package/dist/commands/config/words.js +28 -1
  15. package/dist/commands/mode.d.ts +1 -1
  16. package/dist/commands/package/data.js +27 -0
  17. package/dist/commands/package/theme.js +2 -1
  18. package/dist/commands/scene/scene.js +6 -1
  19. package/dist/commands/shared/books/adventures.d.ts +1 -0
  20. package/dist/commands/shared/books/adventures.js +1 -1
  21. package/dist/commands/shared/campaign/git.d.ts +25 -0
  22. package/dist/commands/shared/campaign/git.js +104 -0
  23. package/dist/commands/shared/campaign/saves.js +5 -1
  24. package/dist/commands/shared/packages/catalog.js +24 -5
  25. package/dist/commands/status.d.ts +1 -0
  26. package/dist/commands/status.js +8 -4
  27. package/dist/core/context.d.ts +2 -0
  28. package/dist/core/version.d.ts +2 -0
  29. package/dist/core/version.js +5 -0
  30. package/dist/dashboard/guide/ar.md +6 -4
  31. package/dist/dashboard/guide/cs.md +6 -4
  32. package/dist/dashboard/guide/da.md +6 -4
  33. package/dist/dashboard/guide/de.md +8 -6
  34. package/dist/dashboard/guide/el.md +6 -4
  35. package/dist/dashboard/guide/en.md +5 -3
  36. package/dist/dashboard/guide/es.md +6 -4
  37. package/dist/dashboard/guide/fi.md +6 -4
  38. package/dist/dashboard/guide/fr.md +6 -4
  39. package/dist/dashboard/guide/he.md +6 -4
  40. package/dist/dashboard/guide/hi.md +6 -4
  41. package/dist/dashboard/guide/hu.md +6 -4
  42. package/dist/dashboard/guide/is.md +6 -4
  43. package/dist/dashboard/guide/it.md +6 -4
  44. package/dist/dashboard/guide/ja.md +7 -5
  45. package/dist/dashboard/guide/ko.md +6 -4
  46. package/dist/dashboard/guide/nb.md +7 -5
  47. package/dist/dashboard/guide/nl.md +6 -4
  48. package/dist/dashboard/guide/pl.md +6 -4
  49. package/dist/dashboard/guide/pt.md +6 -4
  50. package/dist/dashboard/guide/ro.md +6 -4
  51. package/dist/dashboard/guide/ru.md +6 -4
  52. package/dist/dashboard/guide/sv.md +6 -4
  53. package/dist/dashboard/guide/tr.md +6 -4
  54. package/dist/dashboard/guide/uk.md +6 -4
  55. package/dist/dashboard/guide/zh.md +6 -4
  56. package/dist/dashboard/i18n/ar.json +25 -0
  57. package/dist/dashboard/i18n/cs.json +25 -0
  58. package/dist/dashboard/i18n/da.json +25 -0
  59. package/dist/dashboard/i18n/de.json +25 -0
  60. package/dist/dashboard/i18n/el.json +25 -0
  61. package/dist/dashboard/i18n/es.json +25 -0
  62. package/dist/dashboard/i18n/fi.json +25 -0
  63. package/dist/dashboard/i18n/fr.json +25 -0
  64. package/dist/dashboard/i18n/he.json +25 -0
  65. package/dist/dashboard/i18n/hi.json +25 -0
  66. package/dist/dashboard/i18n/hu.json +25 -0
  67. package/dist/dashboard/i18n/is.json +25 -0
  68. package/dist/dashboard/i18n/it.json +25 -0
  69. package/dist/dashboard/i18n/ja.json +25 -0
  70. package/dist/dashboard/i18n/ko.json +25 -0
  71. package/dist/dashboard/i18n/nb.json +25 -0
  72. package/dist/dashboard/i18n/nl.json +25 -0
  73. package/dist/dashboard/i18n/pl.json +25 -0
  74. package/dist/dashboard/i18n/pt.json +25 -0
  75. package/dist/dashboard/i18n/ro.json +25 -0
  76. package/dist/dashboard/i18n/ru.json +25 -0
  77. package/dist/dashboard/i18n/sv.json +25 -0
  78. package/dist/dashboard/i18n/tr.json +25 -0
  79. package/dist/dashboard/i18n/uk.json +25 -0
  80. package/dist/dashboard/i18n/zh.json +25 -0
  81. package/dist/dashboard/packages/installed.js +2 -2
  82. package/dist/dashboard/packages/packages.js +1 -1
  83. package/dist/dashboard/parts/labels.js +7 -0
  84. package/dist/dashboard/settings/settings.js +33 -6
  85. package/dist/dashboard/shell/system-style.js +89 -5
  86. package/dist/dashboard/shell/tooltip.js +5 -4
  87. package/dist/dashboard/style.css +234 -81
  88. package/dist/git/git.d.ts +12 -0
  89. package/dist/git/git.js +175 -0
  90. package/dist/git/ignore.d.ts +2 -0
  91. package/dist/git/ignore.js +16 -0
  92. package/dist/git/index.d.ts +2 -0
  93. package/dist/git/index.js +2 -0
  94. package/dist/importer/index.d.ts +1 -1
  95. package/dist/importer/index.js +1 -1
  96. package/dist/languages/pack.js +2 -1
  97. package/dist/server/bell-listener.d.ts +2 -1
  98. package/dist/server/bell-listener.js +10 -41
  99. package/dist/server/dashboard/files.d.ts +3 -2
  100. package/dist/server/dashboard/files.js +44 -15
  101. package/dist/server/dashboard/index.d.ts +15 -2
  102. package/dist/server/dashboard/index.js +52 -22
  103. package/dist/server/dashboard/news.d.ts +3 -2
  104. package/dist/server/dashboard/news.js +19 -5
  105. package/dist/server/dashboard/ports.d.ts +17 -2
  106. package/dist/server/dashboard/ports.js +60 -4
  107. package/dist/server/mcp.d.ts +3 -2
  108. package/dist/server/mcp.js +55 -11
  109. package/dist/themes/css.d.ts +1 -1
  110. package/dist/themes/css.js +101 -2
  111. package/dist/themes/index.d.ts +1 -1
  112. package/dist/themes/index.js +1 -1
  113. package/dist/themes/theme.d.ts +34 -3
  114. package/dist/themes/theme.js +176 -19
  115. package/instructions/core.md +1 -0
  116. package/instructions/dashboard-guide.md +1 -1
  117. package/package.json +1 -1
@@ -0,0 +1,12 @@
1
+ /** Whether `folder` is inside a git repository: it, or a folder above it, holds a .git. Git itself need not be installed. */
2
+ export declare function isRepository(folder: string): boolean;
3
+ /** The folder of the repository `folder` is in, the one that holds the .git: it or one above it; undefined outside any. */
4
+ export declare function repositoryRoot(folder: string): string | undefined;
5
+ /**
6
+ * Commits every change under `folder`, and only there, with `message`, `left` (paths in it) taken out of the repository but left on the disk: true when there
7
+ * was a change, false when there was none. The commit is made on an index of its own, so that what the player staged elsewhere stays staged and out of it;
8
+ * then the repository's index follows it under `folder`. It throws with git's words.
9
+ */
10
+ export declare function commitFolder(folder: string, message: string, left?: string[]): Promise<boolean>;
11
+ /** Pushes the branch of the repository of `folder` to where it is pushed. It throws with git's words. */
12
+ export declare function push(folder: string): Promise<void>;
@@ -0,0 +1,175 @@
1
+ // Git in a folder, through the git of this computer: whether the folder is in a repository, a commit of its changes, a push. It never asks anything: a git
2
+ // that would ask for a password or a passphrase fails instead, and says why.
3
+ import { spawn } from "node:child_process";
4
+ import { randomUUID } from "node:crypto";
5
+ import { existsSync, rmSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { dirname, join, resolve } from "node:path";
8
+ /** Whether `folder` is inside a git repository: it, or a folder above it, holds a .git. Git itself need not be installed. */
9
+ export function isRepository(folder) {
10
+ return repositoryRoot(folder) !== undefined;
11
+ }
12
+ /** The folder of the repository `folder` is in, the one that holds the .git: it or one above it; undefined outside any. */
13
+ export function repositoryRoot(folder) {
14
+ for (let current = resolve(folder);; current = dirname(current)) {
15
+ // A folder, or a file in a worktree or a submodule.
16
+ if (existsSync(join(current, ".git"))) {
17
+ return current;
18
+ }
19
+ if (dirname(current) === current) {
20
+ return undefined;
21
+ }
22
+ }
23
+ }
24
+ /**
25
+ * Commits every change under `folder`, and only there, with `message`, `left` (paths in it) taken out of the repository but left on the disk: true when there
26
+ * was a change, false when there was none. The commit is made on an index of its own, so that what the player staged elsewhere stays staged and out of it;
27
+ * then the repository's index follows it under `folder`. It throws with git's words.
28
+ */
29
+ export async function commitFolder(folder, message, left = []) {
30
+ const own = { GIT_INDEX_FILE: join(tmpdir(), `rpg-git-index-${randomUUID()}`) };
31
+ try {
32
+ const before = await hasCommits(folder);
33
+ if (before) {
34
+ await git(folder, ["read-tree", "HEAD"], own);
35
+ }
36
+ await stageFolder(folder, left, own);
37
+ // The changes to HEAD, or in a repository with no commit yet whatever is staged.
38
+ const changes = await git(folder, before ? ["diff", "--cached", "--name-only"] : ["ls-files"], own);
39
+ if (changes.trim() === "") {
40
+ return false;
41
+ }
42
+ await git(folder, ["commit", "--quiet", "--message", message], own);
43
+ }
44
+ finally {
45
+ rmSync(own.GIT_INDEX_FILE, { force: true });
46
+ }
47
+ await stageFolder(folder, left);
48
+ return true;
49
+ }
50
+ /** Pushes the branch of the repository of `folder` to where it is pushed. It throws with git's words. */
51
+ export async function push(folder) {
52
+ // A branch with no upstream yet gets the one of its name, as the player's first git push -u would.
53
+ await git(folder, ["-c", "push.autoSetupRemote=true", "push", "--quiet"], await sshVariables(folder));
54
+ }
55
+ /** The ssh of the player, as GIT_SSH_COMMAND, GIT_SSH or core.sshCommand say, else ssh that never asks for a passphrase. */
56
+ async function sshVariables(folder) {
57
+ if (process.env.GIT_SSH_COMMAND !== undefined || process.env.GIT_SSH !== undefined) {
58
+ return {};
59
+ }
60
+ try {
61
+ const own = (await git(folder, ["config", "--get", "core.sshCommand"])).trim();
62
+ if (own !== "") {
63
+ // Their command kept; BatchMode only where it is OpenSSH's.
64
+ return { GIT_SSH_COMMAND: /(^|[\\/])ssh(\.exe)?"?(\s|$)/i.test(own) ? `${own} -o BatchMode=yes` : own };
65
+ }
66
+ }
67
+ catch {
68
+ // Unset: git says so with a failure.
69
+ }
70
+ return { GIT_SSH_COMMAND: "ssh -o BatchMode=yes" };
71
+ }
72
+ /** Stages every change under `folder`, `left` taken out, on the index `variables` name, or the repository's. */
73
+ async function stageFolder(folder, left, variables = {}) {
74
+ await git(folder, ["add", "--all", "--", "."], variables);
75
+ if (left.length > 0) {
76
+ await git(folder, ["rm", "-r", "--cached", "--quiet", "--ignore-unmatch", "--", ...left], variables);
77
+ }
78
+ }
79
+ async function hasCommits(folder) {
80
+ try {
81
+ await git(folder, ["rev-parse", "--verify", "--quiet", "HEAD"]);
82
+ return true;
83
+ }
84
+ catch {
85
+ return false;
86
+ }
87
+ }
88
+ // How long git may take before it is stopped: a push that waits on a network or on a question never answers.
89
+ const longest = 120_000;
90
+ // What a git that another git holds says: tried once more a moment later.
91
+ const heldByAnother = /index\.lock|cannot lock ref/i;
92
+ /** What git printed, or an error with what it said and how to fix it when it failed, could not start or took too long; once again when another git held it. */
93
+ async function git(folder, args, variables = {}) {
94
+ try {
95
+ return await gitOnce(folder, args, variables);
96
+ }
97
+ catch (error) {
98
+ if (!(error instanceof Error) || !heldByAnother.test(error.message)) {
99
+ throw error;
100
+ }
101
+ await new Promise((done) => setTimeout(done, 500));
102
+ return gitOnce(folder, args, variables);
103
+ }
104
+ }
105
+ function gitOnce(folder, args, variables) {
106
+ return new Promise((done, fail) => {
107
+ // core.askPass emptied too: an askpass is a program that asks.
108
+ const child = spawn("git", ["-c", "core.askPass=", ...args], { cwd: folder, env: { ...quietEnvironment(), ...variables }, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
109
+ let out = "";
110
+ let said = "";
111
+ let settled = false;
112
+ const settle = (work) => {
113
+ if (!settled) {
114
+ settled = true;
115
+ clearTimeout(timer);
116
+ work();
117
+ }
118
+ };
119
+ // A git stopped answers at once: its hooks, ssh or the remote's helper may keep its pipes open long after.
120
+ const timer = setTimeout(() => {
121
+ stopTree(child.pid);
122
+ child.stdout.destroy();
123
+ child.stderr.destroy();
124
+ settle(() => fail(new Error(`git ${args[0]} took longer than ${longest / 60_000} minutes and was stopped: look at the network, or at a hook of the repository that waits.`)));
125
+ }, longest);
126
+ child.stdout.on("data", (chunk) => (out += chunk.toString("utf8")));
127
+ child.stderr.on("data", (chunk) => (said += chunk.toString("utf8")));
128
+ child.on("error", (error) => settle(() => fail(new Error(`git could not start (${error.message}): install git, or turn git off in the settings.`))));
129
+ child.on("close", (code) => settle(() => (code === 0 ? done(out) : fail(new Error(gitFailure(said || out, args[0]))))));
130
+ });
131
+ }
132
+ /** What git said when it failed, its errors and hints, with our own fix for the failures a player meets most. */
133
+ function gitFailure(said, command) {
134
+ if (/please tell me who you are|author identity unknown/i.test(said)) {
135
+ return 'git does not know who commits: run git config user.name "Your Name" and git config user.email "you@example.com" in the campaign\'s folder.';
136
+ }
137
+ if (/could not read (username|password)|cannot prompt|terminal prompts disabled|permission denied \(publickey|authentication failed/i.test(said)) {
138
+ return "git has no credentials for the remote: run git push once from a terminal in the campaign's folder and sign in; then the engine pushes with what git keeps.";
139
+ }
140
+ if (/has no upstream branch/i.test(said)) {
141
+ return "the branch has no upstream yet: run git push -u origin with the branch's name once in the campaign's folder.";
142
+ }
143
+ if (/no configured push destination|does not appear to be a git repository/i.test(said)) {
144
+ return "the repository has no remote to push to: add one with git remote add origin and its address, or choose commit alone in the settings.";
145
+ }
146
+ const lines = said.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "");
147
+ const told = lines.filter((line) => /^(fatal|error|hint):/i.test(line));
148
+ return (told.length > 0 ? told : lines.slice(0, 6)).join(" ") || `git ${command} stopped`;
149
+ }
150
+ /** Stops a process and every process it started: on Windows by its tree, elsewhere by a kill its children see as their pipes close. */
151
+ function stopTree(pid) {
152
+ if (pid === undefined) {
153
+ return;
154
+ }
155
+ if (process.platform === "win32") {
156
+ spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }).on("error", () => undefined);
157
+ return;
158
+ }
159
+ try {
160
+ process.kill(pid, "SIGKILL");
161
+ }
162
+ catch {
163
+ // Already gone.
164
+ }
165
+ }
166
+ /** The environment of git: the one of this process, with every question it could ask turned into a failure. */
167
+ function quietEnvironment() {
168
+ return {
169
+ ...process.env,
170
+ GIT_TERMINAL_PROMPT: "0",
171
+ GCM_INTERACTIVE: "never",
172
+ GIT_ASKPASS: "",
173
+ SSH_ASKPASS: "",
174
+ };
175
+ }
@@ -0,0 +1,2 @@
1
+ /** The text of a .gitignore, or none, with the engine's block holding `lines`: in place of the block it had, else after its own lines. */
2
+ export declare function withIgnoreBlock(text: string | undefined, lines: string[]): string;
@@ -0,0 +1,16 @@
1
+ // The engine's block of a .gitignore: its lines between two marks, which it writes again whole; the lines around it are the player's and stay as they are.
2
+ const begin = "# rpg-engine: begin (written by rpg-engine; your own lines go outside this block)";
3
+ const end = "# rpg-engine: end";
4
+ /** The text of a .gitignore, or none, with the engine's block holding `lines`: in place of the block it had, else after its own lines. */
5
+ export function withIgnoreBlock(text, lines) {
6
+ const newline = text?.includes("\r\n") === true ? "\r\n" : "\n";
7
+ const block = [begin, ...lines, end].join(newline);
8
+ const kept = (text ?? "").split(/\r?\n/);
9
+ const from = kept.indexOf(begin);
10
+ const to = kept.indexOf(end, from);
11
+ if (from !== -1 && to !== -1) {
12
+ return [...kept.slice(0, from), block, ...kept.slice(to + 1)].join(newline);
13
+ }
14
+ const before = (text ?? "").replace(/(\r?\n)*$/, "");
15
+ return before === "" ? `${block}${newline}` : `${before}${newline}${newline}${block}${newline}`;
16
+ }
@@ -0,0 +1,2 @@
1
+ export { commitFolder, isRepository, push, repositoryRoot } from "./git.ts";
2
+ export { withIgnoreBlock } from "./ignore.ts";
@@ -0,0 +1,2 @@
1
+ export { commitFolder, isRepository, push, repositoryRoot } from "./git.js";
2
+ export { withIgnoreBlock } from "./ignore.js";
@@ -1 +1 @@
1
- export { beginOpening, claimImport, clearOpening, doneImports, dropDocumentText, dropImport, finishAdventure, hasImport, importAge, importDate, importedPages, type ImportedText, importFile, importFolder, importPiece, type ImportStart, importStarts, type ImportState, importStyle, isOwnOpening, markOpening, openImport, type OpeningImport, openingImport, openLicense, pieceName, prepareImport, readImportState, releaseImport, runElsewhere, writeImportState, } from "./work.ts";
1
+ export { beginOpening, claimImport, clearOpening, doneImports, dropDocumentText, dropImport, finishAdventure, hasImport, importAge, importDate, importedPages, type ImportedText, importFile, importFolder, importPiece, importsFolderName, type ImportStart, importStarts, type ImportState, importStyle, isOwnOpening, markOpening, openImport, type OpeningImport, openingImport, openLicense, pieceName, prepareImport, readImportState, releaseImport, runElsewhere, writeImportState, } from "./work.ts";
@@ -1,3 +1,3 @@
1
1
  // The importer's folder (D-489): the player's document in pieces, how far the import is, and the adventure the helper writes. Depends on nothing else in
2
2
  // rpg-engine.
3
- export { beginOpening, claimImport, clearOpening, doneImports, dropDocumentText, dropImport, finishAdventure, hasImport, importAge, importDate, importedPages, importFile, importFolder, importPiece, importStarts, importStyle, isOwnOpening, markOpening, openImport, openingImport, openLicense, pieceName, prepareImport, readImportState, releaseImport, runElsewhere, writeImportState, } from "./work.js";
3
+ export { beginOpening, claimImport, clearOpening, doneImports, dropDocumentText, dropImport, finishAdventure, hasImport, importAge, importDate, importedPages, importFile, importFolder, importPiece, importsFolderName, importStarts, importStyle, isOwnOpening, markOpening, openImport, openingImport, openLicense, pieceName, prepareImport, readImportState, releaseImport, runElsewhere, writeImportState, } from "./work.js";
@@ -10,7 +10,8 @@ const codePattern = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
10
10
  const languageSchema = z.object({
11
11
  code: z.string().regex(codePattern, "a language's code, such as de or pt-PT").refine((code) => code.split("-")[0] !== "en", "English is the page's own"),
12
12
  name: z.string().trim().min(1),
13
- engine: z.string().optional(),
13
+ // The lowest rpg-engine that reads it, such as "0.22": checked as one of data alone is installed.
14
+ engine: z.string({ error: 'engine is written in quotes, as engine: "0.22": without them YAML reads 0.30 as the number 0.3' }).regex(/^\d+(\.\d+){0,2}$/, 'engine is the lowest rpg-engine version, such as "0.22", not a range').optional(),
14
15
  // Its version, for a package of data alone, which has no package.json to say it.
15
16
  version: z.union([z.string(), z.number()]).transform(String).optional(),
16
17
  }).strict();
@@ -4,6 +4,7 @@ export declare const bellLine = "The player acted on the dashboard: call status
4
4
  export declare function listenHere(): Promise<void>;
5
5
  /**
6
6
  * Waits at the dashboard of the hook's chat until the player says a sentence: true then; false when there is none to wait at, or it goes away. The chat's own
7
- * server is the one with its session; after /clear, which gives the hook a new one, the only server of its campaign.
7
+ * server is the one with its session; after /clear, which gives the hook a new one, the only server of its campaign, while no other chat waits there for the
8
+ * page (D-577): better no ring than one in a chat that cannot read the page.
8
9
  */
9
10
  export declare function waitForBell(input: string, ports?: number[]): Promise<boolean>;
@@ -1,9 +1,8 @@
1
1
  // Claude Code's doorbell for the player's sentences on the dashboard (D-495): `rpg --listen`, the Stop hook init writes, waits at the dashboard of its own
2
2
  // chat and, when the player says a sentence, tells the chat to call status. It never carries the sentence, which reaches the master in that call.
3
- import { get } from "node:http";
4
3
  import { findCampaign } from "../campaign/index.js";
5
4
  import { samePath } from "../library/index.js";
6
- import { campaignPorts } from "./dashboard/ports.js";
5
+ import { askDashboard, campaignPorts, dashboardAt } from "./dashboard/ports.js";
7
6
  /** What the chat hears from the doorbell: never the player's words, only where to read them. */
8
7
  export const bellLine = "The player acted on the dashboard: call status to read what they did.";
9
8
  /** Reads the hook's input, waits for the doorbell, and ends the process as Claude Code's asyncRewake reads it: 2 with the line to wake the chat, else 0. */
@@ -22,7 +21,8 @@ export async function listenHere() {
22
21
  }
23
22
  /**
24
23
  * Waits at the dashboard of the hook's chat until the player says a sentence: true then; false when there is none to wait at, or it goes away. The chat's own
25
- * server is the one with its session; after /clear, which gives the hook a new one, the only server of its campaign.
24
+ * server is the one with its session; after /clear, which gives the hook a new one, the only server of its campaign, while no other chat waits there for the
25
+ * page (D-577): better no ring than one in a chat that cannot read the page.
26
26
  */
27
27
  export async function waitForBell(input, ports) {
28
28
  const hook = hookInput(input);
@@ -30,10 +30,13 @@ export async function waitForBell(input, ports) {
30
30
  if (root === undefined) {
31
31
  return false;
32
32
  }
33
- const probes = await Promise.all((ports ?? campaignPorts(root)).filter((port) => port !== 0).map(async (port) => ({ port, said: await probe(port) })));
34
- const ours = probes.filter((one) => one.said !== undefined && one.said.root !== null && samePath(one.said.root, root));
35
- const port = (ours.find((one) => hook.session !== undefined && one.said?.session === hook.session) ?? (ours.length === 1 ? ours[0] : undefined))?.port;
36
- return port === undefined ? false : (await body(port, "/api/bell")) === "ring";
33
+ const probes = await Promise.all((ports ?? campaignPorts(root)).filter((port) => port !== 0).map(async (port) => ({ port, said: await dashboardAt(port) })));
34
+ const ours = probes.flatMap((one) => (one.said !== undefined && one.said.root !== null && samePath(one.said.root, root) ? [{ port: one.port, said: one.said }] : []));
35
+ // The only page of the campaign, once nobody else waits for it: a chat that does could be this one, and a wrong chat cannot read the page. An older
36
+ // engine's page does not say who waits, so it is never taken as this chat's.
37
+ const only = ours.length === 1 && ours[0].said.others?.length === 0 ? ours[0] : undefined;
38
+ const port = (ours.find((one) => hook.session !== undefined && one.said.session === hook.session) ?? only)?.port;
39
+ return port === undefined ? false : (await askDashboard(port, "/api/bell")) === "ring";
37
40
  }
38
41
  function hookInput(input) {
39
42
  try {
@@ -47,37 +50,3 @@ function hookInput(input) {
47
50
  return {};
48
51
  }
49
52
  }
50
- // How long a port may take to say whose dashboard it is: one of this computer answers at once.
51
- const probeWait = 1000;
52
- /** Whose dashboard answers at a port: its chat's session and campaign; undefined where none does. */
53
- async function probe(port) {
54
- const said = await body(port, "/api/bell?probe", probeWait);
55
- try {
56
- const parsed = said === undefined ? undefined : JSON.parse(said);
57
- return parsed === undefined
58
- ? undefined
59
- : { session: typeof parsed.session === "string" ? parsed.session : null, root: typeof parsed.root === "string" ? parsed.root : null };
60
- }
61
- catch {
62
- return undefined;
63
- }
64
- }
65
- /** The body a dashboard of this computer answers with, once it ends; undefined when it does not answer, or not with 200. */
66
- function body(port, path, wait) {
67
- return new Promise((done) => {
68
- // A connection of its own: Node's shared one ends a request idle for five seconds, and the doorbell waits for hours.
69
- const request = get({ host: "127.0.0.1", port, path, agent: false, ...(wait === undefined ? {} : { timeout: wait }) }, (response) => {
70
- let text = "";
71
- response.setEncoding("utf8");
72
- response.on("data", (chunk) => {
73
- text += chunk;
74
- });
75
- response.on("end", () => done(response.statusCode === 200 ? text : undefined));
76
- response.on("error", () => done(undefined));
77
- });
78
- if (wait !== undefined) {
79
- request.on("timeout", () => request.destroy());
80
- }
81
- request.on("error", () => done(undefined));
82
- });
83
- }
@@ -37,8 +37,9 @@ export declare function pageModulesOf(root: string, served: Served): PageModule[
37
37
  */
38
38
  export declare function themeNow(response: ServerResponse, served: Served): Promise<void>;
39
39
  /**
40
- * A file of the theme of the campaign's game system, at theme/<path>, only from its folder, by real paths, and only while the theme passes its checks: a face
41
- * or a picture. Its ornament comes in the colour asked, ?ink=#rrggbb, and turned for a page that reads right to left, &mirrored.
40
+ * A file of the theme of the campaign's game system, at theme/<path>, only from its folder, by real paths, and only while the theme passes its checks: a face,
41
+ * a picture or its style sheet. Its ornament comes in the colour asked, ?ink=#rrggbb, and turned for a page that reads right to left, &mirrored; its cards'
42
+ * texture in the colour asked, &texture.
42
43
  */
43
44
  export declare function sendThemeFile(name: string, query: URLSearchParams, request: IncomingMessage, response: ServerResponse, served: Served): Promise<void>;
44
45
  /**
@@ -16,7 +16,7 @@ import { realPath } from "../../core/files.js";
16
16
  import { files, isInside, withFiles } from "../../core/store.js";
17
17
  import { findHiddenImage, findImage } from "../../images/index.js";
18
18
  import { languagePackFor, packGuide, packPhrases } from "../../languages/index.js";
19
- import { drawnOrnament, isThemeId, readTheme, themeCss, themeFile } from "../../themes/index.js";
19
+ import { drawnOrnament, drawnTexture, isThemeId, readTheme, themeCss, themeFile } from "../../themes/index.js";
20
20
  const imageTypes = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".svg": "image/svg+xml" };
21
21
  const pageTypes = {
22
22
  ".js": "text/javascript; charset=utf-8",
@@ -34,6 +34,8 @@ const pageTypes = {
34
34
  export const themeAddress = "/theme";
35
35
  export const themesAddress = "/themes";
36
36
  const themeTypes = { ...imageTypes, ".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf", ".otf": "font/otf" };
37
+ // A theme's own style sheet, served only as the one its theme.yaml names.
38
+ const styleType = "text/css; charset=utf-8";
37
39
  // A picture runs nothing, even an SVG opened by itself.
38
40
  const picturePolicy = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
39
41
  // From src/ and from dist/ alike, the built page is in dist/dashboard, one level up.
@@ -161,6 +163,20 @@ export function packagePageFile(path, served) {
161
163
  export function pageModulesOf(root, served) {
162
164
  return campaignPageModules(root, served.context, campaignSystem(root, served.context));
163
165
  }
166
+ /**
167
+ * A theme's own style sheet, when it names one: the address of a sheet of one line, which the page links and which brings the theme's into the layer
168
+ * theme-style, so that none of its braces leaves that layer and its url() come from its own folder; it changes with what the sheet holds.
169
+ */
170
+ function styleOf(theme, address) {
171
+ const sheet = sheetAddress(theme, address);
172
+ return sheet === undefined ? {} : { style: `${sheet}&layer` };
173
+ }
174
+ /** The address of a theme's own style sheet, which changes with what it holds; undefined when it names none. */
175
+ function sheetAddress(theme, address) {
176
+ const bytes = theme.style === undefined ? undefined : files().bytes(join(theme.folder, theme.style));
177
+ const at = `${address}/${(theme.style ?? "").split("/").map(encodeURIComponent).join("/")}`;
178
+ return bytes === undefined ? undefined : `${at}?v=${createHash("sha1").update(bytes).digest("base64url").slice(0, 12)}`;
179
+ }
164
180
  /**
165
181
  * The theme of the campaign's game system (D-528): its CSS of custom properties, its icons and its name, which the page uses while the player keeps the game's
166
182
  * style on; refused when it does not pass its checks, which validate says; the system's name alone when it names none. Beside it, the themes installed on
@@ -171,7 +187,7 @@ export async function themeNow(response, served) {
171
187
  await served.session.ready();
172
188
  const system = root === undefined ? undefined : withFiles(served.session, () => campaignSystem(root, served.context));
173
189
  const reading = root === undefined ? undefined : withFiles(served.session, () => campaignTheme(root, served.context));
174
- const installed = withFiles(served.session, () => themesHere(served.context)).flatMap(({ id, theme }) => theme === undefined ? [] : [{ id, name: theme.name, css: themeCss(theme, `${themesAddress}/${id}`), icons: theme.icons }]);
190
+ const installed = withFiles(served.session, () => themesHere(served.context).flatMap(({ id, theme }) => theme === undefined ? [] : [{ id, name: theme.name, css: themeCss(theme, `${themesAddress}/${id}`), icons: theme.icons, ...styleOf(theme, `${themesAddress}/${id}`) }]));
175
191
  const themes = installed.length === 0 ? {} : { themes: installed };
176
192
  if (system === undefined) {
177
193
  sendJson(response, 200, themes);
@@ -184,18 +200,20 @@ export async function themeNow(response, served) {
184
200
  sendJson(response, 200, { system: reading.system, refused: true, ...themes });
185
201
  }
186
202
  else {
187
- sendJson(response, 200, { system: reading.system, name: reading.theme.name, css: themeCss(reading.theme, themeAddress), icons: reading.theme.icons, ...themes });
203
+ const style = withFiles(served.session, () => (reading.theme === undefined ? {} : styleOf(reading.theme, themeAddress)));
204
+ sendJson(response, 200, { system: reading.system, name: reading.theme.name, css: themeCss(reading.theme, themeAddress), icons: reading.theme.icons, ...style, ...themes });
188
205
  }
189
206
  }
190
207
  /**
191
- * A file of the theme of the campaign's game system, at theme/<path>, only from its folder, by real paths, and only while the theme passes its checks: a face
192
- * or a picture. Its ornament comes in the colour asked, ?ink=#rrggbb, and turned for a page that reads right to left, &mirrored.
208
+ * A file of the theme of the campaign's game system, at theme/<path>, only from its folder, by real paths, and only while the theme passes its checks: a face,
209
+ * a picture or its style sheet. Its ornament comes in the colour asked, ?ink=#rrggbb, and turned for a page that reads right to left, &mirrored; its cards'
210
+ * texture in the colour asked, &texture.
193
211
  */
194
212
  export async function sendThemeFile(name, query, request, response, served) {
195
213
  const root = findCampaign(served.context.folder);
196
214
  await served.session.ready();
197
- const folder = root === undefined ? undefined : withFiles(served.session, () => campaignTheme(root, served.context))?.theme?.folder;
198
- sendFileOfTheme(folder, name, `${themeAddress}/${name}`, query, request, response, served);
215
+ const theme = root === undefined ? undefined : withFiles(served.session, () => campaignTheme(root, served.context))?.theme;
216
+ sendFileOfTheme(theme, name, themeAddress, query, request, response, served);
199
217
  }
200
218
  /**
201
219
  * A file of a theme installed on its own, at themes/<id>/<path>, as the system's theme sends its files: only from its folder, by real paths, and only while it
@@ -205,21 +223,32 @@ export async function sendInstalledThemeFile(path, query, request, response, ser
205
223
  const [id, ...rest] = path.split("/");
206
224
  const themes = themesFolder(served.context);
207
225
  await served.session.ready();
208
- const folder = themes === undefined || !isThemeId(id) ? undefined : withFiles(served.session, () => readTheme(join(themes, id)).theme?.folder);
209
- sendFileOfTheme(folder, rest.join("/"), `${themesAddress}/${path}`, query, request, response, served);
226
+ const theme = themes === undefined || !isThemeId(id) ? undefined : withFiles(served.session, () => readTheme(join(themes, id)).theme);
227
+ sendFileOfTheme(theme, rest.join("/"), `${themesAddress}/${id}`, query, request, response, served);
210
228
  }
211
- /** A face or a picture of the theme in this folder, by its name in the address; its ornament in the colour asked, ?ink=#rrggbb, and turned, &mirrored. */
212
- function sendFileOfTheme(folder, name, address, query, request, response, served) {
213
- const given = decoded(name);
214
- const file = folder === undefined || given === undefined ? undefined : themeFile(folder, given);
215
- const type = file === undefined ? undefined : themeTypes[extname(file).toLowerCase()];
229
+ /**
230
+ * A face or a picture of this theme, by its name in the address after the theme's, or the style sheet it names, &layer the line that brings it into its
231
+ * layer; its ornament in the colour asked, ?ink=#rrggbb, and turned, &mirrored; its cards' texture, &texture, all it fills in that colour.
232
+ */
233
+ function sendFileOfTheme(theme, name, base, query, request, response, served) {
234
+ const address = `${base}/${name}`;
235
+ const given = decoded(name)?.replaceAll("\\", "/");
236
+ const file = theme === undefined || given === undefined ? undefined : themeFile(theme.folder, given);
237
+ const style = theme !== undefined && given === theme.style;
238
+ const type = file === undefined ? undefined : style ? styleType : themeTypes[extname(file).toLowerCase()];
216
239
  if (file === undefined || type === undefined) {
217
240
  send(response, 404, "text/plain; charset=utf-8", `Nothing at ${address}.`);
218
241
  return;
219
242
  }
243
+ const sheet = theme !== undefined && style && query.has("layer") ? withFiles(served.session, () => sheetAddress(theme, base)) : undefined;
244
+ if (sheet !== undefined) {
245
+ sendTagged(request, response, Buffer.from(`@import url("${sheet}") layer(theme-style);\n`), { "Content-Type": styleType, "Content-Security-Policy": securityHeaders["Content-Security-Policy"] });
246
+ return;
247
+ }
220
248
  const ink = query.get("ink");
221
249
  const tinted = type === imageTypes[".svg"] && ink !== null && /^#[0-9a-f]{6}$/i.test(ink);
222
- const bytes = withFiles(served.session, () => (tinted ? Buffer.from(drawnOrnament(files().text(file) ?? "", ink, query.has("mirrored"))) : files().bytes(file)));
250
+ const drawn = (svg, colour) => (query.has("texture") ? drawnTexture(svg, colour) : drawnOrnament(svg, colour, query.has("mirrored")));
251
+ const bytes = withFiles(served.session, () => (tinted ? Buffer.from(drawn(files().text(file) ?? "", ink)) : files().bytes(file)));
223
252
  if (bytes === undefined) {
224
253
  send(response, 404, "text/plain; charset=utf-8", `Nothing at ${address}.`);
225
254
  return;
@@ -7,8 +7,9 @@ import type { SessionStore } from "../../core/session-store.ts";
7
7
  import { type Acts } from "../player-acts.ts";
8
8
  import type { EngineAsked } from "./engine.ts";
9
9
  import { type Asked, type ShownCard } from "./player.ts";
10
+ import { type DashboardAt } from "./ports.ts";
10
11
  import { type PackageAction, type PackagePhase } from "./writes.ts";
11
- export { campaignPorts, dashboardPorts } from "./ports.ts";
12
+ export { answers, campaignPorts, dashboardAt, dashboardPorts } from "./ports.ts";
12
13
  /** A dashboard that is running: its link, and how to stop it. */
13
14
  export interface Dashboard {
14
15
  url: string;
@@ -42,8 +43,18 @@ export interface CodexQueue {
42
43
  ready(): boolean;
43
44
  send(thread: string, text: string): Promise<boolean>;
44
45
  }
45
- /** Serves the dashboard of the campaign of context.folder, on 127.0.0.1 only, at the first of the ports that is free; undefined when none is. */
46
+ /**
47
+ * Serves the dashboard of the campaign of context.folder, on 127.0.0.1 only, at the first of the ports that is free, which campaign.yaml then keeps; undefined
48
+ * when none is, or when another chat of the campaign serves its page already: one page for each campaign (D-577).
49
+ */
46
50
  export declare function startDashboard(context: Context, session: SessionStore, options?: DashboardOptions): Promise<Dashboard | undefined>;
51
+ /** The link of the campaign's page where another chat serves it (D-577); undefined when none does. */
52
+ export declare function campaignPageElsewhere(root: string, ports?: number[]): Promise<{
53
+ url: string;
54
+ port: number;
55
+ } | undefined>;
56
+ /** Whether what answers at a port is the page of this campaign. */
57
+ export declare function isCampaignPage(there: DashboardAt | undefined, root: string): boolean;
47
58
  /** What the server keeps while it runs, shared by the files beside it: the pages open, the question asked, what the master has not heard yet. */
48
59
  export interface Served {
49
60
  port: number;
@@ -105,6 +116,8 @@ export interface Served {
105
116
  engineLatest?: EngineAsked;
106
117
  /** The player's sentences said on the page, waiting for the master or heard lately (D-495). */
107
118
  acts: Acts;
119
+ /** The other chats of the campaign that wait for its page, by session, with when each last asked (D-577). */
120
+ others: Map<string, number>;
108
121
  /** The doorbell of Claude Code's hook, waiting for a sentence; and whether one ever came, so that this chat has one (D-495). */
109
122
  bell?: ServerResponse;
110
123
  belled?: boolean;