@vibechain/os 0.2.1 → 0.4.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.
Files changed (47) hide show
  1. package/AGENTS.md +110 -201
  2. package/README.md +78 -7
  3. package/SECURITY.md +22 -3
  4. package/dist/app-runtime.d.ts +1 -1
  5. package/dist/app-runtime.js +11 -3
  6. package/dist/bundle.js +10 -0
  7. package/dist/canvas.d.ts +40 -0
  8. package/dist/canvas.js +41 -0
  9. package/dist/cli.js +1 -1
  10. package/dist/listing.d.ts +35 -0
  11. package/dist/listing.js +56 -0
  12. package/dist/loop.d.ts +34 -0
  13. package/dist/loop.js +47 -0
  14. package/dist/manifest.d.ts +70 -1
  15. package/dist/manifest.js +117 -9
  16. package/dist/preview-ui.js +1 -1
  17. package/dist/scaffold.js +20 -7
  18. package/dist/testing.d.ts +29 -0
  19. package/dist/testing.js +49 -0
  20. package/examples/paw-beat/README.md +50 -0
  21. package/examples/paw-beat/cat.ts +129 -0
  22. package/examples/paw-beat/game.ts +151 -0
  23. package/examples/paw-beat/index.html +65 -0
  24. package/examples/paw-beat/main.ts +243 -0
  25. package/examples/paw-beat/music.ts +123 -0
  26. package/examples/paw-beat/store/icon.png +0 -0
  27. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  28. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  29. package/examples/paw-beat/vibemarket.json +21 -0
  30. package/examples/vibexp-app/README.md +19 -3
  31. package/examples/vibexp-app/store/icon.png +0 -0
  32. package/examples/vibexp-app/store/screenshot-1.png +0 -0
  33. package/examples/vibexp-app/vibemarket.json +21 -1
  34. package/package.json +19 -2
  35. package/examples/chonk-stack/card-slice.ts +0 -17
  36. package/examples/chonk-stack/cat3d.ts +0 -57
  37. package/examples/chonk-stack/game.css +0 -174
  38. package/examples/chonk-stack/index.html +0 -32
  39. package/examples/chonk-stack/main.ts +0 -149
  40. package/examples/chonk-stack/model.ts +0 -40
  41. package/examples/chonk-stack/renderer.ts +0 -263
  42. package/examples/chonk-stack/skins.ts +0 -47
  43. package/examples/chonk-stack/vibemarket.json +0 -21
  44. package/examples/collection-room/index.html +0 -3
  45. package/examples/collection-room/main.ts +0 -31
  46. package/examples/collection-room/vibemarket.json +0 -12
  47. package/examples/tsconfig.json +0 -4
