@vibechain/os 0.5.0 → 0.5.2

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 (51) hide show
  1. package/AGENTS.md +22 -9
  2. package/README.md +53 -17
  3. package/SECURITY.md +6 -2
  4. package/dist/app-client.js +29 -5
  5. package/dist/app-host.d.ts +27 -4
  6. package/dist/app-host.js +76 -9
  7. package/dist/app-protocol.d.ts +36 -1
  8. package/dist/app-protocol.js +21 -0
  9. package/dist/app-wire.d.ts +24 -3
  10. package/dist/app-wire.js +19 -4
  11. package/dist/audio.d.ts +65 -0
  12. package/dist/audio.js +162 -0
  13. package/dist/browser.d.ts +2 -0
  14. package/dist/browser.js +2 -0
  15. package/dist/bundle.d.ts +2 -0
  16. package/dist/bundle.js +2 -0
  17. package/dist/capture.d.ts +22 -0
  18. package/dist/capture.js +99 -0
  19. package/dist/cli.js +3 -1
  20. package/dist/commands.d.ts +6 -0
  21. package/dist/commands.js +17 -0
  22. package/dist/index.d.ts +5 -2
  23. package/dist/index.js +1 -0
  24. package/dist/links.d.ts +21 -0
  25. package/dist/links.js +43 -0
  26. package/dist/os.d.ts +33 -8
  27. package/dist/os.js +68 -14
  28. package/dist/preview-parent.d.ts +8 -2
  29. package/dist/preview-parent.js +35 -10
  30. package/dist/preview-ui.js +1 -1
  31. package/dist/preview.js +1 -1
  32. package/dist/templates/plain/game.js +3 -1
  33. package/dist/testing.d.ts +15 -2
  34. package/dist/testing.js +64 -19
  35. package/dist/transport.d.ts +2 -0
  36. package/dist/transport.js +1 -1
  37. package/dist/vibemarket-os.js +1 -1
  38. package/examples/paw-beat/README.md +28 -9
  39. package/examples/paw-beat/game.ts +280 -123
  40. package/examples/paw-beat/index.html +18 -4
  41. package/examples/paw-beat/main.ts +101 -44
  42. package/examples/paw-beat/music.ts +72 -337
  43. package/examples/paw-beat/stage.ts +23 -9
  44. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  45. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  46. package/examples/paw-beat/synth.ts +477 -0
  47. package/examples/paw-beat/tracks.ts +286 -0
  48. package/examples/paw-beat/vibemarket.json +2 -2
  49. package/examples/vibexp-app/plain/game.ts +6 -2
  50. package/package.json +7 -1
  51. package/skill.md +399 -0
package/dist/app-host.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CHANNEL } from "./channel.js";
2
2
  import { appRuntimeRefusal } from "./app-runtime.js";
