@vibechain/os 0.1.0 → 0.2.0

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 CHANGED
@@ -4,7 +4,7 @@
4
4
  [SECURITY.md](SECURITY.md), the `os init` starter and
5
5
  `connectVibeMarketApp()`. Use category `vibexp-app`, `permissions: []` and
6
6
  `collectionId: null`. That browser-only app facade has readiness, lifecycle and
7
- bounded app-owned checkpoints; it has no profile, inventory, Steam/native,
7
+ bounded app-owned checkpoints and a score-only `game.finish({score})` signal; it has no profile, inventory, Steam/native,
8
8
  wallet, purchase or reward authority. The existing Market-game contract below
9
9
  continues to apply to collection games using `connectGameSdk()`; do not infer
10
10
  those permissions for an OS app. Public app publication remains disabled.
@@ -20,7 +20,7 @@ scripts, fonts, APIs, workers or wallet libraries. Bundle your dependencies/asse
20
20
  Install the published package in an independent game project:
21
21
 
22
22
  ```sh
23
- npm install @vibechain/os@0.1.0
23
+ npm install @vibechain/os@0.2.0
24
24
  ```
25
25
 
26
26
  To use a reviewed local SDK tarball instead, build it in the host checkout:
@@ -30,13 +30,13 @@ cd vibemarket/packages/os
30
30
  yarn install --frozen-lockfile
31
31
  yarn review
32
32
  yarn build
33
- yarn pack --filename /tmp/vibechain-os-0.1.0.tgz
33
+ yarn pack --filename /tmp/vibechain-os-0.2.0.tgz
34
34
  ```
35
35
 
36
36
  In an independent game project, install that tarball:
37
37
 
38
38
  ```sh
39
- npm install /tmp/vibechain-os-0.1.0.tgz
39
+ npm install /tmp/vibechain-os-0.2.0.tgz
40
40
  npm install --save-dev typescript esbuild
41
41
  ```
42
42
 
@@ -50,6 +50,8 @@ strict TypeScript. Do not import VibeMarket host files or depend on a repo alias
50
50
  import { connectGameSdk } from '@vibechain/os';
51
51
  const sdk = await connectGameSdk();
52
52
  await sdk.ready(); // Call when the first usable frame is mounted, within 30 seconds.
53
+ // At the end of a round: await sdk.game.finish({ score: 42 });
54
+ // Report only the integer score; the host owns results and any verified reward.
53
55
  const profile = await sdk.profile.get(); // null for guests; no wallet address
54
56
  const packs = await sdk.catalog.list(); // only this game's approved collection
55
57
  const inventory = await sdk.inventory.get(); // pages of <=100 cards
@@ -80,7 +82,7 @@ Scores are session-only; cosmetics never alter timing, speed, or rewards.
80
82
 
81
83
  `profile.get`, `catalog.list`, `inventory.get`, `packs.buy`, `packs.sell`,
82
84
  `packs.open`, `cards.reveal`, `cards.sell` and `cards.collect` each require an
83
- explicit manifest permission. `ready()` and `showShop()` are always available.
85
+ explicit manifest permission. `ready()`, `showShop()` and the score-only `game.finish()` signal are always available; they grant no reward or transaction authority.
84
86
  The SDK has no provider, arbitrary signing, chain RPC, wallet/session object,
85
87
  private key, balances, recipient override or transaction calldata escape hatch.
86
88
  `playerId` is session-local, not a durable account ID. Guest inventories are empty.
package/README.md CHANGED
@@ -1,23 +1,23 @@
1
1
  # @vibechain/os
2
2
 
3
- Build a VibeMarket OS app with TypeScript, without cloning the monorepo or obtaining company secrets. The existing Market game client and development publisher remain compatible. **The OS app host is browser-only development software; production third-party app publishing remains disabled.** Installing this package does not grant a listing, native access or economic authority.
3
+ Build games, tools and desktop apps for VibeMarket OS with TypeScript. Start with a working app, preview it in a desktop window and save progress with checkpoints.
4
4
 
5
- ## Make an app without the monorepo
5
+ ## Quickstart
6
6
 
7
7
  ```sh
8
- npx --yes @vibechain/os@0.1.0 init my-app
8
+ npx --yes @vibechain/os@0.2.0 init my-app
9
9
  cd my-app
10
10
  npm install
11
11
  npm run build
12
12
  npm run dev
