@vibe-engine/cli 0.1.1 → 0.1.2
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/dist/assets.d.ts +1 -0
- package/dist/assets.js +13 -7
- package/dist/main.js +11 -4
- package/dist/run.d.ts +2 -0
- package/dist/run.js +1 -1
- package/dist/session-daemon.d.ts +1 -0
- package/dist/session-daemon.js +103 -0
- package/dist/session-host.d.ts +29 -0
- package/dist/session-host.js +226 -0
- package/dist/session.d.ts +6 -0
- package/dist/session.js +256 -0
- package/dist/typecheck.d.ts +15 -0
- package/dist/typecheck.js +68 -0
- package/package.json +4 -4
- package/templates/arena-3d/AGENTS.md +4 -4
- package/templates/platformer-2d/AGENTS.md +4 -4
- package/templates/shooter-2d-pvp/AGENTS.md +5 -4
- package/templates/shooter-2d-pvp/src/listeners/players.listener.ts +3 -2
- package/templates/shooter-2d-pvp/src/systems/gun.system.ts +3 -0
- package/templates/shooter-2d-pvp/tests/pvp.test.ts +25 -0
package/dist/assets.d.ts
CHANGED
package/dist/assets.js
CHANGED
|
@@ -5,6 +5,7 @@ import { join } from 'node:path';
|
|
|
5
5
|
import { SHADER_PRESETS, shaderProblems, uiThemeAssets } from '@vibe-engine/core';
|
|
6
6
|
import { PROJECT_ERRORS, createWorld, loadProject, walk } from './project.js';
|
|
7
7
|
import { checkBoundaries } from './boundary.js';
|
|
8
|
+
import { typecheck } from './typecheck.js';
|
|
8
9
|
import { withSource } from './source.js';
|
|
9
10
|
export const assets = defineCommand({
|
|
10
11
|
name: 'assets',
|
|
@@ -24,11 +25,12 @@ export const assets = defineCommand({
|
|
|
24
25
|
});
|
|
25
26
|
export const check = defineCommand({
|
|
26
27
|
name: 'check',
|
|
27
|
-
summary: 'Load the project and every scene (setup + first tick) and report every problem: discovery, assets, ids, setup errors, client/server boundary',
|
|
28
|
-
flags: {},
|
|
29
|
-
output: { ok: 'true when there are no problems', scenes: 'scenes checked', assets: 'assets in the catalog' },
|
|
30
|
-
errors: { ...PROJECT_ERRORS, 'check-failed': 'one or more problems; detail.problems lists each with code (scene-failed, boundary-violation, asset-missing, shader-missing, shader-invalid...), scene and source' },
|
|
31
|
-
async run({ io }) {
|
|
28
|
+
summary: 'Load the project and every scene (setup + first tick) and report every problem: TypeScript errors, discovery, assets, ids, setup errors, client/server boundary',
|
|
29
|
+
flags: { types: { type: 'boolean', default: true, doc: 'run the TypeScript typecheck (--no-types skips it)' } },
|
|
30
|
+
output: { ok: 'true when there are no problems', scenes: 'scenes checked', assets: 'assets in the catalog', typecheck: "'ok', or why it did not run (no typescript in the project, --no-types)" },
|
|
31
|
+
errors: { ...PROJECT_ERRORS, 'check-failed': 'one or more problems; detail.problems lists each with code (type-error, scene-failed, boundary-violation, asset-missing, shader-missing, shader-invalid...), scene and source (file:line[:column])' },
|
|
32
|
+
async run({ flags, io }) {
|
|
33
|
+
const types = flags.types ? typecheck(io.cwd) : null; // em paralelo com o resto
|
|
32
34
|
const project = await loadProject(io.cwd); // problema de projeto: um erro só, com o código dele
|
|
33
35
|
const problems = [];
|
|
34
36
|
const shaders = { ...SHADER_PRESETS, ...Object.fromEntries(project.shaders.map((s) => [s.id, s.def])) };
|
|
@@ -61,6 +63,10 @@ export const check = defineCommand({
|
|
|
61
63
|
for (const b of existsSync(src) ? checkBoundaries(io.cwd, walk(src)) : []) {
|
|
62
64
|
problems.push({ code: 'boundary-violation', message: `${b.file}:${b.line}: ${b.rule} ('${b.target}')`, source: `${b.file}:${b.line}` });
|
|
63
65
|
}
|
|
66
|
+
const tc = types ? await types : { ran: false, reason: 'skipped (--no-types)' };
|
|
67
|
+
// Erros de tipo primeiro: muitas vezes explicam a falha de cena logo abaixo.
|
|
68
|
+
if (tc.ran)
|
|
69
|
+
problems.unshift(...tc.errors.map((e) => ({ code: 'type-error', message: `${e.file}:${e.line}:${e.column}: ${e.code} ${e.message}`, source: `${e.file}:${e.line}:${e.column}` })));
|
|
64
70
|
if (problems.length) {
|
|
65
71
|
throw new CliError('check-failed', `${problems.length} problem${problems.length > 1 ? 's' : ''}`, {
|
|
66
72
|
detail: { problems },
|
|
@@ -68,9 +74,9 @@ export const check = defineCommand({
|
|
|
68
74
|
hint: problems.map((p) => (p.scene ? `${p.scene}: ${p.message}` : p.message)).join(' | '),
|
|
69
75
|
});
|
|
70
76
|
}
|
|
71
|
-
return { ok: true, scenes: project.scenes.length, assets: project.assets.length };
|
|
77
|
+
return { ok: true, scenes: project.scenes.length, assets: project.assets.length, typecheck: tc.ran ? 'ok' : tc.reason };
|
|
72
78
|
},
|
|
73
79
|
human(o) {
|
|
74
|
-
return `ok · ${o.scenes} scenes · ${o.assets} assets`;
|
|
80
|
+
return `ok · ${o.scenes} scenes · ${o.assets} assets · types ${o.typecheck}`;
|
|
75
81
|
},
|
|
76
82
|
});
|
package/dist/main.js
CHANGED
|
@@ -9,6 +9,7 @@ import { build, dev } from './web.js';
|
|
|
9
9
|
import { create } from './create.js';
|
|
10
10
|
import { serve } from './serve.js';
|
|
11
11
|
import { testCmd } from './test-run.js';
|
|
12
|
+
import { SESSION_COMMANDS } from './session.js';
|
|
12
13
|
const describe = (c) => ({
|
|
13
14
|
name: c.name,
|
|
14
15
|
summary: c.summary,
|
|
@@ -20,12 +21,12 @@ const describe = (c) => ({
|
|
|
20
21
|
const help = defineCommand({
|
|
21
22
|
name: 'help',
|
|
22
23
|
summary: 'List commands with their flags, output fields and error codes',
|
|
23
|
-
positionals: [{ name: 'command', doc: 'show a single command' }],
|
|
24
|
+
positionals: [{ name: 'command', doc: 'show a single command' }, { name: 'subcommand', doc: "for two-word commands ('session step')" }],
|
|
24
25
|
flags: { tree: { type: 'boolean', default: false, doc: 'every command with its full schema (with --json)' } },
|
|
25
26
|
output: { commands: 'commands with name, summary, positionals, flags, output and errors' },
|
|
26
27
|
errors: {},
|
|
27
28
|
async run({ positionals }) {
|
|
28
|
-
const name = positionals
|
|
29
|
+
const name = positionals.length ? positionals.join(' ') : undefined;
|
|
29
30
|
if (name === undefined)
|
|
30
31
|
return { commands: COMMANDS.map(describe) };
|
|
31
32
|
const cmd = COMMANDS.find((c) => c.name === name);
|
|
@@ -35,15 +36,18 @@ const help = defineCommand({
|
|
|
35
36
|
},
|
|
36
37
|
human({ commands }) {
|
|
37
38
|
if (commands.length > 1)
|
|
38
|
-
return ['vibe <command> [flags] (add --json for machine output)', '', ...commands.map((c) => ` ${c.name.padEnd(
|
|
39
|
+
return ['vibe <command> [flags] (add --json for machine output)', '', ...commands.map((c) => ` ${c.name.padEnd(16)} ${c.summary}`), '', 'vibe help <command> shows flags and error codes.'].join('\n');
|
|
39
40
|
const c = commands[0];
|
|
40
41
|
const flags = Object.entries(c.flags).map(([n, f]) => ` --${n} <${f.type}>${f.default !== undefined ? ` (default ${f.default})` : ''}\n ${f.doc}`);
|
|
41
42
|
const errors = Object.entries(c.errors).map(([code, when]) => ` ${code.padEnd(18)} ${when}`);
|
|
42
43
|
return [`vibe ${c.name} — ${c.summary}`, '', 'flags:', ...flags, '', 'errors:', ...errors].join('\n');
|
|
43
44
|
},
|
|
44
45
|
});
|
|
45
|
-
export const COMMANDS = [create, run, testCmd, dev, serve, build, info, assets, check, map, help];
|
|
46
|
+
export const COMMANDS = [create, run, testCmd, dev, serve, build, info, assets, check, map, ...SESSION_COMMANDS, help];
|
|
46
47
|
function unknownCommand(name) {
|
|
48
|
+
const group = COMMANDS.filter((c) => c.name.startsWith(`${name} `));
|
|
49
|
+
if (group.length)
|
|
50
|
+
return new CliError('unknown-command', `'${name}' needs a subcommand`, { expected: group.map((c) => c.name).join(' | '), hint: `vibe help ${group[0].name}` });
|
|
47
51
|
return new CliError('unknown-command', `unknown command '${name}'`, { expected: COMMANDS.map((c) => c.name).join(' | '), hint: 'vibe help --tree --json lists every command' });
|
|
48
52
|
}
|
|
49
53
|
/** Roda a CLI e devolve o exit code: 0 ok, 1 erro do comando, 2 uso errado. */
|
|
@@ -53,6 +57,9 @@ export async function main(argv, io) {
|
|
|
53
57
|
let [name = 'help', ...rest] = argv;
|
|
54
58
|
if (name.startsWith('-'))
|
|
55
59
|
[name, rest] = ['help', argv];
|
|
60
|
+
// Comandos de duas palavras ('session step'): o segundo argumento faz parte do nome.
|
|
61
|
+
if (rest[0] && !rest[0].startsWith('-') && COMMANDS.some((c) => c.name === `${name} ${rest[0]}`))
|
|
62
|
+
[name, rest] = [`${name} ${rest[0]}`, rest.slice(1)];
|
|
56
63
|
const cmd = COMMANDS.find((c) => c.name === name);
|
|
57
64
|
if (!cmd)
|
|
58
65
|
throw unknownCommand(name);
|
package/dist/run.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type World } from '@vibe-engine/core';
|
|
1
2
|
export interface RunOutput {
|
|
2
3
|
runId: string;
|
|
3
4
|
scene: string;
|
|
@@ -16,3 +17,4 @@ export interface RunOutput {
|
|
|
16
17
|
};
|
|
17
18
|
}
|
|
18
19
|
export declare const run: import("./registry.ts").CommandSpec<RunOutput>;
|
|
20
|
+
export declare function pickScene(world: World, scene: string | undefined): string;
|
package/dist/run.js
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Processo de uma sessão (`vibe session start` o cria, separado do terminal).
|
|
3
|
+
* Protocolo RFC-003: POST /rpc com `{ protocolVersion: 1, requestId, method, payload }`
|
|
4
|
+
* e `Authorization: Bearer <token>`, só em 127.0.0.1. O token e a porta ficam em
|
|
5
|
+
* `.vibe/sessions/<id>.json` (modo 600). Sem chamadas por `idleMinutes`, sai sozinho.
|
|
6
|
+
*/
|
|
7
|
+
import { createServer } from 'node:http';
|
|
8
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
11
|
+
import { CliError } from './registry.js';
|
|
12
|
+
import { PROTOCOL_VERSION, createSessionHost, sessionsDir } from './session-host.js';
|
|
13
|
+
const MAX_BODY = 1 << 20;
|
|
14
|
+
const opts = JSON.parse(process.argv[2]);
|
|
15
|
+
const ipc = (m) => process.send?.(m);
|
|
16
|
+
let host;
|
|
17
|
+
try {
|
|
18
|
+
host = await createSessionHost(opts);
|
|
19
|
+
}
|
|
20
|
+
catch (err) {
|
|
21
|
+
const e = err instanceof CliError ? err : new CliError('internal', err.message);
|
|
22
|
+
ipc({ error: e.toJSON().error });
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
const token = randomBytes(24).toString('hex');
|
|
26
|
+
const file = join(sessionsDir(opts.root), `${opts.id}.json`);
|
|
27
|
+
let idle;
|
|
28
|
+
const touch = () => {
|
|
29
|
+
clearTimeout(idle);
|
|
30
|
+
idle = setTimeout(() => shutdown(), opts.idleMinutes * 60_000);
|
|
31
|
+
};
|
|
32
|
+
const shutdown = () => {
|
|
33
|
+
host.close();
|
|
34
|
+
rmSync(file, { force: true });
|
|
35
|
+
rmSync(file.replace(/\.json$/, '.log'), { force: true }); // fechou limpo: o log só fica quando o processo morre
|
|
36
|
+
server.close();
|
|
37
|
+
process.exit(0);
|
|
38
|
+
};
|
|
39
|
+
const authorized = (header) => {
|
|
40
|
+
const want = Buffer.from(`Bearer ${token}`);
|
|
41
|
+
const got = Buffer.from(header ?? '');
|
|
42
|
+
return got.length === want.length && timingSafeEqual(got, want);
|
|
43
|
+
};
|
|
44
|
+
const server = createServer((req, res) => {
|
|
45
|
+
const reply = (status, body) => {
|
|
46
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
47
|
+
res.end(JSON.stringify(body));
|
|
48
|
+
};
|
|
49
|
+
// Host diferente de 127.0.0.1:porta = página de outro site tentando falar com a sessão (DNS rebinding).
|
|
50
|
+
if (req.method !== 'POST' || req.url !== '/rpc' || req.headers.host !== `127.0.0.1:${port}`)
|
|
51
|
+
return reply(404, { ok: false });
|
|
52
|
+
if (!authorized(req.headers.authorization))
|
|
53
|
+
return reply(401, { ok: false, error: { code: 'session-unauthorized', message: 'missing or wrong session token' } });
|
|
54
|
+
let size = 0;
|
|
55
|
+
const chunks = [];
|
|
56
|
+
req.on('data', (c) => {
|
|
57
|
+
size += c.length;
|
|
58
|
+
if (size > MAX_BODY)
|
|
59
|
+
req.destroy();
|
|
60
|
+
else
|
|
61
|
+
chunks.push(c);
|
|
62
|
+
});
|
|
63
|
+
req.on('end', async () => {
|
|
64
|
+
touch();
|
|
65
|
+
let msg;
|
|
66
|
+
try {
|
|
67
|
+
msg = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return reply(400, { ok: false, error: { code: 'usage', message: 'body is not JSON' } });
|
|
71
|
+
}
|
|
72
|
+
const requestId = typeof msg.requestId === 'string' ? msg.requestId : null;
|
|
73
|
+
if (msg.protocolVersion !== PROTOCOL_VERSION)
|
|
74
|
+
return reply(400, { requestId, ok: false, error: { code: 'protocol-mismatch', message: `session speaks protocol ${PROTOCOL_VERSION}, got ${msg.protocolVersion}`, hint: 'the CLI and the session come from different engine versions: stop the session and start it again' } });
|
|
75
|
+
if (typeof msg.method !== 'string' || (msg.payload !== undefined && (typeof msg.payload !== 'object' || msg.payload === null)))
|
|
76
|
+
return reply(400, { requestId, ok: false, error: { code: 'usage', message: 'expected { method: string, payload?: object }' } });
|
|
77
|
+
if (msg.method === 'stop') {
|
|
78
|
+
reply(200, { requestId, ok: true, result: { session: opts.id, stopped: true } });
|
|
79
|
+
return setImmediate(shutdown);
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
reply(200, { requestId, ok: true, result: await host.call(msg.method, (msg.payload ?? {})) });
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
const e = err instanceof CliError ? err : new CliError('internal', err.message);
|
|
86
|
+
reply(200, { requestId, ok: false, error: e.toJSON().error });
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
let port = 0;
|
|
91
|
+
server.listen(0, '127.0.0.1', () => {
|
|
92
|
+
port = server.address().port;
|
|
93
|
+
const status = host.call('status', {});
|
|
94
|
+
void status.then((s) => {
|
|
95
|
+
const info = { id: opts.id, pid: process.pid, port, token, scene: s.scene, seed: s.seed, startedAt: new Date().toISOString() };
|
|
96
|
+
mkdirSync(sessionsDir(opts.root), { recursive: true });
|
|
97
|
+
writeFileSync(file, JSON.stringify(info, null, 2), { mode: 0o600 });
|
|
98
|
+
touch();
|
|
99
|
+
ipc({ ready: info });
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
process.on('SIGTERM', shutdown);
|
|
103
|
+
process.on('SIGINT', shutdown);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export declare const PROTOCOL_VERSION = 1;
|
|
2
|
+
/** O que `.vibe/sessions/<id>.json` guarda: como achar e falar com a sessão. */
|
|
3
|
+
export interface SessionFile {
|
|
4
|
+
id: string;
|
|
5
|
+
pid: number;
|
|
6
|
+
port: number;
|
|
7
|
+
token: string;
|
|
8
|
+
scene: string;
|
|
9
|
+
seed: number;
|
|
10
|
+
startedAt: string;
|
|
11
|
+
}
|
|
12
|
+
export declare const sessionsDir: (root: string) => string;
|
|
13
|
+
export interface SessionOptions {
|
|
14
|
+
id: string;
|
|
15
|
+
root: string;
|
|
16
|
+
scene?: string;
|
|
17
|
+
seed?: number;
|
|
18
|
+
saveDir?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface SessionEvent {
|
|
21
|
+
frame: number;
|
|
22
|
+
name: string;
|
|
23
|
+
payload: unknown;
|
|
24
|
+
}
|
|
25
|
+
export interface SessionHost {
|
|
26
|
+
call(method: string, payload: Record<string, unknown>): Promise<object>;
|
|
27
|
+
close(): void;
|
|
28
|
+
}
|
|
29
|
+
export declare function createSessionHost(opts: SessionOptions): Promise<SessionHost>;
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sessão viva (#31, #33, #34): um World do projeto, parado no tick 0, que só
|
|
3
|
+
* anda com `step` (ou `resume`, em tempo real). Toda resposta leva `frame` e
|
|
4
|
+
* `revision`; quem manda `revision` antiga num comando que muda o estado recebe
|
|
5
|
+
* `session-revision-stale` em vez de agir sobre um estado que não viu.
|
|
6
|
+
*
|
|
7
|
+
* Roda no processo da sessão (`session-daemon.ts`); os testes chamam direto.
|
|
8
|
+
*/
|
|
9
|
+
import { join, resolve } from 'node:path';
|
|
10
|
+
import { LOCAL_PLAYER } from '@vibe-engine/core';
|
|
11
|
+
import { CliError } from './registry.js';
|
|
12
|
+
import { createWorld, loadProject } from './project.js';
|
|
13
|
+
import { withSource } from './source.js';
|
|
14
|
+
import { fileSaveStore } from './save-store.js';
|
|
15
|
+
import { pickScene } from './run.js';
|
|
16
|
+
export const PROTOCOL_VERSION = 1;
|
|
17
|
+
export const sessionsDir = (root) => join(root, '.vibe', 'sessions');
|
|
18
|
+
/** Eventos guardados pela sessão (os mais antigos saem primeiro). */
|
|
19
|
+
const EVENT_LOG_MAX = 5000;
|
|
20
|
+
const MUTATING = new Set(['step', 'resume', 'reset', 'input']);
|
|
21
|
+
export async function createSessionHost(opts) {
|
|
22
|
+
const project = await loadProject(opts.root);
|
|
23
|
+
let seed = opts.seed ?? 1;
|
|
24
|
+
let scene = '';
|
|
25
|
+
let world = null;
|
|
26
|
+
let revision = 0;
|
|
27
|
+
let timer = null;
|
|
28
|
+
let lastError = null;
|
|
29
|
+
const log = [];
|
|
30
|
+
const fail = (err) => {
|
|
31
|
+
const e = err;
|
|
32
|
+
const src = withSource(e, opts.root);
|
|
33
|
+
lastError = { frame: world.frame, message: e.message, ...src };
|
|
34
|
+
throw new CliError('world-error', e.message, { detail: { frame: world.frame }, ...src, hint: 'fix the file in source, then `vibe session reset` (the state is inconsistent after an error)' });
|
|
35
|
+
};
|
|
36
|
+
async function open(nextScene, nextSeed) {
|
|
37
|
+
const w = await createWorld(project, nextSeed, opts.saveDir ? { saves: fileSaveStore(resolve(opts.root, opts.saveDir)) } : {});
|
|
38
|
+
const s = pickScene(w, nextScene ?? project.config.startScene);
|
|
39
|
+
world = w;
|
|
40
|
+
seed = nextSeed;
|
|
41
|
+
scene = s;
|
|
42
|
+
log.length = 0;
|
|
43
|
+
lastError = null;
|
|
44
|
+
await world.start(s).catch(fail);
|
|
45
|
+
}
|
|
46
|
+
function step(frames) {
|
|
47
|
+
for (let i = 0; i < frames; i++) {
|
|
48
|
+
const from = world.frame;
|
|
49
|
+
try {
|
|
50
|
+
world.step(1);
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
revision++;
|
|
54
|
+
fail(err);
|
|
55
|
+
}
|
|
56
|
+
for (const e of world.observe({ entityIds: [], sinceFrame: from }).events)
|
|
57
|
+
log.push({ frame: e.frame, name: e.name, payload: e.payload });
|
|
58
|
+
}
|
|
59
|
+
if (log.length > EVENT_LOG_MAX)
|
|
60
|
+
log.splice(0, log.length - EVENT_LOG_MAX);
|
|
61
|
+
revision++;
|
|
62
|
+
}
|
|
63
|
+
const pause = () => {
|
|
64
|
+
if (timer)
|
|
65
|
+
clearInterval(timer);
|
|
66
|
+
timer = null;
|
|
67
|
+
};
|
|
68
|
+
const head = () => ({ session: opts.id, frame: world.frame, revision });
|
|
69
|
+
const status = () => ({
|
|
70
|
+
...head(),
|
|
71
|
+
scene: world.sceneControl.id ?? scene,
|
|
72
|
+
seed,
|
|
73
|
+
running: timer !== null,
|
|
74
|
+
simTimeMs: (world.frame * 1000) / world.tickRate,
|
|
75
|
+
tickRate: world.tickRate,
|
|
76
|
+
hash: world.hash(),
|
|
77
|
+
entities: Object.keys(world.observe({ components: [] }).entities).length,
|
|
78
|
+
error: lastError,
|
|
79
|
+
});
|
|
80
|
+
await open(opts.scene, seed);
|
|
81
|
+
const methods = {
|
|
82
|
+
status,
|
|
83
|
+
step(p) {
|
|
84
|
+
if (timer)
|
|
85
|
+
throw new CliError('session-running', 'the session is running in real time', { hint: 'vibe session pause, then step' });
|
|
86
|
+
const frames = p.frames ?? 1;
|
|
87
|
+
if (!Number.isInteger(frames) || frames < 0)
|
|
88
|
+
throw new CliError('usage', `frames must be a non-negative integer, got ${frames}`, { expected: 'integer >= 0' });
|
|
89
|
+
const from = world.frame;
|
|
90
|
+
step(frames);
|
|
91
|
+
const counts = {};
|
|
92
|
+
for (const e of log)
|
|
93
|
+
if (e.frame >= from)
|
|
94
|
+
counts[e.name] = (counts[e.name] ?? 0) + 1;
|
|
95
|
+
return { ...status(), stepped: frames, events: counts };
|
|
96
|
+
},
|
|
97
|
+
pause() {
|
|
98
|
+
pause();
|
|
99
|
+
return status();
|
|
100
|
+
},
|
|
101
|
+
resume() {
|
|
102
|
+
if (!timer) {
|
|
103
|
+
timer = setInterval(() => {
|
|
104
|
+
try {
|
|
105
|
+
step(1);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
pause(); // o erro fica em `status().error`
|
|
109
|
+
}
|
|
110
|
+
}, 1000 / world.tickRate);
|
|
111
|
+
}
|
|
112
|
+
return status();
|
|
113
|
+
},
|
|
114
|
+
async reset(p) {
|
|
115
|
+
pause();
|
|
116
|
+
if (p.seed !== undefined && !Number.isInteger(p.seed))
|
|
117
|
+
throw new CliError('usage', `seed must be an integer, got ${p.seed}`, { expected: 'integer' });
|
|
118
|
+
await open(p.scene ?? scene, p.seed ?? seed);
|
|
119
|
+
revision++;
|
|
120
|
+
return status();
|
|
121
|
+
},
|
|
122
|
+
input(p) {
|
|
123
|
+
const changes = Array.isArray(p.changes) ? toChanges(p.changes) : single(p);
|
|
124
|
+
for (const c of changes) {
|
|
125
|
+
checkValue(c.action, c.value);
|
|
126
|
+
if (c.frame < world.frame)
|
|
127
|
+
throw new CliError('input-invalid', `change for tick ${c.frame} is in the past (session is at tick ${world.frame})`, { expected: `frame >= ${world.frame}` });
|
|
128
|
+
}
|
|
129
|
+
world.input.schedule(changes);
|
|
130
|
+
revision++;
|
|
131
|
+
return { ...head(), scheduled: changes };
|
|
132
|
+
},
|
|
133
|
+
query(p) {
|
|
134
|
+
const want = list(p.with);
|
|
135
|
+
const all = Object.entries(world.observe({}).entities).filter(([, comps]) => want.every((c) => c in comps));
|
|
136
|
+
const offset = Number(p.cursor ?? 0);
|
|
137
|
+
const limit = Number(p.limit ?? 50);
|
|
138
|
+
if (!Number.isInteger(offset) || offset < 0)
|
|
139
|
+
throw new CliError('usage', `cursor must come from a previous query, got '${p.cursor}'`);
|
|
140
|
+
const page = all.slice(offset, offset + limit).map(([id, comps]) => ({ id, components: Object.keys(comps) }));
|
|
141
|
+
const next = offset + limit < all.length ? String(offset + limit) : null;
|
|
142
|
+
return { ...head(), total: all.length, entities: page, next };
|
|
143
|
+
},
|
|
144
|
+
inspect(p) {
|
|
145
|
+
const id = String(p.entity ?? '');
|
|
146
|
+
const obs = world.observe({ entityIds: [id] });
|
|
147
|
+
const comps = obs.entities[id];
|
|
148
|
+
if (!comps) {
|
|
149
|
+
const ids = Object.keys(world.observe({ components: [] }).entities);
|
|
150
|
+
throw new CliError('entity-not-found', `entity '${id}' does not exist at tick ${world.frame}`, { detail: { entities: ids.slice(0, 20), total: ids.length }, hint: 'vibe session query lists entity ids' });
|
|
151
|
+
}
|
|
152
|
+
const only = list(p.components);
|
|
153
|
+
const components = only.length ? Object.fromEntries(Object.entries(comps).filter(([c]) => only.includes(c))) : comps;
|
|
154
|
+
return { ...head(), entity: id, hidden: obs.hidden.includes(id), components };
|
|
155
|
+
},
|
|
156
|
+
events(p) {
|
|
157
|
+
const since = Number(p.since ?? 0);
|
|
158
|
+
const filters = list(p.filter);
|
|
159
|
+
const limit = Number(p.limit ?? 100);
|
|
160
|
+
const match = (name) => !filters.length || filters.some((f) => (f.endsWith('*') ? name.startsWith(f.slice(0, -1)) : name === f));
|
|
161
|
+
const found = log.filter((e) => e.frame >= since && match(e.name));
|
|
162
|
+
return { ...head(), total: found.length, oldest: log[0]?.frame ?? null, events: found.slice(-limit) };
|
|
163
|
+
},
|
|
164
|
+
state(p) {
|
|
165
|
+
const obs = world.observe({});
|
|
166
|
+
return { ...head(), scene: obs.scene, states: obs.states, resources: obs.resources, inputs: world.input.recorded().slice(-Number(p.inputs ?? 20)) };
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
function single(p) {
|
|
170
|
+
const action = String(p.action ?? '');
|
|
171
|
+
const player = p.player ?? LOCAL_PLAYER;
|
|
172
|
+
const at = p.at === undefined ? world.frame : Number(p.at);
|
|
173
|
+
if (!Number.isInteger(at))
|
|
174
|
+
throw new CliError('usage', `at must be a tick number, got ${p.at}`);
|
|
175
|
+
const spec = actionSpec(action);
|
|
176
|
+
if (p.press) {
|
|
177
|
+
if (spec.type !== 'button')
|
|
178
|
+
throw new CliError('input-invalid', `'${action}' is a ${spec.type}; only buttons can be pressed`, { expected: 'a value instead of --press' });
|
|
179
|
+
return [{ frame: at, player, action, value: true }, { frame: at + 1, player, action, value: false }];
|
|
180
|
+
}
|
|
181
|
+
if (p.value === undefined)
|
|
182
|
+
throw new CliError('usage', `input '${action}' needs a value or --press`, { expected: spec.type === 'button' ? 'true | false' : spec.type === 'vector2' ? '[x,y]' : 'a number' });
|
|
183
|
+
const value = p.value;
|
|
184
|
+
const out = [{ frame: at, player, action, value }];
|
|
185
|
+
if (p.frames !== undefined) {
|
|
186
|
+
const n = Number(p.frames);
|
|
187
|
+
if (!Number.isInteger(n) || n < 1)
|
|
188
|
+
throw new CliError('usage', `frames must be a positive integer, got ${p.frames}`);
|
|
189
|
+
out.push({ frame: at + n, player, action, value: spec.type === 'button' ? false : spec.type === 'vector2' ? [0, 0] : 0 });
|
|
190
|
+
}
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
193
|
+
function actionSpec(action) {
|
|
194
|
+
const spec = world.inputMap?.actions[action];
|
|
195
|
+
if (!spec)
|
|
196
|
+
throw new CliError('input-invalid', `unknown action '${action}'`, { expected: 'an action declared in defineInput', detail: { actions: Object.keys(world.inputMap?.actions ?? {}) } });
|
|
197
|
+
return spec;
|
|
198
|
+
}
|
|
199
|
+
function checkValue(action, value) {
|
|
200
|
+
const { type } = actionSpec(action);
|
|
201
|
+
const ok = type === 'button' ? typeof value === 'boolean' : type === 'vector2' ? Array.isArray(value) && value.length === 2 && value.every((n) => typeof n === 'number') : typeof value === 'number';
|
|
202
|
+
if (!ok)
|
|
203
|
+
throw new CliError('input-invalid', `'${action}' is a ${type}, got ${JSON.stringify(value)}`, { expected: type === 'button' ? 'true | false' : type === 'vector2' ? '[x,y]' : 'a number' });
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
async call(method, payload) {
|
|
207
|
+
const fn = methods[method];
|
|
208
|
+
if (!fn)
|
|
209
|
+
throw new CliError('usage', `unknown session method '${method}'`, { expected: Object.keys(methods).join(' | ') });
|
|
210
|
+
if (MUTATING.has(method) && payload.revision !== undefined && payload.revision !== revision) {
|
|
211
|
+
throw new CliError('session-revision-stale', `revision ${payload.revision} is old; the session is at revision ${revision} (tick ${world.frame})`, { detail: head(), hint: 'vibe session status, look at the new state, then retry with its revision' });
|
|
212
|
+
}
|
|
213
|
+
return fn(payload);
|
|
214
|
+
},
|
|
215
|
+
close: pause,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function toChanges(raw) {
|
|
219
|
+
return raw.map((c, i) => {
|
|
220
|
+
const ok = c && typeof c === 'object' && Number.isInteger(c.frame) && c.frame >= 0 && typeof c.action === 'string' && 'value' in c && (c.player === undefined || typeof c.player === 'string');
|
|
221
|
+
if (!ok)
|
|
222
|
+
throw new CliError('input-invalid', `changes[${i}] is not a valid change`, { expected: '{ frame: integer >= 0, action: string, value, player?: string }', detail: { index: i, got: c } });
|
|
223
|
+
return { frame: c.frame, action: c.action, value: c.value, player: c.player ?? LOCAL_PLAYER };
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
const list = (v) => (v === undefined || v === null || v === '' ? [] : String(v).split(',').map((s) => s.trim()).filter(Boolean));
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type CommandSpec } from './registry.ts';
|
|
2
|
+
import { type SessionFile } from './session-host.ts';
|
|
3
|
+
/** Sessões abertas no projeto; arquivos de processos mortos são apagados. */
|
|
4
|
+
export declare function listSessions(root: string): SessionFile[];
|
|
5
|
+
export declare function callSession(s: SessionFile, method: string, payload?: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
6
|
+
export declare const SESSION_COMMANDS: CommandSpec<any>[];
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `vibe session ...` (ADR-0009, RFC-003): comandos curtos que falam com uma
|
|
3
|
+
* sessão viva. `start` sobe o processo da sessão; o resto acha a sessão em
|
|
4
|
+
* `.vibe/sessions/` (a única aberta, ou `--session <id>`) e chama um método.
|
|
5
|
+
*/
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { existsSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync } from 'node:fs';
|
|
8
|
+
import { extname, join, relative, resolve } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
import { CliError, defineCommand } from './registry.js';
|
|
12
|
+
import { CONFIG_FILE, PROJECT_ERRORS } from './project.js';
|
|
13
|
+
import { PROTOCOL_VERSION, sessionsDir } from './session-host.js';
|
|
14
|
+
const SESSION_ERRORS = {
|
|
15
|
+
'session-not-found': 'no open session with that id (or several are open and --session is missing)',
|
|
16
|
+
'session-unreachable': 'the session process is gone or does not answer',
|
|
17
|
+
'session-unauthorized': 'the session token in .vibe/sessions/ does not match',
|
|
18
|
+
'protocol-mismatch': 'the CLI and the session process come from different engine versions',
|
|
19
|
+
};
|
|
20
|
+
const sessionFlag = { session: { type: 'string', doc: 'session id (default: the only open session in this project)' } };
|
|
21
|
+
const revisionFlag = { revision: { type: 'number', doc: 'fail with session-revision-stale if the session changed since this revision' } };
|
|
22
|
+
const HEAD = { session: 'session id', frame: 'current tick', revision: 'state revision: goes up on every change' };
|
|
23
|
+
const STATUS = { ...HEAD, scene: 'active scene', seed: 'session seed', running: 'true while resumed (real time)', simTimeMs: 'simulated time in ms', tickRate: 'ticks per second', hash: 'state hash (same seed + same inputs = same hash)', entities: 'entity count', error: 'last world error ({ frame, message, source }) or null' };
|
|
24
|
+
/** Sessões abertas no projeto; arquivos de processos mortos são apagados. */
|
|
25
|
+
export function listSessions(root) {
|
|
26
|
+
const dir = sessionsDir(root);
|
|
27
|
+
if (!existsSync(dir))
|
|
28
|
+
return [];
|
|
29
|
+
const out = [];
|
|
30
|
+
for (const name of readdirSync(dir).filter((n) => n.endsWith('.json'))) {
|
|
31
|
+
const path = join(dir, name);
|
|
32
|
+
try {
|
|
33
|
+
const s = JSON.parse(readFileSync(path, 'utf8'));
|
|
34
|
+
process.kill(s.pid, 0);
|
|
35
|
+
out.push(s);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
rmSync(path, { force: true });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return out.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
|
|
42
|
+
}
|
|
43
|
+
function findSession(root, id) {
|
|
44
|
+
const open = listSessions(root);
|
|
45
|
+
const ids = open.map((s) => s.id);
|
|
46
|
+
if (id !== undefined) {
|
|
47
|
+
const s = open.find((x) => x.id === id);
|
|
48
|
+
if (!s)
|
|
49
|
+
throw new CliError('session-not-found', `session '${id}' is not open`, { detail: { open: ids }, hint: ids.length ? `open: ${ids.join(', ')}` : 'vibe session start' });
|
|
50
|
+
return s;
|
|
51
|
+
}
|
|
52
|
+
if (open.length === 1)
|
|
53
|
+
return open[0];
|
|
54
|
+
throw new CliError('session-not-found', open.length ? `${open.length} sessions are open: pass --session` : 'no session is open in this project', { detail: { open: ids }, hint: open.length ? `--session ${ids[0]}` : 'vibe session start [--scene <id>] [--seed <n>]' });
|
|
55
|
+
}
|
|
56
|
+
export async function callSession(s, method, payload = {}) {
|
|
57
|
+
let res;
|
|
58
|
+
try {
|
|
59
|
+
res = await fetch(`http://127.0.0.1:${s.port}/rpc`, {
|
|
60
|
+
method: 'POST',
|
|
61
|
+
headers: { authorization: `Bearer ${s.token}`, 'content-type': 'application/json' },
|
|
62
|
+
body: JSON.stringify({ protocolVersion: PROTOCOL_VERSION, requestId: randomUUID(), method, payload }),
|
|
63
|
+
signal: AbortSignal.timeout(60_000),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
throw new CliError('session-unreachable', `session '${s.id}' does not answer: ${err.message}`, { hint: 'vibe session list (removes dead sessions), then vibe session start' });
|
|
68
|
+
}
|
|
69
|
+
const body = (await res.json().catch(() => ({})));
|
|
70
|
+
if (body.ok)
|
|
71
|
+
return body.result;
|
|
72
|
+
const { code = 'internal', message = `session answered HTTP ${res.status}`, ...fields } = body.error ?? {};
|
|
73
|
+
throw new CliError(code, message, fields);
|
|
74
|
+
}
|
|
75
|
+
const toPayload = (flags, names) => Object.fromEntries(names.filter((n) => flags[n] !== undefined).map((n) => [n, flags[n]]));
|
|
76
|
+
const head = (o) => `${o.session} · tick ${o.frame} · revision ${o.revision}`;
|
|
77
|
+
const statusLine = (o) => `${head(o)} · ${o.scene} · seed ${o.seed} · ${o.running ? 'running' : 'paused'} · hash ${o.hash} · ${o.entities} entities${o.error ? `\nlast error at tick ${o.error.frame}: ${o.error.message}` : ''}`;
|
|
78
|
+
function sessionCommand(c) {
|
|
79
|
+
return defineCommand({
|
|
80
|
+
name: `session ${c.verb}`,
|
|
81
|
+
summary: c.summary,
|
|
82
|
+
...(c.positionals && { positionals: c.positionals }),
|
|
83
|
+
flags: { ...sessionFlag, ...(c.mutating ? revisionFlag : {}), ...c.flags },
|
|
84
|
+
output: c.output,
|
|
85
|
+
errors: { ...SESSION_ERRORS, ...c.errors },
|
|
86
|
+
async run({ flags, positionals, io }) {
|
|
87
|
+
const s = findSession(io.cwd, flags.session);
|
|
88
|
+
const payload = { ...(c.payload?.(flags, positionals, io.cwd) ?? {}), ...(flags.revision !== undefined && { revision: flags.revision }) };
|
|
89
|
+
return callSession(s, c.verb, payload);
|
|
90
|
+
},
|
|
91
|
+
human: c.human ?? statusLine,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
const start = defineCommand({
|
|
95
|
+
name: 'session start',
|
|
96
|
+
summary: 'Open a live session: the scene loads paused at tick 0 in a background process; other session commands drive it',
|
|
97
|
+
flags: {
|
|
98
|
+
scene: { type: 'string', doc: 'scene id; default: startScene in vibe.config.ts, or the only scene' },
|
|
99
|
+
seed: { type: 'number', default: 1, doc: 'session seed' },
|
|
100
|
+
'save-dir': { type: 'string', doc: 'read and write saves as files in this folder (default: in memory)' },
|
|
101
|
+
idle: { type: 'number', default: 30, doc: 'minutes without commands before the session closes itself' },
|
|
102
|
+
},
|
|
103
|
+
output: { ...STATUS, log: 'file with the session process output (console.log of the game)' },
|
|
104
|
+
errors: { ...PROJECT_ERRORS, ...SESSION_ERRORS, 'scene-not-found': 'the scene id is not registered', 'world-error': 'the scene setup threw; source points at the game file' },
|
|
105
|
+
async run({ flags, io }) {
|
|
106
|
+
if (!existsSync(join(io.cwd, CONFIG_FILE)))
|
|
107
|
+
throw new CliError('config-missing', `no ${CONFIG_FILE} in ${io.cwd}`, { hint: 'run vibe session start in the project folder' });
|
|
108
|
+
const seed = flags.seed;
|
|
109
|
+
const idle = flags.idle;
|
|
110
|
+
if (!Number.isInteger(seed))
|
|
111
|
+
throw new CliError('usage', `--seed must be an integer, got ${seed}`, { expected: 'integer' });
|
|
112
|
+
if (!(idle > 0))
|
|
113
|
+
throw new CliError('usage', `--idle must be a positive number of minutes, got ${idle}`);
|
|
114
|
+
const id = `s_${randomUUID().slice(0, 6)}`;
|
|
115
|
+
const dir = sessionsDir(io.cwd);
|
|
116
|
+
mkdirSync(dir, { recursive: true });
|
|
117
|
+
const logFile = join(dir, `${id}.log`);
|
|
118
|
+
const log = openSync(logFile, 'w');
|
|
119
|
+
const here = fileURLToPath(import.meta.url);
|
|
120
|
+
const daemon = resolve(here, '..', `session-daemon${extname(here)}`);
|
|
121
|
+
const opts = { id, root: io.cwd, seed, idleMinutes: idle, ...(flags.scene !== undefined && { scene: flags.scene }), ...(flags['save-dir'] !== undefined && { saveDir: flags['save-dir'] }) };
|
|
122
|
+
const child = spawn(process.execPath, [daemon, JSON.stringify(opts)], { cwd: io.cwd, detached: true, stdio: ['ignore', log, log, 'ipc'] });
|
|
123
|
+
const msg = await new Promise((ok) => {
|
|
124
|
+
const timer = setTimeout(() => ok({ error: { code: 'session-unreachable', message: 'the session did not start in 60 s' } }), 60_000);
|
|
125
|
+
child.once('message', (m) => { clearTimeout(timer); ok(m); });
|
|
126
|
+
child.once('exit', (code) => { clearTimeout(timer); ok({ error: { code: 'session-unreachable', message: `the session process exited (code ${code}); see ${relative(io.cwd, logFile)}` } }); });
|
|
127
|
+
});
|
|
128
|
+
child.removeAllListeners();
|
|
129
|
+
if (child.connected)
|
|
130
|
+
child.disconnect();
|
|
131
|
+
child.unref();
|
|
132
|
+
if (msg.error) {
|
|
133
|
+
if (child.exitCode === null)
|
|
134
|
+
child.kill();
|
|
135
|
+
const { code, message, ...fields } = msg.error;
|
|
136
|
+
throw new CliError(code, message, fields);
|
|
137
|
+
}
|
|
138
|
+
return { ...(await callSession(msg.ready, 'status')), log: relative(io.cwd, logFile) };
|
|
139
|
+
},
|
|
140
|
+
human: (o) => `${statusLine(o)}\nnext: vibe session step 60 · vibe session inspect <entity> · vibe session stop`,
|
|
141
|
+
});
|
|
142
|
+
const listCmd = defineCommand({
|
|
143
|
+
name: 'session list',
|
|
144
|
+
summary: 'List the open sessions of this project (and forget dead ones)',
|
|
145
|
+
flags: {},
|
|
146
|
+
output: { sessions: 'open sessions: id, pid, scene, seed, startedAt' },
|
|
147
|
+
errors: {},
|
|
148
|
+
async run({ io }) {
|
|
149
|
+
return { sessions: listSessions(io.cwd).map(({ token: _t, port: _p, ...s }) => s) };
|
|
150
|
+
},
|
|
151
|
+
human: ({ sessions }) => (sessions.length ? sessions.map((s) => `${s.id} ${s.scene} seed ${s.seed} pid ${s.pid} since ${s.startedAt}`).join('\n') : 'no open sessions (vibe session start)'),
|
|
152
|
+
});
|
|
153
|
+
const parseValue = (raw) => {
|
|
154
|
+
try {
|
|
155
|
+
return JSON.parse(raw);
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
throw new CliError('usage', `value '${raw}' is not JSON`, { expected: 'true | false | a number | [x,y]' });
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
const readChanges = (file, cwd) => {
|
|
162
|
+
try {
|
|
163
|
+
return JSON.parse(readFileSync(resolve(cwd, file), 'utf8'));
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
throw new CliError('input-invalid', `cannot read '${file}': ${err.message}`, { expected: 'a JSON array of { frame, action, value, player? }' });
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
export const SESSION_COMMANDS = [
|
|
170
|
+
start,
|
|
171
|
+
listCmd,
|
|
172
|
+
sessionCommand({ verb: 'status', summary: 'Show tick, revision, scene, seed, running/paused, state hash and the last world error', output: STATUS }),
|
|
173
|
+
sessionCommand({
|
|
174
|
+
verb: 'step',
|
|
175
|
+
summary: 'Advance a paused session by exactly N fixed ticks and count the events emitted',
|
|
176
|
+
positionals: [{ name: 'frames', doc: 'ticks to advance (default 1)' }],
|
|
177
|
+
mutating: true,
|
|
178
|
+
output: { ...STATUS, stepped: 'ticks advanced', events: 'count of each event name emitted in these ticks' },
|
|
179
|
+
errors: { 'session-running': 'the session is resumed; pause it first', 'session-revision-stale': 'the session changed since --revision', 'world-error': 'a system threw; source points at the game file' },
|
|
180
|
+
payload: (_f, [frames]) => ({ frames: frames === undefined ? 1 : Number(frames) }),
|
|
181
|
+
human: (o) => `${statusLine(o)}\nevents: ${Object.entries(o.events).map(([n, c]) => `${n} ${c}`).join(', ') || 'none'}`,
|
|
182
|
+
}),
|
|
183
|
+
sessionCommand({ verb: 'pause', summary: 'Stop real-time ticking (sessions start paused)', output: STATUS }),
|
|
184
|
+
sessionCommand({ verb: 'resume', summary: 'Tick in real time (tickRate per second) until pause; an error pauses it', mutating: true, output: STATUS, errors: { 'session-revision-stale': 'the session changed since --revision' } }),
|
|
185
|
+
sessionCommand({
|
|
186
|
+
verb: 'reset',
|
|
187
|
+
summary: 'Start the scene again at tick 0 (same seed and scene unless given)',
|
|
188
|
+
flags: { seed: { type: 'number', doc: 'new seed' }, scene: { type: 'string', doc: 'another scene' } },
|
|
189
|
+
mutating: true,
|
|
190
|
+
output: STATUS,
|
|
191
|
+
errors: { 'scene-not-found': 'the scene id is not registered', 'session-revision-stale': 'the session changed since --revision', 'world-error': 'the scene setup threw' },
|
|
192
|
+
payload: (f) => toPayload(f, ['seed', 'scene']),
|
|
193
|
+
}),
|
|
194
|
+
sessionCommand({
|
|
195
|
+
verb: 'input',
|
|
196
|
+
summary: 'Schedule input by tick: a value now (or --at), --press for one tick, --frames to hold then release, or --file with a recorded sequence',
|
|
197
|
+
positionals: [{ name: 'action', doc: 'action from defineInput (not with --file)' }, { name: 'value', doc: 'JSON value: true, 0.5, [1,0] (not with --press)' }],
|
|
198
|
+
flags: {
|
|
199
|
+
press: { type: 'boolean', default: false, doc: 'press a button for exactly one tick' },
|
|
200
|
+
frames: { type: 'number', doc: 'hold the value for N ticks, then release (false / 0 / [0,0])' },
|
|
201
|
+
at: { type: 'number', doc: 'tick to apply at (default: the next tick)' },
|
|
202
|
+
player: { type: 'string', doc: "player id (default 'local')" },
|
|
203
|
+
file: { type: 'string', doc: 'JSON file with [{ frame, action, value, player? }] (world.input.recorded() format)' },
|
|
204
|
+
},
|
|
205
|
+
mutating: true,
|
|
206
|
+
output: { ...HEAD, scheduled: 'changes scheduled: { frame, player, action, value }' },
|
|
207
|
+
errors: { 'input-invalid': 'unknown action, value of the wrong type, tick in the past or bad file', 'session-revision-stale': 'the session changed since --revision' },
|
|
208
|
+
payload(f, [action, value], cwd) {
|
|
209
|
+
if (f.file !== undefined)
|
|
210
|
+
return { changes: readChanges(f.file, cwd) };
|
|
211
|
+
if (action === undefined)
|
|
212
|
+
throw new CliError('usage', 'input needs an action (or --file)', { hint: 'vibe session input jump --press' });
|
|
213
|
+
return { action, ...(value !== undefined && { value: parseValue(value) }), ...(f.press ? { press: true } : {}), ...toPayload(f, ['frames', 'at', 'player']) };
|
|
214
|
+
},
|
|
215
|
+
human: (o) => `${head(o)}\n${o.scheduled.map((c) => `tick ${c.frame}: ${c.player} ${c.action} = ${JSON.stringify(c.value)}`).join('\n')}`,
|
|
216
|
+
}),
|
|
217
|
+
sessionCommand({
|
|
218
|
+
verb: 'query',
|
|
219
|
+
summary: 'List entity ids (spawn order) that have every given component, a page at a time',
|
|
220
|
+
flags: { with: { type: 'string', doc: 'comma-separated component ids (default: every entity)' }, limit: { type: 'number', default: 50, doc: 'page size' }, cursor: { type: 'string', doc: 'the next value of the previous page' } },
|
|
221
|
+
output: { ...HEAD, total: 'matching entities', entities: 'this page: { id, components }', next: 'cursor for the next page, or null' },
|
|
222
|
+
payload: (f) => toPayload(f, ['with', 'limit', 'cursor']),
|
|
223
|
+
human: (o) => `${head(o)} · ${o.total} entities\n${o.entities.map((e) => `${e.id} ${e.components.join(', ')}`).join('\n')}${o.next ? `\nmore: --cursor ${o.next}` : ''}`,
|
|
224
|
+
}),
|
|
225
|
+
sessionCommand({
|
|
226
|
+
verb: 'inspect',
|
|
227
|
+
summary: 'Show the component values of one entity',
|
|
228
|
+
positionals: [{ name: 'entity', doc: 'entity id', required: true }],
|
|
229
|
+
flags: { components: { type: 'string', doc: 'comma-separated component ids (default: all)' } },
|
|
230
|
+
output: { ...HEAD, entity: 'entity id', hidden: 'hidden by its scene/state', components: 'component id → value' },
|
|
231
|
+
errors: { 'entity-not-found': 'no entity with that id at this tick' },
|
|
232
|
+
payload(f, [entity]) {
|
|
233
|
+
if (entity === undefined)
|
|
234
|
+
throw new CliError('usage', 'inspect needs an entity id', { hint: 'vibe session query lists ids' });
|
|
235
|
+
return { entity, ...toPayload(f, ['components']) };
|
|
236
|
+
},
|
|
237
|
+
human: (o) => `${head(o)} · ${o.entity}${o.hidden ? ' (hidden)' : ''}\n${Object.entries(o.components).map(([c, v]) => `${c} ${JSON.stringify(v)}`).join('\n')}`,
|
|
238
|
+
}),
|
|
239
|
+
sessionCommand({
|
|
240
|
+
verb: 'events',
|
|
241
|
+
summary: 'Events emitted since a tick (physics contacts, input, game events), newest last',
|
|
242
|
+
flags: { since: { type: 'number', doc: 'from this tick (default 0)' }, filter: { type: 'string', doc: "comma-separated names; a trailing * matches a prefix ('physics.*')" }, limit: { type: 'number', default: 100, doc: 'at most this many (the newest)' } },
|
|
243
|
+
output: { ...HEAD, total: 'matching events in the session log', oldest: 'oldest tick still in the log (it keeps the last 5000 events)', events: '{ frame, name, payload }' },
|
|
244
|
+
payload: (f) => toPayload(f, ['since', 'filter', 'limit']),
|
|
245
|
+
human: (o) => `${head(o)} · ${o.total} events\n${o.events.map((e) => `@${e.frame} ${e.name} ${JSON.stringify(e.payload)}`).join('\n')}`,
|
|
246
|
+
}),
|
|
247
|
+
sessionCommand({
|
|
248
|
+
verb: 'state',
|
|
249
|
+
summary: 'Scene, active states, resources and the last recorded input changes',
|
|
250
|
+
flags: { inputs: { type: 'number', default: 20, doc: 'how many recorded input changes' } },
|
|
251
|
+
output: { ...HEAD, scene: 'active scene', states: 'active states', resources: 'resource id → inspect()', inputs: 'last recorded input changes (replayable with vibe run --inputs)' },
|
|
252
|
+
payload: (f) => toPayload(f, ['inputs']),
|
|
253
|
+
human: (o) => `${head(o)} · ${o.scene} · states ${o.states.join(', ') || 'none'}\nresources ${JSON.stringify(o.resources)}\ninputs ${JSON.stringify(o.inputs)}`,
|
|
254
|
+
}),
|
|
255
|
+
sessionCommand({ verb: 'stop', summary: 'Close the session and its process', output: { session: 'session id', stopped: 'true' }, human: (o) => `${o.session} stopped` }),
|
|
256
|
+
];
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface TsError {
|
|
2
|
+
file: string;
|
|
3
|
+
line: number;
|
|
4
|
+
column: number;
|
|
5
|
+
code: string;
|
|
6
|
+
message: string;
|
|
7
|
+
}
|
|
8
|
+
export type TypecheckResult = {
|
|
9
|
+
ran: true;
|
|
10
|
+
errors: TsError[];
|
|
11
|
+
} | {
|
|
12
|
+
ran: false;
|
|
13
|
+
reason: string;
|
|
14
|
+
};
|
|
15
|
+
export declare function typecheck(root: string): Promise<TypecheckResult>;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typecheck do projeto para o `vibe check` (#42): roda o `tsc` do próprio
|
|
3
|
+
* projeto e devolve cada erro com arquivo, linha e coluna. Sem `tsconfig.json`,
|
|
4
|
+
* usa um gerado em `.vibe/` com as regras da engine (as mesmas que o Node
|
|
5
|
+
* aceita ao rodar `.ts` direto). Sem `typescript` instalado, não roda e diz por quê.
|
|
6
|
+
*/
|
|
7
|
+
import { execFile } from 'node:child_process';
|
|
8
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { createRequire } from 'node:module';
|
|
10
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
11
|
+
export async function typecheck(root) {
|
|
12
|
+
const req = createRequire(join(root, 'package.json'));
|
|
13
|
+
let tsc;
|
|
14
|
+
try {
|
|
15
|
+
tsc = join(dirname(req.resolve('typescript/package.json')), 'bin', 'tsc');
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return { ran: false, reason: 'typescript is not installed in this project (add typescript and @types/node to devDependencies)' };
|
|
19
|
+
}
|
|
20
|
+
const project = existsSync(join(root, 'tsconfig.json')) ? join(root, 'tsconfig.json') : generated(root, req);
|
|
21
|
+
const out = await new Promise((ok) => {
|
|
22
|
+
execFile(process.execPath, [tsc, '--noEmit', '--pretty', 'false', '-p', project], { cwd: root, timeout: 120_000, maxBuffer: 16 << 20 }, (_err, stdout) => ok(String(stdout)));
|
|
23
|
+
});
|
|
24
|
+
const cfgDir = dirname(project);
|
|
25
|
+
const errors = [];
|
|
26
|
+
for (const line of out.split('\n')) {
|
|
27
|
+
const global = /^error (TS\d+): (.*)$/.exec(line.trim()); // erro sem posição (tsconfig inválido, opção desconhecida)
|
|
28
|
+
if (global)
|
|
29
|
+
errors.push({ file: relative(root, project), line: 1, column: 1, code: global[1], message: global[2] });
|
|
30
|
+
const m = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/.exec(line.trim());
|
|
31
|
+
if (!m)
|
|
32
|
+
continue;
|
|
33
|
+
const abs = isAbsolute(m[1]) ? m[1] : resolve(root, m[1]);
|
|
34
|
+
const file = relative(root, existsSync(abs) ? abs : resolve(cfgDir, m[1]));
|
|
35
|
+
if (file.startsWith('..') || file.includes('node_modules'))
|
|
36
|
+
continue; // só o código do jogo: a engine (link no monorepo) tem o próprio typecheck
|
|
37
|
+
errors.push({ file, line: Number(m[2]), column: Number(m[3]), code: m[4], message: m[5] });
|
|
38
|
+
}
|
|
39
|
+
return { ran: true, errors };
|
|
40
|
+
}
|
|
41
|
+
function generated(root, req) {
|
|
42
|
+
const dir = join(root, '.vibe');
|
|
43
|
+
mkdirSync(dir, { recursive: true });
|
|
44
|
+
let node = true;
|
|
45
|
+
try {
|
|
46
|
+
req.resolve('@types/node/package.json');
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
node = false;
|
|
50
|
+
}
|
|
51
|
+
const file = join(dir, 'tsconfig.check.json');
|
|
52
|
+
writeFileSync(file, JSON.stringify({
|
|
53
|
+
compilerOptions: {
|
|
54
|
+
target: 'es2024',
|
|
55
|
+
module: 'nodenext',
|
|
56
|
+
moduleResolution: 'nodenext',
|
|
57
|
+
strict: true,
|
|
58
|
+
verbatimModuleSyntax: true,
|
|
59
|
+
erasableSyntaxOnly: true, // o Node roda .ts só apagando tipos: enum/namespace quebrariam lá
|
|
60
|
+
allowImportingTsExtensions: true,
|
|
61
|
+
noEmit: true,
|
|
62
|
+
skipLibCheck: true,
|
|
63
|
+
types: node ? ['node'] : [],
|
|
64
|
+
},
|
|
65
|
+
include: ['../src', '../tests', '../*.ts'],
|
|
66
|
+
}, null, 2));
|
|
67
|
+
return file;
|
|
68
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibe-engine/cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "vibe CLI: create, dev, run --headless, test, check, build and serve vibe-engine games",
|
|
5
5
|
"license": "MIT OR Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -35,12 +35,12 @@
|
|
|
35
35
|
}
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@vibe-engine/core": "0.1.
|
|
38
|
+
"@vibe-engine/core": "0.1.2",
|
|
39
39
|
"vite": "8.4.0"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@vibe-engine/2d": "0.1.
|
|
43
|
-
"@vibe-engine/net": "0.1.
|
|
42
|
+
"@vibe-engine/2d": "0.1.2",
|
|
43
|
+
"@vibe-engine/net": "0.1.2"
|
|
44
44
|
},
|
|
45
45
|
"files": [
|
|
46
46
|
"dist",
|
|
@@ -86,6 +86,7 @@ Build levels as text maps (`*.map.ts` with `defineMap`): one character per cell,
|
|
|
86
86
|
- UI look lives in `vibe.config.ts` → `ui: { font, color, styles }`: named styles with `hover`/`pressed`/`focused`/`disabled` variants. Buttons use `button` and texts use `text` automatically; apply others with `UiStyle({ use: 'panel title' })`. For 9-slice skins, set `skin: 'ui/button'` and put `{ "slice": 3 }` in `assets/ui/button.meta.json`. Fonts go in `assets/fonts/*.woff2|ttf`, referenced by id (`font: 'fonts/pixel'`). The style is visual only; test the state, not the look.
|
|
87
87
|
- **Text fields and world labels:** `UiInput({ value, placeholder, maxLength })` is a text field whose text is state; read `UiInput.value`, react to `UiChanged` / `UiSubmitted` (Enter), and test with `world.ui.type('menu/name', 'Ana')` + `world.ui.submit('menu/name')` (typed keys never reach game input). `Label2D({ text, offset, owner })` / `Label3D` draws text that follows the entity (names, tags); it's state, so assert the text. In multiplayer, pass a small `profile` with the join (`NetJoinRoom({ type, profile: { name } })`), declare `profile: { name: t.string({ maxLength: 16 }) }` in the room, and read it in `NetPlayerJoined { player, profile }` (the server cleans and validates it).
|
|
88
88
|
- **Showing a value** (HUD, labels): derive it from state every tick (a system in `update`, or `bindText`). It can never go stale, whatever changed the state.
|
|
89
|
+
- **Multiplayer entities owned by a player** (fighter, gun, their bullets): add `NetOwner({ player })` from `@vibe-engine/net`. The owner's client predicts them; every other client draws them ~100 ms in the past, sliding between real server positions (interpolation), so remote players never jitter.
|
|
89
90
|
- **Instant hits** (hitscan gun, knife, punch, explosion, line of sight): `raycast(world, { from, dir, range, by, ignore, filter })` and `overlap(world, { at, radius, dir?, angle?, by })` from `@vibe-engine/2d` (`raycast3D`/`overlap3D` in 3D). They read components, so call them inside a system. Pass `by: playerId` when a player's action does it: in multiplayer the server then accepts what that player saw on screen, within limits (lag compensation; `net.lagCompensation` in `vibe.config.ts`, `false` turns it off). Leave `by` out for things nobody aims (explosions, AI sight).
|
|
90
91
|
- **Shaders** (GLSL ES 3.0): `SpriteShader({ shader: 'flash' })` on a sprite, `PostEffect({ shader: 'vignette' })` on any entity for a full-screen pass, `Mesh({ material: 'toon' })` / `MeshShader` in 3D. Presets: `flash`, `outline`, `dissolve`, `palette`, `crt`, `bloom`, `shockwave`, `vignette`, `toon`; your own go in `*.shader.ts` (`defineShader('id', { fragment, uniforms: { amount: t.number() } })`). Systems write `uniforms` (state, testable headless); `time` comes for free. `vibe check` reports unknown shader ids and bad uniforms; compile errors point at file and line.
|
|
91
92
|
- **Destructible scenery** (2D): `destroyTiles(mapEntity, { x, y, radius }, emit)` from `@vibe-engine/2d` removes the tiles in a circle, emits `TilesDestroyed` with the cells, and only the touched chunks are rebuilt. Layers named in `Tilemap.indestructible` (`indestructible: true` in `tilemapFromGrid`) are kept.
|
|
@@ -129,12 +130,11 @@ Use the `vibe` CLI (`pnpm exec vibe ...`). Add `--json` for structured output: e
|
|
|
129
130
|
| understand the project | `vibe info [--component Player]` |
|
|
130
131
|
| read engine docs for **this** version | `vibe docs search "<term>"`, `vibe docs show <topic>` |
|
|
131
132
|
| run once without a screen | `vibe run --headless --scene <id> --frames N [--inputs file]` |
|
|
132
|
-
| drive a live session | `vibe session start --scene <id> --seed 1
|
|
133
|
-
| inspect
|
|
133
|
+
| drive a live session (paused at tick 0, background process) | `vibe session start [--scene <id>] [--seed 1]` → `vibe session step 60`, `vibe session input jump --press` (or `move 1 --frames 30`, `--at <tick>`, `--file inputs.json`), `reset`, `resume`/`pause`, `stop`. With several sessions open, add `--session <id>`; `--revision <n>` refuses to act on a state you have not seen |
|
|
134
|
+
| inspect a live session | `vibe session status`, `vibe session inspect <entity> [--components A,B]`, `vibe session query --with A,B`, `vibe session events --since N --filter 'physics.*'`, `vibe session state` |
|
|
134
135
|
| test | `vibe test [filter] [--name <regex>]` |
|
|
135
|
-
| see the screen | `vibe session screenshot <s>` (needs a renderer) |
|
|
136
136
|
| replay a run | `vibe replay <runId>` |
|
|
137
|
-
| check scenes, ids and asset references | `vibe check` |
|
|
137
|
+
| check TypeScript errors (file:line:column), scenes, ids and asset references | `vibe check` (`--no-types` skips the typecheck) |
|
|
138
138
|
| list assets (id = path under `assets/` without extension) | `vibe assets` |
|
|
139
139
|
| see a level with coordinates / validate all levels | `vibe map show <id>`, `vibe map check` |
|
|
140
140
|
| open in the browser (localhost; editing `src/` restarts the session) | `vibe dev [--port 5173]` |
|
|
@@ -86,6 +86,7 @@ Build levels as text maps (`*.map.ts` with `defineMap`): one character per cell,
|
|
|
86
86
|
- UI look lives in `vibe.config.ts` → `ui: { font, color, styles }`: named styles with `hover`/`pressed`/`focused`/`disabled` variants. Buttons use `button` and texts use `text` automatically; apply others with `UiStyle({ use: 'panel title' })`. For 9-slice skins, set `skin: 'ui/button'` and put `{ "slice": 3 }` in `assets/ui/button.meta.json`. Fonts go in `assets/fonts/*.woff2|ttf`, referenced by id (`font: 'fonts/pixel'`). The style is visual only; test the state, not the look.
|
|
87
87
|
- **Text fields and world labels:** `UiInput({ value, placeholder, maxLength })` is a text field whose text is state; read `UiInput.value`, react to `UiChanged` / `UiSubmitted` (Enter), and test with `world.ui.type('menu/name', 'Ana')` + `world.ui.submit('menu/name')` (typed keys never reach game input). `Label2D({ text, offset, owner })` / `Label3D` draws text that follows the entity (names, tags); it's state, so assert the text. In multiplayer, pass a small `profile` with the join (`NetJoinRoom({ type, profile: { name } })`), declare `profile: { name: t.string({ maxLength: 16 }) }` in the room, and read it in `NetPlayerJoined { player, profile }` (the server cleans and validates it).
|
|
88
88
|
- **Showing a value** (HUD, labels): derive it from state every tick (a system in `update`, or `bindText`). It can never go stale, whatever changed the state.
|
|
89
|
+
- **Multiplayer entities owned by a player** (fighter, gun, their bullets): add `NetOwner({ player })` from `@vibe-engine/net`. The owner's client predicts them; every other client draws them ~100 ms in the past, sliding between real server positions (interpolation), so remote players never jitter.
|
|
89
90
|
- **Instant hits** (hitscan gun, knife, punch, explosion, line of sight): `raycast(world, { from, dir, range, by, ignore, filter })` and `overlap(world, { at, radius, dir?, angle?, by })` from `@vibe-engine/2d` (`raycast3D`/`overlap3D` in 3D). They read components, so call them inside a system. Pass `by: playerId` when a player's action does it: in multiplayer the server then accepts what that player saw on screen, within limits (lag compensation; `net.lagCompensation` in `vibe.config.ts`, `false` turns it off). Leave `by` out for things nobody aims (explosions, AI sight).
|
|
90
91
|
- **Shaders** (GLSL ES 3.0): `SpriteShader({ shader: 'flash' })` on a sprite, `PostEffect({ shader: 'vignette' })` on any entity for a full-screen pass, `Mesh({ material: 'toon' })` / `MeshShader` in 3D. Presets: `flash`, `outline`, `dissolve`, `palette`, `crt`, `bloom`, `shockwave`, `vignette`, `toon`; your own go in `*.shader.ts` (`defineShader('id', { fragment, uniforms: { amount: t.number() } })`). Systems write `uniforms` (state, testable headless); `time` comes for free. `vibe check` reports unknown shader ids and bad uniforms; compile errors point at file and line.
|
|
91
92
|
- **Destructible scenery** (2D): `destroyTiles(mapEntity, { x, y, radius }, emit)` from `@vibe-engine/2d` removes the tiles in a circle, emits `TilesDestroyed` with the cells, and only the touched chunks are rebuilt. Layers named in `Tilemap.indestructible` (`indestructible: true` in `tilemapFromGrid`) are kept.
|
|
@@ -129,12 +130,11 @@ Use the `vibe` CLI (`pnpm exec vibe ...`). Add `--json` for structured output: e
|
|
|
129
130
|
| understand the project | `vibe info [--component Player]` |
|
|
130
131
|
| read engine docs for **this** version | `vibe docs search "<term>"`, `vibe docs show <topic>` |
|
|
131
132
|
| run once without a screen | `vibe run --headless --scene <id> --frames N [--inputs file]` |
|
|
132
|
-
| drive a live session | `vibe session start --scene <id> --seed 1
|
|
133
|
-
| inspect
|
|
133
|
+
| drive a live session (paused at tick 0, background process) | `vibe session start [--scene <id>] [--seed 1]` → `vibe session step 60`, `vibe session input jump --press` (or `move 1 --frames 30`, `--at <tick>`, `--file inputs.json`), `reset`, `resume`/`pause`, `stop`. With several sessions open, add `--session <id>`; `--revision <n>` refuses to act on a state you have not seen |
|
|
134
|
+
| inspect a live session | `vibe session status`, `vibe session inspect <entity> [--components A,B]`, `vibe session query --with A,B`, `vibe session events --since N --filter 'physics.*'`, `vibe session state` |
|
|
134
135
|
| test | `vibe test [filter] [--name <regex>]` |
|
|
135
|
-
| see the screen | `vibe session screenshot <s>` (needs a renderer) |
|
|
136
136
|
| replay a run | `vibe replay <runId>` |
|
|
137
|
-
| check scenes, ids and asset references | `vibe check` |
|
|
137
|
+
| check TypeScript errors (file:line:column), scenes, ids and asset references | `vibe check` (`--no-types` skips the typecheck) |
|
|
138
138
|
| list assets (id = path under `assets/` without extension) | `vibe assets` |
|
|
139
139
|
| see a level with coordinates / validate all levels | `vibe map show <id>`, `vibe map check` |
|
|
140
140
|
| open in the browser (localhost; editing `src/` restarts the session) | `vibe dev [--port 5173]` |
|
|
@@ -86,6 +86,7 @@ Build levels as text maps (`*.map.ts` with `defineMap`): one character per cell,
|
|
|
86
86
|
- UI look lives in `vibe.config.ts` → `ui: { font, color, styles }`: named styles with `hover`/`pressed`/`focused`/`disabled` variants. Buttons use `button` and texts use `text` automatically; apply others with `UiStyle({ use: 'panel title' })`. For 9-slice skins, set `skin: 'ui/button'` and put `{ "slice": 3 }` in `assets/ui/button.meta.json`. Fonts go in `assets/fonts/*.woff2|ttf`, referenced by id (`font: 'fonts/pixel'`). The style is visual only; test the state, not the look.
|
|
87
87
|
- **Text fields and world labels:** `UiInput({ value, placeholder, maxLength })` is a text field whose text is state; read `UiInput.value`, react to `UiChanged` / `UiSubmitted` (Enter), and test with `world.ui.type('menu/name', 'Ana')` + `world.ui.submit('menu/name')` (typed keys never reach game input). `Label2D({ text, offset, owner })` / `Label3D` draws text that follows the entity (names, tags); it's state, so assert the text. In multiplayer, pass a small `profile` with the join (`NetJoinRoom({ type, profile: { name } })`), declare `profile: { name: t.string({ maxLength: 16 }) }` in the room, and read it in `NetPlayerJoined { player, profile }` (the server cleans and validates it).
|
|
88
88
|
- **Showing a value** (HUD, labels): derive it from state every tick (a system in `update`, or `bindText`). It can never go stale, whatever changed the state.
|
|
89
|
+
- **Multiplayer entities owned by a player** (fighter, gun, their bullets): add `NetOwner({ player })` from `@vibe-engine/net`. The owner's client predicts them; every other client draws them ~100 ms in the past, sliding between real server positions (interpolation), so remote players never jitter.
|
|
89
90
|
- **Instant hits** (hitscan gun, knife, punch, explosion, line of sight): `raycast(world, { from, dir, range, by, ignore, filter })` and `overlap(world, { at, radius, dir?, angle?, by })` from `@vibe-engine/2d` (`raycast3D`/`overlap3D` in 3D). They read components, so call them inside a system. Pass `by: playerId` when a player's action does it: in multiplayer the server then accepts what that player saw on screen, within limits (lag compensation; `net.lagCompensation` in `vibe.config.ts`, `false` turns it off). Leave `by` out for things nobody aims (explosions, AI sight).
|
|
90
91
|
- **Shaders** (GLSL ES 3.0): `SpriteShader({ shader: 'flash' })` on a sprite, `PostEffect({ shader: 'vignette' })` on any entity for a full-screen pass, `Mesh({ material: 'toon' })` / `MeshShader` in 3D. Presets: `flash`, `outline`, `dissolve`, `palette`, `crt`, `bloom`, `shockwave`, `vignette`, `toon`; your own go in `*.shader.ts` (`defineShader('id', { fragment, uniforms: { amount: t.number() } })`). Systems write `uniforms` (state, testable headless); `time` comes for free. `vibe check` reports unknown shader ids and bad uniforms; compile errors point at file and line.
|
|
91
92
|
- **Destructible scenery** (2D): `destroyTiles(mapEntity, { x, y, radius }, emit)` from `@vibe-engine/2d` removes the tiles in a circle, emits `TilesDestroyed` with the cells, and only the touched chunks are rebuilt. Layers named in `Tilemap.indestructible` (`indestructible: true` in `tilemapFromGrid`) are kept.
|
|
@@ -129,12 +130,11 @@ Use the `vibe` CLI (`pnpm exec vibe ...`). Add `--json` for structured output: e
|
|
|
129
130
|
| understand the project | `vibe info [--component Player]` |
|
|
130
131
|
| read engine docs for **this** version | `vibe docs search "<term>"`, `vibe docs show <topic>` |
|
|
131
132
|
| run once without a screen | `vibe run --headless --scene <id> --frames N [--inputs file]` |
|
|
132
|
-
| drive a live session | `vibe session start --scene <id> --seed 1
|
|
133
|
-
| inspect
|
|
133
|
+
| drive a live session (paused at tick 0, background process) | `vibe session start [--scene <id>] [--seed 1]` → `vibe session step 60`, `vibe session input jump --press` (or `move 1 --frames 30`, `--at <tick>`, `--file inputs.json`), `reset`, `resume`/`pause`, `stop`. With several sessions open, add `--session <id>`; `--revision <n>` refuses to act on a state you have not seen |
|
|
134
|
+
| inspect a live session | `vibe session status`, `vibe session inspect <entity> [--components A,B]`, `vibe session query --with A,B`, `vibe session events --since N --filter 'physics.*'`, `vibe session state` |
|
|
134
135
|
| test | `vibe test [filter] [--name <regex>]` |
|
|
135
|
-
| see the screen | `vibe session screenshot <s>` (needs a renderer) |
|
|
136
136
|
| replay a run | `vibe replay <runId>` |
|
|
137
|
-
| check scenes, ids and asset references | `vibe check` |
|
|
137
|
+
| check TypeScript errors (file:line:column), scenes, ids and asset references | `vibe check` (`--no-types` skips the typecheck) |
|
|
138
138
|
| list assets (id = path under `assets/` without extension) | `vibe assets` |
|
|
139
139
|
| see a level with coordinates / validate all levels | `vibe map show <id>`, `vibe map check` |
|
|
140
140
|
| open in the browser (localhost; editing `src/` restarts the session) | `vibe dev [--port 5173]` |
|
|
@@ -165,6 +165,7 @@ Online PvP in arenas of up to 6 players (three are always open in the lobby; mor
|
|
|
165
165
|
- Camera and UI are local to each client (`net: 'local'` components are not replicated). `view.local` points the camera at `fighter-<localPlayer>` and writes the small top-right HUD (`hud/hp`: health + weapon, `hud/board`: kill limit and scoreboard). Controls are listed in the lobby. `localPlayer` is in the system context.
|
|
166
166
|
- Ids created during play must be the same on client and server: bullets are `bullet-<player>-<n>` and rifle tracers `tracer-<player>-<n>`, from a counter in `Gun`.
|
|
167
167
|
- Rifle and knife use `raycast`/`overlap` with `by: gun.owner`: the server accepts what that player saw (lag compensation), so a hit on a target that just turned around still counts, within limits. Bullets are simulated on the server and need nothing extra.
|
|
168
|
+
- Fighters, guns, bullets and tracers carry `NetOwner({ player })`: your own are predicted; other players' are drawn ~100 ms in the past, interpolated between server snapshots (smooth, never corrected).
|
|
168
169
|
- Health, kills and deaths are decided by the server; a client that edits them locally is overwritten by the next snapshot.
|
|
169
170
|
|
|
170
171
|
Files:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { defineListener } from '@vibe-engine/core';
|
|
2
2
|
import { Collider2D, Label2D, RigidBody2D, Sprite, Transform2D } from '@vibe-engine/2d';
|
|
3
|
-
import { NetPlayerJoined, NetPlayerLeft } from '@vibe-engine/net';
|
|
3
|
+
import { NetOwner, NetPlayerJoined, NetPlayerLeft } from '@vibe-engine/net';
|
|
4
4
|
import { COLORS, Fighter } from '../components/fighter.component.ts';
|
|
5
5
|
import { Arena, Gun } from '../components/gun.component.ts';
|
|
6
6
|
import { spawnPoints } from '../level/build.ts';
|
|
@@ -22,8 +22,9 @@ export const Players = defineListener('arena.players', (on) => {
|
|
|
22
22
|
Collider2D.box({ width: 14, height: 18, offset: { x: 0, y: 3 }, friction: 0 }),
|
|
23
23
|
Fighter({ owner: player, color, name, spawn: at, invulnerable: 90 }),
|
|
24
24
|
Label2D({ text: name, offset: { x: 0, y: -13 }, size: 16, background: '#f4f4f2b3', owner: player }), // o próprio sai com as cores trocadas
|
|
25
|
+
NetOwner({ player }), // nos outros clientes, desenhado interpolado (desliza) em vez de previsto
|
|
25
26
|
]);
|
|
26
|
-
world.spawn(`gun-${player}`, [Transform2D(at), Sprite({ asset: 'sprites/pistol', layer: 4, anchor: { x: 0.25, y: 0.5 } }), Gun({ owner: player })]);
|
|
27
|
+
world.spawn(`gun-${player}`, [Transform2D(at), Sprite({ asset: 'sprites/pistol', layer: 4, anchor: { x: 0.25, y: 0.5 } }), Gun({ owner: player }), NetOwner({ player })]);
|
|
27
28
|
});
|
|
28
29
|
on(NetPlayerLeft, ({ player }, { world }) => {
|
|
29
30
|
if (world.exists(`fighter-${player}`)) world.despawn(`fighter-${player}`);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { defineSystem, type EntityRef } from '@vibe-engine/core';
|
|
2
2
|
import { Collider2D, Grounded, RigidBody2D, Sprite, Transform2D, overlap, raycast } from '@vibe-engine/2d';
|
|
3
|
+
import { NetOwner } from '@vibe-engine/net';
|
|
3
4
|
import { Fighter } from '../components/fighter.component.ts';
|
|
4
5
|
import { Arena, Bullet, Gun, Tracer } from '../components/gun.component.ts';
|
|
5
6
|
import { KnifeSwung, RifleFired, ShotFired, WeaponSwapped } from '../events/combat.events.ts';
|
|
@@ -81,6 +82,7 @@ export const GunControl = defineSystem('gun.control', {
|
|
|
81
82
|
Transform2D({ x: muzzle.x, y: muzzle.y, rotation: t.rotation }),
|
|
82
83
|
Sprite({ width: length, height: 1, color: '#fff6c8', anchor: { x: 0, y: 0.5 }, layer: 5 }),
|
|
83
84
|
Tracer(),
|
|
85
|
+
NetOwner({ player: gun.owner }),
|
|
84
86
|
]);
|
|
85
87
|
emit(RifleFired, { gun: g.id, from: muzzle, to, hit: hit?.entity ?? '' });
|
|
86
88
|
continue;
|
|
@@ -97,6 +99,7 @@ export const GunControl = defineSystem('gun.control', {
|
|
|
97
99
|
RigidBody2D({ type: 'kinematic', velocity: { x: dir.x * gun.bulletSpeed, y: dir.y * gun.bulletSpeed } }),
|
|
98
100
|
Collider2D.circle({ radius: 2, trigger: true }),
|
|
99
101
|
Bullet({ owner: gun.owner }),
|
|
102
|
+
NetOwner({ player: gun.owner }), // a bala dos outros sai do cano que você vê (no passado)
|
|
100
103
|
]);
|
|
101
104
|
emit(ShotFired, { gun: g.id, bullet: id, dir: { x: dir.x, y: dir.y } });
|
|
102
105
|
}
|
|
@@ -219,3 +219,28 @@ test('player names: no name typed means the fighter is called by its color', asy
|
|
|
219
219
|
assert.equal(fighter(w, 'p2').name, 'blue');
|
|
220
220
|
assert.equal(w.entity('fighter-p2').read(Label2D).text, 'blue');
|
|
221
221
|
});
|
|
222
|
+
|
|
223
|
+
test('interpolation: the other player slides smoothly on my screen (no correction jumps) even zigzagging over a jittery link', async () => {
|
|
224
|
+
const clock = createClock();
|
|
225
|
+
const sw = await openScene(root, { scene: 'arena' });
|
|
226
|
+
const server = createNetServer(sw);
|
|
227
|
+
const cs: Array<{ world: World; client: NetClient }> = [];
|
|
228
|
+
for (const seed of [1, 2]) {
|
|
229
|
+
const net = createLoopback(clock, { latencyMs: 50, jitterMs: 20, seed });
|
|
230
|
+
server.connect(net.server);
|
|
231
|
+
const world = await openScene(root, { scene: 'arena' });
|
|
232
|
+
cs.push({ world, client: createNetClient(world, net.client) });
|
|
233
|
+
}
|
|
234
|
+
const tick = () => { clock.advance(1000 / 60); server.tick(); for (const c of cs) c.client.tick(); };
|
|
235
|
+
for (let i = 0; i < 150; i++) tick();
|
|
236
|
+
const [me, other] = cs as [typeof cs[0], typeof cs[0]];
|
|
237
|
+
const shown: number[] = [];
|
|
238
|
+
for (let i = 0; i < 400; i++) {
|
|
239
|
+
if (i % 23 === 0) other.client.input.set('move', Math.floor(i / 23) % 2 ? -1 : 1);
|
|
240
|
+
tick();
|
|
241
|
+
shown.push(me.world.entity('fighter-p2').read(Transform2D).x + (me.world.visualOffsets.get('fighter-p2')?.x ?? 0));
|
|
242
|
+
}
|
|
243
|
+
const worst = Math.max(...shown.slice(1).map((v, i) => Math.abs(v - shown[i]!)));
|
|
244
|
+
assert.ok(worst < 2.6, `biggest on-screen step of the other fighter ${worst.toFixed(2)} px/tick (walk speed ≈ 2.2; extrapolation gave ~6.5)`);
|
|
245
|
+
assert.equal(me.client.stats.corrections, 0, 'remote fighters are drawn from server positions, never corrected');
|
|
246
|
+
});
|