@vibechain/os 0.4.1 → 0.5.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 (79) hide show
  1. package/AGENTS.md +76 -48
  2. package/README.md +131 -54
  3. package/SECURITY.md +45 -20
  4. package/dist/app-client.d.ts +4 -1
  5. package/dist/app-client.js +4 -1
  6. package/dist/app-host.d.ts +111 -9
  7. package/dist/app-host.js +339 -58
  8. package/dist/app-protocol.d.ts +2 -0
  9. package/dist/app-runtime.d.ts +18 -2
  10. package/dist/app-runtime.js +75 -11
  11. package/dist/app-wire.d.ts +194 -0
  12. package/dist/app-wire.js +253 -0
  13. package/dist/browser.d.ts +2 -0
  14. package/dist/browser.js +2 -0
  15. package/dist/bundle.js +6 -6
  16. package/dist/canvas.d.ts +2 -2
  17. package/dist/canvas.js +3 -1
  18. package/dist/check.d.ts +12 -0
  19. package/dist/check.js +167 -0
  20. package/dist/cli-publish.d.ts +24 -0
  21. package/dist/cli-publish.js +288 -0
  22. package/dist/cli-session.d.ts +108 -0
  23. package/dist/cli-session.js +245 -0
  24. package/dist/cli.d.ts +10 -0
  25. package/dist/cli.js +46 -10
  26. package/dist/index.d.ts +5 -0
  27. package/dist/index.js +3 -0
  28. package/dist/listing.d.ts +3 -3
  29. package/dist/listing.js +1 -1
  30. package/dist/loop.d.ts +18 -2
  31. package/dist/loop.js +13 -1
  32. package/dist/manifest.d.ts +90 -4
  33. package/dist/manifest.js +340 -5
  34. package/dist/os.d.ts +56 -0
  35. package/dist/os.js +354 -0
  36. package/dist/preview-parent.d.ts +36 -0
  37. package/dist/preview-parent.js +122 -11
  38. package/dist/preview-ui.js +1 -1
  39. package/dist/preview.js +25 -7
  40. package/dist/redact.d.ts +6 -0
  41. package/dist/redact.js +16 -0
  42. package/dist/runtime-policy.d.ts +20 -0
  43. package/dist/runtime-policy.js +45 -0
  44. package/dist/scaffold.d.ts +13 -2
  45. package/dist/scaffold.js +95 -31
  46. package/dist/submit-notice.d.ts +26 -0
  47. package/dist/submit-notice.js +34 -0
  48. package/dist/templates/plain/game.js +18 -0
  49. package/dist/testing.d.ts +63 -0
  50. package/dist/testing.js +157 -1
  51. package/dist/transport.d.ts +20 -0
  52. package/dist/transport.js +71 -19
  53. package/dist/vibemarket-os.js +1 -0
  54. package/dist/worker.d.ts +18 -0
  55. package/dist/worker.js +34 -0
  56. package/examples/paw-beat/README.md +20 -8
  57. package/examples/paw-beat/cat.ts +665 -89
  58. package/examples/paw-beat/game.ts +162 -28
  59. package/examples/paw-beat/index.html +114 -40
  60. package/examples/paw-beat/main.ts +264 -149
  61. package/examples/paw-beat/music.ts +314 -65
  62. package/examples/paw-beat/stage.ts +560 -0
  63. package/examples/paw-beat/store/icon.png +0 -0
  64. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  65. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  66. package/examples/paw-beat/vibemarket.json +2 -2
  67. package/examples/vibexp-app/README.md +7 -7
  68. package/examples/vibexp-app/index.html +3 -2
  69. package/examples/vibexp-app/plain/game.ts +20 -0
  70. package/examples/vibexp-app/plain/index.html +6 -0
  71. package/examples/vibexp-app/plain/vibemarket.json +17 -0
  72. package/examples/vibexp-app/src/main.ts +46 -31
  73. package/examples/vibexp-app/store/icon.png +0 -0
  74. package/examples/vibexp-app/three/README.md +21 -0
  75. package/examples/vibexp-app/three/index.html +4 -0
  76. package/examples/vibexp-app/three/src/main.ts +45 -0
  77. package/examples/vibexp-app/three/vibemarket.json +19 -0
  78. package/examples/vibexp-app/vibemarket.json +17 -11
  79. package/package.json +6 -2
