@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.
- package/AGENTS.md +76 -48
- 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 +95 -31
- 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 +7 -7
- 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/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 +17 -11
- package/package.json +6 -2
package/dist/os.js
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `connect()`: the one app API of @vibechain/os 0.5 (VM_OS_APPS_3.md section 11). On a host that advertises protocol 2 it
|
|
3
|
+
* says hello and every method works; on an older host `ready`, `finish`, lifecycle, `load` and `save` work (saves use the
|
|
4
|
+
* window-only checkpoint) and the rest reject with `unsupported`. Every rejection is an OsError with a stable code.
|
|
5
|
+
*/
|
|
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";
|
|
8
|
+
import { gameFinishInput } from "./completion.js";
|
|
9
|
+
import { packSlug } from "./manifest.js";
|
|
10
|
+
import { connectHostPort, createRpcTransport } from "./transport.js";
|
|
11
|
+
export { OS_ERROR_CODES } from "./app-wire.js";
|
|
12
|
+
/** 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
|
+
}
|
|
19
|
+
const MESSAGES = {
|
|
20
|
+
unsupported: "This host is older than this SDK and has no such feature.",
|
|
21
|
+
"not-permitted": "The manifest does not declare that, or the app is behind another window.",
|
|
22
|
+
invalid: "That argument is not valid.",
|
|
23
|
+
"too-large": "That is too large.",
|
|
24
|
+
"rate-limited": "Too many requests; try again later.",
|
|
25
|
+
"needs-click": "That needs a fresh click in the app.",
|
|
26
|
+
unavailable: "The host could not answer now; try again.",
|
|
27
|
+
timeout: "The host did not answer in 10 seconds.",
|
|
28
|
+
closed: "The session ended. Reopen the app.",
|
|
29
|
+
};
|
|
30
|
+
const fail = (code, message = MESSAGES[code]) => new OsError(code, message);
|
|
31
|
+
/** Errors the SDK raises itself keep their code; anything else is `invalid` (an argument) unless said otherwise. */
|
|
32
|
+
const asOsError = (error, fallback) => error instanceof OsError ? error
|
|
33
|
+
: error instanceof AppHostError ? new OsError(error.code, error.message) : fail(fallback, error.message);
|
|
34
|
+
const slug = (value) => { if (!packSlug(value))
|
|
35
|
+
throw fail("invalid", "That is not a pack slug."); return value; };
|
|
36
|
+
/** Connect to the host: the handshake, then hello on a protocol 2 host. Call once, early. */
|
|
37
|
+
export async function connect(options = {}) {
|
|
38
|
+
const challenge = new URLSearchParams(window.location.hash.slice(1)).get(APP_FRAGMENT);
|
|
39
|
+
if (!appNonce(challenge))
|
|
40
|
+
throw fail("unsupported", "Open this app in VibeMarket OS or the SDK preview.");
|
|
41
|
+
let connection;
|
|
42
|
+
try {
|
|
43
|
+
connection = await connectHostPort(options.signal, challenge);
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
throw fail(options.signal?.aborted ? "closed" : "timeout", error.message);
|
|
47
|
+
}
|
|
48
|
+
// connectHostPort admits only a transfer carrying a valid session; createOs checks it again
|
|
49
|
+
return createOs(connection.port, connection.session, connection.protocol ?? 1, window.location.href);
|
|
50
|
+
}
|
|
51
|
+
/** The app API over an admitted port. `href` is the frame's own URL, against which art paths resolve. */
|
|
52
|
+
export async function createOs(port, session, protocol, href) {
|
|
53
|
+
if (!appNonce(session))
|
|
54
|
+
throw fail("unavailable", "Invalid app session.");
|
|
55
|
+
let state = Object.freeze({ active: true, width: 0, height: 0 }), closed = false;
|
|
56
|
+
const pause = new Set(), resume = new Set(), resize = new Set(), watchers = new Set();
|
|
57
|
+
const transport = createRpcTransport(port, {
|
|
58
|
+
session, timeoutMs: APP_LIMITS.requestTimeoutMs,
|
|
59
|
+
maxPending: protocol === 2 ? 64 : APP_LIMITS.inFlight, jsonBytes: protocol === 2 ? APP_SESSION_LIMITS.messageBytes : APP_LIMITS.responseBytes,
|
|
60
|
+
errors: {
|
|
61
|
+
reply: (message, code) => fail(osErrorCode(code) ? code : "unavailable", message),
|
|
62
|
+
timeout: () => fail("timeout"), closed: () => fail("closed"), busy: () => fail("rate-limited", "Too many requests are waiting; try again later."),
|
|
63
|
+
},
|
|
64
|
+
...(protocol === 2 ? { pace: { perSecond: APP_SESSION_LIMITS.clientPerSecond, perMinute: APP_SESSION_LIMITS.clientPerMinute } } : {}),
|
|
65
|
+
onEvent(value) {
|
|
66
|
+
if (value.event === "app.cards") {
|
|
67
|
+
cardsEvent(value.state);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (value.event !== "app.lifecycle")
|
|
71
|
+
return;
|
|
72
|
+
let next;
|
|
73
|
+
try {
|
|
74
|
+
next = lifecycleValue(value.state);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const previous = state;
|
|
80
|
+
state = Object.freeze({ active: next.active, width: next.width, height: next.height });
|
|
81
|
+
if (previous.active && !next.active)
|
|
82
|
+
for (const listener of [...pause])
|
|
83
|
+
listener();
|
|
84
|
+
if (!previous.active && next.active)
|
|
85
|
+
for (const listener of [...resume])
|
|
86
|
+
listener();
|
|
87
|
+
if (previous.width !== next.width || previous.height !== next.height)
|
|
88
|
+
for (const listener of [...resize])
|
|
89
|
+
listener(Object.freeze({ width: next.width, height: next.height }));
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
const call = async (request) => {
|
|
93
|
+
if (closed)
|
|
94
|
+
throw fail("closed");
|
|
95
|
+
const result = await transport.request(request);
|
|
96
|
+
if (!result || typeof result !== "object" || Array.isArray(result))
|
|
97
|
+
throw fail("unavailable", "Invalid host response.");
|
|
98
|
+
return result;
|
|
99
|
+
};
|
|
100
|
+
const completed = (result) => { if (result.completed !== true)
|
|
101
|
+
throw fail("unavailable", "Invalid host acknowledgement."); };
|
|
102
|
+
let hello = null;
|
|
103
|
+
if (protocol === 2) {
|
|
104
|
+
try {
|
|
105
|
+
hello = wireHello(await call({ method: "host.hello", protocol: 2, sdk: OS_SDK_VERSION }));
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
transport.destroy();
|
|
109
|
+
throw asOsError(error, "unavailable");
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const v2 = () => { if (!hello)
|
|
113
|
+
throw fail("unsupported"); return hello; };
|
|
114
|
+
const absolute = (art) => art === null ? null : new URL(v2().root + art, href).href;
|
|
115
|
+
const card = (wire) => ({ ...wire, art: absolute(wire.art) });
|
|
116
|
+
// ---- cards: whole-list paging and live updates
|
|
117
|
+
let held = null, stale = false, refreshing = null;
|
|
118
|
+
const list = async (pack) => {
|
|
119
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
120
|
+
const cards = [];
|
|
121
|
+
let after = null, revision = null, consistent = true;
|
|
122
|
+
do {
|
|
123
|
+
const page = await call({ method: "cards.list", ...(pack === undefined ? {} : { pack }), ...(after === null ? {} : { after }) });
|
|
124
|
+
if (!Array.isArray(page.cards) || (page.after !== null && typeof page.after !== "string") || typeof page.revision !== "string")
|
|
125
|
+
throw fail("unavailable", "Invalid host response.");
|
|
126
|
+
if (revision !== null && page.revision !== revision) {
|
|
127
|
+
consistent = false;
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
revision = page.revision;
|
|
131
|
+
after = page.after;
|
|
132
|
+
for (const wire of page.cards)
|
|
133
|
+
cards.push(card(wireCard(wire)));
|
|
134
|
+
} while (after !== null);
|
|
135
|
+
if (consistent && revision !== null) {
|
|
136
|
+
if (pack === undefined)
|
|
137
|
+
held = { revision, cards: new Map(cards.map(item => [item.id, item])) };
|
|
138
|
+
return { cards, revision };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
throw fail("unavailable", "The cards kept changing while they were read; try again.");
|
|
142
|
+
};
|
|
143
|
+
const notify = () => { const cards = [...held.cards.values()]; for (const listener of [...watchers])
|
|
144
|
+
listener(cards.slice()); };
|
|
145
|
+
/** Read the whole list again; tell the listeners unless this is the first read that only sets the baseline. */
|
|
146
|
+
const refresh = (tell) => refreshing ??= (async () => {
|
|
147
|
+
try {
|
|
148
|
+
do {
|
|
149
|
+
stale = false;
|
|
150
|
+
await list();
|
|
151
|
+
} while (stale);
|
|
152
|
+
if (tell)
|
|
153
|
+
notify();
|
|
154
|
+
}
|
|
155
|
+
catch { /* the next change tries again */ }
|
|
156
|
+
finally {
|
|
157
|
+
refreshing = null;
|
|
158
|
+
}
|
|
159
|
+
})();
|
|
160
|
+
/** Declared ahead so the transport can call it; returns before reading any later state while nobody listens. */
|
|
161
|
+
function cardsEvent(value) {
|
|
162
|
+
if (!watchers.size)
|
|
163
|
+
return;
|
|
164
|
+
let event;
|
|
165
|
+
try {
|
|
166
|
+
event = wireCardsEvent(value);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (refreshing) {
|
|
172
|
+
stale = true;
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if ("reset" in event || !held) {
|
|
176
|
+
void refresh(true);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
for (const id of event.removed)
|
|
180
|
+
held.cards.delete(id);
|
|
181
|
+
for (const wire of event.changed)
|
|
182
|
+
held.cards.set(wire.id, card(wire));
|
|
183
|
+
held = { revision: event.revision, cards: held.cards };
|
|
184
|
+
notify();
|
|
185
|
+
}
|
|
186
|
+
// ---- saves: one write in flight, at most one per interval; later calls replace the pending value. The interval runs from
|
|
187
|
+
// the previous write's ANSWER, not its sending: the host counts a write when it reads it, which is before it answers, so
|
|
188
|
+
// however late the host reads (a busy desk right after ready), the next write never reaches it sooner than 10 s after.
|
|
189
|
+
let pendingSave = null, writing = false, lastWrite = -Infinity, saveTimer;
|
|
190
|
+
const interval = protocol === 2 ? APP_SESSION_LIMITS.saveIntervalMs : 0;
|
|
191
|
+
const flush = () => {
|
|
192
|
+
if (writing || !pendingSave || saveTimer !== undefined)
|
|
193
|
+
return;
|
|
194
|
+
const wait = lastWrite + interval - Date.now();
|
|
195
|
+
if (wait > 0) {
|
|
196
|
+
saveTimer = window.setTimeout(() => { saveTimer = undefined; flush(); }, wait);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const { text, waiters } = pendingSave;
|
|
200
|
+
pendingSave = null;
|
|
201
|
+
writing = true;
|
|
202
|
+
const value = JSON.parse(text);
|
|
203
|
+
call(protocol === 2 ? { method: "app.save.set", value } : { method: "app.checkpoint.set", value })
|
|
204
|
+
.then(result => { if (protocol === 2 ? typeof result.savedAt !== "string" : result.completed !== true)
|
|
205
|
+
throw fail("unavailable", "Invalid host acknowledgement."); })
|
|
206
|
+
.then(() => { for (const waiter of waiters)
|
|
207
|
+
waiter.resolve(); }, (error) => { const failure = asOsError(error, "unavailable"); for (const waiter of waiters)
|
|
208
|
+
waiter.reject(failure); })
|
|
209
|
+
.finally(() => { writing = false; lastWrite = Date.now(); flush(); });
|
|
210
|
+
};
|
|
211
|
+
let token = null;
|
|
212
|
+
const os = {
|
|
213
|
+
get active() { return state.active; },
|
|
214
|
+
get size() { return Object.freeze({ width: state.width, height: state.height }); },
|
|
215
|
+
get guest() { return hello?.guest ?? false; },
|
|
216
|
+
async ready() { completed(await call({ method: "ui.ready" })); },
|
|
217
|
+
progress(fraction) {
|
|
218
|
+
if (typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1)
|
|
219
|
+
throw fail("invalid", "Progress is a number from 0 to 1.");
|
|
220
|
+
if (!hello || readied)
|
|
221
|
+
return;
|
|
222
|
+
progressValue = fraction;
|
|
223
|
+
if (progressTimer === undefined) {
|
|
224
|
+
sendProgress();
|
|
225
|
+
progressTimer = window.setTimeout(() => { progressTimer = undefined; if (progressValue !== null)
|
|
226
|
+
sendProgress(); }, 1000);
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
async load() {
|
|
230
|
+
if (hello) {
|
|
231
|
+
const result = await call({ method: "app.save.get" });
|
|
232
|
+
return (result.value === null ? null : saveValue(JSON.stringify(result.value)));
|
|
233
|
+
}
|
|
234
|
+
const result = await call({ method: "app.checkpoint.get" });
|
|
235
|
+
if (!("checkpoint" in result))
|
|
236
|
+
throw fail("unavailable", "Invalid host response.");
|
|
237
|
+
return result.checkpoint;
|
|
238
|
+
},
|
|
239
|
+
save(value) {
|
|
240
|
+
let text;
|
|
241
|
+
try {
|
|
242
|
+
text = saveJson(value);
|
|
243
|
+
if (!hello) {
|
|
244
|
+
if (new TextEncoder().encode(text).byteLength > APP_LIMITS.checkpointBytes)
|
|
245
|
+
throw fail("too-large", "This host keeps at most 32 KiB, and only while the window is open.");
|
|
246
|
+
try {
|
|
247
|
+
checkpointJson(value);
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
throw fail("too-large", error.message);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
return Promise.reject(asOsError(error, "invalid"));
|
|
256
|
+
}
|
|
257
|
+
if (closed)
|
|
258
|
+
return Promise.reject(fail("closed"));
|
|
259
|
+
return new Promise((resolve, reject) => {
|
|
260
|
+
pendingSave = { text, waiters: [...(pendingSave?.waiters ?? []), { resolve, reject }] };
|
|
261
|
+
flush();
|
|
262
|
+
});
|
|
263
|
+
},
|
|
264
|
+
async cards(pack) {
|
|
265
|
+
const filter = pack === undefined ? undefined : slug(pack);
|
|
266
|
+
v2();
|
|
267
|
+
return (await list(filter)).cards;
|
|
268
|
+
},
|
|
269
|
+
onCards(listener) {
|
|
270
|
+
watchers.add(listener);
|
|
271
|
+
if (hello && watchers.size === 1) {
|
|
272
|
+
call({ method: "cards.watch", on: true }).then(() => { if (!held)
|
|
273
|
+
void refresh(false); }, () => { });
|
|
274
|
+
}
|
|
275
|
+
return () => {
|
|
276
|
+
if (!watchers.delete(listener) || watchers.size || !hello || closed)
|
|
277
|
+
return;
|
|
278
|
+
call({ method: "cards.watch", on: false }).catch(() => { });
|
|
279
|
+
};
|
|
280
|
+
},
|
|
281
|
+
async packs() { v2(); const result = await call({ method: "cards.packs" }); if (!Array.isArray(result.packs))
|
|
282
|
+
throw fail("unavailable", "Invalid host response."); return result.packs.map(item => { const pack = wirePackSummary(item); return { ...pack, art: absolute(pack.art) }; }); },
|
|
283
|
+
async pack(id) {
|
|
284
|
+
const name = slug(id);
|
|
285
|
+
v2();
|
|
286
|
+
const pack = wirePack((await call({ method: "cards.pack", pack: name })).pack);
|
|
287
|
+
return { ...pack, art: absolute(pack.art), cards: pack.cards.map(item => ({ ...item, art: absolute(item.art) })) };
|
|
288
|
+
},
|
|
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."); },
|
|
291
|
+
async player() {
|
|
292
|
+
v2();
|
|
293
|
+
if (token && token.expiresAt - Date.now() > APP_SESSION_LIMITS.tokenReuseMs)
|
|
294
|
+
return { ...token };
|
|
295
|
+
const next = wirePlayer(await call({ method: "player.get" }));
|
|
296
|
+
if (next.guest) {
|
|
297
|
+
token = null;
|
|
298
|
+
return next;
|
|
299
|
+
}
|
|
300
|
+
const player = { ...next, picture: absolute(next.picture) };
|
|
301
|
+
token = player.token ? player : null;
|
|
302
|
+
return { ...player };
|
|
303
|
+
},
|
|
304
|
+
async finish(result) {
|
|
305
|
+
let input;
|
|
306
|
+
try {
|
|
307
|
+
input = gameFinishInput(result);
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
throw asOsError(error, "invalid");
|
|
311
|
+
}
|
|
312
|
+
completed(await call({ method: "game.finish", ...input }));
|
|
313
|
+
},
|
|
314
|
+
async maximize(on = true) { if (typeof on !== "boolean")
|
|
315
|
+
throw fail("invalid"); v2(); completed(await call({ method: "display.maximize", on })); },
|
|
316
|
+
async fullscreen(on = true) { if (typeof on !== "boolean")
|
|
317
|
+
throw fail("invalid"); v2(); completed(await call({ method: "display.fullscreen", on })); },
|
|
318
|
+
onPause(listener) { pause.add(listener); return () => { pause.delete(listener); }; },
|
|
319
|
+
onResume(listener) { resume.add(listener); return () => { resume.delete(listener); }; },
|
|
320
|
+
onResize(listener) { resize.add(listener); return () => { resize.delete(listener); }; },
|
|
321
|
+
close() {
|
|
322
|
+
if (closed)
|
|
323
|
+
return;
|
|
324
|
+
closed = true;
|
|
325
|
+
if (saveTimer !== undefined)
|
|
326
|
+
window.clearTimeout(saveTimer);
|
|
327
|
+
if (progressTimer !== undefined)
|
|
328
|
+
window.clearTimeout(progressTimer);
|
|
329
|
+
pendingSave?.waiters.forEach(waiter => waiter.reject(fail("closed")));
|
|
330
|
+
pendingSave = null;
|
|
331
|
+
pause.clear();
|
|
332
|
+
resume.clear();
|
|
333
|
+
resize.clear();
|
|
334
|
+
watchers.clear();
|
|
335
|
+
transport.destroy();
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
// progress: at most one request a second, the latest value; none after ready
|
|
339
|
+
let progressValue = null, progressTimer, readied = false;
|
|
340
|
+
const sendProgress = () => { const value = progressValue; progressValue = null; call({ method: "ui.progress", value }).catch(() => { }); };
|
|
341
|
+
const ready = os.ready;
|
|
342
|
+
os.ready = async () => { readied = true; progressValue = null; await ready(); };
|
|
343
|
+
// 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"]) {
|
|
345
|
+
const method = os[key];
|
|
346
|
+
os[key] = async (...args) => { try {
|
|
347
|
+
return await method(...args);
|
|
348
|
+
}
|
|
349
|
+
catch (error) {
|
|
350
|
+
throw asOsError(error, "unavailable");
|
|
351
|
+
} };
|
|
352
|
+
}
|
|
353
|
+
return Object.freeze(os);
|
|
354
|
+
}
|
package/dist/preview-parent.d.ts
CHANGED
|
@@ -1 +1,37 @@
|
|
|
1
|
+
import { type WireCard, type WirePack, type WirePackSummary } from "./app-wire.ts";
|
|
2
|
+
/** What preview.json says about the app (preview.ts). */
|
|
3
|
+
export interface PreviewMetadata {
|
|
4
|
+
name: string;
|
|
5
|
+
runtime: string;
|
|
6
|
+
id: string;
|
|
7
|
+
entry: string;
|
|
8
|
+
packs: string[];
|
|
9
|
+
cards: "none" | "linked" | "all";
|
|
10
|
+
network: string[];
|
|
11
|
+
}
|
|
12
|
+
export declare function previewMetadata(input: unknown): PreviewMetadata;
|
|
13
|
+
/**
|
|
14
|
+
* 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
|
+
*/
|
|
18
|
+
export declare function previewCatalog(meta: Pick<PreviewMetadata, "packs" | "cards">, random?: () => number): {
|
|
19
|
+
pack(slug: string): WirePack;
|
|
20
|
+
cards(): {
|
|
21
|
+
cards: WireCard[];
|
|
22
|
+
revision: string;
|
|
23
|
+
};
|
|
24
|
+
packs(): WirePackSummary[];
|
|
25
|
+
pull(): string | null;
|
|
26
|
+
};
|
|
27
|
+
/** The save in this browser's storage (it survives a reload, as a signed-in save would), or in memory when storage is off. */
|
|
28
|
+
export declare function previewSaves(id: string, storage: () => Storage): {
|
|
29
|
+
get(): {
|
|
30
|
+
value: string | null;
|
|
31
|
+
savedAt: string | null;
|
|
32
|
+
};
|
|
33
|
+
set(value: string): {
|
|
34
|
+
savedAt: string;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
1
37
|
export declare function startPreviewParent(): Promise<void>;
|
package/dist/preview-parent.js
CHANGED
|
@@ -1,21 +1,120 @@
|
|
|
1
1
|
import { createAppController, mountAppFrame } from "./app-host.js";
|
|
2
2
|
import { APP_FRAGMENT, createAppNonce } from "./app-protocol.js";
|
|
3
3
|
import { appRuntimeRefusal } from "./app-runtime.js";
|
|
4
|
+
import { AppHostError, cardArtPath, coverArtPath, RARITIES } from "./app-wire.js";
|
|
5
|
+
import { assetPath, packSlug } from "./manifest.js";
|
|
6
|
+
export function previewMetadata(input) {
|
|
7
|
+
if (!input || typeof input !== "object" || !("runtime" in input) || typeof input.runtime !== "string")
|
|
8
|
+
throw Error("Invalid preview metadata.");
|
|
9
|
+
const value = input;
|
|
10
|
+
const strings = (list, valid) => Array.isArray(list) && list.length <= 8 && list.every(valid) ? list : null;
|
|
11
|
+
const packs = strings(value.packs, packSlug), network = strings(value.network, item => typeof item === "string");
|
|
12
|
+
if (typeof value.name !== "string" || typeof value.id !== "string" || typeof value.entry !== "string" || !assetPath(value.entry) || !packs || !network
|
|
13
|
+
|| !(value.cards === "none" || value.cards === "linked" || value.cards === "all"))
|
|
14
|
+
throw Error("Invalid preview metadata.");
|
|
15
|
+
return { name: value.name, runtime: input.runtime, id: value.id, entry: value.entry, packs, cards: value.cards, network };
|
|
16
|
+
}
|
|
17
|
+
/** A pack name from its slug: "rooftop-rats" reads "Rooftop Rats". */
|
|
18
|
+
const title = (slug) => slug.split("-").map(word => word[0].toUpperCase() + word.slice(1)).join(" ");
|
|
19
|
+
/**
|
|
20
|
+
* 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
|
+
*/
|
|
24
|
+
export function previewCatalog(meta, random = Math.random) {
|
|
25
|
+
const slugs = meta.packs.length ? meta.packs : meta.cards === "all" ? ["preview-pack"] : [];
|
|
26
|
+
const packs = slugs.map(slug => ({
|
|
27
|
+
id: slug, name: title(slug), creator: "Preview", art: coverArtPath(slug), total: 6,
|
|
28
|
+
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
|
+
}));
|
|
30
|
+
const counts = new Map(packs.flatMap(pack => pack.cards.slice(0, 3).map(card => [card.id, 1])));
|
|
31
|
+
let revision = 1;
|
|
32
|
+
const readable = (slug) => meta.cards === "all" ? slugs.includes(slug) : meta.packs.includes(slug);
|
|
33
|
+
return {
|
|
34
|
+
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.");
|
|
38
|
+
return pack;
|
|
39
|
+
},
|
|
40
|
+
cards() {
|
|
41
|
+
if (meta.cards === "none")
|
|
42
|
+
throw new AppHostError("not-permitted", "The manifest does not declare cards.");
|
|
43
|
+
const cards = packs.flatMap(pack => pack.cards.filter(card => counts.has(card.id)).map(card => ({ ...card, count: counts.get(card.id) })));
|
|
44
|
+
return { cards, revision: String(revision) };
|
|
45
|
+
},
|
|
46
|
+
packs() {
|
|
47
|
+
return packs.map(({ cards, ...pack }) => ({ ...pack, held: meta.cards === "none" ? 0 : cards.filter(card => counts.has(card.id)).length }));
|
|
48
|
+
},
|
|
49
|
+
pull() {
|
|
50
|
+
const all = packs.flatMap(pack => pack.cards);
|
|
51
|
+
if (!all.length)
|
|
52
|
+
return null;
|
|
53
|
+
const card = all[Math.min(all.length - 1, Math.floor(random() * all.length))];
|
|
54
|
+
counts.set(card.id, (counts.get(card.id) ?? 0) + 1);
|
|
55
|
+
revision++;
|
|
56
|
+
return card.name;
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/** The save in this browser's storage (it survives a reload, as a signed-in save would), or in memory when storage is off. */
|
|
61
|
+
export function previewSaves(id, storage) {
|
|
62
|
+
const key = `vmos-preview-save:${id}`;
|
|
63
|
+
let memory = { value: null, savedAt: null };
|
|
64
|
+
return {
|
|
65
|
+
get() { try {
|
|
66
|
+
const stored = storage().getItem(key);
|
|
67
|
+
if (stored)
|
|
68
|
+
return JSON.parse(stored);
|
|
69
|
+
}
|
|
70
|
+
catch { /* memory */ } return memory; },
|
|
71
|
+
set(value) { memory = { value, savedAt: new Date().toISOString() }; try {
|
|
72
|
+
storage().setItem(key, JSON.stringify(memory));
|
|
73
|
+
}
|
|
74
|
+
catch { /* memory */ } return { savedAt: memory.savedAt }; },
|
|
75
|
+
};
|
|
76
|
+
}
|
|
4
77
|
export async function startPreviewParent() {
|
|
5
78
|
const refusal = appRuntimeRefusal(window);
|
|
6
79
|
if (refusal)
|
|
7
80
|
throw Error(refusal);
|
|
8
|
-
const surface = document.getElementById("surface"), status = document.getElementById("status"), toggle = document.getElementById("toggle"), reset = document.getElementById("reset");
|
|
81
|
+
const surface = document.getElementById("surface"), status = document.getElementById("status"), toggle = document.getElementById("toggle"), reset = document.getElementById("reset"), pull = document.getElementById("pull");
|
|
9
82
|
const result = document.getElementById("result"), score = document.getElementById("score");
|
|
10
|
-
if (!surface || !status || !result || !score || !(toggle instanceof HTMLButtonElement) || !(reset instanceof HTMLButtonElement))
|
|
83
|
+
if (!surface || !status || !result || !score || !(toggle instanceof HTMLButtonElement) || !(reset instanceof HTMLButtonElement) || !(pull instanceof HTMLButtonElement))
|
|
11
84
|
throw Error("Preview controls are missing.");
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
throw Error("Invalid preview metadata.");
|
|
15
|
-
const runtime = new URL(input.runtime);
|
|
85
|
+
const meta = previewMetadata(await (await fetch("/preview.json", { credentials: "omit" })).json());
|
|
86
|
+
const runtime = new URL(meta.runtime);
|
|
16
87
|
if (runtime.origin !== `http://localhost:${window.location.port}` || !/^\/game-assets\/[a-f0-9]{64}\//.test(runtime.pathname) || runtime.search || runtime.hash)
|
|
17
88
|
throw Error("Invalid preview runtime.");
|
|
18
|
-
|
|
89
|
+
const catalog = previewCatalog(meta), saves = previewSaves(meta.id, () => window.localStorage);
|
|
90
|
+
const clicked = () => { if (!navigator.userActivation?.isActive)
|
|
91
|
+
throw new AppHostError("needs-click", "That needs a fresh click in the app."); };
|
|
92
|
+
const services = {
|
|
93
|
+
guest: false, entry: meta.entry,
|
|
94
|
+
async saveGet() { return saves.get(); },
|
|
95
|
+
async saveSet(text) { return saves.set(text); },
|
|
96
|
+
async cards() { return catalog.cards(); },
|
|
97
|
+
async packs() { return catalog.packs(); },
|
|
98
|
+
async pack(slug) { return catalog.pack(slug); },
|
|
99
|
+
async showPack(slug) { catalog.pack(slug); clicked(); status.textContent = `VibeMarket would open the pack ${slug} in its market window here.`; },
|
|
100
|
+
// a stand-in identity; the preview has no account and signs nothing
|
|
101
|
+
async player() {
|
|
102
|
+
const player = { guest: false, handle: "preview_player", username: "preview", name: "Preview Player", picture: null };
|
|
103
|
+
return meta.network.length ? { ...player, token: "preview.not-a-real-token.unsigned", expiresAt: Date.now() + 300_000 } : player;
|
|
104
|
+
},
|
|
105
|
+
async maximize(on) { surface.classList.toggle("maximized", on); },
|
|
106
|
+
async fullscreen(on) {
|
|
107
|
+
if (!on) {
|
|
108
|
+
if (document.fullscreenElement)
|
|
109
|
+
await document.exitFullscreen();
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
clicked();
|
|
113
|
+
await surface.requestFullscreen();
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
const owner = () => createAppController(undefined, { services, idle: () => { status.textContent = "Still playing? VibeMarket asks here after 15 minutes without input."; } });
|
|
117
|
+
let controller = owner(), frame = null;
|
|
19
118
|
let mounted = null, observer = null, minimized = false;
|
|
20
119
|
let completion = null;
|
|
21
120
|
const detach = () => { mounted?.dispose(); mounted = null; controller.suspend(); observer?.disconnect(); observer = null; frame?.remove(); frame = null; };
|
|
@@ -35,16 +134,20 @@ export async function startPreviewParent() {
|
|
|
35
134
|
}
|
|
36
135
|
const challenge = createAppNonce(), source = new URL(runtime);
|
|
37
136
|
source.hash = `${APP_FRAGMENT}=${challenge}`;
|
|
137
|
+
// the production frame element (VM_OS_APPS_3.md section 12.2)
|
|
38
138
|
frame = document.createElement("iframe");
|
|
39
139
|
frame.title = "VibeMarket OS app";
|
|
40
|
-
frame.sandbox.add("allow-scripts");
|
|
140
|
+
frame.sandbox.add("allow-scripts", "allow-pointer-lock");
|
|
141
|
+
frame.allow = "autoplay; gamepad";
|
|
142
|
+
frame.setAttribute("credentialless", "");
|
|
41
143
|
frame.referrerPolicy = "no-referrer";
|
|
42
144
|
frame.src = source.href;
|
|
43
145
|
surface.appendChild(frame);
|
|
44
146
|
mounted = mountAppFrame(frame, { controller, challenge, current: () => !minimized && !document.hidden,
|
|
45
147
|
ready: () => { status.textContent = "App ready · Minimize and restore to check its saved work."; },
|
|
148
|
+
progress: fraction => { status.textContent = `Loading the isolated app… ${Math.round(fraction * 100)}%`; },
|
|
46
149
|
finish: value => { completion = value; reset.textContent = "Play again"; draw(); },
|
|
47
|
-
fault: message => { detach(); controller.dispose(); controller =
|
|
150
|
+
fault: message => { detach(); controller.dispose(); controller = owner(); status.textContent = message; },
|
|
48
151
|
});
|
|
49
152
|
observer = new ResizeObserver(() => { if (frame)
|
|
50
153
|
mounted?.resize(frame.clientWidth, frame.clientHeight); });
|
|
@@ -52,9 +155,17 @@ export async function startPreviewParent() {
|
|
|
52
155
|
status.textContent = "Loading the isolated app…";
|
|
53
156
|
};
|
|
54
157
|
toggle.onclick = () => { minimized = !minimized; toggle.textContent = minimized ? "Restore" : "Minimize"; draw(); };
|
|
55
|
-
reset.onclick = () => { detach(); controller.dispose(); controller =
|
|
158
|
+
reset.onclick = () => { detach(); controller.dispose(); controller = owner(); completion = null; minimized = false; toggle.textContent = "Minimize"; reset.textContent = "Close / reset"; draw(); };
|
|
159
|
+
pull.onclick = () => {
|
|
160
|
+
const name = catalog.pull();
|
|
161
|
+
status.textContent = name ? `Pulled ${name}. The app hears about it through onCards.` : "This app links no packs and does not read all cards, so there is nothing to pull.";
|
|
162
|
+
void controller.cardsChanged?.();
|
|
163
|
+
};
|
|
164
|
+
// the desk reports user activation while the app is in front; the preview's own window stands in for it
|
|
165
|
+
const activity = window.setInterval(() => { if (navigator.userActivation?.isActive)
|
|
166
|
+
controller.activity?.(); }, 10_000);
|
|
56
167
|
document.addEventListener("visibilitychange", draw);
|
|
57
|
-
window.addEventListener("pagehide", () => { detach(); controller.dispose(); document.removeEventListener("visibilitychange", draw); }, { once: true });
|
|
168
|
+
window.addEventListener("pagehide", () => { window.clearInterval(activity); detach(); controller.dispose(); document.removeEventListener("visibilitychange", draw); }, { once: true });
|
|
58
169
|
draw();
|
|
59
170
|
}
|
|
60
171
|
if (typeof window !== "undefined" && typeof document !== "undefined")
|