@vibechain/os 0.4.1 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +80 -48
- package/README.md +143 -55
- package/SECURITY.md +47 -20
- package/dist/app-client.d.ts +4 -1
- package/dist/app-client.js +15 -4
- package/dist/app-host.d.ts +124 -9
- package/dist/app-host.js +395 -57
- package/dist/app-protocol.d.ts +17 -1
- package/dist/app-protocol.js +12 -0
- package/dist/app-runtime.d.ts +18 -2
- package/dist/app-runtime.js +75 -11
- package/dist/app-wire.d.ts +215 -0
- package/dist/app-wire.js +268 -0
- package/dist/browser.d.ts +3 -0
- package/dist/browser.js +3 -0
- package/dist/bundle.js +6 -6
- package/dist/canvas.d.ts +2 -2
- package/dist/canvas.js +3 -1
- package/dist/capture.d.ts +22 -0
- package/dist/capture.js +99 -0
- package/dist/check.d.ts +12 -0
- package/dist/check.js +167 -0
- package/dist/cli-publish.d.ts +24 -0
- package/dist/cli-publish.js +288 -0
- package/dist/cli-session.d.ts +108 -0
- package/dist/cli-session.js +245 -0
- package/dist/cli.d.ts +10 -0
- package/dist/cli.js +46 -10
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/links.d.ts +15 -0
- package/dist/links.js +41 -0
- package/dist/listing.d.ts +3 -3
- package/dist/listing.js +1 -1
- package/dist/loop.d.ts +18 -2
- package/dist/loop.js +13 -1
- package/dist/manifest.d.ts +90 -4
- package/dist/manifest.js +340 -5
- package/dist/os.d.ts +63 -0
- package/dist/os.js +383 -0
- package/dist/preview-parent.d.ts +42 -0
- package/dist/preview-parent.js +134 -11
- package/dist/preview-ui.js +1 -1
- package/dist/preview.js +25 -7
- package/dist/redact.d.ts +6 -0
- package/dist/redact.js +16 -0
- package/dist/runtime-policy.d.ts +20 -0
- package/dist/runtime-policy.js +45 -0
- package/dist/scaffold.d.ts +13 -2
- package/dist/scaffold.js +95 -31
- package/dist/submit-notice.d.ts +26 -0
- package/dist/submit-notice.js +34 -0
- package/dist/templates/plain/game.js +18 -0
- package/dist/testing.d.ts +68 -0
- package/dist/testing.js +181 -1
- package/dist/transport.d.ts +22 -0
- package/dist/transport.js +71 -19
- package/dist/vibemarket-os.js +1 -0
- package/dist/worker.d.ts +18 -0
- package/dist/worker.js +34 -0
- package/examples/paw-beat/README.md +20 -8
- package/examples/paw-beat/cat.ts +665 -89
- package/examples/paw-beat/game.ts +162 -28
- package/examples/paw-beat/index.html +114 -40
- package/examples/paw-beat/main.ts +264 -149
- package/examples/paw-beat/music.ts +314 -65
- package/examples/paw-beat/stage.ts +560 -0
- package/examples/paw-beat/store/icon.png +0 -0
- package/examples/paw-beat/store/screenshot-1.webp +0 -0
- package/examples/paw-beat/store/screenshot-2.webp +0 -0
- package/examples/paw-beat/vibemarket.json +2 -2
- package/examples/vibexp-app/README.md +7 -7
- package/examples/vibexp-app/index.html +3 -2
- package/examples/vibexp-app/plain/game.ts +20 -0
- package/examples/vibexp-app/plain/index.html +6 -0
- package/examples/vibexp-app/plain/vibemarket.json +17 -0
- package/examples/vibexp-app/src/main.ts +46 -31
- package/examples/vibexp-app/store/icon.png +0 -0
- package/examples/vibexp-app/three/README.md +21 -0
- package/examples/vibexp-app/three/index.html +4 -0
- package/examples/vibexp-app/three/src/main.ts +45 -0
- package/examples/vibexp-app/three/vibemarket.json +19 -0
- package/examples/vibexp-app/vibemarket.json +17 -11
- package/package.json +6 -2
package/dist/preview-ui.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var q="vibemarket.game.v1";var U=["127.0.0.1","localhost"],$=["vibechain.com","www.vibechain.com"];function W({protocol:e,hostname:t,port:n}){return e==="http:"?U.includes(t):e==="https:"&&$.includes(t)&&n===""}function O(e){return W(e.location)?e.top!==e.self?"Third-party apps require a top-level browser host.":["__VM_STEAM__","__TAURI_INTERNALS__","__TAURI__","vibeNative","ReactNativeWebView"].some(t=>t in e)||/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i.test(e.navigator.userAgent)?"Third-party apps are disabled in native shells until their IPC isolation is verified.":null:"Third-party apps are available only on vibechain.com and in the local browser developer preview."}function J(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 P="vibexp";var l=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4});function j(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function M(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function B(e,t){let n=JSON.stringify(e);if(typeof n!="string"||n.length>t||new TextEncoder().encode(n).length>t)throw Error("App message exceeds limit.");return n}function V(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 T=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),I=(e,t)=>{let n=Object.keys(e);return n.length===t.length&&Reflect.ownKeys(e).length===n.length&&n.every(i=>t.includes(i)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,i)??{},"value"))};function G(e){let t=0,n=0,i=(o,m)=>{if(++t>l.checkpointNodes||m>l.checkpointDepth)throw Error("App checkpoint is too complex.");if(o===null||typeof o=="boolean")return;if(typeof o=="number"){if(!Number.isFinite(o))throw Error("Checkpoint numbers must be finite.");return}if(typeof o=="string"){if(o.length>l.stringBytes)throw Error("App checkpoint string is too large.");let s=new TextEncoder().encode(o).byteLength;if(s>l.stringBytes||(n+=s)>l.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(o)){if(o.length>l.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(o).length!==o.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let s=0;s<o.length;s++){let a=Object.getOwnPropertyDescriptor(o,s);if(!a||!("value"in a))throw Error("Sparse/accessor checkpoints are unsupported.");i(a.value,m+1)}return}if(!T(o))throw Error("App checkpoint must contain only JSON values.");let u=Object.keys(o);if(Reflect.ownKeys(o).length!==u.length)throw Error("Checkpoint properties must be enumerable strings.");if(u.length>l.objectKeys)throw Error("App checkpoint has too many keys.");for(let s of u){if(["__proto__","constructor","prototype"].includes(s)||s.length>128)throw Error("Invalid app checkpoint key.");if(n+=new TextEncoder().encode(s).byteLength,n>l.checkpointBytes)throw Error("App checkpoint keys are too large.");let a=Object.getOwnPropertyDescriptor(o,s);if(!a||!("value"in a))throw Error("App checkpoint accessors are unsupported.");i(a.value,m+1)}};i(e,0);let d=JSON.stringify(e);if(new TextEncoder().encode(d).byteLength>l.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return d}function Y(e){return JSON.parse(G(e))}function H(e,t){if(!T(e)||!I(e,["id","session","request"])||e.session!==t||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!T(e.request))throw Error("Invalid app session request.");let n=e.request;if(n.method==="game.finish"&&I(n,["method","score"]))return{id:e.id,request:{method:"game.finish",...J({score:n.score})}};if((n.method==="ui.ready"||n.method==="app.checkpoint.get")&&I(n,["method"]))return{id:e.id,request:{method:n.method}};if(n.method==="app.checkpoint.set"&&I(n,["method","value"]))return{id:e.id,request:{method:n.method,value:Y(n.value)}};throw Error("This app has no permission for that method.")}function _(e){if(!T(e)||!I(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})}function L(e=()=>performance.now()){let t="null",n=!1,i,d,o=!1,m=e();if(!Number.isFinite(m))throw Error("App clock is invalid.");let u=m,s=m,a=0,c=0,g,y,f=r=>{if(n||g)return;g=r,clearTimeout(h),t="null";let w=y;i?.close(),w?.(r)},h=setTimeout(()=>f("App session expired. Reopen the app."),l.sessionMs),p=()=>{let r;try{r=e()}catch{f("App clock changed. Reopen the app.");return}if(!Number.isFinite(r)||r<u){f("App clock changed. Reopen the app.");return}if(u=r,r-m>=l.sessionMs){f("App session expired. Reopen the app.");return}return r};return{attach(r,w,b){if(n||g||!j(w))throw r.close(),Error(g??"App controller is closed.");if(p()===void 0)throw r.close(),Error(g);i?.close();let A=!1,C=0,z=new Set,N=()=>{A||(A=!0,r.onmessage=null,r.onmessageerror=null,r.close(),i===S&&(i=void 0,y=void 0))},k=x=>{A||(N(),b.fault(x))},E=()=>!A&&!n&&b.current(),S={lifecycle(x){E()&&r.postMessage(B({session:w,event:"app.lifecycle",state:_(x)},l.responseBytes))},close:N};return i=S,y=b.fault,r.onmessage=x=>{if(!E()){N();return}let F=p();if(F===void 0)return;if(F-s>=1e3&&(s=F,a=0),++a>l.requestsPerSecond||++c>l.lifetimeRequests||C>=l.inFlight){k("App request limit exceeded.");return}let v;try{v=H(V(x.data,l.requestBytes),w)}catch{k("Invalid or unpermitted app request.");return}if(z.has(v.id)){k("App request was replayed.");return}z.add(v.id),C++,Promise.resolve().then(()=>{if(!E())return;let R;switch(v.request.method){case"ui.ready":b.ready(),R={completed:!0};break;case"game.finish":if(d&&d.score!==v.request.score)throw Error("This game has already finished.");d??=Object.freeze({score:v.request.score}),R={completed:!0};break;case"app.checkpoint.get":R={checkpoint:JSON.parse(t)};break;case"app.checkpoint.set":t=G(v.request.value),R={completed:!0};break}let K={session:w,id:v.id,result:R};E()&&(r.postMessage(B(K,l.responseBytes)),v.request.method==="game.finish"&&d&&!o&&E()&&(o=!0,b.finish?.(d)))}).catch(()=>{A||k("App request could not complete.")}).finally(()=>{C--})},r.onmessageerror=()=>k("App message could not be decoded."),r.start(),S},suspend(){i?.close()},dispose(){n||(n=!0,clearTimeout(h),i?.close(),t="null")}}}function D(e,t){let n=O(window);if(n)throw Error(n);if(!j(t.challenge)||new URL(e.src).hash!==`#${P}=${t.challenge}`)throw Error("Invalid app frame challenge.");let i=!1,d=!1,o=!1,m=0,u,s=_({active:!0,width:0,height:0}),a=()=>{i||(i=!0,clearTimeout(f),e.removeEventListener("load",g),window.removeEventListener("message",y),u?.close())},c=h=>{i||(a(),t.fault(h))},g=()=>{d?c("App navigation ended this session."):d=!0},y=h=>{if(i||o||!t.current()||h.source!==e.contentWindow)return;if(++m>32){c("App connection limit exceeded.");return}if(!d||h.origin!=="null")return;let p;try{p=V(h.data,256)}catch{c("Invalid app connection message.");return}if(!p||typeof p!="object"||Array.isArray(p)||!("channel"in p)||p.channel!==q||!("type"in p)||p.type!=="connect"||!("challenge"in p)||p.challenge!==t.challenge||Object.keys(p).length!==3)return;o=!0,window.removeEventListener("message",y);let r=new MessageChannel,w=M();try{if(u=t.controller.attach(r.port1,w,{current:t.current,ready(){clearTimeout(f),t.ready()},finish:t.finish,fault:c}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:q,challenge:t.challenge,session:w},"*",[r.port2]),u.lifecycle(s)}catch{r.port1.close(),r.port2.close(),c("App connection could not complete.")}},f=setTimeout(()=>c("App took too long to become ready."),15e3);return e.addEventListener("load",g),window.addEventListener("message",y),{resize(h,p){s=_({active:!0,width:Math.min(4096,Math.max(0,Math.floor(h))),height:Math.min(4096,Math.max(0,Math.floor(p)))}),u?.lifecycle(s)},dispose:a}}async function Z(){let e=O(window);if(e)throw Error(e);let t=document.getElementById("surface"),n=document.getElementById("status"),i=document.getElementById("toggle"),d=document.getElementById("reset"),o=document.getElementById("result"),m=document.getElementById("score");if(!t||!n||!o||!m||!(i instanceof HTMLButtonElement)||!(d instanceof HTMLButtonElement))throw Error("Preview controls are missing.");let u=await(await fetch("/preview.json",{credentials:"omit"})).json();if(!u||typeof u!="object"||!("runtime"in u)||typeof u.runtime!="string")throw Error("Invalid preview metadata.");let s=new URL(u.runtime);if(s.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(s.pathname)||s.search||s.hash)throw Error("Invalid preview runtime.");let a=L(),c=null,g=null,y=null,f=!1,h=null,p=()=>{g?.dispose(),g=null,a.suspend(),y?.disconnect(),y=null,c?.remove(),c=null},r=()=>{if(p(),t.hidden=f||document.hidden||h!==null,o.hidden=!0,f||document.hidden){n.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(h){o.hidden=!1,m.textContent=String(h.score),n.textContent="Round complete. No Cash reward for this preview.";return}let w=M(),b=new URL(s);b.hash=`${P}=${w}`,c=document.createElement("iframe"),c.title="VibeMarket OS app",c.sandbox.add("allow-scripts"),c.referrerPolicy="no-referrer",c.src=b.href,t.appendChild(c),g=D(c,{controller:a,challenge:w,current:()=>!f&&!document.hidden,ready:()=>{n.textContent="App ready \xB7 Minimize and restore to check its saved work."},finish:A=>{h=A,d.textContent="Play again",r()},fault:A=>{p(),a.dispose(),a=L(),n.textContent=A}}),y=new ResizeObserver(()=>{c&&g?.resize(c.clientWidth,c.clientHeight)}),y.observe(c),n.textContent="Loading the isolated app\u2026"};i.onclick=()=>{f=!f,i.textContent=f?"Restore":"Minimize",r()},d.onclick=()=>{p(),a.dispose(),a=L(),h=null,f=!1,i.textContent="Minimize",d.textContent="Close / reset",r()},document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",()=>{p(),a.dispose(),document.removeEventListener("visibilitychange",r)},{once:!0}),r()}typeof window<"u"&&typeof document<"u"&&Z().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{Z as startPreviewParent};
|
|
1
|
+
var Me="vibemarket.game.v1";var gt=["127.0.0.1","localhost"],ft=["vibechain.com","www.vibechain.com"],yt=["__VM_STEAM__","__TAURI_INTERNALS__"],Je=["__TAURI__","vibeNative","ReactNativeWebView"],wt=/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i,kt="Third-party apps are available only on vibechain.com and in the local browser developer preview.",bt="Third-party apps require a top-level browser host.",At="Third-party apps are disabled in native shells until their IPC isolation is verified.";function vt({protocol:e,hostname:t,port:r}){return e==="http:"?gt.includes(t)?"local":null:e==="https:"&&ft.includes(t)&&r===""?"production":null}function Ke(e,t){let r=Object.getOwnPropertyDescriptor(e,t);return r&&"value"in r?r.value:void 0}var Et=Object.freeze({windows:1,macos:1,linux:1}),xt=[["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 St(e){return xt.find(([,t])=>t.test(e))?.[0]??null}function Pt(e,t,r){let n=Ke(e,"__VM_STEAM__");if(typeof n!="object"||n===null)return!1;let s=Object.getPrototypeOf(n);if(s!==Object.prototype&&s!==null)return!1;if(Ke(n,"appFrames")===1)return!0;let o=St(t);return o!==null&&r[o]===1}function le(e,t=Et){let r=vt(e.location);if(r===null)return kt;if(e.top!==e.self)return bt;let n=e.navigator.userAgent;return(r==="production"&&Pt(e,n,t)?Je:[...yt,...Je]).some(o=>o in e)||wt.test(n)?At:null}function pe(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 ue="vibexp";var A=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}),Re=1e6,Ue=1101024,_e=e=>typeof e=="string"&&/^[1-9]\d{0,15}$/.test(e),Ce=e=>typeof e=="string"&&e.length<=Re&&/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(e);function Ie(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 K(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 he(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 de=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 Oe(e){let t=0,r=0,n=(o,l)=>{if(++t>A.checkpointNodes||l>A.checkpointDepth)throw Error("App checkpoint is too complex.");if(o===null||typeof o=="boolean")return;if(typeof o=="number"){if(!Number.isFinite(o))throw Error("Checkpoint numbers must be finite.");return}if(typeof o=="string"){if(o.length>A.stringBytes)throw Error("App checkpoint string is too large.");let a=new TextEncoder().encode(o).byteLength;if(a>A.stringBytes||(r+=a)>A.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(o)){if(o.length>A.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(o).length!==o.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let a=0;a<o.length;a++){let p=Object.getOwnPropertyDescriptor(o,a);if(!p||!("value"in p))throw Error("Sparse/accessor checkpoints are unsupported.");n(p.value,l+1)}return}if(!de(o))throw Error("App checkpoint must contain only JSON values.");let y=Object.keys(o);if(Reflect.ownKeys(o).length!==y.length)throw Error("Checkpoint properties must be enumerable strings.");if(y.length>A.objectKeys)throw Error("App checkpoint has too many keys.");for(let a of y){if(["__proto__","constructor","prototype"].includes(a)||a.length>128)throw Error("Invalid app checkpoint key.");if(r+=new TextEncoder().encode(a).byteLength,r>A.checkpointBytes)throw Error("App checkpoint keys are too large.");let p=Object.getOwnPropertyDescriptor(o,a);if(!p||!("value"in p))throw Error("App checkpoint accessors are unsupported.");n(p.value,l+1)}};n(e,0);let s=JSON.stringify(e);if(new TextEncoder().encode(s).byteLength>A.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return s}function Te(e){return JSON.parse(Oe(e))}function qe(e,t){if(!de(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)||!de(e.request))throw Error("Invalid app session request.");let r=e.request;if(r.method==="app.frame"){if(!Z(r,["method","id","image"])||!_e(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(K(e,A.requestBytes),r.method==="game.finish"&&Z(r,["method","score"]))return{id:e.id,request:{method:"game.finish",...pe({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:Te(r.value)}};throw Error("This app has no permission for that method.")}function ee(e){if(!de(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 Gt={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var Ht={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},Jt={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},Mt={packs:3,network:8,packSlugMax:56},Rt=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,V=e=>typeof e=="string"&&e.length<=Mt.packSlugMax&&Rt.test(e);function Ze(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 v=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:Re,captureMs:1200,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),ge=["common","rare","epic","legendary","mythic"],Le=/^[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}),te=1024,ne=Object.freeze({"host.hello":{request:256,response:te,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*te,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*te,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*te,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*te,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"}}),Ye=Object.freeze(Object.keys(ne).filter(e=>e!=="host.hello"&&e!=="card.show")),_t=new TextEncoder,se=e=>_t.encode(e).byteLength,X=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),U=(e,t,r=[])=>Reflect.ownKeys(e).every(s=>typeof s=="string"&&(t.includes(s)||r.includes(s))&&"value"in Object.getOwnPropertyDescriptor(e,s))&&t.every(s=>Object.hasOwn(e,s));var w=class extends Error{code;constructor(t,r){super(r),this.name="AppHostError",this.code=t}};function Ne(e){let t=s=>new w("invalid",s),r=(s,o)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(!Number.isFinite(s))throw t("A save's numbers must be finite.");return}if(typeof s!="object")throw t("A save must contain only JSON values.");if(o>v.saveDepth)throw t(`A save nests at most ${v.saveDepth} levels deep.`);if(Array.isArray(s)){if(Reflect.ownKeys(s).length!==s.length+1)throw t("A save's arrays cannot have extra properties.");for(let l=0;l<s.length;l++){let y=Object.getOwnPropertyDescriptor(s,l);if(!y||!("value"in y))throw t("A save's arrays cannot be sparse or have accessors.");r(y.value,o+1)}return}if(!X(s))throw t("A save must contain only plain objects, arrays and JSON values.");for(let l of Reflect.ownKeys(s)){let y=Object.getOwnPropertyDescriptor(s,l);if(typeof l!="string"||!y||!("value"in y)||!y.enumerable)throw t("A save's properties must be plain enumerable data.");r(y.value,o+1)}}};r(e,1);let n=JSON.stringify(e);if(se(n)>v.saveBytes)throw new w("too-large",`A save is at most ${v.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return n}function Qe(e){let t;try{t=JSON.parse(e)}catch{throw new w("invalid","The saved data is not JSON.")}return Ne(t),t}var I=(e,t,r=0)=>typeof e=="string"&&e.length>=r&&e.length<=t,fe=(e,t,r)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=r,Ct=e=>typeof e=="string"&&ge.includes(e),$e=".bin",ye=(e,t)=>`-/card/${e}/${t}${$e}`,we=e=>`-/cover/${e}${$e}`,It=e=>`-/player/${e}${$e}`;function et(e,t){if(!X(e)||!U(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:r,pack:n,name:s,art:o}=e,l=typeof r=="string"?r.slice(r.indexOf("/")+1):"";if(!V(n)||r!==`${n}/${l}`||!Le.test(l)||!I(s,120)||!Ct(e.rarity)||t&&!fe(e.count,1,1e6)||o!==null&&o!==ye(n,l))throw Error("Invalid card.");return{id:r,pack:n,name:s,rarity:e.rarity,...t?{count:e.count}:{},art:o}}function ze(e){return et(e,!0)}function Ot(e){return et(e,!1)}function tt(e){let{id:t,name:r,creator:n,art:s,total:o}=e;if(!V(t)||!I(r,120,1)||n!==null&&!I(n,64,1)||s!==null&&s!==we(t)||!fe(o,0,1e4))throw Error("Invalid pack.");return{id:t,name:r,creator:n,art:s,total:o}}function rt(e){if(!X(e)||!U(e,["id","name","creator","art","held","total"])||!fe(e.held,0,1e4))throw Error("Invalid pack.");let t=tt(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function nt(e){if(!X(e)||!U(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=tt(e),r=e.cards.map(Ot);if(r.some(n=>n.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:r}}var Tt=/[\u0000-\u001F\u007F-\u009F]/,Xe=e=>typeof e=="string"&&re.handle.test(e);function st(e){if(X(e)&&U(e,["guest"])&&e.guest===!0)return{guest:!0};if(!X(e)||!U(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:r,name:n,picture:s,token:o,expiresAt:l}=e;if(!Xe(t)||!I(n,re.nameMax,1)||Tt.test(n)||r!==void 0&&(!Xe(r)||r===t)||s!==null&&s!==It(t)||"token"in e!="expiresAt"in e||o!==void 0&&(!I(o,re.tokenMax,re.tokenMin)||!re.token.test(o)||!fe(l,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...r===void 0?{}:{username:r},name:n,picture:s,...o===void 0?{}:{token:o,expiresAt:l}}}var Fe=e=>I(e,64,1);var ot=e=>e.includes("/")?"../".repeat(e.split("/").length-1):"./";function it(e){let t=e.method,r=(...n)=>U(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,...pe({score:e.score})}:null;case"app.checkpoint.set":return r("value")?{method:t,value:Te(e.value)}:null;case"host.hello":return r("protocol","sdk")&&e.protocol===2&&I(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")&&_e(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!U(e,["method"],["pack","after"])||"pack"in e&&!I(e.pack,64,1)||"after"in e&&!I(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")&&I(e.pack,64,1)?{method:t,pack:e.pack}:null;case"card.show":return r("pack","card")&&I(e.pack,64,1)&&I(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 Ve(e){return Object.hasOwn(ne,e)?ne[e]:{request:A.requestBytes,response:A.responseBytes,states:"LFB"}}function Lt(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=it(e.request),s=n!==null&&!Object.hasOwn(ne,n.method);if(!n||!r&&!s&&n.method!=="host.hello"&&n.method!=="app.frame")throw Error("This app has no permission for that method.");if(se(JSON.stringify(e.request))>Ve(n.method).request)throw Error("App request exceeds its bound.");return{id:e.id,request:n}}function at(e,t){let r=[];return n=>(r=r.filter(s=>n-s<t),r.length>=e?!1:(r.push(n),!0))}var G={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 ct(e=()=>performance.now(),t={}){let r=t.services,n=r!==void 0,s="null",o=!1,l,y,a=!1,p=e();if(!Number.isFinite(p))throw Error("App clock is invalid.");let d=p,O=p,W=0,N=0,j=p,P,b,R,E=!1,k,_=at(v.requestsPerMinute,6e4),$=n?v.sessionMs:A.sessionMs,z=n?v.lifetimeRequests:A.lifetimeRequests,oe=n?"App session reached its 4-hour limit. Reopen the app to keep playing.":"App session expired. Reopen the app.",g=h=>{if(o||P)return;P=h,clearTimeout(B),clearTimeout(R),s="null";let M=b;l?.close(),M?.(h)},B=setTimeout(()=>g(oe),$),C=()=>{let h;try{h=e()}catch{g("App clock changed. Reopen the app.");return}if(!Number.isFinite(h)||h<d){g("App clock changed. Reopen the app.");return}if(d=h,h-p>=$){g(oe);return}return h},ke=h=>{clearTimeout(R),R=setTimeout(()=>{let M=C();if(M===void 0)return;let F=M-j;if(F<v.idleMs){ke(v.idleMs-F);return}E||(E=!0,t.idle?.())},h)},We=h=>{j=h,E&&(E=!1,ke(v.idleMs))};n&&ke(v.idleMs);let be={protocol:n?2:1,attach(h,M,F){if(o||P||!Ie(M))throw h.close(),Error(P??"App controller is closed.");if(C()===void 0)throw h.close(),Error(P);l?.close();let Y=!1,Ae=0,ie=!1,ve=!1,je=0,Ee=!1,xe=!1,H,Be=new Set,De=new Map,ut=0,Q,q=c=>{let i=Q;Q=void 0,i&&(clearTimeout(i.timer),i.resolve(c))},Se=()=>{q(null),!Y&&(Y=!0,h.onmessage=null,h.onmessageerror=null,h.close(),l===Pe&&(l=void 0,b=void 0,k=void 0))},J=c=>{Y||(Se(),F.fault(c))},T=()=>!Y&&!o&&F.current(),Ge=F.foreground??(()=>!0),ae=(c,i)=>{T()&&h.postMessage(K(c,i))},Pe={lifecycle(c){T()&&h.postMessage(K({session:M,event:"app.lifecycle",state:ee(c)},A.responseBytes))},close:Se,capture(c=v.captureMs){if(q(null),!T())return Promise.resolve(null);let i=String(++ut),f=typeof c=="number"&&Number.isFinite(c)?Math.max(0,c):v.captureMs;return new Promise(u=>{Q={id:i,resolve:u,timer:setTimeout(()=>{Q?.id===i&&q(null)},f)};try{ae({session:M,event:"app.capture",id:i},256)}catch{q(null)}})}};l=Pe,b=F.fault,r&&(k=async()=>{if(!xe||!H||!T())return;let c=await r.cards();if(!T()||!xe||!H||!Fe(c.revision)||c.revision===H.revision)return;let i=new Map(c.cards.map(S=>{let x=ze(S);return[x.id,x]})),f=[...i.values()].filter(S=>JSON.stringify(H.cards.get(S.id))!==JSON.stringify(S)),u=[...H.cards.keys()].filter(S=>!i.has(S)),m={changed:f,removed:u,revision:c.revision};se(JSON.stringify(m))>v.cardsEventBytes&&(m={reset:!0,revision:c.revision}),H={revision:c.revision,cards:i},ae({session:M,event:"app.cards",state:m},v.cardsEventBytes+1024)});let He=c=>{let i=Q?.id===c.id;if(c.image!==null&&!Ce(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}},mt=async(c,i)=>{let f=(u,m)=>{try{return m(u)}catch{throw new w("unavailable",G.unavailable)}};switch(i.method){case"host.hello":return{protocol:2,guest:c.guest,features:[...Ye,...c.showCard?["card.show"]:[]],root:ot(c.entry)};case"ui.progress":if(!ve){if(i.value<0||i.value>1)throw new w("invalid","Progress is a number from 0 to 1.");F.progress?.(i.value)}return{completed:!0};case"app.frame":return He(i);case"app.save.get":{let u=await c.saveGet();return{value:u.value===null?null:f(u.value,Qe),savedAt:u.savedAt===null?null:f(u.savedAt,m=>{if(typeof m!="string"||m.length>30)throw Error();return m})}}case"app.save.set":{let u=Ne(i.value);if(Ee)throw new w("rate-limited","A save is already being written.");Ee=!0;try{let{savedAt:m}=await c.saveSet(u);return{savedAt:f(m,S=>{if(typeof S!="string"||S.length>30)throw Error();return S})}}finally{Ee=!1}}case"cards.list":{if(i.pack!==void 0&&!V(i.pack))throw new w("invalid",G.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",G.after);let m=await c.cards(),S=f(m,L=>{if(!Fe(L.revision)||!Array.isArray(L.cards))throw Error();return L.cards.map(ze)});i.pack===void 0&&u===0&&(H={revision:m.revision,cards:new Map(S.map(L=>[L.id,L]))});let x=i.pack===void 0?S:S.filter(L=>L.pack===i.pack),D=u+v.cardsPage;return{cards:x.slice(u,D),after:D<x.length?String(D):null,revision:m.revision}}case"cards.packs":return{packs:f(await c.packs(),u=>{if(!Array.isArray(u)||u.length>200)throw Error();return u.map(rt)})};case"cards.pack":if(!V(i.pack))throw new w("invalid",G.slug);return{pack:f(await c.pack(i.pack),u=>{let m=nt(u);if(m.id!==i.pack)throw Error();return m})};case"cards.watch":return xe=i.on,{completed:!0};case"pack.show":if(!V(i.pack))throw new w("invalid",G.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(!V(i.pack)||!Le.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 f(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}}};h.onmessage=c=>{if(!T()){Se();return}let i=C();if(i===void 0)return;if(i-O>=1e3&&(O=i,W=0),++W>A.requestsPerSecond||++N>z||Ae>=(ie?v.inFlight:A.inFlight)||n&&!_(i)){J("App request limit exceeded.");return}let f,u;try{n?{id:f,request:u}=Lt(he(c.data,v.messageBytes),M,ie):{id:f,request:u}=qe(he(c.data,Ue),M)}catch{J("Invalid or unpermitted app request.");return}if(n){if(!/^[1-9]\d{0,15}$/.test(f)||Number(f)<=je){J("App request was replayed.");return}je=Number(f)}else{if(Be.has(f)){J("App request was replayed.");return}Be.add(f)}if(u.method==="host.hello"){if(ie){J("App said hello twice.");return}ie=!0}Ae++,n&&We(i);let m=u.method,S=m==="ui.ready"||m==="game.finish"||m==="app.checkpoint.get"||m==="app.checkpoint.set";Promise.resolve().then(()=>{if(T()&&!(!Ge()&&(m==="game.finish"||m==="app.checkpoint.set"))){if(u.method==="app.frame"&&!n){try{let x=He(u);T()&&h.postMessage(K({session:M,id:f,result:x},A.responseBytes))}catch(x){T()&&h.postMessage(K({session:M,id:f,error:x.message,code:"invalid"},A.responseBytes))}return}if(S){let x;switch(u.method){case"ui.ready":ve=!0,F.ready(),x={completed:!0};break;case"game.finish":if(y&&y.score!==u.score){if(!n)throw Error("This game has already finished.");ae({session:M,id:f,error:"This game has already finished.",code:"invalid"},A.responseBytes);return}y??=Object.freeze({score:u.score}),x={completed:!0};break;case"app.checkpoint.get":x={checkpoint:JSON.parse(s)};break;default:s=Oe(u.value),x={completed:!0};break}T()&&(h.postMessage(K({session:M,id:f,result:x},A.responseBytes)),m==="game.finish"&&y&&!a&&T()&&(a=!0,F.finish?.(y)));return}return ht(f,u,m,i)}}).catch(()=>{Y||J("App request could not complete.")}).finally(()=>{Ae--})};let ht=async(c,i,f,u)=>{let m=Ve(f),S;try{let x=ve?Ge()?"F":"B":"L";if(!m.states.includes(x))throw new w("not-permitted",G.states);if(m.rate&&!(i.method==="display.fullscreen"&&!i.on)){let L=m.bucket??f,ce=De.get(L);if(ce||(ce=at(m.rate[0],m.rate[1]),De.set(L,ce)),!ce(u))throw new w("rate-limited",G.rate)}let D=await mt(r,i);if(se(JSON.stringify(D))>m.response)throw new w("unavailable","The answer is larger than this request may return.");S={session:M,id:c,result:D}}catch(x){let D=x instanceof w?x.code:"unavailable";S={session:M,id:c,error:x instanceof w?x.message.slice(0,300):G.unavailable,code:D}}ae(S,v.messageBytes)};return h.onmessageerror=()=>J("App message could not be decoded."),h.start(),Pe},suspend(){l?.close()},dispose(){o||(o=!0,clearTimeout(B),clearTimeout(R),l?.close(),s="null")}};return n&&(be.activity=()=>{let h=C();h!==void 0&&We(h)},be.cardsChanged=async()=>{try{await k?.()}catch{}}),be}function lt(e,t){let r=le(window);if(r)throw Error(r);if(!Ie(t.challenge)||new URL(e.src).hash!==`#${ue}=${t.challenge}`)throw Error("Invalid app frame challenge.");let n=t.controller.protocol===2,s=!1,o=!1,l=!1,y=0,a,p=!1,d=ee({active:!0,width:0,height:0}),O=()=>N("App took too long to become ready."),W=()=>{s||(s=!0,clearTimeout(b),clearTimeout(R),e.removeEventListener("load",j),window.removeEventListener("message",P),a?.close())},N=E=>{s||(W(),t.fault(E))},j=()=>{o?N("App navigation ended this session."):o=!0},P=E=>{if(s||l||!t.current()||E.source!==e.contentWindow)return;if(++y>32){N("App connection limit exceeded.");return}if(!o||E.origin!=="null")return;let k;try{k=he(E.data,256)}catch{N("Invalid app connection message.");return}if(!k||typeof k!="object"||Array.isArray(k)||!("channel"in k)||k.channel!==Me||!("type"in k)||k.type!=="connect"||!("challenge"in k)||k.challenge!==t.challenge||Object.keys(k).length!==3)return;l=!0,window.removeEventListener("message",P);let _=new MessageChannel,$=me();try{if(a=t.controller.attach(_.port1,$,{current:t.current,foreground:t.foreground,ready(){p=!0,clearTimeout(b),clearTimeout(R),t.ready()},finish:t.finish,fault:N,progress(z){p||s||(clearTimeout(b),b=setTimeout(O,v.readyMs),t.progress?.(z))}}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:Me,challenge:t.challenge,session:$,...n?{protocol:2}:{}},"*",[_.port2]),a.lifecycle(d)}catch{_.port1.close(),_.port2.close(),N("App connection could not complete.")}},b=setTimeout(O,v.readyMs),R=n?setTimeout(O,v.progressReadyMs):void 0;return e.addEventListener("load",j),window.addEventListener("message",P),{resize(E,k){d=ee({active:d.active,width:Math.min(4096,Math.max(0,Math.floor(E))),height:Math.min(4096,Math.max(0,Math.floor(k)))}),a?.lifecycle(d)},setActive(E){E!==d.active&&(d=ee({...d,active:E}),a?.lifecycle(d))},dispose:W,capture(E){return s||!a?Promise.resolve(null):a.capture(E)}}}function Nt(e){if(!e||typeof e!="object"||!("runtime"in e)||typeof e.runtime!="string")throw Error("Invalid preview metadata.");let t=e,r=(o,l)=>Array.isArray(o)&&o.length<=8&&o.every(l)?o:null,n=r(t.packs,V),s=r(t.network,o=>typeof o=="string");if(typeof t.name!="string"||typeof t.id!="string"||typeof t.entry!="string"||!Ze(t.entry)||!n||!s||!(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:s}}var pt=e=>e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" "),dt="preview-public";function $t(e,t=Math.random){let r=e.packs.length?e.packs:e.cards==="all"?["preview-pack"]:[],n=a=>({id:a,name:pt(a),creator:"Preview",art:we(a),total:6,cards:Array.from({length:6},(p,d)=>({id:`${a}/c${d+1}`,pack:a,name:`${pt(a)} #${d+1}`,rarity:ge[d%ge.length],art:ye(a,`c${d+1}`)}))}),s=r.map(n),o=[...s,...r.includes(dt)?[]:[n(dt)]],l=new Map(s.flatMap(a=>a.cards.slice(0,3).map(p=>[p.id,1]))),y=1;return{pack(a){let p=o.find(d=>d.id===a);if(!p)throw new w("invalid","There is no such public pack.");return p},card(a,p){let d=this.pack(a).cards.find(O=>O.id===`${a}/${p}`);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:s.flatMap(p=>p.cards.filter(d=>l.has(d.id)).map(d=>({...d,count:l.get(d.id)}))),revision:String(y)}},packs(){return s.map(({cards:a,...p})=>({...p,held:e.cards==="none"?0:a.filter(d=>l.has(d.id)).length}))},pull(){let a=s.flatMap(d=>d.cards);if(!a.length)return null;let p=a[Math.min(a.length-1,Math.floor(t()*a.length))];return l.set(p.id,(l.get(p.id)??0)+1),y++,p.name}}}function zt(e,t){let r=`vmos-preview-save:${e}`,n={value:null,savedAt:null};return{get(){try{let s=t().getItem(r);if(s)return JSON.parse(s)}catch{}return n},set(s){n={value:s,savedAt:new Date().toISOString()};try{t().setItem(r,JSON.stringify(n))}catch{}return{savedAt:n.savedAt}}}}async function Ft(){let e=le(window);if(e)throw Error(e);let t=document.getElementById("surface"),r=document.getElementById("status"),n=document.getElementById("toggle"),s=document.getElementById("reset"),o=document.getElementById("pull"),l=document.getElementById("result"),y=document.getElementById("score");if(!t||!r||!l||!y||!(n instanceof HTMLButtonElement)||!(s instanceof HTMLButtonElement)||!(o instanceof HTMLButtonElement))throw Error("Preview controls are missing.");let a=Nt(await(await fetch("/preview.json",{credentials:"omit"})).json()),p=new URL(a.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 d=$t(a),O=zt(a.id,()=>window.localStorage),W=()=>{if(!navigator.userActivation?.isActive)throw new w("needs-click","That needs a fresh click in the app.")},N={guest:!1,entry:a.entry,async saveGet(){return O.get()},async saveSet(g){return O.set(g)},async cards(){return d.cards()},async packs(){return d.packs()},async pack(g){return d.pack(g)},async showPack(g){d.pack(g),W(),r.textContent=`VibeMarket would open the pack ${g} in its market window here.`},async showCard(g,B){let C=d.card(g,B);W(),r.textContent=`VibeMarket would open the card ${C.name} (${B}) on the pack ${g}'s page here.`},async player(){let g={guest:!1,handle:"preview_player",username:"preview",name:"Preview Player",picture:null};return a.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}W(),await t.requestFullscreen()}},j=()=>ct(void 0,{services:N,idle:()=>{r.textContent="Still playing? VibeMarket asks here after 15 minutes without input."}}),P=j(),b=null,R=null,E=null,k=!1,_=null,$=()=>{R?.dispose(),R=null,P.suspend(),E?.disconnect(),E=null,b?.remove(),b=null},z=()=>{if($(),t.hidden=k||document.hidden||_!==null,l.hidden=!0,k||document.hidden){r.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(_){l.hidden=!1,y.textContent=String(_.score),r.textContent="Round complete. No Cash reward for this preview.";return}let g=me(),B=new URL(p);B.hash=`${ue}=${g}`,b=document.createElement("iframe"),b.title="VibeMarket OS app",b.sandbox.add("allow-scripts","allow-pointer-lock"),b.allow="autoplay; gamepad",b.setAttribute("credentialless",""),b.referrerPolicy="no-referrer",b.src=B.href,t.appendChild(b),R=lt(b,{controller:P,challenge:g,current:()=>!k&&!document.hidden,ready:()=>{r.textContent="App ready \xB7 Minimize and restore to check its saved work."},progress:C=>{r.textContent=`Loading the isolated app\u2026 ${Math.round(C*100)}%`},finish:C=>{_=C,s.textContent="Play again",z()},fault:C=>{$(),P.dispose(),P=j(),r.textContent=C}}),E=new ResizeObserver(()=>{b&&R?.resize(b.clientWidth,b.clientHeight)}),E.observe(b),r.textContent="Loading the isolated app\u2026"};n.onclick=()=>{k=!k,n.textContent=k?"Restore":"Minimize",z()},s.onclick=()=>{$(),P.dispose(),P=j(),_=null,k=!1,n.textContent="Minimize",s.textContent="Close / reset",z()},o.onclick=()=>{let g=d.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 oe=window.setInterval(()=>{navigator.userActivation?.isActive&&P.activity?.()},1e4);document.addEventListener("visibilitychange",z),window.addEventListener("pagehide",()=>{window.clearInterval(oe),$(),P.dispose(),document.removeEventListener("visibilitychange",z)},{once:!0}),z()}typeof window<"u"&&typeof document<"u"&&Ft().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{dt as PREVIEW_PUBLIC_PACK,$t as previewCatalog,Nt as previewMetadata,zt as previewSaves,Ft as startPreviewParent};
|
package/dist/preview.js
CHANGED
|
@@ -2,16 +2,25 @@ import { createServer } from "node:http";
|
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { APP_CATEGORY, APP_FRAGMENT } from "./app-protocol.js";
|
|
4
4
|
import { readBuiltBundle, assetType } from "./bundle.js";
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
import { appRuntimeCsp, appRuntimeHeaders } from "./runtime-policy.js";
|
|
6
|
+
import { CARD_ID } from "./app-wire.js";
|
|
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="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>`;
|
|
7
10
|
const MODULES = new Set(["preview-ui.js"]);
|
|
8
11
|
/** One immutable in-memory bundle. No file serving by arbitrary URL, proxy, credential or write endpoint. */
|
|
9
12
|
export async function startAppPreview(directory, port = 0) {
|
|
10
13
|
if (!Number.isInteger(port) || port < 0 || port > 65535)
|
|
11
14
|
throw Error("Invalid preview port.");
|
|
12
15
|
const bundle = await readBuiltBundle(directory);
|
|
13
|
-
if (bundle.manifest.category !== APP_CATEGORY || bundle.manifest.collectionId !== null || bundle.manifest.permissions.length)
|
|
16
|
+
if (bundle.manifest.schemaVersion !== 3 && (bundle.manifest.category !== APP_CATEGORY || bundle.manifest.collectionId !== null || bundle.manifest.permissions.length))
|
|
14
17
|
throw Error("VibeMarket OS apps must declare category:vibexp-app, collectionId:null and permissions:[]. Market games use their existing host.");
|
|
18
|
+
const manifest = bundle.manifest, network = manifest.schemaVersion === 3 ? manifest.network : [];
|
|
19
|
+
/** What the preview host needs: the app's id, entry and the schema 3 declarations it fakes cards and a player for. */
|
|
20
|
+
const metadata = (runtime) => ({
|
|
21
|
+
name: manifest.name, runtime, fragment: APP_FRAGMENT, id: manifest.id, entry: manifest.entry,
|
|
22
|
+
packs: manifest.schemaVersion === 3 ? manifest.packs : [], cards: manifest.schemaVersion === 3 ? manifest.cards : "none", network,
|
|
23
|
+
});
|
|
15
24
|
const modules = new Map();
|
|
16
25
|
for (const name of MODULES)
|
|
17
26
|
modules.set(name, await readFile(new URL(`./${name}`, import.meta.url)));
|
|
@@ -19,7 +28,8 @@ export async function startAppPreview(directory, port = 0) {
|
|
|
19
28
|
const server = createServer((request, response) => {
|
|
20
29
|
const host = request.headers.host;
|
|
21
30
|
const parentHost = `127.0.0.1:${actualPort}`, runtimeHost = `localhost:${actualPort}`;
|
|
22
|
-
|
|
31
|
+
// the parent keeps fullscreen for itself: an app goes fullscreen only through the host (owner decision O2)
|
|
32
|
+
const base = { "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", "Cache-Control": "no-store", "Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=(), bluetooth=(), clipboard-read=(), clipboard-write=(), fullscreen=(self)" };
|
|
23
33
|
const send = (status, body, headers = {}) => { response.writeHead(status, { ...base, ...headers }); response.end(body); };
|
|
24
34
|
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
25
35
|
send(405, "Method not allowed");
|
|
@@ -36,13 +46,21 @@ export async function startAppPreview(directory, port = 0) {
|
|
|
36
46
|
}
|
|
37
47
|
if (host === runtimeHost) {
|
|
38
48
|
const prefix = `/game-assets/${bundle.digest}/`, name = pathname.startsWith(prefix) ? pathname.slice(prefix.length) : "";
|
|
49
|
+
// the production policy, from the same generator, with this preview's asset prefix and parent
|
|
50
|
+
const headers = appRuntimeHeaders(appRuntimeCsp(`http://${runtimeHost}${prefix}`, network, { frameAncestors: `http://${parentHost}` }));
|
|
51
|
+
// fake card and cover art under the version prefix, as the website serves it (only the `.bin` form): the listing icon stands in for every image
|
|
52
|
+
const art = /^-\/(?:card\/([^/]+)\/([^/]+)|cover\/([^/]+))\.bin$/.exec(name);
|
|
53
|
+
const icon = art && bundle.manifest.schemaVersion !== 1 ? bundle.files[bundle.manifest.store.icon] : undefined;
|
|
54
|
+
if (art && icon && packSlug(art[1] ?? art[3]) && (art[2] === undefined || CARD_ID.test(art[2]))) {
|
|
55
|
+
send(200, request.method === "HEAD" ? "" : icon, { ...headers, "Content-Type": "image/png", "Cache-Control": "public, max-age=600" });
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
39
58
|
const bytes = Object.hasOwn(bundle.files, name) ? bundle.files[name] : undefined;
|
|
40
59
|
if (!bytes || !assetType(name)) {
|
|
41
60
|
send(404, "Not found");
|
|
42
61
|
return;
|
|
43
62
|
}
|
|
44
|
-
|
|
45
|
-
send(200, request.method === "HEAD" ? "" : bytes, { "Content-Type": assetType(name), "Access-Control-Allow-Origin": "*", "Content-Security-Policy": `default-src 'none'; sandbox allow-scripts; base-uri 'none'; object-src 'none'; form-action 'none'; frame-src 'none'; frame-ancestors http://${parentHost}; script-src ${assets} 'wasm-unsafe-eval'; style-src ${assets} 'unsafe-inline'; img-src ${assets} data: blob:; font-src ${assets}; media-src ${assets} blob:; connect-src ${assets}; worker-src 'none'`, "Cache-Control": "public,max-age=31536000,immutable" });
|
|
63
|
+
send(200, request.method === "HEAD" ? "" : bytes, { ...headers, "Content-Type": assetType(name), "Cache-Control": "public,max-age=31536000,immutable" });
|
|
46
64
|
return;
|
|
47
65
|
}
|
|
48
66
|
const parentCsp = `default-src 'none'; base-uri 'none'; object-src 'none'; form-action 'none'; frame-ancestors 'none'; script-src 'self'; style-src 'self'; img-src data:; connect-src 'self'; frame-src http://${runtimeHost}`;
|
|
@@ -55,7 +73,7 @@ export async function startAppPreview(directory, port = 0) {
|
|
|
55
73
|
return;
|
|
56
74
|
}
|
|
57
75
|
if (pathname === "/preview.json") {
|
|
58
|
-
send(200, JSON.stringify(
|
|
76
|
+
send(200, JSON.stringify(metadata(`http://${runtimeHost}/game-assets/${bundle.digest}/${bundle.manifest.entry}`)), { "Content-Type": "application/json" });
|
|
59
77
|
return;
|
|
60
78
|
}
|
|
61
79
|
const name = pathname.startsWith("/sdk/") ? pathname.slice(5) : "";
|
package/dist/redact.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** What the CLI may print about a request or a server's answer (cli-session.ts, cli.ts). No imports, so the dispatcher can use it. */
|
|
2
|
+
/** Masks every CLI token shape and each given secret of at least 8 characters. */
|
|
3
|
+
export declare function redact(text: string, secrets?: readonly string[]): string;
|
|
4
|
+
/** Server or app text as one safe terminal line: control, format and separator characters become spaces (no escape sequences,
|
|
5
|
+
* no bidi tricks), at most `max` characters, any token shape masked. */
|
|
6
|
+
export declare function printable(value: unknown, max?: number): string;
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** What the CLI may print about a request or a server's answer (cli-session.ts, cli.ts). No imports, so the dispatcher can use it. */
|
|
2
|
+
/** Masks every CLI token shape and each given secret of at least 8 characters. */
|
|
3
|
+
export function redact(text, secrets = []) {
|
|
4
|
+
let out = text;
|
|
5
|
+
for (const secret of secrets)
|
|
6
|
+
if (secret.length >= 8)
|
|
7
|
+
out = out.split(secret).join("[redacted]");
|
|
8
|
+
return out.replace(/vmos_cli_[A-Za-z0-9_-]*/g, "vmos_cli_[redacted]");
|
|
9
|
+
}
|
|
10
|
+
/** Server or app text as one safe terminal line: control, format and separator characters become spaces (no escape sequences,
|
|
11
|
+
* no bidi tricks), at most `max` characters, any token shape masked. */
|
|
12
|
+
export function printable(value, max = 500) {
|
|
13
|
+
const text = typeof value === "string" ? value : "";
|
|
14
|
+
const clean = text.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, " ");
|
|
15
|
+
return redact(clean.length > max ? `${clean.slice(0, max - 1)}…` : clean);
|
|
16
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export { networkOrigin } from "./manifest.ts";
|
|
2
|
+
/** The sandbox every runtime response carries. The frame's own sandbox attribute may be narrower. */
|
|
3
|
+
export declare const RUNTIME_SANDBOX = "sandbox allow-scripts allow-pointer-lock";
|
|
4
|
+
/** The Permissions-Policy every runtime response carries. Fullscreen is the host's (owner decision O2), never the frame's. */
|
|
5
|
+
export declare const RUNTIME_PERMISSIONS = "camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=(), bluetooth=(), hid=(), midi=(), clipboard-read=(), clipboard-write=(), display-capture=(), fullscreen=(), publickey-credentials-get=(), idle-detection=()";
|
|
6
|
+
/** Every directive the policy sends, in order. A test enumerates them to prove where declared origins may appear. */
|
|
7
|
+
export declare const RUNTIME_DIRECTIVES: readonly ["default-src", "script-src", "style-src", "img-src", "media-src", "font-src", "connect-src", "worker-src", "child-src", "frame-src", "object-src", "base-uri", "form-action", "frame-ancestors"];
|
|
8
|
+
export interface RuntimeCspOptions {
|
|
9
|
+
/** who may frame the runtime: `'self'` on the website (the default); the preview's parent origin locally */
|
|
10
|
+
frameAncestors?: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The policy of one app version. `prefix` is the absolute URL of the version's folder, ending in `/` (every source names
|
|
14
|
+
* that exact prefix, never 'self': the document's origin is opaque, and 'self' would mean the whole site). `network` is
|
|
15
|
+
* the manifest's normalized origin list; each is re-checked, and one that is not an origin an app may declare, or that
|
|
16
|
+
* is not in its normalized form, throws rather than produce a partial policy.
|
|
17
|
+
*/
|
|
18
|
+
export declare function appRuntimeCsp(prefix: string, network: readonly string[], options?: RuntimeCspOptions): string;
|
|
19
|
+
/** The headers every runtime response carries with its policy. */
|
|
20
|
+
export declare function appRuntimeHeaders(csp: string): Record<string, string>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The app runtime's Content-Security-Policy, one generator for the website (vibechain.com/os/runtime/external/...) and
|
|
3
|
+
* the local preview, so the two cannot drift (VM_OS_APPS_3.md section 12). Declared network origins enter a policy here
|
|
4
|
+
* and nowhere else: `connect-src` gets every origin, `img-src`, `media-src` and `font-src` the `https://` ones, and no
|
|
5
|
+
* other directive ever names one (invariant 11).
|
|
6
|
+
*/
|
|
7
|
+
import { networkOrigin } from "./manifest.js";
|
|
8
|
+
export { networkOrigin } from "./manifest.js";
|
|
9
|
+
/** The sandbox every runtime response carries. The frame's own sandbox attribute may be narrower. */
|
|
10
|
+
export const RUNTIME_SANDBOX = "sandbox allow-scripts allow-pointer-lock";
|
|
11
|
+
/** The Permissions-Policy every runtime response carries. Fullscreen is the host's (owner decision O2), never the frame's. */
|
|
12
|
+
export const RUNTIME_PERMISSIONS = "camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=(), bluetooth=(), hid=(), midi=(), clipboard-read=(), clipboard-write=(), display-capture=(), fullscreen=(), publickey-credentials-get=(), idle-detection=()";
|
|
13
|
+
/** Every directive the policy sends, in order. A test enumerates them to prove where declared origins may appear. */
|
|
14
|
+
export const RUNTIME_DIRECTIVES = ["default-src", "script-src", "style-src", "img-src", "media-src", "font-src", "connect-src", "worker-src", "child-src", "frame-src", "object-src", "base-uri", "form-action", "frame-ancestors"];
|
|
15
|
+
const SOURCE = /^https?:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?\/(?:[A-Za-z0-9_.~-]+\/)*$/;
|
|
16
|
+
/**
|
|
17
|
+
* The policy of one app version. `prefix` is the absolute URL of the version's folder, ending in `/` (every source names
|
|
18
|
+
* that exact prefix, never 'self': the document's origin is opaque, and 'self' would mean the whole site). `network` is
|
|
19
|
+
* the manifest's normalized origin list; each is re-checked, and one that is not an origin an app may declare, or that
|
|
20
|
+
* is not in its normalized form, throws rather than produce a partial policy.
|
|
21
|
+
*/
|
|
22
|
+
export function appRuntimeCsp(prefix, network, options = {}) {
|
|
23
|
+
if (!SOURCE.test(prefix))
|
|
24
|
+
throw Error("The runtime prefix must be an absolute http(s) URL of a folder, ending in /.");
|
|
25
|
+
const ancestors = options.frameAncestors ?? "'self'";
|
|
26
|
+
if (ancestors !== "'self'" && !/^https?:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?$/.test(ancestors))
|
|
27
|
+
throw Error("frame-ancestors must be 'self' or one origin.");
|
|
28
|
+
if (network.length > 8 || new Set(network).size !== network.length || network.some(origin => networkOrigin(origin) !== origin))
|
|
29
|
+
throw Error("The network list is not a normalized list of declared origins.");
|
|
30
|
+
const https = network.filter(origin => origin.startsWith("https://"));
|
|
31
|
+
const list = (...sources) => sources.join(" ");
|
|
32
|
+
return [
|
|
33
|
+
RUNTIME_SANDBOX, "default-src 'none'", `script-src ${prefix} 'wasm-unsafe-eval'`, `style-src ${prefix} 'unsafe-inline'`,
|
|
34
|
+
`img-src ${list(prefix, "data:", "blob:", ...https)}`, `media-src ${list(prefix, "blob:", ...https)}`, `font-src ${list(prefix, ...https)}`, `connect-src ${list(prefix, ...network)}`,
|
|
35
|
+
"worker-src blob:", "child-src blob:", "frame-src 'none'", "object-src 'none'", "base-uri 'none'", "form-action 'none'",
|
|
36
|
+
`frame-ancestors ${ancestors}`,
|
|
37
|
+
].join("; ");
|
|
38
|
+
}
|
|
39
|
+
/** The headers every runtime response carries with its policy. */
|
|
40
|
+
export function appRuntimeHeaders(csp) {
|
|
41
|
+
return {
|
|
42
|
+
"Content-Security-Policy": csp, "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer",
|
|
43
|
+
"Permissions-Policy": RUNTIME_PERMISSIONS, "X-Robots-Tag": "noindex, nofollow", "Access-Control-Allow-Origin": "*",
|
|
44
|
+
};
|
|
45
|
+
}
|
package/dist/scaffold.d.ts
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
export declare const SDK_PACKAGE = "@vibechain/os";
|
|
2
|
-
/**
|
|
3
|
-
export declare
|
|
2
|
+
/** `os init --template`: no build step and nothing to install (plain: exactly the files of the bundle), TypeScript and a 2D canvas (canvas, the default), or Three.js (three). */
|
|
3
|
+
export declare const APP_TEMPLATES: readonly ["plain", "canvas", "three"];
|
|
4
|
+
export type AppTemplate = typeof APP_TEMPLATES[number];
|
|
5
|
+
export declare const appTemplate: (value: unknown) => value is AppTemplate;
|
|
6
|
+
/**
|
|
7
|
+
* Pin registry apps to the installed CLI version; an explicit local archive remains supported. `built` is the package's
|
|
8
|
+
* build output folder, which holds the plain template's `vibemarket-os.js` and `game.js`.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createApp(directory: string, sdkTarball?: string, template?: AppTemplate, built?: URL): Promise<string>;
|
|
11
|
+
/**
|
|
12
|
+
* `os assets`: copies `index.html`, `vibemarket.json`, the listed store images and the whole `public/` folder (its
|
|
13
|
+
* contents land at the root of `dist/`, bounded by the bundle limits) into `dist/`.
|
|
14
|
+
*/
|
|
4
15
|
export declare function stageAppAssets(root: string): Promise<void>;
|
package/dist/scaffold.js
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
import { copyFile, lstat, mkdir, readdir, realpath, writeFile } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
|
-
import { parseManifest } from "./manifest.js";
|
|
4
|
+
import { APP_BUNDLE_LIMITS, assetPath, parseManifest } from "./manifest.js";
|
|
5
5
|
import { readBoundedAsset } from "./bundle.js";
|
|
6
6
|
export const SDK_PACKAGE = "@vibechain/os";
|
|
7
|
-
/**
|
|
8
|
-
export
|
|
7
|
+
/** `os init --template`: no build step and nothing to install (plain: exactly the files of the bundle), TypeScript and a 2D canvas (canvas, the default), or Three.js (three). */
|
|
8
|
+
export const APP_TEMPLATES = ["plain", "canvas", "three"];
|
|
9
|
+
export const appTemplate = (value) => typeof value === "string" && APP_TEMPLATES.includes(value);
|
|
10
|
+
/** Where each template's files live in the package; the plain template's two scripts are build output (`dist/`). */
|
|
11
|
+
const TEMPLATE_DIRECTORY = { canvas: "../examples/vibexp-app/", plain: "../examples/vibexp-app/plain/", three: "../examples/vibexp-app/three/" };
|
|
12
|
+
const STARTER_IMAGES = "../examples/vibexp-app/store/";
|
|
13
|
+
const missing = (error) => error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT";
|
|
14
|
+
/**
|
|
15
|
+
* Pin registry apps to the installed CLI version; an explicit local archive remains supported. `built` is the package's
|
|
16
|
+
* build output folder, which holds the plain template's `vibemarket-os.js` and `game.js`.
|
|
17
|
+
*/
|
|
18
|
+
export async function createApp(directory, sdkTarball, template = "canvas", built = new URL("../dist/", import.meta.url)) {
|
|
9
19
|
let dependency;
|
|
10
20
|
if (sdkTarball !== undefined) {
|
|
11
21
|
const tarball = await realpath(sdkTarball);
|
|
@@ -20,10 +30,18 @@ export async function createApp(directory, sdkTarball) {
|
|
|
20
30
|
throw Error("Installed SDK package metadata is invalid.");
|
|
21
31
|
dependency = input.version;
|
|
22
32
|
}
|
|
23
|
-
const template = fileURLToPath(new URL(
|
|
24
|
-
// The
|
|
25
|
-
const starter = parseManifest(JSON.parse(new TextDecoder().decode(await readBoundedAsset(path.join(
|
|
26
|
-
const
|
|
33
|
+
const source = fileURLToPath(new URL(TEMPLATE_DIRECTORY[template], import.meta.url)), images = fileURLToPath(new URL(STARTER_IMAGES, import.meta.url));
|
|
34
|
+
// The template's own manifest names its store images, so the copy list follows the listing.
|
|
35
|
+
const starter = parseManifest(JSON.parse(new TextDecoder().decode(await readBoundedAsset(path.join(source, "vibemarket.json"), 16 * 1024))));
|
|
36
|
+
const listing = starter.schemaVersion !== 1 ? [starter.store.icon, ...starter.store.screenshots] : [];
|
|
37
|
+
/** [from, to] pairs. The canvas starter carries its own images; plain and three take the starter's two placeholders. */
|
|
38
|
+
const copies = template === "canvas"
|
|
39
|
+
? ["index.html", "vibemarket.json", "README.md", "src/main.ts", ...listing].map(file => [path.join(source, file), file])
|
|
40
|
+
: [
|
|
41
|
+
...(template === "plain" ? ["index.html", "vibemarket.json"] : ["index.html", "vibemarket.json", "README.md", "src/main.ts"]).map(file => [path.join(source, file), file]),
|
|
42
|
+
...listing.map((file, index) => [path.join(images, index === 0 ? "icon.png" : "screenshot-1.png"), file]),
|
|
43
|
+
...(template === "plain" ? [[fileURLToPath(new URL("vibemarket-os.js", built)), "vibemarket-os.js"], [fileURLToPath(new URL("templates/plain/game.js", built)), "game.js"]] : []),
|
|
44
|
+
];
|
|
27
45
|
const requested = path.resolve(directory);
|
|
28
46
|
await mkdir(requested, { recursive: true });
|
|
29
47
|
if ((await lstat(requested)).isSymbolicLink())
|
|
@@ -31,47 +49,93 @@ export async function createApp(directory, sdkTarball) {
|
|
|
31
49
|
const target = await realpath(requested);
|
|
32
50
|
if ((await readdir(target)).length)
|
|
33
51
|
throw Error("The new app directory must be empty.");
|
|
34
|
-
for (const file of
|
|
52
|
+
for (const [from, file] of copies) {
|
|
35
53
|
const destination = path.join(target, file);
|
|
36
54
|
if (path.dirname(destination) !== target)
|
|
37
55
|
await mkdir(path.dirname(destination), { recursive: true });
|
|
38
|
-
await copyFile(
|
|
56
|
+
await copyFile(from, destination);
|
|
39
57
|
}
|
|
58
|
+
if (template === "plain")
|
|
59
|
+
return target;
|
|
40
60
|
await writeFile(path.join(target, "tsconfig.json"), JSON.stringify({ compilerOptions: { target: "ES2022", module: "ESNext", moduleResolution: "Bundler", lib: ["ES2022", "DOM"], strict: true, skipLibCheck: true, noEmit: true }, include: ["src/**/*.ts"] }, null, 2) + "\n", { flag: "wx" });
|
|
41
61
|
await writeFile(path.join(target, "package.json"), JSON.stringify({
|
|
42
62
|
name: "my-vibemarket-app", version: "0.1.0", private: true, type: "module",
|
|
43
63
|
scripts: {
|
|
44
64
|
build: "tsc --noEmit && esbuild src/main.ts --bundle --minify --format=esm --target=es2022 --outfile=dist/main.js && os assets",
|
|
45
|
-
dev: "os preview dist", pack: "os pack dist app.zip",
|
|
65
|
+
check: "os check", dev: "os preview dist", pack: "os pack dist app.zip",
|
|
46
66
|
},
|
|
47
|
-
dependencies: { [SDK_PACKAGE]: dependency },
|
|
48
|
-
devDependencies: { typescript: "5.9.3", esbuild: "0.28.2" },
|
|
67
|
+
dependencies: { [SDK_PACKAGE]: dependency, ...(template === "three" ? { three: "0.175.0" } : {}) },
|
|
68
|
+
devDependencies: { typescript: "5.9.3", esbuild: "0.28.2", ...(template === "three" ? { "@types/three": "0.175.0" } : {}) },
|
|
49
69
|
}, null, 2) + "\n", { flag: "wx" });
|
|
50
70
|
return target;
|
|
51
71
|
}
|
|
72
|
+
/** Copies one file into the output, refusing symlinked folders and files on the way. */
|
|
73
|
+
async function stage(from, output, name) {
|
|
74
|
+
const destination = path.join(output, name), parent = path.dirname(destination);
|
|
75
|
+
if (parent !== output) {
|
|
76
|
+
await mkdir(parent, { recursive: true });
|
|
77
|
+
if (await realpath(parent) !== parent)
|
|
78
|
+
throw Error("App output cannot be a symlink.");
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
if ((await lstat(destination)).isSymbolicLink())
|
|
82
|
+
throw Error("App output cannot contain symlinked files.");
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (!missing(error))
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
await copyFile(from, destination);
|
|
89
|
+
}
|
|
90
|
+
/** Every file under `public/`, relative to it, within the bundle limits; no symlinks or unsafe names. */
|
|
91
|
+
async function publicFiles(root) {
|
|
92
|
+
const files = [];
|
|
93
|
+
let entries = 0, bytes = 0;
|
|
94
|
+
const walk = async (relative) => {
|
|
95
|
+
for (const name of (await readdir(path.join(root, relative))).sort()) {
|
|
96
|
+
const file = relative ? `${relative}/${name}` : name, stat = await lstat(path.join(root, file));
|
|
97
|
+
if (++entries > APP_BUNDLE_LIMITS.files)
|
|
98
|
+
throw Error(`public/ has more than ${APP_BUNDLE_LIMITS.files} files and folders.`);
|
|
99
|
+
if (!assetPath(file))
|
|
100
|
+
throw Error(`public/${file}: use only ASCII letters, digits, _, - and . in file names, not starting with a dot.`);
|
|
101
|
+
if (stat.isSymbolicLink())
|
|
102
|
+
throw Error(`public/${file} is a symlink; copy the file in instead.`);
|
|
103
|
+
if (stat.isDirectory()) {
|
|
104
|
+
await walk(file);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (!stat.isFile() || stat.size > APP_BUNDLE_LIMITS.file || (bytes += stat.size) > APP_BUNDLE_LIMITS.expanded)
|
|
108
|
+
throw Error(`public/${file} is not a file within the bundle limits.`);
|
|
109
|
+
files.push(file);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
await walk("");
|
|
113
|
+
return files;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* `os assets`: copies `index.html`, `vibemarket.json`, the listed store images and the whole `public/` folder (its
|
|
117
|
+
* contents land at the root of `dist/`, bounded by the bundle limits) into `dist/`.
|
|
118
|
+
*/
|
|
52
119
|
export async function stageAppAssets(root) {
|
|
53
120
|
const directory = await realpath(root), output = path.join(directory, "dist");
|
|
54
121
|
const manifest = parseManifest(JSON.parse(new TextDecoder().decode(await readBoundedAsset(path.join(directory, "vibemarket.json"), 16 * 1024))));
|
|
122
|
+
const assets = path.join(directory, "public");
|
|
123
|
+
let extra = [];
|
|
124
|
+
try {
|
|
125
|
+
if ((await lstat(assets)).isDirectory())
|
|
126
|
+
extra = await publicFiles(assets);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (!missing(error))
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
55
132
|
await mkdir(output, { recursive: true });
|
|
56
133
|
if (await realpath(output) !== output)
|
|
57
134
|
throw Error("App output cannot be a symlink.");
|
|
58
|
-
// A schema version 2 listing also needs its store images next to the built app.
|
|
59
|
-
const names = ["index.html", "vibemarket.json", ...(manifest.schemaVersion
|
|
60
|
-
for (const name of names)
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if (await realpath(parent) !== parent)
|
|
65
|
-
throw Error("App output cannot be a symlink.");
|
|
66
|
-
}
|
|
67
|
-
try {
|
|
68
|
-
if ((await lstat(destination)).isSymbolicLink())
|
|
69
|
-
throw Error("App output cannot contain symlinked files.");
|
|
70
|
-
}
|
|
71
|
-
catch (error) {
|
|
72
|
-
if (!(error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT"))
|
|
73
|
-
throw error;
|
|
74
|
-
}
|
|
75
|
-
await copyFile(path.join(directory, name), destination);
|
|
76
|
-
}
|
|
135
|
+
// A schema version 2 or 3 listing also needs its store images next to the built app.
|
|
136
|
+
const names = ["index.html", "vibemarket.json", ...(manifest.schemaVersion !== 1 ? [manifest.store.icon, ...manifest.store.screenshots] : [])];
|
|
137
|
+
for (const name of names)
|
|
138
|
+
await stage(path.join(directory, name), output, name);
|
|
139
|
+
for (const name of extra)
|
|
140
|
+
await stage(path.join(assets, name), output, name);
|
|
77
141
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a developer is told before submitting to VibeStore, and what each refusal means, in one place. The `os submit` command
|
|
3
|
+
* prints it, and the public guide (vibechain.com/os/docs, Review and Publish) renders it from this module, so the two cannot
|
|
4
|
+
* drift. Submitting records no acceptance of these terms; reading them before you submit is on you.
|
|
5
|
+
*/
|
|
6
|
+
export declare const SUBMIT_TERMS: Readonly<{
|
|
7
|
+
label: "Terms";
|
|
8
|
+
url: "https://vibechain.com/terms";
|
|
9
|
+
}>;
|
|
10
|
+
export declare const SUBMIT_PUBLICATION: Readonly<{
|
|
11
|
+
title: "Approval is publication.";
|
|
12
|
+
text: "When a version is approved, its files are copied to public IPFS. Anyone with that copy’s address can fetch it, and removing or revoking the app in VibeStore later does not recall it. Submit only what you are willing to publish permanently, and never put secrets in a bundle.";
|
|
13
|
+
}>;
|
|
14
|
+
/** VibeStore's publisher limits, shared by the Submit tab and `os submit`. */
|
|
15
|
+
export declare const STORE_QUOTAS: Readonly<{
|
|
16
|
+
appsPerPublisher: 5;
|
|
17
|
+
versionsPerApp: 20;
|
|
18
|
+
submissionsPerDay: 10;
|
|
19
|
+
storedBytesPerPublisher: number;
|
|
20
|
+
linkRequestsPerDay: 10;
|
|
21
|
+
}>;
|
|
22
|
+
/** Every refusal code a submission can get, through either front door. */
|
|
23
|
+
export declare const SUBMIT_CODES: readonly ["guest", "too-large", "bad-archive", "bad-manifest", "missing-icon", "bad-icon", "bad-screenshot", "id-taken", "version-exists", "quota", "storage", "pack-not-found", "pack-link-blocked", "link-quota"];
|
|
24
|
+
export type SubmitCode = typeof SUBMIT_CODES[number];
|
|
25
|
+
/** What each refusal means and how to fix it. */
|
|
26
|
+
export declare const SUBMIT_ERRORS: Readonly<Record<SubmitCode, readonly [meaning: string, fix: string]>>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { APP_BUNDLE_LIMITS, APP_STORE_LIMITS } from "./manifest.js";
|
|
2
|
+
/**
|
|
3
|
+
* What a developer is told before submitting to VibeStore, and what each refusal means, in one place. The `os submit` command
|
|
4
|
+
* prints it, and the public guide (vibechain.com/os/docs, Review and Publish) renders it from this module, so the two cannot
|
|
5
|
+
* drift. Submitting records no acceptance of these terms; reading them before you submit is on you.
|
|
6
|
+
*/
|
|
7
|
+
export const SUBMIT_TERMS = Object.freeze({ label: "Terms", url: "https://vibechain.com/terms" });
|
|
8
|
+
export const SUBMIT_PUBLICATION = Object.freeze({
|
|
9
|
+
title: "Approval is publication.",
|
|
10
|
+
text: "When a version is approved, its files are copied to public IPFS. Anyone with that copy’s address can fetch it, and removing or revoking the app in VibeStore later does not recall it. Submit only what you are willing to publish permanently, and never put secrets in a bundle.",
|
|
11
|
+
});
|
|
12
|
+
/** VibeStore's publisher limits, shared by the Submit tab and `os submit`. */
|
|
13
|
+
export const STORE_QUOTAS = Object.freeze({ appsPerPublisher: 5, versionsPerApp: 20, submissionsPerDay: 10, storedBytesPerPublisher: 2 * 1024 * 1024 * 1024, linkRequestsPerDay: 10 });
|
|
14
|
+
/** Every refusal code a submission can get, through either front door. */
|
|
15
|
+
export const SUBMIT_CODES = ["guest", "too-large", "bad-archive", "bad-manifest", "missing-icon", "bad-icon",
|
|
16
|
+
"bad-screenshot", "id-taken", "version-exists", "quota", "storage", "pack-not-found", "pack-link-blocked", "link-quota"];
|
|
17
|
+
const KiB = 1024, MiB = 1024 * 1024;
|
|
18
|
+
/** What each refusal means and how to fix it. */
|
|
19
|
+
export const SUBMIT_ERRORS = Object.freeze({
|
|
20
|
+
guest: ["You are not signed in with a Steam account.", "Sign in with Steam in VibeMarket OS, then submit again."],
|
|
21
|
+
"too-large": [`The ZIP is larger than ${APP_BUNDLE_LIMITS.archive / MiB} MiB.`, "Remove unused files, or compress images and audio."],
|
|
22
|
+
"bad-archive": [`VibeStore cannot read the ZIP, or an entry breaks a file rule: more than ${APP_BUNDLE_LIMITS.files.toLocaleString("en-US")} entries, a file over ${APP_BUNDLE_LIMITS.file / MiB} MiB, more than ${APP_BUNDLE_LIMITS.expanded / MiB} MiB expanded, an unsafe or hidden path, a symlink, encryption, or a file type VibeStore does not serve (such as SVG).`, "The message names the entry. Build the ZIP with os pack."],
|
|
23
|
+
"bad-manifest": ["vibemarket.json is missing from the root of the ZIP, is not valid JSON, is over 16 KiB, breaks a field rule, or names an entry file that is not in the ZIP.", "Fix the field the message names. os pack reports the same problem."],
|
|
24
|
+
"missing-icon": ["The file store.icon names is not in the ZIP.", "Copy the icon into the build. The starter's build does this with os assets."],
|
|
25
|
+
"bad-icon": [`The icon is not a PNG of exactly ${APP_STORE_LIMITS.iconSize} x ${APP_STORE_LIMITS.iconSize} pixels, or it is over ${APP_STORE_LIMITS.iconBytes / KiB} KiB.`, "Export the icon again at that size."],
|
|
26
|
+
"bad-screenshot": [`A screenshot is missing, over ${APP_STORE_LIMITS.screenshotBytes / MiB} MiB, or its contents do not match its extension.`, "The message names the file."],
|
|
27
|
+
"id-taken": ["Another developer already publishes an app with this id.", "Choose a different id in vibemarket.json."],
|
|
28
|
+
"version-exists": ["This version number was already submitted with different files.", "Raise version in vibemarket.json and submit again."],
|
|
29
|
+
quota: [`A publisher limit was reached: ${STORE_QUOTAS.appsPerPublisher} apps, ${STORE_QUOTAS.versionsPerApp} versions per app, ${STORE_QUOTAS.submissionsPerDay} submissions a day (UTC) or ${STORE_QUOTAS.storedBytesPerPublisher / (1024 * MiB)} GiB stored.`, "The message says which limit. The daily limit resets at midnight UTC."],
|
|
30
|
+
storage: ["VibeStore could not store the app. Nothing was submitted.", "Try again in a minute."],
|
|
31
|
+
"pack-not-found": ["A slug in packs names no vmOS pack, or that pack was removed.", "Copy the slug from the pack's vibechain.com/os/pack/<slug> link, or remove it from packs."],
|
|
32
|
+
"pack-link-blocked": ["The creator of a pack in packs declined this app and asked not to be asked again.", "Remove that pack from packs and submit again."],
|
|
33
|
+
"link-quota": [`This account already asked ${STORE_QUOTAS.linkRequestsPerDay} pack creators today (UTC) to link their packs.`, "Submit again after midnight UTC, or remove packs you do not own from packs."],
|
|
34
|
+
});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
(() => {
|
|
3
|
+
VibemarketOS.connect().then(async (os) => {
|
|
4
|
+
const cat = document.getElementById("cat");
|
|
5
|
+
const best = (await os.load())?.best ?? 0;
|
|
6
|
+
let taps = 0;
|
|
7
|
+
cat.onclick = () => {
|
|
8
|
+
taps++;
|
|
9
|
+
cat.textContent = `${taps} (best ${best})`;
|
|
10
|
+
};
|
|
11
|
+
os.ready();
|
|
12
|
+
setTimeout(async () => {
|
|
13
|
+
cat.disabled = true;
|
|
14
|
+
if (taps > best) await os.save({ best: taps });
|
|
15
|
+
await os.finish({ score: taps });
|
|
16
|
+
}, 3e4);
|
|
17
|
+
});
|
|
18
|
+
})();
|