@vibechain/os 0.5.1 → 0.6.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.
Files changed (59) hide show
  1. package/AGENTS.md +52 -11
  2. package/README.md +115 -20
  3. package/SECURITY.md +6 -4
  4. package/dist/app-client.js +20 -4
  5. package/dist/app-host.d.ts +74 -5
  6. package/dist/app-host.js +94 -6
  7. package/dist/app-protocol.d.ts +21 -0
  8. package/dist/app-protocol.js +9 -0
  9. package/dist/app-wire.d.ts +186 -6
  10. package/dist/app-wire.js +213 -7
  11. package/dist/audio.d.ts +65 -0
  12. package/dist/audio.js +162 -0
  13. package/dist/browser.d.ts +2 -1
  14. package/dist/browser.js +2 -1
  15. package/dist/bundle.d.ts +2 -0
  16. package/dist/bundle.js +5 -3
  17. package/dist/check.js +11 -4
  18. package/dist/cli.js +3 -1
  19. package/dist/commands.d.ts +6 -0
  20. package/dist/commands.js +17 -0
  21. package/dist/fake-services.d.ts +88 -0
  22. package/dist/fake-services.js +132 -0
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +1 -1
  25. package/dist/links.d.ts +13 -0
  26. package/dist/links.js +17 -1
  27. package/dist/listing.d.ts +12 -0
  28. package/dist/listing.js +49 -1
  29. package/dist/manifest.d.ts +76 -1
  30. package/dist/manifest.js +170 -5
  31. package/dist/os.d.ts +83 -5
  32. package/dist/os.js +179 -15
  33. package/dist/preview-parent.d.ts +21 -2
  34. package/dist/preview-parent.js +101 -8
  35. package/dist/preview-surfaces.d.ts +36 -0
  36. package/dist/preview-surfaces.js +84 -0
  37. package/dist/preview-ui.js +1 -1
  38. package/dist/preview.js +4 -2
  39. package/dist/templates/plain/game.js +3 -1
  40. package/dist/testing.d.ts +50 -7
  41. package/dist/testing.js +137 -13
  42. package/dist/transport.d.ts +4 -1
  43. package/dist/transport.js +2 -2
  44. package/dist/vibemarket-os.js +1 -1
  45. package/examples/paw-beat/README.md +38 -10
  46. package/examples/paw-beat/cat.ts +13 -0
  47. package/examples/paw-beat/game.ts +290 -123
  48. package/examples/paw-beat/index.html +20 -4
  49. package/examples/paw-beat/main.ts +156 -48
  50. package/examples/paw-beat/music.ts +72 -337
  51. package/examples/paw-beat/stage.ts +23 -9
  52. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  53. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  54. package/examples/paw-beat/synth.ts +477 -0
  55. package/examples/paw-beat/tracks.ts +286 -0
  56. package/examples/paw-beat/vibemarket.json +15 -8
  57. package/examples/vibexp-app/plain/game.ts +6 -2
  58. package/package.json +7 -1
  59. package/skill.md +471 -0
package/dist/app-wire.js CHANGED
@@ -5,9 +5,17 @@
5
5
  */
6
6
  import { gameFinishInput } from "./completion.js";
7
7
  import { APP_LIMITS, FRAME_CHARS, captureId, frameImage, checkpointValue } from "./app-protocol.js";
8
- import { packSlug } from "./manifest.js";
9
- /** The nine stable error codes (section 11.3). Messages may change; codes never do. */
10
- export const OS_ERROR_CODES = ["unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed"];
8
+ import { GAME_SCORE_LIMIT } from "./completion.js";
9
+ import { LEADERBOARD_FORMATS, LEADERBOARD_ORDERS, PRODUCT_KINDS, assetPath, packSlug, serviceId, } from "./manifest.js";
10
+ /**
11
+ * The stable error codes (VM_OS_APPS_3.md section 11.3, nine since 0.5; VM_OS_APPS_4.md section 9 added four in 0.6:
12
+ * `cancelled`, `insufficient`, `limit` and `guest`). Messages may change; codes never do. A 0.5 client reads a code it does
13
+ * not know as `unavailable`, and a host answers the 0.6 codes only to the 0.6 methods, which a 0.5 client never sends.
14
+ */
15
+ export const OS_ERROR_CODES = [
16
+ "unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed",
17
+ "cancelled", "insufficient", "limit", "guest",
18
+ ];
11
19
  export const osErrorCode = (value) => typeof value === "string" && OS_ERROR_CODES.includes(value);
12
20
  /** Session-wide numbers of an apps3 host and a protocol 2 client (sections 9 and 10.1). */
