@seriousgaming/sdk-tools 1.5.0 → 1.6.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 (169) hide show
  1. package/dist/agent/guidance.md +350 -0
  2. package/dist/bundling/ui-bundler.d.ts +12 -0
  3. package/dist/cli-25RWY5BQ.js +41 -0
  4. package/dist/cli-2BH7FX27.js +52 -0
  5. package/dist/cli-2GZYGRVL.js +36 -0
  6. package/dist/cli-2NU2LPEE.js +97 -0
  7. package/dist/cli-3BRC32CP.js +132 -0
  8. package/dist/cli-3D3ZXWOV.js +111 -0
  9. package/dist/cli-3ZKWV3PN.js +96 -0
  10. package/dist/cli-45OCBG53.js +60 -0
  11. package/dist/cli-4LKXZQ2B.js +48 -0
  12. package/dist/cli-4PXNOJQX.js +81 -0
  13. package/dist/cli-4SIWLHQO.js +717 -0
  14. package/dist/cli-4UWFQNGF.js +54 -0
  15. package/dist/cli-4VFZHLDG.js +202 -0
  16. package/dist/cli-4YB3ROVR.js +78 -0
  17. package/dist/cli-5ACDPCXI.js +21 -0
  18. package/dist/cli-5IAW3LIF.js +38 -0
  19. package/dist/cli-5SM367K7.js +30 -0
  20. package/dist/cli-64AB62PM.js +25 -0
  21. package/dist/cli-6K3VQQUS.js +307 -0
  22. package/dist/cli-6QB2VFPY.js +80 -0
  23. package/dist/cli-6SGCYEEC.js +649 -0
  24. package/dist/cli-6UTPHWRQ.js +207 -0
  25. package/dist/cli-6VNKQ3OX.js +391 -0
  26. package/dist/cli-72XDEFU3.js +61 -0
  27. package/dist/cli-7A6MKCUJ.js +463 -0
  28. package/dist/cli-7XLHO2FE.js +226 -0
  29. package/dist/cli-AV2FYC5G.js +225 -0
  30. package/dist/cli-B6YHEKIJ.js +248 -0
  31. package/dist/cli-BJMS3VX3.js +1837 -0
  32. package/dist/cli-BUQI5UU4.js +43 -0
  33. package/dist/cli-BWX5E7TQ.js +23 -0
  34. package/dist/cli-BYCHKSSH.js +1331 -0
  35. package/dist/cli-C3CMJSNL.js +89 -0
  36. package/dist/cli-C47GJATR.js +42 -0
  37. package/dist/cli-C5QOJJWX.js +46 -0
  38. package/dist/cli-C6ZLPK2U.js +124 -0
  39. package/dist/cli-CD5CIJZI.js +72 -0
  40. package/dist/cli-DDJYUKQG.js +36 -0
  41. package/dist/cli-DFBTZEBX.js +167 -0
  42. package/dist/cli-DOXRQ3S5.js +60 -0
  43. package/dist/cli-EVI36HEM.js +79 -0
  44. package/dist/cli-F2D4GGUA.js +549 -0
  45. package/dist/cli-FQRVFGN6.js +0 -0
  46. package/dist/cli-FWFRKQNE.js +11 -0
  47. package/dist/cli-G6CANSPL.js +88 -0
  48. package/dist/cli-GFNDW2DL.js +124 -0
  49. package/dist/cli-HCRTYQQS.js +16 -0
  50. package/dist/cli-HFX3YPUL.js +76 -0
  51. package/dist/cli-HKORECAG.js +53 -0
  52. package/dist/cli-HOE3WLFH.js +73 -0
  53. package/dist/cli-HSIHDN6K.js +187 -0
  54. package/dist/cli-HW53ICZC.js +89 -0
  55. package/dist/cli-IDVUHGKG.js +218 -0
  56. package/dist/cli-IEMKI7J7.js +1387 -0
  57. package/dist/cli-ILFDANBR.js +101 -0
  58. package/dist/cli-ILKCQNM6.js +8 -0
  59. package/dist/cli-IP4RXGHM.js +2847 -0
  60. package/dist/cli-IUS2YCD3.js +31 -0
  61. package/dist/cli-J4DKUUTK.js +138 -0
  62. package/dist/cli-J4UBELKF.js +37 -0
  63. package/dist/cli-JJSWBW4H.js +89 -0
  64. package/dist/cli-JVI24FI6.js +68 -0
  65. package/dist/cli-JZCLIT3O.js +135 -0
  66. package/dist/cli-JZOZOEZM.js +131 -0
  67. package/dist/cli-KGM6RRQW.js +185 -0
  68. package/dist/cli-KGT5L7VZ.js +13641 -0
  69. package/dist/cli-KOGRWFN7.js +89 -0
  70. package/dist/cli-KSGB2ZLK.js +101 -0
  71. package/dist/cli-L7VYSXQK.js +243 -0
  72. package/dist/cli-LK3V4RI5.js +36 -0
  73. package/dist/cli-LQOHATY2.js +126 -0
  74. package/dist/cli-MJUYJIEP.js +13 -0
  75. package/dist/cli-MJV47HKI.js +143 -0
  76. package/dist/cli-MMN4BPO4.js +145 -0
  77. package/dist/cli-MOPSZ3CS.js +88 -0
  78. package/dist/cli-MU5LB43S.js +136 -0
  79. package/dist/cli-MYJGMA6U.js +40 -0
  80. package/dist/cli-N24OHSAN.js +36 -0
  81. package/dist/cli-N45DREM4.js +99 -0
  82. package/dist/cli-N6H6T2E2.js +616 -0
  83. package/dist/cli-NROTDF5Y.js +182 -0
  84. package/dist/cli-O5ABH2WK.js +226 -0
  85. package/dist/cli-OMWC75CC.js +256 -0
  86. package/dist/cli-OXAUOWCN.js +50 -0
  87. package/dist/cli-PGCIHPU7.js +143 -0
  88. package/dist/cli-Q6ZBZYK2.js +35 -0
  89. package/dist/cli-QUNIRH7A.js +57 -0
  90. package/dist/cli-QUSCIUOM.js +142 -0
  91. package/dist/cli-QVASWX2A.js +187 -0
  92. package/dist/cli-QWQMPCL6.js +253 -0
  93. package/dist/cli-QY5NZAR7.js +97 -0
  94. package/dist/cli-R2MUZQE2.js +62 -0
  95. package/dist/cli-RCIWBCXD.js +36 -0
  96. package/dist/cli-RLEGRWFM.js +81 -0
  97. package/dist/cli-RSW6EBBD.js +89 -0
  98. package/dist/cli-RZITKPJX.js +367 -0
  99. package/dist/cli-S5IVGDDD.js +32 -0
  100. package/dist/cli-SRHBXZCN.js +159 -0
  101. package/dist/cli-TDSQSCX4.js +131 -0
  102. package/dist/cli-TIDQ4WUE.js +257 -0
  103. package/dist/cli-TT36JCU5.js +370 -0
  104. package/dist/cli-TTKICM5P.js +100 -0
  105. package/dist/cli-TTMBBEJC.js +131 -0
  106. package/dist/cli-UMEBPAZQ.js +16 -0
  107. package/dist/cli-UNAJ2OTE.js +15 -0
  108. package/dist/cli-UZZFNXRX.js +226 -0
  109. package/dist/cli-VDBW23SS.js +81 -0
  110. package/dist/cli-VL2P354N.js +46 -0
  111. package/dist/cli-VPRRICZA.js +304 -0
  112. package/dist/cli-VQ6HVQW4.js +4010 -0
  113. package/dist/cli-WR3NOY74.js +36 -0
  114. package/dist/cli-WU43JT4T.js +52 -0
  115. package/dist/cli-XAT25PRU.js +117 -0
  116. package/dist/cli-XOTNXEJA.js +124 -0
  117. package/dist/cli-XSLNH5PR.js +6417 -0
  118. package/dist/cli-XSVGKI3R.js +39 -0
  119. package/dist/cli-XZCJIKIV.js +124 -0
  120. package/dist/cli-Y3DDNMPX.js +97 -0
  121. package/dist/cli-Y3O5F4JN.js +90 -0
  122. package/dist/cli-YOTGR3NB.js +82 -0
  123. package/dist/cli-Z56ZIVA6.js +97 -0
  124. package/dist/cli-ZBN5KAIB.js +59 -0
  125. package/dist/cli-ZDOTXEKL.js +31 -0
  126. package/dist/cli-ZDUADFBY.js +88 -0
  127. package/dist/cli-ZJFQ7EEA.js +131 -0
  128. package/dist/cli-ZTWOE3ZT.js +65 -0
  129. package/dist/cli.js +148 -43093
  130. package/dist/client/build-surfaces.d.ts +33 -0
  131. package/dist/client/dev-server.d.ts +6 -0
  132. package/dist/client/index.d.ts +1 -0
  133. package/dist/client/playwright.d.ts +62 -0
  134. package/dist/client.js +228 -48
  135. package/dist/core/session.d.ts +15 -1
  136. package/dist/dev/console/assets/{index-BVF8exas.js → index-CuMOOH9m.js} +1 -1
  137. package/dist/dev/console/index.html +1 -1
  138. package/dist/dev/shell.d.ts +19 -0
  139. package/dist/dev/surfaces.d.ts +7 -0
  140. package/dist/docs/ai-agents.md +1 -1
  141. package/dist/docs/api/index.md +14 -12
  142. package/dist/docs/api/sdk-tools-client.md +29 -0
  143. package/dist/docs/api/sdk-tools-playwright.md +104 -0
  144. package/dist/docs/changelog.md +34 -0
  145. package/dist/docs/cli-and-dev-server.md +21 -0
  146. package/dist/docs/cli-reference.md +45 -31
  147. package/dist/docs/environment-variables.md +6 -0
  148. package/dist/docs/getting-started.md +1 -1
  149. package/dist/docs/guides/designing-a-game.md +29 -4
  150. package/dist/docs/guides/starter-game.md +3 -3
  151. package/dist/docs/guides/testing.md +33 -18
  152. package/dist/docs/guides/upgrading.md +19 -2
  153. package/dist/docs/page-index.md +10 -9
  154. package/dist/docs/recipes/e2e-testing.md +19 -20
  155. package/dist/playwright.js +32232 -0
  156. package/dist/templates/package/CLAUDE.md.template +7 -346
  157. package/dist/templates/package/claude/rules/workflow-create-engine.md +2 -2
  158. package/dist/templates/package/claude/rules/workflow-create-guide.md +2 -2
  159. package/dist/templates/package/claude/rules/workflow-create-user-interface.md +1 -1
  160. package/dist/templates/package/claude/rules/workflow-test-engine-or-ui.md +1 -1
  161. package/dist/templates/package/claude/rules/workflow-update-sdk-version.md +3 -3
  162. package/dist/templates/package/global-setup.ts.template +7 -18
  163. package/dist/templates/package/playwright.config.ts.liquid +8 -11
  164. package/dist/templates/starter-game/playwright.config.ts +8 -11
  165. package/dist/templates/starter-game/testing/e2e/game.spec.ts +1 -1
  166. package/dist/templates/starter-game/testing/e2e/global-setup.ts +7 -18
  167. package/dist/utils/prompt.d.ts +5 -5
  168. package/dist/utils/resource-scan.d.ts +39 -0
  169. package/package.json +7 -3