13
13
  ```
14
14
 
15
- Open the printed `http://127.0.0.1:PORT` address. Stamp Club is a complete starter: add stamps, minimize and restore, then close/reset. Host-accepted state survives suspension in the same open window. Reset clears it. Rebuild and restart the immutable preview after changes. `npm run pack` creates `app.zip` for the existing **development** publisher.
15
+ Open the printed `http://127.0.0.1:PORT` address. Stamp Club is a complete starter: start a round, add stamps, minimize and restore, then finish to see the host's result screen. Play again starts a fresh round. Host-accepted state survives suspension in the same open window. Reset clears it. Rebuild and restart the immutable preview after changes. `npm run pack` creates `app.zip` for the existing **development** publisher.
16
16
 
17
- The starter pins the installed SDK version and installs its own TypeScript and esbuild. It has no monorepo aliases or credentials. To use a reviewed archive instead of the registry, supply its real absolute path both to npm and the initializer:
17
+ The starter includes TypeScript and esbuild and pins your SDK version. To install from a downloaded SDK archive, supply its absolute path to npm and the initializer:
18
18
 
19
19
  ```sh
20
- npm exec --yes --package=/absolute/path/vibechain-os-0.1.0.tgz -- os init my-app /absolute/path/vibechain-os-0.1.0.tgz
20
+ npm exec --yes --package=/absolute/path/vibechain-os-0.2.0.tgz -- os init my-app /absolute/path/vibechain-os-0.2.0.tgz
21
21
  ```
22
22
 
23
23
  That explicit fallback keeps a `file:` archive dependency; retain the archive for later reinstalls. Use a supported Node.js release: `^22.23.4`, `^24.22.1` or `^26.12.1`.
@@ -41,7 +41,27 @@ window.addEventListener("pagehide", () => app.destroy(), { once: true });
41
41
 
42
42
  Checkpoint is a base app capability, separate from Market permissions. It accepts only the same app's bounded JSON: ≤32 KiB UTF-8, depth8, ≤2,048 nodes, ≤64 keys/object, ≤256 items/array and ≤8KiB/string. State lives in trusted host memory, scoped to the open installation/version/identity/window; it is cleared on close, revoke, package/identity change or the controller's absolute 15-minute expiry. Suspension does not extend that lifetime. There is no arbitrary namespace, disk storage, account data or browser-restart guarantee. `write()` resolves after acknowledgement; an accepted snapshot can be restored even if that acknowledgement was interrupted.
43
43
 
