mirror of
https://github.com/sortedcord/omnia.git
synced 2026-07-22 12:02:49 +05:30
MAJOR: Removed old scenario builder and moved scenario loader into packages/scenario
This commit is contained in:
@@ -1,18 +0,0 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
6
content/scenario-builder/next-env.d.ts
vendored
6
content/scenario-builder/next-env.d.ts
vendored
@@ -1,6 +0,0 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/types/routes.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { NextConfig } from "next";
|
||||
import { networkInterfaces } from "os";
|
||||
|
||||
const getLocalIPs = () => {
|
||||
const ips: string[] = ["localhost", "127.0.0.1"];
|
||||
const nets = networkInterfaces();
|
||||
for (const name of Object.keys(nets)) {
|
||||
for (const net of nets[name] || []) {
|
||||
if (net.family === "IPv4" && !net.internal) {
|
||||
ips.push(net.address);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ips;
|
||||
};
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
allowedDevOrigins: getLocalIPs(),
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/api/:path*",
|
||||
headers: [
|
||||
{ key: "Access-Control-Allow-Origin", value: "*" },
|
||||
{ key: "Access-Control-Allow-Methods", value: "GET,POST,PUT,DELETE,OPTIONS" },
|
||||
{ key: "Access-Control-Allow-Headers", value: "Content-Type, Authorization" },
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -1,27 +0,0 @@
|
||||
{
|
||||
"name": "scenario-builder",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "16.2.10",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"@omnia/core": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.2.10",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -1 +0,0 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
Before Width: | Height: | Size: 391 B |
@@ -1 +0,0 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
@@ -1 +0,0 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
Before Width: | Height: | Size: 128 B |
@@ -1 +0,0 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
Before Width: | Height: | Size: 385 B |
@@ -1,125 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import Database from "better-sqlite3";
|
||||
import { WorldState, Entity, SQLiteRepository, AttributeVisibility } from "@omnia/core";
|
||||
import path from "path";
|
||||
|
||||
const DB_PATH = path.resolve("/home/sortedcord/Projects/omnia_umbrella/omnia/omnia.db");
|
||||
|
||||
function getRepo() {
|
||||
const db = new Database(DB_PATH);
|
||||
return { repo: new SQLiteRepository(db), db };
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const id = searchParams.get("id");
|
||||
|
||||
const { repo, db } = getRepo();
|
||||
|
||||
try {
|
||||
if (id) {
|
||||
const world = repo.loadWorldState(id);
|
||||
if (!world) {
|
||||
return NextResponse.json({ error: `World with ID ${id} not found` }, { status: 404 });
|
||||
}
|
||||
|
||||
// Serialize world
|
||||
const serialized = {
|
||||
id: world.id,
|
||||
attributes: Array.from(world.attributes.values()).map(attr => ({
|
||||
name: attr.name,
|
||||
value: attr.getValue(),
|
||||
visibility: attr.getVisibility(),
|
||||
allowedEntities: Array.from(attr.getAllowedEntities())
|
||||
})),
|
||||
entities: Array.from(world.entities.values()).map(entity => ({
|
||||
id: entity.id,
|
||||
attributes: Array.from(entity.attributes.values()).map(attr => ({
|
||||
name: attr.name,
|
||||
value: attr.getValue(),
|
||||
visibility: attr.getVisibility(),
|
||||
allowedEntities: Array.from(attr.getAllowedEntities())
|
||||
}))
|
||||
}))
|
||||
};
|
||||
return NextResponse.json(serialized);
|
||||
} else {
|
||||
// List all worlds
|
||||
const rows = db.prepare("SELECT id FROM objects WHERE type = 'world'").all() as { id: string }[];
|
||||
const worlds = [];
|
||||
for (const row of rows) {
|
||||
const world = repo.loadWorldState(row.id);
|
||||
if (world) {
|
||||
const nameAttr = world.attributes.get("name")?.getValue() || "Unnamed World";
|
||||
worlds.push({
|
||||
id: world.id,
|
||||
name: nameAttr
|
||||
});
|
||||
}
|
||||
}
|
||||
return NextResponse.json({ worlds });
|
||||
}
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("API GET Error:", error);
|
||||
const message = error instanceof Error ? error.message : "Internal Server Error";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const payload = await request.json();
|
||||
if (!payload.id) {
|
||||
return NextResponse.json({ error: "World ID is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { repo, db } = getRepo();
|
||||
|
||||
try {
|
||||
const world = new WorldState(payload.id);
|
||||
|
||||
// Add attributes to world
|
||||
if (payload.attributes && Array.isArray(payload.attributes)) {
|
||||
for (const attr of payload.attributes) {
|
||||
world.addAttribute(
|
||||
attr.name,
|
||||
attr.value,
|
||||
attr.visibility || AttributeVisibility.PUBLIC,
|
||||
attr.allowedEntities ? new Set(attr.allowedEntities) : null
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Add entities to world
|
||||
if (payload.entities && Array.isArray(payload.entities)) {
|
||||
for (const ent of payload.entities) {
|
||||
const entity = new Entity(ent.id);
|
||||
if (ent.attributes && Array.isArray(ent.attributes)) {
|
||||
for (const attr of ent.attributes) {
|
||||
entity.addAttribute(
|
||||
attr.name,
|
||||
attr.value,
|
||||
attr.visibility || AttributeVisibility.PRIVATE,
|
||||
attr.allowedEntities ? new Set(attr.allowedEntities) : null
|
||||
);
|
||||
}
|
||||
}
|
||||
world.addEntity(entity);
|
||||
}
|
||||
}
|
||||
|
||||
repo.saveWorldState(world);
|
||||
return NextResponse.json({ success: true, worldId: world.id });
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("API POST Error:", error);
|
||||
const message = error instanceof Error ? error.message : "Internal Server Error";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 25 KiB |
@@ -1,6 +0,0 @@
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
padding: 10px;
|
||||
background-color: white;
|
||||
color: black;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html
|
||||
lang="en"
|
||||
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
|
||||
>
|
||||
<body className="min-h-full flex flex-col">{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -1,586 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
function generateUUID(): string {
|
||||
if (typeof window !== "undefined" && window.crypto && window.crypto.randomUUID) {
|
||||
return window.crypto.randomUUID();
|
||||
}
|
||||
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
||||
const r = (Math.random() * 16) | 0;
|
||||
const v = c === "x" ? r : (r & 0x3) | 0x8;
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
|
||||
interface Attribute {
|
||||
name: string;
|
||||
value: string;
|
||||
visibility: "PUBLIC" | "PRIVATE";
|
||||
allowedEntities: string[];
|
||||
}
|
||||
|
||||
interface Entity {
|
||||
id: string;
|
||||
attributes: Attribute[];
|
||||
}
|
||||
|
||||
interface WorldData {
|
||||
id: string;
|
||||
attributes: Attribute[];
|
||||
entities: Entity[];
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
const [worldsList, setWorldsList] = useState<{ id: string; name: string }[]>([]);
|
||||
const [selectedWorldId, setSelectedWorldId] = useState<string>("");
|
||||
const [worldData, setWorldData] = useState<WorldData | null>(null);
|
||||
const [status, setStatus] = useState<string>("");
|
||||
const [error, setError] = useState<string>("");
|
||||
|
||||
// Temp state for adding new attributes / entities
|
||||
const [newWorldAttribute, setNewWorldAttribute] = useState<{ name: string; value: string; visibility: "PUBLIC" | "PRIVATE" }>({ name: "", value: "", visibility: "PUBLIC" });
|
||||
const [newEntityAttribute, setNewEntityAttribute] = useState<Record<string, { name: string; value: string; visibility: "PUBLIC" | "PRIVATE" }>>({});
|
||||
|
||||
const fetchWorlds = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/world");
|
||||
if (!res.ok) throw new Error("Failed to fetch worlds");
|
||||
const data = await res.json();
|
||||
setWorldsList(data.worlds || []);
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : "Failed to load worlds list";
|
||||
setError(msg);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
fetchWorlds();
|
||||
}, []);
|
||||
|
||||
const handleCreateNewWorld = () => {
|
||||
const newId = generateUUID();
|
||||
setWorldData({
|
||||
id: newId,
|
||||
attributes: [{ name: "name", value: "New World", visibility: "PUBLIC", allowedEntities: [] }],
|
||||
entities: []
|
||||
});
|
||||
setSelectedWorldId("");
|
||||
setStatus("Created new world locally. Don't forget to save!");
|
||||
setError("");
|
||||
};
|
||||
|
||||
const handleLoadWorld = async (id: string) => {
|
||||
if (!id) return;
|
||||
try {
|
||||
setStatus(`Loading world ${id}...`);
|
||||
setError("");
|
||||
const res = await fetch(`/api/world?id=${id}`);
|
||||
if (!res.ok) throw new Error("Failed to load world data");
|
||||
const data = await res.json();
|
||||
setWorldData(data);
|
||||
setSelectedWorldId(id);
|
||||
setStatus(`Loaded world successfully!`);
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : "Failed to load world";
|
||||
setError(msg);
|
||||
setStatus("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveWorld = async () => {
|
||||
if (!worldData) return;
|
||||
try {
|
||||
setStatus("Saving world to database...");
|
||||
setError("");
|
||||
const res = await fetch("/api/world", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(worldData)
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || "Failed to save world");
|
||||
|
||||
setStatus("World saved successfully!");
|
||||
fetchWorlds();
|
||||
setSelectedWorldId(worldData.id);
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : "Failed to save world";
|
||||
setError(msg);
|
||||
setStatus("");
|
||||
}
|
||||
};
|
||||
|
||||
// World Attribute management
|
||||
const addWorldAttribute = () => {
|
||||
if (!worldData || !newWorldAttribute.name.trim()) return;
|
||||
if (worldData.attributes.some(a => a.name === newWorldAttribute.name)) {
|
||||
setError(`Attribute "${newWorldAttribute.name}" already exists on world.`);
|
||||
return;
|
||||
}
|
||||
setWorldData({
|
||||
...worldData,
|
||||
attributes: [
|
||||
...worldData.attributes,
|
||||
{ name: newWorldAttribute.name, value: newWorldAttribute.value, visibility: newWorldAttribute.visibility, allowedEntities: [] }
|
||||
]
|
||||
});
|
||||
setNewWorldAttribute({ name: "", value: "", visibility: "PUBLIC" });
|
||||
setError("");
|
||||
};
|
||||
|
||||
const removeWorldAttribute = (name: string) => {
|
||||
if (!worldData) return;
|
||||
setWorldData({
|
||||
...worldData,
|
||||
attributes: worldData.attributes.filter(a => a.name !== name)
|
||||
});
|
||||
};
|
||||
|
||||
const updateWorldAttributeValue = (name: string, value: string) => {
|
||||
if (!worldData) return;
|
||||
setWorldData({
|
||||
...worldData,
|
||||
attributes: worldData.attributes.map(a => a.name === name ? { ...a, value } : a)
|
||||
});
|
||||
};
|
||||
|
||||
const updateWorldAttributeVisibility = (name: string, visibility: "PUBLIC" | "PRIVATE") => {
|
||||
if (!worldData) return;
|
||||
setWorldData({
|
||||
...worldData,
|
||||
attributes: worldData.attributes.map(a => a.name === name ? { ...a, visibility, allowedEntities: visibility === "PUBLIC" ? [] : a.allowedEntities } : a)
|
||||
});
|
||||
};
|
||||
|
||||
// Entity management
|
||||
const handleAddEntity = () => {
|
||||
if (!worldData) return;
|
||||
const newId = generateUUID();
|
||||
const newEntity: Entity = {
|
||||
id: newId,
|
||||
attributes: [{ name: "name", value: "New Entity", visibility: "PRIVATE", allowedEntities: [] }]
|
||||
};
|
||||
setWorldData({
|
||||
...worldData,
|
||||
entities: [...worldData.entities, newEntity]
|
||||
});
|
||||
};
|
||||
|
||||
const handleRemoveEntity = (entityId: string) => {
|
||||
if (!worldData) return;
|
||||
// Also clean up this entity from all attribute ACL lists
|
||||
const updatedEntities = worldData.entities.filter(e => e.id !== entityId).map(e => ({
|
||||
...e,
|
||||
attributes: e.attributes.map(a => ({
|
||||
...a,
|
||||
allowedEntities: a.allowedEntities.filter(id => id !== entityId)
|
||||
}))
|
||||
}));
|
||||
|
||||
const updatedWorldAttributes = worldData.attributes.map(a => ({
|
||||
...a,
|
||||
allowedEntities: a.allowedEntities.filter(id => id !== entityId)
|
||||
}));
|
||||
|
||||
setWorldData({
|
||||
...worldData,
|
||||
attributes: updatedWorldAttributes,
|
||||
entities: updatedEntities
|
||||
});
|
||||
};
|
||||
|
||||
// Entity Attribute management
|
||||
const addEntityAttribute = (entityId: string) => {
|
||||
if (!worldData) return;
|
||||
const input = newEntityAttribute[entityId];
|
||||
if (!input || !input.name.trim()) return;
|
||||
|
||||
const entity = worldData.entities.find(e => e.id === entityId);
|
||||
if (!entity) return;
|
||||
|
||||
if (entity.attributes.some(a => a.name === input.name)) {
|
||||
setError(`Attribute "${input.name}" already exists on entity.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedEntities = worldData.entities.map(e => {
|
||||
if (e.id === entityId) {
|
||||
return {
|
||||
...e,
|
||||
attributes: [
|
||||
...e.attributes,
|
||||
{ name: input.name, value: input.value, visibility: input.visibility, allowedEntities: [] }
|
||||
]
|
||||
};
|
||||
}
|
||||
return e;
|
||||
});
|
||||
|
||||
setWorldData({ ...worldData, entities: updatedEntities });
|
||||
setNewEntityAttribute({
|
||||
...newEntityAttribute,
|
||||
[entityId]: { name: "", value: "", visibility: "PRIVATE" }
|
||||
});
|
||||
setError("");
|
||||
};
|
||||
|
||||
const removeEntityAttribute = (entityId: string, attrName: string) => {
|
||||
if (!worldData) return;
|
||||
const updatedEntities = worldData.entities.map(e => {
|
||||
if (e.id === entityId) {
|
||||
return {
|
||||
...e,
|
||||
attributes: e.attributes.filter(a => a.name !== attrName)
|
||||
};
|
||||
}
|
||||
return e;
|
||||
});
|
||||
setWorldData({ ...worldData, entities: updatedEntities });
|
||||
};
|
||||
|
||||
const updateEntityAttributeValue = (entityId: string, attrName: string, value: string) => {
|
||||
if (!worldData) return;
|
||||
const updatedEntities = worldData.entities.map(e => {
|
||||
if (e.id === entityId) {
|
||||
return {
|
||||
...e,
|
||||
attributes: e.attributes.map(a => a.name === attrName ? { ...a, value } : a)
|
||||
};
|
||||
}
|
||||
return e;
|
||||
});
|
||||
setWorldData({ ...worldData, entities: updatedEntities });
|
||||
};
|
||||
|
||||
const updateEntityAttributeVisibility = (entityId: string, attrName: string, visibility: "PUBLIC" | "PRIVATE") => {
|
||||
if (!worldData) return;
|
||||
const updatedEntities = worldData.entities.map(e => {
|
||||
if (e.id === entityId) {
|
||||
return {
|
||||
...e,
|
||||
attributes: e.attributes.map(a => a.name === attrName ? { ...a, visibility, allowedEntities: visibility === "PUBLIC" ? [] : a.allowedEntities } : a)
|
||||
};
|
||||
}
|
||||
return e;
|
||||
});
|
||||
setWorldData({ ...worldData, entities: updatedEntities });
|
||||
};
|
||||
|
||||
const toggleEntityAcl = (targetEntityId: string, attrName: string, allowedEntityId: string, checked: boolean) => {
|
||||
if (!worldData) return;
|
||||
const updatedEntities = worldData.entities.map(e => {
|
||||
if (e.id === targetEntityId) {
|
||||
return {
|
||||
...e,
|
||||
attributes: e.attributes.map(a => {
|
||||
if (a.name === attrName) {
|
||||
const currentAcl = a.allowedEntities;
|
||||
const newAcl = checked
|
||||
? [...currentAcl, allowedEntityId]
|
||||
: currentAcl.filter(id => id !== allowedEntityId);
|
||||
return { ...a, allowedEntities: newAcl };
|
||||
}
|
||||
return a;
|
||||
})
|
||||
};
|
||||
}
|
||||
return e;
|
||||
});
|
||||
setWorldData({ ...worldData, entities: updatedEntities });
|
||||
};
|
||||
|
||||
const toggleWorldAcl = (attrName: string, allowedEntityId: string, checked: boolean) => {
|
||||
if (!worldData) return;
|
||||
setWorldData({
|
||||
...worldData,
|
||||
attributes: worldData.attributes.map(a => {
|
||||
if (a.name === attrName) {
|
||||
const currentAcl = a.allowedEntities;
|
||||
const newAcl = checked
|
||||
? [...currentAcl, allowedEntityId]
|
||||
: currentAcl.filter(id => id !== allowedEntityId);
|
||||
return { ...a, allowedEntities: newAcl };
|
||||
}
|
||||
return a;
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: "20px", fontFamily: "sans-serif" }}>
|
||||
<h1>Omnia Scenario Builder</h1>
|
||||
<hr />
|
||||
|
||||
{/* Persistence Controls */}
|
||||
<section style={{ marginBottom: "20px" }}>
|
||||
<h2>World Persistence</h2>
|
||||
<div style={{ display: "flex", gap: "10px", alignItems: "center" }}>
|
||||
<button onClick={handleCreateNewWorld}>Create New World</button>
|
||||
<span>or Load Existing:</span>
|
||||
<select
|
||||
value={selectedWorldId}
|
||||
onChange={(e) => handleLoadWorld(e.target.value)}
|
||||
>
|
||||
<option value="">-- Select World --</option>
|
||||
{worldsList.map((w) => (
|
||||
<option key={w.id} value={w.id}>
|
||||
{w.name} ({w.id})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{worldData && (
|
||||
<>
|
||||
<button onClick={handleSaveWorld} style={{ fontWeight: "bold" }}>
|
||||
Save World to DB
|
||||
</button>
|
||||
<button onClick={() => handleLoadWorld(worldData.id)}>
|
||||
Reload / Discard Changes
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Status Messages */}
|
||||
{status && <div style={{ color: "green", margin: "10px 0" }}><strong>Status:</strong> {status}</div>}
|
||||
{error && <div style={{ color: "red", margin: "10px 0" }}><strong>Error:</strong> {error}</div>}
|
||||
|
||||
{worldData ? (
|
||||
<div>
|
||||
<hr />
|
||||
{/* World Information */}
|
||||
<section style={{ marginBottom: "30px" }}>
|
||||
<h2>World Attributes (ID: {worldData.id})</h2>
|
||||
|
||||
<table border={1} cellPadding={5} style={{ borderCollapse: "collapse", width: "100%", marginBottom: "10px" }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Attribute Name</th>
|
||||
<th>Value</th>
|
||||
<th>Visibility</th>
|
||||
<th>ACL (Allowed Entities for PRIVATE)</th>
|
||||
<th>Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{worldData.attributes.map((attr) => (
|
||||
<tr key={attr.name}>
|
||||
<td><strong>{attr.name}</strong></td>
|
||||
<td>
|
||||
<input
|
||||
type="text"
|
||||
value={attr.value}
|
||||
onChange={(e) => updateWorldAttributeValue(attr.name, e.target.value)}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<select
|
||||
value={attr.visibility}
|
||||
onChange={(e) => updateWorldAttributeVisibility(attr.name, e.target.value as "PUBLIC" | "PRIVATE")}
|
||||
>
|
||||
<option value="PUBLIC">PUBLIC</option>
|
||||
<option value="PRIVATE">PRIVATE</option>
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
{attr.visibility === "PRIVATE" ? (
|
||||
<div>
|
||||
{worldData.entities.length === 0 ? (
|
||||
<span style={{ color: "gray" }}>No entities in world to grant access to</span>
|
||||
) : (
|
||||
worldData.entities.map((e) => {
|
||||
const entName = e.attributes.find(a => a.name === "name")?.value || e.id;
|
||||
return (
|
||||
<label key={e.id} style={{ display: "block" }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={attr.allowedEntities.includes(e.id)}
|
||||
onChange={(evt) => toggleWorldAcl(attr.name, e.id, evt.target.checked)}
|
||||
/>{" "}
|
||||
{entName} ({e.id.slice(0, 8)}...)
|
||||
</label>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<span style={{ color: "gray" }}>N/A (Visible to all)</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<button onClick={() => removeWorldAttribute(attr.name)}>Delete</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{/* Add World Attribute */}
|
||||
<div style={{ background: "#f5f5f5", padding: "10px", border: "1px solid #ccc" }}>
|
||||
<h4>Add World Attribute</h4>
|
||||
Name:{" "}
|
||||
<input
|
||||
type="text"
|
||||
value={newWorldAttribute.name}
|
||||
onChange={(e) => setNewWorldAttribute({ ...newWorldAttribute, name: e.target.value })}
|
||||
placeholder="e.g. description"
|
||||
/>{" "}
|
||||
Value:{" "}
|
||||
<input
|
||||
type="text"
|
||||
value={newWorldAttribute.value}
|
||||
onChange={(e) => setNewWorldAttribute({ ...newWorldAttribute, value: e.target.value })}
|
||||
placeholder="e.g. A lush land"
|
||||
/>{" "}
|
||||
Visibility:{" "}
|
||||
<select
|
||||
value={newWorldAttribute.visibility}
|
||||
onChange={(e) => setNewWorldAttribute({ ...newWorldAttribute, visibility: e.target.value as "PUBLIC" | "PRIVATE" })}
|
||||
>
|
||||
<option value="PUBLIC">PUBLIC</option>
|
||||
<option value="PRIVATE">PRIVATE</option>
|
||||
</select>{" "}
|
||||
<button onClick={addWorldAttribute}>Add Attribute</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<hr />
|
||||
|
||||
{/* Entities section */}
|
||||
<section style={{ marginBottom: "30px" }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
||||
<h2>World Entities</h2>
|
||||
<button onClick={handleAddEntity}>+ Add New Entity</button>
|
||||
</div>
|
||||
|
||||
{worldData.entities.length === 0 ? (
|
||||
<p>No entities found in this world. Click "+ Add New Entity" to add one.</p>
|
||||
) : (
|
||||
worldData.entities.map((entity, index) => {
|
||||
const entName = entity.attributes.find(a => a.name === "name")?.value || "Unnamed Entity";
|
||||
const entInputState = newEntityAttribute[entity.id] || { name: "", value: "", visibility: "PRIVATE" };
|
||||
|
||||
return (
|
||||
<div key={entity.id} style={{ border: "1px solid #999", padding: "15px", marginBottom: "20px", background: "#fafafa" }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
||||
<h3>Entity #{index + 1}: {entName} <span style={{ fontSize: "12px", color: "gray", fontWeight: "normal" }}>({entity.id})</span></h3>
|
||||
<button onClick={() => handleRemoveEntity(entity.id)} style={{ color: "red" }}>Delete Entity</button>
|
||||
</div>
|
||||
|
||||
<table border={1} cellPadding={5} style={{ borderCollapse: "collapse", width: "100%", marginBottom: "10px", background: "white" }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Attribute Name</th>
|
||||
<th>Value</th>
|
||||
<th>Visibility</th>
|
||||
<th>ACL (Allowed Entities for PRIVATE)</th>
|
||||
<th>Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entity.attributes.map((attr) => (
|
||||
<tr key={attr.name}>
|
||||
<td><strong>{attr.name}</strong></td>
|
||||
<td>
|
||||
<input
|
||||
type="text"
|
||||
value={attr.value}
|
||||
onChange={(e) => updateEntityAttributeValue(entity.id, attr.name, e.target.value)}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<select
|
||||
value={attr.visibility}
|
||||
onChange={(e) => updateEntityAttributeVisibility(entity.id, attr.name, e.target.value as "PUBLIC" | "PRIVATE")}
|
||||
>
|
||||
<option value="PUBLIC">PUBLIC</option>
|
||||
<option value="PRIVATE">PRIVATE</option>
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
{attr.visibility === "PRIVATE" ? (
|
||||
<div>
|
||||
{worldData.entities.filter(e => e.id !== entity.id).length === 0 ? (
|
||||
<span style={{ color: "gray" }}>No other entities in world to grant access to</span>
|
||||
) : (
|
||||
worldData.entities
|
||||
.filter(e => e.id !== entity.id)
|
||||
.map((e) => {
|
||||
const otherName = e.attributes.find(a => a.name === "name")?.value || e.id;
|
||||
return (
|
||||
<label key={e.id} style={{ display: "block" }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={attr.allowedEntities.includes(e.id)}
|
||||
onChange={(evt) => toggleEntityAcl(entity.id, attr.name, e.id, evt.target.checked)}
|
||||
/>{" "}
|
||||
{otherName} ({e.id.slice(0, 8)}...)
|
||||
</label>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<span style={{ color: "gray" }}>N/A (Visible to all)</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<button onClick={() => removeEntityAttribute(entity.id, attr.name)}>Delete</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{/* Add Entity Attribute */}
|
||||
<div style={{ background: "#eee", padding: "10px", border: "1px dashed #777" }}>
|
||||
<h5>Add Attribute to {entName}</h5>
|
||||
Name:{" "}
|
||||
<input
|
||||
type="text"
|
||||
value={entInputState.name}
|
||||
onChange={(e) => setNewEntityAttribute({
|
||||
...newEntityAttribute,
|
||||
[entity.id]: { ...entInputState, name: e.target.value }
|
||||
})}
|
||||
placeholder="e.g. title"
|
||||
/>{" "}
|
||||
Value:{" "}
|
||||
<input
|
||||
type="text"
|
||||
value={entInputState.value}
|
||||
onChange={(e) => setNewEntityAttribute({
|
||||
...newEntityAttribute,
|
||||
[entity.id]: { ...entInputState, value: e.target.value }
|
||||
})}
|
||||
placeholder="e.g. Witcher"
|
||||
/>{" "}
|
||||
Visibility:{" "}
|
||||
<select
|
||||
value={entInputState.visibility}
|
||||
onChange={(e) => setNewEntityAttribute({
|
||||
...newEntityAttribute,
|
||||
[entity.id]: { ...entInputState, visibility: e.target.value as "PUBLIC" | "PRIVATE" }
|
||||
})}
|
||||
>
|
||||
<option value="PUBLIC">PUBLIC</option>
|
||||
<option value="PRIVATE">PRIVATE</option>
|
||||
</select>{" "}
|
||||
<button onClick={() => addEntityAttribute(entity.id)}>Add Attribute</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ padding: "40px 0", textAlign: "center", color: "gray" }}>
|
||||
Please select a world to load or click "Create New World" to begin.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export function proxy(request: NextRequest) {
|
||||
const origin = request.headers.get("origin") || "*";
|
||||
|
||||
// Handle preflight OPTIONS requests
|
||||
if (request.method === "OPTIONS") {
|
||||
return new NextResponse(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin": origin,
|
||||
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
"Access-Control-Max-Age": "86400",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Handle standard requests
|
||||
const response = NextResponse.next();
|
||||
response.headers.set("Access-Control-Allow-Origin", origin);
|
||||
response.headers.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
|
||||
response.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: "/api/:path*",
|
||||
};
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"name": "@omnia/scenario-core",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./dist/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@omnia/core": "workspace:*",
|
||||
"@omnia/spatial": "workspace:*",
|
||||
"@omnia/memory": "workspace:*",
|
||||
"zod": "^4.4.3"
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
export * from "./schema.js";
|
||||
export * from "./loader.js";
|
||||
@@ -1,127 +0,0 @@
|
||||
import { WorldState, Entity, SQLiteRepository, AttributeVisibility } from "@omnia/core";
|
||||
import { Location } from "@omnia/spatial";
|
||||
import { BufferRepository } from "@omnia/memory";
|
||||
import { ScenarioSchema, Scenario } from "./schema.js";
|
||||
|
||||
export class ScenarioLoader {
|
||||
constructor(
|
||||
private coreRepo: SQLiteRepository,
|
||||
private bufferRepo: BufferRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Instantiates a live world from a static JSON scenario template.
|
||||
* Creates a new world instance in the database using a generated unique World ID.
|
||||
*
|
||||
* @param scenarioJson The raw JSON scenario template contents.
|
||||
* @param targetWorldId The unique ID for the running instance to create (e.g. UUID).
|
||||
* Allows launching multiple active runs from one scenario.
|
||||
*/
|
||||
async initializeWorld(scenarioJson: unknown, targetWorldId: string): Promise<string> {
|
||||
// 1. Validate scenario template schema
|
||||
const scenario: Scenario = ScenarioSchema.parse(scenarioJson);
|
||||
|
||||
// 2. Instantiate running WorldState using the target instance ID
|
||||
const world = new WorldState(targetWorldId, new Date(scenario.startTime));
|
||||
|
||||
// Seed world-level attributes as system-only (private, empty ACL)
|
||||
world.addAttribute("name", scenario.name, AttributeVisibility.PRIVATE, new Set());
|
||||
world.addAttribute("description", scenario.description, AttributeVisibility.PRIVATE, new Set());
|
||||
|
||||
if (scenario.world?.attributes) {
|
||||
for (const attr of scenario.world.attributes) {
|
||||
const vis = attr.visibility === "PUBLIC" ? AttributeVisibility.PUBLIC : AttributeVisibility.PRIVATE;
|
||||
world.addAttribute(
|
||||
attr.name,
|
||||
attr.value,
|
||||
vis,
|
||||
attr.allowedEntities ? new Set(attr.allowedEntities) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Save World State core row
|
||||
this.coreRepo.saveWorldState(world);
|
||||
|
||||
// 4. Instantiate and Persist Locations
|
||||
if (scenario.locations) {
|
||||
for (const locData of scenario.locations) {
|
||||
const location = new Location(locData.id, locData.parentId ?? null);
|
||||
|
||||
if (locData.attributes) {
|
||||
for (const attr of locData.attributes) {
|
||||
const vis = attr.visibility === "PUBLIC" ? AttributeVisibility.PUBLIC : AttributeVisibility.PRIVATE;
|
||||
location.addAttribute(
|
||||
attr.name,
|
||||
attr.value,
|
||||
vis,
|
||||
attr.allowedEntities ? new Set(attr.allowedEntities) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (locData.connections) {
|
||||
location.connections = locData.connections.map((c) => ({
|
||||
targetId: c.targetId,
|
||||
portalName: c.portalName,
|
||||
portalStateDescriptor: c.portalStateDescriptor,
|
||||
visionProp: c.visionProp,
|
||||
soundProp: c.soundProp,
|
||||
bidirectional: c.bidirectional,
|
||||
}));
|
||||
}
|
||||
|
||||
// Save location record linked to the world instance
|
||||
world.addLocation(location);
|
||||
this.coreRepo.saveLocation(location, world.id);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Instantiate and Persist Entities (with Aliases & Memory Buffers)
|
||||
if (scenario.entities) {
|
||||
for (const entData of scenario.entities) {
|
||||
const entity = new Entity(entData.id, entData.locationId ?? null);
|
||||
|
||||
// Load attributes
|
||||
if (entData.attributes) {
|
||||
for (const attr of entData.attributes) {
|
||||
const vis = attr.visibility === "PUBLIC" ? AttributeVisibility.PUBLIC : AttributeVisibility.PRIVATE;
|
||||
entity.addAttribute(
|
||||
attr.name,
|
||||
attr.value,
|
||||
vis,
|
||||
attr.allowedEntities ? new Set(attr.allowedEntities) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Load aliases
|
||||
if (entData.aliases) {
|
||||
for (const [targetId, alias] of Object.entries(entData.aliases)) {
|
||||
entity.aliases.set(targetId, alias);
|
||||
}
|
||||
}
|
||||
|
||||
// Save entity record linked to the world instance
|
||||
world.addEntity(entity);
|
||||
this.coreRepo.saveEntity(entity, world.id);
|
||||
|
||||
// Seed initial memory buffer history
|
||||
if (entData.initialMemories) {
|
||||
for (const mem of entData.initialMemories) {
|
||||
this.bufferRepo.save({
|
||||
id: mem.id,
|
||||
ownerId: entData.id,
|
||||
timestamp: mem.timestamp,
|
||||
locationId: mem.locationId,
|
||||
intent: mem.intent,
|
||||
outcome: mem.outcome,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return world.id;
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const AttributeVisibilitySchema = z.enum(["PUBLIC", "PRIVATE"]);
|
||||
|
||||
export const ScenarioAttributeSchema = z.object({
|
||||
name: z.string(),
|
||||
value: z.string(),
|
||||
visibility: AttributeVisibilitySchema,
|
||||
allowedEntities: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
export const ScenarioPortalConnectionSchema = z.object({
|
||||
targetId: z.string(),
|
||||
portalName: z.string().optional(),
|
||||
portalStateDescriptor: z.string().optional(),
|
||||
visionProp: z.number().min(0).max(10),
|
||||
soundProp: z.number().min(0).max(10),
|
||||
bidirectional: z.boolean(),
|
||||
});
|
||||
|
||||
export const ScenarioLocationSchema = z.object({
|
||||
id: z.string(),
|
||||
parentId: z.string().nullable().optional(),
|
||||
attributes: z.array(ScenarioAttributeSchema).optional(),
|
||||
connections: z.array(ScenarioPortalConnectionSchema).optional(),
|
||||
});
|
||||
|
||||
export const ScenarioMemoryEntrySchema = z.object({
|
||||
id: z.string(),
|
||||
timestamp: z.string(), // ISO string
|
||||
locationId: z.string().nullable(),
|
||||
intent: z.object({
|
||||
type: z.enum(["dialogue", "action", "monologue"]),
|
||||
originalText: z.string(),
|
||||
description: z.string(),
|
||||
actorId: z.string(),
|
||||
targetIds: z.array(z.string()),
|
||||
}),
|
||||
outcome: z.object({
|
||||
isValid: z.boolean(),
|
||||
reason: z.string(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
export const ScenarioEntitySchema = z.object({
|
||||
id: z.string(),
|
||||
locationId: z.string().nullable().optional(),
|
||||
attributes: z.array(ScenarioAttributeSchema).optional(),
|
||||
aliases: z.record(z.string(), z.string()).optional(), // targetId -> subjective descriptor
|
||||
initialMemories: z.array(ScenarioMemoryEntrySchema).optional(),
|
||||
});
|
||||
|
||||
export const ScenarioSchema = z.object({
|
||||
id: z.string(), // Template identifier
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
startTime: z.string(), // ISO string
|
||||
world: z.object({
|
||||
attributes: z.array(ScenarioAttributeSchema).optional(),
|
||||
}).optional(),
|
||||
locations: z.array(ScenarioLocationSchema).optional(),
|
||||
entities: z.array(ScenarioEntitySchema).optional(),
|
||||
});
|
||||
|
||||
export type Scenario = z.infer<typeof ScenarioSchema>;
|
||||
@@ -1,136 +0,0 @@
|
||||
import { describe, test, expect } from "vitest";
|
||||
import Database from "better-sqlite3";
|
||||
import { SQLiteRepository } from "@omnia/core";
|
||||
import { Location } from "@omnia/spatial";
|
||||
import { BufferRepository } from "@omnia/memory";
|
||||
import { ScenarioLoader, ScenarioSchema } from "../src/index.js";
|
||||
|
||||
describe("Scenario Validation & Schema Tests (Tier 1)", () => {
|
||||
const validScenario = {
|
||||
id: "sc-haunted-house",
|
||||
name: "Haunted House Mystery",
|
||||
description: "A spooky old manor.",
|
||||
startTime: "2026-07-09T08:00:00.000Z",
|
||||
world: {
|
||||
attributes: [
|
||||
{ name: "weather", value: "stormy", visibility: "PUBLIC" },
|
||||
],
|
||||
},
|
||||
locations: [
|
||||
{
|
||||
id: "lobby",
|
||||
parentId: null,
|
||||
attributes: [
|
||||
{ name: "light", value: "dim", visibility: "PUBLIC" },
|
||||
],
|
||||
connections: [
|
||||
{
|
||||
targetId: "kitchen",
|
||||
portalName: "swinging door",
|
||||
visionProp: 2,
|
||||
soundProp: 6,
|
||||
bidirectional: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "kitchen",
|
||||
parentId: "lobby",
|
||||
},
|
||||
],
|
||||
entities: [
|
||||
{
|
||||
id: "investigator",
|
||||
locationId: "lobby",
|
||||
attributes: [
|
||||
{ name: "sanity", value: "100", visibility: "PRIVATE", allowedEntities: ["investigator"] },
|
||||
],
|
||||
aliases: {
|
||||
ghost: "shadowy specter",
|
||||
},
|
||||
initialMemories: [
|
||||
{
|
||||
id: "mem-seed-1",
|
||||
timestamp: "2026-07-09T07:55:00.000Z",
|
||||
locationId: "lobby",
|
||||
intent: {
|
||||
type: "action",
|
||||
originalText: "I entered the foyer.",
|
||||
description: "entered the house",
|
||||
actorId: "investigator",
|
||||
targetIds: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
test("successfully validates a valid scenario JSON template", () => {
|
||||
const result = ScenarioSchema.safeParse(validScenario);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
test("fails validation on invalid scenario structure", () => {
|
||||
const invalidScenario = {
|
||||
id: "sc-bad",
|
||||
name: "Missing critical fields",
|
||||
// description and startTime are missing
|
||||
};
|
||||
const result = ScenarioSchema.safeParse(invalidScenario);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
test("loads scenario into SQLite database and reconstitutes all objects correctly", async () => {
|
||||
const db = new Database(":memory:");
|
||||
const coreRepo = new SQLiteRepository(db);
|
||||
const bufferRepo = new BufferRepository(db);
|
||||
const loader = new ScenarioLoader(coreRepo, bufferRepo);
|
||||
|
||||
const targetWorldId = "active-world-run-1";
|
||||
const worldId = await loader.initializeWorld(validScenario, targetWorldId);
|
||||
expect(worldId).toBe(targetWorldId);
|
||||
|
||||
// 1. Verify WorldState loaded
|
||||
const world = coreRepo.loadWorldState(targetWorldId);
|
||||
expect(world).not.toBeNull();
|
||||
expect(world!.id).toBe(targetWorldId);
|
||||
expect(world!.clock.get().toISOString()).toBe("2026-07-09T08:00:00.000Z");
|
||||
expect(world!.attributes.get("name")?.getValue()).toBe("Haunted House Mystery");
|
||||
expect(world!.attributes.get("weather")?.getValue()).toBe("stormy");
|
||||
|
||||
// 2. Verify Locations loaded with connections & hierarchy
|
||||
const locations = coreRepo.listLocations(targetWorldId, (id, parentId) => new Location(id, parentId));
|
||||
expect(locations).toHaveLength(2);
|
||||
|
||||
const lobby = locations.find((l) => l.id === "lobby");
|
||||
expect(lobby).toBeDefined();
|
||||
expect(lobby!.parentId).toBeNull();
|
||||
expect(lobby!.attributes.get("light")?.getValue()).toBe("dim");
|
||||
expect(lobby!.connections).toHaveLength(1);
|
||||
expect(lobby!.connections[0].targetId).toBe("kitchen");
|
||||
expect(lobby!.connections[0].portalName).toBe("swinging door");
|
||||
expect(lobby!.connections[0].visionProp).toBe(2);
|
||||
|
||||
const kitchen = locations.find((l) => l.id === "kitchen");
|
||||
expect(kitchen).toBeDefined();
|
||||
expect(kitchen!.parentId).toBe("lobby");
|
||||
|
||||
// 3. Verify Entities loaded with subjective alias map
|
||||
const loadedInvestigator = world!.getEntity("investigator");
|
||||
expect(loadedInvestigator).toBeDefined();
|
||||
expect(loadedInvestigator!.locationId).toBe("lobby");
|
||||
expect(loadedInvestigator!.attributes.get("sanity")?.getValue()).toBe("100");
|
||||
expect(loadedInvestigator!.aliases.get("ghost")).toBe("shadowy specter");
|
||||
|
||||
// 4. Verify pre-seeded memories loaded in BufferRepository
|
||||
const memories = bufferRepo.listForOwner("investigator");
|
||||
expect(memories).toHaveLength(1);
|
||||
expect(memories[0].id).toBe("mem-seed-1");
|
||||
expect(memories[0].timestamp).toBe("2026-07-09T07:55:00.000Z");
|
||||
expect(memories[0].locationId).toBe("lobby");
|
||||
expect(memories[0].intent.description).toBe("entered the house");
|
||||
|
||||
db.close();
|
||||
});
|
||||
});
|
||||
@@ -1,124 +0,0 @@
|
||||
import { describe, test, expect } from "vitest";
|
||||
import Database from "better-sqlite3";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { SQLiteRepository } from "@omnia/core";
|
||||
import { Location } from "@omnia/spatial";
|
||||
import { BufferRepository } from "@omnia/memory";
|
||||
import { ScenarioLoader, ScenarioSchema } from "../src/index.js";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const SCENARIO_PATH = path.resolve(__dirname, "../../demo/scenarios/talking-room.json");
|
||||
|
||||
describe("Talking Room Demo Scenario Test (Tier 1)", () => {
|
||||
test("talking-room.json exists, parses, and loads correctly into database", async () => {
|
||||
// 1. Verify file exists
|
||||
expect(fs.existsSync(SCENARIO_PATH)).toBe(true);
|
||||
|
||||
// 2. Read and parse JSON
|
||||
const rawJson = fs.readFileSync(SCENARIO_PATH, "utf-8");
|
||||
const scenarioJson = JSON.parse(rawJson);
|
||||
const parsed = ScenarioSchema.safeParse(scenarioJson);
|
||||
expect(parsed.success).toBe(true);
|
||||
|
||||
// 3. Setup SQLite and loader
|
||||
const db = new Database(":memory:");
|
||||
const coreRepo = new SQLiteRepository(db);
|
||||
const bufferRepo = new BufferRepository(db);
|
||||
const loader = new ScenarioLoader(coreRepo, bufferRepo);
|
||||
|
||||
const worldInstanceId = "run-talking-room-1";
|
||||
await loader.initializeWorld(scenarioJson, worldInstanceId);
|
||||
|
||||
// 4. Assert WorldState
|
||||
const world = coreRepo.loadWorldState(worldInstanceId);
|
||||
expect(world).not.toBeNull();
|
||||
expect(world!.attributes.get("name")?.getValue()).toBe("Talking Room");
|
||||
expect(world!.attributes.get("name")?.visibility).toBe("PRIVATE");
|
||||
expect(world!.attributes.get("description")?.getValue()).toBe(scenarioJson.description);
|
||||
expect(world!.attributes.get("description")?.visibility).toBe("PRIVATE");
|
||||
expect(world!.attributes.get("experiment_codename")?.getValue()).toBe("Project Tabula Rasa (Phase 3)");
|
||||
expect(world!.attributes.get("experiment_codename")?.visibility).toBe("PRIVATE");
|
||||
expect(world!.attributes.get("experiment_codename")?.getAllowedEntities()).toHaveLength(0); // System only!
|
||||
|
||||
// 5. Assert location
|
||||
const locations = coreRepo.listLocations(worldInstanceId, (id, parentId) => new Location(id, parentId));
|
||||
expect(locations).toHaveLength(1);
|
||||
expect(locations[0].id).toBe("white-room");
|
||||
expect(locations[0].attributes.get("description")?.getValue()).toContain("A pristine, featureless room");
|
||||
|
||||
// 6. Assert entities and their private attributes / allowedEntities
|
||||
const alphaId = "7c9b83b3-8cfb-4e89-8d77-626a5757d591";
|
||||
const betaId = "bf3f29d2-cf11-4b11-9a99-b13c126d400e";
|
||||
|
||||
const alpha = world!.getEntity(alphaId);
|
||||
expect(alpha).toBeDefined();
|
||||
expect(alpha!.locationId).toBe("white-room");
|
||||
|
||||
// Name visibility check
|
||||
const alphaName = alpha!.attributes.get("name")!;
|
||||
expect(alphaName.getValue()).toBe("Bob");
|
||||
expect(alphaName.visibility).toBe("PRIVATE");
|
||||
expect(alphaName.hasAccess(alphaId)).toBe(true);
|
||||
expect(alphaName.hasAccess(betaId)).toBe(false);
|
||||
|
||||
// Check system-only attribute (neural_erasure_dose)
|
||||
const alphaDose = alpha!.attributes.get("neural_erasure_dose")!;
|
||||
expect(alphaDose.visibility).toBe("PRIVATE");
|
||||
expect(alphaDose.hasAccess(alphaId)).toBe(false);
|
||||
expect(alphaDose.hasAccess(betaId)).toBe(false);
|
||||
|
||||
// Verify subjective aliases are initially undefined
|
||||
expect(alpha!.aliases.get(betaId)).toBeUndefined();
|
||||
|
||||
const beta = world!.getEntity(betaId);
|
||||
expect(beta).toBeDefined();
|
||||
expect(beta!.locationId).toBe("white-room");
|
||||
expect(beta!.aliases.get(alphaId)).toBeUndefined();
|
||||
|
||||
// Verify subjective aliases can be dynamically resolved via AliasDeltaGenerator
|
||||
const { AliasDeltaGenerator } = await import("@omnia/architect");
|
||||
const { MockLLMProvider } = await import("@omnia/llm");
|
||||
const llmProvider = new MockLLMProvider([{ alias: "the person in the Beta jumpsuit" }]);
|
||||
const aliasGenerator = new AliasDeltaGenerator(llmProvider);
|
||||
|
||||
const generatedAlias = await aliasGenerator.generate(alpha!, beta!);
|
||||
expect(generatedAlias).toBe("the person in the Beta jumpsuit");
|
||||
alpha!.aliases.set(betaId, generatedAlias);
|
||||
expect(alpha!.aliases.get(betaId)).toBe("the person in the Beta jumpsuit");
|
||||
|
||||
// Verify subjective world state serializes the location attributes (epistemic inclusion)
|
||||
const { serializeSubjectiveWorldState } = await import("@omnia/core");
|
||||
const subjectiveState = serializeSubjectiveWorldState(world!, alphaId);
|
||||
expect(subjectiveState).toContain("You are at location: white-room");
|
||||
expect(subjectiveState).toContain("Location attributes:");
|
||||
expect(subjectiveState).toContain("description: A pristine, featureless room");
|
||||
expect(subjectiveState).toContain("lighting: Bright, uniform illumination");
|
||||
|
||||
// Verify objective world state serializes locations (physics awareness)
|
||||
const { serializeObjectiveWorldState } = await import("@omnia/core");
|
||||
const objectiveState = serializeObjectiveWorldState(world!);
|
||||
expect(objectiveState).toContain("Locations:");
|
||||
expect(objectiveState).toContain("- Location [ID: white-room]:");
|
||||
expect(objectiveState).toContain("description: A pristine, featureless room");
|
||||
|
||||
// 7. Assert initial pre-seeded memories
|
||||
const alphaMemories = bufferRepo.listForOwner(alphaId);
|
||||
expect(alphaMemories).toHaveLength(1);
|
||||
expect(alphaMemories[0].id).toBe("alpha-wake");
|
||||
expect(alphaMemories[0].intent.type).toBe("monologue");
|
||||
expect(alphaMemories[0].intent.originalText).toContain("jail");
|
||||
expect(alphaMemories[0].intent.description).toBe("");
|
||||
|
||||
const betaMemories = bufferRepo.listForOwner(betaId);
|
||||
expect(betaMemories).toHaveLength(1);
|
||||
expect(betaMemories[0].id).toBe("beta-wake");
|
||||
expect(betaMemories[0].intent.type).toBe("action");
|
||||
expect(betaMemories[0].intent.originalText).toContain("agreement");
|
||||
expect(betaMemories[0].intent.description).toBe("");
|
||||
|
||||
db.close();
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [
|
||||
{ "path": "../../packages/core" },
|
||||
{ "path": "../../packages/spatial" },
|
||||
{ "path": "../../packages/memory" }
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user