@vibechain/os 0.5.1 → 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.
Files changed (43) hide show
  1. package/AGENTS.md +15 -6
  2. package/README.md +35 -10
  3. package/SECURITY.md +3 -1
  4. package/dist/app-client.js +20 -4
  5. package/dist/app-host.d.ts +12 -2
  6. package/dist/app-host.js +12 -2
  7. package/dist/app-protocol.d.ts +21 -0
  8. package/dist/app-protocol.js +9 -0
  9. package/dist/audio.d.ts +65 -0
  10. package/dist/audio.js +162 -0
  11. package/dist/browser.d.ts +1 -0
  12. package/dist/browser.js +1 -0
  13. package/dist/bundle.d.ts +2 -0
  14. package/dist/bundle.js +2 -0
  15. package/dist/cli.js +3 -1
  16. package/dist/commands.d.ts +6 -0
  17. package/dist/commands.js +17 -0
  18. package/dist/index.d.ts +2 -2
  19. package/dist/links.d.ts +6 -0
  20. package/dist/links.js +2 -0
  21. package/dist/os.d.ts +20 -2
  22. package/dist/os.js +30 -5
  23. package/dist/preview-parent.js +15 -2
  24. package/dist/preview-ui.js +1 -1
  25. package/dist/preview.js +1 -1
  26. package/dist/templates/plain/game.js +3 -1
  27. package/dist/testing.d.ts +9 -1
  28. package/dist/testing.js +27 -6
  29. package/dist/vibemarket-os.js +1 -1
  30. package/examples/paw-beat/README.md +28 -9
  31. package/examples/paw-beat/game.ts +280 -123
  32. package/examples/paw-beat/index.html +18 -4
  33. package/examples/paw-beat/main.ts +101 -44
  34. package/examples/paw-beat/music.ts +72 -337
  35. package/examples/paw-beat/stage.ts +23 -9
  36. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  37. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  38. package/examples/paw-beat/synth.ts +477 -0
  39. package/examples/paw-beat/tracks.ts +286 -0
  40. package/examples/paw-beat/vibemarket.json +2 -2
  41. package/examples/vibexp-app/plain/game.ts +6 -2
  42. package/package.json +7 -1
  43. package/skill.md +399 -0
package/dist/testing.js CHANGED
@@ -1,4 +1,4 @@
1
- import { APP_LIMITS, checkpointJson, checkpointValue, lifecycleValue } from "./app-protocol.js";
1
+ import { APP_LIMITS, AUDIBLE, checkpointJson, checkpointValue, lifecycleValue, soundValue } from "./app-protocol.js";
2
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";
@@ -12,9 +12,9 @@ import { parseVmosLink } from "./links.js";
12
12
  */
13
13
  export function createFakeApp(options = {}) {
14
14
  let checkpoint = checkpointValue(options.checkpoint ?? null);
15
- 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 });
16
16
  let ready = false, destroyed = false, finished = null;
17
- const listeners = new Set();
17
+ const listeners = new Set(), sounds = new Set();
18
18
  const open = () => { if (destroyed)
19
19
  throw Error("Game session ended."); };
20
20
  const app = Object.freeze({
@@ -36,8 +36,12 @@ export function createFakeApp(options = {}) {
36
36
  current: () => state,
37
37
  onChanged(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
38
38
  }),
39
+ sound: Object.freeze({
40
+ current: () => sound,
41
+ onChanged(listener) { sounds.add(listener); return () => { sounds.delete(listener); }; },
42
+ }),
39
43
  onCapture() { return () => { }; },
40
- destroy() { destroyed = true; listeners.clear(); },
44
+ destroy() { destroyed = true; listeners.clear(); sounds.clear(); },
41
45
  });
