@vibechain/os 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +22 -9
- package/README.md +53 -17
- package/SECURITY.md +6 -2
- package/dist/app-client.js +29 -5
- package/dist/app-host.d.ts +27 -4
- package/dist/app-host.js +76 -9
- package/dist/app-protocol.d.ts +36 -1
- package/dist/app-protocol.js +21 -0
- package/dist/app-wire.d.ts +24 -3
- package/dist/app-wire.js +19 -4
- package/dist/audio.d.ts +65 -0
- package/dist/audio.js +162 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +2 -0
- package/dist/bundle.d.ts +2 -0
- package/dist/bundle.js +2 -0
- package/dist/capture.d.ts +22 -0
- package/dist/capture.js +99 -0
- package/dist/cli.js +3 -1
- package/dist/commands.d.ts +6 -0
- package/dist/commands.js +17 -0
- package/dist/index.d.ts +5 -2
- package/dist/index.js +1 -0
- package/dist/links.d.ts +21 -0
- package/dist/links.js +43 -0
- package/dist/os.d.ts +33 -8
- package/dist/os.js +68 -14
- package/dist/preview-parent.d.ts +8 -2
- package/dist/preview-parent.js +35 -10
- package/dist/preview-ui.js +1 -1
- package/dist/preview.js +1 -1
- package/dist/templates/plain/game.js +3 -1
- package/dist/testing.d.ts +15 -2
- package/dist/testing.js +64 -19
- package/dist/transport.d.ts +2 -0
- package/dist/transport.js +1 -1
- package/dist/vibemarket-os.js +1 -1
- package/examples/paw-beat/README.md +28 -9
- package/examples/paw-beat/game.ts +280 -123
- package/examples/paw-beat/index.html +18 -4
- package/examples/paw-beat/main.ts +101 -44
- package/examples/paw-beat/music.ts +72 -337
- package/examples/paw-beat/stage.ts +23 -9
- package/examples/paw-beat/store/screenshot-1.webp +0 -0
- package/examples/paw-beat/store/screenshot-2.webp +0 -0
- package/examples/paw-beat/synth.ts +477 -0
- package/examples/paw-beat/tracks.ts +286 -0
- package/examples/paw-beat/vibemarket.json +2 -2
- package/examples/vibexp-app/plain/game.ts +6 -2
- package/package.json +7 -1
- package/skill.md +399 -0
package/dist/testing.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { APP_LIMITS, checkpointJson, checkpointValue, lifecycleValue } from "./app-protocol.js";
|
|
2
|
-
import { AppHostError, saveJson, saveValue, wireCard, wirePack } from "./app-wire.js";
|
|
1
|
+
import { APP_LIMITS, AUDIBLE, checkpointJson, checkpointValue, lifecycleValue, soundValue } from "./app-protocol.js";
|
|
2
|
+
import { AppHostError, CARD_ID, saveJson, saveValue, wireCard, wirePack } from "./app-wire.js";
|
|
3
3
|
import { gameFinishInput } from "./completion.js";
|
|
4
4
|
import { packSlug } from "./manifest.js";
|
|
5
5
|
import { OsError } from "./os.js";
|
|
6
|
+
import { parseVmosLink } from "./links.js";
|
|
6
7
|
/**
|
|
7
8
|
* An in-memory stand-in for the VibeMarket OS host, for unit tests. It applies the same
|
|
8
9
|
* checkpoint, score and lifecycle validation as the real host and the same single-shot
|
|
@@ -11,9 +12,9 @@ import { OsError } from "./os.js";
|
|
|
11
12
|
*/
|
|
12
13
|
export function createFakeApp(options = {}) {
|
|
13
14
|
let checkpoint = checkpointValue(options.checkpoint ?? null);
|
|
14
|
-
let state = lifecycleValue({ active: true, width: 800, height: 600, ...options.lifecycle });
|
|
15
|
+
let state = lifecycleValue({ active: true, width: 800, height: 600, ...options.lifecycle }), sound = soundValue({ ...AUDIBLE, ...options.sound });
|
|
15
16
|
let ready = false, destroyed = false, finished = null;
|
|
16
|
-
const listeners = new Set();
|
|
17
|
+
const listeners = new Set(), sounds = new Set();
|
|
17
18
|
const open = () => { if (destroyed)
|
|
18
19
|
throw Error("Game session ended."); };
|
|
19
20
|
const app = Object.freeze({
|
|
@@ -35,7 +36,12 @@ export function createFakeApp(options = {}) {
|
|
|
35
36
|
current: () => state,
|
|
36
37
|
onChanged(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
37
38
|
}),
|
|
38
|
-
|
|
39
|
+
sound: Object.freeze({
|
|
40
|
+
current: () => sound,
|
|
41
|
+
onChanged(listener) { sounds.add(listener); return () => { sounds.delete(listener); }; },
|
|
42
|
+
}),
|
|
43
|
+
onCapture() { return () => { }; },
|
|
44
|
+
destroy() { destroyed = true; listeners.clear(); sounds.clear(); },
|
|
39
45
|
});
|
|
40
46
|
return {
|
|
41
47
|
app,
|
|
@@ -44,6 +50,13 @@ export function createFakeApp(options = {}) {
|
|
|
44
50
|
for (const listener of [...listeners])
|
|
45
51
|
listener(state);
|
|
46
52
|
},
|
|
53
|
+
setSound(next) {
|
|
54
|
+
const previous = sound;
|
|
55
|
+
sound = soundValue({ ...sound, ...next });
|
|
56
|
+
if (previous.muted !== sound.muted || previous.volume !== sound.volume)
|
|
57
|
+
for (const listener of [...sounds])
|
|
58
|
+
listener(sound);
|
|
59
|
+
},
|
|
47
60
|
get ready() { return ready; },
|
|
48
61
|
get finished() { return finished; },
|
|
49
62
|
get checkpoint() { return checkpointValue(checkpoint); },
|
|
@@ -63,9 +76,10 @@ export function createFakeOs(options = {}) {
|
|
|
63
76
|
const checkCards = (cards) => cards.map(card => ({ ...wireCard({ ...card, art: null }), art: card.art }));
|
|
64
77
|
const packs = (options.packs ?? []).map(pack => ({ ...wirePack({ ...pack, art: null, cards: pack.cards.map(card => ({ ...card, art: null })) }), art: pack.art, cards: pack.cards.map(card => ({ ...card })) }));
|
|
65
78
|
let held = checkCards(options.cards ?? []), saved = protocol === 2 ? saveJson(options.save ?? null) : checkpointJson(options.save ?? null);
|
|
66
|
-
let state = lifecycleValue({ active: true, width: 800, height: 600, ...options.lifecycle });
|
|
79
|
+
let state = lifecycleValue({ active: true, width: 800, height: 600, ...options.lifecycle }), sound = soundValue({ ...AUDIBLE, ...options.sound });
|
|
80
|
+
const sounds = new Set();
|
|
67
81
|
let ready = false, closed = false, clicked = false, saves = 0, maximized = false, fullscreen = false, finished = null;
|
|
68
|
-
const progress = [], shown = [];
|
|
82
|
+
const progress = [], shown = [], shownCards = [];
|
|
69
83
|
const pause = new Set(), resume = new Set(), resize = new Set(), watchers = new Set();
|
|
70
84
|
const open = () => { if (closed)
|
|
71
85
|
throw fail("closed", "The session ended. Reopen the app."); };
|
|
@@ -74,12 +88,28 @@ export function createFakeOs(options = {}) {
|
|
|
74
88
|
const slug = (value) => { if (!packSlug(value))
|
|
75
89
|
throw fail("invalid", "That is not a pack slug."); return value; };
|
|
76
90
|
const readable = (pack) => access.cards === "all" || linked.includes(pack);
|
|
91
|
+
/** Any public pack the fake knows; an unknown one is `invalid`, as on the host. */
|
|
92
|
+
const known = (name) => { const pack = packs.find(item => item.id === name); if (!pack)
|
|
93
|
+
throw fail("invalid", "There is no such public pack."); return pack; };
|
|
94
|
+
const show = (name, card) => {
|
|
95
|
+
const pack = known(name);
|
|
96
|
+
if (card !== undefined && !pack.cards.some(item => item.id === `${name}/${card}`))
|
|
97
|
+
throw fail("invalid", "That card is not in that pack.");
|
|
98
|
+
if (!clicked)
|
|
99
|
+
throw fail("needs-click", "That needs a fresh click in the app.");
|
|
100
|
+
clicked = false;
|
|
101
|
+
if (card === undefined)
|
|
102
|
+
shown.push(name);
|
|
103
|
+
else
|
|
104
|
+
shownCards.push({ pack: name, card });
|
|
105
|
+
};
|
|
77
106
|
const permitted = () => held.filter(card => readable(card.pack));
|
|
78
107
|
const copy = (cards) => cards.map(card => ({ ...card }));
|
|
79
108
|
const os = Object.freeze({
|
|
80
109
|
get active() { return state.active; },
|
|
81
110
|
get size() { return Object.freeze({ width: state.width, height: state.height }); },
|
|
82
111
|
get guest() { return protocol === 2 && options.guest === true; },
|
|
112
|
+
get sound() { return sound; },
|
|
83
113
|
async ready() { open(); ready = true; },
|
|
84
114
|
progress(fraction) {
|
|
85
115
|
if (typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1)
|
|
@@ -121,20 +151,24 @@ export function createFakeOs(options = {}) {
|
|
|
121
151
|
async pack(id) {
|
|
122
152
|
const name = slug(id);
|
|
123
153
|
v2();
|
|
124
|
-
const pack =
|
|
125
|
-
if (!pack || !readable(name))
|
|
126
|
-
throw fail("not-permitted", "This app may not read that pack.");
|
|
154
|
+
const pack = known(name);
|
|
127
155
|
return { ...pack, cards: pack.cards.map(card => ({ ...card })) };
|
|
128
156
|
},
|
|
129
|
-
async showPack(id) {
|
|
130
|
-
|
|
157
|
+
async showPack(id) { const name = slug(id); v2(); show(name); },
|
|
158
|
+
async showCard(pack, cardId) {
|
|
159
|
+
const name = slug(pack);
|
|
131
160
|
v2();
|
|
132
|
-
if (!
|
|
133
|
-
throw fail("
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
161
|
+
if (typeof cardId !== "string" || !CARD_ID.test(cardId))
|
|
162
|
+
throw fail("invalid", "That is not a card id.");
|
|
163
|
+
show(name, cardId);
|
|
164
|
+
},
|
|
165
|
+
async open(link) {
|
|
166
|
+
const target = parseVmosLink(link);
|
|
167
|
+
open();
|
|
168
|
+
if (!target)
|
|
169
|
+
throw fail("invalid", "That is not a vmOS pack or card link.");
|
|
170
|
+
v2();
|
|
171
|
+
show(target.pack, target.kind === "card" ? target.card : undefined);
|
|
138
172
|
},
|
|
139
173
|
async player() {
|
|
140
174
|
v2();
|
|
@@ -168,7 +202,10 @@ export function createFakeOs(options = {}) {
|
|
|
168
202
|
onPause(listener) { pause.add(listener); return () => { pause.delete(listener); }; },
|
|
169
203
|
onResume(listener) { resume.add(listener); return () => { resume.delete(listener); }; },
|
|
170
204
|
onResize(listener) { resize.add(listener); return () => { resize.delete(listener); }; },
|
|
171
|
-
|
|
205
|
+
onSound(listener) { sounds.add(listener); return () => { sounds.delete(listener); }; },
|
|
206
|
+
/** the fake host never asks for a frame */
|
|
207
|
+
onCapture() { return () => { }; },
|
|
208
|
+
close() { closed = true; pause.clear(); resume.clear(); resize.clear(); sounds.clear(); watchers.clear(); },
|
|
172
209
|
});
|
|
173
210
|
return {
|
|
174
211
|
os,
|
|
@@ -191,6 +228,13 @@ export function createFakeOs(options = {}) {
|
|
|
191
228
|
for (const listener of [...resize])
|
|
192
229
|
listener(Object.freeze({ width: state.width, height: state.height }));
|
|
193
230
|
},
|
|
231
|
+
setSound(next) {
|
|
232
|
+
const previous = sound;
|
|
233
|
+
sound = soundValue({ ...sound, ...next });
|
|
234
|
+
if (previous.muted !== sound.muted || previous.volume !== sound.volume)
|
|
235
|
+
for (const listener of [...sounds])
|
|
236
|
+
listener(sound);
|
|
237
|
+
},
|
|
194
238
|
click() { clicked = true; },
|
|
195
239
|
get ready() { return ready; },
|
|
196
240
|
get progress() { return [...progress]; },
|
|
@@ -198,6 +242,7 @@ export function createFakeOs(options = {}) {
|
|
|
198
242
|
get saves() { return saves; },
|
|
199
243
|
get finished() { return finished; },
|
|
200
244
|
get shownPacks() { return [...shown]; },
|
|
245
|
+
get shownCards() { return shownCards.map(item => ({ ...item })); },
|
|
201
246
|
get maximized() { return maximized; },
|
|
202
247
|
get fullscreen() { return fullscreen; },
|
|
203
248
|
get closed() { return closed; },
|
package/dist/transport.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ export interface PortOptions {
|
|
|
7
7
|
timeoutMs?: number;
|
|
8
8
|
maxPending?: number;
|
|
9
9
|
jsonBytes?: number;
|
|
10
|
+
/** outgoing messages may be this large (default `jsonBytes`), for a protocol 1 client's captured frame */
|
|
11
|
+
outBytes?: number;
|
|
10
12
|
onEvent?: (value: Record<string, unknown>) => void;
|
|
11
13
|
/** protocol 2: the errors a request rejects with (a host error reply carries `code`) */
|
|
12
14
|
errors?: TransportErrors;
|
package/dist/transport.js
CHANGED
|
@@ -82,7 +82,7 @@ export function createRpcTransport(port, options = {}) {
|
|
|
82
82
|
pending.set(id, { resolve: value => resolve(value), reject, timer, record });
|
|
83
83
|
try {
|
|
84
84
|
const envelope = { id, request: message, ...(options.session === undefined ? {} : { session: options.session }) };
|
|
85
|
-
port.postMessage(options.jsonBytes === undefined ? envelope : appJson(envelope, options.jsonBytes));
|
|
85
|
+
port.postMessage(options.jsonBytes === undefined ? envelope : appJson(envelope, options.outBytes ?? options.jsonBytes));
|
|
86
86
|
}
|
|
87
87
|
catch (error) {
|
|
88
88
|
pending.delete(id);
|
package/dist/vibemarket-os.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var VibemarketOS=(()=>{var X=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var Ne=(e,t)=>{for(var n in t)X(e,n,{get:t[n],enumerable:!0})},$e=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ze(t))!je.call(e,s)&&s!==n&&X(e,s,{get:()=>t[s],enumerable:!(a=Te(t,s))||a.enumerable});return e};var Le=e=>$e(X({},"__esModule",{value:!0}),e);var rt={};Ne(rt,{OsError:()=>z,connect:()=>Oe});function K(e){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw Error("Invalid game completion.");let t=Object.getOwnPropertyDescriptor(e,"score");if(Reflect.ownKeys(e).length!==1||!t||!("value"in t)||!t.enumerable||typeof t.value!="number"||!Number.isInteger(t.value)||t.value<0||t.value>1e9)throw Error("Score must be an integer from 0 to 1,000,000,000.");return Object.freeze({score:t.value})}var le="vibexp";var v=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4});function W(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function Y(e,t){let n=JSON.stringify(e);if(typeof n!="string"||n.length>t||new TextEncoder().encode(n).length>t)throw Error("App message exceeds limit.");return n}function pe(e,t){if(typeof e!="string"||e.length>t||new TextEncoder().encode(e).length>t)throw Error("Invalid app message size or encoding.");return JSON.parse(e)}var ue=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Ve=(e,t)=>{let n=Object.keys(e);return n.length===t.length&&Reflect.ownKeys(e).length===n.length&&n.every(a=>t.includes(a)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,a)??{},"value"))};function de(e){let t=0,n=0,a=(i,p)=>{if(++t>v.checkpointNodes||p>v.checkpointDepth)throw Error("App checkpoint is too complex.");if(i===null||typeof i=="boolean")return;if(typeof i=="number"){if(!Number.isFinite(i))throw Error("Checkpoint numbers must be finite.");return}if(typeof i=="string"){if(i.length>v.stringBytes)throw Error("App checkpoint string is too large.");let u=new TextEncoder().encode(i).byteLength;if(u>v.stringBytes||(n+=u)>v.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(i)){if(i.length>v.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(i).length!==i.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let u=0;u<i.length;u++){let f=Object.getOwnPropertyDescriptor(i,u);if(!f||!("value"in f))throw Error("Sparse/accessor checkpoints are unsupported.");a(f.value,p+1)}return}if(!ue(i))throw Error("App checkpoint must contain only JSON values.");let l=Object.keys(i);if(Reflect.ownKeys(i).length!==l.length)throw Error("Checkpoint properties must be enumerable strings.");if(l.length>v.objectKeys)throw Error("App checkpoint has too many keys.");for(let u of l){if(["__proto__","constructor","prototype"].includes(u)||u.length>128)throw Error("Invalid app checkpoint key.");if(n+=new TextEncoder().encode(u).byteLength,n>v.checkpointBytes)throw Error("App checkpoint keys are too large.");let f=Object.getOwnPropertyDescriptor(i,u);if(!f||!("value"in f))throw Error("App checkpoint accessors are unsupported.");a(f.value,p+1)}};a(e,0);let s=JSON.stringify(e);if(new TextEncoder().encode(s).byteLength>v.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return s}function he(e){if(!ue(e)||!Ve(e,["active","width","height"])||typeof e.active!="boolean"||typeof e.width!="number"||!Number.isInteger(e.width)||e.width<0||e.width>4096||typeof e.height!="number"||!Number.isInteger(e.height)||e.height<0||e.height>4096)throw Error("Invalid app lifecycle.");return Object.freeze({active:e.active,width:e.width,height:e.height})}var at={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var ct={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},lt={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},De={packs:3,network:8,packSlugMax:56},We=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,F=e=>typeof e=="string"&&e.length<=De.packSlugMax&&We.test(e);var ge=["unsupported","not-permitted","invalid","too-large","rate-limited","needs-click","unavailable","timeout","closed"],ye=e=>typeof e=="string"&&ge.includes(e),R=Object.freeze({idleMs:900*1e3,sessionMs:14400*1e3,requestsPerSecond:10,requestsPerMinute:120,lifetimeRequests:3e4,inFlight:8,readyMs:15e3,progressReadyMs:12e4,saveBytes:1048576,saveDepth:64,saveIntervalMs:1e4,messageBytes:1101024,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),Fe=["common","rare","epic","legendary","mythic"],Be=/^[A-Za-z0-9_-]{1,64}$/,q=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}),B=1024,qe=Object.freeze({"host.hello":{request:256,response:B,states:"LFB"},"ui.progress":{request:64,response:64,rate:[4,1e3],states:"LFB"},"app.save.get":{request:64,response:11e5,rate:[6,6e4],states:"LFB"},"app.save.set":{request:11e5,response:256,rate:[1,1e4],states:"LFB"},"cards.list":{request:256,response:256*B,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*B,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*B,rate:[30,6e4],states:"LFB"},"cards.watch":{request:64,response:64,rate:[30,6e4],states:"LFB"},"pack.show":{request:128,response:64,rate:[1,1e4],states:"F"},"player.get":{request:64,response:2*B,rate:[10,6e4],states:"LFB"},"display.maximize":{request:64,response:64,rate:[2,1e3],states:"F"},"display.fullscreen":{request:64,response:64,rate:[1,1e3],states:"F"}}),ft=Object.freeze(Object.keys(qe).filter(e=>e!=="host.hello")),Ge=new TextEncoder,He=e=>Ge.encode(e).byteLength,I=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),M=(e,t,n=[])=>Reflect.ownKeys(e).every(s=>typeof s=="string"&&(t.includes(s)||n.includes(s))&&"value"in Object.getOwnPropertyDescriptor(e,s))&&t.every(s=>Object.hasOwn(e,s)),T=class extends Error{code;constructor(t,n){super(n),this.name="AppHostError",this.code=t}};function Q(e){let t=s=>new T("invalid",s),n=(s,i)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(!Number.isFinite(s))throw t("A save's numbers must be finite.");return}if(typeof s!="object")throw t("A save must contain only JSON values.");if(i>R.saveDepth)throw t(`A save nests at most ${R.saveDepth} levels deep.`);if(Array.isArray(s)){if(Reflect.ownKeys(s).length!==s.length+1)throw t("A save's arrays cannot have extra properties.");for(let p=0;p<s.length;p++){let l=Object.getOwnPropertyDescriptor(s,p);if(!l||!("value"in l))throw t("A save's arrays cannot be sparse or have accessors.");n(l.value,i+1)}return}if(!I(s))throw t("A save must contain only plain objects, arrays and JSON values.");for(let p of Reflect.ownKeys(s)){let l=Object.getOwnPropertyDescriptor(s,p);if(typeof p!="string"||!l||!("value"in l)||!l.enumerable)throw t("A save's properties must be plain enumerable data.");n(l.value,i+1)}}};n(e,1);let a=JSON.stringify(e);if(He(a)>R.saveBytes)throw new T("too-large",`A save is at most ${R.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return a}function we(e){let t;try{t=JSON.parse(e)}catch{throw new T("invalid","The saved data is not JSON.")}return Q(t),t}var _=(e,t,n=0)=>typeof e=="string"&&e.length>=n&&e.length<=t,J=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Ke=e=>typeof e=="string"&&Fe.includes(e),ee=".bin",Je=(e,t)=>`-/card/${e}/${t}${ee}`,Ze=e=>`-/cover/${e}${ee}`,Ue=e=>`-/player/${e}${ee}`;function be(e,t){if(!I(e)||!M(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:n,pack:a,name:s,art:i}=e,p=typeof n=="string"?n.slice(n.indexOf("/")+1):"";if(!F(a)||n!==`${a}/${p}`||!Be.test(p)||!_(s,120)||!Ke(e.rarity)||t&&!J(e.count,1,1e6)||i!==null&&i!==Je(a,p))throw Error("Invalid card.");return{id:n,pack:a,name:s,rarity:e.rarity,...t?{count:e.count}:{},art:i}}function te(e){return be(e,!0)}function Xe(e){return be(e,!1)}function ke(e){let{id:t,name:n,creator:a,art:s,total:i}=e;if(!F(t)||!_(n,120,1)||a!==null&&!_(a,64,1)||s!==null&&s!==Ze(t)||!J(i,0,1e4))throw Error("Invalid pack.");return{id:t,name:n,creator:a,art:s,total:i}}function Ae(e){if(!I(e)||!M(e,["id","name","creator","art","held","total"])||!J(e.held,0,1e4))throw Error("Invalid pack.");let t=ke(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function xe(e){if(!I(e)||!M(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=ke(e),n=e.cards.map(Xe);if(n.some(a=>a.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:n}}var Ye=/[\u0000-\u001F\u007F-\u009F]/,me=e=>typeof e=="string"&&q.handle.test(e);function ve(e){if(I(e)&&M(e,["guest"])&&e.guest===!0)return{guest:!0};if(!I(e)||!M(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:n,name:a,picture:s,token:i,expiresAt:p}=e;if(!me(t)||!_(a,q.nameMax,1)||Ye.test(a)||n!==void 0&&(!me(n)||n===t)||s!==null&&s!==Ue(t)||"token"in e!="expiresAt"in e||i!==void 0&&(!_(i,q.tokenMax,q.tokenMin)||!q.token.test(i)||!J(p,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...n===void 0?{}:{username:n},name:a,picture:s,...i===void 0?{}:{token:i,expiresAt:p}}}var fe=e=>_(e,64,1);function Ee(e){if(I(e)&&M(e,["reset","revision"])&&e.reset===!0&&fe(e.revision))return{reset:!0,revision:e.revision};if(!I(e)||!M(e,["changed","removed","revision"])||!Array.isArray(e.changed)||!Array.isArray(e.removed)||!fe(e.revision)||e.removed.some(t=>!_(t,130,3)))throw Error("Invalid cards event.");return{changed:e.changed.map(te),removed:e.removed,revision:e.revision}}function Pe(e){if(!I(e)||!M(e,["protocol","guest","features","root"])||e.protocol!==2||typeof e.guest!="boolean"||!Array.isArray(e.features)||e.features.length>64||e.features.some(t=>!_(t,40,1))||typeof e.root!="string"||!/^(?:\.\/|(?:\.\.\/){1,32})$/.test(e.root))throw Error("Invalid hello.");return{protocol:2,guest:e.guest,features:e.features,root:e.root}}var re="vibemarket.game.v1";function Se(e,t={}){let n=0,a=!1,s,i=new Map,p=t.jsonBytes!==void 0,l=t.errors,u=[],f=[],m=d=>{d&&(d.done=Date.now(),S())},g=()=>l?l.closed():Error("Game session ended.");function S(){let d=t.pace;for(;f.length;){let w=Date.now();for(let b=u.length-1;b>=0;b--)u[b].done!==null&&w-u[b].done>=6e4&&u.splice(b,1);let y=u.filter(b=>b.done===null||w-b.done<1e3);if(y.length<d.perSecond&&u.length<d.perMinute){f.shift()();continue}let A=y.length>=d.perSecond?{list:y,ms:1e3}:{list:u,ms:6e4},x=A.list.filter(b=>b.done!==null).map(b=>b.done+A.ms-w);x.length&&s===void 0&&(s=window.setTimeout(()=>{s=void 0,S()},Math.max(1,Math.min(...x))));return}}return e.onmessage=d=>{let w;try{w=t.jsonBytes===void 0?d.data:pe(d.data,t.jsonBytes)}catch{return}if(a||!w||typeof w!="object"||Array.isArray(w))return;let y=w;if(t.session!==void 0&&y.session!==t.session)return;if("event"in y){t.onEvent?.(y);return}if(typeof y.id!="string")return;let A=i.get(y.id);if(A)if(i.delete(y.id),window.clearTimeout(A.timer),m(A.record),typeof y.error=="string"){let x=p?y.error.slice(0,500):y.error;A.reject(l?l.reply(x,y.code):Error(x))}else"result"in y?A.resolve(y.result):A.reject(l?l.reply("Invalid host response.","unavailable"):Error("Invalid host response."))},e.start(),{request(d){if(a)return Promise.reject(g());if(i.size+f.length>=(t.maxPending??16))return Promise.reject(l?l.busy():Error("Too many pending requests."));let w=String(++n);return new Promise((y,A)=>{let x=()=>{let b=t.pace?{done:null}:void 0;b&&u.push(b);let j=window.setTimeout(()=>{i.delete(w),m(b),A(l?l.timeout():Error(t.jsonBytes===void 0?"Request timed out. Check your VibeMarket inventory before trying again; a submitted transaction may still complete.":"App request timed out. Restore the window and read its last accepted checkpoint before retrying."))},t.timeoutMs??18e4);i.set(w,{resolve:O=>y(O),reject:A,timer:j,record:b});try{let O={id:w,request:d,...t.session===void 0?{}:{session:t.session}};e.postMessage(t.jsonBytes===void 0?O:Y(O,t.jsonBytes))}catch(O){i.delete(w),window.clearTimeout(j),m(b),A(O)}};if(!t.pace){x();return}f.push(()=>{a?A(g()):x()}),S()})},destroy(){if(!a){a=!0,s!==void 0&&window.clearTimeout(s);for(let d of f.splice(0))d();i.forEach(d=>{window.clearTimeout(d.timer),d.reject(g())}),i.clear(),e.onmessage=null,e.close()}}}}function Re(e,t){return new Promise((n,a)=>{let s,i=()=>{window.clearTimeout(u),s!==void 0&&window.clearInterval(s),window.removeEventListener("message",l),e?.removeEventListener("abort",p)},p=()=>{i(),a(Error("Game session ended."))},l=m=>{if(m.source!==window.parent||!m.data||typeof m.data!="object"||!("channel"in m.data)||m.data.channel!==re||m.ports.length!==1)return;let g;if(t!==void 0){if(!("challenge"in m.data)||m.data.challenge!==t||!("session"in m.data)||!W(m.data.session))return;g=m.data.session}let S=t!==void 0&&"protocol"in m.data&&m.data.protocol===2?2:void 0;i(),n({port:m.ports[0],...g===void 0?{}:{session:g},...S===void 0?{}:{protocol:S}})},u=window.setTimeout(()=>{i(),a(Error("VibeMarket did not connect. Reopen the game."))},15e3);if(window.addEventListener("message",l),e?.addEventListener("abort",p,{once:!0}),e?.aborted){p();return}let f=()=>{let m={channel:re,type:"connect",...t===void 0?{}:{challenge:t}};window.parent.postMessage(t===void 0?m:Y(m,256),"*")};f(),t!==void 0&&(s=window.setInterval(f,250))})}var Qe="0.5.0",z=class extends Error{code;constructor(t,n){super(n),this.name="OsError",this.code=t}},et={unsupported:"This host is older than this SDK and has no such feature.","not-permitted":"The manifest does not declare that, or the app is behind another window.",invalid:"That argument is not valid.","too-large":"That is too large.","rate-limited":"Too many requests; try again later.","needs-click":"That needs a fresh click in the app.",unavailable:"The host could not answer now; try again.",timeout:"The host did not answer in 10 seconds.",closed:"The session ended. Reopen the app."},h=(e,t=et[e])=>new z(e,t),G=(e,t)=>e instanceof z?e:e instanceof T?new z(e.code,e.message):h(t,e.message),ne=e=>{if(!F(e))throw h("invalid","That is not a pack slug.");return e};async function Oe(e={}){let t=new URLSearchParams(window.location.hash.slice(1)).get(le);if(!W(t))throw h("unsupported","Open this app in VibeMarket OS or the SDK preview.");let n;try{n=await Re(e.signal,t)}catch(a){throw h(e.signal?.aborted?"closed":"timeout",a.message)}return tt(n.port,n.session,n.protocol??1,window.location.href)}async function tt(e,t,n,a){if(!W(t))throw h("unavailable","Invalid app session.");let s=Object.freeze({active:!0,width:0,height:0}),i=!1,p=new Set,l=new Set,u=new Set,f=new Set,m=Se(e,{session:t,timeoutMs:v.requestTimeoutMs,maxPending:n===2?64:v.inFlight,jsonBytes:n===2?R.messageBytes:v.responseBytes,errors:{reply:(r,o)=>h(ye(o)?o:"unavailable",r),timeout:()=>h("timeout"),closed:()=>h("closed"),busy:()=>h("rate-limited","Too many requests are waiting; try again later.")},...n===2?{pace:{perSecond:R.clientPerSecond,perMinute:R.clientPerMinute}}:{},onEvent(r){if(r.event==="app.cards"){Ie(r.state);return}if(r.event!=="app.lifecycle")return;let o;try{o=he(r.state)}catch{return}let c=s;if(s=Object.freeze({active:o.active,width:o.width,height:o.height}),c.active&&!o.active)for(let k of[...p])k();if(!c.active&&o.active)for(let k of[...l])k();if(c.width!==o.width||c.height!==o.height)for(let k of[...u])k(Object.freeze({width:o.width,height:o.height}))}}),g=async r=>{if(i)throw h("closed");let o=await m.request(r);if(!o||typeof o!="object"||Array.isArray(o))throw h("unavailable","Invalid host response.");return o},S=r=>{if(r.completed!==!0)throw h("unavailable","Invalid host acknowledgement.")},d=null;if(n===2)try{d=Pe(await g({method:"host.hello",protocol:2,sdk:Qe}))}catch(r){throw m.destroy(),G(r,"unavailable")}let w=()=>{if(!d)throw h("unsupported");return d},y=r=>r===null?null:new URL(w().root+r,a).href,A=r=>({...r,art:y(r.art)}),x=null,b=!1,j=null,O=async r=>{for(let o=0;o<4;o++){let c=[],k=null,E=null,H=!0;do{let P=await g({method:"cards.list",...r===void 0?{}:{pack:r},...k===null?{}:{after:k}});if(!Array.isArray(P.cards)||P.after!==null&&typeof P.after!="string"||typeof P.revision!="string")throw h("unavailable","Invalid host response.");if(E!==null&&P.revision!==E){H=!1;break}E=P.revision,k=P.after;for(let Ce of P.cards)c.push(A(te(Ce)))}while(k!==null);if(H&&E!==null)return r===void 0&&(x={revision:E,cards:new Map(c.map(P=>[P.id,P]))}),{cards:c,revision:E}}throw h("unavailable","The cards kept changing while they were read; try again.")},se=()=>{let r=[...x.cards.values()];for(let o of[...f])o(r.slice())},oe=r=>j??=(async()=>{try{do b=!1,await O();while(b);r&&se()}catch{}finally{j=null}})();function Ie(r){if(!f.size)return;let o;try{o=Ee(r)}catch{return}if(j){b=!0;return}if("reset"in o||!x){oe(!0);return}for(let c of o.removed)x.cards.delete(c);for(let c of o.changed)x.cards.set(c.id,A(c));x={revision:o.revision,cards:x.cards},se()}let C=null,Z=!1,ie=-1/0,N,Me=n===2?R.saveIntervalMs:0,U=()=>{if(Z||!C||N!==void 0)return;let r=ie+Me-Date.now();if(r>0){N=window.setTimeout(()=>{N=void 0,U()},r);return}let{text:o,waiters:c}=C;C=null,Z=!0;let k=JSON.parse(o);g(n===2?{method:"app.save.set",value:k}:{method:"app.checkpoint.set",value:k}).then(E=>{if(n===2?typeof E.savedAt!="string":E.completed!==!0)throw h("unavailable","Invalid host acknowledgement.")}).then(()=>{for(let E of c)E.resolve()},E=>{let H=G(E,"unavailable");for(let P of c)P.reject(H)}).finally(()=>{Z=!1,ie=Date.now(),U()})},$=null,L={get active(){return s.active},get size(){return Object.freeze({width:s.width,height:s.height})},get guest(){return d?.guest??!1},async ready(){S(await g({method:"ui.ready"}))},progress(r){if(typeof r!="number"||!Number.isFinite(r)||r<0||r>1)throw h("invalid","Progress is a number from 0 to 1.");!d||ae||(V=r,D===void 0&&(ce(),D=window.setTimeout(()=>{D=void 0,V!==null&&ce()},1e3)))},async load(){if(d){let o=await g({method:"app.save.get"});return o.value===null?null:we(JSON.stringify(o.value))}let r=await g({method:"app.checkpoint.get"});if(!("checkpoint"in r))throw h("unavailable","Invalid host response.");return r.checkpoint},save(r){let o;try{if(o=Q(r),!d){if(new TextEncoder().encode(o).byteLength>v.checkpointBytes)throw h("too-large","This host keeps at most 32 KiB, and only while the window is open.");try{de(r)}catch(c){throw h("too-large",c.message)}}}catch(c){return Promise.reject(G(c,"invalid"))}return i?Promise.reject(h("closed")):new Promise((c,k)=>{C={text:o,waiters:[...C?.waiters??[],{resolve:c,reject:k}]},U()})},async cards(r){let o=r===void 0?void 0:ne(r);return w(),(await O(o)).cards},onCards(r){return f.add(r),d&&f.size===1&&g({method:"cards.watch",on:!0}).then(()=>{x||oe(!1)},()=>{}),()=>{!f.delete(r)||f.size||!d||i||g({method:"cards.watch",on:!1}).catch(()=>{})}},async packs(){w();let r=await g({method:"cards.packs"});if(!Array.isArray(r.packs))throw h("unavailable","Invalid host response.");return r.packs.map(o=>{let c=Ae(o);return{...c,art:y(c.art)}})},async pack(r){let o=ne(r);w();let c=xe((await g({method:"cards.pack",pack:o})).pack);return{...c,art:y(c.art),cards:c.cards.map(k=>({...k,art:y(k.art)}))}},async showPack(r){let o=ne(r);if(w(),(await g({method:"pack.show",pack:o})).shown!==!0)throw h("unavailable","Invalid host acknowledgement.")},async player(){if(w(),$&&$.expiresAt-Date.now()>R.tokenReuseMs)return{...$};let r=ve(await g({method:"player.get"}));if(r.guest)return $=null,r;let o={...r,picture:y(r.picture)};return $=o.token?o:null,{...o}},async finish(r){let o;try{o=K(r)}catch(c){throw G(c,"invalid")}S(await g({method:"game.finish",...o}))},async maximize(r=!0){if(typeof r!="boolean")throw h("invalid");w(),S(await g({method:"display.maximize",on:r}))},async fullscreen(r=!0){if(typeof r!="boolean")throw h("invalid");w(),S(await g({method:"display.fullscreen",on:r}))},onPause(r){return p.add(r),()=>{p.delete(r)}},onResume(r){return l.add(r),()=>{l.delete(r)}},onResize(r){return u.add(r),()=>{u.delete(r)}},close(){i||(i=!0,N!==void 0&&window.clearTimeout(N),D!==void 0&&window.clearTimeout(D),C?.waiters.forEach(r=>r.reject(h("closed"))),C=null,p.clear(),l.clear(),u.clear(),f.clear(),m.destroy())}},V=null,D,ae=!1,ce=()=>{let r=V;V=null,g({method:"ui.progress",value:r}).catch(()=>{})},_e=L.ready;L.ready=async()=>{ae=!0,V=null,await _e()};for(let r of["ready","load","cards","packs","pack","showPack","player","finish","maximize","fullscreen"]){let o=L[r];L[r]=async(...c)=>{try{return await o(...c)}catch(k){throw G(k,"unavailable")}}}return Object.freeze(L)}return Le(rt);})();
|
|
1
|
+
"use strict";var VibemarketOS=(()=>{var pe=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var at=(e,t)=>{for(var r in t)pe(e,r,{get:t[r],enumerable:!0})},ct=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of st(t))!it.call(e,o)&&o!==r&&pe(e,o,{get:()=>t[o],enumerable:!(a=ot(t,o))||a.enumerable});return e};var lt=e=>ct(pe({},"__esModule",{value:!0}),e);var Tt={};at(Tt,{OsError:()=>M,cardLink:()=>Je,connect:()=>Ze,createAudio:()=>et,packLink:()=>Ue,parseVmosLink:()=>ie});function re(e){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw Error("Invalid game completion.");let t=Object.getOwnPropertyDescriptor(e,"score");if(Reflect.ownKeys(e).length!==1||!t||!("value"in t)||!t.enumerable||typeof t.value!="number"||!Number.isInteger(t.value)||t.value<0||t.value>1e9)throw Error("Score must be an integer from 0 to 1,000,000,000.");return Object.freeze({score:t.value})}var xe="vibexp";var S=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4}),ue=1e6;var de=e=>typeof e=="string"&&/^[1-9]\d{0,15}$/.test(e),oe=e=>typeof e=="string"&&e.length<=ue&&/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(e);function J(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function me(e,t){let r=JSON.stringify(e);if(typeof r!="string"||r.length>t||new TextEncoder().encode(r).length>t)throw Error("App message exceeds limit.");return r}function Ee(e,t){if(typeof e!="string"||e.length>t||new TextEncoder().encode(e).length>t)throw Error("Invalid app message size or encoding.");return JSON.parse(e)}var he=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Se=(e,t)=>{let r=Object.keys(e);return r.length===t.length&&Reflect.ownKeys(e).length===r.length&&r.every(a=>t.includes(a)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,a)??{},"value"))};function Re(e){let t=0,r=0,a=(s,l)=>{if(++t>S.checkpointNodes||l>S.checkpointDepth)throw Error("App checkpoint is too complex.");if(s===null||typeof s=="boolean")return;if(typeof s=="number"){if(!Number.isFinite(s))throw Error("Checkpoint numbers must be finite.");return}if(typeof s=="string"){if(s.length>S.stringBytes)throw Error("App checkpoint string is too large.");let p=new TextEncoder().encode(s).byteLength;if(p>S.stringBytes||(r+=p)>S.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(s)){if(s.length>S.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(s).length!==s.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let p=0;p<s.length;p++){let y=Object.getOwnPropertyDescriptor(s,p);if(!y||!("value"in y))throw Error("Sparse/accessor checkpoints are unsupported.");a(y.value,l+1)}return}if(!he(s))throw Error("App checkpoint must contain only JSON values.");let c=Object.keys(s);if(Reflect.ownKeys(s).length!==c.length)throw Error("Checkpoint properties must be enumerable strings.");if(c.length>S.objectKeys)throw Error("App checkpoint has too many keys.");for(let p of c){if(["__proto__","constructor","prototype"].includes(p)||p.length>128)throw Error("Invalid app checkpoint key.");if(r+=new TextEncoder().encode(p).byteLength,r>S.checkpointBytes)throw Error("App checkpoint keys are too large.");let y=Object.getOwnPropertyDescriptor(s,p);if(!y||!("value"in y))throw Error("App checkpoint accessors are unsupported.");a(y.value,l+1)}};a(e,0);let o=JSON.stringify(e);if(new TextEncoder().encode(o).byteLength>S.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return o}var Z=Object.freeze({muted:!1,volume:1});function Pe(e){if(!he(e)||!Se(e,["muted","volume"])||typeof e.muted!="boolean"||typeof e.volume!="number"||!Number.isFinite(e.volume)||e.volume<0||e.volume>1)throw Error("Invalid app sound.");return Object.freeze({muted:e.muted,volume:e.volume})}function Oe(e){if(!he(e)||!Se(e,["active","width","height"])||typeof e.active!="boolean"||typeof e.width!="number"||!Number.isInteger(e.width)||e.width<0||e.width>4096||typeof e.height!="number"||!Number.isInteger(e.height)||e.height<0||e.height>4096)throw Error("Invalid app lifecycle.");return Object.freeze({active:e.active,width:e.width,height:e.height})}var Nt={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var Vt={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},Dt={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},pt={packs:3,network:8,packSlugMax:56},ut=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,I=e=>typeof e=="string"&&e.length<=pt.packSlugMax&&ut.test(e);var _e=["unsupported","not-permitted","invalid","too-large","rate-limited","needs-click","unavailable","timeout","closed"],Ie=e=>typeof e=="string"&&_e.includes(e),T=Object.freeze({idleMs:900*1e3,sessionMs:14400*1e3,requestsPerSecond:10,requestsPerMinute:120,lifetimeRequests:3e4,inFlight:8,readyMs:15e3,progressReadyMs:12e4,saveBytes:1048576,saveDepth:64,saveIntervalMs:1e4,messageBytes:1101024,frameChars:ue,captureMs:1200,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),dt=["common","rare","epic","legendary","mythic"],Q=/^[A-Za-z0-9_-]{1,64}$/,Y=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}),X=1024,mt=Object.freeze({"host.hello":{request:256,response:X,states:"LFB"},"ui.progress":{request:64,response:64,rate:[4,1e3],states:"LFB"},"app.frame":{request:1000256,response:64,rate:[4,1e3],states:"LFB"},"app.save.get":{request:64,response:11e5,rate:[6,6e4],states:"LFB"},"app.save.set":{request:11e5,response:256,rate:[1,1e4],states:"LFB"},"cards.list":{request:256,response:256*X,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*X,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*X,rate:[30,6e4],states:"LFB"},"cards.watch":{request:64,response:64,rate:[30,6e4],states:"LFB"},"pack.show":{request:128,response:64,rate:[1,1e4],bucket:"show",states:"F"},"card.show":{request:192,response:64,rate:[1,1e4],bucket:"show",states:"F"},"player.get":{request:64,response:2*X,rate:[10,6e4],states:"LFB"},"display.maximize":{request:64,response:64,rate:[2,1e3],states:"F"},"display.fullscreen":{request:64,response:64,rate:[1,1e3],states:"F"}}),qt=Object.freeze(Object.keys(mt).filter(e=>e!=="host.hello"&&e!=="card.show")),ht=new TextEncoder,ft=e=>ht.encode(e).byteLength,L=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),z=(e,t,r=[])=>Reflect.ownKeys(e).every(o=>typeof o=="string"&&(t.includes(o)||r.includes(o))&&"value"in Object.getOwnPropertyDescriptor(e,o))&&t.every(o=>Object.hasOwn(e,o)),M=class extends Error{code;constructor(t,r){super(r),this.name="OsError",this.code=t}},N=class extends Error{code;constructor(t,r){super(r),this.name="AppHostError",this.code=t}};function fe(e){let t=o=>new N("invalid",o),r=(o,s)=>{if(!(o===null||typeof o=="boolean"||typeof o=="string")){if(typeof o=="number"){if(!Number.isFinite(o))throw t("A save's numbers must be finite.");return}if(typeof o!="object")throw t("A save must contain only JSON values.");if(s>T.saveDepth)throw t(`A save nests at most ${T.saveDepth} levels deep.`);if(Array.isArray(o)){if(Reflect.ownKeys(o).length!==o.length+1)throw t("A save's arrays cannot have extra properties.");for(let l=0;l<o.length;l++){let c=Object.getOwnPropertyDescriptor(o,l);if(!c||!("value"in c))throw t("A save's arrays cannot be sparse or have accessors.");r(c.value,s+1)}return}if(!L(o))throw t("A save must contain only plain objects, arrays and JSON values.");for(let l of Reflect.ownKeys(o)){let c=Object.getOwnPropertyDescriptor(o,l);if(typeof l!="string"||!c||!("value"in c)||!c.enumerable)throw t("A save's properties must be plain enumerable data.");r(c.value,s+1)}}};r(e,1);let a=JSON.stringify(e);if(ft(a)>T.saveBytes)throw new N("too-large",`A save is at most ${T.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return a}function Te(e){let t;try{t=JSON.parse(e)}catch{throw new N("invalid","The saved data is not JSON.")}return fe(t),t}var j=(e,t,r=0)=>typeof e=="string"&&e.length>=r&&e.length<=t,se=(e,t,r)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=r,gt=e=>typeof e=="string"&&dt.includes(e),ge=".bin",yt=(e,t)=>`-/card/${e}/${t}${ge}`,wt=e=>`-/cover/${e}${ge}`,kt=e=>`-/player/${e}${ge}`;function Le(e,t){if(!L(e)||!z(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:r,pack:a,name:o,art:s}=e,l=typeof r=="string"?r.slice(r.indexOf("/")+1):"";if(!I(a)||r!==`${a}/${l}`||!Q.test(l)||!j(o,120)||!gt(e.rarity)||t&&!se(e.count,1,1e6)||s!==null&&s!==yt(a,l))throw Error("Invalid card.");return{id:r,pack:a,name:o,rarity:e.rarity,...t?{count:e.count}:{},art:s}}function ye(e){return Le(e,!0)}function bt(e){return Le(e,!1)}function ze(e){let{id:t,name:r,creator:a,art:o,total:s}=e;if(!I(t)||!j(r,120,1)||a!==null&&!j(a,64,1)||o!==null&&o!==wt(t)||!se(s,0,1e4))throw Error("Invalid pack.");return{id:t,name:r,creator:a,art:o,total:s}}function je(e){if(!L(e)||!z(e,["id","name","creator","art","held","total"])||!se(e.held,0,1e4))throw Error("Invalid pack.");let t=ze(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function $e(e){if(!L(e)||!z(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=ze(e),r=e.cards.map(bt);if(r.some(a=>a.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:r}}var At=/[\u0000-\u001F\u007F-\u009F]/,Ce=e=>typeof e=="string"&&Y.handle.test(e);function Ne(e){if(L(e)&&z(e,["guest"])&&e.guest===!0)return{guest:!0};if(!L(e)||!z(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:r,name:a,picture:o,token:s,expiresAt:l}=e;if(!Ce(t)||!j(a,Y.nameMax,1)||At.test(a)||r!==void 0&&(!Ce(r)||r===t)||o!==null&&o!==kt(t)||"token"in e!="expiresAt"in e||s!==void 0&&(!j(s,Y.tokenMax,Y.tokenMin)||!Y.token.test(s)||!se(l,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...r===void 0?{}:{username:r},name:a,picture:o,...s===void 0?{}:{token:s,expiresAt:l}}}var Me=e=>j(e,64,1);function Ve(e){if(L(e)&&z(e,["reset","revision"])&&e.reset===!0&&Me(e.revision))return{reset:!0,revision:e.revision};if(!L(e)||!z(e,["changed","removed","revision"])||!Array.isArray(e.changed)||!Array.isArray(e.removed)||!Me(e.revision)||e.removed.some(t=>!j(t,130,3)))throw Error("Invalid cards event.");return{changed:e.changed.map(ye),removed:e.removed,revision:e.revision}}function De(e){if(!L(e)||!z(e,["protocol","guest","features","root"])||e.protocol!==2||typeof e.guest!="boolean"||!Array.isArray(e.features)||e.features.length>64||e.features.some(t=>!j(t,40,1))||typeof e.root!="string"||!/^(?:\.\/|(?:\.\.\/){1,32})$/.test(e.root))throw Error("Invalid hello.");return{protocol:2,guest:e.guest,features:e.features,root:e.root}}var vt=1280,xt=[.85,.6,.4];function Et(e){let t=null,r=0;for(let a of Array.from(e.querySelectorAll("canvas"))){let o=a.getBoundingClientRect(),s=o.width*o.height;s>r&&a.width>0&&a.height>0&&(t=a,r=s)}return t}function St(e,t){try{let r=e.width,a=e.height;if(!(r>0&&a>0))return null;let o=Math.min(1,vt/Math.max(r,a)),s=t.createElement("canvas");s.width=Math.max(1,Math.round(r*o)),s.height=Math.max(1,Math.round(a*o));let l=s.getContext("2d");if(!l)return null;l.drawImage(e,0,0,s.width,s.height);for(let c of xt){let p=s.toDataURL("image/webp",c);if(p.startsWith("data:image/webp")||(p=s.toDataURL("image/jpeg",c)),oe(p))return p}return null}catch{return null}}function Fe(e,t){return typeof e=="string"?oe(e)?e:null:e!==null&&typeof e=="object"&&"getContext"in e&&"toDataURL"in e?St(e,t):null}function Be(e,t){let r=null,a=()=>globalThis.document,o=(s,l)=>{if(!t())try{e(s,l)}catch{}};return{on(s){return r=s,()=>{r===s&&(r=null)}},clear(){r=null},event(s){if(!(t()||!de(s)))try{let l=r;if(l){Promise.resolve().then(l).then(c=>Fe(c,a()),()=>null).then(c=>o(s,c),()=>{});return}requestAnimationFrame(()=>{let c=null;try{let p=Et(a());c=p?Fe(p,a()):null}catch{c=null}o(s,c)})}catch{}}}}var we="vibemarket.game.v1";function We(e,t={}){let r=0,a=!1,o,s=new Map,l=t.jsonBytes!==void 0,c=t.errors,p=[],y=[],f=k=>{k&&(k.done=Date.now(),x())},E=()=>c?c.closed():Error("Game session ended.");function x(){let k=t.pace;for(;y.length;){let m=Date.now();for(let h=p.length-1;h>=0;h--)p[h].done!==null&&m-p[h].done>=6e4&&p.splice(h,1);let w=p.filter(h=>h.done===null||m-h.done<1e3);if(w.length<k.perSecond&&p.length<k.perMinute){y.shift()();continue}let b=w.length>=k.perSecond?{list:w,ms:1e3}:{list:p,ms:6e4},A=b.list.filter(h=>h.done!==null).map(h=>h.done+b.ms-m);A.length&&o===void 0&&(o=window.setTimeout(()=>{o=void 0,x()},Math.max(1,Math.min(...A))));return}}return e.onmessage=k=>{let m;try{m=t.jsonBytes===void 0?k.data:Ee(k.data,t.jsonBytes)}catch{return}if(a||!m||typeof m!="object"||Array.isArray(m))return;let w=m;if(t.session!==void 0&&w.session!==t.session)return;if("event"in w){t.onEvent?.(w);return}if(typeof w.id!="string")return;let b=s.get(w.id);if(b)if(s.delete(w.id),window.clearTimeout(b.timer),f(b.record),typeof w.error=="string"){let A=l?w.error.slice(0,500):w.error;b.reject(c?c.reply(A,w.code):Error(A))}else"result"in w?b.resolve(w.result):b.reject(c?c.reply("Invalid host response.","unavailable"):Error("Invalid host response."))},e.start(),{request(k){if(a)return Promise.reject(E());if(s.size+y.length>=(t.maxPending??16))return Promise.reject(c?c.busy():Error("Too many pending requests."));let m=String(++r);return new Promise((w,b)=>{let A=()=>{let h=t.pace?{done:null}:void 0;h&&p.push(h);let O=window.setTimeout(()=>{s.delete(m),f(h),b(c?c.timeout():Error(t.jsonBytes===void 0?"Request timed out. Check your VibeMarket inventory before trying again; a submitted transaction may still complete.":"App request timed out. Restore the window and read its last accepted checkpoint before retrying."))},t.timeoutMs??18e4);s.set(m,{resolve:C=>w(C),reject:b,timer:O,record:h});try{let C={id:m,request:k,...t.session===void 0?{}:{session:t.session}};e.postMessage(t.jsonBytes===void 0?C:me(C,t.outBytes??t.jsonBytes))}catch(C){s.delete(m),window.clearTimeout(O),f(h),b(C)}};if(!t.pace){A();return}y.push(()=>{a?b(E()):A()}),x()})},destroy(){if(!a){a=!0,o!==void 0&&window.clearTimeout(o);for(let k of y.splice(0))k();s.forEach(k=>{window.clearTimeout(k.timer),k.reject(E())}),s.clear(),e.onmessage=null,e.close()}}}}function Ge(e,t){return new Promise((r,a)=>{let o,s=()=>{window.clearTimeout(p),o!==void 0&&window.clearInterval(o),window.removeEventListener("message",c),e?.removeEventListener("abort",l)},l=()=>{s(),a(Error("Game session ended."))},c=f=>{if(f.source!==window.parent||!f.data||typeof f.data!="object"||!("channel"in f.data)||f.data.channel!==we||f.ports.length!==1)return;let E;if(t!==void 0){if(!("challenge"in f.data)||f.data.challenge!==t||!("session"in f.data)||!J(f.data.session))return;E=f.data.session}let x=t!==void 0&&"protocol"in f.data&&f.data.protocol===2?2:void 0;s(),r({port:f.ports[0],...E===void 0?{}:{session:E},...x===void 0?{}:{protocol:x}})},p=window.setTimeout(()=>{s(),a(Error("VibeMarket did not connect. Reopen the game."))},15e3);if(window.addEventListener("message",c),e?.addEventListener("abort",l,{once:!0}),e?.aborted){l();return}let y=()=>{let f={channel:we,type:"connect",...t===void 0?{}:{challenge:t}};window.parent.postMessage(t===void 0?f:me(f,256),"*")};y(),t!==void 0&&(o=window.setInterval(y,250))})}var Rt=200,ke="[a-z0-9]+(?:-[a-z0-9]+)*",Pt="[A-Za-z0-9_-]{1,64}",He=new RegExp(`^vmos://pack/(${ke})$`),qe=new RegExp(`^vmos://card/(${ke})/(${Pt})$`),Ke=new RegExp(`^https://(?:www\\.)?vibechain\\.com/os/pack/(${ke})/?$`),nn=Object.freeze({pack:He,card:qe,web:Ke});function ie(e){if(typeof e!="string"||e.length>Rt)return null;let t=qe.exec(e);if(t)return I(t[1])?{kind:"card",pack:t[1],card:t[2]}:null;let r=He.exec(e)??Ke.exec(e);return r&&I(r[1])?{kind:"pack",pack:r[1]}:null}function Ue(e){if(!I(e))throw new M("invalid","That is not a pack slug.");return`vmos://pack/${e}`}function Je(e,t){if(!I(e)||typeof t!="string"||!Q.test(t))throw new M("invalid","That is not a pack slug and a card id.");return`vmos://card/${e}/${t}`}var Ot="0.5.2",Ct=Object.freeze({unsupported:"This host is older than this SDK and has no such feature.","not-permitted":"The manifest does not declare that, or the app is behind another window.",invalid:"That argument is not valid.","too-large":"That is too large.","rate-limited":"Too many requests; try again later.","needs-click":"That needs a fresh click in the app.",unavailable:"The host could not answer now; try again.",timeout:"The host did not answer in 10 seconds.",closed:"The session ended. Reopen the app."}),Mt=Ct,g=(e,t=Mt[e])=>new M(e,t),ee=(e,t)=>e instanceof M?e:e instanceof N?new M(e.code,e.message):g(t,e.message),ae=e=>{if(!I(e))throw g("invalid","That is not a pack slug.");return e};async function Ze(e={}){let t=new URLSearchParams(window.location.hash.slice(1)).get(xe);if(!J(t))throw g("unsupported","Open this app in VibeMarket OS or the SDK preview.");let r;try{r=await Ge(e.signal,t)}catch(a){throw g(e.signal?.aborted?"closed":"timeout",a.message)}return _t(r.port,r.session,r.protocol??1,window.location.href)}async function _t(e,t,r,a){if(!J(t))throw g("unavailable","Invalid app session.");let o=Object.freeze({active:!0,width:0,height:0}),s=!1,l=Z,c=new Set,p=new Set,y=new Set,f=new Set,E=new Set,x=We(e,{session:t,timeoutMs:S.requestTimeoutMs,maxPending:r===2?64:S.inFlight,jsonBytes:r===2?T.messageBytes:S.responseBytes,errors:{reply:(n,i)=>g(Ie(i)?i:"unavailable",n),timeout:()=>g("timeout"),closed:()=>g("closed"),busy:()=>g("rate-limited","Too many requests are waiting; try again later.")},...r===2?{pace:{perSecond:T.clientPerSecond,perMinute:T.clientPerMinute}}:{},onEvent(n){if(n.event==="app.cards"){V(n.state);return}if(n.event==="app.capture"){k.event(n.id);return}if(n.event==="app.sound"){w(n.state);return}if(n.event!=="app.lifecycle")return;let i;try{i=Oe(n.state)}catch{return}let u=o;if(o=Object.freeze({active:i.active,width:i.width,height:i.height}),u.active&&!i.active)for(let v of[...c])v();if(!u.active&&i.active)for(let v of[...p])v();if(u.width!==i.width||u.height!==i.height)for(let v of[...y])v(Object.freeze({width:i.width,height:i.height}))}}),k=Be((n,i)=>{m({method:"app.frame",id:n,image:i}).catch(()=>{})},()=>r!==2||!A||s),m=async n=>{if(s)throw g("closed");let i=await x.request(n);if(!i||typeof i!="object"||Array.isArray(i))throw g("unavailable","Invalid host response.");return i};function w(n){let i;try{i=Pe(n)}catch{return}if(!(i.muted===l.muted&&i.volume===l.volume)){l=i;for(let u of[...E])u(l)}}let b=n=>{if(n.completed!==!0)throw g("unavailable","Invalid host acknowledgement.")},A=null;if(r===2)try{A=De(await m({method:"host.hello",protocol:2,sdk:Ot}))}catch(n){throw x.destroy(),ee(n,"unavailable")}let h=()=>{if(!A)throw g("unsupported");return A},O=n=>n===null?null:new URL(h().root+n,a).href,C=n=>({...n,art:O(n.art)}),_=null,D=!1,F=null,B=async n=>{for(let i=0;i<4;i++){let u=[],v=null,R=null,ne=!0;do{let P=await m({method:"cards.list",...n===void 0?{}:{pack:n},...v===null?{}:{after:v}});if(!Array.isArray(P.cards)||P.after!==null&&typeof P.after!="string"||typeof P.revision!="string")throw g("unavailable","Invalid host response.");if(R!==null&&P.revision!==R){ne=!1;break}R=P.revision,v=P.after;for(let rt of P.cards)u.push(C(ye(rt)))}while(v!==null);if(ne&&R!==null)return n===void 0&&(_={revision:R,cards:new Map(u.map(P=>[P.id,P]))}),{cards:u,revision:R}}throw g("unavailable","The cards kept changing while they were read; try again.")},W=()=>{let n=[..._.cards.values()];for(let i of[...f])i(n.slice())},d=n=>F??=(async()=>{try{do D=!1,await B();while(D);n&&W()}catch{}finally{F=null}})();function V(n){if(!f.size)return;let i;try{i=Ve(n)}catch{return}if(F){D=!0;return}if("reset"in i||!_){d(!0);return}for(let u of i.removed)_.cards.delete(u);for(let u of i.changed)_.cards.set(u.id,C(u));_={revision:i.revision,cards:_.cards},W()}let $=null,ce=!1,be=-1/0,G,tt=r===2?T.saveIntervalMs:0,le=()=>{if(ce||!$||G!==void 0)return;let n=be+tt-Date.now();if(n>0){G=window.setTimeout(()=>{G=void 0,le()},n);return}let{text:i,waiters:u}=$;$=null,ce=!0;let v=JSON.parse(i);m(r===2?{method:"app.save.set",value:v}:{method:"app.checkpoint.set",value:v}).then(R=>{if(r===2?typeof R.savedAt!="string":R.completed!==!0)throw g("unavailable","Invalid host acknowledgement.")}).then(()=>{for(let R of u)R.resolve()},R=>{let ne=ee(R,"unavailable");for(let P of u)P.reject(ne)}).finally(()=>{ce=!1,be=Date.now(),le()})},H=null,te=async n=>{let i=h();if(n.method==="card.show"&&!i.features.includes("card.show"))throw g("unsupported");if((await m(n)).shown!==!0)throw g("unavailable","Invalid host acknowledgement.")},q={get active(){return o.active},get size(){return Object.freeze({width:o.width,height:o.height})},get guest(){return A?.guest??!1},get sound(){return l},async ready(){b(await m({method:"ui.ready"}))},progress(n){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>1)throw g("invalid","Progress is a number from 0 to 1.");!A||Ae||(K=n,U===void 0&&(ve(),U=window.setTimeout(()=>{U=void 0,K!==null&&ve()},1e3)))},async load(){if(A){let i=await m({method:"app.save.get"});return i.value===null?null:Te(JSON.stringify(i.value))}let n=await m({method:"app.checkpoint.get"});if(!("checkpoint"in n))throw g("unavailable","Invalid host response.");return n.checkpoint},save(n){let i;try{if(i=fe(n),!A){if(new TextEncoder().encode(i).byteLength>S.checkpointBytes)throw g("too-large","This host keeps at most 32 KiB, and only while the window is open.");try{Re(n)}catch(u){throw g("too-large",u.message)}}}catch(u){return Promise.reject(ee(u,"invalid"))}return s?Promise.reject(g("closed")):new Promise((u,v)=>{$={text:i,waiters:[...$?.waiters??[],{resolve:u,reject:v}]},le()})},async cards(n){let i=n===void 0?void 0:ae(n);return h(),(await B(i)).cards},onCards(n){return f.add(n),A&&f.size===1&&m({method:"cards.watch",on:!0}).then(()=>{_||d(!1)},()=>{}),()=>{!f.delete(n)||f.size||!A||s||m({method:"cards.watch",on:!1}).catch(()=>{})}},async packs(){h();let n=await m({method:"cards.packs"});if(!Array.isArray(n.packs))throw g("unavailable","Invalid host response.");return n.packs.map(i=>{let u=je(i);return{...u,art:O(u.art)}})},async pack(n){let i=ae(n);h();let u=$e((await m({method:"cards.pack",pack:i})).pack);return{...u,art:O(u.art),cards:u.cards.map(v=>({...v,art:O(v.art)}))}},async showPack(n){let i=ae(n);h(),await te({method:"pack.show",pack:i})},async showCard(n,i){let u=ae(n);if(typeof i!="string"||!Q.test(i))throw g("invalid","That is not a card id.");await te({method:"card.show",pack:u,card:i})},async open(n){let i=ie(n);if(!i)throw g("invalid","That is not a vmOS pack or card link.");await(i.kind==="pack"?te({method:"pack.show",pack:i.pack}):te({method:"card.show",pack:i.pack,card:i.card}))},async player(){if(h(),H&&H.expiresAt-Date.now()>T.tokenReuseMs)return{...H};let n=Ne(await m({method:"player.get"}));if(n.guest)return H=null,n;let i={...n,picture:O(n.picture)};return H=i.token?i:null,{...i}},async finish(n){let i;try{i=re(n)}catch(u){throw ee(u,"invalid")}b(await m({method:"game.finish",...i}))},async maximize(n=!0){if(typeof n!="boolean")throw g("invalid");h(),b(await m({method:"display.maximize",on:n}))},async fullscreen(n=!0){if(typeof n!="boolean")throw g("invalid");h(),b(await m({method:"display.fullscreen",on:n}))},onPause(n){return c.add(n),()=>{c.delete(n)}},onResume(n){return p.add(n),()=>{p.delete(n)}},onCapture(n){if(typeof n!="function")throw g("invalid","A capture handler is a function.");return k.on(n)},onResize(n){return y.add(n),()=>{y.delete(n)}},onSound(n){return E.add(n),()=>{E.delete(n)}},close(){s||(s=!0,G!==void 0&&window.clearTimeout(G),U!==void 0&&window.clearTimeout(U),$?.waiters.forEach(n=>n.reject(g("closed"))),$=null,k.clear(),c.clear(),p.clear(),y.clear(),E.clear(),f.clear(),x.destroy())}},K=null,U,Ae=!1,ve=()=>{let n=K;K=null,m({method:"ui.progress",value:n}).catch(()=>{})},nt=q.ready;q.ready=async()=>{Ae=!0,K=null,await nt()};for(let n of["ready","load","cards","packs","pack","showPack","showCard","open","player","finish","maximize","fullscreen"]){let i=q[n];q[n]=async(...u)=>{try{return await i(...u)}catch(v){throw ee(v,"unavailable")}}}return Object.freeze(q)}var Xe=.05,Ye=Object.freeze(["pointerdown","pointerup","keydown","touchend"]),Qe=Object.freeze({gestures:3,remakes:3});function It(e){if("lifecycle"in e){let t=e.sound;return{active:()=>e.lifecycle.current().active,sound:()=>t?.current()??Z,onActive(r){let a=e.lifecycle.current().active;return e.lifecycle.onChanged(o=>{o.active!==a&&(a=o.active,r(a))})},onSound:r=>t?t.onChanged(r):()=>{}}}return{active:()=>e.active,sound:()=>e.sound??Z,onActive(t){let r=[e.onPause(()=>t(!1)),e.onResume(()=>t(!0))];return()=>{for(let a of r)a()}},onSound:t=>typeof e.onSound=="function"?e.onSound(t):()=>{}}}function et(e,t={}){let r=It(e),a=()=>new AudioContext({latencyHint:t.latencyHint??"interactive"}),o=t.context??a(),s=o.createGain(),l=!1,c=!1,p=!1,y=r.active(),f=0,E=0,x,k=new Set,m=()=>{let d=r.sound();return d.muted||l||!y?0:d.volume},w=()=>{for(let d of[...k])d()},b=()=>{let d=o.currentTime,V=s.gain;V.cancelScheduledValues(d),V.setValueAtTime(V.value,d),V.linearRampToValueAtTime(m(),d+Xe)},A=()=>!p&&!c&&y,h=()=>{A()&&o.state!=="running"&&o.resume().catch(()=>{})},O=()=>{if(o.state==="running"&&(f=0),o.state==="closed"&&!p){_();return}w()},C=()=>{s.gain.value=m(),s.connect(o.destination),o.addEventListener("statechange",O)};function _(){if(E>=Qe.remakes)return;E++,f=0;let d=o;d.removeEventListener("statechange",O),d.state!=="closed"&&d.close().catch(()=>{});try{o=a()}catch{o=d;return}s=o.createGain(),C(),h(),w()}let D=()=>{clearTimeout(x),x=setTimeout(()=>{x=void 0,!p&&!A()&&o.state==="running"&&o.suspend().catch(()=>{})},Xe*1e3+20)},F=[r.onSound(()=>{b(),w()}),r.onActive(d=>{y=d,b(),y?(clearTimeout(x),h()):D(),w()})],B=()=>{!A()||o.state==="running"||(++f>Qe.gestures?_():h())},W=()=>{document.visibilityState==="visible"&&h()};for(let d of Ye)window.addEventListener(d,B,{capture:!0,passive:!0});return document.addEventListener("visibilitychange",W),C(),h(),{get context(){return o},get master(){return s},get desktop(){return r.sound()},get audible(){let d=r.sound();return!d.muted&&d.volume>0&&!l&&y&&o.state==="running"},get muted(){return l},set muted(d){d!==l&&(l=d,b(),w())},get paused(){return c},set paused(d){d!==c&&(c=d,c?o.suspend().catch(()=>{}):h(),w())},onChange(d){return k.add(d),()=>{k.delete(d)}},close(){if(!p){p=!0,clearTimeout(x);for(let d of F)d();for(let d of Ye)window.removeEventListener(d,B,{capture:!0});document.removeEventListener("visibilitychange",W),o.removeEventListener("statechange",O),k.clear(),o.close().catch(()=>{})}}}}return lt(Tt);})();
|
|
@@ -1,24 +1,43 @@
|
|
|
1
1
|
# Paw Beat
|
|
2
2
|
|
|
3
|
-
A 3D rhythm game for VibeMarket OS, written in TypeScript with Three.js. Arrows slide down four lanes toward their outlines. Press the matching key as each one lands (arrow keys, WASD or the on-screen pads) and Biscuit the cat dances that step: a side step and point for left and right, a leap with paws up for up, a squat and floor pat for down. Timing is judged perfect, great or good; every ten steps in a row adds 10% to each step, up to double, and combos of 10, 25, 50, 75 and 100 earn a spin and confetti. A miss makes Biscuit stumble.
|
|
3
|
+
A 3D rhythm game for VibeMarket OS, written in TypeScript with Three.js. Arrows slide down four lanes toward their outlines. Press the matching key as each one lands (arrow keys, WASD or the on-screen pads) and Biscuit the cat dances that step: a side step and point for left and right, a leap with paws up for up, a squat and floor pat for down. Timing is judged perfect, great or good; every ten steps in a row adds 10% to each step, up to double, and combos of 10, 25, 50, 75 and 100 earn a spin and confetti. A miss makes Biscuit stumble. There are six tracks of about a minute each; a random one plays when you start, never the same one twice in a row, and **Next track** on the title card picks another. Each round ends with a results card: grade, score, accuracy, best combo and every judgement, with your personal best on that track marked.
|
|
4
|
+
|
|
5
|
+
## The tracks
|
|
6
|
+
|
|
7
|
+
| Track | Tempo | Key | Character |
|
|
8
|
+
|---|---|---|---|
|
|
9
|
+
| Biscuit's Groove | 120 | A minor | The original song: a four-on-the-floor dance beat with a saw-and-square lead that builds, drops and comes home |
|
|
10
|
+
| Sunny Windowsill | 100, swung | F major | A lazy shuffle: electric piano, a slap of bass, a whistled verse and a chorus walked down the chords |
|
|
11
|
+
| Midnight Zoomies | 140 | E minor | A broken beat with a growling, detuned bass and a bright supersaw hook; a lift through B major into the finale |
|
|
12
|
+
| Yarn Ball Waltz | 150, in 3/4 | D major | A music-box waltz on a strummed nylon guitar, with a borrowed G minor chord for a wistful turn |
|
|
13
|
+
| Rooftop Bossa | 112 | G minor (dorian) | A bossa nova: nylon strings, a soft flute, a clave on the rim and a bridge through B-flat |
|
|
14
|
+
| Laser Pointer | 132 | C major, then D | Chiptune: square waves, racing arpeggios, noise drums and a key change for the last level |
|
|
15
|
+
|
|
16
|
+
All six are original, written for this example, and played by the same instruments in `synth.ts`.
|
|
4
17
|
|
|
5
18
|
It is a complete example of the app API and of a small game built entirely in code:
|
|
6
19
|
|
|
7
20
|
| File | What it shows |
|
|
8
21
|
|---|---|
|
|
9
|
-
| `game.ts` | The rules as pure TypeScript with no DOM, renderer or audio, so they can be unit-tested:
|
|
22
|
+
| `game.ts` | The rules as pure TypeScript with no DOM, renderer or audio, so they can be unit-tested: reading a track (note and chord names, sections, swing), a chart generator that writes fair steps from the track's own tune, timing judgement, combo bonus, the grade, picking the next track and the personal bests |
|
|
23
|
+
| `tracks.ts` | The six tracks as plain data: tempo, meter, sections, chords, the tune as note names, and the drum, bass, pad and arpeggio patterns |
|
|
24
|
+
| `synth.ts` | The instruments, all oscillators and noise (four drum kits, five basses, six leads, five pads, arpeggios, risers and cymbal swells), a tempo-synced echo and a small generated room, ducking under the kick and a soft limiter; and the player that turns a track's data into sound |
|
|
10
25
|
| `cat.ts` | Biscuit, built at runtime: smooth body parts meshed from signed distance functions ("surface nets"), a toon shader with rim light and outline, a face painted by the shader so expressions are a few numbers, two-bone inverse kinematics for arms and legs, a tube tail rewritten every frame, and spring-blended dance moves |
|
|
11
|
-
| `stage.ts` | The dance floor, backdrop and spotlights as single shader meshes that pulse with the beat and take
|
|
12
|
-
| `music.ts` | The
|
|
13
|
-
| `main.ts` | `connectVibeMarketApp()`, `fitCanvas` (with WebGL context loss handled) and `
|
|
26
|
+
| `stage.ts` | The dance floor, backdrop and spotlights as single shader meshes that pulse with the beat and take the track's colours, tinted by each section; the lanes and targets; every note in one instanced mesh; pooled sparks and confetti; camera framings that fit any window size |
|
|
27
|
+
| `music.ts` | The live song: the chosen track scheduled a beat at a time ahead of the audio clock, which also times the steps, through the SDK's audio helper |
|
|
28
|
+
| `main.ts` | `connectVibeMarketApp()`, `fitCanvas` (with WebGL context loss handled), `createLoop` and `createAudio` (the desktop's sound) from the SDK helpers; the title, play and results flow; the track choice; a checkpoint for the personal bests and the sound setting; and `game.finish({ score })` |
|
|
14
29
|
| `index.html` | The page: the canvas, the score and progress display, the judgement and combo callout, the touch pads, the title and results cards, all styled inline |
|
|
15
30
|
|
|
16
|
-
Nothing is downloaded or generated outside the game: there are no models, textures, fonts, samples or images in the bundle. It is `index.html`, one script, the manifest and the three store images in `store/`, which are captures of the game itself.
|
|
31
|
+
Nothing is downloaded or generated outside the game: there are no models, textures, fonts, samples or images in the bundle. It is `index.html`, one script, the manifest and the three store images in `store/`, which are captures of the game itself. Each track's arrangement is fixed; the steps, and some of its phrases, come from a seed, so each round is a little different and any round can be replayed in a test.
|
|
32
|
+
|
|
33
|
+
## Adding a track
|
|
34
|
+
|
|
35
|
+
A track is data in `tracks.ts`; nothing else needs to change. Give it an `id`, a `name` and a `mood`; a `bpm`, a `meter` (4, or 3 for a waltz) and a `swing`; and its sections in order, from a one-bar count-in to an outro whose last note is the home note. Each section has a role (which sets how the steps are written and how the stage behaves), a number of bars, its chords ("Am F C G", or "F,G" for two in a bar), which phrases of the tune play, and which drum, bass, pad and arpeggio patterns sound. Write the tune as note names with lengths in eighths ("E5:2 A5:1 r:1"); a list of phrases gives the seed alternatives. Patterns are strings of sixteenth notes, explained at the top of `synth.ts`. Then run the tests: they check that the tune fits its sections, that every pattern exists and is whole bars long, that the chart is fair and about as hard as the others, and that nothing is scheduled in the past or after the end.
|
|
17
36
|
|
|
18
37
|
## Controls
|
|
19
38
|
|
|
20
39
|
- Arrow keys or `A` `S` `W` `D`, or tap the pads at the bottom.
|
|
21
|
-
- `M` or the sound button
|
|
40
|
+
- Sound follows the vmOS taskbar speaker and volume, live. `M` or the sound button is an extra mute for the game alone: it can turn the music off, never on while vmOS is muted, and then the button says "Sound off in vmOS". Sound starts with your first press of **Start dancing**, as browsers require; if the browser held it back, the next key or tap starts it and the music joins at the current beat.
|
|
22
41
|
- The game follows `prefers-reduced-motion`: the camera cuts instead of gliding, the spotlights hold still and the floor stops flashing on each bar.
|
|
23
42
|
|
|
24
43
|
## Build and run
|
|
@@ -55,8 +74,8 @@ The requirements are checked when you submit from the VibeStore **Submit** tab,
|
|
|
55
74
|
|
|
56
75
|
## What the score means
|
|
57
76
|
|
|
58
|
-
The score is reported to the host with `game.finish` a few seconds after the results card appears, or straight away if you press **Dance again**. The host owns the final results screen and may replace the game's window once it has the score; if it keeps the window open, the card stays as the result. The score is display data: the
|
|
77
|
+
The score is reported to the host with `game.finish` a few seconds after the results card appears, or straight away if you press **Dance again**. The host owns the final results screen and may replace the game's window once it has the score; if it keeps the window open, the card stays as the result. The score is display data: it never sets a reward. Finishing a round may earn the player a small amount of Printer Cash, decided and paid by VibeMarket OS; the game cannot grant or change it. The preview awards nothing.
|
|
59
78
|
|
|
60
79
|
## License
|
|
61
80
|
|
|
62
|
-
MIT, with the rest of the `@vibechain/os` package. Biscuit, the
|
|
81
|
+
MIT, with the rest of the `@vibechain/os` package. Biscuit, the six tracks and all of the code here are original to this example.
|