44
- Manifest: use schema/sdkVersion1, `permissions: []` and `collectionId: null`. App methods are deliberately limited to readiness and checkpoint reads/writes. Raw requests for profile, inventory, rewards, purchases, Steam, native IPC or wallet operations terminate this app session. Existing Market games continue using `connectGameSdk()` with their existing permissions and host transaction review.
44
+ Manifest: use schema/sdkVersion1, `permissions: []` and `collectionId: null`. App methods are deliberately limited to readiness, checkpoints and the score-only completion signal. Raw requests for profile, inventory, rewards, purchases, Steam, native IPC or wallet operations terminate this app session. Existing Market games continue using `connectGameSdk()` with their existing permissions and host transaction review.
45
+
46
+ ## Intro, loading and results
47
+
48
+ Your app owns its intro, artwork and custom loading screen. Render those inside the app frame and call `ready()` when your initial UI is usable; readiness does not have to wait for the player to press Start. The host keeps its normal readiness deadline. Use bundled artwork and the existing asset rules.
49
+
50
+ Both `connectVibeMarketApp()` and `connectGameSdk()` expose the same completion signal in 0.2.0:
51
+
52
+ ```ts
53
+ await app.game.finish({ score: 42 });
54
+ ```
55
+
56
+ `score` must be an integer from 0 through 1,000,000,000, with no other input fields. It is a reported game score. The host owns the final screen and Play again control. Completion is single-shot for that open controller, including suspended generations: retrying the same score acknowledges the accepted result; changing the score is rejected. The host posts acknowledgement before showing results. If the frame closes before it receives that acknowledgement, inspect the host result rather than assuming the completion failed.
57
+
58
+ Completion does not grant Cash, XP, inventory or a wallet action. The local preview and collection host report score only. An approved host may show an existing Cash award only after its own registered game policy and server reward flow confirm it; the frame cannot select a reward amount or supply proof of payment. Older hosts may not understand this additive method; use the matching 0.2.0 host/preview.
59
+
60
+ ## Publishing status
61
+
62
+ This release supports local browser previews. Production app submissions and approval are not available yet. Installing the SDK does not list your app in VibeMarket OS. The app API does not grant native, inventory, payment or reward access. Existing Market games continue to use their separate permissioned API.
63
+
64
+ See the [SDK docs](https://vibechain.com/os/docs) for the app API and [SECURITY.md](SECURITY.md) for the sandbox and resource limits.
45
65
 
46
66
  ## Maintainer workflow
47
67
 
@@ -50,7 +70,7 @@ yarn install --frozen-lockfile
50
70
  yarn review
51
71
  yarn build
52
72
  yarn check:package
53
- yarn release:preview --version 0.1.0
73
+ yarn release:preview --version 0.2.0
54
74
  ```
55
75
 
56
76
  `yarn build` emits JavaScript/declarations plus one bundled preview host UI. Production publishing still requires a separate reviewed service and explicit activation. The existing local upload/publish/rollback commands retain their operator-token and loopback gates. Read [SECURITY.md](SECURITY.md) before integrating any untrusted app.
package/SECURITY.md CHANGED
@@ -9,6 +9,7 @@ This is a bounded local browser development adapter, not a certification that ar
9
9
  - The additive app codec uses bounded JSON on the existing channel/envelope/port transport. Legacy Market messages stay unchanged. Wrong session, replayed IDs, unknown methods, invalid schemas, malformed/oversized messages and quota exhaustion close the port. No implicit Market permissions are inherited.
10
10
  - Close, navigation, minimize, app focus loss, hidden document, identity or package change revoke the active generation. Minimize/focus loss preserves only the same app's host-accepted bounded checkpoint. Restore creates a fresh iframe, challenge and session. Host focus uses desktop policy, not the browser `blur` event caused by focusing the child itself.
11
11
  - The app receives no host authentication, wallet address, profile, inventory, Steam ticket, native handle, money or arbitrary HTTP relay. Checkpoint contains only its own supplied JSON; it is parsed, never merged into host objects. An app must not ask people to enter secrets inside its UI.
12
+ - `game.finish` accepts only an integer score from 0 through 1,000,000,000. It cannot carry Cash, XP, receipts or grant instructions. The first score is retained across suspension; same-score retries acknowledge without a second host callback, and changed scores are refused. The host posts its acknowledgement before notifying its results UI. Callback throws or acknowledgement failure never authorize another award. Stale generations cannot notify the host. A reported score is not reward proof; only a separately registered host/server policy can confirm an existing Cash award.
12
13
 
13
14
  ## Enforced accepted-work limits
14
15
 
@@ -1,5 +1,6 @@
1
1
  import { APP_FRAGMENT, APP_LIMITS, appNonce, checkpointValue, lifecycleValue } from "./app-protocol.js";
2
2
  import { connectHostPort, createRpcTransport } from "./transport.js";
3
+ import { gameFinishInput } from "./completion.js";
3
4
  /** No profile, inventory, wallet, native, economy or arbitrary storage methods. */
4
5
  export async function connectVibeMarketApp(signal) {
5
6
  const challenge = new URLSearchParams(window.location.hash.slice(1)).get(APP_FRAGMENT);
@@ -35,6 +36,7 @@ export function createAppPortSdk(port, session) {
35
36
  const complete = (result) => { if (!("completed" in result) || result.completed !== true)
36
37
  throw Error("Invalid app acknowledgement."); };
37
38
  return Object.freeze({
39
+ game: Object.freeze({ async finish(input) { complete(await transport.request({ method: "game.finish", ...gameFinishInput(input) })); } }),
38
40
  async ready() { complete(await transport.request({ method: "ui.ready" })); },
39
41
  checkpoint: Object.freeze({
40
42
  async read() { const result = await transport.request({ method: "app.checkpoint.get" }); if (!("checkpoint" in result))
@@ -1,3 +1,4 @@
1
+ import type { GameFinishInput } from "./completion.ts";
1
2
  import { type AppLifecycle } from "./app-protocol.ts";
2
3
  export interface AppSession {
3
4
  lifecycle(value: AppLifecycle): void;
@@ -7,6 +8,7 @@ export interface AppController {
7
8
  attach(port: MessagePort, session: string, options: {
8
9
  current: () => boolean;
9
10
  ready: () => void;
11
+ finish?: (result: Readonly<GameFinishInput>) => void;
10
12
  fault: (message: string) => void;
11
13
  }): AppSession;
12
14
  suspend(): void;
@@ -20,6 +22,7 @@ export interface AppFrameOptions {
20
22
  current: () => boolean;
21
23
  ready: () => void;
22
24
  fault: (message: string) => void;
25
+ finish?: (result: Readonly<GameFinishInput>) => void;
23
26
  }
24
27
  /** Caller supplies the already-validated immutable URL, including this generation's fragment. */
25
28
  export declare function mountAppFrame(frame: HTMLIFrameElement, options: AppFrameOptions): {
package/dist/app-host.js CHANGED
@@ -4,6 +4,7 @@ import { APP_FRAGMENT, APP_LIMITS, appJson, appNonce, checkpointJson, createAppN
4
4
  /** A single installation/window owns only the JSON this same app host-accepted. */
5
5
  export function createAppController(clock = () => performance.now()) {
6
6
  let checkpoint = "null", disposed = false, active;
7
+ let completion, completionNotified = false;
7
8
  const startedAt = clock();
8
9
  if (!Number.isFinite(startedAt))
9
10
  throw Error("App clock is invalid.");
@@ -107,6 +108,12 @@ export function createAppController(clock = () => performance.now()) {
107
108
  options.ready();
108
109
  result = { completed: true };
109
110
  break;
111
+ case "game.finish":
112
+ if (completion && completion.score !== message.request.score)
113
+ throw Error("This game has already finished.");
114
+ completion ??= Object.freeze({ score: message.request.score });
115
+ result = { completed: true };
116
+ break;
110
117
  case "app.checkpoint.get":
111
118
  result = { checkpoint: JSON.parse(checkpoint) };
112
119
  break;
@@ -116,8 +123,13 @@ export function createAppController(clock = () => performance.now()) {
116
123
  break;
117
124
  }
118
125
  const response = { session, id: message.id, result };
119
- if (current())
126
+ if (current()) {
120
127
  port.postMessage(appJson(response, APP_LIMITS.responseBytes));
128
+ if (message.request.method === "game.finish" && completion && !completionNotified && current()) {
129
+ completionNotified = true;
130
+ options.finish?.(completion);
131
+ }
132
+ }
121
133
  }).catch(() => { if (!stopped)
122
134
  refuse("App request could not complete."); }).finally(() => { inFlight--; });
123
135
  };
@@ -173,7 +185,7 @@ export function mountAppFrame(frame, options) {
173
185
  const ports = new MessageChannel(), nonce = createAppNonce();
174
186
  try {
175
187
  session = options.controller.attach(ports.port1, nonce, { current: options.current,
176
- ready() { clearTimeout(timeout); options.ready(); }, fault });
188
+ ready() { clearTimeout(timeout); options.ready(); }, finish: options.finish, fault });
177
189
  // Opaque frames require wildcard targetOrigin; the exact WindowProxy/challenge bind this transfer.
178
190
  if (!frame.contentWindow)
179
191
  throw Error("App frame is unavailable.");
@@ -1,4 +1,5 @@
1
1
  /** Additive app messages on the existing SDK channel. No account or economy authority. */
2
+ import { type GameFinishInput } from "./completion.ts";
2
3
  export declare const APP_PROTOCOL: 1;
3
4
  export declare const APP_FRAGMENT = "vibexp";
4
5
  export declare const APP_CATEGORY = "vibexp-app";
@@ -22,7 +23,9 @@ export type AppValue = null | boolean | number | string | AppValue[] | {
22
23
  };
23
24
  export type AppRequest = {
24
25
  method: "ui.ready" | "app.checkpoint.get";
25
- } | {
26
+ } | ({
27
+ method: "game.finish";
28
+ } & GameFinishInput) | {
26
29
  method: "app.checkpoint.set";
27
30
  value: AppValue;
28
31
  };
@@ -37,6 +40,9 @@ export interface AppLifecycle {
37
40
  height: number;
38
41
  }
39
42
  export interface VibeMarketAppSdk {
43
+ game: {
44
+ finish(input: GameFinishInput): Promise<void>;
45
+ };
40
46
  ready(): Promise<void>;
41
47
  checkpoint: {
42
48
  read(): Promise<AppValue>;
@@ -1,4 +1,5 @@
1
1
  /** Additive app messages on the existing SDK channel. No account or economy authority. */
2
+ import { gameFinishInput } from "./completion.js";
2
3
  export const APP_PROTOCOL = 1;
3
4
  export const APP_FRAGMENT = "vibexp";
4
5
  export const APP_CATEGORY = "vibexp-app";
@@ -96,6 +97,8 @@ export function parseAppEnvelope(input, session) {
96
97
  || typeof input.id !== "string" || input.id.length > 80 || !/^[A-Za-z0-9_-]{1,80}$/.test(input.id) || !plain(input.request))
97
98
  throw Error("Invalid app session request.");
98
99
  const request = input.request;
100
+ if (request.method === "game.finish" && exact(request, ["method", "score"]))
101
+ return { id: input.id, request: { method: "game.finish", ...gameFinishInput({ score: request.score }) } };
99
102
  if ((request.method === "ui.ready" || request.method === "app.checkpoint.get") && exact(request, ["method"]))
100
103
  return { id: input.id, request: { method: request.method } };
101
104
  if (request.method === "app.checkpoint.set" && exact(request, ["method", "value"]))
package/dist/client.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { connectHostPort, createRpcTransport } from "./transport.js";
2
+ import { gameFinishAcknowledgement, gameFinishInput } from "./completion.js";
2
3
  /** Existing Market v1 API; no Desk capability is inferred from these methods. */
3
4
  export async function connectGameSdk(signal) {
4
5
  const { port } = await connectHostPort(signal);
@@ -11,6 +12,7 @@ export function createPortSdk(port) {
11
12
  listeners.forEach(listener => listener());
12
13
  } });
13
14
  return Object.freeze({
15
+ game: Object.freeze({ async finish(input) { gameFinishAcknowledgement(await transport.request({ method: "game.finish", ...gameFinishInput(input) })); } }),
14
16
  profile: { get: () => transport.request({ method: "profile.get" }) },
15
17
  catalog: { list: () => transport.request({ method: "catalog.list" }) },
16
18
  inventory: {
@@ -0,0 +1,7 @@
1
+ /** A reported game score is untrusted display data, never a Cash or XP grant. */
2
+ export interface GameFinishInput {
3
+ score: number;
4
+ }
5
+ export declare const GAME_SCORE_LIMIT = 1000000000;
6
+ export declare function gameFinishInput(input: unknown): Readonly<GameFinishInput>;
7
+ export declare function gameFinishAcknowledgement(input: unknown): void;
@@ -0,0 +1,14 @@
1
+ export const GAME_SCORE_LIMIT = 1_000_000_000;
2
+ export function gameFinishInput(input) {
3
+ if (!input || typeof input !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
4
+ throw Error("Invalid game completion.");
5
+ const score = Object.getOwnPropertyDescriptor(input, "score");
6
+ if (Reflect.ownKeys(input).length !== 1 || !score || !("value" in score) || !score.enumerable
7
+ || typeof score.value !== "number" || !Number.isInteger(score.value) || score.value < 0 || score.value > GAME_SCORE_LIMIT)
8
+ throw Error("Score must be an integer from 0 to 1,000,000,000.");
9
+ return Object.freeze({ score: score.value });
10
+ }
11
+ export function gameFinishAcknowledgement(input) {
12
+ if (!input || typeof input !== "object" || !("completed" in input) || input.completed !== true)
13
+ throw Error("Invalid game completion acknowledgement.");
14
+ }
package/dist/index.d.ts CHANGED
@@ -2,6 +2,8 @@ export { connectGameSdk, createPortSdk } from "./client.ts";
2
2
  export { CHANNEL } from "./channel.ts";
3
3
  export { watchInventory } from "./inventory.ts";
4
4
  export { connectVibeMarketApp } from "./app-client.ts";
5
+ export { GAME_SCORE_LIMIT } from "./completion.ts";
6
+ export type { GameFinishInput } from "./completion.ts";
5
7
  export type { AppValue, AppLifecycle, VibeMarketAppSdk } from "./app-protocol.ts";
6
8
  export type { InventoryObserver } from "./inventory.ts";
7
9
  export type * from "./types.ts";
package/dist/index.js CHANGED
@@ -2,3 +2,4 @@ export { connectGameSdk, createPortSdk } from "./client.js";
2
2
  export { CHANNEL } from "./channel.js";
3
3
  export { watchInventory } from "./inventory.js";
4
4
  export { connectVibeMarketApp } from "./app-client.js";
5
+ export { GAME_SCORE_LIMIT } from "./completion.js";
@@ -6,7 +6,8 @@ export async function startPreviewParent() {
6
6
  if (refusal)
7
7
  throw Error(refusal);
8
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))
9
+ const result = document.getElementById("result"), score = document.getElementById("score");
10
+ if (!surface || !status || !result || !score || !(toggle instanceof HTMLButtonElement) || !(reset instanceof HTMLButtonElement))
10
11
  throw Error("Preview controls are missing.");
11
12
  const input = await (await fetch("/preview.json", { credentials: "omit" })).json();
12
13
  if (!input || typeof input !== "object" || !("runtime" in input) || typeof input.runtime !== "string")
@@ -16,13 +17,22 @@ export async function startPreviewParent() {
16
17
  throw Error("Invalid preview runtime.");
17
18
  let controller = createAppController(), frame = null;
18
19
  let mounted = null, observer = null, minimized = false;
20
+ let completion = null;
19
21
  const detach = () => { mounted?.dispose(); mounted = null; controller.suspend(); observer?.disconnect(); observer = null; frame?.remove(); frame = null; };
20
22
  const draw = () => {
21
23
  detach();
24
+ surface.hidden = minimized || document.hidden || completion !== null;
25
+ result.hidden = true;
22
26
  if (minimized || document.hidden) {
23
27
  status.textContent = "App suspended. Its host-accepted checkpoint stays in this window.";
24
28
  return;
25
29
  }
30
+ if (completion) {
31
+ result.hidden = false;
32
+ score.textContent = String(completion.score);
33
+ status.textContent = "Round complete. No Cash reward for this preview.";
34
+ return;
35
+ }
26
36
  const challenge = createAppNonce(), source = new URL(runtime);
27
37
  source.hash = `${APP_FRAGMENT}=${challenge}`;
28
38
  frame = document.createElement("iframe");
@@ -33,6 +43,7 @@ export async function startPreviewParent() {
33
43
  surface.appendChild(frame);
34
44
  mounted = mountAppFrame(frame, { controller, challenge, current: () => !minimized && !document.hidden,
35
45
  ready: () => { status.textContent = "App ready · Minimize and restore to check its saved work."; },
46
+ finish: value => { completion = value; reset.textContent = "Play again"; draw(); },
36
47
  fault: message => { detach(); controller.dispose(); controller = createAppController(); status.textContent = message; },
37
48
  });
38
49
  observer = new ResizeObserver(() => { if (frame)
@@ -41,7 +52,7 @@ export async function startPreviewParent() {
41
52
  status.textContent = "Loading the isolated app…";
42
53
  };
43
54
  toggle.onclick = () => { minimized = !minimized; toggle.textContent = minimized ? "Restore" : "Minimize"; draw(); };
44
- reset.onclick = () => { detach(); controller.dispose(); controller = createAppController(); minimized = false; toggle.textContent = "Minimize"; draw(); };
55
+ reset.onclick = () => { detach(); controller.dispose(); controller = createAppController(); completion = null; minimized = false; toggle.textContent = "Minimize"; reset.textContent = "Close / reset"; draw(); };
45
56
  document.addEventListener("visibilitychange", draw);
46
57
  window.addEventListener("pagehide", () => { detach(); controller.dispose(); document.removeEventListener("visibilitychange", draw); }, { once: true });
47
58
  draw();
@@ -1 +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};
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};
package/dist/preview.js CHANGED
@@ -2,8 +2,8 @@ import { createServer } from "node:http";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { APP_CATEGORY, APP_FRAGMENT } from "./app-protocol.js";
4
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>`;
5
+ const CSS = `body{margin:0;background:#387bd8;font:14px Arial;color:#17233a}main{max-width:1000px;margin:40px auto}header{display:flex;flex-wrap:wrap;gap:8px;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}#result{background:#ece9d8;border:3px solid #0059e9;text-align:center;padding:48px 24px;min-height:300px}#result h2{font-size:32px;margin:0 0 24px}#score{display:block;font-size:clamp(32px,10vw,72px);overflow-wrap:anywhere;max-width:100%;color:#176844;margin:16px}`;
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><section id="result" hidden aria-label="Game results"><h2>Round complete</h2><p>Your score: <strong id="score"></strong></p><p>No Cash reward for this preview.</p></section><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
7
  const MODULES = new Set(["preview-ui.js"]);
8
8
  /** One immutable in-memory bundle. No file serving by arbitrary URL, proxy, credential or write endpoint. */
9
9
  export async function startAppPreview(directory, port = 0) {
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  /** Serializable game-facing DTOs. Never add wallet/session/driver objects here. */
2
+ import type { GameFinishInput } from "./completion.ts";
2
3
  export type GameProfile = {
3
4
  playerId: string;
4
5
  name: string;
@@ -38,7 +39,9 @@ export type GameAction = {
38
39
  };
39
40
  export type GameRequest = GameAction | {
40
41
  method: "profile.get" | "catalog.list" | "ui.ready" | "ui.shop";
41
- } | {
42
+ } | ({
43
+ method: "game.finish";
44
+ } & GameFinishInput) | {
42
45
  method: "inventory.get";
43
46
  cursor?: number;
44
47
  };
@@ -55,6 +58,9 @@ export type GameReview = {
55
58
  action: GameAction;
56
59
  };
57
60
  export interface GameSdk {
61
+ game: {
62
+ finish(input: GameFinishInput): Promise<void>;
63
+ };
58
64
  profile: {
59
65
  get(): Promise<GameProfile>;
60
66
  };
@@ -1,9 +1,9 @@
1
1
  # Stamp Club
2
2
 
3
- This standalone TypeScript app uses the exact SDK version that created it, or an explicitly supplied SDK archive. No monorepo checkout, company account or secrets are required.
3
+ Stamp Club is a small VibeMarket OS app built with TypeScript. Use it to try your own intro, checkpoints, window lifecycle events and a host-owned final score screen, then replace the stamp counter with your own idea.
4
4
 
5
- Run `npm install`, `npm run build`, then `npm run dev`. Open the printed **127.0.0.1** URL. Add stamps, minimize the window and restore it: the host restores only this app's host-accepted JSON into a fresh isolated frame. Closing/resetting clears it. Rebuild and restart the preview after source changes.
5
+ Run `npm install`, `npm run build`, then `npm run dev`. Open the printed **127.0.0.1** URL. Start a round, add stamps, minimize the window and restore it: the host restores only this app's host-accepted JSON into a fresh isolated frame. Finish the round to see the reported score. Play again creates a new controller and clears the old round. Rebuild and restart the preview after source changes.
6
6
 
7
7
  `npm run pack` produces `app.zip` for the existing development publisher. Production app publishing remains disabled; installing the SDK does not provide a public app-store listing.
8
8
 
9
- The app API has `ready()`, `checkpoint.read()/write()` and lifecycle notifications. Checkpoints are at most 32 KiB, remain in host memory only while this window is open, and carry no account, inventory, wallet, Cash, Steam or reward authority. Native shells are unsupported. See the SDK security documentation before accepting untrusted code.
9
+ The app API has `ready()`, `checkpoint.read()/write()`, lifecycle notifications and `game.finish({score})`. Your app owns its intro/loading UI; the host owns final results. The preview awards no Cash. Checkpoints are at most 32 KiB, remain in host memory only while this window is open, and carry no account, inventory, wallet, Cash, Steam or reward authority. Native shells are unsupported. See the SDK security documentation before accepting untrusted code.
@@ -1,4 +1,4 @@
1
1
  <!doctype html>
2
2
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Stamp Club</title>
3
3
  <style>body{margin:0;background:#ece9d8;color:#17233a;font:16px Arial;display:grid;min-height:100vh;place-items:center}main{max-width:520px;padding:32px;text-align:center}small{letter-spacing:.18em}h1{font-size:44px;margin:16px 0}output{display:block;font-size:88px;font-weight:700;color:#176844;margin:24px}button{border:1px solid #174b9c;border-radius:4px;background:linear-gradient(#fff,#d7e8ff);padding:14px 28px;color:#17233a;font:700 18px Arial;cursor:pointer}button:disabled{opacity:.5}p{line-height:1.5;color:#58637b}</style></head>
4
- <body><main><small>YOUR FIRST VIBEMARKET OS APP</small><h1>Stamp Club</h1><p>A tiny app with its own window, private connection and restorable state.</p><output id="count">0</output><button id="stamp" type="button" disabled>Add a stamp</button><p id="status" role="status">Connecting to the host…</p><p>Free local demo. No account, inventory, wallet or reward access.</p></main><script type="module" src="./main.js"></script></body></html>
4
+ <body><main><small>YOUR FIRST VIBEMARKET OS APP</small><h1>Stamp Club</h1><section id="intro"><p>A tiny round with its own intro, restorable state and host-owned results. Add stamps, then finish to see your score.</p><button id="start" type="button" disabled>Start round</button></section><section id="round" hidden><output id="count">0</output><button id="stamp" type="button" disabled>Add a stamp</button> <button id="finish" type="button" disabled>Finish round</button></section><p id="status" role="status">Connecting to the host…</p><p>Free local demo. No account, inventory, wallet or reward access.</p></main><script type="module" src="./main.js"></script></body></html>
@@ -1,22 +1,37 @@
1
- import { connectVibeMarketApp } from "@vibechain/os";
1
+ import { connectVibeMarketApp, GAME_SCORE_LIMIT } from "@vibechain/os";
2
2
 
3
3
  const count = document.querySelector<HTMLOutputElement>("#count");
4
4
  const button = document.querySelector<HTMLButtonElement>("#stamp");
5
5
  const status = document.querySelector<HTMLElement>("#status");
6
- if (!count || !button || !status) throw Error("Starter markup is missing.");
6
+ const start = document.querySelector<HTMLButtonElement>("#start"), finish = document.querySelector<HTMLButtonElement>("#finish");
7
+ const intro = document.querySelector<HTMLElement>("#intro"), round = document.querySelector<HTMLElement>("#round");
8
+ if (!count || !button || !status || !start || !finish || !intro || !round) throw Error("Starter markup is missing.");
7
9
  const sdk = await connectVibeMarketApp();
8
10
  const checkpoint = await sdk.checkpoint.read();
9
11
  let stamps = checkpoint !== null && typeof checkpoint === "object" && !Array.isArray(checkpoint)
10
- && typeof checkpoint.stamps === "number" && Number.isSafeInteger(checkpoint.stamps) && checkpoint.stamps >= 0 ? checkpoint.stamps : 0;
12
+ && typeof checkpoint.stamps === "number" && Number.isSafeInteger(checkpoint.stamps) && checkpoint.stamps >= 0 && checkpoint.stamps <= GAME_SCORE_LIMIT ? checkpoint.stamps : 0;
11
13
  const paint = () => { count.value = String(stamps); };
12
14
  paint();
15
+ const playing = checkpoint !== null && typeof checkpoint === "object" && !Array.isArray(checkpoint) && checkpoint.playing === true;
16
+ intro.hidden = playing; round.hidden = !playing;
13
17
  button.disabled = false;
18
+ finish.disabled = false;
19
+ start.disabled = false;
20
+ start.addEventListener("click", () => {
21
+ start.disabled = true;
22
+ void sdk.checkpoint.write({ stamps, playing: true }).then(() => { intro.hidden = true; round.hidden = false; })
23
+ .catch(() => { status.textContent = "This app session ended. Restore the window to reconnect."; start.disabled = false; });
24
+ });
25
+ finish.addEventListener("click", () => {
26
+ button.disabled = true; finish.disabled = true;
27
+ void sdk.game.finish({ score: stamps }).catch(() => { status.textContent = "The game session ended. Check the host result before retrying."; });
28
+ });
14
29
  button.addEventListener("click", () => {
15
30
  button.disabled = true;
16
- void sdk.checkpoint.write({ stamps: stamps + 1 }).then(() => { stamps++; paint(); status.textContent = "Saved in this open VibeMarket OS window. Try minimizing and restoring it."; })
31
+ void sdk.checkpoint.write({ stamps: stamps + 1, playing: true }).then(() => { stamps++; paint(); status.textContent = "Saved in this open VibeMarket OS window. Try minimizing and restoring it."; })
17
32
  .catch(() => { status.textContent = "This app session ended. Restore the window to reconnect."; })
18
- .finally(() => { button.disabled = !sdk.lifecycle.current().active; });
33
+ .finally(() => { button.disabled = !sdk.lifecycle.current().active || stamps === GAME_SCORE_LIMIT; });
19
34
  });
20
- sdk.lifecycle.onChanged(state => { button.disabled = !state.active; });
35
+ sdk.lifecycle.onChanged(state => { button.disabled = !state.active || stamps === GAME_SCORE_LIMIT; });
21
36
  window.addEventListener("pagehide", () => sdk.destroy(), { once: true });
22
37
  await sdk.ready();
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@vibechain/os",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "license": "MIT",
5
5
  "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" },
6
6
  "repository": { "type": "git", "url": "git+https://github.com/wieldlabs/www.git", "directory": "vibemarket/packages/os" },
7
7
  "homepage": "https://vibechain.com/os/docs",
8
8
  "engines": { "node": "^22.23.4 || ^24.22.1 || ^26.12.1" },
9
9
  "type": "module",
10
- "description": "TypeScript SDK and isolated local tooling for VibeMarket OS apps and Market games",
10
+ "description": "Build games, tools and desktop apps for VibeMarket OS with TypeScript",
11
11
  "types": "./dist/index.d.ts",
12
12
  "files": [
13
13
  "dist",