@nodetool-ai/game-runtime 0.8.19 → 0.8.21

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 (64) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/adventure.d.ts +42 -0
  3. package/dist/adventure.d.ts.map +1 -0
  4. package/dist/adventure.js +733 -0
  5. package/dist/adventure.js.map +1 -0
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/native-browser/assets.d.ts +19 -0
  11. package/dist/native-browser/assets.d.ts.map +1 -0
  12. package/dist/native-browser/assets.js +70 -0
  13. package/dist/native-browser/assets.js.map +1 -0
  14. package/dist/native-browser/index.d.ts +6 -0
  15. package/dist/native-browser/index.d.ts.map +1 -0
  16. package/dist/native-browser/index.js +5 -0
  17. package/dist/native-browser/index.js.map +1 -0
  18. package/dist/native-browser/input.d.ts +70 -0
  19. package/dist/native-browser/input.d.ts.map +1 -0
  20. package/dist/native-browser/input.js +298 -0
  21. package/dist/native-browser/input.js.map +1 -0
  22. package/dist/native-browser/saves.d.ts +37 -0
  23. package/dist/native-browser/saves.d.ts.map +1 -0
  24. package/dist/native-browser/saves.js +187 -0
  25. package/dist/native-browser/saves.js.map +1 -0
  26. package/dist/native-browser/session.d.ts +46 -0
  27. package/dist/native-browser/session.d.ts.map +1 -0
  28. package/dist/native-browser/session.js +206 -0
  29. package/dist/native-browser/session.js.map +1 -0
  30. package/dist/native-browser/wasm.d.ts +28 -0
  31. package/dist/native-browser/wasm.d.ts.map +1 -0
  32. package/dist/native-browser/wasm.js +68 -0
  33. package/dist/native-browser/wasm.js.map +1 -0
  34. package/dist/native-browser/worker.d.ts +8 -0
  35. package/dist/native-browser/worker.d.ts.map +1 -0
  36. package/dist/native-browser/worker.js +109 -0
  37. package/dist/native-browser/worker.js.map +1 -0
  38. package/dist/native-editor-client.d.ts +1283 -0
  39. package/dist/native-editor-client.d.ts.map +1 -0
  40. package/dist/native-editor-client.js +106 -0
  41. package/dist/native-editor-client.js.map +1 -0
  42. package/dist/native-game-export.mjs +112 -0
  43. package/dist/native-game-notices.txt +934 -0
  44. package/dist/native-game-web-export.mjs +125 -0
  45. package/dist/native-json-save-files.d.ts +8 -0
  46. package/dist/native-json-save-files.d.ts.map +1 -0
  47. package/dist/native-json-save-files.js +95 -0
  48. package/dist/native-json-save-files.js.map +1 -0
  49. package/dist/native-template.d.ts +14 -0
  50. package/dist/native-template.d.ts.map +1 -0
  51. package/dist/native-template.js +99 -0
  52. package/dist/native-template.js.map +1 -0
  53. package/dist/native-worker.d.ts +36 -0
  54. package/dist/native-worker.d.ts.map +1 -0
  55. package/dist/native-worker.js +158 -0
  56. package/dist/native-worker.js.map +1 -0
  57. package/dist/native.d.ts +49 -0
  58. package/dist/native.d.ts.map +1 -0
  59. package/dist/native.js +305 -0
  60. package/dist/native.js.map +1 -0
  61. package/dist/systems/presentation2d.d.ts.map +1 -1
  62. package/dist/systems/presentation2d.js +3 -1
  63. package/dist/systems/presentation2d.js.map +1 -1
  64. package/package.json +32 -7
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-editor-client.d.ts","sourceRoot":"","sources":["../src/native-editor-client.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,QAAA,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AACtE,MAAM,MAAM,kBAAkB,GAAG,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,QAAQ,CAAC,EAAE;IAAE,MAAM,EAAE,IAAI,CAAA;CAAE,CAAC,CAAC,QAAQ,CAAC,CAAC;AAC/F,qBAAa,iBAAkB,SAAQ,KAAK;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM;IAAmB,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM;IAArF,YAAqB,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAW,eAAe,CAAC,EAAE,MAAM,YAAA,EAAsD;CAC5I;AACD,gGAAgG;AAChG,wBAAsB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,mBAAmB,EAAE,OAAO,GAAE;IAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,IAAI,GAAG,IAAI,CAAA;CAAO,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAkDhS"}
@@ -0,0 +1,106 @@
1
+ import { createConnection } from "node:net";
2
+ import { randomUUID } from "node:crypto";
3
+ import { z } from "zod";
4
+ import { nativeGameDocument, nativeGameTransactionForDimension } from "@nodetool-ai/protocol/native-game";
5
+ const response = z.discriminatedUnion("status", [
6
+ z.object({ status: z.literal("ok"), result: z.object({ document: nativeGameDocument, revision: z.number().int().nonnegative(), playing: z.boolean() }).passthrough() }),
7
+ z.object({ status: z.literal("error"), error: z.object({ code: z.string(), message: z.string(), currentRevision: z.number().int().nonnegative().optional() }) })
8
+ ]);
9
+ export const nativeEditorRequest = z.discriminatedUnion("operation", [
10
+ z.object({ operation: z.literal("inspect") }),
11
+ z.object({ operation: z.literal("transaction"), expectedRevision: z.number().int().nonnegative(), operations: z.array(z.record(z.string(), z.json())).min(1).max(1024) }),
12
+ z.object({ operation: z.enum(["undo", "redo"]), expectedRevision: z.number().int().nonnegative() }),
13
+ z.object({ operation: z.enum(["save", "start", "stop", "step"]) }),
14
+ z.object({ operation: z.literal("select"), entityId: z.string().min(1).max(128) })
15
+ ]);
16
+ export class NativeEditorError extends Error {
17
+ code;
18
+ currentRevision;
19
+ constructor(code, message, currentRevision) {
20
+ super(message);
21
+ this.code = code;
22
+ this.currentRevision = currentRevision;
23
+ this.name = "NativeEditorError";
24
+ }
25
+ }
26
+ /** Sends an operation to the live editor's user-local socket, sharing its document revision. */
27
+ export async function requestNativeEditor(socketPath, input, options = {}) {
28
+ options.signal?.throwIfAborted();
29
+ let request = nativeEditorRequest.parse(input);
30
+ if (request.operation === "transaction") {
31
+ if (!options.dimension) {
32
+ const { requestId: _requestId, ...inspectionOptions } = options;
33
+ const inspected = await requestNativeEditor(socketPath, { operation: "inspect" }, inspectionOptions);
34
+ return requestNativeEditor(socketPath, input, { ...options, dimension: inspected.document.dimension, documentId: options.documentId ?? inspected.document.id });
35
+ }
36
+ const transaction = nativeGameTransactionForDimension(options.dimension).parse({ requestId: options.requestId ?? randomUUID(), expectedRevision: request.expectedRevision, operations: request.operations });
37
+ request = { operation: "transaction", expectedRevision: transaction.expectedRevision, operations: transaction.operations };
38
+ }
39
+ const requestId = options.requestId ?? randomUUID();
40
+ const timeoutMs = z.number().int().min(1).max(60_000).parse(options.timeoutMs ?? 10_000);
41
+ const requestEnvelope = { protocolVersion: 1, requestId, ...request };
42
+ if (options.documentId) {
43
+ requestEnvelope.documentId = options.documentId;
44
+ }
45
+ const payload = Buffer.from(`${JSON.stringify(requestEnvelope)}\n`);
46
+ if (payload.length > 4 * 1024 * 1024) {
47
+ throw new NativeEditorError("resource_limit", "Editor request exceeds frame limit");
48
+ }
49
+ return await new Promise((resolve, reject) => {
50
+ const socket = createConnection(socketPath);
51
+ let bytes = Buffer.alloc(0);
52
+ let settled = false;
53
+ const finish = (error, result) => {
54
+ if (settled) {
55
+ return;
56
+ }
57
+ settled = true;
58
+ clearTimeout(timer);
59
+ options.signal?.removeEventListener("abort", abort);
60
+ socket.destroy();
61
+ if (error) {
62
+ reject(error);
63
+ }
64
+ else if (result) {
65
+ resolve(result);
66
+ }
67
+ };
68
+ const abort = () => finish(new NativeEditorError("cancelled", "Editor request cancelled"));
69
+ const timer = setTimeout(() => finish(new NativeEditorError("timeout", "Editor request timed out")), timeoutMs);
70
+ options.signal?.addEventListener("abort", abort, { once: true });
71
+ if (options.signal?.aborted) {
72
+ abort();
73
+ return;
74
+ }
75
+ socket.once("connect", () => socket.write(payload));
76
+ socket.once("error", (error) => finish(error));
77
+ socket.once("close", () => { if (!settled) {
78
+ finish(new NativeEditorError("worker_failed", "Editor socket closed before responding"));
79
+ } });
80
+ socket.on("data", (chunk) => {
81
+ bytes = Buffer.concat([bytes, chunk]);
82
+ if (bytes.length > 8 * 1024 * 1024) {
83
+ finish(new NativeEditorError("resource_limit", "Editor response exceeds frame limit"));
84
+ return;
85
+ }
86
+ const end = bytes.indexOf(10);
87
+ if (end < 0) {
88
+ return;
89
+ }
90
+ try {
91
+ const envelope = z.object({ requestId: z.literal(requestId), protocolVersion: z.literal(1).default(1) }).passthrough().parse(JSON.parse(bytes.subarray(0, end).toString("utf8")));
92
+ const parsed = response.parse(envelope);
93
+ if (parsed.status === "error") {
94
+ finish(new NativeEditorError(parsed.error.code, parsed.error.message, parsed.error.currentRevision));
95
+ }
96
+ else {
97
+ finish(undefined, parsed.result);
98
+ }
99
+ }
100
+ catch (error) {
101
+ finish(new NativeEditorError("protocol_error", z.string().catch("Invalid editor response").parse(error instanceof Error ? error.message : error)));
102
+ }
103
+ });
104
+ });
105
+ }
106
+ //# sourceMappingURL=native-editor-client.js.map
@@ -0,0 +1 @@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0 +1,112 @@
1
+ #!/usr/bin/env node
2
+ import { createHash } from 'node:crypto';
3
+ import { spawn } from 'node:child_process';
4
+ import { constants } from 'node:fs';
5
+ import { access, chmod, cp, copyFile, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
6
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
7
+ import { platform, arch } from 'node:os';
8
+ import { fileURLToPath } from 'node:url';
9
+
10
+ async function run(command, args, options = {}) {
11
+ return await new Promise((resolveRun, reject) => {
12
+ const child = spawn(command, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] });
13
+ let output = '', errors = '';
14
+ child.stdout.on('data', chunk => { output += chunk; if (output.length > 4 * 1024 * 1024) { child.kill(); } });
15
+ child.stderr.on('data', chunk => { errors = (errors + chunk).slice(-65536); });
16
+ const timer = setTimeout(() => child.kill(), 120000);
17
+ child.once('error', reject);
18
+ child.once('close', (code, signal) => { clearTimeout(timer); if (code === 0) { resolveRun(output); } else { reject(new Error(`${command} failed (${signal ?? code}): ${errors}`)); } });
19
+ });
20
+ }
21
+ const sha = bytes => createHash('sha256').update(bytes).digest('hex');
22
+ function inside(root, path) { const rel = relative(root, path); return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); }
23
+ async function exists(path) { try { await access(path); return true; } catch { return false; } }
24
+ async function files(root, path = root) {
25
+ const result = [];
26
+ for (const entry of await readdir(path, { withFileTypes: true })) {
27
+ const candidate = join(path, entry.name);
28
+ if (entry.isDirectory()) { result.push(...await files(root, candidate)); }
29
+ else if (entry.isSymbolicLink()) {
30
+ const target = await realpath(candidate);
31
+ if (!inside(root, target) || !(await stat(target)).isFile()) { throw new Error(`Runtime symlink escapes distribution or targets a directory: ${candidate}`); }
32
+ await rm(candidate); await copyFile(target,candidate); result.push(candidate);
33
+ } else if (entry.isFile()) { result.push(candidate); }
34
+ }
35
+ return result;
36
+ }
37
+
38
+ /** Export only verified authored content and a deployed runtime, never the host environment. */
39
+ export async function exportNativePlayer(options) {
40
+ const output = resolve(options.output);
41
+ if (await exists(output)) { throw new Error('Export destination already exists'); }
42
+ const sourcePath = resolve(options.document);
43
+ const bytes = await readFile(sourcePath);
44
+ if (bytes.length > 4 * 1024 * 1024) { throw new Error('Document exceeds 4 MiB'); }
45
+ const document = JSON.parse(bytes.toString('utf8'));
46
+ document.assets ??= [];
47
+ if (document.engine !== 'native-cpp-1' || !((document.schemaVersion === 4 && document.dimension === '3d') || (document.schemaVersion === 5 && document.dimension === '2d')) || !Array.isArray(document.assets) || document.assets.length > 100000) { throw new Error('Expected native C++ dimensional document with prepared asset manifest'); }
48
+ await mkdir(dirname(output), { recursive: true });
49
+ const stage = await mkdtemp(join(dirname(output), '.native-game-export-'));
50
+ const root = await realpath(resolve(options.assetsRoot ?? dirname(sourcePath)));
51
+ try {
52
+ if (options.runtimeDir) {
53
+ for (const entry of await readdir(resolve(options.runtimeDir))) {
54
+ await cp(join(resolve(options.runtimeDir), entry), join(stage,entry), { recursive:true,force:false,errorOnExist:true,verbatimSymlinks:true });
55
+ }
56
+ } else {
57
+ if (!options.buildDir) { throw new Error('Provide --build-dir or --runtime-dir containing a deployed native player'); }
58
+ await run('cmake', ['--install', resolve(options.buildDir), '--prefix', stage, '--strip']);
59
+ }
60
+ await files(stage);
61
+ const player = join(stage, 'bin', platform() === 'win32' ? 'game-player.exe' : 'game-player');
62
+ const worker = join(stage, 'bin', platform() === 'win32' ? 'game-worker.exe' : 'game-worker');
63
+ await access(player, constants.X_OK); await access(worker, constants.X_OK);
64
+ for (const notice of ['Luau-LICENSE', 'Lua-LICENSE', 'Jolt-LICENSE', 'nlohmann-json-LICENSE']) { await access(join(stage, 'share', 'nodetool-game', 'licenses', notice)); }
65
+ await mkdir(join(stage, 'assets'), {recursive:true});
66
+ const manifest = new Map(); let total = 0;
67
+ for (const asset of document.assets) {
68
+ if (typeof asset.id !== 'string' || manifest.has(asset.id) || typeof asset.path !== 'string' || isAbsolute(asset.path) || asset.path.includes('\\') || asset.path.split('/').some(part => !part || part === '..' || part === '.') || !/^[a-f0-9]{64}$/.test(asset.digest) || !Number.isSafeInteger(asset.size) || asset.size < 0 || asset.size > 64 * 1024 * 1024) { throw new Error('Invalid prepared asset entry'); }
69
+ const source = await realpath(resolve(root, asset.path));
70
+ if (!inside(root, source) || !(await stat(source)).isFile()) { throw new Error(`Asset leaves prepared root: ${asset.id}`); }
71
+ const data = await readFile(source); total += data.length;
72
+ if (total > 256 * 1024 * 1024 || data.length !== asset.size || sha(data) !== asset.digest) { throw new Error(`Asset digest, size or total budget mismatch: ${asset.id}`); }
73
+ manifest.set(asset.id, asset);
74
+ const target = join(stage, 'assets', asset.path); await mkdir(dirname(target), { recursive: true }); await writeFile(target, data);
75
+ }
76
+ for (const asset of manifest.values()) { for (const id of asset.dependencies ?? []) { if (!manifest.has(id)) { throw new Error(`Missing asset dependency: ${id}`); } } }
77
+ const documentText = JSON.stringify(document);
78
+ await writeFile(join(stage, 'game.json'), documentText);
79
+ const smoke = join(stage, '.export-check'); await mkdir(smoke);
80
+ const args = [join(stage, 'game.json'), '--assets-dir', join(stage, 'assets'), '--capture', join(smoke, 'frame.png'), '--tick', '0', '--report', join(smoke, 'render.json')];
81
+ // Keep display/driver configuration, but remove application credentials and development loaders.
82
+ const environment = Object.fromEntries(Object.entries(process.env).filter(([key]) => ['PATH','DISPLAY','WAYLAND_DISPLAY','XDG_RUNTIME_DIR','HOME','TMPDIR','LANG','LC_ALL','VK_ICD_FILENAMES','VK_DRIVER_FILES','QSG_RHI_BACKEND','QT_QPA_PLATFORM'].includes(key)));
83
+ if (platform() === 'linux') { environment.QT_QPA_PLATFORM='xcb'; environment.QSG_RHI_BACKEND='vulkan'; }
84
+ const command = platform() === 'linux' ? 'xvfb-run' : player;
85
+ const smokeArgs = command === player ? args : ['-a', player, ...args];
86
+ await run(command, smokeArgs, { cwd: stage, env: environment });
87
+ const smokeReport = JSON.parse(await readFile(join(smoke, 'render.json'), 'utf8')); delete smokeReport.capture; smokeReport.captureVerified=true; await rm(smoke, { recursive: true });
88
+ const launcher = platform() === 'win32' ? 'play.cmd' : 'play';
89
+ const launchText = platform() === 'win32' ? '@echo off\r\n"%~dp0bin\\game-player.exe" "%~dp0game.json" --assets-dir "%~dp0assets" %*\r\n' : '#!/bin/sh\nTASK_GAME_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)\nexec "$TASK_GAME_DIR/bin/game-player" "$TASK_GAME_DIR/game.json" --assets-dir "$TASK_GAME_DIR/assets" "$@"\n';
90
+ await writeFile(join(stage, launcher), launchText); await chmod(join(stage, launcher), 0o755);
91
+ const inventory = [];
92
+ for (const path of await files(stage)) { const data = await readFile(path); inventory.push({ path: relative(stage, path).split(sep).join('/'), size: data.length, digest: sha(data) }); }
93
+ inventory.sort((a,b) => a.path.localeCompare(b.path));
94
+ const report = { engine: 'native-cpp-1', schemaVersion: document.schemaVersion, dimension: document.dimension, platform: platform(), architecture: arch(), documentDigest: sha(Buffer.from(documentText)), assetBytes: total, entry: launcher, files: inventory, smoke: smokeReport };
95
+ await writeFile(join(stage, 'bundle.json'), JSON.stringify(report, null, 2) + '\n');
96
+ await rename(stage, output);
97
+ return { ...report, output };
98
+ } catch (error) { await rm(stage, { recursive: true, force: true }); throw error; }
99
+ }
100
+
101
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
102
+ try {
103
+ const options = {};
104
+ for (let i=2;i<process.argv.length;i+=2) {
105
+ const key = process.argv[i], value = process.argv[i+1];
106
+ if (!value || !['--document','--assets-root','--build-dir','--runtime-dir','--output'].includes(key)) { throw new Error('Usage: native-game-export --document FILE --assets-root DIR (--build-dir DIR | --runtime-dir DIR) --output DIR'); }
107
+ options[{'--document':'document','--assets-root':'assetsRoot','--build-dir':'buildDir','--runtime-dir':'runtimeDir','--output':'output'}[key]] = value;
108
+ }
109
+ if (!options.document || !options.output) { throw new Error('Document and output are required'); }
110
+ console.log(JSON.stringify(await exportNativePlayer(options)));
111
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
112
+ }