@team-antioch/sc2-adjutant 0.1.0 → 0.1.1

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 (149) hide show
  1. package/README.md +2 -0
  2. package/data/blizzard-baseline.json +3061 -0
  3. package/data/button-hotkeys.json +5722 -0
  4. package/data/game-assets.json +50909 -0
  5. package/data/package-entries.json +32361 -2
  6. package/dist/capture/bank-fixtures.d.ts +13 -0
  7. package/dist/capture/bank-fixtures.js +35 -0
  8. package/dist/capture/bank-snapshots.d.ts +95 -0
  9. package/dist/capture/bank-snapshots.js +302 -0
  10. package/dist/capture/editor-broker-client.d.ts +27 -4
  11. package/dist/capture/editor-broker-client.js +3 -3
  12. package/dist/capture/editor-broker.js +154 -9
  13. package/dist/capture/effect-tour.d.ts +113 -0
  14. package/dist/capture/effect-tour.js +283 -0
  15. package/dist/capture/effect-video.d.ts +74 -0
  16. package/dist/capture/effect-video.js +173 -0
  17. package/dist/capture/exemplar-capture.d.ts +4 -0
  18. package/dist/capture/exemplar-capture.js +4 -1
  19. package/dist/capture/shots.d.ts +6 -1
  20. package/dist/capture/shots.js +1 -1
  21. package/dist/capture/stop-tour.d.ts +3 -1
  22. package/dist/capture/stop-tour.js +1 -1
  23. package/dist/capture/style-pack-captures.d.ts +67 -0
  24. package/dist/capture/style-pack-captures.js +172 -0
  25. package/dist/catalog/stock-catalog.d.ts +8 -0
  26. package/dist/catalog/stock-catalog.js +13 -0
  27. package/dist/cli/capture-exemplars.js +18 -32
  28. package/dist/cli/effect-tour.d.ts +2 -0
  29. package/dist/cli/effect-tour.js +378 -0
  30. package/dist/cli/make-frames.d.ts +1 -0
  31. package/dist/cli/make-frames.js +21 -0
  32. package/dist/cli/sound-mix.d.ts +1 -0
  33. package/dist/cli/sound-mix.js +75 -0
  34. package/dist/cli/study.js +6 -26
  35. package/dist/domain/blueprint-trigger.d.ts +355 -3
  36. package/dist/domain/blueprint-trigger.js +149 -8
  37. package/dist/domain/library-interface.d.ts +50 -29
  38. package/dist/domain/library-interface.js +54 -41
  39. package/dist/domain/mission-blueprint.d.ts +13 -6
  40. package/dist/domain/mission-blueprint.js +6 -0
  41. package/dist/domain/mod-blueprint.d.ts +4 -4
  42. package/dist/host/game-logs.d.ts +63 -0
  43. package/dist/host/game-logs.js +178 -0
  44. package/dist/host/game-ownership.d.ts +37 -0
  45. package/dist/host/game-ownership.js +84 -0
  46. package/dist/host/game-run-report.d.ts +63 -0
  47. package/dist/host/game-run-report.js +119 -0
  48. package/dist/host/known-errors.d.ts +34 -0
  49. package/dist/host/known-errors.js +73 -0
  50. package/dist/init/init-workspace.d.ts +3 -1
  51. package/dist/init/init-workspace.js +10 -1
  52. package/dist/map/convert-mission-triggers.d.ts +115 -7
  53. package/dist/map/convert-mission-triggers.js +527 -47
  54. package/dist/map/editor-changes.d.ts +1 -1
  55. package/dist/map/editor-form.d.ts +5 -0
  56. package/dist/map/editor-form.js +72 -0
  57. package/dist/map/game-packages.d.ts +3 -2
  58. package/dist/map/game-packages.js +5 -2
  59. package/dist/map/kept-references.js +47 -1
  60. package/dist/map/kept-session.js +3 -1
  61. package/dist/map/outline-diff.d.ts +24 -0
  62. package/dist/map/outline-diff.js +95 -0
  63. package/dist/map/outline-trigger.d.ts +7 -0
  64. package/dist/map/outline-trigger.js +29 -20
  65. package/dist/map/ownership-plan.d.ts +6 -2
  66. package/dist/map/ownership-plan.js +1 -1
  67. package/dist/map/package-output.js +13 -8
  68. package/dist/map/tune-kept-triggers.d.ts +7 -0
  69. package/dist/map/tune-kept-triggers.js +33 -6
  70. package/dist/map/write-blueprint-trigger.d.ts +9 -4
  71. package/dist/map/write-blueprint-trigger.js +46 -13
  72. package/dist/map/write-map-package.js +20 -9
  73. package/dist/mcp/capture-jobs.d.ts +2 -0
  74. package/dist/mcp/capture-jobs.js +2 -0
  75. package/dist/mcp/server.d.ts +11 -2
  76. package/dist/mcp/server.js +17 -4
  77. package/dist/mcp/tools/bank-report.d.ts +19 -0
  78. package/dist/mcp/tools/bank-report.js +51 -0
  79. package/dist/mcp/tools/blueprint.js +18 -14
  80. package/dist/mcp/tools/capture.d.ts +4 -0
  81. package/dist/mcp/tools/capture.js +22 -5
  82. package/dist/mcp/tools/catalog.d.ts +1 -1
  83. package/dist/mcp/tools/catalog.js +30 -1
  84. package/dist/mcp/tools/compile.d.ts +1 -1
  85. package/dist/mcp/tools/compile.js +100 -9
  86. package/dist/mcp/tools/editor-handoff.d.ts +4 -1
  87. package/dist/mcp/tools/editor-handoff.js +6 -3
  88. package/dist/mcp/tools/style-pack.d.ts +11 -0
  89. package/dist/mcp/tools/style-pack.js +245 -0
  90. package/dist/mcp/tools/tool-group.d.ts +9 -0
  91. package/dist/mods/button-hotkeys.d.ts +45 -0
  92. package/dist/mods/button-hotkeys.js +185 -0
  93. package/dist/mods/compile-mod.js +19 -5
  94. package/dist/mods/custom-doodads.d.ts +21 -1
  95. package/dist/mods/custom-doodads.js +53 -7
  96. package/dist/mods/data-rules.js +8 -1
  97. package/dist/mods/effective-entry.d.ts +18 -0
  98. package/dist/mods/effective-entry.js +52 -0
  99. package/dist/mods/function-search.js +12 -0
  100. package/dist/mods/library-xml.d.ts +34 -5
  101. package/dist/mods/library-xml.js +94 -22
  102. package/dist/mods/sound-mix.d.ts +92 -0
  103. package/dist/mods/sound-mix.js +195 -0
  104. package/dist/plugins/check-workspace.js +22 -3
  105. package/dist/plugins/plugin-api.d.ts +59 -5
  106. package/dist/plugins/plugin-api.js +6 -0
  107. package/dist/plugins/plugin-sdk.d.ts +13 -1
  108. package/dist/plugins/plugin-sdk.js +16 -1
  109. package/dist/plugins/plugin-sources.js +1 -0
  110. package/dist/plugins/registry.d.ts +4 -0
  111. package/dist/plugins/registry.js +6 -2
  112. package/dist/plugins/workspace.d.ts +5 -0
  113. package/dist/plugins/workspace.js +10 -2
  114. package/dist/study/blizzard-baseline.d.ts +76 -0
  115. package/dist/study/blizzard-baseline.js +137 -0
  116. package/dist/study/exemplar-report.d.ts +71 -0
  117. package/dist/study/exemplar-report.js +163 -0
  118. package/dist/study/find-places.d.ts +127 -0
  119. package/dist/study/find-places.js +306 -0
  120. package/dist/study/load-map-package.d.ts +3 -0
  121. package/dist/study/load-map-package.js +11 -0
  122. package/dist/study/map-study.d.ts +1 -0
  123. package/dist/study/map-study.js +3 -0
  124. package/dist/study/measure-lighting.d.ts +6 -0
  125. package/dist/study/measure-lighting.js +1 -1
  126. package/dist/study/measures.d.ts +225 -0
  127. package/dist/study/measures.js +366 -0
  128. package/dist/study/scaffold-style-pack.d.ts +58 -0
  129. package/dist/study/scaffold-style-pack.js +261 -0
  130. package/dist/study/study-exemplars.d.ts +67 -0
  131. package/dist/study/study-exemplars.js +133 -0
  132. package/dist/triggers/blueprint-triggers.d.ts +71 -11
  133. package/dist/triggers/blueprint-triggers.js +403 -48
  134. package/dist/triggers/kept-trigger-galaxy.d.ts +29 -0
  135. package/dist/triggers/kept-trigger-galaxy.js +103 -7
  136. package/dist/triggers/splice-map-script.d.ts +2 -0
  137. package/dist/triggers/splice-map-script.js +309 -8
  138. package/dist/triggers/write-triggers-xml.js +20 -5
  139. package/dist/ui/frame-path-check.d.ts +43 -4
  140. package/dist/ui/frame-path-check.js +121 -13
  141. package/dist/ui/frame-paths.d.ts +21 -1
  142. package/dist/ui/frame-paths.js +26 -6
  143. package/dist/ui/toast.d.ts +4 -5
  144. package/dist/ui/toast.js +6 -10
  145. package/examples/example-campaign/README.md +27 -0
  146. package/examples/example-campaign/missions/ashfall-relay/blueprint.json +11 -1
  147. package/examples/example-campaign/missions/ashfall-relay/triggers/ash-tremors.json +69 -0
  148. package/examples/example-campaign/missions/ashfall-relay/triggers/start-ash-tremors.json +31 -0
  149. package/package.json +3 -3