package/dist/canvas.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Keep a canvas backing store matched to the host surface, with the pixel ratio capped
3
+ * so a high-density display cannot multiply the fill cost. The canvas is resized (and so
4
+ * cleared) only when the computed size actually changes. Style the canvas to fill the
5
+ * app; this sets only its `width` and `height`.
6
+ */
7
+ export function fitCanvas(app, canvas, options = {}, view = window) {
8
+ const maxRatio = options.maxPixelRatio ?? 2, maxPixels = options.maxPixels ?? 3840 * 2160;
9
+ if (!Number.isFinite(maxRatio) || maxRatio < 1 || maxRatio > 4)
10
+ throw Error("maxPixelRatio must be from 1 to 4.");
11
+ if (!Number.isInteger(maxPixels) || maxPixels < 1)
12
+ throw Error("maxPixels must be a positive integer.");
13
+ let fit = null;
14
+ const apply = (state) => {
15
+ if (state.width < 1 || state.height < 1)
16
+ return;
17
+ const device = Number.isFinite(view.devicePixelRatio) && view.devicePixelRatio >= 1 ? view.devicePixelRatio : 1;
18
+ const pixelRatio = Math.min(device, maxRatio, Math.sqrt(maxPixels / (state.width * state.height)));
19
+ const width = Math.max(1, Math.floor(state.width * pixelRatio)), height = Math.max(1, Math.floor(state.height * pixelRatio));
20
+ if (fit && fit.width === width && fit.height === height)
21
+ return;
22
+ canvas.width = width;
23
+ canvas.height = height;
24
+ fit = Object.freeze({ width, height, pixelRatio });
25
+ options.onResize?.(fit);
26
+ };
27
+ const lost = (event) => { event.preventDefault(); options.onContextLost?.(); };
28
+ const restored = () => { options.onContextRestored?.(); };
29
+ canvas.addEventListener("webglcontextlost", lost);
30
+ canvas.addEventListener("webglcontextrestored", restored);
31
+ const unsubscribe = app.lifecycle.onChanged(apply);
32
+ apply(app.lifecycle.current());
33
+ return {
34
+ current: () => fit,
35
+ stop() {
36
+ unsubscribe();
37
+ canvas.removeEventListener("webglcontextlost", lost);
38
+ canvas.removeEventListener("webglcontextrestored", restored);
39
+ },
40
+ };
41
+ }
package/dist/cli.js CHANGED
@@ -13,7 +13,7 @@ export async function runCli(argv, runtime = createCliRuntime()) {
13
13
  if (command === "init") {
14
14
  if (!args[0] || args.length > 2)
15
15
  throw Error("Usage: os init <empty-directory> [sdk.tgz]");
16
- runtime.log(`Created ${await createApp(args[0], args[1])}. Run npm install, yarn run build, then yarn run dev there.`);
16
+ runtime.log(`Created ${await createApp(args[0], args[1])}. Run npm install, npm run build, then npm run dev there.`);
17
17
  return;
18
18
  }
19
19
  if (command === "assets") {
@@ -0,0 +1,35 @@
1
+ import { type AppManifestV2 } from "./manifest.ts";
2
+ /**
3
+ * Byte checks for a schema version 2 store listing. Pure functions over `Uint8Array` with no Node or DOM
4
+ * dependency, so the same rules run in the CLI, a server and a browser.
5
+ */
6
+ export type ImageKind = "png" | "jpeg" | "webp";
7
+ export interface ImageSize {
8
+ width: number;
9
+ height: number;
10
+ }
11
+ /** The `StoreSubmitCode` values a listing check can produce. */
12
+ export type ListingErrorCode = "missing-icon" | "bad-icon" | "bad-screenshot";
13
+ export interface ListingError {
14
+ ok: false;
15
+ code: ListingErrorCode;
16
+ message: string;
17
+ detail: string;
18
+ }
19
+ export type ListingResult = {
20
+ ok: true;
21
+ } | ListingError;
22
+ /**
23
+ * Width and height of a PNG from its first chunk, or null. Checks the 8-byte signature, that the first chunk is
24
+ * `IHDR` with length 13 and present in full, and that both dimensions are 1 to 2^31-1 as the PNG format requires.
25
+ * Nothing else in the file is read or trusted; this is not a decoder.
26
+ */
27
+ export declare function pngSize(bytes: Uint8Array): ImageSize | null;
28
+ /** The image format named by a file's magic bytes, or null. */
29
+ export declare function imageKind(bytes: Uint8Array): ImageKind | null;
30
+ /**
31
+ * Checks the icon and screenshots a v2 manifest names against the bundle's files: the icon exists, is a PNG of
32
+ * exactly 256 x 256 pixels and at most 256 KiB; each screenshot exists, is at most 1 MiB and its signature matches
33
+ * its extension. `detail` is the offending path. Assumes `manifest` came from `parseManifest`.
34
+ */
35
+ export declare function checkListing(manifest: AppManifestV2, files: Readonly<Record<string, Uint8Array>>): ListingResult;
@@ -0,0 +1,56 @@
1
+ import { APP_STORE_LIMITS } from "./manifest.js";
2
+ const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
3
+ const IHDR = [0x49, 0x48, 0x44, 0x52];
4
+ const startsWith = (bytes, prefix, offset = 0) => bytes.length >= offset + prefix.length && prefix.every((value, i) => bytes[offset + i] === value);
5
+ const uint32 = (bytes, offset) => ((bytes[offset] << 24) >>> 0) + (bytes[offset + 1] << 16) + (bytes[offset + 2] << 8) + bytes[offset + 3];
6
+ /**
7
+ * Width and height of a PNG from its first chunk, or null. Checks the 8-byte signature, that the first chunk is
8
+ * `IHDR` with length 13 and present in full, and that both dimensions are 1 to 2^31-1 as the PNG format requires.
9
+ * Nothing else in the file is read or trusted; this is not a decoder.
10
+ */
11
+ export function pngSize(bytes) {
12
+ if (bytes.length < 8 + 8 + 13 || !startsWith(bytes, PNG) || uint32(bytes, 8) !== 13 || !startsWith(bytes, IHDR, 12))
13
+ return null;
14
+ const width = uint32(bytes, 16), height = uint32(bytes, 20);
15
+ return width > 0 && height > 0 && width <= 0x7fffffff && height <= 0x7fffffff ? { width, height } : null;
16
+ }
17
+ /** The image format named by a file's magic bytes, or null. */
18
+ export function imageKind(bytes) {
19
+ if (startsWith(bytes, PNG))
20
+ return "png";
21
+ if (startsWith(bytes, [0xff, 0xd8, 0xff]))
22
+ return "jpeg";
23
+ if (startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) && startsWith(bytes, [0x57, 0x45, 0x42, 0x50], 8))
24
+ return "webp";
25
+ return null;
26
+ }
27
+ const KIND_BY_EXTENSION = { png: "png", jpg: "jpeg", jpeg: "jpeg", webp: "webp" };
28
+ const fail = (code, message, detail) => ({ ok: false, code, message, detail });
29
+ const KiB = 1024;
30
+ /**
31
+ * Checks the icon and screenshots a v2 manifest names against the bundle's files: the icon exists, is a PNG of
32
+ * exactly 256 x 256 pixels and at most 256 KiB; each screenshot exists, is at most 1 MiB and its signature matches
33
+ * its extension. `detail` is the offending path. Assumes `manifest` came from `parseManifest`.
34
+ */
35
+ export function checkListing(manifest, files) {
36
+ const limits = APP_STORE_LIMITS, file = (name) => Object.hasOwn(files, name) ? files[name] : undefined;
37
+ const { icon, screenshots } = manifest.store, iconBytes = file(icon);
38
+ if (!iconBytes)
39
+ return fail("missing-icon", `The store icon ${icon} is not in the app bundle.`, icon);
40
+ if (iconBytes.byteLength > limits.iconBytes)
41
+ return fail("bad-icon", `The store icon ${icon} is larger than ${limits.iconBytes / KiB} KiB.`, icon);
42
+ const size = pngSize(iconBytes);
43
+ if (!size || size.width !== limits.iconSize || size.height !== limits.iconSize)
44
+ return fail("bad-icon", `The store icon ${icon} must be a PNG of exactly ${limits.iconSize} x ${limits.iconSize} pixels.`, icon);
45
+ for (const shot of screenshots) {
46
+ const bytes = file(shot);
47
+ if (!bytes)
48
+ return fail("bad-screenshot", `The screenshot ${shot} is not in the app bundle.`, shot);
49
+ if (bytes.byteLength > limits.screenshotBytes)
50
+ return fail("bad-screenshot", `The screenshot ${shot} is larger than ${limits.screenshotBytes / KiB / KiB} MiB.`, shot);
51
+ const expected = KIND_BY_EXTENSION[shot.slice(shot.lastIndexOf(".") + 1)];
52
+ if (!expected || imageKind(bytes) !== expected)
53
+ return fail("bad-screenshot", `The screenshot ${shot} is not a ${expected ?? "supported"} image, or its contents do not match its extension.`, shot);
54
+ }
55
+ return { ok: true };
56
+ }
package/dist/loop.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { AppLifecycle } from "./app-protocol.ts";
2
+ /** The part of the app SDK the game helpers read. `connectVibeMarketApp()` satisfies it. */
3
+ export interface LifecycleSource {
4
+ lifecycle: {
5
+ current(): Readonly<AppLifecycle>;
6
+ onChanged(listener: (state: Readonly<AppLifecycle>) => void): () => void;
7
+ };
8
+ }
9
+ export interface LoopOptions {
10
+ /** Fixed simulation step in milliseconds, above 0 and at most 1000. Default: 1000 / 60. */
11
+ stepMs?: number;
12
+ /** Most simulation steps run in one frame after a stall, 1 to 240. Extra time is dropped. Default: 5. */
13
+ maxSteps?: number;
14
+ /** Advance the simulation by exactly `stepMs`. */
15
+ update(stepMs: number): void;
16
+ /** Draw once per frame. `alpha` (0 to 1) is how far the frame sits between two simulation steps. */
17
+ render(alpha: number): void;
18
+ }
19
+ export interface Loop {
20
+ /** True while a frame is scheduled: the app is active and the loop was not stopped. */
21
+ readonly running: boolean;
22
+ /** Stop for good and release the lifecycle listener. */
23
+ stop(): void;
24
+ }
25
+ export interface FrameClock {
26
+ requestAnimationFrame(callback: (time: number) => void): number;
27
+ cancelAnimationFrame(handle: number): void;
28
+ }
29
+ /**
30
+ * A fixed-timestep game loop that runs only while the host reports the app active.
31
+ * Time spent inactive is discarded rather than simulated on return. If `update` or
32
+ * `render` throws, the error propagates and the loop stays stopped.
33
+ */
34
+ export declare function createLoop(app: LifecycleSource, options: LoopOptions, clock?: FrameClock): Loop;
package/dist/loop.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * A fixed-timestep game loop that runs only while the host reports the app active.
3
+ * Time spent inactive is discarded rather than simulated on return. If `update` or
4
+ * `render` throws, the error propagates and the loop stays stopped.
5
+ */
6
+ export function createLoop(app, options, clock = window) {
7
+ const step = options.stepMs ?? 1000 / 60, maxSteps = options.maxSteps ?? 5;
8
+ if (!Number.isFinite(step) || step <= 0 || step > 1000)
9
+ throw Error("stepMs must be above 0 and at most 1000.");
10
+ if (!Number.isInteger(maxSteps) || maxSteps < 1 || maxSteps > 240)
11
+ throw Error("maxSteps must be an integer from 1 to 240.");
12
+ let frame, previous, accumulator = 0, stopped = false;
13
+ const pause = () => {
14
+ if (frame !== undefined)
15
+ clock.cancelAnimationFrame(frame);
16
+ frame = undefined;
17
+ previous = undefined;
18
+ };
19
+ const schedule = () => {
20
+ if (frame === undefined && !stopped && app.lifecycle.current().active)
21
+ frame = clock.requestAnimationFrame(tick);
22
+ };
23
+ const tick = (time) => {
24
+ frame = undefined;
25
+ if (previous !== undefined)
26
+ accumulator += Math.min(Math.max(time - previous, 0), step * maxSteps);
27
+ previous = time;
28
+ while (accumulator >= step) {
29
+ options.update(step);
30
+ accumulator -= step;
31
+ if (stopped)
32
+ return;
33
+ }
34
+ options.render(accumulator / step);
35
+ schedule();
36
+ };
37
+ const unsubscribe = app.lifecycle.onChanged(state => { if (state.active)
38
+ schedule();
39
+ else
40
+ pause(); });
41
+ schedule();
42
+ return {
43
+ get running() { return frame !== undefined; },
44
+ stop() { if (stopped)
45
+ return; stopped = true; pause(); unsubscribe(); },
46
+ };
47
+ }
@@ -1,6 +1,7 @@
1
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
2
  export type GamePermission = typeof GAME_PERMISSIONS[number];
3
- export interface GameManifest {
3
+ /** Schema version 1: Market games and VibeMarket OS apps without a store listing. */
4
+ export interface GameManifestV1 {
4
5
  schemaVersion: 1;
5
6
  sdkVersion: 1;
6
7
  id: string;
@@ -12,6 +13,71 @@ export interface GameManifest {
12
13
  permissions: GamePermission[];
13
14
  collectionId: string | null;
14
15
  }
16
+ /** VibeStore listing categories. */
17
+ export declare const APP_STORE_CATEGORIES: readonly ["game", "tool", "toy"];
18
+ export type AppStoreCategory = typeof APP_STORE_CATEGORIES[number];
19
+ /** Content rating levels for `store.rating.violence` and `store.rating.language`. */
20
+ export declare const APP_CONTENT_RATINGS: readonly ["none", "mild", "strong"];
21
+ export type AppContentRating = typeof APP_CONTENT_RATINGS[number];
22
+ /** Screenshot file extensions a listing may name (lowercase). */
23
+ export declare const APP_SCREENSHOT_EXTENSIONS: readonly ["png", "jpg", "jpeg", "webp"];
24
+ export type AppScreenshotExtension = typeof APP_SCREENSHOT_EXTENSIONS[number];
25
+ /** Window size bounds in CSS pixels, inclusive. */
26
+ export declare const APP_WINDOW_LIMITS: {
27
+ readonly minWidth: 320;
28
+ readonly maxWidth: 1600;
29
+ readonly minHeight: 200;
30
+ readonly maxHeight: 1200;
31
+ };
32
+ /**
33
+ * Listing bounds, inclusive. Description length counts Unicode code points after trimming.
34
+ * The icon and screenshot byte limits are checked on bundle bytes by `checkListing` in `@vibechain/os/listing`.
35
+ */
36
+ export declare const APP_STORE_LIMITS: {
37
+ readonly descriptionMin: 40;
38
+ readonly descriptionMax: 2000;
39
+ readonly supportMax: 200;
40
+ readonly screenshotsMin: 1;
41
+ readonly screenshotsMax: 4;
42
+ readonly iconSize: 256;
43
+ readonly iconBytes: number;
44
+ readonly screenshotBytes: number;
45
+ };
46
+ export interface AppWindow {
47
+ width: number;
48
+ height: number;
49
+ resizable: boolean;
50
+ }
51
+ export interface AppContentRatingSet {
52
+ violence: AppContentRating;
53
+ language: AppContentRating;
54
+ mature: boolean;
55
+ }
56
+ export interface AppStoreListing {
57
+ icon: string;
58
+ screenshots: string[];
59
+ description: string;
60
+ category: AppStoreCategory;
61
+ rating: AppContentRatingSet;
62
+ support: string;
63
+ }
64
+ /** Schema version 2: a VibeMarket OS app with a VibeStore listing. */
65
+ export interface AppManifestV2 {
66
+ schemaVersion: 2;
67
+ sdkVersion: 1;
68
+ id: string;
69
+ version: string;
70
+ name: string;
71
+ tagline: string;
72
+ category: "vibexp-app";
73
+ entry: string;
74
+ permissions: [];
75
+ collectionId: null;
76
+ window: AppWindow;
77
+ store: AppStoreListing;
78
+ }
79
+ /** Every manifest `parseManifest` admits, discriminated on `schemaVersion`. */
80
+ export type GameManifest = GameManifestV1 | AppManifestV2;
15
81
  export declare const GAME_LIMITS: {
16
82
  readonly archive: number;
17
83
  readonly expanded: number;
@@ -21,4 +87,7 @@ export declare const GAME_LIMITS: {
21
87
  readonly games: 40;
22
88
  };
23
89
  export declare function assetPath(value: string): boolean;
90
+ /** An `https://` URL without credentials, or a plausible email address. Exported for forms that validate as the parser does. */
91
+ export declare function supportContact(value: string): boolean;
92
+ /** Accepts schema version 1 exactly as before and schema version 2 with its window and store listing. Unknown fields are rejected at every level. */
24
93
  export declare function parseManifest(input: unknown): GameManifest;
package/dist/manifest.js CHANGED
@@ -1,19 +1,32 @@
1
1
  export const GAME_PERMISSIONS = ["profile.get", "catalog.list", "inventory.get", "packs.buy", "packs.sell", "packs.open", "cards.reveal", "cards.sell", "cards.collect"];
2
+ /** VibeStore listing categories. */
3
+ export const APP_STORE_CATEGORIES = ["game", "tool", "toy"];
4
+ /** Content rating levels for `store.rating.violence` and `store.rating.language`. */
5
+ export const APP_CONTENT_RATINGS = ["none", "mild", "strong"];
6
+ /** Screenshot file extensions a listing may name (lowercase). */
7
+ export const APP_SCREENSHOT_EXTENSIONS = ["png", "jpg", "jpeg", "webp"];
8
+ /** Window size bounds in CSS pixels, inclusive. */
9
+ export const APP_WINDOW_LIMITS = { minWidth: 320, maxWidth: 1600, minHeight: 200, maxHeight: 1200 };
10
+ /**
11
+ * Listing bounds, inclusive. Description length counts Unicode code points after trimming.
12
+ * The icon and screenshot byte limits are checked on bundle bytes by `checkListing` in `@vibechain/os/listing`.
13
+ */
14
+ export const APP_STORE_LIMITS = {
15
+ descriptionMin: 40, descriptionMax: 2000, supportMax: 200, screenshotsMin: 1, screenshotsMax: 4,
16
+ iconSize: 256, iconBytes: 256 * 1024, screenshotBytes: 1024 * 1024,
17
+ };
2
18
  export const GAME_LIMITS = { archive: 20 * 1024 * 1024, expanded: 64 * 1024 * 1024, file: 16 * 1024 * 1024, files: 256, versions: 100, games: 40 };
3
19
  export function assetPath(value) {
4
20
  return value.length > 0 && value.length <= 200 && value.split("/").every(part => /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(part) && !part.endsWith("."));
5
21
  }
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.");
22
+ const V1_FIELDS = ["schemaVersion", "sdkVersion", "id", "version", "name", "tagline", "category", "entry", "permissions", "collectionId"];
23
+ const record = (value) => !!value && typeof value === "object" && !Array.isArray(value);
24
+ const exactFields = (data, fields) => !Object.keys(data).some(key => !fields.includes(key)) && fields.every(key => key in data);
25
+ const extension = (file) => file.slice(file.lastIndexOf(".") + 1);
26
+ /** The rules both schema versions share; field set and version checks stay with the caller. */
27
+ function common(data) {
13
28
  const str = (key, max) => { const value = data[key]; if (typeof value !== "string" || !value.trim() || value !== value.trim() || value.length > max)
14
29
  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
30
  const id = str("id", 60), version = str("version", 50), entry = str("entry", 200);
18
31
  if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(id) || id === "chonk-club")
19
32
  throw Error("Choose a lowercase game slug; chonk-club is reserved for the built-in game.");
@@ -21,6 +34,14 @@ export function parseManifest(input) {
21
34
  throw Error("Version must be semver, for example 1.0.0 or 1.0.0-test.1.");
22
35
  if (!assetPath(entry) || !entry.endsWith(".html"))
23
36
  throw Error("Entry must be a relative .html asset path.");
37
+ return { str, id, version, entry };
38
+ }
39
+ function parseV1(data) {
40
+ if (!exactFields(data, V1_FIELDS))
41
+ throw Error("Manifest fields must match schema version 1 exactly.");
42
+ if (data.schemaVersion !== 1 || data.sdkVersion !== 1)
43
+ throw Error("Only manifest and SDK version 1 are supported.");
44
+ const { str, id, version, entry } = common(data);
24
45
  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
46
  throw Error("Permissions must be a unique list of supported SDK methods.");
26
47
  const permissions = data.permissions;
@@ -30,3 +51,90 @@ export function parseManifest(input) {
30
51
  throw Error("Trading permissions require a collectionId.");
31
52
  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
53
  }
54
+ function parseWindow(input) {
55
+ if (!record(input) || !exactFields(input, ["width", "height", "resizable"]))
56
+ throw Error("window must be an object with exactly width, height and resizable.");
57
+ const { width, height, resizable } = input, limits = APP_WINDOW_LIMITS;
58
+ if (!Number.isInteger(width) || width < limits.minWidth || width > limits.maxWidth)
59
+ throw Error(`window.width must be an integer from ${limits.minWidth} to ${limits.maxWidth}.`);
60
+ if (!Number.isInteger(height) || height < limits.minHeight || height > limits.maxHeight)
61
+ throw Error(`window.height must be an integer from ${limits.minHeight} to ${limits.maxHeight}.`);
62
+ if (typeof resizable !== "boolean")
63
+ throw Error("window.resizable must be true or false.");
64
+ return { width: width, height: height, resizable };
65
+ }
66
+ // Controls other than newline: C0 (tab and carriage return included), DEL and C1.
67
+ const CONTROL = /[\u0000-\u0009\u000B-\u001F\u007F-\u009F]/;
68
+ const EMAIL = /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*\.[A-Za-z]{2,63}$/;
69
+ /** An `https://` URL without credentials, or a plausible email address. Exported for forms that validate as the parser does. */
70
+ export function supportContact(value) {
71
+ if (value.length > APP_STORE_LIMITS.supportMax || value !== value.trim() || /\s/.test(value) || CONTROL.test(value))
72
+ return false;
73
+ if (!value.startsWith("https://"))
74
+ return EMAIL.test(value);
75
+ let url;
76
+ try {
77
+ url = new URL(value);
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ return url.protocol === "https:" && !url.username && !url.password && /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]+)$/.test(url.hostname);
83
+ }
84
+ function parseStore(input) {
85
+ if (!record(input) || !exactFields(input, ["icon", "screenshots", "description", "category", "rating", "support"]))
86
+ throw Error("store must be an object with exactly icon, screenshots, description, category, rating and support.");
87
+ const limits = APP_STORE_LIMITS, { icon, screenshots, description, category, rating, support } = input;
88
+ if (typeof icon !== "string" || !assetPath(icon) || !icon.endsWith(".png"))
89
+ throw Error("store.icon must be a relative asset path ending in .png.");
90
+ if (!Array.isArray(screenshots) || screenshots.length < limits.screenshotsMin || screenshots.length > limits.screenshotsMax)
91
+ throw Error(`store.screenshots must list ${limits.screenshotsMin} to ${limits.screenshotsMax} images.`);
92
+ const shots = screenshots, paths = [], seen = new Set([icon.toLowerCase()]);
93
+ for (const shot of shots) {
94
+ if (typeof shot !== "string" || !assetPath(shot) || !APP_SCREENSHOT_EXTENSIONS.includes(extension(shot)))
95
+ throw Error("Each store screenshot must be a relative asset path ending in .png, .jpg, .jpeg or .webp.");
96
+ if (seen.has(shot.toLowerCase()))
97
+ throw Error("store.screenshots must be distinct files, none of them the icon.");
98
+ seen.add(shot.toLowerCase());
99
+ paths.push(shot);
100
+ }
101
+ if (typeof description !== "string" || CONTROL.test(description))
102
+ throw Error("store.description must be plain text; newlines are the only control characters allowed.");
103
+ const text = description.trim(), length = [...text].length;
104
+ if (length < limits.descriptionMin || length > limits.descriptionMax)
105
+ throw Error(`store.description must be ${limits.descriptionMin} to ${limits.descriptionMax} characters.`);
106
+ if (typeof category !== "string" || !APP_STORE_CATEGORIES.includes(category))
107
+ throw Error(`store.category must be one of ${APP_STORE_CATEGORIES.join(", ")}.`);
108
+ if (!record(rating) || !exactFields(rating, ["violence", "language", "mature"]))
109
+ throw Error("store.rating must be an object with exactly violence, language and mature.");
110
+ const levels = APP_CONTENT_RATINGS;
111
+ if (typeof rating.violence !== "string" || !levels.includes(rating.violence) || typeof rating.language !== "string" || !levels.includes(rating.language))
112
+ throw Error(`store.rating.violence and store.rating.language must each be one of ${APP_CONTENT_RATINGS.join(", ")}.`);
113
+ if (typeof rating.mature !== "boolean")
114
+ throw Error("store.rating.mature must be true or false.");
115
+ if (typeof support !== "string" || !supportContact(support))
116
+ throw Error(`store.support must be an https:// URL or an email address of at most ${limits.supportMax} characters.`);
117
+ return {
118
+ icon, screenshots: paths, description: text, category: category,
119
+ rating: { violence: rating.violence, language: rating.language, mature: rating.mature }, support,
120
+ };
121
+ }
122
+ function parseV2(data) {
123
+ if (!exactFields(data, [...V1_FIELDS, "window", "store"]))
124
+ throw Error("Manifest fields must match schema version 2 exactly.");
125
+ if (data.sdkVersion !== 1)
126
+ throw Error("Only SDK version 1 is supported.");
127
+ const { str, id, version, entry } = common(data);
128
+ if (data.category !== "vibexp-app" || !Array.isArray(data.permissions) || data.permissions.length || data.collectionId !== null)
129
+ throw Error("Schema version 2 apps must declare category vibexp-app, permissions [] and collectionId null.");
130
+ return {
131
+ schemaVersion: 2, sdkVersion: 1, id, version, name: str("name", 60), tagline: str("tagline", 160), category: "vibexp-app", entry,
132
+ permissions: [], collectionId: null, window: parseWindow(data.window), store: parseStore(data.store),
133
+ };
134
+ }
135
+ /** Accepts schema version 1 exactly as before and schema version 2 with its window and store listing. Unknown fields are rejected at every level. */
136
+ export function parseManifest(input) {
137
+ if (!record(input))
138
+ throw Error("vibemarket.json must be an object.");
139
+ return input.schemaVersion === 2 ? parseV2(input) : parseV1(input);
140
+ }
@@ -1 +1 @@
1
- var S="vibemarket.game.v1";function O(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(t=>t 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}function J(e){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw Error("Invalid game completion.");let t=Object.getOwnPropertyDescriptor(e,"score");if(Reflect.ownKeys(e).length!==1||!t||!("value"in t)||!t.enumerable||typeof t.value!="number"||!Number.isInteger(t.value)||t.value<0||t.value>1e9)throw Error("Score must be an integer from 0 to 1,000,000,000.");return Object.freeze({score:t.value})}var P="vibexp";var l=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4});function j(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function T(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function B(e,t){let n=JSON.stringify(e);if(typeof n!="string"||n.length>t||new TextEncoder().encode(n).length>t)throw Error("App message exceeds limit.");return n}function V(e,t){if(typeof e!="string"||e.length>t||new TextEncoder().encode(e).length>t)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),I=(e,t)=>{let n=Object.keys(e);return n.length===t.length&&Reflect.ownKeys(e).length===n.length&&n.every(i=>t.includes(i)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,i)??{},"value"))};function G(e){let t=0,n=0,i=(o,m)=>{if(++t>l.checkpointNodes||m>l.checkpointDepth)throw Error("App checkpoint is too complex.");if(o===null||typeof o=="boolean")return;if(typeof o=="number"){if(!Number.isFinite(o))throw Error("Checkpoint numbers must be finite.");return}if(typeof o=="string"){if(o.length>l.stringBytes)throw Error("App checkpoint string is too large.");let s=new TextEncoder().encode(o).byteLength;if(s>l.stringBytes||(n+=s)>l.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(o)){if(o.length>l.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(o).length!==o.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let s=0;s<o.length;s++){let p=Object.getOwnPropertyDescriptor(o,s);if(!p||!("value"in p))throw Error("Sparse/accessor checkpoints are unsupported.");i(p.value,m+1)}return}if(!M(o))throw Error("App checkpoint must contain only JSON values.");let u=Object.keys(o);if(Reflect.ownKeys(o).length!==u.length)throw Error("Checkpoint properties must be enumerable strings.");if(u.length>l.objectKeys)throw Error("App checkpoint has too many keys.");for(let s of u){if(["__proto__","constructor","prototype"].includes(s)||s.length>128)throw Error("Invalid app checkpoint key.");if(n+=new TextEncoder().encode(s).byteLength,n>l.checkpointBytes)throw Error("App checkpoint keys are too large.");let p=Object.getOwnPropertyDescriptor(o,s);if(!p||!("value"in p))throw Error("App checkpoint accessors are unsupported.");i(p.value,m+1)}};i(e,0);let d=JSON.stringify(e);if(new TextEncoder().encode(d).byteLength>l.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return d}function $(e){return JSON.parse(G(e))}function D(e,t){if(!M(e)||!I(e,["id","session","request"])||e.session!==t||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 n=e.request;if(n.method==="game.finish"&&I(n,["method","score"]))return{id:e.id,request:{method:"game.finish",...J({score:n.score})}};if((n.method==="ui.ready"||n.method==="app.checkpoint.get")&&I(n,["method"]))return{id:e.id,request:{method:n.method}};if(n.method==="app.checkpoint.set"&&I(n,["method","value"]))return{id:e.id,request:{method:n.method,value:$(n.value)}};throw Error("This app has no permission for that method.")}function _(e){if(!M(e)||!I(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 t="null",n=!1,i,d,o=!1,m=e();if(!Number.isFinite(m))throw Error("App clock is invalid.");let u=m,s=m,p=0,c=0,g,y,f=r=>{if(n||g)return;g=r,clearTimeout(h),t="null";let w=y;i?.close(),w?.(r)},h=setTimeout(()=>f("App session expired. Reopen the app."),l.sessionMs),a=()=>{let r;try{r=e()}catch{f("App clock changed. Reopen the app.");return}if(!Number.isFinite(r)||r<u){f("App clock changed. Reopen the app.");return}if(u=r,r-m>=l.sessionMs){f("App session expired. Reopen the app.");return}return r};return{attach(r,w,b){if(n||g||!j(w))throw r.close(),Error(g??"App controller is closed.");if(a()===void 0)throw r.close(),Error(g);i?.close();let A=!1,N=0,z=new Set,C=()=>{A||(A=!0,r.onmessage=null,r.onmessageerror=null,r.close(),i===F&&(i=void 0,y=void 0))},k=x=>{A||(C(),b.fault(x))},E=()=>!A&&!n&&b.current(),F={lifecycle(x){E()&&r.postMessage(B({session:w,event:"app.lifecycle",state:_(x)},l.responseBytes))},close:C};return i=F,y=b.fault,r.onmessage=x=>{if(!E()){C();return}let q=a();if(q===void 0)return;if(q-s>=1e3&&(s=q,p=0),++p>l.requestsPerSecond||++c>l.lifetimeRequests||N>=l.inFlight){k("App request limit exceeded.");return}let v;try{v=D(V(x.data,l.requestBytes),w)}catch{k("Invalid or unpermitted app request.");return}if(z.has(v.id)){k("App request was replayed.");return}z.add(v.id),N++,Promise.resolve().then(()=>{if(!E())return;let R;switch(v.request.method){case"ui.ready":b.ready(),R={completed:!0};break;case"game.finish":if(d&&d.score!==v.request.score)throw Error("This game has already finished.");d??=Object.freeze({score:v.request.score}),R={completed:!0};break;case"app.checkpoint.get":R={checkpoint:JSON.parse(t)};break;case"app.checkpoint.set":t=G(v.request.value),R={completed:!0};break}let K={session:w,id:v.id,result:R};E()&&(r.postMessage(B(K,l.responseBytes)),v.request.method==="game.finish"&&d&&!o&&E()&&(o=!0,b.finish?.(d)))}).catch(()=>{A||k("App request could not complete.")}).finally(()=>{N--})},r.onmessageerror=()=>k("App message could not be decoded."),r.start(),F},suspend(){i?.close()},dispose(){n||(n=!0,clearTimeout(h),i?.close(),t="null")}}}function H(e,t){let n=O(window);if(n)throw Error(n);if(!j(t.challenge)||new URL(e.src).hash!==`#${P}=${t.challenge}`)throw Error("Invalid app frame challenge.");let i=!1,d=!1,o=!1,m=0,u,s=_({active:!0,width:0,height:0}),p=()=>{i||(i=!0,clearTimeout(f),e.removeEventListener("load",g),window.removeEventListener("message",y),u?.close())},c=h=>{i||(p(),t.fault(h))},g=()=>{d?c("App navigation ended this session."):d=!0},y=h=>{if(i||o||!t.current()||h.source!==e.contentWindow)return;if(++m>32){c("App connection limit exceeded.");return}if(!d||h.origin!=="null")return;let a;try{a=V(h.data,256)}catch{c("Invalid app connection message.");return}if(!a||typeof a!="object"||Array.isArray(a)||!("channel"in a)||a.channel!==S||!("type"in a)||a.type!=="connect"||!("challenge"in a)||a.challenge!==t.challenge||Object.keys(a).length!==3)return;o=!0,window.removeEventListener("message",y);let r=new MessageChannel,w=T();try{if(u=t.controller.attach(r.port1,w,{current:t.current,ready(){clearTimeout(f),t.ready()},finish:t.finish,fault:c}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:S,challenge:t.challenge,session:w},"*",[r.port2]),u.lifecycle(s)}catch{r.port1.close(),r.port2.close(),c("App connection could not complete.")}},f=setTimeout(()=>c("App took too long to become ready."),15e3);return e.addEventListener("load",g),window.addEventListener("message",y),{resize(h,a){s=_({active:!0,width:Math.min(4096,Math.max(0,Math.floor(h))),height:Math.min(4096,Math.max(0,Math.floor(a)))}),u?.lifecycle(s)},dispose:p}}async function U(){let e=O(window);if(e)throw Error(e);let t=document.getElementById("surface"),n=document.getElementById("status"),i=document.getElementById("toggle"),d=document.getElementById("reset"),o=document.getElementById("result"),m=document.getElementById("score");if(!t||!n||!o||!m||!(i instanceof HTMLButtonElement)||!(d instanceof HTMLButtonElement))throw Error("Preview controls are missing.");let u=await(await fetch("/preview.json",{credentials:"omit"})).json();if(!u||typeof u!="object"||!("runtime"in u)||typeof u.runtime!="string")throw Error("Invalid preview metadata.");let s=new URL(u.runtime);if(s.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(s.pathname)||s.search||s.hash)throw Error("Invalid preview runtime.");let p=L(),c=null,g=null,y=null,f=!1,h=null,a=()=>{g?.dispose(),g=null,p.suspend(),y?.disconnect(),y=null,c?.remove(),c=null},r=()=>{if(a(),t.hidden=f||document.hidden||h!==null,o.hidden=!0,f||document.hidden){n.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(h){o.hidden=!1,m.textContent=String(h.score),n.textContent="Round complete. No Cash reward for this preview.";return}let w=T(),b=new URL(s);b.hash=`${P}=${w}`,c=document.createElement("iframe"),c.title="VibeMarket OS app",c.sandbox.add("allow-scripts"),c.referrerPolicy="no-referrer",c.src=b.href,t.appendChild(c),g=H(c,{controller:p,challenge:w,current:()=>!f&&!document.hidden,ready:()=>{n.textContent="App ready \xB7 Minimize and restore to check its saved work."},finish:A=>{h=A,d.textContent="Play again",r()},fault:A=>{a(),p.dispose(),p=L(),n.textContent=A}}),y=new ResizeObserver(()=>{c&&g?.resize(c.clientWidth,c.clientHeight)}),y.observe(c),n.textContent="Loading the isolated app\u2026"};i.onclick=()=>{f=!f,i.textContent=f?"Restore":"Minimize",r()},d.onclick=()=>{a(),p.dispose(),p=L(),h=null,f=!1,i.textContent="Minimize",d.textContent="Close / reset",r()},document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",()=>{a(),p.dispose(),document.removeEventListener("visibilitychange",r)},{once:!0}),r()}typeof window<"u"&&typeof document<"u"&&U().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{U as startPreviewParent};
1
+ var q="vibemarket.game.v1";var U=["127.0.0.1","localhost"],$=["vibechain.com","www.vibechain.com"];function W({protocol:e,hostname:t,port:n}){return e==="http:"?U.includes(t):e==="https:"&&$.includes(t)&&n===""}function O(e){return W(e.location)?e.top!==e.self?"Third-party apps require a top-level browser host.":["__VM_STEAM__","__TAURI_INTERNALS__","__TAURI__","vibeNative","ReactNativeWebView"].some(t=>t 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:"Third-party apps are available only on vibechain.com and in the local browser developer preview."}function J(e){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw Error("Invalid game completion.");let t=Object.getOwnPropertyDescriptor(e,"score");if(Reflect.ownKeys(e).length!==1||!t||!("value"in t)||!t.enumerable||typeof t.value!="number"||!Number.isInteger(t.value)||t.value<0||t.value>1e9)throw Error("Score must be an integer from 0 to 1,000,000,000.");return Object.freeze({score:t.value})}var P="vibexp";var l=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4});function j(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function M(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function B(e,t){let n=JSON.stringify(e);if(typeof n!="string"||n.length>t||new TextEncoder().encode(n).length>t)throw Error("App message exceeds limit.");return n}function V(e,t){if(typeof e!="string"||e.length>t||new TextEncoder().encode(e).length>t)throw Error("Invalid app message size or encoding.");return JSON.parse(e)}var T=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),I=(e,t)=>{let n=Object.keys(e);return n.length===t.length&&Reflect.ownKeys(e).length===n.length&&n.every(i=>t.includes(i)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,i)??{},"value"))};function G(e){let t=0,n=0,i=(o,m)=>{if(++t>l.checkpointNodes||m>l.checkpointDepth)throw Error("App checkpoint is too complex.");if(o===null||typeof o=="boolean")return;if(typeof o=="number"){if(!Number.isFinite(o))throw Error("Checkpoint numbers must be finite.");return}if(typeof o=="string"){if(o.length>l.stringBytes)throw Error("App checkpoint string is too large.");let s=new TextEncoder().encode(o).byteLength;if(s>l.stringBytes||(n+=s)>l.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(o)){if(o.length>l.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(o).length!==o.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let s=0;s<o.length;s++){let a=Object.getOwnPropertyDescriptor(o,s);if(!a||!("value"in a))throw Error("Sparse/accessor checkpoints are unsupported.");i(a.value,m+1)}return}if(!T(o))throw Error("App checkpoint must contain only JSON values.");let u=Object.keys(o);if(Reflect.ownKeys(o).length!==u.length)throw Error("Checkpoint properties must be enumerable strings.");if(u.length>l.objectKeys)throw Error("App checkpoint has too many keys.");for(let s of u){if(["__proto__","constructor","prototype"].includes(s)||s.length>128)throw Error("Invalid app checkpoint key.");if(n+=new TextEncoder().encode(s).byteLength,n>l.checkpointBytes)throw Error("App checkpoint keys are too large.");let a=Object.getOwnPropertyDescriptor(o,s);if(!a||!("value"in a))throw Error("App checkpoint accessors are unsupported.");i(a.value,m+1)}};i(e,0);let d=JSON.stringify(e);if(new TextEncoder().encode(d).byteLength>l.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return d}function Y(e){return JSON.parse(G(e))}function H(e,t){if(!T(e)||!I(e,["id","session","request"])||e.session!==t||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!T(e.request))throw Error("Invalid app session request.");let n=e.request;if(n.method==="game.finish"&&I(n,["method","score"]))return{id:e.id,request:{method:"game.finish",...J({score:n.score})}};if((n.method==="ui.ready"||n.method==="app.checkpoint.get")&&I(n,["method"]))return{id:e.id,request:{method:n.method}};if(n.method==="app.checkpoint.set"&&I(n,["method","value"]))return{id:e.id,request:{method:n.method,value:Y(n.value)}};throw Error("This app has no permission for that method.")}function _(e){if(!T(e)||!I(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 t="null",n=!1,i,d,o=!1,m=e();if(!Number.isFinite(m))throw Error("App clock is invalid.");let u=m,s=m,a=0,c=0,g,y,f=r=>{if(n||g)return;g=r,clearTimeout(h),t="null";let w=y;i?.close(),w?.(r)},h=setTimeout(()=>f("App session expired. Reopen the app."),l.sessionMs),p=()=>{let r;try{r=e()}catch{f("App clock changed. Reopen the app.");return}if(!Number.isFinite(r)||r<u){f("App clock changed. Reopen the app.");return}if(u=r,r-m>=l.sessionMs){f("App session expired. Reopen the app.");return}return r};return{attach(r,w,b){if(n||g||!j(w))throw r.close(),Error(g??"App controller is closed.");if(p()===void 0)throw r.close(),Error(g);i?.close();let A=!1,C=0,z=new Set,N=()=>{A||(A=!0,r.onmessage=null,r.onmessageerror=null,r.close(),i===S&&(i=void 0,y=void 0))},k=x=>{A||(N(),b.fault(x))},E=()=>!A&&!n&&b.current(),S={lifecycle(x){E()&&r.postMessage(B({session:w,event:"app.lifecycle",state:_(x)},l.responseBytes))},close:N};return i=S,y=b.fault,r.onmessage=x=>{if(!E()){N();return}let F=p();if(F===void 0)return;if(F-s>=1e3&&(s=F,a=0),++a>l.requestsPerSecond||++c>l.lifetimeRequests||C>=l.inFlight){k("App request limit exceeded.");return}let v;try{v=H(V(x.data,l.requestBytes),w)}catch{k("Invalid or unpermitted app request.");return}if(z.has(v.id)){k("App request was replayed.");return}z.add(v.id),C++,Promise.resolve().then(()=>{if(!E())return;let R;switch(v.request.method){case"ui.ready":b.ready(),R={completed:!0};break;case"game.finish":if(d&&d.score!==v.request.score)throw Error("This game has already finished.");d??=Object.freeze({score:v.request.score}),R={completed:!0};break;case"app.checkpoint.get":R={checkpoint:JSON.parse(t)};break;case"app.checkpoint.set":t=G(v.request.value),R={completed:!0};break}let K={session:w,id:v.id,result:R};E()&&(r.postMessage(B(K,l.responseBytes)),v.request.method==="game.finish"&&d&&!o&&E()&&(o=!0,b.finish?.(d)))}).catch(()=>{A||k("App request could not complete.")}).finally(()=>{C--})},r.onmessageerror=()=>k("App message could not be decoded."),r.start(),S},suspend(){i?.close()},dispose(){n||(n=!0,clearTimeout(h),i?.close(),t="null")}}}function D(e,t){let n=O(window);if(n)throw Error(n);if(!j(t.challenge)||new URL(e.src).hash!==`#${P}=${t.challenge}`)throw Error("Invalid app frame challenge.");let i=!1,d=!1,o=!1,m=0,u,s=_({active:!0,width:0,height:0}),a=()=>{i||(i=!0,clearTimeout(f),e.removeEventListener("load",g),window.removeEventListener("message",y),u?.close())},c=h=>{i||(a(),t.fault(h))},g=()=>{d?c("App navigation ended this session."):d=!0},y=h=>{if(i||o||!t.current()||h.source!==e.contentWindow)return;if(++m>32){c("App connection limit exceeded.");return}if(!d||h.origin!=="null")return;let p;try{p=V(h.data,256)}catch{c("Invalid app connection message.");return}if(!p||typeof p!="object"||Array.isArray(p)||!("channel"in p)||p.channel!==q||!("type"in p)||p.type!=="connect"||!("challenge"in p)||p.challenge!==t.challenge||Object.keys(p).length!==3)return;o=!0,window.removeEventListener("message",y);let r=new MessageChannel,w=M();try{if(u=t.controller.attach(r.port1,w,{current:t.current,ready(){clearTimeout(f),t.ready()},finish:t.finish,fault:c}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:q,challenge:t.challenge,session:w},"*",[r.port2]),u.lifecycle(s)}catch{r.port1.close(),r.port2.close(),c("App connection could not complete.")}},f=setTimeout(()=>c("App took too long to become ready."),15e3);return e.addEventListener("load",g),window.addEventListener("message",y),{resize(h,p){s=_({active:!0,width:Math.min(4096,Math.max(0,Math.floor(h))),height:Math.min(4096,Math.max(0,Math.floor(p)))}),u?.lifecycle(s)},dispose:a}}async function Z(){let e=O(window);if(e)throw Error(e);let t=document.getElementById("surface"),n=document.getElementById("status"),i=document.getElementById("toggle"),d=document.getElementById("reset"),o=document.getElementById("result"),m=document.getElementById("score");if(!t||!n||!o||!m||!(i instanceof HTMLButtonElement)||!(d instanceof HTMLButtonElement))throw Error("Preview controls are missing.");let u=await(await fetch("/preview.json",{credentials:"omit"})).json();if(!u||typeof u!="object"||!("runtime"in u)||typeof u.runtime!="string")throw Error("Invalid preview metadata.");let s=new URL(u.runtime);if(s.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(s.pathname)||s.search||s.hash)throw Error("Invalid preview runtime.");let a=L(),c=null,g=null,y=null,f=!1,h=null,p=()=>{g?.dispose(),g=null,a.suspend(),y?.disconnect(),y=null,c?.remove(),c=null},r=()=>{if(p(),t.hidden=f||document.hidden||h!==null,o.hidden=!0,f||document.hidden){n.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(h){o.hidden=!1,m.textContent=String(h.score),n.textContent="Round complete. No Cash reward for this preview.";return}let w=M(),b=new URL(s);b.hash=`${P}=${w}`,c=document.createElement("iframe"),c.title="VibeMarket OS app",c.sandbox.add("allow-scripts"),c.referrerPolicy="no-referrer",c.src=b.href,t.appendChild(c),g=D(c,{controller:a,challenge:w,current:()=>!f&&!document.hidden,ready:()=>{n.textContent="App ready \xB7 Minimize and restore to check its saved work."},finish:A=>{h=A,d.textContent="Play again",r()},fault:A=>{p(),a.dispose(),a=L(),n.textContent=A}}),y=new ResizeObserver(()=>{c&&g?.resize(c.clientWidth,c.clientHeight)}),y.observe(c),n.textContent="Loading the isolated app\u2026"};i.onclick=()=>{f=!f,i.textContent=f?"Restore":"Minimize",r()},d.onclick=()=>{p(),a.dispose(),a=L(),h=null,f=!1,i.textContent="Minimize",d.textContent="Close / reset",r()},document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",()=>{p(),a.dispose(),document.removeEventListener("visibilitychange",r)},{once:!0}),r()}typeof window<"u"&&typeof document<"u"&&Z().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{Z as startPreviewParent};
package/dist/scaffold.js CHANGED
@@ -20,6 +20,10 @@ export async function createApp(directory, sdkTarball) {
20
20
  throw Error("Installed SDK package metadata is invalid.");
21
21
  dependency = input.version;
22
22
  }
23
+ const template = fileURLToPath(new URL("../examples/vibexp-app/", import.meta.url));
24
+ // The starter's own manifest names its store images, so the copy list follows the listing.
25
+ const starter = parseManifest(JSON.parse(new TextDecoder().decode(await readBoundedAsset(path.join(template, "vibemarket.json"), 16 * 1024))));
26
+ const files = ["index.html", "vibemarket.json", "README.md", "src/main.ts", ...(starter.schemaVersion === 2 ? [starter.store.icon, ...starter.store.screenshots] : [])];
23
27
  const requested = path.resolve(directory);
24
28
  await mkdir(requested, { recursive: true });
25
29
  if ((await lstat(requested)).isSymbolicLink())
@@ -27,10 +31,12 @@ export async function createApp(directory, sdkTarball) {
27
31
  const target = await realpath(requested);
28
32
  if ((await readdir(target)).length)
29
33
  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
+ for (const file of files) {
35
+ const destination = path.join(target, file);
36
+ if (path.dirname(destination) !== target)
37
+ await mkdir(path.dirname(destination), { recursive: true });
38
+ await copyFile(path.join(template, file), destination);
39
+ }
34
40
  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
41
  await writeFile(path.join(target, "package.json"), JSON.stringify({
36
42
  name: "my-vibemarket-app", version: "0.1.0", private: true, type: "module",
@@ -45,12 +51,19 @@ export async function createApp(directory, sdkTarball) {
45
51
  }
46
52
  export async function stageAppAssets(root) {
47
53
  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))));
54
+ const manifest = parseManifest(JSON.parse(new TextDecoder().decode(await readBoundedAsset(path.join(directory, "vibemarket.json"), 16 * 1024))));
49
55
  await mkdir(output, { recursive: true });
50
56
  if (await realpath(output) !== output)
51
57
  throw Error("App output cannot be a symlink.");
52
- for (const name of ["index.html", "vibemarket.json"]) {
53
- const destination = path.join(output, name);
58
+ // A schema version 2 listing also needs its store images next to the built app.
59
+ const names = ["index.html", "vibemarket.json", ...(manifest.schemaVersion === 2 ? [manifest.store.icon, ...manifest.store.screenshots] : [])];
60
+ for (const name of names) {
61
+ const destination = path.join(output, name), parent = path.dirname(destination);
62
+ if (parent !== output) {
63
+ await mkdir(parent, { recursive: true });
64
+ if (await realpath(parent) !== parent)
65
+ throw Error("App output cannot be a symlink.");
66
+ }
54
67
  try {
55
68
  if ((await lstat(destination)).isSymbolicLink())
56
69
  throw Error("App output cannot contain symlinked files.");
@@ -0,0 +1,29 @@
1
+ import { type AppLifecycle, type AppValue, type VibeMarketAppSdk } from "./app-protocol.ts";
2
+ import { type GameFinishInput } from "./completion.ts";
3
+ export interface FakeAppOptions {
4
+ /** What `checkpoint.read()` returns first. Default: `null`, as on a first open. */
5
+ checkpoint?: AppValue;
6
+ /** Starting lifecycle. Default: active, 800 x 600. */
7
+ lifecycle?: Partial<AppLifecycle>;
8
+ }
9
+ export interface FakeApp {
10
+ /** Pass this wherever your game expects the result of `connectVibeMarketApp()`. */
11
+ readonly app: VibeMarketAppSdk;
12
+ /** Change the lifecycle as the host would (minimize, restore, resize) and notify listeners. */
13
+ setLifecycle(next: Partial<AppLifecycle>): void;
14
+ /** True once the game called `ready()`. */
15
+ readonly ready: boolean;
16
+ /** The score the game finished with, or null. */
17
+ readonly finished: Readonly<GameFinishInput> | null;
18
+ /** The last checkpoint the fake host accepted. */
19
+ readonly checkpoint: AppValue;
20
+ /** True once the game called `destroy()`. */
21
+ readonly destroyed: boolean;
22
+ }
23
+ /**
24
+ * An in-memory stand-in for the VibeMarket OS host, for unit tests. It applies the same
25
+ * checkpoint, score and lifecycle validation as the real host and the same single-shot
26
+ * completion rule, but has no window, no port, no time limit and no request budget.
27
+ * Passing here does not replace a run in the preview.
28
+ */
29
+ export declare function createFakeApp(options?: FakeAppOptions): FakeApp;