@vgai/engine 0.5.16 → 0.5.18

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 (109) hide show
  1. package/dist/adapter/adapter-module.d.ts +1 -16
  2. package/dist/adapter/adapter-module.d.ts.map +1 -1
  3. package/dist/adapter/adapter-module.js +1 -11
  4. package/dist/adapter/finders/scenes-from-entrypoint-selection.d.ts +0 -2
  5. package/dist/adapter/finders/scenes-from-entrypoint-selection.d.ts.map +1 -1
  6. package/dist/adapter/finders/scenes-from-entrypoint-selection.js +3 -6
  7. package/dist/adapter/renderer-config.d.ts +83 -0
  8. package/dist/adapter/renderer-config.d.ts.map +1 -0
  9. package/dist/adapter/renderer-config.js +121 -0
  10. package/dist/adapter/root-adapter.d.ts +6 -2
  11. package/dist/adapter/root-adapter.d.ts.map +1 -1
  12. package/dist/adapter/root-seam-contract.d.ts +5 -0
  13. package/dist/adapter/root-seam-contract.d.ts.map +1 -1
  14. package/dist/adapter/root-seam-contract.js +1 -0
  15. package/dist/adapter/setup-three-root-adapter.js +9 -9
  16. package/dist/canvas-react/pixi-react-adapter.d.ts.map +1 -1
  17. package/dist/canvas-react/pixi-react-adapter.js +92 -41
  18. package/dist/data/curve.d.ts +1 -1
  19. package/dist/data/curve.js +2 -2
  20. package/dist/dev/instruments.d.ts +4 -4
  21. package/dist/dev/instruments.js +4 -4
  22. package/dist/dev/register-render-vitals.d.ts +2 -2
  23. package/dist/dev/register-render-vitals.js +2 -2
  24. package/dist/dev/static-batch-advisor.d.ts +1 -1
  25. package/dist/dev/static-batch-advisor.js +2 -2
  26. package/dist/input/input-manager.d.ts +15 -0
  27. package/dist/input/input-manager.d.ts.map +1 -1
  28. package/dist/input/input-manager.js +22 -0
  29. package/dist/manifest/load.d.ts +0 -3
  30. package/dist/manifest/load.d.ts.map +1 -1
  31. package/dist/manifest/load.js +0 -4
  32. package/dist/manifest/schema.d.ts +0 -2
  33. package/dist/manifest/schema.d.ts.map +1 -1
  34. package/dist/manifest/schema.js +3 -24
  35. package/dist/pixi/authoring.d.ts +33 -0
  36. package/dist/pixi/authoring.d.ts.map +1 -1
  37. package/dist/pixi/authoring.js +86 -6
  38. package/dist/react/world-state.d.ts +12 -0
  39. package/dist/react/world-state.d.ts.map +1 -1
  40. package/dist/react/world-state.js +14 -0
  41. package/dist/render/soft-particle-depth.d.ts +3 -3
  42. package/dist/render/soft-particle-depth.d.ts.map +1 -1
  43. package/dist/render/soft-particle-depth.js +8 -13
  44. package/dist/runtime/create-runtime.d.ts +2 -16
  45. package/dist/runtime/create-runtime.d.ts.map +1 -1
  46. package/dist/runtime/create-runtime.js +36 -38
  47. package/dist/runtime/dev-build.d.ts +37 -0
  48. package/dist/runtime/dev-build.d.ts.map +1 -0
  49. package/dist/runtime/dev-build.js +49 -0
  50. package/dist/runtime/game.d.ts +9 -1
  51. package/dist/runtime/game.d.ts.map +1 -1
  52. package/dist/runtime/game.js +25 -1
  53. package/dist/runtime/mount-manifest.d.ts +0 -13
  54. package/dist/runtime/mount-manifest.d.ts.map +1 -1
  55. package/dist/runtime/mount-manifest.js +2 -21
  56. package/dist/world3d-react/engine-bridge.d.ts.map +1 -1
  57. package/dist/world3d-react/engine-bridge.js +28 -3
  58. package/dist/world3d-react/index.d.ts +2 -2
  59. package/dist/world3d-react/index.d.ts.map +1 -1
  60. package/dist/world3d-react/index.js +2 -2
  61. package/dist/world3d-react/r3f-adapter.d.ts +2 -2
  62. package/dist/world3d-react/r3f-adapter.d.ts.map +1 -1
  63. package/dist/world3d-react/r3f-adapter.js +90 -15
  64. package/dist/world3d-react/r3f-root-factory.d.ts.map +1 -1
  65. package/dist/world3d-react/r3f-root-factory.js +12 -2
  66. package/dist/world3d-react/rapier-physics-bridge.d.ts +4 -4
  67. package/dist/world3d-react/rapier-physics-bridge.js +3 -3
  68. package/dist/world3d-react/renderer-config.d.ts +7 -69
  69. package/dist/world3d-react/renderer-config.d.ts.map +1 -1
  70. package/dist/world3d-react/renderer-config.js +7 -108
  71. package/dist/world3d-react/world-context.d.ts +43 -0
  72. package/dist/world3d-react/world-context.d.ts.map +1 -1
  73. package/dist/world3d-react/world-context.js +89 -46
  74. package/dist-config/config.js.map +1 -1
  75. package/package.json +1 -1
  76. package/schemas/engine-capabilities.json +3 -3
  77. package/schemas/vgai-project.schema.json +2 -7
  78. package/src/adapter/adapter-module.ts +1 -25
  79. package/src/adapter/finders/scenes-from-entrypoint-selection.ts +3 -8
  80. package/src/adapter/renderer-config.ts +178 -0
  81. package/src/adapter/root-adapter.ts +6 -2
  82. package/src/adapter/root-seam-contract.ts +1 -0
  83. package/src/adapter/setup-three-root-adapter.ts +9 -9
  84. package/src/canvas-react/pixi-react-adapter.tsx +98 -53
  85. package/src/data/curve.ts +2 -2
  86. package/src/dev/instruments.ts +4 -4
  87. package/src/dev/register-render-vitals.ts +2 -2
  88. package/src/dev/static-batch-advisor.ts +2 -2
  89. package/src/input/input-manager.ts +23 -0
  90. package/src/manifest/load.ts +0 -7
  91. package/src/manifest/schema.ts +3 -26
  92. package/src/pixi/authoring.ts +98 -6
  93. package/src/react/world-state.tsx +15 -0
  94. package/src/render/soft-particle-depth.ts +8 -13
  95. package/src/runtime/create-runtime.ts +38 -52
  96. package/src/runtime/dev-build.ts +49 -0
  97. package/src/runtime/game.ts +31 -2
  98. package/src/runtime/mount-manifest.ts +2 -33
  99. package/src/world3d-react/engine-bridge.ts +28 -3
  100. package/src/world3d-react/index.ts +5 -5
  101. package/src/world3d-react/r3f-adapter.tsx +89 -20
  102. package/src/world3d-react/r3f-root-factory.tsx +12 -2
  103. package/src/world3d-react/rapier-physics-bridge.tsx +4 -4
  104. package/src/world3d-react/renderer-config.ts +7 -164
  105. package/src/world3d-react/world-context.ts +100 -51
  106. package/dist/runtime/dev-layers.d.ts +0 -34
  107. package/dist/runtime/dev-layers.d.ts.map +0 -1
  108. package/dist/runtime/dev-layers.js +0 -46
  109. package/src/runtime/dev-layers.ts +0 -46
@@ -1,111 +1,10 @@
1
1
  /**
2
- * world3d-react/renderer-config.tsthe seam a WORLD uses to state how its own frame is rendered.
2
+ * `@engine/world3d-react/renderer-config` — a published entry point.
3
3
  *
4
- * The host owns the `WebGLRenderer` (`ThreeHostContext.renderer`) and configures it with this
5
- * engine's defaults: ACES tone mapping, sRGB output, PCF-soft shadows. Those defaults are right for
6
- * a world authored against them and WRONG for a world that was authored against a different
7
- * engine's pipeline an imported Godot 3 GLES2 game does gamma-space lighting with no tonemapper
8
- * at all, so ACES quietly desaturates and darkens every colour its author picked.
9
- *
10
- * So a world may DECLARE the pipeline it was authored for, and `createR3FAdapter` applies it to the
11
- * host's renderer for the life of the mount, restoring what it found on dispose. Three properties
12
- * of that shape are load-bearing:
13
- *
14
- * - **It is per-renderer, never engine-wide.** Every field here is a `WebGLRenderer` instance
15
- * property, and a play root gets its own renderer (`create-runtime.ts`). Nothing here reaches a
16
- * module-level three global, so one world's declaration cannot change how the editor's own
17
- * viewport, another root, or a thumbnail bake renders.
18
- * - **Absent means "leave the host's value alone".** Every field is optional and an omitted one
19
- * is never written, so declaring a tone mapping does not silently reset the clear colour.
20
- * - **It is restored on dispose.** The renderer outlives the mount, so a world that did not put
21
- * back what it found would leak its pipeline into whatever mounts next.
22
- *
23
- * This is deliberately NOT a general render-settings system. It carries what a world can honestly
24
- * state about its own colour pipeline and nothing else; a property the host fixes at CONSTRUCTION
25
- * (the WebGL context's `antialias` attribute, and therefore the MSAA sample count) cannot be
26
- * declared here, because there would be no honest moment to apply it.
27
- */
28
- /**
29
- * Apply `config` to `renderer`, returning the restore function that puts back what was there.
30
- *
31
- * `three` is passed in rather than imported for values so the enum constants come from the HOST's
32
- * three instance — the same identity rule `r3f-adapter.tsx` follows for the scene and camera.
4
+ * The engine package's export map is the wildcard `"./*"`, so every file under
5
+ * `packages/engine/src/` is an entry point a game outside this repo can import by path. The module
6
+ * itself now lives in the adapter seam (`@engine/adapter/renderer-config`, which its header
7
+ * explains), and this file keeps the path that shipped resolving to it. Import the seam path in
8
+ * new code.
33
9
  */
34
- export function applyWorldRendererConfig(three, renderer, config) {
35
- // A host that mounts a world WITHOUT rasterizing it hands the adapter a duck-typed renderer —
36
- // the editor's design session (`createDesignTimeRenderer`: four members, deliberately never
37
- // widened) and jsdom test harnesses both do. Such a surface has no colour pipeline to configure:
38
- // the frame the user sees is drawn by a DIFFERENT renderer (the editor's own), so applying the
39
- // world's config there is meaningless — and calling `getClearColor` on it is a TypeError that
40
- // unmounts the whole world at edit time (measured: every Godot port's edit viewport blanked with
41
- // '"world" failed to mount — renderer.getClearColor is not a function'). Detect the real
42
- // `WebGLRenderer` surface by the one method this function must call, and no-op otherwise.
43
- if (typeof renderer.getClearColor !== 'function') {
44
- return () => { };
45
- }
46
- const toneMappings = {
47
- none: three.NoToneMapping,
48
- linear: three.LinearToneMapping,
49
- reinhard: three.ReinhardToneMapping,
50
- cineon: three.CineonToneMapping,
51
- aces: three.ACESFilmicToneMapping,
52
- agx: three.AgXToneMapping,
53
- neutral: three.NeutralToneMapping,
54
- };
55
- const colorSpaces = {
56
- srgb: three.SRGBColorSpace,
57
- 'srgb-linear': three.LinearSRGBColorSpace,
58
- };
59
- const shadowMapTypes = {
60
- basic: three.BasicShadowMap,
61
- pcf: three.PCFShadowMap,
62
- 'pcf-soft': three.PCFSoftShadowMap,
63
- vsm: three.VSMShadowMap,
64
- };
65
- const restores = [];
66
- if (config.toneMapping !== undefined) {
67
- const previous = renderer.toneMapping;
68
- renderer.toneMapping = toneMappings[config.toneMapping];
69
- restores.push(() => {
70
- renderer.toneMapping = previous;
71
- });
72
- }
73
- if (config.toneMappingExposure !== undefined) {
74
- const previous = renderer.toneMappingExposure;
75
- renderer.toneMappingExposure = config.toneMappingExposure;
76
- restores.push(() => {
77
- renderer.toneMappingExposure = previous;
78
- });
79
- }
80
- if (config.outputColorSpace !== undefined) {
81
- const previous = renderer.outputColorSpace;
82
- renderer.outputColorSpace = colorSpaces[config.outputColorSpace];
83
- restores.push(() => {
84
- renderer.outputColorSpace = previous;
85
- });
86
- }
87
- if (config.shadowMapType !== undefined && renderer.shadowMap !== undefined) {
88
- const previous = renderer.shadowMap.type;
89
- renderer.shadowMap.type = shadowMapTypes[config.shadowMapType];
90
- renderer.shadowMap.needsUpdate = true;
91
- restores.push(() => {
92
- renderer.shadowMap.type = previous;
93
- renderer.shadowMap.needsUpdate = true;
94
- });
95
- }
96
- if (config.clearColor !== undefined) {
97
- const previousColor = new three.Color();
98
- renderer.getClearColor(previousColor);
99
- // Alpha is READ BACK and re-passed, never assumed: see `clearColor`'s doc above.
100
- const alpha = renderer.getClearAlpha();
101
- renderer.setClearColor(new three.Color(config.clearColor), alpha);
102
- restores.push(() => {
103
- renderer.setClearColor(previousColor, alpha);
104
- });
105
- }
106
- return () => {
107
- // Reverse order, so a field written twice (it cannot be, today) unwinds correctly.
108
- for (let i = restores.length - 1; i >= 0; i--)
109
- restores[i]?.();
110
- };
111
- }
10
+ export * from '../adapter/renderer-config';
@@ -128,6 +128,49 @@ export interface R3FRootRuntime {
128
128
  * react-door registrations are untouched when a Game hosts this world). */
129
129
  dispose(): void;
130
130
  }
131
+ /**
132
+ * The GAME-SCOPED input wiring one three root owns — and the half that has
133
+ * nothing to do with the vgai runtime context.
134
+ *
135
+ * Two things happen here, both of them HOST work performed from outside the
136
+ * world's own tree:
137
+ *
138
+ * 1. the project's input map is loaded through `Game.loadInputMap` (game-owned,
139
+ * load-once), so the actions the project declared exist;
140
+ * 2. this root's seams are registered on the game-scoped debug registry
141
+ * (`setVirtualInputTarget`/`setInputActionsSource`/`setInputTraceSource`),
142
+ * which is what makes `game.input.hold/tap/...` (the bot/`vgai eval` input
143
+ * doctrine) and the built-in `input.actions`/`input.trace` providers
144
+ * resolve to this world instead of throwing `DEBUG_INPUT_UNAVAILABLE`.
145
+ *
146
+ * It is called on BOTH three-root paths, and that is the point: a world that
147
+ * mounts as a default-exported component receives no vgai runtime context
148
+ * (`engineRuntime: false` — see `r3f-root-factory.tsx`), but "no context in the
149
+ * tree" was never meant to say "the host does not wire this game's input". It
150
+ * was read that way, and the cost was measured on a fresh scaffold: the
151
+ * declared map never loaded and every `game.input.*` door threw, so the QA
152
+ * bot, autoplay routes and `vgai eval` could not drive the ONE world shape
153
+ * `vgai create` produces. Same split, same reasoning, as `WorldProvider`
154
+ * riding `host.game` rather than the runtime (see `r3f-adapter.tsx`).
155
+ *
156
+ * `optionalInputMap` is the CONVENTIONAL-PATH probe used when the project
157
+ * never named a map: an absent file is the ordinary state of a brand-new
158
+ * project, so it resolves quietly instead of printing an error on every boot.
159
+ * A map that exists and fails to parse is as loud as ever.
160
+ *
161
+ * LIFETIME, honestly: `registry.strip(id)` runs on the mount's dispose (both
162
+ * paths), but it walks providers/commands only — the three seams set here
163
+ * survive it, keyed by this world's id, until a remount of the same id
164
+ * overwrites them. That residue is inert rather than hidden: every closure
165
+ * below reads GAME-scoped state (`game.input`, `game.loop.fixedDt`, the game's
166
+ * seed), so a stale entry actuates exactly what a live one would. See the
167
+ * dispose comment in `r3f-adapter.tsx` for the full accounting.
168
+ */
169
+ export declare function wireGameInputSeams(host: ThreeHostContext, registry: DebugRegistry, options: {
170
+ readonly id: string;
171
+ readonly inputMapPath?: string | null | undefined;
172
+ readonly optionalInputMap?: boolean | undefined;
173
+ }): Promise<void>;
131
174
  /**
132
175
  * Build the engine runtime for one R3F world from a `ThreeHostContext` — the same
133
176
  * wiring, at the same layer, as the classic `SetupThreeRootAdapter.mount()`
@@ -1 +1 @@
1
- {"version":3,"file":"world-context.d.ts","sourceRoot":"","sources":["../../src/world3d-react/world-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAmCK;AAEL,OAAO,KAAK,KAAK,KAAK,MAAM,OAAO,CAAC;AACpC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAOhE,OAAO,EAAE,kBAAkB,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xD;;mFAE+E;IAC/E,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IACxC;;;;;;yDAMqD;IACrD,QAAQ,CAAC,aAAa,EAAE,aAAa,CAAC;IACtC;qEACiE;IACjE,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC;;;4DAGwD;IACxD,cAAc,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC;IAC/D;;gFAE4E;IAC5E,OAAO,IAAI,IAAI,CAAC;CACjB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,gBAAgB,EACtB,QAAQ,EAAE,aAAa,EACvB,OAAO,EAAE;IACP,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAClD,QAAQ,CAAC,gBAAgB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;CACjD,GACA,OAAO,CAAC,IAAI,CAAC,CAiDf;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,gBAAgB,EACtB,OAAO,EAAE,qBAAqB,GAC7B,cAAc,CAqGhB"}
@@ -43,6 +43,92 @@ import { disposeDebrisSubtree } from '../runtime/game';
43
43
  /** The classic adapter's default input-map path — the conventional location
44
44
  * every scaffolded project ships (`public/inputmaps/default.inputmap.json`). */