13
21
  export const APP_SESSION_LIMITS = Object.freeze({
@@ -35,6 +43,13 @@ export const APP_SESSION_LIMITS = Object.freeze({
35
43
  clientPerSecond: 8, clientPerMinute: 100,
36
44
  /** a player token is reused while more than this remains */
37
45
  tokenReuseMs: 60_000,
46
+ /**
47
+ * SDK 0.6: how recent the click must be for a call that opens a vmOS surface over the app (share, invite, the leaderboard
48
+ * panel, an app link), and for `buy` (VM_OS_APPS_4.md section 8.2: a click within the last second)
49
+ */
50
+ clickMs: 5000, buyClickMs: 1000,
51
+ /** SDK 0.6: how long the SDK waits for a call answered only when the player closes a vmOS surface (buy, share, invite, the panel) */
52
+ surfaceMs: 30 * 60 * 1000,
38
53
  });
39
54
  export const RARITIES = ["common", "rare", "epic", "legendary", "mythic"];
40
55
  /** A card's id inside its pack, as the creator card rule admits it. */
@@ -46,6 +61,23 @@ export const CARD_ID = /^[A-Za-z0-9_-]{1,64}$/;
46
61
  * exactly `-/player/<handle>.bin` under the version prefix, and a three-part JWT of at most 1,500 characters.
47
62
  */
48
63
  export const PLAYER_RULES = Object.freeze({ handle: /^[a-z0-9_]{3,15}$/, nameMax: 64, token: /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/, tokenMin: 20, tokenMax: 1500 });
64
+ export const BOARD_SCOPES = ["everyone", "friends"];
65
+ export const BOARD_PERIODS = ["all", "week"];
66
+ export const PRESENCES = ["playing", "online", "offline"];
67
+ /** The numbers of VM_OS_APPS_4.md sections 3 to 8 that the SDK and the host check on every call. */
68
+ export const APPS4_LIMITS = Object.freeze({
69
+ boardRowsMax: 50, boardRowsDefault: 10, inviteText: 80, inviteData: 256, inviteRecipients: 10, shareText: 140,
70
+ friendsMax: 100, receiptsMax: 100, timeScoreMax: 86_400_000,
71
+ });
72
+ /** A receipt id as the backend issues it. */
73
+ export const RECEIPT_ID = /^[A-Za-z0-9_-]{1,64}$/;
74
+ /** An app id, as a manifest's `id` admits it. */
75
+ export const APP_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
76
+ export const appId = (value) => typeof value === "string" && value.length <= 60 && APP_ID.test(value);
77
+ /** The feature a host lists when `finish({ score, board })` reaches its board; without it the SDK sends `{ score }` only. */
78
+ export const FINISH_BOARD_FEATURE = "game.finish.board";
79
+ /** The name a secret achievement shows until it is unlocked. */
80
+ export const SECRET_ACHIEVEMENT_NAME = "Secret achievement";
49
81
  const KiB = 1024;
50
82
  /**
51
83
  * Request and response JSON bounds (of the request object and the result), the soft rate (answered `rate-limited`) and the
@@ -67,12 +99,33 @@ export const APP_METHODS_2 = Object.freeze({
67
99
  "player.get": { request: 64, response: 2 * KiB, rate: [10, 60_000], states: "LFB" },
68
100
  "display.maximize": { request: 64, response: 64, rate: [2, 1000], states: "F" },
69
101
  "display.fullscreen": { request: 64, response: 64, rate: [1, 1000], states: "F" },
102
+ // 0.6 (VM_OS_APPS_4.md sections 3 to 8)
103
+ "leaderboard.get": { request: 256, response: 32 * KiB, rate: [30, 60_000], states: "LFB" },
104
+ "leaderboard.show": { request: 128, response: 64, rate: [1, 3000], states: "F", click: APP_SESSION_LIMITS.clickMs, surface: true },
105
+ "achievement.unlock": { request: 128, response: 64, rate: [20, 60_000], states: "LFB" },
106
+ "achievements.list": { request: 64, response: 64 * KiB, rate: [10, 60_000], states: "LFB" },
107
+ "friends.list": { request: 64, response: 64 * KiB, rate: [10, 60_000], states: "LFB" },
108
+ "app.launch": { request: 64, response: 2 * KiB, rate: [4, 60_000], states: "LFB" },
109
+ "invite.open": { request: 4 * KiB, response: 64, rate: [1, 10_000], states: "F", click: APP_SESSION_LIMITS.clickMs, guest: true, surface: true },
110
+ "share.open": { request: 2 * KiB, response: 64, rate: [1, 10_000], states: "F", click: APP_SESSION_LIMITS.clickMs, guest: true, surface: true },
111
+ "products.list": { request: 64, response: 64 * KiB, rate: [10, 60_000], states: "LFB" },
112
+ "product.buy": { request: 128, response: 512, rate: [1, 3000], states: "F", click: APP_SESSION_LIMITS.buyClickMs, guest: true, surface: true },
113
+ "purchases.list": { request: 64, response: 32 * KiB, rate: [10, 60_000], states: "LFB" },
114
+ "purchase.consume": { request: 192, response: 64, rate: [30, 60_000], states: "LFB" },
115
+ "purchase.token": { request: 192, response: 2 * KiB, rate: [10, 60_000], states: "LFB" },
116
+ "app.show": { request: 192, response: 64, rate: [1, 10_000], bucket: "show", states: "F", click: APP_SESSION_LIMITS.clickMs },
70
117
  });
118
+ /** The 0.6 methods: a host lists each in hello's features only when it can answer it (AppHostServices), like `card.show`. */
119
+ export const APPS4_METHODS = Object.freeze([
120
+ "leaderboard.get", "leaderboard.show", "achievement.unlock", "achievements.list", "friends.list", "app.launch", "invite.open", "share.open",
121
+ "products.list", "product.buy", "purchases.list", "purchase.consume", "purchase.token", "app.show",
122
+ ]);
71
123
  /**
72
- * Protocol 2 features a hello answers with: the methods beyond protocol 1. `card.show` (0.5.1) is listed only by a host whose
73
- * services can show a card; a 0.5.0 host never lists it, and a client never sends a method its host did not list.
124
+ * Protocol 2 features a hello answers with: the methods beyond protocol 1. `card.show` (0.5.1) and the 0.6 methods are listed
125
+ * only by a host whose services answer them; a 0.5.0 host never lists them, and a client never sends a method its host did
126
+ * not list (it answers `unsupported` itself).
74
127
  */
75
- export const APP_FEATURES_2 = Object.freeze(Object.keys(APP_METHODS_2).filter(method => method !== "host.hello" && method !== "card.show"));
128
+ export const APP_FEATURES_2 = Object.freeze(Object.keys(APP_METHODS_2).filter(method => method !== "host.hello" && method !== "card.show" && !APPS4_METHODS.includes(method)));
76
129
  const encoder = new TextEncoder();
77
130
  export const utf8Bytes = (text) => encoder.encode(text).byteLength;
78
131
  const plain = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
@@ -227,9 +280,127 @@ export function wireHello(value) {
227
280
  throw Error("Invalid hello.");
228
281
  return { protocol: 2, guest: value.guest, features: value.features, root: value.root };
229
282
  }
283
+ // ---- 0.6 shapes: strict, so nothing private can ride along (APPS 4 section 10)
284
+ const oneOf = (values, value) => typeof value === "string" && values.includes(value);
285
+ const picture = (value, handle) => value === null || value === playerPicturePath(handle);
286
+ const displayName = (value) => string(value, PLAYER_RULES.nameMax, 1) && !CONTROL.test(value);
287
+ const score = (value) => whole(value, 0, GAME_SCORE_LIMIT);
288
+ const line = (value, max, min = 1) => typeof value === "string" && value.length >= min && [...value].length <= max && !CONTROL.test(value);
289
+ /** An achievement icon on the wire: the manifest's bundle path of a PNG or WebP. */
290
+ const iconPath = (value) => typeof value === "string" && assetPath(value) && /\.(?:png|webp)$/.test(value);
291
+ const playerFields = (value) => handleOf(value.handle) && displayName(value.name) && picture(value.picture, value.handle);
292
+ /** A board read as the host sends it; `query`, when given, is what was asked (the answer must be that board and period). */
293
+ export function wireLeaderboard(value, query) {
294
+ if (!plain(value) || !keysExactly(value, ["board", "name", "order", "format", "period", "entries", "you"]))
295
+ throw Error("Invalid leaderboard.");
296
+ const { board, name, order, format, period, entries, you } = value;
297
+ if (!serviceId(board) || !line(name, 40) || !oneOf(LEADERBOARD_ORDERS, order) || !oneOf(LEADERBOARD_FORMATS, format) || !oneOf(BOARD_PERIODS, period)
298
+ || !Array.isArray(entries) || entries.length > (query?.limit ?? APPS4_LIMITS.boardRowsMax)
299
+ || (query && (board !== query.board || period !== query.period)))
300
+ throw Error("Invalid leaderboard.");
301
+ const rows = entries.map(entry => {
302
+ if (!plain(entry) || !keysExactly(entry, ["rank", "handle", "name", "picture", "score", "you"]) || !whole(entry.rank, 1, Number.MAX_SAFE_INTEGER) || !playerFields(entry)
303
+ || !score(entry.score) || typeof entry.you !== "boolean")
304
+ throw Error("Invalid leaderboard entry.");
305
+ return { rank: entry.rank, handle: entry.handle, name: entry.name, picture: entry.picture, score: entry.score, you: entry.you };
306
+ });
307
+ let mine = null;
308
+ if (you !== null) {
309
+ if (!plain(you) || !keysExactly(you, ["rank", "score"]) || !whole(you.rank, 1, Number.MAX_SAFE_INTEGER) || !score(you.score))
310
+ throw Error("Invalid leaderboard.");
311
+ mine = { rank: you.rank, score: you.score };
312
+ }
313
+ return { board, name, order, format, period, entries: rows, you: mine };
314
+ }
315
+ export function wireAchievement(value) {
316
+ if (!plain(value) || !keysExactly(value, ["id", "name", "description", "icon", "secret", "unlocked", "at"]))
317
+ throw Error("Invalid achievement.");
318
+ const { id, name, description, icon, secret, unlocked, at } = value;
319
+ if (!serviceId(id) || !line(name, 40) || !line(description, 120, 0) || (icon !== null && !iconPath(icon)) || typeof secret !== "boolean" || typeof unlocked !== "boolean"
320
+ || (unlocked ? !whole(at, 0, Number.MAX_SAFE_INTEGER) : at !== null)
321
+ // a secret the player has not found says nothing about itself
322
+ || (secret && !unlocked && (description !== "" || icon !== null)))
323
+ throw Error("Invalid achievement.");
324
+ return { id, name, description, icon, secret, unlocked, at: at };
325
+ }
326
+ export function wireFriend(value) {
327
+ if (!plain(value) || !keysExactly(value, ["handle", "name", "picture", "presence"]) || !playerFields(value) || !oneOf(PRESENCES, value.presence))
328
+ throw Error("Invalid friend.");
329
+ return { handle: value.handle, name: value.name, picture: value.picture, presence: value.presence };
330
+ }
331
+ export function wireInvite(value) {
332
+ if (!plain(value) || !keysExactly(value, ["from", "data"]) || !handleOf(value.from) || (value.data !== null && !string(value.data, APPS4_LIMITS.inviteData)))
333
+ throw Error("Invalid invite.");
334
+ return { from: value.from, data: value.data };
335
+ }
336
+ export function wireProduct(value) {
337
+ if (!plain(value) || !keysExactly(value, ["id", "name", "description", "price", "kind", "owned"]))
338
+ throw Error("Invalid product.");
339
+ const { id, name, description, price, kind, owned } = value;
340
+ if (!serviceId(id) || !line(name, 40) || !line(description, 120) || !whole(price, 1, 1_000_000) || !oneOf(PRODUCT_KINDS, kind) || typeof owned !== "boolean"
341
+ || (owned && kind !== "permanent"))
342
+ throw Error("Invalid product.");
343
+ return { id, name, description, price, kind, owned };
344
+ }
345
+ export function wireReceipt(value) {
346
+ if (!plain(value) || !keysExactly(value, ["id", "product", "kind", "price", "at", "consumed"]))
347
+ throw Error("Invalid receipt.");
348
+ const { id, product, kind, price, at, consumed } = value;
349
+ if (typeof id !== "string" || !RECEIPT_ID.test(id) || !serviceId(product) || !oneOf(PRODUCT_KINDS, kind) || !whole(price, 1, 1_000_000) || !whole(at, 0, Number.MAX_SAFE_INTEGER)
350
+ || typeof consumed !== "boolean" || (consumed && kind !== "consumable"))
351
+ throw Error("Invalid receipt.");
352
+ return { id, product, kind, price, at, consumed };
353
+ }
354
+ /**
355
+ * Why a 0.6 request's values are not acceptable (`invalid`), or null: the exact rules of VM_OS_APPS_4.md sections 3 to 8 on top
356
+ * of `appRequest2`'s structural check. The SDK refuses before sending and the host refuses again before its handler runs.
357
+ */
358
+ export function apps4Problem(request) {
359
+ const board = (value) => value === undefined || serviceId(value);
360
+ switch (request.method) {
361
+ case "leaderboard.get": {
362
+ if (!board(request.board))
363
+ return "That is not a board id.";
364
+ if (request.scope !== undefined && !oneOf(BOARD_SCOPES, request.scope))
365
+ return 'scope is "everyone" or "friends".';
366
+ if (request.period !== undefined && !oneOf(BOARD_PERIODS, request.period))
367
+ return 'period is "all" or "week".';
368
+ if (request.limit !== undefined && !whole(request.limit, 1, APPS4_LIMITS.boardRowsMax))
369
+ return `limit is a whole number from 1 to ${APPS4_LIMITS.boardRowsMax}.`;
370
+ return null;
371
+ }
372
+ case "leaderboard.show": return board(request.board) ? null : "That is not a board id.";
373
+ case "achievement.unlock": return serviceId(request.id) ? null : "That is not an achievement id.";
374
+ case "invite.open":
375
+ if (request.to !== undefined && !handleOf(request.to))
376
+ return "to is a player's handle.";
377
+ if (request.text !== undefined && !line(request.text, APPS4_LIMITS.inviteText, 0))
378
+ return `An invite's text is one line of at most ${APPS4_LIMITS.inviteText} characters.`;
379
+ if (request.data !== undefined && !string(request.data, APPS4_LIMITS.inviteData))
380
+ return `An invite's data is at most ${APPS4_LIMITS.inviteData} characters.`;
381
+ return null;
382
+ case "share.open":
383
+ if (request.text !== undefined && !line(request.text, APPS4_LIMITS.shareText, 0))
384
+ return `A share's text is one line of at most ${APPS4_LIMITS.shareText} characters.`;
385
+ if (request.score !== undefined && !score(request.score))
386
+ return "score is a whole number from 0 to 1,000,000,000.";
387
+ if (!board(request.board))
388
+ return "That is not a board id.";
389
+ if (request.board !== undefined && request.score === undefined)
390
+ return "A board is shared with a score.";
391
+ return null;
392
+ case "product.buy": return serviceId(request.product) ? null : "That is not a product id.";
393
+ case "purchase.consume":
394
+ case "purchase.token": return RECEIPT_ID.test(request.receipt) ? null : "That is not a receipt id.";
395
+ case "app.show": return appId(request.app) ? null : "That is not an app id.";
396
+ default: return null;
397
+ }
398
+ }
230
399
  /** The version prefix relative to the entry document: `./` for `index.html`, `../` for `app/index.html`. */
231
400
  export const entryRoot = (entry) => entry.includes("/") ? "../".repeat(entry.split("/").length - 1) : "./";
232
401
  export { captureId, frameImage };
402
+ /** The keys whose value is not undefined (an optional field is either a value or absent, never `undefined` on the wire). */
403
+ const defined = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
233
404
  /**
234
405
  * A protocol 2 request, structurally checked (a violation ends the session). Values a well-behaved client could still get
235
406
  * wrong (a bad slug, a save over the limit) are left for the controller to answer `invalid` or `too-large`.
@@ -239,7 +410,11 @@ export function appRequest2(request) {
239
410
  switch (method) {
240
411
  case "ui.ready":
241
412
  case "app.checkpoint.get": return only() ? { method } : null;
242
- case "game.finish": return only("score") ? { method, ...gameFinishInput({ score: request.score }) } : null;
413
+ case "game.finish":
414
+ // 0.6: a board, only to a host that listed FINISH_BOARD_FEATURE (a 0.5 host ends the session on it)
415
+ if (keysExactly(request, ["method", "score"], ["board"]) && "board" in request)
416
+ return serviceId(request.board) ? { method, ...gameFinishInput({ score: request.score }), board: request.board } : null;
417
+ return only("score") ? { method, ...gameFinishInput({ score: request.score }) } : null;
243
418
  case "app.checkpoint.set": return only("value") ? { method, value: checkpointValue(request.value) } : null;
244
419
  case "host.hello": return only("protocol", "sdk") && request.protocol === 2 && string(request.sdk, 20, 1) && /^[\x20-\x7e]+$/.test(request.sdk) ? { method, protocol: 2, sdk: request.sdk } : null;
245
420
  case "ui.progress": return only("value") && typeof request.value === "number" && Number.isFinite(request.value) ? { method, value: request.value } : null;
@@ -259,6 +434,37 @@ export function appRequest2(request) {
259
434
  case "display.maximize":
260
435
  case "display.fullscreen":
261
436
  case "cards.watch": return only("on") && typeof request.on === "boolean" ? { method, on: request.on } : null;
437
+ // 0.6: types and loose bounds here (a violation ends the session); the exact rules are apps4Problem's soft `invalid`
438
+ case "leaderboard.get": {
439
+ const { board, scope, period, limit } = request;
440
+ if (!keysExactly(request, ["method"], ["board", "scope", "period", "limit"]) || (board !== undefined && !string(board, 64, 1)) || (scope !== undefined && !string(scope, 16, 1))
441
+ || (period !== undefined && !string(period, 16, 1)) || (limit !== undefined && typeof limit !== "number"))
442
+ return null;
443
+ return { method, ...defined({ board, scope, period, limit }) };
444
+ }
445
+ case "leaderboard.show": return keysExactly(request, ["method"], ["board"]) && (request.board === undefined || string(request.board, 64, 1)) ? { method, ...defined({ board: request.board }) } : null;
446
+ case "achievement.unlock": return only("id") && string(request.id, 64, 1) ? { method, id: request.id } : null;
447
+ case "achievements.list":
448
+ case "friends.list":
449
+ case "app.launch":
450
+ case "products.list":
451
+ case "purchases.list": return only() ? { method } : null;
452
+ case "invite.open": {
453
+ const { to, text, data } = request;
454
+ if (!keysExactly(request, ["method"], ["to", "text", "data"]) || (to !== undefined && !string(to, 64, 1)) || (text !== undefined && !string(text, 1024)) || (data !== undefined && !string(data, 1024)))
455
+ return null;
456
+ return { method, ...defined({ to, text, data }) };
457
+ }
458
+ case "share.open": {
459
+ const { text, score, board } = request;
460
+ if (!keysExactly(request, ["method"], ["text", "score", "board"]) || (text !== undefined && !string(text, 1024)) || (score !== undefined && typeof score !== "number") || (board !== undefined && !string(board, 64, 1)))
461
+ return null;
462
+ return { method, ...defined({ text, score, board }) };
463
+ }
464
+ case "product.buy": return only("product") && string(request.product, 64, 1) ? { method, product: request.product } : null;
465
+ case "purchase.consume":
466
+ case "purchase.token": return only("receipt") && string(request.receipt, 64, 1) ? { method, receipt: request.receipt } : null;
467
+ case "app.show": return only("app") && string(request.app, 64, 1) ? { method, app: request.app } : null;
262
468
  default: return null;
263
469
  }
264
470
  }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * `@vibechain/os/audio`: Web Audio that follows the desktop. `createAudio(app)` returns an AudioContext and a master GainNode
3
+ * that already obey the host's sound (the taskbar speaker and volume, `os.sound`), the window's lifecycle and the browser's
4
+ * gesture rule, and that recover from a context the browser stopped. An app connects what it plays to `master` and needs no
5
+ * other sound code.
6
+ *
7
+ * This is cooperative: a sandboxed frame cannot be muted from outside in a browser, so the host tells the app and the app
8
+ * obeys. VibeStore review requires every app that makes sound to follow the host's sound state; this helper is the easy way.
9
+ */
10
+ import { type AppSound } from "./app-protocol.ts";
11
+ import type { LifecycleSource, OsLifecycle } from "./loop.ts";
12
+ /** How long the master takes to reach a new level, in seconds: short enough to feel instant, long enough not to click. */
13
+ export declare const AUDIO_RAMP_SECONDS = 0.05;
14
+ /** The gestures that let a browser start audio in the frame; on each one a context that is not running is resumed. */
15
+ export declare const AUDIO_GESTURES: readonly string[];
16
+ /**
17
+ * Recovery bounds. A context still not running after this many gestures in a row (WebKit can leave one `suspended` or
18
+ * `interrupted` for the life of the page, after an audio interruption, sleep or an output change) is replaced by a new one,
19
+ * made inside the gesture so it may start; a context the browser closed is replaced at once. At most `remakes` times.
20
+ */
21
+ export declare const AUDIO_RECOVERY: Readonly<{
22
+ gestures: 3;
23
+ remakes: 3;
24
+ }>;
25
+ /** The 0.4 app object (`connectVibeMarketApp()`): lifecycle and, from 0.5.2, `sound`. */
26
+ export type AudioLegacySource = LifecycleSource & {
27
+ sound?: {
28
+ current(): Readonly<AppSound>;
29
+ onChanged(listener: (sound: Readonly<AppSound>) => void): () => void;
30
+ };
31
+ };
32
+ /** The 0.5 `Os` from `connect()`: lifecycle and, from 0.5.2, `sound`. */
33
+ export type AudioOsSource = OsLifecycle & {
34
+ readonly sound?: Readonly<AppSound>;
35
+ onSound?(listener: (sound: Readonly<AppSound>) => void): () => void;
36
+ };
37
+ export interface AudioOptions {
38
+ /** an AudioContext the app made itself; by default the helper makes one with `latencyHint` (and so does any replacement) */
39
+ context?: AudioContext;
40
+ /** for the helper's own contexts; default "interactive" */
41
+ latencyHint?: AudioContextLatencyCategory | number;
42
+ }
43
+ export interface AppAudio {
44
+ /** the current context. It is replaced if the browser closed it or it stayed stopped (see AUDIO_RECOVERY): read it again in `onChange` */
45
+ readonly context: AudioContext;
46
+ /** connect everything the app plays here; it follows the desktop, the app's own mute and the window, and is replaced with the context */
47
+ readonly master: GainNode;
48
+ /** the desktop's sound now */
49
+ readonly desktop: Readonly<AppSound>;
50
+ /** whether a player can hear the app: the desktop allows sound, the app's own mute is off, the window is active and the context runs */
51
+ readonly audible: boolean;
52
+ /** the app's own extra mute (a game's sound button). It can silence the app; it never overrides the desktop's mute. */
53
+ muted: boolean;
54
+ /** hold the context suspended (a pause menu, a lost GPU): neither the window coming back nor a click resumes it until false */
55
+ paused: boolean;
56
+ /** called after the desktop's sound, the app's mute, `paused`, the window, the context's state or the context itself changed */
57
+ onChange(listener: () => void): () => void;
58
+ /** stop following and close the context */
59
+ close(): void;
60
+ }
61
+ /**
62
+ * Web Audio for an app, following the desktop. Make it once, ideally in the first click (a context made then starts at
63
+ * once); a context made earlier starts on the frame's first click or key. Throws where the browser has no Web Audio.
64
+ */
65
+ export declare function createAudio(app: AudioLegacySource | AudioOsSource, options?: AudioOptions): AppAudio;
package/dist/audio.js ADDED
@@ -0,0 +1,162 @@
1
+ /**
2
+ * `@vibechain/os/audio`: Web Audio that follows the desktop. `createAudio(app)` returns an AudioContext and a master GainNode
3
+ * that already obey the host's sound (the taskbar speaker and volume, `os.sound`), the window's lifecycle and the browser's
4
+ * gesture rule, and that recover from a context the browser stopped. An app connects what it plays to `master` and needs no
5
+ * other sound code.
6
+ *
7
+ * This is cooperative: a sandboxed frame cannot be muted from outside in a browser, so the host tells the app and the app
8
+ * obeys. VibeStore review requires every app that makes sound to follow the host's sound state; this helper is the easy way.
9
+ */
10
+ import { AUDIBLE } from "./app-protocol.js";
11
+ /** How long the master takes to reach a new level, in seconds: short enough to feel instant, long enough not to click. */
12
+ export const AUDIO_RAMP_SECONDS = 0.05;
13
+ /** The gestures that let a browser start audio in the frame; on each one a context that is not running is resumed. */
14
+ export const AUDIO_GESTURES = Object.freeze(["pointerdown", "pointerup", "keydown", "touchend"]);
15
+ /**
16
+ * Recovery bounds. A context still not running after this many gestures in a row (WebKit can leave one `suspended` or
17
+ * `interrupted` for the life of the page, after an audio interruption, sleep or an output change) is replaced by a new one,
18
+ * made inside the gesture so it may start; a context the browser closed is replaced at once. At most `remakes` times.
19
+ */
20
+ export const AUDIO_RECOVERY = Object.freeze({ gestures: 3, remakes: 3 });
21
+ function follow(app) {
22
+ if ("lifecycle" in app) {
23
+ const sound = app.sound;
24
+ return {
25
+ active: () => app.lifecycle.current().active,
26
+ sound: () => sound?.current() ?? AUDIBLE,
27
+ onActive(listener) { let last = app.lifecycle.current().active; return app.lifecycle.onChanged(state => { if (state.active !== last) {
28
+ last = state.active;
29
+ listener(last);
30
+ } }); },
31
+ onSound: listener => sound ? sound.onChanged(listener) : () => { },
32
+ };
33
+ }
34
+ return {
35
+ active: () => app.active,
36
+ sound: () => app.sound ?? AUDIBLE,
37
+ onActive(listener) { const offs = [app.onPause(() => listener(false)), app.onResume(() => listener(true))]; return () => { for (const off of offs)
38
+ off(); }; },
39
+ onSound: listener => typeof app.onSound === "function" ? app.onSound(listener) : () => { },
40
+ };
41
+ }
42
+ /**
43
+ * Web Audio for an app, following the desktop. Make it once, ideally in the first click (a context made then starts at
44
+ * once); a context made earlier starts on the frame's first click or key. Throws where the browser has no Web Audio.
45
+ */
46
+ export function createAudio(app, options = {}) {
47
+ const host = follow(app);
48
+ const make = () => new AudioContext({ latencyHint: options.latencyHint ?? "interactive" });
49
+ let context = options.context ?? make(), master = context.createGain();
50
+ let own = false, paused = false, closed = false, active = host.active(), tries = 0, remakes = 0, suspendTimer;
51
+ const listeners = new Set();
52
+ const target = () => { const sound = host.sound(); return sound.muted || own || !active ? 0 : sound.volume; };
53
+ const changed = () => { for (const listener of [...listeners])
54
+ listener(); };
55
+ /** Move the master to where the desktop, the app and the window say, with a short ramp so nothing clicks. */
56
+ const apply = () => {
57
+ const now = context.currentTime, gain = master.gain;
58
+ gain.cancelScheduledValues(now);
59
+ gain.setValueAtTime(gain.value, now);
60
+ gain.linearRampToValueAtTime(target(), now + AUDIO_RAMP_SECONDS);
61
+ };
62
+ const wanted = () => !closed && !paused && active;
63
+ const start = () => { if (wanted() && context.state !== "running")
64
+ context.resume().catch(() => { }); };
65
+ const statechange = () => {
66
+ if (context.state === "running")
67
+ tries = 0;
68
+ if (context.state === "closed" && !closed) {
69
+ remake();
70
+ return;
71
+ }
72
+ changed();
73
+ };
74
+ const wire = () => {
75
+ master.gain.value = target();
76
+ master.connect(context.destination);
77
+ context.addEventListener("statechange", statechange);
78
+ };
79
+ /** A new context and master for one the browser closed or kept stopped; the app reconnects its nodes in `onChange`. */
80
+ function remake() {
81
+ if (remakes >= AUDIO_RECOVERY.remakes)
82
+ return;
83
+ remakes++;
84
+ tries = 0;
85
+ const old = context;
86
+ old.removeEventListener("statechange", statechange);
87
+ if (old.state !== "closed")
88
+ old.close().catch(() => { });
89
+ try {
90
+ context = make();
91
+ }
92
+ catch {
93
+ context = old;
94
+ return;
95
+ }
96
+ master = context.createGain();
97
+ wire();
98
+ start();
99
+ changed();
100
+ }
101
+ /** After the ramp down has played, stop the clock: a window behind another or a paused app costs nothing. */
102
+ const stop = () => {
103
+ clearTimeout(suspendTimer);
104
+ suspendTimer = setTimeout(() => { suspendTimer = undefined; if (!closed && !wanted() && context.state === "running")
105
+ context.suspend().catch(() => { }); }, AUDIO_RAMP_SECONDS * 1000 + 20);
106
+ };
107
+ const offs = [
108
+ host.onSound(() => { apply(); changed(); }),
109
+ host.onActive(next => { active = next; apply(); if (active) {
110
+ clearTimeout(suspendTimer);
111
+ start();
112
+ }
113
+ else
114
+ stop(); changed(); }),
115
+ ];
116
+ /** Every gesture while the context is not running resumes it; a context that ignores several in a row is replaced. */
117
+ const gesture = () => {
118
+ if (!wanted() || context.state === "running")
119
+ return;
120
+ if (++tries > AUDIO_RECOVERY.gestures)
121
+ remake();
122
+ else
123
+ start();
124
+ };
125
+ const visible = () => { if (document.visibilityState === "visible")
126
+ start(); };
127
+ for (const type of AUDIO_GESTURES)
128
+ window.addEventListener(type, gesture, { capture: true, passive: true });
129
+ document.addEventListener("visibilitychange", visible);
130
+ wire();
131
+ start();
132
+ return {
133
+ get context() { return context; },
134
+ get master() { return master; },
135
+ get desktop() { return host.sound(); },
136
+ get audible() { const sound = host.sound(); return !sound.muted && sound.volume > 0 && !own && active && context.state === "running"; },
137
+ get muted() { return own; },
138
+ set muted(value) { if (value === own)
139
+ return; own = value; apply(); changed(); },
140
+ get paused() { return paused; },
141
+ set paused(value) { if (value === paused)
142
+ return; paused = value; if (paused)
143
+ context.suspend().catch(() => { });
144
+ else
145
+ start(); changed(); },
146
+ onChange(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
147
+ close() {
148
+ if (closed)
149
+ return;
150
+ closed = true;
151
+ clearTimeout(suspendTimer);
152
+ for (const off of offs)
153
+ off();
154
+ for (const type of AUDIO_GESTURES)
155
+ window.removeEventListener(type, gesture, { capture: true });
156
+ document.removeEventListener("visibilitychange", visible);
157
+ context.removeEventListener("statechange", statechange);
158
+ listeners.clear();
159
+ context.close().catch(() => { });
160
+ },
161
+ };
162
+ }
package/dist/browser.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  /** The no-bundler build's entry: `dist/vibemarket-os.js` exposes exactly these as the global `VibemarketOS`. */
2
2
  export { connect, OsError } from "./os.ts";
3
- export { cardLink, packLink, parseVmosLink } from "./links.ts";
3
+ export { appLink, cardLink, packLink, parseVmosLink } from "./links.ts";
4
+ export { createAudio } from "./audio.ts";
package/dist/browser.js CHANGED
@@ -1,3 +1,4 @@
1
1
  /** The no-bundler build's entry: `dist/vibemarket-os.js` exposes exactly these as the global `VibemarketOS`. */
2
2
  export { connect, OsError } from "./os.js";
3
- export { cardLink, packLink, parseVmosLink } from "./links.js";
3
+ export { appLink, cardLink, packLink, parseVmosLink } from "./links.js";
4
+ export { createAudio } from "./audio.js";
package/dist/bundle.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /** The file extensions a bundle may contain (SVG is refused in schema 2 and 3 bundles by readBuiltBundle). */
2
+ export declare const ASSET_EXTENSIONS: readonly string[];
1
3
  export declare const assetType: (file: string) => string | undefined;
2
4
  export declare const compareAssetNames: (a: string, b: string) => number;
3
5
  /** Local authoring reader. Every allocation is bounded before reading; files cannot grow the budget. */
package/dist/bundle.js CHANGED
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { lstat, open, opendir, realpath } from "node:fs/promises";
3
3
  import { constants } from "node:fs";
4
4
  import path from "node:path";
5
- import { APP_BUNDLE_LIMITS, assetPath, parseManifest } from "./manifest.js";
5
+ import { APP_BUNDLE_LIMITS, APP_MANIFEST_LIMITS, assetPath, parseManifest } from "./manifest.js";
6
6
  import { checkListing } from "./listing.js";
7
7
  const TYPES = {
8
8
  html: "text/html; charset=utf-8", js: "text/javascript; charset=utf-8", mjs: "text/javascript; charset=utf-8",
@@ -11,6 +11,8 @@ const TYPES = {
11
11
  woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf", mp3: "audio/mpeg", ogg: "audio/ogg",
12
12
  wav: "audio/wav", mp4: "video/mp4", webm: "video/webm", wasm: "application/wasm", bin: "application/octet-stream", txt: "text/plain; charset=utf-8",
13
13
  };
14
+ /** The file extensions a bundle may contain (SVG is refused in schema 2 and 3 bundles by readBuiltBundle). */
15
+ export const ASSET_EXTENSIONS = Object.freeze(Object.keys(TYPES));
14
16
  export const assetType = (file) => TYPES[file.slice(file.lastIndexOf(".") + 1).toLowerCase()];
15
17
  export const compareAssetNames = (a, b) => a < b ? -1 : a > b ? 1 : 0;
16
18
  /** Local authoring reader. Every allocation is bounded before reading; files cannot grow the budget. */
@@ -70,8 +72,8 @@ export async function readBuiltBundle(directory) {
70
72
  }
71
73
  await walk("");
72
74
  const input = files["vibemarket.json"];
73
- if (!input || input.byteLength > 16 * 1024)
74
- throw Error("A manifest of at most16KiB is required.");
75
+ if (!input || input.byteLength > APP_MANIFEST_LIMITS.manifestBytes)
76
+ throw Error(`A manifest of at most ${APP_MANIFEST_LIMITS.manifestBytes / 1024} KiB is required.`);
75
77
  const manifest = parseManifest(JSON.parse(new TextDecoder().decode(input)));
76
78
  if (!files[manifest.entry])
77
79
  throw Error("Manifest entry is missing from the app bundle.");
package/dist/check.js CHANGED
@@ -7,8 +7,8 @@ import { lstat, opendir } from "node:fs/promises";
7
7
  import path from "node:path";
8
8
  import { zipSync } from "fflate";
9
9
  import { assetType, compareAssetNames, readBoundedAsset } from "./bundle.js";
10
- import { imageKind, pngSize } from "./listing.js";
11
- import { APP_BUNDLE_LIMITS, APP_STORE_LIMITS, assetPath, checkManifest, manifestNotices, manifestProblemText, parseManifest } from "./manifest.js";
10
+ import { achievementIconProblem, imageKind, pngSize } from "./listing.js";
11
+ import { APP_BUNDLE_LIMITS, APP_MANIFEST_LIMITS, APP_STORE_LIMITS, assetPath, checkManifest, manifestNotices, manifestProblemText, parseManifest } from "./manifest.js";
12
12
  const KiB = 1024, MiB = 1024 * 1024;
13
13
  const size = (bytes) => bytes >= MiB ? `${(bytes / MiB).toFixed(1)} MiB` : `${Math.ceil(bytes / KiB)} KiB`;
14
14
  const missing = (error) => error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT";
@@ -116,12 +116,12 @@ function listingProblems(icon, screenshots, files) {
116
116
  async function manifestAt(file, label) {
117
117
  let bytes;
118
118
  try {
119
- bytes = await readBoundedAsset(file, 16 * KiB);
119
+ bytes = await readBoundedAsset(file, APP_MANIFEST_LIMITS.manifestBytes);
120
120
  }
121
121
  catch (error) {
122
122
  if (missing(error))
123
123
  return null;
124
- return { problem: `${label}: must be a file of at most 16 KiB.` };
124
+ return { problem: `${label}: must be a file of at most ${APP_MANIFEST_LIMITS.manifestBytes / KiB} KiB.` };
125
125
  }
126
126
  try {
127
127
  return { value: JSON.parse(new TextDecoder().decode(bytes)) };
@@ -158,6 +158,13 @@ export async function checkApp(directory, limits = APP_BUNDLE_LIMITS) {
158
158
  problems.push(...listingProblems(parsed.store.icon, parsed.store.screenshots, files));
159
159
  else
160
160
  notices.push("schemaVersion: 1 has no store listing and cannot be submitted to VibeStore; use 3.");
161
+ // SDK 0.6: each achievement's icon, by the same rule as the store's checkListing
162
+ if (parsed.schemaVersion === 3)
163
+ (parsed.achievements ?? []).forEach((achievement, index) => {
164
+ const problem = achievement.icon === null ? null : achievementIconProblem(achievement.icon, files.get(achievement.icon));
165
+ if (problem)
166
+ problems.push(`achievements[${index}].icon: ${problem}`);
167
+ });
161
168
  if (!problems.length) {
162
169
  const zip = zipSync(Object.fromEntries([...files].map(([name, bytes]) => [name, bytes])), { level: 6 });
163
170
  if (zip.length > limits.archive)
package/dist/cli.js CHANGED
@@ -4,6 +4,7 @@ import { APP_BUNDLE_LIMITS, GAME_LIMITS } from "./manifest.js";
4
4
  import { readBuiltBundle } from "./bundle.js";
5
5
  import { APP_TEMPLATES, appTemplate, createApp, stageAppAssets } from "./scaffold.js";
6
6
  import { checkApp } from "./check.js";
7
+ import { APP_CLI_COMMANDS } from "./commands.js";
7
8
  import { startAppPreview } from "./preview.js";
8
9
  import { redact } from "./redact.js";
9
10
  const MiB = 1024 * 1024;
@@ -84,7 +85,8 @@ export async function runCli(argv, runtime = createCliRuntime()) {
84
85
  return;
85
86
  }
86
87
  if (!["upload", "list", "publish", "rollback"].includes(command ?? "")) {
87
- runtime.log("os init <empty-directory> [sdk.tgz] [--template plain|canvas|three]\nos assets\nos check [directory]\nos preview <dist> [port]\nos pack <dist> <game.zip>\n\nSubmit to VibeStore (sign in with Steam in your browser):\nos login [--no-browser] [--device <name>]\nos whoami\nos submit <dist> [--yes]\nos status [app-id]\nos logout\n\nInternal publisher (local operators only):\nos upload <game.zip>\nos list\nos publish <game-id> <version> <registry-revision>\nos rollback <game-id> <version> <registry-revision>\n\nSet VIBEMARKET_PUBLISH_URL=http://127.0.0.1:8888 and VIBEMARKET_PUBLISH_TOKEN (local operator credential). Upload returns a draft preview URL. Publish and rollback only update the active version pointer.");
88
+ const usage = (group) => APP_CLI_COMMANDS.filter(command => command.group === group).map(command => command.usage).join("\n");
89
+ runtime.log(usage("build") + "\n\nSubmit to VibeStore (sign in with Steam in your browser):\n" + usage("publish") + "\n\nInternal publisher (local operators only):\nos upload <game.zip>\nos list\nos publish <game-id> <version> <registry-revision>\nos rollback <game-id> <version> <registry-revision>\n\nSet VIBEMARKET_PUBLISH_URL=http://127.0.0.1:8888 and VIBEMARKET_PUBLISH_TOKEN (local operator credential). Upload returns a draft preview URL. Publish and rollback only update the active version pointer.");
88
90
  return;
89
91
  }
90
92
  const base = new URL(runtime.env.VIBEMARKET_PUBLISH_URL ?? "http://127.0.0.1:8888");
@@ -0,0 +1,6 @@
1
+ export interface AppCliCommand {
2
+ usage: string;
3
+ does: string;
4
+ group: "build" | "publish";
5
+ }
6
+ export declare const APP_CLI_COMMANDS: readonly AppCliCommand[];