@vibechain/os 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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;
package/dist/browser.d.ts CHANGED
@@ -1,2 +1,3 @@
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";
package/dist/browser.js CHANGED
@@ -1,2 +1,3 @@
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";
@@ -0,0 +1,22 @@
1
+ /** The longest side of a captured frame, in pixels. */
2
+ export declare const CAPTURE_MAX_SIDE = 1280;
3
+ /** The visible canvas with the largest on-screen area, or null. */
4
+ export declare function largestCanvas(doc: Pick<Document, "querySelectorAll">): HTMLCanvasElement | null;
5
+ /** Draw `source` downscaled to at most 1280 pixels on its longest side and encode it (WebP, else JPEG) under 1,000,000 characters; null if it cannot. */
6
+ export declare function encodeCanvas(source: HTMLCanvasElement, doc: Pick<Document, "createElement">): string | null;
7
+ /** What an `os.onCapture` handler may answer. */
8
+ export type CaptureResult = HTMLCanvasElement | string | null;
9
+ /** The picture for a handler's answer: a canvas is downscaled and encoded, a data URL is kept if it is a valid one. */
10
+ export declare function frameFrom(result: unknown, doc: Pick<Document, "createElement">): string | null;
11
+ /**
12
+ * The client half of one capture exchange, shared by `connect()` and the 0.4 client. `send` posts the `app.frame`; `closed`
13
+ * says the session is over. With no handler the answer is the largest visible canvas on the NEXT animation frame, so a
14
+ * continuously rendering WebGL game's drawing buffer still holds the frame it just drew. Nothing here ever throws.
15
+ */
16
+ export declare function createCapturer(send: (id: string, image: string | null) => void, closed: () => boolean): {
17
+ /** the latest handler wins; the returned function removes this one only if it is still the latest */
18
+ on(next: () => CaptureResult | Promise<CaptureResult>): () => void;
19
+ clear(): void;
20
+ /** the host's `app.capture` event */
21
+ event(id: unknown): void;
22
+ };
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The app side of the desktop camera: turn a canvas into the data URL an `app.frame` carries. The browser objects are passed
3
+ * in, so the helpers run (and test) without a global `document`.
4
+ */
5
+ import { captureId, frameImage } from "./app-protocol.js";
6
+ /** The longest side of a captured frame, in pixels. */
7
+ export const CAPTURE_MAX_SIDE = 1280;
8
+ const QUALITIES = [0.85, 0.6, 0.4];
9
+ /** The visible canvas with the largest on-screen area, or null. */
10
+ export function largestCanvas(doc) {
11
+ let best = null, area = 0;
12
+ for (const canvas of Array.from(doc.querySelectorAll("canvas"))) {
13
+ const box = canvas.getBoundingClientRect(), size = box.width * box.height;
14
+ if (size > area && canvas.width > 0 && canvas.height > 0) {
15
+ best = canvas;
16
+ area = size;
17
+ }
18
+ }
19
+ return best;
20
+ }
21
+ /** Draw `source` downscaled to at most 1280 pixels on its longest side and encode it (WebP, else JPEG) under 1,000,000 characters; null if it cannot. */
22
+ export function encodeCanvas(source, doc) {
23
+ try {
24
+ const width = source.width, height = source.height;
25
+ if (!(width > 0 && height > 0))
26
+ return null;
27
+ const scale = Math.min(1, CAPTURE_MAX_SIDE / Math.max(width, height));
28
+ const target = doc.createElement("canvas");
29
+ target.width = Math.max(1, Math.round(width * scale));
30
+ target.height = Math.max(1, Math.round(height * scale));
31
+ const context = target.getContext("2d");
32
+ if (!context)
33
+ return null;
34
+ context.drawImage(source, 0, 0, target.width, target.height);
35
+ for (const quality of QUALITIES) {
36
+ let url = target.toDataURL("image/webp", quality);
37
+ if (!url.startsWith("data:image/webp"))
38
+ url = target.toDataURL("image/jpeg", quality);
39
+ if (frameImage(url))
40
+ return url;
41
+ }
42
+ return null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ /** The picture for a handler's answer: a canvas is downscaled and encoded, a data URL is kept if it is a valid one. */
49
+ export function frameFrom(result, doc) {
50
+ if (typeof result === "string")
51
+ return frameImage(result) ? result : null;
52
+ if (result !== null && typeof result === "object" && "getContext" in result && "toDataURL" in result)
53
+ return encodeCanvas(result, doc);
54
+ return null;
55
+ }
56
+ /**
57
+ * The client half of one capture exchange, shared by `connect()` and the 0.4 client. `send` posts the `app.frame`; `closed`
58
+ * says the session is over. With no handler the answer is the largest visible canvas on the NEXT animation frame, so a
59
+ * continuously rendering WebGL game's drawing buffer still holds the frame it just drew. Nothing here ever throws.
60
+ */
61
+ export function createCapturer(send, closed) {
62
+ let handler = null;
63
+ const page = () => globalThis.document;
64
+ const answer = (id, image) => { if (closed())
65
+ return; try {
66
+ send(id, image);
67
+ }
68
+ catch { /* capture never breaks the app */ } };
69
+ return {
70
+ /** the latest handler wins; the returned function removes this one only if it is still the latest */
71
+ on(next) { handler = next; return () => { if (handler === next)
72
+ handler = null; }; },
73
+ clear() { handler = null; },
74
+ /** the host's `app.capture` event */
75
+ event(id) {
76
+ if (closed() || !captureId(id))
77
+ return;
78
+ try {
79
+ const custom = handler;
80
+ if (custom) {
81
+ Promise.resolve().then(custom).then(result => frameFrom(result, page()), () => null).then(image => answer(id, image), () => { });
82
+ return;
83
+ }
84
+ requestAnimationFrame(() => {
85
+ let image = null;
86
+ try {
87
+ const canvas = largestCanvas(page());
88
+ image = canvas ? frameFrom(canvas, page()) : null;
89
+ }
90
+ catch {
91
+ image = null;
92
+ }
93
+ answer(id, image);
94
+ });
95
+ }
96
+ catch { /* no document or animation frames: the host's timeout answers */ }
97
+ },
98
+ };
99
+ }
package/dist/index.d.ts CHANGED
@@ -3,7 +3,10 @@ export { CHANNEL } from "./channel.ts";
3
3
  export { watchInventory } from "./inventory.ts";
4
4
  export { connect, OsError, OS_ERROR_CODES, OS_SDK_VERSION } from "./os.ts";
5
5
  export type { Card, Os, OsErrorCode, OsSize, Pack, PackCard, PackSummary, Player, Rarity, SignedInPlayer } from "./os.ts";
6
+ export type { CaptureResult } from "./capture.ts";
6
7
  export { spawnWorker } from "./worker.ts";
8
+ export { cardLink, packLink, parseVmosLink, VMOS_LINK_MAX } from "./links.ts";
9
+ export type { VmosLink } from "./links.ts";
7
10
  export type { SpawnedWorker, WorkerHost } from "./worker.ts";
8
11
  /** @deprecated Use `connect()`: the same readiness, lifecycle and score, plus saves that outlive the window, cards and more. */
9
12
  export { connectVibeMarketApp } from "./app-client.ts";
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ export { CHANNEL } from "./channel.js";
3
3
  export { watchInventory } from "./inventory.js";
4
4
  export { connect, OsError, OS_ERROR_CODES, OS_SDK_VERSION } from "./os.js";
5
5
  export { spawnWorker } from "./worker.js";
6
+ export { cardLink, packLink, parseVmosLink, VMOS_LINK_MAX } from "./links.js";
6
7
  /** @deprecated Use `connect()`: the same readiness, lifecycle and score, plus saves that outlive the window, cards and more. */
7
8
  export { connectVibeMarketApp } from "./app-client.js";
8
9
  export { GAME_SCORE_LIMIT } from "./completion.js";
@@ -0,0 +1,15 @@
1
+ export type VmosLink = {
2
+ kind: "pack";
3
+ pack: string;
4
+ } | {
5
+ kind: "card";
6
+ pack: string;
7
+ card: string;
8
+ };
9
+ export declare const VMOS_LINK_MAX = 200;
10
+ /** The target a link names, or null when it is not exactly one of the three forms. */
11
+ export declare function parseVmosLink(text: unknown): VmosLink | null;
12
+ /** `vmos://pack/<slug>`; throws an OsError `invalid` for a value that is not a pack slug. */
13
+ export declare function packLink(slug: string): string;
14
+ /** `vmos://card/<slug>/<cardId>`; throws an OsError `invalid` for a value that is not a pack slug or a card id. */
15
+ export declare function cardLink(slug: string, cardId: string): string;
package/dist/links.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * App links (VM_OS_APPS_3.md, link-out): one string form an app can show, store or receive from its server for a vmOS pack or
3
+ * card, opened with `os.open(link)`. Pure functions, no DOM: the SDK parses a link and sends the host only the parsed target;
4
+ * nothing here, nor the host, ever navigates to the string.
5
+ *
6
+ * vmos://pack/<slug>
7
+ * vmos://card/<slug>/<cardId>
8
+ * https://vibechain.com/os/pack/<slug> (and https://www.vibechain.com/...; one optional trailing "/")
9
+ *
10
+ * Exact and anchored: lowercase scheme and host, at most 200 characters, no percent-encoding, query, fragment, user, port,
11
+ * other host or other path. `<slug>` is a pack slug (at most 56 characters), `<cardId>` a creator card id.
12
+ */
13
+ import { CARD_ID, OsError } from "./app-wire.js";
14
+ import { packSlug } from "./manifest.js";
15
+ export const VMOS_LINK_MAX = 200;
16
+ const SLUG = "[a-z0-9]+(?:-[a-z0-9]+)*", CARD = "[A-Za-z0-9_-]{1,64}";
17
+ const PACK_LINK = new RegExp(`^vmos://pack/(${SLUG})$`);
18
+ const CARD_LINK = new RegExp(`^vmos://card/(${SLUG})/(${CARD})$`);
19
+ const WEB_PACK = new RegExp(`^https://(?:www\\.)?vibechain\\.com/os/pack/(${SLUG})/?$`);
20
+ /** The target a link names, or null when it is not exactly one of the three forms. */
21
+ export function parseVmosLink(text) {
22
+ if (typeof text !== "string" || text.length > VMOS_LINK_MAX)
23
+ return null;
24
+ const card = CARD_LINK.exec(text);
25
+ if (card)
26
+ return packSlug(card[1]) ? { kind: "card", pack: card[1], card: card[2] } : null;
27
+ const pack = PACK_LINK.exec(text) ?? WEB_PACK.exec(text);
28
+ return pack && packSlug(pack[1]) ? { kind: "pack", pack: pack[1] } : null;
29
+ }
30
+ /** `vmos://pack/<slug>`; throws an OsError `invalid` for a value that is not a pack slug. */
31
+ export function packLink(slug) {
32
+ if (!packSlug(slug))
33
+ throw new OsError("invalid", "That is not a pack slug.");
34
+ return `vmos://pack/${slug}`;
35
+ }
36
+ /** `vmos://card/<slug>/<cardId>`; throws an OsError `invalid` for a value that is not a pack slug or a card id. */
37
+ export function cardLink(slug, cardId) {
38
+ if (!packSlug(slug) || typeof cardId !== "string" || !CARD_ID.test(cardId))
39
+ throw new OsError("invalid", "That is not a pack slug and a card id.");
40
+ return `vmos://card/${slug}/${cardId}`;
41
+ }
package/dist/os.d.ts CHANGED
@@ -1,13 +1,10 @@
1
- import { type Card, type OsErrorCode, type Pack, type PackSummary, type Player } from "./app-wire.ts";
1
+ import { type Card, type Pack, type PackSummary, type Player } from "./app-wire.ts";
2
+ import { type CaptureResult } from "./capture.ts";
2
3
  export type { Card, OsErrorCode, Pack, PackCard, PackSummary, Player, Rarity, SignedInPlayer } from "./app-wire.ts";
3
4
  export { OS_ERROR_CODES } from "./app-wire.ts";
4
5
  /** The SDK version a 0.5 client reports in `host.hello`. */
5
- export declare const OS_SDK_VERSION = "0.5.0";
6
- /** Every rejection of the app API. Branch on `code`; `message` is a plain sentence that may change. */
7
- export declare class OsError extends Error {
8
- readonly code: OsErrorCode;
9
- constructor(code: OsErrorCode, message: string);
10
- }
6
+ export declare const OS_SDK_VERSION = "0.5.1";
7
+ export { OsError } from "./app-wire.ts";
11
8
  export type OsSize = Readonly<{
12
9
  width: number;
13
10
  height: number;
@@ -31,10 +28,14 @@ export interface Os {
31
28
  /** called with the whole current list whenever it changes; returns unsubscribe */
32
29
  onCards(listener: (cards: Card[]) => void): () => void;
33
30
  packs(): Promise<PackSummary[]>;
34
- /** a pack's full public card list, in pack order */
31
+ /** any public pack's face (name, cover, cards with art), in pack order; holdings only come from `cards()` */
35
32
  pack(id: string): Promise<Pack>;
36
- /** the host opens the pack in the market window; needs a click in the app */
33
+ /** the host opens any public pack in VibeMarket; needs a click in the app */
37
34
  showPack(id: string): Promise<void>;
35
+ /** the host opens that card in its pack's page; needs a click in the app (0.5.1 hosts) */
36
+ showCard(pack: string, cardId: string): Promise<void>;
37
+ /** open an app link (`vmos://pack/<slug>`, `vmos://card/<slug>/<cardId>`, `https://vibechain.com/os/pack/<slug>`); needs a click */
38
+ open(link: string): Promise<void>;
38
39
  /** who is playing: handle, name and picture, or `{ guest: true }`; plus a 5-minute token for your own server with `network` */
39
40
  player(): Promise<Player>;
40
41
  finish(result: {
@@ -45,6 +46,12 @@ export interface Os {
45
46
  onPause(listener: () => void): () => void;
46
47
  onResume(listener: () => void): () => void;
47
48
  onResize(listener: (size: OsSize) => void): () => void;
49
+ /**
50
+ * The desktop camera asks for a picture of the app. By default the SDK sends the largest visible canvas; register a handler
51
+ * to draw one yourself (DOM apps, a custom view). It may return a canvas, a PNG/JPEG/WebP data URL (at most 1,000,000
52
+ * characters) or null, now or as a promise. The latest handler wins; returns unsubscribe.
53
+ */
54
+ onCapture?(handler: () => CaptureResult | Promise<CaptureResult>): () => void;
48
55
  /** release the port */
49
56
  close(): void;
50
57
  }
package/dist/os.js CHANGED
@@ -4,18 +4,16 @@
4
4
  * window-only checkpoint) and the rest reject with `unsupported`. Every rejection is an OsError with a stable code.
5
5
  */
6
6
  import { APP_FRAGMENT, APP_LIMITS, appNonce, checkpointJson, lifecycleValue } from "./app-protocol.js";
7
- import { APP_SESSION_LIMITS, AppHostError, osErrorCode, saveJson, saveValue, wireCard, wireCardsEvent, wireHello, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
7
+ import { APP_SESSION_LIMITS, AppHostError, CARD_ID, OsError, osErrorCode, saveJson, saveValue, wireCard, wireCardsEvent, wireHello, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
8
+ import { createCapturer } from "./capture.js";
8
9
  import { gameFinishInput } from "./completion.js";
9
10
  import { packSlug } from "./manifest.js";
10
11
  import { connectHostPort, createRpcTransport } from "./transport.js";
12
+ import { parseVmosLink } from "./links.js";
11
13
  export { OS_ERROR_CODES } from "./app-wire.js";
12
14
  /** The SDK version a 0.5 client reports in `host.hello`. */
13
- export const OS_SDK_VERSION = "0.5.0";
14
- /** Every rejection of the app API. Branch on `code`; `message` is a plain sentence that may change. */
15
- export class OsError extends Error {
16
- code;
17
- constructor(code, message) { super(message); this.name = "OsError"; this.code = code; }
18
- }
15
+ export const OS_SDK_VERSION = "0.5.1";
16
+ export { OsError } from "./app-wire.js";
19
17
  const MESSAGES = {
20
18
  unsupported: "This host is older than this SDK and has no such feature.",
21
19
  "not-permitted": "The manifest does not declare that, or the app is behind another window.",
@@ -67,6 +65,10 @@ export async function createOs(port, session, protocol, href) {
67
65
  cardsEvent(value.state);
68
66
  return;
69
67
  }
68
+ if (value.event === "app.capture") {
69
+ capturer.event(value.id);
70
+ return;
71
+ }
70
72
  if (value.event !== "app.lifecycle")
71
73
  return;
72
74
  let next;
@@ -89,6 +91,7 @@ export async function createOs(port, session, protocol, href) {
89
91
  listener(Object.freeze({ width: next.width, height: next.height }));
90
92
  },
91
93
  });
94
+ const capturer = createCapturer((id, image) => { call({ method: "app.frame", id, image }).catch(() => { }); }, () => protocol !== 2 || !hello || closed);
92
95
  const call = async (request) => {
93
96
  if (closed)
94
97
  throw fail("closed");
@@ -209,6 +212,15 @@ export async function createOs(port, session, protocol, href) {
209
212
  .finally(() => { writing = false; lastWrite = Date.now(); flush(); });
210
213
  };
211
214
  let token = null;
215
+ /** pack.show or card.show; a host that did not list card.show (0.5.0) is answered here, never sent a method it cannot read */
216
+ const show = async (request) => {
217
+ const hello = v2();
218
+ if (request.method === "card.show" && !hello.features.includes("card.show"))
219
+ throw fail("unsupported");
220
+ const result = await call(request);
221
+ if (result.shown !== true)
222
+ throw fail("unavailable", "Invalid host acknowledgement.");
223
+ };
212
224
  const os = {
213
225
  get active() { return state.active; },
214
226
  get size() { return Object.freeze({ width: state.width, height: state.height }); },
@@ -286,8 +298,19 @@ export async function createOs(port, session, protocol, href) {
286
298
  const pack = wirePack((await call({ method: "cards.pack", pack: name })).pack);
287
299
  return { ...pack, art: absolute(pack.art), cards: pack.cards.map(item => ({ ...item, art: absolute(item.art) })) };
288
300
  },
289
- async showPack(id) { const name = slug(id); v2(); const result = await call({ method: "pack.show", pack: name }); if (result.shown !== true)
290
- throw fail("unavailable", "Invalid host acknowledgement."); },
301
+ async showPack(id) { const name = slug(id); v2(); await show({ method: "pack.show", pack: name }); },
302
+ async showCard(pack, cardId) {
303
+ const name = slug(pack);
304
+ if (typeof cardId !== "string" || !CARD_ID.test(cardId))
305
+ throw fail("invalid", "That is not a card id.");
306
+ await show({ method: "card.show", pack: name, card: cardId });
307
+ },
308
+ async open(link) {
309
+ const target = parseVmosLink(link);
310
+ if (!target)
311
+ throw fail("invalid", "That is not a vmOS pack or card link.");
312
+ await (target.kind === "pack" ? show({ method: "pack.show", pack: target.pack }) : show({ method: "card.show", pack: target.pack, card: target.card }));
313
+ },
291
314
  async player() {
292
315
  v2();
293
316
  if (token && token.expiresAt - Date.now() > APP_SESSION_LIMITS.tokenReuseMs)
@@ -317,6 +340,11 @@ export async function createOs(port, session, protocol, href) {
317
340
  throw fail("invalid"); v2(); completed(await call({ method: "display.fullscreen", on })); },
318
341
  onPause(listener) { pause.add(listener); return () => { pause.delete(listener); }; },
319
342
  onResume(listener) { resume.add(listener); return () => { resume.delete(listener); }; },
343
+ onCapture(handler) {
344
+ if (typeof handler !== "function")
345
+ throw fail("invalid", "A capture handler is a function.");
346
+ return capturer.on(handler);
347
+ },
320
348
  onResize(listener) { resize.add(listener); return () => { resize.delete(listener); }; },
321
349
  close() {
322
350
  if (closed)
@@ -328,6 +356,7 @@ export async function createOs(port, session, protocol, href) {
328
356
  window.clearTimeout(progressTimer);
329
357
  pendingSave?.waiters.forEach(waiter => waiter.reject(fail("closed")));
330
358
  pendingSave = null;
359
+ capturer.clear();
331
360
  pause.clear();
332
361
  resume.clear();
333
362
  resize.clear();
@@ -341,7 +370,7 @@ export async function createOs(port, session, protocol, href) {
341
370
  const ready = os.ready;
342
371
  os.ready = async () => { readied = true; progressValue = null; await ready(); };
343
372
  // every rejection is an OsError: a malformed host answer is `unavailable`
344
- for (const key of ["ready", "load", "cards", "packs", "pack", "showPack", "player", "finish", "maximize", "fullscreen"]) {
373
+ for (const key of ["ready", "load", "cards", "packs", "pack", "showPack", "showCard", "open", "player", "finish", "maximize", "fullscreen"]) {
345
374
  const method = os[key];
346
375
  os[key] = async (...args) => { try {
347
376
  return await method(...args);
@@ -10,13 +10,19 @@ export interface PreviewMetadata {
10
10
  network: string[];
11
11
  }
12
12
  export declare function previewMetadata(input: unknown): PreviewMetadata;
13
+ /** A public pack every preview knows, linked or not, for trying `os.pack`, `os.showPack`, `os.showCard` and `os.open`. */
14
+ export declare const PREVIEW_PUBLIC_PACK = "preview-public";
13
15
  /**
14
16
  * The preview's stand-in for VibeMarket: six cards in each linked pack (or one sample pack for `cards: "all"`), of which
15
- * the player holds the first three; `pull()` adds a copy of a random card, as a pull would. Art is the bundle's listing
16
- * icon, served under the version prefix like the website's art route.
17
+ * the player holds the first three, and one more public pack nobody linked (`PREVIEW_PUBLIC_PACK`); `pull()` adds a copy
18
+ * of a random held-pack card, as a pull would. Art is the bundle's listing icon, served under the version prefix like the
19
+ * website's art route.
17
20
  */
18
21
  export declare function previewCatalog(meta: Pick<PreviewMetadata, "packs" | "cards">, random?: () => number): {
22
+ /** any public pack's face, linked or not (the host's rule since 0.5.1) */
19
23
  pack(slug: string): WirePack;
24
+ /** one card of a public pack, or `invalid` */
25
+ card(slug: string, card: string): WirePack["cards"][number];
20
26
  cards(): {
21
27
  cards: WireCard[];
22
28
  revision: string;
@@ -16,27 +16,38 @@ export function previewMetadata(input) {
16
16
  }
17
17
  /** A pack name from its slug: "rooftop-rats" reads "Rooftop Rats". */
18
18
  const title = (slug) => slug.split("-").map(word => word[0].toUpperCase() + word.slice(1)).join(" ");
19
+ /** A public pack every preview knows, linked or not, for trying `os.pack`, `os.showPack`, `os.showCard` and `os.open`. */
20
+ export const PREVIEW_PUBLIC_PACK = "preview-public";
19
21
  /**
20
22
  * The preview's stand-in for VibeMarket: six cards in each linked pack (or one sample pack for `cards: "all"`), of which
21
- * the player holds the first three; `pull()` adds a copy of a random card, as a pull would. Art is the bundle's listing
22
- * icon, served under the version prefix like the website's art route.
23
+ * the player holds the first three, and one more public pack nobody linked (`PREVIEW_PUBLIC_PACK`); `pull()` adds a copy
24
+ * of a random held-pack card, as a pull would. Art is the bundle's listing icon, served under the version prefix like the
25
+ * website's art route.
23
26
  */
24
27
  export function previewCatalog(meta, random = Math.random) {
25
28
  const slugs = meta.packs.length ? meta.packs : meta.cards === "all" ? ["preview-pack"] : [];
26
- const packs = slugs.map(slug => ({
29
+ const make = (slug) => ({
27
30
  id: slug, name: title(slug), creator: "Preview", art: coverArtPath(slug), total: 6,
28
31
  cards: Array.from({ length: 6 }, (_, index) => ({ id: `${slug}/c${index + 1}`, pack: slug, name: `${title(slug)} #${index + 1}`, rarity: RARITIES[index % RARITIES.length], art: cardArtPath(slug, `c${index + 1}`) })),
29
- }));
32
+ });
33
+ const packs = slugs.map(make), everyPublic = [...packs, ...(slugs.includes(PREVIEW_PUBLIC_PACK) ? [] : [make(PREVIEW_PUBLIC_PACK)])];
30
34
  const counts = new Map(packs.flatMap(pack => pack.cards.slice(0, 3).map(card => [card.id, 1])));
31
35
  let revision = 1;
32
- const readable = (slug) => meta.cards === "all" ? slugs.includes(slug) : meta.packs.includes(slug);
33
36
  return {
37
+ /** any public pack's face, linked or not (the host's rule since 0.5.1) */
34
38
  pack(slug) {
35
- const pack = packs.find(item => item.id === slug);
36
- if (!pack || !readable(slug))
37
- throw new AppHostError("not-permitted", "This app may not read that pack.");
39
+ const pack = everyPublic.find(item => item.id === slug);
40
+ if (!pack)
41
+ throw new AppHostError("invalid", "There is no such public pack.");
38
42
  return pack;
39
43
  },
44
+ /** one card of a public pack, or `invalid` */
45
+ card(slug, card) {
46
+ const found = this.pack(slug).cards.find(item => item.id === `${slug}/${card}`);
47
+ if (!found)
48
+ throw new AppHostError("invalid", "That card is not in that pack.");
49
+ return found;
50
+ },
40
51
  cards() {
41
52
  if (meta.cards === "none")
42
53
  throw new AppHostError("not-permitted", "The manifest does not declare cards.");
@@ -97,6 +108,7 @@ export async function startPreviewParent() {
97
108
  async packs() { return catalog.packs(); },
98
109
  async pack(slug) { return catalog.pack(slug); },
99
110
  async showPack(slug) { catalog.pack(slug); clicked(); status.textContent = `VibeMarket would open the pack ${slug} in its market window here.`; },
111
+ async showCard(slug, card) { const shown = catalog.card(slug, card); clicked(); status.textContent = `VibeMarket would open the card ${shown.name} (${card}) on the pack ${slug}'s page here.`; },
100
112
  // a stand-in identity; the preview has no account and signs nothing
101
113
  async player() {
102
114
  const player = { guest: false, handle: "preview_player", username: "preview", name: "Preview Player", picture: null };