45
45
  export const DEFAULT_INPUT_MAP_PATH = '/inputmaps/default.inputmap.json';
46
+ /**
47
+ * The GAME-SCOPED input wiring one three root owns — and the half that has
48
+ * nothing to do with the vgai runtime context.
49
+ *
50
+ * Two things happen here, both of them HOST work performed from outside the
51
+ * world's own tree:
52
+ *
53
+ * 1. the project's input map is loaded through `Game.loadInputMap` (game-owned,
54
+ * load-once), so the actions the project declared exist;
55
+ * 2. this root's seams are registered on the game-scoped debug registry
56
+ * (`setVirtualInputTarget`/`setInputActionsSource`/`setInputTraceSource`),
57
+ * which is what makes `game.input.hold/tap/...` (the bot/`vgai eval` input
58
+ * doctrine) and the built-in `input.actions`/`input.trace` providers
59
+ * resolve to this world instead of throwing `DEBUG_INPUT_UNAVAILABLE`.
60
+ *
61
+ * It is called on BOTH three-root paths, and that is the point: a world that
62
+ * mounts as a default-exported component receives no vgai runtime context
63
+ * (`engineRuntime: false` — see `r3f-root-factory.tsx`), but "no context in the
64
+ * tree" was never meant to say "the host does not wire this game's input". It
65
+ * was read that way, and the cost was measured on a fresh scaffold: the
66
+ * declared map never loaded and every `game.input.*` door threw, so the QA
67
+ * bot, autoplay routes and `vgai eval` could not drive the ONE world shape
68
+ * `vgai create` produces. Same split, same reasoning, as `WorldProvider`
69
+ * riding `host.game` rather than the runtime (see `r3f-adapter.tsx`).
70
+ *
71
+ * `optionalInputMap` is the CONVENTIONAL-PATH probe used when the project
72
+ * never named a map: an absent file is the ordinary state of a brand-new
73
+ * project, so it resolves quietly instead of printing an error on every boot.
74
+ * A map that exists and fails to parse is as loud as ever.
75
+ *
76
+ * LIFETIME, honestly: `registry.strip(id)` runs on the mount's dispose (both
77
+ * paths), but it walks providers/commands only — the three seams set here
78
+ * survive it, keyed by this world's id, until a remount of the same id
79
+ * overwrites them. That residue is inert rather than hidden: every closure
80
+ * below reads GAME-scoped state (`game.input`, `game.loop.fixedDt`, the game's
81
+ * seed), so a stale entry actuates exactly what a live one would. See the
82
+ * dispose comment in `r3f-adapter.tsx` for the full accounting.
83
+ */
84
+ export function wireGameInputSeams(host, registry, options) {
85
+ const { id, inputMapPath = DEFAULT_INPUT_MAP_PATH, optionalInputMap = false } = options;
86
+ if (!host.game)
87
+ return Promise.resolve();
88
+ const game = host.game;
89
+ const input = game.input;
90
+ registry.setInputActionsSource(id, () => input.actionNames().map((name) => ({ name, valueType: input.getActionValueType(name) })));
91
+ registry.setInputTraceSource(id, () => {
92
+ const raw = input.getInputTrace();
93
+ return {
94
+ version: raw.version,
95
+ seed: getSeededRandom(game)?.seed ?? null,
96
+ fixedDt: game.loop.fixedDt,
97
+ ticks: raw.ticks,
98
+ };
99
+ });
100
+ registry.setVirtualInputTarget(id, {
101
+ setVirtualAction: (action, value) => input.setVirtualAction(action, value),
102
+ tapVirtualAction: (action) => input.tapVirtualAction(action),
103
+ clearVirtualActions: () => input.clearVirtualActions(),
104
+ scheduleActionAtTick: (tick, action, value) => input.scheduleActionAtTick(tick, action, value),
105
+ startInputRecording: () => input.startInputRecording(),
106
+ stopInputRecording: () => input.stopInputRecording(),
107
+ isInputRecording: () => input.isInputRecording(),
108
+ injectAxis: (sourceId, value) => input.injectAxis(sourceId, value),
109
+ injectVector2: (sourceId, value) => input.injectVector2(sourceId, value),
110
+ injectPointerDelta: (sourceId, delta) => input.injectPointerDelta(sourceId, delta),
111
+ injectPointerPosition: (sourceId, value) => input.injectPointerPosition(sourceId, value),
112
+ });
113
+ if (host.headless || inputMapPath === null)
114
+ return Promise.resolve();
115
+ // Load-once through the game-owned path (competing paths across roots throw
116
+ // THERE, loudly). A FAILED load (missing/bad file) must not fail the mount:
117
+ // a three world with no declared actions is legal. It degrades loudly
118
+ // instead — naming exactly what breaks.
119
+ // The non-optional call passes ONE argument, exactly as it always has — a
120
+ // trailing `undefined` is a different call to any observer of it.
121
+ const load = optionalInputMap
122
+ ? game.loadInputMap(inputMapPath, { optional: true })
123
+ : game.loadInputMap(inputMapPath);
124
+ return load.catch((err) => {
125
+ // biome-ignore lint/suspicious/noConsole: deliberate loud degrade — the documented alternative to failing the mount (see comment above)
126
+ console.error(`three world "${id}": failed to load input map "${inputMapPath}" — declared input ` +
127
+ 'actions and `game.input.*` (bot/virtual input) will not work until a valid map ' +
128
+ 'loads. Ship one at the conventional path or pass `inputMapPath` to ' +
129
+ `createR3FAdapter (null to opt out). Cause: ${err instanceof Error ? err.message : String(err)}`);
130
+ });
131
+ }
46
132
  /**
47
133
  * Build the engine runtime for one R3F world from a `ThreeHostContext` — the same
48
134
  * wiring, at the same layer, as the classic `SetupThreeRootAdapter.mount()`
@@ -101,52 +187,9 @@ export function createR3FRootContext(host, options) {
101
187
  const gameClock = host.game ? getSimClock(host.game) : null;
102
188
  const clock = gameClock ?? createSimClock({ dispose: (obj) => disposeDebrisSubtree(obj, []) });
103
189
  ctx.clock = clock;
104
- // --- ctx.input + the debug-registry input seams (gap 3) — the game-owned
105
- // InputManager, polled by the game-scoped runner each frame; this world
106
- // registers the SAME per-world seams the classic adapter registers so
107
- // `game.input.*` (virtual input) and the built-in `input.actions`/
108
- // `input.trace` providers resolve to it. ---
109
- let inputMapReady = Promise.resolve();
110
- if (host.game) {
111
- const game = host.game;
112
- const input = game.input;
113
- debugRegistry.setInputActionsSource(id, () => input.actionNames().map((name) => ({ name, valueType: input.getActionValueType(name) })));
114
- debugRegistry.setInputTraceSource(id, () => {
115
- const raw = input.getInputTrace();
116
- return {
117
- version: raw.version,
118
- seed: getSeededRandom(game)?.seed ?? null,
119
- fixedDt: game.loop.fixedDt,
120
- ticks: raw.ticks,
121
- };
122
- });
123
- debugRegistry.setVirtualInputTarget(id, {
124
- setVirtualAction: (action, value) => input.setVirtualAction(action, value),
125
- tapVirtualAction: (action) => input.tapVirtualAction(action),
126
- clearVirtualActions: () => input.clearVirtualActions(),
127
- scheduleActionAtTick: (tick, action, value) => input.scheduleActionAtTick(tick, action, value),
128
- startInputRecording: () => input.startInputRecording(),
129
- stopInputRecording: () => input.stopInputRecording(),
130
- isInputRecording: () => input.isInputRecording(),
131
- injectAxis: (sourceId, value) => input.injectAxis(sourceId, value),
132
- injectVector2: (sourceId, value) => input.injectVector2(sourceId, value),
133
- injectPointerDelta: (sourceId, delta) => input.injectPointerDelta(sourceId, delta),
134
- injectPointerPosition: (sourceId, value) => input.injectPointerPosition(sourceId, value),
135
- });
136
- if (!host.headless && inputMapPath !== null) {
137
- // Load-once through the game-owned path (classic parity — competing
138
- // paths across roots throw THERE, loudly). A FAILED load (missing/bad
139
- // file) must not fail this mount: an R3F tree with no declared actions
140
- // is legal. It degrades loudly instead — naming exactly what breaks.
141
- inputMapReady = game.loadInputMap(inputMapPath).catch((err) => {
142
- // biome-ignore lint/suspicious/noConsole: deliberate loud degrade — the documented alternative to failing the mount (see comment above)
143
- console.error(`R3F world "${id}": failed to load input map "${inputMapPath}" — declared input ` +
144
- 'actions and `game.input.*` (bot/virtual input) will not work until a valid map ' +
145
- 'loads. Ship one at the conventional path or pass `inputMapPath` to ' +
146
- `createR3FAdapter (null to opt out). Cause: ${err instanceof Error ? err.message : String(err)}`);
147
- });
148
- }
149
- }
190
+ // --- ctx.input + the debug-registry input seams (gap 3) — see
191
+ // `wireGameInputSeams` below; `ctx.input` is that same game-owned manager. ---
192
+ const inputMapReady = wireGameInputSeams(host, debugRegistry, { id, inputMapPath });
150
193
  return {
151
194
  ctx,
152
195
  systems,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/data/curve.ts", "../src/data/data-ref.ts", "../src/data/data-check-core.ts", "../src/data/data-asset.ts", "../src/data/vite-plugin-data.ts"],
4
- "sourcesContent": ["/**\n * Curve FIELDS in data assets \u2014 a response curve a designer shapes, living\n * inside an ordinary `.data.json` like any other tunable value.\n *\n * A curve is a FIELD TYPE, never a file type: there is no `.curve.json`, no\n * curve asset class, no baked LUT, and no document. `curve(axes)` is a real\n * Zod schema you drop into a `*.schema.ts` beside `z.number()`, so the value\n * lives in the same data file, hot-swaps through the same `defineData` handle,\n * and is edited by the same Data panel that edits everything else.\n *\n * The JSON a designer (or an agent) reads and writes:\n *\n * ```json\n * { \"interpolation\": \"smooth\",\n * \"points\": [{ \"x\": 0, \"y\": 1 }, { \"x\": 12, \"y\": 0.85 }, { \"x\": 30, \"y\": 0.2 }] }\n * ```\n *\n * TWO MODES, NO TANGENTS. `linear` and `smooth`, and nothing else. Per-key\n * tangent handles would double the JSON, make it unreadable to an agent, and\n * hand every author a way to make a curve overshoot its own points. Smoothness\n * is DERIVED instead \u2014 Fritsch\u2013Carlson monotone cubic tangents, computed from\n * the points themselves \u2014 so the interpolant is guaranteed to stay inside each\n * segment's `[yLeft, yRight]` band. \"Shape it by moving points\" is the whole\n * authoring model.\n *\n * RUNG AUDIT (recorded decision, 2026-08-14): no npm dependency. The candidate\n * packages (`monotone-cubic-spline` and its siblings) are unmaintained\n * micro-packages, and d3's `curveMonotoneX` is an SVG PATH GENERATOR \u2014 it\n * draws, it does not sample `y` at an `x`. What we need is ~40 lines of\n * well-known numerics with no API surface, so it is written here.\n *\n * `sampleCurve` is the entire runtime: a pure function, no class, no cache\n * object, no \"curve system\". Game code calls it every frame from its own\n * update, the same way it reads any other tuning value.\n */\n\nimport { z } from 'zod';\n\n/** One authored key: a `y` value at an `x` position. No tangents \u2014 see above. */\nexport interface CurvePoint {\n x: number;\n y: number;\n}\n\n/** A curve field's value, exactly as it sits in the `.data.json`. */\nexport interface CurveValue {\n interpolation: 'linear' | 'smooth';\n points: CurvePoint[];\n}\n\n/**\n * The curve's DOMAIN, declared by the engineer in the schema (never by the\n * data): what the axes mean and how far they run. The editor draws its rails\n * from this and clamps every drag to it; the schema rejects a point outside\n * it.\n */\nexport interface CurveAxes {\n x: { min: number; max: number; label?: string };\n y: { min: number; max: number; label?: string };\n}\n\n/** How the marker rides out to the emitted JSON Schema \u2014 the editor's and the dev menu's detection key, the exact shape `dataRef` uses with `x-vgai-ref`. */\nconst CURVE_META_KEY = 'x-vgai-curve';\n\nfunction axisLabel(axes: CurveAxes, axis: 'x' | 'y'): string {\n return axes[axis].label ?? axis;\n}\n\n/** Every out-of-domain / ordering problem in one pass, as teaching issues (`parseDataJson`'s \"errors teach\" doctrine, \u00A76.5). */\nfunction checkPoints(value: CurveValue, axes: CurveAxes, ctx: z.RefinementCtx): void {\n const points = value.points;\n for (let i = 0; i < points.length; i++) {\n const point = points[i] as CurvePoint;\n for (const axis of ['x', 'y'] as const) {\n const { min, max } = axes[axis];\n if (point[axis] < min || point[axis] > max) {\n ctx.addIssue({\n code: 'custom',\n path: ['points', i, axis],\n message:\n `${point[axis]} is outside this curve's ${axisLabel(axes, axis)} domain ` +\n `[${min}, ${max}] \u2014 move the point inside the domain, or widen the axis in the ` +\n `schema (curve({ ${axis}: { min, max } })).`,\n });\n }\n }\n if (i === 0) continue;\n const previous = points[i - 1] as CurvePoint;\n if (point.x <= previous.x) {\n ctx.addIssue({\n code: 'custom',\n path: ['points', i, 'x'],\n message:\n `${point.x} must be strictly greater than the previous point's x (${previous.x}) \u2014 ` +\n 'curve points run left to right along x, with no duplicate x. Sort the points, or ' +\n 'nudge this one.',\n });\n }\n }\n}\n\n/**\n * A Zod schema for a data-asset FIELD holding a response curve. Use it in a\n * `.schema.ts` exactly like any other field:\n *\n * ```ts\n * export const TuningSchema = z.object({\n * spawnRate: z.number().min(0).max(10).default(1),\n * difficultyRamp: curve({\n * x: { min: 0, max: 300, label: 'Sim time (s)' },\n * y: { min: 0, max: 2, label: 'Spawn multiplier' },\n * }).describe('How hard the game leans on the player as the round runs.'),\n * });\n * ```\n *\n * The schema is STRICT (an unrecognized key is an error, never a silent\n * strip), demands at least two points, and enforces strictly-increasing `x`\n * with every point inside the declared axes \u2014 each with a message that names\n * the fix rather than the rule.\n *\n * The emitted JSON Schema (`toDataJsonSchema`) carries\n * `\"x-vgai-curve\": axes` \u2014 a Zod `.meta()`, which survives `z.toJSONSchema`\n * including inside a table's `additionalProperties` row schema, exactly the\n * way `dataRef`'s `\"x-vgai-ref\"` does. That marker is what makes the editor's\n * Data panel render a curve EDITOR instead of a raw-JSON cell, with no emitter\n * changes anywhere.\n */\nexport function curve(axes: CurveAxes): z.ZodType<CurveValue> {\n const point = z.strictObject({\n x: z.number().describe(`Position along ${axisLabel(axes, 'x')}.`),\n y: z.number().describe(`Value at that position, along ${axisLabel(axes, 'y')}.`),\n });\n return z\n .strictObject({\n interpolation: z\n .enum(['linear', 'smooth'])\n .describe(\n 'How the value moves between points: \"linear\" for straight segments, ' +\n '\"smooth\" for a monotone cubic that never overshoots them.',\n ),\n points: z\n .array(point)\n .min(2, {\n message:\n 'a curve needs at least two points \u2014 add another { \"x\": \u2026, \"y\": \u2026 } so the ' +\n 'value has somewhere to travel between.',\n })\n .describe('Keys in increasing x order; the value is clamped outside the first/last x.'),\n })\n .superRefine((value, ctx) => checkPoints(value, axes, ctx))\n .meta({ [CURVE_META_KEY]: axes }) as unknown as z.ZodType<CurveValue>;\n}\n\n/**\n * Read a curve field's declared axes back off a LIVE Zod schema (as opposed to\n * the emitted JSON Schema, which the editor's Data panel reads instead).\n *\n * This is the dev-menu capability's detection door: it derives its rows by\n * walking the game's own `TuningSchema` object, so it needs the axes from the\n * schema in hand. Wrappers (`.optional()`, `.default(\u2026)`, `.describe(\u2026)` chains\n * that re-wrap) hide the metadata behind an inner type, so a bounded unwrap\n * walks down to it.\n */\nexport function curveAxesOf(schema: z.ZodType): CurveAxes | undefined {\n let current: unknown = schema;\n for (let depth = 0; depth < 5 && current; depth++) {\n const meta = (current as z.ZodType).meta?.() as Record<string, unknown> | undefined;\n const axes = meta?.[CURVE_META_KEY];\n if (axes && typeof axes === 'object' && 'x' in axes && 'y' in axes) return axes as CurveAxes;\n current = (current as { def?: { innerType?: unknown } }).def?.innerType;\n }\n return undefined;\n}\n\n/**\n * Fritsch\u2013Carlson tangents: the ordinary cubic-Hermite slopes, then limited so\n * the interpolant cannot overshoot the data. This is what makes \"smooth\" safe\n * to hand a designer \u2014 a curve that dips below its own points would silently\n * feed the game a value nobody authored.\n */\nfunction monotoneTangents(points: readonly CurvePoint[]): number[] {\n const n = points.length;\n const secants: number[] = [];\n for (let i = 0; i < n - 1; i++) {\n const left = points[i] as CurvePoint;\n const right = points[i + 1] as CurvePoint;\n secants.push((right.y - left.y) / (right.x - left.x));\n }\n const tangents: number[] = [secants[0] as number];\n for (let i = 1; i < n - 1; i++) {\n tangents.push(((secants[i - 1] as number) + (secants[i] as number)) / 2);\n }\n tangents.push(secants[n - 2] as number);\n\n for (let i = 0; i < n - 1; i++) {\n const secant = secants[i] as number;\n if (secant === 0) {\n // A flat segment must stay flat: any slope at either end would bulge.\n tangents[i] = 0;\n tangents[i + 1] = 0;\n continue;\n }\n let alpha = (tangents[i] as number) / secant;\n let beta = (tangents[i + 1] as number) / secant;\n // A tangent fighting the segment's own direction is a local extremum the\n // data does not have.\n if (alpha < 0) {\n tangents[i] = 0;\n alpha = 0;\n }\n if (beta < 0) {\n tangents[i + 1] = 0;\n beta = 0;\n }\n const radius = alpha * alpha + beta * beta;\n if (radius > 9) {\n const scale = 3 / Math.sqrt(radius);\n tangents[i] = scale * alpha * secant;\n tangents[i + 1] = scale * beta * secant;\n }\n }\n return tangents;\n}\n\n/**\n * The curve's value at `x` \u2014 the whole runtime API.\n *\n * Read it every frame from the game's own update, the way every other data\n * value is read (`tuning.get()` then sample); never precompute a table, and\n * never hold the result across frames \u2014 an edit to the `.data.json` hot-swaps\n * underneath you and that is the point.\n *\n * Outside `[first.x, last.x]` the value CLAMPS to the nearest endpoint: a\n * curve declares what it knows about, and extrapolating past it would invent\n * numbers nobody authored.\n */\nexport function sampleCurve(value: CurveValue, x: number): number {\n const points = value.points;\n if (points.length === 0) return 0;\n const first = points[0] as CurvePoint;\n const last = points[points.length - 1] as CurvePoint;\n if (points.length === 1 || x <= first.x) return first.y;\n if (x >= last.x) return last.y;\n\n let i = 0;\n while (i < points.length - 2 && x >= (points[i + 1] as CurvePoint).x) i++;\n const left = points[i] as CurvePoint;\n const right = points[i + 1] as CurvePoint;\n const span = right.x - left.x;\n if (span <= 0) return left.y; // duplicate x \u2014 the schema rejects it; a hand-built value might not\n const t = (x - left.x) / span;\n if (value.interpolation === 'linear') return left.y + (right.y - left.y) * t;\n\n const tangents = monotoneTangents(points);\n const t2 = t * t;\n const t3 = t2 * t;\n return (\n (2 * t3 - 3 * t2 + 1) * left.y +\n (t3 - 2 * t2 + t) * span * (tangents[i] as number) +\n (-2 * t3 + 3 * t2) * right.y +\n (t3 - t2) * span * (tangents[i + 1] as number)\n );\n}\n", "/**\n * `file#key` refs \u2014 the resolvable half.\n *\n * Cross-asset references (`\"enemies#goblin\"`, `\"tuning#economy.slotGrowth\"`)\n * have been DETECTED and VALIDATED since W5 (`data-check-core.ts`'s\n * `DATA_REF_PATTERN` + `findDanglingDataRefs`, enforced by both `vgai doctor`\n * and the build plugin) \u2014 but nothing could actually RESOLVE one at runtime,\n * and nothing declared a field AS a ref in its schema (detection was by\n * string-shape convention alone). This module closes both halves:\n *\n * - {@link dataRef} \u2014 a typed Zod schema for a ref FIELD. Stamps the emitted\n * JSON Schema with a precise `pattern` (the target stem is baked into the\n * regex, so VS Code validates the prefix for free) and a machine-readable\n * `\"x-vgai-ref\": target` marker (a Zod `.meta()` that survives\n * `toDataJsonSchema`, including inside a table's `additionalProperties` row\n * schema \u2014 no emitter changes needed). The editor's Data panel\n * (`json-schema-fields.ts`'s `'ref'` kind) reads that marker to render a\n * `stem#key` PICKER instead of free text.\n * - {@link getRef} \u2014 lazy, read-time resolution. The caller names the target\n * HANDLE explicitly (`getRef(items, goblin.drop)`), so the resolved type is\n * the handle's own row type \u2014 no stem\u2192handle registry, no load-order\n * problem, no cycle hazard (nothing walks a graph; two refs resolved when\n * you choose to resolve them isn't a cycle), and it's HMR-correct for free\n * (it reads `target.get()` at CALL time, same doctrine as every other data\n * read \u2014 \"read every frame\", never cache across frames).\n *\n * Deliberately NOT built (and the design note this module's history carries):\n * eager resolution inside `defineData` (would change `get()`'s shipped output\n * type and entangle HMR \u2014 an edit to `enemies.data.json` would have to\n * re-notify every OTHER asset that references it), and a global\n * `resolveRef(addressString)` (needs a runtime stem\u2192handle registry that\n * `src/data/assets.ts` \u2014 side-effect-free, config-load-time, schemas-only by\n * its own module doc \u2014 must not become).\n */\n\nimport { z } from 'zod';\nimport type { DataHandle } from './data-asset';\nimport { DATA_REF_PATTERN } from './data-check-core';\n\n/** An asset-stem-tagged `file#key` string \u2014 `` `${Stem}#${string}` ``. */\nexport type DataRef<Stem extends string = string> = `${Stem}#${string}`;\n\n/** Prefix/key-path grammar a ref must match, parameterized by target stem (mirrors `DATA_REF_PATTERN` in `data-check-core.ts`, minus the alternation \u2014 this one is anchored to ONE target). */\nfunction refPattern(target: string): RegExp {\n return new RegExp(`^${target}#[A-Za-z0-9_-]+(?:\\\\.[A-Za-z0-9_-]+)*$`);\n}\n\n/**\n * A Zod schema for a data-asset FIELD that references another asset by\n * `\"<target>#<key>(.<field>)*\"`. Use it in a `.schema.ts`:\n *\n * ```ts\n * export const EnemyRowSchema = z.object({\n * name: z.string(),\n * drop: dataRef('items'), // -> \"items#potion\"\n * });\n * ```\n *\n * The emitted JSON Schema (`toDataJsonSchema`) carries both a precise\n * `pattern` (VS Code validates the target-stem prefix for free) and\n * `\"x-vgai-ref\": target` (the editor's Data panel picker keys off this).\n * Detection by `data-check-core.ts`'s conventional-string calibration still\n * applies at the VALUE level (a `dataRef` field's actual string still has to\n * look like `target#key` to resolve) \u2014 this only makes the field's INTENT\n * declared in the schema, closing the \u00A79.4 \"renamed target file silently\n * un-checks its refs\" hole for anything that adopts it (see\n * `collectDeclaredRefFields`/`findMissingRefTargets` in `data-check-core.ts`).\n */\nexport function dataRef<Stem extends string>(target: Stem): z.ZodType<DataRef<Stem>> {\n return z\n .string()\n .regex(refPattern(target), {\n message:\n `must be a \"${target}#<key>\" reference \u2014 ` +\n `expected the target asset stem \"${target}\", e.g. \"${target}#some-key\".`,\n })\n .meta({ 'x-vgai-ref': target }) as z.ZodType<DataRef<Stem>>;\n}\n\n/** First failing key-path segment, or `null` if the whole path resolves \u2014 same walk `data-check-core.ts`'s `firstUnresolvedSegment` does over parsed JSON, here over a live handle's value. */\nfunction firstMissingSegment(root: unknown, keyPath: readonly string[]): string | null {\n let node: unknown = root;\n for (const segment of keyPath) {\n if (node === null || typeof node !== 'object' || Array.isArray(node) || !(segment in node)) {\n return segment;\n }\n node = (node as Record<string, unknown>)[segment];\n }\n return null;\n}\n\n/**\n * Resolve a `\"target#key(.field)*\"` ref against the named target HANDLE,\n * read live (`target.get()` at call time \u2014 HMR-correct, no caching across\n * frames, same doctrine as any other data read).\n *\n * `ref`'s stem prefix should name `target`'s own asset \u2014 when `target` was\n * built with a `sourcePath` (every `defineData` call populates it), a\n * mismatch throws a teaching error instead of silently walking the wrong\n * handle's data. Without a `sourcePath` (a hand-rolled `DataHandle`, or an\n * older one built before this field existed) the mismatch check is skipped \u2014\n * resolution still proceeds against `target`, since the caller named it\n * explicitly and that's the actual contract.\n *\n * Throws a teaching error naming the ref and the first key-path segment that\n * doesn't resolve (a deleted row, a typo'd key) \u2014 never returns `undefined`\n * silently, matching `parseDataJson`'s \"errors teach\" doctrine (\u00A76.5).\n */\nexport function getRef<T>(target: DataHandle<Record<string, T>>, ref: string): T {\n const m = DATA_REF_PATTERN.exec(ref);\n if (!m) {\n throw new Error(\n `getRef: \"${ref}\" is not a \"file#key\" reference \u2014 ` +\n 'expected a string shaped like \"some-file#some-key\".',\n );\n }\n const refStem = m[1] as string;\n const keyPathStr = m[2] as string;\n const targetStem = target.sourcePath\n ?.split('\\\\')\n .join('/')\n .split('/')\n .pop()\n ?.replace(/\\.data\\.json$/, '');\n if (targetStem !== undefined && targetStem !== refStem) {\n throw new Error(\n `getRef: ref \"${ref}\" names target asset \"${refStem}\", but the handle passed in is ` +\n `\"${targetStem}\" (${target.sourcePath}). Pass the handle ` +\n `\"${refStem}#...\" actually names \u2014 getRef(${refStem}, ...), not getRef(${targetStem}, ...).`,\n );\n }\n const keyPath = keyPathStr.split('.');\n const root = target.get();\n const missing = firstMissingSegment(root, keyPath);\n if (missing !== null) {\n throw new Error(\n `getRef: dangling ref \"${ref}\" \u2014 \"${missing}\" does not exist` +\n (targetStem ? ` in ${targetStem}.data.json` : '') +\n '. Fix the key or remove the ref (refs are \"file#key\" strings).',\n );\n }\n let node: unknown = root;\n for (const segment of keyPath) node = (node as Record<string, unknown>)[segment];\n return node as T;\n}\n", "/**\n * Data-asset integrity core \u2014 the PURE half of W5 enforcement (\"dangling\n * `file#key` ref\" / \u00A76.7 build-path validation). No filesystem, no vite, no\n * zod: plain parsed-JSON in, findings out, so BOTH consumers \u2014 `vgai\n * doctor`'s data checks (`packages/editor/src/doctor/data-checks.ts`) and the\n * build-time plugin (`./vite-plugin-data.ts`) \u2014 share one definition of \"what\n * is a ref\" and \"what counts as dangling\" and can never drift apart.\n *\n * What is a ref (\u00A72.2): a cross-asset reference is a plain string\n * `\"file#key\"` \u2014 optionally with a field path, `\"tuning#economy.slotGrowth\"`\n * (file `#` key `.` field-path). There is no branded-ref Zod helper shipped\n * yet (W1 deferred it), so ref DETECTION is by convention, tuned against\n * false positives: a string is treated as a ref IFF it matches\n * {@link DATA_REF_PATTERN} AND its `file` prefix names a data asset that\n * actually exists in the project (`src/data/<file>.data.json`). Strings that\n * merely contain `#` \u2014 hex colors (`\"#ff0000\"`, no prefix), URLs with\n * fragments (`/` and `:` never match), musical pitches (`\"C#4\"` only matches\n * if a `C.data.json` exists) \u2014 never fire. The flip side is deliberate and\n * honest: a ref whose file prefix names a NONEXISTENT asset is\n * indistinguishable from an arbitrary string and is NOT flagged (\"error if\n * refs exist yet\" \u2014 the check only bites once the target file exists).\n *\n * `dataRef` (`./data-ref.ts`) now exists, closing that flip side for anyone\n * who adopts it: a `dataRef(target)` field's EMITTED schema carries\n * `\"x-vgai-ref\": target` \u2014 a declared intent, independent of whether the\n * target file currently exists. {@link collectDeclaredRefFields} /\n * {@link findMissingRefTargets} below walk that (zod-free \u2014 plain emitted\n * JSON Schema in, findings out, same purity contract as the rest of this\n * module) to catch the \u00A79.4 hole for DECLARED refs: renaming/deleting a\n * target file used to silently un-check every ref into it; now a declared\n * ref's target is checked by NAME, not by \"does a string happen to look\n * like one right now.\" Undeclared conventional-string refs keep the\n * calibrated behavior above, unchanged.\n */\n\n/**\n * `file#key(.field)*` \u2014 prefix must look like an asset stem (letters,\n * digits, `_`, `-`), key path is dot-separated segments of the same alphabet.\n */\nexport const DATA_REF_PATTERN = /^([A-Za-z0-9_-]+)#([A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*)$/;\n\n/** One ref-shaped string found while walking a data file's parsed JSON. */\nexport interface DataRefOccurrence {\n /** Asset stem of the data file the ref string was found IN (e.g. `\"tuning\"`). */\n readonly inAsset: string;\n /** JSON path of the string inside that file (e.g. `\"rows.goblin.drops[2]\"`). */\n readonly atPath: string;\n /** The full ref string, verbatim (e.g. `\"enemies#goblin\"`). */\n readonly ref: string;\n /** Parsed target asset stem (`\"enemies\"`). */\n readonly targetAsset: string;\n /** Parsed dot-separated key path into the target (`[\"goblin\"]`). */\n readonly targetKeyPath: readonly string[];\n}\n\n/** One dangling ref: the target FILE exists but the key path does not resolve in it. */\nexport interface DanglingRefFinding extends DataRefOccurrence {\n /** The first key-path segment that failed to resolve, for the teaching message. */\n readonly missingSegment: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Walk one data file's parsed JSON and collect every ref-shaped string whose\n * file prefix names an asset in `assetNames`. The top-level `\"$schema\"`\n * interchange line is skipped (it is wiring, not data \u2014 same special-casing\n * as `parseDataJson`'s strip).\n */\nexport function collectDataRefs(\n inAsset: string,\n json: unknown,\n assetNames: ReadonlySet<string>,\n): DataRefOccurrence[] {\n const out: DataRefOccurrence[] = [];\n visitForRefs(json, '', true, (node, path) => {\n const occurrence = asRefOccurrence(inAsset, node, path, assetNames);\n if (occurrence) out.push(occurrence);\n });\n return out;\n}\n\n/** Depth-first walk over parsed JSON, calling `onString` for every string leaf with its JSON path. */\nfunction visitForRefs(\n node: unknown,\n path: string,\n topLevel: boolean,\n onString: (value: string, path: string) => void,\n): void {\n if (typeof node === 'string') {\n onString(node, path);\n return;\n }\n if (Array.isArray(node)) {\n node.forEach((item, i) => {\n visitForRefs(item, `${path}[${i}]`, false, onString);\n });\n return;\n }\n if (isPlainObject(node)) {\n for (const [key, value] of Object.entries(node)) {\n if (topLevel && key === '$schema') continue;\n visitForRefs(value, path ? `${path}.${key}` : key, false, onString);\n }\n }\n}\n\n/** The string is a ref iff it matches the pattern AND its file prefix names a real asset. */\nfunction asRefOccurrence(\n inAsset: string,\n value: string,\n path: string,\n assetNames: ReadonlySet<string>,\n): DataRefOccurrence | null {\n const m = DATA_REF_PATTERN.exec(value);\n if (!m || !assetNames.has(m[1] as string)) return null;\n return {\n inAsset,\n atPath: path || '(root)',\n ref: value,\n targetAsset: m[1] as string,\n targetKeyPath: (m[2] as string).split('.'),\n };\n}\n\n/**\n * Find every dangling `file#key(.field)*` ref across a project's data assets.\n *\n * @param files parsed `.data.json` payloads keyed by asset stem (the\n * filename minus `.data.json` \u2014 the same name the ref's prefix uses, \u00A72.2).\n * Pass only files that parsed as JSON; unparseable files are already an\n * error in their own right and can't be resolved against anyway.\n * @returns one finding per ref whose target FILE is in `files` but whose key\n * path does not fully resolve inside it (a table row that doesn't exist, a\n * singleton field path that walks off the object).\n */\nexport function findDanglingDataRefs(files: ReadonlyMap<string, unknown>): DanglingRefFinding[] {\n const assetNames = new Set(files.keys());\n const findings: DanglingRefFinding[] = [];\n for (const [name, json] of files) {\n for (const occurrence of collectDataRefs(name, json, assetNames)) {\n const missing = firstUnresolvedSegment(files.get(occurrence.targetAsset), occurrence);\n if (missing !== null) findings.push({ ...occurrence, missingSegment: missing });\n }\n }\n return findings;\n}\n\n/** The first key-path segment that fails to resolve in the target payload, or `null` if the whole path resolves. */\nfunction firstUnresolvedSegment(target: unknown, ref: DataRefOccurrence): string | null {\n let node: unknown = target;\n for (const segment of ref.targetKeyPath) {\n if (!isPlainObject(node) || !(segment in node)) return segment;\n node = node[segment];\n }\n return null;\n}\n\n/** One `dataRef` field declared in an emitted JSON Schema. */\nexport interface DeclaredRefField {\n /** Dot-separated field path within the schema (e.g. `\"drop\"`, `\"loot.dropTable\"`). A table's row-schema fields are reported WITHOUT a row-key segment \u2014 the declaration applies to every row alike. */\n readonly fieldPath: string;\n /** The asset stem the field's `dataRef(...)` call named. */\n readonly targetStem: string;\n}\n\n/** One declared ref whose target stem names no asset that currently exists. */\nexport interface MissingRefTargetFinding {\n readonly fieldPath: string;\n readonly targetStem: string;\n}\n\n/** Loosely-typed view of an emitted JSON Schema node \u2014 walked structurally, never through Zod (this module stays zod-free). */\ninterface JsonSchemaNode {\n properties?: Record<string, unknown>;\n additionalProperties?: unknown;\n 'x-vgai-ref'?: unknown;\n}\n\nfunction asSchemaNode(value: unknown): JsonSchemaNode | null {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as JsonSchemaNode)\n : null;\n}\n\n/**\n * Walk an emitted data-asset JSON Schema (`toDataJsonSchema`'s output, or the\n * committed `.schema.json` twin \u2014 same shape either way) and collect every\n * field stamped `\"x-vgai-ref\": <target>` by `dataRef` (`./data-ref.ts`).\n * Handles both blessed shapes (spec \u00A72.1): a singleton's `properties`, and a\n * table's `additionalProperties` row schema \u2014 walked with the SAME field\n * path (a table's declared ref applies uniformly to every row, there is no\n * per-row schema variation). Nested `properties` inside a ref-declaring\n * field are not walked further (a ref leaf has no children); nested groups\n * elsewhere recurse via their own `properties`.\n */\nexport function collectDeclaredRefFields(schema: unknown): DeclaredRefField[] {\n const out: DeclaredRefField[] = [];\n walkForDeclaredRefs(schema, '', out);\n return out;\n}\n\nfunction walkForDeclaredRefs(raw: unknown, path: string, out: DeclaredRefField[]): void {\n const node = asSchemaNode(raw);\n if (!node) return;\n\n if (typeof node['x-vgai-ref'] === 'string') {\n out.push({ fieldPath: path || '(root)', targetStem: node['x-vgai-ref'] });\n return; // a ref leaf \u2014 nothing further to walk under it\n }\n\n if (isPlainObject(node.properties)) {\n for (const [key, child] of Object.entries(node.properties)) {\n if (key === '$schema') continue;\n walkForDeclaredRefs(child, path ? `${path}.${key}` : key, out);\n }\n }\n // A table's row schema (`z.record(rowSchema)` emits an object-valued\n // `additionalProperties`) \u2014 same field-path grammar, no row-key segment.\n if (isPlainObject(node.additionalProperties)) {\n walkForDeclaredRefs(node.additionalProperties, path, out);\n }\n}\n\n/**\n * Every declared ref field whose target stem names no asset in\n * `assetNames` \u2014 the \u00A79.4 fix: a `dataRef('items')` field stays flagged if\n * `items.data.json` is renamed or deleted, independent of whether any\n * CURRENT value happens to look like an `items#...` string (the gap the\n * conventional-string calibration above deliberately leaves open).\n */\nexport function findMissingRefTargets(\n declared: readonly DeclaredRefField[],\n assetNames: ReadonlySet<string>,\n): MissingRefTargetFinding[] {\n return declared\n .filter((d) => !assetNames.has(d.targetStem))\n .map((d) => ({ fieldPath: d.fieldPath, targetStem: d.targetStem }));\n}\n", "/**\n * Data assets \u2014 W1 (\u00A72.3 consumption API).\n *\n * A data asset is designer-tunable game data: a JSON file in the project's\n * `src/data/`, governed by a Zod schema (`*.schema.ts`, engineer-owned) whose\n * emitted JSON Schema (`*.schema.json`, see {@link toDataJsonSchema}) gives\n * VS Code validation via the data file's `\"$schema\"` first line. Data assets\n * are immutable at runtime \u2014 definitions, not state (\u00A72.1).\n *\n * The blessed consumption shape, scaffolded working-at-birth by the project\n * template (`src/data/` there is the worked example \u2014 \u00A76.2):\n *\n * ```ts\n * import raw from './tuning.data.json';\n * import { TuningSchema } from './tuning.schema';\n * import { defineData } from '@engine/data/data-asset';\n *\n * export const tuning = defineData(TuningSchema, raw, 'src/data/tuning.data.json');\n * // Vite HMR needs the literal dep path in THIS module (static analysis) \u2014\n * // this one line is the entire live-tuning wiring (['default'] not .default:\n * // strict tsconfigs index-signature ModuleNamespace):\n * import.meta.hot?.accept('./tuning.data.json', (m) => tuning.hotSwap(m?.['default']));\n * ```\n *\n * Game code reads `tuning.get()` inside its update loop (never cache fields\n * across frames) or `subscribe()`s; an edit to the `.data.json` \u2014 from\n * VS Code, an agent, or the future editor Data tab (W2) \u2014 flows through Vite\n * HMR into the running game with no remount. React roots/tools get a\n * `useData` hook with W3's tool-hooks package (deferred with it: the engine\n * core stays React-free).\n */\n\nimport { z } from 'zod';\n\n/**\n * A live handle to one data asset (\u00A72.3). `get`/`subscribe` are the whole\n * runtime surface; `hotSwap` exists only for the owning module's\n * `import.meta.hot.accept` callback.\n */\nexport interface DataHandle<T> {\n /** Current parsed values. Read every frame \u2014 HMR swaps them under you. */\n get(): T;\n /**\n * Called with the new value after every successful hot swap (NOT with the\n * initial value). Returns an unsubscribe function.\n */\n subscribe(fn: (value: T) => void): () => void;\n /**\n * HMR entry point \u2014 call from the owning module's\n * `import.meta.hot.accept('<file>.data.json', (m) => handle.hotSwap(m?.default))`.\n * Parses like load, but a FAILING edit keeps the last good value and\n * `console.error`s instead of throwing: a typo mid-live-tune must not\n * crash the running game. Fix the file and save again.\n */\n hotSwap(next: unknown): void;\n /**\n * The project-relative path this handle was defined with (`defineData`'s\n * own `sourcePath` argument, populated automatically below) \u2014 OPTIONAL so\n * any hand-rolled structural implementer stays valid. `getRef`\n * (`./data-ref.ts`) reads this to catch a `getRef(wrongHandle, \"stem#key\")`\n * mismatch with a teaching error instead of silently resolving against the\n * wrong asset; without it, `getRef` just skips that one check.\n */\n readonly sourcePath?: string;\n}\n\n/**\n * Define a data asset from its Zod schema, the statically imported JSON, and\n * its project-relative path (used verbatim in error messages, so pass the\n * real one). Parse-on-load: an invalid file fails loud at import time, naming\n * the file, every bad path, and the fix (\u00A72.3, \u00A76.5 \"errors teach\").\n *\n * Schema fields should carry `.min/.max/.default/.describe` \u2014 the same\n * annotations every authored schema uses \u2014 so the emitted JSON Schema\n * documents the file and (W2+) the editor renders real widgets.\n */\nexport function defineData<S extends z.ZodType>(\n schema: S,\n initial: unknown,\n sourcePath: string,\n): DataHandle<z.output<S>> {\n let current = parseDataJson(schema, initial, sourcePath);\n const subscribers = new Set<(value: z.output<S>) => void>();\n return {\n get: () => current,\n sourcePath,\n subscribe(fn) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n },\n hotSwap(next) {\n let parsed: z.output<S>;\n try {\n parsed = parseDataJson(schema, next, sourcePath);\n } catch (err) {\n // Keep the last good value alive \u2014 see the JSDoc on DataHandle.hotSwap.\n // biome-ignore lint/suspicious/noConsole: deliberate, greppable \u2014 a rejected live-tune edit must be loud without crashing the running game\n console.error(`[data] hot edit rejected, keeping previous values.\\n${String(err)}`);\n return;\n }\n current = parsed;\n for (const fn of subscribers) fn(current);\n },\n };\n}\n\n/**\n * Emit the JSON Schema interchange artifact for a data asset's Zod schema\n * (\u00A72.1: `*.schema.json` is EMITTED, never hand-written; D4: generated and\n * committed by default so VS Code works with no dev server running).\n *\n * Wraps `z.toJSONSchema` with `io: 'input'` \u2014 the one non-obvious knob:\n * defaulted fields must be OPTIONAL in the file schema (a data file may omit\n * them), whereas the default output mode would mark every field `required`\n * and make VS Code reject valid files. The template's root `emit-schemas.ts`\n * is the blessed caller (`npm run emit-schemas`).\n *\n * The emitted root schema also explicitly ALLOWS the `\"$schema\"` string\n * property, mirroring the parse-side strip below: without it, a TABLE\n * asset's emitted schema (`z.record` \u2192 `additionalProperties: <rowSchema>`)\n * makes VS Code flag the data file's own `\"$schema\"` line as an invalid row.\n */\nexport function toDataJsonSchema(schema: z.ZodType): Record<string, unknown> {\n const emitted = z.toJSONSchema(schema, { io: 'input' }) as Record<string, unknown>;\n if (emitted['type'] === 'object') {\n const properties = (emitted['properties'] ?? {}) as Record<string, unknown>;\n properties['$schema'] ??= { type: 'string' };\n emitted['properties'] = properties;\n }\n return emitted;\n}\n\n/**\n * Parse a raw `.data.json` payload: strips the `\"$schema\"` interchange line,\n * validates through the Zod schema, throws the teaching error on failure.\n * `defineData` uses this internally on load and hot swap; it is exported for\n * emit/doctor-style scripts (the template's `emit-schemas.ts` validates every\n * data file through it, so file validation and runtime validation can never\n * disagree).\n */\nexport function parseDataJson<S extends z.ZodType>(\n schema: S,\n data: unknown,\n sourcePath: string,\n): z.output<S> {\n // Strip the data file's `\"$schema\"` interchange line before validating \u2014\n // singleton (z.object, strip-mode) schemas ignored it by luck, but a TABLE\n // asset (z.record) would try to validate it as a row and fail.\n const payload =\n data !== null && typeof data === 'object' && !Array.isArray(data) && '$schema' in data\n ? Object.fromEntries(Object.entries(data).filter(([key]) => key !== '$schema'))\n : data;\n const result = schema.safeParse(payload);\n if (!result.success) {\n const issues = result.error.issues\n .map((issue) => ` - ${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('\\n');\n throw new Error(\n `Data asset \"${sourcePath}\" failed its schema:\\n${issues}\\n` +\n `Fix the JSON to match the Zod schema (its emitted twin, ` +\n `\"${sourcePath.replace(/\\.data\\.json$/, '.schema.json')}\", documents every field \u2014 ` +\n `re-emit with \\`npm run emit-schemas\\` if the schema changed). ` +\n `Worked example: the template's src/data/.`,\n );\n }\n return result.data;\n}\n", "/**\n * `vgaiDataCheck` \u2014 build-path validation for data assets and project tools (the\n * enforcement half of W5). A Vite plugin for the PROJECT's own `vite.config.ts`\n * (the template wires it; the editor dev server boots Vite from the ENGINE's\n * config and never runs this \u2014 its surface is covered by `vgai doctor` instead).\n * Build-only (`apply: 'build'`): in dev, `defineData`'s parse-on-load already\n * fails loud in the console.\n *\n * Three checks, all failing the build loud:\n *\n * 1. **Schema integrity** (`buildStart`): every registered asset's\n * `.data.json` is read fresh from disk and validated through\n * {@link parseDataJson} \u2014 the EXACT parse `defineData` runs at load (\u00A79.1:\n * an emitted-JSON-Schema validator here could disagree with runtime; the\n * Zod schema itself never can). The schemas arrive EXECUTABLE because\n * `vite.config.ts` statically imports the project's data-asset registry\n * (`src/data/assets.ts` in the template) \u2014 Vite's config loader bundles\n * config-relative TS imports, which is what makes this the one build-side\n * place project Zod schemas can run.\n * 2. **Ref integrity** (`buildStart`): every `file#key(.field)*` string in\n * every `src/data/*.data.json` (registered or not) must resolve \u2014 shared\n * definition with `vgai doctor` via {@link findDanglingDataRefs}, so the\n * two surfaces can never disagree about what \"dangling\" means. A second,\n * narrower ref check runs alongside it for REGISTERED assets only: any\n * field declared with `dataRef(target)` (`./data-ref.ts`) whose `target`\n * names no asset currently on disk fails loud too (\u00A79.4's \"renamed the\n * target file\" hole, closed for declared refs \u2014 see\n * `collectDeclaredRefFields`/`findMissingRefTargets` in `data-check-core.ts`).\n * 3. **Tools never ship** (`generateBundle`): no emitted chunk may contain a\n * module from `src/tools/` or a `*.tool.*` file (\u00A74: tester serves and\n * standalone builds strip tools entirely; W4 made this true by\n * construction \u2014 nothing imports tools \u2014 and this check PINS it against\n * the day some game module imports a tool \"just for a helper\").\n *\n * Unregistered data files (a `.data.json` with no entry in the passed\n * `assets` list) are a WARNING, not an error: they still get ref-integrity\n * and runtime parse-on-load, but no build-time schema check \u2014 the warning\n * names the registry file to fix.\n */\n\n// Node built-ins are imported LAZILY (inside `collectDataCheckProblems`),\n// never statically: this module is re-exported by the `@vgai/engine/config`\n// barrel, which every project `*.schema.ts` reaches through its `data-ref`\n// shim \u2014 so this module EVALUATES in the browser graph of any world whose\n// schema the game imports. A static `import { \u2026 } from 'node:fs'` dies there\n// (\"Module node:fs has been externalized for browser compatibility\") before\n// the world can mount. The fs work itself only ever runs in Node (vite build\n// / emit-schemas), where the dynamic import resolves normally.\nimport type { Plugin } from 'vite';\nimport type { z } from 'zod';\nimport { parseDataJson, toDataJsonSchema } from './data-asset';\nimport {\n collectDeclaredRefFields,\n findDanglingDataRefs,\n findMissingRefTargets,\n} from './data-check-core';\n\n/** One registered data asset: its executable Zod schema + the project-relative path of its `.data.json`. */\nexport interface DataCheckAsset {\n readonly schema: z.ZodType;\n /** e.g. `'src/data/tuning.data.json'` \u2014 read fresh from disk at buildStart. */\n readonly sourcePath: string;\n}\n\nexport interface VgaiDataCheckOptions {\n readonly assets: readonly DataCheckAsset[];\n /** Project root the `sourcePath`s resolve against. Default: `process.cwd()` (vite build's cwd). */\n readonly root?: string;\n}\n\n/** The Node APIs the checks need, resolved lazily \u2014 see the import note above. */\ninterface NodeIo {\n readdirSync: typeof import('node:fs')['readdirSync'];\n readFileSync: typeof import('node:fs')['readFileSync'];\n statSync: typeof import('node:fs')['statSync'];\n join: typeof import('node:path')['join'];\n relative: typeof import('node:path')['relative'];\n}\n\nasync function loadNodeIo(): Promise<NodeIo> {\n const [fs, path] = await Promise.all([import('node:fs'), import('node:path')]);\n return {\n readdirSync: fs.readdirSync,\n readFileSync: fs.readFileSync,\n statSync: fs.statSync,\n join: path.join,\n relative: path.relative,\n };\n}\n\n/** Recursively collect `*.data.json` under `dir` (absent dir \u2192 empty \u2014 a project with no data assets builds fine). */\nfunction findDataFiles(io: NodeIo, dir: string): string[] {\n let entries: string[];\n try {\n entries = io.readdirSync(dir) as string[];\n } catch {\n return [];\n }\n const out: string[] = [];\n for (const entry of entries) {\n const full = io.join(dir, entry);\n if (io.statSync(full).isDirectory()) out.push(...findDataFiles(io, full));\n else if (entry.endsWith('.data.json')) out.push(full);\n }\n return out;\n}\n\n/** `src/data/tuning.data.json` \u2192 `tuning` (normalizing either slash direction). */\nfunction assetStem(sourcePath: string): string {\n const rel = sourcePath.split('\\\\').join('/');\n return (\n rel\n .split('/')\n .pop()\n ?.replace(/\\.data\\.json$/, '') ?? rel\n );\n}\n\n/**\n * Parse every data file in the project once \u2014 the registered subset gets\n * schema validation, the whole set feeds ref integrity. Unparseable files\n * become errors; unregistered files become warnings naming the registry.\n *\n * DUPLICATE-STEM GUARD: `findDataFiles` walks `src/data/` recursively, so two\n * files in different subdirectories can share a stem (e.g.\n * `src/data/enemies.data.json` and `src/data/legacy/enemies.data.json`) \u2014 the\n * exact identity `file#key` refs AND the registry's `sourcePath` lookup both\n * address by stem alone (\u00A72.2). Without this guard `parsedByStem.set` would\n * silently last-wins the collision, and check 1 below could validate a\n * REGISTERED asset's schema against a totally unrelated file's JSON. Detected\n * here (one error per colliding path, naming every path) and excluded from\n * `parsedByStem` entirely \u2014 any resolution against a duplicate stem would be\n * an arbitrary, possibly-wrong pick, so neither check 1 nor check 2 (ref\n * integrity) resolves anything through it once it's flagged.\n */\ninterface ParsedDataFiles {\n parsedByStem: Map<string, unknown>;\n /** Stems the duplicate-stem guard already flagged \u2014 check 1 skips its own\n * redundant \"not found on disk\" for these (the duplicate-stem error\n * already explains why the stem has no single resolvable payload). */\n ambiguousStems: Set<string>;\n}\n\nfunction parseAllDataFiles(\n io: NodeIo,\n root: string,\n registered: ReadonlySet<string>,\n errors: string[],\n warnings: string[],\n): ParsedDataFiles {\n const parsedByStem = new Map<string, unknown>();\n const pathsByStem = new Map<string, string[]>();\n for (const abs of findDataFiles(io, io.join(root, 'src', 'data'))) {\n const rel = io.relative(root, abs).split('\\\\').join('/');\n const stem = assetStem(rel);\n const paths = pathsByStem.get(stem);\n if (paths) paths.push(rel);\n else pathsByStem.set(stem, [rel]);\n\n try {\n parsedByStem.set(stem, JSON.parse(io.readFileSync(abs, 'utf-8') as string));\n } catch (err) {\n errors.push(\n `\"${rel}\" is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n );\n continue;\n }\n if (!registered.has(rel)) {\n warnings.push(\n `\"${rel}\" is not registered in the data-asset registry (src/data/assets.ts), so it gets ` +\n 'no build-time schema check (runtime parse-on-load still applies). Register it there \u2014 ' +\n 'the template ships the worked example.',\n );\n }\n }\n\n const ambiguousStems = new Set<string>();\n for (const [stem, paths] of pathsByStem) {\n if (paths.length < 2) continue;\n ambiguousStems.add(stem);\n errors.push(\n `asset stem \"${stem}\" is claimed by ${paths.length} files (${paths.join(', ')}) \u2014 ` +\n '\"file#key\" refs and the data-asset registry address a file by its stem alone (\u00A72.2), so ' +\n 'this is an unresolvable identity collision. Rename one \u2014 asset stems must be unique ' +\n 'across the whole project, not just per directory.',\n );\n parsedByStem.delete(stem); // arbitrary otherwise \u2014 neither check below may resolve through it\n }\n\n return { parsedByStem, ambiguousStems };\n}\n\n/**\n * The fs half of checks 1 + 2, extracted from the plugin hook so it is\n * directly unit-testable against a fixture folder (no rollup context needed).\n */\nexport async function collectDataCheckProblems(options: VgaiDataCheckOptions): Promise<{\n errors: string[];\n warnings: string[];\n}> {\n const io = await loadNodeIo();\n const root = options.root ?? process.cwd();\n const errors: string[] = [];\n const warnings: string[] = [];\n const registered = new Set(options.assets.map((a) => a.sourcePath.split('\\\\').join('/')));\n const { parsedByStem, ambiguousStems } = parseAllDataFiles(\n io,\n root,\n registered,\n errors,\n warnings,\n );\n\n // Check 1 \u2014 registered assets validate through the exact runtime parse.\n for (const asset of options.assets) {\n const rel = asset.sourcePath.split('\\\\').join('/');\n if (!parsedByStem.has(assetStem(rel))) {\n // An AMBIGUOUS stem already has its own duplicate-stem error above,\n // which fully explains why there's no single payload to validate\n // against \u2014 a second \"not found on disk\" here would just be\n // confusing noise about a file that plainly IS on disk.\n if (!ambiguousStems.has(assetStem(rel))) {\n errors.push(\n `registered data asset \"${rel}\" was not found on disk \u2014 fix the path in the registry ` +\n '(src/data/assets.ts) or restore the file.',\n );\n }\n continue;\n }\n try {\n parseDataJson(asset.schema, parsedByStem.get(assetStem(rel)), rel);\n } catch (err) {\n errors.push(err instanceof Error ? err.message : String(err));\n }\n }\n\n // Check 2 \u2014 no dangling refs anywhere.\n for (const dangling of findDanglingDataRefs(parsedByStem)) {\n errors.push(\n `dangling data ref in \"src/data/${dangling.inAsset}.data.json\" at ${dangling.atPath}: ` +\n `\"${dangling.ref}\" \u2014 \"${dangling.missingSegment}\" does not exist in ` +\n `src/data/${dangling.targetAsset}.data.json. Fix the key or remove the ref ` +\n '(refs are \"file#key\" strings).',\n );\n }\n\n // Check 2b \u2014 every declared `dataRef(target)` field (registered assets\n // only, same set check 1 already validates) must name a target that's\n // actually on disk \u2014 the \u00A79.4 fix: this fires even if NO current value\n // happens to look like a ref, unlike check 2 above (see\n // `data-check-core.ts`'s module doc).\n const assetNames = new Set(parsedByStem.keys());\n for (const asset of options.assets) {\n const rel = asset.sourcePath.split('\\\\').join('/');\n const declared = collectDeclaredRefFields(toDataJsonSchema(asset.schema));\n for (const missing of findMissingRefTargets(declared, assetNames)) {\n errors.push(\n `\"${rel}\" declares field \"${missing.fieldPath}\" as dataRef('${missing.targetStem}'), but ` +\n `no \"src/data/${missing.targetStem}.data.json\" exists. Restore/rename the target file, ` +\n `or update the dataRef('${missing.targetStem}') call in the schema.`,\n );\n }\n }\n\n return { errors, warnings };\n}\n\n/** True iff a bundled module id is tool code that must never ship (\u00A74). Pure, unit-tested. */\nexport function isToolModuleId(id: string): boolean {\n const normalized = id.split('\\\\').join('/');\n return /\\/src\\/tools\\//.test(normalized) || /\\.tool\\.[tj]sx?(\\?|$)/.test(normalized);\n}\n\n/**\n * Build-path validation plugin \u2014 see the module doc. Wire it in the project's\n * `vite.config.ts`, passing the data-asset registry:\n *\n * ```ts\n * import { vgaiDataCheck } from '@vgai/engine/data/vite-plugin-data';\n * import { dataAssets } from './src/data/assets';\n * export default defineConfig({\n * plugins: [vgaiDataCheck({\n * root: __dirname,\n * assets: dataAssets.map((a) => ({ schema: a.schema, sourcePath: `src/data/${a.name}.data.json` })),\n * })],\n * });\n * ```\n */\nexport function vgaiDataCheck(options: VgaiDataCheckOptions): Plugin {\n return {\n name: 'vgai:data-check',\n apply: 'build',\n async buildStart() {\n const { errors, warnings } = await collectDataCheckProblems(options);\n for (const warning of warnings) this.warn(warning);\n if (errors.length > 0) {\n // ONE error carrying every problem \u2014 fail loud with the full picture,\n // not a fix-one-rebuild-see-the-next loop.\n this.error(\n `data-asset validation failed (${errors.length} problem${errors.length === 1 ? '' : 's'}` +\n `):\\n${errors.map((e) => ` - ${e}`).join('\\n')}`,\n );\n }\n },\n generateBundle(_outputOptions, bundle) {\n const leaked = new Set<string>();\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk') continue;\n for (const id of Object.keys(output.modules)) {\n if (isToolModuleId(id)) leaked.add(id.split('\\\\').join('/'));\n }\n }\n if (leaked.size > 0) {\n this.error(\n 'project tool code reached the game build \u2014 tools are editor-only and must never ship ' +\n 'to players. Remove every game-code import of these ' +\n `modules (tools may import game code, never the reverse):\\n${[...leaked]\n .map((id) => ` - ${id}`)\n .join('\\n')}`,\n );\n }\n },\n };\n}\n"],
4
+ "sourcesContent": ["/**\n * Curve FIELDS in data assets \u2014 a response curve a designer shapes, living\n * inside an ordinary `.data.json` like any other tunable value.\n *\n * A curve is a FIELD TYPE, never a file type: there is no `.curve.json`, no\n * curve asset class, no baked LUT, and no document. `curve(axes)` is a real\n * Zod schema you drop into a `*.schema.ts` beside `z.number()`, so the value\n * lives in the same data file, hot-swaps through the same `defineData` handle,\n * and is edited by the same Data panel that edits everything else.\n *\n * The JSON a designer (or an agent) reads and writes:\n *\n * ```json\n * { \"interpolation\": \"smooth\",\n * \"points\": [{ \"x\": 0, \"y\": 1 }, { \"x\": 12, \"y\": 0.85 }, { \"x\": 30, \"y\": 0.2 }] }\n * ```\n *\n * TWO MODES, NO TANGENTS. `linear` and `smooth`, and nothing else. Per-key\n * tangent handles would double the JSON, make it unreadable to an agent, and\n * hand every author a way to make a curve overshoot its own points. Smoothness\n * is DERIVED instead \u2014 Fritsch\u2013Carlson monotone cubic tangents, computed from\n * the points themselves \u2014 so the interpolant is guaranteed to stay inside each\n * segment's `[yLeft, yRight]` band. \"Shape it by moving points\" is the whole\n * authoring model.\n *\n * RUNG AUDIT (recorded decision, 2026-08-14): no npm dependency. The candidate\n * packages (`monotone-cubic-spline` and its siblings) are unmaintained\n * micro-packages, and d3's `curveMonotoneX` is an SVG PATH GENERATOR \u2014 it\n * draws, it does not sample `y` at an `x`. What we need is ~40 lines of\n * well-known numerics with no API surface, so it is written here.\n *\n * `sampleCurve` is the entire runtime: a pure function, no class, no cache\n * object, no \"curve system\". Game code calls it every frame from its own\n * update, the same way it reads any other tuning value.\n */\n\nimport { z } from 'zod';\n\n/** One authored key: a `y` value at an `x` position. No tangents \u2014 see above. */\nexport interface CurvePoint {\n x: number;\n y: number;\n}\n\n/** A curve field's value, exactly as it sits in the `.data.json`. */\nexport interface CurveValue {\n interpolation: 'linear' | 'smooth';\n points: CurvePoint[];\n}\n\n/**\n * The curve's DOMAIN, declared by the engineer in the schema (never by the\n * data): what the axes mean and how far they run. The editor draws its rails\n * from this and clamps every drag to it; the schema rejects a point outside\n * it.\n */\nexport interface CurveAxes {\n x: { min: number; max: number; label?: string };\n y: { min: number; max: number; label?: string };\n}\n\n/** How the marker rides out to the emitted JSON Schema \u2014 the editor's detection key, the exact shape `dataRef` uses with `x-vgai-ref`. */\nconst CURVE_META_KEY = 'x-vgai-curve';\n\nfunction axisLabel(axes: CurveAxes, axis: 'x' | 'y'): string {\n return axes[axis].label ?? axis;\n}\n\n/** Every out-of-domain / ordering problem in one pass, as teaching issues (`parseDataJson`'s \"errors teach\" doctrine, \u00A76.5). */\nfunction checkPoints(value: CurveValue, axes: CurveAxes, ctx: z.RefinementCtx): void {\n const points = value.points;\n for (let i = 0; i < points.length; i++) {\n const point = points[i] as CurvePoint;\n for (const axis of ['x', 'y'] as const) {\n const { min, max } = axes[axis];\n if (point[axis] < min || point[axis] > max) {\n ctx.addIssue({\n code: 'custom',\n path: ['points', i, axis],\n message:\n `${point[axis]} is outside this curve's ${axisLabel(axes, axis)} domain ` +\n `[${min}, ${max}] \u2014 move the point inside the domain, or widen the axis in the ` +\n `schema (curve({ ${axis}: { min, max } })).`,\n });\n }\n }\n if (i === 0) continue;\n const previous = points[i - 1] as CurvePoint;\n if (point.x <= previous.x) {\n ctx.addIssue({\n code: 'custom',\n path: ['points', i, 'x'],\n message:\n `${point.x} must be strictly greater than the previous point's x (${previous.x}) \u2014 ` +\n 'curve points run left to right along x, with no duplicate x. Sort the points, or ' +\n 'nudge this one.',\n });\n }\n }\n}\n\n/**\n * A Zod schema for a data-asset FIELD holding a response curve. Use it in a\n * `.schema.ts` exactly like any other field:\n *\n * ```ts\n * export const TuningSchema = z.object({\n * spawnRate: z.number().min(0).max(10).default(1),\n * difficultyRamp: curve({\n * x: { min: 0, max: 300, label: 'Sim time (s)' },\n * y: { min: 0, max: 2, label: 'Spawn multiplier' },\n * }).describe('How hard the game leans on the player as the round runs.'),\n * });\n * ```\n *\n * The schema is STRICT (an unrecognized key is an error, never a silent\n * strip), demands at least two points, and enforces strictly-increasing `x`\n * with every point inside the declared axes \u2014 each with a message that names\n * the fix rather than the rule.\n *\n * The emitted JSON Schema (`toDataJsonSchema`) carries\n * `\"x-vgai-curve\": axes` \u2014 a Zod `.meta()`, which survives `z.toJSONSchema`\n * including inside a table's `additionalProperties` row schema, exactly the\n * way `dataRef`'s `\"x-vgai-ref\"` does. That marker is what makes the editor's\n * Data panel render a curve EDITOR instead of a raw-JSON cell, with no emitter\n * changes anywhere.\n */\nexport function curve(axes: CurveAxes): z.ZodType<CurveValue> {\n const point = z.strictObject({\n x: z.number().describe(`Position along ${axisLabel(axes, 'x')}.`),\n y: z.number().describe(`Value at that position, along ${axisLabel(axes, 'y')}.`),\n });\n return z\n .strictObject({\n interpolation: z\n .enum(['linear', 'smooth'])\n .describe(\n 'How the value moves between points: \"linear\" for straight segments, ' +\n '\"smooth\" for a monotone cubic that never overshoots them.',\n ),\n points: z\n .array(point)\n .min(2, {\n message:\n 'a curve needs at least two points \u2014 add another { \"x\": \u2026, \"y\": \u2026 } so the ' +\n 'value has somewhere to travel between.',\n })\n .describe('Keys in increasing x order; the value is clamped outside the first/last x.'),\n })\n .superRefine((value, ctx) => checkPoints(value, axes, ctx))\n .meta({ [CURVE_META_KEY]: axes }) as unknown as z.ZodType<CurveValue>;\n}\n\n/**\n * Read a curve field's declared axes back off a LIVE Zod schema (as opposed to\n * the emitted JSON Schema, which the editor's Data panel reads instead).\n *\n * This is the dev-tools capability's detection door: it derives its rows by\n * walking the game's own `TuningSchema` object, so it needs the axes from the\n * schema in hand. Wrappers (`.optional()`, `.default(\u2026)`, `.describe(\u2026)` chains\n * that re-wrap) hide the metadata behind an inner type, so a bounded unwrap\n * walks down to it.\n */\nexport function curveAxesOf(schema: z.ZodType): CurveAxes | undefined {\n let current: unknown = schema;\n for (let depth = 0; depth < 5 && current; depth++) {\n const meta = (current as z.ZodType).meta?.() as Record<string, unknown> | undefined;\n const axes = meta?.[CURVE_META_KEY];\n if (axes && typeof axes === 'object' && 'x' in axes && 'y' in axes) return axes as CurveAxes;\n current = (current as { def?: { innerType?: unknown } }).def?.innerType;\n }\n return undefined;\n}\n\n/**\n * Fritsch\u2013Carlson tangents: the ordinary cubic-Hermite slopes, then limited so\n * the interpolant cannot overshoot the data. This is what makes \"smooth\" safe\n * to hand a designer \u2014 a curve that dips below its own points would silently\n * feed the game a value nobody authored.\n */\nfunction monotoneTangents(points: readonly CurvePoint[]): number[] {\n const n = points.length;\n const secants: number[] = [];\n for (let i = 0; i < n - 1; i++) {\n const left = points[i] as CurvePoint;\n const right = points[i + 1] as CurvePoint;\n secants.push((right.y - left.y) / (right.x - left.x));\n }\n const tangents: number[] = [secants[0] as number];\n for (let i = 1; i < n - 1; i++) {\n tangents.push(((secants[i - 1] as number) + (secants[i] as number)) / 2);\n }\n tangents.push(secants[n - 2] as number);\n\n for (let i = 0; i < n - 1; i++) {\n const secant = secants[i] as number;\n if (secant === 0) {\n // A flat segment must stay flat: any slope at either end would bulge.\n tangents[i] = 0;\n tangents[i + 1] = 0;\n continue;\n }\n let alpha = (tangents[i] as number) / secant;\n let beta = (tangents[i + 1] as number) / secant;\n // A tangent fighting the segment's own direction is a local extremum the\n // data does not have.\n if (alpha < 0) {\n tangents[i] = 0;\n alpha = 0;\n }\n if (beta < 0) {\n tangents[i + 1] = 0;\n beta = 0;\n }\n const radius = alpha * alpha + beta * beta;\n if (radius > 9) {\n const scale = 3 / Math.sqrt(radius);\n tangents[i] = scale * alpha * secant;\n tangents[i + 1] = scale * beta * secant;\n }\n }\n return tangents;\n}\n\n/**\n * The curve's value at `x` \u2014 the whole runtime API.\n *\n * Read it every frame from the game's own update, the way every other data\n * value is read (`tuning.get()` then sample); never precompute a table, and\n * never hold the result across frames \u2014 an edit to the `.data.json` hot-swaps\n * underneath you and that is the point.\n *\n * Outside `[first.x, last.x]` the value CLAMPS to the nearest endpoint: a\n * curve declares what it knows about, and extrapolating past it would invent\n * numbers nobody authored.\n */\nexport function sampleCurve(value: CurveValue, x: number): number {\n const points = value.points;\n if (points.length === 0) return 0;\n const first = points[0] as CurvePoint;\n const last = points[points.length - 1] as CurvePoint;\n if (points.length === 1 || x <= first.x) return first.y;\n if (x >= last.x) return last.y;\n\n let i = 0;\n while (i < points.length - 2 && x >= (points[i + 1] as CurvePoint).x) i++;\n const left = points[i] as CurvePoint;\n const right = points[i + 1] as CurvePoint;\n const span = right.x - left.x;\n if (span <= 0) return left.y; // duplicate x \u2014 the schema rejects it; a hand-built value might not\n const t = (x - left.x) / span;\n if (value.interpolation === 'linear') return left.y + (right.y - left.y) * t;\n\n const tangents = monotoneTangents(points);\n const t2 = t * t;\n const t3 = t2 * t;\n return (\n (2 * t3 - 3 * t2 + 1) * left.y +\n (t3 - 2 * t2 + t) * span * (tangents[i] as number) +\n (-2 * t3 + 3 * t2) * right.y +\n (t3 - t2) * span * (tangents[i + 1] as number)\n );\n}\n", "/**\n * `file#key` refs \u2014 the resolvable half.\n *\n * Cross-asset references (`\"enemies#goblin\"`, `\"tuning#economy.slotGrowth\"`)\n * have been DETECTED and VALIDATED since W5 (`data-check-core.ts`'s\n * `DATA_REF_PATTERN` + `findDanglingDataRefs`, enforced by both `vgai doctor`\n * and the build plugin) \u2014 but nothing could actually RESOLVE one at runtime,\n * and nothing declared a field AS a ref in its schema (detection was by\n * string-shape convention alone). This module closes both halves:\n *\n * - {@link dataRef} \u2014 a typed Zod schema for a ref FIELD. Stamps the emitted\n * JSON Schema with a precise `pattern` (the target stem is baked into the\n * regex, so VS Code validates the prefix for free) and a machine-readable\n * `\"x-vgai-ref\": target` marker (a Zod `.meta()` that survives\n * `toDataJsonSchema`, including inside a table's `additionalProperties` row\n * schema \u2014 no emitter changes needed). The editor's Data panel\n * (`json-schema-fields.ts`'s `'ref'` kind) reads that marker to render a\n * `stem#key` PICKER instead of free text.\n * - {@link getRef} \u2014 lazy, read-time resolution. The caller names the target\n * HANDLE explicitly (`getRef(items, goblin.drop)`), so the resolved type is\n * the handle's own row type \u2014 no stem\u2192handle registry, no load-order\n * problem, no cycle hazard (nothing walks a graph; two refs resolved when\n * you choose to resolve them isn't a cycle), and it's HMR-correct for free\n * (it reads `target.get()` at CALL time, same doctrine as every other data\n * read \u2014 \"read every frame\", never cache across frames).\n *\n * Deliberately NOT built (and the design note this module's history carries):\n * eager resolution inside `defineData` (would change `get()`'s shipped output\n * type and entangle HMR \u2014 an edit to `enemies.data.json` would have to\n * re-notify every OTHER asset that references it), and a global\n * `resolveRef(addressString)` (needs a runtime stem\u2192handle registry that\n * `src/data/assets.ts` \u2014 side-effect-free, config-load-time, schemas-only by\n * its own module doc \u2014 must not become).\n */\n\nimport { z } from 'zod';\nimport type { DataHandle } from './data-asset';\nimport { DATA_REF_PATTERN } from './data-check-core';\n\n/** An asset-stem-tagged `file#key` string \u2014 `` `${Stem}#${string}` ``. */\nexport type DataRef<Stem extends string = string> = `${Stem}#${string}`;\n\n/** Prefix/key-path grammar a ref must match, parameterized by target stem (mirrors `DATA_REF_PATTERN` in `data-check-core.ts`, minus the alternation \u2014 this one is anchored to ONE target). */\nfunction refPattern(target: string): RegExp {\n return new RegExp(`^${target}#[A-Za-z0-9_-]+(?:\\\\.[A-Za-z0-9_-]+)*$`);\n}\n\n/**\n * A Zod schema for a data-asset FIELD that references another asset by\n * `\"<target>#<key>(.<field>)*\"`. Use it in a `.schema.ts`:\n *\n * ```ts\n * export const EnemyRowSchema = z.object({\n * name: z.string(),\n * drop: dataRef('items'), // -> \"items#potion\"\n * });\n * ```\n *\n * The emitted JSON Schema (`toDataJsonSchema`) carries both a precise\n * `pattern` (VS Code validates the target-stem prefix for free) and\n * `\"x-vgai-ref\": target` (the editor's Data panel picker keys off this).\n * Detection by `data-check-core.ts`'s conventional-string calibration still\n * applies at the VALUE level (a `dataRef` field's actual string still has to\n * look like `target#key` to resolve) \u2014 this only makes the field's INTENT\n * declared in the schema, closing the \u00A79.4 \"renamed target file silently\n * un-checks its refs\" hole for anything that adopts it (see\n * `collectDeclaredRefFields`/`findMissingRefTargets` in `data-check-core.ts`).\n */\nexport function dataRef<Stem extends string>(target: Stem): z.ZodType<DataRef<Stem>> {\n return z\n .string()\n .regex(refPattern(target), {\n message:\n `must be a \"${target}#<key>\" reference \u2014 ` +\n `expected the target asset stem \"${target}\", e.g. \"${target}#some-key\".`,\n })\n .meta({ 'x-vgai-ref': target }) as z.ZodType<DataRef<Stem>>;\n}\n\n/** First failing key-path segment, or `null` if the whole path resolves \u2014 same walk `data-check-core.ts`'s `firstUnresolvedSegment` does over parsed JSON, here over a live handle's value. */\nfunction firstMissingSegment(root: unknown, keyPath: readonly string[]): string | null {\n let node: unknown = root;\n for (const segment of keyPath) {\n if (node === null || typeof node !== 'object' || Array.isArray(node) || !(segment in node)) {\n return segment;\n }\n node = (node as Record<string, unknown>)[segment];\n }\n return null;\n}\n\n/**\n * Resolve a `\"target#key(.field)*\"` ref against the named target HANDLE,\n * read live (`target.get()` at call time \u2014 HMR-correct, no caching across\n * frames, same doctrine as any other data read).\n *\n * `ref`'s stem prefix should name `target`'s own asset \u2014 when `target` was\n * built with a `sourcePath` (every `defineData` call populates it), a\n * mismatch throws a teaching error instead of silently walking the wrong\n * handle's data. Without a `sourcePath` (a hand-rolled `DataHandle`, or an\n * older one built before this field existed) the mismatch check is skipped \u2014\n * resolution still proceeds against `target`, since the caller named it\n * explicitly and that's the actual contract.\n *\n * Throws a teaching error naming the ref and the first key-path segment that\n * doesn't resolve (a deleted row, a typo'd key) \u2014 never returns `undefined`\n * silently, matching `parseDataJson`'s \"errors teach\" doctrine (\u00A76.5).\n */\nexport function getRef<T>(target: DataHandle<Record<string, T>>, ref: string): T {\n const m = DATA_REF_PATTERN.exec(ref);\n if (!m) {\n throw new Error(\n `getRef: \"${ref}\" is not a \"file#key\" reference \u2014 ` +\n 'expected a string shaped like \"some-file#some-key\".',\n );\n }\n const refStem = m[1] as string;\n const keyPathStr = m[2] as string;\n const targetStem = target.sourcePath\n ?.split('\\\\')\n .join('/')\n .split('/')\n .pop()\n ?.replace(/\\.data\\.json$/, '');\n if (targetStem !== undefined && targetStem !== refStem) {\n throw new Error(\n `getRef: ref \"${ref}\" names target asset \"${refStem}\", but the handle passed in is ` +\n `\"${targetStem}\" (${target.sourcePath}). Pass the handle ` +\n `\"${refStem}#...\" actually names \u2014 getRef(${refStem}, ...), not getRef(${targetStem}, ...).`,\n );\n }\n const keyPath = keyPathStr.split('.');\n const root = target.get();\n const missing = firstMissingSegment(root, keyPath);\n if (missing !== null) {\n throw new Error(\n `getRef: dangling ref \"${ref}\" \u2014 \"${missing}\" does not exist` +\n (targetStem ? ` in ${targetStem}.data.json` : '') +\n '. Fix the key or remove the ref (refs are \"file#key\" strings).',\n );\n }\n let node: unknown = root;\n for (const segment of keyPath) node = (node as Record<string, unknown>)[segment];\n return node as T;\n}\n", "/**\n * Data-asset integrity core \u2014 the PURE half of W5 enforcement (\"dangling\n * `file#key` ref\" / \u00A76.7 build-path validation). No filesystem, no vite, no\n * zod: plain parsed-JSON in, findings out, so BOTH consumers \u2014 `vgai\n * doctor`'s data checks (`packages/editor/src/doctor/data-checks.ts`) and the\n * build-time plugin (`./vite-plugin-data.ts`) \u2014 share one definition of \"what\n * is a ref\" and \"what counts as dangling\" and can never drift apart.\n *\n * What is a ref (\u00A72.2): a cross-asset reference is a plain string\n * `\"file#key\"` \u2014 optionally with a field path, `\"tuning#economy.slotGrowth\"`\n * (file `#` key `.` field-path). There is no branded-ref Zod helper shipped\n * yet (W1 deferred it), so ref DETECTION is by convention, tuned against\n * false positives: a string is treated as a ref IFF it matches\n * {@link DATA_REF_PATTERN} AND its `file` prefix names a data asset that\n * actually exists in the project (`src/data/<file>.data.json`). Strings that\n * merely contain `#` \u2014 hex colors (`\"#ff0000\"`, no prefix), URLs with\n * fragments (`/` and `:` never match), musical pitches (`\"C#4\"` only matches\n * if a `C.data.json` exists) \u2014 never fire. The flip side is deliberate and\n * honest: a ref whose file prefix names a NONEXISTENT asset is\n * indistinguishable from an arbitrary string and is NOT flagged (\"error if\n * refs exist yet\" \u2014 the check only bites once the target file exists).\n *\n * `dataRef` (`./data-ref.ts`) now exists, closing that flip side for anyone\n * who adopts it: a `dataRef(target)` field's EMITTED schema carries\n * `\"x-vgai-ref\": target` \u2014 a declared intent, independent of whether the\n * target file currently exists. {@link collectDeclaredRefFields} /\n * {@link findMissingRefTargets} below walk that (zod-free \u2014 plain emitted\n * JSON Schema in, findings out, same purity contract as the rest of this\n * module) to catch the \u00A79.4 hole for DECLARED refs: renaming/deleting a\n * target file used to silently un-check every ref into it; now a declared\n * ref's target is checked by NAME, not by \"does a string happen to look\n * like one right now.\" Undeclared conventional-string refs keep the\n * calibrated behavior above, unchanged.\n */\n\n/**\n * `file#key(.field)*` \u2014 prefix must look like an asset stem (letters,\n * digits, `_`, `-`), key path is dot-separated segments of the same alphabet.\n */\nexport const DATA_REF_PATTERN = /^([A-Za-z0-9_-]+)#([A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*)$/;\n\n/** One ref-shaped string found while walking a data file's parsed JSON. */\nexport interface DataRefOccurrence {\n /** Asset stem of the data file the ref string was found IN (e.g. `\"tuning\"`). */\n readonly inAsset: string;\n /** JSON path of the string inside that file (e.g. `\"rows.goblin.drops[2]\"`). */\n readonly atPath: string;\n /** The full ref string, verbatim (e.g. `\"enemies#goblin\"`). */\n readonly ref: string;\n /** Parsed target asset stem (`\"enemies\"`). */\n readonly targetAsset: string;\n /** Parsed dot-separated key path into the target (`[\"goblin\"]`). */\n readonly targetKeyPath: readonly string[];\n}\n\n/** One dangling ref: the target FILE exists but the key path does not resolve in it. */\nexport interface DanglingRefFinding extends DataRefOccurrence {\n /** The first key-path segment that failed to resolve, for the teaching message. */\n readonly missingSegment: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Walk one data file's parsed JSON and collect every ref-shaped string whose\n * file prefix names an asset in `assetNames`. The top-level `\"$schema\"`\n * interchange line is skipped (it is wiring, not data \u2014 same special-casing\n * as `parseDataJson`'s strip).\n */\nexport function collectDataRefs(\n inAsset: string,\n json: unknown,\n assetNames: ReadonlySet<string>,\n): DataRefOccurrence[] {\n const out: DataRefOccurrence[] = [];\n visitForRefs(json, '', true, (node, path) => {\n const occurrence = asRefOccurrence(inAsset, node, path, assetNames);\n if (occurrence) out.push(occurrence);\n });\n return out;\n}\n\n/** Depth-first walk over parsed JSON, calling `onString` for every string leaf with its JSON path. */\nfunction visitForRefs(\n node: unknown,\n path: string,\n topLevel: boolean,\n onString: (value: string, path: string) => void,\n): void {\n if (typeof node === 'string') {\n onString(node, path);\n return;\n }\n if (Array.isArray(node)) {\n node.forEach((item, i) => {\n visitForRefs(item, `${path}[${i}]`, false, onString);\n });\n return;\n }\n if (isPlainObject(node)) {\n for (const [key, value] of Object.entries(node)) {\n if (topLevel && key === '$schema') continue;\n visitForRefs(value, path ? `${path}.${key}` : key, false, onString);\n }\n }\n}\n\n/** The string is a ref iff it matches the pattern AND its file prefix names a real asset. */\nfunction asRefOccurrence(\n inAsset: string,\n value: string,\n path: string,\n assetNames: ReadonlySet<string>,\n): DataRefOccurrence | null {\n const m = DATA_REF_PATTERN.exec(value);\n if (!m || !assetNames.has(m[1] as string)) return null;\n return {\n inAsset,\n atPath: path || '(root)',\n ref: value,\n targetAsset: m[1] as string,\n targetKeyPath: (m[2] as string).split('.'),\n };\n}\n\n/**\n * Find every dangling `file#key(.field)*` ref across a project's data assets.\n *\n * @param files parsed `.data.json` payloads keyed by asset stem (the\n * filename minus `.data.json` \u2014 the same name the ref's prefix uses, \u00A72.2).\n * Pass only files that parsed as JSON; unparseable files are already an\n * error in their own right and can't be resolved against anyway.\n * @returns one finding per ref whose target FILE is in `files` but whose key\n * path does not fully resolve inside it (a table row that doesn't exist, a\n * singleton field path that walks off the object).\n */\nexport function findDanglingDataRefs(files: ReadonlyMap<string, unknown>): DanglingRefFinding[] {\n const assetNames = new Set(files.keys());\n const findings: DanglingRefFinding[] = [];\n for (const [name, json] of files) {\n for (const occurrence of collectDataRefs(name, json, assetNames)) {\n const missing = firstUnresolvedSegment(files.get(occurrence.targetAsset), occurrence);\n if (missing !== null) findings.push({ ...occurrence, missingSegment: missing });\n }\n }\n return findings;\n}\n\n/** The first key-path segment that fails to resolve in the target payload, or `null` if the whole path resolves. */\nfunction firstUnresolvedSegment(target: unknown, ref: DataRefOccurrence): string | null {\n let node: unknown = target;\n for (const segment of ref.targetKeyPath) {\n if (!isPlainObject(node) || !(segment in node)) return segment;\n node = node[segment];\n }\n return null;\n}\n\n/** One `dataRef` field declared in an emitted JSON Schema. */\nexport interface DeclaredRefField {\n /** Dot-separated field path within the schema (e.g. `\"drop\"`, `\"loot.dropTable\"`). A table's row-schema fields are reported WITHOUT a row-key segment \u2014 the declaration applies to every row alike. */\n readonly fieldPath: string;\n /** The asset stem the field's `dataRef(...)` call named. */\n readonly targetStem: string;\n}\n\n/** One declared ref whose target stem names no asset that currently exists. */\nexport interface MissingRefTargetFinding {\n readonly fieldPath: string;\n readonly targetStem: string;\n}\n\n/** Loosely-typed view of an emitted JSON Schema node \u2014 walked structurally, never through Zod (this module stays zod-free). */\ninterface JsonSchemaNode {\n properties?: Record<string, unknown>;\n additionalProperties?: unknown;\n 'x-vgai-ref'?: unknown;\n}\n\nfunction asSchemaNode(value: unknown): JsonSchemaNode | null {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as JsonSchemaNode)\n : null;\n}\n\n/**\n * Walk an emitted data-asset JSON Schema (`toDataJsonSchema`'s output, or the\n * committed `.schema.json` twin \u2014 same shape either way) and collect every\n * field stamped `\"x-vgai-ref\": <target>` by `dataRef` (`./data-ref.ts`).\n * Handles both blessed shapes (spec \u00A72.1): a singleton's `properties`, and a\n * table's `additionalProperties` row schema \u2014 walked with the SAME field\n * path (a table's declared ref applies uniformly to every row, there is no\n * per-row schema variation). Nested `properties` inside a ref-declaring\n * field are not walked further (a ref leaf has no children); nested groups\n * elsewhere recurse via their own `properties`.\n */\nexport function collectDeclaredRefFields(schema: unknown): DeclaredRefField[] {\n const out: DeclaredRefField[] = [];\n walkForDeclaredRefs(schema, '', out);\n return out;\n}\n\nfunction walkForDeclaredRefs(raw: unknown, path: string, out: DeclaredRefField[]): void {\n const node = asSchemaNode(raw);\n if (!node) return;\n\n if (typeof node['x-vgai-ref'] === 'string') {\n out.push({ fieldPath: path || '(root)', targetStem: node['x-vgai-ref'] });\n return; // a ref leaf \u2014 nothing further to walk under it\n }\n\n if (isPlainObject(node.properties)) {\n for (const [key, child] of Object.entries(node.properties)) {\n if (key === '$schema') continue;\n walkForDeclaredRefs(child, path ? `${path}.${key}` : key, out);\n }\n }\n // A table's row schema (`z.record(rowSchema)` emits an object-valued\n // `additionalProperties`) \u2014 same field-path grammar, no row-key segment.\n if (isPlainObject(node.additionalProperties)) {\n walkForDeclaredRefs(node.additionalProperties, path, out);\n }\n}\n\n/**\n * Every declared ref field whose target stem names no asset in\n * `assetNames` \u2014 the \u00A79.4 fix: a `dataRef('items')` field stays flagged if\n * `items.data.json` is renamed or deleted, independent of whether any\n * CURRENT value happens to look like an `items#...` string (the gap the\n * conventional-string calibration above deliberately leaves open).\n */\nexport function findMissingRefTargets(\n declared: readonly DeclaredRefField[],\n assetNames: ReadonlySet<string>,\n): MissingRefTargetFinding[] {\n return declared\n .filter((d) => !assetNames.has(d.targetStem))\n .map((d) => ({ fieldPath: d.fieldPath, targetStem: d.targetStem }));\n}\n", "/**\n * Data assets \u2014 W1 (\u00A72.3 consumption API).\n *\n * A data asset is designer-tunable game data: a JSON file in the project's\n * `src/data/`, governed by a Zod schema (`*.schema.ts`, engineer-owned) whose\n * emitted JSON Schema (`*.schema.json`, see {@link toDataJsonSchema}) gives\n * VS Code validation via the data file's `\"$schema\"` first line. Data assets\n * are immutable at runtime \u2014 definitions, not state (\u00A72.1).\n *\n * The blessed consumption shape, scaffolded working-at-birth by the project\n * template (`src/data/` there is the worked example \u2014 \u00A76.2):\n *\n * ```ts\n * import raw from './tuning.data.json';\n * import { TuningSchema } from './tuning.schema';\n * import { defineData } from '@engine/data/data-asset';\n *\n * export const tuning = defineData(TuningSchema, raw, 'src/data/tuning.data.json');\n * // Vite HMR needs the literal dep path in THIS module (static analysis) \u2014\n * // this one line is the entire live-tuning wiring (['default'] not .default:\n * // strict tsconfigs index-signature ModuleNamespace):\n * import.meta.hot?.accept('./tuning.data.json', (m) => tuning.hotSwap(m?.['default']));\n * ```\n *\n * Game code reads `tuning.get()` inside its update loop (never cache fields\n * across frames) or `subscribe()`s; an edit to the `.data.json` \u2014 from\n * VS Code, an agent, or the future editor Data tab (W2) \u2014 flows through Vite\n * HMR into the running game with no remount. React roots/tools get a\n * `useData` hook with W3's tool-hooks package (deferred with it: the engine\n * core stays React-free).\n */\n\nimport { z } from 'zod';\n\n/**\n * A live handle to one data asset (\u00A72.3). `get`/`subscribe` are the whole\n * runtime surface; `hotSwap` exists only for the owning module's\n * `import.meta.hot.accept` callback.\n */\nexport interface DataHandle<T> {\n /** Current parsed values. Read every frame \u2014 HMR swaps them under you. */\n get(): T;\n /**\n * Called with the new value after every successful hot swap (NOT with the\n * initial value). Returns an unsubscribe function.\n */\n subscribe(fn: (value: T) => void): () => void;\n /**\n * HMR entry point \u2014 call from the owning module's\n * `import.meta.hot.accept('<file>.data.json', (m) => handle.hotSwap(m?.default))`.\n * Parses like load, but a FAILING edit keeps the last good value and\n * `console.error`s instead of throwing: a typo mid-live-tune must not\n * crash the running game. Fix the file and save again.\n */\n hotSwap(next: unknown): void;\n /**\n * The project-relative path this handle was defined with (`defineData`'s\n * own `sourcePath` argument, populated automatically below) \u2014 OPTIONAL so\n * any hand-rolled structural implementer stays valid. `getRef`\n * (`./data-ref.ts`) reads this to catch a `getRef(wrongHandle, \"stem#key\")`\n * mismatch with a teaching error instead of silently resolving against the\n * wrong asset; without it, `getRef` just skips that one check.\n */\n readonly sourcePath?: string;\n}\n\n/**\n * Define a data asset from its Zod schema, the statically imported JSON, and\n * its project-relative path (used verbatim in error messages, so pass the\n * real one). Parse-on-load: an invalid file fails loud at import time, naming\n * the file, every bad path, and the fix (\u00A72.3, \u00A76.5 \"errors teach\").\n *\n * Schema fields should carry `.min/.max/.default/.describe` \u2014 the same\n * annotations every authored schema uses \u2014 so the emitted JSON Schema\n * documents the file and (W2+) the editor renders real widgets.\n */\nexport function defineData<S extends z.ZodType>(\n schema: S,\n initial: unknown,\n sourcePath: string,\n): DataHandle<z.output<S>> {\n let current = parseDataJson(schema, initial, sourcePath);\n const subscribers = new Set<(value: z.output<S>) => void>();\n return {\n get: () => current,\n sourcePath,\n subscribe(fn) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n },\n hotSwap(next) {\n let parsed: z.output<S>;\n try {\n parsed = parseDataJson(schema, next, sourcePath);\n } catch (err) {\n // Keep the last good value alive \u2014 see the JSDoc on DataHandle.hotSwap.\n // biome-ignore lint/suspicious/noConsole: deliberate, greppable \u2014 a rejected live-tune edit must be loud without crashing the running game\n console.error(`[data] hot edit rejected, keeping previous values.\\n${String(err)}`);\n return;\n }\n current = parsed;\n for (const fn of subscribers) fn(current);\n },\n };\n}\n\n/**\n * Emit the JSON Schema interchange artifact for a data asset's Zod schema\n * (\u00A72.1: `*.schema.json` is EMITTED, never hand-written; D4: generated and\n * committed by default so VS Code works with no dev server running).\n *\n * Wraps `z.toJSONSchema` with `io: 'input'` \u2014 the one non-obvious knob:\n * defaulted fields must be OPTIONAL in the file schema (a data file may omit\n * them), whereas the default output mode would mark every field `required`\n * and make VS Code reject valid files. The template's root `emit-schemas.ts`\n * is the blessed caller (`npm run emit-schemas`).\n *\n * The emitted root schema also explicitly ALLOWS the `\"$schema\"` string\n * property, mirroring the parse-side strip below: without it, a TABLE\n * asset's emitted schema (`z.record` \u2192 `additionalProperties: <rowSchema>`)\n * makes VS Code flag the data file's own `\"$schema\"` line as an invalid row.\n */\nexport function toDataJsonSchema(schema: z.ZodType): Record<string, unknown> {\n const emitted = z.toJSONSchema(schema, { io: 'input' }) as Record<string, unknown>;\n if (emitted['type'] === 'object') {\n const properties = (emitted['properties'] ?? {}) as Record<string, unknown>;\n properties['$schema'] ??= { type: 'string' };\n emitted['properties'] = properties;\n }\n return emitted;\n}\n\n/**\n * Parse a raw `.data.json` payload: strips the `\"$schema\"` interchange line,\n * validates through the Zod schema, throws the teaching error on failure.\n * `defineData` uses this internally on load and hot swap; it is exported for\n * emit/doctor-style scripts (the template's `emit-schemas.ts` validates every\n * data file through it, so file validation and runtime validation can never\n * disagree).\n */\nexport function parseDataJson<S extends z.ZodType>(\n schema: S,\n data: unknown,\n sourcePath: string,\n): z.output<S> {\n // Strip the data file's `\"$schema\"` interchange line before validating \u2014\n // singleton (z.object, strip-mode) schemas ignored it by luck, but a TABLE\n // asset (z.record) would try to validate it as a row and fail.\n const payload =\n data !== null && typeof data === 'object' && !Array.isArray(data) && '$schema' in data\n ? Object.fromEntries(Object.entries(data).filter(([key]) => key !== '$schema'))\n : data;\n const result = schema.safeParse(payload);\n if (!result.success) {\n const issues = result.error.issues\n .map((issue) => ` - ${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('\\n');\n throw new Error(\n `Data asset \"${sourcePath}\" failed its schema:\\n${issues}\\n` +\n `Fix the JSON to match the Zod schema (its emitted twin, ` +\n `\"${sourcePath.replace(/\\.data\\.json$/, '.schema.json')}\", documents every field \u2014 ` +\n `re-emit with \\`npm run emit-schemas\\` if the schema changed). ` +\n `Worked example: the template's src/data/.`,\n );\n }\n return result.data;\n}\n", "/**\n * `vgaiDataCheck` \u2014 build-path validation for data assets and project tools (the\n * enforcement half of W5). A Vite plugin for the PROJECT's own `vite.config.ts`\n * (the template wires it; the editor dev server boots Vite from the ENGINE's\n * config and never runs this \u2014 its surface is covered by `vgai doctor` instead).\n * Build-only (`apply: 'build'`): in dev, `defineData`'s parse-on-load already\n * fails loud in the console.\n *\n * Three checks, all failing the build loud:\n *\n * 1. **Schema integrity** (`buildStart`): every registered asset's\n * `.data.json` is read fresh from disk and validated through\n * {@link parseDataJson} \u2014 the EXACT parse `defineData` runs at load (\u00A79.1:\n * an emitted-JSON-Schema validator here could disagree with runtime; the\n * Zod schema itself never can). The schemas arrive EXECUTABLE because\n * `vite.config.ts` statically imports the project's data-asset registry\n * (`src/data/assets.ts` in the template) \u2014 Vite's config loader bundles\n * config-relative TS imports, which is what makes this the one build-side\n * place project Zod schemas can run.\n * 2. **Ref integrity** (`buildStart`): every `file#key(.field)*` string in\n * every `src/data/*.data.json` (registered or not) must resolve \u2014 shared\n * definition with `vgai doctor` via {@link findDanglingDataRefs}, so the\n * two surfaces can never disagree about what \"dangling\" means. A second,\n * narrower ref check runs alongside it for REGISTERED assets only: any\n * field declared with `dataRef(target)` (`./data-ref.ts`) whose `target`\n * names no asset currently on disk fails loud too (\u00A79.4's \"renamed the\n * target file\" hole, closed for declared refs \u2014 see\n * `collectDeclaredRefFields`/`findMissingRefTargets` in `data-check-core.ts`).\n * 3. **Tools never ship** (`generateBundle`): no emitted chunk may contain a\n * module from `src/tools/` or a `*.tool.*` file (\u00A74: tester serves and\n * standalone builds strip tools entirely; W4 made this true by\n * construction \u2014 nothing imports tools \u2014 and this check PINS it against\n * the day some game module imports a tool \"just for a helper\").\n *\n * Unregistered data files (a `.data.json` with no entry in the passed\n * `assets` list) are a WARNING, not an error: they still get ref-integrity\n * and runtime parse-on-load, but no build-time schema check \u2014 the warning\n * names the registry file to fix.\n */\n\n// Node built-ins are imported LAZILY (inside `collectDataCheckProblems`),\n// never statically: this module is re-exported by the `@vgai/engine/config`\n// barrel, which every project `*.schema.ts` reaches through its `data-ref`\n// shim \u2014 so this module EVALUATES in the browser graph of any world whose\n// schema the game imports. A static `import { \u2026 } from 'node:fs'` dies there\n// (\"Module node:fs has been externalized for browser compatibility\") before\n// the world can mount. The fs work itself only ever runs in Node (vite build\n// / emit-schemas), where the dynamic import resolves normally.\nimport type { Plugin } from 'vite';\nimport type { z } from 'zod';\nimport { parseDataJson, toDataJsonSchema } from './data-asset';\nimport {\n collectDeclaredRefFields,\n findDanglingDataRefs,\n findMissingRefTargets,\n} from './data-check-core';\n\n/** One registered data asset: its executable Zod schema + the project-relative path of its `.data.json`. */\nexport interface DataCheckAsset {\n readonly schema: z.ZodType;\n /** e.g. `'src/data/tuning.data.json'` \u2014 read fresh from disk at buildStart. */\n readonly sourcePath: string;\n}\n\nexport interface VgaiDataCheckOptions {\n readonly assets: readonly DataCheckAsset[];\n /** Project root the `sourcePath`s resolve against. Default: `process.cwd()` (vite build's cwd). */\n readonly root?: string;\n}\n\n/** The Node APIs the checks need, resolved lazily \u2014 see the import note above. */\ninterface NodeIo {\n readdirSync: typeof import('node:fs')['readdirSync'];\n readFileSync: typeof import('node:fs')['readFileSync'];\n statSync: typeof import('node:fs')['statSync'];\n join: typeof import('node:path')['join'];\n relative: typeof import('node:path')['relative'];\n}\n\nasync function loadNodeIo(): Promise<NodeIo> {\n const [fs, path] = await Promise.all([import('node:fs'), import('node:path')]);\n return {\n readdirSync: fs.readdirSync,\n readFileSync: fs.readFileSync,\n statSync: fs.statSync,\n join: path.join,\n relative: path.relative,\n };\n}\n\n/** Recursively collect `*.data.json` under `dir` (absent dir \u2192 empty \u2014 a project with no data assets builds fine). */\nfunction findDataFiles(io: NodeIo, dir: string): string[] {\n let entries: string[];\n try {\n entries = io.readdirSync(dir) as string[];\n } catch {\n return [];\n }\n const out: string[] = [];\n for (const entry of entries) {\n const full = io.join(dir, entry);\n if (io.statSync(full).isDirectory()) out.push(...findDataFiles(io, full));\n else if (entry.endsWith('.data.json')) out.push(full);\n }\n return out;\n}\n\n/** `src/data/tuning.data.json` \u2192 `tuning` (normalizing either slash direction). */\nfunction assetStem(sourcePath: string): string {\n const rel = sourcePath.split('\\\\').join('/');\n return (\n rel\n .split('/')\n .pop()\n ?.replace(/\\.data\\.json$/, '') ?? rel\n );\n}\n\n/**\n * Parse every data file in the project once \u2014 the registered subset gets\n * schema validation, the whole set feeds ref integrity. Unparseable files\n * become errors; unregistered files become warnings naming the registry.\n *\n * DUPLICATE-STEM GUARD: `findDataFiles` walks `src/data/` recursively, so two\n * files in different subdirectories can share a stem (e.g.\n * `src/data/enemies.data.json` and `src/data/legacy/enemies.data.json`) \u2014 the\n * exact identity `file#key` refs AND the registry's `sourcePath` lookup both\n * address by stem alone (\u00A72.2). Without this guard `parsedByStem.set` would\n * silently last-wins the collision, and check 1 below could validate a\n * REGISTERED asset's schema against a totally unrelated file's JSON. Detected\n * here (one error per colliding path, naming every path) and excluded from\n * `parsedByStem` entirely \u2014 any resolution against a duplicate stem would be\n * an arbitrary, possibly-wrong pick, so neither check 1 nor check 2 (ref\n * integrity) resolves anything through it once it's flagged.\n */\ninterface ParsedDataFiles {\n parsedByStem: Map<string, unknown>;\n /** Stems the duplicate-stem guard already flagged \u2014 check 1 skips its own\n * redundant \"not found on disk\" for these (the duplicate-stem error\n * already explains why the stem has no single resolvable payload). */\n ambiguousStems: Set<string>;\n}\n\nfunction parseAllDataFiles(\n io: NodeIo,\n root: string,\n registered: ReadonlySet<string>,\n errors: string[],\n warnings: string[],\n): ParsedDataFiles {\n const parsedByStem = new Map<string, unknown>();\n const pathsByStem = new Map<string, string[]>();\n for (const abs of findDataFiles(io, io.join(root, 'src', 'data'))) {\n const rel = io.relative(root, abs).split('\\\\').join('/');\n const stem = assetStem(rel);\n const paths = pathsByStem.get(stem);\n if (paths) paths.push(rel);\n else pathsByStem.set(stem, [rel]);\n\n try {\n parsedByStem.set(stem, JSON.parse(io.readFileSync(abs, 'utf-8') as string));\n } catch (err) {\n errors.push(\n `\"${rel}\" is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n );\n continue;\n }\n if (!registered.has(rel)) {\n warnings.push(\n `\"${rel}\" is not registered in the data-asset registry (src/data/assets.ts), so it gets ` +\n 'no build-time schema check (runtime parse-on-load still applies). Register it there \u2014 ' +\n 'the template ships the worked example.',\n );\n }\n }\n\n const ambiguousStems = new Set<string>();\n for (const [stem, paths] of pathsByStem) {\n if (paths.length < 2) continue;\n ambiguousStems.add(stem);\n errors.push(\n `asset stem \"${stem}\" is claimed by ${paths.length} files (${paths.join(', ')}) \u2014 ` +\n '\"file#key\" refs and the data-asset registry address a file by its stem alone (\u00A72.2), so ' +\n 'this is an unresolvable identity collision. Rename one \u2014 asset stems must be unique ' +\n 'across the whole project, not just per directory.',\n );\n parsedByStem.delete(stem); // arbitrary otherwise \u2014 neither check below may resolve through it\n }\n\n return { parsedByStem, ambiguousStems };\n}\n\n/**\n * The fs half of checks 1 + 2, extracted from the plugin hook so it is\n * directly unit-testable against a fixture folder (no rollup context needed).\n */\nexport async function collectDataCheckProblems(options: VgaiDataCheckOptions): Promise<{\n errors: string[];\n warnings: string[];\n}> {\n const io = await loadNodeIo();\n const root = options.root ?? process.cwd();\n const errors: string[] = [];\n const warnings: string[] = [];\n const registered = new Set(options.assets.map((a) => a.sourcePath.split('\\\\').join('/')));\n const { parsedByStem, ambiguousStems } = parseAllDataFiles(\n io,\n root,\n registered,\n errors,\n warnings,\n );\n\n // Check 1 \u2014 registered assets validate through the exact runtime parse.\n for (const asset of options.assets) {\n const rel = asset.sourcePath.split('\\\\').join('/');\n if (!parsedByStem.has(assetStem(rel))) {\n // An AMBIGUOUS stem already has its own duplicate-stem error above,\n // which fully explains why there's no single payload to validate\n // against \u2014 a second \"not found on disk\" here would just be\n // confusing noise about a file that plainly IS on disk.\n if (!ambiguousStems.has(assetStem(rel))) {\n errors.push(\n `registered data asset \"${rel}\" was not found on disk \u2014 fix the path in the registry ` +\n '(src/data/assets.ts) or restore the file.',\n );\n }\n continue;\n }\n try {\n parseDataJson(asset.schema, parsedByStem.get(assetStem(rel)), rel);\n } catch (err) {\n errors.push(err instanceof Error ? err.message : String(err));\n }\n }\n\n // Check 2 \u2014 no dangling refs anywhere.\n for (const dangling of findDanglingDataRefs(parsedByStem)) {\n errors.push(\n `dangling data ref in \"src/data/${dangling.inAsset}.data.json\" at ${dangling.atPath}: ` +\n `\"${dangling.ref}\" \u2014 \"${dangling.missingSegment}\" does not exist in ` +\n `src/data/${dangling.targetAsset}.data.json. Fix the key or remove the ref ` +\n '(refs are \"file#key\" strings).',\n );\n }\n\n // Check 2b \u2014 every declared `dataRef(target)` field (registered assets\n // only, same set check 1 already validates) must name a target that's\n // actually on disk \u2014 the \u00A79.4 fix: this fires even if NO current value\n // happens to look like a ref, unlike check 2 above (see\n // `data-check-core.ts`'s module doc).\n const assetNames = new Set(parsedByStem.keys());\n for (const asset of options.assets) {\n const rel = asset.sourcePath.split('\\\\').join('/');\n const declared = collectDeclaredRefFields(toDataJsonSchema(asset.schema));\n for (const missing of findMissingRefTargets(declared, assetNames)) {\n errors.push(\n `\"${rel}\" declares field \"${missing.fieldPath}\" as dataRef('${missing.targetStem}'), but ` +\n `no \"src/data/${missing.targetStem}.data.json\" exists. Restore/rename the target file, ` +\n `or update the dataRef('${missing.targetStem}') call in the schema.`,\n );\n }\n }\n\n return { errors, warnings };\n}\n\n/** True iff a bundled module id is tool code that must never ship (\u00A74). Pure, unit-tested. */\nexport function isToolModuleId(id: string): boolean {\n const normalized = id.split('\\\\').join('/');\n return /\\/src\\/tools\\//.test(normalized) || /\\.tool\\.[tj]sx?(\\?|$)/.test(normalized);\n}\n\n/**\n * Build-path validation plugin \u2014 see the module doc. Wire it in the project's\n * `vite.config.ts`, passing the data-asset registry:\n *\n * ```ts\n * import { vgaiDataCheck } from '@vgai/engine/data/vite-plugin-data';\n * import { dataAssets } from './src/data/assets';\n * export default defineConfig({\n * plugins: [vgaiDataCheck({\n * root: __dirname,\n * assets: dataAssets.map((a) => ({ schema: a.schema, sourcePath: `src/data/${a.name}.data.json` })),\n * })],\n * });\n * ```\n */\nexport function vgaiDataCheck(options: VgaiDataCheckOptions): Plugin {\n return {\n name: 'vgai:data-check',\n apply: 'build',\n async buildStart() {\n const { errors, warnings } = await collectDataCheckProblems(options);\n for (const warning of warnings) this.warn(warning);\n if (errors.length > 0) {\n // ONE error carrying every problem \u2014 fail loud with the full picture,\n // not a fix-one-rebuild-see-the-next loop.\n this.error(\n `data-asset validation failed (${errors.length} problem${errors.length === 1 ? '' : 's'}` +\n `):\\n${errors.map((e) => ` - ${e}`).join('\\n')}`,\n );\n }\n },\n generateBundle(_outputOptions, bundle) {\n const leaked = new Set<string>();\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk') continue;\n for (const id of Object.keys(output.modules)) {\n if (isToolModuleId(id)) leaked.add(id.split('\\\\').join('/'));\n }\n }\n if (leaked.size > 0) {\n this.error(\n 'project tool code reached the game build \u2014 tools are editor-only and must never ship ' +\n 'to players. Remove every game-code import of these ' +\n `modules (tools may import game code, never the reverse):\\n${[...leaked]\n .map((id) => ` - ${id}`)\n .join('\\n')}`,\n );\n }\n },\n };\n}\n"],
5
5
  "mappings": ";AAoCA,SAAS,SAAS;AA0BlB,IAAM,iBAAiB;AAEvB,SAAS,UAAU,MAAiB,MAAyB;AAC3D,SAAO,KAAK,IAAI,EAAE,SAAS;AAC7B;AAGA,SAAS,YAAY,OAAmB,MAAiB,KAA4B;AACnF,QAAM,SAAS,MAAM;AACrB,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AACtC,UAAM,QAAQ,OAAO,CAAC;AACtB,eAAW,QAAQ,CAAC,KAAK,GAAG,GAAY;AACtC,YAAM,EAAE,KAAK,IAAI,IAAI,KAAK,IAAI;AAC9B,UAAI,MAAM,IAAI,IAAI,OAAO,MAAM,IAAI,IAAI,KAAK;AAC1C,YAAI,SAAS;AAAA,UACX,MAAM;AAAA,UACN,MAAM,CAAC,UAAU,GAAG,IAAI;AAAA,UACxB,SACE,GAAG,MAAM,IAAI,CAAC,4BAA4B,UAAU,MAAM,IAAI,CAAC,YAC3D,GAAG,KAAK,GAAG,uFACI,IAAI;AAAA,QAC3B,CAAC;AAAA,MACH;AAAA,IACF;AACA,QAAI,MAAM,EAAG;AACb,UAAM,WAAW,OAAO,IAAI,CAAC;AAC7B,QAAI,MAAM,KAAK,SAAS,GAAG;AACzB,UAAI,SAAS;AAAA,QACX,MAAM;AAAA,QACN,MAAM,CAAC,UAAU,GAAG,GAAG;AAAA,QACvB,SACE,GAAG,MAAM,CAAC,0DAA0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