42
46
  return {
43
47
  app,
@@ -46,6 +50,13 @@ export function createFakeApp(options = {}) {
46
50
  for (const listener of [...listeners])
47
51
  listener(state);
48
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
+ },
49
60
  get ready() { return ready; },
50
61
  get finished() { return finished; },
51
62
  get checkpoint() { return checkpointValue(checkpoint); },
@@ -65,7 +76,8 @@ export function createFakeOs(options = {}) {
65
76
  const checkCards = (cards) => cards.map(card => ({ ...wireCard({ ...card, art: null }), art: card.art }));
66
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 })) }));
67
78
  let held = checkCards(options.cards ?? []), saved = protocol === 2 ? saveJson(options.save ?? null) : checkpointJson(options.save ?? null);
68
- 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();
69
81
  let ready = false, closed = false, clicked = false, saves = 0, maximized = false, fullscreen = false, finished = null;
70
82
  const progress = [], shown = [], shownCards = [];
71
83
  const pause = new Set(), resume = new Set(), resize = new Set(), watchers = new Set();
@@ -97,6 +109,7 @@ export function createFakeOs(options = {}) {
97
109
  get active() { return state.active; },
98
110
  get size() { return Object.freeze({ width: state.width, height: state.height }); },
99
111
  get guest() { return protocol === 2 && options.guest === true; },
112
+ get sound() { return sound; },
100
113
  async ready() { open(); ready = true; },
101
114
  progress(fraction) {
102
115
  if (typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1)
@@ -189,9 +202,10 @@ export function createFakeOs(options = {}) {
189
202
  onPause(listener) { pause.add(listener); return () => { pause.delete(listener); }; },
190
203
  onResume(listener) { resume.add(listener); return () => { resume.delete(listener); }; },
191
204
  onResize(listener) { resize.add(listener); return () => { resize.delete(listener); }; },
205
+ onSound(listener) { sounds.add(listener); return () => { sounds.delete(listener); }; },
192
206
  /** the fake host never asks for a frame */
193
207
  onCapture() { return () => { }; },
194
- close() { closed = true; pause.clear(); resume.clear(); resize.clear(); watchers.clear(); },
208
+ close() { closed = true; pause.clear(); resume.clear(); resize.clear(); sounds.clear(); watchers.clear(); },
195
209
  });
196
210
  return {
197
211
  os,
@@ -214,6 +228,13 @@ export function createFakeOs(options = {}) {
214
228
  for (const listener of [...resize])
215
229
  listener(Object.freeze({ width: state.width, height: state.height }));
216
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
+ },
217
238
  click() { clicked = true; },
218
239
  get ready() { return ready; },
219
240
  get progress() { return [...progress]; },
@@ -1 +1 @@
1
- "use strict";var VibemarketOS=(()=>{var re=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ke=Object.prototype.hasOwnProperty;var Je=(e,t)=>{for(var n in t)re(e,n,{get:t[n],enumerable:!0})},Ue=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of He(t))!Ke.call(e,i)&&i!==n&&re(e,i,{get:()=>t[i],enumerable:!(a=Ge(t,i))||a.enumerable});return e};var Ze=e=>Ue(re({},"__esModule",{value:!0}),e);var xt={};Je(xt,{OsError:()=>P,cardLink:()=>Ve,connect:()=>De,packLink:()=>Ne,parseVmosLink:()=>Y});function U(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 ye="vibexp";var x=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}),ne=1e6;var se=e=>typeof e=="string"&&/^[1-9]\d{0,15}$/.test(e),Z=e=>typeof e=="string"&&e.length<=ne&&/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(e);function B(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function oe(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 we(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 ke=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Xe=(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 be(e){let t=0,n=0,a=(s,l)=>{if(++t>x.checkpointNodes||l>x.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>x.stringBytes)throw Error("App checkpoint string is too large.");let u=new TextEncoder().encode(s).byteLength;if(u>x.stringBytes||(n+=u)>x.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(s)){if(s.length>x.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 u=0;u<s.length;u++){let y=Object.getOwnPropertyDescriptor(s,u);if(!y||!("value"in y))throw Error("Sparse/accessor checkpoints are unsupported.");a(y.value,l+1)}return}if(!ke(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>x.objectKeys)throw Error("App checkpoint has too many keys.");for(let u of c){if(["__proto__","constructor","prototype"].includes(u)||u.length>128)throw Error("Invalid app checkpoint key.");if(n+=new TextEncoder().encode(u).byteLength,n>x.checkpointBytes)throw Error("App checkpoint keys are too large.");let y=Object.getOwnPropertyDescriptor(s,u);if(!y||!("value"in y))throw Error("App checkpoint accessors are unsupported.");a(y.value,l+1)}};a(e,0);let i=JSON.stringify(e);if(new TextEncoder().encode(i).byteLength>x.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return i}function Ae(e){if(!ke(e)||!Xe(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 Rt={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var Ot={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},Ct={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},Ye={packs:3,network:8,packSlugMax:56},Qe=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,C=e=>typeof e=="string"&&e.length<=Ye.packSlugMax&&Qe.test(e);var Ee=["unsupported","not-permitted","invalid","too-large","rate-limited","needs-click","unavailable","timeout","closed"],Pe=e=>typeof e=="string"&&Ee.includes(e),M=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:ne,captureMs:1200,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),et=["common","rare","epic","legendary","mythic"],G=/^[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}),W=1024,tt=Object.freeze({"host.hello":{request:256,response:W,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*W,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*W,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*W,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*W,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"}}),zt=Object.freeze(Object.keys(tt).filter(e=>e!=="host.hello"&&e!=="card.show")),rt=new TextEncoder,nt=e=>rt.encode(e).byteLength,_=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),I=(e,t,n=[])=>Reflect.ownKeys(e).every(i=>typeof i=="string"&&(t.includes(i)||n.includes(i))&&"value"in Object.getOwnPropertyDescriptor(e,i))&&t.every(i=>Object.hasOwn(e,i)),P=class extends Error{code;constructor(t,n){super(n),this.name="OsError",this.code=t}},z=class extends Error{code;constructor(t,n){super(n),this.name="AppHostError",this.code=t}};function ie(e){let t=i=>new z("invalid",i),n=(i,s)=>{if(!(i===null||typeof i=="boolean"||typeof i=="string")){if(typeof i=="number"){if(!Number.isFinite(i))throw t("A save's numbers must be finite.");return}if(typeof i!="object")throw t("A save must contain only JSON values.");if(s>M.saveDepth)throw t(`A save nests at most ${M.saveDepth} levels deep.`);if(Array.isArray(i)){if(Reflect.ownKeys(i).length!==i.length+1)throw t("A save's arrays cannot have extra properties.");for(let l=0;l<i.length;l++){let c=Object.getOwnPropertyDescriptor(i,l);if(!c||!("value"in c))throw t("A save's arrays cannot be sparse or have accessors.");n(c.value,s+1)}return}if(!_(i))throw t("A save must contain only plain objects, arrays and JSON values.");for(let l of Reflect.ownKeys(i)){let c=Object.getOwnPropertyDescriptor(i,l);if(typeof l!="string"||!c||!("value"in c)||!c.enumerable)throw t("A save's properties must be plain enumerable data.");n(c.value,s+1)}}};n(e,1);let a=JSON.stringify(e);if(nt(a)>M.saveBytes)throw new z("too-large",`A save is at most ${M.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return a}function Se(e){let t;try{t=JSON.parse(e)}catch{throw new z("invalid","The saved data is not JSON.")}return ie(t),t}var T=(e,t,n=0)=>typeof e=="string"&&e.length>=n&&e.length<=t,X=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,st=e=>typeof e=="string"&&et.includes(e),ae=".bin",ot=(e,t)=>`-/card/${e}/${t}${ae}`,it=e=>`-/cover/${e}${ae}`,at=e=>`-/player/${e}${ae}`;function Re(e,t){if(!_(e)||!I(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:n,pack:a,name:i,art:s}=e,l=typeof n=="string"?n.slice(n.indexOf("/")+1):"";if(!C(a)||n!==`${a}/${l}`||!G.test(l)||!T(i,120)||!st(e.rarity)||t&&!X(e.count,1,1e6)||s!==null&&s!==ot(a,l))throw Error("Invalid card.");return{id:n,pack:a,name:i,rarity:e.rarity,...t?{count:e.count}:{},art:s}}function ce(e){return Re(e,!0)}function ct(e){return Re(e,!1)}function Oe(e){let{id:t,name:n,creator:a,art:i,total:s}=e;if(!C(t)||!T(n,120,1)||a!==null&&!T(a,64,1)||i!==null&&i!==it(t)||!X(s,0,1e4))throw Error("Invalid pack.");return{id:t,name:n,creator:a,art:i,total:s}}function Ce(e){if(!_(e)||!I(e,["id","name","creator","art","held","total"])||!X(e.held,0,1e4))throw Error("Invalid pack.");let t=Oe(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function Me(e){if(!_(e)||!I(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=Oe(e),n=e.cards.map(ct);if(n.some(a=>a.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:n}}var lt=/[\u0000-\u001F\u007F-\u009F]/,xe=e=>typeof e=="string"&&q.handle.test(e);function _e(e){if(_(e)&&I(e,["guest"])&&e.guest===!0)return{guest:!0};if(!_(e)||!I(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:n,name:a,picture:i,token:s,expiresAt:l}=e;if(!xe(t)||!T(a,q.nameMax,1)||lt.test(a)||n!==void 0&&(!xe(n)||n===t)||i!==null&&i!==at(t)||"token"in e!="expiresAt"in e||s!==void 0&&(!T(s,q.tokenMax,q.tokenMin)||!q.token.test(s)||!X(l,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...n===void 0?{}:{username:n},name:a,picture:i,...s===void 0?{}:{token:s,expiresAt:l}}}var ve=e=>T(e,64,1);function Ie(e){if(_(e)&&I(e,["reset","revision"])&&e.reset===!0&&ve(e.revision))return{reset:!0,revision:e.revision};if(!_(e)||!I(e,["changed","removed","revision"])||!Array.isArray(e.changed)||!Array.isArray(e.removed)||!ve(e.revision)||e.removed.some(t=>!T(t,130,3)))throw Error("Invalid cards event.");return{changed:e.changed.map(ce),removed:e.removed,revision:e.revision}}function Te(e){if(!_(e)||!I(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(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 pt=1280,ut=[.85,.6,.4];function dt(e){let t=null,n=0;for(let a of Array.from(e.querySelectorAll("canvas"))){let i=a.getBoundingClientRect(),s=i.width*i.height;s>n&&a.width>0&&a.height>0&&(t=a,n=s)}return t}function ht(e,t){try{let n=e.width,a=e.height;if(!(n>0&&a>0))return null;let i=Math.min(1,pt/Math.max(n,a)),s=t.createElement("canvas");s.width=Math.max(1,Math.round(n*i)),s.height=Math.max(1,Math.round(a*i));let l=s.getContext("2d");if(!l)return null;l.drawImage(e,0,0,s.width,s.height);for(let c of ut){let u=s.toDataURL("image/webp",c);if(u.startsWith("data:image/webp")||(u=s.toDataURL("image/jpeg",c)),Z(u))return u}return null}catch{return null}}function Le(e,t){return typeof e=="string"?Z(e)?e:null:e!==null&&typeof e=="object"&&"getContext"in e&&"toDataURL"in e?ht(e,t):null}function ze(e,t){let n=null,a=()=>globalThis.document,i=(s,l)=>{if(!t())try{e(s,l)}catch{}};return{on(s){return n=s,()=>{n===s&&(n=null)}},clear(){n=null},event(s){if(!(t()||!se(s)))try{let l=n;if(l){Promise.resolve().then(l).then(c=>Le(c,a()),()=>null).then(c=>i(s,c),()=>{});return}requestAnimationFrame(()=>{let c=null;try{let u=dt(a());c=u?Le(u,a()):null}catch{c=null}i(s,c)})}catch{}}}}var le="vibemarket.game.v1";function $e(e,t={}){let n=0,a=!1,i,s=new Map,l=t.jsonBytes!==void 0,c=t.errors,u=[],y=[],g=k=>{k&&(k.done=Date.now(),w())},S=()=>c?c.closed():Error("Game session ended.");function w(){let k=t.pace;for(;y.length;){let f=Date.now();for(let m=u.length-1;m>=0;m--)u[m].done!==null&&f-u[m].done>=6e4&&u.splice(m,1);let h=u.filter(m=>m.done===null||f-m.done<1e3);if(h.length<k.perSecond&&u.length<k.perMinute){y.shift()();continue}let b=h.length>=k.perSecond?{list:h,ms:1e3}:{list:u,ms:6e4},R=b.list.filter(m=>m.done!==null).map(m=>m.done+b.ms-f);R.length&&i===void 0&&(i=window.setTimeout(()=>{i=void 0,w()},Math.max(1,Math.min(...R))));return}}return e.onmessage=k=>{let f;try{f=t.jsonBytes===void 0?k.data:we(k.data,t.jsonBytes)}catch{return}if(a||!f||typeof f!="object"||Array.isArray(f))return;let h=f;if(t.session!==void 0&&h.session!==t.session)return;if("event"in h){t.onEvent?.(h);return}if(typeof h.id!="string")return;let b=s.get(h.id);if(b)if(s.delete(h.id),window.clearTimeout(b.timer),g(b.record),typeof h.error=="string"){let R=l?h.error.slice(0,500):h.error;b.reject(c?c.reply(R,h.code):Error(R))}else"result"in h?b.resolve(h.result):b.reject(c?c.reply("Invalid host response.","unavailable"):Error("Invalid host response."))},e.start(),{request(k){if(a)return Promise.reject(S());if(s.size+y.length>=(t.maxPending??16))return Promise.reject(c?c.busy():Error("Too many pending requests."));let f=String(++n);return new Promise((h,b)=>{let R=()=>{let m=t.pace?{done:null}:void 0;m&&u.push(m);let $=window.setTimeout(()=>{s.delete(f),g(m),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(f,{resolve:O=>h(O),reject:b,timer:$,record:m});try{let O={id:f,request:k,...t.session===void 0?{}:{session:t.session}};e.postMessage(t.jsonBytes===void 0?O:oe(O,t.outBytes??t.jsonBytes))}catch(O){s.delete(f),window.clearTimeout($),g(m),b(O)}};if(!t.pace){R();return}y.push(()=>{a?b(S()):R()}),w()})},destroy(){if(!a){a=!0,i!==void 0&&window.clearTimeout(i);for(let k of y.splice(0))k();s.forEach(k=>{window.clearTimeout(k.timer),k.reject(S())}),s.clear(),e.onmessage=null,e.close()}}}}function je(e,t){return new Promise((n,a)=>{let i,s=()=>{window.clearTimeout(u),i!==void 0&&window.clearInterval(i),window.removeEventListener("message",c),e?.removeEventListener("abort",l)},l=()=>{s(),a(Error("Game session ended."))},c=g=>{if(g.source!==window.parent||!g.data||typeof g.data!="object"||!("channel"in g.data)||g.data.channel!==le||g.ports.length!==1)return;let S;if(t!==void 0){if(!("challenge"in g.data)||g.data.challenge!==t||!("session"in g.data)||!B(g.data.session))return;S=g.data.session}let w=t!==void 0&&"protocol"in g.data&&g.data.protocol===2?2:void 0;s(),n({port:g.ports[0],...S===void 0?{}:{session:S},...w===void 0?{}:{protocol:w}})},u=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 g={channel:le,type:"connect",...t===void 0?{}:{challenge:t}};window.parent.postMessage(t===void 0?g:oe(g,256),"*")};y(),t!==void 0&&(i=window.setInterval(y,250))})}var mt=200,pe="[a-z0-9]+(?:-[a-z0-9]+)*",gt="[A-Za-z0-9_-]{1,64}",ft=new RegExp(`^vmos://pack/(${pe})$`),yt=new RegExp(`^vmos://card/(${pe})/(${gt})$`),wt=new RegExp(`^https://(?:www\\.)?vibechain\\.com/os/pack/(${pe})/?$`);function Y(e){if(typeof e!="string"||e.length>mt)return null;let t=yt.exec(e);if(t)return C(t[1])?{kind:"card",pack:t[1],card:t[2]}:null;let n=ft.exec(e)??wt.exec(e);return n&&C(n[1])?{kind:"pack",pack:n[1]}:null}function Ne(e){if(!C(e))throw new P("invalid","That is not a pack slug.");return`vmos://pack/${e}`}function Ve(e,t){if(!C(e)||typeof t!="string"||!G.test(t))throw new P("invalid","That is not a pack slug and a card id.");return`vmos://card/${e}/${t}`}var kt="0.5.1",bt={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."},d=(e,t=bt[e])=>new P(e,t),H=(e,t)=>e instanceof P?e:e instanceof z?new P(e.code,e.message):d(t,e.message),Q=e=>{if(!C(e))throw d("invalid","That is not a pack slug.");return e};async function De(e={}){let t=new URLSearchParams(window.location.hash.slice(1)).get(ye);if(!B(t))throw d("unsupported","Open this app in VibeMarket OS or the SDK preview.");let n;try{n=await je(e.signal,t)}catch(a){throw d(e.signal?.aborted?"closed":"timeout",a.message)}return At(n.port,n.session,n.protocol??1,window.location.href)}async function At(e,t,n,a){if(!B(t))throw d("unavailable","Invalid app session.");let i=Object.freeze({active:!0,width:0,height:0}),s=!1,l=new Set,c=new Set,u=new Set,y=new Set,g=$e(e,{session:t,timeoutMs:x.requestTimeoutMs,maxPending:n===2?64:x.inFlight,jsonBytes:n===2?M.messageBytes:x.responseBytes,errors:{reply:(r,o)=>d(Pe(o)?o:"unavailable",r),timeout:()=>d("timeout"),closed:()=>d("closed"),busy:()=>d("rate-limited","Too many requests are waiting; try again later.")},...n===2?{pace:{perSecond:M.clientPerSecond,perMinute:M.clientPerMinute}}:{},onEvent(r){if(r.event==="app.cards"){Fe(r.state);return}if(r.event==="app.capture"){S.event(r.id);return}if(r.event!=="app.lifecycle")return;let o;try{o=Ae(r.state)}catch{return}let p=i;if(i=Object.freeze({active:o.active,width:o.width,height:o.height}),p.active&&!o.active)for(let A of[...l])A();if(!p.active&&o.active)for(let A of[...c])A();if(p.width!==o.width||p.height!==o.height)for(let A of[...u])A(Object.freeze({width:o.width,height:o.height}))}}),S=ze((r,o)=>{w({method:"app.frame",id:r,image:o}).catch(()=>{})},()=>n!==2||!f||s),w=async r=>{if(s)throw d("closed");let o=await g.request(r);if(!o||typeof o!="object"||Array.isArray(o))throw d("unavailable","Invalid host response.");return o},k=r=>{if(r.completed!==!0)throw d("unavailable","Invalid host acknowledgement.")},f=null;if(n===2)try{f=Te(await w({method:"host.hello",protocol:2,sdk:kt}))}catch(r){throw g.destroy(),H(r,"unavailable")}let h=()=>{if(!f)throw d("unsupported");return f},b=r=>r===null?null:new URL(h().root+r,a).href,R=r=>({...r,art:b(r.art)}),m=null,$=!1,O=null,ue=async r=>{for(let o=0;o<4;o++){let p=[],A=null,v=null,J=!0;do{let E=await w({method:"cards.list",...r===void 0?{}:{pack:r},...A===null?{}:{after:A}});if(!Array.isArray(E.cards)||E.after!==null&&typeof E.after!="string"||typeof E.revision!="string")throw d("unavailable","Invalid host response.");if(v!==null&&E.revision!==v){J=!1;break}v=E.revision,A=E.after;for(let qe of E.cards)p.push(R(ce(qe)))}while(A!==null);if(J&&v!==null)return r===void 0&&(m={revision:v,cards:new Map(p.map(E=>[E.id,E]))}),{cards:p,revision:v}}throw d("unavailable","The cards kept changing while they were read; try again.")},de=()=>{let r=[...m.cards.values()];for(let o of[...y])o(r.slice())},he=r=>O??=(async()=>{try{do $=!1,await ue();while($);r&&de()}catch{}finally{O=null}})();function Fe(r){if(!y.size)return;let o;try{o=Ie(r)}catch{return}if(O){$=!0;return}if("reset"in o||!m){he(!0);return}for(let p of o.removed)m.cards.delete(p);for(let p of o.changed)m.cards.set(p.id,R(p));m={revision:o.revision,cards:m.cards},de()}let L=null,ee=!1,me=-1/0,j,Be=n===2?M.saveIntervalMs:0,te=()=>{if(ee||!L||j!==void 0)return;let r=me+Be-Date.now();if(r>0){j=window.setTimeout(()=>{j=void 0,te()},r);return}let{text:o,waiters:p}=L;L=null,ee=!0;let A=JSON.parse(o);w(n===2?{method:"app.save.set",value:A}:{method:"app.checkpoint.set",value:A}).then(v=>{if(n===2?typeof v.savedAt!="string":v.completed!==!0)throw d("unavailable","Invalid host acknowledgement.")}).then(()=>{for(let v of p)v.resolve()},v=>{let J=H(v,"unavailable");for(let E of p)E.reject(J)}).finally(()=>{ee=!1,me=Date.now(),te()})},N=null,K=async r=>{let o=h();if(r.method==="card.show"&&!o.features.includes("card.show"))throw d("unsupported");if((await w(r)).shown!==!0)throw d("unavailable","Invalid host acknowledgement.")},V={get active(){return i.active},get size(){return Object.freeze({width:i.width,height:i.height})},get guest(){return f?.guest??!1},async ready(){k(await w({method:"ui.ready"}))},progress(r){if(typeof r!="number"||!Number.isFinite(r)||r<0||r>1)throw d("invalid","Progress is a number from 0 to 1.");!f||ge||(D=r,F===void 0&&(fe(),F=window.setTimeout(()=>{F=void 0,D!==null&&fe()},1e3)))},async load(){if(f){let o=await w({method:"app.save.get"});return o.value===null?null:Se(JSON.stringify(o.value))}let r=await w({method:"app.checkpoint.get"});if(!("checkpoint"in r))throw d("unavailable","Invalid host response.");return r.checkpoint},save(r){let o;try{if(o=ie(r),!f){if(new TextEncoder().encode(o).byteLength>x.checkpointBytes)throw d("too-large","This host keeps at most 32 KiB, and only while the window is open.");try{be(r)}catch(p){throw d("too-large",p.message)}}}catch(p){return Promise.reject(H(p,"invalid"))}return s?Promise.reject(d("closed")):new Promise((p,A)=>{L={text:o,waiters:[...L?.waiters??[],{resolve:p,reject:A}]},te()})},async cards(r){let o=r===void 0?void 0:Q(r);return h(),(await ue(o)).cards},onCards(r){return y.add(r),f&&y.size===1&&w({method:"cards.watch",on:!0}).then(()=>{m||he(!1)},()=>{}),()=>{!y.delete(r)||y.size||!f||s||w({method:"cards.watch",on:!1}).catch(()=>{})}},async packs(){h();let r=await w({method:"cards.packs"});if(!Array.isArray(r.packs))throw d("unavailable","Invalid host response.");return r.packs.map(o=>{let p=Ce(o);return{...p,art:b(p.art)}})},async pack(r){let o=Q(r);h();let p=Me((await w({method:"cards.pack",pack:o})).pack);return{...p,art:b(p.art),cards:p.cards.map(A=>({...A,art:b(A.art)}))}},async showPack(r){let o=Q(r);h(),await K({method:"pack.show",pack:o})},async showCard(r,o){let p=Q(r);if(typeof o!="string"||!G.test(o))throw d("invalid","That is not a card id.");await K({method:"card.show",pack:p,card:o})},async open(r){let o=Y(r);if(!o)throw d("invalid","That is not a vmOS pack or card link.");await(o.kind==="pack"?K({method:"pack.show",pack:o.pack}):K({method:"card.show",pack:o.pack,card:o.card}))},async player(){if(h(),N&&N.expiresAt-Date.now()>M.tokenReuseMs)return{...N};let r=_e(await w({method:"player.get"}));if(r.guest)return N=null,r;let o={...r,picture:b(r.picture)};return N=o.token?o:null,{...o}},async finish(r){let o;try{o=U(r)}catch(p){throw H(p,"invalid")}k(await w({method:"game.finish",...o}))},async maximize(r=!0){if(typeof r!="boolean")throw d("invalid");h(),k(await w({method:"display.maximize",on:r}))},async fullscreen(r=!0){if(typeof r!="boolean")throw d("invalid");h(),k(await w({method:"display.fullscreen",on:r}))},onPause(r){return l.add(r),()=>{l.delete(r)}},onResume(r){return c.add(r),()=>{c.delete(r)}},onCapture(r){if(typeof r!="function")throw d("invalid","A capture handler is a function.");return S.on(r)},onResize(r){return u.add(r),()=>{u.delete(r)}},close(){s||(s=!0,j!==void 0&&window.clearTimeout(j),F!==void 0&&window.clearTimeout(F),L?.waiters.forEach(r=>r.reject(d("closed"))),L=null,S.clear(),l.clear(),c.clear(),u.clear(),y.clear(),g.destroy())}},D=null,F,ge=!1,fe=()=>{let r=D;D=null,w({method:"ui.progress",value:r}).catch(()=>{})},We=V.ready;V.ready=async()=>{ge=!0,D=null,await We()};for(let r of["ready","load","cards","packs","pack","showPack","showCard","open","player","finish","maximize","fullscreen"]){let o=V[r];V[r]=async(...p)=>{try{return await o(...p)}catch(A){throw H(A,"unavailable")}}}return Object.freeze(V)}return Ze(xt);})();
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. One song lasts about a minute and ends with a results card: grade, score, accuracy, best combo and every judgement, with your personal best marked.
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: the song's sections and melody as data, a chart generator that writes steps from them, timing judgement, combo bonus and the grade |
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 each section's colours; the lanes and targets; every note in one instanced mesh; pooled sparks and confetti; camera framings that fit any window size |
12
- | `music.ts` | The whole song synthesized with Web Audio (drums, bass, pads, lead, bell, risers) through a soft limiter, scheduled ahead on the audio clock, which also times the steps |
13
- | `main.ts` | `connectVibeMarketApp()`, `fitCanvas` (with WebGL context loss handled) and `createLoop` from the SDK helpers; the title, play and results flow; a checkpoint for the personal best and the sound setting; and `game.finish({ score })` |
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. The song's arrangement is fixed; the steps, and the way the drop's tune is answered, come from a seed, so each round is a little different and any round can be replayed in a test.
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 turns the music off and on. Sound starts with your first press of **Start dancing**, as browsers require.
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 game cannot grant Cash, XP or items, and the preview awards nothing.
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 song and all of the code here are original to this example.
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.