@scenoco-three/compiler 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SceNoCo contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # @scenoco-three/compiler
2
+
3
+ The **build-time** toolchain for [SceNoCo](https://github.com/): the XML parser, the
4
+ validator, the scene compiler, the optimized bundle encoder, the XSD/docs exporters,
5
+ component discovery, a file watcher, and the `scenoco` CLI. None of this ships to the
6
+ browser — the runtime (`@scenoco-three/core`) loads only the compiled bundle.
7
+
8
+ ```bash
9
+ scenoco init my-app # scaffold a runnable project
10
+ scenoco validate scene.xml --components src # "tsc for scenes": file:line:col diagnostics
11
+ scenoco bundle scene.xml -o scene.bundle.json
12
+ scenoco export --out schema --components src # scene.xsd + component-api.md
13
+ ```
14
+
15
+ ```ts
16
+ import { compileSceneXml, bundleScene } from '@scenoco-three/compiler';
17
+ const result = compileSceneXml(xml, { path, resolve });
18
+ if (result.ok) writeFileSync('scene.bundle.json', JSON.stringify(bundleScene(result.scene)));
19
+ ```
20
+
21
+ The validator never fail-fasts — one pass returns every problem, each with a position and a
22
+ fix-it message. The validator, compiler, and exporters are all generated views of the same
23
+ registry as the runtime, so the schema cannot drift.
24
+
25
+ See the [repository](../../README.md) and [ARCHITECTURE.md](../../ARCHITECTURE.md).
26
+
27
+ ## License
28
+
29
+ [MIT](./LICENSE)
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,373 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, resolve } from 'node:path';
4
+ import { scaffoldFiles, componentFile, sceneFile } from './templates.js';
5
+ import { deserializeBundle } from '@scenoco-three/core';
6
+ import { bundlePrefab, bundleScene, compilePrefabXml, compileSceneXml, formatDiagnostic, generateDocs, generateXsd, loadComponents, serializeScene, watchSceneFiles, } from '../index.js';
7
+ /** Loads `src=` resources from disk, relative to the referencing file. */
8
+ const fsResolver = (request, referrer) => {
9
+ const path = resolve(referrer ? dirname(referrer) : '.', request);
10
+ return existsSync(path) ? { path, contents: readFileSync(path, 'utf8') } : null;
11
+ };
12
+ /** A `.prefab.xml` file compiles as a standalone, dynamically-instantiable prefab. */
13
+ const isPrefabFile = (file) => file.endsWith('.prefab.xml');
14
+ function compileFile(file, xml, options) {
15
+ return isPrefabFile(file) ? compilePrefabXml(xml, options) : compileSceneXml(xml, options);
16
+ }
17
+ function bundleFor(file, scene) {
18
+ return isPrefabFile(file) ? bundlePrefab(scene) : bundleScene(scene);
19
+ }
20
+ const USAGE = `scenoco — Scene · Node · Component CLI
21
+
22
+ Usage:
23
+ scenoco init [dir] Scaffold a new SceNoCo project (default: current dir)
24
+ scenoco new component <Name> Generate src/components/<Name>.ts boilerplate
25
+ scenoco new scene <name> [--type <t>] Generate src/scenes/<name>.scene.xml skeleton
26
+ Types: basic (default), breakout, rpg, platformer
27
+ scenoco check Pre-flight: @system co-location, camera, physics
28
+ scenoco validate <file...> Validate scene XML; prints file:line:col diagnostics
29
+ scenoco bundle <file> [-o out] Build an optimized runtime bundle (default: <file>.bundle.json)
30
+ scenoco compile <file> [-o out] Compile to the raw CompiledScene JSON, for debugging
31
+ scenoco decompile <json> [-o out] Turn a bundle/CompiledScene JSON back into canonical scene XML
32
+ scenoco watch <file...> [--out dir] [--mode bundle|compiled]
33
+ Watch scenes and rebuild on XML/resource updates
34
+ scenoco export [--out <dir>] [--compact] Write scene.xsd + component-api.md (default: ./schema)
35
+ --compact: minimal API reference for agent system prompts
36
+
37
+ Options:
38
+ --components <dirs> Comma-separated directories scanned for @component classes
39
+ (default: "src"). They are compiled and registered so scenes
40
+ can reference them and the exporters can document them.
41
+
42
+ Exit code is non-zero when validation fails — wire it into your edit→check→fix loop.`;
43
+ // Commands that don't need the project's components registered first.
44
+ const SKIP_COMPONENT_LOAD = new Set(['init', 'new']);
45
+ async function main(argv) {
46
+ // Strip the global --components flag; commands re-parse their own flags.
47
+ const { positionals, options } = parseArgs(argv, { '--components': 'components' });
48
+ const [command, ...rest] = positionals;
49
+ if (command !== undefined && command !== '-h' && command !== '--help' && !SKIP_COMPONENT_LOAD.has(command)) {
50
+ const roots = (options.components ?? 'src')
51
+ .split(',')
52
+ .map((s) => s.trim())
53
+ .filter(Boolean);
54
+ await loadComponents(roots);
55
+ }
56
+ switch (command) {
57
+ case 'init':
58
+ return cmdInit(rest);
59
+ case 'new':
60
+ return cmdNew(rest);
61
+ case 'check':
62
+ return await cmdCheck(rest, options);
63
+ case 'validate':
64
+ return cmdValidate(rest);
65
+ case 'bundle':
66
+ return cmdBundle(rest);
67
+ case 'compile':
68
+ return cmdCompile(rest);
69
+ case 'decompile':
70
+ return cmdDecompile(rest);
71
+ case 'watch':
72
+ return cmdWatch(rest);
73
+ case 'export':
74
+ return cmdExport(rest);
75
+ case undefined:
76
+ case '-h':
77
+ case '--help':
78
+ console.log(USAGE);
79
+ return command === undefined ? 1 : 0;
80
+ default:
81
+ console.error(`Unknown command "${command}".\n\n${USAGE}`);
82
+ return 1;
83
+ }
84
+ }
85
+ function cmdInit(args) {
86
+ const { positionals } = parseArgs(args, {});
87
+ const dir = resolve(positionals[0] ?? '.');
88
+ const name = basename(dir).replace(/[^a-z0-9-]/gi, '-').toLowerCase() || 'scenoco-app';
89
+ const files = scaffoldFiles(name);
90
+ let written = 0;
91
+ let skipped = 0;
92
+ for (const [rel, content] of Object.entries(files)) {
93
+ const path = resolve(dir, rel);
94
+ if (existsSync(path)) {
95
+ console.warn(` skip ${rel} (already exists)`);
96
+ skipped++;
97
+ continue;
98
+ }
99
+ mkdirSync(dirname(path), { recursive: true });
100
+ writeFileSync(path, content);
101
+ console.log(` create ${rel}`);
102
+ written++;
103
+ }
104
+ console.log(`\n✓ scaffolded "${name}" (${written} files${skipped ? `, ${skipped} skipped` : ''})`);
105
+ console.log('\nNext:');
106
+ console.log(` ${dir === process.cwd() ? '' : `cd ${positionals[0] ?? '.'} && `}npm install`);
107
+ console.log(' npm run dev # http://localhost:5173');
108
+ console.log(' npm run validate # check scenes');
109
+ console.log(' npm run export # generate schema/ (XSD + component-api.md)');
110
+ return 0;
111
+ }
112
+ function cmdValidate(args) {
113
+ if (args.length === 0) {
114
+ console.error('validate: expected at least one file');
115
+ return 1;
116
+ }
117
+ let totalErrors = 0;
118
+ for (const file of args) {
119
+ const path = resolve(file);
120
+ // Compile (validate + resolve referenced files) but discard the output.
121
+ const result = compileFile(file, readFileSync(path, 'utf8'), { path, resolve: fsResolver });
122
+ if (!result.ok) {
123
+ for (const d of result.diagnostics)
124
+ console.error(formatDiagnostic(d, file));
125
+ totalErrors += result.diagnostics.length;
126
+ }
127
+ }
128
+ if (totalErrors === 0) {
129
+ console.log(`✓ ${args.length} file(s) valid`);
130
+ return 0;
131
+ }
132
+ console.error(`\n✗ ${totalErrors} problem(s) in ${args.length} file(s)`);
133
+ return 1;
134
+ }
135
+ function cmdBundle(args) {
136
+ return buildCommand(args, 'bundle', '.bundle.json', (file, scene) => JSON.stringify(bundleFor(file, scene)));
137
+ }
138
+ function cmdCompile(args) {
139
+ return buildCommand(args, 'compile', '.json', (_file, scene) => JSON.stringify(scene));
140
+ }
141
+ /** Inverse of compile/bundle: JSON → canonical scene XML. */
142
+ function cmdDecompile(args) {
143
+ const { positionals, options } = parseArgs(args, { '-o': 'out', '--out': 'out' });
144
+ const file = positionals[0];
145
+ if (!file) {
146
+ console.error('decompile: expected a .bundle.json or compiled .json file');
147
+ return 1;
148
+ }
149
+ const data = JSON.parse(readFileSync(resolve(file), 'utf8'));
150
+ // A Bundle is a fixed-index array; a CompiledScene is an object.
151
+ const scene = Array.isArray(data) ? deserializeBundle(data) : data;
152
+ const out = resolve(options.out ?? file.replace(/(\.bundle)?\.json$/, '') + '.scene.xml');
153
+ writeFileSync(out, serializeScene(scene));
154
+ console.log(`✓ decompiled ${file} → ${out}`);
155
+ return 0;
156
+ }
157
+ /** Shared compile-then-write flow for the `bundle` and `compile` commands. */
158
+ function buildCommand(args, name, suffix, serialize) {
159
+ const { positionals, options } = parseArgs(args, { '-o': 'out', '--out': 'out' });
160
+ const file = positionals[0];
161
+ if (!file) {
162
+ console.error(`${name}: expected a file`);
163
+ return 1;
164
+ }
165
+ const path = resolve(file);
166
+ const result = compileFile(file, readFileSync(path, 'utf8'), { path, resolve: fsResolver });
167
+ if (!result.ok) {
168
+ for (const d of result.diagnostics)
169
+ console.error(formatDiagnostic(d, file));
170
+ console.error(`\n✗ cannot ${name} ${file}: ${result.diagnostics.length} problem(s)`);
171
+ return 1;
172
+ }
173
+ const out = resolve(options.out ?? `${file}${suffix}`);
174
+ writeFileSync(out, serialize(file, result.scene));
175
+ console.log(`✓ ${name === 'bundle' ? 'bundled' : 'compiled'} ${file} → ${out}`);
176
+ return 0;
177
+ }
178
+ function cmdNew(args) {
179
+ const [subCommand, name] = args;
180
+ if (!subCommand || !name) {
181
+ console.error('new: usage: scenoco new component <Name> | scenoco new scene <name> [--type basic|breakout|rpg|platformer]');
182
+ return 1;
183
+ }
184
+ if (subCommand === 'component') {
185
+ const path = resolve(`src/components/${name}.ts`);
186
+ if (existsSync(path)) {
187
+ console.error(`new: ${path} already exists`);
188
+ return 1;
189
+ }
190
+ mkdirSync(dirname(path), { recursive: true });
191
+ writeFileSync(path, componentFile(name));
192
+ console.log(`✓ created ${path}`);
193
+ console.log(` → add <${name} /> inside a <Components> block in your scene XML`);
194
+ return 0;
195
+ }
196
+ if (subCommand === 'scene') {
197
+ const { options } = parseArgs(args.slice(2), { '--type': 'type', '-t': 'type' });
198
+ const type = (options.type ?? 'basic');
199
+ const validTypes = ['basic', 'breakout', 'rpg', 'platformer'];
200
+ if (!validTypes.includes(type)) {
201
+ console.error(`new: unknown scene type "${type}". Valid: ${validTypes.join(', ')}`);
202
+ return 1;
203
+ }
204
+ const path = resolve(`src/scenes/${name}.scene.xml`);
205
+ if (existsSync(path)) {
206
+ console.error(`new: ${path} already exists`);
207
+ return 1;
208
+ }
209
+ mkdirSync(dirname(path), { recursive: true });
210
+ writeFileSync(path, sceneFile(name, type));
211
+ console.log(`✓ created ${path} (type: ${type})`);
212
+ console.log(` → import scene from './${name}.scene.xml?bundle'; in main.ts`);
213
+ if (type === 'breakout') {
214
+ console.log(` → call engine.setActiveCamera(engine.findObject('cam')!) after loadScene`);
215
+ }
216
+ if (type === 'rpg' || type === 'platformer') {
217
+ console.log(` → call await initRapier() before engine.loadScene() in main.ts`);
218
+ }
219
+ return 0;
220
+ }
221
+ console.error(`new: unknown sub-command "${subCommand}". Use "component" or "scene".`);
222
+ return 1;
223
+ }
224
+ async function cmdCheck(_args, options) {
225
+ const roots = (options.components ?? 'src')
226
+ .split(',')
227
+ .map((s) => s.trim())
228
+ .filter(Boolean);
229
+ const rf = readFileSync;
230
+ const res = resolve;
231
+ const SYSTEM_RE = /@system\s*\(/;
232
+ const COMPONENT_RE = /@component\s*\(/;
233
+ const NODE_TAG_RE = /@(?:node|attachment)\s*\(/;
234
+ const ORTHO_RE = /<OrthographicCamera/;
235
+ const PHYSICS_RE = /<Physics[\s/]/;
236
+ const SOURCE_EXT = /\.(?:[cm]?[jt]sx?)$/;
237
+ const SKIP = new Set(['.git', 'node_modules', 'dist', 'build', '.scenoco']);
238
+ let warnings = 0;
239
+ let checked = 0;
240
+ function walkFiles(dir) {
241
+ const out = [];
242
+ if (!existsSync(dir))
243
+ return out;
244
+ const stack = [dir];
245
+ while (stack.length > 0) {
246
+ const d = stack.pop();
247
+ for (const e of readdirSync(d, { withFileTypes: true })) {
248
+ if (e.isDirectory()) {
249
+ if (!SKIP.has(e.name))
250
+ stack.push(res(d, e.name));
251
+ }
252
+ else {
253
+ out.push(res(d, e.name));
254
+ }
255
+ }
256
+ }
257
+ return out;
258
+ }
259
+ console.log('Checking components...');
260
+ for (const root of roots) {
261
+ for (const f of walkFiles(res(process.cwd(), root))) {
262
+ if (!SOURCE_EXT.test(f) || f.endsWith('.d.ts'))
263
+ continue;
264
+ const src = rf(f, 'utf8');
265
+ checked++;
266
+ if (SYSTEM_RE.test(src) && !COMPONENT_RE.test(src) && !NODE_TAG_RE.test(src)) {
267
+ const rel = f.replace(process.cwd() + '/', '');
268
+ console.warn(` ✗ ${rel}: @system declared but no @component/@node in same file`);
269
+ console.warn(` → co-locate @system(T) with @component T or this file will be skipped`);
270
+ warnings++;
271
+ }
272
+ }
273
+ }
274
+ console.log('\nChecking scenes...');
275
+ let sceneCount = 0;
276
+ const seenScenes = new Set();
277
+ for (const root of roots) {
278
+ // Walk from the root's parent so sibling scenes/ directories are included,
279
+ // but deduplicate across roots so no file is checked twice.
280
+ const searchDir = res(process.cwd(), root, '..');
281
+ for (const f of walkFiles(searchDir)) {
282
+ if (seenScenes.has(f))
283
+ continue;
284
+ if (!f.endsWith('.scene.xml') && !f.endsWith('.prefab.xml'))
285
+ continue;
286
+ seenScenes.add(f);
287
+ const src = rf(f, 'utf8');
288
+ const rel = f.replace(process.cwd() + '/', '');
289
+ sceneCount++;
290
+ if (ORTHO_RE.test(src)) {
291
+ console.warn(` ⚠ ${rel}: uses <OrthographicCamera>`);
292
+ console.warn(` → call engine.setActiveCamera(engine.findObject('cam')!) in main.ts`);
293
+ warnings++;
294
+ }
295
+ if (PHYSICS_RE.test(src)) {
296
+ console.log(` ℹ ${rel}: uses <Physics> — ensure await initRapier() is in main.ts`);
297
+ }
298
+ }
299
+ }
300
+ console.log(`\n${warnings === 0 ? '✓' : '✗'} checked ${checked} source file(s) + ${sceneCount} scene(s)` +
301
+ (warnings > 0 ? `, ${warnings} warning(s)` : ' — no issues found'));
302
+ return warnings > 0 ? 1 : 0;
303
+ }
304
+ function cmdWatch(args) {
305
+ const { positionals, options } = parseArgs(args, {
306
+ '--out': 'out',
307
+ '-o': 'out',
308
+ '--mode': 'mode',
309
+ });
310
+ if (positionals.length === 0) {
311
+ console.error('watch: expected at least one file');
312
+ return 1;
313
+ }
314
+ const entries = positionals.map((f) => resolve(f));
315
+ const mode = options.mode === 'compiled' ? 'compiled' : 'bundle';
316
+ void watchSceneFiles(entries, {
317
+ outDir: options.out ? resolve(options.out) : undefined,
318
+ mode,
319
+ resolve: fsResolver,
320
+ onEvent(event) {
321
+ if (event.type === 'diagnostics') {
322
+ for (const d of event.diagnostics)
323
+ console.error(formatDiagnostic(d, event.file));
324
+ return;
325
+ }
326
+ if (event.type === 'success') {
327
+ console.log(`✓ rebuilt ${event.file} → ${event.outputPath} (${event.durationMs} ms)`);
328
+ return;
329
+ }
330
+ if (event.type === 'error') {
331
+ console.error(`✗ watch error in ${event.file}: ${event.message}`);
332
+ }
333
+ },
334
+ }).catch((e) => {
335
+ console.error(e instanceof Error ? e.message : String(e));
336
+ process.exitCode = 1;
337
+ });
338
+ console.log(`watching ${entries.length} file(s) (${mode})`);
339
+ return 0;
340
+ }
341
+ function cmdExport(args) {
342
+ const { options, positionals } = parseArgs(args, { '--out': 'out', '-o': 'out' });
343
+ const compact = positionals.includes('--compact');
344
+ const dir = resolve(options.out ?? 'schema');
345
+ write(`${dir}/scene.xsd`, generateXsd());
346
+ write(`${dir}/component-api.md`, generateDocs({ compact }));
347
+ const note = compact ? ' (compact mode — suitable for agent system prompts)' : '';
348
+ console.log(`✓ wrote scene.xsd and component-api.md to ${dir}${note}`);
349
+ return 0;
350
+ }
351
+ function write(path, content) {
352
+ mkdirSync(dirname(path), { recursive: true });
353
+ writeFileSync(path, content);
354
+ }
355
+ /** Minimal flag parser: maps known flags (with a value) to option keys. */
356
+ function parseArgs(args, flags) {
357
+ const positionals = [];
358
+ const options = {};
359
+ for (let i = 0; i < args.length; i++) {
360
+ const arg = args[i];
361
+ const key = flags[arg];
362
+ if (key) {
363
+ options[key] = args[++i] ?? '';
364
+ }
365
+ else {
366
+ positionals.push(arg);
367
+ }
368
+ }
369
+ return { positionals, options };
370
+ }
371
+ // Set the exit code but let the event loop drain naturally — `watch` keeps the
372
+ // process alive through its file watcher; every other command just finishes.
373
+ process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Files written by `scenoco init` — kept as a pure path→content map so the
3
+ * scaffold can be unit-tested without touching the filesystem. The result is a
4
+ * runnable SceNoCo project: a starter component, a scene that uses it, and the
5
+ * Vite wiring so `npm run dev` serves it with no XML parser in the browser.
6
+ */
7
+ export declare function scaffoldFiles(packageName: string, version?: string): Record<string, string>;
8
+ /** Generate a component file boilerplate. */
9
+ export declare function componentFile(name: string): string;
10
+ /** Generate a scene XML skeleton for a given game type. */
11
+ export declare function sceneFile(name: string, type?: 'basic' | 'rpg' | 'platformer' | 'breakout'): string;