@seriousgaming/sdk-tools 1.5.0 → 1.6.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 (160) hide show
  1. package/dist/bundling/ui-bundler.d.ts +12 -0
  2. package/dist/cli-25RWY5BQ.js +41 -0
  3. package/dist/cli-272KBNJH.js +97 -0
  4. package/dist/cli-2BH7FX27.js +52 -0
  5. package/dist/cli-2GOFEW26.js +81 -0
  6. package/dist/cli-3E3MD5U4.js +21 -0
  7. package/dist/cli-3HE4AVZG.js +115 -0
  8. package/dist/cli-4AKVLEC4.js +1387 -0
  9. package/dist/cli-4BV45LBH.js +126 -0
  10. package/dist/cli-4LKXZQ2B.js +48 -0
  11. package/dist/cli-4UWFQNGF.js +54 -0
  12. package/dist/cli-4YB3ROVR.js +78 -0
  13. package/dist/cli-57RXC3HQ.js +36 -0
  14. package/dist/cli-5JEGTVTG.js +96 -0
  15. package/dist/cli-6AMT3BUO.js +97 -0
  16. package/dist/cli-6RRVEGFB.js +80 -0
  17. package/dist/cli-6WXLXJVX.js +36 -0
  18. package/dist/cli-7OGYADZ3.js +97 -0
  19. package/dist/cli-AK7OIPWY.js +229 -0
  20. package/dist/cli-B4TN6PJP.js +124 -0
  21. package/dist/cli-B6YHEKIJ.js +248 -0
  22. package/dist/cli-BPYMTOUL.js +89 -0
  23. package/dist/cli-BWX5E7TQ.js +23 -0
  24. package/dist/cli-BYJWFFCF.js +37 -0
  25. package/dist/cli-C3NVCKO6.js +43 -0
  26. package/dist/cli-C47GJATR.js +42 -0
  27. package/dist/cli-C5QOJJWX.js +46 -0
  28. package/dist/cli-C6TH5S7K.js +6417 -0
  29. package/dist/cli-DL2CVMRF.js +89 -0
  30. package/dist/cli-DMW2OQIJ.js +76 -0
  31. package/dist/cli-DZW3XD5F.js +143 -0
  32. package/dist/cli-E2NLWIFE.js +1331 -0
  33. package/dist/cli-E33CJRRQ.js +36 -0
  34. package/dist/cli-E6DJIMYD.js +142 -0
  35. package/dist/cli-EEFJKIGL.js +151 -0
  36. package/dist/cli-EVFS55WN.js +185 -0
  37. package/dist/cli-F2D4GGUA.js +549 -0
  38. package/dist/cli-FBTRTIZJ.js +226 -0
  39. package/dist/cli-FWFRKQNE.js +11 -0
  40. package/dist/cli-FYINNRML.js +760 -0
  41. package/dist/cli-G522CPRL.js +88 -0
  42. package/dist/cli-G6KELFSX.js +2847 -0
  43. package/dist/cli-G6UE5NL4.js +90 -0
  44. package/dist/cli-GBFM76BF.js +16 -0
  45. package/dist/cli-GDQ6ILJY.js +101 -0
  46. package/dist/cli-GFBGYFYD.js +50 -0
  47. package/dist/cli-GGPDQNM3.js +35 -0
  48. package/dist/cli-GTSGLN3Z.js +307 -0
  49. package/dist/cli-GUXKQMJ7.js +13641 -0
  50. package/dist/cli-GXD36NF2.js +60 -0
  51. package/dist/cli-HCRTYQQS.js +16 -0
  52. package/dist/cli-HYY64SUD.js +185 -0
  53. package/dist/cli-I355WTAF.js +463 -0
  54. package/dist/cli-IDKYF5XB.js +59 -0
  55. package/dist/cli-ILKCQNM6.js +8 -0
  56. package/dist/cli-IRZ5KB7D.js +36 -0
  57. package/dist/cli-IUS2YCD3.js +31 -0
  58. package/dist/cli-J4DKUUTK.js +138 -0
  59. package/dist/cli-JFU22EJ2.js +187 -0
  60. package/dist/cli-JMZLT65J.js +226 -0
  61. package/dist/cli-JZM7XTNV.js +89 -0
  62. package/dist/cli-K2B6WHKA.js +81 -0
  63. package/dist/cli-KL3756X6.js +126 -0
  64. package/dist/cli-KNOOKGYW.js +88 -0
  65. package/dist/cli-LFGRFIEO.js +226 -0
  66. package/dist/cli-LFM7GJHI.js +0 -0
  67. package/dist/cli-LMDJCHHD.js +304 -0
  68. package/dist/cli-LXYPE3L5.js +99 -0
  69. package/dist/cli-M6BCQRID.js +153 -0
  70. package/dist/cli-MBNMPVDC.js +367 -0
  71. package/dist/cli-MJUYJIEP.js +13 -0
  72. package/dist/cli-MMN4BPO4.js +145 -0
  73. package/dist/cli-MYJGMA6U.js +40 -0
  74. package/dist/cli-N6H6T2E2.js +616 -0
  75. package/dist/cli-O5KP4OVN.js +61 -0
  76. package/dist/cli-O6PWMJTZ.js +25 -0
  77. package/dist/cli-ORIG557O.js +141 -0
  78. package/dist/cli-PFFCNGHI.js +243 -0
  79. package/dist/cli-PNLYX6R6.js +131 -0
  80. package/dist/cli-PQBXVLEU.js +649 -0
  81. package/dist/cli-PTT5RGKO.js +62 -0
  82. package/dist/cli-Q2XJF5AS.js +127 -0
  83. package/dist/cli-QEVDDBNO.js +60 -0
  84. package/dist/cli-QEVE5HUM.js +167 -0
  85. package/dist/cli-QUIJCBYB.js +391 -0
  86. package/dist/cli-QUNIRH7A.js +57 -0
  87. package/dist/cli-QVASWX2A.js +187 -0
  88. package/dist/cli-QWQMPCL6.js +253 -0
  89. package/dist/cli-R4PCG5YX.js +131 -0
  90. package/dist/cli-RA673NGF.js +53 -0
  91. package/dist/cli-RN6IWTL2.js +36 -0
  92. package/dist/cli-ROT3DRKU.js +145 -0
  93. package/dist/cli-RZITKPJX.js +367 -0
  94. package/dist/cli-S5IVGDDD.js +32 -0
  95. package/dist/cli-S5QDONIQ.js +218 -0
  96. package/dist/cli-SIPDUBFL.js +36 -0
  97. package/dist/cli-SMFSZF2G.js +4009 -0
  98. package/dist/cli-SRHBXZCN.js +159 -0
  99. package/dist/cli-TCY5LJ7E.js +88 -0
  100. package/dist/cli-TDSQSCX4.js +131 -0
  101. package/dist/cli-TIDQ4WUE.js +257 -0
  102. package/dist/cli-TLLA6KAP.js +79 -0
  103. package/dist/cli-TPU4TUR6.js +132 -0
  104. package/dist/cli-U2UE7I7J.js +30 -0
  105. package/dist/cli-UELGBQG7.js +101 -0
  106. package/dist/cli-UHSZBKYO.js +97 -0
  107. package/dist/cli-UJ4UCL2Z.js +38 -0
  108. package/dist/cli-UKQYZYFK.js +31 -0
  109. package/dist/cli-UMFFURZ7.js +81 -0
  110. package/dist/cli-UNAJ2OTE.js +15 -0
  111. package/dist/cli-UNJ5X6BU.js +89 -0
  112. package/dist/cli-UTJU4IYG.js +117 -0
  113. package/dist/cli-V4GHRWOV.js +1837 -0
  114. package/dist/cli-VCI3CG36.js +73 -0
  115. package/dist/cli-VCKOC2EV.js +256 -0
  116. package/dist/cli-VL2P354N.js +46 -0
  117. package/dist/cli-WAE26SVW.js +72 -0
  118. package/dist/cli-WOGIAU2E.js +100 -0
  119. package/dist/cli-WU43JT4T.js +52 -0
  120. package/dist/cli-XCO2VQOH.js +122 -0
  121. package/dist/cli-XSVGKI3R.js +39 -0
  122. package/dist/cli-YOTGR3NB.js +82 -0
  123. package/dist/cli-YVVXUD2G.js +197 -0
  124. package/dist/cli-ZISJ36MM.js +89 -0
  125. package/dist/cli-ZTWOE3ZT.js +65 -0
  126. package/dist/cli-ZVSFYDPQ.js +205 -0
  127. package/dist/cli-ZWPYIXNI.js +68 -0
  128. package/dist/cli.js +148 -43093
  129. package/dist/client/build-surfaces.d.ts +33 -0
  130. package/dist/client/dev-server.d.ts +6 -0
  131. package/dist/client/index.d.ts +1 -0
  132. package/dist/client/playwright.d.ts +62 -0
  133. package/dist/client.js +228 -48
  134. package/dist/core/session.d.ts +15 -1
  135. package/dist/dev/console/assets/{index-BVF8exas.js → index-CuMOOH9m.js} +1 -1
  136. package/dist/dev/console/index.html +1 -1
  137. package/dist/dev/shell.d.ts +19 -0
  138. package/dist/dev/surfaces.d.ts +7 -0
  139. package/dist/docs/api/index.md +14 -12
  140. package/dist/docs/api/sdk-tools-client.md +29 -0
  141. package/dist/docs/api/sdk-tools-playwright.md +104 -0
  142. package/dist/docs/changelog.md +19 -0
  143. package/dist/docs/cli-and-dev-server.md +21 -0
  144. package/dist/docs/cli-reference.md +45 -31
  145. package/dist/docs/environment-variables.md +6 -0
  146. package/dist/docs/guides/designing-a-game.md +29 -4
  147. package/dist/docs/guides/starter-game.md +2 -2
  148. package/dist/docs/guides/testing.md +33 -18
  149. package/dist/docs/page-index.md +8 -7
  150. package/dist/docs/recipes/e2e-testing.md +19 -20
  151. package/dist/playwright.js +32232 -0
  152. package/dist/templates/package/claude/rules/workflow-test-engine-or-ui.md +1 -1
  153. package/dist/templates/package/global-setup.ts.template +7 -18
  154. package/dist/templates/package/playwright.config.ts.liquid +8 -11
  155. package/dist/templates/starter-game/playwright.config.ts +8 -11
  156. package/dist/templates/starter-game/testing/e2e/game.spec.ts +1 -1
  157. package/dist/templates/starter-game/testing/e2e/global-setup.ts +7 -18
  158. package/dist/utils/prompt.d.ts +5 -5
  159. package/dist/utils/resource-scan.d.ts +39 -0
  160. package/package.json +7 -3
