@seriousgaming/sdk-tools 1.3.0 → 1.5.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 (176) hide show
  1. package/dist/cli.js +4055 -2646
  2. package/dist/client.js +807 -172
  3. package/dist/core/session-host.d.ts +4 -2
  4. package/dist/core/settings-locks.d.ts +27 -2
  5. package/dist/dev/console/assets/{index-DEV8N0na.js → index-BVF8exas.js} +22 -22
  6. package/dist/dev/console/index.html +1 -1
  7. package/dist/dev/public-origins.d.ts +61 -0
  8. package/dist/dev/routes.d.ts +4 -0
  9. package/dist/dev/shell.d.ts +32 -4
  10. package/dist/dev/view/batch.d.ts +7 -1
  11. package/dist/docs/ai-agents.md +5 -0
  12. package/dist/docs/api/index.md +1 -1
  13. package/dist/docs/api/sdk-tools-client.md +1 -0
  14. package/dist/docs/api/sdk.md +79 -2
  15. package/dist/docs/changelog-0.x.md +2 -2
  16. package/dist/docs/changelog.md +62 -4
  17. package/dist/docs/cli-and-dev-server.md +58 -0
  18. package/dist/docs/cli-error-codes.md +39 -36
  19. package/dist/docs/cli-reference.md +68 -21
  20. package/dist/docs/concepts/terminology.md +1 -1
  21. package/dist/docs/environment-variables.md +10 -5
  22. package/dist/docs/guides/ai-facilitation.md +2 -0
  23. package/dist/docs/guides/capabilities.md +4 -0
  24. package/dist/docs/guides/designing-a-game.md +2 -0
  25. package/dist/docs/guides/designing-screens.md +133 -0
  26. package/dist/docs/guides/endpoints.md +4 -2
  27. package/dist/docs/guides/engine-testing.md +6 -2
  28. package/dist/docs/guides/engine.md +2 -0
  29. package/dist/docs/guides/file-handling.md +116 -22
  30. package/dist/docs/guides/games.md +3 -1
  31. package/dist/docs/guides/global-settings.md +2 -0
  32. package/dist/docs/guides/guide.md +2 -0
  33. package/dist/docs/guides/hooks.md +2 -0
  34. package/dist/docs/guides/index.md +9 -0
  35. package/dist/docs/guides/internationalization.md +2 -0
  36. package/dist/docs/guides/llm-integration.md +5 -3
  37. package/dist/docs/guides/multi-team-games.md +3 -1
  38. package/dist/docs/guides/patterns.md +2 -0
  39. package/dist/docs/guides/presentation.md +1 -1
  40. package/dist/docs/guides/production-constraints.md +2 -0
  41. package/dist/docs/guides/scenario-editor.md +3 -1
  42. package/dist/docs/guides/scenarios.md +15 -3
  43. package/dist/docs/guides/session-game-flow.md +365 -0
  44. package/dist/docs/guides/session-hooks.md +205 -0
  45. package/dist/docs/guides/session.md +27 -565
  46. package/dist/docs/guides/settings.md +64 -2
  47. package/dist/docs/guides/setup.md +3 -1
  48. package/dist/docs/guides/speech-generation.md +2 -0
  49. package/dist/docs/guides/starter-game.md +61 -21
  50. package/dist/docs/guides/testing.md +2 -0
  51. package/dist/docs/guides/tick-controller.md +3 -1
  52. package/dist/docs/guides/type-safety.md +2 -0
  53. package/dist/docs/guides/ui-files-and-llms.md +328 -0
  54. package/dist/docs/guides/ui-participants.md +281 -0
  55. package/dist/docs/guides/ui-styling.md +263 -0
  56. package/dist/docs/guides/ui-ticks.md +247 -0
  57. package/dist/docs/guides/ui.md +11 -1092
  58. package/dist/docs/guides/upgrading.md +2 -0
  59. package/dist/docs/guides/validators.md +64 -4
  60. package/dist/docs/guides/waiting-room.md +1 -1
  61. package/dist/docs/index.md +2 -1
  62. package/dist/docs/page-index.md +145 -0
  63. package/dist/docs/recipes/adapt-a-game-for-walkthroughs.md +1 -1
  64. package/dist/docs/recipes/adapt-ui-for-observers.md +1 -1
  65. package/dist/docs/recipes/create-presentation.md +11 -0
  66. package/dist/docs/recipes/create-scenario-editor.md +1 -0
  67. package/dist/docs/recipes/create-session-ui.md +2 -1
  68. package/dist/docs/recipes/create-setup.md +1 -0
  69. package/dist/docs/recipes/create-user-interface.md +1 -0
  70. package/dist/docs/recipes/create-waiting-room-ui.md +1 -0
  71. package/dist/docs/recipes/design-state-for-concurrent-writes.md +1 -1
  72. package/dist/docs/recipes/fix-duplicate-packages.md +2 -2
  73. package/dist/docs/recipes/index.md +3 -0
  74. package/dist/docs/recipes/screenshot-a-surface.md +80 -0
  75. package/dist/docs/recipes/test-a-multi-role-game.md +1 -1
  76. package/dist/docs/recipes/upload-and-display-files.md +7 -7
  77. package/dist/docs/recipes/use-request-tick.md +2 -2
  78. package/dist/docs/recipes/validate-scenarios.md +4 -1
  79. package/dist/execution/config-resolver.d.ts +4 -1
  80. package/dist/execution/endpoint-runner.d.ts +6 -0
  81. package/dist/execution/logic-calls.d.ts +7 -2
  82. package/dist/execution/scenario-gates.d.ts +21 -1
  83. package/dist/guide/settings.d.ts +1 -1
  84. package/dist/host.js +64 -2
  85. package/dist/runtime/manifest-version.d.ts +1 -1
  86. package/dist/runtime.js +7 -2
  87. package/dist/storage/asset-resolver.d.ts +24 -1
  88. package/dist/storage/blob-store.d.ts +7 -0
  89. package/dist/templates/package/CLAUDE.md.template +14 -5
  90. package/dist/templates/package/DESIGN.md.liquid +39 -7
  91. package/dist/templates/package/README.md.liquid +1 -1
  92. package/dist/templates/package/claude/rules/workflow-create-user-interface.md +1 -1
  93. package/dist/templates/package/pnpm-workspace.yaml.template +13 -0
  94. package/dist/templates/starter-game/capabilities/pacing/capability.sdk.json +18 -0
  95. package/dist/templates/starter-game/package.json +2 -0
  96. package/dist/templates/starter-game/presentation/defaults.ts +52 -0
  97. package/dist/templates/starter-game/presentation/index.html +20 -0
  98. package/dist/templates/starter-game/presentation/presentation.sdk.json +10 -0
  99. package/dist/templates/starter-game/presentation/src/App.tsx +55 -0
  100. package/dist/templates/starter-game/presentation/src/Band.tsx +40 -0
  101. package/dist/templates/starter-game/presentation/src/Slides.tsx +415 -0
  102. package/dist/templates/starter-game/presentation/src/WeatherIcon.tsx +21 -0
  103. package/dist/templates/starter-game/presentation/src/i18n.ts +88 -0
  104. package/dist/templates/starter-game/presentation/src/main.tsx +15 -0
  105. package/dist/templates/starter-game/presentation/src/stalls.test.ts +196 -0
  106. package/dist/templates/starter-game/presentation/src/stalls.ts +199 -0
  107. package/dist/templates/starter-game/presentation/types.ts +94 -0
  108. package/dist/templates/starter-game/seriousgaming.sdk.json +2 -1
  109. package/dist/templates/starter-game/session/defaults.ts +6 -0
  110. package/dist/templates/starter-game/session/index.html +1 -1
  111. package/dist/templates/starter-game/session/session.sdk.json +2 -2
  112. package/dist/templates/starter-game/session/src/App.test.tsx +436 -115
  113. package/dist/templates/starter-game/session/src/App.tsx +372 -222
  114. package/dist/templates/starter-game/session/src/JoinCodes.tsx +184 -0
  115. package/dist/templates/starter-game/session/src/ManagePanel.tsx +188 -0
  116. package/dist/templates/starter-game/session/src/Results.tsx +340 -0
  117. package/dist/templates/starter-game/session/src/SessionBar.tsx +179 -0
  118. package/dist/templates/starter-game/session/src/SessionPanels.tsx +105 -0
  119. package/dist/templates/starter-game/session/src/SidePanel.tsx +89 -0
  120. package/dist/templates/starter-game/session/src/StallCard.tsx +253 -0
  121. package/dist/templates/starter-game/session/src/TopBar.tsx +36 -0
  122. package/dist/templates/starter-game/session/src/i18n.ts +91 -24
  123. package/dist/templates/starter-game/session/src/status.ts +28 -0
  124. package/dist/templates/starter-game/session/types.ts +8 -2
  125. package/dist/templates/starter-game/shared/Awning.tsx +31 -0
  126. package/dist/templates/starter-game/shared/HostLogo.test.tsx +38 -0
  127. package/dist/templates/starter-game/shared/HostLogo.tsx +48 -0
  128. package/dist/templates/starter-game/shared/StallIcons.tsx +83 -0
  129. package/dist/templates/starter-game/shared/days.ts +11 -0
  130. package/dist/templates/starter-game/shared/format.test.ts +13 -0
  131. package/dist/templates/starter-game/{ui/src → shared}/format.ts +1 -1
  132. package/dist/templates/starter-game/testing/e2e/game.spec.ts +42 -8
  133. package/dist/templates/starter-game/ui/defaults.ts +3 -0
  134. package/dist/templates/starter-game/ui/src/App.test.tsx +197 -29
  135. package/dist/templates/starter-game/ui/src/App.tsx +176 -99
  136. package/dist/templates/starter-game/ui/src/DayBar.test.tsx +50 -7
  137. package/dist/templates/starter-game/ui/src/DayBar.tsx +96 -38
  138. package/dist/templates/starter-game/ui/src/DaysTable.tsx +69 -0
  139. package/dist/templates/starter-game/ui/src/FirstDay.tsx +37 -0
  140. package/dist/templates/starter-game/ui/src/Header.tsx +257 -0
  141. package/dist/templates/starter-game/ui/src/Lesson.tsx +63 -0
  142. package/dist/templates/starter-game/ui/src/MakeRow.tsx +98 -71
  143. package/dist/templates/starter-game/ui/src/Notices.tsx +59 -0
  144. package/dist/templates/starter-game/ui/src/PastDay.tsx +88 -0
  145. package/dist/templates/starter-game/ui/src/Section.tsx +26 -26
  146. package/dist/templates/starter-game/ui/src/ThemeToggle.tsx +25 -11
  147. package/dist/templates/starter-game/ui/src/TodayPanel.test.tsx +37 -33
  148. package/dist/templates/starter-game/ui/src/TodayPanel.tsx +66 -52
  149. package/dist/templates/starter-game/ui/src/WeatherCard.tsx +47 -0
  150. package/dist/templates/starter-game/ui/src/WeekOver.tsx +145 -0
  151. package/dist/templates/starter-game/ui/src/YesterdayPanel.tsx +65 -114
  152. package/dist/templates/starter-game/ui/src/days.ts +58 -0
  153. package/dist/templates/starter-game/ui/src/i18n.ts +86 -32
  154. package/dist/templates/starter-game/ui/src/test-helpers.ts +1 -0
  155. package/dist/templates/starter-game/ui/src/theme.ts +8 -8
  156. package/dist/templates/starter-game/ui/types.ts +6 -0
  157. package/dist/templates/starter-game/ui/ui.sdk.json +1 -1
  158. package/dist/templates/starter-game/validators/daylimit/defaults.ts +13 -0
  159. package/dist/templates/starter-game/validators/daylimit/logic/logic.test.ts +20 -0
  160. package/dist/templates/starter-game/validators/daylimit/logic/logic.ts +23 -0
  161. package/dist/templates/starter-game/validators/daylimit/types.ts +23 -0
  162. package/dist/templates/starter-game/validators/daylimit/validator.sdk.json +10 -0
  163. package/dist/templates/starter-game/waiting_room/src/App.test.tsx +83 -5
  164. package/dist/templates/starter-game/waiting_room/src/App.tsx +262 -119
  165. package/dist/templates/starter-game/waiting_room/src/i18n.ts +8 -4
  166. package/dist/utils/error-codes.d.ts +12 -0
  167. package/dist/utils/local-refs.d.ts +40 -0
  168. package/dist/utils/schema-members.d.ts +19 -0
  169. package/package.json +11 -4
  170. package/dist/templates/starter-game/session/src/Section.tsx +0 -37
  171. package/dist/templates/starter-game/session/src/TeamDoor.tsx +0 -96
  172. package/dist/templates/starter-game/session/src/format.ts +0 -8
  173. package/dist/templates/starter-game/ui/src/HistoryPanel.test.tsx +0 -74
  174. package/dist/templates/starter-game/ui/src/HistoryPanel.tsx +0 -120
  175. package/dist/templates/starter-game/ui/src/HostLogo.test.tsx +0 -25
  176. package/dist/templates/starter-game/ui/src/HostLogo.tsx +0 -38