@@ -0,0 +1,194 @@
1
+ import { type AppRequest, type AppValue } from "./app-protocol.ts";
2
+ /** The nine stable error codes (section 11.3). Messages may change; codes never do. */
3
+ export declare const OS_ERROR_CODES: readonly ["unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed"];
4
+ export type OsErrorCode = typeof OS_ERROR_CODES[number];
5
+ export declare const osErrorCode: (value: unknown) => value is OsErrorCode;
6
+ /** Session-wide numbers of an apps3 host and a protocol 2 client (sections 9 and 10.1). */
7
+ export declare const APP_SESSION_LIMITS: Readonly<{
8
+ /** no user activation and no app request for this long while in front: the host asks "Still playing?" */
9
+ idleMs: number;
10
+ /** absolute controller life */
11
+ sessionMs: number;
12
+ requestsPerSecond: 10;
13
+ requestsPerMinute: 120;
14
+ lifetimeRequests: 30000;
15
+ /** in flight: protocol 1 sessions keep APP_LIMITS.inFlight */
16
+ inFlight: 8;
17
+ /** ready() within this, or progress() at least this often ... */
18
+ readyMs: 15000;
19
+ /** ... and ready() within this */
20
+ progressReadyMs: 120000;
21
+ /** one save: UTF-8 JSON bytes and nesting depth (the root container is level 1) */
22
+ saveBytes: 1048576;
23
+ saveDepth: 64;
24
+ /** at most one save write per this interval; the SDK coalesces calls made sooner */
25
+ saveIntervalMs: 10000;
26
+ /** the largest protocol 2 message: a save plus its envelope */
27
+ messageBytes: number;
28
+ cardsPage: 500;
29
+ cardsEventBytes: number;
30
+ /** the client's own pacing, below the host's hard limits (see transport.ts) */
31
+ clientPerSecond: 8;
32
+ clientPerMinute: 100;
33
+ /** a player token is reused while more than this remains */
34
+ tokenReuseMs: 60000;
35
+ }>;
36
+ export declare const RARITIES: readonly ["common", "rare", "epic", "legendary", "mythic"];
37
+ export type Rarity = typeof RARITIES[number];
38
+ /** A card's id inside its pack, as the creator card rule admits it. */
39
+ export declare const CARD_ID: RegExp;
40
+ /** A card the player holds, as an app sees it. `id` is `<pack slug>/<card id>`, stable forever. */
41
+ export interface Card {
42
+ id: string;
43
+ pack: string;
44
+ name: string;
45
+ rarity: Rarity;
46
+ count: number;
47
+ art: string | null;
48
+ }
49
+ export type PackCard = Omit<Card, "count">;
50
+ export interface PackSummary {
51
+ id: string;
52
+ name: string;
53
+ creator: string | null;
54
+ art: string | null;
55
+ held: number;
56
+ total: number;
57
+ }
58
+ export interface Pack extends Omit<PackSummary, "held"> {
59
+ cards: PackCard[];
60
+ }
61
+ /**
62
+ * Who is playing: the player's public vmOS identity, for every schema 3 app (owner decision 2026-11-23: no anonymous ids).
63
+ * `handle` never changes; `username` and `name` may. `picture` is the avatar, an image URL under the app's own address, or
64
+ * null. `token` and `expiresAt` (epoch milliseconds) only for apps that declare `network`: a 5-minute signed statement of
65
+ * the same identity for the app's own server. A guest is `{ guest: true }` and nothing else.
66
+ */
67
+ export type Player = {
68
+ guest: true;
69
+ } | SignedInPlayer;
70
+ export interface SignedInPlayer {
71
+ guest: false;
72
+ handle: string;
73
+ username?: string;
74
+ name: string;
75
+ picture: string | null;
76
+ token?: string;
77
+ expiresAt?: number;
78
+ }
79
+ /**
80
+ * The rules a player's fields follow on the wire, as the backend's `vibemarket/steam/os-apps.ts` (`appPlayerSchema`,
81
+ * `parseAppIdentity`) admits them: a handle or @name of 3 to 15 lowercase letters, digits and underscores (`username` only when
82
+ * it differs from `handle`), a display name of 1 to 64 UTF-16 code units without control characters, the picture as
83
+ * exactly `-/player/<handle>.bin` under the version prefix, and a three-part JWT of at most 1,500 characters.
84
+ */
85
+ export declare const PLAYER_RULES: Readonly<{
86
+ handle: RegExp;
87
+ nameMax: 64;
88
+ token: RegExp;
89
+ tokenMin: 20;
90
+ tokenMax: 1500;
91
+ }>;
92
+ /** On the wire `art` is the path after the version prefix (`-/card/<slug>/<id>.bin`, `-/cover/<slug>.bin`); the SDK makes it absolute. */
93
+ export type WireCard = Card;
94
+ export type WirePackCard = PackCard;
95
+ export type WirePackSummary = PackSummary;
96
+ export type WirePack = Pack;
97
+ export type AppCardsEvent = {
98
+ changed: WireCard[];
99
+ removed: string[];
100
+ revision: string;
101
+ } | {
102
+ reset: true;
103
+ revision: string;
104
+ };
105
+ export interface AppHello {
106
+ protocol: 2;
107
+ guest: boolean;
108
+ features: string[];
109
+ root: string;
110
+ }
111
+ export type AppRequest2 = AppRequest | {
112
+ method: "host.hello";
113
+ protocol: 2;
114
+ sdk: string;
115
+ } | {
116
+ method: "ui.progress";
117
+ value: number;
118
+ } | {
119
+ method: "app.save.get" | "cards.packs" | "player.get";
120
+ } | {
121
+ method: "app.save.set";
122
+ value: AppValue;
123
+ } | {
124
+ method: "cards.list";
125
+ pack?: string;
126
+ after?: string;
127
+ } | {
128
+ method: "cards.pack" | "pack.show";
129
+ pack: string;
130
+ } | {
131
+ method: "display.maximize" | "display.fullscreen" | "cards.watch";
132
+ on: boolean;
133
+ };
134
+ export type AppMethod2 = AppRequest2["method"];
135
+ /** L loading (before ready), F ready and in front, B behind another window (the grace). */
136
+ type States = "LFB" | "L" | "F";
137
+ interface MethodRule {
138
+ request: number;
139
+ response: number;
140
+ rate?: readonly [count: number, windowMs: number];
141
+ states: States;
142
+ }
143
+ /**
144
+ * Request and response JSON bounds (of the request object and the result), the soft rate (answered `rate-limited`) and the
145
+ * states each method is answered in (otherwise `not-permitted`). The hard session limits apply on top. `cards.watch`
146
+ * is this package's addition to the contract's table: it is how the host learns the app has an `onCards` listener.
147
+ */
148
+ 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. */
150
+ export declare const APP_FEATURES_2: readonly string[];
151
+ export declare const utf8Bytes: (text: string) => number;
152
+ /** An error with one of the nine codes, raised by the host's services or the controller and answered without ending the session. */
153
+ export declare class AppHostError extends Error {
154
+ readonly code: OsErrorCode;
155
+ constructor(code: OsErrorCode, message: string);
156
+ }
157
+ /**
158
+ * The save rule (section 8.2): any JSON value, at most 1 MiB as UTF-8 JSON, containers nested at most 64 deep (the root is
159
+ * level 1), finite numbers, plain data only (no accessors, symbols, sparse arrays or class instances). Returns the JSON
160
+ * text, or throws an AppHostError coded `invalid` or `too-large`.
161
+ */
162
+ export declare function saveJson(input: unknown): string;
163
+ /** A save value read back from JSON text (the host's store), checked by the same rule. */
164
+ export declare function saveValue(text: string): AppValue;
165
+ /** The art path of a card or a cover, as the host must send it. */
166
+ /**
167
+ * The one extension of every card, cover and player-picture path (owner decision 2026-11-23): Cloudflare caches `.bin` by
168
+ * default and no zone rule rewrites its cache headers. The real type is the response's Content-Type. Mirrors the wire's
169
+ * `APP_ART_EXTENSION` (vibemarket/steam/os-apps.ts); the website answers only these exact forms.
170
+ */
171
+ export declare const ART_EXTENSION = ".bin";
172
+ export declare const cardArtPath: (pack: string, card: string) => string;
173
+ export declare const coverArtPath: (pack: string) => string;
174
+ export declare const playerPicturePath: (handle: string) => string;
175
+ /** Strict shapes: anything more than these fields is refused, so nothing private can ride along (invariant 15). */
176
+ export declare function wireCard(value: unknown): WireCard;
177
+ export declare function wirePackCard(value: unknown): WirePackCard;
178
+ export declare function wirePackSummary(value: unknown): WirePackSummary;
179
+ export declare function wirePack(value: unknown): WirePack;
180
+ /** A player as the host sends it: `picture` is the path after the version prefix; the SDK makes it absolute. */
181
+ export declare function wirePlayer(value: unknown): Player;
182
+ export declare const cardsRevision: (value: unknown) => value is string;
183
+ export declare function wireCardsEvent(value: unknown): AppCardsEvent;
184
+ export declare function wireHello(value: unknown): AppHello;
185
+ /** The version prefix relative to the entry document: `./` for `index.html`, `../` for `app/index.html`. */
186
+ export declare const entryRoot: (entry: string) => string;
187
+ /**
188
+ * A protocol 2 request, structurally checked (a violation ends the session). Values a well-behaved client could still get
189
+ * wrong (a bad slug, a save over the limit) are left for the controller to answer `invalid` or `too-large`.
190
+ */
191
+ export declare function appRequest2(request: Record<string, unknown>): AppRequest2 | null;
192
+ /** The protocol 1 bound of a method of protocol 1, the table's bound otherwise. */
193
+ export declare function methodRule(method: AppMethod2): MethodRule;
194
+ export {};
@@ -0,0 +1,253 @@
1
+ /**
2
+ * Protocol 2 of the app channel (VM_OS_APPS_3.md section 11.4): the messages a 0.5 client and an apps3 host exchange after
3
+ * `host.hello`, their per-method size bounds, rates and window states, and the card, pack and player shapes an app sees.
4
+ * Pure data and validators with no DOM or Node dependency, shared by the host (app-host.ts) and the client (os.ts).
5
+ */
6
+ import { gameFinishInput } from "./completion.js";
7
+ import { APP_LIMITS, 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"];
11
+ export const osErrorCode = (value) => typeof value === "string" && OS_ERROR_CODES.includes(value);
12
+ /** Session-wide numbers of an apps3 host and a protocol 2 client (sections 9 and 10.1). */
13
+ export const APP_SESSION_LIMITS = Object.freeze({
14
+ /** no user activation and no app request for this long while in front: the host asks "Still playing?" */
15
+ idleMs: 15 * 60 * 1000,
16
+ /** absolute controller life */
17
+ sessionMs: 4 * 60 * 60 * 1000,
18
+ requestsPerSecond: 10, requestsPerMinute: 120, lifetimeRequests: 30_000,
19
+ /** in flight: protocol 1 sessions keep APP_LIMITS.inFlight */
20
+ inFlight: 8,
21
+ /** ready() within this, or progress() at least this often ... */
22
+ readyMs: 15_000,
23
+ /** ... and ready() within this */
24
+ progressReadyMs: 120_000,
25
+ /** one save: UTF-8 JSON bytes and nesting depth (the root container is level 1) */
26
+ saveBytes: 1_048_576, saveDepth: 64,
27
+ /** at most one save write per this interval; the SDK coalesces calls made sooner */
28
+ saveIntervalMs: 10_000,
29
+ /** the largest protocol 2 message: a save plus its envelope */
30
+ messageBytes: 1_100_000 + 1024,
31
+ cardsPage: 500, cardsEventBytes: 256 * 1024,
32
+ /** the client's own pacing, below the host's hard limits (see transport.ts) */
33
+ clientPerSecond: 8, clientPerMinute: 100,
34
+ /** a player token is reused while more than this remains */
35
+ tokenReuseMs: 60_000,
36
+ });
37
+ export const RARITIES = ["common", "rare", "epic", "legendary", "mythic"];
38
+ /** A card's id inside its pack, as the creator card rule admits it. */
39
+ export const CARD_ID = /^[A-Za-z0-9_-]{1,64}$/;
40
+ /**
41
+ * The rules a player's fields follow on the wire, as the backend's `vibemarket/steam/os-apps.ts` (`appPlayerSchema`,
42
+ * `parseAppIdentity`) admits them: a handle or @name of 3 to 15 lowercase letters, digits and underscores (`username` only when
43
+ * it differs from `handle`), a display name of 1 to 64 UTF-16 code units without control characters, the picture as
44
+ * exactly `-/player/<handle>.bin` under the version prefix, and a three-part JWT of at most 1,500 characters.
45
+ */
46
+ 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 });
47
+ const KiB = 1024;
48
+ /**
49
+ * Request and response JSON bounds (of the request object and the result), the soft rate (answered `rate-limited`) and the
50
+ * states each method is answered in (otherwise `not-permitted`). The hard session limits apply on top. `cards.watch`
51
+ * is this package's addition to the contract's table: it is how the host learns the app has an `onCards` listener.
52
+ */
53
+ export const APP_METHODS_2 = Object.freeze({
54
+ "host.hello": { request: 256, response: KiB, states: "LFB" },
55
+ "ui.progress": { request: 64, response: 64, rate: [4, 1000], states: "LFB" },
56
+ "app.save.get": { request: 64, response: 1_100_000, rate: [6, 60_000], states: "LFB" },
57
+ "app.save.set": { request: 1_100_000, response: 256, rate: [1, 10_000], states: "LFB" },
58
+ "cards.list": { request: 256, response: 256 * KiB, rate: [30, 60_000], states: "LFB" },
59
+ "cards.packs": { request: 64, response: 64 * KiB, rate: [30, 60_000], states: "LFB" },
60
+ "cards.pack": { request: 128, response: 64 * KiB, rate: [30, 60_000], states: "LFB" },
61
+ "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" },
63
+ "player.get": { request: 64, response: 2 * KiB, rate: [10, 60_000], states: "LFB" },
64
+ "display.maximize": { request: 64, response: 64, rate: [2, 1000], states: "F" },
65
+ "display.fullscreen": { request: 64, response: 64, rate: [1, 1000], states: "F" },
66
+ });
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"));
69
+ const encoder = new TextEncoder();
70
+ export const utf8Bytes = (text) => encoder.encode(text).byteLength;
71
+ const plain = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
72
+ && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
73
+ const keysExactly = (value, required, optional = []) => {
74
+ const own = Reflect.ownKeys(value);
75
+ return own.every(key => typeof key === "string" && (required.includes(key) || optional.includes(key)) && "value" in Object.getOwnPropertyDescriptor(value, key))
76
+ && required.every(key => Object.hasOwn(value, key));
77
+ };
78
+ /** An error with one of the nine codes, raised by the host's services or the controller and answered without ending the session. */
79
+ export class AppHostError extends Error {
80
+ code;
81
+ constructor(code, message) { super(message); this.name = "AppHostError"; this.code = code; }
82
+ }
83
+ /**
84
+ * The save rule (section 8.2): any JSON value, at most 1 MiB as UTF-8 JSON, containers nested at most 64 deep (the root is
85
+ * level 1), finite numbers, plain data only (no accessors, symbols, sparse arrays or class instances). Returns the JSON
86
+ * text, or throws an AppHostError coded `invalid` or `too-large`.
87
+ */
88
+ export function saveJson(input) {
89
+ const invalid = (message) => new AppHostError("invalid", message);
90
+ const visit = (value, depth) => {
91
+ if (value === null || typeof value === "boolean" || typeof value === "string")
92
+ return;
93
+ if (typeof value === "number") {
94
+ if (!Number.isFinite(value))
95
+ throw invalid("A save's numbers must be finite.");
96
+ return;
97
+ }
98
+ if (typeof value !== "object")
99
+ throw invalid("A save must contain only JSON values.");
100
+ if (depth > APP_SESSION_LIMITS.saveDepth)
101
+ throw invalid(`A save nests at most ${APP_SESSION_LIMITS.saveDepth} levels deep.`);
102
+ if (Array.isArray(value)) {
103
+ if (Reflect.ownKeys(value).length !== value.length + 1)
104
+ throw invalid("A save's arrays cannot have extra properties.");
105
+ for (let index = 0; index < value.length; index++) {
106
+ const item = Object.getOwnPropertyDescriptor(value, index);
107
+ if (!item || !("value" in item))
108
+ throw invalid("A save's arrays cannot be sparse or have accessors.");
109
+ visit(item.value, depth + 1);
110
+ }
111
+ return;
112
+ }
113
+ if (!plain(value))
114
+ throw invalid("A save must contain only plain objects, arrays and JSON values.");
115
+ for (const key of Reflect.ownKeys(value)) {
116
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
117
+ if (typeof key !== "string" || !descriptor || !("value" in descriptor) || !descriptor.enumerable)
118
+ throw invalid("A save's properties must be plain enumerable data.");
119
+ visit(descriptor.value, depth + 1);
120
+ }
121
+ };
122
+ visit(input, 1);
123
+ const text = JSON.stringify(input);
124
+ if (utf8Bytes(text) > APP_SESSION_LIMITS.saveBytes)
125
+ throw new AppHostError("too-large", `A save is at most ${APP_SESSION_LIMITS.saveBytes.toLocaleString("en-US")} bytes of JSON.`);
126
+ return text;
127
+ }
128
+ /** A save value read back from JSON text (the host's store), checked by the same rule. */
129
+ export function saveValue(text) {
130
+ let value;
131
+ try {
132
+ value = JSON.parse(text);
133
+ }
134
+ catch {
135
+ throw new AppHostError("invalid", "The saved data is not JSON.");
136
+ }
137
+ saveJson(value);
138
+ return value;
139
+ }
140
+ const string = (value, max, min = 0) => typeof value === "string" && value.length >= min && value.length <= max;
141
+ const whole = (value, min, max) => typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
142
+ const rarity = (value) => typeof value === "string" && RARITIES.includes(value);
143
+ /** The art path of a card or a cover, as the host must send it. */
144
+ /**
145
+ * The one extension of every card, cover and player-picture path (owner decision 2026-11-23): Cloudflare caches `.bin` by
146
+ * default and no zone rule rewrites its cache headers. The real type is the response's Content-Type. Mirrors the wire's
147
+ * `APP_ART_EXTENSION` (vibemarket/steam/os-apps.ts); the website answers only these exact forms.
148
+ */
149
+ export const ART_EXTENSION = ".bin";
150
+ export const cardArtPath = (pack, card) => `-/card/${pack}/${card}${ART_EXTENSION}`;
151
+ export const coverArtPath = (pack) => `-/cover/${pack}${ART_EXTENSION}`;
152
+ export const playerPicturePath = (handle) => `-/player/${handle}${ART_EXTENSION}`;
153
+ function cardShape(value, counted) {
154
+ if (!plain(value) || !keysExactly(value, counted ? ["id", "pack", "name", "rarity", "count", "art"] : ["id", "pack", "name", "rarity", "art"]))
155
+ throw Error("Invalid card.");
156
+ const { id, pack, name, art } = value, card = typeof id === "string" ? id.slice(id.indexOf("/") + 1) : "";
157
+ if (!packSlug(pack) || id !== `${pack}/${card}` || !CARD_ID.test(card) || !string(name, 120) || !rarity(value.rarity)
158
+ || (counted && !whole(value.count, 1, 1_000_000)) || (art !== null && art !== cardArtPath(pack, card)))
159
+ throw Error("Invalid card.");
160
+ return { id, pack, name, rarity: value.rarity, ...(counted ? { count: value.count } : {}), art };
161
+ }
162
+ /** Strict shapes: anything more than these fields is refused, so nothing private can ride along (invariant 15). */
163
+ export function wireCard(value) { return cardShape(value, true); }
164
+ export function wirePackCard(value) { return cardShape(value, false); }
165
+ function packHead(value) {
166
+ const { id, name, creator, art, total } = value;
167
+ if (!packSlug(id) || !string(name, 120, 1) || (creator !== null && !string(creator, 64, 1)) || (art !== null && art !== coverArtPath(id)) || !whole(total, 0, 10_000))
168
+ throw Error("Invalid pack.");
169
+ return { id, name, creator, art, total };
170
+ }
171
+ export function wirePackSummary(value) {
172
+ if (!plain(value) || !keysExactly(value, ["id", "name", "creator", "art", "held", "total"]) || !whole(value.held, 0, 10_000))
173
+ throw Error("Invalid pack.");
174
+ const head = packHead(value);
175
+ return { id: head.id, name: head.name, creator: head.creator, art: head.art, held: value.held, total: head.total };
176
+ }
177
+ export function wirePack(value) {
178
+ if (!plain(value) || !keysExactly(value, ["id", "name", "creator", "art", "total", "cards"]) || !Array.isArray(value.cards) || value.cards.length > 10_000)
179
+ throw Error("Invalid pack.");
180
+ const head = packHead(value), cards = value.cards.map(wirePackCard);
181
+ if (cards.some(card => card.pack !== head.id))
182
+ throw Error("Invalid pack.");
183
+ return { ...head, cards };
184
+ }
185
+ const CONTROL = /[\u0000-\u001F\u007F-\u009F]/;
186
+ const handleOf = (value) => typeof value === "string" && PLAYER_RULES.handle.test(value);
187
+ /** A player as the host sends it: `picture` is the path after the version prefix; the SDK makes it absolute. */
188
+ export function wirePlayer(value) {
189
+ if (plain(value) && keysExactly(value, ["guest"]) && value.guest === true)
190
+ return { guest: true };
191
+ if (!plain(value) || !keysExactly(value, ["guest", "handle", "name", "picture"], ["username", "token", "expiresAt"]) || value.guest !== false)
192
+ throw Error("Invalid player.");
193
+ const { handle, username, name, picture, token, expiresAt } = value;
194
+ if (!handleOf(handle) || !string(name, PLAYER_RULES.nameMax, 1) || CONTROL.test(name) || (username !== undefined && (!handleOf(username) || username === handle))
195
+ || (picture !== null && picture !== playerPicturePath(handle))
196
+ || ("token" in value) !== ("expiresAt" in value)
197
+ || (token !== undefined && (!string(token, PLAYER_RULES.tokenMax, PLAYER_RULES.tokenMin) || !PLAYER_RULES.token.test(token) || !whole(expiresAt, 0, Number.MAX_SAFE_INTEGER))))
198
+ throw Error("Invalid player.");
199
+ return { guest: false, handle, ...(username === undefined ? {} : { username: username }), name: name, picture: picture,
200
+ ...(token === undefined ? {} : { token: token, expiresAt: expiresAt }) };
201
+ }
202
+ export const cardsRevision = (value) => string(value, 64, 1);
203
+ export function wireCardsEvent(value) {
204
+ if (plain(value) && keysExactly(value, ["reset", "revision"]) && value.reset === true && cardsRevision(value.revision))
205
+ return { reset: true, revision: value.revision };
206
+ if (!plain(value) || !keysExactly(value, ["changed", "removed", "revision"]) || !Array.isArray(value.changed) || !Array.isArray(value.removed) || !cardsRevision(value.revision)
207
+ || value.removed.some(id => !string(id, 130, 3)))
208
+ throw Error("Invalid cards event.");
209
+ return { changed: value.changed.map(wireCard), removed: value.removed, revision: value.revision };
210
+ }
211
+ export function wireHello(value) {
212
+ if (!plain(value) || !keysExactly(value, ["protocol", "guest", "features", "root"]) || value.protocol !== 2 || typeof value.guest !== "boolean"
213
+ || !Array.isArray(value.features) || value.features.length > 64 || value.features.some(feature => !string(feature, 40, 1))
214
+ || typeof value.root !== "string" || !/^(?:\.\/|(?:\.\.\/){1,32})$/.test(value.root))
215
+ throw Error("Invalid hello.");
216
+ return { protocol: 2, guest: value.guest, features: value.features, root: value.root };
217
+ }
218
+ /** The version prefix relative to the entry document: `./` for `index.html`, `../` for `app/index.html`. */
219
+ export const entryRoot = (entry) => entry.includes("/") ? "../".repeat(entry.split("/").length - 1) : "./";
220
+ /**
221
+ * A protocol 2 request, structurally checked (a violation ends the session). Values a well-behaved client could still get
222
+ * wrong (a bad slug, a save over the limit) are left for the controller to answer `invalid` or `too-large`.
223
+ */
224
+ export function appRequest2(request) {
225
+ const method = request.method, only = (...keys) => keysExactly(request, ["method", ...keys]);
226
+ switch (method) {
227
+ case "ui.ready":
228
+ case "app.checkpoint.get": return only() ? { method } : null;
229
+ case "game.finish": return only("score") ? { method, ...gameFinishInput({ score: request.score }) } : null;
230
+ case "app.checkpoint.set": return only("value") ? { method, value: checkpointValue(request.value) } : null;
231
+ 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
+ case "ui.progress": return only("value") && typeof request.value === "number" && Number.isFinite(request.value) ? { method, value: request.value } : null;
233
+ case "app.save.get":
234
+ case "cards.packs":
235
+ case "player.get": return only() ? { method } : null;
236
+ case "app.save.set": return only("value") ? { method, value: request.value } : null;
237
+ case "cards.list": {
238
+ if (!keysExactly(request, ["method"], ["pack", "after"]) || ("pack" in request && !string(request.pack, 64, 1)) || ("after" in request && !string(request.after, 64, 1)))
239
+ return null;
240
+ return { method, ...("pack" in request ? { pack: request.pack } : {}), ...("after" in request ? { after: request.after } : {}) };
241
+ }
242
+ case "cards.pack":
243
+ case "pack.show": return only("pack") && string(request.pack, 64, 1) ? { method, pack: request.pack } : null;
244
+ case "display.maximize":
245
+ case "display.fullscreen":
246
+ case "cards.watch": return only("on") && typeof request.on === "boolean" ? { method, on: request.on } : null;
247
+ default: return null;
248
+ }
249
+ }
250
+ /** The protocol 1 bound of a method of protocol 1, the table's bound otherwise. */
251
+ export function methodRule(method) {
252
+ return Object.hasOwn(APP_METHODS_2, method) ? APP_METHODS_2[method] : { request: APP_LIMITS.requestBytes, response: APP_LIMITS.responseBytes, states: "LFB" };
253
+ }
@@ -0,0 +1,2 @@
1
+ /** The no-bundler build's entry: `dist/vibemarket-os.js` exposes exactly these as the global `VibemarketOS`. */
2
+ export { connect, OsError } from "./os.ts";
@@ -0,0 +1,2 @@
1
+ /** The no-bundler build's entry: `dist/vibemarket-os.js` exposes exactly these as the global `VibemarketOS`. */
2
+ export { connect, OsError } from "./os.js";
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 { assetPath, GAME_LIMITS, parseManifest } from "./manifest.js";
5
+ import { APP_BUNDLE_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",
@@ -47,7 +47,7 @@ export async function readBuiltBundle(directory) {
47
47
  const folded = new Set();
48
48
  async function walk(relative) {
49
49
  for await (const entry of await opendir(path.join(root, relative))) {
50
- if (++entries > GAME_LIMITS.files)
50
+ if (++entries > APP_BUNDLE_LIMITS.files)
51
51
  throw Error("App exceeds bundle entry limits.");
52
52
  const name = entry.name;
53
53
  const file = relative ? `${relative}/${name}` : name;
@@ -63,7 +63,7 @@ export async function readBuiltBundle(directory) {
63
63
  await walk(file);
64
64
  continue;
65
65
  }
66
- if (!stat.isFile() || !assetType(file) || stat.size > GAME_LIMITS.file || (size += stat.size) > GAME_LIMITS.expanded)
66
+ if (!stat.isFile() || !assetType(file) || stat.size > APP_BUNDLE_LIMITS.file || (size += stat.size) > APP_BUNDLE_LIMITS.expanded)
67
67
  throw Error("App exceeds bundle limits or contains unsupported files.");
68
68
  files[file] = await readBoundedAsset(path.join(root, file), stat.size);
69
69
  }
@@ -75,11 +75,11 @@ export async function readBuiltBundle(directory) {
75
75
  const manifest = parseManifest(JSON.parse(new TextDecoder().decode(input)));
76
76
  if (!files[manifest.entry])
77
77
  throw Error("Manifest entry is missing from the app bundle.");
78
- if (manifest.schemaVersion === 2) {
79
- // SVG is a document format that can carry script; schema version 2 bundles are served by the store runtime.
78
+ if (manifest.schemaVersion !== 1) {
79
+ // SVG is a document format that can carry script; schema version 2 and 3 bundles are served by the store runtime.
80
80
  const svg = Object.keys(files).sort(compareAssetNames).find(file => assetType(file) === TYPES.svg);
81
81
  if (svg)
82
- throw Error(`Schema version 2 apps cannot contain SVG files; convert ${svg} to PNG or WebP.`);
82
+ throw Error(`Schema version ${manifest.schemaVersion} apps cannot contain SVG files; convert ${svg} to PNG or WebP.`);
83
83
  const listing = checkListing(manifest, files);
84
84
  if (!listing.ok)
85
85
  throw Error(`Store listing (${listing.code}): ${listing.message}`);
package/dist/canvas.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { LifecycleSource } from "./loop.ts";
1
+ import { type LifecycleSource, type OsLifecycle } from "./loop.ts";
2
2
  export interface CanvasFit {
3
3
  /** Backing-store size in device pixels. */
4
4
  width: number;
@@ -35,6 +35,6 @@ export interface FittedCanvas {
35
35
  * cleared) only when the computed size actually changes. Style the canvas to fill the
36
36
  * app; this sets only its `width` and `height`.
37
37
  */
38
- export declare function fitCanvas(app: LifecycleSource, canvas: FitTarget, options?: FitOptions, view?: {
38
+ export declare function fitCanvas(source: LifecycleSource | OsLifecycle, canvas: FitTarget, options?: FitOptions, view?: {
39
39
  devicePixelRatio: number;
40
40
  }): FittedCanvas;
package/dist/canvas.js CHANGED
@@ -1,10 +1,12 @@
1
+ import { lifecycleSource } from "./loop.js";
1
2
  /**
2
3
  * Keep a canvas backing store matched to the host surface, with the pixel ratio capped
3
4
  * so a high-density display cannot multiply the fill cost. The canvas is resized (and so
4
5
  * cleared) only when the computed size actually changes. Style the canvas to fill the
5
6
  * app; this sets only its `width` and `height`.
6
7
  */
7
- export function fitCanvas(app, canvas, options = {}, view = window) {
8
+ export function fitCanvas(source, canvas, options = {}, view = window) {
9
+ const app = lifecycleSource(source);
8
10
  const maxRatio = options.maxPixelRatio ?? 2, maxPixels = options.maxPixels ?? 3840 * 2160;
9
11
  if (!Number.isFinite(maxRatio) || maxRatio < 1 || maxRatio > 4)
10
12
  throw Error("maxPixelRatio must be from 1 to 4.");
@@ -0,0 +1,12 @@
1
+ import { APP_BUNDLE_LIMITS } from "./manifest.ts";
2
+ type BundleLimits = {
3
+ readonly [K in keyof typeof APP_BUNDLE_LIMITS]: number;
4
+ };
5
+ export interface CheckReport {
6
+ problems: string[];
7
+ notices: string[];
8
+ bundle: string | null;
9
+ }
10
+ /** `limits` is the store's; a test passes smaller ones. */
11
+ export declare function checkApp(directory: string, limits?: BundleLimits): Promise<CheckReport>;
12
+ export {};