@@ -0,0 +1,1837 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ SEMVER_PATTERN
4
+ } from "./cli-ILKCQNM6.js";
5
+ import {
6
+ validateEndpoint,
7
+ validateEndpointFiles,
8
+ validateEngine,
9
+ validateEngineFiles,
10
+ validateHook,
11
+ validateTickController,
12
+ validateUIFiles,
13
+ validateUserInterface,
14
+ validateValidator
15
+ } from "./cli-JMZLT65J.js";
16
+ import {
17
+ fileSettingDeclarationErrors,
18
+ isChapterEmpty,
19
+ memberDeclarations,
20
+ packageFileSettingErrors,
21
+ referenceLocale,
22
+ settingReferences,
23
+ strayFences
24
+ } from "./cli-GUXKQMJ7.js";
25
+ import {
26
+ SCENARIO_VALIDATION,
27
+ hasScenarioGate,
28
+ runScenarioGates,
29
+ validateTsTypes
30
+ } from "./cli-VCKOC2EV.js";
31
+ import {
32
+ LogicLoader,
33
+ applySchemaDefaults,
34
+ deepMergeContext,
35
+ resolveCapabilityScope
36
+ } from "./cli-E2NLWIFE.js";
37
+ import {
38
+ describeAssetByReference
39
+ } from "./cli-QWQMPCL6.js";
40
+ import {
41
+ GAME_SETTINGS,
42
+ LOGIC_NODE_BUILTIN,
43
+ MANIFEST_FILE,
44
+ Transpile,
45
+ bundleFileOf,
46
+ collectSettingsOverrideErrors,
47
+ collectSettingsOverrideFindings,
48
+ createAjv,
49
+ declaredGameSettings,
50
+ dereference,
51
+ didYouMean,
52
+ getResourceMeta,
53
+ loadConfig,
54
+ openSettingsObjects,
55
+ parseSettingPath,
56
+ pointerOf,
57
+ refProblemMessage,
58
+ refProblems,
59
+ settingsSchemas,
60
+ teamsMaxOf,
61
+ unenforceableLockMessage,
62
+ unenforceableLocks
63
+ } from "./cli-SMFSZF2G.js";
64
+
65
+ // cli/validation/package-validation.ts
66
+ import { existsSync as existsSync2 } from "fs";
67
+ import { readFile } from "fs/promises";
68
+ import { dirname as dirname2, resolve as resolve2 } from "path";
69
+
70
+ // cli/validation/facilitator-guide-validator.ts
71
+ import { existsSync, readdirSync, readFileSync, statSync } from "fs";
72
+ import { dirname, join, resolve, sep } from "path";
73
+
74
+ // cli/guide/video-registry.ts
75
+ var VIDEO_PROVIDERS = {
76
+ youtube: {
77
+ idPattern: /^[A-Za-z0-9_-]{11}$/,
78
+ embedUrl: (id) => `https://www.youtube-nocookie.com/embed/${id}`,
79
+ embedHosts: ["www.youtube-nocookie.com"]
80
+ }
81
+ };
82
+ var FILE_VIDEO_PROVIDER = "file";
83
+ var FILE_VIDEO_EXTENSIONS = {
84
+ src: ["mp4", "webm"],
85
+ poster: ["png", "jpg", "jpeg", "gif", "webp", "avif"],
86
+ captions: ["vtt"]
87
+ };
88
+ var ALLOWED_KEYS = {
89
+ youtube: /* @__PURE__ */ new Set(["provider", "id"]),
90
+ [FILE_VIDEO_PROVIDER]: /* @__PURE__ */ new Set(["provider", "src", "title", "poster", "captions"])
91
+ };
92
+ var SUPPORTED_PROVIDERS = [...Object.keys(VIDEO_PROVIDERS), FILE_VIDEO_PROVIDER];
93
+ var CHAPTER_BASE = "https://guide.invalid/content/locale/chapter.md";
94
+ function guideAssetPath(reference) {
95
+ if (/^[a-z][a-z0-9+.-]*:/i.test(reference) || reference.startsWith("/")) return void 0;
96
+ if (reference.includes("\\") || /[?#]/.test(reference)) return void 0;
97
+ let resolved;
98
+ try {
99
+ resolved = new URL(reference, CHAPTER_BASE);
100
+ } catch {
101
+ return void 0;
102
+ }
103
+ if (resolved.origin !== "https://guide.invalid" || !resolved.pathname.startsWith("/assets/")) {
104
+ return void 0;
105
+ }
106
+ try {
107
+ const path = decodeURIComponent(resolved.pathname.slice("/assets/".length));
108
+ const segments = path.split("/");
109
+ return segments.some((s) => s === "" || s === "." || s === ".." || s.includes("\\")) ? void 0 : path;
110
+ } catch {
111
+ return void 0;
112
+ }
113
+ }
114
+ function extensionOf(path) {
115
+ const dot = path.lastIndexOf(".");
116
+ return dot === -1 ? "" : path.slice(dot + 1).toLowerCase();
117
+ }
118
+ function parseVideoBlock(body) {
119
+ const entries = {};
120
+ for (const rawLine of body.split("\n")) {
121
+ const line = rawLine.trim();
122
+ if (line.length === 0) continue;
123
+ const match = line.match(/^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/);
124
+ if (!match) {
125
+ return { ok: false, error: `Malformed line in video block: "${line}"` };
126
+ }
127
+ const key = match[1];
128
+ const value = match[2].trim();
129
+ if (key in entries) {
130
+ return { ok: false, error: `Duplicate key "${key}" in video block` };
131
+ }
132
+ entries[key] = value;
133
+ }
134
+ const provider = entries.provider;
135
+ if (!provider) {
136
+ return { ok: false, error: 'Video block is missing "provider"' };
137
+ }
138
+ const allowed = ALLOWED_KEYS[provider];
139
+ if (!allowed) {
140
+ return {
141
+ ok: false,
142
+ error: `Unknown video provider "${provider}". Supported providers: ${SUPPORTED_PROVIDERS.join(", ")}`
143
+ };
144
+ }
145
+ for (const key of Object.keys(entries)) {
146
+ if (!allowed.has(key)) {
147
+ return { ok: false, error: `Unknown key "${key}" in video block` };
148
+ }
149
+ }
150
+ if (provider === FILE_VIDEO_PROVIDER) return parseFileVideo(entries);
151
+ const registered = VIDEO_PROVIDERS[provider];
152
+ const id = entries.id;
153
+ if (!id) {
154
+ return { ok: false, error: 'Video block is missing "id"' };
155
+ }
156
+ if (!registered.idPattern.test(id)) {
157
+ return {
158
+ ok: false,
159
+ error: `Video id "${id}" is not a valid ${provider} id`
160
+ };
161
+ }
162
+ return { ok: true, kind: "embed", provider, id, embedUrl: registered.embedUrl(id) };
163
+ }
164
+ function parseFileVideo(entries) {
165
+ if (!entries.src) {
166
+ return { ok: false, error: 'Video block is missing "src"' };
167
+ }
168
+ const files = {};
169
+ for (const key of Object.keys(
170
+ FILE_VIDEO_EXTENSIONS
171
+ )) {
172
+ const reference = entries[key];
173
+ if (reference === void 0) continue;
174
+ const path = guideAssetPath(reference);
175
+ if (!path) {
176
+ return {
177
+ ok: false,
178
+ error: `Video ${key} "${reference}" must be a file in the guide's assets/ directory`
179
+ };
180
+ }
181
+ const extensions = FILE_VIDEO_EXTENSIONS[key];
182
+ if (!extensions.includes(extensionOf(path))) {
183
+ return {
184
+ ok: false,
185
+ error: `Video ${key} "${reference}" must be a ${extensions.map((e) => `.${e}`).join(", ")} file`
186
+ };
187
+ }
188
+ files[key] = path;
189
+ }
190
+ return {
191
+ ok: true,
192
+ kind: "file",
193
+ provider: FILE_VIDEO_PROVIDER,
194
+ src: files.src,
195
+ ...files.poster ? { poster: files.poster } : {},
196
+ ...files.captions ? { captions: files.captions } : {},
197
+ ...entries.title ? { title: entries.title } : {}
198
+ };
199
+ }
200
+
201
+ // cli/validation/guide-settings-validator.ts
202
+ function typesOf(schema) {
203
+ if (Array.isArray(schema.type)) return schema.type;
204
+ return schema.type ? [schema.type] : [];
205
+ }
206
+ function propertyAt(path, context) {
207
+ const parsed = parseSettingPath(path);
208
+ if (!parsed || parsed.keys.length === 0) {
209
+ return {
210
+ error: `"${path}" should be a settings identifier and a property, e.g. engine.weeks`
211
+ };
212
+ }
213
+ const { identifier, keys } = parsed;
214
+ if (!context.declared.includes(identifier)) {
215
+ return {
216
+ error: `"${path}" reads settings "${identifier}", which the guide does not list in its settings`
217
+ };
218
+ }
219
+ const root = context.schemas[identifier];
220
+ let schema = root;
221
+ for (const key of keys) {
222
+ const properties = typeof schema === "object" && root ? dereference(root, schema).properties : void 0;
223
+ schema = properties?.[key];
224
+ if (typeof schema !== "object" || !root) {
225
+ return { error: `"${path}" names no property of settings "${identifier}"` };
226
+ }
227
+ }
228
+ return { schema: root ? dereference(root, schema) : schema };
229
+ }
230
+ function literalError(path, literal, schema) {
231
+ const types = typesOf(schema);
232
+ if (schema.enum && !schema.enum.some((value) => String(value) === literal)) {
233
+ return `is="${literal}" is not one of the values "${path}" allows (${schema.enum.join(", ")})`;
234
+ }
235
+ if (types.includes("integer") || types.includes("number")) {
236
+ const number = Number(literal);
237
+ if (literal.trim() === "" || !Number.isFinite(number)) {
238
+ return `is="${literal}" is not a number, and "${path}" is one`;
239
+ }
240
+ if (types.includes("integer") && !types.includes("number") && !Number.isInteger(number)) {
241
+ return `is="${literal}" is not a whole number, and "${path}" is one`;
242
+ }
243
+ return null;
244
+ }
245
+ if (types.includes("boolean")) {
246
+ return literal === "true" || literal === "false" ? null : `is="${literal}" should be true or false, as "${path}" is`;
247
+ }
248
+ if (types.includes("string")) return null;
249
+ return `"${path}" is not a single value a condition can compare`;
250
+ }
251
+ function resolutions(context) {
252
+ const defaults = Object.fromEntries(
253
+ context.declared.filter((identifier) => identifier in context.schemas).map((identifier) => [identifier, applySchemaDefaults(context.schemas[identifier])])
254
+ );
255
+ return [
256
+ defaults,
257
+ ...Object.values(context.scenarios).map(
258
+ (overrides) => Object.fromEntries(
259
+ Object.entries(defaults).map(([identifier, values]) => [
260
+ identifier,
261
+ deepMergeContext(values, overrides[identifier] ?? {})
262
+ ])
263
+ )
264
+ )
265
+ ];
266
+ }
267
+ function validateGuideSettings(chapters, context) {
268
+ const errors = [];
269
+ const warnings = [];
270
+ const used = /* @__PURE__ */ new Set();
271
+ for (const chapter of chapters) {
272
+ for (const line of strayFences(chapter.markdown)) {
273
+ warnings.push(
274
+ `${chapter.label}:${line}: this ::: closes nothing, so a block above it ended early; a :::when that holds another ::: block needs more colons than it, as in ::::when`
275
+ );
276
+ }
277
+ for (const reference of settingReferences(chapter.markdown)) {
278
+ const where = `${chapter.label}:${reference.line}`;
279
+ const directive = reference.kind === "value" ? ":setting" : ":::when";
280
+ for (const attribute of reference.unknownAttributes) {
281
+ errors.push(`${where}: ${directive} has no attribute "${attribute}"`);
282
+ }
283
+ if (reference.nested) {
284
+ errors.push(
285
+ `${where}: :::when sits inside another :::when; give the inner block its own condition instead`
286
+ );
287
+ }
288
+ if (reference.path === "") {
289
+ errors.push(
290
+ reference.kind === "value" ? `${where}: :setting[\u2026] names no setting` : `${where}: :::when needs setting="identifier.property"`
291
+ );
292
+ continue;
293
+ }
294
+ const identifier = parseSettingPath(reference.path)?.identifier;
295
+ if (identifier !== void 0) used.add(identifier);
296
+ const property = propertyAt(reference.path, context);
297
+ if ("error" in property) {
298
+ errors.push(`${where}: ${directive} ${property.error}`);
299
+ continue;
300
+ }
301
+ const types = typesOf(property.schema);
302
+ if (reference.kind === "value") {
303
+ const renderable = types.length > 0 && types.every((type) => ["string", "number", "integer"].includes(type));
304
+ if (!renderable) {
305
+ errors.push(
306
+ `${where}: :setting[${reference.path}] can show only a number or text, and "${reference.path}" is ${types.join(" or ") || "untyped"}`
307
+ );
308
+ }
309
+ } else if (reference.is === void 0) {
310
+ if (types.length !== 1 || types[0] !== "boolean") {
311
+ errors.push(
312
+ `${where}: :::when on "${reference.path}" needs is="\u2026", since it is not true or false`
313
+ );
314
+ }
315
+ } else {
316
+ const error = literalError(reference.path, reference.is, property.schema);
317
+ if (error) errors.push(`${where}: :::when ${error}`);
318
+ }
319
+ }
320
+ }
321
+ for (const identifier of context.declared) {
322
+ if (!used.has(identifier)) {
323
+ warnings.push(
324
+ `The guide lists settings "${identifier}" but no chapter uses it; remove it from settings`
325
+ );
326
+ }
327
+ }
328
+ if (errors.length === 0) {
329
+ const settings = resolutions(context);
330
+ for (const chapter of chapters.filter((candidate) => candidate.reference)) {
331
+ if (settings.every((resolved) => isChapterEmpty(chapter.markdown, resolved))) {
332
+ warnings.push(
333
+ `${chapter.label} is empty under the defaults and every scenario, so it never shows`
334
+ );
335
+ }
336
+ }
337
+ }
338
+ return { errors, warnings };
339
+ }
340
+
341
+ // cli/validation/facilitator-guide-validator.ts
342
+ var LARGE_VIDEO_FILE_BYTES = 25 * 1024 * 1024;
343
+ var VIDEO_BLOCK_PATTERN = /^[ \t]*```video[ \t]*\r?\n([\s\S]*?)^[ \t]*```[ \t]*$/gm;
344
+ var IMAGE_PATTERN = /!\[[^\]]*\]\(([^()\s]+)(?:\s+"[^"]*")?\)/g;
345
+ function listChapters(localeDir) {
346
+ return readdirSync(localeDir).filter((name) => name.endsWith(".md") && statSync(join(localeDir, name)).isFile()).sort();
347
+ }
348
+ function validateFacilitatorGuideContent(options) {
349
+ const errors = [];
350
+ const warnings = [];
351
+ const { definition, rootDirectory } = options;
352
+ const contentDir = join(rootDirectory, "content");
353
+ const declaredLocales = Object.keys(definition.locales);
354
+ if (!existsSync(contentDir)) {
355
+ warnings.push("Guide has no content/ directory");
356
+ return { errors, warnings };
357
+ }
358
+ for (const entry of readdirSync(contentDir)) {
359
+ if (!statSync(join(contentDir, entry)).isDirectory()) continue;
360
+ if (!declaredLocales.includes(entry)) {
361
+ warnings.push(
362
+ `Content directory "content/${entry}/" has no matching locale in the guide definition`
363
+ );
364
+ }
365
+ }
366
+ const reference = referenceLocale(definition.locales);
367
+ const referenceDir = join(contentDir, reference);
368
+ const referenceChapters = existsSync(referenceDir) ? listChapters(referenceDir) : [];
369
+ if (referenceChapters.length === 0) {
370
+ warnings.push(`Guide has no chapters for its reference locale "${reference}"`);
371
+ }
372
+ const read = [];
373
+ for (const locale of declaredLocales) {
374
+ const localeDir = join(contentDir, locale);
375
+ if (!existsSync(localeDir)) {
376
+ warnings.push(`Declared locale "${locale}" has no content/${locale}/ directory`);
377
+ continue;
378
+ }
379
+ const chapters = listChapters(localeDir);
380
+ if (locale !== reference) {
381
+ for (const missing of referenceChapters.filter((c) => !chapters.includes(c))) {
382
+ warnings.push(
383
+ `Locale "${locale}" is missing chapter "${missing}" (present in "${reference}"; it will fall back at runtime)`
384
+ );
385
+ }
386
+ for (const extra of chapters.filter((c) => !referenceChapters.includes(c))) {
387
+ warnings.push(
388
+ `Locale "${locale}" has chapter "${extra}" that does not exist in "${reference}"`
389
+ );
390
+ }
391
+ }
392
+ for (const chapter of chapters) {
393
+ const chapterPath = join(localeDir, chapter);
394
+ const content = readFileSync(chapterPath, "utf-8");
395
+ const label = `content/${locale}/${chapter}`;
396
+ read.push({ label, markdown: content, reference: locale === reference });
397
+ for (const match of content.matchAll(VIDEO_BLOCK_PATTERN)) {
398
+ const parsed = parseVideoBlock(match[1]);
399
+ if (!parsed.ok) {
400
+ errors.push(`${label}: ${parsed.error}`);
401
+ continue;
402
+ }
403
+ if (parsed.kind !== "file") continue;
404
+ const assetsDir = join(rootDirectory, "assets");
405
+ for (const [key, path] of [
406
+ ["src", parsed.src],
407
+ ["poster", parsed.poster],
408
+ ["captions", parsed.captions]
409
+ ]) {
410
+ if (path === void 0) continue;
411
+ const file = join(assetsDir, path);
412
+ if (!existsSync(file) || !statSync(file).isFile()) {
413
+ errors.push(
414
+ `${label}: video ${key} "assets/${path}" does not resolve to a file`
415
+ );
416
+ } else if (key === "src" && statSync(file).size > LARGE_VIDEO_FILE_BYTES) {
417
+ const megabytes = Math.round(statSync(file).size / (1024 * 1024));
418
+ warnings.push(
419
+ `${label}: video "assets/${path}" is ${megabytes} MB; every upload of the package carries it, so consider compressing it or embedding it from YouTube`
420
+ );
421
+ }
422
+ }
423
+ }
424
+ for (const match of content.matchAll(IMAGE_PATTERN)) {
425
+ const target = match[1];
426
+ if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith("/")) continue;
427
+ const decoded = decodeURI(target);
428
+ const resolved = resolve(dirname(chapterPath), decoded);
429
+ const guideRoot = resolve(rootDirectory);
430
+ if (resolved !== guideRoot && !resolved.startsWith(guideRoot + sep)) {
431
+ errors.push(
432
+ `${label}: image reference "${target}" escapes the guide directory`
433
+ );
434
+ } else if (!existsSync(resolved)) {
435
+ errors.push(`${label}: image reference "${target}" does not resolve to a file`);
436
+ }
437
+ }
438
+ }
439
+ }
440
+ if (options.settings) {
441
+ const checked = validateGuideSettings(read, {
442
+ ...options.settings,
443
+ declared: definition.settings ?? []
444
+ });
445
+ errors.push(...checked.errors);
446
+ warnings.push(...checked.warnings);
447
+ }
448
+ return { errors, warnings };
449
+ }
450
+
451
+ // cli/validation/game-validator.ts
452
+ function validateGame(game, config) {
453
+ const errors = [];
454
+ const warnings = [];
455
+ const findings = [];
456
+ const declared = declaredGameSettings(
457
+ config.settings?.find((entry) => entry.definition.identifier === GAME_SETTINGS)?.definition.settingsSchema
458
+ );
459
+ if (!config.waiting_room) {
460
+ const hint = "A held start shows participants the waiting room UI, and this package has none. Add one with `sdk new waiting_room`, or remove openOnStart.";
461
+ if (declared.waitingRoom.openOnStart) {
462
+ errors.push(
463
+ `game.waitingRoom.openOnStart is true, but there is no waiting room UI. ${hint}`
464
+ );
465
+ }
466
+ for (const scenario of config.scenarios ?? []) {
467
+ if (scenarioGame(scenario)?.waitingRoom?.openOnStart === true) {
468
+ errors.push(
469
+ `Scenario "${scenario.definition.identifier}" sets game.waitingRoom.openOnStart, but there is no waiting room UI. ${hint}`
470
+ );
471
+ }
472
+ }
473
+ }
474
+ warnings.push(...namesBeyondMax("game", declared));
475
+ warnings.push(...openSettingsObjectWarnings(config));
476
+ for (const scenario of config.scenarios ?? []) {
477
+ const overrides = scenarioGame(scenario);
478
+ if (!overrides?.teams) continue;
479
+ warnings.push(
480
+ ...namesBeyondMax(`Scenario "${scenario.definition.identifier}": game`, {
481
+ ...declared,
482
+ teams: {
483
+ ...declared.teams,
484
+ ...overrides.teams.max === void 0 ? {} : { max: overrides.teams.max },
485
+ ...overrides.teams.defaultNames === void 0 ? {} : { defaultNames: overrides.teams.defaultNames }
486
+ }
487
+ })
488
+ );
489
+ }
490
+ const engineIdentifiers = config.engine ? [config.engine.definition.identifier] : [];
491
+ const userInterfaceIdentifiers = config.ui ? [config.ui.definition.identifier] : [];
492
+ const engineMap = /* @__PURE__ */ new Map();
493
+ if (config.engine) engineMap.set(config.engine.definition.identifier, config.engine);
494
+ const sessionUIMap = /* @__PURE__ */ new Map();
495
+ if (config.session) sessionUIMap.set(config.session.definition.identifier, config.session);
496
+ const uiMap = /* @__PURE__ */ new Map();
497
+ if (config.ui) uiMap.set(config.ui.definition.identifier, config.ui);
498
+ const capabilityMap = /* @__PURE__ */ new Map();
499
+ if (config.capabilities) {
500
+ for (const capability of config.capabilities) {
501
+ capabilityMap.set(capability.definition.identifier, capability);
502
+ }
503
+ }
504
+ const engines = [];
505
+ for (const engineId of engineIdentifiers) {
506
+ const engine = engineMap.get(engineId);
507
+ if (!engine) {
508
+ errors.push(`Engine "${engineId}" not found in configuration`);
509
+ continue;
510
+ }
511
+ engines.push(engine);
512
+ }
513
+ for (const uiId of userInterfaceIdentifiers) {
514
+ if (!uiMap.has(uiId)) {
515
+ errors.push(`User Interface ${uiId} not found in configuration`);
516
+ }
517
+ }
518
+ if (userInterfaceIdentifiers.length > 1) {
519
+ errors.push(
520
+ `A game wires one user interface, but this one wires ${userInterfaceIdentifiers.length}: ${userInterfaceIdentifiers.join(", ")}. Render the extra surfaces inside the remaining one.`
521
+ );
522
+ }
523
+ const settingsEditors = [config.setup, config.scenario_editor].filter(
524
+ (editor) => editor !== void 0
525
+ );
526
+ for (const editor of settingsEditors) {
527
+ const references = validateSettingsEditorReferences(editor, game, config);
528
+ errors.push(...references.errors);
529
+ findings.push(...references.findings);
530
+ }
531
+ const tickControllerMap = /* @__PURE__ */ new Map();
532
+ if (config.tick_controller)
533
+ tickControllerMap.set(config.tick_controller.definition.identifier, config.tick_controller);
534
+ const hookMap = /* @__PURE__ */ new Map();
535
+ for (const hook of config.hooks ?? []) {
536
+ hookMap.set(hook.definition.identifier, hook);
537
+ }
538
+ const validatorMap = /* @__PURE__ */ new Map();
539
+ for (const validator of config.validators ?? []) {
540
+ validatorMap.set(validator.definition.identifier, validator);
541
+ }
542
+ const endpointMap = /* @__PURE__ */ new Map();
543
+ for (const endpoint of config.endpoints ?? []) {
544
+ endpointMap.set(endpoint.definition.identifier, endpoint);
545
+ }
546
+ const gameEndpointIds = new Set(endpointMap.keys());
547
+ const checkUIEndpointsSubset = (uiId, uiEndpoints, label) => {
548
+ (uiEndpoints ?? []).forEach((endpointId, index) => {
549
+ if (gameEndpointIds.has(endpointId)) return;
550
+ const message = `${label} "${uiId}" requests endpoint "${endpointId}", which this package does not declare`;
551
+ errors.push(message);
552
+ findings.push(
553
+ referenceFinding(
554
+ message,
555
+ { type: uiId, identifier: uiId },
556
+ ["endpoints", index],
557
+ endpointId,
558
+ [...gameEndpointIds]
559
+ )
560
+ );
561
+ });
562
+ };
563
+ if (config.ui) {
564
+ checkUIEndpointsSubset(
565
+ config.ui.definition.identifier,
566
+ config.ui.definition.endpoints,
567
+ "User Interface"
568
+ );
569
+ }
570
+ {
571
+ const ui = config.session;
572
+ if (ui) {
573
+ checkUIEndpointsSubset(
574
+ ui.definition.identifier,
575
+ ui.definition.endpoints,
576
+ "Session User Interface"
577
+ );
578
+ }
579
+ }
580
+ for (const editor of settingsEditors) {
581
+ checkUIEndpointsSubset(
582
+ editor.definition.identifier,
583
+ editor.definition.endpoints,
584
+ settingsEditorLabel(editor)
585
+ );
586
+ }
587
+ for (const endpoint of endpointMap.values()) {
588
+ const { identifier, visibility, description, writes, requestSchema } = endpoint.definition;
589
+ if (visibility === "external" && !description?.trim()) {
590
+ errors.push(
591
+ `Endpoint "${identifier}" is external, so it must carry a description: it is what a caller outside the game, such as an AI agent, reads to decide whether to call it`
592
+ );
593
+ }
594
+ if (visibility === "external" && requestSchema.type !== "object") {
595
+ const message = `Endpoint "${identifier}" is external, so its requestSchema must declare \`"type": "object"\` at the top: a caller outside the game, such as an AI agent, passes its request as an object of named arguments`;
596
+ errors.push(message);
597
+ const file = bundleFileOf("endpoint", identifier);
598
+ findings.push({
599
+ code: "EXTERNAL_REQUEST_NOT_OBJECT",
600
+ message,
601
+ ...file === void 0 ? {} : { file },
602
+ pointer: pointerOf("definition", "requestSchema"),
603
+ resource: { type: "endpoint", identifier },
604
+ hint: 'Wrap the request in an object, such as `{ "type": "object", "properties": { "price": { "type": "number" } }, "required": ["price"], "additionalProperties": false }`, or use `{ "type": "object", "properties": {}, "additionalProperties": false }` for an endpoint that takes no input. Otherwise make the endpoint internal.'
605
+ });
606
+ }
607
+ (writes ?? []).forEach((capabilityId, index) => {
608
+ if (capabilityMap.has(capabilityId)) return;
609
+ const message = `Endpoint "${identifier}" writes capability "${capabilityId}", which this package does not declare`;
610
+ errors.push(message);
611
+ findings.push(
612
+ referenceFinding(
613
+ message,
614
+ { type: "endpoint", identifier },
615
+ ["writes", index],
616
+ capabilityId,
617
+ [...capabilityMap.keys()]
618
+ )
619
+ );
620
+ });
621
+ errors.push(...endpointSchemaErrors(endpoint));
622
+ }
623
+ const checkEndpointScope = (uiId, endpoints, label) => {
624
+ for (const endpointId of endpoints ?? []) {
625
+ const endpoint = endpointMap.get(endpointId);
626
+ if (endpoint && (endpoint.definition.scope ?? "team") === "team") {
627
+ errors.push(
628
+ `${label} "${uiId}" calls endpoint "${endpointId}", which is team-scoped, but this surface has no team of its own. Declare the endpoint as \`"scope": "session"\``
629
+ );
630
+ }
631
+ }
632
+ };
633
+ if (config.session) {
634
+ checkEndpointScope(
635
+ config.session.definition.identifier,
636
+ config.session.definition.endpoints,
637
+ "Session User Interface"
638
+ );
639
+ }
640
+ if (config.setup) {
641
+ checkEndpointScope(
642
+ config.setup.definition.identifier,
643
+ config.setup.definition.endpoints,
644
+ settingsEditorLabel(config.setup)
645
+ );
646
+ }
647
+ const sessionSurfaces = [
648
+ ...config.ui ? [
649
+ [
650
+ config.ui.definition.identifier,
651
+ config.ui.definition.endpoints,
652
+ "User Interface"
653
+ ]
654
+ ] : [],
655
+ ...config.waiting_room ? [
656
+ [
657
+ config.waiting_room.definition.identifier,
658
+ config.waiting_room.definition.endpoints,
659
+ "Waiting Room User Interface"
660
+ ]
661
+ ] : [],
662
+ ...config.session ? [
663
+ [
664
+ config.session.definition.identifier,
665
+ config.session.definition.endpoints,
666
+ "Session User Interface"
667
+ ]
668
+ ] : [],
669
+ ...config.setup ? [
670
+ [
671
+ config.setup.definition.identifier,
672
+ config.setup.definition.endpoints,
673
+ settingsEditorLabel(config.setup)
674
+ ]
675
+ ] : []
676
+ ];
677
+ for (const [uiId, endpoints, label] of sessionSurfaces) {
678
+ for (const endpointId of endpoints ?? []) {
679
+ if (endpointMap.get(endpointId)?.definition.scope !== "scenario") continue;
680
+ errors.push(
681
+ `${label} "${uiId}" calls endpoint "${endpointId}", which is scenario-scoped, but this surface runs in a session and a scenario-scoped endpoint works on a scenario draft. Only the scenario editor may list it`
682
+ );
683
+ }
684
+ }
685
+ if (config.scenario_editor) {
686
+ const editorId = config.scenario_editor.definition.identifier;
687
+ (config.scenario_editor.definition.endpoints ?? []).forEach((endpointId, index) => {
688
+ const definition = endpointMap.get(endpointId)?.definition;
689
+ if (!definition || definition.scope === "scenario") return;
690
+ const message = `Scenario Editor "${editorId}" calls endpoint "${endpointId}", which is ${definition.scope ?? "team"}-scoped, but the scenario editor works on a scenario draft with no session, so it calls scenario-scoped endpoints alone`;
691
+ errors.push(message);
692
+ const file = bundleFileOf("scenario_editor", editorId);
693
+ findings.push({
694
+ code: "EDITOR_ENDPOINT_NOT_SCENARIO",
695
+ message,
696
+ ...file === void 0 ? {} : { file },
697
+ pointer: pointerOf("definition", "endpoints", index),
698
+ resource: { type: "scenario_editor", identifier: editorId },
699
+ hint: `Declare "${endpointId}" as \`"scope": "scenario"\`: it then receives the draft's settings and nothing of game state. An endpoint that needs \`reads\`, \`writes\` or \`actions\` has no place on the editor.`
700
+ });
701
+ });
702
+ }
703
+ for (const endpoint of endpointMap.values()) {
704
+ const { definition } = endpoint;
705
+ if (definition.scope !== "scenario") continue;
706
+ const stateful = [
707
+ ...["reads", "writes", "actions"].filter(
708
+ (field) => (definition[field] ?? []).length > 0
709
+ ),
710
+ ...definition.roster ? ["roster"] : []
711
+ ];
712
+ if (stateful.length === 0) continue;
713
+ const fields = stateful.map((field) => `\`${field}\``).join(", ");
714
+ const message = `Endpoint "${definition.identifier}" is scenario-scoped but declares ${fields}: it runs on a scenario draft with no session, so there is no game state to read, write or act on`;
715
+ errors.push(message);
716
+ const file = bundleFileOf("endpoint", definition.identifier);
717
+ findings.push({
718
+ code: "SCENARIO_ENDPOINT_STATEFUL",
719
+ message,
720
+ ...file === void 0 ? {} : { file },
721
+ pointer: pointerOf("definition", stateful[0] ?? "scope"),
722
+ resource: { type: "endpoint", identifier: definition.identifier },
723
+ hint: `A scenario-scoped endpoint receives the draft's settings alone. Remove ${fields}, or make it a session-scoped endpoint for the session's own surfaces.`
724
+ });
725
+ }
726
+ errors.push(...collectMissingSettingsDefaults(config));
727
+ errors.push(...collectVestigialRequired(config));
728
+ if (declared.maxTicks === null && !config.tick_controller) {
729
+ const message = `Game "${game.definition.identifier}" declares neither "maxTicks" nor a tick_controller, so only its engine can end it, by returning complete: true from Run. If it never does, the game has no termination condition.`;
730
+ warnings.push(message);
731
+ findings.push({
732
+ severity: "warning",
733
+ code: "NO_TERMINATION",
734
+ message,
735
+ file: MANIFEST_FILE,
736
+ pointer: "",
737
+ hint: "Set `maxTicks` in seriousgaming.sdk.json, add a tick controller, or make sure Run returns complete: true."
738
+ });
739
+ }
740
+ if (config.scenario_editor && game.definition.customScenarios?.supported !== true) {
741
+ const editorId = config.scenario_editor.definition.identifier;
742
+ const message = `Game "${game.definition.identifier}" ships a scenario_editor but does not set customScenarios.supported, so no host will ever open the editor.`;
743
+ warnings.push(message);
744
+ findings.push({
745
+ severity: "warning",
746
+ code: "SCENARIO_EDITOR_UNREACHABLE",
747
+ message,
748
+ file: MANIFEST_FILE,
749
+ pointer: "",
750
+ resource: { type: "scenario_editor", identifier: editorId },
751
+ hint: 'Set `"customScenarios": { "supported": true }` in seriousgaming.sdk.json, or delete the scenario_editor if the game should not offer custom scenarios.'
752
+ });
753
+ }
754
+ const settingsReferences = collectUnknownSettingsReferences(config);
755
+ errors.push(...settingsReferences.errors);
756
+ findings.push(...settingsReferences.findings);
757
+ if (errors.length > 0) {
758
+ return { success: false, errors, warnings, findings };
759
+ }
760
+ const sharedWriteValidation = validateSharedCapabilityWrites(game, engines, config);
761
+ errors.push(...sharedWriteValidation.errors);
762
+ const uiSharedWriteValidation = validateUISharedCapabilityWrites(config);
763
+ errors.push(...uiSharedWriteValidation.errors);
764
+ const endpointWriteValidation = validateEndpointCapabilityWrites(config);
765
+ errors.push(...endpointWriteValidation.errors);
766
+ const scopeValidation = validateCapabilityScopes(game, engines, config);
767
+ errors.push(...scopeValidation.errors);
768
+ const privateScopeValidation = validatePrivateCapabilityDeclarations(config);
769
+ errors.push(...validateSessionLifetimeDeclarations(config));
770
+ for (const validator of config.validators ?? []) {
771
+ if (validator.definition.gates && validator.definition.gates.length === 0) {
772
+ errors.push(
773
+ `Validator "${validator.definition.identifier}" exports none of \`UpdateData\`, \`RequestTick\` and \`Scenario\`, so it gates nothing. Export \`UpdateData\` to gate a context write, \`RequestTick\` to gate a tick request, or \`Scenario\` to gate a scenario.`
774
+ );
775
+ }
776
+ }
777
+ errors.push(...privateScopeValidation.errors);
778
+ const crossTeamParticipantsValidation = validateCrossTeamParticipants(game, uiMap);
779
+ errors.push(...crossTeamParticipantsValidation.errors);
780
+ const localeValidation = validateGameLocales(game);
781
+ errors.push(...localeValidation.errors);
782
+ const requestedEndpoints = /* @__PURE__ */ new Set();
783
+ const collectEndpoints = (endpoints) => {
784
+ for (const id of endpoints ?? []) requestedEndpoints.add(id);
785
+ };
786
+ collectEndpoints(config.ui?.definition.endpoints);
787
+ collectEndpoints(config.session?.definition.endpoints);
788
+ for (const editor of settingsEditors) collectEndpoints(editor.definition.endpoints);
789
+ for (const endpointId of gameEndpointIds) {
790
+ if (endpointMap.get(endpointId)?.definition.visibility === "external") continue;
791
+ if (!requestedEndpoints.has(endpointId)) {
792
+ const message = `Package declares endpoint "${endpointId}" but no user interface requests it`;
793
+ warnings.push(message);
794
+ const file = bundleFileOf("endpoint", endpointId);
795
+ findings.push({
796
+ severity: "warning",
797
+ code: "ENDPOINT_UNREQUESTED",
798
+ message,
799
+ ...file === void 0 ? {} : { file },
800
+ resource: { type: "endpoint", identifier: endpointId },
801
+ hint: 'List it in a user interface\'s `endpoints`, make it `"visibility": "external"`, or delete it.'
802
+ });
803
+ }
804
+ }
805
+ return {
806
+ success: errors.length === 0,
807
+ errors,
808
+ warnings,
809
+ findings,
810
+ engine: config.engine
811
+ };
812
+ }
813
+ function referenceFinding(message, referrer, path, name, known) {
814
+ const file = bundleFileOf(referrer.type, referrer.identifier);
815
+ const hint = didYouMean(name, known);
816
+ return {
817
+ code: "REFERENCE_UNKNOWN",
818
+ message,
819
+ ...file === void 0 ? {} : { file },
820
+ pointer: pointerOf("definition", ...path),
821
+ resource: referrer,
822
+ ...hint === void 0 ? {} : { hint }
823
+ };
824
+ }
825
+ function collectMissingSettingsDefaults(config) {
826
+ const errors = [];
827
+ for (const settings of config.settings ?? []) {
828
+ const schema = settings.definition.settingsSchema;
829
+ for (const [property, definition] of Object.entries(schema?.properties ?? {})) {
830
+ if (definition && typeof definition === "object" && "default" in definition) continue;
831
+ errors.push(
832
+ `Settings property "${property}" on settings "${settings.definition.identifier}" declares no default. Every settingsSchema property needs one, so resolved settings are always complete.`
833
+ );
834
+ }
835
+ }
836
+ return errors;
837
+ }
838
+ function openSettingsObjectWarnings(config) {
839
+ return (config.settings ?? []).flatMap(
840
+ (settings) => openSettingsObjects(settings.definition.settingsSchema).map(
841
+ (pointer) => `Settings "${settings.definition.identifier}" leaves the object at ${pointer === "" ? "the top of its settingsSchema" : `settingsSchema${pointer}`} open. A key it does not declare is refused all the same; add "additionalProperties": false so the schema says so.`
842
+ )
843
+ );
844
+ }
845
+ function collectVestigialRequired(config) {
846
+ const errors = [];
847
+ for (const settings of config.settings ?? []) {
848
+ if (!Array.isArray(settings.definition.settingsSchema.required)) continue;
849
+ errors.push(
850
+ `The settingsSchema on settings "${settings.definition.identifier}" declares "required". Every property must declare a default, so every one is always present and the list rejects nothing. Delete it. A property with no sensible value of its own defaults to an empty one ("", [] or {}); when every scenario must replace it, a validator's \`Scenario\` gate can refuse a scenario that does not.`
851
+ );
852
+ }
853
+ return errors;
854
+ }
855
+ function collectUnknownSettingsReferences(config) {
856
+ const known = (config.settings ?? []).map((s) => s.definition.identifier);
857
+ const declared = new Set(known);
858
+ const resources = [
859
+ { label: 'Engine "engine"', type: "engine", definition: config.engine?.definition },
860
+ { label: 'User Interface "ui"', type: "ui", definition: config.ui?.definition },
861
+ {
862
+ label: 'Session User Interface "session"',
863
+ type: "session",
864
+ definition: config.session?.definition
865
+ },
866
+ {
867
+ label: 'Waiting Room User Interface "waiting_room"',
868
+ type: "waiting_room",
869
+ definition: config.waiting_room?.definition
870
+ },
871
+ {
872
+ label: 'Presentation "presentation"',
873
+ type: "presentation",
874
+ definition: config.presentation?.definition
875
+ },
876
+ {
877
+ label: 'Tick Controller "tick_controller"',
878
+ type: "tick_controller",
879
+ definition: config.tick_controller?.definition
880
+ },
881
+ { label: 'Guide "guide"', type: "guide", definition: config.guide?.definition },
882
+ ...(config.hooks ?? []).map((hook) => ({
883
+ label: `Hook "${hook.definition.identifier}"`,
884
+ type: "hook",
885
+ definition: hook.definition
886
+ })),
887
+ ...(config.validators ?? []).map((validator) => ({
888
+ label: `Validator "${validator.definition.identifier}"`,
889
+ type: "validator",
890
+ definition: validator.definition
891
+ })),
892
+ ...(config.endpoints ?? []).map((endpoint) => ({
893
+ label: `Endpoint "${endpoint.definition.identifier}"`,
894
+ type: "endpoint",
895
+ definition: endpoint.definition
896
+ }))
897
+ ];
898
+ const errors = [];
899
+ const findings = [];
900
+ for (const { label, type, definition } of resources) {
901
+ (definition?.settings ?? []).forEach((identifier, index) => {
902
+ if (declared.has(identifier)) return;
903
+ const message = `${label} reads settings "${identifier}", which this package does not declare. Create it with \`pnpm run sdk new settings\`, or remove it from settings.`;
904
+ errors.push(message);
905
+ findings.push(
906
+ referenceFinding(
907
+ message,
908
+ { type, identifier: definition?.identifier ?? type },
909
+ ["settings", index],
910
+ identifier,
911
+ known
912
+ )
913
+ );
914
+ });
915
+ }
916
+ return { errors, findings };
917
+ }
918
+ function validateGameLocales(game) {
919
+ const errors = [];
920
+ const supportedLocales = game.definition.supportedLocales || ["en"];
921
+ const simId = game.definition.identifier;
922
+ const simLocales = game.definition.locales;
923
+ const availableSimLocales = simLocales ? Object.keys(simLocales) : ["en"];
924
+ for (const locale of supportedLocales) {
925
+ if (!availableSimLocales.includes(locale)) {
926
+ errors.push(
927
+ `Game "${simId}" lists locale "${locale}" in supportedLocales, but does not define it in the locales object`
928
+ );
929
+ }
930
+ }
931
+ for (const locale of availableSimLocales) {
932
+ if (!supportedLocales.includes(locale)) {
933
+ errors.push(
934
+ `Game "${simId}" defines locale "${locale}" in the locales object, but does not list it in supportedLocales`
935
+ );
936
+ }
937
+ }
938
+ return { errors };
939
+ }
940
+ function scenarioGame(scenario) {
941
+ const game = scenario.definition.settings?.[GAME_SETTINGS];
942
+ return game !== null && typeof game === "object" ? game : null;
943
+ }
944
+ function namesBeyondMax(owner, settings) {
945
+ const { defaultNames, max } = settings.teams;
946
+ if (max === null || defaultNames.length <= max) return [];
947
+ return [
948
+ `${owner}.teams.defaultNames lists ${defaultNames.length} names but ${owner}.teams.max is ${max}; names beyond the maximum will not be used.`
949
+ ];
950
+ }
951
+ function validateSharedCapabilityWrites(game, engines, config) {
952
+ const errors = [];
953
+ const sharedCapabilityIds = new Set(
954
+ (config.capabilities ?? []).filter((cap) => resolveCapabilityScope(cap.definition) === "shared").map((cap) => cap.definition.identifier)
955
+ );
956
+ if (sharedCapabilityIds.size === 0) return { errors };
957
+ const isSharedState = game.definition.teams?.mode === "shared-state";
958
+ const teamsMax = teamsMaxOf(
959
+ config.settings?.find((entry) => entry.definition.identifier === GAME_SETTINGS)?.definition.settingsSchema
960
+ );
961
+ const isMultiTeam = !(teamsMax.max === 1 && teamsMax.locked);
962
+ const independentMultiTeam = !isSharedState && isMultiTeam;
963
+ const singleTeamHint = teamsMax.max === 1 ? "teams.max is 1 but not locked, so a scenario or session could raise it: lock it with gameSettingsConstraints.teams.max.readOnly: true for a single-team game" : "declare teams.max: 1 and lock it with gameSettingsConstraints.teams.max.readOnly: true for a single-team game";
964
+ for (const engine of engines) {
965
+ const isAggregate = engine.definition.aggregate === true;
966
+ const writes = engine.definition.writes ?? [];
967
+ for (const capId of writes) {
968
+ if (!sharedCapabilityIds.has(capId)) continue;
969
+ if (independentMultiTeam) {
970
+ errors.push(
971
+ `Engine "${engine.definition.identifier}" writes to shared capability "${capId}" in an independent-mode game. Independent teams tick on their own clocks, so there is no coherent engine writer order for session-wide shared state: shared capabilities are facilitator-only in independent mode. Set teams.mode to 'shared-state', use a team-scope capability, or ${singleTeamHint}.`
972
+ );
973
+ } else if (!isAggregate) {
974
+ errors.push(
975
+ `Engine "${engine.definition.identifier}" writes to shared capability "${capId}" but is not an aggregate engine. A shared capability holds one value for the whole session, so only an engine that sees every team at once may write it. Export "InitAggregate" and "RunAggregate" from the engine's logic, or give the value its own team-scope capability.`
976
+ );
977
+ }
978
+ }
979
+ }
980
+ return { errors };
981
+ }
982
+ function validateUISharedCapabilityWrites(config) {
983
+ const errors = [];
984
+ const sharedCapabilityIds = new Set(
985
+ (config.capabilities ?? []).filter((cap) => resolveCapabilityScope(cap.definition) === "shared").map((cap) => cap.definition.identifier)
986
+ );
987
+ if (sharedCapabilityIds.size === 0) return { errors };
988
+ const reject = (resourceLabel, resources) => {
989
+ for (const { definition } of resources ?? []) {
990
+ for (const capId of definition.writes ?? []) {
991
+ if (sharedCapabilityIds.has(capId)) {
992
+ errors.push(
993
+ `${resourceLabel} "${definition.identifier}" writes to shared capability "${capId}". Shared capabilities may only be written by an aggregate engine, a session user interface, or a session-scoped endpoint.`
994
+ );
995
+ }
996
+ }
997
+ }
998
+ };
999
+ reject("User Interface", config.ui && [config.ui]);
1000
+ reject("Waiting Room User Interface", config.waiting_room && [config.waiting_room]);
1001
+ reject("Hook", config.hooks);
1002
+ return { errors };
1003
+ }
1004
+ function endpointSchemaErrors(endpoint) {
1005
+ const { identifier, requestSchema, responseSchema } = endpoint.definition;
1006
+ const errors = [];
1007
+ const ajv = createAjv();
1008
+ for (const [label, schema] of [
1009
+ ["requestSchema", requestSchema],
1010
+ ["responseSchema", responseSchema]
1011
+ ]) {
1012
+ try {
1013
+ ajv.compile(schema);
1014
+ } catch (error) {
1015
+ errors.push(
1016
+ `Endpoint "${identifier}" ${label} does not compile: ${error instanceof Error ? error.message : String(error)}`
1017
+ );
1018
+ }
1019
+ }
1020
+ const visit = (schema, path) => {
1021
+ if (!schema || typeof schema !== "object") return;
1022
+ const node = schema;
1023
+ if (node.blob !== void 0 && node.type !== "string") {
1024
+ errors.push(
1025
+ `Endpoint "${identifier}" requestSchema ${path || "(root)"} declares \`blob\` but is not \`"type": "string"\`. A file field is a URI string: a blob: reference or a data: URI`
1026
+ );
1027
+ }
1028
+ for (const { step, schema: child } of memberDeclarations(node)) {
1029
+ visit(child, `${path}/${step}`);
1030
+ }
1031
+ if (node.items && !Array.isArray(node.items)) visit(node.items, `${path}/items`);
1032
+ };
1033
+ visit(requestSchema, "");
1034
+ return errors;
1035
+ }
1036
+ function validateEndpointCapabilityWrites(config) {
1037
+ const errors = [];
1038
+ const scopeOf = new Map(
1039
+ (config.capabilities ?? []).map((cap) => [
1040
+ cap.definition.identifier,
1041
+ resolveCapabilityScope(cap.definition)
1042
+ ])
1043
+ );
1044
+ for (const endpoint of config.endpoints ?? []) {
1045
+ const definition = endpoint.definition;
1046
+ if (definition.scope === "session") continue;
1047
+ for (const capId of definition.writes ?? []) {
1048
+ if (scopeOf.get(capId) === "shared") {
1049
+ errors.push(
1050
+ `Endpoint "${definition.identifier}" is team-scoped but writes to shared capability "${capId}". A shared capability holds one value for the whole session, and a team-addressed patch cannot reach it: the write would be answered and then silently dropped. Add "scope": "session" to the endpoint, or give the value its own team-scope capability.`
1051
+ );
1052
+ }
1053
+ }
1054
+ }
1055
+ return { errors };
1056
+ }
1057
+ function validatePrivateCapabilityDeclarations(config) {
1058
+ const errors = [];
1059
+ const privateCapabilityIds = new Set(
1060
+ (config.capabilities ?? []).filter((cap) => resolveCapabilityScope(cap.definition) === "private").map((cap) => cap.definition.identifier)
1061
+ );
1062
+ if (privateCapabilityIds.size === 0) return { errors };
1063
+ const reject = (resourceLabel, resources) => {
1064
+ for (const { definition } of resources ?? []) {
1065
+ const declared = {
1066
+ reads: definition.reads,
1067
+ crossTeamReads: "crossTeamReads" in definition ? definition.crossTeamReads : void 0,
1068
+ writes: "writes" in definition ? definition.writes : void 0
1069
+ };
1070
+ for (const field of ["reads", "crossTeamReads", "writes"]) {
1071
+ for (const capId of declared[field] ?? []) {
1072
+ if (!privateCapabilityIds.has(capId)) continue;
1073
+ errors.push(
1074
+ `${resourceLabel} "${definition.identifier}" declares "${capId}" in ${field}, but that capability's scope is 'private'. A private capability is never delivered to a user interface, so the declaration cannot be honoured. Remove it, or change the capability's scope to 'team' if a surface genuinely needs the value.`
1075
+ );
1076
+ }
1077
+ }
1078
+ }
1079
+ };
1080
+ reject("User Interface", config.ui && [config.ui]);
1081
+ reject("Session User Interface", config.session && [config.session]);
1082
+ reject("Waiting Room User Interface", config.waiting_room && [config.waiting_room]);
1083
+ reject("Presentation", config.presentation && [config.presentation]);
1084
+ return { errors };
1085
+ }
1086
+ function validateSessionLifetimeDeclarations(config) {
1087
+ const sessionIds = new Set(
1088
+ (config.capabilities ?? []).filter((cap) => cap.definition.lifetime === "session").map((cap) => cap.definition.identifier)
1089
+ );
1090
+ const engine = config.engine?.definition;
1091
+ if (sessionIds.size === 0 || !engine) return [];
1092
+ const errors = [];
1093
+ for (const field of ["reads", "writes"]) {
1094
+ for (const capId of engine[field] ?? []) {
1095
+ if (!sessionIds.has(capId)) continue;
1096
+ errors.push(
1097
+ `Engine "${engine.identifier}" declares "${capId}" in ${field}, but that capability's lifetime is 'session'. Undo and reset leave a session-lifetime value alone, so a tick that used it could not be replayed from its snapshot. Remove it from the engine, or drop the capability's lifetime back to 'tick'.`
1098
+ );
1099
+ }
1100
+ }
1101
+ return errors;
1102
+ }
1103
+ function validateCapabilityScopes(game, engines, config) {
1104
+ const errors = [];
1105
+ const scopeByCapability = /* @__PURE__ */ new Map();
1106
+ for (const capability of config.capabilities ?? []) {
1107
+ scopeByCapability.set(
1108
+ capability.definition.identifier,
1109
+ resolveCapabilityScope(capability.definition)
1110
+ );
1111
+ }
1112
+ const isSharedState = game.definition.teams?.mode === "shared-state";
1113
+ const checkUIReads = (uiLabel, definition) => {
1114
+ const reads = definition.reads ?? [];
1115
+ for (const capabilityId of definition.crossTeamReads ?? []) {
1116
+ if (!reads.includes(capabilityId)) {
1117
+ errors.push(
1118
+ `${uiLabel} "${definition.identifier}" lists "${capabilityId}" in crossTeamReads but does not read it. Add "${capabilityId}" to \`reads\`: \`crossTeamReads\` says every team's value of a capability arrives, and \`reads\` is what says it arrives at all.`
1119
+ );
1120
+ }
1121
+ const targetScope = scopeByCapability.get(capabilityId);
1122
+ if (targetScope !== void 0 && targetScope !== "team-readable") {
1123
+ errors.push(
1124
+ `${uiLabel} "${definition.identifier}" lists "${capabilityId}" in crossTeamReads but that capability's scope is '${targetScope}'. A crossTeamReads entry requires scope: 'team-readable'.`
1125
+ );
1126
+ }
1127
+ }
1128
+ };
1129
+ if (config.ui) {
1130
+ checkUIReads("User Interface", config.ui.definition);
1131
+ }
1132
+ if (config.waiting_room) {
1133
+ checkUIReads("Waiting Room User Interface", config.waiting_room.definition);
1134
+ }
1135
+ if (!isSharedState) {
1136
+ const referenced = /* @__PURE__ */ new Map();
1137
+ const collect = (label, definition) => {
1138
+ for (const capabilityId of [
1139
+ ...definition.reads ?? [],
1140
+ ...definition.writes ?? []
1141
+ ]) {
1142
+ if (scopeByCapability.get(capabilityId) === "team-readable") {
1143
+ referenced.set(capabilityId, `${label} "${definition.identifier}"`);
1144
+ }
1145
+ }
1146
+ };
1147
+ for (const engine of engines) {
1148
+ collect("engine", engine.definition);
1149
+ }
1150
+ if (config.ui) {
1151
+ collect("user interface", config.ui.definition);
1152
+ }
1153
+ for (const [capId, referencedBy] of referenced) {
1154
+ errors.push(
1155
+ `Capability "${capId}" has scope 'team-readable' and is used by ${referencedBy}, but the game's interaction mode is not 'shared-state'. Set game.teams.mode to 'shared-state' or change the capability's scope.`
1156
+ );
1157
+ }
1158
+ }
1159
+ return { errors };
1160
+ }
1161
+ function validateCrossTeamParticipants(game, uiMap) {
1162
+ const errors = [];
1163
+ if (game.definition.teams?.mode === "shared-state") return { errors };
1164
+ const check = (label, identifier, declares) => {
1165
+ if (declares) {
1166
+ errors.push(
1167
+ `${label} "${identifier}" declares crossTeamParticipants, but the game's interaction mode is not 'shared-state'. Set game.teams.mode to 'shared-state' or remove crossTeamParticipants.`
1168
+ );
1169
+ }
1170
+ };
1171
+ for (const ui of uiMap.values()) {
1172
+ check("User Interface", ui.definition.identifier, ui.definition.crossTeamParticipants);
1173
+ }
1174
+ return { errors };
1175
+ }
1176
+ function settingsEditorLabel(editor) {
1177
+ return editor.definition.identifier === "setup" ? "Setup User Interface" : "Scenario Editor";
1178
+ }
1179
+ function validateSettingsEditorReferences(editor, game, config) {
1180
+ const known = (config.settings ?? []).map((s) => s.definition.identifier);
1181
+ const declared = new Set(known);
1182
+ const errors = [];
1183
+ const findings = [];
1184
+ const editorId = editor.definition.identifier;
1185
+ (editor.definition.configures || []).forEach((identifier, index) => {
1186
+ if (declared.has(identifier)) return;
1187
+ const message = `${settingsEditorLabel(editor)} "${editorId}" configures settings "${identifier}", but game "${game.definition.identifier}" does not declare them`;
1188
+ errors.push(message);
1189
+ findings.push(
1190
+ referenceFinding(
1191
+ message,
1192
+ { type: editorId, identifier: editorId },
1193
+ ["configures", index],
1194
+ identifier,
1195
+ known
1196
+ )
1197
+ );
1198
+ });
1199
+ return { errors, findings };
1200
+ }
1201
+
1202
+ // cli/validation/package-validator.ts
1203
+ function validatePackageDefinition(packageBundle) {
1204
+ const errors = [];
1205
+ if (!packageBundle?.definition) {
1206
+ errors.push("Package definition is missing");
1207
+ return { success: false, errors };
1208
+ }
1209
+ const { identifier, version } = packageBundle.definition;
1210
+ if (typeof version !== "string" || version === "") {
1211
+ errors.push(
1212
+ `Package "${identifier ?? "(unknown)"}" is missing definition.version. Set a Semantic Versioning 2.0.0 string (e.g. "0.1.0").`
1213
+ );
1214
+ return { success: false, errors };
1215
+ }
1216
+ if (!SEMVER_PATTERN.test(version)) {
1217
+ errors.push(
1218
+ `Package "${identifier ?? "(unknown)"}" has invalid definition.version "${version}". Versions must conform to Semantic Versioning 2.0.0 (https://semver.org/spec/v2.0.0.html). Run \`pnpm run sdk package version <valid-semver>\` to update it.`
1219
+ );
1220
+ }
1221
+ return { success: errors.length === 0, errors };
1222
+ }
1223
+
1224
+ // cli/validation/schema-defaults-validator.ts
1225
+ var SCHEMA_KEYS = [
1226
+ "variablesSchema",
1227
+ "settingsSchema",
1228
+ "requestSchema",
1229
+ "responseSchema"
1230
+ ];
1231
+ var SINGLE_SCHEMA_KEYWORDS = [
1232
+ "additionalProperties",
1233
+ "additionalItems",
1234
+ "contains",
1235
+ "propertyNames",
1236
+ "if",
1237
+ "then",
1238
+ "else",
1239
+ "not"
1240
+ ];
1241
+ var SCHEMA_MAP_KEYWORDS = ["properties", "patternProperties", "definitions", "$defs"];
1242
+ var SCHEMA_ARRAY_KEYWORDS = ["allOf", "anyOf", "oneOf"];
1243
+ function isSchemaObject(value) {
1244
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1245
+ }
1246
+ function describe(errors) {
1247
+ if (!errors || errors.length === 0) return "does not satisfy its own schema";
1248
+ return errors.map((error) => {
1249
+ const where = error.instancePath ? `${error.instancePath} ` : "";
1250
+ const message = error.message ?? "is invalid";
1251
+ if (error.keyword === "additionalProperties" && typeof error.params.additionalProperty === "string") {
1252
+ const extra = error.params.additionalProperty;
1253
+ return `${where}${message} ('${extra}' is not declared)`;
1254
+ }
1255
+ if (error.keyword === "required") {
1256
+ return `${where}${message} \u2014 a default is used whole when nothing overrides it, so it must be a complete value. Give the default every required field, or drop \`required\` so an empty value is complete. When every scenario must supply a real value, a validator's \`Scenario\` gate can refuse one that does not`;
1257
+ }
1258
+ return `${where}${message}`.trim();
1259
+ }).join("; ");
1260
+ }
1261
+ function checkDefault(subschema, root, path, issues) {
1262
+ if (!("default" in subschema)) return;
1263
+ const { default: defaultValue, ...constraints } = subschema;
1264
+ const standalone = { ...constraints };
1265
+ if (root.$defs && !standalone.$defs) standalone.$defs = root.$defs;
1266
+ if (root.definitions && !standalone.definitions) standalone.definitions = root.definitions;
1267
+ let validate;
1268
+ try {
1269
+ validate = createAjv("reference").compile(standalone);
1270
+ } catch {
1271
+ return;
1272
+ }
1273
+ if (!validate(defaultValue)) {
1274
+ issues.push({ path, reason: describe(validate.errors) });
1275
+ }
1276
+ }
1277
+ function walk(node, root, path, issues, seen) {
1278
+ if (!isSchemaObject(node)) return;
1279
+ if (seen.has(node)) return;
1280
+ seen.add(node);
1281
+ checkDefault(node, root, path, issues);
1282
+ for (const keyword of SCHEMA_MAP_KEYWORDS) {
1283
+ const map = node[keyword];
1284
+ if (!isSchemaObject(map)) continue;
1285
+ for (const [name, child] of Object.entries(map)) {
1286
+ walk(child, root, `${path}.${keyword}.${name}`, issues, seen);
1287
+ }
1288
+ }
1289
+ for (const keyword of SCHEMA_ARRAY_KEYWORDS) {
1290
+ const branches = node[keyword];
1291
+ if (!Array.isArray(branches)) continue;
1292
+ branches.forEach((child, index) => {
1293
+ walk(child, root, `${path}.${keyword}[${index}]`, issues, seen);
1294
+ });
1295
+ }
1296
+ for (const keyword of SINGLE_SCHEMA_KEYWORDS) {
1297
+ walk(
1298
+ node[keyword],
1299
+ root,
1300
+ `${path}.${keyword}`,
1301
+ issues,
1302
+ seen
1303
+ );
1304
+ }
1305
+ if (Array.isArray(node.items)) {
1306
+ node.items.forEach((child, index) => {
1307
+ walk(child, root, `${path}.items[${index}]`, issues, seen);
1308
+ });
1309
+ } else {
1310
+ walk(node.items, root, `${path}.items`, issues, seen);
1311
+ }
1312
+ }
1313
+ function findInvalidSchemaDefaults(definition) {
1314
+ if (!isSchemaObject(definition)) return [];
1315
+ const issues = [];
1316
+ for (const key of SCHEMA_KEYS) {
1317
+ const schema = definition[key];
1318
+ if (!isSchemaObject(schema)) continue;
1319
+ walk(schema, schema, key, issues, /* @__PURE__ */ new Set());
1320
+ }
1321
+ return issues;
1322
+ }
1323
+ function validateSchemaDefaults(label, definition) {
1324
+ return findInvalidSchemaDefaults(definition).map(
1325
+ (issue) => `${label}: the default for '${issue.path}' ${issue.reason}`
1326
+ );
1327
+ }
1328
+
1329
+ // cli/validation/package-validation.ts
1330
+ function descriptor(entry) {
1331
+ return entry;
1332
+ }
1333
+ var named = (resource) => resource.definition.identifier;
1334
+ var writesOf = (resource) => resource.definition.writes ?? [];
1335
+ function slot(resource) {
1336
+ return resource ? [resource] : [];
1337
+ }
1338
+ function packageFiles(packagePath, scenarioRoot) {
1339
+ return async (reference) => {
1340
+ if (!reference.startsWith("shared:") && !reference.startsWith("asset:")) return void 0;
1341
+ try {
1342
+ return await describeAssetByReference(packagePath, scenarioRoot, reference);
1343
+ } catch {
1344
+ return void 0;
1345
+ }
1346
+ };
1347
+ }
1348
+ function schemaDefaults(type) {
1349
+ const label = getResourceMeta(type).label;
1350
+ return (resource) => ({
1351
+ errors: validateSchemaDefaults(
1352
+ `${label} "${resource.definition.identifier}"`,
1353
+ resource.definition
1354
+ )
1355
+ });
1356
+ }
1357
+ function localRefs(type) {
1358
+ const label = getResourceMeta(type).label;
1359
+ const keyword = type === "capability" ? "variablesSchema" : "settingsSchema";
1360
+ return (resource) => {
1361
+ const schema = resource.definition[keyword];
1362
+ if (schema === null || typeof schema !== "object") return { errors: [] };
1363
+ return {
1364
+ errors: refProblems(schema).map(
1365
+ (problem) => refProblemMessage(`${label} "${resource.definition.identifier}"`, keyword, problem)
1366
+ )
1367
+ };
1368
+ };
1369
+ }
1370
+ function readsWritten(type) {
1371
+ const label = getResourceMeta(type).label;
1372
+ return (resource, context) => {
1373
+ const definition = resource.definition;
1374
+ const outcome = {
1375
+ errors: [],
1376
+ warnings: [],
1377
+ findings: []
1378
+ };
1379
+ (definition.reads ?? []).forEach((capId, index) => {
1380
+ if (!context.capabilityIds.has(capId)) return;
1381
+ if (context.writtenInPackage.has(capId)) return;
1382
+ const message = `${label} "${definition.identifier}" declares a read of capability "${capId}", but no engine, user interface, or hook in this package writes it, so it can only ever hold its schema defaults. Remove the read if it is unused, or move the values to a settings resource if they are meant to be constants.`;
1383
+ outcome.warnings.push(message);
1384
+ outcome.findings.push({
1385
+ severity: "warning",
1386
+ code: "READ_NEVER_WRITTEN",
1387
+ message,
1388
+ pointer: pointerOf("definition", "reads", index)
1389
+ });
1390
+ });
1391
+ return outcome;
1392
+ };
1393
+ }
1394
+ var uiFiles = (ui, context) => validateUIFiles(ui, context.workingDir);
1395
+ var userInterfaceReferences = (ui, context) => validateUserInterface(ui, context.config);
1396
+ var VALIDATION_DESCRIPTORS = [
1397
+ // The package definition the loader synthesised: Semantic Versioning 2.0.0
1398
+ // on the version it took from `package.json` (#421), which nothing else
1399
+ // gates. Production runtimes rely on it for version ordering
1400
+ // (SPECIFICATION.md §2.2, §2.5).
1401
+ descriptor({
1402
+ type: "package",
1403
+ resources: (config) => [config.package],
1404
+ identify: (pkg) => pkg?.definition?.identifier ?? "(unknown)",
1405
+ checks: [
1406
+ (pkg, context) => {
1407
+ const validation = validatePackageDefinition(pkg);
1408
+ return validation.success ? { errors: [] } : {
1409
+ errors: validation.errors.map(
1410
+ (error) => `${error} (source: ${context.configPath})`
1411
+ )
1412
+ };
1413
+ }
1414
+ ]
1415
+ }),
1416
+ // Every `tsType` import names an engine that exists and exports the type (#601).
1417
+ descriptor({
1418
+ type: "capability",
1419
+ resources: (config) => config.capabilities ?? [],
1420
+ identify: named,
1421
+ checks: [
1422
+ (capability, context) => ({
1423
+ errors: validateTsTypes([capability], context.workingDir)
1424
+ }),
1425
+ schemaDefaults("capability"),
1426
+ localRefs("capability")
1427
+ ]
1428
+ }),
1429
+ // The built-in `game` resource's defaults are the manifest's own values,
1430
+ // which the game's checks already hold to their schema.
1431
+ descriptor({
1432
+ type: "settings",
1433
+ resources: (config) => (config.settings ?? []).filter(
1434
+ (settings) => settings.definition.identifier !== GAME_SETTINGS
1435
+ ),
1436
+ identify: named,
1437
+ checks: [
1438
+ schemaDefaults("settings"),
1439
+ localRefs("settings"),
1440
+ // A lock inside a list's items or a map's entries keeps nothing (§6.1a).
1441
+ (settings) => ({
1442
+ errors: unenforceableLocks(settings.definition.settingsSchema).map(
1443
+ (lock) => unenforceableLockMessage(settings.definition.identifier, lock)
1444
+ )
1445
+ }),
1446
+ // What a file setting expects, and the files its defaults name (§6.1a).
1447
+ (settings) => ({
1448
+ errors: fileSettingDeclarationErrors(
1449
+ settings.definition.identifier,
1450
+ settings.definition.settingsSchema
1451
+ )
1452
+ }),
1453
+ async (settings, context) => {
1454
+ const schema = settings.definition.settingsSchema;
1455
+ const defaults = Object.fromEntries(
1456
+ Object.entries(schema.properties ?? {}).flatMap(
1457
+ ([key, property]) => typeof property === "object" && "default" in property ? [[key, property.default]] : []
1458
+ )
1459
+ );
1460
+ return {
1461
+ errors: await packageFileSettingErrors(
1462
+ `The defaults of settings "${settings.definition.identifier}"`,
1463
+ { [settings.definition.identifier]: defaults },
1464
+ settingsSchemas(context.config),
1465
+ packageFiles(dirname2(context.configPath), null),
1466
+ // An `asset:` default is refused with the declaration.
1467
+ (reference) => !reference.startsWith("shared:")
1468
+ )
1469
+ };
1470
+ }
1471
+ ]
1472
+ }),
1473
+ descriptor({
1474
+ type: "engine",
1475
+ resources: (config) => slot(config.engine),
1476
+ identify: named,
1477
+ writer: writesOf,
1478
+ checks: [
1479
+ (engine, context) => validateEngine(engine, context.config),
1480
+ (engine, context) => validateEngineFiles(engine, context.workingDir),
1481
+ schemaDefaults("engine"),
1482
+ readsWritten("engine")
1483
+ ]
1484
+ }),
1485
+ descriptor({
1486
+ type: "ui",
1487
+ resources: (config) => slot(config.ui),
1488
+ identify: named,
1489
+ writer: writesOf,
1490
+ checks: [userInterfaceReferences, uiFiles, schemaDefaults("ui"), readsWritten("ui")]
1491
+ }),
1492
+ // What the two settings editors configure is checked with the game.
1493
+ descriptor({
1494
+ type: "setup",
1495
+ resources: (config) => slot(config.setup),
1496
+ identify: named,
1497
+ checks: [uiFiles]
1498
+ }),
1499
+ descriptor({
1500
+ type: "scenario_editor",
1501
+ resources: (config) => slot(config.scenario_editor),
1502
+ identify: named,
1503
+ checks: [uiFiles]
1504
+ }),
1505
+ descriptor({
1506
+ type: "tick_controller",
1507
+ resources: (config) => slot(config.tick_controller),
1508
+ identify: named,
1509
+ checks: [
1510
+ (tc, context) => validateTickController(tc, context.config),
1511
+ schemaDefaults("tick_controller"),
1512
+ readsWritten("tick_controller")
1513
+ ]
1514
+ }),
1515
+ descriptor({
1516
+ type: "hook",
1517
+ resources: (config) => config.hooks ?? [],
1518
+ identify: named,
1519
+ writer: writesOf,
1520
+ checks: [
1521
+ (hook, context) => validateHook(hook, context.config),
1522
+ schemaDefaults("hook"),
1523
+ readsWritten("hook")
1524
+ ]
1525
+ }),
1526
+ descriptor({
1527
+ type: "validator",
1528
+ resources: (config) => config.validators ?? [],
1529
+ identify: named,
1530
+ checks: [
1531
+ (validator, context) => validateValidator(validator, context.config),
1532
+ schemaDefaults("validator"),
1533
+ readsWritten("validator")
1534
+ ]
1535
+ }),
1536
+ descriptor({
1537
+ type: "endpoint",
1538
+ resources: (config) => config.endpoints ?? [],
1539
+ identify: named,
1540
+ checks: [
1541
+ (endpoint, context) => validateEndpoint(endpoint, context.config),
1542
+ (endpoint, context) => validateEndpointFiles(endpoint, context.workingDir),
1543
+ schemaDefaults("endpoint"),
1544
+ readsWritten("endpoint")
1545
+ ]
1546
+ }),
1547
+ descriptor({
1548
+ type: "session",
1549
+ resources: (config) => slot(config.session),
1550
+ identify: named,
1551
+ writer: writesOf,
1552
+ checks: [
1553
+ userInterfaceReferences,
1554
+ uiFiles,
1555
+ schemaDefaults("session"),
1556
+ readsWritten("session")
1557
+ ]
1558
+ }),
1559
+ descriptor({
1560
+ type: "waiting_room",
1561
+ resources: (config) => slot(config.waiting_room),
1562
+ identify: named,
1563
+ checks: [
1564
+ userInterfaceReferences,
1565
+ uiFiles,
1566
+ schemaDefaults("waiting_room"),
1567
+ readsWritten("waiting_room")
1568
+ ]
1569
+ }),
1570
+ descriptor({
1571
+ type: "presentation",
1572
+ resources: (config) => slot(config.presentation),
1573
+ identify: named,
1574
+ checks: [userInterfaceReferences, uiFiles]
1575
+ }),
1576
+ // Composition, settings, locales and roles. A game wires whatever its
1577
+ // package declares (#417), so a reference cannot dangle; what can still go
1578
+ // wrong is two scenarios claiming the default.
1579
+ descriptor({
1580
+ type: "game",
1581
+ resources: (config) => slot(config.game),
1582
+ identify: named,
1583
+ checks: [
1584
+ (game, context) => validateGame(game, context.config),
1585
+ // With no default, a session can run on no scenario at all, so the
1586
+ // `Scenario` gate judges the defaults too: a game that cannot run
1587
+ // on them alone says so here, not when a session is created
1588
+ // (§15.8).
1589
+ async (game, context) => {
1590
+ if (!hasScenarioGate(context.config)) return { errors: [] };
1591
+ const resource = { type: "game", identifier: game.definition.identifier };
1592
+ const errors = [];
1593
+ const errorFindings = [];
1594
+ if (!(context.config.requires ?? []).includes(SCENARIO_VALIDATION)) {
1595
+ const message = `A validator exports \`Scenario\`, which needs the \`${SCENARIO_VALIDATION}\` feature, but \`requires\` does not list it`;
1596
+ errors.push(message);
1597
+ errorFindings.push({
1598
+ code: "FEATURE_UNDECLARED",
1599
+ message,
1600
+ file: MANIFEST_FILE,
1601
+ pointer: pointerOf("requires"),
1602
+ resource,
1603
+ hint: `Add "${SCENARIO_VALIDATION}" to \`requires\` in seriousgaming.sdk.json, so a runtime that cannot run the gate refuses the package rather than saving scenarios the game would refuse.`
1604
+ });
1605
+ }
1606
+ if (!(context.config.scenarios ?? []).some((s) => s.definition.default)) {
1607
+ const refused = scenarioRefusals(
1608
+ await runScenarioGates({
1609
+ packagePath: dirname2(context.configPath),
1610
+ config: context.config,
1611
+ loader: context.logicLoader,
1612
+ scenarioSettings: null
1613
+ }),
1614
+ "The defaults, which a session runs on when no scenario is the default,",
1615
+ resource,
1616
+ MANIFEST_FILE,
1617
+ () => void 0
1618
+ );
1619
+ errors.push(...refused.errors);
1620
+ errorFindings.push(...refused.errorFindings);
1621
+ }
1622
+ return errorFindings.length > 0 ? { errors, errorFindings } : { errors };
1623
+ },
1624
+ (_game, context) => {
1625
+ const defaults = (context.config.scenarios ?? []).filter(
1626
+ (scenario) => scenario.definition.default
1627
+ );
1628
+ return defaults.length > 1 ? {
1629
+ errors: [
1630
+ `Game has ${defaults.length} default scenarios \u2014 at most one scenario may be marked as default`
1631
+ ]
1632
+ } : { errors: [] };
1633
+ }
1634
+ ]
1635
+ }),
1636
+ descriptor({
1637
+ type: "scenario",
1638
+ resources: (config) => config.scenarios ?? [],
1639
+ identify: named,
1640
+ checks: [
1641
+ // The same check `ConfigResolver.assertLayeredSettingsValid` runs at
1642
+ // session start (#371). Without it the build was green on a
1643
+ // scenario the dev server and the production runtime both refuse.
1644
+ (scenario, context) => {
1645
+ if (!scenario.definition.settings) return { errors: [] };
1646
+ const overrides = scenario.definition.settings;
1647
+ const schemas = settingsSchemas(context.config);
1648
+ return {
1649
+ errors: collectSettingsOverrideErrors(overrides, schemas),
1650
+ errorFindings: collectSettingsOverrideFindings(
1651
+ overrides,
1652
+ schemas,
1653
+ "/definition/settings"
1654
+ )
1655
+ };
1656
+ },
1657
+ // Every file the scenario names is shipped and fits its setting (§6.1a).
1658
+ async (scenario, context) => {
1659
+ if (!scenario.definition.settings) return { errors: [] };
1660
+ const packagePath = dirname2(context.configPath);
1661
+ return {
1662
+ errors: await packageFileSettingErrors(
1663
+ `Scenario "${scenario.definition.identifier}"`,
1664
+ scenario.definition.settings,
1665
+ settingsSchemas(context.config),
1666
+ packageFiles(packagePath, resolve2(packagePath, scenario.rootDirectory))
1667
+ )
1668
+ };
1669
+ },
1670
+ // A default is what a caller gets when it chooses nothing, and a
1671
+ // restricted scenario is not offered to a caller without a grant
1672
+ // (SPECIFICATION.md §6.7). Together they resolve to the scenario
1673
+ // for some callers and to nothing for the rest, which is neither a
1674
+ // default nor a restriction.
1675
+ (scenario) => scenario.definition.default && scenario.definition.restricted ? {
1676
+ errors: [
1677
+ "Scenario is both `default` and `restricted`. A default is what a caller gets when it chooses nothing, so it must be one every caller can be offered. Drop one of the two."
1678
+ ]
1679
+ } : { errors: [] },
1680
+ // The `Scenario` gate, run on the scenario as the package ships it
1681
+ // (§15.8).
1682
+ async (scenario, context) => {
1683
+ const identifier = scenario.definition.identifier;
1684
+ const packagePath = dirname2(context.configPath);
1685
+ return scenarioRefusals(
1686
+ await runScenarioGates({
1687
+ packagePath,
1688
+ config: context.config,
1689
+ loader: context.logicLoader,
1690
+ // Its files as the package ships them (§15.8).
1691
+ files: {
1692
+ scenarioRoot: resolve2(packagePath, scenario.rootDirectory),
1693
+ blobs: "none"
1694
+ },
1695
+ scenarioSettings: scenario.definition.settings ?? {}
1696
+ }),
1697
+ `Scenario "${identifier}"`,
1698
+ { type: "scenario", identifier },
1699
+ bundleFileOf("scenario", identifier),
1700
+ (path) => pointerOf("definition", "settings", ...path.split("."))
1701
+ );
1702
+ }
1703
+ ]
1704
+ }),
1705
+ // Locale completeness, video blocks and asset references.
1706
+ descriptor({
1707
+ type: "guide",
1708
+ resources: (config) => slot(config.guide),
1709
+ identify: named,
1710
+ checks: [
1711
+ (guide, context) => validateFacilitatorGuideContent({
1712
+ definition: guide.definition,
1713
+ rootDirectory: resolve2(context.workingDir, guide.rootDirectory),
1714
+ settings: {
1715
+ schemas: settingsSchemas(context.config),
1716
+ scenarios: Object.fromEntries(
1717
+ (context.config.scenarios ?? []).map((scenario) => [
1718
+ scenario.definition.identifier,
1719
+ scenario.definition.settings ?? {}
1720
+ ])
1721
+ )
1722
+ }
1723
+ })
1724
+ ]
1725
+ })
1726
+ ];
1727
+ async function validatePackage(options) {
1728
+ const configPath = resolve2(options.workingDir, options.config);
1729
+ return validateLoadedPackage(await loadConfig(configPath), {
1730
+ configPath,
1731
+ workingDir: options.workingDir
1732
+ });
1733
+ }
1734
+ async function validateLoadedPackage(config, options) {
1735
+ const writtenInPackage = /* @__PURE__ */ new Set();
1736
+ for (const entry of VALIDATION_DESCRIPTORS) {
1737
+ if (!entry.writer) continue;
1738
+ for (const resource of entry.resources(config)) {
1739
+ for (const write of entry.writer(resource)) writtenInPackage.add(write);
1740
+ }
1741
+ }
1742
+ const context = {
1743
+ config,
1744
+ configPath: options.configPath,
1745
+ workingDir: options.workingDir,
1746
+ writtenInPackage,
1747
+ capabilityIds: new Set((config.capabilities ?? []).map(named)),
1748
+ logicLoader: new LogicLoader(dirname2(options.configPath), {
1749
+ transpile: Transpile,
1750
+ fs: { existsSync: existsSync2, readFile }
1751
+ })
1752
+ };
1753
+ const results = [];
1754
+ for (const entry of VALIDATION_DESCRIPTORS) {
1755
+ for (const resource of entry.resources(config)) {
1756
+ const result = {
1757
+ identifier: entry.identify(resource),
1758
+ type: entry.type,
1759
+ errors: [],
1760
+ warnings: [],
1761
+ diagnostics: []
1762
+ };
1763
+ for (const check of entry.checks) {
1764
+ record(result, await check(resource, context));
1765
+ }
1766
+ results.push(result);
1767
+ }
1768
+ }
1769
+ const failed = results.filter((r) => r.errors.length > 0).length;
1770
+ const withWarnings = results.filter((r) => r.warnings.length > 0).length;
1771
+ return {
1772
+ success: failed === 0,
1773
+ resources: results,
1774
+ summary: {
1775
+ total: results.length,
1776
+ passed: results.length - failed,
1777
+ failed,
1778
+ warnings: withWarnings
1779
+ }
1780
+ };
1781
+ }
1782
+ function record(result, outcome) {
1783
+ if (outcome.errorFindings) {
1784
+ result.errors.push(...outcome.errors);
1785
+ result.diagnostics.push(
1786
+ ...outcome.errorFindings.map((finding) => located("error", finding, result))
1787
+ );
1788
+ return;
1789
+ }
1790
+ const byMessage = new Map((outcome.findings ?? []).map((f) => [f.message, f]));
1791
+ const add = (severity, message) => {
1792
+ const finding = byMessage.get(message) ?? {
1793
+ code: message.includes(LOGIC_NODE_BUILTIN) ? LOGIC_NODE_BUILTIN : "PACKAGE_INVALID",
1794
+ message
1795
+ };
1796
+ result.diagnostics.push(located(severity, finding, result));
1797
+ };
1798
+ for (const message of outcome.errors) {
1799
+ result.errors.push(message);
1800
+ add("error", message);
1801
+ }
1802
+ for (const message of outcome.warnings ?? []) {
1803
+ result.warnings.push(message);
1804
+ add("warning", message);
1805
+ }
1806
+ }
1807
+ function located(severity, finding, resource) {
1808
+ const file = finding.file ?? (resource.type === "game" ? void 0 : bundleFileOf(resource.type, resource.identifier));
1809
+ return {
1810
+ ...finding,
1811
+ severity: finding.severity ?? severity,
1812
+ ...file === void 0 ? {} : { file },
1813
+ resource: finding.resource ?? { type: resource.type, identifier: resource.identifier }
1814
+ };
1815
+ }
1816
+ function scenarioRefusals(problems, subject, resource, file, pointerFor) {
1817
+ const errors = [];
1818
+ const errorFindings = [];
1819
+ for (const problem of problems) {
1820
+ const setting = problem.path ? ` ${problem.path}:` : "";
1821
+ const message = `${subject} is refused by validator "${problem.validatorIdentifier}":${setting} ${problem.message}`;
1822
+ const pointer = problem.path ? pointerFor(problem.path) : void 0;
1823
+ errors.push(message);
1824
+ errorFindings.push({
1825
+ code: "SCENARIO_REFUSED",
1826
+ message,
1827
+ ...file === void 0 ? {} : { file },
1828
+ ...pointer === void 0 ? {} : { pointer },
1829
+ resource
1830
+ });
1831
+ }
1832
+ return { errors, errorFindings };
1833
+ }
1834
+
1835
+ export {
1836
+ validatePackage
1837
+ };