package/dist/client.js CHANGED
@@ -487,6 +487,10 @@ var ERROR_CODES = {
487
487
  category: "usage",
488
488
  description: "A file named on the command line does not exist or cannot be read."
489
489
  },
490
+ DOCS_SECTION_NOT_FOUND: {
491
+ category: "usage",
492
+ description: "The page `docs view --section` reads has no heading by that name; the details list the ones it has."
493
+ },
490
494
  RESOURCE_TYPE_UNKNOWN: {
491
495
  category: "usage",
492
496
  description: "The resource type does not exist, or does not support this operation."
@@ -677,6 +681,10 @@ var ERROR_CODES = {
677
681
  category: "refused",
678
682
  description: "Game logic (an engine, hook, endpoint, validator or tick controller) threw. A diagnostic, not an error code: it sits in `diagnostics` under the command's TICK_FAILED, SESSION_ERROR or HANDLER_ERROR, with the file, line and column it threw at."
679
683
  },
684
+ SURFACE_NOT_RENDERED: {
685
+ category: "refused",
686
+ description: "`sdk screenshot` gave up on the page: its surface did not connect, or did not report its first paint before the timeout. error.details carries the page's console errors, failed requests and uncaught exceptions."
687
+ },
680
688
  SETTINGS_STALE: {
681
689
  category: "refused",
682
690
  description: "The package changed on disk since the session started in a way that applies only at initialisation (a setting, a manifest field such as `teams`, or a capability removed or moved to another scope), so a command that advances or changes play was refused. Run `sdk init`."
@@ -718,6 +726,10 @@ var ERROR_CODES = {
718
726
  category: "environment",
719
727
  description: "The dev server could not be stopped."
720
728
  },
729
+ BROWSER_MISSING: {
730
+ category: "environment",
731
+ description: "`sdk screenshot` found no Playwright in the package's dependencies, or no Chromium installed for it. Add `@playwright/test` and run `pnpm exec playwright install chromium`."
732
+ },
721
733
  LLM_NOT_CONFIGURED: {
722
734
  category: "environment",
723
735
  description: "Logic called generateText, and the dev server or in-process session running it has no platform API key configured."
@@ -2703,7 +2715,9 @@ var SUPPORTED_FEATURES = [
2703
2715
  // A validator's `Scenario` gate (§15.8).
2704
2716
  "scenario-validation",
2705
2717
  // The presentation as a host overlay a session surface may open (§6.4).
2706
- "presentation-overlay"
2718
+ "presentation-overlay",
2719
+ // File reads in a validator's `Scenario` gate (§15.8).
2720
+ "scenario-files"
2707
2721
  ];
2708
2722
  function unsupportedFeatures(manifest) {
2709
2723
  return (manifest.requires ?? []).filter((feature) => !SUPPORTED_FEATURES.includes(feature));
@@ -3144,8 +3158,11 @@ function createAjv(fileValues = "resolved") {
3144
3158
  const ajv4 = new Ajv({
3145
3159
  allErrors: true,
3146
3160
  // Report all errors, not just the first one
3147
- verbose: true
3161
+ verbose: true,
3148
3162
  // Include schema and data in errors
3163
+ // A game schema may write a keyword beside a `$ref` with no `type` of
3164
+ // its own (§6), which strictTypes would log as a warning on every compile.
3165
+ strictTypes: false
3149
3166
  });
3150
3167
  ajv4.addKeyword({ keyword: "tsType", schemaType: "string" });
3151
3168
  ajv4.addKeyword({
@@ -3253,25 +3270,263 @@ function typesOf(schema2) {
3253
3270
 
3254
3271
  // cli/core/settings-locks.ts
3255
3272
  import { isDeepStrictEqual } from "util";
3256
- function lockedPaths(schema2) {
3273
+
3274
+ // ../sdk/lib/build/callbacks.js
3275
+ var UndeclaredApiUseError = class extends Error {
3276
+ resourceIdentifier;
3277
+ api;
3278
+ constructor(resourceIdentifier, api) {
3279
+ super(`Resource "${resourceIdentifier}" attempted to call callback "${api}" but did not declare it in its bundle's "uses" array. Add "${api}" to the bundle's uses to allow this call.`);
3280
+ this.name = "UndeclaredApiUseError";
3281
+ this.resourceIdentifier = resourceIdentifier;
3282
+ this.api = api;
3283
+ }
3284
+ };
3285
+
3286
+ // ../sdk/lib/build/tick-validation.js
3287
+ var MAX_EFFECTIVE_TICK_INTERVAL_MS = 7 * 24 * 60 * 60 * 1e3;
3288
+
3289
+ // ../sdk/lib/build/setting-path.js
3290
+ var NOT_PLAIN = /[.[\]"\s]/u;
3291
+ function isPlainKey(key) {
3292
+ return key !== "" && !NOT_PLAIN.test(key);
3293
+ }
3294
+ function settingPath(identifier, ...keys) {
3295
+ let path3 = isPlainKey(identifier) ? identifier : `[${JSON.stringify(identifier)}]`;
3296
+ for (const key of keys) {
3297
+ const step = String(key);
3298
+ path3 += isPlainKey(step) ? `.${step}` : `[${JSON.stringify(step)}]`;
3299
+ }
3300
+ return path3;
3301
+ }
3302
+ function parseSettingPath(path3) {
3303
+ const steps = [];
3304
+ let at = 0;
3305
+ while (at < path3.length) {
3306
+ if (path3[at] === "[") {
3307
+ const end2 = closingQuote(path3, at + 1);
3308
+ if (end2 === void 0 || path3[end2 + 1] !== "]")
3309
+ return void 0;
3310
+ let key2;
3311
+ try {
3312
+ key2 = JSON.parse(path3.slice(at + 1, end2 + 1));
3313
+ } catch {
3314
+ return void 0;
3315
+ }
3316
+ if (typeof key2 !== "string")
3317
+ return void 0;
3318
+ steps.push(key2);
3319
+ at = end2 + 2;
3320
+ continue;
3321
+ }
3322
+ if (steps.length > 0) {
3323
+ if (path3[at] !== ".")
3324
+ return void 0;
3325
+ at += 1;
3326
+ }
3327
+ let end = at;
3328
+ while (end < path3.length && path3[end] !== "." && path3[end] !== "[")
3329
+ end += 1;
3330
+ const key = path3.slice(at, end);
3331
+ if (!isPlainKey(key))
3332
+ return void 0;
3333
+ steps.push(key);
3334
+ at = end;
3335
+ }
3336
+ const [identifier, ...keys] = steps;
3337
+ return identifier === void 0 ? void 0 : { identifier, keys };
3338
+ }
3339
+ function closingQuote(path3, start) {
3340
+ if (path3[start] !== '"')
3341
+ return void 0;
3342
+ for (let at = start + 1; at < path3.length; at += 1) {
3343
+ if (path3[at] === "\\")
3344
+ at += 1;
3345
+ else if (path3[at] === '"')
3346
+ return at;
3347
+ }
3348
+ return void 0;
3349
+ }
3350
+
3351
+ // ../sdk/lib/build/validators.js
3352
+ var SCENARIO_GATE_READ_LIMIT_BYTES = 10 * 1024 * 1024;
3353
+ var ScenarioAssetTooLargeError = class _ScenarioAssetTooLargeError extends Error {
3354
+ /** The reference the gate asked to read. */
3355
+ reference;
3356
+ /** The file's size in bytes. */
3357
+ size;
3358
+ /** The cap it exceeds: {@link SCENARIO_GATE_READ_LIMIT_BYTES}. */
3359
+ limit;
3360
+ constructor(reference, size) {
3361
+ super(`Cannot read "${reference}" in a Scenario gate: it is ${size} bytes, over the ${SCENARIO_GATE_READ_LIMIT_BYTES}-byte (10 MB) limit on a gate's reads. Call describeAsset to check that it is there or how large it is.`);
3362
+ this.name = "ScenarioAssetTooLargeError";
3363
+ this.reference = reference;
3364
+ this.size = size;
3365
+ this.limit = SCENARIO_GATE_READ_LIMIT_BYTES;
3366
+ Object.setPrototypeOf(this, _ScenarioAssetTooLargeError.prototype);
3367
+ }
3368
+ };
3369
+
3370
+ // cli/utils/local-refs.ts
3371
+ function isLocalRef(ref) {
3372
+ return ref === "#" || ref.startsWith("#/");
3373
+ }
3374
+ function resolveLocalRef(root2, ref) {
3375
+ if (!isLocalRef(ref)) return void 0;
3376
+ let current = root2;
3377
+ for (const token of ref === "#" ? [] : ref.slice(2).split("/")) {
3378
+ const key = decodeToken(token);
3379
+ if (current === null || typeof current !== "object") return void 0;
3380
+ if (Array.isArray(current)) {
3381
+ if (!/^\d+$/.test(key)) return void 0;
3382
+ current = current[Number(key)];
3383
+ } else {
3384
+ if (!Object.prototype.hasOwnProperty.call(current, key)) return void 0;
3385
+ current = current[key];
3386
+ }
3387
+ }
3388
+ return typeof current === "boolean" || current !== null && typeof current === "object" && !Array.isArray(current) ? current : void 0;
3389
+ }
3390
+ function decodeToken(token) {
3391
+ let decoded = token;
3392
+ try {
3393
+ decoded = decodeURIComponent(token);
3394
+ } catch {
3395
+ }
3396
+ return decoded.replace(/~1/g, "/").replace(/~0/g, "~");
3397
+ }
3398
+ function dereference(root2, schema2) {
3399
+ let current = schema2;
3400
+ const followed = /* @__PURE__ */ new Set();
3401
+ while (typeof current.$ref === "string") {
3402
+ const { $ref: ref, ...beside } = current;
3403
+ const target = followed.has(ref) ? void 0 : resolveLocalRef(root2, ref);
3404
+ followed.add(ref);
3405
+ if (target === void 0 || typeof target !== "object") return beside;
3406
+ current = { ...target, ...beside };
3407
+ }
3408
+ return current;
3409
+ }
3410
+ var SCHEMA_MAPS = ["properties", "patternProperties", "definitions", "$defs"];
3411
+ var SCHEMA_SLOTS = [
3412
+ "additionalProperties",
3413
+ "additionalItems",
3414
+ "contains",
3415
+ "propertyNames",
3416
+ "if",
3417
+ "then",
3418
+ "else",
3419
+ "not"
3420
+ ];
3421
+ var SCHEMA_LISTS = ["allOf", "anyOf", "oneOf"];
3422
+ function childSchemas(schema2) {
3423
+ const found = [];
3424
+ const push2 = (step, child) => {
3425
+ if (child !== null && typeof child === "object" && !Array.isArray(child)) {
3426
+ found.push({ step, schema: child });
3427
+ }
3428
+ };
3429
+ for (const keyword of SCHEMA_MAPS) {
3430
+ const map3 = schema2[keyword];
3431
+ if (!map3 || typeof map3 !== "object") continue;
3432
+ for (const [key, child] of Object.entries(map3))
3433
+ push2(`${keyword}/${encodeToken(key)}`, child);
3434
+ }
3435
+ for (const keyword of SCHEMA_SLOTS) push2(keyword, schema2[keyword]);
3436
+ for (const keyword of SCHEMA_LISTS) {
3437
+ schema2[keyword]?.forEach((child, index3) => push2(`${keyword}/${index3}`, child));
3438
+ }
3439
+ if (Array.isArray(schema2.items)) {
3440
+ schema2.items.forEach((child, index3) => push2(`items/${index3}`, child));
3441
+ } else {
3442
+ push2("items", schema2.items);
3443
+ }
3444
+ return found;
3445
+ }
3446
+ function encodeToken(key) {
3447
+ return key.replace(/~/g, "~0").replace(/\//g, "~1");
3448
+ }
3449
+ function refProblems(schema2) {
3450
+ const problems = [];
3451
+ const visit2 = (node2, pointer) => {
3452
+ const ref = node2.$ref;
3453
+ if (typeof ref === "string") {
3454
+ if (!isLocalRef(ref)) problems.push({ pointer, ref, reason: "not-local" });
3455
+ else if (resolveLocalRef(schema2, ref) === void 0) {
3456
+ problems.push({ pointer, ref, reason: "unresolved" });
3457
+ }
3458
+ }
3459
+ for (const child of childSchemas(node2)) visit2(child.schema, `${pointer}/${child.step}`);
3460
+ };
3461
+ visit2(schema2, "");
3462
+ return problems;
3463
+ }
3464
+ function refProblemMessage(owner, keyword, problem) {
3465
+ const at = `${keyword}${problem.pointer}`;
3466
+ return problem.reason === "not-local" ? `${owner}: ${at} has "$ref": ${JSON.stringify(problem.ref)}, which is not a reference into the same schema. A reference may only name a part of the schema that holds it, such as "#/$defs/rule"` : `${owner}: ${at} has "$ref": ${JSON.stringify(problem.ref)}, which names nothing in the schema. Add it under $defs, or correct the reference`;
3467
+ }
3468
+
3469
+ // cli/core/settings-locks.ts
3470
+ function lockedPathsNamed(override, schema2) {
3257
3471
  const paths = [];
3258
- if (schema2) collect(schema2, [], paths);
3472
+ if (schema2) named(schema2, schema2, override, [], paths);
3259
3473
  return paths;
3260
3474
  }
3261
- function collect(schema2, at, paths) {
3475
+ function named(root2, declared, value, at, paths) {
3476
+ if (value === void 0) return;
3477
+ const schema2 = dereference(root2, declared);
3262
3478
  if (schema2.readOnly === true) {
3263
3479
  paths.push(at);
3264
3480
  return;
3265
3481
  }
3266
- for (const [key, property] of Object.entries(schema2.properties ?? {})) {
3267
- if (typeof property === "object") collect(property, [...at, key], paths);
3482
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return;
3483
+ for (const [key, member] of Object.entries(value)) {
3484
+ const property = schema2.properties?.[key];
3485
+ if (typeof property === "object") named(root2, property, member, [...at, key], paths);
3268
3486
  }
3269
3487
  }
3270
- function lockedPathsNamed(override, schema2) {
3271
- return lockedPaths(schema2).filter((path3) => valueAt(override, path3) !== void 0);
3488
+ function unenforceableLocks(schema2) {
3489
+ const found = [];
3490
+ const visited = /* @__PURE__ */ new Set();
3491
+ const walk3 = (declared, at, inside) => {
3492
+ const ref = declared.$ref;
3493
+ if (typeof ref === "string") {
3494
+ const key = `${inside ? "entry" : "named"}\0${ref}`;
3495
+ if (visited.has(key)) return;
3496
+ visited.add(key);
3497
+ }
3498
+ const node2 = dereference(schema2, declared);
3499
+ if (node2.readOnly === true) {
3500
+ if (inside) found.push({ path: at, ...inside });
3501
+ return;
3502
+ }
3503
+ for (const [key, property] of Object.entries(node2.properties ?? {})) {
3504
+ if (typeof property === "object") walk3(property, [...at, key], inside);
3505
+ }
3506
+ const entries = { container: at, kind: "map" };
3507
+ for (const [pattern, child] of Object.entries(node2.patternProperties ?? {})) {
3508
+ if (typeof child === "object") walk3(child, [...at, `/${pattern}/`], inside ?? entries);
3509
+ }
3510
+ if (typeof node2.additionalProperties === "object") {
3511
+ walk3(node2.additionalProperties, [...at, "*"], inside ?? entries);
3512
+ }
3513
+ const items = Array.isArray(node2.items) ? node2.items : node2.items ? [node2.items] : [];
3514
+ for (const item of items) {
3515
+ if (typeof item === "object") {
3516
+ walk3(item, [...at, "[]"], inside ?? { container: at, kind: "list" });
3517
+ }
3518
+ }
3519
+ };
3520
+ walk3(schema2, [], void 0);
3521
+ return found;
3522
+ }
3523
+ function unenforceableLockMessage(identifier, lock) {
3524
+ const where3 = lock.kind === "list" ? "a list's items" : "a map's entries";
3525
+ const container2 = lock.container.length > 0 ? lock.container.join(".") : "the top level";
3526
+ return `Settings "${identifier}" property "${lock.path.join(".")}" is readOnly inside ${where3}, which a scenario adds and removes, so there is no single value for the lock to keep. Lock the whole ${lock.kind} instead: put readOnly on "${container2}"`;
3272
3527
  }
3273
3528
  function lockedSettingName(identifier, path3) {
3274
- return [identifier, ...path3].join(".");
3529
+ return settingPath(identifier, ...path3);
3275
3530
  }
3276
3531
  function lockedSettingMessage(identifier, path3) {
3277
3532
  return `"${lockedSettingName(identifier, path3)}" is read-only: the game fixes it, so no scenario or session may change it`;
@@ -3281,7 +3536,7 @@ function withoutLockedDefaults(settings, schemas) {
3281
3536
  for (const [identifier, schema2] of Object.entries(schemas)) {
3282
3537
  if (!(identifier in result)) continue;
3283
3538
  const defaults = schemaDefaults(schema2);
3284
- for (const path3 of lockedPaths(schema2)) {
3539
+ for (const path3 of lockedPathsNamed(result[identifier], schema2)) {
3285
3540
  if (path3.length === 0) {
3286
3541
  if (isDeepStrictEqual(result[identifier], defaults)) delete result[identifier];
3287
3542
  continue;
@@ -4198,13 +4453,41 @@ function validateSettingsOverrides(overrides, schemas, sourceLabel) {
4198
4453
  ${errors.join("\n")}` } : { valid: true };
4199
4454
  }
4200
4455
  function validatePartialOverride(override, settingsSchema) {
4201
- const validator = settingsAjv.compile(closed(withoutRequired(settingsSchema)));
4456
+ let validator;
4457
+ try {
4458
+ validator = settingsAjv.compile(closed(withoutRequired(settingsSchema)));
4459
+ } catch (error) {
4460
+ return [
4461
+ {
4462
+ keyword: "compile",
4463
+ instancePath: "",
4464
+ schemaPath: "#",
4465
+ params: {},
4466
+ message: `cannot be checked: its settings schema does not compile (${error instanceof Error ? error.message : String(error)})`
4467
+ }
4468
+ ];
4469
+ }
4202
4470
  return validator(override) ? null : validator.errors ?? [];
4203
4471
  }
4204
4472
  var SCHEMA_MAP_KEYWORDS = ["properties", "patternProperties", "definitions", "$defs"];
4205
4473
  var SUBSCHEMA_KEYWORDS = ["additionalProperties", "then", "else"];
4206
4474
  var SCHEMA_LIST_KEYWORDS = ["allOf", "anyOf", "oneOf"];
4207
4475
  function withoutRequired(schema2) {
4476
+ const partial = partially(schema2);
4477
+ if (typeof schema2 !== "object" || typeof partial !== "object") return partial;
4478
+ for (const keyword of DEFINITION_KEYWORDS) {
4479
+ const defs = schema2[keyword];
4480
+ const copied = partial[keyword];
4481
+ if (!defs || typeof defs !== "object" || !copied || typeof copied !== "object") continue;
4482
+ for (const [name, def] of Object.entries(defs)) {
4483
+ copied[`${WHOLE}${name}`] = wholeRefs(def);
4484
+ }
4485
+ }
4486
+ return partial;
4487
+ }
4488
+ var DEFINITION_KEYWORDS = ["$defs", "definitions"];
4489
+ var WHOLE = "__whole__";
4490
+ function partially(schema2) {
4208
4491
  if (typeof schema2 !== "object" || schema2 === null) return schema2;
4209
4492
  const { required: _required, ...rest } = schema2;
4210
4493
  const copy = { ...rest };
@@ -4212,20 +4495,32 @@ function withoutRequired(schema2) {
4212
4495
  const map3 = rest[keyword];
4213
4496
  if (map3 && typeof map3 === "object") {
4214
4497
  copy[keyword] = Object.fromEntries(
4215
- Object.entries(map3).map(([key, value]) => [key, withoutRequired(value)])
4498
+ Object.entries(map3).map(([key, value]) => [key, partially(value)])
4216
4499
  );
4217
4500
  }
4218
4501
  }
4219
4502
  for (const keyword of SUBSCHEMA_KEYWORDS) {
4220
4503
  const sub = rest[keyword];
4221
- if (sub !== void 0) copy[keyword] = withoutRequired(sub);
4504
+ if (sub !== void 0) copy[keyword] = partially(sub);
4222
4505
  }
4223
4506
  for (const keyword of SCHEMA_LIST_KEYWORDS) {
4224
4507
  const list3 = rest[keyword];
4225
- if (Array.isArray(list3)) copy[keyword] = list3.map(withoutRequired);
4508
+ if (Array.isArray(list3)) copy[keyword] = list3.map(partially);
4226
4509
  }
4510
+ if (rest.items !== void 0) copy.items = wholeRefs(rest.items);
4227
4511
  return copy;
4228
4512
  }
4513
+ var DATA_KEYWORDS = /* @__PURE__ */ new Set(["default", "const", "enum", "examples"]);
4514
+ function wholeRefs(value) {
4515
+ if (Array.isArray(value)) return value.map(wholeRefs);
4516
+ if (value === null || typeof value !== "object") return value;
4517
+ return Object.fromEntries(
4518
+ Object.entries(value).map(([key, child]) => [
4519
+ key,
4520
+ key === "$ref" && typeof child === "string" ? child.replace(/^#\/(\$defs|definitions)\/(?=[^/]+$)/, `#/$1/${WHOLE}`) : DATA_KEYWORDS.has(key) ? child : wholeRefs(child)
4521
+ ])
4522
+ );
4523
+ }
4229
4524
  var COMBINATOR_KEYWORDS = ["allOf", "anyOf", "oneOf", "if", "not", "$ref"];
4230
4525
  function closed(schema2) {
4231
4526
  if (typeof schema2 !== "object" || schema2 === null) return schema2;
@@ -4827,12 +5122,12 @@ function assertRequiredFeaturesSupported(config, filePath) {
4827
5122
  function assertDeclaredServicesSupported(resources) {
4828
5123
  const missing = unsupportedServices(resources);
4829
5124
  if (missing.length === 0) return;
4830
- const named2 = missing.map(
5125
+ const named3 = missing.map(
4831
5126
  ({ service, resources: declaring }) => `"${service}" (declared by ${declaring.join(", ")})`
4832
5127
  ).join(", ");
4833
5128
  throw new CliError(
4834
5129
  "PACKAGE_INVALID",
4835
- `Invalid package: its resources declare ${named2} in \`uses\`, which this version of the SDK does not provide. Upgrade the SDK, or remove the service from \`uses\` if the resource does not call it.`
5130
+ `Invalid package: its resources declare ${named3} in \`uses\`, which this version of the SDK does not provide. Upgrade the SDK, or remove the service from \`uses\` if the resource does not call it.`
4836
5131
  );
4837
5132
  }
4838
5133
  function resolvePackage(config, configDir, game) {
@@ -5615,12 +5910,23 @@ var ConfigResolver = class {
5615
5910
  /**
5616
5911
  * Resolve the active scenario from a provided ID or the game's default.
5617
5912
  * Returns null if the game declares no scenarios, or when null is passed
5618
- * to explicitly opt out of the default scenario (the settings defaults).
5913
+ * for a game with no default scenario (the settings defaults).
5914
+ *
5915
+ * A game that declares a default never runs on none (§6.7), so null is
5916
+ * refused for it, naming the default.
5619
5917
  */
5620
5918
  resolveScenario(scenarioId) {
5621
- if (scenarioId === null) return null;
5622
5919
  const game = this.ctx.getGame();
5623
5920
  const config = this.ctx.getConfig();
5921
+ if (scenarioId === null) {
5922
+ const fallback = config?.scenarios?.find((s) => s.definition.default);
5923
+ if (fallback) {
5924
+ throw new DeniedError(
5925
+ `This game runs on a scenario: its default is "${fallback.definition.identifier}", so it cannot run on none`
5926
+ );
5927
+ }
5928
+ return null;
5929
+ }
5624
5930
  if (!game || !config) return null;
5625
5931
  const allScenarios = config.scenarios || [];
5626
5932
  if (allScenarios.length === 0) return null;
@@ -6033,20 +6339,20 @@ function assertDeletesDeclared(label4, deletes, declaration, shared, target) {
6033
6339
  const reads = new Set(declaration.reads ?? []);
6034
6340
  for (const path3 of deletes) {
6035
6341
  const capId = deleteHead(path3);
6036
- const named2 = `${label4} deletes ${describeDeletePath(path3)}`;
6342
+ const named3 = `${label4} deletes ${describeDeletePath(path3)}`;
6037
6343
  if (target === "team" && shared.has(capId)) {
6038
6344
  throw new Error(
6039
- `${named2} under shared capability "${capId}". A shared capability has one value for the session, so only an aggregate result's "shared" or a session-scoped endpoint may change it.`
6345
+ `${named3} under shared capability "${capId}". A shared capability has one value for the session, so only an aggregate result's "shared" or a session-scoped endpoint may change it.`
6040
6346
  );
6041
6347
  }
6042
6348
  if (target === "shared" && !shared.has(capId)) {
6043
6349
  throw new Error(
6044
- `${named2} under "${capId}", which is not a shared-scope capability. Only shared capabilities may be deleted from a shared result.`
6350
+ `${named3} under "${capId}", which is not a shared-scope capability. Only shared capabilities may be deleted from a shared result.`
6045
6351
  );
6046
6352
  }
6047
6353
  if (!writes.has(capId)) {
6048
6354
  throw new Error(
6049
- reads.has(capId) ? `${named2} under capability "${capId}", but declares it only in reads. Add it to writes, or leave it alone.` : `${named2} under "${capId}", which it does not declare in writes.`
6355
+ reads.has(capId) ? `${named3} under capability "${capId}", but declares it only in reads. Add it to writes, or leave it alone.` : `${named3} under "${capId}", which it does not declare in writes.`
6050
6356
  );
6051
6357
  }
6052
6358
  }
@@ -6326,7 +6632,7 @@ function computeCapabilityDefaults(config) {
6326
6632
  // cli/storage/blob-store.ts
6327
6633
  import { randomUUID } from "crypto";
6328
6634
  import { existsSync as existsSync4 } from "fs";
6329
- import { mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
6635
+ import { mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rm, stat, writeFile as writeFile2 } from "fs/promises";
6330
6636
  import { join as join3, resolve as resolve2 } from "path";
6331
6637
  var MAX_BLOB_SIZE = 20 * 1024 * 1024;
6332
6638
  var redirected = /* @__PURE__ */ new Map();
@@ -6376,6 +6682,18 @@ async function readBlob(packagePath, id) {
6376
6682
  const meta = JSON.parse(metaRaw);
6377
6683
  return { ...meta, data };
6378
6684
  }
6685
+ async function describeBlob(packagePath, id) {
6686
+ const dir = getBlobsDir(packagePath);
6687
+ try {
6688
+ const [metaRaw, bin] = await Promise.all([
6689
+ readFile2(metaPath(dir, id), "utf-8"),
6690
+ stat(binPath(dir, id))
6691
+ ]);
6692
+ return { ...JSON.parse(metaRaw), size: bin.size };
6693
+ } catch {
6694
+ return void 0;
6695
+ }
6696
+ }
6379
6697
  async function deleteBlobs(packagePath, retentions) {
6380
6698
  const dir = getBlobsDir(packagePath);
6381
6699
  let entries;
@@ -6400,19 +6718,62 @@ async function deleteBlobs(packagePath, retentions) {
6400
6718
  );
6401
6719
  }
6402
6720
 
6721
+ // cli/utils/schema-members.ts
6722
+ function memberSchemas(schema2, key) {
6723
+ const found = [];
6724
+ let declared = false;
6725
+ const named3 = schema2.properties?.[key];
6726
+ if (named3 !== void 0) {
6727
+ declared = true;
6728
+ if (typeof named3 === "object") found.push(named3);
6729
+ }
6730
+ for (const [pattern, child] of Object.entries(schema2.patternProperties ?? {})) {
6731
+ if (!matches2(pattern, key)) continue;
6732
+ declared = true;
6733
+ if (typeof child === "object") found.push(child);
6734
+ }
6735
+ if (!declared && typeof schema2.additionalProperties === "object") {
6736
+ found.push(schema2.additionalProperties);
6737
+ }
6738
+ return found;
6739
+ }
6740
+ function memberDeclarations(schema2) {
6741
+ const found = [];
6742
+ for (const [key, child] of Object.entries(schema2.properties ?? {})) {
6743
+ if (typeof child === "object") found.push({ step: key, schema: child });
6744
+ }
6745
+ for (const [pattern, child] of Object.entries(schema2.patternProperties ?? {})) {
6746
+ if (typeof child === "object") found.push({ step: `/${pattern}/`, schema: child });
6747
+ }
6748
+ if (typeof schema2.additionalProperties === "object") {
6749
+ found.push({ step: "*", schema: schema2.additionalProperties });
6750
+ }
6751
+ return found;
6752
+ }
6753
+ function matches2(pattern, key) {
6754
+ try {
6755
+ return new RegExp(pattern, "u").test(key);
6756
+ } catch {
6757
+ return false;
6758
+ }
6759
+ }
6760
+
6403
6761
  // cli/execution/blob-inputs.ts
6404
6762
  var MAX_INLINE_BYTES = 5 * 1024 * 1024;
6405
- function blobValues(schema2, value, path3 = []) {
6406
- if (!schema2 || typeof schema2 !== "object") return [];
6763
+ function blobValues(declared, value, path3 = [], root2 = declared) {
6764
+ if (!declared || typeof declared !== "object" || !root2) return [];
6765
+ const schema2 = dereference(root2, declared);
6407
6766
  const spec = schema2.blob;
6408
6767
  if (spec) return value === void 0 ? [] : [{ path: path3, spec, value }];
6409
6768
  if (Array.isArray(value) && schema2.items && !Array.isArray(schema2.items)) {
6410
6769
  const items = schema2.items;
6411
- return value.flatMap((item, at) => blobValues(items, item, [...path3, at]));
6770
+ return value.flatMap((item, at) => blobValues(items, item, [...path3, at], root2));
6412
6771
  }
6413
- if (value && typeof value === "object" && !Array.isArray(value) && schema2.properties) {
6414
- return Object.entries(schema2.properties).flatMap(
6415
- ([key, child]) => typeof child === "object" ? blobValues(child, value[key], [...path3, key]) : []
6772
+ if (value && typeof value === "object" && !Array.isArray(value)) {
6773
+ return Object.entries(value).flatMap(
6774
+ ([key, member]) => memberSchemas(schema2, key).flatMap(
6775
+ (child) => blobValues(child, member, [...path3, key], root2)
6776
+ )
6416
6777
  );
6417
6778
  }
6418
6779
  return [];
@@ -6527,7 +6888,7 @@ var ACTION_FIELDS = {
6527
6888
  addTeam: { "name?": "string" },
6528
6889
  setLocale: { locale: "string" }
6529
6890
  };
6530
- function matches2(value, kind2) {
6891
+ function matches3(value, kind2) {
6531
6892
  switch (kind2) {
6532
6893
  case "string":
6533
6894
  return typeof value === "string" && value.length > 0;
@@ -6565,7 +6926,7 @@ function readEndpointActions(identifier, declared, returned) {
6565
6926
  if (key.endsWith("?")) continue;
6566
6927
  throw new Error(`${label4} ("${type}") requires "${name}"`);
6567
6928
  }
6568
- if (!matches2(value, kind2)) {
6929
+ if (!matches3(value, kind2)) {
6569
6930
  throw new Error(`${label4} ("${type}") field "${name}" must be a ${kind2}`);
6570
6931
  }
6571
6932
  }
@@ -6922,7 +7283,7 @@ var EndpointRunner = class {
6922
7283
  const callbacks = calls.callbacksFor(
6923
7284
  endpoint.definition.identifier,
6924
7285
  endpoint.definition.uses,
6925
- scenarioScoped ? "scenario" : void 0
7286
+ scenarioScoped ? { scenarioRoot: args.scenarioRoot ?? null } : void 0
6926
7287
  );
6927
7288
  const scope = sessionScoped || scenarioScoped ? null : args.scopedTeamIndex ?? null;
6928
7289
  const label4 = exportName === "Handle" ? `Endpoint "${args.identifier}"` : `Endpoint "${args.identifier}" ${exportName}`;
@@ -7146,21 +7507,6 @@ async function runHookChain(host, signal, payload) {
7146
7507
  return structuredClone(host.board());
7147
7508
  }
7148
7509
 
7149
- // ../sdk/lib/build/callbacks.js
7150
- var UndeclaredApiUseError = class extends Error {
7151
- resourceIdentifier;
7152
- api;
7153
- constructor(resourceIdentifier, api) {
7154
- super(`Resource "${resourceIdentifier}" attempted to call callback "${api}" but did not declare it in its bundle's "uses" array. Add "${api}" to the bundle's uses to allow this call.`);
7155
- this.name = "UndeclaredApiUseError";
7156
- this.resourceIdentifier = resourceIdentifier;
7157
- this.api = api;
7158
- }
7159
- };
7160
-
7161
- // ../sdk/lib/build/tick-validation.js
7162
- var MAX_EFFECTIVE_TICK_INTERVAL_MS = 7 * 24 * 60 * 60 * 1e3;
7163
-
7164
7510
  // cli/runtime/guarded-callbacks.ts
7165
7511
  var API_USE_TO_CALLBACK = {
7166
7512
  generateText: "generateText",
@@ -7182,68 +7528,106 @@ function createGuardedCallbacks(callbacks, uses, resourceIdentifier) {
7182
7528
  }
7183
7529
 
7184
7530
  // cli/storage/asset-resolver.ts
7185
- import { readFile as readFile3 } from "fs/promises";
7531
+ import { readFile as readFile3, stat as stat2 } from "fs/promises";
7186
7532
  import { basename as basename2, isAbsolute as isAbsolute3, normalize, resolve as resolvePath, sep as sep4 } from "path";
7187
7533
  var ASSET_PREFIX = "asset:";
7188
7534
  var SHARED_PREFIX = "shared:";
7189
7535
  var BLOB_PREFIX = "blob:";
7190
- var EXTENSION_MIME_TYPES = {
7191
- pdf: "application/pdf",
7192
- json: "application/json",
7193
- txt: "text/plain",
7194
- md: "text/markdown",
7195
- html: "text/html",
7196
- htm: "text/html",
7536
+ var EXTENSION_MEDIA_TYPES = {
7537
+ aac: "audio/aac",
7538
+ avif: "image/avif",
7539
+ bmp: "image/bmp",
7197
7540
  css: "text/css",
7198
7541
  csv: "text/csv",
7199
- svg: "image/svg+xml",
7200
- png: "image/png",
7201
- jpg: "image/jpeg",
7202
- jpeg: "image/jpeg",
7542
+ doc: "application/msword",
7543
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
7544
+ flac: "audio/flac",
7203
7545
  gif: "image/gif",
7204
- webp: "image/webp",
7546
+ htm: "text/html",
7547
+ html: "text/html",
7205
7548
  ico: "image/x-icon",
7549
+ jpeg: "image/jpeg",
7550
+ jpg: "image/jpeg",
7551
+ js: "text/javascript",
7552
+ json: "application/json",
7553
+ m4a: "audio/mp4",
7554
+ m4v: "video/mp4",
7555
+ md: "text/markdown",
7556
+ mjs: "text/javascript",
7557
+ mov: "video/quicktime",
7206
7558
  mp3: "audio/mpeg",
7207
- wav: "audio/wav",
7559
+ mp4: "video/mp4",
7560
+ odp: "application/vnd.oasis.opendocument.presentation",
7561
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
7562
+ odt: "application/vnd.oasis.opendocument.text",
7208
7563
  ogg: "audio/ogg",
7209
7564
  opus: "audio/ogg",
7210
- mp4: "video/mp4",
7565
+ otf: "font/otf",
7566
+ pdf: "application/pdf",
7567
+ png: "image/png",
7568
+ ppt: "application/vnd.ms-powerpoint",
7569
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
7570
+ rtf: "application/rtf",
7571
+ svg: "image/svg+xml",
7572
+ tif: "image/tiff",
7573
+ tiff: "image/tiff",
7574
+ ttf: "font/ttf",
7575
+ txt: "text/plain",
7576
+ vtt: "text/vtt",
7577
+ wav: "audio/wav",
7211
7578
  webm: "video/webm",
7579
+ webp: "image/webp",
7212
7580
  woff: "font/woff",
7213
- woff2: "font/woff2"
7581
+ woff2: "font/woff2",
7582
+ xls: "application/vnd.ms-excel",
7583
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
7584
+ xml: "application/xml",
7585
+ yaml: "application/yaml",
7586
+ yml: "application/yaml",
7587
+ zip: "application/zip"
7214
7588
  };
7215
- function mimeFromExtension(path3) {
7216
- const dot = path3.lastIndexOf(".");
7217
- if (dot < 0) return "application/octet-stream";
7218
- const ext = path3.slice(dot + 1).toLowerCase();
7219
- return EXTENSION_MIME_TYPES[ext] ?? "application/octet-stream";
7589
+ var UNLISTED_MEDIA_TYPE = "application/octet-stream";
7590
+ function mediaTypeOf(path3) {
7591
+ const name = path3.slice(Math.max(path3.lastIndexOf("/"), path3.lastIndexOf("\\")) + 1);
7592
+ const dot = name.lastIndexOf(".");
7593
+ if (dot < 0) return UNLISTED_MEDIA_TYPE;
7594
+ const ext = name.slice(dot + 1).toLowerCase();
7595
+ return Object.hasOwn(EXTENSION_MEDIA_TYPES, ext) ? EXTENSION_MEDIA_TYPES[ext] : UNLISTED_MEDIA_TYPE;
7220
7596
  }
7221
7597
  function isAssetReference(value) {
7222
7598
  return typeof value === "string" && (value.startsWith(ASSET_PREFIX) || value.startsWith(SHARED_PREFIX) || value.startsWith(BLOB_PREFIX));
7223
7599
  }
7224
- async function resolveAsset(scenarioRootDirectory, path3) {
7600
+ function scenarioAssetPath(scenarioRootDirectory, path3) {
7225
7601
  const assetsRoot = resolvePath(scenarioRootDirectory, "assets");
7226
7602
  const resolvedPath = resolvePath(assetsRoot, normalize(path3));
7227
7603
  if (!resolvedPath.startsWith(assetsRoot + sep4)) {
7228
7604
  throw new Error(`Asset path escapes scenario assets directory: ${path3}`);
7229
7605
  }
7606
+ return resolvedPath;
7607
+ }
7608
+ function sharedAssetPath(packagePath, path3) {
7609
+ const sharedRoot = resolvePath(packagePath, "shared-assets");
7610
+ const resolvedPath = resolvePath(sharedRoot, normalize(path3));
7611
+ if (!resolvedPath.startsWith(sharedRoot + sep4)) {
7612
+ throw new Error(`Asset path escapes shared-assets directory: ${path3}`);
7613
+ }
7614
+ return resolvedPath;
7615
+ }
7616
+ async function resolveAsset(scenarioRootDirectory, path3) {
7617
+ const resolvedPath = scenarioAssetPath(scenarioRootDirectory, path3);
7230
7618
  const data = await readFile3(resolvedPath);
7231
7619
  return {
7232
7620
  data,
7233
- mimeType: mimeFromExtension(resolvedPath),
7621
+ mimeType: mediaTypeOf(resolvedPath),
7234
7622
  name: basename2(resolvedPath)
7235
7623
  };
7236
7624
  }
7237
7625
  async function resolveSharedAsset(packagePath, path3) {
7238
- const sharedRoot = resolvePath(packagePath, "shared-assets");
7239
- const resolvedPath = resolvePath(sharedRoot, normalize(path3));
7240
- if (!resolvedPath.startsWith(sharedRoot + sep4)) {
7241
- throw new Error(`Asset path escapes shared-assets directory: ${path3}`);
7242
- }
7626
+ const resolvedPath = sharedAssetPath(packagePath, path3);
7243
7627
  const data = await readFile3(resolvedPath);
7244
7628
  return {
7245
7629
  data,
7246
- mimeType: mimeFromExtension(resolvedPath),
7630
+ mimeType: mediaTypeOf(resolvedPath),
7247
7631
  name: basename2(resolvedPath)
7248
7632
  };
7249
7633
  }
@@ -7269,6 +7653,30 @@ async function readAssetByReference(packagePath, scenarioRootDirectory, referenc
7269
7653
  `Invalid asset reference "${reference}": expected an "asset:", "shared:", or "blob:" prefix`
7270
7654
  );
7271
7655
  }
7656
+ async function describeAssetByReference(packagePath, scenarioRootDirectory, reference) {
7657
+ if (reference.startsWith(BLOB_PREFIX)) {
7658
+ const blob = await describeBlob(packagePath, reference.slice(BLOB_PREFIX.length));
7659
+ return blob && { mimeType: blob.mimeType, size: blob.size };
7660
+ }
7661
+ let path3;
7662
+ if (reference.startsWith(SHARED_PREFIX)) {
7663
+ path3 = sharedAssetPath(packagePath, reference.slice(SHARED_PREFIX.length));
7664
+ } else if (reference.startsWith(ASSET_PREFIX)) {
7665
+ if (!scenarioRootDirectory) return void 0;
7666
+ const root2 = isAbsolute3(scenarioRootDirectory) ? scenarioRootDirectory : resolvePath(packagePath, scenarioRootDirectory);
7667
+ path3 = scenarioAssetPath(root2, reference.slice(ASSET_PREFIX.length));
7668
+ } else {
7669
+ throw new Error(
7670
+ `Invalid asset reference "${reference}": expected an "asset:", "shared:", or "blob:" prefix`
7671
+ );
7672
+ }
7673
+ try {
7674
+ const file = await stat2(path3);
7675
+ return file.isFile() ? { mimeType: mediaTypeOf(path3), size: file.size } : void 0;
7676
+ } catch {
7677
+ return void 0;
7678
+ }
7679
+ }
7272
7680
 
7273
7681
  // cli/execution/executor-callbacks.ts
7274
7682
  function createExecutorCallbacks(deps) {
@@ -7311,6 +7719,16 @@ function createExecutorCallbacks(deps) {
7311
7719
  name: asset.name
7312
7720
  };
7313
7721
  },
7722
+ // Not `uses`-gated, like `readAsset`, and resolved exactly as it is,
7723
+ // so a file one finds is one the other reads (§10.3).
7724
+ describeAsset: async (reference) => {
7725
+ requireGame();
7726
+ return describeAssetByReference(
7727
+ deps.packagePath,
7728
+ deps.getActiveScenarioRoot(),
7729
+ reference
7730
+ );
7731
+ },
7314
7732
  extractText: async (reference) => {
7315
7733
  requireGame();
7316
7734
  const asset = await readAssetByReference(
@@ -7535,11 +7953,18 @@ var LogicCalls = class {
7535
7953
  * The callbacks a resource receives: the raw runtime callbacks, built
7536
7954
  * fresh so they read the live game, with every one its `uses` does not
7537
7955
  * declare replaced by a throwing stub.
7956
+ *
7957
+ * `onDraft` is a scenario-scoped call's: its files are the draft's, and
7958
+ * `asset:` resolves against the scenario being written, not the session's
7959
+ * (§6.5, §6.12, §16.2).
7538
7960
  */
7539
- callbacksFor(resourceIdentifier, uses, blobRetention) {
7961
+ callbacksFor(resourceIdentifier, uses, onDraft) {
7540
7962
  const raw = createExecutorCallbacks({
7541
7963
  ...this.options.callbacks,
7542
- ...blobRetention === void 0 ? {} : { blobRetention },
7964
+ ...onDraft === void 0 ? {} : {
7965
+ blobRetention: "scenario",
7966
+ getActiveScenarioRoot: () => onDraft.scenarioRoot
7967
+ },
7543
7968
  readPastState: this.pastStateReader,
7544
7969
  getScopedTeamIndexes: () => this.scopedTeamIndexes,
7545
7970
  getAllTeamIndexes: () => this.teamIndexesForHistory(),
@@ -21989,8 +22414,10 @@ function isUint8Array2(value) {
21989
22414
  // cli/guide/settings.ts
21990
22415
  var WHEN_ATTRIBUTES = ["setting", "is", "not"];
21991
22416
  function lookupSetting(settings, path3) {
21992
- const [identifier, ...keys] = path3.split(".");
21993
- if (!identifier || keys.length === 0 || !(identifier in settings)) return { found: false };
22417
+ const parsed = parseSettingPath(path3);
22418
+ if (!parsed || parsed.keys.length === 0) return { found: false };
22419
+ const { identifier, keys } = parsed;
22420
+ if (!Object.prototype.hasOwnProperty.call(settings, identifier)) return { found: false };
21994
22421
  let value = settings[identifier];
21995
22422
  for (const key of keys) {
21996
22423
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -22951,6 +23378,7 @@ var SessionEndpoints = class {
22951
23378
  request: command.request,
22952
23379
  settings: edited.settings,
22953
23380
  scenarioName: edited.scenarioName,
23381
+ scenarioRoot: edited.scenarioRoot,
22954
23382
  now: this.host.clock.now(),
22955
23383
  caller: {
22956
23384
  role: "author",
@@ -24373,36 +24801,45 @@ var SessionTimers = class {
24373
24801
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
24374
24802
 
24375
24803
  // cli/validation/file-settings.ts
24376
- function fileSettingValues(schema2, value, path3 = []) {
24377
- if (!schema2 || typeof schema2 !== "object") return [];
24804
+ function fileSettingValues(declared, value, path3 = [], root2 = declared) {
24805
+ if (!declared || typeof declared !== "object" || !root2) return [];
24806
+ const schema2 = dereference(root2, declared);
24378
24807
  const spec = schema2.blob;
24379
24808
  if (spec) return value === void 0 ? [] : [{ path: path3, spec, value }];
24380
24809
  if (Array.isArray(value) && schema2.items && !Array.isArray(schema2.items)) {
24381
24810
  const items = schema2.items;
24382
- return value.flatMap((item, at) => fileSettingValues(items, item, [...path3, String(at)]));
24811
+ return value.flatMap(
24812
+ (item, at) => fileSettingValues(items, item, [...path3, String(at)], root2)
24813
+ );
24383
24814
  }
24384
- if (value && typeof value === "object" && !Array.isArray(value) && schema2.properties) {
24385
- return Object.entries(schema2.properties).flatMap(
24386
- ([key, child]) => typeof child === "object" ? fileSettingValues(child, value[key], [...path3, key]) : []
24815
+ if (value && typeof value === "object" && !Array.isArray(value)) {
24816
+ return Object.entries(value).flatMap(
24817
+ ([key, member]) => memberSchemas(schema2, key).flatMap(
24818
+ (child) => fileSettingValues(child, member, [...path3, key], root2)
24819
+ )
24387
24820
  );
24388
24821
  }
24389
24822
  return [];
24390
24823
  }
24391
- function fileSettingDeclarations(schema2, path3 = []) {
24824
+ function fileSettingDeclarations(root2, declared = root2, path3 = [], followed = /* @__PURE__ */ new Set()) {
24825
+ if (typeof declared.$ref === "string") {
24826
+ if (followed.has(declared.$ref)) return [];
24827
+ followed.add(declared.$ref);
24828
+ }
24829
+ const schema2 = dereference(root2, declared);
24392
24830
  const found = [];
24393
24831
  if ("blob" in schema2) found.push({ path: path3, schema: schema2 });
24394
- for (const [key, child] of Object.entries(schema2.properties ?? {})) {
24395
- if (typeof child === "object")
24396
- found.push(...fileSettingDeclarations(child, [...path3, key]));
24832
+ for (const { step, schema: child } of memberDeclarations(schema2)) {
24833
+ found.push(...fileSettingDeclarations(root2, child, [...path3, step], followed));
24397
24834
  }
24398
24835
  if (schema2.items && !Array.isArray(schema2.items) && typeof schema2.items === "object") {
24399
- found.push(...fileSettingDeclarations(schema2.items, [...path3, "[]"]));
24836
+ found.push(...fileSettingDeclarations(root2, schema2.items, [...path3, "[]"], followed));
24400
24837
  }
24401
24838
  return found;
24402
24839
  }
24403
24840
  var MEDIA_TYPE = /^[^/\s]+\/[^/\s]+$/;
24404
24841
  function where2(identifier, path3) {
24405
- return [identifier, ...path3].join(".");
24842
+ return settingPath(identifier, ...path3);
24406
24843
  }
24407
24844
  function fileSettingDeclarationErrors(identifier, settingsSchema) {
24408
24845
  const errors = [];
@@ -24433,12 +24870,17 @@ function fileSettingDeclarationErrors(identifier, settingsSchema) {
24433
24870
  }
24434
24871
  for (const [key, property] of Object.entries(settingsSchema.properties ?? {})) {
24435
24872
  if (typeof property !== "object" || !("default" in property)) continue;
24436
- for (const { path: path3, value } of fileSettingValues(property, property.default, [key])) {
24873
+ for (const { path: path3, value } of fileSettingValues(
24874
+ property,
24875
+ property.default,
24876
+ [],
24877
+ settingsSchema
24878
+ )) {
24437
24879
  if (typeof value !== "string" || value === "" || value.startsWith("shared:")) {
24438
24880
  continue;
24439
24881
  }
24440
24882
  errors.push(
24441
- `Settings "${identifier}" property "${path3.join(".")}" holds a file and defaults to ${JSON.stringify(value)}. A default resolves with no scenario active, so it must be empty for no file or a \`shared:\` reference`
24883
+ `Settings "${identifier}" property "${settingPath(key, ...path3)}" holds a file and defaults to ${JSON.stringify(value)}. A default resolves with no scenario active, so it must be empty for no file or a \`shared:\` reference`
24442
24884
  );
24443
24885
  }
24444
24886
  }
@@ -24466,13 +24908,13 @@ async function packageFileSettingErrors(owner, settings, schemas, resolve12, ski
24466
24908
  }
24467
24909
  return errors;
24468
24910
  }
24469
- async function fileSettingWriteErrors(overrides, schemas, describeBlob, options = {}) {
24911
+ async function fileSettingWriteErrors(overrides, schemas, describeBlob2, options = {}) {
24470
24912
  const errors = [];
24471
24913
  for (const [identifier, value] of Object.entries(overrides)) {
24472
24914
  for (const file of fileSettingValues(schemas[identifier], value)) {
24473
24915
  if (typeof file.value !== "string" || !file.value.startsWith("blob:")) continue;
24474
24916
  const setting = `Setting ${where2(identifier, file.path)}`;
24475
- const found = await describeBlob(file.value);
24917
+ const found = await describeBlob2(file.value);
24476
24918
  if (!found) {
24477
24919
  errors.push(
24478
24920
  `${setting} names ${file.value}, which is not a stored blob. Upload the file first and use the reference it returns`
@@ -24547,13 +24989,13 @@ async function updateSharedContext(host, command) {
24547
24989
  const declared = new Set(
24548
24990
  surface && "writes" in surface.definition ? surface.definition.writes ?? [] : []
24549
24991
  );
24550
- const named2 = [...Object.keys(command.payload), ...(command.deletes ?? []).map(deleteHead)];
24992
+ const named3 = [...Object.keys(command.payload), ...(command.deletes ?? []).map(deleteHead)];
24551
24993
  const declaredByPackage = new Set(
24552
24994
  (executor.getConfig()?.capabilities ?? []).map(
24553
24995
  (capability) => capability.definition.identifier
24554
24996
  )
24555
24997
  );
24556
- for (const capability of named2) {
24998
+ for (const capability of named3) {
24557
24999
  if (!shared.has(capability)) {
24558
25000
  if (declaredByPackage.has(capability)) {
24559
25001
  throw new DeniedError(
@@ -24650,11 +25092,11 @@ function refuseUndeclaredTeamWrite(host, uiIdentifier, payload, deletes) {
24650
25092
  const capabilities = new Set(
24651
25093
  (host.executor.getConfig()?.capabilities ?? []).map((cap) => cap.definition.identifier)
24652
25094
  );
24653
- const named2 = [
25095
+ const named3 = [
24654
25096
  ...Object.keys(payload),
24655
25097
  ...(deletes ?? []).map((path3) => (typeof path3 === "string" ? path3.split(".") : path3)[0])
24656
25098
  ];
24657
- for (const key of named2) {
25099
+ for (const key of named3) {
24658
25100
  if (key === void 0 || !capabilities.has(key)) {
24659
25101
  throw new DeniedError(
24660
25102
  `"${key}" is not a capability of this game, so "${uiIdentifier}" cannot write it`
@@ -25229,19 +25671,11 @@ var Session = class {
25229
25671
  applyPendingChanges: () => this.applyPendingChanges(),
25230
25672
  clearBlobs: (retentions) => this.clearBlobs(retentions),
25231
25673
  describeBlob: async (reference) => {
25232
- try {
25233
- const blob = await readBlob(
25234
- this.options.packagePath,
25235
- reference.slice("blob:".length)
25236
- );
25237
- return {
25238
- mimeType: blob.mimeType,
25239
- size: blob.data.length,
25240
- retention: blob.retention
25241
- };
25242
- } catch {
25243
- return void 0;
25244
- }
25674
+ const blob = await describeBlob(
25675
+ this.options.packagePath,
25676
+ reference.slice("blob:".length)
25677
+ );
25678
+ return blob && { mimeType: blob.mimeType, size: blob.size, retention: blob.retention };
25245
25679
  },
25246
25680
  enqueue: (work) => this.enqueue(work),
25247
25681
  apply: (command) => this.apply(command),
@@ -26073,11 +26507,11 @@ var Session = class {
26073
26507
  if (scenarioId !== null && !this.declaredScenarioIds().has(scenarioId)) {
26074
26508
  throw new DeniedError(`This package declares no scenario "${scenarioId}" to edit`);
26075
26509
  }
26510
+ const scenario = this.executor.getConfig()?.scenarios?.find((entry) => entry.definition.identifier === scenarioId);
26076
26511
  return {
26077
26512
  settings: this.scenarioDraft(scenarioId) ?? this.executor.resolveScenarioDraft(scenarioId, null),
26078
- scenarioName: this.executor.scenarioNameOf(
26079
- this.executor.getConfig()?.scenarios?.find((scenario) => scenario.definition.identifier === scenarioId)
26080
- )
26513
+ scenarioName: this.executor.scenarioNameOf(scenario),
26514
+ scenarioRoot: scenario?.rootDirectory ?? null
26081
26515
  };
26082
26516
  }
26083
26517
  /**
@@ -26774,6 +27208,7 @@ import { dirname as dirname6, resolve as resolve7 } from "path";
26774
27208
  import { existsSync as existsSync9 } from "fs";
26775
27209
  import { readFile as readFile6 } from "fs/promises";
26776
27210
  var SCENARIO_VALIDATION = "scenario-validation";
27211
+ var SCENARIO_FILES = "scenario-files";
26777
27212
  function hasScenarioGate(config) {
26778
27213
  return (config.validators ?? []).some((v) => v.definition.gates?.includes("scenario"));
26779
27214
  }
@@ -26786,6 +27221,7 @@ async function runScenarioGates(options) {
26786
27221
  });
26787
27222
  const resolved = resolveSettingsLayers(config, options.scenarioSettings, null);
26788
27223
  const locale = options.locale ?? config.game?.definition.supportedLocales?.[0] ?? "en";
27224
+ const readsFiles = (config.requires ?? []).includes(SCENARIO_FILES);
26789
27225
  const problems = [];
26790
27226
  for (const validator of config.validators ?? []) {
26791
27227
  if (!validator.definition.gates?.includes("scenario")) continue;
@@ -26812,7 +27248,11 @@ async function runScenarioGates(options) {
26812
27248
  const found = await withBound(
26813
27249
  gate({
26814
27250
  settings: structuredClone(pick(resolved)),
26815
- locale
27251
+ locale,
27252
+ callbacks: readsFiles ? scenarioCallbacks(
27253
+ options.packagePath,
27254
+ options.files ?? { scenarioRoot: null, blobs: "none" }
27255
+ ) : withoutScenarioFiles(identifier)
26816
27256
  }),
26817
27257
  options.boundMs ?? DEFAULT_LOGIC_EXECUTION_BOUND_MS
26818
27258
  );
@@ -26835,6 +27275,40 @@ async function runScenarioGates(options) {
26835
27275
  }
26836
27276
  return problems;
26837
27277
  }
27278
+ function scenarioCallbacks(packagePath, files) {
27279
+ const unreadable = async (reference) => {
27280
+ if (!reference.startsWith("blob:") || files.blobs === "all") return false;
27281
+ if (files.blobs === "none") return true;
27282
+ const blob = await describeBlob(packagePath, reference.slice("blob:".length));
27283
+ return blob !== void 0 && blob.retention !== "scenario";
27284
+ };
27285
+ return {
27286
+ readAsset: async (reference) => {
27287
+ if (await unreadable(reference)) {
27288
+ throw new Error(`Cannot read "${reference}": the scenario cannot name that file`);
27289
+ }
27290
+ const described = await describeAssetByReference(
27291
+ packagePath,
27292
+ files.scenarioRoot,
27293
+ reference
27294
+ );
27295
+ if (described && described.size > SCENARIO_GATE_READ_LIMIT_BYTES) {
27296
+ throw new ScenarioAssetTooLargeError(reference, described.size);
27297
+ }
27298
+ const asset = await readAssetByReference(packagePath, files.scenarioRoot, reference);
27299
+ return { data: new Uint8Array(asset.data), mimeType: asset.mimeType, name: asset.name };
27300
+ },
27301
+ describeAsset: async (reference) => await unreadable(reference) ? void 0 : describeAssetByReference(packagePath, files.scenarioRoot, reference)
27302
+ };
27303
+ }
27304
+ function withoutScenarioFiles(identifier) {
27305
+ const refuse = (callback) => async () => {
27306
+ throw new Error(
27307
+ `Validator "${identifier}" called ${callback} in its Scenario gate, which needs the "${SCENARIO_FILES}" feature, but requires does not list it. Add "${SCENARIO_FILES}" to requires in seriousgaming.sdk.json.`
27308
+ );
27309
+ };
27310
+ return { readAsset: refuse("readAsset"), describeAsset: refuse("describeAsset") };
27311
+ }
26838
27312
  async function withBound(run, boundMs) {
26839
27313
  let timer;
26840
27314
  try {
@@ -27051,26 +27525,28 @@ function typesOf2(schema2) {
27051
27525
  return schema2.type ? [schema2.type] : [];
27052
27526
  }
27053
27527
  function propertyAt(path3, context) {
27054
- const [identifier, ...keys] = path3.split(".");
27055
- if (!identifier || keys.length === 0) {
27528
+ const parsed = parseSettingPath(path3);
27529
+ if (!parsed || parsed.keys.length === 0) {
27056
27530
  return {
27057
27531
  error: `"${path3}" should be a settings identifier and a property, e.g. engine.weeks`
27058
27532
  };
27059
27533
  }
27534
+ const { identifier, keys } = parsed;
27060
27535
  if (!context.declared.includes(identifier)) {
27061
27536
  return {
27062
27537
  error: `"${path3}" reads settings "${identifier}", which the guide does not list in its settings`
27063
27538
  };
27064
27539
  }
27065
- let schema2 = context.schemas[identifier];
27540
+ const root2 = context.schemas[identifier];
27541
+ let schema2 = root2;
27066
27542
  for (const key of keys) {
27067
- const properties = typeof schema2 === "object" ? schema2.properties : void 0;
27543
+ const properties = typeof schema2 === "object" && root2 ? dereference(root2, schema2).properties : void 0;
27068
27544
  schema2 = properties?.[key];
27069
- if (typeof schema2 !== "object") {
27545
+ if (typeof schema2 !== "object" || !root2) {
27070
27546
  return { error: `"${path3}" names no property of settings "${identifier}"` };
27071
27547
  }
27072
27548
  }
27073
- return { schema: schema2 };
27549
+ return { schema: root2 ? dereference(root2, schema2) : schema2 };
27074
27550
  }
27075
27551
  function literalError(path3, literal, schema2) {
27076
27552
  const types = typesOf2(schema2);
@@ -27136,7 +27612,8 @@ function validateGuideSettings(chapters, context) {
27136
27612
  );
27137
27613
  continue;
27138
27614
  }
27139
- used.add(reference.path.split(".")[0]);
27615
+ const identifier = parseSettingPath(reference.path)?.identifier;
27616
+ if (identifier !== void 0) used.add(identifier);
27140
27617
  const property = propertyAt(reference.path, context);
27141
27618
  if ("error" in property) {
27142
27619
  errors.push(`${where3}: ${directive2} ${property.error}`);
@@ -27869,8 +28346,8 @@ function endpointSchemaErrors(endpoint) {
27869
28346
  `Endpoint "${identifier}" requestSchema ${path3 || "(root)"} declares \`blob\` but is not \`"type": "string"\`. A file field is a URI string: a blob: reference or a data: URI`
27870
28347
  );
27871
28348
  }
27872
- for (const [key, child] of Object.entries(node2.properties ?? {})) {
27873
- visit2(child, `${path3}/${key}`);
28349
+ for (const { step, schema: child } of memberDeclarations(node2)) {
28350
+ visit2(child, `${path3}/${step}`);
27874
28351
  }
27875
28352
  if (node2.items && !Array.isArray(node2.items)) visit2(node2.items, `${path3}/items`);
27876
28353
  };
@@ -27978,7 +28455,7 @@ function validateCapabilityScopes(game, engines, config) {
27978
28455
  }
27979
28456
  if (!isSharedState) {
27980
28457
  const referenced = /* @__PURE__ */ new Map();
27981
- const collect2 = (label4, definition3) => {
28458
+ const collect = (label4, definition3) => {
27982
28459
  for (const capabilityId of [
27983
28460
  ...definition3.reads ?? [],
27984
28461
  ...definition3.writes ?? []
@@ -27989,10 +28466,10 @@ function validateCapabilityScopes(game, engines, config) {
27989
28466
  }
27990
28467
  };
27991
28468
  for (const engine of engines) {
27992
- collect2("engine", engine.definition);
28469
+ collect("engine", engine.definition);
27993
28470
  }
27994
28471
  if (config.ui) {
27995
- collect2("user interface", config.ui.definition);
28472
+ collect("user interface", config.ui.definition);
27996
28473
  }
27997
28474
  for (const [capId, referencedBy] of referenced) {
27998
28475
  errors.push(
@@ -28380,16 +28857,16 @@ function validateSchemaDefaults(label4, definition3) {
28380
28857
  function descriptor(entry) {
28381
28858
  return entry;
28382
28859
  }
28383
- var named = (resource) => resource.definition.identifier;
28860
+ var named2 = (resource) => resource.definition.identifier;
28384
28861
  var writesOf = (resource) => resource.definition.writes ?? [];
28385
28862
  function slot(resource) {
28386
28863
  return resource ? [resource] : [];
28387
28864
  }
28388
28865
  function packageFiles(packagePath, scenarioRoot) {
28389
28866
  return async (reference) => {
28867
+ if (!reference.startsWith("shared:") && !reference.startsWith("asset:")) return void 0;
28390
28868
  try {
28391
- const asset = reference.startsWith("shared:") ? await resolveSharedAsset(packagePath, reference.slice("shared:".length)) : reference.startsWith("asset:") && scenarioRoot !== null ? await resolveAsset(scenarioRoot, reference.slice("asset:".length)) : void 0;
28392
- return asset && { mimeType: asset.mimeType, size: asset.data.length };
28869
+ return await describeAssetByReference(packagePath, scenarioRoot, reference);
28393
28870
  } catch {
28394
28871
  return void 0;
28395
28872
  }
@@ -28404,6 +28881,19 @@ function schemaDefaults2(type) {
28404
28881
  )
28405
28882
  });
28406
28883
  }
28884
+ function localRefs(type) {
28885
+ const label4 = getResourceMeta(type).label;
28886
+ const keyword = type === "capability" ? "variablesSchema" : "settingsSchema";
28887
+ return (resource) => {
28888
+ const schema2 = resource.definition[keyword];
28889
+ if (schema2 === null || typeof schema2 !== "object") return { errors: [] };
28890
+ return {
28891
+ errors: refProblems(schema2).map(
28892
+ (problem) => refProblemMessage(`${label4} "${resource.definition.identifier}"`, keyword, problem)
28893
+ )
28894
+ };
28895
+ };
28896
+ }
28407
28897
  function readsWritten(type) {
28408
28898
  const label4 = getResourceMeta(type).label;
28409
28899
  return (resource, context) => {
@@ -28454,12 +28944,13 @@ var VALIDATION_DESCRIPTORS = [
28454
28944
  descriptor({
28455
28945
  type: "capability",
28456
28946
  resources: (config) => config.capabilities ?? [],
28457
- identify: named,
28947
+ identify: named2,
28458
28948
  checks: [
28459
28949
  (capability, context) => ({
28460
28950
  errors: validateTsTypes([capability], context.workingDir)
28461
28951
  }),
28462
- schemaDefaults2("capability")
28952
+ schemaDefaults2("capability"),
28953
+ localRefs("capability")
28463
28954
  ]
28464
28955
  }),
28465
28956
  // The built-in `game` resource's defaults are the manifest's own values,
@@ -28469,9 +28960,16 @@ var VALIDATION_DESCRIPTORS = [
28469
28960
  resources: (config) => (config.settings ?? []).filter(
28470
28961
  (settings) => settings.definition.identifier !== GAME_SETTINGS
28471
28962
  ),
28472
- identify: named,
28963
+ identify: named2,
28473
28964
  checks: [
28474
28965
  schemaDefaults2("settings"),
28966
+ localRefs("settings"),
28967
+ // A lock inside a list's items or a map's entries keeps nothing (§6.1a).
28968
+ (settings) => ({
28969
+ errors: unenforceableLocks(settings.definition.settingsSchema).map(
28970
+ (lock) => unenforceableLockMessage(settings.definition.identifier, lock)
28971
+ )
28972
+ }),
28475
28973
  // What a file setting expects, and the files its defaults name (§6.1a).
28476
28974
  (settings) => ({
28477
28975
  errors: fileSettingDeclarationErrors(
@@ -28502,7 +29000,7 @@ var VALIDATION_DESCRIPTORS = [
28502
29000
  descriptor({
28503
29001
  type: "engine",
28504
29002
  resources: (config) => slot(config.engine),
28505
- identify: named,
29003
+ identify: named2,
28506
29004
  writer: writesOf,
28507
29005
  checks: [
28508
29006
  (engine, context) => validateEngine(engine, context.config),
@@ -28514,7 +29012,7 @@ var VALIDATION_DESCRIPTORS = [
28514
29012
  descriptor({
28515
29013
  type: "ui",
28516
29014
  resources: (config) => slot(config.ui),
28517
- identify: named,
29015
+ identify: named2,
28518
29016
  writer: writesOf,
28519
29017
  checks: [userInterfaceReferences, uiFiles, schemaDefaults2("ui"), readsWritten("ui")]
28520
29018
  }),
@@ -28522,19 +29020,19 @@ var VALIDATION_DESCRIPTORS = [
28522
29020
  descriptor({
28523
29021
  type: "setup",
28524
29022
  resources: (config) => slot(config.setup),
28525
- identify: named,
29023
+ identify: named2,
28526
29024
  checks: [uiFiles]
28527
29025
  }),
28528
29026
  descriptor({
28529
29027
  type: "scenario_editor",
28530
29028
  resources: (config) => slot(config.scenario_editor),
28531
- identify: named,
29029
+ identify: named2,
28532
29030
  checks: [uiFiles]
28533
29031
  }),
28534
29032
  descriptor({
28535
29033
  type: "tick_controller",
28536
29034
  resources: (config) => slot(config.tick_controller),
28537
- identify: named,
29035
+ identify: named2,
28538
29036
  checks: [
28539
29037
  (tc, context) => validateTickController(tc, context.config),
28540
29038
  schemaDefaults2("tick_controller"),
@@ -28544,7 +29042,7 @@ var VALIDATION_DESCRIPTORS = [
28544
29042
  descriptor({
28545
29043
  type: "hook",
28546
29044
  resources: (config) => config.hooks ?? [],
28547
- identify: named,
29045
+ identify: named2,
28548
29046
  writer: writesOf,
28549
29047
  checks: [
28550
29048
  (hook, context) => validateHook(hook, context.config),
@@ -28555,7 +29053,7 @@ var VALIDATION_DESCRIPTORS = [
28555
29053
  descriptor({
28556
29054
  type: "validator",
28557
29055
  resources: (config) => config.validators ?? [],
28558
- identify: named,
29056
+ identify: named2,
28559
29057
  checks: [
28560
29058
  (validator, context) => validateValidator(validator, context.config),
28561
29059
  schemaDefaults2("validator"),
@@ -28565,7 +29063,7 @@ var VALIDATION_DESCRIPTORS = [
28565
29063
  descriptor({
28566
29064
  type: "endpoint",
28567
29065
  resources: (config) => config.endpoints ?? [],
28568
- identify: named,
29066
+ identify: named2,
28569
29067
  checks: [
28570
29068
  (endpoint, context) => validateEndpoint(endpoint, context.config),
28571
29069
  (endpoint, context) => validateEndpointFiles(endpoint, context.workingDir),
@@ -28576,7 +29074,7 @@ var VALIDATION_DESCRIPTORS = [
28576
29074
  descriptor({
28577
29075
  type: "session",
28578
29076
  resources: (config) => slot(config.session),
28579
- identify: named,
29077
+ identify: named2,
28580
29078
  writer: writesOf,
28581
29079
  checks: [
28582
29080
  userInterfaceReferences,
@@ -28588,7 +29086,7 @@ var VALIDATION_DESCRIPTORS = [
28588
29086
  descriptor({
28589
29087
  type: "waiting_room",
28590
29088
  resources: (config) => slot(config.waiting_room),
28591
- identify: named,
29089
+ identify: named2,
28592
29090
  checks: [
28593
29091
  userInterfaceReferences,
28594
29092
  uiFiles,
@@ -28599,7 +29097,7 @@ var VALIDATION_DESCRIPTORS = [
28599
29097
  descriptor({
28600
29098
  type: "presentation",
28601
29099
  resources: (config) => slot(config.presentation),
28602
- identify: named,
29100
+ identify: named2,
28603
29101
  checks: [userInterfaceReferences, uiFiles]
28604
29102
  }),
28605
29103
  // Composition, settings, locales and roles. A game wires whatever its
@@ -28608,7 +29106,7 @@ var VALIDATION_DESCRIPTORS = [
28608
29106
  descriptor({
28609
29107
  type: "game",
28610
29108
  resources: (config) => slot(config.game),
28611
- identify: named,
29109
+ identify: named2,
28612
29110
  checks: [
28613
29111
  (game, context) => validateGame(game, context.config),
28614
29112
  // With no default, a session can run on no scenario at all, so the
@@ -28665,7 +29163,7 @@ var VALIDATION_DESCRIPTORS = [
28665
29163
  descriptor({
28666
29164
  type: "scenario",
28667
29165
  resources: (config) => config.scenarios ?? [],
28668
- identify: named,
29166
+ identify: named2,
28669
29167
  checks: [
28670
29168
  // The same check `ConfigResolver.assertLayeredSettingsValid` runs at
28671
29169
  // session start (#371). Without it the build was green on a
@@ -28710,11 +29208,17 @@ var VALIDATION_DESCRIPTORS = [
28710
29208
  // (§15.8).
28711
29209
  async (scenario, context) => {
28712
29210
  const identifier = scenario.definition.identifier;
29211
+ const packagePath = dirname6(context.configPath);
28713
29212
  return scenarioRefusals(
28714
29213
  await runScenarioGates({
28715
- packagePath: dirname6(context.configPath),
29214
+ packagePath,
28716
29215
  config: context.config,
28717
29216
  loader: context.logicLoader,
29217
+ // Its files as the package ships them (§15.8).
29218
+ files: {
29219
+ scenarioRoot: resolve7(packagePath, scenario.rootDirectory),
29220
+ blobs: "none"
29221
+ },
28718
29222
  scenarioSettings: scenario.definition.settings ?? {}
28719
29223
  }),
28720
29224
  `Scenario "${identifier}"`,
@@ -28729,7 +29233,7 @@ var VALIDATION_DESCRIPTORS = [
28729
29233
  descriptor({
28730
29234
  type: "guide",
28731
29235
  resources: (config) => slot(config.guide),
28732
- identify: named,
29236
+ identify: named2,
28733
29237
  checks: [
28734
29238
  (guide, context) => validateFacilitatorGuideContent({
28735
29239
  definition: guide.definition,
@@ -28767,7 +29271,7 @@ async function validateLoadedPackage(config, options) {
28767
29271
  configPath: options.configPath,
28768
29272
  workingDir: options.workingDir,
28769
29273
  writtenInPackage,
28770
- capabilityIds: new Set((config.capabilities ?? []).map(named)),
29274
+ capabilityIds: new Set((config.capabilities ?? []).map(named2)),
28771
29275
  logicLoader: new LogicLoader(dirname6(options.configPath), {
28772
29276
  transpile: Transpile,
28773
29277
  fs: { existsSync: existsSync13, readFile: readFile7 }
@@ -29305,6 +29809,32 @@ async function watchPackage(packagePath, onChange, debounceMs = 150) {
29305
29809
  };
29306
29810
  }
29307
29811
 
29812
+ // cli/dev/public-origins.ts
29813
+ function publicAssetOrigin(origins, assetPort) {
29814
+ if (origins.publicAssetUrl) return origins.publicAssetUrl;
29815
+ if (!origins.publicUrl) return null;
29816
+ const url = new URL(origins.publicUrl);
29817
+ return `${url.protocol}//${url.hostname}:${assetPort}`;
29818
+ }
29819
+ function publicHmrOrigin(origins, assetPort, vitePort) {
29820
+ if (origins.publicHmrUrl) return origins.publicHmrUrl;
29821
+ const asset = publicAssetOrigin(origins, assetPort);
29822
+ if (!asset) return null;
29823
+ const url = new URL(asset);
29824
+ return `${url.protocol === "https:" ? "wss" : "ws"}://${url.hostname}:${vitePort}`;
29825
+ }
29826
+ function hmrClientTarget(origin) {
29827
+ const url = new URL(origin);
29828
+ const protocol = url.protocol === "wss:" ? "wss" : "ws";
29829
+ const clientPort = url.port ? Number(url.port) : protocol === "wss" ? 443 : 80;
29830
+ return { protocol, host: url.hostname, clientPort };
29831
+ }
29832
+ function publicHostnames(origins) {
29833
+ return [
29834
+ ...new Set(origins.filter((o) => Boolean(o)).map((o) => new URL(o).hostname))
29835
+ ];
29836
+ }
29837
+
29308
29838
  // cli/dev/routes.ts
29309
29839
  import { existsSync as existsSync19 } from "fs";
29310
29840
  import { readFile as readFile10 } from "fs/promises";
@@ -29599,7 +30129,14 @@ async function saveSessionScenario(session, packagePath, request) {
29599
30129
  packagePath,
29600
30130
  config,
29601
30131
  scenarioSettings: settings,
29602
- locale: projection.session.locale
30132
+ locale: projection.session.locale,
30133
+ // Its files as a session on it would find them: a draft's in the
30134
+ // scenario it was opened on and the blobs it can read, the
30135
+ // session's in its scenario and every blob it holds (§6.12, §15.8).
30136
+ files: {
30137
+ scenarioRoot: source?.rootDirectory ?? null,
30138
+ blobs: request.draft === true ? "draft" : "all"
30139
+ }
29603
30140
  });
29604
30141
  if (problems.length > 0) {
29605
30142
  throw new SaveScenarioError("denied", describeScenarioProblems(problems).join("\n"));
@@ -29722,10 +30259,11 @@ function themeMessages(theme) {
29722
30259
  { type: "themePreferenceChanged", preference: theme.preference }
29723
30260
  ];
29724
30261
  }
29725
- function assetUrls(assetOrigin) {
30262
+ function assetUrls(assetOrigin, editing) {
30263
+ const scenarioAssets = editing === void 0 ? "scenario/" : editing.scenario === null ? "no-scenario/" : `scenarios/${encodeURIComponent(editing.scenario)}/`;
29726
30264
  return {
29727
30265
  blobPrefix: `${assetOrigin}/assets/blobs/`,
29728
- scenarioAssetPrefix: `${assetOrigin}/assets/scenario/`,
30266
+ scenarioAssetPrefix: `${assetOrigin}/assets/${scenarioAssets}`,
29729
30267
  sharedAssetPrefix: `${assetOrigin}/assets/shared/`,
29730
30268
  assetAuthRedeemUrl: `${assetOrigin}/assets/auth/redeem`
29731
30269
  };
@@ -29751,7 +30289,13 @@ function buildBatch(options) {
29751
30289
  const { surface, state: state2, theme, origin, assetOrigin } = options;
29752
30290
  const common = [
29753
30291
  { type: "setLocale", payload: { locale: state2.session.locale } },
29754
- { type: "setAssetUrls", payload: assetUrls(assetOrigin ?? origin) },
30292
+ {
30293
+ type: "setAssetUrls",
30294
+ payload: assetUrls(
30295
+ assetOrigin ?? origin,
30296
+ surface.kind === "scenario-editor" ? { scenario: options.viewer.scenario ?? null } : void 0
30297
+ )
30298
+ },
29755
30299
  ...theme ? themeMessages(theme) : []
29756
30300
  ];
29757
30301
  switch (surface.kind) {
@@ -30210,12 +30754,16 @@ var ASSET_PATHS = {
30210
30754
  "/api": {
30211
30755
  blob: "/api/blobs/:blobId",
30212
30756
  scenario: "/api/scenario/assets/*path",
30757
+ editedScenario: "/api/scenarios/:scenario/assets/*path",
30758
+ noScenario: "/api/no-scenario/assets/*path",
30213
30759
  shared: "/api/shared/assets/*path",
30214
30760
  redeem: "/api/asset-auth/redeem"
30215
30761
  },
30216
30762
  "/assets": {
30217
30763
  blob: "/assets/blobs/:blobId",
30218
30764
  scenario: "/assets/scenario/*path",
30765
+ editedScenario: "/assets/scenarios/:scenario/*path",
30766
+ noScenario: "/assets/no-scenario/*path",
30219
30767
  shared: "/assets/shared/*path",
30220
30768
  redeem: "/assets/auth/redeem"
30221
30769
  }
@@ -30233,15 +30781,17 @@ function registerAssetRoutes(app, deps, prefix) {
30233
30781
  res.json({ ok: true });
30234
30782
  });
30235
30783
  app.get(paths.blob, async (req, res) => {
30784
+ let blob;
30236
30785
  try {
30237
- const blob = await readBlob(packagePath, req.params.blobId);
30238
- res.setHeader("Content-Type", blob.mimeType);
30239
- res.setHeader("X-Asset-Name", encodeURIComponent(blob.name));
30240
- res.setHeader("Access-Control-Expose-Headers", "X-Asset-Name");
30241
- res.send(blob.data);
30786
+ blob = await readBlob(packagePath, req.params.blobId);
30242
30787
  } catch {
30243
30788
  res.status(404).send("Blob not found");
30789
+ return;
30244
30790
  }
30791
+ res.setHeader("Content-Type", blob.mimeType);
30792
+ res.setHeader("X-Asset-Name", encodeURIComponent(blob.name));
30793
+ res.setHeader("Access-Control-Expose-Headers", "X-Asset-Name");
30794
+ sendBytes(req, res, blob.data);
30245
30795
  });
30246
30796
  app.get(paths.scenario, (req, res) => {
30247
30797
  const scenario = session.activeScenario();
@@ -30249,9 +30799,23 @@ function registerAssetRoutes(app, deps, prefix) {
30249
30799
  res.status(404).send("No active scenario");
30250
30800
  return;
30251
30801
  }
30252
- const root2 = isAbsolute11(scenario.rootDirectory) ? scenario.rootDirectory : resolve11(packagePath, scenario.rootDirectory);
30253
- serveAsset(req, res, resolve11(root2, "assets"));
30802
+ serveAsset(req, res, scenarioAssets(scenario));
30254
30803
  });
30804
+ app.get(paths.editedScenario, (req, res) => {
30805
+ const scenario = session.packageConfiguration()?.scenarios?.find((entry) => entry.definition.identifier === req.params.scenario);
30806
+ if (!scenario) {
30807
+ res.status(404).send("No such scenario");
30808
+ return;
30809
+ }
30810
+ serveAsset(req, res, scenarioAssets(scenario));
30811
+ });
30812
+ app.get(paths.noScenario, (_req, res) => {
30813
+ res.status(404).send("No scenario is being edited");
30814
+ });
30815
+ function scenarioAssets(scenario) {
30816
+ const root2 = isAbsolute11(scenario.rootDirectory) ? scenario.rootDirectory : resolve11(packagePath, scenario.rootDirectory);
30817
+ return resolve11(root2, "assets");
30818
+ }
30255
30819
  app.get(paths.shared, (req, res) => {
30256
30820
  serveAsset(req, res, resolve11(packagePath, "shared-assets"));
30257
30821
  });
@@ -30282,10 +30846,27 @@ function serveAsset(req, res, root2) {
30282
30846
  res.status(404).send("Asset not found");
30283
30847
  return;
30284
30848
  }
30849
+ res.setHeader("Content-Type", mediaTypeOf(resolved));
30285
30850
  res.setHeader("X-Asset-Name", encodeURIComponent(assetPath.split("/").pop() ?? assetPath));
30286
30851
  res.setHeader("Access-Control-Expose-Headers", "X-Asset-Name");
30287
30852
  res.sendFile(normalize3(assetPath), { root: root2 });
30288
30853
  }
30854
+ function sendBytes(req, res, data) {
30855
+ res.setHeader("Accept-Ranges", "bytes");
30856
+ const ranges = req.headers.range === void 0 ? void 0 : req.range(data.length);
30857
+ if (ranges === -1) {
30858
+ res.status(416).setHeader("Content-Range", `bytes */${data.length}`);
30859
+ res.end();
30860
+ return;
30861
+ }
30862
+ if (Array.isArray(ranges) && ranges.type === "bytes" && ranges.length === 1) {
30863
+ const [{ start, end }] = ranges;
30864
+ res.status(206).setHeader("Content-Range", `bytes ${start}-${end}/${data.length}`);
30865
+ res.send(data.subarray(start, end + 1));
30866
+ return;
30867
+ }
30868
+ res.send(data);
30869
+ }
30289
30870
 
30290
30871
  // cli/dev/view/commands.ts
30291
30872
  var FRAME_COMMANDS = {
@@ -30751,6 +31332,8 @@ var DevShell = class {
30751
31332
  viteFailure = null;
30752
31333
  /** Serialises the first requests for a surface so they share one Vite. */
30753
31334
  viteStarting = null;
31335
+ /** The hot-reload socket's own listener, when a public origin moves its client. */
31336
+ hmrServer = null;
30754
31337
  port;
30755
31338
  vitePort;
30756
31339
  assetPort;
@@ -30849,7 +31432,7 @@ var DevShell = class {
30849
31432
  await this.viteStarting;
30850
31433
  await this.vite?.close();
30851
31434
  await Promise.all(
30852
- [this.server, this.assetServer].map(
31435
+ [this.server, this.assetServer, this.hmrServer].map(
30853
31436
  (server) => new Promise((resolve12) => {
30854
31437
  if (!server) return resolve12();
30855
31438
  server.close(() => resolve12());
@@ -30970,18 +31553,37 @@ var DevShell = class {
30970
31553
  get assetUrl() {
30971
31554
  return `http://localhost:${this.assetPort}`;
30972
31555
  }
31556
+ /** Where people reach the console, when a proxy stands in front of it. */
31557
+ get publicUrl() {
31558
+ return this.options.publicUrl ?? null;
31559
+ }
31560
+ /** Where people's browsers load bundles from, when a proxy stands in front. */
31561
+ get publicAssetUrl() {
31562
+ return publicAssetOrigin(this.options, this.assetPort);
31563
+ }
30973
31564
  /**
30974
- * The asset origin as a client that reached `host` must name it: the same
30975
- * host, the asset port. A browser on another machine reached us by an
30976
- * address `localhost` would not resolve to on its side.
31565
+ * The asset origin as a client that reached `host` must name it: the
31566
+ * public one where given, else the same host on the asset port. A browser
31567
+ * on another machine reached us by an address `localhost` would not
31568
+ * resolve to on its side.
30977
31569
  */
30978
31570
  assetOrigin(host) {
31571
+ const configured = this.publicAssetUrl;
31572
+ if (configured) return configured;
30979
31573
  const name = (host ?? "localhost").replace(/:\d+$/, "") || "localhost";
30980
31574
  return `http://${name}:${this.assetPort}`;
30981
31575
  }
30982
31576
  /** The console's own origin, as a client that reached `host` names it. */
30983
31577
  consoleOrigin(host) {
30984
- return host ? `http://${host}` : this.url;
31578
+ return this.options.publicUrl ?? (host ? `http://${host}` : this.url);
31579
+ }
31580
+ /** Where a frame's hot-reload client connects, when a public origin decides it. */
31581
+ get publicHmrUrl() {
31582
+ return publicHmrOrigin(this.options, this.assetPort, this.vitePort);
31583
+ }
31584
+ /** What the bundle policy's `connect-src` admits for hot reload. */
31585
+ hmrSources(host) {
31586
+ return this.publicHmrUrl ?? hmrConnectSources(host, this.vitePort);
30985
31587
  }
30986
31588
  /** The session this shell wraps, for tests and for the CLI in-process path. */
30987
31589
  get runtime() {
@@ -31112,7 +31714,7 @@ ${MISSING_CONSOLE_MESSAGE}
31112
31714
  */
31113
31715
  configureAssets() {
31114
31716
  this.assetApp.use((req, res, next) => {
31115
- applyBundlePolicy(res, req.headers.host, this.vitePort);
31717
+ applyBundlePolicy(res, this.hmrSources(req.headers.host));
31116
31718
  next();
31117
31719
  });
31118
31720
  registerAssetRoutes(
@@ -31171,6 +31773,7 @@ Install the package's dependencies to serve its surfaces.
31171
31773
  return this.viteStarting;
31172
31774
  }
31173
31775
  async createVite() {
31776
+ const server = await this.viteServerOptions();
31174
31777
  return createViteServer({
31175
31778
  root: this.options.packagePath,
31176
31779
  appType: "custom",
@@ -31193,10 +31796,43 @@ Install the package's dependencies to serve its surfaces.
31193
31796
  workingDir: this.options.packagePath
31194
31797
  })
31195
31798
  ],
31196
- server: { middlewareMode: true, hmr: { port: this.vitePort, ...this.bindHost } },
31799
+ server,
31197
31800
  logLevel: "error"
31198
31801
  });
31199
31802
  }
31803
+ /**
31804
+ * Vite's server options: its own hot-reload socket on the Vite port, as
31805
+ * before, unless a public origin says where the client connects.
31806
+ *
31807
+ * Vite takes one `host` for both where its socket listens and where its
31808
+ * client connects, and a public hostname is no address to listen on. So
31809
+ * behind a proxy the socket's listener is opened here, on the Vite port
31810
+ * as usual, and Vite only attaches to it.
31811
+ */
31812
+ async viteServerOptions() {
31813
+ const hmr = this.publicHmrUrl;
31814
+ if (!hmr) {
31815
+ return { middlewareMode: true, hmr: { port: this.vitePort, ...this.bindHost } };
31816
+ }
31817
+ const listener = createServer((_req, res) => {
31818
+ res.writeHead(426, { "Content-Type": "text/plain" }).end("Upgrade Required");
31819
+ });
31820
+ await new Promise((resolve12, reject) => {
31821
+ listener.once("error", reject);
31822
+ listener.listen(this.vitePort, this.bindHost.host, () => {
31823
+ listener.off("error", reject);
31824
+ resolve12();
31825
+ });
31826
+ });
31827
+ this.hmrServer = listener;
31828
+ return {
31829
+ middlewareMode: true,
31830
+ ws: { server: listener, ...hmrClientTarget(hmr) },
31831
+ // Vite refuses a request whose `Host` it does not recognise, and a
31832
+ // proxy that passes its own on would otherwise be refused it.
31833
+ allowedHosts: publicHostnames([this.options.publicUrl, this.publicAssetUrl, hmr])
31834
+ };
31835
+ }
31200
31836
  // -----------------------------------------------------------------------
31201
31837
  // WebSocket
31202
31838
  // -----------------------------------------------------------------------
@@ -31516,8 +32152,7 @@ function send(socket, message) {
31516
32152
  if (socket.readyState !== 1) return;
31517
32153
  socket.send(JSON.stringify(message));
31518
32154
  }
31519
- function applyBundlePolicy(res, host, vitePort) {
31520
- const hmr = hmrConnectSources(host, vitePort);
32155
+ function applyBundlePolicy(res, hmr) {
31521
32156
  res.setHeader(
31522
32157
  "Content-Security-Policy",
31523
32158
  [