@@ -0,0 +1,257 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ resolveDocsPath
4
+ } from "./cli-UNAJ2OTE.js";
5
+ import {
6
+ CliError,
7
+ reportResult
8
+ } from "./cli-N6H6T2E2.js";
9
+
10
+ // cli/commands/docs.ts
11
+ import { readFileSync as readFileSync2, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
12
+ import { existsSync } from "fs";
13
+ import { join as join2, resolve } from "path";
14
+
15
+ // cli/docs-reference/anchors.ts
16
+ var ATX_HEADING = /^ {0,3}#{1,6}\s+(.*?)\s*#*\s*$/;
17
+ function slug(text) {
18
+ return text.replace(/<[^>]+>/g, "").replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[*_`~]/g, (character) => character === "_" ? "_" : "").trim().toLowerCase().replace(/[^\p{L}\p{M}\p{N}\p{Pc}\- ]/gu, "").replace(/ /g, "-");
19
+ }
20
+ function atxHeadingText(line) {
21
+ return ATX_HEADING.exec(line)?.[1];
22
+ }
23
+ function createAnchorSlugger() {
24
+ const seen = /* @__PURE__ */ new Map();
25
+ return (headingText2) => {
26
+ const base = slug(headingText2);
27
+ const count = seen.get(base) ?? 0;
28
+ seen.set(base, count + 1);
29
+ return count === 0 ? base : `${base}-${count}`;
30
+ };
31
+ }
32
+
33
+ // cli/docs-reference/outline.ts
34
+ var FENCE = /^\s*(`{3,}|~{3,})/;
35
+ function headingText(raw) {
36
+ return raw.replace(/<[^>]+>/g, "").replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
37
+ }
38
+ function readOutline(markdown) {
39
+ const slugFor = createAnchorSlugger();
40
+ const headings = [];
41
+ let fence;
42
+ let offset = 0;
43
+ const lines = markdown.split("\n");
44
+ lines.forEach((line, index) => {
45
+ const start = offset;
46
+ offset += line.length + 1;
47
+ const opener = FENCE.exec(line);
48
+ if (fence) {
49
+ const closes = opener && opener[1][0] === fence.marker && opener[1].length >= fence.size && line.trim() === opener[1];
50
+ if (closes) fence = void 0;
51
+ return;
52
+ }
53
+ if (opener) {
54
+ fence = { marker: opener[1][0], size: opener[1].length };
55
+ return;
56
+ }
57
+ const raw = atxHeadingText(line);
58
+ if (raw === void 0) return;
59
+ headings.push({
60
+ level: /^ {0,3}(#+)/.exec(line)?.[1].length ?? 1,
61
+ text: headingText(raw),
62
+ slug: slugFor(raw),
63
+ line: index + 1,
64
+ start
65
+ });
66
+ });
67
+ return headings.map((heading, index) => {
68
+ const next = headings.slice(index + 1).find((candidate) => candidate.level <= heading.level);
69
+ const end = next ? next.start : markdown.length;
70
+ return { ...heading, end, length: end - heading.start };
71
+ });
72
+ }
73
+ function normalise(text) {
74
+ return text.replace(/[`*_]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
75
+ }
76
+ function findSections(outline, query) {
77
+ const wanted = query.trim().replace(/^#/, "");
78
+ const bySlug = outline.filter((heading) => heading.slug === wanted.toLowerCase());
79
+ if (bySlug.length > 0) return bySlug;
80
+ return outline.filter((heading) => normalise(heading.text) === normalise(wanted));
81
+ }
82
+
83
+ // cli/docs-reference/page-index.ts
84
+ import { readdirSync, readFileSync, statSync } from "node:fs";
85
+ import { join, posix, relative, sep } from "node:path";
86
+ var PAGE_INDEX = "page-index.md";
87
+
88
+ // cli/commands/docs.ts
89
+ function buildFileTree(dir, basePath = "") {
90
+ try {
91
+ const entries = readdirSync2(dir);
92
+ const nodes = [];
93
+ for (const entry of entries) {
94
+ if (entry.startsWith(".") || entry === "node_modules") {
95
+ continue;
96
+ }
97
+ const fullPath = join2(dir, entry);
98
+ const relativePath = basePath ? join2(basePath, entry) : entry;
99
+ const stat = statSync2(fullPath);
100
+ if (stat.isDirectory()) {
101
+ nodes.push({
102
+ name: entry,
103
+ path: relativePath,
104
+ isDir: true,
105
+ children: buildFileTree(fullPath, relativePath)
106
+ });
107
+ } else if (entry.endsWith(".md")) {
108
+ nodes.push({
109
+ name: entry,
110
+ path: relativePath,
111
+ isDir: false,
112
+ children: []
113
+ });
114
+ }
115
+ }
116
+ return nodes.sort((a, b) => {
117
+ if (a.isDir !== b.isDir) {
118
+ return a.isDir ? -1 : 1;
119
+ }
120
+ return a.name.localeCompare(b.name);
121
+ });
122
+ } catch {
123
+ return [];
124
+ }
125
+ }
126
+ function formatTree(nodes, prefix = "") {
127
+ const lines = [];
128
+ nodes.forEach((node, index) => {
129
+ const isLastNode = index === nodes.length - 1;
130
+ const connector = isLastNode ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
131
+ const icon = node.isDir ? "\u{1F4C1} " : "\u{1F4C4} ";
132
+ lines.push(prefix + connector + icon + node.name);
133
+ if (node.isDir && node.children.length > 0) {
134
+ const extension = isLastNode ? " " : "\u2502 ";
135
+ const childLines = formatTree(node.children, prefix + extension);
136
+ lines.push(...childLines);
137
+ }
138
+ });
139
+ return lines;
140
+ }
141
+ function filePaths(nodes) {
142
+ return nodes.flatMap((node) => node.isDir ? filePaths(node.children) : [node.path]);
143
+ }
144
+ function printTree(docsPath) {
145
+ const fileTree = buildFileTree(docsPath);
146
+ reportResult({ files: filePaths(fileTree), index: PAGE_INDEX }, () => {
147
+ if (fileTree.length === 0) {
148
+ console.log("No documentation files found. Create .md files in the docs/ directory.");
149
+ return;
150
+ }
151
+ console.log("\n\u{1F4DA} Serious Gaming SDK Documentation\n");
152
+ console.log("docs/");
153
+ formatTree(fileTree).forEach((line) => console.log(line));
154
+ console.log(
155
+ "\nStart at page-index.md: every page with a one-sentence summary and its length.\n\nUsage: pnpm run sdk docs view <file-path> [--outline | --section <heading>]\nExample: pnpm run sdk docs view page-index.md\nExample: pnpm run sdk docs view guides/engine.md --outline\n"
156
+ );
157
+ });
158
+ }
159
+ function readDocFile(docsPath, filePath) {
160
+ const resolved = resolve(join2(docsPath, filePath));
161
+ if (!resolved.startsWith(resolve(docsPath))) {
162
+ throw new CliError("USAGE_BAD_ARGUMENT", "Invalid file path: it is outside the docs");
163
+ }
164
+ if (!resolved.endsWith(".md")) {
165
+ throw new CliError("USAGE_BAD_ARGUMENT", "Only .md files are supported");
166
+ }
167
+ try {
168
+ return readFileSync2(resolved, "utf-8");
169
+ } catch (error) {
170
+ if (error.code === "ENOENT") {
171
+ throw new CliError("FILE_NOT_FOUND", `File not found: ${filePath}`, {
172
+ hint: 'Run "pnpm run sdk docs view" to see available files.'
173
+ });
174
+ }
175
+ throw new CliError("FILE_NOT_FOUND", `Error reading file: ${error.message}`);
176
+ }
177
+ }
178
+ function describeHeading({ level, text, slug: slug2, length }) {
179
+ return { level, text, slug: slug2, length };
180
+ }
181
+ function printOutline(filePath, content) {
182
+ const headings = readOutline(content).map(describeHeading);
183
+ reportResult({ file: filePath, length: content.length, headings }, () => {
184
+ console.log(`${filePath} (${content.length.toLocaleString("en-GB")} characters)
185
+ `);
186
+ for (const heading of headings) {
187
+ const indent = " ".repeat(heading.level - 1);
188
+ console.log(
189
+ `${indent}${"#".repeat(heading.level)} ${heading.text} [${heading.slug}, ${heading.length.toLocaleString("en-GB")} characters]`
190
+ );
191
+ }
192
+ console.log(
193
+ `
194
+ Read one section with: pnpm run sdk docs view ${filePath} --section <slug or heading>`
195
+ );
196
+ });
197
+ }
198
+ function printSection(filePath, content, query) {
199
+ const outline = readOutline(content);
200
+ const matches = findSections(outline, query);
201
+ const available = outline.map((heading2) => heading2.slug);
202
+ if (matches.length === 0) {
203
+ throw new CliError("DOCS_SECTION_NOT_FOUND", `${filePath} has no section '${query}'`, {
204
+ hint: `Run "pnpm run sdk docs view ${filePath} --outline" to see its sections.`,
205
+ details: { file: filePath, section: query, available }
206
+ });
207
+ }
208
+ if (matches.length > 1) {
209
+ throw new CliError(
210
+ "USAGE_BAD_FLAG",
211
+ `More than one section of ${filePath} is headed '${query}': ` + matches.map((heading2) => heading2.slug).join(", "),
212
+ {
213
+ hint: "Name the section by its slug instead.",
214
+ details: { file: filePath, section: query, matches: matches.map((h) => h.slug) }
215
+ }
216
+ );
217
+ }
218
+ const [heading] = matches;
219
+ const section = `${content.slice(heading.start, heading.end).trimEnd()}
220
+ `;
221
+ reportResult(
222
+ { file: filePath, heading: describeHeading(heading), content: section },
223
+ () => console.log(section)
224
+ );
225
+ }
226
+ async function docsCommand(filePath, options = {}) {
227
+ const docsPath = resolveDocsPath();
228
+ if (!existsSync(docsPath)) {
229
+ throw new CliError(
230
+ "SDK_INCOMPLETE",
231
+ "Documentation files not found. Make sure the SDK is properly installed."
232
+ );
233
+ }
234
+ if (options.outline && options.section !== void 0) {
235
+ throw new CliError("USAGE_BAD_FLAG", "--outline and --section cannot be combined", {
236
+ hint: "Read the outline first, then ask for one of its sections."
237
+ });
238
+ }
239
+ if (!filePath) {
240
+ if (options.outline || options.section !== void 0) {
241
+ throw new CliError(
242
+ "USAGE_MISSING_ARGUMENT",
243
+ `${options.outline ? "--outline" : "--section"} needs a page to read`,
244
+ { hint: `Name one, such as ${PAGE_INDEX} or guides/engine.md.` }
245
+ );
246
+ }
247
+ printTree(docsPath);
248
+ return;
249
+ }
250
+ const content = readDocFile(docsPath, filePath);
251
+ if (options.outline) printOutline(filePath, content);
252
+ else if (options.section !== void 0) printSection(filePath, content, options.section);
253
+ else reportResult({ file: filePath, content }, () => console.log(content));
254
+ }
255
+ export {
256
+ docsCommand
257
+ };
@@ -0,0 +1,370 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ bundlePaths
4
+ } from "./cli-OXAUOWCN.js";
5
+ import {
6
+ MANIFEST_REFERRER,
7
+ RESOURCE_METADATA_BY_MANIFEST_KEY
8
+ } from "./cli-VQ6HVQW4.js";
9
+
10
+ // cli/templating/resource-engine.ts
11
+ import { existsSync as existsSync2, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
12
+ import { dirname as dirname2, join as join2 } from "path";
13
+
14
+ // cli/templating/renderer.ts
15
+ import { writeFileSync, copyFileSync, existsSync } from "fs";
16
+ import { join, dirname } from "path";
17
+ import { fileURLToPath } from "url";
18
+ import { Liquid } from "liquidjs";
19
+ function getTemplatesDirectory() {
20
+ const currentFilePath = fileURLToPath(import.meta.url);
21
+ const currentDir = dirname(currentFilePath);
22
+ const isDev = currentFilePath.includes("/cli/templating/") || currentFilePath.includes("\\cli\\templating\\");
23
+ return isDev ? join(currentDir, "../templates") : join(currentDir, "./templates");
24
+ }
25
+ var templatesDir = getTemplatesDirectory();
26
+ var liquid = new Liquid({
27
+ root: templatesDir,
28
+ extname: ".liquid"
29
+ });
30
+ async function renderTemplate(templatePath, data) {
31
+ return await liquid.renderFile(templatePath, data);
32
+ }
33
+ function copyStaticFile(templatePath, destPath) {
34
+ const sourcePath = join(templatesDir, templatePath);
35
+ if (!existsSync(sourcePath)) {
36
+ throw new Error(`Template file not found: ${templatePath}`);
37
+ }
38
+ copyFileSync(sourcePath, destPath);
39
+ }
40
+ async function renderAndWriteTemplate(templatePath, destPath, data) {
41
+ const rendered = await renderTemplate(templatePath, data);
42
+ writeFileSync(destPath, rendered, "utf-8");
43
+ }
44
+ function writeJsonFile(destPath, content) {
45
+ writeFileSync(destPath, JSON.stringify(content, null, 4) + "\n", "utf-8");
46
+ }
47
+
48
+ // cli/templating/resource-engine.ts
49
+ function readJson(file) {
50
+ try {
51
+ if (!existsSync2(file)) return null;
52
+ return JSON.parse(readFileSync(file, "utf-8"));
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+ function writeJson(file, value) {
58
+ writeFileSync2(file, JSON.stringify(value, null, 4) + "\n", "utf-8");
59
+ }
60
+ function renameInDefinition(def, shape, oldId, newId) {
61
+ switch (shape.kind) {
62
+ case "stringArray": {
63
+ const arr = def[shape.path];
64
+ if (!Array.isArray(arr)) return false;
65
+ let modified = false;
66
+ def[shape.path] = arr.map((id) => {
67
+ if (id === oldId) {
68
+ modified = true;
69
+ return newId;
70
+ }
71
+ return id;
72
+ });
73
+ return modified;
74
+ }
75
+ case "keyedMap": {
76
+ const map = def[shape.path];
77
+ if (!map || typeof map !== "object") return false;
78
+ if (!(oldId in map)) return false;
79
+ const value = map[oldId];
80
+ delete map[oldId];
81
+ map[newId] = value;
82
+ return true;
83
+ }
84
+ }
85
+ }
86
+ function removeFromDefinition(def, shape, id) {
87
+ switch (shape.kind) {
88
+ case "stringArray": {
89
+ const arr = def[shape.path];
90
+ if (!Array.isArray(arr)) return false;
91
+ const filtered = arr.filter((x) => x !== id);
92
+ if (filtered.length < arr.length) {
93
+ def[shape.path] = filtered;
94
+ return true;
95
+ }
96
+ return false;
97
+ }
98
+ case "keyedMap": {
99
+ const map = def[shape.path];
100
+ if (!map || typeof map !== "object" || !(id in map)) return false;
101
+ delete map[id];
102
+ if (Object.keys(map).length === 0) delete def[shape.path];
103
+ return true;
104
+ }
105
+ }
106
+ }
107
+ function definitionReferences(def, shape, id) {
108
+ switch (shape.kind) {
109
+ case "stringArray": {
110
+ const arr = def[shape.path];
111
+ return Array.isArray(arr) && arr.includes(id);
112
+ }
113
+ case "keyedMap": {
114
+ const map = def[shape.path];
115
+ return !!map && typeof map === "object" && id in map;
116
+ }
117
+ }
118
+ }
119
+ function referenceLabel(referrerLabel, identifier, shape) {
120
+ const suffix = shape.kind === "stringArray" && shape.labelSuffix ? ` (${shape.labelSuffix})` : "";
121
+ return `${referrerLabel}: ${identifier}${suffix}`;
122
+ }
123
+ function rewriteReferences(packagePath, config, meta, oldId, newId) {
124
+ const labels = [];
125
+ const files = [];
126
+ for (const site of meta.referenceSites) {
127
+ for (const referrerKey of site.referrerKeys) {
128
+ if (referrerKey === MANIFEST_REFERRER) {
129
+ const manifest = config;
130
+ const modified = newId === null ? removeFromDefinition(manifest, site.shape, oldId) : renameInDefinition(manifest, site.shape, oldId, newId);
131
+ if (modified) {
132
+ const file = configFile(packagePath);
133
+ writeJson(file, config);
134
+ files.push(file);
135
+ labels.push(referenceLabel("Game", gameIdentifier(config), site.shape));
136
+ }
137
+ continue;
138
+ }
139
+ const referrerMeta = RESOURCE_METADATA_BY_MANIFEST_KEY.get(referrerKey);
140
+ const referrerLabel = referrerMeta?.label ?? referrerKey;
141
+ for (const relPath of bundlePaths(packagePath, referrerMeta ?? meta)) {
142
+ const file = join2(packagePath, relPath);
143
+ const bundle = readJson(file);
144
+ const def = bundle?.definition;
145
+ if (!def) continue;
146
+ const modified = newId === null ? removeFromDefinition(def, site.shape, oldId) : renameInDefinition(def, site.shape, oldId, newId);
147
+ if (modified) {
148
+ writeJson(file, bundle);
149
+ files.push(file);
150
+ labels.push(
151
+ referenceLabel(
152
+ referrerLabel,
153
+ nameFromPath(referrerMeta ?? meta, relPath),
154
+ site.shape
155
+ )
156
+ );
157
+ }
158
+ }
159
+ }
160
+ }
161
+ return { labels, files };
162
+ }
163
+ function resourceDirFromPath(packagePath, meta, relPath) {
164
+ return join2(packagePath, relPath.replace(`/${meta.bundleFile}`, ""));
165
+ }
166
+ function nameFromPath(meta, relPath) {
167
+ return meta.slot ?? relPath.split("/")[1];
168
+ }
169
+ function findBundlePath(packagePath, meta, identifier) {
170
+ return bundlePaths(packagePath, meta).find(
171
+ (relPath) => nameFromPath(meta, relPath) === identifier
172
+ );
173
+ }
174
+ function configFile(packagePath) {
175
+ return join2(packagePath, "seriousgaming.sdk.json");
176
+ }
177
+ function gameIdentifier(config) {
178
+ return `${config.identifier ?? "(unknown)"}.game`;
179
+ }
180
+ async function createResourceFiles(meta, options, scaffold) {
181
+ const filesCreated = [];
182
+ try {
183
+ if (!existsSync2(configFile(options.packagePath))) {
184
+ return {
185
+ success: false,
186
+ error: "seriousgaming.sdk.json not found. This command must be run in a Serious Gaming package directory."
187
+ };
188
+ }
189
+ const dir = meta.slot ? join2(options.packagePath, meta.slot) : join2(options.packagePath, meta.pluralDir, requireIdentifier(meta, options));
190
+ if (existsSync2(dir)) {
191
+ return {
192
+ success: false,
193
+ error: scaffold.alreadyExists?.(dir) ?? `${meta.label} directory already exists: ${dir}`
194
+ };
195
+ }
196
+ mkdirSync(dir, { recursive: true });
197
+ for (const directory of scaffold.directories ?? []) {
198
+ mkdirSync(join2(dir, directory), { recursive: true });
199
+ }
200
+ const rootDirectory = meta.layout ? "." : scaffold.rootDirectory;
201
+ const bundlePath = join2(dir, meta.bundleFile);
202
+ const { identifier: _named, ...definition } = scaffold.definition;
203
+ writeJsonFile(bundlePath, {
204
+ definition,
205
+ ...meta.layout,
206
+ ...rootDirectory !== void 0 && { rootDirectory }
207
+ });
208
+ filesCreated.push(bundlePath);
209
+ for (const file of scaffold.files ?? []) {
210
+ const path = join2(dir, file.path);
211
+ mkdirSync(dirname2(path), { recursive: true });
212
+ await renderAndWriteTemplate(file.template, path, file.data ?? {});
213
+ filesCreated.push(path);
214
+ }
215
+ return { success: true, filesCreated };
216
+ } catch (error) {
217
+ return {
218
+ success: false,
219
+ error: error instanceof Error ? error.message : "Unknown error occurred",
220
+ filesCreated
221
+ };
222
+ }
223
+ }
224
+ function requireIdentifier(meta, options) {
225
+ if (!options.identifier) throw new Error(`A ${meta.label.toLowerCase()} needs a name`);
226
+ return options.identifier;
227
+ }
228
+ function presentFields(fields) {
229
+ return Object.fromEntries(
230
+ Object.entries(fields).filter(([, value]) => {
231
+ if (value === void 0 || value === "") return false;
232
+ if (Array.isArray(value)) return value.length > 0;
233
+ if (typeof value === "object" && value !== null) return Object.keys(value).length > 0;
234
+ return true;
235
+ })
236
+ );
237
+ }
238
+ function updateResourceFiles(meta, options) {
239
+ try {
240
+ const configPath = configFile(options.packagePath);
241
+ const config = readJson(configPath);
242
+ if (!config) return { success: false, error: "seriousgaming.sdk.json not found" };
243
+ const bundlePath = findBundlePath(options.packagePath, meta, options.oldIdentifier);
244
+ if (!bundlePath) {
245
+ return { success: false, error: `${meta.label} not found in package configuration` };
246
+ }
247
+ const bundleFilePath = join2(options.packagePath, bundlePath);
248
+ const bundle = readJson(bundleFilePath);
249
+ if (!bundle) return { success: false, error: `Could not read ${meta.label} file` };
250
+ bundle.definition = meta.mergeDefinition ? { ...bundle.definition, ...options.newDefinition } : options.newDefinition;
251
+ delete bundle.definition.identifier;
252
+ const filesUpdated = [];
253
+ const referencesUpdated = [];
254
+ const directoriesRenamed = [];
255
+ const newIdentifier = options.newIdentifier ?? options.oldIdentifier;
256
+ if (newIdentifier !== options.oldIdentifier) {
257
+ if (meta.slot) {
258
+ return {
259
+ success: false,
260
+ error: `A game holds one ${meta.label.toLowerCase()}, so it lives in the "${meta.slot}" slot and has no name to change.`
261
+ };
262
+ }
263
+ const { labels } = rewriteReferences(
264
+ options.packagePath,
265
+ config,
266
+ meta,
267
+ options.oldIdentifier,
268
+ newIdentifier
269
+ );
270
+ referencesUpdated.push(...labels);
271
+ const oldDir = resourceDirFromPath(options.packagePath, meta, bundlePath);
272
+ const newDir = join2(options.packagePath, meta.pluralDir, newIdentifier);
273
+ if (!existsSync2(dirname2(newDir))) mkdirSync(dirname2(newDir), { recursive: true });
274
+ renameSync(oldDir, newDir);
275
+ directoriesRenamed.push({ from: oldDir, to: newDir });
276
+ const newBundleFile = join2(newDir, meta.bundleFile);
277
+ writeJson(newBundleFile, bundle);
278
+ filesUpdated.push(newBundleFile);
279
+ } else {
280
+ writeJson(bundleFilePath, bundle);
281
+ filesUpdated.push(bundleFilePath);
282
+ }
283
+ return {
284
+ success: true,
285
+ filesUpdated,
286
+ referencesUpdated: referencesUpdated.length > 0 ? referencesUpdated : void 0,
287
+ directoriesRenamed: directoriesRenamed.length > 0 ? directoriesRenamed : void 0
288
+ };
289
+ } catch (error) {
290
+ return {
291
+ success: false,
292
+ error: error instanceof Error ? error.message : "Unknown error occurred"
293
+ };
294
+ }
295
+ }
296
+ function deleteResourceFiles(meta, options) {
297
+ try {
298
+ const configPath = configFile(options.packagePath);
299
+ const config = readJson(configPath);
300
+ if (!config) return { success: false, error: "seriousgaming.sdk.json not found" };
301
+ const bundlePath = findBundlePath(options.packagePath, meta, options.identifier);
302
+ if (!bundlePath) {
303
+ return { success: false, error: `${meta.label} not found in package configuration` };
304
+ }
305
+ const dir = resourceDirFromPath(options.packagePath, meta, bundlePath);
306
+ if (!existsSync2(dir)) {
307
+ return { success: false, error: `${meta.label} directory not found: ${dir}` };
308
+ }
309
+ const { labels } = rewriteReferences(
310
+ options.packagePath,
311
+ config,
312
+ meta,
313
+ options.identifier,
314
+ null
315
+ );
316
+ rmSync(dir, { recursive: true });
317
+ return {
318
+ success: true,
319
+ filesDeleted: [dir],
320
+ referencesRemoved: labels
321
+ };
322
+ } catch (error) {
323
+ return {
324
+ success: false,
325
+ error: error instanceof Error ? error.message : "Unknown error occurred"
326
+ };
327
+ }
328
+ }
329
+ function findResourceReferences(meta, options) {
330
+ const config = readJson(configFile(options.packagePath));
331
+ if (!config) return [];
332
+ const references = [];
333
+ for (const site of meta.referenceSites) {
334
+ for (const referrerKey of site.referrerKeys) {
335
+ if (referrerKey === MANIFEST_REFERRER) {
336
+ if (definitionReferences(config, site.shape, options.identifier)) {
337
+ references.push(referenceLabel("Game", gameIdentifier(config), site.shape));
338
+ }
339
+ continue;
340
+ }
341
+ const referrerMeta = RESOURCE_METADATA_BY_MANIFEST_KEY.get(referrerKey);
342
+ const referrerLabel = referrerMeta?.label ?? referrerKey;
343
+ for (const relPath of bundlePaths(options.packagePath, referrerMeta ?? meta)) {
344
+ const bundle = readJson(join2(options.packagePath, relPath));
345
+ const def = bundle?.definition;
346
+ if (def && definitionReferences(def, site.shape, options.identifier)) {
347
+ references.push(
348
+ referenceLabel(
349
+ referrerLabel,
350
+ nameFromPath(referrerMeta ?? meta, relPath),
351
+ site.shape
352
+ )
353
+ );
354
+ }
355
+ }
356
+ }
357
+ }
358
+ return references;
359
+ }
360
+
361
+ export {
362
+ copyStaticFile,
363
+ renderAndWriteTemplate,
364
+ writeJsonFile,
365
+ createResourceFiles,
366
+ presentFields,
367
+ updateResourceFiles,
368
+ deleteResourceFiles,
369
+ findResourceReferences
370
+ };