3
- import { APP_FRAGMENT, APP_LIMITS, appJson, appNonce, checkpointJson, createAppNonce, lifecycleValue, parseAppEnvelope, parseAppJson } from "./app-protocol.js";
4
- import { APP_FEATURES_2, APP_METHODS_2, APP_SESSION_LIMITS, CARD_ID, cardArtPath, coverArtPath, AppHostError, appRequest2, cardsRevision, entryRoot, methodRule, saveJson, saveValue, utf8Bytes, wireCard, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
3
+ import { APP_FRAGMENT, APP_LIMITS, FRAME_MESSAGE_BYTES, appJson, appNonce, checkpointJson, createAppNonce, lifecycleValue, parseAppEnvelope, parseAppJson, soundValue } from "./app-protocol.js";
4
+ import { APP_FEATURES_2, APP_METHODS_2, APP_SESSION_LIMITS, CARD_ID, cardArtPath, coverArtPath, AppHostError, appRequest2, cardsRevision, frameImage, entryRoot, methodRule, saveJson, saveValue, utf8Bytes, wireCard, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
5
5
  import { packSlug } from "./manifest.js";
6
6
  /**
7
7
  * An apps3 session's request: protocol 1 methods exactly as `parseAppEnvelope` admits them, `host.hello` before hello, and
@@ -14,7 +14,8 @@ function envelope2(data, session, hello) {
14
14
  throw Error("Invalid app session request.");
15
15
  const request = appRequest2(data.request);
16
16
  const legacy = request !== null && !Object.hasOwn(APP_METHODS_2, request.method);
17
- if (!request || (!hello && !legacy && request.method !== "host.hello"))
17
+ // app.frame is also admitted before hello: a 0.4 client never says hello and still answers the desktop camera
18
+ if (!request || (!hello && !legacy && request.method !== "host.hello" && request.method !== "app.frame"))
18
19
  throw Error("This app has no permission for that method.");
19
20
  if (utf8Bytes(JSON.stringify(data.request)) > methodRule(request.method).request)
20
21
  throw Error("App request exceeds its bound.");
@@ -125,7 +126,13 @@ export function createAppController(clock = () => performance.now(), options = {
125
126
  let baseline;
126
127
  const seen = new Set();
127
128
  const soft = new Map();
129
+ let captureSeq = 0, capturing;
130
+ const endCapture = (image) => { const waiting = capturing; capturing = undefined; if (waiting) {
131
+ clearTimeout(waiting.timer);
132
+ waiting.resolve(image);
133
+ } };
128
134
  const close = () => {
135
+ endCapture(null);
129
136
  if (stopped)
130
137
  return;
131
138
  stopped = true;
@@ -147,7 +154,24 @@ export function createAppController(clock = () => performance.now(), options = {
147
154
  const handle = {
148
155
  lifecycle(value) { if (current())
149
156
  port.postMessage(appJson({ session, event: "app.lifecycle", state: lifecycleValue(value) }, APP_LIMITS.responseBytes)); },
157
+ sound(value) { send({ session, event: "app.sound", state: soundValue(value) }, 256); },
150
158
  close,
159
+ capture(timeoutMs = APP_SESSION_LIMITS.captureMs) {
160
+ endCapture(null);
161
+ if (!current())
162
+ return Promise.resolve(null);
163
+ const id = String(++captureSeq), wait = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) ? Math.max(0, timeoutMs) : APP_SESSION_LIMITS.captureMs;
164
+ return new Promise(resolve => {
165
+ capturing = { id, resolve, timer: setTimeout(() => { if (capturing?.id === id)
166
+ endCapture(null); }, wait) };
167
+ try {
168
+ send({ session, event: "app.capture", id }, 256);
169
+ }
170
+ catch {
171
+ endCapture(null);
172
+ }
173
+ });
174
+ },
151
175
  };
152
176
  active = handle;
153
177
  activeFault = attachOptions.fault;
@@ -168,6 +192,18 @@ export function createAppController(clock = () => performance.now(), options = {
168
192
  baseline = { revision: next.revision, cards: fresh };
169
193
  send({ session, event: "app.cards", state: event }, APP_SESSION_LIMITS.cardsEventBytes + 1024);
170
194
  };
195
+ /** The answer to an `app.frame` on any protocol: ignore a late id, refuse a bad picture softly, else hand it to the pending capture. */
196
+ const frameAnswer = (request) => {
197
+ const pending = capturing?.id === request.id;
198
+ if (request.image !== null && !frameImage(request.image)) {
199
+ if (pending)
200
+ endCapture(null);
201
+ throw new AppHostError("invalid", "That is not a PNG, JPEG or WebP data URL of at most 1,000,000 characters.");
202
+ }
203
+ if (pending)
204
+ endCapture(request.image);
205
+ return { completed: true };
206
+ };
171
207
  /** One protocol 2 answer. A thrown AppHostError is a soft refusal; anything else from the services is `unavailable`. */
172
208
  const answer2 = async (services, request) => {
173
209
  const check = (value, valid) => { try {
@@ -177,7 +213,7 @@ export function createAppController(clock = () => performance.now(), options = {
177
213
  throw new AppHostError("unavailable", MESSAGE.unavailable);
178
214
  } };
179
215
  switch (request.method) {
180
- case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2], root: entryRoot(services.entry) };
216
+ case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2, ...(services.showCard ? ["card.show"] : [])], root: entryRoot(services.entry) };
181
217
  case "ui.progress":
182
218
  // ignored once the app is ready
183
219
  if (!ready) {
@@ -186,6 +222,7 @@ export function createAppController(clock = () => performance.now(), options = {
186
222
  attachOptions.progress?.(request.value);
187
223
  }
188
224
  return { completed: true };
225
+ case "app.frame": return frameAnswer(request);
189
226
  case "app.save.get": {
190
227
  const stored = await services.saveGet();
191
228
  return { value: stored.value === null ? null : check(stored.value, saveValue), savedAt: stored.savedAt === null ? null : check(stored.savedAt, value => { if (typeof value !== "string" || value.length > 30)
@@ -235,6 +272,13 @@ export function createAppController(clock = () => performance.now(), options = {
235
272
  throw new AppHostError("invalid", MESSAGE.slug);
236
273
  await services.showPack(request.pack);
237
274
  return { shown: true };
275
+ case "card.show":
276
+ if (!services.showCard)
277
+ throw new AppHostError("unsupported", "This host cannot show a card.");
278
+ if (!packSlug(request.pack) || !CARD_ID.test(request.card))
279
+ throw new AppHostError("invalid", "That is not a pack slug and a card id.");
280
+ await services.showCard(request.pack, request.card);
281
+ return { shown: true };
238
282
  case "player.get": return check(await services.player(), wirePlayer);
239
283
  case "display.maximize":
240
284
  await services.maximize(request.on);
@@ -264,9 +308,9 @@ export function createAppController(clock = () => performance.now(), options = {
264
308
  let id, request;
265
309
  try {
266
310
  if (!apps3)
267
- ({ id, request } = parseAppEnvelope(parseAppJson(event.data, APP_LIMITS.requestBytes), session));
311
+ ({ id, request } = parseAppEnvelope(parseAppJson(event.data, FRAME_MESSAGE_BYTES), session));
268
312
  else
269
- ({ id, request } = envelope2(parseAppJson(event.data, hello ? APP_SESSION_LIMITS.messageBytes : APP_LIMITS.requestBytes), session, hello));
313
+ ({ id, request } = envelope2(parseAppJson(event.data, APP_SESSION_LIMITS.messageBytes), session, hello));
270
314
  }
271
315
  catch {
272
316
  refuse("Invalid or unpermitted app request.");
@@ -306,6 +350,18 @@ export function createAppController(clock = () => performance.now(), options = {
306
350
  // backgrounded: a write is withheld exactly as a suspended app's would be lost (see AppAttachOptions)
307
351
  if (!foreground() && (method === "game.finish" || method === "app.checkpoint.set"))
308
352
  return;
353
+ if (request.method === "app.frame" && !apps3) {
354
+ try {
355
+ const result = frameAnswer(request);
356
+ if (current())
357
+ port.postMessage(appJson({ session, id, result }, APP_LIMITS.responseBytes));
358
+ }
359
+ catch (error) {
360
+ if (current())
361
+ port.postMessage(appJson({ session, id, error: error.message, code: "invalid" }, APP_LIMITS.responseBytes));
362
+ }
363
+ return;
364
+ }
309
365
  if (legacy) {
310
366
  let result;
311
367
  switch (request.method) {
@@ -355,10 +411,11 @@ export function createAppController(clock = () => performance.now(), options = {
355
411
  throw new AppHostError("not-permitted", MESSAGE.states);
356
412
  // leaving fullscreen is always allowed (section 9.2)
357
413
  if (rule.rate && !(request.method === "display.fullscreen" && !request.on)) {
358
- let limiter = soft.get(method);
414
+ const key = rule.bucket ?? method;
415
+ let limiter = soft.get(key);
359
416
  if (!limiter) {
360
417
  limiter = slidingWindow(rule.rate[0], rule.rate[1]);
361
- soft.set(method, limiter);
418
+ soft.set(key, limiter);
362
419
  }
363
420
  if (!limiter(now))
364
421
  throw new AppHostError("rate-limited", MESSAGE.rate);
@@ -405,7 +462,7 @@ export function mountAppFrame(frame, options) {
405
462
  throw Error("Invalid app frame challenge.");
406
463
  const protocol2 = options.controller.protocol === 2;
407
464
  let ended = false, loaded = false, connected = false, bootstrapMessages = 0, session, readied = false;
408
- let bounds = lifecycleValue({ active: true, width: 0, height: 0 });
465
+ let bounds = lifecycleValue({ active: true, width: 0, height: 0 }), sound = options.sound === undefined ? null : soundValue(options.sound);
409
466
  const slow = () => fault("App took too long to become ready.");
410
467
  const dispose = () => { if (ended)
411
468
  return; ended = true; clearTimeout(timeout); clearTimeout(ceiling); frame.removeEventListener("load", load); window.removeEventListener("message", connect); session?.close(); };
@@ -454,6 +511,8 @@ export function mountAppFrame(frame, options) {
454
511
  throw Error("App frame is unavailable.");
455
512
  frame.contentWindow.postMessage({ channel: CHANNEL, challenge: options.challenge, session: nonce, ...(protocol2 ? { protocol: 2 } : {}) }, "*", [ports.port2]);
456
513
  session.lifecycle(bounds);
514
+ if (sound)
515
+ session.sound(sound);
457
516
  }
458
517
  catch {
459
518
  ports.port1.close();
@@ -469,7 +528,15 @@ export function mountAppFrame(frame, options) {
469
528
  resize(width, height) { bounds = lifecycleValue({ active: bounds.active, width: Math.min(4096, Math.max(0, Math.floor(width))), height: Math.min(4096, Math.max(0, Math.floor(height))) }); session?.lifecycle(bounds); },
470
529
  setActive(active) { if (active === bounds.active)
471
530
  return; bounds = lifecycleValue({ ...bounds, active }); session?.lifecycle(bounds); },
531
+ setSound(next) {
532
+ const value = soundValue(next);
533
+ if (sound && sound.muted === value.muted && sound.volume === value.volume)
534
+ return;
535
+ sound = value;
536
+ session?.sound(value);
537
+ },
472
538
  dispose,
539
+ capture(timeoutMs) { return ended || !session ? Promise.resolve(null) : session.capture(timeoutMs); },
473
540
  };
474
541
  }
475
542
  /**
@@ -18,6 +18,18 @@ export declare const APP_LIMITS: Readonly<{
18
18
  sessionMs: number;
19
19
  requestTimeoutMs: 10000;
20
20
  }>;
21
+ /** A captured frame (`app.frame`) is a PNG, JPEG or WebP data URL of at most this many characters; its message may be this much larger than a protocol 1 request. */
22
+ export declare const FRAME_CHARS = 1000000;
23
+ export declare const FRAME_MESSAGE_BYTES: number;
24
+ /** A capture id: the host counts 1, 2, 3 ... per session. */
25
+ export declare const captureId: (value: unknown) => value is string;
26
+ export declare const frameImage: (value: unknown) => value is string;
27
+ /** The desktop camera's answer. Allowed on protocol 1 sessions too; `image` is checked by the host (a bad one is a soft `invalid`). */
28
+ export type AppFrameRequest = {
29
+ method: "app.frame";
30
+ id: string;
31
+ image: string | null;
32
+ };
21
33
  export type AppValue = null | boolean | number | string | AppValue[] | {
22
34
  [key: string]: AppValue;
23
35
  };
@@ -54,6 +66,16 @@ export interface VibeMarketAppSdk {
54
66
  current(): Readonly<AppLifecycle>;
55
67
  onChanged(listener: (state: Readonly<AppLifecycle>) => void): () => void;
56
68
  };
69
+ /**
70
+ * The desktop's sound (0.5.2): audible at full volume until the host says otherwise, then every change. Optional only so
71
+ * that objects written against 0.5.1 still type-check; `connectVibeMarketApp()` always provides it.
72
+ */
73
+ sound?: {
74
+ current(): Readonly<AppSound>;
75
+ onChanged(listener: (sound: Readonly<AppSound>) => void): () => void;
76
+ };
77
+ /** The desktop camera asks for a picture: by default the largest canvas is sent; register a handler (canvas, data URL or null) to draw your own. Latest wins; returns unsubscribe. */
78
+ onCapture?(handler: () => HTMLCanvasElement | string | null | Promise<HTMLCanvasElement | string | null>): () => void;
57
79
  destroy(): void;
58
80
  }
59
81
  export declare function appNonce(value: unknown): value is string;
@@ -65,6 +87,19 @@ export declare function checkpointJson(input: unknown): string;
65
87
  export declare function checkpointValue(input: unknown): AppValue;
66
88
  export declare function parseAppEnvelope(input: unknown, session: string): {
67
89
  id: string;
68
- request: AppRequest;
90
+ request: AppRequest | AppFrameRequest;
69
91
  };
92
+ /**
93
+ * The desktop's sound for this app (the `app.sound` event, any protocol): `muted` when the taskbar speaker (or the desktop's
94
+ * games sound) is off, `volume` the level games play at, from 0 to 1 (the website's desk sends master volume × its Games fader). The host is the one source of truth; an app follows it (`createAudio` from `@vibechain/os/audio` does). A host
95
+ * that predates it sends nothing, and the SDK reads that as audible at full volume.
96
+ */
97
+ export interface AppSound {
98
+ muted: boolean;
99
+ volume: number;
100
+ }
101
+ export declare const AUDIBLE: Readonly<AppSound>;
102
+ export declare function soundValue(input: unknown): Readonly<AppSound>;
103
+ /** Whether anything an app plays can be heard. */
104
+ export declare const audible: (sound: Readonly<AppSound>) => boolean;
70
105
  export declare function lifecycleValue(input: unknown): Readonly<AppLifecycle>;
@@ -10,6 +10,12 @@ export const APP_LIMITS = Object.freeze({
10
10
  requestsPerSecond: 10, inFlight: 4, lifetimeRequests: 5000,
11
11
  sessionMs: 15 * 60 * 1000, requestTimeoutMs: 10_000,
12
12
  });
13
+ /** A captured frame (`app.frame`) is a PNG, JPEG or WebP data URL of at most this many characters; its message may be this much larger than a protocol 1 request. */
14
+ export const FRAME_CHARS = 1_000_000;
15
+ export const FRAME_MESSAGE_BYTES = 1_100_000 + 1024;
16
+ /** A capture id: the host counts 1, 2, 3 ... per session. */
17
+ export const captureId = (value) => typeof value === "string" && /^[1-9]\d{0,15}$/.test(value);
18
+ export const frameImage = (value) => typeof value === "string" && value.length <= FRAME_CHARS && /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(value);
13
19
  export function appNonce(value) { return typeof value === "string" && /^[a-f0-9]{32}$/.test(value); }
14
20
  export function createAppNonce() {
15
21
  return [...crypto.getRandomValues(new Uint8Array(16))].map(value => value.toString(16).padStart(2, "0")).join("");
@@ -97,6 +103,12 @@ export function parseAppEnvelope(input, session) {
97
103
  || typeof input.id !== "string" || input.id.length > 80 || !/^[A-Za-z0-9_-]{1,80}$/.test(input.id) || !plain(input.request))
98
104
  throw Error("Invalid app session request.");
99
105
  const request = input.request;
106
+ if (request.method === "app.frame") {
107
+ if (!exact(request, ["method", "id", "image"]) || !captureId(request.id) || (request.image !== null && typeof request.image !== "string"))
108
+ throw Error("Invalid app frame.");
109
+ return { id: input.id, request: { method: "app.frame", id: request.id, image: request.image } };
110
+ }
111
+ appJson(input, APP_LIMITS.requestBytes); // every other request keeps its 34 KiB bound
100
112
  if (request.method === "game.finish" && exact(request, ["method", "score"]))
101
113
  return { id: input.id, request: { method: "game.finish", ...gameFinishInput({ score: request.score }) } };
102
114
  if ((request.method === "ui.ready" || request.method === "app.checkpoint.get") && exact(request, ["method"]))
@@ -105,6 +117,15 @@ export function parseAppEnvelope(input, session) {
105
117
  return { id: input.id, request: { method: request.method, value: checkpointValue(request.value) } };
106
118
  throw Error("This app has no permission for that method.");
107
119
  }
120
+ export const AUDIBLE = Object.freeze({ muted: false, volume: 1 });
121
+ export function soundValue(input) {
122
+ if (!plain(input) || !exact(input, ["muted", "volume"]) || typeof input.muted !== "boolean"
123
+ || typeof input.volume !== "number" || !Number.isFinite(input.volume) || input.volume < 0 || input.volume > 1)
124
+ throw Error("Invalid app sound.");
125
+ return Object.freeze({ muted: input.muted, volume: input.volume });
126
+ }
127
+ /** Whether anything an app plays can be heard. */
128
+ export const audible = (sound) => !sound.muted && sound.volume > 0;
108
129
  export function lifecycleValue(input) {
109
130
  if (!plain(input) || !exact(input, ["active", "width", "height"]) || typeof input.active !== "boolean"
110
131
  || typeof input.width !== "number" || !Number.isInteger(input.width) || input.width < 0 || input.width > 4096
@@ -1,4 +1,4 @@
1
- import { type AppRequest, type AppValue } from "./app-protocol.ts";
1
+ import { captureId, frameImage, type AppRequest, type AppValue } from "./app-protocol.ts";
2
2
  /** The nine stable error codes (section 11.3). Messages may change; codes never do. */
3
3
  export declare const OS_ERROR_CODES: readonly ["unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed"];
4
4
  export type OsErrorCode = typeof OS_ERROR_CODES[number];
@@ -25,6 +25,9 @@ export declare const APP_SESSION_LIMITS: Readonly<{
25
25
  saveIntervalMs: 10000;
26
26
  /** the largest protocol 2 message: a save plus its envelope */
27
27
  messageBytes: number;
28
+ /** a captured frame (`app.frame`): the data URL's length in characters, and how long the host waits for it by default */
29
+ frameChars: 1000000;
30
+ captureMs: 1200;
28
31
  cardsPage: 500;
29
32
  cardsEventBytes: number;
30
33
  /** the client's own pacing, below the host's hard limits (see transport.ts) */
@@ -115,6 +118,10 @@ export type AppRequest2 = AppRequest | {
115
118
  } | {
116
119
  method: "ui.progress";
117
120
  value: number;
121
+ } | {
122
+ method: "app.frame";
123
+ id: string;
124
+ image: string | null;
118
125
  } | {
119
126
  method: "app.save.get" | "cards.packs" | "player.get";
120
127
  } | {
@@ -127,6 +134,10 @@ export type AppRequest2 = AppRequest | {
127
134
  } | {
128
135
  method: "cards.pack" | "pack.show";
129
136
  pack: string;
137
+ } | {
138
+ method: "card.show";
139
+ pack: string;
140
+ card: string;
130
141
  } | {
131
142
  method: "display.maximize" | "display.fullscreen" | "cards.watch";
132
143
  on: boolean;
@@ -134,10 +145,12 @@ export type AppRequest2 = AppRequest | {
134
145
  export type AppMethod2 = AppRequest2["method"];
135
146
  /** L loading (before ready), F ready and in front, B behind another window (the grace). */
136
147
  type States = "LFB" | "L" | "F";
148
+ /** `bucket` names a soft rate shared by several methods (pack.show and card.show: one per 10 s together). */
137
149
  interface MethodRule {
138
150
  request: number;
139
151
  response: number;
140
152
  rate?: readonly [count: number, windowMs: number];
153
+ bucket?: string;
141
154
  states: States;
142
155
  }
143
156
  /**
@@ -146,9 +159,17 @@ interface MethodRule {
146
159
  * is this package's addition to the contract's table: it is how the host learns the app has an `onCards` listener.
147
160
  */
148
161
  export declare const APP_METHODS_2: Readonly<Record<Exclude<AppMethod2, AppRequest["method"]>, MethodRule>>;
149
- /** Protocol 2 features a hello answers with: the methods beyond protocol 1. */
162
+ /**
163
+ * Protocol 2 features a hello answers with: the methods beyond protocol 1. `card.show` (0.5.1) is listed only by a host whose
164
+ * 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.
165
+ */
150
166
  export declare const APP_FEATURES_2: readonly string[];
151
167
  export declare const utf8Bytes: (text: string) => number;
168
+ /** Every rejection of the app API. Branch on `code`; `message` is a plain sentence that may change. */
169
+ export declare class OsError extends Error {
170
+ readonly code: OsErrorCode;
171
+ constructor(code: OsErrorCode, message: string);
172
+ }
152
173
  /** An error with one of the nine codes, raised by the host's services or the controller and answered without ending the session. */
153
174
  export declare class AppHostError extends Error {
154
175
  readonly code: OsErrorCode;
@@ -184,6 +205,7 @@ export declare function wireCardsEvent(value: unknown): AppCardsEvent;
184
205
  export declare function wireHello(value: unknown): AppHello;
185
206
  /** The version prefix relative to the entry document: `./` for `index.html`, `../` for `app/index.html`. */
186
207
  export declare const entryRoot: (entry: string) => string;
208
+ export { captureId, frameImage };
187
209
  /**
188
210
  * A protocol 2 request, structurally checked (a violation ends the session). Values a well-behaved client could still get
189
211
  * wrong (a bad slug, a save over the limit) are left for the controller to answer `invalid` or `too-large`.
@@ -191,4 +213,3 @@ export declare const entryRoot: (entry: string) => string;
191
213
  export declare function appRequest2(request: Record<string, unknown>): AppRequest2 | null;
192
214
  /** The protocol 1 bound of a method of protocol 1, the table's bound otherwise. */
193
215
  export declare function methodRule(method: AppMethod2): MethodRule;
194
- export {};
package/dist/app-wire.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * Pure data and validators with no DOM or Node dependency, shared by the host (app-host.ts) and the client (os.ts).
5
5
  */
6
6
  import { gameFinishInput } from "./completion.js";
7
- import { APP_LIMITS, checkpointValue } from "./app-protocol.js";
7
+ import { APP_LIMITS, FRAME_CHARS, captureId, frameImage, checkpointValue } from "./app-protocol.js";
8
8
  import { packSlug } from "./manifest.js";
9
9
  /** The nine stable error codes (section 11.3). Messages may change; codes never do. */
10
10
  export const OS_ERROR_CODES = ["unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed"];
@@ -28,6 +28,8 @@ export const APP_SESSION_LIMITS = Object.freeze({
28
28
  saveIntervalMs: 10_000,
29
29
  /** the largest protocol 2 message: a save plus its envelope */
30
30
  messageBytes: 1_100_000 + 1024,
31
+ /** a captured frame (`app.frame`): the data URL's length in characters, and how long the host waits for it by default */
32
+ frameChars: FRAME_CHARS, captureMs: 1200,
31
33
  cardsPage: 500, cardsEventBytes: 256 * 1024,
32
34
  /** the client's own pacing, below the host's hard limits (see transport.ts) */
33
35
  clientPerSecond: 8, clientPerMinute: 100,
@@ -53,19 +55,24 @@ const KiB = 1024;
53
55
  export const APP_METHODS_2 = Object.freeze({
54
56
  "host.hello": { request: 256, response: KiB, states: "LFB" },
55
57
  "ui.progress": { request: 64, response: 64, rate: [4, 1000], states: "LFB" },
58
+ "app.frame": { request: 1_000_000 + 256, response: 64, rate: [4, 1000], states: "LFB" },
56
59
  "app.save.get": { request: 64, response: 1_100_000, rate: [6, 60_000], states: "LFB" },
57
60
  "app.save.set": { request: 1_100_000, response: 256, rate: [1, 10_000], states: "LFB" },
58
61
  "cards.list": { request: 256, response: 256 * KiB, rate: [30, 60_000], states: "LFB" },
59
62
  "cards.packs": { request: 64, response: 64 * KiB, rate: [30, 60_000], states: "LFB" },
60
63
  "cards.pack": { request: 128, response: 64 * KiB, rate: [30, 60_000], states: "LFB" },
61
64
  "cards.watch": { request: 64, response: 64, rate: [30, 60_000], states: "LFB" },
62
- "pack.show": { request: 128, response: 64, rate: [1, 10_000], states: "F" },
65
+ "pack.show": { request: 128, response: 64, rate: [1, 10_000], bucket: "show", states: "F" },
66
+ "card.show": { request: 192, response: 64, rate: [1, 10_000], bucket: "show", states: "F" },
63
67
  "player.get": { request: 64, response: 2 * KiB, rate: [10, 60_000], states: "LFB" },
64
68
  "display.maximize": { request: 64, response: 64, rate: [2, 1000], states: "F" },
65
69
  "display.fullscreen": { request: 64, response: 64, rate: [1, 1000], states: "F" },
66
70
  });
67
- /** Protocol 2 features a hello answers with: the methods beyond protocol 1. */
68
- export const APP_FEATURES_2 = Object.freeze(Object.keys(APP_METHODS_2).filter(method => method !== "host.hello"));
71
+ /**
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.
74
+ */
75
+ export const APP_FEATURES_2 = Object.freeze(Object.keys(APP_METHODS_2).filter(method => method !== "host.hello" && method !== "card.show"));
69
76
  const encoder = new TextEncoder();
70
77
  export const utf8Bytes = (text) => encoder.encode(text).byteLength;
71
78
  const plain = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
@@ -75,6 +82,11 @@ const keysExactly = (value, required, optional = []) => {
75
82
  return own.every(key => typeof key === "string" && (required.includes(key) || optional.includes(key)) && "value" in Object.getOwnPropertyDescriptor(value, key))
76
83
  && required.every(key => Object.hasOwn(value, key));
77
84
  };
85
+ /** Every rejection of the app API. Branch on `code`; `message` is a plain sentence that may change. */
86
+ export class OsError extends Error {
87
+ code;
88
+ constructor(code, message) { super(message); this.name = "OsError"; this.code = code; }
89
+ }
78
90
  /** An error with one of the nine codes, raised by the host's services or the controller and answered without ending the session. */
79
91
  export class AppHostError extends Error {
80
92
  code;
@@ -217,6 +229,7 @@ export function wireHello(value) {
217
229
  }
218
230
  /** The version prefix relative to the entry document: `./` for `index.html`, `../` for `app/index.html`. */
219
231
  export const entryRoot = (entry) => entry.includes("/") ? "../".repeat(entry.split("/").length - 1) : "./";
232
+ export { captureId, frameImage };
220
233
  /**
221
234
  * A protocol 2 request, structurally checked (a violation ends the session). Values a well-behaved client could still get
222
235
  * wrong (a bad slug, a save over the limit) are left for the controller to answer `invalid` or `too-large`.
@@ -230,6 +243,7 @@ export function appRequest2(request) {
230
243
  case "app.checkpoint.set": return only("value") ? { method, value: checkpointValue(request.value) } : null;
231
244
  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;
232
245
  case "ui.progress": return only("value") && typeof request.value === "number" && Number.isFinite(request.value) ? { method, value: request.value } : null;
246
+ case "app.frame": return only("id", "image") && captureId(request.id) && (request.image === null || typeof request.image === "string") ? { method, id: request.id, image: request.image } : null;
233
247
  case "app.save.get":
234
248
  case "cards.packs":
235
249
  case "player.get": return only() ? { method } : null;
@@ -241,6 +255,7 @@ export function appRequest2(request) {
241
255
  }
242
256
  case "cards.pack":
243
257
  case "pack.show": return only("pack") && string(request.pack, 64, 1) ? { method, pack: request.pack } : null;
258
+ case "card.show": return only("pack", "card") && string(request.pack, 64, 1) && string(request.card, 64, 1) ? { method, pack: request.pack, card: request.card } : null;
244
259
  case "display.maximize":
245
260
  case "display.fullscreen":
246
261
  case "cards.watch": return only("on") && typeof request.on === "boolean" ? { method, on: request.on } : null;
@@ -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;