@vibechain/os 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var _e="vibemarket.game.v1";var gt=["127.0.0.1","localhost"],yt=["vibechain.com","www.vibechain.com"],wt=["__VM_STEAM__","__TAURI_INTERNALS__"],Ke=["__TAURI__","vibeNative","ReactNativeWebView"],kt=/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i,bt="Third-party apps are available only on vibechain.com and in the local browser developer preview.",At="Third-party apps require a top-level browser host.",vt="Third-party apps are disabled in native shells until their IPC isolation is verified.";function Et({protocol:e,hostname:t,port:r}){return e==="http:"?gt.includes(t)?"local":null:e==="https:"&&yt.includes(t)&&r===""?"production":null}function Ue(e,t){let r=Object.getOwnPropertyDescriptor(e,t);return r&&"value"in r?r.value:void 0}var xt=Object.freeze({windows:1,macos:1,linux:1}),St=[["windows",/^Mozilla\/5\.0 \(Windows NT \d+\.\d+; Win64; x64\) AppleWebKit\/537\.36 \(KHTML, like Gecko\) Chrome\/\d+(?:\.\d+){3} Safari\/537\.36 Edg\/\d+(?:\.\d+){3}$/],["macos",/^Mozilla\/5\.0 \(Macintosh; Intel Mac OS X \d+(?:_\d+){1,2}\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)$/],["linux",/^Mozilla\/5\.0 \(X11; Linux (?:x86_64|aarch64)\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)(?: Version\/\d+(?:\.\d+){0,3} Safari\/\d+(?:\.\d+){0,3})?$/]];function Pt(e){return St.find(([,t])=>t.test(e))?.[0]??null}function Mt(e,t,r){let n=Ue(e,"__VM_STEAM__");if(typeof n!="object"||n===null)return!1;let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return!1;if(Ue(n,"appFrames")===1)return!0;let s=Pt(t);return s!==null&&r[s]===1}function me(e,t=xt){let r=Et(e.location);if(r===null)return bt;if(e.top!==e.self)return At;let n=e.navigator.userAgent;return(r==="production"&&Mt(e,n,t)?Ke:[...wt,...Ke]).some(s=>s in e)||kt.test(n)?vt:null}function he(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 fe="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}),Ce=1e6,qe=1101024,Ie=e=>typeof e=="string"&&/^[1-9]\d{0,15}$/.test(e),Oe=e=>typeof e=="string"&&e.length<=Ce&&/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(e);function Te(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function ge(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function X(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 ye(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 se=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Z=(e,t)=>{let r=Object.keys(e);return r.length===t.length&&Reflect.ownKeys(e).length===r.length&&r.every(n=>t.includes(n)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,n)??{},"value"))};function Le(e){let t=0,r=0,n=(s,l)=>{if(++t>v.checkpointNodes||l>v.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>v.stringBytes)throw Error("App checkpoint string is too large.");let a=new TextEncoder().encode(s).byteLength;if(a>v.stringBytes||(r+=a)>v.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(s)){if(s.length>v.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 a=0;a<s.length;a++){let m=Object.getOwnPropertyDescriptor(s,a);if(!m||!("value"in m))throw Error("Sparse/accessor checkpoints are unsupported.");n(m.value,l+1)}return}if(!se(s))throw Error("App checkpoint must contain only JSON values.");let f=Object.keys(s);if(Reflect.ownKeys(s).length!==f.length)throw Error("Checkpoint properties must be enumerable strings.");if(f.length>v.objectKeys)throw Error("App checkpoint has too many keys.");for(let a of f){if(["__proto__","constructor","prototype"].includes(a)||a.length>128)throw Error("Invalid app checkpoint key.");if(r+=new TextEncoder().encode(a).byteLength,r>v.checkpointBytes)throw Error("App checkpoint keys are too large.");let m=Object.getOwnPropertyDescriptor(s,a);if(!m||!("value"in m))throw Error("App checkpoint accessors are unsupported.");n(m.value,l+1)}};n(e,0);let o=JSON.stringify(e);if(new TextEncoder().encode(o).byteLength>v.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return o}function Ne(e){return JSON.parse(Le(e))}function Ze(e,t){if(!se(e)||!Z(e,["id","session","request"])||e.session!==t||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!se(e.request))throw Error("Invalid app session request.");let r=e.request;if(r.method==="app.frame"){if(!Z(r,["method","id","image"])||!Ie(r.id)||r.image!==null&&typeof r.image!="string")throw Error("Invalid app frame.");return{id:e.id,request:{method:"app.frame",id:r.id,image:r.image}}}if(X(e,v.requestBytes),r.method==="game.finish"&&Z(r,["method","score"]))return{id:e.id,request:{method:"game.finish",...he({score:r.score})}};if((r.method==="ui.ready"||r.method==="app.checkpoint.get")&&Z(r,["method"]))return{id:e.id,request:{method:r.method}};if(r.method==="app.checkpoint.set"&&Z(r,["method","value"]))return{id:e.id,request:{method:r.method,value:Ne(r.value)}};throw Error("This app has no permission for that method.")}var Gt=Object.freeze({muted:!1,volume:1});function we(e){if(!se(e)||!Z(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 ie(e){if(!se(e)||!Z(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 Jt={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var Kt={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},Ut={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},Rt={packs:3,network:8,packSlugMax:56},_t=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,j=e=>typeof e=="string"&&e.length<=Rt.packSlugMax&&_t.test(e);function Xe(e){return e.length>0&&e.length<=200&&e.split("/").every(t=>/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(t)&&!t.endsWith("."))}var E=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:Ce,captureMs:1200,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),ke=["common","rare","epic","legendary","mythic"],$e=/^[A-Za-z0-9_-]{1,64}$/,ce=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}),ae=1024,le=Object.freeze({"host.hello":{request:256,response:ae,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*ae,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*ae,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*ae,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*ae,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"}}),Qe=Object.freeze(Object.keys(le).filter(e=>e!=="host.hello"&&e!=="card.show")),Ct=new TextEncoder,pe=e=>Ct.encode(e).byteLength,ee=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Y=(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));var w=class extends Error{code;constructor(t,r){super(r),this.name="AppHostError",this.code=t}};function ze(e){let t=o=>new w("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>E.saveDepth)throw t(`A save nests at most ${E.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 f=Object.getOwnPropertyDescriptor(o,l);if(!f||!("value"in f))throw t("A save's arrays cannot be sparse or have accessors.");r(f.value,s+1)}return}if(!ee(o))throw t("A save must contain only plain objects, arrays and JSON values.");for(let l of Reflect.ownKeys(o)){let f=Object.getOwnPropertyDescriptor(o,l);if(typeof l!="string"||!f||!("value"in f)||!f.enumerable)throw t("A save's properties must be plain enumerable data.");r(f.value,s+1)}}};r(e,1);let n=JSON.stringify(e);if(pe(n)>E.saveBytes)throw new w("too-large",`A save is at most ${E.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return n}function et(e){let t;try{t=JSON.parse(e)}catch{throw new w("invalid","The saved data is not JSON.")}return ze(t),t}var T=(e,t,r=0)=>typeof e=="string"&&e.length>=r&&e.length<=t,be=(e,t,r)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=r,It=e=>typeof e=="string"&&ke.includes(e),Fe=".bin",Ae=(e,t)=>`-/card/${e}/${t}${Fe}`,ve=e=>`-/cover/${e}${Fe}`,Ot=e=>`-/player/${e}${Fe}`;function tt(e,t){if(!ee(e)||!Y(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:r,pack:n,name:o,art:s}=e,l=typeof r=="string"?r.slice(r.indexOf("/")+1):"";if(!j(n)||r!==`${n}/${l}`||!$e.test(l)||!T(o,120)||!It(e.rarity)||t&&!be(e.count,1,1e6)||s!==null&&s!==Ae(n,l))throw Error("Invalid card.");return{id:r,pack:n,name:o,rarity:e.rarity,...t?{count:e.count}:{},art:s}}function Ve(e){return tt(e,!0)}function Tt(e){return tt(e,!1)}function rt(e){let{id:t,name:r,creator:n,art:o,total:s}=e;if(!j(t)||!T(r,120,1)||n!==null&&!T(n,64,1)||o!==null&&o!==ve(t)||!be(s,0,1e4))throw Error("Invalid pack.");return{id:t,name:r,creator:n,art:o,total:s}}function nt(e){if(!ee(e)||!Y(e,["id","name","creator","art","held","total"])||!be(e.held,0,1e4))throw Error("Invalid pack.");let t=rt(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function ot(e){if(!ee(e)||!Y(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=rt(e),r=e.cards.map(Tt);if(r.some(n=>n.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:r}}var Lt=/[\u0000-\u001F\u007F-\u009F]/,Ye=e=>typeof e=="string"&&ce.handle.test(e);function st(e){if(ee(e)&&Y(e,["guest"])&&e.guest===!0)return{guest:!0};if(!ee(e)||!Y(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:r,name:n,picture:o,token:s,expiresAt:l}=e;if(!Ye(t)||!T(n,ce.nameMax,1)||Lt.test(n)||r!==void 0&&(!Ye(r)||r===t)||o!==null&&o!==Ot(t)||"token"in e!="expiresAt"in e||s!==void 0&&(!T(s,ce.tokenMax,ce.tokenMin)||!ce.token.test(s)||!be(l,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...r===void 0?{}:{username:r},name:n,picture:o,...s===void 0?{}:{token:s,expiresAt:l}}}var je=e=>T(e,64,1);var it=e=>e.includes("/")?"../".repeat(e.split("/").length-1):"./";function at(e){let t=e.method,r=(...n)=>Y(e,["method",...n]);switch(t){case"ui.ready":case"app.checkpoint.get":return r()?{method:t}:null;case"game.finish":return r("score")?{method:t,...he({score:e.score})}:null;case"app.checkpoint.set":return r("value")?{method:t,value:Ne(e.value)}:null;case"host.hello":return r("protocol","sdk")&&e.protocol===2&&T(e.sdk,20,1)&&/^[\x20-\x7e]+$/.test(e.sdk)?{method:t,protocol:2,sdk:e.sdk}:null;case"ui.progress":return r("value")&&typeof e.value=="number"&&Number.isFinite(e.value)?{method:t,value:e.value}:null;case"app.frame":return r("id","image")&&Ie(e.id)&&(e.image===null||typeof e.image=="string")?{method:t,id:e.id,image:e.image}:null;case"app.save.get":case"cards.packs":case"player.get":return r()?{method:t}:null;case"app.save.set":return r("value")?{method:t,value:e.value}:null;case"cards.list":return!Y(e,["method"],["pack","after"])||"pack"in e&&!T(e.pack,64,1)||"after"in e&&!T(e.after,64,1)?null:{method:t,..."pack"in e?{pack:e.pack}:{},..."after"in e?{after:e.after}:{}};case"cards.pack":case"pack.show":return r("pack")&&T(e.pack,64,1)?{method:t,pack:e.pack}:null;case"card.show":return r("pack","card")&&T(e.pack,64,1)&&T(e.card,64,1)?{method:t,pack:e.pack,card:e.card}:null;case"display.maximize":case"display.fullscreen":case"cards.watch":return r("on")&&typeof e.on=="boolean"?{method:t,on:e.on}:null;default:return null}}function We(e){return Object.hasOwn(le,e)?le[e]:{request:v.requestBytes,response:v.responseBytes,states:"LFB"}}function Nt(e,t,r){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype||Object.keys(e).length!==3||!("session"in e)||e.session!==t||!("id"in e)||typeof e.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!("request"in e)||!e.request||typeof e.request!="object"||Array.isArray(e.request))throw Error("Invalid app session request.");let n=at(e.request),o=n!==null&&!Object.hasOwn(le,n.method);if(!n||!r&&!o&&n.method!=="host.hello"&&n.method!=="app.frame")throw Error("This app has no permission for that method.");if(pe(JSON.stringify(e.request))>We(n.method).request)throw Error("App request exceeds its bound.");return{id:e.id,request:n}}function ct(e,t){let r=[];return n=>(r=r.filter(o=>n-o<t),r.length>=e?!1:(r.push(n),!0))}var H={states:"That is not available while the app is loading or behind another window.",rate:"Too many requests of that kind; try again later.",slug:"That is not a pack slug.",after:"That page cursor is not valid.",unavailable:"The host could not answer that now; try again."};function lt(e=()=>performance.now(),t={}){let r=t.services,n=r!==void 0,o="null",s=!1,l,f,a=!1,m=e();if(!Number.isFinite(m))throw Error("App clock is invalid.");let d=m,R=m,I=0,J=0,O=m,z,L,P,A=!1,b,k=ct(E.requestsPerMinute,6e4),_=n?E.sessionMs:v.sessionMs,F=n?E.lifetimeRequests:v.lifetimeRequests,C=n?"App session reached its 4-hour limit. Reopen the app to keep playing.":"App session expired. Reopen the app.",W=p=>{if(s||z)return;z=p,clearTimeout(B),clearTimeout(P),o="null";let M=L;l?.close(),M?.(p)},B=setTimeout(()=>W(C),_),K=()=>{let p;try{p=e()}catch{W("App clock changed. Reopen the app.");return}if(!Number.isFinite(p)||p<d){W("App clock changed. Reopen the app.");return}if(d=p,p-m>=_){W(C);return}return p},te=p=>{clearTimeout(P),P=setTimeout(()=>{let M=K();if(M===void 0)return;let V=M-O;if(V<E.idleMs){te(E.idleMs-V);return}A||(A=!0,t.idle?.())},p)},g=p=>{O=p,A&&(A=!1,te(E.idleMs))};n&&te(E.idleMs);let D={protocol:n?2:1,attach(p,M,V){if(s||z||!Te(M))throw p.close(),Error(z??"App controller is closed.");if(K()===void 0)throw p.close(),Error(z);l?.close();let re=!1,Ee=0,ue=!1,xe=!1,Be=0,Se=!1,Pe=!1,U,De=new Set,Ge=new Map,mt=0,ne,Q=c=>{let i=ne;ne=void 0,i&&(clearTimeout(i.timer),i.resolve(c))},Me=()=>{Q(null),!re&&(re=!0,p.onmessage=null,p.onmessageerror=null,p.close(),l===Re&&(l=void 0,L=void 0,b=void 0))},q=c=>{re||(Me(),V.fault(c))},N=()=>!re&&!s&&V.current(),He=V.foreground??(()=>!0),oe=(c,i)=>{N()&&p.postMessage(X(c,i))},Re={lifecycle(c){N()&&p.postMessage(X({session:M,event:"app.lifecycle",state:ie(c)},v.responseBytes))},sound(c){oe({session:M,event:"app.sound",state:we(c)},256)},close:Me,capture(c=E.captureMs){if(Q(null),!N())return Promise.resolve(null);let i=String(++mt),y=typeof c=="number"&&Number.isFinite(c)?Math.max(0,c):E.captureMs;return new Promise(u=>{ne={id:i,resolve:u,timer:setTimeout(()=>{ne?.id===i&&Q(null)},y)};try{oe({session:M,event:"app.capture",id:i},256)}catch{Q(null)}})}};l=Re,L=V.fault,r&&(b=async()=>{if(!Pe||!U||!N())return;let c=await r.cards();if(!N()||!Pe||!U||!je(c.revision)||c.revision===U.revision)return;let i=new Map(c.cards.map(S=>{let x=Ve(S);return[x.id,x]})),y=[...i.values()].filter(S=>JSON.stringify(U.cards.get(S.id))!==JSON.stringify(S)),u=[...U.cards.keys()].filter(S=>!i.has(S)),h={changed:y,removed:u,revision:c.revision};pe(JSON.stringify(h))>E.cardsEventBytes&&(h={reset:!0,revision:c.revision}),U={revision:c.revision,cards:i},oe({session:M,event:"app.cards",state:h},E.cardsEventBytes+1024)});let Je=c=>{let i=ne?.id===c.id;if(c.image!==null&&!Oe(c.image))throw i&&Q(null),new w("invalid","That is not a PNG, JPEG or WebP data URL of at most 1,000,000 characters.");return i&&Q(c.image),{completed:!0}},ht=async(c,i)=>{let y=(u,h)=>{try{return h(u)}catch{throw new w("unavailable",H.unavailable)}};switch(i.method){case"host.hello":return{protocol:2,guest:c.guest,features:[...Qe,...c.showCard?["card.show"]:[]],root:it(c.entry)};case"ui.progress":if(!xe){if(i.value<0||i.value>1)throw new w("invalid","Progress is a number from 0 to 1.");V.progress?.(i.value)}return{completed:!0};case"app.frame":return Je(i);case"app.save.get":{let u=await c.saveGet();return{value:u.value===null?null:y(u.value,et),savedAt:u.savedAt===null?null:y(u.savedAt,h=>{if(typeof h!="string"||h.length>30)throw Error();return h})}}case"app.save.set":{let u=ze(i.value);if(Se)throw new w("rate-limited","A save is already being written.");Se=!0;try{let{savedAt:h}=await c.saveSet(u);return{savedAt:y(h,S=>{if(typeof S!="string"||S.length>30)throw Error();return S})}}finally{Se=!1}}case"cards.list":{if(i.pack!==void 0&&!j(i.pack))throw new w("invalid",H.slug);let u=i.after===void 0?0:/^(?:0|[1-9]\d{0,5})$/.test(i.after)?Number(i.after):-1;if(u<0)throw new w("invalid",H.after);let h=await c.cards(),S=y(h,$=>{if(!je($.revision)||!Array.isArray($.cards))throw Error();return $.cards.map(Ve)});i.pack===void 0&&u===0&&(U={revision:h.revision,cards:new Map(S.map($=>[$.id,$]))});let x=i.pack===void 0?S:S.filter($=>$.pack===i.pack),G=u+E.cardsPage;return{cards:x.slice(u,G),after:G<x.length?String(G):null,revision:h.revision}}case"cards.packs":return{packs:y(await c.packs(),u=>{if(!Array.isArray(u)||u.length>200)throw Error();return u.map(nt)})};case"cards.pack":if(!j(i.pack))throw new w("invalid",H.slug);return{pack:y(await c.pack(i.pack),u=>{let h=ot(u);if(h.id!==i.pack)throw Error();return h})};case"cards.watch":return Pe=i.on,{completed:!0};case"pack.show":if(!j(i.pack))throw new w("invalid",H.slug);return await c.showPack(i.pack),{shown:!0};case"card.show":if(!c.showCard)throw new w("unsupported","This host cannot show a card.");if(!j(i.pack)||!$e.test(i.card))throw new w("invalid","That is not a pack slug and a card id.");return await c.showCard(i.pack,i.card),{shown:!0};case"player.get":return y(await c.player(),st);case"display.maximize":return await c.maximize(i.on),{completed:!0};case"display.fullscreen":return await c.fullscreen(i.on),{completed:!0}}};p.onmessage=c=>{if(!N()){Me();return}let i=K();if(i===void 0)return;if(i-R>=1e3&&(R=i,I=0),++I>v.requestsPerSecond||++J>F||Ee>=(ue?E.inFlight:v.inFlight)||n&&!k(i)){q("App request limit exceeded.");return}let y,u;try{n?{id:y,request:u}=Nt(ye(c.data,E.messageBytes),M,ue):{id:y,request:u}=Ze(ye(c.data,qe),M)}catch{q("Invalid or unpermitted app request.");return}if(n){if(!/^[1-9]\d{0,15}$/.test(y)||Number(y)<=Be){q("App request was replayed.");return}Be=Number(y)}else{if(De.has(y)){q("App request was replayed.");return}De.add(y)}if(u.method==="host.hello"){if(ue){q("App said hello twice.");return}ue=!0}Ee++,n&&g(i);let h=u.method,S=h==="ui.ready"||h==="game.finish"||h==="app.checkpoint.get"||h==="app.checkpoint.set";Promise.resolve().then(()=>{if(N()&&!(!He()&&(h==="game.finish"||h==="app.checkpoint.set"))){if(u.method==="app.frame"&&!n){try{let x=Je(u);N()&&p.postMessage(X({session:M,id:y,result:x},v.responseBytes))}catch(x){N()&&p.postMessage(X({session:M,id:y,error:x.message,code:"invalid"},v.responseBytes))}return}if(S){let x;switch(u.method){case"ui.ready":xe=!0,V.ready(),x={completed:!0};break;case"game.finish":if(f&&f.score!==u.score){if(!n)throw Error("This game has already finished.");oe({session:M,id:y,error:"This game has already finished.",code:"invalid"},v.responseBytes);return}f??=Object.freeze({score:u.score}),x={completed:!0};break;case"app.checkpoint.get":x={checkpoint:JSON.parse(o)};break;default:o=Le(u.value),x={completed:!0};break}N()&&(p.postMessage(X({session:M,id:y,result:x},v.responseBytes)),h==="game.finish"&&f&&!a&&N()&&(a=!0,V.finish?.(f)));return}return ft(y,u,h,i)}}).catch(()=>{re||q("App request could not complete.")}).finally(()=>{Ee--})};let ft=async(c,i,y,u)=>{let h=We(y),S;try{let x=xe?He()?"F":"B":"L";if(!h.states.includes(x))throw new w("not-permitted",H.states);if(h.rate&&!(i.method==="display.fullscreen"&&!i.on)){let $=h.bucket??y,de=Ge.get($);if(de||(de=ct(h.rate[0],h.rate[1]),Ge.set($,de)),!de(u))throw new w("rate-limited",H.rate)}let G=await ht(r,i);if(pe(JSON.stringify(G))>h.response)throw new w("unavailable","The answer is larger than this request may return.");S={session:M,id:c,result:G}}catch(x){let G=x instanceof w?x.code:"unavailable";S={session:M,id:c,error:x instanceof w?x.message.slice(0,300):H.unavailable,code:G}}oe(S,E.messageBytes)};return p.onmessageerror=()=>q("App message could not be decoded."),p.start(),Re},suspend(){l?.close()},dispose(){s||(s=!0,clearTimeout(B),clearTimeout(P),l?.close(),o="null")}};return n&&(D.activity=()=>{let p=K();p!==void 0&&g(p)},D.cardsChanged=async()=>{try{await b?.()}catch{}}),D}function pt(e,t){let r=me(window);if(r)throw Error(r);if(!Te(t.challenge)||new URL(e.src).hash!==`#${fe}=${t.challenge}`)throw Error("Invalid app frame challenge.");let n=t.controller.protocol===2,o=!1,s=!1,l=!1,f=0,a,m=!1,d=ie({active:!0,width:0,height:0}),R=t.sound===void 0?null:we(t.sound),I=()=>O("App took too long to become ready."),J=()=>{o||(o=!0,clearTimeout(P),clearTimeout(A),e.removeEventListener("load",z),window.removeEventListener("message",L),a?.close())},O=b=>{o||(J(),t.fault(b))},z=()=>{s?O("App navigation ended this session."):s=!0},L=b=>{if(o||l||!t.current()||b.source!==e.contentWindow)return;if(++f>32){O("App connection limit exceeded.");return}if(!s||b.origin!=="null")return;let k;try{k=ye(b.data,256)}catch{O("Invalid app connection message.");return}if(!k||typeof k!="object"||Array.isArray(k)||!("channel"in k)||k.channel!==_e||!("type"in k)||k.type!=="connect"||!("challenge"in k)||k.challenge!==t.challenge||Object.keys(k).length!==3)return;l=!0,window.removeEventListener("message",L);let _=new MessageChannel,F=ge();try{if(a=t.controller.attach(_.port1,F,{current:t.current,foreground:t.foreground,ready(){m=!0,clearTimeout(P),clearTimeout(A),t.ready()},finish:t.finish,fault:O,progress(C){m||o||(clearTimeout(P),P=setTimeout(I,E.readyMs),t.progress?.(C))}}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:_e,challenge:t.challenge,session:F,...n?{protocol:2}:{}},"*",[_.port2]),a.lifecycle(d),R&&a.sound(R)}catch{_.port1.close(),_.port2.close(),O("App connection could not complete.")}},P=setTimeout(I,E.readyMs),A=n?setTimeout(I,E.progressReadyMs):void 0;return e.addEventListener("load",z),window.addEventListener("message",L),{resize(b,k){d=ie({active:d.active,width:Math.min(4096,Math.max(0,Math.floor(b))),height:Math.min(4096,Math.max(0,Math.floor(k)))}),a?.lifecycle(d)},setActive(b){b!==d.active&&(d=ie({...d,active:b}),a?.lifecycle(d))},setSound(b){let k=we(b);R&&R.muted===k.muted&&R.volume===k.volume||(R=k,a?.sound(k))},dispose:J,capture(b){return o||!a?Promise.resolve(null):a.capture(b)}}}function $t(e){if(!e||typeof e!="object"||!("runtime"in e)||typeof e.runtime!="string")throw Error("Invalid preview metadata.");let t=e,r=(s,l)=>Array.isArray(s)&&s.length<=8&&s.every(l)?s:null,n=r(t.packs,j),o=r(t.network,s=>typeof s=="string");if(typeof t.name!="string"||typeof t.id!="string"||typeof t.entry!="string"||!Xe(t.entry)||!n||!o||!(t.cards==="none"||t.cards==="linked"||t.cards==="all"))throw Error("Invalid preview metadata.");return{name:t.name,runtime:e.runtime,id:t.id,entry:t.entry,packs:n,cards:t.cards,network:o}}var ut=e=>e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" "),dt="preview-public";function zt(e,t=Math.random){let r=e.packs.length?e.packs:e.cards==="all"?["preview-pack"]:[],n=a=>({id:a,name:ut(a),creator:"Preview",art:ve(a),total:6,cards:Array.from({length:6},(m,d)=>({id:`${a}/c${d+1}`,pack:a,name:`${ut(a)} #${d+1}`,rarity:ke[d%ke.length],art:Ae(a,`c${d+1}`)}))}),o=r.map(n),s=[...o,...r.includes(dt)?[]:[n(dt)]],l=new Map(o.flatMap(a=>a.cards.slice(0,3).map(m=>[m.id,1]))),f=1;return{pack(a){let m=s.find(d=>d.id===a);if(!m)throw new w("invalid","There is no such public pack.");return m},card(a,m){let d=this.pack(a).cards.find(R=>R.id===`${a}/${m}`);if(!d)throw new w("invalid","That card is not in that pack.");return d},cards(){if(e.cards==="none")throw new w("not-permitted","The manifest does not declare cards.");return{cards:o.flatMap(m=>m.cards.filter(d=>l.has(d.id)).map(d=>({...d,count:l.get(d.id)}))),revision:String(f)}},packs(){return o.map(({cards:a,...m})=>({...m,held:e.cards==="none"?0:a.filter(d=>l.has(d.id)).length}))},pull(){let a=o.flatMap(d=>d.cards);if(!a.length)return null;let m=a[Math.min(a.length-1,Math.floor(t()*a.length))];return l.set(m.id,(l.get(m.id)??0)+1),f++,m.name}}}function Ft(e,t){let r=`vmos-preview-save:${e}`,n={value:null,savedAt:null};return{get(){try{let o=t().getItem(r);if(o)return JSON.parse(o)}catch{}return n},set(o){n={value:o,savedAt:new Date().toISOString()};try{t().setItem(r,JSON.stringify(n))}catch{}return{savedAt:n.savedAt}}}}async function Vt(){let e=me(window);if(e)throw Error(e);let t=document.getElementById("surface"),r=document.getElementById("status"),n=document.getElementById("toggle"),o=document.getElementById("reset"),s=document.getElementById("pull"),l=document.getElementById("sound"),f=document.getElementById("volume"),a=document.getElementById("result"),m=document.getElementById("score");if(!t||!r||!a||!m||!(n instanceof HTMLButtonElement)||!(o instanceof HTMLButtonElement)||!(s instanceof HTMLButtonElement)||!(l instanceof HTMLButtonElement)||!(f instanceof HTMLInputElement))throw Error("Preview controls are missing.");let d=$t(await(await fetch("/preview.json",{credentials:"omit"})).json()),R=new URL(d.runtime);if(R.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(R.pathname)||R.search||R.hash)throw Error("Invalid preview runtime.");let I=zt(d),J=Ft(d.id,()=>window.localStorage),O=()=>{if(!navigator.userActivation?.isActive)throw new w("needs-click","That needs a fresh click in the app.")},z={guest:!1,entry:d.entry,async saveGet(){return J.get()},async saveSet(g){return J.set(g)},async cards(){return I.cards()},async packs(){return I.packs()},async pack(g){return I.pack(g)},async showPack(g){I.pack(g),O(),r.textContent=`VibeMarket would open the pack ${g} in its market window here.`},async showCard(g,D){let p=I.card(g,D);O(),r.textContent=`VibeMarket would open the card ${p.name} (${D}) on the pack ${g}'s page here.`},async player(){let g={guest:!1,handle:"preview_player",username:"preview",name:"Preview Player",picture:null};return d.network.length?{...g,token:"preview.not-a-real-token.unsigned",expiresAt:Date.now()+3e5}:g},async maximize(g){t.classList.toggle("maximized",g)},async fullscreen(g){if(!g){document.fullscreenElement&&await document.exitFullscreen();return}O(),await t.requestFullscreen()}},L=()=>lt(void 0,{services:z,idle:()=>{r.textContent="Still playing? VibeMarket asks here after 15 minutes without input."}}),P=L(),A=null,b=null,k=null,_=!1,F=null,C={muted:!1,volume:1},W=()=>{b?.dispose(),b=null,P.suspend(),k?.disconnect(),k=null,A?.remove(),A=null},B=()=>{if(W(),t.hidden=_||document.hidden||F!==null,a.hidden=!0,_||document.hidden){r.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(F){a.hidden=!1,m.textContent=String(F.score),r.textContent="Round complete. No Cash reward for this preview.";return}let g=ge(),D=new URL(R);D.hash=`${fe}=${g}`,A=document.createElement("iframe"),A.title="VibeMarket OS app",A.sandbox.add("allow-scripts","allow-pointer-lock"),A.allow="autoplay; gamepad",A.setAttribute("credentialless",""),A.referrerPolicy="no-referrer",A.src=D.href,t.appendChild(A),b=pt(A,{controller:P,challenge:g,sound:C,current:()=>!_&&!document.hidden,ready:()=>{r.textContent="App ready \xB7 Minimize and restore to check its saved work."},progress:p=>{r.textContent=`Loading the isolated app\u2026 ${Math.round(p*100)}%`},finish:p=>{F=p,o.textContent="Play again",B()},fault:p=>{W(),P.dispose(),P=L(),r.textContent=p}}),k=new ResizeObserver(()=>{A&&b?.resize(A.clientWidth,A.clientHeight)}),k.observe(A),r.textContent="Loading the isolated app\u2026"};n.onclick=()=>{_=!_,n.textContent=_?"Restore":"Minimize",B()},o.onclick=()=>{W(),P.dispose(),P=L(),F=null,_=!1,n.textContent="Minimize",o.textContent="Close / reset",B()};let K=g=>{C=g,b?.setSound(C),l.textContent=C.muted?"Sound off":"Sound on",l.setAttribute("aria-pressed",String(!C.muted)),r.textContent=C.muted?"Desktop sound off: the app must be silent.":`Desktop sound on at ${Math.round(C.volume*100)}%: the app follows this volume.`};l.onclick=()=>K({muted:!C.muted,volume:C.volume}),f.oninput=()=>K({muted:C.muted,volume:Math.min(1,Math.max(0,Number(f.value)/100))}),s.onclick=()=>{let g=I.pull();r.textContent=g?`Pulled ${g}. The app hears about it through onCards.`:"This app links no packs and does not read all cards, so there is nothing to pull.",P.cardsChanged?.()};let te=window.setInterval(()=>{navigator.userActivation?.isActive&&P.activity?.()},1e4);document.addEventListener("visibilitychange",B),window.addEventListener("pagehide",()=>{window.clearInterval(te),W(),P.dispose(),document.removeEventListener("visibilitychange",B)},{once:!0}),B()}typeof window<"u"&&typeof document<"u"&&Vt().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{dt as PREVIEW_PUBLIC_PACK,zt as previewCatalog,$t as previewMetadata,Ft as previewSaves,Vt as startPreviewParent};
1
+ var je="vibemarket.game.v1";var Qt=["127.0.0.1","localhost"],Yt=["vibechain.com","www.vibechain.com"],qt=["__VM_STEAM__","__TAURI_INTERNALS__"],ut=["__TAURI__","vibeNative","ReactNativeWebView"],er=/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i,tr="Third-party apps are available only on vibechain.com and in the local browser developer preview.",rr="Third-party apps require a top-level browser host.",nr="Third-party apps are disabled in native shells until their IPC isolation is verified.";function or({protocol:e,hostname:t,port:r}){return e==="http:"?Qt.includes(t)?"local":null:e==="https:"&&Yt.includes(t)&&r===""?"production":null}function mt(e,t){let r=Object.getOwnPropertyDescriptor(e,t);return r&&"value"in r?r.value:void 0}var sr=Object.freeze({windows:1,macos:1,linux:1}),ir=[["windows",/^Mozilla\/5\.0 \(Windows NT \d+\.\d+; Win64; x64\) AppleWebKit\/537\.36 \(KHTML, like Gecko\) Chrome\/\d+(?:\.\d+){3} Safari\/537\.36 Edg\/\d+(?:\.\d+){3}$/],["macos",/^Mozilla\/5\.0 \(Macintosh; Intel Mac OS X \d+(?:_\d+){1,2}\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)$/],["linux",/^Mozilla\/5\.0 \(X11; Linux (?:x86_64|aarch64)\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)(?: Version\/\d+(?:\.\d+){0,3} Safari\/\d+(?:\.\d+){0,3})?$/]];function ar(e){return ir.find(([,t])=>t.test(e))?.[0]??null}function cr(e,t,r){let o=mt(e,"__VM_STEAM__");if(typeof o!="object"||o===null)return!1;let n=Object.getPrototypeOf(o);if(n!==Object.prototype&&n!==null)return!1;if(mt(o,"appFrames")===1)return!0;let a=ar(t);return a!==null&&r[a]===1}function Pe(e,t=sr){let r=or(e.location);if(r===null)return tr;if(e.top!==e.self)return rr;let o=e.navigator.userAgent;return(r==="production"&&cr(e,o,t)?ut:[...qt,...ut]).some(a=>a in e)||er.test(o)?nr:null}function ge(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 Re="vibexp";var N=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}),We=1e6,ht=1101024,He=e=>typeof e=="string"&&/^[1-9]\d{0,15}$/.test(e),Ge=e=>typeof e=="string"&&e.length<=We&&/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(e);function Ue(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function Me(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function le(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 _e(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 ye=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),pe=(e,t)=>{let r=Object.keys(e);return r.length===t.length&&Reflect.ownKeys(e).length===r.length&&r.every(o=>t.includes(o)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,o)??{},"value"))};function Ke(e){let t=0,r=0,o=(a,s)=>{if(++t>N.checkpointNodes||s>N.checkpointDepth)throw Error("App checkpoint is too complex.");if(a===null||typeof a=="boolean")return;if(typeof a=="number"){if(!Number.isFinite(a))throw Error("Checkpoint numbers must be finite.");return}if(typeof a=="string"){if(a.length>N.stringBytes)throw Error("App checkpoint string is too large.");let c=new TextEncoder().encode(a).byteLength;if(c>N.stringBytes||(r+=c)>N.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(a)){if(a.length>N.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(a).length!==a.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let c=0;c<a.length;c++){let p=Object.getOwnPropertyDescriptor(a,c);if(!p||!("value"in p))throw Error("Sparse/accessor checkpoints are unsupported.");o(p.value,s+1)}return}if(!ye(a))throw Error("App checkpoint must contain only JSON values.");let l=Object.keys(a);if(Reflect.ownKeys(a).length!==l.length)throw Error("Checkpoint properties must be enumerable strings.");if(l.length>N.objectKeys)throw Error("App checkpoint has too many keys.");for(let c of l){if(["__proto__","constructor","prototype"].includes(c)||c.length>128)throw Error("Invalid app checkpoint key.");if(r+=new TextEncoder().encode(c).byteLength,r>N.checkpointBytes)throw Error("App checkpoint keys are too large.");let p=Object.getOwnPropertyDescriptor(a,c);if(!p||!("value"in p))throw Error("App checkpoint accessors are unsupported.");o(p.value,s+1)}};o(e,0);let n=JSON.stringify(e);if(new TextEncoder().encode(n).byteLength>N.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return n}function Je(e){return JSON.parse(Ke(e))}function ft(e,t){if(!ye(e)||!pe(e,["id","session","request"])||e.session!==t||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!ye(e.request))throw Error("Invalid app session request.");let r=e.request;if(r.method==="app.frame"){if(!pe(r,["method","id","image"])||!He(r.id)||r.image!==null&&typeof r.image!="string")throw Error("Invalid app frame.");return{id:e.id,request:{method:"app.frame",id:r.id,image:r.image}}}if(le(e,N.requestBytes),r.method==="game.finish"&&pe(r,["method","score"]))return{id:e.id,request:{method:"game.finish",...ge({score:r.score})}};if((r.method==="ui.ready"||r.method==="app.checkpoint.get")&&pe(r,["method"]))return{id:e.id,request:{method:r.method}};if(r.method==="app.checkpoint.set"&&pe(r,["method","value"]))return{id:e.id,request:{method:r.method,value:Je(r.value)}};throw Error("This app has no permission for that method.")}var Gr=Object.freeze({muted:!1,volume:1});function Te(e){if(!ye(e)||!pe(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 we(e){if(!ye(e)||!pe(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 Kr={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var pr=/^[a-z][a-z0-9-]{0,31}$/,ee=e=>typeof e=="string"&&pr.test(e),lr={leaderboards:5,achievements:50,products:50,nameMax:40,descriptionMax:120,achievementIconSize:128,achievementIconBytes:64*1024,priceMax:1e6},Ze=["high","low"],Xe=["number","time"],Ie=["consumable","permanent"],gt=Object.freeze({id:"score",name:"High scores",order:"high",format:"number"});function ke(e){let t=(e.leaderboards??[]).map(r=>({...r}));return t.some(r=>r.id===gt.id)?t:[...t,{...gt}]}var Jr={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},Zr={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},dr={packs:3,network:8,packSlugMax:56,manifestBytes:64*1024},ur=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,te=e=>typeof e=="string"&&e.length<=dr.packSlugMax&&ur.test(e);function Ae(e){return e.length>0&&e.length<=200&&e.split("/").every(t=>/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(t)&&!t.endsWith("."))}var mr=e=>!!e&&typeof e=="object"&&!Array.isArray(e);var hr=e=>e.path?`${e.path}: ${e.message}`:e.message;function fr(e,t,r,o=[],n=[]){let a=[];for(let s of Object.keys(e))n.includes(s)?a.push({path:t+s,message:"is no longer needed in schema version 3; remove it."}):!r.includes(s)&&!o.includes(s)&&a.push({path:t+s,message:"is not a field here; remove it."});for(let s of r)s in e||a.push({path:t+s,message:"is required."});return a}var gr=/[\u0000-\u001F\u007F-\u009F]/;function be(e,t,r,o){if(typeof e!="string")o(t,"must be a string.");else if(!e.trim())o(t,"must not be empty.");else if(e!==e.trim())o(t,"must not start or end with spaces.");else if(gr.test(e))o(t,"must be one line of plain text, with no line breaks or control characters.");else if([...e].length>r)o(t,`must be at most ${r} characters.`);else return e;return null}function yr(e,t){let r=lr,o=!0,n=(p,u,d,P,k,E)=>{if(!(p in e))return;let T=e[p];if(!Array.isArray(T)){t(p,`must be a list of ${d} objects.`),o=!1;return}T.length>u&&(t(p,`may declare at most ${u} ${d}s.`),o=!1);let z=[],I=new Set;return T.forEach((L,$)=>{let i=`${p}[${$}]`;if(!mr(L)){t(i,`must be an object with ${yt(P)}.`),o=!1;return}let g=fr(L,`${i}.`,P,k);for(let F of g)t(F.path,F.message);let y=!g.length;"id"in L&&(ee(L.id)?I.has(L.id)?(t(`${i}.id`,`repeats another ${d}'s id; each id is used once.`),y=!1):I.add(L.id):(t(`${i}.id`,"must be a lowercase letter followed by up to 31 lowercase letters, digits and hyphens, such as high-score."),y=!1));let v=E(L,i);y&&v!==null?z.push(v):o=!1}),z},a=(p,u,d,P,k)=>u in p?typeof p[u]=="string"&&P.includes(p[u])?p[u]:(t(`${d}.${u}`,`must be ${yt(P.map(E=>`"${E}"`),"or")}.`),null):k,s=n("leaderboards",r.leaderboards,"leaderboard",["id","name"],["order","format"],(p,u)=>{let d="name"in p?be(p.name,`${u}.name`,r.nameMax,t):null,P=a(p,"order",u,Ze,"high"),k=a(p,"format",u,Xe,"number");return d===null||P===null||k===null?null:{id:p.id,name:d,order:P,format:k}}),l=n("achievements",r.achievements,"achievement",["id","name","description"],["icon","secret"],(p,u)=>{let d="name"in p?be(p.name,`${u}.name`,r.nameMax,t):null,P="description"in p?be(p.description,`${u}.description`,r.descriptionMax,t):null,k=null,E=!0;if("icon"in p){let T=p.icon;typeof T!="string"||!Ae(T)||!/\.(?:png|webp)$/.test(T)?(t(`${u}.icon`,"must be the relative path of a .png or .webp file in the bundle, such as achievements/first.png."),E=!1):k=T}return"secret"in p&&typeof p.secret!="boolean"&&(t(`${u}.secret`,"must be true or false."),E=!1),d===null||P===null||!E?null:{id:p.id,name:d,description:P,icon:k,secret:p.secret===!0}}),c=n("products",r.products,"product",["id","name","description","price","kind"],[],(p,u)=>{let d="name"in p?be(p.name,`${u}.name`,r.nameMax,t):null,P="description"in p?be(p.description,`${u}.description`,r.descriptionMax,t):null,{price:k}=p,E=!0;"price"in p&&(typeof k!="number"||!Number.isInteger(k)||k<1||k>r.priceMax)&&(t(`${u}.price`,"must be a whole number of Printer Cash, at least 1, within the store's maximum price."),E=!1);let T="kind"in p?a(p,"kind",u,Ie,"consumable"):null;return d===null||P===null||T===null||!E?null:{id:p.id,name:d,description:P,price:k,kind:T}});return o?{...s?{leaderboards:s}:{},...l?{achievements:l}:{},...c?{products:c}:{}}:null}function wt(e){let t=[],r={};for(let n of["leaderboards","achievements","products"])e[n]!==void 0&&(r[n]=e[n]);let o=yr(r,(n,a)=>{t.push({path:n,message:a})});if(!o)throw Error(hr(t[0]));return o}var yt=(e,t="and")=>`${e.slice(0,-1).join(", ")} ${t} ${e.at(-1)}`;var C=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:We,captureMs:1200,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4,clickMs:5e3,buyClickMs:1e3,surfaceMs:1800*1e3}),Ce=["common","rare","epic","legendary","mythic"],Ye=/^[A-Za-z0-9_-]{1,64}$/,re=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}),br=["everyone","friends"],bt=["all","week"],kr=["playing","online","offline"],j=Object.freeze({boardRowsMax:50,boardRowsDefault:10,inviteText:80,inviteData:256,inviteRecipients:10,shareText:140,friendsMax:100,receiptsMax:100,timeScoreMax:864e5}),kt=/^[A-Za-z0-9_-]{1,64}$/,Ar=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,vr=e=>typeof e=="string"&&e.length<=60&&Ar.test(e),At="game.finish.board",vt="Secret achievement",K=1024,ve=Object.freeze({"host.hello":{request:256,response:K,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*K,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*K,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*K,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*K,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"},"leaderboard.get":{request:256,response:32*K,rate:[30,6e4],states:"LFB"},"leaderboard.show":{request:128,response:64,rate:[1,3e3],states:"F",click:C.clickMs,surface:!0},"achievement.unlock":{request:128,response:64,rate:[20,6e4],states:"LFB"},"achievements.list":{request:64,response:64*K,rate:[10,6e4],states:"LFB"},"friends.list":{request:64,response:64*K,rate:[10,6e4],states:"LFB"},"app.launch":{request:64,response:2*K,rate:[4,6e4],states:"LFB"},"invite.open":{request:4*K,response:64,rate:[1,1e4],states:"F",click:C.clickMs,guest:!0,surface:!0},"share.open":{request:2*K,response:64,rate:[1,1e4],states:"F",click:C.clickMs,guest:!0,surface:!0},"products.list":{request:64,response:64*K,rate:[10,6e4],states:"LFB"},"product.buy":{request:128,response:512,rate:[1,3e3],states:"F",click:C.buyClickMs,guest:!0,surface:!0},"purchases.list":{request:64,response:32*K,rate:[10,6e4],states:"LFB"},"purchase.consume":{request:192,response:64,rate:[30,6e4],states:"LFB"},"purchase.token":{request:192,response:2*K,rate:[10,6e4],states:"LFB"},"app.show":{request:192,response:64,rate:[1,1e4],bucket:"show",states:"F",click:C.clickMs}}),Le=Object.freeze(["leaderboard.get","leaderboard.show","achievement.unlock","achievements.list","friends.list","app.launch","invite.open","share.open","products.list","product.buy","purchases.list","purchase.consume","purchase.token","app.show"]),Et=Object.freeze(Object.keys(ve).filter(e=>e!=="host.hello"&&e!=="card.show"&&!Le.includes(e))),Er=new TextEncoder,xe=e=>Er.encode(e).byteLength,J=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),B=(e,t,r=[])=>Reflect.ownKeys(e).every(n=>typeof n=="string"&&(t.includes(n)||r.includes(n))&&"value"in Object.getOwnPropertyDescriptor(e,n))&&t.every(n=>Object.hasOwn(e,n));var M=class extends Error{code;constructor(t,r){super(r),this.name="AppHostError",this.code=t}};function qe(e){let t=n=>new M("invalid",n),r=(n,a)=>{if(!(n===null||typeof n=="boolean"||typeof n=="string")){if(typeof n=="number"){if(!Number.isFinite(n))throw t("A save's numbers must be finite.");return}if(typeof n!="object")throw t("A save must contain only JSON values.");if(a>C.saveDepth)throw t(`A save nests at most ${C.saveDepth} levels deep.`);if(Array.isArray(n)){if(Reflect.ownKeys(n).length!==n.length+1)throw t("A save's arrays cannot have extra properties.");for(let s=0;s<n.length;s++){let l=Object.getOwnPropertyDescriptor(n,s);if(!l||!("value"in l))throw t("A save's arrays cannot be sparse or have accessors.");r(l.value,a+1)}return}if(!J(n))throw t("A save must contain only plain objects, arrays and JSON values.");for(let s of Reflect.ownKeys(n)){let l=Object.getOwnPropertyDescriptor(n,s);if(typeof s!="string"||!l||!("value"in l)||!l.enumerable)throw t("A save's properties must be plain enumerable data.");r(l.value,a+1)}}};r(e,1);let o=JSON.stringify(e);if(xe(o)>C.saveBytes)throw new M("too-large",`A save is at most ${C.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return o}function xt(e){let t;try{t=JSON.parse(e)}catch{throw new M("invalid","The saved data is not JSON.")}return qe(t),t}var O=(e,t,r=0)=>typeof e=="string"&&e.length>=r&&e.length<=t,Q=(e,t,r)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=r,xr=e=>typeof e=="string"&&Ce.includes(e),et=".bin",$e=(e,t)=>`-/card/${e}/${t}${et}`,Fe=e=>`-/cover/${e}${et}`,St=e=>`-/player/${e}${et}`;function Pt(e,t){if(!J(e)||!B(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:r,pack:o,name:n,art:a}=e,s=typeof r=="string"?r.slice(r.indexOf("/")+1):"";if(!te(o)||r!==`${o}/${s}`||!Ye.test(s)||!O(n,120)||!xr(e.rarity)||t&&!Q(e.count,1,1e6)||a!==null&&a!==$e(o,s))throw Error("Invalid card.");return{id:r,pack:o,name:n,rarity:e.rarity,...t?{count:e.count}:{},art:a}}function tt(e){return Pt(e,!0)}function Sr(e){return Pt(e,!1)}function Rt(e){let{id:t,name:r,creator:o,art:n,total:a}=e;if(!te(t)||!O(r,120,1)||o!==null&&!O(o,64,1)||n!==null&&n!==Fe(t)||!Q(a,0,1e4))throw Error("Invalid pack.");return{id:t,name:r,creator:o,art:n,total:a}}function Mt(e){if(!J(e)||!B(e,["id","name","creator","art","held","total"])||!Q(e.held,0,1e4))throw Error("Invalid pack.");let t=Rt(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function _t(e){if(!J(e)||!B(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=Rt(e),r=e.cards.map(Sr);if(r.some(o=>o.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:r}}var rt=/[\u0000-\u001F\u007F-\u009F]/,Ee=e=>typeof e=="string"&&re.handle.test(e);function Tt(e){if(J(e)&&B(e,["guest"])&&e.guest===!0)return{guest:!0};if(!J(e)||!B(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:r,name:o,picture:n,token:a,expiresAt:s}=e;if(!Ee(t)||!O(o,re.nameMax,1)||rt.test(o)||r!==void 0&&(!Ee(r)||r===t)||n!==null&&n!==St(t)||"token"in e!="expiresAt"in e||a!==void 0&&(!O(a,re.tokenMax,re.tokenMin)||!re.token.test(a)||!Q(s,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...r===void 0?{}:{username:r},name:o,picture:n,...a===void 0?{}:{token:a,expiresAt:s}}}var nt=e=>O(e,64,1);var ie=(e,t)=>typeof t=="string"&&e.includes(t),Pr=(e,t)=>e===null||e===St(t),Rr=e=>O(e,re.nameMax,1)&&!rt.test(e),Qe=e=>Q(e,0,1e9),de=(e,t,r=1)=>typeof e=="string"&&e.length>=r&&[...e].length<=t&&!rt.test(e),Mr=e=>typeof e=="string"&&Ae(e)&&/\.(?:png|webp)$/.test(e),It=e=>Ee(e.handle)&&Rr(e.name)&&Pr(e.picture,e.handle);function Ot(e,t){if(!J(e)||!B(e,["board","name","order","format","period","entries","you"]))throw Error("Invalid leaderboard.");let{board:r,name:o,order:n,format:a,period:s,entries:l,you:c}=e;if(!ee(r)||!de(o,40)||!ie(Ze,n)||!ie(Xe,a)||!ie(bt,s)||!Array.isArray(l)||l.length>(t?.limit??j.boardRowsMax)||t&&(r!==t.board||s!==t.period))throw Error("Invalid leaderboard.");let p=l.map(d=>{if(!J(d)||!B(d,["rank","handle","name","picture","score","you"])||!Q(d.rank,1,Number.MAX_SAFE_INTEGER)||!It(d)||!Qe(d.score)||typeof d.you!="boolean")throw Error("Invalid leaderboard entry.");return{rank:d.rank,handle:d.handle,name:d.name,picture:d.picture,score:d.score,you:d.you}}),u=null;if(c!==null){if(!J(c)||!B(c,["rank","score"])||!Q(c.rank,1,Number.MAX_SAFE_INTEGER)||!Qe(c.score))throw Error("Invalid leaderboard.");u={rank:c.rank,score:c.score}}return{board:r,name:o,order:n,format:a,period:s,entries:p,you:u}}function Ct(e){if(!J(e)||!B(e,["id","name","description","icon","secret","unlocked","at"]))throw Error("Invalid achievement.");let{id:t,name:r,description:o,icon:n,secret:a,unlocked:s,at:l}=e;if(!ee(t)||!de(r,40)||!de(o,120,0)||n!==null&&!Mr(n)||typeof a!="boolean"||typeof s!="boolean"||(s?!Q(l,0,Number.MAX_SAFE_INTEGER):l!==null)||a&&!s&&(o!==""||n!==null))throw Error("Invalid achievement.");return{id:t,name:r,description:o,icon:n,secret:a,unlocked:s,at:l}}function Lt(e){if(!J(e)||!B(e,["handle","name","picture","presence"])||!It(e)||!ie(kr,e.presence))throw Error("Invalid friend.");return{handle:e.handle,name:e.name,picture:e.picture,presence:e.presence}}function ot(e){if(!J(e)||!B(e,["from","data"])||!Ee(e.from)||e.data!==null&&!O(e.data,j.inviteData))throw Error("Invalid invite.");return{from:e.from,data:e.data}}function $t(e){if(!J(e)||!B(e,["id","name","description","price","kind","owned"]))throw Error("Invalid product.");let{id:t,name:r,description:o,price:n,kind:a,owned:s}=e;if(!ee(t)||!de(r,40)||!de(o,120)||!Q(n,1,1e6)||!ie(Ie,a)||typeof s!="boolean"||s&&a!=="permanent")throw Error("Invalid product.");return{id:t,name:r,description:o,price:n,kind:a,owned:s}}function st(e){if(!J(e)||!B(e,["id","product","kind","price","at","consumed"]))throw Error("Invalid receipt.");let{id:t,product:r,kind:o,price:n,at:a,consumed:s}=e;if(typeof t!="string"||!kt.test(t)||!ee(r)||!ie(Ie,o)||!Q(n,1,1e6)||!Q(a,0,Number.MAX_SAFE_INTEGER)||typeof s!="boolean"||s&&o!=="consumable")throw Error("Invalid receipt.");return{id:t,product:r,kind:o,price:n,at:a,consumed:s}}function Ft(e){let t=r=>r===void 0||ee(r);switch(e.method){case"leaderboard.get":return t(e.board)?e.scope!==void 0&&!ie(br,e.scope)?'scope is "everyone" or "friends".':e.period!==void 0&&!ie(bt,e.period)?'period is "all" or "week".':e.limit!==void 0&&!Q(e.limit,1,j.boardRowsMax)?`limit is a whole number from 1 to ${j.boardRowsMax}.`:null:"That is not a board id.";case"leaderboard.show":return t(e.board)?null:"That is not a board id.";case"achievement.unlock":return ee(e.id)?null:"That is not an achievement id.";case"invite.open":return e.to!==void 0&&!Ee(e.to)?"to is a player's handle.":e.text!==void 0&&!de(e.text,j.inviteText,0)?`An invite's text is one line of at most ${j.inviteText} characters.`:e.data!==void 0&&!O(e.data,j.inviteData)?`An invite's data is at most ${j.inviteData} characters.`:null;case"share.open":return e.text!==void 0&&!de(e.text,j.shareText,0)?`A share's text is one line of at most ${j.shareText} characters.`:e.score!==void 0&&!Qe(e.score)?"score is a whole number from 0 to 1,000,000,000.":t(e.board)?e.board!==void 0&&e.score===void 0?"A board is shared with a score.":null:"That is not a board id.";case"product.buy":return ee(e.product)?null:"That is not a product id.";case"purchase.consume":case"purchase.token":return kt.test(e.receipt)?null:"That is not a receipt id.";case"app.show":return vr(e.app)?null:"That is not an app id.";default:return null}}var Nt=e=>e.includes("/")?"../".repeat(e.split("/").length-1):"./";var Oe=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));function Dt(e){let t=e.method,r=(...o)=>B(e,["method",...o]);switch(t){case"ui.ready":case"app.checkpoint.get":return r()?{method:t}:null;case"game.finish":return B(e,["method","score"],["board"])&&"board"in e?ee(e.board)?{method:t,...ge({score:e.score}),board:e.board}:null:r("score")?{method:t,...ge({score:e.score})}:null;case"app.checkpoint.set":return r("value")?{method:t,value:Je(e.value)}:null;case"host.hello":return r("protocol","sdk")&&e.protocol===2&&O(e.sdk,20,1)&&/^[\x20-\x7e]+$/.test(e.sdk)?{method:t,protocol:2,sdk:e.sdk}:null;case"ui.progress":return r("value")&&typeof e.value=="number"&&Number.isFinite(e.value)?{method:t,value:e.value}:null;case"app.frame":return r("id","image")&&He(e.id)&&(e.image===null||typeof e.image=="string")?{method:t,id:e.id,image:e.image}:null;case"app.save.get":case"cards.packs":case"player.get":return r()?{method:t}:null;case"app.save.set":return r("value")?{method:t,value:e.value}:null;case"cards.list":return!B(e,["method"],["pack","after"])||"pack"in e&&!O(e.pack,64,1)||"after"in e&&!O(e.after,64,1)?null:{method:t,..."pack"in e?{pack:e.pack}:{},..."after"in e?{after:e.after}:{}};case"cards.pack":case"pack.show":return r("pack")&&O(e.pack,64,1)?{method:t,pack:e.pack}:null;case"card.show":return r("pack","card")&&O(e.pack,64,1)&&O(e.card,64,1)?{method:t,pack:e.pack,card:e.card}:null;case"display.maximize":case"display.fullscreen":case"cards.watch":return r("on")&&typeof e.on=="boolean"?{method:t,on:e.on}:null;case"leaderboard.get":{let{board:o,scope:n,period:a,limit:s}=e;return!B(e,["method"],["board","scope","period","limit"])||o!==void 0&&!O(o,64,1)||n!==void 0&&!O(n,16,1)||a!==void 0&&!O(a,16,1)||s!==void 0&&typeof s!="number"?null:{method:t,...Oe({board:o,scope:n,period:a,limit:s})}}case"leaderboard.show":return B(e,["method"],["board"])&&(e.board===void 0||O(e.board,64,1))?{method:t,...Oe({board:e.board})}:null;case"achievement.unlock":return r("id")&&O(e.id,64,1)?{method:t,id:e.id}:null;case"achievements.list":case"friends.list":case"app.launch":case"products.list":case"purchases.list":return r()?{method:t}:null;case"invite.open":{let{to:o,text:n,data:a}=e;return!B(e,["method"],["to","text","data"])||o!==void 0&&!O(o,64,1)||n!==void 0&&!O(n,1024)||a!==void 0&&!O(a,1024)?null:{method:t,...Oe({to:o,text:n,data:a})}}case"share.open":{let{text:o,score:n,board:a}=e;return!B(e,["method"],["text","score","board"])||o!==void 0&&!O(o,1024)||n!==void 0&&typeof n!="number"||a!==void 0&&!O(a,64,1)?null:{method:t,...Oe({text:o,score:n,board:a})}}case"product.buy":return r("product")&&O(e.product,64,1)?{method:t,product:e.product}:null;case"purchase.consume":case"purchase.token":return r("receipt")&&O(e.receipt,64,1)?{method:t,receipt:e.receipt}:null;case"app.show":return r("app")&&O(e.app,64,1)?{method:t,app:e.app}:null;default:return null}}function it(e){return Object.hasOwn(ve,e)?ve[e]:{request:N.requestBytes,response:N.responseBytes,states:"LFB"}}var zt=Object.freeze({"leaderboard.get":"leaderboard","leaderboard.show":"showLeaderboard","achievement.unlock":"unlock","achievements.list":"achievements","friends.list":"friends","app.launch":"launch","invite.open":"invite","share.open":"share","products.list":"products","product.buy":"buy","purchases.list":"purchases","purchase.consume":"consume","purchase.token":"receiptToken","app.show":"showApp"}),_r=e=>Le.includes(e);function Tr(e){return[...Le.filter(t=>typeof e[zt[t]]=="function"),...e.leaderboard?[At]:[]]}function Ir(e,t,r){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype||Object.keys(e).length!==3||!("session"in e)||e.session!==t||!("id"in e)||typeof e.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!("request"in e)||!e.request||typeof e.request!="object"||Array.isArray(e.request))throw Error("Invalid app session request.");let o=Dt(e.request),n=o!==null&&!Object.hasOwn(ve,o.method);if(!o||!r&&!n&&o.method!=="host.hello"&&o.method!=="app.frame")throw Error("This app has no permission for that method.");if(xe(JSON.stringify(e.request))>it(o.method).request)throw Error("App request exceeds its bound.");return{id:e.id,request:o}}function Vt(e,t){let r=[];return o=>(r=r.filter(n=>o-n<t),r.length>=e?!1:(r.push(o),!0))}var q={states:"That is not available while the app is loading or behind another window.",rate:"Too many requests of that kind; try again later.",slug:"That is not a pack slug.",after:"That page cursor is not valid.",unavailable:"The host could not answer that now; try again.",unsupported:"This host does not offer that.",guest:"Guests cannot do that; sign in with Steam first.",click:"That needs a fresh click in the app."};function Bt(e=()=>performance.now(),t={}){let r=t.services,o=r!==void 0,n="null",a=!1,s,l,c=!1,p=e();if(!Number.isFinite(p))throw Error("App clock is invalid.");let u=p,d=p,P=0,k=0,E=p,T,z,I,L=!1,$,i=Vt(C.requestsPerMinute,6e4),g=o?C.sessionMs:N.sessionMs,y=o?C.lifetimeRequests:N.lifetimeRequests,v=o?"App session reached its 4-hour limit. Reopen the app to keep playing.":"App session expired. Reopen the app.",F=A=>{if(a||T)return;T=A,clearTimeout(G),clearTimeout(I),n="null";let D=z;s?.close(),D?.(A)},G=setTimeout(()=>F(v),g),H=()=>{let A;try{A=e()}catch{F("App clock changed. Reopen the app.");return}if(!Number.isFinite(A)||A<u){F("App clock changed. Reopen the app.");return}if(u=A,A-p>=g){F(v);return}return A},R=A=>{clearTimeout(I),I=setTimeout(()=>{let D=H();if(D===void 0)return;let Z=D-E;if(Z<C.idleMs){R(C.idleMs-Z);return}L||(L=!0,t.idle?.())},A)},V=A=>{E=A,L&&(L=!1,R(C.idleMs))};o&&R(C.idleMs);let oe={protocol:o?2:1,attach(A,D,Z){if(a||T||!Ue(D))throw A.close(),Error(T??"App controller is closed.");if(H()===void 0)throw A.close(),Error(T);s?.close();let x=!1,Y=0,W=!1,he=!1,at=0,De=!1,Ve=!1,ae,ct=new Set,pt=new Map,Kt=0,fe,ue=f=>{let m=fe;fe=void 0,m&&(clearTimeout(m.timer),m.resolve(f))},ze=()=>{ue(null),!x&&(x=!0,A.onmessage=null,A.onmessageerror=null,A.close(),s===Be&&(s=void 0,z=void 0,$=void 0))},ce=f=>{x||(ze(),Z.fault(f))},X=()=>!x&&!a&&Z.current(),lt=Z.foreground??(()=>!0),me=(f,m)=>{X()&&A.postMessage(le(f,m))},Be={lifecycle(f){X()&&A.postMessage(le({session:D,event:"app.lifecycle",state:we(f)},N.responseBytes))},sound(f){me({session:D,event:"app.sound",state:Te(f)},256)},close:ze,capture(f=C.captureMs){if(ue(null),!X())return Promise.resolve(null);let m=String(++Kt),b=typeof f=="number"&&Number.isFinite(f)?Math.max(0,f):C.captureMs;return new Promise(w=>{fe={id:m,resolve:w,timer:setTimeout(()=>{fe?.id===m&&ue(null)},b)};try{me({session:D,event:"app.capture",id:m},256)}catch{ue(null)}})},invite(f){return!W||!X()?!1:(me({session:D,event:"app.invite",state:ot(f)},2*1024),!0)}};s=Be,z=Z.fault,r&&($=async()=>{if(!Ve||!ae||!X())return;let f=await r.cards();if(!X()||!Ve||!ae||!nt(f.revision)||f.revision===ae.revision)return;let m=new Map(f.cards.map(_=>{let S=tt(_);return[S.id,S]})),b=[...m.values()].filter(_=>JSON.stringify(ae.cards.get(_.id))!==JSON.stringify(_)),w=[...ae.cards.keys()].filter(_=>!m.has(_)),h={changed:b,removed:w,revision:f.revision};xe(JSON.stringify(h))>C.cardsEventBytes&&(h={reset:!0,revision:f.revision}),ae={revision:f.revision,cards:m},me({session:D,event:"app.cards",state:h},C.cardsEventBytes+1024)});let dt=f=>{let m=fe?.id===f.id;if(f.image!==null&&!Ge(f.image))throw m&&ue(null),new M("invalid","That is not a PNG, JPEG or WebP data URL of at most 1,000,000 characters.");return m&&ue(f.image),{completed:!0}},Jt=async(f,m)=>{let b=(w,h)=>{try{return h(w)}catch{throw new M("unavailable",q.unavailable)}};switch(m.method){case"host.hello":return{protocol:2,guest:f.guest,features:[...Et,...f.showCard?["card.show"]:[],...Tr(f)],root:Nt(f.entry)};case"ui.progress":if(!he){if(m.value<0||m.value>1)throw new M("invalid","Progress is a number from 0 to 1.");Z.progress?.(m.value)}return{completed:!0};case"app.frame":return dt(m);case"app.save.get":{let w=await f.saveGet();return{value:w.value===null?null:b(w.value,xt),savedAt:w.savedAt===null?null:b(w.savedAt,h=>{if(typeof h!="string"||h.length>30)throw Error();return h})}}case"app.save.set":{let w=qe(m.value);if(De)throw new M("rate-limited","A save is already being written.");De=!0;try{let{savedAt:h}=await f.saveSet(w);return{savedAt:b(h,_=>{if(typeof _!="string"||_.length>30)throw Error();return _})}}finally{De=!1}}case"cards.list":{if(m.pack!==void 0&&!te(m.pack))throw new M("invalid",q.slug);let w=m.after===void 0?0:/^(?:0|[1-9]\d{0,5})$/.test(m.after)?Number(m.after):-1;if(w<0)throw new M("invalid",q.after);let h=await f.cards(),_=b(h,U=>{if(!nt(U.revision)||!Array.isArray(U.cards))throw Error();return U.cards.map(tt)});m.pack===void 0&&w===0&&(ae={revision:h.revision,cards:new Map(_.map(U=>[U.id,U]))});let S=m.pack===void 0?_:_.filter(U=>U.pack===m.pack),se=w+C.cardsPage;return{cards:S.slice(w,se),after:se<S.length?String(se):null,revision:h.revision}}case"cards.packs":return{packs:b(await f.packs(),w=>{if(!Array.isArray(w)||w.length>200)throw Error();return w.map(Mt)})};case"cards.pack":if(!te(m.pack))throw new M("invalid",q.slug);return{pack:b(await f.pack(m.pack),w=>{let h=_t(w);if(h.id!==m.pack)throw Error();return h})};case"cards.watch":return Ve=m.on,{completed:!0};case"pack.show":if(!te(m.pack))throw new M("invalid",q.slug);return await f.showPack(m.pack),{shown:!0};case"card.show":if(!f.showCard)throw new M("unsupported","This host cannot show a card.");if(!te(m.pack)||!Ye.test(m.card))throw new M("invalid","That is not a pack slug and a card id.");return await f.showCard(m.pack,m.card),{shown:!0};case"player.get":return b(await f.player(),Tt);case"display.maximize":return await f.maximize(m.on),{completed:!0};case"display.fullscreen":return await f.fullscreen(m.on),{completed:!0};default:return Zt(f,m,b)}},Zt=async(f,m,b)=>{let w=(h,_,S)=>{if(!Array.isArray(h)||h.length>_)throw Error();return h.map(S)};switch(m.method){case"leaderboard.get":{let h={board:m.board??"score",scope:m.scope??"everyone",period:m.period??"all",limit:m.limit??j.boardRowsDefault};return{leaderboard:b(await f.leaderboard(h),_=>Ot(_,h))}}case"leaderboard.show":return await f.showLeaderboard(m.board??"score"),{shown:!0};case"achievement.unlock":return b(await f.unlock(m.id),h=>{if(!h||typeof h.unlocked!="boolean")throw Error();return{unlocked:h.unlocked}});case"achievements.list":return{achievements:b(await f.achievements(),h=>w(h,50,Ct))};case"friends.list":return{friends:b(await f.friends(),h=>w(h,j.friendsMax,Lt))};case"app.launch":return{invite:b(await f.launch(),h=>h===null?null:ot(h))};case"invite.open":{let{method:h,..._}=m;return b(await f.invite(_),S=>{if(!S||!Number.isInteger(S.sent)||S.sent<0||S.sent>j.inviteRecipients)throw Error();return{sent:S.sent}})}case"share.open":{let{method:h,..._}=m;return b(await f.share(_),S=>{if(!S||typeof S.shared!="boolean")throw Error();return{shared:S.shared}})}case"products.list":return{products:b(await f.products(),h=>w(h,50,$t))};case"product.buy":return{receipt:b(await f.buy(m.product),h=>{let _=st(h);if(_.product!==m.product)throw Error();return _})};case"purchases.list":return{purchases:b(await f.purchases(),h=>w(h,j.receiptsMax,st))};case"purchase.consume":return await f.consume(m.receipt),{completed:!0};case"purchase.token":return{token:b(await f.receiptToken(m.receipt),h=>{if(typeof h!="string"||h.length<re.tokenMin||h.length>re.tokenMax||!re.token.test(h))throw Error();return h})};case"app.show":return await f.showApp(m.app),{shown:!0}}};A.onmessage=f=>{if(!X()){ze();return}let m=H();if(m===void 0)return;if(m-d>=1e3&&(d=m,P=0),++P>N.requestsPerSecond||++k>y||Y>=(W?C.inFlight:N.inFlight)||o&&!i(m)){ce("App request limit exceeded.");return}let b,w;try{o?{id:b,request:w}=Ir(_e(f.data,C.messageBytes),D,W):{id:b,request:w}=ft(_e(f.data,ht),D)}catch{ce("Invalid or unpermitted app request.");return}if(o){if(!/^[1-9]\d{0,15}$/.test(b)||Number(b)<=at){ce("App request was replayed.");return}at=Number(b)}else{if(ct.has(b)){ce("App request was replayed.");return}ct.add(b)}if(w.method==="host.hello"){if(W){ce("App said hello twice.");return}W=!0}Y++,o&&V(m);let h=w.method,_=h==="ui.ready"||h==="game.finish"||h==="app.checkpoint.get"||h==="app.checkpoint.set";Promise.resolve().then(()=>{if(X()&&!(!lt()&&(h==="game.finish"||h==="app.checkpoint.set"))){if(w.method==="app.frame"&&!o){try{let S=dt(w);X()&&A.postMessage(le({session:D,id:b,result:S},N.responseBytes))}catch(S){X()&&A.postMessage(le({session:D,id:b,error:S.message,code:"invalid"},N.responseBytes))}return}if(_){let S;switch(w.method){case"ui.ready":he=!0,Z.ready(),S={completed:!0};break;case"game.finish":if(l&&(l.score!==w.score||l.board!==w.board)){if(!o)throw Error("This game has already finished.");me({session:D,id:b,error:"This game has already finished.",code:"invalid"},N.responseBytes);return}l??=Object.freeze({score:w.score,...w.board===void 0?{}:{board:w.board}}),S={completed:!0};break;case"app.checkpoint.get":S={checkpoint:JSON.parse(n)};break;default:n=Ke(w.value),S={completed:!0};break}X()&&(A.postMessage(le({session:D,id:b,result:S},N.responseBytes)),h==="game.finish"&&l&&!c&&X()&&(c=!0,Z.finish?.(l)));return}return Xt(b,w,h,m)}}).catch(()=>{x||ce("App request could not complete.")}).finally(()=>{Y--})};let Xt=async(f,m,b,w)=>{let h=it(b),_;try{let S=he?lt()?"F":"B":"L";if(!h.states.includes(S))throw new M("not-permitted",q.states);if(_r(b)){if(typeof r[zt[b]]!="function")throw new M("unsupported",q.unsupported);let U=Ft(m);if(U)throw new M("invalid",U);if(h.guest&&r.guest)throw new M("guest",q.guest);if(h.click!==void 0&&r.clicked?.(h.click)!==!0)throw new M("needs-click",q.click)}if(h.rate&&!(m.method==="display.fullscreen"&&!m.on)){let U=h.bucket??b,Se=pt.get(U);if(Se||(Se=Vt(h.rate[0],h.rate[1]),pt.set(U,Se)),!Se(w))throw new M("rate-limited",q.rate)}let se=await Jt(r,m);if(xe(JSON.stringify(se))>h.response)throw new M("unavailable","The answer is larger than this request may return.");_={session:D,id:f,result:se}}catch(S){let se=S instanceof M?S.code:"unavailable";_={session:D,id:f,error:S instanceof M?S.message.slice(0,300):q.unavailable,code:se}}me(_,C.messageBytes)};return A.onmessageerror=()=>ce("App message could not be decoded."),A.start(),Be},suspend(){s?.close()},dispose(){a||(a=!0,clearTimeout(G),clearTimeout(I),s?.close(),n="null")}};return o&&(oe.activity=()=>{let A=H();A!==void 0&&V(A)},oe.cardsChanged=async()=>{try{await $?.()}catch{}}),oe}function jt(e,t){let r=Pe(window);if(r)throw Error(r);if(!Ue(t.challenge)||new URL(e.src).hash!==`#${Re}=${t.challenge}`)throw Error("Invalid app frame challenge.");let o=t.controller.protocol===2,n=!1,a=!1,s=!1,l=0,c,p=!1,u=we({active:!0,width:0,height:0}),d=t.sound===void 0?null:Te(t.sound),P=()=>E("App took too long to become ready."),k=()=>{n||(n=!0,clearTimeout(I),clearTimeout(L),e.removeEventListener("load",T),window.removeEventListener("message",z),c?.close())},E=$=>{n||(k(),t.fault($))},T=()=>{a?E("App navigation ended this session."):a=!0},z=$=>{if(n||s||!t.current()||$.source!==e.contentWindow)return;if(++l>32){E("App connection limit exceeded.");return}if(!a||$.origin!=="null")return;let i;try{i=_e($.data,256)}catch{E("Invalid app connection message.");return}if(!i||typeof i!="object"||Array.isArray(i)||!("channel"in i)||i.channel!==je||!("type"in i)||i.type!=="connect"||!("challenge"in i)||i.challenge!==t.challenge||Object.keys(i).length!==3)return;s=!0,window.removeEventListener("message",z);let g=new MessageChannel,y=Me();try{if(c=t.controller.attach(g.port1,y,{current:t.current,foreground:t.foreground,ready(){p=!0,clearTimeout(I),clearTimeout(L),t.ready()},finish:t.finish,fault:E,progress(v){p||n||(clearTimeout(I),I=setTimeout(P,C.readyMs),t.progress?.(v))}}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:je,challenge:t.challenge,session:y,...o?{protocol:2}:{}},"*",[g.port2]),c.lifecycle(u),d&&c.sound(d)}catch{g.port1.close(),g.port2.close(),E("App connection could not complete.")}},I=setTimeout(P,C.readyMs),L=o?setTimeout(P,C.progressReadyMs):void 0;return e.addEventListener("load",T),window.addEventListener("message",z),{resize($,i){u=we({active:u.active,width:Math.min(4096,Math.max(0,Math.floor($))),height:Math.min(4096,Math.max(0,Math.floor(i)))}),c?.lifecycle(u)},setActive($){$!==u.active&&(u=we({...u,active:$}),c?.lifecycle(u))},setSound($){let i=Te($);d&&d.muted===i.muted&&d.volume===i.volume||(d=i,c?.sound(i))},dispose:k,capture($){return n||!c?Promise.resolve(null):c.capture($)},invite($){return!n&&c?.invite?.($)===!0}}}var Or=20,ne=(e,t)=>new M(e,t);function Wt(e){let t=ke({leaderboards:[...e.leaderboards??[]]}),r=e.achievements??[],o=e.products??[],n=(e.friends??[]).map(i=>({...i})),a=(e.scores??[]).map(i=>({board:i.board??"score",handle:i.handle,name:i.name,picture:i.picture??null,score:i.score,friend:i.friend===!0})),s=new Map,l=new Map,c=[],p=[],u=[],d=[],P=e.printerCash??1e3,k=0,E=e.player,T=i=>{if(!E)throw ne("guest",`Guests cannot ${i}; the player has to sign in.`);return E},z=i=>{let g=t.find(y=>y.id===i);if(!g)throw ne("invalid",`The board ${i} is not declared in the manifest.`);return g},I=i=>{let g=o.find(y=>y.id===i);if(!g)throw ne("invalid",`The product ${i} is not declared in the manifest.`);return g},L=i=>{let g=d.find(y=>y.id===i);if(!g)throw ne("invalid","There is no such receipt.");return g},$=(i,g,y)=>i==="high"?g>y:g<y;return{post(i,g="score"){let y=t.find(F=>F.id===g);if(!E||!y||y.format==="time"&&i>j.timeScoreMax)return!1;let v=s.get(g);return(!v||$(y.order,i,v.score))&&s.set(g,{score:i,at:e.now()}),c.push({board:g,score:i}),!0},leaderboard(i){let g=z(i.board),y=new Set(n.map(R=>R.handle)),v=a.filter(R=>R.board===g.id&&(i.scope==="everyone"||R.friend||y.has(R.handle))).map((R,V)=>({handle:R.handle,name:R.name,picture:R.picture,score:R.score,you:!1,at:V-a.length})),F=s.get(g.id);E&&F&&v.push({handle:E.handle,name:E.name,picture:E.picture,score:F.score,you:!0,at:F.at}),v.sort((R,V)=>R.score===V.score?R.at-V.at:$(g.order,R.score,V.score)?-1:1);let G=v.map((R,V)=>({rank:V+1,handle:R.handle,name:R.name,picture:R.picture,score:R.score,you:R.you})),H=G.find(R=>R.you);return{board:g.id,name:g.name,order:g.order,format:g.format,period:i.period,entries:G.slice(0,i.limit),you:H?{rank:H.rank,score:H.score}:null}},unlock(i){if(!r.some(g=>g.id===i))throw ne("invalid",`The achievement ${i} is not declared in the manifest.`);return!E||l.has(i)?{unlocked:!1}:(l.set(i,e.now()),{unlocked:!0})},achievements(){return r.map(i=>{let g=l.get(i.id)??null,y=g!==null;return i.secret&&!y?{id:i.id,name:vt,description:"",icon:null,secret:!0,unlocked:!1,at:null}:{id:i.id,name:i.name,description:i.description,icon:i.icon,secret:i.secret,unlocked:y,at:g}})},friends(){let i={playing:0,online:1,offline:2};return n.slice().sort((g,y)=>i[g.presence]-i[y.presence]||(g.name<y.name?-1:g.name>y.name?1:0)).slice(0,j.friendsMax).map(g=>({...g}))},invite(i,g){T("invite friends");let y=i.to!==void 0&&n.some(F=>F.handle===i.to)?1:Math.min(n.length,j.inviteRecipients),v=g?y:0;return u.push({...i,sent:v}),{sent:v}},share(i,g){return T("share"),i.score!==void 0&&z(i.board??"score"),g?(p.push({...i,...i.score!==void 0?{board:i.board??"score"}:{}}),{shared:!0}):{shared:!1}},products(){return o.map(i=>({...i,owned:i.kind==="permanent"&&d.some(g=>g.product===i.id)}))},buy(i,g){let y=I(i);if(T("buy"),!g)throw ne("cancelled","The player closed the dialog without spending.");let v=y.kind==="permanent"?d.find(G=>G.product===y.id):void 0;if(v)return{...v};if(d.filter(G=>G.kind==="consumable"&&!G.consumed).length>=Or)throw ne("limit","Too many purchases are waiting to be consumed; consume them first.");if(P<y.price)throw ne("insufficient","The player does not have enough Printer Cash for that.");P-=y.price;let F={id:`fake-r${++k}`,product:y.id,kind:y.kind,price:y.price,at:e.now(),consumed:!1};return d.push(F),{...F}},purchases(){return d.filter(i=>!i.consumed).map(i=>({...i}))},consume(i){let g=L(i);if(g.kind!=="consumable")throw ne("invalid","Only a consumable's receipt is consumed.");g.consumed=!0},receiptToken(i){if(!e.network)throw ne("not-permitted","Receipt tokens are for apps that declare network.");return`fake.receipt-token.${L(i).id}`},product:I,get state(){return{posted:c.map(i=>({...i})),unlocked:[...l.keys()],shares:p.map(i=>({...i})),invites:u.map(i=>({...i})),receipts:d.map(i=>({...i})),printerCash:P}}}}function Ne(e,t){if(t==="number")return e.toLocaleString("en-US");let r=Math.floor(e/6e4),o=Math.floor(e%6e4/1e3),n=Math.floor(e%1e3/10);return`${r}:${String(o).padStart(2,"0")}.${String(n).padStart(2,"0")}`}function Ht(e){let t=(c,p,u)=>{let d=e.document.createElement(c);return d.className=p,u!==void 0&&(d.textContent=u),d},r=Promise.resolve(),o=null,n=[],a=!1,s=(c,p,u)=>{let d=r.then(()=>new Promise(P=>{let k=t("section","pv-surface");k.setAttribute("role","dialog"),k.setAttribute("aria-modal","true"),k.setAttribute("aria-label",`Preview: ${c}`),k.append(t("small","pv-label","Preview \xB7 vmOS draws this itself"),t("h2","pv-title",c));for(let I of p)k.append(t("p","pv-line",I));let E=t("div","pv-buttons"),T=null,z=I=>{o?.node===k&&(o=null,k.remove(),P(I))};for(let I of u){let L=t("button",I.value?"pv-confirm":"pv-cancel",I.label);L.type="button",L.addEventListener("click",()=>z(I.value)),I.hold&&(L.disabled=!0,e.setTimeout(()=>{L.disabled=!1},I.hold)),I.focus&&(T=L),E.append(L)}k.append(E),e.root.append(k),o={node:k,done:()=>z(!1)},T?.focus()}));return r=d,d},l=()=>{if(a||!n.length)return;a=!0;let c=t("div","pv-toast",`Preview \xB7 ${n.shift()}`);c.setAttribute("role","status"),e.root.append(c),e.setTimeout(()=>{c.remove(),a=!1,l()},4e3)};return{ask(c){return s(c.title,c.lines,[{label:c.cancel,value:!1,focus:!0},{label:c.confirm,value:!0,...c.holdMs?{hold:c.holdMs}:{}}])},async board(c){let p=c.entries.map(d=>`${d.rank}. ${d.name}${d.you?" (you)":""}: ${Ne(d.score,c.format)}`),u=c.you&&!c.entries.some(d=>d.you)?[`You: #${c.you.rank}, ${Ne(c.you.score,c.format)}`]:[];await s(c.name,[...p.length?p:["No scores yet."],...u],[{label:"Close",value:!1,focus:!0}])},toast(c){n.push(c),n.length>5&&n.splice(0,n.length,`${n.length} achievements unlocked`),l()},clear(){n.length=0,o?.done()}}}function Cr(e){if(!e||typeof e!="object"||!("runtime"in e)||typeof e.runtime!="string")throw Error("Invalid preview metadata.");let t=e,r=(l,c)=>Array.isArray(l)&&l.length<=8&&l.every(c)?l:null,o=r(t.packs,te),n=r(t.network,l=>typeof l=="string");if(typeof t.name!="string"||typeof t.id!="string"||typeof t.entry!="string"||!Ae(t.entry)||!o||!n||!(t.cards==="none"||t.cards==="linked"||t.cards==="all"))throw Error("Invalid preview metadata.");let a,s=Array.isArray(t.achievements)?t.achievements.map(l=>l&&typeof l=="object"&&l.icon===null?Object.fromEntries(Object.entries(l).filter(([c])=>c!=="icon")):l):t.achievements;try{a=wt({leaderboards:t.leaderboards,achievements:s,products:t.products})}catch{throw Error("Invalid preview metadata.")}return{name:t.name,runtime:e.runtime,id:t.id,entry:t.entry,packs:o,cards:t.cards,network:n,...a}}var Lr=Object.freeze([{handle:"preview_friend",name:"Preview Friend",picture:null,presence:"playing"},{handle:"sample_cat",name:"Sample Cat",picture:null,presence:"online"},{handle:"quiet_one",name:"Quiet One",picture:null,presence:"offline"}]);function $r(e){return e.flatMap(t=>(t.format==="time"?[65e3,8e4,95e3]:[1200,800,400]).map((r,o)=>({board:t.id,handle:["preview_friend","sample_cat","stranger_dog"][o],name:["Preview Friend","Sample Cat","Stranger Dog"][o],score:r,friend:o<2})))}var Fr=500;function Nr(e,t,r,o,n=Wt({...e,player:{handle:"preview_player",name:"Preview Player",picture:null},scores:$r(ke(e)),friends:Lr,printerCash:Fr,network:e.network.length>0,now:Date.now})){let a=s=>s.filter(l=>l!==void 0);return{fakes:n,clicked:()=>o(),async leaderboard(s){return n.leaderboard(s)},async showLeaderboard(s){await t.board(n.leaderboard({board:s,scope:"everyone",period:"all",limit:10}))},async unlock(s){let l=n.unlock(s);return l.unlocked&&t.toast(`Achievement unlocked: ${e.achievements.find(c=>c.id===s).name}`),l},async achievements(){return n.achievements()},async friends(){return n.friends()},async launch(){return null},async invite(s){let l=await t.ask({title:"Invite friends",lines:a([`vmOS would let the player choose friends who have ${e.name}${s.to?`, with ${s.to} chosen`:""}.`,s.text,s.data===void 0?void 0:`Your app's data: ${s.data}`]),confirm:"Send invites",cancel:"Close"});return n.invite(s,l)},async share(s){let l=s.score===void 0?void 0:n.leaderboard({board:s.board??"score",scope:"everyone",period:"all",limit:1}),c=await t.ask({title:"Share",lines:a([`vmOS would compose a card for ${e.name} with the player's name${l?` and ${Ne(s.score,l.format)} on ${l.name}`:""}; the player picks a friend in chat or their VibeSpace status.`,s.text===void 0?void 0:`Caption: ${s.text}`]),confirm:"Post",cancel:"Close"});return n.share(s,c)},async products(){return n.products()},async buy(s){let l=n.product(s);if(n.products().some(d=>d.id===s&&d.owned))return n.buy(s,!0);let p=n.state.printerCash,u=await t.ask({title:l.name,holdMs:600,confirm:`Spend ${l.price} Printer Cash`,cancel:"Cancel",lines:[l.description,p>=l.price?`Printer Cash: ${p} now, ${p-l.price} after.`:`Printer Cash: ${p}. That is not enough.`,"In the preview nothing is spent."]});return n.buy(s,u)},async purchases(){return n.purchases()},async consume(s){n.consume(s)},async receiptToken(s){return n.receiptToken(s),"preview.not-a-real-receipt-token.unsigned"},async showApp(s){r(`VibeMarket OS would open ${s}'s page in MiniVibe here.`)}}}var Gt=e=>e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" "),Ut="preview-public";function Dr(e,t=Math.random){let r=e.packs.length?e.packs:e.cards==="all"?["preview-pack"]:[],o=c=>({id:c,name:Gt(c),creator:"Preview",art:Fe(c),total:6,cards:Array.from({length:6},(p,u)=>({id:`${c}/c${u+1}`,pack:c,name:`${Gt(c)} #${u+1}`,rarity:Ce[u%Ce.length],art:$e(c,`c${u+1}`)}))}),n=r.map(o),a=[...n,...r.includes(Ut)?[]:[o(Ut)]],s=new Map(n.flatMap(c=>c.cards.slice(0,3).map(p=>[p.id,1]))),l=1;return{pack(c){let p=a.find(u=>u.id===c);if(!p)throw new M("invalid","There is no such public pack.");return p},card(c,p){let u=this.pack(c).cards.find(d=>d.id===`${c}/${p}`);if(!u)throw new M("invalid","That card is not in that pack.");return u},cards(){if(e.cards==="none")throw new M("not-permitted","The manifest does not declare cards.");return{cards:n.flatMap(p=>p.cards.filter(u=>s.has(u.id)).map(u=>({...u,count:s.get(u.id)}))),revision:String(l)}},packs(){return n.map(({cards:c,...p})=>({...p,held:e.cards==="none"?0:c.filter(u=>s.has(u.id)).length}))},pull(){let c=n.flatMap(u=>u.cards);if(!c.length)return null;let p=c[Math.min(c.length-1,Math.floor(t()*c.length))];return s.set(p.id,(s.get(p.id)??0)+1),l++,p.name}}}function Vr(e,t){let r=`vmos-preview-save:${e}`,o={value:null,savedAt:null};return{get(){try{let n=t().getItem(r);if(n)return JSON.parse(n)}catch{}return o},set(n){o={value:n,savedAt:new Date().toISOString()};try{t().setItem(r,JSON.stringify(o))}catch{}return{savedAt:o.savedAt}}}}async function zr(){let e=Pe(window);if(e)throw Error(e);let t=document.getElementById("surface"),r=document.getElementById("status"),o=document.getElementById("toggle"),n=document.getElementById("reset"),a=document.getElementById("pull"),s=document.getElementById("surfaces"),l=document.getElementById("sound"),c=document.getElementById("volume"),p=document.getElementById("result"),u=document.getElementById("score");if(!t||!r||!p||!u||!s||!(o instanceof HTMLButtonElement)||!(n instanceof HTMLButtonElement)||!(a instanceof HTMLButtonElement)||!(l instanceof HTMLButtonElement)||!(c instanceof HTMLInputElement))throw Error("Preview controls are missing.");let d=Cr(await(await fetch("/preview.json",{credentials:"omit"})).json()),P=new URL(d.runtime);if(P.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(P.pathname)||P.search||P.hash)throw Error("Invalid preview runtime.");let k=Dr(d),E=Vr(d.id,()=>window.localStorage),T=()=>navigator.userActivation?.isActive===!0,z=()=>{if(!T())throw new M("needs-click","That needs a fresh click in the app.")},I=Ht({root:s,document,setTimeout:(x,Y)=>window.setTimeout(x,Y)}),{fakes:L,...$}=Nr(d,I,x=>{r.textContent=x},T),i={guest:!1,entry:d.entry,async saveGet(){return E.get()},async saveSet(x){return E.set(x)},async cards(){return k.cards()},async packs(){return k.packs()},async pack(x){return k.pack(x)},async showPack(x){k.pack(x),z(),r.textContent=`VibeMarket would open the pack ${x} in its market window here.`},async showCard(x,Y){let W=k.card(x,Y);z(),r.textContent=`VibeMarket would open the card ${W.name} (${Y}) on the pack ${x}'s page here.`},async player(){let x={guest:!1,handle:"preview_player",username:"preview",name:"Preview Player",picture:null};return d.network.length?{...x,token:"preview.not-a-real-token.unsigned",expiresAt:Date.now()+3e5}:x},async maximize(x){t.classList.toggle("maximized",x)},async fullscreen(x){if(!x){document.fullscreenElement&&await document.exitFullscreen();return}z(),await t.requestFullscreen()},...$},g=()=>Bt(void 0,{services:i,idle:()=>{r.textContent="Still playing? VibeMarket asks here after 15 minutes without input."}}),y=g(),v=null,F=null,G=null,H=!1,R=null,V={muted:!1,volume:1},oe=()=>{F?.dispose(),F=null,y.suspend(),G?.disconnect(),G=null,v?.remove(),v=null},A=()=>{if(oe(),t.hidden=H||document.hidden||R!==null,p.hidden=!0,H||document.hidden){r.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(R){p.hidden=!1,u.textContent=String(R.score);let W=ke(d).find(he=>he.id===(R.board??"score"));r.textContent=`Round complete. No Cash reward for this preview.${W?` The score is on the preview's ${W.name} board.`:""}`;return}let x=Me(),Y=new URL(P);Y.hash=`${Re}=${x}`,v=document.createElement("iframe"),v.title="VibeMarket OS app",v.sandbox.add("allow-scripts","allow-pointer-lock"),v.allow="autoplay; gamepad",v.setAttribute("credentialless",""),v.referrerPolicy="no-referrer",v.src=Y.href,t.appendChild(v),F=jt(v,{controller:y,challenge:x,sound:V,current:()=>!H&&!document.hidden,ready:()=>{r.textContent="App ready \xB7 Minimize and restore to check its saved work."},progress:W=>{r.textContent=`Loading the isolated app\u2026 ${Math.round(W*100)}%`},finish:W=>{R=W,L.post(W.score,W.board),n.textContent="Play again",A()},fault:W=>{oe(),y.dispose(),y=g(),r.textContent=W}}),G=new ResizeObserver(()=>{v&&F?.resize(v.clientWidth,v.clientHeight)}),G.observe(v),r.textContent="Loading the isolated app\u2026"};o.onclick=()=>{H=!H,o.textContent=H?"Restore":"Minimize",A()},n.onclick=()=>{I.clear(),oe(),y.dispose(),y=g(),R=null,H=!1,o.textContent="Minimize",n.textContent="Close / reset",A()};let D=x=>{V=x,F?.setSound(V),l.textContent=V.muted?"Sound off":"Sound on",l.setAttribute("aria-pressed",String(!V.muted)),r.textContent=V.muted?"Desktop sound off: the app must be silent.":`Desktop sound on at ${Math.round(V.volume*100)}%: the app follows this volume.`};l.onclick=()=>D({muted:!V.muted,volume:V.volume}),c.oninput=()=>D({muted:V.muted,volume:Math.min(1,Math.max(0,Number(c.value)/100))}),a.onclick=()=>{let x=k.pull();r.textContent=x?`Pulled ${x}. The app hears about it through onCards.`:"This app links no packs and does not read all cards, so there is nothing to pull.",y.cardsChanged?.()};let Z=window.setInterval(()=>{navigator.userActivation?.isActive&&y.activity?.()},1e4);document.addEventListener("visibilitychange",A),window.addEventListener("pagehide",()=>{window.clearInterval(Z),oe(),y.dispose(),document.removeEventListener("visibilitychange",A)},{once:!0}),A()}typeof window<"u"&&typeof document<"u"&&zr().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{Lr as PREVIEW_FRIENDS,Fr as PREVIEW_PRINTER_CASH,Ut as PREVIEW_PUBLIC_PACK,Dr as previewCatalog,Cr as previewMetadata,Vr as previewSaves,$r as previewScores,Nr as previewServices,zr as startPreviewParent};
package/dist/preview.js CHANGED
@@ -5,8 +5,8 @@ import { readBuiltBundle, assetType } from "./bundle.js";
5
5
  import { appRuntimeCsp, appRuntimeHeaders } from "./runtime-policy.js";
6
6
  import { CARD_ID } from "./app-wire.js";
7
7
  import { packSlug } from "./manifest.js";
8
- const CSS = `body{margin:0;background:#387bd8;font:14px Arial;color:#17233a}main{max-width:1000px;margin:40px auto}header{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:space-between;background:linear-gradient(#1684ff,#0049d9);color:white;padding:8px;border-radius:8px 8px 0 0}h1{font-size:15px;margin:0}.frame{background:#ece9d8;border:3px solid #0059e9;min-height:520px}iframe{border:0;width:100%;height:540px;display:block}button{padding:6px 12px}#status{padding:10px;background:#ece9d8;margin:0}small{display:block;padding:12px;color:#fff}#result{background:#ece9d8;border:3px solid #0059e9;text-align:center;padding:48px 24px;min-height:300px}#result h2{font-size:32px;margin:0 0 24px}#score{display:block;font-size:clamp(32px,10vw,72px);overflow-wrap:anywhere;max-width:100%;color:#176844;margin:16px}.maximized iframe{height:calc(100vh - 140px)}#surface:fullscreen iframe{height:100vh}`;
9
- const HTML = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>VibeMarket OS App Preview</title><link rel="stylesheet" href="/preview.css"></head><body><main><header><h1>VibeMarket OS · App Preview</h1><div><button id="toggle" type="button">Minimize</button> <button id="pull" type="button">Pull a card</button> <button id="sound" type="button" aria-pressed="true">Sound on</button> <input id="volume" type="range" min="0" max="100" value="100" aria-label="Desktop volume"> <button id="reset" type="button">Close / reset</button></div></header><div id="surface" class="frame"></div><section id="result" hidden aria-label="Game results"><h2>Round complete</h2><p>Your score: <strong id="score"></strong></p><p>No Cash reward for this preview.</p></section><p id="status" role="status">Loading the isolated app…</p><small>Local development only · fake cards, a fake player token and a save kept in this browser; no account, Cash, Steam or wallet. Build again and restart this preview to load changed files.</small></main><script type="module" src="/sdk/preview-ui.js"></script></body></html>`;
8
+ const CSS = `body{margin:0;background:#387bd8;font:14px Arial;color:#17233a}main{max-width:1000px;margin:40px auto}header{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:space-between;background:linear-gradient(#1684ff,#0049d9);color:white;padding:8px;border-radius:8px 8px 0 0}h1{font-size:15px;margin:0}.frame{background:#ece9d8;border:3px solid #0059e9;min-height:520px}iframe{border:0;width:100%;height:540px;display:block}button{padding:6px 12px}#status{padding:10px;background:#ece9d8;margin:0}small{display:block;padding:12px;color:#fff}#result{background:#ece9d8;border:3px solid #0059e9;text-align:center;padding:48px 24px;min-height:300px}#result h2{font-size:32px;margin:0 0 24px}#score{display:block;font-size:clamp(32px,10vw,72px);overflow-wrap:anywhere;max-width:100%;color:#176844;margin:16px}.maximized iframe{height:calc(100vh - 140px)}#surface:fullscreen iframe{height:100vh}#surfaces{position:fixed;inset:auto 16px 16px auto;display:flex;flex-direction:column;gap:8px;max-width:360px;z-index:10}.pv-surface{background:#fff;border:3px dashed #c2185b;border-radius:8px;padding:12px 16px;box-shadow:0 6px 24px #0006}.pv-label{display:block;padding:0;color:#c2185b;font-weight:bold}.pv-title{font-size:16px;margin:6px 0}.pv-line{margin:4px 0}.pv-buttons{display:flex;gap:8px;justify-content:flex-end;margin-top:8px}.pv-toast{background:#17233a;color:#fff;border:2px dashed #ff8fab;border-radius:8px;padding:10px 14px}`;
9
+ const HTML = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>VibeMarket OS App Preview</title><link rel="stylesheet" href="/preview.css"></head><body><main><header><h1>VibeMarket OS · App Preview</h1><div><button id="toggle" type="button">Minimize</button> <button id="pull" type="button">Pull a card</button> <button id="sound" type="button" aria-pressed="true">Sound on</button> <input id="volume" type="range" min="0" max="100" value="100" aria-label="Desktop volume"> <button id="reset" type="button">Close / reset</button></div></header><div id="surface" class="frame"></div><div id="surfaces" aria-live="polite"></div><section id="result" hidden aria-label="Game results"><h2>Round complete</h2><p>Your score: <strong id="score"></strong></p><p>No Cash reward for this preview.</p></section><p id="status" role="status">Loading the isolated app…</p><small>Local development only · fake cards, a fake player token and a save kept in this browser; no account, Cash, Steam or wallet. Build again and restart this preview to load changed files.</small></main><script type="module" src="/sdk/preview-ui.js"></script></body></html>`;
10
10
  const MODULES = new Set(["preview-ui.js"]);
11
11
  /** One immutable in-memory bundle. No file serving by arbitrary URL, proxy, credential or write endpoint. */
12
12
  export async function startAppPreview(directory, port = 0) {
@@ -20,6 +20,8 @@ export async function startAppPreview(directory, port = 0) {
20
20
  const metadata = (runtime) => ({
21
21
  name: manifest.name, runtime, fragment: APP_FRAGMENT, id: manifest.id, entry: manifest.entry,
22
22
  packs: manifest.schemaVersion === 3 ? manifest.packs : [], cards: manifest.schemaVersion === 3 ? manifest.cards : "none", network,
23
+ // SDK 0.6: the declared boards, achievements and products, which the preview's fakes answer with
24
+ ...(manifest.schemaVersion === 3 ? { ...(manifest.leaderboards ? { leaderboards: manifest.leaderboards } : {}), ...(manifest.achievements ? { achievements: manifest.achievements } : {}), ...(manifest.products ? { products: manifest.products } : {}) } : {}),
23
25
  });
24
26
  const modules = new Map();
25
27
  for (const name of MODULES)
package/dist/testing.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { type AppLifecycle, type AppSound, type AppValue, type VibeMarketAppSdk } from "./app-protocol.ts";
2
- import { type Card, type Pack } from "./app-wire.ts";
2
+ import { type Card, type Friend, type Invite, type Pack } from "./app-wire.ts";
3
+ import { type FakeScore, type FakeServicesState } from "./fake-services.ts";
3
4
  import { type GameFinishInput } from "./completion.ts";
4
5
  import { type Os } from "./os.ts";
6
+ export type { FakeScore, FakeServicesState } from "./fake-services.ts";
5
7
  export interface FakeAppOptions {
6
8
  /** What `checkpoint.read()` returns first. Default: `null`, as on a first open. */
7
9
  checkpoint?: AppValue;
@@ -62,8 +64,25 @@ export interface FakeOsOptions {
62
64
  sound?: Partial<AppSound>;
63
65
  /** 1 behaves like a host older than 0.5: saves are the 32 KiB checkpoint and the rest is `unsupported`. Default 2. */
64
66
  protocol?: 1 | 2;
65
- /** The clock `player()` stamps expiry with. Default `Date.now`. */
67
+ /** The clock `player()` stamps expiry with, and receipts and unlocks are dated by. Default `Date.now`. */
66
68
  now?: () => number;
69
+ /**
70
+ * SDK 0.6: `"0.5"` behaves like a host from before 0.6: every 0.6 call answers `unsupported`, `launch.invite` is null and
71
+ * `finish` posts to no board. Default `"0.6"`. (`protocol: 1` is older still.)
72
+ */
73
+ host?: "0.5" | "0.6";
74
+ /** The manifest's `leaderboards`, `achievements` and `products`, as written in vibemarket.json (checked by the manifest's rules). */
75
+ leaderboards?: readonly unknown[];
76
+ achievements?: readonly unknown[];
77
+ products?: readonly unknown[];
78
+ /** Other players' best scores, for `leaderboard()`. */
79
+ scores?: readonly FakeScore[];
80
+ /** The player's friends who have the app, for `friends()`, `invite()` and the friends scope. */
81
+ friends?: readonly Friend[];
82
+ /** The player's Printer Cash for `buy`: a buy that costs more answers `insufficient`. Default 1,000. */
83
+ printerCash?: number;
84
+ /** The invite the app was opened with (`os.launch.invite`). Default none. */
85
+ launch?: Invite | null;
67
86
  }
68
87
  export interface FakeOs {
69
88
  /** Pass this wherever your game expects the result of `connect()`. */
@@ -74,8 +93,18 @@ export interface FakeOs {
74
93
  setLifecycle(next: Partial<AppLifecycle>): void;
75
94
  /** Change the desktop's sound as the taskbar speaker or volume would, and call the `onSound` listeners. */
76
95
  setSound(next: Partial<AppSound>): void;
77
- /** The next `showPack` or `fullscreen` call counts as following a click in the app. */
96
+ /** The next call that needs a click (`showPack`, `fullscreen`, `share`, `invite`, `buy`, `showLeaderboard`, `open`) counts as following one. */
78
97
  click(): void;
98
+ /** How the player answers the next spend dialogs and share and invite sheets: confirm (the default) or cancel. */
99
+ setChoice(choice: "confirm" | "cancel"): void;
100
+ /** A friend's invite arrives while the app is open: the `onInvite` listeners hear it. */
101
+ receiveInvite(invite: Invite): void;
102
+ /** What the game did with the 0.6 services: scores posted, achievements unlocked, shares, invites, receipts, Printer Cash left. */
103
+ readonly services: FakeServicesState;
104
+ /** Boards whose panel the game opened (`showLeaderboard`), in order. */
105
+ readonly shownLeaderboards: readonly string[];
106
+ /** Apps the game opened with `open("vmos://app/<appId>")`, in order. */
107
+ readonly shownApps: readonly string[];
79
108
  readonly ready: boolean;
80
109
  /** Every progress value the game reported, in order. */
81
110
  readonly progress: readonly number[];
@@ -83,7 +112,9 @@ export interface FakeOs {
83
112
  readonly save: unknown;
84
113
  /** How many `save` calls were accepted. */
85
114
  readonly saves: number;
86
- readonly finished: Readonly<GameFinishInput> | null;
115
+ readonly finished: Readonly<GameFinishInput & {
116
+ board?: string;
117
+ }> | null;
87
118
  /** Packs the game asked the host to show, in order. */
88
119
  readonly shownPacks: readonly string[];
89
120
  /** Cards the game asked the host to show (`showCard`, or `open` of a card link), in order. */
@@ -99,7 +130,11 @@ export interface FakeOs {
99
130
  * An in-memory stand-in for an apps3 host behind `connect()`, for unit tests of cards, saves and the player. It applies
100
131
  * the real rules: the save limits and JSON checks, pack slugs, the manifest's card access (`none`, `linked`, `all`),
101
132
  * single-shot completion, the click needed by `showPack` and `fullscreen`, the stable error codes, and `protocol: 1`
102
- * for a host older than this SDK. It has no window, no port, no time limits, no rate limits and no save coalescing
103
- * (each save is stored at once), so still run the preview before you ship.
133
+ * for a host older than this SDK. Since 0.6 it also fakes boards, achievements, friends, invites, sharing and spending with
134
+ * the rules of the real services (see fake-services.ts; the same fakes answer in `os preview`): declared ids, the best score
135
+ * by the board's order, one unlock, guests, owned permanent products, receipts kept until consumed; a buy, share or invite
136
+ * needs `click()` first, and `setChoice("cancel")` makes the player close the dialog. It has no window, no port, no time
137
+ * limits, no rate limits, no daily caps and no save coalescing (each save is stored at once), so still run the preview
138
+ * before you ship.
104
139
  */
105
140
  export declare function createFakeOs(options?: FakeOsOptions): FakeOs;
package/dist/testing.js CHANGED
@@ -1,7 +1,8 @@
1
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";
2
+ import { APP_METHODS_2, APPS4_LIMITS, AppHostError, CARD_ID, apps4Problem, saveJson, saveValue, wireCard, wireFriend, wireInvite, wirePack, } from "./app-wire.js";
3
+ import { createFakeServices } from "./fake-services.js";
3
4
  import { gameFinishInput } from "./completion.js";
4
- import { packSlug } from "./manifest.js";
5
+ import { packSlug, parseServices, serviceId } from "./manifest.js";
5
6
  import { OsError } from "./os.js";
6
7
  import { parseVmosLink } from "./links.js";
7
8
  /**
@@ -67,8 +68,12 @@ export function createFakeApp(options = {}) {
67
68
  * An in-memory stand-in for an apps3 host behind `connect()`, for unit tests of cards, saves and the player. It applies
68
69
  * the real rules: the save limits and JSON checks, pack slugs, the manifest's card access (`none`, `linked`, `all`),
69
70
  * single-shot completion, the click needed by `showPack` and `fullscreen`, the stable error codes, and `protocol: 1`
70
- * for a host older than this SDK. It has no window, no port, no time limits, no rate limits and no save coalescing
71
- * (each save is stored at once), so still run the preview before you ship.
71
+ * for a host older than this SDK. Since 0.6 it also fakes boards, achievements, friends, invites, sharing and spending with
72
+ * the rules of the real services (see fake-services.ts; the same fakes answer in `os preview`): declared ids, the best score
73
+ * by the board's order, one unlock, guests, owned permanent products, receipts kept until consumed; a buy, share or invite
74
+ * needs `click()` first, and `setChoice("cancel")` makes the player close the dialog. It has no window, no port, no time
75
+ * limits, no rate limits, no daily caps and no save coalescing (each save is stored at once), so still run the preview
76
+ * before you ship.
72
77
  */
73
78
  export function createFakeOs(options = {}) {
74
79
  const protocol = options.protocol ?? 2, access = options.access ?? { cards: "none" }, linked = access.packs ?? [], now = options.now ?? Date.now;
@@ -79,6 +84,51 @@ export function createFakeOs(options = {}) {
79
84
  let state = lifecycleValue({ active: true, width: 800, height: 600, ...options.lifecycle }), sound = soundValue({ ...AUDIBLE, ...options.sound });
80
85
  const sounds = new Set();
81
86
  let ready = false, closed = false, clicked = false, saves = 0, maximized = false, fullscreen = false, finished = null;
87
+ // 0.6
88
+ const modern = protocol === 2 && options.host !== "0.5", declared = parseServices(options);
89
+ const who = options.player ?? { handle: "fake_player", name: "Fake Player" };
90
+ const services = createFakeServices({
91
+ ...declared, player: options.guest === true ? null : { handle: who.handle, name: who.name, picture: who.picture ?? null },
92
+ scores: options.scores ?? [], friends: (options.friends ?? []).map(friend => ({ ...wireFriend({ ...friend, picture: null }), picture: friend.picture })),
93
+ ...(options.printerCash === undefined ? {} : { printerCash: options.printerCash }), network: options.network === true, now,
94
+ });
95
+ let choice = "confirm";
96
+ const launch = Object.freeze({ invite: modern && options.launch ? Object.freeze(wireInvite(options.launch)) : null });
97
+ const invites = new Set(), shownBoards = [], shownApps = [];
98
+ /** The checks the host makes before a 0.6 call reaches the services: unsupported, the arguments, guests, the click. */
99
+ const v4 = (request) => {
100
+ open();
101
+ const problem = apps4Problem(request);
102
+ if (problem)
103
+ throw fail("invalid", problem);
104
+ if (!modern)
105
+ throw fail("unsupported", "This host is older than this SDK and has no such feature.");
106
+ const rule = APP_METHODS_2[request.method];
107
+ if (rule.guest && options.guest === true)
108
+ throw fail("guest", "Guests cannot do that; the player has to sign in.");
109
+ if (rule.click !== undefined) {
110
+ if (!clicked)
111
+ throw fail("needs-click", "That needs a fresh click in the app.");
112
+ clicked = false;
113
+ }
114
+ };
115
+ /** The services' AppHostErrors as the SDK rejects them. */
116
+ const run = (work) => { try {
117
+ return work();
118
+ }
119
+ catch (error) {
120
+ const failure = error;
121
+ throw fail(failure.code, failure.message);
122
+ } };
123
+ const given = (value, keys) => {
124
+ if (value === undefined)
125
+ return {};
126
+ if (value === null || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some(key => !keys.includes(key)))
127
+ throw fail("invalid", `The options are an object with ${keys.join(", ")}.`);
128
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
129
+ };
130
+ const text = (value, what) => { if (typeof value !== "string")
131
+ throw fail("invalid", `${what} is a string.`); return value; };
82
132
  const progress = [], shown = [], shownCards = [];
83
133
  const pause = new Set(), resume = new Set(), resize = new Set(), watchers = new Set();
84
134
  const open = () => { if (closed)
@@ -166,8 +216,13 @@ export function createFakeOs(options = {}) {
166
216
  const target = parseVmosLink(link);
167
217
  open();
168
218
  if (!target)
169
- throw fail("invalid", "That is not a vmOS pack or card link.");
219
+ throw fail("invalid", "That is not a vmOS pack, card or app link.");
170
220
  v2();
221
+ if (target.kind === "app") {
222
+ v4({ method: "app.show", app: target.app });
223
+ shownApps.push(target.app);
224
+ return;
225
+ }
171
226
  show(target.pack, target.kind === "card" ? target.card : undefined);
172
227
  },
173
228
  async player() {
@@ -182,15 +237,53 @@ export function createFakeOs(options = {}) {
182
237
  open();
183
238
  let result;
184
239
  try {
185
- result = gameFinishInput(input);
240
+ const { board, ...rest } = (input && typeof input === "object" ? input : {});
241
+ if (board !== undefined && !serviceId(board))
242
+ throw Error("That is not a board id.");
243
+ const score = gameFinishInput(input && typeof input === "object" ? rest : input).score;
244
+ // a host from before 0.6 never hears the board
245
+ result = Object.freeze({ score, ...(board !== undefined && modern ? { board: board } : {}) });
186
246
  }
187
247
  catch (error) {
188
248
  throw fail("invalid", error.message);
189
249
  }
190
- if (finished && finished.score !== result.score)
250
+ if (finished && (finished.score !== result.score || finished.board !== result.board))
191
251
  throw fail("invalid", "This game has already finished.");
252
+ if (!finished && modern)
253
+ services.post(result.score, result.board);
192
254
  finished ??= result;
193
255
  },
256
+ async leaderboard(options) {
257
+ const asked = given(options, ["board", "scope", "period", "limit"]);
258
+ v4({ method: "leaderboard.get", ...asked });
259
+ return run(() => services.leaderboard({ board: asked.board ?? "score", scope: asked.scope ?? "everyone", period: asked.period ?? "all", limit: asked.limit ?? APPS4_LIMITS.boardRowsDefault }));
260
+ },
261
+ async showLeaderboard(board) {
262
+ const id = board === undefined ? "score" : text(board, "A board id");
263
+ v4({ method: "leaderboard.show", board: id });
264
+ run(() => services.leaderboard({ board: id, scope: "everyone", period: "all", limit: 1 }));
265
+ shownBoards.push(id);
266
+ },
267
+ async unlock(id) { v4({ method: "achievement.unlock", id: text(id, "An achievement id") }); return run(() => services.unlock(id)); },
268
+ async achievements() { v4({ method: "achievements.list" }); return services.achievements(); },
269
+ async friends() { v4({ method: "friends.list" }); return services.friends(); },
270
+ async invite(options) {
271
+ const asked = given(options, ["to", "text", "data"]);
272
+ v4({ method: "invite.open", ...asked });
273
+ return run(() => services.invite(asked, choice === "confirm"));
274
+ },
275
+ get launch() { return launch; },
276
+ onInvite(listener) { invites.add(listener); return () => { invites.delete(listener); }; },
277
+ async share(options) {
278
+ const asked = given(options, ["text", "score", "board"]);
279
+ v4({ method: "share.open", ...asked });
280
+ return run(() => services.share(asked, choice === "confirm"));
281
+ },
282
+ async products() { v4({ method: "products.list" }); return services.products(); },
283
+ async buy(productId) { v4({ method: "product.buy", product: text(productId, "A product id") }); return run(() => services.buy(productId, choice === "confirm")); },
284
+ async purchases() { v4({ method: "purchases.list" }); return services.purchases(); },
285
+ async consume(receiptId) { v4({ method: "purchase.consume", receipt: text(receiptId, "A receipt id") }); run(() => services.consume(receiptId)); },
286
+ async receiptToken(receiptId) { v4({ method: "purchase.token", receipt: text(receiptId, "A receipt id") }); return run(() => services.receiptToken(receiptId)); },
194
287
  async maximize(on = true) { v2(); maximized = on; },
195
288
  async fullscreen(on = true) {
196
289
  v2();
@@ -205,7 +298,7 @@ export function createFakeOs(options = {}) {
205
298
  onSound(listener) { sounds.add(listener); return () => { sounds.delete(listener); }; },
206
299
  /** the fake host never asks for a frame */
207
300
  onCapture() { return () => { }; },
208
- close() { closed = true; pause.clear(); resume.clear(); resize.clear(); sounds.clear(); watchers.clear(); },
301
+ close() { closed = true; pause.clear(); resume.clear(); resize.clear(); sounds.clear(); watchers.clear(); invites.clear(); },
209
302
  });
210
303
  return {
211
304
  os,
@@ -236,6 +329,16 @@ export function createFakeOs(options = {}) {
236
329
  listener(sound);
237
330
  },
238
331
  click() { clicked = true; },
332
+ setChoice(next) { choice = next; },
333
+ receiveInvite(invite) {
334
+ const checked = wireInvite(invite);
335
+ if (modern && !closed)
336
+ for (const listener of [...invites])
337
+ listener({ ...checked });
338
+ },
339
+ get services() { return services.state; },
340
+ get shownLeaderboards() { return [...shownBoards]; },
341
+ get shownApps() { return [...shownApps]; },
239
342
  get ready() { return ready; },
240
343
  get progress() { return [...progress]; },
241
344
  get save() { return JSON.parse(saved); },
@@ -1,5 +1,8 @@
1
1
  export interface RpcTransport<Request, Result> {
2
- request<T extends Result>(message: Request): Promise<T>;
2
+ /** `timeoutMs` replaces the transport's timeout for this request (a call the player answers in a vmOS surface waits longer). */
3
+ request<T extends Result>(message: Request, options?: {
4
+ timeoutMs?: number;
5
+ }): Promise<T>;
3
6
  destroy(): void;
4
7
  }
5
8
  export interface PortOptions {
package/dist/transport.js CHANGED
@@ -67,7 +67,7 @@ export function createRpcTransport(port, options = {}) {
67
67
  };
68
68
  port.start();
69
69
  return {
70
- request(message) {
70
+ request(message, each = {}) {
71
71
  if (closed)
72
72
  return Promise.reject(closedError());
73
73
  if (pending.size + waiting.length >= (options.maxPending ?? 16))
@@ -78,7 +78,7 @@ export function createRpcTransport(port, options = {}) {
78
78
  const record = options.pace ? { done: null } : undefined;
79
79
  if (record)
80
80
  records.push(record);
81
- const timer = window.setTimeout(() => { pending.delete(id); finish(record); reject(errors ? errors.timeout() : Error(options.jsonBytes === undefined ? "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.")); }, options.timeoutMs ?? 180_000);
81
+ const timer = window.setTimeout(() => { pending.delete(id); finish(record); reject(errors ? errors.timeout() : Error(options.jsonBytes === undefined ? "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.")); }, each.timeoutMs ?? options.timeoutMs ?? 180_000);
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 }) };