@vibechain/os 0.0.0-stage → 0.1.1
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/AGENTS.md +217 -0
- package/LICENSE +21 -0
- package/README.md +65 -2
- package/SECURITY.md +35 -0
- package/dist/app-client.d.ts +4 -0
- package/dist/app-client.js +47 -0
- package/dist/app-host.d.ts +28 -0
- package/dist/app-host.js +196 -0
- package/dist/app-protocol.d.ts +62 -0
- package/dist/app-protocol.js +111 -0
- package/dist/app-runtime.d.ts +2 -0
- package/dist/app-runtime.js +11 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +3 -0
- package/dist/bundle.d.ts +10 -0
- package/dist/bundle.js +82 -0
- package/dist/channel.d.ts +1 -0
- package/dist/channel.js +1 -0
- package/dist/cli.d.ts +21 -0
- package/dist/cli.js +90 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.js +34 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +4 -0
- package/dist/inventory.d.ts +12 -0
- package/dist/inventory.js +54 -0
- package/dist/manifest.d.ts +24 -0
- package/dist/manifest.js +32 -0
- package/dist/preview-parent.d.ts +1 -0
- package/dist/preview-parent.js +51 -0
- package/dist/preview-ui.js +1 -0
- package/dist/preview.d.ts +7 -0
- package/dist/preview.js +77 -0
- package/dist/scaffold.d.ts +4 -0
- package/dist/scaffold.js +64 -0
- package/dist/transport.d.ts +17 -0
- package/dist/transport.js +102 -0
- package/dist/types.d.ts +97 -0
- package/dist/types.js +1 -0
- package/examples/chonk-stack/card-slice.ts +17 -0
- package/examples/chonk-stack/cat3d.ts +57 -0
- package/examples/chonk-stack/game.css +174 -0
- package/examples/chonk-stack/index.html +32 -0
- package/examples/chonk-stack/main.ts +149 -0
- package/examples/chonk-stack/model.ts +40 -0
- package/examples/chonk-stack/renderer.ts +263 -0
- package/examples/chonk-stack/skins.ts +47 -0
- package/examples/chonk-stack/vibemarket.json +21 -0
- package/examples/collection-room/index.html +3 -0
- package/examples/collection-room/main.ts +31 -0
- package/examples/collection-room/vibemarket.json +12 -0
- package/examples/tsconfig.json +4 -0
- package/examples/vibexp-app/README.md +9 -0
- package/examples/vibexp-app/index.html +4 -0
- package/examples/vibexp-app/src/main.ts +22 -0
- package/examples/vibexp-app/vibemarket.json +1 -0
- package/package.json +54 -4
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { createAppController, mountAppFrame } from "./app-host.js";
|
|
2
|
+
import { APP_FRAGMENT, createAppNonce } from "./app-protocol.js";
|
|
3
|
+
import { appRuntimeRefusal } from "./app-runtime.js";
|
|
4
|
+
export async function startPreviewParent() {
|
|
5
|
+
const refusal = appRuntimeRefusal(window);
|
|
6
|
+
if (refusal)
|
|
7
|
+
throw Error(refusal);
|
|
8
|
+
const surface = document.getElementById("surface"), status = document.getElementById("status"), toggle = document.getElementById("toggle"), reset = document.getElementById("reset");
|
|
9
|
+
if (!surface || !status || !(toggle instanceof HTMLButtonElement) || !(reset instanceof HTMLButtonElement))
|
|
10
|
+
throw Error("Preview controls are missing.");
|
|
11
|
+
const input = await (await fetch("/preview.json", { credentials: "omit" })).json();
|
|
12
|
+
if (!input || typeof input !== "object" || !("runtime" in input) || typeof input.runtime !== "string")
|
|
13
|
+
throw Error("Invalid preview metadata.");
|
|
14
|
+
const runtime = new URL(input.runtime);
|
|
15
|
+
if (runtime.origin !== `http://localhost:${window.location.port}` || !/^\/game-assets\/[a-f0-9]{64}\//.test(runtime.pathname) || runtime.search || runtime.hash)
|
|
16
|
+
throw Error("Invalid preview runtime.");
|
|
17
|
+
let controller = createAppController(), frame = null;
|
|
18
|
+
let mounted = null, observer = null, minimized = false;
|
|
19
|
+
const detach = () => { mounted?.dispose(); mounted = null; controller.suspend(); observer?.disconnect(); observer = null; frame?.remove(); frame = null; };
|
|
20
|
+
const draw = () => {
|
|
21
|
+
detach();
|
|
22
|
+
if (minimized || document.hidden) {
|
|
23
|
+
status.textContent = "App suspended. Its host-accepted checkpoint stays in this window.";
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const challenge = createAppNonce(), source = new URL(runtime);
|
|
27
|
+
source.hash = `${APP_FRAGMENT}=${challenge}`;
|
|
28
|
+
frame = document.createElement("iframe");
|
|
29
|
+
frame.title = "VibeMarket OS app";
|
|
30
|
+
frame.sandbox.add("allow-scripts");
|
|
31
|
+
frame.referrerPolicy = "no-referrer";
|
|
32
|
+
frame.src = source.href;
|
|
33
|
+
surface.appendChild(frame);
|
|
34
|
+
mounted = mountAppFrame(frame, { controller, challenge, current: () => !minimized && !document.hidden,
|
|
35
|
+
ready: () => { status.textContent = "App ready · Minimize and restore to check its saved work."; },
|
|
36
|
+
fault: message => { detach(); controller.dispose(); controller = createAppController(); status.textContent = message; },
|
|
37
|
+
});
|
|
38
|
+
observer = new ResizeObserver(() => { if (frame)
|
|
39
|
+
mounted?.resize(frame.clientWidth, frame.clientHeight); });
|
|
40
|
+
observer.observe(frame);
|
|
41
|
+
status.textContent = "Loading the isolated app…";
|
|
42
|
+
};
|
|
43
|
+
toggle.onclick = () => { minimized = !minimized; toggle.textContent = minimized ? "Restore" : "Minimize"; draw(); };
|
|
44
|
+
reset.onclick = () => { detach(); controller.dispose(); controller = createAppController(); minimized = false; toggle.textContent = "Minimize"; draw(); };
|
|
45
|
+
document.addEventListener("visibilitychange", draw);
|
|
46
|
+
window.addEventListener("pagehide", () => { detach(); controller.dispose(); document.removeEventListener("visibilitychange", draw); }, { once: true });
|
|
47
|
+
draw();
|
|
48
|
+
}
|
|
49
|
+
if (typeof window !== "undefined" && typeof document !== "undefined")
|
|
50
|
+
void startPreviewParent().catch(error => { const status = document.getElementById("status"); if (status)
|
|
51
|
+
status.textContent = error instanceof Error ? error.message : "Preview failed."; });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var S="vibemarket.game.v1";function x(e){return e.location.protocol!=="http:"||!["127.0.0.1","localhost"].includes(e.location.hostname)?"Third-party apps are available only in the local browser developer preview.":e.top!==e.self?"Third-party apps require a top-level browser host.":["__VM_STEAM__","__TAURI_INTERNALS__","__TAURI__","vibeNative","ReactNativeWebView"].some(n=>n in e)||/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i.test(e.navigator.userAgent)?"Third-party apps are disabled in native shells until their IPC isolation is verified.":null}var T="vibexp";var l=Object.freeze({checkpointBytes:32768,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34816,responseBytes:34816,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:9e5,requestTimeoutMs:1e4});function C(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function P(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function V(e,n){let t=JSON.stringify(e);if(typeof t!="string"||t.length>n||new TextEncoder().encode(t).length>n)throw Error("App message exceeds limit.");return t}function j(e,n){if(typeof e!="string"||e.length>n||new TextEncoder().encode(e).length>n)throw Error("Invalid app message size or encoding.");return JSON.parse(e)}var M=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),R=(e,n)=>{let t=Object.keys(e);return t.length===n.length&&Reflect.ownKeys(e).length===t.length&&t.every(s=>n.includes(s)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,s)??{},"value"))};function B(e){let n=0,t=0,s=(i,h)=>{if(++n>l.checkpointNodes||h>l.checkpointDepth)throw Error("App checkpoint is too complex.");if(i===null||typeof i=="boolean")return;if(typeof i=="number"){if(!Number.isFinite(i))throw Error("Checkpoint numbers must be finite.");return}if(typeof i=="string"){if(i.length>l.stringBytes)throw Error("App checkpoint string is too large.");let r=new TextEncoder().encode(i).byteLength;if(r>l.stringBytes||(t+=r)>l.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(i)){if(i.length>l.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(i).length!==i.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let r=0;r<i.length;r++){let p=Object.getOwnPropertyDescriptor(i,r);if(!p||!("value"in p))throw Error("Sparse/accessor checkpoints are unsupported.");s(p.value,h+1)}return}if(!M(i))throw Error("App checkpoint must contain only JSON values.");let a=Object.keys(i);if(Reflect.ownKeys(i).length!==a.length)throw Error("Checkpoint properties must be enumerable strings.");if(a.length>l.objectKeys)throw Error("App checkpoint has too many keys.");for(let r of a){if(["__proto__","constructor","prototype"].includes(r)||r.length>128)throw Error("Invalid app checkpoint key.");if(t+=new TextEncoder().encode(r).byteLength,t>l.checkpointBytes)throw Error("App checkpoint keys are too large.");let p=Object.getOwnPropertyDescriptor(i,r);if(!p||!("value"in p))throw Error("App checkpoint accessors are unsupported.");s(p.value,h+1)}};s(e,0);let u=JSON.stringify(e);if(new TextEncoder().encode(u).byteLength>l.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return u}function $(e){return JSON.parse(B(e))}function z(e,n){if(!M(e)||!R(e,["id","session","request"])||e.session!==n||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!M(e.request))throw Error("Invalid app session request.");let t=e.request;if((t.method==="ui.ready"||t.method==="app.checkpoint.get")&&R(t,["method"]))return{id:e.id,request:{method:t.method}};if(t.method==="app.checkpoint.set"&&R(t,["method","value"]))return{id:e.id,request:{method:t.method,value:$(t.value)}};throw Error("This app has no permission for that method.")}function O(e){if(!M(e)||!R(e,["active","width","height"])||typeof e.active!="boolean"||typeof e.width!="number"||!Number.isInteger(e.width)||e.width<0||e.width>4096||typeof e.height!="number"||!Number.isInteger(e.height)||e.height<0||e.height>4096)throw Error("Invalid app lifecycle.");return Object.freeze({active:e.active,width:e.width,height:e.height})}function L(e=()=>performance.now()){let n="null",t=!1,s,u=e();if(!Number.isFinite(u))throw Error("App clock is invalid.");let i=u,h=u,a=0,r=0,p,d,f=o=>{if(t||p)return;p=o,clearTimeout(m),n="null";let c=d;s?.close(),c?.(o)},m=setTimeout(()=>f("App session expired. Reopen the app."),l.sessionMs),g=()=>{let o;try{o=e()}catch{f("App clock changed. Reopen the app.");return}if(!Number.isFinite(o)||o<i){f("App clock changed. Reopen the app.");return}if(i=o,o-u>=l.sessionMs){f("App session expired. Reopen the app.");return}return o};return{attach(o,c,y){if(t||p||!C(c))throw o.close(),Error(p??"App controller is closed.");if(g()===void 0)throw o.close(),Error(p);s?.close();let w=!1,I=0,F=new Set,N=()=>{w||(w=!0,o.onmessage=null,o.onmessageerror=null,o.close(),s===_&&(s=void 0,d=void 0))},v=b=>{w||(N(),y.fault(b))},k=()=>!w&&!t&&y.current(),_={lifecycle(b){k()&&o.postMessage(V({session:c,event:"app.lifecycle",state:O(b)},l.responseBytes))},close:N};return s=_,d=y.fault,o.onmessage=b=>{if(!k()){N();return}let q=g();if(q===void 0)return;if(q-h>=1e3&&(h=q,a=0),++a>l.requestsPerSecond||++r>l.lifetimeRequests||I>=l.inFlight){v("App request limit exceeded.");return}let A;try{A=z(j(b.data,l.requestBytes),c)}catch{v("Invalid or unpermitted app request.");return}if(F.has(A.id)){v("App request was replayed.");return}F.add(A.id),I++,Promise.resolve().then(()=>{if(!k())return;let E;switch(A.request.method){case"ui.ready":y.ready(),E={completed:!0};break;case"app.checkpoint.get":E={checkpoint:JSON.parse(n)};break;case"app.checkpoint.set":n=B(A.request.value),E={completed:!0};break}let H={session:c,id:A.id,result:E};k()&&o.postMessage(V(H,l.responseBytes))}).catch(()=>{w||v("App request could not complete.")}).finally(()=>{I--})},o.onmessageerror=()=>v("App message could not be decoded."),o.start(),_},suspend(){s?.close()},dispose(){t||(t=!0,clearTimeout(m),s?.close(),n="null")}}}function J(e,n){let t=x(window);if(t)throw Error(t);if(!C(n.challenge)||new URL(e.src).hash!==`#${T}=${n.challenge}`)throw Error("Invalid app frame challenge.");let s=!1,u=!1,i=!1,h=0,a,r=O({active:!0,width:0,height:0}),p=()=>{s||(s=!0,clearTimeout(g),e.removeEventListener("load",f),window.removeEventListener("message",m),a?.close())},d=o=>{s||(p(),n.fault(o))},f=()=>{u?d("App navigation ended this session."):u=!0},m=o=>{if(s||i||!n.current()||o.source!==e.contentWindow)return;if(++h>32){d("App connection limit exceeded.");return}if(!u||o.origin!=="null")return;let c;try{c=j(o.data,256)}catch{d("Invalid app connection message.");return}if(!c||typeof c!="object"||Array.isArray(c)||!("channel"in c)||c.channel!==S||!("type"in c)||c.type!=="connect"||!("challenge"in c)||c.challenge!==n.challenge||Object.keys(c).length!==3)return;i=!0,window.removeEventListener("message",m);let y=new MessageChannel,w=P();try{if(a=n.controller.attach(y.port1,w,{current:n.current,ready(){clearTimeout(g),n.ready()},fault:d}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:S,challenge:n.challenge,session:w},"*",[y.port2]),a.lifecycle(r)}catch{y.port1.close(),y.port2.close(),d("App connection could not complete.")}},g=setTimeout(()=>d("App took too long to become ready."),15e3);return e.addEventListener("load",f),window.addEventListener("message",m),{resize(o,c){r=O({active:!0,width:Math.min(4096,Math.max(0,Math.floor(o))),height:Math.min(4096,Math.max(0,Math.floor(c)))}),a?.lifecycle(r)},dispose:p}}async function D(){let e=x(window);if(e)throw Error(e);let n=document.getElementById("surface"),t=document.getElementById("status"),s=document.getElementById("toggle"),u=document.getElementById("reset");if(!n||!t||!(s instanceof HTMLButtonElement)||!(u instanceof HTMLButtonElement))throw Error("Preview controls are missing.");let i=await(await fetch("/preview.json",{credentials:"omit"})).json();if(!i||typeof i!="object"||!("runtime"in i)||typeof i.runtime!="string")throw Error("Invalid preview metadata.");let h=new URL(i.runtime);if(h.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(h.pathname)||h.search||h.hash)throw Error("Invalid preview runtime.");let a=L(),r=null,p=null,d=null,f=!1,m=()=>{p?.dispose(),p=null,a.suspend(),d?.disconnect(),d=null,r?.remove(),r=null},g=()=>{if(m(),f||document.hidden){t.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}let o=P(),c=new URL(h);c.hash=`${T}=${o}`,r=document.createElement("iframe"),r.title="VibeMarket OS app",r.sandbox.add("allow-scripts"),r.referrerPolicy="no-referrer",r.src=c.href,n.appendChild(r),p=J(r,{controller:a,challenge:o,current:()=>!f&&!document.hidden,ready:()=>{t.textContent="App ready \xB7 Minimize and restore to check its saved work."},fault:y=>{m(),a.dispose(),a=L(),t.textContent=y}}),d=new ResizeObserver(()=>{r&&p?.resize(r.clientWidth,r.clientHeight)}),d.observe(r),t.textContent="Loading the isolated app\u2026"};s.onclick=()=>{f=!f,s.textContent=f?"Restore":"Minimize",g()},u.onclick=()=>{m(),a.dispose(),a=L(),f=!1,s.textContent="Minimize",g()},document.addEventListener("visibilitychange",g),window.addEventListener("pagehide",()=>{m(),a.dispose(),document.removeEventListener("visibilitychange",g)},{once:!0}),g()}typeof window<"u"&&typeof document<"u"&&D().catch(e=>{let n=document.getElementById("status");n&&(n.textContent=e instanceof Error?e.message:"Preview failed.")});export{D as startPreviewParent};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Server } from "node:http";
|
|
2
|
+
/** One immutable in-memory bundle. No file serving by arbitrary URL, proxy, credential or write endpoint. */
|
|
3
|
+
export declare function startAppPreview(directory: string, port?: number): Promise<{
|
|
4
|
+
server: Server;
|
|
5
|
+
origin: string;
|
|
6
|
+
close(): Promise<void>;
|
|
7
|
+
}>;
|
package/dist/preview.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { APP_CATEGORY, APP_FRAGMENT } from "./app-protocol.js";
|
|
4
|
+
import { readBuiltBundle, assetType } from "./bundle.js";
|
|
5
|
+
const CSS = `body{margin:0;background:#387bd8;font:14px Arial;color:#17233a}main{max-width:1000px;margin:40px auto}header{display:flex;align-items:center;justify-content:space-between;background:linear-gradient(#1684ff,#0049d9);color:white;padding:8px;border-radius:8px 8px 0 0}h1{font-size:15px;margin:0}.frame{background:#ece9d8;border:3px solid #0059e9;min-height:520px}iframe{border:0;width:100%;height:540px;display:block}button{padding:6px 12px}#status{padding:10px;background:#ece9d8;margin:0}small{display:block;padding:12px;color:#fff}`;
|
|
6
|
+
const HTML = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>VibeMarket OS App Preview</title><link rel="stylesheet" href="/preview.css"></head><body><main><header><h1>VibeMarket OS · App Preview</h1><div><button id="toggle" type="button">Minimize</button> <button id="reset" type="button">Close / reset</button></div></header><div id="surface" class="frame"></div><p id="status" role="status">Loading the isolated app…</p><small>Local development only · no account, inventory, Cash, Steam or wallet API. Build again and restart this preview to load changed files.</small></main><script type="module" src="/sdk/preview-ui.js"></script></body></html>`;
|
|
7
|
+
const MODULES = new Set(["preview-ui.js"]);
|
|
8
|
+
/** One immutable in-memory bundle. No file serving by arbitrary URL, proxy, credential or write endpoint. */
|
|
9
|
+
export async function startAppPreview(directory, port = 0) {
|
|
10
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535)
|
|
11
|
+
throw Error("Invalid preview port.");
|
|
12
|
+
const bundle = await readBuiltBundle(directory);
|
|
13
|
+
if (bundle.manifest.category !== APP_CATEGORY || bundle.manifest.collectionId !== null || bundle.manifest.permissions.length)
|
|
14
|
+
throw Error("VibeMarket OS apps must declare category:vibexp-app, collectionId:null and permissions:[]. Market games use their existing host.");
|
|
15
|
+
const modules = new Map();
|
|
16
|
+
for (const name of MODULES)
|
|
17
|
+
modules.set(name, await readFile(new URL(`./${name}`, import.meta.url)));
|
|
18
|
+
let actualPort = 0;
|
|
19
|
+
const server = createServer((request, response) => {
|
|
20
|
+
const host = request.headers.host;
|
|
21
|
+
const parentHost = `127.0.0.1:${actualPort}`, runtimeHost = `localhost:${actualPort}`;
|
|
22
|
+
const base = { "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", "Cache-Control": "no-store", "Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=(), bluetooth=(), clipboard-read=(), clipboard-write=(), fullscreen=()" };
|
|
23
|
+
const send = (status, body, headers = {}) => { response.writeHead(status, { ...base, ...headers }); response.end(body); };
|
|
24
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
25
|
+
send(405, "Method not allowed");
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (host !== parentHost && host !== runtimeHost) {
|
|
29
|
+
send(403, "Invalid preview host");
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
const pathname = request.url?.split("?")[0] ?? "";
|
|
33
|
+
if (request.url?.includes("?") || pathname.includes("%")) {
|
|
34
|
+
send(404, "Not found");
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (host === runtimeHost) {
|
|
38
|
+
const prefix = `/game-assets/${bundle.digest}/`, name = pathname.startsWith(prefix) ? pathname.slice(prefix.length) : "";
|
|
39
|
+
const bytes = Object.hasOwn(bundle.files, name) ? bundle.files[name] : undefined;
|
|
40
|
+
if (!bytes || !assetType(name)) {
|
|
41
|
+
send(404, "Not found");
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
const assets = `http://${runtimeHost}${prefix}`;
|
|
45
|
+
send(200, request.method === "HEAD" ? "" : bytes, { "Content-Type": assetType(name), "Access-Control-Allow-Origin": "*", "Content-Security-Policy": `default-src 'none'; sandbox allow-scripts; base-uri 'none'; object-src 'none'; form-action 'none'; frame-src 'none'; frame-ancestors http://${parentHost}; script-src ${assets} 'wasm-unsafe-eval'; style-src ${assets} 'unsafe-inline'; img-src ${assets} data: blob:; font-src ${assets}; media-src ${assets} blob:; connect-src ${assets}; worker-src 'none'`, "Cache-Control": "public,max-age=31536000,immutable" });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const parentCsp = `default-src 'none'; base-uri 'none'; object-src 'none'; form-action 'none'; frame-ancestors 'none'; script-src 'self'; style-src 'self'; img-src data:; connect-src 'self'; frame-src http://${runtimeHost}`;
|
|
49
|
+
if (pathname === "/") {
|
|
50
|
+
send(200, HTML, { "Content-Type": "text/html; charset=utf-8", "Content-Security-Policy": parentCsp });
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (pathname === "/preview.css") {
|
|
54
|
+
send(200, CSS, { "Content-Type": "text/css; charset=utf-8" });
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (pathname === "/preview.json") {
|
|
58
|
+
send(200, JSON.stringify({ name: bundle.manifest.name, runtime: `http://${runtimeHost}/game-assets/${bundle.digest}/${bundle.manifest.entry}`, fragment: APP_FRAGMENT }), { "Content-Type": "application/json" });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const name = pathname.startsWith("/sdk/") ? pathname.slice(5) : "";
|
|
62
|
+
const module = modules.get(name);
|
|
63
|
+
if (module) {
|
|
64
|
+
send(200, module, { "Content-Type": "text/javascript; charset=utf-8" });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
send(404, "Not found");
|
|
68
|
+
});
|
|
69
|
+
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(port, "127.0.0.1", () => { server.off("error", reject); resolve(); }); });
|
|
70
|
+
const address = server.address();
|
|
71
|
+
if (!address || typeof address === "string") {
|
|
72
|
+
await new Promise((resolve, reject) => { server.close(error => error ? reject(error) : resolve()); server.closeAllConnections(); });
|
|
73
|
+
throw Error("Preview did not bind a TCP port.");
|
|
74
|
+
}
|
|
75
|
+
actualPort = address.port;
|
|
76
|
+
return { server, origin: `http://127.0.0.1:${actualPort}`, close: () => new Promise((resolve, reject) => { server.close(error => error ? reject(error) : resolve()); server.closeAllConnections(); }) };
|
|
77
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare const SDK_PACKAGE = "@vibechain/os";
|
|
2
|
+
/** Pin registry apps to the installed CLI version; an explicit local archive remains supported. */
|
|
3
|
+
export declare function createApp(directory: string, sdkTarball?: string): Promise<string>;
|
|
4
|
+
export declare function stageAppAssets(root: string): Promise<void>;
|
package/dist/scaffold.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { copyFile, lstat, mkdir, readdir, realpath, writeFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { parseManifest } from "./manifest.js";
|
|
5
|
+
import { readBoundedAsset } from "./bundle.js";
|
|
6
|
+
export const SDK_PACKAGE = "@vibechain/os";
|
|
7
|
+
/** Pin registry apps to the installed CLI version; an explicit local archive remains supported. */
|
|
8
|
+
export async function createApp(directory, sdkTarball) {
|
|
9
|
+
let dependency;
|
|
10
|
+
if (sdkTarball !== undefined) {
|
|
11
|
+
const tarball = await realpath(sdkTarball);
|
|
12
|
+
if (!(await lstat(tarball)).isFile() || !tarball.endsWith(".tgz"))
|
|
13
|
+
throw Error("Pass the SDK .tgz archive you installed.");
|
|
14
|
+
dependency = `file:${tarball}`;
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
const input = JSON.parse(new TextDecoder().decode(await readBoundedAsset(fileURLToPath(new URL("../package.json", import.meta.url)), 16 * 1024)));
|
|
18
|
+
if (!input || typeof input !== "object" || !("name" in input) || input.name !== SDK_PACKAGE || !("version" in input) || typeof input.version !== "string"
|
|
19
|
+
|| !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?$/.test(input.version))
|
|
20
|
+
throw Error("Installed SDK package metadata is invalid.");
|
|
21
|
+
dependency = input.version;
|
|
22
|
+
}
|
|
23
|
+
const requested = path.resolve(directory);
|
|
24
|
+
await mkdir(requested, { recursive: true });
|
|
25
|
+
if ((await lstat(requested)).isSymbolicLink())
|
|
26
|
+
throw Error("App destination cannot be a symlink.");
|
|
27
|
+
const target = await realpath(requested);
|
|
28
|
+
if ((await readdir(target)).length)
|
|
29
|
+
throw Error("The new app directory must be empty.");
|
|
30
|
+
const template = fileURLToPath(new URL("../examples/vibexp-app/", import.meta.url));
|
|
31
|
+
await mkdir(path.join(target, "src"));
|
|
32
|
+
for (const file of ["index.html", "vibemarket.json", "README.md", "src/main.ts"])
|
|
33
|
+
await copyFile(path.join(template, file), path.join(target, file));
|
|
34
|
+
await writeFile(path.join(target, "tsconfig.json"), JSON.stringify({ compilerOptions: { target: "ES2022", module: "ESNext", moduleResolution: "Bundler", lib: ["ES2022", "DOM"], strict: true, skipLibCheck: true, noEmit: true }, include: ["src/**/*.ts"] }, null, 2) + "\n", { flag: "wx" });
|
|
35
|
+
await writeFile(path.join(target, "package.json"), JSON.stringify({
|
|
36
|
+
name: "my-vibemarket-app", version: "0.1.0", private: true, type: "module",
|
|
37
|
+
scripts: {
|
|
38
|
+
build: "tsc --noEmit && esbuild src/main.ts --bundle --minify --format=esm --target=es2022 --outfile=dist/main.js && os assets",
|
|
39
|
+
dev: "os preview dist", pack: "os pack dist app.zip",
|
|
40
|
+
},
|
|
41
|
+
dependencies: { [SDK_PACKAGE]: dependency },
|
|
42
|
+
devDependencies: { typescript: "5.9.3", esbuild: "0.28.2" },
|
|
43
|
+
}, null, 2) + "\n", { flag: "wx" });
|
|
44
|
+
return target;
|
|
45
|
+
}
|
|
46
|
+
export async function stageAppAssets(root) {
|
|
47
|
+
const directory = await realpath(root), output = path.join(directory, "dist");
|
|
48
|
+
parseManifest(JSON.parse(new TextDecoder().decode(await readBoundedAsset(path.join(directory, "vibemarket.json"), 16 * 1024))));
|
|
49
|
+
await mkdir(output, { recursive: true });
|
|
50
|
+
if (await realpath(output) !== output)
|
|
51
|
+
throw Error("App output cannot be a symlink.");
|
|
52
|
+
for (const name of ["index.html", "vibemarket.json"]) {
|
|
53
|
+
const destination = path.join(output, name);
|
|
54
|
+
try {
|
|
55
|
+
if ((await lstat(destination)).isSymbolicLink())
|
|
56
|
+
throw Error("App output cannot contain symlinked files.");
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
if (!(error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT"))
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
await copyFile(path.join(directory, name), destination);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface RpcTransport<Request, Result> {
|
|
2
|
+
request<T extends Result>(message: Request): Promise<T>;
|
|
3
|
+
destroy(): void;
|
|
4
|
+
}
|
|
5
|
+
export interface PortOptions {
|
|
6
|
+
session?: string;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
maxPending?: number;
|
|
9
|
+
jsonBytes?: number;
|
|
10
|
+
onEvent?: (value: Record<string, unknown>) => void;
|
|
11
|
+
}
|
|
12
|
+
/** Canonical private-port transport used by both the existing Market client and the app facade. */
|
|
13
|
+
export declare function createRpcTransport<Request, Result>(port: MessagePort, options?: PortOptions): RpcTransport<Request, Result>;
|
|
14
|
+
export declare function connectHostPort(signal?: AbortSignal, challenge?: string): Promise<{
|
|
15
|
+
port: MessagePort;
|
|
16
|
+
session?: string;
|
|
17
|
+
}>;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { CHANNEL } from "./channel.js";
|
|
2
|
+
import { appJson, appNonce, parseAppJson } from "./app-protocol.js";
|
|
3
|
+
/** Canonical private-port transport used by both the existing Market client and the app facade. */
|
|
4
|
+
export function createRpcTransport(port, options = {}) {
|
|
5
|
+
let sequence = 0, closed = false;
|
|
6
|
+
const pending = new Map();
|
|
7
|
+
port.onmessage = (event) => {
|
|
8
|
+
let data;
|
|
9
|
+
try {
|
|
10
|
+
data = options.jsonBytes === undefined ? event.data : parseAppJson(event.data, options.jsonBytes);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
if (closed || !data || typeof data !== "object" || Array.isArray(data))
|
|
16
|
+
return;
|
|
17
|
+
const value = data;
|
|
18
|
+
if (options.session !== undefined && value.session !== options.session)
|
|
19
|
+
return;
|
|
20
|
+
if ("event" in value) {
|
|
21
|
+
options.onEvent?.(value);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
if (typeof value.id !== "string")
|
|
25
|
+
return;
|
|
26
|
+
const call = pending.get(value.id);
|
|
27
|
+
if (!call)
|
|
28
|
+
return;
|
|
29
|
+
pending.delete(value.id);
|
|
30
|
+
window.clearTimeout(call.timer);
|
|
31
|
+
if (typeof value.error === "string")
|
|
32
|
+
call.reject(Error(options.jsonBytes === undefined ? value.error : value.error.slice(0, 500)));
|
|
33
|
+
else if ("result" in value)
|
|
34
|
+
call.resolve(value.result);
|
|
35
|
+
else
|
|
36
|
+
call.reject(Error("Invalid host response."));
|
|
37
|
+
};
|
|
38
|
+
port.start();
|
|
39
|
+
return {
|
|
40
|
+
request(message) {
|
|
41
|
+
if (closed)
|
|
42
|
+
return Promise.reject(Error("Game session ended."));
|
|
43
|
+
if (pending.size >= (options.maxPending ?? 16))
|
|
44
|
+
return Promise.reject(Error("Too many pending requests."));
|
|
45
|
+
const id = String(++sequence);
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
const timer = window.setTimeout(() => { pending.delete(id); reject(Error(options.jsonBytes === undefined ? "Request timed out. Check your VibeMarket inventory before trying again; a submitted transaction may still complete." : "App request timed out. Restore the window and read its last accepted checkpoint before retrying.")); }, options.timeoutMs ?? 180_000);
|
|
48
|
+
pending.set(id, { resolve: value => resolve(value), reject, timer });
|
|
49
|
+
try {
|
|
50
|
+
const envelope = { id, request: message, ...(options.session === undefined ? {} : { session: options.session }) };
|
|
51
|
+
port.postMessage(options.jsonBytes === undefined ? envelope : appJson(envelope, options.jsonBytes));
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
pending.delete(id);
|
|
55
|
+
window.clearTimeout(timer);
|
|
56
|
+
reject(error);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
destroy() {
|
|
61
|
+
if (closed)
|
|
62
|
+
return;
|
|
63
|
+
closed = true;
|
|
64
|
+
pending.forEach(call => { window.clearTimeout(call.timer); call.reject(Error("Game session ended.")); });
|
|
65
|
+
pending.clear();
|
|
66
|
+
port.onmessage = null;
|
|
67
|
+
port.close();
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
export function connectHostPort(signal, challenge) {
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
let retry;
|
|
74
|
+
const cleanup = () => { window.clearTimeout(timeout); if (retry !== undefined)
|
|
75
|
+
window.clearInterval(retry); window.removeEventListener("message", connect); signal?.removeEventListener("abort", abort); };
|
|
76
|
+
const abort = () => { cleanup(); reject(Error("Game session ended.")); };
|
|
77
|
+
const connect = (event) => {
|
|
78
|
+
if (event.source !== window.parent || !event.data || typeof event.data !== "object"
|
|
79
|
+
|| !("channel" in event.data) || event.data.channel !== CHANNEL || event.ports.length !== 1)
|
|
80
|
+
return;
|
|
81
|
+
let session;
|
|
82
|
+
if (challenge !== undefined) {
|
|
83
|
+
if (!("challenge" in event.data) || event.data.challenge !== challenge || !("session" in event.data) || !appNonce(event.data.session))
|
|
84
|
+
return;
|
|
85
|
+
session = event.data.session;
|
|
86
|
+
}
|
|
87
|
+
cleanup();
|
|
88
|
+
resolve({ port: event.ports[0], ...(session === undefined ? {} : { session }) });
|
|
89
|
+
};
|
|
90
|
+
const timeout = window.setTimeout(() => { cleanup(); reject(Error("VibeMarket did not connect. Reopen the game.")); }, 15_000);
|
|
91
|
+
window.addEventListener("message", connect);
|
|
92
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
93
|
+
if (signal?.aborted) {
|
|
94
|
+
abort();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const hello = () => { const message = { channel: CHANNEL, type: "connect", ...(challenge === undefined ? {} : { challenge }) }; window.parent.postMessage(challenge === undefined ? message : appJson(message, 256), "*"); };
|
|
98
|
+
hello();
|
|
99
|
+
if (challenge !== undefined)
|
|
100
|
+
retry = window.setInterval(hello, 250);
|
|
101
|
+
});
|
|
102
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** Serializable game-facing DTOs. Never add wallet/session/driver objects here. */
|
|
2
|
+
export type GameProfile = {
|
|
3
|
+
playerId: string;
|
|
4
|
+
name: string;
|
|
5
|
+
avatar: string;
|
|
6
|
+
} | null;
|
|
7
|
+
export type GamePack = {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
image: string;
|
|
11
|
+
color: string;
|
|
12
|
+
};
|
|
13
|
+
export type GameCard = {
|
|
14
|
+
id: string;
|
|
15
|
+
packId: string;
|
|
16
|
+
name: string;
|
|
17
|
+
image: string;
|
|
18
|
+
rarity: number;
|
|
19
|
+
foil: number;
|
|
20
|
+
state: "sealed" | "revealed" | "collected";
|
|
21
|
+
sellable: boolean;
|
|
22
|
+
};
|
|
23
|
+
export type GameInventory = {
|
|
24
|
+
packs: {
|
|
25
|
+
packId: string;
|
|
26
|
+
quantity: number;
|
|
27
|
+
}[];
|
|
28
|
+
cards: GameCard[];
|
|
29
|
+
nextCursor: number | null;
|
|
30
|
+
};
|
|
31
|
+
export type GameAction = {
|
|
32
|
+
method: "packs.buy" | "packs.sell" | "packs.open";
|
|
33
|
+
packId: string;
|
|
34
|
+
quantity: number;
|
|
35
|
+
} | {
|
|
36
|
+
method: "cards.reveal" | "cards.sell" | "cards.collect";
|
|
37
|
+
cardId: string;
|
|
38
|
+
};
|
|
39
|
+
export type GameRequest = GameAction | {
|
|
40
|
+
method: "profile.get" | "catalog.list" | "ui.ready" | "ui.shop";
|
|
41
|
+
} | {
|
|
42
|
+
method: "inventory.get";
|
|
43
|
+
cursor?: number;
|
|
44
|
+
};
|
|
45
|
+
export type GameResult = GameProfile | GamePack[] | GameInventory | {
|
|
46
|
+
completed: true;
|
|
47
|
+
};
|
|
48
|
+
export type GameReview = {
|
|
49
|
+
title: string;
|
|
50
|
+
item: string;
|
|
51
|
+
quantity: number;
|
|
52
|
+
quoteUsd?: number;
|
|
53
|
+
confirmLabel?: string;
|
|
54
|
+
consequence: string;
|
|
55
|
+
action: GameAction;
|
|
56
|
+
};
|
|
57
|
+
export interface GameSdk {
|
|
58
|
+
profile: {
|
|
59
|
+
get(): Promise<GameProfile>;
|
|
60
|
+
};
|
|
61
|
+
catalog: {
|
|
62
|
+
list(): Promise<GamePack[]>;
|
|
63
|
+
};
|
|
64
|
+
inventory: {
|
|
65
|
+
get(cursor?: number): Promise<GameInventory>;
|
|
66
|
+
onChanged(listener: () => void): () => void;
|
|
67
|
+
};
|
|
68
|
+
packs: {
|
|
69
|
+
buy(packId: string, quantity?: number): Promise<{
|
|
70
|
+
completed: true;
|
|
71
|
+
}>;
|
|
72
|
+
sell(packId: string, quantity?: number): Promise<{
|
|
73
|
+
completed: true;
|
|
74
|
+
}>;
|
|
75
|
+
open(packId: string, quantity?: number): Promise<{
|
|
76
|
+
completed: true;
|
|
77
|
+
}>;
|
|
78
|
+
};
|
|
79
|
+
cards: {
|
|
80
|
+
reveal(cardId: string): Promise<{
|
|
81
|
+
completed: true;
|
|
82
|
+
}>;
|
|
83
|
+
sell(cardId: string): Promise<{
|
|
84
|
+
completed: true;
|
|
85
|
+
}>;
|
|
86
|
+
collect(cardId: string): Promise<{
|
|
87
|
+
completed: true;
|
|
88
|
+
}>;
|
|
89
|
+
};
|
|
90
|
+
ready(): Promise<{
|
|
91
|
+
completed: true;
|
|
92
|
+
}>;
|
|
93
|
+
showShop(): Promise<{
|
|
94
|
+
completed: true;
|
|
95
|
+
}>;
|
|
96
|
+
destroy(): void;
|
|
97
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { START_WIDTH, type CardLayer } from './model';
|
|
2
|
+
|
|
3
|
+
export interface CardSlice { left: number; right: number }
|
|
4
|
+
/** UV width follows physical width, so the card's print never gets squeezed. */
|
|
5
|
+
export function centeredCardSlice(width: number): CardSlice {
|
|
6
|
+
if (!Number.isFinite(width) || width <= 0 || width > START_WIDTH) throw new Error('Invalid card slice width');
|
|
7
|
+
const span = width / START_WIDTH;
|
|
8
|
+
return { left: (1 - span) / 2, right: (1 + span) / 2 };
|
|
9
|
+
}
|
|
10
|
+
/** A landed piece and its falling offcut retain complementary parts of the incoming print. */
|
|
11
|
+
export function cutCardSlice(card: Pick<CardLayer, 'x' | 'width'>, piece: Pick<CardLayer, 'x' | 'width'>): CardSlice {
|
|
12
|
+
const source = centeredCardSlice(card.width);
|
|
13
|
+
if (![card.x, piece.x, piece.width].every(Number.isFinite) || piece.width <= 0
|
|
14
|
+
|| piece.x < card.x - 1e-7 || piece.x + piece.width > card.x + card.width + 1e-7) throw new Error('Piece is outside the card');
|
|
15
|
+
const left = source.left + (piece.x - card.x) / START_WIDTH;
|
|
16
|
+
return { left: Math.max(0, left), right: Math.min(1, left + piece.width / START_WIDTH) };
|
|
17
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import * as THREE from "three";
|
|
2
|
+
import { SKINS } from "./skins";
|
|
3
|
+
|
|
4
|
+
/** Procedural author-owned character: no host renderer or remote model. */
|
|
5
|
+
export function createChonk() {
|
|
6
|
+
const root = new THREE.Group();
|
|
7
|
+
const fur = new THREE.MeshPhysicalMaterial({ color: SKINS[0].fur, roughness: 0.4, clearcoat: 0.45 });
|
|
8
|
+
const belly = new THREE.MeshStandardMaterial({ color: SKINS[0].belly, roughness: 0.55 });
|
|
9
|
+
const pink = new THREE.MeshStandardMaterial({ color: "#ff94bd", roughness: 0.4 });
|
|
10
|
+
const black = new THREE.MeshPhysicalMaterial({ color: "#100e29", roughness: 0.25, clearcoat: 0.4, envMapIntensity: 0.2 });
|
|
11
|
+
const white = new THREE.MeshBasicMaterial({ color: "#ffffff" });
|
|
12
|
+
const gold = new THREE.MeshStandardMaterial({ color: "#ffc54f", metalness: 0.8, roughness: 0.19 });
|
|
13
|
+
const stripe = new THREE.MeshStandardMaterial({ color: "#96623d", roughness: 0.55 });
|
|
14
|
+
const ball = new THREE.SphereGeometry(1, 24, 16);
|
|
15
|
+
const mesh = (geometry: THREE.BufferGeometry, material: THREE.Material, position: number[], scale = [1, 1, 1]) => {
|
|
16
|
+
const item = new THREE.Mesh(geometry, material); item.position.set(position[0], position[1], position[2]); item.scale.set(scale[0], scale[1], scale[2]); item.castShadow = true; root.add(item); return item;
|
|
17
|
+
};
|
|
18
|
+
mesh(ball, fur, [0, 0.68, 0], [0.91, 0.67, 0.71]);
|
|
19
|
+
mesh(ball, belly, [0, 0.6, 0.54], [0.61, 0.44, 0.25]);
|
|
20
|
+
mesh(ball, fur, [0, 1.36, 0.08], [1.03, 0.75, 0.76]);
|
|
21
|
+
const ear = new THREE.ConeGeometry(0.39, 0.8, 3);
|
|
22
|
+
for (const side of [-1, 1]) {
|
|
23
|
+
const outer = mesh(ear, fur, [side * 0.67, 1.99, 0.07]); outer.rotation.z = side * -0.24; outer.rotation.y = Math.PI;
|
|
24
|
+
const inner = mesh(ear, pink, [side * 0.67, 2.02, 0.18], [0.58, 0.66, 0.58]); inner.rotation.copy(outer.rotation);
|
|
25
|
+
mesh(ball, fur, [side * 0.56, 0.12, 0.39], [0.35, 0.16, 0.35]);
|
|
26
|
+
mesh(ball, belly, [side * 0.24, 1.11, 0.75], [0.35, 0.23, 0.13]);
|
|
27
|
+
mesh(ball, pink, [side * 0.59, 1.2, 0.65], [0.17, 0.085, 0.05]);
|
|
28
|
+
mesh(ball, black, [side * 0.38, 1.45, 0.745], [0.12, 0.17, 0.075]);
|
|
29
|
+
mesh(ball, white, [side * 0.38 - 0.035, 1.5, 0.81], [0.037, 0.05, 0.015]);
|
|
30
|
+
for (let i = 0; i < 3; i++) {
|
|
31
|
+
const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(side * 0.58, 1.04 + i * 0.09, 0.7), new THREE.Vector3(side * 1.13, 0.98 + i * 0.15, 0.65)]), new THREE.LineBasicMaterial({ color: "#fff7eb" })); root.add(line);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
mesh(ball, pink, [0, 1.18, 0.865], [0.09, 0.065, 0.055]);
|
|
35
|
+
for (const side of [-1, 1]) {
|
|
36
|
+
const smile = new THREE.Mesh(new THREE.TorusGeometry(0.115, 0.013, 5, 12, Math.PI), black); smile.rotation.z = Math.PI; smile.position.set(side * 0.106, 1.052, 0.873); root.add(smile);
|
|
37
|
+
}
|
|
38
|
+
const tailCurve = new THREE.CatmullRomCurve3([new THREE.Vector3(0.5, 0.35, -0.4), new THREE.Vector3(1.1, 0.4, -0.65), new THREE.Vector3(1.35, 0.9, -0.4), new THREE.Vector3(1.1, 1.05, -0.28)]);
|
|
39
|
+
mesh(new THREE.TubeGeometry(tailCurve, 16, 0.17, 8, false), fur, [0, 0, 0]);
|
|
40
|
+
const glasses = new THREE.Group(), shades = new THREE.Group(), jewelry = new THREE.Group(), stripes = new THREE.Group(), bracelets = new THREE.Group();
|
|
41
|
+
root.add(glasses, shades, jewelry, stripes, bracelets);
|
|
42
|
+
for (const side of [-1, 1]) {
|
|
43
|
+
const lens = new THREE.Mesh(new THREE.TorusGeometry(0.24, 0.028, 6, 24), black); lens.position.set(side * 0.37, 1.45, 0.85); glasses.add(lens);
|
|
44
|
+
const shade = new THREE.Mesh(new THREE.BoxGeometry(0.48, 0.29, 0.06), black); shade.position.set(side * 0.37, 1.44, 0.855); shade.rotation.z = side * 0.07; shades.add(shade);
|
|
45
|
+
const bracelet = new THREE.Mesh(new THREE.TorusGeometry(0.23, 0.055, 6, 16), pink); bracelet.rotation.x = Math.PI / 2; bracelet.position.set(side * 0.56, 0.17, 0.39); bracelets.add(bracelet);
|
|
46
|
+
}
|
|
47
|
+
const bridge = new THREE.Mesh(new THREE.BoxGeometry(0.25, 0.03, 0.04), black); bridge.position.set(0, 1.47, 0.86); glasses.add(bridge); shades.add(bridge.clone());
|
|
48
|
+
const chain = new THREE.Mesh(new THREE.TorusGeometry(0.6, 0.055, 7, 28), gold); chain.rotation.x = Math.PI / 2.8; chain.position.set(0, 0.92, 0.25); jewelry.add(chain);
|
|
49
|
+
const charm = new THREE.Mesh(new THREE.OctahedronGeometry(0.14), gold); charm.position.set(0, 0.49, 0.77); jewelry.add(charm);
|
|
50
|
+
for (const x of [-0.23, 0, 0.23]) { const mark = new THREE.Mesh(new THREE.CapsuleGeometry(0.047, 0.18, 3, 6), stripe); mark.position.set(x, 1.89, 0.49); mark.rotation.x = -0.65; stripes.add(mark); }
|
|
51
|
+
return { root, skin(index: number) {
|
|
52
|
+
const look = SKINS[index] ?? SKINS[0]; fur.color.set(look.fur); belly.color.set(look.belly);
|
|
53
|
+
fur.metalness = index === 5 ? 0.45 : 0; fur.roughness = index === 5 ? 0.22 : 0.4;
|
|
54
|
+
glasses.visible = index === 3; shades.visible = index === 4; jewelry.visible = index === 5; stripes.visible = index === 1 || index === 5; bracelets.visible = index === 2;
|
|
55
|
+
stripe.color.set(index === 5 ? "#b68c28" : "#96623d");
|
|
56
|
+
} };
|
|
57
|
+
}
|