@vibechain/os 0.4.0 → 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.
- package/AGENTS.md +139 -208
- package/README.md +131 -54
- package/SECURITY.md +45 -20
- package/dist/app-client.d.ts +4 -1
- package/dist/app-client.js +4 -1
- package/dist/app-host.d.ts +111 -9
- package/dist/app-host.js +339 -58
- package/dist/app-protocol.d.ts +2 -0
- package/dist/app-runtime.d.ts +18 -2
- package/dist/app-runtime.js +75 -11
- package/dist/app-wire.d.ts +194 -0
- package/dist/app-wire.js +253 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +2 -0
- package/dist/bundle.js +6 -6
- package/dist/canvas.d.ts +2 -2
- package/dist/canvas.js +3 -1
- package/dist/check.d.ts +12 -0
- package/dist/check.js +167 -0
- package/dist/cli-publish.d.ts +24 -0
- package/dist/cli-publish.js +288 -0
- package/dist/cli-session.d.ts +108 -0
- package/dist/cli-session.js +245 -0
- package/dist/cli.d.ts +10 -0
- package/dist/cli.js +46 -10
- package/dist/index.d.ts +5 -0
- package/dist/index.js +3 -0
- package/dist/listing.d.ts +3 -3
- package/dist/listing.js +1 -1
- package/dist/loop.d.ts +18 -2
- package/dist/loop.js +13 -1
- package/dist/manifest.d.ts +90 -4
- package/dist/manifest.js +340 -5
- package/dist/os.d.ts +56 -0
- package/dist/os.js +354 -0
- package/dist/preview-parent.d.ts +36 -0
- package/dist/preview-parent.js +122 -11
- package/dist/preview-ui.js +1 -1
- package/dist/preview.js +25 -7
- package/dist/redact.d.ts +6 -0
- package/dist/redact.js +16 -0
- package/dist/runtime-policy.d.ts +20 -0
- package/dist/runtime-policy.js +45 -0
- package/dist/scaffold.d.ts +13 -2
- package/dist/scaffold.js +99 -29
- package/dist/submit-notice.d.ts +26 -0
- package/dist/submit-notice.js +34 -0
- package/dist/templates/plain/game.js +18 -0
- package/dist/testing.d.ts +63 -0
- package/dist/testing.js +157 -1
- package/dist/transport.d.ts +20 -0
- package/dist/transport.js +71 -19
- package/dist/vibemarket-os.js +1 -0
- package/dist/worker.d.ts +18 -0
- package/dist/worker.js +34 -0
- package/examples/paw-beat/README.md +20 -8
- package/examples/paw-beat/cat.ts +665 -89
- package/examples/paw-beat/game.ts +162 -28
- package/examples/paw-beat/index.html +114 -40
- package/examples/paw-beat/main.ts +264 -149
- package/examples/paw-beat/music.ts +314 -65
- package/examples/paw-beat/stage.ts +560 -0
- package/examples/paw-beat/store/icon.png +0 -0
- package/examples/paw-beat/store/screenshot-1.webp +0 -0
- package/examples/paw-beat/store/screenshot-2.webp +0 -0
- package/examples/paw-beat/vibemarket.json +2 -2
- package/examples/vibexp-app/README.md +20 -4
- package/examples/vibexp-app/index.html +3 -2
- package/examples/vibexp-app/plain/game.ts +20 -0
- package/examples/vibexp-app/plain/index.html +6 -0
- package/examples/vibexp-app/plain/vibemarket.json +17 -0
- package/examples/vibexp-app/src/main.ts +46 -31
- package/examples/vibexp-app/store/icon.png +0 -0
- package/examples/vibexp-app/store/screenshot-1.png +0 -0
- package/examples/vibexp-app/three/README.md +21 -0
- package/examples/vibexp-app/three/index.html +4 -0
- package/examples/vibexp-app/three/src/main.ts +45 -0
- package/examples/vibexp-app/three/vibemarket.json +19 -0
- package/examples/vibexp-app/vibemarket.json +27 -1
- package/package.json +8 -3
- package/examples/chonk-stack/card-slice.ts +0 -17
- package/examples/chonk-stack/cat3d.ts +0 -57
- package/examples/chonk-stack/game.css +0 -174
- package/examples/chonk-stack/index.html +0 -32
- package/examples/chonk-stack/main.ts +0 -149
- package/examples/chonk-stack/model.ts +0 -40
- package/examples/chonk-stack/renderer.ts +0 -263
- package/examples/chonk-stack/skins.ts +0 -47
- package/examples/chonk-stack/vibemarket.json +0 -21
- package/examples/collection-room/index.html +0 -3
- package/examples/collection-room/main.ts +0 -31
- package/examples/collection-room/vibemarket.json +0 -12
- package/examples/tsconfig.json +0 -4
package/dist/app-host.d.ts
CHANGED
|
@@ -1,31 +1,133 @@
|
|
|
1
1
|
import type { GameFinishInput } from "./completion.ts";
|
|
2
2
|
import { type AppLifecycle } from "./app-protocol.ts";
|
|
3
|
+
import { type Player, type WireCard, type WirePack, type WirePackSummary } from "./app-wire.ts";
|
|
3
4
|
export interface AppSession {
|
|
4
5
|
lifecycle(value: AppLifecycle): void;
|
|
5
6
|
close(): void;
|
|
6
7
|
}
|
|
8
|
+
/**
|
|
9
|
+
* `current`: this generation is the live one (its frame is mounted for this app and the page is shown). `foreground`: its
|
|
10
|
+
* window is in front. A generation that is current but not in the foreground is backgrounded: the host keeps its frame
|
|
11
|
+
* for a grace period and has told it `active: false`. While backgrounded, reads are answered (`ui.ready`,
|
|
12
|
+
* `app.checkpoint.get`), but writes (`game.finish`, `app.checkpoint.set`) are withheld: not applied and not answered, as
|
|
13
|
+
* for a suspended app whose session is gone (the app's own request times out). They still count against every request
|
|
14
|
+
* limit. Without `foreground` a generation is always in the foreground, as before. `progress`: a protocol 2 app reported
|
|
15
|
+
* loading progress (0 to 1) before it was ready.
|
|
16
|
+
*/
|
|
17
|
+
export interface AppAttachOptions {
|
|
18
|
+
current: () => boolean;
|
|
19
|
+
foreground?: () => boolean;
|
|
20
|
+
ready: () => void;
|
|
21
|
+
finish?: (result: Readonly<GameFinishInput>) => void;
|
|
22
|
+
fault: (message: string) => void;
|
|
23
|
+
progress?: (fraction: number) => void;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The I/O an apps3 host (the desk, the preview, a test) supplies for protocol 2, one object per open app. The controller
|
|
27
|
+
* owns the protocol (shapes, sizes, rates, window states, paging, coalescing rules, card diffs); these functions own
|
|
28
|
+
* permission and storage. Throw an AppHostError to answer a code (`not-permitted` for `cards: "none"`, `needs-click`
|
|
29
|
+
* without a fresh activation, `too-large` for the account's 8 MiB, `rate-limited`); any other throw answers `unavailable`.
|
|
30
|
+
* Every value they return is re-checked against the strict wire shapes before it reaches the app.
|
|
31
|
+
*/
|
|
32
|
+
export interface AppHostServices {
|
|
33
|
+
/** whether the player is a guest (their save lives only while the window is open) */
|
|
34
|
+
readonly guest: boolean;
|
|
35
|
+
/** the manifest's entry, so art paths resolve against the version prefix */
|
|
36
|
+
readonly entry: string;
|
|
37
|
+
/** the stored save as JSON text, or nulls; prefetched on open */
|
|
38
|
+
saveGet(): Promise<{
|
|
39
|
+
value: string | null;
|
|
40
|
+
savedAt: string | null;
|
|
41
|
+
}>;
|
|
42
|
+
/** store JSON text (already checked: at most 1 MiB, depth 64) */
|
|
43
|
+
saveSet(text: string): Promise<{
|
|
44
|
+
savedAt: string;
|
|
45
|
+
}>;
|
|
46
|
+
/** the permitted holdings, whole, with the revision of the answer; throw `not-permitted` for `cards: "none"` */
|
|
47
|
+
cards(): Promise<{
|
|
48
|
+
cards: WireCard[];
|
|
49
|
+
revision: string;
|
|
50
|
+
}>;
|
|
51
|
+
/** the permitted packs with what the player holds of each */
|
|
52
|
+
packs(): Promise<WirePackSummary[]>;
|
|
53
|
+
/** one pack's public card list, for a pack the app may read */
|
|
54
|
+
pack(slug: string): Promise<WirePack>;
|
|
55
|
+
/** open the market window on a pack (check activation and permission) */
|
|
56
|
+
showPack(slug: string): Promise<void>;
|
|
57
|
+
/** the player's public identity (`picture` as a path after the version prefix), or `{ guest: true }`; `token` and `expiresAt` only for an app that declares `network` */
|
|
58
|
+
player(): Promise<Player>;
|
|
59
|
+
maximize(on: boolean): Promise<void>;
|
|
60
|
+
fullscreen(on: boolean): Promise<void>;
|
|
61
|
+
}
|
|
62
|
+
export interface AppControllerOptions {
|
|
63
|
+
/** protocol 2 and the apps3 lifetime (15 minutes idle, 4 hours absolute); without it the controller is exactly protocol 1 */
|
|
64
|
+
services?: AppHostServices;
|
|
65
|
+
/** no activity for 15 minutes: show "Still playing?" and call `activity()` on an answer, or tear down */
|
|
66
|
+
idle?: () => void;
|
|
67
|
+
}
|
|
7
68
|
export interface AppController {
|
|
8
|
-
attach(port: MessagePort, session: string, options:
|
|
9
|
-
current: () => boolean;
|
|
10
|
-
ready: () => void;
|
|
11
|
-
finish?: (result: Readonly<GameFinishInput>) => void;
|
|
12
|
-
fault: (message: string) => void;
|
|
13
|
-
}): AppSession;
|
|
69
|
+
attach(port: MessagePort, session: string, options: AppAttachOptions): AppSession;
|
|
14
70
|
suspend(): void;
|
|
15
71
|
dispose(): void;
|
|
72
|
+
/** 2 when the host offers protocol 2 (it has services), else 1 */
|
|
73
|
+
readonly protocol?: 1 | 2;
|
|
74
|
+
/** the host saw user activation in the app's window (sampled while it is in front); resets the idle timer */
|
|
75
|
+
activity?(): void;
|
|
76
|
+
/** holdings may have changed (a pull, gift, trade, or the window returned to the front): diff and tell a watching app */
|
|
77
|
+
cardsChanged?(): Promise<void>;
|
|
16
78
|
}
|
|
17
79
|
/** A single installation/window owns only the JSON this same app host-accepted. */
|
|
18
|
-
export declare function createAppController(clock?: () => number): AppController;
|
|
80
|
+
export declare function createAppController(clock?: () => number, options?: AppControllerOptions): AppController;
|
|
19
81
|
export interface AppFrameOptions {
|
|
20
82
|
controller: AppController;
|
|
21
83
|
challenge: string;
|
|
22
84
|
current: () => boolean;
|
|
23
85
|
ready: () => void;
|
|
24
86
|
fault: (message: string) => void;
|
|
87
|
+
/** whether the app's window is in front (AppAttachOptions); `setActive` tells the app the same */
|
|
88
|
+
foreground?: () => boolean;
|
|
25
89
|
finish?: (result: Readonly<GameFinishInput>) => void;
|
|
90
|
+
/** protocol 2: the app's loading progress, 0 to 1, for the host's loading bar */
|
|
91
|
+
progress?: (fraction: number) => void;
|
|
26
92
|
}
|
|
27
|
-
/**
|
|
28
|
-
export
|
|
93
|
+
/** One mounted frame. `setActive` sends the app its lifecycle's `active` flag; `resize` keeps it. */
|
|
94
|
+
export interface MountedAppFrame {
|
|
29
95
|
resize(width: number, height: number): void;
|
|
96
|
+
setActive(active: boolean): void;
|
|
30
97
|
dispose(): void;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Caller supplies the already-validated immutable URL, including this generation's fragment. With a protocol 2
|
|
101
|
+
* controller the transfer advertises `protocol: 2`, and readiness is `ready()` within 15 s, or `progress()` at least
|
|
102
|
+
* every 15 s and `ready()` within 120 s.
|
|
103
|
+
*/
|
|
104
|
+
export declare function mountAppFrame(frame: HTMLIFrameElement, options: AppFrameOptions): MountedAppFrame;
|
|
105
|
+
/** The art and pack fields of the backend's card read (`AppCardsReply` in vibemarket/steam/os-apps.ts), structurally. */
|
|
106
|
+
export interface AppCardsReplyShape {
|
|
107
|
+
packs: readonly {
|
|
108
|
+
slug: string;
|
|
109
|
+
name: string;
|
|
110
|
+
creator: string | null;
|
|
111
|
+
total: number;
|
|
112
|
+
held: number;
|
|
113
|
+
cover: boolean;
|
|
114
|
+
}[];
|
|
115
|
+
cards: readonly {
|
|
116
|
+
pack: string;
|
|
117
|
+
card: string;
|
|
118
|
+
name: string;
|
|
119
|
+
rarity: number;
|
|
120
|
+
count: number;
|
|
121
|
+
art: boolean;
|
|
122
|
+
}[];
|
|
123
|
+
revision: string;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The backend's card read as an app sees it, for an apps3 host's services: rarity numbers named, ids joined, and art as the
|
|
127
|
+
* path after the version prefix only where the backend has servable art and the card id can be a path segment.
|
|
128
|
+
*/
|
|
129
|
+
export declare function appCardsView(reply: AppCardsReplyShape): {
|
|
130
|
+
packs: WirePackSummary[];
|
|
131
|
+
cards: WireCard[];
|
|
132
|
+
revision: string;
|
|
31
133
|
};
|
package/dist/app-host.js
CHANGED
|
@@ -1,26 +1,70 @@
|
|
|
1
1
|
import { CHANNEL } from "./channel.js";
|
|
2
2
|
import { appRuntimeRefusal } from "./app-runtime.js";
|
|
3
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";
|
|
5
|
+
import { packSlug } from "./manifest.js";
|
|
6
|
+
/**
|
|
7
|
+
* An apps3 session's request: protocol 1 methods exactly as `parseAppEnvelope` admits them, `host.hello` before hello, and
|
|
8
|
+
* after hello every protocol 2 method within its request bound. Anything else throws (the session ends).
|
|
9
|
+
*/
|
|
10
|
+
function envelope2(data, session, hello) {
|
|
11
|
+
if (!data || typeof data !== "object" || Array.isArray(data) || Object.getPrototypeOf(data) !== Object.prototype || Object.keys(data).length !== 3
|
|
12
|
+
|| !("session" in data) || data.session !== session || !("id" in data) || typeof data.id !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(data.id)
|
|
13
|
+
|| !("request" in data) || !data.request || typeof data.request !== "object" || Array.isArray(data.request))
|
|
14
|
+
throw Error("Invalid app session request.");
|
|
15
|
+
const request = appRequest2(data.request);
|
|
16
|
+
const legacy = request !== null && !Object.hasOwn(APP_METHODS_2, request.method);
|
|
17
|
+
if (!request || (!hello && !legacy && request.method !== "host.hello"))
|
|
18
|
+
throw Error("This app has no permission for that method.");
|
|
19
|
+
if (utf8Bytes(JSON.stringify(data.request)) > methodRule(request.method).request)
|
|
20
|
+
throw Error("App request exceeds its bound.");
|
|
21
|
+
return { id: data.id, request };
|
|
22
|
+
}
|
|
23
|
+
/** A sliding window of recent times, at most `limit` of them within `windowMs`. */
|
|
24
|
+
function slidingWindow(limit, windowMs) {
|
|
25
|
+
let times = [];
|
|
26
|
+
return (now) => {
|
|
27
|
+
times = times.filter(time => now - time < windowMs);
|
|
28
|
+
if (times.length >= limit)
|
|
29
|
+
return false;
|
|
30
|
+
times.push(now);
|
|
31
|
+
return true;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
const MESSAGE = {
|
|
35
|
+
states: "That is not available while the app is loading or behind another window.",
|
|
36
|
+
rate: "Too many requests of that kind; try again later.",
|
|
37
|
+
slug: "That is not a pack slug.",
|
|
38
|
+
after: "That page cursor is not valid.",
|
|
39
|
+
unavailable: "The host could not answer that now; try again.",
|
|
40
|
+
};
|
|
4
41
|
/** A single installation/window owns only the JSON this same app host-accepted. */
|
|
5
|
-
export function createAppController(clock = () => performance.now()) {
|
|
42
|
+
export function createAppController(clock = () => performance.now(), options = {}) {
|
|
43
|
+
const services = options.services, apps3 = services !== undefined;
|
|
6
44
|
let checkpoint = "null", disposed = false, active;
|
|
7
45
|
let completion, completionNotified = false;
|
|
8
46
|
const startedAt = clock();
|
|
9
47
|
if (!Number.isFinite(startedAt))
|
|
10
48
|
throw Error("App clock is invalid.");
|
|
11
|
-
let lastClock = startedAt, intervalAt = startedAt, requests = 0, total = 0;
|
|
49
|
+
let lastClock = startedAt, intervalAt = startedAt, requests = 0, total = 0, lastActivity = startedAt;
|
|
12
50
|
let terminalReason, activeFault;
|
|
51
|
+
let idleTimer, idleNotified = false;
|
|
52
|
+
let cards;
|
|
53
|
+
const perMinute = slidingWindow(APP_SESSION_LIMITS.requestsPerMinute, 60_000);
|
|
54
|
+
const lifetimeMs = apps3 ? APP_SESSION_LIMITS.sessionMs : APP_LIMITS.sessionMs, lifetimeRequests = apps3 ? APP_SESSION_LIMITS.lifetimeRequests : APP_LIMITS.lifetimeRequests;
|
|
55
|
+
const expired = apps3 ? "App session reached its 4-hour limit. Reopen the app to keep playing." : "App session expired. Reopen the app.";
|
|
13
56
|
const terminate = (reason) => {
|
|
14
57
|
if (disposed || terminalReason)
|
|
15
58
|
return;
|
|
16
59
|
terminalReason = reason;
|
|
17
60
|
clearTimeout(expiry);
|
|
61
|
+
clearTimeout(idleTimer);
|
|
18
62
|
checkpoint = "null";
|
|
19
63
|
const fault = activeFault;
|
|
20
64
|
active?.close();
|
|
21
65
|
fault?.(reason);
|
|
22
66
|
};
|
|
23
|
-
const expiry = setTimeout(() => terminate(
|
|
67
|
+
const expiry = setTimeout(() => terminate(expired), lifetimeMs);
|
|
24
68
|
const readTime = () => {
|
|
25
69
|
let now;
|
|
26
70
|
try {
|
|
@@ -35,14 +79,39 @@ export function createAppController(clock = () => performance.now()) {
|
|
|
35
79
|
return undefined;
|
|
36
80
|
}
|
|
37
81
|
lastClock = now;
|
|
38
|
-
if (now - startedAt >=
|
|
39
|
-
terminate(
|
|
82
|
+
if (now - startedAt >= lifetimeMs) {
|
|
83
|
+
terminate(expired);
|
|
40
84
|
return undefined;
|
|
41
85
|
}
|
|
42
86
|
return now;
|
|
43
87
|
};
|
|
44
|
-
|
|
45
|
-
|
|
88
|
+
// apps3 only: the idle prompt after 15 minutes without activity (re-armed by any activity, never extending the 4 hours)
|
|
89
|
+
const armIdle = (delay) => {
|
|
90
|
+
clearTimeout(idleTimer);
|
|
91
|
+
idleTimer = setTimeout(() => {
|
|
92
|
+
const now = readTime();
|
|
93
|
+
if (now === undefined)
|
|
94
|
+
return;
|
|
95
|
+
const quiet = now - lastActivity;
|
|
96
|
+
if (quiet < APP_SESSION_LIMITS.idleMs) {
|
|
97
|
+
armIdle(APP_SESSION_LIMITS.idleMs - quiet);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (!idleNotified) {
|
|
101
|
+
idleNotified = true;
|
|
102
|
+
options.idle?.();
|
|
103
|
+
}
|
|
104
|
+
}, delay);
|
|
105
|
+
};
|
|
106
|
+
const touch = (now) => { lastActivity = now; if (idleNotified) {
|
|
107
|
+
idleNotified = false;
|
|
108
|
+
armIdle(APP_SESSION_LIMITS.idleMs);
|
|
109
|
+
} };
|
|
110
|
+
if (apps3)
|
|
111
|
+
armIdle(APP_SESSION_LIMITS.idleMs);
|
|
112
|
+
const controller = {
|
|
113
|
+
protocol: apps3 ? 2 : 1,
|
|
114
|
+
attach(port, session, attachOptions) {
|
|
46
115
|
if (disposed || terminalReason || !appNonce(session)) {
|
|
47
116
|
port.close();
|
|
48
117
|
throw Error(terminalReason ?? "App controller is closed.");
|
|
@@ -52,23 +121,129 @@ export function createAppController(clock = () => performance.now()) {
|
|
|
52
121
|
throw Error(terminalReason);
|
|
53
122
|
}
|
|
54
123
|
active?.close();
|
|
55
|
-
let stopped = false, inFlight = 0;
|
|
124
|
+
let stopped = false, inFlight = 0, hello = false, ready = false, lastId = 0, saving = false, watching = false;
|
|
125
|
+
let baseline;
|
|
56
126
|
const seen = new Set();
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
127
|
+
const soft = new Map();
|
|
128
|
+
const close = () => {
|
|
129
|
+
if (stopped)
|
|
130
|
+
return;
|
|
131
|
+
stopped = true;
|
|
132
|
+
port.onmessage = null;
|
|
133
|
+
port.onmessageerror = null;
|
|
134
|
+
port.close();
|
|
135
|
+
if (active === handle) {
|
|
136
|
+
active = undefined;
|
|
137
|
+
activeFault = undefined;
|
|
138
|
+
cards = undefined;
|
|
139
|
+
}
|
|
140
|
+
};
|
|
62
141
|
const refuse = (reason) => { if (stopped)
|
|
63
|
-
return; close();
|
|
64
|
-
const current = () => !stopped && !disposed &&
|
|
142
|
+
return; close(); attachOptions.fault(reason); };
|
|
143
|
+
const current = () => !stopped && !disposed && attachOptions.current();
|
|
144
|
+
const foreground = attachOptions.foreground ?? (() => true);
|
|
145
|
+
const send = (value, bytes) => { if (current())
|
|
146
|
+
port.postMessage(appJson(value, bytes)); };
|
|
65
147
|
const handle = {
|
|
66
148
|
lifecycle(value) { if (current())
|
|
67
149
|
port.postMessage(appJson({ session, event: "app.lifecycle", state: lifecycleValue(value) }, APP_LIMITS.responseBytes)); },
|
|
68
150
|
close,
|
|
69
151
|
};
|
|
70
152
|
active = handle;
|
|
71
|
-
activeFault =
|
|
153
|
+
activeFault = attachOptions.fault;
|
|
154
|
+
// A watching app is told what changed since the list it last read whole (or the last event), or to read again.
|
|
155
|
+
if (services)
|
|
156
|
+
cards = async () => {
|
|
157
|
+
if (!watching || !baseline || !current())
|
|
158
|
+
return;
|
|
159
|
+
const next = await services.cards();
|
|
160
|
+
if (!current() || !watching || !baseline || !cardsRevision(next.revision) || next.revision === baseline.revision)
|
|
161
|
+
return;
|
|
162
|
+
const fresh = new Map(next.cards.map(card => { const checked = wireCard(card); return [checked.id, checked]; }));
|
|
163
|
+
const changed = [...fresh.values()].filter(card => JSON.stringify(baseline.cards.get(card.id)) !== JSON.stringify(card));
|
|
164
|
+
const removed = [...baseline.cards.keys()].filter(id => !fresh.has(id));
|
|
165
|
+
let event = { changed, removed, revision: next.revision };
|
|
166
|
+
if (utf8Bytes(JSON.stringify(event)) > APP_SESSION_LIMITS.cardsEventBytes)
|
|
167
|
+
event = { reset: true, revision: next.revision };
|
|
168
|
+
baseline = { revision: next.revision, cards: fresh };
|
|
169
|
+
send({ session, event: "app.cards", state: event }, APP_SESSION_LIMITS.cardsEventBytes + 1024);
|
|
170
|
+
};
|
|
171
|
+
/** One protocol 2 answer. A thrown AppHostError is a soft refusal; anything else from the services is `unavailable`. */
|
|
172
|
+
const answer2 = async (services, request) => {
|
|
173
|
+
const check = (value, valid) => { try {
|
|
174
|
+
return valid(value);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
throw new AppHostError("unavailable", MESSAGE.unavailable);
|
|
178
|
+
} };
|
|
179
|
+
switch (request.method) {
|
|
180
|
+
case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2], root: entryRoot(services.entry) };
|
|
181
|
+
case "ui.progress":
|
|
182
|
+
// ignored once the app is ready
|
|
183
|
+
if (!ready) {
|
|
184
|
+
if (request.value < 0 || request.value > 1)
|
|
185
|
+
throw new AppHostError("invalid", "Progress is a number from 0 to 1.");
|
|
186
|
+
attachOptions.progress?.(request.value);
|
|
187
|
+
}
|
|
188
|
+
return { completed: true };
|
|
189
|
+
case "app.save.get": {
|
|
190
|
+
const stored = await services.saveGet();
|
|
191
|
+
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)
|
|
192
|
+
throw Error(); return value; }) };
|
|
193
|
+
}
|
|
194
|
+
case "app.save.set": {
|
|
195
|
+
const text = saveJson(request.value);
|
|
196
|
+
if (saving)
|
|
197
|
+
throw new AppHostError("rate-limited", "A save is already being written.");
|
|
198
|
+
saving = true;
|
|
199
|
+
try {
|
|
200
|
+
const { savedAt } = await services.saveSet(text);
|
|
201
|
+
return { savedAt: check(savedAt, value => { if (typeof value !== "string" || value.length > 30)
|
|
202
|
+
throw Error(); return value; }) };
|
|
203
|
+
}
|
|
204
|
+
finally {
|
|
205
|
+
saving = false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
case "cards.list": {
|
|
209
|
+
if (request.pack !== undefined && !packSlug(request.pack))
|
|
210
|
+
throw new AppHostError("invalid", MESSAGE.slug);
|
|
211
|
+
const start = request.after === undefined ? 0 : /^(?:0|[1-9]\d{0,5})$/.test(request.after) ? Number(request.after) : -1;
|
|
212
|
+
if (start < 0)
|
|
213
|
+
throw new AppHostError("invalid", MESSAGE.after);
|
|
214
|
+
const all = await services.cards();
|
|
215
|
+
const listed = check(all, value => { if (!cardsRevision(value.revision) || !Array.isArray(value.cards))
|
|
216
|
+
throw Error(); return value.cards.map(wireCard); });
|
|
217
|
+
if (request.pack === undefined && start === 0)
|
|
218
|
+
baseline = { revision: all.revision, cards: new Map(listed.map(card => [card.id, card])) };
|
|
219
|
+
const chosen = request.pack === undefined ? listed : listed.filter(card => card.pack === request.pack);
|
|
220
|
+
const end = start + APP_SESSION_LIMITS.cardsPage;
|
|
221
|
+
return { cards: chosen.slice(start, end), after: end < chosen.length ? String(end) : null, revision: all.revision };
|
|
222
|
+
}
|
|
223
|
+
case "cards.packs": return { packs: check(await services.packs(), value => { if (!Array.isArray(value) || value.length > 200)
|
|
224
|
+
throw Error(); return value.map(wirePackSummary); }) };
|
|
225
|
+
case "cards.pack":
|
|
226
|
+
if (!packSlug(request.pack))
|
|
227
|
+
throw new AppHostError("invalid", MESSAGE.slug);
|
|
228
|
+
return { pack: check(await services.pack(request.pack), value => { const pack = wirePack(value); if (pack.id !== request.pack)
|
|
229
|
+
throw Error(); return pack; }) };
|
|
230
|
+
case "cards.watch":
|
|
231
|
+
watching = request.on;
|
|
232
|
+
return { completed: true };
|
|
233
|
+
case "pack.show":
|
|
234
|
+
if (!packSlug(request.pack))
|
|
235
|
+
throw new AppHostError("invalid", MESSAGE.slug);
|
|
236
|
+
await services.showPack(request.pack);
|
|
237
|
+
return { shown: true };
|
|
238
|
+
case "player.get": return check(await services.player(), wirePlayer);
|
|
239
|
+
case "display.maximize":
|
|
240
|
+
await services.maximize(request.on);
|
|
241
|
+
return { completed: true };
|
|
242
|
+
case "display.fullscreen":
|
|
243
|
+
await services.fullscreen(request.on);
|
|
244
|
+
return { completed: true };
|
|
245
|
+
}
|
|
246
|
+
};
|
|
72
247
|
port.onmessage = (event) => {
|
|
73
248
|
if (!current()) {
|
|
74
249
|
close();
|
|
@@ -81,78 +256,159 @@ export function createAppController(clock = () => performance.now()) {
|
|
|
81
256
|
intervalAt = now;
|
|
82
257
|
requests = 0;
|
|
83
258
|
}
|
|
84
|
-
if (++requests > APP_LIMITS.requestsPerSecond || ++total >
|
|
259
|
+
if (++requests > APP_LIMITS.requestsPerSecond || ++total > lifetimeRequests || inFlight >= (hello ? APP_SESSION_LIMITS.inFlight : APP_LIMITS.inFlight)
|
|
260
|
+
|| (apps3 && !perMinute(now))) {
|
|
85
261
|
refuse("App request limit exceeded.");
|
|
86
262
|
return;
|
|
87
263
|
}
|
|
88
|
-
let
|
|
264
|
+
let id, request;
|
|
89
265
|
try {
|
|
90
|
-
|
|
266
|
+
if (!apps3)
|
|
267
|
+
({ id, request } = parseAppEnvelope(parseAppJson(event.data, APP_LIMITS.requestBytes), session));
|
|
268
|
+
else
|
|
269
|
+
({ id, request } = envelope2(parseAppJson(event.data, hello ? APP_SESSION_LIMITS.messageBytes : APP_LIMITS.requestBytes), session, hello));
|
|
91
270
|
}
|
|
92
271
|
catch {
|
|
93
272
|
refuse("Invalid or unpermitted app request.");
|
|
94
273
|
return;
|
|
95
274
|
}
|
|
96
|
-
if (
|
|
97
|
-
|
|
98
|
-
|
|
275
|
+
if (apps3) {
|
|
276
|
+
// every client this package has shipped numbers its requests 1, 2, 3, ... per session
|
|
277
|
+
if (!/^[1-9]\d{0,15}$/.test(id) || Number(id) <= lastId) {
|
|
278
|
+
refuse("App request was replayed.");
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
lastId = Number(id);
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
if (seen.has(id)) {
|
|
285
|
+
refuse("App request was replayed.");
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
seen.add(id);
|
|
289
|
+
}
|
|
290
|
+
if (request.method === "host.hello") {
|
|
291
|
+
if (hello) {
|
|
292
|
+
refuse("App said hello twice.");
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
hello = true;
|
|
99
296
|
}
|
|
100
|
-
seen.add(message.id);
|
|
101
297
|
inFlight++;
|
|
298
|
+
if (apps3)
|
|
299
|
+
touch(now);
|
|
300
|
+
const method = request.method;
|
|
301
|
+
const legacy = method === "ui.ready" || method === "game.finish" || method === "app.checkpoint.get" || method === "app.checkpoint.set";
|
|
302
|
+
// protocol 1 answers synchronously in the first microtask, exactly as before; protocol 2 returns its promise
|
|
102
303
|
void Promise.resolve().then(() => {
|
|
103
304
|
if (!current())
|
|
104
305
|
return;
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
306
|
+
// backgrounded: a write is withheld exactly as a suspended app's would be lost (see AppAttachOptions)
|
|
307
|
+
if (!foreground() && (method === "game.finish" || method === "app.checkpoint.set"))
|
|
308
|
+
return;
|
|
309
|
+
if (legacy) {
|
|
310
|
+
let result;
|
|
311
|
+
switch (request.method) {
|
|
312
|
+
case "ui.ready":
|
|
313
|
+
ready = true;
|
|
314
|
+
attachOptions.ready();
|
|
315
|
+
result = { completed: true };
|
|
316
|
+
break;
|
|
317
|
+
case "game.finish":
|
|
318
|
+
if (completion && completion.score !== request.score) {
|
|
319
|
+
// an apps3 host answers a changed score as a policy refusal; protocol 1 hosts end the session as before
|
|
320
|
+
if (!apps3)
|
|
321
|
+
throw Error("This game has already finished.");
|
|
322
|
+
send({ session, id, error: "This game has already finished.", code: "invalid" }, APP_LIMITS.responseBytes);
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
completion ??= Object.freeze({ score: request.score });
|
|
326
|
+
result = { completed: true };
|
|
327
|
+
break;
|
|
328
|
+
case "app.checkpoint.get":
|
|
329
|
+
result = { checkpoint: JSON.parse(checkpoint) };
|
|
330
|
+
break;
|
|
331
|
+
default:
|
|
332
|
+
checkpoint = checkpointJson(request.value);
|
|
333
|
+
result = { completed: true };
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
if (current()) {
|
|
337
|
+
port.postMessage(appJson({ session, id, result }, APP_LIMITS.responseBytes));
|
|
338
|
+
if (method === "game.finish" && completion && !completionNotified && current()) {
|
|
339
|
+
completionNotified = true;
|
|
340
|
+
attachOptions.finish?.(completion);
|
|
341
|
+
}
|
|
131
342
|
}
|
|
343
|
+
return;
|
|
132
344
|
}
|
|
345
|
+
return reply2(id, request, method, now);
|
|
133
346
|
}).catch(() => { if (!stopped)
|
|
134
347
|
refuse("App request could not complete."); }).finally(() => { inFlight--; });
|
|
135
348
|
};
|
|
349
|
+
const reply2 = async (id, request, method, now) => {
|
|
350
|
+
const rule = methodRule(method);
|
|
351
|
+
let reply;
|
|
352
|
+
try {
|
|
353
|
+
const state = !ready ? "L" : foreground() ? "F" : "B";
|
|
354
|
+
if (!rule.states.includes(state))
|
|
355
|
+
throw new AppHostError("not-permitted", MESSAGE.states);
|
|
356
|
+
// leaving fullscreen is always allowed (section 9.2)
|
|
357
|
+
if (rule.rate && !(request.method === "display.fullscreen" && !request.on)) {
|
|
358
|
+
let limiter = soft.get(method);
|
|
359
|
+
if (!limiter) {
|
|
360
|
+
limiter = slidingWindow(rule.rate[0], rule.rate[1]);
|
|
361
|
+
soft.set(method, limiter);
|
|
362
|
+
}
|
|
363
|
+
if (!limiter(now))
|
|
364
|
+
throw new AppHostError("rate-limited", MESSAGE.rate);
|
|
365
|
+
}
|
|
366
|
+
const result = await answer2(services, request);
|
|
367
|
+
if (utf8Bytes(JSON.stringify(result)) > rule.response)
|
|
368
|
+
throw new AppHostError("unavailable", "The answer is larger than this request may return.");
|
|
369
|
+
reply = { session, id, result };
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
const code = error instanceof AppHostError ? error.code : "unavailable";
|
|
373
|
+
reply = { session, id, error: error instanceof AppHostError ? error.message.slice(0, 300) : MESSAGE.unavailable, code };
|
|
374
|
+
}
|
|
375
|
+
send(reply, APP_SESSION_LIMITS.messageBytes);
|
|
376
|
+
};
|
|
136
377
|
port.onmessageerror = () => refuse("App message could not be decoded.");
|
|
137
378
|
port.start();
|
|
138
379
|
return handle;
|
|
139
380
|
},
|
|
140
381
|
suspend() { active?.close(); },
|
|
141
382
|
dispose() { if (disposed)
|
|
142
|
-
return; disposed = true; clearTimeout(expiry); active?.close(); checkpoint = "null"; },
|
|
383
|
+
return; disposed = true; clearTimeout(expiry); clearTimeout(idleTimer); active?.close(); checkpoint = "null"; },
|
|
143
384
|
};
|
|
385
|
+
if (apps3) {
|
|
386
|
+
controller.activity = () => { const now = readTime(); if (now !== undefined)
|
|
387
|
+
touch(now); };
|
|
388
|
+
controller.cardsChanged = async () => { try {
|
|
389
|
+
await cards?.();
|
|
390
|
+
}
|
|
391
|
+
catch { /* the next change or read answers again */ } };
|
|
392
|
+
}
|
|
393
|
+
return controller;
|
|
144
394
|
}
|
|
145
|
-
/**
|
|
395
|
+
/**
|
|
396
|
+
* Caller supplies the already-validated immutable URL, including this generation's fragment. With a protocol 2
|
|
397
|
+
* controller the transfer advertises `protocol: 2`, and readiness is `ready()` within 15 s, or `progress()` at least
|
|
398
|
+
* every 15 s and `ready()` within 120 s.
|
|
399
|
+
*/
|
|
146
400
|
export function mountAppFrame(frame, options) {
|
|
147
401
|
const refusal = appRuntimeRefusal(window);
|
|
148
402
|
if (refusal)
|
|
149
403
|
throw Error(refusal);
|
|
150
404
|
if (!appNonce(options.challenge) || new URL(frame.src).hash !== `#${APP_FRAGMENT}=${options.challenge}`)
|
|
151
405
|
throw Error("Invalid app frame challenge.");
|
|
152
|
-
|
|
406
|
+
const protocol2 = options.controller.protocol === 2;
|
|
407
|
+
let ended = false, loaded = false, connected = false, bootstrapMessages = 0, session, readied = false;
|
|
153
408
|
let bounds = lifecycleValue({ active: true, width: 0, height: 0 });
|
|
409
|
+
const slow = () => fault("App took too long to become ready.");
|
|
154
410
|
const dispose = () => { if (ended)
|
|
155
|
-
return; ended = true; clearTimeout(timeout); frame.removeEventListener("load", load); window.removeEventListener("message", connect); session?.close(); };
|
|
411
|
+
return; ended = true; clearTimeout(timeout); clearTimeout(ceiling); frame.removeEventListener("load", load); window.removeEventListener("message", connect); session?.close(); };
|
|
156
412
|
const fault = (message) => { if (ended)
|
|
157
413
|
return; dispose(); options.fault(message); };
|
|
158
414
|
const load = () => { if (loaded)
|
|
@@ -184,12 +440,19 @@ export function mountAppFrame(frame, options) {
|
|
|
184
440
|
window.removeEventListener("message", connect);
|
|
185
441
|
const ports = new MessageChannel(), nonce = createAppNonce();
|
|
186
442
|
try {
|
|
187
|
-
session = options.controller.attach(ports.port1, nonce, { current: options.current,
|
|
188
|
-
ready() { clearTimeout(timeout); options.ready(); }, finish: options.finish, fault
|
|
443
|
+
session = options.controller.attach(ports.port1, nonce, { current: options.current, foreground: options.foreground,
|
|
444
|
+
ready() { readied = true; clearTimeout(timeout); clearTimeout(ceiling); options.ready(); }, finish: options.finish, fault,
|
|
445
|
+
progress(fraction) {
|
|
446
|
+
if (readied || ended)
|
|
447
|
+
return;
|
|
448
|
+
clearTimeout(timeout);
|
|
449
|
+
timeout = setTimeout(slow, APP_SESSION_LIMITS.readyMs);
|
|
450
|
+
options.progress?.(fraction);
|
|
451
|
+
} });
|
|
189
452
|
// Opaque frames require wildcard targetOrigin; the exact WindowProxy/challenge bind this transfer.
|
|
190
453
|
if (!frame.contentWindow)
|
|
191
454
|
throw Error("App frame is unavailable.");
|
|
192
|
-
frame.contentWindow.postMessage({ channel: CHANNEL, challenge: options.challenge, session: nonce }, "*", [ports.port2]);
|
|
455
|
+
frame.contentWindow.postMessage({ channel: CHANNEL, challenge: options.challenge, session: nonce, ...(protocol2 ? { protocol: 2 } : {}) }, "*", [ports.port2]);
|
|
193
456
|
session.lifecycle(bounds);
|
|
194
457
|
}
|
|
195
458
|
catch {
|
|
@@ -198,11 +461,29 @@ export function mountAppFrame(frame, options) {
|
|
|
198
461
|
fault("App connection could not complete.");
|
|
199
462
|
}
|
|
200
463
|
};
|
|
201
|
-
|
|
464
|
+
let timeout = setTimeout(slow, APP_SESSION_LIMITS.readyMs);
|
|
465
|
+
const ceiling = protocol2 ? setTimeout(slow, APP_SESSION_LIMITS.progressReadyMs) : undefined;
|
|
202
466
|
frame.addEventListener("load", load);
|
|
203
467
|
window.addEventListener("message", connect);
|
|
204
468
|
return {
|
|
205
|
-
resize(width, height) { bounds = lifecycleValue({ active:
|
|
469
|
+
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
|
+
setActive(active) { if (active === bounds.active)
|
|
471
|
+
return; bounds = lifecycleValue({ ...bounds, active }); session?.lifecycle(bounds); },
|
|
206
472
|
dispose,
|
|
207
473
|
};
|
|
208
474
|
}
|
|
475
|
+
/**
|
|
476
|
+
* The backend's card read as an app sees it, for an apps3 host's services: rarity numbers named, ids joined, and art as the
|
|
477
|
+
* path after the version prefix only where the backend has servable art and the card id can be a path segment.
|
|
478
|
+
*/
|
|
479
|
+
export function appCardsView(reply) {
|
|
480
|
+
const rarities = ["common", "rare", "epic", "legendary", "mythic"];
|
|
481
|
+
return {
|
|
482
|
+
packs: reply.packs.map(pack => wirePackSummary({ id: pack.slug, name: pack.name, creator: pack.creator, art: pack.cover ? coverArtPath(pack.slug) : null, held: pack.held, total: pack.total })),
|
|
483
|
+
cards: reply.cards.map(card => wireCard({
|
|
484
|
+
id: `${card.pack}/${card.card}`, pack: card.pack, name: card.name, rarity: rarities[card.rarity] ?? "common", count: card.count,
|
|
485
|
+
art: card.art && CARD_ID.test(card.card) ? cardArtPath(card.pack, card.card) : null,
|
|
486
|
+
})),
|
|
487
|
+
revision: reply.revision,
|
|
488
|
+
};
|
|
489
|
+
}
|