@@ -0,0 +1,261 @@
1
+ // Starting a Style Pack in a Workspace (#29): the scaffold_style_pack and add_exemplar_map tools.
2
+ //
3
+ // The pack is laid out as packages/plugin-style-antioch is (its manifest at the root, the guide in
4
+ // knowledge/, the Exemplar Maps list and lessons in exemplar-maps/), so the folder can later become
5
+ // a package unchanged. It starts with no Exemplar Maps, lessons or moods: those are the mapper's.
6
+ import { randomUUID } from "node:crypto";
7
+ import { existsSync } from "node:fs";
8
+ import { mkdir, readdir, readFile, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
9
+ import path from "node:path";
10
+ import { CAPTURE_IGNORES } from "../capture/style-pack-captures.js";
11
+ import { PLUGIN_API_VERSION } from "../plugins/plugin-api.js";
12
+ import { isLocalPluginSource, localPluginFolder, MANIFEST_FILE } from "../plugins/plugin-sources.js";
13
+ import { EXEMPLAR_ID_PATTERN, PLUGIN_NAME_PATTERN } from "../plugins/registry.js";
14
+ import { exemplarSourceFolder, WORKSPACE_FILE } from "../plugins/workspace.js";
15
+ import { isInside } from "../util/inside.js";
16
+ import { replaceFile } from "../util/replace-file.js";
17
+ /** Where a new pack goes in the Workspace, by default. */
18
+ export const DEFAULT_STYLE_PACK_FOLDER = "style-pack";
19
+ /** What a pack's Exemplar Maps folder never commits: tours, their frames, cited frames and minimaps. */
20
+ export const STYLE_PACK_IGNORES = [...CAPTURE_IGNORES, "*/evidence/", "*/minimap.png"];
21
+ /** The Workspace config at `root`, as JSON, not validated: what a write keeps beside stylePack. */
22
+ async function readConfigJson(root) {
23
+ const file = path.join(root, WORKSPACE_FILE);
24
+ let raw;
25
+ try {
26
+ raw = JSON.parse(await readFile(file, "utf8"));
27
+ }
28
+ catch (error) {
29
+ throw new Error(`Can't read the Workspace config ${file}: ${error.message}`, { cause: error });
30
+ }
31
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
32
+ throw new Error(`Invalid Workspace config ${file}: not a JSON object`);
33
+ return raw;
34
+ }
35
+ /** The Style Pack a config's stylePack names, for a refusal: its Plugin name too, when its manifest can be read. */
36
+ async function describePack(root, source) {
37
+ if (!isLocalPluginSource(source))
38
+ return source;
39
+ try {
40
+ const manifest = JSON.parse(await readFile(path.join(localPluginFolder(root, source), MANIFEST_FILE), "utf8"));
41
+ return typeof manifest.name === "string" ? `${manifest.name} (${source})` : source;
42
+ }
43
+ catch {
44
+ return source;
45
+ }
46
+ }
47
+ /** `relative` written as a Workspace config's local source: with `./`, forward slashes. */
48
+ const asSource = (relative) => `./${relative.split(path.sep).join("/")}`;
49
+ /**
50
+ * Makes a Style Pack Plugin in `folder` of the Workspace at `root`, and names it as the Workspace
51
+ * config's stylePack: its manifest with the style-pack role and knowledge entries, an empty
52
+ * Exemplar Maps list, LESSONS.md and candidate-lessons.md with their headings and the lesson
53
+ * format, a GUIDE.md stub and the .gitignore for what captures write. Refused, before anything is
54
+ * written, when the folder is outside the Workspace, exists and isn't empty, or when the config
55
+ * names a Style Pack already and `replace` isn't set.
56
+ */
57
+ export async function scaffoldStylePack(root, options = {}) {
58
+ const config = await readConfigJson(root);
59
+ const relative = path.normalize(options.folder ?? DEFAULT_STYLE_PACK_FOLDER).replace(/[\\/]+$/, "");
60
+ const folder = path.resolve(root, relative);
61
+ if (folder === path.resolve(root))
62
+ throw new Error(`The Style Pack's folder ${options.folder} is the Workspace's root: give a folder inside it, such as ${DEFAULT_STYLE_PACK_FOLDER}`);
63
+ if (path.isAbsolute(relative) || !(await isInside(root, folder)))
64
+ throw new Error(`The Style Pack's folder ${options.folder} is outside the Workspace ${root}: give a folder inside it, relative to its root`);
65
+ const source = asSource(path.relative(root, folder));
66
+ const campaign = config.campaign;
67
+ const name = options.name ?? `style-${typeof campaign?.id === "string" ? campaign.id : path.basename(folder)}`;
68
+ if (!PLUGIN_NAME_PATTERN.test(name)) {
69
+ const given = options.name ? "" : " (made from the Campaign's id; give a name)";
70
+ throw new Error(`The Style Pack's name ${name}${given} isn't a Plugin name: lowercase, like an npm package name (letters, digits, @, /, dots, hyphens or underscores)`);
71
+ }
72
+ const current = typeof config.stylePack === "string" ? config.stylePack : undefined;
73
+ if (current !== undefined && !options.replace) {
74
+ throw new Error(`The Workspace already names a Style Pack, ${await describePack(root, current)} (stylePack in ${path.join(root, WORKSPACE_FILE)}). Ask the mapper whether the new pack is to replace it, then pass replace: true; nothing was written`);
75
+ }
76
+ if (existsSync(folder)) {
77
+ if (!(await stat(folder)).isDirectory())
78
+ throw new Error(`${folder} is a file, not a folder: give another folder for the Style Pack; nothing was written`);
79
+ if ((await readdir(folder)).length)
80
+ throw new Error(`${folder} already exists and isn't empty: give another folder for the Style Pack, or empty it; nothing was written`);
81
+ }
82
+ // Written beside the folder first, then moved into place, so a failure leaves no half-made pack.
83
+ const files = packFiles(name);
84
+ const staging = path.join(path.dirname(folder), `.${path.basename(folder)}-${randomUUID()}`);
85
+ try {
86
+ for (const [file, content] of Object.entries(files)) {
87
+ await mkdir(path.dirname(path.join(staging, file)), { recursive: true });
88
+ await writeFile(path.join(staging, file), content);
89
+ }
90
+ if (existsSync(folder))
91
+ await rmdir(folder);
92
+ await rename(staging, folder);
93
+ }
94
+ catch (error) {
95
+ await rm(staging, { recursive: true, force: true });
96
+ throw error;
97
+ }
98
+ await replaceFile(path.join(root, WORKSPACE_FILE), `${JSON.stringify({ ...config, stylePack: source }, null, 2)}\n`);
99
+ return { name, folder, source, files: Object.keys(files), ...(current !== undefined ? { replaced: current } : {}) };
100
+ }
101
+ /** The new pack's files, by path in its folder. */
102
+ function packFiles(name) {
103
+ const manifest = {
104
+ name,
105
+ version: "0.1.0",
106
+ pluginApi: PLUGIN_API_VERSION,
107
+ roles: ["style-pack"],
108
+ contributions: {
109
+ knowledge: [
110
+ {
111
+ id: "guide",
112
+ title: "This pack's look, step by step",
113
+ description: "Start here: which Design Lessons govern each step of proposing or critiquing a Mission's look, and how much each weighs.",
114
+ file: "knowledge/GUIDE.md",
115
+ },
116
+ {
117
+ id: "lessons",
118
+ title: "Design Lessons",
119
+ description: "The ratified Design Lessons: each rule, the measured evidence and frames behind it, its weight and the Blueprint hook it shapes.",
120
+ file: "exemplar-maps/LESSONS.md",
121
+ },
122
+ {
123
+ id: "candidate-lessons",
124
+ title: "Candidate Design Lessons",
125
+ description: "Drafts not yet ratified, each with its rule, numbers, supporting maps and frames: none is a Design Lesson until the mapper keeps it.",
126
+ file: "exemplar-maps/candidate-lessons.md",
127
+ },
128
+ ],
129
+ exemplarMaps: "exemplar-maps/exemplars.json",
130
+ },
131
+ };
132
+ return {
133
+ [MANIFEST_FILE]: `${JSON.stringify(manifest, null, 2)}\n`,
134
+ "exemplar-maps/exemplars.json": `${JSON.stringify({ exemplars: [] }, null, 2)}\n`,
135
+ "exemplar-maps/LESSONS.md": LESSONS,
136
+ "exemplar-maps/candidate-lessons.md": CANDIDATES,
137
+ "exemplar-maps/.gitignore": `# In-game tours, their 1000px frames, the frames lessons cite and minimaps (capture_exemplar): never committed.\n${STYLE_PACK_IGNORES.join("\n")}\n`,
138
+ "knowledge/GUIDE.md": guide(name),
139
+ };
140
+ }
141
+ const LESSONS = `# Design Lessons
142
+
143
+ Ratified visual Design Lessons from this pack's Exemplar Maps. Each lesson is a rule to follow during Mission Blueprint co-design, with the evidence behind it. Drafts live in \`candidate-lessons.md\`; only lessons the mapper has ratified appear here, one at a time, in the order they were kept.
144
+
145
+ Each lesson gives:
146
+ - **Rule:** the instruction.
147
+ - **Evidence:** numbers from the Map Studies and the consistency report (\`exemplar_report\`), and what the in-game frames show, each named by its map, the lighting it was captured under and its stop in that tour, or, for a place-tour frame, the place's centre in cells. The frames themselves aren't part of the pack; each citation stands without its picture.
148
+ - **Weight:** how much to trust it. Evidence from a map the mapper made weighs most, then one they edited, then one they approved; agreement across independent maps counts most.
149
+ - **Blueprint hook:** the part of the Mission Blueprint it shapes, and the style-rule slot it could fill.
150
+ - **Ratified:** the date, and the mapper's own words.
151
+
152
+ The format:
153
+
154
+ \`\`\`markdown
155
+ ## DL-01. <the lesson in one line>
156
+
157
+ **Rule.** <the instruction>
158
+
159
+ **Evidence.**
160
+ - <a number, with the maps it comes from>
161
+ - <map> under \`<lighting>\`, stop <n>: <what the frame shows>
162
+
163
+ **Weight.** <how much to trust it, and why>
164
+
165
+ **Blueprint hook.** <the Blueprint fields it shapes; the style-rule slot it could fill>
166
+
167
+ **Ratified.** <YYYY-MM-DD>, the mapper: "<their words>"
168
+ \`\`\`
169
+
170
+ No lessons are ratified yet.
171
+ `;
172
+ const CANDIDATES = `# Candidate Design Lessons
173
+
174
+ Drafts from the consistency report (\`exemplar_report\`) and the in-game frames. Nothing here is a Design Lesson until the mapper ratifies it; each is brought to them one at a time, and a kept one moves to \`LESSONS.md\`.
175
+
176
+ Each candidate gives:
177
+ - **Rule:** the instruction it would become.
178
+ - **Numbers:** the measure, the maps' spread and where it sits against Blizzard's campaign maps.
179
+ - **Supporting maps:** the Exemplar Maps that agree, with their provenance, and those that don't.
180
+ - **Frames:** two to four, each named by its map, its lighting and its stop, or its place's centre in cells; never by its file.
181
+ - **Blueprint hook:** the part of the Mission Blueprint it would shape.
182
+
183
+ The format:
184
+
185
+ \`\`\`markdown
186
+ ## <the candidate in one line>
187
+
188
+ **Rule.** <the instruction>
189
+
190
+ **Numbers.** <measure>: <spread> across <maps>; Blizzard p10 <a>, median <b>, p90 <c>
191
+
192
+ **Supporting maps.** <id> (<provenance>), ...; outside it: <id> <value>
193
+
194
+ **Frames.**
195
+ - <map> under \`<lighting>\`, stop <n>: <what the frame shows>
196
+
197
+ **Blueprint hook.** <the Blueprint fields it would shape>
198
+ \`\`\`
199
+
200
+ No candidates yet.
201
+ `;
202
+ function guide(name) {
203
+ return `# This pack's look, step by step
204
+
205
+ How the \`exemplar-design\` method's steps apply with this Style Pack: which Design Lessons govern each step, and how much each weighs. The rules are the ratified Design Lessons in [\`LESSONS.md\`](../exemplar-maps/LESSONS.md); cite them by id ("DL-01").
206
+
207
+ Through the sc2-adjutant MCP server, each file this guide links is one of the pack's knowledge documents, at \`sc2-adjutant://plugins/${name}/knowledge/<id>\`: \`LESSONS.md\` is \`lessons\`, \`candidate-lessons.md\` is \`candidate-lessons\`, the Exemplar Maps list is \`exemplar-maps\`, and each map's \`study.json\` is \`study-<id>\`. The pack holds no screenshots: in-game frames aren't committed or served.
208
+
209
+ This guide is a stub: it is written once the pack has ratified lessons.
210
+
211
+ ## Weights
212
+
213
+ ## Leading words
214
+
215
+ ## Propose a look
216
+ `;
217
+ }
218
+ /**
219
+ * Records an Exemplar Map in the active Style Pack's Exemplar Maps list: its id, its source map
220
+ * and its provenance. Refused, before anything is written, when the Workspace's Style Pack isn't
221
+ * a local folder, the id is taken, or the source map isn't there.
222
+ */
223
+ export async function addExemplarMap(workspace, { id, map, provenance, note, machine }) {
224
+ const configPath = path.join(workspace.root, WORKSPACE_FILE);
225
+ if (!workspace.stylePack)
226
+ throw new Error(`The Workspace names no Style Pack (stylePack in ${configPath}): scaffold one with scaffold_style_pack first`);
227
+ const plugin = workspace.registry.plugins.find((p) => p.name === workspace.stylePack);
228
+ if (!plugin?.folder || !isLocalPluginSource(plugin.source)) {
229
+ throw new Error(`The Workspace's Style Pack ${workspace.stylePack}${plugin ? ` is ${plugin.source},` : " is"} not a folder in the Workspace, so its Exemplar Maps can't be added to here`);
230
+ }
231
+ if (!EXEMPLAR_ID_PATTERN.test(id))
232
+ throw new Error(`The Exemplar Map id ${id} isn't valid: letters, digits, dots, hyphens or underscores, starting with a letter or digit`);
233
+ // The list as the registry read and checked it when the Workspace loaded: its path stays inside the pack.
234
+ const file = workspace.registry.contributions("knowledge").find((document) => document.plugin === plugin.name && document.id === "exemplar-maps")?.file;
235
+ if (!file)
236
+ throw new Error(`The Style Pack ${plugin.name} lists no Exemplar Maps (contributions.exemplarMaps in ${path.join(plugin.folder, MANIFEST_FILE)})`);
237
+ const listed = workspace.registry.contributions("exemplarMaps").filter((exemplar) => exemplar.plugin === plugin.name);
238
+ if (listed.some((exemplar) => exemplar.id === id)) {
239
+ throw new Error(`The Style Pack already has an Exemplar Map ${id} (its Exemplar Maps: ${listed.map((exemplar) => exemplar.id).join(", ")}): give the new map another id; nothing was written`);
240
+ }
241
+ // An absolute map needs no exemplarMaps folder; a relative one is inside it.
242
+ const sources = path.isAbsolute(map) ? undefined : await exemplarSourceFolder(workspace, machine);
243
+ const source = path.resolve(sources ?? "", map);
244
+ if (!existsSync(source)) {
245
+ throw new Error(`No source map ${source} for Exemplar Map ${id}: put the map there${sources ? `, or give its path inside the exemplarMaps folder ${sources}` : ""}; nothing was written`);
246
+ }
247
+ let list;
248
+ try {
249
+ list = JSON.parse(await readFile(file, "utf8"));
250
+ }
251
+ catch (error) {
252
+ throw new Error(`Can't read the Style Pack's Exemplar Maps ${file}: ${error.message}`, { cause: error });
253
+ }
254
+ // The file as it stands, in case it changed since the Workspace loaded.
255
+ const ids = list.exemplars.map((exemplar) => exemplar.id);
256
+ if (ids.includes(id))
257
+ throw new Error(`The Style Pack already has an Exemplar Map ${id} (in ${file}): give the new map another id; nothing was written`);
258
+ list.exemplars.push({ id, map, provenance, ...(note ? { note } : {}) });
259
+ await replaceFile(file, `${JSON.stringify(list, null, 2)}\n`);
260
+ return { id, map, provenance, file, source };
261
+ }
@@ -0,0 +1,67 @@
1
+ import type { MachineConfig } from "../host/machine-config.js";
2
+ import { type ExemplarMapSource, type Workspace } from "../plugins/workspace.js";
3
+ import { type RecordedMood } from "./find-places.js";
4
+ /** Where the source maps come from, when not from the machine config read from its file. */
5
+ export type ExemplarOptions = {
6
+ /** The Exemplar Maps to work on, by id; every one the pack lists when not given. */
7
+ readonly ids?: readonly string[];
8
+ readonly machine?: Pick<MachineConfig, "file" | "exemplarMaps">;
9
+ };
10
+ /**
11
+ * The Exemplar Maps of `exemplars` that `ids` names, in its order (every one when not given).
12
+ * Refused for an id the pack doesn't list, naming it and the pack's ids.
13
+ */
14
+ export declare function pickExemplars<T extends {
15
+ readonly id: string;
16
+ }>(exemplars: readonly T[], ids?: readonly string[]): T[];
17
+ /**
18
+ * The pack's Exemplar Maps named by `ids` (every one when not given), each with its source map.
19
+ * Refused, before anything is written, for an id the pack doesn't list or a source map that isn't
20
+ * there, naming them and the setting the folder came from.
21
+ */
22
+ export declare function selectExemplars(workspace: Workspace, { ids, machine }?: ExemplarOptions): Promise<ExemplarMapSource[]>;
23
+ /** One Exemplar Map's study as written: its folder and the layer images in it. */
24
+ export type StudiedExemplar = {
25
+ readonly id: string;
26
+ readonly studyDir: string;
27
+ readonly images: readonly string[];
28
+ readonly seconds: number;
29
+ };
30
+ /**
31
+ * Builds the Map Study of each Exemplar Map `ids` names (every one when not given): `study.json`
32
+ * and the layer images, in the pack's folder for that map. `onStudied` hears of each as it is written.
33
+ */
34
+ export declare function studyExemplars(workspace: Workspace, options?: ExemplarOptions & {
35
+ readonly onStudied?: (studied: StudiedExemplar) => void;
36
+ }): Promise<StudiedExemplar[]>;
37
+ /** The pack's mixtures file: `mixtures.json` beside its Exemplar Maps list. */
38
+ export declare function mixturesFile(workspace: Workspace): string;
39
+ /**
40
+ * Where a pack's tours and their frames are, as `<id>/captures/<tour>/` and `<id>/frames/<tour>/`:
41
+ * the research archive's `docs/research/exemplar-maps/` when SC2_RESEARCH_DIR is set, else the
42
+ * pack's Exemplar Maps folder (git-ignored there).
43
+ */
44
+ export declare function exemplarCaptureDir(workspace: Workspace, env?: NodeJS.ProcessEnv): string;
45
+ /** The moods the pack's mixtures file records, none when it has no file or no `moodRules`. */
46
+ export declare function recordedMoods(file: string): Promise<RecordedMood[]>;
47
+ export type FindPlacesResult = {
48
+ readonly file: string;
49
+ readonly maps: readonly string[];
50
+ readonly places: number;
51
+ /** Places per mood, in the pack's mood order; a mood no place has is left out. */
52
+ readonly moods: Readonly<Record<string, number>>;
53
+ /** The maps with no tours in the capture folder, whose places list no frames. */
54
+ readonly withoutFrames: readonly string[];
55
+ };
56
+ export type FindStylePackPlacesOptions = ExemplarOptions & {
57
+ /** Where the tours are (`readCaptureStops`); `exemplarCaptureDir` by default. */
58
+ readonly captureDir?: string;
59
+ /** The day recorded as `generated`, today by default. */
60
+ readonly generated?: string;
61
+ };
62
+ /**
63
+ * Finds the places of each Exemplar Map `ids` names (every one when not given) and writes them to
64
+ * the pack's mixtures file, replacing what it held: each place with the frames near it and the
65
+ * first of the pack's recorded moods (`moodRules`, kept) it passes, or no mood.
66
+ */
67
+ export declare function findStylePackPlaces(workspace: Workspace, options?: FindStylePackPlacesOptions): Promise<FindPlacesResult>;
@@ -0,0 +1,133 @@
1
+ // A Style Pack's Map Studies and places, built from its Exemplar Maps' source maps: what the
2
+ // study_exemplar and find_places tools, `npm run study` and the pack's exemplar scripts all call.
3
+ //
4
+ // Source maps resolve as `exemplarMapSources` says: in the folder the machine config's
5
+ // `exemplarMaps` names, else the Workspace config's.
6
+ import { existsSync } from "node:fs";
7
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
8
+ import path from "node:path";
9
+ import { z } from "zod";
10
+ import { researchArchiveDirIfSet } from "../capture/research-archive.js";
11
+ import { writePng } from "../preview/write-png.js";
12
+ import { exemplarMapSources, stylePackFiles } from "../plugins/workspace.js";
13
+ import { replaceFile } from "../util/replace-file.js";
14
+ import { buildMixtures, findPlaces, moodRuleOf, readCaptureStops } from "./find-places.js";
15
+ import { loadMapPackage } from "./load-map-package.js";
16
+ import { buildMapStudy } from "./map-study.js";
17
+ import { studyDoodads } from "./measure-doodads.js";
18
+ /**
19
+ * The Exemplar Maps of `exemplars` that `ids` names, in its order (every one when not given).
20
+ * Refused for an id the pack doesn't list, naming it and the pack's ids.
21
+ */
22
+ export function pickExemplars(exemplars, ids) {
23
+ if (ids === undefined)
24
+ return [...exemplars];
25
+ const only = [...new Set(ids)];
26
+ const unknown = only.filter((id) => !exemplars.some((exemplar) => exemplar.id === id));
27
+ if (unknown.length) {
28
+ const listed = exemplars.length ? exemplars.map((exemplar) => exemplar.id).join(", ") : "none";
29
+ throw new Error(`The Style Pack has no Exemplar Map ${unknown.join(", ")} (its Exemplar Maps: ${listed})`);
30
+ }
31
+ return only.map((id) => exemplars.find((exemplar) => exemplar.id === id));
32
+ }
33
+ /**
34
+ * The pack's Exemplar Maps named by `ids` (every one when not given), each with its source map.
35
+ * Refused, before anything is written, for an id the pack doesn't list or a source map that isn't
36
+ * there, naming them and the setting the folder came from.
37
+ */
38
+ export async function selectExemplars(workspace, { ids, machine } = {}) {
39
+ const chosen = pickExemplars(await exemplarMapSources(workspace, machine), ids);
40
+ const missing = chosen.filter((exemplar) => !existsSync(exemplar.source));
41
+ if (missing.length) {
42
+ const folder = path.dirname(missing[0].source);
43
+ throw new Error(`No source map for Exemplar Map ${missing.map((exemplar) => `${exemplar.id} (${exemplar.source})`).join(", ")}. Put the map in ${folder}, or set exemplarMaps (in the machine config, or the Workspace config for a folder that travels with the Workspace) to the folder that holds it`);
44
+ }
45
+ return chosen;
46
+ }
47
+ /**
48
+ * Builds the Map Study of each Exemplar Map `ids` names (every one when not given): `study.json`
49
+ * and the layer images, in the pack's folder for that map. `onStudied` hears of each as it is written.
50
+ */
51
+ export async function studyExemplars(workspace, options = {}) {
52
+ const studied = [];
53
+ for (const exemplar of await selectExemplars(workspace, options)) {
54
+ const started = Date.now();
55
+ const { study, images } = buildMapStudy(exemplar, loadMapPackage(exemplar.source));
56
+ await mkdir(exemplar.studyDir, { recursive: true });
57
+ await writeFile(path.join(exemplar.studyDir, "study.json"), `${JSON.stringify(study, null, 2)}\n`);
58
+ for (const [name, image] of Object.entries(images))
59
+ await writeFile(path.join(exemplar.studyDir, name), writePng(image));
60
+ const done = { id: exemplar.id, studyDir: exemplar.studyDir, images: Object.keys(images), seconds: (Date.now() - started) / 1000 };
61
+ studied.push(done);
62
+ options.onStudied?.(done);
63
+ }
64
+ return studied;
65
+ }
66
+ const MoodConditionSchema = z.object({ motifs: z.array(z.string().min(1)).min(1), atLeast: z.number() }).strict();
67
+ const RecordedMoodSchema = z.object({ name: z.string().min(1), when: z.array(z.array(MoodConditionSchema).min(1)).min(1).optional() }).strict();
68
+ /** As much of a mixtures file as find_places reads back: the pack's moods. */
69
+ const MixturesFileSchema = z.object({ moodRules: z.array(RecordedMoodSchema).optional() }).passthrough();
70
+ /** The pack's mixtures file: `mixtures.json` beside its Exemplar Maps list. */
71
+ export function mixturesFile(workspace) {
72
+ const { exemplarDir } = stylePackFiles(workspace);
73
+ if (!exemplarDir)
74
+ throw new Error("The Workspace's Style Pack lists no Exemplar Maps (contributions.exemplarMaps in its sc2-adjutant-plugin.json)");
75
+ return path.join(exemplarDir, "mixtures.json");
76
+ }
77
+ /**
78
+ * Where a pack's tours and their frames are, as `<id>/captures/<tour>/` and `<id>/frames/<tour>/`:
79
+ * the research archive's `docs/research/exemplar-maps/` when SC2_RESEARCH_DIR is set, else the
80
+ * pack's Exemplar Maps folder (git-ignored there).
81
+ */
82
+ export function exemplarCaptureDir(workspace, env = process.env) {
83
+ const archive = researchArchiveDirIfSet(env);
84
+ return archive ? path.join(archive, "docs/research/exemplar-maps") : path.dirname(mixturesFile(workspace));
85
+ }
86
+ /** The moods the pack's mixtures file records, none when it has no file or no `moodRules`. */
87
+ export async function recordedMoods(file) {
88
+ let text;
89
+ try {
90
+ text = await readFile(file, "utf8");
91
+ }
92
+ catch (error) {
93
+ if (error.code === "ENOENT")
94
+ return [];
95
+ throw error;
96
+ }
97
+ let json;
98
+ try {
99
+ json = JSON.parse(text);
100
+ }
101
+ catch (error) {
102
+ throw new Error(`${file} isn't valid JSON: ${error instanceof Error ? error.message : String(error)}`);
103
+ }
104
+ const parsed = MixturesFileSchema.safeParse(json);
105
+ if (!parsed.success)
106
+ throw new Error(`${file}: its moodRules aren't valid: ${parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`);
107
+ return (parsed.data.moodRules ?? []).map(({ name, when }) => (when ? { name, when } : { name }));
108
+ }
109
+ /**
110
+ * Finds the places of each Exemplar Map `ids` names (every one when not given) and writes them to
111
+ * the pack's mixtures file, replacing what it held: each place with the frames near it and the
112
+ * first of the pack's recorded moods (`moodRules`, kept) it passes, or no mood.
113
+ */
114
+ export async function findStylePackPlaces(workspace, options = {}) {
115
+ const exemplars = await selectExemplars(workspace, options);
116
+ const file = mixturesFile(workspace);
117
+ const moodRules = await recordedMoods(file);
118
+ const moods = moodRules.map(moodRuleOf);
119
+ const captureDir = options.captureDir ?? exemplarCaptureDir(workspace);
120
+ const all = [];
121
+ const withoutFrames = [];
122
+ for (const exemplar of exemplars) {
123
+ const stops = readCaptureStops(captureDir, exemplar.id);
124
+ if (!stops)
125
+ withoutFrames.push(exemplar.id);
126
+ all.push(...findPlaces(exemplar.id, studyDoodads(loadMapPackage(exemplar.source)), { moods, ...(stops ? { stops } : {}) }));
127
+ }
128
+ const maps = exemplars.map((exemplar) => exemplar.id);
129
+ const library = buildMixtures(all, moodRules.map((mood) => mood.name));
130
+ const generated = options.generated ?? new Date().toISOString().slice(0, 10);
131
+ await replaceFile(file, `${JSON.stringify({ generated, maps, moodRules, ...library }, null, 1)}\n`);
132
+ return { file, maps, places: all.length, moods: Object.fromEntries(Object.entries(library.moods).map(([mood, mixture]) => [mood, mixture.places])), withoutFrames };
133
+ }
@@ -1,5 +1,5 @@
1
- import { type GuiVariable } from "../domain/library-interface.js";
2
- import { type BlueprintTrigger, type BlueprintTriggerFolder } from "../domain/blueprint-trigger.js";
1
+ import { type GuiBody, type GuiVariable, type LibraryFunction } from "../domain/library-interface.js";
2
+ import { type BlueprintComment, type BlueprintCustomScript, type BlueprintElement, type BlueprintFunction, type BlueprintPreset, type BlueprintRecord, type BlueprintTrigger, type BlueprintTriggerFolder } from "../domain/blueprint-trigger.js";
3
3
  import type { Strings } from "../domain/entry-strings.js";
4
4
  import { type GameLibrary } from "../mods/library-galaxy.js";
5
5
  import { type KeptCatalog, type UnknownPart } from "./kept-trigger-galaxy.js";
@@ -8,14 +8,49 @@ export type AuthoredTrigger = {
8
8
  readonly file: string;
9
9
  readonly trigger: BlueprintTrigger;
10
10
  };
11
- /** The Blueprint's own trigger elements, the global variables it declares, and the folders they're filed in. */
11
+ /** A Blueprint function element, with the file it was read from (relative to the Blueprint). */
12
+ export type AuthoredFunction = {
13
+ readonly file: string;
14
+ readonly fn: BlueprintFunction;
15
+ };
16
+ /** A Blueprint comment element, filed in Root or a folder, with the file it was read from (relative to the Blueprint). */
17
+ export type AuthoredComment = {
18
+ readonly file: string;
19
+ readonly comment: BlueprintComment;
20
+ };
21
+ /** A Blueprint preset type, record or custom script, with the file it was read from (relative to the Blueprint). */
22
+ export type AuthoredItem<T> = {
23
+ readonly file: string;
24
+ readonly item: T;
25
+ };
26
+ /** The Blueprint's own trigger elements (its triggers, functions, comments, preset types, records and custom script), the global variables it declares, and the folders they're filed in. */
12
27
  export type AuthoredTriggers = {
13
28
  readonly triggers: readonly AuthoredTrigger[];
29
+ readonly functions?: readonly AuthoredFunction[];
30
+ readonly comments?: readonly AuthoredComment[];
31
+ readonly presets?: readonly AuthoredItem<BlueprintPreset>[];
32
+ readonly records?: readonly AuthoredItem<BlueprintRecord>[];
33
+ readonly customScripts?: readonly AuthoredItem<BlueprintCustomScript>[];
14
34
  readonly variables?: readonly GuiVariable[];
15
35
  readonly folders: readonly BlueprintTriggerFolder[];
16
36
  };
17
- /** Whether the Blueprint declares any trigger element of its own: a trigger, a global or a folder. */
37
+ /** Whether the Blueprint declares any trigger element of its own: a trigger, a function, a comment, a preset type, a record, custom script, a global or a folder. */
18
38
  export declare const hasAuthoredTriggers: (authored: AuthoredTriggers | undefined) => authored is AuthoredTriggers;
39
+ /** Every element Id a Blueprint preset type gives: its own, its values' and its comments'. */
40
+ export declare const blueprintPresetIds: (preset: BlueprintPreset) => string[];
41
+ /** Every element Id a Blueprint record gives: its own, its members' and their initial values'. */
42
+ export declare const blueprintRecordIds: (record: BlueprintRecord) => string[];
43
+ /** A Blueprint function as the library writer and reader have one: its interface (LibraryFunction) and its GUI body. */
44
+ export declare function libraryForm(fn: BlueprintFunction): {
45
+ readonly fn: LibraryFunction;
46
+ readonly body: GuiBody;
47
+ };
48
+ /** A map function as the library reader reads it (readMapFunctionWhole) as a Blueprint function, with no words yet. */
49
+ export declare function blueprintFunctionOf(fn: LibraryFunction, body: GuiBody | undefined): BlueprintFunction;
50
+ /** A Blueprint function's elements as the Editor writes them in a map's Triggers (LF): its FunctionDef, then every element it owns, in the order the Editor reaches them. */
51
+ export declare function blueprintFunctionXml(fn: BlueprintFunction): readonly string[];
52
+ /** Every element Id a Blueprint function gives: its own, its parameters' and their defaults', its block slots', its variables' and their values', its statements'. */
53
+ export declare function blueprintFunctionIds(fn: BlueprintFunction): string[];
19
54
  /** The Kept Triggers the Blueprint's elements are compiled beside: the package's file, its names, and the previous compile's items in it (by element key), which aren't Kept. */
20
55
  export type KeptTriggers = {
21
56
  readonly triggers: string;
@@ -30,10 +65,12 @@ export type GeneratedTriggers = {
30
65
  };
31
66
  /** A Blueprint trigger's file, as convert_triggers and write_blueprint_trigger write it: its element in the schema's order, as JSON. */
32
67
  export declare const blueprintTriggerFile: (trigger: BlueprintTrigger) => string;
68
+ /** Any Blueprint trigger element's file (a trigger's, a function's), as convert_triggers writes it: its element in its schema's order, as JSON. */
69
+ export declare const blueprintElementFile: (element: BlueprintElement) => string;
33
70
  /**
34
71
  * The Blueprint's own trigger elements, each read from its file in `triggers` (relative to the
35
- * Blueprint), and its folders. A file that can't be read or isn't a trigger element is refused,
36
- * naming it and why.
72
+ * Blueprint), split by kind, and its globals and folders. A file that can't be read or isn't a
73
+ * trigger element is refused, naming it and why.
37
74
  */
38
75
  export declare function readAuthoredTriggers(blueprint: {
39
76
  readonly triggers?: readonly string[] | undefined;
@@ -45,6 +82,19 @@ export declare function readAuthoredTriggers(blueprint: {
45
82
  * conditions and actions with everything each owns, in the order the Editor reaches them.
46
83
  */
47
84
  export declare function blueprintTriggerXml(trigger: BlueprintTrigger): readonly string[];
85
+ /** A Blueprint preset type's elements as the Editor writes them in a map's Triggers (LF): its Preset, filing its values and comments in order, then each of theirs. */
86
+ export declare function blueprintPresetXml(preset: BlueprintPreset): readonly string[];
87
+ /** A Blueprint record's elements as the Editor writes them in a map's Triggers (LF): its Structure, naming its members, then each member's Variable and what it owns. */
88
+ export declare function blueprintRecordXml(record: BlueprintRecord): readonly string[];
89
+ /** A Blueprint custom script's element as the Editor writes it in a map's Triggers (LF): its script, then its init function. */
90
+ export declare function blueprintCustomScriptXml(script: BlueprintCustomScript): readonly string[];
91
+ /**
92
+ * A Blueprint custom script's block of Galaxy as the Editor writes it in the Custom Script section
93
+ * (CRLF): a ruled heading with its name, its script as it stands, then a blank line.
94
+ */
95
+ export declare const customScriptGalaxy: (script: Pick<BlueprintCustomScript, "name" | "script">) => string;
96
+ /** A Blueprint folder's Category element (LF): its icon, then the item lines of what it files. */
97
+ export declare function folderXml(folder: BlueprintTriggerFolder): string;
48
98
  /** Every element Id a Blueprint trigger gives: its own, its variables' and their values', its statements'. */
49
99
  export declare function blueprintTriggerIds(trigger: BlueprintTrigger): string[];
50
100
  /** The libraries a Blueprint trigger's calls and presets name: the map script includes each. */
@@ -68,13 +118,20 @@ export type CompiledBlueprintTriggers = {
68
118
  readonly script: string;
69
119
  readonly triggerStrings: Readonly<Record<string, string>>;
70
120
  readonly gameStrings: Strings;
71
- /** The Kept triggers the Blueprint converts this compile, each by its element Id and Galaxy name, and whether it is disabled (so has no Galaxy). */
121
+ /**
122
+ * The Kept elements the Blueprint converts this compile (triggers, functions, globals, comments,
123
+ * folders, preset types, records and custom script), each by its kind (as the compile record names
124
+ * it), element Id and the ids of the Galaxy blocks it writes over the Kept one's (none for a
125
+ * disabled trigger, a comment or a folder, which have no Galaxy).
126
+ */
72
127
  readonly converted: readonly {
128
+ readonly kind: ConvertedItemKind;
73
129
  readonly id: string;
74
- readonly scriptName: string;
75
- readonly disabled: boolean;
130
+ readonly blocks: readonly string[];
76
131
  }[];
77
132
  };
133
+ /** The kinds of Kept item a Blueprint element converts, as the compile record names them. */
134
+ export type ConvertedItemKind = "trigger" | "function" | "variable" | "comment" | "category" | "preset" | "structure" | "custom-script";
78
135
  /**
79
136
  * The compile's Triggers and MapScript.galaxy with the Blueprint's trigger elements added, and the
80
137
  * strings they need. In Triggers, the Blueprint's folders and the triggers no folder files go in
@@ -82,8 +139,9 @@ export type CompiledBlueprintTriggers = {
82
139
  * depth first through the folders as the Editor writes them: the splice keeps each where the
83
140
  * package has it, while the compile's own go to the end, so the order holds from one compile to the
84
141
  * next. In the script each trigger's declaration, section and _Init call go before the compile's
85
- * own, in that same order, as the Editor writes the tree's. A Blueprint trigger with a Kept
86
- * trigger's Id is that one converted (convert-mission-triggers.ts): it may give the Kept one's
142
+ * own, in that same order, as the Editor writes the tree's; each function's declaration and
143
+ * definition in sections of their own (withFunctions), and each record's, preset type's and custom script's too (withItems). A Blueprint element with a Kept
144
+ * one's Id is that one converted (convert-mission-triggers.ts): it may give the Kept one's
87
145
  * Ids, and is returned in `converted`, for the Equivalence Check. Refused, naming each element and
88
146
  * why, when an Id clashes or a reference is out of reach (BlueprintTriggerError), or when its
89
147
  * Galaxy can't be written.
@@ -93,3 +151,5 @@ export declare function compileBlueprintTriggers(authored: AuthoredTriggers, gen
93
151
  readonly libraries?: Readonly<Record<string, GameLibrary>>;
94
152
  readonly catalog?: KeptCatalog;
95
153
  }): CompiledBlueprintTriggers;
154
+ /** A function's declaration, from its definition (renderFunction's): its signature line, ended `;` in place of ` {`; undefined where it has none. */
155
+ export declare function functionDeclaration(definition: string, name: string): string | undefined;