@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,62 @@
|
|
|
1
|
+
/** Additive app messages on the existing SDK channel. No account or economy authority. */
|
|
2
|
+
export declare const APP_PROTOCOL: 1;
|
|
3
|
+
export declare const APP_FRAGMENT = "vibexp";
|
|
4
|
+
export declare const APP_CATEGORY = "vibexp-app";
|
|
5
|
+
export declare const APP_LIMITS: Readonly<{
|
|
6
|
+
checkpointBytes: number;
|
|
7
|
+
checkpointDepth: 8;
|
|
8
|
+
checkpointNodes: 2048;
|
|
9
|
+
objectKeys: 64;
|
|
10
|
+
arrayItems: 256;
|
|
11
|
+
stringBytes: 8192;
|
|
12
|
+
requestBytes: number;
|
|
13
|
+
responseBytes: number;
|
|
14
|
+
requestsPerSecond: 10;
|
|
15
|
+
inFlight: 4;
|
|
16
|
+
lifetimeRequests: 5000;
|
|
17
|
+
sessionMs: number;
|
|
18
|
+
requestTimeoutMs: 10000;
|
|
19
|
+
}>;
|
|
20
|
+
export type AppValue = null | boolean | number | string | AppValue[] | {
|
|
21
|
+
[key: string]: AppValue;
|
|
22
|
+
};
|
|
23
|
+
export type AppRequest = {
|
|
24
|
+
method: "ui.ready" | "app.checkpoint.get";
|
|
25
|
+
} | {
|
|
26
|
+
method: "app.checkpoint.set";
|
|
27
|
+
value: AppValue;
|
|
28
|
+
};
|
|
29
|
+
export type AppResult = {
|
|
30
|
+
completed: true;
|
|
31
|
+
} | {
|
|
32
|
+
checkpoint: AppValue;
|
|
33
|
+
};
|
|
34
|
+
export interface AppLifecycle {
|
|
35
|
+
active: boolean;
|
|
36
|
+
width: number;
|
|
37
|
+
height: number;
|
|
38
|
+
}
|
|
39
|
+
export interface VibeMarketAppSdk {
|
|
40
|
+
ready(): Promise<void>;
|
|
41
|
+
checkpoint: {
|
|
42
|
+
read(): Promise<AppValue>;
|
|
43
|
+
write(value: AppValue): Promise<void>;
|
|
44
|
+
};
|
|
45
|
+
lifecycle: {
|
|
46
|
+
current(): Readonly<AppLifecycle>;
|
|
47
|
+
onChanged(listener: (state: Readonly<AppLifecycle>) => void): () => void;
|
|
48
|
+
};
|
|
49
|
+
destroy(): void;
|
|
50
|
+
}
|
|
51
|
+
export declare function appNonce(value: unknown): value is string;
|
|
52
|
+
export declare function createAppNonce(): string;
|
|
53
|
+
export declare function appJson(value: unknown, maxBytes: number): string;
|
|
54
|
+
export declare function parseAppJson(value: unknown, maxBytes: number): unknown;
|
|
55
|
+
/** Validate BEFORE serializing. This bounds accepted work, not browser structured-clone allocation. */
|
|
56
|
+
export declare function checkpointJson(input: unknown): string;
|
|
57
|
+
export declare function checkpointValue(input: unknown): AppValue;
|
|
58
|
+
export declare function parseAppEnvelope(input: unknown, session: string): {
|
|
59
|
+
id: string;
|
|
60
|
+
request: AppRequest;
|
|
61
|
+
};
|
|
62
|
+
export declare function lifecycleValue(input: unknown): Readonly<AppLifecycle>;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/** Additive app messages on the existing SDK channel. No account or economy authority. */
|
|
2
|
+
export const APP_PROTOCOL = 1;
|
|
3
|
+
export const APP_FRAGMENT = "vibexp";
|
|
4
|
+
export const APP_CATEGORY = "vibexp-app";
|
|
5
|
+
export const APP_LIMITS = Object.freeze({
|
|
6
|
+
checkpointBytes: 32 * 1024, checkpointDepth: 8, checkpointNodes: 2048,
|
|
7
|
+
objectKeys: 64, arrayItems: 256, stringBytes: 8192,
|
|
8
|
+
requestBytes: 34 * 1024, responseBytes: 34 * 1024,
|
|
9
|
+
requestsPerSecond: 10, inFlight: 4, lifetimeRequests: 5000,
|
|
10
|
+
sessionMs: 15 * 60 * 1000, requestTimeoutMs: 10_000,
|
|
11
|
+
});
|
|
12
|
+
export function appNonce(value) { return typeof value === "string" && /^[a-f0-9]{32}$/.test(value); }
|
|
13
|
+
export function createAppNonce() {
|
|
14
|
+
return [...crypto.getRandomValues(new Uint8Array(16))].map(value => value.toString(16).padStart(2, "0")).join("");
|
|
15
|
+
}
|
|
16
|
+
export function appJson(value, maxBytes) {
|
|
17
|
+
const data = JSON.stringify(value);
|
|
18
|
+
if (typeof data !== "string" || data.length > maxBytes || new TextEncoder().encode(data).length > maxBytes)
|
|
19
|
+
throw Error("App message exceeds limit.");
|
|
20
|
+
return data;
|
|
21
|
+
}
|
|
22
|
+
export function parseAppJson(value, maxBytes) {
|
|
23
|
+
if (typeof value !== "string" || value.length > maxBytes || new TextEncoder().encode(value).length > maxBytes)
|
|
24
|
+
throw Error("Invalid app message size or encoding.");
|
|
25
|
+
return JSON.parse(value);
|
|
26
|
+
}
|
|
27
|
+
const plain = (value) => value !== null && typeof value === "object"
|
|
28
|
+
&& (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
29
|
+
const exact = (value, keys) => {
|
|
30
|
+
const own = Object.keys(value);
|
|
31
|
+
return own.length === keys.length && Reflect.ownKeys(value).length === own.length
|
|
32
|
+
&& own.every(key => keys.includes(key) && Object.hasOwn(Object.getOwnPropertyDescriptor(value, key) ?? {}, "value"));
|
|
33
|
+
};
|
|
34
|
+
/** Validate BEFORE serializing. This bounds accepted work, not browser structured-clone allocation. */
|
|
35
|
+
export function checkpointJson(input) {
|
|
36
|
+
let nodes = 0, stringBytes = 0;
|
|
37
|
+
const visit = (value, depth) => {
|
|
38
|
+
if (++nodes > APP_LIMITS.checkpointNodes || depth > APP_LIMITS.checkpointDepth)
|
|
39
|
+
throw Error("App checkpoint is too complex.");
|
|
40
|
+
if (value === null || typeof value === "boolean")
|
|
41
|
+
return;
|
|
42
|
+
if (typeof value === "number") {
|
|
43
|
+
if (!Number.isFinite(value))
|
|
44
|
+
throw Error("Checkpoint numbers must be finite.");
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (typeof value === "string") {
|
|
48
|
+
if (value.length > APP_LIMITS.stringBytes)
|
|
49
|
+
throw Error("App checkpoint string is too large.");
|
|
50
|
+
const size = new TextEncoder().encode(value).byteLength;
|
|
51
|
+
if (size > APP_LIMITS.stringBytes || (stringBytes += size) > APP_LIMITS.checkpointBytes)
|
|
52
|
+
throw Error("App checkpoint strings are too large.");
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (Array.isArray(value)) {
|
|
56
|
+
if (value.length > APP_LIMITS.arrayItems)
|
|
57
|
+
throw Error("App checkpoint array is too large.");
|
|
58
|
+
if (Reflect.ownKeys(value).length !== value.length + 1)
|
|
59
|
+
throw Error("Array checkpoints cannot have extra properties.");
|
|
60
|
+
for (let index = 0; index < value.length; index++) {
|
|
61
|
+
const item = Object.getOwnPropertyDescriptor(value, index);
|
|
62
|
+
if (!item || !("value" in item))
|
|
63
|
+
throw Error("Sparse/accessor checkpoints are unsupported.");
|
|
64
|
+
visit(item.value, depth + 1);
|
|
65
|
+
}
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (!plain(value))
|
|
69
|
+
throw Error("App checkpoint must contain only JSON values.");
|
|
70
|
+
const keys = Object.keys(value);
|
|
71
|
+
if (Reflect.ownKeys(value).length !== keys.length)
|
|
72
|
+
throw Error("Checkpoint properties must be enumerable strings.");
|
|
73
|
+
if (keys.length > APP_LIMITS.objectKeys)
|
|
74
|
+
throw Error("App checkpoint has too many keys.");
|
|
75
|
+
for (const key of keys) {
|
|
76
|
+
if (["__proto__", "constructor", "prototype"].includes(key) || key.length > 128)
|
|
77
|
+
throw Error("Invalid app checkpoint key.");
|
|
78
|
+
stringBytes += new TextEncoder().encode(key).byteLength;
|
|
79
|
+
if (stringBytes > APP_LIMITS.checkpointBytes)
|
|
80
|
+
throw Error("App checkpoint keys are too large.");
|
|
81
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
82
|
+
if (!descriptor || !("value" in descriptor))
|
|
83
|
+
throw Error("App checkpoint accessors are unsupported.");
|
|
84
|
+
visit(descriptor.value, depth + 1);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
visit(input, 0);
|
|
88
|
+
const encoded = JSON.stringify(input);
|
|
89
|
+
if (new TextEncoder().encode(encoded).byteLength > APP_LIMITS.checkpointBytes)
|
|
90
|
+
throw Error("App checkpoint exceeds32KiB.");
|
|
91
|
+
return encoded;
|
|
92
|
+
}
|
|
93
|
+
export function checkpointValue(input) { return JSON.parse(checkpointJson(input)); }
|
|
94
|
+
export function parseAppEnvelope(input, session) {
|
|
95
|
+
if (!plain(input) || !exact(input, ["id", "session", "request"]) || input.session !== session
|
|
96
|
+
|| typeof input.id !== "string" || input.id.length > 80 || !/^[A-Za-z0-9_-]{1,80}$/.test(input.id) || !plain(input.request))
|
|
97
|
+
throw Error("Invalid app session request.");
|
|
98
|
+
const request = input.request;
|
|
99
|
+
if ((request.method === "ui.ready" || request.method === "app.checkpoint.get") && exact(request, ["method"]))
|
|
100
|
+
return { id: input.id, request: { method: request.method } };
|
|
101
|
+
if (request.method === "app.checkpoint.set" && exact(request, ["method", "value"]))
|
|
102
|
+
return { id: input.id, request: { method: request.method, value: checkpointValue(request.value) } };
|
|
103
|
+
throw Error("This app has no permission for that method.");
|
|
104
|
+
}
|
|
105
|
+
export function lifecycleValue(input) {
|
|
106
|
+
if (!plain(input) || !exact(input, ["active", "width", "height"]) || typeof input.active !== "boolean"
|
|
107
|
+
|| typeof input.width !== "number" || !Number.isInteger(input.width) || input.width < 0 || input.width > 4096
|
|
108
|
+
|| typeof input.height !== "number" || !Number.isInteger(input.height) || input.height < 0 || input.height > 4096)
|
|
109
|
+
throw Error("Invalid app lifecycle.");
|
|
110
|
+
return Object.freeze({ active: input.active, width: input.width, height: input.height });
|
|
111
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Admission policy for the local browser adapter; marker absence is not native certification. */
|
|
2
|
+
export function appRuntimeRefusal(host) {
|
|
3
|
+
if (host.location.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(host.location.hostname))
|
|
4
|
+
return "Third-party apps are available only in the local browser developer preview.";
|
|
5
|
+
if (host.top !== host.self)
|
|
6
|
+
return "Third-party apps require a top-level browser host.";
|
|
7
|
+
if (["__VM_STEAM__", "__TAURI_INTERNALS__", "__TAURI__", "vibeNative", "ReactNativeWebView"].some(key => key in host)
|
|
8
|
+
|| /\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i.test(host.navigator.userAgent))
|
|
9
|
+
return "Third-party apps are disabled in native shells until their IPC isolation is verified.";
|
|
10
|
+
return null;
|
|
11
|
+
}
|
package/dist/bin.d.ts
ADDED
package/dist/bin.js
ADDED
package/dist/bundle.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare const assetType: (file: string) => string | undefined;
|
|
2
|
+
export declare const compareAssetNames: (a: string, b: string) => number;
|
|
3
|
+
/** Local authoring reader. Every allocation is bounded before reading; files cannot grow the budget. */
|
|
4
|
+
export declare function readBoundedAsset(filename: string, limit: number): Promise<Uint8Array>;
|
|
5
|
+
export declare function readBuiltBundle(directory: string): Promise<{
|
|
6
|
+
manifest: import("./manifest.ts").GameManifest;
|
|
7
|
+
files: Record<string, Uint8Array<ArrayBufferLike>>;
|
|
8
|
+
digest: string;
|
|
9
|
+
expandedBytes: number;
|
|
10
|
+
}>;
|
package/dist/bundle.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, open, opendir, realpath } from "node:fs/promises";
|
|
3
|
+
import { constants } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { assetPath, GAME_LIMITS, parseManifest } from "./manifest.js";
|
|
6
|
+
const TYPES = {
|
|
7
|
+
html: "text/html; charset=utf-8", js: "text/javascript; charset=utf-8", mjs: "text/javascript; charset=utf-8",
|
|
8
|
+
css: "text/css; charset=utf-8", json: "application/json", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg",
|
|
9
|
+
webp: "image/webp", gif: "image/gif", avif: "image/avif", svg: "image/svg+xml", ico: "image/x-icon",
|
|
10
|
+
woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf", mp3: "audio/mpeg", ogg: "audio/ogg",
|
|
11
|
+
wav: "audio/wav", mp4: "video/mp4", webm: "video/webm", wasm: "application/wasm", bin: "application/octet-stream", txt: "text/plain; charset=utf-8",
|
|
12
|
+
};
|
|
13
|
+
export const assetType = (file) => TYPES[file.slice(file.lastIndexOf(".") + 1).toLowerCase()];
|
|
14
|
+
export const compareAssetNames = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
15
|
+
/** Local authoring reader. Every allocation is bounded before reading; files cannot grow the budget. */
|
|
16
|
+
export async function readBoundedAsset(filename, limit) {
|
|
17
|
+
const stat = await lstat(filename);
|
|
18
|
+
if (!Number.isSafeInteger(limit) || limit < 0 || !stat.isFile() || stat.isSymbolicLink() || stat.size > limit)
|
|
19
|
+
throw Error("Asset exceeds size/type limit.");
|
|
20
|
+
const handle = await open(filename, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
21
|
+
try {
|
|
22
|
+
const before = await handle.stat();
|
|
23
|
+
if (!before.isFile() || before.dev !== stat.dev || before.ino !== stat.ino || before.size !== stat.size)
|
|
24
|
+
throw Error("App bundle changed before reading.");
|
|
25
|
+
const bytes = new Uint8Array(before.size);
|
|
26
|
+
let offset = 0;
|
|
27
|
+
while (offset < bytes.length) {
|
|
28
|
+
const read = await handle.read(bytes, offset, bytes.length - offset, offset);
|
|
29
|
+
if (!read.bytesRead)
|
|
30
|
+
throw Error("App bundle changed while being read.");
|
|
31
|
+
offset += read.bytesRead;
|
|
32
|
+
}
|
|
33
|
+
const after = await handle.stat(), named = await lstat(filename);
|
|
34
|
+
if (after.dev !== before.dev || after.ino !== before.ino || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs
|
|
35
|
+
|| named.isSymbolicLink() || named.dev !== before.dev || named.ino !== before.ino)
|
|
36
|
+
throw Error("App bundle changed while being read.");
|
|
37
|
+
return bytes;
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
await handle.close();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export async function readBuiltBundle(directory) {
|
|
44
|
+
const root = await realpath(directory), files = Object.create(null);
|
|
45
|
+
let size = 0, entries = 0;
|
|
46
|
+
const folded = new Set();
|
|
47
|
+
async function walk(relative) {
|
|
48
|
+
for await (const entry of await opendir(path.join(root, relative))) {
|
|
49
|
+
if (++entries > GAME_LIMITS.files)
|
|
50
|
+
throw Error("App exceeds bundle entry limits.");
|
|
51
|
+
const name = entry.name;
|
|
52
|
+
const file = relative ? `${relative}/${name}` : name;
|
|
53
|
+
if (!assetPath(file))
|
|
54
|
+
throw Error(`Invalid asset path: ${file}`);
|
|
55
|
+
if (folded.has(file.toLowerCase()))
|
|
56
|
+
throw Error("App bundle paths collide by case.");
|
|
57
|
+
folded.add(file.toLowerCase());
|
|
58
|
+
const stat = await lstat(path.join(root, file));
|
|
59
|
+
if (stat.isSymbolicLink())
|
|
60
|
+
throw Error("App bundle symlinks are forbidden.");
|
|
61
|
+
if (stat.isDirectory()) {
|
|
62
|
+
await walk(file);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (!stat.isFile() || !assetType(file) || stat.size > GAME_LIMITS.file || (size += stat.size) > GAME_LIMITS.expanded)
|
|
66
|
+
throw Error("App exceeds bundle limits or contains unsupported files.");
|
|
67
|
+
files[file] = await readBoundedAsset(path.join(root, file), stat.size);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
await walk("");
|
|
71
|
+
const input = files["vibemarket.json"];
|
|
72
|
+
if (!input || input.byteLength > 16 * 1024)
|
|
73
|
+
throw Error("A manifest of at most16KiB is required.");
|
|
74
|
+
const manifest = parseManifest(JSON.parse(new TextDecoder().decode(input)));
|
|
75
|
+
if (!files[manifest.entry])
|
|
76
|
+
throw Error("Manifest entry is missing from the app bundle.");
|
|
77
|
+
files["vibemarket.json"] = new TextEncoder().encode(JSON.stringify(manifest));
|
|
78
|
+
const digest = createHash("sha256");
|
|
79
|
+
for (const [file, bytes] of Object.entries(files).sort(([a], [b]) => compareAssetNames(a, b)))
|
|
80
|
+
digest.update(JSON.stringify([file, bytes.byteLength, createHash("sha256").update(bytes).digest("hex")]));
|
|
81
|
+
return { manifest, files, digest: digest.digest("hex"), expandedBytes: size };
|
|
82
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const CHANNEL = "vibemarket.game.v1";
|
package/dist/channel.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const CHANNEL = "vibemarket.game.v1";
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface CliSignals {
|
|
2
|
+
once(signal: "SIGINT" | "SIGTERM", handler: () => void): unknown;
|
|
3
|
+
off(signal: "SIGINT" | "SIGTERM", handler: () => void): unknown;
|
|
4
|
+
}
|
|
5
|
+
export interface CliProcess extends CliSignals {
|
|
6
|
+
readonly argv: readonly string[];
|
|
7
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
8
|
+
cwd(): string;
|
|
9
|
+
exitCode?: NodeJS.Process["exitCode"];
|
|
10
|
+
}
|
|
11
|
+
export interface CliRuntime {
|
|
12
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
13
|
+
cwd(): string;
|
|
14
|
+
log(line: string): void;
|
|
15
|
+
readonly signals: CliSignals;
|
|
16
|
+
request(url: URL, init: RequestInit): Promise<Response>;
|
|
17
|
+
}
|
|
18
|
+
export declare function createCliRuntime(host?: CliProcess, log?: (line: string) => void, request?: typeof fetch): CliRuntime;
|
|
19
|
+
/** Passive dispatcher: tests and other tools provide owned process boundaries. */
|
|
20
|
+
export declare function runCli(argv: readonly string[], runtime?: CliRuntime): Promise<void>;
|
|
21
|
+
export declare function launchCli(host: CliProcess, log?: (line: string) => void, report?: (line: string) => void, request?: typeof fetch): Promise<void>;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { readFile, lstat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { zipSync } from "fflate";
|
|
3
|
+
import { GAME_LIMITS } from "./manifest.js";
|
|
4
|
+
import { readBuiltBundle } from "./bundle.js";
|
|
5
|
+
import { createApp, stageAppAssets } from "./scaffold.js";
|
|
6
|
+
import { startAppPreview } from "./preview.js";
|
|
7
|
+
export function createCliRuntime(host = process, log = console.log, request = fetch) {
|
|
8
|
+
return { env: host.env, cwd: () => host.cwd(), log, request: (url, init) => request(url, init), signals: { once: (signal, handler) => host.once(signal, handler), off: (signal, handler) => host.off(signal, handler) } };
|
|
9
|
+
}
|
|
10
|
+
/** Passive dispatcher: tests and other tools provide owned process boundaries. */
|
|
11
|
+
export async function runCli(argv, runtime = createCliRuntime()) {
|
|
12
|
+
const [command, ...args] = argv;
|
|
13
|
+
if (command === "init") {
|
|
14
|
+
if (!args[0] || args.length > 2)
|
|
15
|
+
throw Error("Usage: os init <empty-directory> [sdk.tgz]");
|
|
16
|
+
runtime.log(`Created ${await createApp(args[0], args[1])}. Run npm install, npm run build, then npm run dev there.`);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (command === "assets") {
|
|
20
|
+
if (args.length)
|
|
21
|
+
throw Error("Usage: os assets");
|
|
22
|
+
await stageAppAssets(runtime.cwd());
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (command === "preview") {
|
|
26
|
+
if (!args[0] || args.length > 2 || (args[1] !== undefined && !/^\d{1,5}$/.test(args[1])))
|
|
27
|
+
throw Error("Usage: vibemarket-game preview <built-directory> [port]");
|
|
28
|
+
const preview = await startAppPreview(args[0], args[1] === undefined ? 0 : Number(args[1]));
|
|
29
|
+
runtime.log(`VibeMarket OS preview: ${preview.origin}`);
|
|
30
|
+
await new Promise((resolve, reject) => {
|
|
31
|
+
let closing = false;
|
|
32
|
+
const stop = () => { if (closing)
|
|
33
|
+
return; closing = true; runtime.signals.off("SIGINT", stop); runtime.signals.off("SIGTERM", stop); void preview.close().then(resolve, reject); };
|
|
34
|
+
runtime.signals.once("SIGINT", stop);
|
|
35
|
+
runtime.signals.once("SIGTERM", stop);
|
|
36
|
+
});
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
if (command === "pack") {
|
|
40
|
+
const [directory, output] = args;
|
|
41
|
+
if (!directory || !output)
|
|
42
|
+
throw Error("Usage: vibemarket-game pack <built-directory> <game.zip>");
|
|
43
|
+
const { files, manifest } = await readBuiltBundle(directory);
|
|
44
|
+
const archive = zipSync(files, { level: 6 });
|
|
45
|
+
if (archive.length > GAME_LIMITS.archive)
|
|
46
|
+
throw Error("Compressed bundle exceeds 20 MiB.");
|
|
47
|
+
await writeFile(output, archive);
|
|
48
|
+
runtime.log(`Packed ${manifest.id}@${manifest.version}: ${Object.keys(files).length} files → ${output}`);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (!["upload", "list", "publish", "rollback"].includes(command ?? "")) {
|
|
52
|
+
runtime.log("os init <empty-directory> [sdk.tgz]\nos assets\nos preview <dist> [port]\nos pack <dist> <game.zip>\nos upload <game.zip>\nos list\nos publish <game-id> <version> <registry-revision>\nos rollback <game-id> <version> <registry-revision>\n\nSet VIBEMARKET_PUBLISH_URL=http://127.0.0.1:8888 and VIBEMARKET_PUBLISH_TOKEN (local operator credential). Upload returns a draft preview URL. Publish and rollback only update the active version pointer.");
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const base = new URL(runtime.env.VIBEMARKET_PUBLISH_URL ?? "http://127.0.0.1:8888");
|
|
56
|
+
if (base.protocol !== "http:" || !["localhost", "127.0.0.1"].includes(base.hostname) || base.username || base.password)
|
|
57
|
+
throw Error("The internal publisher only accepts loopback HTTP URLs.");
|
|
58
|
+
const token = runtime.env.VIBEMARKET_PUBLISH_TOKEN;
|
|
59
|
+
if (!token)
|
|
60
|
+
throw Error("Set VIBEMARKET_PUBLISH_TOKEN. In the host checkout run yarn games:publisher-token to provision/read it.");
|
|
61
|
+
const headers = { Authorization: `Bearer ${token}`, "X-Vibe-Publisher": "1", "Content-Type": command === "upload" ? "application/zip" : "application/json" };
|
|
62
|
+
let body;
|
|
63
|
+
if (command === "upload") {
|
|
64
|
+
if (!args[0])
|
|
65
|
+
throw Error("Pass the game ZIP path.");
|
|
66
|
+
const stat = await lstat(args[0]);
|
|
67
|
+
if (stat.size > GAME_LIMITS.archive)
|
|
68
|
+
throw Error("Archive exceeds 20 MiB.");
|
|
69
|
+
body = new Uint8Array(await readFile(args[0]));
|
|
70
|
+
}
|
|
71
|
+
else if (command === "publish" || command === "rollback") {
|
|
72
|
+
if (!args[0] || !args[1] || !/^\d+$/.test(args[2] ?? ""))
|
|
73
|
+
throw Error("Pass game ID, version, and the registry revision returned by list/upload.");
|
|
74
|
+
body = JSON.stringify({ id: args[0], version: args[1], revision: Number(args[2]) });
|
|
75
|
+
}
|
|
76
|
+
const response = await runtime.request(new URL("/api/game-publisher", base), { method: command === "list" ? "GET" : command === "upload" ? "POST" : "PUT", headers, body });
|
|
77
|
+
const result = await response.json();
|
|
78
|
+
if (!response.ok)
|
|
79
|
+
throw Error(JSON.stringify(result));
|
|
80
|
+
runtime.log(JSON.stringify(result, null, 2));
|
|
81
|
+
}
|
|
82
|
+
export async function launchCli(host, log = console.log, report = console.error, request = fetch) {
|
|
83
|
+
try {
|
|
84
|
+
await runCli(host.argv.slice(2), createCliRuntime(host, log, request));
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
report(error instanceof Error ? error.message : "SDK command failed.");
|
|
88
|
+
host.exitCode = 1;
|
|
89
|
+
}
|
|
90
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { GameSdk } from "./types.ts";
|
|
2
|
+
/** Existing Market v1 API; no Desk capability is inferred from these methods. */
|
|
3
|
+
export declare function connectGameSdk(signal?: AbortSignal): Promise<GameSdk>;
|
|
4
|
+
export declare function createPortSdk(port: MessagePort): GameSdk;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { connectHostPort, createRpcTransport } from "./transport.js";
|
|
2
|
+
/** Existing Market v1 API; no Desk capability is inferred from these methods. */
|
|
3
|
+
export async function connectGameSdk(signal) {
|
|
4
|
+
const { port } = await connectHostPort(signal);
|
|
5
|
+
return createPortSdk(port);
|
|
6
|
+
}
|
|
7
|
+
export function createPortSdk(port) {
|
|
8
|
+
const listeners = new Set();
|
|
9
|
+
const transport = createRpcTransport(port, { onEvent(value) {
|
|
10
|
+
if (value.event === "inventory.changed")
|
|
11
|
+
listeners.forEach(listener => listener());
|
|
12
|
+
} });
|
|
13
|
+
return Object.freeze({
|
|
14
|
+
profile: { get: () => transport.request({ method: "profile.get" }) },
|
|
15
|
+
catalog: { list: () => transport.request({ method: "catalog.list" }) },
|
|
16
|
+
inventory: {
|
|
17
|
+
get: (cursor = 0) => transport.request({ method: "inventory.get", cursor }),
|
|
18
|
+
onChanged(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
19
|
+
},
|
|
20
|
+
packs: {
|
|
21
|
+
buy: (packId, quantity = 1) => transport.request({ method: "packs.buy", packId, quantity }),
|
|
22
|
+
sell: (packId, quantity = 1) => transport.request({ method: "packs.sell", packId, quantity }),
|
|
23
|
+
open: (packId, quantity = 1) => transport.request({ method: "packs.open", packId, quantity }),
|
|
24
|
+
},
|
|
25
|
+
cards: {
|
|
26
|
+
reveal: (cardId) => transport.request({ method: "cards.reveal", cardId }),
|
|
27
|
+
sell: (cardId) => transport.request({ method: "cards.sell", cardId }),
|
|
28
|
+
collect: (cardId) => transport.request({ method: "cards.collect", cardId }),
|
|
29
|
+
},
|
|
30
|
+
ready: () => transport.request({ method: "ui.ready" }),
|
|
31
|
+
showShop: () => transport.request({ method: "ui.shop" }),
|
|
32
|
+
destroy() { listeners.clear(); transport.destroy(); },
|
|
33
|
+
});
|
|
34
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { connectGameSdk, createPortSdk } from "./client.ts";
|
|
2
|
+
export { CHANNEL } from "./channel.ts";
|
|
3
|
+
export { watchInventory } from "./inventory.ts";
|
|
4
|
+
export { connectVibeMarketApp } from "./app-client.ts";
|
|
5
|
+
export type { AppValue, AppLifecycle, VibeMarketAppSdk } from "./app-protocol.ts";
|
|
6
|
+
export type { InventoryObserver } from "./inventory.ts";
|
|
7
|
+
export type * from "./types.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { GameInventory, GameSdk } from "./types.ts";
|
|
2
|
+
export interface InventoryObserver {
|
|
3
|
+
onChange(inventory: GameInventory): void;
|
|
4
|
+
onError(error: Error): void;
|
|
5
|
+
/** Maximum pages per refresh, 1–100. Default: 20 (2,000 cards). */
|
|
6
|
+
maxPages?: number;
|
|
7
|
+
}
|
|
8
|
+
/** Atomic, paginated collection updates. Uses only the existing inventory permission. */
|
|
9
|
+
export declare function watchInventory(sdk: Pick<GameSdk, "inventory">, observer: InventoryObserver): {
|
|
10
|
+
refresh: () => Promise<void>;
|
|
11
|
+
destroy(): void;
|
|
12
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** Atomic, paginated collection updates. Uses only the existing inventory permission. */
|
|
2
|
+
export function watchInventory(sdk, observer) {
|
|
3
|
+
const maxPages = observer.maxPages ?? 20;
|
|
4
|
+
if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > 100)
|
|
5
|
+
throw Error("maxPages must be an integer from 1 to 100.");
|
|
6
|
+
let stopped = false;
|
|
7
|
+
let dirty = false;
|
|
8
|
+
let pending;
|
|
9
|
+
const refresh = () => {
|
|
10
|
+
if (stopped)
|
|
11
|
+
return Promise.resolve();
|
|
12
|
+
dirty = true;
|
|
13
|
+
if (pending)
|
|
14
|
+
return pending;
|
|
15
|
+
pending = Promise.resolve().then(async () => {
|
|
16
|
+
while (dirty && !stopped) {
|
|
17
|
+
dirty = false;
|
|
18
|
+
try {
|
|
19
|
+
const cards = [];
|
|
20
|
+
let packs = [];
|
|
21
|
+
let cursor = 0;
|
|
22
|
+
for (let page = 0; page < maxPages; page++) {
|
|
23
|
+
const inventory = await sdk.inventory.get(cursor);
|
|
24
|
+
if (stopped || dirty)
|
|
25
|
+
break;
|
|
26
|
+
if (page === 0)
|
|
27
|
+
packs = inventory.packs;
|
|
28
|
+
cards.push(...inventory.cards);
|
|
29
|
+
if (inventory.nextCursor === null) {
|
|
30
|
+
observer.onChange({ packs, cards: [...new Map(cards.map(card => [card.id, card])).values()], nextCursor: null });
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
if (!Number.isSafeInteger(inventory.nextCursor) || inventory.nextCursor <= cursor)
|
|
34
|
+
throw Error("Inventory pagination did not advance. Retry from the host.");
|
|
35
|
+
if (page + 1 === maxPages)
|
|
36
|
+
throw Error("Inventory exceeds this game's page limit. Increase maxPages before granting collection access.");
|
|
37
|
+
cursor = inventory.nextCursor;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (!stopped && !dirty)
|
|
42
|
+
observer.onError(error instanceof Error ? error : Error("Inventory unavailable."));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}).finally(() => { pending = undefined; });
|
|
46
|
+
return pending;
|
|
47
|
+
};
|
|
48
|
+
const unsubscribe = sdk.inventory.onChanged(() => { void refresh(); });
|
|
49
|
+
void refresh();
|
|
50
|
+
return {
|
|
51
|
+
refresh,
|
|
52
|
+
destroy() { stopped = true; unsubscribe(); },
|
|
53
|
+
};
|
|
54
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export declare const GAME_PERMISSIONS: readonly ["profile.get", "catalog.list", "inventory.get", "packs.buy", "packs.sell", "packs.open", "cards.reveal", "cards.sell", "cards.collect"];
|
|
2
|
+
export type GamePermission = typeof GAME_PERMISSIONS[number];
|
|
3
|
+
export interface GameManifest {
|
|
4
|
+
schemaVersion: 1;
|
|
5
|
+
sdkVersion: 1;
|
|
6
|
+
id: string;
|
|
7
|
+
version: string;
|
|
8
|
+
name: string;
|
|
9
|
+
tagline: string;
|
|
10
|
+
category: string;
|
|
11
|
+
entry: string;
|
|
12
|
+
permissions: GamePermission[];
|
|
13
|
+
collectionId: string | null;
|
|
14
|
+
}
|
|
15
|
+
export declare const GAME_LIMITS: {
|
|
16
|
+
readonly archive: number;
|
|
17
|
+
readonly expanded: number;
|
|
18
|
+
readonly file: number;
|
|
19
|
+
readonly files: 256;
|
|
20
|
+
readonly versions: 100;
|
|
21
|
+
readonly games: 40;
|
|
22
|
+
};
|
|
23
|
+
export declare function assetPath(value: string): boolean;
|
|
24
|
+
export declare function parseManifest(input: unknown): GameManifest;
|
package/dist/manifest.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export const GAME_PERMISSIONS = ["profile.get", "catalog.list", "inventory.get", "packs.buy", "packs.sell", "packs.open", "cards.reveal", "cards.sell", "cards.collect"];
|
|
2
|
+
export const GAME_LIMITS = { archive: 20 * 1024 * 1024, expanded: 64 * 1024 * 1024, file: 16 * 1024 * 1024, files: 256, versions: 100, games: 40 };
|
|
3
|
+
export function assetPath(value) {
|
|
4
|
+
return value.length > 0 && value.length <= 200 && value.split("/").every(part => /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(part) && !part.endsWith("."));
|
|
5
|
+
}
|
|
6
|
+
export function parseManifest(input) {
|
|
7
|
+
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
8
|
+
throw Error("vibemarket.json must be an object.");
|
|
9
|
+
const data = input;
|
|
10
|
+
const fields = ["schemaVersion", "sdkVersion", "id", "version", "name", "tagline", "category", "entry", "permissions", "collectionId"];
|
|
11
|
+
if (Object.keys(data).some(key => !fields.includes(key)) || fields.some(key => !(key in data)))
|
|
12
|
+
throw Error("Manifest fields must match schema version 1 exactly.");
|
|
13
|
+
const str = (key, max) => { const value = data[key]; if (typeof value !== "string" || !value.trim() || value !== value.trim() || value.length > max)
|
|
14
|
+
throw Error(`Invalid manifest ${key}.`); return value; };
|
|
15
|
+
if (data.schemaVersion !== 1 || data.sdkVersion !== 1)
|
|
16
|
+
throw Error("Only manifest and SDK version 1 are supported.");
|
|
17
|
+
const id = str("id", 60), version = str("version", 50), entry = str("entry", 200);
|
|
18
|
+
if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(id) || id === "chonk-club")
|
|
19
|
+
throw Error("Choose a lowercase game slug; chonk-club is reserved for the built-in game.");
|
|
20
|
+
if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?$/.test(version))
|
|
21
|
+
throw Error("Version must be semver, for example 1.0.0 or 1.0.0-test.1.");
|
|
22
|
+
if (!assetPath(entry) || !entry.endsWith(".html"))
|
|
23
|
+
throw Error("Entry must be a relative .html asset path.");
|
|
24
|
+
if (!Array.isArray(data.permissions) || data.permissions.some(value => typeof value !== "string" || !GAME_PERMISSIONS.includes(value)) || new Set(data.permissions).size !== data.permissions.length)
|
|
25
|
+
throw Error("Permissions must be a unique list of supported SDK methods.");
|
|
26
|
+
const permissions = data.permissions;
|
|
27
|
+
if (data.collectionId !== null && (typeof data.collectionId !== "string" || !/^[A-Za-z0-9:_-]{1,200}$/.test(data.collectionId)))
|
|
28
|
+
throw Error("collectionId must be null or a market collection ID.");
|
|
29
|
+
if (!data.collectionId && permissions.some(value => value.startsWith("packs.") || value.startsWith("cards.")))
|
|
30
|
+
throw Error("Trading permissions require a collectionId.");
|
|
31
|
+
return { schemaVersion: 1, sdkVersion: 1, id, version, name: str("name", 60), tagline: str("tagline", 160), category: str("category", 80), entry, permissions: [...permissions].sort(), collectionId: data.collectionId };
|
|
32
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function startPreviewParent(): Promise<void>;
|